File size: 5,968 Bytes
73a3036
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
"""End-to-end Genesis/dexmachina scene demo.

Runs inside the `benchmarking/dexmachina:latest` container. Patches the
installed `dexmachina` package with the missing `envs/hand_cfgs/` submodule
(copied to `outputs/_runtime_patches` on the host, volume-mounted at
`/workspace/outputs/_runtime_patches`), verifies imports, builds a small
Genesis scene (ground plane + xhand URDF), renders 60 frames and muxes them
into an mp4 via `shared.bench.VideoRecorder`.

All output artefacts are written under `/workspace/outputs/`.
"""
from __future__ import annotations

import json
import os
import shutil
import sys
import time
import traceback
from pathlib import Path

OUT_ROOT = Path("/workspace/outputs")
LOG_PATH = OUT_ROOT / "logs" / "dexmachina_scene_demo.log"
MP4_PATH = OUT_ROOT / "videos" / "dexmachina_xhand_demo.mp4"
LOG_PATH.parent.mkdir(parents=True, exist_ok=True)
MP4_PATH.parent.mkdir(parents=True, exist_ok=True)

log_buf = []

def log(msg: str) -> None:
    print(msg, flush=True)
    log_buf.append(str(msg))


def flush_log() -> None:
    LOG_PATH.write_text("\n".join(log_buf) + "\n")


# ---- 1. runtime-patch dexmachina.envs.hand_cfgs (missing in installed wheel)
def patch_hand_cfgs() -> None:
    import dexmachina
    dst = Path(dexmachina.__file__).parent / "envs" / "hand_cfgs"
    src = Path("/workspace/outputs/_runtime_patches/dexmachina/envs/hand_cfgs")
    if not dst.exists():
        if not src.exists():
            raise RuntimeError(f"hand_cfgs staged source missing: {src}")
        shutil.copytree(src, dst)
        log(f"patched: copied {src} -> {dst}")
    else:
        log(f"hand_cfgs already present at {dst}")


# ---- 2. import graph
def do_imports() -> dict:
    import importlib.metadata as im
    import torch, genesis, rl_games, dexmachina  # noqa: F401
    from dexmachina.envs.hand_cfgs.xhand import XHAND_CFGs
    from dexmachina.envs import base_env

    info = {
        "torch": torch.__version__,
        "genesis": getattr(genesis, "__version__", "ok"),
        "rl_games": im.version("rl_games"),
        "dexmachina": im.version("dexmachina"),
        "cuda_available": bool(torch.cuda.is_available()),
        "BaseEnv": base_env.BaseEnv.__name__,
        "XHAND_CFGs_keys": list(XHAND_CFGs.keys()),
    }
    return info


# ---- 3. scene demo
def run_scene_demo() -> dict:
    import numpy as np
    import torch
    import genesis as gs
    sys.path.insert(0, "/workspace/shared")
    from bench.video_recorder import VideoRecorder

    backend = gs.cuda if torch.cuda.is_available() else gs.cpu
    log(f"genesis.init backend={backend}")
    gs.init(backend=backend, logging_level="warning")

    scene = gs.Scene(show_viewer=False)

    # ground plane
    scene.add_entity(gs.morphs.Plane())

    # xhand URDF (right hand is the standard variant)
    # Preference order: staging-backed /workspace/assets symlinks (but in this
    # image those aren't mounted, so the symlink target is missing), then the
    # dexmachina-shipped URDF. We try both so future mount changes "just work".
    candidates = [
        "/workspace/assets/urdf/xhand/xhand_urdf/xhand_right/urdf/xhand_right.urdf",
        "/usr/local/lib/python3.10/dist-packages/dexmachina/assets/xhand/xhand_right.urdf",
    ]
    urdf_path = next((p for p in candidates if Path(p).exists()), None)
    assert urdf_path is not None, f"no xhand urdf found among {candidates}"
    log(f"urdf_path={urdf_path}")
    hand = scene.add_entity(
        gs.morphs.URDF(
            file=urdf_path,
            pos=(0.0, 0.0, 0.25),
            fixed=True,
        )
    )

    W, H = 640, 480
    camera = scene.add_camera(
        res=(W, H),
        pos=(0.6, 0.6, 0.45),
        lookat=(0.0, 0.0, 0.2),
        fov=45,
        GUI=False,
    )

    scene.build()
    log(f"scene built; hand entity: {hand}")

    rec = VideoRecorder(MP4_PATH, fps=30, size=(W, H))
    n_frames = 60
    t0 = time.time()
    for i in range(n_frames):
        scene.step()
        out = camera.render()
        # Genesis camera.render returns a tuple (rgb, depth, seg, normal)
        rgb = out[0] if isinstance(out, tuple) else out
        if hasattr(rgb, "cpu"):
            rgb = rgb.cpu().numpy()
        if rgb.dtype != np.uint8:
            rgb = rgb.astype(np.uint8)
        if rgb.shape[-1] == 4:
            rgb = rgb[..., :3]
        rec.log_frame(np.ascontiguousarray(rgb))
    rec.close()
    dt = time.time() - t0

    size_bytes = MP4_PATH.stat().st_size
    log(f"rendered {n_frames} frames {W}x{H} in {dt:.2f}s; mp4={MP4_PATH} ({size_bytes} bytes)")
    return {
        "mp4_path": str(MP4_PATH),
        "frames": n_frames,
        "resolution": [W, H],
        "mp4_size_bytes": size_bytes,
        "backend": str(backend),
        "elapsed_s": round(dt, 3),
    }


def main() -> int:
    result = {"ok": True, "steps": {}}
    try:
        patch_hand_cfgs()
        imports = do_imports()
        result["steps"]["imports"] = imports
        log("IMPORTS: " + json.dumps(imports))
    except Exception as e:
        result["ok"] = False
        result["steps"]["imports_error"] = repr(e)
        log("IMPORT ERROR: " + repr(e))
        log(traceback.format_exc())
        flush_log()
        (OUT_ROOT / "logs" / "dexmachina_scene_demo.json").write_text(json.dumps(result, indent=2))
        return 2

    try:
        scene_info = run_scene_demo()
        result["steps"]["scene"] = scene_info
        log("SCENE: " + json.dumps(scene_info))
    except Exception as e:
        result["ok"] = False
        result["steps"]["scene_error"] = repr(e)
        log("SCENE ERROR: " + repr(e))
        log(traceback.format_exc())
        flush_log()
        (OUT_ROOT / "logs" / "dexmachina_scene_demo.json").write_text(json.dumps(result, indent=2))
        return 3

    flush_log()
    (OUT_ROOT / "logs" / "dexmachina_scene_demo.json").write_text(json.dumps(result, indent=2))
    log("DONE")
    return 0


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