Repository navigation
Expand file tree
/
Copy pathtxproject.py
More file actions
417 lines (357 loc) · 17.4 KB
/
Copy pathtxproject.py
File metadata and controls
417 lines (357 loc) · 17.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
"""txproject.py — the translation editor's project file, TSV and paste formats.
A translation project is a small JSON file that holds ONLY what the
translator typed, keyed by the catalog row ids (which are retail-relative:
ovl addresses, evt pool slots, textpack slots). It never stores an encoded
or re-exported tree, because re-exporting a patched disc gives misleading
budgets and moved keys; every build starts again from the retail image the
project is pinned to (``retail_id``).
{"format": 1, "language": "fr", "retail_id": "<sha1>",
"translations": {id: {"text": str, "state": "draft"|"done"}},
"target": {...}} # optional, see txtarget.normalise_target
Three text interchange formats live here so the server and the page agree
on one definition:
* TSV: ``id <TAB> source <TAB> translation`` with ``\\n``, ``\\t`` and
``\\\\`` escapes, for spreadsheets and CAT tools.
* The numbered "group paste" block used by the editor's "Copy group for
translation" / "Paste translations into group" buttons: one line per
string, ``[n] text``, with internal line breaks written as ``⏎``. Machine
translators and chat assistants keep ``[n]`` markers and a symbol like ``⏎``
far more reliably than they keep blank-line structure, and when they do
re-wrap a long line the continuation is simply joined back with a space.
Run ``python3 txproject.py selftest --iso RETAIL`` to check the formats
round-trip and that the retail id can be computed (read-only).
"""
from __future__ import annotations
import hashlib
import json
import os
import re
import sys
import tempfile
from pathlib import Path
from typing import Dict, Iterable, List, Optional, Tuple
FORMAT = 1
STATES = ("draft", "done")
NEWLINE_MARK = "\u23ce" # ⏎
BOOT_ELF = "SLUS_204.69" # Xenosaga Episode I (USA)
class ProjectError(ValueError):
pass
# ---------------------------------------------------------------------------
# retail id
# ---------------------------------------------------------------------------
def retail_id(iso_path: str) -> str:
"""sha1 of the boot ELF, every overlay (``OV*.OVL``) and the three TOC
files (``XENOSAGA.00 / .10 / .20``, whole).
Size cannot tell retail from patched copies (they are all 8,468,299,776
bytes until something grows). The executables carry every menu string,
and a TOC entry records each object's sector and size, so a kit import
that changes the executables, moves an object or changes its length
shows up here. (An earlier version hashed only the first 64 KiB of
XENOSAGA.00 and missed a translated copy whose changed entries sat
further in.) A same-length, in-place replacement of a TOC object is
still invisible; nothing short of hashing the whole image catches that.
Read-only; about 6 MB read.
"""
from iso9660 import IsoImage
iso = IsoImage(iso_path)
try:
elf = iso.boot_elf_name() or "SLUS_204.69"
if elf not in iso.files:
raise ProjectError(f"{iso_path}: no boot executable on the disc")
if elf.upper() != BOOT_ELF:
# every reader is keyed to the USA executable's layout; another disc
# (Episode II has a XENOSAGA.00 too) would be read as byte soup
raise ProjectError(f"{iso_path}: not Xenosaga Episode I (USA): the boot "
f"executable is {elf}, not {BOOT_ELF}")
if "XENOSAGA.00" not in iso.files:
raise ProjectError(f"{iso_path}: no XENOSAGA.00 on the disc")
h = hashlib.sha1()
names = [elf] + sorted(n for n in iso.files if n.upper().endswith(".OVL")) + \
[n for n in ("XENOSAGA.00", "XENOSAGA.10", "XENOSAGA.20") if n in iso.files]
for name in names:
h.update(name.encode("ascii", "replace") + b"\0")
h.update(iso.read_file(name))
return h.hexdigest()
finally:
iso.close()
# ---------------------------------------------------------------------------
# project load / save / merge
# ---------------------------------------------------------------------------
def new_project(language: str = "fr", rid: str = "") -> dict:
return {"format": FORMAT, "language": language, "retail_id": rid,
"translations": {}}
def normalise(project: dict) -> dict:
"""Validate a project dict and return a clean copy (drops empty texts,
unknown states become "draft")."""
if not isinstance(project, dict):
raise ProjectError("project must be a JSON object")
fmt = project.get("format", FORMAT)
if fmt != FORMAT:
raise ProjectError(f"unsupported project format {fmt!r} (this kit reads {FORMAT})")
tr_in = project.get("translations") or {}
if not isinstance(tr_in, dict):
raise ProjectError("'translations' must be an object of id -> {text, state}")
tr: Dict[str, dict] = {}
for k, v in tr_in.items():
if isinstance(v, str):
v = {"text": v, "state": "draft"}
if not isinstance(v, dict) or not isinstance(v.get("text"), str):
raise ProjectError(f"translation {k!r} has no text")
if v["text"] == "":
continue
st = v.get("state") if v.get("state") in STATES else "draft"
tr[str(k)] = {"text": v["text"], "state": st}
out = {"format": FORMAT,
"language": str(project.get("language") or "fr"),
"retail_id": str(project.get("retail_id") or ""),
"translations": tr}
# what the translator reads from (the editor's step 2): {"id": "en-usa"} or
# {"id": "ja-reloaded", "path": <the Reloaded ISO>} (txsource); and the
# name a custom language was given (its target code may be "other")
src = project.get("source")
if src is not None:
if not isinstance(src, dict) or not isinstance(src.get("id", ""), str):
raise ProjectError("'source' must be an object {\"id\": ..., \"path\": ...}")
out["source"] = {k: str(src[k]) for k in ("id", "path") if src.get(k)}
if isinstance(project.get("language_name"), str) and project["language_name"].strip():
out["language_name"] = project["language_name"].strip()
tgt = project.get("target")
if tgt is not None:
# what the build draws the language with (txtarget.normalise_target:
# code, kind, script, rtl, font, face, px, align, ...); kept as given
if not isinstance(tgt, dict):
raise ProjectError("'target' must be an object (see txtarget.py)")
from txtarget import normalise_target, TargetError
try:
out["target"] = normalise_target(tgt)
except TargetError as exc:
raise ProjectError(f"target: {exc}") from None
return out
def load(path: str) -> dict:
with open(path, "r", encoding="utf-8", newline="") as fh:
try:
data = json.load(fh)
except json.JSONDecodeError as exc:
raise ProjectError(f"{path}: not valid JSON ({exc})") from None
return normalise(data)
def dumps(project: dict) -> str:
p = normalise(project)
p["translations"] = dict(sorted(p["translations"].items()))
return json.dumps(p, ensure_ascii=False, indent=1) + "\n"
def save(path: str, project: dict) -> None:
"""Atomic write: temp file in the same folder, fsync, rename."""
text = dumps(project)
dst = Path(path).expanduser()
dst.parent.mkdir(parents=True, exist_ok=True)
fd, tmp = tempfile.mkstemp(prefix="." + dst.name + ".", suffix=".tmp", dir=str(dst.parent))
try:
with os.fdopen(fd, "w", encoding="utf-8", newline="") as fh:
fh.write(text)
fh.flush()
os.fsync(fh.fileno())
os.chmod(tmp, 0o644) # mkstemp makes 0600; a project is an ordinary document
os.replace(tmp, dst)
except BaseException:
try:
os.unlink(tmp)
except OSError:
pass
raise
def merge(base: dict, other: dict, overwrite: bool = False) -> Tuple[dict, int]:
"""Copy translations from ``other`` into ``base``; existing entries are
kept unless ``overwrite``. Returns (new project, number of ids taken)."""
out = normalise(base)
n = 0
for k, v in normalise(other)["translations"].items():
if overwrite or k not in out["translations"]:
if out["translations"].get(k) != v:
out["translations"][k] = dict(v)
n += 1
return out, n
# ---------------------------------------------------------------------------
# TSV
# ---------------------------------------------------------------------------
def tsv_escape(s: str) -> str:
return s.replace("\\", "\\\\").replace("\t", "\\t").replace("\n", "\\n").replace("\r", "\\r")
def tsv_unescape(s: str) -> str:
out, i = [], 0
while i < len(s):
c = s[i]
if c == "\\" and i + 1 < len(s):
nxt = s[i + 1]
rep = {"n": "\n", "t": "\t", "\\": "\\", "r": "\r"}.get(nxt)
if rep is not None:
out.append(rep)
i += 2
continue
out.append(c)
i += 1
return "".join(out)
TSV_HEADER = "id\tsource\ttranslation"
def _unquote_cell(c: str) -> str:
"""Undo spreadsheet quoting: Excel / LibreOffice save a tab-delimited cell
that contains a double quote as "...", with each inner quote doubled
(tabs and line breaks are already \\t / \\n here, so a quote is the only
reason a cell gets quoted). Anything else is left as typed."""
if len(c) >= 2 and c[0] == '"' and c[-1] == '"':
inner = c[1:-1]
if '""' in inner and '"' not in inner.replace('""', ""):
return inner.replace('""', '"')
return c
def export_tsv(project: dict, rows: Iterable[dict], only_translated: bool = False) -> str:
"""One line per catalog row (locked rows skipped), header first."""
tr = normalise(project)["translations"]
lines = [TSV_HEADER]
for r in rows:
if r.get("lock"):
continue
t = tr.get(r["id"], {}).get("text", "")
if only_translated and not t:
continue
lines.append("\t".join((r["id"], tsv_escape(r.get("src", "")), tsv_escape(t))))
return "\n".join(lines) + "\n"
def import_tsv(text: str, project: dict, rows: Optional[Iterable[dict]] = None,
state: str = "draft") -> Tuple[dict, int, List[str]]:
"""Apply a TSV (id, source, translation) to ``project``.
Lines with an empty translation are skipped (they do not clear work).
With ``rows`` given, unknown or locked ids are reported and skipped, and
a source column that no longer matches the catalog is reported as a
note but still imported. Returns (project, applied, problems).
"""
out = normalise(project)
known = {r["id"]: r for r in rows} if rows is not None else None
problems: List[str] = []
n = 0
for ln, raw in enumerate(text.lstrip("\ufeff").splitlines(), 1):
if not raw.strip() or (ln == 1 and raw.strip().lower().startswith("id\t")):
continue
cols = raw.split("\t")
if len(cols) < 3:
problems.append(f"line {ln}: expected 3 tab-separated columns, got {len(cols)}")
continue
cols = [_unquote_cell(c) for c in cols]
rid, src, tr = cols[0].strip(), tsv_unescape(cols[1]), tsv_unescape("\t".join(cols[2:]))
if not tr:
continue
if known is not None:
row = known.get(rid)
if row is None:
problems.append(f"line {ln}: unknown id {rid}")
continue
if row.get("lock"):
problems.append(f"line {ln}: {rid} is locked ({row['lock']})")
continue
if src and src != row.get("src", ""):
problems.append(f"line {ln}: {rid} source differs from the disc (imported anyway)")
out["translations"][rid] = {"text": tr, "state": state}
n += 1
return out, n, problems
# ---------------------------------------------------------------------------
# numbered group-paste blocks
# ---------------------------------------------------------------------------
GROUP_INTRO = ("Translate each numbered line into {lang}. Keep every [number] marker, "
"every \u23ce symbol and every \u27e6..\u27e7 or /[...] token exactly as written. "
"One numbered line out per numbered line in.")
_MARK_RE = re.compile(r"^\s*[\[\uff3b](\d{1,5})[\]\uff3d]\s?(.*)$")
_NL_RE = re.compile("\u23ce") # exactly: spaces around it are text (indents, padding)
def format_group(items: List[Tuple[int, str]], language: str = "") -> str:
"""``items`` = [(number, display text)]. Line breaks become ⏎."""
lines = []
if language:
lines += [GROUP_INTRO.format(lang=language), ""]
for n, text in items:
lines.append(f"[{n}] " + text.replace("\r\n", "\n").replace("\n", NEWLINE_MARK))
return "\n".join(lines) + "\n"
def parse_group(text: str) -> Tuple[Dict[int, str], List[str]]:
"""Inverse of format_group. Lines before the first marker are ignored;
a line without a marker continues the previous block (joined with a
space, since real line breaks are spelled ⏎). Returns ({n: text}, notes)."""
out: Dict[int, List[str]] = {}
notes: List[str] = []
cur: Optional[int] = None
for raw in text.replace("\r\n", "\n").replace("\r", "\n").split("\n"):
m = _MARK_RE.match(raw)
if m:
cur = int(m.group(1))
if cur in out:
notes.append(f"[{cur}] appears twice; the last one wins")
out[cur] = [m.group(2)]
elif cur is not None and raw.strip():
out[cur].append(raw.strip())
res = {}
for n, parts in out.items():
joined = " ".join(p for p in parts if p != "") if len(parts) > 1 else parts[0]
res[n] = _NL_RE.sub("\n", joined)
return res, notes
# ---------------------------------------------------------------------------
# selftest
# ---------------------------------------------------------------------------
def selftest(iso: Optional[str]) -> int:
ok = True
def check(cond, what):
nonlocal ok
print(("ok " if cond else "FAIL ") + what)
ok = ok and bool(cond)
tricky = "Ligne 1\tTab \\ «guillemets» ¿qué? ¡sí!\nLigne 2 ⟦0C⟧⟦54⟧ /[label(Shion)]"
check(tsv_unescape(tsv_escape(tricky)) == tricky, "TSV escape round-trip")
rows = [{"id": "evt:a", "src": "Hello\nthere", "lock": None},
{"id": "ovl:b", "src": "Item\tX", "lock": None},
{"id": "ovl:c", "src": "id", "lock": "identifier"}]
p = new_project("fr", "x")
p["translations"]["evt:a"] = {"text": tricky, "state": "done"}
tsv = export_tsv(p, rows)
check("ovl:c" not in tsv, "TSV export skips locked rows")
p2, n, probs = import_tsv(tsv, new_project("fr", "x"), rows)
check(n == 1 and p2["translations"]["evt:a"]["text"] == tricky and not probs,
f"TSV import round-trip (n={n}, problems={probs})")
_, n3, probs3 = import_tsv("evt:zz\ta\tb\novl:c\tid\tident\n", new_project(), rows)
check(n3 == 0 and len(probs3) == 2, "TSV import rejects unknown + locked ids")
p4, n4, _ = import_tsv('\ufeffid\tsource\ttranslation\nevt:a\tHello\t"Le ""Club"" U.M.N."\n'
'ovl:b\tItem\t"Oui"\n', new_project(), rows)
check(n4 == 2 and p4["translations"]["evt:a"]["text"] == 'Le "Club" U.M.N.'
and p4["translations"]["ovl:b"]["text"] == '"Oui"',
"TSV import undoes spreadsheet quoting and a BOM, keeps a plain quoted text")
items = [(1, "Bonjour.\nÇa va ?"), (2, "« Oui » ⟦0D⟧"), (3, "Fin")]
block = format_group(items, "French")
parsed, notes = parse_group(block)
check(parsed == dict(items) and not notes, "group format/parse round-trip")
ws = [(1, "\n Vector Com., Inc.\n Vector"), (2, "Air "), (3, "x \n y")]
parsed, notes = parse_group(format_group(ws))
check(parsed == dict(ws), f"group round-trip keeps indents and trailing spaces: {parsed}")
messy = ("Here you go:\n\n[1] Bonjour.⏎Ça va ?\n[2] « Oui »\n suite du texte\n"
"[3] Fin\n[2] « Oui » ⟦0D⟧\n")
parsed, notes = parse_group(messy)
check(parsed == {1: "Bonjour.\nÇa va ?", 2: "« Oui » ⟦0D⟧", 3: "Fin"} and len(notes) == 1,
f"group parse tolerates preamble, re-wraps, full-width marks, duplicates: {parsed}")
with tempfile.TemporaryDirectory() as td:
fp = os.path.join(td, "sub", "p.json")
save(fp, p)
check(load(fp) == normalise(p), "project save/load round-trip (atomic write)")
check(not [f for f in os.listdir(os.path.dirname(fp)) if f.endswith(".tmp")],
"no temp file left behind")
m, nm = merge(new_project(), p)
check(nm == 1 and m["translations"] == p["translations"], "merge")
if iso:
import time
t = time.time()
rid = retail_id(iso)
check(re.fullmatch(r"[0-9a-f]{40}", rid) is not None,
f"retail_id {rid} ({time.time() - t:.2f} s)")
print("selftest", "passed" if ok else "FAILED")
return 0 if ok else 1
def main(argv=None) -> int:
import argparse
ap = argparse.ArgumentParser(description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
sub = ap.add_subparsers(dest="cmd", required=True)
s = sub.add_parser("selftest")
s.add_argument("--iso")
r = sub.add_parser("retail-id")
r.add_argument("--iso", required=True)
a = ap.parse_args(argv)
if a.cmd == "selftest":
return selftest(a.iso)
print(retail_id(a.iso))
return 0
if __name__ == "__main__":
sys.exit(main())