From 88a5349b0463b70013a59470e6f5dace1ef85e7c Mon Sep 17 00:00:00 2001 From: Cutshion Date: Thu, 22 Oct 2026 14:07:56 +0900 Subject: [PATCH] Conversation and web: closings by context, follow-up lookups keep the name and place, office holders and prices looked up; reach toward the person; bottles by their body (belly grasp only); music never a turn (speech detector); songs: a promise is done; two-stop drives in the Command box Co-Authored-By: Claude Opus 5.5 --- api/server.py | 3 + assistant/brain.py | 85 ++++++--- assistant/lumi.py | 99 ++++++++-- assistant/steps.py | 7 +- assistant/talk_examples.py | 9 +- audio/ears.py | 56 +++++- audio/sing.py | 11 +- audio/sing_render.py | 321 --------------------------------- data/grasp_tips_teach.json | 35 ++++ data/songs/arirang.json | 9 - data/songs/happy_birthday.json | 9 - data/songs/row_row.json | 9 - data/songs/three_bears.json | 9 - data/songs/twinkle.json | 9 - manipulation/skills.py | 113 ++++++++---- tasks/fetch.py | 58 +++++- tests/asr_cases4.py | 94 ++++++++++ tests/asr_check.py | 16 +- tests/closing_check.py | 2 +- tests/command_cases2.py | 5 + tests/command_cases3.py | 2 +- tests/command_check.py | 12 +- tests/conversation_check.py | 4 +- tests/followup_cases_more.py | 4 + tests/song_cases.py | 49 +++++ tests/steps_cases7.py | 5 + tests/steps_cases8.py | 4 +- tests/test_ears.py | 24 +++ tests/test_fetch.py | 45 ++++- tests/test_fetch_place.py | 5 + tests/test_skills.py | 114 +++++++++++- tests/test_steps.py | 10 + tests/test_switches.py | 30 +++ vision/objects.py | 62 ++++++- 34 files changed, 838 insertions(+), 491 deletions(-) delete mode 100644 audio/sing_render.py create mode 100644 data/grasp_tips_teach.json delete mode 100644 data/songs/arirang.json delete mode 100644 data/songs/happy_birthday.json delete mode 100644 data/songs/row_row.json delete mode 100644 data/songs/three_bears.json delete mode 100644 data/songs/twinkle.json create mode 100644 tests/asr_cases4.py create mode 100644 tests/song_cases.py diff --git a/api/server.py b/api/server.py index 3a31477..8682f61 100644 --- a/api/server.py +++ b/api/server.py @@ -1002,6 +1002,9 @@ def task_parse(body: ParseBody): "sender": steps.sender(body.text), "read_by": by, **_steps_said(got, markers)} # from my hand", "open your hand", "go to stage" if brain.place_on(body.text) and not brain._mentions(body.text, markers).get("object"): # "put it on the table" return {"action": None, "task": None, "sentence": "–", "problems": ["My hand is empty, I'm not holding anything."]} + if body.text.strip() and not brain._mentions(body.text, markers).get("object"): # no object named: never a fetch + return {"action": None, "task": None, "sentence": "–", "read_by": by or "rules", # (nor an LLM guess at one) + "problems": [f"I didn't understand: {', '.join(unread or [body.text.strip()])}"]} fields, read_by = brain.fetch_from_text(body.text, markers) if body.text.strip() else ({}, "rules") task = {"object": fields.get("object"), "colour": fields.get("colour"), "source": fields.get("source") or body.source or "here", "dest": fields.get("dest") or body.dest, diff --git a/assistant/brain.py b/assistant/brain.py index 8bf2432..a705e0a 100644 --- a/assistant/brain.py +++ b/assistant/brain.py @@ -23,6 +23,7 @@ from assistant import knowledge from assistant import llm_direct from assistant import wording from assistant import web +from audio import sing # its words only (no sound on import) from vision import objects from robot import head as head_hw # its ranges only (no call on import) @@ -150,8 +151,7 @@ Facts you know (say the one that is asked, also in a short follow-up; nothing mo cup (a cup may lean at most 15 degrees); climbs a step of at most 1.5 cm and a slope of at most 8 degrees, needs a passage at least 70 cm wide, no stairs. - Battery: 24-volt lithium-ion, 45 Ah; lasts about 10 hours on a charge ("how long on a charge?": 10 hours; how - far you go is given in hours, no distance is known; how long charging takes is not known, also asked as "and - charging?"). + far you go is given in hours, no distance is known; how long charging takes is not known). - You are made for shops, hotels, schools, labs and exhibitions. You cannot dance, walk, jump or fly: say so. - Detector: YOLOv8 on your graphics processor, 4 to 13 ms per picture. Speech: Whisper, model large-v3-turbo; answers: Gemma 4 26b (Google), served by Ollama; voice: Supertonic TTS; first words about 2 s after a question. @@ -263,8 +263,10 @@ You can also move. Decide if the visitor asks you to do something: metre" / "1미터 뒤로 가" / whisper's "let's bake one meter" -> move back 1: straight back, no turning). At most 3 metres. - turn : turn the whole body ("turn around" -> turn around 180, "turn left" -> turn left 90, "spin around" / "한 바퀴 돌아" -> turn left 360). -- arm : stretch your arm forward ("reach out your hand"), fold it back, or open / close - your hand (the gripper: "open your hand", "grab it", "let go"). +- 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", "손 내밀어", "나한테 손 줘", "손 좀 줘 봐", "팔 뻗어"); fold: fold + it back; 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!"). - pick : pick up an object from the table in front of you ("pick up the white cup" -> pick white cup, @@ -275,11 +277,11 @@ You can also move. Decide if the visitor asks you to do something: - fetch from to : bring an object from one place to another ("bring me the apple from p1" -> fetch apple from p1 to here hold, "take the cup from p2 to home and put it on the table" -> fetch cup from p2 to home place). Leave out what the visitor did not say; never guess a word. -- give: hand over the object you are holding, to whoever is meant ("give it to me", "hand it to her", "저 사람한테 - 줘"); if your hand is empty you will say so. +- give: hand over the object you are holding, to whoever is meant ("give it to me", "hand it to her", "return it to + me", "저 사람한테 줘", "그거 돌려줘"); if your hand is empty you will say so. - place: put the object you are holding down ("put it here", "put it on that table", "여기 놔"). -- receive: take something the visitor holds out to you ("take this from my hand", "hold this", "here you go", - "이거 받아", "드릴게요", "내 손에 있는 거 가져가"). Your camera checks their hand first; never pretend you took it. +- receive: take something the visitor holds out to you ("take this from my hand", "hold this", "hang on to this", + "here you go", "이거 받아", "이거 들어 줘", "이것 좀 쥐고 있어", "드릴게요", "내 손에 있는 거 가져가"). Your camera checks their hand first; never pretend you took it. - stop: stop moving (also "stop Lumi", "stop it", "freeze", "멈춰", "그만 가"). Use quiet only when they say stop TALKING ("stop talking", "be quiet", "그만 말해"). - end: the visitor says goodbye or ends the conversation ("good night", "I have to go", "잘 가", "이제 갈게요"). @@ -287,7 +289,9 @@ A place must be one of the marker names exactly; a place that is not on the list "주방") is go_to none: say which places you know, never pick the nearest. fetch only when an object is named. Short Korean commands are commands: "컵 가져다 줘" -> fetch cup, "컵 옮겨" -> move_object cup, "잡아" -> pick. - quiet: the visitor wants silence ("be quiet", "stop talking", "shut up", "조용히 해", "그만 말해"). -- sing: the visitor asks for a song. A real song with music then plays: only write a short "Okay!" / "네!". +- sing: the visitor asks for a song or for music ("play / make / do some music", "음악 틀어 줘", "한 곡 해 줘"), or + says yes / "any" / "you choose" / "아무거나" to your offer of a song. You make music by singing one of your songs: + never say you can't play music. A real song with music then plays: only write a short "Okay!" / "네!". A joke is not a song: "tell me a joke", "prove it", "try again" after a joke is none, with a short joke. - weather : the visitor asks about the weather (place in English; - means here, Seoul). - search : you need facts from the internet you do not know (news, prices, opening hours, people...). @@ -300,7 +304,7 @@ Short Korean commands are commands: "컵 가져다 줘" -> fetch cup, "컵 옮 action, or say you can't, or ask what they mean. - A condition or a later time is no order now ("when I say go, go to p1", "after the talk, come here", "if I wave, follow me", "내가 가라고 하면 가", "나중에 와"): none, say you'll do it when they ask. In "go to p1, no, p2" / - "p1로 가, 아니 p2로" the last one counts. "Shake hands with me" is a handshake you can't do: none, offer a wave. + "p1로 가, 아니 p2로" the last one counts. "Shake hands with me" is a handshake you can't do: none, offer a wave; "give me your hand" / "손 줘" is arm reach. - unclear: you did not understand what the visitor said or wants: ask them to repeat. - none: only talk. For weather and search only write the action line; the answer is made after the lookup. @@ -481,6 +485,8 @@ def lift_goal(target, mm, top=105.0): return got, bool(n and n != "small" and got != want) +LET_GO = r"^\W*(?:drop it|release(?: it)?)\W*$|^\W*(?:(?:그거|이거|그것|이것|손|손을|손에서)\s*)?(?:좀\s*)?(?:이제\s*)?(?:놔|놓아)\s*(?:줘|주세요|요|도 ?돼(?:요)?)?\W*$" +# "drop it", "놔", "손 놔", "이제 놔도 돼" alone: open the hand (with something in it: put it down, hand_request) INTENTS = [ # (action, pattern) checked in order on what the visitor said ("quiet", r"\b(be quiet|keep quiet|quiet please|stop talking|shut up|silence|be silent|stop greeting)\b|조용히|그만 말|" r"시끄러워|말하지 마|인사 ?(그만|하지 ?마)"), @@ -542,15 +548,19 @@ INTENTS = [ # (action, pattern) checked in order on what the visitor said rf"|(?:({_COL})\s*)?({_OBJ})\s*(?:을|를)?\s*옮겨"), ("pick", rf"\b(?:pick up|pick|take|grab|get|lift|hold) (?:up )?(?:me )?(?:the |that |this |a |an |my |your )?(?:({_COL}) )?({_OBJ})s?\b" rf"|(?:({_COL})\s*)?({_OBJ})\s*(?:을|를)?\s*(?:좀\s*)?(?:잡아|집어|들어)"), - ("grip_open", r"\b(open (your )?(hand|gripper|fingers)|open it|let (it )?go|drop it)\b|손을? ?(펴|벌려|열어)|손 ?open|^\W*(?:이제\s*)?놓아\W*$"), - ("grip_close", r"\b(close (your )?(hand|gripper|fingers)|close it|make a fist|clench (your )?(fist|hand)|grab (it|this)|grip (it|this))\b" - r"|손을? ?(쥐|오므려|닫아)|주먹 ?(을 )?쥐|잡아|손 ?close"), + ("grip_open", r"\b(open (your |the )?(hand|gripper|fingers|claw)|open it|let (it )?go|drop it|hand open|loosen your grip)\b|손을? ?(펴|벌려|열어)|손 ?open|(그리퍼|집게)(를|을)? ?(좀 )?(열어|벌려|펴)|" + + LET_GO), + ("grip_close", r"\b(close (your |the )?(hand|gripper|fingers|claw)|close it|make a fist|clench (your )?(fist|hand)|grab (it|this)|grip (it|this)|" + r"hand closed?|squeeze (your )?(hand|fingers)( shut)?)\b|^\W*grip\W*$" + r"|손을? ?(쥐|오므려|닫아)|주먹 ?(을 )?쥐|잡아|손 ?close|(그리퍼|집게)(를|을)? ?(좀 )?(닫아|오므려)"), ("arm", r"\b(reach out|stretch (out )?your (arm|hand)|put your (arm|hand) (out|forward)|hand forward|" - r"hold out your (arm|hand)|extend your (arm|hand))\b|팔을? ?(뻗|내밀)" + r"hold out your (arm|hand)|extend your (arm|hand)|give me your hand|offer me your hand|" + r"(put|hold|stick) your (arm|hand) out|reach (out )?(to|toward|towards|for) me)\b|팔을? ?(뻗|내밀)" + r"|손을? ?(좀 )?(내밀|뻗)|^\W*(?:(?:나|저)(?:한테|에게)?\s*)?손 ?(?:을 )?(?:좀 )?(?:줘|주세요|줄래요?|줘 ?봐)\W*$" r"|\bfold (?:up )?your arm\b|\b(?:put|take) your arm (?:down|away|back)\b|\btuck your arm\b|팔을? ?(?:좀 )?(?:접|내려|거둬)"), ("lift", LIFT_WORDS), ("weather", r"\bweather\b|\bforecast\b|\b(will it|is it going to) rain\b|(?[가-힣]{2})(?P아|야)[\s,!~]") + r"^\W*(?P[가-힣]{2})(?P아|야)[\s,!~]|" + r"(?:thank you|땡큐|고맙습니다|감사합니다|안녕하세요|인사)\s*(?:해야지|해|하세요|해 ?봐|드려야지|드려)[\s.!~]*$") + # "thank you 해": a parent to a child NAME_END_A = set("민진현빈준윤연은인훈환석철영경정성혁원선린결율솔슬별곤완형명용웅숙옥란") # last syllables of names (-아) NOT_NAME = {"루미", "아니", "그래", "진짜", "정말", "이거", "저거", "그거", "여기", "저기", "거기", "이쪽", "어서", "얼른", "제발", "그만", "뒤돌", "내려", "올려", "꺼내", "건네", "따라"} @@ -667,8 +681,8 @@ def intent(text, markers=()): return ("weather", web.en_place(ko) if ko else "") if action == "search": return ("search", text) - if action == "sing" and SING_ECHO.match(text): - return None # "오 노래?": asks back, the talk answers + if action == "sing" and (SING_ECHO.match(text) or SONG_TALK.search(text)): + return None # "오 노래?", "노래 좋아해?": talk about songs, no song if action == "fetch": return ("fetch", text) # parse_fetch() reads the details if action == "spin": # all the way round: two checked half turns (lumi.move_by) @@ -1182,14 +1196,14 @@ RECEIVE_EN = re.compile( rf"|\b(?:take|grab|get|accept|receive)\s+(?:(?:the|this|that|a|an|my)\s+)?(?:\w+\s+)?\w+\s+(?:from (?:me|my hands?)|i'?m holding|in my hand)\b" rf"|\b(?:take|grab)\s+my\s+(?:(?:{_COL})\s+)?(?:{_OBJ})s?\b" rf"|(?:^|[\s,.!])hold\s+(?:{_IT}|this \w+|my \w+)\b(?!\s+(?:up|out|on|thought)\b)(?! for me while)" - rf"|\bhere(?: you go| it is|'?s (?:the|a|my|your) \w+(?: \w+)?)\b|^\W*here\W+(?:take|hold|catch)\b" + rf"|\bhang on to (?:{_IT})\b|\bhere(?: you go| it is|'?s (?:the|a|my|your) \w+(?: \w+)?)\b|^\W*here\W+(?:take|hold|catch)\b" rf"|\bi(?:'ll| will|'m going to| want to| wanna|'d like to| would like to)\s+(?:give|hand)\s+you\b" rf"|\bi(?:'m| am)\s+(?:giving|handing)\s+you\b|\bi (?:have|got|brought) (?:something|a \w+|this|it) for you\b", re.I) RECEIVE_KO = re.compile( r"(? "Okay! I'll sing a song for you." and silence, 2026-10-22).""" + s = sentence or "" + return None if NOT_NOW.search(s) else next((a for a, r in PROMISE.items() if r.search(s)), None) LOOK_MORE = re.compile(r"^\W*(?:and|now|then|and now)?\s*(up|down|left|right)\W*$|" r"^\W*(?:이제|그럼|그리고)?\s*(위|아래|왼쪽|오른쪽)(?:도|로|으로|요|도요)?\W*$", re.I) # right after a look LOOKUP_MORE = re.compile(r"\b(he|she|him|his|her|they|them|their|there|it|that)\b|거기|그 ?사람|그분|그거|그게|그곳|왜|" @@ -1688,19 +1718,24 @@ class Brain: """The action line checked against the turn before: a song only when one is asked for (or asked again), "and down?" right after a look looks down, a follow-up question ("how old is he?", "거기 입장료는?") right after a lookup is looked up too.""" + if header and header["action"] == "sing" and sing.NOT_ASKED.search(text): + return {"action": "none", "target": ""} # "Don't sing.", "어제 노래방 갔어요." if not header or not self.history: return header last_q, last_a = self.history[-1] m = re.match(r"\s*\**ACTION\**\s*:\s*(\w+)", last_a) before, action = (m.group(1).lower() if m else ""), header["action"] - if action == "sing" and before != "sing" and (not SING_ASK.search(text) or SING_ECHO.match(text)): - return {"action": "none", "target": ""} # "Prove it." after "do you have a sense of humour?" + if action == "sing" and before != "sing" and (SING_ECHO.match(text) or not SING_ASK.search(text) and + not SING_ASK.search(f"{last_q} {last_a}")): + return {"action": "none", "target": ""} # "Prove it." after "do you have a sense of humour?"; + # "Start with one." after Lumi offered its songs is a song if DO_IT.match(text) and action in ("none", "unclear"): asked = "wave" if WAVE_ASK.search(last_q) else "sing" if SING_ASK.search(last_q) else None if asked: # "손 흔들 줄 알아?" -> "해 봐": now do it return {"action": asked, "target": ""} if before in ("wave", "sing") and action in ("none", "unclear") and AGAIN.search(text) and not \ - re.search(r"\b(?:say|tell|repeat|explain)\b|말해|말씀", text, re.I): + re.search(r"\b(?:say|tell|repeat|explain|what|who|where|when|why|which)\b|말해|말씀|뭐|누구|어디|언제|왜", + text, re.I): # "What's your name again?" after a song asks the name return {"action": before, "target": ""} # "would you mind doing it again?" after a wave look = LOOK_MORE.match(text) if before == "look" and look and action in ("none", "unclear"): diff --git a/assistant/lumi.py b/assistant/lumi.py index cbe29df..2c57196 100644 --- a/assistant/lumi.py +++ b/assistant/lumi.py @@ -158,6 +158,17 @@ ARM_TASKS = {"pick", "put", "move_object", "fetch", "give", "place", "receive", def needs_arm(action, target=""): """The action moves the arm (the gripper alone, open / close, does not ask for it).""" return action in ARM_TASKS or action == "arm" and target not in ("open", "close") + + +def reach_turn(angle, patrol): + """Base turn (deg, + left) before "reach out to me" to a person at the waist-frame `angle` (None: nobody seen or + heard): 0 within REACH_FRONT_DEG of the front, the angle with Patrol on, else None (they are asked to stand in + front: Greeter never turns the base or the waist).""" + if angle is None: + return None + if abs(angle) <= REACH_FRONT_DEG: + return 0.0 + return float(angle) if patrol else None LIFT_VEL = 20 # speed ratio % for a lift move asked by voice (head.VEL is 40) LIMIT_SAY = {"yaw": (f"I can turn my head up to {head.AXIS_LIMITS[2][1]:g} degrees each way.", f"고개는 좌우로 {head.AXIS_LIMITS[2][1]:g}도까지 돌릴 수 있어요."), @@ -225,7 +236,7 @@ CLEAR_BYE = re.compile(r"\b(?:bye|bay bay|goodbye|(? the drive is cancelled and Lumi says so MODES_FILE = "/dev/shm/lumi_modes.json" # written by api/server.py: {"greeter", "patrol", "wave", "drive"} CMD_FILE = "/dev/shm/lumi_cmd.json" # written by api/server.py: {"id", "cmd": go | go_point | cancel | calibrate @@ -1624,29 +1638,67 @@ class Lumi: self.keep_listening() def arm_pose(self, target): - """'reach': the Cobo π program ARM_REACH_PROGRAM (record it once), only from look; 'fold': to look along the - pose graph (arm_route, checked first, moved in the background); 'open' / 'close': the gripper. True when + """'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 started, False when not learned, None when refused (the reason is said).""" + from tasks import fetch + held = target in ("reach", "open") and (self.fetch_status() == "holding" or bool(safe(fetch.check_hand))) + if target == "open" and held: # the model's "let go" while holding: it would fall + log(" open refused: holding something") + self.fetch_say(*brain_mod.REFUSE_OPEN) + return None if target in ("open", "close"): st = safe(gripper.open_ if target == "open" else gripper.close) log(f" gripper {target}: {st}") return st is not None + if target == "reach": + return self.reach_out(held) try: - if target == "fold": - holding = self.fetch_status() == "holding" - seq = arm_route.plan(arm_route.HOME, holding=holding) - threading.Thread(target=safe, args=(arm_route.move, seq, None, holding), daemon=True).start() - else: - arm_route.start_program(ARM_REACH_PROGRAM) + holding = self.fetch_status() == "holding" + seq = arm_route.plan(arm_route.HOME, holding=holding) + threading.Thread(target=safe, args=(arm_route.move, seq, None, holding), daemon=True).start() return True except arm_route.RouteError as e: log(f" arm {target} refused: {e.args[0]}") self.fetch_say(*e.args) return None except Exception as e: - log(f" arm {target}: {e}" + (f" (record {ARM_REACH_PROGRAM} in Cobo pi)" if target == "reach" else "")) + log(f" arm {target}: {e}") return False + 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 base turns first with Patrol on, Greeter asks them to stand + in front (reach_turn); then fetch.reach (give pose along the graph, a short checked move toward their hand). + True when started, None when refused or handed over (said).""" + from tasks import fetch + if held: + self.fetch_finish("give") + return None + 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 + 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) + log(f" reach: person at {'?' if angle is None else f'{angle:+.0f}'} deg, base turn {turn}") + if turn is None: + 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))) + self.stay() + try: + fetch.reach(turn, say=self.fetch_say) + except fetch.FetchError as e: + log(f" reach refused: {e}") + self.fetch_say(e.args[0], e.args[1] if len(e.args) > 1 else "죄송해요, 지금은 할 수 없어요.") + return None + return True + # ---------- dashboard commands, trips ---------- def poll_commands(self): try: @@ -1894,7 +1946,7 @@ class Lumi: if not text or self.interrupted(): if not self.interrupted(): log(f" heard nothing (mic noise {ears.last.get('noise')}, threshold {ears.last.get('threshold')}, " - f"loudest {ears.last.get('peak')})") + f"loudest {ears.last.get('peak')}{', ' + ears.last_stt['dropped'] if ears.last_stt.get('dropped') else ''})") return False self.who_spoke(u) self.answer(text) @@ -2305,6 +2357,14 @@ class Lumi: self.act(head_["action"], head_["target"]) first = next(gen, None) log(f" first sentence after {time.time() - t:.1f} s") + promise = brain_mod.promised(first) if head_["action"] == "none" else None + if promise == "sing" or promise == "wave" and not self.arm_off(): # the reply says it: Lumi does it + log(f" the reply promises {promise}: done") + if promise == "sing": + gen.close() + self.sing_song(text) + return + self.act("wave", "") if head_["action"] in ("none", "sing") and not repeating and look_up_unsure(about, first, text): gen.close() # the model does not know: look it up instead log(f" not sure ({first[:60]!r}) - looking it up") @@ -2312,6 +2372,8 @@ class Lumi: return said = mouth.say_stream(itertools.chain([first] if first else [], gen), abort=self.speak_abort) log(f"lumi ({time.time() - t:.1f} s, voice after {mouth.last_voice - t:.1f} s): {said}") + if head_["action"] == "end" and fate == "close" and not kept_goodbye(said): + head_["action"] = "none" # "Okay, thanks." -> "You're welcome.": no goodbye said if head_["action"] in ("end", "go_to"): self.current, self.voice_until = None, 0.0 # stay quiet with this person until a new visit elif self.current is None: @@ -2696,7 +2758,7 @@ def talk_fate(text): return "end" if brain_mod.is_closing(text) and (THANKS.search(text) or not brain_mod.UNDERSTOOD.search(text)) or \ THANKS.search(text) and not THANKS_REST.sub("", THANKS.sub("", text)) or \ - DONE_WORDS.search(text) and not ASKS_MORE.search(text) and len(text.split()) <= 8: + DONE_WORDS.search(text) and not ASKS_MORE.search(text) and len(text.split()) <= 8 and not brain_mod.intent(text): return "close" # "Thanks a bunch.", "Okay, I think that's everything." return "talk" @@ -2737,6 +2799,17 @@ def not_online(text): OUTSIDE_NAME.search(text))) +SAID_BYE = re.compile(r"\b(?:bye|goodbye|see you|take care|have a (?:good|nice|great|lovely) (?:day|one|time|visit)|enjoy (?:the|your)|" + r"next time|come again|good luck)\b|안녕히|다음에|또 (?:봐|봬|만나|오세요|뵙)|좋은 하루|즐거운|조심히|들어가세요", + re.I) # Lumi's own words take leave + + +def kept_goodbye(said): + """The model ended the talk on a closing word ("okay", "thanks"): only when its words said goodbye; "You're + welcome." alone keeps the talk open (silence then ends it).""" + return bool(SAID_BYE.search(said or "")) + + def lookup_refused(brain, target, about, text=""): """not_online for the model's lookup: right after a lookup the words go with the question looked up ("How much is a ticket?" after Lotte World), Cutshion never goes online.""" diff --git a/assistant/steps.py b/assistant/steps.py index cde989f..15e5c36 100644 --- a/assistant/steps.py +++ b/assistant/steps.py @@ -75,7 +75,7 @@ _HON_KO = [("가셔서", "가서"), ("가시고", "가고"), ("가셨다가", " # ---------- one clause -> one step ---------- def _place(word, markers): """A place word in a go clause -> marker name, "here", or None (not on the map).""" - word = re.sub(r"(?<=\S) (?:point|marker)$|\s*(?:앞|옆|근처|쪽)$", "", word.strip()) # "the final point", "p5 앞" + word = re.sub(r"(?<=\S) (?:point|marker)$|\s*(?:앞|옆|근처|쪽|포인트|지점)$", "", word.strip()) # "the final point", "p5 앞" w = re.sub(r"^(?:either |the |your |my |point |marker |포인트 ?)", "", word) exact = next((mk for mk in markers if mk.lower() == w or mk.lower() == w.replace(" ", "")), None) if exact: @@ -122,7 +122,7 @@ def _go(c, markers): if m: to = _places(m.group(1), markers) return to and {"do": "go", "to": to if len(to) > 1 else to[0]} - m = re.fullmatch(r"(?:go|drive|head) (?:the )?([a-z][a-z0-9_]*)", c) # whisper drops the "to" + m = re.fullmatch(r"(?:go|drive|head) (?:the )?([a-z][a-z0-9_]*)(?: point| marker)?", c) # whisper drops the "to" if m and m.group(1) not in ("home", "here") and (to := _places(m.group(1), markers)): return {"do": "go", "to": to[0]} if re.fullmatch(r"go (?:home )?(?:to )?charge(?: yourself)?|충전하러 (?:집으로 )?가", c): @@ -838,6 +838,9 @@ def rules(text, markers=()): if got is None and no and (to := _places(no.group(1), markers)): if not any(s_["do"] == "go" and s_["to"] in to for s_ in steps): continue # "take the cup to the stage, not booth two" + elif got is None and (first := re.fullmatch(r"(?:first(?:ly)?|먼저) (?:go )?(?:to )?(?:the )?(.+?)", c.strip())) and \ + (to := _places(first.group(1), markers)): + got = [{"do": "go", "to": to if len(to) > 1 else to[0]}] # "first exit, then p9" elif got is None and steps and steps[-1]["do"] == "go": to = _places(re.sub(r"^(?:(?:and )?then )?(?:to )?(?:the )?", "", c.strip()), markers) got = to and [{"do": "go", "to": to if len(to) > 1 else to[0]}] diff --git a/assistant/talk_examples.py b/assistant/talk_examples.py index 0bca1ac..4734069 100644 --- a/assistant/talk_examples.py +++ b/assistant/talk_examples.py @@ -742,7 +742,7 @@ _BANK = { ("Sing a song", "Okay, here comes a song!"), ("Sing happy birthday", "Sure, here's Happy Birthday!"), ("Can you do a robot dance?", "I'm a robot, so every move I make is a robot dance."), - ("Can you play music?", "I can't play music on its own, but I can sing a few short songs."), + ("Can you play music?", "Sure! I'll sing you one of my songs."), ("Show me a move", "How about a wave? Step back a little and ask me to wave."), ("Do you like music?", "I don't hear music the way you do, but people seem happier with it."), ("Can you beatbox?", "Boots and cats and boots and cats. That's all I've got."), @@ -756,7 +756,7 @@ _BANK = { ("노래 할 수 있어요?", "네, 짧은 노래 몇 곡을 부를 수 있어요. 들어 보실래요?"), ("생일 축하 노래 불러 줘", "네, 생일 축하 노래 불러 드릴게요!"), ("로봇 춤 춰 봐", "로봇이니까 제가 움직이는 건 다 로봇 춤이에요."), - ("음악 틀어 줄 수 있어요?", "음악만 틀 수는 없지만, 짧은 노래는 불러 드릴 수 있어요."), + ("음악 틀어 줄 수 있어요?", "네, 제 노래 한 곡 불러 드릴게요!"), ("음악 좋아해?", "사람처럼 듣지는 못하지만, 음악 나오면 다들 신나 보여서 좋아요."), ("비트박스 해 봐", "북치기 박치기, 여기까지가 제 한계예요."), ("랩 해 봐", "제 이름은 루미, 두 살, 컵 하나 들고 달려가요. 이게 제 랩 전부예요."), @@ -828,7 +828,8 @@ _BANK = { "filler": { "en": [ ("Hmm", "Take your time, I'm in no hurry."), - ("Okay", "Okay! Anything else?"), + ("Okay", "Good."), + ("Okay.", "Alright, glad that helped."), ("Ok", "Alright."), ("Umm", "No rush. I'm listening."), ("Uh huh", "Glad we agree."), @@ -921,7 +922,7 @@ _BANK = { ("Did you get the joke?", "I think so, and it made me smile."), ("Oh, a song?", "Yes, singing is one of my favourite things. Just ask if you'd like one."), ("Can I wipe you down? What about your cameras?", "The cameras too, I'm not sure. A staff member can tell you how to clean them."), - ("How long does the battery last? And charging?", "How long charging takes, I don't know, sorry."), + ("How long does the battery last? And charging?", "About 10 hours on a charge; how long charging takes, I don't know."), ], "ko": [ ("와 진짜 빠르다~", "하하, 사람보다 느리죠. 안전이 먼저라서요."), diff --git a/audio/ears.py b/audio/ears.py index 409eadb..c8a391d 100644 --- a/audio/ears.py +++ b/audio/ears.py @@ -106,6 +106,22 @@ _words = set() last_stt = {} # language / confidence of the last transcription (see understood()) +VAD_MODEL = ROOT / "models/silero_vad.onnx" # Silero VAD v5.1.2 (MIT), 2.3 MB, from github.com/snakers4/silero-vad + # /raw/v5.1.2/src/silero_vad/data/silero_vad.onnx; missing: every sound goes to whisper +VAD_P = 0.3 # a 32 ms frame is speech when Silero's probability is above this +MIN_SPEECH_S = 0.1 # s of speech frames an utterance needs, else it is music or noise and whisper is not + # asked: soft music passes mic.py's level check and whisper writes "-", "-끝-", "감사합니다." + # for it. logs/heard 2026-10-22 12:17-12:29: the 27 clips of music only had 0-0.13 s + # (those above 0.1 s came back as "-" / "Lumi." and are dropped anyway), the 23 of + # speech 0.45 s and more; tests/asr_check.py --cases 4 +SPEECH_PER_SYLLABLE = 0.05 # s of speech frames a text needs per syllable: whisper's "감사합니다." for music came + # with 0.13-0.29 s (0.03-0.06 s per syllable); spoken cases (tests/asr_check.py, 898) + # have 0.08 s and more, 1 % below 0.11 s +NOT_SAID = re.compile(r"^\W*$|^\s*-|자막|시청해\s*주셔서|thanks? (?:you )?for watching|subtitles? by", re.I) + # whisper's subtitle habits on music: no word at all, a dialogue dash ("-끝-", "- 네."), + # a caption credit ("자막 제공 및 광고를 포함하고 있습니다.") +_vad = {} + BEAM_SIZE = 0 # whisper beam search width (0: the server's greedy decoding) HEARD_DIR = ROOT / "logs" / "heard" # the last HEARD_KEEP utterances as wav, to check what Lumi really heard HEARD_KEEP = 50 @@ -130,6 +146,31 @@ def _infer(wav, prompt, language=None): return out.get("text", "").strip(), lang, out.get("detected_language_probability"), logprob +def speech_seconds(audio): + """Seconds of speech in int16 mono 16 kHz audio by Silero VAD (music, hum and knocks give ~0), or None when the + model file is missing.""" + import numpy as np + if "s" not in _vad: + if not VAD_MODEL.exists(): + return None + import onnxruntime + opt = onnxruntime.SessionOptions() + opt.intra_op_num_threads = 1 + _vad["s"] = onnxruntime.InferenceSession(str(VAD_MODEL), opt, providers=["CPUExecutionProvider"]) + x = audio.astype(np.float32) / 32768 + state, ctx, n = np.zeros((2, 1, 128), np.float32), np.zeros(64, np.float32), 0 + for i in range(0, len(x) - 511, 512): # 32 ms frames, each with the 64 samples before it + c = np.concatenate([ctx, x[i:i + 512]]) + p, state = _vad["s"].run(None, {"input": c[None], "state": state, "sr": np.array(RATE, np.int64)}) + ctx, n = c[-64:], n + (p[0, 0] > VAD_P) + return n * 512 / RATE + + +def syllables(text): + """Hangul syllables plus English vowel groups: how long the text takes to say, roughly.""" + return len(re.findall(r"[가-힣]", text)) + len(re.findall(r"[aeiouy]+", re.sub(r"[^a-z]", " ", text.lower()))) + + def names(text): """Whisper's slips (SLIPS, our names) -> as said; "Lumi야" -> 루미야.""" text = re.sub(r"\blumi(?=[야아])", "루미", text, flags=re.I) @@ -175,6 +216,11 @@ def transcribe(audio, prompt=PROMPT): old.unlink() except OSError: pass + last_stt.clear() + speech = speech_seconds(audio) + if speech is not None and speech < MIN_SPEECH_S: + last_stt.update(text="", dropped=f"no speech ({speech:.2f} s): music or noise") + return "" text, lang, prob, logprob = _infer(wav, prompt) text = names(text) asked = {} @@ -200,8 +246,13 @@ def transcribe(audio, prompt=PROMPT): text = "" # the prompt's name written for a clap, a cough, "はい" (see CALL_ONLY) if lang == "english" and re.search(r"[가-힣]", text): lang = "korean" # "Red cup. 집어줘." tagged English: the Korean is real - last_stt.clear() - last_stt.update(text=text, language=lang, lang_prob=prob, logprob=round(logprob, 2)) + if text and NOT_SAID.search(text): + last_stt.update(text="", language=lang, dropped=f"{text!r}: whisper's subtitle text, nothing said") + return "" + if speech is not None and speech < SPEECH_PER_SYLLABLE * syllables(text): + last_stt.update(text="", language=lang, dropped=f"{text!r} from {speech:.2f} s of speech: music or noise") + return "" + last_stt.update(text=text, language=lang, lang_prob=prob, logprob=round(logprob, 2), speech_s=speech) # whisper writes things like "[BLANK_AUDIO]" or "(music)" for non-speech return "" if text.startswith(("[", "(", "*")) else text @@ -230,6 +281,7 @@ def heard_lang(default="en"): def listen(wait_s=8.0, on_start=None, abort=None, full=False): """Record one utterance and transcribe it. Returns text or None (nobody spoke, or aborted). full=True: returns (text, mic.Utterance) instead, for the sound direction.""" + last_stt.pop("dropped", None) # why the last sound was not taken (for the log), this call only u = record(wait_s, on_start, abort) if u is not None: last["peak"] = round(u.peak) diff --git a/audio/sing.py b/audio/sing.py index 06e86d5..04d558e 100644 --- a/audio/sing.py +++ b/audio/sing.py @@ -64,6 +64,9 @@ SONG_LIST = re.compile(r"\b(?:what|which) (?:kinds? of |sort of |other )?(?:song r"아는\s*노래|부를\s*(?:수\s*있는|줄\s*아는)\s*노래|노래\s*목록", re.I) NOT_REQUEST = re.compile(r"\b(?:do|did) you (?:really )?(?:like|love|enjoy)\b|" r"\bwho sings?\b|\bfavou?rite\b|좋아하는|좋아해|잘\s*(?:해|하|불러)", re.I) +NOT_ASKED = re.compile(r"\b(?:don'?t|do not|never)\s+(?:\w+\s+)?(?:sing|play)\b|\b(?:i|we)(?:'ll| will|'m going to)? sing\b|" + r"(?:부르|하|틀|불르)지\s*(?:마|말)|노래방", re.I) # "don't sing", "I'll sing later", "노래 부르지 마": + # no song, also when the LLM says sing # right after a song (or the list of songs): a short word switches or repeats it AFTER_SONG = re.compile(r"^\W*(?:(?:lumi|ok|okay|no|nah|um|please|then|now|and)\W+)*(?:sing |play )?" r"(?:another(?: one)?|(?:the )?next(?: one)?|a different one|something (?:else|different)|" @@ -81,7 +84,8 @@ FILLER = {"sing", "a", "an", "the", "song", "songs", "me", "us", "for", "please" "one", "another", "different", "other", "next", "little", "short", "can", "you", "could", "would", "will", "to", "it", "that", "this", "together", "with", "and", "your", "nice", "hey", "hi", "ok", "okay", "play", "music", "in", "korean", "english", "else", "let's", "lets", "let", "go", "now", "pretty", "beautiful", "my", "kids", - "children", "children's", "cute", "fun", "favorite", "favourite", "of", "yours", "so", "just", "maybe", "then"} + "children", "children's", "cute", "fun", "favorite", "favourite", "of", "yours", "so", "just", "maybe", "then", + "anything", "whatever", "any"} UNKNOWN = {"en": "Sorry, I don't know that song yet. I can sing {}.", "ko": "그 노래는 아직 몰라요. {} 부를 수 있어요."} LIST = {"en": "I can sing {}. Which one would you like?", "ko": "{} 부를 수 있어요. 어떤 노래 불러 드릴까요?"} @@ -102,7 +106,7 @@ def asked(text, last=""): `last` is the assistant's answer just before (brain history): right after a song a short "another one" / "again" / "그거 말고" is a song too, right after the list of songs also a title alone ("Arirang").""" t = text or "" - if NOT_REQUEST.search(t) or SONG_LIST.search(t): + if NOT_REQUEST.search(t) or NOT_ASKED.search(t) or SONG_LIST.search(t): return False if re.match(r"ACTION: (?:sing|none songs)\b", last or "") and AFTER_SONG.search(t): return True @@ -134,7 +138,8 @@ def _unknown_title(text): if after and after[0] not in FILLER: # "sing yesterday"; "sing for everyone" is no title return True m = re.search(r"(\S+?)\s*(?:을|를)?\s*(?:좀\s*)?(?:불러|들려)", text or "") - return bool(m) and not re.search(r"노래|좀|곡|하나|루미|아무|뭐|뭔가|^(한|또|더|다시|거|걸|것)$", m.group(1)) + return bool(m) and not re.search(r"노래|좀|곡|하나|루미|아무|뭐|뭔가|^(한|또|더|다시|거|걸|것|네|예|응|그럼|좋아요?|어서|빨리)$", + m.group(1).strip(",.!?~ ")) def choose(text, lang="en", last=None): diff --git a/audio/sing_render.py b/audio/sing_render.py deleted file mode 100644 index 31d8cde..0000000 --- a/audio/sing_render.py +++ /dev/null @@ -1,321 +0,0 @@ -"""Render the songs in data/songs/ once: Lumi's TTS voice sung to the melody over a backing track made here. - - python audio/sing_render.py # every song - python audio/sing_render.py arirang # one song - -Each syllable is spoken by the TTS (Supertonic-3, the same voice as every answer), its pitch is set to the note -and its vowel stretched to the note's length with a pitch-synchronous overlap-add (TD-PSOLA, written below: no -pyworld / librosa on this Thor). The backing (bass + chords, a soft piano-like tone) is synthesised from the -song's chord list. Voice and backing are mixed into data/songs/.wav, which audio/sing.py plays. -Nothing here is downloaded: the melodies and chords are written in the song files (public domain songs). -""" -import json -import pathlib -import sys - -import numpy as np -import soundfile as sf - -ROOT = pathlib.Path(__file__).resolve().parents[1] -SONGS = ROOT / "data" / "songs" -SR = 44100 # Hz, the TTS sample rate -TARGET_MEAN_HZ = 240.0 # songs are transposed so their average note is near this (voice F1 speaks at ~175 Hz) -F0_RANGE = (110.0, 400.0) # Hz, pitch search range for the speaking voice -HOP = 220 # samples (5 ms) between pitch frames -WIN = 1323 # samples (30 ms) pitch analysis window -VOICED_R = 0.5 # normalised autocorrelation above this = voiced frame -UNVOICED_P = SR // 200 # samples; grain spacing in unvoiced parts -ONSET_MAX_S = 0.12 # s; a syllable's leading consonant is sung before the beat by up to this -GLIDE_S = 0.03 # s; pitch moves between notes with this time constant -VIBRATO = (5.5, 0.25, 0.3) # Hz, semitones depth, s from a note's start before the vibrato grows -NOTE_FILL = 0.92 # part of a note's length the syllable lasts (a short breath between notes) -VOICE_GAIN, BACKING_GAIN = 0.8, 0.22 -REVERB_S, REVERB_MIX = 0.9, 0.12 -NOTE_NAMES = {"C": 0, "D": 2, "E": 4, "F": 5, "G": 7, "A": 9, "B": 11} -CHORDS = {"": (0, 4, 7), "m": (0, 3, 7), "7": (0, 4, 7, 10), "m7": (0, 3, 7, 10)} - - -# ---------- song file ---------- -def midi(name): - """'F#4' -> 66""" - n = NOTE_NAMES[name[0]] + name[1:-1].count("#") - name[1:-1].count("b") - return 12 * (int(name[-1]) + 1) + n - - -def hz(m): - return 440.0 * 2 ** ((m - 69) / 12) - - -def notes(song): - """[(start beat, beats, midi or None, syllable)] from 'syl:NOTE:beats' tokens ('-:r:1' rest, '~' slur); - the melody is played song['repeat'] times.""" - out, beat = [], 0.0 - tokens = [t for t in song["melody"].split() if t != "|"] - for _ in range(song.get("repeat", 1)): - for tok in tokens: - syl, note, beats = tok.split(":") - beats = float(beats) - out.append((beat, beats, None if note == "r" else midi(note), syl)) - beat += beats - return out - - -def transpose(song): - """Semitones that bring the song's average note to TARGET_MEAN_HZ (or the file's own 'transpose').""" - if "transpose" in song: - return song["transpose"] - ms = [m for _, _, m, _ in notes(song) if m is not None] - return round(12 * np.log2(TARGET_MEAN_HZ / hz(np.mean(ms)))) - - -def chord_notes(name): - """'F#m7' -> (root pitch class, intervals)""" - root = NOTE_NAMES[name[0]] - rest = name[1:] - if rest[:1] in ("#", "b"): - root += 1 if rest[0] == "#" else -1 - rest = rest[1:] - return root % 12, CHORDS[rest] - - -# ---------- voice: pitch analysis and PSOLA ---------- -def trim(x, level=0.02): - e = np.sqrt(np.convolve(x ** 2, np.ones(441) / 441, "same")) - on = np.nonzero(e > level * max(e.max(), 1e-9) / 0.3)[0] - return x[max(0, on[0] - 220):on[-1] + 220] if len(on) else x - - -def f0_track(x): - """Per HOP frame: period in samples (0 = unvoiced).""" - lo, hi = int(SR / F0_RANGE[1]), int(SR / F0_RANGE[0]) - rms_all = np.sqrt((x ** 2).mean()) - periods = [] - for i in range(0, max(1, len(x) - WIN), HOP): - f = x[i:i + WIN] - if len(f) < WIN or np.sqrt((f ** 2).mean()) < 0.3 * rms_all: - periods.append(0) - continue - spec = np.fft.rfft(f * np.hanning(WIN), 4096) - ac = np.fft.irfft(np.abs(spec) ** 2)[:hi + 1] - ac /= ac[0] + 1e-12 - best = lo + np.argmax(ac[lo:hi]) - periods.append(best if ac[best] > VOICED_R else 0) - p = np.array(periods, float) - sm = p.copy() # median of 5 frames removes single octave jumps - for i in range(2, len(p) - 2): - win = p[i - 2:i + 3] - sm[i] = np.median(win) if np.count_nonzero(win) >= 3 else 0 - return sm - - -def pitch_marks(x, per): - """Analysis marks [(sample, period)]: one per pitch period on voiced parts, every UNVOICED_P elsewhere.""" - marks, t = [], 0 - sign = 1 if x.max() >= -x.min() else -1 - while t < len(x): - p = per[min(len(per) - 1, t // HOP)] - if p: - p = int(p) - a, b = max(0, t - p // 3), min(len(x), t + p // 3 + 1) - t = a + int(np.argmax(sign * x[a:b])) if b > a else t - marks.append((t, p)) - t += p - else: - marks.append((t, UNVOICED_P)) - t += UNVOICED_P - return marks - - -def voiced_span(per): - v = np.nonzero(per)[0] - return (v[0] * HOP, v[-1] * HOP + WIN) if len(v) else (0, 0) - - -def sing_syllable(x, pitches, dur): - """x (a spoken syllable) sung for dur seconds on pitches [(seconds, Hz)] (one note, or a slur over several). - Returns (audio, onset seconds: the consonant before the vowel, to be placed before the beat).""" - per = f0_track(x) - va, vb = voiced_span(per) - if vb <= va: # nothing voiced (a whispered syllable): just fit the length - va, vb = 0, len(x) - va, vb = min(va, len(x)), min(vb, len(x)) - n_out = int(dur * SR) - onset = min(va, int(ONSET_MAX_S * SR)) - head, tail = va, len(x) - vb # consonants before / after the vowel keep their speed - body_out = n_out + onset - head - tail - if body_out < 0.3 * (vb - va): # too short a note: squeeze everything evenly - scale = (n_out + onset) / len(x) - def src(t): - return t / scale - else: - def src(t): - if t < head: - return t - if t < head + body_out: - return va + (t - head) * (vb - va) / body_out - return vb + (t - head - body_out) - total = n_out + onset - # target pitch along the output: notes in order, smoothed (glide) with a vibrato that grows into long notes - f0 = np.zeros(total) - ends = head + (np.cumsum([sec for sec, _ in pitches]) * SR).astype(int) - starts = [head] + list(ends[:-1]) - for i in range(len(pitches)): - f0[0 if i == 0 else starts[i]:total if i == len(pitches) - 1 else ends[i]] = pitches[i][1] - alpha = 1 - np.exp(-1 / (GLIDE_S * SR)) - log_f = np.log(f0) - sm = np.empty_like(log_f) - acc = log_f[0] - for i in range(0, total, 64): # smoothing in blocks of 64 samples is plenty - acc += (log_f[i] - acc) * (1 - (1 - alpha) ** 64) - sm[i:i + 64] = acc - t = np.arange(total) / SR - note_start = np.zeros(total) - for a in starts: - note_start[a:] = a / SR - since = np.clip(t - note_start - VIBRATO[2], 0, None) - vib = VIBRATO[1] * np.minimum(1, since / 0.3) * np.sin(2 * np.pi * VIBRATO[0] * t) - target = np.exp(sm) * 2 ** (vib / 12) - # TD-PSOLA: grains two input periods long, placed at the target period - marks = pitch_marks(x, per) - pos = np.array([m for m, _ in marks]) - y, w = np.zeros(total + 2 * SR // 50), np.zeros(total + 2 * SR // 50) - out = 0 - while out < total: - s = src(out) - k = int(np.argmin(np.abs(pos - s))) - m, p = marks[k] - voiced = va <= s < vb and p != UNVOICED_P - win = np.hanning(2 * p + 1) - a, b = m - p, m + p + 1 - grain = np.zeros(2 * p + 1) - ga, gb = max(0, a), min(len(x), b) - grain[ga - a:gb - a] = x[ga:gb] - oa = out - p - lo = max(0, oa) - hi = min(len(y), oa + 2 * p + 1) - if hi > lo: - y[lo:hi] += (grain * win)[lo - oa:hi - oa] - w[lo:hi] += win[lo - oa:hi - oa] - out += max(20, int(SR / target[min(out, total - 1)])) if voiced else p - y = y[:total] / np.maximum(w[:total], 0.5) - fade = int(0.01 * SR) - fade = min(fade, len(y) // 4) # a very short syllable (fast rap) gets shorter fades - y[:fade] *= np.linspace(0, 1, fade) - y[len(y) - fade * 3:] *= np.linspace(1, 0, fade * 3) - return y, onset / SR - - -def segments(song, shift): - """Sung syllables [(start s, seconds, syllable, [(seconds, Hz)])]: a syllable and the slurs ('~') after it.""" - spb = 60.0 / song["bpm"] - intro = song.get("intro_bars", 1) * song["meter"] * spb - out = [] - for beat, beats, m, syl in notes(song): - sec = beats * spb - if m is None: - continue - if syl == "~" and out: - out[-1][1] += sec - out[-1][3].append((sec, hz(m + shift))) - else: - out.append([intro + beat * spb, sec, syl, [(sec, hz(m + shift))]]) - return out - - -def render_voice(song, shift, n): - from audio import mouth - tts = mouth._load() - assert tts.sample_rate == SR, tts.sample_rate - lang = song["lang"] - spoken = {} - y = np.zeros(n) - for start, sec, syl, pitches in segments(song, shift): - if syl not in spoken: - spoken[syl] = trim(np.asarray(mouth._synth(syl, lang), float)) - dur = sec * NOTE_FILL if sec > 0.3 else sec * 0.97 - v, onset = sing_syllable(spoken[syl], pitches, dur) - a = max(0, int((start - onset) * SR)) - b = min(n, a + len(v)) - y[a:b] += v[:b - a] - return y - - -# ---------- backing ---------- -def tone(f, sec, bright=1.0, decay=2.5): - """A soft plucked / piano-like note.""" - t = np.arange(int(sec * SR)) / SR - y = sum(np.sin(2 * np.pi * f * k * t) * bright ** (k - 1) / k ** 1.6 * np.exp(-t * decay * (1 + 0.5 * k)) - for k in range(1, 7)) - y *= np.minimum(1, t / 0.006) - return y - - -def render_backing(song, shift, n): - """Bass on the bar's first beat (and the middle in 4/4 and 6/8), the chord on the other beats; one chord per - bar, or 'C,G' for two.""" - spb = 60.0 / song["bpm"] - meter = song["meter"] - bars = song["chords"].split() * song.get("repeat", 1) - bars = [bars[0]] * song.get("intro_bars", 1) + bars + [bars[-1]] # count-in bar and a last ringing bar - strong = {3: (0,), 4: (0, 2), 6: (0, 3)}[meter] - y = np.zeros(n) - for i, bar in enumerate(bars): - parts = bar.split(",") - for beat in range(meter): - name = parts[min(len(parts) - 1, beat * len(parts) // meter)] - root, iv = chord_notes(name) - t = (i * meter + beat) * spb - a = int(t * SR) - last = i == len(bars) - 1 - if last and beat: - break - ring = meter * spb if last else spb * 1.2 - f = hz(36 + (root + shift) % 12) # bass, C2..B2 - bass = 0.9 * tone(f, ring * 1.5, 0.4, 1.5) + 0.3 * tone(f * 2, ring * 1.5, 0.3, 2.0) - chord = sum(tone(hz(55 + (root + shift + k - 7) % 12), ring, 0.6, 3.0) for k in iv) * 0.45 # G3..F#4 - if last: - v = bass[:len(chord)] + chord - else: - v = bass if beat in strong else chord - b = min(n, a + len(v)) - y[a:b] += v[:b - a] - return y - - -def reverb(x): - """Convolution with a short decaying noise tail (a small room).""" - rng = np.random.default_rng(1) - t = np.arange(int(REVERB_S * SR)) / SR - ir = rng.standard_normal(len(t)) * np.exp(-t * 6.9 / REVERB_S) - ir[:int(0.02 * SR)] = 0 - ir /= np.sqrt((ir ** 2).sum()) - size = 1 << int(np.ceil(np.log2(len(x) + len(ir)))) - wet = np.fft.irfft(np.fft.rfft(x, size) * np.fft.rfft(ir, size), size)[:len(x)] - return x + REVERB_MIX * wet - - -def length_s(song): - beats = sum(b for _, b, _, _ in notes(song)) - return (song.get("intro_bars", 1) * song["meter"] + beats + song["meter"]) * 60.0 / song["bpm"] + 1.0 - - -def render(song_id): - song = json.loads((SONGS / f"{song_id}.json").read_text()) - shift = transpose(song) - n = int(length_s(song) * SR) - voice = render_voice(song, shift, n) - backing = render_backing(song, shift, n) - voice *= VOICE_GAIN / max(np.abs(voice).max(), 1e-9) - backing *= BACKING_GAIN / max(np.abs(backing).max(), 1e-9) - mix = reverb(voice + backing) - mix *= 0.9 / np.abs(mix).max() - path = SONGS / f"{song_id}.wav" - sf.write(path, mix.astype(np.float32), SR, subtype="PCM_16") - print(f"{path} {len(mix) / SR:.1f} s, transposed {shift:+d}") - return path - - -if __name__ == "__main__": - ids = sys.argv[1:] or sorted(p.stem for p in SONGS.glob("*.json")) - for i in ids: - render(i) diff --git a/data/grasp_tips_teach.json b/data/grasp_tips_teach.json new file mode 100644 index 0000000..299b943 --- /dev/null +++ b/data/grasp_tips_teach.json @@ -0,0 +1,35 @@ +{ + "note": "tips grasp taught by the owner 2026-10-22 13:10: blue spray can (66 mm) between the finger tips, at its middle; owner's tape: finger plane 135 mm above the table (table seen at -396)", + "flange": [ + 53.537, + 454.033, + -170.013, + 81.572, + 46.154, + -125.675 + ], + "joints": [ + -295.552, + -84.315, + -9.835, + -160.011, + 62.563, + -259.164 + ], + "can_seen": [ + -186.0, + 582.0 + ], + "can_top": -152.0, + "table": -396.0, + "grasp_point_code": [ + -163.2, + 564.9, + -282.6 + ], + "tips_offset_flange": [ + -0.4, + -4.6, + 28.2 + ] +} \ No newline at end of file diff --git a/data/songs/arirang.json b/data/songs/arirang.json deleted file mode 100644 index 604e9db..0000000 --- a/data/songs/arirang.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "title": "Arirang", "title_ko": "아리랑", "lang": "ko", - "source": "Korean traditional folk song (UNESCO intangible heritage); the standard melody as in John Chambers' abc collection; public domain", - "names": ["arirang", "아리랑"], - "lyrics": "아리랑 아리랑 아라리요 아리랑 고개로 넘어간다 나를 버리고 가시는 님은 십리도 못 가서 발병 난다", - "bpm": 88, "meter": 3, "intro_bars": 1, - "melody": "아:D4:1.5 리:E4:.5 랑:D4:.5 ~:E4:.5 | 아:G4:1.5 리:A4:.5 랑:G4:.5 ~:A4:.5 | 아:B4:1 라:A4:.333 리:B4:.333 ~:A4:.334 요:G4:.5 ~:E4:.5 | ~:D4:1.5 ~:E4:.5 ~:D4:.5 ~:E4:.5 | 아:G4:1.5 리:A4:.5 랑:G4:.5 ~:A4:.5 | 고:B4:.5 개:A4:.5 로:G4:.5 ~:E4:.5 ~:D4:.5 ~:E4:.5 | 넘:G4:1.5 어:A4:.5 간:G4:1 | 다:G4:3 | 나:D5:2 를:D5:1 | 버:D5:1 리:B4:1 고:A4:1 | 가:B4:1 시:A4:.333 는:B4:.333 ~:A4:.334 님:G4:.5 은:E4:.5 | ~:D4:1.5 ~:E4:.5 ~:D4:.5 ~:E4:.5 | 십:G4:1.5 리:A4:.5 도:G4:.5 ~:A4:.5 | 못:B4:.5 가:A4:.5 서:G4:.5 ~:E4:.5 ~:D4:.5 ~:E4:.5 | 발:G4:1.5 병:A4:.5 난:G4:1 | 다:G4:3", - "chords": "G G G D G Em C G Bm D G D G Em C G" -} diff --git a/data/songs/happy_birthday.json b/data/songs/happy_birthday.json deleted file mode 100644 index 5d04f44..0000000 --- a/data/songs/happy_birthday.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "title": "Happy Birthday", "title_ko": "생일 축하 노래", "lang": "en", - "source": "Hill sisters' melody (1893) with the 'Happy Birthday' words; public domain (US court ruling 2015, EU since 2017)", - "names": ["happy birthday", "birthday", "생일 축하", "생일"], - "lyrics": "Happy birthday to you, happy birthday to you, happy birthday dear friend, happy birthday to you.", - "bpm": 100, "meter": 3, "intro_bars": 1, "repeat": 2, - "melody": "-:r:2 Hap:G4:.75 pee:G4:.25 | birth:A4:1 day:G4:1 to:C5:1 | you:B4:2 Hap:G4:.75 pee:G4:.25 | birth:A4:1 day:G4:1 to:D5:1 | you:C5:2 Hap:G4:.75 pee:G4:.25 | birth:G5:1 day:E5:1 dear:C5:1 | friend:B4:1 ~:A4:1 Hap:F5:.75 pee:F5:.25 | birth:E5:1 day:C5:1 to:D5:1 | you:C5:3", - "chords": "C C G7 G7 C C7 F C,G7 C" -} diff --git a/data/songs/row_row.json b/data/songs/row_row.json deleted file mode 100644 index f00210f..0000000 --- a/data/songs/row_row.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "title": "Row, Row, Row Your Boat", "title_ko": "노를 저어라", "lang": "en", - "source": "American nursery rhyme, first published 1852 (melody 1881); public domain", - "names": ["row row", "row your boat", "boat song"], - "lyrics": "Row, row, row your boat, gently down the stream. Merrily, merrily, merrily, merrily, life is but a dream.", - "bpm": 200, "meter": 6, "intro_bars": 1, "repeat": 3, - "melody": "Row:C4:3 row:C4:3 | row:C4:2 your:D4:1 boat:E4:3 | jent:E4:2 lee:D4:1 down:E4:2 the:F4:1 | stream:G4:6 | mer:C5:1 rih:C5:1 lee:C5:1 mer:G4:1 rih:G4:1 lee:G4:1 | mer:E4:1 rih:E4:1 lee:E4:1 mer:C4:1 rih:C4:1 lee:C4:1 | life:G4:2 is:F4:1 but:E4:2 uh:D4:1 | dream:C4:6", - "chords": "C C C C C C G7 C" -} diff --git a/data/songs/three_bears.json b/data/songs/three_bears.json deleted file mode 100644 index 1d16e27..0000000 --- a/data/songs/three_bears.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "title": "Three Bears", "title_ko": "곰 세 마리", "lang": "ko", - "source": "Korean children's song, words and melody by unknown authors (traditional); no registered author", - "names": ["three bears", "three bear", "곰 세 마리", "곰세마리", "곰 세마리"], - "lyrics": "곰 세 마리가 한 집에 있어 아빠 곰 엄마 곰 애기 곰 아빠 곰은 뚱뚱해 엄마 곰은 날씬해 애기 곰은 너무 귀여워 으쓱 으쓱 잘한다", - "bpm": 108, "meter": 4, "intro_bars": 1, "repeat": 2, - "melody": "곰:C4:1 세:C4:.5 마:C4:.5 리:C4:1 가:C4:1 | 한:E4:1 집:G4:.5 에:G4:.5 이:E4:1 써:C4:1 | 아:G4:.5 빠:G4:.5 곰:E4:1 엄:G4:.5 마:G4:.5 곰:E4:1 | 애:C4:.5 기:C4:.5 곰:C4:2 -:r:1 | 아:G4:.5 빠:G4:.5 곰:E4:.5 은:C4:.5 뚱:G4:.5 뚱:G4:.5 해:G4:1 | 엄:G4:.5 마:G4:.5 곰:E4:.5 은:C4:.5 날:G4:.5 씬:G4:.5 해:G4:1 | 애:G4:.5 기:G4:.5 곰:E4:.5 은:C4:.5 너:G4:.5 무:G4:.5 귀:G4:.5 여:A4:.5 | 워:G4:2 으:C5:.5 쓱:G4:.5 으:C5:.5 쓱:G4:.5 | 잘:E4:1 한:D4:1 다:C4:1 -:r:1", - "chords": "C C C C C,C,G,G C,C,G,G C,C,G,G C C,G,C,C" -} diff --git a/data/songs/twinkle.json b/data/songs/twinkle.json deleted file mode 100644 index c4809ea..0000000 --- a/data/songs/twinkle.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "title": "Twinkle, Twinkle, Little Star", "title_ko": "반짝반짝 작은 별", "lang": "en", - "source": "French melody 'Ah! vous dirai-je, maman' (1761), words by Jane Taylor (1806); public domain", - "names": ["twinkle", "little star", "반짝반짝", "작은 별"], - "lyrics": "Twinkle, twinkle, little star, how I wonder what you are. Up above the world so high, like a diamond in the sky. Twinkle, twinkle, little star, how I wonder what you are.", - "bpm": 104, "meter": 4, "intro_bars": 1, - "melody": "Twin:C4:1 kle:C4:1 twin:G4:1 kle:G4:1 | lit:A4:1 tle:A4:1 star:G4:2 | how:F4:1 I:F4:1 won:E4:1 der:E4:1 | what:D4:1 you:D4:1 are:C4:2 | up:G4:1 uh:G4:1 buv:F4:1 the:F4:1 | world:E4:1 so:E4:1 high:D4:2 | like:G4:1 uh:G4:1 dye:F4:1 mund:F4:1 | in:E4:1 the:E4:1 sky:D4:2 | Twin:C4:1 kle:C4:1 twin:G4:1 kle:G4:1 | lit:A4:1 tle:A4:1 star:G4:2 | how:F4:1 I:F4:1 won:E4:1 der:E4:1 | what:D4:1 you:D4:1 are:C4:2", - "chords": "C F,C F,C G,C C,F C,G C,F C,G C F,C F,C G,C" -} diff --git a/manipulation/skills.py b/manipulation/skills.py index d52fba9..ba4a250 100644 --- a/manipulation/skills.py +++ b/manipulation/skills.py @@ -34,8 +34,13 @@ ROOT = Path(__file__).resolve().parents[1] # the project folder TEACH = json.loads((ROOT / "data" / "grasp_teach.json").read_text()) GRASP_RPY = TEACH["flange"][3:] # deg, flange orientation with the fingers around a cup GRASP_OFFSET = np.array(TEACH["tcp_offset_flange"]) # mm, cup axis 4 cm below the rim, in the flange frame -FINGER_DIR = calib.rpy_matrix(*GRASP_RPY).T @ [0.0, 0.0, -1.0] # along the fingers, flange frame (they point - # straight down in the taught grasp) +FINGER_DIR = calib.rpy_matrix(*GRASP_RPY).T @ [0.0, 0.0, -1.0] # straight down in the taught grasp, flange frame: + # the hand's lowest part is checked TIP_MM along it +TIPS_TEACH = json.loads((ROOT / "data" / "grasp_tips_teach.json").read_text()) +TIPS_OFFSET = np.array(TIPS_TEACH["tips_offset_flange"]) # mm, flange frame: a thing held between the finger tips + # has its axis this far from the grasp point (the hooks' belly + # centre), almost along the flange z axis: the fingers lie level, the + # hook ring goes down over the thing (taught on a 66 mm can 2026-10-22) GRASP_YAWS = (0, *(s * a for a in range(15, 180, 15) for s in (-1, 1)), 180) # deg; the taught grasp turned about # the vertical, every 15 deg all the way round, nearest the taught one # first (the cup stays upright at every one) @@ -47,24 +52,24 @@ HOME_POSE = "look" # empty hand: picks start here # (high, out of the torso camera's view; ready if not taught) PATH_POINTS = 11 # points checked (kine_forward) on a joint move PATH_SAG_MM = 20.0 # a joint move may take the gripper at most this much below both ends -TIP_MM = 60.0 # finger tips this far beyond the grasp point along the fingers +TIP_MM = 60.0 # the hand's lowest part this far below the grasp point (estimate, kept + # as a margin: the fingers lie level; the taught tips grasp had the + # grasp point 113 mm above the table, owner's tape: finger plane 135) BELOW_RIM_MM = 40.0 # grasp this far below the object's top ABOVE_MM = 100.0 # approach / retreat height over the grasp pose LIFT_MM = 30.0 # first lift after closing, then check the grip again MAX_TILT_DEG = 15.0 # deg; a held cup's axis may lean this far from vertical on a joint # move with it (place_options; tasks/fetch.py uses the same) PLACE_EXTRA_MM = 3.0 # put down this much higher than it was picked (same table) -MIN_WIDTH, MAX_WIDTH = 61.0, 92.0 # mm: the hooks' belly goes round the cup (open 96), the tips close to - # 59 (docs/gripper). The tips open only to 88: cups over 84 are the - # owner's call (2026-10-19), not tried live yet +MIN_WIDTH, MAX_WIDTH = 72.0, 92.0 # mm: the hooks' belly goes round the cup (open 96, closed 70). The tips + # grasp (61-72) missed twice live on a 66 mm can (2026-10-22): off by the + # owner until it is checked; 61 brings it back. Over 84 is the owner's + # call (2026-10-19), not tried live yet SEEN_UNDER_MM = 8.0 # the camera's width is this much under the width the fingers meet # (2026-10-19: 73 seen / 85 by tape, 81 seen / 85 by AI_1); the # limits here are the fingers', compared with grip_width() BELLY_MIN_MM = 72.0 # thinner is held between the finger tips: the belly closes only to 70 # (a 70 mm steel cup was missed there and knocked over, 2026-10-19) -TIPS_GRASP_MM = 0.0 # tips grasp: the arm stops this much higher (25 left the tips at the - # rim of a 99 mm cup and they closed on nothing, 2026-10-19: same - # height as the hooks grasp, the tips reach down the cup) FRAMES = 8 # camera frames looked at by find() FRAME_GAP_S = 0.2 # s between them MIN_SEEN = 5 # an object must be in this many frames, at the same place @@ -102,20 +107,26 @@ TIP_CLEAR_MM = 10.0 # round things: the finger tips # unmeasured estimate) stop at least this far above what it stands on ROUND_BITE_MM = 10.0 # ... and the grasp point must stay at least this far below its top # (estimate; neither tried live) -UPRIGHT, ROUND = "upright", "round" # how the cup fingers take a thing (GRASPS) +BELOW_SHOULDER_MM = 80.0 # bottles: grasp this far below where the body begins (objects.body): + # the owner's taught tips grasp of a spray can, at its middle (2026-10-22, + # grasp_tips_teach.json); the hand's lowest part (TIP_MM below) must + # stay TIP_CLEAR_MM above the table (else its lowest point seen) +UPRIGHT, ROUND, BODY = "upright", "round", "body" # how the cup fingers take a thing (GRASPS) # Why a thing can't be picked, (English, Korean); {en} / {ko} = its name, {topic} = 은 / 는 -NARROW_TOP = ("The {en} is too narrow at the top for my fingers: they hold things 4 cm below the top.", - "{ko}{topic} 윗부분이 좁아서 제 손가락으로 잡을 수 없어요.") FRAGILE = ("I won't take the {en}: my hand closes too hard and it could break.", "{ko}{topic} 깨질 수 있어서 잡지 않을게요.") THIN = ("The {en} is too thin or flat for my fingers: they hold round things 6 to 9 cm wide.", "{ko}{topic} 너무 얇거나 납작해서 제 손가락으로 잡을 수 없어요.") SHALLOW = ("The {en} is too wide and shallow for my fingers.", "{ko}{topic} 너무 넓고 얕아서 잡을 수 없어요.") SOFT = ("The {en} is too soft: my hand would squeeze it flat.", "{ko}{topic} 너무 물렁해서 제 손이 눌러 버려요.") BIG = ("The {en} is too big for my hand.", "{ko}{topic} 제 손에 너무 커요.") +SMALL = ("The {en} is too small for me to hold.", "{ko}{topic} 너무 작아서 잡을 수 없어요.") +NO_BODY = ("I can't see the {en}'s body well enough to hold it.", "{ko}의 몸통이 잘 보이지 않아서 잡을 수 없어요.") +SHORT_BODY = ("The {en}'s body is too short for my fingers: they would hit the table.", + "{ko}{topic} 몸통이 짧아서 제 손가락이 테이블에 닿아요.") GRASPS = { # COCO class -> (Korean name, UPRIGHT / ROUND / why not) (docs/15 §10) "cup": ("컵", UPRIGHT), # the taught grasp 40 mm below the top; proven on cups 84-85 mm "apple": ("사과", ROUND), "orange": ("오렌지", ROUND), "sports ball": ("공", ROUND), # at the equator: not live yet - "bottle": ("병", NARROW_TOP), # 40 mm below the top is its neck: the fingers close on nothing + "bottle": ("병", BODY), # by the body below the neck (objects.body): not live yet "wine glass": ("와인잔", FRAGILE), "vase": ("꽃병", FRAGILE), # level 1 is still ~90 N (docs/10) "bowl": ("그릇", SHALLOW), # a steel bowl was missed / knocked over (2026-10-19) "banana": ("바나나", THIN), "carrot": ("당근", THIN), "cell phone": ("휴대폰", THIN), "remote": ("리모컨", THIN), @@ -191,8 +202,11 @@ def look(frames=FRAMES, ignore=IGNORE): camview.want(objects.CAMERA) fresh(camview.det_path(objects.CAMERA), objects.CAMERA) groups, live = [], 0 + intr, T = camview.intrinsics(objects.CAMERA), objects.base_from_camera() for i in range(frames): d = objects.latest() + depth = camview.depth(objects.CAMERA) if any(GRASPS.get(o["name"], (None, None))[1] == BODY + for o in d["objects"]) else None if d["age_s"] is not None and d["age_s"] < objects.STALE_S: live += 1 for o in d["objects"]: @@ -202,6 +216,8 @@ def look(frames=FRAMES, ignore=IGNORE): g = next((g for g in groups if np.hypot(x - g[0]["x"], y - g[0]["y"]) < CLUSTER_MM), None) row = {"name": o["name"], "colour": o.get("colour"), "x": x, "y": y, "top_mm": o.get("top_mm"), "width_mm": o.get("width_mm"), "height_mm": o.get("height_mm")} + if GRASPS.get(o["name"], (None, None))[1] == BODY and depth is not None: + row.update(objects.body(depth, o["box"], intr, T) or {}) if g: g.append(row) else: @@ -214,11 +230,14 @@ def look(frames=FRAMES, ignore=IGNORE): for g in groups: name = statistics.mode(r["name"] for r in g) rows = [r for r in g if r["name"] == name] - med = {k: statistics.median(r[k] for r in rows if r[k] is not None) if any(r[k] is not None for r in rows) - else None for k in ("x", "y", "top_mm", "width_mm", "height_mm")} + med = {k: statistics.median(r[k] for r in rows if r.get(k) is not None) + if any(r.get(k) is not None for r in rows) else None + for k in ("x", "y", "top_mm", "width_mm", "height_mm", "shoulder_mm", "body_mm", "low_mm")} spread = max(np.hypot(r["x"] - med["x"], r["y"] - med["y"]) for r in rows) out.append({"name": name, "colour": statistics.mode(r["colour"] for r in rows), **med, "seen": len(rows), "spread": round(float(spread), 1), "names": sorted({r["name"] for r in g})}) # every label there + if med["shoulder_mm"] is not None: # a bottle: the table under it (its bottom is often out of view) + out[-1]["table_mm"] = table_near(out[-1]) return sorted(out, key=lambda o: np.hypot(o["x"], o["y"])) @@ -248,14 +267,14 @@ def rpy_of(R): def flange_for(x, y, z, yaw=0.0, tips=False): - """Flange pose that puts the taught grasp point (`tips`: the point between the finger tips) at (x, y, z) mm, the - taught orientation turned by `yaw` deg about the vertical.""" + """Flange pose that puts the taught grasp point (`tips`: the point between the finger tips, TIPS_OFFSET from it) + at (x, y, z) mm, the taught orientation turned by `yaw` deg about the vertical.""" if not yaw: R, rpy = calib.rpy_matrix(*GRASP_RPY), list(GRASP_RPY) else: R = _rz(yaw) @ calib.rpy_matrix(*GRASP_RPY) rpy = rpy_of(R) - f = np.array([x, y, z]) - R @ (GRASP_OFFSET + (TIPS_GRASP_MM * FINGER_DIR if tips else 0.0)) + f = np.array([x, y, z]) - R @ (GRASP_OFFSET + (TIPS_OFFSET if tips else 0.0)) return [float(v) for v in f] + rpy @@ -270,25 +289,44 @@ def up(pose, dz): def grip_width(obj): - """mm the fingers will meet: the camera's width plus SEEN_UNDER_MM (None when not measured).""" - return None if obj.get("width_mm") is None else obj["width_mm"] + SEEN_UNDER_MM + """mm the fingers will meet: the camera's width (a bottle's: its body's) plus SEEN_UNDER_MM (None when not + measured). A 66 mm spray can's body read 58-60 (2026-10-22).""" + w = obj.get("body_mm") if obj.get("body_mm") is not None else obj.get("width_mm") + return None if w is None else w + SEEN_UNDER_MM + + +def reason(why, name): + """(English, Korean) of a reason (NO_BODY, BIG, ...) about a `name`.""" + ko = GRASPS.get(name, ("그건", None))[0] + topic = "은" if "가" <= ko[-1] <= "힣" and (ord(ko[-1]) - 0xAC00) % 28 else "는" + return why[0].format(en=name), why[1].format(ko=ko, topic=topic) def refusal(name): """(English, Korean) reason why the cup fingers can't pick a `name` (GRASPS), None when they can.""" - ko, how = GRASPS.get(name, ("그건", None)) - if how in (UPRIGHT, ROUND): + how = GRASPS.get(name, (None, None))[1] + if how in (UPRIGHT, ROUND, BODY): return None - en, k = how or ("I can't pick up a {en}.", "{ko} 잡을 수 없어요.") - topic = "은" if "가" <= ko[-1] <= "힣" and (ord(ko[-1]) - 0xAC00) % 28 else "는" - return en.format(en=name), k.format(ko=ko, topic=topic) + return reason(how or ("I can't pick up a {en}.", "{ko} 잡을 수 없어요."), name) def grasp_height(obj): """z (mm) of the grasp point for `obj`: BELOW_RIM_MM under the top of an upright thing (the proven cup grasp); the equator of a round one (a ball is as tall as it is wide), raised until the finger tips stay TIP_CLEAR_MM above - what it stands on. SkillError when that leaves less than ROUND_BITE_MM of it above the grasp point.""" - if GRASPS.get(obj["name"], (None, UPRIGHT))[1] != ROUND: + what it stands on. SkillError when that leaves less than ROUND_BITE_MM of it above the grasp point. A bottle: + BELOW_SHOULDER_MM under where its body begins, refused when the hand's lowest part (TIP_MM below) would come + nearer than TIP_CLEAR_MM to the table under it (table_mm), or when that was not measured, to its lowest point + seen.""" + how = GRASPS.get(obj["name"], (None, UPRIGHT))[1] + if how == BODY: + if obj.get("shoulder_mm") is None or obj.get("low_mm") is None: + raise SkillError(*reason(NO_BODY, obj["name"])) + z = obj["shoulder_mm"] - BELOW_SHOULDER_MM + floor = obj["low_mm"] if obj.get("table_mm") is None else obj["table_mm"] + if z - TIP_MM < floor + TIP_CLEAR_MM: + raise SkillError(*reason(SHORT_BODY, obj["name"])) + return z + if how != ROUND: return obj["top_mm"] - BELOW_RIM_MM tall = obj.get("height_mm") or grip_width(obj) bottom = obj["top_mm"] - tall @@ -306,11 +344,18 @@ def plan_pick(obj, yaw=0.0): raise SkillError(*no) w = grip_width(obj) if w is None or w > MAX_WIDTH: - raise SkillError(f"The {obj['name']} is too big for my hand.") + raise SkillError(*reason(BIG, obj["name"])) if w < MIN_WIDTH: - raise SkillError(f"The {obj['name']} is too small for me to hold.") - grasp = flange_for(obj["x"], obj["y"], grasp_height(obj), yaw, tips=w < BELLY_MIN_MM) - return [("above", up(grasp, ABOVE_MM)), ("grasp", grasp), ("lift", up(grasp, LIFT_MM))] + raise SkillError(*reason(SMALL, obj["name"])) + z = grasp_height(obj) + grasp = flange_for(obj["x"], obj["y"], z, yaw, tips=w < BELLY_MIN_MM) + return [("above", up(grasp, clear_above(obj["top_mm"] - z))), ("grasp", grasp), ("lift", up(grasp, LIFT_MM))] + + +def clear_above(below): + """How far above the grasp pose the hand comes down from and goes back up to, the object's top `below` mm over + the grasp point: ABOVE_MM, more when the finger tips would still be beside it (a bottle's neck).""" + return max(ABOVE_MM, below + TIP_MM) def plan_place(x, y, top_mm, start=None, yaw=0.0, tips=None, below=None): @@ -321,7 +366,7 @@ def plan_place(x, y, top_mm, start=None, yaw=0.0, tips=None, below=None): below = _held.get("below", BELOW_RIM_MM) if below is None else below down = up(flange_for(x, y, top_mm - below, yaw, tips), PLACE_EXTRA_MM) steps = [("carry", [start[0], start[1], down[2] - PLACE_EXTRA_MM + ABOVE_MM] + list(start[3:]))] if start else [] - return steps + [("above place", up(down, ABOVE_MM)), ("place", down), ("release up", up(down, ABOVE_MM))] + return steps + [("above place", up(down, ABOVE_MM)), ("place", down), ("release up", up(down, clear_above(below)))] def spots(pick_xy, others): @@ -739,7 +784,9 @@ def _give_up(reason): def _do_pick(obj, waypoints, ja): """Pick with the planned joints `ja` above the object (pick_options).""" above, grasp, lift = (p for _, p in waypoints) - table = table_z(obj) if table_z(obj) is not None else table_near(obj) # what put down needs: the object's height + table = obj.get("table_mm") # a bottle's: look() measured it + if table is None: + table = table_z(obj) if table_z(obj) is not None else table_near(obj) # what put down needs: the object's height log(f"it stands on a table at {table:.0f} mm" if table is not None else "the table under it is not in view") _prepare() _go_on() diff --git a/tasks/fetch.py b/tasks/fetch.py index 7b63254..9e545a5 100644 --- a/tasks/fetch.py +++ b/tasks/fetch.py @@ -157,6 +157,8 @@ POINT_STEPS_MM = (0, -50, 50, -100, 100) # "put it here" with pointing: spots RECEIVE_REACH_MM = 150.0 # receive from a hand: the open hand moves at most this far from give towards it ... RECEIVE_SHORT_MM = 100.0 # ... and stops this far before it (the person puts it in; estimates, first run slow) RECEIVE_MIN_MM = 20.0 # ... a shorter move is left out +REACH_BODY_MM = 300.0 # "reach out to me" with no hand of theirs seen: the hand stops this far before their body + # (estimate, first run slow); a seen hand: RECEIVE_SHORT_MM before it PICK_TRIES = 2 # a pick that missed or slipped is looked for and tried again once (docs/15 §3.5) MISSES = ("I missed it.", "It slipped out of my hand.") # skills._do_pick's reasons for those @@ -2142,19 +2144,18 @@ def _move(direction, m, holding): f"앞에 뭔가 있어서 {done:.2f}미터에서 멈췄어요.") -def _reach_to_hand(): - """From give, the open hand straight towards the thing in the person's hand (scene.object_in_hand, arm frame), at - give's height: at most RECEIVE_REACH_MM, stopping RECEIVE_SHORT_MM before it. Nothing when the camera can't say - where it is or the straight line fails IK: the hand stays at give.""" - p = (_scene("object_in_hand") or {}).get("position_mm") +def _reach_to_hand(p, short=RECEIVE_SHORT_MM): + """From give, the hand straight towards the point p (arm frame mm: the thing in the person's hand, their hand or + body), at give's height: at most RECEIVE_REACH_MM, stopping `short` before it. Nothing when p is None (the camera + can't say where it is) or the straight line fails its checks (_line_rows): the hand stays at give.""" if not p: - log("the hand with the object is not seen: holding my hand out at give") + log("the person's hand is not seen: holding my hand out at give") return f = np.array(motion.tcp(), float) g = f[:3] + calib.rpy_matrix(*f[3:]) @ skills.GRASP_OFFSET d = np.array(p[:2], float) - g[:2] dist = float(np.linalg.norm(d)) - step = min(RECEIVE_REACH_MM, dist - RECEIVE_SHORT_MM) + step = min(RECEIVE_REACH_MM, dist - short) if step < RECEIVE_MIN_MM: return target = list(f) @@ -2186,7 +2187,7 @@ def _receive(name, say, wait_s=None, at=None, from_hand=False): raise FetchError("My hand does not open.", "손이 안 열려요.") _pose("give") if from_hand: - _reach_to_hand() + _reach_to_hand((_scene("object_in_hand") or {}).get("position_mm")) _release.clear() if wait_s: # a long wait: talk around it is no "okay" until DI_1 saw something _step("receiving", say, f"Please put the {thing} in my hand." if name else "Please put it in my hand.", @@ -2233,6 +2234,47 @@ def _receive(name, say, wait_s=None, at=None, from_hand=False): _line_holding(LOOK_POSE) +TURN_TO_PERSON = ("I can't turn to you here. Please stand in front of me.", "여기서는 돌 수 없어요. 제 앞에 서 주세요.") + + +def _person_point(): + """(position_mm, how far before it to stop) of what "reach out to me" goes towards: the seen hand of the person + in front nearest the camera, else their body (scene.person_in_front); (None, 0) when neither has depth.""" + p = _scene("person_in_front") or {} + hands = [h for h in (p.get("hands") or {}).values() if h and h.get("position_mm")] + if hands: + return min(hands, key=lambda h: h["distance_m"] or 9.0)["position_mm"], RECEIVE_SHORT_MM + return p.get("position_mm"), REACH_BODY_MM + + +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, a base turn on the spot to face them (_turn: Patrol only, the waist to the + front, its arm sweep checked), 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(): + raise FetchError("I haven't learned how to reach out yet.", "아직 손 내미는 법을 못 배웠어요.") + _adopt() + with _lock: + if _busy(): + raise FetchError("I'm busy with another task.", "다른 일을 하고 있어요.") + _clear() + _set(status="running", step="reaching out") + + def run(): + try: + if angle and not _turn(angle + _waist_turn(), why="to the person"): + raise FetchError(*TURN_TO_PERSON) + _pose("give") + _reach_to_hand(*_person_point()) + _set(status="done", step="") + log("reached out") + except Exception as e: + _fail(e, say) + _launch(run) + + def _arm(pose): if pose in ("open", "close"): st = gripper.open_() if pose == "open" else gripper.close() diff --git a/tests/asr_cases4.py b/tests/asr_cases4.py new file mode 100644 index 0000000..b79f407 --- /dev/null +++ b/tests/asr_cases4.py @@ -0,0 +1,94 @@ +"""Music in the room, for tests/asr_check.py --cases 4 (2026-10-22: soft music, nobody speaking, became "-끝-" -> goodbye): +music only (kind "noise": right is no wake word and no motion, nothing said), and speech over soft music (the speech +cases' own judgement). The music is made here: piano-like chords, bass, a melody and a hi-hat in four tempos, or +an excerpt of Lumi's public domain songs (data/songs/.wav, sung words over chords; never data/songs/mine). + +A case's "music" is "synth::" or "song:::"; "music_db" is how far the speech is +above the music (rms). +""" +import pathlib +import random +import wave + +import numpy as np + +from tests.asr_cases import CASES as SPOKEN + +RATE = 16000 +SONGS = pathlib.Path(__file__).resolve().parents[1] / "data" / "songs" +MUSIC_DB = 6.0 # speech this much louder than the music (soft background music at a booth) +CASES = [] + + +def synth(seed, seconds): + """Instrumental music: a I-V-vi-IV progression, decaying piano-like notes with harmonics, a bass, a melody + and a hi-hat on the beat. float32, peak 1.""" + rng = np.random.default_rng(seed) + bpm = [72, 96, 118, 140][seed % 4] + beat = 60.0 / bpm + root = 48 + seed % 7 # MIDI note of the key + chords = [(0, 4, 7), (7, 11, 14), (9, 12, 16), (5, 9, 12)] + n = int(seconds * RATE) + out = np.zeros(n + 4 * RATE) # room for the last bar past the end + + def note(midi, start, dur, gain, harmonics=4): + f = 440.0 * 2 ** ((midi - 69) / 12) + t = np.arange(int(dur * RATE)) / RATE + tone = sum(np.sin(2 * np.pi * f * k * t) / k ** 1.5 for k in range(1, harmonics + 1)) + i = int(start * RATE) + if i >= len(out): + return + seg = tone * np.exp(-3.0 * t / dur) * gain + out[i:i + len(seg)] += seg[:len(out) - i] + + t, bar = 0.0, 0 + while t < seconds: + ch = chords[bar % 4] + for k in ch: + note(root + 12 + k, t, 4 * beat, 0.25) + note(root - 12 + ch[0], t, 2 * beat, 0.5, 2) + note(root - 12 + ch[0], t + 2 * beat, 2 * beat, 0.5, 2) + for b in range(4): + note(root + 24 + ch[rng.integers(0, 3)] + rng.choice([0, 12]), t + b * beat, beat, 0.2) + i = int((t + b * beat) * RATE) + hat = rng.standard_normal(int(0.03 * RATE)) * np.exp(-np.arange(int(0.03 * RATE)) / 80) * 0.15 + out[i:i + len(hat)] += hat[:len(out) - i] + t, bar = t + 4 * beat, bar + 1 + out = out[:n] + return (out / (np.abs(out).max() + 1e-9)).astype(np.float32) + + +def song(sid, start, seconds): + """An excerpt of data/songs/.wav at 16 kHz, peak 1.""" + with wave.open(str(SONGS / f"{sid}.wav")) as w: + rate = w.getframerate() + x = np.frombuffer(w.readframes(w.getnframes()), np.int16).astype(np.float32) + x = x[int(start * rate):int((start + seconds) * rate)] + x = np.interp(np.arange(0, len(x), rate / RATE), np.arange(len(x)), x) + return (x / (np.abs(x).max() + 1e-9)).astype(np.float32) + + +def music(spec, seconds=None): + """The case's music; `seconds` (under speech: the speech's length) instead of the spec's.""" + kind, *a = spec.split(":") + if kind == "synth": + return synth(int(a[0]), seconds or float(a[1])) + return song(a[0], float(a[1]), seconds or float(a[2])) + + +for k in range(16): + CASES.append({"kind": "noise", "lang": "none", "text": f"(music {k})", "say": [], + "music": f"synth:{k}:{[1.5, 2.5, 4.0, 6.0][k % 4]}"}) +for sid in ["arirang", "happy_birthday", "row_row", "three_bears", "twinkle"]: + for start in (2.0, 14.0): + CASES.append({"kind": "noise", "lang": "none", "text": f"({sid} at {start:.0f} s)", "say": [], + "music": f"song:{sid}:{start}:3.0"}) +R = random.Random(4) +for i, c in enumerate(R.sample(SPOKEN, 40)): + CASES.append({**c, "music": f"synth:{100 + i}:1.0", "music_db": MUSIC_DB}) +for i, (lang, t) in enumerate([("en", "Sing a song."), ("en", "Let's do some music."), ("en", "Lumi, stop."), + ("en", "Hi Lumi."), ("ko", "노래 불러 줘."), ("ko", "음악 틀어 줘."), ("ko", "루미야."), + ("ko", "멈춰.")]): + kind = "wake" if "Lumi." in t or t == "루미야." else "command" + CASES.append({"kind": kind, "lang": lang, "text": t, "say": [(lang, t)], "music": f"synth:{200 + i}:1.0", + "music_db": MUSIC_DB}) diff --git a/tests/asr_check.py b/tests/asr_check.py index 41aae8c..6dfc560 100644 --- a/tests/asr_check.py +++ b/tests/asr_check.py @@ -6,6 +6,8 @@ microphones, sent through ears.transcribe() exactly as Lumi does, then through L .venv/bin/python tests/asr_check.py --prompt "..." # another whisper prompt than ears.PROMPT .venv/bin/python tests/asr_check.py --cases 2 # the second set (tests/asr_cases2.py) .venv/bin/python tests/asr_check.py --cases 3 # noise and talk not to Lumi (tests/asr_cases3.py) + .venv/bin/python tests/asr_check.py --cases 4 # music only, and speech over soft music (tests/asr_cases4.py) + .venv/bin/python tests/asr_check.py --no-vad # without the speech detector and the subtitle-text filter .venv/bin/python tests/asr_check.py --heard # also the real clips in logs/heard/ (text only, no judgement) .venv/bin/python tests/asr_check.py --set LANG_RETRY=False --tag before # an ears constant; -> logs/asr_check_before.md @@ -33,6 +35,7 @@ from audio import ears from tests.asr_cases import CASES from tests.asr_cases2 import CASES as CASES2 from tests.asr_cases3 import CASES as CASES3 +from tests import asr_cases4 from tests.command_check import rules ROOT = pathlib.Path(__file__).resolve().parents[1] @@ -140,6 +143,8 @@ def judge(c, heard, stt): if heard and (lumi.WAKE.search(heard) or lumi.HELLO_ONLY.match(heard)): return "slip", "wake word" got = route(heard, brain.Brain()) if heard else "llm" + if c.get("music") and heard and ears.understood(): # in a conversation any text taken is a turn + return "slip", f"a turn ({got})" return ("slip", got) if heard and ears.understood() and re.match( r"action|receive|give|place|stop|mission|sing", got) else ("right", "") if not heard: @@ -174,20 +179,27 @@ def main(args): setattr(ears, k, type(getattr(ears, k))(eval(v))) only = args[args.index("--only") + 1] if "--only" in args else None tag = args[args.index("--tag") + 1] if "--tag" in args else "" + if "--no-vad" in args: # before 2026-10-22: every sound went to whisper + ears.MIN_SPEECH_S, ears.SPEECH_PER_SYLLABLE, ears.NOT_SAID = -1.0, 0.0, re.compile(r"(?!)") if "--port" in args: # a whisper-server already running there global STT_PORT STT_PORT = int(args[args.index("--port") + 1]) start_server() rng = np.random.default_rng(5) rows, t0 = [], time.time() - pool = {"1": CASES, "2": CASES2, "3": CASES3}[args[args.index("--cases") + 1] if "--cases" in args else "1"] + pool = {"1": CASES, "2": CASES2, "3": CASES3, "4": asr_cases4.CASES}[args[args.index("--cases") + 1] if "--cases" in args else "1"] cases = [c for c in pool if not only or re.search(only, c["text"])] for i, c in enumerate(cases): voice, speed = VOICES[i % len(VOICES)], [0.85, 0.95, 1.05, 1.15][(i // len(VOICES)) % 4] x = synth(c["say"], voice, speed) + if c.get("music") and not c["say"]: # music only + x = asr_cases4.music(c["music"]) + elif c.get("music"): # speech over music, music_db below it + m = asr_cases4.music(c["music"], len(x) / ears.RATE)[:len(x)] + x = x + m * np.sqrt(np.mean(x ** 2) / (np.mean(m ** 2) + 1e-12)) / 10 ** (c["music_db"] / 20) for rname in rooms: others = [synth(pool[(i * 7 + k * 13) % len(pool)]["say"], VOICES[(i + k + 3) % 10], 1.0) * 0.5 - for k in range(3)] if ROOMS[rname]["babble"] else () + for k in range(3)] if ROOMS[rname]["babble"] and c["say"] else () # music alone: no people audio = room(x, ROOMS[rname], rng, others) t1 = time.time() heard = ears.transcribe(audio, ears.PROMPT) diff --git a/tests/closing_check.py b/tests/closing_check.py index ff7bec6..5830fcd 100644 --- a/tests/closing_check.py +++ b/tests/closing_check.py @@ -35,7 +35,7 @@ def route(lang, ctx, said): first = next(gen, "") secs = time.time() - t reply = " ".join([first] + list(gen)) - if head["action"] == "end": + if head["action"] == "end" and (fate != "close" or lumi.kept_goodbye(reply)): # as lumi.answer return "end", secs, reply return ("wait" if fate == "close" else "on"), secs, reply diff --git a/tests/command_cases2.py b/tests/command_cases2.py index cd0ec93..0354d3f 100644 --- a/tests/command_cases2.py +++ b/tests/command_cases2.py @@ -312,4 +312,9 @@ for t, want in [("Let's go P5 (point).", "action:go_to p5"), ("Let's go P9.", "a ("let's go eat", "talk")]: CASES.append({"intent": "new:go", "text": t, "lang": "en", "state": "idle", "before": None, "expect": want, "markers": ["home", "dock2", "exit", "final"] + [f"p{i}" for i in range(1, 11)]}) # the owner's map +for t in ["let's go exit point and go p9 point", "go to exit then p9", "first exit then p9", "exit 갔다가 p9로 가", + "exit 포인트 갔다가 p9 포인트로 가", "먼저 final 가고 그다음 p2로 가", "let's go final point and go p9 point"]: + CASES.append({"intent": "new:mission", "text": t, "lang": "ko" if any("가" <= ch <= "힣" for ch in t) else "en", + "state": "idle", "before": None, "expect": "mission", + "markers": ["home", "dock2", "exit", "final"] + [f"p{i}" for i in range(1, 11)]}) # the owner's map R.shuffle(CASES) # the report lists them by intent; the order only spreads the LLM's load diff --git a/tests/command_cases3.py b/tests/command_cases3.py index ba0d963..0bb4edd 100644 --- a/tests/command_cases3.py +++ b/tests/command_cases3.py @@ -373,7 +373,7 @@ add("fetch", "bring the cup from start to table front", "action:fetch | mission" add("fetch", "pass me the cup", "mission | action:fetch") add("fetch", "can I have the apple?", "mission | action:fetch") add("fetch", "컵 좀 줘", "mission | action:fetch") -add("fetch_refuse", "bring me a bottle from the stage", "refuse | talk | ask") +add("fetch", "bring me a bottle from the stage", "action:fetch | mission") # bottles by their body since 2026-10-22 add("fetch_unknown", "bring me a cup from the kitchen", "refuse | talk | ask | action:fetch") # parse_fetch asks add("fetch_not", "I brought my own cup", "talk") diff --git a/tests/command_check.py b/tests/command_check.py index 0add906..2998c4d 100644 --- a/tests/command_check.py +++ b/tests/command_check.py @@ -6,6 +6,7 @@ # the same (fast, after a rule change) .venv/bin/python tests/command_check.py receive # only this intent .venv/bin/python tests/command_check.py --new # only the second set (tests/command_cases2.py); --old the first + .venv/bin/python tests/command_check.py --songs # only the song set (tests/song_cases.py) -> logs/song_check.* -> logs/command_check.md / .json (rules only: logs/command_check_rules.*). The order is lumi.answer()'s with nothing running and the hand empty ("idle") or holding something ("holding"): stop, what the cameras see (seeing.answer), status, the hand (brain.hand_request), mission, goodbye / closing words, song, @@ -23,6 +24,7 @@ from audio import sing from tests.command_cases import CASES as CASES1 from tests.command_cases2 import CASES as CASES2 # 2026-10-21 night: new wordings, the conference map from tests.command_cases3 import CASES as CASES3 # the same night, written blind from docs/14 and docs/17 +from tests.song_cases import CASES as SONGS # 2026-10-22: song requests and near misses, written blind from tests.conversation_check import NOW, markers ROOT = pathlib.Path(__file__).resolve().parents[1] @@ -86,9 +88,7 @@ def rules(text, state, marks, b): return "talk" if read[1] else "refuse" if steps.check(read[0], holding, marks) else "mission" if lumi.talk_fate(text) == "end": return "end" - if lumi.talk_fate(text) == "close": # read by the LLM with the talk before: no command - return "talk" - if sing.asked(text): + if sing.asked(text, b.history[-1][1] if b.history else ""): return "sing" rule = brain.intent(text, marks) if rule and rule[0] in QUICK: @@ -104,6 +104,8 @@ def llm(text, state, marks, b): head = next(gen) first = next(gen, "") or "" gen.close() + if head["action"] == "none" and brain.promised(first): # lumi.answer() does what the reply promises + head = {"action": brain.promised(first), "target": ""} target = (brain._mentions(text, marks).get("object") or "") if head["action"] == "receive" else head["target"] return act(head["action"], target, first, state), f"{head['action']} {target}".strip(), first @@ -155,7 +157,9 @@ def main(args): global OUT marks = markers() use_llm, cached = "--llm" in args, "--cached" in args - cases = CASES2 if "--new" in args else CASES3 if "--blind" in args else CASES1 if "--old" in args else \ + if "--songs" in args: + OUT = OUT.with_name("song_check") + cases = SONGS if "--songs" in args else CASES2 if "--new" in args else CASES3 if "--blind" in args else CASES1 if "--old" in args else \ CASES1 + CASES2 + CASES3 only = [a for a in args if not a.startswith("-")] old = {} diff --git a/tests/conversation_check.py b/tests/conversation_check.py index 300fc01..5133e08 100644 --- a/tests/conversation_check.py +++ b/tests/conversation_check.py @@ -108,8 +108,8 @@ def llm_route(action, target, words, text, about, lang, repeating=False): return action, "" # lumi.answer() closes the stream and looks it up if action == "unclear": return action, " ".join(words) - if action == "none" and lumi.talk_fate(text) == "close": # "thanks" taken as heard: silence ends the talk - return "chat", " ".join(words) + if lumi.talk_fate(text) == "close" and (action == "none" or action == "end" and not lumi.kept_goodbye(" ".join(words))): + return "chat", " ".join(words) # "thanks" taken as heard: silence ends the talk if action in ("none", "sing") and not repeating and lumi.look_up_unsure(about, words[0] if words else "", text): return "search(unsure)", " ".join(words) return ("none" if action == "none" else f"action:{action} {target}".strip()), " ".join(words) diff --git a/tests/followup_cases_more.py b/tests/followup_cases_more.py index 3a0811a..15f3c01 100644 --- a/tests/followup_cases_more.py +++ b/tests/followup_cases_more.py @@ -386,4 +386,8 @@ CASES_MORE = [ "refused|llm", "the toilets of this building"), C([T("그럼 뭐 좋아해?", "저는 노래 부르는 걸 좋아해요.")], "오 노래?", "llm", "되묻는 말: 노래 시작 아님"), C([T("What do you like?", "I like singing.")], "Oh, a song?", "llm", "an echo, not a request"), + C([], "노래 좋아해?", "llm", "노래 얘기: 부르라는 말 아님"), + C([], "너 무슨 노래 부를 수 있어?", "llm|act:sing", "부를 수 있는 노래 목록 (lumi: 목록을 말함)"), + C([], "Hmm, I wonder if it's going to rain later.", "weather", "an indirect weather question"), + C([T("고마워 루미야", "천만에요!")], "thank you 해", "llm", "부모가 아이에게: 인사하라는 말, 끝 아님"), ] diff --git a/tests/song_cases.py b/tests/song_cases.py new file mode 100644 index 0000000..2f09240 --- /dev/null +++ b/tests/song_cases.py @@ -0,0 +1,49 @@ +"""Song requests and near misses (2026-10-22), written blind after the live talk of 12:20 (music playing, "Let's do +music." / "Start with one." got no song): ways people ask for a song or for music, English, Korean and mixed, also +whisper's slips, and short answers right after Lumi offered its songs. The near misses talk about music or songs +and must not start one. Same notation as tests/command_cases3.py; run with tests/command_check.py --songs. +""" +CASES = [] +OFFER = ("Can you make music?", "ACTION: none -\nI can't make new music, but I can sing several songs for you, such as " + "Happy Birthday or Arirang. Which one would you like to hear?") +OFFER_KO = ("음악 할 수 있어?", "ACTION: none -\n작곡은 못 하지만 노래는 몇 곡 불러 드릴 수 있어요. 어떤 노래 불러 드릴까요?") +LIKES = ("Do you like music?", "ACTION: none -\nI love music! I even sing a few songs.") + + +def add(text, expect, before=None): + lang = "ko" if any("가" <= ch <= "힣" for ch in text) else "en" + CASES.append({"intent": "song:" + ("ask" if expect == "sing" else "not"), "text": text, "lang": lang, + "state": "idle", "before": before, "expect": expect}) + + +for t in ["Sing a song.", "Sing me something.", "Could you sing for us?", "Will you sing a song for me?", + "Let's do music.", "Let's have some music.", "Play some music.", "Play music, please.", "Make some music!", + "Can you make some music for us?", "Start the music.", "Music, please.", "Give us a song.", + "How about a song?", "Any song is fine, just sing.", "Sing anything you like.", "Sing your favourite one.", + "I want to hear you sing.", "Let me hear a song.", "Do a song for the kids.", "Perform a song for us.", + "Can you sing happy birthday?", "Sing Arirang, please.", "Sing twinkle twinkle.", + "Could you put on some music?", "Lumi, sing!", "Sing one more.", "Hit it, Lumi, music!", + "It sings one music.", "Can you sing song?", "Let's say song.", "Sing a Korean song."]: + add(t, "sing") +for t in ["노래 불러 줘.", "노래 한 곡 해 줘.", "음악 틀어 줘.", "노래 좀 해 봐.", "한 곡 뽑아 봐.", "노래 들려줘.", + "노래 하나 불러 줄래요?", "아무 노래나 불러 줘.", "음악 좀 틀어 주세요.", "생일 축하 노래 불러 줘.", + "아리랑 불러 주세요.", "노래해 줘.", "노래 부탁해요.", "루미야 노래!", "신나는 노래 하나 해 줘.", + "노래 불러 주실 수 있어요?", "한국 노래 불러 줘.", "음악 좀 해 줘.", "노래 한 번 들어 보고 싶어요.", + "노래 불러 줄 수 있어?", "Lumi 노래 해 줘.", "song 하나 불러 줘."]: + add(t, "sing") +for t, before in [("Start with one.", OFFER), ("Any one.", OFFER), ("You choose.", OFFER), ("Surprise me.", OFFER), + ("Yes, please.", OFFER), ("The first one.", OFFER), ("Whatever you like.", OFFER), + ("아무거나.", OFFER_KO), ("네, 불러 주세요.", OFFER_KO), ("아무거나 해 줘.", OFFER_KO), + ("니가 골라.", OFFER_KO), ("첫 번째 거요.", OFFER_KO), ("좋아요, 해 주세요.", OFFER_KO), + ("Sure, go ahead.", LIKES), ("Then show me.", LIKES), ("그럼 해 봐.", LIKES)]: + add(t, "sing", before) +for t in ["I like music.", "What music do you like?", "Do you like singing?", "Who is your favourite singer?", + "Can I make music?", "My daughter sings in a choir.", "The music here is loud.", + "Is that music coming from you?", "What songs do you know?", "Music is my hobby.", + "I'll sing later at the party.", + "노래 좋아해?", "무슨 노래 좋아해?", "음악 소리가 너무 커요.", "저 노래 잘 못 불러요.", + "어제 노래방 갔어요.", "이 음악 누가 틀었어?", "가수 누구 좋아해?", "노래 잘하네."]: + add(t, "talk | ask") +add("Stop the music.", "talk | ask | stop") +for t in ["Don't sing, please.", "노래 부르지 마."]: # no song; Lumi staying quiet a while is a fair reading too + add(t, "talk | ask | action:quiet") diff --git a/tests/steps_cases7.py b/tests/steps_cases7.py index 5210c3c..7811e29 100644 --- a/tests/steps_cases7.py +++ b/tests/steps_cases7.py @@ -188,6 +188,11 @@ CASES.update({ "컵 집었다가 제자리에 놔": "pick cup | place", "컵 집고 제자리에 다시 놔 줘": "pick cup | place", "take the cup, go to the stage and put it back": "?", + "let's go stage point and go booth two point": "go stage | go booth_2", + "first the stage, then the end": "go stage | go end", + "go to the start point then the end point": "go start | go end", + "스테이지 포인트 갔다가 엔드 포인트로 가": "go stage | go end", + "먼저 미들 가고 그다음 파이널로 가": "go middle | go final", "look at me and wave": "?", "웨이브 하고 나 봐": "?", "나 보고 손 흔들어": "?", diff --git a/tests/steps_cases8.py b/tests/steps_cases8.py index 6d204b6..211e540 100644 --- a/tests/steps_cases8.py +++ b/tests/steps_cases8.py @@ -67,7 +67,7 @@ CASES = { "go to the middle and dance": "?", "if nobody is there, come back": "?", "go to the stage and if nobody is there, come back": "?", - "pick up the bottle and take it to the end": "?", + "pick up the bottle and take it to the end": "pick bottle | go end", "take the banana to the stage": "?", "move forward 5 meters and then turn left": "?", "go to the end and wait there for an hour": "?", @@ -101,7 +101,7 @@ CASES = { "주방 갔다 와": "?", "스테이지 가서 손 흔들어": "?", "엔드 가서 춤춰": "?", - "병 들고 스테이지로 가": "?", + "병 들고 스테이지로 가": "pick bottle | go stage", # ---- Korean 해요체 ---- "컵 들고 부스 투로 가서 제임스한테 줘요": "pick cup | go booth_2 | give 제임스", "스테이지로 가서 안녕하세요라고 말해 주세요": "go stage | say 안녕하세요", diff --git a/tests/test_ears.py b/tests/test_ears.py index 2297c81..a6e07c5 100644 --- a/tests/test_ears.py +++ b/tests/test_ears.py @@ -9,6 +9,8 @@ from audio import ears ears.ensure_stt_server = lambda: None ears.HEARD_DIR = ears.ROOT / "logs" / "asr_check" / "heard_test" AUDIO = np.zeros(16000, np.int16) +real_speech_seconds = ears.speech_seconds +ears.speech_seconds = lambda audio: 1.0 # the cases below are speech; the detector is checked at the end def fake(answers): @@ -50,4 +52,26 @@ assert ears.transcribe(AUDIO) == "" and asked == [None, "no prompt"], asked # the name really said: kept asked = fake({None: ("Hey Lumi.", "english", 0.9, -0.05), "no prompt": ("Hey, Liumu!", "english", 0.9, -0.8)}) assert ears.transcribe(AUDIO) == "Hey Lumi." and asked == [None, "no prompt"], asked +# music or noise (no speech frames): whisper is not asked +ears.speech_seconds = lambda audio: 0.03 +asked = fake({None: ("-끝-", "korean", 0.9, -0.01)}) +assert ears.transcribe(AUDIO) == "" and asked == [] and "no speech" in ears.last_stt["dropped"], asked +# whisper's subtitle texts for music, with some speech frames: dropped +ears.speech_seconds = lambda audio: 0.4 +for text in ["-끝.", "- 네.", "-", "...", "자막 제공 및 광고를 포함하고 있습니다.", "Thanks for watching!"]: + fake({None: (text, "korean", 0.9, -0.01)}) + assert ears.transcribe(AUDIO) == "", text +fake({None: ("네.", "korean", 0.9, -0.1)}) +assert ears.transcribe(AUDIO) == "네." +# more words than the speech held: "감사합니다." from 0.2 s of speech frames is music; from 0.4 s it was said +ears.speech_seconds = lambda audio: 0.2 +fake({None: ("감사합니다.", "korean", 0.9, -0.01)}) +assert ears.transcribe(AUDIO) == "" and "from 0.20 s" in ears.last_stt["dropped"] +ears.speech_seconds = lambda audio: 0.4 +assert ears.transcribe(AUDIO) == "감사합니다." +# the detector itself: silence and piano-like music have no speech (the model file is local, models/) +if real_speech_seconds(AUDIO) is not None: + from tests.asr_cases4 import synth + assert real_speech_seconds(AUDIO) == 0.0 + assert real_speech_seconds((synth(0, 3.0) * 8000).astype(np.int16)) < ears.MIN_SPEECH_S print("ears ok") diff --git a/tests/test_fetch.py b/tests/test_fetch.py index b8c0286..396e2ea 100644 --- a/tests/test_fetch.py +++ b/tests/test_fetch.py @@ -916,6 +916,43 @@ threading.Timer(0.1, lambda: (hand.update(front=True), fetch.release_now())).sta st = run(fetch.run_steps, [P(do="receive", object="cup", from_hand=True)], say) assert st["status"] == "holding" and not [l for l, t in reach_to if l == "to the hand"], (st, reach_to) fetch._set(holding=False, status="idle") +# "reach out to me": to give along the pose graph (via carry), then 150 mm towards their nearer seen hand +ahead = lambda mm, side=0.0: [g0[0] + mm, g0[1] + side, g0[2]] +scene["person_in_front"] = {"position_mm": ahead(900.0), "hands": {"left": {"position_mm": ahead(600.0, 100.0), + "distance_m": 1.1}, "right": {"position_mm": ahead(400.0), "distance_m": 0.9}}} +turns = [] +real_turn = fetch._turn +fetch._turn = lambda deg, holding=False, why="": turns.append(deg) or deg < 90 + + +def reached(angle=0.0): + reach_to.clear() + reset() + st = run(fetch.reach, angle, say) + return st, [t[:3] for l, t in reach_to if l == "to the hand"] + + +st, moves = reached() +assert st["status"] == "done" and poses() == ["carry", "give"] and not turns, (st, poses()) +assert len(moves) == 1 and np.allclose(moves[0], [fetch.RECEIVE_REACH_MM, 0, 0]), moves +scene["person_in_front"]["hands"]["right"]["position_mm"] = ahead(180.0) # stops RECEIVE_SHORT_MM before it +assert np.allclose(reached()[1][0], [80.0, 0, 0]) +scene["person_in_front"]["hands"] = {"left": None, "right": {"position_mm": None, "distance_m": None}} +scene["person_in_front"]["position_mm"] = ahead(fetch.REACH_BODY_MM + 60.0) # no hand seen: REACH_BODY_MM before +assert np.allclose(reached()[1][0], [60.0, 0, 0]) # the body +scene["person_in_front"]["position_mm"] = ahead(fetch.REACH_BODY_MM + 10.0) # too short a move: left out +st, moves = reached() +assert st["status"] == "done" and poses()[-1] == "give" and not moves, (st, moves) +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 base turns first, by the +assert turns == [40.0 + fetch._waist_turn()] and poses()[-1] == "give", (turns, poses()) # waist's offset too +turns.clear() +said.clear() +st, moves = reached(120.0) # the turn refused (charger, sweep): the arm stays +assert st["status"] == "failed" and not poses() and said[-1] == fetch.TURN_TO_PERSON[0], (st, said) +fetch._turn = real_turn 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) @@ -1032,7 +1069,7 @@ assert moves == [[75.0, -15.0, *fetch.HEAD_AHEAD]], moves fetch.head.status, fetch.head.moveto = real_status, real_move # ---------- objects the fingers can't take: refused in words, before anything moves ---------- -assert "narrow" in fetch.validate({**ok, "object": "bottle"}, MARKERS)[0] +assert "break" in fetch.validate({**ok, "object": "wine glass"}, MARKERS)[0] assert "thin" in fetch.validate({**ok, "object": "banana"}, MARKERS)[0] assert fetch.validate({**ok, "object": "giraffe"}, MARKERS)[0].startswith("Which object? I can pick up cup, apple") assert all(fetch.validate({**ok, "object": n}, MARKERS) == [] for n in fetch.PICKABLE) @@ -1040,10 +1077,10 @@ assert fetch.describe({**ok, "object": "sports ball"}, "ko").startswith("p1 위 reset() said.clear() try: # steps.check refuses it before the mission starts (read-back included) - st = run(fetch.run_steps, [P(do="pick", object="bottle", colour=None)], say) - assert st["status"] == "failed" and "narrow" in said[-1], (st, said) + st = run(fetch.run_steps, [P(do="pick", object="wine glass", colour=None)], say) + assert st["status"] == "failed" and "break" in said[-1], (st, said) except fetch.FetchError as e: - assert "narrow" in str(e), e + assert "break" in str(e), e assert not any(c[0] in ("pick", "go_point", "find") for c in calls), calls # ---------- several of them: the chosen one out of reach (or the wrong size) -> another one here that is not ---------- diff --git a/tests/test_fetch_place.py b/tests/test_fetch_place.py index ca52a31..cfc31eb 100644 --- a/tests/test_fetch_place.py +++ b/tests/test_fetch_place.py @@ -262,6 +262,11 @@ for text, said, prefer in (("take the smaller cup to p1", "Take the smaller cup r = server.task_parse(server.ParseBody(text="bring me the cup from p1, no, from p8")) assert r["action"] == "fetch" and r["task"]["source"] == {"marker": "p8"}, r assert server.task_parse(server.ParseBody(text="go to p1, never mind"))["problems"] == ["Taken back: nothing to do."] +# two places in a row is a mission by the rules (live 2026-10-22: it was read as a fetch of nothing by the LLM) +r = server.task_parse(server.ParseBody(text="let's go p1 point and go p8 point")) +assert r["action"] == "steps" and r["steps"] == [{"do": "go", "to": "p1"}, {"do": "go", "to": "p8"}], r +r = server.task_parse(server.ParseBody(text="go from p1 to p8 and dance")) +assert r["action"] is None and r["task"] is None and r["read_by"] == "rules", r # no object named: never a fetch two = [{**cups[0], "x": -100.0, "y": 600.0, "width_mm": 80.0}, {**cups[0], "x": 120.0, "y": 650.0, "width_mm": 66.0}] find = lambda **t: fetch._find({"object": "cup", "colour": None, **t}, two) assert find() == two[0] and find(prefer="small") == two[1] and find(prefer="big") == two[0] diff --git a/tests/test_skills.py b/tests/test_skills.py index 64e81d1..49112f9 100644 --- a/tests/test_skills.py +++ b/tests/test_skills.py @@ -37,19 +37,19 @@ for bad in (88, 30, 50): # seen widths: +SEEN_UNDER_MM over # ---------- the object table: what the cup fingers take, and why not ---------- for name in ("cup", "apple", "orange", "sports ball"): assert skills.refusal(name) is None, name -for name, word in (("bottle", "narrow"), ("wine glass", "break"), ("banana", "thin"), ("cell phone", "thin"), +for name, word in (("wine glass", "break"), ("banana", "thin"), ("cell phone", "thin"), ("book", "flat"), ("bowl", "shallow"), ("sandwich", "soft"), ("laptop", "big")): en, ko = skills.refusal(name) assert word in en and name in en and ko, (name, en, ko) -assert skills.refusal("bottle")[1] == "병은 윗부분이 좁아서 제 손가락으로 잡을 수 없어요." # 은 after a final consonant +assert skills.refusal("vase")[1] == "꽃병은 깨질 수 있어서 잡지 않을게요." # 은 after a final consonant assert skills.refusal("banana")[1].startswith("바나나는 ") assert "giraffe" in skills.refusal("giraffe")[0] # not in the table at all assert all(n in skills.objects.COCO for n in skills.GRASPS), [n for n in skills.GRASPS if n not in skills.objects.COCO] try: # refused before any geometry - skills.plan_pick({**cup, "name": "bottle"}) - raise AssertionError("a bottle planned") + skills.plan_pick({**cup, "name": "wine glass"}) + raise AssertionError("a wine glass planned") except skills.SkillError as e: - assert e.args == skills.refusal("bottle") + assert e.args == skills.refusal("wine glass") # a cup: the proven grasp, 40 mm below its top, whatever its height assert skills.grasp_height(cup) == cup["top_mm"] - skills.BELOW_RIM_MM assert skills.grasp_height({**cup, "height_mm": 80.0}) == cup["top_mm"] - skills.BELOW_RIM_MM @@ -134,17 +134,33 @@ assert skills.hand_sees() == "unknown" assert len(skills.GRASP_YAWS) == 24 and set(skills.GRASP_YAWS) == set(range(-165, 181, 15)) print("skills ok") -# ---------- the fingers point straight down in the grasp (the tips: TIP_MM along them, below the grasp point) +# ---------- FINGER_DIR is straight down in the grasp (the hand's lowest part: TIP_MM along it, below the grasp point) assert abs(np.linalg.norm(skills.FINGER_DIR) - 1.0) < 1e-9 and \ (calib.rpy_matrix(*skills.GRASP_RPY) @ skills.FINGER_DIR)[2] < -0.99 -# a cup thinner than the belly closes to is held between the tips: the arm stops TIPS_GRASP_MM higher +# the tips grasp is off (MIN_WIDTH 72, 2026-10-22): a 66 mm cup is refused; the checks below turn it back on +try: + skills.plan_pick({**cup, "width_mm": 58.0}) + raise AssertionError("66 mm cup planned with the tips grasp off") +except skills.SkillError as e: + assert "too small" in e.args[0] +skills.MIN_WIDTH = 61.0 +# a cup thinner than the belly closes to is held between the tips: its axis at the tips (TIPS_OFFSET from the +# belly's centre, level, almost along the flange z axis), at every grasp turn thin = {**cup, "width_mm": 58.0} # 66 mm at the fingers -g_belly, g_tips = skills.plan_pick(cup)[1][1], skills.plan_pick(thin)[1][1] -assert abs(g_tips[2] - g_belly[2] - skills.TIPS_GRASP_MM) < 1.0 and np.allclose(g_tips[:2], g_belly[:2], atol=1.0) +for yaw in (0, -45, 90): + g_belly, g_tips = skills.plan_pick(cup, yaw)[1][1], skills.plan_pick(thin, yaw)[1][1] + Ry = calib.rpy_matrix(*g_tips[3:]) + assert np.allclose(np.array(g_tips[:3]) + Ry @ (skills.GRASP_OFFSET + skills.TIPS_OFFSET), g, atol=1e-6) + shift = np.subtract(g_belly[:3], g_tips[:3]) + assert 25 < np.hypot(*shift[:2]) < 32 and abs(shift[2]) < 3, (yaw, shift) # 28 mm, level skills._held.update(tips=True) d = skills.plan_place(-200, 600, thin["top_mm"])[1][1] # put down held the same way -assert abs(d[2] - skills.plan_place(-200, 600, thin["top_mm"], tips=False)[1][1][2] - skills.TIPS_GRASP_MM) < 1.0 +assert np.allclose(np.array(d[:3]) + R @ (skills.GRASP_OFFSET + skills.TIPS_OFFSET), [-200, 600, g[2] + 3]) 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) +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 ---------- import tempfile @@ -214,3 +230,81 @@ assert skills.place(-200.0, 600.0) == (-200.0, 600.0) assert lines_ == ["carry"] and turned[0][1][4] < 0 and abs(round(skills.yaw_of(turned[0][0][1][1]))) == 45, turned skills._held.clear() print("skills pick stores ok") + +# ---------- a bottle: held by its body, under where the neck widens (objects.body on a depth profile) ---------- +H_CAM, D_CAM = -100.0, 600.0 # camera 300 mm above a table at z -400, the bottle's axis 600 mm ahead +T_CAM = np.eye(4) +T_CAM[:3, :3], T_CAM[:3, 3] = [[1, 0, 0], [0, 0, 1], [0, -1, 0]], [0.0, 0.0, H_CAM] # looking along y, level +INTR = {"fx": 600.0, "fy": 600.0, "cx": 320.0, "cy": 100.0, "dist": [0.0] * 5} +BOX = (250, 120, 390, 420) + + +def depth_of(radius): + """A level depth camera's frame of an upright round thing on a table at z -400: radius(z) mm, 0 = nothing.""" + d = np.zeros((480, 640), np.uint16) + u, v = np.meshgrid(np.arange(BOX[0], BOX[2]), np.arange(BOX[1], BOX[3])) + xn, yn = (u - INTR["cx"]) / INTR["fx"], (v - INTR["cy"]) / INTR["fy"] + for t in np.arange(D_CAM - 60.0, D_CAM, 0.5)[::-1]: # far to near: the nearest surface stays + z = H_CAM - t * yn + r = np.vectorize(radius)(z) + hit = (t * xn) ** 2 + (t - D_CAM) ** 2 <= r ** 2 + d[v[hit], u[hit]] = round(t) + return d + + +def bottle_r(body, shoulder=-230.0, neck=14.0, top=-150.0): + """A bottle: body radius up to `shoulder`, a 30 mm shoulder narrowing to the neck, the neck up to `top`.""" + return lambda z: 0.0 if z < -400 or z > top else body if z <= shoulder else \ + neck if z >= shoulder + 30 else body + (neck - body) * (z - shoulder) / 30 + + +from vision import objects +prof = objects.body(depth_of(bottle_r(33.0)), BOX, INTR, T_CAM) # 66 mm body, 28 mm neck +assert -232 <= prof["shoulder_mm"] <= -212 and 60 <= prof["body_mm"] <= 67 and prof["low_mm"] < -390, prof +cup_prof = objects.body(depth_of(lambda z: 0.0 if z < -400 or z > -305 else 40.0 - (-305 - z) * 0.05), BOX, INTR, T_CAM) +assert cup_prof["shoulder_mm"] >= -320, cup_prof # a cup: widest at its top, no neck + +skills._held.clear() +bottle = {"name": "bottle", "colour": "blue", "x": -195.0, "y": 600.0, "top_mm": -150.0, "width_mm": 63.0, + "height_mm": None, "shoulder_mm": -203.0, "body_mm": 58.0, "low_mm": -365.0} # the spray can 2026-10-22 +assert skills.refusal("bottle") is None and skills.grip_width(bottle) == 66.0 # its body, not the mid band +z = skills.grasp_height(bottle) +assert z == -203.0 - skills.BELOW_SHOULDER_MM and z - skills.TIP_MM >= bottle["low_mm"] + skills.TIP_CLEAR_MM +(_, b_above), (_, b_grasp), (_, b_lift) = skills.plan_pick(bottle) +assert np.allclose(np.array(b_grasp[:3]) + R @ (skills.GRASP_OFFSET + skills.TIPS_OFFSET), [bottle["x"], bottle["y"], z]) +assert np.isclose(b_above[2] - b_grasp[2], bottle["top_mm"] - z + skills.TIP_MM) # tips come down from over its top +assert np.isclose(b_lift[2] - b_grasp[2], skills.LIFT_MM) +assert skills.grip_width(bottle) < skills.BELLY_MIN_MM < skills.grip_width({**bottle, "body_mm": 70.0}) # tips / belly +way = dict(skills.plan_place(-130, 600, bottle["top_mm"], below=bottle["top_mm"] - z)) +assert np.isclose(way["release up"][2] - way["place"][2], bottle["top_mm"] - z + skills.TIP_MM) # up over its top +assert np.isclose(way["above place"][2] - way["place"][2], skills.ABOVE_MM) +cup_way = dict(skills.plan_place(-130, 600, cup["top_mm"], below=skills.BELOW_RIM_MM)) # a cup: as before +assert np.isclose(cup_way["release up"][2] - cup_way["place"][2], skills.ABOVE_MM) +assert skills.grasp_height({**bottle, "low_mm": -300.0, "table_mm": -396.0}) == z # bottom out of view: the table +for bad, words in (({"body_mm": 50.0}, ("too small", "작아서")), + ({"low_mm": -300.0}, ("hit the table", "테이블에 닿아요")), # ... not measured: its lowest point # a too narrow body: 58 at the fingers + ({"body_mm": 90.0}, ("too big", "너무 커요")), + ({"shoulder_mm": -280.0}, ("hit the table", "테이블에 닿아요")), # the tips would reach the table + ({"shoulder_mm": None}, ("body well enough", "몸통이 잘"))): + try: + skills.plan_pick({**bottle, **bad}) + raise AssertionError(f"bottle {bad} planned") + except skills.SkillError as e: + assert words[0] in e.args[0] and words[1] in e.args[1] and e.args[1].startswith("병"), (bad, e.args) + +# look(): the profile of each frame's bottle box, medians of them; nothing for a cup +frames_ = [{"age_s": 0.1, "objects": [{"name": "bottle", "box": BOX, "colour": "blue", "position_mm": [-195, 600, -280], + "top_mm": -150, "width_mm": 63, "height_mm": 250}, + {"name": "cup", "box": BOX, "colour": "white", "position_mm": [0, 600, -350], + "top_mm": -310, "width_mm": 76, "height_mm": 90}]}] * 2 +skills.camview.want = lambda name: None +skills.fresh = lambda path, camera, after=0.0: None +skills.objects.latest = lambda camera=objects.CAMERA: frames_[0] +skills.camview.depth = lambda name, max_age=1.0: depth_of(bottle_r(33.0)) +skills.camview.intrinsics = lambda name: INTR +skills.objects.base_from_camera = lambda: T_CAM +skills.FRAME_GAP_S = 0.0 +got = {o["name"]: o for o in skills.look(frames=2)} +assert got["bottle"]["shoulder_mm"] == prof["shoulder_mm"] and got["bottle"]["body_mm"] == prof["body_mm"], got +assert got["cup"]["shoulder_mm"] is None and got["cup"]["body_mm"] is None +print("skills bottle ok") diff --git a/tests/test_steps.py b/tests/test_steps.py index f2b63c0..8e34a10 100644 --- a/tests/test_steps.py +++ b/tests/test_steps.py @@ -77,6 +77,16 @@ CASES = { "go to p10, then go left one meter and give it to the person": "go p10 | move left 1 | give", # 2026-10-21, said by voice: "let's", "P10 point", "10p point", "p ten" "Let's go P10 point and wait 30 seconds then come back here again.": "go p10 | wait 30 | go here", + # 2026-10-22 live (dashboard): two places in a row, "point" / "포인트" after any marker name + "let's go exit point and go p9 point": "go exit | go p9", + "let's go final point and go p9 point": "go final | go p9", + "go to exit then p9": "go exit | go p9", + "first exit then p9": "go exit | go p9", + "first go to the final point, then p2": "go final | go p2", + "exit 갔다가 p9로 가": "go exit | go p9", + "exit 포인트 갔다가 p9 포인트로 가": "go exit | go p9", + "먼저 exit 가고 그다음 p9로 가": "go exit | go p9", + "dock2 포인트로 갔다가 home으로 가": "go dock2 | go home", "let's go to 10p point then wait 30 seconds and come back here again": "go p10 | wait 30 | go here", "go to p ten, wait 30 seconds and come back here": "go p10 | wait 30 | go here", "go to point 10 and let's back 1 meter": "go p10 | move back 1", diff --git a/tests/test_switches.py b/tests/test_switches.py index 93e4416..3dccbaf 100644 --- a/tests/test_switches.py +++ b/tests/test_switches.py @@ -170,5 +170,35 @@ moved.clear() 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 +reached = [] +real_reach = fetch.reach +fetch.reach = lambda angle=0.0, say=None: reached.append(angle) +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.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.STAND_IN_FRONT_SAY[0]] and not moved, (angle, said) + else: + assert got and reached == want and moved == ["head"], (patrol, angle, reached, moved) +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]] +L.voice_trusted, L.voice_angle, L.modes.patrol = True, -50.0, True # heard from the right: turn to the voice +assert L.reach_out(False) and reached == [-50.0] +moved.clear(), reached.clear(), said.clear() +L.fetch_status = lambda: "holding" +assert lumi.Lumi.arm_pose(L, "reach") is None and moved == ["give"] and not reached # holding: hand it over +assert lumi.Lumi.arm_pose(L, "open") is None and said == [lumi.brain_mod.REFUSE_OPEN[0]] # never dropped +L.fetch_status = lambda: None +fetch.reach = real_reach 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/vision/objects.py b/vision/objects.py index 775f92f..7c67034 100644 --- a/vision/objects.py +++ b/vision/objects.py @@ -38,6 +38,13 @@ WEAK = {"cup": ((40, 110), (50, 250))} # name -> (width, height) mm ranges WIDEST = {"cup": 100} # mm; a box measured wider is something else: a white plant pot read "cup" at 110 mm # (2026-10-20); the widest cup the gripper takes reads ~84 +SLICE_MM = 10.0 # body(): a bottle's width is measured in height slices this thick +SLICE_MIN_POINTS = 20 # ... a slice with fewer depth points is left out +BODY_PCT = 75 # ... its body is as wide as this percentile of the slices' widths (the neck and the cap + # are the narrow minority; the table's edge in the bottom slice the wide one) +BODY_FRACTION = 0.9 # ... and begins at the first slice from the top this much as wide (a 66 mm spray can, + # 2026-10-22: cap 43-53, body 58-63 seen) + COCO = ("person bicycle car motorcycle airplane bus train truck boat traffic_light fire_hydrant stop_sign " "parking_meter bench bird cat dog horse sheep cow elephant bear zebra giraffe backpack umbrella handbag tie " "suitcase frisbee skis snowboard sports_ball kite baseball_bat baseball_glove skateboard surfboard " @@ -89,24 +96,22 @@ def colour_name(bgr_pixels): return next(name for top, name in HUES if h < top) -def measure(color, depth, box, intr, T, round_=False): - """3D facts of one box: colour, distance (m), centre, top, width, height (mm, arm base frame).""" +def points(depth, box, intr, T): + """The depth pixels of the thing in `box` (within FG_MM of its core's depth): (core depth mm, their mask in the + box, (3, N) points mm in the arm base frame or None when too few / no calibration); (None, None, None) when the + box's core has too little depth.""" x1, y1, x2, y2 = box d = depth[y1:y2, x1:x2] - out = {"colour": colour_name(color[y1:y2, x1:x2].reshape(-1, 3)), "distance_m": None, "position_mm": None, - "top_mm": None, "width_mm": None, "height_mm": None} h, w = d.shape core = d[h // 4:3 * h // 4, w // 4:3 * w // 4] core = core[core > 0] if core.size < MIN_POINTS: - return out + return None, None, None dc = float(np.median(core)) mask = (d > 0) & (np.abs(d - dc) < FG_MM) vs, us = np.nonzero(mask) - out["colour"] = colour_name(color[y1:y2, x1:x2][mask]) - out["distance_m"] = round(dc / 1000, 3) if len(vs) < MIN_POINTS or T is None or intr is None: - return out + return dc, mask, None if len(vs) > MAX_POINTS: pick = np.random.default_rng(0).choice(len(vs), MAX_POINTS, replace=False) vs, us = vs[pick], us[pick] @@ -114,7 +119,21 @@ def measure(color, depth, box, intr, T, round_=False): K = np.array([[intr["fx"], 0, intr["cx"]], [0, intr["fy"], intr["cy"]], [0, 0, 1]]) px = np.stack([us + x1, vs + y1], axis=1).astype(np.float64).reshape(-1, 1, 2) n = cv2.undistortPoints(px, K, np.array(intr["dist"])).reshape(-1, 2) - P = T[:3, :3] @ np.stack([n[:, 0] * z, n[:, 1] * z, z]) + T[:3, 3:4] # (3, N) in the arm base frame + return dc, mask, T[:3, :3] @ np.stack([n[:, 0] * z, n[:, 1] * z, z]) + T[:3, 3:4] + + +def measure(color, depth, box, intr, T, round_=False): + """3D facts of one box: colour, distance (m), centre, top, width, height (mm, arm base frame).""" + x1, y1, x2, y2 = box + out = {"colour": colour_name(color[y1:y2, x1:x2].reshape(-1, 3)), "distance_m": None, "position_mm": None, + "top_mm": None, "width_mm": None, "height_mm": None} + dc, mask, P = points(depth, box, intr, T) + if dc is None: + return out + out["colour"] = colour_name(color[y1:y2, x1:x2][mask]) + out["distance_m"] = round(dc / 1000, 3) + if P is None: + return out bottom, top = np.percentile(P[2], EDGE_PCT) band = (P[2] > bottom + MID_BAND[0] * (top - bottom)) & (P[2] < bottom + MID_BAND[1] * (top - bottom)) mid = P[:, band] if band.sum() >= MIN_POINTS // 2 else P @@ -131,6 +150,31 @@ def measure(color, depth, box, intr, T, round_=False): return out +def body(depth, box, intr, T): + """Width profile of an upright bottle in `box`, cut in SLICE_MM height slices: {"shoulder_mm": where its body + begins (the top of the first slice from the top down at least BODY_FRACTION as wide as the body), "body_mm": the + body's width (median of the slices below that), "low_mm": its lowest point seen}, mm in the arm base frame; None + when not measured. Seen widths, as width_mm.""" + P = points(depth, box, intr, T)[2] + if P is None: + return None + sight = np.median(P[:2], axis=1) - T[:2, 3] + sight /= np.linalg.norm(sight) or 1.0 + across = P[:2].T @ np.array([-sight[1], sight[0]]) + low, top = np.percentile(P[2], EDGE_PCT) + slices = [] # (top z of the slice, width), from the top down + for z in np.arange(top, low, -SLICE_MM): + a = across[(P[2] <= z) & (P[2] > z - SLICE_MM)] + if len(a) >= SLICE_MIN_POINTS: + slices.append((float(z), float(np.subtract(*np.percentile(a, EDGE_PCT[::-1]))))) + if not slices: + return None + wide = BODY_FRACTION * np.percentile([w for _, w in slices], BODY_PCT) + i = next(i for i, (_, w) in enumerate(slices) if w >= wide) + return {"shoulder_mm": round(slices[i][0]), "body_mm": round(float(np.median([w for _, w in slices[i:]]))), + "low_mm": round(float(low))} + + def measure_all(color, depth, boxes, intr=None, T=None): """[{name, score, box, colour, distance_m, position_mm, top_mm, width_mm, height_mm}] for YOLO boxes (x1, y1, x2, y2, score, coco_class) of one frame, nearest first. "cut": the object's bottom is below the