mirror of
https://github.com/Dasemu/vnpipe.git
synced 2026-11-27 07:46:37 +00:00
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.<code>] and refuse a mapping built with another configuration. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
c3db641024
commit
782d04b829
6 files changed
+121
-24
No files matched your search
@@ -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
|
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
|
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 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.<code>]` (sections, speakers, overrides, ...); `vnpipe renpy` refuses a
|
||||||
|
mapping built from other ones (names and strings need no rebuild).
|
||||||
|
|
||||||
## Ren'Py output
|
## Ren'Py output
|
||||||
|
|
||||||
@@ -49,8 +52,10 @@ Every say statement carries an explicit `id` (its first line id), and each trans
|
|||||||
`translate <language> <id>:` for all of them: the first box of a game unit with text shows the
|
`translate <language> <id>:` 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
|
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
|
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
|
are shared: each clip of the group, in order, starts on the next translated say box of the same
|
||||||
speaker and `voice sustain` carries it over that speaker's next boxes and directions.
|
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 <language>
|
Names, title cards, the scene list, About and the art-style labels go to `translate <language>
|
||||||
strings:`; equal original strings that translate differently get `{#scene}` tags. The credits
|
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
|
[translations.en.speakers] # speaker label as printed -> cast id
|
||||||
"MEPHISTOPHELES" = "mephisto"
|
"MEPHISTOPHELES" = "mephisto"
|
||||||
|
|
||||||
[translations.en.scene_speakers.<scene id>] # per-scene overrides of `speakers`
|
[translations.en.scene_speakers.<scene id>] # 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;
|
[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)
|
"FAUST AND WAGNER" = "" # the text after is spoken by this cast id ("" = none)
|
||||||
|
|||||||
+44
-15
@@ -36,7 +36,7 @@ from vnpipe.renpy_gen import (
|
|||||||
scene_menu_titles,
|
scene_menu_titles,
|
||||||
title_cards,
|
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
|
from vnpipe.translate_align import game_units
|
||||||
|
|
||||||
MAX_LINE_WORDS = 45 # a longer line (a prose paragraph) is split at sentence ends
|
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: "
|
f"translation {code!r} was built from another annotated.json: "
|
||||||
"run `vnpipe translate build` again"
|
"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"]}
|
ids = {ln["id"] for sc in annotated["scenes"] for ln in sc["lines"]}
|
||||||
for sid, scene in data["scenes"].items():
|
for sid, scene in data["scenes"].items():
|
||||||
unknown = [k for k in scene["units"] if k not in ids]
|
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
|
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:
|
class VoiceState:
|
||||||
"""Which speaker's clip the translated boxes keep playing."""
|
"""Which speaker's clip the translated boxes keep playing."""
|
||||||
|
|
||||||
def __init__(self) -> None:
|
def __init__(self) -> None:
|
||||||
self.active: str | None = None
|
self.active: str | None = None
|
||||||
|
|
||||||
def statement(self, speaker: str, is_dir: bool, pending: list[tuple[str, str]]) -> str | None:
|
def statement(self, speaker: str, is_dir: bool, clip: str | None) -> str | None:
|
||||||
if not is_dir and pending and pending[0][0] == speaker:
|
if clip is not None:
|
||||||
path = pending.pop(0)[1]
|
|
||||||
self.active = speaker
|
self.active = speaker
|
||||||
return f'voice "{path}"'
|
return f'voice "{clip}"'
|
||||||
if self.active is not None and (is_dir or speaker == self.active):
|
if self.active is not None and (is_dir or speaker == self.active):
|
||||||
return "voice sustain"
|
return "voice sustain"
|
||||||
self.active = None
|
self.active = None
|
||||||
@@ -200,22 +221,30 @@ def render_scene_blocks(
|
|||||||
continue
|
continue
|
||||||
if not head.sustain:
|
if not head.sustain:
|
||||||
voice.active = None
|
voice.active = None
|
||||||
pending = [(r.speaker, r.voice) for r in group if r.voice]
|
clips = [(r.speaker, r.voice) for r in group if r.voice]
|
||||||
body: list[str] = []
|
|
||||||
limit = NVL_MAX_LINES if head.nvl else ADV_MAX_LINES
|
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]:
|
for item in units[head.line_id]:
|
||||||
speaker = item["speaker"]
|
speaker = item["speaker"]
|
||||||
if speaker != "narrator" and speaker not in cast:
|
if speaker != "narrator" and speaker not in cast:
|
||||||
raise ValueError(f"translation {tl.code!r}: unknown speaker {speaker!r}")
|
raise ValueError(f"translation {tl.code!r}: unknown speaker {speaker!r}")
|
||||||
is_dir = item["kind"] == "dir"
|
is_dir = item["kind"] == "dir"
|
||||||
for box in item_boxes(item, limit):
|
boxes += [(speaker, is_dir, box) for box in item_boxes(item, limit)]
|
||||||
if head.nvl:
|
say_at = [i for i, (_, is_dir, _) in enumerate(boxes) if not is_dir]
|
||||||
body.append("nvl clear")
|
try:
|
||||||
statement = voice.statement(speaker, is_dir, pending)
|
placed = assign_clips(clips, [boxes[i][0] for i in say_at])
|
||||||
if statement:
|
except ValueError as exc:
|
||||||
body.append(statement)
|
raise ValueError(f"translation {tl.code!r}, {head.line_id}: {exc}") from None
|
||||||
text = "\\n".join(escape_text(line) for line in box)
|
clip_at = {say_at[k]: path for k, path in placed.items()}
|
||||||
body.append(f'{char_var(speaker, nvl=head.nvl)} "{text}"')
|
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.append(f"translate {tl.language} {head.line_id}:")
|
||||||
out += [f" {ln}" for ln in body]
|
out += [f" {ln}" for ln in body]
|
||||||
out.append("")
|
out.append("")
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||||
"title": "Translation mapped onto the game text (data/translations/<code>.json)",
|
"title": "Translation mapped onto the game text (data/translations/<code>.json)",
|
||||||
"type": "object",
|
"type": "object",
|
||||||
"required": ["version", "code", "language", "source_sha256", "annotated_sha256", "scenes"],
|
"required": ["version", "code", "language", "source_sha256", "annotated_sha256", "config_sha256", "scenes"],
|
||||||
"additionalProperties": false,
|
"additionalProperties": false,
|
||||||
"properties": {
|
"properties": {
|
||||||
"version": {"const": 1},
|
"version": {"const": 1},
|
||||||
@@ -10,6 +10,7 @@
|
|||||||
"language": {"type": "string", "pattern": "^[a-z_]+$"},
|
"language": {"type": "string", "pattern": "^[a-z_]+$"},
|
||||||
"source_sha256": {"type": "string", "pattern": "^[0-9a-f]{64}$"},
|
"source_sha256": {"type": "string", "pattern": "^[0-9a-f]{64}$"},
|
||||||
"annotated_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": {
|
"scenes": {
|
||||||
"type": "object",
|
"type": "object",
|
||||||
"additionalProperties": {
|
"additionalProperties": {
|
||||||
|
|||||||
+25
-3
@@ -51,6 +51,26 @@ def translation_cfg(work: Work, code: str) -> dict[str, Any]:
|
|||||||
return cfg
|
return cfg
|
||||||
|
|
||||||
|
|
||||||
|
# The keys of [translations.<code>] 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:
|
def output_path(work: Work, code: str) -> Path:
|
||||||
return work.path(f"{OUT_DIR}/{code}.json")
|
return work.path(f"{OUT_DIR}/{code}.json")
|
||||||
|
|
||||||
@@ -93,9 +113,10 @@ def build_scene(
|
|||||||
sid = scene["id"]
|
sid = scene["id"]
|
||||||
speakers = {**cfg.get("speakers", {}), **cfg.get("scene_speakers", {}).get(sid, {})}
|
speakers = {**cfg.get("speakers", {}), **cfg.get("scene_speakers", {}).get(sid, {})}
|
||||||
cast = work.cast
|
cast = work.cast
|
||||||
for label, cid in {**speakers, **cfg.get("direction_labels", {})}.items():
|
for label, value in {**speakers, **cfg.get("direction_labels", {})}.items():
|
||||||
if cid and cid not in cast:
|
for cid in value if isinstance(value, list) else [value]:
|
||||||
raise SystemExit(f"translate: label {label!r} maps to unknown cast id {cid!r}")
|
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), {})
|
scene_cfg = next((s for s in work.data.get("scenes", []) if s["id"] == sid), {})
|
||||||
source = parse_units(
|
source = parse_units(
|
||||||
numbered,
|
numbered,
|
||||||
@@ -207,6 +228,7 @@ def build(work: Work, code: str) -> dict[str, Any]:
|
|||||||
"annotated_sha256": hashlib.sha256(
|
"annotated_sha256": hashlib.sha256(
|
||||||
work.path("data/annotated.json").read_bytes()
|
work.path("data/annotated.json").read_bytes()
|
||||||
).hexdigest(),
|
).hexdigest(),
|
||||||
|
"config_sha256": config_digest(cfg),
|
||||||
"scenes": scenes,
|
"scenes": scenes,
|
||||||
}
|
}
|
||||||
validate(data, "translation")
|
validate(data, "translation")
|
||||||
|
|||||||
@@ -131,7 +131,7 @@ class UnknownLabel(ValueError):
|
|||||||
|
|
||||||
def parse_units(
|
def parse_units(
|
||||||
numbered: list[tuple[int, str]],
|
numbered: list[tuple[int, str]],
|
||||||
speakers: dict[str, str],
|
speakers: dict[str, str | list[str]],
|
||||||
default_speaker: str | None = None,
|
default_speaker: str | None = None,
|
||||||
prose: bool = False,
|
prose: bool = False,
|
||||||
ignore: frozenset[str] = frozenset(),
|
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())):
|
while rows and (not rows[-1][1].strip() or ROMAN_RE.match(rows[-1][1].strip())):
|
||||||
rows.pop()
|
rows.pop()
|
||||||
units: list[Unit] = []
|
units: list[Unit] = []
|
||||||
|
occurrences: dict[str, int] = {}
|
||||||
cur: Unit | None = None # the open speech
|
cur: Unit | None = None # the open speech
|
||||||
speaker: tuple[str, str] | None = None # (label, cast id) of the current speech
|
speaker: tuple[str, str] | None = None # (label, cast id) of the current speech
|
||||||
pending_blank = False
|
pending_blank = False
|
||||||
@@ -298,7 +299,13 @@ def parse_units(
|
|||||||
continue
|
continue
|
||||||
if name not in speakers:
|
if name not in speakers:
|
||||||
raise UnknownLabel(f"line {src}: unknown speaker label {name!r}")
|
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
|
cur = None
|
||||||
started = True
|
started = True
|
||||||
pending_blank = False
|
pending_blank = False
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ from vnpipe.config import load_work
|
|||||||
from vnpipe.renpy_gen import BoxRecord
|
from vnpipe.renpy_gen import BoxRecord
|
||||||
from vnpipe.translate_align import (
|
from vnpipe.translate_align import (
|
||||||
SETTING,
|
SETTING,
|
||||||
|
UnknownLabel,
|
||||||
find_section_lines,
|
find_section_lines,
|
||||||
group_units,
|
group_units,
|
||||||
parse_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():
|
def test_parse_units_without_labels_is_one_speech():
|
||||||
units = parse_units(section("lyric"), SPEAKERS, default_speaker="poet_voice")
|
units = parse_units(section("lyric"), SPEAKERS, default_speaker="poet_voice")
|
||||||
assert len(units) == 1 and units[0].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
|
@pytest.fixture
|
||||||
def tl_project(tl_work, tmp_path):
|
def tl_project(tl_work, tmp_path):
|
||||||
translate.write_json(translate.output_path(tl_work, "en"), translate.build(tl_work, "en"))
|
translate.write_json(translate.output_path(tl_work, "en"), translate.build(tl_work, "en"))
|
||||||
|
|||||||
Reference in new issue
Block a user