dsh-pdf-workbench 1.3.3 → 1.3.4
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.
- package/LICENSE +21 -21
- package/README.md +199 -199
- package/docs/RELEASE.md +119 -119
- package/icon.svg +6 -6
- package/index.js +10 -2
- package/package.json +1 -1
- package/screenshots.json +8 -8
- package/src/client/host-ui-entry.js +11 -11
- package/src/client/react-jsx-runtime.cjs +21 -21
- package/src/client/viewer.js +80 -80
- package/src/host/routes.js +10 -0
- package/tools/AGENTS.md +33 -33
- package/tools/README.md +138 -138
- package/tools/auto_chapters.py +122 -122
- package/tools/dsfile.mjs +198 -198
- package/tools/export_chapter.py +108 -108
- package/tools/export_page.py +91 -91
- package/tools/md2overlay.py +200 -200
- package/tools/md2tex.py +422 -422
- package/tools/pdf_blocks.py +110 -110
- package/tools/pdf_fontsize.py +20 -20
- package/tools/pdf_merge.py +15 -15
- package/tools/pdf_pagesizes.py +8 -8
- package/tools/pdf_raster.py +21 -21
- package/tools/pdfkit.py +896 -896
- package/tools/realign_overlay.py +248 -248
- package/tools/rebuild_overlay.py +55 -55
- package/tools/rename_chapters.py +93 -93
- package/tools//350/247/204/350/214/203/00_/345/205/261/345/220/214/347/272/246/345/256/232.md +142 -142
- package/tools//350/247/204/350/214/203/01_/346/226/207/346/234/254/346/217/220/345/217/226.md +204 -204
- package/tools//350/247/204/350/214/203/02_/347/255/224/347/226/221.md +61 -61
- package/tools//350/247/204/350/214/203/03_/344/271/240/351/242/230/350/247/243/347/255/224.md +77 -77
- 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
- package/vendor/cmaps/LICENSE.txt +36 -36
- package/vendor/fonts/excalifont/OFL.txt +98 -98
- package/vendor/fonts/zhhand/OFL.txt +99 -99
- package/vendor/host-ui.cjs +1719 -1719
- package/vendor/host-ui.css +799 -799
- package/vendor/pdf.min.mjs +28 -28
- package/vendor/pdf.worker.min.mjs +28 -28
- package/vendor/pdfjs-LICENSE.txt +177 -177
- package/vendor/rough/LICENSE +21 -21
- package/vendor/rough/rough.mjs +1 -1
- package/vendor/wasm/LICENSE_JBIG2 +196 -196
- package/vendor/wasm/LICENSE_OPENJPEG +39 -39
- package/vendor/wasm/LICENSE_PDFJS_JBIG2 +13 -13
- package/vendor/wasm/LICENSE_PDFJS_OPENJPEG +22 -22
- package/vendor/wasm/LICENSE_PDFJS_QCMS +19 -19
- package/vendor/wasm/LICENSE_QCMS +21 -21
- package/vendor/wasm/jbig2_nowasm_fallback.js +15 -15
- package/vendor/wasm/openjpeg_nowasm_fallback.js +17 -17
- package//345/256/211/350/243/205/344/270/216/345/210/206/345/217/221.md +1 -1
- package/tools/node.cmd +0 -3
- package/tools/py.cmd +0 -3
package/tools/export_page.py
CHANGED
|
@@ -1,91 +1,91 @@
|
|
|
1
|
-
"""Compose one exported PDF page: original + revealed translation + annotations.
|
|
2
|
-
|
|
3
|
-
Usage:
|
|
4
|
-
python export_page.py <source.pdf> <overlay.pdf|-> <page> <masks.json|-> <annots.json|-> <out.pdf>
|
|
5
|
-
|
|
6
|
-
`overlay.pdf` is the bbox-positioned translation (`<stem>_overlay.pdf`); each mask
|
|
7
|
-
is a normalized `{x,y,w,h}` window that reveals that region of the overlay page.
|
|
8
|
-
Annotations are normalized strokes (`{kind:'stroke', points:[[x,y]...], color,
|
|
9
|
-
width}`) and text notes (`{kind:'text', x, y, text, color}`).
|
|
10
|
-
"""
|
|
11
|
-
import json
|
|
12
|
-
import os
|
|
13
|
-
import sys
|
|
14
|
-
|
|
15
|
-
import fitz
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
def rgb(value, fallback=(0.12, 0.12, 0.12)):
|
|
19
|
-
text = str(value or "").strip().lstrip("#")
|
|
20
|
-
if len(text) == 3:
|
|
21
|
-
text = "".join(char * 2 for char in text)
|
|
22
|
-
if len(text) != 6:
|
|
23
|
-
return fallback
|
|
24
|
-
try:
|
|
25
|
-
return tuple(int(text[index:index + 2], 16) / 255.0 for index in (0, 2, 4))
|
|
26
|
-
except ValueError:
|
|
27
|
-
return fallback
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
source_path, overlay_path, page_number, masks_path, annots_path, out_path = sys.argv[1:7]
|
|
31
|
-
index = max(0, int(page_number) - 1)
|
|
32
|
-
masks = []
|
|
33
|
-
if masks_path != "-":
|
|
34
|
-
with open(masks_path, encoding="utf-8") as handle:
|
|
35
|
-
masks = json.load(handle)
|
|
36
|
-
annots = []
|
|
37
|
-
if annots_path != "-":
|
|
38
|
-
with open(annots_path, encoding="utf-8") as handle:
|
|
39
|
-
annots = json.load(handle)
|
|
40
|
-
|
|
41
|
-
source = fitz.open(source_path)
|
|
42
|
-
index = min(index, source.page_count - 1)
|
|
43
|
-
doc = fitz.open()
|
|
44
|
-
page = doc.new_page(width=source[0].rect.width, height=source[index].rect.height)
|
|
45
|
-
box = page.rect
|
|
46
|
-
page.show_pdf_page(box, source, index)
|
|
47
|
-
|
|
48
|
-
if overlay_path != "-" and os.path.exists(overlay_path):
|
|
49
|
-
overlay = fitz.open(overlay_path)
|
|
50
|
-
if index < overlay.page_count:
|
|
51
|
-
for mask in masks:
|
|
52
|
-
try:
|
|
53
|
-
rect = fitz.Rect(
|
|
54
|
-
float(mask["x"]) * box.width,
|
|
55
|
-
float(mask["y"]) * box.height,
|
|
56
|
-
(float(mask["x"]) + float(mask["w"])) * box.width,
|
|
57
|
-
(float(mask["y"]) + float(mask["h"])) * box.height,
|
|
58
|
-
)
|
|
59
|
-
except (KeyError, TypeError, ValueError):
|
|
60
|
-
continue
|
|
61
|
-
if rect.is_empty or rect.width <= 1 or rect.height <= 1:
|
|
62
|
-
continue
|
|
63
|
-
# Same page size on both sides, so the clip equals the target rect.
|
|
64
|
-
page.show_pdf_page(rect, overlay, index, clip=rect)
|
|
65
|
-
|
|
66
|
-
for entry in annots:
|
|
67
|
-
color = rgb(entry.get("color"))
|
|
68
|
-
if entry.get("kind") == "text":
|
|
69
|
-
text = str(entry.get("text") or "")
|
|
70
|
-
if text.strip() == "":
|
|
71
|
-
continue
|
|
72
|
-
x = float(entry.get("x", 0)) * box.width
|
|
73
|
-
y = float(entry.get("y", 0)) * box.height
|
|
74
|
-
for offset, line in enumerate(text.split("\n")):
|
|
75
|
-
page.insert_text((x, y + 14 + offset * 18), line, fontsize=14,
|
|
76
|
-
fontname="china-s", color=color)
|
|
77
|
-
continue
|
|
78
|
-
points = [
|
|
79
|
-
fitz.Point(float(point[0]) * box.width, float(point[1]) * box.height)
|
|
80
|
-
for point in entry.get("points") or []
|
|
81
|
-
if isinstance(point, (list, tuple)) and len(point) >= 2
|
|
82
|
-
]
|
|
83
|
-
if len(points) < 2:
|
|
84
|
-
continue
|
|
85
|
-
page.draw_polyline(points, color=color, width=float(entry.get("width") or 2),
|
|
86
|
-
lineCap=1, lineJoin=1, overlay=True)
|
|
87
|
-
|
|
88
|
-
tmp = out_path + ".tmp.pdf"
|
|
89
|
-
doc.save(tmp)
|
|
90
|
-
os.replace(tmp, out_path)
|
|
91
|
-
print(out_path)
|
|
1
|
+
"""Compose one exported PDF page: original + revealed translation + annotations.
|
|
2
|
+
|
|
3
|
+
Usage:
|
|
4
|
+
python export_page.py <source.pdf> <overlay.pdf|-> <page> <masks.json|-> <annots.json|-> <out.pdf>
|
|
5
|
+
|
|
6
|
+
`overlay.pdf` is the bbox-positioned translation (`<stem>_overlay.pdf`); each mask
|
|
7
|
+
is a normalized `{x,y,w,h}` window that reveals that region of the overlay page.
|
|
8
|
+
Annotations are normalized strokes (`{kind:'stroke', points:[[x,y]...], color,
|
|
9
|
+
width}`) and text notes (`{kind:'text', x, y, text, color}`).
|
|
10
|
+
"""
|
|
11
|
+
import json
|
|
12
|
+
import os
|
|
13
|
+
import sys
|
|
14
|
+
|
|
15
|
+
import fitz
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def rgb(value, fallback=(0.12, 0.12, 0.12)):
|
|
19
|
+
text = str(value or "").strip().lstrip("#")
|
|
20
|
+
if len(text) == 3:
|
|
21
|
+
text = "".join(char * 2 for char in text)
|
|
22
|
+
if len(text) != 6:
|
|
23
|
+
return fallback
|
|
24
|
+
try:
|
|
25
|
+
return tuple(int(text[index:index + 2], 16) / 255.0 for index in (0, 2, 4))
|
|
26
|
+
except ValueError:
|
|
27
|
+
return fallback
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
source_path, overlay_path, page_number, masks_path, annots_path, out_path = sys.argv[1:7]
|
|
31
|
+
index = max(0, int(page_number) - 1)
|
|
32
|
+
masks = []
|
|
33
|
+
if masks_path != "-":
|
|
34
|
+
with open(masks_path, encoding="utf-8") as handle:
|
|
35
|
+
masks = json.load(handle)
|
|
36
|
+
annots = []
|
|
37
|
+
if annots_path != "-":
|
|
38
|
+
with open(annots_path, encoding="utf-8") as handle:
|
|
39
|
+
annots = json.load(handle)
|
|
40
|
+
|
|
41
|
+
source = fitz.open(source_path)
|
|
42
|
+
index = min(index, source.page_count - 1)
|
|
43
|
+
doc = fitz.open()
|
|
44
|
+
page = doc.new_page(width=source[0].rect.width, height=source[index].rect.height)
|
|
45
|
+
box = page.rect
|
|
46
|
+
page.show_pdf_page(box, source, index)
|
|
47
|
+
|
|
48
|
+
if overlay_path != "-" and os.path.exists(overlay_path):
|
|
49
|
+
overlay = fitz.open(overlay_path)
|
|
50
|
+
if index < overlay.page_count:
|
|
51
|
+
for mask in masks:
|
|
52
|
+
try:
|
|
53
|
+
rect = fitz.Rect(
|
|
54
|
+
float(mask["x"]) * box.width,
|
|
55
|
+
float(mask["y"]) * box.height,
|
|
56
|
+
(float(mask["x"]) + float(mask["w"])) * box.width,
|
|
57
|
+
(float(mask["y"]) + float(mask["h"])) * box.height,
|
|
58
|
+
)
|
|
59
|
+
except (KeyError, TypeError, ValueError):
|
|
60
|
+
continue
|
|
61
|
+
if rect.is_empty or rect.width <= 1 or rect.height <= 1:
|
|
62
|
+
continue
|
|
63
|
+
# Same page size on both sides, so the clip equals the target rect.
|
|
64
|
+
page.show_pdf_page(rect, overlay, index, clip=rect)
|
|
65
|
+
|
|
66
|
+
for entry in annots:
|
|
67
|
+
color = rgb(entry.get("color"))
|
|
68
|
+
if entry.get("kind") == "text":
|
|
69
|
+
text = str(entry.get("text") or "")
|
|
70
|
+
if text.strip() == "":
|
|
71
|
+
continue
|
|
72
|
+
x = float(entry.get("x", 0)) * box.width
|
|
73
|
+
y = float(entry.get("y", 0)) * box.height
|
|
74
|
+
for offset, line in enumerate(text.split("\n")):
|
|
75
|
+
page.insert_text((x, y + 14 + offset * 18), line, fontsize=14,
|
|
76
|
+
fontname="china-s", color=color)
|
|
77
|
+
continue
|
|
78
|
+
points = [
|
|
79
|
+
fitz.Point(float(point[0]) * box.width, float(point[1]) * box.height)
|
|
80
|
+
for point in entry.get("points") or []
|
|
81
|
+
if isinstance(point, (list, tuple)) and len(point) >= 2
|
|
82
|
+
]
|
|
83
|
+
if len(points) < 2:
|
|
84
|
+
continue
|
|
85
|
+
page.draw_polyline(points, color=color, width=float(entry.get("width") or 2),
|
|
86
|
+
lineCap=1, lineJoin=1, overlay=True)
|
|
87
|
+
|
|
88
|
+
tmp = out_path + ".tmp.pdf"
|
|
89
|
+
doc.save(tmp)
|
|
90
|
+
os.replace(tmp, out_path)
|
|
91
|
+
print(out_path)
|
package/tools/md2overlay.py
CHANGED
|
@@ -1,200 +1,200 @@
|
|
|
1
|
-
"""Render one page's translated blocks at their original bbox positions.
|
|
2
|
-
|
|
3
|
-
Usage:
|
|
4
|
-
python md2overlay.py <blocks.json> <out.pdf> <page-width-pt> <page-height-pt> <font-class>
|
|
5
|
-
"""
|
|
6
|
-
import json
|
|
7
|
-
import os
|
|
8
|
-
import shutil
|
|
9
|
-
import subprocess
|
|
10
|
-
import sys
|
|
11
|
-
|
|
12
|
-
from md2tex import cjk_font, convert, sanitize_display_math
|
|
13
|
-
|
|
14
|
-
blocks_path, out_path = sys.argv[1], sys.argv[2]
|
|
15
|
-
page_width = float(sys.argv[3])
|
|
16
|
-
page_height = float(sys.argv[4])
|
|
17
|
-
font_class = sys.argv[5] if len(sys.argv) > 5 else "10pt"
|
|
18
|
-
font_pt = float(font_class.replace("pt", ""))
|
|
19
|
-
|
|
20
|
-
with open(blocks_path, encoding="utf-8") as handle:
|
|
21
|
-
blocks = json.load(handle)
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
def overlaps_x(left, right):
|
|
25
|
-
"""True when two blocks share horizontal space, i.e. stack vertically."""
|
|
26
|
-
return not (left[0] + left[2] <= right[0] or right[0] + right[2] <= left[0])
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
def same_line(first, second):
|
|
30
|
-
"""True when two boxes really share a printed line.
|
|
31
|
-
|
|
32
|
-
Boxes that merely touch by a fraction of a point must not count: a paragraph
|
|
33
|
-
and the heading right under it were treated as one line, and the heading got
|
|
34
|
-
pushed to the page edge."""
|
|
35
|
-
first_top, first_bottom = float(first[1]), float(first[1]) + float(first[3])
|
|
36
|
-
second_top, second_bottom = float(second[1]), float(second[1]) + float(second[3])
|
|
37
|
-
overlap = min(first_bottom, second_bottom) - max(first_top, second_top)
|
|
38
|
-
return overlap > 0.5 * min(float(first[3]), float(second[3]))
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
def room_below(block):
|
|
42
|
-
"""Points available from this block's top to the next block that sits under
|
|
43
|
-
it. Text may use the page's white space but must never run into a neighbour;
|
|
44
|
-
that balance is what keeps a tightened paragraph readable instead of 3pt."""
|
|
45
|
-
x, y, width, height = [float(value) for value in block.get("bbox") or [0, 0, 1, 1]]
|
|
46
|
-
limit = page_height - y * page_height - 4.0
|
|
47
|
-
for other in blocks:
|
|
48
|
-
if other is block:
|
|
49
|
-
continue
|
|
50
|
-
other_box = other.get("bbox") or [0, 0, 1, 1]
|
|
51
|
-
if not overlaps_x([x, y, width], other_box):
|
|
52
|
-
continue
|
|
53
|
-
gap = (float(other_box[1]) - y) * page_height
|
|
54
|
-
# A box that starts barely below this one is a fragment on the same
|
|
55
|
-
# line, not something underneath: counting it squeezed blocks to 4pt.
|
|
56
|
-
if max(2.0, font_pt * 0.6) < gap < limit:
|
|
57
|
-
limit = gap
|
|
58
|
-
return max(6.0, limit)
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
def room_right(block):
|
|
62
|
-
"""Normalized right edge this block may use: its own width or the start of
|
|
63
|
-
the next block beside it. Short blocks such as "if dim V = n." were forced
|
|
64
|
-
into two lines by their narrow box and then shrank to 4pt; letting them use
|
|
65
|
-
the empty space beside them keeps them one readable line."""
|
|
66
|
-
x, y, width, height = [float(value) for value in block.get("bbox") or [0, 0, 1, 1]]
|
|
67
|
-
right = x + width
|
|
68
|
-
limit = 0.985
|
|
69
|
-
for other in blocks:
|
|
70
|
-
if other is block:
|
|
71
|
-
continue
|
|
72
|
-
other_box = other.get("bbox") or [0, 0, 1, 1]
|
|
73
|
-
if not same_line(block.get("bbox") or [0, 0, 1, 1], other_box):
|
|
74
|
-
continue
|
|
75
|
-
start = float(other_box[0])
|
|
76
|
-
if start > right + 0.005:
|
|
77
|
-
limit = min(limit, start - 0.004)
|
|
78
|
-
return max(x + 0.08, limit)
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
def inline_formula(md):
|
|
82
|
-
"""Turn a standalone `$$...$$` block into one inline math run.
|
|
83
|
-
|
|
84
|
-
A formula block's box is one line tall in the original, while a display
|
|
85
|
-
equation needs about twice that; rendering it as display forced adjustbox to
|
|
86
|
-
shrink it to 6pt. Inline keeps it the same optical size as the body text."""
|
|
87
|
-
body = md.strip()
|
|
88
|
-
if body.startswith("$$") and body.endswith("$$") and body.count("$$") == 2:
|
|
89
|
-
return "$%s$" % " ".join(body[2:-2].split())
|
|
90
|
-
return ""
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
def start_x(block):
|
|
94
|
-
"""Left edge to use, pushed right past a same-line neighbour it would overlap.
|
|
95
|
-
|
|
96
|
-
PyMuPDF sometimes splits one printed line into two boxes whose x ranges
|
|
97
|
-
overlap ("p⁰ = …" and "(g 为 G 的阶)。"). Drawn at their own x the two runs
|
|
98
|
-
collide, because the Chinese formula is wider than the English one; starting
|
|
99
|
-
the right-hand run after the left run keeps the line readable."""
|
|
100
|
-
x, y, width, height = [float(value) for value in block.get("bbox") or [0, 0, 1, 1]]
|
|
101
|
-
for other in blocks:
|
|
102
|
-
if other is block:
|
|
103
|
-
continue
|
|
104
|
-
other_box = other.get("bbox") or [0, 0, 1, 1]
|
|
105
|
-
if not same_line(block.get("bbox") or [0, 0, 1, 1], other_box):
|
|
106
|
-
continue
|
|
107
|
-
other_left, other_right = float(other_box[0]), float(other_box[0]) + float(other_box[2])
|
|
108
|
-
if other_left < x - 0.002 and other_right > x + 0.01:
|
|
109
|
-
x = min(0.9, other_right + 0.006)
|
|
110
|
-
return x
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
parts = []
|
|
114
|
-
for block in blocks:
|
|
115
|
-
md = (block.get("md") or "").strip()
|
|
116
|
-
if md == "":
|
|
117
|
-
continue
|
|
118
|
-
bbox = block.get("bbox") or [0, 0, 1, 1]
|
|
119
|
-
x, y, width, _height = [float(value) for value in bbox]
|
|
120
|
-
room = room_below(block)
|
|
121
|
-
body = ""
|
|
122
|
-
left = start_x(block)
|
|
123
|
-
x_pt = max(0.0, left * page_width)
|
|
124
|
-
y_pt = max(0.0, y * page_height)
|
|
125
|
-
# Keep every block inside its own box width. Borrowing the space to the
|
|
126
|
-
# right made the translation wider than the box the reader draws around the
|
|
127
|
-
# original text, so the reveal clipped whole words; wrapping (and, when
|
|
128
|
-
# really tight, scaling) stays inside the block instead.
|
|
129
|
-
w_pt = max(40.0, min(width * page_width, page_width - x_pt - 4.0))
|
|
130
|
-
# Very narrow boxes ("if dim V = n.") cannot hold one Chinese line at body
|
|
131
|
-
# size and used to collapse to 4pt after wrapping. A slightly smaller face
|
|
132
|
-
# keeps them on one line and inside the box. The block's own printed size
|
|
133
|
-
# (pdf_blocks reports it relative to the page's body text) keeps headings
|
|
134
|
-
# and titles at their larger look instead of shrinking them to body size.
|
|
135
|
-
block_scale = float(block.get("size") or 1.0)
|
|
136
|
-
block_scale = max(0.85, min(1.6, block_scale))
|
|
137
|
-
body_pt = font_pt * block_scale * (0.8 if w_pt < 90.0 else 1.0)
|
|
138
|
-
if room < body_pt * 2.6 and "$$" in md:
|
|
139
|
-
# Too little room for a display equation: keep the math inline, including
|
|
140
|
-
# prose that carries an inline `$$...$$` fragment.
|
|
141
|
-
body = inline_formula(md)
|
|
142
|
-
if body == "":
|
|
143
|
-
body = convert(md.replace("$$", "$").split("\n"), "", drop_leading_heading=False)
|
|
144
|
-
if body == "":
|
|
145
|
-
# Same normalization the reading PDF gets: display math rebuilt on its own
|
|
146
|
-
# lines. Without it, a one-line `$$...$$` swallowed the prose after it and
|
|
147
|
-
# the paragraph came out as broken math.
|
|
148
|
-
body = convert(sanitize_display_math(md).split("\n"), "", drop_leading_heading=False)
|
|
149
|
-
if body.strip() == "":
|
|
150
|
-
continue
|
|
151
|
-
# Cap the block at the white space below it: a Chinese paragraph is often
|
|
152
|
-
# taller than the English it replaces. Text may borrow a paragraph gap but
|
|
153
|
-
# never runs into the next block, and adjustbox only shrinks when the text
|
|
154
|
-
# still exceeds that room, so most blocks keep their natural size.
|
|
155
|
-
h_pt = room
|
|
156
|
-
parts.append(
|
|
157
|
-
"\\begin{textblock}{%.2f}(%.2f,%.2f)\n"
|
|
158
|
-
"\\begin{adjustbox}{max width=%.2fpt,max totalheight=%.2fpt}\n"
|
|
159
|
-
"\\begin{minipage}[t]{%.2fpt}\\raggedright\\fontsize{%.1f}{%.1f}\\selectfont\n%s\n\\end{minipage}\n"
|
|
160
|
-
"\\end{adjustbox}\n"
|
|
161
|
-
"\\end{textblock}\n"
|
|
162
|
-
% (w_pt, x_pt, y_pt, w_pt, h_pt, w_pt, body_pt, body_pt * 1.25, body)
|
|
163
|
-
)
|
|
164
|
-
|
|
165
|
-
tex = r"""\documentclass[UTF8,%s]{ctexart}
|
|
166
|
-
\usepackage[paperwidth=%.4fin,paperheight=%.4fin,margin=0pt]{geometry}
|
|
167
|
-
\usepackage{fontspec}
|
|
168
|
-
\setCJKmainfont{%s}
|
|
169
|
-
\usepackage{amsmath,amssymb}
|
|
170
|
-
\usepackage[absolute,overlay]{textpos}
|
|
171
|
-
\usepackage{adjustbox}
|
|
172
|
-
\setlength{\TPHorizModule}{1pt}
|
|
173
|
-
\setlength{\TPVertModule}{1pt}
|
|
174
|
-
\pagestyle{empty}
|
|
175
|
-
\begin{document}
|
|
176
|
-
%s
|
|
177
|
-
\end{document}
|
|
178
|
-
""" % (font_class, page_width / 72.0, page_height / 72.0, cjk_font(), "\n".join(parts))
|
|
179
|
-
|
|
180
|
-
# Build next to the output instead of a fresh temp directory: some sandboxes
|
|
181
|
-
# allow writes in the destination directory but not in a mkdtemp directory.
|
|
182
|
-
work = os.path.abspath(out_path) + ".work"
|
|
183
|
-
os.makedirs(work, exist_ok=True)
|
|
184
|
-
tex_path = os.path.join(work, "doc.tex")
|
|
185
|
-
pdf_path = os.path.join(work, "doc.pdf")
|
|
186
|
-
try:
|
|
187
|
-
with open(tex_path, "w", encoding="utf-8") as handle:
|
|
188
|
-
handle.write(tex)
|
|
189
|
-
|
|
190
|
-
result = subprocess.run(
|
|
191
|
-
["xelatex", "-interaction=nonstopmode", "doc.tex"],
|
|
192
|
-
cwd=work, capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=180,
|
|
193
|
-
)
|
|
194
|
-
if not os.path.exists(pdf_path):
|
|
195
|
-
raise SystemExit("xelatex failed: " + (result.stdout or "")[-800:])
|
|
196
|
-
|
|
197
|
-
os.replace(pdf_path, out_path)
|
|
198
|
-
finally:
|
|
199
|
-
shutil.rmtree(work, ignore_errors=True)
|
|
200
|
-
print(out_path)
|
|
1
|
+
"""Render one page's translated blocks at their original bbox positions.
|
|
2
|
+
|
|
3
|
+
Usage:
|
|
4
|
+
python md2overlay.py <blocks.json> <out.pdf> <page-width-pt> <page-height-pt> <font-class>
|
|
5
|
+
"""
|
|
6
|
+
import json
|
|
7
|
+
import os
|
|
8
|
+
import shutil
|
|
9
|
+
import subprocess
|
|
10
|
+
import sys
|
|
11
|
+
|
|
12
|
+
from md2tex import cjk_font, convert, sanitize_display_math
|
|
13
|
+
|
|
14
|
+
blocks_path, out_path = sys.argv[1], sys.argv[2]
|
|
15
|
+
page_width = float(sys.argv[3])
|
|
16
|
+
page_height = float(sys.argv[4])
|
|
17
|
+
font_class = sys.argv[5] if len(sys.argv) > 5 else "10pt"
|
|
18
|
+
font_pt = float(font_class.replace("pt", ""))
|
|
19
|
+
|
|
20
|
+
with open(blocks_path, encoding="utf-8") as handle:
|
|
21
|
+
blocks = json.load(handle)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def overlaps_x(left, right):
|
|
25
|
+
"""True when two blocks share horizontal space, i.e. stack vertically."""
|
|
26
|
+
return not (left[0] + left[2] <= right[0] or right[0] + right[2] <= left[0])
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def same_line(first, second):
|
|
30
|
+
"""True when two boxes really share a printed line.
|
|
31
|
+
|
|
32
|
+
Boxes that merely touch by a fraction of a point must not count: a paragraph
|
|
33
|
+
and the heading right under it were treated as one line, and the heading got
|
|
34
|
+
pushed to the page edge."""
|
|
35
|
+
first_top, first_bottom = float(first[1]), float(first[1]) + float(first[3])
|
|
36
|
+
second_top, second_bottom = float(second[1]), float(second[1]) + float(second[3])
|
|
37
|
+
overlap = min(first_bottom, second_bottom) - max(first_top, second_top)
|
|
38
|
+
return overlap > 0.5 * min(float(first[3]), float(second[3]))
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def room_below(block):
|
|
42
|
+
"""Points available from this block's top to the next block that sits under
|
|
43
|
+
it. Text may use the page's white space but must never run into a neighbour;
|
|
44
|
+
that balance is what keeps a tightened paragraph readable instead of 3pt."""
|
|
45
|
+
x, y, width, height = [float(value) for value in block.get("bbox") or [0, 0, 1, 1]]
|
|
46
|
+
limit = page_height - y * page_height - 4.0
|
|
47
|
+
for other in blocks:
|
|
48
|
+
if other is block:
|
|
49
|
+
continue
|
|
50
|
+
other_box = other.get("bbox") or [0, 0, 1, 1]
|
|
51
|
+
if not overlaps_x([x, y, width], other_box):
|
|
52
|
+
continue
|
|
53
|
+
gap = (float(other_box[1]) - y) * page_height
|
|
54
|
+
# A box that starts barely below this one is a fragment on the same
|
|
55
|
+
# line, not something underneath: counting it squeezed blocks to 4pt.
|
|
56
|
+
if max(2.0, font_pt * 0.6) < gap < limit:
|
|
57
|
+
limit = gap
|
|
58
|
+
return max(6.0, limit)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def room_right(block):
|
|
62
|
+
"""Normalized right edge this block may use: its own width or the start of
|
|
63
|
+
the next block beside it. Short blocks such as "if dim V = n." were forced
|
|
64
|
+
into two lines by their narrow box and then shrank to 4pt; letting them use
|
|
65
|
+
the empty space beside them keeps them one readable line."""
|
|
66
|
+
x, y, width, height = [float(value) for value in block.get("bbox") or [0, 0, 1, 1]]
|
|
67
|
+
right = x + width
|
|
68
|
+
limit = 0.985
|
|
69
|
+
for other in blocks:
|
|
70
|
+
if other is block:
|
|
71
|
+
continue
|
|
72
|
+
other_box = other.get("bbox") or [0, 0, 1, 1]
|
|
73
|
+
if not same_line(block.get("bbox") or [0, 0, 1, 1], other_box):
|
|
74
|
+
continue
|
|
75
|
+
start = float(other_box[0])
|
|
76
|
+
if start > right + 0.005:
|
|
77
|
+
limit = min(limit, start - 0.004)
|
|
78
|
+
return max(x + 0.08, limit)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def inline_formula(md):
|
|
82
|
+
"""Turn a standalone `$$...$$` block into one inline math run.
|
|
83
|
+
|
|
84
|
+
A formula block's box is one line tall in the original, while a display
|
|
85
|
+
equation needs about twice that; rendering it as display forced adjustbox to
|
|
86
|
+
shrink it to 6pt. Inline keeps it the same optical size as the body text."""
|
|
87
|
+
body = md.strip()
|
|
88
|
+
if body.startswith("$$") and body.endswith("$$") and body.count("$$") == 2:
|
|
89
|
+
return "$%s$" % " ".join(body[2:-2].split())
|
|
90
|
+
return ""
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def start_x(block):
|
|
94
|
+
"""Left edge to use, pushed right past a same-line neighbour it would overlap.
|
|
95
|
+
|
|
96
|
+
PyMuPDF sometimes splits one printed line into two boxes whose x ranges
|
|
97
|
+
overlap ("p⁰ = …" and "(g 为 G 的阶)。"). Drawn at their own x the two runs
|
|
98
|
+
collide, because the Chinese formula is wider than the English one; starting
|
|
99
|
+
the right-hand run after the left run keeps the line readable."""
|
|
100
|
+
x, y, width, height = [float(value) for value in block.get("bbox") or [0, 0, 1, 1]]
|
|
101
|
+
for other in blocks:
|
|
102
|
+
if other is block:
|
|
103
|
+
continue
|
|
104
|
+
other_box = other.get("bbox") or [0, 0, 1, 1]
|
|
105
|
+
if not same_line(block.get("bbox") or [0, 0, 1, 1], other_box):
|
|
106
|
+
continue
|
|
107
|
+
other_left, other_right = float(other_box[0]), float(other_box[0]) + float(other_box[2])
|
|
108
|
+
if other_left < x - 0.002 and other_right > x + 0.01:
|
|
109
|
+
x = min(0.9, other_right + 0.006)
|
|
110
|
+
return x
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
parts = []
|
|
114
|
+
for block in blocks:
|
|
115
|
+
md = (block.get("md") or "").strip()
|
|
116
|
+
if md == "":
|
|
117
|
+
continue
|
|
118
|
+
bbox = block.get("bbox") or [0, 0, 1, 1]
|
|
119
|
+
x, y, width, _height = [float(value) for value in bbox]
|
|
120
|
+
room = room_below(block)
|
|
121
|
+
body = ""
|
|
122
|
+
left = start_x(block)
|
|
123
|
+
x_pt = max(0.0, left * page_width)
|
|
124
|
+
y_pt = max(0.0, y * page_height)
|
|
125
|
+
# Keep every block inside its own box width. Borrowing the space to the
|
|
126
|
+
# right made the translation wider than the box the reader draws around the
|
|
127
|
+
# original text, so the reveal clipped whole words; wrapping (and, when
|
|
128
|
+
# really tight, scaling) stays inside the block instead.
|
|
129
|
+
w_pt = max(40.0, min(width * page_width, page_width - x_pt - 4.0))
|
|
130
|
+
# Very narrow boxes ("if dim V = n.") cannot hold one Chinese line at body
|
|
131
|
+
# size and used to collapse to 4pt after wrapping. A slightly smaller face
|
|
132
|
+
# keeps them on one line and inside the box. The block's own printed size
|
|
133
|
+
# (pdf_blocks reports it relative to the page's body text) keeps headings
|
|
134
|
+
# and titles at their larger look instead of shrinking them to body size.
|
|
135
|
+
block_scale = float(block.get("size") or 1.0)
|
|
136
|
+
block_scale = max(0.85, min(1.6, block_scale))
|
|
137
|
+
body_pt = font_pt * block_scale * (0.8 if w_pt < 90.0 else 1.0)
|
|
138
|
+
if room < body_pt * 2.6 and "$$" in md:
|
|
139
|
+
# Too little room for a display equation: keep the math inline, including
|
|
140
|
+
# prose that carries an inline `$$...$$` fragment.
|
|
141
|
+
body = inline_formula(md)
|
|
142
|
+
if body == "":
|
|
143
|
+
body = convert(md.replace("$$", "$").split("\n"), "", drop_leading_heading=False)
|
|
144
|
+
if body == "":
|
|
145
|
+
# Same normalization the reading PDF gets: display math rebuilt on its own
|
|
146
|
+
# lines. Without it, a one-line `$$...$$` swallowed the prose after it and
|
|
147
|
+
# the paragraph came out as broken math.
|
|
148
|
+
body = convert(sanitize_display_math(md).split("\n"), "", drop_leading_heading=False)
|
|
149
|
+
if body.strip() == "":
|
|
150
|
+
continue
|
|
151
|
+
# Cap the block at the white space below it: a Chinese paragraph is often
|
|
152
|
+
# taller than the English it replaces. Text may borrow a paragraph gap but
|
|
153
|
+
# never runs into the next block, and adjustbox only shrinks when the text
|
|
154
|
+
# still exceeds that room, so most blocks keep their natural size.
|
|
155
|
+
h_pt = room
|
|
156
|
+
parts.append(
|
|
157
|
+
"\\begin{textblock}{%.2f}(%.2f,%.2f)\n"
|
|
158
|
+
"\\begin{adjustbox}{max width=%.2fpt,max totalheight=%.2fpt}\n"
|
|
159
|
+
"\\begin{minipage}[t]{%.2fpt}\\raggedright\\fontsize{%.1f}{%.1f}\\selectfont\n%s\n\\end{minipage}\n"
|
|
160
|
+
"\\end{adjustbox}\n"
|
|
161
|
+
"\\end{textblock}\n"
|
|
162
|
+
% (w_pt, x_pt, y_pt, w_pt, h_pt, w_pt, body_pt, body_pt * 1.25, body)
|
|
163
|
+
)
|
|
164
|
+
|
|
165
|
+
tex = r"""\documentclass[UTF8,%s]{ctexart}
|
|
166
|
+
\usepackage[paperwidth=%.4fin,paperheight=%.4fin,margin=0pt]{geometry}
|
|
167
|
+
\usepackage{fontspec}
|
|
168
|
+
\setCJKmainfont{%s}
|
|
169
|
+
\usepackage{amsmath,amssymb}
|
|
170
|
+
\usepackage[absolute,overlay]{textpos}
|
|
171
|
+
\usepackage{adjustbox}
|
|
172
|
+
\setlength{\TPHorizModule}{1pt}
|
|
173
|
+
\setlength{\TPVertModule}{1pt}
|
|
174
|
+
\pagestyle{empty}
|
|
175
|
+
\begin{document}
|
|
176
|
+
%s
|
|
177
|
+
\end{document}
|
|
178
|
+
""" % (font_class, page_width / 72.0, page_height / 72.0, cjk_font(), "\n".join(parts))
|
|
179
|
+
|
|
180
|
+
# Build next to the output instead of a fresh temp directory: some sandboxes
|
|
181
|
+
# allow writes in the destination directory but not in a mkdtemp directory.
|
|
182
|
+
work = os.path.abspath(out_path) + ".work"
|
|
183
|
+
os.makedirs(work, exist_ok=True)
|
|
184
|
+
tex_path = os.path.join(work, "doc.tex")
|
|
185
|
+
pdf_path = os.path.join(work, "doc.pdf")
|
|
186
|
+
try:
|
|
187
|
+
with open(tex_path, "w", encoding="utf-8") as handle:
|
|
188
|
+
handle.write(tex)
|
|
189
|
+
|
|
190
|
+
result = subprocess.run(
|
|
191
|
+
["xelatex", "-interaction=nonstopmode", "doc.tex"],
|
|
192
|
+
cwd=work, capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=180,
|
|
193
|
+
)
|
|
194
|
+
if not os.path.exists(pdf_path):
|
|
195
|
+
raise SystemExit("xelatex failed: " + (result.stdout or "")[-800:])
|
|
196
|
+
|
|
197
|
+
os.replace(pdf_path, out_path)
|
|
198
|
+
finally:
|
|
199
|
+
shutil.rmtree(work, ignore_errors=True)
|
|
200
|
+
print(out_path)
|