build_dynaword: preserve_id / preserve_created flags (split from #19)
#45
by PiotrSty - opened
- .gitignore +14 -0
- src/build_dynaword.py +46 -11
- src/test_build_dynaword_flags.py +45 -0
.gitignore
CHANGED
|
@@ -5,3 +5,17 @@ data/european_hplt_pl_500m/
|
|
| 5 |
data/european_hplt_pl_chunk_test*/
|
| 6 |
data/european_hplt_pl_file_test/
|
| 7 |
data/european_hplt_pl_parallel_500m*/
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
data/european_hplt_pl_chunk_test*/
|
| 6 |
data/european_hplt_pl_file_test/
|
| 7 |
data/european_hplt_pl_parallel_500m*/
|
| 8 |
+
__pycache__/
|
| 9 |
+
*.pyc
|
| 10 |
+
# Build inputs and scratch for the studia_bas source: the issue PDF cache, the
|
| 11 |
+
# .jsonl.zst intermediate build_dynaword.py consumes, and one-off probe output.
|
| 12 |
+
studia_bas_pdfs/
|
| 13 |
+
artifacts/studia_bas*.jsonl
|
| 14 |
+
artifacts/studia_bas*.jsonl.zst
|
| 15 |
+
artifacts/studia_bas_download_test/
|
| 16 |
+
artifacts/author_probe.txt
|
| 17 |
+
artifacts/author_new.txt
|
| 18 |
+
artifacts/probe_all.jsonl.zst
|
| 19 |
+
artifacts/download_all.log
|
| 20 |
+
artifacts/studia_bas_pii_audit.md
|
| 21 |
+
artifacts/studia_bas_builder_review.md
|
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, json, os, re, subprocess, sys, time
|
| 20 |
from itertools import islice
|
| 21 |
import multiprocessing as mp
|
| 22 |
from pathlib import Path
|
|
@@ -70,7 +70,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, lines = args
|
| 74 |
kept, texts = [], []
|
| 75 |
st = [0, 0, 0, 0] # read, short, lang, ocr
|
| 76 |
metas = []
|
|
@@ -91,12 +91,18 @@ def _process_chunk(args):
|
|
| 91 |
st[3] += 1; continue
|
| 92 |
texts.append(text)
|
| 93 |
metas.append((
|
|
|
|
|
|
|
| 94 |
_meta_value(row, ("license", "licence", "rights", "edm:rights"), default_license),
|
| 95 |
_meta_value(row, ("author", "authors", "creator", "creators")),
|
|
|
|
| 96 |
))
|
| 97 |
toks = [len(t) for t in _ENC.encode_ordinary_batch(texts, num_threads=1)] if texts else []
|
| 98 |
-
for t, (license_value, author), tk in zip(texts, metas, toks):
|
| 99 |
-
kept.append((
|
|
|
|
|
|
|
|
|
|
| 100 |
return kept, st
|
| 101 |
|
| 102 |
|
|
@@ -118,6 +124,9 @@ def build_source(name, cfg, sl_dir, out_root, pool, seen, counter):
|
|
| 118 |
"licenses": {}, "authors_with_value": 0}
|
| 119 |
t0 = time.time()
|
| 120 |
is_ocr, created = bool(cfg.get("is_ocr")), cfg.get("created", "")
|
|
|
|
|
|
|
|
|
|
| 121 |
default_license = cfg.get("license", "")
|
| 122 |
bid, btext, bcre, btok, blic, baut = [], [], [], [], [], []
|
| 123 |
|
|
@@ -132,18 +141,40 @@ def build_source(name, cfg, sl_dir, out_root, pool, seen, counter):
|
|
| 132 |
], schema=SCHEMA))
|
| 133 |
bid.clear(); btext.clear(); bcre.clear(); btok.clear(); blic.clear(); baut.clear()
|
| 134 |
|
| 135 |
-
proc =
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 139 |
for kept, cst in pool.imap_unordered(_process_chunk, arg_iter, chunksize=1):
|
| 140 |
st["read"] += cst[0]; st["drop_short"] += cst[1]
|
| 141 |
st["drop_lang"] += cst[2]; st["drop_ocr"] += cst[3]
|
| 142 |
-
for text, cre, tok, license_value, author, h in kept:
|
| 143 |
if h in seen:
|
| 144 |
st["drop_dup"] += 1; continue
|
| 145 |
seen.add(h)
|
| 146 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 147 |
btext.append(text); bcre.append(cre); btok.append(tok)
|
| 148 |
blic.append(license_value); baut.append(author)
|
| 149 |
st["chars"] += len(text); st["tokens"] += tok; st["kept"] += 1
|
|
@@ -152,7 +183,11 @@ def build_source(name, cfg, sl_dir, out_root, pool, seen, counter):
|
|
| 152 |
st["authors_with_value"] += 1
|
| 153 |
if len(btext) >= 2000:
|
| 154 |
flush()
|
| 155 |
-
flush(); writer.close();
|
|
|
|
|
|
|
|
|
|
|
|
|
| 156 |
st["secs"] = round(time.time() - t0, 1)
|
| 157 |
print(f" {name}: read {st['read']:,} kept {st['kept']:,} | -short {st['drop_short']:,} "
|
| 158 |
f"-lang {st['drop_lang']:,} -dup {st['drop_dup']:,} -ocr {st['drop_ocr']:,} | "
|
|
|
|
| 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
|
|
|
|
| 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 = []
|
|
|
|
| 91 |
st[3] += 1; continue
|
| 92 |
texts.append(text)
|
| 93 |
metas.append((
|
| 94 |
+
_meta_value(row, ("created", "date", "published", "publication_date"), created)
|
| 95 |
+
if preserve_created else created,
|
| 96 |
_meta_value(row, ("license", "licence", "rights", "edm:rights"), default_license),
|
| 97 |
_meta_value(row, ("author", "authors", "creator", "creators")),
|
| 98 |
+
_meta_value(row, ("id", "record_id")),
|
| 99 |
))
|
| 100 |
toks = [len(t) for t in _ENC.encode_ordinary_batch(texts, num_threads=1)] if texts else []
|
| 101 |
+
for t, (created_value, license_value, author, record_id), tk in zip(texts, metas, toks):
|
| 102 |
+
kept.append((
|
| 103 |
+
t, created_value, tk, license_value, author,
|
| 104 |
+
hashlib.sha1(t.encode("utf-8")).digest(), record_id,
|
| 105 |
+
))
|
| 106 |
return kept, st
|
| 107 |
|
| 108 |
|
|
|
|
| 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()
|
| 130 |
default_license = cfg.get("license", "")
|
| 131 |
bid, btext, bcre, btok, blic, baut = [], [], [], [], [], []
|
| 132 |
|
|
|
|
| 141 |
], schema=SCHEMA))
|
| 142 |
bid.clear(); btext.clear(); bcre.clear(); btok.clear(); blic.clear(); baut.clear()
|
| 143 |
|
| 144 |
+
proc = None
|
| 145 |
+
stream = None
|
| 146 |
+
compressed = None
|
| 147 |
+
executable = shutil.which("zstd")
|
| 148 |
+
if executable:
|
| 149 |
+
proc = subprocess.Popen([executable, "-dc", str(src_path)],
|
| 150 |
+
stdout=subprocess.PIPE, bufsize=1 << 22)
|
| 151 |
+
stream = proc.stdout
|
| 152 |
+
else:
|
| 153 |
+
try:
|
| 154 |
+
import zstandard
|
| 155 |
+
except ImportError as exc:
|
| 156 |
+
raise RuntimeError(
|
| 157 |
+
"reading .zst requires zstd or Python zstandard: pip install zstandard"
|
| 158 |
+
) from exc
|
| 159 |
+
compressed = src_path.open("rb")
|
| 160 |
+
stream = io.TextIOWrapper(
|
| 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]
|
| 168 |
st["drop_lang"] += cst[2]; st["drop_ocr"] += cst[3]
|
| 169 |
+
for text, cre, tok, license_value, author, h, record_id in kept:
|
| 170 |
if h in seen:
|
| 171 |
st["drop_dup"] += 1; continue
|
| 172 |
seen.add(h)
|
| 173 |
+
output_id = record_id if preserve_id and record_id else f"{name}_{counter[0]}"
|
| 174 |
+
if output_id in used_ids:
|
| 175 |
+
raise ValueError(f"duplicate record id in {name}: {output_id}")
|
| 176 |
+
used_ids.add(output_id)
|
| 177 |
+
bid.append(output_id); counter[0] += 1
|
| 178 |
btext.append(text); bcre.append(cre); btok.append(tok)
|
| 179 |
blic.append(license_value); baut.append(author)
|
| 180 |
st["chars"] += len(text); st["tokens"] += tok; st["kept"] += 1
|
|
|
|
| 183 |
st["authors_with_value"] += 1
|
| 184 |
if len(btext) >= 2000:
|
| 185 |
flush()
|
| 186 |
+
flush(); writer.close(); stream.close()
|
| 187 |
+
if compressed is not None:
|
| 188 |
+
compressed.close()
|
| 189 |
+
if proc is not None:
|
| 190 |
+
proc.wait()
|
| 191 |
st["secs"] = round(time.time() - t0, 1)
|
| 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']:,} | "
|
src/test_build_dynaword_flags.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""The per-source opt-in flags studia_bas introduced into the generic builder.
|
| 2 |
+
|
| 3 |
+
These pin that a source without the flags is gated exactly as it was before the
|
| 4 |
+
studia_bas contribution, which matters because several existing sources already
|
| 5 |
+
emit a per-record ``date`` or ``created`` field into their intermediate JSONL.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
import json
|
| 9 |
+
|
| 10 |
+
import pytest
|
| 11 |
+
|
| 12 |
+
from build_dynaword import _init_worker, _process_chunk
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
@pytest.fixture(autouse=True)
|
| 16 |
+
def _encoder():
|
| 17 |
+
# _process_chunk normally runs in a pool worker, where the encoder is a global
|
| 18 |
+
# the initializer sets up.
|
| 19 |
+
_init_worker()
|
| 20 |
+
|
| 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 |
+
|
| 28 |
+
TEXT = "Ustawa o finansach publicznych reguluje zasady gospodarki budżetowej. " * 40
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def test_record_date_is_ignored_unless_the_source_opts_in():
|
| 32 |
+
# sejm_api, govpl, njkp and europeana all carry a per-record date already, so
|
| 33 |
+
# reading it by default would silently rewrite their created column.
|
| 34 |
+
kept = _chunk([{"text": TEXT, "date": "2019-04-01"}], preserve_created=False)
|
| 35 |
+
assert [row[1] for row in kept] == ["2026-07-19"]
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def test_record_date_is_used_when_the_source_opts_in():
|
| 39 |
+
kept = _chunk([{"text": TEXT, "date": "2019-04-01"}], preserve_created=True)
|
| 40 |
+
assert [row[1] for row in kept] == ["2019-04-01"]
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def test_opting_in_still_falls_back_to_the_source_constant():
|
| 44 |
+
kept = _chunk([{"text": TEXT}], preserve_created=True)
|
| 45 |
+
assert [row[1] for row in kept] == ["2026-07-19"]
|