feat: add deterministic text stage (fetch, scope cut, parser) with tests

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
dasemuandClaude Opus 5.5 committed 2026-10-17 09:46:10 +02:00
1 parent 10af4346f6
commit fdfe6d057e
9 files changed
+8589

No files matched your search

+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 ***
+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")
+229
View File
@@ -0,0 +1,229 @@
import argparse
import json
from pathlib import Path
import pytest
from vnpipe import text
from vnpipe.config import load_work
from vnpipe.schema import validate
ROOT = Path(__file__).resolve().parent.parent
FIXTURE = Path(__file__).parent / "fixtures" / "mini_raw.txt"
RAW = ROOT / "works/faust/data/raw/pg68566.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()
@pytest.mark.skipif(not RAW.is_file(), reason="raw Gutenberg file not downloaded")
def test_real_file_integration():
work = load_work(ROOT / "works/faust")
_, parsed = text.build(RAW.read_bytes(), work.data)
assert [s["id"] for s in parsed["scenes"]] == [
"dedicatoria",
"prologo_teatro",
"prologo_cielo",
"noche",
]
known = set(work.speakers.values())
for s in parsed["scenes"]:
assert s["lines"]
assert {ln["speaker"] for ln in s["lines"]} - {None} <= known
@pytest.mark.skipif(not RAW.is_file(), reason="raw Gutenberg file not downloaded")
def test_cli_parse_is_byte_identical(tmp_path):
import shutil
work_dir = tmp_path / "faust"
(work_dir / "data/raw").mkdir(parents=True)
shutil.copy(ROOT / "works/faust/work.toml", work_dir / "work.toml")
shutil.copy(RAW, work_dir / "data/raw/pg68566.txt")
args = argparse.Namespace(work=work_dir)
assert text.cmd_parse(args) == 0
first = (work_dir / "data/parsed.json").read_bytes()
assert text.cmd_parse(args) == 0
assert (work_dir / "data/parsed.json").read_bytes() == first
assert first.endswith(b"\n")
assert (work_dir / "data/play.txt").read_text(encoding="utf-8").startswith("DEDICATORIA\n")