"""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 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()