#!/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. It also applies `eurlex.review.csv` (slayerlabs/polish-dynaword-v2#108, maintainer decisions 1A, 2A and 4A of 2026-10-19). A row is a candidate when one of `CANDIDATE_RULES` matches it: a (c) sign or photo credit, a UN ECE regulation, or a European Parliament stub. The review holds one hand-checked decision for every candidate and for nothing else; the build refuses to run when they disagree. Drops: third-party credits (`third_party_credit`), UN ECE regulations republished in the Official Journal (`unece_regulation`, and `unece_annex` for Council decisions whose annex is a regulation's text), and Parliament rows that hold only a divider or a title (`ep_divider_stub`, `ep_discharge_stub`). --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. The input and the review are pinned by SHA-256. The input, the v0.2.5 Parquet, predates the October 2026 rights audit and is no longer published: the release tags v0.2.0-v0.2.5 that held it were deleted after the audit. The pins record which files a rerun needs; with them in place: python3 src/clean_eurlex.py """ from __future__ import annotations import argparse import json import re import sys from collections import Counter 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 from sejm_api_common import UNPUBLISHED, check_pin, read_pinned_review # 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" REVIEW_CSV = ROOT / "data" / SOURCE / f"{SOURCE}.review.csv" INPUT_SHA256 = "5f151d57c20103f5488fd7f1b6c108311b648e4c7ed1ff02ef7a376be5c92f04" # v0.2.5 REVIEW_SHA256 = "082feea1a6d99c2b3c2680189cef4577257a454008fd3e751b45300df51fe5a2" # eurlex.review.csv 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), } # Review candidates (v2#108): name -> (pattern, characters searched or None for the whole text, # only rows shorter than this or None). Wide on purpose; the review decides each match. CANDIDATE_RULES = { "copyright_sign": (WHOLE_TEXT_RULES["copyright_sign"], None, None), "photo_permission": (re.compile(r"Wykorzystywanie\s+lub\s+powielanie[^.]{0,200}bezpośredniej\s+zgody" r"\s+właściciela\s+praw\s+autorskich"), None, None), "photo_credit": (re.compile(r"(?i)\b(?:zdjęcie|zdjęcia|fotografia|ilustracja|fot\.|photo(?:graph)?(?: by)?" r"|źródło\s+zdjęcia|autor\s+zdjęcia)\s*:"), None, None), "photo_heading": (re.compile(r"(?i)prawa\s+autorskie\s+do\s+(?:fotografii|zdjęć|ilustracji|grafik|map)" r"|(?:^|\n)\s*(?:Fotografie|Ilustracje|Zdjęcia|Okładka|Grafika|Mapa)\s*:\s*\S"), None, None), "stock_photo": (re.compile(r"(?i)\b(?:Getty\s?Images|iStock(?:photo)?|Shutterstock|Alamy|Adobe\s+Stock|Fotolia" r"|Dreamstime|Depositphotos|Pixabay|Unsplash)\b"), None, None), "unece_head": (re.compile(r"(?i:oryginaln\w+\s+(?:teksty|akty|wersje)\s+(?:EKG|ONZ))|(?i:wp29fdocstts|unece\.org/trans)" r"|ECE/TRANS/(?:WP\.?29|180)|Regulamin\s+ONZ\s+nr\s+\d+" r"|Regulamin\s+(?:nr\s+)?\d+\s+Europejskiej\s+Komisji\s+Gospodarczej" r"|Regulamin\s+EKG\s+ONZ\s+nr|Regulamin\s+nr\s+\d+\s+EKG\s+ONZ" r"|(?i:(?:Globalny|Ogólnoświatowy)\s+przepis\s+techniczny" r"|Porozumieni\w+\s+dotycząc\w+\s+przyjęcia\s+jednolitych)"), 1500, None), "unece_title": (re.compile(r"(?is)regulamin\w*\b.{0,120}?(?:ONZ|EKG|Europejskiej\s+Komisji\s+Gospodarczej)"), 400, None), "unece_body": (re.compile(r"(?:„\s*)?REGULAMIN\s+(?:ONZ\s+)?NR\s+\d+|SPIS\s+TREŚCI\s+REGULAMIN\b" r"|Jedynie\s+oryginalne\s+teksty\s+EKG"), None, None), # an Official Journal C file (Formex name C_yyyynnnPL.) that is only the "adopted texts" divider "ep_divider_stub": (re.compile(r"(?s)\AC_\d{7}PL\..*TEKSTY PRZYJĘTE"), None, 600), "ep_discharge_stub": (re.compile(r"REZOLUCJA\s+Parlamentu\s+Europejskiego\s+zawierająca\s+uwagi"), None, 800), } REVIEW_REASONS = { "drop": {"third_party_credit", "unece_regulation", "unece_annex", "ep_divider_stub", "ep_discharge_stub"}, "keep": {"not_a_credit", "eu_credit", "legal_argument", "binary_data", "eu_document", "international_agreement", "false_match"}, } 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 candidate_rules(text: str) -> list[str]: """Names of the CANDIDATE_RULES that match `text`.""" return [name for name, (pattern, window, shorter) in CANDIDATE_RULES.items() if (shorter is None or len(text) < shorter) and pattern.search(text if window is None else text[:window])] def read_review(path: Path = REVIEW_CSV, expected: str = REVIEW_SHA256) -> dict[str, tuple[str, str]]: """id -> (decision, reason) from the pinned review table.""" return read_pinned_review(path, expected, f"it is not the reviewed {REVIEW_CSV.name}", REVIEW_REASONS) def clean(path: Path = PARQUET, withhold: frozenset[str] | None = None, review: dict[str, tuple[str, str]] | None = None, old: str = OLD_LICENSE, new: str = NEW_LICENSE) -> dict: """Rewrite `license` of every row to `new`, drop the `withhold` rows and the rows the review drops, then recompute stats. `withhold` defaults to `pinned_iasb_ids()`, `review` to `read_review()`. Each row must carry the IASB notice exactly when its id is in `withhold`; any other row must match a candidate rule exactly when its id is in `review`. Every `withhold` and `review` id must be in the input. Returns the stats. """ withhold = pinned_iasb_ids() if withhold is None else withhold review = read_review() if review is None else review 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() reviewed: set[str] = set() by_reason: Counter[str] = Counter() 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(False) continue hits, decision = candidate_rules(text), review.get(doc_id) if bool(hits) != (decision is not None): raise ValueError(f"{path.name}: {doc_id} matches {hits or 'no candidate rule'} but review={decision}") if decision: reviewed.add(doc_id) if decision[0] == "drop": by_reason[decision[1]] += 1 keep.append(not decision or decision[0] != "drop") 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") if missing := review.keys() - reviewed: raise ValueError(f"{path.name}: {len(missing)} reviewed id(s) not in the input or IASB-listed, " f"e.g. {sorted(missing)[:3]}") writer.close() tmp.replace(path) except BaseException: writer.close() tmp.unlink(missing_ok=True) raise stats = normalize_one(path) stats["read"] += len(dropped) + sum(by_reason.values()) stats["drop_iasb_notice"] = len(dropped) stats["drop_review"] = sum(by_reason.values()) stats["drop_review_by_reason"] = dict(sorted(by_reason.items())) 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: check_pin(args.parquet, INPUT_SHA256, UNPUBLISHED) stats = clean(args.parquet) print(f"{SOURCE}: {stats['read']:,} -> {stats['kept']:,} docs (IASB dropped {stats['drop_iasb_notice']}, " f"review dropped {stats['drop_review_by_reason']}) | " f"{stats['tokens']:,} tokens | licences {stats['licenses']}") if __name__ == "__main__": main()