Datasets:
Download src/fetch_njkp.py from SlayerLab/polish-dynaword: direct link, hf CLI and curl.
- Browser
- Download file 13.4 kB
-
https://huggingface.co/datasets/SlayerLab/polish-dynaword/resolve/a9d134ac79a9fe586fc9c11cb39eb32d69dcd21f/src/fetch_njkp.py
- Command line
-
hf download hf://datasets/SlayerLab/polish-dynaword@a9d134ac79a9fe586fc9c11cb39eb32d69dcd21f/src/fetch_njkp.py
-
curl -L -o fetch_njkp.py https://huggingface.co/datasets/SlayerLab/polish-dynaword/resolve/a9d134ac79a9fe586fc9c11cb39eb32d69dcd21f/src/fetch_njkp.py
13.4 kB
| #!/usr/bin/env python3 | |
| """Fetch the NKJP 1-million-word subcorpus (Podkorpus Milionowy NKJP 1.2) and | |
| build a DynaWord-style parquet shard from the TEI source. | |
| Downloads + extracts the IPI PAN tarball under /tmp, then walks every sample | |
| folder and emits one parquet row per <div> in text.xml. Each <div> is a single | |
| contiguous excerpt from one source document (its <ab> paragraphs joined by | |
| newlines, ellipses stripped); across <div>s the excerpts are unrelated, so they | |
| are kept as separate rows rather than merged. | |
| The same minimal gates as src/build_dynaword.py are applied per passage (drop | |
| < 200 chars, drop non-Polish by diacritic ratio, exact sha1 dedup; the OCR gate | |
| is inapplicable - NKJP1M is not OCR), so the shard matches what the DynaWord | |
| build would keep. Per-row `created` is the sample's TEI publication date | |
| (<date type="published">) when the header records one. Token counts use | |
| tiktoken cl100k (encode_ordinary), same as build_dynaword.py, and the emitted | |
| stats are recomputed from the written parquet. | |
| Text extraction + the stats report are adapted from tmp/count_tokens.py. | |
| Usage: | |
| python3 src/fetch_njkp.py --out . --workers 8 | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import hashlib | |
| import json | |
| import re | |
| import ssl | |
| import sys | |
| import tarfile | |
| import time | |
| from concurrent.futures import ProcessPoolExecutor | |
| from datetime import date | |
| from pathlib import Path | |
| from urllib.error import URLError | |
| from urllib.request import urlopen, Request | |
| from xml.etree import ElementTree as ET | |
| import pyarrow as pa | |
| import pyarrow.parquet as pq | |
| import tiktoken | |
| URL = ("https://clip.ipipan.waw.pl/NationalCorpusOfPolish" | |
| "?action=AttachFile&do=get&target=NKJP-PodkorpusMilionowy-1.2.tar.gz") | |
| ROOT_NAME = "NKJP-PodkorpusMilionowy-1.2" | |
| UA = {"User-Agent": "polish-dynaword/0.1 (+research; openly-licensed corpus)"} | |
| KEY = "nkjp1m" # source name / parquet stem, consumed by build_dynaword | |
| LICENSE = "CC-BY" # stated on the NKJP download page (clip.ipipan.waw.pl) | |
| AUTHOR = "NKJP" # compiled/distributed by the NKJP Consortium (IPI PAN) | |
| # Gates - identical thresholds to src/build_dynaword.py so the shard matches | |
| # what the DynaWord build itself would keep. | |
| MIN_CHARS = 200 | |
| MIN_POLISH_RATIO = 0.005 | |
| POLISH_RE = re.compile(r"[ąćęłńóśźżĄĆĘŁŃÓŚŹŻ]") | |
| ALPHA_RE = re.compile(r"[^\W\d_]", re.UNICODE) | |
| NS = "{http://www.tei-c.org/ns/1.0}" | |
| DIV_TAG, AB_TAG, DATE_TAG = f"{NS}div", f"{NS}ab", f"{NS}date" | |
| _ELLIPSIS = re.compile(r"…|\.{3,}") # ellipsis markers stripped from text | |
| # Same schema as src/build_dynaword.py so the shard drops straight into DynaWord. | |
| SCHEMA = pa.schema([ | |
| ("id", pa.string()), ("text", pa.string()), ("source", pa.string()), | |
| ("added", pa.string()), ("created", pa.string()), ("token_count", pa.int64()), | |
| ("license", pa.string()), ("author", pa.string()), | |
| ]) | |
| _ENC = None # per-worker tiktoken encoder | |
| def download(url: str, dst: Path) -> Path: | |
| if dst.exists() and dst.stat().st_size: | |
| print(f" cached {dst}", flush=True) | |
| return dst | |
| print(f" downloading {url}", flush=True) | |
| dst.parent.mkdir(parents=True, exist_ok=True) | |
| def stream(ctx): | |
| with urlopen(Request(url, headers=UA), timeout=120, context=ctx) as r, \ | |
| dst.open("wb") as f: | |
| while chunk := r.read(1 << 20): | |
| f.write(chunk) | |
| try: | |
| stream(None) | |
| except URLError as e: | |
| # clip.ipipan.waw.pl ships an incomplete cert chain Python rejects (curl | |
| # accepts it); retry unverified for this known source only. | |
| if not isinstance(e.reason, ssl.SSLError): | |
| raise | |
| print(" ! TLS verify failed; retrying unverified", file=sys.stderr, flush=True) | |
| stream(ssl._create_unverified_context()) | |
| return dst | |
| def extract_archive(archive: Path, dest: Path) -> Path: | |
| # The tarball has no top folder, so extract into a dedicated dir to scope | |
| # the text.xml scan. | |
| root = dest / ROOT_NAME | |
| if root.is_dir(): | |
| print(f" already extracted {root}", flush=True) | |
| return root | |
| print(f" extracting {archive} -> {root}", flush=True) | |
| root.mkdir(parents=True) | |
| with tarfile.open(archive, "r:gz") as tar: | |
| tar.extractall(root, filter="data") # py3.12+ safe extraction | |
| return root | |
| def _clean(text: str) -> str: | |
| """Strip ellipsis markers (… and "...") and tidy the whitespace they leave.""" | |
| return re.sub(r"[ \t]{2,}", " ", _ELLIPSIS.sub(" ", text)).strip() | |
| def _polish_ratio(text: str) -> float: | |
| """Fraction of letters that are Polish-specific diacritics (build_dynaword).""" | |
| letters = ALPHA_RE.findall(text) | |
| return len(POLISH_RE.findall(text)) / len(letters) if letters else 0.0 | |
| def _norm_date(raw: str) -> str: | |
| """Normalize a TEI @when value to an ISO date or bare year, else "". | |
| Keeps full YYYY-MM-DD, keeps bare YYYY, and salvages a leading 4-digit year | |
| from anything else (e.g. "YYYY-MM", a stray trailing space). Values whose | |
| year is implausible as a publication year (NKJP1M has a few malformed ones, | |
| such as "200") are treated as missing. | |
| """ | |
| raw = (raw or "").strip() | |
| if re.fullmatch(r"\d{4}-\d{2}-\d{2}", raw): | |
| return raw if 1500 <= int(raw[:4]) <= 2014 else "" | |
| m = re.match(r"(\d{4})", raw) | |
| return m.group(1) if m and 1500 <= int(m.group(1)) <= 2014 else "" | |
| def _published_date(header_path: Path) -> str: | |
| """Publication date from a sample's TEI header (<date type='published'>).""" | |
| try: | |
| tree = ET.parse(header_path) | |
| except Exception: # noqa: BLE001 - missing/unreadable header -> no date | |
| return "" | |
| for el in tree.iter(DATE_TAG): | |
| if el.get("type") == "published": | |
| d = _norm_date(el.get("when") or (el.text or "")) | |
| if d: | |
| return d | |
| return "" | |
| def extract_passages(xml_path: str) -> list[str]: | |
| """One passage per TEI <div> (its <ab> paragraphs joined by newlines). | |
| <ab> blocks inside a <div> are adjacent source paragraphs (real coherence); | |
| different <div>s are unrelated sampled excerpts, so each becomes its own row. | |
| Adapted from tmp/count_tokens.py, which instead merged every <ab> per file. | |
| """ | |
| passages, current = [], [] | |
| for _, elem in ET.iterparse(xml_path, events=("end",)): | |
| if elem.tag == AB_TAG: | |
| # itertext() also captures any nested inline markup text. | |
| text = _clean("".join(elem.itertext())) | |
| if text: | |
| current.append(text) | |
| elem.clear() | |
| elif elem.tag == DIV_TAG: | |
| if current: | |
| passages.append("\n".join(current)) | |
| current = [] | |
| elem.clear() | |
| if current: # <ab> outside any <div> (not expected) - keep as one passage | |
| passages.append("\n".join(current)) | |
| return passages | |
| def process_file(xml_path: str) -> tuple[list[dict], list[int]]: | |
| """Sample file -> (kept row dicts per surviving <div>, [read, short, lang]). | |
| Gates run per passage; dedup is deferred to main() so it can span files. | |
| """ | |
| global _ENC | |
| if _ENC is None: | |
| _ENC = tiktoken.get_encoding("cl100k_base") | |
| folder_dir = Path(xml_path).parent | |
| folder = folder_dir.name | |
| created = _published_date(folder_dir / "header.xml") | |
| try: | |
| passages = extract_passages(xml_path) | |
| except Exception: # noqa: BLE001 - skip unreadable samples, don't crash | |
| return [], [0, 0, 0] | |
| read = short = lang = 0 | |
| kept = [] | |
| for i, text in enumerate(passages): | |
| read += 1 | |
| text = text.strip() | |
| if len(text) < MIN_CHARS: | |
| short += 1 | |
| continue | |
| if _polish_ratio(text) < MIN_POLISH_RATIO: | |
| lang += 1 | |
| continue | |
| kept.append({ | |
| "id": f"{KEY}_{folder}_{i}", # passage index kept stable across gating | |
| "text": text, | |
| "created": created, | |
| "tokens": len(_ENC.encode_ordinary(text)), | |
| "chars": len(text), | |
| "sha1": hashlib.sha1(text.encode("utf-8")).digest(), | |
| }) | |
| return kept, [read, short, lang] | |
| def build_stats(parquet_path: Path, gate: dict) -> dict: | |
| """Recompute the sidecar stats directly from the written parquet. | |
| Counts (kept/chars/tokens/licenses/authors/dates) come from the bytes on | |
| disk; the drop_* tallies are build-time artifacts carried over from `gate`. | |
| A cross-check asserts read == kept + drops so the two can't silently drift. | |
| """ | |
| t = pq.read_table(parquet_path) | |
| d = t.to_pydict() | |
| n = t.num_rows | |
| dated = [c for c in d["created"] if c] | |
| years = sorted({int(c[:4]) for c in dated}) | |
| read = gate["read"] | |
| drops = gate["drop_short"] + gate["drop_lang"] + gate["drop_dup"] + gate["drop_ocr"] | |
| assert n == read - drops, f"gate arithmetic: kept {n} != read {read} - drops {drops}" | |
| return { | |
| "read": read, | |
| "kept": n, | |
| "drop_short": gate["drop_short"], | |
| "drop_lang": gate["drop_lang"], | |
| "drop_dup": gate["drop_dup"], | |
| "drop_ocr": gate["drop_ocr"], | |
| "chars": sum(len(x) for x in d["text"]), | |
| "tokens": sum(d["token_count"]), | |
| "licenses": {LICENSE: n}, | |
| "authors_with_value": sum(1 for a in d["author"] if a), | |
| "documents_with_created": len(dated), | |
| "created_range": f"{years[0]}-{years[-1]}" if years else "", | |
| "license": LICENSE, | |
| "stats_recomputed_from_parquet": True, | |
| } | |
| def report(rows: list[dict], stats: dict) -> None: | |
| """Aggregate cl100k token stats. (adapted from count_tokens.py)""" | |
| toks = sorted(r["tokens"] for r in rows) | |
| total_tok, total_chars = sum(toks), sum(r["chars"] for r in rows) | |
| def pct(p: float) -> int: | |
| return toks[max(0, min(len(toks) - 1, round(p / 100 * (len(toks) - 1))))] | |
| print("\n" + "=" * 60) | |
| print("NKJP cl100k token statistics") | |
| print("=" * 60) | |
| print(f"Passages kept: {len(rows):,}") | |
| print(f"Total tokens: {total_tok:,}") | |
| print(f"Total characters: {total_chars:,}") | |
| if toks: | |
| print(f"Mean tokens/pass.: {total_tok / len(toks):,.1f}") | |
| print(f"Median / p90 / max: {pct(50):,} / {pct(90):,} / {max(toks):,}") | |
| if total_tok: | |
| print(f"Chars per token: {total_chars / total_tok:.2f}") | |
| if stats.get("created_range"): | |
| print(f"Created range: {stats['created_range']} " | |
| f"({stats['documents_with_created']:,}/{len(rows):,} dated)") | |
| def main() -> int: | |
| ap = argparse.ArgumentParser(description=__doc__) | |
| ap.add_argument("--out", default=".", | |
| help="DynaWord root; shard -> <out>/data/nkjp1m/nkjp1m.parquet") | |
| ap.add_argument("--tmp", default="/tmp", help="Download + extraction dir") | |
| ap.add_argument("--workers", type=int, default=None, help="Process pool size") | |
| ap.add_argument("--added", default=date.today().isoformat(), | |
| help="Value for the 'added' column (default: today)") | |
| args = ap.parse_args() | |
| t0 = time.time() | |
| tmp = Path(args.tmp).expanduser() | |
| root = extract_archive(download(URL, tmp / f"{ROOT_NAME}.tar.gz"), tmp) | |
| files = sorted(str(p) for p in root.rglob("text.xml")) | |
| if not files: | |
| print(f"error: no text.xml under {root}", file=sys.stderr) | |
| return 1 | |
| print(f"Found {len(files)} text.xml files under {root}", flush=True) | |
| read = short = lang = 0 | |
| collected = [] # kept row dicts, in sorted file + passage order (deterministic) | |
| with ProcessPoolExecutor(max_workers=args.workers) as pool: | |
| for i, (kept, st3) in enumerate(pool.map(process_file, files, chunksize=16), 1): | |
| read += st3[0]; short += st3[1]; lang += st3[2] | |
| collected.extend(kept) | |
| if i % 1000 == 0 or i == len(files): | |
| print(f" processed {i}/{len(files)} files, {len(collected):,} kept passages", | |
| file=sys.stderr) | |
| # Exact dedup (sha1), first-wins over the deterministic order above. | |
| seen, rows, drop_dup = set(), [], 0 | |
| for r in collected: | |
| if r["sha1"] in seen: | |
| drop_dup += 1 | |
| continue | |
| seen.add(r["sha1"]) | |
| rows.append(r) | |
| n = len(rows) | |
| out = Path(args.out).expanduser().resolve() / "data" / KEY / f"{KEY}.parquet" | |
| out.parent.mkdir(parents=True, exist_ok=True) | |
| pq.write_table(pa.table({ | |
| "id": [r["id"] for r in rows], | |
| "text": [r["text"] for r in rows], | |
| "source": [KEY] * n, | |
| "added": [args.added] * n, | |
| "created": [r["created"] for r in rows], | |
| "token_count": [r["tokens"] for r in rows], | |
| "license": [LICENSE] * n, | |
| "author": [AUTHOR] * n, | |
| }, schema=SCHEMA), out, compression="zstd") | |
| # DynaWord-style sidecar stats, recomputed from the parquet just written. | |
| gate = {"read": read, "drop_short": short, "drop_lang": lang, | |
| "drop_dup": drop_dup, "drop_ocr": 0} | |
| stats = build_stats(out, gate) | |
| out.with_name(f"{KEY}.stats.json").write_text( | |
| json.dumps(stats, ensure_ascii=False, indent=2) + "\n") | |
| report(rows, stats) | |
| print(f"\nWrote {n:,} passages from {len(files):,} files " | |
| f"(read {read:,}, -short {short:,} -lang {lang:,} -dup {drop_dup:,}) " | |
| f"-> {out} in {round(time.time() - t0)}s", flush=True) | |
| return 0 | |
| if __name__ == "__main__": | |
| raise SystemExit(main()) | |