From 782d04b8294445878ce0d78464c0f3e0c6232d5e Mon Sep 17 00:00:00 2001 From: Dasemu Date: Tue, 20 Oct 2026 17:52:09 +0200 Subject: [PATCH] fix(translate): place every voice clip, per-occurrence speakers, config hash - Place a group's clips on the translated say boxes by speaker, falling back to position, so ensemble lines keep their clip; an unplaced clip is an error. - A speaker label may map to a list of cast ids, one per occurrence. - Store a hash of the mapping keys of [translations.] and refuse a mapping built with another configuration. Co-Authored-By: Claude Opus 5.5 --- docs/translations.md | 12 +++-- src/vnpipe/renpy_tl.py | 59 ++++++++++++++++------ src/vnpipe/schemas/translation.schema.json | 3 +- src/vnpipe/translate.py | 28 ++++++++-- src/vnpipe/translate_align.py | 11 +++- tests/test_translate.py | 32 ++++++++++++ 6 files changed, 121 insertions(+), 24 deletions(-) diff --git a/docs/translations.md b/docs/translations.md index e11890d..7d134a4 100644 --- a/docs/translations.md +++ b/docs/translations.md @@ -42,6 +42,9 @@ their own text, `grouped` ones show nothing; `suspects` are groups whose size ra the scene's. `translate status --scene ID` prints the alignment side by side. Fix a wrong pairing with an override that quotes the translation verbatim (see below); the build fails if the quote does not start exactly one unit. A scene is `complete` when its first unit has text. +The JSON stores hashes of `data/annotated.json` and of the mapping keys of +`[translations.]` (sections, speakers, overrides, ...); `vnpipe renpy` refuses a +mapping built from other ones (names and strings need no rebuild). ## Ren'Py output @@ -49,8 +52,10 @@ Every say statement carries an explicit `id` (its first line id), and each trans `translate :` for all of them: the first box of a game unit with text shows the translated units (split into boxes like the original: stanzas, at most 4 lines in ADV and 8 in NVL, long prose paragraphs cut at sentence ends), every other box is `pass`. The voice clips -are shared: a clip that starts in the group starts on the first translated box of the same -speaker and `voice sustain` carries it over that speaker's next boxes and directions. +are shared: each clip of the group, in order, starts on the next translated say box of the same +speaker (or, if none is left, on the next say box), and `voice sustain` carries it over that +speaker's next boxes and directions. Every clip is placed; a group with more clips than +translated say boxes is an error. Names, title cards, the scene list, About and the art-style labels go to `translate strings:`; equal original strings that translate differently get `{#scene}` tags. The credits @@ -83,7 +88,8 @@ ensembles = ["chorus"] # default: [voice].ensembles [translations.en.speakers] # speaker label as printed -> cast id "MEPHISTOPHELES" = "mephisto" -[translations.en.scene_speakers.] # per-scene overrides of `speakers` +[translations.en.scene_speakers.] # per-scene overrides of `speakers`; a list +"THE FIRST" = ["artisans", "servant_girls"] # gives one cast id per occurrence, in order [translations.en.direction_labels] # labels printed like a speaker but read as a direction; "FAUST AND WAGNER" = "" # the text after is spoken by this cast id ("" = none) diff --git a/src/vnpipe/renpy_tl.py b/src/vnpipe/renpy_tl.py index 754ffff..ecff1f0 100644 --- a/src/vnpipe/renpy_tl.py +++ b/src/vnpipe/renpy_tl.py @@ -36,7 +36,7 @@ from vnpipe.renpy_gen import ( scene_menu_titles, title_cards, ) -from vnpipe.translate import load_translation, translations +from vnpipe.translate import config_digest, load_translation, translations from vnpipe.translate_align import game_units MAX_LINE_WORDS = 45 # a longer line (a prose paragraph) is split at sentence ends @@ -83,6 +83,11 @@ def load_all(work: Work, annotated: dict[str, Any]) -> list[Translation]: f"translation {code!r} was built from another annotated.json: " "run `vnpipe translate build` again" ) + if data["config_sha256"] != config_digest(cfg): + raise ValueError( + f"translation {code!r} was built with another [translations.{code}] mapping " + "configuration: run `vnpipe translate build` again" + ) ids = {ln["id"] for sc in annotated["scenes"] for ln in sc["lines"]} for sid, scene in data["scenes"].items(): unknown = [k for k in scene["units"] if k not in ids] @@ -157,17 +162,33 @@ def item_boxes(item: dict[str, Any], limit: int) -> list[list[str]]: return boxes +def assign_clips(clips: list[tuple[str, str]], says: list[str]) -> dict[int, str]: + """Place a group's voice clips (in order, with the Spanish box's speaker) on its translated + say boxes (their speakers, in order): each clip goes to the next box of the same speaker + when one is left (keeping room for the clips after it), else to the next box. Every clip + is placed; a group with more clips than say boxes is an error.""" + if len(clips) > len(says): + raise ValueError(f"{len(clips)} voice clips but only {len(says)} translated say boxes") + placed: dict[int, str] = {} + start = 0 + for k, (speaker, path) in enumerate(clips): + last = len(says) - (len(clips) - k) # leave a box for each later clip + at = next((i for i in range(start, last + 1) if says[i] == speaker), start) + placed[at] = path + start = at + 1 + return placed + + class VoiceState: """Which speaker's clip the translated boxes keep playing.""" def __init__(self) -> None: self.active: str | None = None - def statement(self, speaker: str, is_dir: bool, pending: list[tuple[str, str]]) -> str | None: - if not is_dir and pending and pending[0][0] == speaker: - path = pending.pop(0)[1] + def statement(self, speaker: str, is_dir: bool, clip: str | None) -> str | None: + if clip is not None: self.active = speaker - return f'voice "{path}"' + return f'voice "{clip}"' if self.active is not None and (is_dir or speaker == self.active): return "voice sustain" self.active = None @@ -200,22 +221,30 @@ def render_scene_blocks( continue if not head.sustain: voice.active = None - pending = [(r.speaker, r.voice) for r in group if r.voice] - body: list[str] = [] + clips = [(r.speaker, r.voice) for r in group if r.voice] limit = NVL_MAX_LINES if head.nvl else ADV_MAX_LINES + boxes: list[tuple[str, bool, list[str]]] = [] for item in units[head.line_id]: speaker = item["speaker"] if speaker != "narrator" and speaker not in cast: raise ValueError(f"translation {tl.code!r}: unknown speaker {speaker!r}") is_dir = item["kind"] == "dir" - for box in item_boxes(item, limit): - if head.nvl: - body.append("nvl clear") - statement = voice.statement(speaker, is_dir, pending) - if statement: - body.append(statement) - text = "\\n".join(escape_text(line) for line in box) - body.append(f'{char_var(speaker, nvl=head.nvl)} "{text}"') + boxes += [(speaker, is_dir, box) for box in item_boxes(item, limit)] + say_at = [i for i, (_, is_dir, _) in enumerate(boxes) if not is_dir] + try: + placed = assign_clips(clips, [boxes[i][0] for i in say_at]) + except ValueError as exc: + raise ValueError(f"translation {tl.code!r}, {head.line_id}: {exc}") from None + clip_at = {say_at[k]: path for k, path in placed.items()} + body: list[str] = [] + for i, (speaker, is_dir, box) in enumerate(boxes): + if head.nvl: + body.append("nvl clear") + statement = voice.statement(speaker, is_dir, clip_at.get(i)) + if statement: + body.append(statement) + text = "\\n".join(escape_text(line) for line in box) + body.append(f'{char_var(speaker, nvl=head.nvl)} "{text}"') out.append(f"translate {tl.language} {head.line_id}:") out += [f" {ln}" for ln in body] out.append("") diff --git a/src/vnpipe/schemas/translation.schema.json b/src/vnpipe/schemas/translation.schema.json index ac467d6..5409f15 100644 --- a/src/vnpipe/schemas/translation.schema.json +++ b/src/vnpipe/schemas/translation.schema.json @@ -2,7 +2,7 @@ "$schema": "https://json-schema.org/draft/2020-12/schema", "title": "Translation mapped onto the game text (data/translations/.json)", "type": "object", - "required": ["version", "code", "language", "source_sha256", "annotated_sha256", "scenes"], + "required": ["version", "code", "language", "source_sha256", "annotated_sha256", "config_sha256", "scenes"], "additionalProperties": false, "properties": { "version": {"const": 1}, @@ -10,6 +10,7 @@ "language": {"type": "string", "pattern": "^[a-z_]+$"}, "source_sha256": {"type": "string", "pattern": "^[0-9a-f]{64}$"}, "annotated_sha256": {"type": "string", "pattern": "^[0-9a-f]{64}$"}, + "config_sha256": {"type": "string", "pattern": "^[0-9a-f]{64}$"}, "scenes": { "type": "object", "additionalProperties": { diff --git a/src/vnpipe/translate.py b/src/vnpipe/translate.py index 002f221..716b8c4 100644 --- a/src/vnpipe/translate.py +++ b/src/vnpipe/translate.py @@ -51,6 +51,26 @@ def translation_cfg(work: Work, code: str) -> dict[str, Any]: return cfg +# The keys of [translations.] that change the mapping (the others, such as names and +# strings, are read by `vnpipe renpy` directly). +MAPPING_KEYS = ( + "text_file", + "sections", + "speakers", + "scene_speakers", + "direction_labels", + "ignore_lines", + "ensembles", + "overrides", +) + + +def config_digest(cfg: dict[str, Any]) -> str: + """Hash of the mapping configuration, stored in the JSON to detect a stale build.""" + picked = {k: cfg[k] for k in MAPPING_KEYS if k in cfg} + return hashlib.sha256(json.dumps(picked, sort_keys=True).encode("utf-8")).hexdigest() + + def output_path(work: Work, code: str) -> Path: return work.path(f"{OUT_DIR}/{code}.json") @@ -93,9 +113,10 @@ def build_scene( sid = scene["id"] speakers = {**cfg.get("speakers", {}), **cfg.get("scene_speakers", {}).get(sid, {})} cast = work.cast - for label, cid in {**speakers, **cfg.get("direction_labels", {})}.items(): - if cid and cid not in cast: - raise SystemExit(f"translate: label {label!r} maps to unknown cast id {cid!r}") + for label, value in {**speakers, **cfg.get("direction_labels", {})}.items(): + for cid in value if isinstance(value, list) else [value]: + if cid and cid not in cast: + raise SystemExit(f"translate: label {label!r} maps to unknown cast id {cid!r}") scene_cfg = next((s for s in work.data.get("scenes", []) if s["id"] == sid), {}) source = parse_units( numbered, @@ -207,6 +228,7 @@ def build(work: Work, code: str) -> dict[str, Any]: "annotated_sha256": hashlib.sha256( work.path("data/annotated.json").read_bytes() ).hexdigest(), + "config_sha256": config_digest(cfg), "scenes": scenes, } validate(data, "translation") diff --git a/src/vnpipe/translate_align.py b/src/vnpipe/translate_align.py index a9e4822..99911be 100644 --- a/src/vnpipe/translate_align.py +++ b/src/vnpipe/translate_align.py @@ -131,7 +131,7 @@ class UnknownLabel(ValueError): def parse_units( numbered: list[tuple[int, str]], - speakers: dict[str, str], + speakers: dict[str, str | list[str]], default_speaker: str | None = None, prose: bool = False, ignore: frozenset[str] = frozenset(), @@ -177,6 +177,7 @@ def parse_units( while rows and (not rows[-1][1].strip() or ROMAN_RE.match(rows[-1][1].strip())): rows.pop() units: list[Unit] = [] + occurrences: dict[str, int] = {} cur: Unit | None = None # the open speech speaker: tuple[str, str] | None = None # (label, cast id) of the current speech pending_blank = False @@ -298,7 +299,13 @@ def parse_units( continue if name not in speakers: raise UnknownLabel(f"line {src}: unknown speaker label {name!r}") - speaker = (name, speakers[name]) + cid = speakers[name] + if isinstance(cid, list): # one cast id per occurrence of the label, in order + seen = occurrences[name] = occurrences.get(name, 0) + 1 + if seen > len(cid): + raise UnknownLabel(f"line {src}: label {name!r} occurs more than {len(cid)}x") + cid = cid[seen - 1] + speaker = (name, cid) cur = None started = True pending_blank = False diff --git a/tests/test_translate.py b/tests/test_translate.py index 452e3a2..4a00429 100644 --- a/tests/test_translate.py +++ b/tests/test_translate.py @@ -12,6 +12,7 @@ from vnpipe.config import load_work from vnpipe.renpy_gen import BoxRecord from vnpipe.translate_align import ( SETTING, + UnknownLabel, find_section_lines, group_units, parse_units, @@ -81,6 +82,14 @@ def test_parse_units_speeches_and_directions(): ] +def test_a_speaker_list_maps_each_occurrence_of_a_label(): + speakers = {**SPEAKERS, "MANAGER": ["director", "lord", "poet"]} + units = parse_units(section("talk"), speakers) + assert [u.speaker for u in units if u.label == "MANAGER"] == ["director", "lord", "poet"] + with pytest.raises(UnknownLabel, match="more than 2x"): + parse_units(section("talk"), {**SPEAKERS, "MANAGER": ["director", "lord"]}) + + def test_parse_units_without_labels_is_one_speech(): units = parse_units(section("lyric"), SPEAKERS, default_speaker="poet_voice") assert len(units) == 1 and units[0].speaker == "poet_voice" @@ -198,6 +207,29 @@ def test_voice_follows_the_first_box_of_the_same_speaker(): ] +def test_clips_follow_the_box_position_when_the_speaker_differs(): + # an ensemble line ("chorus") shown by a named source speaker, and a speaker mismatch + says = ["girl", "student", "girl"] + clips = [("chorus", "a.ogg"), ("student", "b.ogg"), ("burgher", "c.ogg")] + assert renpy_tl.assign_clips(clips, says) == {0: "a.ogg", 1: "b.ogg", 2: "c.ogg"} + # a later speaker match is skipped if it leaves no box for the clips after it + assert renpy_tl.assign_clips([("x", "a"), ("y", "b")], ["y", "x"]) == {0: "a", 1: "b"} + assert renpy_tl.assign_clips([("y", "a")], ["x", "y"]) == {1: "a"} + with pytest.raises(ValueError, match="2 voice clips"): + renpy_tl.assign_clips([("x", "a"), ("x", "b")], ["x"]) + + +def test_changed_mapping_config_is_an_error(tl_work, tmp_path): + translate.write_json(translate.output_path(tl_work, "en"), translate.build(tl_work, "en")) + annotated = json.loads(tl_work.path("data/annotated.json").read_text(encoding="utf-8")) + data = json.loads(json.dumps(tl_work.data)) + data["translations"]["en"]["names"]["lord"] = "God" # names need no rebuild + renpy_gen.generate(type(tl_work)(tl_work.root, data), annotated, tmp_path / "ok") + data["translations"]["en"]["speakers"]["POET"] = "director" + with pytest.raises(ValueError, match="mapping configuration"): + renpy_gen.generate(type(tl_work)(tl_work.root, data), annotated, tmp_path / "p") + + @pytest.fixture def tl_project(tl_work, tmp_path): translate.write_json(translate.output_path(tl_work, "en"), translate.build(tl_work, "en"))