File size: 5,573 Bytes
d48c6a9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Load and replay Dexify clips.

    python tools/dexify_data.py list   xhand/data/TACO.h5                # clip ids of a file
    python tools/dexify_data.py info   xhand/data/TACO.h5 CLIP_ID        # arrays and metadata of one clip
    python tools/dexify_data.py replay xhand/data/TACO.h5 CLIP_ID [--video out.mp4] [--objects objects]

replay plays the recorded states back kinematically (no physics) in MuJoCo: the released hands (<hand>/robot/xhand/xhand_<side>_env.xml,
<hand> = the folder of the .h5 file's data/; joints set from <side>/qpos), the object (objects/<Dataset>/<object_id>/object.xml;
extract objects/<Dataset>.tar.gz into objects/<Dataset>/ first) at object_pos / object_quat, and the support disks. Without --video it opens the interactive viewer; with
--video it renders offscreen (needs imageio, e.g. pip install imageio[ffmpeg]; set MUJOCO_GL=egl on a headless machine).
Requires: numpy, h5py, mujoco >= 3.2.
"""
import argparse
import os

import h5py
import mujoco
import numpy as np

ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


def load_clip(h5_path, clip_id):
    """-> dict of numpy arrays (object_pos, object_quat, support_disks, <side>/qpos, wrist_pos, wrist_quat, contact) and the attrs."""
    with h5py.File(h5_path, "r") as h:
        g = h[clip_id]
        out = {k: g[k][()] for k in ("object_pos", "object_quat", "support_disks")}
        for side in ("right", "left"):
            if side in g:
                out[side] = {k: g[side][k][()] for k in g[side]}
        out["meta"] = dict(g.attrs)
    return out


def robot_xml(h5_path, side):
    hand_dir = os.path.dirname(os.path.dirname(os.path.abspath(h5_path)))  # <repo>/<hand>/data/<Dataset>.h5 -> <repo>/<hand>
    robot_dir = os.path.join(hand_dir, "robot")
    name = sorted(os.listdir(robot_dir))[0]
    return os.path.join(robot_dir, name, f"{name}_{side}_env.xml")


def build_scene(clip, objects_dir, h5_path):
    meta = clip["meta"]
    sides = [s for s in ("right", "left") if s in clip]
    spec = mujoco.MjSpec()
    spec.option.gravity = (0, 0, 0)
    spec.worldbody.add_light(pos=(0, 0, 3), dir=(0, 0, -1), diffuse=(0.8, 0.8, 0.8))
    for side in sides:
        hs = mujoco.MjSpec.from_file(robot_xml(h5_path, side))
        root = hs.worldbody.first_body()
        spec.worldbody.add_frame().attach_body(root, f"{side}/", "")
    os_ = mujoco.MjSpec.from_file(os.path.join(objects_dir, meta["dataset"], meta["object_id"], "object.xml"))
    spec.worldbody.add_frame().attach_body(os_.body("object"), "obj/", "")
    for i, (x, y, top, r, hgt) in enumerate(clip["support_disks"]):
        spec.worldbody.add_geom(name=f"disk{i}", type=mujoco.mjtGeom.mjGEOM_CYLINDER, size=(r, hgt / 2, 0),
                                pos=(x, y, top - hgt / 2), rgba=(0.9, 0.9, 0.9, 1))
    m = spec.compile()
    adr = {}
    for side in sides:
        xs = mujoco.MjModel.from_xml_path(robot_xml(h5_path, side))
        nq = clip[side]["qpos"].shape[1]
        names = [mujoco.mj_id2name(xs, mujoco.mjtObj.mjOBJ_JOINT, j) for j in range(xs.njnt)]
        adr[side] = [m.jnt_qposadr[mujoco.mj_name2id(m, mujoco.mjtObj.mjOBJ_JOINT, f"{side}/{n}")] for n in names[:nq]]
    fj = m.jnt_qposadr[mujoco.mj_name2id(m, mujoco.mjtObj.mjOBJ_JOINT, "obj/object_freejoint")]
    return m, adr, fj


def set_frame(m, d, clip, adr, fj, t):
    for side, a in adr.items():
        d.qpos[a] = clip[side]["qpos"][t]
    d.qpos[fj:fj + 3] = clip["object_pos"][t]
    d.qpos[fj + 3:fj + 7] = clip["object_quat"][t]
    mujoco.mj_forward(m, d)


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("cmd", choices=["list", "info", "replay"])
    ap.add_argument("h5")
    ap.add_argument("clip", nargs="?")
    ap.add_argument("--objects", default=os.path.join(ROOT, "objects"))
    ap.add_argument("--video", default=None)
    ap.add_argument("--size", default="960x540")
    a = ap.parse_args()
    if a.cmd == "list":
        with h5py.File(a.h5, "r") as h:
            print("\n".join(h.keys()))
        return
    clip = load_clip(a.h5, a.clip)
    if a.cmd == "info":
        for k, v in clip["meta"].items():
            print(f"{k}: {v}")
        for k in ("object_pos", "object_quat", "support_disks"):
            print(k, clip[k].shape)
        for side in ("right", "left"):
            if side in clip:
                print(side, {k: v.shape for k, v in clip[side].items()})
        return
    m, adr, fj = build_scene(clip, a.objects, a.h5)
    d = mujoco.MjData(m)
    T = len(clip["object_pos"])
    if a.video:
        import imageio
        W, H = map(int, a.size.split("x"))
        m.vis.global_.offwidth, m.vis.global_.offheight = max(W, 640), max(H, 480)
        r = mujoco.Renderer(m, H, W)
        cam = mujoco.MjvCamera()
        cam.lookat[:] = clip["object_pos"][0]
        cam.distance, cam.azimuth, cam.elevation = 0.7, 135, -30
        with imageio.get_writer(a.video, fps=30) as w:
            for t in range(0, T, 2):
                set_frame(m, d, clip, adr, fj, t)
                cam.lookat[:] = 0.8 * cam.lookat + 0.2 * clip["object_pos"][t]
                r.update_scene(d, cam)
                w.append_data(r.render())
        print(f"wrote {a.video} ({T} frames at 60 Hz, rendered at 30 fps)")
        return
    import time
    import mujoco.viewer
    with mujoco.viewer.launch_passive(m, d) as v:
        t = 0
        while v.is_running():
            set_frame(m, d, clip, adr, fj, t)
            v.sync()
            time.sleep(1 / 60)
            t = (t + 1) % T


if __name__ == "__main__":
    main()