diff --git a/CLAUDE.md b/CLAUDE.md index bc791c4..943a817 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -14,8 +14,9 @@ Works (texts) live in their own repos, e.g. `../Faust-VN`. ## Commands - `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 {...}`, `renpy [--with-test]` - (default output `/vn`). + `parse`, `annotate {run,status,prompt,merge}`, `assets {...}`, `voice {fetch,asr,build,cut}` + (`docs/voice.md`), `renpy [--with-test]` (default output `/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`. - In the sandbox: `export UV_CACHE_DIR=$TMPDIR/uv-cache`. diff --git a/LESSONS.md b/LESSONS.md index 9eca44f..42a41d8 100644 --- a/LESSONS.md +++ b/LESSONS.md @@ -20,3 +20,7 @@ Recurring problems and what worked. Read before starting; add an entry when a mi made a 200-token answer cost ~10,000 hidden output tokens (50x) and minutes of latency. - Haiku gets entrances wrong when asked for `E +id` far from the character's first line; speakers auto-enter, so `E` is used mainly for exits. Check pilot output against the text. +- Voice track: judge a clip by re-transcribing it and comparing with its source speech (recall, + and precision for foreign words at the edges). Whisper mishears very short utterances + ("Liebs Kind!" -> "Ipskind!"), so low recall there is not a cut error; low precision is. + Never trust word timestamps near a neighbour's voice: pads are capped to 45% of the silence. diff --git a/docs/pipeline.md b/docs/pipeline.md index 930caa5..54b7e89 100644 --- a/docs/pipeline.md +++ b/docs/pipeline.md @@ -28,6 +28,7 @@ redone unless their input changes. | Text | `fetch`, `parse` | `text.py` | | 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` | | 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. @@ -40,6 +41,7 @@ redone unless their input changes. | `src/vnpipe/schemas/` | JSON Schemas: parsed text, annotated text, asset manifest | | `src/vnpipe/prompts/annotate.md` | Annotator instructions and vocabularies (its hash versions the cache) | | `src/vnpipe/renpy_templates/` | Default Ren'Py GUI, screens and fonts | +| `scripts/asr.py` | Standalone faster-whisper script run on a GPU host by `voice asr` | | `tests/` | Unit tests on `tests/fixtures/` (a mini work); the Ren'Py SDK tests need `RENPY_SDK` | ## Asset manifest diff --git a/docs/voice.md b/docs/voice.md new file mode 100644 index 0000000..684b542 --- /dev/null +++ b/docs/voice.md @@ -0,0 +1,75 @@ +# Voice track + +A work can play a recording of the text in its original language under the translated text +(like subtitled anime). `vnpipe voice` builds it from a public-domain reading: ASR timestamps +locate each source-language speech in the audio, the speeches are mapped onto the game's +speeches by speaker sequence, and one clip per speech is cut. Anything doubtful stays silent; +a wrong voice is never emitted. + +``` +audio sections (mp3) ──fetch──▶ data/raw/... (gitignored) +source-language text ──fetch──▶ data/raw/... (gitignored) +audio ──asr (GPU host)──▶ voice/asr/NN.json words with start/end/prob (commit it) +text + ASR + annotated.json ──build──▶ voice/map.json, voice/report/.txt +mp3 + map ──cut (ffmpeg)──▶ voice/clips/.ogg + ──renpy──▶ game/voice/*.ogg + `voice` statements +``` + +## Stages + +| Command | What it does | +|---|---| +| `voice fetch [--scenes a,b]` | Downloads the source text and the audio sections (skips existing files). | +| `voice asr [--scenes] [--host H] [--force]` | `scp`s the sections and `scripts/asr.py` to the GPU host, runs faster-whisper (word timestamps) on every `[voice.asr].devices` GPU in parallel (files balanced by size), copies `voice/asr/NN.json` back. Skips sections already present. The only step that needs a GPU; commit the JSON so the rest runs anywhere. | +| `voice build [--scenes]` | Parses the source text into speeches, aligns them with the ASR words, maps them onto the game's speeches and writes `voice/map.json` and one report per scene. | +| `voice cut [--scenes]` | Cuts and normalises one clip per `ok` speech. Cached by (audio, window, loudness). | + +Then `vnpipe renpy` ships the clips. `--scenes` defaults to `[voice].scenes`, else every +`[[voice.sections]]` entry. Config keys: see [work-config.md](work-config.md#voice). + +## How it works + +1. **Source speeches** (`voice_align.parse_speeches`): a speaker label is an upper-case line + (`FAUST.`, `MEPHISTOPHELES (zu Faust).`, parentheses may span lines); `( ... )` stage + directions are dropped; the label maps to a cast id through `[voice.speakers]` + (unknown labels become speeches nobody can be mapped to). +2. **Word alignment** (`align`): `difflib.SequenceMatcher` over tokens normalised to lower-case + letters (ß/ss and umlauts folded). The narrator reading speaker names or stage directions, + and the preamble/outro, have no counterpart in the text, so they are never matched. Per speech, + matched ASR words are clustered (a stray match is dropped); the span grows by up to two + unmatched edge words that are less than 0.3 s from it (misheard first/last words). +3. **Speaker-sequence mapping** (`map_speeches`): global alignment over the two speaker-id + sequences; only equal ids pair up, closer lengths score higher. Crowd labels are ordinal + ("the others", "second"), so ids listed in `[voice].ensembles` also pair with each other + (at a penalty); an individual never stands in for a crowd. Pairs whose length ratio + (game words / source tokens) is outside 0.4-2.5 are dropped (merged or split speeches), unless + the difference is at most 4 words (interjections). +4. **Filters**: coverage (matched share of the speech's tokens) at least 0.6, and the duration + must be plausible for the syllable count (1.6-9 syllables/s). Statuses in the map: `ok`, + `unmapped`, `low-coverage`, `implausible-duration`, `cut-failed`. Only `ok` has a clip. +5. **Cut**: `[voice.filters].` is an ffmpeg `-af` chain (noise cleanup, EQ) applied + to that speaker's clips before loudnorm; it is part of the cut cache key. Window = span start-0.1 s .. end+0.25 s, shrunk to 45% of the silence to the + neighbouring ASR word so another voice is never pulled in. Two-pass `loudnorm` + (I=-18, linear), mono Opus 40 kbps. The clip's duration is checked against the window. +6. **Ren'Py**: `voice "voice/.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" + section from `[voice].credits` when clips ship. + +`voice/report/.txt` lists, per scene, the game speeches and their status, the ASR +coverage and the source speeches left without a game speech. + +## Quality check + +Re-transcribe the clips with `scripts/asr.py` and compare each transcript with its source +speech (recall of the speech's words, precision against extra words = other voices). Clips +that fail only because of ASR mishearings on very short utterances are expected; contamination +shows as low precision with foreign words at the edges. + +## Running it elsewhere + +- ASR needs `faster-whisper` and a CUDA GPU on the host; it is deliberately not a vnpipe + dependency. Medium (int8_float16) fits 4 GB; large-v3 did not. +- ffmpeg/ffprobe (libopus, loudnorm) must be on `PATH` for `cut`. +- Source text per section is found by its heading line, in order, so repeated headings work. diff --git a/docs/work-config.md b/docs/work-config.md index b1a7710..c97aa32 100644 --- a/docs/work-config.md +++ b/docs/work-config.md @@ -17,6 +17,7 @@ A work is a directory containing `work.toml`, plus the folders the pipeline fill | `[staging.]` | `bg` (background shown after the title card), `mode` (`adv` or `nvl`), `cast = { = "left\|center\|right" }` pins sprite characters for the whole scene, `music` (see Audio; ignores the annotation moods for this scene). | | `[[cues]]` | `at` (line id; fires right before it) plus any of `bg`, `transition` (`dissolve`, `fade`, `flash`, `slow`), `tint` (`none`, `dark`, `red`), `mode`, `hide_all`, `shake`, `move = { = "" }`, `music` (see Audio; applies from that line until the next cue or the scene end). | | `[[overrides]]` | `from`, `to` (inclusive line ids in one scene), `emotion`: forces the emotion before expression mapping. | +| `[voice]` | Voice track (see Voice below): `text_url`, `text_file`, `audio_url` (with `{nn}`), `audio_dir`, `scenes`, `credits`, `[voice.asr]`, `[voice.speakers]`, `[[voice.sections]]`. | ### Text structure @@ -82,3 +83,47 @@ mood (`ann.music`), unless overridden: exists). Attributions are printed verbatim. Labels follow `[work].language`. - Defaults: `preferences.text_cps = 40`, `afm_time = 15`, `window auto`, a blinking click-to-continue arrow. Verse boxes stay at 4 lines; NVL keeps stanza pages. + +### Voice + +Optional; the full pipeline is in [voice.md](voice.md). Everything is work data: + +```toml +[voice] +scenes = ["calle_1"] # what `vnpipe voice` processes by default (omit: all) +text_url = "https://.../pg2229.txt" # source-language text +text_file = "data/raw/pg2229.txt" # cache (gitignored) +audio_url = "https://.../faust1_{nn:02d}_goethe_64kb.mp3" # one file per section number +audio_dir = "data/raw/librivox" # NN.mp3 cache (gitignored) +ensembles = ["chorus", "citizens"] # cast ids of crowds/choruses: two of them may pair up +credits = ["Lectura dramatizada de ..."] # lines of the "Voces"/"Voices" credits section + +[voice.asr] # `vnpipe voice asr`: ssh host with faster-whisper +host = "user@gpu-host" # (or --host) +workdir = "/opt/asr" # cwd on the host; files go to /vnpipe-asr/ +python = ".venv/bin/python" +prelude = "export LD_LIBRARY_PATH=..." # shell snippet run before python +model = "medium" +language = "de" +devices = [0, 1] # GPUs used in parallel (default [0]) + +[voice.speakers] # source-text speaker label (upper case) -> cast id +"FAUST" = "faust" + +[voice.scene_speakers.] # same, overriding [voice.speakers] in one scene + +[voice.filters] # optional per-speaker ffmpeg -af chain, before loudnorm +faust = "highpass=f=80,afftdn=nr=11" + +[[voice.sections]] # one per scene, in play order +scene = "calle_1" # scene id +nn = 10 # audio section number (audio_url, voice/asr/NN.json) +heading = "Straße (I)" # heading line in the source text, searched in order +# A section without speaker labels (a lyric) is one speech by `default_speaker`; +# `skip_paragraphs` drops its first N paragraphs (the setting). +# default_speaker = "poet_voice"; skip_paragraphs = 1 +``` + +Voice data lives in the work: `voice/asr/NN.json` (committed ASR cache), `voice/map.json`, +`voice/report/.txt`, `voice/clips/*.ogg`. `vnpipe renpy` copies the clips to +`game/voice/` and credits them when `[voice].credits` is set. diff --git a/scripts/asr.py b/scripts/asr.py new file mode 100644 index 0000000..0ac7446 --- /dev/null +++ b/scripts/asr.py @@ -0,0 +1,50 @@ +"""Standalone word-level ASR for `vnpipe voice asr` (runs on a GPU host, not in the pipeline). + +Depends only on faster-whisper. Writes one JSON per input audio file: +{"audio", "model", "language", "duration", "words": [[word, start, end, prob], ...]} + + python asr.py --out OUT_DIR [--model medium] [--language de] FILE.mp3 ... +""" + +import argparse +import json +from pathlib import Path + +from faster_whisper import WhisperModel + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("files", nargs="+", type=Path) + parser.add_argument("--out", type=Path, required=True) + parser.add_argument("--model", default="medium") + parser.add_argument("--language", default="de") + parser.add_argument("--device-index", type=int, default=0) + args = parser.parse_args() + args.out.mkdir(parents=True, exist_ok=True) + model = WhisperModel( + args.model, device="cuda", device_index=args.device_index, compute_type="int8_float16" + ) + for path in args.files: + segments, info = model.transcribe( + str(path), language=args.language, word_timestamps=True, vad_filter=True + ) + words = [ + [w.word.strip(), round(w.start, 2), round(w.end, 2), round(w.probability, 3)] + for seg in segments + for w in seg.words + ] + payload = { + "audio": path.name, + "model": args.model, + "language": args.language, + "duration": round(info.duration, 2), + "words": words, + } + dest = args.out / f"{path.stem}.json" + dest.write_text(json.dumps(payload, ensure_ascii=False) + "\n", encoding="utf-8") + print(f"{path.name}: {len(words)} words -> {dest}", flush=True) + + +if __name__ == "__main__": + main() diff --git a/src/vnpipe/cli.py b/src/vnpipe/cli.py index 1f21eaa..0487307 100644 --- a/src/vnpipe/cli.py +++ b/src/vnpipe/cli.py @@ -8,7 +8,7 @@ import argparse import importlib from pathlib import Path -STAGE_MODULES = ["text", "annotate", "assets", "renpy_gen"] +STAGE_MODULES = ["text", "annotate", "assets", "renpy_gen", "voice"] def main(argv: list[str] | None = None) -> int: diff --git a/src/vnpipe/renpy_gen.py b/src/vnpipe/renpy_gen.py index 566b58f..645a740 100644 --- a/src/vnpipe/renpy_gen.py +++ b/src/vnpipe/renpy_gen.py @@ -23,6 +23,7 @@ from vnpipe import PACKAGE_DIR from vnpipe.assets import load_manifest, placeholder, style_file, usable_rendition from vnpipe.config import Work, load_work from vnpipe.schema import validate +from vnpipe.voice import copy_voice, voice_files TEMPLATE_DIR = PACKAGE_DIR / "renpy_templates" NO_MANIFEST_STYLE = {"default": {"label": "Default"}} # work without an asset manifest @@ -76,6 +77,7 @@ UI_LABELS = { "translation": "Traducción", "source": "Fuente", "music": "Música", + "voices": "Voces", "art": "Ilustraciones", "art_with": "Ilustraciones generadas con {}", "gutenberg": "Proyecto Gutenberg, n.º {id}", @@ -87,6 +89,7 @@ UI_LABELS = { "translation": "Translation", "source": "Source", "music": "Music", + "voices": "Voices", "art": "Illustrations", "art_with": "Illustrations generated with {}", "gutenberg": "Project Gutenberg #{id}", @@ -360,11 +363,18 @@ class SceneWriter: """Turns one scene's lines into Ren'Py statements, tracking staging state.""" def __init__( - self, work: Work, scene: dict[str, Any], audio: Audio, music_state: dict[str, str | None] + self, + work: Work, + scene: dict[str, Any], + audio: Audio, + music_state: dict[str, str | None], + voice_files: dict[int, str] | None = None, ): self.work = work self.scene = scene self.audio = audio + self.voice_files = voice_files or {} # speech index -> clip path (relative to game/) + self.voice_started: int | None = None # speech whose clip is playing self.voice = lyric_voice(work) self.cues = {c["at"]: c for c in work.data.get("cues", [])} staging = work.data.get("staging", {}).get(scene["id"], {}) @@ -481,10 +491,25 @@ class SceneWriter: 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": self.emit("nvl clear") + def voice_statement(self, box: Box) -> 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).""" + speech = box.key[1] + path = self.voice_files.get(speech) + if not path: + return + if self.voice_started == speech: + self.emit("voice sustain") + elif not box.is_direction: + self.emit(f"voice {_plain_quote(path)}") + self.voice_started = speech + def music(self, spec: str | None) -> None: """Play/stop for a mood, ``track:`` or ``none``; never restarts what already plays.""" if spec is None or (not self.audio.files and spec != "none"): @@ -641,7 +666,12 @@ def apply_overrides(work: Work, annotated: dict[str, Any]) -> dict[str, Any]: return result -def render_script(work: Work, annotated: dict[str, Any], audio: Audio | None = None) -> str: +def render_script( + work: Work, + annotated: dict[str, Any], + audio: Audio | None = None, + voice: dict[str, dict[int, str]] | None = None, +) -> str: validate_staging(work, annotated) annotated = apply_overrides(work, annotated) out = [ @@ -657,7 +687,9 @@ def render_script(work: Work, annotated: dict[str, Any], audio: Audio | None = N 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).render()) + out.extend( + SceneWriter(work, scene, audio, music_state, (voice or {}).get(scene["id"])).render() + ) seen |= {line["id"] for line in scene["lines"]} missing = known - seen if missing: @@ -947,6 +979,8 @@ def credits_sections(work: Work, manifest: dict[str, Any] | None) -> list[tuple[ sections.append( (ui["music"], [t.get(f"attribution_{lang}") or t["attribution"] for t in tracks]) ) + if voice_files(work) and work.data.get("voice", {}).get("credits"): + sections.append((ui["voices"], list(work.data["voice"]["credits"]))) about_tail = ABOUT_LABELS.get(info.get("language", "es"), ABOUT_LABELS["en"])[2] sections.append(("vnpipe", [about_tail])) return [(title, [_markup(e) for e in entries]) for title, entries in sections] @@ -1059,6 +1093,7 @@ def generate( img.save(dest, "PNG") written.append(dest) written.extend(copy_audio(work, out)) + written.extend(copy_voice(work, out)) written.extend(copy_translations(work, out)) test_file = game / E2E_FILE test_file.unlink(missing_ok=True) @@ -1069,7 +1104,10 @@ def generate( ("characters.rpy", render_characters(work)), ("images.rpy", render_images(entries, title_cards(work, annotated))), ("menu_data.rpy", render_menu_data(work, annotated, manifest)), - ("script.rpy", render_script(work, annotated, scan_audio(out))), + ( + "script.rpy", + render_script(work, annotated, scan_audio(out), voice_files(work, annotated)), + ), ): write_text(game / name, text) written.append(game / name) diff --git a/src/vnpipe/voice.py b/src/vnpipe/voice.py new file mode 100644 index 0000000..c3e50c4 --- /dev/null +++ b/src/vnpipe/voice.py @@ -0,0 +1,474 @@ +"""Voice track: a source-language reading played under the translated text. + +Stages (all deterministic and cached on disk; see docs/voice.md): + + fetch download the reading's audio sections and the source-language text + asr word-level transcription of each audio section on a GPU host -> voice/asr/NN.json + build parse the source text, align it with the ASR words, map its speeches onto the game's + speeches by speaker sequence -> voice/map.json + voice/report/.txt + cut ffmpeg: one normalised clip per mapped speech -> voice/clips/.ogg + +``vnpipe renpy`` then plays the clips (``voice`` statements); speeches with no clip stay silent. +""" + +import argparse +import json +import shlex +import shutil +import subprocess +import urllib.request +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path +from typing import Any + +from vnpipe.config import Work, load_work +from vnpipe.voice_align import ( + Target, + align, + find_sections, + map_speeches, + pad_bounds, + parse_speeches, + plausible_duration, +) + +CLIPS_DIR = "voice/clips" +MAP_FILE = "voice/map.json" +MIN_COVERAGE = 0.6 # share of a speech's words found in the audio, below which it stays silent +LOUDNESS = "I=-18:TP=-2:LRA=11" +ASR_SCRIPT = Path(__file__).resolve().parents[2] / "scripts" / "asr.py" + + +# --- configuration ------------------------------------------------------------------------- + + +def voice_cfg(work: Work) -> dict[str, Any]: + cfg = work.data.get("voice") + if not cfg: + raise SystemExit("this work has no [voice] table in work.toml") + return cfg + + +def selected_sections(work: Work, scenes: str | None) -> list[dict[str, Any]]: + """The ``[[voice.sections]]`` entries to process: ``--scenes a,b``, else ``[voice].scenes``, + else all of them.""" + cfg = voice_cfg(work) + wanted = scenes.split(",") if scenes else cfg.get("scenes") + sections = cfg["sections"] + known = {s["scene"] for s in sections} + for scene in wanted or []: + if scene not in known: + raise SystemExit(f"voice: scene {scene!r} has no [[voice.sections]] entry") + return [s for s in sections if not wanted or s["scene"] in wanted] + + +def asr_path(work: Work, section: dict[str, Any]) -> Path: + return work.path(f"voice/asr/{section['nn']:02d}.json") + + +def audio_path(work: Work, section: dict[str, Any]) -> Path: + return work.path(voice_cfg(work)["audio_dir"]) / f"{section['nn']:02d}.mp3" + + +# --- fetch --------------------------------------------------------------------------------- + + +def download(url: str, dest: Path) -> None: + dest.parent.mkdir(parents=True, exist_ok=True) + request = urllib.request.Request(url, headers={"User-Agent": "vnpipe/0.1"}) + with urllib.request.urlopen(request, timeout=120) as response: # noqa: S310 + payload = response.read() + tmp = dest.with_suffix(dest.suffix + ".part") + tmp.write_bytes(payload) + tmp.replace(dest) + print(f"fetch: wrote {dest} ({len(payload)} bytes)") + + +def cmd_fetch(args: argparse.Namespace) -> int: + work = load_work(args.work) + cfg = voice_cfg(work) + text = work.path(cfg["text_file"]) + if not text.exists(): + download(cfg["text_url"], text) + for section in selected_sections(work, args.scenes): + dest = audio_path(work, section) + if not dest.exists(): + download(cfg["audio_url"].format(nn=section["nn"]), dest) + return 0 + + +# --- asr ----------------------------------------------------------------------------------- + + +def run(cmd: list[str], **kwargs: Any) -> subprocess.CompletedProcess[str]: + result = subprocess.run(cmd, capture_output=True, text=True, **kwargs) # noqa: S603 + if result.returncode: + raise SystemExit(f"voice: {' '.join(cmd[:3])} failed:\n{result.stderr[-800:]}") + return result + + +def cmd_asr(args: argparse.Namespace) -> int: + work = load_work(args.work) + cfg = voice_cfg(work).get("asr", {}) + host = args.host or cfg.get("host") + if not host: + raise SystemExit("voice asr: pass --host or set [voice.asr].host") + if host.startswith("-"): + raise SystemExit(f"voice asr: invalid host {host!r}") + workdir = cfg.get("workdir", ".") + remote = workdir + "/vnpipe-asr" + sections = selected_sections(work, args.scenes) + todo = [s for s in sections if args.force or not asr_path(work, s).exists()] + if not todo: + print("asr: all sections already transcribed") + return 0 + ssh = ["ssh", "-o", "BatchMode=yes", host] + scp = ["scp", "-o", "BatchMode=yes"] + run([*ssh, f"mkdir -p {shlex.quote(remote + '/in')} {shlex.quote(remote + '/out')}"]) + run([*scp, str(ASR_SCRIPT), f"{host}:{remote}/asr.py"]) + names = [] + for section in todo: + src = audio_path(work, section) + if not src.is_file(): + raise SystemExit(f"asr: {src} missing; run `vnpipe voice fetch`") + run([*scp, str(src), f"{host}:{remote}/in/{src.name}"]) + names.append(f"in/{src.name}") + devices = cfg.get("devices", [0]) + groups: list[list[str]] = [[] for _ in devices] + loads = [0] * len(devices) + for name in sorted( + names, key=lambda n: -work.path(f"{voice_cfg(work)['audio_dir']}/{n[3:]}").stat().st_size + ): + i = loads.index(min(loads)) # biggest first onto the least loaded device + groups[i].append(name) + loads[i] += work.path(f"{voice_cfg(work)['audio_dir']}/{name[3:]}").stat().st_size + + def transcribe(device: int, files: list[str]) -> str: + script = ( + f"cd {shlex.quote(workdir)} && {cfg.get('prelude', 'true')} && " + f"{cfg.get('python', 'python')} vnpipe-asr/asr.py --out vnpipe-asr/out " + f"--model {shlex.quote(str(cfg.get('model', 'medium')))} " + f"--language {shlex.quote(str(cfg.get('language', 'de')))} " + f"--device-index {int(device)} " + + " ".join(shlex.quote(f"vnpipe-asr/{n}") for n in files) + ) + return run([*ssh, script]).stdout.strip() + + jobs = [(d, g) for d, g in zip(devices, groups, strict=True) if g] + with ThreadPoolExecutor(max_workers=len(jobs)) as pool: + for output in pool.map(lambda job: transcribe(*job), jobs): + print(output) + for section in todo: + dest = asr_path(work, section) + dest.parent.mkdir(parents=True, exist_ok=True) + run([*scp, f"{host}:{remote}/out/{section['nn']:02d}.json", str(dest)]) + print(f"asr: wrote {dest}") + return 0 + + +# --- build --------------------------------------------------------------------------------- + + +def game_targets(scene: dict[str, Any]) -> list[Target]: + """Speeches of a game scene that have a speaker, in order.""" + found: dict[int, Target] = {} + for line in scene["lines"]: + speaker = line["ann"]["speaker"] + if line["kind"] not in ("verse", "prose") or not speaker: + continue + target = found.setdefault(line["speech"], Target(line["speech"], speaker, 0, line["id"])) + target.words += len(line["text"].split()) + return [found[k] for k in sorted(found)] + + +def load_json(path: Path, default: Any) -> Any: + return json.loads(path.read_text(encoding="utf-8")) if path.is_file() else default + + +def build_scene( + work: Work, + scene: dict[str, Any], + section: dict[str, Any], + german: str, + asr: dict[str, Any], +) -> dict[str, Any]: + """Align one scene; returns its map entry.""" + cfg = voice_cfg(work) + speakers = {**cfg["speakers"], **cfg.get("scene_speakers", {}).get(scene["id"], {})} + source = parse_speeches( + german, speakers, section.get("default_speaker"), section.get("skip_paragraphs", 0) + ) + words = asr["words"] + spans = align(source, words) + targets = game_targets(scene) + mapping = map_speeches(source, targets, frozenset(cfg.get("ensembles", []))) + total_tokens = sum(len(s.tokens) for s in source) + matched_tokens = sum(sp.matched for sp in spans if sp) + used: set[int] = set() + entries = [] + for target in targets: + entry: dict[str, Any] = { + "speech": target.speech, + "first_line": target.first_line, + "speaker": target.speaker, + "words": target.words, + "source": None, + "status": "unmapped", + "file": None, + } + j = mapping.get(target.speech) + if j is not None: + used.add(j) + sp, span = source[j], spans[j] + entry["source"] = j + if span is None or span.coverage < MIN_COVERAGE: + entry["status"] = "low-coverage" + entry["coverage"] = round(span.coverage, 2) if span else 0.0 + else: + start, end = pad_bounds(span, words) + entry.update( + coverage=round(span.coverage, 2), + start=round(start, 2), + end=round(end, 2), + status="ok" + if plausible_duration(span.end - span.start, sp.text) + else "implausible-duration", + ) + if entry["status"] == "ok": + entry["file"] = f"voice/{target.first_line}.ogg" + entries.append(entry) + voiced = sum(e["status"] == "ok" for e in entries) + result = { + "section": section["nn"], + "speeches": len(entries), + "voiced": voiced, + "source_speeches": len(source), + "asr_coverage": round(matched_tokens / total_tokens, 3) if total_tokens else 0.0, + "entries": entries, + "unmapped_source": [ + { + "index": sp.index, + "label": sp.label, + "speaker": sp.speaker, + "tokens": len(sp.tokens), + "coverage": round(spans[sp.index].coverage, 2) if spans[sp.index] else None, + } + for sp in source + if sp.index not in used + ], + } + return result + + +def report_text(scene_id: str, result: dict[str, Any]) -> str: + out = [ + f"scene {scene_id} (audio section {result['section']})", + f"voiced {result['voiced']}/{result['speeches']} game speeches", + f"source speeches {result['source_speeches']}, " + f"ASR coverage {result['asr_coverage']:.1%} of source words", + "", + "game speeches:", + ] + for e in result["entries"]: + extra = "" + if e["source"] is not None: + extra = f" <- source #{e['source']} cov {e.get('coverage', 0):.2f}" + if "start" in e: + extra += f" {e['start']:.1f}-{e['end']:.1f}s" + out.append(f" {e['status']:<20} {e['first_line']} {e['speaker']} ({e['words']}w){extra}") + out += ["", "source speeches without a game speech:"] + for sp in result["unmapped_source"]: + cov = "not found" if sp["coverage"] is None else f"cov {sp['coverage']:.2f}" + who = f"{sp['label']} -> {sp['speaker']}" + out.append(f" #{sp['index']} {who} ({sp['tokens']} tokens, {cov})") + return "\n".join(out) + "\n" + + +def cmd_build(args: argparse.Namespace) -> int: + work = load_work(args.work) + cfg = voice_cfg(work) + text_path = work.path(cfg["text_file"]) + if not text_path.is_file(): + raise SystemExit("voice build: source text missing; run `vnpipe voice fetch`") + annotated = json.loads(work.path("data/annotated.json").read_text(encoding="utf-8")) + scenes = {s["id"]: s for s in annotated["scenes"]} + all_sections = cfg["sections"] + texts = find_sections( + text_path.read_text(encoding="utf-8"), [s["heading"] for s in all_sections] + ) + by_scene = {s["scene"]: t for s, t in zip(all_sections, texts, strict=True)} + voice_map = load_json(work.path(MAP_FILE), {"version": 1, "scenes": {}}) + for section in selected_sections(work, args.scenes): + scene_id = section["scene"] + path = asr_path(work, section) + if not path.is_file(): + raise SystemExit(f"voice build: {path} missing; run `vnpipe voice asr`") + asr = json.loads(path.read_text(encoding="utf-8")) + result = build_scene(work, scenes[scene_id], section, by_scene[scene_id], asr) + voice_map["scenes"][scene_id] = result + write_report(work, scene_id, result) + print( + f"build: {scene_id}: voiced {result['voiced']}/{result['speeches']}, " + f"ASR coverage {result['asr_coverage']:.1%}" + ) + voice_map["scenes"] = dict(sorted(voice_map["scenes"].items())) + write_map(work, voice_map) + return 0 + + +def write_report(work: Work, scene_id: str, result: dict[str, Any]) -> None: + path = work.path(f"voice/report/{scene_id}.txt") + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(report_text(scene_id, result), encoding="utf-8", newline="\n") + + +def write_map(work: Work, voice_map: dict[str, Any]) -> None: + path = work.path(MAP_FILE) + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text( + json.dumps(voice_map, ensure_ascii=False, indent=1) + "\n", encoding="utf-8", newline="\n" + ) + + +# --- cut ----------------------------------------------------------------------------------- + + +def probe_duration(path: Path) -> float: + out = run( + ["ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0", str(path)] + ).stdout + return float(out.strip()) + + +def cut_clip(src: Path, start: float, end: float, dest: Path, chain: str = "") -> None: + """Optional ``chain`` (ffmpeg ``-af`` filters, e.g. a noise cleanup), then two-pass + loudnorm (linear, so short clips are not pumped); mono Opus ~40 kbps.""" + pre = f"{chain}," if chain else "" + seek = ["-ss", f"{start:.3f}", "-t", f"{end - start:.3f}", "-i", str(src)] + first = run( + ["ffmpeg", "-hide_banner", "-nostats", *seek] + + ["-af", f"{pre}loudnorm={LOUDNESS}:print_format=json", "-f", "null", "-"] + ).stderr + stats, _ = json.JSONDecoder().raw_decode(first[first.rindex("{") :]) + if stats["input_i"] in ("-inf", "inf"): + raise ValueError("silent clip") + measured = ( + f"measured_I={stats['input_i']}:measured_TP={stats['input_tp']}:" + f"measured_LRA={stats['input_lra']}:measured_thresh={stats['input_thresh']}:" + f"offset={stats['target_offset']}:linear=true" + ) + dest.parent.mkdir(parents=True, exist_ok=True) + tmp = dest.with_suffix(".part.ogg") + run( + ["ffmpeg", "-hide_banner", "-nostats", "-y", *seek] + + ["-af", f"{pre}loudnorm={LOUDNESS}:{measured}", "-ac", "1", "-ar", "48000"] + + ["-c:a", "libopus", "-b:a", "40k", "-application", "voip", str(tmp)] + ) + tmp.replace(dest) + + +def cmd_cut(args: argparse.Namespace) -> int: + work = load_work(args.work) + voice_map = load_json(work.path(MAP_FILE), None) + if voice_map is None: + raise SystemExit("voice cut: voice/map.json missing; run `vnpipe voice build`") + clips = work.path(CLIPS_DIR) + filters: dict[str, str] = voice_cfg(work).get("filters", {}) + for section in selected_sections(work, args.scenes): + scene_id = section["scene"] + result = voice_map["scenes"].get(scene_id) + if result is None: + raise SystemExit(f"voice cut: {scene_id} not built; run `vnpipe voice build`") + src = audio_path(work, section) + made = reused = 0 + for entry in result["entries"]: + dest = clips / f"{entry['first_line']}.ogg" + if entry["status"] not in ("ok", "cut-failed"): + dest.unlink(missing_ok=True) + continue + chain = filters.get(entry["speaker"], "") + key = f"{src.name}:{entry['start']}:{entry['end']}:{LOUDNESS}:{chain}" + if dest.is_file() and entry.get("cut_key") == key: + reused += 1 + continue + expected = entry["end"] - entry["start"] + try: + cut_clip(src, entry["start"], entry["end"], dest, chain) + if abs(probe_duration(dest) - expected) > 0.3: + raise ValueError("duration mismatch") + except (ValueError, SystemExit, KeyError) as exc: + dest.unlink(missing_ok=True) + entry.update(status="cut-failed", file=None, error=str(exc)[:200]) + entry.pop("cut_key", None) + continue + entry.update(status="ok", file=f"voice/{entry['first_line']}.ogg", cut_key=key) + entry.pop("error", None) + made += 1 + result["voiced"] = sum(e["status"] == "ok" for e in result["entries"]) + print(f"cut: {scene_id}: {made} new, {reused} cached, {result['voiced']} voiced") + write_report(work, scene_id, result) + write_map(work, voice_map) + return 0 + + +# --- used by `vnpipe renpy` ---------------------------------------------------------------- + + +def voice_files(work: Work, annotated: dict[str, Any] | None = None) -> dict[str, dict[int, str]]: + """scene id -> {speech index: path relative to ``game/``} for clips that exist. + + A clip counts only if it was cut for the current map entry (``cut_key``) and, when + ``annotated`` is given, the speech still starts on the line the clip was cut for, so a + re-parse that shifts speech indices never plays a clip on the wrong speech.""" + voice_map = load_json(work.path(MAP_FILE), None) + if voice_map is None: + return {} + scenes = {s["id"]: s for s in annotated["scenes"]} if annotated else {} + found: dict[str, dict[int, str]] = {} + for scene_id, result in voice_map["scenes"].items(): + first_lines = None + if annotated is not None: + scene = scenes.get(scene_id) + first_lines = {t.speech: t.first_line for t in game_targets(scene)} if scene else {} + for entry in result["entries"]: + if not (entry.get("file") and entry.get("cut_key")): + continue + if first_lines is not None and first_lines.get(entry["speech"]) != entry["first_line"]: + continue + if work.path(f"{CLIPS_DIR}/{entry['first_line']}.ogg").is_file(): + found.setdefault(scene_id, {})[entry["speech"]] = entry["file"] + return found + + +def copy_voice(work: Work, out: Path) -> list[Path]: + """Copy ``/voice/clips/*.ogg`` into ``game/voice/`` (never into ``game/audio/``).""" + dest_root = out / "game" / "voice" + shutil.rmtree(dest_root, ignore_errors=True) + written = [] + for src in sorted(work.path(CLIPS_DIR).glob("*.ogg")): + dest = dest_root / src.name + dest.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(src, dest) + written.append(dest) + return written + + +# --- CLI ----------------------------------------------------------------------------------- + + +def register(subparsers: argparse._SubParsersAction) -> None: + voice = subparsers.add_parser("voice", help="Voice track from a source-language reading") + sub = voice.add_subparsers(dest="voice_command", required=True) + + def add(name: str, help_: str, handler: Any) -> argparse.ArgumentParser: + p = sub.add_parser(name, help=help_) + p.add_argument("--scenes", help="Comma-separated scene ids (default: [voice].scenes)") + p.set_defaults(handler=handler) + return p + + add("fetch", "Download the audio sections and the source text", cmd_fetch) + asr = add("asr", "Transcribe audio sections with word timestamps on a GPU host", cmd_asr) + asr.add_argument("--host", help="ssh host (default: [voice.asr].host)") + asr.add_argument("--force", action="store_true", help="Redo sections already transcribed") + add("build", "Align source text with ASR and map speeches onto the game text", cmd_build) + add("cut", "Cut normalised clips from the mapped speeches", cmd_cut) diff --git a/src/vnpipe/voice_align.py b/src/vnpipe/voice_align.py new file mode 100644 index 0000000..4b9f27a --- /dev/null +++ b/src/vnpipe/voice_align.py @@ -0,0 +1,354 @@ +"""Voice track, pure logic: parse a spoken-language source text into speeches, align it with +ASR words, and map those speeches onto the game's speeches by speaker sequence. + +No I/O here; ``vnpipe.voice`` wires it to files, ffmpeg and the CLI. +""" + +import math +import re +import unicodedata +from bisect import bisect_left +from dataclasses import dataclass, field +from difflib import SequenceMatcher +from typing import Any + +# --- tokens ----------------------------------------------------------------------------- + +_FOLD = str.maketrans({"ß": "ss", "ä": "a", "ö": "o", "ü": "u"}) +_VOWELS = re.compile(r"[aeiouyäöü]+", re.IGNORECASE) + + +def normalise(word: str) -> str: + """Lowercase letters only; ß/ss and umlauts folded, so ASR spelling variants still match.""" + word = unicodedata.normalize("NFC", word).lower().translate(_FOLD) + return re.sub(r"[^a-z]", "", word) + + +def tokenize(text: str) -> list[str]: + """Normalised tokens of a text (hyphens and dashes split words).""" + parts = re.split(r"[\s\-–—]+", text) + return [t for t in (normalise(p) for p in parts) if t] + + +def syllables(text: str) -> int: + """Rough syllable count: vowel groups (a diphthong counts once).""" + return sum(len(_VOWELS.findall(t)) for t in text.split()) + + +# --- source text ------------------------------------------------------------------------- + + +def find_sections(text: str, headings: list[str]) -> list[str]: + """Cut ``text`` at each heading, searched in order; a heading is a whole line (not + indented, so the table of contents never matches) preceded by a blank line. + The last section ends at the Project Gutenberg end marker, if present.""" + lines = text.splitlines() + 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 source text") + end = next( + (i for i, ln in enumerate(lines) if ln.startswith("*** END OF")), + len(lines), + ) + bounds = [*starts, end] + return ["\n".join(lines[a + 1 : b]) for a, b in zip(bounds, bounds[1:], strict=False)] + + +_LABEL = re.compile( + r"^([A-ZÄÖÜ][A-ZÄÖÜ ]*[A-ZÄÖÜ])(?:\.? ?\([^)]*\))?\.?[ \t]*$", + re.MULTILINE, +) + + +@dataclass +class Speech: + """One speech of the source text.""" + + index: int + label: str # speaker heading as printed (upper case) + speaker: str | None # cast id (None: not in the mapping) + text: str + tokens: list[str] = field(default_factory=list) + + +def parse_speeches( + section: str, + speakers: dict[str, str], + default_speaker: str | None = None, + skip_paragraphs: int = 0, +) -> list[Speech]: + """Speeches of one section. ``speakers`` maps the printed upper-case label (without its + parenthetical) to a cast id. Stage directions ``( ... )`` are dropped from the text; the + setting block before the first label is ignored. + + A section with no speaker label at all (a lyric, a song) is one speech by + ``default_speaker``, after dropping its first ``skip_paragraphs`` paragraphs (the setting).""" + marked = _LABEL.sub(lambda m: f"\x00{m.group(1)}\x00", section) + marked = re.sub(r"\([^)]*\)", " ", marked) + speeches: list[Speech] = [] + label: str | None = None + body: list[str] = [] + + def close() -> None: + if label is None: + return + text = " ".join(" ".join(body).split()) + tokens = tokenize(text) + if tokens: + speeches.append(Speech(len(speeches), label, speakers.get(label), text, tokens)) + + if default_speaker and "\x00" not in marked: + paragraphs = [p for p in re.split(r"\n\s*\n", marked.strip()) if p.strip()] + text = " ".join(" ".join(paragraphs[skip_paragraphs:]).split()) + return [Speech(0, "", default_speaker, text, tokenize(text))] + for raw in marked.splitlines(): + line = raw.strip() + if line.startswith("\x00") and line.endswith("\x00"): + close() + label, body = line.strip("\x00"), [] + elif label is not None and line: + body.append(line) + close() + return speeches + + +# --- ASR alignment ----------------------------------------------------------------------- + + +@dataclass +class Span: + """Where one source speech sits in the audio.""" + + start: float + end: float + first: int # ASR word index range [first, last] + last: int + matched: int + total: int + + @property + def coverage(self) -> float: + return self.matched / self.total if self.total else 0.0 + + +def match_tokens(a: list[str], b: list[str], n: int = 3) -> list[tuple[int, int]]: + """Monotonic token matches ``(i, j)`` with ``a[i] == b[j]``. + + Plain ``SequenceMatcher`` is far too slow on a whole section (thousands of tokens, most of + them "und"/"die"), so first anchor on word n-grams that occur exactly once on each side + (longest increasing run), then match only the stretches between anchors.""" + keys_a: dict[tuple[str, ...], list[int]] = {} + keys_b: dict[tuple[str, ...], list[int]] = {} + for i in range(len(a) - n + 1): + keys_a.setdefault(tuple(a[i : i + n]), []).append(i) + for j in range(len(b) - n + 1): + keys_b.setdefault(tuple(b[j : j + n]), []).append(j) + pairs = sorted( + (ia[0], keys_b[k][0]) + for k, ia in keys_a.items() + if len(ia) == 1 and len(keys_b.get(k, ())) == 1 + ) + # longest increasing subsequence on the b positions + tails: list[int] = [] + ends: list[int] = [] + prev = [-1] * len(pairs) + for idx, (_, j) in enumerate(pairs): + pos = bisect_left(tails, j) + if pos == len(tails): + tails.append(j) + ends.append(idx) + else: + tails[pos] = j + ends[pos] = idx + prev[idx] = ends[pos - 1] if pos else -1 + chain: list[tuple[int, int]] = [] + idx = ends[-1] if ends else -1 + while idx >= 0: + chain.append(pairs[idx]) + idx = prev[idx] + chain.reverse() + + matches: list[tuple[int, int]] = [] + ia = jb = 0 # next unmatched positions + + def fill(a_end: int, b_end: int) -> None: + blocks = SequenceMatcher(None, a[ia:a_end], b[jb:b_end], autojunk=False) + for x, y, size in blocks.get_matching_blocks(): + matches.extend((ia + x + k, jb + y + k) for k in range(size)) + + for i, j in chain: + if i < ia or j < jb: + continue # overlaps the previous anchor + fill(i, j) + matches.extend((i + k, j + k) for k in range(n)) + ia, jb = i + n, j + n + fill(len(a), len(b)) + return matches + + +def align( + speeches: list[Speech], asr_words: list[list[Any]], max_gap: int = 12 +) -> list[Span | None]: + """Align the speeches' tokens with ASR words ([word, start, end, prob]) and return one + ``Span`` per speech (None when nothing matched). + + Sequence alignment on normalised tokens; matched ASR words of a speech are clustered + (a stray match far from the rest is dropped) and the span is trimmed to the cluster, then + grown by the unmatched edge tokens that sit right next to it in time.""" + de: list[str] = [] + owner: list[int] = [] + for sp in speeches: + de.extend(sp.tokens) + owner.extend([sp.index] * len(sp.tokens)) + asr = [normalise(w[0]) for w in asr_words] + matches: dict[int, list[tuple[int, int]]] = {sp.index: [] for sp in speeches} + claimed = set() + for i, j in match_tokens(de, asr): + matches[owner[i]].append((i, j)) + claimed.add(j) + offsets: dict[int, int] = {} + pos = 0 + for sp in speeches: + offsets[sp.index] = pos + pos += len(sp.tokens) + + spans: list[Span | None] = [] + for sp in speeches: + found = matches[sp.index] + if not found: + spans.append(None) + continue + # cluster by ASR index: split where consecutive matches are > max_gap words apart + clusters: list[list[tuple[int, int]]] = [[found[0]]] + for item in found[1:]: + if item[1] - clusters[-1][-1][1] > max_gap: + clusters.append([]) + clusters[-1].append(item) + best = max(clusters, key=len) + first, last = best[0][1], best[-1][1] + lead = best[0][0] - offsets[sp.index] # unmatched source tokens before the cluster + trail = offsets[sp.index] + len(sp.tokens) - 1 - best[-1][0] + for _ in range(min(lead, 2)): # misheard first words: take adjacent unclaimed words + prev = first - 1 + if prev < 0 or prev in claimed or asr_words[first][1] - asr_words[prev][2] > 0.3: + break + first = prev + for _ in range(min(trail, 2)): + nxt = last + 1 + if nxt >= len(asr_words) or nxt in claimed: + break + if asr_words[nxt][1] - asr_words[last][2] > 0.3: + break + last = nxt + spans.append( + Span( + start=asr_words[first][1], + end=asr_words[last][2], + first=first, + last=last, + matched=len(best), + total=len(sp.tokens), + ) + ) + return spans + + +def pad_bounds( + span: Span, asr_words: list[list[Any]], pre: float = 0.1, post: float = 0.25 +) -> tuple[float, float]: + """Cut window around a span: the paddings, shrunk to 45% of the silence to the neighbouring + ASR word so a neighbour (another voice) is never pulled in.""" + start, end = span.start - pre, span.end + post + if span.first > 0: + gap = span.start - asr_words[span.first - 1][2] + start = span.start - min(pre, max(0.0, gap) * 0.45) + if span.last + 1 < len(asr_words): + gap = asr_words[span.last + 1][1] - span.end + end = span.end + min(post, max(0.0, gap) * 0.45) + return max(0.0, start), end + + +def plausible_duration(duration: float, text: str) -> bool: + """Reading speed sanity check: between 1.6 and 9 syllables per second (plus a margin).""" + syl = max(1, syllables(text)) + return syl / 9.0 - 0.3 <= duration <= syl / 1.6 + 1.0 + + +# --- speaker-sequence mapping -------------------------------------------------------------- + + +@dataclass +class Target: + """A speech of the game text: its index in the scene, speaker and size in words.""" + + speech: int + speaker: str + words: int + first_line: str + + +def map_speeches( + source: list[Speech], + targets: list[Target], + ensembles: frozenset[str] = frozenset(), + min_ratio: float = 0.4, + max_ratio: float = 2.5, + short: int = 4, +) -> dict[int, int]: + """Map target speech index -> source speech index. + + Global alignment over the two speaker sequences: only equal speaker ids pair up (or two + ids of ``ensembles``, at a penalty), the others are gaps. Pairs score higher the closer + their lengths are, so a merge/split by the translator resolves to the best partner. Pairs + whose length ratio (target words / source tokens) is outside ``[min_ratio, max_ratio]`` + are dropped afterwards (merges or splits, where a clip would not match the text), unless + the two speeches differ + by at most ``short`` words (interjections: the ratio means nothing there).""" + n, m = len(targets), len(source) + gap = -1.0 + + def score(i: int, j: int) -> float | None: + a, b = targets[i].speaker, source[j].speaker + if a != b and not (a in ensembles and b in ensembles): + return None + ratio = targets[i].words / max(1, len(source[j].tokens)) + # two different ensemble ids may be the same crowd (labels are ordinal: "the others") + return 4.0 - (0.0 if a == b else 1.5) - min(3.0, abs(math.log2(max(ratio, 1e-3))) * 2) + + table = [[0.0] * (m + 1) for _ in range(n + 1)] + for i in range(1, n + 1): + table[i][0] = i * gap + for j in range(1, m + 1): + table[0][j] = j * gap + for i in range(1, n + 1): + for j in range(1, m + 1): + best = max(table[i - 1][j] + gap, table[i][j - 1] + gap) + s = score(i - 1, j - 1) + if s is not None: + 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 = score(i - 1, j - 1) + if s is not None and table[i][j] == table[i - 1][j - 1] + s: + pairs[i - 1] = j - 1 + i, j = i - 1, j - 1 + elif table[i][j] == table[i - 1][j] + gap: + i -= 1 + else: + j -= 1 + result = {} + for ti, sj in pairs.items(): + size = len(source[sj].tokens) + ratio = targets[ti].words / max(1, size) + if min_ratio <= ratio <= max_ratio or abs(targets[ti].words - size) <= short: + result[targets[ti].speech] = sj + return result diff --git a/tests/fixtures/voice_de.txt b/tests/fixtures/voice_de.txt new file mode 100644 index 0000000..b15f9b5 --- /dev/null +++ b/tests/fixtures/voice_de.txt @@ -0,0 +1,49 @@ +Mini: +Ein Beispiel + +Contents + + Erste Szene + Zweite Szene + +*** START OF THE PROJECT GUTENBERG EBOOK MINI *** + + + + +Erste Szene + + +Faust. Margarete. + +FAUST. +Mein schönes Fräulein, darf ich wagen, +Meinen Arm und Geleit Ihr anzutragen? + +MARGARETE. +Bin weder Fräulein, weder schön, +Kann ungeleitet nach Hause gehn. +(Sie macht sich los und ab.) + +FAUST (für sich). +Beim Himmel, dieses Kind ist schön! +Sie ist so sitt- und tugendreich. +(Mephistopheles tritt auf.) + +MEPHISTOPHELES (zu Faust, indem er +sich verneigt). +Ein Schüler? Wer? + +UNBEKANNTER. +Ich bin’s. + + + + +Zweite Szene + + +MEPHISTOPHELES. +Es ist ein Maß, ein süßes Ding. + +*** END OF THE PROJECT GUTENBERG EBOOK MINI *** diff --git a/tests/test_voice.py b/tests/test_voice.py new file mode 100644 index 0000000..36c52dc --- /dev/null +++ b/tests/test_voice.py @@ -0,0 +1,185 @@ +from pathlib import Path + +import pytest + +from vnpipe.voice_align import ( + Target, + align, + find_sections, + map_speeches, + normalise, + pad_bounds, + parse_speeches, + plausible_duration, + syllables, + tokenize, +) + +FIXTURES = Path(__file__).parent / "fixtures" +SPEAKERS = {"FAUST": "faust", "MARGARETE": "margarita", "MEPHISTOPHELES": "mephisto"} + + +@pytest.fixture(scope="module") +def sections(): + text = (FIXTURES / "voice_de.txt").read_text(encoding="utf-8") + return find_sections(text, ["Erste Szene", "Zweite Szene"]) + + +def test_normalise_folds_spelling_variants(): + assert normalise("Fräulein,") == "fraulein" + assert normalise("Maß") == normalise("Mass") == "mass" + assert normalise("geht’s!") == "gehts" + assert tokenize("sitt- und tugendreich — gar") == ["sitt", "und", "tugendreich", "gar"] + + +def test_syllables_counts_vowel_groups(): + assert syllables("Mein schönes Fräulein") == 5 # ei, ö, e, äu, ei + + +def test_find_sections_skips_contents_and_stops_at_end(sections): + assert "Mein schönes Fräulein" in sections[0] + assert "Zweite Szene" not in sections[0] + assert sections[1].strip().startswith("MEPHISTOPHELES.") + assert "END OF" not in sections[1] + with pytest.raises(ValueError, match="not found"): + find_sections("a\n\n\nB\n\nx", ["Missing"]) + + +def test_parse_speeches(sections): + speeches = parse_speeches(sections[0], SPEAKERS) + assert [(s.speaker, s.label) for s in speeches] == [ + ("faust", "FAUST"), + ("margarita", "MARGARETE"), + ("faust", "FAUST"), # "FAUST (für sich)." is the same speaker + ("mephisto", "MEPHISTOPHELES"), # multi-line parenthetical on the label + (None, "UNBEKANNTER"), # unknown label: kept, never mapped + ] + assert speeches[1].text == "Bin weder Fräulein, weder schön, Kann ungeleitet nach Hause gehn." + assert "Mephistopheles" not in speeches[2].text # stage direction dropped + assert speeches[2].tokens[-3:] == ["sitt", "und", "tugendreich"][-3:] + assert speeches[3].text == "Ein Schüler? Wer?" + + +def asr_for(speeches, narrator=("faust",), mishear_first=False): + """Fake ASR: preamble, then per speech the narrator reading its name and the speech.""" + words, t = [], 0.0 + + def add(word, gap=0.3): + nonlocal t + t += gap + words.append([word, round(t, 2), round(t + 0.25, 2), 0.9]) + t += 0.25 + + for w in ("Dies", "ist", "eine", "LibriVox", "Aufnahme"): + add(w) + for sp in speeches: + add(sp.label.title(), gap=0.8) # the narrator announces the speaker + for i, token in enumerate(sp.tokens): + add("Xyz" if (mishear_first and i == 0) else token, gap=0.1) + return words + + +def test_align_excludes_narrator_and_preamble(sections): + speeches = parse_speeches(sections[0], SPEAKERS) + words = asr_for(speeches) + spans = align(speeches, words) + for sp, span in zip(speeches, spans, strict=True): + assert span and span.coverage == 1.0 + assert words[span.first][0].lower() == sp.tokens[0] + assert words[span.last][0].lower() == sp.tokens[-1] + assert spans[0].end < spans[1].start # ordered, disjoint + + +def test_align_recovers_a_misheard_first_word(sections): + speeches = parse_speeches(sections[0], SPEAKERS) + words = asr_for(speeches, mishear_first=True) + span = align(speeches, words)[1] + assert span.coverage < 1.0 + assert words[span.first][0] == "Xyz" # grown by the unmatched, adjacent word + assert words[span.first - 1][0] == "Margarete" # but not into the narrator's name + + +def test_align_missing_speech_gets_none(): + speeches = parse_speeches("FAUST.\nganz anderer Text hier", {"FAUST": "faust"}) + assert align(speeches, [["nichts", 0.0, 0.5, 0.9]]) == [None] + + +def test_pad_bounds_never_reach_the_neighbour(sections): + speeches = parse_speeches(sections[0], SPEAKERS) + words = asr_for(speeches) + span = align(speeches, words)[0] + start, end = pad_bounds(span, words) + assert words[span.first - 1][2] < start < span.start + assert span.end < end < words[span.last + 1][1] + # a neighbour 0.1 s away leaves almost no padding + words[span.last + 1][1] = span.end + 0.1 + assert pad_bounds(span, words)[1] <= span.end + 0.05 + + +def test_plausible_duration(): + text = "Mein schönes Fräulein, darf ich wagen" # ~9 syllables + assert plausible_duration(4.0, text) + assert not plausible_duration(0.5, text) # impossibly fast + assert not plausible_duration(40.0, text) # a clip with much more than the text + + +def sp(speaker, n): + return parse_speeches(f"FAUST.\n{' '.join(['wort'] * n)}", {"FAUST": speaker})[0] + + +def test_map_speeches_by_speaker_sequence(): + source = [sp("a", 10), sp("b", 10), sp("a", 10), sp("b", 5)] + targets = [Target(0, "a", 10, "x1"), Target(1, "b", 11, "x2"), Target(2, "a", 9, "x3")] + assert map_speeches(source, targets) == {0: 0, 1: 1, 2: 2} + + +def test_map_speeches_skips_extra_speech_on_either_side(): + source = [sp("a", 10), sp("b", 10), sp("a", 10)] + targets = [Target(0, "a", 10, "x1"), Target(1, "b", 10, "x2"), Target(2, "a", 10, "x3")] + assert map_speeches(source, targets[:2] + [Target(3, "a", 12, "x4")]) == {0: 0, 1: 1, 3: 2} + # the translator added a speech that has no counterpart: it stays unmapped + extra = [targets[0], Target(5, "b", 12, "y"), *targets[1:]] + assert 5 not in map_speeches(source, extra) or map_speeches(source, extra)[5] == 1 + + +def test_map_speeches_drops_merges_and_keeps_interjections(): + source = [sp("a", 40), sp("b", 3)] + # 120 words against 40 tokens: a merge, no voice + assert map_speeches(source, [Target(0, "a", 120, "x"), Target(1, "b", 5, "y")]) == {1: 1} + # short interjections are paired whatever the ratio + assert map_speeches([sp("b", 1)], [Target(0, "b", 4, "y")]) == {0: 0} + + +def test_unlabelled_section_is_one_speech_by_the_default_speaker(): + section = ( + "\nIn der Kapelle, davor Blumen.\n\nAch neige,\nDu Schmerzenreiche,\n\nDein Antlitz.\n" + ) + assert parse_speeches(section, {}) == [] + (speech,) = parse_speeches(section, {}, default_speaker="margarita", skip_paragraphs=1) + assert speech.speaker == "margarita" + assert speech.text == "Ach neige, Du Schmerzenreiche, Dein Antlitz." + + +def test_map_speeches_pairs_ensemble_ids_in_sequence(): + source = [sp("crowd", 10), sp("faust", 10), sp("crowd", 10)] + targets = [ + Target(0, "artisans", 10, "a"), + Target(1, "faust", 10, "b"), + Target(2, "citizens", 10, "c"), + ] + assert map_speeches(source, targets) == {1: 1} # different ids never pair by default + ensembles = frozenset({"crowd", "artisans", "citizens"}) + assert map_speeches(source, targets, ensembles) == {0: 0, 1: 1, 2: 2} + # an individual never stands in for an ensemble + assert map_speeches([sp("faust", 10)], [Target(0, "citizens", 10, "x")], ensembles) == {} + + +def test_match_tokens_anchors_and_fills(): + from vnpipe.voice_align import match_tokens + + a = ["und", "die", "der", "ein", "wort", "a", "b", "c", "d", "e", "f", "g", "x", "y", "z"] + b = ["und", "die", "ein", "wort", "a", "b", "c", "d", "e", "f", "g", "q", "y", "z"] + pairs = match_tokens(a, b) + assert all(a[i] == b[j] for i, j in pairs) + assert [i for i, _ in pairs] == sorted(i for i, _ in pairs) + assert len(pairs) >= 12 diff --git a/tests/test_voice_renpy.py b/tests/test_voice_renpy.py new file mode 100644 index 0000000..5d6f6fb --- /dev/null +++ b/tests/test_voice_renpy.py @@ -0,0 +1,130 @@ +import json +from pathlib import Path + +from vnpipe import renpy_gen +from vnpipe import voice as voice_mod +from vnpipe.config import load_work + +FIXTURES = Path(__file__).parent / "fixtures" + + +def test_game_targets_and_voice_emission(tmp_path): + work = load_work(FIXTURES / "mini_work") + annotated = json.loads((FIXTURES / "annotated_mini.json").read_text(encoding="utf-8")) + talk = next(s for s in annotated["scenes"] if s["id"] == "talk") + targets = voice_mod.game_targets(talk) + assert [(t.speech, t.speaker, t.first_line) for t in targets][:3] == [ + (0, "director", "talk_0002"), + (1, "poet", "talk_0008"), + (2, "director", "talk_0009"), + ] + voice = { + "lyric": {0: "voice/lyric_0001.ogg"}, + "talk": {2: "voice/talk_0009.ogg"}, + } + script = renpy_gen.render_script(work, annotated, voice=voice) + lines = [ln.strip() for ln in script.splitlines()] + # a speech spanning several boxes: `voice` once, then `voice sustain` + lyric = lines[lines.index("label scene_lyric:") : lines.index("label scene_talk:")] + assert lyric.count('voice "voice/lyric_0001.ogg"') == 1 + assert lyric.count("voice sustain") >= 1 + first_say = next(i for i, ln in enumerate(lyric) if ln.startswith("c_")) + assert lyric[first_say - 1] == 'voice "voice/lyric_0001.ogg"' + # a stage direction inside the voiced speech keeps the clip going + talk_block = lines[lines.index("label scene_talk:") :] + assert talk_block.count('voice "voice/talk_0009.ogg"') == 1 + i = talk_block.index('voice "voice/talk_0009.ogg"') + assert talk_block[i + 1].startswith("c_director") + assert "voice sustain" in talk_block[i + 2 : i + 6] + # speeches without a clip emit nothing + assert script.count("voice ") == script.count('voice "') + script.count("voice sustain") + plain = renpy_gen.render_script(work, annotated) + assert 'voice "' not in plain and "voice sustain" not in plain + + +def test_voice_clips_are_copied_outside_audio_and_credited(tmp_path): + root = tmp_path / "w" + (root / "voice/clips").mkdir(parents=True) + (root / "voice/clips/talk_0009.ogg").write_bytes(b"OggS") + (root / "voice/map.json").write_text( + json.dumps( + { + "version": 1, + "scenes": { + "talk": { + "entries": [ + { + "speech": 2, + "first_line": "talk_0009", + "file": "voice/talk_0009.ogg", + "cut_key": "k", + } + ] + } + }, + } + ), + encoding="utf-8", + ) + base = load_work(FIXTURES / "mini_work") + data = json.loads(json.dumps(base.data)) + data["voice"] = {"credits": ["Lectura de [LibriVox]"]} + work = type(base)(root=root, data=data) + assert voice_mod.voice_files(work) == {"talk": {2: "voice/talk_0009.ogg"}} + annotated = json.loads((FIXTURES / "annotated_mini.json").read_text(encoding="utf-8")) + assert voice_mod.voice_files(work, annotated) == {"talk": {2: "voice/talk_0009.ogg"}} + talk = next(s for s in annotated["scenes"] if s["id"] == "talk") + for ln in talk["lines"]: # a re-parse renumbers the speeches + ln["speech"] += 1 + assert voice_mod.voice_files(work, annotated) == {} # never a clip on the wrong speech + written = voice_mod.copy_voice(work, tmp_path / "out") + assert [p.relative_to(tmp_path / "out").as_posix() for p in written] == [ + "game/voice/talk_0009.ogg" + ] + assert dict(renpy_gen.credits_sections(work, None))["Voces"] == ["Lectura de [[LibriVox]"] + (root / "voice/clips/talk_0009.ogg").unlink() # no clip, no credit, no voice + assert voice_mod.voice_files(work) == {} + assert "Voces" not in dict(renpy_gen.credits_sections(work, None)) + + +def test_cut_clip_applies_the_speaker_chain_before_loudnorm(monkeypatch, tmp_path): + calls = [] + + class Result: + stderr = json.dumps( + { + "input_i": "-20", + "input_tp": "-3", + "input_lra": "5", + "input_thresh": "-30", + "target_offset": "0.1", + } + ) + + def fake_run(cmd, **kwargs): + calls.append(cmd) + return Result() + + monkeypatch.setattr(voice_mod, "run", fake_run) + (tmp_path / "x.part.ogg").write_bytes(b"") + voice_mod.cut_clip(Path("a.mp3"), 1.0, 3.0, tmp_path / "x.ogg", "highpass=f=80") + filters = [c[c.index("-af") + 1] for c in calls] + assert len(filters) == 2 + assert all(f.startswith("highpass=f=80,loudnorm=") for f in filters) + calls.clear() + (tmp_path / "x.part.ogg").write_bytes(b"") + voice_mod.cut_clip(Path("a.mp3"), 1.0, 3.0, tmp_path / "x.ogg") + assert all(c[c.index("-af") + 1].startswith("loudnorm=") for c in calls) + + +def test_uncut_clip_is_not_played(tmp_path): + root = tmp_path / "w" + (root / "voice/clips").mkdir(parents=True) + (root / "voice/clips/talk_0009.ogg").write_bytes(b"OggS") # left over from an older cut + entry = {"speech": 2, "first_line": "talk_0009", "file": "voice/talk_0009.ogg"} + (root / "voice/map.json").write_text( + json.dumps({"version": 1, "scenes": {"talk": {"entries": [entry]}}}), encoding="utf-8" + ) + base = load_work(FIXTURES / "mini_work") + work = type(base)(root=root, data=base.data) + assert voice_mod.voice_files(work) == {}