#!/usr/bin/env python3 """Rebuild `1000_novels` as its public-domain subset with per-row attribution. CLARIN-PL replied (October 2026) that handle 11321/312 holds metadata only: CLARIN does not distribute the texts and holds no rights documentation, so no licence covers them. A row is kept only when the per-text rights screen finds it public domain in Poland: polish-dynaword-v2/evidence/1000_novels_rights_screen.csv (written by polish-dynaword-v2/scripts/novels_rights_screen.py) Kept rows are labelled `public-domain`, and `author` credits the author and any translator. Title, death year, screen basis and CLARIN file name go to `1000_novels.attribution.jsonl`. After the screen, a row is dropped when it duplicates a wolne_lektury or eltec_pol document (slayerlabs/polish-dynaword-v2#45; the maintainer chose to keep those two sources whole): cover = |S(row) & union of S(doc) over the source's documents| / |S(row)| >= DUP_AT S() is the set of 5-word shingles from src/shingle_containment.py (near_dedup tokenisation). The union matters because Wolne Lektury splits long novels into tomes. A trailing Wolne Lektury footer is cut from the row before scoring; the released text is not changed. Every screened row's cover against each source, and the documents holding >= MATCH_AT of its shingles, go to `1000_novels.dedup.tsv`. The inputs are the v0.2.5 Parquet, the screen CSV (polish-dynaword-v2 main since v2 PR #73) and the wolne_lektury and eltec_pol Parquets, all pinned by SHA-256. Restore the 1000_novels Parquet before a rerun: git checkout v0.2.5 -- data/1000_novels/1000_novels.parquet python3 src/clean_1000_novels.py --screen ../polish-dynaword-v2/evidence/1000_novels_rights_screen.csv """ from __future__ import annotations import argparse import csv import json import os import re import unicodedata from collections import Counter from pathlib import Path import pyarrow.parquet as pq from sejm_api_common import check_pin, sha256_file from shingle_containment import containment, strip_wl_footer SOURCE = "1000_novels" ROOT = Path(__file__).resolve().parents[1] DATA = ROOT / "data" / SOURCE INPUT_SHA256 = "27be09e5e2347dcf1a83e94b6c210ca26bdd89365bc3563e88ea5af9846990ea" # v0.2.5 # polish-dynaword-v2 evidence/1000_novels_rights_screen.csv for v0.2.6; also in 1000_novels.license-evidence.json SCREEN_SHA256 = "7fefc75f8fcbd07e5ec98842276765ffef9520b6acb4e24b4751c67cc3d2081c" UPSTREAM = "https://clarin-pl.eu/dspace/handle/11321/312" LICENSE = "public-domain" DEDUP = f"{SOURCE}.dedup.tsv" # DUP_AT sits in an empty stretch of the covers of the 887 screened rows: none between 0.0727 # and 0.5178 against wolne_lektury, none between 0.0462 and 0.7771 against eltec_pol. DUP_AT = 0.5 MATCH_AT = 0.05 # Main's Parquets: wolne_lektury after its eltec_pol dedup (Hub PR 67), eltec_pol as in v0.2.1-v0.2.5. REFERENCES = { "wolne_lektury": "f308d49235551241d6c47c5e88138ba52e6235422ae272ddbc135c3b8696ae0e", "eltec_pol": "ba40061741dff11165149f6c2cf3d5526e1b6c759e7ce1e03ccc164d58838325", } REFERENCE_PATHS = {name: ROOT / "data" / name / f"{name}.parquet" for name in REFERENCES} DEDUP_FIELDS = ["id", "action", *(f"{n}_cover" for n in REFERENCES), *(f"{n}_matches" for n in REFERENCES), "author", "title"] KEEP = {"pd_by_term"} SCREENS = KEEP | {"in_copyright", "unresolved"} # Read off each text's header by hand where the rules below fail: no header, a dedication # ("H. K. T."), a series title (Proust), a title broken over lines, or a misspelt file name. TITLES = { "conrad_murzyn-z-zalogi-narcyza_1923.txt": "Murzyn z załogi „Narcyza”", "orzeszkowa_pan-graba_czesc1_1872.txt": "Pan Graba", "proust_w-cieniu-zakwitajacych-dziewczat_tom-I_1937.txt": "W cieniu zakwitających dziewcząt", "proust_w-cieniu-zakwitajacych-dziewczat_tom-II_1937.txt": "W cieniu zakwitających dziewcząt", "proust_w-cieniu-zakwitajacych-dziewczat_tom-III_1937.txt": "W cieniu zakwitających dziewcząt", "prus_co-sie-z-wielkiej-idei-zrobilo-w-malym-miasteczku.txt": "Co się z wielkiej idei zrobiło w małem miasteczku", "prus_piesn-swiata_1935.txt": "Pleśń świata", "puszkin_basn-o-krolu-saltanie_1924.txt": "Baśń o królu Sałtanie, o jego synu, słynnym i potężnym bohaterze Gwidonie, i o pięknej królewnie Łabędziu", "reymont_wampir.txt": "Wampir", "sienkiewicz_bajka1.txt": "Bajka", "sienkiewicz_bajka3.txt": "Bajka", "sienkiewicz_jako-sie-pan-lubomirski-nawrocil-kosciol-w-tarnowie-zbudowal_1931.txt": "Jako się pan Lubomirski nawrócił i kościół w Tarnawie zbudował", "verne_przygody-trzech-rosjan-i-trzech-anglikow-w-poludniowej-afryce_1883.txt": "Przygody trzech Rossyan i trzech Anglików w południowej Afryce", "zapolska_papuzia_1958.txt": "Papuzia", "zeromski_popioly.txt": "Popioły", "zulawski_list-senki-do-lucjusza_1914.txt": "List Seneki do Lucyljusza", "zulawski_z-domu-ojcow_1897.txt": "Z domu ojców", } NOT_A_TITLE = re.compile(r"^(tłum|tłumacz|przekład|rozdział|tom|księga|[IVXLC]+\.?$|\d+\.?$)", re.I) def fold(text: str) -> str: """ASCII slug as in CLARIN file names: `Śpiewak spod strzechy` -> `spiewak-spod-strzechy`.""" text = text.replace("ł", "l").replace("Ł", "L") text = unicodedata.normalize("NFKD", text).encode("ascii", "ignore").decode().lower() return re.sub(r"[^a-z0-9]+", "-", text).strip("-") def file_slug(clarin_file: str) -> str: """`sienkiewicz_krzyzacy_tom-II_1900.txt` -> `krzyzacy_tom-II` folded.""" parts = clarin_file.removesuffix(".txt").split("_")[1:] if parts and re.fullmatch(r"\d{4}", parts[-1]): parts = parts[:-1] return fold(" ".join(parts)) def header_lines(text: str, limit: int = 8) -> list[str]: lines = [] for line in re.split(r"[\r\n]+", text[:3000]): line = line.strip().lstrip("<").strip() if line: lines.append(line) if len(lines) == limit: break return lines def tidy(title: str) -> str: return re.sub(r"\s+", " ", title).strip(" .\t") def title_of(text: str, clarin_file: str, author: str) -> tuple[str, str]: """(title, how): `manual` = TITLES; `file` = header words that fold to the file-name slug (V against the file name); `position` = the line next to the author line (I); `none`.""" if clarin_file in TITLES: return TITLES[clarin_file], "manual" slug = file_slug(clarin_file) lines = header_lines(text) for i in range(len(lines)): for span in (1, 2, 3): # titles broken over lines: "...kościół w Tarnawie" / "zbudował" if fold(" ".join(lines[i:i + span])) == slug: return tidy(" ".join(lines[i:i + span])), "file" words = lines[i].split() # "Kalosze szczęścia (tłum. Mirandola)/1. Początek" for n in range(1, len(words)): if fold(" ".join(words[:n])) == slug: return tidy(" ".join(words[:n])), "file" keys = {fold(clarin_file.split("_")[0]), fold(author.split()[-1])} def is_author(line: str) -> bool: return len(line.split()) <= 6 and any(k and k in fold(line) for k in keys) if len(lines) > 1: for author_at, title_at in ((0, 1), (1, 0)): candidate = lines[title_at] if is_author(lines[author_at]) and not is_author(candidate) and not NOT_A_TITLE.match(candidate): return tidy(candidate), "position" return "", "none" def credit(author: str, translator: str) -> str: return f"{author} (tłum. {translator})" if translator else author def check_references(ref_paths: dict[str, Path]) -> None: """Fail unless ref_paths are exactly the pinned wolne_lektury and eltec_pol Parquets.""" if ref_paths.keys() != REFERENCES.keys(): raise SystemExit(f"reference sources must be {sorted(REFERENCES)}, got {sorted(ref_paths)}") for name, path in ref_paths.items(): if (found := sha256_file(path)) != REFERENCES[name]: raise SystemExit(f"{path} does not match the pinned {name} SHA-256 {REFERENCES[name]} " f"(found {found}); the dedup is pinned to main's {name} Parquet") def cross_source_covers(texts: list[str], ref_paths: dict[str, Path]) -> list[dict]: """Per text and reference source: its cover, and the documents holding >= MATCH_AT of it.""" texts = [strip_wl_footer(t) for t in texts] out = [{} for _ in texts] for name, path in ref_paths.items(): refs = pq.read_table(path, columns=["id", "text"]) ref_ids = refs.column("id").to_pylist() for row, m in zip(out, containment(texts, refs.column("text").to_pylist()), strict=True): shares = sorted(((s / m.shingles, ref_ids[r]) for r, s in zip(m.refs, m.shared)), reverse=True) row[name] = (m.cover, [(i, share) for share, i in shares if share >= MATCH_AT]) return out def build(input_path: Path, screen_path: Path, out_dir: Path, ref_paths: dict[str, Path] = REFERENCE_PATHS) -> dict: if (found := sha256_file(screen_path)) != SCREEN_SHA256: raise SystemExit(f"{screen_path} is not the pinned rights screen: SHA-256 {found}, expected " f"{SCREEN_SHA256}; regenerate it with polish-dynaword-v2/scripts/novels_rights_screen.py " "or update SCREEN_SHA256 and 1000_novels.license-evidence.json together") check_pin(input_path, INPUT_SHA256, "restore it with `git checkout v0.2.5 -- data/1000_novels/1000_novels.parquet`") check_references(ref_paths) table = pq.read_table(input_path) with screen_path.open(encoding="utf-8", newline="") as stream: screen = {row["id"]: row for row in csv.DictReader(stream)} ids = table.column("id").to_pylist() if set(ids) != set(screen) or len(ids) != len(set(ids)): raise SystemExit("rights screen and Parquet do not cover the same ids") if unknown := {row["screen"] for row in screen.values()} - SCREENS: raise SystemExit(f"unknown screen values: {unknown}") screened = [row for row in table.to_pylist() if screen[row["id"]]["screen"] in KEEP] if stale := TITLES.keys() - {screen[row["id"]]["clarin_file"] for row in screened}: raise SystemExit(f"TITLES names files that are not screened public domain: {sorted(stale)}") covers = cross_source_covers([row["text"] for row in screened], ref_paths) kept, attribution, dedup = [], [], [] duplicates = Counter() for row, cover in zip(screened, covers, strict=True): rights = screen[row["id"]] title, how = title_of(row["text"], rights["clarin_file"], rights["author"]) dup_of = [name for name in REFERENCES if cover[name][0] >= DUP_AT] duplicates.update(dup_of) duplicates["both"] += len(dup_of) == len(REFERENCES) dedup.append({"id": row["id"], "action": "drop" if dup_of else "keep", **{f"{name}_cover": f"{cover[name][0]:.4f}" for name in REFERENCES}, **{f"{name}_matches": " ".join(f"{i}={share:.4f}" for i, share in cover[name][1]) for name in REFERENCES}, "author": rights["author"], "title": title}) if dup_of: continue kept.append({**row, "license": LICENSE, "author": credit(rights["author"], rights["translator"])}) attribution.append({ "id": row["id"], "author": rights["author"], "author_died": rights["author_died"], "translator": rights["translator"], "title": title, "title_from": how, "clarin_file": rights["clarin_file"], "upstream": UPSTREAM, "license": LICENSE, "screen": rights["screen"], "basis": rights["basis"], }) stats = { "read": len(ids), "kept": len(kept), "drop_rights": len(ids) - len(screened), "drop_cross_dup": len(screened) - len(kept), "drop_short": 0, "drop_lang": 0, "drop_dup": 0, "drop_ocr": 0, "chars": sum(len(r["text"]) for r in kept), "tokens": sum(r["token_count"] for r in kept), "licenses": {LICENSE: len(kept)}, "authors_with_value": sum(bool(r["author"]) for r in kept), "license": LICENSE, "screen": dict(Counter(r["screen"] for r in screen.values())), "cross_dup": {name: duplicates[name] for name in [*REFERENCES, "both"]}, "titles": dict(Counter(a["title_from"] for a in attribution)), "input_sha256": INPUT_SHA256, "screen_sha256": SCREEN_SHA256, **{f"{name}_sha256": sha for name, sha in REFERENCES.items()}, } staged = { out_dir / f"{SOURCE}.parquet.tmp": lambda p: pq.write_table( table.from_pylist(kept, schema=table.schema), p, compression="zstd"), out_dir / f"{SOURCE}.attribution.jsonl.tmp": lambda p: p.write_text( "".join(json.dumps(a, ensure_ascii=False) + "\n" for a in attribution), encoding="utf-8"), out_dir / f"{DEDUP}.tmp": lambda p: _write_dedup(p, dedup), out_dir / f"{SOURCE}.stats.json.tmp": lambda p: p.write_text( json.dumps(stats, indent=2, ensure_ascii=False) + "\n", encoding="utf-8"), } for path, write in staged.items(): write(path) for path in staged: os.replace(path, path.with_suffix("")) return stats def _write_dedup(path: Path, rows: list[dict]) -> None: with path.open("w", encoding="utf-8", newline="") as handle: writer = csv.DictWriter(handle, DEDUP_FIELDS, delimiter="\t", lineterminator="\n") writer.writeheader() writer.writerows(rows) def main() -> None: parser = argparse.ArgumentParser(description=__doc__.split("\n")[0]) parser.add_argument("--input", type=Path, default=DATA / f"{SOURCE}.parquet") parser.add_argument("--screen", type=Path, required=True, help="1000_novels_rights_screen.csv") parser.add_argument("--out", type=Path, default=DATA) args = parser.parse_args() print(json.dumps(build(args.input, args.screen, args.out), indent=2, ensure_ascii=False)) if __name__ == "__main__": main()