rosettex 1.0.0__py3-none-any.whl

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 (161) hide show
  1. rosettex/__init__.py +1 -0
  2. rosettex/__main__.py +3 -0
  3. rosettex/arxiv.py +117 -0
  4. rosettex/assemble.py +70 -0
  5. rosettex/checks.py +364 -0
  6. rosettex/cli.py +1138 -0
  7. rosettex/data/__init__.py +0 -0
  8. rosettex/data/commands.json +38 -0
  9. rosettex/data/fonts/LICENSES/NotoSerifBengali-OFL.txt +93 -0
  10. rosettex/data/fonts/LICENSES/NotoSerifDevanagari-OFL.txt +93 -0
  11. rosettex/data/fonts/LICENSES/NotoSerifEthiopic-OFL.txt +93 -0
  12. rosettex/data/fonts/LICENSES/NotoSerifGujarati-OFL.txt +93 -0
  13. rosettex/data/fonts/LICENSES/NotoSerifJP-OFL.txt +92 -0
  14. rosettex/data/fonts/LICENSES/NotoSerifKR-OFL.txt +92 -0
  15. rosettex/data/fonts/LICENSES/NotoSerifKannada-OFL.txt +93 -0
  16. rosettex/data/fonts/LICENSES/NotoSerifMyanmar-OFL.txt +93 -0
  17. rosettex/data/fonts/LICENSES/NotoSerifSC-OFL.txt +92 -0
  18. rosettex/data/fonts/LICENSES/NotoSerifTC-OFL.txt +92 -0
  19. rosettex/data/fonts/LICENSES/NotoSerifTamil-OFL.txt +93 -0
  20. rosettex/data/fonts/LICENSES/NotoSerifTelugu-OFL.txt +93 -0
  21. rosettex/data/fonts/LICENSES/NotoSerifThai-OFL.txt +93 -0
  22. rosettex/data/fonts/LICENSES/Vazirmatn-OFL.txt +93 -0
  23. rosettex/data/fonts/MANIFEST.json +219 -0
  24. rosettex/data/fonts/NotoSerifBengali-Regular.ttf +0 -0
  25. rosettex/data/fonts/NotoSerifDevanagari-Regular.ttf +0 -0
  26. rosettex/data/fonts/NotoSerifEthiopic-Regular.ttf +0 -0
  27. rosettex/data/fonts/NotoSerifGujarati-Regular.ttf +0 -0
  28. rosettex/data/fonts/NotoSerifJP-Regular.otf +0 -0
  29. rosettex/data/fonts/NotoSerifKR-Regular.otf +0 -0
  30. rosettex/data/fonts/NotoSerifKannada-Regular.ttf +0 -0
  31. rosettex/data/fonts/NotoSerifMyanmar-Regular.ttf +0 -0
  32. rosettex/data/fonts/NotoSerifSC-Regular.otf +0 -0
  33. rosettex/data/fonts/NotoSerifTC-Regular.otf +0 -0
  34. rosettex/data/fonts/NotoSerifTamil-Regular.ttf +0 -0
  35. rosettex/data/fonts/NotoSerifTelugu-Regular.ttf +0 -0
  36. rosettex/data/fonts/NotoSerifThai-Regular.ttf +0 -0
  37. rosettex/data/fonts/Vazirmatn-Regular.ttf +0 -0
  38. rosettex/data/fonts/__init__.py +0 -0
  39. rosettex/data/fonts/coverage.json +1 -0
  40. rosettex/data/instructions.md +19 -0
  41. rosettex/data/langs/am.json +15 -0
  42. rosettex/data/langs/ar.json +15 -0
  43. rosettex/data/langs/as.json +15 -0
  44. rosettex/data/langs/be.json +20 -0
  45. rosettex/data/langs/bg.json +20 -0
  46. rosettex/data/langs/bn.json +15 -0
  47. rosettex/data/langs/ckb.json +15 -0
  48. rosettex/data/langs/cs.json +20 -0
  49. rosettex/data/langs/de.json +55 -0
  50. rosettex/data/langs/en.json +110 -0
  51. rosettex/data/langs/es.json +23 -0
  52. rosettex/data/langs/fa.json +15 -0
  53. rosettex/data/langs/fr.json +59 -0
  54. rosettex/data/langs/gu.json +15 -0
  55. rosettex/data/langs/hi.json +15 -0
  56. rosettex/data/langs/id.json +20 -0
  57. rosettex/data/langs/it.json +20 -0
  58. rosettex/data/langs/ja.json +15 -0
  59. rosettex/data/langs/kk.json +20 -0
  60. rosettex/data/langs/kn.json +15 -0
  61. rosettex/data/langs/ko.json +46 -0
  62. rosettex/data/langs/ky.json +20 -0
  63. rosettex/data/langs/mai.json +15 -0
  64. rosettex/data/langs/mk.json +20 -0
  65. rosettex/data/langs/mn.json +20 -0
  66. rosettex/data/langs/mr.json +15 -0
  67. rosettex/data/langs/ms.json +19 -0
  68. rosettex/data/langs/my.json +15 -0
  69. rosettex/data/langs/ne.json +15 -0
  70. rosettex/data/langs/nl.json +20 -0
  71. rosettex/data/langs/pl.json +20 -0
  72. rosettex/data/langs/ps.json +15 -0
  73. rosettex/data/langs/pt.json +26 -0
  74. rosettex/data/langs/ro.json +20 -0
  75. rosettex/data/langs/ru.json +39 -0
  76. rosettex/data/langs/sa.json +15 -0
  77. rosettex/data/langs/sd.json +15 -0
  78. rosettex/data/langs/sr-Cyrl.json +20 -0
  79. rosettex/data/langs/sr-Latn.json +20 -0
  80. rosettex/data/langs/sr.json +21 -0
  81. rosettex/data/langs/sv.json +20 -0
  82. rosettex/data/langs/ta.json +15 -0
  83. rosettex/data/langs/te.json +15 -0
  84. rosettex/data/langs/tg.json +20 -0
  85. rosettex/data/langs/th.json +15 -0
  86. rosettex/data/langs/ti.json +15 -0
  87. rosettex/data/langs/tr.json +20 -0
  88. rosettex/data/langs/ug.json +15 -0
  89. rosettex/data/langs/uk.json +38 -0
  90. rosettex/data/langs/ur.json +15 -0
  91. rosettex/data/langs/vi.json +64 -0
  92. rosettex/data/langs/zh-CN.json +16 -0
  93. rosettex/data/langs/zh-HK.json +16 -0
  94. rosettex/data/langs/zh-Hans.json +18 -0
  95. rosettex/data/langs/zh-Hant.json +16 -0
  96. rosettex/data/langs/zh-MO.json +16 -0
  97. rosettex/data/langs/zh-SG.json +16 -0
  98. rosettex/data/langs/zh-TW.json +16 -0
  99. rosettex/data/langs/zh.json +16 -0
  100. rosettex/data/schemas/build.json +88 -0
  101. rosettex/data/schemas/check.json +88 -0
  102. rosettex/data/schemas/doctor.json +56 -0
  103. rosettex/data/schemas/envelope.json +125 -0
  104. rosettex/data/schemas/fetch.json +57 -0
  105. rosettex/data/schemas/fix.json +35 -0
  106. rosettex/data/schemas/guide.json +32 -0
  107. rosettex/data/schemas/install-skill.json +39 -0
  108. rosettex/data/schemas/prepare.json +49 -0
  109. rosettex/data/schemas/review.json +42 -0
  110. rosettex/data/schemas/setup.json +49 -0
  111. rosettex/data/schemas/status.json +51 -0
  112. rosettex/data/scripts/__init__.py +0 -0
  113. rosettex/data/scripts/arabic.json +24 -0
  114. rosettex/data/scripts/bengali.json +21 -0
  115. rosettex/data/scripts/cyrillic.json +19 -0
  116. rosettex/data/scripts/devanagari.json +21 -0
  117. rosettex/data/scripts/ethiopic.json +21 -0
  118. rosettex/data/scripts/gujarati.json +21 -0
  119. rosettex/data/scripts/han.json +26 -0
  120. rosettex/data/scripts/hangul.json +30 -0
  121. rosettex/data/scripts/kana.json +27 -0
  122. rosettex/data/scripts/kannada.json +21 -0
  123. rosettex/data/scripts/latin.json +21 -0
  124. rosettex/data/scripts/myanmar.json +22 -0
  125. rosettex/data/scripts/tamil.json +20 -0
  126. rosettex/data/scripts/telugu.json +21 -0
  127. rosettex/data/scripts/thai.json +20 -0
  128. rosettex/data/skill/rosettex/SKILL.md +43 -0
  129. rosettex/escape.py +87 -0
  130. rosettex/jsonio.py +24 -0
  131. rosettex/langdata.py +91 -0
  132. rosettex/mcp.py +176 -0
  133. rosettex/numbers.py +51 -0
  134. rosettex/pdf/__init__.py +6 -0
  135. rosettex/pdf/classify.py +4340 -0
  136. rosettex/pdf/extract.py +1762 -0
  137. rosettex/pdf/merge.py +429 -0
  138. rosettex/pdf/overlay.py +354 -0
  139. rosettex/pdf/pipeline.py +586 -0
  140. rosettex/pdf/reconcile.py +729 -0
  141. rosettex/pdf/rxfit.lua +387 -0
  142. rosettex/pdf/schema.py +356 -0
  143. rosettex/pdf/snippets.py +1119 -0
  144. rosettex/pdf/stream.py +1850 -0
  145. rosettex/pdf/strip.py +565 -0
  146. rosettex/postcheck.py +229 -0
  147. rosettex/protocol/skill_head.md +23 -0
  148. rosettex/segment.py +1219 -0
  149. rosettex/skill.py +296 -0
  150. rosettex/source.py +540 -0
  151. rosettex/terms.py +269 -0
  152. rosettex/texparse.py +221 -0
  153. rosettex/textio.py +55 -0
  154. rosettex/toolchain.py +424 -0
  155. rosettex/unpack.py +205 -0
  156. rosettex/workspace.py +413 -0
  157. rosettex-1.0.0.dist-info/METADATA +197 -0
  158. rosettex-1.0.0.dist-info/RECORD +161 -0
  159. rosettex-1.0.0.dist-info/WHEEL +4 -0
  160. rosettex-1.0.0.dist-info/entry_points.txt +3 -0
  161. rosettex-1.0.0.dist-info/licenses/LICENSE +25 -0
