#!/usr/bin/env python3 """Build an auditable slice of Polish Wikipedia talk pages (ns 1+5, CC BY-SA 4.0).""" from __future__ import annotations import argparse import bz2 from collections import Counter from concurrent.futures import ProcessPoolExecutor from datetime import datetime, timezone from difflib import SequenceMatcher import gzip import hashlib import ipaddress import json from pathlib import Path import re import time import unicodedata from xml.etree.ElementTree import iterparse from urllib.parse import quote import requests SOURCE = "plwiki_talk" OWN_REPO = "PiotrSty/plwiki-talk-pages" TARGET = "SlayerLab/polish-dynaword" DUMP_DATE = "20260901" DUMP_BASE = f"https://dumps.wikimedia.org/plwiki/{DUMP_DATE}" DUMPSTATUS_URL = DUMP_BASE + "/dumpstatus.json" INDEX_URL = "https://dumps.wikimedia.org/plwiki/" SOURCE_URL = "https://pl.wikipedia.org/" FIELDS = ["id", "text", "source", "added", "created", "token_count", "license", "author"] UA = {"User-Agent": "polish-dynaword/0.2 (+research; openly-licensed corpus)"} LICENSE_SPDX = "CC-BY-SA-4.0" LICENSE_TERMS_URL = "https://foundation.wikimedia.org/w/index.php?title=Policy:Terms_of_Use/pl&oldid=584706" TALK_NS = {"1", "5"} MIN_TEXT_CHARS = 500 BOILERPLATE_MIN_DOC_FREQ = 0.01 EMAIL_RE = re.compile(r"(?i)\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b") PHONE_RE = re.compile(r"(?i)(?:\btelefon|\btel\.|\bphone)\s*:?[ \t]*(?:\+48[ \t]*)?\d(?:[ .-]?\d){8}\b") IPV4_RE = re.compile(r"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b") IPV6_RE = re.compile(r"(?i)\b(?:[0-9a-f]{1,4}:){3,}[0-9a-f]{1,4}\b") IPV6_CANDIDATE_RE = re.compile(r"(?= BOILERPLATE_MIN_DOC_FREQ and len(line) < 160} def normalize(text): text = unicodedata.normalize("NFKC", text or "").replace("­", "").replace("​", "") text = re.sub(r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]", "", text) lines = [re.sub(r"[ \t\xa0]+", " ", line).strip() for line in text.splitlines()] lines = [line for line in lines if not re.fullmatch(r"\d{1,4}", line)] text = "\n".join(lines) text = re.sub(r"(?<=\w)-\n(?=[a-ząćęłńóśźż])", "", text) text = re.sub(r"(? limit: return set(sorted(hashes)[:limit]) return hashes class NearDuplicateIndex: def __init__(self): self.postings = {} self.records = [] self.comparisons = 0 @staticmethod def prefix(sketch): return sorted(sketch)[:len(sketch) - (9 * len(sketch) + 9) // 10 + 1] def find(self, sketch): candidates = set() for value in self.prefix(sketch): candidates.update(self.postings.get(value, ())) for position in sorted(candidates): row_id, other = self.records[position] if 10 * min(len(sketch), len(other)) < 9 * max(len(sketch), len(other)): continue self.comparisons += 1 intersection = len(sketch & other) score = intersection / max(len(sketch) + len(other) - intersection, 1) if score >= 0.90: return row_id, score return None, 0.0 def add(self, row_id, sketch): position = len(self.records) self.records.append((row_id, sketch)) for value in self.prefix(sketch): self.postings.setdefault(value, []).append(position) def language_vote(identifier, text): chunks = [text[:30_000], text[max(0, len(text) // 2 - 15_000):len(text) // 2 + 15_000], text[-30_000:]] classified = {chunk: identifier.classify(chunk) for chunk in dict.fromkeys(chunks) if chunk.strip()} votes = [classified[chunk] for chunk in chunks if chunk in classified] languages = Counter(language for language, _ in votes) return (languages.most_common(1)[0][0] if languages else "unknown", votes) def audit_target(out): info = request_json(f"https://huggingface.co/api/datasets/{TARGET}") revision = info["sha"] tree = request_json(f"https://huggingface.co/api/datasets/{TARGET}/tree/{revision}?recursive=true&expand=false") discussions = request_json(f"https://huggingface.co/api/datasets/{TARGET}/discussions?status=open&p=0") paths = sorted(item.get("path", "") for item in tree) open_rows = [{"num": item.get("num"), "title": item.get("title"), "status": item.get("status"), "author": item.get("author", {}).get("name")} for item in discussions.get("discussions", [])] terms = ("plwiki_talk", "wikipedia_talk", "talk", "dyskusja") matches = [path for path in paths if any(term in path.casefold() for term in terms)] discussion_matches = [row for row in open_rows if any(term in (row.get("title") or "").casefold() for term in terms)] report = { "target": TARGET, "revision": revision, "last_modified": info.get("lastModified"), "tree_paths": len(paths), "source_path_matches": matches, "open_discussions": open_rows, "matching_open_discussions": discussion_matches, "source_absent": not matches and not discussion_matches, "observed_at": now(), } save(out / "target_audit.json", report) print(json.dumps({"revision": revision, "source_absent": report["source_absent"], "tree_matches": matches, "discussion_matches": discussion_matches}, ensure_ascii=False, indent=2)) def audit_overlap(out): import pyarrow.parquet as pq from huggingface_hub import HfApi, HfFileSystem acquisition = load(out / "acquisition.json") revision = HfApi().dataset_info(TARGET).sha remote = f"datasets/{TARGET}@{revision}/data/wikipedia/wikipedia.parquet" with HfFileSystem().open(remote, "rb") as handle: table = pq.read_table(handle, columns=["id"]) target_ids = set(table.column("id").to_pylist()) candidate_ids = {f"{SOURCE}_{row['pageid']}" for row in read_lines(out / "source_manifest.jsonl")} collisions = sorted(candidate_ids & target_ids) report = { "target": f"{TARGET}:data/wikipedia", "target_revision": revision, "method": "Literal dataset-record ID comparison only. Source-specific ID prefixes make zero collisions " "uninformative about page identity or text overlap. No target namespace or text audit was performed.", "target_rows": table.num_rows, "candidate_records": len(candidate_ids), "id_collisions": collisions[:50], "collision_count": len(collisions), "text_overlap": "not tested; quoted-article passages and target-wide text dedup remain integration gates", "observed_at": now(), } save(out / "overlap_audit.json", report) print(json.dumps({key: report[key] for key in ("target_revision", "target_rows", "candidate_records", "collision_count")}, ensure_ascii=False, indent=2)) def build(out): import pyarrow as pa import pyarrow.parquet as pq import tiktoken from langid.langid import LanguageIdentifier, model build_started_at = now() acquisition = load(out / "acquisition.json") selection = load(out / "selection.json") encoder = tiktoken.get_encoding("cl100k_base") identifier = LanguageIdentifier.from_modelstring(model, norm_probs=True) identifier.set_languages(["pl", "en", "de", "uk", "ru"]) candidates = [] for shard in sorted((out / "extracted").glob("*.jsonl.gz")): with gzip.open(shard, "rt", encoding="utf-8") as f: for line in f: row = json.loads(line) row["text"] = normalize(row["text"]) candidates.append(row) boilerplate = strip_boilerplate([row["text"].splitlines() for row in candidates]) print(f"boilerplate lines: {len(boilerplate)}", flush=True) rows, attribution, decisions, exact_seen = [], [], [], {} near_index = NearDuplicateIndex() pii = Counter() added = acquisition["observed_at"][:10] started = last_progress = time.monotonic() for processed, record in enumerate(candidates, 1): current = time.monotonic() if current - last_progress >= 10 or processed == len(candidates): print(f" processed={processed - 1}/{len(candidates)} kept={len(rows)} " f"rate={(processed - 1) / max(current - started, 0.001):.1f}/s " f"near_comparisons={near_index.comparisons}", flush=True) last_progress = current text = "\n".join(line for line in record["text"].splitlines() if re.sub(r"\s+", " ", line).strip() not in boilerplate) text = re.sub(r"\n{3,}", "\n\n", text).strip() replacement_count = text.count("\ufffd") letters = len(re.findall(r"[A-Za-zĄĆĘŁŃÓŚŹŻąćęłńóśźż]", text)) language, votes = "not_checked", [] reason = "" if len(text) < MIN_TEXT_CHARS: reason = "too_little_text" elif letters / max(len(text), 1) < 0.5: reason = "low_letter_ratio" elif replacement_count > 100 or replacement_count / max(len(text), 1) > 0.002: reason = "excessive_replacement_characters" if not reason: language, votes = language_vote(identifier, text) if language != "pl": reason = "non_polish_text" text = text.replace("\ufffd", "[UNREADABLE_GLYPH]") text, pii_counts = redact_pii(text) pii.update(pii_counts) if not reason and len(text) < MIN_TEXT_CHARS: reason = "too_little_text_after_redaction" exact_key = digest(" ".join(text.casefold().split()).encode("utf-8")) duplicate_of, duplicate_score = None, 0.0 if not reason and exact_key in exact_seen: reason, duplicate_of, duplicate_score = "normalized_duplicate", exact_seen[exact_key], 1.0 if not reason: sketch = shingle_sketch(text) duplicate_of, duplicate_score = near_index.find(sketch) if duplicate_of is not None: reason = "near_duplicate" row_id = f"{SOURCE}_{record['pageid']}" decision = { "id": row_id, "selected": not bool(reason), "reason": reason or "include", "characters": len(text), "letter_ratio": letters / max(len(text), 1), "replacement_characters": replacement_count, "language": language, "language_votes": [{"language": lang, "confidence": float(score)} for lang, score in votes], } if duplicate_of: decision.update({"duplicate_of": duplicate_of, "jaccard": duplicate_score}) decisions.append(decision) if reason: continue exact_seen[exact_key] = row_id near_index.add(row_id, sketch) row = { "id": row_id, "text": text, "source": SOURCE, "added": added, "created": (record["timestamp"] or "")[:10] or "unknown", "token_count": len(encoder.encode_ordinary(text)), "license": LICENSE_SPDX, "author": "plwiki contributors", } rows.append(row) attribution.append({ "id": row_id, "pageid": record["pageid"], "ns": record["ns"], "title": record["title"], "url": page_url(record["title"]), "last_revision_at": record["timestamp"], "wikitext_chars": record["wikitext_chars"], "license": LICENSE_SPDX, "license_evidence": LICENSE_TERMS_URL + " (section 7, text licensing and attribution by page URL)", "dump": {"date": selection["dump_date"], "files": [f["name"] for f in selection["files"]]}, "text_sha256": digest(text.encode("utf-8")), "transformations": ["official pages-meta-current dump", "mwparserfromhell wikitext strip", "cross-document boilerplate-line removal", "Unicode/whitespace normalization", "page-number-only removal", "line-wrap repair", "email/labelled-phone/IP/labelled-national-ID/account-candidate pattern redaction"], }) root = out / "hf_repo" (root / "data").mkdir(parents=True, exist_ok=True) (root / "artifacts").mkdir(parents=True, exist_ok=True) schema = pa.schema([(field, pa.int64() if field == "token_count" else pa.string()) for field in FIELDS]) pq.write_table(pa.Table.from_pylist(rows, schema=schema), root / "data/train-00000-of-00001.parquet", compression="zstd") write_lines(root / "artifacts/attribution.jsonl", attribution) write_lines(root / "artifacts/decisions.jsonl", decisions) write_lines(root / "artifacts/source_manifest.jsonl", read_lines(out / "source_manifest.jsonl")) sample = sorted(rows, key=lambda row: digest(("sample:" + row["id"]).encode("utf-8")))[:12] write_lines(root / "artifacts/sample.jsonl", sample) save(root / "artifacts/selection.json", selection) save(root / "artifacts/acquisition.json", acquisition) save(root / "artifacts/boilerplate_lines.json", sorted(boilerplate)) overlap = load(out / "overlap_audit.json") if (out / "overlap_audit.json").exists() else None target_audit = load(out / "target_audit.json") if (out / "target_audit.json").exists() else None if overlap: save(root / "artifacts/overlap_audit.json", overlap) if target_audit: save(root / "artifacts/target_audit.json", target_audit) stats = { "dump_date": selection["dump_date"], "dump_files": len(selection["files"]), "talk_pages": acquisition["talk_pages"], "kept": len(rows), "rejected": len(decisions) - len(rows), "tokens": sum(row["token_count"] for row in rows), "characters": sum(len(row["text"]) for row in rows), "license_counts": dict(Counter(row["license"] for row in rows)), "boilerplate_lines_removed": len(boilerplate), "sample_count": len(sample), "added": added, } qa = { "scope": "Polish Wikipedia article-talk (ns=1) and project-talk (ns=5) pages from the pinned pages-meta-current dump", "license_terms_url": LICENSE_TERMS_URL, "license_gate": "Wikimedia Terms of Use section 7: CC BY-SA 4.0 and page-URL attribution; third-party notices still require review", "rejection_counts": dict(Counter(item["reason"] for item in decisions if not item["selected"])), "minimum_final_text_characters": MIN_TEXT_CHARS, "created_field_semantics": "Last revision date from the dump, not the page creation date", "language_gate": "independent three-window langid vote", "pii_pattern_matches": dict(pii), "exact_dedup": True, "pii_policy": "IPv6 parsed including compressed notation; labelled PESEL/NIP/REGON and 26-digit account candidates masked conservatively without checksum validation; counts cover all candidates before rejection", "pii_limitations": "Unlabelled national identifiers, free-form phone numbers, names and personal disclosures may remain; this is not complete anonymization", "near_dedup": "deterministic capped 5-word-shingle hash Jaccard >= 0.90 within source", "boilerplate": f"lines occurring in >= {BOILERPLATE_MIN_DOC_FREQ:.0%} of documents removed ({len(boilerplate)} patterns)", "wikipedia_shard_overlap": overlap or "pending", "cross_source_text_dedup": "pending target integration", "benchmark_overlap": "pending", "limitations": [ "talk pages contain informal text with typos, edit disputes and occasional abuse/vandalism", "user-talk namespace (ns=3) excluded by scope decision; its quality was not measured", "comments may quote article text; quoted passages are not disjoint from the wikipedia shard", "record model is a whole talk page; individual comments are not split", "pattern checks are not comprehensive de-identification", ], } save(root / "artifacts/stats.json", stats) save(root / "artifacts/qa.json", qa) protocol_id = "protocol:plwiki-talk-v1" run = { "id": "run:" + digest({"script": digest(Path(__file__).read_bytes()), "selection": selection, "acquisition": digest(acquisition)}), "protocol": protocol_id, "started_at": build_started_at, "finished_at": now(), "success": True, "actor": "actor:devin", "stats": stats, } save(root / "artifacts/run.json", run) excluded = {"README.md", "NOTICE.md", "artifacts/checksums.json", "artifacts/ontology.json"} checks = {path.relative_to(root).as_posix(): digest(path.read_bytes()) for path in sorted(root.rglob("*")) if path.is_file() and path.relative_to(root).as_posix() not in excluded and not path.relative_to(root).as_posix().startswith("src/")} save(root / "artifacts/checksums.json", checks) source_version = "version:source:" + digest(selection["files"]) dataset_version = "version:dataset:" + digest(checks) selection_evidence = "evidence:selection:" + digest(selection) acquisition_evidence = "evidence:acquisition:" + digest(acquisition) qa_evidence = "evidence:qa:" + digest(qa) evidence = [ {"id": selection_evidence, "observation_type": "dump_inventory_and_pinning", "artifact": "artifacts/selection.json", "content_address": digest(selection), "produced_by": run["id"]}, {"id": acquisition_evidence, "observation_type": "dump_download_sha1_and_extraction", "artifact": "artifacts/acquisition.json", "content_address": digest(acquisition), "produced_by": run["id"]}, {"id": qa_evidence, "observation_type": "source_qa", "artifact": "artifacts/qa.json", "content_address": digest(qa), "produced_by": run["id"]}, ] overlap_evidence = None if overlap: overlap_evidence = "evidence:overlap:" + digest(overlap) evidence.append({"id": overlap_evidence, "observation_type": "namespace_overlap_audit", "artifact": "artifacts/overlap_audit.json", "content_address": digest(overlap), "produced_by": run["id"]}) target_evidence = None if target_audit: target_evidence = "evidence:target:" + digest(target_audit) evidence.append({"id": target_evidence, "observation_type": "target_registry_audit", "artifact": "artifacts/target_audit.json", "content_address": digest(target_audit), "produced_by": run["id"]}) ontology = { "schema": "slayer-research-ontology-profile-v1", "objects": [{"id": "object:source:plwiki-dump-" + selection["dump_date"], "type": "Source"}, {"id": "object:dataset:plwiki-talk", "type": "Dataset"}], "versions": [{"id": source_version, "object": "object:source:plwiki-dump-" + selection["dump_date"], "content_address": source_version.rsplit(":", 1)[-1]}, {"id": dataset_version, "object": "object:dataset:plwiki-talk", "content_address": dataset_version.rsplit(":", 1)[-1]}], "protocols": [{"id": protocol_id, "procedure": "pinned dump; sha1-verified shards; namespaces 1+5; wikitext strip; boilerplate removal; normalization; PII patterns; exact and near dedup"}], "runs": [run], "evidence": evidence, "claims": [ {"id": "claim:talk-pages-observed", "statement": f"The pinned dump {selection['dump_date']} yielded {acquisition['talk_pages']} non-redirect talk pages in namespaces 1 and 5.", "supported_by": [selection_evidence, acquisition_evidence], "falsification_condition": "The pinned dump shards do not reproduce the count."}, {"id": "claim:slice-retention", "statement": f"The slice retained {stats['kept']} records after text QA and within-source deduplication.", "supported_by": [acquisition_evidence, qa_evidence], "falsification_condition": "The decisions, Parquet rows, or checksums do not reproduce the retention count."}, {"id": "claim:source-absence-at-audit", "statement": "Talk-namespace Wikipedia content was not registered as a source in the pinned DynaWord data tree or open pull-request list at audit time.", "supported_by": [target_evidence] if target_evidence else [qa_evidence], "falsification_condition": "The pinned target evidence contains a matching source or proposal."}, {"id": "claim:training-value-untested", "statement": "Net corpus novelty and training benefit remain untested hypotheses.", "supported_by": [qa_evidence] + ([overlap_evidence] if overlap_evidence else []), "falsification_condition": "Target-wide text deduplication and controlled ablations establish those properties."}, ], "actors": [{"id": "actor:piotrsty", "type": "Contributor"}, {"id": "actor:wikimedia", "type": "Organization"}, {"id": "actor:devin", "type": "Agent"}], "relations": [{"source": dataset_version, "predicate": "DERIVED_FROM", "target": source_version}, {"source": dataset_version, "predicate": "GENERATED_BY", "target": run["id"]}] + ([{"source": dataset_version, "predicate": "VALIDATED_AGAINST", "target": f"hf:dataset:{TARGET}@{target_audit['revision']}"}] if target_audit else []), "pending": ["quoted-article-fragment dedup vs wikipedia shard", "cross-source text deduplication", "benchmark contamination check", "abuse/vandalism content screening", "controlled training ablation"], } save(root / "artifacts/ontology.json", ontology) card = f"""--- license: cc-by-sa-4.0 language: - pl task_categories: - text-generation configs: - config_name: default data_files: - split: train path: data/train-00000-of-00001.parquet --- # Polish Wikipedia talk pages (plwiki, namespaces 1+5) Article-talk and project-talk pages from the pinned `plwiki-{selection['dump_date']}-pages-meta-current` dump (https://dumps.wikimedia.org/plwiki/{selection['dump_date']}/). The source selects namespaces 1 and 5; zero collisions of source-prefixed record IDs do not establish disjointness from the target `wikipedia` shard. Target-wide text deduplication remains pending. This is conversational written Polish: editorial disputes, coordination, questions and answers. - Dump files: {stats['dump_files']} shards, sha1-verified against dumpstatus.json - Non-redirect talk pages (ns 1+5): {stats['talk_pages']:,} - Retained after text QA and within-source deduplication: {stats['kept']:,} - Characters: {stats['characters']:,} - Tokens: {stats['tokens']:,} (`cl100k_base` proxy) - License: CC BY-SA 4.0 per record; authorship via per-page history link ## Provenance and rights Each record keeps its page id, title, namespace, last-revision timestamp and canonical URL (history is the attribution trail, per [Wikimedia Terms of Use, section 7]({LICENSE_TERMS_URL})). That section grants CC BY-SA 4.0 rights to contributor text and allows attribution via the source-page URL. Additional third-party attribution notices must be preserved and remain a review item. The user-talk namespace (ns=3) is excluded by scope decision; its quality was not measured. The `created` field is the last revision date, not page creation. ## Processing and limitations Wikitext is stripped with mwparserfromhell; lines occurring in at least {BOILERPLATE_MIN_DOC_FREQ:.0%} of documents are removed as cross-document boilerplate (see `artifacts/boilerplate_lines.json`). Unicode and whitespace normalization, email/labelled-phone/IP/labelled-national-ID/account-candidate pattern redaction, three-window langid vote, exact and near deduplication within source. The final text must contain at least {MIN_TEXT_CHARS} characters after redaction. Rejection counts: ```json {json.dumps(qa['rejection_counts'], ensure_ascii=False, indent=2)} ``` PII filtering masks parsed IPv6 addresses (including compressed forms), labelled PESEL/NIP/REGON and 26-digit account candidates as well as the existing patterns. The account filter is conservative and may mask non-account numbers; unlabelled identifiers, free-form phone numbers, names and personal disclosures may remain. This is not complete anonymization. Talk pages are informal: they contain typos, edit disputes, quoted article fragments and occasional vandalism or abuse. Quoted article text is not disjoint from the shipped `wikipedia` shard; text-level dedup against it remains a target integration gate. The record model is a whole talk page; comments are not split. ## Review artifacts See `artifacts/sample.jsonl`, `attribution.jsonl`, `decisions.jsonl`, `source_manifest.jsonl`, `overlap_audit.json`, `stats.json`, `qa.json`, `checksums.json`, `run.json` and `ontology.json`. """ (root / "README.md").write_text(card, encoding="utf-8") (root / "NOTICE.md").write_text( "# Attribution and license notice\n\n" "Source: Polish Wikipedia talk pages, https://pl.wikipedia.org/ - Wikimedia Foundation.\n\n" "Text is available under the Creative Commons Attribution-ShareAlike 4.0 License " "(https://creativecommons.org/licenses/by-sa/4.0/). Attribution is provided via the per-record " "canonical page URL in `artifacts/attribution.jsonl`; each page's revision history lists its " "contributors.\n\n" "Preparation: Piotr Styla with Devin. Changes: namespace filtering (1 and 5), wikitext " "stripping, cross-document boilerplate removal, Unicode and whitespace normalization, limited " "email/labelled-phone/IP/labelled-national-ID/account-candidate redaction, language/quality filtering and within-source deduplication. No " "endorsement by the Wikimedia Foundation or page contributors is implied.\n", encoding="utf-8", ) print(json.dumps(stats, ensure_ascii=False, indent=2)) def verify(out): import pyarrow.parquet as pq root = out / "hf_repo" table = pq.read_table(root / "data/train-00000-of-00001.parquet") rows = table.to_pylist() stats = load(root / "artifacts/stats.json") decisions = read_lines(root / "artifacts/decisions.jsonl") attribution = read_lines(root / "artifacts/attribution.jsonl") sample = read_lines(root / "artifacts/sample.jsonl") assert table.column_names == FIELDS assert len(rows) == stats["kept"] == len(attribution) assert sum(item["selected"] for item in decisions) == len(rows) assert sum(row["token_count"] for row in rows) == stats["tokens"] assert all(row["source"] == SOURCE and row["license"] == LICENSE_SPDX for row in rows) assert all(EMAIL_RE.search(row["text"]) is None for row in rows) by_id = {row["id"]: row for row in rows} assert len(sample) == stats["sample_count"] and all(by_id[row["id"]] == row for row in sample) ontology = load(root / "artifacts/ontology.json") evidence = {item["id"] for item in ontology["evidence"]} assert all(item["falsification_condition"] and set(item["supported_by"]) <= evidence for item in ontology["claims"]) checks = load(root / "artifacts/checksums.json") assert all((root / path).is_file() and digest((root / path).read_bytes()) == checksum for path, checksum in checks.items()) for item in ontology["evidence"]: artifact = root / item["artifact"] assert artifact.is_file() and digest(load(artifact)) == item["content_address"] import tiktoken encoder = tiktoken.get_encoding("cl100k_base") assert len(by_id) == len(rows) assert set(by_id) == {item["id"] for item in attribution} assert set(by_id) == {item["id"] for item in decisions if item["selected"]} assert len(decisions) == stats["talk_pages"] assert len(decisions) - len(rows) == stats["rejected"] assert sum(len(row["text"]) for row in rows) == stats["characters"] short_ids = [row["id"] for row in rows if len(row["text"]) < MIN_TEXT_CHARS] assert all(row["token_count"] > 0 for row in rows) assert all(len(row["created"]) == 10 and row["author"] for row in rows) assert all(item["ns"] in TALK_NS and item["url"] == page_url(item["title"]) and item["text_sha256"] == digest(by_id[item["id"]]["text"].encode("utf-8")) for item in attribution) assert all(len(encoder.encode_ordinary(row["text"])) == row["token_count"] for row in rows) boilerplate = set(load(root / "artifacts/boilerplate_lines.json")) review_ids = {row["id"] for row in sorted(sample, key=lambda item: len(item["text"]))[:3]} comparisons = [] reconstructed = set() for shard in sorted((out / "extracted").glob("*.jsonl.gz")): with gzip.open(shard, "rt", encoding="utf-8") as handle: for line in handle: original = json.loads(line) row_id = f"{SOURCE}_{original['pageid']}" if row_id not in by_id: continue text = normalize(original["text"]) text = "\n".join(line for line in text.splitlines() if re.sub(r"\s+", " ", line).strip() not in boilerplate) text = re.sub(r"\n{3,}", "\n\n", text).strip().replace("\ufffd", "[UNREADABLE_GLYPH]") text, _ = redact_pii(text) before = redact_pii(original["text"])[0] if row_id in review_ids else "" assert text == by_id[row_id]["text"], row_id assert row_id not in reconstructed reconstructed.add(row_id) if row_id in review_ids: comparisons.append({"id": row_id, "title": original["title"], "before_normalization_pii_patterns_redacted": before, "after": text}) assert reconstructed == set(by_id) write_lines(out / "validation_samples.jsonl", comparisons) lengths = sorted(len(row["text"]) for row in rows) rejection_counts = dict(Counter(item["reason"] for item in decisions if not item["selected"])) residuals = {name: sum(bool(pattern.search(row["text"])) for row in rows) for name, pattern in {"email": EMAIL_RE, "labelled_phone": PHONE_RE, "ipv4": IPV4_RE, "ipv6_current_pattern": IPV6_RE}.items()} privacy_review = { "compressed_ipv6_documents": sum(any(is_ipv6(match.group()) for match in IPV6_CANDIDATE_RE.finditer(row["text"])) for row in rows), "labelled_national_identifier_candidates": sum(bool(NATIONAL_ID_RE.search(row["text"])) for row in rows), "bank_account_candidates": sum(bool(BANK_ACCOUNT_RE.search(row["text"])) for row in rows), } report = { "observed_at": now(), "verified": not short_ids and not any(residuals.values()) and not any(privacy_review.values()), "stats": stats, "additional_privacy_review_document_counts": privacy_review, "below_minimum_length_ids": short_ids, "rejection_counts": rejection_counts, "retained_namespaces": dict(Counter(item["ns"] for item in attribution)), "length_quantiles": {str(q): lengths[int((len(lengths) - 1) * q)] for q in (0, 0.5, 0.9, 0.99, 1)}, "residual_pattern_document_counts": residuals, "all_token_counts_recomputed": True, "texts_reconstructed_from_extracted_source": len(reconstructed), "before_after_samples": len(comparisons), "publication_ready": False, "pending": ["license evidence and attribution review", "PII coverage review", "target overlap audit methodology review", "manual text quality review"], } save(out / "validation_report.json", report) print(json.dumps(report, ensure_ascii=False, indent=2)) assert report["verified"], "Validation failures: see validation_report.json" def main(): parser = argparse.ArgumentParser() parser.add_argument("--output", type=Path, required=True) parser.add_argument("--workers", type=int, default=8) parser.add_argument("command", choices=["discover", "acquire", "audit_target", "audit_overlap", "build", "verify"]) args = parser.parse_args() if args.command == "discover": discover(args.output) elif args.command == "acquire": acquire(args.output, args.workers) elif args.command == "audit_target": audit_target(args.output) elif args.command == "audit_overlap": audit_overlap(args.output) elif args.command == "build": build(args.output) else: verify(args.output) if __name__ == "__main__": main()