#!/usr/bin/env python3 """Mask the phone numbers left in kultura_bez_barier_pl (v0.2.6 rights audit, slayerlabs/polish-dynaword-v2#57). The builder's labelled-phone regex missed "Tel./SMS", "tel:", "+ 48" and landlines with "wew.", so the accessibility-coordinator directory in `podsumowanie_wizyt_studyjnych` shipped with names and phone numbers. The builder now runs a second pass with ted_pl's patterns on retained records (`redact_wider_pii`). The raw PDFs are not in this repo, so this script applies that same pass to the published text instead of rebuilding it: the first pass already ran on it, and the second pass runs last in build(), so the output is what build() now produces from the pinned PDFs (not re-checked against them here). Rewritten: the Parquet `text` and `token_count`, the attribution `text_sha256` and `transformations`, the sample, stats `tokens`/`characters`, qa `pii_pattern_matches`, and the ontology manifest, which gains a run, a dataset version and checksum/qa evidence for the new files (computed last, so edit the builder and the test first). The input is the Parquet and sidecars as contributed in PR #27 (unchanged since), pinned by SHA-256. Restore them before a rerun: git checkout 7444b7d -- 'data/kultura_bez_barier_pl/*.parquet' 'data/kultura_bez_barier_pl/*.jsonl' \ 'data/kultura_bez_barier_pl/*.json' artifacts/kultura_bez_barier_pl_ontology_manifest.json python3 src/clean_kultura_bez_barier_pl.py """ from __future__ import annotations from collections import Counter import json import os from pathlib import Path import sys import pyarrow as pa import pyarrow.parquet as pq import tiktoken sys.path.insert(0, str(Path(__file__).resolve().parent)) from build_kultura_bez_barier_pl import SOURCE, WIDER_PII_STEP, now, read_lines, redact_wider_pii, sha # noqa: E402 ROOT = Path(__file__).resolve().parents[1] DATA = ROOT / "data" / SOURCE MANIFEST = ROOT / "artifacts" / f"{SOURCE}_ontology_manifest.json" INPUT_SHA256 = { DATA / f"{SOURCE}.parquet": "1d9cd403ab297b3a8a84ce6ae7a25e4f4fd5025b37be959e4692a5170ed64642", DATA / f"{SOURCE}.attribution.jsonl": "4e592737d4d9c93a67c6437d5ad3881e92f8fb9aec62064eaaa84625144cf538", DATA / f"{SOURCE}.sample.jsonl": "9ce1a4cc8f2b6a8882f1a795d3b7f8bbb133c9c81ae6507830bb7b2a2f1bd7e5", DATA / f"{SOURCE}.stats.json": "5fc1c11510ed0536bb3a4f2c86397006642911d8542c9c28bc88dacefa392ac3", DATA / f"{SOURCE}.qa.json": "3946eb001b0f43248a54256099ff98021cf14eec4e9e94c402210f88563ead58", MANIFEST: "2e7c26bb3985c1a2255bef59bf02675b2dc09bf127717d4bf02f8ce09b4268dc", } OLD_TRANSFORMATIONS = ["pdfplumber page text extraction", "page-number removal", "line-wrap and hyphen repair", "Unicode and whitespace normalization", "email and labelled-phone redaction"] SAMPLE_SIZE = 12 PROTOCOL = {"id": "protocol:pii-rescrub-v1", "procedure": "src/clean_kultura_bez_barier_pl.py: the builder's second PII pass (ted_pl patterns) applied " "to the published text; token counts, attribution text hashes, sample, stats and qa recomputed"} def lines(rows: list[dict]) -> str: return "".join(json.dumps(row, ensure_ascii=False, sort_keys=True) + "\n" for row in rows) def dump(value: dict) -> str: return json.dumps(value, ensure_ascii=False, sort_keys=True, indent=2) + "\n" def crlf(text: str) -> bytes: """The contributed text files use CRLF (written on Windows); keep it so the diff shows only the changes.""" return text.replace("\n", "\r\n").encode("utf-8") def rescrub(rows: list[dict], attribution: list[dict]) -> tuple[list[dict], list[dict], Counter]: """Rows and attribution after the second pass, plus its hit counts keyed as build() keys them.""" if [row["id"] for row in rows] != [item["id"] for item in attribution]: raise SystemExit("Parquet and attribution sidecar do not list the same ids in the same order") encoder = tiktoken.get_encoding("cl100k_base") counts, new_rows, new_attribution = Counter(), [], [] for row, item in zip(rows, attribution): if item["transformations"] != OLD_TRANSFORMATIONS or item["text_sha256"] != sha(row["text"].encode()): raise SystemExit(f"{row['id']}: attribution does not describe the PR #27 text") text, wider = redact_wider_pii(row["text"]) counts.update({"ted_pl_" + name: hits for name, hits in wider.items()}) new_rows.append({**row, "text": text, "token_count": len(encoder.encode_ordinary(text))}) new_attribution.append({**item, "text_sha256": sha(text.encode()), "transformations": OLD_TRANSFORMATIONS + [WIDER_PII_STEP]}) return new_rows, new_attribution, counts def manifest_update(manifest: dict, files: dict[str, bytes], qa: dict, run: dict) -> dict: """`manifest` plus a run, a dataset version and evidence for `files` (manifest path -> new bytes).""" old_checks = next(item for item in manifest["evidence"] if item["observation_type"] == "checksums") if unknown := files.keys() - old_checks["payload"].keys(): raise SystemExit(f"not in the manifest checksums: {sorted(unknown)}") checks = {**old_checks["payload"], **{name: sha(data) for name, data in files.items()}} old_version = next(item["id"] for item in manifest["versions"] if item["object"] == "object:dataset:kultura-bez-barier-pl" and item["content_address"] == sha(old_checks["payload"])) version = "version:dataset:" + sha(checks) check_id, qa_id = "evidence:checksums:" + sha(checks), "evidence:qa:" + sha(qa) supported = {"claim:replayable": [check_id], "claim:rights-qualified": [qa_id]} return {**manifest, "protocols": manifest["protocols"] + [PROTOCOL], "runs": manifest["runs"] + [run], "versions": manifest["versions"] + [{"id": version, "object": "object:dataset:kultura-bez-barier-pl", "content_address": sha(checks)}], "evidence": manifest["evidence"] + [ {"id": check_id, "observation_type": "checksums", "payload": checks, "produced_by": run["id"]}, {"id": qa_id, "observation_type": "qa", "payload": qa, "produced_by": run["id"]}], "claims": [{**claim, "supported_by": supported[claim["id"]]} for claim in manifest["claims"]], "relations": manifest["relations"] + [ {"source": version, "predicate": "DERIVED_FROM", "target": old_version}, {"source": version, "predicate": "GENERATED_BY", "target": run["id"]}], "pending": manifest["pending"] + ["replay of the v0.2.6 second PII pass from the raw PDFs (applied offline " "to the published text)"]} def main() -> None: for path, expected in INPUT_SHA256.items(): if sha(path.read_bytes()) != expected: raise SystemExit(f"{path} is not the PR #27 input; restore it with the command in this script's docstring") started = now() table = pq.read_table(DATA / f"{SOURCE}.parquet") rows, attribution, counts = rescrub(table.to_pylist(), read_lines(DATA / f"{SOURCE}.attribution.jsonl")) samples = sorted(rows, key=lambda row: sha(("sample:" + row["id"]).encode()))[:SAMPLE_SIZE] stats = {**json.loads((DATA / f"{SOURCE}.stats.json").read_text(encoding="utf-8")), "tokens": sum(row["token_count"] for row in rows), "characters": sum(len(row["text"]) for row in rows)} qa = json.loads((DATA / f"{SOURCE}.qa.json").read_text(encoding="utf-8")) qa["pii_pattern_matches"] = {**qa["pii_pattern_matches"], **counts} sink = pa.BufferOutputStream() pq.write_table(pa.Table.from_pylist(rows, schema=table.schema), sink, compression="zstd") staged = { # manifest path -> (repo path, bytes) "data/train-00000-of-00001.parquet": (DATA / f"{SOURCE}.parquet", sink.getvalue().to_pybytes()), "artifacts/attribution.jsonl": (DATA / f"{SOURCE}.attribution.jsonl", crlf(lines(attribution))), "artifacts/sample.jsonl": (DATA / f"{SOURCE}.sample.jsonl", crlf(lines(samples))), "artifacts/stats.json": (DATA / f"{SOURCE}.stats.json", crlf(dump(stats))), "artifacts/qa.json": (DATA / f"{SOURCE}.qa.json", crlf(dump(qa))), } code = {name: (ROOT / name).read_bytes() for name in ("src/build_kultura_bez_barier_pl.py", "src/test_kultura_bez_barier_contribution.py")} run = {"id": "run:" + sha({"script": sha(Path(__file__).read_bytes()), "builder": sha(code["src/build_kultura_bez_barier_pl.py"]), "inputs": sorted(INPUT_SHA256.values())}), "protocol": PROTOCOL["id"], "started_at": started, "finished_at": now(), "success": True} manifest = manifest_update(json.loads(MANIFEST.read_text(encoding="utf-8")), {**{name: data for name, (_, data) in staged.items()}, **code}, qa, run) staged["manifest"] = (MANIFEST, crlf(dump(manifest))) for path, data in staged.values(): path.with_name(path.name + ".tmp").write_bytes(data) for path, _ in staged.values(): os.replace(path.with_name(path.name + ".tmp"), path) print(json.dumps({"pii_pattern_matches": qa["pii_pattern_matches"], "tokens": stats["tokens"], "characters": stats["characters"], "changed_rows": [r["id"] for r, o in zip(rows, table.to_pylist()) if r["text"] != o["text"]]}, indent=2)) if __name__ == "__main__": main()