dsh-pdf-workbench 1.3.0 → 1.3.1

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 (52) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +192 -163
  3. package/client.js +911 -223
  4. package/docs/RELEASE.md +110 -0
  5. package/icon.svg +6 -6
  6. package/index.js +18 -0
  7. package/package.json +1 -1
  8. package/screenshots.json +8 -8
  9. package/src/client/viewer.js +80 -80
  10. package/src/host/libraries.js +9 -12
  11. package/src/host/links.js +1 -1
  12. package/src/host/pending.js +1 -1
  13. package/src/host/routes.js +58 -12
  14. package/tools/AGENTS.md +33 -33
  15. package/tools/README.md +138 -138
  16. package/tools/auto_chapters.py +122 -122
  17. package/tools/dsfile.mjs +198 -198
  18. package/tools/export_chapter.py +108 -108
  19. package/tools/export_page.py +91 -91
  20. package/tools/md2overlay.py +200 -200
  21. package/tools/md2tex.py +422 -422
  22. package/tools/pdf_blocks.py +110 -110
  23. package/tools/pdf_fontsize.py +20 -20
  24. package/tools/pdf_merge.py +15 -15
  25. package/tools/pdf_pagesizes.py +8 -8
  26. package/tools/pdf_raster.py +21 -21
  27. package/tools/pdfkit.py +896 -896
  28. package/tools/realign_overlay.py +248 -248
  29. package/tools/rebuild_overlay.py +55 -55
  30. package/tools/rename_chapters.py +93 -93
  31. package/tools//350/247/204/350/214/203/00_/345/205/261/345/220/214/347/272/246/345/256/232.md +142 -142
  32. package/tools//350/247/204/350/214/203/01_/346/226/207/346/234/254/346/217/220/345/217/226.md +204 -204
  33. package/tools//350/247/204/350/214/203/02_/347/255/224/347/226/221.md +61 -61
  34. package/tools//350/247/204/350/214/203/03_/344/271/240/351/242/230/350/247/243/347/255/224.md +77 -77
  35. package/tools//350/247/204/350/214/203/api/346/217/220/347/244/272/350/257/215_/346/217/220/345/217/226.md +11 -11
  36. package/vendor/cmaps/LICENSE.txt +36 -36
  37. package/vendor/fonts/excalifont/OFL.txt +98 -98
  38. package/vendor/fonts/zhhand/OFL.txt +99 -99
  39. package/vendor/pdf.min.mjs +28 -28
  40. package/vendor/pdf.worker.min.mjs +28 -28
  41. package/vendor/pdfjs-LICENSE.txt +177 -177
  42. package/vendor/rough/LICENSE +21 -21
  43. package/vendor/rough/rough.mjs +1 -1
  44. package/vendor/wasm/LICENSE_JBIG2 +196 -196
  45. package/vendor/wasm/LICENSE_OPENJPEG +39 -39
  46. package/vendor/wasm/LICENSE_PDFJS_JBIG2 +13 -13
  47. package/vendor/wasm/LICENSE_PDFJS_OPENJPEG +22 -22
  48. package/vendor/wasm/LICENSE_PDFJS_QCMS +19 -19
  49. package/vendor/wasm/LICENSE_QCMS +21 -21
  50. package/vendor/wasm/jbig2_nowasm_fallback.js +15 -15
  51. package/vendor/wasm/openjpeg_nowasm_fallback.js +17 -17
  52. package//345/256/211/350/243/205/344/270/216/345/210/206/345/217/221.md +2 -2
