"""Helpers shared by the literary attribution builders (wolne_lektury, eltec_pol; polish-dynaword-v2#109). A builder writes a sidecar (one JSON line per Parquet row, same order, sorted keys) and a Parquet whose `author` column is filled from it. Every sidecar line carries `text_sha1` and `with_authors` refuses a table whose text does not hash to it: a builder that changes the text (eltec_pol) changes the table first, and the sidecar describes the text as released. """ from __future__ import annotations import hashlib import json import re import sys from pathlib import Path import pyarrow as pa import pyarrow.parquet as pq sys.path.insert(0, str(Path(__file__).resolve().parent)) from sejm_api_common import replace_all, write_json # noqa: E402 # Words per 1,000 with a period letter inside (the "é" of "téj", "ſ"). Loanwords ("café") give a few per text; # a text in period spelling gives dozens. PERIOD_SPELLING_AT = 5.0 _PERIOD_LETTER = re.compile(r"(?<=[a-ząćęłńóśźż])[éáſ]|ſ") # Headings of a preface, commentary or note section on a line of its own. They are counted, not judged: a # "Wstęp" may be the author's own, or the source edition's editor's. APPARATUS_HEADING = re.compile( r"^\s*(wstęp|przedmowa|słowo wstępne|od wydawc\w*|od redakcji|od tłumacza|posłowie|komentarz" r"|uwagi? (?:wydawc|redakcyjn)\w*|nota (?:wydawnicza|edytorska|redakcyjna)|o wydaniu|przypisy)\s*$", re.I | re.M) # What src/build_dynaword.py and src/takedown.py do to every source's text, in order. A step with `stat` has # its drop count in the source's stats.json. Only the strip can change a text. BUILD_DYNAWORD_STEPS = [ {"stage": "src/build_dynaword.py", "changes_text": "leading and trailing whitespace only", "step": "strip each text"}, {"stage": "src/build_dynaword.py", "changes_text": "no", "step": "drop a text shorter than 200 characters", "stat": "drop_short"}, {"stage": "src/build_dynaword.py", "changes_text": "no", "step": "drop a text the language gate does not take " "for Polish (src/language_gate.py)", "stat": "drop_lang"}, {"stage": "src/build_dynaword.py", "changes_text": "no", "step": "drop a text whose alphabetic share is too low " "(the OCR gate; it applies to OCR sources only and this is not one)", "stat": "drop_ocr"}, {"stage": "src/build_dynaword.py", "changes_text": "no", "step": "drop a text identical to one already kept, " "across sources", "stat": "drop_dup"}, {"stage": "src/build_dynaword.py", "changes_text": "no", "step": "count tokens (tiktoken cl100k_base) and " "SHA-1 the text"}, {"stage": "src/takedown.py", "changes_text": "no", "step": "drop a blocklisted record (none of this " "source's records was on the blocklist when this was built)"}, ] def text_sha1(text: str) -> str: return hashlib.sha1(text.encode("utf-8")).hexdigest() def text_digest(table: pa.Table) -> str: """One digest of every row's id and text, to show that two Parquets carry the same text.""" lines = (f"{i}\t{text_sha1(t)}\n" for i, t in zip(table.column("id").to_pylist(), table.column("text").to_pylist(), strict=True)) return hashlib.sha256("".join(lines).encode("utf-8")).hexdigest() def period_spelling_rate(text: str) -> float: """Words with a period letter per 1,000 words (a heuristic for text that was not modernised).""" words = text.split() return 1000 * sum(bool(_PERIOD_LETTER.search(w)) for w in words) / len(words) if words else 0.0 def steps_with_counts(steps: list[dict], stats: dict) -> list[dict]: """`steps` for the evidence file: a step's `stat` key becomes `rows_dropped`, read from `stats`.""" return [{**{k: v for k, v in step.items() if k != "stat"}, **({"rows_dropped": stats[step["stat"]]} if "stat" in step else {})} for step in steps] SOFT_HYPHEN = "\u00ad" # invisible; a typesetter's line-break hint that survived the digitisation def text_checks(table: pa.Table) -> dict: """What the released text contains, counted over every row (no sampling): the checks both literary sources share. A section heading or a period spelling is listed with the ids of its rows.""" ids, texts = table.column("id").to_pylist(), table.column("text").to_pylist() headings: dict[str, list[str]] = {} for row_id, text in zip(ids, texts, strict=True): for name in sorted({m.group(1).lower() for m in APPARATUS_HEADING.finditer(text)}): headings.setdefault(name, []).append(row_id) period = [i for i, t in zip(ids, texts, strict=True) if period_spelling_rate(t) >= PERIOD_SPELLING_AT] hyphenated = {i: t.count(SOFT_HYPHEN) for i, t in zip(ids, texts, strict=True) if SOFT_HYPHEN in t} return { "rows": len(ids), "leading_or_trailing_whitespace": sum(t != t.strip() for t in texts), "section_headings": {name: {"rows": len(rows), "ids": rows} for name, rows in sorted(headings.items())}, "period_spelling": {"words_per_1000_at_least": PERIOD_SPELLING_AT, "rows": len(period), "ids": period}, "soft_hyphen": {"rows": len(hyphenated), "occurrences": sum(hyphenated.values()), "per_row": hyphenated}, } # A bracket closing the given names: the real name behind a pseudonym, as in 'M-ski, Adam [Zofia Trzeszczkowska]'. TRAILING_BRACKET = re.compile(r"(.*?)\s*(\[[^\[\]]*\])") def natural_order(name: str) -> str: """'Sienkiewicz, Henryk' -> 'Henryk Sienkiewicz', with runs of white space made one space. A bracket after the given names stays last ('M-ski, Adam [Zofia Trzeszczkowska]' -> 'Adam M-ski [Zofia Trzeszczkowska]'). A name without exactly one comma, with a parenthesis (a qualifier such as '(ojciec)') or with only a bracket after the comma stays as the source gives it.""" name = " ".join(name.split()) family, comma, given = (part.strip() for part in name.partition(",")) if not comma or not family or not given or "," in given or "(" in name: return name bracket = TRAILING_BRACKET.fullmatch(given) if not bracket: return f"{given} {family}" return f"{bracket[1]} {family} {bracket[2]}" if bracket[1] else name def write_sidecar(path: Path, records: list[dict]) -> None: with path.open("w", encoding="utf-8", newline="\n") as handle: for record in records: handle.write(json.dumps(record, ensure_ascii=False, sort_keys=True) + "\n") def read_sidecar(path: Path) -> list[dict]: with path.open(encoding="utf-8") as handle: return [json.loads(line) for line in handle] def with_authors(table: pa.Table, records: list[dict]) -> pa.Table: """`table` with `author` set from `records` (one per row, same order, each with `id`, `author` and `text_sha1`). Fails if the rows or their text differ from the records: only `author` may change.""" ids, texts = table.column("id").to_pylist(), table.column("text").to_pylist() if ids != [r["id"] for r in records]: raise SystemExit("the sidecar does not list the Parquet rows in order") changed = [i for i, text, r in zip(ids, texts, records, strict=True) if text_sha1(text) != r["text_sha1"]] if changed: raise SystemExit(f"{len(changed)} rows have text that differs from the sidecar's text_sha1, " f"first {changed[0]}; the text must not change") index = table.column_names.index("author") return table.set_column(index, table.schema.field("author"), pa.array([r["author"] for r in records], pa.string())) def write_release(out_dir: Path, source: str, table: pa.Table, records: list[dict], evidence: dict, stats_update: dict | None = None) -> dict: """Write the sidecar, the Parquet with `author` filled, the stats with `authors_with_value` (and `stats_update`, for a builder that changed the text) and the evidence file for `source`, all or none. Returns the new stats.""" stats_path = out_dir / f"{source}.stats.json" stats = json.loads(stats_path.read_text(encoding="utf-8")) stats["authors_with_value"] = sum(bool(r["author"]) for r in records) stats.update(stats_update or {}) released = with_authors(table, records) replace_all({ out_dir / f"{source}.attribution.jsonl": lambda p: write_sidecar(p, records), out_dir / f"{source}.parquet": lambda p: pq.write_table(released, p, compression="zstd"), stats_path: lambda p: p.write_text(json.dumps(stats, indent=2, ensure_ascii=False) + "\n", encoding="utf-8"), out_dir / f"{source}.license-evidence.json": lambda p: write_json(p, evidence), }) return stats