File size: 47,191 Bytes
fa7129e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
808ad53
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fa7129e
 
 
808ad53
 
 
fa7129e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
#!/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"(?<![\w:])(?:[0-9a-fA-F]{0,4}:){2,}[0-9a-fA-F:.]*(?![\w:])")
NATIONAL_ID_RE = re.compile(r"(?i)\b(PESEL|NIP|REGON)\s*[:=]?\s*\d(?:[ -]?\d){8,13}\b")
BANK_ACCOUNT_RE = re.compile(r"(?<!\d)(?:PL\s*)?\d{2}(?:[ -]?\d){24}(?!\d)")


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), params=None):
    response = None
    for attempt in range(attempts):
        response = requests.get(url, headers=UA, params=params, 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, params=None):
    return request(url, params=params).json()


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


def drop_layout_lines(text):
    """Drop interwiki-link blocks and category lines left as plain text after stripping.



    Interwiki tails ("de:X en:Y es:Z ...") and category names ("Kategoria:...")

    survive mwparserfromhell as ordinary lines; the cross-document boilerplate

    filter only removes lines frequent in >=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"(?<![.!?:;\n])\n(?!\n)(?=[a-ząćęłńóśźż])", " ", text)
    return re.sub(r"\n{3,}", "\n\n", text).strip()


def page_url(title, wiki=""):
    if wiki:
        # construct from wiki base
        return f"https://{wiki}.fandom.com/pl/wiki/" + quote((title or "").replace(" ", "_"), safe="/:")
    return SOURCE_URL


def normalize_title(text):
    text = unicodedata.normalize("NFKD", text or "").casefold()
    text = "".join(character for character in text if not unicodedata.combining(character))
    return " ".join(re.findall(r"\w+", text))


def shingle_sketch(text, limit=5_000):
    words = re.findall(r"\w+", text.casefold())
    hashes = set()
    for index in range(max(0, len(words) - 4)):
        value = " ".join(words[index:index + 5]).encode("utf-8")
        hashes.add(int.from_bytes(hashlib.blake2b(value, digest_size=8).digest(), "big"))
    if len(hashes) > 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()