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/voice.py b/src/vnpipe/voice.py new file mode 100644 index 0000000..dc5fc17 --- /dev/null +++ b/src/vnpipe/voice.py @@ -0,0 +1,431 @@ +"""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 shutil +import subprocess +import urllib.request +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") + remote = cfg.get("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 {remote}/in {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}") + script = ( + f"cd {cfg.get('workdir', '.')} && {cfg.get('prelude', 'true')} && " + f"{cfg.get('python', 'python')} vnpipe-asr/asr.py --out vnpipe-asr/out " + f"--model {cfg.get('model', 'medium')} --language {cfg.get('language', 'de')} " + + " ".join(f"vnpipe-asr/{n}" for n in names) + ) + print(run([*ssh, script]).stdout.strip()) + 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) + source = parse_speeches(german, cfg["speakers"]) + words = asr["words"] + spans = align(source, words) + targets = game_targets(scene) + mapping = map_speeches(source, targets) + 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) -> None: + """Two-pass loudnorm (linear, so short clips are not pumped), mono Opus ~40 kbps.""" + seek = ["-ss", f"{start:.3f}", "-t", f"{end - start:.3f}", "-i", str(src)] + first = run( + ["ffmpeg", "-hide_banner", "-nostats", *seek] + + ["-af", f"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"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) + 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 + key = f"{src.name}:{entry['start']}:{entry['end']}:{LOUDNESS}" + 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) + 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) -> dict[str, dict[int, str]]: + """scene id -> {speech index: path relative to ``game/``} for clips that exist.""" + voice_map = load_json(work.path(MAP_FILE), None) + if voice_map is None: + return {} + found: dict[str, dict[int, str]] = {} + for scene_id, result in voice_map["scenes"].items(): + for entry in result["entries"]: + if entry.get("file") and 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..00edcd2 --- /dev/null +++ b/src/vnpipe/voice_align.py @@ -0,0 +1,284 @@ +"""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 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]) -> 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.""" + 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)) + + 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 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] + blocks = SequenceMatcher(None, de, asr, autojunk=False).get_matching_blocks() + matches: dict[int, list[tuple[int, int]]] = {sp.index: [] for sp in speeches} + claimed = set() + for a, b, size in blocks: + for k in range(size): + matches[owner[a + k]].append((a + k, b + k)) + claimed.add(b + k) + 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], + 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, 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 (they are + 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: + if targets[i].speaker != source[j].speaker: + return None + ratio = targets[i].words / max(1, len(source[j].tokens)) + return 4.0 - 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..2e7e015 --- /dev/null +++ b/tests/test_voice.py @@ -0,0 +1,150 @@ +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}