agenthoi-eval / scripts /prepare_benchmark_assets.py
ProAudience's picture
Upload folder using huggingface_hub
271f3e5 verified
Raw History Blame Contribute Delete
5.27 kB
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Copy ref images from benchmark JSONs into benchmarks/assets/ and write portable JSONs.
Usage (on a machine that can read the paths inside the JSON files):
python scripts/prepare_benchmark_assets.py
python scripts/prepare_benchmark_assets.py --datasets crosstest AC homa
python scripts/prepare_benchmark_assets.py --dry-run
Outputs:
benchmarks/assets/<image_id>/ref_human.png|ref_object.png|ref_pasted.png
benchmarks/datasets_portable/<same basenames as datasets/>
"""
from __future__ import annotations
import argparse
import hashlib
import json
import os
import re
import shutil
from pathlib import Path
EVAL_ROOT = Path(__file__).resolve().parent.parent
DATASET_DIR = EVAL_ROOT / "benchmarks" / "datasets"
PORTABLE_DIR = EVAL_ROOT / "benchmarks" / "datasets_portable"
ASSETS_DIR = EVAL_ROOT / "benchmarks" / "assets"
DATASET_MAP = {
"crosstest": "hoi_crosstest_20251107.json",
"AC": "hoi_AC_test_evalset.json",
"homa": "hoi_selfcollect_homa1_evalset.json",
}
IMAGE_KEYS = (
("ref_image_path", "ref_human.png"),
("ref_obj_image_path", "ref_object.png"),
("pasted_image", "ref_pasted.png"),
)
def safe_dir_name(image_id: str) -> str:
s = re.sub(r"[^\w=\-.]", "_", image_id)
return s[:200] if len(s) > 200 else s
def copy_if_exists(src: str, dst: Path, dry_run: bool) -> bool:
if not src or not isinstance(src, str):
return False
if not src.lower().endswith((".png", ".jpg", ".jpeg", ".webp")):
return False
if not os.path.isfile(src):
return False
if dry_run:
return True
dst.parent.mkdir(parents=True, exist_ok=True)
if dst.exists() and dst.stat().st_size == os.path.getsize(src):
return True
shutil.copy2(src, dst)
return True
def portable_path(image_id: str, filename: str) -> str:
return f"benchmarks/assets/{safe_dir_name(image_id)}/{filename}"
def process_dataset(
src_json: Path,
dst_json: Path,
assets_dir: Path,
dry_run: bool,
report: dict,
) -> None:
with open(src_json, "r", encoding="utf-8") as f:
items = json.load(f)
out_items = []
for item in items:
image_id = item["image_id"]
subdir = assets_dir / safe_dir_name(image_id)
new_item = dict(item)
for json_key, local_name in IMAGE_KEYS:
src = item.get(json_key)
if not src:
continue
dst_file = subdir / local_name
if copy_if_exists(src, dst_file, dry_run):
new_item[json_key] = portable_path(image_id, local_name)
report["copied"] += 1
else:
report["missing"] += 1
if src.lower().endswith((".png", ".jpg", ".jpeg", ".webp")):
report["missing_paths"].append(src)
out_items.append(new_item)
if not dry_run:
dst_json.parent.mkdir(parents=True, exist_ok=True)
with open(dst_json, "w", encoding="utf-8") as f:
json.dump(out_items, f, ensure_ascii=False, indent=2)
report["samples"] = len(out_items)
def main():
parser = argparse.ArgumentParser(description="Package benchmark ref images for release/HF")
parser.add_argument(
"--datasets",
nargs="+",
default=list(DATASET_MAP.keys()),
choices=list(DATASET_MAP.keys()),
help="Which splits to process",
)
parser.add_argument("--dry-run", action="store_true")
parser.add_argument(
"--assets-dir",
type=Path,
default=ASSETS_DIR,
)
parser.add_argument(
"--portable-dir",
type=Path,
default=PORTABLE_DIR,
)
args = parser.parse_args()
total_report = {"copied": 0, "missing": 0, "missing_paths": [], "samples": 0}
for name in args.datasets:
src = DATASET_DIR / DATASET_MAP[name]
dst = args.portable_dir / DATASET_MAP[name]
report = {"copied": 0, "missing": 0, "missing_paths": [], "samples": 0}
print(f"[{name}] {src.name}")
process_dataset(src, dst, args.assets_dir, args.dry_run, report)
print(
f" samples={report['samples']} copied_fields={report['copied']} "
f"missing_fields={report['missing']}"
)
for k in ("copied", "missing", "samples"):
total_report[k] += report[k]
total_report["missing_paths"].extend(report["missing_paths"])
if not args.dry_run and args.assets_dir.exists():
n_dirs = sum(1 for _ in args.assets_dir.iterdir() if _.is_dir())
print(f"\nassets: {args.assets_dir} ({n_dirs} sample dirs)")
print(f"portable json: {args.portable_dir}")
missing_unique = sorted(set(total_report["missing_paths"]))
if missing_unique:
miss_log = EVAL_ROOT / "benchmarks" / "assets_missing.txt"
if not args.dry_run:
miss_log.write_text("\n".join(missing_unique) + "\n", encoding="utf-8")
print(f"\n[warn] {len(missing_unique)} unique missing source files")
print(f" log: {miss_log}")
print(" Re-run this script on the dev machine where those paths exist.")
if args.dry_run:
print("\n(dry-run, no files written)")
if __name__ == "__main__":
main()