Repository navigation
Expand file tree
/
Copy pathtxspeakers.py
More file actions
120 lines (101 loc) · 4.49 KB
/
Copy pathtxspeakers.py
File metadata and controls
120 lines (101 loc) · 4.49 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
"""Regenerate txspeakers.json: Japanese name box -> USA English name box.
The translation editor's "By speaker" view groups dialogue by the name in
its /[label(...)] tag. Cutscenes often pass the Japanese name (【シオン】)
instead of the English one, so the view needs to know which English label
the same speaker carries. This pairs every USA /[label(EN)] with the
Reloaded disc's /[label(JP)] at the same code position (same container,
same class layout, same method), counts the pairs, and keeps, for each
Japanese name, the English name used most often. Nothing is typed in.
python3 txspeakers.py --usa USA.iso --reloaded RELOADED.iso [--out txspeakers.json]
"""
from __future__ import annotations
import argparse
import json
import re
import unicodedata
from collections import Counter
from pathlib import Path
import evttext as et
import txsource as ts
from iso9660 import IsoImage
LAB = re.compile(rb"^/\[label\((.*?)\)?\]$", re.S)
ABOUT = ("Speaker names for the translation editor's 'By speaker' view. Each Japanese name box "
"(/[label(...)] on Xenosaga I Reloaded, SLPS_290.05) is paired with the USA disc's "
"/[label(...)] at the same code position in the same scene container; the English shown is "
"the USA label used most often for it. Generated by txspeakers.py from the two discs, not "
"written by hand. Keys are NFKC-normalised, U+2212 as '-'.")
def norm(name: str) -> str:
return unicodedata.normalize("NFKC", name).replace("−", "-")
def _containers(path: str) -> dict:
iso = IsoImage(path)
try:
return {(ch, p): data for ch, p, data, _ in et.iter_containers(iso)}
finally:
iso.close()
def label_pairs(usa: str, reloaded: str) -> Counter:
u, r = _containers(usa), _containers(reloaded)
pairs: Counter = Counter()
for key in sorted(u):
if key not in r:
continue
ud, rd = u[key], r[key]
try:
ue, re_ = et.fl00_entries(ud), et.fl00_entries(rd)
except et.EvtTextError:
continue
rname = {rd[no:no + nl]: k for k, (no, nl, _, _) in enumerate(re_)}
for (no, nl, do, ds) in ue:
rj = rname.get(ud[no:no + nl])
if rj is None:
continue
_, _, do2, ds2 = re_[rj]
ucls, rcls = ud[do:do + ds], rd[do2:do2 + ds2]
if ds <= 24 or ucls[:4] != et.CAFEBABE or rcls[:4] != et.CAFEBABE:
continue
try:
uent, um = ts._class_methods(ucls)
rent, rm = ts._class_methods(rcls)
except Exception:
continue
if [(a, b) for a, b, _ in um] != [(a, b) for a, b, _ in rm]:
continue
st: Counter = Counter()
for (_, _, ut), (_, _, rt) in zip(um, rm):
for upool, rpools, _partial in ts._method_pairs(ut, rt, uent, rent, st):
m = LAB.match(ts._utf_raw(uent, upool).rstrip(b"\0"))
if not m or len(rpools) != 1 or rpools[0] < 0:
continue
m2 = LAB.match(ts._utf_raw(rent, rpools[0]).rstrip(b"\0"))
if not m2:
continue
en = m.group(1).decode("euc_jp", "replace")
jp = m2.group(1).decode("euc_jp", "replace")
pairs[(en, jp)] += 1
return pairs
def build(usa: str, reloaded: str) -> dict:
best: dict = {}
for (en, jp), n in label_pairs(usa, reloaded).items():
if not en or not jp:
continue
k = norm(jp)
if k not in best or best[k][1] < n:
best[k] = (en, n)
return {"_about": ABOUT,
"ja_to_en": {k: v[0] for k, v in sorted(best.items(), key=lambda kv: -kv[1][1])}}
def load() -> dict:
"""The shipped table (empty if the file is missing)."""
try:
return json.loads((Path(__file__).with_name("txspeakers.json")).read_text("utf-8"))["ja_to_en"]
except (OSError, ValueError, KeyError):
return {}
def main() -> None:
ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
ap.add_argument("--usa", required=True)
ap.add_argument("--reloaded", required=True)
ap.add_argument("--out", default=str(Path(__file__).with_name("txspeakers.json")))
a = ap.parse_args()
data = build(a.usa, a.reloaded)
Path(a.out).write_text(json.dumps(data, ensure_ascii=False, indent=1), "utf-8")
print(f"{len(data['ja_to_en'])} Japanese names -> {a.out}")
if __name__ == "__main__":
main()