qrpack 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- qrpack/__init__.py +35 -0
- qrpack/calibrate.py +208 -0
- qrpack/cli.py +243 -0
- qrpack/core.py +274 -0
- qrpack/scan.py +135 -0
- qrpack/sheet.py +247 -0
- qrpack-0.1.0.dist-info/METADATA +667 -0
- qrpack-0.1.0.dist-info/RECORD +12 -0
- qrpack-0.1.0.dist-info/WHEEL +5 -0
- qrpack-0.1.0.dist-info/entry_points.txt +2 -0
- qrpack-0.1.0.dist-info/licenses/LICENSE +21 -0
- qrpack-0.1.0.dist-info/top_level.txt +1 -0
qrpack/__init__.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
"""qrpack — pack a folder into printable QR codes and restore it from a photo.
|
|
2
|
+
|
|
3
|
+
Modules:
|
|
4
|
+
core.py archiving, framing, checksums
|
|
5
|
+
sheet.py layout and printable output
|
|
6
|
+
scan.py decoding and recovery
|
|
7
|
+
calibrate.py measuring the resolution limit of a print-and-scan chain
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
__version__ = "0.1.0"
|
|
11
|
+
|
|
12
|
+
from .core import (
|
|
13
|
+
DigestMismatchError,
|
|
14
|
+
Header,
|
|
15
|
+
chunk,
|
|
16
|
+
compress,
|
|
17
|
+
decompress,
|
|
18
|
+
pack_bytes,
|
|
19
|
+
sha256_digest,
|
|
20
|
+
unpack_bytes,
|
|
21
|
+
verify_digest,
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
__all__ = [
|
|
25
|
+
"__version__",
|
|
26
|
+
"pack_bytes",
|
|
27
|
+
"unpack_bytes",
|
|
28
|
+
"compress",
|
|
29
|
+
"decompress",
|
|
30
|
+
"Header",
|
|
31
|
+
"chunk",
|
|
32
|
+
"sha256_digest",
|
|
33
|
+
"DigestMismatchError",
|
|
34
|
+
"verify_digest",
|
|
35
|
+
]
|
qrpack/calibrate.py
ADDED
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
"""Calibration: what ECC levels cost, and what survives printing (issues #41, #42).
|
|
2
|
+
|
|
3
|
+
Raising the ECC level lets a code survive more damage, but it also needs more
|
|
4
|
+
modules, so each module gets smaller in the same printed square. Decoders start
|
|
5
|
+
failing at roughly 3 px/module, so the table `ecc_cost` returns says which level
|
|
6
|
+
is usable on a given printer, not in theory. `survives` goes one step further:
|
|
7
|
+
it simulates print + photo and asks whether the code still decodes.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import io
|
|
13
|
+
import random
|
|
14
|
+
import tempfile
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
|
|
17
|
+
import segno
|
|
18
|
+
from PIL import Image, ImageFilter
|
|
19
|
+
|
|
20
|
+
from qrpack.core import chunk
|
|
21
|
+
from qrpack.scan import decode_one
|
|
22
|
+
from qrpack.sheet import ECC_LEVELS, QUIET_ZONE, _check_ecc, _validated_qr, render_codes
|
|
23
|
+
|
|
24
|
+
# 40 mm cell at 300 DPI -- what we actually print.
|
|
25
|
+
PRINTED_PX = 472
|
|
26
|
+
|
|
27
|
+
# Raw bytes of the blob per code, the ladder `sweep` climbs by default.
|
|
28
|
+
LADDER = (100, 300, 600, 900, 1200, 1500)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def ecc_cost(payload: str, printed_px: int = PRINTED_PX) -> list[dict]:
|
|
32
|
+
"""One row per ECC level: version, modules, px/module.
|
|
33
|
+
|
|
34
|
+
`modules` counts the quiet zone too, because that is part of the printed
|
|
35
|
+
square. `px_per_module` is `printed_px / modules`.
|
|
36
|
+
|
|
37
|
+
Raises ValueError for an empty payload or a non-positive `printed_px`,
|
|
38
|
+
TypeError for a non-string payload or non-integer `printed_px`, and
|
|
39
|
+
segno.DataOverflowError if the payload does not fit at some level.
|
|
40
|
+
"""
|
|
41
|
+
if isinstance(printed_px, bool) or not isinstance(printed_px, int):
|
|
42
|
+
raise TypeError("printed_px must be an integer")
|
|
43
|
+
if printed_px <= 0:
|
|
44
|
+
raise ValueError("printed_px must be positive")
|
|
45
|
+
rows = []
|
|
46
|
+
for ecc in ECC_LEVELS:
|
|
47
|
+
qr = _validated_qr(payload, ecc)
|
|
48
|
+
modules = qr.symbol_size(scale=1, border=QUIET_ZONE)[0]
|
|
49
|
+
rows.append(
|
|
50
|
+
{
|
|
51
|
+
"ecc": ecc,
|
|
52
|
+
"version": qr.version,
|
|
53
|
+
"modules": modules,
|
|
54
|
+
"px_per_module": printed_px / modules,
|
|
55
|
+
}
|
|
56
|
+
)
|
|
57
|
+
return rows
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def survives(
|
|
61
|
+
payload: str,
|
|
62
|
+
printed_px: int,
|
|
63
|
+
blur: int = 0,
|
|
64
|
+
jpeg_quality: int = 100,
|
|
65
|
+
ecc: str = "m",
|
|
66
|
+
) -> bool:
|
|
67
|
+
"""Render one code, simulate print + photo, and report whether it decodes.
|
|
68
|
+
|
|
69
|
+
The code is rendered with `sheet.render_codes`, then resized to a square of
|
|
70
|
+
`printed_px` pixels. That is the point of the function: on paper every cell
|
|
71
|
+
occupies the same physical square, so a denser symbol gets fewer pixels per
|
|
72
|
+
module. Scaling every code by the same *fraction* instead would make big
|
|
73
|
+
codes look artificially good. `blur` is a Gaussian radius in pixels and
|
|
74
|
+
`jpeg_quality` below 100 adds a JPEG round trip (100 means none).
|
|
75
|
+
|
|
76
|
+
True only if `scan.decode_one` returns exactly the original payload.
|
|
77
|
+
|
|
78
|
+
Raises TypeError/ValueError for bad arguments and segno.DataOverflowError
|
|
79
|
+
if the payload does not fit in any QR code: an unencodable payload is a
|
|
80
|
+
caller error, not a code that failed to survive.
|
|
81
|
+
"""
|
|
82
|
+
_check_args(printed_px, blur, jpeg_quality, ecc)
|
|
83
|
+
cell = render_codes([payload], ecc=ecc)[0]
|
|
84
|
+
image = cell.resize((printed_px, printed_px), Image.Resampling.BOX)
|
|
85
|
+
if blur:
|
|
86
|
+
image = image.filter(ImageFilter.GaussianBlur(blur))
|
|
87
|
+
if jpeg_quality < 100:
|
|
88
|
+
buffer = io.BytesIO()
|
|
89
|
+
image.save(buffer, format="JPEG", quality=jpeg_quality)
|
|
90
|
+
buffer.seek(0)
|
|
91
|
+
with Image.open(buffer) as jpeg:
|
|
92
|
+
image = jpeg.convert("RGB")
|
|
93
|
+
with tempfile.TemporaryDirectory() as directory:
|
|
94
|
+
path = Path(directory) / "photo.png"
|
|
95
|
+
image.save(path)
|
|
96
|
+
try:
|
|
97
|
+
return decode_one(path) == payload
|
|
98
|
+
except ValueError:
|
|
99
|
+
return False
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def _check_int(name: str, value: object) -> None:
|
|
103
|
+
if isinstance(value, bool) or not isinstance(value, int):
|
|
104
|
+
raise TypeError(f"{name} must be an integer")
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _check_args(printed_px: int, blur: int, jpeg_quality: int, ecc: str) -> None:
|
|
108
|
+
_check_int("printed_px", printed_px)
|
|
109
|
+
if printed_px <= 0:
|
|
110
|
+
raise ValueError("printed_px must be positive")
|
|
111
|
+
_check_int("blur", blur)
|
|
112
|
+
if blur < 0:
|
|
113
|
+
raise ValueError("blur must not be negative")
|
|
114
|
+
_check_int("jpeg_quality", jpeg_quality)
|
|
115
|
+
if not 1 <= jpeg_quality <= 100:
|
|
116
|
+
raise ValueError("jpeg_quality must be between 1 and 100")
|
|
117
|
+
_check_ecc(ecc)
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def _payload_of(chunk_bytes: int) -> str:
|
|
121
|
+
"""A deterministic, realistic payload line carrying `chunk_bytes` bytes."""
|
|
122
|
+
raw = random.Random(0).randbytes(chunk_bytes)
|
|
123
|
+
return chunk(raw, chunk_bytes)[0].decode("ascii")
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def sweep(
|
|
127
|
+
chunk_sizes=LADDER,
|
|
128
|
+
printed_px: int = PRINTED_PX,
|
|
129
|
+
blur: int = 0,
|
|
130
|
+
jpeg_quality: int = 100,
|
|
131
|
+
ecc: str = "m",
|
|
132
|
+
) -> list[dict]:
|
|
133
|
+
"""One pass/fail row per payload size, every code at the same printed size.
|
|
134
|
+
|
|
135
|
+
`chunk_sizes` counts raw blob bytes per code, like `--chunk`. A row has
|
|
136
|
+
chunk_bytes, payload_chars, fits, version, modules, px_per_module and
|
|
137
|
+
survives. A size too big for any QR code at this `ecc` gets fits=False,
|
|
138
|
+
survives=False and None for the rest, so a sweep can run past the limit.
|
|
139
|
+
"""
|
|
140
|
+
_check_args(printed_px, blur, jpeg_quality, ecc)
|
|
141
|
+
sizes = tuple(chunk_sizes)
|
|
142
|
+
if not sizes:
|
|
143
|
+
raise ValueError("chunk_sizes must not be empty")
|
|
144
|
+
for size in sizes:
|
|
145
|
+
_check_int("chunk size", size)
|
|
146
|
+
if size <= 0:
|
|
147
|
+
raise ValueError("chunk size must be positive")
|
|
148
|
+
|
|
149
|
+
rows = []
|
|
150
|
+
for size in sizes:
|
|
151
|
+
payload = _payload_of(size)
|
|
152
|
+
try:
|
|
153
|
+
qr = _validated_qr(payload, ecc)
|
|
154
|
+
except segno.DataOverflowError:
|
|
155
|
+
rows.append(
|
|
156
|
+
{
|
|
157
|
+
"chunk_bytes": size,
|
|
158
|
+
"payload_chars": len(payload),
|
|
159
|
+
"fits": False,
|
|
160
|
+
"version": None,
|
|
161
|
+
"modules": None,
|
|
162
|
+
"px_per_module": None,
|
|
163
|
+
"survives": False,
|
|
164
|
+
}
|
|
165
|
+
)
|
|
166
|
+
continue
|
|
167
|
+
modules = qr.symbol_size(scale=1, border=QUIET_ZONE)[0]
|
|
168
|
+
rows.append(
|
|
169
|
+
{
|
|
170
|
+
"chunk_bytes": size,
|
|
171
|
+
"payload_chars": len(payload),
|
|
172
|
+
"fits": True,
|
|
173
|
+
"version": qr.version,
|
|
174
|
+
"modules": modules,
|
|
175
|
+
"px_per_module": printed_px / modules,
|
|
176
|
+
"survives": survives(payload, printed_px, blur, jpeg_quality, ecc),
|
|
177
|
+
}
|
|
178
|
+
)
|
|
179
|
+
return rows
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def recommend(rows: list[dict]) -> int | None:
|
|
183
|
+
"""Largest chunk size that survived, with every smaller size surviving too.
|
|
184
|
+
|
|
185
|
+
Stops at the first failure when walking up the ladder, so a lucky pass above
|
|
186
|
+
a failure is never recommended. Returns None when even the smallest failed.
|
|
187
|
+
"""
|
|
188
|
+
best = None
|
|
189
|
+
for row in sorted(rows, key=lambda r: r["chunk_bytes"]):
|
|
190
|
+
if not row["survives"]:
|
|
191
|
+
break
|
|
192
|
+
best = row["chunk_bytes"]
|
|
193
|
+
return best
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def format_table(rows: list[dict]) -> str:
|
|
197
|
+
"""The table `qrpack calibrate` prints, one line per payload size."""
|
|
198
|
+
lines = ["payload ver modules px/module decodes"]
|
|
199
|
+
for row in rows:
|
|
200
|
+
if not row["fits"]:
|
|
201
|
+
lines.append(f"{row['chunk_bytes']:>6} B {'-':>3} {'-':>7} {'-':>9} no fit")
|
|
202
|
+
continue
|
|
203
|
+
verdict = "PASS" if row["survives"] else "fail"
|
|
204
|
+
lines.append(
|
|
205
|
+
f"{row['chunk_bytes']:>6} B v{row['version']:<2} {row['modules']:>7} "
|
|
206
|
+
f"{row['px_per_module']:>9.2f} {verdict}"
|
|
207
|
+
)
|
|
208
|
+
return "\n".join(lines)
|
qrpack/cli.py
ADDED
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
"""Command-line entry point: ``qrpack estimate | pack | restore | calibrate``.
|
|
2
|
+
|
|
3
|
+
Owned by @dreamboy17. Each module owner adds or wires their own subcommand;
|
|
4
|
+
keep edits to your subcommand's ``_add_*`` function and its ``_cmd_*`` handler.
|
|
5
|
+
|
|
6
|
+
Day 1: the interface exists and every subcommand parses its arguments.
|
|
7
|
+
Day 2: the handlers are wired to core / sheet / scan.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import argparse
|
|
13
|
+
import io
|
|
14
|
+
import sys
|
|
15
|
+
import tarfile
|
|
16
|
+
from collections.abc import Sequence
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
|
|
19
|
+
from . import __version__
|
|
20
|
+
from .core import chunk, compress, decompress, pack_bytes, unpack_bytes, verify_digest
|
|
21
|
+
from .calibrate import LADDER, PRINTED_PX, format_table, recommend, sweep
|
|
22
|
+
from .scan import reassemble, scan_image
|
|
23
|
+
from .sheet import make_sheet
|
|
24
|
+
|
|
25
|
+
# Bytes of compressed data per QR code. In the prototype measurements quoted in
|
|
26
|
+
# the project proposal, 1,200 B chunks decoded 5 of 5 cells where version-40
|
|
27
|
+
# symbols decoded 0 of 2. A starting point only: `qrpack calibrate` is meant
|
|
28
|
+
# to measure the right value for each printer and camera.
|
|
29
|
+
DEFAULT_CHUNK = 1200
|
|
30
|
+
# A full 1,200-byte chunk makes a QR symbol too wide for four columns on A4
|
|
31
|
+
# (make_sheet refuses rather than shrink it); three fit, 12 codes per page.
|
|
32
|
+
DEFAULT_COLS = 3
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _fail(name: str, message: str) -> int:
|
|
36
|
+
print(f"qrpack {name}: {message}", file=sys.stderr)
|
|
37
|
+
return 1
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _cmd_estimate(args: argparse.Namespace) -> int:
|
|
41
|
+
if not args.src.exists():
|
|
42
|
+
return _fail("estimate", f"{args.src} does not exist")
|
|
43
|
+
if args.chunk <= 0:
|
|
44
|
+
return _fail("estimate", f"--chunk must be positive, got {args.chunk}")
|
|
45
|
+
raw = pack_bytes(args.src)
|
|
46
|
+
compressed = compress(raw)
|
|
47
|
+
payloads = chunk(compressed, args.chunk)
|
|
48
|
+
encoded = sum(len(p) for p in payloads)
|
|
49
|
+
print(
|
|
50
|
+
f"{len(raw)} B raw -> {len(compressed)} B compressed -> "
|
|
51
|
+
f"{encoded} chars encoded -> {len(payloads)} codes"
|
|
52
|
+
)
|
|
53
|
+
return 0
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _cmd_pack(args: argparse.Namespace) -> int:
|
|
57
|
+
if not args.src.exists():
|
|
58
|
+
return _fail("pack", f"{args.src} does not exist")
|
|
59
|
+
if args.chunk <= 0:
|
|
60
|
+
return _fail("pack", f"--chunk must be positive, got {args.chunk}")
|
|
61
|
+
raw = pack_bytes(args.src)
|
|
62
|
+
compressed = compress(raw)
|
|
63
|
+
# chunk() returns bytes; make_sheet() takes the payloads as text.
|
|
64
|
+
payloads = [p.decode("ascii") for p in chunk(compressed, args.chunk)]
|
|
65
|
+
title = f"qrpack backup of {args.src.resolve().name}"
|
|
66
|
+
try:
|
|
67
|
+
pages, codes = make_sheet(payloads, title, args.output, cols=args.cols)
|
|
68
|
+
except (TypeError, ValueError) as exc:
|
|
69
|
+
# make_sheet explains what is wrong (too many columns, bad extension);
|
|
70
|
+
# show that message instead of a traceback.
|
|
71
|
+
return _fail("pack", str(exc))
|
|
72
|
+
print(f"{codes} codes on {pages} page(s) -> {args.output}")
|
|
73
|
+
return 0
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _cmd_restore(args: argparse.Namespace) -> int:
|
|
77
|
+
for image in args.images:
|
|
78
|
+
if not image.exists():
|
|
79
|
+
return _fail("restore", f"{image} does not exist")
|
|
80
|
+
texts = []
|
|
81
|
+
for image in args.images:
|
|
82
|
+
texts.extend(scan_image(image, args.cols))
|
|
83
|
+
if not texts:
|
|
84
|
+
return _fail("restore", "no qrpack codes found in the image(s)")
|
|
85
|
+
try:
|
|
86
|
+
blob, digest, missing = reassemble(texts)
|
|
87
|
+
except ValueError as exc:
|
|
88
|
+
return _fail("restore", str(exc))
|
|
89
|
+
if missing:
|
|
90
|
+
# Name the lost parts instead of writing a corrupt archive.
|
|
91
|
+
return _fail("restore", f"missing parts {missing}; rescan them and pass every sheet")
|
|
92
|
+
try:
|
|
93
|
+
verify_digest(blob, digest)
|
|
94
|
+
except ValueError as exc:
|
|
95
|
+
return _fail("restore", str(exc))
|
|
96
|
+
raw = decompress(blob)
|
|
97
|
+
args.output.mkdir(parents=True, exist_ok=True)
|
|
98
|
+
if not tarfile.is_tarfile(io.BytesIO(raw)):
|
|
99
|
+
# pack_bytes stores a single file as its raw bytes, without a name.
|
|
100
|
+
target = args.output / "restored.bin"
|
|
101
|
+
target.write_bytes(raw)
|
|
102
|
+
print(f"restored 1 file ({len(raw)} B) -> {target}")
|
|
103
|
+
return 0
|
|
104
|
+
try:
|
|
105
|
+
names = unpack_bytes(raw, args.output)
|
|
106
|
+
except ValueError as exc:
|
|
107
|
+
return _fail("restore", str(exc))
|
|
108
|
+
print(f"restored {len(names)} file(s) -> {args.output}")
|
|
109
|
+
return 0
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def _cmd_calibrate(args: argparse.Namespace) -> int:
|
|
113
|
+
try:
|
|
114
|
+
rows = sweep(
|
|
115
|
+
LADDER,
|
|
116
|
+
printed_px=args.printed_px,
|
|
117
|
+
blur=args.blur,
|
|
118
|
+
jpeg_quality=args.jpeg_quality,
|
|
119
|
+
ecc=args.ecc,
|
|
120
|
+
)
|
|
121
|
+
except (TypeError, ValueError) as exc:
|
|
122
|
+
return _fail("calibrate", str(exc))
|
|
123
|
+
print(format_table(rows))
|
|
124
|
+
best = recommend(rows)
|
|
125
|
+
if best is None:
|
|
126
|
+
return _fail("calibrate", "no payload size decoded; raise --printed-px or lower --blur")
|
|
127
|
+
print()
|
|
128
|
+
print(f"recommended --chunk : {best} B")
|
|
129
|
+
return 0
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _add_chunk_option(p: argparse.ArgumentParser) -> None:
|
|
133
|
+
p.add_argument(
|
|
134
|
+
"--chunk",
|
|
135
|
+
type=int,
|
|
136
|
+
default=DEFAULT_CHUNK,
|
|
137
|
+
metavar="BYTES",
|
|
138
|
+
help=f"compressed bytes per QR code (default {DEFAULT_CHUNK})",
|
|
139
|
+
)
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def _add_estimate(sub: argparse._SubParsersAction) -> None:
|
|
143
|
+
p = sub.add_parser(
|
|
144
|
+
"estimate",
|
|
145
|
+
help="report how many codes and sheets SRC would take",
|
|
146
|
+
description="Report raw -> compressed -> encoded size and the number of codes.",
|
|
147
|
+
)
|
|
148
|
+
p.add_argument("src", type=Path, metavar="SRC", help="file or folder to measure")
|
|
149
|
+
_add_chunk_option(p)
|
|
150
|
+
p.set_defaults(func=_cmd_estimate)
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def _add_pack(sub: argparse._SubParsersAction) -> None:
|
|
154
|
+
p = sub.add_parser(
|
|
155
|
+
"pack",
|
|
156
|
+
help="turn a file or folder into a printable sheet of QR codes",
|
|
157
|
+
description="Turn a file or folder into a printable sheet of QR codes.",
|
|
158
|
+
)
|
|
159
|
+
p.add_argument("src", type=Path, metavar="SRC", help="file or folder to pack")
|
|
160
|
+
p.add_argument(
|
|
161
|
+
"-o", "--output", type=Path, required=True, metavar="OUT",
|
|
162
|
+
help="output image, e.g. sheet.png",
|
|
163
|
+
)
|
|
164
|
+
_add_chunk_option(p)
|
|
165
|
+
p.add_argument(
|
|
166
|
+
"--cols", type=int, default=DEFAULT_COLS,
|
|
167
|
+
help=f"codes per row on the sheet (default {DEFAULT_COLS})",
|
|
168
|
+
)
|
|
169
|
+
p.set_defaults(func=_cmd_pack)
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def _add_restore(sub: argparse._SubParsersAction) -> None:
|
|
173
|
+
p = sub.add_parser(
|
|
174
|
+
"restore",
|
|
175
|
+
help="rebuild the original files from photos of a sheet",
|
|
176
|
+
description="Rebuild the original files from one or more sheet images.",
|
|
177
|
+
)
|
|
178
|
+
p.add_argument(
|
|
179
|
+
"images", type=Path, nargs="+", metavar="IMG",
|
|
180
|
+
help="sheet image(s); several sheets may be given in any order",
|
|
181
|
+
)
|
|
182
|
+
p.add_argument(
|
|
183
|
+
"-o", "--output", type=Path, required=True, metavar="DIR",
|
|
184
|
+
help="directory to restore into",
|
|
185
|
+
)
|
|
186
|
+
p.add_argument(
|
|
187
|
+
"--cols", type=int, default=DEFAULT_COLS,
|
|
188
|
+
help=f"codes per row the sheet was packed with (default {DEFAULT_COLS})",
|
|
189
|
+
)
|
|
190
|
+
p.set_defaults(func=_cmd_restore)
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def _add_calibrate(sub: argparse._SubParsersAction) -> None:
|
|
194
|
+
p = sub.add_parser(
|
|
195
|
+
"calibrate",
|
|
196
|
+
help="measure which chunk size survives print and photo, and recommend one",
|
|
197
|
+
description="Render a ladder of payload sizes at one printed size, degrade "
|
|
198
|
+
"them, and report which still decode.",
|
|
199
|
+
)
|
|
200
|
+
p.add_argument(
|
|
201
|
+
"--ecc", default="m", metavar="LEVEL",
|
|
202
|
+
help="error-correction level: l, m, q or h (default m)",
|
|
203
|
+
)
|
|
204
|
+
p.add_argument(
|
|
205
|
+
"--printed-px", type=int, default=PRINTED_PX, metavar="PX",
|
|
206
|
+
help=f"printed square size in pixels (default {PRINTED_PX}: 40 mm at 300 DPI)",
|
|
207
|
+
)
|
|
208
|
+
p.add_argument(
|
|
209
|
+
"--blur", type=int, default=0, metavar="RADIUS",
|
|
210
|
+
help="Gaussian blur radius in pixels to simulate a soft photo (default 0)",
|
|
211
|
+
)
|
|
212
|
+
p.add_argument(
|
|
213
|
+
"--jpeg-quality", type=int, default=100, metavar="Q",
|
|
214
|
+
help="JPEG quality 1-100 to simulate compression (default 100: none)",
|
|
215
|
+
)
|
|
216
|
+
p.set_defaults(func=_cmd_calibrate)
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
220
|
+
parser = argparse.ArgumentParser(
|
|
221
|
+
prog="qrpack",
|
|
222
|
+
description="Pack a folder into printable QR codes and restore it from a photo.",
|
|
223
|
+
)
|
|
224
|
+
parser.add_argument("--version", action="version", version=f"qrpack {__version__}")
|
|
225
|
+
sub = parser.add_subparsers(dest="command", metavar="COMMAND")
|
|
226
|
+
_add_estimate(sub)
|
|
227
|
+
_add_pack(sub)
|
|
228
|
+
_add_restore(sub)
|
|
229
|
+
_add_calibrate(sub)
|
|
230
|
+
return parser
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def main(argv: Sequence[str] | None = None) -> int:
|
|
234
|
+
parser = build_parser()
|
|
235
|
+
args = parser.parse_args(argv)
|
|
236
|
+
if args.command is None:
|
|
237
|
+
parser.print_help(sys.stderr)
|
|
238
|
+
return 2
|
|
239
|
+
return args.func(args)
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
if __name__ == "__main__":
|
|
243
|
+
sys.exit(main())
|