feat(renpy): generate translations and an in-game language choice

Write game/tl/<language>/ from data/translations (say ids, translate blocks
keeping voice and voice sustain, strings for names, cards, menus and
credits), and add a Language control in Preferences and the first-launch
picker. Spanish stays the default; a stale language falls back to it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
dasemuandClaude Opus 5.5 committed 2026-10-20 13:38:28 +02:00
1 parent 33c8b32b69
commit da80379149
10 files changed
+879 -56

No files matched your search

+2 -1
View File
@@ -15,7 +15,8 @@ Works (texts) live in their own repos, e.g. `../Faust-VN`.
- `uv sync` — install. `uv run pytest` — tests. `uv run ruff check . && uv run ruff format --check .` — lint.
- `uv run vnpipe --help` — CLI (`--work` defaults to the current directory). Stages: `fetch`,
`parse`, `annotate {run,status,prompt,merge}`, `assets {...}`, `voice {fetch,asr,build,cut}`
(`docs/voice.md`), `renpy [--with-test]` (default output `<work>/vn`).
(`docs/voice.md`), `translate {fetch,build,status}` (`docs/translations.md`),
`renpy [--with-test]` (default output `<work>/vn`).
- `scripts/asr.py` runs on a GPU host (faster-whisper), never as a vnpipe dependency.
- Ren'Py SDK: set `RENPY_SDK` to the unpacked SDK directory (tests that need it are skipped
otherwise; fallback `tools/renpy-sdk`). See `docs/running.md`.
+117 -39
View File
@@ -11,6 +11,7 @@ The GUI files in ``renpy_templates/`` were produced once with the Ren'Py SDK's
import argparse
import hashlib
import json
import re
import shutil
import tomllib
from dataclasses import dataclass, field
@@ -30,6 +31,7 @@ NO_MANIFEST_STYLE = {"default": {"label": "Default"}} # work without an asset m
ADV_MAX_LINES = 4
NVL_MAX_LINES = 8
SAY_ID_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
SPLIT_INDENT = 6 # parsed `indent` at or above this marks a split verse line
TITLE_PAUSE = 2.0
END_PAUSE = 3.0
@@ -164,16 +166,15 @@ def scan_audio(out: Path) -> Audio:
def copy_translations(work: Work, out: Path) -> list[Path]:
"""Install the UI translation for ``[ui].language`` and make it the only language.
"""Install the UI translation for ``[ui].language``.
vnpipe ships ``renpy_templates/tl/<language>/`` (Ren'Py's common strings plus every string
of the template screens); ``<work>/tl/**/*.rpy`` is copied on top, so a work file with the
same path replaces the shipped one. ``config.language`` (not only
``config.default_language``, which applies on first run) forces the language even when a
persistent preference from an older build says otherwise.
same path replaces the shipped one. Which language plays is decided in ``languages.rpy``
(the work's own language unless the player picked a translation).
"""
dest_root = out / "game" / "tl"
lang_file = out / "game" / "language.rpy"
(out / "game" / "language.rpy").unlink(missing_ok=True) # written by older versions
language = work.data.get("ui", {}).get("language")
sources: dict[Path, Path] = {}
roots = [TEMPLATE_DIR / "tl" / language] if language else []
@@ -192,15 +193,6 @@ def copy_translations(work: Work, out: Path) -> list[Path]:
dest.parent.mkdir(parents=True, exist_ok=True)
shutil.copyfile(src, dest)
written.append(dest)
if language:
write_text(
lang_file,
f"define config.default_language = {quote(language)}\n"
f"define config.language = {quote(language)}\n",
)
written.append(lang_file)
else:
lang_file.unlink(missing_ok=True)
return written
@@ -370,6 +362,18 @@ class Box:
is_direction: bool = False
@dataclass
class BoxRecord:
"""A say statement as written, for the translations (``vnpipe.renpy_tl``): its ``id``
(the first line id), speaker, mode and the voice statement it carries."""
line_id: str
speaker: str
nvl: bool
voice: str | None = None # clip path when the box starts the voice
sustain: bool = False # the box carries `voice sustain`
def _playlist(files: list[str]) -> str:
return "[" + ", ".join(_plain_quote(f) for f in files) + "]"
@@ -388,8 +392,10 @@ class SceneWriter:
audio: Audio,
music_state: dict[str, str | None],
voice_files: dict[int, str] | None = None,
records: list[BoxRecord] | None = None,
):
self.work = work
self.records = records if records is not None else []
self.scene = scene
self.audio = audio
self.voice_files = voice_files or {} # speech index -> clip path (relative to game/)
@@ -509,13 +515,19 @@ class SceneWriter:
if self.mode == "adv":
self.stage(box)
text = "\\n".join(escape_text(line["text"]) for line in box.lines)
variable = char_var(box.speaker, nvl=self.mode == "nvl")
self.voice_statement(box)
self.emit(f'{variable} "{text}"')
if self.mode == "nvl":
nvl = self.mode == "nvl"
variable = char_var(box.speaker, nvl=nvl)
record = BoxRecord(first["id"], box.speaker, nvl)
if nvl: # before the say, so it belongs to the say's translation block
self.emit("nvl clear")
self.voice_statement(box, record)
if not SAY_ID_RE.match(first["id"]):
raise ValueError(f"line id {first['id']!r} cannot be a Ren'Py say id")
# the explicit id names the translation block (`translate <language> <id>:`)
self.emit(f'{variable} "{text}" id {first["id"]}')
self.records.append(record)
def voice_statement(self, box: Box) -> None:
def voice_statement(self, box: Box, record: BoxRecord) -> None:
"""``voice`` before the first box of a voiced speech, ``voice sustain`` before the
following ones (a stage direction inside the speech keeps the clip going, but never
starts it)."""
@@ -525,9 +537,11 @@ class SceneWriter:
return
if self.voice_started == speech:
self.emit("voice sustain")
record.sustain = True
elif not box.is_direction:
self.emit(f"voice {_plain_quote(path)}")
self.voice_started = speech
record.voice = path
def music(self, spec: str | None) -> None:
"""Play/stop for a mood, ``track:<path>`` or ``none``; never restarts what already plays."""
@@ -690,7 +704,9 @@ def render_script(
annotated: dict[str, Any],
audio: Audio | None = None,
voice: dict[str, dict[int, str]] | None = None,
records: dict[str, list[BoxRecord]] | None = None,
) -> str:
"""The game script; ``records`` (if given) receives every scene's say boxes."""
validate_staging(work, annotated)
annotated = apply_overrides(work, annotated)
out = [
@@ -706,9 +722,9 @@ def render_script(
audio = audio or Audio()
music_state: dict[str, str | None] = {"playing": UNKNOWN_MUSIC}
for scene in annotated["scenes"]:
out.extend(
SceneWriter(work, scene, audio, music_state, (voice or {}).get(scene["id"])).render()
)
boxes = [] if records is None else records.setdefault(scene["id"], [])
writer = SceneWriter(work, scene, audio, music_state, (voice or {}).get(scene["id"]), boxes)
out.extend(writer.render())
seen |= {line["id"] for line in scene["lines"]}
missing = known - seen
if missing:
@@ -988,26 +1004,41 @@ def render_characters(work: Work) -> str:
return "\n".join(out)
def title_cards(work: Work, annotated: dict[str, Any]) -> dict[str, tuple[str, str | None]]:
"""Image name -> (heading, optional subtitle line: place/time, from ``[[scenes]].subtitle``)."""
def title_cards(
work: Work, annotated: dict[str, Any], tags: dict[str, str] | None = None
) -> dict[str, tuple[str, str | None]]:
"""Image name -> (heading, optional subtitle line: place/time, from ``[[scenes]].subtitle``).
``tags`` (scene ids -> ``{#id}`` tag) tell apart equal texts that translate differently."""
tags = tags or {}
subtitles = {sc["id"]: sc.get("subtitle") for sc in work.data.get("scenes", [])}
cards: dict[str, tuple[str, str | None]] = {
f"card_{sc['id']}": (sc["heading"], subtitles.get(sc["id"])) for sc in annotated["scenes"]
}
cards: dict[str, tuple[str, str | None]] = {}
for sc in annotated["scenes"]:
tag = f"{{#{tags[sc['id']]}}}" if sc["id"] in tags else ""
subtitle = subtitles.get(sc["id"])
cards[f"card_{sc['id']}"] = (sc["heading"] + tag, subtitle and subtitle + tag)
cards["card_end"] = (work.data["work"].get("end_text", DEFAULT_END_TEXT), None)
return cards
def _tagged(text: str) -> str:
"""Escape markup, keeping a trailing ``{#...}`` disambiguation tag."""
match = re.search(r"\{#[^{}]*\}$", text)
if not match:
return escape_text(text)
return escape_text(text[: match.start()]) + match.group(0)
def render_card(heading: str, subtitle: str | None) -> str:
"""A spaced-out heading; with a subtitle, a thin gold rule and a smaller italic line below."""
props = "size=76, kerning=3, text_align=0.5, xmaximum=1600"
if not subtitle:
return f'Text("{escape_text(heading)}", {props})'
return f'Text("{_tagged(heading)}", {props})'
sub_props = 'size=34, italic=True, color="#c9a25b", text_align=0.5, xmaximum=1600'
return (
f'VBox(Text("{escape_text(heading)}", {props}, xalign=0.5), '
f'VBox(Text("{_tagged(heading)}", {props}, xalign=0.5), '
'Solid("#c9a25b", xsize=200, ysize=2, xalign=0.5), '
f'Text("{escape_text(subtitle)}", {sub_props}, xalign=0.5), spacing=26)'
f'Text("{_tagged(subtitle)}", {sub_props}, xalign=0.5), spacing=26)'
)
@@ -1034,7 +1065,8 @@ def render_images(entries: list[ImageEntry], cards: dict[str, tuple[str, str | N
return "\n".join(out)
def _about(work: Work) -> str:
def about_parts(work: Work) -> list[str]:
"""Paragraphs of the About screen text."""
info = work.data["work"]
text_l, trans_l, tail = ABOUT_LABELS.get(info.get("language", "es"), ABOUT_LABELS["en"])
parts = [info.get("subtitle", "")]
@@ -1043,7 +1075,11 @@ def _about(work: Work) -> str:
if info.get("translator"):
parts.append(f"{trans_l}: {info['translator']}")
parts.append(tail)
return "\\n\\n".join(escape_text(p) for p in parts if p)
return [p for p in parts if p]
def _about(work: Work) -> str:
return "\\n\\n".join(escape_text(p) for p in about_parts(work))
def ui_labels(work: Work) -> dict[str, str]:
@@ -1108,8 +1144,11 @@ def credits_sections(work: Work, manifest: dict[str, Any] | None) -> list[tuple[
return [(title, [_markup(e) for e in entries]) for title, entries in sections]
def scene_menu_titles(work: Work, annotated: dict[str, Any]) -> list[tuple[str, str]]:
def scene_menu_titles(
work: Work, annotated: dict[str, Any], tags: dict[str, str] | None = None
) -> list[tuple[str, str]]:
"""(label, title) per scene; a repeated heading gets its subtitle, else its number."""
tags = tags or {}
subtitles = {sc["id"]: sc.get("subtitle") for sc in work.data.get("scenes", [])}
headings = [sc["heading"] for sc in annotated["scenes"]]
seen: dict[str, int] = {}
@@ -1119,11 +1158,21 @@ def scene_menu_titles(work: Work, annotated: dict[str, Any]) -> list[tuple[str,
if headings.count(title) > 1:
seen[title] = seen.get(title, 0) + 1
title += f" ({subtitles.get(sc['id']) or seen[title]})"
result.append((f"scene_{sc['id']}", _markup(title)))
tag = f"{{#{tags[sc['id']]} menu}}" if sc["id"] in tags else ""
result.append((f"scene_{sc['id']}", _markup(title) + tag))
return result
def render_menu_data(work: Work, annotated: dict[str, Any], manifest: dict[str, Any] | None) -> str:
def render_menu_data(
work: Work,
annotated: dict[str, Any],
manifest: dict[str, Any] | None,
tags: dict[str, str] | None = None,
credits_tl: dict[str, list[tuple[str, list[str]]]] | None = None,
) -> str:
"""Menu data; ``credits_tl`` holds the credits of each translation (Ren'Py language ->
sections), shown instead of ``vn_credits`` in that language."""
def py(value: Any) -> str: # JSON strings are valid Python literals
return json.dumps(value, ensure_ascii=False)
@@ -1133,8 +1182,9 @@ def render_menu_data(work: Work, annotated: dict[str, Any], manifest: dict[str,
"## Generated by `vnpipe renpy`. Do not edit: regenerate instead.",
"",
f"define vn_subtitle = {py(subtitle)}",
f"define vn_scenes = {py(scene_menu_titles(work, annotated))}",
f"define vn_scenes = {py(scene_menu_titles(work, annotated, tags))}",
f"define vn_credits = {py(credits_sections(work, manifest))}",
f"define vn_credits_tl = {py(credits_tl or {})}",
"",
]
)
@@ -1176,6 +1226,10 @@ def generate(
)
if first_bg:
menu_bg = bg_image_name(first_bg)
from vnpipe import renpy_tl # imports this module
tls = renpy_tl.load_all(work, annotated)
tags = renpy_tl.collision_tags(work, annotated, tls) if tls else {}
styles, default_style = art_styles(manifest)
picker_title, picker_hint = ART_STYLE_LABELS.get(
info.get("language", "es"), ART_STYLE_LABELS["en"]
@@ -1195,6 +1249,7 @@ def generate(
"UI_SCENES": ui["scenes"],
"UI_CREDITS": ui["credits"],
"LOCKED": LOCKED_SCENE,
"LANGUAGES": repr(renpy_tl.languages(work, tls)),
}
written: list[Path] = []
for src in sorted((TEMPLATE_DIR / "game").rglob("*")):
@@ -1222,17 +1277,40 @@ def generate(
if with_test:
write_text(test_file, render_e2e(styles, ui))
written.append(test_file)
records: dict[str, list[BoxRecord]] = {}
credits_tl = {
tl.language: renpy_tl.translated_credits(work, annotated, manifest, tl) for tl in tls
}
for name, text in (
("characters.rpy", render_characters(work)),
("images.rpy", render_images(entries, title_cards(work, annotated))),
("menu_data.rpy", render_menu_data(work, annotated, manifest)),
("images.rpy", render_images(entries, title_cards(work, annotated, tags))),
("menu_data.rpy", render_menu_data(work, annotated, manifest, tags, credits_tl)),
(
"script.rpy",
render_script(work, annotated, scan_audio(out), voice_files(work, annotated)),
render_script(work, annotated, scan_audio(out), voice_files(work, annotated), records),
),
):
write_text(game / name, text)
written.append(game / name)
for tl in tls:
tl_dir = game / "tl" / tl.language
shutil.rmtree(tl_dir, ignore_errors=True)
for name, text in (
(
"script.rpy",
renpy_tl.render_tl_script(
tl, apply_overrides(work, annotated), records, lyric_voice(work), work.cast
),
),
(
"strings.rpy",
renpy_tl.render_tl_strings(
tl, renpy_tl.string_pairs(work, annotated, manifest, tl, tags)
),
),
):
write_text(tl_dir / name, text)
written.append(tl_dir / name)
for e in entries:
for _, rel, source in e.variants:
@@ -0,0 +1,26 @@
## Languages: the play's own text, plus every translation built by `vnpipe translate`
## (game/tl/<language>/). The player picks one in Preferences, or at first launch; the
## choice is kept in `persistent.vn_language`. `config.language` is set from that choice
## only, so a language preference left by an older build never overrides it, and loading a
## save keeps the chosen language. Static except for the substituted list.
default persistent.vn_language = None
## (Ren'Py language, label in that language) pairs; the first is the default.
define vn_languages = @@LANGUAGES@@
init 1 python:
def vn_known_language(language):
return any(lang == language for lang, _label in vn_languages)
def vn_set_language(language):
"""Remember the player's choice; Language(language) then switches to it."""
persistent.vn_language = language
config.language = language
if vn_known_language(persistent.vn_language):
config.language = persistent.vn_language
else:
config.language = vn_languages[0][0]
config.default_language = vn_languages[0][0]
+4 -2
View File
@@ -1,5 +1,6 @@
## Scene select and credits screens, reached from the main menu. The data they show
## (`vn_scenes`, `vn_credits`) is generated in menu_data.rpy; static otherwise.
## (`vn_scenes`, `vn_credits`, `vn_credits_tl`) is generated in menu_data.rpy; static
## otherwise.
## Labels of the scenes the player has reached; updated when a scene starts.
default persistent.vn_seen_scenes = set()
@@ -77,7 +78,8 @@ screen vn_credits():
vbox:
spacing 6
for section_title, entries in vn_credits:
## a translation has its own credits (its text comes from another translator)
for section_title, entries in vn_credits_tl.get(_preferences.language, vn_credits):
null height 20
label section_title
for entry in entries:
@@ -1060,6 +1060,17 @@ screen preferences():
for style_id, style_label in vn_art_styles:
textbutton style_label action SetField(persistent, "art_style", style_id)
if len(vn_languages) > 1:
frame:
style "pref_panel"
vbox:
style_prefix "radio"
label _("Language")
## Each language under its own name, so it can be found in any.
for lang, lang_label in vn_languages:
textbutton lang_label action [Function(vn_set_language, lang), Language(lang)]
## Additional panels of type "radio_pref" or "check_pref" can be
## added here, to add additional creator-defined preferences.
+25 -2
View File
@@ -33,6 +33,17 @@ screen vn_art_style_picker():
null height 40
if len(vn_languages) > 1:
hbox:
xalign 0.5
spacing 40
for lang, lang_label in vn_languages:
textbutton lang_label:
style_prefix "vn_language"
action [Function(vn_set_language, lang), Language(lang)]
null height 20
for style_id, style_label in vn_art_styles:
textbutton style_label:
style_prefix "vn_picker"
@@ -52,9 +63,21 @@ style vn_picker_button_text:
xalign 0.5
text_align 0.5
## Shown once, before the first scene, when there is a choice to make.
style vn_language_button is gui_button
style vn_language_button_text is gui_button_text
style vn_language_button:
padding (16, 6)
style vn_language_button_text:
size 32
selected_color gui.accent_color
selected_underline True
## Shown once, before the first scene, when there is a choice to make (an art style, and
## the language when the game has translations).
label vn_pick_art_style:
if len(vn_art_styles) > 1 and not persistent.art_style_chosen:
if (len(vn_art_styles) > 1 or len(vn_languages) > 1) and not persistent.art_style_chosen:
scene black
$ quick_menu = False
call screen vn_art_style_picker
@@ -102,6 +102,9 @@ translate spanish strings:
old "Transitions"
new "Transiciones"
old "Language"
new "Idioma"
old "Text Speed"
new "Velocidad del texto"
+391
View File
@@ -0,0 +1,391 @@
"""Ren'Py side of the translations: ``game/tl/<language>/`` from ``data/translations/<code>.json``.
Every say statement of the generated script carries an explicit ``id`` (its first line id), so
each translation writes ``translate <language> <id>:`` for every one of them:
- the first box of a game unit that the mapping gave text shows that text, split into boxes
like the original (stanzas, at most 4 lines in ADV or 8 in NVL, long prose paragraphs at
sentence ends);
- every other box (the rest of the unit, or a unit grouped with an earlier one) is ``pass``.
The voice clips are shared by every language: a clip that starts on a box of the group starts
on the first translated box of the same speaker, ``voice sustain`` keeps it going over the
following boxes of that speaker and over stage directions.
Menu, card and credit strings go to ``translate <language> strings:``; the credits, whose
entries differ per language, are a per-language list in ``menu_data.rpy``.
"""
import hashlib
import re
from dataclasses import dataclass
from typing import Any
from vnpipe.config import Work
from vnpipe.renpy_gen import (
ADV_MAX_LINES,
ART_STYLE_LABELS,
NVL_MAX_LINES,
UI_LABELS,
BoxRecord,
_markup,
about_parts,
char_var,
credits_sections,
escape_text,
scene_menu_titles,
title_cards,
)
from vnpipe.translate import 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
SENTENCE_END_RE = re.compile(r"[.!?…][’”)]*\s+|[.!?]—") # where a long line may be cut
# Native names of the languages a work or translation is written in.
LANGUAGE_NAMES = {
"de": "Deutsch",
"en": "English",
"es": "Español",
"fr": "Français",
"it": "Italiano",
"pt": "Português",
}
@dataclass
class Translation:
"""One configured translation and its built mapping."""
code: str
language: str # Ren'Py language name (``english``)
label: str # shown in the language picker, in that language
cfg: dict[str, Any]
data: dict[str, Any]
def load_all(work: Work, annotated: dict[str, Any]) -> list[Translation]:
"""The work's translations; an unbuilt or stale mapping is an error (the generated game
would silently show the wrong lines)."""
result = []
annotated_file = work.path("data/annotated.json")
digest = (
hashlib.sha256(annotated_file.read_bytes()).hexdigest()
if annotated_file.is_file()
else None
)
for code, cfg in translations(work).items():
data = load_translation(work, code)
if data is None:
raise ValueError(f"translation {code!r}: run `vnpipe translate build` first")
if digest is not None and data["annotated_sha256"] != digest:
raise ValueError(
f"translation {code!r} was built from another annotated.json: "
"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]
if unknown:
raise ValueError(f"translation {code!r}, {sid}: unknown line ids {unknown[:3]}")
result.append(
Translation(
code,
cfg["language"],
cfg.get("label") or LANGUAGE_NAMES.get(code, code),
cfg,
data,
)
)
return result
def languages(work: Work, tls: list[Translation]) -> list[tuple[str | None, str]]:
"""(Ren'Py language, label) pairs; the work's own language first (the default)."""
ui = work.data.get("ui", {})
lang = work.data["work"].get("language", "es")
own = (ui.get("language"), ui.get("language_label") or LANGUAGE_NAMES.get(lang, lang))
return [own, *((t.language, t.label) for t in tls)]
# --- say blocks ------------------------------------------------------------------------------
def _split_long(line: str) -> list[str]:
"""A line over ``MAX_LINE_WORDS`` words as runs of whole sentences (the text unchanged)."""
if len(line.split()) <= MAX_LINE_WORDS:
return [line]
cuts = [0, *(m.end() for m in SENTENCE_END_RE.finditer(line)), len(line)]
pieces = [line[a:b] for a, b in zip(cuts, cuts[1:], strict=False) if b > a]
chunks: list[str] = []
for piece in pieces: # slices of the line, so a chunk is always a verbatim substring
if chunks and len((chunks[-1] + piece).split()) <= MAX_LINE_WORDS:
chunks[-1] += piece
else:
chunks.append(piece)
return [c.strip() for c in chunks if c.strip()]
def item_boxes(item: dict[str, Any], limit: int) -> list[list[str]]:
"""The boxes (lists of lines) of one translated item."""
boxes: list[list[str]] = []
if item["kind"] == "dir":
lines = [ln for st in item["stanzas"] for ln in st]
for line in lines:
parts = _split_long(line)
if len(parts) > 1 or not boxes or len(boxes[-1]) >= limit:
boxes.extend([p] for p in parts)
else:
boxes[-1].append(line)
return boxes
for stanza in item["stanzas"]:
box: list[str] = []
for line in stanza:
parts = _split_long(line)
if len(parts) > 1:
if box:
boxes.append(box)
box = []
boxes.extend([p] for p in parts)
continue
if len(box) >= limit:
boxes.append(box)
box = []
box.append(line)
if box:
boxes.append(box)
return boxes
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]
self.active = speaker
return f'voice "{path}"'
if self.active is not None and (is_dir or speaker == self.active):
return "voice sustain"
self.active = None
return None
def render_scene_blocks(
tl: Translation,
scene: dict[str, Any],
records: list[BoxRecord],
lyric_voice: str,
cast: dict[str, Any],
) -> list[str]:
units = tl.data["scenes"][scene["id"]]["units"]
heads = {u.first_line for u in game_units(scene, lyric_voice)}
out: list[str] = []
voice = VoiceState()
# groups: a box with text, then the boxes that show nothing until the next one
groups: list[list[BoxRecord]] = []
for rec in records:
if rec.line_id in heads and rec.line_id in units or not groups:
groups.append([rec])
else:
groups[-1].append(rec)
for group in groups:
head = group[0]
if not (head.line_id in heads and head.line_id in units): # nothing before any text
for rec in group:
out += [f"translate {tl.language} {rec.line_id}:", " pass", ""]
continue
if not head.sustain:
voice.active = None
pending = [(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
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}"')
out.append(f"translate {tl.language} {head.line_id}:")
out += [f" {ln}" for ln in body]
out.append("")
for rec in group[1:]:
out += [f"translate {tl.language} {rec.line_id}:", " pass", ""]
return out
def render_tl_script(
tl: Translation,
annotated: dict[str, Any],
records: dict[str, list[BoxRecord]],
lyric_voice: str,
cast: dict[str, Any],
) -> str:
out = [
"## Generated by `vnpipe renpy` from data/translations/"
f"{tl.code}.json. Do not edit: regenerate instead.",
"",
]
for scene in annotated["scenes"]:
if scene["id"] not in tl.data["scenes"]:
raise ValueError(f"translation {tl.code!r} has no scene {scene['id']!r}")
out += render_scene_blocks(tl, scene, records.get(scene["id"], []), lyric_voice, cast)
return "\n".join(out)
# --- strings ---------------------------------------------------------------------------------
def string_literal(text: str) -> str:
"""A Ren'Py string literal whose value is ``text`` exactly (already markup-escaped)."""
return '"' + text.replace("\\", "\\\\").replace('"', '\\"').replace("\n", "\\n") + '"'
def render_tl_strings(tl: Translation, pairs: list[tuple[str, str]]) -> str:
"""``translate <language> strings:`` for each (original, translation) pair; an original
may appear once only (a clash is an error: tag the original with ``{#...}``)."""
seen: dict[str, str] = {}
out = [
"## Generated by `vnpipe renpy`. Do not edit: regenerate instead.",
"",
f"translate {tl.language} strings:",
"",
]
for old, new in pairs:
if not old or old == new:
continue
if old in seen:
if seen[old] != new:
raise ValueError(
f"translation {tl.code!r}: {old!r} is both {seen[old]!r} and {new!r}"
)
continue
seen[old] = new
out += [f" old {string_literal(old)}", f" new {string_literal(new)}", ""]
return "\n".join(out)
def _runtime(text: str) -> str:
"""The value Ren'Py holds for a generated string (markup escaped, a trailing ``{#...}``
tag kept)."""
match = re.search(r"\{#[^{}]*\}$", text)
if not match:
return _markup(text)
return _markup(text[: match.start()]) + match.group(0)
def translated_view(
work: Work, annotated: dict[str, Any], tl: Translation
) -> tuple[Work, dict[str, Any]]:
"""The work and script as the translation names them: title, subtitle, translator, end
text, source, voice credits, scene headings and subtitles."""
cfg = tl.cfg
info = {**work.data["work"], "language": tl.code}
for key in ("title", "subtitle", "translator", "end_text"):
if key in cfg:
info[key] = cfg[key]
sections = {s["scene"]: s for s in cfg.get("sections", [])}
scenes = [
{**sc, "subtitle": sections.get(sc["id"], {}).get("subtitle")}
for sc in work.data.get("scenes", [])
]
data = {**work.data, "work": info, "scenes": scenes}
if cfg.get("gutenberg_id"):
data["source"] = {**work.data.get("source", {}), "gutenberg_id": cfg["gutenberg_id"]}
if "voice" in work.data:
data["voice"] = {**work.data["voice"], "credits": cfg.get("voice_credits", [])}
ann = {
**annotated,
"scenes": [
{**sc, "heading": tl.data["scenes"][sc["id"]]["title"]} for sc in annotated["scenes"]
],
}
return Work(work.root, data), ann
def collision_tags(work: Work, annotated: dict[str, Any], tls: list[Translation]) -> dict[str, str]:
"""Scene id -> tag id for scenes whose heading, subtitle or menu title is the same text as
another one but translated differently (``{#<id>}`` on cards, ``{#<id> menu}`` in the
scene list)."""
es_cards = title_cards(work, annotated)
es_menu = dict(scene_menu_titles(work, annotated))
targets: dict[str, dict[str, set[str]]] = {} # original -> translation -> scene ids
for tl in tls:
tw, ta = translated_view(work, annotated, tl)
en_cards = title_cards(tw, ta)
en_menu = dict(scene_menu_titles(tw, ta))
for sc in annotated["scenes"]:
sid = sc["id"]
name = f"card_{sid}"
pairs = list(zip(es_cards[name], en_cards[name], strict=True))
pairs.append((es_menu[f"scene_{sid}"], en_menu[f"scene_{sid}"]))
for old, new in pairs:
if old:
targets.setdefault(old, {}).setdefault(new or "", set()).add(sid)
tags: dict[str, str] = {}
for by_new in targets.values():
if len(by_new) > 1:
for sids in by_new.values():
tags.update({sid: sid for sid in sids})
return tags
def string_pairs(
work: Work,
annotated: dict[str, Any],
manifest: dict[str, Any] | None,
tl: Translation,
tags: dict[str, str],
) -> list[tuple[str, str]]:
"""(original, translation) of every generated string the game shows outside dialogue."""
tw, ta = translated_view(work, annotated, tl)
lang = work.data["work"].get("language", "es")
pairs: list[tuple[str, str]] = []
names = tl.cfg.get("names", {})
missing = [cid for cid, c in work.cast.items() if c.get("name") and cid not in names]
if missing:
raise ValueError(f"[translations.{tl.code}.names] lacks {missing}")
for cid, name in names.items():
if cid not in work.cast:
raise ValueError(f"[translations.{tl.code}.names]: unknown cast id {cid!r}")
pairs.append((_markup(work.cast[cid].get("name") or ""), _markup(name)))
es_cards, en_cards = title_cards(work, annotated, tags), title_cards(tw, ta)
for name, card in es_cards.items():
for old, new in zip(card, en_cards[name], strict=True):
if old and new:
pairs.append((_runtime(old), _markup(new)))
en_menu = dict(scene_menu_titles(tw, ta))
pairs += [(old, en_menu[label]) for label, old in scene_menu_titles(work, annotated, tags)]
info, tinfo = work.data["work"], tw.data["work"]
pairs.append((_markup(info["title"]), _markup(tinfo["title"])))
pairs.append((_markup(info.get("subtitle", "")), _markup(tinfo.get("subtitle", ""))))
pairs.append(
(
"\n\n".join(_markup(p) for p in about_parts(work)),
"\n\n".join(_markup(p) for p in about_parts(tw)),
)
)
ui, tui = UI_LABELS.get(lang, UI_LABELS["en"]), UI_LABELS.get(tl.code, UI_LABELS["en"])
pairs += [(ui[k], tui[k]) for k in ("scenes", "credits")]
art = ART_STYLE_LABELS.get(lang, ART_STYLE_LABELS["en"])
tart = ART_STYLE_LABELS.get(tl.code, ART_STYLE_LABELS["en"])
pairs += list(zip(art, tart, strict=True))
pairs += [(_markup(k), _markup(v)) for k, v in tl.cfg.get("strings", {}).items()]
return pairs
def translated_credits(
work: Work, annotated: dict[str, Any], manifest: dict[str, Any] | None, tl: Translation
) -> list[tuple[str, list[str]]]:
tw, _ = translated_view(work, annotated, tl)
return credits_sections(tw, manifest)
+20 -12
View File
@@ -49,7 +49,8 @@ def scene_block(script: str, scene_id: str) -> list[str]:
def say_lines(block: list[str]) -> list[str]:
return [ln for ln in block if ln.startswith("c_")]
"""Say statements without their ``id`` clause."""
return [re.sub(r" id \w+$", "", ln) for ln in block if ln.startswith("c_")]
def test_escape_text():
@@ -116,10 +117,11 @@ def test_mode_switch_and_flash_shake(script):
block = scene_block(script, "talk")
i_nvl = block.index("# talk_0016")
# nvl cue at 0016: sprites hidden (nothing changes the bg), director spoke in nvl mode
assert block[i_nvl + 1].startswith("c_director_nvl ")
assert "nvl clear" in block[i_nvl:]
# each nvl page is cleared before its say (so the clear joins the say's translate block)
assert block[i_nvl + 1] == "nvl clear"
assert block[i_nvl + 2].startswith("c_director_nvl ")
# lyric voice lines in nvl are grouped into one page
pages = [ln for ln in block if ln.startswith("c_poet_voice_nvl")]
pages = [ln for ln in say_lines(block) if ln.startswith("c_poet_voice_nvl")]
assert pages == ['c_poet_voice_nvl "Callan los pájaros;\\nla noche cae."']
# cue 3: leave nvl, flash + shake, tint reset
i_cue = block.index("# talk_0019")
@@ -276,7 +278,7 @@ def test_stage_direction_keeps_on_stage(work, annotated):
direction = next(ln for ln in ann["scenes"][1]["lines"] if ln["id"] == "talk_0010")
direction["ann"]["on_stage"] = []
block = scene_block(renpy_gen.render_script(work, ann), "talk")
i = block.index('c_narrator "Se aleja."')
i = block.index('c_narrator "Se aleja." id talk_0010')
assert not any(ln.startswith("hide ") for ln in block[i - 3 : i])
@@ -435,7 +437,7 @@ def test_scan_and_copy_audio(work, tmp_path):
assert "audio/scenes/x.ogg" in audio.files
def test_copy_translations_and_forced_language(work, tmp_path):
def test_copy_translations(work, tmp_path):
root = tmp_path / "w"
(root / "tl/spanish").mkdir(parents=True)
work_common = "translate spanish strings:\n"
@@ -450,17 +452,23 @@ def test_copy_translations_and_forced_language(work, tmp_path):
assert (tl / "screens.rpy").read_bytes() == shipped.read_bytes()
assert (tl / "common.rpy").read_text(encoding="utf-8") == work_common
assert (tl / "extra.rpy").is_file()
assert tl / "screens.rpy" in copied
# the language is chosen in languages.rpy: a language.rpy left by an older build goes
lang = out / "game/language.rpy"
assert lang in copied
# config.language beats a persistent preference left by an older build
assert lang.read_text(encoding="utf-8") == (
'define config.default_language = "spanish"\ndefine config.language = "spanish"\n'
)
# Without [ui].language the stale file is removed.
lang.write_text("define config.language = 'spanish'\n", encoding="utf-8")
renpy_gen.copy_translations(type(work)(root=tmp_path / "none", data=work.data), out)
assert not lang.exists()
def test_languages_file_forces_the_work_language(project):
text = (project / "game/languages.rpy").read_text(encoding="utf-8")
# no translations: one language, the work's [ui].language (none in the fixture)
assert "define vn_languages = [(None, 'Español')]" in text
# config.language follows the player's choice only, never a stale preference
assert "config.language = persistent.vn_language" in text
assert "config.language = vn_languages[0][0]" in text
def _tl_strings(path: Path) -> list[str]:
return re.findall(r'^\s*old "((?:[^"\\]|\\.)*)"$', path.read_text(encoding="utf-8"), re.M)
+280
View File
@@ -0,0 +1,280 @@
import json
import os
import re
import shutil
import subprocess
from pathlib import Path
import pytest
from vnpipe import renpy_gen, renpy_tl, translate
from vnpipe.config import load_work
from vnpipe.renpy_gen import BoxRecord
from vnpipe.translate_align import (
SETTING,
find_section_lines,
group_units,
parse_units,
strip_gutenberg,
)
FIXTURES = Path(__file__).parent / "fixtures"
ROOT = Path(__file__).resolve().parent.parent
SDK = Path(os.environ.get("RENPY_SDK") or ROOT / "tools/renpy-sdk") / "renpy.sh"
SPEAKERS = {"MANAGER": "director", "POET": "poet", "THE LORD": "lord", "VOICE": "poet_voice"}
@pytest.fixture
def tl_work(tmp_path):
"""mini_work plus an English translation (fixture ebook) and its annotated script."""
root = tmp_path / "w"
shutil.copytree(FIXTURES / "mini_work", root)
with (root / "work.toml").open("a", encoding="utf-8") as fh:
fh.write((FIXTURES / "mini_tl.toml").read_text(encoding="utf-8"))
(root / "data/raw").mkdir(parents=True)
shutil.copyfile(FIXTURES / "annotated_mini.json", root / "data/annotated.json")
shutil.copyfile(FIXTURES / "mini_tl_en.txt", root / "data/raw/en.txt")
return load_work(root)
def section(name: str) -> list[tuple[int, str]]:
text = strip_gutenberg((FIXTURES / "mini_tl_en.txt").read_text(encoding="utf-8"))
lyric, talk = find_section_lines(text, ["LYRIC", "TALK"])
return {"lyric": lyric, "talk": talk}[name]
def test_strip_gutenberg_keeps_only_the_ebook_text():
text = strip_gutenberg((FIXTURES / "mini_tl_en.txt").read_text(encoding="utf-8"))
assert "Project Gutenberg" not in text and "Licence" not in text
assert text.lstrip().startswith("CONTENTS")
def test_find_section_lines_skips_the_contents():
text = strip_gutenberg((FIXTURES / "mini_tl_en.txt").read_text(encoding="utf-8"))
lyric, _ = find_section_lines(text, ["LYRIC", "TALK"])
assert lyric[1][1].startswith("Again ye come") # not the indented contents entry
def test_parse_units_speeches_and_directions():
units = parse_units(section("talk"), SPEAKERS)
kinds = [(u.kind, u.speaker, u.label) for u in units]
assert kinds == [
("dir", None, SETTING), # place line and cast list, kept apart
("say", "director", "MANAGER"),
("say", "poet", "POET"),
("say", "director", "MANAGER"),
("dir", None, ""), # "[_Exit_." at the end of a verse line
("say", "poet", "POET"),
("say", "lord", "THE LORD"),
("say", "director", "MANAGER"),
("say", "poet_voice", "VOICE"),
("say", "poet", "POET"),
]
assert units[0].stanzas == [["A STAGE"], ["MANAGER. POET."]]
assert units[3].lines == ["Hush, he hears."]
assert units[4].text == "Exit."
# footnote number dropped; a parenthesis inside a verse stays verse
assert units[5].lines == [
"My breast is pressed",
"Beneath such weight.",
"(The evening comes),—",
]
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"
assert [len(st) for st in units[0].stanzas] == [3, 2] # [Illustration] dropped
def test_group_units_shows_every_source_unit_once_in_order():
# game 0..4, source 0..5; pairs 0-0, 2-3, 4-5: loose source units go to loose game units
carried = group_units(5, 6, {0: 0, 2: 3, 4: 5})
assert carried == {0: [0], 1: [1, 2], 2: [3], 3: [4], 4: [5]}
assert sorted(s for v in carried.values() for s in v) == list(range(6))
def test_build_maps_every_scene(tl_work):
data = translate.build(tl_work, "en")
talk = data["scenes"]["talk"]
assert talk["title"] == "CONVERSATION"
assert talk["stats"]["complete"] and talk["stats"]["forced"] == 1
units = talk["units"]
assert units["talk_0002"][0]["stanzas"][0][0] == "Ye two, who oft my help have been,"
assert units["talk_0010"] == [
{
"kind": "dir",
"speaker": "narrator",
"src_line": units["talk_0010"][0]["src_line"],
"stanzas": [["Exit."]],
}
]
assert units["talk_0017"][0]["speaker"] == "poet_voice"
assert "SETTING" not in json.dumps(data) # the unused setting is not shown
lyric = data["scenes"]["lyric"]
assert list(lyric["units"]) == ["lyric_0001"]
assert lyric["stats"]["coverage"] == 1.0
# deterministic
assert json.dumps(translate.build(tl_work, "en")) == json.dumps(data)
def test_override_must_quote_exactly_one_unit(tl_work):
data = json.loads(json.dumps(tl_work.data))
data["translations"]["en"]["overrides"][0]["source"] = "Nothing like this"
with pytest.raises(SystemExit, match="0 source units"):
translate.build(type(tl_work)(tl_work.root, data), "en")
def test_split_long_lines_keeps_the_text_verbatim():
line = ("One two three four five six seven eight nine ten. " * 6).strip() + " End!—Next part"
chunks = renpy_tl._split_long(line)
assert len(chunks) > 1
assert all(len(c.split()) <= renpy_tl.MAX_LINE_WORDS for c in chunks)
assert re.sub(r"\s+", "", "".join(chunks)) == re.sub(r"\s+", "", line)
def test_voice_follows_the_first_box_of_the_same_speaker():
tl = renpy_tl.Translation(
"en",
"english",
"English",
{},
{
"scenes": {
"s": {
"units": {
"s_0001": [
{"kind": "say", "speaker": "poet", "src_line": 1, "stanzas": [["A"]]},
{
"kind": "say",
"speaker": "lord",
"src_line": 2,
"stanzas": [["B"], ["C"]],
},
{
"kind": "dir",
"speaker": "narrator",
"src_line": 3,
"stanzas": [["D"]],
},
],
}
}
},
},
)
scene = {
"id": "s",
"lines": [
{
"id": f"s_000{i}",
"kind": "verse",
"speech": i,
"text": "x",
"ann": {"speaker": who, "kind": "speech"},
}
for i, who in ((1, "lord"), (2, "lord"))
],
}
records = [
BoxRecord("s_0001", "lord", False, voice="voice/a.ogg"),
BoxRecord("s_0002", "lord", False),
]
cast = {"poet": {}, "lord": {}}
out = renpy_tl.render_scene_blocks(tl, scene, records, "poet_voice", cast)
assert out == [
"translate english s_0001:",
' c_poet "A"',
' voice "voice/a.ogg"',
' c_lord "B"',
" voice sustain",
' c_lord "C"',
" voice sustain",
' c_narrator "D"',
"",
"translate english s_0002:",
" pass",
"",
]
@pytest.fixture
def tl_project(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"))
out = tmp_path / "proj"
renpy_gen.generate(tl_work, annotated, out)
return out
def test_generate_writes_a_block_for_every_say(tl_project):
game = tl_project / "game"
script = (game / "script.rpy").read_text(encoding="utf-8")
tl = (game / "tl/english/script.rpy").read_text(encoding="utf-8")
ids = re.findall(r" id (\w+)$", script, re.M)
assert ids and ids == re.findall(r"^translate english (\w+):$", tl, re.M)
# the lyric scene is NVL: English pages cleared like the Spanish ones
lyric = tl.split("translate english lyric_0001:\n")[1].split("\n\n")[0].splitlines()
assert lyric == [
" nvl clear",
' c_poet_voice_nvl "Again ye come, ye hovering Forms! I find ye,\\n'
"As early to my clouded sight ye shone!\\n"
'Shall I attempt, this once, to seize and bind ye?"',
" nvl clear",
' c_poet_voice_nvl "And dear ones rise,\\nWhom fortune stole."',
]
# director's 6 lines: 4 + 2 in ADV; the rest of his Spanish unit shows nothing
talk = tl.split("translate english talk_0002:\n")[1].split("\n\n")[0].splitlines()
assert [ln.count("\\n") for ln in talk] == [3, 1]
assert "translate english talk_0006:\n pass" in tl
def test_generate_translates_names_cards_and_menus(tl_project):
game = tl_project / "game"
strings = (game / "tl/english/strings.rpy").read_text(encoding="utf-8")
for old, new in (
("El Director", "Manager"),
("CONVERSACIÓN", "CONVERSATION"),
("Escenas", "Scenes"),
("Estilo visual", "Visual style"),
("Continuará…", "To be continued…"),
):
assert f' old "{old}"\n new "{new}"' in strings
languages = (game / "languages.rpy").read_text(encoding="utf-8")
assert "define vn_languages = [(None, 'Español'), ('english', 'English')]" in languages
menu = (game / "menu_data.rpy").read_text(encoding="utf-8")
credits_tl = json.loads(re.search(r"^define vn_credits_tl = (.*)$", menu, re.M).group(1))
text = dict(credits_tl["english"])["Text"]
assert "Translation: E. Translator" in text
assert dict(credits_tl["english"]).get("Voices") is None # no voice clips in the fixture
def test_missing_names_are_an_error(tl_work, tmp_path):
translate.write_json(translate.output_path(tl_work, "en"), translate.build(tl_work, "en"))
data = json.loads(json.dumps(tl_work.data))
del data["translations"]["en"]["names"]["lord"]
annotated = json.loads(tl_work.path("data/annotated.json").read_text(encoding="utf-8"))
with pytest.raises(ValueError, match="lord"):
renpy_gen.generate(type(tl_work)(tl_work.root, data), annotated, tmp_path / "p")
def test_stale_translation_is_an_error(tl_work, tmp_path):
translate.write_json(translate.output_path(tl_work, "en"), translate.build(tl_work, "en"))
path = tl_work.path("data/annotated.json")
annotated = json.loads(path.read_text(encoding="utf-8"))
path.write_text(json.dumps(annotated, indent=2), encoding="utf-8")
with pytest.raises(ValueError, match="translate build"):
renpy_gen.generate(tl_work, annotated, tmp_path / "p")
@pytest.mark.skipif(not SDK.exists(), reason="Ren'Py SDK not found (set RENPY_SDK)")
def test_renpy_lint_with_translation(tl_project, tmp_path):
env = {**os.environ, "HOME": str(tmp_path / "home")}
(tmp_path / "home").mkdir()
result = subprocess.run(
[str(SDK), str(tl_project), "lint"], capture_output=True, text=True, env=env, timeout=300
)
report = result.stdout + result.stderr
assert result.returncode == 0, report
assert "Traceback" not in report and "error" not in report.lower(), report
assert "The english translation contains" in report