mirror of
https://github.com/Dasemu/vnpipe.git
synced 2026-11-26 07:16:23 +00:00
feat(voice): ensembles, per-speaker filters, unlabelled sections, parallel GPUs
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
381296dffa
commit
f1581babe7
4 files changed
+118
-24
No files matched your search
+39
-15
@@ -16,6 +16,7 @@ import json
|
||||
import shutil
|
||||
import subprocess
|
||||
import urllib.request
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
@@ -128,13 +129,29 @@ def cmd_asr(args: argparse.Namespace) -> int:
|
||||
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())
|
||||
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 {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')} "
|
||||
f"--device-index {device} " + " ".join(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)
|
||||
@@ -171,11 +188,14 @@ def build_scene(
|
||||
) -> dict[str, Any]:
|
||||
"""Align one scene; returns its map entry."""
|
||||
cfg = voice_cfg(work)
|
||||
source = parse_speeches(german, cfg["speakers"])
|
||||
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)
|
||||
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()
|
||||
@@ -314,12 +334,14 @@ def probe_duration(path: Path) -> float:
|
||||
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."""
|
||||
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"loudnorm={LOUDNESS}:print_format=json", "-f", "null", "-"]
|
||||
+ ["-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"):
|
||||
@@ -333,7 +355,7 @@ def cut_clip(src: Path, start: float, end: float, dest: Path) -> None:
|
||||
tmp = dest.with_suffix(".part.ogg")
|
||||
run(
|
||||
["ffmpeg", "-hide_banner", "-nostats", "-y", *seek]
|
||||
+ ["-af", f"loudnorm={LOUDNESS}:{measured}", "-ac", "1", "-ar", "48000"]
|
||||
+ ["-af", f"{pre}loudnorm={LOUDNESS}:{measured}", "-ac", "1", "-ar", "48000"]
|
||||
+ ["-c:a", "libopus", "-b:a", "40k", "-application", "voip", str(tmp)]
|
||||
)
|
||||
tmp.replace(dest)
|
||||
@@ -345,6 +367,7 @@ def cmd_cut(args: argparse.Namespace) -> int:
|
||||
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)
|
||||
@@ -357,13 +380,14 @@ def cmd_cut(args: argparse.Namespace) -> int:
|
||||
if entry["status"] not in ("ok", "cut-failed"):
|
||||
dest.unlink(missing_ok=True)
|
||||
continue
|
||||
key = f"{src.name}:{entry['start']}:{entry['end']}:{LOUDNESS}"
|
||||
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)
|
||||
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:
|
||||
|
||||
@@ -77,10 +77,18 @@ class Speech:
|
||||
tokens: list[str] = field(default_factory=list)
|
||||
|
||||
|
||||
def parse_speeches(section: str, speakers: dict[str, str]) -> list[Speech]:
|
||||
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."""
|
||||
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] = []
|
||||
@@ -95,6 +103,10 @@ def parse_speeches(section: str, speakers: dict[str, str]) -> list[Speech]:
|
||||
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"):
|
||||
@@ -231,26 +243,30 @@ class Target:
|
||||
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, 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
|
||||
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:
|
||||
if targets[i].speaker != source[j].speaker:
|
||||
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))
|
||||
return 4.0 - min(3.0, abs(math.log2(max(ratio, 1e-3))) * 2)
|
||||
# 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):
|
||||
|
||||
@@ -148,3 +148,27 @@ def test_map_speeches_drops_merges_and_keeps_interjections():
|
||||
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) == {}
|
||||
@@ -74,3 +74,33 @@ def test_voice_clips_are_copied_outside_audio_and_credited(tmp_path):
|
||||
(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)
|
||||
Reference in new issue
Block a user