#!/usr/bin/env python3 """Build an auditable slice of Polish Fandom wikis (fan-content namespaces), CC BY-SA 3.0.""" from __future__ import annotations import argparse 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 = "fandom_pl" OWN_REPO = "PiotrSty/fandom-pl" TARGET = "SlayerLab/polish-dynaword" SOURCE_URL = "https://www.fandom.com/licensing" 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-3.0" LICENSE_TERMS_URL = "https://creativecommons.org/licenses/by-sa/3.0/" FANDOM_LICENSE_URL = "https://web.archive.org/web/20241231234031/https://www.fandom.com/licensing" WIKIS = [ ("elderscrolls", "https://elderscrolls.fandom.com/pl/api.php"), ("wiedzmin", "https://wiedzmin.fandom.com/pl/api.php"), ("gothic", "https://gothic.fandom.com/pl/api.php"), ("harrypotter", "https://harrypotter.fandom.com/pl/api.php"), ("gta", "https://gta.fandom.com/pl/api.php"), ("sims", "https://sims.fandom.com/pl/api.php"), ("starwars", "https://starwars.fandom.com/pl/api.php"), ("naruto", "https://naruto.fandom.com/pl/api.php"), ("pokemon", "https://pokemon.fandom.com/pl/api.php"), ("dragonage", "https://dragonage.fandom.com/pl/api.php"), ("fallout", "https://fallout.fandom.com/pl/api.php"), ("creepypasta", "https://creepypasta.fandom.com/pl/api.php"), ] MIN_TEXT_CHARS = 500 BOILERPLATE_MIN_DOC_FREQ = 0.01 DF_FRACTION = 0.02 DF_SUBSAMPLE_STRIDE = 4 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"(?=1% of documents, so they leak into the corpus. This is the v2 fix for that residue. """ kept = [] for line in text.splitlines(): stripped = line.strip() if stripped and ( re.match(r"^[a-z]{2,3}:\S", stripped) or len(re.findall(r"\b[a-z]{2,3}:", stripped)) >= 2 or re.match(r"^(?:Kategoria|Category):", stripped) ): continue kept.append(line) return "\n".join(kept) def strip_wikitext(wikitext): import mwparserfromhell try: return drop_layout_lines( mwparserfromhell.parse(wikitext).strip_code(normalize=True, collapse=True).strip() ).strip() except Exception: return "" def _strip_batch(items): return [strip_wikitext(wikitext) for _, _, _, _, wikitext in items] def discover(out): results = [] for name, api_url in WIKIS: try: r = request_json(api_url + "?action=query&meta=siteinfo&siprop=general|statistics&format=json") q = r.get("query", {}) g, st = q.get("general", {}), q.get("statistics", {}) results.append({ "name": name, "api_url": api_url, "wikiid": g.get("wikiid"), "articles": st.get("articles"), "pages": st.get("pages"), "lang": g.get("lang"), "base": g.get("base"), }) except Exception as e: print(f"WARNING: {name} discovery failed: {e}") if not results: raise ValueError("no wikis discovered") selection = { "observed_at": now(), "wikis": results, "total_articles": sum(r["articles"] for r in results), "min_text_chars": MIN_TEXT_CHARS, "license": "CC BY-SA 3.0 (Fandom site license, per Wayback snapshot 2024-12-31)", "license_url_observed": FANDOM_LICENSE_URL, "license_provenance": "Wayback Machine snapshot of https://www.fandom.com/licensing", "files_sha256": digest(results), } save(out / "selection.json", selection) print(json.dumps({k: selection[k] for k in ("total_articles", "license")}, indent=2)) print("wikis:", len(results)) def fetch_wiki_titles(api_url, namespace=0, limit=500): """Yield titles from allpages with pagination.""" apcontinue = None while True: params = {"action": "query", "list": "allpages", "apnamespace": namespace, "aplimit": limit, "format": "json"} if apcontinue: params["apcontinue"] = apcontinue r = request_json(api_url, params=params) pages = r.get("query", {}).get("allpages", []) for p in pages: yield p["title"] apcontinue = r.get("continue", {}).get("apcontinue") if not apcontinue: break def fetch_revisions(api_url, titles): """Batch fetch revisions for up to 50 titles.""" if not titles: return [] params = {"action": "query", "titles": "|".join(titles), "prop": "revisions", "rvprop": "content|timestamp", "rvslots": "main", "format": "json"} r = request_json(api_url, params=params) records = [] for pageid, data in r.get("query", {}).get("pages", {}).items(): if "missing" in data: continue if "ns" not in data or "title" not in data: continue title = data["title"] ns = str(data["ns"]) revs = data.get("revisions", []) if not revs: continue latest = revs[0] text = latest.get("slots", {}).get("main", {}).get("*", "") timestamp = latest.get("timestamp", "") records.append((pageid, ns, title, timestamp, text)) return records def acquire(out, workers): selection = load(out / "selection.json") extracted_dir = out / "extracted" extracted_dir.mkdir(exist_ok=True) manifest = [] BATCH_SIZE = 50 def add_manifest(path): added = 0 with gzip.open(path, "rt", encoding="utf-8") as f: for line in f: row = json.loads(line) manifest.append({"pageid": row["pageid"], "ns": row["ns"], "title": row["title"], "timestamp": row["timestamp"], "wiki": row["wiki"], "url": page_url(row["title"], row["wiki"])}) added += 1 return added for wiki in selection["wikis"]: name = wiki["name"] api_url = wiki["api_url"] print(f" fetching {name} (ns0 articles: {wiki['articles']:,})", flush=True) out_path = extracted_dir / f"{name}.jsonl.gz" if out_path.exists(): count = add_manifest(out_path) print(f" {name}: already fetched ({count} records)", flush=True) continue tmp_path = extracted_dir / f"{name}.jsonl.gz.tmp" if tmp_path.exists(): tmp_path.unlink() titles = list(fetch_wiki_titles(api_url, namespace=0, limit=500)) print(f" {name}: {len(titles)} titles fetched", flush=True) written = 0 with gzip.open(tmp_path, "wt", encoding="utf-8") as f: for batch_index, i in enumerate(range(0, len(titles), BATCH_SIZE), start=1): batch = titles[i:i + BATCH_SIZE] records = fetch_revisions(api_url, batch) texts = _strip_batch(records) for (pageid, ns, title, timestamp, wikitext), text in zip(records, texts): f.write(json.dumps({"pageid": pageid, "ns": ns, "title": title, "timestamp": timestamp, "wikitext_chars": len(wikitext), "text": text, "wiki": name}, ensure_ascii=False) + "\n") written += len(records) if batch_index % 25 == 0 or i + BATCH_SIZE >= len(titles): print(f" {name}: {min(i + BATCH_SIZE, len(titles))}/{len(titles)} titles, " f"{written} revisions written", flush=True) time.sleep(1) # throttle tmp_path.replace(out_path) count = add_manifest(out_path) print(f" {name}: {count} records written", flush=True) write_lines(out / "source_manifest.jsonl", manifest) acquisition = { "observed_at": now(), "wikis": selection["wikis"], "source_pages": len(manifest), "manifest_sha256": digest((out / "source_manifest.jsonl").read_bytes()), } save(out / "acquisition.json", acquisition) print(json.dumps(acquisition, ensure_ascii=False, indent=2)) def strip_boilerplate(texts_index): counts = Counter() for lines in texts_index: counts.update(set(re.sub(r"\s+", " ", line).strip() for line in lines if line.strip())) n = len(texts_index) return {line for line, count in counts.items() if count / n >= 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 def boilerplate_shingles(candidates, boilerplate, stride=DF_SUBSAMPLE_STRIDE, fraction=DF_FRACTION): df = Counter() sampled = 0 for index, record in enumerate(candidates): if index % stride: continue 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() df.update(shingle_sketch(text)) sampled += 1 max_df = max(1, int(sampled * fraction)) return {shingle for shingle, count in df.items() if count > max_df}, max_df, sampled def filter_sketch(sketch, hot): return {shingle for shingle in sketch if shingle not in hot} 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 = ("fandom", "elderscrolls", "wiedzmin", "gothic", "harrypotter", "gta", "sims", "starwars", "naruto", "pokemon", "dragonage", "fallout", "creepypasta") 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) hot, max_df, df_sampled = boilerplate_shingles(candidates, boilerplate) print(f"boilerplate shingles: {len(hot)} (df>{max_df} over {df_sampled} sampled docs)", 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 = filter_sketch(shingle_sketch(text), hot) duplicate_of, duplicate_score = near_index.find(sketch) if duplicate_of is not None: reason = "near_duplicate" row_id = f"{SOURCE}_{record.get('wiki', 'fandom')}_{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": f"{record.get('wiki', 'fandom')} contributors", } rows.append(row) attribution.append({ "id": row_id, "pageid": record["pageid"], "wiki": record.get("wiki", "fandom"), "ns": record["ns"], "title": record["title"], "url": page_url(record["title"], record.get("wiki", "")), "last_revision_at": record["timestamp"], "wikitext_chars": record["wikitext_chars"], "license": LICENSE_SPDX, "license_evidence": LICENSE_TERMS_URL + " (Fandom site license, per Wayback snapshot; attribution by page URL)", "dump": {"wikis": selection["wikis"], "license_provenance": selection["license_provenance"]}, "text_sha256": digest(text.encode("utf-8")), "transformations": ["MediaWiki API fetch (allpages + revisions), latest revision per page", "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 = { "wikis": selection["wikis"], "source_pages": acquisition["source_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), "boilerplate_shingles_excluded": len(hot), "sample_count": len(sample), "added": added, } qa = { "scope": "Polish Fandom wikis (12 wikis, ns0 articles only), latest revision per page fetched via MediaWiki API", "license_terms_url": LICENSE_TERMS_URL, "license_gate": "CC BY-SA 3.0 declared on Fandom licensing page (Wayback snapshot 2024-12-31); 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; shingles with document frequency >2% (sampled 1-in-4) excluded from sketches", "boilerplate": f"lines occurring in >= {BOILERPLATE_MIN_DOC_FREQ:.0%} of documents removed ({len(boilerplate)} patterns); {len(hot)} high-df shingles excluded from near-dedup sketches (df>{max_df} over {df_sampled} sampled docs)", "wikipedia_shard_overlap": overlap or "pending", "cross_source_text_dedup": "pending target integration", "benchmark_overlap": "pending", "limitations": [ "fan-fiction and gaming wiki register: lore, walkthroughs, guides, infobox-heavy content; not factual reference text", "pages may quote/copy official game materials or other copyrighted works; quoted passages are not guaranteed disjoint from other shards", "record model is a whole content page; individual sections 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:fandom-content-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({ "wikis": selection["wikis"], "license_provenance": selection["license_provenance"], "files_sha256": selection.get("files_sha256", digest(selection["wikis"])), }) 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:fandom-api", "type": "Source"}, {"id": "object:dataset:fandom-content", "type": "Dataset"}], "versions": [{"id": source_version, "object": "object:source:fandom-api", "content_address": source_version.rsplit(":", 1)[-1]}, {"id": dataset_version, "object": "object:dataset:fandom-content", "content_address": dataset_version.rsplit(":", 1)[-1]}], "protocols": [{"id": protocol_id, "procedure": "pinned MediaWiki API fetch (allpages + revisions) for 12 Polish Fandom wikis; latest revision per page; ns0 only; wikitext strip; boilerplate removal; normalization; PII patterns; exact and near dedup with high-document-frequency shingle exclusion"}], "runs": [run], "evidence": evidence, "claims": [ {"id": "claim:source-pages-observed", "statement": f"The MediaWiki API fetch yielded {acquisition['source_pages']} non-redirect ns0 pages across 12 Fandom wikis.", "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": "Fandom wikis 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:fandom-community", "type": "Organization"}, {"id": "actor:MediaWiki API", "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": ["cross-source text deduplication", "benchmark contamination check", "parody-of-real-content screening", "controlled training ablation"], } save(root / "artifacts/ontology.json", ontology) card = f"""--- license: cc-by-sa-3.0 language: - pl task_categories: - text-generation configs: - config_name: default data_files: - split: train path: data/train-00000-of-00001.parquet --- # Polish Fandom wikis (fan-content, ns0 articles) Content pages from 12 Polish-language Fandom wikis, fetched via MediaWiki API and filtered to namespace 0 (articles). Fandom wikis are community-run fan sites for video games, TV series, books and franchises - containing lore, walkthroughs, guides, infobox-heavy pages and fan-created content. This is informal, hobbyist Polish covering fandom topics (gaming, fantasy, sci-fi, horror) - a register complementary to factual sources. - Wikis: {len(selection['wikis'])} (elderscrolls, wiedzmin, gothic, harrypotter, gta, sims, starwars, naruto, pokemon, dragonage, fallout, creepypasta) - Total ns0 articles enumerated: {stats['source_pages']:,} - Retained after text QA and within-source deduplication: {stats['kept']:,} - Characters: {stats['characters']:,} - Tokens: {stats['tokens']:,} (`cl100k_base` proxy) - License: CC BY-SA 3.0 per record (Fandom site license, per Wayback snapshot 2024-12-31); authorship via per-page history link ## Provenance and rights Fandom text is licensed [CC BY-SA 3.0]({LICENSE_TERMS_URL}); the official licensing page states this as the default license for Fandom communities. Each record keeps its page id, title, namespace, last-revision timestamp and canonical URL - the page revision history is the attribution trail. Additional third-party attribution notices must be preserved and remain a review item. 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. The register is fan-created content: lore, walkthroughs, guides, infobox-heavy pages and hobbyist writing. Pages may quote or copy official game materials or other copyrighted works; quoted passages are not guaranteed disjoint from other corpus shards. The record model is a whole page; individual sections 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 Fandom wikis (12 wikis: elderscrolls, wiedzmin, gothic, harrypotter, gta, sims, starwars, naruto, pokemon, dragonage, fallout, creepypasta), https://www.fandom.com/ - community-run fan sites.\n\n" "Text is available under the Creative Commons Attribution-ShareAlike 3.0 License " "(https://creativecommons.org/licenses/by-sa/3.0/). Attribution is provided via the per-record " "canonical page URL in `artifacts/attribution.jsonl`; each page's revision history lists its " "contributors. License verified via Wayback Machine snapshot of https://www.fandom.com/licensing (2024-12-31).\n\n" "Preparation: Piotr Styla with Devin. Changes: ns0-only filtering, MediaWiki API fetch (allpages + revisions), latest-revision " "selection, 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 " "Fandom or wiki 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["source_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"] == "0" and item["url"] == page_url(item["title"], item.get("wiki", "")) 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.get('wiki', 'fandom')}_{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()