#!/usr/bin/env python3 """eurlex rights-audit actions (slayerlabs/polish-dynaword-v2#57). clean (default): the v0.2.5 release labelled every row `CC-BY-4.0`. The EUR-Lex legal notice licenses under CC BY 4.0 only "the editorial content of this website, the summaries of EU legislation and the consolidated texts"; the legal documents themselves are reusable under the Commission's reuse policy (Decision 2011/833/EU). Rewrites the per-row `license` column to `LicenseRef-EU-Reuse-Policy`, drops the 92 hand-checked documents carrying the IASB notice (all rights reserved outside the EEA; maintainer decision 2026-10-06), and recomputes `eurlex.stats.json` with `normalize_schema.normalize_one`. No kept row is edited except its `license`. Raises, and leaves the parquet as it was, if any row carries a licence other than the old or the new label, if a row carries the IASB notice but is not in the pinned list, or if a pinned id is missing from the input or lacks the notice. --scan: report-only count of documents the notice's third-party / special-conditions exclusions may reach, read from the v0.2.5 input. Writes `data/eurlex/eurlex.third-party-scan.json`, whose `iasb_notice_ids` is the pinned drop list; it refuses to change a pinned list. The regexes are heuristics: counts are lower bounds on what they target, and recall for third-party text they do not target is unknown. Restore the v0.2.5 input before a rerun (sha256 5f151d57c20103f5488fd7f1b6c108311b648e4c7ed1ff02ef7a376be5c92f04): git checkout 3bab9f9 -- data/eurlex/eurlex.parquet python3 src/clean_eurlex.py """ from __future__ import annotations import argparse import json import re import sys from pathlib import Path import pyarrow as pa import pyarrow.compute as pc import pyarrow.parquet as pq sys.path.insert(0, str(Path(__file__).resolve().parent)) from normalize_schema import normalize_one # noqa: E402 SOURCE = "eurlex" ROOT = Path(__file__).resolve().parents[1] PARQUET = ROOT / "data" / SOURCE / f"{SOURCE}.parquet" SCAN_JSON = ROOT / "data" / SOURCE / f"{SOURCE}.third-party-scan.json" OLD_LICENSE, NEW_LICENSE = "CC-BY-4.0", "LicenseRef-EU-Reuse-Policy" BATCH = 8192 # same as normalize_schema, so the row groups match # Whole-text rule. The IASB's notice in the IAS/IFRS adopting acts and their consolidated # versions: reproduction allowed in the EEA, "all rights reserved outside the EEA" (worded # "Wszystkie istniejące prawa [są] zastrzeżone poza EOG" or "Wszelkie prawa zastrzeżone poza EOG"). WHOLE_TEXT_RULES = { "iasb_notice": re.compile(r"zastrze[żz]one\s+poza\s+EOG"), "copyright_sign": re.compile("©"), } # Header-window rules: documents whose first HEADER characters mark an author other than the Commission. HEADER = 3000 HEADER_RULES = { "ecb_act": re.compile(r"\((EBC|CON)/\d{4}/\d+\)"), "eesc": re.compile(r"EESC[-_ ]\d{4}|Opinia Europejskiego Komitetu Ekonomiczno-Społecznego" r"|Europejski Komitet Ekonomiczno-Społeczny"), "state_aid_sa": re.compile(r"\bSA\.\d{4,6}\b"), "un_ece_regulation": re.compile(r"Regulamin\w* nr \d+[^\n]{0,80}(Europejskiej Komisji Gospodarczej|EKG ONZ)", re.I), } def pinned_iasb_ids(path: Path = SCAN_JSON) -> frozenset[str]: """The hand-checked IASB-notice ids recorded by --scan on the v0.2.5 input.""" return frozenset(json.loads(path.read_text())["iasb_notice_ids"]) def clean(path: Path = PARQUET, withhold: frozenset[str] | None = None, old: str = OLD_LICENSE, new: str = NEW_LICENSE) -> dict: """Rewrite `license` of every row to `new`, drop the `withhold` rows, then recompute stats. `withhold` defaults to `pinned_iasb_ids()`. Each row must carry the IASB notice exactly when its id is in `withhold`, and every `withhold` id must be in the input. Returns the stats. """ withhold = pinned_iasb_ids() if withhold is None else withhold iasb = WHOLE_TEXT_RULES["iasb_notice"] tmp = path.with_suffix(".parquet.tmp") pf = pq.ParquetFile(path) schema = pf.schema_arrow index = schema.get_field_index("license") writer = pq.ParquetWriter(tmp, schema, compression="zstd") dropped: set[str] = set() try: for batch in pf.iter_batches(batch_size=BATCH): tbl = pa.Table.from_batches([batch]) found = set(pc.unique(tbl["license"]).to_pylist()) if not found <= {old, new}: raise ValueError(f"{path.name}: unexpected licence(s) {sorted(map(str, found - {old, new}))}") keep = [] for doc_id, text in zip(tbl["id"].to_pylist(), tbl["text"].to_pylist()): notice, listed = iasb.search(text) is not None, doc_id in withhold if notice != listed: raise ValueError(f"{path.name}: {doc_id} has IASB notice={notice} but pinned={listed}") if listed: dropped.add(doc_id) keep.append(not listed) tbl = tbl.filter(pa.array(keep)) tbl = tbl.set_column(index, schema.field(index), pa.array([new] * tbl.num_rows, type=pa.string())) writer.write_table(tbl) if missing := withhold - dropped: raise ValueError(f"{path.name}: {len(missing)} pinned id(s) not in the input, e.g. {sorted(missing)[:3]}; " "restore the v0.2.5 input first") writer.close() tmp.replace(path) except BaseException: writer.close() tmp.unlink(missing_ok=True) raise stats = normalize_one(path) stats["read"] += len(dropped) stats["drop_iasb_notice"] = len(dropped) path.with_name(f"{SOURCE}.stats.json").write_text(json.dumps(stats, ensure_ascii=False, indent=2) + "\n") return stats def scan(path: Path = PARQUET) -> dict: """Count documents matching each rule. Report-only.""" pf = pq.ParquetFile(path) rules = {**{k: (v, False) for k, v in WHOLE_TEXT_RULES.items()}, **{k: (v, True) for k, v in HEADER_RULES.items()}} out = {k: {"docs": 0, "chars": 0} for k in rules} iasb_ids: list[str] = [] rows = chars = 0 for batch in pf.iter_batches(batch_size=BATCH, columns=["id", "text"]): for doc_id, text in zip(batch["id"].to_pylist(), batch["text"].to_pylist()): rows += 1 chars += len(text) for name, (pattern, header_only) in rules.items(): if pattern.search(text[:HEADER] if header_only else text): out[name]["docs"] += 1 out[name]["chars"] += len(text) if name == "iasb_notice": iasb_ids.append(doc_id) for name, (pattern, header_only) in rules.items(): out[name]["pattern"] = pattern.pattern out[name]["window"] = f"first {HEADER} characters" if header_only else "whole text" out[name]["share_of_chars"] = round(out[name]["chars"] / chars, 5) return {"rows": rows, "chars": chars, "rules": out, "iasb_notice_ids": sorted(iasb_ids)} def main() -> None: ap = argparse.ArgumentParser(description=__doc__.split("\n")[0]) ap.add_argument("--scan", action="store_true", help="write the report-only third-party scan instead of relabelling") ap.add_argument("--parquet", type=Path, default=PARQUET) args = ap.parse_args() if args.scan: result = scan(args.parquet) if SCAN_JSON.exists() and (pinned := pinned_iasb_ids(SCAN_JSON)) and pinned != set(result["iasb_notice_ids"]): raise SystemExit(f"{SCAN_JSON.name} pins {len(pinned)} IASB ids, this input has " f"{len(result['iasb_notice_ids'])}: --scan reads the v0.2.5 input (see the docstring)") SCAN_JSON.write_text(json.dumps(result, ensure_ascii=False, indent=2) + "\n") print(json.dumps({k: v for k, v in result.items() if k != "iasb_notice_ids"}, ensure_ascii=False, indent=2)) else: stats = clean(args.parquet) print(f"{SOURCE}: {stats['read']:,} -> {stats['kept']:,} docs (IASB dropped {stats['drop_iasb_notice']}) | " f"{stats['tokens']:,} tokens | licences {stats['licenses']}") if __name__ == "__main__": main()