File size: 4,982 Bytes
d2d0d6d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Load one HandWorldBench evaluation case from a downloaded copy of the benchmark.

Usage:
    python load_clip.py <dataset_dir> <case_id>         # print a summary of one case
    python load_clip.py <dataset_dir> --list [category] # list case ids

As a library:
    from load_clip import load_catalog, load_case
    case = load_case("HandWorldBench-data", "hw500_0001")
    case["hands"]["joints_2d_px"]          # (T, 2, 21, 2) float64, reference pixels
    case["camera"]["c2w"]                  # (T, 4, 4) camera-to-world

Only numpy is required. Paths in catalog.json are relative to <dataset_dir>.
"""
import argparse
import json
import sys
from pathlib import Path

import numpy as np


def load_catalog(root):
    """Return {case_id: catalog record} for the 500 benchmark cases."""
    root = Path(root)
    records = json.loads((root / "catalog.json").read_text(encoding="utf-8"))
    return {r["case_id"]: r for r in records}


def _npz(path):
    with np.load(path, allow_pickle=False) as z:
        return {k: z[k] for k in z.files}


def load_prompts(root):
    """Return {case_id: prompts.jsonl row}."""
    rows = (json.loads(l) for l in (Path(root) / "prompts.jsonl").read_text(encoding="utf-8").splitlines() if l.strip())
    return {r["case_id"]: r for r in rows}


def load_case(root, case_id, catalog=None):
    """Return one case: its catalog record, resolved file paths, arrays and annotations.

    `prompt` (prompts.jsonl) is the generation prompt; it is identical to the catalog's `task_description`.
    """
    root = Path(root)
    catalog = catalog or load_catalog(root)
    prompts = load_prompts(root)
    if case_id not in catalog:
        raise KeyError(f"{case_id} is not in {root / 'catalog.json'}")
    rec = catalog[case_id]
    files = rec["files"]
    geometry = rec["geometry"]
    return {
        "case_id": case_id,
        "category": rec["category"],
        "prompt": prompts[case_id]["prompt"],
        "task_description": rec["task_description"],
        "reference_video": root / rec["reference"]["video"],
        "first_frame": root / files["first_frame"],
        "controls": {name: root / p for name, p in files["controls"].items()},
        "width": rec["reference"]["width"],
        "height": rec["reference"]["height"],
        "fps": rec["reference"]["fps"],
        "frame_count": rec["reference"]["frame_count"],
        "hand_order": geometry["hand_order"],
        "joint_names": geometry.get("joint_names"),
        "hands": _npz(root / geometry["path"]),
        "camera": _npz(root / files["camera"]),
        "annotations": json.loads((root / files["annotations"]).read_text(encoding="utf-8")),
        "applicability": rec["applicability"],
        "record": rec,
    }


def _summary(case):
    hands, cam = case["hands"], case["camera"]
    applicable = sorted(m for m, s in case["applicability"].items() if s == "applicable")
    caption = case["annotations"].get("caption", {}).get("text", "")
    lines = [
        f"case_id        {case['case_id']}  ({case['category']})",
        f"prompt         {case['prompt']}",
        f"reference      {case['reference_video']}  {case['width']}x{case['height']} @ {case['fps']} fps, {case['frame_count']} frames",
        f"first frame    {case['first_frame']}",
        "controls       " + ", ".join(f"{k}={v.name}" for k, v in case["controls"].items()),
        f"hands          joints_2d_px {hands['joints_2d_px'].shape}, joints_camera_m {hands['joints_camera_m'].shape}, "
        f"hand order {case['hand_order']}, valid 2-D points {int(hands['valid_uv'].sum())}",
        f"camera         {str(cam['distortion_model'])}, K[0,0]={cam['K'][0, 0]:.1f}, c2w {cam['c2w'].shape}",
        f"caption        {caption[:160]}{'...' if len(caption) > 160 else ''}",
        f"metrics        {len(applicable)} applicable: {', '.join(applicable)}",
    ]
    missing = [str(p) for p in [case["reference_video"], case["first_frame"], *case["controls"].values()] if not p.exists()]
    if missing:
        lines.append("missing files  " + ", ".join(missing))
    return "\n".join(lines)


def main(argv=None):
    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument("dataset_dir", type=Path)
    parser.add_argument("case_id", nargs="?")
    parser.add_argument("--list", nargs="?", const="all", metavar="CATEGORY",
                        help="list case ids (optionally only human, handson or real_robot)")
    args = parser.parse_args(argv)
    catalog = load_catalog(args.dataset_dir)
    if args.list:
        for cid, rec in catalog.items():
            if args.list in ("all", rec["category"]):
                print(cid, rec["category"])
        return 0
    if not args.case_id:
        parser.error("give a case id or --list")
    print(_summary(load_case(args.dataset_dir, args.case_id, catalog)))
    return 0


if __name__ == "__main__":
    sys.exit(main())