-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathqr.py
More file actions
223 lines (170 loc) · 8.34 KB
/
Copy pathqr.py
File metadata and controls
223 lines (170 loc) · 8.34 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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
"""QR code generation utilities."""
from __future__ import annotations
import base64
import binascii
import hashlib
import io
from dataclasses import dataclass
from typing import Optional
from .config import AppConfig
@dataclass(slots=True)
class QRCodeManager:
"""Generate QR codes using :mod:`segno` when available."""
config: AppConfig
@staticmethod
def _encode_for_qr(payload: bytes) -> str:
"""Return a text-safe representation of ``payload`` for QR encoding."""
return base64.b64encode(payload).decode("ascii")
@staticmethod
def decode_qr_payload(data: bytes | bytearray | str) -> bytes:
"""Return the original payload extracted from a QR code scan.
The QR libraries used by the application are inconsistent when
returning binary data – some treat the payload as a null-terminated
string which truncates the ciphertext. Encoding the payload with
Base64 before rendering the QR image keeps the contents portable.
The decoder first tries to interpret the scanned data as Base64 and
falls back to returning the raw bytes to remain backwards compatible
with QR codes generated by previous versions of the application.
"""
if isinstance(data, str):
raw = data.encode("utf-8")
else:
raw = bytes(data)
candidate = raw.strip()
try:
return base64.b64decode(candidate, validate=True)
except (binascii.Error, ValueError):
return raw
def is_available(self) -> bool:
try:
import segno # type: ignore # pragma: no cover - optional dependency
except Exception:
return False
return True
def _ensure_bytes(self, payload: bytes | bytearray | str) -> bytes:
"""Return ``payload`` as ``bytes`` for QR operations."""
if isinstance(payload, (bytes, bytearray)):
return bytes(payload)
return payload.encode("utf-8")
def payload_digest(self, data: bytes | bytearray | str) -> str:
"""Return the SHA-256 digest of the QR payload.
The digest allows callers to verify that a decoded payload matches the
original data that was serialised into a QR code. The method returns the
digest as a hexadecimal string to avoid introducing binary data into the
workflow.
"""
return hashlib.sha256(self._ensure_bytes(data)).hexdigest()
def _render_qr_png(self, payload: bytes) -> bytes:
"""Return a PNG image representing ``payload``.
The function attempts to decorate the QR code with a frame that
advertises the repository URL. When Pillow or the extra drawing
primitives are not available the method falls back to ``segno``'s
native ``save`` implementation so the caller still receives a valid
image.
"""
try:
import segno # type: ignore # pragma: no cover - optional dependency
except Exception as exc: # pragma: no cover - depends on environment
raise RuntimeError("QR generation requires segno; install segno[pil]") from exc
qr_data = self._encode_for_qr(payload)
qr = segno.make(qr_data, error=self.config.qr_error_correction)
repo_text = getattr(self.config, "repo_url", "").strip()
if repo_text:
try: # pragma: no cover - depends on optional Pillow runtime
from PIL import Image, ImageDraw, ImageFont
base_img = qr.to_pil(scale=self.config.qr_scale, border=self.config.qr_border)
base_img = base_img.convert("RGB")
font_size = max(14, base_img.size[0] // 18)
try:
font = ImageFont.truetype("DejaVuSans.ttf", font_size)
except Exception:
font = ImageFont.load_default()
drawer = ImageDraw.Draw(base_img)
try:
bbox = drawer.textbbox((0, 0), repo_text, font=font)
text_width = bbox[2] - bbox[0]
text_height = bbox[3] - bbox[1]
except AttributeError: # pragma: no cover - Pillow compatibility
text_width, text_height = drawer.textsize(repo_text, font=font)
extra_vertical = max(0, text_width - base_img.height)
margin = max(
text_height + font_size // 2,
base_img.width // 18,
(extra_vertical // 2) + text_height + 5,
)
canvas_width = base_img.width + 2 * margin
canvas_height = base_img.height + 2 * margin
canvas = Image.new("RGB", (canvas_width, canvas_height), "white")
canvas.paste(base_img, (margin, margin))
draw = ImageDraw.Draw(canvas)
top_x = (canvas_width - text_width) // 2
top_y = (margin - text_height) // 2
draw.text((top_x, top_y), repo_text, fill="black", font=font)
bottom_y = canvas_height - margin + (margin - text_height) // 2
draw.text((top_x, bottom_y), repo_text, fill="black", font=font)
text_image = Image.new("RGBA", (text_width, text_height), (255, 255, 255, 0))
ImageDraw.Draw(text_image).text((0, 0), repo_text, fill="black", font=font)
left_img = text_image.rotate(90, expand=True)
right_img = text_image.rotate(-90, expand=True)
left_x = (margin - left_img.width) // 2
left_y = (canvas_height - left_img.height) // 2
canvas.paste(left_img, (left_x, left_y), left_img)
right_x = canvas_width - margin + (margin - right_img.width) // 2
canvas.paste(right_img, (right_x, left_y), right_img)
buffer = io.BytesIO()
canvas.save(buffer, format="PNG")
buffer.seek(0)
return buffer.read()
except Exception:
pass
buffer = io.BytesIO()
qr.save(buffer, kind="png", scale=self.config.qr_scale, border=self.config.qr_border)
buffer.seek(0)
return buffer.read()
def save_png(self, data: bytes | bytearray | str, path: str) -> str:
"""Persist a QR code representing ``data`` to ``path``.
The method returns the SHA-256 digest of ``data`` so that callers can
display or record the checksum alongside the generated QR image.
"""
payload = self._ensure_bytes(data)
png_bytes = self._render_qr_png(payload)
with open(path, "wb") as handle:
handle.write(png_bytes)
return self.payload_digest(payload)
def to_qpixmap(self, data: bytes | bytearray | str): # pragma: no cover - requires PyQt at runtime
"""Return a ``QPixmap`` representing ``data``.
The method imports :mod:`PyQt5` lazily to keep the module usable in
headless test environments. A :class:`RuntimeError` is raised if the
dependency is missing.
"""
try:
from PyQt5.QtGui import QImage, QPixmap
except Exception as exc: # pragma: no cover - depends on environment
raise RuntimeError("PyQt5 is required to generate a preview pixmap") from exc
payload = self._ensure_bytes(data)
buffer = io.BytesIO(self._render_qr_png(payload))
image = QImage()
if not image.loadFromData(buffer.read()):
raise RuntimeError("Failed to load QR image into QImage")
return QPixmap.fromImage(image)
def read_from_file(self, path: str) -> Optional[bytes]: # pragma: no cover - requires optional deps
"""Decode QR contents using OpenCV and :mod:`pyzbar` when available."""
try:
import cv2 # type: ignore
from pyzbar import pyzbar # type: ignore
except Exception:
return None
image = cv2.imread(path)
if image is None:
return None
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
for processed in (
gray,
cv2.GaussianBlur(gray, (5, 5), 0),
cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1],
):
decoded = pyzbar.decode(processed)
if decoded:
return self.decode_qr_payload(decoded[0].data)
return None
__all__ = ["QRCodeManager"]