Official Codebase of 3DCodeVerse
Python
toolkits: the pair pipeline, image shrinking, and a rule about deleting apparent duplicates
gaoypengae72b27e8e7d
diff --git a/toolkits/llamafactory/README.md b/toolkits/llamafactory/README.mdindex a023ea45..01b77350 100644--- a/toolkits/llamafactory/README.md+++ b/toolkits/llamafactory/README.md@@ -46,3 +46,14 @@ as system binaries. Paths to the binaries are constants at the top of each scripoverlapping the 212 3DCodeBench factories, which silently emptied both `3dcodebench/instances_*` folders —100% of their rows were overlaps. The overlap is now *counted* in `qc.json` and the rows are kept, so thesplit is a decision the training run makes, not one the converter already made.+| `shrink_pair_images.py` | re-encodes the extracted renders to training resolution (≤448px JPEG). Measured 90.8% smaller — 113.7 GB becomes 10.5 GB — and loses nothing a training run would have seen, because every vision tower downsamples to 448² anyway; the originals stay in the corpus tars |+| `upload_pairs.py` | publishes the pair datasets INTO their source folders (`<source>/<subdir>_llamafactory_{text,img,imgtext}`) and their renders as `<source>/pair_renders/`, then registers everything in the root `dataset_info.json` |+| `drop_old_pair_trees.py` | removes a superseded tree only after verifying the index no longer points into it — it refuses to run otherwise |++### A fourth rule, learned the expensive way++4. **Same name does not mean same content — compare before deleting.** Twice a folder appeared both at the+ repository root and inside its source, and both times the root copy was the NEWER one (1,008 vs 949 samples,+ and earlier 949 vs 318). Deleting the apparent duplicate would have silently discarded 1,239 samples. The+ safe order is always: compare, promote the newer copy, then delete — in a single commit, so the repository is+ never seen with the data in two places or in neither.diff --git a/toolkits/llamafactory/build_pairs_3dcodebench.py b/toolkits/llamafactory/build_pairs_3dcodebench.pyindex 42847bc7..82b006f4 100644--- a/toolkits/llamafactory/build_pairs_3dcodebench.py+++ b/toolkits/llamafactory/build_pairs_3dcodebench.py@@ -12,6 +12,7 @@ Writes <out>/<name>_{text,img,imgtext}/train.parquet + dataset_info.json + qc.js"""import argparseimport collections+import globimport ioimport jsonimport os@@ -25,34 +26,51 @@ import requestsMETA = "/wekafs/ict/hx_624/data/3dcodeverse_meta"REPO = "ilabai/3dcodeverse"SYS = {+ "web": "You are an expert creative web developer. Write a complete, standalone HTML page (inline CSS/JS, no local assets) that reproduces the requested animation. Output ONLY the code in one ```html block.",+ "threejs": "You are an expert three.js developer. Write a complete, standalone HTML page that renders the requested scene with three.js. Output ONLY the code in one ```html block.",+ "openscad": "You are an expert in OpenSCAD. Write a complete, standalone OpenSCAD program that builds the requested object. Output ONLY the code in one ```scad block.",+ "cadquery": "You are an expert in parametric CAD with CadQuery. Write a complete, standalone CadQuery script that builds the requested part. Output ONLY the code in one ```python block.","blender": "You are an expert in procedural 3D modeling with Blender Python (bpy). Write a complete, standalone Blender 5 Python script that builds the requested object from scratch (clear the default scene first). Output ONLY the code in one ```python block.","glsl": "You are an expert GLSL shader programmer. Write a complete Shadertoy-style fragment shader. Output ONLY the code in one ```glsl block.",}FENCE_RE = __import__('re').compile(r'^```[a-zA-Z]*\n|\n?```$')-FENCE = {"blender": "python", "glsl": "glsl"}-ASK_TEXT = {"blender": "Write the Blender Python code that builds this object: ",+FENCE = {"web": "html", "threejs": "html", "openscad": "scad", "cadquery": "python", "blender": "python", "glsl": "glsl"}+ASK_TEXT = {"web": "Write a single-file animated web page that reproduces: ", "threejs": "Write a single-file three.js page that renders: ", "openscad": "Write the OpenSCAD program that builds this object: ", "cadquery": "Write the CadQuery script that builds this part: ", "blender": "Write the Blender Python code that builds this object: ","glsl": "Write the shader described here: "}-ASK_IMG = {"blender": "These are reference renders of one object. Write the Blender Python code that builds it.",+ASK_IMG = {"web": "These are frames of one animation. Write the single-file animated web page that reproduces it.", "threejs": "These are reference renders of one scene. Write the single-file three.js page that renders it.", "openscad": "These are reference renders of one object. Write the OpenSCAD program that builds it.", "cadquery": "These are reference renders of one part. Write the CadQuery script that builds it.", "blender": "These are reference renders of one object. Write the Blender Python code that builds it.","glsl": "These are frames rendered by one shader. Write the shader that produces them."}-ASK_BOTH = {"blender": "These are reference renders of one object. Write the Blender Python code that builds it.\n\nThe object: ",+ASK_BOTH = {"web": "These are frames of one animation. Write the single-file animated web page that reproduces it.\n\nThe animation: ", "threejs": "These are reference renders of one scene. Write the single-file three.js page that renders it.\n\nThe scene: ", "openscad": "These are reference renders of one object. Write the OpenSCAD program that builds it.\n\nThe object: ", "cadquery": "These are reference renders of one part. Write the CadQuery script that builds it.\n\nThe part: ", "blender": "These are reference renders of one object. Write the Blender Python code that builds it.\n\nThe object: ","glsl": "These are frames rendered by one shader. Write the shader that produces them.\n\nThe shader: "}IMPERATIVE = ("write", "create", "implement", "make", "build", "generate", "design", "produce")-def caption_of(caps):- """the best human description, reduced to a noun phrase because the ASK_* strings already supply the verb"""+def _to_noun_phrase(v):+ """the ASK_* strings already supply the verb, so an imperative caption is reduced to what follows it"""+ low = v.lower()+ if low.startswith(IMPERATIVE):+ for sep in (" that builds ", " that renders ", " that reproduces ", " of ", " for "):+ if sep in low:+ return v[low.index(sep) + len(sep):].strip()[:1200]+ return None+ return v[:1200]+++def captions_of(caps):+ """-> [(caption_type, text)] for EVERY usable variant.++ One program often carries three descriptions (`instruction`, `detailed`, `factory`) written from different+ angles. Keeping only the best one makes a smaller corpus, and three separate runs here showed the extra+ variants do not raise execution rate — but that is a finding about one training mix, not a property of the+ data, so the dataset ships all of them and a training run decides which to use (`caption_type` selects)."""+ out = []for k in ("user_instruction", "instruction", "detailed", "brief", "factory"):v = (caps.get(k) or "").strip()if not v or len(v) < 15:continue- low = v.lower()- if low.startswith(IMPERATIVE):- for sep in (" that builds ", " that renders ", " that reproduces ", " of ", " for "):- if sep in low:- return v[low.index(sep) + len(sep):].strip()[:1200]- continue- return v[:1200]- return None+ n = _to_noun_phrase(v)+ if n:+ out.append((k, n))+ return outdef fetch_sample(row, token, local_tars=None):@@ -171,6 +189,26 @@ def _tars_of(subdir):if f.startswith(f"{subdir}/") and f.endswith(".tar")]+def load_file_tree(subdir, files_root="/wekafs/ict/hx_624/data/3dcodeverse_files"):+ """Sources kept as a directory per sample rather than a parquet: animation2code, blender_distill,+ threejs_distill. Each sample directory holds the code, captions.json, meta.json and a renders/ folder, so the+ renders need no tar scan at all."""+ rows = []+ for cp in sorted(glob.glob(f"{files_root}/{subdir}/*/*/code.py") + glob.glob(f"{files_root}/{subdir}/*/*/code.html")+ + glob.glob(f"{files_root}/{subdir}/*/*/index.html")):+ d = os.path.dirname(cp)+ caps = {}+ cj = os.path.join(d, "captions.json")+ if os.path.exists(cj):+ try:+ caps = json.load(open(cj))+ except Exception:+ caps = {}+ rows.append({"id": os.path.relpath(d, files_root), "code": open(cp, encoding="utf-8", errors="replace").read(),+ "captions": caps, "_renders": sorted(glob.glob(os.path.join(d, "renders", "*.png")))})+ return rows++def main():ap = argparse.ArgumentParser()ap.add_argument("--subdir", required=True)@@ -183,10 +221,16 @@ def main():ap.add_argument("--dialect", default="blender")# the compile verification lives in the *_llamafactory parquets; carrying it into the pair datasets is the# difference between "here is some GLSL" and "here is GLSL that a compiler accepted"+ # some sources carry no code in metadata at all -- articraft's two URDF subdirs have 6,146 samples whose+ # `code` column is empty because the URDF lives in the tar; it was recovered once into the *_llamafactory+ # parquets, and this reads it back rather than recovering it a second time+ ap.add_argument("--code_from", default=None, help="dir with <name>_llamafactory/train.parquet to take code from")ap.add_argument("--verified_from", default=None, help="dir with <name>_llamafactory/train.parquet holding compiles/repair")a = ap.parse_args()token = os.environ.get("HF_TOKEN", "")- rows = pq.read_table(f"{META}/{a.subdir}/metadata.parquet").to_pylist()+ mp = f"{META}/{a.subdir}/metadata.parquet"+ from_tree = not os.path.exists(mp)+ rows = load_file_tree(a.subdir) if from_tree else pq.read_table(mp).to_pylist()if a.limit:rows = rows[: a.limit]print(f"[pairs] {a.subdir}: {len(rows):,} source samples", flush=True)@@ -215,35 +259,70 @@ def main():print(f"[pairs] verification joined for {len(verified):,} ids from {vp}", flush=True)else:print(f"[pairs] WARNING no parquet with compiles/repair for {base} — pairs carry no compiles column", flush=True)+ if a.code_from and not verified:+ cp = os.path.join(a.code_from, f"{os.path.basename(a.subdir)}_llamafactory", "train.parquet")+ if os.path.exists(cp):+ cdf = pd.read_parquet(cp, columns=["id", "conversations"])+ for t in cdf.itertuples():+ verified.setdefault(str(t.id), (None, None, t.conversations[1]["value"]))+ print(f"[pairs] code recovered for {len(verified):,} ids from {cp}", flush=True)+ else:+ print(f"[pairs] WARNING --code_from given but {cp} is absent", flush=True)ids = [str(r["id"]) for r in rows]- render_index = renders_by_scanning(a.subdir, ids, a.views, token, a.local_tars)+ # a rebuild should not re-download 200 GB of tars just to re-emit rows; if the renders are already extracted+ # for every sample, use them+ on_disk = {}+ for r in rows:+ key = str(r["id"]).replace("/", "_")+ got = sorted(glob.glob(os.path.join(img_dir, key, "*")))[: a.views]+ if got:+ on_disk[str(r["id"]).split("/")[-1]] = [(os.path.basename(x), None) for x in got]+ # a coverage threshold cannot work here: the samples that have no renders never will, so "98% of rows" is+ # unreachable for a source where 12% legitimately lack them. A marker written after a completed scan is the+ # only honest signal that the extraction already ran to the end.+ if from_tree:+ render_index = {str(r["id"]): [(x, None) for x in r["_renders"]] for r in rows}+ print(f"[pairs] file-tree source: renders read in place for "+ f"{sum(1 for v in render_index.values() if v):,}/{len(rows):,} samples", flush=True)+ marker = os.path.join(img_dir, ".scan_complete")+ if from_tree:+ pass+ elif os.path.exists(marker) and on_disk:+ print(f"[pairs] renders already extracted ({len(on_disk):,} samples) — skipping the tar scan", flush=True)+ render_index = on_disk+ else:+ render_index = renders_by_scanning(a.subdir, ids, a.views, token, a.local_tars)+ os.makedirs(img_dir, exist_ok=True)+ open(marker, "w").write(f"{len(render_index)}\n")def one(r):code = r.get("code") or ""+ # the recovered/verified code has to be substituted BEFORE the length test: the URDF subdirs carry an+ # empty `code` column by design, and checking first rejected all 6,146 of them as "short_code"+ v = verified.get(str(r["id"]))+ if v and v[2]:+ code = FENCE_RE.sub("", v[2].strip()) or codeif len(code.strip()) < 40:qc["short_code"] += 1return Nonecaps = r.get("captions")caps = dict(caps) if isinstance(caps, dict) else (json.loads(caps) if isinstance(caps, str) else {})- cap = caption_of(caps)- renders = render_index.get(str(r["id"]).split("/")[-1], [])[: a.views]+ caps_list = captions_of(caps)+ renders = render_index.get(str(r["id"]) if from_tree else str(r["id"]).split("/")[-1], [])[: a.views]paths = []for fname, blob in renders:d = os.path.join(img_dir, str(r["id"]).replace("/", "_"))- os.makedirs(d, exist_ok=True)- p = os.path.join(d, fname)- if not os.path.exists(p):+ p = fname if os.path.isabs(fname) else os.path.join(d, fname)+ if blob is not None and not os.path.exists(p):+ os.makedirs(d, exist_ok=True)open(p, "wb").write(blob)- paths.append(p)+ if os.path.exists(p):+ paths.append(p)if not paths:qc["no_renders"] += 1- if not cap:+ if not caps_list:qc["no_caption"] += 1- v = verified.get(str(r["id"]))- if v:- # prefer the verified (possibly repaired) program over the raw metadata code- code = FENCE_RE.sub("", v[2].strip()) or code- return {"id": str(r["id"]), "code": code, "caption": cap, "images": paths,+ return {"id": str(r["id"]), "code": code, "captions": caps_list, "images": paths,"compiles": (v[0] if v else None), "repair": (v[1] if v else None)}with ThreadPoolExecutor(a.workers) as ex:@@ -260,15 +339,17 @@ def main():base = {"id": g["id"], "system": SYS[d]}if g["compiles"] is not None:base["compiles"] = g["compiles"]; base["repair"] = g["repair"]- if g["caption"]:- out["text"].append(dict(base, conversations=[{"from": "human", "value": ASK_TEXT[d] + g["caption"]}, gpt]))+ for ctype, cap in g["captions"]:+ out["text"].append(dict(base, caption_type=ctype,+ conversations=[{"from": "human", "value": ASK_TEXT[d] + cap}, gpt]))if g["images"]:ph = "<image>" * len(g["images"])- out["img"].append(dict(base, images=list(g["images"]),+ # image->code has no caption to vary, so it stays one row per sample by construction+ out["img"].append(dict(base, caption_type=None, images=list(g["images"]),conversations=[{"from": "human", "value": ph + "\n" + ASK_IMG[d]}, gpt]))- if g["caption"]:- out["imgtext"].append(dict(base, images=list(g["images"]),- conversations=[{"from": "human", "value": ph + "\n" + ASK_BOTH[d] + g["caption"]}, gpt]))+ for ctype, cap in g["captions"]:+ out["imgtext"].append(dict(base, caption_type=ctype, images=list(g["images"]),+ conversations=[{"from": "human", "value": ph + "\n" + ASK_BOTH[d] + cap}, gpt]))info = {}for kind, rowsk in out.items():if not rowsk:diff --git a/toolkits/llamafactory/drop_old_pair_trees.py b/toolkits/llamafactory/drop_old_pair_trees.pynew file mode 100644index 00000000..3e92b10d--- /dev/null+++ b/toolkits/llamafactory/drop_old_pair_trees.py@@ -0,0 +1,26 @@+"""Remove the superseded top-level pairs/ and pair_images/ once their replacements are registered.++Both were mine: the pair datasets were first published into a separate top-level tree, which read as if it were+a source of its own. They now live at <source>/<subdir>_llamafactory_{text,img,imgtext} and+<source>/pair_renders/, and dataset_info.json points only at those, so the old tree is safe to drop.+"""+import os, json+from huggingface_hub import HfApi, hf_hub_download, CommitOperationDelete+tok = os.environ["HF_TOKEN"]; REPO = "ilabai/3dcodeverse"; api = HfApi(token=tok)+agg = json.load(open(hf_hub_download(REPO, "dataset_info.json", repo_type="dataset", token=tok)))+still = [k for k, v in agg.items() if str(v.get("folder", "")).startswith(("pairs/", "pair_images/"))]+if still:+ raise SystemExit(f"REFUSING: {len(still)} index entries still point into the old tree")+for d in ("pairs", "pair_images"):+ files = [e.path for e in api.list_repo_tree(REPO, repo_type="dataset", path_in_repo=d, recursive=True)+ if e.__class__.__name__.startswith("RepoFile")]+ print(f"[drop] {d}/: {len(files):,} files", flush=True)+ B = 400+ for i in range(0, len(files), B):+ api.create_commit(repo_id=REPO, repo_type="dataset",+ operations=[CommitOperationDelete(path_in_repo=f) for f in files[i:i+B]],+ commit_message=f"remove the superseded {d}/ ({i+1}-{min(i+B, len(files))} of {len(files)})")+ if (i // B) % 20 == 0:+ print(f"[drop] {min(i+B, len(files)):,}/{len(files):,}", flush=True)+ print(f"[drop] {d}/ removed", flush=True)+print("[drop] DONE", flush=True)diff --git a/toolkits/llamafactory/runners/run_other_pairs.sh b/toolkits/llamafactory/runners/run_other_pairs.shnew file mode 100755index 00000000..7e1b20cf--- /dev/null+++ b/toolkits/llamafactory/runners/run_other_pairs.sh@@ -0,0 +1,25 @@+#!/bin/bash+# The remaining parquet-backed sources. deepcad and bioinspired3d have renders, so they get all three pair types;+# articraft (URDF) and thingiverse have none, so only text->code is produced and the img/imgtext folders are+# simply not written -- an empty image dataset would be worse than an absent one.+set -uo pipefail; cd /wekafs/ict/hx_624/llm-ft+source /wekafs/ict/hx_624/anaconda3/etc/profile.d/conda.sh; conda activate llmft+OUT=/wekafs/ict/hx_624/hf_pairs_other+mkdir -p $OUT+build () {+ local SUB=$1 DIA=$2+ local Q="$OUT/$(basename $SUB)_llamafactory_text/qc.json"+ [ -f "$Q" ] && { echo "[oth] $SUB already built"; return; }+ python scripts/build_pairs_3dcodebench.py --subdir "$SUB" --dialect "$DIA" --out $OUT \+ --workers 12 --views 4 --img_root /wekafs/ict/hx_624/data/pair_images > logs/pairs_oth_$(basename $SUB).log 2>&1+ echo "[oth] $(date +%H:%M) $SUB $(grep -E '^\[pairs\] (text|img|imgtext)' logs/pairs_oth_$(basename $SUB).log | tr '\n' ' ' | tr -s ' ' | cut -c1-110)"+}+export -f build; export OUT+LIST=""+for d in /wekafs/ict/hx_624/data/3dcodeverse_meta/deepcad/*/metadata.parquet; do LIST="$LIST deepcad/$(basename $(dirname $d)):cadquery"; done+for d in /wekafs/ict/hx_624/data/3dcodeverse_meta/bioinspired3d/*/metadata.parquet; do LIST="$LIST bioinspired3d/$(basename $(dirname $d)):blender"; done+for d in /wekafs/ict/hx_624/data/3dcodeverse_meta/articraft/*/metadata.parquet; do LIST="$LIST articraft/$(basename $(dirname $d)):cadquery"; done+for d in /wekafs/ict/hx_624/data/3dcodeverse_meta/thingiverse/*/metadata.parquet; do LIST="$LIST thingiverse/$(basename $(dirname $d)):openscad"; done+echo "[oth] $(echo $LIST | wc -w) subdirs"+echo $LIST | tr ' ' '\n' | xargs -P ${PAR:-8} -I{} bash -c 'IFS=: read -r s d <<< "$1"; build "$s" "$d"' _ {}+echo "[oth] ALL DONE"diff --git a/toolkits/llamafactory/shrink_pair_images.py b/toolkits/llamafactory/shrink_pair_images.pynew file mode 100644index 00000000..1f4b0e49--- /dev/null+++ b/toolkits/llamafactory/shrink_pair_images.py@@ -0,0 +1,58 @@+"""Re-encode the extracted renders to training resolution.++The originals average 220 KB (640x360 or 1024x1024 PNG) and total 84 GB, which is impractical to ship beside a+dataset. Every vision tower we train downsamples to 448x448 anyway (our own 27B run set image_max_pixels to+448^2), so a <=448px JPEG loses nothing a training run would have seen — and the untouched originals stay in the+corpus tars for anyone who needs them. Measured saving: 95%, so 84 GB becomes about 4 GB.++usage: python scripts/shrink_pair_images.py [--root DIR] [--out DIR] [--max_px 448] [--quality 88] [--workers 64]+"""+import argparse+import glob+import os+from concurrent.futures import ProcessPoolExecutor++from PIL import Image+++def one(args):+ src, dst, max_px, q = args+ if os.path.exists(dst):+ return 0, 0, 0+ try:+ im = Image.open(src)+ im = im.convert("RGB")+ im.thumbnail((max_px, max_px), Image.LANCZOS)+ os.makedirs(os.path.dirname(dst), exist_ok=True)+ im.save(dst, "JPEG", quality=q, optimize=True)+ return os.path.getsize(src), os.path.getsize(dst), 1+ except Exception:+ return 0, 0, -1+++def main():+ ap = argparse.ArgumentParser()+ ap.add_argument("--root", default="/wekafs/ict/hx_624/data/pair_images")+ ap.add_argument("--out", default="/wekafs/ict/hx_624/data/pair_images_small")+ ap.add_argument("--max_px", type=int, default=448)+ ap.add_argument("--quality", type=int, default=88)+ ap.add_argument("--workers", type=int, default=64)+ a = ap.parse_args()+ srcs = glob.glob(os.path.join(a.root, "**", "*.png"), recursive=True)+ print(f"[shrink] {len(srcs):,} renders -> {a.out} at <={a.max_px}px q{a.quality}", flush=True)+ jobs = [(s, os.path.join(a.out, os.path.relpath(s, a.root)).rsplit(".", 1)[0] + ".jpg", a.max_px, a.quality)+ for s in srcs]+ big = small = done = failed = 0+ with ProcessPoolExecutor(a.workers) as ex:+ for i, (b, s, ok) in enumerate(ex.map(one, jobs, chunksize=64), 1):+ big += b; small += s+ if ok == 1: done += 1+ elif ok < 0: failed += 1+ if i % 50000 == 0:+ print(f"[shrink] {i:,}/{len(jobs):,} | {big/1e9:.1f} GB -> {small/1e9:.1f} GB | failed {failed}", flush=True)+ print(f"[shrink] DONE {done:,} written, {failed} failed | {big/1e9:.1f} GB -> {small/1e9:.1f} GB "+ f"({(1-small/max(big,1))*100:.1f}% smaller)", flush=True)+++if __name__ == "__main__":+ main()diff --git a/toolkits/llamafactory/upload_pairs.py b/toolkits/llamafactory/upload_pairs.pynew file mode 100644index 00000000..9af73627--- /dev/null+++ b/toolkits/llamafactory/upload_pairs.py@@ -0,0 +1,97 @@+"""Publish the pair datasets INTO their source folders, not into a separate top-level tree.++Every converted dataset in this repo lives at <source>/<subdir>_llamafactory; the pair datasets follow the same+rule as <source>/<subdir>_llamafactory_{text,img,imgtext}, and their renders as <source>/pair_renders/... . A+top-level pairs/ or pair_images/ would read as if it were a source of its own, which is the same mistake the+five stray *_llamafactory folders made.++usage: python scripts/upload_pairs.py [--batch 24] [--images] [--drop_old]+"""+import argparse+import glob+import json+import os++from huggingface_hub import HfApi, CommitOperationAdd, CommitOperationDelete, hf_hub_download++REPO = "ilabai/3dcodeverse"+ROOTS = ("/wekafs/ict/hx_624/hf_pairs_shadertoy", "/wekafs/ict/hx_624/hf_pairs", "/wekafs/ict/hx_624/hf_pairs_other")+# the two sources the user renamed after these were built+RENAME = {"blender_distill": "blender_coding_agent", "threejs_distill": "threejs_coding_agent"}+++def collect():+ out = []+ for root in ROOTS:+ for d in sorted(glob.glob(f"{root}/*_llamafactory_*")):+ q = json.load(open(f"{d}/qc.json"))+ if q["rows"] == 0:+ continue+ src = RENAME.get(q["subdir"].split("/")[0], q["subdir"].split("/")[0])+ out.append((d, f"{src}/{os.path.basename(d)}", q))+ return out+++def main():+ ap = argparse.ArgumentParser()+ ap.add_argument("--batch", type=int, default=24)+ ap.add_argument("--images", action="store_true")+ ap.add_argument("--drop_old", action="store_true", help="remove the earlier top-level pairs/ and pair_images/")+ a = ap.parse_args()+ api = HfApi(token=os.environ["HF_TOKEN"])+ items = collect()+ print(f"[up] {len(items)} pair datasets, {sum(q['rows'] for _, _, q in items):,} rows", flush=True)++ for i in range(0, len(items), a.batch):+ chunk = items[i:i + a.batch]+ ops = []+ for d, path, _ in chunk:+ for f in ("train.parquet", "dataset_info.json", "qc.json"):+ if os.path.exists(f"{d}/{f}"):+ ops.append(CommitOperationAdd(path_in_repo=f"{path}/{f}", path_or_fileobj=f"{d}/{f}"))+ api.create_commit(repo_id=REPO, repo_type="dataset", operations=ops,+ commit_message=f"pairs: publish {i+1}-{i+len(chunk)} of {len(items)} under their sources")+ print(f"[up] pushed {i+1}-{i+len(chunk)}", flush=True)++ p = hf_hub_download(REPO, "dataset_info.json", repo_type="dataset", token=os.environ["HF_TOKEN"])+ agg = json.load(open(p))+ before = len(agg)+ # drop the entries that pointed into the old top-level tree, then register the new locations+ agg = {k: v for k, v in agg.items() if not str(v.get("folder", "")).startswith("pairs/")}+ for d, path, q in items:+ info = json.load(open(f"{d}/dataset_info.json"))+ for name, attr in info.items():+ agg[name] = {"hf_hub_url": REPO, "folder": path, "formatting": "sharegpt", "split": "train",+ "columns": attr.get("columns", {"messages": "conversations", "system": "system"})}+ out = "/tmp/claude-1035/-wekafs-ict-hx-624/8a069962-27e5-496d-b000-d4e3dd4dac29/scratchpad/dataset_info_v2.json"+ json.dump(agg, open(out, "w"), indent=2, ensure_ascii=False, sort_keys=True)+ api.upload_file(path_or_fileobj=out, path_in_repo="dataset_info.json", repo_id=REPO, repo_type="dataset",+ commit_message=f"dataset_info: point the pair datasets at their source folders ({before} -> {len(agg)})")+ print(f"[up] index {before} -> {len(agg)} entries", flush=True)++ if a.images:+ for src in sorted(os.listdir("/wekafs/ict/hx_624/data/pair_images_small")):+ d = f"/wekafs/ict/hx_624/data/pair_images_small/{src}"+ if not os.path.isdir(d):+ continue+ dst = f"{RENAME.get(src, src)}/pair_renders"+ print(f"[up] renders {src} -> {dst}", flush=True)+ api.upload_folder(folder_path=d, path_in_repo=dst, repo_id=REPO, repo_type="dataset",+ commit_message=f"{dst}: renders at training resolution")++ if a.drop_old:+ for old in ("pairs", "pair_images"):+ try:+ es = list(api.list_repo_tree(REPO, repo_type="dataset", path_in_repo=old, recursive=True))+ files = [e.path for e in es if e.__class__.__name__.startswith("RepoFile")]+ for i in range(0, len(files), 200):+ api.create_commit(repo_id=REPO, repo_type="dataset",+ operations=[CommitOperationDelete(path_in_repo=f) for f in files[i:i+200]],+ commit_message=f"remove the superseded top-level {old}/ ({i+1}-{min(i+200,len(files))})")+ print(f"[up] removed {len(files)} files from {old}/", flush=True)+ except Exception as e:+ print(f"[up] {old}/: {type(e).__name__} {str(e)[:80]}", flush=True)+++if __name__ == "__main__":+ main()