feat(renpy): play voice clips and credit the reading

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
dasemuandClaude Opus 5.5 committed 2026-10-19 14:54:31 +02:00
1 parent d537e16aa4
commit aea948c53d
2 files changed
+115 -4

No files matched your search

+39 -4
View File
@@ -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
@@ -73,6 +74,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}",
@@ -84,6 +86,7 @@ UI_LABELS = {
"translation": "Translation",
"source": "Source",
"music": "Music",
"voices": "Voices",
"art": "Illustrations",
"art_with": "Illustrations generated with {}",
"gutenberg": "Project Gutenberg #{id}",
@@ -357,11 +360,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"], {})
@@ -478,10 +488,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:<path>`` or ``none``; never restarts what already plays."""
if spec is None or (not self.audio.files and spec != "none"):
@@ -614,7 +639,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 = [
@@ -630,7 +660,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:
@@ -920,6 +952,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]
@@ -1032,6 +1066,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)
@@ -1042,7 +1077,7 @@ 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))),
):
write_text(game / name, text)
written.append(game / name)
+76
View File
@@ -0,0 +1,76 @@
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"}
]
}
},
}
),
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"}}
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))