refolio 0.1.0b1__tar.gz

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.
Files changed (37) hide show
  1. refolio-0.1.0b1/.gitignore +7 -0
  2. refolio-0.1.0b1/LICENSE +21 -0
  3. refolio-0.1.0b1/PKG-INFO +78 -0
  4. refolio-0.1.0b1/README.md +64 -0
  5. refolio-0.1.0b1/THIRD_PARTY_NOTICES.md +29 -0
  6. refolio-0.1.0b1/pyproject.toml +29 -0
  7. refolio-0.1.0b1/refolio/__init__.py +2 -0
  8. refolio-0.1.0b1/refolio/book.py +320 -0
  9. refolio-0.1.0b1/refolio/cli.py +339 -0
  10. refolio-0.1.0b1/refolio/dewarp.py +164 -0
  11. refolio-0.1.0b1/refolio/docs/reference.en.md +35 -0
  12. refolio-0.1.0b1/refolio/docs/reference.ja.md +33 -0
  13. refolio-0.1.0b1/refolio/docs.py +9 -0
  14. refolio-0.1.0b1/refolio/doctor.py +51 -0
  15. refolio-0.1.0b1/refolio/geometry.py +132 -0
  16. refolio-0.1.0b1/refolio/gutter.py +134 -0
  17. refolio-0.1.0b1/refolio/i18n.py +60 -0
  18. refolio-0.1.0b1/refolio/illum.py +222 -0
  19. refolio-0.1.0b1/refolio/lang_ja.py +40 -0
  20. refolio-0.1.0b1/refolio/layout.py +376 -0
  21. refolio-0.1.0b1/refolio/margins.py +108 -0
  22. refolio-0.1.0b1/refolio/metrics.py +106 -0
  23. refolio-0.1.0b1/refolio/ocr.py +161 -0
  24. refolio-0.1.0b1/refolio/paths.py +24 -0
  25. refolio-0.1.0b1/refolio/pdfio.py +100 -0
  26. refolio-0.1.0b1/refolio/pipeline.py +46 -0
  27. refolio-0.1.0b1/refolio/sr.py +169 -0
  28. refolio-0.1.0b1/refolio/textlayer.py +152 -0
  29. refolio-0.1.0b1/tests/synth.py +37 -0
  30. refolio-0.1.0b1/tests/test_cli_json.py +88 -0
  31. refolio-0.1.0b1/tests/test_extension.py +71 -0
  32. refolio-0.1.0b1/tests/test_i18n.py +45 -0
  33. refolio-0.1.0b1/tests/test_layout.py +160 -0
  34. refolio-0.1.0b1/tests/test_pdfio.py +58 -0
  35. refolio-0.1.0b1/tests/test_refolio.py +110 -0
  36. refolio-0.1.0b1/tests/test_sr.py +72 -0
  37. refolio-0.1.0b1/tests/test_textlayer.py +84 -0
