#!/usr/bin/env python3 """Pack curated ds/ artifacts into Hugging Face-ready staging folders. Usage: .venv-hf/bin/python scripts/hf_pack.py [--out hf-staging] [--only REPO ...] Each repo folder is self-contained (README.md card + data). Large JSONL is converted to zstd parquet shards; nested fields become JSON strings so the schema is stable. Model files / small files are hard-linked (no extra disk). Writes /pack_report.json with row counts and sha256 checks. """ from __future__ import annotations import argparse import hashlib import json import os import shutil from pathlib import Path import pyarrow as pa import pyarrow.parquet as pq import re DS = Path(__file__).resolve().parents[1] SHARD_BYTES = 400 * 1024 * 1024 # approx uncompressed text per shard CARDS = DS / "scripts/hf_cards" # --- secrets must never reach a (public) repo: redact in published copies SECRET_RE = re.compile(r"(sk-proj-[A-Za-z0-9_-]{20,}|sk-[A-Za-z0-9]{20,}|hf_[A-Za-z0-9]{30,}|ghp_[A-Za-z0-9]{20,}|AKIA[0-9A-Z]{16})") TEXT_SUFFIX = {".py", ".md", ".json", ".txt", ".sh", ".yaml", ".yml", ".jsonl", ".org", ".log", ".csv", ".toml", ".cfg"} REDACTED: list[str] = [] # --- per-document licenses (see scripts/hf_cards/LICENSES) CBETA_IDS = set((CARDS / "kanripo_cbeta_ids.txt").read_text().split()) SOURCE_LICENSE = {"ndl": "pdm-1.0", "kanripo": "cc-by-sa-4.0", "minhon": "cc-by-sa-4.0", "wikisource": "cc-by-sa-4.0"} def license_for(source: str, kanripo_work: str | None = None) -> str: if source == "kanripo" and kanripo_work in CBETA_IDS: return "cc-by-nc-sa-3.0-tw" return SOURCE_LICENSE[source] # ---------------------------------------------------------------- helpers def link(src: Path, dst: Path) -> None: dst.parent.mkdir(parents=True, exist_ok=True) if dst.exists(): dst.unlink() if src.suffix.lower() in TEXT_SUFFIX and src.stat().st_size < 20_000_000: txt = src.read_text(encoding="utf-8", errors="surrogateescape") if SECRET_RE.search(txt): dst.write_text(SECRET_RE.sub("", txt), encoding="utf-8", errors="surrogateescape") REDACTED.append(str(src.relative_to(DS))) return try: os.link(src, dst) except OSError: shutil.copy2(src, dst) def link_tree(src: Path, dst: Path, skip=("__pycache__", ".lock")) -> int: n = 0 for p in sorted(src.rglob("*")): if p.is_file() and not any(s in p.parts or p.name == s for s in skip): link(p, dst / p.relative_to(src)) n += 1 return n def iter_jsonl(path: Path): with path.open("r", encoding="utf-8") as f: for line in f: if line.strip(): yield json.loads(line) def infer_types(rows_iter) -> dict[str, str]: """key -> 'int'|'float'|'bool'|'str'|'json' (union over all rows).""" kinds: dict[str, set] = {} for r in rows_iter: for k, v in r.items(): s = kinds.setdefault(k, set()) if v is None: continue if isinstance(v, bool): s.add("bool") elif isinstance(v, int): s.add("int") elif isinstance(v, float): s.add("float") elif isinstance(v, str): s.add("str") else: s.add("json") out = {} for k, s in kinds.items(): if not s or s == {"str"}: out[k] = "str" elif s == {"int"}: out[k] = "int" elif s <= {"int", "float"}: out[k] = "float" elif s == {"bool"}: out[k] = "bool" else: out[k] = "json" # mixed or nested -> JSON string return out PA = {"int": pa.int64(), "float": pa.float64(), "bool": pa.bool_(), "str": pa.string(), "json": pa.string()} def coerce(v, t): if v is None: return None if t == "json": return json.dumps(v, ensure_ascii=False) if t == "float": return float(v) return v class ShardWriter: def __init__(self, outdir: Path, prefix: str, types: dict[str, str]): self.outdir, self.prefix, self.types = outdir, prefix, types self.schema = pa.schema([(k, PA[t]) for k, t in types.items()]) self.buf: list[dict] = [] self.bytes = 0 self.files: list[Path] = [] self.rows = 0 outdir.mkdir(parents=True, exist_ok=True) def add(self, row: dict): self.buf.append({k: coerce(row.get(k), t) for k, t in self.types.items()}) self.bytes += len(row.get("text") or "") * 3 + 512 if self.bytes >= SHARD_BYTES: self.flush() def flush(self): if not self.buf: return p = self.outdir / f"{self.prefix}-{len(self.files):05d}.parquet" tbl = pa.Table.from_pylist(self.buf, schema=self.schema) pq.write_table(tbl, p, compression="zstd", compression_level=9, row_group_size=2000) self.files.append(p) self.rows += len(self.buf) self.buf, self.bytes = [], 0 def close(self): self.flush() # rename to HF shard convention prefix-00000-of-0000N.parquet n = len(self.files) final = [] for i, p in enumerate(self.files): q = p.with_name(f"{self.prefix}-{i:05d}-of-{n:05d}.parquet") p.rename(q) final.append(q) self.files = final return self.rows def jsonl_to_parquet(src: Path, outdir: Path, prefix: str, transform=None) -> dict: tf = transform or (lambda r: r) types = infer_types(tf(r) for r in iter_jsonl(src)) w = ShardWriter(outdir, prefix, types) h = hashlib.sha256() n_src = 0 for r in iter_jsonl(src): n_src += 1 r = tf(r) h.update((r.get("text") or "").encode()) w.add(r) w.close() return {"source": str(src.relative_to(DS)), "rows_source": n_src, "rows_written": w.rows, "text_concat_sha256": h.hexdigest(), "files": [p.name for p in w.files], "types": types} def verify_parquet(files: list[Path], expect_rows: int, expect_sha: str) -> dict: h = hashlib.sha256() n = 0 for p in sorted(files): pf = pq.ParquetFile(p) has_text = "text" in pf.schema_arrow.names for rg in range(pf.num_row_groups): t = pf.read_row_group(rg, columns=["text"] if has_text else None) n += t.num_rows if has_text: for s in t.column("text").to_pylist(): h.update((s or "").encode()) ok = n == expect_rows and (h.hexdigest() == expect_sha) return {"rows_readback": n, "text_sha_match": h.hexdigest() == expect_sha, "ok": ok} def write(path: Path, text: str): path.parent.mkdir(parents=True, exist_ok=True) path.write_text(text, encoding="utf-8") # ---------------------------------------------------------------- repos def pack_pretrain(out: Path) -> dict: """unified/pretrain-v1/build-003 joined with split assignment (build-006).""" src = DS / "unified/pretrain-v1/build-003/pretrain.jsonl" spl = DS / "unified/training-tokens-v1/build-006/splits.jsonl" split_of = {} for r in iter_jsonl(spl): split_of[r["id"]] = {k: r[k] for k in ("split", "era", "era_basis", "group", "tokens")} keep = ["id", "source", "title", "era", "era_basis", "group", "split", "tokens", "normalized_chars", "date_status", "script_profile", "license_status", "source_document_id", "work_candidate_id", "unit_type", "unit_label", "license", "text_sha256", "text"] def tf(r): s = split_of[r["id"]] row = {**r, **s} meta = {k: v for k, v in r.items() if k not in keep} o = {k: row.get(k) for k in keep} o["license"] = license_for(r["source"], r["id"].split("/")[1] if r["source"] == "kanripo" else None) o["metadata"] = json.dumps(meta, ensure_ascii=False) return o types = {k: "str" for k in keep} | {"tokens": "int", "normalized_chars": "int", "metadata": "str"} writers = {s: ShardWriter(out / "data", s, types) for s in ("train", "validation", "test")} shas = {s: hashlib.sha256() for s in writers} counts = {s: 0 for s in writers} lic_counts: dict = {} tokens = {s: 0 for s in writers} n = 0 for r in iter_jsonl(src): n += 1 o = tf(r) s = o["split"] writers[s].add(o) shas[s].update(o["text"].encode()) counts[s] += 1 tokens[s] += o["tokens"] k = (o["source"], o["license"]) lic_counts[k] = [lic_counts.get(k, [0, 0])[0] + 1, lic_counts.get(k, [0, 0])[1] + o["tokens"]] rep = {"rows_source": n, "rows_split_file": len(split_of), "splits": {}, "license_docs_tokens": {f"{a}|{b}": v for (a, b), v in sorted(lic_counts.items())}} for s, w in writers.items(): w.close() rep["splits"][s] = {"rows": counts[s], "tokens_no_bos_eos": tokens[s], "files": [p.name for p in w.files], **verify_parquet(w.files, counts[s], shas[s].hexdigest())} # provenance files for rel in ["unified/current_pretraining.json"]: link(DS / rel, out / "meta" / Path(rel).name) for d, names in { "unified/pretrain-v1/build-003": ["manifest.json", "report.json", "verification.json", "excluded.jsonl"], "unified/split-groups-v1/build-003": ["manifest.json", "report.json", "groups.json", "joins.jsonl"], "unified/training-tokens-v1/build-006": ["manifest.json", "report.json", "REPORT.md", "verification.json", "evaluation-windows.jsonl", "group-joins.jsonl"], }.items(): for nm in names: link(DS / d / nm, out / "meta" / d.replace("/", "__") / nm) link_tree(DS / "scripts", out / "code/scripts", skip=("__pycache__",)) link_tree(DS / "worklog", out / "code/worklog") for nm in ["README.md", "agent.md", "ndl_download.py"]: link(DS / nm, out / "code" / nm) return rep def pack_sources(out: Path) -> dict: rep = {} jobs = { "ndl": DS / "corpus/preprocessed-v1/build-001/documents.jsonl", "kanripo": DS / "kanripo/preprocessed-v1/build-002/documents.jsonl", "minhon": DS / "minhon/preprocessed-v1/build-003-bibdated/clean_pages.jsonl", "wikisource": DS / "wikisource/corpus-v1/documents.jsonl", "wikisource_works": DS / "wikisource/corpus-v1/works.jsonl", "ndl_catalog": DS / "corpus/metadata/selected_before_1868.jsonl", "ndl_api_catalog": DS / "corpus/metadata/api_selected_before_1868.jsonl", } tfs = { "ndl": lambda r: {**r, "license": license_for("ndl")}, "kanripo": lambda r: {**r, "license": license_for("kanripo", r["work_id"])}, "minhon": lambda r: {**r, "license": license_for("minhon")}, "wikisource": lambda r: {**r, "license": license_for("wikisource")}, "wikisource_works": lambda r: {**r, "license": license_for("wikisource")}, } for name, src in jobs.items(): r = jsonl_to_parquet(src, out / "data" / name, "train", transform=tfs.get(name)) r.update(verify_parquet([out / "data" / name / f for f in r["files"]], r["rows_source"], r["text_concat_sha256"])) rep[name] = r # per-PID NDL API bibliographic JSON (31k small files) -> one parquet rows = [] for p in sorted((DS / "corpus/metadata").glob("*.json")): rows.append({"pid": p.stem, "json": p.read_text(encoding="utf-8")}) d = out / "data/ndl_api_bibliography" d.mkdir(parents=True, exist_ok=True) pq.write_table(pa.Table.from_pylist(rows), d / "train-00000-of-00001.parquet", compression="zstd") rep["ndl_api_bibliography"] = {"rows": len(rows)} # side files per source build (manifests, reports, edits, exclusions) for d, names in { "corpus/preprocessed-v1/build-001": ["manifest.json", "report.json", "verification.json", "output_verification.json", "excluded.jsonl", "edits.jsonl"], "kanripo/preprocessed-v1/build-002": ["manifest.json", "report.json", "verification.json", "excluded.jsonl", "duplicates.jsonl", "edits.jsonl", "files.jsonl"], "minhon/preprocessed-v1/build-003-bibdated": ["README.md", "manifest.json", "report.json", "verification.json", "date_evidence.jsonl", "documents.csv", "included_documents.csv", "excluded_documents.csv"], "wikisource/corpus-v1": ["report.json", "duplicates.jsonl"], }.items(): for nm in names: link(DS / d / nm, out / "meta" / d.replace("/", "__") / nm) link(DS / "corpus/metadata/dataset_202602_k_internet.zip", out / "meta/ndl/dataset_202602_k_internet.zip") link_tree(DS / "kanripo/metadata", out / "meta/kanripo/metadata") link_tree(DS / "minhon/title-lists", out / "meta/minhon/title-lists") link_tree(DS / "wikisource/metadata", out / "meta/wikisource/metadata") for nm in ["pids_before_1868.txt", "pids_api_before_1868.txt"]: link(DS / nm, out / "meta/ndl" / nm) for nm in ["oncoj.csv", "lexicon.xml"]: link(DS / nm, out / "extras" / nm) return rep def pack_sft(out: Path) -> dict: exp = DS / "unified/sft-dialogue-v1/build-openai-001/exports/002" by_split: dict[str, list[str]] = {} for line in (exp / "dialogues.jsonl").read_text(encoding="utf-8").splitlines(): if line.strip(): by_split.setdefault(json.loads(line).get("split", "train"), []).append(line) for s, lines in by_split.items(): write(out / "data" / f"{s}.jsonl", "\n".join(lines) + "\n") for p in exp.iterdir(): if p.name != "dialogues.jsonl": link(p, out / "meta/export-002" / p.name) b = DS / "unified/sft-dialogue-v1/build-openai-001" for nm in ["SUMMARY.md", "manifest.json", "coverage-verification.json"]: link(b / nm, out / "meta" / nm) link_tree(DS / "unified/evaluation-tasks-v1/validation-001", out / "evaluation-tasks") return {"splits": {s: len(v) for s, v in by_split.items()}} def pack_model(src: Path, out: Path, extra: dict[str, Path] | None = None, skip=("__pycache__", ".lock")) -> dict: n = link_tree(src, out, skip=skip) for nm, p in (extra or {}).items(): link(p, out / nm) return {"files": n + len(extra or {})} REPOS = { "classical-ja-pretrain": ("dataset", pack_pretrain), "classical-ja-sources": ("dataset", pack_sources), "classical-ja-sft-dialogue": ("dataset", pack_sft), "classical-ja-tokenizer": ("model", lambda o: pack_model( DS / "unified/tokenizer-v1/build-001", o, {"classical_tokenizer.py": DS / "runs/classical-smollm2-trunk/export/classical_tokenizer.py", "tokenizer_config.json": DS / "runs/classical-smollm2-trunk/export/tokenizer_config.json"}, skip=("__pycache__", ".lock", "train.txt"))), "classical-smollm2-trunk": ("model", lambda o: pack_model( DS / "runs/classical-smollm2-trunk/export", o, {"metrics.jsonl": DS / "runs/classical-smollm2-trunk/metrics.jsonl", "run.json": DS / "runs/classical-smollm2-trunk/run.json", "status.json": DS / "runs/classical-smollm2-trunk/status.json"})), "classical-smollm2-sft": ("model", lambda o: pack_model( DS / "runs/classical-sft-confidence2-001/checkpoint-000090", o, {"SUMMARY.md": DS / "runs/classical-sft-confidence2-001/SUMMARY.md", "best.json": DS / "runs/classical-sft-confidence2-001/best.json", "metrics.jsonl": DS / "runs/classical-sft-confidence2-001/metrics.jsonl", "training_config.json": DS / "runs/classical-sft-confidence2-001/config.json"})), } def main(): ap = argparse.ArgumentParser() ap.add_argument("--out", default=str(DS / "hf-staging")) ap.add_argument("--only", nargs="*") a = ap.parse_args() for name, (kind, fn) in REPOS.items(): if a.only and name not in a.only: continue out = Path(a.out) / name if out.exists(): shutil.rmtree(out) out.mkdir(parents=True) print(f"[pack] {name}", flush=True) rep = {"repo": name, "type": kind, **fn(out)} card = CARDS / f"{name}.md" if card.exists(): link(card, out / "README.md") if kind == "dataset": link_tree(CARDS / "LICENSES", out / "LICENSES") else: link(CARDS / "APACHE-2.0.txt", out / "LICENSE") rep["redacted_files"] = sorted(set(REDACTED)); REDACTED.clear() write(out / "pack_report.json", json.dumps(rep, ensure_ascii=False, indent=2)) print(json.dumps(rep, ensure_ascii=False)[:2000], flush=True) if __name__ == "__main__": main()