feat(text): parse full-length plays (footnotes, repeated headings, prose, direction hints)

Drop footnote definitions/markers and multi-line illustrations, allow repeated
scene headings via 'occurrence', prose scenes via 'format', notes with addressees,
wrapped headings, parenthesised/italic directions and [parser] direction_headings.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
dasemuandClaude Opus 5.5 committed 2026-10-19 04:13:28 +02:00
1 parent ff78dc5b14
commit dc840ce3a0
3 files changed
+412 -42

No files matched your search

+152 -42
View File
@@ -13,10 +13,16 @@ from vnpipe.schema import validate
BASE_INDENT = 4
UPPER = "A-ZÁÉÍÓÚÜÑ"
ILLUSTRATION_RE = re.compile(r"^\[Ilustración[^\]]*\]$")
ILLUSTRATION_START_RE = re.compile(r"^\[Ilustración")
FOOTNOTE_START_RE = re.compile(r"^ {1,3}\[\d+\]\s")
FOOTNOTE_MARK_RE = re.compile(r"(?<=\S)\[\d+\]")
# A speaker heading: NAME, optionally followed by an italic note (separated by a comma or a
# space) that may mix italics and upper-case addressees: "MEFISTÓFELES, _a_ FAUSTO",
# "FAUSTO (_solo_)".
_NOTE = rf"_[^_]+_(?:\s*(?:_[^_]+_|[{UPPER}][{UPPER} ]*))*"
HEADING_RE = re.compile(
rf"^(?P<name>[{UPPER}][{UPPER} ]*?)"
r"(?:,\s*_(?P<note1>[^_]+)_|\s*\(_(?P<note2>[^_]+)_\))?$"
rf"(?:(?:,\s*|\s+)(?P<note1>{_NOTE})|\s*\(_(?P<note2>[^_]+)_\))?\.?$"
)
Line = tuple[int, str] # (1-based raw line number, text without line ending)
@@ -35,9 +41,11 @@ def clean(raw_text: str, scope_cfg: dict[str, Any]) -> list[Line]:
"""Cut the raw text to the configured scope and drop noise.
The start marker is the first line whose stripped text equals ``start_marker``; the end
marker is the ``end_occurrence``-th such line after it (exclusive). Illustration markers
are removed, trailing whitespace stripped and blank runs collapsed to a single blank line.
Returned line numbers refer to the raw file.
marker is the ``end_occurrence``-th such line after it (exclusive). Dropped as noise:
illustration markers (also multi-line ones), footnote definitions (`` [12] text``, with
their indented continuation lines) and footnote markers (``word[12]``). Trailing whitespace
is stripped and blank runs collapse to a single blank line. Returned line numbers refer to
the raw file.
"""
lines = _split(raw_text)
start_marker, end_marker = scope_cfg["start_marker"], scope_cfg["end_marker"]
@@ -51,10 +59,25 @@ def clean(raw_text: str, scope_cfg: dict[str, Any]) -> list[Line]:
end = matches[occurrence - 1]
out: list[Line] = []
skip_footnote = False
in_illustration = False
for i in range(start, end):
text = lines[i].rstrip()
if ILLUSTRATION_RE.match(text.strip()):
stripped = text.strip()
if in_illustration:
in_illustration = not stripped.endswith("]")
continue
if ILLUSTRATION_START_RE.match(stripped):
in_illustration = not stripped.endswith("]")
continue
if FOOTNOTE_START_RE.match(text):
skip_footnote = True
continue
if skip_footnote:
if stripped and _indent(text) < BASE_INDENT:
continue
skip_footnote = False
text = FOOTNOTE_MARK_RE.sub("", text)
if not text and out and not out[-1][1]:
continue
out.append((i + 1, text))
@@ -76,14 +99,29 @@ def _indent(text: str) -> int:
return len(text) - len(text.lstrip(" "))
def _match_heading(text: str) -> re.Match[str] | None:
return HEADING_RE.match(text) if text and not text[0].isspace() else None
def _scene_index(work_cfg: dict[str, Any]) -> dict[tuple[str, int], dict[str, Any]]:
"""Map (heading, occurrence) to the scene config; ids and keys must be unique."""
index: dict[tuple[str, int], dict[str, Any]] = {}
ids: set[str] = set()
for cfg in work_cfg["scenes"]:
key = (cfg["heading"], cfg.get("occurrence", 1))
if key in index:
raise ParseError(
f"scenes {index[key]['id']!r} and {cfg['id']!r} share heading {key[0]!r}: "
"give each a distinct `occurrence` (1-based, in order of appearance)"
)
if cfg["id"] in ids:
raise ParseError(f"duplicate scene id {cfg['id']!r}")
index[key] = cfg
ids.add(cfg["id"])
return index
class _SceneBuilder:
def __init__(self, scene_cfg: dict[str, Any]):
self.id: str = scene_cfg["id"]
self.heading: str = scene_cfg["heading"]
self.prose: bool = scene_cfg.get("format", "verse") == "prose"
self.lines: list[dict[str, Any]] = []
self.speaker: str | None = None
self.note: str | None = None
@@ -91,6 +129,7 @@ class _SceneBuilder:
self.stanza = 0
self.has_verse = False
self.pending_blank = False
self.started = False # a speech or verse line has begun: no more preamble
def add(self, kind: str, text: str, src: int, indent: int = 0, speaker: Any = False) -> None:
self.lines.append(
@@ -111,29 +150,89 @@ class _SceneBuilder:
self.speech += 1
self.speaker, self.note = speaker, note
self.stanza, self.has_verse, self.pending_blank = 0, False, False
self.started = True
def verse(self, text: str, src: int) -> None:
if self.pending_blank and self.has_verse:
self.stanza += 1
self.pending_blank, self.has_verse = False, True
self.started = True
self.add("verse", _strip_markup(text), src, max(_indent(text) - BASE_INDENT, 0))
def to_dict(self) -> dict[str, Any]:
return {"id": self.id, "heading": self.heading, "lines": self.lines}
def _block(lines: list[Line], i: int) -> tuple[list[str], int]:
"""Consecutive non-blank stripped lines starting at index ``i``; returns (block, next i)."""
block: list[str] = []
while i < len(lines) and lines[i][1].strip():
block.append(lines[i][1].strip())
i += 1
return block, i
def parse(lines: list[Line], work_cfg: dict[str, Any], source_sha256: str) -> dict[str, Any]:
"""Parse cleaned lines into the structure described by parsed.schema.json."""
scenes_by_heading = {s["heading"]: s for s in work_cfg["scenes"]}
"""Parse cleaned lines into the structure described by parsed.schema.json.
Line types, in the order they are tried (see docs/work-config.md):
scene heading (``[[scenes]]``), ``(_ ... _)`` direction, ``direction_headings`` entry,
italic direction block, speaker heading (``[speakers]``), preamble block (cast list or
setting before the first speech), prose paragraph (``format = "prose"`` scenes), verse.
"""
scene_cfgs = _scene_index(work_cfg)
headings = {h for h, _ in scene_cfgs}
speakers: dict[str, str] = work_cfg["speakers"]
direction_headings: set[str] = set(work_cfg.get("parser", {}).get("direction_headings", []))
seen_headings: dict[str, int] = {}
scenes: list[_SceneBuilder] = []
cur: _SceneBuilder | None = None
expect_block = False
i = 0
def fail(src: int, msg: str) -> ParseError:
return ParseError(f"raw line {src}: {msg}")
def speaker_heading(at: int, cur: _SceneBuilder) -> tuple[re.Match[str] | str, int] | None:
"""Speaker heading at index ``at`` (a wrapped note is joined): (match, next index)."""
src, text = lines[at]
stripped, nxt = text.strip(), at + 1
indent = _indent(text)
if indent >= BASE_INDENT:
return None
while stripped.count("_") % 2 and nxt < len(lines) and lines[nxt][1].strip():
stripped += " " + lines[nxt][1].strip()
nxt += 1
if stripped in speakers:
match: re.Match[str] | str | None = stripped
else:
match = HEADING_RE.match(stripped)
if match is None:
return None
name = match if isinstance(match, str) else match["name"].strip()
after = lines[nxt][1] if nxt < len(lines) else ""
if indent and (name not in speakers or after.strip()):
return None # indented lines are verse unless they are known, isolated headings
# a heading is followed by a blank line or by verse; anything else makes it part of a
# cast/setting block ("MARGARITA\n_entra de un salto..._")
peek = nxt
while peek < len(lines) and not lines[peek][1].strip():
peek += 1
if peek < len(lines):
follow = lines[peek][1]
adjacent = peek == nxt
if follow.strip().startswith(("_", "(_")):
ok = not adjacent or follow.startswith(" ") or indent
elif _indent(follow) > 0:
ok = True
else:
nxt_head = follow.strip() in speakers or follow.strip() in headings
ok = cur.prose and not adjacent and not nxt_head
if not ok and name in speakers and not adjacent and not nxt_head and not cur.prose:
raise fail(src, f"{stripped!r} is followed by unindented text; prose scene?")
if not ok:
return None
return match, nxt
while i < len(lines):
src, text = lines[i]
stripped = text.strip()
@@ -143,55 +242,66 @@ def parse(lines: list[Line], work_cfg: dict[str, Any], source_sha256: str) -> di
cur.pending_blank = True
continue
if not text[0].isspace() and stripped in scenes_by_heading:
cur = _SceneBuilder(scenes_by_heading[stripped])
if not text[0].isspace() and stripped in headings:
n = seen_headings[stripped] = seen_headings.get(stripped, 0) + 1
if (stripped, n) not in scene_cfgs:
raise fail(
src, f"scene heading {stripped!r} occurs {n} times, fewer are configured"
)
cur = _SceneBuilder(scene_cfgs[(stripped, n)])
scenes.append(cur)
expect_block = True
continue
if cur is None:
raise fail(src, f"text before any scene heading: {stripped!r}")
indent = _indent(text)
match = _match_heading(text)
is_heading = match is not None
if indent and indent < BASE_INDENT:
# Indented heading (a typesetting quirk): only accepted for known speakers.
m = HEADING_RE.match(stripped)
nxt = lines[i][1].strip() if i < len(lines) else ""
if m and m["name"] in speakers and not nxt:
match, is_heading = m, True
if expect_block:
expect_block = False
if indent < BASE_INDENT and (stripped.startswith("_") or not is_heading or indent):
block = [stripped]
while i < len(lines) and lines[i][1].strip():
block.append(lines[i][1].strip())
i += 1
kind = "direction" if stripped.startswith("_") else "cast"
cur.add(kind, _strip_markup(" ".join(block)), src, speaker=None)
continue
if stripped.startswith("(_"):
if stripped.startswith("(_") or (indent < BASE_INDENT and stripped.startswith("(")):
block = [stripped]
while not block[-1].endswith("_)"):
while not (
block[-1].rstrip("_").endswith(")")
and " ".join(block).count("(") == " ".join(block).count(")")
):
if i >= len(lines) or not lines[i][1].strip():
raise fail(src, "unterminated stage direction")
block.append(lines[i][1].strip())
i += 1
joined = " ".join(block)
cur.add("direction", _strip_markup(joined[2:-2]), src, speaker=None)
inner = " ".join(block)[1:].rstrip("_") # tolerate a misplaced closing "_" after ")"
cur.add("direction", _strip_markup(inner[:-1]), src, speaker=None)
continue
if is_heading and match is not None:
name = match["name"].strip()
if cur.started and indent < BASE_INDENT and stripped in direction_headings:
cur.add("direction", _strip_markup(stripped), src, speaker=None)
continue
if indent < BASE_INDENT and stripped.startswith("_"):
block, i = _block(lines, i - 1)
cur.add("direction", _strip_markup(" ".join(block)), src, speaker=None)
continue
found = speaker_heading(i - 1, cur)
if found is not None:
match, i = found
if isinstance(match, str):
name, note = match, None
else:
name = match["name"].strip()
note = match["note1"] or match["note2"]
if name not in speakers:
raise fail(src, f"unknown speaker or scene heading {stripped!r}")
note = match["note1"] or match["note2"]
cur.start_speech(speakers[name], note.strip() if note else None)
note = _strip_markup(note) if note else None
cur.start_speech(speakers[name], note)
continue
if not cur.started and indent < BASE_INDENT:
block, i = _block(lines, i - 1)
cur.add("cast", _strip_markup(" ".join(block)), src, speaker=None)
continue
if indent == 0:
if cur.prose and cur.speaker:
block, i = _block(lines, i - 1)
cur.verse(" ".join(block), src)
continue
raise fail(src, f"unrecognised line {stripped!r}")
cur.verse(text, src)
+94
View File
@@ -0,0 +1,94 @@
The Project Gutenberg eBook of Mini Extended
*** START OF THE PROJECT GUTENBERG EBOOK ***
PRELUDIO
ANA, BRUNO
ANA
Buenos días[1] al sol que nace,
camino adelante.
[Ilustración:
UN PIE DE FOTO
EN VARIAS LINEAS]
[1] Nota al pie con
una segunda línea.
BRUNO, _a_ ANA
Y buenas tardes.
[Ilustración]
CALLE
_Amanece en la plaza._
ANA (_aparte_)
Silencio.
BRUNO, _en voz baja y
mirando alrededor_.
¿Quién viene?
Nadie.
ENTRA UN VECINO
EL VECINO _a_ ANA
Buen día.
(VECINO _se quita el sombrero_.)
(_Pasan_ ANA _y_ BRUNO.)_
_Suena una campana_
CORO, TUTTI
¡Ay, ay!
CALLE
ANA
_entra corriendo, sin aliento_
BRUNO
¿Qué pasa?
INTERMEDIO[2]
[2] Nota sobre el intermedio.
ANA
Un verso.
NOCHE
_Campo raso_, ANA, BRUNO
ANA
Primer párrafo de la prosa, que se parte
en dos líneas.
Segundo párrafo.
(_Vase._)
BRUNO
Respuesta breve.
FIN
Texto fuera de alcance.
+166
View File
@@ -0,0 +1,166 @@
"""Text-stage mechanisms for full-length texts: footnotes, repeated headings, prose, hints."""
from pathlib import Path
import pytest
from vnpipe import text
from vnpipe.schema import validate
RAW = (Path(__file__).parent / "fixtures" / "mini_ext_raw.txt").read_text(encoding="utf-8")
CFG = {
"work": {"id": "ext"},
"scope": {"start_marker": "PRELUDIO", "end_marker": "FIN"},
"parser": {"direction_headings": ["ENTRA UN VECINO"]},
"speakers": {
"ANA": "ana",
"BRUNO": "bruno",
"EL VECINO": "neighbour",
"CORO, TUTTI": "chorus",
},
"scenes": [
{"heading": "PRELUDIO", "id": "preludio"},
{"heading": "CALLE", "id": "calle_1", "occurrence": 1},
{"heading": "CALLE", "id": "calle_2", "occurrence": 2},
{"heading": "INTERMEDIO", "id": "intermedio"},
{"heading": "NOCHE", "id": "noche", "format": "prose"},
],
}
SHA = "0" * 64
def parse(cfg=CFG, raw=RAW):
return text.parse(text.clean(raw, cfg["scope"]), cfg, SHA)
@pytest.fixture(scope="module")
def parsed():
return parse()
def scene(parsed, scene_id):
return next(s for s in parsed["scenes"] if s["id"] == scene_id)
def test_footnotes_and_multiline_illustrations_are_dropped():
lines = text.clean(RAW, CFG["scope"])
joined = "\n".join(t for _, t in lines)
assert "Nota" not in joined and "pie de foto" not in joined.lower()
assert "[1]" not in joined and "[2]" not in joined
assert "Buenos días al sol que nace," in joined
assert "INTERMEDIO\n" in joined # footnote marker removed from the heading
assert "\n\n\n" not in joined
assert "fuera de alcance" not in joined
def test_src_lines_survive_dropped_blocks():
raw_lines = RAW.split("\n")
for ln in (x for s in parse()["scenes"] for x in s["lines"] if x["kind"] == "verse"):
raw = raw_lines[ln["src_line"] - 1]
assert ln["text"].startswith(raw.strip().replace("_", "")[:10].replace("[1]", ""))
def test_repeated_heading_uses_occurrence(parsed):
assert [s["id"] for s in parsed["scenes"]] == [
"preludio",
"calle_1",
"calle_2",
"intermedio",
"noche",
]
assert scene(parsed, "calle_1")["heading"] == scene(parsed, "calle_2")["heading"] == "CALLE"
assert scene(parsed, "calle_2")["lines"][0]["id"] == "calle_2_0001"
def test_repeated_heading_without_occurrence_is_a_config_error():
scenes = [dict(s) for s in CFG["scenes"]]
del scenes[2]["occurrence"]
with pytest.raises(text.ParseError, match="occurrence"):
parse({**CFG, "scenes": scenes})
def test_more_occurrences_than_configured_fail():
scenes = [s for s in CFG["scenes"] if s["id"] != "calle_2"]
with pytest.raises(text.ParseError, match="CALLE.*2 times"):
parse({**CFG, "scenes": scenes})
def test_duplicate_scene_id_is_a_config_error():
scenes = [dict(s) for s in CFG["scenes"]]
scenes[2]["id"] = "calle_1"
with pytest.raises(text.ParseError, match="duplicate scene id"):
parse({**CFG, "scenes": scenes})
def test_speaker_notes_with_addressee_and_separators(parsed):
notes = {
(ln["speaker"], ln["speaker_note"])
for ln in scene(parsed, "preludio")["lines"] + scene(parsed, "calle_1")["lines"]
if ln["kind"] == "verse"
}
assert ("bruno", "a ANA") in notes # ", _a_ ANA"
assert ("ana", "aparte") in notes # "(_aparte_)"
assert ("neighbour", "a ANA") in notes # "EL VECINO _a_ ANA" (no comma)
def test_wrapped_note_and_trailing_period(parsed):
wrapped = [ln for ln in scene(parsed, "calle_1")["lines"] if ln["text"] == "¿Quién viene?"][0]
assert wrapped["speaker"] == "bruno"
assert wrapped["speaker_note"] == "en voz baja y mirando alrededor"
assert wrapped["indent"] == 2
assert scene(parsed, "calle_1")["lines"][-1]["speaker"] == "chorus" # exact-line speaker key
def test_direction_headings_apply_after_the_first_speech(parsed):
texts = [ln["text"] for ln in scene(parsed, "calle_1")["lines"] if ln["kind"] == "direction"]
assert "ENTRA UN VECINO" in texts
assert texts[0] == "Amanece en la plaza." # italic block before the first speech
assert "Suena una campana" in texts # italic block between speeches
def test_direction_heading_is_cast_in_a_preamble():
cfg = {**CFG, "parser": {"direction_headings": ["ANA, BRUNO", "ENTRA UN VECINO"]}}
first = parse(cfg)["scenes"][0]["lines"][0]
assert first["kind"] == "cast" and first["text"] == "ANA, BRUNO"
def test_parenthesised_directions(parsed):
texts = [ln["text"] for ln in scene(parsed, "calle_1")["lines"] if ln["kind"] == "direction"]
assert "VECINO se quita el sombrero." in texts # "(NAME _..._)"
assert "Pasan ANA y BRUNO." in texts # tolerates the misplaced ")_"
def test_heading_inside_a_cast_block(parsed):
first = scene(parsed, "calle_2")["lines"][0]
assert first["kind"] == "cast"
assert first["text"] == "ANA entra corriendo, sin aliento"
assert scene(parsed, "calle_2")["lines"][1]["speaker"] == "bruno"
def test_prose_scene_paragraphs_are_verse_lines(parsed):
lines = scene(parsed, "noche")["lines"]
assert [ln["kind"] for ln in lines] == ["direction", "verse", "verse", "direction", "verse"]
ana = [ln for ln in lines if ln["speaker"] == "ana"]
assert ana[0]["text"] == "Primer párrafo de la prosa, que se parte en dos líneas."
assert [ln["stanza"] for ln in ana] == [0, 1]
assert all(ln["indent"] == 0 for ln in ana)
assert lines[-1]["speaker"] == "bruno" and lines[-1]["speech"] == 1
def test_unindented_text_fails_outside_prose_scenes():
scenes = [dict(s) for s in CFG["scenes"]]
scenes[-1].pop("format")
with pytest.raises(text.ParseError, match="prose scene"):
parse({**CFG, "scenes": scenes})
def test_unlisted_caps_line_still_fails():
cfg = {**CFG, "parser": {}}
with pytest.raises(text.ParseError, match="ENTRA UN VECINO"):
parse(cfg)
def test_schema_valid_and_deterministic(parsed):
validate(parsed, "parsed")
assert parse() == parsed