#!/usr/bin/env python3 """What the ELTeC-pol level-1 TEI files say about each eltec_pol novel (polish-dynaword-v2#109). The 100 TEI files (61 MB) are not in this repository. `eltec_tei.jsonl` next to eltec_meta.tsv holds, for each file of COST-ELTeC/ELTeC-pol at commit COMMIT (folder `level1`): its size, SHA-256 and git blob SHA-1, the SHA-1 of the text src/fetch_eltec.py makes of it, the header facts (title, author, who encoded it, print edition, first edition, digital source, revision log, whether any or exists), the amount of text the extractor still leaves out, and where in the text it restores the chapter titles and the two / parts (`restored`: positions among the paragraphs, so the text without them can be rebuilt). The table is pinned by SHA-256 (TABLE_SHA256), so the per-file SHA-256 values are pinned with it. python3 -I src/eltec_tei.py check compare the files with the committed table python3 -I src/eltec_tei.py write rebuild the table (then update TABLE_SHA256) The files are data from the internet: they are parsed, never run, and a DOCTYPE or ENTITY declaration is refused. """ from __future__ import annotations import hashlib import json import re import sys from pathlib import Path from xml.etree.ElementTree import Element, fromstring sys.path.insert(0, str(Path(__file__).resolve().parent)) from attribution_common import text_sha1 # noqa: E402 from fetch_eltec import RESTORED_PARTS, SEPARATOR, TEI, XML_ID, tei_paragraphs # noqa: E402 from sejm_api_common import check_pin # noqa: E402 COMMIT = "95fe196e35720b3de9644ef3ef1d1bb242bae99a" # COST-ELTeC/ELTeC-pol, branch master, fetched 2026-10-20 FILES = 100 TABLE = (Path(__file__).resolve().parents[1] / "artifacts" / "rights_audit_2026-10" / "literary" / "eltec_tei.jsonl") TABLE_SHA256 = "b60074952661381e695b7e1864a29f6ef7ab2c506a1064513158ec5a73661ee5" BIBL_TYPES = ("digitalSource", "firstEdition", "printSource") RESTORED_KINDS = ("back", "front", "head") # the kinds of paragraph in tei_paragraphs that are not a

of PLACE_AND_PUBLISHER = re.compile(r"^([^:]+): ([^:]+)$") # "Warszawa: Gebethner i Wolff"; anything else stays as given def collapse(text: str | None) -> str: return " ".join((text or "").split()) def tag(el: Element) -> str: return el.tag.removeprefix(TEI) def first(parent: Element, name: str) -> Element | None: return parent.find(f"{TEI}{name}") def child_text(parent: Element, name: str) -> str | None: """The whitespace-collapsed text of the first child of `parent`; None when absent or empty.""" el = first(parent, name) return (collapse("".join(el.itertext())) or None) if el is not None else None def year(value: str | None) -> int | None: if value is None: return None if not re.fullmatch(r"\d{4}", value): raise SystemExit(f"a date that is not a four-digit year: {value!r}") return int(value) def edition(bibl: Element) -> dict: """A print or first edition. `place` and `publisher` are set only for the form "Place: Publisher"; `publisher_as_given` always holds the field as the file has it.""" given = child_text(bibl, "publisher") split = PLACE_AND_PUBLISHER.match(given) if given else None return {"author": child_text(bibl, "author"), "place": split[1].strip() if split else None, "publisher": split[2].strip() if split else None, "publisher_as_given": given, "title": child_text(bibl, "title"), "year": year(child_text(bibl, "date"))} def digital_source(bibl: Element) -> dict: refs = [r.get("target") or collapse("".join(r.itertext())) for r in bibl.findall(f"{TEI}ref")] return {"publisher": child_text(bibl, "publisher"), "refs": refs, "title": child_text(bibl, "title")} def stray_chars(el: Element) -> int: """Characters in `el` outside every

and : text between and after them.""" if tag(el) in ("p", "head"): return 0 return len(collapse(el.text)) + sum(stray_chars(child) + len(collapse(child.tail)) for child in el) def not_in_text(root: Element) -> dict: """What src/fetch_eltec.py still leaves out of the text: and (of the one part it restores, only the text outside every

and ), and the text of outside every

