diff --git a/README.md b/README.md index 1476584..27aa926 100644 --- a/README.md +++ b/README.md @@ -57,8 +57,10 @@ action is answered, never executed. **Perception.** Two RGB-D cameras let Lumi detect, track and recognise people, read clothing, gestures and held objects, and measure objects on a table in 3D. Visual answers always come from a fresh camera frame. -**Voice.** A six-microphone array locates the speaker, filters noise and music, and ignores Lumi's own voice. -Speech is recognised and synthesised on the GPU with sub-second latency. +**Voice.** A six-microphone array locates the speaker; Lumi turns its head, +and its body when needed, to whoever it talks with and keeps facing them. It filters noise and music, ignores its own +voice, and hears a stop word even while it speaks or sings. Speech is recognised and synthesised on the GPU with +sub-second latency. **Mobility.** Lumi navigates any mapped floor, moves and turns by spoken distances and angles, follows a person, recovers from a blocked path, and returns to its charging dock. @@ -241,8 +243,9 @@ Lumi는 쿳션이 개발한 **JAKA Lumi** 모바일 매니퓰레이터용 소프 **인식.** 두 대의 RGB-D 카메라로 사람을 감지·추적·식별하고, 옷차림과 제스처, 손에 든 물건을 알아보며, 테이블 위 물체를 3차원으로 측정합니다. 시각에 관한 답변은 항상 최신 카메라 영상을 기준으로 합니다. -**음성.** 6채널 마이크 어레이로 말하는 사람의 방향을 찾고, 소음과 음악을 걸러 내며, 자기 목소리는 무시합니다. -음성 인식과 음성 합성은 GPU에서 1초 이내의 지연으로 처리됩니다. +**음성.** 6채널 마이크 어레이로 말하는 사람의 방향을 찾고, 대화하는 사람 쪽으로 머리를, 필요하면 몸을 +돌려 계속 바라봅니다. 소음과 음악을 걸러 내고 자기 목소리는 무시하며, 말하거나 노래하는 중에도 멈춤 명령을 +알아듣습니다. 음성 인식과 음성 합성은 GPU에서 1초 이내의 지연으로 처리됩니다. **이동.** 지도가 있는 어떤 공간에서든 주행하고, 말로 지정한 거리와 각도만큼 이동·회전하며, 사람을 따라가고, 막힌 경로를 우회하며, 충전 도크로 돌아갑니다. diff --git a/assistant/brain.py b/assistant/brain.py index e28675f..3a7bd1b 100644 --- a/assistant/brain.py +++ b/assistant/brain.py @@ -367,7 +367,7 @@ You can also move. Decide if the visitor asks you to do something: - look [degrees|small]: turn your head ("look at me" / "look here" / "이쪽 봐" / "여기 봐" -> me, the one speaking; "look straight ahead" / "정면 봐" -> center; "don't look at me" / "stop staring" / "쳐다보지 마" -> away, "turn your head left" -> look left, "고개 들어" -> look up, "look down a bit" -> look down small, "head 30 degrees right" -> look right - 30, "look behind you" / "look at the back side" / "turn your head back" / "뒤 봐" / "뒤돌아 봐" / "고개 뒤로 돌려" -> look + 30, "I'm on your right side" / "나 오른쪽에 있어" -> look right, "look behind you" / "look at the back side" / "turn your head back" / "뒤 봐" / "뒤돌아 봐" / "고개 뒤로 돌려" -> look left {yaw}, "look over your right shoulder" / "오른쪽 뒤 봐" -> look right {yaw}; the question "what's behind you?" / "뒤에 뭐 있어?" is none). Your head turns at most {yaw} degrees left or right and tilts from {pitch_down} degrees down to {pitch_up} degrees up. - lift [mm|small]: raise or lower your upper body on the lift column ("raise yourself" -> lift up, "키 @@ -380,9 +380,11 @@ You can also move. Decide if the visitor asks you to do something: "turn left" -> turn left 90, "spin around" / "한 바퀴 돌아" -> turn left 360); a bare number is degrees. Numbers may be words (마흔다섯 / 사십오 = 45, 일 미터 반 = 1.5, 오십 센티 = 0.5 m); 레프트 / 라이트 mean left / right, never the lift. -- arm : reach: hold your hand out to the visitor, in any words ("reach out to me", "give me +- arm : reach: hold your hand out to the visitor, in any words ("reach out to me", "give me your hand", "hand out please", "offer me your hand", "extend your arm towards me", "손 내밀어", "나한테 손 줘", - "팔 뻗어"); fold: fold it back; open / close: your hand, the gripper ("open your hand", "spread your fingers", "let go", "release", "손 펴", + "팔 뻗어"); fold: fold it back, also to the look pose ("let's take look position", "룩 자세로"); carry / ready: your + arm to that pose ("put your hand carry position", "캐리 자세"); any other pose name: none, say you know look, carry + and ready and ask which; open / close: your hand, the gripper ("open your hand", "spread your fingers", "let go", "release", "손 펴", "놔" -> arm open; "close your hand", "close the gripper", "grip", "make a fist", "손 쥐어", "그리퍼 닫아" -> arm close). - wave: wave your hand ("wave", "shake your hand", "say hi with your hand"). "Hello Lumi!" said to you or "say hello" / "hello 해 봐" is talk (none): say the word itself ("Hello!"). @@ -561,6 +563,30 @@ LIFT_WORDS = (r"\b(?:raise|lift|lower) (?:yourself|your body|your torso|your upp r"|\b(?:go|move) (?:higher|lower)\b|키(?:를)? ?(?:좀 )?(?:[\d.]+ ?(?:m|mm|cm) ?(?:만 ?)?)?(?:높여|키워|올려|낮춰|줄여|크게|작게)" r"|몸(?:을)? ?(?:좀 )?(?:[\d.]+ ?(?:m|mm|cm) ?(?:만 ?)?)?(?:올려|내려|낮춰|높여)" r"|리프트(?:를)? ?(?:좀 )?(?:올려|내려|위로|아래로)|상체(?:를)? ?(?:좀 )?(?:올려|내려|들어)") +SPEAKER_SIDE = re.compile( # the speaker says where they stand: "I'm on your right", "I am your left, right side", "뒤에 있어" + r"\b(?:i'?m|i am|im|we'?re|we are)\s+(?:(?:here|over here|right here|now|standing|sitting|over)\s+)*" + r"(?:(?:(?:on|at|to|by)\s+(?:the|your)|your)\s+((?:(?:left|right)\W+)*(?:left|right))(?:[\s-]+(?:hand[\s-]+)?side)?" + r"|(behind) you|at your (back))(?=\s*(?:[,.!;]|$|(?:lumi|now|here|look)\b))" # not "on the right track", "behind you all the way" + r"|(?:^|[,.!]\s*)(?:(?:루미야?|나|저|난|전|내가|제가|나는|저는)\s*)?(?:(?:여기|지금|바로)\s*)*(왼쪽|오른쪽|왼편|오른편|뒤쪽|뒤)\s*" + r"(?:에\s*(?:서\s*)?)?(?:서\s*)?(?:있어요|있어|있다|있습니다|있지|이에요|예요|입니다|이야|야)(?![가-힣])(?!\s*\?)", re.I) + # sentence-first only: "컵 왼쪽에 있어" is about the cup, "왼쪽에 있어?" a question +SPEAKER_SIDE_ONLY = re.compile(r"^\W*(?:(?:please|lumi|now|so|and|ok|okay|then)\W+)*(?:(?:look|turn)(?: (?:at|over|to|towards?) " + r"(?:me|us|that|there|here|this|my side))?(?: (?:here|there|please|now))*|여기 ?봐|이쪽 ?봐|저기 ?봐|봐)?\W*$", re.I) + + +def speaker_side(text): + """"I'm on your right (side)", "I am your left, right side. Look at that.", "나 여기 왼쪽이야", "I'm behind you" -> + "right" | "left" | the look behind; None when the words say more than that ("I'm on your left, go to p3").""" + t = (text or "").lower() + m = SPEAKER_SIDE.search(t) + if not m or not SPEAKER_SIDE_ONLY.match(t[:m.start()] + " " + t[m.end():]): + return None + word = next(g for g in m.groups() if g) + if word in ("behind", "back", "뒤", "뒤쪽"): + return f"left {HEAD_YAW[1]:g}" # as "look behind you" (head_target) + return "right" if re.findall(r"left|right|왼|오른", word)[-1] in ("right", "오른") else "left" # the last said + + SMALL = re.compile(r"\ba (?:little )?bit\b|\bslightly\b|\ba little\b|\ba touch\b|조금|살짝|약간|좀 더") MORE = re.compile(r"\b(?:more|further)\b|(?:^|\s)더(?:\s|$)") # "look left more", "왼쪽 더 봐": a step on from where it is HEAD_YAW, HEAD_PITCH = head_hw.AXIS_LIMITS[2], head_hw.AXIS_LIMITS[3] # commanded looks: the body's full range @@ -1022,7 +1048,9 @@ def not_an_order(text, asked=True): the LLM (which reads them from the conversation) instead of acting on a keyword. Unsure is never acted on. asked=False: questions do not count (a chain answers its question part: "wave and what time is it?").""" t = unfill(wording.ko_plain(text or "")) # "날 따라오면 돼" is "날 따라와": no condition - rest = instead_of(t) # "don't put your arm out, my baby will grab it" + if speaker_side(text): + return False # "I'm on your right": said so the head turns there + rest = instead_of(t) # "don't put your arm out, my baby will grab it" now = NOW_CLAUSE.sub(" ", WAIT_UNTIL.sub(" ", t)) # "when you're ready", "while you do", "말씀하실 때": now return bool(to_someone_else(t) or CANT_GO.search(t) or DRINK.search(t) or IDIOMS.search(t) or CONDITION.search(now) or REMARK.search(now) or @@ -1155,6 +1183,8 @@ def direct_order(text): short fragment command ("booth A", "faster", "left a bit", "회전"). Only then may a keyword rule act; anything else (a statement, a story, a plan between people, a question about ability or habit) is read by the LLM with the talk before it. Each sentence / clause is checked; one order in it is enough (not_an_order weeds out the rest).""" + if speaker_side(text): + return True # "I'm on your right side": a cue to look there text = re.sub(r"\b(can|could|would|will) (?:ya|yah|yu)\b", r"\1 you", text or "", flags=re.I) # "could ya grab it" t = re.sub(_LEAD, "", unfill(wording.ko_plain(_MAY_NOT.sub(" 줘", text or ""))).strip(), flags=re.I) # every # speech level as 반말 @@ -1257,6 +1287,18 @@ ARM_BACK = re.compile( # the arm back to look (fold), said after a reach; r"\bfold (?:your |the |ur )?(?:arm|hand)\b|\barm\b.*\bput (?:it )?back\b|(? CLOSE_BOX * frame_h] +def look_me_pitch(box, height, pitch, fy, cy): + """Head pitch (deg, + up) that puts a person's head (their box top) near the top of the head camera's view with as + much of them below as fits, or None when the head may stay: the whole person is in view (far), or the change is + small. Pinhole angles without the lens distortion; the next frame corrects what is left.""" + top, bottom = box[1], box[3] + if top <= LOOK_ME_EDGE_PX: # their head is cut: tilt up + new = pitch + LOOK_ME_UP_STEP + elif bottom < height - LOOK_ME_EDGE_PX: # all of them is in view + return None + else: + new = pitch + math.degrees(math.atan((cy - top) / fy) - math.atan((cy - LOOK_ME_TOP_ROW * height) / fy)) + new = max(head.PITCH_RANGE[0], min(head.PITCH_RANGE[1], new)) + return new if abs(new - pitch) >= LOOK_ME_MIN_DEG else None + + class Vision(threading.Thread): """Person detection + simple tracking (nearest match by angle and distance).""" @@ -603,6 +671,38 @@ class Vision(threading.Thread): best = min(self.tracks, default=None, key=lambda t: abs(t.angle - angle)) return best if best is not None and abs(best.angle - angle) <= max_diff else None + def seen(self): + """Everyone in view as (waist-frame angle, distance): this camera's people and, while the head camera is in + use, the torso camera's fresh ones too (someone beside Lumi is often outside the turned head camera's view).""" + with self.lock: + out = [(t.angle, t.distance) for t in self.tracks if t.distance <= STAY_MAX] + if self.camera != "torso": + camview.want("torso") + try: + d = json.loads(camview.det_path("torso").read_text()) + if time.time() - d["time"] <= TORSO_FRESH_S: + out += [(p["angle_deg"], p["distance_m"]) for p in d["people"] + if p["distance_m"] is not None and p["distance_m"] <= STAY_MAX] + except (FileNotFoundError, ValueError, KeyError): + pass + return out + + @staticmethod + def head_person(angle, since): + """The head camera's person nearest this waist-frame angle in a frame newer than `since`, as {box, height, + pitch (head pitch of that frame), fy, cy}, or None.""" + intr = camview.intrinsics("head") + try: + d = json.loads(camview.det_path("head").read_text()) + people = [p for p in d["people"] if abs(p["angle_deg"] - angle) <= SPEAKER_MATCH_DEG] + if d["time"] <= since or not people or intr is None or not d.get("head_pose"): + return None + p = min(people, key=lambda p: abs(p["angle_deg"] - angle)) + return {"box": p["box"], "height": d["height"], "pitch": d["head_pose"][3], + "fy": intr["fy"], "cy": intr["cy"]} + except (FileNotFoundError, ValueError, KeyError): + return None + def only_person(self): with self.lock: near = [t for t in self.tracks if t.distance <= 3.0] @@ -672,9 +772,12 @@ class Patrol: log(f"battery {battery} % - patrol again") self.mode = "patrol" return - if self.mode == "patrol" and battery < LOW_BATTERY: + if self.mode == "patrol" and battery < LOW_BATTERY and now >= self.wait_until: log(f"battery {battery} % - going home to charge") self.pause() + if not waist_home("going home"): # every drive starts with the waist at the front + self.wait_until = now + 5 + return ok, msg = safe(agv.go, "home", default=(False, "error")) self.mode, self.moving = ("going_home", True) if ok else ("patrol", False) return @@ -721,6 +824,12 @@ class Patrol: if (ms == "running" and not force) or now < self.wait_until: # something else is driving, or waiting return target = self.route[self.i] + if not waist_home("driving"): # every drive starts with the waist at the front + if self.once: # said by say_stuck + self.stuck, self.stuck_why, self.mode = target, WAIST_BACK_SAY, "done" + else: + self.wait_until = now + 5 + return if isinstance(target, (tuple, list)): ok, msg = safe(agv.go_point, *target, default=(False, "error")) else: @@ -832,6 +941,47 @@ class Lumi: """End a held look and send the head to rest: ahead, looking down.""" self.looked_at = 0.0 self.turn_head(0, head.HEAD_REST_PITCH) + self.waist_rest() + + def waist_rest(self, why="the conversation is over"): + """The waist back to the front too when a conversation ends (waist_home, in the background), Greeter or + Patrol; it waits like the head while a look is held.""" + if not self.look_held(): + threading.Thread(target=waist_home, args=(why,), daemon=True).start() + + def keep_focus(self): + """In the background: the head stays on the person Lumi talks with (self.current) as they move, a turn when + they are more than FOCUS_DEG off. A held look waits (turn_head), except one held by "look at me": it follows + that person (self.look_me). Not during a task, a follow, a song or a "look at me" search (head_busy).""" + while True: + time.sleep(FOCUS_EVERY_S) + try: + self.focus_step() + except Exception as e: + log(f"focus error: {e!r}") + + def focus_step(self): + from tasks import follow + t = self.current + if t is None or getattr(self, "head_busy", False) or time.time() < self.calib_until or \ + self.doing() or follow.running() or not self.vision.present(t): + return + want = HEAD_SIGN * max(-head.YAW_LIMIT, min(head.YAW_LIMIT, t.angle)) + if abs(want - self.det_yaw()) > FOCUS_DEG: + self.turn_head(want, force=t is getattr(self, "look_me", None)) + + def face(self, track): + """Turn to the person who now speaks: a waist turned for someone else comes back to the front first + (waist_home), then the head turns to them (their angle from where the waist was, plus the turn taken back).""" + w = waist_turned() + if abs(w) < 1.0: + self.turn_head(HEAD_SIGN * track.angle) + return + angle = track.angle + + def run(): + self.turn_head(HEAD_SIGN * (angle + w if waist_home("someone else speaks") else angle)) + threading.Thread(target=run, daemon=True).start() def wave(self, ok=None, quiet=False): """Wave because someone asked or said "bye bye" in view (never on a greeting): manipulation/wave.py checks the @@ -905,16 +1055,8 @@ class Lumi: log(f" {action} refused: on a mission") # the LLM's action must not take Lumi off its task return if action == "look" and target == "me": # "look at me", "이쪽 봐": the speaker, never just the centre - track = self.current if self.current and self.vision and self.vision.present(self.current) else None - if self.voice_trusted and (track is None or abs(track.angle - self.voice_angle) > SPEAKER_MATCH_DEG): - track = self.vision.near_angle(self.voice_angle) if self.vision else None - angle = track.angle if track else self.voice_angle - else: - track = track or (self.vision.only_person() if self.vision else None) - angle = track.angle if track else None # no idea where they are: the head stays self.looked_at = time.time() # held like any look - self.turn_head(None if angle is None else HEAD_SIGN * max(-head.YAW_LIMIT, min(head.YAW_LIMIT, angle)), 10, - force=True) + threading.Thread(target=self.look_at_speaker, daemon=True).start() elif action == "look" and target.split()[0:1] and (target.split()[0] in LOOK or target == "away"): return self.look(target) # a LIMIT_SAY key when the head is at its end elif action == "lift": @@ -950,6 +1092,86 @@ class Lumi: if self.fetch_status() == "holding": self.fetch_finish(action) + def look_at_speaker(self): + """"Look at me": the person seen nearest the voice (both cameras). Nobody seen there: the head turns to the + voice first, then to whoever the head camera finds there; nobody there either (the voice direction can be + off): the person talked to, else the nearest person seen. Nobody seen and no voice: the head stays. Then the + head tilts until the head camera sees the person from their head down (look_me_pitch). That person becomes + the one talked with, and while the look is held the head follows them (look_me, keep_focus).""" + if not self.vision: + return + self.head_busy = True # keep_focus waits: the head is turned here + try: + self._look_at_speaker() + finally: + self.head_busy = False + + def _look_at_speaker(self): + def near(seen, angle): + return min((s for s in seen if abs(s[0] - angle) <= SPEAKER_MATCH_DEG), + key=lambda s: abs(s[0] - angle), default=None) + + def face(angle, pitch=LOOK_ME_PITCH): + safe(head.turn, HEAD_SIGN * max(-head.YAW_LIMIT, min(head.YAW_LIMIT, angle)), pitch) + + recent = time.time() - getattr(self, "voice_at", 0.0) <= VOICE_KEEP_S # this turn's sound too weak: the + voice = self.voice_angle if self.voice_trusted or recent else None # caller's last sure direction + seen = self.vision.seen() + found = near(seen, voice) if voice is not None else None + if found is None and voice is not None and abs(voice) > head.YAW_LIMIT: + voice = self.turn_body_to(voice) # behind or far aside: the head alone can't get there + if found is None and voice is not None: + log(f" look me: nobody seen at the voice ({voice:+.0f} deg), turning there first") + face(voice) + time.sleep(LOOK_ME_SETTLE_S) # new head camera frames from there + seen = self.vision.seen() + found = near(seen, voice) + why = "nearest the voice" + if found is None: + cur = self.current if self.current and self.vision.present(self.current) else None + if cur: + found, why = (cur.angle, cur.distance), f"the person talked with (#{cur.id})" + elif voice is not None: # the voice off: the person nearest its direction, not + found = min(seen, key=lambda s: abs(s[0] - voice), default=None) # the nearest one far off it + why = f"nearest the voice's side ({voice:+.0f} deg)" + else: + found, why = min(seen, key=lambda s: s[1], default=None), "the nearest seen, no voice direction" + if found is None: + log(f" look me: nobody seen{'' if voice is None else ' at the voice either'}, the head stays") + return + log(f" look me: person at {found[0]:+.0f} deg, {found[1]:.2f} m ({why})") + face(found[0]) + for _ in range(LOOK_ME_TRIES): + since = time.time() + time.sleep(LOOK_ME_SETTLE_S) # new head camera frames from there + p = self.vision.head_person(found[0], since) + pitch = p and look_me_pitch(p["box"], p["height"], p["pitch"], p["fy"], p["cy"]) + if pitch is None: + break + log(f" look me: box top {p['box'][1]}, pitch {p['pitch']:+.0f} -> {pitch:+.0f} deg") + face(found[0], pitch) + t = self.vision.near_angle(found[0], SPEAKER_MATCH_DEG) + if t is not None: # the focus: talked with, the held look follows them + log(f" look me: focus on person #{t.id}") + t.greeted, self.current, self.look_me = True, t, t + + def turn_body_to(self, angle): + """A voice past the head's reach (waist-frame deg): with Patrol the base turns to it (look_toward), else the + waist turns in place toward it (the base stays; fetch._waist_to checks the arm's sweep). Returns the voice's + waist-frame angle after the turn (unchanged when nothing could turn).""" + from tasks import fetch + if self.modes.drive and self.modes.patrol: + self.look_toward(angle) + return 0.0 + w = waist_turned() + want = max(-LOOK_WAIST_MAX, min(LOOK_WAIST_MAX, w + angle)) + log(f" look me: the voice at {angle:+.0f} deg is past the head: waist to {want:+.0f} deg") + try: + fetch._waist_to(want, in_place=True, look=angle) + except Exception as e: + log(f" look me: waist did not turn: {e!r}") + return angle - (waist_turned() - w) + def look(self, target): """'left', 'left 30', 'down small' (brain.head_goal): the head, cut to its range. Returns "yaw" / "pitch" when a number asked for was past the range, the direction ("down") when the head already stands at that end @@ -957,7 +1179,7 @@ class Lumi: cur = safe(head.status) if cur is None: return None - self.looked_at = time.time() + self.looked_at, self.look_me = time.time(), None # held where asked, not on a person yaw, pitch, limited = brain_mod.head_goal(target, cur[2], cur[3], LOOK) # the body's full range (AXIS_LIMITS): if limited in ("left", "right", "up", "down"): log(f" look {target}: already at the end (yaw {cur[2]:.0f}, pitch {cur[3]:.0f})") @@ -1218,7 +1440,8 @@ class Lumi: if self.patrol: self.patrol.pause() self.patrol = None - self.head_rest() # a stop word ends a held look + self.looked_at = 0.0 # a stop word ends a held look; the head stays with the + # person, it rests when the conversation ends self.fetch_say("Okay, I stopped.", "네, 멈췄어요.") self.keep_listening() @@ -1281,7 +1504,14 @@ class Lumi: self.last_song = song self.brain.history.append((text, f"ACTION: sing {song}")) log(f" singing {song}") - done = sing.sing(song, abort=self.song_abort) + t = self.current # dance toward the listener, never back at yaw 0 + yaw = HEAD_SIGN * t.angle if t is not None and self.vision and self.vision.present(t) else self.det_yaw() + self.song_request = (text, time.time()) # the request said again is no new one (song_abort) + self.head_busy = True # keep_focus waits: the dance moves the head + try: + done = sing.sing(song, abort=self.song_abort, centre_yaw=yaw) # sing.around keeps it inside YAW_LIMIT + finally: + self.head_busy = False log(f" song {'finished' if done else 'stopped'}") self.keep_listening() @@ -1290,6 +1520,8 @@ class Lumi: it and is answered next (pending_text). The song's own words and unclear sounds are ignored.""" # not self.interrupted(): the head dances away from the listener, who then "left" (songs cut after 2-4 s, # 2026-10-23); only words end a song + if self.peeked_stop(sing.stop_words): + return True u = self.mic.next(0.0) if u is None or not getattr(u, "during_speech", False) or u.seconds < 0.25 or mouth.own_voice(u): return False @@ -1301,6 +1533,13 @@ class Lumi: return True if brain_mod.is_backchannel(text): # "thank you": often whisper's guess on music; "wow" return False + # the clip mic hears the song too, and the sound match (own_voice) does not know music through the room (0.2-0.4 + # against the song itself): whisper's words from it, single words and the request said again leave it going + request, started = self.song_request + why = sing.ignored_over_song(text, request, time.time() - started, ears.last_stt.get("speech_s")) + if why: + log(f" ignored while singing ({why}): {text!r}") + return False log(f" song interrupted: {text!r}") self.pending_text = text return True @@ -1850,7 +2089,8 @@ class Lumi: said, done = (f"Okay, I'll pick up the {target}.", "네, 집어 볼게요."), ("I've got it.", "잡았어요.") def run(): # the held name for the dashboard and the replies from tasks import fetch - skills.pick(name, colour) + self.stay() # Greeter only: the waist turns in place, the base stays + fetch.pick_here(name, colour, say=self.fetch_say) fetch.held_by_skill({"object": name, "colour": colour}) else: said, done = (f"Okay, I'll move the {target}.", "네, 옮겨 볼게요."), ("Done.", "다 옮겼어요.") @@ -1859,10 +2099,13 @@ class Lumi: mouth.say(said[0] if en else said[1]) def work(): + from tasks import fetch try: run() mouth.say(done[0] if en else done[1]) - except skills.SkillError as e: + except fetch.Stopped: + log(f" {action} {target}: stopped") + except (skills.SkillError, fetch.FetchError) as e: log(f" {action} {target}: {e}") mouth.say(e.args[0] if en else e.args[1] if len(e.args) > 1 else "죄송해요, 지금은 할 수 없어요.") except (motion.MotionError, ConnectionError, OSError) as e: @@ -1873,8 +2116,8 @@ class Lumi: self.keep_listening() def arm_pose(self, target): - """'reach': the hand out to the person (reach_out); 'fold': to look along the pose graph (arm_route, checked - first, moved in the background); 'open' / 'close': the gripper, never opened on something held. True when + """'reach': the hand out to the person (reach_out); 'fold' / 'carry' / 'ready': to look / that pose along the + pose graph (arm_route, checked first, moved in the background); 'open' / 'close': the gripper, never opened on something held. True when started, False when not learned, None when refused (the reason is said).""" from tasks import fetch held = target in ("reach", "open") and self.held_now() @@ -1891,7 +2134,7 @@ class Lumi: self.reached_at = 0.0 # folding: no auto fold after it try: holding = self.fetch_status() == "holding" - seq = arm_route.plan(arm_route.HOME, holding=holding) + seq = arm_route.plan(arm_route.HOME if target == "fold" else target, holding=holding) # "carry", "ready" threading.Thread(target=safe, args=(arm_route.move, seq, None, holding), daemon=True).start() return True except arm_route.RouteError as e: @@ -1905,9 +2148,8 @@ class Lumi: def reach_out(self, held): """"Reach out to me", "give me your hand", "손 내밀어": something in the hand = hand it over. Else toward the person (the tracked one, else the one the voice came from, else the voice's direction): the head turns to - them; further to the side than REACH_FRONT_DEG the waist turns first with Patrol on, Greeter says it stays in - place and asks them to stand in front (reach_turn); then fetch.reach (give pose along the graph, a short checked - move toward their hand). The arm folds back on "thanks" / "okay" or after REACH_HOLD_S (reach_done). + them; further to the side than REACH_FRONT_DEG the waist turns first (reach_turn, Greeter only too: the base + stays); then fetch.reach (give pose along the graph, a short checked move toward their hand). The arm folds back on "thanks" / "okay" or after REACH_HOLD_S (reach_done). True when started, None when refused or handed over (said).""" from tasks import fetch if held: @@ -1916,17 +2158,20 @@ class Lumi: if self.skill_thread is not None and self.skill_thread.is_alive(): self.fetch_say("I'm still busy with my arm.", "아직 팔로 하는 일이 있어요.") return None + with _waist_lock: # a waist coming back to the front (face) ends first + pass track = None if self.vision: track = self.current if self.current and self.vision.present(self.current) else \ self.vision.near_angle(self.voice_angle) if self.voice_trusted else self.vision.only_person() angle = track.angle if track else self.voice_angle if self.voice_trusted else None - turn = reach_turn(angle, self.modes.patrol) + turn = reach_turn(angle) log(f" reach: person at {'?' if angle is None else f'{angle:+.0f}'} deg, waist turn {turn}") if turn is None: - self.fetch_say(*(STAND_IN_FRONT_SAY if angle is None else GREETER_FRONT_SAY)) + self.fetch_say(*STAND_IN_FRONT_SAY) return None - self.turn_head(0 if turn else HEAD_SIGN * max(-head.YAW_LIMIT, min(head.YAW_LIMIT, angle)), force=True) + if not turn: # a waist turn takes the head along onto them (fetch._waist_to look): no head move here, + self.turn_head(HEAD_SIGN * max(-head.YAW_LIMIT, min(head.YAW_LIMIT, angle)), force=True) # it raced it self.stay() try: fetch.reach(turn, say=self.fetch_say) @@ -2136,7 +2381,7 @@ class Lumi: log(" calibration: someone else stands in the same direction - skipped") return self.calib_n += 1 - c = doa.add_sample(u.mics, me.angle - HEAD_SIGN * self.det_yaw()) + c = doa.add_sample(u.mics, me.angle - HEAD_SIGN * self.det_yaw(), doa.clip_ref(u)) log(f" calibration sample {self.calib_n}: person at {me.angle:+.0f} deg, {me.distance:.1f} m" + (f" -> calibrated {c}" if c else "")) self.write_calib("calibrated" if c else "collecting", c) @@ -2147,14 +2392,18 @@ class Lumi: return self.interrupted() or self.barge_in() def barge_in(self): - u = self.mic.next(0.0) - if u is None: - return False - if not getattr(u, "during_speech", False) or u.seconds < 0.25: - return False - own = mouth.own_voice(u) # the speaker's sound in the clip mic (mouth.echo) - text = (ears.transcribe(u.mono) or "").strip() from tasks import follow + text = self.peeked_stop(lambda t: stop_order(t, self.markers) or follow.running() and follow.stop_word(t)) + if text is None: + u = self.mic.next(0.0) + if u is None: + return False + if not getattr(u, "during_speech", False) or u.seconds < 0.25: + return False + own = mouth.own_voice(u) # the speaker's sound in the clip mic (mouth.echo) + text = (ears.transcribe(u.mono) or "").strip() + if self.own_stop(text, u): # Lumi's own "stop" ("say stop to end") is no stop + text = "" if follow.running() and follow.stop_word(text): # following: the base stops now, "stop" is answered next follow.stop() # (anyone's: safety, never dropped as an echo) self.pending_text = "stop" @@ -2199,6 +2448,27 @@ class Lumi: return True return False + def peeked_stop(self, is_stop): + """A stop word in the last seconds the clip mic heard while Lumi talks (mic.peek()), before that utterance + ends: Lumi's own voice in the clip mic keeps it going (a 17.9 s answer was stopped only at its end, 2026-10-27). + Not Lumi's own sound (mouth.own_voice) or a stop word Lumi says itself. The words heard, else None.""" + u = getattr(self.mic, "peek", lambda: None)() + if u is None or mouth.own_voice(u): + return None + text = (ears.quick(u.mono) or "").strip() + if not text or not is_stop(text) or not ears.heard_clearly(BARGE_IN_LOGPROB) or self.own_stop(text, u): + return None + log(f" stop word while talking: {text!r}") + return text + + @staticmethod + def own_stop(text, u): + """Every word heard is in what Lumi was saying then (its own "stop" picked up by the clip mic).""" + said = set(re.findall(r"\w+", mouth.saying(time.time() - u.seconds - 1.0).lower())) # just heard; the + # clip mic lags up to 1 s + words = set(re.findall(r"\w+", (text or "").lower())) + return bool(words) and words <= said + @staticmethod def own_echo(text, seconds=30.0, share=0.6): """The clip mic also hears Lumi: ignore what overlaps with what it said in the last `seconds`. A word counts @@ -2265,7 +2535,7 @@ class Lumi: text, self.pending_text = self.pending_text, None call, self.pending_call = getattr(self, "pending_call", None), None if call and call[0] == text: # a call while Lumi talked: turn to the caller first - self.who_spoke(call[1]) + self.who_spoke(call[1], text) self.answer(text) return True self.warm_llm() # the LLM's prompt start cached while they speak @@ -2302,16 +2572,16 @@ class Lumi: if self.follow_filter(text, u): # following: only the followed person is listened to return True if not follow.running(): # following: the head stays on the followed person - self.who_spoke(u) + self.who_spoke(u, text) self.answer(text) if self.mission_hold == "talk" and not self.asked_go_on and self.mission_running(): self.asked_go_on = True # answered while halted for them: may I go on? self.fetch_say("Can I go on with my task?", "하던 일 계속해도 될까요?") return True - def _doa_sample(self, mics, true_deg): + def _doa_sample(self, mics, true_deg, ref=None): try: - c = doa.add_sample(mics, true_deg) + c = doa.add_sample(mics, true_deg, ref) if c: log(f"sound direction calibrated: {c}") finally: @@ -2410,8 +2680,10 @@ class Lumi: else "지금은 다른 분을 따라가는 중이에요.") return True - def who_spoke(self, u): - """Use the sound direction: pick the visible person who spoke; meanwhile collect calibration samples.""" + def who_spoke(self, u, text=None): + """Use the sound direction: pick the visible person who spoke; meanwhile collect calibration samples. Someone + else near the voice takes the talk over (and the head) only with a call, a stop word or an order in `text`; + other words keep the focus on the person talked with.""" if not self.vision or u is None: return self.voice_trusted = False # set again below only from this turn's own sound @@ -2420,22 +2692,34 @@ class Lumi: if only is not None and only is self.current and only.distance <= 1.6 and u.seconds >= 0.8: # the only person in view is the one we talk to, close by: their angle is the truth if _doa_fit.acquire(blocking=False): # the refit takes seconds (a grid over all samples): in the - threading.Thread(target=self._doa_sample, args=(u.mics, only.angle - HEAD_SIGN * yaw), # background, - daemon=True).start() # never before the answer (it held answers ~15 s, 2026-10-21) + threading.Thread(target=self._doa_sample, args=(u.mics, only.angle - HEAD_SIGN * yaw, doa.clip_ref(u)), + daemon=True).start() # background, never before the answer (it held answers ~15 s) return cal = doa.load_calib() if not cal["fitted"]: return - ang, conf, _ = doa.estimate(u.mics, cal) - if conf < DOA_MIN_CONF: + ang, conf, _ = doa.estimate(u.mics, cal, doa.clip_ref(u)) # with the clip mic: its wearer's voice + trusted = conf >= voice_min_conf(u) + log(f" voice at {HEAD_SIGN * yaw + ang:+.0f} deg (confidence {conf:.2f}{doa.clip_note(u.mics, doa.clip_ref(u))}" + f"{'' if trusted else ', not trusted'})") + if not trusted: return self.voice_angle, self.voice_trusted = HEAD_SIGN * yaw + ang, True # "이쪽 봐": this voice, also out of view + self.voice_at = time.time() t = self.vision.near_angle(HEAD_SIGN * yaw + ang) if t is not None and t is not self.current: + cur = self.current + rule = text and brain_mod.intent(text, self.markers) # an order; a weather or web question is no + if text and cur is not None and self.vision.present(cur) and not ( # order ("nice weather today") + WAKE.search(text) or stop_order(text, self.markers) or rule and rule[0] not in ("weather", "search")): + log(f" voice near person #{t.id}, no call, stop or order: focus stays on #{cur.id}") + return log(f" voice from {HEAD_SIGN * yaw + ang:+.0f} deg: person #{t.id} is speaking") t.greeted = True self.current = t - self.turn_head(HEAD_SIGN * t.angle) + if getattr(self, "look_me", None) is not None: # a "look at me" hold was for the one before + self.looked_at, self.look_me = 0.0, None + self.face(t) def det_yaw(self): """Current head yaw (deg), read from the body every 0.3 s (the torso camera does not know it).""" @@ -2533,6 +2817,7 @@ class Lumi: if not quiet: # a goodbye ends a held look; silence keeps it (LOOK_HOLD_S) self.looked_at = 0.0 self.turn_head(0, head.HEAD_REST_PITCH) # waits while a look is held + self.waist_rest() if self.traveling(): log(" conversation over - driving on") self.patrol.wait_until = time.time() + 0.5 @@ -2640,7 +2925,7 @@ class Lumi: mouth.say(done[target][0] if en else done[target][1]) ok = self.arm_pose(target) if ok: - if target == "fold": + if target in ("fold", "carry", "ready"): mouth.say("Okay." if en else "네.") elif target not in done: mouth.say("Here you go." if en else "여기요.") @@ -2904,6 +3189,8 @@ class Lumi: head_["action"] = "end" # "thanks, that's all" -> "Have a great day!": it took leave if head_["action"] in ("end", "go_to"): self.current, self.voice_until = None, 0.0 # stay quiet with this person until a new visit + if head_["action"] == "end": # the model took leave: head and waist to rest + self.head_rest() elif self.current is None: self.voice_until = time.time() + VOICE_SESSION_S if fate == "close" and head_["action"] == "none": # "thanks" taken as heard: silence now ends the talk @@ -2938,12 +3225,14 @@ class Lumi: lang = ears.heard_lang("ko" if re.search(r"[가-힣]", text) else "en") self.lang = lang cal = doa.load_calib() - ang, conf, raw = doa.estimate(u.mics, cal) - trusted = cal["fitted"] and conf >= DOA_MIN_CONF + ang, conf, raw = doa.estimate(u.mics, cal, doa.clip_ref(u)) # with the clip mic: its wearer's voice + trusted = cal["fitted"] and conf >= voice_min_conf(u) robot_angle = HEAD_SIGN * self.det_yaw() + ang self.voice_angle, self.voice_trusted = robot_angle, trusted + if trusted: + self.voice_at = time.time() log(f"WAKE {text!r}: voice at {robot_angle:+.0f} deg (confidence {conf:.2f}, " - f"{'calibrated' if cal['fitted'] else 'NOT calibrated'})") + f"{'calibrated' if cal['fitted'] else 'NOT calibrated'}{doa.clip_note(u.mics, doa.clip_ref(u))})") if self.traveling(): # someone calls while driving: stop for them log(" called while driving - stop and talk, then drive on") self.patrol.pause() @@ -2955,7 +3244,7 @@ class Lumi: if target is not None: target.greeted = True self.current = target - self.turn_head(HEAD_SIGN * target.angle) + self.face(target) if not command: # just "Hi Lumi": a short answer, then listen mouth.say(WAKE_REPLY[lang]) self.voice_until = time.time() + VOICE_SESSION_S @@ -2976,31 +3265,47 @@ class Lumi: if t is not None: return t view = CAMERA_HALF_FOV + (head.YAW_LIMIT if self.vision.camera == "head" else 0.0) - if abs(robot_angle) > view and self.modes.drive and self.modes.patrol: + w = waist_turned() if abs(robot_angle) > view and self.modes.drive and self.modes.patrol else None + if w is not None and waist_home("turning to a caller"): log(f" caller outside the camera ({robot_angle:+.0f} deg): turning toward the voice") - self.turn_head(0) - safe(agv.turn_by, math.radians(robot_angle)) + self.turn_head(0, force=True) # a call or an order: also over a held look + safe(agv.turn_by, math.radians(robot_angle + w)) # from the base's front: the waist is there now t0 = time.time() time.sleep(0.6) while time.time() - t0 < 8 and (safe(agv.status, default={}) or {}).get("move_status") == "running": time.sleep(0.2) time.sleep(0.8) # let detection catch up self.voice_angle = 0.0 - return self.vision.near_angle(0.0, 35) or self.vision.only_person() - self.turn_head(HEAD_SIGN * max(-head.YAW_LIMIT, min(head.YAW_LIMIT, robot_angle))) - if self.vision.camera == "head": # the camera turned with the head: look again - time.sleep(1.5) - return self.vision.near_angle(robot_angle) - return None + t = self.vision.near_angle(0.0, 35) or self.vision.only_person() + log(" after the turn: " + (f"person #{t.id} at {t.angle:+.0f} deg, {t.distance:.2f} m" if t else "nobody ahead")) + return t + was = self.det_yaw() + self.turn_head(HEAD_SIGN * max(-head.YAW_LIMIT, min(head.YAW_LIMIT, robot_angle)), force=True) + if self.vision.camera != "head": + return None + time.sleep(1.5) # the camera turned with the head: look again + t = self.vision.near_angle(robot_angle) + if t is None: # nobody there (the voice direction can be off): the + near = min(self.vision.seen(), key=lambda s: abs(s[0] - robot_angle), default=None) # person seen + log(f" nobody at the voice ({robot_angle:+.0f} deg): " # nearest its side (not the nearest far off it) + + (f"person seen at {near[0]:+.0f} deg, {near[1]:.2f} m" if near else "head back")) + self.turn_head(HEAD_SIGN * max(-head.YAW_LIMIT, min(head.YAW_LIMIT, near[0])) if near else was, force=True) + if near: + time.sleep(1.5) + t = self.vision.near_angle(near[0]) + return t def look_toward(self, robot_angle): """Turn the head toward a waist-frame angle; turn the base too if it is outside the head's range.""" if abs(robot_angle) <= head.YAW_LIMIT: self.turn_head(HEAD_SIGN * robot_angle) elif self.modes.drive and self.modes.patrol: + w = waist_turned() + if not waist_home("turning to a voice"): + return log(f" voice behind ({robot_angle:+.0f} deg): turning the base") self.turn_head(0) - safe(agv.turn_by, math.radians(robot_angle)) + safe(agv.turn_by, math.radians(robot_angle + w)) # from the base's front: the waist is there now t = time.time() time.sleep(0.5) while time.time() - t < 8 and (safe(agv.status, default={}) or {}).get("move_status") == "running": @@ -3035,6 +3340,9 @@ class Lumi: if goal is None: mouth.say("Sorry, I can't get closer from here.") return + if not waist_home("coming to a person"): # every drive starts with the waist at the front + mouth.say(WAIST_BACK_SAY[0 if self.lang == "en" else 1]) + return ok, msg = safe(agv.go_point, *goal, default=(False, "error")) if not ok: log(f" base refused: {msg}") @@ -3060,14 +3368,14 @@ class Lumi: log(f" person #{track.id} is {track.distance:.2f} m away - stop") safe(agv.cancel) break - if time.time() - last_look > 1.0: # keep looking at them while driving - self.turn_head(HEAD_SIGN * track.angle) - last_look = time.time() + if time.time() - last_look > 1.0: # keep looking at them while driving (also over + self.turn_head(HEAD_SIGN * max(-head.YAW_LIMIT, min(head.YAW_LIMIT, track.angle)), force=True) + last_look = time.time() # a held "look at me": it was them) time.sleep(0.2) else: safe(agv.cancel) if self.vision.present(track): - self.turn_head(HEAD_SIGN * track.angle) + self.turn_head(HEAD_SIGN * max(-head.YAW_LIMIT, min(head.YAW_LIMIT, track.angle)), force=True) self.last_activity = time.time() def pointed_drive(self, text): @@ -3091,6 +3399,9 @@ class Lumi: self.keep_listening() return True far = spot["clamped"] + if not waist_home("driving where pointed"): # every drive starts with the waist at the front + mouth.say(WAIST_BACK_SAY[0 if en else 1]) + return True mouth.say((f"Going that way, {pointing.MAX_M:g} meters." if far else "Going there.") if en else (f"그쪽으로 {pointing.MAX_M:g}미터 갈게요." if far else "그곳으로 갈게요.")) ok, msg = safe(agv.go_point, *spot["map"], default=(False, "error")) @@ -3163,6 +3474,7 @@ class Lumi: self.last_activity, self.prompts = time.time(), 0 self.alive = time.time() threading.Thread(target=self.watchdog, daemon=True).start() + threading.Thread(target=self.keep_focus, daemon=True).start() while True: self.alive = time.time() try: @@ -3177,7 +3489,7 @@ class Lumi: self.poll_commands() self.reach_done() # the hand held out REACH_HOLD_S: back to look self.publish_busy(self.doing()) - if self.patrol and self.patrol.mode == "done" and not self.a.patrol: + if self.patrol and self.patrol.mode == "done" and not self.a.patrol and not self.patrol.stuck: # said first self.patrol = None # a dashboard / voice trip has arrived moving = self.traveling() # on the way only people in the path, close by; standing: everyone in the greeting zone @@ -3194,7 +3506,7 @@ class Lumi: from tasks import follow following = follow.running() # no greetings (the head would turn away), keep listening greet_now = self.modes.greeter and not moving and time.time() > self.quiet_until and not following \ - and not self.doing() # never during a task: standing, idle or talking only + and not self.doing() and self.current is None # never during a task or while talking with someone candidate = self.waver() if greet_now else None # Lumi never speaks to someone who only stands there or focus = self.current or candidate # walks past: a wave (or the wake word) calls it self.vision.det.focus_angle = focus.angle if focus else None # drawn red in the dashboard @@ -3205,15 +3517,22 @@ class Lumi: return if self.current and not self.vision.present(self.current): + gone = self.current # often the same person under a new track id (#5 -> #7 at + again = None if following else self.vision.near_angle(gone.angle, FOCUS_REFIND_DEG) # 19:24, 2026-10-27) + if again is not None: + log(f"person #{gone.id} seen again as #{again.id} at {again.angle:+.0f} deg") + again.greeted, self.current = True, again + if getattr(self, "look_me", None) is gone: + self.look_me = again + return log(f"person #{self.current.id} left - stop talking") self.current = None if following else self.vision.nearest_greeted() # someone else still here? if self.current: self.turn_head(HEAD_SIGN * self.current.angle) else: # often still there, out of the frame (beside the arm): keep listening without the wake word - # for a while, like a conversation started by voice. After "look left" the head stays there - if not self.look_held(): - self.turn_head(0, head.HEAD_REST_PITCH) + # for a while, like a conversation started by voice. The head stays their way; it rests when this + # voice session ends by silence (end_conversation) self.voice_until = time.time() + VOICE_SESSION_S self.last_activity, self.prompts = time.time(), 0 return diff --git a/audio/doa.py b/audio/doa.py index c37af34..46bd356 100644 --- a/audio/doa.py +++ b/audio/doa.py @@ -9,7 +9,9 @@ offset + sign * k * 60 deg. Angles are in the head frame: 0 = where the head loo Calibration needs people at known angles. lumi.py collects them on its own: while it talks with a person the head camera sees, each utterance of that person is a sample (camera angle = truth). After MIN_SAMPLES -samples spread over at least SPREAD_DEG it fits sign / offset / radius and writes doa_calib.json. +samples spread over at least SPREAD_DEG it fits sign / offset / radius and writes doa_calib.json, unless the fit is +worse than the saved one. With the clip mic a sample is weighted by the clip voice like estimate(), and is skipped +when that voice is not found in the array audio. Or by hand: python audio/doa.py --calibrate # stand in front of the head camera, talk, move left / right, Ctrl+C to fit @@ -31,6 +33,10 @@ NFFT, HOP = 512, 256 BAND = (300.0, 3500.0) # Hz used GRID = np.arange(-180, 180, 2.0) # deg MIN_SAMPLES, SPREAD_DEG = 6, 30.0 +CLIP_MAX_LAG_S = 0.3 # s searched for the clip mic's voice in the head array audio (radio delay + buffers; + # the array window is cut by the clip's own times, so they differ by tens of ms) +USE_CLIP_REF = False # weight the direction by the clip mic's voice; off: the plain array estimate +CLIP_MIN_SCORE = 8.0 # clip voice found in the array: correlation peak over its spread (unrelated audio ~4-5) PAIRS = [(i, j) for i in range(6) for j in range(i + 1, 6)] _freqs = np.fft.rfftfreq(NFFT, 1 / RATE) @@ -46,20 +52,55 @@ def load_calib(): return {"radius": 0.04, "offset": 0.0, "sign": 1, "fitted": False} -def cross_spectra(mics): - """Average PHAT-normalised cross-spectra of all mic pairs: (15, n_band) complex, or None if too short.""" +def _spectra(x): + """Band spectra of 50 % overlapping windows: (t, F, channels).""" + win = np.hanning(NFFT).astype(np.float32) + frames = np.stack([x[i:i + NFFT] * win[:, None] for i in range(0, len(x) - NFFT, HOP)]) # (t, NFFT, ch) + return np.fft.rfft(frames, axis=1)[:, _band, :] + + +def clip_lag(mics, ref): + """Where the clip mic's voice sits in the head array audio: (lag, score). Clip sample k is array sample k + lag; + score = GCC-PHAT peak (clip against the array's mean, speech band) over the spread of the correlation.""" + a, c = mics.astype(np.float32).mean(1), np.asarray(ref, np.float32) + n = 1 << int(np.ceil(np.log2(len(a) + len(c)))) + f = np.fft.rfftfreq(n, 1 / RATE) + x = np.fft.rfft(a, n) * np.conj(np.fft.rfft(c, n)) + x = np.where((f >= BAND[0]) & (f <= BAND[1]), x / (np.abs(x) + 1e-9), 0) + cc = np.fft.irfft(x, n) + m = int(CLIP_MAX_LAG_S * RATE) + cc = np.concatenate([cc[-m:], cc[:m + 1]]) # lags -m .. +m + k = int(np.argmax(cc)) + return k - m, float(cc[k] / (cc.std() + 1e-12)) + + +def cross_spectra(mics, ref=None): + """Average PHAT-normalised cross-spectra of all mic pairs: (15, n_band) complex, or None if too short. + + ref: the clip mic's audio of the same utterance (worn by the person talking to Lumi). The array then hears that + person faintly under louder room sound, so the louder-frames rule picks the room. Instead the clip is lined up + with the array (clip_lag) and each time-frequency bin is weighted by the clip's power there: bins where the wearer + talks count, the room in between and in other frequencies does not (a fixed share of the strongest bins worked + too, but the right share changed with how loud the room was). When the clip voice is not found in the array the + plain estimate is made (the louder frames), as without a clip.""" x = mics.astype(np.float32) if len(x) < NFFT: return None - win = np.hanning(NFFT).astype(np.float32) - frames = np.stack([x[i:i + NFFT] * win[:, None] for i in range(0, len(x) - NFFT, HOP)]) # (t, NFFT, 6) - spec = np.fft.rfft(frames, axis=1)[:, _band, :] # (t, F, 6) - energy = (np.abs(spec) ** 2).sum((1, 2)) - keep = energy >= np.percentile(energy, 50) # the louder half of the frames: the voice, not pauses - spec = spec[keep] + spec = _spectra(x) # (t, F, 6) + lag, score = clip_lag(x, ref) if ref is not None and len(ref) else (0, 0.0) + if score < CLIP_MIN_SCORE: + energy = (np.abs(spec) ** 2).sum((1, 2)) + w = (energy >= np.percentile(energy, 50))[:, None] * np.ones(spec.shape[1]) # the louder half of the frames: + else: # the voice, not pauses + c = np.zeros(len(x), np.float32) # the clip at the array's sample times + src = np.asarray(ref, np.float32)[max(0, -lag):] + c[max(0, lag):max(0, lag) + len(src)] = src[:len(x) - max(0, lag)] + p = np.abs(_spectra(c[:, None])[:, :, 0]) ** 2 # (t, F) clip power + w = p / (p.max() + 1e-12) g = np.stack([(spec[:, :, i] * np.conj(spec[:, :, j])) for i, j in PAIRS]) # (15, t, F) g = g / (np.abs(g) + 1e-9) - return g.mean(1) # (15, F) + return (g * w[None]).sum(1) / w.sum(0).max() # weighted mean over the frames: (15, F); a frequency + # where the clip voice is weak counts little def _steering(radius, offset, sign): @@ -82,10 +123,33 @@ def _power(g, calib): return np.real((_cache[key] * g[None]).sum((1, 2))) # (n_grid,) -def estimate(mics, calib=None): - """(angle deg in the head frame, confidence 0..1, raw angle with the default geometry).""" +def clip_ref(u): + """The clip mic's audio of an utterance cut from it (its wearer's voice is the one to find), else None. Off + (USE_CLIP_REF): live, the clip-weighted direction came out at confidence 0.03-0.07, too weak to trust.""" + return u.mono if USE_CLIP_REF and getattr(u, "source", None) == "clip" else None + + +def clip_found(mics, ref): + """Is the clip mic's voice clearly in the head array audio (then the estimate is its wearer's direction)?""" + if ref is None or mics is None or len(mics) < NFFT or not len(ref): + return False + return clip_lag(mics, ref)[1] >= CLIP_MIN_SCORE + + +def clip_note(mics, ref): + """For the log: how clearly the clip voice was found in the array audio, "" without a clip.""" + if ref is None or mics is None or len(mics) < NFFT or not len(ref): + return "" + lag, score = clip_lag(mics, ref) + if score < CLIP_MIN_SCORE: + return f", clip not found (score {score:.1f})" + return f", clip score {score:.0f} at {lag * 1000 / RATE:+.0f} ms" + + +def estimate(mics, calib=None, ref=None): + """(angle deg in the head frame, confidence 0..1, raw angle with the default geometry). ref: see cross_spectra.""" calib = calib or load_calib() - g = cross_spectra(mics) + g = cross_spectra(mics, ref) if g is None: return 0.0, 0.0, 0.0 p = _power(g, calib) @@ -96,9 +160,14 @@ def estimate(mics, calib=None): # ---------- calibration ---------- -def add_sample(mics, true_deg): - """Store one utterance with its true head-frame angle; refit when there are enough. Returns the new calib or None.""" - g = cross_spectra(mics) +def add_sample(mics, true_deg, ref=None): + """Store one utterance with its true head-frame angle; refit when there are enough. Returns the new calib, or None + (too few samples, or the refit explains the samples worse than the saved calibration did: that one is kept). + ref: the clip mic's audio (clip_ref): the sample is the wearer's voice as estimate() hears it; an utterance whose + clip voice is not found in the array audio is no sample (the array heard the room, not the wearer).""" + if ref is not None and len(ref) and len(mics) >= NFFT and clip_lag(mics, ref)[1] < CLIP_MIN_SCORE: + return None + g = cross_spectra(mics, ref) if g is None: return None try: @@ -111,12 +180,13 @@ def add_sample(mics, true_deg): gs, ts = gs[-60:], ts[-60:] np.savez(SAMPLES, g=np.array(gs), t=np.array(ts)) if len(ts) >= MIN_SAMPLES and max(ts) - min(ts) >= SPREAD_DEG: - return fit(np.array(gs), np.array(ts)) + return fit(np.array(gs), np.array(ts), keep_better=True) return None -def fit(gs, ts): - """Grid search sign / offset / radius that best explains the samples; saves doa_calib.json.""" +def fit(gs, ts, keep_better=False): + """Grid search sign / offset / radius that best explains the samples; saves doa_calib.json. keep_better: only when + its median error is no worse than the saved calibration's (else None, the saved one stays).""" best = None for sign in (1, -1): for radius in (0.03, 0.035, 0.04, 0.045, 0.05): @@ -130,6 +200,12 @@ def fit(gs, ts): if best is None or score < best[0]: best = (score, c) score, c = best + if keep_better: + try: + if round(score, 1) > float(json.loads(CALIB.read_text())["median_error_deg"]): + return None + except (FileNotFoundError, ValueError, KeyError): + pass c["median_error_deg"] = round(score, 1) c["samples"] = len(ts) c["time"] = time.strftime("%Y-%m-%d %H:%M") diff --git a/audio/ears.py b/audio/ears.py index 4dcb002..8c4c144 100644 --- a/audio/ears.py +++ b/audio/ears.py @@ -273,6 +273,14 @@ def transcribe(audio, prompt=None): return text +def quick(audio): + """transcribe() for a short window of speech still going on (mic.peek()): not kept in HEARD_DIR, no early run.""" + text, stt = _hear(audio, None) + last_stt.clear() + last_stt.update(stt, early=False) + return text + + def early(audio): """mic.py, in a pause of an utterance still going on: whisper starts on what was said so far, in the background (one run at a time: a newer one waits for the older).""" diff --git a/audio/mic.py b/audio/mic.py index 7b1c249..eb1f161 100644 --- a/audio/mic.py +++ b/audio/mic.py @@ -11,7 +11,8 @@ cuts utterances: speech starts when the level stays above START_FACTOR x the bac START_FRAMES frames and ends after END_SILENCE of quiet. While Lumi itself speaks (mouth.py calls speaking()), the head array records nothing (the speaker is ~25x louder than a voice there). The clip mic keeps listening (BARGE_IN): its utterances are marked during_speech, so -lumi.py can stop talking when the visitor says "stop" / "thanks" or asks something new. +lumi.py can stop talking when the visitor says "stop" / "thanks" or asks something new. Lumi's voice in the clip mic +can keep an utterance from ending, so while Lumi talks its last PEEK_WINDOW_S are also offered every PEEK_S (peek()). python audio/mic.py # print every utterance: source, length, level and the direction """ @@ -49,7 +50,15 @@ MAX_UTTERANCE = 8.0 # s (12 s: in a room with music an utterance ne PRE_ROLL = 10 # frames kept before the start (300 ms) AFTER_SPEAKING = 0.4 # s still ignored after Lumi stopped talking (room echo) BARGE_IN = True # clip mic: keep listening while Lumi talks (interruptions) +PEEK_S = 0.7 # clip mic while Lumi talks: every this many s of an utterance still going on ... +PEEK_WINDOW_S = 2.0 # ... its last this many s go to peek() (a stop word: ~0.5 s of whisper on the GPU). + # Lumi's voice in the clip mic kept an utterance going to MAX_UTTERANCE: "Stop. Stop. + # Stop." was heard only when a 17.9 s answer ended (logs/heard/192150.wav, 2026-10-27) +PEEK_MIN_S = 0.5 # s an utterance needs before its first peek RING_S = 20.0 # s of head-array audio kept for the sound direction of clip-mic utterances +DUMP_FLAG = ROOT / "data" / "doa_dump_on" # while this file exists each clip-mic utterance is saved with its +DUMP_DIR = ROOT / "logs" / "doa_dump" # head-array audio (npz), to check the sound direction offline +DUMP_MARGIN_S = 1.0 # s of head-array audio saved before and after the clip's times ("wide") class Utterance: @@ -132,6 +141,8 @@ class Mic(threading.Thread): self.external = None # ALSA device of the clip mic, when found self.muted_until = 0.0 self.speaking_now = False + self.talking_since = None # Lumi started talking at (clip mic, during_speech) + self.peeked, self.peeked_at = None, 0.0 # see peek() self.error = None # the active detector's state (ears.py reads these) @@ -190,6 +201,13 @@ class Mic(threading.Thread): frames = [x for t, x in self.ring if t_start <= t <= t_end + 0.05] return np.concatenate(frames) if frames else np.zeros((0, 6), np.int16) + def _dump(self, u): + """Save a clip-mic utterance with the head array's audio of its time and DUMP_MARGIN_S around it.""" + DUMP_DIR.mkdir(parents=True, exist_ok=True) + wide = self.head_audio(u.t_start - DUMP_MARGIN_S, u.t_end + DUMP_MARGIN_S) + np.savez(DUMP_DIR / time.strftime("%H%M%S.npz"), mics=u.mics, mono=u.mono, wide=wide, + t_start=u.t_start, t_end=u.t_end) + # ---------- recording threads ---------- def run(self): threading.Thread(target=self._clip_loop, daemon=True).start() @@ -249,32 +267,49 @@ class Mic(threading.Thread): proc = subprocess.Popen(["arecord", "-q", "-D", dev, "-f", "S16_LE", "-r", str(RATE), "-c", "1", "-t", "raw"], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) nbytes = FRAME * 2 - talking_since = None # Lumi started talking at (for during_speech) + self.talking_since = None try: while True: raw = proc.stdout.read(nbytes) if len(raw) < nbytes: return - x = np.frombuffer(raw, np.int16) - now = time.time() - if self.muted(): - if not BARGE_IN: - self.clip_seg.reset() - continue - talking_since = talking_since or now - elif talking_since and not self.clip_seg.in_speech: - talking_since = None - level = float(np.sqrt(np.mean(x.astype(np.float32) ** 2))) - done = self.clip_seg.feed(x, level, now) - if done: - frames, t0, t1, peak = done - during = talking_since is not None and t1 >= talking_since - self._put(Utterance(self.head_audio(t0, t1), np.concatenate(frames), t0, t1, peak, "clip", during)) - elif on_quiet and self.clip_seg.quiet_now(): - on_quiet(np.concatenate(self.clip_seg.frames)) + self._clip_frame(np.frombuffer(raw, np.int16), time.time()) finally: proc.kill() + def _clip_frame(self, x, now): + """One 30 ms clip-mic frame (int16 mono).""" + if self.muted(): + if not BARGE_IN: + self.clip_seg.reset() + return + self.talking_since = self.talking_since or now # Lumi started talking at (for during_speech) + elif self.talking_since and not self.clip_seg.in_speech: + self.talking_since = None + level = float(np.sqrt(np.mean(x.astype(np.float32) ** 2))) + done = self.clip_seg.feed(x, level, now) + if done: + frames, t0, t1, peak = done + during = self.talking_since is not None and t1 >= self.talking_since + u = Utterance(self.head_audio(t0, t1), np.concatenate(frames), t0, t1, peak, "clip", during) + if DUMP_FLAG.exists(): + self._dump(u) + self._put(u) + elif on_quiet and self.clip_seg.quiet_now(): + on_quiet(np.concatenate(self.clip_seg.frames)) + elif self.speaking_now and self.clip_seg.in_speech and now - self.peeked_at >= PEEK_S and \ + len(self.clip_seg.frames) * FRAME >= PEEK_MIN_S * RATE: + # Lumi's own voice in the clip mic keeps the utterance from ending: its last seconds are offered now + mono = np.concatenate(self.clip_seg.frames[-round(PEEK_WINDOW_S * RATE / FRAME):]) + self.peeked = Utterance(np.zeros((0, 6), np.int16), mono, now - len(mono) / RATE, now, + self.clip_seg.peak, "clip", True) + self.peeked_at = now + + def peek(self): + """The newest window of a clip-mic utterance still going on while Lumi talks (a mic.Utterance, once), or None: + lumi.py looks for a stop word in it.""" + u, self.peeked = self.peeked, None + return u _mic = None _lock = threading.Lock() @@ -306,8 +341,8 @@ if __name__ == "__main__": u = m.next(1.0) if u is None: continue - ang = doa.estimate(u.mics) if len(u.mics) else (0.0, 0.0, 0.0) + ang = doa.estimate(u.mics, ref=doa.clip_ref(u)) if len(u.mics) else (0.0, 0.0, 0.0) print(f"[{u.source}] {u.seconds:4.1f} s peak {u.peak:5.0f} noise {m.noise:4.0f} " - f"direction {ang[0]:+5.0f} deg (confidence {ang[1]:.2f})") + f"direction {ang[0]:+5.0f} deg (confidence {ang[1]:.2f}{doa.clip_note(u.mics, doa.clip_ref(u))})") except KeyboardInterrupt: pass diff --git a/audio/mouth.py b/audio/mouth.py index a9123b5..3f70af8 100644 --- a/audio/mouth.py +++ b/audio/mouth.py @@ -66,6 +66,13 @@ last_echo = None # echo() of the last own_voice() c last_voice = 0.0 # time.time() when the last say_stream() began to play (lumi.py logs it) +def saying(since): + """What Lumi has been saying from `since` (time.time()) on: the sentence playing then and those after it.""" + texts = [t for when, t in _recent if when > since] + before = [t for when, t in _recent if since - 20.0 < when <= since] # a long sentence takes 15 s and more + return " ".join(before[-1:] + texts) + + def recent_speech(seconds=30.0): """What Lumi said in the last seconds (lumi.py ignores its own voice picked up by the clip mic). Long sentences take 15 s and more to say, so the window is long.""" diff --git a/audio/sing.py b/audio/sing.py index 10ea58d..a697b5a 100644 --- a/audio/sing.py +++ b/audio/sing.py @@ -6,10 +6,12 @@ files, local only, never copied off the robot) and move the head with it. Lumi s Each .json holds the title, the names it is asked by, the lyrics and the head moves timed to the beat. The song is played through mouth._play (the microphone is muted the same way as for speech, -and abort() stops it within 50 ms). The head turns to yaw 0 / pitch 0 and dances around it in a thread, following the +and abort() stops it within 50 ms). The head turns to the centre yaw (the person talked to; 0 by default) / pitch 0 +and dances around it in a thread, following the music: small diagonal bobs landing on the beats in energetic parts, a quick sweep with a dip on a bar's accent or a phrase start, slower sways in calm parts, each move called early enough (the owner's measured head timing) to land -on its beat, one call at a time; it goes back to yaw 0 / pitch 0 when the song ends or is stopped. Never the lift, the waist or the arm. +on its beat, one call at a time; it goes back to the centre yaw / pitch 0 when the song ends or is stopped. Never the lift, +the waist or the arm. """ import difflib import json @@ -22,6 +24,8 @@ import time import numpy as np +from robot.head import YAW_LIMIT + ROOT = pathlib.Path(__file__).resolve().parents[1] MINE = ROOT / "data" / "songs" / "mine" # the owner's songs: local only YAW_SWAY = 40.0 # deg; head yaw stays within +- this while singing (owner: wider, 2026-10-21) @@ -41,17 +45,23 @@ BOB_DEG = (7.0, 12.0) # deg, a beat's bob (diagonal nod / tilt), alter ACCENT_DEG = (25.0, 38.0) # deg, a bar's or phrase's accent: a quick sweep with a dip SWAY_DEG = (12.0, 20.0) # deg, a calm sway ACCENT_EVERY_S = 1.2 # s, at least this between two accents -CENTRE_PITCH = 12.0 # deg; the dance moves around yaw 0, this pitch +CENTRE_PITCH = 12.0 # deg; the dance moves around the centre yaw (sing's centre_yaw), this pitch GAP_S = 0.02 # s between a call returning and the next one MIN_CHANGE = (1.5, 0.8) # deg; every move changes yaw and pitch at least this much MIN_TURN_DEG = 20.0 # two moves in a row differ in direction by at least this (never one line) -HEAD_VEL = 70 # speed ratio % for turning to yaw 0 / pitch 0 before and after the song +HEAD_VEL = 70 # speed ratio % for turning to the centre yaw / pitch 0 after the song LATE_S = 0.4 # s; a move this late is skipped (the previous one took longer) RETURN_WAIT_S = 3.0 # s a new song waits for the head to get back from the last one BANK_SIM = 0.80 # song bank (assistant/song_bank.py): the closest wording at least this similar ... BANK_MARGIN = 0.05 # ... and this much closer than the closest wording of another kind BANK_MIN_WORDS = 3 # the bank reads only words with a song or music word in them and at least this many # words ("Let's", cut off from "Let's follow me", sang once, 2026-10-22) +REPEAT_S = 10.0 # s after a song starts in which its request said again is a repeat, not a new request + # ("Let's make music." said again while the reply took 5.6 s cut the song 2 s in, 2026-10-27) +SPEECH_PER_SYLLABLE = 0.12 # s of speech (Silero VAD, ears.speech_seconds) per syllable that words heard over a song + # need, else whisper read the music: "Last hole." from 0.26 s (0.09 per syllable) cut a + # song; the owner's requests over songs had 0.2-0.3 (logs/heard 2026-10-27). Stricter + # than ears.SPEECH_PER_SYLLABLE (0.05) for normal listening; stop words skip it SONG_WORD = re.compile(r"\bsing|\bsong|\bmusic|\btunes?\b|\bplaylist|k-?pop|노래|노레|노랠|음악|곡|불러|부르|틀어|들려|케이팝", re.I) SING = re.compile(r"\bsing\b|\bsay (?:a |some )?songs?\b|" # whisper writes "let's say song" @@ -245,6 +255,23 @@ def stop_words(text): return bool(STOP.search(text or "")) +def ignored_over_song(text, request, sung_s, speech_s): + """Why words heard while singing (no stop word) leave the song going, or None when they end it (a change: "another + song", "다른 노래", a title; a question or command). Ignored: words with too little speech in them (the music + read by whisper), a single word, and a song asked for again (any time "sing a song"; within REPEAT_S the request's + own words). request: the words that started the song; sung_s: s since it started; speech_s: last_stt's.""" + from audio import ears + change = ANOTHER.search(text) or _title(text, songs(), plain=False) + if speech_s is not None and speech_s < SPEECH_PER_SYLLABLE * ears.syllables(text): + return f"{speech_s:.2f} s of speech: the music" + if len(text.split()) < 2 and not change: + return "one word" + if not change and (asked(text) or sung_s < REPEAT_S and difflib.SequenceMatcher( + None, ears._letters(text), ears._letters(request or "")).ratio() >= ears.SAME_WORDS): + return "the song asked for again" + return None + + def _name_re(name): """A song's name in any spacing ("big bang", "러브어택", "a teez"); Latin names as whole words ("bad" is not in "badminton").""" @@ -495,9 +522,16 @@ def head_targets(song, seed=0): return out -def _move_head(song, seed, stop, head_api): - """Turn the head to yaw 0 / pitch 0, follow the head targets until the song ends or stop is set, then go back - to yaw 0 / pitch 0. One call at a time (each blocks until the head arrives).""" +def around(centre, y): + """A dance yaw y (within +-YAW_SWAY of 0) moved to the centre yaw; the side toward YAW_LIMIT squeezed to fit.""" + centre = max(-YAW_LIMIT, min(YAW_LIMIT, centre)) + room = min(YAW_SWAY, YAW_LIMIT - abs(centre)) if y * centre > 0 else YAW_SWAY + return round(centre + y * room / YAW_SWAY, 2) + + +def _move_head(song, seed, stop, head_api, centre=0.0): + """Turn the head to the centre yaw / pitch 0, follow the head targets around it until the song ends or stop is + set, then go back to the centre yaw / pitch 0. One call at a time (each blocks until the head arrives).""" try: lift, waist, _, _ = head_api.status() except Exception as e: @@ -505,7 +539,7 @@ def _move_head(song, seed, stop, head_api): return t0 = time.time() try: - head_api.moveto([lift, waist, 0.0, 0.0], VEL_LIVELY, VEL_LIVELY) + head_api.moveto([lift, waist, around(centre, 0.0), 0.0], VEL_LIVELY, VEL_LIVELY) for t, yaw, pitch, vel in head_targets(song, seed): while not stop.is_set() and time.time() - t0 < t: stop.wait(0.02) @@ -513,19 +547,20 @@ def _move_head(song, seed, stop, head_api): break if time.time() - t0 - t > LATE_S: continue - head_api.moveto([lift, waist, yaw, pitch], vel, vel) + head_api.moveto([lift, waist, around(centre, yaw), pitch], vel, vel) except Exception as e: print(f"sing: head move failed: {e}") finally: try: - head_api.moveto([lift, waist, 0.0, 0.0], HEAD_VEL, HEAD_VEL) + head_api.moveto([lift, waist, around(centre, 0.0), 0.0], HEAD_VEL, HEAD_VEL) except Exception as e: print(f"sing: head return failed: {e}") -def sing(song_id, abort=None, play=None, head_api=None, load=None): - """Sing one song; blocks until it ends (True) or abort() becomes True (False). The head returns in its own - thread, so a stop is at once. play / head_api / load are for tests (default: the speaker and the real head).""" +def sing(song_id, abort=None, play=None, head_api=None, load=None, centre_yaw=0.0): + """Sing one song; blocks until it ends (True) or abort() becomes True (False). The head dances around centre_yaw + (deg, toward the listener) and returns in its own thread, so a stop is at once. play / head_api / load are for + tests (default: the speaker and the real head).""" global _head_thread from audio import mouth if play is None: @@ -547,7 +582,8 @@ def sing(song_id, abort=None, play=None, head_api=None, load=None): # the clip mic hears the song: its words are Lumi's own voice until 30 s after its end (mouth.recent_speech) mouth._recent.append((time.time() + len(wav) / rate, song["lyrics"])) stop = threading.Event() - _head_thread = threading.Thread(target=_move_head, args=(song, time.time(), stop, head_api), daemon=True) + _head_thread = threading.Thread(target=_move_head, args=(song, time.time(), stop, head_api, centre_yaw), + daemon=True) _head_thread.start() try: return bool(play(wav, rate, abort)) diff --git a/data/grasp_teach.json b/data/grasp_teach.json index 9f79365..254cdc2 100644 --- a/data/grasp_teach.json +++ b/data/grasp_teach.json @@ -28,8 +28,9 @@ -301.0 ], "tcp_offset_flange": [ - 106.4, - -86.5, - 230.5 - ] + 103.6, + -88.3, + 219.7 + ], + "tcp_offset_note": "corrected 2026-10-27 by hover readings at three cup spots (data/hover_readings.json): the taught point carried the camera's cup-centre error (-10.0, +5.2 mm in the arm frame); the camera's own error is fixed in vision/objects.py ROUND_FIX_MM" } \ No newline at end of file diff --git a/docs/TUNING.md b/docs/TUNING.md index a3260e9..dd532eb 100644 --- a/docs/TUNING.md +++ b/docs/TUNING.md @@ -23,7 +23,9 @@ Every value here is a constant at the top of its file, with a comment on what it | `robot/motion.py` | `STILL_S` | 2 s | An arm standing this long short of its target has stopped short: stopped, nothing more sent | | `robot/motion.py` | `SETTLE_S` | 0.3 s | After each arrival (inpos, joints within 0.3°) the arm stands this long before the next move of a route or wave. Estimate | | `manipulation/arm_route.py` | `HEAD_CLEAR_MM` | 250 mm | The gripper (flange, grasp point, finger tips) keeps this from the head's turning centre (`head_cam.head_centre()`) on every pose-graph move, the wave and straight moves with an object. The head camera is 102 mm from that centre; `look` keeps 327 mm. Estimate (head size not measured) | -| `manipulation/arm_route.py` | `EDGES` | give–carry, carry–look, look–wave_out, wave_out–wave_start, wave_start–wave, look–ready | The only joint moves between named poses | +| `manipulation/arm_route.py` | `EDGES` | give–carry, carry–look, look–wave_out, wave_out–wave_start, wave_start–wave, look–ready | The only joint moves between named poses with something in the hand (never a `WAVE_POSES` pose); with an empty hand they win ties | +| `manipulation/arm_route.py` | `NO_EDGES` | look–wave_start | Pose pairs never joined by one joint move with an empty hand (any other pair may be, when its move passes the checks) | +| `manipulation/arm_route.py` | `STOP_DEG` | 10° | Joint travel one more stop on an empty-hand route counts as when routes are compared (estimate) | | `manipulation/arm_route.py` | `LINK_HEAD_CLEAR_MM` | 220 mm | Every arm link (elbow, wrist) keeps this from the head's turning centre on every pose-graph move. Estimate below the least of the taught graph (267 mm at `wave`) | | `manipulation/arm_route.py` | `JOIN_DEG` | 20° | An arm at no pose (free drive, stopped half way) joins the graph by one checked joint move to a pose, the nearest first; joins further than this run at the slow speed | | `manipulation/arm_route.py` | `UP_MM` | 100, 200 mm | When no direct join passes the checks, the arm first goes this far straight up, then joins | @@ -48,6 +50,9 @@ Every value here is a constant at the top of its file, with a comment on what it | `robot/nav_guard.py` | `MARGIN_M`, `LOOKAHEAD_M`, `STEP_M`, `TURN_AHEAD_S` | 0.10 m, 0.30 m, 0.15 m, 0.5 s | While navigation drives (go to, missions, fetch legs, come here, dock): flange, grasp point and finger tips are checked at the base's pose, turned on at its turn rate for `TURN_AHEAD_S`, and every `STEP_M` along the planned path up to `LOOKAHEAD_M`; an arm point nearer than `MARGIN_M` to anything the lidar / map shows (and nearer than now) cancels the move. Estimates | | `robot/nav_guard.py` | `CLEAR_S`, `BLOCK_S` | 1 s, 10 s | The same goal is sent again after the way has been clear this long; blocked this long in all: "I stopped: my arm would hit something on the way" | | `tasks/fetch.py` | `STUCK_S`, `STUCK_M` | 30 s, 0.1 m | A navigation drive that has not moved this far in this time is cancelled | +| `assistant/lumi.py` | `LOOK_ME_PITCH`, `LOOK_ME_TOP_ROW`, `LOOK_ME_UP_STEP`, `LOOK_ME_MIN_DEG`, `LOOK_ME_TRIES`, `LOOK_ME_SETTLE_S` | 0°, 0.08, 10°, 2°, 3, 0.6 s | "Look at me": first head pitch (level); then the head tilts until the person's head sits this share of the image height from the top, tilting up a step while their head is cut, smaller changes not made, at most this many times, each after this wait for new frames | +| `assistant/lumi.py` | `LOOK_WAIST_MAX` | 120° | "Look at me" from past the head's reach with Patrol off: the waist turns in place at most this far (with Patrol the base turns) | +| `assistant/lumi.py` | `FOCUS_EVERY_S`, `FOCUS_DEG`, `FOCUS_REFIND_DEG` | 0.5 s, 8°, 15° | Keeping the head on the person Lumi talks with: checked this often, followed once they are this far off the head's direction; a lost track's person is taken again as a new track within this angle | | `assistant/lumi.py` | `FOLLOW_VOICE_DEG`, `FOLLOW_SORRY_S` | 35°, 20 s | While following, a voice this near the followed person's angle is theirs (estimate); the "I'm following someone" line at most this often | | `tasks/follow.py` | `FOLLOW_GAP_M`, `NEAR_STOP_M` | 1.0 m, 0.8 m | "Follow me": camera distance kept to the person (nearer: no forward); nearer than `NEAR_STOP_M` no turn either. Estimate | | `tasks/follow.py` | `FOLLOW_MAX_MS`, `SPEED_GAIN` | 0.5 m/s, 0.8 /s | Follow speed cap (joy_control's own clamp, [05_AGV_BASE.md](05_AGV_BASE.md)); speed = their walking speed + this per m beyond the gap | @@ -57,7 +62,8 @@ Every value here is a constant at the top of its file, with a comment on what it | `tasks/follow.py` | `STALE_S`, `COAST_S`, `LOST_S` | 0.4 s, 1.0 s, 3 s | A sighting older than `STALE_S` is not new; unseen, the base drives on toward where they should be for `COAST_S`, then slows; "I lost you" after `LOST_S` | | `tasks/follow.py` | `VEL_TAU_S`, `WALK_MAX_MS` | 0.5 s, 2 m/s | Walking-velocity filter time constant; faster estimates are noise | | `tasks/follow.py` | `JUMP_M`, `GATE_GROW_MS`, `SWITCH_M`, `RELOCK_LOOK` | 0.5 m, 0.7 m/s, 0.15 m, 0.6 | Keeping the person: a sighting further than `JUMP_M` (+ `GATE_GROW_MS` per s unseen) from where they should be is someone else; another track must be `SWITCH_M` nearer to be taken; clothes `reid.same` below `RELOCK_LOOK` never taken. Estimates | -| `tasks/follow.py` | `HEAD_YAW_MAX`, `HEAD_PITCH`, `HEAD_STEP_DEG`, `HEAD_LEAD_S`, `HEAD_VEL` | 180°, 10°, 3°, 0.3 s, 50 % | Head on the person while following: yaw limit (the body API range; right behind it keeps the side it came from), fixed pitch, smallest move, sent where they will be this much later, speed | +| `tasks/follow.py` | `HEAD_REL_MAX`, `HEAD_PITCH`, `HEAD_STEP_DEG`, `HEAD_LEAD_S`, `HEAD_VEL` | 30°, 10°, 3°, 0.3 s, 50 % | Head on the person while following: always straight on them (up to ±180° on the waist); a person further than `HEAD_REL_MAX` from the base heading turns the waist for the rest; fixed pitch, smallest move, sent where they will be this much later, speed | +| `tasks/follow.py` | `WAIST_FOLLOW_MAX`, `WAIST_STEP_DEG`, `WAIST_FOLLOW_VEL`, `WAIST_DRIVE_DEG`, `WAIST_RETRY_S` | 90°, 8°, 50 %, 15°, 1 s | Waist toward the person while following, at the same time as the head and the base: at most this far from the front (the base turns for the rest; it unwinds as the base turns), at most `WAIST_STEP_DEG` per body move (the head goes to its full target in the same move) at `WAIST_FOLLOW_VEL`, each step checked along the arm's sweep; the base drives forward only with the person near ahead and the waist within `WAIST_DRIVE_DEG` of the front; a blocked waist turn is tried again after `WAIST_RETRY_S`. Estimates | | `tasks/follow.py` | `BRAKE_S`, `BLOCKED_END_S` | 0.5 s, 5 s | Each command is checked where the base (`BASE_HALF_M + CLEAR_M`) and the arm (`ARM_CLEAR_M`) would be this much later; blocked this long: "Something is in my way" | | `tasks/follow.py` | `TICK_S`, `LOG_S` | 0.1 s, 1 s | Command rate (steady); `follow: v … w … driven … person … head … tick` line (driven = the base's real speed from its pose) in `logs/lumi_console.log` | | `assistant/lumi.py` | `MATCH_DEG_PER_M` | 10 °/m | Person tracking: each m of distance difference counts as this many degrees when a detection is given to a track. Estimate | @@ -123,7 +129,7 @@ Every value here is a constant at the top of its file, with a comment on what it | `assistant/steps.py` | `WAIT_ORDER_S` | 5 min | "do what they tell you": no instruction by then, the mission goes on with its rest | | `tasks/fetch.py` | `RECEIVE_REACH_MM`, `RECEIVE_SHORT_MM`, `RECEIVE_MIN_MM` | 150, 100, 20 mm | "Take this from my hand" and "reach out to me": the hand moves at most this far from `give` towards the thing in the hand (or their hand), stops this far before it, leaves out a shorter move. Estimates | | `tasks/fetch.py` | `REACH_BODY_MM` | 300 mm | "Reach out to me" with no hand of theirs seen: the hand stops this far before the person's body. Estimate | -| `assistant/lumi.py` | `REACH_FRONT_DEG` | 20° | "Reach out to me": a person further to the side is turned to first with the waist (Patrol) or asked to stand in front (Greeter). Estimate | +| `assistant/lumi.py` | `REACH_FRONT_DEG` | 20° | "Reach out to me": a person further to the side is turned to first with the waist (Greeter or Patrol; the base stays). Estimate | | `assistant/lumi.py` | `REACH_HOLD_S` | 30 s | The hand stays held out this long after a reach without "thanks" / "okay", then the arm folds back to `look`. Estimate | | `tasks/fetch.py` | `POINT_STEPS_MM` | 0, ±50, ±100 mm | "Put it here" with pointing: spot grid around the pointed point | | `tasks/fetch.py` | `RECEIVE_DI_S` | 0.5 s | `receive`: the finger sensor (DI_1) must see something this long before Lumi asks the person to let go (the hand closes on their "okay") | @@ -182,6 +188,10 @@ Every value here is a constant at the top of its file, with a comment on what it | `audio/mouth.py` | `STEPS` | 4 | Supertonic synthesis steps (quality / speed). On the GPU a step takes a few ms, on the CPU 0.1–0.27 s | | `audio/mouth.py` | `NOISE_SEED` | 7 | The fixed noise every sentence starts from (one voice for every sentence; another seed is a slightly different voice) | | `audio/mouth.py` | `ECHO_MIN`, `ECHO_TOP_DB`, `ECHO_MIN_FRAMES`, `ECHO_LAG_S`, `ECHO_KEEP_S` | 0.6, 15 dB, 12, −0.3…1.0 s, 30 s | Lumi's own voice in the clip mic: a clip-mic utterance whose spectrogram (16 bands, its frames within `ECHO_TOP_DB` of its loudest, at least `ECHO_MIN_FRAMES`) correlates at least `ECHO_MIN` with what the speaker played `ECHO_LAG_S` earlier is dropped before whisper (`mouth.own_voice`; check: `tests/echo_check.py`). Estimate | +| `audio/mic.py` | `PEEK_S`, `PEEK_WINDOW_S`, `PEEK_MIN_S` | 0.7 s, 2.0 s, 0.5 s | While Lumi talks or sings, its own voice in the clip mic keeps an utterance from ending: every `PEEK_S` its last `PEEK_WINDOW_S` are transcribed (from `PEEK_MIN_S` on) and a stop word in them stops Lumi at once (`lumi.peeked_stop`). Each check is one whisper run (~0.5 s on the GPU) | +| `audio/doa.py` | `CLIP_MAX_LAG_S`, `CLIP_MIN_SCORE` | 0.3 s, 8 | Sound direction with the clip mic (used only with `USE_CLIP_REF`, off: live confidences 0.03–0.07): how far apart in time the clip voice is looked for in the head array's audio, and how clearly it must be found there (correlation peak over its spread; unrelated audio gives 3–5). Below it the plain array estimate is used | +| `assistant/lumi.py` | `DOA_MIN_CONF`, `DOA_CLIP_MIN_CONF` | 0.12, 0.05 | Sound direction trusted from this confidence: plain array estimate / clip voice found in the array (clip-weighted confidences run lower). `DOA_CLIP_MIN_CONF`: estimate | +| `assistant/lumi.py` | `VOICE_KEEP_S` | 20 s | A sure voice direction stands this long for following words whose own direction is too weak | | `audio/tts_gpu.py` | `MAX_LEN` | 640 | Longest text / latent (~44 s of speech) the TensorRT engines take; longer goes to the CPU. A change needs `tts_gpu.py build` | | `audio/ears.py` | `WHISPER_MODEL` | `ggml-large-v3-turbo.bin` (f16) | Speech-to-text model; takes effect when the whisper-server is started again (check: `tests/asr_check.py`) | | `audio/ears.py` | `PROMPT`, `LANG_PROMPT` | "Hi Lumi. Hey Lumi. 루미야."; one per language | Whisper's prompt (spells the name); `LANG_PROMPT` when asked again in one language | @@ -192,6 +202,8 @@ Every value here is a constant at the top of its file, with a comment on what it | `audio/ears.py` | `NOT_SAID` | no word, a leading "-", 자막 / 시청해 주셔서 / thanks for watching | Whisper's subtitle texts for music, dropped | | `audio/ears.py` | `BEAM_SIZE` | 0 (greedy) | Whisper beam search | | `audio/sing.py` | `BANK_SIM`, `BANK_MARGIN` | 0.80, 0.05 | Song bank (`assistant/song_bank.py`): words this similar (bge-m3) to a wording that asks for a song / the songs, and this much closer than to any wording of another kind, sing / list at once without the LLM. Lower catches more and risks wrong songs | +| `audio/sing.py` | `REPEAT_S` | 10 s | After a song starts, its request said again within this time is a repeat and does not stop the song | +| `audio/sing.py` | `SPEECH_PER_SYLLABLE` | 0.12 s | Words heard over a song need this much speech per syllable, else they came from the music and don't stop the song | | `audio/sing.py` | `BANK_MIN_WORDS` | 3 | The song bank reads only words with a song / music word and at least this many words | | `audio/ears.py` | `MERGE_WAIT_S` | 1.5 s | A sentence cut off by a pause (it ends on "let's", "can you", "and", "저기" …: `CUT_OFF`) waits this long for the rest, heard as one sentence (`mic.END_SILENCE` is 0.6 s) | | `audio/mic.py` | `EARLY_QUIET_S`, `EARLY_MIN_S`, `EARLY_MAX_S` | 0.3 s, 0.4 s, 4.0 s | After this much quiet inside an utterance (0.4–4 s long so far) whisper starts on it; the result is used when the utterance ends with no new speech. Longer utterances are talk with pauses, where each early run delays the last | diff --git a/manipulation/arm_route.py b/manipulation/arm_route.py index e18e237..ef612c9 100644 --- a/manipulation/arm_route.py +++ b/manipulation/arm_route.py @@ -1,12 +1,16 @@ -"""The arm moves between named poses only along a graph of taught poses, every joint move checked before anything -moves. +"""The arm moves between named poses only by joint moves between taught poses, every joint move checked before +anything moves. - give - carry - look - wave_out - wave_start - wave + give - carry - look - wave_out - wave_start - wave (EDGES: the moves run live first) | ready -`look` is where every arm action starts (picks and puts go out from it and come back to it, skills.py). From any -pose of the graph the arm goes to another along the graph, one joint move per edge. An arm at no pose (after free +`look` is where every arm action starts (picks and puts go out from it and come back to it, skills.py). With an empty +hand the arm goes from pose to pose by the route of least joint travel (each move its largest joint turn plus +STOP_DEG for the stop), any two poses one joint move apart when that move passes the checks below (all but NO_EDGES; +on equal travel the EDGES first): from wave_start straight to give, from give straight to look. With something in +the hand only the EDGES (fetch runs them as straight lines, the cup upright) and never a wave pose (WAVE_POSES). An +arm at no pose (after free drive, after a stop half way) joins the graph by one checked joint move to a pose of it, the nearest first; when no such move passes, first straight up by UP_MM (a joint move to the IK pose above, checked the same way), then the join. Joins further than JOIN_DEG run at HOLD_SPEED. Only when nothing passes, nothing moves and Lumi asks for the @@ -28,6 +32,7 @@ Cobo π programs start only from `look` (start_program); hand_shaking.jks never python manipulation/arm_route.py goto # go there along the route (SPEED; the owner at the STOP) """ import collections +import heapq import sys import time @@ -39,7 +44,12 @@ from vision import calib, head_cam HOME = "look" # every arm action starts here EDGES = (("give", "carry"), ("carry", "look"), ("look", "wave_out"), ("wave_out", "wave_start"), - ("wave_start", "wave"), ("look", "ready")) # the only joint moves between named poses (both ways) + ("wave_start", "wave"), ("look", "ready")) # the moves with something in the hand (both ways) +NO_EDGES = {frozenset(("look", "wave_start"))} # never one joint move: passes 267 mm from the head (the wave + # goes up and down through wave_out, 309 mm) +WAVE_POSES = ("wave_out", "wave_start", "wave") # never with something in the hand (the cup would tip) +STOP_DEG = 10.0 # deg of joint travel one more stop on a route costs (SETTLE_S, slowing down and + # starting again; an estimate, it only weighs routes against each other) SPEED = "route" # motion.JOINT_SPEED of the moves along the graph, empty hand HOLD_SPEED = "slow" # ... with something in the hand AT_POSE_DEG = 3.0 # deg; the arm is at a pose when every joint is this close (where, programs) @@ -84,10 +94,10 @@ def _deg(now, pose): return max(abs(a - b) for a, b in zip(motion.nearest(pose, now), now)) -def graph(): - """{pose: joints} of the graph's taught poses.""" +def graph(holding=False): + """{pose: joints} of the graph's taught poses (`holding`: without WAVE_POSES).""" p = motion.poses() - return {n: p[n] for e in EDGES for n in e if n in p} + return {n: p[n] for e in EDGES for n in e if n in p and not (holding and n in WAVE_POSES)} def where(now=None): @@ -117,10 +127,64 @@ def _path(a, b, nodes): return None -def hops(now, target, leaf=False): +def _cheapest(a, b, nodes, ok): + """Poses a .. b of least joint travel, one joint move between any two of `nodes` but NO_EDGES and the moves + refused in `ok` ({frozenset pair: passed}); on equal travel fewer moves off EDGES. None when there is none.""" + listed = {frozenset(e) for e in EDGES} + todo, done = [((0.0, 0), [a])], set() + while todo: + cost, path = heapq.heappop(todo) + n = path[-1] + if n == b: + return path + if n in done: + continue + done.add(n) + for m in nodes: + e = frozenset((n, m)) + if m not in done and e not in NO_EDGES and ok.get(e) is not False: + heapq.heappush(todo, ((cost[0] + _deg(nodes[n], nodes[m]) + STOP_DEG, cost[1] + (e not in listed)), + path + [m])) + return None + + +def route(a, b, nodes, holding=False): + """Poses a .. b. Holding: the fewest EDGES. Empty hand: _cheapest, each of its moves checked (check_moves) before + it is taken, a refused one left out and the next cheapest tried. RouteError when there is no way: why the last + move was refused, else NOT_TAUGHT.""" + if holding: + path = _path(a, b, nodes) + if path is None: + log(f"arm route: no way from {a} to {b} among {', '.join(nodes)}") + raise RouteError(*NOT_TAUGHT) + return path + ok, why = {}, NOT_TAUGHT + while True: + path = _cheapest(a, b, nodes, ok) + if path is None: + log(f"arm route: no checked way from {a} to {b}") + raise RouteError(*why) + for x, y in zip(path, path[1:]): + e = frozenset((x, y)) + if e not in ok: + try: + check_moves(nodes[x], [nodes[y]]) + ok[e] = True + except RouteError as err: + if err.args == UNSURE: + raise + ok[e], why = False, err.args + break + else: + return path + + +def hops(now, target, leaf=False, holding=False): """The poses the arm goes through from the joints `now` to `target`, in order (not the one it is at). `leaf`: the arm is out on the task's own checked way from look (above a table): when it is at no pose, straight to target.""" - nodes = graph() + if holding and target in WAVE_POSES: + raise RouteError(*SPILL) + nodes = graph(holding) if target not in nodes: log(f"arm route: {target} is not taught (robot/motion.py teach {target})") raise RouteError(*NOT_TAUGHT) @@ -135,10 +199,7 @@ def hops(now, target, leaf=False): log(f"arm route: arm at {_r(now)}, {d[start]:.0f} deg from {start}, the nearest pose (joins within " f"{JOIN_DEG:.0f})") raise RouteError(*UNKNOWN) - path = _path(start, target, nodes) - if path is None: - log(f"arm route: no way from {start} to {target} among {', '.join(nodes)}") - raise RouteError(*NOT_TAUGHT) + path = route(start, target, nodes, holding) return path if d[start] > EXACT_DEG else path[1:] @@ -248,20 +309,17 @@ def join(now, target, holding=False): """[(pose, joints)] of a checked way from an arm at no pose of the graph to `target`: one joint move to a graph pose (the nearest first), then along the graph; else first straight up by UP_MM. RouteError(UNKNOWN) when no way passes the checks; nothing moved.""" - nodes, p = graph(), motion.poses() + nodes = graph(holding) if target not in nodes: - raise RouteError(*NOT_TAUGHT) + raise RouteError(*(SPILL if holding and target in WAVE_POSES else NOT_TAUGHT)) order = sorted(nodes, key=lambda n: (_deg(now, nodes[n]), n != HOME)) for mm in (None, *UP_MM): first = [] if mm is None else [("up", _up(now, mm))] if first and first[0][1] is None: continue - for n in order: - names = _path(n, target, nodes) - if names is None: - continue - way = first + [(x, p[x]) for x in names] + for n in order: # the nearest pose first, then the way on from it try: + way = first + [(x, nodes[x]) for x in route(n, target, nodes, holding)] return list(zip([x for x, _ in way], check_moves(now, [j for _, j in way], holding))) except RouteError as e: if e.args == UNSURE: @@ -274,7 +332,7 @@ def plan(target, holding=False, leaf=False, now=None): """[(pose, joints)] of the checked way from here to `target` ([] when it is there). RouteError to refuse.""" now = skills._joints() if now is None else now try: - names = hops(now, target, leaf) + names = hops(now, target, leaf, holding) except RouteError as e: if e.args != UNKNOWN: raise diff --git a/manipulation/skills.py b/manipulation/skills.py index 5a9ef8c..f67adbf 100644 --- a/manipulation/skills.py +++ b/manipulation/skills.py @@ -150,10 +150,11 @@ IK_SEEDS = ("ready", "look", "carry", "give") # taught poses whose arm configu # seed, so one seed alone misses cups another configuration reaches WRIST_MIN_DEG = 10.0 # deg; |J5| at least this at above, grasp and lift (estimate: the # proven picks had J5 +20; near 0 J4 / J6 swing round) -TRUSTED_YAW_DEG = 15.0 # deg; grasp turns up to this picked live (-10, -15: 3 of 3); -30 and - # -45 missed 4 of 4 (2026-10-26, a finger end on the rim). The taught - # grasp point's horizontal error turns with the grasp: - # a waist turn or a base move comes before a larger turn +TRUSTED_YAW_DEG = 15.0 # deg; grasp turns from -this to 0 picked live (-10, -15: 3 of 3); -30 + # and -45 missed 4 of 4 (2026-10-26, a finger end on the rim); +15 + # missed 2 of 2 (2026-10-27, a finger on the cup, DI_1 set; never hover- + # checked). The taught grasp point's horizontal error turns with the + # grasp: a waist turn or a base move comes before another turn COMFORT_R_MM = 710.0 # mm, cup's horizontal distance from the arm base origin: picks proven # up to here (furthest live success (-68, 703)); further, the base moves # in first when it can (tasks/fetch.py). Estimate until measured live @@ -760,7 +761,8 @@ def checked(waypoints, start_joints): def pick_options(obj, start, max_yaw=None): - """(waypoints, joints above) of every grasp turn (GRASP_YAWS; within `max_yaw` deg when given) and wrist solution + """(waypoints, joints above) of every grasp turn (GRASP_YAWS; from -`max_yaw` to 0 deg when given: the turns picked + live, TRUSTED_YAW_DEG) and wrist solution reachable from `start`: a joint move down to above that stays above it, then straight down and up; the controller confirms each one given. Every pick that worked live had J5 > 0: those come first. Objects of the wrong width raise.""" @@ -768,7 +770,7 @@ def pick_options(obj, start, max_yaw=None): tried = [] for wrist, seeds in ((1, IK_SEEDS[:1]), (1, IK_SEEDS[1:]), (-1, IK_SEEDS[:1]), (-1, IK_SEEDS[1:])): for yaw in GRASP_YAWS: # the proven wrist (J5 > 0) and `ready` configuration first - if max_yaw is not None and abs(yaw) > max_yaw: + if max_yaw is not None and not -max_yaw <= yaw <= 0: continue waypoints = plan_pick(obj, yaw) for ja in above_joints(waypoints[0][1], start, seeds): @@ -884,7 +886,7 @@ def carry_by_joints(plan): def reachable_pick(obj, start=None, accept=lambda waypoints, ja: True, max_yaw=None): - """(waypoints, joints above) of the first pick option from `start` (home), grasp turned at most `max_yaw` deg + """(waypoints, joints above) of the first pick option from `start` (home), grasp turned -`max_yaw`..0 deg (e.g. TRUSTED_YAW_DEG; None: any), that `accept` also takes, else None.""" for waypoints, ja in pick_options(obj, home_joints() if start is None else start, max_yaw): if accept(waypoints, ja): @@ -893,7 +895,7 @@ def reachable_pick(obj, start=None, accept=lambda waypoints, ja: True, max_yaw=N log(f"grasp {how}, turned {yaw:+d} deg, wrist J5 {ja[4]:+.0f}" if yaw else f"grasp {how}, wrist J5 {ja[4]:+.0f}") return waypoints, ja - log(f"plan refused: no grasp turn{'' if max_yaw is None else f' within {max_yaw:.0f} deg'} reaches " + log(f"plan refused: no grasp turn{'' if max_yaw is None else f' from -{max_yaw:.0f} to 0 deg'} reaches " f"({obj['x']:.0f}, {obj['y']:.0f})") return None @@ -1014,7 +1016,7 @@ def pick(name="cup", colour=None): obj = find(name, colour) log(f"found {obj['colour']} {obj['name']} at ({obj['x']:.0f}, {obj['y']:.0f}) top {obj['top_mm']:.0f} " f"width {obj['width_mm']:.0f}") - plan = reachable_pick(obj) + plan = reachable_pick(obj, max_yaw=TRUSTED_YAW_DEG) # no base here to bring it round (fetch can) if plan is None: raise SkillError("I can't reach it safely.") _guarded(_do_pick, obj, *plan) diff --git a/tasks/fetch.py b/tasks/fetch.py index ec1682f..29722c2 100644 --- a/tasks/fetch.py +++ b/tasks/fetch.py @@ -450,7 +450,7 @@ def _line_holding(name): if _at_pose(name): return try: - names = arm_route.hops(skills._joints(), name, leaf=True) + names = arm_route.hops(skills._joints(), name, leaf=True, holding=True) except arm_route.RouteError as e: raise FetchError(*e.args) from e lines, start = [], None @@ -696,15 +696,19 @@ def _sweep_blocked(deg, what): return False -def _waist_to(rel): +def _waist_to(rel, in_place=False, look=None): """Turn the waist to `rel` deg from the front (the waist of measure-axis), lift and head stay; the arm keeps its - pose; `rel` is cut to the body's limit. False when the arm's sweep is not clear (_sweep_blocked).""" + pose; `rel` is cut to the body's limit. False when the arm's sweep is not clear (_sweep_blocked), or with Patrol + off (stay_put) unless `in_place` (reach: turning to the person in front of Lumi, the base stays). `look`: the + waist-frame angle (deg, + left, as before the turn) the head keeps facing: it sits on the waist, so its yaw goes to + look minus the turn (cut to head.YAW_LIMIT) in the same body move. Without it the head keeps its yaw and turns + with the waist.""" waist = head.status()[1] lo, hi = head.AXIS_LIMITS[1] d = max(lo, min(hi, waist - _waist_turn() + rel)) - waist if abs(d) < 1.0: return True - if stay_put: + if stay_put and not in_place: log("not turning my waist: Patrol is off") return False _go_on() @@ -712,6 +716,9 @@ def _waist_to(rel): if _sweep_blocked(d, "turning my waist"): return False lift, waist = head.status()[:2] + if look is not None: + yaw = max(-head.YAW_LIMIT, min(head.YAW_LIMIT, look - d)) + log(f"head yaw {yaw:+.0f} deg with the waist: still on {look:+.0f} deg") log(f"waist {waist:.0f} -> {waist + d:.0f} deg") _body_move([lift, waist + d, yaw, pitch], vel=WAIST_VEL, acc=20, timeout=60) skills.moved() @@ -1067,8 +1074,9 @@ def waist_for(obj): def _waist_reach(task, obj, say): """(obj, waypoints, joints above) of a pick after a waist turn, for an object the arm doesn't reach from here: the first turn of waist_for whose pick, planned where the object will be (turned), passes; the waist turns (its sweep - checked), the camera looks again and the pick is planned from what it sees. None when no turn reaches it or the - object is not seen again where it should be (then the base moves).""" + checked), the camera looks again and the pick is planned from what it sees. The waist turns in place, also with + Patrol off (the base stays). None when no turn reaches it or the object is not seen again where it should be (then + the base moves).""" for deg in waist_for(obj): try: if not _reachable(turned(obj, deg)): @@ -1077,7 +1085,7 @@ def _waist_reach(task, obj, say): return None _step("turning my waist to reach it", say) _pose(_look()) - if not _waist_to(_waist_turn() + deg): + if not _waist_to(_waist_turn() + deg, in_place=True): return None want = turned(obj, deg) hits = [o for o in skills.look() if _is_task(o, task) and o["seen"] >= skills.MIN_SEEN @@ -1528,23 +1536,26 @@ def _reach_at(obj, g): return True # the width decides up close -def _reach(task, obj, say): +def _reach(task, obj, say, voice=False): """Step 5: (obj, waypoints, joints above) of a pick that passes IK. A cup past COMFORT_R_MM (the arm almost straight knocks it over) is not taken from here while the base can bring it in; out of reach: the waist, then a base move (_approach to pick_goal, every move measured, a way that did nothing not tried again). After every attempt to move, also one that failed half way, the cup is looked at again where it is kept (_see_again): a plan never uses a position from before a move. Up to APPROACH_TRIES times (never on the charger). A cup the base can't - bring nearer is taken from where it stands (any grasp turn as the last resort); else ask the person, saying why.""" + bring nearer is taken from where it stands (any grasp turn as the last resort); else ask the person, saying why. + `voice` (the voice pick, pick_here): never a grasp turn past skills.TRUSTED_YAW_DEG (+15 deg missed 2 of 2 live), + and with Patrol off no base move is tried: the waist only, then the person is asked.""" yaw, tried, why = arm_yaw(), set(), None # grasp turns past skills.TRUSTED_YAW_DEG only when the base can't help _width_far["moves"] = 0 for i in range(APPROACH_TRIES + 1): - can_move = yaw is not None and i < APPROACH_TRIES and not _charging() and "stuck" not in tried + can_move = yaw is not None and i < APPROACH_TRIES and not (voice and stay_put) and not _charging() and \ + "stuck" not in tried edge = can_move and not stay_put and "edge" not in tried and at_edge(obj) if edge: log(f"the {task['object']} at ({obj['x']:.0f}, {obj['y']:.0f}) is at the edge of my reach: closer first") else: try: - plan = _reachable(obj) or ((not can_move or "edge" in tried) and _reachable(obj, None)) + plan = _reachable(obj) or ((not can_move or "edge" in tried) and not voice and _reachable(obj, None)) except skills.SkillError: # too big / small: another one of them here may do other = _other_here(task, obj) if i == 0 else None if other: @@ -1567,7 +1578,7 @@ def _reach(task, obj, say): if edge: tried.add("edge") continue - plan = _reachable(obj, None) + plan = not voice and _reachable(obj, None) if plan: return (obj, *plan) raise @@ -1601,7 +1612,7 @@ def _reach(task, obj, say): why = blocked break if why: - plan = _reachable(obj, None) # the base can't do better: any grasp turn (P2: the last resort) + plan = not voice and _reachable(obj, None) # the base can't do better: any grasp turn (P2: the last resort) if plan: return (obj, *plan) log(f"asking for help: {why}") @@ -1611,7 +1622,7 @@ def _reach(task, obj, say): ("I can't reach it, please move it closer to me.", "손이 닿지 않아요. 저에게 조금 더 가까이 놓아 주세요."))) deadline = time.time() + ASK_WAIT_S while time.time() < deadline: - if _stop.wait(ASK_EVERY_S): + if _stop.wait(ASK_EVERY_S) or skills._cancel.is_set(): raise Stopped() try: obj = _find(task) @@ -2320,7 +2331,7 @@ def _new_run(): _clear() -def _launch(fn, *a): +def _launch(fn, *a, ahead=True): global _thread from tasks import follow # imported here: follow imports this module if follow.running(): # its joy_control commands would fight this task's (2026-10-23: @@ -2330,7 +2341,7 @@ def _launch(fn, *a): def run(): fn(*a) - if not _stop.is_set(): # done or failed: the head looks ahead again (not after a STOP) + if ahead and not _stop.is_set(): # done or failed: the head looks ahead again (not after a STOP) try: head_ahead() except Exception as e: @@ -2398,6 +2409,25 @@ def held_by_skill(what): _set(holding=True, held_object=skills._held["what"], status="holding", step="holding") +def pick_here(name, colour=None, say=None): + """The voice pick ("take the cup", assistant/lumi.py's skill thread): the `name` (`colour`) seen from where Lumi + stands is reached as a fetch reaches it, with trusted grasp turns only (_reach voice=True: from here, else the + waist in place, else with Patrol on the base, else the person is asked) and picked; it ends held just above the + table. Returns the object.""" + task = {"object": name, "colour": colour} + _clear() + try: + obj = _find(task) + log(f"found {obj['colour']} {obj['name']} at ({obj['x']:.0f}, {obj['y']:.0f}) top {obj['top_mm']:.0f} " + f"width {obj['width_mm']:.0f}") + obj, waypoints, ja = _reach(task, obj, say, voice=True) + _step("picking") + skills._guarded(skills._do_pick, obj, waypoints, ja) + finally: + _set(step="") + return obj + + def _hold_again(): """The hand holds something the state does not: it is the thing forgotten last (_forget_held), its name and what put down needs. Live 2026-10-26 18:53:00 one hand read said empty with the cup in it; after that every reply said @@ -2909,8 +2939,9 @@ def _person_point(): def reach(angle=0.0, say=None): """Hold the hand out to the person ("reach out to me", "손 내밀어"): first, when `angle` (deg, + left, waist - frame: the person tracker's) is not 0, the waist turns to face them (_waist_to: Patrol only, its arm sweep - checked; past the waist's limits they are asked to stand in front), then the arm along the pose graph to give + frame: the person tracker's) is not 0, the waist turns to face them (_waist_to, also with Patrol off: the base + stays; its arm sweep checked; past the waist's limits they are asked to stand in front; the waist stays turned + after; the head turns with it onto them and stays on them, also after), then the arm along the pose graph to give (arm_route, every move checked), then at most RECEIVE_REACH_MM straight towards their hand or body (_person_point, _reach_to_hand). The arm stays out; "fold" brings it back to look.""" if "give" not in motion.poses(): @@ -2926,7 +2957,8 @@ def reach(angle=0.0, say=None): try: if angle: # the waist, not the base: the person stays where they are lo, hi = head.AXIS_LIMITS[1] - if not lo <= head.status()[1] + angle <= hi or not _waist_to(angle + _waist_turn()): + if not lo <= head.status()[1] + angle <= hi or \ + not _waist_to(angle + _waist_turn(), in_place=True, look=angle): raise FetchError(*TURN_TO_PERSON) _pose("give") _reach_to_hand(*_person_point()) @@ -2934,7 +2966,7 @@ def reach(angle=0.0, say=None): log("reached out") except Exception as e: _fail(e, say) - _launch(run) + _launch(run, ahead=False) # the head stays on the person, not ahead def _arm(pose): @@ -3023,6 +3055,12 @@ def stop(): if _state["status"] in ("running", "holding", "waiting"): _set(status="stopped") log("stopped") + elif (_thread is None or not _thread.is_alive()) and state().get("status") in ("running", "waiting"): + d = state() # a run of a process that is gone (restarted mid-task): the file says running + d.update(status="stopped", log=d.get("log", []) + [time.strftime("%H:%M:%S") + " stopped"]) + tmp = STATE_FILE.with_suffix(".tmp") + tmp.write_text(json.dumps(d)) + os.replace(tmp, STATE_FILE) def end(timeout=5.0): diff --git a/tasks/follow.py b/tasks/follow.py index 65830cc..2e86650 100644 --- a/tasks/follow.py +++ b/tasks/follow.py @@ -6,11 +6,13 @@ put on the map (base pose + distance, angle) with a smoothed walking velocity, s toward where the person is now, not where they were seen (no stop-and-go when frames are missed). A sighting far from that place is someone else (a passer-by who took the track over); a lost track is swapped for a fresh one near that place whose clothes are not clearly different (re-lock). The head turns toward the person in its own thread (only -this task moves the body meanwhile: head.owners), the base turns after it, so they stay in view when they walk to the -side or behind. The base is driven with joy_control every TICK_S (one command lasts 0.5 s: a stuck loop stops the base -by itself), the arm in look and the waist at the front as for every fetch drive. Every command is checked first: where -the base and the arm would be BRAKE_S later must be clear (lidar + map, agv.clearance); when not, the base stands, and -after BLOCKED_END_S it gives up. +this task moves the body meanwhile: head.owners) and the waist with it, all at once: the head straight on them (up to ++-180 on the waist), the waist a short way toward them in the same move, the base turning toward them at the same time; +as the base comes round the waist and the head unwind (waist_for). Nothing waits for another. Following starts with the +waist where it is (turned toward the person after "look behind"). The base is driven with joy_control every TICK_S (one +command lasts 0.5 s: a stuck loop stops the base by itself), the arm in look; forward only with the person near ahead +and the waist near the front. Every command is checked first: where the base and the arm would be BRAKE_S later must be clear +(lidar + map, agv.clearance); when not, the base stands, and after BLOCKED_END_S it gives up. stop() from any thread: the event is set and the base is sent 0 at once """ @@ -57,7 +59,20 @@ BASE_CLEAR_M = fetch.BASE_HALF_M + fetch.CLEAR_M # m; base centre kept this fa TICK_S = 0.1 # s between commands, steady (joy_control wants > 2 Hz; a tick takes ~10-30 ms) LOG_S = 1.0 # s between "follow: v ... " lines (what the next live run is read from) JOIN_S = 2.0 # s a new "follow me" waits for the old loop to end -HEAD_YAW_MAX = 180.0 # deg; the head turns toward the person up to this far (+ left; body API range, head.AXIS_LIMITS) +BEHIND_DEG = 180.0 # deg; the person's angle from the base is kept within +-this (right behind: one side) +HEAD_REL_MAX = 30.0 # deg; a person this near the base heading is looked at with the head alone; further, the + # waist turns toward them for the rest (the head is never held back by it) +WAIST_FOLLOW_MAX = 90.0 # deg from the front; the waist turns toward the person at most this far, the base turns + # for the rest (fetch.WAIST_SCAN_MAX 120 is the search's; less here, estimate) +WAIST_STEP_DEG = 8.0 # deg; one body move turns the waist at most this far, so every move is short (~0.4 s) and + # the head's next correction is not held back; the waist keeps on in the next move +WAIST_FOLLOW_VEL = 50 # speed ratio % of a move that turns the waist (the head in it too). The waist's deg/s at + # this ratio is not measured; estimate ~40 deg/s as the head's (audio/sing.py), about the + # base's own TURN_MAX_RS turn that sweeps the arm the same way. Lower it if the arm swings + # too hard (fetch.WAIST_VEL 20 is the search's long turns) +WAIST_DRIVE_DEG = 15.0 # deg; the base drives forward only with the waist this near the front: navigation does not + # know the arm, blocked() checks it turned (estimate) +WAIST_RETRY_S = 1.0 # s; a waist turn found blocked is not tried again for this long (each try probes the map) HEAD_PITCH = 10.0 # deg; head pitch while following, a little up toward a standing person (as "look at me") HEAD_STEP_DEG = 3.0 # deg; a new head move only when the target is this far from where the head was sent HEAD_LEAD_S = 0.3 # s; the head is sent where the person will be this much later (a moveto takes time) @@ -181,16 +196,14 @@ def ready(): def prepare(): - """Arm to look, waist to the front (as before every fetch drive). The head stays where it is: it is on the person - already (the track is seen), and ahead they may be out of view (lost at once, 2026-10-21). Returns the arm's points (m, base - frame) that stick out past the base, [] when the arm's place on the base is not measured. FetchError when it - must not drive.""" + """Arm to look. The waist and the head stay where they are: they are on the person already (the track is seen), + and ahead they may be out of view (lost at once). Returns the arm's points (m, base frame) that stick out past the + base, [] when the arm's place on the base is not measured. FetchError when it must not drive.""" why = ready() if why: raise fetch.FetchError(*why) fetch._stop.clear() # a stop said earlier must not end this one fetch._drive_pose() - fetch._waist_front() if fetch.arm_yaw() is None: fetch.log("follow: the arm's place on the base is not measured: only the base is checked") return [] @@ -203,6 +216,12 @@ def _to_map(pose, d, a): return np.array([x + d * math.cos(th + math.radians(a)), y + d * math.sin(th + math.radians(a))]) +def _seen_from(pose, turned): + """The base pose turned by the waist's turn (deg): sightings are waist-frame angles (lumi.Vision), _to_map them + from this.""" + return pose[0], pose[1], pose[2] + math.radians(turned) + + def _rel(pose, p): """(distance m, angle deg + left) of the map point p from the base at pose.""" x, y, th = pose @@ -256,19 +275,54 @@ def _pick(see, got, people, person, pose, sig, now): return best[1:] -def _head_follow(target, done, lift, waist, stats): - """Turn the head to target[0] (yaw, pitch) whenever it is HEAD_STEP_DEG from where it was sent last. One moveto - at a time, from this thread only: overlapping calls hang the body API. The drive loop never waits for it.""" - sent = None +def waist_for(b): + """Waist turn (deg from the front, + left) for a person b deg from the base heading: what is past HEAD_REL_MAX, + up to WAIST_FOLLOW_MAX. 0 when they are near ahead, so it unwinds as the base turns to them.""" + return max(-WAIST_FOLLOW_MAX, min(WAIST_FOLLOW_MAX, math.copysign(max(0.0, abs(b) - HEAD_REL_MAX), b))) + + +def _head_follow(target, done, lift, front, w, waist_free, stats): + """Turn the head, and the waist with it, to the person at target[0] (deg from the base heading, pitch). Every move + sends the head straight to them (up to +-BEHIND_DEG on the waist, never held back) and the waist at most + WAIST_STEP_DEG toward waist_for() in the same move, so the waist keeps turning move after move while the base turns + and the head stays on the person all along. Every waist step is checked along the arm's sweep (fetch.turn_hits); + blocked, or waist_free False (arm not in look, its place not measured): the waist stays and the head alone turns. + `front`: the waist's reading at the front, `w`: its turn from there now. One moveto at a time, from this thread + only: overlapping calls hang the body API. The drive loop never waits for it.""" + sent, retry = None, 0.0 # (head yaw, pitch) sent last while not done.is_set(): t = target[0] - if t is None or sent is not None and max(abs(t[0] - sent[0]), abs(t[1] - sent[1])) < HEAD_STEP_DEG: + if t is None: done.wait(TICK_S / 2) continue + b, pitch = t + want = waist_for(b) - w if waist_free and time.time() >= retry else 0.0 + step = max(-WAIST_STEP_DEG, min(WAIST_STEP_DEG, want)) + if abs(step) < HEAD_STEP_DEG and (waist_for(b) != 0.0 or abs(step) < 0.5): + step = 0.0 # small steps only for the last bit to the front + yaw = max(-BEHIND_DEG, min(BEHIND_DEG, b - w - step)) + off = float("inf") if sent is None else max(abs(yaw - sent[0]), abs(pitch - sent[1])) + if step == 0.0 and off < HEAD_STEP_DEG: + done.wait(TICK_S / 2) + continue + if step: + try: + hit = fetch.turn_hits(step) + except (ConnectionError, OSError, ValueError, KeyError) as e: # not checked: not turned + fetch.log(f"follow: the waist's sweep can't be checked: {e!r}") + hit = () + if hit is not None: + if hit: + fetch.log(f"follow: waist stays at {w:+.0f} deg, turning {step:+.0f} my arm would hit something " + f"at ({hit[0]:.2f}, {hit[1]:.2f}); the head turns alone") + retry = time.time() + WAIST_RETRY_S + continue # at once again: the head alone + vel = min(HEAD_VEL, WAIST_FOLLOW_VEL) if step else HEAD_VEL try: t0 = time.time() - head.moveto([lift, waist, *t], vel=HEAD_VEL, acc=HEAD_VEL, timeout=HEAD_TIMEOUT_S) - sent, stats["head"], stats["head_ms"] = t, t[0], round(1000 * (time.time() - t0)) + head.moveto([lift, front + w + step, yaw, pitch], vel=vel, acc=vel, timeout=HEAD_TIMEOUT_S) + w += step + sent, stats["head"], stats["head_ms"] = (yaw, pitch), yaw, round(1000 * (time.time() - t0)) except (ConnectionError, OSError, ValueError, KeyError) as e: fetch.log(f"follow: head error {e!r}") done.wait(1.0) @@ -279,16 +333,35 @@ def _run(see, say, people): v = w = 0.0 done, target, stats = threading.Event(), [None], {"head": None, "head_ms": None} head.owners = (threading.current_thread(),) - person, head_thread = Person(), None + person, head_thread, front = Person(), None, None try: - got = see() # where they are now: prepare() may turn the waist + got = see() # where they are now (waist-frame angle) sig = got[3] if got else None if _fresh(got): - person.seen(_to_map(agv.pose(), *got[:2]), time.time() - got[2]) + person.seen(_to_map(_seen_from(agv.pose(), fetch._waist_turn()), *got[:2]), time.time() - got[2]) arm_pts = prepare() - lift, waist = head.status()[:2] - head_thread = threading.Thread(target=_head_follow, args=(target, done, lift, waist, stats), daemon=True, - name="follow head") + lift, waist, yaw = head.status()[:3] + turned = fetch._waist_turn() + front, gaze = waist - turned, turned + yaw # the waist's reading at the front; where the head looks + waist_free = bool(arm_pts) # its sweep can be checked ... + if waist_free: + try: + waist_free = fetch._at_pose(fetch._look()) # ... and the arm is folded in look + except Exception as e: + waist_free = False + fetch.log(f"follow: the arm's pose can't be read: {e!r}") + if not waist_free: + fetch.log("follow: my arm is not in look: the waist stays, the head turns alone") + if not waist_free and abs(turned) >= WAIST_DRIVE_DEG: # it would never drive: the waist to the front, the + look = got[1] if _fresh(got) else None # head kept on them (fetch._waist_to checks the sweep) + if not fetch._waist_to(0.0, in_place=True, look=look): + raise fetch.FetchError("My arm can't turn back to the front: something is in its way.", + "팔을 앞으로 돌릴 수 없어요. 뭔가 막고 있어요.") + lift, waist, yaw = head.status()[:3] + turned = waist - front + gaze = turned + yaw + head_thread = threading.Thread(target=_head_follow, args=(target, done, lift, front, turned, waist_free, stats), + daemon=True, name="follow head") head.owners += (head_thread,) head_thread.start() start_t = next_t = time.time() # lost counts from here: prepare() takes a few seconds @@ -296,8 +369,13 @@ def _run(see, say, people): while not _stop.is_set(): now = time.time() pose = agv.pose() + try: + turned = head.status()[1] - front + except (ConnectionError, OSError, KeyError): + pass # the last reading: the body API may be busy + seen_from = _seen_from(pose, turned) mine, was = see(), see - see, got = _pick(see, mine, people, person, pose, sig, now) + see, got = _pick(see, mine, people, person, seen_from, sig, now) if see is not was: fetch.log(f"follow: re-locked onto the person at {got[0]:.2f} m {got[1]:+.0f} deg") elif got is None and _fresh(mine) and now - odd_t > LOG_S: @@ -305,9 +383,9 @@ def _run(see, say, people): fetch.log(f"follow: a sighting at {mine[0]:.2f} m {mine[1]:+.0f} deg is not them (someone else)") if _fresh(got): _followed[0] = (got[1], now - got[2]) - p = _to_map(pose, *got[:2]) + p = _to_map(seen_from, *got[:2]) person.seen(p, now - got[2]) - near = [float(np.linalg.norm(_to_map(pose, *o[1:3]) - p)) for o in people() if _fresh(o[1:])] \ + near = [float(np.linalg.norm(_to_map(seen_from, *o[1:3]) - p)) for o in people() if _fresh(o[1:])] \ if people else [0.0] if got[3] is not None and all(e > JUMP_M or e < 0.05 for e in near): # alone (or themselves): sig = reid.blend(sig, got[3]) # these clothes are theirs @@ -318,19 +396,20 @@ def _run(see, say, people): if person.p is None: # not seen yet (only before the first sighting) cmd, d, a, walk = (0.0, 0.0), 0.0, 0.0, 0.0 else: - # angles taken on from the head's last target, not -180..180: right behind, +179 and -179 are - # the same place, the head must not swing round and the base not turn the other way - ref = target[0][0] if target[0] else 0.0 + # angles from the base heading, taken on from the last target, not -180..180: right behind, +179 + # and -179 are the same place, the head and waist must not swing round, the base not turn the other way + ref = target[0][0] if target[0] else gaze d, a = _rel(pose, person.at(now)) a = ref + (a - ref + 180.0) % 360.0 - 180.0 yaw = _rel(pose, person.at(now + HEAD_LEAD_S))[1] yaw = ref + (yaw - ref + 180.0) % 360.0 - 180.0 - target[0] = (max(-HEAD_YAW_MAX, min(HEAD_YAW_MAX, yaw)), HEAD_PITCH) + target[0] = (max(-BEHIND_DEG, min(BEHIND_DEG, yaw)), HEAD_PITCH) walk = float(person.vel @ np.array([math.cos(pose[2]), math.sin(pose[2])])) - cmd = speeds(d, a, v, w, walk, go=now - person.t <= COAST_S, dt=TICK_S) + go = now - person.t <= COAST_S and abs(turned) < WAIST_DRIVE_DEG # forward with the waist ahead + cmd = speeds(d, a, v, w, walk, go=go, dt=TICK_S) spot = cmd[0] == 0.0 and cmd[1] != 0.0 # a turn on the spot (the person aside or behind) if spot and not turning: - hit = fetch.turn_hits(a) # the arm's whole sweep toward them + hit = fetch.turn_hits(a - turned) # the arm's whole sweep toward them (it is turned already) if hit is not None: fetch.log(f"follow: turning {a:+.0f} deg my arm would hit something at " f"({hit[0]:.2f}, {hit[1]:.2f})") @@ -339,7 +418,8 @@ def _run(see, say, people): return turning = spot # stopped by something: on again only when the speed it was stopped at is clear (no creeping up to it) - why = cmd != (0.0, 0.0) and blocked(max(cmd[0], hold_v) if cmd[0] else 0.0, cmd[1], arm_pts, pose) + pts = [fetch._rot(turned) @ p for p in arm_pts] # the arm turned with the waist + why = cmd != (0.0, 0.0) and blocked(max(cmd[0], hold_v) if cmd[0] else 0.0, cmd[1], pts, pose) if why: if blocked_t is None: fetch.log(f"follow: standing, {why}") @@ -358,7 +438,7 @@ def _run(see, say, people): driven = math.hypot(pose[0] - log_pose[0], pose[1] - log_pose[1]) / max(now - log_t, 1e-3) log_t, log_pose = now, pose fetch.log(f"follow: v {v:.2f} w {w:+.2f} driven {driven:.2f} m/s | person {d:.2f} m {a:+.0f} deg, seen " - f"{now - (person.t or now):.2f} s ago, walking {walk:+.2f} m/s | head " + f"{now - (person.t or now):.2f} s ago, walking {walk:+.2f} m/s | waist {turned:+.0f} head " f"{stats['head'] or 0:+.0f} deg ({stats['head_ms']} ms) | tick {1000 * (time.time() - now):.0f} ms") next_t = max(next_t + TICK_S, time.time()) # a steady rate; a slow tick is not caught up _stop.wait(next_t - time.time()) @@ -382,11 +462,17 @@ def _run(see, say, people): _joy(0.0, 0.0) except (ConnectionError, OSError): pass # one command lasts 0.5 s: the base stops anyway - if head_thread is not None: # the head back to rest (ahead, looking down) once its own - head_thread.join(HEAD_TIMEOUT_S) # move has ended: overlapping movetos hang the body API - try: - head.moveto([*head.status()[:2], 0.0, head.HEAD_REST_PITCH], vel=HEAD_VEL, acc=HEAD_VEL, - timeout=HEAD_TIMEOUT_S) + if head_thread is not None: # the head back to rest (ahead, looking down), the waist to + head_thread.join(HEAD_TIMEOUT_S) # the front, once its own move has ended: overlapping movetos + try: # hang the body API + lift, waist = head.status()[:2] + back = front - waist + if abs(back) >= 1.0 and fetch.turn_hits(back) is not None: + fetch.log(f"follow: the waist stays at {-back:+.0f} deg: my arm would hit something going back") + back = 0.0 + vel = fetch.WAIST_VEL if abs(back) >= 1.0 else HEAD_VEL + head.moveto([lift, waist + back, 0.0, head.HEAD_REST_PITCH], vel=vel, acc=vel, + timeout=60 if abs(back) >= 1.0 else HEAD_TIMEOUT_S) except (ConnectionError, OSError, ValueError, KeyError) as e: fetch.log(f"follow: head error {e!r}") head.owners = () diff --git a/tests/command_cases.py b/tests/command_cases.py index 242a387..bf879f5 100644 --- a/tests/command_cases.py +++ b/tests/command_cases.py @@ -155,7 +155,9 @@ for t, want in [("look at me", "me"), ("look at me please", "me"), ("eyes on me" ("look over your right shoulder", "right 180"), ("뒤 봐", "left 180"), ("뒤를 봐", "left 180"), ("뒤돌아 봐", "left 180"), ("뒤쪽 봐", "left 180"), ("뒤에 봐 줘", "left 180"), ("고개 뒤로 돌려", "left 180"), ("오른쪽 뒤 봐", "right 180"), ("back side 봐", "left 180"), ("뒤 좀 look 해 줘", "left 180"), - ("look forward", "center"), ("look ahead", "center")]: + ("look forward", "center"), ("look ahead", "center"), + ("I am your right side.", "right"), ("I'm on your left side", "left"), ("I'm behind you", "left 180"), + ("나 오른쪽에 있어", "right"), ("나 여기 왼쪽이야", "left")]: # where the speaker stands: the head turns there alts = " | ".join("talk" if w.strip() == "talk" else f"action:look {w.strip()}" for w in want.split("|")) both("look", [t], alts) @@ -227,7 +229,7 @@ for t in ["How many people work at Cutshion company?", "how many people work at "쿳션에는 몇 명이 일해요?"]: # knowledge both("question", [t], "talk") -for t in ["I'll be back", "I'm behind you", "I'll be right back"]: # "back", "behind": no head turn +for t in ["I'll be back", "I'll be right back"]: # "back": no head turn both("question", [t], "talk | end") # ---------- things it can't do: a plain answer, no motion ---------- diff --git a/tests/no_robot.py b/tests/no_robot.py new file mode 100644 index 0000000..d2563a6 --- /dev/null +++ b/tests/no_robot.py @@ -0,0 +1,37 @@ +"""Import first in a test: any connection to the robot (arm / body controller, AGV base) is refused and the test fails +at exit with where it came from, even when the code under test catches the error. `import tests.no_robot` or +`from tests import no_robot`.""" +import atexit +import os +import socket +import sys +import traceback + +ROBOT_HOSTS = {"192.168.10.90", "192.168.10.10"} # arm / body controller, AGV base (CLAUDE.md "Addresses") +hits = [] # (host, port, the caller's frame) + + +def _guard(real): + def connect(sock, address, *a): + if isinstance(address, tuple) and address[0] in ROBOT_HOSTS: + frames = [f for f in traceback.extract_stack()[:-1] if "/tests/no_robot.py" not in f.filename] + ours = [f"{f.filename.rsplit('/', 1)[-1]}:{f.name}:{f.lineno}" for f in frames + if "lumi-wave" in f.filename and "site-packages" not in f.filename] + caller = " < ".join(ours[::-1][:4]) or "?" # innermost first + hits.append((address[0], address[1], caller)) + raise ConnectionRefusedError(f"a test reached the robot: {address[0]}:{address[1]} from {caller}") + return real(sock, address, *a) + return connect + + +socket.socket.connect = _guard(socket.socket.connect) +socket.socket.connect_ex = _guard(socket.socket.connect_ex) + + +@atexit.register +def _report(): + if hits: + for host, port, caller in dict.fromkeys(hits): + print(f"REACHED THE ROBOT: {host}:{port} from {caller}", file=sys.stderr) + sys.stderr.flush() + os._exit(1) diff --git a/tests/test_abilities.py b/tests/test_abilities.py index 5cd375f..46aac8c 100644 --- a/tests/test_abilities.py +++ b/tests/test_abilities.py @@ -2,6 +2,7 @@ the rest on "tell me more" / "yes" right after. No robot, no speaker, no LLM. python tests/test_abilities.py""" import types +import no_robot # noqa: F401 any connection to the robot fails the test from assistant import abilities as ab from assistant import lumi from audio import mouth @@ -39,6 +40,7 @@ mouth.say = lambda text, lang=None, abort=None: said.append(text) lumi.ears.understood = lambda *a: True lumi.ears.last_stt = {"language": "english", "logprob": -0.1} L = lumi.Lumi.__new__(lumi.Lumi) +L.markers = ["home", "p1"] # never the base's marker list L.lang, L.current, L.closing_pending = "en", None, None L.brain = types.SimpleNamespace(history=[]) L.follow_stop = lambda text: False diff --git a/tests/test_arm.py b/tests/test_arm.py index 4dba123..d2965d5 100644 --- a/tests/test_arm.py +++ b/tests/test_arm.py @@ -1,4 +1,5 @@ """Self-check of robot/arm.py retries, no robot: python tests/test_arm.py""" +import no_robot # noqa: F401 any connection to the robot fails the test from robot import arm sent = [] diff --git a/tests/test_arm_bank.py b/tests/test_arm_bank.py index 2360590..70ab7f1 100644 --- a/tests/test_arm_bank.py +++ b/tests/test_arm_bank.py @@ -4,6 +4,7 @@ python tests/test_arm_bank.py Needs the embedding server (assistant/knowledge.embed starts it); nothing moves. Every arm / hand capability said in new ways (English and Korean at every level) reads as that one motion or as nothing (the LLM then decides); hard negatives (questions, remarks, past, negations, gestures Lumi has none of) and side words never become another motion.""" +import no_robot # noqa: F401 any connection to the robot fails the test from assistant import intent_bank as ib M = ["home", "dock2", "booth_A", "stage", "coffee_corner", "p3"] @@ -53,6 +54,7 @@ NEVER = [ # no motion at all from the bank ("the kids want to wave at you", False), ("can my son shake your hand", False), ("shaking hands is fun", False), ("you folded your arm earlier", False), ("손 펴도 돼?", False), ("팔 접는 게 좋아", False), ("you're good at opening your hand", False), + ("put your arm in tuck position", False), ("move your hand to high position", False), # not taught: the model asks ] diff --git a/tests/test_arm_give_route.py b/tests/test_arm_give_route.py new file mode 100644 index 0000000..5147dc3 --- /dev/null +++ b/tests/test_arm_give_route.py @@ -0,0 +1,63 @@ +"""Self-check of the routes to `give` (manipulation/arm_route.py) with the taught poses, the measured head centre and +the offline arm kinematics (robot/kinematics.py), no robot: python tests/test_arm_give_route.py""" +import numpy as np + +import no_robot # noqa: F401 any connection to the robot fails the test +from manipulation import arm_route, skills +from robot import kinematics, motion +from vision import head_cam + +POSES = {"ready": [-284.35, -75.43, -52.45, -136.99, 26.46, -278.46], # data/arm_poses.json, 2026-10-27 + "carry": [-280.6, -86.13, -2.58, -173.3, 85.86, 119.9], + "give": [-270.97, -86.67, -3.28, -168.9, 56.87, 128.14], + "look": [-239.15, -88.4, -29.48, 199.97, 81.4, 158.35], + "wave_out": [-239.15, -89.88, 0.5, -160.11, 77.47, -201.64], + "wave_start": [-178.86, -77.26, -2.49, -175.06, 38.21, -219.73], + "wave": [-178.86, -77.26, -17.24, -175.06, 38.37, -219.7]} +motion.poses = lambda: dict(POSES) +head_cam.head_centre = lambda: np.array([-93.0, -19.9, 356.1]) # the 2026-10-19 fit +skills._ask = kinematics.ask +arm_route.log = lambda *a: None + + +def names(target, now, holding=False): + return [n for n, _ in arm_route.plan(target, holding, now=list(now))] + + +def moved(j, joint, deg): + j = list(j) + j[joint] += deg + return j + + +# ---------- empty hand: the least joint travel, every move checked ---------- +assert names("give", POSES["wave_start"]) == ["give"] # after a wave: straight down to give +assert names("give", POSES["wave"]) == ["give"] +assert names("give", POSES["look"]) == ["give"] # 32 deg, not look -> carry -> give (71) +assert names("look", POSES["give"]) == ["look"] +assert names("look", POSES["wave_start"]) == ["wave_out", "look"] # never look - wave_start in one move +assert names("wave_start", POSES["look"]) == ["wave_out", "wave_start"] +assert names("give", moved(POSES["carry"], 0, -8)) == ["carry", "give"] # near carry: to carry, then on +assert names("give", moved(POSES["carry"], 0, -30)) == ["carry", "give"] # far: the nearest pose first (join) +assert names("give", moved(POSES["look"], 1, 6)) == ["look", "give"] + +# ---------- holding: only the EDGES, never a wave pose, the cup upright ---------- +assert names("give", POSES["look"], holding=True) == ["carry", "give"] +assert names("look", POSES["give"], holding=True) == ["carry", "look"] +for start in (POSES["wave_start"], moved(POSES["wave_start"], 0, 5), moved(POSES["wave_out"], 2, 4)): + try: + route = names("give", start, holding=True) + except arm_route.RouteError: + continue # refused: nothing moves + assert not set(route) & set(arm_route.WAVE_POSES), route + prev = start + for n in route: + assert arm_route.move_problem(prev, motion.nearest(POSES[n], prev), head_cam.head_centre(), True) is None + prev = POSES[n] +assert arm_route.hops(POSES["look"], "give", leaf=True, holding=True) == ["carry", "give"] # fetch._line_holding +try: + arm_route.plan("wave_start", holding=True, now=POSES["look"]) + raise AssertionError("went to a wave pose holding") +except arm_route.RouteError as e: + assert e.args == arm_route.SPILL, e.args +print("arm give route ok") diff --git a/tests/test_arm_route.py b/tests/test_arm_route.py index f340d48..21fa6a7 100644 --- a/tests/test_arm_route.py +++ b/tests/test_arm_route.py @@ -7,6 +7,7 @@ from pathlib import Path import numpy as np +import no_robot # noqa: F401 any connection to the robot fails the test from manipulation import arm_route, skills from robot import arm, gripper, motion from tasks import fetch @@ -76,19 +77,30 @@ def refused(reason, fn, *a, **k): edges = {frozenset(e) for e in arm_route.EDGES} -# ---------- every pair of poses: along the graph's edges, one joint move each ---------- +# ---------- every pair of poses, empty hand: one checked joint move (all clear here) but look - wave_start ---------- for a in POSES: for b in POSES: fake = use(POSES[a]) route = arm_route.goto(b) - assert [a] + route == arm_route._path(a, b, POSES) and fake.sent == [POSES[n] for n in route], (a, b, route) + assert fake.sent == [POSES[n] for n in route] and arm_route.where(fake.j) == b, (a, b, route) + want = [] if a == b else ["wave_out", b] if {a, b} == {"look", "wave_start"} else [b] + assert route == want, (a, b, route) # look - wave_start: wave_out ties wave, EDGES first +# ... holding: along EDGES only, never a wave pose +for a in POSES: + for b in POSES: + if a in arm_route.WAVE_POSES or b in arm_route.WAVE_POSES: + continue + fake = use(POSES[a]) + route = arm_route.goto(b, holding=True) + assert [a] + route == arm_route._path(a, b, arm_route.graph(True)), (a, b, route) assert all(frozenset(p) in edges for p in zip([a] + route, route)), (a, b, route) - assert arm_route.where(fake.j) == b +use(POSES["look"]) +refused(arm_route.SPILL, arm_route.goto, "wave_start", holding=True) use(POSES["give"]) -assert arm_route.goto("look") == ["carry", "look"] # after giving: give -> carry -> look -assert arm_route.goto("give") == ["carry", "give"] # to give: look -> carry -> give -use(POSES["wave"]) -assert arm_route.goto("look") == ["wave_start", "wave_out", "look"] # fold: down to look +assert arm_route.goto("look", holding=True) == ["carry", "look"] # after giving: give -> carry -> look +assert arm_route.goto("give", holding=True) == ["carry", "give"] # to give: look -> carry -> give +use(POSES["wave_start"]) +assert arm_route.goto("give") == ["give"] # empty after a wave: straight to give assert not any("tuck" in e for e in arm_route.EDGES) use(POSES["look"]) assert arm_route.goto("wave_start") == ["wave_out", "wave_start"] # up: never look -> wave_start directly @@ -109,6 +121,8 @@ fake = use(near) assert arm_route.goto("carry") == ["look", "carry"] and fake.sent == [POSES["look"], POSES["carry"]], fake.sent fake = use([20.5, 0, 0, 0, 0, 0]) # within EXACT_DEG of carry: straight on assert arm_route.goto("give") == ["give"] +fake = use([23.0, 0, 3, 0, 0, 0]) # nearer carry than give: carry first +assert arm_route.goto("give") == ["carry", "give"] # ---------- 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]) @@ -128,10 +142,16 @@ 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) for start in (POSES["look"], near, POSES["give"]): fake = use(start) - refused(arm_route.NEAR_HEAD, arm_route.goto, "give" if start != POSES["give"] else "look") + refused(arm_route.NEAR_HEAD, arm_route.goto, "give" if start != POSES["give"] else "look", holding=True) assert fake.sent == [], fake.sent +fake = use(POSES["look"]) # empty: around it, every move checked +assert arm_route.goto("give") == ["ready", "give"], fake.sent # (ready ties wave_out) fake = use(POSES["look"]) -assert arm_route.goto("wave") == ["wave_out", "wave_start", "wave"] # other edges: clear of it +assert arm_route.goto("wave") == ["wave"] # clear of it +head["centre"] = np.array([0.0, -300.0, 300.0]) # on every way out of look: refused, why said +fake = use(POSES["look"]) +refused(arm_route.NEAR_HEAD, arm_route.goto, "wave") +assert fake.sent == [] head["centre"] = None # the head not measured: nothing moves refused(arm_route.UNSURE, arm_route.goto, "look") head["centre"] = FAR @@ -141,7 +161,9 @@ refused(arm_route.BLOCKED, arm_route.goto, "give") assert fake.sent == [] POSES["give"] = [40.0, 0, 0, 0, 0, 0] del POSES["wave_start"] -refused(arm_route.NOT_TAUGHT, arm_route.goto, "wave") # no way to wave without wave_start +del POSES["wave"] +refused(arm_route.NOT_TAUGHT, arm_route.goto, "wave_start") # not taught +POSES["wave"] = [0.0, -20, 20, 0, 20, 0] refused(arm_route.NOT_TAUGHT, arm_route.goto, "nowhere") POSES["wave_start"] = [0.0, -20, 20, 0, 0, 0] @@ -195,7 +217,7 @@ arrived = [e for e in fake.log if e[0] == "get_data"][0][4] second = [e for e in fake.log if e[0] == "joint_move"][1][4] assert second - arrived >= motion.SETTLE_S * 0.9, second - arrived # stood at wave_out first fake = arm.cmd = QueueArm(POSES["look"]) -arm_route.goto("wave_start", holding=True) +arm_route.goto("give", holding=True) hold = motion.JOINT_SPEED[arm_route.HOLD_SPEED] assert order(fake) == ["joint_move", "get_data", "joint_move", "get_data"], order(fake) assert fake.moves() == [(hold, hold * motion.JOINT_ACCEL_FACTOR, keys)] * 2 and hold < route, fake.moves() diff --git a/tests/test_arm_words.py b/tests/test_arm_words.py index 6473d86..1fc6e08 100644 --- a/tests/test_arm_words.py +++ b/tests/test_arm_words.py @@ -4,6 +4,7 @@ holding = give; the known faults of that day; negations, later times and remarks .venv/bin/python tests/test_arm_words.py """ +import no_robot # noqa: F401 any connection to the robot fails the test from assistant import brain from tests import command_check @@ -50,6 +51,20 @@ CASES = [ # (text, state, route) ('"give it to me" is a nice English phrase', "holding", None), ("몸 5센티만 내려 주세요", "holding", "action:lift"), ("테이블에 놔 줄래? 영상 찍고 있어", "holding", "place"), ("it's my birthday, put that back where you found it!", "holding", "action:put back"), ("Lumi buddy, any chance you could pick up the apple?", "idle", "action:pick apple"), + # 2026-10-27: taught poses by name (look = fold) + ("Let's take look position.", "idle", "action:arm fold"), ("Let's put your hand look position.", "idle", "action:arm fold"), + ("let's bring your hand look position", "idle", "action:arm fold"), ("let's come your hand look position", "idle", "action:arm fold"), + ("look position", "idle", "action:arm fold"), ("go to look", "idle", "action:arm fold"), ("hand to look", "idle", "action:arm fold"), + ("bring your hand to look position", "idle", "action:arm fold"), ("carry position", "idle", "action:arm carry"), + ("put your arm in carry position", "idle", "action:arm carry"), ("carry", "idle", "action:arm carry"), + ("arm to carry", "idle", "action:arm carry"), ("ready position", "idle", "action:arm ready"), + ("carry position", "holding", "action:arm carry"), ("룩 포지션", "idle", "action:arm fold"), ("룩 자세로", "idle", "action:arm fold"), + ("팔 룩으로", "idle", "action:arm fold"), ("캐리 자세", "idle", "action:arm carry"), ("팔 캐리로 해 줘", "idle", "action:arm carry"), + ("팔 원위치", "idle", "action:arm fold"), ("팔 내려", "idle", "action:arm fold"), + ("what is the look position?", "idle", None), ("can you carry this?", "idle", None), ("I like your look position", "idle", None), + ("캐리 자세가 뭐야?", "idle", None), ("룩 자세로 가지 마", "idle", None), ("don't go to carry position", "idle", None), + ("put your arm in tuck position", "idle", None), ("get ready", "idle", None), ("are you ready?", "idle", None), + ("what does carry position mean?", "idle", None), ("look at my hand", "idle", None), ] MOVES = ("action:", "give", "place", "receive", "mission", "chain") diff --git a/tests/test_barge_stop.py b/tests/test_barge_stop.py new file mode 100644 index 0000000..73e92c7 --- /dev/null +++ b/tests/test_barge_stop.py @@ -0,0 +1,95 @@ +"""Self-check of a stop word said while Lumi talks or sings (live 2026-10-27 19:21, logs/lumi_console.log): Lumi's own +voice in the clip mic kept the utterance going, so "Stop. Stop. Stop." was heard only when the 17.9 s answer ended. +A fake clip-mic stream goes through the real audio/mic.py detector and assistant/lumi.py barge_in() / song_abort(); +whisper is faked (it hears "Stop." where the owner's frames are). No audio device, nothing reaches the robot: +python tests/test_barge_stop.py""" +import time + +import numpy as np + +import no_robot # noqa: F401 any connection to the robot fails the test +from assistant import lumi +from audio import ears, mic, mouth +from tasks import follow + +LUMI, OWNER = 2000, 3001 # sample values: Lumi's voice from the speaker, the owner's word +STOP_AT, REACT_S, WHISPER_S = 3.0, 1.5, 0.5 # owner's "stop" s into the answer; allowed; one transcription +acts = [] +follow.running = lambda: False +mouth.own_voice = lambda u: False # the sound match is checked in tests/test_mouth.py +lumi.mouth.recent_speech = lambda s: "" + + +def fake_whisper(owner_said, lumi_said): + def quick(audio): + text = owner_said if (np.abs(audio) == OWNER).any() else lumi_said + ears.last_stt.clear() + ears.last_stt.update(text=text, language="korean" if "그" in text else "english", logprob=-0.1) + return text + ears.quick = quick + + +def fresh(saying): + L = lumi.Lumi.__new__(lumi.Lumi) + L.markers, L.pending_text, L.mic = ["home", "charge", "dock2"], None, mic.Mic() + L.act = lambda a, t: acts.append(a) + L.song_request = ("sing a song", time.time()) + mouth._recent[:] = [(time.time(), saying)] + acts.clear() + return L + + +def stream(L, abort, owner=True, seconds=7.5): + """Quiet, then Lumi talks (loud the whole time, the utterance goes on to mic.MAX_UTTERANCE) with the owner's word at STOP_AT. + Returns s from the word to the abort (whisper's time added), or None when nothing stopped Lumi.""" + m, t0 = L.mic, 1000.0 + frame = np.full(mic.FRAME, LUMI, np.int16) + frame[::2] *= -1 + for i in range(100): # 3 s of room noise: the detector learns the floor + m._clip_frame(np.zeros(mic.FRAME, np.int16) + 50, t0 + i * 0.03) + m.speaking(True) + for i in range(int(seconds / 0.03)): + t = i * 0.03 + x = frame.copy() + if owner and STOP_AT <= t < STOP_AT + 0.4: + x[x > 0], x[x < 0] = OWNER, -OWNER + m._clip_frame(x, t0 + 3.0 + t) + assert m.utterances.empty(), "Lumi's voice must keep the utterance going (the live case)" + if abort(): + return t - STOP_AT + WHISPER_S + return None + + +# the live case: a long answer, "stop" in the middle -> stopped within REACT_S, the stop handled as before +fake_whisper("Stop. Stop.", "I know home, charge, dock2.") +L = fresh("I don't have a place called that on this map. I know: home, charge, dock2.") +took = stream(L, L.barge_in) +assert took is not None and 0 < took <= REACT_S, took +assert acts == ["stop"] and L.pending_text == "Stop. Stop.", (acts, L.pending_text) + +# Lumi's own answer says "stop" and the clip mic hears it: no stop +fake_whisper("", "Stop.") +L = fresh("Press the red button to stop.") +assert stream(L, L.barge_in, owner=False) is None and not acts, acts + +# ... but the owner's "stop" during that answer, heard with other words, still stops +fake_whisper("Lumi, stop now.", "Stop.") +L = fresh("Press the red button to stop.") +assert stream(L, L.barge_in) is not None and acts == ["stop"], acts + +# Lumi's own words without a stop word: nothing +fake_whisper("", "I know home, charge, dock2.") +L = fresh("I know home, charge, dock2.") +assert stream(L, L.barge_in, owner=False) is None and not acts, acts + +# a song, "그만" -> the song ends at once (no act: song_abort only ends the song, as before) +fake_whisper("그만.", "La la la, the sun is up.") +L = fresh("La la la, the sun is up.") +took = stream(L, L.song_abort) +assert took is not None and 0 < took <= REACT_S and not acts, (took, acts) + +# a song, only the music: goes on +L = fresh("La la la, the sun is up.") +assert stream(L, L.song_abort, owner=False) is None + +print("barge stop ok") diff --git a/tests/test_battery.py b/tests/test_battery.py index 654c4a7..580dd3c 100644 --- a/tests/test_battery.py +++ b/tests/test_battery.py @@ -1,5 +1,6 @@ """Self-check: battery questions answered from the base's live status (assistant/battery.py), EN + KO; how long it lasts is left to the LLM (10 hours), how long charging takes is not known. Fake base: python tests/test_battery.py""" +import no_robot # noqa: F401 any connection to the robot fails the test from assistant import battery NOW = ["And charging?", "charging?", "battery?", "Battery", "what's your battery level?", "How much battery do you have?", diff --git a/tests/test_chain.py b/tests/test_chain.py index 93d02ef..f86e9c1 100644 --- a/tests/test_chain.py +++ b/tests/test_chain.py @@ -4,6 +4,7 @@ import re import threading import types +import no_robot # noqa: F401 any connection to the robot fails the test from assistant import chain, lumi from tasks import fetch diff --git a/tests/test_come_back.py b/tests/test_come_back.py index a047bcc..3482b18 100644 --- a/tests/test_come_back.py +++ b/tests/test_come_back.py @@ -3,6 +3,7 @@ python tests/test_come_back.py""" import tempfile from pathlib import Path +import no_robot # noqa: F401 any connection to the robot fails the test from assistant import brain from assistant import lumi from assistant import steps diff --git a/tests/test_command_box.py b/tests/test_command_box.py index 4bb5151..dee6828 100644 --- a/tests/test_command_box.py +++ b/tests/test_command_box.py @@ -8,6 +8,7 @@ import types re._MAXCACHE = 100000 # the readers use more patterns than re's cache holds: 3x faster +import no_robot # noqa: F401 any connection to the robot fails the test from assistant import brain, lumi from tasks import fetch diff --git a/tests/test_detour.py b/tests/test_detour.py index cd4ca9b..b859268 100644 --- a/tests/test_detour.py +++ b/tests/test_detour.py @@ -7,6 +7,7 @@ import tempfile import time from pathlib import Path +import no_robot # noqa: F401 any connection to the robot fails the test from assistant import brain, detour, lumi from tasks import fetch from tests.detour_cases import CASES, GOAL, M, PREFIX_EN, PREFIX_KO diff --git a/tests/test_doa_clip.py b/tests/test_doa_clip.py new file mode 100644 index 0000000..8ad997c --- /dev/null +++ b/tests/test_doa_clip.py @@ -0,0 +1,104 @@ +"""Self-check of the sound direction with the clip mic as reference (audio/doa.py): a voice from one side plus a +louder noise from another, made for the six-mic ring of the calibration geometry. With the clip audio (the voice, +reaching the robot later over the radio) the direction is the voice's; audio without that voice gives the plain estimate; +head-array utterances (no reference) are estimated as before. No hardware: python tests/test_doa_clip.py""" +import numpy as np + +import no_robot # noqa: F401 any connection to the robot fails the test +from audio import doa + +CAL = {"radius": 0.045, "offset": 30.0, "sign": -1} +RATE = doa.RATE +rng = np.random.default_rng(1) + + +def voice(seconds): + """Speech-like: harmonics of a gliding pitch, in syllables (4 per second) with pauses.""" + t = np.arange(int(seconds * RATE)) / RATE + f0 = 140 + 30 * np.sin(2 * np.pi * 0.7 * t) + phase = 2 * np.pi * np.cumsum(f0) / RATE + x = sum(np.sin(k * phase) / k for k in range(1, 20)) + return x * np.clip(np.sin(2 * np.pi * 2 * t), 0, None) ** 2 + + +def at_ring(x, deg): + """The six mics' signals of a far source at deg (head frame), by fractional delays in the spectrum.""" + th, phi = np.radians(deg), np.radians(CAL["offset"] + CAL["sign"] * 60.0 * np.arange(6)) + tau = -CAL["radius"] * np.cos(th - phi) / doa.SOUND + f = np.fft.rfftfreq(len(x), 1 / RATE) + X = np.fft.rfft(x) + return np.stack([np.fft.irfft(X * np.exp(-2j * np.pi * f * d), len(x)) for d in tau], 1) + + +def rms(x): + return float(np.sqrt(np.mean(x ** 2))) + + +def scene(voice_deg, noise_deg, noise_over_voice, seconds=2.5): + v = voice(seconds) + n = rng.standard_normal(len(v)) + n *= noise_over_voice * rms(v) / rms(n) + mics = at_ring(v, voice_deg) + at_ring(n, noise_deg) + 0.02 * rms(v) * rng.standard_normal((len(v), 6)) + return (mics * 3000 / rms(mics)).astype(np.int16), v + + +def clip_of(v, delay_ms): + """What the clip mic gives: the voice, close and clean, delayed by the radio (array sample k = clip k - delay).""" + c = np.roll(v, int(delay_ms * RATE / 1000)) + 0.01 * rms(v) * rng.standard_normal(len(v)) + return (c * 3000 / rms(c)).astype(np.int16) + + +def off(a, b): + return abs((a - b + 180) % 360 - 180) + + +fails = [] +for voice_deg, noise_deg in [(-60, 170), (-30, 180), (-90, 150), (45, -120), (0, 120)]: + mics, v = scene(voice_deg, noise_deg, 2.0) # the noise twice as loud as the voice at the head + for delay_ms in (0, 40, -25): + ang, conf, _ = doa.estimate(mics, CAL, clip_of(v, delay_ms)) + print(f"voice {voice_deg:+4d}, noise {noise_deg:+4d}, clip delay {delay_ms:+3d} ms: " + f"{ang:+5.0f} deg (confidence {conf:.2f})") + if off(ang, voice_deg) > 10 or conf < 0.12: + fails.append((voice_deg, noise_deg, delay_ms, ang, conf)) + ang, conf, _ = doa.estimate(mics, CAL) + print(f" without the clip: {ang:+5.0f} deg (confidence {conf:.2f})") + assert off(ang, voice_deg) > 30, "the scene must be hard without the clip (else the test proves nothing)" +assert not fails, fails + +# the clip wearer's voice is not found in the array audio: the plain estimate, as without the clip +mics, _ = scene(-60, 170, 0.5) +other = clip_of(voice(2.5)[::-1].copy(), 0) +assert doa.clip_lag(mics, other)[1] < doa.CLIP_MIN_SCORE +assert doa.estimate(mics, CAL, other) == doa.estimate(mics, CAL) +assert "clip not found" in doa.clip_note(mics, other) +mics, v = scene(-60, 170, 2.0) +assert "clip score" in doa.clip_note(mics, clip_of(v, 40)) +assert doa.clip_note(mics, None) == "" +print(f"clip voice not in the array: plain estimate {doa.estimate(mics, CAL, other)[0]:+.0f} deg") + +# head-array utterances: no reference, the voice alone is found as before +mics, _ = scene(-60, 170, 0.1) +ang, conf, _ = doa.estimate(mics, CAL) +assert off(ang, -60) <= 10 and conf > 0.12, (ang, conf) +assert doa.clip_ref(type("U", (), {"source": "head", "mono": "x"})) is None +doa.USE_CLIP_REF = True +assert doa.clip_ref(type("U", (), {"source": "clip", "mono": "x"})) == "x" + +# calibration samples (add_sample) in a temporary folder: with the clip the wearer's voice is learnt under louder room +# noise; a clip voice not in the array is no sample; a refit worse than the saved calibration does not replace it +import json, pathlib, tempfile +tmp = pathlib.Path(tempfile.mkdtemp()) +doa.CALIB, doa.SAMPLES = tmp / "calib.json", tmp / "samples.npz" +mics, _ = scene(-60, 170, 0.5) +assert doa.add_sample(mics, -60, other) is None and not doa.SAMPLES.exists() +c = None +for deg in (-40, -20, 0, 20, 40, 10): + mics, v = scene(deg, 170, 2.0) + c = doa.add_sample(mics, deg, clip_of(v, 40)) +assert c and (c["sign"], c["offset"]) == (CAL["sign"], CAL["offset"]) and c["median_error_deg"] <= 4, c +doa.CALIB.write_text(json.dumps({**c, "median_error_deg": -1.0})) # a saved fit no new one can beat +mics, _ = scene(30, 170, 2.0) +assert doa.add_sample(mics, 30) is None and json.loads(doa.CALIB.read_text())["median_error_deg"] == -1.0 +assert len(np.load(doa.SAMPLES)["t"]) == 7 # the sample itself is kept +print("ok") diff --git a/tests/test_drive_log.py b/tests/test_drive_log.py index 1d29a08..36a7b9c 100644 --- a/tests/test_drive_log.py +++ b/tests/test_drive_log.py @@ -1,4 +1,5 @@ """Self-check of robot/drive_log.py with made-up base status reads, no robot: python tests/test_drive_log.py""" +import no_robot # noqa: F401 any connection to the robot fails the test from robot import drive_log MARKERS = {"p10": (3.0, 0.0)} diff --git a/tests/test_driving.py b/tests/test_driving.py index 0dd658b..6364f56 100644 --- a/tests/test_driving.py +++ b/tests/test_driving.py @@ -5,10 +5,12 @@ import threading import time from pathlib import Path +import no_robot # noqa: F401 any connection to the robot fails the test from assistant import brain, driving from manipulation import skills from tasks import fetch +fetch.head_ahead = lambda: None # never the real head M = ["home", "p9"] read = lambda text, last=None, talking=False: driving.read(brain._norm(text), last, talking) diff --git a/tests/test_ears.py b/tests/test_ears.py index 3a06313..127f2ca 100644 --- a/tests/test_ears.py +++ b/tests/test_ears.py @@ -4,6 +4,7 @@ """ import numpy as np +import no_robot # noqa: F401 any connection to the robot fails the test from audio import ears ears.ensure_stt_server = lambda: None diff --git a/tests/test_fetch.py b/tests/test_fetch.py index ac72c0d..75254f0 100644 --- a/tests/test_fetch.py +++ b/tests/test_fetch.py @@ -8,6 +8,7 @@ from pathlib import Path import numpy as np +import no_robot # noqa: F401 any connection to the robot fails the test from robot import head assert head.LIFT_MAX_MM == 0.0 # live: the lift stays at the bottom (head camera cable); the cases below are the long cable's head.LIFT_MAX_MM, head.AXIS_LIMITS = 105.0, ((0.0, 105.0),) + head.AXIS_LIMITS[1:] @@ -610,8 +611,8 @@ assert fetch.turn_hits(90) is None real_points, real_extr = skills.surface_points, skills.objects.base_from_camera skills.objects.base_from_camera = lambda: np.eye(4) skills.surface_points = lambda pts, guess_z=-400.0, **kw: [tuple(p) for p in pts] # depth right at each point -calls.clear() -assert fetch._turn(30) is False and not any(c[0] == "go_point" for c in calls) +calls.clear() # 40 deg: the toy hand (0.23 m out) sweeps past SELF_MM of itself +assert fetch._turn(40) is False and not any(c[0] == "go_point" for c in calls) skills.surface_points = lambda pts, guess_z=-400.0, **kw: [tuple(np.array(p) * 3) for p in pts] # only far behind them assert fetch.depth_hits(30) is None # only the head camera, turned to the side of the turn, sees something in the arm's way: no turn; the head stays there @@ -630,8 +631,8 @@ fetch.head.moveto = head_move fetch.head_cam.base_from_head = lambda yaw, pitch: np.eye(4) skills.surface_points = lambda pts, guess_z=-400.0, camera="torso", T=None: \ [tuple(p) if camera == "head" else None for p in pts] -calls.clear() -assert fetch._turn(-30) is False and not any(c[0] == "go_point" for c in calls) +calls.clear() # 40 deg, as above: past SELF_MM of the toy hand +assert fetch._turn(-40) is False and not any(c[0] == "go_point" for c in calls) assert heads == [(-fetch.HEAD_SIDE_DEG, fetch.HEAD_LOW_PITCH)], heads # no move back: the next look turns it skills.surface_points = lambda pts, guess_z=-400.0, **kw: [None] * len(pts) @@ -974,7 +975,7 @@ scene["person_in_front"] = {"position_mm": ahead(900.0), "hands": {"left": {"pos "distance_m": 1.1}, "right": {"position_mm": ahead(400.0), "distance_m": 0.9}}} turns = [] real_waist_to = fetch._waist_to -fetch._waist_to = lambda deg: turns.append(deg) or deg < 90 +fetch._waist_to = lambda deg, in_place=False, look=None: turns.append(deg) or in_place and deg < 90 # in place def reached(angle=0.0): @@ -998,8 +999,10 @@ assert st["status"] == "done" and poses()[-1] == "give" and not moves, (st, move scene["person_in_front"] = None # nobody seen: the hand at give st, moves = reached() assert st["status"] == "done" and poses()[-1] == "give" and not moves, (st, moves) -st, moves = reached(40.0) # to the side (Patrol): the waist turns first, by the +fetch.stay_put = True # Greeter only: the waist still turns (the base stays) +st, moves = reached(40.0) # to the side: the waist turns first, by the assert turns == [40.0 + fetch._waist_turn()] and poses()[-1] == "give", (turns, poses()) # waist's offset too +fetch.stay_put = False turns.clear() said.clear() st, moves = reached(120.0) # the waist turn refused (sweep): the arm stays @@ -1008,6 +1011,30 @@ turns.clear() st, moves = reached(160.0) # past the waist's limit (-15 + 160 > 140): stand in front assert st["status"] == "failed" and not turns and not poses() and said[-1] == fetch.TURN_TO_PERSON[0], (st, turns) fetch._waist_to = real_waist_to +# the head on the person through the whole reach (live: the waist turned with the head kept at +46 on it, so the +# head looked 90 deg left, away, until head_ahead at the end): Greeter only, person at -40 deg (waist frame), the +# head on them; the sweep check turns the head to that side (head_hits); every head command looks their way, the +# last one right at them (head yaw = -40 - the waist's turn), and nothing turns it ahead after +real_status, real_move, real_blocked = fetch.head.status, fetch.head.moveto, fetch._sweep_blocked +hp = {"waist": -15.0, "yaw": -40.0, "pitch": 10.0} +gaze = [] # waist-frame (as before the turn) angle of each command +fetch.head.status = lambda: [75.0, hp["waist"], hp["yaw"], hp["pitch"]] +def head_cmd(pos, **kw): + hp.update(waist=pos[1], yaw=pos[2], pitch=pos[3]) + gaze.append(pos[1] + 15.0 + pos[2]) +fetch.head.moveto = head_cmd +fetch._sweep_blocked = lambda deg, what: head_cmd([75.0, hp["waist"], math.copysign(fetch.HEAD_SIDE_DEG, deg), + fetch.HEAD_LOW_PITCH]) and False +fetch.stay_put = True +st, moves = reached(-40.0) +assert st["status"] == "done" and poses()[-1] == "give", st +assert hp["waist"] == -55.0 and hp["yaw"] == 0.0 and hp["pitch"] == 10.0, hp +assert gaze[-1] == -40.0 and all(g < 0 for g in gaze), gaze +gaze.clear() +st, moves = reached(0.0) # in front: no waist turn, the head left on them +assert st["status"] == "done" and not gaze and hp["yaw"] == 0.0, gaze +fetch.stay_put = False +fetch.head.status, fetch.head.moveto, fetch._sweep_blocked = real_status, real_move, real_blocked fetch._line_rows, fetch._scene = real_line_rows, real_scene hand["front"] = False # the cup is in the hand but nobody says okay: the hand never closes (their fingers may be in it) @@ -1275,4 +1302,63 @@ fetch._set(holding=False, status="idle") skills._held.clear() fetch._scene, skills.on_table = real_scene, real_on_table +# ---------- the voice pick (pick_here): trusted turns only; here, the waist in place, the base with Patrol, or ask ---- +real = {k: getattr(fetch, k) for k in ("_waist_to", "waist_for", "turned", "_approach", "pick_goal", "at_edge", + "_see_again")} +yaws = [] +def trusted_x(obj, start=None, accept=None, max_yaw=None): # reached only from x > 0 (after the waist turn) + yaws.append(max_yaw) + return (skills.plan_pick(obj), [0.0] * 6) if obj["x"] > 0 or reach["ok"] else None +skills.reachable_pick = trusted_x +fetch._waist_to = lambda rel, in_place=False: calls.append(("waist", in_place)) or in_place or not fetch.stay_put +fetch.waist_for = lambda obj: [40.0] +fetch.turned = lambda obj, deg: {**obj, "x": obj["x"] + 300.0} +fetch._approach = lambda obj, yaw, tried, **kw: calls.append(("approach",)) or False # as near as the base brings it +fetch.pick_goal = lambda obj: fetch.PICK_ZONE_CENTRE +fetch.at_edge = lambda obj: False +fetch._see_again = lambda task, mem, yaw, say: dict(CUP) +fetch.CALIB_FILE.write_text(json.dumps({"arm_yaw_in_base_deg": -86.2})) +base_moves = lambda: [c for c in calls if c[0] in ("approach", "go", "go_point", "joy")] +for patrol in (False, True): + fetch.stay_put = not patrol + reset() + fetch.CALIB_FILE.write_text(json.dumps({"arm_yaw_in_base_deg": -86.2})) + calls.clear(), yaws.clear() + skills.look = lambda frames=None, **kw: [] + assert fetch.pick_here("apple", "red", say)["x"] == CUP["x"] # in reach from here: nothing turns + assert ("pick", "apple") in calls and not [c for c in calls if c[0] == "waist"] and not base_moves(), calls + reach["ok"] = False # only after a waist turn + calls.clear(), yaws.clear() + skills.look = lambda frames=None, **kw: [fetch.turned(dict(CUP), 40.0)] if ("waist", True) in calls else [] + assert fetch.pick_here("apple", "red", say)["x"] > 0 + assert ("waist", True) in calls and ("pick", "apple") in calls and not base_moves(), calls + assert None not in yaws, yaws # never an untrusted grasp turn +fetch.waist_for = lambda obj: [] # no waist turn reaches it either +skills.look = lambda frames=None, **kw: [] +for patrol in (True, False): + fetch.stay_put = not patrol + calls.clear(), yaws.clear(), said.clear() + try: + fetch.pick_here("apple", "red", say) + raise AssertionError("picked out of reach") + except fetch.FetchError as e: + assert e.args[0] == "I still can't reach it.", e.args + assert bool(base_moves()) == patrol, (patrol, calls) # Patrol on: the base came closer first + assert said[-1] == "I can't reach it, please move it closer to me." and None not in yaws, (said, yaws) + assert not [c for c in calls if c[0] in ("pick", "line", "waist") or c[0] == "pose" and not patrol], calls + # the arm never moved (to look only before a base move) +fetch.stay_put = False +for k, v in real.items(): + setattr(fetch, k, v) +skills.reachable_pick = fake_reachable +reset() + print("fetch ok") + +# ---------- STOP after a restart mid-task: the file of a run that is gone says "running", STOP ends it ---------- +fetch._state["status"], fetch._thread = "idle", None +fetch.STATE_FILE.write_text(json.dumps({"status": "running", "step": "picking", "holding": False, "log": ["13:07:50 picking"]})) +fetch.skills.cancel = fetch.agv.cancel = lambda: None +fetch.stop() +assert fetch.state()["status"] == "stopped" and fetch.state()["log"][-1].endswith("stopped"), fetch.state() +print("stale run stopped ok") diff --git a/tests/test_fetch_carry.py b/tests/test_fetch_carry.py index 0f607de..8b04f7e 100644 --- a/tests/test_fetch_carry.py +++ b/tests/test_fetch_carry.py @@ -5,6 +5,7 @@ import sys from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +import no_robot # noqa: F401 any connection to the robot fails the test from tests import pick_sweep as ps ps.install() diff --git a/tests/test_fetch_intents.py b/tests/test_fetch_intents.py index a865512..655aa6c 100644 --- a/tests/test_fetch_intents.py +++ b/tests/test_fetch_intents.py @@ -1,6 +1,7 @@ """Self-check of the voice side of fetch tasks (docs/16 §4), no robot, no audio: python tests/test_fetch_intents.py""" import time +import no_robot # noqa: F401 any connection to the robot fails the test from assistant import brain, fetch_dialog M = ["p1", "p2", "p3", "home", "final"] diff --git a/tests/test_fetch_place.py b/tests/test_fetch_place.py index 74a58e0..1b6c013 100644 --- a/tests/test_fetch_place.py +++ b/tests/test_fetch_place.py @@ -4,6 +4,7 @@ import math import tempfile from pathlib import Path +import no_robot # noqa: F401 any connection to the robot fails the test from assistant import brain from manipulation import skills from tasks import fetch @@ -12,6 +13,7 @@ from vision import objects tmp = Path(tempfile.mkdtemp()) fetch.STATE_FILE = tmp / "lumi_task.json" # never the real /dev/shm file fetch.CALIB_FILE = tmp / "fetch_calib.json" +fetch._charging = lambda: True # on the charger: no backing off to look (never the base) skills.arm.cmd = lambda *a, **kw: (_ for _ in ()).throw(AssertionError(f"real arm command in a test: {a}")) fetch.head.moveto = lambda *a, **kw: (_ for _ in ()).throw(AssertionError("real lift move in a test")) diff --git a/tests/test_fetch_wait.py b/tests/test_fetch_wait.py index 45aac24..9d3b70f 100644 --- a/tests/test_fetch_wait.py +++ b/tests/test_fetch_wait.py @@ -5,6 +5,7 @@ import threading import time from pathlib import Path +import no_robot # noqa: F401 any connection to the robot fails the test from manipulation import skills from tasks import fetch diff --git a/tests/test_fetch_ways.py b/tests/test_fetch_ways.py index 0f9c357..b9ab95d 100644 --- a/tests/test_fetch_ways.py +++ b/tests/test_fetch_ways.py @@ -13,6 +13,7 @@ from pathlib import Path import numpy as np +import no_robot # noqa: F401 any connection to the robot fails the test from manipulation import skills from tasks import fetch from vision import head_cam diff --git a/tests/test_fetch_words.py b/tests/test_fetch_words.py index ee1f838..007b833 100644 --- a/tests/test_fetch_words.py +++ b/tests/test_fetch_words.py @@ -4,6 +4,7 @@ 2. steps.rules: cup tasks of several parts (fetch then more, deliver and come back, put it at a place, wait until someone takes it, Korean calls / endings of every level, Korean written without spaces). Notation of tests/test_steps.py.""" +import no_robot # noqa: F401 any connection to the robot fails the test from assistant import brain, steps diff --git a/tests/test_focus.py b/tests/test_focus.py new file mode 100644 index 0000000..fdbe91d --- /dev/null +++ b/tests/test_focus.py @@ -0,0 +1,180 @@ +"""Self-check of the focus on one person (live 2026-10-27 19:22-19:28): once someone calls, gives an order or says +"look at me", the head stays on them as they move; a newcomer (even waving) is not greeted or looked at; someone else +takes over only with a call, a stop word or an order said from their direction. Fake vision, head, base and mic; +nothing reaches the robot: python tests/test_focus.py""" +import threading +import time +import types + +import no_robot # noqa: F401 any connection to the robot fails the test +from assistant import lumi + +M = ["home", "dock2"] + [f"p{i}" for i in range(1, 11)] +S = lumi.HEAD_SIGN +moves, said, base = [], [], {"move_status": "idle"} +lumi.head.status = lambda: [0.0, 0.0, 0.0, 20.0] +lumi.head.turn = lambda yaw, pitch=None, **k: moves.append(round(yaw)) +lumi.mouth.say = lambda text, **k: said.append(text) +lumi.LOOK_ME_SETTLE_S = 0.0 +up = [] # bearings of raised hands the fake pose net sees +lumi.hands_up = lambda frames: list(up) +import vision.scene as scene # noqa: E402 +scene.snapshot = lambda cams: [] + + +class Track: + def __init__(self, id, angle, distance=1.2): + self.id, self.angle, self.distance, self.greeted, self.person = id, angle, distance, False, None + + +class Vision: + camera, pinned = "head", True + + def __init__(self, *tracks): + self.tracks = list(tracks) + self.det = types.SimpleNamespace(focus_angle=None) + + def near_angle(self, a, d=lumi.SPEAKER_MATCH_DEG): + return min((t for t in self.tracks if abs(t.angle - a) <= d), key=lambda t: abs(t.angle - a), default=None) + + def present(self, t): + return t in self.tracks + + def to_greet(self): + return next((t for t in self.tracks if not t.greeted), None) + + def only_person(self): + return self.tracks[0] if len(self.tracks) == 1 else None + + def nearest_greeted(self): + return next((t for t in self.tracks if t.greeted), None) + + def seen(self): + return [(t.angle, t.distance) for t in self.tracks] + + def head_person(self, angle, since): + return None + + def know(self, t): + return types.SimpleNamespace(talking=False), None + + +def fresh(*tracks): + L = lumi.Lumi.__new__(lumi.Lumi) + L.markers, L.lang, L.current, L.pending_text, L.patrol = M, "en", None, None, None + L.vision, L.mic = Vision(*tracks), types.SimpleNamespace(next=lambda timeout: None) + L.modes = types.SimpleNamespace(greeter=True, patrol=True, drive=True, refresh=lambda: None) + L.voice_until = L.quiet_until = L.calib_until = 0.0 + L.last_activity, L.closing_pending, L._yaw, L._yaw_time = time.time(), None, 0.0, time.time() + 1e6 + L.skill_thread, L.prompts, L.wave_checked = None, 0, 0.0 + L.poll_commands = L.say_stuck = lambda: None + L.reach_done = lambda: False + L.publish_busy = lambda what: None + L.talk_turn = lambda: False + L.brain = types.SimpleNamespace(reset=lambda: None, history=[]) + moves.clear(), said.clear(), up.clear() + return L + + +def settle(): + time.sleep(0.2) # turn_head moves the head in a thread + + +# ---- talking with #1 (right), #2 walks in on the left and waves: no greeting, the head stays on #1 as they move ---- +L = fresh(a := Track(1, 30.0)) +a.greeted, L.current = True, a +L.vision.tracks.append(b := Track(2, -40.0)) +up.append(-40.0) +for _ in range(3): + L.step() + L.wave_checked = 0.0 +assert lumi.GREETING not in said and L.current is a and not b.greeted, said +a.angle = 45.0 +L.focus_step() +settle() +assert moves == [S * 45], moves # the head follows #1, never #2 +moves.clear() +L._yaw = S * 45 +L.focus_step() # still on them: no move +settle() +assert moves == [], moves + +# ---- the voice near #2: plain words keep the focus on #1; "stop", "Lumi" or an order hand it to #2 ---- +lumi.doa.load_calib = lambda: {"fitted": True} +lumi.doa.clip_ref = lambda u: None +lumi.doa.estimate = lambda mics, cal, ref=None: (-40.0, 0.9, 0.0) +lumi.waist_turned = lambda: 0.0 +from tasks import fetch as _fetch # noqa: E402 +_fetch._waist_to = lambda rel, in_place=False, look=None: True # "look at me" past the head turns the waist +lumi.waist_home = lambda why: True +lumi.agv.turn_by = lambda rad: None # "look at me" past the head with Patrol turns the base +lumi.agv.status = lambda: {"move_status": "succeeded"} +U = types.SimpleNamespace(mics=None, seconds=1.0, source="clip") +for text, takes in (("The weather is nice today.", False), ("Stop.", True), ("Lumi, over here.", True), + ("Go to p3.", True), ("I like your colour.", False)): + L = fresh(a := Track(1, 30.0), b := Track(2, -40.0)) + a.greeted, L.current = True, a + L.who_spoke(U, text) + settle() + assert (L.current is b) == takes and (moves == [S * -40] if takes else moves == []), (text, L.current.id, moves) + +# ---- "look at me" (19:24:16): focus on the person found; a newcomer does not take the head; the head follows the +# looked-at person over the held look, also when their track gets a new id (#5 -> #7) ---- +L = fresh(a := Track(5, -19.0, 1.15)) +L.voice_angle, L.voice_trusted = -62.0, True +L.looked_at = time.time() # act("look", "me") holds the look +L.look_at_speaker() +assert L.current is a and L.look_me is a and a.greeted, (L.current, getattr(L, "look_me", None)) +L.vision.tracks.append(b := Track(6, 40.0)) +up.append(40.0) +moves.clear() +for _ in range(3): + L.step() + L.wave_checked = 0.0 +assert lumi.GREETING not in said and L.current is a, said +L._yaw = S * -19 +a.angle = -35.0 # they step aside +L.focus_step() +settle() +assert L.look_held() and moves == [S * -35], moves # over the held look: it was them +L.vision.tracks.remove(a) +L.vision.tracks.append(a2 := Track(7, -33.0, 1.15)) +L.step() +assert L.current is a2 and L.look_me is a2, L.current.id +# a "look left" hold is not a person: the head stays where asked +L.look_me, L._yaw = None, S * 60 +moves.clear() +L.focus_step() +settle() +assert moves == [], moves + +# ---- "come here" with the look held: the head stays on the caller while the base drives ---- +lumi.agv.cancel = lambda: None +lumi.agv.status = lambda: dict(base) +lumi.agv.pose = lambda: (0.0, 0.0, 0.0) +lumi.agv.go_point = lambda *a: (True, "") +lumi.agv.turn_by = lambda a: (_ for _ in ()).throw(AssertionError("the base turned away from the caller")) +lumi.nav.person_on_map = lambda *a: (3.0, 0.0) +lumi.nav.approach = lambda *a: (2.0, 0.0, 0.0) +lumi.waist_home = lambda why: True +L = fresh(a := Track(5, -19.0, 2.5), Track(8, 30.0, 2.4)) +L.current, L.look_me, L.looked_at = a, a, time.time() +L.voice_angle, L.voice_trusted = -107.0, True # the voice read far off (19:24:22): the focus wins +base["move_status"] = "running" +threading.Timer(1.5, lambda: base.update(move_status="succeeded")).start() +L.come_to(L.current, say=True) +settle() +assert moves and set(moves) == {S * -19}, moves + +# ---- after turning to the voice: the person nearest its side, not the nearest one far off it ---- +heads = [] +lumi.time.sleep, real_sleep = (lambda s: None), lumi.time.sleep +L = fresh(Track(9, -50.0, 0.8), Track(10, 38.0, 2.5)) +L.vision.near_angle = lambda a, d=lumi.SPEAKER_MATCH_DEG: None +L.vision.seen = lambda: [(-50.0, 0.8), (38.0, 2.5)] +L.det_yaw = lambda: 0.0 +L.turn_head = lambda yaw=None, pitch=None, force=False: heads.append((round(yaw), force)) +L.find_caller(50.0, True) +lumi.time.sleep = real_sleep +assert heads == [(S * 50, True), (S * 38, True)], heads +print("focus ok") diff --git a/tests/test_follow.py b/tests/test_follow.py index cd73759..4b979a4 100644 --- a/tests/test_follow.py +++ b/tests/test_follow.py @@ -10,6 +10,7 @@ from pathlib import Path import numpy as np +import no_robot # noqa: F401 any connection to the robot fails the test from assistant import brain, lumi from robot import agv, head, motion from tasks import fetch, follow @@ -35,6 +36,7 @@ fetch.head_ahead = lambda: None fetch.arm_yaw = lambda: -86.0 ARM = [np.array([0.44, 0.0]), np.array([0.52, 0.0]), np.array([0.60, 0.0])] # flange, grasp point, tips (m) fetch.arm_points = lambda: ARM +fetch._waist_turn = lambda: head.status()[1] # the waist's front reads 0 class Body: @@ -120,6 +122,7 @@ class World: return None d, a = self.sight(self.person_at()) self.dist.append(d) + a -= body.pos[1] # lumi.Vision gives waist-frame angles if self.fov and abs(a - body.pos[2]) > HALF_FOV: return None return d, a, 0.0, self.look @@ -280,12 +283,12 @@ print("arm off: follows, powered off refuses") # any other failure in prepare: said, the base at 0, the head free again, the thread ends said.clear() -fetch._waist_front = lambda: 1 / 0 +drive_pose, fetch._drive_pose = fetch._drive_pose, (lambda: 1 / 0) w = World() follow.start(w.see, say) assert wait_end(1.0) and said and "went wrong" in said[0] and w.cmds and w.cmds[-1][1:] == (0.0, 0.0), said assert head.owners == () -fetch._waist_front = lambda: None +fetch._drive_pose = drive_pose print("failure in prepare: said, stopped") # the person walks around to behind (radius 2 m, 0 -> 150 deg in 6 s), seen by the head camera only: the head turns @@ -491,13 +494,120 @@ follow.TURN_MAX_RS = turn_max assert follow.running() and not said, said follow.stop() assert wait_end(0.5) -yaws = [m[4] for m in body.moves if m[1] == "follow head"] -assert max(yaws) > 90.0 and all(abs(y) <= 180.0 for y in yaws), yaws # past the side -assert all(abs(b - a) < 90.0 for a, b in zip(yaws, yaws[1:])), yaws # never swung round +moves = [m for m in body.moves if m[1] == "follow head"] +yaws, gaze = [m[4] for m in moves], [m[3] + m[4] for m in moves] +assert max(gaze) > 90.0, gaze # past the side +assert all(abs(b - a) < 90.0 for a, b in zip(gaze, gaze[1:])), gaze # never swung round assert math.degrees(w.th) > 120.0 and w.dist[-1] < follow.FOLLOW_GAP_M + 0.4, (math.degrees(w.th), w.dist[-1]) -print(f"past the side to behind: head up to {max(yaws):.0f} deg, base turned {math.degrees(w.th):.0f} deg, " +print(f"past the side to behind: waist + head up to {max(gaze):.0f} deg, base turned {math.degrees(w.th):.0f} deg, " f"gap {w.dist[-1]:.2f} m") +# owner, live: the head waited for a slow stepwise waist and lost the person. Now head, waist and base all at once: +# the person right behind (170 deg) -> the first move puts head + waist on them (the head not held to HEAD_REL_MAX), +# the waist keeps turning move after move while the base turns, the base forward only once they are ahead +assert follow.waist_for(10.0) == 0.0 and follow.waist_for(-70.0) == -40.0 and follow.waist_for(170.0) == 90.0 + + +def at(deg, r=2.0): + return World(person=(r * math.cos(math.radians(deg)), r * math.sin(math.radians(deg)))) # seen (torso) + + +def person_deg(w): + x, y, th = w.pose() + p = w.person_at() + return (math.degrees(math.atan2(p[1] - y, p[0] - x) - th) + 180.0) % 360.0 - 180.0 + + +def watch(w, secs): + """[(t, waist, head yaw, base deg, gaze off the person deg)] every 20 ms; the angle of every forward command.""" + samples, ahead, request = [], [], w.request + + def req(cmd): + out = request(cmd) + if w.cmds and w.cmds[-1][1] > 0.0: + ahead.append(person_deg(w)) + return out + w.request = agv.request = req + follow.start(w.see, say) + t0 = time.time() + while time.time() < t0 + secs: + _, waist, yaw, _ = body.pos + b = person_deg(w) + samples.append((time.time() - t0, waist, yaw, math.degrees(w.th), (b - waist - yaw + 180.0) % 360.0 - 180.0)) + time.sleep(0.02) + return samples, ahead + + +said.clear() +body.moves.clear() +w = at(170.0) +samples, ahead = watch(w, 8.0) +assert follow.running() and not said, said +follow.stop() +assert wait_end(0.5) +moves = [m for m in body.moves if m[1] == "follow head"] +first = moves[0] +assert 0.0 < first[3] <= follow.WAIST_STEP_DEG and first[4] > 90.0 and abs(first[3] + first[4] - 170.0) < 10.0, first +assert max(abs(s[4]) for s in samples[5:]) < 15.0, max(abs(s[4]) for s in samples[5:]) # gaze on them +turning = [s for s in samples if 10.0 < s[3] < 90.0] # the base turning ... +assert turning and max(s[1] for s in turning) >= 3 * follow.WAIST_STEP_DEG, turning[:3] # ... the waist too +assert w.cmds[0][2] > 0.0 and w.cmds[0][0] - w.t0 < 0.5, w.cmds[:2] # turning at once +assert max(b[0] - a[0] for a, b in zip(w.cmds, w.cmds[1:])) < 0.2 # no tick waits +assert ahead and max(abs(a) for a in ahead) <= follow.TURN_ONLY_DEG + 5.0, max(abs(a) for a in ahead) +assert abs(body.pos[1]) < 1e-6 and abs(body.pos[2]) <= follow.TURN_DEAD_DEG + follow.HEAD_STEP_DEG, body.pos +assert abs(math.degrees(w.th) - 170.0) < 10.0 and w.dist[-1] < follow.FOLLOW_GAP_M + 0.3, (math.degrees(w.th), w.dist[-1]) +print(f"behind 170 deg: first move waist {first[3]:+.0f} head {first[4]:+.0f}, waist up to " + f"{max(s[1] for s in samples):.0f} deg while the base turned, forward only within {max(map(abs, ahead)):.0f} deg") + +# "look behind" turned the waist and the head to the owner, then "follow me": nothing turns away from them +said.clear() +body.moves.clear() +body.pos = [50.0, 120.0, 50.0, follow.HEAD_PITCH] # on them at 170 deg +w = at(170.0) +samples, _ = watch(w, 4.0) +follow.stop() +assert wait_end(0.5) and not said, said +assert max(abs(s[4]) for s in samples) < 15.0, max(samples, key=lambda s: abs(s[4])) # from the very start +moves = [m for m in body.moves if m[1] == "follow head"] +assert all(abs(m[3] + m[4] - 170.0) < 60.0 for m in moves[:3]), moves[:3] +print(f"start turned to the owner: gaze off at most {max(abs(s[4]) for s in samples):.0f} deg") + +# stopped with the waist turned: it comes back to the front (sweep checked), the head to rest +body.moves.clear() +w = at(70.0) +follow.TURN_MAX_RS, turn_max = 0.05, follow.TURN_MAX_RS # a slow base +follow.start(w.see, say) +time.sleep(0.6) +assert body.pos[1] > 10.0, body.pos +follow.stop() +assert wait_end(1.0) +follow.TURN_MAX_RS = turn_max +assert body.moves[-1][3:] == (0.0, 0.0, head.HEAD_REST_PITCH), body.moves[-1] +print("stopped turned: waist back to the front") + +# the arm's sweep blocked for the waist, or the arm not in look: the waist stays, the head alone goes on them +turn_hits = fetch.turn_hits +for why in ("sweep", "not look"): + body.moves.clear() + if why == "sweep": + fetch.turn_hits = lambda d: (1.0, 1.0) if threading.current_thread().name == "follow head" else None + else: + calls = iter([True]) # ready() sees it in look, then + fetch._at_pose = lambda name: next(calls, False) # it is moved out (by hand) + w = at(70.0) + follow.TURN_MAX_RS, turn_max = 0.05, follow.TURN_MAX_RS + follow.start(w.see, say) + time.sleep(1.5) + follow.stop() + assert wait_end(1.0) + follow.TURN_MAX_RS = turn_max + moves = [m for m in body.moves if m[1] == "follow head"] + assert all(m[3] == 0.0 for m in moves), moves # the waist stays + yaws = [m[4] for m in moves] + assert max(yaws) > 60.0, yaws # the head alone on them + fetch.turn_hits, fetch._at_pose = turn_hits, (lambda name: True) + print(f"waist {why}: stays at the front, head up to {max(yaws):.0f} deg") + # right behind: the angle flips between +179 and -179; the head and the base keep one side said.clear() body.moves.clear() @@ -518,7 +628,7 @@ assert yaws and all(y > 0 for y in yaws[1:]), yaws print("right behind: one side") # lumi: act("stop") ends following; follow_me locks onto the person talking, refuses when it must -lumi.agv.cancel = lumi.skills.cancel = lumi.arm.stop = lambda: None +lumi.agv.cancel = lumi.skills.cancel = lumi.motion.stop = lambda: None w = World(person=(3.0, 0.0)) follow.start(w.see, say) time.sleep(0.1) diff --git a/tests/test_follow_listen.py b/tests/test_follow_listen.py index 39ce4c1..92a4f3b 100644 --- a/tests/test_follow_listen.py +++ b/tests/test_follow_listen.py @@ -3,15 +3,18 @@ no robot, no audio: python tests/test_follow_listen.py""" import threading import time +import no_robot # noqa: F401 any connection to the robot fails the test from assistant import lumi -from tasks import follow +from tasks import fetch, follow done, heard = [], [] +fetch.stop = lambda: None # the real one cancels the arm and the base, writes the live task file +fetch._waist_turn = lambda: 0.0 # the waist at the front (the real one asks the body API) follow.running = lambda: run["on"] follow.followed_angle = lambda: run["angle"] follow.stop = lambda: done.append("follow stop") lumi.doa.load_calib = lambda: {"fitted": True} -lumi.doa.estimate = lambda mics, cal: (mics, 0.5, None) # the fake mics carry the voice angle (head frame) +lumi.doa.estimate = lambda mics, cal, ref=None: (mics, 0.5, None) # the fake mics carry the voice angle (head frame) lumi.mouth.say = lambda text, **k: done.append(("say", text)) lumi.mouth.recent_speech = lambda s=30.0: "" lumi.ears.understood = lambda *a: True @@ -41,6 +44,12 @@ class Vision: # someone at -60 deg besides the def present(self, t): return True + def seen(self): + return [(self.stranger.angle, 1.0)] + + def head_person(self, angle, since): + return None + def to_greet(self): return None @@ -109,16 +118,27 @@ for by_clip in (True, False): run["on"] = False L = fresh("What time is it?", -70.0) assert L.talk_turn() and heard == ["What time is it?"] and L.current is L.vision.stranger, (heard, L.current) -# "look at me" / "이쪽 봐": the head turns to this turn's voice (a person there, or the voice out of view), never the centre -for deg, want in ((40.0, 50.0), (-70.0, -60.0)): +# "look at me" / "이쪽 봐": the head turns to this turn's voice first; nobody there: to the person seen (-60) +lumi.head.turn = lambda yaw, pitch=None: done.append(("head turn", round(yaw))) +lumi.LOOK_ME_SETTLE_S = 0.0 + + +def looked(L, want): + end = time.time() + 2.0 # act() turns the head in a thread + while [d for d in done if d[0] == "head turn"] != want and time.time() < end: + time.sleep(0.01) + return [d for d in done if d[0] == "head turn"] == want + + +for deg, want in ((40.0, [50, -60]), (-70.0, [-60])): L = fresh("이쪽 봐 줘", deg) L.answer = lambda text: lumi.Lumi.act(L, "look", "me") L.base_off, L.mission_running = (lambda *a, **k: False), (lambda: False) - assert L.talk_turn() and ("head", (want, 10)) in done, (deg, done) -lumi.doa.load_calib = lambda: {"fitted": False} # no sound direction, nobody seen: the head stays + assert L.talk_turn() and looked(L, [("head turn", w) for w in want]), (deg, done) +lumi.doa.load_calib = lambda: {"fitted": False} # no sound direction: the person seen L = fresh("look at me", 10.0) L.answer = lambda text: lumi.Lumi.act(L, "look", "me") L.base_off, L.mission_running = (lambda *a, **k: False), (lambda: False) -assert L.talk_turn() and ("head", (None, 10)) in done, done +assert L.talk_turn() and looked(L, [("head turn", -60)]), done lumi.doa.load_calib = lambda: {"fitted": True} print("follow listen ok") diff --git a/tests/test_followup.py b/tests/test_followup.py index 7077af2..373784c 100644 --- a/tests/test_followup.py +++ b/tests/test_followup.py @@ -10,6 +10,7 @@ import re import sys from pathlib import Path +import no_robot # noqa: F401 any connection to the robot fails the test from assistant import brain, lumi, seeing, web from tests.conversation_check import NOW, rules_route from tests.followup_cases import CASES diff --git a/tests/test_gripper.py b/tests/test_gripper.py index 2040842..430f934 100644 --- a/tests/test_gripper.py +++ b/tests/test_gripper.py @@ -1,4 +1,5 @@ """Self-check of robot/gripper.py's finger gap from AI_1 (no robot): python tests/test_gripper.py""" +import no_robot # noqa: F401 any connection to the robot fails the test from robot import gripper as g assert g.gap_mm(g.AI_OPEN) == 96.0 and g.gap_mm(g.AI_SHUT) == 70.0 # belly, open / closed (tape) diff --git a/tests/test_held_hand.py b/tests/test_held_hand.py index 0d787fa..d40dfbb 100644 --- a/tests/test_held_hand.py +++ b/tests/test_held_hand.py @@ -5,6 +5,7 @@ PUT_BACK), the arm words (reach / fold), and the hard negatives that must not mo """ import itertools +import no_robot # noqa: F401 any connection to the robot fails the test from assistant import brain MARKERS = ["home", "dock2", "p1", "p3", "booth_A", "stage", "Gate_A3"] diff --git a/tests/test_intent_bank.py b/tests/test_intent_bank.py index fc4d3f5..e622d1c 100644 --- a/tests/test_intent_bank.py +++ b/tests/test_intent_bank.py @@ -2,6 +2,7 @@ Needs the embedding server (assistant/knowledge.embed starts it); nothing moves. Guards first, then readings on maps with other marker names (any map, not p1..p10), then words that must never become a motion.""" +import no_robot # noqa: F401 any connection to the robot fails the test from assistant import intent_bank as ib EXPO = ["home", "dock2", "booth_A", "booth_B", "entrance", "stage", "coffee_corner", "info_desk"] diff --git a/tests/test_intents.py b/tests/test_intents.py index d9bec69..2c530ab 100644 --- a/tests/test_intents.py +++ b/tests/test_intents.py @@ -1,9 +1,13 @@ """Self-check of the keyword rules in brain.intent() for arm and object commands, no robot: python tests/test_intents.py""" +import no_robot # noqa: F401 any connection to the robot fails the test from assistant import brain CASES = { "Lumi, pick up the white cup": ("pick", "white cup"), "take the cup please": ("pick", "cup"), + "Can you take the cup?": ("pick", "cup"), "Let's take the cup.": ("pick", "cup"), "Take the cup.": ("pick", "cup"), + "pick up the cup": ("pick", "cup"), "컵 집어 줘": ("pick", "cup"), "컵 잡아": ("pick", "cup"), + "Can you take a photo?": None, "Take care.": None, "Take a look.": None, "Take a cup of coffee.": None, "can you hold the mug": ("pick", "cup"), "pick up the orange": ("pick", "orange"), "pick up the orange cup": ("pick", "orange cup"), @@ -76,6 +80,8 @@ CASES.update({ # any wording of the body commands, English, Korean and mixed ( "reach out your hand": ("arm", "reach"), "stretch out your arm": ("arm", "reach"), "fold your arm": ("arm", "fold"), "put your arm down": ("arm", "fold"), "팔 뻗어": ("arm", "reach"), "팔 접어": ("arm", "fold"), "팔 내려": ("arm", "fold"), "open your hand": ("arm", "open"), "close your hand": ("arm", "close"), "손 펴": ("arm", "open"), "손 쥐어": ("arm", "close"), + "let's take look position": ("arm", "fold"), "put your arm in carry position": ("arm", "carry"), "캐리 자세": ("arm", "carry"), + "룩 자세로": ("arm", "fold"), "what is the look position?": None, "put your arm in tuck position": None, # lift "raise yourself": ("lift", "up"), "lift yourself up": ("lift", "up"), "lower yourself a bit": ("lift", "down small"), "raise yourself 5 cm": ("lift", "up 50"), "get taller": ("lift", "up"), "make yourself shorter": ("lift", "down"), @@ -109,8 +115,19 @@ CASES.update({ # looking behind (2026-10-21 live: "look at the back side" was "look forward": ("look", "center"), "look ahead": ("look", "center"), "turn around and look at me": ("look", "me"), "turn around": ("turn", "around 180"), "뒤로 돌아 봐": ("turn", "around 180"), "back up 1 m": ("move", "back 1"), "what's behind you?": None, "who is behind you?": None, "뒤에 뭐 있어?": None, "뒤에 누가 있어?": None, - "I'll be back": None, "I'm behind you": None, "look back at me": None, "look at the back of the box": None, + "I'll be back": None, "look back at me": None, "look at the back of the box": None, "I'm your backside.": None, "don't look behind": None, + # the speaker says where they stand: the head turns there (live 2026-10-27: "I am your right side." went to the LLM, none) + "I am your left, right side.": ("look", "right"), "I am your right side.": ("look", "right"), + "I am your right side. Look at that.": ("look", "right"), "I'm on your right side": ("look", "right"), + "I'm on your right": ("look", "right"), "I'm here on your left": ("look", "left"), "I'm on your left hand side.": ("look", "left"), + "Lumi, I'm on your right, look at me": ("look", "right"), "I'm behind you": ("look", "left 180"), + "나 오른쪽에 있어": ("look", "right"), "오른쪽에 있어요": ("look", "right"), "나 여기 왼쪽이야": ("look", "left"), + "저 왼쪽에 있어요": ("look", "left"), "뒤에 있어": ("look", "left 180"), + "you are right": None, "right, I see": None, "all right": None, "I'm right here": None, "that's right": None, + "right now": None, "I'm right": None, "I'm on the right track": None, "I'm behind you all the way": None, + "I'm your right hand man": None, "컵 왼쪽에 있어": None, "왼쪽에 있어?": None, "Am I on your right?": None, + "I'm not on your right": None, }) wrong = {text: (brain.intent(text, []), want) for text, want in CASES.items() if brain.intent(text, []) != want} @@ -203,6 +220,9 @@ from assistant import lumi # a venue question on assert lumi.not_online("여기 몇 시까지 해요?") and lumi.not_online("입장료 얼마예요?") and lumi.not_online("what time is the keynote?") assert not lumi.not_online("루브르 몇 시까지 해?") and not lumi.not_online("How much are tickets for the Louvre?") assert not lumi.not_online("롯데월드 입장료 얼마야?") +for text, want in (("I am your right side. Look at that.", "right"), ("Lumi, I'm on your right, look at me", "right"), + ("나 여기 왼쪽이야", "left"), ("I'm behind you", "left 180")): # one look, never the LLM or a chain + assert lumi.route(text, ["p3"], brain.Brain()) == ("quick", ("look", want)), text # the model's motion runs only on a direct order (or "yes" to Lumi's own offer, "do it again"); else talk only for text, line in (("우리 커피 들렀다가 p3 가자", "go_to p3"), ("let's grab coffee then go to p3", "go_to p3"), ("Don't look up.", "look down"), ("흔들지 마", "wave -"), ("고개 돌리지 마세요", "turn left"), diff --git a/tests/test_ko_levels.py b/tests/test_ko_levels.py index b793453..ec6a6d1 100644 --- a/tests/test_ko_levels.py +++ b/tests/test_ko_levels.py @@ -4,6 +4,7 @@ gives no motion. No robot; the embedding server answers the bank. .venv/bin/python tests/test_ko_levels.py """ +import no_robot # noqa: F401 any connection to the robot fails the test from tests import ko_levels_check CAPS = {"wave", "turn45", "head_up", "follow", "fetch", "go_to"} diff --git a/tests/test_korean_numbers.py b/tests/test_korean_numbers.py index 2bb6251..8813c42 100644 --- a/tests/test_korean_numbers.py +++ b/tests/test_korean_numbers.py @@ -3,6 +3,7 @@ wording.norm, the route lumi.answer() takes before the LLM and intent_bank.said_ without a fitting unit is asked. No robot: python tests/test_korean_numbers.py""" import math +import no_robot # noqa: F401 any connection to the robot fails the test from assistant import brain, intent_bank, steps, wording from tests import command_check from tests.korean_numbers_cases import NORM, ROUTE, SAID, STEPS diff --git a/tests/test_look_me.py b/tests/test_look_me.py new file mode 100644 index 0000000..855db73 --- /dev/null +++ b/tests/test_look_me.py @@ -0,0 +1,133 @@ +"""Self-check of "look at me": the person seen nearest the voice (head or torso camera), the voice first when nobody +is seen there, nobody seen -> the head stays. No robot: python tests/test_look_me.py""" +import math + +import no_robot # noqa: F401 any connection to the robot fails the test +from assistant import lumi + +turns, pitches = [], [] +lumi.head.turn = lambda yaw, pitch=None: (turns.append(round(yaw)), pitches.append(pitch)) +lumi.LOOK_ME_SETTLE_S = 0.0 + + +class Vision: + def __init__(self, before, after=None): + self.views = [before, before if after is None else after] + + def seen(self): + return self.views.pop(0) if len(self.views) > 1 else self.views[0] + + def present(self, t): + return False + + def head_person(self, angle, since): + return None + + def near_angle(self, a, max_diff=25.0): + return None + + +def look(seen, voice=None, after=None): + L = lumi.Lumi.__new__(lumi.Lumi) + L.vision, L.current = Vision(seen, after), None + L.voice_angle, L.voice_trusted = (voice or 0.0), voice is not None + turns.clear() + L.look_at_speaker() + return list(turns) + + +# someone on Lumi's right, seen only by the torso camera, no voice direction: the head turns right to them +assert look([(-33.0, 0.78)]) == [-33], turns +# the voice agrees with a person seen: that person, not the nearer one elsewhere +assert look([(-33.0, 1.2), (40.0, 0.6)], voice=-20.0) == [-33], turns +# the voice comes from out of view: the head turns there, then to the person its camera finds +assert look([(40.0, 0.6)], voice=-55.0, after=[(-50.0, 0.9), (40.0, 0.6)]) == [-55, -50], turns +# the voice direction is wrong (left), the only person is on the right: voice first, then the person seen +assert look([(-33.0, 0.78)], voice=50.0) == [50, -33], turns +# nobody seen, no voice: the head does not move (it used to tilt up) +assert look([]) == [], turns + +# "Lumi" with the voice read on the left, nobody there: the head turns there, then to the person seen, else back +heads = [] +lumi.time.sleep = lambda s: None + + +class Head(Vision): + camera = "head" + + def near_angle(self, a, max_diff=25.0): + return None + + +for seen, want in (([(-33.0, 0.8)], [50, -33]), ([], [50, 5])): + L = lumi.Lumi.__new__(lumi.Lumi) + L.vision, L.current = Head(seen), None + L.det_yaw = lambda: 5.0 + L.turn_head = lambda yaw=None, pitch=None, force=False: heads.append(round(yaw)) + heads.clear() + assert L.find_caller(50.0, True) is None and heads == want, heads + +# the pitch follows the person in the head camera (torso camera intrinsics, near the head camera's) +FY, CY, H = 608.4, 363.2, 720 +far = lumi.look_me_pitch +assert far([600, 250, 700, 600], H, 0.0, FY, CY) is None # far, all of them in view: stays level +# sitting, close: head low, legs cut: down 30 deg, cut to the head's range +assert far([600, 400, 800, 720], H, 0.0, FY, CY) == lumi.head.PITCH_RANGE[0] +p = far([600, 400, 800, 720], H, 30.0, FY, CY) +assert -2 < p < 2, p +assert far([500, 0, 900, 720], H, 0.0, FY, CY) == lumi.LOOK_ME_UP_STEP # tall, close: head cut, up a step +assert far([500, 0, 900, 720], H, 35.0, FY, CY) is None # already at the top of the range +assert far([600, 60, 800, 720], H, 5.0, FY, CY) is None # head already near the top + + +class Camera(Vision): + """Head camera frames after each turn: the box top moves by the pitch change (fy px per radian).""" + def __init__(self, top, bottom=720): + super().__init__([(-30.0, 1.0)]) + self.top, self.bottom, self.pitch = top, bottom, 0.0 + + def head_person(self, angle, since): + if pitches: + shift = FY * (math.tan(math.radians(pitches[-1] - self.pitch))) + self.top, self.pitch = self.top + shift, pitches[-1] + return {"box": [500, max(0, self.top), 900, self.bottom], "height": H, "pitch": self.pitch, "fy": FY, "cy": CY} + + +def look_pitch(cam): + L = lumi.Lumi.__new__(lumi.Lumi) + L.vision, L.current, L.voice_angle, L.voice_trusted = cam, None, 0.0, False + turns.clear(), pitches.clear() + L.look_at_speaker() + return [round(p) for p in pitches] + + +assert look_pitch(Camera(250, 600)) == [0], pitches # far: level, no correction +assert look_pitch(Camera(300)) == [0, -5], pitches # sitting close: down, to the lowest pitch +assert look_pitch(Camera(100)) == [0, -3], pitches # standing close, legs cut: head to the top +p = look_pitch(Camera(-150)) # tall close: up until the head shows +assert p[0] == 0 and p[-1] > 10 and len(p) <= 1 + lumi.LOOK_ME_TRIES, p +assert set(turns) == {-30}, turns # the yaw stays on them +print("look me: ok") + +# "look at me" from behind with Patrol off: the waist turns in place toward the voice, the head looks on from there +from tasks import fetch +waist = {"at": 0.0, "calls": []} +lumi.waist_turned = lambda: waist["at"] + + +def fake_waist_to(rel, in_place=False, look=None): + waist["calls"].append((round(rel), in_place, look)) + waist["at"] = rel + return True + + +fetch._waist_to = fake_waist_to +L = lumi.Lumi.__new__(lumi.Lumi) +L.vision, L.current = Vision([]), None +L.voice_angle, L.voice_trusted = 170.0, True +L.modes = type("M", (), {"drive": True, "patrol": False})() +turns.clear() +L.look_at_speaker() +assert waist["calls"] == [(120, True, 170.0)], waist +assert turns == [50], turns # 170 - 120 left for the head +print("look me behind: ok") diff --git a/tests/test_map_info.py b/tests/test_map_info.py index e63a6b3..f21033d 100644 --- a/tests/test_map_info.py +++ b/tests/test_map_info.py @@ -2,6 +2,7 @@ list at once (api/server.py, robot/agv.py), with a fake base, no robot: python tests/test_map_info.py""" import time +import no_robot # noqa: F401 any connection to the robot fails the test from api import server from robot import agv diff --git a/tests/test_map_names.py b/tests/test_map_names.py index 3a66361..15f08f5 100644 --- a/tests/test_map_names.py +++ b/tests/test_map_names.py @@ -3,6 +3,7 @@ assistant's live list), with fake marker lists for the office and a conference m python tests/test_map_names.py""" import types +import no_robot # noqa: F401 any connection to the robot fails the test from assistant import brain, lumi, steps, wording from robot import agv diff --git a/tests/test_memory.py b/tests/test_memory.py index 36cdda1..8295604 100644 --- a/tests/test_memory.py +++ b/tests/test_memory.py @@ -8,6 +8,7 @@ from pathlib import Path import numpy as np +import no_robot # noqa: F401 any connection to the robot fails the test from assistant import memory memory.DIR = Path(tempfile.mkdtemp()) diff --git a/tests/test_mimic.py b/tests/test_mimic.py index c9aa9a9..a6cc7f5 100644 --- a/tests/test_mimic.py +++ b/tests/test_mimic.py @@ -1,6 +1,7 @@ """Self-check of tasks/mimic.py without the robot or camera: face angles and the playback plan.""" import numpy as np +import no_robot # noqa: F401 any connection to the robot fails the test from tasks import mimic from vision import pose diff --git a/tests/test_mission_name.py b/tests/test_mission_name.py index f13a429..40be847 100644 --- a/tests/test_mission_name.py +++ b/tests/test_mission_name.py @@ -12,6 +12,7 @@ import time re._MAXCACHE = 100000 +import no_robot # noqa: F401 any connection to the robot fails the test from assistant import lumi from tasks import fetch diff --git a/tests/test_mission_route.py b/tests/test_mission_route.py index 328e241..82c08dc 100644 --- a/tests/test_mission_route.py +++ b/tests/test_mission_route.py @@ -6,6 +6,7 @@ drives is refused with one line, one that stays in place runs). Fake robot; the python tests/test_mission_route.py""" import types +import no_robot # noqa: F401 any connection to the robot fails the test from assistant import brain, chain, lumi, steps from tasks import fetch from tests import steps_cases7 as c7 diff --git a/tests/test_mission_stop.py b/tests/test_mission_stop.py index 7e2cdf9..12cdf4c 100644 --- a/tests/test_mission_stop.py +++ b/tests/test_mission_stop.py @@ -7,6 +7,7 @@ import tempfile import threading import time +import no_robot # noqa: F401 any connection to the robot fails the test from assistant import lumi from tasks import fetch diff --git a/tests/test_mission_talk.py b/tests/test_mission_talk.py index 4c89b24..26fdb77 100644 --- a/tests/test_mission_talk.py +++ b/tests/test_mission_talk.py @@ -2,6 +2,7 @@ python tests/test_mission_talk.py""" import time +import no_robot # noqa: F401 any connection to the robot fails the test from assistant import lumi from tasks import fetch diff --git a/tests/test_mission_wait.py b/tests/test_mission_wait.py index d356b1b..0c29f7d 100644 --- a/tests/test_mission_wait.py +++ b/tests/test_mission_wait.py @@ -3,6 +3,7 @@ the place, "go on", "okay" while receiving) and of the status answer; no robot, python tests/test_mission_wait.py""" import time +import no_robot # noqa: F401 any connection to the robot fails the test from assistant import lumi from assistant import steps from tasks import fetch diff --git a/tests/test_motion_words.py b/tests/test_motion_words.py index 2708275..67b9bbd 100644 --- a/tests/test_motion_words.py +++ b/tests/test_motion_words.py @@ -4,6 +4,7 @@ """ import types +import no_robot # noqa: F401 any connection to the robot fails the test from assistant import brain, lumi from robot import head diff --git a/tests/test_mouth.py b/tests/test_mouth.py index 1176c6a..51ef15a 100644 --- a/tests/test_mouth.py +++ b/tests/test_mouth.py @@ -2,6 +2,7 @@ python tests/test_mouth.py """ +import no_robot # noqa: F401 any connection to the robot fails the test from assistant import llm_direct from audio import mouth diff --git a/tests/test_nav_guard.py b/tests/test_nav_guard.py index f0877f6..981a69f 100644 --- a/tests/test_nav_guard.py +++ b/tests/test_nav_guard.py @@ -5,6 +5,7 @@ import re import threading import time +import no_robot # noqa: F401 any connection to the robot fails the test from robot import agv, nav_guard from tasks import fetch diff --git a/tests/test_number_slips.py b/tests/test_number_slips.py index 6697065..a571012 100644 --- a/tests/test_number_slips.py +++ b/tests/test_number_slips.py @@ -1,5 +1,6 @@ """Self-check of whisper's number / unit slips read right in a move (assistant/wording.py number_slips), and words that must stay as they are. python tests/test_number_slips.py""" +import no_robot # noqa: F401 any connection to the robot fails the test from assistant import wording CASES = { diff --git a/tests/test_objects.py b/tests/test_objects.py index c324abe..f11eeb1 100644 --- a/tests/test_objects.py +++ b/tests/test_objects.py @@ -1,6 +1,7 @@ """Self-check of objects.measure on a synthetic cup: python tests/test_objects.py""" import numpy as np +import no_robot # noqa: F401 any connection to the robot fails the test from vision import objects # camera looking along base +y, base z up (like the real torso camera), 600 mm from a cup of r 40 mm, h 100 mm @@ -27,7 +28,7 @@ box = (us.min() - 5, vs.min() - 5, us.max() + 5, vs.max() + 5) m = objects.measure(color, depth, box, INTR, T, round_=True) print(m) assert m["colour"] == "red" -cx, cy, cz = m["position_mm"] +cx, cy, cz = np.subtract(m["position_mm"], [*objects.ROUND_FIX_MM, 0]) # the measured camera error added assert abs(cx) < 5 and abs(cy - D) < 10 and abs(cz) < 5, m assert abs(m["width_mm"] - 2 * R) < 8, m assert abs(m["height_mm"] - H) < 12, m diff --git a/tests/test_parity.py b/tests/test_parity.py index 84cb7b0..e08926b 100644 --- a/tests/test_parity.py +++ b/tests/test_parity.py @@ -1,5 +1,6 @@ """tests/parity_check.py on a few fixed sentences: typed (the Command box) and voice give the same plan, English and Korean the same, each the one asked for. Rules only, nothing moves: python tests/test_parity.py""" +import no_robot # noqa: F401 any connection to the robot fails the test from tests import parity_check as pc M = ["p1", "p2", "p3", "p5", "home", "exit", "dock2"] diff --git a/tests/test_pick_sweep.py b/tests/test_pick_sweep.py index d8b15f8..ba956ee 100644 --- a/tests/test_pick_sweep.py +++ b/tests/test_pick_sweep.py @@ -9,6 +9,7 @@ import sys from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +import no_robot # noqa: F401 any connection to the robot fails the test from tests import pick_sweep as ps ps.install() diff --git a/tests/test_places.py b/tests/test_places.py index a879040..9d1a966 100644 --- a/tests/test_places.py +++ b/tests/test_places.py @@ -1,5 +1,6 @@ """Self-check of marker names and numbers as people say them (assistant/wording.py), the keyword rules (brain.intent) and the check of the LLM's place (brain.named_place), no robot, no LLM: python tests/test_places.py""" +import no_robot # noqa: F401 any connection to the robot fails the test from assistant import brain, wording from tests.steps_cases5 import INTENTS diff --git a/tests/test_pointing.py b/tests/test_pointing.py index e737e2c..d8bd593 100644 --- a/tests/test_pointing.py +++ b/tests/test_pointing.py @@ -3,6 +3,7 @@ import math import numpy as np +import no_robot # noqa: F401 any connection to the robot fails the test from robot import agv from tasks import fetch from vision import pointing, pose, scene diff --git a/tests/test_quick_answers.py b/tests/test_quick_answers.py index 375464c..2585f59 100644 --- a/tests/test_quick_answers.py +++ b/tests/test_quick_answers.py @@ -4,6 +4,7 @@ Needs the embedding server (assistant/knowledge.embed starts it); nothing moves. in other words than the bank's too; follow-ups, camera questions, commands and company facts never do.""" import re +import no_robot # noqa: F401 any connection to the robot fails the test from assistant import quick_answers as qa TALK = [("what does cutshion make?", "Cutshion makes robot applications, such as barista and cooking robots.")] diff --git a/tests/test_reach.py b/tests/test_reach.py index c3f898e..c3c505d 100644 --- a/tests/test_reach.py +++ b/tests/test_reach.py @@ -8,6 +8,7 @@ import math import numpy as np +import no_robot # noqa: F401 any connection to the robot fails the test from robot import kinematics, motion from manipulation import arm_route, skills from tasks import fetch @@ -67,13 +68,15 @@ def line_ok(w, ja): # the straight line return True except fetch.FetchError: return False -for xy in ((-104, 694), (-99, 738)): +for seen in ((-104, 694), (-99, 738)): # seen live before the camera's error was fixed + xy = np.add(seen, skills.objects.ROUND_FIX_MM) assert skills.reachable_pick(cup(*xy, -186), accept=line_ok) is None, xy plan = skills.reachable_pick(cup(*xy, -186), accept=lambda w, ja: skills.carry_up(w[0][1], ja) is not None) assert plan, xy via, carry = skills.carry_up(plan[0][0][1], plan[1]) assert via[2] > plan[0][0][1][2] and np.allclose(kinematics.pose(carry)[:3], kinematics.pose(motion.poses()["carry"])[:3], atol=0.1) -plan = skills.reachable_pick(cup(-104, 694, -186), accept=lambda w, ja: skills.carry_up(w[0][1], ja) is not None, +# the live (-104, 694) is (-92, 689) with the camera fixed: 9 mm past the trusted-turn edge; just inside it +plan = skills.reachable_pick(cup(-92, 680, -186), accept=lambda w, ja: skills.carry_up(w[0][1], ja) is not None, max_yaw=skills.TRUSTED_YAW_DEG) assert plan and abs(skills.yaw_of(plan[0][1][1])) <= 15.5, plan @@ -111,7 +114,8 @@ assert np.isclose(np.hypot(*(np.subtract((t["x"], t["y"]), C))), np.hypot(*(np.s assert t["x"] > o["x"] # waist left: a thing on the left comes ahead assert np.allclose([fetch.turned(t, -30.0)[k] for k in "xy"], [o[k] for k in "xy"]) -for r, b in ((600, 60), (600, -60), (550, 90), (600, -100), (730, 7), (720, 25)): # beside it and the live ones +for r, b in ((600, 60), (600, -60), (550, 90), (600, -100), (720, 7), (720, 25)): # beside it and the live ones + # (the live 730 mm one is 1 cm past the trusted reach since the grasp point was fixed, 2026-10-27) o = around(r, b) assert trusted(o) is None, (r, b) # not from here ... turns = fetch.waist_for(o) @@ -125,9 +129,10 @@ for r, b in ((1000, 0), (950, 40)): # too far for any wa LIVE = (((262, 774, -189), "base"), ((267, 763, -188), "base"), ((260, 722, -186), "base"), # missed at -45 / -30 ((300, 621, -191), "waist"), ((-99, 738, -181), "waist"), # missed at -30 / carry line jumped at -30 ((-141, 869, -186), "base"), ((-117, 960, -186), "base"), # across the table / far - ((-104, 694, -186), "here"), ((-73, 588, -186), "here"), ((-96, 598, -260), "here")) # carried / picked -for (x, y, top), how in LIVE: - o = cup(x, y, top) + ((-104, 694, -186), "waist"), ((-73, 588, -186), "here"), ((-96, 598, -260), "here")) # carried / picked +# (694: picked from here live; at the trusted-turn edge since the grasp point was fixed, a small waist turn first) +for (x, y, top), how in LIVE: # seen before the camera's error was fixed + o = cup(x + skills.objects.ROUND_FIX_MM[0], y + skills.objects.ROUND_FIX_MM[1], top) got = "here" if trusted(o) else "waist" if any(trusted(fetch.turned(o, d)) for d in fetch.waist_for(o)) else "base" assert got == how, ((x, y, top), got, how) body["waist"] = 100.0 # the waist near its limit (140): no turn past it @@ -143,7 +148,7 @@ fetch._other_here = lambda task, obj: None fetch.arm_yaw = lambda: -95.5 fetch.remember = lambda obj, yaw: {} fetch.agv.pose = lambda: (0.0, 0.0, 0.0) -def waist_to(rel): +def waist_to(rel, in_place=False): calls.append(("waist", round(rel))) body["waist"] = -20.31 + rel return True diff --git a/tests/test_reid.py b/tests/test_reid.py index cbc7de8..f9bc616 100644 --- a/tests/test_reid.py +++ b/tests/test_reid.py @@ -4,6 +4,7 @@ import types import numpy as np +import no_robot # noqa: F401 any connection to the robot fails the test from assistant import lumi from vision import reid diff --git a/tests/test_robot_free.py b/tests/test_robot_free.py index 7262361..60833bb 100644 --- a/tests/test_robot_free.py +++ b/tests/test_robot_free.py @@ -5,6 +5,7 @@ import json import tempfile from pathlib import Path +import no_robot # noqa: F401 any connection to the robot fails the test from fastapi import HTTPException from api import server diff --git a/tests/test_route_words.py b/tests/test_route_words.py index d442cc4..dbd3e04 100644 --- a/tests/test_route_words.py +++ b/tests/test_route_words.py @@ -5,6 +5,7 @@ cases. No robot. .venv/bin/python tests/test_route_words.py """ +import no_robot # noqa: F401 any connection to the robot fails the test from assistant import brain, detour from tests import command_check diff --git a/tests/test_scene.py b/tests/test_scene.py index 2b57aa3..a69f3af 100644 --- a/tests/test_scene.py +++ b/tests/test_scene.py @@ -5,6 +5,7 @@ from pathlib import Path import numpy as np +import no_robot # noqa: F401 any connection to the robot fails the test from assistant import seeing from vision import pose, scene diff --git a/tests/test_seeing_dialogues.py b/tests/test_seeing_dialogues.py index f801ac9..1efdf4f 100644 --- a/tests/test_seeing_dialogues.py +++ b/tests/test_seeing_dialogues.py @@ -15,6 +15,7 @@ import sys import time from pathlib import Path +import no_robot # noqa: F401 any connection to the robot fails the test from assistant import brain, lumi, seeing from vision import scene diff --git a/tests/test_seeing_fresh.py b/tests/test_seeing_fresh.py index 90d9149..45ffc55 100644 --- a/tests/test_seeing_fresh.py +++ b/tests/test_seeing_fresh.py @@ -9,6 +9,7 @@ import tempfile import time from pathlib import Path +import no_robot # noqa: F401 any connection to the robot fails the test import cv2 import numpy as np diff --git a/tests/test_seeing_people.py b/tests/test_seeing_people.py index 3d8651b..da6bd52 100644 --- a/tests/test_seeing_people.py +++ b/tests/test_seeing_people.py @@ -5,6 +5,7 @@ alone. Fake people, no robot, no VLM. python tests/test_seeing_people.py """ import re +import no_robot # noqa: F401 any connection to the robot fails the test from assistant import seeing from vision import scene diff --git a/tests/test_skills.py b/tests/test_skills.py index aa064bf..400d330 100644 --- a/tests/test_skills.py +++ b/tests/test_skills.py @@ -1,6 +1,7 @@ """Self-check of the skills.py geometry, no robot: python tests/test_skills.py""" import numpy as np +import no_robot # noqa: F401 any connection to the robot fails the test from vision import calib, head_cam from manipulation import skills @@ -124,6 +125,29 @@ assert plan and plan[1][4] < 0 and abs(round(skills.yaw_of(plan[0][1][1]))) == 4 plan = skills.reachable_pick(cup, start, accept=lambda wp, ja: abs(skills.yaw_of(wp[1][1])) > 100) assert plan and abs(round(skills.yaw_of(plan[0][1][1]))) == 105, plan assert skills.reachable_pick(cup, start, accept=lambda wp, ja: False) is None +# trusted turns are the ones picked live, -15..0: +15 missed 2 of 2 (a finger on the cup); the voice pick keeps to them +def ik_at(turns): + def ask(name, **a): + if name == "kine_forward": + return {"errorCode": "0", "cartPosition": [0, 0, 0] + list(skills.GRASP_RPY)} + ok = round(skills.yaw_of(a["cartPosition"])) in turns + return {"errorCode": "0", "jointPosition": list(a["jointPosition"])} if ok else {"errorCode": "1"} + return ask +skills._ask = ik_at({15, -15}) +plan = skills.reachable_pick(cup, start, max_yaw=skills.TRUSTED_YAW_DEG) +assert plan and round(skills.yaw_of(plan[0][1][1])) == -15, plan +skills._ask = ik_at({15, 30}) +assert skills.reachable_pick(cup, start, max_yaw=skills.TRUSTED_YAW_DEG) is None +real_find, real_guarded, real_home = skills.find, skills._guarded, skills.home_joints +skills.home_joints = lambda: start +skills.find = lambda name, colour=None, seen=None: dict(cup, colour="grey", width_mm=74) +skills._guarded = lambda *a: (_ for _ in ()).throw(AssertionError("picked at an untrusted turn")) +try: + skills.pick("cup") + raise AssertionError("picked") +except skills.SkillError as e: + assert e.args[0] == "I can't reach it safely.", e +skills.find, skills._guarded, skills.home_joints = real_find, real_guarded, real_home # hand_sees: depth right at the cup's axis = object, far behind it = empty, nothing seen = unknown skills.objects.base_from_camera = lambda: np.eye(4) # camera at the arm base origin skills._ask = lambda name, **a: {"errorCode": "0", "cartPosition": [0.0, 500.0, 0.0] + list(skills.GRASP_RPY)} @@ -162,7 +186,8 @@ assert np.allclose(np.array(d[:3]) + R @ (skills.GRASP_OFFSET + skills.TIPS_OFFS skills._held.clear() # the owner's taught tips grasp of the spray can (grasp_tips_teach.json): the same flange within a few mm, 2 deg t = skills.TIPS_TEACH -f = skills.flange_for(*t["can_seen"], t["grasp_point_code"][2], skills.yaw_of(t["flange"]), tips=True) +can = np.add(t["can_seen"][:2], skills.objects.ROUND_FIX_MM) # seen before the camera's error was fixed +f = skills.flange_for(*can, t["grasp_point_code"][2], skills.yaw_of(t["flange"]), tips=True) assert np.linalg.norm(np.subtract(f[:3], t["flange"][:3])) < 10, f # ---------- frames after a move: wait for one written after it ended, never longer than FRESH_WAIT_S ---------- diff --git a/tests/test_songs.py b/tests/test_songs.py index 568c323..6bbe046 100644 --- a/tests/test_songs.py +++ b/tests/test_songs.py @@ -7,6 +7,7 @@ import types import numpy as np +import no_robot # noqa: F401 any connection to the robot fails the test from audio import sing from assistant import lumi @@ -172,6 +173,17 @@ assert time.time() - stop_at < 0.1, time.time() - stop_at # at on sing._head_thread.join(2) assert head.moves and head.moves[-1] == [120.0, 5.0, 0.0, 0.0], head.moves +for centre in (-40.0, 55.0, -90.0): # the owner on a side: the dance around them, inside the limits + head = FakeHead() + assert sing.sing(B, None, player(2.5), head, fake_load, centre_yaw=centre) + sing._head_thread.join(2) + c = max(-sing.YAW_LIMIT, min(sing.YAW_LIMIT, centre)) + assert head.moves[0][2] == c and head.moves[-1][2] == c, (centre, head.moves) # turns there and stays there + assert all(abs(m[2] - c) <= sing.YAW_SWAY and abs(m[2]) <= sing.YAW_LIMIT for m in head.moves), (centre, head.moves) + assert c == -sing.YAW_LIMIT or len({m[2] for m in head.moves}) > 2, head.moves # still dances (at the limit: one side) +assert all(abs(sing.around(c, y)) <= sing.YAW_LIMIT for c in range(-90, 91, 5) for y in range(-40, 41, 2)) +assert sing.around(0.0, 33.0) == 33.0 # the default: as before + played = [] # a stereo file reaches the one-channel speaker as mono assert sing.sing(D, None, lambda wav, rate, abort: played.append(wav.ndim) or True, FakeHead(), lambda path: (np.zeros((4410, 2), np.float32), 44100)) @@ -184,9 +196,13 @@ heard = [] # what the fake clip mic he sung = [] -def fake_sing(sid, abort=None): +centres = [] + + +def fake_sing(sid, abort=None, centre_yaw=0.0): sung.append(sid) - return real_sing(sid, abort, player(5), FakeHead(), fake_load) + centres.append(centre_yaw) + return real_sing(sid, abort, player(5), FakeHead(), fake_load, centre_yaw) lumi.sing.sing = fake_sing @@ -194,11 +210,13 @@ lumi.LOG_FILE = "/dev/null" # keep the assistant's log clea lumi.ears.transcribe = lambda mono: heard.pop(0) if heard else "" lumi.ears.understood = lambda *a: True L = lumi.Lumi.__new__(lumi.Lumi) +L.markers = ["home", "p1"] # never the base's marker list L.lang, L.current, L.vision, L.last_song, L.pending_text, L.voice_until = "en", None, None, None, None, 0.0 L.skill_thread, L.mission_hold = None, None L.brain = types.SimpleNamespace(history=[]) L.fetch_status = lambda: None L.mission_running = lambda: False +L.det_yaw = lambda: -40.0 # nobody tracked: the head already faces the voice utterance = types.SimpleNamespace(during_speech=True, seconds=1.0, mono=None) L.mic = types.SimpleNamespace(next=lambda wait: utterance if heard else None) @@ -206,6 +224,7 @@ t0 = time.time() threading.Timer(0.3, lambda: heard.append("stop")).start() L.sing_song("sing Love Attack") assert sung == [L_] and time.time() - t0 < 1.0 and L.pending_text is None, (sung, time.time() - t0) +assert centres == [-40.0], centres # the dance stays toward the listener threading.Timer(0.3, lambda: heard.append("sing another song")).start() L.sing_song("sing a song") @@ -221,6 +240,24 @@ t0 = time.time() L.sing_song("sing Fantastic Baby") assert time.time() - t0 > 4.5 and L.pending_text is None +# words over a song that are no new request leave it going (logs/lumi.log 2026-10-27, logs/heard): whisper's words +# from the music (0.26 s of speech for "Last hole."), a single word, the request said again while it starts +lumi.ears.last_stt = {"speech_s": 0.26} +threading.Timer(0.3, lambda: heard.append("Last hole.")).start() +t0 = time.time() +L.sing_song("Let's make music.") +assert time.time() - t0 > 4.5 and L.pending_text is None +lumi.ears.last_stt = {} +ign = sing.ignored_over_song +assert ign("Last hole.", "Let's make music.", 3.0, 0.26) and ign("Let's make music.", "Let's make music.", 2.0, 0.99) +assert ign("Okay.", "sing a song", 3.0, 0.5) and ign("Lumi.", "sing a song", 3.0, None) +assert ign("sing a song", "Let's make music.", 40.0, 1.0) and ign("노래 불러 줘", "sing a song", 40.0, 1.0) +assert ign("Let's make music.", "Let's make music.", 40.0, 0.99) is None # long after: asked for real +for words, speech in (("Let's change music.", 1.28), ("Let's change the music.", 1.2), ("another song", 0.6), + ("다른 노래", 0.6), ("바꿔", 0.3), ("sing Fantastic Baby", 0.9), ("What time is it?", 0.9), + ("Lumi, go to p3", 0.8), ("Let's make music.", None)): + assert ign(words, "Let's make music.", 2.0 if words != "Let's make music." else 30.0, speech) is None, words + # lumi.answer(): "again" right after a song is the song (not the drive words), "Can you sing song?" tagged Korean # by whisper is still sung, "what songs can you sing?" lists them said = [] diff --git a/tests/test_steps.py b/tests/test_steps.py index dadbfe9..981cd30 100644 --- a/tests/test_steps.py +++ b/tests/test_steps.py @@ -5,6 +5,7 @@ Each case: command -> the steps it must give, written short: say | place | place white dining table left | give | hold | arm reach | wait (no time: stay / until go on) | wait 30 | wait order [600] (an instruction there) | receive cup wait [120] "?" as the steps: some words must stay unread (Lumi asks again, nothing runs).""" +import no_robot # noqa: F401 any connection to the robot fails the test from assistant import steps M = ["home", "PInit", "Wp", "a", "b", "dock2", "exit", "final"] + [f"p{i}" for i in range(1, 11)] diff --git a/tests/test_stop_live.py b/tests/test_stop_live.py index ea2d655..425a8e1 100644 --- a/tests/test_stop_live.py +++ b/tests/test_stop_live.py @@ -22,11 +22,13 @@ lumi.motion.stop = lambda: done.append("arm stop") follow.stop = lambda: done.append("follow stop") fetch.stop = lambda: done.append("fetch stop") fetch.state = lambda: {"status": "idle"} +lumi.waist_home = lambda why: True # the waist at the front before a drive (it reads the body and arm) +lumi.waist_turned = lambda: 0.0 lumi.mouth.say = lambda text, **k: done.append(("say", text)) lumi.mouth.own_voice = lambda u: False lumi.mouth.recent_speech = lambda s: "" lumi.doa.load_calib = lambda: {"fitted": False} -lumi.doa.estimate = lambda mics, cal: (0.0, 0.0, 0.0) +lumi.doa.estimate = lambda mics, cal, ref=None: (0.0, 0.0, 0.0) lumi.ears.heard_lang = lambda lang: lang @@ -125,13 +127,13 @@ lumi.head.status = lambda: [0, 0, 0, 0] lumi.nav.person_on_map = lambda *a: (3.0, 0.0) lumi.nav.approach = lambda *a: (2.0, 0.0, 0.0) L = fresh(U("Stop!"), trip=False) -L.vision, L.modes, L.turn_head = Vision(), type("Modes", (), {"drive": True})(), lambda *a: None +L.vision, L.modes, L.turn_head = Vision(), type("Modes", (), {"drive": True})(), lambda *a, **k: None base["move_status"] = "running" t = time.time() L.come_to(Track()) assert stopped(L) and time.time() - t < 3, done L = fresh(U("What is your name?"), trip=False) -L.vision, L.modes, L.turn_head = Vision(), type("Modes", (), {"drive": True})(), lambda *a: None +L.vision, L.modes, L.turn_head = Vision(), type("Modes", (), {"drive": True})(), lambda *a, **k: None base["move_status"] = "running" threading.Timer(1.0, lambda: base.update(move_status="succeeded")).start() L.come_to(Track()) @@ -140,7 +142,7 @@ assert "agv cancel" not in done and L.pending_text == "What is your name?", done # right after Lumi said "Okay, I stopped.", "Stop." is no echo of it (own_echo counts "stop" in "stopped") lumi.mouth.recent_speech = lambda s: "Okay, I stopped. Let's go to p5." L = fresh(U("Stop."), trip=False) -L.vision, L.modes, L.turn_head = Vision(), type("Modes", (), {"drive": True})(), lambda *a: None +L.vision, L.modes, L.turn_head = Vision(), type("Modes", (), {"drive": True})(), lambda *a, **k: None base["move_status"] = "running" L.come_to(Track()) assert stopped(L), done @@ -148,7 +150,7 @@ head_u = U("Stop.") head_u.source = "head" lumi.ears.listen = lambda **k: ("Stop.", head_u) L = fresh(trip=False) -L.warm_llm, L.interrupted, L.who_spoke, L.mission_hold = lambda: None, lambda: False, lambda u: None, None +L.warm_llm, L.interrupted, L.who_spoke, L.mission_hold = lambda: None, lambda: False, lambda u, text=None: None, None L.follow_filter = lambda text, u: False assert L.talk_turn() and ("answer", "Stop.") in done, done @@ -161,7 +163,7 @@ for heard in ("Stop.", "멈춰.", "Stop it."): L = fresh(U(heard, during_speech=True)) assert L.check_wake() and stopped(L), (heard, done) L = fresh(trip=False) -L.warm_llm, L.interrupted, L.who_spoke, L.mission_hold = lambda: None, lambda: False, lambda u: None, None +L.warm_llm, L.interrupted, L.who_spoke, L.mission_hold = lambda: None, lambda: False, lambda u, text=None: None, None L.follow_filter = lambda text, u: False assert L.talk_turn() and ("answer", "Stop.") in done, done L = fresh(U("Okay, I'm going to p5.", during_speech=True)) # Lumi's own sentence: still ignored diff --git a/tests/test_switches.py b/tests/test_switches.py index 14c84bb..f73b3f9 100644 --- a/tests/test_switches.py +++ b/tests/test_switches.py @@ -4,6 +4,7 @@ arm action with the arm switched off asks to enable it, nothing else asks. Fake python tests/test_switches.py""" import types +import no_robot # noqa: F401 any connection to the robot fails the test from assistant import lumi from tasks import fetch, follow @@ -175,9 +176,9 @@ L.act("go_to", "p3") assert moved == ["start_trip"] follow.stop, fetch.stop = real_follow_stop, real_fetch_stop -# ---------- "reach out to me": toward the person; Greeter never turns the base for it, asks them in front ---------- -assert lumi.reach_turn(None, True) is None and lumi.reach_turn(10.0, False) == 0.0 -assert lumi.reach_turn(-35.0, True) == -35.0 and lumi.reach_turn(35.0, False) is None +# ---------- "reach out to me": toward the person; the waist turns to them with Greeter only too (the base stays) ---- +assert lumi.reach_turn(None) is None and lumi.reach_turn(10.0) == 0.0 +assert lumi.reach_turn(-35.0) == -35.0 and lumi.reach_turn(35.0) == 35.0 reached = [] real_reach = fetch.reach fetch.reach = lambda angle=0.0, say=None: reached.append(angle) @@ -185,14 +186,16 @@ L.fetch_finish = lambda how, **k: moved.append(how) L.skill_thread, L.voice_trusted = None, False person = types.SimpleNamespace(angle=35.0) L.vision = types.SimpleNamespace(present=lambda t: False, near_angle=lambda a, d=25: None, only_person=lambda: person) -for patrol, angle, want in ((False, 35.0, None), (True, 35.0, [35.0]), (False, -12.0, [0.0]), (True, -12.0, [0.0])): +L.turn_head = lambda yaw=None, pitch=None, force=False: moved.append(("head", yaw)) +for patrol, angle, want in ((False, 35.0, [35.0]), (True, 35.0, [35.0]), (False, -40.0, [-40.0]), (False, -12.0, [0.0]), + (True, -12.0, [0.0])): L.modes.patrol, person.angle = patrol, angle reached.clear(), said.clear(), moved.clear() got = L.reach_out(False) - if want is None: # nothing moves, not even the head - assert got is None and not reached and said == [lumi.GREETER_FRONT_SAY[0]] and not moved, (angle, said) - else: - assert got and reached == want and moved == ["head"], (patrol, angle, reached, moved) + # a waist turn takes the head onto them (fetch._waist_to look); a head turn here raced it (looked away live) + head_cmds = [] if want[0] else [("head", lumi.HEAD_SIGN * angle)] + assert got and reached == want and moved == head_cmds and not said, (patrol, angle, reached, moved, said) +L.turn_head = lambda *a, **k: moved.append("head") L.vision = None # nobody seen, the voice's direction not trusted: ask reached.clear(), said.clear() assert L.reach_out(False) is None and not reached and said == [lumi.STAND_IN_FRONT_SAY[0]] @@ -210,5 +213,60 @@ assert lumi.Lumi.arm_pose(L, "open") and moved == ["open"] and not said, (moved, lumi.gripper.open_, fetch.check_hand = real_open, real_check L.fetch_status = lambda: None fetch.reach = real_reach + +# ---------- the waist back to the front (waist_home): in place, Greeter only too; never with the arm out or a task ---- +real = {n: getattr(fetch, n) for n in ("_waist_turn", "state", "_at_pose", "_waist_to")} +calls = [] +fetch._waist_to = lambda rel, in_place=False: calls.append((rel, in_place)) or True +fetch.state = lambda: {"status": "idle"} +fetch._at_pose = lambda name: True +fetch._waist_turn = lambda: 0.4 # at the front already: nothing moves +assert lumi.waist_home("test") and calls == [] +fetch._waist_turn = lambda: 35.0 # turned for a person +fetch.state = lambda: {"status": "running"} # a task turns the waist itself +assert lumi.waist_home("test") is False and calls == [] +fetch.state = lambda: {"status": "done"} +fetch._at_pose = lambda name: False # the hand held out (a reach): it stays turned +assert lumi.waist_home("test") is False and calls == [] +fetch._at_pose = lambda name: True +assert lumi.waist_home("test") and calls == [(0.0, True)] # in place: also with Patrol off (stay_put) +fetch._waist_to = lambda rel, in_place=False: False # the arm's sweep is not clear +assert lumi.waist_home("test") is False +for n, f in real.items(): + setattr(fetch, n, f) + +# ---------- every drive and base turn starts with the waist at the front ---------- +order = [] +real_home = lumi.waist_home +lumi.waist_home = lambda why: order.append("waist") or True +lumi.agv.status = lambda: {"move_status": "idle", "power_percent": 90} +lumi.agv.go = lambda m: order.append(("go", m)) or (True, "OK") +lumi.agv.go_point = lambda x, y, th: order.append(("go", (x, y, th))) or (True, "OK") +lumi.agv.turn_by = lambda a: order.append(("turn", round(lumi.math.degrees(a)))) or (True, "OK") +P = lumi.Patrol(["p3"], once=True) +P.tick(force=True) +assert order == ["waist", ("go", "p3")] and P.moving, order +lumi.agv.status = lambda: {"move_status": "idle", "power_percent": 2} # low battery: home, the waist first +order.clear() +P = lumi.Patrol(["p3"]) +P.tick(force=True) +assert order == ["waist", ("go", "home")] and P.mode == "going_home", order +lumi.agv.status = lambda: {"move_status": "idle", "power_percent": 90} +L.modes.patrol, L.modes.drive = True, True +real_turned, lumi.waist_turned = lumi.waist_turned, lambda: 30.0 # turned 30 left for someone +order.clear() +L.look_toward(150.0) # a voice behind: the base turns to it from the base's front +assert order == ["waist", ("turn", 180)], order +lumi.waist_home = lambda why: order.append("waist") or False # it can't come back: no drive, no turn, said why +order.clear() +P = lumi.Patrol(["p3"], once=True) +P.tick(force=True) +assert order == ["waist"] and P.stuck == "p3" and P.stuck_why == lumi.WAIST_BACK_SAY and P.mode == "done" +order.clear() +L.look_toward(150.0) +assert order == ["waist"], order +lumi.waist_home, lumi.waist_turned = real_home, real_turned +for name in ("status", "go", "go_point", "turn_by"): + setattr(lumi.agv, name, forbid) print(f"switches ok: {len(BASE)} base phrases refused with Greeter only, {len(IN_PLACE)} in place done; " "arm off asks; Patrol allows all; stop always") diff --git a/tests/test_talk.py b/tests/test_talk.py index 34fae74..3415981 100644 --- a/tests/test_talk.py +++ b/tests/test_talk.py @@ -9,6 +9,7 @@ """ import time +import no_robot # noqa: F401 any connection to the robot fails the test from assistant import brain, knowledge, memory, talk_examples, web FAKE_NOW = "Friday, 13 March 2026, 10:05" # a date the model could never have guessed diff --git a/tests/test_task_switches.py b/tests/test_task_switches.py index ba3e35e..c7b6555 100644 --- a/tests/test_task_switches.py +++ b/tests/test_task_switches.py @@ -6,6 +6,7 @@ import json import tempfile from pathlib import Path +import no_robot # noqa: F401 any connection to the robot fails the test from fastapi import HTTPException from api import server diff --git a/tests/test_vision.py b/tests/test_vision.py index 7856505..f8b79f7 100644 --- a/tests/test_vision.py +++ b/tests/test_vision.py @@ -1,5 +1,6 @@ """Self-check of the camera choice in lumi.Vision (head standing, torso driving, fallback), no robot: python tests/test_vision.py""" +import no_robot # noqa: F401 any connection to the robot fails the test from assistant import lumi v = lumi.Vision.__new__(lumi.Vision) # no camera service needed: only pick() is checked diff --git a/tests/test_voice_words.py b/tests/test_voice_words.py index 7920289..081d8df 100644 --- a/tests/test_voice_words.py +++ b/tests/test_voice_words.py @@ -5,6 +5,7 @@ import pathlib import tempfile import types +import no_robot # noqa: F401 any connection to the robot fails the test from assistant import lumi from assistant import voice_words as vw from audio import mouth @@ -62,6 +63,7 @@ mouth.say = lambda text, lang=None, abort=None: said.append(text) lumi.ears.understood = lambda *a: True lumi.ears.last_stt = {"language": "english", "logprob": -0.1} L = lumi.Lumi.__new__(lumi.Lumi) +L.markers = ["home", "p1"] # never the base's marker list L.lang, L.current, L.closing_pending = "en", None, None L.brain = types.SimpleNamespace(history=[]) L.follow_stop = lambda text: False diff --git a/tests/test_wake.py b/tests/test_wake.py index 075ba5f..2c57426 100644 --- a/tests/test_wake.py +++ b/tests/test_wake.py @@ -7,6 +7,7 @@ import threading import time import types +import no_robot # noqa: F401 any connection to the robot fails the test from assistant import brain as brain_mod from assistant import lumi from tasks import fetch, follow @@ -24,11 +25,13 @@ lumi.mouth.own_voice = lambda u: False lumi.mouth.recent_speech = lambda s: "" lumi.mouth.last_echo = 0.0 lumi.doa.load_calib = lambda: {"fitted": False} -lumi.doa.estimate = lambda mics, cal: (0.0, 0.0, 0.0) +lumi.doa.estimate = lambda mics, cal, ref=None: (0.0, 0.0, 0.0) lumi.ears.heard_lang = lambda lang: lang lumi.ears.transcribe = lambda mono: mono lumi.ears.understood = lambda lp: True lumi.time.sleep = lambda s: None +lumi.waist_turned = lambda: 0.0 # the waist at the front (it reads the body) +lumi.waist_home = lambda why: True M = ["home", "dock2"] @@ -106,7 +109,7 @@ def fresh(*tracks, utts=()): L.mission_running = lambda: False L.mission_hold = None L.warm_llm = lambda: None - L.who_spoke = lambda u: done.append("who spoke") + L.who_spoke = lambda u, text=None: done.append("who spoke") lumi.ears.listen = lambda **k: (None, None) done.clear() up.clear() @@ -264,9 +267,68 @@ time.sleep(0.2) assert moves == [(10.0, 10), (0, lumi.head.HEAD_REST_PITCH)] and not H.look_held(), moves moves.clear() H.looked_at = H.last_activity = time.time() -H.head_rest() # a goodbye / stop word ends the hold +H.head_rest() # "be quiet" ends the hold time.sleep(0.2) assert moves == [(0, lumi.head.HEAD_REST_PITCH)] and H.looked_at == 0.0, moves lumi.head.status, lumi.head.turn = real_status, real_turn +# the head stays toward the person while the conversation goes on; it rests only when the conversation is over +fetch.stop = lambda: done.append("fetch stop") +L = fresh(a := Track(31, 40)) +a.greeted, L.current, L.looked_at = True, a, time.time() +L.act = lambda action, target: done.append(("act", action)) +L.stop_all("Stop.") # stopping a song or an answer mid-talk +assert ("act", "stop") in done and "head" not in done and L.looked_at == 0.0, done +L = fresh(a := Track(32, 40)) +a.greeted, L.current = True, a +L.vision.tracks.clear() # out of the frame, nobody else greeted +L.step() +assert L.current is None and L.voice_until > time.time() and "head" not in done, done +L.step() # the voice session goes on: still no rest +assert "head" not in done, done +L.voice_until = time.time() - 1 # the session ends by silence, nobody in view +L.check_wake = lambda: False +L.step() +assert "head" in done and L.voice_until == 0.0, done # end_conversation: yaw 0, rest pitch + +# the conversation ends (silence, goodbye, "be quiet"): the waist comes back to the front too, Greeter or Patrol; +# a held look keeps both (the waist waits like the head) +homed, back = [], threading.Event() +real_home, real_turned = lumi.waist_home, lumi.waist_turned +lumi.waist_home = lambda why: homed.append(why) or back.set() or True +for patrol in (False, True): + L = fresh(a := Track(33, 40)) + a.greeted, L.current, L.modes.patrol = True, a, patrol + L.traveling = lambda: False + homed.clear(), back.clear() + L.end_conversation(None, quiet=True) + assert back.wait(2) and "head" in done and L.current is None and homed, (patrol, done, homed) + homed.clear(), back.clear() + L.head_rest() # "be quiet" + assert back.wait(2) and homed +L.looked_at = L.last_activity = time.time() # "look up" just now, then silence ends the talk +homed.clear(), back.clear() +L.end_conversation(None, quiet=True) +assert not back.wait(0.3) and not homed + +# someone else takes over (on the right, Lumi turned left for the first one): the waist back to the front, then the +# head to the new person (their angle from the waist's old place + the turn taken back); not turned: the head only +lumi.doa.load_calib = lambda: {"fitted": True} +lumi.doa.clip_ref = lambda u: None +lumi.doa.estimate = lambda mics, cal, ref=None: (-50.0, 0.9, 0.0) +for turned, homes, want in ((30.0, True, -20.0), (30.0, False, -50.0), (0.0, True, -50.0)): + L = fresh(a := Track(40, 40), b := Track(41, -50)) + a.greeted, L.current = True, a + heads, back = [], threading.Event() + L.turn_head = lambda yaw=None, *r, **k: heads.append(yaw) or back.set() + lumi.waist_turned = lambda w=turned: w + lumi.waist_home = lambda why, ok=homes: homed.append(why) or ok + homed.clear() + lumi.Lumi.who_spoke(L, U("Lumi, stop.", seconds=1.0)) + assert back.wait(2) and L.current is b and heads == [lumi.HEAD_SIGN * want], (turned, homes, heads) + assert bool(homed) == bool(turned), (turned, homed) +lumi.waist_home, lumi.waist_turned = real_home, real_turned +lumi.doa.load_calib = lambda: {"fitted": False} +lumi.doa.estimate = lambda mics, cal, ref=None: (0.0, 0.0, 0.0) + print("ok: wake words, waves, no greeting to passers-by or during tasks, answers never cut, names") diff --git a/tests/test_wave.py b/tests/test_wave.py index 23c679f..3f87b84 100644 --- a/tests/test_wave.py +++ b/tests/test_wave.py @@ -7,6 +7,7 @@ from pathlib import Path import numpy as np +import no_robot # noqa: F401 any connection to the robot fails the test from assistant import lumi from manipulation import arm_route, skills, wave from robot import agv, arm, gripper, motion @@ -27,6 +28,7 @@ gripper.state = lambda: {"holding": hand["holding"]} base = {"move_status": "idle"} agv.status = lambda: dict(base) wave.log = arm_route.log = lambda *a: None +fetch._waist_turn = lambda: 0.0 # the waist at the front (never the body) motion.SETTLE_S = 0.01 # quick here (tests/test_arm_route.py checks it) @@ -128,11 +130,12 @@ refused(wave.HOLDING) skills.hand_sees = lambda: "unknown" assert a.sent == [] -# ---------- from carry (empty hand): down to look first, then up ---------- +# ---------- from carry (empty hand): the least joint travel checked; straight to wave_start passes the head ---------- POSES["carry"] = [30.0, 0.0, 0.0, 0.0, 0.0, 0.0] a = use(FakeArm(POSES["carry"])) wave.wave() -assert a.sent[:4] == [LOOK, POSES["wave_out"], top, swing], a.sent +assert a.sent[:3] == [POSES["wave_out"], top, swing], a.sent +assert arm_route.profile(POSES["carry"], top, HEAD)[0] < arm_route.HEAD_CLEAR_MM del POSES["carry"] # ---------- an unknown start (after free drive: the wrist the other way round): joins by a checked move; power ---------- @@ -152,7 +155,7 @@ del POSES["wave"] refused(wave.NOT_TAUGHT) POSES["wave"] = swing del POSES["wave_out"] -refused(wave.NOT_TAUGHT) +refused(wave.NEAR_HEAD) # the ways left (look -> wave -> ...) pass the head POSES["wave_out"] = [-50.0, 0.0, 0.0, 0.0, 0.0, 0.0] assert arm.cmd.sent == [] # nothing sent for any refusal diff --git a/tests/test_web.py b/tests/test_web.py index f47a7df..a05564b 100644 --- a/tests/test_web.py +++ b/tests/test_web.py @@ -4,6 +4,7 @@ The search words made from a question, the parts of a Naver page that are kept, DuckDuckGo when Naver gives nothing), and what a follow-up of a lookup searches for. Live answers: tests/web_check.py.""" import datetime +import no_robot # noqa: F401 any connection to the robot fails the test from assistant import brain, lumi, web # English questions become search words; Korean stays as it is diff --git a/vision/objects.py b/vision/objects.py index 40f1e09..6ea59e8 100644 --- a/vision/objects.py +++ b/vision/objects.py @@ -33,6 +33,8 @@ EDGE_PCT = (1, 99) # percentiles taken as the object's edges (robust to MIN_SATURATION = 50 # HSV S below this is white / grey / black DARK_V = 60 # HSV V below this has no hue the camera can tell (black trousers: V ~48, S ~95, read # "blue"; blue jeans V ~90, 2026-10-22) +ROUND_FIX_MM = (13.9, -3.1) # mm (x, y), arm frame, added to a round thing's centre: the camera read cup centres this + # far off, mean of three spots 7-11 cm apart (hover readings, 2026-10-27; +-4 mm between them) EDGE_PX = 4 # a box this close to the bottom of the frame is cut off: height and centre z unknown STALE_S = 1.5 # s; an older detection file means the camera service is not live SURE_SCORE = 0.35 # a box scoring less (person.WEAK_SCORE) is kept only when depth measures this size there: @@ -146,7 +148,7 @@ def measure(color, depth, box, intr, T, round_=False): width = float(np.subtract(*np.percentile(across, EDGE_PCT[::-1]))) centre = np.array([*surface[:2], (top + bottom) / 2]) if round_: # the camera sees the front; the centre is behind it - centre[:2] += sight * width / 2 + centre[:2] += sight * width / 2 + np.array(ROUND_FIX_MM) out.update(position_mm=[round(float(v)) for v in centre], top_mm=round(float(top)), width_mm=round(width), height_mm=round(float(top - bottom))) return out