Molbap HF Staff commited on
Commit
964609b
·
verified ·
1 Parent(s): 8763659

Upload folder using huggingface_hub

Browse files
__pycache__/app.cpython-313.pyc DELETED
Binary file (28.9 kB)
 
__pycache__/libero_robot.cpython-313.pyc DELETED
Binary file (15.4 kB)
 
app.py CHANGED
@@ -74,6 +74,7 @@ from libero_robot import LiberoSceneConfig # noqa: E402
74
  SUITE, SCENE_TASK = "libero_goal", 8
75
  TASKS = [task.language for task in _get_suite(SUITE).tasks]
76
  SESSION_S = 75
 
77
  EXAMPLE_GOALS = [
78
  "warm up the bowl",
79
  "the wine bottle belongs on the rack",
@@ -168,6 +169,18 @@ def planner_failure(error: str) -> str:
168
  return f"The planner failed: {error}"
169
 
170
 
 
 
 
 
 
 
 
 
 
 
 
 
171
  def planner_message(answer) -> dict | None:
172
  """One chat bubble per planner result; holds only show in the status line."""
173
  latency = f" · {answer.latency_s:.1f} s" if answer.latency_s else ""
@@ -177,28 +190,29 @@ def planner_message(answer) -> dict | None:
177
  if answer.completed:
178
  return {
179
  "role": "assistant",
180
- "content": "Request done, according to the planner. The robot keeps its last instruction.",
181
  "metadata": {"title": f"Planner{latency}"},
182
  }
183
  if answer.held:
184
  return None
185
  return {
186
  "role": "assistant",
187
- "content": f"**{answer.answer}**\n\n{answer.detail}".strip(),
188
  "metadata": {"title": f"Planner{latency}"},
189
  }
190
  return {"role": "assistant", "content": answer.answer, "metadata": {"title": f"Answer{latency}"}}
191
 
192
 
193
- def status_html(state: str, instruction: str, goal: str | None, remaining: float | None, rate_hz: float | None) -> str:
194
  goal_line = f'<div class="goal">Request: {html.escape(goal)}</div>' if goal else ""
 
195
  rate = f'<span class="pill">sim {rate_hz:.0f} Hz</span>' if rate_hz else ""
196
  timer = f'<span class="pill">{remaining:.0f} s left</span>' if remaining is not None else ""
197
  return (
198
  f'<div class="status"><div class="row"><span class="pill {state.split()[0]}">'
199
  f'{"<span class=spinner></span>" if state == "starting" else ""}{state}</span>'
200
  f'{timer}{rate}</div>'
201
- f'<div class="label">Current instruction</div><div class="instruction">{html.escape(instruction)}</div>{goal_line}</div>'
202
  )
203
 
204
 
@@ -223,7 +237,9 @@ def apply(controller, command: dict, chat: list, goal: str | None) -> str | None
223
 
224
 
225
  def drive(controller, engine, robot, path: Path, chat: list, events: list):
226
- """Stream frames and chat until time is up, applying commands as they arrive."""
 
 
227
  commands, offset = read_commands(path, 0)
228
  goal, retries, done, recent, sequence = None, 0, False, [], 0
229
  stream = f"{path.stem}-{time.time()}"
@@ -238,7 +254,7 @@ def drive(controller, engine, robot, path: Path, chat: list, events: list):
238
  controller.start()
239
  for command in commands:
240
  if command["kind"] == "stop":
241
- return
242
  goal = apply(controller, command, chat, goal)
243
  retries, done = 0, False
244
  commands, offset = read_commands(path, offset)
@@ -268,18 +284,23 @@ def drive(controller, engine, robot, path: Path, chat: list, events: list):
268
  sequence += 1
269
  recent.append((sequence, pose))
270
  recent = recent[-6:]
 
 
 
 
 
271
  if engine.hold_for_planner():
272
  state = "waiting for planner"
273
  else:
274
  state = "steering" if goal else "running"
275
  if done:
276
  state = "planner done, robot continues"
277
- elapsed = time.time() - started
278
  rate = (robot.steps - first_step) / elapsed if elapsed > 2 else None
279
  yield player_update(recent, rate, stream), chat, status_html(state, controller.task, goal, SESSION_S - elapsed, rate)
280
  time.sleep(0.25)
281
  if controller.failed:
282
  raise RuntimeError(controller.failure_traceback)
 
283
 
284
 
285
  @spaces.GPU(duration=120)
@@ -319,13 +340,14 @@ def run_session(session: str):
319
  server = threading.Thread(target=controller.serve, daemon=True)
320
  server.start()
321
  try:
322
- yield from drive(controller, ctx.policy.inference, robot, path, chat, events)
323
  finally:
324
  controller.stop()
325
  server.join(timeout=10)
326
  strategy.teardown(ctx)
327
- chat.append({"role": "assistant", "content": "Session ended."})
328
- yield player_update([]), chat, status_html("finished", controller.task, None, None, None)
 
329
  finally:
330
  WORKER_BUSY.release()
331
 
@@ -408,11 +430,14 @@ with gr.Blocks(title="Steer a robot with words") as demo:
408
  with gr.Column(scale=3):
409
  view = gr.HTML(
410
  player_update([]),
411
- html_template='<div class="player"><canvas class="screen"></canvas><div class="loading">Loading the 3D scene</div></div>',
 
 
 
412
  js_on_load=PLAYER_JS,
413
  elem_id="view",
414
  )
415
- status = gr.HTML(status_html("idle", "none. Type a request or click an instruction to start a 75 s session.", None, None, None))
416
  with gr.Column(scale=2):
417
  chat = gr.Chatbot(show_label=False, height=340, layout="panel", elem_id="chat", placeholder="Session log", buttons=[], feedback_options=None)
418
  goal_box = gr.Textbox(placeholder="Request, e.g. warm up the bowl", show_label=False, submit_btn="Steer", elem_id="goal")
 
74
  SUITE, SCENE_TASK = "libero_goal", 8
75
  TASKS = [task.language for task in _get_suite(SUITE).tasks]
76
  SESSION_S = 75
77
+ NEXT_SESSION = f"A new request or instruction starts a new {SESSION_S} s session from the initial scene."
78
  EXAMPLE_GOALS = [
79
  "warm up the bowl",
80
  "the wine bottle belongs on the rack",
 
169
  return f"The planner failed: {error}"
170
 
171
 
172
+ def readable_detail(detail: str | None) -> str:
173
+ """lerobot's planner detail is "scene: ...; previous command: ..."; show it as two plain sentences."""
174
+ match = re.fullmatch(r"(?:scene: (.*?))?(?:;? ?previous command: (.*))?", detail or "", re.DOTALL)
175
+ if not match:
176
+ return detail or ""
177
+ scene, verdict = match.group(1), match.group(2)
178
+ lines = [scene.rstrip(".;") + "." if scene else ""]
179
+ if verdict and verdict.strip().lower() != "none":
180
+ lines.append(f"Previous instruction: {verdict.strip()}.")
181
+ return "\n\n".join(line for line in lines if line)
182
+
183
+
184
  def planner_message(answer) -> dict | None:
185
  """One chat bubble per planner result; holds only show in the status line."""
186
  latency = f" · {answer.latency_s:.1f} s" if answer.latency_s else ""
 
190
  if answer.completed:
191
  return {
192
  "role": "assistant",
193
+ "content": "The planner says the request is done. The session ends when the simulator confirms the last instruction.",
194
  "metadata": {"title": f"Planner{latency}"},
195
  }
196
  if answer.held:
197
  return None
198
  return {
199
  "role": "assistant",
200
+ "content": f"**{answer.answer}**\n\n{readable_detail(answer.detail)}".strip(),
201
  "metadata": {"title": f"Planner{latency}"},
202
  }
203
  return {"role": "assistant", "content": answer.answer, "metadata": {"title": f"Answer{latency}"}}
204
 
205
 
206
+ def status_html(state: str, instruction: str, goal: str | None, remaining: float | None, rate_hz: float | None, note: str | None = None) -> str:
207
  goal_line = f'<div class="goal">Request: {html.escape(goal)}</div>' if goal else ""
208
+ goal_line += f'<div class="goal">{html.escape(note)}</div>' if note else ""
209
  rate = f'<span class="pill">sim {rate_hz:.0f} Hz</span>' if rate_hz else ""
210
  timer = f'<span class="pill">{remaining:.0f} s left</span>' if remaining is not None else ""
211
  return (
212
  f'<div class="status"><div class="row"><span class="pill {state.split()[0]}">'
213
  f'{"<span class=spinner></span>" if state == "starting" else ""}{state}</span>'
214
  f'{timer}{rate}</div>'
215
+ f'<div class="label">{"Last" if state in ("done", "stopped", "time up") else "Current"} instruction</div><div class="instruction">{html.escape(instruction)}</div>{goal_line}</div>'
216
  )
217
 
218
 
 
237
 
238
 
239
  def drive(controller, engine, robot, path: Path, chat: list, events: list):
240
+ """Stream poses and chat, applying commands as they arrive. Returns why the session ended: "done" when
241
+ the simulator confirms the current instruction (and the planner, if a request is running, says done),
242
+ "stopped", or "time up"."""
243
  commands, offset = read_commands(path, 0)
244
  goal, retries, done, recent, sequence = None, 0, False, [], 0
245
  stream = f"{path.stem}-{time.time()}"
 
254
  controller.start()
255
  for command in commands:
256
  if command["kind"] == "stop":
257
+ return "stopped"
258
  goal = apply(controller, command, chat, goal)
259
  retries, done = 0, False
260
  commands, offset = read_commands(path, offset)
 
284
  sequence += 1
285
  recent.append((sequence, pose))
286
  recent = recent[-6:]
287
+ elapsed = time.time() - started
288
+ if (goal is None or done) and robot.instruction_done(controller.task):
289
+ chat.append({"role": "assistant", "content": f"Done: the simulator confirms \"{controller.task}\" after {elapsed:.0f} s. The robot is stopped."})
290
+ yield player_update(recent, None, stream), chat, status_html("done", controller.task, None, None, None)
291
+ return "done"
292
  if engine.hold_for_planner():
293
  state = "waiting for planner"
294
  else:
295
  state = "steering" if goal else "running"
296
  if done:
297
  state = "planner done, robot continues"
 
298
  rate = (robot.steps - first_step) / elapsed if elapsed > 2 else None
299
  yield player_update(recent, rate, stream), chat, status_html(state, controller.task, goal, SESSION_S - elapsed, rate)
300
  time.sleep(0.25)
301
  if controller.failed:
302
  raise RuntimeError(controller.failure_traceback)
303
+ return "stopped" if controller.stopped else "time up"
304
 
305
 
306
  @spaces.GPU(duration=120)
 
340
  server = threading.Thread(target=controller.serve, daemon=True)
341
  server.start()
342
  try:
343
+ outcome = yield from drive(controller, ctx.policy.inference, robot, path, chat, events)
344
  finally:
345
  controller.stop()
346
  server.join(timeout=10)
347
  strategy.teardown(ctx)
348
+ if outcome != "done":
349
+ chat.append({"role": "assistant", "content": "Time is up." if outcome == "time up" else "Stopped."})
350
+ yield player_update([]), chat, status_html(outcome, controller.task, None, None, None, NEXT_SESSION)
351
  finally:
352
  WORKER_BUSY.release()
353
 
 
430
  with gr.Column(scale=3):
431
  view = gr.HTML(
432
  player_update([]),
433
+ html_template=(
434
+ '<div class="player"><canvas class="screen"></canvas><span class="tag">Scene camera</span>'
435
+ '<span class="tag wrist">Wrist camera</span><div class="loading">Loading the 3D scene</div></div>'
436
+ ),
437
  js_on_load=PLAYER_JS,
438
  elem_id="view",
439
  )
440
+ status = gr.HTML(status_html("idle", "none", None, None, None, NEXT_SESSION.replace("new request", "request").replace("a new 75", "a 75")))
441
  with gr.Column(scale=2):
442
  chat = gr.Chatbot(show_label=False, height=340, layout="panel", elem_id="chat", placeholder="Session log", buttons=[], feedback_options=None)
443
  goal_box = gr.Textbox(placeholder="Request, e.g. warm up the bowl", show_label=False, submit_btn="Steer", elem_id="goal")
libero_robot.py CHANGED
@@ -10,10 +10,13 @@ import threading
10
  import time
11
  from dataclasses import dataclass
12
  from functools import cached_property
 
13
 
14
  import mujoco
15
  import numpy as np
16
  import torch
 
 
17
  from OpenGL import EGL
18
 
19
  from lerobot.envs.libero import LiberoEnv, _get_suite
@@ -41,7 +44,14 @@ class LiberoScene(Robot):
41
  def __init__(self, config: LiberoSceneConfig):
42
  super().__init__(config)
43
  self.config = config
44
- self.language = _get_suite(config.suite).get_task(config.task_id).language
 
 
 
 
 
 
 
45
  self._libero = None
46
  self._raw = None
47
  self._images = None
@@ -111,6 +121,11 @@ class LiberoScene(Robot):
111
  model = self._robosuite.sim.model._model
112
  return [mujoco.mj_id2name(model, mujoco.mjtObj.mjOBJ_BODY, body) or "world" for body in bodies]
113
 
 
 
 
 
 
114
  def _render(self, camera: str) -> np.ndarray:
115
  """Render one camera from any thread.
116
 
@@ -162,6 +177,9 @@ def self_check() -> None:
162
  print(f"connect {time.time() - started:.1f}s")
163
  # As in the Space: connect() on one thread, the control loop on another.
164
  scene.get_observation()
 
 
 
165
  control = threading.Thread(target=control_loop_check, args=(scene,))
166
  control.start()
167
  control.join()
 
10
  import time
11
  from dataclasses import dataclass
12
  from functools import cached_property
13
+ from pathlib import Path
14
 
15
  import mujoco
16
  import numpy as np
17
  import torch
18
+ from libero.libero import get_libero_path
19
+ from libero.libero.envs.bddl_utils import robosuite_parse_problem
20
  from OpenGL import EGL
21
 
22
  from lerobot.envs.libero import LiberoEnv, _get_suite
 
44
  def __init__(self, config: LiberoSceneConfig):
45
  super().__init__(config)
46
  self.config = config
47
+ suite = _get_suite(config.suite)
48
+ self.language = suite.get_task(config.task_id).language
49
+ # Every task of a LIBERO suite shares one scene, so each instruction's goal can be checked in it.
50
+ bddl_files = Path(get_libero_path("bddl_files"))
51
+ self.goals = {
52
+ task.language: robosuite_parse_problem(str(bddl_files / task.problem_folder / task.bddl_file))["goal_state"]
53
+ for task in suite.tasks
54
+ }
55
  self._libero = None
56
  self._raw = None
57
  self._images = None
 
121
  model = self._robosuite.sim.model._model
122
  return [mujoco.mj_id2name(model, mujoco.mjtObj.mjOBJ_BODY, body) or "world" for body in bodies]
123
 
124
+ def instruction_done(self, instruction: str) -> bool:
125
+ """Whether the scene satisfies this instruction's goal, as LIBERO scores it."""
126
+ goal = self.goals.get(instruction)
127
+ return bool(goal) and all(self._robosuite._eval_predicate(state) for state in goal)
128
+
129
  def _render(self, camera: str) -> np.ndarray:
130
  """Render one camera from any thread.
131
 
 
177
  print(f"connect {time.time() - started:.1f}s")
178
  # As in the Space: connect() on one thread, the control loop on another.
179
  scene.get_observation()
180
+ finished = [instruction for instruction in scene.goals if scene.instruction_done(instruction)]
181
+ assert len(scene.goals) == 10 and not finished, f"goals already met at the start: {finished}"
182
+ assert scene.instruction_done(scene.language) == bool(scene._libero._env.check_success())
183
  control = threading.Thread(target=control_loop_check, args=(scene,))
184
  control.start()
185
  control.join()
style.css CHANGED
@@ -13,6 +13,8 @@
13
  #view .player { border-radius: 14px; overflow: hidden; background: #09090b; border: 1px solid #27272a; }
14
  #view .player { position: relative; }
15
  #view .screen { display: block; width: 100%; aspect-ratio: 2 / 1; }
 
 
16
  #view .loading { position: absolute; inset: 0; display: flex; align-items: center; justify-content: center; color: #a1a1aa; }
17
  /* Gradio outlines outputs in orange while an event streams; the session streams the whole time. */
18
  .block.generating, .generating { border-color: #27272a !important; box-shadow: none !important; }
@@ -25,6 +27,8 @@
25
  .pill { font-size: 0.78rem; padding: 3px 10px; border-radius: 999px; background: #27272a; color: #d4d4d8; }
26
  .pill.running, .pill.steering { background: #422006; color: #fbbf24; }
27
  .pill.waiting, .pill.starting { background: #172554; color: #93c5fd; }
 
 
28
  .pill.planner { background: #052e16; color: #4ade80; }
29
 
30
  .section { color: #a1a1aa; font-size: 0.9rem; margin: 14px 2px 2px; }
 
13
  #view .player { border-radius: 14px; overflow: hidden; background: #09090b; border: 1px solid #27272a; }
14
  #view .player { position: relative; }
15
  #view .screen { display: block; width: 100%; aspect-ratio: 2 / 1; }
16
+ #view .tag { position: absolute; top: 8px; left: 8px; font-size: 0.75rem; color: #d4d4d8; background: rgba(9, 9, 11, 0.65); padding: 2px 8px; border-radius: 999px; }
17
+ #view .tag.wrist { left: calc(50% + 8px); }
18
  #view .loading { position: absolute; inset: 0; display: flex; align-items: center; justify-content: center; color: #a1a1aa; }
19
  /* Gradio outlines outputs in orange while an event streams; the session streams the whole time. */
20
  .block.generating, .generating { border-color: #27272a !important; box-shadow: none !important; }
 
27
  .pill { font-size: 0.78rem; padding: 3px 10px; border-radius: 999px; background: #27272a; color: #d4d4d8; }
28
  .pill.running, .pill.steering { background: #422006; color: #fbbf24; }
29
  .pill.waiting, .pill.starting { background: #172554; color: #93c5fd; }
30
+ .pill.done { background: #052e16; color: #4ade80; }
31
+ .pill.stopped, .pill.time { background: #27272a; color: #d4d4d8; }
32
  .pill.planner { background: #052e16; color: #4ade80; }
33
 
34
  .section { color: #a1a1aa; font-size: 0.9rem; margin: 14px 2px 2px; }