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/__init__.py ADDED
@@ -0,0 +1 @@
1
+ __version__ = "1.0.0"
rosettex/__main__.py ADDED
@@ -0,0 +1,3 @@
1
+ from rosettex.cli import main
2
+
3
+ raise SystemExit(main())
rosettex/arxiv.py ADDED
@@ -0,0 +1,117 @@
1
+ """arXiv input parsing and polite, resumable downloads (spec §6). Stdlib only."""
2
+ import http.client
3
+ import re
4
+ import time
5
+ import urllib.error
6
+ import urllib.request
7
+ from pathlib import Path
8
+
9
+ from rosettex import __version__
10
+
11
+ BASE = "https://arxiv.org"
12
+ UA = f"rosettex/{__version__}"
13
+ SPACING = 3.0 # seconds between requests (arXiv etiquette)
14
+ TIMEOUT = 60
15
+
16
+ _ID = r"(?P<id>\d{4}\.\d{4,5}|[a-z][a-z.-]*/\d{7})(?:v(?P<ver>\d+))?"
17
+ _BARE = re.compile(rf"^(?:arxiv:)?{_ID}$", re.I)
18
+ _LINK = re.compile(rf"^(?:https?://)?(?:www\.|export\.)?arxiv\.org/(?:abs|pdf|e-print|src)/{_ID}(?:\.pdf)?/?$", re.I)
19
+ _last = 0.0
20
+
21
+
22
+ class ArxivError(Exception):
23
+ def __init__(self, code: str, message: str, status: int | None = None, content_range: str | None = None):
24
+ super().__init__(message)
25
+ self.code, self.status, self.content_range = code, status, content_range
26
+
27
+
28
+ def parse(arg: str) -> tuple[str, int | None] | None:
29
+ """'2005.11401v2', 'math/0211159', 'https://arxiv.org/pdf/2005.11401.pdf' → (id, version or None)."""
30
+ arg = re.sub(r"[?#].*$", "", arg.strip())
31
+ m = _BARE.match(arg) or _LINK.match(arg)
32
+ if not m:
33
+ return None
34
+ return m.group("id"), int(m.group("ver")) if m.group("ver") else None
35
+
36
+
37
+ def _request(url: str, method: str = "GET", headers: dict | None = None):
38
+ global _last
39
+ wait = _last + SPACING - time.monotonic()
40
+ if wait > 0:
41
+ time.sleep(wait)
42
+ _last = time.monotonic()
43
+ req = urllib.request.Request(url, method=method, headers={"User-Agent": UA, **(headers or {})})
44
+ try:
45
+ return urllib.request.urlopen(req, timeout=TIMEOUT)
46
+ except urllib.error.HTTPError as exc:
47
+ if exc.code == 404:
48
+ raise ArxivError("not_found", f"arXiv has no such paper: {url}") from None
49
+ if exc.code in (403, 410):
50
+ raise ArxivError("withdrawn", f"arXiv refuses this paper (withdrawn?): {url} HTTP {exc.code}") from None
51
+ raise ArxivError("network", f"{url}: HTTP {exc.code}", exc.code, exc.headers.get("Content-Range")) from None
52
+ except (urllib.error.URLError, TimeoutError, OSError) as exc:
53
+ raise ArxivError("network", f"{url}: {exc}") from None
54
+
55
+
56
+ def latest_version(aid: str) -> int:
57
+ """The version arXiv serves for an unversioned ID, read from the e-print's Content-Disposition."""
58
+ with _request(f"{BASE}/src/{aid}", "HEAD") as r:
59
+ m = re.search(r"v(\d+)(?:\.[\w.]+)?\"?$", r.headers.get("Content-Disposition", ""))
60
+ if not m:
61
+ raise ArxivError("network", f"cannot read the version of {aid} from arXiv")
62
+ return int(m.group(1))
63
+
64
+
65
+ def download(url: str, dest: Path) -> Path:
66
+ """GET url into dest via dest.part, resuming with Range. Skips the network when dest exists."""
67
+ dest = Path(dest)
68
+ if dest.is_file():
69
+ return dest
70
+ part = dest.with_name(dest.name + ".part")
71
+ have = part.stat().st_size if part.is_file() else 0
72
+ try:
73
+ r = _request(url, headers={"Range": f"bytes={have}-"} if have else None)
74
+ except ArxivError as exc:
75
+ if not (have and exc.status == 416):
76
+ raise
77
+ # the .part may already hold the whole file (a stop between the last write and the rename)
78
+ if exc.content_range == f"bytes */{have}":
79
+ part.replace(dest)
80
+ return dest
81
+ part.unlink()
82
+ have = 0
83
+ r = _request(url)
84
+ try:
85
+ with r:
86
+ if have and r.status != 206:
87
+ have = 0 # server ignored Range: start over
88
+ total = r.headers.get("Content-Length")
89
+ # ponytail: no Content-Length → no size check (arXiv always sends it); verify the archive if that changes
90
+ total = int(total) + have if total else None
91
+ with open(part, "ab" if have else "wb") as fh:
92
+ while chunk := r.read(1 << 16):
93
+ fh.write(chunk)
94
+ except (OSError, http.client.HTTPException) as exc:
95
+ raise ArxivError("network", f"{url}: {exc}; rerun to resume") from None
96
+ if total is not None and part.stat().st_size != total:
97
+ raise ArxivError("network", f"{url}: incomplete download ({part.stat().st_size}/{total} bytes); rerun to resume")
98
+ part.replace(dest)
99
+ return dest
100
+
101
+
102
+ def fetch(aid: str, version: int | None, dl: Path) -> dict:
103
+ """Download e-print and PDF of aid (latest version when None) into dl/. Returns the project.json 'arxiv' record."""
104
+ dl.mkdir(parents=True, exist_ok=True)
105
+ stem = aid.replace("/", "_")
106
+ if version is None:
107
+ version = latest_version(aid)
108
+ vid = f"{aid}v{version}"
109
+ urls = {"e-print": f"{BASE}/src/{vid}", "pdf": f"{BASE}/pdf/{vid}"}
110
+ eprint = download(urls["e-print"], dl / f"{stem}v{version}.e-print")
111
+ pdf = None
112
+ try:
113
+ pdf = download(urls["pdf"], dl / f"{stem}v{version}.pdf")
114
+ except ArxivError as exc:
115
+ if exc.code != "not_found":
116
+ raise
117
+ return {"id": aid, "version": version, "urls": urls, "e-print": eprint, "pdf": pdf}
rosettex/assemble.py ADDED
@@ -0,0 +1,70 @@
1
+ import shutil
2
+ from pathlib import Path
3
+
4
+ from rosettex.jsonio import write_json
5
+ from rosettex.segment import Segment, _has_translated_child, render
6
+ from rosettex.textio import read_source, write_text
7
+
8
+
9
+ def splice(text: str, edits: list[tuple[int, int, str]]) -> str:
10
+ edits = sorted(edits, key=lambda e: e[0])
11
+ for (s1, e1, _), (s2, _, _) in zip(edits, edits[1:]):
12
+ if s2 < e1:
13
+ raise ValueError(f"overlapping edits at {s1}-{e1} and {s2}")
14
+ for s, e, rep in reversed(edits):
15
+ text = text[:s] + rep + text[e:]
16
+ return text
17
+
18
+
19
+ def assemble_tree(
20
+ src_dir: Path,
21
+ out_dir: Path,
22
+ project: dict,
23
+ segments: list[Segment],
24
+ translations: dict[str, str],
25
+ keep_source: set[str] = frozenset(),
26
+ ) -> dict:
27
+ src_dir, out_dir = Path(src_dir), Path(out_dir)
28
+ if out_dir.exists():
29
+ shutil.rmtree(out_dir)
30
+ shutil.copytree(src_dir, out_dir, symlinks=False)
31
+ by_id = {s.id: s for s in segments}
32
+ effective = {k: v for k, v in translations.items() if k not in keep_source and v}
33
+ per_file: dict[str, list[tuple[int, int, str, str]]] = {}
34
+ applied = 0
35
+ for s in segments:
36
+ if s.parent is not None:
37
+ continue
38
+ if s.id in effective or _has_translated_child(s, effective, by_id):
39
+ per_file.setdefault(s.file, []).append((s.start, s.end, render(s, effective, by_id), s.id))
40
+ applied += 1
41
+ written = []
42
+ pos_map: dict[str, dict] = {"files": {}}
43
+ encodings = project.get("encodings") or {}
44
+ for rel in project["files"]:
45
+ text, enc = read_source(src_dir / rel, encodings.get(rel))
46
+ sorted_edits = sorted(per_file.get(rel, []), key=lambda e: e[0])
47
+ assembled = splice(text, [(s, e, rep) for s, e, rep, _ in sorted_edits])
48
+ delta = 0
49
+ map_edits = []
50
+ for s, e, rep, seg_id in sorted_edits:
51
+ out_s = s + delta
52
+ out_e = out_s + len(rep)
53
+ map_edits.append({"seg": seg_id, "src": [s, e], "out": [out_s, out_e]})
54
+ delta += len(rep) - (e - s)
55
+ pos_map["files"][rel] = {"source": rel, "edits": map_edits}
56
+ write_text(out_dir / f"{rel}.assembled", assembled)
57
+ if sorted_edits or enc != "utf-8":
58
+ write_text(out_dir / rel, assembled)
59
+ written.append(rel)
60
+ main_enc = encodings.get(project["main"], "utf-8")
61
+ if main_enc not in ("utf-8", "utf-8-sig"): # 8-bit source: the build copy is all UTF-8 (B sets inputenc)
62
+ for p in sorted(out_dir.rglob("*")):
63
+ rel = p.relative_to(out_dir).as_posix()
64
+ if p.suffix in (".bbl", ".tex") and p.is_file() and rel not in project["files"]:
65
+ text, enc = read_source(p, main_enc)
66
+ if enc not in ("utf-8", "utf-8-sig"):
67
+ write_text(p, text)
68
+ written.append(rel)
69
+ write_json(out_dir / "rosettex-map.json", pos_map)
70
+ return {"files_written": written, "segments_applied": applied, "map": pos_map}
rosettex/checks.py ADDED
@@ -0,0 +1,364 @@
1
+ from __future__ import annotations
2
+
3
+ from bisect import bisect_right
4
+ from collections import Counter
5
+ from dataclasses import dataclass
6
+ import re
7
+ import unicodedata
8
+
9
+ from rosettex.langdata import load_coverage, load_profile
10
+ from rosettex.numbers import extract, extract_months
11
+ from rosettex.pdf.reconcile import norm_marks
12
+ from rosettex.segment import Segment
13
+
14
+ _TOKEN = re.compile(r"⟦(/?)([a-z])(\d+)⟧")
15
+ _WORD = re.compile(r"[^\W\d_]+")
16
+
17
+ _COVERAGE: dict[str, list[list[int]]] | None = None
18
+ _COVERED_RANGES_CACHE: dict[str, tuple[list[int], list[tuple[int, int]]]] = {}
19
+ _PARSED_BLOCKS_CACHE: dict[str, list[tuple[int, int]]] = {}
20
+
21
+
22
+ @dataclass
23
+ class Issue:
24
+ segment: str
25
+ code: str
26
+ message: str
27
+ level: str = "error"
28
+
29
+
30
+ def _get_coverage() -> dict[str, list[list[int]]]:
31
+ global _COVERAGE
32
+ if _COVERAGE is None:
33
+ _COVERAGE = load_coverage()
34
+ return _COVERAGE
35
+
36
+
37
+ def _get_font_coverage_checker(tgt_lang: dict) -> tuple[list[int], list[tuple[int, int]]]:
38
+ script = tgt_lang.get("script", "")
39
+ profile = tgt_lang.get("profile") or {}
40
+ fonts = tuple(profile.get("fonts", []))
41
+ cache_key = f"{script}:{','.join(fonts)}"
42
+ if cache_key in _COVERED_RANGES_CACHE:
43
+ return _COVERED_RANGES_CACHE[cache_key]
44
+
45
+ cov = _get_coverage()
46
+ all_fonts = list(fonts) + [
47
+ "texgyretermes-regular.otf",
48
+ "lmroman10-regular.otf",
49
+ "NotoSerif-Regular.ttf",
50
+ "Tempora-Regular.otf",
51
+ "cmunrm.otf",
52
+ "Arimo-Regular.ttf",
53
+ ]
54
+ all_ranges: list[list[int]] = []
55
+ for f in all_fonts:
56
+ all_ranges.extend(cov.get(f, []))
57
+
58
+ if not all_ranges:
59
+ res = ([], [])
60
+ _COVERED_RANGES_CACHE[cache_key] = res
61
+ return res
62
+
63
+ sorted_r = sorted(all_ranges, key=lambda r: r[0])
64
+ merged: list[list[int]] = [list(sorted_r[0])]
65
+ for cur_start, cur_end in sorted_r[1:]:
66
+ prev_start, prev_end = merged[-1]
67
+ if cur_start <= prev_end + 1:
68
+ merged[-1][1] = max(prev_end, cur_end)
69
+ else:
70
+ merged.append([cur_start, cur_end])
71
+
72
+ starts = [r[0] for r in merged]
73
+ merged_tuples = [(r[0], r[1]) for r in merged]
74
+ res = (starts, merged_tuples)
75
+ _COVERED_RANGES_CACHE[cache_key] = res
76
+ return res
77
+
78
+
79
+ def _is_glyph_covered(cp: int, starts: list[int], merged: list[tuple[int, int]]) -> bool:
80
+ if not starts:
81
+ return True
82
+ idx = bisect_right(starts, cp) - 1
83
+ if idx >= 0 and merged[idx][0] <= cp <= merged[idx][1]:
84
+ return True
85
+ return False
86
+
87
+
88
+ def _get_parsed_blocks(profile: dict) -> list[tuple[int, int]]:
89
+ pid = profile.get("id", "")
90
+ if pid in _PARSED_BLOCKS_CACHE:
91
+ return _PARSED_BLOCKS_CACHE[pid]
92
+ raw_blocks = profile.get("blocks", [])
93
+ parsed = []
94
+ for b in raw_blocks:
95
+ parts = b.split("-")
96
+ if len(parts) == 2:
97
+ parsed.append((int(parts[0], 16), int(parts[1], 16)))
98
+ elif len(parts) == 1:
99
+ val = int(parts[0], 16)
100
+ parsed.append((val, val))
101
+ _PARSED_BLOCKS_CACHE[pid] = parsed
102
+ return parsed
103
+
104
+
105
+ def _in_blocks(c: str, parsed_blocks: list[tuple[int, int]]) -> bool:
106
+ o = ord(c)
107
+ return any(lo <= o <= hi for lo, hi in parsed_blocks)
108
+
109
+
110
+ def _placeholders(seg: Segment, tr: str) -> list[Issue]:
111
+ issues = []
112
+ want = Counter(m.group(0) for m in _TOKEN.finditer(seg.text))
113
+ got = Counter(m.group(0) for m in _TOKEN.finditer(tr))
114
+ missing = sorted(want - got)
115
+ extra = sorted(k for k in got if k not in want)
116
+ dup = sorted(k for k in got if k in want and got[k] > want[k])
117
+ if missing:
118
+ issues.append(Issue(seg.id, "placeholder_missing", "missing " + " ".join(missing)))
119
+ if extra:
120
+ issues.append(Issue(seg.id, "placeholder_extra", "not in the source: " + " ".join(extra)))
121
+ if dup:
122
+ issues.append(Issue(seg.id, "placeholder_duplicated", "more than once: " + " ".join(dup)))
123
+ stack, broken = [], False
124
+ last_open_pos: dict[str, int] = {}
125
+ for m in _TOKEN.finditer(tr):
126
+ closing, kind, num = m.groups()
127
+ if kind != "b":
128
+ continue
129
+ key = f"b{num}"
130
+ if not closing:
131
+ stack.append(key)
132
+ last_open_pos[key] = m.end()
133
+ elif not stack or stack[-1] != key:
134
+ broken = True
135
+ break
136
+ else:
137
+ stack.pop()
138
+ inner = tr[last_open_pos[key]:m.start()]
139
+ if not inner.strip():
140
+ broken = True
141
+ break
142
+ if broken or stack:
143
+ issues.append(Issue(seg.id, "pair_broken", "paired codes ⟦bN⟧…⟦/bN⟧ must stay in order, nested, non-empty"))
144
+ return issues
145
+
146
+
147
+ def _locale(lang: dict) -> dict:
148
+ return {"decimal": lang.get("decimal", "."), "group": lang.get("group", [","])}
149
+
150
+
151
+ def check_translation(
152
+ seg: Segment,
153
+ translation: str,
154
+ src_lang: dict,
155
+ tgt_lang: dict,
156
+ terms: list[tuple[str, str]],
157
+ recorded_hash: str | None,
158
+ budget: int | None = None,
159
+ ) -> list[Issue]:
160
+ tr = norm_marks(unicodedata.normalize("NFC", translation.strip()))
161
+ issues: list[Issue] = []
162
+ if recorded_hash is not None and recorded_hash != seg.hash:
163
+ return [Issue(seg.id, "stale", "the source text changed since this translation was written")]
164
+ issues += _placeholders(seg, tr)
165
+
166
+ # 1. Non-ASCII digits are errors (Arabic-Indic, Devanagari… digits)
167
+ foreign = [c for c in tr if unicodedata.category(c) == "Nd" and not c.isascii() and c not in seg.text]
168
+ if foreign:
169
+ issues.append(
170
+ Issue(
171
+ seg.id,
172
+ "digits",
173
+ "non-ASCII digits not allowed (keep digits ASCII 0-9): " + "".join(sorted(set(foreign))),
174
+ )
175
+ )
176
+
177
+ # 2. Number values compared as multisets
178
+ src_loc = _locale(src_lang)
179
+ src_nums = Counter(extract(seg.text, src_loc))
180
+ tgt_nums = Counter(extract(tr, _locale(tgt_lang)))
181
+ month_nums = Counter(extract_months(seg.text, src_lang))
182
+
183
+ def _nums_mismatch(sn: Counter) -> bool:
184
+ return bool((sn - tgt_nums) or ((tgt_nums - sn) - month_nums))
185
+
186
+ if _nums_mismatch(src_nums):
187
+ alt_loc = {"decimal": ".", "group": [g for g in src_loc["group"] if g not in (".", ",")]}
188
+ if src_loc["decimal"] != "," or _nums_mismatch(Counter(extract(seg.text, alt_loc))):
189
+ issues.append(
190
+ Issue(
191
+ seg.id,
192
+ "number_changed",
193
+ f"numbers differ (write them in the {tgt_lang['code']} style with the same values)",
194
+ )
195
+ )
196
+
197
+ # 3. Untranslated detection
198
+ tgt_profile = tgt_lang.get("profile")
199
+ if not tgt_profile and tgt_lang.get("script"):
200
+ tgt_profile = load_profile(tgt_lang["script"])
201
+ tgt_lang["profile"] = tgt_profile
202
+ tgt_script = (tgt_profile.get("id") if tgt_profile else None) or tgt_lang.get("script", "latin")
203
+
204
+ src_profile = src_lang.get("profile")
205
+ if not src_profile and src_lang.get("script"):
206
+ src_profile = load_profile(src_lang["script"])
207
+ src_lang["profile"] = src_profile
208
+ src_script = (src_profile.get("id") if src_profile else None) or src_lang.get("script", "latin")
209
+
210
+ if tgt_script != src_script:
211
+ # Script ratio among letters outside placeholders and kept terms
212
+ clean_tr = _TOKEN.sub(" ", tr)
213
+ for term, target in sorted(terms, key=lambda kv: len(kv[0]), reverse=True):
214
+ expect = term if target == "=" else target
215
+ if expect:
216
+ clean_tr = clean_tr.replace(expect, " ")
217
+ if term:
218
+ clean_tr = clean_tr.replace(term, " ")
219
+ letters = [c for c in clean_tr if c.isalpha()]
220
+ if len(letters) >= 6 and tgt_profile:
221
+ parsed_blocks = _get_parsed_blocks(tgt_profile)
222
+ target_hits = sum(1 for c in letters if _in_blocks(c, parsed_blocks))
223
+ ratio = target_hits / len(letters)
224
+ min_target_ratio = float(tgt_profile.get("min_target_ratio", 0.3))
225
+ if ratio < min_target_ratio:
226
+ issues.append(
227
+ Issue(
228
+ seg.id,
229
+ "untranslated",
230
+ f"target script ratio {ratio:.2f} below minimum {min_target_ratio:.2f}",
231
+ )
232
+ )
233
+ # Non-Latin source (ja, zh, ru …): letters of the source script left in the translation. A Latin source
234
+ # is exempt: names, acronyms and code in Latin letters are normal in any translation.
235
+ if src_script != "latin" and src_profile and tgt_profile:
236
+ src_blocks, tgt_blocks = _get_parsed_blocks(src_profile), _get_parsed_blocks(tgt_profile)
237
+ left = [c for c in letters if _in_blocks(c, src_blocks) and not _in_blocks(c, tgt_blocks)]
238
+ if len(left) >= 3 and len(left) >= 0.05 * len(letters) and not any(
239
+ i.code == "untranslated" for i in issues
240
+ ):
241
+ issues.append(
242
+ Issue(
243
+ seg.id,
244
+ "source_letters_left",
245
+ f"{len(left)} {src_script} letters left untranslated: " + "".join(dict.fromkeys(left))[:20],
246
+ )
247
+ )
248
+ else:
249
+ # Function-word test for equal scripts
250
+ words = [w.lower() for w in _WORD.findall(_TOKEN.sub(" ", tr))]
251
+ if src_lang.get("code") != tgt_lang.get("code") and len(words) >= 6:
252
+ src_fw = set(src_lang.get("function_words", [])) - set(tgt_lang.get("function_words", []))
253
+ hits = sum(w in src_fw for w in words)
254
+ if hits >= 3 and hits / len(words) > 0.15:
255
+ issues.append(Issue(seg.id, "untranslated", f"{hits} {src_lang['code']} function words left"))
256
+
257
+ # 3b. Missing ZWSP check for zwsp profiles (e.g. Myanmar)
258
+ if tgt_profile and tgt_profile.get("linebreak") == "zwsp":
259
+ parsed_blocks = _get_parsed_blocks(tgt_profile)
260
+ runs = _TOKEN.sub(" ", tr).split()
261
+ for run in runs:
262
+ consec = 0
263
+ for c in run:
264
+ if c == "\u200b":
265
+ consec = 0
266
+ elif _in_blocks(c, parsed_blocks):
267
+ consec += 1
268
+ if consec > 20:
269
+ issues.append(
270
+ Issue(
271
+ seg.id,
272
+ "missing_zwsp",
273
+ "spaces-free run longer than 20 characters of the script without U+200B",
274
+ )
275
+ )
276
+ break
277
+ else:
278
+ consec = 0
279
+ if consec > 20:
280
+ break
281
+
282
+ # 4. Glyph coverage
283
+ starts, merged = _get_font_coverage_checker(tgt_lang)
284
+ if starts:
285
+ clean_no_ph = _TOKEN.sub("", tr)
286
+ uncovered = sorted(
287
+ set(
288
+ c
289
+ for c in clean_no_ph
290
+ if c not in " \t\n\r\u200b\u200c\u200d\u200e\u200f"
291
+ and not _is_glyph_covered(ord(c), starts, merged)
292
+ )
293
+ )
294
+ if uncovered:
295
+ issues.append(
296
+ Issue(
297
+ seg.id,
298
+ "glyph_uncovered",
299
+ "characters outside font coverage: " + "".join(uncovered),
300
+ )
301
+ )
302
+
303
+ # 5. Kept / fixed terms
304
+ masked, tr_low = seg.text.lower(), tr.lower()
305
+ for term, target in sorted(terms, key=lambda kv: len(kv[0]), reverse=True):
306
+ pat = re.compile(rf"(?<![\w-]){re.escape(term.lower())}(?![\w-])")
307
+ if pat.search(masked):
308
+ masked = pat.sub(lambda m: "\x00" * len(m.group(0)), masked)
309
+ expect = term if target == "=" else target
310
+ if expect.lower() not in tr_low:
311
+ issues.append(Issue(seg.id, "term_mismatch", f"'{term}' must be translated as '{expect}'"))
312
+
313
+ # 6. Length ratio warning
314
+ lo_hi = tgt_lang.get("length_ratio")
315
+ if lo_hi and len(lo_hi) == 2:
316
+ lo, hi = float(lo_hi[0]), float(lo_hi[1])
317
+ clean_src = _TOKEN.sub(" ", seg.text).strip()
318
+ clean_dst = _TOKEN.sub(" ", tr).strip()
319
+ if len(clean_src) >= 40:
320
+ ratio = len(clean_dst) / len(clean_src)
321
+ if ratio < lo or ratio > hi:
322
+ issues.append(
323
+ Issue(
324
+ seg.id,
325
+ "length",
326
+ f"length ratio {ratio:.2f} outside expected [{lo:.2f}, {hi:.2f}]",
327
+ level="warning",
328
+ )
329
+ )
330
+
331
+ # 7. Character budget warning (PDF route, spec §7.7: > 25% over)
332
+ if budget and budget > 0:
333
+ clean_dst = _TOKEN.sub(" ", tr).strip()
334
+ if len(clean_dst) > 1.25 * budget:
335
+ issues.append(
336
+ Issue(
337
+ seg.id,
338
+ "budget",
339
+ f"translation is {len(clean_dst)} chars, >25% over budget {budget}",
340
+ level="warning",
341
+ )
342
+ )
343
+
344
+ return issues
345
+
346
+
347
+ def check_all(
348
+ segs: list[Segment],
349
+ translations: dict[str, str],
350
+ hashes: dict[str, str],
351
+ src_lang: dict,
352
+ tgt_lang: dict,
353
+ terms: list[tuple[str, str]],
354
+ budgets: dict[str, int] | None = None,
355
+ ) -> list[Issue]:
356
+ out = []
357
+ for s in segs:
358
+ tr = translations.get(s.id, "")
359
+ if not tr.strip():
360
+ out.append(Issue(s.id, "missing", "not translated yet"))
361
+ continue
362
+ budget = budgets.get(s.id) if budgets else None
363
+ out += check_translation(s, tr, src_lang, tgt_lang, terms, hashes.get(s.id), budget=budget)
364
+ return out