#!/usr/bin/env python3 """Drop wolne_lektury documents whose text is an eltec_pol novel (slayerlabs/polish-dynaword-v2#72). 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. 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 hashlib 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 shingle_containment import best_containment, strip_wl_footer 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 check_pin(path: Path, expected: str, restore: str) -> None: with path.open("rb") as stream: if hashlib.file_digest(stream, "sha256").hexdigest() != expected: raise SystemExit(f"{path} does not match the pinned SHA-256; {restore}") def build(input_path: Path, eltec_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)}) kept = table.filter(pa.array(keep)) 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 - kept.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())), 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") 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("--out", type=Path, default=DATA) args = parser.parse_args() print(json.dumps(build(args.input, args.eltec, args.out), indent=2, ensure_ascii=False)) if __name__ == "__main__": main()