@@ -1,248 +1,248 @@
1
- """Rebuild a translation overlay from cached page Markdown, aligned by paragraph.
2
-
3
- Why this exists: a chapter translated page by page (no `page-NNN.blocks.json`)
4
- can only be overlaid as a whole-page reflow, so its type size and position do
5
- not match the original. This tool re-splits the cached translation into
6
- paragraphs and puts each paragraph at the matching original text block, using
7
- the block bboxes from `pdf_blocks`. It costs no API calls; it is an
8
- approximation, not a block-level translation.
9
-
10
- Usage: python realign_overlay.py <source.pdf> <cache-dir> <out.pdf> <tools-dir>
11
- """
12
- import json
13
- import math
14
- import os
15
- import re
16
- import shutil
17
- import subprocess
18
- import sys
19
-
20
- import fitz
21
-
22
-
23
- def page_markdown(page_number, cache_dir):
24
- path = os.path.join(cache_dir, "page-%03d.md" % page_number)
25
- try:
26
- with open(path, encoding="utf-8") as handle:
27
- return handle.read()
28
- except OSError:
29
- return ""
30
-
31
-
32
- def segments_of(markdown):
33
- """Split a page's Markdown into paragraph-sized pieces.
34
-
35
- Blank lines are the only reliable separator the model gives us; a piece that
36
- is just the printed page number is not a paragraph."""
37
- parts = [part.strip() for part in re.split(r"\n\s*\n", markdown) if part.strip()]
38
- return [part for part in parts if not re.fullmatch(r"[\d\s]+", part)]
39
-
40
-
41
- def font_class_of(document):
42
- sizes = []
43
- for page in document:
44
- for block in page.get_text("dict").get("blocks", []):
45
- if block.get("type", 0) != 0:
46
- continue
47
- for line in block.get("lines", []):
48
- for span in line.get("spans", []):
49
- value = span.get("size", 0)
50
- if value > 0:
51
- sizes.append(value)
52
- sizes.sort()
53
- median = sizes[len(sizes) // 2] if sizes else 11.0
54
- return "12pt" if median >= 12.5 else "11pt" if median >= 11.2 else "10pt" if median >= 10 else "9pt"
55
-
56
-
57
- def merge_boxes(first, second):
58
- x0 = min(first[0], second[0])
59
- y0 = min(first[1], second[1])
60
- x1 = max(first[0] + first[2], second[0] + second[2])
61
- y1 = max(first[1] + first[3], second[1] + second[3])
62
- return [x0, y0, x1 - x0, y1 - y0]
63
-
64
-
65
- def drop_fragments(blocks, segments):
66
- """Drop tiny formula fragments that carry no paragraph of their own.
67
-
68
- PyMuPDF splits a displayed formula into two or three boxes ("n_i" and
69
- "s∈G" on their own). The translation puts the whole formula in one
70
- paragraph, so keeping the fragment as a separate block shifts every
71
- following paragraph by one block. Dropping the shortest formula fragments
72
- keeps the rest aligned; the fragment's symbols are already in the formula
73
- that precedes it.
74
- """
75
- kept = list(blocks)
76
- while len(kept) > len(segments):
77
- candidates = []
78
- for index, block in enumerate(kept):
79
- text = (block.get("text") or "").strip()
80
- height = float(block["bbox"][3])
81
- if block.get("kind") == "formula" and len(text) <= 12 and height < 0.022:
82
- candidates.append((len(text), index))
83
- if not candidates:
84
- break
85
- candidates.sort()
86
- kept.pop(candidates[0][1])
87
- return kept
88
-
89
-
90
- def align(segments, blocks):
91
- """Line paragraphs and blocks up in reading order.
92
-
93
- Counts usually match; when they do not, merge the pair with the smallest gap
94
- (fewer blocks than paragraphs) or the two shortest neighbours (more
95
- paragraphs than blocks) so the rest keeps its own position."""
96
- segs = list(segments)
97
- blks = [dict(block) for block in blocks]
98
- while len(segs) > len(blks) and len(segs) > 1:
99
- best = min(range(len(segs) - 1), key=lambda index: len(segs[index]) + len(segs[index + 1]))
100
- segs[best:best + 2] = [segs[best] + "\n\n" + segs[best + 1]]
101
- while len(blks) > len(segs) and len(blks) > 1:
102
- best = None
103
- for index in range(len(blks) - 1):
104
- first, second = blks[index], blks[index + 1]
105
- gap = second["bbox"][1] - (first["bbox"][1] + first["bbox"][3])
106
- first_center = first["bbox"][0] + first["bbox"][2] / 2
107
- second_center = second["bbox"][0] + second["bbox"][2] / 2
108
- # A display formula split over two boxes sits right under its own
109
- # first half and shares its centre line; a paragraph followed by a
110
- # formula does not. Choosing by gap alone merged the wrong pair and
111
- # shifted every following translation by one block.
112
- score = abs(gap) + abs(first_center - second_center) * 0.5
113
- if best is None or score < best[0]:
114
- best = (score, index)
115
- if best is None:
116
- break
117
- index = best[1]
118
- first, second = blks[index], blks[index + 1]
119
- merged = {
120
- "bbox": merge_boxes(first["bbox"], second["bbox"]),
121
- "size": max(first.get("size", 1.0), second.get("size", 1.0)),
122
- "kind": "paragraph",
123
- }
124
- blks[index:index + 2] = [merged]
125
- return segs, blks
126
-
127
-
128
- def estimate_height(text, width_pt, font_pt):
129
- """Rough height in points a paragraph needs at this width and body size."""
130
- plain = re.sub(r"\$\$.*?\$\$", " ", text, flags=re.S)
131
- per_line = max(8, int(width_pt / (font_pt * 1.05)))
132
- lines = 0
133
- for line in plain.split("\n"):
134
- stripped = line.strip()
135
- if stripped == "":
136
- continue
137
- lines += max(1, math.ceil(len(stripped) / per_line))
138
- formulas = text.count("$$") // 2
139
- return lines * font_pt * 1.25 + formulas * font_pt * 2.2
140
-
141
-
142
- def display_gap(text):
143
- """Offset just before the first display formula that starts its own line."""
144
- match = re.search(r"\n\s*\$\$", text)
145
- return -1 if match is None else match.start()
146
-
147
-
148
- def balance_dense(pairs, width_pt, height_pt, font_pt):
149
- """Give a packed paragraph a second block instead of shrinking it to 4pt.
150
-
151
- The whole-page translation merges the original's paragraphs differently, so
152
- one segment can carry a paragraph plus the formula and sentence of the block
153
- below. When that segment needs much more room than its own box, split it
154
- before the display formula and let the next block start with that formula.
155
- """
156
- result = []
157
- index = 0
158
- while index < len(pairs):
159
- block, text = pairs[index]
160
- if index + 1 < len(pairs):
161
- x, y, w, h = block["bbox"]
162
- room = (pairs[index + 1][0]["bbox"][1] - y) * height_pt
163
- gap_at = display_gap(text)
164
- if gap_at > 0 and room > 0 and estimate_height(text, w * width_pt, font_pt) > room * 1.35:
165
- head = text[:gap_at].strip()
166
- tail = text[gap_at:].strip()
167
- if head and tail:
168
- next_block, next_text = pairs[index + 1]
169
- result.append((block, head))
170
- result.append((next_block, tail + "\n\n" + next_text))
171
- index += 2
172
- continue
173
- result.append((block, text))
174
- index += 1
175
- return result
176
-
177
-
178
- def page_pdf(page_number, size, blocks, segments, font_class, work, tools_dir):
179
- """Render one page with md2overlay; returns the page PDF path or None."""
180
- if not segments or not blocks:
181
- return None
182
- font_pt = float(font_class.replace("pt", ""))
183
- pairs = balance_dense(list(zip(blocks, segments)), size[0], size[1], font_pt)
184
- synthetic = []
185
- for index, (block, text) in enumerate(pairs):
186
- synthetic.append({
187
- "id": "r-%04d-%02d" % (page_number, index + 1),
188
- "page": page_number,
189
- "bbox": block["bbox"],
190
- "size": block.get("size", 1.0),
191
- "kind": block.get("kind", "paragraph"),
192
- "md": text,
193
- })
194
- blocks_path = os.path.join(work, "page-%03d.blocks.json" % page_number)
195
- with open(blocks_path, "w", encoding="utf-8") as handle:
196
- json.dump(synthetic, handle, ensure_ascii=False)
197
- page_path = os.path.join(work, "page-%03d.pdf" % page_number)
198
- subprocess.run(
199
- [sys.executable, os.path.join(tools_dir, "md2overlay.py"), blocks_path, page_path,
200
- str(size[0]), str(size[1]), font_class],
201
- check=True,
202
- )
203
- return page_path if os.path.exists(page_path) else None
204
-
205
-
206
- def run(source, cache_dir, out_path, tools_dir):
207
- sys.path.insert(0, tools_dir)
208
- from pdf_blocks import blocks_for_page
209
-
210
- document = fitz.open(source)
211
- font_class = font_class_of(document)
212
- work = out_path + ".work"
213
- shutil.rmtree(work, ignore_errors=True)
214
- os.makedirs(work, exist_ok=True)
215
- merged = fitz.open()
216
- placed = 0
217
- try:
218
- for index, page in enumerate(document):
219
- number = index + 1
220
- size = [page.rect.width, page.rect.height]
221
- segments = segments_of(page_markdown(number, cache_dir))
222
- blocks = blocks_for_page(source, number)
223
- blocks = drop_fragments(blocks, segments)
224
- segments, blocks = align(segments, blocks)
225
- page_path = page_pdf(number, size, blocks, segments, font_class, work, tools_dir)
226
- if page_path is None:
227
- merged.new_page(width=size[0], height=size[1])
228
- continue
229
- merged.insert_pdf(fitz.open(page_path))
230
- placed += 1
231
- if merged.page_count == 0:
232
- raise SystemExit("no cached translation to realign")
233
- temporary = out_path + ".tmp.pdf"
234
- merged.save(temporary)
235
- os.replace(temporary, out_path)
236
- print(json.dumps({"pages": merged.page_count, "aligned": placed}, ensure_ascii=False))
237
- finally:
238
- shutil.rmtree(work, ignore_errors=True)
239
-
240
-
241
- def main():
242
- if len(sys.argv) < 5:
243
- raise SystemExit("usage: realign_overlay.py <source.pdf> <cache-dir> <out.pdf> <tools-dir>")
244
- run(sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4])
245
-
246
-
247
- if __name__ == "__main__":
248
- main()
1
+ """Rebuild a translation overlay from cached page Markdown, aligned by paragraph.
2
+
3
+ Why this exists: a chapter translated page by page (no `page-NNN.blocks.json`)
4
+ can only be overlaid as a whole-page reflow, so its type size and position do
5
+ not match the original. This tool re-splits the cached translation into
6
+ paragraphs and puts each paragraph at the matching original text block, using
7
+ the block bboxes from `pdf_blocks`. It costs no API calls; it is an
8
+ approximation, not a block-level translation.
9
+
10
+ Usage: python realign_overlay.py <source.pdf> <cache-dir> <out.pdf> <tools-dir>
11
+ """
12
+ import json
13
+ import math
14
+ import os
15
+ import re
16
+ import shutil
17
+ import subprocess
18
+ import sys
19
+
20
+ import fitz
21
+
22
+
23
+ def page_markdown(page_number, cache_dir):
24
+ path = os.path.join(cache_dir, "page-%03d.md" % page_number)
25
+ try:
26
+ with open(path, encoding="utf-8") as handle:
27
+ return handle.read()
28
+ except OSError:
29
+ return ""
30
+
31
+
32
+ def segments_of(markdown):
33
+ """Split a page's Markdown into paragraph-sized pieces.
34
+
35
+ Blank lines are the only reliable separator the model gives us; a piece that
36
+ is just the printed page number is not a paragraph."""
37
+ parts = [part.strip() for part in re.split(r"\n\s*\n", markdown) if part.strip()]
38
+ return [part for part in parts if not re.fullmatch(r"[\d\s]+", part)]
39
+
40
+
41
+ def font_class_of(document):
42
+ sizes = []
43
+ for page in document:
44
+ for block in page.get_text("dict").get("blocks", []):
45
+ if block.get("type", 0) != 0:
46
+ continue
47
+ for line in block.get("lines", []):
48
+ for span in line.get("spans", []):
49
+ value = span.get("size", 0)
50
+ if value > 0:
51
+ sizes.append(value)
52
+ sizes.sort()
53
+ median = sizes[len(sizes) // 2] if sizes else 11.0
54
+ return "12pt" if median >= 12.5 else "11pt" if median >= 11.2 else "10pt" if median >= 10 else "9pt"
55
+
56
+
57
+ def merge_boxes(first, second):
58
+ x0 = min(first[0], second[0])
59
+ y0 = min(first[1], second[1])
60
+ x1 = max(first[0] + first[2], second[0] + second[2])
61
+ y1 = max(first[1] + first[3], second[1] + second[3])
62
+ return [x0, y0, x1 - x0, y1 - y0]
63
+
64
+
65
+ def drop_fragments(blocks, segments):
66
+ """Drop tiny formula fragments that carry no paragraph of their own.
67
+
68
+ PyMuPDF splits a displayed formula into two or three boxes ("n_i" and
69
+ "s∈G" on their own). The translation puts the whole formula in one
70
+ paragraph, so keeping the fragment as a separate block shifts every
71
+ following paragraph by one block. Dropping the shortest formula fragments
72
+ keeps the rest aligned; the fragment's symbols are already in the formula
73
+ that precedes it.
74
+ """
75
+ kept = list(blocks)
76
+ while len(kept) > len(segments):
77
+ candidates = []
78
+ for index, block in enumerate(kept):
79
+ text = (block.get("text") or "").strip()
80
+ height = float(block["bbox"][3])
81
+ if block.get("kind") == "formula" and len(text) <= 12 and height < 0.022:
82
+ candidates.append((len(text), index))
83
+ if not candidates:
84
+ break
85
+ candidates.sort()
86
+ kept.pop(candidates[0][1])
87
+ return kept
88
+
89
+
90
+ def align(segments, blocks):
91
+ """Line paragraphs and blocks up in reading order.
92
+
93
+ Counts usually match; when they do not, merge the pair with the smallest gap
94
+ (fewer blocks than paragraphs) or the two shortest neighbours (more
95
+ paragraphs than blocks) so the rest keeps its own position."""
96
+ segs = list(segments)
97
+ blks = [dict(block) for block in blocks]
98
+ while len(segs) > len(blks) and len(segs) > 1:
99
+ best = min(range(len(segs) - 1), key=lambda index: len(segs[index]) + len(segs[index + 1]))
100
+ segs[best:best + 2] = [segs[best] + "\n\n" + segs[best + 1]]
101
+ while len(blks) > len(segs) and len(blks) > 1:
102
+ best = None
103
+ for index in range(len(blks) - 1):
104
+ first, second = blks[index], blks[index + 1]
105
+ gap = second["bbox"][1] - (first["bbox"][1] + first["bbox"][3])
106
+ first_center = first["bbox"][0] + first["bbox"][2] / 2
107
+ second_center = second["bbox"][0] + second["bbox"][2] / 2
108
+ # A display formula split over two boxes sits right under its own
109
+ # first half and shares its centre line; a paragraph followed by a
110
+ # formula does not. Choosing by gap alone merged the wrong pair and
111
+ # shifted every following translation by one block.
112
+ score = abs(gap) + abs(first_center - second_center) * 0.5
113
+ if best is None or score < best[0]:
114
+ best = (score, index)
115
+ if best is None:
116
+ break
117
+ index = best[1]
118
+ first, second = blks[index], blks[index + 1]
119
+ merged = {
120
+ "bbox": merge_boxes(first["bbox"], second["bbox"]),
121
+ "size": max(first.get("size", 1.0), second.get("size", 1.0)),
122
+ "kind": "paragraph",
123
+ }
124
+ blks[index:index + 2] = [merged]
125
+ return segs, blks
126
+
127
+
128
+ def estimate_height(text, width_pt, font_pt):
129
+ """Rough height in points a paragraph needs at this width and body size."""
130
+ plain = re.sub(r"\$\$.*?\$\$", " ", text, flags=re.S)
131
+ per_line = max(8, int(width_pt / (font_pt * 1.05)))
132
+ lines = 0
133
+ for line in plain.split("\n"):
134
+ stripped = line.strip()
135
+ if stripped == "":
136
+ continue
137
+ lines += max(1, math.ceil(len(stripped) / per_line))
138
+ formulas = text.count("$$") // 2
139
+ return lines * font_pt * 1.25 + formulas * font_pt * 2.2
140
+
141
+
142
+ def display_gap(text):
143
+ """Offset just before the first display formula that starts its own line."""
144
+ match = re.search(r"\n\s*\$\$", text)
145
+ return -1 if match is None else match.start()
146
+
147
+
148
+ def balance_dense(pairs, width_pt, height_pt, font_pt):
149
+ """Give a packed paragraph a second block instead of shrinking it to 4pt.
150
+
151
+ The whole-page translation merges the original's paragraphs differently, so
152
+ one segment can carry a paragraph plus the formula and sentence of the block
153
+ below. When that segment needs much more room than its own box, split it
154
+ before the display formula and let the next block start with that formula.
155
+ """
156
+ result = []
157
+ index = 0
158
+ while index < len(pairs):
159
+ block, text = pairs[index]
160
+ if index + 1 < len(pairs):
161
+ x, y, w, h = block["bbox"]
162
+ room = (pairs[index + 1][0]["bbox"][1] - y) * height_pt
163
+ gap_at = display_gap(text)
164
+ if gap_at > 0 and room > 0 and estimate_height(text, w * width_pt, font_pt) > room * 1.35:
165
+ head = text[:gap_at].strip()
166
+ tail = text[gap_at:].strip()
167
+ if head and tail:
168
+ next_block, next_text = pairs[index + 1]
169
+ result.append((block, head))
170
+ result.append((next_block, tail + "\n\n" + next_text))
171
+ index += 2
172
+ continue
173
+ result.append((block, text))
174
+ index += 1
175
+ return result
176
+
177
+
178
+ def page_pdf(page_number, size, blocks, segments, font_class, work, tools_dir):
179
+ """Render one page with md2overlay; returns the page PDF path or None."""
180
+ if not segments or not blocks:
181
+ return None
182
+ font_pt = float(font_class.replace("pt", ""))
183
+ pairs = balance_dense(list(zip(blocks, segments)), size[0], size[1], font_pt)
184
+ synthetic = []
185
+ for index, (block, text) in enumerate(pairs):
186
+ synthetic.append({
187
+ "id": "r-%04d-%02d" % (page_number, index + 1),
188
+ "page": page_number,
189
+ "bbox": block["bbox"],
190
+ "size": block.get("size", 1.0),
191
+ "kind": block.get("kind", "paragraph"),
192
+ "md": text,
193
+ })
194
+ blocks_path = os.path.join(work, "page-%03d.blocks.json" % page_number)
195
+ with open(blocks_path, "w", encoding="utf-8") as handle:
196
+ json.dump(synthetic, handle, ensure_ascii=False)
197
+ page_path = os.path.join(work, "page-%03d.pdf" % page_number)
198
+ subprocess.run(
199
+ [sys.executable, os.path.join(tools_dir, "md2overlay.py"), blocks_path, page_path,
200
+ str(size[0]), str(size[1]), font_class],
201
+ check=True,
202
+ )
203
+ return page_path if os.path.exists(page_path) else None
204
+
205
+
206
+ def run(source, cache_dir, out_path, tools_dir):
207
+ sys.path.insert(0, tools_dir)
208
+ from pdf_blocks import blocks_for_page
209
+
210
+ document = fitz.open(source)
211
+ font_class = font_class_of(document)
212
+ work = out_path + ".work"
213
+ shutil.rmtree(work, ignore_errors=True)
214
+ os.makedirs(work, exist_ok=True)
215
+ merged = fitz.open()
216
+ placed = 0
217
+ try:
218
+ for index, page in enumerate(document):
219
+ number = index + 1
220
+ size = [page.rect.width, page.rect.height]
221
+ segments = segments_of(page_markdown(number, cache_dir))
222
+ blocks = blocks_for_page(source, number)
223
+ blocks = drop_fragments(blocks, segments)
224
+ segments, blocks = align(segments, blocks)
225
+ page_path = page_pdf(number, size, blocks, segments, font_class, work, tools_dir)
226
+ if page_path is None:
227
+ merged.new_page(width=size[0], height=size[1])
228
+ continue
229
+ merged.insert_pdf(fitz.open(page_path))
230
+ placed += 1
231
+ if merged.page_count == 0:
232
+ raise SystemExit("no cached translation to realign")
233
+ temporary = out_path + ".tmp.pdf"
234
+ merged.save(temporary)
235
+ os.replace(temporary, out_path)
236
+ print(json.dumps({"pages": merged.page_count, "aligned": placed}, ensure_ascii=False))
237
+ finally:
238
+ shutil.rmtree(work, ignore_errors=True)
239
+
240
+
241
+ def main():
242
+ if len(sys.argv) < 5:
243
+ raise SystemExit("usage: realign_overlay.py <source.pdf> <cache-dir> <out.pdf> <tools-dir>")
244
+ run(sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4])
245
+
246
+
247
+ if __name__ == "__main__":
248
+ main()
@@ -1,55 +1,55 @@
1
- """Rebuild an overlay PDF from cached per-page block translations.
2
-
3
- Usage: python rebuild_overlay.py <source.pdf> <cache-dir> <out.pdf> <tools-dir>
4
- """
5
- import json
6
- import os
7
- import subprocess
8
- import sys
9
- import tempfile
10
-
11
- import fitz
12
-
13
- source, cache_dir, out_path, tools_dir = sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4]
14
-
15
- document = fitz.open(source)
16
- sizes = [[page.rect.width, page.rect.height] for page in document]
17
-
18
- span_sizes = []
19
- for page in document:
20
- for block in page.get_text("dict").get("blocks", []):
21
- if block.get("type", 0) != 0:
22
- continue
23
- for line in block.get("lines", []):
24
- for span in line.get("spans", []):
25
- value = span.get("size", 0)
26
- if value > 0:
27
- span_sizes.append(value)
28
- span_sizes.sort()
29
- median = span_sizes[len(span_sizes) // 2] if span_sizes else 11.0
30
- font_class = "12pt" if median >= 12.5 else "11pt" if median >= 11.2 else "10pt" if median >= 10 else "9pt"
31
-
32
- merged = fitz.open()
33
- with tempfile.TemporaryDirectory(prefix="rebuild-overlay-") as work:
34
- for index, size in enumerate(sizes):
35
- blocks_path = os.path.join(cache_dir, "page-%03d.blocks.json" % (index + 1))
36
- if not os.path.exists(blocks_path):
37
- continue
38
- page_pdf = os.path.join(work, "page-%03d.pdf" % (index + 1))
39
- result = subprocess.run(
40
- [sys.executable, os.path.join(tools_dir, "md2overlay.py"), blocks_path, page_pdf,
41
- str(size[0]), str(size[1]), font_class],
42
- capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=180,
43
- )
44
- if os.path.exists(page_pdf):
45
- merged.insert_pdf(fitz.open(page_pdf))
46
- elif result.stdout or result.stderr:
47
- sys.stderr.write((result.stdout or "") + (result.stderr or ""))
48
- sys.exit(1)
49
-
50
- if merged.page_count == 0:
51
- sys.exit("no cached block pages")
52
- temp_path = out_path + ".tmp.pdf"
53
- merged.save(temp_path)
54
- os.replace(temp_path, out_path)
55
- print(out_path)
1
+ """Rebuild an overlay PDF from cached per-page block translations.
2
+
3
+ Usage: python rebuild_overlay.py <source.pdf> <cache-dir> <out.pdf> <tools-dir>
4
+ """
5
+ import json
6
+ import os
7
+ import subprocess
8
+ import sys
9
+ import tempfile
10
+
11
+ import fitz
12
+
13
+ source, cache_dir, out_path, tools_dir = sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4]
14
+
15
+ document = fitz.open(source)
16
+ sizes = [[page.rect.width, page.rect.height] for page in document]
17
+
18
+ span_sizes = []
19
+ for page in document:
20
+ for block in page.get_text("dict").get("blocks", []):
21
+ if block.get("type", 0) != 0:
22
+ continue
23
+ for line in block.get("lines", []):
24
+ for span in line.get("spans", []):
25
+ value = span.get("size", 0)
26
+ if value > 0:
27
+ span_sizes.append(value)
28
+ span_sizes.sort()
29
+ median = span_sizes[len(span_sizes) // 2] if span_sizes else 11.0
30
+ font_class = "12pt" if median >= 12.5 else "11pt" if median >= 11.2 else "10pt" if median >= 10 else "9pt"
31
+
32
+ merged = fitz.open()
33
+ with tempfile.TemporaryDirectory(prefix="rebuild-overlay-") as work:
34
+ for index, size in enumerate(sizes):
35
+ blocks_path = os.path.join(cache_dir, "page-%03d.blocks.json" % (index + 1))
36
+ if not os.path.exists(blocks_path):
37
+ continue
38
+ page_pdf = os.path.join(work, "page-%03d.pdf" % (index + 1))
39
+ result = subprocess.run(
40
+ [sys.executable, os.path.join(tools_dir, "md2overlay.py"), blocks_path, page_pdf,
41
+ str(size[0]), str(size[1]), font_class],
42
+ capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=180,
43
+ )
44
+ if os.path.exists(page_pdf):
45
+ merged.insert_pdf(fitz.open(page_pdf))
46
+ elif result.stdout or result.stderr:
47
+ sys.stderr.write((result.stdout or "") + (result.stderr or ""))
48
+ sys.exit(1)
49
+
50
+ if merged.page_count == 0:
51
+ sys.exit("no cached block pages")
52
+ temp_path = out_path + ".tmp.pdf"
53
+ merged.save(temp_path)
54
+ os.replace(temp_path, out_path)
55
+ print(out_path)