-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerator.py
More file actions
66 lines (51 loc) · 2 KB
/
generator.py
File metadata and controls
66 lines (51 loc) · 2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import os
import qrcode
from PIL import Image, ImageDraw, ImageFont
from paperless_api import get_next_asn
DATA_DIR = os.environ.get("LABEL_PRINTER_DATA_DIR", ".")
SERIAL_FILE = os.path.join(DATA_DIR, "serial_number.txt")
OUTPUT_FILE = os.path.join(DATA_DIR, "serial_qr.png")
FONT_PATH = "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf"
def generate_image_with_optimal_size():
# Primary: read from local file (fast, always increments)
if os.path.exists(SERIAL_FILE):
with open(SERIAL_FILE, "r") as file:
serial_number = int(file.read().strip())
else:
# Fallback: only query Paperless if no local file exists
api_asn = get_next_asn()
if api_asn is not None:
serial_number = api_asn
else:
serial_number = 1
serial_str = f"ASN{serial_number:05}"
qr = qrcode.QRCode(
version=1,
error_correction=qrcode.constants.ERROR_CORRECT_L,
box_size=5,
border=1,
)
qr.add_data(serial_str)
qr.make(fit=True)
img_qr = qr.make_image(fill="black", back_color="white").convert("RGB")
img_qr.thumbnail((200, 200), Image.Resampling.LANCZOS)
font_size = 60
try:
font = ImageFont.truetype(FONT_PATH, font_size)
except IOError:
font = ImageFont.load_default()
total_width = 696
total_height = max(img_qr.height, font.size)
img = Image.new("RGB", (total_width, total_height), "white")
img.paste(img_qr, (0, (total_height - img_qr.height) // 2))
draw = ImageDraw.Draw(img)
text_x = img_qr.width + 100
text_y = (total_height - font.size) // 2
draw.text((text_x, text_y), serial_str, fill="black", font=font)
img.save(OUTPUT_FILE, dpi=(600, 600))
# Save next serial number locally
with open(SERIAL_FILE, "w") as file:
file.write(str(serial_number + 1))
print(f"Image created with serial number: {serial_str}, width: {total_width}px, QR size: {img_qr.size}")
if __name__ == "__main__":
generate_image_with_optimal_size()