Share one Polish-language gate (diacritic ratio, then langid vote); exempt plwiki and plwikivoyage (v2#77)

#85
by ppuzio - opened
src/build_dynaword.py CHANGED
@@ -16,7 +16,7 @@ Usage:
16
  python3 src/build_dynaword.py --sources gutenberg --jobs 16
17
  """
18
  from __future__ import annotations
19
- import argparse, hashlib, io, json, os, re, shutil, subprocess, sys, time
20
  from itertools import islice
21
  import multiprocessing as mp
22
  from pathlib import Path
@@ -24,12 +24,10 @@ import pyarrow as pa
24
  import pyarrow.parquet as pq
25
 
26
  sys.path.insert(0, str(Path(__file__).resolve().parent))
 
27
  from sources import SOURCES, ADDED
28
 
29
- POLISH_RE = re.compile(r"[ąćęłńóśźżĄĆĘŁŃÓŚŹŻ]")
30
- ALPHA_RE = re.compile(r"[^\W\d_]", re.UNICODE)
31
  MIN_CHARS = 200
32
- MIN_POLISH_RATIO = 0.005
33
  MIN_ALPHA_RATIO = 0.70
34
 
35
  SCHEMA = pa.schema([
@@ -47,11 +45,6 @@ def _init_worker():
47
  _ENC = tiktoken.get_encoding("cl100k_base")
48
 
49
 
50
- def _polish_ratio(text):
51
- letters = ALPHA_RE.findall(text)
52
- return len(POLISH_RE.findall(text)) / len(letters) if letters else 0.0
53
-
54
-
55
  def _first_text(value) -> str:
56
  if value is None:
57
  return ""
@@ -70,7 +63,7 @@ def _meta_value(row: dict, keys: tuple[str, ...], default: str = "") -> str:
70
 
71
  def _process_chunk(args):
72
  """Worker: gate + tokenize a batch of raw lines. Returns (records, stats)."""
73
- is_ocr, created, default_license, preserve_created, lines = args
74
  kept, texts = [], []
75
  st = [0, 0, 0, 0] # read, short, lang, ocr
76
  metas = []
@@ -83,7 +76,7 @@ def _process_chunk(args):
83
  continue
84
  if len(text) < MIN_CHARS:
85
  st[1] += 1; continue
86
- if _polish_ratio(text) < MIN_POLISH_RATIO:
87
  st[2] += 1; continue
88
  if is_ocr:
89
  ar = len(ALPHA_RE.findall(text)) / len(text) if text else 0.0
@@ -124,6 +117,7 @@ def build_source(name, cfg, sl_dir, out_root, pool, seen, counter):
124
  "licenses": {}, "authors_with_value": 0}
125
  t0 = time.time()
126
  is_ocr, created = bool(cfg.get("is_ocr")), cfg.get("created", "")
 
127
  preserve_id = bool(cfg.get("preserve_id"))
128
  preserve_created = bool(cfg.get("preserve_created"))
129
  used_ids = set()
@@ -161,7 +155,7 @@ def build_source(name, cfg, sl_dir, out_root, pool, seen, counter):
161
  zstandard.ZstdDecompressor().stream_reader(compressed), encoding="utf-8"
162
  )
163
  line_iter = (ln for ln in stream if ln.strip())
164
- arg_iter = ((is_ocr, created, default_license, preserve_created, ch)
165
  for ch in _chunks(line_iter, 2000))
166
  for kept, cst in pool.imap_unordered(_process_chunk, arg_iter, chunksize=1):
167
  st["read"] += cst[0]; st["drop_short"] += cst[1]
@@ -192,7 +186,8 @@ def build_source(name, cfg, sl_dir, out_root, pool, seen, counter):
192
  print(f" {name}: read {st['read']:,} kept {st['kept']:,} | -short {st['drop_short']:,} "
193
  f"-lang {st['drop_lang']:,} -dup {st['drop_dup']:,} -ocr {st['drop_ocr']:,} | "
194
  f"{st['chars']/1e6:.0f}M chars, {st['tokens']/1e6:.1f}M tok | {st['secs']}s", flush=True)
195
- (out_dir / f"{name}.stats.json").write_text(json.dumps({**st, "license": cfg["license"]}, indent=2))
 
196
  return st
197
 
198
 
 
16
  python3 src/build_dynaword.py --sources gutenberg --jobs 16
17
  """
18
  from __future__ import annotations
19
+ import argparse, hashlib, io, json, os, shutil, subprocess, sys, time
20
  from itertools import islice
21
  import multiprocessing as mp
22
  from pathlib import Path
 
24
  import pyarrow.parquet as pq
25
 
26
  sys.path.insert(0, str(Path(__file__).resolve().parent))
27
+ from language_gate import ALPHA_RE, GATE, is_polish
28
  from sources import SOURCES, ADDED
29
 
 
 
30
  MIN_CHARS = 200
 
31
  MIN_ALPHA_RATIO = 0.70
32
 
33
  SCHEMA = pa.schema([
 
45
  _ENC = tiktoken.get_encoding("cl100k_base")
46
 
47
 
 
 
 
 
 
48
  def _first_text(value) -> str:
49
  if value is None:
50
  return ""
 
63
 
64
  def _process_chunk(args):
65
  """Worker: gate + tokenize a batch of raw lines. Returns (records, stats)."""
66
+ is_ocr, lang_gate, created, default_license, preserve_created, lines = args
67
  kept, texts = [], []
68
  st = [0, 0, 0, 0] # read, short, lang, ocr
69
  metas = []
 
76
  continue
77
  if len(text) < MIN_CHARS:
78
  st[1] += 1; continue
79
+ if lang_gate and not is_polish(text):
80
  st[2] += 1; continue
81
  if is_ocr:
82
  ar = len(ALPHA_RE.findall(text)) / len(text) if text else 0.0
 
117
  "licenses": {}, "authors_with_value": 0}
118
  t0 = time.time()
119
  is_ocr, created = bool(cfg.get("is_ocr")), cfg.get("created", "")
120
+ lang_gate = not cfg.get("polish_by_origin")
121
  preserve_id = bool(cfg.get("preserve_id"))
122
  preserve_created = bool(cfg.get("preserve_created"))
123
  used_ids = set()
 
155
  zstandard.ZstdDecompressor().stream_reader(compressed), encoding="utf-8"
156
  )
157
  line_iter = (ln for ln in stream if ln.strip())
158
+ arg_iter = ((is_ocr, lang_gate, created, default_license, preserve_created, ch)
159
  for ch in _chunks(line_iter, 2000))
160
  for kept, cst in pool.imap_unordered(_process_chunk, arg_iter, chunksize=1):
161
  st["read"] += cst[0]; st["drop_short"] += cst[1]
 
186
  print(f" {name}: read {st['read']:,} kept {st['kept']:,} | -short {st['drop_short']:,} "
187
  f"-lang {st['drop_lang']:,} -dup {st['drop_dup']:,} -ocr {st['drop_ocr']:,} | "
188
  f"{st['chars']/1e6:.0f}M chars, {st['tokens']/1e6:.1f}M tok | {st['secs']}s", flush=True)
189
+ (out_dir / f"{name}.stats.json").write_text(json.dumps(
190
+ {**st, "lang_gate": GATE if lang_gate else None, "license": cfg["license"]}, indent=2))
191
  return st
192
 
193
 
src/build_nonsa_pl.py CHANGED
@@ -20,6 +20,8 @@ from urllib.parse import quote
20
 
21
  import requests
22
 
 
 
23
 
24
  SOURCE = "nonsa"
25
  OWN_REPO = "PiotrSty/nonsa-pl"
@@ -481,14 +483,6 @@ class NearDuplicateIndex:
481
  self.postings.setdefault(value, []).append(position)
482
 
483
 
484
- def language_vote(identifier, text):
485
- chunks = [text[:30_000], text[max(0, len(text) // 2 - 15_000):len(text) // 2 + 15_000], text[-30_000:]]
486
- classified = {chunk: identifier.classify(chunk) for chunk in dict.fromkeys(chunks) if chunk.strip()}
487
- votes = [classified[chunk] for chunk in chunks if chunk in classified]
488
- languages = Counter(language for language, _ in votes)
489
- return (languages.most_common(1)[0][0] if languages else "unknown", votes)
490
-
491
-
492
  def audit_target(out):
493
  info = request_json(f"https://huggingface.co/api/datasets/{TARGET}")
494
  revision = info["sha"]
 
20
 
21
  import requests
22
 
23
+ from language_gate import language_vote
24
+
25
 
26
  SOURCE = "nonsa"
27
  OWN_REPO = "PiotrSty/nonsa-pl"
 
483
  self.postings.setdefault(value, []).append(position)
484
 
485
 
 
 
 
 
 
 
 
 
486
  def audit_target(out):
487
  info = request_json(f"https://huggingface.co/api/datasets/{TARGET}")
488
  revision = info["sha"]
src/build_plwiki_talk_pl.py CHANGED
@@ -21,6 +21,8 @@ from urllib.parse import quote
21
 
22
  import requests
23
 
 
 
24
 
25
  SOURCE = "plwiki_talk"
26
  OWN_REPO = "PiotrSty/plwiki-talk-pages"
@@ -341,14 +343,6 @@ class NearDuplicateIndex:
341
  self.postings.setdefault(value, []).append(position)
342
 
343
 
344
- def language_vote(identifier, text):
345
- chunks = [text[:30_000], text[max(0, len(text) // 2 - 15_000):len(text) // 2 + 15_000], text[-30_000:]]
346
- classified = {chunk: identifier.classify(chunk) for chunk in dict.fromkeys(chunks) if chunk.strip()}
347
- votes = [classified[chunk] for chunk in chunks if chunk in classified]
348
- languages = Counter(language for language, _ in votes)
349
- return (languages.most_common(1)[0][0] if languages else "unknown", votes)
350
-
351
-
352
  def audit_target(out):
353
  info = request_json(f"https://huggingface.co/api/datasets/{TARGET}")
354
  revision = info["sha"]
 
21
 
22
  import requests
23
 
24
+ from language_gate import language_vote
25
+
26
 
27
  SOURCE = "plwiki_talk"
28
  OWN_REPO = "PiotrSty/plwiki-talk-pages"
 
343
  self.postings.setdefault(value, []).append(position)
344
 
345
 
 
 
 
 
 
 
 
 
346
  def audit_target(out):
347
  info = request_json(f"https://huggingface.co/api/datasets/{TARGET}")
348
  revision = info["sha"]
src/build_plwiki_usertalk_pl.py CHANGED
@@ -21,6 +21,8 @@ from urllib.parse import quote
21
 
22
  import requests
23
 
 
 
24
 
25
  SOURCE = "plwiki_user_talk"
26
  OWN_REPO = "PiotrSty/plwiki-user-talk-pages"
@@ -364,14 +366,6 @@ class NearDuplicateIndex:
364
  self.postings.setdefault(value, []).append(position)
365
 
366
 
367
- def language_vote(identifier, text):
368
- chunks = [text[:30_000], text[max(0, len(text) // 2 - 15_000):len(text) // 2 + 15_000], text[-30_000:]]
369
- classified = {chunk: identifier.classify(chunk) for chunk in dict.fromkeys(chunks) if chunk.strip()}
370
- votes = [classified[chunk] for chunk in chunks if chunk in classified]
371
- languages = Counter(language for language, _ in votes)
372
- return (languages.most_common(1)[0][0] if languages else "unknown", votes)
373
-
374
-
375
  def audit_target(out):
376
  info = request_json(f"https://huggingface.co/api/datasets/{TARGET}")
377
  revision = info["sha"]
 
21
 
22
  import requests
23
 
24
+ from language_gate import language_vote
25
+
26
 
27
  SOURCE = "plwiki_user_talk"
28
  OWN_REPO = "PiotrSty/plwiki-user-talk-pages"
 
366
  self.postings.setdefault(value, []).append(position)
367
 
368
 
 
 
 
 
 
 
 
 
369
  def audit_target(out):
370
  info = request_json(f"https://huggingface.co/api/datasets/{TARGET}")
371
  revision = info["sha"]
src/build_uzp_orzeczenia_pl.py CHANGED
@@ -26,6 +26,8 @@ import time
26
 
27
  import requests
28
 
 
 
29
 
30
  SOURCE = "uzp_orzeczenia_pl"
31
  OWN_REPO = "PiotrSty/uzp-orzeczenia-pl"
@@ -406,14 +408,6 @@ class NearDuplicateIndex:
406
  self.postings.setdefault(value, []).append(position)
407
 
408
 
409
- def language_vote(identifier, text):
410
- chunks = [text[:30_000], text[max(0, len(text) // 2 - 15_000):len(text) // 2 + 15_000], text[-30_000:]]
411
- classified = {chunk: identifier.classify(chunk) for chunk in dict.fromkeys(chunks) if chunk.strip()}
412
- votes = [classified[chunk] for chunk in chunks if chunk in classified]
413
- languages = Counter(language for language, _ in votes)
414
- return (languages.most_common(1)[0][0] if languages else "unknown", votes)
415
-
416
-
417
  def audit_target(out):
418
  info = request_json(f"https://huggingface.co/api/datasets/{TARGET}")
419
  revision = info["sha"]
 
26
 
27
  import requests
28
 
29
+ from language_gate import language_vote
30
+
31
 
32
  SOURCE = "uzp_orzeczenia_pl"
33
  OWN_REPO = "PiotrSty/uzp-orzeczenia-pl"
 
408
  self.postings.setdefault(value, []).append(position)
409
 
410
 
 
 
 
 
 
 
 
 
411
  def audit_target(out):
412
  info = request_json(f"https://huggingface.co/api/datasets/{TARGET}")
413
  revision = info["sha"]
src/build_wiadomosci_statystyczne_pl.py CHANGED
@@ -19,6 +19,8 @@ from urllib.parse import quote, urlsplit, urlunsplit
19
 
20
  import requests
21
 
 
 
22
 
23
  SOURCE = "wiadomosci_statystyczne_pl"
24
  OWN_REPO = "PiotrSty/wiadomosci-statystyczne-pl-articles"
@@ -280,13 +282,6 @@ def shingle_sketch(text, limit=5_000):
280
  return hashes
281
 
282
 
283
- def language_vote(identifier, text):
284
- chunks = [text[:30_000], text[max(0, len(text) // 2 - 15_000):len(text) // 2 + 15_000], text[-30_000:]]
285
- votes = [identifier.classify(chunk) for chunk in chunks if chunk.strip()]
286
- languages = Counter(language for language, _ in votes)
287
- return (languages.most_common(1)[0][0] if languages else "unknown", votes)
288
-
289
-
290
  def audit_target(out):
291
  info = request_json(f"https://huggingface.co/api/datasets/{TARGET}")
292
  revision = info["sha"]
 
19
 
20
  import requests
21
 
22
+ from language_gate import language_vote
23
+
24
 
25
  SOURCE = "wiadomosci_statystyczne_pl"
26
  OWN_REPO = "PiotrSty/wiadomosci-statystyczne-pl-articles"
 
282
  return hashes
283
 
284
 
 
 
 
 
 
 
 
285
  def audit_target(out):
286
  info = request_json(f"https://huggingface.co/api/datasets/{TARGET}")
287
  revision = info["sha"]
src/clean_samorzad_gov_pl.py CHANGED
@@ -25,6 +25,8 @@ import pyarrow as pa
25
  import pyarrow.dataset as ds
26
  import pyarrow.parquet as pq
27
 
 
 
28
  SOURCE = "samorzad_gov_pl"
29
  LICENSE = "CC-BY-SA-4.0"
30
  LICENSE_URL = "https://creativecommons.org/licenses/by-sa/4.0/"
@@ -40,9 +42,6 @@ UPSTREAM_EXPECTED = {
40
  "record_text_sha256": UPSTREAM_TEXT_SHA256,
41
  }
42
  MIN_CHARS = 200
43
- MIN_POLISH_RATIO = 0.005
44
- POLISH_RE = re.compile(r"[ąćęłńóśźżĄĆĘŁŃÓŚŹŻ]")
45
- ALPHA_RE = re.compile(r"[^\W\d_]", re.UNICODE)
46
  _SITE_NAME_RE = re.compile(
47
  r"<meta\b(?=[^>]*\bproperty\s*=\s*['\"]og:site_name['\"])(?=[^>]*\bcontent\s*=\s*(['\"])(.*?)\1)[^>]*>",
48
  re.IGNORECASE | re.DOTALL,
@@ -321,11 +320,6 @@ def third_party_drop(title: str, text: str) -> str | None:
321
  return None
322
 
323
 
324
- def _polish_ratio(text: str) -> float:
325
- letters = ALPHA_RE.findall(text)
326
- return len(POLISH_RE.findall(text)) / len(letters) if letters else 0.0
327
-
328
-
329
  def _text_hash(text: str) -> bytes:
330
  return hashlib.sha256(text.encode("utf-8")).digest()
331
 
@@ -462,6 +456,7 @@ def build(
462
  "kept": 0,
463
  "drop_short": 0,
464
  "drop_lang": 0,
 
465
  "drop_dup": 0,
466
  "drop_ocr": 0,
467
  "drop_third_party": dict.fromkeys(THIRD_PARTY_DROPS, 0),
@@ -493,7 +488,7 @@ def build(
493
  if len(text) < MIN_CHARS:
494
  stats["drop_short"] += 1
495
  continue
496
- if _polish_ratio(text) < MIN_POLISH_RATIO:
497
  stats["drop_lang"] += 1
498
  continue
499
  digest = _text_hash(text)
 
25
  import pyarrow.dataset as ds
26
  import pyarrow.parquet as pq
27
 
28
+ from language_gate import GATE, is_polish
29
+
30
  SOURCE = "samorzad_gov_pl"
31
  LICENSE = "CC-BY-SA-4.0"
32
  LICENSE_URL = "https://creativecommons.org/licenses/by-sa/4.0/"
 
42
  "record_text_sha256": UPSTREAM_TEXT_SHA256,
43
  }
44
  MIN_CHARS = 200
 
 
 
45
  _SITE_NAME_RE = re.compile(
46
  r"<meta\b(?=[^>]*\bproperty\s*=\s*['\"]og:site_name['\"])(?=[^>]*\bcontent\s*=\s*(['\"])(.*?)\1)[^>]*>",
47
  re.IGNORECASE | re.DOTALL,
 
320
  return None
321
 
322
 
 
 
 
 
 
323
  def _text_hash(text: str) -> bytes:
324
  return hashlib.sha256(text.encode("utf-8")).digest()
325
 
 
456
  "kept": 0,
457
  "drop_short": 0,
458
  "drop_lang": 0,
459
+ "lang_gate": GATE,
460
  "drop_dup": 0,
461
  "drop_ocr": 0,
462
  "drop_third_party": dict.fromkeys(THIRD_PARTY_DROPS, 0),
 
488
  if len(text) < MIN_CHARS:
489
  stats["drop_short"] += 1
490
  continue
491
+ if not is_polish(text):
492
  stats["drop_lang"] += 1
493
  continue
494
  digest = _text_hash(text)
src/fetch_njkp.py CHANGED
@@ -40,6 +40,8 @@ from xml.etree import ElementTree as ET
40
 
41
  import pyarrow as pa
42
  import pyarrow.parquet as pq
 
 
43
  import tiktoken
44
 
45
  URL = ("https://clip.ipipan.waw.pl/NationalCorpusOfPolish"
@@ -54,12 +56,10 @@ LICENSE = "CC-BY-4.0"
54
  LICENSE_URL = "https://creativecommons.org/licenses/by/4.0/"
55
  AUTHOR = "NKJP Consortium (IPI PAN, IJP PAN, PWN, University of Łódź)"
56
 
57
- # Gates - identical thresholds to src/build_dynaword.py so the shard matches
58
- # what the DynaWord build itself would keep.
 
59
  MIN_CHARS = 200
60
- MIN_POLISH_RATIO = 0.005
61
- POLISH_RE = re.compile(r"[ąćęłńóśźżĄĆĘŁŃÓŚŹŻ]")
62
- ALPHA_RE = re.compile(r"[^\W\d_]", re.UNICODE)
63
 
64
  NS = "{http://www.tei-c.org/ns/1.0}"
65
  DIV_TAG, AB_TAG, DATE_TAG = f"{NS}div", f"{NS}ab", f"{NS}date"
@@ -119,12 +119,6 @@ def _clean(text: str) -> str:
119
  return re.sub(r"[ \t]{2,}", " ", _ELLIPSIS.sub(" ", text)).strip()
120
 
121
 
122
- def _polish_ratio(text: str) -> float:
123
- """Fraction of letters that are Polish-specific diacritics (build_dynaword)."""
124
- letters = ALPHA_RE.findall(text)
125
- return len(POLISH_RE.findall(text)) / len(letters) if letters else 0.0
126
-
127
-
128
  def _norm_date(raw: str) -> str:
129
  """Normalize a TEI @when value to an ISO date or bare year, else "".
130
 
@@ -203,7 +197,7 @@ def process_file(xml_path: str) -> tuple[list[dict], list[int]]:
203
  if len(text) < MIN_CHARS:
204
  short += 1
205
  continue
206
- if _polish_ratio(text) < MIN_POLISH_RATIO:
207
  lang += 1
208
  continue
209
  kept.append({
 
40
 
41
  import pyarrow as pa
42
  import pyarrow.parquet as pq
43
+
44
+ from language_gate import MIN_POLISH_RATIO, polish_ratio
45
  import tiktoken
46
 
47
  URL = ("https://clip.ipipan.waw.pl/NationalCorpusOfPolish"
 
56
  LICENSE_URL = "https://creativecommons.org/licenses/by/4.0/"
57
  AUTHOR = "NKJP Consortium (IPI PAN, IJP PAN, PWN, University of Łódź)"
58
 
59
+ # Gates - the length threshold matches src/build_dynaword.py. The language gate is
60
+ # the diacritic ratio alone, not language_gate.is_polish: data/nkjp1m/ATTRIBUTION.md,
61
+ # agreed with IPI PAN, describes the filter as that ratio.
62
  MIN_CHARS = 200
 
 
 
63
 
64
  NS = "{http://www.tei-c.org/ns/1.0}"
65
  DIV_TAG, AB_TAG, DATE_TAG = f"{NS}div", f"{NS}ab", f"{NS}date"
 
119
  return re.sub(r"[ \t]{2,}", " ", _ELLIPSIS.sub(" ", text)).strip()
120
 
121
 
 
 
 
 
 
 
122
  def _norm_date(raw: str) -> str:
123
  """Normalize a TEI @when value to an ISO date or bare year, else "".
124
 
 
197
  if len(text) < MIN_CHARS:
198
  short += 1
199
  continue
200
+ if polish_ratio(text) < MIN_POLISH_RATIO:
201
  lang += 1
202
  continue
203
  kept.append({
src/fetch_open_icm_pl.py CHANGED
@@ -18,6 +18,8 @@ import unicodedata
18
 
19
  import requests
20
 
 
 
21
 
22
  SOURCE = "open_icm_pl"
23
  OWN_REPO = "PiotrSty/open-icm-pl-publications"
@@ -493,13 +495,6 @@ def shingle_sketch(text, limit=5_000):
493
  return hashes
494
 
495
 
496
- def language_vote(identifier, text):
497
- chunks = [text[:30_000], text[max(0, len(text) // 2 - 15_000):len(text) // 2 + 15_000], text[-30_000:]]
498
- votes = [identifier.classify(chunk) for chunk in chunks if chunk.strip()]
499
- languages = Counter(language for language, _ in votes)
500
- return (languages.most_common(1)[0][0] if languages else "unknown", votes)
501
-
502
-
503
  def build(out):
504
  import pyarrow as pa
505
  import pyarrow.parquet as pq
 
18
 
19
  import requests
20
 
21
+ from language_gate import language_vote
22
+
23
 
24
  SOURCE = "open_icm_pl"
25
  OWN_REPO = "PiotrSty/open-icm-pl-publications"
 
495
  return hashes
496
 
497
 
 
 
 
 
 
 
 
498
  def build(out):
499
  import pyarrow as pa
500
  import pyarrow.parquet as pq
src/fetch_wikimedia.py CHANGED
@@ -36,6 +36,7 @@ from build_plwiki_talk_pl import ( # noqa: E402 shared dump helpers
36
  UA, digest, load, now, request, request_json, save, sha1_file,
37
  )
38
  from fetch_wikipedia import pages, text_key # noqa: E402
 
39
  from rights import ( # noqa: E402
40
  BY_SA_4_CUTOFF, DROPPED_PAGES, WIKINEWS_BY_4_CUTOFF, check_dropped_reached, license_for_revision,
41
  )
@@ -441,7 +442,7 @@ Author metadata present for **{st['authors_with_value']:,}** documents.
441
 
442
  ## Filters applied (build_dynaword.py)
443
  - drop documents < 200 chars: **{st['drop_short']:,}** (the fetcher already dropped {prep.get('ns0_short', 0):,})
444
- - drop non-Polish (diacritic ratio): **{st['drop_lang']:,}**
445
  - exact cross-source dedup (sha1): **{st['drop_dup']:,}**
446
  - OCR alpha-ratio < 0.70 (OCR sources only): **{st['drop_ocr']:,}**
447
  - read {st['read']:,} → kept {kept:,}
 
36
  UA, digest, load, now, request, request_json, save, sha1_file,
37
  )
38
  from fetch_wikipedia import pages, text_key # noqa: E402
39
+ from language_gate import card_line # noqa: E402
40
  from rights import ( # noqa: E402
41
  BY_SA_4_CUTOFF, DROPPED_PAGES, WIKINEWS_BY_4_CUTOFF, check_dropped_reached, license_for_revision,
42
  )
 
442
 
443
  ## Filters applied (build_dynaword.py)
444
  - drop documents < 200 chars: **{st['drop_short']:,}** (the fetcher already dropped {prep.get('ns0_short', 0):,})
445
+ {card_line(st)}
446
  - exact cross-source dedup (sha1): **{st['drop_dup']:,}**
447
  - OCR alpha-ratio < 0.70 (OCR sources only): **{st['drop_ocr']:,}**
448
  - read {st['read']:,} → kept {kept:,}
src/language_gate.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Shared Polish-language gate: a diacritic pre-check, then a three-window langid vote.
2
+
3
+ The diacritic ratio alone dropped Polish documents with few diacritics: lists, tables
4
+ and template skeletons (slayerlabs/polish-dynaword-v2#77). A text whose ratio reaches
5
+ MIN_POLISH_RATIO is Polish without a langid call; a text below it is kept only if the
6
+ langid vote over its start, middle and end windows says "pl".
7
+
8
+ Sources that are Polish by origin (``polish_by_origin`` in sources.py) skip the gate:
9
+ on plwiki the dropped pages were Polish articles whose bulk is a list of foreign names
10
+ or titles, and langid labels the list, not the article.
11
+ """
12
+ from __future__ import annotations
13
+
14
+ from collections import Counter
15
+ import re
16
+
17
+ POLISH_RE = re.compile(r"[ąćęłńóśźżĄĆĘŁŃÓŚŹŻ]")
18
+ ALPHA_RE = re.compile(r"[^\W\d_]", re.UNICODE)
19
+ MIN_POLISH_RATIO = 0.005
20
+ # cs and sk keep Czech and Slovak text from scoring as Polish, the nearest
21
+ # Latin-script language left in a smaller set.
22
+ GATE_LANGUAGES = ("pl", "en", "de", "cs", "sk", "uk", "ru")
23
+ # Card wording: what build stats record in "lang_gate". Stats written before this
24
+ # module existed have no such key; those builds used the diacritic ratio alone.
25
+ GATE = "diacritic ratio, then langid vote"
26
+ LEGACY_GATE = "diacritic ratio"
27
+
28
+ _identifier = None # per-process langid identifier, built on first use
29
+
30
+
31
+ def polish_ratio(text: str) -> float:
32
+ """Fraction of letters that are Polish-specific diacritics."""
33
+ letters = ALPHA_RE.findall(text)
34
+ return len(POLISH_RE.findall(text)) / len(letters) if letters else 0.0
35
+
36
+
37
+ def language_vote(identifier, text):
38
+ """Majority langid label over the first, middle and last 30,000 characters.
39
+
40
+ Returns (label, votes); the label is "unknown" for blank text, and a three-way
41
+ tie goes to the first window. Identical windows (short texts) are classified once.
42
+ """
43
+ chunks = [text[:30_000], text[max(0, len(text) // 2 - 15_000):len(text) // 2 + 15_000], text[-30_000:]]
44
+ classified = {chunk: identifier.classify(chunk) for chunk in dict.fromkeys(chunks) if chunk.strip()}
45
+ votes = [classified[chunk] for chunk in chunks if chunk in classified]
46
+ languages = Counter(language for language, _ in votes)
47
+ return (languages.most_common(1)[0][0] if languages else "unknown", votes)
48
+
49
+
50
+ def gate_identifier():
51
+ global _identifier
52
+ if _identifier is None:
53
+ from langid.langid import LanguageIdentifier, model
54
+ _identifier = LanguageIdentifier.from_modelstring(model, norm_probs=True)
55
+ _identifier.set_languages(list(GATE_LANGUAGES))
56
+ return _identifier
57
+
58
+
59
+ def is_polish(text: str) -> bool:
60
+ if polish_ratio(text) >= MIN_POLISH_RATIO:
61
+ return True
62
+ return language_vote(gate_identifier(), text)[0] == "pl"
63
+
64
+
65
+ def card_line(stats: dict) -> str:
66
+ """The dataset-card bullet for the language filter, worded from the build stats."""
67
+ gate = stats.get("lang_gate", LEGACY_GATE)
68
+ if gate is None:
69
+ return "- drop non-Polish: not applied (Polish by origin)"
70
+ return f"- drop non-Polish ({gate}): **{stats.get('drop_lang', 0):,}**"
src/make_docs.py CHANGED
@@ -14,6 +14,7 @@ from pathlib import Path
14
 
15
  sys.path.insert(0, str(Path(__file__).resolve().parent))
16
  from sources import SOURCES, EXCLUDED, ADDED
 
17
 
18
  ROOT = Path(__file__).resolve().parent.parent
19
  VERSION = "0.2.5"
@@ -126,7 +127,7 @@ def datasheet(name, cfg, st):
126
  ## Filters applied (build_dynaword.py)
127
  Minimal, per Dynaword guidelines (heavy filtering left to downstream use):
128
  - drop documents < 200 chars: **{st.get('drop_short', 0):,}**
129
- - drop non-Polish (diacritic ratio): **{st.get('drop_lang', 0):,}**
130
  - exact cross-source dedup (sha1): **{st.get('drop_dup', 0):,}**
131
  - OCR alpha-ratio < 0.70 (OCR sources only): **{st.get('drop_ocr', 0):,}**
132
  - read {st.get('read', st['kept']):,} → kept {st['kept']:,}
 
14
 
15
  sys.path.insert(0, str(Path(__file__).resolve().parent))
16
  from sources import SOURCES, EXCLUDED, ADDED
17
+ from language_gate import card_line
18
 
19
  ROOT = Path(__file__).resolve().parent.parent
20
  VERSION = "0.2.5"
 
127
  ## Filters applied (build_dynaword.py)
128
  Minimal, per Dynaword guidelines (heavy filtering left to downstream use):
129
  - drop documents < 200 chars: **{st.get('drop_short', 0):,}**
130
+ {card_line(st)}
131
  - exact cross-source dedup (sha1): **{st.get('drop_dup', 0):,}**
132
  - OCR alpha-ratio < 0.70 (OCR sources only): **{st.get('drop_ocr', 0):,}**
133
  - read {st.get('read', st['kept']):,} → kept {st['kept']:,}
src/sources.py CHANGED
@@ -113,6 +113,8 @@ SOURCES = {
113
  },
114
  "wikipedia": {
115
  "added": "2026-07-02",
 
 
116
  "release": "0.2.0",
117
  "file_key": "wikipedia",
118
  "preserve_id": True,
@@ -421,6 +423,8 @@ SOURCES = {
421
  },
422
  "wikivoyage": {
423
  "added": "2026-07-02",
 
 
424
  "release": "0.2.0",
425
  "file_key": "plwikivoyage",
426
  "preserve_id": True,
 
113
  },
114
  "wikipedia": {
115
  "added": "2026-07-02",
116
+ # Polish by origin: build_dynaword skips the language gate (src/language_gate.py).
117
+ "polish_by_origin": True,
118
  "release": "0.2.0",
119
  "file_key": "wikipedia",
120
  "preserve_id": True,
 
423
  },
424
  "wikivoyage": {
425
  "added": "2026-07-02",
426
+ # Polish by origin: build_dynaword skips the language gate (src/language_gate.py).
427
+ "polish_by_origin": True,
428
  "release": "0.2.0",
429
  "file_key": "plwikivoyage",
430
  "preserve_id": True,
src/test_build_dynaword_flags.py CHANGED
@@ -21,7 +21,7 @@ def _encoder():
21
 
22
  def _chunk(rows, *, preserve_created, created="2026-07-19"):
23
  lines = [json.dumps(row, ensure_ascii=False) for row in rows]
24
- kept, _ = _process_chunk((False, created, "CC0", preserve_created, lines))
25
  return kept
26
 
27
 
 
21
 
22
  def _chunk(rows, *, preserve_created, created="2026-07-19"):
23
  lines = [json.dumps(row, ensure_ascii=False) for row in rows]
24
+ kept, _ = _process_chunk((False, True, created, "CC0", preserve_created, lines))
25
  return kept
26
 
27
 
src/test_language_gate.py ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+
3
+ import pytest
4
+
5
+ import language_gate
6
+ from language_gate import GATE, LEGACY_GATE, MIN_POLISH_RATIO, card_line, is_polish, language_vote, polish_ratio
7
+
8
+ POLISH = "Zażółć gęślą jaźń. Miasto leży nad rzeką, a jego mieszkańcy pracują w porcie. " * 10
9
+ # Polish with almost no diacritics: a list of foreign titles under a short Polish lead.
10
+ POLISH_LIST = (
11
+ "Ponizej znajduje sie lista filmow wydanych przez wytwornie w latach osiemdziesiatych. "
12
+ "Kazdy film ma swoja strone z opisem fabuly oraz obsada. Wiekszosc z nich byla "
13
+ "nagradzana na festiwalach, a niektore trafily do kin w wielu krajach. "
14
+ ) * 8
15
+ ENGLISH = "The city lies on the river, and most of its residents work in the harbour or the shipyard. " * 10
16
+ GERMAN = "Die Stadt liegt am Fluss, und die meisten Einwohner arbeiten im Hafen oder auf der Werft. " * 10
17
+ CZECH = "Město leží na řece a většina jeho obyvatel pracuje v přístavu nebo v loděnici. " * 10
18
+ RUSSIAN = "Город расположен на реке, и большинство его жителей работают в порту или на верфи. " * 10
19
+ UKRAINIAN = "Місто розташоване на річці, і більшість його мешканців працюють у порту або на верфі. " * 10
20
+
21
+
22
+ class _Identifier:
23
+ """langid stand-in: labels a window by its first character and records each call."""
24
+
25
+ def __init__(self, labels):
26
+ self.labels, self.calls = labels, []
27
+
28
+ def classify(self, chunk):
29
+ self.calls.append(chunk)
30
+ return self.labels[chunk[0]], 1.0
31
+
32
+
33
+ @pytest.fixture
34
+ def no_langid(monkeypatch):
35
+ def fail():
36
+ raise AssertionError("langid must not run when the diacritic ratio passes")
37
+ monkeypatch.setattr(language_gate, "gate_identifier", fail)
38
+
39
+
40
+ def test_polish_prose_passes_on_the_ratio_without_langid(no_langid):
41
+ assert polish_ratio(POLISH) >= MIN_POLISH_RATIO
42
+ assert is_polish(POLISH)
43
+
44
+
45
+ def test_ratio_boundary(no_langid, monkeypatch):
46
+ at = "ą" + "a" * 199
47
+ assert polish_ratio(at) == MIN_POLISH_RATIO
48
+ assert is_polish(at)
49
+ below = "ą" + "a" * 200
50
+ monkeypatch.setattr(language_gate, "gate_identifier", lambda: _Identifier({"ą": "en"}))
51
+ assert not is_polish(below)
52
+
53
+
54
+ def test_polish_list_with_few_diacritics_is_kept_by_the_vote():
55
+ assert polish_ratio(POLISH_LIST) < MIN_POLISH_RATIO
56
+ assert language_vote(language_gate.gate_identifier(), POLISH_LIST)[0] == "pl"
57
+ assert is_polish(POLISH_LIST)
58
+
59
+
60
+ @pytest.mark.parametrize("text,label", [
61
+ (ENGLISH, "en"), (GERMAN, "de"), (CZECH, "cs"), (RUSSIAN, "ru"), (UKRAINIAN, "uk"),
62
+ ])
63
+ def test_other_languages_are_dropped(text, label):
64
+ assert language_vote(language_gate.gate_identifier(), text)[0] == label
65
+ assert not is_polish(text)
66
+
67
+
68
+ def test_blank_text_votes_unknown_and_is_dropped():
69
+ assert language_vote(_Identifier({}), " \n ") == ("unknown", [])
70
+ assert not is_polish("")
71
+
72
+
73
+ def test_vote_windows_majority_tie_and_dedup():
74
+ text = "p" * 30_000 + "e" * 30_000 + "e" * 30_000
75
+ label, votes = language_vote(_Identifier({"p": "pl", "e": "en"}), text)
76
+ assert label == "en" and [v[0] for v in votes] == ["pl", "en", "en"]
77
+
78
+ tie = "p" * 30_000 + "d" * 30_000 + "e" * 30_000
79
+ assert language_vote(_Identifier({"p": "pl", "d": "de", "e": "en"}), tie)[0] == "pl"
80
+
81
+ identifier = _Identifier({"k": "pl"})
82
+ label, votes = language_vote(identifier, "krótki tekst")
83
+ assert label == "pl" and len(votes) == 3 and len(identifier.calls) == 1
84
+
85
+
86
+ def test_gate_identifier_is_restricted_to_the_gate_languages():
87
+ language_gate._identifier = None
88
+ identifier = language_gate.gate_identifier()
89
+ assert identifier is language_gate.gate_identifier()
90
+ assert sorted(identifier.nb_classes) == sorted(language_gate.GATE_LANGUAGES)
91
+
92
+
93
+ @pytest.mark.parametrize("stats,line", [
94
+ ({"drop_lang": 5564}, f"- drop non-Polish ({LEGACY_GATE}): **5,564**"),
95
+ ({"drop_lang": 3, "lang_gate": GATE}, f"- drop non-Polish ({GATE}): **3**"),
96
+ ({"drop_lang": 0, "lang_gate": None}, "- drop non-Polish: not applied (Polish by origin)"),
97
+ ({"lang_gate": GATE}, f"- drop non-Polish ({GATE}): **0**"),
98
+ ])
99
+ def test_card_line(stats, line):
100
+ assert card_line(stats) == line
101
+
102
+
103
+ def test_polish_by_origin_sources():
104
+ from sources import SOURCES
105
+ assert {name for name, cfg in SOURCES.items() if cfg.get("polish_by_origin")} == {"wikipedia", "wikivoyage"}
106
+
107
+
108
+ @pytest.mark.parametrize("polish_by_origin,kept,dropped,gate", [(False, 1, 1, GATE), (True, 2, 0, None)])
109
+ def test_build_source_applies_the_gate_unless_polish_by_origin(tmp_path, polish_by_origin, kept, dropped, gate):
110
+ import zstandard
111
+ import build_dynaword
112
+
113
+ build_dynaword._init_worker()
114
+ rows = [{"text": POLISH}, {"text": ENGLISH}]
115
+ (tmp_path / "src.jsonl.zst").write_bytes(zstandard.ZstdCompressor().compress(
116
+ "".join(json.dumps(row) + "\n" for row in rows).encode()))
117
+ cfg = {"file_key": "src", "license": "CC0", "created": "2026", "polish_by_origin": polish_by_origin}
118
+
119
+ class Pool:
120
+ def imap_unordered(self, fn, items, chunksize):
121
+ return map(fn, items)
122
+
123
+ st = build_dynaword.build_source("probe", cfg, tmp_path, tmp_path, Pool(), set(), [0])
124
+ assert (st["kept"], st["drop_lang"]) == (kept, dropped)
125
+ stats = json.loads((tmp_path / "data" / "probe" / "probe.stats.json").read_text())
126
+ assert stats["lang_gate"] == gate
src/test_studia_bas_contract.py CHANGED
@@ -173,7 +173,7 @@ def test_canonical_builder_preserves_per_record_created_metadata(monkeypatch):
173
  monkeypatch.setattr(build_dynaword, "_ENC", _TokenStub())
174
  record = extract_article(article_fixture(), issue_number="77", year=2024)
175
  kept, stats = build_dynaword._process_chunk(
176
- (False, "2021-2025", LICENSE, True, [json.dumps(record, ensure_ascii=False)])
177
  )
178
  assert stats[0] == 1
179
  assert kept[0][1] == "2024"
@@ -263,7 +263,7 @@ def test_canonical_builder_falls_back_to_source_created_when_record_metadata_is_
263
  # Missing 'created' in the record
264
  record = {'text': 'To jest testowy polski tekst z polskimi znakami diakrytycznymi ąćęłńóśźż.' * 10}
265
  kept, stats = build_dynaword._process_chunk(
266
- (False, '2010-2020', 'CC0', True, [json.dumps(record)])
267
  )
268
  assert kept[0][1] == '2010-2020'
269
 
@@ -279,7 +279,7 @@ def test_canonical_builder_backward_compatibility(monkeypatch, tmp_path):
279
  # Missing 'created' falls back to source config
280
  record = {'text': 'To jest testowy polski tekst z polskimi znakami diakrytycznymi ąćęłńóśźż.' * 10, 'id': 'custom_123'}
281
  kept, _ = build_dynaword._process_chunk(
282
- (False, 'fallback_created', 'fallback_license', True, [json.dumps(record)])
283
  )
284
  assert kept[0][1] == 'fallback_created'
285
  assert kept[0][6] == 'custom_123'
 
173
  monkeypatch.setattr(build_dynaword, "_ENC", _TokenStub())
174
  record = extract_article(article_fixture(), issue_number="77", year=2024)
175
  kept, stats = build_dynaword._process_chunk(
176
+ (False, True, "2021-2025", LICENSE, True, [json.dumps(record, ensure_ascii=False)])
177
  )
178
  assert stats[0] == 1
179
  assert kept[0][1] == "2024"
 
263
  # Missing 'created' in the record
264
  record = {'text': 'To jest testowy polski tekst z polskimi znakami diakrytycznymi ąćęłńóśźż.' * 10}
265
  kept, stats = build_dynaword._process_chunk(
266
+ (False, True, '2010-2020', 'CC0', True, [json.dumps(record)])
267
  )
268
  assert kept[0][1] == '2010-2020'
269
 
 
279
  # Missing 'created' falls back to source config
280
  record = {'text': 'To jest testowy polski tekst z polskimi znakami diakrytycznymi ąćęłńóśźż.' * 10, 'id': 'custom_123'}
281
  kept, _ = build_dynaword._process_chunk(
282
+ (False, True, 'fallback_created', 'fallback_license', True, [json.dumps(record)])
283
  )
284
  assert kept[0][1] == 'fallback_created'
285
  assert kept[0][6] == 'custom_123'