mirror of
https://github.com/Dasemu/vnpipe.git
synced 2026-11-26 07:16:23 +00:00
feat(translate): map a public-domain translation onto the game's speeches
Add the translate {fetch,build,status} stage: parse a Project Gutenberg
ebook into speeches and directions, align them with the game's speeches by
speaker sequence, group split or merged speeches, and accept verbatim
overrides. Output: data/translations/<code>.json.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
70a0ad577b
commit
33c8b32b69
9 files changed
+1093
-2
No files matched your search
@@ -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.
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
# 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.
|
||||
|
||||
## 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: a clip that starts in the group starts on the first translated box of the same
|
||||
speaker and `voice sustain` carries it over that speaker's next boxes and directions.
|
||||
|
||||
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`
|
||||
|
||||
[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)
|
||||
```
|
||||
+8
-1
@@ -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, e.g. `spanish`, forced with `config.language` so an old persistent preference cannot switch the menus back to English; 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). |
|
||||
| `[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
@@ -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:
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
{
|
||||
"$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", "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}$"},
|
||||
"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"}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,326 @@
|
||||
"""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
|
||||
|
||||
|
||||
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, cid in {**speakers, **cfg.get("direction_labels", {})}.items():
|
||||
if cid and cid not in cast:
|
||||
raise SystemExit(f"translate: label {label!r} maps to unknown cast id {cid!r}")
|
||||
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(),
|
||||
"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")
|
||||
@@ -0,0 +1,491 @@
|
||||
"""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],
|
||||
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] = []
|
||||
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}")
|
||||
speaker = (name, speakers[name])
|
||||
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())}
|
||||
Vendored
+39
@@ -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"
|
||||
Vendored
+69
@@ -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.
|
||||
Reference in new issue
Block a user