ppuzio Claude Opus 5.5 commited on
Commit
5e556f6
·
1 Parent(s): 7ebe08c

nonsa: strip file/category wiki markup, cite origin license, drop decisions/ontology artifacts

Browse files

Address review on #41: category links removed and file links reduced to their
caption before strip_code(), with a regex pass for links left verbatim by
malformed markup; magic words removed. Shard rebuilt (12,304 records,
16,883,883 tokens). Datasheet links the archive.org license field and the
dumped siteinfo rightsinfo, and states NERGAL has not run.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

artifacts/nonsa_ontology_manifest.json DELETED
@@ -1,131 +0,0 @@
1
- {
2
- "actors": [
3
- {
4
- "id": "actor:piotrsty",
5
- "type": "Contributor"
6
- },
7
- {
8
- "id": "actor:nonsensopedia-community",
9
- "type": "Organization"
10
- },
11
- {
12
- "id": "actor:wikiteam",
13
- "type": "Organization"
14
- },
15
- {
16
- "id": "actor:devin",
17
- "type": "Agent"
18
- }
19
- ],
20
- "claims": [
21
- {
22
- "falsification_condition": "The pinned Parquet or decisions do not reproduce this count.",
23
- "id": "claim:nonsa-target-retention",
24
- "statement": "The proposed DynaWord slice contains 12391 records.",
25
- "supported_by": [
26
- "evidence:nonsa-target-stats:849f2e838d50e3df9e354228bb00c8703725de9780386ff14904fe3f655d46f3"
27
- ]
28
- },
29
- {
30
- "falsification_condition": "Target-wide text deduplication and controlled ablations establish those properties.",
31
- "id": "claim:nonsa-training-value-untested",
32
- "statement": "Net text novelty and training benefit remain untested hypotheses; parody-of-real-content overlap is untested.",
33
- "supported_by": [
34
- "evidence:nonsa-target-overlap:1c54969111d23fb88d4f47f264d1da5a570f35fee9b171ed3a63eedca45ada1a"
35
- ]
36
- }
37
- ],
38
- "evidence": [
39
- {
40
- "artifact": "data/nonsa/nonsa.stats.json",
41
- "content_address": "849f2e838d50e3df9e354228bb00c8703725de9780386ff14904fe3f655d46f3",
42
- "id": "evidence:nonsa-target-stats:849f2e838d50e3df9e354228bb00c8703725de9780386ff14904fe3f655d46f3",
43
- "observation_type": "target_slice_counts",
44
- "produced_by": "run:nonsa-dynaword-integration:849f2e838d50e3df9e354228bb00c8703725de9780386ff14904fe3f655d46f3"
45
- },
46
- {
47
- "artifact": "data/nonsa/nonsa.overlap_audit.json",
48
- "content_address": "1c54969111d23fb88d4f47f264d1da5a570f35fee9b171ed3a63eedca45ada1a",
49
- "id": "evidence:nonsa-target-overlap:1c54969111d23fb88d4f47f264d1da5a570f35fee9b171ed3a63eedca45ada1a",
50
- "observation_type": "namespace_overlap_audit",
51
- "produced_by": "run:nonsa-dynaword-integration:849f2e838d50e3df9e354228bb00c8703725de9780386ff14904fe3f655d46f3"
52
- }
53
- ],
54
- "objects": [
55
- {
56
- "id": "object:dataset:nonsa-content",
57
- "type": "Dataset"
58
- },
59
- {
60
- "id": "object:dataset:nonsa-dynaword-slice",
61
- "type": "Dataset"
62
- }
63
- ],
64
- "pending": [
65
- "cross-source text deduplication",
66
- "benchmark contamination check",
67
- "parody-of-real-content screening",
68
- "controlled training ablation"
69
- ],
70
- "protocols": [
71
- {
72
- "id": "protocol:nonsa-dynaword-integration-v1",
73
- "procedure": "carry over the source slice verbatim; ID disjointness already audited vs wikipedia shard"
74
- }
75
- ],
76
- "relations": [
77
- {
78
- "predicate": "DERIVED_FROM",
79
- "source": "version:dataset:nonsa-dynaword:e1257107cddaf63ce69b53055ce5d86cf3401f02f61c8e62e7579cd7d6920a73",
80
- "target": "hf:dataset:PiotrSty/nonsa-pl@09f62dc3826159dbc8c0df7a95243a18ec52abda"
81
- },
82
- {
83
- "predicate": "GENERATED_BY",
84
- "source": "version:dataset:nonsa-dynaword:e1257107cddaf63ce69b53055ce5d86cf3401f02f61c8e62e7579cd7d6920a73",
85
- "target": "run:nonsa-dynaword-integration:849f2e838d50e3df9e354228bb00c8703725de9780386ff14904fe3f655d46f3"
86
- },
87
- {
88
- "predicate": "VALIDATED_AGAINST",
89
- "source": "version:dataset:nonsa-dynaword:e1257107cddaf63ce69b53055ce5d86cf3401f02f61c8e62e7579cd7d6920a73",
90
- "target": "hf:dataset:SlayerLab/polish-dynaword@1564cb054434ba049cbd0d355a9bfaf044b6a852"
91
- }
92
- ],
93
- "runs": [
94
- {
95
- "actor": "actor:devin",
96
- "finished_at": "2026-09-28T14:29:24.077299+00:00",
97
- "id": "run:nonsa-dynaword-integration:849f2e838d50e3df9e354228bb00c8703725de9780386ff14904fe3f655d46f3",
98
- "protocol": "protocol:nonsa-dynaword-integration-v1",
99
- "started_at": "2026-09-28T14:29:24.077299+00:00",
100
- "stats": {
101
- "added": "2026-09-28",
102
- "boilerplate_lines_removed": 9,
103
- "characters": 44870619,
104
- "dump_date": "20251009",
105
- "kept": 12391,
106
- "license_counts": {
107
- "CC-BY-SA-3.0": 12391
108
- },
109
- "sample_count": 12,
110
- "source_pages": 26781,
111
- "source_slice_kept": 12391,
112
- "target_revision": "1564cb054434ba049cbd0d355a9bfaf044b6a852",
113
- "tokens": 17107478
114
- },
115
- "success": true
116
- }
117
- ],
118
- "schema": "slayer-research-ontology-profile-v1",
119
- "versions": [
120
- {
121
- "content_address": "09f62dc3826159dbc8c0df7a95243a18ec52abda",
122
- "id": "hf:dataset:PiotrSty/nonsa-pl@09f62dc3826159dbc8c0df7a95243a18ec52abda",
123
- "object": "object:dataset:nonsa-content"
124
- },
125
- {
126
- "content_address": "e1257107cddaf63ce69b53055ce5d86cf3401f02f61c8e62e7579cd7d6920a73",
127
- "id": "version:dataset:nonsa-dynaword:e1257107cddaf63ce69b53055ce5d86cf3401f02f61c8e62e7579cd7d6920a73",
128
- "object": "object:dataset:nonsa-dynaword-slice"
129
- }
130
- ]
131
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
data/nonsa/NOTICE.md CHANGED
@@ -2,6 +2,6 @@
2
 
3
  Source: Nonsensopedia, https://nonsa.pl/ - a Polish-language satirical community wiki.
4
 
5
- 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 (https://archive.org/details/wiki-nonsa.pl-20251009).
6
 
7
  Preparation: Piotr Styla with Devin. Changes: content-namespace filtering, 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.
 
2
 
3
  Source: Nonsensopedia, https://nonsa.pl/ - a Polish-language satirical community wiki.
4
 
5
+ 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 `nonsa.attribution.jsonl`; each page's revision history lists its contributors. Dump archived by the WikiTeam preservation project (https://archive.org/details/wiki-nonsa.pl-20251009).
6
 
7
  Preparation: Piotr Styla with Devin. Changes: content-namespace filtering, 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.
data/nonsa/nonsa.attribution.jsonl CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:bdb7b3c41f053ecae30a8ff08227d3e8402d9354e74c810115e74ed130369666
3
- size 11261414
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6f892a1a69e2c98a4a36784a8bef5232a6711e72f8da74444853a0584d4655cd
3
+ size 11169936
data/nonsa/nonsa.checksums.json CHANGED
@@ -1,11 +1,10 @@
1
- {
2
- "NOTICE.md": "3f204a8d97c00f35f68e7ed2adf2eaac202e3a4e42a8ccaf1c8c65bd88664e0f",
3
- "nonsa.attribution.jsonl": "bdb7b3c41f053ecae30a8ff08227d3e8402d9354e74c810115e74ed130369666",
4
- "nonsa.decisions.jsonl": "d5326e406636063c35b49fed5118dae052a952fb1235d7a980525c798c389965",
5
- "nonsa.md": "9546710cfd91f21fd15c405d3bc02f63d5180a2b822b6788a12ed12142464b15",
6
- "nonsa.overlap_audit.json": "35f9f0b152dd5b550ab91986712ec0c449a5482af5b7587f9393021e2e39c0b2",
7
- "nonsa.parquet": "e1257107cddaf63ce69b53055ce5d86cf3401f02f61c8e62e7579cd7d6920a73",
8
- "nonsa.qa.json": "6af11df3f9687e6cefd591db96be4933ca0269c7fc2aa0641c4cc1dc1a07b0f6",
9
- "nonsa.sample.jsonl": "671e377529141e524c59dc9790482b4702d853d598a8297848d517bd5681f620",
10
- "nonsa.stats.json": "ccb9d1e9d3b9c359d6b3ba879119335d1162a8b8cdccddbf121ab2ce265f0f68"
11
- }
 
1
+ {
2
+ "NOTICE.md": "6f8499311cc7974784ade7c3e9dddcc63d6a246ce2ea4debae5942ec9a6947bb",
3
+ "nonsa.attribution.jsonl": "6f892a1a69e2c98a4a36784a8bef5232a6711e72f8da74444853a0584d4655cd",
4
+ "nonsa.md": "d50b337d3c11ca9864a80052791551908216df5d49835dd3557aaecaf54e7f92",
5
+ "nonsa.overlap_audit.json": "35f9f0b152dd5b550ab91986712ec0c449a5482af5b7587f9393021e2e39c0b2",
6
+ "nonsa.parquet": "e83dbba88dac95728ec8db4d949e3a3f8628e15a3b3619a19267c657c65e0bc8",
7
+ "nonsa.qa.json": "b354ebe72c85f6ac59d89307c27dab994b904fa6988d10ff913d88b9a164905b",
8
+ "nonsa.sample.jsonl": "70dc17de3b22f10837a91e932d2e6ce3c010c17d37d45f9aa9d2aff86653c200",
9
+ "nonsa.stats.json": "a66a73581a25733aaf33505fc9b5a8192f8aefd134af638c42adce94df3d3d2e"
10
+ }
 
data/nonsa/nonsa.decisions.jsonl DELETED
The diff for this file is too large to render. See raw diff
 
data/nonsa/nonsa.md CHANGED
@@ -1,31 +1,63 @@
1
- # Nonsensopedia - Polish satirical wiki (content namespaces) - CC BY-SA 3.0
2
-
3
- This slice is rebuilt deterministically from the pinned wikiteam3 dump
4
- `nonsa.pl-20251009-history.xml.zst`
5
- (https://archive.org/details/wiki-nonsa.pl-20251009, sha1-verified). Scope is the content namespaces:
6
- 0 (articles), 100 (Cytaty), 102 (NonNews), 104 (NonZrodla), 106 (Slownik),
7
- 108 (Gra), 110 (Forum), 114 (Poradnik); the latest revision of each page.
8
- Nonsensopedia is the Polish satirical encyclopedia - informal, humorous,
9
- creative Polish covering parody reference text, fake news, quotes, forum
10
- discussions and interactive games - a register absent from the corpus.
11
-
12
- - Non-redirect content pages enumerated: 26,781
13
- - Source slice retained after QA/dedup: 12,391
14
- - Proposed records: 12,391
15
- - Proposed tokens: 17,107,478 (`cl100k_base` proxy)
16
- - Characters: 44,870,619
17
- - License: CC BY-SA 3.0 per record (site license, declared in the archive.org item metadata: https://creativecommons.org/licenses/by-sa/3.0/)
18
- - Immutable source snapshot: https://huggingface.co/datasets/PiotrSty/nonsa-pl/tree/09f62dc3826159dbc8c0df7a95243a18ec52abda
19
-
20
- Per-record page id, title, namespace, last-revision timestamp and canonical URL
21
- are preserved; page history is the contributor-attribution trail. Wikitext is
22
- stripped with mwparserfromhell; lines occurring in >=1% of documents are removed
23
- as cross-document boilerplate; emails, labelled phones, IP literals, labelled
24
- national identifiers and 26-digit account candidates are redacted (pattern
25
- redaction is not complete anonymization); exact and near deduplication applied
26
- within source.
27
-
28
- Limitations: deliberately non-factual register (satire, parody of real
29
- Wikipedia/cultural material); quoted passages are not guaranteed disjoint
30
- from other corpus shards. Record model is a whole content page; individual
31
- entries are not split.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Nonsensopedia - Polish satirical wiki (content namespaces) - CC BY-SA 3.0
2
+
3
+ This slice is rebuilt deterministically from the pinned wikiteam3 dump
4
+ `nonsa.pl-20251009-history.xml.zst`
5
+ (https://archive.org/details/wiki-nonsa.pl-20251009, sha1-verified). Scope is the content namespaces:
6
+ 0 (articles), 100 (Cytaty), 102 (NonNews), 104 (NonZrodla), 106 (Slownik),
7
+ 108 (Gra), 110 (Forum), 114 (Poradnik); the latest revision of each page.
8
+ Nonsensopedia is the Polish satirical encyclopedia - informal, humorous,
9
+ creative Polish covering parody reference text, fake news, quotes, forum
10
+ discussions and interactive games - a register absent from the corpus.
11
+
12
+ - Non-redirect content pages enumerated: 26,781
13
+ - Source slice retained after QA/dedup: 12,304 (14,477 rejected: 14,425 too little text after stripping, 27 non-Polish, 23 low letter ratio, 1 near duplicate, 1 too little text after redaction)
14
+ - Proposed records: 12,304
15
+ - Proposed tokens: 16,883,883 (`cl100k_base` proxy)
16
+ - Characters: 44,279,318
17
+ - Immutable source snapshot: https://huggingface.co/datasets/PiotrSty/nonsa-pl/tree/09f62dc3826159dbc8c0df7a95243a18ec52abda
18
+
19
+ ## License
20
+
21
+ CC BY-SA 3.0 per record, the site license of nonsa.pl. Where that is stated at the origin:
22
+
23
+ - archive.org item page https://archive.org/details/wiki-nonsa.pl-20251009, "License" field
24
+ (machine-readable in https://archive.org/metadata/wiki-nonsa.pl-20251009: `licenseurl:
25
+ http://creativecommons.org/licenses/by-sa/3.0/`, `rights: Creative Commons Attribution-ShareAlike 3.0`);
26
+ - the wiki's own `rightsinfo`, captured by WikiTeam at dump time in
27
+ https://archive.org/download/wiki-nonsa.pl-20251009/nonsa.pl-20251009-dumpMeta/siteinfo.json
28
+ (`{"text": "Creative Commons Attribution-ShareAlike 3.0", "url": "http://creativecommons.org/licenses/by-sa/3.0/"}`,
29
+ MediaWiki 1.37.6, sitename Nonsensopedia).
30
+
31
+ Attribution is per record via the canonical page URL (`nonsa.attribution.jsonl`); each page's
32
+ history lists its contributors. Embedded third-party quotations have not been reviewed.
33
+ ## Processing
34
+
35
+ Per-record page id, title, namespace, last-revision timestamp and canonical URL
36
+ are preserved; page history is the contributor-attribution trail. Wikitext is
37
+ stripped with mwparserfromhell (`strip_wikitext` in `src/build_nonsa_pl.py`). Before
38
+ `strip_code()`, category links (`[[Kategoria:…]]`) are removed and file links
39
+ (`[[Plik:…]]`, `Grafika:`, `File:`, `Image:`) are replaced by their caption only (the
40
+ last non-option parameter; `thumb`, `200px`, `right`, `alt=`… are dropped); inline
41
+ `[[:Kategoria:…]]` links keep their text. The same rule is re-applied to links left
42
+ verbatim in the output because malformed markup (e.g. an unclosed `''` in a caption) made
43
+ the parser read them as text. Magic words (`__NOTOC__` etc.) are removed. After this, 6 of
44
+ 12,304 records still contain a `NNpx|` option string and 107 a literal `{{` (templates
45
+ with unbalanced braces in the source wikitext); both are left as-is. Lines occurring in >=1% of documents are removed
46
+ as cross-document boilerplate; emails, labelled phones, IP literals, labelled
47
+ national identifiers and 26-digit account candidates are redacted (pattern
48
+ redaction is not complete anonymization); exact and near deduplication applied
49
+ within source.
50
+
51
+ ## PII
52
+
53
+ Scrubber: in-build pattern redaction only (emails, labelled phones, IPv4/IPv6 literals,
54
+ labelled PESEL/NIP/REGON, 26-digit account candidates; counts in `nonsa.qa.json`).
55
+ [SlayerLab/NERGAL](https://huggingface.co/SlayerLab/NERGAL) has **not** been run. This
56
+ source stays at `release: None` until the shard is re-run through NERGAL.
57
+
58
+ ## Limitations
59
+
60
+ Deliberately non-factual register (satire, parody of real
61
+ Wikipedia/cultural material); quoted passages are not guaranteed disjoint
62
+ from other corpus shards. Record model is a whole content page; individual
63
+ entries are not split.
data/nonsa/nonsa.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:e1257107cddaf63ce69b53055ce5d86cf3401f02f61c8e62e7579cd7d6920a73
3
- size 23380290
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e83dbba88dac95728ec8db4d949e3a3f8628e15a3b3619a19267c657c65e0bc8
3
+ size 23155214
data/nonsa/nonsa.qa.json CHANGED
@@ -1,17 +1,38 @@
1
- {
2
- "benchmark_overlap": "pending",
3
- "cross_source_text_dedup": "pending target integration",
4
- "id_collisions_vs_wikipedia_shard": 0,
5
- "license_terms_url": "https://creativecommons.org/licenses/by-sa/3.0/",
6
- "limitations": [
7
- "satirical/humorous register: parody articles, fake news (NonNews), fake dictionary entries (Slownik), quotes (Cytaty), forum posts and games; not factual reference text",
8
- "pages may parody or quote real Wikipedia/cultural material; quoted passages are not guaranteed disjoint from other shards",
9
- "record model is a whole content page; individual entries/comments are not split",
10
- "pattern checks are not comprehensive de-identification"
11
- ],
12
- "overlap_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.",
13
- "pii_policy": "IPv6 parsed including compressed notation; labelled PESEL/NIP/REGON and 26-digit account candidates masked conservatively without checksum validation; not complete anonymization",
14
- "scope": "DynaWord proposal: Nonsensopedia content namespaces (0 articles, 100 Cytaty, 102 NonNews, 104 NonZrodla, 106 Slownik, 108 Gra, 110 Forum, 114 Poradnik) - satirical/humorous Polish register",
15
- "source_text_qa_rejected": 14390,
16
- "within_source_exact_and_near_dedup": true
17
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "benchmark_overlap": "pending",
3
+ "boilerplate": "lines occurring in >= 1% of documents removed (7 patterns); 0 high-df shingles excluded from near-dedup sketches (df>133 over 6696 sampled docs)",
4
+ "created_field_semantics": "Last revision date from the dump, not the page creation date",
5
+ "cross_source_text_dedup": "pending target integration",
6
+ "exact_dedup": true,
7
+ "language_gate": "independent three-window langid vote",
8
+ "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",
9
+ "license_terms_url": "https://creativecommons.org/licenses/by-sa/3.0/",
10
+ "limitations": [
11
+ "satirical/humorous register: parody articles, fake news (NonNews), fake dictionary entries (Slownik), quotes (Cytaty), forum posts and games; not factual reference text",
12
+ "pages may parody or quote real Wikipedia/cultural material; quoted passages are not guaranteed disjoint from other shards",
13
+ "record model is a whole content page; individual entries/comments are not split",
14
+ "pattern checks are not comprehensive de-identification"
15
+ ],
16
+ "minimum_final_text_characters": 500,
17
+ "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",
18
+ "pii_limitations": "Unlabelled national identifiers, free-form phone numbers, names and personal disclosures may remain; this is not complete anonymization",
19
+ "pii_pattern_matches": {
20
+ "account_candidate": 12,
21
+ "email": 39,
22
+ "ipv4": 239,
23
+ "ipv6": 11,
24
+ "ipv6_legacy_pattern": 3,
25
+ "labelled_phone": 18,
26
+ "national_identifier": 0
27
+ },
28
+ "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",
29
+ "rejection_counts": {
30
+ "low_letter_ratio": 23,
31
+ "near_duplicate": 1,
32
+ "non_polish_text": 27,
33
+ "too_little_text": 14425,
34
+ "too_little_text_after_redaction": 1
35
+ },
36
+ "scope": "Nonsensopedia content namespaces (0 articles, 100 Cytaty, 102 NonNews, 104 NonZrodla, 106 Slownik, 108 Gra, 110 Forum, 114 Poradnik), latest revision per page from the wikiteam3 archive.org dump",
37
+ "wikipedia_shard_overlap": "pending"
38
+ }
data/nonsa/nonsa.sample.jsonl CHANGED
The diff for this file is too large to render. See raw diff
 
data/nonsa/nonsa.stats.json CHANGED
@@ -1,15 +1,15 @@
1
- {
2
- "added": "2026-09-28",
3
- "boilerplate_lines_removed": 9,
4
- "characters": 44870619,
5
- "dump_date": "20251009",
6
- "kept": 12391,
7
- "license_counts": {
8
- "CC-BY-SA-3.0": 12391
9
- },
10
- "sample_count": 12,
11
- "source_pages": 26781,
12
- "source_slice_kept": 12391,
13
- "target_revision": "1564cb054434ba049cbd0d355a9bfaf044b6a852",
14
- "tokens": 17107478
15
- }
 
1
+ {
2
+ "added": "2026-09-29",
3
+ "boilerplate_lines_removed": 7,
4
+ "characters": 44279318,
5
+ "dump_date": "20251009",
6
+ "kept": 12304,
7
+ "license_counts": {
8
+ "CC-BY-SA-3.0": 12304
9
+ },
10
+ "sample_count": 12,
11
+ "source_pages": 26781,
12
+ "source_slice_kept": 12304,
13
+ "target_revision": "1564cb054434ba049cbd0d355a9bfaf044b6a852",
14
+ "tokens": 16883883
15
+ }
src/build_nonsa_pl.py CHANGED
@@ -1,880 +1,959 @@
1
- #!/usr/bin/env python3
2
- """Build an auditable slice of Nonsensopedia (nonsa.pl) content namespaces, CC BY-SA 3.0."""
3
- from __future__ import annotations
4
-
5
- import argparse
6
- from collections import Counter
7
- from concurrent.futures import ProcessPoolExecutor
8
- from datetime import datetime, timezone
9
- from difflib import SequenceMatcher
10
- import gzip
11
- import hashlib
12
- import ipaddress
13
- import json
14
- from pathlib import Path
15
- import re
16
- import time
17
- import unicodedata
18
- from xml.etree.ElementTree import iterparse
19
- from urllib.parse import quote
20
-
21
- import requests
22
-
23
-
24
- SOURCE = "nonsa"
25
- OWN_REPO = "PiotrSty/nonsa-pl"
26
- TARGET = "SlayerLab/polish-dynaword"
27
- DUMP_DATE = "20251009"
28
- IA_ITEM = f"wiki-nonsa.pl-{DUMP_DATE}"
29
- IA_META_URL = f"https://archive.org/metadata/{IA_ITEM}"
30
- IA_FILE = f"nonsa.pl-{DUMP_DATE}-history.xml.zst"
31
- SOURCE_URL = "https://nonsa.pl/"
32
- FIELDS = ["id", "text", "source", "added", "created", "token_count", "license", "author"]
33
- UA = {"User-Agent": "polish-dynaword/0.2 (+research; openly-licensed corpus)"}
34
- LICENSE_SPDX = "CC-BY-SA-3.0"
35
- LICENSE_TERMS_URL = "https://creativecommons.org/licenses/by-sa/3.0/"
36
- IA_ITEM_URL = f"https://archive.org/details/{IA_ITEM}"
37
- # Content namespaces: 0 articles, 100 Cytaty, 102 NonNews, 104 NonZrodla,
38
- # 106 Slownik, 108 Gra, 110 Forum, 114 Poradnik
39
- CONTENT_NS = {"0", "100", "102", "104", "106", "108", "110", "114"}
40
- MIN_TEXT_CHARS = 500
41
- BOILERPLATE_MIN_DOC_FREQ = 0.01
42
- DF_FRACTION = 0.02 # shingles in >2% of docs are template boilerplate
43
- DF_SUBSAMPLE_STRIDE = 4 # document-frequency pass samples every Nth document
44
- EMAIL_RE = re.compile(r"(?i)\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b")
45
- PHONE_RE = re.compile(r"(?i)(?:\btelefon|\btel\.|\bphone)\s*:?[ \t]*(?:\+48[ \t]*)?\d(?:[ .-]?\d){8}\b")
46
- IPV4_RE = re.compile(r"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b")
47
- IPV6_RE = re.compile(r"(?i)\b(?:[0-9a-f]{1,4}:){3,}[0-9a-f]{1,4}\b")
48
-
49
-
50
- IPV6_CANDIDATE_RE = re.compile(r"(?<![\w:])(?:[0-9a-fA-F]{0,4}:){2,}[0-9a-fA-F:.]*(?![\w:])")
51
- NATIONAL_ID_RE = re.compile(r"(?i)\b(PESEL|NIP|REGON)\s*[:=]?\s*\d(?:[ -]?\d){8,13}\b")
52
- BANK_ACCOUNT_RE = re.compile(r"(?<!\d)(?:PL\s*)?\d{2}(?:[ -]?\d){24}(?!\d)")
53
-
54
-
55
- def is_ipv6(value):
56
- try:
57
- return ipaddress.ip_address(value.rstrip(".")).version == 6
58
- except ValueError:
59
- return False
60
-
61
-
62
- def redact_pii(text):
63
- counts = Counter()
64
-
65
- def replace_ipv6(match):
66
- value = match.group().rstrip(".")
67
- if not is_ipv6(value):
68
- return match.group()
69
- counts["ipv6"] += 1
70
- return "[REDACTED:IP]" + match.group()[len(value):]
71
-
72
- text = IPV6_CANDIDATE_RE.sub(replace_ipv6, text)
73
- for name, pattern, replacement in (
74
- ("email", EMAIL_RE, "[REDACTED:EMAIL]"),
75
- ("labelled_phone", PHONE_RE, "[REDACTED:PHONE]"),
76
- ("ipv4", IPV4_RE, "[REDACTED:IP]"),
77
- ("ipv6_legacy_pattern", IPV6_RE, "[REDACTED:IP]"),
78
- ("national_identifier", NATIONAL_ID_RE, lambda match: match.group(1) + " [REDACTED:ID]"),
79
- ("account_candidate", BANK_ACCOUNT_RE, "[REDACTED:ACCOUNT]"),
80
- ):
81
- text, count = pattern.subn(replacement, text)
82
- counts[name] += count
83
- return text, counts
84
-
85
-
86
- def now():
87
- return datetime.now(timezone.utc).isoformat()
88
-
89
-
90
- def digest(value):
91
- if not isinstance(value, bytes):
92
- value = json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode("utf-8")
93
- return hashlib.sha256(value).hexdigest()
94
-
95
-
96
- def sha1_file(path):
97
- h = hashlib.sha1()
98
- with path.open("rb") as handle:
99
- while chunk := handle.read(1 << 22):
100
- h.update(chunk)
101
- return h.hexdigest()
102
-
103
-
104
- def save(path, value):
105
- path.parent.mkdir(parents=True, exist_ok=True)
106
- path.write_text(json.dumps(value, ensure_ascii=False, sort_keys=True, indent=2) + "\n", encoding="utf-8")
107
-
108
-
109
- def write_lines(path, rows):
110
- path.parent.mkdir(parents=True, exist_ok=True)
111
- with path.open("w", encoding="utf-8") as handle:
112
- for row in rows:
113
- handle.write(json.dumps(row, ensure_ascii=False, sort_keys=True) + "\n")
114
-
115
-
116
- def read_lines(path):
117
- return [json.loads(line) for line in path.read_text(encoding="utf-8").split("\n") if line]
118
-
119
-
120
- def load(path):
121
- return json.loads(path.read_text(encoding="utf-8"))
122
-
123
-
124
- def request(url, attempts=5, timeout=(15, 90)):
125
- response = None
126
- for attempt in range(attempts):
127
- response = requests.get(url, headers=UA, timeout=timeout)
128
- if response.status_code not in (429, 500, 502, 503, 504):
129
- response.raise_for_status()
130
- return response
131
- time.sleep(2 ** attempt)
132
- response.raise_for_status()
133
-
134
-
135
- def request_json(url):
136
- return request(url).json()
137
-
138
-
139
- def _local(tag):
140
- return tag.rsplit("}", 1)[-1]
141
-
142
-
143
- def strip_wikitext(wikitext):
144
- import mwparserfromhell
145
- try:
146
- return mwparserfromhell.parse(wikitext).strip_code(normalize=True, collapse=True).strip()
147
- except Exception:
148
- return ""
149
-
150
-
151
- def _strip_batch(items):
152
- return [strip_wikitext(wikitext) for _, _, _, _, wikitext in items]
153
-
154
-
155
- def discover(out):
156
- metadata = request_json(IA_META_URL)
157
- license_url = (metadata.get("metadata") or {}).get("licenseurl")
158
- files = []
159
- for item in metadata.get("files", []):
160
- if item.get("name") == IA_FILE:
161
- files.append({"name": item["name"],
162
- "url": f"https://archive.org/download/{IA_ITEM}/{item['name']}",
163
- "size": int(item["size"]), "sha1": item.get("sha1"),
164
- "md5": item.get("md5"), "format": item.get("format")})
165
- if not files:
166
- raise ValueError(f"history dump {IA_FILE} not found in {IA_ITEM}")
167
- selection = {
168
- "observed_at": now(), "dump_date": DUMP_DATE,
169
- "archive_org_item": IA_ITEM, "archive_org_metadata_url": IA_META_URL,
170
- "files": files, "total_bytes": sum(item["size"] for item in files),
171
- "content_namespaces": sorted(CONTENT_NS, key=int), "min_text_chars": MIN_TEXT_CHARS,
172
- "license": "CC BY-SA 3.0 (Nonsensopedia site license; archive.org item licenseurl)",
173
- "license_url_observed": license_url,
174
- "dump_producer": "wikiteam3 (https://github.com/saveweb/wikiteam3/)",
175
- "files_sha256": digest(files),
176
- }
177
- save(out / "selection.json", selection)
178
- print(json.dumps({k: selection[k] for k in ("dump_date", "total_bytes")}, indent=2))
179
- print("files:", len(files))
180
-
181
-
182
- def parse_dump(path):
183
- """wikiteam3 xmlrevisions export: each <page> element carries one <revision>;
184
- group by pageid and keep the latest revision (max timestamp) per page."""
185
- import zstandard
186
-
187
- latest = {}
188
- dctx = zstandard.ZstdDecompressor(max_window_size=2 ** 31)
189
- with path.open("rb") as raw, dctx.stream_reader(raw) as fh:
190
- title = ns = pageid = timestamp = text = None
191
- redirect = False
192
- for ev, el in iterparse(fh, events=("end",)):
193
- tag = _local(el.tag)
194
- if tag == "title":
195
- title = el.text
196
- elif tag == "ns":
197
- ns = el.text
198
- elif tag == "id" and pageid is None:
199
- pageid = el.text
200
- elif tag == "timestamp":
201
- timestamp = el.text
202
- elif tag == "redirect":
203
- redirect = True
204
- elif tag == "text":
205
- text = el.text
206
- elif tag == "page":
207
- if ns in CONTENT_NS and not redirect:
208
- current = latest.get(pageid)
209
- if current is None or (timestamp or "") > (current[3] or ""):
210
- latest[pageid] = (pageid, ns, title, timestamp, text)
211
- title = ns = pageid = timestamp = text = None
212
- redirect = False
213
- el.clear()
214
- return [record for record in latest.values() if record[4]]
215
-
216
-
217
- def acquire(out, workers):
218
- selection = load(out / "selection.json")
219
- dump_dir = out / "raw_dump"
220
- dump_dir.mkdir(parents=True, exist_ok=True)
221
- extracted_dir = out / "extracted"
222
- extracted_dir.mkdir(exist_ok=True)
223
- manifest = []
224
- for item in selection["files"]:
225
- dst = dump_dir / item["name"]
226
- if not dst.exists() or dst.stat().st_size != item["size"]:
227
- print(f" pobieram {item['name']} ({item['size']/1e6:.0f} MB)", flush=True)
228
- for attempt in range(8):
229
- have = dst.stat().st_size if dst.exists() else 0
230
- headers = dict(UA)
231
- if have:
232
- headers["Range"] = f"bytes={have}-"
233
- try:
234
- with requests.get(item["url"], headers=headers, stream=True, timeout=(15, 300)) as r:
235
- r.raise_for_status()
236
- if have and r.status_code != 206:
237
- have = 0
238
- with dst.open("ab" if have else "wb") as f:
239
- for chunk in r.iter_content(1 << 22):
240
- f.write(chunk)
241
- break
242
- except requests.RequestException as error:
243
- print(f" retry {item['name']}: {type(error).__name__}", flush=True)
244
- time.sleep(min(2 ** attempt, 60))
245
- else:
246
- raise RuntimeError(f"download failed: {item['name']}")
247
- sha = sha1_file(dst)
248
- if item["sha1"] and sha != item["sha1"]:
249
- raise ValueError(f"sha1 mismatch {item['name']}: {sha} != {item['sha1']}")
250
- print(f" {item['name']} sha1 OK", flush=True)
251
-
252
- out_path = extracted_dir / (item["name"] + ".jsonl.gz")
253
- if not out_path.exists():
254
- records = parse_dump(dst)
255
- batches = [records[i:i + 2000] for i in range(0, len(records), 2000)]
256
- with ProcessPoolExecutor(max_workers=workers) as pool:
257
- texts = [text for batch in pool.map(_strip_batch, batches) for text in batch]
258
- with gzip.open(out_path, "wt", encoding="utf-8") as f:
259
- for (pageid, ns, title, timestamp, wikitext), text in zip(records, texts):
260
- f.write(json.dumps({"pageid": pageid, "ns": ns, "title": title,
261
- "timestamp": timestamp, "wikitext_chars": len(wikitext),
262
- "text": text}, ensure_ascii=False) + "\n")
263
- shard_records = 0
264
- kept_chars = 0
265
- with gzip.open(out_path, "rt", encoding="utf-8") as f:
266
- for line in f:
267
- row = json.loads(line)
268
- shard_records += 1
269
- kept_chars += len(row["text"])
270
- manifest.append({"pageid": row["pageid"], "ns": row["ns"], "title": row["title"],
271
- "timestamp": row["timestamp"],
272
- "url": page_url(row["title"])})
273
- print(f" {item['name']}: {shard_records} stron tresci", flush=True)
274
- write_lines(out / "source_manifest.jsonl", manifest)
275
- acquisition = {
276
- "observed_at": now(), "dump_date": selection["dump_date"],
277
- "files": selection["files"], "source_pages": len(manifest),
278
- "manifest_sha256": digest((out / "source_manifest.jsonl").read_bytes()),
279
- }
280
- save(out / "acquisition.json", acquisition)
281
- print(json.dumps(acquisition, ensure_ascii=False, indent=2))
282
-
283
-
284
- def strip_boilerplate(texts_index):
285
- counts = Counter()
286
- for lines in texts_index:
287
- counts.update(set(re.sub(r"\s+", " ", line).strip() for line in lines if line.strip()))
288
- n = len(texts_index)
289
- return {line for line, count in counts.items()
290
- if count / n >= BOILERPLATE_MIN_DOC_FREQ and len(line) < 160}
291
-
292
-
293
- def normalize(text):
294
- text = unicodedata.normalize("NFKC", text or "").replace("­", "").replace("​", "")
295
- text = re.sub(r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]", "", text)
296
- lines = [re.sub(r"[ \t\xa0]+", " ", line).strip() for line in text.splitlines()]
297
- lines = [line for line in lines if not re.fullmatch(r"\d{1,4}", line)]
298
- text = "\n".join(lines)
299
- text = re.sub(r"(?<=\w)-\n(?=[a-ząćęłńóśźż])", "", text)
300
- text = re.sub(r"(?<![.!?:;\n])\n(?!\n)(?=[a-ząćęłńóśźż])", " ", text)
301
- return re.sub(r"\n{3,}", "\n\n", text).strip()
302
-
303
-
304
- def page_url(title):
305
- return SOURCE_URL + "wiki/" + quote((title or "").replace(" ", "_"), safe="/:")
306
-
307
-
308
- def normalize_title(text):
309
- text = unicodedata.normalize("NFKD", text or "").casefold()
310
- text = "".join(character for character in text if not unicodedata.combining(character))
311
- return " ".join(re.findall(r"\w+", text))
312
-
313
-
314
- def shingle_sketch(text, limit=5_000):
315
- words = re.findall(r"\w+", text.casefold())
316
- hashes = set()
317
- for index in range(max(0, len(words) - 4)):
318
- value = " ".join(words[index:index + 5]).encode("utf-8")
319
- hashes.add(int.from_bytes(hashlib.blake2b(value, digest_size=8).digest(), "big"))
320
- if len(hashes) > limit:
321
- return set(sorted(hashes)[:limit])
322
- return hashes
323
-
324
-
325
- def boilerplate_shingles(candidates, boilerplate, stride=DF_SUBSAMPLE_STRIDE, fraction=DF_FRACTION):
326
- df = Counter()
327
- sampled = 0
328
- for index, record in enumerate(candidates):
329
- if index % stride:
330
- continue
331
- text = "\n".join(line for line in record["text"].splitlines()
332
- if re.sub(r"\s+", " ", line).strip() not in boilerplate)
333
- text = re.sub(r"\n{3,}", "\n\n", text).strip()
334
- df.update(shingle_sketch(text))
335
- sampled += 1
336
- max_df = max(1, int(sampled * fraction))
337
- return {shingle for shingle, count in df.items() if count > max_df}, max_df, sampled
338
-
339
-
340
- def filter_sketch(sketch, hot):
341
- return {shingle for shingle in sketch if shingle not in hot}
342
-
343
-
344
- class NearDuplicateIndex:
345
- def __init__(self):
346
- self.postings = {}
347
- self.records = []
348
- self.comparisons = 0
349
-
350
- @staticmethod
351
- def prefix(sketch):
352
- return sorted(sketch)[:len(sketch) - (9 * len(sketch) + 9) // 10 + 1]
353
-
354
- def find(self, sketch):
355
- candidates = set()
356
- for value in self.prefix(sketch):
357
- candidates.update(self.postings.get(value, ()))
358
- for position in sorted(candidates):
359
- row_id, other = self.records[position]
360
- if 10 * min(len(sketch), len(other)) < 9 * max(len(sketch), len(other)):
361
- continue
362
- self.comparisons += 1
363
- intersection = len(sketch & other)
364
- score = intersection / max(len(sketch) + len(other) - intersection, 1)
365
- if score >= 0.90:
366
- return row_id, score
367
- return None, 0.0
368
-
369
- def add(self, row_id, sketch):
370
- position = len(self.records)
371
- self.records.append((row_id, sketch))
372
- for value in self.prefix(sketch):
373
- self.postings.setdefault(value, []).append(position)
374
-
375
-
376
- def language_vote(identifier, text):
377
- chunks = [text[:30_000], text[max(0, len(text) // 2 - 15_000):len(text) // 2 + 15_000], text[-30_000:]]
378
- classified = {chunk: identifier.classify(chunk) for chunk in dict.fromkeys(chunks) if chunk.strip()}
379
- votes = [classified[chunk] for chunk in chunks if chunk in classified]
380
- languages = Counter(language for language, _ in votes)
381
- return (languages.most_common(1)[0][0] if languages else "unknown", votes)
382
-
383
-
384
- def audit_target(out):
385
- info = request_json(f"https://huggingface.co/api/datasets/{TARGET}")
386
- revision = info["sha"]
387
- tree = request_json(f"https://huggingface.co/api/datasets/{TARGET}/tree/{revision}?recursive=true&expand=false")
388
- discussions = request_json(f"https://huggingface.co/api/datasets/{TARGET}/discussions?status=open&p=0")
389
- paths = sorted(item.get("path", "") for item in tree)
390
- open_rows = [{"num": item.get("num"), "title": item.get("title"), "status": item.get("status"),
391
- "author": item.get("author", {}).get("name")} for item in discussions.get("discussions", [])]
392
- terms = ("nonsa", "nonsensopedia")
393
- matches = [path for path in paths if any(term in path.casefold() for term in terms)]
394
- discussion_matches = [row for row in open_rows if any(term in (row.get("title") or "").casefold()
395
- for term in terms)]
396
- report = {
397
- "target": TARGET, "revision": revision, "last_modified": info.get("lastModified"),
398
- "tree_paths": len(paths), "source_path_matches": matches, "open_discussions": open_rows,
399
- "matching_open_discussions": discussion_matches, "source_absent": not matches and not discussion_matches,
400
- "observed_at": now(),
401
- }
402
- save(out / "target_audit.json", report)
403
- print(json.dumps({"revision": revision, "source_absent": report["source_absent"],
404
- "tree_matches": matches, "discussion_matches": discussion_matches}, ensure_ascii=False, indent=2))
405
-
406
-
407
- def audit_overlap(out):
408
- import pyarrow.parquet as pq
409
- from huggingface_hub import HfApi, HfFileSystem
410
-
411
- acquisition = load(out / "acquisition.json")
412
- revision = HfApi().dataset_info(TARGET).sha
413
- remote = f"datasets/{TARGET}@{revision}/data/wikipedia/wikipedia.parquet"
414
- with HfFileSystem().open(remote, "rb") as handle:
415
- table = pq.read_table(handle, columns=["id"])
416
- target_ids = set(table.column("id").to_pylist())
417
- candidate_ids = {f"{SOURCE}_{row['pageid']}" for row in read_lines(out / "source_manifest.jsonl")}
418
- collisions = sorted(candidate_ids & target_ids)
419
- report = {
420
- "target": f"{TARGET}:data/wikipedia", "target_revision": revision,
421
- "method": "Literal dataset-record ID comparison only. Source-specific ID prefixes make zero collisions "
422
- "uninformative about page identity or text overlap. No target namespace or text audit was performed.",
423
- "target_rows": table.num_rows, "candidate_records": len(candidate_ids),
424
- "id_collisions": collisions[:50], "collision_count": len(collisions),
425
- "text_overlap": "not tested; quoted-article passages and target-wide text dedup remain integration gates",
426
- "observed_at": now(),
427
- }
428
- save(out / "overlap_audit.json", report)
429
- print(json.dumps({key: report[key] for key in ("target_revision", "target_rows", "candidate_records",
430
- "collision_count")}, ensure_ascii=False, indent=2))
431
-
432
-
433
- def build(out):
434
- import pyarrow as pa
435
- import pyarrow.parquet as pq
436
- import tiktoken
437
- from langid.langid import LanguageIdentifier, model
438
-
439
- build_started_at = now()
440
- acquisition = load(out / "acquisition.json")
441
- selection = load(out / "selection.json")
442
- encoder = tiktoken.get_encoding("cl100k_base")
443
- identifier = LanguageIdentifier.from_modelstring(model, norm_probs=True)
444
- identifier.set_languages(["pl", "en", "de", "uk", "ru"])
445
-
446
- candidates = []
447
- for shard in sorted((out / "extracted").glob("*.jsonl.gz")):
448
- with gzip.open(shard, "rt", encoding="utf-8") as f:
449
- for line in f:
450
- row = json.loads(line)
451
- row["text"] = normalize(row["text"])
452
- candidates.append(row)
453
- boilerplate = strip_boilerplate([row["text"].splitlines() for row in candidates])
454
- print(f"boilerplate lines: {len(boilerplate)}", flush=True)
455
- hot, max_df, df_sampled = boilerplate_shingles(candidates, boilerplate)
456
- print(f"boilerplate shingles: {len(hot)} (df>{max_df} over {df_sampled} sampled docs)", flush=True)
457
-
458
- rows, attribution, decisions, exact_seen = [], [], [], {}
459
- near_index = NearDuplicateIndex()
460
- pii = Counter()
461
- added = acquisition["observed_at"][:10]
462
- started = last_progress = time.monotonic()
463
- for processed, record in enumerate(candidates, 1):
464
- current = time.monotonic()
465
- if current - last_progress >= 10 or processed == len(candidates):
466
- print(f" processed={processed - 1}/{len(candidates)} kept={len(rows)} "
467
- f"rate={(processed - 1) / max(current - started, 0.001):.1f}/s "
468
- f"near_comparisons={near_index.comparisons}", flush=True)
469
- last_progress = current
470
- text = "\n".join(line for line in record["text"].splitlines()
471
- if re.sub(r"\s+", " ", line).strip() not in boilerplate)
472
- text = re.sub(r"\n{3,}", "\n\n", text).strip()
473
- replacement_count = text.count("\ufffd")
474
- letters = len(re.findall(r"[A-Za-zĄĆĘŁŃÓŚŹŻąćęłńóśźż]", text))
475
- language, votes = "not_checked", []
476
- reason = ""
477
- if len(text) < MIN_TEXT_CHARS:
478
- reason = "too_little_text"
479
- elif letters / max(len(text), 1) < 0.5:
480
- reason = "low_letter_ratio"
481
- elif replacement_count > 100 or replacement_count / max(len(text), 1) > 0.002:
482
- reason = "excessive_replacement_characters"
483
- if not reason:
484
- language, votes = language_vote(identifier, text)
485
- if language != "pl":
486
- reason = "non_polish_text"
487
- text = text.replace("\ufffd", "[UNREADABLE_GLYPH]")
488
- text, pii_counts = redact_pii(text)
489
- pii.update(pii_counts)
490
- if not reason and len(text) < MIN_TEXT_CHARS:
491
- reason = "too_little_text_after_redaction"
492
- exact_key = digest(" ".join(text.casefold().split()).encode("utf-8"))
493
- duplicate_of, duplicate_score = None, 0.0
494
- if not reason and exact_key in exact_seen:
495
- reason, duplicate_of, duplicate_score = "normalized_duplicate", exact_seen[exact_key], 1.0
496
- if not reason:
497
- sketch = filter_sketch(shingle_sketch(text), hot)
498
- duplicate_of, duplicate_score = near_index.find(sketch)
499
- if duplicate_of is not None:
500
- reason = "near_duplicate"
501
- row_id = f"{SOURCE}_{record['pageid']}"
502
- decision = {
503
- "id": row_id, "selected": not bool(reason), "reason": reason or "include",
504
- "characters": len(text), "letter_ratio": letters / max(len(text), 1),
505
- "replacement_characters": replacement_count, "language": language,
506
- "language_votes": [{"language": lang, "confidence": float(score)} for lang, score in votes],
507
- }
508
- if duplicate_of:
509
- decision.update({"duplicate_of": duplicate_of, "jaccard": duplicate_score})
510
- decisions.append(decision)
511
- if reason:
512
- continue
513
- exact_seen[exact_key] = row_id
514
- near_index.add(row_id, sketch)
515
- row = {
516
- "id": row_id, "text": text, "source": SOURCE, "added": added,
517
- "created": (record["timestamp"] or "")[:10] or "unknown",
518
- "token_count": len(encoder.encode_ordinary(text)),
519
- "license": LICENSE_SPDX, "author": "nonsensopedia contributors",
520
- }
521
- rows.append(row)
522
- attribution.append({
523
- "id": row_id, "pageid": record["pageid"], "ns": record["ns"], "title": record["title"],
524
- "url": page_url(record["title"]),
525
- "last_revision_at": record["timestamp"], "wikitext_chars": record["wikitext_chars"],
526
- "license": LICENSE_SPDX,
527
- "license_evidence": LICENSE_TERMS_URL + " (site license via archive.org item metadata; attribution by page URL)",
528
- "dump": {"date": selection["dump_date"], "archive_org_item": selection["archive_org_item"],
529
- "files": [f["name"] for f in selection["files"]]},
530
- "text_sha256": digest(text.encode("utf-8")),
531
- "transformations": ["wikiteam3 xmlrevisions dump, latest revision per page", "mwparserfromhell wikitext strip",
532
- "cross-document boilerplate-line removal",
533
- "Unicode/whitespace normalization", "page-number-only removal",
534
- "line-wrap repair", "email/labelled-phone/IP/labelled-national-ID/account-candidate pattern redaction"],
535
- })
536
-
537
- root = out / "hf_repo"
538
- (root / "data").mkdir(parents=True, exist_ok=True)
539
- (root / "artifacts").mkdir(parents=True, exist_ok=True)
540
- schema = pa.schema([(field, pa.int64() if field == "token_count" else pa.string()) for field in FIELDS])
541
- pq.write_table(pa.Table.from_pylist(rows, schema=schema), root / "data/train-00000-of-00001.parquet", compression="zstd")
542
- write_lines(root / "artifacts/attribution.jsonl", attribution)
543
- write_lines(root / "artifacts/decisions.jsonl", decisions)
544
- write_lines(root / "artifacts/source_manifest.jsonl", read_lines(out / "source_manifest.jsonl"))
545
- sample = sorted(rows, key=lambda row: digest(("sample:" + row["id"]).encode("utf-8")))[:12]
546
- write_lines(root / "artifacts/sample.jsonl", sample)
547
- save(root / "artifacts/selection.json", selection)
548
- save(root / "artifacts/acquisition.json", acquisition)
549
- save(root / "artifacts/boilerplate_lines.json", sorted(boilerplate))
550
- overlap = load(out / "overlap_audit.json") if (out / "overlap_audit.json").exists() else None
551
- target_audit = load(out / "target_audit.json") if (out / "target_audit.json").exists() else None
552
- if overlap:
553
- save(root / "artifacts/overlap_audit.json", overlap)
554
- if target_audit:
555
- save(root / "artifacts/target_audit.json", target_audit)
556
- stats = {
557
- "dump_date": selection["dump_date"], "dump_files": len(selection["files"]),
558
- "source_pages": acquisition["source_pages"],
559
- "kept": len(rows), "rejected": len(decisions) - len(rows),
560
- "tokens": sum(row["token_count"] for row in rows),
561
- "characters": sum(len(row["text"]) for row in rows),
562
- "license_counts": dict(Counter(row["license"] for row in rows)),
563
- "boilerplate_lines_removed": len(boilerplate),
564
- "boilerplate_shingles_excluded": len(hot),
565
- "sample_count": len(sample), "added": added,
566
- }
567
- qa = {
568
- "scope": "Nonsensopedia content namespaces (0 articles, 100 Cytaty, 102 NonNews, 104 NonZrodla, 106 Slownik, 108 Gra, 110 Forum, 114 Poradnik), latest revision per page from the wikiteam3 archive.org dump",
569
- "license_terms_url": LICENSE_TERMS_URL,
570
- "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",
571
- "rejection_counts": dict(Counter(item["reason"] for item in decisions if not item["selected"])),
572
- "minimum_final_text_characters": MIN_TEXT_CHARS,
573
- "created_field_semantics": "Last revision date from the dump, not the page creation date",
574
- "language_gate": "independent three-window langid vote",
575
- "pii_pattern_matches": dict(pii), "exact_dedup": True,
576
- "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",
577
- "pii_limitations": "Unlabelled national identifiers, free-form phone numbers, names and personal disclosures may remain; this is not complete anonymization",
578
- "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",
579
- "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)",
580
- "wikipedia_shard_overlap": overlap or "pending", "cross_source_text_dedup": "pending target integration",
581
- "benchmark_overlap": "pending", "limitations": [
582
- "satirical/humorous register: parody articles, fake news (NonNews), fake dictionary entries (Slownik), quotes (Cytaty), forum posts and games; not factual reference text",
583
- "pages may parody or quote real Wikipedia/cultural material; quoted passages are not guaranteed disjoint from other shards",
584
- "record model is a whole content page; individual entries/comments are not split",
585
- "pattern checks are not comprehensive de-identification",
586
- ],
587
- }
588
- save(root / "artifacts/stats.json", stats)
589
- save(root / "artifacts/qa.json", qa)
590
- protocol_id = "protocol:nonsa-content-v1"
591
- run = {
592
- "id": "run:" + digest({"script": digest(Path(__file__).read_bytes()), "selection": selection,
593
- "acquisition": digest(acquisition)}),
594
- "protocol": protocol_id, "started_at": build_started_at, "finished_at": now(),
595
- "success": True, "actor": "actor:devin", "stats": stats,
596
- }
597
- save(root / "artifacts/run.json", run)
598
- excluded = {"README.md", "NOTICE.md", "artifacts/checksums.json", "artifacts/ontology.json"}
599
- checks = {path.relative_to(root).as_posix(): digest(path.read_bytes()) for path in sorted(root.rglob("*"))
600
- if path.is_file()
601
- and path.relative_to(root).as_posix() not in excluded
602
- and not path.relative_to(root).as_posix().startswith("src/")}
603
- save(root / "artifacts/checksums.json", checks)
604
- source_version = "version:source:" + digest(selection["files"])
605
- dataset_version = "version:dataset:" + digest(checks)
606
- selection_evidence = "evidence:selection:" + digest(selection)
607
- acquisition_evidence = "evidence:acquisition:" + digest(acquisition)
608
- qa_evidence = "evidence:qa:" + digest(qa)
609
- evidence = [
610
- {"id": selection_evidence, "observation_type": "dump_inventory_and_pinning",
611
- "artifact": "artifacts/selection.json", "content_address": digest(selection), "produced_by": run["id"]},
612
- {"id": acquisition_evidence, "observation_type": "dump_download_sha1_and_extraction",
613
- "artifact": "artifacts/acquisition.json", "content_address": digest(acquisition), "produced_by": run["id"]},
614
- {"id": qa_evidence, "observation_type": "source_qa", "artifact": "artifacts/qa.json",
615
- "content_address": digest(qa), "produced_by": run["id"]},
616
- ]
617
- overlap_evidence = None
618
- if overlap:
619
- overlap_evidence = "evidence:overlap:" + digest(overlap)
620
- evidence.append({"id": overlap_evidence, "observation_type": "namespace_overlap_audit",
621
- "artifact": "artifacts/overlap_audit.json", "content_address": digest(overlap),
622
- "produced_by": run["id"]})
623
- target_evidence = None
624
- if target_audit:
625
- target_evidence = "evidence:target:" + digest(target_audit)
626
- evidence.append({"id": target_evidence, "observation_type": "target_registry_audit",
627
- "artifact": "artifacts/target_audit.json", "content_address": digest(target_audit),
628
- "produced_by": run["id"]})
629
- ontology = {
630
- "schema": "slayer-research-ontology-profile-v1",
631
- "objects": [{"id": "object:source:nonsa-dump-" + selection["dump_date"], "type": "Source"},
632
- {"id": "object:dataset:nonsa-content", "type": "Dataset"}],
633
- "versions": [{"id": source_version, "object": "object:source:nonsa-dump-" + selection["dump_date"],
634
- "content_address": source_version.rsplit(":", 1)[-1]},
635
- {"id": dataset_version, "object": "object:dataset:nonsa-content",
636
- "content_address": dataset_version.rsplit(":", 1)[-1]}],
637
- "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"}],
638
- "runs": [run], "evidence": evidence,
639
- "claims": [
640
- {"id": "claim:source-pages-observed",
641
- "statement": f"The pinned dump {selection['dump_date']} yielded {acquisition['source_pages']} non-redirect pages in the content namespaces.",
642
- "supported_by": [selection_evidence, acquisition_evidence],
643
- "falsification_condition": "The pinned dump shards do not reproduce the count."},
644
- {"id": "claim:slice-retention",
645
- "statement": f"The slice retained {stats['kept']} records after text QA and within-source deduplication.",
646
- "supported_by": [acquisition_evidence, qa_evidence],
647
- "falsification_condition": "The decisions, Parquet rows, or checksums do not reproduce the retention count."},
648
- {"id": "claim:source-absence-at-audit",
649
- "statement": "Nonsensopedia content was not registered as a source in the pinned DynaWord data tree or open pull-request list at audit time.",
650
- "supported_by": [target_evidence] if target_evidence else [qa_evidence],
651
- "falsification_condition": "The pinned target evidence contains a matching source or proposal."},
652
- {"id": "claim:training-value-untested",
653
- "statement": "Net corpus novelty and training benefit remain untested hypotheses.",
654
- "supported_by": [qa_evidence] + ([overlap_evidence] if overlap_evidence else []),
655
- "falsification_condition": "Target-wide text deduplication and controlled ablations establish those properties."},
656
- ],
657
- "actors": [{"id": "actor:piotrsty", "type": "Contributor"},
658
- {"id": "actor:nonsensopedia-community", "type": "Organization"},
659
- {"id": "actor:wikiteam", "type": "Organization"}, {"id": "actor:devin", "type": "Agent"}],
660
- "relations": [{"source": dataset_version, "predicate": "DERIVED_FROM", "target": source_version},
661
- {"source": dataset_version, "predicate": "GENERATED_BY", "target": run["id"]}] +
662
- ([{"source": dataset_version, "predicate": "VALIDATED_AGAINST",
663
- "target": f"hf:dataset:{TARGET}@{target_audit['revision']}"}] if target_audit else []),
664
- "pending": ["cross-source text deduplication", "benchmark contamination check",
665
- "parody-of-real-content screening", "controlled training ablation"],
666
- }
667
- save(root / "artifacts/ontology.json", ontology)
668
- card = f"""---
669
- license: cc-by-sa-3.0
670
- language:
671
- - pl
672
- task_categories:
673
- - text-generation
674
- configs:
675
- - config_name: default
676
- data_files:
677
- - split: train
678
- path: data/train-00000-of-00001.parquet
679
- ---
680
-
681
- # Nonsensopedia - Polish satirical wiki (content namespaces)
682
-
683
- Content pages from the pinned wikiteam3 dump of nonsa.pl
684
- ({IA_ITEM_URL}, generated {selection['dump_date']}). Nonsensopedia is the
685
- Polish-language satirical encyclopedia - a community wiki parodying Wikipedia
686
- and its sister projects. Content namespaces included: 0 (articles),
687
- 100 (Cytaty - quotes), 102 (NonNews - fake news), 104 (NonZrodla - fake
688
- sources), 106 (Slownik - fake dictionary), 108 (Gra - games), 110 (Forum),
689
- 114 (Poradnik - guides). Latest revision per page. This is informal,
690
- humorous creative Polish - satire, jokes, parody reference text.
691
-
692
- - Dump: {IA_FILE}, sha1-verified against archive.org item metadata
693
- - Non-redirect content pages: {stats['source_pages']:,}
694
- - Retained after text QA and within-source deduplication: {stats['kept']:,}
695
- - Characters: {stats['characters']:,}
696
- - Tokens: {stats['tokens']:,} (`cl100k_base` proxy)
697
- - License: CC BY-SA 3.0 per record; authorship via per-page history link
698
-
699
- ## Provenance and rights
700
-
701
- Nonsensopedia text is licensed [CC BY-SA 3.0]({LICENSE_TERMS_URL}); the
702
- archive.org item metadata declares the same licenseurl. Each record keeps
703
- its page id, title, namespace, last-revision timestamp and canonical URL -
704
- the page revision history is the attribution trail. The dump was produced by
705
- the WikiTeam preservation project (wikiteam3). Additional third-party
706
- attribution notices must be preserved and remain a review item.
707
- The `created` field is the last revision date, not page creation.
708
-
709
- ## Processing and limitations
710
-
711
- Wikitext is stripped with mwparserfromhell; lines occurring in at least
712
- {BOILERPLATE_MIN_DOC_FREQ:.0%} of documents are removed as
713
- cross-document boilerplate (see `artifacts/boilerplate_lines.json`). Unicode and
714
- whitespace normalization, email/labelled-phone/IP/labelled-national-ID/account-candidate pattern redaction, three-window langid
715
- vote, exact and near deduplication within source. The final text must contain at
716
- least {MIN_TEXT_CHARS} characters after redaction. Rejection counts:
717
-
718
- ```json
719
- {json.dumps(qa['rejection_counts'], ensure_ascii=False, indent=2)}
720
- ```
721
-
722
- PII filtering masks parsed IPv6 addresses (including compressed forms), labelled
723
- PESEL/NIP/REGON and 26-digit account candidates as well as the existing patterns.
724
- The account filter is conservative and may mask non-account numbers; unlabelled
725
- identifiers, free-form phone numbers, names and personal disclosures may remain.
726
- This is not complete anonymization.
727
-
728
- The register is deliberately non-factual: satirical articles, fake news,
729
- fake dictionary entries, quotes, forum posts and game pages. Pages may parody
730
- or quote real Wikipedia articles and other copyrighted works; quoted passages
731
- are not guaranteed disjoint from other corpus shards. The record model is a
732
- whole content page; individual entries are not split.
733
-
734
- ## Review artifacts
735
-
736
- See `artifacts/sample.jsonl`, `attribution.jsonl`, `decisions.jsonl`,
737
- `source_manifest.jsonl`, `overlap_audit.json`, `stats.json`, `qa.json`,
738
- `checksums.json`, `run.json` and `ontology.json`.
739
- """
740
- (root / "README.md").write_text(card, encoding="utf-8")
741
- (root / "NOTICE.md").write_text(
742
- "# Attribution and license notice\n\n"
743
- "Source: Nonsensopedia, https://nonsa.pl/ - a Polish-language satirical community wiki.\n\n"
744
- "Text is available under the Creative Commons Attribution-ShareAlike 3.0 License "
745
- "(https://creativecommons.org/licenses/by-sa/3.0/). Attribution is provided via the per-record "
746
- "canonical page URL in `artifacts/attribution.jsonl`; each page's revision history lists its "
747
- "contributors. Dump archived by the WikiTeam preservation project "
748
- f"({IA_ITEM_URL}).\n\n"
749
- "Preparation: Piotr Styla with Devin. Changes: content-namespace filtering, latest-revision "
750
- "selection, wikitext stripping, cross-document boilerplate removal, Unicode and whitespace "
751
- "normalization, limited email/labelled-phone/IP/labelled-national-ID/account-candidate "
752
- "redaction, language/quality filtering and within-source deduplication. No endorsement by "
753
- "Nonsensopedia contributors is implied.\n",
754
- encoding="utf-8",
755
- )
756
- print(json.dumps(stats, ensure_ascii=False, indent=2))
757
-
758
-
759
- def verify(out):
760
- import pyarrow.parquet as pq
761
-
762
- root = out / "hf_repo"
763
- table = pq.read_table(root / "data/train-00000-of-00001.parquet")
764
- rows = table.to_pylist()
765
- stats = load(root / "artifacts/stats.json")
766
- decisions = read_lines(root / "artifacts/decisions.jsonl")
767
- attribution = read_lines(root / "artifacts/attribution.jsonl")
768
- sample = read_lines(root / "artifacts/sample.jsonl")
769
- assert table.column_names == FIELDS
770
- assert len(rows) == stats["kept"] == len(attribution)
771
- assert sum(item["selected"] for item in decisions) == len(rows)
772
- assert sum(row["token_count"] for row in rows) == stats["tokens"]
773
- assert all(row["source"] == SOURCE and row["license"] == LICENSE_SPDX for row in rows)
774
- assert all(EMAIL_RE.search(row["text"]) is None for row in rows)
775
- by_id = {row["id"]: row for row in rows}
776
- assert len(sample) == stats["sample_count"] and all(by_id[row["id"]] == row for row in sample)
777
- ontology = load(root / "artifacts/ontology.json")
778
- evidence = {item["id"] for item in ontology["evidence"]}
779
- assert all(item["falsification_condition"] and set(item["supported_by"]) <= evidence for item in ontology["claims"])
780
- checks = load(root / "artifacts/checksums.json")
781
- assert all((root / path).is_file() and digest((root / path).read_bytes()) == checksum for path, checksum in checks.items())
782
- for item in ontology["evidence"]:
783
- artifact = root / item["artifact"]
784
- assert artifact.is_file() and digest(load(artifact)) == item["content_address"]
785
- import tiktoken
786
-
787
- encoder = tiktoken.get_encoding("cl100k_base")
788
- assert len(by_id) == len(rows)
789
- assert set(by_id) == {item["id"] for item in attribution}
790
- assert set(by_id) == {item["id"] for item in decisions if item["selected"]}
791
- assert len(decisions) == stats["source_pages"]
792
- assert len(decisions) - len(rows) == stats["rejected"]
793
- assert sum(len(row["text"]) for row in rows) == stats["characters"]
794
- short_ids = [row["id"] for row in rows if len(row["text"]) < MIN_TEXT_CHARS]
795
- assert all(row["token_count"] > 0 for row in rows)
796
- assert all(len(row["created"]) == 10 and row["author"] for row in rows)
797
- assert all(item["ns"] in CONTENT_NS and item["url"] == page_url(item["title"])
798
- and item["text_sha256"] == digest(by_id[item["id"]]["text"].encode("utf-8"))
799
- for item in attribution)
800
- assert all(len(encoder.encode_ordinary(row["text"])) == row["token_count"] for row in rows)
801
- boilerplate = set(load(root / "artifacts/boilerplate_lines.json"))
802
- review_ids = {row["id"] for row in sorted(sample, key=lambda item: len(item["text"]))[:3]}
803
- comparisons = []
804
- reconstructed = set()
805
- for shard in sorted((out / "extracted").glob("*.jsonl.gz")):
806
- with gzip.open(shard, "rt", encoding="utf-8") as handle:
807
- for line in handle:
808
- original = json.loads(line)
809
- row_id = f"{SOURCE}_{original['pageid']}"
810
- if row_id not in by_id:
811
- continue
812
- text = normalize(original["text"])
813
- text = "\n".join(line for line in text.splitlines()
814
- if re.sub(r"\s+", " ", line).strip() not in boilerplate)
815
- text = re.sub(r"\n{3,}", "\n\n", text).strip().replace("\ufffd", "[UNREADABLE_GLYPH]")
816
- text, _ = redact_pii(text)
817
- before = redact_pii(original["text"])[0] if row_id in review_ids else ""
818
- assert text == by_id[row_id]["text"], row_id
819
- assert row_id not in reconstructed
820
- reconstructed.add(row_id)
821
- if row_id in review_ids:
822
- comparisons.append({"id": row_id, "title": original["title"],
823
- "before_normalization_pii_patterns_redacted": before,
824
- "after": text})
825
- assert reconstructed == set(by_id)
826
- write_lines(out / "validation_samples.jsonl", comparisons)
827
- lengths = sorted(len(row["text"]) for row in rows)
828
- rejection_counts = dict(Counter(item["reason"] for item in decisions if not item["selected"]))
829
- residuals = {name: sum(bool(pattern.search(row["text"])) for row in rows)
830
- for name, pattern in {"email": EMAIL_RE, "labelled_phone": PHONE_RE,
831
- "ipv4": IPV4_RE, "ipv6_current_pattern": IPV6_RE}.items()}
832
- privacy_review = {
833
- "compressed_ipv6_documents": sum(any(is_ipv6(match.group()) for match in IPV6_CANDIDATE_RE.finditer(row["text"])) for row in rows),
834
- "labelled_national_identifier_candidates": sum(bool(NATIONAL_ID_RE.search(row["text"])) for row in rows),
835
- "bank_account_candidates": sum(bool(BANK_ACCOUNT_RE.search(row["text"])) for row in rows),
836
- }
837
- report = {
838
- "observed_at": now(), "verified": not short_ids and not any(residuals.values()) and not any(privacy_review.values()), "stats": stats,
839
- "additional_privacy_review_document_counts": privacy_review,
840
- "below_minimum_length_ids": short_ids,
841
- "rejection_counts": rejection_counts,
842
- "retained_namespaces": dict(Counter(item["ns"] for item in attribution)),
843
- "length_quantiles": {str(q): lengths[int((len(lengths) - 1) * q)] for q in (0, 0.5, 0.9, 0.99, 1)},
844
- "residual_pattern_document_counts": residuals,
845
- "all_token_counts_recomputed": True,
846
- "texts_reconstructed_from_extracted_source": len(reconstructed),
847
- "before_after_samples": len(comparisons),
848
- "publication_ready": False,
849
- "pending": ["license evidence and attribution review", "PII coverage review",
850
- "target overlap audit methodology review", "manual text quality review"],
851
- }
852
- save(out / "validation_report.json", report)
853
- print(json.dumps(report, ensure_ascii=False, indent=2))
854
- assert report["verified"], "Validation failures: see validation_report.json"
855
-
856
-
857
- def main():
858
- parser = argparse.ArgumentParser()
859
- parser.add_argument("--output", type=Path, required=True)
860
- parser.add_argument("--workers", type=int, default=8)
861
- parser.add_argument("command", choices=["discover", "acquire", "audit_target", "audit_overlap",
862
- "build", "verify"])
863
- args = parser.parse_args()
864
- if args.command == "discover":
865
- discover(args.output)
866
- elif args.command == "acquire":
867
- acquire(args.output, args.workers)
868
- elif args.command == "audit_target":
869
- audit_target(args.output)
870
- elif args.command == "audit_overlap":
871
- audit_overlap(args.output)
872
- elif args.command == "build":
873
- build(args.output)
874
- else:
875
- verify(args.output)
876
-
877
-
878
- if __name__ == "__main__":
879
- main()
880
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Build an auditable slice of Nonsensopedia (nonsa.pl) content namespaces, CC BY-SA 3.0."""
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ from collections import Counter
7
+ from concurrent.futures import ProcessPoolExecutor
8
+ from datetime import datetime, timezone
9
+ from difflib import SequenceMatcher
10
+ import gzip
11
+ import hashlib
12
+ import ipaddress
13
+ import json
14
+ from pathlib import Path
15
+ import re
16
+ import time
17
+ import unicodedata
18
+ from xml.etree.ElementTree import iterparse
19
+ from urllib.parse import quote
20
+
21
+ import requests
22
+
23
+
24
+ SOURCE = "nonsa"
25
+ OWN_REPO = "PiotrSty/nonsa-pl"
26
+ TARGET = "SlayerLab/polish-dynaword"
27
+ DUMP_DATE = "20251009"
28
+ IA_ITEM = f"wiki-nonsa.pl-{DUMP_DATE}"
29
+ IA_META_URL = f"https://archive.org/metadata/{IA_ITEM}"
30
+ IA_FILE = f"nonsa.pl-{DUMP_DATE}-history.xml.zst"
31
+ SOURCE_URL = "https://nonsa.pl/"
32
+ FIELDS = ["id", "text", "source", "added", "created", "token_count", "license", "author"]
33
+ UA = {"User-Agent": "polish-dynaword/0.2 (+research; openly-licensed corpus)"}
34
+ LICENSE_SPDX = "CC-BY-SA-3.0"
35
+ LICENSE_TERMS_URL = "https://creativecommons.org/licenses/by-sa/3.0/"
36
+ IA_ITEM_URL = f"https://archive.org/details/{IA_ITEM}"
37
+ # Content namespaces: 0 articles, 100 Cytaty, 102 NonNews, 104 NonZrodla,
38
+ # 106 Slownik, 108 Gra, 110 Forum, 114 Poradnik
39
+ CONTENT_NS = {"0", "100", "102", "104", "106", "108", "110", "114"}
40
+ MIN_TEXT_CHARS = 500
41
+ BOILERPLATE_MIN_DOC_FREQ = 0.01
42
+ DF_FRACTION = 0.02 # shingles in >2% of docs are template boilerplate
43
+ DF_SUBSAMPLE_STRIDE = 4 # document-frequency pass samples every Nth document
44
+ EMAIL_RE = re.compile(r"(?i)\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b")
45
+ PHONE_RE = re.compile(r"(?i)(?:\btelefon|\btel\.|\bphone)\s*:?[ \t]*(?:\+48[ \t]*)?\d(?:[ .-]?\d){8}\b")
46
+ IPV4_RE = re.compile(r"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b")
47
+ IPV6_RE = re.compile(r"(?i)\b(?:[0-9a-f]{1,4}:){3,}[0-9a-f]{1,4}\b")
48
+
49
+
50
+ IPV6_CANDIDATE_RE = re.compile(r"(?<![\w:])(?:[0-9a-fA-F]{0,4}:){2,}[0-9a-fA-F:.]*(?![\w:])")
51
+ NATIONAL_ID_RE = re.compile(r"(?i)\b(PESEL|NIP|REGON)\s*[:=]?\s*\d(?:[ -]?\d){8,13}\b")
52
+ BANK_ACCOUNT_RE = re.compile(r"(?<!\d)(?:PL\s*)?\d{2}(?:[ -]?\d){24}(?!\d)")
53
+
54
+
55
+ def is_ipv6(value):
56
+ try:
57
+ return ipaddress.ip_address(value.rstrip(".")).version == 6
58
+ except ValueError:
59
+ return False
60
+
61
+
62
+ def redact_pii(text):
63
+ counts = Counter()
64
+
65
+ def replace_ipv6(match):
66
+ value = match.group().rstrip(".")
67
+ if not is_ipv6(value):
68
+ return match.group()
69
+ counts["ipv6"] += 1
70
+ return "[REDACTED:IP]" + match.group()[len(value):]
71
+
72
+ text = IPV6_CANDIDATE_RE.sub(replace_ipv6, text)
73
+ for name, pattern, replacement in (
74
+ ("email", EMAIL_RE, "[REDACTED:EMAIL]"),
75
+ ("labelled_phone", PHONE_RE, "[REDACTED:PHONE]"),
76
+ ("ipv4", IPV4_RE, "[REDACTED:IP]"),
77
+ ("ipv6_legacy_pattern", IPV6_RE, "[REDACTED:IP]"),
78
+ ("national_identifier", NATIONAL_ID_RE, lambda match: match.group(1) + " [REDACTED:ID]"),
79
+ ("account_candidate", BANK_ACCOUNT_RE, "[REDACTED:ACCOUNT]"),
80
+ ):
81
+ text, count = pattern.subn(replacement, text)
82
+ counts[name] += count
83
+ return text, counts
84
+
85
+
86
+ def now():
87
+ return datetime.now(timezone.utc).isoformat()
88
+
89
+
90
+ def digest(value):
91
+ if not isinstance(value, bytes):
92
+ value = json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode("utf-8")
93
+ return hashlib.sha256(value).hexdigest()
94
+
95
+
96
+ def sha1_file(path):
97
+ h = hashlib.sha1()
98
+ with path.open("rb") as handle:
99
+ while chunk := handle.read(1 << 22):
100
+ h.update(chunk)
101
+ return h.hexdigest()
102
+
103
+
104
+ def save(path, value):
105
+ path.parent.mkdir(parents=True, exist_ok=True)
106
+ path.write_text(json.dumps(value, ensure_ascii=False, sort_keys=True, indent=2) + "\n", encoding="utf-8")
107
+
108
+
109
+ def write_lines(path, rows):
110
+ path.parent.mkdir(parents=True, exist_ok=True)
111
+ with path.open("w", encoding="utf-8") as handle:
112
+ for row in rows:
113
+ handle.write(json.dumps(row, ensure_ascii=False, sort_keys=True) + "\n")
114
+
115
+
116
+ def read_lines(path):
117
+ return [json.loads(line) for line in path.read_text(encoding="utf-8").split("\n") if line]
118
+
119
+
120
+ def load(path):
121
+ return json.loads(path.read_text(encoding="utf-8"))
122
+
123
+
124
+ def request(url, attempts=5, timeout=(15, 90)):
125
+ response = None
126
+ for attempt in range(attempts):
127
+ response = requests.get(url, headers=UA, timeout=timeout)
128
+ if response.status_code not in (429, 500, 502, 503, 504):
129
+ response.raise_for_status()
130
+ return response
131
+ time.sleep(2 ** attempt)
132
+ response.raise_for_status()
133
+
134
+
135
+ def request_json(url):
136
+ return request(url).json()
137
+
138
+
139
+ def _local(tag):
140
+ return tag.rsplit("}", 1)[-1]
141
+
142
+
143
+ # strip_code() keeps the text of every wikilink, so category tags survive as
144
+ # "Kategoria:X" lines and file links as their option list ("right|200px|caption").
145
+ FILE_NS = {"plik", "grafika", "file", "image"}
146
+ CATEGORY_NS = {"kategoria", "category"}
147
+ IMAGE_OPTION_RE = re.compile(
148
+ r"(?i)^\s*(?:\d*x?\d+\s*px"
149
+ r"|thumb|thumbnail|mały|miniatura|frame|framed|ramka|frameless|bezramki|border|obramowanie"
150
+ r"|left|lewo|right|prawo|center|centre|centruj|none|brak|upright|pionowo"
151
+ r"|baseline|sub|super|top|text-top|middle|bottom|text-bottom"
152
+ r"|(?:link|alt|page|class|lang|upright|thumb|thumbnail|mały|miniatura)\s*=.*)\s*$")
153
+ MAGIC_WORD_RE = re.compile(r"__[A-ZĄĆĘŁŃÓŚŹŻ]+__")
154
+
155
+
156
+ def split_top_level(text):
157
+ """Split link parameters on '|' outside nested [[...]] / {{...}}."""
158
+ parts, depth, start, i = [], 0, 0, 0
159
+ while i < len(text):
160
+ pair = text[i:i + 2]
161
+ if pair in ("[[", "{{"):
162
+ depth += 1
163
+ i += 2
164
+ continue
165
+ if pair in ("]]", "}}") and depth:
166
+ depth -= 1
167
+ i += 2
168
+ continue
169
+ if text[i] == "|" and not depth:
170
+ parts.append(text[start:i])
171
+ start = i + 1
172
+ i += 1
173
+ parts.append(text[start:])
174
+ return parts
175
+
176
+
177
+ def link_namespace(title):
178
+ name = str(title).strip()
179
+ if name.startswith(":") or ":" not in name: # [[:Kategoria:X]] is an inline link
180
+ return ""
181
+ return name.split(":", 1)[0].strip().casefold()
182
+
183
+
184
+ def file_caption(params):
185
+ """MediaWiki renders the last non-option parameter of a file link as its caption."""
186
+ if not params:
187
+ return ""
188
+ captions = [part for part in split_top_level(params) if not IMAGE_OPTION_RE.match(part)]
189
+ return captions[-1].strip() if captions else ""
190
+
191
+
192
+ def replace_link(namespace, params):
193
+ """Replacement for a category/file link, or None to keep the link."""
194
+ if namespace in CATEGORY_NS:
195
+ return ""
196
+ if namespace in FILE_NS:
197
+ caption = file_caption(params)
198
+ return f"\n{caption}\n" if caption else ""
199
+ return None
200
+
201
+
202
+ # Malformed markup (e.g. an unclosed '' inside a caption) makes mwparserfromhell
203
+ # read the whole link as plain text, so strip_code() leaves it verbatim.
204
+ RESIDUAL_LINK_RE = re.compile(r"\[\[([^\[\]\n]*)\]\]")
205
+
206
+
207
+ def _replace_residual_link(match):
208
+ title, _, params = match.group(1).partition("|")
209
+ replacement = replace_link(link_namespace(title), params)
210
+ return match.group(0) if replacement is None else replacement
211
+
212
+
213
+ def strip_wikitext(wikitext):
214
+ import mwparserfromhell
215
+ try:
216
+ code = mwparserfromhell.parse(wikitext)
217
+ # reversed: links nested in a caption are rewritten before their parent is read
218
+ for link in reversed(code.filter_wikilinks()):
219
+ params = "" if link.text is None else str(link.text)
220
+ replacement = replace_link(link_namespace(link.title), params)
221
+ if replacement is not None:
222
+ code.replace(link, replacement)
223
+ text = code.strip_code(normalize=True, collapse=True)
224
+ text = RESIDUAL_LINK_RE.sub(_replace_residual_link, text)
225
+ return re.sub(r"\n{3,}", "\n\n", MAGIC_WORD_RE.sub("", text)).strip()
226
+ except Exception:
227
+ return ""
228
+
229
+
230
+ def _strip_batch(items):
231
+ return [strip_wikitext(wikitext) for _, _, _, _, wikitext in items]
232
+
233
+
234
+ def discover(out):
235
+ metadata = request_json(IA_META_URL)
236
+ license_url = (metadata.get("metadata") or {}).get("licenseurl")
237
+ files = []
238
+ for item in metadata.get("files", []):
239
+ if item.get("name") == IA_FILE:
240
+ files.append({"name": item["name"],
241
+ "url": f"https://archive.org/download/{IA_ITEM}/{item['name']}",
242
+ "size": int(item["size"]), "sha1": item.get("sha1"),
243
+ "md5": item.get("md5"), "format": item.get("format")})
244
+ if not files:
245
+ raise ValueError(f"history dump {IA_FILE} not found in {IA_ITEM}")
246
+ selection = {
247
+ "observed_at": now(), "dump_date": DUMP_DATE,
248
+ "archive_org_item": IA_ITEM, "archive_org_metadata_url": IA_META_URL,
249
+ "files": files, "total_bytes": sum(item["size"] for item in files),
250
+ "content_namespaces": sorted(CONTENT_NS, key=int), "min_text_chars": MIN_TEXT_CHARS,
251
+ "license": "CC BY-SA 3.0 (Nonsensopedia site license; archive.org item licenseurl)",
252
+ "license_url_observed": license_url,
253
+ "dump_producer": "wikiteam3 (https://github.com/saveweb/wikiteam3/)",
254
+ "files_sha256": digest(files),
255
+ }
256
+ save(out / "selection.json", selection)
257
+ print(json.dumps({k: selection[k] for k in ("dump_date", "total_bytes")}, indent=2))
258
+ print("files:", len(files))
259
+
260
+
261
+ def parse_dump(path):
262
+ """wikiteam3 xmlrevisions export: each <page> element carries one <revision>;
263
+ group by pageid and keep the latest revision (max timestamp) per page."""
264
+ import zstandard
265
+
266
+ latest = {}
267
+ dctx = zstandard.ZstdDecompressor(max_window_size=2 ** 31)
268
+ with path.open("rb") as raw, dctx.stream_reader(raw) as fh:
269
+ title = ns = pageid = timestamp = text = None
270
+ redirect = False
271
+ for ev, el in iterparse(fh, events=("end",)):
272
+ tag = _local(el.tag)
273
+ if tag == "title":
274
+ title = el.text
275
+ elif tag == "ns":
276
+ ns = el.text
277
+ elif tag == "id" and pageid is None:
278
+ pageid = el.text
279
+ elif tag == "timestamp":
280
+ timestamp = el.text
281
+ elif tag == "redirect":
282
+ redirect = True
283
+ elif tag == "text":
284
+ text = el.text
285
+ elif tag == "page":
286
+ if ns in CONTENT_NS and not redirect:
287
+ current = latest.get(pageid)
288
+ if current is None or (timestamp or "") > (current[3] or ""):
289
+ latest[pageid] = (pageid, ns, title, timestamp, text)
290
+ title = ns = pageid = timestamp = text = None
291
+ redirect = False
292
+ el.clear()
293
+ return [record for record in latest.values() if record[4]]
294
+
295
+
296
+ def acquire(out, workers):
297
+ selection = load(out / "selection.json")
298
+ dump_dir = out / "raw_dump"
299
+ dump_dir.mkdir(parents=True, exist_ok=True)
300
+ extracted_dir = out / "extracted"
301
+ extracted_dir.mkdir(exist_ok=True)
302
+ manifest = []
303
+ for item in selection["files"]:
304
+ dst = dump_dir / item["name"]
305
+ if not dst.exists() or dst.stat().st_size != item["size"]:
306
+ print(f" pobieram {item['name']} ({item['size']/1e6:.0f} MB)", flush=True)
307
+ for attempt in range(8):
308
+ have = dst.stat().st_size if dst.exists() else 0
309
+ headers = dict(UA)
310
+ if have:
311
+ headers["Range"] = f"bytes={have}-"
312
+ try:
313
+ with requests.get(item["url"], headers=headers, stream=True, timeout=(15, 300)) as r:
314
+ r.raise_for_status()
315
+ if have and r.status_code != 206:
316
+ have = 0
317
+ with dst.open("ab" if have else "wb") as f:
318
+ for chunk in r.iter_content(1 << 22):
319
+ f.write(chunk)
320
+ break
321
+ except requests.RequestException as error:
322
+ print(f" retry {item['name']}: {type(error).__name__}", flush=True)
323
+ time.sleep(min(2 ** attempt, 60))
324
+ else:
325
+ raise RuntimeError(f"download failed: {item['name']}")
326
+ sha = sha1_file(dst)
327
+ if item["sha1"] and sha != item["sha1"]:
328
+ raise ValueError(f"sha1 mismatch {item['name']}: {sha} != {item['sha1']}")
329
+ print(f" {item['name']} sha1 OK", flush=True)
330
+
331
+ out_path = extracted_dir / (item["name"] + ".jsonl.gz")
332
+ if not out_path.exists():
333
+ records = parse_dump(dst)
334
+ batches = [records[i:i + 2000] for i in range(0, len(records), 2000)]
335
+ with ProcessPoolExecutor(max_workers=workers) as pool:
336
+ texts = [text for batch in pool.map(_strip_batch, batches) for text in batch]
337
+ with gzip.open(out_path, "wt", encoding="utf-8") as f:
338
+ for (pageid, ns, title, timestamp, wikitext), text in zip(records, texts):
339
+ f.write(json.dumps({"pageid": pageid, "ns": ns, "title": title,
340
+ "timestamp": timestamp, "wikitext_chars": len(wikitext),
341
+ "text": text}, ensure_ascii=False) + "\n")
342
+ shard_records = 0
343
+ kept_chars = 0
344
+ with gzip.open(out_path, "rt", encoding="utf-8") as f:
345
+ for line in f:
346
+ row = json.loads(line)
347
+ shard_records += 1
348
+ kept_chars += len(row["text"])
349
+ manifest.append({"pageid": row["pageid"], "ns": row["ns"], "title": row["title"],
350
+ "timestamp": row["timestamp"],
351
+ "url": page_url(row["title"])})
352
+ print(f" {item['name']}: {shard_records} stron tresci", flush=True)
353
+ write_lines(out / "source_manifest.jsonl", manifest)
354
+ acquisition = {
355
+ "observed_at": now(), "dump_date": selection["dump_date"],
356
+ "files": selection["files"], "source_pages": len(manifest),
357
+ "manifest_sha256": digest((out / "source_manifest.jsonl").read_bytes()),
358
+ }
359
+ save(out / "acquisition.json", acquisition)
360
+ print(json.dumps(acquisition, ensure_ascii=False, indent=2))
361
+
362
+
363
+ def strip_boilerplate(texts_index):
364
+ counts = Counter()
365
+ for lines in texts_index:
366
+ counts.update(set(re.sub(r"\s+", " ", line).strip() for line in lines if line.strip()))
367
+ n = len(texts_index)
368
+ return {line for line, count in counts.items()
369
+ if count / n >= BOILERPLATE_MIN_DOC_FREQ and len(line) < 160}
370
+
371
+
372
+ def normalize(text):
373
+ text = unicodedata.normalize("NFKC", text or "").replace("­", "").replace("​", "")
374
+ text = re.sub(r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]", "", text)
375
+ lines = [re.sub(r"[ \t\xa0]+", " ", line).strip() for line in text.splitlines()]
376
+ lines = [line for line in lines if not re.fullmatch(r"\d{1,4}", line)]
377
+ text = "\n".join(lines)
378
+ text = re.sub(r"(?<=\w)-\n(?=[a-ząćęłńóśźż])", "", text)
379
+ text = re.sub(r"(?<![.!?:;\n])\n(?!\n)(?=[a-ząćęłńóśźż])", " ", text)
380
+ return re.sub(r"\n{3,}", "\n\n", text).strip()
381
+
382
+
383
+ def page_url(title):
384
+ return SOURCE_URL + "wiki/" + quote((title or "").replace(" ", "_"), safe="/:")
385
+
386
+
387
+ def normalize_title(text):
388
+ text = unicodedata.normalize("NFKD", text or "").casefold()
389
+ text = "".join(character for character in text if not unicodedata.combining(character))
390
+ return " ".join(re.findall(r"\w+", text))
391
+
392
+
393
+ def shingle_sketch(text, limit=5_000):
394
+ words = re.findall(r"\w+", text.casefold())
395
+ hashes = set()
396
+ for index in range(max(0, len(words) - 4)):
397
+ value = " ".join(words[index:index + 5]).encode("utf-8")
398
+ hashes.add(int.from_bytes(hashlib.blake2b(value, digest_size=8).digest(), "big"))
399
+ if len(hashes) > limit:
400
+ return set(sorted(hashes)[:limit])
401
+ return hashes
402
+
403
+
404
+ def boilerplate_shingles(candidates, boilerplate, stride=DF_SUBSAMPLE_STRIDE, fraction=DF_FRACTION):
405
+ df = Counter()
406
+ sampled = 0
407
+ for index, record in enumerate(candidates):
408
+ if index % stride:
409
+ continue
410
+ text = "\n".join(line for line in record["text"].splitlines()
411
+ if re.sub(r"\s+", " ", line).strip() not in boilerplate)
412
+ text = re.sub(r"\n{3,}", "\n\n", text).strip()
413
+ df.update(shingle_sketch(text))
414
+ sampled += 1
415
+ max_df = max(1, int(sampled * fraction))
416
+ return {shingle for shingle, count in df.items() if count > max_df}, max_df, sampled
417
+
418
+
419
+ def filter_sketch(sketch, hot):
420
+ return {shingle for shingle in sketch if shingle not in hot}
421
+
422
+
423
+ class NearDuplicateIndex:
424
+ def __init__(self):
425
+ self.postings = {}
426
+ self.records = []
427
+ self.comparisons = 0
428
+
429
+ @staticmethod
430
+ def prefix(sketch):
431
+ return sorted(sketch)[:len(sketch) - (9 * len(sketch) + 9) // 10 + 1]
432
+
433
+ def find(self, sketch):
434
+ candidates = set()
435
+ for value in self.prefix(sketch):
436
+ candidates.update(self.postings.get(value, ()))
437
+ for position in sorted(candidates):
438
+ row_id, other = self.records[position]
439
+ if 10 * min(len(sketch), len(other)) < 9 * max(len(sketch), len(other)):
440
+ continue
441
+ self.comparisons += 1
442
+ intersection = len(sketch & other)
443
+ score = intersection / max(len(sketch) + len(other) - intersection, 1)
444
+ if score >= 0.90:
445
+ return row_id, score
446
+ return None, 0.0
447
+
448
+ def add(self, row_id, sketch):
449
+ position = len(self.records)
450
+ self.records.append((row_id, sketch))
451
+ for value in self.prefix(sketch):
452
+ self.postings.setdefault(value, []).append(position)
453
+
454
+
455
+ def language_vote(identifier, text):
456
+ chunks = [text[:30_000], text[max(0, len(text) // 2 - 15_000):len(text) // 2 + 15_000], text[-30_000:]]
457
+ classified = {chunk: identifier.classify(chunk) for chunk in dict.fromkeys(chunks) if chunk.strip()}
458
+ votes = [classified[chunk] for chunk in chunks if chunk in classified]
459
+ languages = Counter(language for language, _ in votes)
460
+ return (languages.most_common(1)[0][0] if languages else "unknown", votes)
461
+
462
+
463
+ def audit_target(out):
464
+ info = request_json(f"https://huggingface.co/api/datasets/{TARGET}")
465
+ revision = info["sha"]
466
+ tree = request_json(f"https://huggingface.co/api/datasets/{TARGET}/tree/{revision}?recursive=true&expand=false")
467
+ discussions = request_json(f"https://huggingface.co/api/datasets/{TARGET}/discussions?status=open&p=0")
468
+ paths = sorted(item.get("path", "") for item in tree)
469
+ open_rows = [{"num": item.get("num"), "title": item.get("title"), "status": item.get("status"),
470
+ "author": item.get("author", {}).get("name")} for item in discussions.get("discussions", [])]
471
+ terms = ("nonsa", "nonsensopedia")
472
+ matches = [path for path in paths if any(term in path.casefold() for term in terms)]
473
+ discussion_matches = [row for row in open_rows if any(term in (row.get("title") or "").casefold()
474
+ for term in terms)]
475
+ report = {
476
+ "target": TARGET, "revision": revision, "last_modified": info.get("lastModified"),
477
+ "tree_paths": len(paths), "source_path_matches": matches, "open_discussions": open_rows,
478
+ "matching_open_discussions": discussion_matches, "source_absent": not matches and not discussion_matches,
479
+ "observed_at": now(),
480
+ }
481
+ save(out / "target_audit.json", report)
482
+ print(json.dumps({"revision": revision, "source_absent": report["source_absent"],
483
+ "tree_matches": matches, "discussion_matches": discussion_matches}, ensure_ascii=False, indent=2))
484
+
485
+
486
+ def audit_overlap(out):
487
+ import pyarrow.parquet as pq
488
+ from huggingface_hub import HfApi, HfFileSystem
489
+
490
+ acquisition = load(out / "acquisition.json")
491
+ revision = HfApi().dataset_info(TARGET).sha
492
+ remote = f"datasets/{TARGET}@{revision}/data/wikipedia/wikipedia.parquet"
493
+ with HfFileSystem().open(remote, "rb") as handle:
494
+ table = pq.read_table(handle, columns=["id"])
495
+ target_ids = set(table.column("id").to_pylist())
496
+ candidate_ids = {f"{SOURCE}_{row['pageid']}" for row in read_lines(out / "source_manifest.jsonl")}
497
+ collisions = sorted(candidate_ids & target_ids)
498
+ report = {
499
+ "target": f"{TARGET}:data/wikipedia", "target_revision": revision,
500
+ "method": "Literal dataset-record ID comparison only. Source-specific ID prefixes make zero collisions "
501
+ "uninformative about page identity or text overlap. No target namespace or text audit was performed.",
502
+ "target_rows": table.num_rows, "candidate_records": len(candidate_ids),
503
+ "id_collisions": collisions[:50], "collision_count": len(collisions),
504
+ "text_overlap": "not tested; quoted-article passages and target-wide text dedup remain integration gates",
505
+ "observed_at": now(),
506
+ }
507
+ save(out / "overlap_audit.json", report)
508
+ print(json.dumps({key: report[key] for key in ("target_revision", "target_rows", "candidate_records",
509
+ "collision_count")}, ensure_ascii=False, indent=2))
510
+
511
+
512
+ def build(out):
513
+ import pyarrow as pa
514
+ import pyarrow.parquet as pq
515
+ import tiktoken
516
+ from langid.langid import LanguageIdentifier, model
517
+
518
+ build_started_at = now()
519
+ acquisition = load(out / "acquisition.json")
520
+ selection = load(out / "selection.json")
521
+ encoder = tiktoken.get_encoding("cl100k_base")
522
+ identifier = LanguageIdentifier.from_modelstring(model, norm_probs=True)
523
+ identifier.set_languages(["pl", "en", "de", "uk", "ru"])
524
+
525
+ candidates = []
526
+ for shard in sorted((out / "extracted").glob("*.jsonl.gz")):
527
+ with gzip.open(shard, "rt", encoding="utf-8") as f:
528
+ for line in f:
529
+ row = json.loads(line)
530
+ row["text"] = normalize(row["text"])
531
+ candidates.append(row)
532
+ boilerplate = strip_boilerplate([row["text"].splitlines() for row in candidates])
533
+ print(f"boilerplate lines: {len(boilerplate)}", flush=True)
534
+ hot, max_df, df_sampled = boilerplate_shingles(candidates, boilerplate)
535
+ print(f"boilerplate shingles: {len(hot)} (df>{max_df} over {df_sampled} sampled docs)", flush=True)
536
+
537
+ rows, attribution, decisions, exact_seen = [], [], [], {}
538
+ near_index = NearDuplicateIndex()
539
+ pii = Counter()
540
+ added = acquisition["observed_at"][:10]
541
+ started = last_progress = time.monotonic()
542
+ for processed, record in enumerate(candidates, 1):
543
+ current = time.monotonic()
544
+ if current - last_progress >= 10 or processed == len(candidates):
545
+ print(f" processed={processed - 1}/{len(candidates)} kept={len(rows)} "
546
+ f"rate={(processed - 1) / max(current - started, 0.001):.1f}/s "
547
+ f"near_comparisons={near_index.comparisons}", flush=True)
548
+ last_progress = current
549
+ text = "\n".join(line for line in record["text"].splitlines()
550
+ if re.sub(r"\s+", " ", line).strip() not in boilerplate)
551
+ text = re.sub(r"\n{3,}", "\n\n", text).strip()
552
+ replacement_count = text.count("\ufffd")
553
+ letters = len(re.findall(r"[A-Za-zĄĆĘŁŃÓŚŹŻąćęłńóśźż]", text))
554
+ language, votes = "not_checked", []
555
+ reason = ""
556
+ if len(text) < MIN_TEXT_CHARS:
557
+ reason = "too_little_text"
558
+ elif letters / max(len(text), 1) < 0.5:
559
+ reason = "low_letter_ratio"
560
+ elif replacement_count > 100 or replacement_count / max(len(text), 1) > 0.002:
561
+ reason = "excessive_replacement_characters"
562
+ if not reason:
563
+ language, votes = language_vote(identifier, text)
564
+ if language != "pl":
565
+ reason = "non_polish_text"
566
+ text = text.replace("\ufffd", "[UNREADABLE_GLYPH]")
567
+ text, pii_counts = redact_pii(text)
568
+ pii.update(pii_counts)
569
+ if not reason and len(text) < MIN_TEXT_CHARS:
570
+ reason = "too_little_text_after_redaction"
571
+ exact_key = digest(" ".join(text.casefold().split()).encode("utf-8"))
572
+ duplicate_of, duplicate_score = None, 0.0
573
+ if not reason and exact_key in exact_seen:
574
+ reason, duplicate_of, duplicate_score = "normalized_duplicate", exact_seen[exact_key], 1.0
575
+ if not reason:
576
+ sketch = filter_sketch(shingle_sketch(text), hot)
577
+ duplicate_of, duplicate_score = near_index.find(sketch)
578
+ if duplicate_of is not None:
579
+ reason = "near_duplicate"
580
+ row_id = f"{SOURCE}_{record['pageid']}"
581
+ decision = {
582
+ "id": row_id, "selected": not bool(reason), "reason": reason or "include",
583
+ "characters": len(text), "letter_ratio": letters / max(len(text), 1),
584
+ "replacement_characters": replacement_count, "language": language,
585
+ "language_votes": [{"language": lang, "confidence": float(score)} for lang, score in votes],
586
+ }
587
+ if duplicate_of:
588
+ decision.update({"duplicate_of": duplicate_of, "jaccard": duplicate_score})
589
+ decisions.append(decision)
590
+ if reason:
591
+ continue
592
+ exact_seen[exact_key] = row_id
593
+ near_index.add(row_id, sketch)
594
+ row = {
595
+ "id": row_id, "text": text, "source": SOURCE, "added": added,
596
+ "created": (record["timestamp"] or "")[:10] or "unknown",
597
+ "token_count": len(encoder.encode_ordinary(text)),
598
+ "license": LICENSE_SPDX, "author": "nonsensopedia contributors",
599
+ }
600
+ rows.append(row)
601
+ attribution.append({
602
+ "id": row_id, "pageid": record["pageid"], "ns": record["ns"], "title": record["title"],
603
+ "url": page_url(record["title"]),
604
+ "last_revision_at": record["timestamp"], "wikitext_chars": record["wikitext_chars"],
605
+ "license": LICENSE_SPDX,
606
+ "license_evidence": LICENSE_TERMS_URL + " (site license via archive.org item metadata; attribution by page URL)",
607
+ "dump": {"date": selection["dump_date"], "archive_org_item": selection["archive_org_item"],
608
+ "files": [f["name"] for f in selection["files"]]},
609
+ "text_sha256": digest(text.encode("utf-8")),
610
+ "transformations": ["wikiteam3 xmlrevisions dump, latest revision per page", "mwparserfromhell wikitext strip",
611
+ "cross-document boilerplate-line removal",
612
+ "Unicode/whitespace normalization", "page-number-only removal",
613
+ "line-wrap repair", "email/labelled-phone/IP/labelled-national-ID/account-candidate pattern redaction"],
614
+ })
615
+
616
+ root = out / "hf_repo"
617
+ (root / "data").mkdir(parents=True, exist_ok=True)
618
+ (root / "artifacts").mkdir(parents=True, exist_ok=True)
619
+ schema = pa.schema([(field, pa.int64() if field == "token_count" else pa.string()) for field in FIELDS])
620
+ pq.write_table(pa.Table.from_pylist(rows, schema=schema), root / "data/train-00000-of-00001.parquet", compression="zstd")
621
+ write_lines(root / "artifacts/attribution.jsonl", attribution)
622
+ write_lines(root / "artifacts/decisions.jsonl", decisions)
623
+ write_lines(root / "artifacts/source_manifest.jsonl", read_lines(out / "source_manifest.jsonl"))
624
+ sample = sorted(rows, key=lambda row: digest(("sample:" + row["id"]).encode("utf-8")))[:12]
625
+ write_lines(root / "artifacts/sample.jsonl", sample)
626
+ save(root / "artifacts/selection.json", selection)
627
+ save(root / "artifacts/acquisition.json", acquisition)
628
+ save(root / "artifacts/boilerplate_lines.json", sorted(boilerplate))
629
+ overlap = load(out / "overlap_audit.json") if (out / "overlap_audit.json").exists() else None
630
+ target_audit = load(out / "target_audit.json") if (out / "target_audit.json").exists() else None
631
+ if overlap:
632
+ save(root / "artifacts/overlap_audit.json", overlap)
633
+ if target_audit:
634
+ save(root / "artifacts/target_audit.json", target_audit)
635
+ stats = {
636
+ "dump_date": selection["dump_date"], "dump_files": len(selection["files"]),
637
+ "source_pages": acquisition["source_pages"],
638
+ "kept": len(rows), "rejected": len(decisions) - len(rows),
639
+ "tokens": sum(row["token_count"] for row in rows),
640
+ "characters": sum(len(row["text"]) for row in rows),
641
+ "license_counts": dict(Counter(row["license"] for row in rows)),
642
+ "boilerplate_lines_removed": len(boilerplate),
643
+ "boilerplate_shingles_excluded": len(hot),
644
+ "sample_count": len(sample), "added": added,
645
+ }
646
+ qa = {
647
+ "scope": "Nonsensopedia content namespaces (0 articles, 100 Cytaty, 102 NonNews, 104 NonZrodla, 106 Slownik, 108 Gra, 110 Forum, 114 Poradnik), latest revision per page from the wikiteam3 archive.org dump",
648
+ "license_terms_url": LICENSE_TERMS_URL,
649
+ "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",
650
+ "rejection_counts": dict(Counter(item["reason"] for item in decisions if not item["selected"])),
651
+ "minimum_final_text_characters": MIN_TEXT_CHARS,
652
+ "created_field_semantics": "Last revision date from the dump, not the page creation date",
653
+ "language_gate": "independent three-window langid vote",
654
+ "pii_pattern_matches": dict(pii), "exact_dedup": True,
655
+ "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",
656
+ "pii_limitations": "Unlabelled national identifiers, free-form phone numbers, names and personal disclosures may remain; this is not complete anonymization",
657
+ "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",
658
+ "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)",
659
+ "wikipedia_shard_overlap": overlap or "pending", "cross_source_text_dedup": "pending target integration",
660
+ "benchmark_overlap": "pending", "limitations": [
661
+ "satirical/humorous register: parody articles, fake news (NonNews), fake dictionary entries (Slownik), quotes (Cytaty), forum posts and games; not factual reference text",
662
+ "pages may parody or quote real Wikipedia/cultural material; quoted passages are not guaranteed disjoint from other shards",
663
+ "record model is a whole content page; individual entries/comments are not split",
664
+ "pattern checks are not comprehensive de-identification",
665
+ ],
666
+ }
667
+ save(root / "artifacts/stats.json", stats)
668
+ save(root / "artifacts/qa.json", qa)
669
+ protocol_id = "protocol:nonsa-content-v1"
670
+ run = {
671
+ "id": "run:" + digest({"script": digest(Path(__file__).read_bytes()), "selection": selection,
672
+ "acquisition": digest(acquisition)}),
673
+ "protocol": protocol_id, "started_at": build_started_at, "finished_at": now(),
674
+ "success": True, "actor": "actor:devin", "stats": stats,
675
+ }
676
+ save(root / "artifacts/run.json", run)
677
+ excluded = {"README.md", "NOTICE.md", "artifacts/checksums.json", "artifacts/ontology.json"}
678
+ checks = {path.relative_to(root).as_posix(): digest(path.read_bytes()) for path in sorted(root.rglob("*"))
679
+ if path.is_file()
680
+ and path.relative_to(root).as_posix() not in excluded
681
+ and not path.relative_to(root).as_posix().startswith("src/")}
682
+ save(root / "artifacts/checksums.json", checks)
683
+ source_version = "version:source:" + digest(selection["files"])
684
+ dataset_version = "version:dataset:" + digest(checks)
685
+ selection_evidence = "evidence:selection:" + digest(selection)
686
+ acquisition_evidence = "evidence:acquisition:" + digest(acquisition)
687
+ qa_evidence = "evidence:qa:" + digest(qa)
688
+ evidence = [
689
+ {"id": selection_evidence, "observation_type": "dump_inventory_and_pinning",
690
+ "artifact": "artifacts/selection.json", "content_address": digest(selection), "produced_by": run["id"]},
691
+ {"id": acquisition_evidence, "observation_type": "dump_download_sha1_and_extraction",
692
+ "artifact": "artifacts/acquisition.json", "content_address": digest(acquisition), "produced_by": run["id"]},
693
+ {"id": qa_evidence, "observation_type": "source_qa", "artifact": "artifacts/qa.json",
694
+ "content_address": digest(qa), "produced_by": run["id"]},
695
+ ]
696
+ overlap_evidence = None
697
+ if overlap:
698
+ overlap_evidence = "evidence:overlap:" + digest(overlap)
699
+ evidence.append({"id": overlap_evidence, "observation_type": "namespace_overlap_audit",
700
+ "artifact": "artifacts/overlap_audit.json", "content_address": digest(overlap),
701
+ "produced_by": run["id"]})
702
+ target_evidence = None
703
+ if target_audit:
704
+ target_evidence = "evidence:target:" + digest(target_audit)
705
+ evidence.append({"id": target_evidence, "observation_type": "target_registry_audit",
706
+ "artifact": "artifacts/target_audit.json", "content_address": digest(target_audit),
707
+ "produced_by": run["id"]})
708
+ ontology = {
709
+ "schema": "slayer-research-ontology-profile-v1",
710
+ "objects": [{"id": "object:source:nonsa-dump-" + selection["dump_date"], "type": "Source"},
711
+ {"id": "object:dataset:nonsa-content", "type": "Dataset"}],
712
+ "versions": [{"id": source_version, "object": "object:source:nonsa-dump-" + selection["dump_date"],
713
+ "content_address": source_version.rsplit(":", 1)[-1]},
714
+ {"id": dataset_version, "object": "object:dataset:nonsa-content",
715
+ "content_address": dataset_version.rsplit(":", 1)[-1]}],
716
+ "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"}],
717
+ "runs": [run], "evidence": evidence,
718
+ "claims": [
719
+ {"id": "claim:source-pages-observed",
720
+ "statement": f"The pinned dump {selection['dump_date']} yielded {acquisition['source_pages']} non-redirect pages in the content namespaces.",
721
+ "supported_by": [selection_evidence, acquisition_evidence],
722
+ "falsification_condition": "The pinned dump shards do not reproduce the count."},
723
+ {"id": "claim:slice-retention",
724
+ "statement": f"The slice retained {stats['kept']} records after text QA and within-source deduplication.",
725
+ "supported_by": [acquisition_evidence, qa_evidence],
726
+ "falsification_condition": "The decisions, Parquet rows, or checksums do not reproduce the retention count."},
727
+ {"id": "claim:source-absence-at-audit",
728
+ "statement": "Nonsensopedia content was not registered as a source in the pinned DynaWord data tree or open pull-request list at audit time.",
729
+ "supported_by": [target_evidence] if target_evidence else [qa_evidence],
730
+ "falsification_condition": "The pinned target evidence contains a matching source or proposal."},
731
+ {"id": "claim:training-value-untested",
732
+ "statement": "Net corpus novelty and training benefit remain untested hypotheses.",
733
+ "supported_by": [qa_evidence] + ([overlap_evidence] if overlap_evidence else []),
734
+ "falsification_condition": "Target-wide text deduplication and controlled ablations establish those properties."},
735
+ ],
736
+ "actors": [{"id": "actor:piotrsty", "type": "Contributor"},
737
+ {"id": "actor:nonsensopedia-community", "type": "Organization"},
738
+ {"id": "actor:wikiteam", "type": "Organization"}, {"id": "actor:devin", "type": "Agent"}],
739
+ "relations": [{"source": dataset_version, "predicate": "DERIVED_FROM", "target": source_version},
740
+ {"source": dataset_version, "predicate": "GENERATED_BY", "target": run["id"]}] +
741
+ ([{"source": dataset_version, "predicate": "VALIDATED_AGAINST",
742
+ "target": f"hf:dataset:{TARGET}@{target_audit['revision']}"}] if target_audit else []),
743
+ "pending": ["cross-source text deduplication", "benchmark contamination check",
744
+ "parody-of-real-content screening", "controlled training ablation"],
745
+ }
746
+ save(root / "artifacts/ontology.json", ontology)
747
+ card = f"""---
748
+ license: cc-by-sa-3.0
749
+ language:
750
+ - pl
751
+ task_categories:
752
+ - text-generation
753
+ configs:
754
+ - config_name: default
755
+ data_files:
756
+ - split: train
757
+ path: data/train-00000-of-00001.parquet
758
+ ---
759
+
760
+ # Nonsensopedia - Polish satirical wiki (content namespaces)
761
+
762
+ Content pages from the pinned wikiteam3 dump of nonsa.pl
763
+ ({IA_ITEM_URL}, generated {selection['dump_date']}). Nonsensopedia is the
764
+ Polish-language satirical encyclopedia - a community wiki parodying Wikipedia
765
+ and its sister projects. Content namespaces included: 0 (articles),
766
+ 100 (Cytaty - quotes), 102 (NonNews - fake news), 104 (NonZrodla - fake
767
+ sources), 106 (Slownik - fake dictionary), 108 (Gra - games), 110 (Forum),
768
+ 114 (Poradnik - guides). Latest revision per page. This is informal,
769
+ humorous creative Polish - satire, jokes, parody reference text.
770
+
771
+ - Dump: {IA_FILE}, sha1-verified against archive.org item metadata
772
+ - Non-redirect content pages: {stats['source_pages']:,}
773
+ - Retained after text QA and within-source deduplication: {stats['kept']:,}
774
+ - Characters: {stats['characters']:,}
775
+ - Tokens: {stats['tokens']:,} (`cl100k_base` proxy)
776
+ - License: CC BY-SA 3.0 per record; authorship via per-page history link
777
+
778
+ ## Provenance and rights
779
+
780
+ Nonsensopedia text is licensed [CC BY-SA 3.0]({LICENSE_TERMS_URL}); the
781
+ archive.org item metadata declares the same licenseurl. Each record keeps
782
+ its page id, title, namespace, last-revision timestamp and canonical URL -
783
+ the page revision history is the attribution trail. The dump was produced by
784
+ the WikiTeam preservation project (wikiteam3). Additional third-party
785
+ attribution notices must be preserved and remain a review item.
786
+ The `created` field is the last revision date, not page creation.
787
+
788
+ ## Processing and limitations
789
+
790
+ Wikitext is stripped with mwparserfromhell; lines occurring in at least
791
+ {BOILERPLATE_MIN_DOC_FREQ:.0%} of documents are removed as
792
+ cross-document boilerplate (see `artifacts/boilerplate_lines.json`). Unicode and
793
+ whitespace normalization, email/labelled-phone/IP/labelled-national-ID/account-candidate pattern redaction, three-window langid
794
+ vote, exact and near deduplication within source. The final text must contain at
795
+ least {MIN_TEXT_CHARS} characters after redaction. Rejection counts:
796
+
797
+ ```json
798
+ {json.dumps(qa['rejection_counts'], ensure_ascii=False, indent=2)}
799
+ ```
800
+
801
+ PII filtering masks parsed IPv6 addresses (including compressed forms), labelled
802
+ PESEL/NIP/REGON and 26-digit account candidates as well as the existing patterns.
803
+ The account filter is conservative and may mask non-account numbers; unlabelled
804
+ identifiers, free-form phone numbers, names and personal disclosures may remain.
805
+ This is not complete anonymization.
806
+
807
+ The register is deliberately non-factual: satirical articles, fake news,
808
+ fake dictionary entries, quotes, forum posts and game pages. Pages may parody
809
+ or quote real Wikipedia articles and other copyrighted works; quoted passages
810
+ are not guaranteed disjoint from other corpus shards. The record model is a
811
+ whole content page; individual entries are not split.
812
+
813
+ ## Review artifacts
814
+
815
+ See `artifacts/sample.jsonl`, `attribution.jsonl`, `decisions.jsonl`,
816
+ `source_manifest.jsonl`, `overlap_audit.json`, `stats.json`, `qa.json`,
817
+ `checksums.json`, `run.json` and `ontology.json`.
818
+ """
819
+ (root / "README.md").write_text(card, encoding="utf-8")
820
+ (root / "NOTICE.md").write_text(
821
+ "# Attribution and license notice\n\n"
822
+ "Source: Nonsensopedia, https://nonsa.pl/ - a Polish-language satirical community wiki.\n\n"
823
+ "Text is available under the Creative Commons Attribution-ShareAlike 3.0 License "
824
+ "(https://creativecommons.org/licenses/by-sa/3.0/). Attribution is provided via the per-record "
825
+ "canonical page URL in `artifacts/attribution.jsonl`; each page's revision history lists its "
826
+ "contributors. Dump archived by the WikiTeam preservation project "
827
+ f"({IA_ITEM_URL}).\n\n"
828
+ "Preparation: Piotr Styla with Devin. Changes: content-namespace filtering, latest-revision "
829
+ "selection, wikitext stripping, cross-document boilerplate removal, Unicode and whitespace "
830
+ "normalization, limited email/labelled-phone/IP/labelled-national-ID/account-candidate "
831
+ "redaction, language/quality filtering and within-source deduplication. No endorsement by "
832
+ "Nonsensopedia contributors is implied.\n",
833
+ encoding="utf-8",
834
+ )
835
+ print(json.dumps(stats, ensure_ascii=False, indent=2))
836
+
837
+
838
+ def verify(out):
839
+ import pyarrow.parquet as pq
840
+
841
+ root = out / "hf_repo"
842
+ table = pq.read_table(root / "data/train-00000-of-00001.parquet")
843
+ rows = table.to_pylist()
844
+ stats = load(root / "artifacts/stats.json")
845
+ decisions = read_lines(root / "artifacts/decisions.jsonl")
846
+ attribution = read_lines(root / "artifacts/attribution.jsonl")
847
+ sample = read_lines(root / "artifacts/sample.jsonl")
848
+ assert table.column_names == FIELDS
849
+ assert len(rows) == stats["kept"] == len(attribution)
850
+ assert sum(item["selected"] for item in decisions) == len(rows)
851
+ assert sum(row["token_count"] for row in rows) == stats["tokens"]
852
+ assert all(row["source"] == SOURCE and row["license"] == LICENSE_SPDX for row in rows)
853
+ assert all(EMAIL_RE.search(row["text"]) is None for row in rows)
854
+ by_id = {row["id"]: row for row in rows}
855
+ assert len(sample) == stats["sample_count"] and all(by_id[row["id"]] == row for row in sample)
856
+ ontology = load(root / "artifacts/ontology.json")
857
+ evidence = {item["id"] for item in ontology["evidence"]}
858
+ assert all(item["falsification_condition"] and set(item["supported_by"]) <= evidence for item in ontology["claims"])
859
+ checks = load(root / "artifacts/checksums.json")
860
+ assert all((root / path).is_file() and digest((root / path).read_bytes()) == checksum for path, checksum in checks.items())
861
+ for item in ontology["evidence"]:
862
+ artifact = root / item["artifact"]
863
+ assert artifact.is_file() and digest(load(artifact)) == item["content_address"]
864
+ import tiktoken
865
+
866
+ encoder = tiktoken.get_encoding("cl100k_base")
867
+ assert len(by_id) == len(rows)
868
+ assert set(by_id) == {item["id"] for item in attribution}
869
+ assert set(by_id) == {item["id"] for item in decisions if item["selected"]}
870
+ assert len(decisions) == stats["source_pages"]
871
+ assert len(decisions) - len(rows) == stats["rejected"]
872
+ assert sum(len(row["text"]) for row in rows) == stats["characters"]
873
+ short_ids = [row["id"] for row in rows if len(row["text"]) < MIN_TEXT_CHARS]
874
+ assert all(row["token_count"] > 0 for row in rows)
875
+ assert all(len(row["created"]) == 10 and row["author"] for row in rows)
876
+ assert all(item["ns"] in CONTENT_NS and item["url"] == page_url(item["title"])
877
+ and item["text_sha256"] == digest(by_id[item["id"]]["text"].encode("utf-8"))
878
+ for item in attribution)
879
+ assert all(len(encoder.encode_ordinary(row["text"])) == row["token_count"] for row in rows)
880
+ boilerplate = set(load(root / "artifacts/boilerplate_lines.json"))
881
+ review_ids = {row["id"] for row in sorted(sample, key=lambda item: len(item["text"]))[:3]}
882
+ comparisons = []
883
+ reconstructed = set()
884
+ for shard in sorted((out / "extracted").glob("*.jsonl.gz")):
885
+ with gzip.open(shard, "rt", encoding="utf-8") as handle:
886
+ for line in handle:
887
+ original = json.loads(line)
888
+ row_id = f"{SOURCE}_{original['pageid']}"
889
+ if row_id not in by_id:
890
+ continue
891
+ text = normalize(original["text"])
892
+ text = "\n".join(line for line in text.splitlines()
893
+ if re.sub(r"\s+", " ", line).strip() not in boilerplate)
894
+ text = re.sub(r"\n{3,}", "\n\n", text).strip().replace("\ufffd", "[UNREADABLE_GLYPH]")
895
+ text, _ = redact_pii(text)
896
+ before = redact_pii(original["text"])[0] if row_id in review_ids else ""
897
+ assert text == by_id[row_id]["text"], row_id
898
+ assert row_id not in reconstructed
899
+ reconstructed.add(row_id)
900
+ if row_id in review_ids:
901
+ comparisons.append({"id": row_id, "title": original["title"],
902
+ "before_normalization_pii_patterns_redacted": before,
903
+ "after": text})
904
+ assert reconstructed == set(by_id)
905
+ write_lines(out / "validation_samples.jsonl", comparisons)
906
+ lengths = sorted(len(row["text"]) for row in rows)
907
+ rejection_counts = dict(Counter(item["reason"] for item in decisions if not item["selected"]))
908
+ residuals = {name: sum(bool(pattern.search(row["text"])) for row in rows)
909
+ for name, pattern in {"email": EMAIL_RE, "labelled_phone": PHONE_RE,
910
+ "ipv4": IPV4_RE, "ipv6_current_pattern": IPV6_RE}.items()}
911
+ privacy_review = {
912
+ "compressed_ipv6_documents": sum(any(is_ipv6(match.group()) for match in IPV6_CANDIDATE_RE.finditer(row["text"])) for row in rows),
913
+ "labelled_national_identifier_candidates": sum(bool(NATIONAL_ID_RE.search(row["text"])) for row in rows),
914
+ "bank_account_candidates": sum(bool(BANK_ACCOUNT_RE.search(row["text"])) for row in rows),
915
+ }
916
+ report = {
917
+ "observed_at": now(), "verified": not short_ids and not any(residuals.values()) and not any(privacy_review.values()), "stats": stats,
918
+ "additional_privacy_review_document_counts": privacy_review,
919
+ "below_minimum_length_ids": short_ids,
920
+ "rejection_counts": rejection_counts,
921
+ "retained_namespaces": dict(Counter(item["ns"] for item in attribution)),
922
+ "length_quantiles": {str(q): lengths[int((len(lengths) - 1) * q)] for q in (0, 0.5, 0.9, 0.99, 1)},
923
+ "residual_pattern_document_counts": residuals,
924
+ "all_token_counts_recomputed": True,
925
+ "texts_reconstructed_from_extracted_source": len(reconstructed),
926
+ "before_after_samples": len(comparisons),
927
+ "publication_ready": False,
928
+ "pending": ["license evidence and attribution review", "PII coverage review",
929
+ "target overlap audit methodology review", "manual text quality review"],
930
+ }
931
+ save(out / "validation_report.json", report)
932
+ print(json.dumps(report, ensure_ascii=False, indent=2))
933
+ assert report["verified"], "Validation failures: see validation_report.json"
934
+
935
+
936
+ def main():
937
+ parser = argparse.ArgumentParser()
938
+ parser.add_argument("--output", type=Path, required=True)
939
+ parser.add_argument("--workers", type=int, default=8)
940
+ parser.add_argument("command", choices=["discover", "acquire", "audit_target", "audit_overlap",
941
+ "build", "verify"])
942
+ args = parser.parse_args()
943
+ if args.command == "discover":
944
+ discover(args.output)
945
+ elif args.command == "acquire":
946
+ acquire(args.output, args.workers)
947
+ elif args.command == "audit_target":
948
+ audit_target(args.output)
949
+ elif args.command == "audit_overlap":
950
+ audit_overlap(args.output)
951
+ elif args.command == "build":
952
+ build(args.output)
953
+ else:
954
+ verify(args.output)
955
+
956
+
957
+ if __name__ == "__main__":
958
+ main()
959
+
src/sources.py CHANGED
@@ -51,7 +51,7 @@ SOURCES = {
51
  "custom_datasheet": True,
52
  },
53
  "nonsa": {
54
- "added": "2026-09-28",
55
  "release": None,
56
  "file_key": "nonsa",
57
  "pretty": "Nonsensopedia (Polish satirical wiki, content namespaces)",
 
51
  "custom_datasheet": True,
52
  },
53
  "nonsa": {
54
+ "added": "2026-09-29",
55
  "release": None,
56
  "file_key": "nonsa",
57
  "pretty": "Nonsensopedia (Polish satirical wiki, content namespaces)",
src/test_build_nonsa_pl.py CHANGED
@@ -1,206 +1,239 @@
1
- import importlib.util
2
- from pathlib import Path
3
-
4
-
5
- SCRIPT = Path(__file__).with_name("build_nonsa_pl.py")
6
- SPEC = importlib.util.spec_from_file_location("build_nonsa_pl", SCRIPT)
7
- MODULE = importlib.util.module_from_spec(SPEC)
8
- SPEC.loader.exec_module(MODULE)
9
-
10
-
11
- def test_content_namespaces_exclude_talk_and_meta():
12
- assert "0" in MODULE.CONTENT_NS
13
- assert all(int(ns) >= 0 for ns in MODULE.CONTENT_NS)
14
- for talk in ("1", "3", "101", "103", "105", "107", "109", "111", "113", "115"):
15
- assert talk not in MODULE.CONTENT_NS
16
-
17
-
18
- def test_normalize_repairs_hyphenation_and_page_numbers():
19
- assert MODULE.normalize("Pierw-\nszy akapit.\n12\n\ndrugi wiersz") == "Pierwszy akapit.\n\ndrugi wiersz"
20
-
21
-
22
- def test_title_normalization_is_case_and_diacritic_insensitive():
23
- assert MODULE.normalize_title("Dyskusja:Łódź (woj.)") == "dyskusja łodz woj"
24
-
25
-
26
- def test_boilerplate_lines_removed_only_when_frequent():
27
- docs = [["Baner wikiprojektu", f"Prawdziwa dyskusja {i}."] for i in range(150)]
28
- lines = MODULE.strip_boilerplate(docs)
29
- assert "Baner wikiprojektu" in lines
30
- assert "Prawdziwa dyskusja 0." not in lines
31
-
32
-
33
- def test_boilerplate_long_lines_never_dropped():
34
- docs = [["x" * 200] * 1 for _ in range(150)]
35
- assert MODULE.strip_boilerplate(docs) == set()
36
-
37
-
38
- def test_ip_redaction_patterns():
39
- text = "Podpisano przez 83.4.55.1 dnia 2 maja"
40
- assert MODULE.IPV4_RE.search(text)
41
- assert not MODULE.IPV4_RE.search("wersja 1.2 wydana")
42
-
43
-
44
- def test_redaction_covers_compressed_ipv6_and_labelled_identifiers():
45
- text = "Adres [2001:db8::1], ::ffff:192.0.2.1. PESEL: 00000000000 NIP 000-000-00-00 REGON: 000000000 Rachunek PL00 " + "0000 " * 6
46
- cleaned, counts = MODULE.redact_pii(text)
47
- assert "2001:db8" not in cleaned and "192.0.2.1" not in cleaned
48
- assert cleaned.count("[REDACTED:IP]") == 2
49
- assert cleaned.count("[REDACTED:ID]") == 3
50
- assert "[REDACTED:ACCOUNT]" in cleaned
51
- assert counts["ipv6"] == 2 and counts["national_identifier"] == 3
52
- assert MODULE.redact_pii(cleaned)[0] == cleaned
53
-
54
-
55
- def test_redaction_preserves_time_and_version_numbers():
56
- text = "Wersja 1.2.3, godzina 12:30:45. Adres 2001:db8::2."
57
- cleaned, _ = MODULE.redact_pii(text)
58
- assert cleaned == "Wersja 1.2.3, godzina 12:30:45. Adres [REDACTED:IP]."
59
-
60
-
61
- def test_attribution_url_quotes_fragments_and_polish_characters():
62
- from urllib.parse import unquote, urlsplit
63
-
64
- url = MODULE.page_url("Dyskusja:Łódź/C#")
65
- assert url.isascii()
66
- assert not urlsplit(url).fragment
67
- assert unquote(urlsplit(url).path) == "/wiki/Dyskusja:Łódź/C#"
68
-
69
-
70
- def test_text_bound_and_license():
71
- assert MODULE.MIN_TEXT_CHARS == 500
72
- assert MODULE.LICENSE_SPDX == "CC-BY-SA-3.0"
73
- assert MODULE.DUMP_DATE.startswith("20")
74
- assert MODULE.IA_FILE.endswith("-history.xml.zst")
75
-
76
-
77
- def test_boilerplate_shingles_detected_on_subsample_and_filtered():
78
- template = ["to jest szablon powitania bota " * 30]
79
- docs = [{"text": "\n".join(template + [f"unikalny tekst {i} " * 30])} for i in range(200)]
80
- hot, max_df, sampled = MODULE.boilerplate_shingles(docs, set(), stride=1, fraction=0.5)
81
- assert sampled == 200 and max_df == 100
82
- template_sketch = MODULE.shingle_sketch(" ".join(template))
83
- assert template_sketch & hot == template_sketch # whole template is boilerplate
84
- unique = MODULE.shingle_sketch(f"unikalny tekst 7 " * 30)
85
- assert unique - hot
86
- assert MODULE.filter_sketch(template_sketch | unique, hot) == unique - hot
87
-
88
-
89
- def test_indexed_dedup_matches_exhaustive_comparison():
90
- import random
91
-
92
- rng = random.Random(42)
93
- sketches = [set(), {1}, {1}, set(range(10)), set(range(9)), set(range(8))]
94
- for _ in range(200):
95
- base = set(rng.sample(range(10000), rng.randint(10, 200)))
96
- sketches.extend([base, base | {10001}, set(sorted(base)[1:]), base | set(range(20))])
97
- index = MODULE.NearDuplicateIndex()
98
- retained = []
99
- for sketch in sketches:
100
- expected = (None, 0.0)
101
- for row_id, other in retained:
102
- score = len(sketch & other) / max(len(sketch | other), 1)
103
- if score >= 0.90:
104
- expected = (row_id, score)
105
- break
106
- assert index.find(sketch) == expected
107
- if expected[0] is None:
108
- row_id = str(len(retained))
109
- retained.append((row_id, sketch))
110
- index.add(row_id, sketch)
111
-
112
-
113
- def test_index_avoids_comparing_disjoint_sketches():
114
- index = MODULE.NearDuplicateIndex()
115
- for i in range(1000):
116
- sketch = set(range(i * 100, (i + 1) * 100))
117
- assert index.find(sketch) == (None, 0.0)
118
- index.add(str(i), sketch)
119
- assert index.comparisons == 0
120
- assert index.find(set(range(90000, 90100))) == ("900", 1.0)
121
- assert index.comparisons == 1
122
-
123
-
124
- def test_language_vote_reuses_identical_windows_without_changing_votes():
125
- class Identifier:
126
- def __init__(self):
127
- self.calls = 0
128
-
129
- def classify(self, text):
130
- self.calls += 1
131
- return "pl", 0.99
132
-
133
- identifier = Identifier()
134
- language, votes = MODULE.language_vote(identifier, "Przykładowy polski tekst.")
135
- assert language == "pl" and votes == [("pl", 0.99)] * 3
136
- assert identifier.calls == 1
137
-
138
-
139
- def write_test_source(tmp_path, texts):
140
- import gzip
141
- import json
142
-
143
- MODULE.save(tmp_path / "selection.json", {"dump_date": "20251009", "files": [], "archive_org_item": "wiki-nonsa.pl-20251009", "observed_at": "2026-09-11T00:00:00Z"})
144
- MODULE.save(tmp_path / "acquisition.json", {"source_pages": len(texts), "observed_at": "2026-09-11T00:00:00Z"})
145
- records = [{"pageid": str(index), "ns": "0", "title": f"NonArtykul:Test {index}", "timestamp": "2025-10-01",
146
- "wikitext_chars": len(text), "text": text} for index, text in enumerate(texts, 1)]
147
- MODULE.write_lines(tmp_path / "source_manifest.jsonl", records)
148
- (tmp_path / "extracted").mkdir()
149
- with gzip.open(tmp_path / "extracted/test.jsonl.gz", "wt", encoding="utf-8") as handle:
150
- for record in records:
151
- handle.write(json.dumps(record) + "\n")
152
-
153
-
154
- def test_build_rechecks_length_after_redaction(tmp_path, monkeypatch):
155
- text = ("To jest przykładowa wypowiedź po polsku. " * 20)[:470] + " " + "kontakt" * 8 + "@example.org"
156
- write_test_source(tmp_path, [text])
157
- monkeypatch.setattr(MODULE, "language_vote", lambda identifier, text: ("pl", [("pl", 1.0)]))
158
- MODULE.build(tmp_path)
159
- decision = MODULE.read_lines(tmp_path / "hf_repo/artifacts/decisions.jsonl")[0]
160
- assert not decision["selected"]
161
- assert decision["reason"] == "too_little_text_after_redaction"
162
-
163
-
164
- def test_build_verify_roundtrip_and_tamper_detection(tmp_path, monkeypatch):
165
- import pytest
166
- import pyarrow as pa
167
- import pyarrow.parquet as pq
168
-
169
- text = "To jest przykładowa wypowiedź po polsku dotycząca edycji encyklopedii. " * 15
170
- write_test_source(tmp_path, [text, text, "Krótki tekst."])
171
- monkeypatch.setattr(MODULE, "language_vote", lambda identifier, text: ("pl", [("pl", 1.0)]))
172
- MODULE.build(tmp_path)
173
- MODULE.verify(tmp_path)
174
- report = MODULE.load(tmp_path / "validation_report.json")
175
- assert report["verified"]
176
- assert report["texts_reconstructed_from_extracted_source"] == 1
177
- assert report["rejection_counts"] == {"normalized_duplicate": 1, "too_little_text": 1}
178
- assert report["before_after_samples"] == 1
179
- assert not report["publication_ready"]
180
- path = tmp_path / "hf_repo/data/train-00000-of-00001.parquet"
181
- table = pq.read_table(path)
182
- rows = table.to_pylist()
183
- rows[0]["token_count"] += 1
184
- pq.write_table(pa.Table.from_pylist(rows, schema=table.schema), path)
185
- with pytest.raises(AssertionError):
186
- MODULE.verify(tmp_path)
187
-
188
-
189
- def test_parse_dump_keeps_latest_revision_per_page(tmp_path):
190
- import zstandard
191
- import json
192
-
193
- pages = []
194
- for pageid, ts, text in [("5", "2020-01-01T00:00:00Z", "stara rewizja"),
195
- ("5", "2024-06-01T00:00:00Z", "nowa rewizja"),
196
- ("7", "2023-01-01T00:00:00Z", "inna strona")]:
197
- pages.append(f'<page><title>T{pageid}</title><ns>0</ns><id>{pageid}</id>'
198
- f'<revision><timestamp>{ts}</timestamp>'
199
- f'<text xml:space="preserve">{text}</text></revision></page>')
200
- xml = ('<mediawiki xmlns="http://www.mediawiki.org/xml/export-0.11/"><siteinfo/>'
201
- + "".join(pages) + "</mediawiki>").encode("utf-8")
202
- dump = tmp_path / "dump.xml.zst"
203
- dump.write_bytes(zstandard.ZstdCompressor().compress(xml))
204
- records = {rec[0]: rec for rec in MODULE.parse_dump(dump)}
205
- assert set(records) == {"5", "7"}
206
- assert records["5"][3] == "2024-06-01T00:00:00Z" and records["5"][4] == "nowa rewizja"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import importlib.util
2
+ from pathlib import Path
3
+
4
+
5
+ SCRIPT = Path(__file__).with_name("build_nonsa_pl.py")
6
+ SPEC = importlib.util.spec_from_file_location("build_nonsa_pl", SCRIPT)
7
+ MODULE = importlib.util.module_from_spec(SPEC)
8
+ SPEC.loader.exec_module(MODULE)
9
+
10
+
11
+ def test_content_namespaces_exclude_talk_and_meta():
12
+ assert "0" in MODULE.CONTENT_NS
13
+ assert all(int(ns) >= 0 for ns in MODULE.CONTENT_NS)
14
+ for talk in ("1", "3", "101", "103", "105", "107", "109", "111", "113", "115"):
15
+ assert talk not in MODULE.CONTENT_NS
16
+
17
+
18
+ def test_normalize_repairs_hyphenation_and_page_numbers():
19
+ assert MODULE.normalize("Pierw-\nszy akapit.\n12\n\ndrugi wiersz") == "Pierwszy akapit.\n\ndrugi wiersz"
20
+
21
+
22
+ def test_title_normalization_is_case_and_diacritic_insensitive():
23
+ assert MODULE.normalize_title("Dyskusja:Łódź (woj.)") == "dyskusja łodz woj"
24
+
25
+
26
+ def test_boilerplate_lines_removed_only_when_frequent():
27
+ docs = [["Baner wikiprojektu", f"Prawdziwa dyskusja {i}."] for i in range(150)]
28
+ lines = MODULE.strip_boilerplate(docs)
29
+ assert "Baner wikiprojektu" in lines
30
+ assert "Prawdziwa dyskusja 0." not in lines
31
+
32
+
33
+ def test_boilerplate_long_lines_never_dropped():
34
+ docs = [["x" * 200] * 1 for _ in range(150)]
35
+ assert MODULE.strip_boilerplate(docs) == set()
36
+
37
+
38
+ def test_ip_redaction_patterns():
39
+ text = "Podpisano przez 83.4.55.1 dnia 2 maja"
40
+ assert MODULE.IPV4_RE.search(text)
41
+ assert not MODULE.IPV4_RE.search("wersja 1.2 wydana")
42
+
43
+
44
+ def test_redaction_covers_compressed_ipv6_and_labelled_identifiers():
45
+ text = "Adres [2001:db8::1], ::ffff:192.0.2.1. PESEL: 00000000000 NIP 000-000-00-00 REGON: 000000000 Rachunek PL00 " + "0000 " * 6
46
+ cleaned, counts = MODULE.redact_pii(text)
47
+ assert "2001:db8" not in cleaned and "192.0.2.1" not in cleaned
48
+ assert cleaned.count("[REDACTED:IP]") == 2
49
+ assert cleaned.count("[REDACTED:ID]") == 3
50
+ assert "[REDACTED:ACCOUNT]" in cleaned
51
+ assert counts["ipv6"] == 2 and counts["national_identifier"] == 3
52
+ assert MODULE.redact_pii(cleaned)[0] == cleaned
53
+
54
+
55
+ def test_redaction_preserves_time_and_version_numbers():
56
+ text = "Wersja 1.2.3, godzina 12:30:45. Adres 2001:db8::2."
57
+ cleaned, _ = MODULE.redact_pii(text)
58
+ assert cleaned == "Wersja 1.2.3, godzina 12:30:45. Adres [REDACTED:IP]."
59
+
60
+
61
+ def test_attribution_url_quotes_fragments_and_polish_characters():
62
+ from urllib.parse import unquote, urlsplit
63
+
64
+ url = MODULE.page_url("Dyskusja:Łódź/C#")
65
+ assert url.isascii()
66
+ assert not urlsplit(url).fragment
67
+ assert unquote(urlsplit(url).path) == "/wiki/Dyskusja:Łódź/C#"
68
+
69
+
70
+ def test_text_bound_and_license():
71
+ assert MODULE.MIN_TEXT_CHARS == 500
72
+ assert MODULE.LICENSE_SPDX == "CC-BY-SA-3.0"
73
+ assert MODULE.DUMP_DATE.startswith("20")
74
+ assert MODULE.IA_FILE.endswith("-history.xml.zst")
75
+
76
+
77
+ def test_boilerplate_shingles_detected_on_subsample_and_filtered():
78
+ template = ["to jest szablon powitania bota " * 30]
79
+ docs = [{"text": "\n".join(template + [f"unikalny tekst {i} " * 30])} for i in range(200)]
80
+ hot, max_df, sampled = MODULE.boilerplate_shingles(docs, set(), stride=1, fraction=0.5)
81
+ assert sampled == 200 and max_df == 100
82
+ template_sketch = MODULE.shingle_sketch(" ".join(template))
83
+ assert template_sketch & hot == template_sketch # whole template is boilerplate
84
+ unique = MODULE.shingle_sketch(f"unikalny tekst 7 " * 30)
85
+ assert unique - hot
86
+ assert MODULE.filter_sketch(template_sketch | unique, hot) == unique - hot
87
+
88
+
89
+ def test_indexed_dedup_matches_exhaustive_comparison():
90
+ import random
91
+
92
+ rng = random.Random(42)
93
+ sketches = [set(), {1}, {1}, set(range(10)), set(range(9)), set(range(8))]
94
+ for _ in range(200):
95
+ base = set(rng.sample(range(10000), rng.randint(10, 200)))
96
+ sketches.extend([base, base | {10001}, set(sorted(base)[1:]), base | set(range(20))])
97
+ index = MODULE.NearDuplicateIndex()
98
+ retained = []
99
+ for sketch in sketches:
100
+ expected = (None, 0.0)
101
+ for row_id, other in retained:
102
+ score = len(sketch & other) / max(len(sketch | other), 1)
103
+ if score >= 0.90:
104
+ expected = (row_id, score)
105
+ break
106
+ assert index.find(sketch) == expected
107
+ if expected[0] is None:
108
+ row_id = str(len(retained))
109
+ retained.append((row_id, sketch))
110
+ index.add(row_id, sketch)
111
+
112
+
113
+ def test_index_avoids_comparing_disjoint_sketches():
114
+ index = MODULE.NearDuplicateIndex()
115
+ for i in range(1000):
116
+ sketch = set(range(i * 100, (i + 1) * 100))
117
+ assert index.find(sketch) == (None, 0.0)
118
+ index.add(str(i), sketch)
119
+ assert index.comparisons == 0
120
+ assert index.find(set(range(90000, 90100))) == ("900", 1.0)
121
+ assert index.comparisons == 1
122
+
123
+
124
+ def test_language_vote_reuses_identical_windows_without_changing_votes():
125
+ class Identifier:
126
+ def __init__(self):
127
+ self.calls = 0
128
+
129
+ def classify(self, text):
130
+ self.calls += 1
131
+ return "pl", 0.99
132
+
133
+ identifier = Identifier()
134
+ language, votes = MODULE.language_vote(identifier, "Przykładowy polski tekst.")
135
+ assert language == "pl" and votes == [("pl", 0.99)] * 3
136
+ assert identifier.calls == 1
137
+
138
+
139
+ def write_test_source(tmp_path, texts):
140
+ import gzip
141
+ import json
142
+
143
+ MODULE.save(tmp_path / "selection.json", {"dump_date": "20251009", "files": [], "archive_org_item": "wiki-nonsa.pl-20251009", "observed_at": "2026-09-11T00:00:00Z"})
144
+ MODULE.save(tmp_path / "acquisition.json", {"source_pages": len(texts), "observed_at": "2026-09-11T00:00:00Z"})
145
+ records = [{"pageid": str(index), "ns": "0", "title": f"NonArtykul:Test {index}", "timestamp": "2025-10-01",
146
+ "wikitext_chars": len(text), "text": text} for index, text in enumerate(texts, 1)]
147
+ MODULE.write_lines(tmp_path / "source_manifest.jsonl", records)
148
+ (tmp_path / "extracted").mkdir()
149
+ with gzip.open(tmp_path / "extracted/test.jsonl.gz", "wt", encoding="utf-8") as handle:
150
+ for record in records:
151
+ handle.write(json.dumps(record) + "\n")
152
+
153
+
154
+ def test_build_rechecks_length_after_redaction(tmp_path, monkeypatch):
155
+ text = ("To jest przykładowa wypowiedź po polsku. " * 20)[:470] + " " + "kontakt" * 8 + "@example.org"
156
+ write_test_source(tmp_path, [text])
157
+ monkeypatch.setattr(MODULE, "language_vote", lambda identifier, text: ("pl", [("pl", 1.0)]))
158
+ MODULE.build(tmp_path)
159
+ decision = MODULE.read_lines(tmp_path / "hf_repo/artifacts/decisions.jsonl")[0]
160
+ assert not decision["selected"]
161
+ assert decision["reason"] == "too_little_text_after_redaction"
162
+
163
+
164
+ def test_build_verify_roundtrip_and_tamper_detection(tmp_path, monkeypatch):
165
+ import pytest
166
+ import pyarrow as pa
167
+ import pyarrow.parquet as pq
168
+
169
+ text = "To jest przykładowa wypowiedź po polsku dotycząca edycji encyklopedii. " * 15
170
+ write_test_source(tmp_path, [text, text, "Krótki tekst."])
171
+ monkeypatch.setattr(MODULE, "language_vote", lambda identifier, text: ("pl", [("pl", 1.0)]))
172
+ MODULE.build(tmp_path)
173
+ MODULE.verify(tmp_path)
174
+ report = MODULE.load(tmp_path / "validation_report.json")
175
+ assert report["verified"]
176
+ assert report["texts_reconstructed_from_extracted_source"] == 1
177
+ assert report["rejection_counts"] == {"normalized_duplicate": 1, "too_little_text": 1}
178
+ assert report["before_after_samples"] == 1
179
+ assert not report["publication_ready"]
180
+ path = tmp_path / "hf_repo/data/train-00000-of-00001.parquet"
181
+ table = pq.read_table(path)
182
+ rows = table.to_pylist()
183
+ rows[0]["token_count"] += 1
184
+ pq.write_table(pa.Table.from_pylist(rows, schema=table.schema), path)
185
+ with pytest.raises(AssertionError):
186
+ MODULE.verify(tmp_path)
187
+
188
+
189
+ def test_parse_dump_keeps_latest_revision_per_page(tmp_path):
190
+ import zstandard
191
+ import json
192
+
193
+ pages = []
194
+ for pageid, ts, text in [("5", "2020-01-01T00:00:00Z", "stara rewizja"),
195
+ ("5", "2024-06-01T00:00:00Z", "nowa rewizja"),
196
+ ("7", "2023-01-01T00:00:00Z", "inna strona")]:
197
+ pages.append(f'<page><title>T{pageid}</title><ns>0</ns><id>{pageid}</id>'
198
+ f'<revision><timestamp>{ts}</timestamp>'
199
+ f'<text xml:space="preserve">{text}</text></revision></page>')
200
+ xml = ('<mediawiki xmlns="http://www.mediawiki.org/xml/export-0.11/"><siteinfo/>'
201
+ + "".join(pages) + "</mediawiki>").encode("utf-8")
202
+ dump = tmp_path / "dump.xml.zst"
203
+ dump.write_bytes(zstandard.ZstdCompressor().compress(xml))
204
+ records = {rec[0]: rec for rec in MODULE.parse_dump(dump)}
205
+ assert set(records) == {"5", "7"}
206
+ assert records["5"][3] == "2024-06-01T00:00:00Z" and records["5"][4] == "nowa rewizja"
207
+
208
+
209
+ def test_strip_wikitext_drops_category_tags_and_file_options():
210
+ wikitext = ("Wstęp o kotach.\n"
211
+ "[[Plik:Kot.jpg|thumb|250px|Kot [[Nonsensopedia|nonsensopedyczny]]]]\n"
212
+ "[[Grafika:Pies.png|right|200px]]\n"
213
+ "[[File:Mysz.png|mały|alt=mysz|link=Mysz|Mysz w {{Szablon|x}} norze]]\n"
214
+ "Zobacz też [[:Kategoria:Koty|kategorię kotów]] i [[Pies|psa]].\n"
215
+ "__NOTOC__\n[[Kategoria:Zwierzęta]]\n[[kategoria:Koty|*]]")
216
+ text = MODULE.strip_wikitext(wikitext)
217
+ assert "Kategoria:" not in text and "kategoria:" not in text
218
+ assert "px" not in text and "thumb" not in text and "|" not in text
219
+ assert "__NOTOC__" not in text
220
+ assert "Kot nonsensopedyczny" in text
221
+ assert "Mysz w norze" in text or "Mysz w norze" in text
222
+ assert "kategorię kotów" in text and "psa" in text
223
+
224
+
225
+ def test_file_caption_uses_last_non_option_parameter():
226
+ assert MODULE.file_caption("Podpis|center|300px") == "Podpis"
227
+ assert MODULE.file_caption("thumb|200px") == ""
228
+ assert MODULE.file_caption("") == ""
229
+ assert MODULE.split_top_level("a|[[b|c]]|{{d|e}}") == ["a", "[[b|c]]", "{{d|e}}"]
230
+
231
+
232
+ def test_strip_wikitext_handles_links_the_parser_leaves_as_text():
233
+ # Real case (nonsa page 17970): an unclosed '' makes the link unparseable.
234
+ wikitext = ("== Wydarzenia ==\n"
235
+ "[[Plik:Dzień świra.jpg|thumb|200px|''– Może powtórzymy rolę?<br />– Nie no…]]\n"
236
+ "* [[20 stycznia]] – konkurs.")
237
+ text = MODULE.strip_wikitext(wikitext)
238
+ assert "Plik:" not in text and "200px" not in text and "thumb" not in text
239
+ assert "Może powtórzymy rolę?" in text and "20 stycznia – konkurs." in text