Datasets:
ArXiv:
License:
Tools and the ImageNet-21k card for the released repository; datasets.json under the new name
787d9b7 verified Download tools/openembed_data/build.py from UCSC-VLAA/OpenEmbed-Data: direct link, hf CLI and curl.
- Browser
- Download file 16.3 kB
-
https://huggingface.co/datasets/UCSC-VLAA/OpenEmbed-Data/resolve/main/tools/openembed_data/build.py
- Command line
-
hf download hf://datasets/UCSC-VLAA/OpenEmbed-Data/tools/openembed_data/build.py
-
curl -L -o build.py https://huggingface.co/datasets/UCSC-VLAA/OpenEmbed-Data/resolve/main/tools/openembed_data/build.py
16.3 kB
| #!/usr/bin/env python3 | |
| """One entry point for rebuilding the OpenEmbed training data from this repository. | |
| It reads datasets.json next to this script, the index of every dataset folder: its loader, what it needs and how | |
| large it is. For each dataset asked for, it runs that dataset's own loader with the same command its README gives, | |
| then prints one line per dataset and writes a summary. | |
| python tools/openembed_data/build.py list [--sets ...] [--json] | |
| python tools/openembed_data/build.py fetch --sets ... [--teacher] | |
| python tools/openembed_data/build.py rebuild --sets ... --out shards/ [--cache cache/] [--procs N] [--no-write] | |
| [--shards NAME,...] [--timm-dir DIR] [--fetch] [--dry-run] | |
| --sets takes dataset ids (mmeb/GQA), folders (vqa/mmeb-gqa), a folder's last part (mmeb-gqa), categories (vqa), or | |
| "all", separated by commas. Run it from the folder that holds tools/ and the dataset folders: the repository root, | |
| or the folder hf download filled (see "Getting the files" in the repository README). `fetch` downloads the folders | |
| of the datasets asked for, and tools/ (needs huggingface_hub). | |
| Dress-ED (editing/dressed/) carries the shards the training read: for it, rebuild checks each shard against its | |
| MANIFEST.json and links or copies it into --out. | |
| Under --out, each dataset's shards go to <folder>/. Logs and problem lists go to _build/: <folder, / as __>.log, | |
| .problems.jsonl and .report.json (when the loader writes one). _build/summary.json sums up the run. Each dataset ends | |
| in one of these results: | |
| pass the loader rebuilt every record and its checks hold. Exact sets: every sha256, md5 and crc32c is as | |
| published. Approximate sets: every record rebuilt, with the images re-encoded from the source. | |
| incomplete records were left out; each one is listed in its .problems.jsonl (a source image missing or changed, ...) | |
| failed the loader stopped; see its .log | |
| needs a prerequisite is missing: the dataset's folder, a login, an archive to put into the cache by hand, a | |
| package | |
| not here a folder of identifiers only (none since 2026-11-18, when DocBank became a regular folder) | |
| The exit status is 1 unless every dataset asked for passed (a "not here" dataset does not count against it), and 2 | |
| when packages are missing. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import ast | |
| import json | |
| import os | |
| import re | |
| import subprocess | |
| import sys | |
| import time | |
| HERE = os.path.dirname(os.path.abspath(__file__)) | |
| LOADER = { | |
| "rebuild_shards": ("tools", "openembed_data", "rebuild_shards.py"), | |
| "rebuild_edit": ("tools", "openembed_data", "rebuild_edit.py"), | |
| "mmeb_train": ("tools", "mmeb_train", "rebuild_shards.py"), | |
| "imagenet21k": ("classification", "imagenet-21k", "tools", "loader.py"), | |
| "shipped_shards": ("tools", "openembed_data", "copy_shards.py"), # 2026-11-19: Dress-ED carries its shards | |
| } | |
| IMPORT_NAME = {"pyarrow": "pyarrow", "huggingface_hub": "huggingface_hub", "crc32c": "crc32c", "Pillow": "PIL", | |
| "av": "av", "numpy": "numpy"} | |
| OPTIONAL = {"crc32c"} # the loaders fall back to a slower CRC-32C | |
| def load_index(path=None): | |
| return json.load(open(path or os.path.join(HERE, "datasets.json"), encoding="utf-8")) | |
| def select(index, spec): | |
| ds = index["datasets"] | |
| if not spec or spec == "all": | |
| return list(ds) | |
| out, unknown = [], [] | |
| for w in (x.strip() for x in spec.split(",") if x.strip()): | |
| hit = [e for e in ds if w in (e["dataset_id"], e["folder"], e["folder"].split("/", 1)[1], e["category"])] | |
| if not hit: | |
| unknown.append(w) | |
| out += [e for e in hit if e not in out] | |
| if unknown: | |
| raise SystemExit(f"unknown datasets: {unknown} (`build.py list` shows them all)") | |
| return out | |
| def size(n): | |
| if n is None: | |
| return "?" | |
| for unit, f in (("TB", 1e12), ("GB", 1e9), ("MB", 1e6)): | |
| if n >= f: | |
| return f"{n / f:,.1f} {unit}" | |
| return "0" if n == 0 else f"{n / 1e3:,.0f} kB" | |
| def needs_text(e): | |
| n = e.get("needs") or {} | |
| parts = [] | |
| if "login" in n: | |
| parts.append("login") | |
| if "archive" in n: | |
| parts.append(f"archive {n['archive']['file']}") | |
| if "builder" in n: | |
| parts.append("its builder") | |
| return ", ".join(parts) or "-" | |
| def cmd_list(a, index): | |
| sets = select(index, a.sets) | |
| if a.json: | |
| print(json.dumps(sets, indent=1, ensure_ascii=False)) | |
| return 0 | |
| print(f"{'dataset':28} {'folder':36} {'case':17} {'records':>11} {'download':>10} needs") | |
| for e in sets: | |
| dl = "n/a" if e["loader"] is None else size((e.get("download") or {}).get("bytes")) | |
| print(f"{e['dataset_id']:28} {e['folder']:36} {e['case']:17} {e['records'] or 0:>11,} {dl:>10} {needs_text(e)}") | |
| known = [e["download"]["bytes"] for e in sets if (e.get("download") or {}).get("bytes") is not None] | |
| print(f"{len(sets)} datasets, {sum(e['records'] or 0 for e in sets):,} records; downloads known for {len(known)}: " | |
| f"{size(sum(known))} (counted per dataset: sets that share a source, such as M-BEIR's image archive, fetch " | |
| "it once into the same --cache)") | |
| return 0 | |
| def fetch(root, repo, sets, teacher=False): | |
| from huggingface_hub import snapshot_download | |
| pats = ["tools/*"] + [f"{e['folder']}/*" for e in sets] + ([f"teacher/{e['folder']}/*" for e in sets] if teacher else []) | |
| snapshot_download(repo, repo_type="dataset", allow_patterns=pats, local_dir=root) | |
| def cmd_fetch(a, index): | |
| sets = select(index, a.sets) | |
| fetch(a.root, a.repo or index["repository"], sets, a.teacher) | |
| print(f"{len(sets)} dataset folders and tools/ in {a.root}") | |
| return 0 | |
| def check_packages(sets): | |
| """Missing packages the selected datasets' READMEs name (crc32c only warns), and pinned versions that differ.""" | |
| import importlib.metadata as md | |
| import importlib.util | |
| missing, warn = {}, [] | |
| for e in sets: | |
| for spec in (e.get("pip") or "").replace('"', "").split(): | |
| name = re.split(r"[<>=!~]", spec, 1)[0] | |
| mod = IMPORT_NAME.get(name, name) | |
| if importlib.util.find_spec(mod) is None: | |
| (warn.append(f"{name} not installed: a slower fallback is used") if name in OPTIONAL | |
| else missing.setdefault(name, spec)) | |
| continue | |
| pin = re.match(r"[^=<>!~]+==(.+)$", spec) | |
| if pin: | |
| try: | |
| have = md.version(name) | |
| except md.PackageNotFoundError: | |
| continue | |
| if have != pin.group(1): | |
| warn.append(f"{e['dataset_id']}: its README pins {spec}, {name} {have} is installed (the rebuilt " | |
| f"bytes may differ and be reported as such)") | |
| return missing, sorted(set(warn)) | |
| def command(e, a, root, out_dir, rep, prob): | |
| py = sys.executable | |
| loader = os.path.join(root, *LOADER[e["loader"]]) | |
| cache = os.path.abspath(a.cache) | |
| if e["loader"] == "rebuild_shards": | |
| c = [py, loader, "--root", root, "--sets", e["dataset_id"], "--cache", os.path.join(cache, "sources"), | |
| "--procs", str(a.procs), "--report", rep, "--problems", prob] | |
| return c + (["--no-write"] if a.no_write else ["--out", out_dir]) + (["--shards", a.shards] if a.shards else []) | |
| if e["loader"] == "rebuild_edit": | |
| c = [py, loader, "--set-dir", os.path.join(root, e["folder"]), "--cache", os.path.join(cache, "edit"), | |
| "--procs", str(a.procs), "--problems", prob] | |
| return c + ([] if a.no_write else ["--out", out_dir]) + (["--shards", a.shards] if a.shards else []) | |
| if e["loader"] == "mmeb_train": | |
| c = [py, loader, "--root", root, "--sets", e["dataset_id"], "--zips", os.path.join(cache, "mmeb_train_zips"), | |
| "--procs", str(a.procs), "--report", rep, "--problems", prob] | |
| return c + (["--no-write"] if a.no_write else ["--out", out_dir]) | |
| if e["loader"] == "imagenet21k": | |
| c = [py, loader, "iterate" if a.no_write else "rebuild", "--package", os.path.join(root, e["folder"])] | |
| c += ["--timm-dir", os.path.abspath(a.timm_dir)] if a.timm_dir else ["--hf"] | |
| c += ([] if a.no_write else ["--out", out_dir]) + ["--problems", prob] | |
| return c + (["--shards", a.shards] if a.shards else []) | |
| if e["loader"] == "shipped_shards": | |
| c = [py, loader, "--set-dir", os.path.join(root, e["folder"]), "--problems", prob] | |
| return c + ([] if a.no_write else ["--out", out_dir]) + (["--shards", a.shards] if a.shards else []) | |
| raise ValueError(e["loader"]) | |
| def prerequisite(e, a, root): | |
| """None, or what is missing before this dataset's loader can run.""" | |
| n = e.get("needs") or {} | |
| if e["loader"] is None: | |
| return "not here", n.get("builder", "identifiers only") | |
| if not os.path.isdir(os.path.join(root, e["folder"])): | |
| return "needs", f"its folder {e['folder']}/ (build.py fetch --sets {e['dataset_id']}, or --fetch)" | |
| if "archive" in n: | |
| x = n["archive"] | |
| if not os.path.exists(os.path.join(os.path.abspath(a.cache), "sources", x["file"])): | |
| return "needs", (f"{x['file']} ({size(x.get('bytes'))}, sha256 {x.get('sha256')}) in " | |
| f"{os.path.join(os.path.abspath(a.cache), 'sources')}/ (from {x.get('url')})") | |
| if "login" in n and not a.timm_dir: | |
| try: | |
| from huggingface_hub import get_token | |
| tok = get_token() | |
| except ImportError: | |
| tok = None | |
| if not tok: | |
| return "needs", n["login"] | |
| return None | |
| def outcome(e, rc, rep, prob, log): | |
| """The result line of one dataset from the loader's exit status, report, problem list and output.""" | |
| problems = sum(1 for _ in open(prob)) if os.path.exists(prob) else 0 | |
| info = {"exit_status": rc, "problems": problems} | |
| if os.path.exists(rep): | |
| r = json.load(open(rep)).get("sets", {}).get(e["dataset_id"], {}) | |
| info.update({k: r[k] for k in ("records", "record_ok", "shards", "shards_ok", "error") if k in r}) | |
| text = open(log, errors="replace").read() | |
| for line in text.splitlines(): # rebuild_edit: one JSON summary line | |
| if line.startswith('{"set"'): | |
| s = json.loads(line) | |
| info.update({"records_written": s.get("records"), "skipped": s.get("skipped")}) | |
| elif line.startswith("{'shard'"): # the ImageNet-21k loader: one dict per shard | |
| s = ast.literal_eval(line) | |
| info["records_written"] = info.get("records_written", 0) + s.get("written", 0) | |
| if rc == 0: | |
| return "pass", info | |
| if info.get("error"): | |
| return "needs", info | |
| if problems: | |
| return "incomplete", info | |
| return "failed", info | |
| def cmd_rebuild(a, index): | |
| sets = select(index, a.sets) | |
| root = os.path.abspath(a.root) | |
| if a.shards and len(sets) != 1: | |
| raise SystemExit("--shards names shards of one dataset: give exactly one in --sets") | |
| if a.shards and not (sets[0].get("shards_option") or sets[0].get("loader") == "rebuild_shards"): # 2026-11-18 | |
| raise SystemExit(f"{sets[0]['dataset_id']}: its loader rebuilds whole datasets only (no --shards)") | |
| if a.fetch: | |
| todo = [e for e in sets if e["loader"] and not os.path.isdir(os.path.join(root, e["folder"]))] | |
| if todo: | |
| fetch(root, a.repo or index["repository"], todo) | |
| runnable = [e for e in sets if e["loader"]] | |
| missing, warn = check_packages(runnable) | |
| for w in warn: | |
| print(f"note: {w}", flush=True) | |
| if missing: | |
| print("missing packages: pip install " + " ".join(sorted(missing.values())), flush=True) | |
| return 2 | |
| out, bdir = os.path.abspath(a.out), os.path.join(os.path.abspath(a.out), "_build") | |
| os.makedirs(bdir, exist_ok=True) | |
| results = [] | |
| for e in sets: | |
| base = os.path.join(bdir, e["folder"].replace("/", "__")) | |
| rep, prob, log = base + ".report.json", base + ".problems.jsonl", base + ".log" | |
| pre = prerequisite(e, a, root) | |
| if pre: | |
| res = {"dataset_id": e["dataset_id"], "folder": e["folder"], "result": pre[0], "why": pre[1]} | |
| else: | |
| cmd = command(e, a, root, os.path.join(out, e["folder"]), rep, prob) | |
| if a.dry_run: | |
| print(" ".join(cmd), flush=True) | |
| continue | |
| for p in (rep, prob): | |
| if os.path.exists(p): | |
| os.remove(p) | |
| t0 = time.time() | |
| what = f"shards {a.shards}" if a.shards else f"{e['records']:,} records" | |
| print(f"{time.strftime('%H:%M:%S')} {e['dataset_id']}: {e['case']}, {what} ...", flush=True) | |
| with open(log, "w") as fh: | |
| rc = subprocess.run(cmd, cwd=root, stdout=fh, stderr=subprocess.STDOUT).returncode | |
| result, info = outcome(e, rc, rep, prob, log) | |
| res = {"dataset_id": e["dataset_id"], "folder": e["folder"], "result": result, "seconds": round(time.time() - t0), | |
| "case": e["case"], **info, "log": os.path.relpath(log, out), | |
| "problem_list": os.path.relpath(prob, out) if info["problems"] else None} | |
| results.append(res) | |
| print(f" {res['dataset_id']}: {res['result']}" + (f" ({res['why']})" if res.get("why") else | |
| f" in {res['seconds']}s" + (f", {res['problems']} problems in {res['problem_list']}" if res.get("problem_list") | |
| else "")), flush=True) | |
| if a.dry_run: | |
| return 0 | |
| bad = [r for r in results if r["result"] not in ("pass", "not here")] | |
| summary = {"finished": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "out": out, "no_write": a.no_write, | |
| "counts": {k: sum(r["result"] == k for r in results) for k in ("pass", "incomplete", "failed", "needs", "not here")}, | |
| "datasets": results} | |
| json.dump(summary, open(os.path.join(bdir, "summary.json"), "w"), indent=1) | |
| print(f"{len(results)} datasets: " + ", ".join(f"{v} {k}" for k, v in summary["counts"].items() if v) + | |
| f"; summary in {os.path.join(bdir, 'summary.json')}", flush=True) | |
| return 1 if bad else 0 | |
| def main(argv=None): | |
| ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) | |
| ap.add_argument("--root", default=os.path.abspath(os.path.join(HERE, "..", "..")), | |
| help="the folder that holds tools/ and the dataset folders (default: two levels above this script)") | |
| ap.add_argument("--index", default=None, help="the index to read (default: datasets.json next to this script)") | |
| sub = ap.add_subparsers(dest="cmd", required=True) | |
| p = sub.add_parser("list") | |
| p.add_argument("--sets", default="all") | |
| p.add_argument("--json", action="store_true") | |
| p = sub.add_parser("fetch") | |
| p.add_argument("--sets", required=True) | |
| p.add_argument("--teacher", action="store_true", help="also the datasets' teacher embeddings (teacher/<folder>/)") | |
| p.add_argument("--repo", default=None) | |
| p = sub.add_parser("rebuild") | |
| p.add_argument("--sets", required=True) | |
| p.add_argument("--out", required=True) | |
| p.add_argument("--cache", default="cache", help="downloads of the original sources (and archives put in by hand, " | |
| "under <cache>/sources/)") | |
| p.add_argument("--procs", type=int, default=os.cpu_count() or 4) | |
| p.add_argument("--no-write", action="store_true", help="rebuild and check without writing shards") | |
| p.add_argument("--shards", default="", help="only these shards (one dataset whose loader takes --shards)") | |
| p.add_argument("--timm-dir", default=None, help="ImageNet-21k: local timm tars instead of streaming them") | |
| p.add_argument("--fetch", action="store_true", help="download the dataset folders that are not here yet") | |
| p.add_argument("--repo", default=None) | |
| p.add_argument("--dry-run", action="store_true", help="print the loader commands and stop") | |
| a = ap.parse_args(argv) | |
| index = load_index(a.index) | |
| return {"list": cmd_list, "fetch": cmd_fetch, "rebuild": cmd_rebuild}[a.cmd](a, index) | |
| if __name__ == "__main__": | |
| sys.exit(main()) | |