File size: 9,538 Bytes
81fafcb
44a5f97
81fafcb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
#!/usr/bin/env python3
"""What the ELTeC-pol level-1 TEI files say about each eltec_pol novel.

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 <editor> or <editionStmt> exists), the amount of text the extractor still leaves
out, and where in the text it restores the chapter titles and the two <front>/<back> 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 <directory with the 100 files>   compare the files with the committed table
  python3 -I src/eltec_tei.py write <directory with the 100 files>   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 <p> of <body>
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 <name> 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 <p> and <head>: 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: <front> and <back> (of the one part it restores, only
    the text outside every <p> and <head>), and the text of <body> outside every <p> and <head>."""
    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"<!DOCTYPE" in xml or b"<!ENTITY" in xml:
        raise SystemExit(f"{name}: refusing a file with a DOCTYPE or ENTITY declaration")
    root = fromstring(xml)
    header, text = first(root, "teiHeader"), first(root, "text")
    if header is None or text is None or first(text, "body") is None:
        raise SystemExit(f"{name}: no <teiHeader>, <text> or <body>")
    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 <bibl type={bibl.get('type')!r}>")
        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 <titleStmt>")
    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:])