Files

120 lines
7.6 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""实时演示:一个 MuJoCo 窗口里,依次对桌上每个物体跑 胸口相机采集 → HUG → 重定向 L20 → 右臂抓取 → 放到放置区 → 回 ready。
用法:A7L20_SCENE=ycb1 MUJOCO_GL=glfw .venv/bin/python scripts/live_demo.py [--objects a,b] [--num 16] [--top 5] [--no-view]
子进程:HUG 用 $HUG_PYTHON,重定向用 $RETARGET_PYTHON;本进程用 a7l20 .venv 跑 MuJoCo + mink。
"""
import argparse, json, os, subprocess, sys, time
from pathlib import Path
from project_paths import configured_path
import numpy as np
sys.path.insert(0, str(Path(__file__).resolve().parent))
from grasp_exec import Sim, load_grasp_json, run, ROOT, SCENE
HUG_PY = configured_path('HUG_PYTHON', configured_path('HUG_ROOT', 'external/hug') / '.venv/bin/python'); SDK_PY = configured_path('RETARGET_PYTHON', '.retarget/bin/python')
DROP = np.array([0.56, -0.30]) # 放置区(桌面右后角)
def sh(cmd, cwd=None, env=None, allow=()):
"""跑子进程;返回码非 0 且不在 allow 里则中止。返回 (returncode, stdout, 用时)。"""
t0 = time.time(); r = subprocess.run(cmd, cwd=cwd, env=env, capture_output=True, text=True)
if r.returncode != 0 and r.returncode not in allow:
print(r.stdout[-2000:]); print(r.stderr[-3000:]); raise SystemExit(f"子进程失败: {' '.join(map(str, cmd[:3]))}")
return r.returncode, r.stdout, time.time() - t0
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--objects", default=None); ap.add_argument("--num", type=int, default=16); ap.add_argument("--top", type=int, default=5)
ap.add_argument("--no-view", action="store_true"); ap.add_argument("--render", action="store_true")
ap.add_argument("--perceive", action="store_true", help="用点云感知(perceive_object.py)替换真值像素喂给 HUG;识别不到的物体记为感知漏检并跳过")
ap.add_argument("--pcd", action="store_true", help="在 MuJoCo 窗口里叠加显示 D405 相机点云(每次采集的快照,RGB 上色)")
a = ap.parse_args()
sim = Sim(render=a.render, view=not a.no_view)
cap = ROOT / f"data/live_{SCENE}"; cap.mkdir(parents=True, exist_ok=True)
objs = [o["name"] for o in sim.info["objects"]]
if a.objects: objs = [o for o in a.objects.split(",") if o in objs]
env_hug = {k: v for k, v in os.environ.items() if k not in ("all_proxy", "ALL_PROXY")} | {"HF_HUB_OFFLINE": "1", "HF_ENDPOINT": "https://hf-mirror.com"}
env_sdk = dict(os.environ) | {"PYTHONPATH": "", "LD_LIBRARY_PATH": ""}
HUG_ARGS = ["--perceive"] if a.perceive else []
def set_pcd():
"""把当前采集的 RGB-D 反投影成点云快照,交给 viewer 叠加显示。"""
if not (a.pcd and sim.viewer is not None):
return
from view_pointcloud import backproject, voxel
Pw, C, _ = backproject(cap); Pw, C, _ = voxel(Pw, C, v=0.008)
if len(Pw) > 2500:
idx = np.random.default_rng(0).choice(len(Pw), 2500, replace=False); Pw, C = Pw[idx], C[idx]
sim.pcd = (Pw, C.astype(np.float64) / 255.0)
def perceive(qf):
"""跑一遍点云感知,写 perception.json;返回感知阶段用时。--perceive 关闭时空转。"""
if not a.perceive:
return 0.0
_, out, dt = sh([sys.executable, str(ROOT / "scripts/perceive_object.py"), "--capture", str(cap)])
line = [l for l in out.splitlines() if l.startswith("[perceive] clusters")]
print(f" perceive {dt:.1f}s: " + (line[0] if line else out.strip().splitlines()[-1][:100]))
return dt
results = {}
print(f"scene={SCENE} objects={objs} perceive={'ON(点云感知)' if a.perceive else 'OFF(真值像素)'}")
sim.hold(1.0)
for obj in objs:
print(f"\n==== {obj} ====")
qf = cap / "state_qpos.npy"; np.save(qf, sim.d.qpos.copy())
_, out, dt = sh([sys.executable, str(ROOT / "scripts/capture_chest_rgbd.py"), "--out", str(cap), "--qpos", str(qf)])
print(f" capture {dt:.1f}s: " + out.strip().splitlines()[0][:100])
set_pcd()
perceive(qf)
code, out, dt = sh([str(HUG_PY), str(ROOT / "scripts/hug_infer_point.py"), "--capture", str(cap), "--object", obj, "--num", str(a.num)] + HUG_ARGS, cwd=str(configured_path('HUG_ROOT', 'external/hug')), env=env_hug, allow=(3,))
if code == 3: # 点云感知没认出该物体:不对不可信位姿下手,记为漏检并跳过
print(f" 感知漏检: " + out.strip().splitlines()[-1][:120]); results[obj] = "miss"; sim.go_ready(2.5)
print(f" => {obj}: PERCEPTION_MISS"); continue
print(f" HUG {dt:.1f}s: " + [l for l in out.splitlines() if l.startswith("sampled") or l.startswith("click")][0][:100])
_, out, dt = sh([str(SDK_PY), str(ROOT / "scripts/hug_to_l20.py"), "--npz", str(cap / f"hug_{obj}.npz"), "--top", str(a.top)], env=env_sdk)
print(f" retarget {dt:.1f}s: " + [l for l in out.splitlines() if "pass filters" in l][0])
ok = False; body = next(o["body"] for o in sim.info["objects"] if o["name"] == obj); rounds = 0
k = 0
while k < a.top and not ok:
gj = cap / f"grasp_l20_{obj}_{k}.json"
if not gj.exists(): break
g = load_grasp_json(sim, gj)
print(f" -- candidate {k}: {json.loads(gj.read_text())['metrics']}")
p_before = sim.obj_pos(body).copy()
ok = run(sim, g)
if not ok and np.linalg.norm(sim.obj_pos(body) - p_before) > 0.015 and rounds < 2:
rounds += 1; sim.go_ready(2.5)
print(f" 物体被推动 {np.linalg.norm(sim.obj_pos(body) - p_before)*100:.1f} cm,重新感知(第 {rounds} 轮)")
np.save(qf, sim.d.qpos.copy()); sh([sys.executable, str(ROOT / "scripts/capture_chest_rgbd.py"), "--out", str(cap), "--qpos", str(qf)])
set_pcd()
perceive(qf)
c2, o2, _ = sh([str(HUG_PY), str(ROOT / "scripts/hug_infer_point.py"), "--capture", str(cap), "--object", obj, "--num", str(a.num), "--seed", str(rounds)] + HUG_ARGS, cwd=str(configured_path('HUG_ROOT', 'external/hug')), env=env_hug, allow=(3,))
if c2 == 3: # 被推动后感知不到了:放弃该物体
print(f" 重感知漏检,放弃 {obj}"); ok = False; break
sh([str(SDK_PY), str(ROOT / "scripts/hug_to_l20.py"), "--npz", str(cap / f"hug_{obj}.npz"), "--top", str(a.top)], env=env_sdk)
k = 0; continue
k += 1
if ok:
# 搬到放置区、松手、回 ready
p, R = sim.cfg_base_pose(); over = np.array([DROP[0], DROP[1], p[2]])
sim.move_to(over, R, 2.0); sim.hold(0.3, (over, R))
down = over - np.array([0, 0, 0.08]); sim.move_to(down, R, 1.2); sim.release(1.0, (down, R))
sim.move_to(over, R, 1.0); sim.go_ready(2.5)
else:
sim.go_ready(2.5)
results[obj] = "ok" if ok else "fail"
print(f" => {obj}: {'SUCCESS' if ok else 'FAIL'}")
print("\n==== summary ====")
mark = {"ok": "✓", "fail": "✗", "miss": "感知漏检"}
for k, v in results.items(): print(f" {k:22s} {mark.get(v, v)}")
n_ok = sum(v == "ok" for v in results.values()); n_miss = sum(v == "miss" for v in results.values())
print(f" {n_ok}/{len(results)} succeeded" + (f"(其中感知漏检 {n_miss})" if n_miss else ""))
if a.render:
sim.save_video(ROOT / f"out/live_{SCENE}.mp4")
if sim.viewer is not None:
print("viewer: 演示结束,窗口保持;关窗退出")
while sim.viewer.is_running(): sim.step(None)
if __name__ == "__main__":
main()