dsh-pdf-workbench 1.4.1 → 1.5.0

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 (78) hide show
  1. package/README.md +29 -7
  2. package/client.js +4106 -469
  3. package/docs/LAYOUT.md +56 -0
  4. package/docs/RELEASE.md +8 -0
  5. package/docs/TESTING.md +16 -0
  6. package/docs/ci.md +18 -13
  7. package/docs/copy/templates.md +4 -4
  8. package/docs/decisions.md +119 -0
  9. package/docs/features.md +14 -8
  10. package/docs/requirements/2026-11-25-v1.5/346/224/271/350/277/233/351/234/200/346/261/202.md +622 -0
  11. package/docs/roles/{release-manager.md → ci.md} +37 -47
  12. package/docs/roles/programmer.md +45 -59
  13. package/docs/roles/requirements.md +68 -0
  14. package/docs/todo.md +590 -32
  15. package/index.js +337 -1
  16. package/package.json +1 -1
  17. package/src/host/backup.js +172 -33
  18. package/src/host/book-wizard.js +454 -0
  19. package/src/host/digest.js +4 -0
  20. package/src/host/engine.js +88 -0
  21. package/src/host/exports.js +159 -0
  22. package/src/host/http.js +28 -1
  23. package/src/host/imports.js +650 -0
  24. package/src/host/index-source.js +117 -11
  25. package/src/host/library-export.js +162 -0
  26. package/src/host/pdf-source.js +6 -2
  27. package/src/host/routes.js +1020 -120
  28. package/src/host/shortcut.js +238 -0
  29. package/src/host/storage.js +421 -0
  30. package/src/host/translate-blocks.js +49 -45
  31. package/src/host/translate-job.js +37 -10
  32. package/src/host/translate.js +19 -45
  33. package/src/host/translation-cache.js +209 -0
  34. package/src/host/typst-install.js +132 -0
  35. package/src/host/zip.js +486 -4
  36. package/tools/latex_to_typst.py +1353 -0
  37. package/tools/md2overlay.py +147 -152
  38. package/tools/md2overlay_typst.py +312 -0
  39. package/tools/md2typst.py +818 -0
  40. package/tools/overlay_layout.py +332 -0
  41. package/tools/pdf_blocks.py +82 -10
  42. package/tools/realign_overlay.py +4 -1
  43. package/tools/rebuild_overlay.py +3 -1
  44. package/tools/split_pdf.py +158 -0
  45. package/tools/typst_runtime.py +98 -0
  46. package/vendor/katex/LICENSE +21 -0
  47. package/vendor/katex/fonts/KaTeX_AMS-Regular.woff2 +0 -0
  48. package/vendor/katex/fonts/KaTeX_Caligraphic-Bold.woff2 +0 -0
  49. package/vendor/katex/fonts/KaTeX_Caligraphic-Regular.woff2 +0 -0
  50. package/vendor/katex/fonts/KaTeX_Fraktur-Bold.woff2 +0 -0
  51. package/vendor/katex/fonts/KaTeX_Fraktur-Regular.woff2 +0 -0
  52. package/vendor/katex/fonts/KaTeX_Main-Bold.woff2 +0 -0
  53. package/vendor/katex/fonts/KaTeX_Main-BoldItalic.woff2 +0 -0
  54. package/vendor/katex/fonts/KaTeX_Main-Italic.woff2 +0 -0
  55. package/vendor/katex/fonts/KaTeX_Main-Regular.woff2 +0 -0
  56. package/vendor/katex/fonts/KaTeX_Math-BoldItalic.woff2 +0 -0
  57. package/vendor/katex/fonts/KaTeX_Math-Italic.woff2 +0 -0
  58. package/vendor/katex/fonts/KaTeX_SansSerif-Bold.woff2 +0 -0
  59. package/vendor/katex/fonts/KaTeX_SansSerif-Italic.woff2 +0 -0
  60. package/vendor/katex/fonts/KaTeX_SansSerif-Regular.woff2 +0 -0
  61. package/vendor/katex/fonts/KaTeX_Script-Regular.woff2 +0 -0
  62. package/vendor/katex/fonts/KaTeX_Size1-Regular.woff2 +0 -0
  63. package/vendor/katex/fonts/KaTeX_Size2-Regular.woff2 +0 -0
  64. package/vendor/katex/fonts/KaTeX_Size3-Regular.woff2 +0 -0
  65. package/vendor/katex/fonts/KaTeX_Size4-Regular.woff2 +0 -0
  66. package/vendor/katex/fonts/KaTeX_Typewriter-Regular.woff2 +0 -0
  67. package/vendor/katex/katex.min.css +1 -0
  68. package/vendor/katex/katex.min.js +1 -0
  69. package//345/256/211/350/243/205/344/270/216/345/210/206/345/217/221.md +9 -1
  70. package/docs/boss-handover.md +0 -84
  71. package/docs/roles/auditor.md +0 -123
  72. package/docs/roles/boss.md +0 -162
  73. package/docs/roles/code-reviewer.md +0 -132
  74. package/docs/roles/feature-inventory.md +0 -119
  75. package/docs/roles/feedback-collector.md +0 -105
  76. package/docs/roles/tester.md +0 -140
  77. package/docs/roles/ui-copywriter.md +0 -122
  78. package/src/host/book-import.js +0 -98