rosettex/cli.py ADDED
@@ -0,0 +1,1138 @@
1
+ import argparse
2
+ import copy
3
+ import hashlib
4
+ from importlib import resources
5
+ import json
6
+ import re
7
+ import shutil
8
+ import sys
9
+ from pathlib import Path
10
+
11
+ from rosettex import skill as skill_mod
12
+ from rosettex import terms as terms_mod
13
+ from rosettex import workspace as ws
14
+ from rosettex.build.pipeline import BuildConfigError, build as run_build
15
+ from rosettex.build.repair_state import reset_repair_state
16
+ from rosettex.checks import check_all
17
+ from rosettex.jsonio import read_json, write_json
18
+ from rosettex.langdata import load_lang
19
+ from rosettex.postcheck import report as make_report
20
+ from rosettex.segment import extract_segments
21
+ from rosettex.arxiv import ArxivError
22
+ from rosettex.source import detect_lang, effective_dir, effective_hash, fetch, file_encodings, input_tree
23
+ from rosettex.unpack import UnpackError
24
+ from rosettex.textio import read_source
25
+
26
+ DEFAULT_BUDGET = 45.0
27
+ _ANS_ID = re.compile(r"^(s\d+)\s+", re.M)
28
+ _REPAIR_ACTION = (
29
+ "Build has problems; inspect diagnosis and repair via one of the three channels: "
30
+ "(1) translation: append a corrected line 'sNNNN <translation>' to out/*.txt; "
31
+ "(2) fix: run 'rosettex fix <work> --file <source_file>' and edit work/fix/<source_file>; "
32
+ "(3) build_settings: edit work/build.json (engine, preamble_extra, shim_off). "
33
+ "Then re-run next_argv."
34
+ )
35
+ _PDF_REPAIR_ACTION = (
36
+ "Some translated segments overflow their boxes; shorten the translations listed in diagnosis "
37
+ "(keep the placeholders) by appending corrected lines 'sNNNN <translation>' to out/*.txt, "
38
+ "then re-run next_argv."
39
+ )
40
+
41
+
42
+ STATES = ("done", "partial", "needs_repair", "not_started", "ask_user", "error")
43
+ _ASK_LANG = "Ask the user for the target language if unknown, put its code in place of <code>, then run next_argv."
44
+ _DEFAULT_ACTION = {
45
+ "done": "Run next_argv.",
46
+ "partial": "Budget used up at a safe point; run next_argv to continue where it stopped.",
47
+ "needs_repair": "Fix the reported problems, then run next_argv.",
48
+ "not_started": "Do the work next_action names, then run next_argv.",
49
+ "ask_user": "Ask the user ask_user.question (offer ask_user.options), then run next_argv with the answer.",
50
+ "error": "Fix the problem named in message, then run next_argv.",
51
+ }
52
+
53
+
54
+ def _emit(data: dict, code: int) -> int:
55
+ """The §13 envelope for every command: ok, state, error (a code, when not ok), message, next_action,
56
+ next_argv, ask_user ({question, options}, when the user must decide). Exit 0 ok, 1 check/build problems,
57
+ 2 usage/environment."""
58
+ data.setdefault("ok", code == 0)
59
+ if data.get("error") is None:
60
+ data.pop("error", None)
61
+ err = data.get("error")
62
+ if err and not re.fullmatch(r"[a-z0-9_]+", str(err)): # free text (toolchain): keep it as message
63
+ data.setdefault("message", str(err))
64
+ data["error"] = "environment" if code == 2 else "failed"
65
+ st = data.get("state")
66
+ if data.get("ask_user"):
67
+ if isinstance(data["ask_user"], str):
68
+ data["ask_user"] = {"question": data["ask_user"], "options": []}
69
+ data["state"] = "ask_user"
70
+ elif st not in STATES:
71
+ data["state"] = {"complete": "done"}.get(st) or (
72
+ "error" if code == 2 else "done" if data["ok"] else "needs_repair"
73
+ )
74
+ if st and not data["ok"]:
75
+ data.setdefault("error", st)
76
+ if not data["ok"]:
77
+ data.setdefault("error", data["state"])
78
+ data.setdefault("next_argv", [])
79
+ if not data.get("next_action"):
80
+ data["next_action"] = (
81
+ "Nothing left to do." if data["ok"] and not data["next_argv"] else _DEFAULT_ACTION[data["state"]]
82
+ )
83
+ try:
84
+ sys.stdout.reconfigure(encoding="utf-8")
85
+ except AttributeError:
86
+ pass
87
+ print(json.dumps(data, ensure_ascii=False))
88
+ return code
89
+
90
+
91
+ def _fail(error: str, message: str, next_argv: list[str] | None = None, code: int = 2, **extra) -> int:
92
+ return _emit({"ok": False, "state": "error", "error": error, "message": message,
93
+ "next_argv": next_argv or [], **extra}, code)
94
+
95
+
96
+ def _missing_work(work: Path) -> int:
97
+ return _fail("missing_work", f"missing project.json in {work}: not a rosettex work dir",
98
+ _argv("fetch", "<source>", "-o", work),
99
+ next_action="Check the work dir path; if the paper was never fetched, put the paper (folder, archive, "
100
+ "arXiv ID or link) in place of <source> and run next_argv.")
101
+
102
+
103
+ def _argv(*parts) -> list[str]:
104
+ return ["rosettex", *[str(p) for p in parts]]
105
+
106
+
107
+ def _default_out(work: Path) -> Path:
108
+ """A concrete --out for next_argv (no <file.pdf> placeholder): <work>/<main stem>.<lang>.pdf."""
109
+ proj = read_json(work / "project.json")
110
+ stem = Path(proj["main"]).stem if proj.get("main") else (proj.get("stem") or "orig")
111
+ return work / f"{stem}.{proj.get('lang') or 'out'}.pdf"
112
+
113
+
114
+ def _sync(work: Path) -> dict:
115
+ return ws.sync_effective(work)
116
+
117
+
118
+ def _with_sync(payload: dict, sync_info: dict) -> dict:
119
+ if sync_info.get("resynced"):
120
+ payload["resynced"] = True
121
+ payload["translations_kept"] = sync_info["kept"]
122
+ payload["translations_lost"] = sync_info["lost"]
123
+ return payload
124
+
125
+
126
+ def _build_instructions(work: Path, tgt_lang: dict, sheets: list[str]) -> str:
127
+ tmpl = resources.files("rosettex.data").joinpath("instructions.md").read_text(encoding="utf-8")
128
+ sheet_list = ", ".join(sheets) if sheets else "read/01.md"
129
+ return tmpl.format(lang=tgt_lang["code"], work=str(work), sheets=sheet_list).rstrip()
130
+
131
+
132
+ def cmd_fetch(a) -> int:
133
+ try:
134
+ proj = fetch(a.source, Path(a.o), a.main)
135
+ except (ArxivError, UnpackError) as exc:
136
+ action = {
137
+ "network": "Network error; check the connection and re-run next_argv (downloads resume).",
138
+ "no_source": "This paper has no TeX source on arXiv; rosettex v1 cannot translate it.",
139
+ }.get(exc.code, "Fix the input and re-run.")
140
+ nxt = _argv("fetch", a.source, "-o", a.o) if exc.code == "network" else []
141
+ return _fail(exc.code, str(exc), nxt, next_action=action)
142
+ if proj.get("route") == "pdf":
143
+ return _emit(
144
+ {
145
+ "ok": True,
146
+ "route": "pdf",
147
+ "main": None,
148
+ "stem": proj.get("stem"),
149
+ "files": [],
150
+ "arxiv": proj.get("arxiv"),
151
+ "next_action": _ASK_LANG,
152
+ "next_argv": _argv("prepare", a.o, "--lang", "<code>"),
153
+ },
154
+ 0,
155
+ )
156
+ if not proj["main"]:
157
+ return _emit(
158
+ {
159
+ "ok": False,
160
+ "error": "ambiguous_main",
161
+ "ask_user": {"question": "Which file is the paper's main TeX file?", "options": proj["candidates"]},
162
+ "next_action": "Ask the user which candidate is the main file, put it in place of <candidate>, then run next_argv.",
163
+ "next_argv": _argv("fetch", a.source, "-o", a.o, "--main", "<candidate>"),
164
+ },
165
+ 2,
166
+ )
167
+ return _emit(
168
+ {
169
+ "ok": True,
170
+ "route": "tex",
171
+ "main": proj["main"],
172
+ "files": proj["files"],
173
+ "arxiv": proj.get("arxiv"),
174
+ "engine_hint": proj["engine_hint"],
175
+ "next_action": _ASK_LANG,
176
+ "next_argv": _argv("prepare", a.o, "--lang", "<code>"),
177
+ },
178
+ 0,
179
+ )
180
+
181
+
182
+ def cmd_prepare(a) -> int:
183
+ work = Path(a.work)
184
+ if not (work / "project.json").exists():
185
+ return _missing_work(work)
186
+ proj = read_json(work / "project.json")
187
+ from_arg = getattr(a, "from")
188
+ try:
189
+ tgt_lang = load_lang(a.lang)
190
+ src_lang = load_lang(from_arg) if from_arg else None
191
+ except ValueError as exc:
192
+ return _fail("bad_lang", str(exc), _argv("prepare", work, "--lang", "<code>"),
193
+ next_action="Put a supported language code (see message) in place of <code>, then run next_argv.")
194
+ if src_lang and tgt_lang["code"] == src_lang["code"]:
195
+ return _fail("same_lang", f"source and target language are the same: {tgt_lang['code']}",
196
+ _argv("prepare", work, "--lang", "<code>"), next_action=_ASK_LANG)
197
+
198
+ old_segs, old_tr = [], {}
199
+ if (work / "segments.json").exists():
200
+ old_segs = ws.load_segments(work)
201
+ for sid, entry in ws.load_translations(work).items():
202
+ if isinstance(entry, dict) and entry.get("text"):
203
+ old_tr[sid] = entry["text"]
204
+ if (work / "out").is_dir():
205
+ ans_tr, _ = ws.read_answers(work, old_segs)
206
+ old_tr.update(ans_tr)
207
+
208
+ route = a.route or ("tex" if proj.get("main") else "pdf")
209
+ if route == "pdf":
210
+ orig_pdf = work / "orig.pdf"
211
+ if not orig_pdf.is_file():
212
+ return _fail(
213
+ "no_pdf",
214
+ f"no orig.pdf in workspace {work}",
215
+ next_action="Fetch a PDF or an arXiv paper with PDF, or rerun prepare with --route tex.",
216
+ )
217
+ from rosettex.pdf import schema as pdf_schema # noqa: PLC0415
218
+ from rosettex.pdf.classify import classify as pdf_classify, to_segments as pdf_to_segments # noqa: PLC0415
219
+ from rosettex.pdf.extract import PdfError, extract as pdf_extract # noqa: PLC0415
220
+ from rosettex.pdf.pipeline import text_direction as pdf_text_direction # noqa: PLC0415
221
+ from rosettex.pdf.reconcile import is_suspect as pdf_is_suspect # noqa: PLC0415
222
+
223
+ try:
224
+ layout, chars = pdf_extract(orig_pdf)
225
+ layout = pdf_classify(layout, chars, tgt_lang["code"])
226
+ except PdfError as exc:
227
+ return _fail(exc.code, str(exc))
228
+
229
+ src_dir = pdf_text_direction(layout)
230
+ tgt_dir = (tgt_lang.get("profile") or {}).get("direction", "ltr")
231
+ if src_dir != tgt_dir:
232
+ return _fail(
233
+ "direction_change",
234
+ f"PDF route cannot change writing direction ({src_dir} → {tgt_dir}): "
235
+ "translate from the paper's TeX source instead",
236
+ next_action="Tell the user the PDF route cannot change writing direction; "
237
+ "translate from the paper's TeX source instead.",
238
+ )
239
+
240
+ segs = pdf_to_segments(layout)
241
+ for s in segs:
242
+ if not s.hash:
243
+ s.hash = hashlib.sha1(s.text.encode("utf-8")).hexdigest()[:6]
244
+
245
+ det = detect_lang(None, [], segs)
246
+ proj["source_lang"] = det["source_lang"]
247
+ proj["source_lang_signals"] = det["source_lang_signals"]
248
+ if src_lang is None:
249
+ if not det["confident"]:
250
+ write_json(work / "project.json", proj)
251
+ return _emit(
252
+ {
253
+ "ok": False,
254
+ "error": "source_lang_unclear",
255
+ "source_lang": det["source_lang"],
256
+ "source_lang_signals": det["source_lang_signals"],
257
+ "ask_user": {"question": "Which language is the paper written in?", "options": det["options"]},
258
+ "next_action": "Ask the user which language the paper is written in, put its code in place of "
259
+ "<code>, then run next_argv.",
260
+ "next_argv": _argv("prepare", work, "--lang", tgt_lang["code"], "--from", "<code>"),
261
+ },
262
+ 2,
263
+ )
264
+ src_lang = load_lang(det["source_lang"])
265
+ if tgt_lang["code"] == src_lang["code"]:
266
+ return _fail(
267
+ "same_lang",
268
+ f"the paper is already in {tgt_lang['code']} (detected: {'; '.join(det['source_lang_signals'])})",
269
+ _argv("prepare", work, "--lang", "<code>"),
270
+ next_action=_ASK_LANG,
271
+ )
272
+
273
+ (work / "pdf").mkdir(parents=True, exist_ok=True)
274
+ (work / "pdf" / "layout_base.json").unlink(missing_ok=True)
275
+ reset_repair_state(work)
276
+ pdf_schema.save(layout, work / "pdf" / "layout.json")
277
+ block_by_id = {b["id"]: b for b in layout.get("blocks") or []}
278
+ pdf_meta: dict[str, dict] = {}
279
+ for seg in layout.get("segments") or []:
280
+ blks = seg.get("blocks") or []
281
+ first_pg = block_by_id[blks[0]]["page"] if blks and blks[0] in block_by_id else 0
282
+ suspects = {
283
+ code
284
+ for code, info in (seg.get("ph") or {}).items()
285
+ if code.startswith("m") and pdf_is_suspect(info.get("raw", ""), info.get("pw"))
286
+ }
287
+ pdf_meta[seg["id"]] = {
288
+ "page": first_pg + 1,
289
+ "budget": int(seg.get("budget") or 0),
290
+ "suspects": suspects,
291
+ }
292
+
293
+ ws.save_segments(work, segs)
294
+ tr = ws.carry_over(old_segs, old_tr, segs) if old_segs else {}
295
+ if old_segs and ((work / "out").is_dir() or tr):
296
+ ws.archive_and_write_carried(work, segs, tr)
297
+ ws.save_translations(work, segs, tr)
298
+
299
+ sheets = ws.write_sheets(work, segs, tgt_lang["code"], pdf_meta=pdf_meta)
300
+ terms_mod.write_terms(work, terms_mod.candidates(segs, src_lang))
301
+
302
+ proj.update({"route": "pdf", "lang": tgt_lang["code"], "from": src_lang["code"]})
303
+ proj.setdefault("stem", Path(proj["main"]).stem if proj.get("main") else "orig")
304
+ write_json(work / "project.json", proj)
305
+ instructions = _build_instructions(work, tgt_lang, sheets)
306
+ return _emit(
307
+ {
308
+ "ok": True,
309
+ "route": "pdf",
310
+ "segments": len(segs),
311
+ "sheets": sheets,
312
+ "unknown": 0,
313
+ "instructions": instructions,
314
+ "next_action": "Translate following instructions (answers into out/*.txt), then run next_argv.",
315
+ "next_argv": _argv("check", work),
316
+ },
317
+ 0,
318
+ )
319
+
320
+ if not proj.get("main"):
321
+ return _fail(
322
+ "no_source",
323
+ "no TeX main file in workspace; use --route pdf or fetch a TeX source",
324
+ _argv("prepare", work, "--lang", tgt_lang["code"], "--route", "pdf"),
325
+ )
326
+
327
+ eff = effective_dir(work)
328
+ if re.search(r"^[^%\n]*\\documentstyle\b", read_source(eff / proj["main"])[0], re.M):
329
+ return _fail("latex209_unsupported",
330
+ f"{proj['main']} is a LaTeX 2.09 source (\\documentstyle): current TeX cannot build it, so "
331
+ "rosettex v1 cannot translate it.",
332
+ next_action="Tell the user this paper uses LaTeX 2.09 and cannot be translated by rosettex.")
333
+ eff_files = input_tree(eff, proj["main"])
334
+ proj["files"] = eff_files
335
+ proj["encodings"] = file_encodings(eff, eff_files, proj["main"])
336
+ proj["effective_hash"] = effective_hash(work, proj.get("source_hash"))
337
+ segs, unknown = extract_segments(eff, {**proj, "lang": tgt_lang["code"]})
338
+ det = detect_lang(eff, eff_files, segs)
339
+ proj["source_lang"] = det["source_lang"]
340
+ proj["source_lang_signals"] = det["source_lang_signals"]
341
+ if src_lang is None:
342
+ if not det["confident"]:
343
+ write_json(work / "project.json", proj)
344
+ return _emit(
345
+ {
346
+ "ok": False,
347
+ "error": "source_lang_unclear",
348
+ "source_lang": det["source_lang"],
349
+ "source_lang_signals": det["source_lang_signals"],
350
+ "ask_user": {"question": "Which language is the paper written in?", "options": det["options"]},
351
+ "next_action": "Ask the user which language the paper is written in, put its code in place of "
352
+ "<code>, then run next_argv.",
353
+ "next_argv": _argv("prepare", work, "--lang", tgt_lang["code"], "--from", "<code>"),
354
+ },
355
+ 2,
356
+ )
357
+ src_lang = load_lang(det["source_lang"])
358
+ if tgt_lang["code"] == src_lang["code"]:
359
+ return _fail("same_lang", f"the paper is already in {tgt_lang['code']} (detected: "
360
+ f"{'; '.join(det['source_lang_signals'])})",
361
+ _argv("prepare", work, "--lang", "<code>"), next_action=_ASK_LANG)
362
+ ws.save_segments(work, segs)
363
+
364
+ tr = ws.carry_over(old_segs, old_tr, segs) if old_segs else {}
365
+ if old_segs and ((work / "out").is_dir() or tr):
366
+ ws.archive_and_write_carried(work, segs, tr)
367
+ ws.save_translations(work, segs, tr)
368
+
369
+ sheets = ws.write_sheets(work, segs, tgt_lang["code"])
370
+ terms_mod.write_terms(work, terms_mod.candidates(segs, src_lang))
371
+ ws.write_unknown(work, unknown)
372
+
373
+ proj.update({"route": "tex", "lang": tgt_lang["code"], "from": src_lang["code"]})
374
+ write_json(work / "project.json", proj)
375
+ instructions = _build_instructions(work, tgt_lang, sheets)
376
+ return _emit(
377
+ {
378
+ "ok": True,
379
+ "route": "tex",
380
+ "segments": len(segs),
381
+ "sheets": sheets,
382
+ "unknown": len(unknown),
383
+ "instructions": instructions,
384
+ "next_action": "Translate following instructions (answers into out/*.txt), then run next_argv.",
385
+ "next_argv": _argv("check", work),
386
+ },
387
+ 0,
388
+ )
389
+
390
+
391
+ def _kept_terms(terms: list[tuple[str, str]]) -> set[str]:
392
+ return {term for term, target in terms if target == "=" or target == term}
393
+
394
+
395
+ def _check(work: Path, only_file: str | None):
396
+ proj = read_json(work / "project.json")
397
+ all_segs = ws.load_segments(work)
398
+ tr, parse_errors = ws.read_answers(work, all_segs)
399
+ prev = ws.load_translations(work)
400
+ hashes = {
401
+ sid: entry["hash"]
402
+ for sid, entry in prev.items()
403
+ if isinstance(entry, dict) and entry.get("hash") and entry.get("text") == tr.get(sid)
404
+ }
405
+ segs = all_segs
406
+ if only_file:
407
+ target = Path(only_file)
408
+ if not target.is_absolute():
409
+ target = work / target
410
+ if not target.is_file():
411
+ raise FileNotFoundError(f"answer file not found: {target}")
412
+ file_ids = set(_ANS_ID.findall(target.read_text(encoding="utf-8-sig")))
413
+ segs = [s for s in all_segs if s.id in file_ids]
414
+ rel = f"out/{target.name}"
415
+ parse_errors = [e for e in parse_errors if e.get("file") == rel]
416
+ terms = ws.read_terms(work)
417
+ budgets: dict[str, int] | None = None
418
+ d14: dict | None = None
419
+ check_segs = segs
420
+ check_tr = tr
421
+ if proj.get("route") == "pdf":
422
+ base_path = work / "pdf" / "layout_base.json"
423
+ layout_path = base_path if base_path.is_file() else (work / "pdf" / "layout.json")
424
+ if layout_path.is_file():
425
+ from rosettex.pdf.reconcile import reconcile as d14_reconcile # noqa: PLC0415
426
+
427
+ layout = read_json(layout_path)
428
+ layout_segs = {s["id"]: s for s in layout.get("segments") or []}
429
+ budgets = {s["id"]: int(s["budget"]) for s in layout.get("segments") or [] if s.get("budget")}
430
+ kept = _kept_terms(terms)
431
+ rec_segs = []
432
+ rec_tr = dict(tr)
433
+ wrapped = 0
434
+ unwrapped = 0
435
+ for s in segs:
436
+ ans = tr.get(s.id, "")
437
+ lseg = layout_segs.get(s.id)
438
+ if ans.strip() and lseg is not None:
439
+ recon = d14_reconcile(lseg, ans, kept, layout)
440
+ wrapped += len(recon.wraps)
441
+ unwrapped += len(recon.unwraps)
442
+ sc = copy.copy(s)
443
+ sc.text = recon.text
444
+ rec_segs.append(sc)
445
+ rec_tr[s.id] = recon.translation
446
+ else:
447
+ rec_segs.append(s)
448
+ check_segs = rec_segs
449
+ check_tr = rec_tr
450
+ d14 = {
451
+ "wrapped": wrapped,
452
+ "unwrapped": unwrapped,
453
+ "summary": f"math: +{wrapped} wrapped, −{unwrapped} unwrapped",
454
+ }
455
+ issues = check_all(
456
+ check_segs, check_tr, hashes, load_lang(proj["from"]), load_lang(proj["lang"]), terms, budgets=budgets
457
+ )
458
+ ws.save_translations(work, all_segs, tr)
459
+ return proj, all_segs, segs, tr, issues, parse_errors, d14
460
+
461
+
462
+ def cmd_check(a) -> int:
463
+ work = Path(a.work)
464
+ if not (work / "project.json").exists():
465
+ return _missing_work(work)
466
+ if not (work / "segments.json").exists():
467
+ return _fail("not_prepared", f"workspace not prepared: {work}", _argv("prepare", work, "--lang", "<code>"),
468
+ next_action=_ASK_LANG)
469
+ sync_info = _sync(work)
470
+ try:
471
+ _, all_segs, segs, tr, issues, parse_errors, d14 = _check(work, a.file)
472
+ except FileNotFoundError as exc:
473
+ return _fail("not_found", str(exc), _argv("check", work))
474
+
475
+ translated_count = sum(bool(tr.get(s.id)) for s in segs)
476
+ if len(segs) > 0 and translated_count == 0:
477
+ payload = _with_sync(
478
+ {
479
+ "ok": False,
480
+ "state": "not_started",
481
+ "total": len(segs),
482
+ "next_action": (
483
+ "write answers for read/01.md into out/01.txt "
484
+ "(one line per segment: sNNNN <translation>), then run rosettex check"
485
+ ),
486
+ "next_argv": _argv("check", work),
487
+ },
488
+ sync_info,
489
+ )
490
+ return _emit(payload, 1)
491
+
492
+ seg_by_id = {s.id: s for s in all_segs}
493
+ missing_ids = [i.segment for i in issues if i.code == "missing"]
494
+ missing_count = len(missing_ids)
495
+
496
+ errs: list[dict] = []
497
+ warns: list[dict] = []
498
+ for i in issues:
499
+ if i.code == "missing":
500
+ continue
501
+ s = seg_by_id.get(i.segment)
502
+ clean_src = re.sub(r"\s+", " ", s.text).strip() if s else ""
503
+ src_line = f"{s.id} {clean_src}" if s else i.segment
504
+ item = {
505
+ "id": i.segment,
506
+ "code": i.code,
507
+ "message": i.message,
508
+ "fix_hint": src_line,
509
+ }
510
+ if i.level == "warning":
511
+ warns.append(item)
512
+ else:
513
+ errs.append(item)
514
+ for pe in parse_errors:
515
+ errs.append(
516
+ {
517
+ "id": f"{pe['file']}:{pe['line']}",
518
+ "code": pe["code"],
519
+ "message": pe["message"],
520
+ "fix_hint": f"fix line {pe['line']} in {pe['file']}",
521
+ }
522
+ )
523
+
524
+ ok = not errs and missing_count == 0
525
+ payload = _with_sync(
526
+ {
527
+ "ok": ok,
528
+ "state": "done" if ok else "needs_repair",
529
+ "error": None if ok else "check_failed",
530
+ "next_action": "Run next_argv (change its --out if the user wants the PDF elsewhere)." if ok else (
531
+ "Append corrected lines (sNNNN <translation>) to out/*.txt for every error and missing "
532
+ "segment, then run next_argv."
533
+ ),
534
+ "errors": errs,
535
+ "warnings": warns,
536
+ "missing": missing_ids[:20],
537
+ "missing_count": missing_count,
538
+ "translated": len(segs) - missing_count,
539
+ "total": len(segs),
540
+ "next_argv": _argv("build", work, "--out", _default_out(work)) if ok else _argv("check", work),
541
+ },
542
+ sync_info,
543
+ )
544
+ if d14 is not None:
545
+ payload["d14"] = d14
546
+ return _emit(payload, 0 if ok else 1)
547
+
548
+
549
+ def cmd_review(a) -> int:
550
+ work = Path(a.work)
551
+ if not (work / "project.json").exists():
552
+ return _missing_work(work)
553
+ if not (work / "segments.json").exists():
554
+ return _fail("not_prepared", f"workspace not prepared: {work}", _argv("prepare", work, "--lang", "<code>"),
555
+ next_action=_ASK_LANG)
556
+ sync_info = _sync(work)
557
+ segs = ws.load_segments(work)
558
+ tr, _ = ws.read_answers(work, segs)
559
+ out_path = ws.write_review(work, segs, tr, Path(a.out) if a.out else None)
560
+ payload = _with_sync(
561
+ {
562
+ "ok": True,
563
+ "path": str(out_path),
564
+ "segments": len(segs),
565
+ "translated": sum(bool(tr.get(s.id)) for s in segs),
566
+ "next_argv": [],
567
+ },
568
+ sync_info,
569
+ )
570
+ return _emit(payload, 0)
571
+
572
+
573
+ def _norm_rel(raw: str) -> str | None:
574
+ cleaned = raw.strip().replace("\\", "/")
575
+ while cleaned.startswith("./"):
576
+ cleaned = cleaned[2:]
577
+ if not cleaned or cleaned.startswith("/") or ".." in Path(cleaned).parts:
578
+ return None
579
+ if re.match(r"^[A-Za-z]:", cleaned):
580
+ return None
581
+ return cleaned
582
+
583
+
584
+ def _fix_next_argv(work: Path) -> list[str]:
585
+ rep_path = work / "report.json"
586
+ if rep_path.is_file():
587
+ try:
588
+ rep = read_json(rep_path)
589
+ if rep.get("state") == "needs_repair" and isinstance(rep.get("next_argv"), list):
590
+ return rep["next_argv"]
591
+ except Exception:
592
+ pass
593
+ return _argv("build", work, "--out", _default_out(work))
594
+
595
+
596
+ def cmd_fix(a) -> int:
597
+ work = Path(a.work)
598
+ if not (work / "project.json").exists():
599
+ return _missing_work(work)
600
+ if read_json(work / "project.json").get("route") == "pdf":
601
+ return _fail(
602
+ "not_supported",
603
+ "fix is not supported on the PDF route (there is no TeX source to overlay); "
604
+ "fix translations by appending corrected 'sNNNN <translation>' lines to out/*.txt",
605
+ _argv("check", work),
606
+ next_action="Append corrected 'sNNNN <translation>' lines to out/*.txt, then run next_argv.",
607
+ )
608
+ if a.drop:
609
+ rel = _norm_rel(a.drop)
610
+ if not rel:
611
+ return _fail("bad_path", f"invalid path: {a.drop}")
612
+ fix_root = (work / "fix").resolve()
613
+ target = (work / "fix" / rel).resolve()
614
+ if not target.is_file() and rel.startswith("fix/"):
615
+ rel = rel[4:]
616
+ target = (work / "fix" / rel).resolve()
617
+ if not target.is_relative_to(fix_root):
618
+ return _fail("bad_path", f"path escapes fix dir: {a.drop}")
619
+ if not target.is_file():
620
+ return _fail("not_found", f"overlay file not found: fix/{rel}")
621
+ target.unlink()
622
+ parent = target.parent
623
+ while parent != fix_root and parent.is_dir():
624
+ try:
625
+ parent.rmdir()
626
+ except OSError:
627
+ break
628
+ parent = parent.parent
629
+ return _emit(
630
+ {
631
+ "ok": True,
632
+ "path": f"fix/{rel}",
633
+ "dropped": True,
634
+ "next_argv": _fix_next_argv(work),
635
+ },
636
+ 0,
637
+ )
638
+
639
+ rel = _norm_rel(a.file)
640
+ if not rel:
641
+ return _fail("bad_path", f"invalid path: {a.file}")
642
+ src_root = (work / "src").resolve()
643
+ src_file = (work / "src" / rel).resolve()
644
+ if not src_file.is_relative_to(src_root) or not src_file.is_file():
645
+ return _fail("not_found", f"not a file of the source tree: {a.file}")
646
+ fix_dir = work / "fix"
647
+ fix_dir.mkdir(parents=True, exist_ok=True)
648
+ fix_root = fix_dir.resolve()
649
+ dst = (fix_dir / rel).resolve()
650
+ if not dst.is_relative_to(fix_root):
651
+ return _fail("bad_path", f"path escapes fix dir: {a.file}")
652
+ if not dst.exists():
653
+ eff_file = effective_dir(work) / rel
654
+ source_copy = eff_file if eff_file.is_file() else src_file
655
+ dst.parent.mkdir(parents=True, exist_ok=True)
656
+ shutil.copy2(source_copy, dst)
657
+ return _emit(
658
+ {
659
+ "ok": True,
660
+ "path": f"fix/{rel}",
661
+ "next_action": f"Edit {work / 'fix' / rel} (the overlay of the source file), then run next_argv.",
662
+ "next_argv": _fix_next_argv(work),
663
+ },
664
+ 0,
665
+ )
666
+
667
+
668
+ def _build_argv(a, force: bool = False) -> list[str]:
669
+ """The same build command (for partial / needs_repair reruns)."""
670
+ argv = _argv("build", a.work, "--out", a.out)
671
+ if a.force or force:
672
+ argv.append("--force")
673
+ if a.no_agent:
674
+ argv.append("--no-agent")
675
+ if a.budget != DEFAULT_BUDGET:
676
+ argv += ["--budget", f"{a.budget:g}"]
677
+ return argv
678
+
679
+
680
+ def cmd_build(a) -> int:
681
+ work, out = Path(a.work), Path(a.out)
682
+ if not (work / "project.json").exists():
683
+ return _missing_work(work)
684
+ if out.exists() and not a.force:
685
+ return _emit(
686
+ {
687
+ "ok": False,
688
+ "error": "output_exists",
689
+ "message": f"{out} exists",
690
+ "ask_user": {"question": f"{out} already exists. Overwrite it?",
691
+ "options": ["overwrite", "choose another output path"]},
692
+ "next_action": "Ask the user; on 'overwrite' run next_argv, else rerun build with another --out.",
693
+ "next_argv": _build_argv(a, force=True),
694
+ },
695
+ 2,
696
+ )
697
+ if not (work / "segments.json").exists():
698
+ return _fail("not_prepared", f"workspace not prepared: {work}", _argv("prepare", work, "--lang", "<code>"),
699
+ next_action=_ASK_LANG)
700
+ sync_info = _sync(work)
701
+ proj, _, _, tr, issues, _, _ = _check(work, None)
702
+ bad = {i.segment for i in issues if i.code != "missing" and i.level == "error"} # warnings never keep source
703
+ untranslated = {i.segment for i in issues if i.code == "missing"}
704
+ usable = {k: v for k, v in tr.items() if k not in bad}
705
+ if proj.get("route") == "pdf":
706
+ from rosettex.pdf.extract import PdfError # noqa: PLC0415
707
+ from rosettex.pdf.pipeline import build as pdf_build # noqa: PLC0415
708
+ from rosettex.pdf.reconcile import norm_marks # noqa: PLC0415
709
+
710
+ usable_pdf = {k: norm_marks(v) for k, v in usable.items()}
711
+ kept_terms = _kept_terms(ws.read_terms(work))
712
+ try:
713
+ pdf_rep = pdf_build(
714
+ work,
715
+ proj["lang"],
716
+ usable_pdf,
717
+ fallback=a.no_agent,
718
+ agent=not a.no_agent,
719
+ kept_terms=kept_terms,
720
+ )
721
+ except PdfError as exc:
722
+ return _fail(exc.code, str(exc))
723
+ except Exception as exc: # noqa: BLE001
724
+ return _fail("build_failed", f"{type(exc).__name__}: {exc}", _argv("status", work), code=1)
725
+
726
+ kept_reasons: dict[str, str] = {}
727
+ for sid in sorted(bad):
728
+ kept_reasons[sid] = "check_error"
729
+ for sid in sorted(untranslated):
730
+ kept_reasons[sid] = "untranslated"
731
+ for sid, reason in sorted((pdf_rep.get("demoted") or {}).items()):
732
+ kept_reasons.setdefault(sid, reason)
733
+ warnings = list(pdf_rep.get("warnings") or [])
734
+
735
+ if pdf_rep.get("state") == "needs_repair":
736
+ build_argv = _build_argv(a)
737
+ rep = {
738
+ "ok": False,
739
+ "route": "pdf",
740
+ "state": "needs_repair",
741
+ "engine": "lualatex",
742
+ "pdf": None,
743
+ "problems": [],
744
+ "warnings": warnings,
745
+ "kept_source": sorted(kept_reasons),
746
+ "kept_reasons": kept_reasons,
747
+ "diagnosis": pdf_rep.get("diagnosis", []),
748
+ "rounds_left": pdf_rep.get("rounds_left", 0),
749
+ "repairs": pdf_rep.get("repairs", []),
750
+ "next_action": _PDF_REPAIR_ACTION,
751
+ "next_argv": build_argv,
752
+ "pdf_report": pdf_rep,
753
+ }
754
+ write_json(work / "report.json", rep)
755
+ payload = {
756
+ "ok": False,
757
+ "route": "pdf",
758
+ "state": "needs_repair",
759
+ "error": "needs_repair",
760
+ "pdf": None,
761
+ "engine": "lualatex",
762
+ "problems": rep["problems"],
763
+ "warnings": rep["warnings"],
764
+ "kept_source": rep["kept_source"],
765
+ "diagnosis": rep["diagnosis"],
766
+ "rounds_left": rep["rounds_left"],
767
+ "repairs": rep["repairs"],
768
+ "d14": pdf_rep.get("d14", {}),
769
+ "overflow": pdf_rep.get("overflow", []),
770
+ "seconds": pdf_rep.get("seconds", {}),
771
+ "next_action": _PDF_REPAIR_ACTION,
772
+ "next_argv": build_argv,
773
+ }
774
+ return _emit(payload, 1)
775
+
776
+ out_pdf = work / pdf_rep["out"] if pdf_rep.get("out") else work / "out.pdf"
777
+ built = out_pdf.is_file()
778
+ if built:
779
+ out.parent.mkdir(parents=True, exist_ok=True)
780
+ shutil.copyfile(out_pdf, out)
781
+
782
+ if pdf_rep.get("overflow"):
783
+ warnings.append(f"{len(pdf_rep['overflow'])} segment(s) overflowed after fallback")
784
+ rep = {
785
+ "ok": built,
786
+ "route": "pdf",
787
+ "engine": "lualatex",
788
+ "pdf": str(out) if built else None,
789
+ "problems": [],
790
+ "warnings": warnings,
791
+ "kept_source": sorted(kept_reasons),
792
+ "kept_reasons": kept_reasons,
793
+ "repairs": pdf_rep.get("repairs", []),
794
+ "pdf_report": pdf_rep,
795
+ }
796
+ write_json(work / "report.json", rep)
797
+ payload = {
798
+ "ok": rep["ok"],
799
+ "route": "pdf",
800
+ "state": "done" if built else "error",
801
+ "error": None if rep["ok"] else "build_failed",
802
+ "next_action": (
803
+ "Report the PDF path to the user; run next_argv for the final status."
804
+ if rep["ok"]
805
+ else "No PDF; see problems."
806
+ ),
807
+ "pdf": str(out) if built else None,
808
+ "engine": "lualatex",
809
+ "problems": rep["problems"],
810
+ "warnings": rep["warnings"],
811
+ "kept_source": rep["kept_source"],
812
+ "d14": pdf_rep.get("d14", {}),
813
+ "overflow": pdf_rep.get("overflow", []),
814
+ "fallback": pdf_rep.get("fallback", []),
815
+ "repairs": rep["repairs"],
816
+ "links": pdf_rep.get("links", {}),
817
+ "seconds": pdf_rep.get("seconds", {}),
818
+ "next_argv": _argv("status", work),
819
+ }
820
+ return _emit(payload, 0 if rep["ok"] else 1)
821
+ try:
822
+ res = run_build(work, proj["lang"], usable, agent=not a.no_agent, budget=a.budget)
823
+ except BuildConfigError as exc:
824
+ return _fail("build_config", str(exc), _build_argv(a),
825
+ next_action=f"Fix {work / 'build.json'} as message says, then run next_argv.")
826
+ if res.get("state") == "partial":
827
+ st_path = work / "build_state.json" # status reruns exactly this argv (the --out is known only here)
828
+ write_json(st_path, {**read_json(st_path), "argv": _build_argv(a)})
829
+ return _emit(
830
+ _with_sync({"ok": False, "state": "partial", "error": "budget", "pdf": None,
831
+ "next_argv": _build_argv(a)}, sync_info),
832
+ 1,
833
+ )
834
+
835
+ rep = make_report(res, load_lang(proj["lang"]))
836
+ kept_reasons: dict[str, str] = {}
837
+ for sid in sorted(bad):
838
+ kept_reasons[sid] = "check_error"
839
+ for sid in sorted(untranslated):
840
+ kept_reasons[sid] = "untranslated"
841
+ for sid in res["culprits"]:
842
+ kept_reasons[sid] = "culprit"
843
+ for sid in res.get("bisect_cap_kept", []):
844
+ kept_reasons[sid] = "bisect_cap"
845
+ rep["kept_source"] = sorted(kept_reasons)
846
+ rep["kept_reasons"] = kept_reasons
847
+ rep["culprits"] = res["culprits"]
848
+ rep["bisect_compiles"] = res.get("bisect_compiles", 0)
849
+ rep["bisect_capped"] = res.get("bisect_capped", False)
850
+ rep["baseline_failed"] = res.get("baseline_failed", False)
851
+ rep["repairs"] = res.get("repairs", [])
852
+ rep["installed"] = res.get("installed", [])
853
+ rep["install_failed"] = res.get("install_failed", [])
854
+ if res.get("diagnosis"):
855
+ rep["diagnosis"] = res["diagnosis"]
856
+ if rep["baseline_failed"]:
857
+ rep["problems"].append({"code": "baseline_failed", "message": "baseline (untranslated + shim) failed"})
858
+
859
+ if res.get("guard_refused"):
860
+ guard_errs = res.get("guard_errors", [])
861
+ rep["ok"] = False
862
+ rep["state"] = "guard_refused"
863
+ rep["guard_refused"] = True
864
+ rep["guard_errors"] = guard_errs
865
+ rep["problems"] = [{"code": "guard_refused", "message": "; ".join(guard_errs)}]
866
+ write_json(work / "report.json", rep)
867
+ payload = _with_sync(
868
+ {
869
+ "ok": False,
870
+ "state": "error",
871
+ "error": "guard_refused",
872
+ "pdf": None,
873
+ "engine": rep["engine"],
874
+ "problems": rep["problems"],
875
+ "warnings": rep["warnings"],
876
+ "kept_source": rep["kept_source"],
877
+ "guard_errors": guard_errs,
878
+ "repairs": rep["repairs"],
879
+ "next_action": (
880
+ "Build refused by security read guard; remove forbidden paths or Lua execution "
881
+ "from overlays or build.json preamble_extra."
882
+ ),
883
+ "next_argv": _argv("status", work),
884
+ },
885
+ sync_info,
886
+ )
887
+ return _emit(payload, 1)
888
+
889
+ if res.get("state") == "needs_repair":
890
+ build_argv = _build_argv(a)
891
+ rep["ok"] = False
892
+ rep["state"] = "needs_repair"
893
+ rep["pdf"] = None
894
+ rep["rounds_left"] = res["rounds_left"]
895
+ rep["diagnosis"] = res.get("diagnosis", [])
896
+ rep["next_action"] = _REPAIR_ACTION
897
+ rep["next_argv"] = build_argv
898
+ write_json(work / "report.json", rep)
899
+ payload = _with_sync(
900
+ {
901
+ "ok": False,
902
+ "state": "needs_repair",
903
+ "error": "needs_repair",
904
+ "pdf": None,
905
+ "engine": rep["engine"],
906
+ "problems": rep["problems"],
907
+ "warnings": rep["warnings"],
908
+ "kept_source": rep["kept_source"],
909
+ "diagnosis": rep["diagnosis"],
910
+ "rounds_left": res["rounds_left"],
911
+ "repairs": rep["repairs"],
912
+ "next_action": _REPAIR_ACTION,
913
+ "next_argv": build_argv,
914
+ },
915
+ sync_info,
916
+ )
917
+ return _emit(payload, 1)
918
+
919
+ write_json(work / "report.json", rep)
920
+ if res["pdf"]:
921
+ out.parent.mkdir(parents=True, exist_ok=True)
922
+ shutil.copyfile(res["pdf"], out)
923
+ payload = _with_sync(
924
+ {
925
+ "ok": rep["ok"],
926
+ "state": "done" if res["pdf"] else "error",
927
+ "error": None if rep["ok"] else ("build_problems" if res["pdf"] else "build_failed"),
928
+ "next_action": "Report the PDF path to the user; run next_argv for the final status." if rep["ok"] else (
929
+ "The PDF was built with problems (see problems, diagnosis, kept_source); tell the user, "
930
+ "then run next_argv." if res["pdf"] else "No PDF; see problems and diagnosis."
931
+ ),
932
+ "pdf": str(out) if res["pdf"] else None,
933
+ "engine": rep["engine"],
934
+ "problems": rep["problems"],
935
+ "warnings": rep["warnings"],
936
+ "kept_source": rep["kept_source"],
937
+ "repairs": rep["repairs"],
938
+ "next_argv": _argv("status", work),
939
+ },
940
+ sync_info,
941
+ )
942
+ if rep.get("diagnosis"):
943
+ payload["diagnosis"] = rep["diagnosis"]
944
+ return _emit(payload, 0 if rep["ok"] else 1)
945
+
946
+
947
+ def cmd_status(a) -> int:
948
+ work = Path(a.work)
949
+ if not (work / "project.json").exists():
950
+ return _missing_work(work)
951
+ proj = read_json(work / "project.json")
952
+ route = proj.get("route") or ("tex" if proj.get("main") else "pdf")
953
+ sync_info = _sync(work)
954
+ if not (work / "segments.json").exists():
955
+ return _emit(
956
+ {
957
+ "ok": True,
958
+ "route": route,
959
+ "state": "not_started",
960
+ "next_action": _ASK_LANG,
961
+ "stage": "fetched",
962
+ "translated": 0,
963
+ "total": 0,
964
+ "next_argv": _argv("prepare", work, "--lang", "<code>"),
965
+ },
966
+ 0,
967
+ )
968
+ segs = ws.load_segments(work)
969
+ tr = ws.read_answers(work, segs)[0] if (work / "out").is_dir() else {}
970
+ done = sum(bool(tr.get(s.id)) for s in segs)
971
+ rep_path = work / "report.json"
972
+ if (work / "build_state.json").exists(): # a budget-stopped build records its argv at the stop
973
+ stage, nxt = "building", (read_json(work / "build_state.json").get("argv")
974
+ or _argv("build", work, "--out", _default_out(work)))
975
+ elif rep_path.exists():
976
+ rep = read_json(rep_path)
977
+ if rep.get("state") == "needs_repair":
978
+ stage = "needs_repair"
979
+ nxt = rep.get("next_argv") or _argv("build", work, "--out", _default_out(work))
980
+ else:
981
+ stage, nxt = "built", []
982
+ elif done == len(segs):
983
+ stage, nxt = "checked", _argv("check", work)
984
+ else:
985
+ stage, nxt = ("translating" if done else "prepared"), _argv("check", work)
986
+ state = {"built": "done", "needs_repair": "needs_repair", "prepared": "not_started"}.get(stage, "partial")
987
+ payload = _with_sync(
988
+ {
989
+ "ok": True,
990
+ "route": route,
991
+ "state": state,
992
+ "stage": stage,
993
+ "translated": done,
994
+ "total": len(segs),
995
+ "next_argv": nxt,
996
+ },
997
+ sync_info,
998
+ )
999
+ return _emit(payload, 0)
1000
+
1001
+
1002
+ def cmd_setup(a) -> int:
1003
+ from rosettex import toolchain
1004
+
1005
+ data, code = toolchain.setup(a.yes, a.budget, a.tex)
1006
+ if isinstance(data.get("ask_user"), str):
1007
+ data["ask_user"] = {"question": data["ask_user"],
1008
+ "options": ["install the private TeX Live", "use the system TeX Live"]}
1009
+ data["error"] = "confirm_install"
1010
+ data["next_action"] = ("Ask the user; on install run next_argv, on system TeX run "
1011
+ "'rosettex setup --tex system'.")
1012
+ elif data.get("state") == "partial" and code == 2: # a failed step (resumable): an environment error
1013
+ data["state"] = "error"
1014
+ data["message"], data["error"] = data.get("error"), "setup_failed"
1015
+ elif data.get("state") == "partial":
1016
+ data["error"] = "budget"
1017
+ return _emit(data, code)
1018
+
1019
+
1020
+ def cmd_doctor(a) -> int:
1021
+ from rosettex import toolchain
1022
+
1023
+ data, code = toolchain.doctor(a.force)
1024
+ if not data["ok"] and code == 1:
1025
+ data.update(state="error", error="doctor_failed")
1026
+ return _emit(data, code)
1027
+
1028
+
1029
+ def cmd_guide(a) -> int:
1030
+ text = skill_mod.render_guide()
1031
+ if a.json:
1032
+ return _emit({"ok": True, "state": "done", "text": text, "next_argv": []}, 0)
1033
+ try:
1034
+ sys.stdout.reconfigure(encoding="utf-8")
1035
+ except AttributeError:
1036
+ pass
1037
+ print(text)
1038
+ return 0
1039
+
1040
+
1041
+ def cmd_install_skill(a) -> int:
1042
+ results = skill_mod.install_skill(remove=a.remove, force=a.force)
1043
+ if a.json:
1044
+ return _emit({"ok": True, "state": "done", "locations": results, "next_argv": []}, 0)
1045
+ try:
1046
+ sys.stdout.reconfigure(encoding="utf-8")
1047
+ except AttributeError:
1048
+ pass
1049
+ for item in results:
1050
+ status = item["status"]
1051
+ loc = item["path"]
1052
+ reason = item.get("reason")
1053
+ if reason:
1054
+ print(f"{loc}: {status} ({reason})")
1055
+ else:
1056
+ print(f"{loc}: {status}")
1057
+ return 0
1058
+
1059
+
1060
+ class _UsageError(Exception):
1061
+ pass
1062
+
1063
+
1064
+ class _Parser(argparse.ArgumentParser):
1065
+ def error(self, message): # subparsers inherit this class
1066
+ raise _UsageError(f"{self.prog}: {message}")
1067
+
1068
+
1069
+ def main(argv=None) -> int:
1070
+ argv = sys.argv[1:] if argv is None else list(argv)
1071
+ try:
1072
+ return _main(argv)
1073
+ except _UsageError as exc:
1074
+ if "--json" in argv:
1075
+ return _fail("usage", str(exc), _argv("guide"),
1076
+ next_action="Fix the command line (rosettex <command> --help), see next_argv for the protocol.")
1077
+ print(f"usage error: {exc}", file=sys.stderr)
1078
+ return 2
1079
+
1080
+
1081
+ def _main(argv: list[str]) -> int:
1082
+ p = _Parser(prog="rosettex")
1083
+ sub = p.add_subparsers(dest="cmd", required=True)
1084
+ f = sub.add_parser("fetch")
1085
+ f.add_argument("source")
1086
+ f.add_argument("-o", required=True)
1087
+ f.add_argument("--main", help="main .tex file (relative to the source) when detection is ambiguous")
1088
+ pr = sub.add_parser("prepare")
1089
+ pr.add_argument("work")
1090
+ pr.add_argument("--lang", required=True)
1091
+ pr.add_argument("--from", default=None, help="source language (default: detected from the source)")
1092
+ pr.add_argument("--route", choices=["tex", "pdf"], default=None, help="translation route (default: auto)")
1093
+ c = sub.add_parser("check")
1094
+ c.add_argument("work")
1095
+ c.add_argument("--file")
1096
+ rv = sub.add_parser("review")
1097
+ rv.add_argument("work")
1098
+ rv.add_argument("--out")
1099
+ fx = sub.add_parser("fix")
1100
+ fx.add_argument("work")
1101
+ fx_grp = fx.add_mutually_exclusive_group(required=True)
1102
+ fx_grp.add_argument("--file")
1103
+ fx_grp.add_argument("--drop")
1104
+ b = sub.add_parser("build")
1105
+ b.add_argument("work")
1106
+ b.add_argument("--out", required=True)
1107
+ b.add_argument("--force", action="store_true")
1108
+ b.add_argument("--no-agent", action="store_true")
1109
+ b.add_argument("--budget", type=float, default=DEFAULT_BUDGET,
1110
+ help="seconds; stop at a safe point and return state partial (default 45)")
1111
+ s = sub.add_parser("status")
1112
+ s.add_argument("work")
1113
+ g = sub.add_parser("guide")
1114
+ ins = sub.add_parser("install-skill")
1115
+ ins.add_argument("--remove", action="store_true")
1116
+ ins.add_argument("--force", action="store_true")
1117
+ su = sub.add_parser("setup")
1118
+ su.add_argument("--yes", action="store_true")
1119
+ su.add_argument("--budget", type=float)
1120
+ su.add_argument("--tex", choices=["private", "system"], default="private")
1121
+ dr = sub.add_parser("doctor")
1122
+ dr.add_argument("--force", action="store_true")
1123
+ for sp in (f, pr, c, rv, fx, b, s, g, ins, su, dr):
1124
+ sp.add_argument("--json", action="store_true")
1125
+ a = p.parse_args(argv)
1126
+ return {
1127
+ "fetch": cmd_fetch,
1128
+ "prepare": cmd_prepare,
1129
+ "check": cmd_check,
1130
+ "review": cmd_review,
1131
+ "fix": cmd_fix,
1132
+ "build": cmd_build,
1133
+ "status": cmd_status,
1134
+ "guide": cmd_guide,
1135
+ "install-skill": cmd_install_skill,
1136
+ "setup": cmd_setup,
1137
+ "doctor": cmd_doctor,
1138
+ }[a.cmd](a)