and .""" text = first(root, "text") restored = RESTORED_PARTS.get(root.get(XML_ID)) def left_out(name: str) -> int: part = first(text, name) if part is None: return 0 return stray_chars(part) if name == restored else len(collapse(" ".join(part.itertext()))) return {"back_chars": left_out("back"), "body_stray_chars": stray_chars(first(text, "body")), "front_chars": left_out("front")} def restored_positions(paragraphs: list[tuple[str, str]]) -> dict: """The positions among `paragraphs` (the paragraphs of the text) of each kind the extractor restores.""" return {kind: [i for i, (k, _) in enumerate(paragraphs) if k == kind] for kind in RESTORED_KINDS} def read_file(name: str, xml: bytes) -> dict: """The table row of one TEI file.""" if b", or ") by_type: dict[str, Element] = {} for bibl in header.iter(f"{TEI}bibl"): if bibl.get("type") not in BIBL_TYPES or bibl.get("type") in by_type: raise SystemExit(f"{name}: unexpected or repeated ") by_type[bibl.get("type")] = bibl if "digitalSource" not in by_type: raise SystemExit(f"{name}: no digital source") title_stmt = header.find(f"{TEI}fileDesc/{TEI}titleStmt") if title_stmt is None: raise SystemExit(f"{name}: no ") author = first(title_stmt, "author") paragraphs = tei_paragraphs(root) return { "author": child_text(title_stmt, "author"), "author_ref": author.get("ref") if author is not None else None, "bytes": len(xml), "changes": [{"text": collapse("".join(c.itertext())), "when": c.get("when")} for c in header.iter(f"{TEI}change")], "digital_source": digital_source(by_type["digitalSource"]), "editor_elements": sum(tag(el) in ("editor", "editionStmt") for el in header.iter()), "file": name, "first_edition": edition(by_type["firstEdition"]) if "firstEdition" in by_type else None, "git_blob": hashlib.sha1(b"blob %d\0" % len(xml) + xml).hexdigest(), "not_in_text": not_in_text(root), "note_elements": len(list(root.iter(f"{TEI}note"))), "print_source": edition(by_type["printSource"]) if "printSource" in by_type else None, "restored": restored_positions(paragraphs), "responsibility": [{"name": child_text(r, "name"), "role": child_text(r, "resp")} for r in title_stmt.findall(f"{TEI}respStmt")], "sha256": hashlib.sha256(xml).hexdigest(), "text_sha1": text_sha1(SEPARATOR.join(t for _, t in paragraphs)), "text_sha1_without_restored": text_sha1(SEPARATOR.join(t for k, t in paragraphs if k == "p")), "title": child_text(title_stmt, "title"), } def read_dir(directory: Path) -> list[dict]: """The rows of the .xml files in `directory`, in name order. Refuses links and any count but FILES.""" paths = sorted(p for p in directory.iterdir() if p.suffix == ".xml") if len(paths) != FILES or any(p.is_symlink() or not p.is_file() for p in paths): raise SystemExit(f"{directory} must hold {FILES} regular .xml files") return [read_file(p.name, p.read_bytes()) for p in paths] def dump(rows: list[dict]) -> str: return "".join(json.dumps(row, ensure_ascii=False, sort_keys=True) + "\n" for row in rows) def read_table(path: Path = TABLE, expected: str = TABLE_SHA256) -> list[dict]: """The committed rows, in file-name order, after the SHA-256 pin.""" check_pin(path, expected, "restore it from main") rows = [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines()] if len(rows) != FILES or [r["file"] for r in rows] != sorted({r["file"] for r in rows}): raise SystemExit(f"{path} does not list {FILES} distinct files in name order") return rows def read_checked_dir(directory: Path) -> list[dict]: """The committed rows, once the files in `directory` are shown to be the files they describe.""" committed = read_table() wrong = [a["file"] for a, b in zip(read_dir(directory), committed, strict=True) if a != b] if wrong: raise SystemExit(f"{len(wrong)} files differ from the committed table, first {wrong[0]}") return committed def main(argv: list[str]) -> None: if len(argv) != 2 or argv[0] not in ("check", "write"): raise SystemExit(__doc__) if argv[0] == "write": TABLE.write_text(dump(read_dir(Path(argv[1]))), encoding="utf-8", newline="\n") print(f"wrote {TABLE}; set TABLE_SHA256 to {hashlib.sha256(TABLE.read_bytes()).hexdigest()}") return read_checked_dir(Path(argv[1])) print(f"{FILES} files match the committed table (commit {COMMIT})") if __name__ == "__main__": main(sys.argv[1:])