@@ -0,0 +1,7 @@
1
+ .venv/
2
+ __pycache__/
3
+ *.egg-info/
4
+ out/
5
+ .pytest_cache/
6
+ samples/
7
+ work/
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Takahiro Yoshida
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,78 @@
1
+ Metadata-Version: 2.5
2
+ Name: refolio
3
+ Version: 0.1.0b1
4
+ Summary: Turn scans of bound books (flatbed or overhead) into clean, searchable PDFs, without changing a glyph.
5
+ License-Expression: MIT
6
+ License-File: LICENSE
7
+ Requires-Python: >=3.10
8
+ Requires-Dist: numpy
9
+ Requires-Dist: opencv-python-headless<5,>=4.8
10
+ Requires-Dist: pypdfium2>=4.30
11
+ Provides-Extra: test
12
+ Requires-Dist: pytest; extra == 'test'
13
+ Description-Content-Type: text/markdown
14
+
15
+ # Refolio
16
+
17
+ **Turn scans of bound books into clean, searchable PDFs — without changing a glyph.**
18
+
19
+ [日本語](README.ja.md) · **Beta**
20
+
21
+ Refolio takes a PDF of a scanned or photocopied book — open as spreads, or page by page — and makes one that is
22
+ easier to read: spreads split at the gutter, pages straightened and trimmed, page curl near the spine flattened,
23
+ one standard paper size for the whole book with the text block at the same place on every page, the binding
24
+ shadow and paper grain removed, and, optionally, an invisible text layer for search and copy.
25
+
26
+ It is a command-line tool (`refolio`) and a [VS Code extension](vscode-extension/README.md). Everything runs on
27
+ your machine.
28
+
29
+ ## Principle
30
+
31
+ Refolio never draws a glyph. Every step either moves pixels geometrically (split, rotate, trim, flatten the curl,
32
+ place on the paper; each step is recorded, so coordinates can be carried between the scan and the result) or
33
+ multiplies them by a smooth brightness gain. Super-resolution is the only step that makes new pixels, and a
34
+ super-resolved page is used only if every glyph keeps its shape (`glyph_guard`).
35
+
36
+ ## Install
37
+
38
+ ```bash
39
+ pip install --pre refolio # or: uv tool install --prerelease allow refolio (a beta)
40
+ refolio setup --sr # super-resolution (Real-ESRGAN, 47 MB), used for scans below 300 dpi
41
+ refolio setup --ocr # optional: the text layer (NDLOCR-Lite, about 0.5 GB)
42
+ refolio doctor # what is installed
43
+ ```
44
+
45
+ Python 3.10 or later. PDFs are read with pypdfium2, so nothing else (poppler, Ghostscript) is needed.
46
+ `refolio setup --ocr` needs [uv](https://github.com/astral-sh/uv): the text recognition lives in its own
47
+ environment. Add `--gpu` to read on an NVIDIA GPU (onnxruntime-gpu with the CUDA and cuDNN libraries, about 2.4 GB).
48
+
49
+ ## Use
50
+
51
+ ```bash
52
+ refolio make book.pdf book.refolio.pdf # the whole book
53
+ refolio make book.pdf out.pdf --size b5 # another paper size (auto by default)
54
+ refolio make book.pdf out.pdf --binding right # right-bound books (vertical text): right page first
55
+ refolio make book.pdf out.pdf --layout off # keep every scan as one page; only the brightness changes
56
+ refolio make book.pdf out.pdf --ocr off --sr off # without the text layer or super-resolution
57
+ ```
58
+
59
+ Text recognition and super-resolution are used when they are installed (`--ocr auto`, `--sr auto`).
60
+ Super-resolution touches only grey pages scanned below 300 dpi.
61
+
62
+ Every command takes `--json` and then prints JSON Lines on stdout: `progress` lines, then one `result` or `error`.
63
+ `refolio docs` prints a reference written for AI agents (Claude Code and others), so an agent can run Refolio for
64
+ you.
65
+
66
+ ## Beta
67
+
68
+ - Vertical text: give `--binding right`; it is not detected yet.
69
+ - Overhead scanners (ScanSnap SV600 and the like) are not tested yet.
70
+ - Text that was hidden in the fold when the book was scanned or copied cannot be recovered: press the book flat at
71
+ the spine.
72
+
73
+ ## Credits and licenses
74
+
75
+ MIT License. Some ideas (one set of margins per book, the page number as a reference, super-resolution) come from
76
+ [DN_SuperBook_PDF_Converter](https://github.com/dnobori/DN_SuperBook_PDF_Converter); no code is taken from it.
77
+ Text recognition: [NDLOCR-Lite](https://github.com/ndl-lab/ndlocr-lite) (National Diet Library, Japan; CC BY 4.0).
78
+ Third-party software: [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md).
@@ -0,0 +1,64 @@
1
+ # Refolio
2
+
3
+ **Turn scans of bound books into clean, searchable PDFs — without changing a glyph.**
4
+
5
+ [日本語](README.ja.md) · **Beta**
6
+
7
+ Refolio takes a PDF of a scanned or photocopied book — open as spreads, or page by page — and makes one that is
8
+ easier to read: spreads split at the gutter, pages straightened and trimmed, page curl near the spine flattened,
9
+ one standard paper size for the whole book with the text block at the same place on every page, the binding
10
+ shadow and paper grain removed, and, optionally, an invisible text layer for search and copy.
11
+
12
+ It is a command-line tool (`refolio`) and a [VS Code extension](vscode-extension/README.md). Everything runs on
13
+ your machine.
14
+
15
+ ## Principle
16
+
17
+ Refolio never draws a glyph. Every step either moves pixels geometrically (split, rotate, trim, flatten the curl,
18
+ place on the paper; each step is recorded, so coordinates can be carried between the scan and the result) or
19
+ multiplies them by a smooth brightness gain. Super-resolution is the only step that makes new pixels, and a
20
+ super-resolved page is used only if every glyph keeps its shape (`glyph_guard`).
21
+
22
+ ## Install
23
+
24
+ ```bash
25
+ pip install --pre refolio # or: uv tool install --prerelease allow refolio (a beta)
26
+ refolio setup --sr # super-resolution (Real-ESRGAN, 47 MB), used for scans below 300 dpi
27
+ refolio setup --ocr # optional: the text layer (NDLOCR-Lite, about 0.5 GB)
28
+ refolio doctor # what is installed
29
+ ```
30
+
31
+ Python 3.10 or later. PDFs are read with pypdfium2, so nothing else (poppler, Ghostscript) is needed.
32
+ `refolio setup --ocr` needs [uv](https://github.com/astral-sh/uv): the text recognition lives in its own
33
+ environment. Add `--gpu` to read on an NVIDIA GPU (onnxruntime-gpu with the CUDA and cuDNN libraries, about 2.4 GB).
34
+
35
+ ## Use
36
+
37
+ ```bash
38
+ refolio make book.pdf book.refolio.pdf # the whole book
39
+ refolio make book.pdf out.pdf --size b5 # another paper size (auto by default)
40
+ refolio make book.pdf out.pdf --binding right # right-bound books (vertical text): right page first
41
+ refolio make book.pdf out.pdf --layout off # keep every scan as one page; only the brightness changes
42
+ refolio make book.pdf out.pdf --ocr off --sr off # without the text layer or super-resolution
43
+ ```
44
+
45
+ Text recognition and super-resolution are used when they are installed (`--ocr auto`, `--sr auto`).
46
+ Super-resolution touches only grey pages scanned below 300 dpi.
47
+
48
+ Every command takes `--json` and then prints JSON Lines on stdout: `progress` lines, then one `result` or `error`.
49
+ `refolio docs` prints a reference written for AI agents (Claude Code and others), so an agent can run Refolio for
50
+ you.
51
+
52
+ ## Beta
53
+
54
+ - Vertical text: give `--binding right`; it is not detected yet.
55
+ - Overhead scanners (ScanSnap SV600 and the like) are not tested yet.
56
+ - Text that was hidden in the fold when the book was scanned or copied cannot be recovered: press the book flat at
57
+ the spine.
58
+
59
+ ## Credits and licenses
60
+
61
+ MIT License. Some ideas (one set of margins per book, the page number as a reference, super-resolution) come from
62
+ [DN_SuperBook_PDF_Converter](https://github.com/dnobori/DN_SuperBook_PDF_Converter); no code is taken from it.
63
+ Text recognition: [NDLOCR-Lite](https://github.com/ndl-lab/ndlocr-lite) (National Diet Library, Japan; CC BY 4.0).
64
+ Third-party software: [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md).
@@ -0,0 +1,29 @@
1
+ # Third-party software
2
+
3
+ Refolio itself is under the MIT License (`LICENSE`). It ships two programs by others in the VS Code extension, and
4
+ installs or downloads others when you ask for them. Each keeps its own license.
5
+
6
+ ## Shipped in the VS Code extension
7
+
8
+ | Software | Version | License | Where |
9
+ |---|---|---|---|
10
+ | [uv](https://github.com/astral-sh/uv) (Astral Software Inc.) | 0.12.18 | MIT or Apache-2.0 | `bin/uv`; license texts in `third_party/uv/` |
11
+ | [PDF.js](https://github.com/mozilla/pdf.js) (Mozilla Foundation) | 4.0.379 | Apache-2.0 | `media/pdfjs/`; license text in `media/pdfjs/LICENSE` |
12
+
13
+ ## Installed from PyPI when Refolio is set up (`pip`/`uv`, not shipped)
14
+
15
+ | Software | License |
16
+ |---|---|
17
+ | Python (installed by uv, python-build-standalone) | PSF License and the licenses of its bundled libraries |
18
+ | [NumPy](https://numpy.org/) | BSD-3-Clause |
19
+ | [opencv-python-headless](https://github.com/opencv/opencv-python) | Apache-2.0 (OpenCV); the wheel bundles third-party libraries under their own licenses (FFmpeg: LGPL-2.1) |
20
+ | [pypdfium2](https://github.com/pypdfium2-team/pypdfium2) | Apache-2.0 or BSD-3-Clause; PDFium: BSD-3-Clause and others |
21
+
22
+ ## Downloaded only when you ask for them
23
+
24
+ | Software | When | License |
25
+ |---|---|---|
26
+ | [NDLOCR-Lite](https://github.com/ndl-lab/ndlocr-lite) (National Diet Library, Japan) and its models | `refolio setup --ocr` (the extension's first setup) | CC BY 4.0. Its own dependencies are listed in its `LICENCE_DEPENDENCEIES` |
27
+ | [ONNX Runtime](https://github.com/microsoft/onnxruntime) (CPU, or onnxruntime-gpu with `--gpu`) | with NDLOCR-Lite | MIT |
28
+ | NVIDIA CUDA and cuDNN libraries (`nvidia-*` packages) | `refolio setup --ocr --gpu` only | NVIDIA proprietary licenses: installing them means accepting NVIDIA's terms |
29
+ | [Real-ESRGAN ncnn Vulkan](https://github.com/xinntao/Real-ESRGAN) v0.2.5.0 and its models | `refolio setup --sr` (the extension's first setup) | BSD-3-Clause |
@@ -0,0 +1,29 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.21"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "refolio"
7
+ dynamic = ["version"]
8
+ description = "Turn scans of bound books (flatbed or overhead) into clean, searchable PDFs, without changing a glyph."
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = "MIT"
12
+ dependencies = ["numpy", "opencv-python-headless>=4.8,<5", "pypdfium2>=4.30"]
13
+
14
+ [project.optional-dependencies]
15
+ test = ["pytest"]
16
+
17
+ [project.scripts]
18
+ refolio = "refolio.cli:main"
19
+
20
+ [tool.hatch.version]
21
+ path = "refolio/__init__.py"
22
+
23
+ [tool.hatch.build.targets.wheel]
24
+ packages = ["refolio"]
25
+
26
+ [tool.hatch.build.targets.sdist]
27
+ # only what builds and tests the package: not the extension (node_modules), work/, notes or samples
28
+ include = ["/refolio", "/tests", "/README.md", "/LICENSE", "/THIRD_PARTY_NOTICES.md", "/pyproject.toml"]
29
+ exclude = ["**/__pycache__"]
@@ -0,0 +1,2 @@
1
+ """Refolio: scans of bound books -> clean, searchable PDFs. Every step is geometric (recorded) or a smooth per-pixel gain."""
2
+ __version__ = "0.1.0b1"
@@ -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
+