@@ -0,0 +1,332 @@
1
+ """Shared placement/measurement contract for the overlay engines (LaTeX and Typst).
2
+
3
+ Both kernels decide the same geometry — where a block may sit (`start_x`,
4
+ `room_right`, `room_below`), what size/leading it gets, and what the sidecar
5
+ `page-NNN.layout.json` records — so those decisions live here instead of being
6
+ duplicated per renderer. The measurement is engine-agnostic: both engines print
7
+ a zero-width white `MDnnn` marker on a block's first line, and the file is read
8
+ back with PyMuPDF in content order.
9
+ """
10
+ import json
11
+
12
+ import fitz
13
+
14
+
15
+ def layout_target(blocks_path, out_path):
16
+ """Where the per-page layout record goes: beside the block cache."""
17
+ if blocks_path.endswith(".blocks.json"):
18
+ return blocks_path[: -len(".blocks.json")] + ".layout.json"
19
+ return out_path + ".layout.json"
20
+
21
+
22
+ def overlaps_x(left, right):
23
+ """True when two blocks share horizontal space, i.e. stack vertically."""
24
+ return not (left[0] + left[2] <= right[0] or right[0] + right[2] <= left[0])
25
+
26
+
27
+ def same_line(first, second):
28
+ """True when two boxes really share a printed line."""
29
+ first_top, first_bottom = float(first[1]), float(first[1]) + float(first[3])
30
+ second_top, second_bottom = float(second[1]), float(second[1]) + float(second[3])
31
+ overlap = min(first_bottom, second_bottom) - max(first_top, second_top)
32
+ return overlap > 0.5 * min(float(first[3]), float(second[3]))
33
+
34
+
35
+ def room_below(block, blocks, page_height, font_pt):
36
+ """Points available from this block's top to the next block under it."""
37
+ x, y, width, height = [float(value) for value in block.get("bbox") or [0, 0, 1, 1]]
38
+ limit = page_height - y * page_height - 4.0
39
+ for other in blocks:
40
+ if other is block:
41
+ continue
42
+ other_box = other.get("bbox") or [0, 0, 1, 1]
43
+ if not overlaps_x([x, y, width], other_box):
44
+ continue
45
+ gap = (float(other_box[1]) - y) * page_height
46
+ if max(2.0, font_pt * 0.6) < gap < limit:
47
+ limit = gap
48
+ return max(6.0, limit)
49
+
50
+
51
+ def room_right(block, blocks):
52
+ """Normalized right edge this block may use when the space beside it is free."""
53
+ x, y, width, height = [float(value) for value in block.get("bbox") or [0, 0, 1, 1]]
54
+ right = x + width
55
+ limit = 0.985
56
+ for other in blocks:
57
+ if other is block:
58
+ continue
59
+ other_box = other.get("bbox") or [0, 0, 1, 1]
60
+ if not same_line(block.get("bbox") or [0, 0, 1, 1], other_box):
61
+ continue
62
+ start = float(other_box[0])
63
+ if start > right + 0.005:
64
+ limit = min(limit, start - 0.004)
65
+ return max(x + 0.08, limit)
66
+
67
+
68
+ def inline_formula(md):
69
+ """Turn a standalone `$$...$$` block into one inline math run."""
70
+ body = md.strip()
71
+ if body.startswith("$$") and body.endswith("$$") and body.count("$$") == 2:
72
+ return "$%s$" % " ".join(body[2:-2].split())
73
+ return ""
74
+
75
+
76
+ def start_x(block, blocks):
77
+ """Left edge to use, pushed right past a same-line neighbour it would overlap."""
78
+ x, y, width, height = [float(value) for value in block.get("bbox") or [0, 0, 1, 1]]
79
+ for other in blocks:
80
+ if other is block:
81
+ continue
82
+ other_box = other.get("bbox") or [0, 0, 1, 1]
83
+ if not same_line(block.get("bbox") or [0, 0, 1, 1], other_box):
84
+ continue
85
+ other_left, other_right = float(other_box[0]), float(other_box[0]) + float(other_box[2])
86
+ if other_left < x - 0.002 and other_right > x + 0.01:
87
+ x = min(0.9, other_right + 0.006)
88
+ return x
89
+
90
+
91
+ def baseline_of(block, page_height, font_pt):
92
+ """The block's first printed baseline, in points from the page top."""
93
+ first = block.get("firstBaseline")
94
+ if first is None or float(first) <= 0:
95
+ bbox = block.get("bbox") or [0, 0, 1, 1]
96
+ return float(bbox[1]) * page_height + font_pt * float(block.get("size") or 1.0)
97
+ return float(first) * page_height
98
+
99
+
100
+ def leading_of(block, body_pt, page_height):
101
+ """Line spacing in points: the printed leading, kept readable."""
102
+ leading = float(block.get("leading") or 0.0)
103
+ if leading <= 0.0:
104
+ return body_pt * 1.25
105
+ return max(body_pt * 1.15, min(body_pt * 1.6, leading * page_height))
106
+
107
+
108
+ def alignment_of(block):
109
+ """The alignment command the LaTeX block's minipage should carry."""
110
+ align = block.get("align")
111
+ if align == "center":
112
+ return "\\centering"
113
+ if align == "right":
114
+ return "\\raggedleft"
115
+ if align == "justify":
116
+ return ""
117
+ return "\\raggedright"
118
+
119
+
120
+ def align_name(block):
121
+ """The printed alignment as a semantic name for the sidecar and the DOM layer."""
122
+ align = block.get("align")
123
+ if align == "center":
124
+ return "center"
125
+ if align == "right":
126
+ return "right"
127
+ if align == "justify":
128
+ return "justify"
129
+ return "left"
130
+
131
+
132
+ def floor_pt(font_pt, min_pt):
133
+ """The smallest body size the overlay may use on this chapter's page."""
134
+ return min(font_pt, min_pt)
135
+
136
+
137
+ def body_of(block, adjustments, font_pt, min_pt):
138
+ """The rendered font size for one block: printed size, then the fit scale."""
139
+ ratio = max(0.95, min(1.5, float(block.get("size") or 1.0)))
140
+ adjustment = adjustments.get(str(block.get("id") or "")) or {}
141
+ scale = float(adjustment.get("scale", 1.0))
142
+ return max(floor_pt(font_pt, min_pt), font_pt * ratio * scale)
143
+
144
+
145
+ def measure_page(pdf_path, placed):
146
+ """Where each placed block's text actually landed, in points.
147
+
148
+ Both engines write one block after another, so the extraction order *is* the
149
+ block order: every span after a block's marker belongs to that block until
150
+ the next marker. That is exact even when a long translation runs past the
151
+ following block. Blocks whose body starts with display math carry no marker;
152
+ they are claimed by their reserved rectangle first.
153
+ """
154
+ document = fitz.open(pdf_path)
155
+ try:
156
+ spans = []
157
+ line_number = 0
158
+ for block in document[0].get_text("dict").get("blocks", []):
159
+ for line in block.get("lines", []):
160
+ line_number += 1
161
+ for span in line.get("spans", []):
162
+ text = span.get("text", "")
163
+ if text == "":
164
+ continue
165
+ origin = span.get("origin") or (0.0, 0.0)
166
+ size = float(span.get("size") or 0.0)
167
+ baseline = float(origin[1])
168
+ raw = fitz.Rect(span["bbox"])
169
+ # Typst maths spans carry the whole font box (a 10pt symbol
170
+ # can report 66pt of height), which would inflate every
171
+ # block's `dst` and its overflow flag. Clamp the vertical
172
+ # extent to what a glyph can actually ink around its baseline.
173
+ top = max(raw.y0, baseline - size * 1.25) if size > 0 else raw.y0
174
+ bottom = min(raw.y1, baseline + size * 0.55) if size > 0 else raw.y1
175
+ if bottom <= top:
176
+ bottom = top + 1.0
177
+ spans.append({
178
+ "text": text,
179
+ "rect": fitz.Rect(raw.x0, top, raw.x1, bottom),
180
+ "size": size,
181
+ "baseline": baseline,
182
+ "line": line_number,
183
+ })
184
+ marker_index = {item["marker"]: index for index, item in enumerate(placed) if item["marker"] is not None}
185
+ marker_at = {}
186
+ for position, span in enumerate(spans):
187
+ for marker, index in marker_index.items():
188
+ if marker in span["text"]:
189
+ marker_at[position] = index
190
+ break
191
+ groups = [[] for _ in placed]
192
+ assigned = set()
193
+ for index, item in enumerate(placed):
194
+ if item["marker"] is not None:
195
+ continue
196
+ left, top, right, bottom = item["rect"]
197
+ for position, span in enumerate(spans):
198
+ if position in assigned or position in marker_at:
199
+ continue
200
+ rect = span["rect"]
201
+ # A display equation can be wider than the box reserved for it
202
+ # (it does not wrap) and its tall parts reach above the box, so
203
+ # the claim uses the baseline band and a wider horizontal reach
204
+ # instead of the ink box.
205
+ if not (left - 40 <= rect.x0 <= right + 40):
206
+ continue
207
+ if not (item["target"] - 20 <= span["baseline"] <= item["target"] + item["room"] + 20):
208
+ continue
209
+ groups[index].append(span)
210
+ assigned.add(position)
211
+ current = None
212
+ for position, span in enumerate(spans):
213
+ if position in marker_at:
214
+ current = marker_at[position]
215
+ continue
216
+ if position in assigned or current is None:
217
+ continue
218
+ groups[current].append(span)
219
+ assigned.add(position)
220
+ anchors = {}
221
+ for span in spans:
222
+ for marker, index in marker_index.items():
223
+ if marker in span["text"]:
224
+ anchors[index] = span
225
+ break
226
+ measured = []
227
+ for index, own in enumerate(groups):
228
+ text_spans = [span for span in own if span["text"] not in marker_index]
229
+ anchor = anchors.get(index)
230
+ if anchor is None and not text_spans:
231
+ measured.append(None)
232
+ continue
233
+ if not text_spans:
234
+ # The marker was found but its own text produced no spans: the
235
+ # baseline is exact, but there is no ink rectangle to report.
236
+ measured.append({
237
+ "bounds": None,
238
+ "size": 0.0,
239
+ "baseline": anchor["baseline"],
240
+ "lines": 0,
241
+ })
242
+ continue
243
+ bounds = text_spans[0]["rect"]
244
+ for span in text_spans[1:]:
245
+ bounds = bounds | span["rect"]
246
+ sizes = sorted(span["size"] for span in text_spans if span["size"] > 0)
247
+ # The first printed line's baseline: the largest span on that line.
248
+ # A superscript shares the line but reports a higher origin, and a
249
+ # display equation's marker sits at the placement top rather than on
250
+ # the equation, so neither the marker nor min(baseline) is right.
251
+ first_line = min(span["line"] for span in text_spans)
252
+ line_spans = [span for span in text_spans if span["line"] == first_line]
253
+ first_baseline = max(line_spans, key=lambda span: span["size"])["baseline"]
254
+ measured.append({
255
+ "bounds": bounds,
256
+ "size": sizes[len(sizes) // 2] if sizes else 0.0,
257
+ "baseline": first_baseline,
258
+ # Count extracted lines, not span tops: a superscript on a line
259
+ # is not a second line.
260
+ "lines": len({span["line"] for span in text_spans}),
261
+ })
262
+ return measured
263
+ finally:
264
+ document.close()
265
+
266
+
267
+ def plan_adjustments(placed, measured, font_pt, min_pt):
268
+ """Second-pass correction per block: vertical origin, then font size."""
269
+ adjustments = {}
270
+ limit = floor_pt(font_pt, min_pt)
271
+ for entry, row in zip(placed, measured):
272
+ if row is None:
273
+ continue
274
+ adjustment = {}
275
+ delta = row["baseline"] - entry["target"]
276
+ if abs(delta) > 0.05:
277
+ adjustment["y"] = max(0.0, entry["y"] - delta)
278
+ height = row["bounds"].height if row["bounds"] is not None else 0.0
279
+ if height > entry["room"] + 0.5 and entry["body"] > limit + 0.01:
280
+ scale = max(limit / font_pt, entry["room"] / height)
281
+ if scale < 0.999:
282
+ adjustment["scale"] = scale
283
+ if adjustment:
284
+ adjustments[entry["id"]] = adjustment
285
+ return adjustments
286
+
287
+
288
+ def write_layout(placed, measured, target, page_width, page_height, font_pt):
289
+ """Record where each block's translation landed, for the reader's boxes.
290
+
291
+ `box`/`baseline`/`leadingPt`/`align` are what a DOM text layer needs to put
292
+ the same text on the same printed line; `dst` stays the ink rectangle the
293
+ drawn frames use. The fields are additive: older sidecars simply lack them.
294
+ """
295
+ rows = []
296
+ for entry, row in zip(placed, measured):
297
+ if row is None or row["bounds"] is None:
298
+ continue
299
+ bounds = row["bounds"]
300
+ left, top, right, bottom = entry["rect"]
301
+ rows.append({
302
+ "id": entry["id"],
303
+ "dst": [
304
+ bounds.x0 / page_width,
305
+ bounds.y0 / page_height,
306
+ (bounds.x1 - bounds.x0) / page_width,
307
+ (bounds.y1 - bounds.y0) / page_height,
308
+ ],
309
+ # Where the block was placed: left/top/width of the text box in page
310
+ # fractions, and the printed baseline it was anchored to.
311
+ "box": [left / page_width, top / page_height,
312
+ (right - left) / page_width, (bottom - top) / page_height],
313
+ "baseline": round(entry["target"] / page_height, 5),
314
+ "leadingPt": round(entry["leading"], 2),
315
+ "align": entry["align"],
316
+ # The size the block was asked to render at; formulas legitimately use
317
+ # smaller script sizes, so the readable-size floor is checked against
318
+ # this rather than against the smallest glyph on the page.
319
+ "fontPt": round(entry["body"], 1),
320
+ "renderPt": round(row["size"], 1),
321
+ "lines": row["lines"],
322
+ "baselineDelta": round(row["baseline"] - entry["target"], 2),
323
+ "overflow": bool(bounds.height > entry["room"] + 0.5),
324
+ "scale": round(entry["body"] / font_pt, 3) if font_pt > 0 else 0.0,
325
+ })
326
+ try:
327
+ with open(target, "w", encoding="utf-8") as handle:
328
+ json.dump({"page": {"width": page_width, "height": page_height}, "blocks": rows},
329
+ handle, ensure_ascii=False)
330
+ return True
331
+ except Exception:
332
+ return False
@@ -6,15 +6,47 @@ Usage:
6
6
  The parsing is also importable: `blocks_for_page(path, number)` returns the same
7
7
  list, which is what the paragraph realigner uses instead of spawning this script
8
8
  (no pipes, no second interpreter).
9
+
10
+ Besides the paragraph box and its text, each block reports what the overlay needs
11
+ to sit the translation where the original sits: the first baseline, the printed
12
+ line spacing, the text alignment and the dominant font. The font size is the
13
+ character-weighted body size, not the largest span, so a heading inside a
14
+ paragraph cannot inflate the whole block.
9
15
  """
10
16
  import json
11
17
  import sys
12
18
 
13
19
  import fitz
14
20
 
21
+ # Long paragraphs used to be cut at 400 characters, so the model only saw the
22
+ # first part of a paragraph and guessed the tail from the page image. The cap is
23
+ # now only a request-size guard.
24
+ MAX_BLOCK_CHARS = 4000
25
+
26
+
27
+ def _align_of(line_boxes):
28
+ """How a block's lines line up: left / center / right / justify."""
29
+ if len(line_boxes) < 2:
30
+ return "left"
31
+ lefts = [box[0] for box in line_boxes]
32
+ rights = [box[2] for box in line_boxes]
33
+ centers = [(box[0] + box[2]) / 2 for box in line_boxes]
34
+ left_var = max(lefts) - min(lefts)
35
+ right_var = max(rights) - min(rights)
36
+ center_var = max(centers) - min(centers)
37
+ if left_var < 3.0 and right_var < 3.0:
38
+ return "justify"
39
+ if left_var < 3.0:
40
+ return "left"
41
+ if center_var < 3.0:
42
+ return "center"
43
+ if right_var < 3.0:
44
+ return "right"
45
+ return "left"
46
+
15
47
 
16
48
  def blocks_for_page(pdf_path, page_number):
17
- """Return the page's blocks: normalized bbox, relative size, kind and text."""
49
+ """Return the page's blocks: bbox, body size, text, baseline and alignment."""
18
50
  document = fitz.open(pdf_path)
19
51
  page = document[page_number - 1]
20
52
  width, height = page.rect.width, page.rect.height
@@ -25,16 +57,36 @@ def blocks_for_page(pdf_path, page_number):
25
57
  if block.get("type", 0) != 0:
26
58
  continue
27
59
  lines = block.get("lines", [])
28
- sizes = []
29
60
  text = []
61
+ weight = 0.0
62
+ chars = 0
63
+ line_boxes = []
64
+ baselines = []
65
+ fonts = {}
30
66
  for line in lines:
31
- for span in line.get("spans", []):
32
- sizes.append(span.get("size", 0))
67
+ spans = [span for span in line.get("spans", []) if span.get("text", "").strip() != ""]
68
+ if not spans:
69
+ continue
70
+ line_boxes.append(line["bbox"])
71
+ # The baseline comes from the largest span on the line: a superscript
72
+ # riding on the same line must not define the paragraph's baseline.
73
+ main = max(spans, key=lambda span: float(span.get("size") or 0.0))
74
+ origin = main.get("origin") or (0.0, line["bbox"][3])
75
+ baselines.append(float(origin[1]))
76
+ for span in spans:
77
+ size = float(span.get("size") or 0.0)
78
+ piece = span.get("text", "").strip()
79
+ count = max(1, len(piece))
80
+ weight += size * count
81
+ chars += count
33
82
  text.append(span.get("text", ""))
83
+ name = str(span.get("font") or "")
84
+ fonts[name] = fonts.get(name, 0) + count
34
85
  content = " ".join(part.strip() for part in text if part.strip())
35
86
  if content == "":
36
87
  continue
37
88
  bbox = block["bbox"]
89
+ body_size = weight / chars if chars > 0 else 0.0
38
90
  items.append({
39
91
  "bbox": [
40
92
  bbox[0] / width,
@@ -42,8 +94,11 @@ def blocks_for_page(pdf_path, page_number):
42
94
  (bbox[2] - bbox[0]) / width,
43
95
  (bbox[3] - bbox[1]) / height,
44
96
  ],
45
- "size": max(sizes) if sizes else 0,
46
- "text": content[:400],
97
+ "size": body_size,
98
+ "text": content[:MAX_BLOCK_CHARS],
99
+ "_lineBoxes": line_boxes,
100
+ "_baselines": baselines,
101
+ "_fonts": fonts,
47
102
  })
48
103
 
49
104
  def center(item):
@@ -72,22 +127,39 @@ def blocks_for_page(pdf_path, page_number):
72
127
  x1 = max(nearest["bbox"][0] + nearest["bbox"][2], small["bbox"][0] + small["bbox"][2])
73
128
  y1 = max(nearest["bbox"][1] + nearest["bbox"][3], small["bbox"][1] + small["bbox"][3])
74
129
  nearest["bbox"] = [x0, y0, x1 - x0, y1 - y0]
75
- nearest["text"] = f"{nearest['text']} {small['text']}".strip()[:400]
130
+ nearest["text"] = f"{nearest['text']} {small['text']}".strip()[:MAX_BLOCK_CHARS]
131
+ nearest["_lineBoxes"] = nearest["_lineBoxes"] + small["_lineBoxes"]
132
+ nearest["_baselines"] = nearest["_baselines"] + small["_baselines"]
133
+ for name, count in small["_fonts"].items():
134
+ nearest["_fonts"][name] = nearest["_fonts"].get(name, 0) + count
76
135
  items = keep
77
136
 
78
137
  ordered = sorted(item["size"] for item in items)
79
138
  median = ordered[len(ordered) // 2] if ordered else 1.0
80
139
  for index, item in enumerate(items):
140
+ line_boxes = item.pop("_lineBoxes")
141
+ baselines = sorted(item.pop("_baselines"))
142
+ fonts = item.pop("_fonts")
81
143
  item["id"] = f"b-{page_number:04d}-{index + 1:02d}"
82
144
  item["page"] = page_number
83
- left, top, width, height = item["bbox"]
84
- if top < 0.09 and width < 0.7:
145
+ left, top, width_n, height_n = item["bbox"]
146
+ if top < 0.09 and width_n < 0.7:
85
147
  item["kind"] = "heading"
86
- elif width < 0.62 and left > 0.12 and left + width < 0.9 and height < 0.05:
148
+ elif width_n < 0.62 and left > 0.12 and left + width_n < 0.9 and height_n < 0.05:
87
149
  item["kind"] = "formula"
88
150
  else:
89
151
  item["kind"] = "paragraph"
90
152
  item["size"] = item["size"] / median if median > 0 else 1.0
153
+ # Where the printed text sits: the overlay anchors the translation on this
154
+ # baseline instead of on the top edge of the box.
155
+ item["lines"] = len(baselines)
156
+ item["firstBaseline"] = baselines[0] / height if baselines else top + height_n
157
+ item["leading"] = (
158
+ (baselines[-1] - baselines[0]) / (len(baselines) - 1) / height
159
+ if len(baselines) > 1 else 0.0
160
+ )
161
+ item["align"] = _align_of(line_boxes)
162
+ item["font"] = max(fonts, key=fonts.get) if fonts else ""
91
163
 
92
164
  # Page numbers / footers: tiny blocks in the bottom margin carry no paragraph
93
165
  # content and were being misread as formulas.
@@ -19,6 +19,9 @@ import sys
19
19
 
20
20
  import fitz
21
21
 
22
+ # The Host picks the engine; the overlay renderer name arrives in the env.
23
+ OVERLAY_SCRIPT = os.environ.get("MATH_DESK_OVERLAY_SCRIPT", "").strip() or "md2overlay.py"
24
+
22
25
 
23
26
  def page_markdown(page_number, cache_dir):
24
27
  path = os.path.join(cache_dir, "page-%03d.md" % page_number)
@@ -196,7 +199,7 @@ def page_pdf(page_number, size, blocks, segments, font_class, work, tools_dir):
196
199
  json.dump(synthetic, handle, ensure_ascii=False)
197
200
  page_path = os.path.join(work, "page-%03d.pdf" % page_number)
198
201
  subprocess.run(
199
- [sys.executable, os.path.join(tools_dir, "md2overlay.py"), blocks_path, page_path,
202
+ [sys.executable, os.path.join(tools_dir, OVERLAY_SCRIPT), blocks_path, page_path,
200
203
  str(size[0]), str(size[1]), font_class],
201
204
  check=True,
202
205
  )
@@ -11,6 +11,8 @@ import tempfile
11
11
  import fitz
12
12
 
13
13
  source, cache_dir, out_path, tools_dir = sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4]
14
+ # The Host picks the engine; the overlay renderer name arrives in the env.
15
+ overlay_script = os.environ.get("MATH_DESK_OVERLAY_SCRIPT", "").strip() or "md2overlay.py"
14
16
 
15
17
  document = fitz.open(source)
16
18
  sizes = [[page.rect.width, page.rect.height] for page in document]
@@ -37,7 +39,7 @@ with tempfile.TemporaryDirectory(prefix="rebuild-overlay-") as work:
37
39
  continue
38
40
  page_pdf = os.path.join(work, "page-%03d.pdf" % (index + 1))
39
41
  result = subprocess.run(
40
- [sys.executable, os.path.join(tools_dir, "md2overlay.py"), blocks_path, page_pdf,
42
+ [sys.executable, os.path.join(tools_dir, overlay_script), blocks_path, page_pdf,
41
43
  str(size[0]), str(size[1]), font_class],
42
44
  capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=180,
43
45
  )
@@ -0,0 +1,158 @@
1
+ """Split one PDF into chapter files named the way the workbench reads them.
2
+
3
+ Local tool (T-10): no OCR, no encryption, no watermark — only the split the
4
+ plugin actually needs. Output names follow the workbench rule
5
+ `<id>_cNN_<title>_p<from>-<to>.pdf`, where the page numbers are 1-based physical
6
+ pages and `cNN` is the chapter code the reader sorts by.
7
+
8
+ Usage:
9
+ py split_pdf.py <input.pdf> <out-dir> --ranges "1-10,11-17,18-32" --id 书名
10
+ py split_pdf.py <input.pdf> <out-dir> --breaks "10,17" --id 书名
11
+ py split_pdf.py <input.pdf> <out-dir> --bookmarks --id 书名
12
+
13
+ `--breaks` means "cut after these pages": 10,17 gives 1-10, 11-17, 18-end.
14
+ `--bookmarks` reads the level-1 outline; each entry becomes one chapter and its
15
+ title is reused when the range has a single bookmark.
16
+ Ranges win over breaks, breaks win over bookmarks.
17
+ """
18
+ import argparse
19
+ import json
20
+ import os
21
+ import re
22
+ import sys
23
+
24
+ sys.stdout.reconfigure(encoding="utf-8", errors="replace")
25
+ sys.stderr.reconfigure(encoding="utf-8", errors="replace")
26
+
27
+ try:
28
+ import fitz
29
+ except ImportError: # pragma: no cover - PyMuPDF is a plugin dependency
30
+ raise SystemExit("需要 PyMuPDF:py -m pip install pymupdf")
31
+
32
+
33
+ def safe_title(text, fallback):
34
+ """A file-name-safe chapter title; the workbench only splits on `_`."""
35
+ cleaned = re.sub(r"[\\/:*?\"<>|\r\n\t_]+", " ", str(text or "")).strip()
36
+ cleaned = re.sub(r"\s+", "", cleaned)
37
+ return cleaned[:40] if cleaned else fallback
38
+
39
+
40
+ def parse_ranges(spec, page_count):
41
+ """`1-10,11-17` -> [(1, 10), (11, 17)], clamped to the document."""
42
+ ranges = []
43
+ for piece in str(spec).split(","):
44
+ piece = piece.strip()
45
+ if piece == "":
46
+ continue
47
+ match = re.fullmatch(r"(\d+)\s*(?:-\s*(\d+))?", piece)
48
+ if match is None:
49
+ raise SystemExit("看不懂的页码范围:%s(例:1-10,11-17)" % piece)
50
+ start = int(match.group(1))
51
+ end = int(match.group(2) or start)
52
+ if start < 1 or end < start or end > page_count:
53
+ raise SystemExit("页码范围超出文档:%s(共 %d 页)" % (piece, page_count))
54
+ ranges.append((start, end))
55
+ if ranges == []:
56
+ raise SystemExit("没有可拆分的页码范围")
57
+ return ranges
58
+
59
+
60
+ def ranges_from_breaks(spec, page_count):
61
+ """`10,17` -> 1-10, 11-17, 18-end (a trailing zero-length range is dropped)."""
62
+ cuts = []
63
+ for piece in str(spec).split(","):
64
+ piece = piece.strip()
65
+ if piece == "":
66
+ continue
67
+ if not piece.isdigit():
68
+ raise SystemExit("断点必须是页码:%s" % piece)
69
+ cuts.append(int(piece))
70
+ cuts = sorted({cut for cut in cuts if 0 < cut < page_count})
71
+ if cuts == []:
72
+ raise SystemExit("断点必须落在 1..%d 之内" % (page_count - 1))
73
+ ranges = []
74
+ start = 1
75
+ for cut in cuts:
76
+ ranges.append((start, cut))
77
+ start = cut + 1
78
+ if start <= page_count:
79
+ ranges.append((start, page_count))
80
+ return ranges
81
+
82
+
83
+ def ranges_from_bookmarks(doc):
84
+ """Level-1 outline entries -> chapter ranges plus their titles."""
85
+ entries = [(title, page) for level, title, page in doc.get_toc(simple=False) if level == 1 and page > 0]
86
+ if entries == []:
87
+ raise SystemExit("这本 PDF 没有一级书签,改用 --ranges 或 --breaks")
88
+ entries.sort(key=lambda item: item[1])
89
+ ranges = []
90
+ for index, (title, page) in enumerate(entries):
91
+ end = entries[index + 1][1] - 1 if index + 1 < len(entries) else doc.page_count
92
+ start = max(1, page)
93
+ if end < start:
94
+ continue
95
+ ranges.append((start, end, title))
96
+ return ranges
97
+
98
+
99
+ def write_parts(input_path, out_dir, parts, book_id):
100
+ """parts: [(from, to, title)] -> written file paths."""
101
+ os.makedirs(out_dir, exist_ok=True)
102
+ source = fitz.open(input_path)
103
+ written = []
104
+ try:
105
+ for index, (start, end, title) in enumerate(parts):
106
+ code = "c%02d" % index
107
+ name = "%s_%s_%s_p%03d-%03d.pdf" % (
108
+ safe_title(book_id, "book"), code, safe_title(title, "未命名"), start, end)
109
+ target = os.path.join(out_dir, name)
110
+ part = fitz.open()
111
+ try:
112
+ part.insert_pdf(source, from_page=start - 1, to_page=end - 1)
113
+ part.save(target, garbage=3, deflate=True)
114
+ finally:
115
+ part.close()
116
+ written.append({"code": code, "from": start, "to": end, "title": title, "path": target})
117
+ print("%s %d-%d %s" % (code, start, end, name))
118
+ finally:
119
+ source.close()
120
+ manifest = os.path.join(out_dir, "拆分清单.json")
121
+ with open(manifest, "w", encoding="utf-8") as handle:
122
+ json.dump({"input": os.path.abspath(input_path), "parts": written}, handle, ensure_ascii=False, indent=1)
123
+ return written, manifest
124
+
125
+
126
+ def main(argv=None):
127
+ parser = argparse.ArgumentParser(description="把一本 PDF 按章节拆成书库可读的分片")
128
+ parser.add_argument("input", help="整本 PDF")
129
+ parser.add_argument("outdir", help="输出目录(通常是 <书库>/分片/<书id>)")
130
+ parser.add_argument("--id", default="", help="书 id,用于文件名前缀;缺省取输入文件名")
131
+ parser.add_argument("--ranges", default="", help="页码范围:1-10,11-17")
132
+ parser.add_argument("--breaks", default="", help="断点:10,17(= 在第 10、17 页后切开)")
133
+ parser.add_argument("--bookmarks", action="store_true", help="按一级书签切章")
134
+ args = parser.parse_args(argv)
135
+
136
+ if not os.path.isfile(args.input):
137
+ raise SystemExit("找不到输入文件:%s" % args.input)
138
+ source = fitz.open(args.input)
139
+ try:
140
+ page_count = source.page_count
141
+ if args.ranges:
142
+ parts = [(start, end, "") for start, end in parse_ranges(args.ranges, page_count)]
143
+ elif args.breaks:
144
+ parts = [(start, end, "") for start, end in ranges_from_breaks(args.breaks, page_count)]
145
+ elif args.bookmarks:
146
+ parts = ranges_from_bookmarks(source)
147
+ else:
148
+ raise SystemExit("请给出 --ranges、--breaks 或 --bookmarks 之一")
149
+ book_id = args.id or os.path.splitext(os.path.basename(args.input))[0]
150
+ written, manifest = write_parts(args.input, args.outdir, parts, book_id)
151
+ print("共 %d 份,清单:%s" % (len(written), manifest))
152
+ return 0
153
+ finally:
154
+ source.close()
155
+
156
+
157
+ if __name__ == "__main__":
158
+ sys.exit(main())