#!/usr/bin/env python3 """Drop wolne_lektury documents whose text is an eltec_pol novel (slayerlabs/polish-dynaword-v2#72), then label each kept row with its own Wolne Lektury licence (polish-dynaword-v2#57). Half of the 100 ELTeC-pol novels are also in Wolne Lektury. The maintainer chose (2026-10-06) to drop the Wolne Lektury copies and keep eltec_pol whole, because ELTeC's CC BY 4.0 is the clean licence. Wolne Lektury splits long novels into tomes, so the test is containment, not Jaccard: score = |S(wl) & S(novel)| / |S(wl)| S() is the set of 5-word shingles over NFKC-casefolded \\w+ tokens (the tokenisation of the repo's near_dedup), and `novel` is the ELTeC novel sharing the most shingles with the WL doc; the shingling and scoring code is in src/shingle_containment.py. A trailing Wolne Lektury footer is cut from WL text before scoring (the #45 measurement's rule); the released text is not changed. Docs scoring >= DROP_AT are dropped. Docs scoring >= REPORT_AT but below DROP_AT are only partly in an ELTeC novel; they are kept and listed. Both groups are written to wolne_lektury.eltec_pairs.tsv. The `license` of each kept row comes from wolne_lektury.licences.tsv, which src/wolne_lektury_licences.py writes from Wolne Lektury's metadata; the build stops unless that file labels exactly the kept rows. The rows in that module's UNLICENSED, whose metadata gives no usable licence, are dropped first (stats `drop_rights`). Both input Parquets are pinned by SHA-256. Restore the WL Parquet before a rerun: git checkout v0.2.5 -- data/wolne_lektury/wolne_lektury.parquet python3 src/clean_wolne_lektury.py """ from __future__ import annotations import argparse import csv import json import os from collections import Counter from pathlib import Path import pyarrow as pa import pyarrow.compute as pc import pyarrow.parquet as pq from sejm_api_common import check_pin from shingle_containment import best_containment, strip_wl_footer from sources import SOURCES from wolne_lektury_licences import LABELS, LICENCES, UNLICENSED SOURCE = "wolne_lektury" ROOT = Path(__file__).resolve().parents[1] DATA = ROOT / "data" / SOURCE ELTEC = ROOT / "data" / "eltec_pol" / "eltec_pol.parquet" INPUT_SHA256 = "5833c25db296f2479b3c09745ebedd550b2425dd6ebaf021f0095e684a0221a1" # v0.2.1-v0.2.5 ELTEC_SHA256 = "ba40061741dff11165149f6c2cf3d5526e1b6c759e7ce1e03ccc164d58838325" # v0.2.1-v0.2.5 PAIRS = f"{SOURCE}.eltec_pairs.tsv" # Thresholds sit in empty stretches of the v0.2.5 score distribution: no doc scores between # 0.7588 and 0.9636 (above: 63 docs, the novels; below: two tomes of an abridged ELTeC # Trędowata), and none between 0.2203 and 0.4267 (below: poems quoted in a novel). DROP_AT = 0.9 REPORT_AT = 0.3 def wl_title(text: str) -> str: """Author and title: the first two non-empty lines of a Wolne Lektury text.""" return " / ".join([line.strip() for line in text.splitlines() if line.strip()][:2]) def relabel(table: pa.Table, licences_path: Path) -> pa.Table: """`table` with each row's `license` from the licences TSV, which must list exactly its rows.""" with licences_path.open(encoding="utf-8", newline="") as handle: records = list(csv.DictReader(handle, delimiter="\t")) labels = {record["id"]: record["license"] for record in records} ids = table.column("id").to_pylist() if len(labels) != len(records) or labels.keys() != set(ids): raise SystemExit(f"{licences_path.name} does not list exactly the kept rows; " "rerun src/wolne_lektury_licences.py") if not set(labels.values()) <= set(LABELS): raise SystemExit(f"{licences_path.name} has labels outside {LABELS}") return table.set_column(table.column_names.index("license"), "license", pa.array([labels[i] for i in ids], pa.string())) def drop_unlicensed(table: pa.Table) -> pa.Table: """`table` without the UNLICENSED rows, every one of which must be in it.""" unlicensed = pc.is_in(table.column("id"), pa.array(sorted(UNLICENSED))) if pc.sum(unlicensed).as_py() != len(UNLICENSED): raise SystemExit("an UNLICENSED id is not among the deduplicated rows") return table.filter(pc.invert(unlicensed)) def build(input_path: Path, eltec_path: Path, licences_path: Path, out_dir: Path) -> dict: check_pin(input_path, INPUT_SHA256, f"restore it with `git checkout v0.2.5 -- data/{SOURCE}/{SOURCE}.parquet`") check_pin(eltec_path, ELTEC_SHA256, "it is not the v0.2.5 eltec_pol Parquet") table = pq.read_table(input_path) eltec = pq.read_table(eltec_path, columns=["id", "text"]) texts = table.column("text").to_pylist() eltec_ids = eltec.column("id").to_pylist() scores = best_containment([strip_wl_footer(t) for t in texts], eltec.column("text").to_pylist()) keep, pairs = [], [] for wl_id, text, (novel, score) in zip(table.column("id").to_pylist(), texts, scores, strict=True): keep.append(score < DROP_AT) if score >= REPORT_AT: pairs.append({"wl_id": wl_id, "eltec_id": eltec_ids[novel], "score": f"{score:.4f}", "action": "drop" if score >= DROP_AT else "keep_partial", "wl_title": wl_title(text)}) deduped = table.filter(pa.array(keep)) licensed = drop_unlicensed(deduped) kept = relabel(licensed, licences_path) stats_path = out_dir / f"{SOURCE}.stats.json" stats = json.loads(stats_path.read_text(encoding="utf-8")) # keeps build_dynaword's read/drop_* counts stats.update( kept=kept.num_rows, drop_eltec_dup=table.num_rows - deduped.num_rows, drop_rights=deduped.num_rows - licensed.num_rows, chars=pc.sum(pc.utf8_length(kept.column("text"))).as_py(), tokens=pc.sum(kept.column("token_count")).as_py(), licenses=dict(sorted(Counter(kept.column("license").to_pylist()).items())), license=SOURCES[SOURCE]["license"], authors_with_value=sum(map(bool, kept.column("author").to_pylist())), input_sha256=INPUT_SHA256, eltec_sha256=ELTEC_SHA256, ) drops = ("drop_short", "drop_lang", "drop_dup", "drop_ocr", "drop_eltec_dup", "drop_rights") if stats["read"] - sum(stats[k] for k in drops) != stats["kept"]: raise SystemExit("stats drop counts do not add up to the kept rows") staged = { out_dir / f"{SOURCE}.parquet.tmp": lambda p: pq.write_table(kept, p, compression="zstd"), out_dir / f"{PAIRS}.tmp": lambda p: _write_pairs(p, pairs), 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_pairs(path: Path, pairs: list[dict]) -> None: with path.open("w", encoding="utf-8", newline="") as handle: writer = csv.DictWriter(handle, ["wl_id", "eltec_id", "score", "action", "wl_title"], delimiter="\t", lineterminator="\n") writer.writeheader() writer.writerows(sorted(pairs, key=lambda p: (p["eltec_id"], p["wl_id"]))) 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("--eltec", type=Path, default=ELTEC) parser.add_argument("--licences", type=Path, default=DATA / LICENCES) parser.add_argument("--out", type=Path, default=DATA) args = parser.parse_args() print(json.dumps(build(args.input, args.eltec, args.licences, args.out), indent=2, ensure_ascii=False)) if __name__ == "__main__": main()