diff --git a/docs/work-config.md b/docs/work-config.md index 355ecaa..f45d745 100644 --- a/docs/work-config.md +++ b/docs/work-config.md @@ -9,13 +9,37 @@ A work is a directory containing `work.toml`, plus the folders the pipeline fill | `[work]` | `id`, `title`, `subtitle`, `author`, `translator`, `language` (`es`/`en`, used for the About text), `lyric_voice` (cast id for verse nobody speaks; default `poet_voice`), `end_text`, `menu_bg` (background asset id for the main menu; default: first staged `bg`). | | `[source]` | `gutenberg_id`, `url`, `raw_file` (cache path, relative to the work root, gitignored). | | `[scope]` | `start_marker`, `end_marker` (whole stripped lines), `end_occurrence` (1-based, searched after the start; the end marker itself is excluded). | -| `[speakers]` | Speaker heading as printed (upper case) → cast id. An unknown speaker is a parse error. | -| `[[scenes]]` | `heading` (as printed), `id`, `location`, `time_of_day`. | +| `[speakers]` | Speaker heading as printed (upper case, without its italic note) → cast id. Several headings may share one id (anonymous crowd speakers). A key with punctuation or markup (`"CORO, TUTTI"`) is matched against the whole printed line first. An unknown speaker is a parse error. | +| `[[scenes]]` | `heading` (as printed), `id`, `location`, `time_of_day`, optional `occurrence` and `format` (below). | +| `[parser]` | `direction_headings`: whole lines in capitals that are stage directions or section titles (`"ENTRA FAUSTO"`), not speakers. Each becomes a `direction` line once the scene's first speech has started (before it, the line is treated as cast/setting). | | `[cast.]` | `name` (shown in the dialogue box), `color`, `sprite` (default `true`; `false` = never drawn), `expressions` (annotation emotion → sprite expression; needs `neutral`). | | `[staging.]` | `bg` (background shown after the title card), `mode` (`adv` or `nvl`), `cast = { = "left\|center\|right" }` pins sprite characters for the whole scene. | | `[[cues]]` | `at` (line id; fires right before it) plus any of `bg`, `transition` (`dissolve`, `fade`, `flash`, `slow`), `tint` (`none`, `dark`, `red`), `mode`, `hide_all`, `shake`, `move = { = "" }`. | | `[[overrides]]` | `from`, `to` (inclusive line ids in one scene), `emotion`: forces the emotion before expression mapping. | +### Text structure + +`parse` cuts the scope, then drops noise: illustration markers (also multi-line), footnote +definitions (` [12] text` plus indented continuation lines) and footnote markers (`word[12]`). +Then, per line: + +- A scene heading starts a scene. A heading printed more than once needs one `[[scenes]]` + entry per appearance, each with `occurrence` (1-based, in order of appearance; default 1). + Two entries with the same heading and occurrence, or the same `id`, are config errors; an + appearance with no entry is a parse error. +- Before the first speech, unindented blocks are `cast` lines (cast list, setting in capitals; + an italic block is a `direction`). A speaker heading directly followed by an unindented line + belongs to such a block. +- A speaker heading is `NAME`, optionally followed by an italic note (`, _a_ FAUSTO`, + ` (_solo_)`, notes wrapped over two lines); the note is kept in `speaker_note`. It must be + followed by a blank line and verse, otherwise it is not a heading. +- `(...)` blocks, unindented `_italic_` blocks and `direction_headings` are `direction` lines. +- `format = "prose"` on a scene: unindented paragraphs (consecutive lines joined) become one + `verse` line each (`indent` 0, `stanza` = paragraph index in the speech). Unindented text + in a verse scene is a parse error. + +Anything else is a `ParseError` with the raw line number. + Emotions: `neutral`, `joyful`, `melancholic`, `solemn`, `ironic`, `angry`, `fearful`, `ecstatic`. Unknown line ids, characters, positions or emotions are errors at generation. See [adaptation-rules.md](adaptation-rules.md) for how these choices are meant to be used. diff --git a/src/vnpipe/schemas/parsed.schema.json b/src/vnpipe/schemas/parsed.schema.json index 90d4336..2463c7c 100644 --- a/src/vnpipe/schemas/parsed.schema.json +++ b/src/vnpipe/schemas/parsed.schema.json @@ -27,7 +27,7 @@ "additionalProperties": false, "properties": { "id": {"type": "string", "pattern": "^[a-z0-9_]+_[0-9]{4}$", "description": "_<4-digit index within scene>"}, - "kind": {"enum": ["verse", "direction", "cast"], "description": "verse = spoken/recited text line; direction = stage direction (parenthesised or italic setting text); cast = list of characters under a scene heading"}, + "kind": {"enum": ["verse", "direction", "cast"], "description": "verse = spoken/recited text line (one paragraph in a prose scene); direction = stage direction (parenthesised or italic setting text); cast = list of characters under a scene heading"}, "speaker": {"type": ["string", "null"], "description": "Cast id from work.toml [speakers], null when nobody speaks (e.g. Dedicatoria, directions)"}, "speaker_note": {"type": ["string", "null"], "description": "Inline note in the speaker heading, e.g. 'solo', 'aterrado'"}, "speech": {"type": "integer", "minimum": 0, "description": "Index of the speech (speaker turn) within the scene; directions get the index of the speech they occur in or precede"}, diff --git a/src/vnpipe/text.py b/src/vnpipe/text.py index 62a5346..c775aa9 100644 --- a/src/vnpipe/text.py +++ b/src/vnpipe/text.py @@ -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[{UPPER}][{UPPER} ]*?)" - r"(?:,\s*_(?P[^_]+)_|\s*\(_(?P[^_]+)_\))?$" + rf"(?:(?:,\s*|\s+)(?P{_NOTE})|\s*\(_(?P[^_]+)_\))?\.?$" ) 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) diff --git a/tests/fixtures/mini_ext_raw.txt b/tests/fixtures/mini_ext_raw.txt new file mode 100644 index 0000000..6479b70 --- /dev/null +++ b/tests/fixtures/mini_ext_raw.txt @@ -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. diff --git a/tests/test_text_ext.py b/tests/test_text_ext.py new file mode 100644 index 0000000..f3b75c1 --- /dev/null +++ b/tests/test_text_ext.py @@ -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