File size: 5,266 Bytes
271f3e5 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 | #!/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()
|