refolio 0.1.0b1__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.
Potentially problematic release.
This version of refolio might be problematic. Click here for more details.
- refolio/__init__.py +2 -0
- refolio/book.py +320 -0
- refolio/cli.py +339 -0
- refolio/dewarp.py +164 -0
- refolio/docs/reference.en.md +35 -0
- refolio/docs/reference.ja.md +33 -0
- refolio/docs.py +9 -0
- refolio/doctor.py +51 -0
- refolio/geometry.py +132 -0
- refolio/gutter.py +134 -0
- refolio/i18n.py +60 -0
- refolio/illum.py +222 -0
- refolio/lang_ja.py +40 -0
- refolio/layout.py +376 -0
- refolio/margins.py +108 -0
- refolio/metrics.py +106 -0
- refolio/ocr.py +161 -0
- refolio/paths.py +24 -0
- refolio/pdfio.py +100 -0
- refolio/pipeline.py +46 -0
- refolio/sr.py +169 -0
- refolio/textlayer.py +152 -0
- refolio-0.1.0b1.dist-info/METADATA +78 -0
- refolio-0.1.0b1.dist-info/RECORD +27 -0
- refolio-0.1.0b1.dist-info/WHEEL +4 -0
- refolio-0.1.0b1.dist-info/entry_points.txt +2 -0
- refolio-0.1.0b1.dist-info/licenses/LICENSE +21 -0
refolio/__init__.py
ADDED
refolio/book.py
ADDED
|
@@ -0,0 +1,320 @@
|
|
|
1
|
+
"""A scanned book PDF in, an easier-to-read PDF out.
|
|
2
|
+
|
|
3
|
+
By default (layout.py) spreads are split into pages, each straightened, trimmed and placed on one standard paper size
|
|
4
|
+
for the book (2026-11-28: the user wants spreads split and pages shaped). With layout=False each page keeps its scan as
|
|
5
|
+
it is (no split, same resolution and page size). Either way the brightness: grain smoothing (illum.clean: non-local
|
|
6
|
+
means on the shadow-normalized page) and illum.view (no binding shadow, white paper, black ink). Page curl near the spine is flattened (dewarp) where it is visible. Pages
|
|
7
|
+
are written as JPEG (grey, or colour when the page has colour) straight into a small PDF writer.
|
|
8
|
+
"""
|
|
9
|
+
import multiprocessing
|
|
10
|
+
import os
|
|
11
|
+
import time
|
|
12
|
+
import zlib
|
|
13
|
+
from concurrent.futures import ProcessPoolExecutor
|
|
14
|
+
|
|
15
|
+
import cv2
|
|
16
|
+
import numpy as np
|
|
17
|
+
|
|
18
|
+
from . import pdfio
|
|
19
|
+
from .i18n import t
|
|
20
|
+
from .illum import clean, has_colour, view, view_color
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def page_info(pdf):
|
|
25
|
+
"""[(width_pt, height_pt, rotate)] for every page."""
|
|
26
|
+
return pdfio.page_info(pdf)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def page_image(pdf, page, dpi=300):
|
|
30
|
+
"""The scan of one page as stored (colour kept); a page made of several images is rendered at `dpi`."""
|
|
31
|
+
return pdfio.page_image(pdf, page, dpi=dpi)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _one(job):
|
|
35
|
+
"""A page with colour (highlighter, figures) stays in colour (view_color); other pages become grey. A black-and-
|
|
36
|
+
white page (1-bit scan) is kept as it is, as 1 bit. A page with an accepted super-resolution image (a PNG made by
|
|
37
|
+
_super_resolve) is made from that image instead of the scan."""
|
|
38
|
+
pdf, page, quality, bits = job[:4]
|
|
39
|
+
sr_png = job[4] if len(job) > 4 else None
|
|
40
|
+
cv2.setNumThreads(1)
|
|
41
|
+
im = cv2.imread(sr_png, cv2.IMREAD_COLOR) if sr_png else page_image(pdf, page)
|
|
42
|
+
if bits:
|
|
43
|
+
g = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY) >= 128
|
|
44
|
+
return g.shape[1], g.shape[0], 1, zlib.compress(np.packbits(g, axis=1).tobytes(), 9)
|
|
45
|
+
if has_colour(im):
|
|
46
|
+
out = view_color(im)
|
|
47
|
+
else:
|
|
48
|
+
out = view(clean(cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)))
|
|
49
|
+
return out.shape[1], out.shape[0], out.ndim, cv2.imencode(".jpg", out, [cv2.IMWRITE_JPEG_QUALITY, quality])[1].tobytes()
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _scan(pdf, page, rot, color, sr_png=None):
|
|
53
|
+
"""A scan as shown on screen (PDF /Rotate applied). The stored image is turned here; a page made of several
|
|
54
|
+
images is rendered by PDFium, which turns it already."""
|
|
55
|
+
from .layout import orient
|
|
56
|
+
if sr_png:
|
|
57
|
+
im = cv2.imread(sr_png, cv2.IMREAD_COLOR if color else cv2.IMREAD_GRAYSCALE)
|
|
58
|
+
return orient(im, rot)
|
|
59
|
+
try:
|
|
60
|
+
return orient(pdfio.page_image(pdf, page, color=color, strict=True), rot)
|
|
61
|
+
except RuntimeError:
|
|
62
|
+
return pdfio.page_image(pdf, page, color=color)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _analyse_one(job):
|
|
66
|
+
pdf, page, rot, split, prior, dewarp = job
|
|
67
|
+
cv2.setNumThreads(1)
|
|
68
|
+
from .layout import analyse
|
|
69
|
+
return analyse(_scan(pdf, page, rot, False), split, prior, dewarp)
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _page_one(job):
|
|
73
|
+
"""One output page: cut out of its scan (layout.cut), brightness as in _one (colour kept, grey cleaned with the
|
|
74
|
+
grain wiped off the paper, 1 bit kept as 1 bit), placed on the book's paper size (layout.put)."""
|
|
75
|
+
from .layout import clear_ground, clear_outer, cut, put
|
|
76
|
+
pdf, page, rot, width, part, placed, quality, bits, sr_png = job
|
|
77
|
+
cv2.setNumThreads(1)
|
|
78
|
+
im = _scan(pdf, page, rot, True, sr_png)
|
|
79
|
+
s = im.shape[1] / width
|
|
80
|
+
base = _scan(pdf, page, rot, False) if part.get("dewarp") else None
|
|
81
|
+
crop = cut(im, part, s, base=base)
|
|
82
|
+
if bits:
|
|
83
|
+
g = put(cv2.cvtColor(crop, cv2.COLOR_BGR2GRAY), placed, s) >= 128
|
|
84
|
+
return g.shape[1], g.shape[0], 1, zlib.compress(np.packbits(g, axis=1).tobytes(), 9)
|
|
85
|
+
if has_colour(crop):
|
|
86
|
+
out = put(clear_outer(clear_ground(view_color(crop)), part, s), placed, s)
|
|
87
|
+
else:
|
|
88
|
+
out = put(clear_outer(clear_ground(view(clean(cv2.cvtColor(crop, cv2.COLOR_BGR2GRAY), paper=True))), part, s),
|
|
89
|
+
placed, s)
|
|
90
|
+
return out.shape[1], out.shape[0], out.ndim, cv2.imencode(".jpg", out, [cv2.IMWRITE_JPEG_QUALITY, quality])[1].tobytes()
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def bilevel_pages(pdf):
|
|
94
|
+
"""Pages whose only image is 1 bit (a black-and-white scan, e.g. CCITT): nothing to gain, and as grey JPEG they
|
|
95
|
+
would be several times larger (a 52-page book with 37 such pages: 8 MB -> 52 MB)."""
|
|
96
|
+
return pdfio.bilevel_pages(pdf)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
FONT_IDS = dict(fh=3, fv=4, cid=5, desc=6, file=7, tounicode=8, gidmap=9)
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def write_pdf(path, pages, text=False):
|
|
103
|
+
"""pages: iterable of (width_px, height_px, kind, data, (width_pt, height_pt, rotate)[, lines]); kind 1 = packed
|
|
104
|
+
1-bit rows (zlib), 2 = grey JPEG, 3 = colour JPEG. text=True: each page may carry OCR lines (textlayer.Layer),
|
|
105
|
+
drawn invisibly over the image; the fonts are written at the end, when every character is known."""
|
|
106
|
+
offs, n = [], 0
|
|
107
|
+
layer = None
|
|
108
|
+
if text:
|
|
109
|
+
from .textlayer import Layer
|
|
110
|
+
layer = Layer()
|
|
111
|
+
with open(path, "wb") as fh:
|
|
112
|
+
def obj(body):
|
|
113
|
+
offs.append(fh.tell())
|
|
114
|
+
fh.write(f"{len(offs)} 0 obj\n".encode() + body + b"\nendobj\n")
|
|
115
|
+
|
|
116
|
+
def replace(num, body): # an object reserved at the start, written now
|
|
117
|
+
offs[num - 1] = fh.tell()
|
|
118
|
+
fh.write(f"{num} 0 obj\n".encode() + body + b"\nendobj\n")
|
|
119
|
+
fh.write(b"%PDF-1.4\n%\xe2\xe3\xcf\xd3\n")
|
|
120
|
+
obj(b"<< /Type /Catalog /Pages 2 0 R >>")
|
|
121
|
+
obj(b"") # page tree, filled in at the end
|
|
122
|
+
if layer:
|
|
123
|
+
for _ in FONT_IDS:
|
|
124
|
+
obj(b"null") # fonts, filled in at the end
|
|
125
|
+
kids = []
|
|
126
|
+
for page in pages:
|
|
127
|
+
w, h, ch, jpg, (pw, ph, rot) = page[:5]
|
|
128
|
+
lines = page[5] if len(page) > 5 else None
|
|
129
|
+
n += 1
|
|
130
|
+
cs = "/DeviceRGB" if ch == 3 else "/DeviceGray"
|
|
131
|
+
bpc, flt = (1, "/FlateDecode") if ch == 1 else (8, "/DCTDecode") # ch 1: packed 1-bit rows, zlib
|
|
132
|
+
obj(f"<< /Type /XObject /Subtype /Image /Width {w} /Height {h} /ColorSpace {cs} "
|
|
133
|
+
f"/BitsPerComponent {bpc} /Filter {flt} /Length {len(jpg)} >>\nstream\n".encode() + jpg + b"\nendstream")
|
|
134
|
+
img = len(offs)
|
|
135
|
+
draw = f"q {pw:.2f} 0 0 {ph:.2f} 0 0 cm /Im0 Do Q".encode()
|
|
136
|
+
fonts = ""
|
|
137
|
+
if layer and lines:
|
|
138
|
+
draw += b"\n" + layer.page_ops(lines, w, h, pw, ph).encode()
|
|
139
|
+
fonts = f" /Font << /FH {FONT_IDS['fh']} 0 R /FV {FONT_IDS['fv']} 0 R >>"
|
|
140
|
+
body = zlib.compress(draw, 6)
|
|
141
|
+
obj(f"<< /Length {len(body)} /Filter /FlateDecode >>\nstream\n".encode() + body + b"\nendstream")
|
|
142
|
+
else:
|
|
143
|
+
obj(f"<< /Length {len(draw)} >>\nstream\n".encode() + draw + b"\nendstream")
|
|
144
|
+
cont = len(offs)
|
|
145
|
+
obj(f"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 {pw:.2f} {ph:.2f}] /Rotate {rot} "
|
|
146
|
+
f"/Resources << /XObject << /Im0 {img} 0 R >>{fonts} >> /Contents {cont} 0 R >>".encode())
|
|
147
|
+
kids.append(len(offs))
|
|
148
|
+
if layer:
|
|
149
|
+
for num, body in layer.objects(FONT_IDS).items():
|
|
150
|
+
replace(num, body)
|
|
151
|
+
tree = f"<< /Type /Pages /Kids [{' '.join(f'{k} 0 R' for k in kids)}] /Count {n} >>".encode()
|
|
152
|
+
replace(2, tree)
|
|
153
|
+
xref = fh.tell()
|
|
154
|
+
fh.write(f"xref\n0 {len(offs) + 1}\n0000000000 65535 f \n".encode())
|
|
155
|
+
fh.write(b"".join(f"{o:010d} 00000 n \n".encode() for o in offs))
|
|
156
|
+
fh.write(f"trailer\n<< /Size {len(offs) + 1} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n".encode())
|
|
157
|
+
return n
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def _ocr_image(path, w, h, ch, data):
|
|
161
|
+
"""The page as the OCR sees it: exactly the pixels written into the PDF."""
|
|
162
|
+
if ch == 1:
|
|
163
|
+
bits = np.unpackbits(np.frombuffer(zlib.decompress(data), np.uint8).reshape(h, -1), axis=1)[:, :w]
|
|
164
|
+
cv2.imwrite(path + ".png", (bits * 255).astype(np.uint8))
|
|
165
|
+
else:
|
|
166
|
+
with open(path + ".jpg", "wb") as fh:
|
|
167
|
+
fh.write(data)
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def _super_resolve(src, info, bits, out_dir, below, target, report):
|
|
171
|
+
"""Super-resolution of the low-resolution grey pages, one at a time (it runs on the GPU): x4 with Real-ESRGAN,
|
|
172
|
+
kept only if glyph_guard finds every glyph of the scan unchanged, then resized to `target` dpi and saved as PNG.
|
|
173
|
+
Returns ({page: png}, stats). Colour pages, 1-bit pages and pages at `below` dpi or more are left as scanned.
|
|
174
|
+
If the engine fails (no usable GPU), the remaining pages are left as scanned and the error is reported."""
|
|
175
|
+
from . import sr
|
|
176
|
+
from .illum import has_colour
|
|
177
|
+
images = pdfio.image_info(src)
|
|
178
|
+
todo = []
|
|
179
|
+
for i, ((pw, ph, _), (n, _bpp, size)) in enumerate(zip(info, images)):
|
|
180
|
+
if n == 1 and size and i + 1 not in bits and size[0] / (pw / 72) < below:
|
|
181
|
+
todo.append((i + 1, size[0] / (pw / 72)))
|
|
182
|
+
stats = dict(accepted=0, rejected=0, skipped=len(info) - len(todo), error=None, rejected_pages=[])
|
|
183
|
+
out = {}
|
|
184
|
+
for k, (page, dpi) in enumerate(todo):
|
|
185
|
+
report(k, len(todo), "sr")
|
|
186
|
+
im = page_image(src, page)
|
|
187
|
+
if has_colour(im):
|
|
188
|
+
stats["skipped"] += 1
|
|
189
|
+
continue
|
|
190
|
+
g = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
|
|
191
|
+
try:
|
|
192
|
+
u = sr.upscale(g, 4)
|
|
193
|
+
except Exception as e: # noqa: BLE001 - leave the rest as scanned
|
|
194
|
+
stats["error"] = str(e)
|
|
195
|
+
stats["skipped"] += len(todo) - k
|
|
196
|
+
break
|
|
197
|
+
_worst, _n, bad = sr.glyph_guard(g, u)
|
|
198
|
+
if bad:
|
|
199
|
+
stats["rejected"] += 1
|
|
200
|
+
stats["rejected_pages"].append(page)
|
|
201
|
+
continue
|
|
202
|
+
f = min(4.0, target / dpi)
|
|
203
|
+
h, w = g.shape
|
|
204
|
+
u = cv2.resize(u, (round(w * f), round(h * f)), interpolation=cv2.INTER_AREA)
|
|
205
|
+
path = os.path.join(out_dir, f"sr{page:05d}.png")
|
|
206
|
+
cv2.imwrite(path, u)
|
|
207
|
+
out[page] = path
|
|
208
|
+
stats["accepted"] += 1
|
|
209
|
+
report(len(todo), len(todo), "sr")
|
|
210
|
+
return out, stats
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def process_pdf(src, dst, workers=None, quality=80, progress=None, ocr=False, ocr_device="auto",
|
|
214
|
+
sr=False, sr_below=300, sr_target=400, stats=None, layout=True, split="auto", size="auto",
|
|
215
|
+
dpi=400, binding="left", dewarp="auto"):
|
|
216
|
+
"""src PDF -> dst PDF (written in place; the caller moves it). Returns the number of pages written. A
|
|
217
|
+
black-and-white page is kept as 1 bit (80: 1970 本省 130MB -> 121MB (90: 158MB), still clean).
|
|
218
|
+
layout=True: spreads are split into pages, each page straightened, trimmed and placed on one standard paper
|
|
219
|
+
size for the whole book (layout.py; split auto|on|off, size auto|a4|b5|..., dpi: the highest output
|
|
220
|
+
resolution, binding left|right: which page of a spread comes first, dewarp auto|on|off: page curl near the
|
|
221
|
+
spine). layout=False: every scan stays one page
|
|
222
|
+
as it is (same size and resolution), only the brightness changes.
|
|
223
|
+
progress(done, total, stage) is called as scans are looked at ("analyse"), super-resolved ("sr"), pages made
|
|
224
|
+
("pages") and read ("ocr").
|
|
225
|
+
ocr=True: the pages as written are read by NDLOCR-Lite and get an invisible text layer.
|
|
226
|
+
sr=True: grey pages scanned below sr_below dpi are super-resolved to sr_target dpi where the glyph guard passes
|
|
227
|
+
(_super_resolve). stats: a dict that receives {"sr": ...} and {"layout": ...}."""
|
|
228
|
+
import tempfile
|
|
229
|
+
info = page_info(src)
|
|
230
|
+
bits = bilevel_pages(src)
|
|
231
|
+
workers = workers or max(1, (os.cpu_count() or 2) // 2)
|
|
232
|
+
|
|
233
|
+
def report(i, n, stage):
|
|
234
|
+
if progress:
|
|
235
|
+
progress(i, n, stage)
|
|
236
|
+
pool = lambda: ProcessPoolExecutor(workers, mp_context=multiprocessing.get_context("spawn")) # noqa: E731
|
|
237
|
+
with tempfile.TemporaryDirectory() as srdir:
|
|
238
|
+
pngs = {}
|
|
239
|
+
if sr:
|
|
240
|
+
pngs, st = _super_resolve(src, info, bits, srdir, sr_below, sr_target, report)
|
|
241
|
+
if stats is not None:
|
|
242
|
+
stats["sr"] = st
|
|
243
|
+
if not layout:
|
|
244
|
+
jobs = [(src, i + 1, quality, i + 1 in bits, pngs.get(i + 1)) for i in range(len(info))]
|
|
245
|
+
return _make(dst, _one, jobs, info, pool, report, ocr, ocr_device)
|
|
246
|
+
from .layout import SPREAD_ASPECT, plan
|
|
247
|
+
# what most scans of the book are, from the page sizes alone: a book scanned page by page (most scans
|
|
248
|
+
# upright) keeps a sideways scan as one page unless it shows two pages (layout.is_spread)
|
|
249
|
+
wide = [((ph if rot % 180 else pw) / (pw if rot % 180 else ph)) > SPREAD_ASPECT for pw, ph, rot in info]
|
|
250
|
+
prior = "spread" if sum(wide) * 2 >= len(wide) else "single"
|
|
251
|
+
analyses = []
|
|
252
|
+
with pool() as ex:
|
|
253
|
+
for i, a in enumerate(ex.map(_analyse_one, [(src, i + 1, rot, split, prior, dewarp)
|
|
254
|
+
for i, (_, _, rot) in enumerate(info)])):
|
|
255
|
+
analyses.append(a)
|
|
256
|
+
report(i + 1, len(info), "analyse")
|
|
257
|
+
# resolution as shown: the image width over the page width (turned by /Rotate)
|
|
258
|
+
dpis = [a["w"] / ((ph if rot % 180 else pw) / 72) for a, (pw, ph, rot) in zip(analyses, info)]
|
|
259
|
+
pages, linfo = plan(analyses, dpis, size, dpi, binding)
|
|
260
|
+
if stats is not None:
|
|
261
|
+
stats["layout"] = linfo
|
|
262
|
+
jobs = [(src, p["scan"] + 1, info[p["scan"]][2], analyses[p["scan"]]["w"],
|
|
263
|
+
analyses[p["scan"]]["parts"][p["part"]], p, quality, p["scan"] + 1 in bits, pngs.get(p["scan"] + 1))
|
|
264
|
+
for p in pages]
|
|
265
|
+
out_info = [(p["page_pt"][0], p["page_pt"][1], 0) for p in pages]
|
|
266
|
+
return _make(dst, _page_one, jobs, out_info, pool, report, ocr, ocr_device)
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
def _make(dst, fn, jobs, info, pool, report, ocr, ocr_device):
|
|
270
|
+
"""fn(job) -> (w, h, kind, data) per output page; info: (width_pt, height_pt, rotate) per output page."""
|
|
271
|
+
import tempfile
|
|
272
|
+
# spawn, not fork: PDFium (pypdfium2) is open in this process and a forked child deadlocks in it (2026-11-27)
|
|
273
|
+
if not ocr:
|
|
274
|
+
with pool() as ex:
|
|
275
|
+
def pages(res):
|
|
276
|
+
for i, (w, h, ch, jpg) in enumerate(res):
|
|
277
|
+
yield w, h, ch, jpg, info[i]
|
|
278
|
+
report(i + 1, len(info), "pages")
|
|
279
|
+
return write_pdf(dst, pages(ex.map(fn, jobs)))
|
|
280
|
+
from . import ocr as ocrmod
|
|
281
|
+
with tempfile.TemporaryDirectory() as d:
|
|
282
|
+
res = []
|
|
283
|
+
with pool() as ex:
|
|
284
|
+
for i, r in enumerate(ex.map(fn, jobs)):
|
|
285
|
+
res.append(r)
|
|
286
|
+
_ocr_image(os.path.join(d, f"p{i + 1:05d}"), *r)
|
|
287
|
+
report(i + 1, len(info), "pages")
|
|
288
|
+
text = ocrmod.recognize_dir(d, progress=lambda k, n: report(k, n, "ocr"), device=ocr_device)
|
|
289
|
+
return write_pdf(dst, ((w, h, ch, data, info[i], text.get(f"p{i + 1:05d}", []))
|
|
290
|
+
for i, (w, h, ch, data) in enumerate(res)), text=True)
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
def inbox(in_dir, out_dir, staging, settle=120, log=print):
|
|
294
|
+
"""Process every PDF in in_dir that has not changed for `settle` seconds: the result is made in `staging` (outside
|
|
295
|
+
the synced folder, so half-written files never sync) and moved to out_dir under the same name; the input goes to
|
|
296
|
+
in_dir/done/ (in_dir/failed/ with a note on error)."""
|
|
297
|
+
os.makedirs(out_dir, exist_ok=True)
|
|
298
|
+
os.makedirs(staging, exist_ok=True)
|
|
299
|
+
for name in sorted(os.listdir(in_dir)):
|
|
300
|
+
src = os.path.join(in_dir, name)
|
|
301
|
+
if name.startswith(".") or not name.lower().endswith(".pdf") or not os.path.isfile(src):
|
|
302
|
+
continue
|
|
303
|
+
if time.time() - os.path.getmtime(src) < settle:
|
|
304
|
+
continue # still arriving through the sync
|
|
305
|
+
tmp = os.path.join(staging, name)
|
|
306
|
+
t0 = time.time()
|
|
307
|
+
try:
|
|
308
|
+
n = process_pdf(src, tmp)
|
|
309
|
+
os.replace(tmp, os.path.join(out_dir, name)) # staging must be on the same disk (an atomic move)
|
|
310
|
+
os.makedirs(os.path.join(in_dir, "done"), exist_ok=True)
|
|
311
|
+
os.replace(src, os.path.join(in_dir, "done", name))
|
|
312
|
+
log(t("{name}: {n|# page|# pages}, {s} s", name=name, n=n, s=f"{time.time() - t0:.0f}"))
|
|
313
|
+
except Exception as e: # noqa: BLE001 - one bad PDF must not stop the inbox
|
|
314
|
+
os.makedirs(os.path.join(in_dir, "failed"), exist_ok=True)
|
|
315
|
+
os.replace(src, os.path.join(in_dir, "failed", name))
|
|
316
|
+
open(os.path.join(in_dir, "failed", name + ".txt"), "w", encoding="utf-8").write(f"{type(e).__name__}: {e}\n")
|
|
317
|
+
if os.path.exists(tmp):
|
|
318
|
+
os.remove(tmp)
|
|
319
|
+
log(t("{name}: failed: {error}", name=name, error=e))
|
|
320
|
+
|
refolio/cli.py
ADDED
|
@@ -0,0 +1,339 @@
|
|
|
1
|
+
"""refolio — turn scans of bound books into clean PDFs, without changing a glyph.
|
|
2
|
+
|
|
3
|
+
refolio make <in.pdf> <out.pdf> [--ocr auto|on|off] [--sr auto|on|off] a whole scanned book, easier to read, with a text layer
|
|
4
|
+
refolio setup [--ocr [--gpu]] [--sr] install the text recognition (NDLOCR-Lite, with uv) / Real-ESRGAN
|
|
5
|
+
refolio doctor [--gpu] what is installed (GPU, text recognition, super-resolution)
|
|
6
|
+
refolio docs the reference for AI agents (commands and the --json lines)
|
|
7
|
+
refolio inbox <in_dir> <out_dir> --staging DIR make every PDF dropped in in_dir (for a timer)
|
|
8
|
+
|
|
9
|
+
tools for one image or one step:
|
|
10
|
+
refolio split <spread.jpg>... where to split each spread
|
|
11
|
+
refolio spreads <book.pdf> [--csv out.csv] split of every spread + book-level outliers
|
|
12
|
+
refolio pages <page.jpg>... [--csv out.csv] defect measures of split pages (edge cut, shadow, curl)
|
|
13
|
+
refolio process <book.pdf> --out DIR [--first N] [--last N] [--flatten] [--dewarp] [--no-deskew]
|
|
14
|
+
refolio guard <original> <processed> glyph-by-glyph check (for super-resolution or dewarp)
|
|
15
|
+
refolio upscale <page> --out <file> [--scale 4] Real-ESRGAN, kept only if the glyph guard passes
|
|
16
|
+
refolio view <page>... --out DIR an image for people to check (no shadow, white paper; same coordinates)
|
|
17
|
+
|
|
18
|
+
--json (any command): JSON Lines on stdout. Zero or more {"event": "progress", ...} lines, then exactly one
|
|
19
|
+
{"event": "result", ...} or {"event": "error", "message": ...} line. The VS Code extension and AI agents read this;
|
|
20
|
+
its shape is fixed by tests/test_cli_json.py.
|
|
21
|
+
"""
|
|
22
|
+
import argparse
|
|
23
|
+
import csv
|
|
24
|
+
import json
|
|
25
|
+
import os
|
|
26
|
+
import sys
|
|
27
|
+
import time
|
|
28
|
+
|
|
29
|
+
from . import __version__
|
|
30
|
+
from .i18n import t
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class _Out:
|
|
34
|
+
"""Where a command reports. Human mode: text on stderr, tables on stdout. JSON mode: JSON Lines on stdout."""
|
|
35
|
+
|
|
36
|
+
def __init__(self, as_json):
|
|
37
|
+
self.json = as_json
|
|
38
|
+
|
|
39
|
+
def _line(self, d):
|
|
40
|
+
sys.stdout.write(json.dumps(d, ensure_ascii=False) + "\n")
|
|
41
|
+
sys.stdout.flush()
|
|
42
|
+
|
|
43
|
+
def progress(self, done, total, **kw):
|
|
44
|
+
if self.json:
|
|
45
|
+
self._line(dict(event="progress", done=done, total=total, **kw))
|
|
46
|
+
else:
|
|
47
|
+
print(f"{done}/{total}", file=sys.stderr, flush=True)
|
|
48
|
+
|
|
49
|
+
def say(self, text):
|
|
50
|
+
if not self.json:
|
|
51
|
+
print(text, file=sys.stderr, flush=True)
|
|
52
|
+
|
|
53
|
+
def result(self, data=None, rows=None, csv_path=None, text=None):
|
|
54
|
+
"""data: the JSON result. rows: a table (CSV in human mode, "rows" in JSON). text: the human summary."""
|
|
55
|
+
if self.json:
|
|
56
|
+
d = dict(event="result")
|
|
57
|
+
d.update(data or {})
|
|
58
|
+
if rows is not None:
|
|
59
|
+
d["rows"] = rows
|
|
60
|
+
self._line(d)
|
|
61
|
+
return
|
|
62
|
+
if rows is not None:
|
|
63
|
+
_write(rows, csv_path)
|
|
64
|
+
if text:
|
|
65
|
+
print(text, file=sys.stderr)
|
|
66
|
+
|
|
67
|
+
def error(self, message):
|
|
68
|
+
if self.json:
|
|
69
|
+
self._line(dict(event="error", message=str(message)))
|
|
70
|
+
else:
|
|
71
|
+
print(t("error: {message}", message=message), file=sys.stderr)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _side(path, given):
|
|
75
|
+
if given:
|
|
76
|
+
return given
|
|
77
|
+
stem = os.path.splitext(os.path.basename(path))[0]
|
|
78
|
+
return "left" if stem.endswith("_R") else "right" # a right-hand page has its spine on the left
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _parser():
|
|
82
|
+
common = argparse.ArgumentParser(add_help=False)
|
|
83
|
+
common.add_argument("--json", action="store_true", default=argparse.SUPPRESS,
|
|
84
|
+
help="JSON Lines on stdout (for the extension and AI agents)")
|
|
85
|
+
ap = argparse.ArgumentParser(prog="refolio", description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter,
|
|
86
|
+
parents=[common])
|
|
87
|
+
ap.add_argument("--version", action="version", version=f"refolio {__version__}")
|
|
88
|
+
sub = ap.add_subparsers(dest="cmd", required=True)
|
|
89
|
+
|
|
90
|
+
def cmd(name):
|
|
91
|
+
return sub.add_parser(name, parents=[common])
|
|
92
|
+
a = cmd("make"); a.add_argument("src"); a.add_argument("dst")
|
|
93
|
+
a.add_argument("--quality", type=int, default=80, help="JPEG quality of the pages (default 80)")
|
|
94
|
+
a.add_argument("--workers", type=int, help="processes (default: half the CPUs)")
|
|
95
|
+
a.add_argument("--ocr", choices=["auto", "on", "off"], default="auto",
|
|
96
|
+
help="invisible text layer (NDLOCR-Lite). auto: when it is installed")
|
|
97
|
+
a.add_argument("--ocr-device", choices=["auto", "cpu", "cuda"], default="auto")
|
|
98
|
+
a.add_argument("--sr", choices=["auto", "on", "off"], nargs="?", const="on", default="auto",
|
|
99
|
+
help="super-resolution (Real-ESRGAN, on the GPU) of grey pages scanned below --sr-below dpi, "
|
|
100
|
+
"kept only where the glyph guard passes. auto: when it is installed (`--sr` alone: on)")
|
|
101
|
+
a.add_argument("--sr-below", type=int, default=300, help="default 300 dpi")
|
|
102
|
+
a.add_argument("--sr-target", type=int, default=400, help="resolution of a super-resolved page (default 400 dpi)")
|
|
103
|
+
a.add_argument("--layout", choices=["on", "off"], default="on",
|
|
104
|
+
help="on: split spreads into pages, straighten, trim and put every page on one paper size. "
|
|
105
|
+
"off: keep each scan as one page as it is (only the brightness changes)")
|
|
106
|
+
a.add_argument("--split", choices=["auto", "on", "off"], default="auto",
|
|
107
|
+
help="auto: a scan wider than tall is a spread of two pages")
|
|
108
|
+
a.add_argument("--size", choices=["auto", "a6", "b6", "a5", "b5", "a4", "b4", "a3", "letter"], default="auto",
|
|
109
|
+
help="paper size of the output. auto: the smallest standard size the pages fit in at 1:1")
|
|
110
|
+
a.add_argument("--dpi", type=int, default=400, help="highest output resolution (default 400)")
|
|
111
|
+
a.add_argument("--dewarp", choices=["auto", "on", "off"], default="auto",
|
|
112
|
+
help="flatten page curl near the spine (pages of a spread). auto: where the curl is visible")
|
|
113
|
+
a.add_argument("--binding", choices=["left", "right"], default="left",
|
|
114
|
+
help="left: the left page of a spread comes first (horizontal text); right: vertical text")
|
|
115
|
+
a = cmd("setup"); a.add_argument("--ocr", action="store_true", help="install the text recognition (NDLOCR-Lite)")
|
|
116
|
+
a.add_argument("--gpu", action="store_true", help="with --ocr: onnxruntime-gpu (NVIDIA CUDA)")
|
|
117
|
+
a.add_argument("--sr", action="store_true", help="install the super-resolution engine (Real-ESRGAN, Vulkan)")
|
|
118
|
+
a = cmd("doctor"); a.add_argument("--gpu", action="store_true", help="also run the super-resolution engine once (uses the GPU)")
|
|
119
|
+
a = cmd("docs"); a.add_argument("--lang", choices=["en", "ja"])
|
|
120
|
+
a = cmd("inbox"); a.add_argument("in_dir"); a.add_argument("out_dir"); a.add_argument("--staging", required=True)
|
|
121
|
+
a = cmd("split"); a.add_argument("images", nargs="+")
|
|
122
|
+
a = cmd("spreads"); a.add_argument("pdf"); a.add_argument("--csv")
|
|
123
|
+
a = cmd("pages"); a.add_argument("images", nargs="+"); a.add_argument("--csv")
|
|
124
|
+
a.add_argument("--spine", choices=["left", "right"], help="default: left if the name ends in _R, else right")
|
|
125
|
+
a = cmd("process"); a.add_argument("pdf"); a.add_argument("--out", required=True)
|
|
126
|
+
a.add_argument("--first", type=int, default=1); a.add_argument("--last", type=int)
|
|
127
|
+
a.add_argument("--flatten", action="store_true"); a.add_argument("--dewarp", action="store_true")
|
|
128
|
+
a.add_argument("--no-deskew", action="store_true")
|
|
129
|
+
a = cmd("guard"); a.add_argument("original"); a.add_argument("processed")
|
|
130
|
+
a = cmd("upscale"); a.add_argument("page"); a.add_argument("--out", required=True)
|
|
131
|
+
a.add_argument("--scale", type=int, default=4, help="default 4 (realesrgan-x4plus works at x4 only)")
|
|
132
|
+
a = cmd("view"); a.add_argument("images", nargs="+"); a.add_argument("--out", required=True)
|
|
133
|
+
return ap
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def main(argv=None):
|
|
137
|
+
args = _parser().parse_args(argv)
|
|
138
|
+
args.json = getattr(args, "json", False)
|
|
139
|
+
out = _Out(args.json)
|
|
140
|
+
try:
|
|
141
|
+
return _run(args, out) or 0
|
|
142
|
+
except KeyboardInterrupt:
|
|
143
|
+
raise
|
|
144
|
+
except Exception as e: # noqa: BLE001 - reported as one error line
|
|
145
|
+
if os.environ.get("REFOLIO_DEBUG"):
|
|
146
|
+
raise
|
|
147
|
+
out.error(e if isinstance(e, (RuntimeError, OSError)) else f"{type(e).__name__}: {e}")
|
|
148
|
+
return 1
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def _imread(path, flag):
|
|
152
|
+
import cv2
|
|
153
|
+
im = cv2.imread(path, flag)
|
|
154
|
+
if im is None:
|
|
155
|
+
raise FileNotFoundError(t("cannot read the image {path}", path=path))
|
|
156
|
+
return im
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def _run(args, out):
|
|
160
|
+
import cv2
|
|
161
|
+
|
|
162
|
+
if args.cmd == "make":
|
|
163
|
+
from .book import process_pdf
|
|
164
|
+
if not os.path.isfile(args.src):
|
|
165
|
+
raise FileNotFoundError(t("no such file: {path}", path=args.src))
|
|
166
|
+
from . import ocr
|
|
167
|
+
use_ocr = args.ocr == "on" or (args.ocr == "auto" and ocr.engine() is not None)
|
|
168
|
+
if args.ocr == "on" and not ocr.engine():
|
|
169
|
+
raise RuntimeError(t("text recognition is not installed (run `refolio setup --ocr`)"))
|
|
170
|
+
from . import sr
|
|
171
|
+
use_sr = args.sr == "on" or (args.sr == "auto" and sr.engine() is not None)
|
|
172
|
+
if args.sr == "on" and not sr.engine():
|
|
173
|
+
raise RuntimeError(t("the super-resolution engine is not installed (run `refolio setup --sr`)"))
|
|
174
|
+
t0 = time.time()
|
|
175
|
+
stats = {}
|
|
176
|
+
n = process_pdf(args.src, args.dst, workers=args.workers, quality=args.quality, ocr=use_ocr,
|
|
177
|
+
ocr_device=args.ocr_device, sr=use_sr, sr_below=args.sr_below, sr_target=args.sr_target,
|
|
178
|
+
stats=stats, progress=lambda d, total, stage: out.progress(d, total, stage=stage),
|
|
179
|
+
layout=args.layout == "on", split=args.split, size=args.size, dpi=args.dpi, binding=args.binding,
|
|
180
|
+
dewarp=args.dewarp)
|
|
181
|
+
srs = stats.get("sr")
|
|
182
|
+
lay = stats.get("layout")
|
|
183
|
+
text = t("Wrote {path} ({n|# page|# pages})", path=args.dst, n=n)
|
|
184
|
+
if lay:
|
|
185
|
+
text += "\n" + t("{s|# spread|# spreads} split; paper {size} ({w} x {h} mm), {dpi} dpi",
|
|
186
|
+
s=lay["spreads"], size=lay["size"].upper(), w=lay["mm"][0], h=lay["mm"][1], dpi=lay["dpi"])
|
|
187
|
+
if lay["dewarped"]:
|
|
188
|
+
text += "\n" + t("page curl flattened on {n|# page|# pages}", n=lay["dewarped"])
|
|
189
|
+
if lay["split_check"]:
|
|
190
|
+
text += "\n" + t("check the split of scans {pages}: out of line with their neighbours",
|
|
191
|
+
pages=", ".join(map(str, lay["split_check"])))
|
|
192
|
+
if srs:
|
|
193
|
+
text += "\n" + t("super-resolution: {a} pages used, {r} rejected by the glyph guard, {s} left as scanned",
|
|
194
|
+
a=srs["accepted"], r=srs["rejected"], s=srs["skipped"])
|
|
195
|
+
if srs["error"]:
|
|
196
|
+
text += "\n" + t("super-resolution stopped: {error}", error=srs["error"])
|
|
197
|
+
out.result(dict(src=args.src, dst=args.dst, pages=n, seconds=round(time.time() - t0, 1), ocr=use_ocr,
|
|
198
|
+
sr=srs or None, layout=lay), text=text)
|
|
199
|
+
|
|
200
|
+
elif args.cmd == "setup":
|
|
201
|
+
done = {}
|
|
202
|
+
if args.ocr:
|
|
203
|
+
from . import ocr
|
|
204
|
+
done["ocr"] = ocr.setup(gpu=args.gpu, log=out.say)
|
|
205
|
+
if args.sr:
|
|
206
|
+
from . import sr
|
|
207
|
+
done["sr"] = sr.setup(log=out.say)
|
|
208
|
+
if not done:
|
|
209
|
+
raise RuntimeError(t("nothing to set up: give --ocr and/or --sr"))
|
|
210
|
+
out.result(done, text=t("Set up: {what}", what=", ".join(done)))
|
|
211
|
+
|
|
212
|
+
elif args.cmd == "doctor":
|
|
213
|
+
from .doctor import human, report
|
|
214
|
+
r = report(gpu=args.gpu)
|
|
215
|
+
if args.json:
|
|
216
|
+
out.result(r)
|
|
217
|
+
else:
|
|
218
|
+
print(human(r))
|
|
219
|
+
|
|
220
|
+
elif args.cmd == "docs":
|
|
221
|
+
from .docs import reference
|
|
222
|
+
text = reference(args.lang)
|
|
223
|
+
if args.json:
|
|
224
|
+
out.result(dict(text=text))
|
|
225
|
+
else:
|
|
226
|
+
print(text)
|
|
227
|
+
|
|
228
|
+
elif args.cmd == "inbox":
|
|
229
|
+
from .book import inbox
|
|
230
|
+
log = []
|
|
231
|
+
inbox(args.in_dir, args.out_dir, args.staging,
|
|
232
|
+
log=(log.append if args.json else lambda m: print(time.strftime("[%F %T]"), m, flush=True)))
|
|
233
|
+
out.result(dict(log=log))
|
|
234
|
+
|
|
235
|
+
elif args.cmd == "split":
|
|
236
|
+
from .gutter import find_split
|
|
237
|
+
rows = [dict(image=f, **find_split(_imread(f, cv2.IMREAD_GRAYSCALE)).to_dict()) for f in args.images]
|
|
238
|
+
if args.json:
|
|
239
|
+
out.result(rows=rows)
|
|
240
|
+
else:
|
|
241
|
+
for r in rows:
|
|
242
|
+
print(json.dumps(r, ensure_ascii=False))
|
|
243
|
+
|
|
244
|
+
elif args.cmd == "spreads":
|
|
245
|
+
from .gutter import consistent, find_split
|
|
246
|
+
from .pipeline import pdf_image, pdf_pages
|
|
247
|
+
rows, n = [], pdf_pages(args.pdf)
|
|
248
|
+
for p in range(1, n + 1):
|
|
249
|
+
g = pdf_image(args.pdf, p)
|
|
250
|
+
s = find_split(g)
|
|
251
|
+
rows.append(dict(page=p, width=g.shape[1], **s.to_dict()))
|
|
252
|
+
out.progress(p, n)
|
|
253
|
+
for i in consistent([r["x"] for r in rows], [r["width"] for r in rows]):
|
|
254
|
+
rows[i]["outlier"] = 1
|
|
255
|
+
out.result(rows=rows, csv_path=args.csv)
|
|
256
|
+
|
|
257
|
+
elif args.cmd == "pages":
|
|
258
|
+
from . import metrics
|
|
259
|
+
rows = []
|
|
260
|
+
for f in args.images:
|
|
261
|
+
g = _imread(f, cv2.IMREAD_GRAYSCALE)
|
|
262
|
+
side = _side(f, args.spine)
|
|
263
|
+
d, w = metrics.shadow(g, side)
|
|
264
|
+
rows.append(dict(image=os.path.basename(f), spine=side, edge_cut=round(metrics.edge_cut(g, side), 4),
|
|
265
|
+
shadow_depth=round(d, 3), shadow_width=round(w, 3), curvature=round(metrics.curvature(g), 4)))
|
|
266
|
+
out.result(rows=rows, csv_path=args.csv)
|
|
267
|
+
|
|
268
|
+
elif args.cmd == "process":
|
|
269
|
+
from .pipeline import pdf_image, pdf_pages, process_spread
|
|
270
|
+
os.makedirs(args.out, exist_ok=True)
|
|
271
|
+
last = args.last or pdf_pages(args.pdf)
|
|
272
|
+
written = []
|
|
273
|
+
for p in range(args.first, last + 1):
|
|
274
|
+
g = pdf_image(args.pdf, p)
|
|
275
|
+
for side, img, rec in process_spread(g, f"{os.path.basename(args.pdf)}#{p}", deskew=not args.no_deskew,
|
|
276
|
+
do_flatten=args.flatten, do_dewarp=args.dewarp):
|
|
277
|
+
stem = os.path.join(args.out, f"p{p:04d}_{side}")
|
|
278
|
+
cv2.imwrite(stem + ".jpg", img, [cv2.IMWRITE_JPEG_QUALITY, 92])
|
|
279
|
+
rec.save(stem + ".json")
|
|
280
|
+
written.append(stem + ".jpg")
|
|
281
|
+
out.progress(p - args.first + 1, last - args.first + 1)
|
|
282
|
+
out.result(dict(out=args.out, images=written))
|
|
283
|
+
|
|
284
|
+
elif args.cmd == "guard":
|
|
285
|
+
from .sr import glyph_guard
|
|
286
|
+
o, q = (_imread(f, cv2.IMREAD_GRAYSCALE) for f in (args.original, args.processed))
|
|
287
|
+
worst, n, bad = glyph_guard(o, q)
|
|
288
|
+
r = dict(glyphs=n, worst_iou=round(worst, 3), failed=bad[:50], n_failed=len(bad))
|
|
289
|
+
if args.json:
|
|
290
|
+
out.result(r)
|
|
291
|
+
else:
|
|
292
|
+
print(json.dumps(r))
|
|
293
|
+
return 1 if bad else 0
|
|
294
|
+
|
|
295
|
+
elif args.cmd == "upscale":
|
|
296
|
+
from .sr import glyph_guard, upscale
|
|
297
|
+
g = _imread(args.page, cv2.IMREAD_GRAYSCALE)
|
|
298
|
+
u = upscale(g, args.scale)
|
|
299
|
+
worst, n, bad = glyph_guard(g, u)
|
|
300
|
+
r = dict(glyphs=n, worst_iou=round(worst, 3), failed=bad[:50], n_failed=len(bad), accepted=not bad)
|
|
301
|
+
if bad:
|
|
302
|
+
root, ext = os.path.splitext(args.out)
|
|
303
|
+
rejected = root + ".rejected" + ext
|
|
304
|
+
cv2.imwrite(rejected, u) # to look at which glyphs changed
|
|
305
|
+
out.result(dict(r, out=None, rejected=rejected),
|
|
306
|
+
text=t("Not used: the shape changed in {bad} of {n} glyphs (worst agreement {worst}): {where}",
|
|
307
|
+
bad=len(bad), n=n, worst=f"{worst:.3f}", where=bad[:20]))
|
|
308
|
+
return 1
|
|
309
|
+
cv2.imwrite(args.out, u)
|
|
310
|
+
out.result(dict(r, out=args.out),
|
|
311
|
+
text=t("Wrote {path} ({n} glyphs, worst agreement {worst})", path=args.out, n=n, worst=f"{worst:.3f}"))
|
|
312
|
+
|
|
313
|
+
elif args.cmd == "view":
|
|
314
|
+
from . import illum
|
|
315
|
+
os.makedirs(args.out, exist_ok=True)
|
|
316
|
+
written = []
|
|
317
|
+
for i, f in enumerate(args.images):
|
|
318
|
+
dst = os.path.join(args.out, os.path.basename(f))
|
|
319
|
+
cv2.imwrite(dst, illum.view(_imread(f, cv2.IMREAD_GRAYSCALE)), [cv2.IMWRITE_JPEG_QUALITY, 92])
|
|
320
|
+
written.append(dst)
|
|
321
|
+
out.progress(i + 1, len(args.images))
|
|
322
|
+
out.result(dict(out=args.out, images=written))
|
|
323
|
+
return 0
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
def _write(rows, path):
|
|
327
|
+
if not rows:
|
|
328
|
+
return
|
|
329
|
+
keys = list(dict.fromkeys(k for r in rows for k in r))
|
|
330
|
+
fh = open(path, "w", newline="", encoding="utf-8") if path else sys.stdout
|
|
331
|
+
w = csv.DictWriter(fh, keys)
|
|
332
|
+
w.writeheader()
|
|
333
|
+
w.writerows(rows)
|
|
334
|
+
if path:
|
|
335
|
+
fh.close()
|
|
336
|
+
|
|
337
|
+
|
|
338
|
+
if __name__ == "__main__":
|
|
339
|
+
sys.exit(main())
|