Merge branch 'feat/english' into development

This commit is contained in:
dasemu committed 2026-10-22 19:16:07 +02:00
commit d1bcdf3340
28 files changed
+4367 -353

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`.
+1
View File
@@ -29,6 +29,7 @@ redone unless their input changes.
| Annotation | `annotate run/status/prompt/merge` ([details](annotation.md)) | `annotate.py` |
| Assets | `assets prompt/import/process/check/status/placeholders/sheet/migrate` | `assets.py` |
| Voice (optional) | `voice fetch/asr/build/cut` ([details](voice.md)) | `voice.py`, `voice_align.py` |
| Translations (optional) | `translate fetch/build/status` ([details](translations.md)) | `translate.py`, `translate_align.py`, `renpy_tl.py` |
| Ren'Py | `renpy [--from-parsed] [--with-test] [--out DIR]` | `renpy_gen.py` |
`--work DIR` (before the subcommand) selects the work root; default is the current directory.
+14 -1
View File
@@ -89,6 +89,18 @@ tweaks, `@@TOKEN@@` placeholders for title/build name/about text/menu background
--accent '#c9a25b' --boring '#14110e' --template "$RENPY_SDK/gui" --start
```
Since then the menus were redesigned around the scene title cards (gold rule with a diamond,
size-76 titles): a book-title main menu, a navigation column with the work's title, framed
panels, and a save/load register (one row per slot with thumbnail, scene title, the line on
screen and the date; Roman-numbered pages; autosave and quick save pages only when loading;
a delete button per slot). The scene and line come from `config.save_json_callbacks`
(`menus.rpy`). The ornament images (`gui/vn/*.png`, check/radio marks, bars) are drawn by
`gui_extra_images()` in `renpy_gen.py`. `tl/spanish/` holds the Spanish UI strings: Ren'Py's
SDK translation (corrected and completed) plus every `_()` string of the screens; a test
fails when a screen string has no translation. To check a project for untranslated strings,
run `renpy.sh <copy of vn> translate spanish` on a throw-away copy and look for new `old`
entries after the "TODO: Translation updated" line.
These files are part of Ren'Py (MIT licence, Tom Rothamel and contributors). The font
`game/fonts/RobotoSlab-*.ttf` is Roboto Slab (Apache 2.0), taken from the SDK
documentation assets.
@@ -106,7 +118,8 @@ The expected result is a statistics block with no warnings above it.
Lint does not catch runtime errors (missing GUI images, display bugs). `--with-test` also
writes `game/e2e_test.rpy`, a Ren'Py `testcase` that clicks "Start", advances through the
whole game up to the final card (`label the_end`) and back to the main menu (then opens and
closes the Scenes and Credits screens), failing on any
closes the Scenes, Credits, Load, Preferences and About screens; a save made at the first
scene must carry its title), failing on any
exception (`traceback.txt`). Use a throw-away output directory so the test file never ends
up in `vn/` or in a build:
+114
View File
@@ -0,0 +1,114 @@
# Translations
A work can be played in other languages besides its own, from a **published public-domain
translation** of the same text. vnpipe never translates or rewrites the play: every line shown
in another language is copied verbatim from that translation (a Project Gutenberg ebook).
Only the game's own interface strings (menu labels, scene subtitles, credits) are written in
`work.toml` per language.
```
translation ebook ──translate fetch──▶ data/raw/<file>.txt (gitignored)
──translate build──▶ data/translations/<code>.json (committed)
──renpy──▶ game/tl/<language>/script.rpy, strings.rpy
game/languages.rpy (the choice: Preferences, first launch)
```
## Mapping (`translate build`)
The ebook (Gutenberg header, footer and licence removed) is cut at each scene's heading and
parsed into **units**: speeches (split at stage directions) and stage directions. The game
side has the same units: each direction line and each run of lines with the same speaker and
speech. The two sequences are aligned (dynamic programming): a speech pairs only with a speech
of the same speaker (two ids of `ensembles` may pair, at a penalty), a direction with a
direction; similar sizes score higher.
Translators split and merge speeches differently, so the units are **grouped**: source units
left between two pairs are shown with the first unpaired game unit of the stretch (else with
the previous pair). Every source unit is shown exactly once, in the translation's order, each
with its own speaker. A game unit with no text of its own shows nothing in that language.
Parsing rules worth knowing (`translate_align.parse_units`):
- an upper-case line followed by a blank line is a speaker label, mapped by `speakers`; an
indented one only for a known speaker (a chorus inside a song);
- `(...)` blocks, `[Exit` lines (also at the end of a verse line) and italic paragraphs are
directions; a note under a label becomes `LABEL (note)`; a parenthesis inside a stanza
ending in punctuation (`(These elements),—`) is verse;
- before the first speech, place and cast lines form one **setting** unit, used only where an
override puts it; footnote numbers at line ends and illustration markers are dropped.
`translate status` prints coverage per scene (worst first): `paired` and `carry` units show
their own text, `grouped` ones show nothing; `suspects` are groups whose size ratio is far from
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.<code>]` (sections, speakers, overrides, ...); `vnpipe renpy` refuses a
mapping built from other ones (names and strings need no rebuild).
## Ren'Py output
Every say statement carries an explicit `id` (its first line id), and each translation writes
`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
NVL, long prose paragraphs cut at sentence ends), every other box is `pass`. The voice clips
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 <language>
strings:`; equal original strings that translate differently get `{#scene}` tags. The credits
are a list per language (`vn_credits_tl`). `vnpipe renpy` fails if the JSON is missing or was
built from another `data/annotated.json`.
The language choice (`game/languages.rpy`): the work's own language is the default; the player
picks another in Preferences ("Language") or in the first-launch picker. The choice is stored
in `persistent.vn_language` and copied to `config.language`, so a stale preference never
switches the language and loading a save keeps it. `RENPY_LANGUAGE=<language>` forces one
(e.g. for the playthrough test).
## Configuration
```toml
[translations.en]
language = "english" # Ren'Py language name
label = "English" # shown in the language choice
text_url = "https://www.gutenberg.org/cache/epub/NNN/pgNNN.txt"
text_file = "data/raw/pgNNN.txt" # cache (gitignored)
gutenberg_id = NNN # credited as the source
title = "Faust" # [work] fields in this language
subtitle = "First Part"
translator = "..."
end_text = "To be continued…"
voice_credits = ["..."] # [voice].credits in this language
ignore_lines = ["..."] # exact lines of the ebook that are not play text
ensembles = ["chorus"] # default: [voice].ensembles
[translations.en.speakers] # speaker label as printed -> cast id
"MEPHISTOPHELES" = "mephisto"
[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;
"FAUST AND WAGNER" = "" # the text after is spoken by this cast id ("" = none)
[translations.en.names] # cast id -> name (every named cast member)
mephisto = "Mephistopheles"
[translations.en.strings] # other strings of the work (art-style labels)
"Pictórico" = "Painterly"
[[translations.en.sections]] # one per scene, in play order
scene = "noche"
heading = "NIGHT" # heading line in the ebook, searched in order
title = "NIGHT" # optional: shown heading (default: `heading`)
subtitle = "Faust’s study · Night" # card subtitle
# default_speaker = "poet_voice" # a section without speaker labels is one speech
[[translations.en.overrides]] # forced pair: game unit (first line id) <-> source unit
scene = "dia_nebuloso"
game = "dia_nebuloso_0001"
source = "A FIELD" # verbatim start of the source unit (markup removed)
```
+1 -1
View File
@@ -54,7 +54,7 @@ Then `vnpipe renpy` ships the clips. `--scenes` defaults to `[voice].scenes`, el
6. **Ren'Py**: `voice "voice/<id>.ogg"` before the first box of the speech, `voice sustain`
before its other boxes (a stage direction inside the speech keeps the clip going). Clips
live in `game/voice/`, never under `audio/`, so they are not music moods. The Preferences
screen has a Voice Volume slider (translate it in `tl/`). Credits get a "Voces"/"Voices"
screen has a Voice Volume slider (translated in `renpy_templates/tl/`). Credits get a "Voces"/"Voices"
section from `[voice].credits` when clips ship.
`voice/report/<scene>.txt` lists, per scene, the game speeches and their status, the ASR
+8 -1
View File
@@ -7,7 +7,7 @@ A work is a directory containing `work.toml`, plus the folders the pipeline fill
| Table | Keys |
|---|---|
| `[work]` | `id`, `title`, `subtitle`, `author`, `translator`, `language` (`es`/`en`: About, menu and credits texts), `lyric_voice` (cast id for verse nobody speaks; default `poet_voice`), `end_text`, `menu_bg` (legacy alias of `[ui].main_menu_bg`). |
| `[ui]` | `main_menu_bg` (background asset id of the main menu and, darker, the game menu; default: `[work].menu_bg`, else the first staged `bg`); `language` (Ren'Py language name set as `config.default_language`, e.g. `spanish`; its strings come from `<work>/tl/<language>/*.rpy`, copied into `game/tl/`). |
| `[ui]` | `main_menu_bg` (background asset id of the main menu and, darker, the game menu; default: `[work].menu_bg`, else the first staged `bg`); `language` (Ren'Py language name of the work's own language, e.g. `spanish`; it is the default and `config.language` follows only the player's explicit choice, so an old persistent preference cannot switch the menus back to English; `language_label` (its name in the language choice, default from `[work].language`); vnpipe ships `renpy_templates/tl/<language>/` (Ren'Py's common strings and every template screen string; only `spanish` so far) and copies `<work>/tl/<language>/*.rpy` on top, a work file replacing a shipped file with the same name). |
| `[source]` | `gutenberg_id`, `url`, `raw_file` (cache path, relative to the work root, gitignored). |
| `[scope]` | `start_marker`, `end_marker` (whole stripped lines), `end_occurrence` (1-based, searched after the start; the end marker itself is excluded). |
| `[speakers]` | Speaker heading as printed (upper case, without its italic note) → cast id. Several headings may share one id (anonymous crowd speakers). A key with punctuation or markup (`"CORO, TUTTI"`) is matched against the whole printed line first. An unknown speaker is a parse error. |
@@ -127,3 +127,10 @@ heading = "Straße (I)" # heading line in the source text, s
Voice data lives in the work: `voice/asr/NN.json` (committed ASR cache), `voice/map.json`,
`voice/report/<scene>.txt`, `voice/clips/*.ogg`. `vnpipe renpy` copies the clips to
`game/voice/` and credits them when `[voice].credits` is set.
### Translations
Optional `[translations.<code>]` tables: other languages from a published translation of the
text (verbatim, never machine-translated). Configuration, mapping rules and the Ren'Py output
are in [translations.md](translations.md); the mapping is committed as
`data/translations/<code>.json`.
+1 -1
View File
@@ -8,7 +8,7 @@ import argparse
import importlib
from pathlib import Path
STAGE_MODULES = ["text", "annotate", "assets", "renpy_gen", "voice"]
STAGE_MODULES = ["text", "annotate", "assets", "renpy_gen", "voice", "translate"]
def main(argv: list[str] | None = None) -> int:
+262 -61
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,24 +166,33 @@ def scan_audio(out: Path) -> Audio:
def copy_translations(work: Work, out: Path) -> list[Path]:
"""Copy ``<work>/tl/**/*.rpy`` into ``game/tl/`` and set ``[ui].language`` as default."""
src_root = work.path("tl")
"""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. 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 []
roots.append(work.path("tl"))
for i, root in enumerate(roots):
if not root.is_dir():
continue
prefix = Path(language) if i == 0 and language else Path()
for src in sorted(root.rglob("*.rpy")):
sources[prefix / src.relative_to(root)] = src
written = []
if src_root.is_dir():
if sources:
shutil.rmtree(dest_root, ignore_errors=True)
for src in sorted(src_root.rglob("*.rpy")):
dest = dest_root / src.relative_to(src_root)
for rel, src in sorted(sources.items()):
dest = dest_root / rel
dest.parent.mkdir(parents=True, exist_ok=True)
shutil.copyfile(src, dest)
written.append(dest)
language = work.data.get("ui", {}).get("language")
if language:
write_text(lang_file, f"define config.default_language = {quote(language)}\n")
written.append(lang_file)
else:
lang_file.unlink(missing_ok=True)
return written
@@ -351,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) + "]"
@@ -369,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/)
@@ -490,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)."""
@@ -506,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."""
@@ -671,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 = [
@@ -687,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:
@@ -722,13 +757,19 @@ def _solid(size: tuple[int, int], color: tuple[int, ...]) -> Image.Image:
def _check_image(selected: bool, round_: bool) -> Image.Image:
"""Preference marks: a diamond (radio) or a square (check), filled with gold when set."""
img = Image.new("RGBA", (38, 38), (0, 0, 0, 0))
draw = ImageDraw.Draw(img)
box = [4, 4, 33, 33]
shape = draw.ellipse if round_ else draw.rectangle
shape(box, outline=IVORY + (255,), width=3)
if selected:
shape([12, 12, 25, 25], fill=ACCENT + (255,))
if round_:
outer = [(19, 4), (34, 19), (19, 34), (4, 19)]
inner = [(19, 11), (27, 19), (19, 27), (11, 19)]
draw.polygon(outer, outline=IVORY + (200,), width=2)
if selected:
draw.polygon(inner, fill=ACCENT + (255,))
else:
draw.rectangle([6, 6, 31, 31], outline=IVORY + (200,), width=2)
if selected:
draw.rectangle([12, 12, 25, 25], fill=ACCENT + (255,))
return img
@@ -739,6 +780,84 @@ def _slot_image(border_alpha: int, fill_alpha: int) -> Image.Image:
return img
def _card_image(fill: tuple[int, ...], outer_alpha: int, inner_alpha: int) -> Image.Image:
"""A book-plate panel: tinted fill, a gold outline and a fainter inner rule 5 px inside.
Used as a Frame with 12 px borders, so the double rule never scales."""
img = Image.new("RGBA", (64, 64), fill)
draw = ImageDraw.Draw(img)
draw.rectangle([0, 0, 63, 63], outline=ACCENT + (outer_alpha,), width=2)
draw.rectangle([5, 5, 58, 58], outline=ACCENT + (inner_alpha,), width=1)
return img
def _rule_image(width: int, height: int, diamond: int) -> Image.Image:
"""A gold rule fading out at both ends, with a small diamond at its centre."""
img = Image.new("RGBA", (width, height), (0, 0, 0, 0))
mid_y = height // 2
half = width / 2
for x in range(width):
alpha = round(255 * min(1.0, (1 - abs(x + 0.5 - half) / half) * 1.6))
img.putpixel((x, mid_y), ACCENT + (alpha,))
img.putpixel((x, mid_y + 1), ACCENT + (alpha // 2,))
cx, d = width // 2, diamond
ImageDraw.Draw(img).polygon(
[(cx, mid_y - d), (cx + d, mid_y), (cx, mid_y + d), (cx - d, mid_y)], fill=ACCENT + (255,)
)
return img
def _nav_marker(alpha: int) -> Image.Image:
"""Navigation highlight: a gold bar on the left edge and a tint fading to the right."""
img = Image.new("RGBA", (96, 8), (0, 0, 0, 0))
for x in range(96):
a = alpha if x < 4 else round(alpha * 0.28 * (1 - (x - 4) / 92))
for y in range(8):
img.putpixel((x, y), ACCENT + (a,))
return img
def _line_bar(color: tuple[int, ...], thickness: int) -> Image.Image:
"""A bar/slider track: a thin horizontal line centred in a transparent 48x48 tile."""
img = Image.new("RGBA", (48, 48), (0, 0, 0, 0))
top = 24 - thickness // 2
ImageDraw.Draw(img).rectangle([0, top, 47, top + thickness - 1], fill=color)
return img
def _vline_bar(color: tuple[int, ...], thickness: int) -> Image.Image:
return _line_bar(color, thickness).transpose(Image.Transpose.ROTATE_90)
def _diamond_thumb(width: int, height: int) -> Image.Image:
img = Image.new("RGBA", (width, height), (0, 0, 0, 0))
cx, cy = width // 2, height // 2
r = min(cx, cy) - 1
ImageDraw.Draw(img).polygon(
[(cx, cy - r), (cx + r, cy), (cx, cy + r), (cx - r, cy)],
fill=ACCENT + (255,),
outline=DARK + (255,),
)
return img
def _hairline() -> Image.Image:
"""A faint gold line on the top edge (a Frame with a 1 px top border keeps it 1 px)."""
img = Image.new("RGBA", (64, 4), (0, 0, 0, 0))
ImageDraw.Draw(img).line([(0, 0), (63, 0)], fill=ACCENT + (70,))
return img
def _vignette() -> Image.Image:
"""Menu shade (scaled up to the screen): darker towards the edges, never opaque."""
w, h = 192, 108
img = Image.new("RGBA", (w, h))
for y in range(h):
for x in range(w):
d = min(1.0, (((x - w / 2) / (w / 2)) ** 2 + ((y - h / 2) / (h / 2)) ** 2) ** 0.5)
img.putpixel((x, y), DARK + (round(120 + 115 * d * d),))
return img
def gui_extra_images() -> dict[str, Image.Image]:
"""Deterministic simple GUI images, keyed by path relative to ``game/``."""
base: dict[str, Image.Image] = {
@@ -751,22 +870,35 @@ def gui_extra_images() -> dict[str, Image.Image]:
"button/check_selected_foreground.png": _check_image(True, False),
"button/radio_foreground.png": _check_image(False, True),
"button/radio_selected_foreground.png": _check_image(True, True),
"bar/left.png": _solid((48, 48), ACCENT + (255,)),
"bar/right.png": _solid((48, 48), IVORY + (60,)),
"bar/top.png": _solid((48, 48), IVORY + (60,)),
"bar/bottom.png": _solid((48, 48), ACCENT + (255,)),
"slider/horizontal_bar.png": _solid((48, 48), IVORY + (60,)),
"slider/horizontal_thumb.png": _solid((20, 38), ACCENT + (255,)),
"slider/vertical_bar.png": _solid((48, 48), IVORY + (60,)),
"slider/vertical_thumb.png": _solid((38, 20), ACCENT + (255,)),
"scrollbar/horizontal_bar.png": _solid((48, 48), IVORY + (40,)),
"scrollbar/horizontal_thumb.png": _solid((48, 48), ACCENT + (255,)),
"scrollbar/vertical_bar.png": _solid((48, 48), IVORY + (40,)),
"scrollbar/vertical_thumb.png": _solid((48, 48), ACCENT + (255,)),
"bar/left.png": _line_bar(ACCENT + (255,), 6),
"bar/right.png": _line_bar(IVORY + (70,), 2),
"bar/top.png": _vline_bar(IVORY + (70,), 2),
"bar/bottom.png": _vline_bar(ACCENT + (255,), 6),
"slider/horizontal_bar.png": _line_bar(IVORY + (90,), 2),
"slider/horizontal_thumb.png": _diamond_thumb(34, 38),
"slider/vertical_bar.png": _vline_bar(IVORY + (90,), 2),
"slider/vertical_thumb.png": _diamond_thumb(38, 34),
"scrollbar/horizontal_bar.png": _line_bar(IVORY + (50,), 2),
"scrollbar/horizontal_thumb.png": _line_bar(ACCENT + (220,), 6),
"scrollbar/vertical_bar.png": _vline_bar(IVORY + (50,), 2),
"scrollbar/vertical_thumb.png": _vline_bar(ACCENT + (220,), 6),
# Menu ornaments (screens.rpy): panels, rules, navigation marker, menu shade.
"vn/card_background.png": _card_image(DARK + (215,), 120, 45),
"vn/card_hover_background.png": _card_image((38, 31, 22, 235), 255, 140),
"vn/card_empty.png": _card_image(DARK + (120,), 55, 0),
"vn/rule.png": _rule_image(520, 18, 6),
"vn/rule_small.png": _rule_image(240, 14, 4),
"vn/nav_background.png": _solid((96, 8), (0, 0, 0, 0)),
"vn/nav_hover_background.png": _nav_marker(130),
"vn/nav_selected_background.png": _nav_marker(255),
"vn/nav_selected_hover_background.png": _nav_marker(255),
"vn/vignette.png": _vignette(),
"vn/hairline.png": _hairline(),
}
result = dict(base)
for path, img in base.items():
result[f"phone/{path}"] = img
if not path.startswith("vn/"): # ornaments are not looked up by variant prefix
result[f"phone/{path}"] = img
return {f"gui/{path}": img for path, img in sorted(result.items())}
@@ -806,15 +938,20 @@ testcase default:
pause 1.0
# Actions, not label text: stock menu labels may be translated.
run Start()
@@PICK@@ advance until eval (e2e_state["end"]) timeout 900
@@PICK@@ pause 1.0
# A save carries the scene title shown by the load screen.
run FileSave(1, confirm=False)
assert eval (FileJson(1, "vn_scene") is not None)
advance until eval (e2e_state["end"]) timeout 900
advance until screen "main_menu" timeout 60
@@MENUS@@ assert eval (e2e_state["end"])
"""
def render_e2e(styles: dict[str, Any], ui: dict[str, str]) -> str:
def render_e2e(styles: dict[str, Any]) -> str:
"""The playthrough testcase; with a style choice it also exercises the first-launch picker
(picking the last style, so the non-default switch branch is the one in use)."""
(picking the last style, so the non-default switch branch is the one in use). Menus are
opened by action, not label, so the test also runs in a translation (RENPY_LANGUAGE)."""
pick = ""
if len(styles) > 1:
sid, cfg = list(styles.items())[-1]
@@ -825,15 +962,17 @@ def render_e2e(styles: dict[str, Any], ui: dict[str, str]) -> str:
f" assert eval (persistent.art_style == {sid!r})\n"
)
menus = (
f" click {_plain_quote(ui['credits'])}\n"
' run ShowMenu("vn_credits")\n'
' assert screen "vn_credits"\n'
" run Return()\n"
' assert screen "main_menu"\n'
f" click {_plain_quote(ui['scenes'])}\n"
' run ShowMenu("vn_scene_select")\n'
' assert screen "vn_scene_select"\n'
" run Return()\n"
' assert screen "main_menu"\n'
)
for screen in ("load", "preferences", "about"):
menus += f' run ShowMenu("{screen}")\n assert screen "{screen}"\n run Return()\n'
return E2E_TESTCASE.replace("@@PICK@@", pick).replace("@@MENUS@@", menus)
@@ -866,26 +1005,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)'
)
@@ -912,7 +1066,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", "")]
@@ -921,7 +1076,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]:
@@ -986,8 +1145,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] = {}
@@ -997,11 +1159,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)
@@ -1011,8 +1183,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 {})}",
"",
]
)
@@ -1054,6 +1227,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"]
@@ -1073,6 +1250,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("*")):
@@ -1098,19 +1276,42 @@ def generate(
test_file = game / E2E_FILE
test_file.unlink(missing_ok=True)
if with_test:
write_text(test_file, render_e2e(styles, ui))
write_text(test_file, render_e2e(styles))
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:
+19 -20
View File
@@ -28,21 +28,21 @@ define config.check_conflicting_properties = True
define gui.accent_color = '#c9a25b'
## The color used for a text button when it is neither selected nor hovered.
define gui.idle_color = '#888888'
define gui.idle_color = '#b4a990'
## The small color is used for small text, which needs to be brighter/darker to
## achieve the same effect.
define gui.idle_small_color = '#aaaaaa'
define gui.idle_small_color = '#cfc4ab'
## The color that is used for buttons and bars that are hovered.
define gui.hover_color = '#dec79c'
define gui.hover_color = '#ecd4a0'
## The color used for a text button when it is selected but not focused. A
## button is selected if it is the current screen or preference value.
define gui.selected_color = '#ffffff'
define gui.selected_color = '#d9b46a'
## The color used for a text button when it cannot be selected.
define gui.insensitive_color = '#8888887f'
define gui.insensitive_color = '#7d74647f'
## Colors used for the portions of bars that are not filled in. These are not
## used directly, but are used when re-generating bar image files.
@@ -188,10 +188,10 @@ define gui.confirm_button_text_xalign = 0.5
define gui.page_button_borders = Borders(15, 6, 15, 6)
define gui.quick_button_borders = Borders(15, 6, 15, 0)
define gui.quick_button_text_size = 21
define gui.quick_button_borders = Borders(18, 6, 18, 6)
define gui.quick_button_text_size = 24
define gui.quick_button_text_idle_color = gui.idle_small_color
define gui.quick_button_text_selected_color = gui.accent_color
define gui.quick_button_text_selected_color = gui.selected_color
## You can also add your own customizations, by adding properly-named variables.
## For example, you can uncomment the following line to set the width of a
@@ -211,9 +211,9 @@ define gui.choice_button_borders = Borders(150, 8, 150, 8)
define gui.choice_button_text_font = gui.text_font
define gui.choice_button_text_size = gui.text_size
define gui.choice_button_text_xalign = 0.5
define gui.choice_button_text_idle_color = '#888888'
define gui.choice_button_text_hover_color = "#ffffff"
define gui.choice_button_text_insensitive_color = '#8888887f'
define gui.choice_button_text_idle_color = '#cfc4ab'
define gui.choice_button_text_hover_color = '#ecd4a0'
define gui.choice_button_text_insensitive_color = '#7d74647f'
## File Slot Buttons ###########################################################
@@ -237,8 +237,8 @@ define config.thumbnail_width = 384
define config.thumbnail_height = 216
## The number of columns and rows in the grid of save slots.
define gui.file_slot_cols = 3
define gui.file_slot_rows = 2
define gui.file_slot_cols = 1
define gui.file_slot_rows = 4
## Positioning and Spacing #####################################################
@@ -251,10 +251,10 @@ define gui.file_slot_rows = 2
define gui.navigation_xpos = 60
## The vertical position of the skip indicator.
define gui.skip_ypos = 15
define gui.skip_ypos = 36
## The vertical position of the notify screen.
define gui.notify_ypos = 68
define gui.notify_ypos = 36
## The spacing between menu choices.
define gui.choice_spacing = 33
@@ -341,7 +341,7 @@ define config.history_length = 250
## The height of a history screen entry, or None to make the height variable at
## the cost of performance.
define gui.history_height = 210
define gui.history_height = None
## Additional space to add between history screen entries.
define gui.history_spacing = 0
@@ -424,7 +424,7 @@ init python:
@gui.variant
def touch():
gui.quick_button_borders = Borders(60, 21, 60, 0)
gui.quick_button_borders = Borders(54, 18, 54, 10)
## This changes the size and spacing of various GUI elements to ensure they
## are easily visible on phones.
@@ -454,14 +454,13 @@ init python:
gui.navigation_spacing = 30
gui.pref_button_spacing = 15
gui.history_height = 285
gui.history_text_width = 1035
gui.quick_button_text_size = 30
## File button layout.
gui.file_slot_cols = 2
gui.file_slot_rows = 2
gui.file_slot_cols = 1
gui.file_slot_rows = 3
## NVL-mode.
gui.nvl_height = None
Binary file not shown.

Before

Width:  |  Height:  |  Size: 38 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 39 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 39 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 38 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 39 KiB

@@ -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]
+31 -2
View File
@@ -1,15 +1,41 @@
## 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()
## The scene being played (a label of `vn_scenes`); saved with the game.
default vn_current_scene = None
init python:
def vn_mark_scene(label):
store.vn_current_scene = label
if label not in persistent.vn_seen_scenes:
persistent.vn_seen_scenes.add(label)
renpy.save_persistent()
## Save metadata shown by the file slots (screens.rpy): the scene title and the first
## line of the text on screen. Text tags are dropped and markup is escaped.
VN_EXCERPT_CHARS = 90
def vn_excerpt(what):
line = renpy.filter_text_tags(what or "", allow=[]).strip().split("\n")[0].strip()
if len(line) > VN_EXCERPT_CHARS:
line = line[:VN_EXCERPT_CHARS].rsplit(" ", 1)[0] + "…"
return line.replace("[", "[[").replace("{", "{{")
def vn_save_json(d):
titles = dict((l, t) for l, t in vn_scenes)
if store.vn_current_scene in titles:
d["vn_scene"] = titles[store.vn_current_scene]
if _history_list:
last = _history_list[-1]
d["vn_who"] = (last.who or "").replace("[", "[[").replace("{", "{{")
d["vn_line"] = vn_excerpt(last.what)
config.save_json_callbacks.append(vn_save_json)
screen vn_scene_select():
tag menu
@@ -33,6 +59,8 @@ style vn_scenes_button_text is gui_button_text
style vn_scenes_button:
properties gui.button_properties("navigation_button")
xalign 0.0
padding (26, 5, 20, 5)
background Frame("gui/vn/nav_[prefix_]background.png", 6, 0)
style vn_scenes_button_text:
properties gui.text_properties("navigation_button")
@@ -50,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:
File diff suppressed because it is too large. Load diff
+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
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,247 @@
## The strings of vnpipe's template screens (renpy_templates/game/*.rpy) in Spanish (Spain).
## Keep in step with the template: tests/test_renpy_gen.py checks every _("...") string.
translate spanish strings:
old "Back"
new "Atrás"
old "History"
new "Historial"
old "Skip"
new "Saltar"
old "Auto"
new "Auto"
old "Save"
new "Guardar"
old "Q.Save"
new "Guardar rápido"
old "Q.Load"
new "Cargar rápido"
old "Prefs"
new "Opciones"
old "Start"
new "Comenzar"
old "Load"
new "Cargar"
old "Preferences"
new "Opciones"
old "End Replay"
new "Terminar la repetición"
old "Main Menu"
new "Menú principal"
old "About"
new "Acerca de"
old "Help"
new "Ayuda"
old "Quit"
new "Salir"
old "Return"
new "Volver"
old "Version [config.version!t]\n"
new "Versión [config.version!t]\n"
old "Made with {a=https://www.renpy.org/}Ren'Py{/a} [renpy.version_only].\n\n[renpy.license!t]"
new "Hecho con {a=https://www.renpy.org/}Ren'Py{/a} [renpy.version_only].\n\n[renpy.license!t]"
old "Page {}"
new "Página {}"
old "Automatic saves"
new "Autoguardado"
old "Quick saves"
new "Guardado rápido"
old "empty slot"
new "Espacio libre"
old "Saved game"
new "Partida guardada"
old "{#vn_file_time}%A, %d/%m/%Y · %H:%M"
new "{#vn_file_time}%A, %d/%m/%Y · %H:%M"
old "Delete"
new "Borrar"
old "Autosaves"
new "Autoguardado"
old "Display"
new "Pantalla"
old "Window"
new "Ventana"
old "Fullscreen"
new "Pantalla completa"
old "Unseen Text"
new "Texto no leído"
old "After Choices"
new "Tras las elecciones"
old "Transitions"
new "Transiciones"
old "Language"
new "Idioma"
old "Text Speed"
new "Velocidad del texto"
old "Auto-Forward Time"
new "Avance automático"
old "Music Volume"
new "Volumen de la música"
old "Sound Volume"
new "Volumen de los efectos"
old "Test"
new "Probar"
old "Voice Volume"
new "Volumen de las voces"
old "Mute All"
new "Silenciar todo"
old "The dialogue history is empty."
new "El historial está vacío."
old "Keyboard"
new "Teclado"
old "Mouse"
new "Ratón"
old "Gamepad"
new "Mando"
old "Enter"
new "Intro"
old "Advances dialogue and activates the interface."
new "Avanza el diálogo y activa la interfaz."
old "Space"
new "Espacio"
old "Advances dialogue without selecting choices."
new "Avanza el diálogo sin elegir opciones."
old "Arrow Keys"
new "Flechas"
old "Navigate the interface."
new "Recorren la interfaz."
old "Escape"
new "Esc"
old "Accesses the game menu."
new "Abre el menú del juego."
old "Ctrl"
new "Ctrl"
old "Skips dialogue while held down."
new "Salta el diálogo mientras se mantiene pulsada."
old "Tab"
new "Tab"
old "Toggles dialogue skipping."
new "Activa o desactiva el salto del diálogo."
old "Page Up"
new "Re Pág"
old "Rolls back to earlier dialogue."
new "Vuelve al diálogo anterior."
old "Page Down"
new "Av Pág"
old "Rolls forward to later dialogue."
new "Avanza hasta el diálogo siguiente."
old "Hides the user interface."
new "Oculta la interfaz."
old "Takes a screenshot."
new "Hace una captura de pantalla."
old "Toggles assistive {a=https://www.renpy.org/l/voicing}self-voicing{/a}."
new "Activa o desactiva la {a=https://www.renpy.org/l/voicing}lectura en voz alta{/a}."
old "Opens the accessibility menu."
new "Abre el menú de accesibilidad."
old "Left Click"
new "Clic izquierdo"
old "Middle Click"
new "Clic central"
old "Right Click"
new "Clic derecho"
old "Mouse Wheel Up"
new "Rueda hacia arriba"
old "Mouse Wheel Down"
new "Rueda hacia abajo"
old "Right Trigger\nA/Bottom Button"
new "Gatillo derecho\nA/Botón inferior"
old "Left Trigger\nLeft Shoulder"
new "Gatillo izquierdo\nBotón superior izquierdo"
old "Right Shoulder"
new "Botón superior derecho"
old "D-Pad, Sticks"
new "Cruceta, palancas"
old "Start, Guide, B/Right Button"
new "Start, Guía, B/Botón derecho"
old "Y/Top Button"
new "Y/Botón superior"
old "Calibrate"
new "Calibrar"
old "Yes"
new "Sí"
old "No"
new "No"
old "Skipping"
new "Saltando"
old "Menu"
new "Menú"
+420
View File
@@ -0,0 +1,420 @@
"""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 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
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"
)
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]
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
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, clip: str | None) -> str | None:
if clip is not None:
self.active = speaker
return f'voice "{clip}"'
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
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"
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("")
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)
@@ -0,0 +1,51 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "Translation mapped onto the game text (data/translations/<code>.json)",
"type": "object",
"required": ["version", "code", "language", "source_sha256", "annotated_sha256", "config_sha256", "scenes"],
"additionalProperties": false,
"properties": {
"version": {"const": 1},
"code": {"type": "string"},
"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": {
"type": "object",
"required": ["title", "subtitle", "units", "stats"],
"additionalProperties": false,
"properties": {
"title": {"type": "string"},
"subtitle": {"type": ["string", "null"]},
"units": {
"description": "First line id of a game unit -> the source units it shows, in order. Game units absent here show nothing (their text is in their group's first unit).",
"type": "object",
"additionalProperties": {
"type": "array",
"minItems": 1,
"items": {
"type": "object",
"required": ["kind", "speaker", "src_line", "stanzas"],
"additionalProperties": false,
"properties": {
"kind": {"enum": ["say", "dir"]},
"speaker": {"type": "string"},
"src_line": {"type": "integer"},
"stanzas": {
"type": "array",
"minItems": 1,
"items": {"type": "array", "minItems": 1, "items": {"type": "string"}}
}
}
}
}
},
"stats": {"type": "object"}
}
}
}
}
}
+348
View File
@@ -0,0 +1,348 @@
"""Translations: show the play in another language, from a published public-domain translation.
Stages (deterministic; see docs/translations.md):
fetch download the translation's text (a Project Gutenberg plain-text ebook)
build parse it into speeches and stage directions, map them onto the game's speeches by
speaker sequence -> data/translations/<code>.json
status coverage per scene (worst first); ``--scene`` prints the alignment side by side
``vnpipe renpy`` then writes ``game/tl/<language>/`` from the JSON. Nothing is machine
translated: every line comes verbatim from the configured translation.
"""
import argparse
import hashlib
import json
from pathlib import Path
from typing import Any
from vnpipe.config import Work, load_work
from vnpipe.schema import validate
from vnpipe.translate_align import (
SETTING,
GameUnit,
Unit,
align_units,
find_section_lines,
game_units,
group_units,
parse_units,
strip_gutenberg,
)
from vnpipe.voice import download
OUT_DIR = "data/translations"
SUSPECT_RATIO = 2.5 # a group whose size ratio is this far from the scene's is flagged
SUSPECT_WORDS = 25 # ... when it is at least this big (game + source words)
# --- configuration -------------------------------------------------------------------------
def translations(work: Work) -> dict[str, dict[str, Any]]:
"""``[translations.<code>]`` tables, by code (e.g. ``en``)."""
return work.data.get("translations", {})
def translation_cfg(work: Work, code: str) -> dict[str, Any]:
cfg = translations(work).get(code)
if cfg is None:
raise SystemExit(f"no [translations.{code}] table in work.toml")
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:
return work.path(f"{OUT_DIR}/{code}.json")
def load_translation(work: Work, code: str) -> dict[str, Any] | None:
path = output_path(work, code)
if not path.is_file():
return None
data = json.loads(path.read_text(encoding="utf-8"))
validate(data, "translation")
return data
def lyric_voice(work: Work) -> str:
return work.data["work"].get("lyric_voice", "poet_voice")
# --- build ---------------------------------------------------------------------------------
def find_override(source: list[Unit], quote: str, scene_id: str) -> int:
"""Index of the source unit whose text starts with ``quote`` (verbatim, after markup
cleaning); exactly one must match."""
hits = [u.index for u in source if u.text.startswith(quote)]
if len(hits) != 1:
raise SystemExit(
f"translate: override in {scene_id}: {len(hits)} source units start with {quote!r}"
)
return hits[0]
def build_scene(
work: Work,
cfg: dict[str, Any],
scene: dict[str, Any],
section: dict[str, Any],
numbered: list[tuple[int, str]],
) -> dict[str, Any]:
"""Map one scene; returns its entry of the translation file."""
sid = scene["id"]
speakers = {**cfg.get("speakers", {}), **cfg.get("scene_speakers", {}).get(sid, {})}
cast = work.cast
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,
speakers,
default_speaker=section.get("default_speaker"),
prose=scene_cfg.get("format") == "prose",
ignore=frozenset(cfg.get("ignore_lines", [])),
direction_labels=cfg.get("direction_labels", {}),
)
game = game_units(scene, lyric_voice(work))
by_line = {u.first_line: u.index for u in game}
forced: dict[int, Unit] = {}
for ov in cfg.get("overrides", []):
if ov["scene"] != sid:
continue
if ov["game"] not in by_line:
raise SystemExit(f"translate: override {ov['game']!r} is not the start of a unit")
forced[by_line[ov["game"]]] = source[find_override(source, ov["source"], sid)]
# The setting (place and cast lines) is shown only where an override puts it.
used = {id(u) for u in forced.values()}
source = [u for u in source if u.label != SETTING or id(u) in used]
for k, u in enumerate(source):
u.index = k
anchors = {g: u.index for g, u in forced.items()}
ensembles = frozenset(cfg.get("ensembles", work.data.get("voice", {}).get("ensembles", [])))
pairs = align_units(game, source, ensembles, anchors)
carried = group_units(len(game), len(source), pairs)
units: dict[str, list[dict[str, Any]]] = {}
for g, sources in carried.items():
units[game[g].first_line] = [
{
"kind": source[s].kind,
"speaker": source[s].speaker or "narrator",
"src_line": source[s].src_line,
"stanzas": source[s].stanzas,
}
for s in sources
]
return {
"title": section.get("title", section["heading"]),
"subtitle": section.get("subtitle"),
"units": units,
"stats": scene_stats(game, source, pairs, carried, set(anchors)),
}
def scene_stats(
game: list[GameUnit],
source: list[Unit],
pairs: dict[int, int],
carried: dict[int, list[int]],
forced: set[int],
) -> dict[str, Any]:
"""Counts for ``status``, and the groups whose sizes look wrong (to review)."""
ratio = sum(u.words for u in game) / max(1, sum(u.words for u in source))
heads = sorted(carried)
suspects = []
for k, head in enumerate(heads):
end = heads[k + 1] if k + 1 < len(heads) else len(game)
g_words = sum(u.words for u in game[head:end])
s_words = sum(source[s].words for s in carried[head])
rel = (g_words / max(1, s_words)) / ratio
if g_words + s_words >= SUSPECT_WORDS and not (1 / SUSPECT_RATIO <= rel <= SUSPECT_RATIO):
suspects.append(game[head].first_line)
paired = len(pairs)
carrying = sum(1 for g in carried if g not in pairs)
return {
"game_units": len(game),
"paired": paired,
"carrying": carrying,
"grouped": len(game) - paired - carrying,
"source_units": len(source),
"source_attached": len(source) - paired,
"forced": len(forced),
"coverage": round((paired + carrying) / len(game), 3) if game else 1.0,
"complete": not game or 0 in carried,
"suspects": suspects,
}
def source_sections(work: Work, cfg: dict[str, Any]) -> tuple[str, dict[str, Any]]:
path = work.path(cfg["text_file"])
if not path.is_file():
raise SystemExit(f"translate: {path} missing; run `vnpipe translate fetch`")
raw = path.read_bytes()
text = strip_gutenberg(raw.decode("utf-8"))
sections = cfg["sections"]
found = find_section_lines(text, [s["heading"] for s in sections])
return hashlib.sha256(raw).hexdigest(), {
s["scene"]: (s, lines) for s, lines in zip(sections, found, strict=True)
}
def build(work: Work, code: str) -> dict[str, Any]:
cfg = translation_cfg(work, code)
digest, sections = source_sections(work, cfg)
annotated = json.loads(work.path("data/annotated.json").read_text(encoding="utf-8"))
scenes = {}
for scene in annotated["scenes"]:
if scene["id"] not in sections:
raise SystemExit(f"translate: scene {scene['id']!r} has no [[sections]] entry")
section, numbered = sections[scene["id"]]
scenes[scene["id"]] = build_scene(work, cfg, scene, section, numbered)
data = {
"version": 1,
"code": code,
"language": cfg["language"],
"source_sha256": digest,
"annotated_sha256": hashlib.sha256(
work.path("data/annotated.json").read_bytes()
).hexdigest(),
"config_sha256": config_digest(cfg),
"scenes": scenes,
}
validate(data, "translation")
return data
def write_json(path: Path, data: dict[str, Any]) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(
json.dumps(data, ensure_ascii=False, indent=1) + "\n", encoding="utf-8", newline="\n"
)
# --- status --------------------------------------------------------------------------------
def status_lines(data: dict[str, Any]) -> list[str]:
"""One line per scene, worst coverage first."""
rows = sorted(data["scenes"].items(), key=lambda kv: (kv[1]["stats"]["coverage"], kv[0]))
out = [
f"{'scene':<20} {'coverage':>8} {'paired':>7} {'carry':>6} {'grouped':>8} "
f"{'src':>5} {'attached':>8} {'forced':>6} suspects"
]
for sid, sc in rows:
st = sc["stats"]
out.append(
f"{sid:<20} {st['coverage']:>8.1%} {st['paired']:>7} {st['carrying']:>6} "
f"{st['grouped']:>8} {st['source_units']:>5} {st['source_attached']:>8} "
f"{st['forced']:>6} {' '.join(st['suspects'])}"
)
return out
def alignment_lines(work: Work, data: dict[str, Any], scene_id: str) -> list[str]:
"""Side-by-side view of one scene: each game unit and the source text it shows."""
annotated = json.loads(work.path("data/annotated.json").read_text(encoding="utf-8"))
scene = next(s for s in annotated["scenes"] if s["id"] == scene_id)
lines = {ln["id"]: ln for ln in scene["lines"]}
units = data["scenes"][scene_id]["units"]
suspects = set(data["scenes"][scene_id]["stats"]["suspects"])
out = []
for unit in game_units(scene, lyric_voice(work)):
first = lines[unit.first_line]["text"]
mark = "!" if unit.first_line in suspects else " "
out.append(f"{mark}{unit.first_line} [{unit.speaker or 'dir'} {unit.words}w] {first[:60]}")
for item in units.get(unit.first_line, []):
text = " / ".join(ln for st in item["stanzas"] for ln in st)
words = len(text.split())
out.append(f" -> {item['speaker']} {words}w @{item['src_line']}: {text[:70]}")
if unit.first_line not in units:
out.append(" (grouped)")
return out
# --- CLI -----------------------------------------------------------------------------------
def codes(work: Work, wanted: str | None) -> list[str]:
all_codes = list(translations(work))
if not all_codes:
raise SystemExit("this work has no [translations.<code>] table in work.toml")
picked = wanted.split(",") if wanted else all_codes
for code in picked:
translation_cfg(work, code)
return picked
def cmd_fetch(args: argparse.Namespace) -> int:
work = load_work(args.work)
for code in codes(work, args.lang):
cfg = translation_cfg(work, code)
dest = work.path(cfg["text_file"])
if dest.exists():
print(f"fetch: {dest} already present")
else:
download(cfg["text_url"], dest)
return 0
def cmd_build(args: argparse.Namespace) -> int:
work = load_work(args.work)
for code in codes(work, args.lang):
data = build(work, code)
write_json(output_path(work, code), data)
print(f"build: wrote {output_path(work, code)}")
for line in status_lines(data):
print(line)
return 0
def cmd_status(args: argparse.Namespace) -> int:
work = load_work(args.work)
for code in codes(work, args.lang):
data = load_translation(work, code)
if data is None:
raise SystemExit(f"status: {output_path(work, code)} missing; run `translate build`")
print(f"[{code}] {data['language']}")
lines = alignment_lines(work, data, args.scene) if args.scene else status_lines(data)
for line in lines:
print(line)
return 0
def register(subparsers: argparse._SubParsersAction) -> None:
parser = subparsers.add_parser("translate", help="Map a published translation onto the game")
sub = parser.add_subparsers(dest="translate_command", required=True)
def add(name: str, help_: str, handler: Any) -> argparse.ArgumentParser:
p = sub.add_parser(name, help=help_)
p.add_argument("--lang", help="Comma-separated translation codes (default: all)")
p.set_defaults(handler=handler)
return p
add("fetch", "Download the translation text", cmd_fetch)
add("build", "Parse and map the translation -> data/translations/<code>.json", cmd_build)
status = add("status", "Coverage per scene, worst first", cmd_status)
status.add_argument("--scene", help="Print one scene's alignment side by side")
+498
View File
@@ -0,0 +1,498 @@
"""Translations, pure logic: parse a published translation of the play into speeches and stage
directions, and map them onto the game's speeches and directions by speaker sequence.
The game text is never translated by vnpipe: every English (or other) line comes verbatim from
a public-domain translation. Where the two translations split or merge speeches differently,
the units are grouped: a group's text goes on its first game unit, the others show nothing.
No I/O here; ``vnpipe.translate`` wires it to files and the CLI.
"""
import math
import re
from dataclasses import dataclass, field
from typing import Any
# --- source text ----------------------------------------------------------------------------
ILLUSTRATION_RE = re.compile(r"^\[Illustration[^\]]*\]?$", re.IGNORECASE)
ROMAN_RE = re.compile(r"^[IVXLC]+\.?$")
UPPER = "A-ZÀ-ÖØ-Þ"
# A speaker label: an upper-case name, optionally with a parenthetical note
# ("MEPHISTOPHELES (_to_ FAUST)", "FAUST _(passing by)_").
LABEL_RE = re.compile(
rf"^(?P<name>[{UPPER}][{UPPER}’'\-,.& ]*?[{UPPER}])\.?"
r"(?:\s*_?\((?P<note>[^)]*)\)_?)?\.?$"
)
ITALIC_RE = re.compile(r"^_[^_]+_\W*$") # a paragraph wholly in italics
EXIT_RE = re.compile(r"^_?\[.*$") # "[_Exit_.", "[He sets the goblet to his mouth."
# "...the matter. _[Exit_.": an exit printed at the end of a verse line
TRAILING_EXIT_RE = re.compile(r"^(?P<text>.*?\S)\s*(?P<exit>_?\[_?(?:Exit|Exeunt)(?![a-z]).*)$")
FOOTNOTE_RE = re.compile(r"(?<=[^\s\d])\s?\d{1,3}$") # "my stand.27": a note reference
SETTING = "setting" # label of the unit holding the place and cast lines before the first speech
def strip_gutenberg(text: str) -> str:
"""The text between the Project Gutenberg start and end markers (header, footer and
licence removed); the whole text if the markers are missing."""
lines = text.replace("\r\n", "\n").removeprefix("").split("\n")
start = next((i for i, ln in enumerate(lines) if ln.startswith("*** START OF")), -1)
end = next((i for i, ln in enumerate(lines) if ln.startswith("*** END OF")), len(lines))
return "\n".join(lines[start + 1 : end])
def find_section_lines(text: str, headings: list[str]) -> list[list[tuple[int, str]]]:
"""Cut ``text`` at each heading line, searched in order: a whole line (not indented, so a
table of contents never matches) preceded by a blank line. Returns, per heading, the
numbered lines (1-based within ``text``) after it up to the next heading."""
lines = text.split("\n")
starts: list[int] = []
pos = 0
for heading in headings:
for i in range(pos, len(lines)):
if lines[i] == heading and i > 0 and not lines[i - 1].strip():
starts.append(i)
pos = i + 1
break
else:
raise ValueError(f"heading {heading!r} not found in the translation")
bounds = [*starts, len(lines)]
return [
[(n + 1, lines[n]) for n in range(a + 1, b)]
for a, b in zip(bounds, bounds[1:], strict=False)
]
@dataclass
class Unit:
"""A speech (or part of one, between stage directions) or a stage direction."""
index: int
kind: str # "say" or "dir"
speaker: str | None # cast id; None for a direction
label: str # speaker label as printed ("" for directions)
stanzas: list[list[str]] = field(default_factory=list)
src_line: int = 0
@property
def lines(self) -> list[str]:
return [ln for st in self.stanzas for ln in st]
@property
def words(self) -> int:
return sum(len(ln.split()) for ln in self.lines)
@property
def text(self) -> str:
return " ".join(self.lines)
def clean_markup(text: str) -> str:
"""Drop italic/bold markers and collapse spaces."""
text = re.sub(r"(?<!\w)=|=(?!\w)", "", text.replace("_", ""))
return re.sub(r"\s+", " ", text).strip()
def _is_label(stripped: str) -> re.Match[str] | None:
if not stripped or stripped.startswith(("(", "[", "_")):
return None
match = LABEL_RE.match(stripped)
if match is None or not re.search(rf"[{UPPER}]{{2}}", match["name"]):
return None
return match
def _paragraph(rows: list[tuple[int, str]], i: int) -> str:
"""The stripped, joined non-blank lines from index ``i``."""
block = []
while i < len(rows) and rows[i][1].strip():
block.append(rows[i][1].strip())
i += 1
return " ".join(block)
def _whole_speech(rows: list[tuple[int, str]], i: int, after_label: bool) -> bool:
"""An italic paragraph right after a label and followed by another label (or the end) is
the whole speech (a sung refrain, a Latin hymn line), not a stage direction."""
if not after_label:
return False
while i < len(rows) and rows[i][1].strip():
i += 1
while i < len(rows) and not rows[i][1].strip():
i += 1
return i >= len(rows) or (
not rows[i][1].startswith(" ") and _is_label(rows[i][1].strip()) is not None
)
class UnknownLabel(ValueError):
"""A speaker label of the translation has no cast id in the configuration."""
def parse_units(
numbered: list[tuple[int, str]],
speakers: dict[str, str | list[str]],
default_speaker: str | None = None,
prose: bool = False,
ignore: frozenset[str] = frozenset(),
direction_labels: dict[str, str] | None = None,
) -> list[Unit]:
"""Units of one section, in order.
- Before the first speaker label (the setting): a ``(...)`` or ``_..._`` paragraph is a
direction; anything else (cast lists, place names) goes into one direction labelled
``SETTING`` (one stanza per paragraph), which the mapper only uses when an override
names it (the game drops its own cast lines).
- ``(...)`` blocks, ``[_Exit_`` lines and ``_..._`` paragraphs are directions.
- An upper-case line followed by a blank line is a speaker label (indented only for a known
speaker: the chorus inside a song), mapped through
``speakers`` (printed name without the note -> cast id); an unknown label directly
followed by another label is a cast list: dropped in the setting, a direction (an
entrance) after it.
- Everything else is verse (one line per printed line, stanzas split at blank lines) or, in
a ``prose`` section, paragraphs (one line each).
- A label listed in ``direction_labels`` ("PEASANTS, UNDER THE LINDEN-TREE") is printed as
a direction; the text after it is spoken by the cast id it maps to (none if empty).
- Lines in ``ignore`` (exact stripped text) and illustration markers are dropped; a
trailing Roman numeral (the next scene's number) is dropped, and so are footnote
reference numbers at the end of a line (the notes are not part of the play).
A section with no speaker label is one speech by ``default_speaker``.
"""
direction_labels = direction_labels or {}
rows = []
for n, t in numbered:
t = FOOTNOTE_RE.sub("", t.rstrip())
match = TRAILING_EXIT_RE.match(t)
if match and not EXIT_RE.match(t.strip()):
parts = [(n, match["text"]), (n, match["exit"])]
if match["text"].lstrip().startswith("("): # "(_Enter_ X.) [_Exit_.": the exit
parts.reverse() # belongs to the speech before the entrance
rows += parts
else:
rows.append((n, t))
rows = [
(n, t) for n, t in rows if not ILLUSTRATION_RE.match(t.strip()) and t.strip() not in ignore
]
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
started = False
setting: Unit | None = None
has_labels = any(
_is_label(t.strip()) and t.strip() not in ignore and not t.startswith(" ") for _, t in rows
)
def new_dir(text: str, src: int) -> None:
nonlocal cur
cur = None
units.append(Unit(len(units), "dir", None, "", [[clean_markup(text)]], src))
def add_setting(text: str, src: int) -> None:
nonlocal setting
if setting is None:
setting = Unit(len(units), "dir", None, SETTING, [], src)
units.append(setting)
setting.stanzas.append([clean_markup(text)])
def add_line(text: str, src: int) -> None:
nonlocal cur, pending_blank
if cur is None:
if speaker is None:
if default_speaker is None:
raise ValueError(f"line {src}: text before any speaker label: {text!r}")
label, cast = "", default_speaker
else:
label, cast = speaker
cur = Unit(len(units), "say", cast, label, [[]], src)
units.append(cur)
elif pending_blank and cur.stanzas[-1]:
cur.stanzas.append([])
pending_blank = False
cur.stanzas[-1].append(clean_markup(text))
i = 0
while i < len(rows):
src, text = rows[i]
stripped = text.strip()
i += 1
if not stripped:
pending_blank = True
continue
indented = text.startswith(" ")
if stripped.startswith("(") and indented and "_" not in stripped and cur is not None:
started = True # "(The witch's tricks)" inside an indented verse stanza
add_line(stripped, src)
continue
if stripped.startswith("("):
block = [stripped]
while " ".join(block).count("(") > " ".join(block).count(")"):
if i >= len(rows) or not rows[i][1].strip():
raise ValueError(f"line {src}: unterminated stage direction")
block.append(rows[i][1].strip())
i += 1
joined = " ".join(block).rstrip("._ ")
if re.search(r"\)[,;:—–-]+$", joined): # "(These elements),—": verse
started = True
add_line(joined, src)
continue
if joined.endswith(")"):
joined = joined[1:-1]
if clean_markup(joined)[:1].islower() and cur is None and speaker is not None:
joined = (
f"{speaker[0]} ({clean_markup(joined)})" # the label's note: "WITCH (declaims)"
)
new_dir(joined, src)
pending_blank = False
continue
if EXIT_RE.match(stripped):
new_dir(clean_markup(stripped).lstrip("[").rstrip("]"), src)
continue
if stripped.startswith("_(") and stripped.rstrip("._").endswith(")"):
new_dir(stripped.rstrip("._ ").lstrip("_")[1:-1], src)
pending_blank = False
continue
if (
not indented
and has_labels
and (i < 2 or not rows[i - 2][1].strip()) # starts a paragraph
and ITALIC_RE.match(_paragraph(rows, i - 1))
and not _whole_speech(rows, i - 1, cur is None and speaker is not None)
):
block = [stripped]
while i < len(rows) and rows[i][1].strip():
block.append(rows[i][1].strip())
i += 1
new_dir(" ".join(block), src)
continue
match = _is_label(stripped)
if match is not None and indented: # only a known speaker, inside a song
known = match["name"].strip().rstrip(".,") in speakers
if not known or (i < len(rows) and rows[i][1].strip()):
match = None
if match is not None and match["name"].strip().rstrip(".,") not in speakers:
nxt = rows[i][1] if i < len(rows) else ""
if nxt.strip() and not nxt.startswith(" "):
match = None # caps text running on: not a label
if match is not None and has_labels:
name = match["name"].strip().rstrip(".,")
after = i
while after < len(rows) and not rows[after][1].strip():
after += 1
follow = rows[after][1].strip() if after < len(rows) else ""
if name in direction_labels:
new_dir(stripped, src)
cid = direction_labels[name]
speaker = (name, cid) if cid else None
started = True
continue
if not started and (not follow or _is_label(follow) or name not in speakers):
add_setting(stripped, src) # cast list or place line
continue
if name not in speakers and _is_label(follow):
new_dir(stripped, src) # an entrance: the names of who comes on
speaker = None
continue
if name not in speakers:
raise UnknownLabel(f"line {src}: unknown speaker label {name!r}")
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
continue
if not started and has_labels: # cast list or place line of the setting
add_setting(_paragraph(rows, i - 1), src)
while i < len(rows) and rows[i][1].strip():
i += 1
continue
if prose and not indented:
block = [stripped]
while i < len(rows) and rows[i][1].strip() and not rows[i][1].startswith(" "):
block.append(rows[i][1].strip())
i += 1
add_line(" ".join(block), src)
pending_blank = True
continue
started = True
add_line(stripped, src)
for unit in units:
unit.stanzas = [st for st in unit.stanzas if st]
return [u for u in units if u.stanzas]
# --- game side ----------------------------------------------------------------------------
def is_direction(line: dict[str, Any]) -> bool:
"""Same rule as the Ren'Py generator: a direction line, or one annotated as such."""
return line["kind"] == "direction" or line["ann"]["kind"] == "stage_direction"
@dataclass
class GameUnit:
"""A run of game lines that starts a new box: a speech part or a stage direction."""
index: int
kind: str # "say" or "dir"
speaker: str | None
first_line: str
words: int = 0
line_ids: list[str] = field(default_factory=list)
def game_units(scene: dict[str, Any], lyric_voice: str) -> list[GameUnit]:
"""The scene's units: every stage direction line, and every run of lines with the same
(speaker, speech) between directions. Cast lines are skipped (they are never shown)."""
units: list[GameUnit] = []
key: tuple[str, int] | None = None
for line in scene["lines"]:
if line["kind"] == "cast":
continue
words = len(line["text"].split())
if is_direction(line):
units.append(GameUnit(len(units), "dir", None, line["id"], words, [line["id"]]))
key = None
continue
speaker = line["ann"]["speaker"] or lyric_voice
if key != (speaker, line["speech"]):
key = (speaker, line["speech"])
units.append(GameUnit(len(units), "say", speaker, line["id"]))
units[-1].words += words
units[-1].line_ids.append(line["id"])
return units
# --- mapping ------------------------------------------------------------------------------
@dataclass
class Mapping:
"""Result of mapping one scene: game unit index -> source unit indices it carries.
``pairs`` are the direct matches (same speaker, or two directions); ``carried`` lists, per
game unit, every source unit whose text it shows (its pair plus unmatched neighbours);
game units absent from ``carried`` show nothing (they belong to a group)."""
pairs: dict[int, int]
carried: dict[int, list[int]]
forced: set[int] = field(default_factory=set)
def _pair_score(g: GameUnit, s: Unit, ratio: float, ensembles: frozenset[str]) -> float | None:
if g.kind != s.kind or s.label == SETTING:
return None
size = g.words / max(1, s.words) / ratio
penalty = min(3.0, abs(math.log2(max(size, 1e-3))) * 2)
if g.kind == "dir":
return 2.0 - penalty / 2
if g.speaker != s.speaker:
if not (g.speaker in ensembles and s.speaker in ensembles):
return None
return 2.5 - penalty
return 4.0 - penalty
def align_units(
game: list[GameUnit],
source: list[Unit],
ensembles: frozenset[str] = frozenset(),
anchors: dict[int, int] | None = None,
) -> dict[int, int]:
"""Global alignment of the two unit sequences (game index -> source index).
Speeches pair only with speeches of the same speaker (or two crowd ids of ``ensembles``,
at a penalty), directions with directions; closer sizes (relative to the scene's overall
size ratio) score higher. ``anchors`` are forced pairs: the alignment runs separately
between them."""
anchors = dict(sorted((anchors or {}).items()))
pairs: dict[int, int] = {}
prev_g = prev_s = 0
for g_i, s_i in [*anchors.items(), (len(game), len(source))]:
if g_i < prev_g or s_i < prev_s:
raise ValueError("translation overrides are not in order")
pairs.update(_align_block(game, source, prev_g, g_i, prev_s, s_i, ensembles))
if g_i < len(game):
pairs[g_i] = s_i
prev_g, prev_s = g_i + 1, s_i + 1
return pairs
def _align_block(
game: list[GameUnit],
source: list[Unit],
g0: int,
g1: int,
s0: int,
s1: int,
ensembles: frozenset[str],
) -> dict[int, int]:
gs, ss = game[g0:g1], source[s0:s1]
g_words = sum(u.words for u in game) or 1
s_words = sum(u.words for u in source) or 1
ratio = g_words / s_words
n, m = len(gs), len(ss)
def gap(unit: GameUnit | Unit) -> float:
return -0.4 if unit.kind == "dir" else -1.0
table = [[0.0] * (m + 1) for _ in range(n + 1)]
for i in range(1, n + 1):
table[i][0] = table[i - 1][0] + gap(gs[i - 1])
for j in range(1, m + 1):
table[0][j] = table[0][j - 1] + gap(ss[j - 1])
scores: dict[tuple[int, int], float] = {}
for i in range(1, n + 1):
for j in range(1, m + 1):
best = max(table[i - 1][j] + gap(gs[i - 1]), table[i][j - 1] + gap(ss[j - 1]))
s = _pair_score(gs[i - 1], ss[j - 1], ratio, ensembles)
if s is not None:
scores[i, j] = s
best = max(best, table[i - 1][j - 1] + s)
table[i][j] = best
pairs: dict[int, int] = {}
i, j = n, m
while i > 0 and j > 0:
s = scores.get((i, j))
if s is not None and table[i][j] == table[i - 1][j - 1] + s:
pairs[g0 + i - 1] = s0 + j - 1
i, j = i - 1, j - 1
elif table[i][j] == table[i - 1][j] + gap(gs[i - 1]):
i -= 1
else:
j -= 1
return pairs
def group_units(n_game: int, n_source: int, pairs: dict[int, int]) -> dict[int, list[int]]:
"""Which source units each game unit shows, so every source unit is shown once and in
order. Between two pairs, unmatched source units go to the first unmatched game unit of
the stretch, else to the preceding pair (or, before the first pair, to the next one)."""
carried: dict[int, list[int]] = {}
anchors = sorted(pairs.items())
bounds = [(-1, -1), *anchors, (n_game, n_source)]
for (ga, sa), (gb, sb) in zip(bounds, bounds[1:], strict=False):
if gb < n_game:
carried.setdefault(gb, []).append(sb)
loose_s = list(range(sa + 1, sb))
if not loose_s:
continue
loose_g = list(range(ga + 1, gb))
if loose_g:
carried.setdefault(loose_g[0], []).extend(loose_s)
elif ga >= 0:
carried.setdefault(ga, []).extend(loose_s)
elif gb < n_game:
carried[gb] = loose_s + carried[gb]
elif n_game: # no pair at all: everything on the first game unit
carried.setdefault(0, []).extend(loose_s)
return {g: sorted(v) for g, v in sorted(carried.items())}
+39
View File
@@ -0,0 +1,39 @@
[translations.en]
language = "english"
label = "English"
text_url = "https://example.org/mini.txt"
text_file = "data/raw/en.txt"
gutenberg_id = 1
title = "Mini"
subtitle = "Fixture work"
translator = "E. Translator"
end_text = "To be continued…"
voice_credits = ["Voices: nobody."]
[translations.en.speakers]
MANAGER = "director"
POET = "poet"
"THE LORD" = "lord"
VOICE = "poet_voice"
[[translations.en.sections]]
scene = "lyric"
heading = "LYRIC"
default_speaker = "poet_voice"
subtitle = "Lyric · Dusk"
[[translations.en.sections]]
scene = "talk"
heading = "TALK"
title = "CONVERSATION"
[[translations.en.overrides]]
scene = "talk"
game = "talk_0010"
source = "Exit."
[translations.en.names]
director = "Manager"
poet = "Poet"
lord = "The Lord"
+69
View File
@@ -0,0 +1,69 @@
The Project Gutenberg eBook of Mini (a test fixture)
*** START OF THE PROJECT GUTENBERG EBOOK MINI ***
CONTENTS
LYRIC
TALK
LYRIC
Again ye come, ye hovering Forms! I find ye,
As early to my clouded sight ye shone!
Shall I attempt, this once, to seize and bind ye?
And dear ones rise,
Whom fortune stole.
[Illustration]
TALK
A STAGE
MANAGER. POET.
MANAGER
Ye two, who oft my help have been,
Say, what think ye?
I wish to please the crowd,
Who live and let me live.
Already there they sit,
With curious eyebrows raised.
POET
Away, profane!
MANAGER (_softly_)
Hush, he hears. [_Exit_.
POET
My breast is pressed
Beneath such weight.27
(The evening comes),—
THE LORD
My servant! Tempt him.
MANAGER
Enough talk.
VOICE
The birds are still;
The night descends.
POET
I wake.
*** END OF THE PROJECT GUTENBERG EBOOK MINI ***
Licence text that must never be read.
+78 -11
View File
@@ -1,5 +1,6 @@
import json
import os
import re
import subprocess
from pathlib import Path
@@ -48,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():
@@ -115,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")
@@ -275,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])
@@ -434,22 +437,86 @@ def test_scan_and_copy_audio(work, tmp_path):
assert "audio/scenes/x.ogg" in audio.files
def test_copy_translations_and_default_language(work, tmp_path):
def test_copy_translations(work, tmp_path):
root = tmp_path / "w"
(root / "tl/spanish").mkdir(parents=True)
(root / "tl/spanish/common.rpy").write_text("translate spanish strings:\n", encoding="utf-8")
work_common = "translate spanish strings:\n"
(root / "tl/spanish/common.rpy").write_text(work_common, encoding="utf-8")
(root / "tl/spanish/extra.rpy").write_text(work_common, encoding="utf-8")
data = {**work.data, "ui": {**work.data.get("ui", {}), "language": "spanish"}}
out = tmp_path / "out"
copied = renpy_gen.copy_translations(type(work)(root=root, data=data), out)
assert (out / "game/tl/spanish/common.rpy").is_file()
tl = out / "game/tl/spanish"
# vnpipe's own translation ships; a work file with the same path replaces it
shipped = renpy_gen.TEMPLATE_DIR / "tl/spanish/screens.rpy"
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
assert lang.read_text(encoding="utf-8") == 'define config.default_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)
def test_shipped_spanish_covers_every_template_string():
"""Every _("...") string of the template screens has exactly one Spanish translation."""
template = ""
for path in sorted((renpy_gen.TEMPLATE_DIR / "game").glob("*.rpy")):
template += path.read_text(encoding="utf-8")
wanted = set(re.findall(r'(?<![\w.])_\("((?:[^"\\]|\\.)*)"\)', template))
wanted = {s for s in wanted if "@@" not in s} # work values (title) are already translated
assert len(wanted) > 70
olds = []
for path in sorted((renpy_gen.TEMPLATE_DIR / "tl/spanish").glob("*.rpy")):
olds += _tl_strings(path)
assert len(olds) == len(set(olds)), "a string translated twice breaks Ren'Py"
assert sorted(wanted - set(olds)) == []
def test_no_sync_buttons(project):
options = (project / "game/options.rpy").read_text(encoding="utf-8")
assert "define config.has_sync = False" in options
screens = (project / "game/screens.rpy").read_text(encoding="utf-8")
assert "UploadSync" not in screens and "DownloadSync" not in screens
def test_menu_ornaments_are_deterministic():
a, b = renpy_gen.gui_extra_images(), renpy_gen.gui_extra_images()
assert a.keys() == b.keys()
assert all(a[k].tobytes() == b[k].tobytes() for k in a)
for name in ("card_background", "card_hover_background", "rule", "nav_selected_background"):
assert f"gui/vn/{name}.png" in a
assert "gui/phone/vn/rule.png" not in a # ornaments are not looked up per variant
rule = a["gui/vn/rule.png"]
mid = rule.height // 2
# bright in the middle, faded at the ends
assert rule.getpixel((0, mid))[3] < 10 and rule.getpixel((rule.width // 3, mid))[3] == 255
def test_save_metadata_and_slots(project):
menus = (project / "game/menus.rpy").read_text(encoding="utf-8")
assert "config.save_json_callbacks.append(vn_save_json)" in menus
assert "store.vn_current_scene = label" in menus
screens = (project / "game/screens.rpy").read_text(encoding="utf-8")
assert 'info.get("vn_scene")' in screens and 'info["vn_line"]' in screens
assert "FileDelete(slot)" in screens and "vn_roman(page)" in screens
def test_mood_directory_is_a_playlist(work, annotated):
block = scene_block(renpy_gen.render_script(work, annotated, _audio()), "lyric")
assert _music_lines(block) == [
+312
View File
@@ -0,0 +1,312 @@
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,
UnknownLabel,
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_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"
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",
"",
]
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"))
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