File size: 5,248 Bytes
d87189c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/venv/main/bin/python3
"""
finalize_multiview.py β€” after multiview.py has written all 3 view videos, fold
them into the dataset metadata so /workspace/retargeted_lerobot becomes a clean
LeRobot v2.1 dataset whose image schema MATCHES abc-teleop exactly:
    observation.images.top / left_wrist / right_wrist  (224x224, h264, yuv420p, 30fps)

It rewrites (backing up first):
  meta/info.json          β€” features: drop observation.images.camera, add 3 view keys
  meta/episodes_stats.jsonl β€” per episode: drop camera stats, add the 3 view stats
                              (computed exactly during generation), keep state/action/…
The old camera .mp4 files are left on disk (unreferenced) β€” nothing is deleted.

Usage: /venv/main/bin/python3 finalize_multiview.py --ds /workspace/retargeted_lerobot \
         [--teleop /workspace/abc-teleop] [--keep-camera]
"""
import os, json, glob, shutil, argparse

KEYS = ["observation.images.top",
        "observation.images.left_wrist",
        "observation.images.right_wrist"]
VID_H = VID_W = 224
FPS = 30

def video_block():
    return {"dtype": "video", "shape": [VID_H, VID_W, 3],
            "names": ["height", "width", "channels"],
            "info": {"video.height": VID_H, "video.width": VID_W,
                     "video.codec": "h264", "video.pix_fmt": "yuv420p",
                     "video.is_depth_map": False, "video.fps": FPS,
                     "video.channels": 3, "has_audio": False}}

def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--ds", default="/workspace/retargeted_lerobot")
    ap.add_argument("--teleop", default="/workspace/abc-teleop")
    ap.add_argument("--keep-camera", action="store_true",
                    help="also keep observation.images.camera in the schema")
    args = ap.parse_args()
    ds = args.ds
    meta = os.path.join(ds, "meta")

    # results -> {episode_index: {key: stats}}
    res = {}
    with open(os.path.join(ds, "multiview_results.jsonl")) as f:
        for line in f:
            d = json.loads(line)
            if "stats" in d:
                res[d["episode_index"]] = d["stats"]   # last wins (resume-safe)
    print(f"results with stats: {len(res)} episodes")

    # sanity: every episode must have all 3 view videos on disk
    missing = []
    for e in res:
        ci = e // 1000
        for k in KEYS:
            p = f"{ds}/videos/chunk-{ci:03d}/{k}/episode_{e:06d}.mp4"
            if not os.path.exists(p):
                missing.append(p)
    if missing:
        print(f"WARNING: {len(missing)} view videos missing on disk, e.g. {missing[:3]}")

    # ── info.json ────────────────────────────────────────────────────────────
    info_p = os.path.join(meta, "info.json")
    info = json.load(open(info_p))
    feats = info["features"]
    if not args.keep_camera:
        feats.pop("observation.images.camera", None)
    # insert the 3 view blocks first (ordering cosmetic)
    new_feats = {k: video_block() for k in KEYS}
    for k, v in feats.items():
        if k not in new_feats:
            new_feats[k] = v
    info["features"] = new_feats

    n_ep = info["total_episodes"]
    n_keys = len(KEYS) + (1 if args.keep_camera else 0)
    # mirror teleop's total_videos convention if available, else episodes*keys
    tv = n_ep * n_keys
    tinfo_p = os.path.join(args.teleop, "meta", "info.json")
    if os.path.exists(tinfo_p):
        ti = json.load(open(tinfo_p))
        n_tvid_keys = sum(1 for v in ti["features"].values() if v.get("dtype") == "video")
        if n_tvid_keys and ti.get("total_episodes"):
            per_ep = ti["total_videos"] / ti["total_episodes"]   # e.g. 3.0 or 1.0
            # teleop counts videos-per-episode == #camera keys -> apply same rule
            tv = int(round(per_ep / n_tvid_keys * n_keys * n_ep))
    info["total_videos"] = tv

    shutil.copy(info_p, info_p + ".camera.bak")
    json.dump(info, open(info_p, "w"), indent=4)
    print(f"info.json: video keys -> {[k for k,v in info['features'].items() if v.get('dtype')=='video']}"
          f"  total_videos={tv}")

    # ── episodes_stats.jsonl ─────────────────────────────────────────────────
    es_p = os.path.join(meta, "episodes_stats.jsonl")
    shutil.copy(es_p, es_p + ".camera.bak")
    out_lines = []
    n_patched = 0
    with open(es_p) as f:
        for line in f:
            d = json.loads(line)
            e = d["episode_index"]
            st = d.get("stats", {})
            if not args.keep_camera:
                st.pop("observation.images.camera", None)
            if e in res:
                for k in KEYS:
                    st[k] = res[e][k]
                n_patched += 1
            d["stats"] = st
            out_lines.append(json.dumps(d))
    with open(es_p, "w") as f:
        f.write("\n".join(out_lines) + "\n")
    print(f"episodes_stats.jsonl: patched {n_patched}/{len(out_lines)} episodes")
    print("done. dataset image schema now matches abc-teleop (top/left_wrist/right_wrist).")

if __name__ == "__main__":
    main()