Improve arm moves, placing and voice stop and resume

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-27 12:43:29 +09:00
co-authored by Claude Opus 5.5
parent d06fdd7b3f
commit 2e8dc226ff
17 changed files with 812 additions and 116 deletions
+139 -18
View File
@@ -73,6 +73,9 @@ CAM_SCALE_SD = 0.008 # per-scene depth scale error
CAM_NOISE_MM = 2.0 # per-frame noise of a detection's centre
ARM_XY_ERR_M = 0.03 # true arm base origin off the calibrated one by up to this (samples spread 6-19 cm in x)
ARM_YAW_ERR_DEG = 1.0
FURN_SAMPLES = 9 # a table top / chair seat sampled this many points a side for its detection ...
ROUND_SINK_MM = 1300.0 # a round table's box this near the arm base is named "sink" (live 2026-10-20)
FURN_MIN_PART = 0.2 # ... detected when this part of it is in the camera's view
STALL_GAPS = (0.10, 0.25) # m in front of the base where its own safety stop holds it (per scene)
EVENTS = ("no box for it", "the base went", "an obstacle", "plan refused", "straight move to carry",
@@ -151,14 +154,18 @@ def arm_to_world(a):
def rect_dist(p, r):
"""Distance (m) from map point p to rectangle r {c, half, ang} (0 inside)."""
"""Distance (m) from map point p to rectangle r {c, half, ang} or round table {c, r} (0 inside)."""
if "r" in r:
return max(0.0, float(np.linalg.norm(np.asarray(p, float) - r["c"])) - r["r"])
q = rot2(-r["ang"]) @ (np.asarray(p, float) - r["c"])
d = np.maximum(np.abs(q) - r["half"], 0.0)
return float(np.hypot(*d))
def legs(t):
"""Map points (m) of a table's four legs (LEG_IN_M in from its corners)."""
"""Map points (m) of a table's four legs (LEG_IN_M in from its corners); a round table: three under its rim."""
if "r" in t:
return [t["c"] + (t["r"] - LEG_IN_M) * np.array([math.cos(a), math.sin(a)]) for a in (0.5, 2.6, 4.7)]
hx, hy = t["half"][0] - LEG_IN_M, t["half"][1] - LEG_IN_M
return [t["c"] + rot2(t["ang"]) @ [sx * hx, sy * hy] for sx in (-1, 1) for sy in (-1, 1)]
@@ -213,9 +220,8 @@ def render(u, v):
t1, t2 = (lo - rel_o) / rel_d, (hi - rel_o) / rel_d
tn, tf = np.nanmax(np.minimum(t1, t2), 1), np.nanmin(np.maximum(t1, t2), 1)
take(tn, tn <= tf)
cup = W.get("arm_cup")
if cup is not None:
(cx, cy), r, z0, z1 = cup
for cyl in W["arm_discs"] + ([W["arm_cup"]] if W.get("arm_cup") is not None else []):
(cx, cy), r, z0, z1 = cyl # round table tops and the cup: upright cylinders
px, py = o[0] - cx, o[1] - cy
a = D[:, 0] ** 2 + D[:, 1] ** 2
b = 2 * (px * D[:, 0] + py * D[:, 1])
@@ -255,6 +261,11 @@ def measured(p):
def detections():
return cup_seen() + [{**o, "position_mm": [float(v) for v in measured(np.array(o["position_mm"]))]}
for o in furniture(torso_sees, 0.0)]
def cup_seen():
cup = W.get("cup")
if cup is None or W["in_hand"]:
return []
@@ -274,6 +285,47 @@ def detections():
"height_mm": cup["top"] - cup["table"] + float(W["rng"].normal(0, 2.0))}]
def furniture(fov, noise_mm):
"""Tables ("dining table", white unless the scene says) and chairs ("chair", grey) as a camera detects them in
place scenes: the middle of the part of the top in its view, `fov(p)` (a big box's centre moves with the view),
at the top's height; a part below FURN_MIN_PART of the top in view is not detected."""
if not W.get("furniture"):
return []
out, g = [], np.linspace(-1.0, 1.0, FURN_SAMPLES)
for kind, t in [("dining table", t) for t in W["tables"]] + [("chair", b) for b in W["boxes"]]:
if "r" in t:
pts = [t["c"] + t["r"] * np.array([a, b]) for a in g for b in g if a * a + b * b <= 1.0]
else:
pts = [t["c"] + rot2(t["ang"]) @ (np.array([a, b]) * t["half"]) for a in g for b in g]
top = [np.append(world_to_arm(p), t["z"]) for p in pts]
seen = [p for p in top if fov(p)]
if len(seen) < FURN_MIN_PART * len(top):
continue
c = np.mean(seen, axis=0) + np.append(W["rng"].normal(0, noise_mm, 2), 0.0)
size = 2000.0 * (t["r"] if "r" in t else max(t["half"]))
if "r" in t and np.linalg.norm(c[:2]) < ROUND_SINK_MM:
kind = "sink" # live: the round white table up close read "sink"
out.append({"name": kind, "colour": t.get("colour", "white" if kind == "dining table" else "grey"),
"score": 0.8, "box": [0, 0, 1, 1], "position_mm": [float(v) for v in c],
"top_mm": float(t["z"]), "width_mm": size})
return out
def torso_sees(p):
pc = np.linalg.inv(cam_true()) @ np.append(p, 1.0)
if pc[2] <= 0 or np.linalg.norm(pc[:3]) > DET_RANGE_MM:
return False
u, v = INTR["fx"] * pc[0] / pc[2] + INTR["cx"], INTR["fy"] * pc[1] / pc[2] + INTR["cy"]
return EDGE_PX <= u < INTR["width"] - EDGE_PX and EDGE_PX <= v < INTR["height"] - EDGE_PX
def head_sees(p):
pc = np.linalg.inv(head_T(*W["body"][2:])) @ np.append(p, 1.0)
return pc[2] > 0 and np.linalg.norm(pc[:3]) <= DET_RANGE_MM and \
abs(math.degrees(math.atan2(pc[0], pc[2]))) <= HEAD_FOV_DEG[0] and \
abs(math.degrees(math.atan2(pc[1], pc[2]))) <= HEAD_FOV_DEG[1]
def head_T(yaw, pitch):
"""Head camera -> arm transform at head (yaw, pitch): at the head's centre, looking ahead (arm +y) turned by yaw
(+ left) and tilted by pitch (+ up). Its depth frames are not simulated (camview.depth gives None)."""
@@ -287,7 +339,12 @@ def head_T(yaw, pitch):
def head_detections():
"""The cup as the head camera sees it (positions in the arm frame, HEAD_NOISE_MM), inside its field of view."""
"""The cup (and in place scenes the furniture) as the head camera sees it (positions in the arm frame,
HEAD_NOISE_MM), inside its field of view."""
return head_cup() + furniture(head_sees, HEAD_NOISE_MM)
def head_cup():
cup = W.get("cup")
if cup is None or W["in_hand"]:
return []
@@ -307,7 +364,9 @@ def refresh():
yaw, org = arm_true()
x, y, th = W["base"]
boxes = []
for r, z0, z1 in [(t, t["z"] - TABLE_THICK_MM, t["z"]) for t in W["tables"]] + \
W["arm_discs"] = [(world_to_arm(t["c"]), t["r"] * 1000.0, t["z"] - TABLE_THICK_MM, t["z"])
for t in W["tables"] if "r" in t]
for r, z0, z1 in [(t, t["z"] - TABLE_THICK_MM, t["z"]) for t in W["tables"] if "r" not in t] + \
[(b, FLOOR_Z, b["z"]) for b in W["boxes"]]:
c = world_to_arm(r["c"])
a = math.radians(r["ang"] - math.degrees(th) - yaw)
@@ -381,9 +440,11 @@ def f_open(wait=True):
bottom = g[2] + held["below"] - held["h"] # grasp point is `below` under its top
xy = arm_to_world(g)
on = [t for t in W["tables"] if rect_dist(xy, t) == 0.0]
edge = lambda t: t["r"] - float(np.linalg.norm(xy - t["c"])) if "r" in t else \
-max(np.abs(rot2(-t["ang"]) @ (xy - t["c"])) - t["half"])
W["rec"]["released"] = {"xy": [round(float(v), 3) for v in xy],
"edge_m": round(min((-max(np.abs(rot2(-t["ang"]) @ (xy - t["c"])) - t["half"])
for t in on), default=-1.0), 3),
"edge_m": round(min((edge(t) for t in on), default=-1.0), 3),
"table": next((W["tables"].index(t) for t in on), None),
"above_table_mm": round(float(bottom - on[0]["z"]), 1) if on else None}
W["hand"].update(holding=False, closed=False)
refresh()
@@ -601,6 +662,15 @@ def pick_at(x, y, top, grip=80.0, gap=0.10, height=110.0, variant="table", stall
"tables": [table], "boxes": boxes, "stall_gap": stall_gap, "err_seed": err_seed}
def place_at(tables, boxes=(), on=None, stall_gap=0.25, err_seed=3):
"""A fixed place scene: `tables` / `boxes` (chairs) as in make_place, map frame m (the base at the origin facing
+x), the cup held as after a pick from a table at -328 mm; `on`: what the command named."""
return {"kind": "place", "i": 0, "seed": 0, "bearing": 0.0, "dist_mm": 0, "variant": "fixed", "other": None,
"held": {"grip": 80.0, "h": 110.0, "table0": -328.0}, "tables": [dict(t) for t in tables],
"boxes": [dict(b) for b in boxes], "stall_gap": stall_gap, "err_seed": err_seed,
**({"on": on} if on else {})}
def make_place(i, seed):
rng = random.Random(seed * 200003 + i)
for _ in range(200):
@@ -618,11 +688,49 @@ def make_place(i, seed):
other = None
if rng.random() < 0.25: # another cup already on it, near its front edge
other = [float(v) for v in table["c"] - n * (depth / 2 - 0.12)]
return {"kind": "place", "i": i, "seed": seed, "bearing": round(bearing, 1), "dist_mm": round(near * 1000),
"variant": "table" + ("+cup" if other else ""),
"held": {"grip": round(rng.uniform(72, 92), 1), "h": round(h, 1), "table0": -403.0 + 75.0},
"tables": [{**table, "c": [float(v) for v in table["c"]]}], "boxes": [], "other": other,
"stall_gap": rng.choice(STALL_GAPS), "err_seed": rng.randrange(1 << 30)}
sc = {"kind": "place", "i": i, "seed": seed, "bearing": round(bearing, 1), "dist_mm": round(near * 1000),
"variant": "table" + ("+cup" if other else ""),
"held": {"grip": round(rng.uniform(72, 92), 1), "h": round(h, 1), "table0": -403.0 + 75.0},
"tables": [{**table, "c": [float(v) for v in table["c"]]}], "boxes": [], "other": other,
"stall_gap": rng.choice(STALL_GAPS), "err_seed": rng.randrange(1 << 30)}
return place_extras(sc, n, near, width, random.Random(seed * 300007 + i))
def place_extras(sc, n, near, width, rng):
"""What the live place of 2026-10-27 had (a separate random stream: the scenes above stay as they were): a round
table, a chair beside the table (its seat ~20 cm lower), "the white dining table" said by name, another (black,
higher) table elsewhere."""
t = sc["tables"][0]
side = np.array([-n[1], n[0]])
if rng.random() < 0.25:
r = rng.uniform(0.35, 0.6)
t = {"c": [float(v) for v in n * (near + r) + side * rng.uniform(-0.15, 0.15)], "r": r, "z": t["z"]}
sc["tables"] = [t]
sc["variant"] += "+round"
W["tables"], W["boxes"] = [{**t, "c": np.array(t["c"])}], []
if rng.random() < 0.4:
for _ in range(20):
c = n * (near + rng.uniform(-0.3, 0.1)) + side * rng.choice((-1, 1)) * (width / 2 + rng.uniform(0.3, 0.5))
chair = {"c": c, "half": (0.22, 0.22), "ang": rng.uniform(0, 90), "z": t["z"] - rng.uniform(180, 260)}
if np.linalg.norm(c) > 0.6 and rect_dist(c, W["tables"][0]) > 0.25:
sc["boxes"] = [{**chair, "c": [float(v) for v in c], "half": list(chair["half"])}]
sc["variant"] += "+chair"
break
if rng.random() < 0.35:
sc["on"] = {"name": "dining table", "colour": "white"}
sc["variant"] += "+named"
if rng.random() < 0.5:
for _ in range(20):
a = math.atan2(n[1], n[0]) + math.radians(rng.choice((-1, 1)) * rng.uniform(90, 180))
m = np.array([math.cos(a), math.sin(a)])
c = m * rng.uniform(0.9, 1.8)
grey = {"c": c, "half": (0.3, 0.4), "ang": math.degrees(a), "z": rng.uniform(-300, -260),
"colour": "black"} # (grey would match "white": one light colour)
if rect_dist(c, W["tables"][0]) > 0.6 and rect_dist((0, 0), grey) > 0.45:
sc["tables"].append({**grey, "c": [float(v) for v in c], "half": list(grey["half"])})
sc["variant"] += "+other table"
break
return sc
def setup(sc, cam=1.0):
@@ -632,7 +740,8 @@ def setup(sc, cam=1.0):
W.update(lines=lines, in_hand=False, base=np.zeros(3), body=[0.0, WAIST_REF, 0.0, -5.0], nav=None,
joy={"v": 0.0, "t": 0.0, "want": 0.0, "start": np.zeros(3)},
J=list(motion.poses()["look"]), hand={"holding": False, "closed": False}, rng=nr,
tables=[{**t, "c": np.array(t["c"]), "half": np.array(t["half"])} for t in sc["tables"]],
tables=[{**t, "c": np.array(t["c"]), **({"half": np.array(t["half"])} if "half" in t else {})}
for t in sc["tables"]], furniture=sc["kind"] == "place",
boxes=[{**b, "c": np.array(b["c"]), "half": np.array(b["half"])} for b in sc["boxes"]],
stall_gap=sc["stall_gap"], col=COLUMN_BASE_M, rec={"moves": []})
e = nr.normal(0, CAM_ROT_SD_DEG * cam, 3)
@@ -720,9 +829,11 @@ def run_scene(sc, cam=1.0):
fetch._pick_here({"object": "cup", "colour": None}, None)
rec["result"] = "ok" if W["hand"]["holding"] else "not holding"
else:
fetch._put_down(None)
fetch._put_down(None, on=sc.get("on"))
rel = rec.get("released")
rec["result"] = "ok" if rel and rel["edge_m"] >= 0.0 else "released off a table" if rel else "not released"
rec["result"] = "ok" if rel and rel["edge_m"] >= 0.0 and rel["table"] == 0 else \
"on another table" if rel and rel["edge_m"] >= 0.0 else \
"released off a table" if rel else "not released"
except fetch.Stopped:
rec["result"] = "stopped"
except (fetch.FetchError, skills.SkillError) as e:
@@ -893,6 +1004,15 @@ def report(rows, path, title, mtimes):
f"{sum(r['still'] > 0 for r in places)} scenes; repeated: {sum(r['repeats'] for r in places)}; tried again "
f"later from the same spot: {sum(r.get('loops', 0) for r in places)} in "
f"{sum(r.get('loops', 0) > 0 for r in places)} scenes", ""]
out += ["| scenes | ok |", "|---|---|"]
for tag in ("plain", "round", "chair", "named", "other table"):
sel = [r for r in places if (tag in r["variant"]) if tag != "plain"] if tag != "plain" else \
[r for r in places if "+" not in r["variant"].replace("+cup", "")]
if sel:
out.append(f"| {tag} | {100 * sum(r['result'] == 'ok' for r in sel) / len(sel):.0f}% ({len(sel)}) |")
navs = [sum(m[0] == "nav" for m in r["moves"]) for r in places]
out += ["", f"- navigation drives: {sum(navs)} in {sum(n > 0 for n in navs)} scenes, at most {max(navs)} in one; "
f"base moves in all: {sum(r['base_moves'] for r in places)}", ""]
rel = [r["released"] for r in places if r.get("released") and r["released"]["above_table_mm"] is not None]
if rel:
hz = [x["above_table_mm"] for x in rel]
@@ -952,7 +1072,8 @@ def main():
scenes = [s for s in scenes if (s["kind"], str(s["i"])) in want]
for s in scenes: # numpy -> plain values for the records
for t in s["tables"] + s["boxes"]:
t["half"] = [float(v) for v in t["half"]]
if "half" in t:
t["half"] = [float(v) for v in t["half"]]
logs = ROOT / "logs"
jl, md = logs / f"pick_sweep_{a.round}.jsonl", logs / f"pick_sweep_{a.round}.md"
stamp = mtimes()
+10 -1
View File
@@ -22,6 +22,9 @@ motion.poses = lambda: dict(POSES)
head_cam.head_centre = lambda: head["centre"]
gripper.state = lambda: {"holding": False, "ai": [160]}
arm_route.log = fetch.log = lambda *a: None
LOOK_LIVE = [-239.2, -88.4, -29.5, 200.0, 81.4, 158.3] # the taught look: its links clear the head
assert arm_route.link_clearance(LOOK_LIVE, LOOK_LIVE, np.array([-93.0, -19.9, 356.1])) > arm_route.LINK_HEAD_CLEAR_MM
arm_route.links = lambda j: [] # toy kinematics: no links, the gripper is checked
motion.SETTLE_S = 0.05 # quick here; the pause itself is checked below
@@ -41,6 +44,8 @@ class FakeArm:
if name == "kine_forward":
j = a["jointPosition"]
return {"cartPosition": [30 * j[0], 30 * j[1], 30 * j[2]] + list(skills.GRASP_RPY), "errorCode": "0"}
if name == "kine_inverse":
return {"errorCode": "-1", "errorMsg": "no IK in the toy"}
if name == "get_data":
return {"joint_actual_position": list(self.j), "inpos": True}
if name == "get_motion_state":
@@ -105,7 +110,10 @@ assert arm_route.goto("carry") == ["look", "carry"] and fake.sent == [POSES["loo
fake = use([20.5, 0, 0, 0, 0, 0]) # within EXACT_DEG of carry: straight on
assert arm_route.goto("give") == ["give"]
# ---------- far from every pose, or a move that passes the head: refused, nothing sent ----------
# ---------- far from every pose: one checked joint move to the nearest pose, slow; none passes: refused ----------
fake = use([60.0, 60.0, 0, 0, 0, 0])
assert arm_route.goto("carry") == ["look", "carry"] and fake.sent == [POSES["look"], POSES["carry"]], fake.sent
head["centre"] = np.array([1800.0, 1800.0, 0.0]) # the gripper is at the head: every way refused
fake = use([60.0, 60.0, 0, 0, 0, 0])
refused(arm_route.UNKNOWN, arm_route.goto, "look")
try:
@@ -114,6 +122,7 @@ try:
except fetch.FetchError as e:
assert e.args == arm_route.UNKNOWN
assert fake.sent == []
head["centre"] = FAR
fake = use([60.0, 60.0, 0, 0, 0, 0]) # a task's own way back from the table: straight
assert arm_route.goto("look", leaf=True) == ["look"]
head["centre"] = np.array([300.0, 0.0, 0.0]) # on the way look -> carry (flange x 0 -> 600)
+1 -1
View File
@@ -95,7 +95,7 @@ for name in ("follow_stop", "voice_setting", "fixed_answer", "drive_words", "mis
L.fetch_status = lambda: None
L.keep_listening = lambda: None
L.fetch_say = lambda *a: None
L.stop_all = lambda: rec("stop")
L.stop_all = lambda text="": rec("stop")
L.chain_request = lambda text, plan=None: rec("chain", [[k, w] for k, w, _ in plan])
L.mission_request = lambda text, read=None: rec("talk") if read[1] else rec("steps", read[0])
L.hand_command = hand
+4 -1
View File
@@ -549,6 +549,9 @@ st = run(fetch.place, None, {"name": "chair", "colour": "orange"})
assert st["status"] == "done" and ("place",) in calls, st["log"][-4:]
# "the grey table": the cameras call it a white sink (flat, table height) -> on it; nothing named in view -> any table
sink = {"name": "sink", "colour": "white", "x": -160.0, "y": 760.0, "top_mm": -400.0, "seen": 8, "spread": 1.0}
flat_fixed = skills.flat_points # the table stands still: in the arm frame it moves with the lift
skills.flat_points = lambda pts, guess_z=-400.0, camera="torso", T=None: \
[(p[0], p[1], surface["z"] + 75.0 - body["lift"]) for p in pts]
for seen in ([chair, sink], []):
reset()
hand.update(holding=True, closed=True)
@@ -563,7 +566,7 @@ for seen in ([chair, sink], []):
instead = "white sink" if seen else "table" # not exactly what was said: the closest (white = grey, a
assert any(f"couldn't find the grey table, so I put it on the {instead} here" in w for w in said), said # flat
assert seen or not any("sink" in l for l in this), this # furniture word), after the one whole search; else any
skills.look, skills.on_table = real_look, real_on_table
skills.look, skills.on_table, skills.flat_points = real_look, real_on_table, flat_fixed
fetch._set(holding=False, status="idle")
hand.update(holding=False, closed=False)
+56
View File
@@ -0,0 +1,56 @@
"""Self-check of the mission step {"do": "carry"} (tests/pick_sweep.py simulator, no robot): a pick stopped right after
the grasp leaves the cup just above the table; the step lifts it straight up and brings it to look, saying nothing:
python tests/test_fetch_carry.py"""
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from tests import pick_sweep as ps
ps.install()
fetch, skills, motion = ps.fetch, ps.skills, ps.motion
class Halt(Exception):
pass
def halt_up(what, pose): # the pick is stopped before its straight move up: holding, 3 cm up
if what == "up":
raise Halt()
REAL_LINE(what, pose)
REAL_LINE = skills._line
for name, sc in (("straight", ps.pick_at(-96, 598, -260)), ("turned", ps.pick_at(260, 722, -186))):
ps.setup(sc, 0.0)
skills._line = halt_up
try:
fetch._pick_here({"object": "cup", "colour": None}, None)
raise AssertionError("the pick was not stopped")
except Halt:
pass
skills._line = REAL_LINE
assert ps.W["hand"]["holding"] and fetch._state["holding"], name
z0 = ps.kin.pose(ps.W["J"])[2]
assert not fetch._at_pose("look"), name
said, ups = [], []
skills._line = lambda what, pose: (ups.append(pose[2]), REAL_LINE(what, pose))
fetch._do_step({"do": "carry"}, lambda en, ko=None: said.append(en))
skills._line = REAL_LINE
assert fetch._at_pose("look") and ps.W["hand"]["holding"], name
assert ups and ups[0] >= z0 + skills.ABOVE_MM - skills.LIFT_MM - 1.0, (name, z0, ups) # straight up first
assert not said, said
fetch._do_step({"do": "carry"}, lambda en, ko=None: said.append(en)) # at look already: nothing moves
assert fetch._at_pose("look") and not said
print(name, "lifted", round(ups[0] - z0), "mm, then to look")
fetch._state.update(holding=False)
try:
fetch._carry_held()
raise AssertionError("carried with an empty hand")
except fetch.FetchError:
pass
print("fetch carry ok")
+3 -4
View File
@@ -205,9 +205,8 @@ only_chair = [white_t, {**grey_t, "name": "chair", "names": ["chair"]}]
assert fetch._support(brain.place_on("put it on the black table"), only_chair) is None
usable, went, said = [], [], []
fetch._usable(usable, only_chair)
real_go_to, real_near = fetch._go_to, fetch._place_near
fetch._go_to = lambda thing, goal, tried, holding=False: went.append((round(thing["x"]), round(thing["y"])))
fetch._place_near = lambda top0, tried: True
real_go_to, real_kept = fetch._go_to, fetch._place_kept
fetch._place_kept = lambda top0, kept, tried: went.append(tuple(round(v) for v in fetch._kept_at(kept)[:2])) or True
fetch._state.update(holding=True, held_object={"object": "cup", "colour": "grey"})
fetch._put_instead(-260.0, brain.place_on("put it on the black table"), "black table", usable, set(),
lambda en, ko: said.append(en))
@@ -217,7 +216,7 @@ went.clear(); said.clear()
fetch._put_instead(-260.0, brain.place_on("put it on the lower red sofa"), "red sofa", usable, set(),
lambda en, ko: said.append(en))
assert went == [(300, 900)] and "on the black chair here" in said[0], (went, said) # same kind, the lower one
fetch._go_to, fetch._place_near = real_go_to, real_near
fetch._place_kept = real_kept
fetch._state.update(holding=False, held_object=None)
skills.flat_points = flat
+222
View File
@@ -0,0 +1,222 @@
"""Self-check of the owner's live test of 2026-10-27 (logs/lumi.log 10:45-11:19), no robot, no audio, no LLM:
python tests/test_mission_name.py
1. While a mission picks / places / carries, only words with Lumi's name halt it ("Lumi, wait", "루미 멈춰"); talk
around it ("네, 안녕하세요.", "Very nice.", "Okay.") neither halts nor resumes it. Stop words and safety words from
anyone still stop at once. "Lumi, keep going" / "루미 계속해" after a stop does the rest of the job.
2. "Lumi stop, not the apple, take the cup": stopped, then the new order is done. Holding after a stop: put it back /
on the table / down again, at every speech level, English and Korean.
3. The dashboard's Command box: "come to me" reads back as "Come to me." and, typed, comes to the person in view."""
import re
import threading
import time
re._MAXCACHE = 100000
from assistant import lumi
from tasks import fetch
M = ["home", "dock2", "exit", "final"] + [f"p{i}" for i in range(1, 11)]
TAKE = [{"do": "pick", "object": "cup", "colour": None}] # the dashboard's "Take the cup"
DELIVERY = TAKE + [{"do": "go", "to": "p6"}, {"do": "give", "person": "James"}]
done = []
run = {"status": "running", "paused": False, "steps": TAKE, "log": [], "holding": False, "since": time.time()}
def _stop():
done.append("stop")
run.update(status="stopped", since=time.time())
fetch.state = lambda: {"status": run["status"], "task": {"steps": run["steps"], "sender": None}, "log": run["log"],
"holding": run["holding"], "since": run["since"]}
fetch.pause = lambda: (done.append("pause"), run.update(paused=True), True)[-1] if run["status"] == "running" else False
fetch.paused = lambda: run["paused"]
fetch.resume = lambda: (done.append("resume"), run.update(paused=False))
fetch.stop = _stop
fetch.end = lambda timeout=5.0: (done.append("end"), run.update(status="stopped"))
fetch.replace = lambda steps, say=None: done.append(("replace", steps))
fetch.proceed = lambda: done.append("proceed")
fetch.run_steps = lambda steps, say=None, sender=None: done.append(("run", steps))
fetch.check_hand = lambda: run["holding"]
fetch.held_name = lambda lang="en": "the cup" if lang == "en" else "컵"
lumi.agv.cancel = lambda: done.append("agv cancel")
lumi.mouth.say = lambda text, **k: done.append(("say", text))
class Track:
def __init__(self, tid):
self.id, self.person, self.angle, self.distance, self.greeted = tid, None, -9.0, 2.35, False
class Brain:
history = []
def fresh(steps=TAKE, current=None, holding=False, log=()):
L = lumi.Lumi.__new__(lumi.Lumi)
L.markers, L.lang, L.current, L.mission_hold, L.asked_go_on = M, "en", current, None, False
L.patrol, L.chain_stop, L.brain, L.pending_text = None, threading.Event(), Brain(), None
L.last_activity, L.said = time.time(), []
L.fetch_say = lambda en, ko: L.said.append(en)
L.keep_listening = lambda: None
L.act = lambda action, target: done.append(("act", action))
L.head_rest = lambda: None
done.clear()
run.update(status="running", paused=False, steps=steps, log=list(log), holding=holding, since=time.time())
return L
bad = []
def check(ok, what):
if not ok:
bad.append(what)
print("WRONG", what)
# ---------- 1. talk around Lumi on a pick: never halts it, never resumes it ----------
for current in (None, Track(97)):
L = fresh(current=current)
L.last_talk = time.time() # someone talked a moment ago (10:56:01 "네.")
for said in ("네, 안녕하세요.", "네.", "Very nice.", "Okay.", "네, 네, 네, 네, 네.", "hello", "hi there", "excuse me",
"sorry", "what are you doing?", "그렇죠.", "I'm Tom.", "the robot is slow", "로봇 신기하다", "hey"):
L.mission_talk(said)
check(not done and not L.said, f"plain talk {said!r} halted or answered: {done} {L.said}")
for said in ("come to me", "give me that", "go to p3"): # an order without the name: not to Lumi on a job
L.mission_talk(said)
check("end" not in done and "pause" not in done, f"{said!r} without the name ended the job: {done}")
# said to Lumi by name: halts it
for said in ("Lumi, wait", "Hi Lumi!", "루미야 잠깐", "루미야, 뭐 해?", "Lumi, what are you doing?", "hey Lumi"):
L = fresh()
L.mission_talk(said)
check(done[:1] == ["pause"], f"{said!r} did not halt it: {done}")
# stop and safety words from anyone, with or without the name: at once, as before
for said in ("stop", "Stop it.", "멈춰", "그만", "Lumi, stop", "루미 멈춰", "stop Lumi"):
L = fresh()
check(L.mission_talk(said) and "stop" in done, f"{said!r} did not stop it: {done}")
for said in ("watch out!", "아파", "my hand!", "위험해"):
L = fresh()
check(L.mission_talk(said) and "pause" in done and L.mission_hold == "safety", f"{said!r} no safety halt: {done}")
# halted by name, then "Lumi, keep going" at every level: goes on
GO_EN = ["Lumi, keep going", "Lumi, go on", "Lumi, continue", "Lumi, carry on", "okay Lumi, you can go on",
"Lumi, keep going please", "Lumi, resume", "Lumi, finish the job"]
GO_KO = ["루미 계속해", "루미야 계속해", "루미야 계속해요", "루미야 계속하세요", "루미야 계속하십시오", "루미야 계속해 줘",
"루미야 계속해 주세요", "루미 계속 진행해", "루미야 하던 거 계속해", "루미야 마저 해", "루미야 마저 하세요"]
for said in GO_EN + GO_KO:
L = fresh()
L.mission_talk("Lumi, wait")
check(L.mission_talk(said) and done[-1] == "resume", f"{said!r} did not go on: {done}")
# ---------- 1b. "Lumi, stop", then "Lumi, keep going": the rest of the job is done ----------
for said in GO_EN + GO_KO:
for steps_, log_, holding, want in ((TAKE, ["10:46:01 step 1/1: {'do': 'pick'}"], False, TAKE),
(DELIVERY, ["step 1/3: pick", "step 2/3: go"], True, DELIVERY[1:]),
(DELIVERY, ["step 1/3: pick"], True, # held: lifted, then on
[{"do": "carry"}] + DELIVERY[1:]),
(DELIVERY, ["step 1/3: pick"], False, DELIVERY)):
L = fresh(steps_, holding=holding, log=log_)
L.mission_talk("Lumi, stop")
check(not L.mission_running() and L.resume_stopped(said) and done[-1] == ("run", want),
f"stop, then {said!r} ({log_[-1]}, holding {holding}): {done[-1]} not {want}")
L = fresh(TAKE, holding=True, log=["step 1/1: pick"]) # "take the cup" stopped with the cup in the hand
L.mission_talk("Lumi, stop")
check(L.resume_stopped("Lumi, keep going") and done[-1] == ("run", [{"do": "carry"}])
and "the cup" in L.said[-1], f"held, nothing left: lifted to look, then asked: {done} {L.said}")
for said in ("keep going", "계속해", "Lumi, keep going?", "did you keep going, Lumi?"): # no name, or a question
L = fresh(DELIVERY, log=["step 1/3: pick"])
L.mission_talk("stop")
check(not L.resume_stopped(said), f"{said!r} after a stop restarted the job")
L = fresh(log=["step 1/1: pick"]) # long after the stop: not taken
L.mission_talk("Lumi, stop")
L.stopped_mission = L.stopped_mission[:2] + (time.time() - lumi.RESUME_S - 1,)
check(not L.resume_stopped("Lumi, keep going"), "keep going long after the stop restarted the job")
# ---------- 2. a stop with a new order after it: stopped, then the new order ----------
for said, want in (("Lumi stop, not the apple, take the cup", ("pick", "cup")),
("Lumi, stop. Take the cup instead.", ("pick", "cup")),
("루미 멈춰, 사과 말고 컵 집어", ("pick", "cup")),
("루미야 멈춰 그거 말고 컵 집어 주세요", ("pick", "cup")),
("stop Lumi, put it back", ("put", "back")),
("루미 멈춰, 제자리에 놔", ("put", "back"))):
L = fresh(log=["step 1/1: pick"])
check(L.mission_talk(said) and "stop" in done and "end" in done and L.pending_text, f"{said!r}: {done} {L.pending_text!r}")
got = lumi.route(L.pending_text or "", M, Brain(), holding=False, chain_ok=False)
check(got == ("quick", want), f"{said!r}: then {L.pending_text!r} read {got}, not {want}")
check(L.stopped_mission is None, f"{said!r}: the old job is still kept to go on with")
for said in ("Stop it.", "Lumi, stop!", "stop, stop", "루미야 멈춰 주세요", "stop, where are you going?",
"Lumi, stop, you're going to hit the table", "stop, don't take the cup"): # nothing to do after it
L = fresh()
L.mission_talk(said)
check(not L.pending_text, f"{said!r}: {L.pending_text!r} taken as an order after the stop")
# holding after a stop: put it back / on the table / down again, every level, English and Korean
EN_LEVELS = ["{x}", "please {x}", "{x}, please", "can you {x}?", "could you {x}?", "would you {x}?", "will you {x}?",
"could you please {x}?", "I need you to {x}", "hey Lumi, {x}", "Lumi, {x} now", "go ahead and {x}", "kindly {x}",
"if you don't mind, {x}", "do me a favor and {x}", "{x} pls", "Lumi could you {x}"]
def ko_levels(v, h):
return [v, f"{v} 줘", f"{v}요", f"{v} 주세요", f"{h}세요", f"{h}십시오", f"{v} 주십시오", f"{v} 주시겠어요?",
f"{v} 주시겠습니까?", f"{v} 줄래?", f"{v} 주실래요?", f"{v} 주게", f"{v} 주이소", f"{v} 도", f"{v} 주라",
f"{v} 주시면 감사하겠습니다", f"{v} 주면 안 될까요?", f"{v} 주실 수 있나요?", f"{v}줘", f"{v} 줘 봐", f"{v} 주시오"]
def put_down(text):
kind, data = lumi.route(text, M, Brain(), holding=True, chain_ok=False)
return kind == "quick" and data[:2] == ("put", "back") or kind == "hand" and data[0][0] == "place"
HELD = [f.format(x=x) for x in ("put it back", "put it on the table", "put it down again", "put it down") for f in EN_LEVELS]
HELD += [w.format(f) for w, v, h in (("제자리에 {}", "놔", "놓으"), ("다시 {}", "놔", "놓으"), ("테이블에 {}", "놔", "놓으"),
("다시 {}", "내려놔", "내려놓으"), ("원래 자리에 {}", "갖다 놔", "갖다 놓으"))
for f in ko_levels(v, h)]
for text in HELD:
check(put_down(text), f"holding: {text!r} does not put it down")
check(lumi.route("take the apple", M, Brain(), holding=False, chain_ok=False) == ("quick", ("pick", "apple")),
"then another thing is not taken")
# ---------- 3. the Command box: "come to me" ----------
from api import server
server.agv.markers = lambda: M
for text, want in (("come to me", "Come to me."), ("이리 와", "Come to me."), ("follow me", "Follow me.")):
got = server.task_parse(server.ParseBody(text=text))
check(got["sentence"] == want and got["action"] == "command", f"box {text!r}: {got['sentence']!r}")
# typed: no voice this turn, so the person in view is the one (11:18:02: a stale voice direction, nobody found)
came = []
L = fresh()
run.update(status="idle", steps=[])
L.voice_angle, L.voice_trusted, L.current = 60.0, True, None # the last voice, long ago, from the side
class Vision:
camera = "head"
tracks = [Track(97)]
lock = threading.Lock()
def present(self, t):
return t in self.tracks
def near_angle(self, angle, max_diff=20):
return next((t for t in self.tracks if abs(t.angle - angle) <= max_diff), None)
def only_person(self):
return self.tracks[0]
L.vision = Vision()
L.turn_head = lambda yaw: None
L.come_to = lambda track, say=False: came.append(track if track is not None else L.find_caller(L.voice_angle, L.voice_trusted))
L.answer = lambda text: L.come_to(L.current, say=True)
L.typed("come to me")
check(came and came[0] is not None and came[0].id == 97, f"typed come to me: came to {came}")
check(lumi.ears.understood(), "typed words taken as not understood (11:22:46 'look at front': 'say it again')")
L = fresh() # typed in the box on a job: to Lumi
L.answer = lambda text: L.mission_talk(text)
L.typed("come to me")
check("end" in done, f"typed 'come to me' on a job was ignored: {done}")
if bad:
raise SystemExit(f"{len(bad)} wrong")
print(f"mission name ok ({len(HELD)} held commands)")
+1 -1
View File
@@ -43,7 +43,7 @@ ok, said = talk(L, "what are you doing?")
assert not ok
ok, said = talk(L, "okay, you can go")
assert ok and done[-1] == "resume" and L.mission_hold is None, done
ok, said = talk(L, "go to p3") # anyone's new task: the mission ends with one line, then it is done
ok, said = talk(L, "Lumi, go to p3") # a new task said to Lumi: the mission ends with one line, then it is done
assert ok is False and done[-1] == "end" and said == "Okay, I've stopped my task.", (done, said)
L = fresh()
ok, said = talk(L, "Lumi, I'm James, give it to me") # the person it is for
+26
View File
@@ -48,4 +48,30 @@ for group, scenes in (("must", MUST), ("physical", PHYSICAL), ("open", OPEN)):
elif group == "physical" and (r["result"] == "ok" or ps.way_exists(sc) is not None):
bad.append((name, "no longer physical", r["result"]))
assert not bad, bad
# ---------- places, the live run of 2026-10-27 (named white table, a higher grey one, a chair seat at -549) ----------
P = lambda deg, m: [m * ps.math.cos(ps.math.radians(deg)), m * ps.math.sin(ps.math.radians(deg))]
WHITE = {"name": "dining table", "colour": "white"}
SEAT = {"c": P(-55, 1.3), "half": [0.22, 0.22], "ang": 10.0, "z": -549.0}
PLACES = { # name: (scene, must end on table 0)
"10:55 the white table by name, far right": (ps.place_at(
[{"c": P(-70, 1.9), "r": 0.5, "z": -330.0},
{"c": P(-120, 1.6), "half": [0.3, 0.4], "ang": -120.0, "z": -267.0, "colour": "black"}], [SEAT], WHITE), True),
"10:55 the same, the base stops 0.1 m early": (ps.place_at(
[{"c": P(-70, 1.9), "r": 0.5, "z": -330.0},
{"c": P(-120, 1.6), "half": [0.3, 0.4], "ang": -120.0, "z": -267.0, "colour": "black"}], [SEAT], WHITE,
stall_gap=0.1), True),
"10:59 a chair seat, no table": (ps.place_at([], [{**SEAT, "c": P(-20, 1.1)}]), False),
"10:59 a chair seat ahead": (ps.place_at([], [{**SEAT, "c": P(0, 1.1)}]), False),
"11:13 the round table ahead, flush": (ps.place_at([{"c": P(0, 0.95), "r": 0.5, "z": -330.0}]), True),
}
for name, (sc, must) in PLACES.items():
r = ps.run_scene(sc, 1.0)
navs = sum(m[0] == "nav" for m in r["moves"])
drives = sum(m[0] == "nav" or m[0] == "straight" and m[1] > 0 for m in r["moves"]) # towards something
print(f"place {name:44s} {r['result']:8s} moves {[m[:3] for m in r['moves']]} {r.get('why') or ''}")
if must and r["result"] != "ok" or not must and (r.get("released") or drives) or navs > ps.fetch.PLACE_NAV_MAX \
or r["result"] in ("exception", "timeout"):
bad.append((name, r["result"], r.get("why"), r["moves"]))
assert not bad, bad
print("pick sweep scenes ok")
+4 -3
View File
@@ -135,9 +135,10 @@ wave.wave()
assert a.sent[:4] == [LOOK, POSES["wave_out"], top, swing], a.sent
del POSES["carry"]
# ---------- an unknown start (after free drive: the wrist the other way round), base, power ----------
# ---------- an unknown start (after free drive: the wrist the other way round): joins by a checked move; power ----------
a = use(FakeArm([-249.1, -90.9, -29.1, 14.6, -83.8, -33.0]))
refused(wave.UNKNOWN_POSE)
wave.wave()
assert a.sent[0][1:3] == LOOK[1:3] and swing in a.sent, a.sent
use(FakeArm(LOOK, enable=False))
refused(wave.OFF)
base["move_status"] = "running"
@@ -153,7 +154,7 @@ POSES["wave"] = swing
del POSES["wave_out"]
refused(wave.NOT_TAUGHT)
POSES["wave_out"] = [-50.0, 0.0, 0.0, 0.0, 0.0, 0.0]
assert a.sent == []
assert arm.cmd.sent == [] # nothing sent for any refusal
# ---------- the assistant: a greeting sends no arm command; a wave asked while holding is refused aloud ----------
calls = []