sightbox/backend/qrcode/qrcode_generator.py

109 lines
4.0 KiB
Python

"""
qrcode_generator.py — wraps the amzqr (amazing-qr) library to render a plain
QR code PNG for one piece of text (a tool's Serial No). No artistic
background is used — amzqr's `picture` parameter is deliberately left unset;
this only needs a scannable code for a physical label, not decoration.
"""
import io
import tempfile
from pathlib import Path
from PIL import Image, ImageDraw, ImageFont
# Vendored at backend/amzqr/ (not pip-installed) — kept as a top-level
# sibling package, not nested under qrcode/, so its own internal absolute
# imports (`from amzqr.mylibs...`) work completely unmodified.
from amzqr import amzqr
LABEL_FONT_SIZE = 16
LABEL_PADDING = 10
LABEL_LINE_SPACING = 4
class QRGenerationError(Exception):
"""Raised when amzqr rejects the input or fails to render the code."""
def generate_qr_png(data):
"""
Renders `data` as a plain QR code and returns the PNG bytes.
Data flow:
data (str) — the text to encode (e.g. a Serial No like "TOOL-00001")
returns (bytes) — PNG image content
Steps:
1. Render the QR code into a throwaway temp directory (amzqr's API
only writes to disk — there's no in-memory mode)
2. Read the rendered file back into memory before the temp dir is
cleaned up
"""
with tempfile.TemporaryDirectory() as tmp_dir:
try:
# Step 1: version=1 lets amzqr pick the smallest size that fits `data`;
# level="H" is the highest error-correction tier, which matters for a
# label that may get scuffed or dirty on a physical tool over time
_version, _level, qr_path = amzqr.run(
data,
version=1,
level="H",
save_name="qrcode.png",
save_dir=tmp_dir,
)
except ValueError as exc:
raise QRGenerationError(str(exc)) from exc
# Step 2: read the rendered PNG back into memory
return Path(qr_path).read_bytes()
def generate_labeled_qr_png(data, label_lines):
"""
Renders `data` as a QR code with human-readable text printed beneath it
on the same white background — for identifying one label out of a
printed bundle without having to scan each one.
Data flow:
data (str) — the text to encode in the QR code (e.g. a Serial No)
label_lines (list) — one or more lines of text to print beneath the QR
code (e.g. [item_name, serial_no])
returns (bytes) — PNG image content: QR code on top, label text below
Steps:
1. Render the base QR code via generate_qr_png()
2. Measure each label line against a fixed-size font to size a new,
wider/taller canvas that fits the QR code and every line of text
3. Paste the QR code onto a white canvas, centered, and draw each
label line centered beneath it in reading order
4. Encode the composite image back to PNG bytes
"""
qr_image = Image.open(io.BytesIO(generate_qr_png(data))).convert("RGB")
font = ImageFont.load_default(size=LABEL_FONT_SIZE)
line_sizes = []
for line in label_lines:
left, top, right, bottom = font.getbbox(line)
line_sizes.append((right - left, bottom - top))
label_height = (
sum(height for _, height in line_sizes)
+ LABEL_LINE_SPACING * (len(label_lines) - 1)
+ LABEL_PADDING * 2
)
canvas_width = max([qr_image.width] + [width + LABEL_PADDING * 2 for width, _ in line_sizes])
canvas_height = qr_image.height + label_height
canvas = Image.new("RGB", (canvas_width, canvas_height), "white")
canvas.paste(qr_image, ((canvas_width - qr_image.width) // 2, 0))
draw = ImageDraw.Draw(canvas)
y = qr_image.height + LABEL_PADDING
for line, (width, height) in zip(label_lines, line_sizes):
draw.text(((canvas_width - width) // 2, y), line, font=font, fill="black")
y += height + LABEL_LINE_SPACING
output = io.BytesIO()
canvas.save(output, format="PNG")
return output.getvalue()