bardofcodes's picture
Add files using upload-large-folder tool
05d6af6 verified
"""Generate manifest.jsonl and metadata.json for the sf_release dataset.
Walks `<root>/dataset/<source_dataset>/<method>/<object_id>/` and records one row
per instance with the artifacts present in that directory. Designed to be
idempotent and to ship inside the released Hugging Face repository so users can
rebuild the manifest at any revision.
Usage:
python scripts/build_manifest.py # writes manifest.jsonl + metadata.json
python scripts/build_manifest.py --checksums # also compute sha256 (slow)
python scripts/build_manifest.py --root /path/to/sf_release --out-dir /path/to/out
"""
from __future__ import annotations
import argparse
import hashlib
import json
import re
from collections import Counter, defaultdict
from pathlib import Path
from typing import Any
# Artifacts we look for in each instance directory.
# Order matters only for documentation; lookup is by exact filename.
OPTIONAL_FILES: dict[str, str] = {
"config": "config.json",
"primitive_assembly": "primitive_assembly.pkl",
"primitive_assembly_textured": "primitive_assembly.pkl_textured.pkl",
"primitive_assembly_eval": "primitive_assembly_eval.pkl",
"primitive_assembly_error": "primitive_assembly_error.pkl",
}
# Subdirectory under the release root that holds subset/method/instance trees.
DATASET_DIR = "dataset"
# Aggregate / method-level files we expect to find at <subset>/<method>/
METHOD_LEVEL_FILES: dict[str, str] = {
"eval_summary_md": "eval_summary", # prefix; suffix encodes range
"eval_summary_pkl": "eval_summary",
}
# toys4k uses "<category>_<numeric_id>" object ids; PartObjaverse uses 32-char hex.
TOYS4K_OBJECT_RE = re.compile(r"^(?P<category>[A-Za-z][A-Za-z0-9_]*?)_(?P<num>\d{3,})$")
HEX_OBJECT_RE = re.compile(r"^[0-9a-f]{32}$")
def sha256_file(path: Path, chunk_size: int = 1 << 20) -> str:
h = hashlib.sha256()
with path.open("rb") as fh:
while True:
buf = fh.read(chunk_size)
if not buf:
break
h.update(buf)
return h.hexdigest()
def parse_object_id(source_dataset: str, name: str) -> tuple[str | None, str]:
"""Return (category, object_id). category is None when not derivable."""
if source_dataset == "toys4k":
m = TOYS4K_OBJECT_RE.match(name)
if m:
return m.group("category"), name
return None, name
if source_dataset == "partobjaverse":
if HEX_OBJECT_RE.match(name):
return None, name
return None, name
return None, name
def scan_instance(instance_dir: Path) -> dict[str, Any]:
files_present: dict[str, bool] = {}
file_sizes: dict[str, int] = {}
for key, filename in OPTIONAL_FILES.items():
candidate = instance_dir / filename
present = candidate.is_file()
files_present[f"has_{key}"] = present
if present:
file_sizes[f"{key}_bytes"] = candidate.stat().st_size
return {"files_present": files_present, "file_sizes": file_sizes}
def build_manifest(
root: Path,
compute_checksums: bool,
dataset_dir: str = DATASET_DIR,
) -> tuple[list[dict[str, Any]], dict[str, Any]]:
rows: list[dict[str, Any]] = []
subset_counts: Counter[tuple[str, str]] = Counter()
method_aggregates: dict[tuple[str, str], dict[str, Any]] = {}
category_counts: dict[tuple[str, str], Counter[str]] = defaultdict(Counter)
if not root.is_dir():
raise SystemExit(f"Release root does not exist: {root}")
data_root = root / dataset_dir
if not data_root.is_dir():
raise SystemExit(f"Dataset directory does not exist: {data_root}")
subsets = sorted(
p.name for p in data_root.iterdir() if p.is_dir() and not p.name.startswith(".")
)
for subset in subsets:
subset_dir = data_root / subset
methods = sorted(p.name for p in subset_dir.iterdir() if p.is_dir())
for method in methods:
method_dir = subset_dir / method
method_files: dict[str, list[str]] = {"eval_summary_md": [], "eval_summary_pkl": []}
for entry in method_dir.iterdir():
if entry.is_file() and entry.name.startswith("eval_summary"):
if entry.suffix == ".md":
method_files["eval_summary_md"].append(entry.name)
elif entry.suffix == ".pkl":
method_files["eval_summary_pkl"].append(entry.name)
for k in method_files:
method_files[k].sort()
method_aggregates[(subset, method)] = method_files
instance_dirs = sorted(p for p in method_dir.iterdir() if p.is_dir())
for instance_dir in instance_dirs:
name = instance_dir.name
category, object_id = parse_object_id(subset, name)
scan = scan_instance(instance_dir)
paths: dict[str, str | None] = {}
for key, filename in OPTIONAL_FILES.items():
rel = f"{dataset_dir}/{subset}/{method}/{name}/{filename}"
paths[f"{key}_path"] = rel if scan["files_present"][f"has_{key}"] else None
row: dict[str, Any] = {
"source_dataset": subset,
"method": method,
"object_id": object_id,
"category": category,
"instance_dir": f"{dataset_dir}/{subset}/{method}/{name}",
**paths,
**scan["files_present"],
**scan["file_sizes"],
}
if compute_checksums:
for key, filename in OPTIONAL_FILES.items():
candidate = instance_dir / filename
if candidate.is_file():
row[f"{key}_sha256"] = sha256_file(candidate)
rows.append(row)
subset_counts[(subset, method)] += 1
if category is not None:
category_counts[(subset, method)][category] += 1
metadata: dict[str, Any] = {
"release_root_name": root.resolve().name,
"data_dir": dataset_dir,
"subsets": sorted({s for s, _ in subset_counts}),
"methods_by_subset": {
subset: sorted({m for s, m in subset_counts if s == subset})
for subset in sorted({s for s, _ in subset_counts})
},
"instance_counts": {
f"{subset}/{method}": count
for (subset, method), count in sorted(subset_counts.items())
},
"total_instances": sum(subset_counts.values()),
"method_level_files": {
f"{subset}/{method}": files
for (subset, method), files in sorted(method_aggregates.items())
},
"category_counts_toys4k": {
f"{subset}/{method}": dict(sorted(counts.items()))
for (subset, method), counts in sorted(category_counts.items())
if subset == "toys4k"
},
"schema": {
"artifact_filenames": OPTIONAL_FILES,
"manifest_columns": [
"source_dataset",
"method",
"object_id",
"category",
"instance_dir",
"config_path",
"primitive_assembly_path",
"primitive_assembly_textured_path",
"primitive_assembly_eval_path",
"primitive_assembly_error_path",
"has_config",
"has_primitive_assembly",
"has_primitive_assembly_textured",
"has_primitive_assembly_eval",
"has_primitive_assembly_error",
"config_bytes",
"primitive_assembly_bytes",
"primitive_assembly_textured_bytes",
"primitive_assembly_eval_bytes",
"primitive_assembly_error_bytes",
],
"checksums_included": compute_checksums,
},
}
return rows, metadata
def write_outputs(rows: list[dict[str, Any]], metadata: dict[str, Any], out_dir: Path) -> None:
out_dir.mkdir(parents=True, exist_ok=True)
manifest_path = out_dir / "manifest.jsonl"
with manifest_path.open("w") as fh:
for row in rows:
fh.write(json.dumps(row, sort_keys=True))
fh.write("\n")
metadata_path = out_dir / "metadata.json"
with metadata_path.open("w") as fh:
json.dump(metadata, fh, indent=2, sort_keys=True)
fh.write("\n")
print(f"Wrote {len(rows)} rows to {manifest_path}")
print(f"Wrote summary to {metadata_path}")
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
default_root = Path(__file__).resolve().parent.parent
parser.add_argument("--root", type=Path, default=default_root,
help="Release root (expects dataset/<subset>/<method>/<instance>/).")
parser.add_argument("--dataset-dir", type=str, default=DATASET_DIR,
help=f"Name of the data subdirectory under --root (default: {DATASET_DIR}).")
parser.add_argument("--out-dir", type=Path, default=None,
help="Where to write manifest.jsonl and metadata.json. Defaults to --root.")
parser.add_argument("--checksums", action="store_true",
help="Compute sha256 for every artifact file. Slow on the full release.")
args = parser.parse_args()
out_dir = args.out_dir if args.out_dir is not None else args.root
rows, metadata = build_manifest(
args.root,
compute_checksums=args.checksums,
dataset_dir=args.dataset_dir,
)
write_outputs(rows, metadata, out_dir)
if __name__ == "__main__":
main()