#!/usr/bin/env python3 """Build an auditable slice of Nonsensopedia (nonsa.pl) 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 from language_gate import language_vote SOURCE = "nonsa" OWN_REPO = "PiotrSty/nonsa-pl" TARGET = "SlayerLab/polish-dynaword" DUMP_DATE = "20251009" IA_ITEM = f"wiki-nonsa.pl-{DUMP_DATE}" IA_META_URL = f"https://archive.org/metadata/{IA_ITEM}" IA_FILE = f"nonsa.pl-{DUMP_DATE}-history.xml.zst" SOURCE_URL = "https://nonsa.pl/" 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/" IA_ITEM_URL = f"https://archive.org/details/{IA_ITEM}" # Content namespaces: 0 articles, 100 Cytaty, 102 NonNews, 104 NonZrodla, # 106 Slownik, 108 Gra, 110 Forum, 114 Poradnik. 100 is still parsed, QA'd and # deduplicated (so every other row is decided exactly as before) but never # retained; see third_party_drop(). CONTENT_NS = {"0", "100", "102", "104", "106", "108", "110", "114"} RETAINED_NS_LABEL = "0 articles, 102 NonNews, 104 NonZrodla, 106 Slownik, 108 Gra, 110 Forum, 114 Poradnik" MIN_TEXT_CHARS = 500 BOILERPLATE_MIN_DOC_FREQ = 0.01 DF_FRACTION = 0.02 # shingles in >2% of docs are template boilerplate DF_SUBSAMPLE_STRIDE = 4 # document-frequency pass samples every Nth document 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"(? tag marks verse and lyrics blocks. A CC BY-SA # licence from the wiki cannot cover third-party text a contributor only quotes. CYTATY_NS = "100" DROP_CYTATY = "third_party_quotations_ns100" DROP_POEM = "poem_block" # strip_wikitext() deletes tags, so the marker exists only in raw wikitext. # Comments and /
 spans print the tag literally (e.g. forum threads
# discussing it), so they are removed first. An unterminated comment hides the rest.
POEM_RE = re.compile(r"])", re.I)
LITERAL_SPAN_RE = re.compile(r"|\Z)|<(nowiki|pre)(?:\s[^>/]*)?>.*?", re.S | re.I)


def has_poem_block(wikitext):
    return bool(POEM_RE.search(LITERAL_SPAN_RE.sub("", wikitext)))


def third_party_drop(ns, has_poem):
    """Drop reason for a page that passed QA and dedup, or "" to keep it."""
    if ns == CYTATY_NS:
        return DROP_CYTATY
    return DROP_POEM if has_poem else ""


def is_ipv6(value):
    try:
        return ipaddress.ip_address(value.rstrip(".")).version == 6
    except ValueError:
        return False


def redact_pii(text):
    counts = Counter()

    def replace_ipv6(match):
        value = match.group().rstrip(".")
        if not is_ipv6(value):
            return match.group()
        counts["ipv6"] += 1
        return "[REDACTED:IP]" + match.group()[len(value):]

    text = IPV6_CANDIDATE_RE.sub(replace_ipv6, text)
    for name, pattern, replacement in (
        ("email", EMAIL_RE, "[REDACTED:EMAIL]"),
        ("labelled_phone", PHONE_RE, "[REDACTED:PHONE]"),
        ("ipv4", IPV4_RE, "[REDACTED:IP]"),
        ("ipv6_legacy_pattern", IPV6_RE, "[REDACTED:IP]"),
        ("national_identifier", NATIONAL_ID_RE, lambda match: match.group(1) + " [REDACTED:ID]"),
        ("account_candidate", BANK_ACCOUNT_RE, "[REDACTED:ACCOUNT]"),
    ):
        text, count = pattern.subn(replacement, text)
        counts[name] += count
    return text, counts


def now():
    return datetime.now(timezone.utc).isoformat()


def digest(value):
    if not isinstance(value, bytes):
        value = json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode("utf-8")
    return hashlib.sha256(value).hexdigest()


def sha1_file(path):
    h = hashlib.sha1()
    with path.open("rb") as handle:
        while chunk := handle.read(1 << 22):
            h.update(chunk)
    return h.hexdigest()


def save(path, value):
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(json.dumps(value, ensure_ascii=False, sort_keys=True, indent=2) + "\n", encoding="utf-8")


def write_lines(path, rows):
    path.parent.mkdir(parents=True, exist_ok=True)
    with path.open("w", encoding="utf-8") as handle:
        for row in rows:
            handle.write(json.dumps(row, ensure_ascii=False, sort_keys=True) + "\n")


def read_lines(path):
    return [json.loads(line) for line in path.read_text(encoding="utf-8").split("\n") if line]


def load(path):
    return json.loads(path.read_text(encoding="utf-8"))


def request(url, attempts=5, timeout=(15, 90)):
    response = None
    for attempt in range(attempts):
        response = requests.get(url, headers=UA, timeout=timeout)
        if response.status_code not in (429, 500, 502, 503, 504):
            response.raise_for_status()
            return response
        time.sleep(2 ** attempt)
    response.raise_for_status()


def request_json(url):
    return request(url).json()


def _local(tag):
    return tag.rsplit("}", 1)[-1]


# strip_code() keeps the text of every wikilink, so category tags survive as
# "Kategoria:X" lines and file links as their option list ("right|200px|caption").
FILE_NS = {"plik", "grafika", "file", "image"}
CATEGORY_NS = {"kategoria", "category"}
IMAGE_OPTION_RE = re.compile(
    r"(?i)^\s*(?:\d*x?\d+\s*px"
    r"|thumb|thumbnail|mały|miniatura|frame|framed|ramka|frameless|bezramki|border|obramowanie"
    r"|left|lewo|right|prawo|center|centre|centruj|none|brak|upright|pionowo"
    r"|baseline|sub|super|top|text-top|middle|bottom|text-bottom"
    r"|(?:link|alt|page|class|lang|upright|thumb|thumbnail|mały|miniatura)\s*=.*)\s*$")
MAGIC_WORD_RE = re.compile(r"__[A-ZĄĆĘŁŃÓŚŹŻ]+__")


def split_top_level(text):
    """Split link parameters on '|' outside nested [[...]] / {{...}}."""
    parts, depth, start, i = [], 0, 0, 0
    while i < len(text):
        pair = text[i:i + 2]
        if pair in ("[[", "{{"):
            depth += 1
            i += 2
            continue
        if pair in ("]]", "}}") and depth:
            depth -= 1
            i += 2
            continue
        if text[i] == "|" and not depth:
            parts.append(text[start:i])
            start = i + 1
        i += 1
    parts.append(text[start:])
    return parts


def link_namespace(title):
    name = str(title).strip()
    if name.startswith(":") or ":" not in name:  # [[:Kategoria:X]] is an inline link
        return ""
    return name.split(":", 1)[0].strip().casefold()


def file_caption(params):
    """MediaWiki renders the last non-option parameter of a file link as its caption."""
    if not params:
        return ""
    captions = [part for part in split_top_level(params) if not IMAGE_OPTION_RE.match(part)]
    return captions[-1].strip() if captions else ""


def replace_link(namespace, params):
    """Replacement for a category/file link, or None to keep the link."""
    if namespace in CATEGORY_NS:
        return ""
    if namespace in FILE_NS:
        caption = file_caption(params)
        return f"\n{caption}\n" if caption else ""
    return None


# Malformed markup (e.g. an unclosed '' inside a caption) makes mwparserfromhell
# read the whole link as plain text, so strip_code() leaves it verbatim.
RESIDUAL_LINK_RE = re.compile(r"\[\[([^\[\]\n]*)\]\]")


def _replace_residual_link(match):
    title, _, params = match.group(1).partition("|")
    replacement = replace_link(link_namespace(title), params)
    return match.group(0) if replacement is None else replacement


def strip_wikitext(wikitext):
    import mwparserfromhell
    try:
        code = mwparserfromhell.parse(wikitext)
        # reversed: links nested in a caption are rewritten before their parent is read
        for link in reversed(code.filter_wikilinks()):
            params = "" if link.text is None else str(link.text)
            replacement = replace_link(link_namespace(link.title), params)
            if replacement is not None:
                code.replace(link, replacement)
        text = code.strip_code(normalize=True, collapse=True)
        text = RESIDUAL_LINK_RE.sub(_replace_residual_link, text)
        return re.sub(r"\n{3,}", "\n\n", MAGIC_WORD_RE.sub("", text)).strip()
    except Exception:
        return ""


def _strip_batch(items):
    return [strip_wikitext(wikitext) for _, _, _, _, wikitext in items]


def discover(out):
    metadata = request_json(IA_META_URL)
    license_url = (metadata.get("metadata") or {}).get("licenseurl")
    files = []
    for item in metadata.get("files", []):
        if item.get("name") == IA_FILE:
            files.append({"name": item["name"],
                          "url": f"https://archive.org/download/{IA_ITEM}/{item['name']}",
                          "size": int(item["size"]), "sha1": item.get("sha1"),
                          "md5": item.get("md5"), "format": item.get("format")})
    if not files:
        raise ValueError(f"history dump {IA_FILE} not found in {IA_ITEM}")
    selection = {
        "observed_at": now(), "dump_date": DUMP_DATE,
        "archive_org_item": IA_ITEM, "archive_org_metadata_url": IA_META_URL,
        "files": files, "total_bytes": sum(item["size"] for item in files),
        "content_namespaces": sorted(CONTENT_NS, key=int), "min_text_chars": MIN_TEXT_CHARS,
        "license": "CC BY-SA 3.0 (Nonsensopedia site license; archive.org item licenseurl)",
        "license_url_observed": license_url,
        "dump_producer": "wikiteam3 (https://github.com/saveweb/wikiteam3/)",
        "files_sha256": digest(files),
    }
    save(out / "selection.json", selection)
    print(json.dumps({k: selection[k] for k in ("dump_date", "total_bytes")}, indent=2))
    print("files:", len(files))


def parse_dump(path):
    """wikiteam3 xmlrevisions export: each  element carries one ;
    group by pageid and keep the latest revision (max timestamp) per page."""
    import zstandard

    latest = {}
    dctx = zstandard.ZstdDecompressor(max_window_size=2 ** 31)
    with path.open("rb") as raw, dctx.stream_reader(raw) as fh:
        title = ns = pageid = timestamp = text = None
        redirect = False
        for ev, el in iterparse(fh, events=("end",)):
            tag = _local(el.tag)
            if tag == "title":
                title = el.text
            elif tag == "ns":
                ns = el.text
            elif tag == "id" and pageid is None:
                pageid = el.text
            elif tag == "timestamp":
                timestamp = el.text
            elif tag == "redirect":
                redirect = True
            elif tag == "text":
                text = el.text
            elif tag == "page":
                if ns in CONTENT_NS and not redirect:
                    current = latest.get(pageid)
                    if current is None or (timestamp or "") > (current[3] or ""):
                        latest[pageid] = (pageid, ns, title, timestamp, text)
                title = ns = pageid = timestamp = text = None
                redirect = False
                el.clear()
    return [record for record in latest.values() if record[4]]


def acquire(out, workers):
    selection = load(out / "selection.json")
    dump_dir = out / "raw_dump"
    dump_dir.mkdir(parents=True, exist_ok=True)
    extracted_dir = out / "extracted"
    extracted_dir.mkdir(exist_ok=True)
    manifest = []
    for item in selection["files"]:
        dst = dump_dir / item["name"]
        if not dst.exists() or dst.stat().st_size != item["size"]:
            print(f"  pobieram {item['name']} ({item['size']/1e6:.0f} MB)", flush=True)
            for attempt in range(8):
                have = dst.stat().st_size if dst.exists() else 0
                headers = dict(UA)
                if have:
                    headers["Range"] = f"bytes={have}-"
                try:
                    with requests.get(item["url"], headers=headers, stream=True, timeout=(15, 300)) as r:
                        r.raise_for_status()
                        if have and r.status_code != 206:
                            have = 0
                        with dst.open("ab" if have else "wb") as f:
                            for chunk in r.iter_content(1 << 22):
                                f.write(chunk)
                    break
                except requests.RequestException as error:
                    print(f"  retry {item['name']}: {type(error).__name__}", flush=True)
                    time.sleep(min(2 ** attempt, 60))
            else:
                raise RuntimeError(f"download failed: {item['name']}")
        sha = sha1_file(dst)
        if item["sha1"] and sha != item["sha1"]:
            raise ValueError(f"sha1 mismatch {item['name']}: {sha} != {item['sha1']}")
        print(f"  {item['name']} sha1 OK", flush=True)

        out_path = extracted_dir / (item["name"] + ".jsonl.gz")
        if not out_path.exists():
            records = parse_dump(dst)
            batches = [records[i:i + 2000] for i in range(0, len(records), 2000)]
            with ProcessPoolExecutor(max_workers=workers) as pool:
                texts = [text for batch in pool.map(_strip_batch, batches) for text in batch]
            with gzip.open(out_path, "wt", encoding="utf-8") as f:
                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),
                                        "has_poem": has_poem_block(wikitext),
                                        "text": text}, ensure_ascii=False) + "\n")
        shard_records = 0
        kept_chars = 0
        with gzip.open(out_path, "rt", encoding="utf-8") as f:
            for line in f:
                row = json.loads(line)
                shard_records += 1
                kept_chars += len(row["text"])
                manifest.append({"pageid": row["pageid"], "ns": row["ns"], "title": row["title"],
                                 "timestamp": row["timestamp"],
                                 "url": page_url(row["title"])})
        print(f"  {item['name']}: {shard_records} stron tresci", flush=True)
    write_lines(out / "source_manifest.jsonl", manifest)
    acquisition = {
        "observed_at": now(), "dump_date": selection["dump_date"],
        "files": selection["files"], "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 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 = ("nonsa", "nonsensopedia")
    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, added=None):
    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)
                if "has_poem" not in row:
                    raise ValueError(f"{shard} predates the has_poem flag: delete it and re-run acquire")
                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 = added or 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['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)
        # Applied after dedup and registration so that dropping a page never changes how
        # any other page is decided: the retained set is the pre-gate set minus these rows.
        third_party = third_party_drop(record["ns"], record["has_poem"])
        if third_party:
            decision.update({"selected": False, "reason": third_party})  # already in `decisions`
            continue
        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": "nonsensopedia 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 + " (site license via archive.org item metadata; attribution by page URL)",
            "dump": {"date": selection["dump_date"], "archive_org_item": selection["archive_org_item"],
                     "files": [f["name"] for f in selection["files"]]},
            "text_sha256": digest(text.encode("utf-8")),
            "transformations": ["wikiteam3 xmlrevisions dump, 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 = {
        "dump_date": selection["dump_date"], "dump_files": len(selection["files"]),
        "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": f"Nonsensopedia content namespaces ({RETAINED_NS_LABEL}), latest revision per page from the wikiteam3 archive.org dump; namespace 100 Cytaty and pages with a  block are dropped (third_party_gate)",
        "third_party_gate": f"Rights gate, applied after QA and dedup so no other page's decision changes. Rejected as {DROP_CYTATY}: namespace {CYTATY_NS} Cytaty (quotations of third-party films, games and music). Rejected as {DROP_POEM}: every other page whose raw wikitext contains a  block (verse and lyrics; the tag is a line-preserving block that the wiki also uses for dialogues, jokes and game pages, so this over-matches on purpose). A  tag inside an HTML comment,  or 
 does not count. The flag is computed from raw wikitext in acquire because strip_wikitext removes the tag. Namespace 100 takes precedence for a page that is in both.",
        "license_terms_url": LICENSE_TERMS_URL,
        "license_gate": "CC BY-SA 3.0 declared in archive.org item metadata (licenseurl) and on nonsa.pl; 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": [
            "satirical/humorous register: parody articles, fake news (NonNews), fake dictionary entries (Slownik), forum posts and games; not factual reference text",
            "pages may parody or quote real Wikipedia/cultural material; quoted passages are not guaranteed disjoint from other shards",
            "quotations embedded in retained pages (the {{cytat}} quote template, 
, plain-text lyrics) are not screened; only namespace 100 and pages are dropped", "record model is a whole content page; individual entries/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:nonsa-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(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:nonsa-dump-" + selection["dump_date"], "type": "Source"}, {"id": "object:dataset:nonsa-content", "type": "Dataset"}], "versions": [{"id": source_version, "object": "object:source:nonsa-dump-" + selection["dump_date"], "content_address": source_version.rsplit(":", 1)[-1]}, {"id": dataset_version, "object": "object:dataset:nonsa-content", "content_address": dataset_version.rsplit(":", 1)[-1]}], "protocols": [{"id": protocol_id, "procedure": "pinned wikiteam3 archive.org dump; sha1-verified; latest revision per page; content namespaces {0,100,102,104,106,108,110,114}; wikitext strip; boilerplate removal; normalization; PII patterns; exact and near dedup with high-document-frequency shingle exclusion; namespace 100 and pages dropped after dedup"}], "runs": [run], "evidence": evidence, "claims": [ {"id": "claim:source-pages-observed", "statement": f"The pinned dump {selection['dump_date']} yielded {acquisition['source_pages']} non-redirect pages in the content namespaces.", "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": "Nonsensopedia 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:nonsensopedia-community", "type": "Organization"}, {"id": "actor:wikiteam", "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 --- # Nonsensopedia - Polish satirical wiki (content namespaces) Content pages from the pinned wikiteam3 dump of nonsa.pl ({IA_ITEM_URL}, generated {selection['dump_date']}). Nonsensopedia is the Polish-language satirical encyclopedia - a community wiki parodying Wikipedia and its sister projects. Content namespaces included: 0 (articles), 102 (NonNews - fake news), 104 (NonZrodla - fake sources), 106 (Slownik - fake dictionary), 108 (Gra - games), 110 (Forum), 114 (Poradnik - guides). Namespace 100 (Cytaty - quotations of third-party films, games and music) and every page with a `` block (verse and lyrics) are excluded. Latest revision per page. This is informal, humorous creative Polish - satire, jokes, parody reference text. - Dump: {IA_FILE}, sha1-verified against archive.org item metadata - Non-redirect content pages: {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; authorship via per-page history link ## Provenance and rights Nonsensopedia text is licensed [CC BY-SA 3.0]({LICENSE_TERMS_URL}); the archive.org item metadata declares the same licenseurl. Each record keeps its page id, title, namespace, last-revision timestamp and canonical URL - the page revision history is the attribution trail. The dump was produced by the WikiTeam preservation project (wikiteam3). 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 deliberately non-factual: satirical articles, fake news, fake dictionary entries, forum posts and game pages. Pages may parody or quote real Wikipedia articles and other copyrighted works; quoted passages are not guaranteed disjoint from other corpus shards. The record model is a whole content page; individual entries 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: Nonsensopedia, https://nonsa.pl/ - a Polish-language satirical community wiki.\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. Dump archived by the WikiTeam preservation project " f"({IA_ITEM_URL}).\n\n" "Preparation: Piotr Styla with Devin. Changes: content-namespace filtering (namespace 100 Cytaty " "and pages with a block removed), 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 " "Nonsensopedia 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"] in CONTENT_NS - {CYTATY_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 assert not third_party_drop(original["ns"], original["has_poem"]), row_id 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" # build output (relative to /hf_repo) -> flat file name under data/nonsa/ EXPORT_FILES = { "data/train-00000-of-00001.parquet": "nonsa.parquet", "artifacts/attribution.jsonl": "nonsa.attribution.jsonl", "artifacts/qa.json": "nonsa.qa.json", "artifacts/sample.jsonl": "nonsa.sample.jsonl", "artifacts/overlap_audit.json": "nonsa.overlap_audit.json", } # the exported stats.json keeps the key set shared by the other data// shards EXPORT_STATS_KEYS = ("added", "boilerplate_lines_removed", "characters", "dump_date", "kept", "license_counts", "sample_count", "source_pages", "tokens") def exported_stats(stats, overlap): return {**{key: stats[key] for key in EXPORT_STATS_KEYS}, "source_slice_kept": stats["kept"], "target_revision": overlap["target_revision"]} def dropped_rows(decisions, manifest): """One row per page removed by the rights gate: the parquet carries neither the dropped text nor its namespace, so this list is what makes the drop recountable.""" pages = {f"{SOURCE}_{item['pageid']}": item for item in manifest} return [{"id": item["id"], "pageid": pages[item["id"]]["pageid"], "ns": pages[item["id"]]["ns"], "title": pages[item["id"]]["title"], "url": pages[item["id"]]["url"], "reason": item["reason"]} for item in decisions if item["reason"] in (DROP_CYTATY, DROP_POEM)] def write_export(path, data): """Write bytes unless the file already holds the same content up to line endings, so the committed CRLF files (NOTICE.md, overlap_audit.json) are not rewritten for nothing.""" if path.exists() and path.read_bytes().replace(b"\r\n", b"\n") == data.replace(b"\r\n", b"\n"): return path.write_bytes(data) def export(out, dest): """Copy the build into the flat data/nonsa/ layout and rewrite nonsa.checksums.json. nonsa.md is the hand-written datasheet: it is never overwritten, only checksummed.""" root = out / "hf_repo" dest.mkdir(parents=True, exist_ok=True) for source, name in EXPORT_FILES.items(): write_export(dest / name, (root / source).read_bytes()) notice = (root / "NOTICE.md").read_text(encoding="utf-8") write_export(dest / "NOTICE.md", notice.replace("`artifacts/attribution.jsonl`", "`nonsa.attribution.jsonl`").encode("utf-8")) write_lines(dest / "nonsa.dropped.jsonl", dropped_rows(read_lines(root / "artifacts/decisions.jsonl"), read_lines(root / "artifacts/source_manifest.jsonl"))) save(dest / "nonsa.stats.json", exported_stats(load(root / "artifacts/stats.json"), load(root / "artifacts/overlap_audit.json"))) save(dest / "nonsa.checksums.json", {path.name: digest(path.read_bytes()) for path in sorted(dest.iterdir()) if path.name != "nonsa.checksums.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("--added", help="build: `added` date for every row (default: acquisition date); " "pass the committed date to rebuild identical rows") parser.add_argument("--dest", type=Path, help="export: target directory, e.g. data/nonsa") parser.add_argument("command", choices=["discover", "acquire", "audit_target", "audit_overlap", "build", "verify", "export"]) 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, args.added) elif args.command == "export": if args.dest is None: parser.error("export needs --dest") export(args.output, args.dest) else: verify(args.output) if __name__ == "__main__": main()