feat: extract vnpipe pipeline from faust-vn

Generic "classic novels to visual novels" pipeline extracted from faust-vn
(source commit 6486ab1). The work-specific data (Faust text, annotations,
assets, generated project) stays in faust-vn.

Changes versus the source: --work defaults to the current directory, the
renpy command writes to <work root>/vn, the Ren'Py SDK is located through
RENPY_SDK, and tests only use fixtures.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
dasemuandClaude Opus 5.5 committed 2026-10-19 03:59:33 +02:00
commit ff78dc5b14
68 files changed
+7727

No files matched your search

+699
View File
@@ -0,0 +1,699 @@
{
"work": "mini",
"parsed_sha256": "0000000000000000000000000000000000000000000000000000000000000000",
"fallback_chunks": [],
"scenes": [
{
"id": "lyric",
"heading": "LÍRICA",
"lines": [
{
"id": "lyric_0001",
"kind": "verse",
"speaker": null,
"speaker_note": null,
"speech": 0,
"stanza": 0,
"indent": 0,
"text": "Tornáis de nuevo, imágenes flotantes,",
"src_line": 100,
"ann": {
"speaker": "poet_voice",
"kind": "narration",
"emotion": "melancholic",
"location": "dedication",
"time_of_day": "timeless",
"on_stage": [],
"music": "sacred"
}
},
{
"id": "lyric_0002",
"kind": "verse",
"speaker": null,
"speaker_note": null,
"speech": 0,
"stanza": 0,
"indent": 0,
"text": "que un día contemplé,",
"src_line": 101,
"ann": {
"speaker": "poet_voice",
"kind": "narration",
"emotion": "melancholic",
"location": "dedication",
"time_of_day": "timeless",
"on_stage": []
}
},
{
"id": "lyric_0003",
"kind": "verse",
"speaker": null,
"speaker_note": null,
"speech": 0,
"stanza": 0,
"indent": 0,
"text": "¿Asiros podré feliz?",
"src_line": 102,
"ann": {
"speaker": "poet_voice",
"kind": "narration",
"emotion": "melancholic",
"location": "dedication",
"time_of_day": "timeless",
"on_stage": []
}
},
{
"id": "lyric_0004",
"kind": "verse",
"speaker": null,
"speaker_note": null,
"speech": 0,
"stanza": 0,
"indent": 0,
"text": "Venid, y envueltas en el velo,",
"src_line": 103,
"ann": {
"speaker": "poet_voice",
"kind": "narration",
"emotion": "melancholic",
"location": "dedication",
"time_of_day": "timeless",
"on_stage": []
}
},
{
"id": "lyric_0005",
"kind": "verse",
"speaker": null,
"speaker_note": null,
"speech": 0,
"stanza": 0,
"indent": 0,
"text": "girad en derredor;",
"src_line": 104,
"ann": {
"speaker": "poet_voice",
"kind": "narration",
"emotion": "melancholic",
"location": "dedication",
"time_of_day": "timeless",
"on_stage": []
}
},
{
"id": "lyric_0006",
"kind": "verse",
"speaker": null,
"speaker_note": null,
"speech": 0,
"stanza": 0,
"indent": 0,
"text": "el corazón aún late,",
"src_line": 105,
"ann": {
"speaker": "poet_voice",
"kind": "narration",
"emotion": "melancholic",
"location": "dedication",
"time_of_day": "timeless",
"on_stage": []
}
},
{
"id": "lyric_0007",
"kind": "verse",
"speaker": null,
"speaker_note": null,
"speech": 0,
"stanza": 0,
"indent": 0,
"text": "si aspira vuestro aliento.",
"src_line": 106,
"ann": {
"speaker": "poet_voice",
"kind": "narration",
"emotion": "melancholic",
"location": "dedication",
"time_of_day": "timeless",
"on_stage": []
}
},
{
"id": "lyric_0008",
"kind": "verse",
"speaker": null,
"speaker_note": null,
"speech": 0,
"stanza": 0,
"indent": 0,
"text": "Hoy vuelven de otro tiempo",
"src_line": 107,
"ann": {
"speaker": "poet_voice",
"kind": "narration",
"emotion": "melancholic",
"location": "dedication",
"time_of_day": "timeless",
"on_stage": []
}
},
{
"id": "lyric_0009",
"kind": "verse",
"speaker": null,
"speaker_note": null,
"speech": 0,
"stanza": 0,
"indent": 0,
"text": "la alegre historia,",
"src_line": 108,
"ann": {
"speaker": "poet_voice",
"kind": "narration",
"emotion": "melancholic",
"location": "dedication",
"time_of_day": "timeless",
"on_stage": []
}
},
{
"id": "lyric_0010",
"kind": "verse",
"speaker": null,
"speaker_note": null,
"speech": 0,
"stanza": 1,
"indent": 0,
"text": "Y los queridos seres",
"src_line": 120,
"ann": {
"speaker": "poet_voice",
"kind": "narration",
"emotion": "melancholic",
"location": "dedication",
"time_of_day": "timeless",
"on_stage": []
}
},
{
"id": "lyric_0011",
"kind": "verse",
"speaker": null,
"speaker_note": null,
"speech": 0,
"stanza": 1,
"indent": 0,
"text": "que la dicha nos robó.",
"src_line": 121,
"ann": {
"speaker": "poet_voice",
"kind": "narration",
"emotion": "melancholic",
"location": "dedication",
"time_of_day": "timeless",
"on_stage": []
}
}
]
},
{
"id": "talk",
"heading": "CONVERSACIÓN",
"lines": [
{
"id": "talk_0001",
"kind": "cast",
"speaker": null,
"speaker_note": null,
"speech": 0,
"stanza": 0,
"indent": 0,
"text": "EL DIRECTOR, EL POETA",
"src_line": 200,
"ann": {
"speaker": null,
"kind": "narration",
"emotion": "neutral",
"location": "stage",
"time_of_day": "day",
"on_stage": []
}
},
{
"id": "talk_0002",
"kind": "verse",
"speaker": "director",
"speaker_note": null,
"speech": 0,
"stanza": 0,
"indent": 2,
"text": "Decid, buenos amigos,",
"src_line": 201,
"ann": {
"speaker": "director",
"kind": "dialogue",
"emotion": "joyful",
"location": "stage",
"time_of_day": "day",
"on_stage": [
{
"character": "director",
"position": "left"
}
]
}
},
{
"id": "talk_0003",
"kind": "verse",
"speaker": "director",
"speaker_note": null,
"speech": 0,
"stanza": 0,
"indent": 0,
"text": "de mi afán camaradas,",
"src_line": 202,
"ann": {
"speaker": "director",
"kind": "dialogue",
"emotion": "neutral",
"location": "stage",
"time_of_day": "day",
"on_stage": [
{
"character": "director",
"position": "left"
}
]
}
},
{
"id": "talk_0004",
"kind": "verse",
"speaker": "director",
"speaker_note": null,
"speech": 0,
"stanza": 0,
"indent": 0,
"text": "¿qué pensáis [ahora]?",
"src_line": 203,
"ann": {
"speaker": "director",
"kind": "dialogue",
"emotion": "neutral",
"location": "stage",
"time_of_day": "day",
"on_stage": [
{
"character": "director",
"position": "left"
}
]
}
},
{
"id": "talk_0005",
"kind": "verse",
"speaker": "director",
"speaker_note": null,
"speech": 0,
"stanza": 0,
"indent": 0,
"text": "Es mi {anhelo} preferente",
"src_line": 204,
"ann": {
"speaker": "director",
"kind": "dialogue",
"emotion": "neutral",
"location": "stage",
"time_of_day": "day",
"on_stage": [
{
"character": "director",
"position": "left"
}
]
}
},
{
"id": "talk_0006",
"kind": "verse",
"speaker": "director",
"speaker_note": null,
"speech": 0,
"stanza": 0,
"indent": 0,
"text": "al público dar gusto:",
"src_line": 205,
"ann": {
"speaker": "director",
"kind": "dialogue",
"emotion": "neutral",
"location": "stage",
"time_of_day": "day",
"on_stage": [
{
"character": "director",
"position": "left"
}
]
}
},
{
"id": "talk_0007",
"kind": "verse",
"speaker": "director",
"speaker_note": null,
"speech": 0,
"stanza": 0,
"indent": 0,
"text": "lo \"mejor\" que pueda.",
"src_line": 206,
"ann": {
"speaker": "director",
"kind": "dialogue",
"emotion": "neutral",
"location": "stage",
"time_of_day": "day",
"on_stage": [
{
"character": "director",
"position": "left"
}
]
}
},
{
"id": "talk_0008",
"kind": "verse",
"speaker": "poet",
"speaker_note": null,
"speech": 1,
"stanza": 0,
"indent": 26,
"text": "¡Vete, profano!",
"src_line": 207,
"ann": {
"speaker": "poet",
"kind": "dialogue",
"emotion": "angry",
"location": "stage",
"time_of_day": "day",
"on_stage": [
{
"character": "director",
"position": "left"
},
{
"character": "poet",
"position": "right"
}
]
}
},
{
"id": "talk_0009",
"kind": "verse",
"speaker": "director",
"speaker_note": null,
"speech": 2,
"stanza": 0,
"indent": 20,
"text": "Calla, que oye.",
"src_line": 208,
"ann": {
"speaker": "director",
"kind": "dialogue",
"emotion": "neutral",
"location": "stage",
"time_of_day": "day",
"on_stage": [
{
"character": "director",
"position": "left"
},
{
"character": "poet",
"position": "right"
}
]
}
},
{
"id": "talk_0010",
"kind": "direction",
"speaker": null,
"speaker_note": null,
"speech": 2,
"stanza": 0,
"indent": 0,
"text": "Se aleja.",
"src_line": 209,
"ann": {
"speaker": "narrator",
"kind": "stage_direction",
"emotion": "neutral",
"location": "stage",
"time_of_day": "day",
"on_stage": [
{
"character": "director",
"position": "left"
},
{
"character": "poet",
"position": "right"
}
]
}
},
{
"id": "talk_0011",
"kind": "verse",
"speaker": "poet",
"speaker_note": null,
"speech": 3,
"stanza": 0,
"indent": 0,
"text": "Mi pecho se oprime",
"src_line": 210,
"ann": {
"speaker": "poet",
"kind": "dialogue",
"emotion": "melancholic",
"location": "stage",
"time_of_day": "day",
"on_stage": [
{
"character": "poet",
"position": "center"
}
]
}
},
{
"id": "talk_0012",
"kind": "verse",
"speaker": "poet",
"speaker_note": null,
"speech": 3,
"stanza": 0,
"indent": 0,
"text": "bajo tanto peso,",
"src_line": 211,
"ann": {
"speaker": "poet",
"kind": "dialogue",
"emotion": "melancholic",
"location": "stage",
"time_of_day": "day",
"on_stage": [
{
"character": "poet",
"position": "center"
}
]
}
},
{
"id": "talk_0013",
"kind": "verse",
"speaker": "poet",
"speaker_note": null,
"speech": 3,
"stanza": 0,
"indent": 0,
"text": "y el ocaso llega.",
"src_line": 212,
"ann": {
"speaker": "poet",
"kind": "dialogue",
"emotion": "melancholic",
"location": "stage",
"time_of_day": "day",
"on_stage": [
{
"character": "poet",
"position": "center"
}
]
}
},
{
"id": "talk_0014",
"kind": "verse",
"speaker": "lord",
"speaker_note": null,
"speech": 4,
"stanza": 0,
"indent": 0,
"text": "¡Mi siervo!",
"src_line": 213,
"ann": {
"speaker": "lord",
"kind": "dialogue",
"emotion": "neutral",
"location": "stage",
"time_of_day": "day",
"on_stage": [
{
"character": "poet",
"position": "right"
},
{
"character": "lord",
"position": "center"
}
],
"music": "none"
}
},
{
"id": "talk_0015",
"kind": "verse",
"speaker": "lord",
"speaker_note": null,
"speech": 4,
"stanza": 0,
"indent": 0,
"text": "Tentarlo puedes.",
"src_line": 214,
"ann": {
"speaker": "lord",
"kind": "dialogue",
"emotion": "neutral",
"location": "stage",
"time_of_day": "day",
"on_stage": [
{
"character": "poet",
"position": "right"
},
{
"character": "lord",
"position": "center"
}
]
}
},
{
"id": "talk_0016",
"kind": "verse",
"speaker": "director",
"speaker_note": null,
"speech": 5,
"stanza": 0,
"indent": 0,
"text": "Basta ya de charla.",
"src_line": 215,
"ann": {
"speaker": "director",
"kind": "dialogue",
"emotion": "neutral",
"location": "stage",
"time_of_day": "day",
"on_stage": [
{
"character": "director",
"position": "left"
},
{
"character": "poet",
"position": "right"
}
]
}
},
{
"id": "talk_0017",
"kind": "verse",
"speaker": null,
"speaker_note": null,
"speech": 6,
"stanza": 0,
"indent": 0,
"text": "Callan los pájaros;",
"src_line": 216,
"ann": {
"speaker": "poet_voice",
"kind": "narration",
"emotion": "neutral",
"location": "stage",
"time_of_day": "day",
"on_stage": []
}
},
{
"id": "talk_0018",
"kind": "verse",
"speaker": null,
"speaker_note": null,
"speech": 6,
"stanza": 0,
"indent": 0,
"text": "la noche cae.",
"src_line": 217,
"ann": {
"speaker": "poet_voice",
"kind": "narration",
"emotion": "neutral",
"location": "stage",
"time_of_day": "day",
"on_stage": []
}
},
{
"id": "talk_0019",
"kind": "verse",
"speaker": "poet",
"speaker_note": null,
"speech": 7,
"stanza": 0,
"indent": 0,
"text": "Despierto.",
"src_line": 218,
"ann": {
"speaker": "poet",
"kind": "dialogue",
"emotion": "angry",
"location": "stage",
"time_of_day": "day",
"on_stage": [
{
"character": "director",
"position": "left"
},
{
"character": "poet",
"position": "right"
}
]
}
}
]
}
]
}
+103
View File
@@ -0,0 +1,103 @@
The Project Gutenberg eBook of Fausto
*** START OF THE PROJECT GUTENBERG EBOOK FAUSTO ***
DEDICATORIA ................................................ 17
TEODORO LLORENTE.
DEDICATORIA
Tornáis de nuevo, hermosas imágenes flotantes,
que dulce y melancólico un día contemplé.
¿Asiros y teneros podré feliz como antes?
¡Aún vuela hacia vosotras el alma cuando os ve!
Hoy vuelven de otro tiempo mejor la alegre historia,
y las risueñas sombras de la feliz edad,
[Ilustración]
[Ilustración]
PRÓLOGO EN EL TEATRO
EL DIRECTOR, EL POETA DRAMÁTICO, EL GRACIOSO
EL DIRECTOR
Decid, buenos amigos,
de mi afán camaradas y testigos,
¿qué pensáis? Es mi anhelo preferente
En complacer al público soy ducho;
mas tranquilo no estoy, no estoy sereno:
EL POETA
¡Vete, profano!
¡Vete! Romper mi servidumbre quiero.
[Ilustración]
PRÓLOGO EN EL CIELO
EL SEÑOR,
_los_ EJÉRCITOS CELESTIALES. _Después_ MEFISTÓFELES.
_Los tres_ ARCÁNGELES _se adelantan_
EL SEÑOR
¿Conoces a Fausto?
MEFISTÓFELES
¿A Fausto
el Doctor?
EL SEÑOR
¡Mi siervo!
(_El cielo se cierra y los Arcángeles se dispersan._)
MEFISTÓFELES, _solo_
De vez en cuando olvido mis rencillas,
y busco al Viejo, y pláticas entablo.
DE NOCHE
_En un aposento gótico, estrecho, con elevada bóveda_, FAUSTO
_intranquilo sentado a su pupitre._
FAUSTO
Filosofía, ¡ay, Dios!, Jurisprudencia,
Medicina además, y Teología,
la _Razón_ lo nombra
(_Toma el libro y pronuncia misteriosamente el nombre del Espíritu.
Enciéndese una luz rojiza y trémula. El Espíritu aparece en ella._)
EL ESPÍRITU
¿Quién me llama?
FAUSTO (_aterrado_)
¿No a ti? Pues dime: ¿a quién? ¿Imagen
soy de Dios, y ni a ti llegar podría?
(_Llaman._)
WAGNER
Not in scope.
*** END OF THE PROJECT GUTENBERG EBOOK FAUSTO ***
+61
View File
@@ -0,0 +1,61 @@
# Minimal work used by tests/test_renpy_gen.py (no assets: the generator falls back to placeholders).
[work]
id = "mini"
title = "Mini"
subtitle = "Fixture work"
author = "A. Author"
translator = "T. Translator"
language = "es"
[cast.narrator]
name = ""
color = "#d8cfc0"
[cast.poet_voice]
name = ""
color = "#e8dcc2"
sprite = false
[cast.director]
name = "El Director"
color = "#c9a25b"
sprite = true
expressions = { neutral = "neutral", joyful = "pleased", angry = "worried" }
[cast.poet]
name = "El Poeta"
color = "#8fa8c8"
sprite = true
expressions = { neutral = "neutral", melancholic = "neutral", angry = "indignant" }
[cast.lord]
name = "El Señor"
color = "#fff4c8"
sprite = false
[staging.lyric]
bg = "bg_dedication"
mode = "nvl"
[staging.talk]
bg = "bg_theatre"
mode = "adv"
[[cues]]
at = "talk_0014"
bg = "bg_heaven"
transition = "slow"
tint = "dark"
hide_all = true
[[cues]]
at = "talk_0016"
mode = "nvl"
[[cues]]
at = "talk_0019"
bg = "bg_theatre"
transition = "flash"
tint = "none"
mode = "adv"
shake = true
+376
View File
@@ -0,0 +1,376 @@
import json
from pathlib import Path
import pytest
from vnpipe import annotate
from vnpipe.cli import main
from vnpipe.config import Work, load_work
WORK_TOML = """
[work]
id = "t"
lyric_voice = "voice"
[[scenes]]
heading = "ONE"
id = "one"
location = "hall"
time_of_day = "day"
[[scenes]]
heading = "TWO"
id = "two"
location = "yard"
time_of_day = "night"
[cast.narrator]
name = ""
[cast.voice]
name = ""
sprite = false
[cast.alice]
name = "Alice"
sprite = true
[cast.bob]
name = "Bob"
sprite = true
[cast.god]
name = "God"
sprite = false
"""
def _line(scene, n, speech, stanza=0, kind="verse", speaker="alice", note=None):
return {
"id": f"{scene}_{n:04d}",
"kind": kind,
"speaker": speaker if kind == "verse" else None,
"speaker_note": note,
"speech": speech,
"stanza": stanza,
"indent": 0,
"text": f"text {scene} {n}",
"src_line": n + 1,
}
def _scene_lines(scene, speeches):
"""speeches: list of (speaker, line count)."""
lines = []
for si, (speaker, count) in enumerate(speeches):
for _ in range(count):
lines.append(_line(scene, len(lines) + 1, si, speaker=speaker))
return lines
def make_work(tmp_path: Path, parsed_scenes) -> Work:
root = tmp_path / "work"
(root / "data").mkdir(parents=True, exist_ok=True)
(root / "work.toml").write_text(WORK_TOML, encoding="utf-8")
parsed = {"work": "t", "source_sha256": "b" * 64, "scenes": parsed_scenes}
(root / "data/parsed.json").write_text(json.dumps(parsed), encoding="utf-8")
return load_work(root)
@pytest.fixture
def work(tmp_path):
one = _scene_lines("one", [("alice", 3), ("bob", 2)])
one.insert(0, _line("one", 0, 0, kind="cast"))
one.insert(2, _line("one", 99, 0, kind="direction"))
two = [_line("two", i + 1, 0, speaker=None) for i in range(2)]
scenes = [
{"id": "one", "heading": "ONE", "lines": one},
{"id": "two", "heading": "TWO", "lines": two},
]
return make_work(tmp_path, scenes)
def chunks_of(work):
parsed, _ = annotate.load_parsed(work)
return annotate.build_chunks(work, parsed)
def good_cache(work, chunk, **line_over):
anns = []
for line in chunk["lines"]:
anns.append(
{
"id": line["id"],
**line["defaults"],
"emotion": "joyful",
"on_stage": [{"character": "alice", "position": "left"}],
"music": None,
}
)
doc = {
"chunk_id": chunk["chunk_id"],
"input_sha256": chunk["input_sha256"],
"annotations": anns,
}
return doc
def put_cache(work, doc):
path = annotate.cache_dir(work) / f"{doc['chunk_id']}.json"
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(doc), encoding="utf-8")
def fill_all(work):
for chunk in chunks_of(work):
put_cache(work, good_cache(work, chunk))
# ---------------------------------------------------------------- chunking
def test_defaults_and_content(work):
one, two = chunks_of(work)
assert [c["chunk_id"] for c in (one, two)] == ["one_c01", "two_c01"]
by_id = {ln["id"]: ln for ln in one["lines"]}
assert by_id["one_0000"]["defaults"] == {
"speaker": "narrator",
"kind": "stage_direction",
"location": "hall",
"time_of_day": "day",
}
assert by_id["one_0099"]["defaults"]["kind"] == "stage_direction"
assert by_id["one_0001"]["defaults"]["speaker"] == "alice"
assert by_id["one_0001"]["defaults"]["kind"] == "dialogue"
# Unattributed verse -> narration spoken by the lyric voice
assert two["lines"][0]["defaults"] == {
"speaker": "voice",
"kind": "narration",
"location": "yard",
"time_of_day": "night",
}
allowed = one["allowed"]
assert allowed["characters"] == ["alice", "bob", "god"]
assert "narrator" in allowed["speakers"] and "voice" in allowed["speakers"]
assert allowed["locations"] == ["hall", "yard"]
assert "neutral" in allowed["emotions"] and "left" in allowed["positions"]
assert one["context_before"] == []
assert one["prompt_version"] == annotate.prompt_version()
def test_never_crosses_scenes_and_respects_limit(tmp_path):
scenes = [
{"id": "one", "heading": "ONE", "lines": _scene_lines("one", [("alice", 30)] * 5)},
{"id": "two", "heading": "TWO", "lines": _scene_lines("two", [("bob", 7)])},
]
work = make_work(tmp_path, scenes)
chunks = chunks_of(work)
assert [c["chunk_id"] for c in chunks] == ["one_c01", "one_c02", "one_c03", "two_c01"]
for chunk in chunks:
assert len(chunk["lines"]) <= 60
assert {ln["id"].rsplit("_", 1)[0] for ln in chunk["lines"]} == {chunk["scene"]["id"]}
assert [len(c["lines"]) for c in chunks] == [60, 60, 30, 7]
def test_splits_at_speech_boundaries(tmp_path):
speeches = [("alice", 25), ("bob", 25), ("alice", 25), ("bob", 10)]
work = make_work(
tmp_path, [{"id": "one", "heading": "O", "lines": _scene_lines("one", speeches)}]
)
chunks = chunks_of(work)
assert [len(c["lines"]) for c in chunks] == [50, 35]
assert chunks[1]["lines"][0]["id"] == "one_0051"
assert len(chunks[1]["context_before"]) == 6
assert chunks[1]["context_before"][-1]["id"] == "one_0050"
def test_oversized_speech_splits_at_stanza_then_hard(tmp_path):
lines = [_line("one", i + 1, 0, stanza=i // 50) for i in range(100)] # two stanzas of 50
work = make_work(tmp_path, [{"id": "one", "heading": "O", "lines": lines}])
assert [len(c["lines"]) for c in chunks_of(work)] == [50, 50]
lines = [_line("one", i + 1, 0, stanza=0) for i in range(130)]
work = make_work(tmp_path, [{"id": "one", "heading": "O", "lines": lines}])
assert [len(c["lines"]) for c in chunks_of(work)] == [60, 60, 10]
def test_hash_deterministic_and_content_sensitive(work, tmp_path):
first = [c["input_sha256"] for c in chunks_of(work)]
assert first == [c["input_sha256"] for c in chunks_of(work)]
parsed, _ = annotate.load_parsed(work)
parsed["scenes"][0]["lines"][1]["text"] = "changed"
changed = annotate.build_chunks(work, parsed)
assert changed[0]["input_sha256"] != first[0]
assert changed[1]["input_sha256"] == first[1]
def test_prompt_change_invalidates_hash(work, monkeypatch, tmp_path):
before = chunks_of(work)[0]["input_sha256"]
fake = tmp_path / "prompt.md"
fake.write_text("different prompt", encoding="utf-8")
monkeypatch.setattr(annotate, "PROMPT_PATH", fake)
assert chunks_of(work)[0]["input_sha256"] != before
def test_chunk_command_writes_and_removes_stale(work, capsys):
assert main(["--work", str(work.root), "annotate", "chunk"]) == 0
out = annotate.chunks_dir(work)
assert sorted(p.name for p in out.glob("*.json")) == ["one_c01.json", "two_c01.json"]
(out / "gone_c09.json").write_text("{}", encoding="utf-8")
snapshot = (out / "one_c01.json").read_bytes()
main(["--work", str(work.root), "annotate", "chunk"])
assert not (out / "gone_c09.json").exists()
assert (out / "one_c01.json").read_bytes() == snapshot
assert json.loads(snapshot)["chunk_id"] == "one_c01"
assert "removed stale gone_c09.json" in capsys.readouterr().out
def test_unconfigured_scene_or_speaker_fails(tmp_path):
scenes = [{"id": "zzz", "heading": "Z", "lines": [_line("zzz", 1, 0)]}]
with pytest.raises(annotate.AnnotateError):
chunks_of(make_work(tmp_path, scenes))
scenes = [{"id": "one", "heading": "O", "lines": [_line("one", 1, 0, speaker="ghost")]}]
with pytest.raises(annotate.AnnotateError):
chunks_of(make_work(tmp_path / "b", scenes))
# ---------------------------------------------------------------- status / merge
def test_status_states(work, capsys):
one, two = chunks_of(work)
assert annotate.check_cache(work, one)[0] == "missing"
put_cache(work, good_cache(work, one))
assert annotate.check_cache(work, one) == ("ok", [])
bad = good_cache(work, two)
bad["input_sha256"] = "c" * 64
put_cache(work, bad)
assert annotate.check_cache(work, two)[0] == "stale"
(annotate.cache_dir(work) / "two_c01.json").write_text("{nope", encoding="utf-8")
assert annotate.check_cache(work, two)[0] == "invalid"
assert main(["--work", str(work.root), "annotate", "status"]) == 0
out = capsys.readouterr().out
assert "one_c01: ok" in out and "two_c01: invalid" in out
assert "summary: 2 chunks: 1 ok, 0 missing, 0 stale, 1 invalid" in out
def merge_main(work, *extra):
return main(["--work", str(work.root), "annotate", "merge", *extra])
def test_merge_ok_and_idempotent(work, capsys):
fill_all(work)
assert merge_main(work) == 0
out = work.path("data/annotated.json")
first = out.read_bytes()
assert merge_main(work) == 0
assert out.read_bytes() == first
doc = json.loads(first)
assert doc["fallback_chunks"] == []
assert doc["parsed_sha256"] and doc["work"] == "t"
line = doc["scenes"][0]["lines"][0]
assert line["id"] == "one_0000" and line["text"] and line["ann"]["emotion"] == "joyful"
assert "id" not in line["ann"] and line["ann"]["music"] is None
assert first.endswith(b"\n")
def break_cache(work, mutate):
chunk = chunks_of(work)[0]
doc = good_cache(work, chunk)
mutate(doc)
path = annotate.cache_dir(work) / "one_c01.json"
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(doc), encoding="utf-8")
@pytest.mark.parametrize(
("mutate", "expect"),
[
(lambda d: d.update(input_sha256="d" * 64), "stale"),
(lambda d: d["annotations"].pop(), "missing lines"),
(lambda d: d["annotations"].reverse(), "not in chunk order"),
(lambda d: d["annotations"][1].update(kind="narration"), "kind is 'narration'"),
(lambda d: d["annotations"][1].update(speaker="bob"), "speaker is 'bob'"),
(lambda d: d["annotations"][1].update(location="yard"), "location is 'yard'"),
(lambda d: d["annotations"][1].update(time_of_day="dawn"), "time_of_day is 'dawn'"),
(
lambda d: d["annotations"][1].update(
on_stage=[{"character": "zed", "position": "left"}]
),
"unknown character 'zed'",
),
(
lambda d: d["annotations"][1].update(
on_stage=[
{"character": "bob", "position": "left"},
{"character": "bob", "position": "right"},
]
),
"more than once",
),
(
lambda d: d["annotations"][1].update(
on_stage=[{"character": "narrator", "position": "left"}]
),
"unknown character 'narrator'",
),
(lambda d: d["annotations"][1].update(emotion="happy"), "schema"),
(lambda d: d.update(chunk_id="two_c01"), "chunk_id"),
],
)
def test_merge_rejects_bad_cache(work, capsys, mutate, expect):
two = chunks_of(work)[1]
put_cache(work, good_cache(work, two))
break_cache(work, mutate)
assert merge_main(work) == 1
err = capsys.readouterr().err
assert "one_c01" in err and expect in err
assert not work.path("data/annotated.json").exists()
def test_merge_without_cache_lists_all_problems(work, capsys):
assert merge_main(work) == 1
err = capsys.readouterr().err
assert "one_c01: missing" in err and "two_c01: missing" in err
def test_merge_fallback(work, capsys):
put_cache(work, good_cache(work, chunks_of(work)[1]))
assert merge_main(work, "--fallback") == 0
captured = capsys.readouterr()
assert "warning: one_c01: missing" in captured.err
doc = json.loads(work.path("data/annotated.json").read_text(encoding="utf-8"))
assert doc["fallback_chunks"] == ["one_c01"]
lines = {ln["id"]: ln["ann"] for s in doc["scenes"] for ln in s["lines"]}
# cast/direction line before anyone spoke: nobody on stage
assert lines["one_0000"]["on_stage"] == []
assert lines["one_0000"]["emotion"] == "neutral" and lines["one_0000"]["music"] is None
# alice speaks first -> left; bob joins -> right, alice stays
assert lines["one_0001"]["on_stage"] == [{"character": "alice", "position": "left"}]
assert lines["one_0005"]["on_stage"] == [
{"character": "alice", "position": "left"},
{"character": "bob", "position": "right"},
]
# the ok chunk is kept as annotated by the LLM
assert lines["two_0001"]["emotion"] == "joyful"
first = work.path("data/annotated.json").read_bytes()
merge_main(work, "--fallback")
assert work.path("data/annotated.json").read_bytes() == first
def test_fallback_skips_characters_without_sprite(tmp_path):
lines = [_line("one", 1, 0, speaker="god"), _line("one", 2, 1, speaker="alice")]
work = make_work(tmp_path, [{"id": "one", "heading": "O", "lines": lines}])
result = annotate.merge(work, fallback=True)
anns = [ln["ann"] for ln in result.document["scenes"][0]["lines"]]
assert anns[0]["on_stage"] == []
assert anns[1]["on_stage"] == [{"character": "alice", "position": "left"}]
# ---------------------------------------------------------------- prompt
def test_prompt_fills_placeholders(work):
text = annotate.render_prompt(work, "one_c01")
assert "{{" not in text
root = work.root.resolve()
assert str(root / "annotations/chunks/one_c01.json") in text
assert str(root / "annotations/cache/one_c01.json") in text
assert "annotate status one_c01" in text
with pytest.raises(SystemExit):
annotate.render_prompt(work, "nope_c01")
+150
View File
@@ -0,0 +1,150 @@
import copy
import json
import pytest
from vnpipe import SCHEMA_DIR
from vnpipe.schema import SchemaError, validate
SHA = "a" * 64
def _ann(**over):
ann = {
"id": "s_0001",
"speaker": "faust",
"kind": "dialogue",
"emotion": "neutral",
"location": "study",
"time_of_day": "night",
"on_stage": [{"character": "faust", "position": "left"}],
"music": None,
}
ann.update(over)
return ann
def _cache(**over):
doc = {"chunk_id": "s_c01", "input_sha256": SHA, "annotations": [_ann()]}
doc.update(over)
return doc
def _load(name):
return json.loads((SCHEMA_DIR / f"{name}.schema.json").read_text(encoding="utf-8"))
def test_valid_annotation_cache():
validate(_cache(), "annotation")
def test_music_is_optional():
ann = _ann()
del ann["music"]
validate(_cache(annotations=[ann]), "annotation")
@pytest.mark.parametrize("key", ["chunk_id", "input_sha256", "annotations"])
def test_cache_required_fields(key):
doc = _cache()
del doc[key]
with pytest.raises(SchemaError):
validate(doc, "annotation")
@pytest.mark.parametrize(
"key", ["id", "speaker", "kind", "emotion", "location", "time_of_day", "on_stage"]
)
def test_annotation_required_fields(key):
ann = _ann()
del ann[key]
with pytest.raises(SchemaError):
validate(_cache(annotations=[ann]), "annotation")
@pytest.mark.parametrize(
"over",
[
{"emotion": "happy"},
{"kind": "verse"},
{"time_of_day": "noon"},
{"music": "loud"},
{"extra": 1},
{"on_stage": [{"character": "faust", "position": "top"}]},
{"on_stage": [{"character": "faust"}]},
{"on_stage": [{"character": "faust", "position": "left", "scale": 2}]},
],
)
def test_annotation_bad_values(over):
with pytest.raises(SchemaError):
validate(_cache(annotations=[_ann(**over)]), "annotation")
def test_cache_rejects_extra_field_and_bad_hash():
with pytest.raises(SchemaError):
validate(_cache(extra=1), "annotation")
with pytest.raises(SchemaError):
validate(_cache(input_sha256="xyz"), "annotation")
def _annotated():
ann = _ann()
del ann["id"]
line = {
"id": "s_0001",
"kind": "verse",
"speaker": "faust",
"speaker_note": None,
"speech": 0,
"stanza": 0,
"indent": 0,
"text": "Hola",
"src_line": 1,
"ann": ann,
}
return {
"work": "w",
"parsed_sha256": SHA,
"fallback_chunks": [],
"scenes": [{"id": "s", "heading": "H", "lines": [line]}],
}
def test_annotated_valid():
validate(_annotated(), "annotated")
def test_annotated_rejects_problems():
doc = _annotated()
del doc["scenes"][0]["lines"][0]["ann"]
with pytest.raises(SchemaError):
validate(doc, "annotated")
doc = _annotated()
doc["scenes"][0]["lines"][0]["ann"]["emotion"] = "happy"
with pytest.raises(SchemaError):
validate(doc, "annotated")
doc = _annotated()
doc["scenes"][0]["lines"][0]["ann"]["id"] = "s_0001"
with pytest.raises(SchemaError):
validate(doc, "annotated")
doc = _annotated()
del doc["fallback_chunks"]
with pytest.raises(SchemaError):
validate(doc, "annotated")
def test_annotated_definitions_match_source_schemas():
"""annotated.schema.json duplicates definitions from the other schemas; keep them in sync."""
annotated = _load("annotated")["$defs"]
source = _load("annotation")["$defs"]
expected = copy.deepcopy(source["annotation"])
expected["required"].remove("id")
del expected["properties"]["id"]
assert annotated["ann"] == expected
assert annotated["position"] == source["position"]
parsed_line = _load("parsed")["properties"]["scenes"]["items"]["properties"]["lines"]["items"]
line = copy.deepcopy(annotated["line"])
assert line["required"] == [*parsed_line["required"], "ann"]
del line["properties"]["ann"]
assert line["properties"] == parsed_line["properties"]
+393
View File
@@ -0,0 +1,393 @@
import json
import os
import subprocess
from pathlib import Path
import pytest
from vnpipe import cli, renpy_gen
from vnpipe.config import load_work
from vnpipe.schema import validate
ROOT = Path(__file__).resolve().parent.parent
FIXTURES = Path(__file__).parent / "fixtures"
SDK = Path(os.environ.get("RENPY_SDK") or ROOT / "tools/renpy-sdk") / "renpy.sh"
@pytest.fixture(scope="module")
def work():
return load_work(FIXTURES / "mini_work")
@pytest.fixture(scope="module")
def annotated():
data = json.loads((FIXTURES / "annotated_mini.json").read_text(encoding="utf-8"))
validate(data, "annotated")
return data
@pytest.fixture(scope="module")
def project(work, annotated, tmp_path_factory):
out = tmp_path_factory.mktemp("proj")
renpy_gen.generate(work, annotated, out)
return out
@pytest.fixture(scope="module")
def script(project) -> str:
return (project / "game/script.rpy").read_text(encoding="utf-8")
def scene_block(script: str, scene_id: str) -> list[str]:
lines = script.split("\n")
start = lines.index(f"label scene_{scene_id}:")
end = next((i for i in range(start + 1, len(lines)) if lines[i].startswith("label ")), None)
if end is None:
end = len(lines)
return [ln.strip() for ln in lines[start:end]]
def say_lines(block: list[str]) -> list[str]:
return [ln for ln in block if ln.startswith("c_")]
def test_escape_text():
assert renpy_gen.escape_text("a [b] {c}") == "a [[b] {{c}"
assert renpy_gen.escape_text('say "hi"\\') == 'say \\"hi\\"\\\\'
assert renpy_gen.escape_text("a\nb") == "a\\nb"
def test_escaping_in_script(script):
assert "¿qué pensáis [[ahora]?" in script
assert "Es mi {{anhelo} preferente" in script
assert 'lo \\"mejor\\" que pueda.' in script
def test_title_card_and_end(script):
block = scene_block(script, "talk")
assert "show card_talk at truecenter" in block
assert "hide card_talk" in block
assert "with fade" in block
assert "scene bg theatre at tint_none" in block
assert script.rstrip().endswith("return")
assert "show card_end at truecenter" in script and "label the_end:" in script
def test_nvl_pages_per_stanza(script):
block = scene_block(script, "lyric")
says = say_lines(block)
# 9-line stanza -> pages of 8 and 1, then the 2-line second stanza
assert [s.count("\\n") + 1 for s in says] == [8, 1, 2]
assert all(s.startswith("c_poet_voice_nvl ") for s in says)
assert block.count("nvl clear") == 3
assert block[-2:] == ["nvl hide dissolve", ""]
assert not any(ln.startswith("show ") and "vn_" in ln for ln in block)
def test_adv_grouping(script):
says = say_lines(scene_block(script, "talk"))
# director's 6 verse lines -> 4 + 2
assert says[0].count("\\n") == 3
assert says[1].count("\\n") == 1
assert says[0].startswith("c_director ")
# split lines (indent >= 6) get their own boxes
assert says[2] == 'c_poet "¡Vete, profano!"'
assert says[3] == 'c_director "Calla, que oye."'
# stage direction: narrator, own box
assert says[4] == 'c_narrator "Se aleja."'
# poet's 3 lines in one box
assert says[5].count("\\n") == 2
def test_cue_forces_box_break_and_emits_before_line(script):
block = scene_block(script, "talk")
cue_start = block.index("# talk_0014 .. talk_0015")
prefix = block[:cue_start]
# cue 1: slow bg change with dark tint and sprites hidden, before the Lord's lines
assert "show bg heaven at tint_dark" in prefix
assert prefix[prefix.index("show bg heaven at tint_dark") + 1] == "with vn_slow"
assert "hide poet" in prefix[-6:]
# Poet's box ended before the cue (box break at cue line)
assert any("y el ocaso llega." in ln for ln in prefix)
def test_mode_switch_and_flash_shake(script):
block = scene_block(script, "talk")
i_nvl = block.index("# talk_0016")
# nvl cue at 0016: sprites hidden (nothing changes the bg), director spoke in nvl mode
assert block[i_nvl + 1].startswith("c_director_nvl ")
assert "nvl clear" in block[i_nvl:]
# lyric voice lines in nvl are grouped into one page
pages = [ln for ln in block if ln.startswith("c_poet_voice_nvl")]
assert pages == ['c_poet_voice_nvl "Callan los pájaros;\\nla noche cae."']
# cue 3: leave nvl, flash + shake, tint reset
i_cue = block.index("# talk_0019")
assert block[i_cue - 4 : i_cue] == [
"nvl hide dissolve",
"show bg theatre at tint_none",
"with vn_flash",
"show layer master at vn_shake",
]
def test_expression_mapping(script):
block = scene_block(script, "talk")
# first line of the first box is joyful -> director "pleased"
assert "show director pleased at vn_left" in block
# poet angry -> indignant (split box); director stays pleased/neutral as per his own lines
assert "show poet indignant at vn_right" in block
# poet melancholic -> neutral
assert "show poet neutral at vn_right" in block
def test_stable_positions(script):
block = scene_block(script, "talk")
shows = [ln for ln in block if ln.startswith("show poet ")]
assert shows and all(ln.endswith("at vn_right") for ln in shows)
assert not any("vn_center" in ln for ln in block) # annotated centre was never used
def test_sprite_false_never_shown(script):
assert "show lord" not in script
assert "show poet_voice" not in script
assert "c_lord " in script # still speaks, with name and colour
def test_characters_and_images(project):
chars = (project / "game/characters.rpy").read_text(encoding="utf-8")
assert 'define c_director = Character("El Director", who_color="#c9a25b")' in chars
assert 'define c_director_nvl = Character("El Director", kind=nvl' in chars
assert "define c_narrator = Character(None, what_color=" in chars
assert "what_italic=True" in chars
nameless_nvl = next(ln for ln in chars.split("\n") if ln.startswith("define c_poet_voice_nvl"))
assert "None" in nameless_nvl and "nvl_thought" in nameless_nvl
images = (project / "game/images.rpy").read_text(encoding="utf-8")
assert 'image bg dedication = "images/bg/dedication.webp"' in images
assert 'image director pleased = "images/sprites/director_pleased.webp"' in images
assert (project / "game/images/sprites/poet_indignant.webp").is_file()
assert (project / "game/images/bg/theatre.webp").is_file()
assert not (project / "game/images/sprites/lord_neutral.webp").exists()
def test_title_card_images(project):
images = (project / "game/images.rpy").read_text(encoding="utf-8")
assert 'image card_talk = Text("CONVERSACIÓN", size=60, text_align=0.5)' in images
assert 'image card_end = Text("Continuará…"' in images
def test_options_substitution(project):
options = (project / "game/options.rpy").read_text(encoding="utf-8")
assert 'config.name = _("Mini")' in options
assert 'build.name = "mini-vn"' in options
assert "@@" not in options
gui = (project / "game/gui.rpy").read_text(encoding="utf-8")
assert 'gui.main_menu_background = "bg dedication"' in gui
assert (project / "game/gui/textbox.png").is_file()
assert (project / "game/fonts/RobotoSlab-Regular.ttf").is_file()
def test_music_only_when_audio_exists(work, annotated, tmp_path):
out = tmp_path / "p"
renpy_gen.generate(work, annotated, out)
assert "play music" not in (out / "game/script.rpy").read_text(encoding="utf-8")
(out / "game/audio").mkdir()
(out / "game/audio/sacred.ogg").write_bytes(b"OggS")
renpy_gen.generate(work, annotated, out)
text = (out / "game/script.rpy").read_text(encoding="utf-8")
assert 'play music "audio/sacred.ogg" fadeout 1.0 fadein 1.0' in text
assert "stop music fadeout 1.0" in text # mood "none" on the Lord's first line
assert (out / "game/audio/sacred.ogg").is_file() # regeneration keeps user audio
def test_unknown_cue_target_fails(work, annotated):
broken = json.loads(json.dumps(annotated))
broken["scenes"][1]["lines"] = broken["scenes"][1]["lines"][:5]
with pytest.raises(ValueError, match="unknown line ids"):
renpy_gen.render_script(work, broken, set())
def test_unknown_speaker_fails(work, annotated):
broken = json.loads(json.dumps(annotated))
broken["scenes"][1]["lines"][1]["ann"]["speaker"] = "ghost"
with pytest.raises(ValueError, match="ghost"):
renpy_gen.render_script(work, broken, set())
def tree(root: Path) -> dict[str, bytes]:
return {
str(p.relative_to(root)): p.read_bytes() for p in sorted(root.rglob("*")) if p.is_file()
}
def test_deterministic(work, annotated, tmp_path):
a, b = tmp_path / "a", tmp_path / "b"
renpy_gen.generate(work, annotated, a)
renpy_gen.generate(work, annotated, b)
renpy_gen.generate(work, annotated, b) # regenerating over an existing tree
assert tree(a) == tree(b)
@pytest.mark.skipif(not SDK.exists(), reason="Ren'Py SDK not found (set RENPY_SDK)")
def test_renpy_lint(work, annotated, tmp_path):
out = tmp_path / "mini"
renpy_gen.generate(work, annotated, out)
env = {**os.environ, "HOME": str(tmp_path / "home")}
(tmp_path / "home").mkdir()
result = subprocess.run(
[str(SDK), str(out), "lint"], capture_output=True, text=True, env=env, timeout=300
)
report = result.stdout + result.stderr
assert result.returncode == 0, report
assert "Traceback" not in report and "error" not in report.lower(), report
def _with_cfg(work, **changes):
data = json.loads(json.dumps(work.data))
for key, value in changes.items():
data[key] = value
return type(work)(root=work.root, data=data)
def test_pinned_cast(work, annotated):
data = json.loads(json.dumps(work.data))
data["staging"]["talk"]["cast"] = {"poet": "left", "director": "center"}
pinned = type(work)(root=work.root, data=data)
block = scene_block(renpy_gen.render_script(pinned, annotated, set()), "talk")
first_box = block.index("# talk_0002 .. talk_0005")
assert "show poet neutral at vn_left" in block[first_box:]
assert any(ln.startswith("show director") and ln.endswith("vn_center") for ln in block)
assert not any("vn_right" in ln for ln in block) # annotation position overridden
def test_stage_direction_keeps_on_stage(work, annotated):
ann = json.loads(json.dumps(annotated))
direction = next(ln for ln in ann["scenes"][1]["lines"] if ln["id"] == "talk_0010")
direction["ann"]["on_stage"] = []
block = scene_block(renpy_gen.render_script(work, ann, set()), "talk")
i = block.index('c_narrator "Se aleja."')
assert not any(ln.startswith("hide ") for ln in block[i - 3 : i])
def test_cue_move(work, annotated):
data = json.loads(json.dumps(work.data))
data["cues"][0]["move"] = {"poet": "left"}
moved = type(work)(root=work.root, data=data)
block = scene_block(renpy_gen.render_script(moved, annotated, set()), "talk")
# sprites are hidden by that cue's hide_all, so nothing to slide; position is updated
assert "with vn_move" not in block
data["cues"][0].pop("hide_all")
data["cues"][0]["move"] = {"poet": "left"}
moved = type(work)(root=work.root, data=data)
block = scene_block(renpy_gen.render_script(moved, annotated, set()), "talk")
i = block.index("with vn_move")
assert block[i - 1].startswith("show poet ") and block[i - 1].endswith("vn_left")
def test_overrides(work, annotated):
ov = [{"from": "talk_0011", "to": "talk_0013", "emotion": "angry"}]
block = scene_block(
renpy_gen.render_script(_with_cfg(work, overrides=ov), annotated, set()), "talk"
)
assert "show poet indignant at vn_right" in block[block.index("# talk_0011 .. talk_0013") :]
@pytest.mark.parametrize(
"change, match",
[
({"overrides": [{"from": "talk_0011", "to": "nope", "emotion": "angry"}]}, "unknown line"),
({"overrides": [{"from": "talk_0011", "to": "talk_0012", "emotion": "mad"}]}, "emotion"),
({"overrides": [{"from": "talk_0011", "to": "lyric_0001", "emotion": "angry"}]}, "range"),
({"overrides": [{"from": "talk_0012", "to": "talk_0011", "emotion": "angry"}]}, "range"),
],
)
def test_invalid_overrides(work, annotated, change, match):
with pytest.raises(ValueError, match=match):
renpy_gen.render_script(_with_cfg(work, **change), annotated, set())
def test_invalid_staging_cast_and_move(work, annotated):
data = json.loads(json.dumps(work.data))
data["staging"]["talk"]["cast"] = {"ghost": "left"}
with pytest.raises(ValueError, match="ghost"):
renpy_gen.render_script(type(work)(root=work.root, data=data), annotated, set())
data = json.loads(json.dumps(work.data))
data["staging"]["talk"]["cast"] = {"poet": "up"}
with pytest.raises(ValueError, match="position"):
renpy_gen.render_script(type(work)(root=work.root, data=data), annotated, set())
data = json.loads(json.dumps(work.data))
data["cues"][0]["move"] = {"poet": "nowhere"}
with pytest.raises(ValueError, match="position"):
renpy_gen.render_script(type(work)(root=work.root, data=data), annotated, set())
def test_every_gui_image_exists(project):
"""Every gui/... path the template screens reference resolves to a shipped file."""
import re
game = project / "game"
text = "".join((game / n).read_text(encoding="utf-8") for n in ("gui.rpy", "screens.rpy"))
text = "\n".join(ln for ln in text.split("\n") if not ln.lstrip().startswith("#"))
refs = set(re.findall(r'"(gui/[^"]+\.png)"', text))
assert len(refs) > 20
missing = []
for ref in sorted(refs):
# Ren'Py's prefix search ends with the un-prefixed name
candidates = [ref.replace("[prefix_]", "")]
if ref.endswith("confirm_frame.png"):
candidates.append("gui/frame.png") # listed fallback in screens.rpy
if not any((game / c).is_file() for c in candidates):
missing.append(ref)
assert not missing
# button_properties() backgrounds fall back to gui/button/background.png
assert (game / "gui/button/background.png").is_file()
assert (game / "gui/phone/button/background.png").is_file()
def test_with_test_flag(work, annotated, tmp_path):
plain, tested = tmp_path / "a", tmp_path / "b"
renpy_gen.generate(work, annotated, plain)
renpy_gen.generate(work, annotated, tested, with_test=True)
assert not (plain / "game/e2e_test.rpy").exists()
assert "testcase default" in (tested / "game/e2e_test.rpy").read_text(encoding="utf-8")
renpy_gen.generate(work, annotated, tested) # flag off removes it again
assert not (tested / "game/e2e_test.rpy").exists()
def run_e2e(project: Path, home: Path) -> str:
home.mkdir(exist_ok=True)
for name in ("traceback.txt", "errors.txt"):
(project / name).unlink(missing_ok=True)
env = {
**os.environ,
"HOME": str(home),
"SDL_VIDEODRIVER": "dummy",
"SDL_AUDIODRIVER": "dummy",
"RENPY_RENDERER": "sw",
}
result = subprocess.run(
[str(SDK), str(project), "test"], capture_output=True, text=True, env=env, timeout=900
)
report = result.stdout + result.stderr
for name in ("traceback.txt", "errors.txt"):
assert not (project / name).exists(), (project / name).read_text(encoding="utf-8")
assert result.returncode == 0, report
assert "Traceback" not in report and "FAIL" not in report, report
return report
@pytest.mark.skipif(not SDK.exists(), reason="Ren'Py SDK not found (set RENPY_SDK)")
def test_e2e_playthrough_mini(work, annotated, tmp_path):
out = tmp_path / "mini"
renpy_gen.generate(work, annotated, out, with_test=True)
run_e2e(out, tmp_path / "home")
def test_cli_defaults_to_current_directory(work, tmp_path, monkeypatch):
import shutil
shutil.copytree(FIXTURES / "mini_work", tmp_path / "w")
(tmp_path / "w/data").mkdir()
shutil.copy(FIXTURES / "annotated_mini.json", tmp_path / "w/data/annotated.json")
monkeypatch.chdir(tmp_path / "w")
assert cli.main(["renpy"]) == 0
assert (tmp_path / "w/vn/game/script.rpy").is_file()
+27
View File
@@ -0,0 +1,27 @@
import pytest
from vnpipe.schema import SchemaError, validate
def test_valid_instance_passes():
validate(
{
"work": "x",
"source_sha256": "a" * 64,
"scenes": [{"id": "s", "heading": "H", "lines": []}],
},
"parsed",
)
def test_reports_all_problems():
with pytest.raises(SchemaError) as exc:
validate({"work": 1, "source_sha256": "bad", "scenes": []}, "parsed")
message = str(exc.value)
assert "3 problem(s)" in message
assert "/work" in message and "/source_sha256" in message and "/scenes" in message
def test_unknown_schema():
with pytest.raises(FileNotFoundError):
validate({}, "nope")
+192
View File
@@ -0,0 +1,192 @@
import json
from pathlib import Path
import pytest
from vnpipe import text
from vnpipe.schema import validate
FIXTURE = Path(__file__).parent / "fixtures" / "mini_raw.txt"
CFG = {
"work": {"id": "mini"},
"scope": {"start_marker": "DEDICATORIA", "end_marker": "(_Llaman._)", "end_occurrence": 1},
"speakers": {
"EL DIRECTOR": "director",
"EL POETA": "poet",
"MEFISTÓFELES": "mephisto",
"EL SEÑOR": "lord",
"FAUSTO": "faust",
"EL ESPÍRITU": "spirit",
},
"scenes": [
{"heading": "DEDICATORIA", "id": "dedicatoria"},
{"heading": "PRÓLOGO EN EL TEATRO", "id": "prologo_teatro"},
{"heading": "PRÓLOGO EN EL CIELO", "id": "prologo_cielo"},
{"heading": "DE NOCHE", "id": "noche"},
],
}
SHA = "0" * 64
@pytest.fixture(scope="module")
def raw() -> str:
return FIXTURE.read_text(encoding="utf-8")
@pytest.fixture(scope="module")
def parsed(raw):
return text.parse(text.clean(raw, CFG["scope"]), CFG, SHA)
def scene(parsed, scene_id):
return next(s for s in parsed["scenes"] if s["id"] == scene_id)
def test_scope_cut(raw):
lines = text.clean(raw, CFG["scope"])
joined = "\n".join(t for _, t in lines)
assert lines[0][1] == "DEDICATORIA"
assert lines[0][0] == 8 # first whole-line match, not the indented TOC entry
assert "Gutenberg" not in joined
assert "TEODORO LLORENTE" not in joined
assert "Llaman" not in joined
assert "WAGNER" not in joined
assert "Ilustración" not in joined
assert "\n\n\n" not in joined
def test_scope_missing_marker(raw):
with pytest.raises(text.ParseError):
text.clean(raw, {**CFG["scope"], "start_marker": "NOPE"})
with pytest.raises(text.ParseError):
text.clean(raw, {**CFG["scope"], "end_occurrence": 5})
def test_crlf_is_normalised(raw):
crlf = raw.replace("\n", "\r\n")
assert text.clean(crlf, CFG["scope"]) == text.clean(raw, CFG["scope"])
def test_scenes_in_order_with_ids(parsed):
assert [s["id"] for s in parsed["scenes"]] == [
"dedicatoria",
"prologo_teatro",
"prologo_cielo",
"noche",
]
first = scene(parsed, "noche")["lines"][0]
assert first["id"] == "noche_0001"
def test_dedicatoria_has_no_speaker(parsed):
lines = scene(parsed, "dedicatoria")["lines"]
assert all(ln["speaker"] is None and ln["kind"] == "verse" for ln in lines)
assert [ln["stanza"] for ln in lines] == [0, 0, 0, 0, 1, 1]
assert [ln["indent"] for ln in lines] == [2, 0, 0, 0, 2, 0]
def test_cast_list_detection(parsed):
teatro = scene(parsed, "prologo_teatro")["lines"][0]
assert teatro["kind"] == "cast"
assert teatro["text"] == "EL DIRECTOR, EL POETA DRAMÁTICO, EL GRACIOSO"
assert teatro["speaker"] is None
cielo = scene(parsed, "prologo_cielo")["lines"][0]
assert cielo["kind"] == "cast"
assert cielo["text"] == (
"EL SEÑOR, los EJÉRCITOS CELESTIALES. Después MEFISTÓFELES. "
"Los tres ARCÁNGELES se adelantan"
)
def test_setting_is_joined_direction(parsed):
first = scene(parsed, "noche")["lines"][0]
assert first["kind"] == "direction"
assert first["text"] == (
"En un aposento gótico, estrecho, con elevada bóveda, FAUSTO "
"intranquilo sentado a su pupitre."
)
def test_stanza_counting(parsed):
lines = [ln for ln in scene(parsed, "prologo_teatro")["lines"] if ln["speaker"] == "director"]
assert [ln["stanza"] for ln in lines] == [0, 0, 0, 1, 1]
assert {ln["speech"] for ln in lines} == {0}
def test_split_verse_indentation(parsed):
poet = [ln for ln in scene(parsed, "prologo_teatro")["lines"] if ln["speaker"] == "poet"]
assert poet[0]["indent"] == 26
assert poet[1]["indent"] == 0
assert poet[0]["speech"] == 1
def test_indented_speaker_heading(parsed):
lines = scene(parsed, "prologo_cielo")["lines"]
mephisto = [ln for ln in lines if ln["text"] in ("¿A Fausto", "el Doctor?")]
assert [ln["speaker"] for ln in mephisto] == ["mephisto", "mephisto"]
assert [ln["indent"] for ln in mephisto] == [19, 0]
assert [ln["speech"] for ln in lines if ln["speaker"]] == [0, 1, 1, 2, 3, 3]
def test_speaker_note(parsed):
solo = [ln for ln in scene(parsed, "prologo_cielo")["lines"] if ln["speaker_note"]]
assert {ln["speaker_note"] for ln in solo} == {"solo"}
assert {ln["speaker"] for ln in solo} == {"mephisto"}
noche = scene(parsed, "noche")["lines"]
terrified = [ln for ln in noche if ln["speaker_note"] == "aterrado"]
assert len(terrified) == 2
assert terrified[0]["speaker"] == "faust"
def test_multiline_stage_direction(parsed):
directions = [ln for ln in scene(parsed, "noche")["lines"] if ln["speaker"] is None][1:]
assert len(directions) == 1
assert directions[0]["kind"] == "direction"
assert directions[0]["text"] == (
"Toma el libro y pronuncia misteriosamente el nombre del Espíritu. "
"Enciéndese una luz rojiza y trémula. El Espíritu aparece en ella."
)
assert directions[0]["src_line"] == 86
inline = [ln for ln in scene(parsed, "prologo_cielo")["lines"] if ln["kind"] == "direction"]
assert inline[0]["text"] == "El cielo se cierra y los Arcángeles se dispersan."
def test_italics_stripped(parsed):
texts = [ln["text"] for ln in scene(parsed, "noche")["lines"]]
assert "la Razón lo nombra" in texts
assert not any("_" in t for s in parsed["scenes"] for t in (ln["text"] for ln in s["lines"]))
def test_src_lines_point_to_raw(raw, parsed):
raw_lines = raw.split("\n")
for s in parsed["scenes"]:
for ln in s["lines"]:
if ln["kind"] == "verse":
assert raw_lines[ln["src_line"] - 1].strip().replace("_", "") == ln["text"]
def test_unknown_speaker_fails(raw):
cfg = {**CFG, "speakers": {k: v for k, v in CFG["speakers"].items() if k != "FAUSTO"}}
with pytest.raises(text.ParseError, match="FAUSTO"):
text.parse(text.clean(raw, CFG["scope"]), cfg, SHA)
def test_unknown_scene_heading_fails(raw):
cfg = {**CFG, "scenes": CFG["scenes"][:3]}
with pytest.raises(text.ParseError, match="DE NOCHE"):
text.parse(text.clean(raw, CFG["scope"]), cfg, SHA)
def test_deterministic_and_schema_valid(raw, parsed):
again = text.parse(text.clean(raw, CFG["scope"]), CFG, SHA)
assert json.dumps(again) == json.dumps(parsed)
validate(parsed, "parsed")
def test_build_hashes_raw_bytes():
data = FIXTURE.read_bytes()
_, result = text.build(data, CFG)
import hashlib
assert result["source_sha256"] == hashlib.sha256(data).hexdigest()