dsh-pdf-workbench 1.3.3 → 1.4.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.
- package/LICENSE +21 -21
- package/README.md +225 -199
- package/assets/screenshot-attachments.jpg +0 -0
- package/assets/screenshot-canvas.jpg +0 -0
- package/assets/screenshot-questions.jpg +0 -0
- package/assets/screenshot-settings-data.jpg +0 -0
- package/assets/screenshot-settings-mode.jpg +0 -0
- package/assets/screenshot-settings-reading.jpg +0 -0
- package/client.js +5700 -849
- package/docs/DETAIL.md +1 -69
- package/docs/RELEASE.md +119 -119
- package/docs/SIDE-PREVIEW.md +5 -1
- package/docs/preview.svg +86 -0
- package/icon.svg +7 -6
- package/index.js +18 -2
- package/locale/en.json +1 -1
- package/locale/zh.json +1 -1
- package/package.json +1 -1
- package/screenshots.json +13 -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/artifacts.js +31 -3
- package/src/host/attachments.js +159 -0
- package/src/host/backup.js +457 -0
- package/src/host/base-session.js +146 -0
- package/src/host/book-import.js +98 -0
- package/src/host/chapter-sessions.js +154 -0
- package/src/host/chapter-text.js +91 -0
- package/src/host/fonts.js +190 -0
- package/src/host/pdf-stream.js +168 -0
- package/src/host/ppt.js +153 -0
- package/src/host/print.js +191 -0
- package/src/host/questions.js +186 -0
- package/src/host/routes.js +671 -25
- package/src/host/state.js +1 -1
- package/src/host/zip.js +186 -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/pdf_text.py +34 -0
- 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/vendor/fonts/zhhand/Xiaolai-Regular.ttf +0 -0
package/tools/md2tex.py
CHANGED
|
@@ -1,422 +1,422 @@
|
|
|
1
|
-
"""Render the CRT markdown with LaTeX (XeLaTeX + ctex) into one PDF per chapter."""
|
|
2
|
-
import json
|
|
3
|
-
import os
|
|
4
|
-
import re
|
|
5
|
-
import shutil
|
|
6
|
-
import subprocess
|
|
7
|
-
import sys
|
|
8
|
-
|
|
9
|
-
SRC = ""
|
|
10
|
-
BOOK = "中国剩余定理"
|
|
11
|
-
OUT = os.path.join("samples", "分片", BOOK)
|
|
12
|
-
WORK = os.path.join("build", "tex")
|
|
13
|
-
MANIFEST = os.path.join("samples", "manifest.json")
|
|
14
|
-
XELATEX = os.environ.get("XELATEX") or shutil.which("xelatex") or "xelatex"
|
|
15
|
-
|
|
16
|
-
CHAPTERS = [
|
|
17
|
-
("c01", "第0章_导读", "0. 导读:先看四张面孔"),
|
|
18
|
-
("c02", "第1章_古题_孙子算经到秦九韶", "1. 一道古题:从《孙子算经》到秦九韶"),
|
|
19
|
-
("c03", "第2章_整数版本", "2. 整数版本"),
|
|
20
|
-
("c04", "第3章_环论版本", "3. 环论版本:《代数学基础》§2.4"),
|
|
21
|
-
("c05", "第4章_多项式版本", "4. 多项式版本:《高等代数学》§5.3"),
|
|
22
|
-
("c06", "第5章_群论版本", "5. 群论版本"),
|
|
23
|
-
("c07", "第6章_统一结构", "6. 统一的结构:CRT 到底在说什么"),
|
|
24
|
-
("c08", "第7章_回望", "7. 回望:从“物不知数”到“单位分解”"),
|
|
25
|
-
("c90", "附录_教材页码符号表自测", "附录 A 教材页码与定理编号"),
|
|
26
|
-
]
|
|
27
|
-
|
|
28
|
-
def font_size():
|
|
29
|
-
raw = os.environ.get("MATH_DESK_FONTSIZE", "").strip()
|
|
30
|
-
return raw if raw in ("9pt", "10pt", "11pt", "12pt") else "11pt"
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
def page_options():
|
|
34
|
-
raw = os.environ.get("MATH_DESK_PAPER", "").strip()
|
|
35
|
-
if "," in raw:
|
|
36
|
-
width, height = raw.split(",", 1)
|
|
37
|
-
return f"paperwidth={float(width):.3f}in,paperheight={float(height):.3f}in,margin=1.2cm"
|
|
38
|
-
return "margin=2.4cm"
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
def cjk_font():
|
|
42
|
-
"""The Chinese face used on screen.
|
|
43
|
-
|
|
44
|
-
SimSun (the ctex default here) is hairline-thin on a monitor; Microsoft
|
|
45
|
-
YaHei is present on every Windows 10/11 the plugin supports and stays
|
|
46
|
-
readable at 100–150%. MATH_DESK_CJKFONT overrides it (pass a family name
|
|
47
|
-
XeLaTeX can find, e.g. `Source Han Serif SC`)."""
|
|
48
|
-
raw = os.environ.get("MATH_DESK_CJKFONT", "").strip()
|
|
49
|
-
return raw if raw != "" else "Microsoft YaHei"
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
PREAMBLE = r"""\documentclass[UTF8,11pt,a4paper]{ctexart}
|
|
53
|
-
\usepackage[%s]{geometry}
|
|
54
|
-
\usepackage{fontspec}
|
|
55
|
-
\setCJKmainfont{%s}
|
|
56
|
-
\usepackage{amsmath,amssymb}
|
|
57
|
-
\usepackage{booktabs,tabularx,array}
|
|
58
|
-
\usepackage{fancyvrb}
|
|
59
|
-
\usepackage{enumitem}
|
|
60
|
-
\usepackage{xcolor}
|
|
61
|
-
\usepackage[hidelinks]{hyperref}
|
|
62
|
-
\setlength{\parindent}{2em}
|
|
63
|
-
\setlength{\parskip}{0.35em}
|
|
64
|
-
\linespread{1.32}
|
|
65
|
-
\setlist{itemsep=2pt,topsep=4pt,leftmargin=2em}
|
|
66
|
-
\pagestyle{plain}
|
|
67
|
-
\begin{document}
|
|
68
|
-
"""
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
def escape(text):
|
|
72
|
-
text = text.replace("\\", r"\textbackslash{}")
|
|
73
|
-
for old, new in (("&", r"\&"), ("%", r"\%"), ("#", r"\#"), ("_", r"\_"),
|
|
74
|
-
("{", r"\{"), ("}", r"\}"), ("~", r"\textasciitilde{}"),
|
|
75
|
-
("^", r"\textasciicircum{}")):
|
|
76
|
-
text = text.replace(old, new)
|
|
77
|
-
return text
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
MATH = re.compile(r"(\$\$.*?\$\$|\$[^$]+?\$)", re.S)
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
def inline(text):
|
|
84
|
-
"""Escape prose but keep inline/display math exactly as written."""
|
|
85
|
-
pieces = []
|
|
86
|
-
for part in MATH.split(text):
|
|
87
|
-
if part == "":
|
|
88
|
-
continue
|
|
89
|
-
if part.startswith("$"):
|
|
90
|
-
pieces.append(part)
|
|
91
|
-
continue
|
|
92
|
-
part = re.sub(r"!\[[^\]]*\]\([^)]*\)", "", part)
|
|
93
|
-
part = re.sub(r"\[([^\]]+)\]\([^)]*\)", r"\1", part)
|
|
94
|
-
slots = []
|
|
95
|
-
|
|
96
|
-
def hold(latex):
|
|
97
|
-
slots.append(latex)
|
|
98
|
-
return "\x01%d\x01" % (len(slots) - 1)
|
|
99
|
-
|
|
100
|
-
part = re.sub(r"\*\*([^*]+)\*\*", lambda m: hold(r"\textbf{%s}" % escape(m.group(1))), part)
|
|
101
|
-
part = re.sub(r"__([^_]+)__", lambda m: hold(r"\textbf{%s}" % escape(m.group(1))), part)
|
|
102
|
-
part = re.sub(r"(?<!\*)\*([^*\n]+)\*(?!\*)", lambda m: hold(r"\emph{%s}" % escape(m.group(1))), part)
|
|
103
|
-
part = re.sub(r"`([^`]*)`", lambda m: hold(r"\texttt{%s}" % escape(m.group(1))), part)
|
|
104
|
-
part = escape(part)
|
|
105
|
-
for index, latex in enumerate(slots):
|
|
106
|
-
part = part.replace("\x01%d\x01" % index, latex)
|
|
107
|
-
pieces.append(part)
|
|
108
|
-
return "".join(pieces)
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
def heading(text, level):
|
|
112
|
-
command = {1: "section", 2: "subsection", 3: "subsubsection"}.get(level, "subsubsection")
|
|
113
|
-
return "\\%s*{%s}\n" % (command, inline(text))
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
def split_groups(lines):
|
|
117
|
-
starts = []
|
|
118
|
-
for index, line in enumerate(lines):
|
|
119
|
-
match = re.match(r"^##\s+(.+)$", line)
|
|
120
|
-
if match:
|
|
121
|
-
starts.append((index, match.group(1).strip()))
|
|
122
|
-
groups = []
|
|
123
|
-
for pos, (index, title) in enumerate(starts):
|
|
124
|
-
end = starts[pos + 1][0] if pos + 1 < len(starts) else len(lines)
|
|
125
|
-
groups.append((title, lines[index:end]))
|
|
126
|
-
return groups
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
def normalize_math_delimiters(text):
|
|
130
|
-
"""Rewrite the model's \\(...\\) and \\[...\\] math into $...$ and $$...$$.
|
|
131
|
-
|
|
132
|
-
The vision model regularly answers with LaTeX delimiters instead of the
|
|
133
|
-
requested dollars; left alone they printed literally ("\\(\\rho\\)") and made
|
|
134
|
-
the translated pages look like broken markup."""
|
|
135
|
-
text = re.sub(r"(?<!\\)\\\(", "$", text)
|
|
136
|
-
text = re.sub(r"(?<!\\)\\\)", "$", text)
|
|
137
|
-
text = re.sub(r"(?<!\\)\\\[", "$$", text)
|
|
138
|
-
text = re.sub(r"(?<!\\)\\\]", "$$", text)
|
|
139
|
-
return text
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
def convert(lines, chapter_title, drop_leading_heading=True):
|
|
143
|
-
"""Markdown lines to LaTeX body.
|
|
144
|
-
|
|
145
|
-
`drop_leading_heading` skips a leading `##` line, which is how a whole
|
|
146
|
-
document avoids printing its own title twice. A single block being placed at
|
|
147
|
-
its bbox has no such duplicate, so the overlay renderer turns it off.
|
|
148
|
-
"""
|
|
149
|
-
lines = [normalize_math_delimiters(line) for line in lines]
|
|
150
|
-
out = []
|
|
151
|
-
if chapter_title:
|
|
152
|
-
out.append("\\section*{%s}\n" % inline(chapter_title))
|
|
153
|
-
i = 1 if drop_leading_heading and lines and re.match(r"^##\s", lines[0]) else 0
|
|
154
|
-
buffer = []
|
|
155
|
-
list_kind = None
|
|
156
|
-
list_items = []
|
|
157
|
-
|
|
158
|
-
def flush_paragraph():
|
|
159
|
-
if buffer:
|
|
160
|
-
text = " ".join(p.strip() for p in buffer if p.strip())
|
|
161
|
-
if text:
|
|
162
|
-
out.append(inline(text) + "\n\n")
|
|
163
|
-
buffer.clear()
|
|
164
|
-
|
|
165
|
-
def flush_list():
|
|
166
|
-
nonlocal list_kind, list_items
|
|
167
|
-
if list_kind is not None and list_items:
|
|
168
|
-
env = "itemize" if list_kind == "ul" else "enumerate"
|
|
169
|
-
out.append("\\begin{%s}\n" % env)
|
|
170
|
-
for item in list_items:
|
|
171
|
-
out.append(" \\item %s\n" % inline(item))
|
|
172
|
-
out.append("\\end{%s}\n\n" % env)
|
|
173
|
-
list_kind = None
|
|
174
|
-
list_items = []
|
|
175
|
-
|
|
176
|
-
while i < len(lines):
|
|
177
|
-
raw = lines[i].rstrip("\n")
|
|
178
|
-
if raw.startswith("```"):
|
|
179
|
-
flush_paragraph()
|
|
180
|
-
flush_list()
|
|
181
|
-
i += 1
|
|
182
|
-
block = []
|
|
183
|
-
while i < len(lines) and not lines[i].startswith("```"):
|
|
184
|
-
block.append(lines[i].rstrip("\n"))
|
|
185
|
-
i += 1
|
|
186
|
-
out.append("\\begin{Verbatim}[fontsize=\\small,frame=single]\n")
|
|
187
|
-
out.extend(row + "\n" for row in block)
|
|
188
|
-
out.append("\\end{Verbatim}\n\n")
|
|
189
|
-
i += 1
|
|
190
|
-
continue
|
|
191
|
-
if not raw.strip():
|
|
192
|
-
flush_paragraph()
|
|
193
|
-
flush_list()
|
|
194
|
-
i += 1
|
|
195
|
-
continue
|
|
196
|
-
if re.match(r"^\s*\|.*\|\s*$", raw) and i + 1 < len(lines) and re.match(r"^\s*\|[\s:|-]+\|\s*$", lines[i + 1]):
|
|
197
|
-
flush_paragraph()
|
|
198
|
-
flush_list()
|
|
199
|
-
rows = []
|
|
200
|
-
while i < len(lines) and re.match(r"^\s*\|.*\|\s*$", lines[i]):
|
|
201
|
-
cells = [c.strip() for c in lines[i].strip().strip("|").split("|")]
|
|
202
|
-
if not re.match(r"^[\s:|-]+$", "".join(cells)):
|
|
203
|
-
rows.append(cells)
|
|
204
|
-
i += 1
|
|
205
|
-
if rows:
|
|
206
|
-
cols = max(len(row) for row in rows)
|
|
207
|
-
out.append("\\begin{center}\n\\begin{tabularx}{\\linewidth}{@{}%s@{}}\n\\toprule\n" % ("X" * cols))
|
|
208
|
-
for r_index, row in enumerate(rows):
|
|
209
|
-
cells = [inline(row[c]) if c < len(row) else "" for c in range(cols)]
|
|
210
|
-
out.append(" & ".join(cells) + r" \\" + "\n")
|
|
211
|
-
if r_index == 0:
|
|
212
|
-
out.append("\\midrule\n")
|
|
213
|
-
out.append("\\bottomrule\n\\end{tabularx}\n\\end{center}\n\n")
|
|
214
|
-
continue
|
|
215
|
-
heading_match = re.match(r"^(#{1,6})\s+(.*)$", raw)
|
|
216
|
-
if heading_match:
|
|
217
|
-
flush_paragraph()
|
|
218
|
-
flush_list()
|
|
219
|
-
level = min(max(len(heading_match.group(1)) - 1, 1), 3)
|
|
220
|
-
out.append(heading(heading_match.group(2).strip(), level) + "\n")
|
|
221
|
-
i += 1
|
|
222
|
-
continue
|
|
223
|
-
list_match = re.match(r"^\s*([-*+]|\d+\.)\s+(.*)$", raw)
|
|
224
|
-
if list_match:
|
|
225
|
-
flush_paragraph()
|
|
226
|
-
kind = "ol" if re.match(r"^\s*\d+\.", raw) else "ul"
|
|
227
|
-
if list_kind is not None and list_kind != kind:
|
|
228
|
-
flush_list()
|
|
229
|
-
list_kind = kind
|
|
230
|
-
list_items.append(list_match.group(2))
|
|
231
|
-
i += 1
|
|
232
|
-
continue
|
|
233
|
-
if raw.startswith(">"):
|
|
234
|
-
flush_paragraph()
|
|
235
|
-
flush_list()
|
|
236
|
-
quote = []
|
|
237
|
-
while i < len(lines) and lines[i].startswith(">"):
|
|
238
|
-
quote.append(lines[i].lstrip("> ").strip())
|
|
239
|
-
i += 1
|
|
240
|
-
out.append("\\begin{quote}\n%s\n\\end{quote}\n\n" % inline(" ".join(quote)))
|
|
241
|
-
continue
|
|
242
|
-
if raw.strip() in ("---", "***", "___"):
|
|
243
|
-
flush_paragraph()
|
|
244
|
-
flush_list()
|
|
245
|
-
out.append("\\par\\noindent\\rule{\\linewidth}{0.4pt}\\par\\medskip\n")
|
|
246
|
-
i += 1
|
|
247
|
-
continue
|
|
248
|
-
if raw.strip() in ("\\newpage", "<!-- pagebreak -->"):
|
|
249
|
-
flush_paragraph()
|
|
250
|
-
flush_list()
|
|
251
|
-
out.append("\\newpage\n\n")
|
|
252
|
-
i += 1
|
|
253
|
-
continue
|
|
254
|
-
if raw.strip().startswith("$$"):
|
|
255
|
-
flush_paragraph()
|
|
256
|
-
flush_list()
|
|
257
|
-
block = [raw.strip()]
|
|
258
|
-
i += 1
|
|
259
|
-
# A `$$ … $$` that fits one line closes on that line; looking only at
|
|
260
|
-
# the following lines swallowed the rest of the page into display
|
|
261
|
-
# math whenever the caller had not normalized the block first.
|
|
262
|
-
closed = raw.count("$$") >= 2
|
|
263
|
-
while not closed and i < len(lines) and "$$" not in lines[i]:
|
|
264
|
-
block.append(lines[i].strip())
|
|
265
|
-
i += 1
|
|
266
|
-
if not closed and i < len(lines):
|
|
267
|
-
block.append(lines[i].strip())
|
|
268
|
-
i += 1
|
|
269
|
-
body = " ".join(block).replace("$$", "").strip()
|
|
270
|
-
out.append("\\[\n%s\n\\]\n\n" % body)
|
|
271
|
-
continue
|
|
272
|
-
buffer.append(raw)
|
|
273
|
-
i += 1
|
|
274
|
-
flush_paragraph()
|
|
275
|
-
flush_list()
|
|
276
|
-
return "".join(out)
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
def write_tex(path, body):
|
|
280
|
-
with open(path, "w", encoding="utf-8") as handle:
|
|
281
|
-
handle.write(PREAMBLE.replace("11pt", font_size(), 1) % (page_options(), cjk_font()))
|
|
282
|
-
handle.write(body)
|
|
283
|
-
handle.write("\\end{document}\n")
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
def compile_tex(tex_path, pdf_path):
|
|
287
|
-
for _ in range(2):
|
|
288
|
-
result = subprocess.run(
|
|
289
|
-
[XELATEX, "-interaction=nonstopmode", "-halt-on-error", os.path.basename(tex_path)],
|
|
290
|
-
cwd=os.path.dirname(tex_path),
|
|
291
|
-
capture_output=True,
|
|
292
|
-
text=True,
|
|
293
|
-
encoding="utf-8",
|
|
294
|
-
errors="replace",
|
|
295
|
-
)
|
|
296
|
-
if result.returncode != 0:
|
|
297
|
-
log = os.path.splitext(tex_path)[0] + ".log"
|
|
298
|
-
tail = ""
|
|
299
|
-
if os.path.exists(log):
|
|
300
|
-
with open(log, encoding="utf-8", errors="replace") as handle:
|
|
301
|
-
tail = "".join(handle.readlines()[-25:])
|
|
302
|
-
raise SystemExit("xelatex failed:\n" + result.stdout[-2000:] + "\n" + tail)
|
|
303
|
-
shutil.copyfile(os.path.splitext(tex_path)[0] + ".pdf", pdf_path)
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
def cover_tex():
|
|
307
|
-
entries = "\n".join("\\item %s" % inline(title) for _key, _file, title in CHAPTERS)
|
|
308
|
-
return (
|
|
309
|
-
"\\begin{center}\n"
|
|
310
|
-
"{\\Huge\\bfseries 中国剩余定理}\\\\[0.6em]\n"
|
|
311
|
-
"{\\Large 从《孙子算经》到环、多项式与群}\\\\[1.2em]\n"
|
|
312
|
-
"\\rule{0.6\\linewidth}{0.4pt}\\\\[0.8em]\n"
|
|
313
|
-
"{\\small 示例书库 · 由 dsh-pdf-math-desk 生成}\n"
|
|
314
|
-
"\\end{center}\n\\vspace{2em}\n"
|
|
315
|
-
"\\section*{目录}\n\\begin{itemize}\n" + entries + "\n\\end{itemize}\n"
|
|
316
|
-
)
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
def sanitize_display_math(text):
|
|
320
|
-
"""Normalize display math before conversion.
|
|
321
|
-
|
|
322
|
-
The translation model sometimes mixes inline math into a display block or
|
|
323
|
-
puts prose after the closing `$$` on the same line, which makes XeLaTeX
|
|
324
|
-
abort with "Display math should end with $$". Display blocks are rebuilt on
|
|
325
|
-
their own lines, with inner single `$` removed; trailing prose stays prose.
|
|
326
|
-
"""
|
|
327
|
-
text = text.replace("\\[", "$$").replace("\\]", "$$")
|
|
328
|
-
text = text.replace("\\(", "$").replace("\\)", "$")
|
|
329
|
-
parts = text.split("$$")
|
|
330
|
-
if len(parts) % 2 == 0:
|
|
331
|
-
parts.append("")
|
|
332
|
-
rebuilt = []
|
|
333
|
-
for index, part in enumerate(parts):
|
|
334
|
-
if index % 2 == 1:
|
|
335
|
-
body = part.replace("$", "")
|
|
336
|
-
rebuilt.append("\n\n$$\n" + body.strip() + "\n$$\n\n")
|
|
337
|
-
else:
|
|
338
|
-
rebuilt.append(part)
|
|
339
|
-
return "".join(rebuilt)
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
def main():
|
|
343
|
-
os.makedirs(OUT, exist_ok=True)
|
|
344
|
-
if os.path.isdir(WORK):
|
|
345
|
-
shutil.rmtree(WORK)
|
|
346
|
-
os.makedirs(WORK, exist_ok=True)
|
|
347
|
-
with open(SRC, encoding="utf-8") as handle:
|
|
348
|
-
lines = handle.read().split("\n")
|
|
349
|
-
groups = split_groups(lines)
|
|
350
|
-
made = []
|
|
351
|
-
|
|
352
|
-
cover_tex_path = os.path.join(WORK, "cover.tex")
|
|
353
|
-
write_tex(cover_tex_path, cover_tex())
|
|
354
|
-
cover_pdf = os.path.join(OUT, f"{BOOK}_c00_前置_封面目录.pdf")
|
|
355
|
-
compile_tex(cover_tex_path, cover_pdf)
|
|
356
|
-
made.append(os.path.basename(cover_pdf))
|
|
357
|
-
|
|
358
|
-
for key, file_title, heading_text in CHAPTERS:
|
|
359
|
-
if heading_text.startswith("附录"):
|
|
360
|
-
body = []
|
|
361
|
-
for group_title, group_lines in groups:
|
|
362
|
-
if group_title.startswith("附录"):
|
|
363
|
-
body.extend(group_lines)
|
|
364
|
-
else:
|
|
365
|
-
body = None
|
|
366
|
-
prefix = heading_text.split(":")[0].strip()
|
|
367
|
-
for group_title, group_lines in groups:
|
|
368
|
-
if group_title.startswith(prefix):
|
|
369
|
-
body = group_lines
|
|
370
|
-
break
|
|
371
|
-
if body is None:
|
|
372
|
-
raise SystemExit("missing chapter: " + heading_text)
|
|
373
|
-
tex_path = os.path.join(WORK, key + ".tex")
|
|
374
|
-
write_tex(tex_path, convert(body, heading_text))
|
|
375
|
-
name = f"{BOOK}_{key}_{file_title}.pdf"
|
|
376
|
-
compile_tex(tex_path, os.path.join(OUT, name))
|
|
377
|
-
made.append(name)
|
|
378
|
-
|
|
379
|
-
entries = []
|
|
380
|
-
total = 0
|
|
381
|
-
for name in made:
|
|
382
|
-
size = os.path.getsize(os.path.join(OUT, name))
|
|
383
|
-
total += size
|
|
384
|
-
entries.append({"name": name, "bytes": size})
|
|
385
|
-
with open(MANIFEST, "w", encoding="utf-8") as handle:
|
|
386
|
-
json.dump({
|
|
387
|
-
"version": 1,
|
|
388
|
-
"book": {
|
|
389
|
-
"id": BOOK,
|
|
390
|
-
"title": "中国剩余定理",
|
|
391
|
-
"subtitle": "从《孙子算经》到环、多项式与群",
|
|
392
|
-
"chapters": len(made),
|
|
393
|
-
"bytes": total,
|
|
394
|
-
},
|
|
395
|
-
"files": entries,
|
|
396
|
-
}, handle, ensure_ascii=False, indent=2)
|
|
397
|
-
print(json.dumps({"chapters": len(made), "bytes": total}, ensure_ascii=False))
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
if __name__ == "__main__":
|
|
401
|
-
if len(sys.argv) >= 3:
|
|
402
|
-
import tempfile
|
|
403
|
-
src, out = sys.argv[1], sys.argv[2]
|
|
404
|
-
# The heading is the caller's choice: a named artifact wants its own
|
|
405
|
-
# name, while a translated page already carries the book's chapter
|
|
406
|
-
# heading and must not repeat a temporary file name ("page-012",
|
|
407
|
-
# ".render-0.67.2") at the top. MATH_DESK_NO_TITLE=1 asks for none.
|
|
408
|
-
if len(sys.argv) > 3:
|
|
409
|
-
title = sys.argv[3]
|
|
410
|
-
elif os.environ.get("MATH_DESK_NO_TITLE") == "1":
|
|
411
|
-
title = ""
|
|
412
|
-
else:
|
|
413
|
-
title = os.path.splitext(os.path.basename(src))[0]
|
|
414
|
-
with open(src, encoding="utf-8") as handle:
|
|
415
|
-
lines = sanitize_display_math(handle.read()).split("\n")
|
|
416
|
-
work = tempfile.mkdtemp(prefix="md2tex-")
|
|
417
|
-
tex = os.path.join(work, "doc.tex")
|
|
418
|
-
write_tex(tex, convert(lines, title))
|
|
419
|
-
compile_tex(tex, out)
|
|
420
|
-
print(out)
|
|
421
|
-
else:
|
|
422
|
-
main()
|
|
1
|
+
"""Render the CRT markdown with LaTeX (XeLaTeX + ctex) into one PDF per chapter."""
|
|
2
|
+
import json
|
|
3
|
+
import os
|
|
4
|
+
import re
|
|
5
|
+
import shutil
|
|
6
|
+
import subprocess
|
|
7
|
+
import sys
|
|
8
|
+
|
|
9
|
+
SRC = ""
|
|
10
|
+
BOOK = "中国剩余定理"
|
|
11
|
+
OUT = os.path.join("samples", "分片", BOOK)
|
|
12
|
+
WORK = os.path.join("build", "tex")
|
|
13
|
+
MANIFEST = os.path.join("samples", "manifest.json")
|
|
14
|
+
XELATEX = os.environ.get("XELATEX") or shutil.which("xelatex") or "xelatex"
|
|
15
|
+
|
|
16
|
+
CHAPTERS = [
|
|
17
|
+
("c01", "第0章_导读", "0. 导读:先看四张面孔"),
|
|
18
|
+
("c02", "第1章_古题_孙子算经到秦九韶", "1. 一道古题:从《孙子算经》到秦九韶"),
|
|
19
|
+
("c03", "第2章_整数版本", "2. 整数版本"),
|
|
20
|
+
("c04", "第3章_环论版本", "3. 环论版本:《代数学基础》§2.4"),
|
|
21
|
+
("c05", "第4章_多项式版本", "4. 多项式版本:《高等代数学》§5.3"),
|
|
22
|
+
("c06", "第5章_群论版本", "5. 群论版本"),
|
|
23
|
+
("c07", "第6章_统一结构", "6. 统一的结构:CRT 到底在说什么"),
|
|
24
|
+
("c08", "第7章_回望", "7. 回望:从“物不知数”到“单位分解”"),
|
|
25
|
+
("c90", "附录_教材页码符号表自测", "附录 A 教材页码与定理编号"),
|
|
26
|
+
]
|
|
27
|
+
|
|
28
|
+
def font_size():
|
|
29
|
+
raw = os.environ.get("MATH_DESK_FONTSIZE", "").strip()
|
|
30
|
+
return raw if raw in ("9pt", "10pt", "11pt", "12pt") else "11pt"
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def page_options():
|
|
34
|
+
raw = os.environ.get("MATH_DESK_PAPER", "").strip()
|
|
35
|
+
if "," in raw:
|
|
36
|
+
width, height = raw.split(",", 1)
|
|
37
|
+
return f"paperwidth={float(width):.3f}in,paperheight={float(height):.3f}in,margin=1.2cm"
|
|
38
|
+
return "margin=2.4cm"
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def cjk_font():
|
|
42
|
+
"""The Chinese face used on screen.
|
|
43
|
+
|
|
44
|
+
SimSun (the ctex default here) is hairline-thin on a monitor; Microsoft
|
|
45
|
+
YaHei is present on every Windows 10/11 the plugin supports and stays
|
|
46
|
+
readable at 100–150%. MATH_DESK_CJKFONT overrides it (pass a family name
|
|
47
|
+
XeLaTeX can find, e.g. `Source Han Serif SC`)."""
|
|
48
|
+
raw = os.environ.get("MATH_DESK_CJKFONT", "").strip()
|
|
49
|
+
return raw if raw != "" else "Microsoft YaHei"
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
PREAMBLE = r"""\documentclass[UTF8,11pt,a4paper]{ctexart}
|
|
53
|
+
\usepackage[%s]{geometry}
|
|
54
|
+
\usepackage{fontspec}
|
|
55
|
+
\setCJKmainfont{%s}
|
|
56
|
+
\usepackage{amsmath,amssymb}
|
|
57
|
+
\usepackage{booktabs,tabularx,array}
|
|
58
|
+
\usepackage{fancyvrb}
|
|
59
|
+
\usepackage{enumitem}
|
|
60
|
+
\usepackage{xcolor}
|
|
61
|
+
\usepackage[hidelinks]{hyperref}
|
|
62
|
+
\setlength{\parindent}{2em}
|
|
63
|
+
\setlength{\parskip}{0.35em}
|
|
64
|
+
\linespread{1.32}
|
|
65
|
+
\setlist{itemsep=2pt,topsep=4pt,leftmargin=2em}
|
|
66
|
+
\pagestyle{plain}
|
|
67
|
+
\begin{document}
|
|
68
|
+
"""
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def escape(text):
|
|
72
|
+
text = text.replace("\\", r"\textbackslash{}")
|
|
73
|
+
for old, new in (("&", r"\&"), ("%", r"\%"), ("#", r"\#"), ("_", r"\_"),
|
|
74
|
+
("{", r"\{"), ("}", r"\}"), ("~", r"\textasciitilde{}"),
|
|
75
|
+
("^", r"\textasciicircum{}")):
|
|
76
|
+
text = text.replace(old, new)
|
|
77
|
+
return text
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
MATH = re.compile(r"(\$\$.*?\$\$|\$[^$]+?\$)", re.S)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def inline(text):
|
|
84
|
+
"""Escape prose but keep inline/display math exactly as written."""
|
|
85
|
+
pieces = []
|
|
86
|
+
for part in MATH.split(text):
|
|
87
|
+
if part == "":
|
|
88
|
+
continue
|
|
89
|
+
if part.startswith("$"):
|
|
90
|
+
pieces.append(part)
|
|
91
|
+
continue
|
|
92
|
+
part = re.sub(r"!\[[^\]]*\]\([^)]*\)", "", part)
|
|
93
|
+
part = re.sub(r"\[([^\]]+)\]\([^)]*\)", r"\1", part)
|
|
94
|
+
slots = []
|
|
95
|
+
|
|
96
|
+
def hold(latex):
|
|
97
|
+
slots.append(latex)
|
|
98
|
+
return "\x01%d\x01" % (len(slots) - 1)
|
|
99
|
+
|
|
100
|
+
part = re.sub(r"\*\*([^*]+)\*\*", lambda m: hold(r"\textbf{%s}" % escape(m.group(1))), part)
|
|
101
|
+
part = re.sub(r"__([^_]+)__", lambda m: hold(r"\textbf{%s}" % escape(m.group(1))), part)
|
|
102
|
+
part = re.sub(r"(?<!\*)\*([^*\n]+)\*(?!\*)", lambda m: hold(r"\emph{%s}" % escape(m.group(1))), part)
|
|
103
|
+
part = re.sub(r"`([^`]*)`", lambda m: hold(r"\texttt{%s}" % escape(m.group(1))), part)
|
|
104
|
+
part = escape(part)
|
|
105
|
+
for index, latex in enumerate(slots):
|
|
106
|
+
part = part.replace("\x01%d\x01" % index, latex)
|
|
107
|
+
pieces.append(part)
|
|
108
|
+
return "".join(pieces)
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def heading(text, level):
|
|
112
|
+
command = {1: "section", 2: "subsection", 3: "subsubsection"}.get(level, "subsubsection")
|
|
113
|
+
return "\\%s*{%s}\n" % (command, inline(text))
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def split_groups(lines):
|
|
117
|
+
starts = []
|
|
118
|
+
for index, line in enumerate(lines):
|
|
119
|
+
match = re.match(r"^##\s+(.+)$", line)
|
|
120
|
+
if match:
|
|
121
|
+
starts.append((index, match.group(1).strip()))
|
|
122
|
+
groups = []
|
|
123
|
+
for pos, (index, title) in enumerate(starts):
|
|
124
|
+
end = starts[pos + 1][0] if pos + 1 < len(starts) else len(lines)
|
|
125
|
+
groups.append((title, lines[index:end]))
|
|
126
|
+
return groups
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def normalize_math_delimiters(text):
|
|
130
|
+
"""Rewrite the model's \\(...\\) and \\[...\\] math into $...$ and $$...$$.
|
|
131
|
+
|
|
132
|
+
The vision model regularly answers with LaTeX delimiters instead of the
|
|
133
|
+
requested dollars; left alone they printed literally ("\\(\\rho\\)") and made
|
|
134
|
+
the translated pages look like broken markup."""
|
|
135
|
+
text = re.sub(r"(?<!\\)\\\(", "$", text)
|
|
136
|
+
text = re.sub(r"(?<!\\)\\\)", "$", text)
|
|
137
|
+
text = re.sub(r"(?<!\\)\\\[", "$$", text)
|
|
138
|
+
text = re.sub(r"(?<!\\)\\\]", "$$", text)
|
|
139
|
+
return text
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def convert(lines, chapter_title, drop_leading_heading=True):
|
|
143
|
+
"""Markdown lines to LaTeX body.
|
|
144
|
+
|
|
145
|
+
`drop_leading_heading` skips a leading `##` line, which is how a whole
|
|
146
|
+
document avoids printing its own title twice. A single block being placed at
|
|
147
|
+
its bbox has no such duplicate, so the overlay renderer turns it off.
|
|
148
|
+
"""
|
|
149
|
+
lines = [normalize_math_delimiters(line) for line in lines]
|
|
150
|
+
out = []
|
|
151
|
+
if chapter_title:
|
|
152
|
+
out.append("\\section*{%s}\n" % inline(chapter_title))
|
|
153
|
+
i = 1 if drop_leading_heading and lines and re.match(r"^##\s", lines[0]) else 0
|
|
154
|
+
buffer = []
|
|
155
|
+
list_kind = None
|
|
156
|
+
list_items = []
|
|
157
|
+
|
|
158
|
+
def flush_paragraph():
|
|
159
|
+
if buffer:
|
|
160
|
+
text = " ".join(p.strip() for p in buffer if p.strip())
|
|
161
|
+
if text:
|
|
162
|
+
out.append(inline(text) + "\n\n")
|
|
163
|
+
buffer.clear()
|
|
164
|
+
|
|
165
|
+
def flush_list():
|
|
166
|
+
nonlocal list_kind, list_items
|
|
167
|
+
if list_kind is not None and list_items:
|
|
168
|
+
env = "itemize" if list_kind == "ul" else "enumerate"
|
|
169
|
+
out.append("\\begin{%s}\n" % env)
|
|
170
|
+
for item in list_items:
|
|
171
|
+
out.append(" \\item %s\n" % inline(item))
|
|
172
|
+
out.append("\\end{%s}\n\n" % env)
|
|
173
|
+
list_kind = None
|
|
174
|
+
list_items = []
|
|
175
|
+
|
|
176
|
+
while i < len(lines):
|
|
177
|
+
raw = lines[i].rstrip("\n")
|
|
178
|
+
if raw.startswith("```"):
|
|
179
|
+
flush_paragraph()
|
|
180
|
+
flush_list()
|
|
181
|
+
i += 1
|
|
182
|
+
block = []
|
|
183
|
+
while i < len(lines) and not lines[i].startswith("```"):
|
|
184
|
+
block.append(lines[i].rstrip("\n"))
|
|
185
|
+
i += 1
|
|
186
|
+
out.append("\\begin{Verbatim}[fontsize=\\small,frame=single]\n")
|
|
187
|
+
out.extend(row + "\n" for row in block)
|
|
188
|
+
out.append("\\end{Verbatim}\n\n")
|
|
189
|
+
i += 1
|
|
190
|
+
continue
|
|
191
|
+
if not raw.strip():
|
|
192
|
+
flush_paragraph()
|
|
193
|
+
flush_list()
|
|
194
|
+
i += 1
|
|
195
|
+
continue
|
|
196
|
+
if re.match(r"^\s*\|.*\|\s*$", raw) and i + 1 < len(lines) and re.match(r"^\s*\|[\s:|-]+\|\s*$", lines[i + 1]):
|
|
197
|
+
flush_paragraph()
|
|
198
|
+
flush_list()
|
|
199
|
+
rows = []
|
|
200
|
+
while i < len(lines) and re.match(r"^\s*\|.*\|\s*$", lines[i]):
|
|
201
|
+
cells = [c.strip() for c in lines[i].strip().strip("|").split("|")]
|
|
202
|
+
if not re.match(r"^[\s:|-]+$", "".join(cells)):
|
|
203
|
+
rows.append(cells)
|
|
204
|
+
i += 1
|
|
205
|
+
if rows:
|
|
206
|
+
cols = max(len(row) for row in rows)
|
|
207
|
+
out.append("\\begin{center}\n\\begin{tabularx}{\\linewidth}{@{}%s@{}}\n\\toprule\n" % ("X" * cols))
|
|
208
|
+
for r_index, row in enumerate(rows):
|
|
209
|
+
cells = [inline(row[c]) if c < len(row) else "" for c in range(cols)]
|
|
210
|
+
out.append(" & ".join(cells) + r" \\" + "\n")
|
|
211
|
+
if r_index == 0:
|
|
212
|
+
out.append("\\midrule\n")
|
|
213
|
+
out.append("\\bottomrule\n\\end{tabularx}\n\\end{center}\n\n")
|
|
214
|
+
continue
|
|
215
|
+
heading_match = re.match(r"^(#{1,6})\s+(.*)$", raw)
|
|
216
|
+
if heading_match:
|
|
217
|
+
flush_paragraph()
|
|
218
|
+
flush_list()
|
|
219
|
+
level = min(max(len(heading_match.group(1)) - 1, 1), 3)
|
|
220
|
+
out.append(heading(heading_match.group(2).strip(), level) + "\n")
|
|
221
|
+
i += 1
|
|
222
|
+
continue
|
|
223
|
+
list_match = re.match(r"^\s*([-*+]|\d+\.)\s+(.*)$", raw)
|
|
224
|
+
if list_match:
|
|
225
|
+
flush_paragraph()
|
|
226
|
+
kind = "ol" if re.match(r"^\s*\d+\.", raw) else "ul"
|
|
227
|
+
if list_kind is not None and list_kind != kind:
|
|
228
|
+
flush_list()
|
|
229
|
+
list_kind = kind
|
|
230
|
+
list_items.append(list_match.group(2))
|
|
231
|
+
i += 1
|
|
232
|
+
continue
|
|
233
|
+
if raw.startswith(">"):
|
|
234
|
+
flush_paragraph()
|
|
235
|
+
flush_list()
|
|
236
|
+
quote = []
|
|
237
|
+
while i < len(lines) and lines[i].startswith(">"):
|
|
238
|
+
quote.append(lines[i].lstrip("> ").strip())
|
|
239
|
+
i += 1
|
|
240
|
+
out.append("\\begin{quote}\n%s\n\\end{quote}\n\n" % inline(" ".join(quote)))
|
|
241
|
+
continue
|
|
242
|
+
if raw.strip() in ("---", "***", "___"):
|
|
243
|
+
flush_paragraph()
|
|
244
|
+
flush_list()
|
|
245
|
+
out.append("\\par\\noindent\\rule{\\linewidth}{0.4pt}\\par\\medskip\n")
|
|
246
|
+
i += 1
|
|
247
|
+
continue
|
|
248
|
+
if raw.strip() in ("\\newpage", "<!-- pagebreak -->"):
|
|
249
|
+
flush_paragraph()
|
|
250
|
+
flush_list()
|
|
251
|
+
out.append("\\newpage\n\n")
|
|
252
|
+
i += 1
|
|
253
|
+
continue
|
|
254
|
+
if raw.strip().startswith("$$"):
|
|
255
|
+
flush_paragraph()
|
|
256
|
+
flush_list()
|
|
257
|
+
block = [raw.strip()]
|
|
258
|
+
i += 1
|
|
259
|
+
# A `$$ … $$` that fits one line closes on that line; looking only at
|
|
260
|
+
# the following lines swallowed the rest of the page into display
|
|
261
|
+
# math whenever the caller had not normalized the block first.
|
|
262
|
+
closed = raw.count("$$") >= 2
|
|
263
|
+
while not closed and i < len(lines) and "$$" not in lines[i]:
|
|
264
|
+
block.append(lines[i].strip())
|
|
265
|
+
i += 1
|
|
266
|
+
if not closed and i < len(lines):
|
|
267
|
+
block.append(lines[i].strip())
|
|
268
|
+
i += 1
|
|
269
|
+
body = " ".join(block).replace("$$", "").strip()
|
|
270
|
+
out.append("\\[\n%s\n\\]\n\n" % body)
|
|
271
|
+
continue
|
|
272
|
+
buffer.append(raw)
|
|
273
|
+
i += 1
|
|
274
|
+
flush_paragraph()
|
|
275
|
+
flush_list()
|
|
276
|
+
return "".join(out)
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
def write_tex(path, body):
|
|
280
|
+
with open(path, "w", encoding="utf-8") as handle:
|
|
281
|
+
handle.write(PREAMBLE.replace("11pt", font_size(), 1) % (page_options(), cjk_font()))
|
|
282
|
+
handle.write(body)
|
|
283
|
+
handle.write("\\end{document}\n")
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
def compile_tex(tex_path, pdf_path):
|
|
287
|
+
for _ in range(2):
|
|
288
|
+
result = subprocess.run(
|
|
289
|
+
[XELATEX, "-interaction=nonstopmode", "-halt-on-error", os.path.basename(tex_path)],
|
|
290
|
+
cwd=os.path.dirname(tex_path),
|
|
291
|
+
capture_output=True,
|
|
292
|
+
text=True,
|
|
293
|
+
encoding="utf-8",
|
|
294
|
+
errors="replace",
|
|
295
|
+
)
|
|
296
|
+
if result.returncode != 0:
|
|
297
|
+
log = os.path.splitext(tex_path)[0] + ".log"
|
|
298
|
+
tail = ""
|
|
299
|
+
if os.path.exists(log):
|
|
300
|
+
with open(log, encoding="utf-8", errors="replace") as handle:
|
|
301
|
+
tail = "".join(handle.readlines()[-25:])
|
|
302
|
+
raise SystemExit("xelatex failed:\n" + result.stdout[-2000:] + "\n" + tail)
|
|
303
|
+
shutil.copyfile(os.path.splitext(tex_path)[0] + ".pdf", pdf_path)
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
def cover_tex():
|
|
307
|
+
entries = "\n".join("\\item %s" % inline(title) for _key, _file, title in CHAPTERS)
|
|
308
|
+
return (
|
|
309
|
+
"\\begin{center}\n"
|
|
310
|
+
"{\\Huge\\bfseries 中国剩余定理}\\\\[0.6em]\n"
|
|
311
|
+
"{\\Large 从《孙子算经》到环、多项式与群}\\\\[1.2em]\n"
|
|
312
|
+
"\\rule{0.6\\linewidth}{0.4pt}\\\\[0.8em]\n"
|
|
313
|
+
"{\\small 示例书库 · 由 dsh-pdf-math-desk 生成}\n"
|
|
314
|
+
"\\end{center}\n\\vspace{2em}\n"
|
|
315
|
+
"\\section*{目录}\n\\begin{itemize}\n" + entries + "\n\\end{itemize}\n"
|
|
316
|
+
)
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
def sanitize_display_math(text):
|
|
320
|
+
"""Normalize display math before conversion.
|
|
321
|
+
|
|
322
|
+
The translation model sometimes mixes inline math into a display block or
|
|
323
|
+
puts prose after the closing `$$` on the same line, which makes XeLaTeX
|
|
324
|
+
abort with "Display math should end with $$". Display blocks are rebuilt on
|
|
325
|
+
their own lines, with inner single `$` removed; trailing prose stays prose.
|
|
326
|
+
"""
|
|
327
|
+
text = text.replace("\\[", "$$").replace("\\]", "$$")
|
|
328
|
+
text = text.replace("\\(", "$").replace("\\)", "$")
|
|
329
|
+
parts = text.split("$$")
|
|
330
|
+
if len(parts) % 2 == 0:
|
|
331
|
+
parts.append("")
|
|
332
|
+
rebuilt = []
|
|
333
|
+
for index, part in enumerate(parts):
|
|
334
|
+
if index % 2 == 1:
|
|
335
|
+
body = part.replace("$", "")
|
|
336
|
+
rebuilt.append("\n\n$$\n" + body.strip() + "\n$$\n\n")
|
|
337
|
+
else:
|
|
338
|
+
rebuilt.append(part)
|
|
339
|
+
return "".join(rebuilt)
|
|
340
|
+
|
|
341
|
+
|
|
342
|
+
def main():
|
|
343
|
+
os.makedirs(OUT, exist_ok=True)
|
|
344
|
+
if os.path.isdir(WORK):
|
|
345
|
+
shutil.rmtree(WORK)
|
|
346
|
+
os.makedirs(WORK, exist_ok=True)
|
|
347
|
+
with open(SRC, encoding="utf-8") as handle:
|
|
348
|
+
lines = handle.read().split("\n")
|
|
349
|
+
groups = split_groups(lines)
|
|
350
|
+
made = []
|
|
351
|
+
|
|
352
|
+
cover_tex_path = os.path.join(WORK, "cover.tex")
|
|
353
|
+
write_tex(cover_tex_path, cover_tex())
|
|
354
|
+
cover_pdf = os.path.join(OUT, f"{BOOK}_c00_前置_封面目录.pdf")
|
|
355
|
+
compile_tex(cover_tex_path, cover_pdf)
|
|
356
|
+
made.append(os.path.basename(cover_pdf))
|
|
357
|
+
|
|
358
|
+
for key, file_title, heading_text in CHAPTERS:
|
|
359
|
+
if heading_text.startswith("附录"):
|
|
360
|
+
body = []
|
|
361
|
+
for group_title, group_lines in groups:
|
|
362
|
+
if group_title.startswith("附录"):
|
|
363
|
+
body.extend(group_lines)
|
|
364
|
+
else:
|
|
365
|
+
body = None
|
|
366
|
+
prefix = heading_text.split(":")[0].strip()
|
|
367
|
+
for group_title, group_lines in groups:
|
|
368
|
+
if group_title.startswith(prefix):
|
|
369
|
+
body = group_lines
|
|
370
|
+
break
|
|
371
|
+
if body is None:
|
|
372
|
+
raise SystemExit("missing chapter: " + heading_text)
|
|
373
|
+
tex_path = os.path.join(WORK, key + ".tex")
|
|
374
|
+
write_tex(tex_path, convert(body, heading_text))
|
|
375
|
+
name = f"{BOOK}_{key}_{file_title}.pdf"
|
|
376
|
+
compile_tex(tex_path, os.path.join(OUT, name))
|
|
377
|
+
made.append(name)
|
|
378
|
+
|
|
379
|
+
entries = []
|
|
380
|
+
total = 0
|
|
381
|
+
for name in made:
|
|
382
|
+
size = os.path.getsize(os.path.join(OUT, name))
|
|
383
|
+
total += size
|
|
384
|
+
entries.append({"name": name, "bytes": size})
|
|
385
|
+
with open(MANIFEST, "w", encoding="utf-8") as handle:
|
|
386
|
+
json.dump({
|
|
387
|
+
"version": 1,
|
|
388
|
+
"book": {
|
|
389
|
+
"id": BOOK,
|
|
390
|
+
"title": "中国剩余定理",
|
|
391
|
+
"subtitle": "从《孙子算经》到环、多项式与群",
|
|
392
|
+
"chapters": len(made),
|
|
393
|
+
"bytes": total,
|
|
394
|
+
},
|
|
395
|
+
"files": entries,
|
|
396
|
+
}, handle, ensure_ascii=False, indent=2)
|
|
397
|
+
print(json.dumps({"chapters": len(made), "bytes": total}, ensure_ascii=False))
|
|
398
|
+
|
|
399
|
+
|
|
400
|
+
if __name__ == "__main__":
|
|
401
|
+
if len(sys.argv) >= 3:
|
|
402
|
+
import tempfile
|
|
403
|
+
src, out = sys.argv[1], sys.argv[2]
|
|
404
|
+
# The heading is the caller's choice: a named artifact wants its own
|
|
405
|
+
# name, while a translated page already carries the book's chapter
|
|
406
|
+
# heading and must not repeat a temporary file name ("page-012",
|
|
407
|
+
# ".render-0.67.2") at the top. MATH_DESK_NO_TITLE=1 asks for none.
|
|
408
|
+
if len(sys.argv) > 3:
|
|
409
|
+
title = sys.argv[3]
|
|
410
|
+
elif os.environ.get("MATH_DESK_NO_TITLE") == "1":
|
|
411
|
+
title = ""
|
|
412
|
+
else:
|
|
413
|
+
title = os.path.splitext(os.path.basename(src))[0]
|
|
414
|
+
with open(src, encoding="utf-8") as handle:
|
|
415
|
+
lines = sanitize_display_math(handle.read()).split("\n")
|
|
416
|
+
work = tempfile.mkdtemp(prefix="md2tex-")
|
|
417
|
+
tex = os.path.join(work, "doc.tex")
|
|
418
|
+
write_tex(tex, convert(lines, title))
|
|
419
|
+
compile_tex(tex, out)
|
|
420
|
+
print(out)
|
|
421
|
+
else:
|
|
422
|
+
main()
|