polish-technical-mega / processing /build_polish_technical_mega_dynaword.py
PiotrSty's picture
Repair v0.3.0: document-disjoint splits, explicit scope, lossless quarantine and rebuilt Slayer packs
aae3233 verified
Raw History Blame Contribute Delete
16.8 kB
"""Build an auditable, document-disjoint technical corpus without replacing old data."""
from __future__ import annotations
import argparse
from collections import Counter, defaultdict
from datetime import date
import hashlib
import json
from pathlib import Path
import re
import shutil
import tiktoken
import pyarrow as pa
import pyarrow.parquet as pq
from technical_corpus_curation import POLICY, assign_groups, balanced_samples, load_metadata
ROOT = Path(__file__).resolve().parents[1]
DATASET = ROOT / "data" / "polish_technical_mega_dynaword_v0_3_0"
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()),
])
INPUTS = (
ROOT / "data" / "polish_cnc_technical_dynaword" / "data",
ROOT / "data" / "polish_cnc_technical_support_dynaword" / "data",
ROOT / "data" / "polish_industrial_maintenance_dynaword" / "data",
ROOT / "data" / "polish_automation_control_dynaword" / "data",
ROOT / "data" / "zpe_cnc_pl_dynaword" / "data",
ROOT / "data" / "polish_source_subset" / "data" / "open_agh_chemistry_pl",
ROOT / "data" / "polish_source_subset" / "data" / "open_icm_pl",
ROOT / "data" / "polish_source_subset" / "data" / "rock_pollub_pl",
ROOT / "data" / "polish_source_subset" / "data" / "wikibooks",
ROOT / "data" / "polish_engineering_new_dynaword" / "data",
)
FORBIDDEN_LICENSE_TERMS = ("noncommercial", "no derivatives", "all rights reserved", "proprietary")
CONTROL_RE = re.compile(r"[\x00-\x08\x0b-\x1f\x7f]")
def norm(text: str) -> str:
return " ".join(text.split()).casefold()
def sha256(text: str) -> str:
return hashlib.sha256(text.encode("utf-8")).hexdigest()
def input_files() -> list[Path]:
return sorted(path for root in INPUTS for path in root.glob("*.parquet"))
def load_records() -> tuple[list[dict], dict, Counter]:
records: list[dict] = []
seen: dict[str, dict] = {}
stats = {"input_files": 0, "input_rows": 0, "duplicate_rows": 0, "forbidden_license_rows": 0, "control_chars_removed": 0}
encoder = tiktoken.get_encoding("cl100k_base")
source_stats: Counter = Counter()
for path in input_files():
stats["input_files"] += 1
table = pq.read_table(path)
for row in table.to_pylist():
stats["input_rows"] += 1
license_name = str(row.get("license") or "")
if any(term in license_name.casefold() for term in FORBIDDEN_LICENSE_TERMS):
raise ValueError(f"Unreviewed restricted licence: {path}: {row['id']}")
text = row.get("text") or ""
cleaned = CONTROL_RE.sub("", text)
stats["control_chars_removed"] += len(text) - len(cleaned)
key = sha256(norm(cleaned))
if key in seen:
stats["duplicate_rows"] += 1
alias = {"id": str(row["id"]), "source": str(row.get("source") or path.parent.name)}
if alias not in seen[key]["_aliases"]:
seen[key]["_aliases"].append(alias)
continue
source = str(row.get("source") or path.parent.name)
record = {
"id": str(row["id"]),
"text": cleaned,
"source": source,
"added": str(row.get("added") or date.today().isoformat()),
"created": str(row.get("created") or ""),
"token_count": len(encoder.encode_ordinary(cleaned)) if cleaned != text else int(row.get("token_count") or 0),
"license": license_name,
"author": str(row.get("author") or ""),
"_text_sha256": key,
"_input_path": str(path.relative_to(ROOT)),
"_aliases": [],
}
records.append(record)
seen[key] = record
source_stats[source] += 1
return records, stats, source_stats
def json_file(path: Path, value: dict) -> None:
path.write_text(json.dumps(value, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
def clean_record(record: dict) -> dict:
return {field.name: record[field.name] for field in SCHEMA}
def assert_baseline(records: list[dict], baseline: Path) -> dict:
original = [row for path in sorted((baseline / "data").glob("*.parquet")) for row in pq.read_table(path).to_pylist()]
fingerprints = lambda rows: {(row["id"], row["source"], sha256(row["text"])) for row in rows}
current, previous = fingerprints(records), fingerprints(original)
if not previous or current != previous:
raise ValueError(f"Inputs changed from the audited baseline: added={len(current - previous)}, missing={len(previous - current)}")
return {"records": len(original), "id_source_text_sha256_preserved": True}
def write_dataset(records: list[dict], stats: dict, metadata: dict, policy: dict, output: Path, baseline_check: dict) -> dict:
# Exclusive creation protects the previous corpus, packs and unrelated files.
output.mkdir(parents=True, exist_ok=False)
for folder in ("data", "samples", "provenance", "licenses", "quarantine", "processing"):
(output / folder).mkdir()
assign_groups(records, metadata, policy)
split_records: dict[str, list[dict]] = defaultdict(list)
for record in records:
split_records[record["_split"]].append(record)
sample_manifest = {"schema": SCHEMA.names, "max_rows": 32, "method": "Round robin across sources, distinct document groups first", "splits": {}}
split_manifest = {}
for split in ("train", "valid", "test", "quarantine"):
rows = sorted(split_records[split], key=lambda item: item["id"])
path = output / "quarantine/records.parquet" if split == "quarantine" else output / "data" / f"{'validation' if split == 'valid' else split}.parquet"
pq.write_table(pa.Table.from_pylist([clean_record(row) for row in rows], schema=SCHEMA), path, compression="zstd")
split_manifest[split] = {
"documents": len(rows), "document_groups": len({row["_group_id"] for row in rows}),
"tokens": sum(row["token_count"] for row in rows),
"sources": dict(sorted(Counter(row["source"] for row in rows).items())),
}
if split != "quarantine":
samples = balanced_samples(rows)
(output / "samples" / f"{split}.jsonl").write_text(
"".join(json.dumps(clean_record(row), ensure_ascii=False) + "\n" for row in samples), encoding="utf-8"
)
sample_manifest["splits"][split] = {"rows": len(samples), "sources": sorted({row["source"] for row in samples})}
provenance = []
used_metadata = set()
for record in sorted(records, key=lambda item: item["id"]):
identities = [record, *record["_aliases"]]
used_metadata.update(item["id"] for item in identities)
text = record["text"]
provenance.append({
"id": record["id"], "source": record["source"], "input_path": record["_input_path"],
"text_sha256": record["_text_sha256"], "raw_text_sha256": sha256(text),
"license": record["license"], "author": record["author"], "created": record["created"],
"token_count": record["token_count"], "split": record["_split"],
"group_id": record["_group_id"], "group_aliases": record["_group_keys"],
"duplicate_input_identities": record["_aliases"], "exclusion_reasons": record["_exclusion_reasons"],
"quality_flags": [name for name, present in (
("unicode_replacement_character", "\ufffd" in text),
("private_use_glyphs", any("\ue000" <= character <= "\uf8ff" for character in text)),
) if present],
})
(output / "provenance/records.jsonl").write_text(
"".join(json.dumps(item, ensure_ascii=False) + "\n" for item in provenance), encoding="utf-8"
)
(output / "provenance/source_metadata.jsonl").write_text(
"".join(json.dumps({"id": identity, "metadata": metadata[identity]}, ensure_ascii=False) + "\n" for identity in sorted(used_metadata)), encoding="utf-8"
)
active = [row for row in records if row["_split"] != "quarantine"]
quarantine = split_records["quarantine"]
reasons = Counter(reason for row in quarantine for reason in row["_exclusion_reasons"])
manifest = {
"dataset": "Polish technical mega DynaWord", "version": policy["version"], "language": ["pl"],
"schema": SCHEMA.names, "base_hub_revision": policy["base_hub_revision"],
"layout": {"train": "data/train.parquet", "valid": "data/validation.parquet", "test": "data/test.parquet", "quarantine": "quarantine/records.parquet"},
"scope": policy["selected_scope"], "proxy_tokenizer": "cl100k_base",
"documents": len(active), "tokens": sum(row["token_count"] for row in active),
"sources": {source: {"documents": count} for source, count in sorted(Counter(row["source"] for row in active).items())},
"splits": {split: split_manifest[split] for split in ("train", "valid", "test")},
"quarantine": {**split_manifest["quarantine"], "reasons": dict(sorted(reasons.items()))},
"conservation": {**baseline_check, "retained_records": len(active), "quarantined_records": len(quarantine)},
"deduplication": "Exact whitespace-normalized casefolded text; duplicate provenance aliases join the same group.",
"split_policy": "SHA256 of canonical document/book alias component; <5 test, <10 valid, otherwise train. Biblioteka uses original numeric article-ID seeds.",
"source_policy": "Original attribution and per-record licences preserved; no blanket relicensing. Metadata labels are not independent legal clearance.",
"limitations": ["Near-duplicate and semantic overlap are not ruled out.", "Source facts and all OCR text have not been manually validated.", "Existing model pretraining contamination is not ruled out."],
**stats,
}
json_file(output / "manifest.json", manifest)
json_file(output / "samples/manifest.json", sample_manifest)
json_file(output / "quarantine/manifest.json", manifest["quarantine"])
json_file(output / "provenance/build_report.json", {"base_hub_revision": policy["base_hub_revision"], **baseline_check, **stats, "retained_records": len(active), "quarantined_records": len(quarantine), "exclusion_reasons": dict(reasons), "quality_flags": dict(Counter(flag for item in provenance for flag in item["quality_flags"]))})
json_file(output / "processing/technical_mega_curation_policy.json", policy)
for name in ("build_polish_technical_mega_dynaword.py", "technical_corpus_curation.py", "pack_cnc_slayer.py", "validate_cnc_dynaword.py", "validate_technical_mega.py"):
shutil.copy2(Path(__file__).with_name(name), output / "processing" / name)
(output / "licenses/SOURCES.md").write_text(
"# Source and licence policy\n\nEach row preserves its original licence and author. "
"`provenance/source_metadata.jsonl` preserves source URLs, attribution, book memberships and available checksums. "
"Join by record ID, including duplicate identities recorded in `provenance/records.jsonl`. "
"Follow each original licence, including attribution/share-alike requirements. No blanket relicensing or independent rights clearance is claimed.\n\n"
"Historical scans, out-of-scope books and a verified damaged article are preserved in `quarantine/records.parquet`; they are not default training data. "
"Per-record exclusions and quality flags are in provenance. Missing OCR words are never guessed.\n", encoding="utf-8"
)
(output / "README.md").write_text(
"---\nlicense: other\nlicense_name: per-record\nlanguage:\n- pl\npretty_name: Polish technical mega DynaWord\n"
"task_categories:\n- text-generation\nlibrary_name: datasets\nsize_categories:\n- 10K<n<100K\ntags:\n- polish\n- technical\n- cnc\n- automation\n- dynaword\nconfigs:\n- config_name: default\n data_files:\n - split: train\n path: data/train.parquet\n - split: validation\n path: data/validation.parquet\n - split: test\n path: data/test.parquet\n---\n\n"
"# Polish technical mega DynaWord — repaired v0.3.0\n\n"
"Polski korpus techniki i nauk ścisłych: przemysł, CNC, automatyka, informatyka, matematyka, fizyka i chemia. "
"To teksty dokumentów, nie zbiór instrukcji do chatbota ani zatwierdzone procedury obsługi maszyn.\n\n"
"## What changed\n\n"
"Chunks of one article/book now share one split. Shared PDF checksums, alternate source identities, ZPE page IDs and overlapping AGH book memberships are joined transitively. "
"Wikibooks selection is an explicit review of book titles, not keyword deletion inside chapters. "
"Out-of-scope content, historical technical scans and verified damaged article 103741 are preserved in quarantine with reasons. "
"Text is not rewritten or completed by a language model. Samples cover source families rather than just the first alphabetic source.\n\n"
f"Baseline revision: `{policy['base_hub_revision']}`. All {len(records):,} original unique records remain accounted for: "
f"**{len(active):,} retained**, **{len(quarantine):,} quarantined**. "
"The previous revision remains available in repository history and under `pre-repair-0.3.0`.\n\n"
"| Split | Text chunks | Document/book groups | Proxy tokens (`cl100k_base`) |\n|---|---:|---:|---:|\n"
+ "\n".join(f"| {split} | {value['documents']} | {value['document_groups']} | {value['tokens']} |" for split, value in split_manifest.items())
+ "\n\n## Files and reproducibility\n\n"
"`data/*.parquet` keeps the eight-column DynaWord schema. The explicit default config excludes quarantine. "
"`provenance/records.jsonl` maps every retained/quarantined record to a document group, content hashes, aliases, exclusion reasons and quality flags. "
"`provenance/source_metadata.jsonl` preserves original attribution. `processing/` contains the builder, explicit curation policy, packer and validators; "
"rebuilding requires the original local source layers/metadata referenced by the builder, which are not all standalone Hub datasets. "
"The published validation report checks the delivered artifacts without downloading original PDFs.\n\n"
"`slayer_v6/` contains freshly regenerated little-endian uint16 native Slayer tokens, EOS 0 after each chunk and uint64 end offsets; see its manifest for exact token counts and tokenizer SHA256. "
"`manifest.json` counts are **proxy tokens**, not native Slayer token counts.\n\n"
"## Limits and training use\n\n"
"Group-disjoint splitting prevents the identified document/chunk leakage, not every near-duplicate, semantic overlap or pretraining contamination. "
"All source text has not received expert factual/OCR review; remaining Unicode quality flags are explicit. Historical text is not current operating guidance. "
"Licence metadata is retained, not independently cleared. Observe original attribution/share-alike terms.\n\n"
"**Do not compare old and new validation curves as if the holdout were unchanged.** "
"Do not reuse old dataloader offsets with these regenerated packs. A model already trained on old held-out material does not regain an unseen test set through repartitioning.\n",
encoding="utf-8",
)
return manifest
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--output", type=Path, default=DATASET)
parser.add_argument("--baseline", type=Path, default=ROOT / "data/polish_technical_mega_dynaword")
parser.add_argument("--policy", type=Path, default=POLICY)
args = parser.parse_args()
if args.output.exists():
raise FileExistsError(f"Refusing to overwrite existing output: {args.output}")
policy = json.loads(args.policy.read_text(encoding="utf-8"))
records, stats, _ = load_records()
baseline_check = assert_baseline(records, args.baseline)
metadata = load_metadata(ROOT / "data")
manifest = write_dataset(records, stats, metadata, policy, args.output, baseline_check)
from pack_cnc_slayer import pack
pack(args.output, args.output / "slayer_v6", ROOT / "models/Slayer1B-1.06/tokenizer.json", "PiotrSty/polish-technical-mega-dynaword")
print(json.dumps({"output": str(args.output), "documents": manifest["documents"], "quarantine": manifest["quarantine"]["documents"], "splits": manifest["splits"]}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()