diff --git a/assistant/brain.py b/assistant/brain.py index dcfca35..2173ffd 100644 --- a/assistant/brain.py +++ b/assistant/brain.py @@ -63,7 +63,7 @@ Rules: - Questions about Cutshion (its robots, prices, people, jobs, hours, delivery, warranty, the CEO) are never looked up on the internet: if the notes do not say it, say plainly that you don't have that fact ("I don't have exact information about that.", "그건 정확한 정보가 없어요.", "That I don't know, sorry.", "아쉽지만 그 정보는 없어요."), - then at most one related fact you do know, with no number that could pass for the answer (the seed investment + then at most one related fact you do know (buying, prices, renting: the phone or the email to ask), with no number that could pass for the answer (the seed investment is not the company's value, the robots ordered are not the robots sold). Never a guessed number, not even when they ask again ("roughly?", "just guess", "대충이라도?", "찍어 봐"): you still don't have it. "How many people work there / at that company?" asks about the company's staff, never about the people you see now. @@ -80,14 +80,14 @@ Rules: Spanish...): action unclear, do nothing they ask, say "Sorry, I only understand English and Korean." A question in English or Korean about a language ("can you speak Chinese?") is answered normally. - A short follow-up ("and normally?", "which ones?", "why?", "tell me more", "몇 개?", "어디어디요?") is about the topic - of your previous answer: answer that. "Why?", "how come?", "how do you know?", "when?", "where?", "how?", + of your previous answer: answer that. "Why?" (also heard "wai?", "와이?"), "how come?", "how do you know?", "when?", "where?", "how?", "what do you mean?", "왜요?", "어떻게 알아?", "언제?", "어디?", "무슨 뜻이야?" right after your answer ask about that answer, also when it said you can't or won't do something: give its reason or where you know it from (what you see with your cameras, what they told you, what Cutshion built and told you about yourself and the company; never "my notes"), and say plainly when you don't know the reason; for a "can't" answer the reason is in your words (Patrol switched off: you work standing in place; your arm switched off; the place is not on your map; busy with - a task; holding something). "Really?", "are you sure?", "진짜?", "확실해요?" there ask you to confirm: "Yes, ..." - with that same point in one sentence. Never change the topic, never ask them to say it again: it is never + a task; holding something: it could fall or spill). "Really?", "are you sure?", "fr?", "no way", "진짜?", "레알?", "실화야?", "확실해요?" there ask you to confirm: "Yes, ..." + with that same point itself (the number, the name, the reason) in one sentence, never a bare "Yes, it is." Never change the topic, never ask them to say it again: it is never unclear. "Say it again" / "다시 한 번만요" means repeat your previous answer; "and in Korean?" / "영어로는요?" means your previous answer in that language. Never answer a follow-up with a list of what you can do. @@ -154,7 +154,7 @@ Rules: Facts you know (say the one that is asked, also in a short follow-up; nothing more): - Body: 146 cm tall, up to 186 cm with the lift; about 96 kg (95.6 kg) in all; the wheeled base alone weighs 50 kg; - the arm itself weighs 9.9 kg. Three cameras: an Orbbec Gemini 2 L depth camera in your head and one on your body + the arm itself weighs 9.9 kg (why so heavy: the base with its motors and big battery is half of it). Three cameras: an Orbbec Gemini 2 L depth camera in your head and one on your body (see up to about 10 m), and a 3D camera at the front of your base (35 cm to 2 m). - Arm: Mini 2 collaborative arm, six joints, reaches 58 cm, its tip moves at up to 1 m per second, it carries 2 kg including the gripper, so about 1 kg in your hand; it stops when it bumps into something. Gripper: a Zimmer @@ -271,7 +271,8 @@ You can also move. Decide if the visitor asks you to do something: place named is go_to. - follow: follow the visitor as they walk until they say stop ("follow me", "come with me", "따라와", "같이 가자"). "Follow me on Instagram" or "I follow you" is talk (none). -- look [degrees|small]: turn your head ("look at me" -> me, "don't look at me" +- look [degrees|small]: turn your head ("look at me" / "look here" / "이쪽 봐" / "여기 봐" -> me, the one speaking; "look straight + ahead" / "정면 봐" -> center; "don't look at me" / "stop staring" / "쳐다보지 마" -> away, "turn your head left" -> look left, "고개 들어" -> look up, "look down a bit" -> look down small, "head 30 degrees right" -> look right 30, "look behind you" / "look at the back side" / "turn your head back" / "뒤 봐" / "뒤돌아 봐" / "고개 뒤로 돌려" -> look left {yaw}, "look over your right shoulder" / "오른쪽 뒤 봐" -> look right {yaw}; the question "what's behind you?" / @@ -383,7 +384,7 @@ NUMBER_WORDS = {"one": "1", "two": "2", "three": "3", "four": "4", "five": "5", "eight": "8", "nine": "9", "ten": "10"} OBJECTS = {"cup": "cup", "mug": "cup", "glass": "cup", "tumbler": "cup", "bottle": "bottle", "apple": "apple", "orange": "orange", "banana": "banana", "컵": "cup", "잔": "cup", "병": "bottle", "사과": "apple", - "오렌지": "orange", "바나나": "banana", "머그컵": "cup", "텀블러": "cup", "종이컵": "cup", "물병": "bottle", + "오렌지": "orange", "바나나": "banana", "머그컵": "cup", "머그": "cup", "텀블러": "cup", "종이컵": "cup", "물병": "bottle", "페트병": "bottle", "ball": "sports ball", "tennis ball": "sports ball", "baseball": "sports ball", "공": "sports ball", "테니스공": "sports ball", "야구공": "sports ball", "wine glass": "wine glass", "와인잔": "wine glass", "vase": "vase", "꽃병": "vase", "bowl": "bowl", "그릇": "bowl", "carrot": "carrot", "당근": "carrot", @@ -545,7 +546,7 @@ INTENTS = [ # (action, pattern) checked in order on what the visitor said r"(?:please )?|please |let'?s |go ahead and |i'?d like you to |i want you to )?wave\b(?!s)|" r"\bwave (?:at|to|your|hello|hi|bye|goodbye|back|again|for)\b|\bgimme a wave\b|\b(?:why don'?t you|if you (?:could|can|would)|" r"you (?:could|should|can|might)|could you|would you|can you|will you) (?:please |just )?wave\b(?!s)|\b(?:give|do) (?:(?:them|him|her|us|me|everyone|the \w+) )?" - r"a (?:little |quick |big |friendly )?wave\b|\b(?:wave|웨이브)\s?(?:해|하고|좀)|\bshake (?:your |a |my )?hands?\b(?! with\b)|\bsay (?:hi|hello|bye) with your hand\b|손 ?(?:을 |좀 |도 )?흔들|손 ?(?:으로 ?)?인사"), + r"a (?:little |quick |big |friendly )?wave\b|\b(?:wave|웨이브)\s?(?:해|하고|좀)|\bshake (?:your hands?|hand)\b(?! with\b)|\bsay (?:hi|hello|bye) with your hand\b|손 ?(?:을 |좀 |도 )?흔들|손 ?(?:으로 ?)?인사"), ("spin", r"\bspin (?:yourself )?(?:all the way |completely |fully )?(?:a)?round\b(?! (?:the|a|an|my|your|and look)\b)" r"|\bturn (?:yourself )?(?:all the way|completely|fully) (?:a)?round\b|\bdo a (?:full )?(?:360|full turn|full circle|spin)\b|\bturn 360\b|\bspin\s*[.!]*$" r"|한 ?바퀴 ?(?:빙 ?)?(?:돌|회전)(?![았었던은]|고 ?(?:와|오))|360\s*도\s*(?:돌|회전)(?![았었던은])|빙글 ?빙글 ?돌(?![았었던은])"), @@ -570,16 +571,16 @@ INTENTS = [ # (action, pattern) checked in order on what the visitor said ("move_object", rf"\b(?:move|shift|slide) (?:the |that |this |a )?(?:({_COL}) )?({_OBJ})s?\b" 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 |the )?(hand|gripper|fingers|claw)|open it|let (it )?go|drop it|hand open|loosen your grip)\b|손을? ?(펴|벌려|열어)|손 ?open|(그리퍼|집게)(를|을)? ?(좀 )?(열어|벌려|펴)|" + rf"|(?:({_COL})\s*)?({_OBJ})\s*(?:을|를)?\s*(?:좀\s*)?(?:손으로\s*)?(?:잡아(?!먹)|집어|들어)"), + ("grip_open", r"\b(open (your |the )?(hand|gripper|fingers|claw)|open it|let (it )?go|drop it(?! off)|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"|손을? ?(쥐|오므려|닫아)|주먹 ?(을 )?쥐|잡아(?!먹|당)|손 ?close|(그리퍼|집게)(를|을)? ?(좀 )?(닫아|오므려)"), + ("arm", r"\b(reach out(?! to (?!me\b))|stretch (out )?your (arm|hand)|put your (arm|hand) (out|forward)|hand forward|" 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"|손을? ?(좀 )?(내밀|뻗)(?!었)|^\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,!~]|" + rf"^\W*(?i:{_FILL_EN})(?!(?:{_NOT_A_NAME})\b)[A-Z][a-z]+, (?!(?i:lumi)\b)|" # "Jake, take the cup", + r",\s*(?i:mom|mum|dad|honey|sweetie|guys|kids)\s*(?:,|[.!?]*\s*$)|" # "so Minji, stand up + rf",\s*(?!(?:{_NOT_A_NAME})\b)[A-Z][a-z]+\s*[.!?]*\s*$") # taller", "here you go, mom" +ASIDE_KO = re.compile(r"(?:엄마|아빠|할머니|할아버지|이모|삼촌|선생님|친구|동생|언니|누나|형|오빠)(?:한테|에게)\s*(?:손|인사|흔들)" + r"(?!.*(?:줘|주세요|주실|드려|드리|줄래|주라|주시))|" + r"^\W*(?:(?:근데|음+|흠+|아+|어+|그럼|자|저기)\s+)?(?:아저씨|아줌마|이모|삼촌|할머니|할아버지|아가야|아기야|애기야|얘야|" + r"여러분|친구야|엄마|아빠|여보|자기야|오빠|언니|누나|형|얘들아|애들아|선생님|팀장님|부장님|과장님|대리님|사장님)(?:[\s,!~]|$)|" + r"^\W*(?:(?:근데|음+|흠+|아+|어+|그럼|자|저기)\s+)?(?P[가-힣]{2})(?P아|야)[\s,!~]|" r"(?:thank you|땡큐|고맙습니다|감사합니다|안녕하세요|인사)\s*(?:해야지|해|하세요|해 ?봐|드려야지|드려)[\s.!~]*$") # "thank you 해": a parent to a child NAME_END_A = set("민진현빈준윤연은인훈환석철영경정성혁원선린결율솔슬별곤완형명용웅숙옥란") # last syllables of names (-아) @@ -651,23 +663,124 @@ def to_someone_else(text): return vowel_end or c in NAME_END_A # 민수야, 지민아; "뒤돌아 봐" is a verb +# ---------- words that name a motion but order none now (lumi.route leaves them to the LLM) ---------- +_LEAD = r"^\W*(?:(?:hey|hi|yo|okay|ok|so|um+|uh+|ah+|oh+|hmm+|alright|well|now|and|but|then|excuse me|lumi|robot|buddy|루미야?|로봇아?|음+|흠+|아+|어+|" \ + r"근데|그럼|그러면|그래서|그리고|저기요?|자)\W+)*" +CONDITION = re.compile( # a condition or a later time: "when the show starts, go to the stage", "이따가 내려놔" + r"\b(?:when(?:ever)?|once|after|before|until|till|as soon as)\s+(?!i (?:talk|speak|am talking|'m talking)\b)" + r"(?:i|we|you|he|she|they|it|the|my|your|his|her|our|their|everyone|someone|people|kids?|guests?|mom|dad)\b|" + r"^\W*(?:if|unless)\b(?! you (?:could|would|can|don'?t mind|wouldn'?t mind|please)\b)|\b(?:later|tomorrow|tonight|next time|in (?:a|an|\d+|one|two|three|five|ten) (?:minutes?|seconds?|hours?|min|sec))\b|" + r"\b(?:only|just) (?:when|if|after)\b|\bwhen i (?:say|tell|count|clap|wave|give)\b|" + r"(?:^|\s)(?:나중에|이따가?|있다가|내일|이따)\s|[가-힣](? "나한테 줘", "don't wave, + just look at me" -> "look at me". The text itself otherwise.""" + m = INSTEAD.match(text or "") + return text[m.end():] if m and text[m.end():].strip(" .!?") else text + + +THEN = re.compile(r"\s*(?:,|;|\band then\b|\bthen\b|\band\b|\bafter that\b)\s*|(?<=[가-힣]고)\s+(?:나서\s+)?", re.I) +ORDER_WORD = re.compile(r"^\W*(?:(?:please|also|just|now)\s+)*(?:look|go|turn|wave|bring|put|take|give|come|follow|move|lift|raise|" + r"lower|tell|say|show|pick|grab|drive|hand|drop|place|open|close|reach|spin|face)\b|" + r"(? "point 5" asks = re.search(r"^\s*(how(?! about (?:you|we) (?!\w+ing\b)\w)|why(?! don'?t you\b)|what if)\b|\b(how do you|how can you|can you carry|are you able)\b|" r"\b(can|could) you (pick( up)?|lift|hold|grab|take) (a|an|any)\b|" # "can you pick up a bottle?" - r"^\s*(what|when|which|at what|do you|does|is it|are you)\b|몇|언제|얼마|" # "at what level do you go back?" + r"^\s*(what|when|which|at what|do you|does|is it(?! possible)|are you)\b|몇|언제|얼마|" # "at what level do you go back?" rf"({_OBJ})(은|는)\s.*수 ?있|(루미가|로봇이)\s.*수 ?있|는 ?거 ?(돼|되나|가능)|" # "물컵은 가져다줄 수 있어요?" r"어떻게|왜|혼자|스스로|\bby yourself\b|\bsomeone\b|줄 ?알아|할 ?줄|\bcome here often\b|" r"^\W*(?:even|only|also|and|but|so)?\s*(?:with|without|if|unless|while)\b.*\?\s*$", # "even with the lift down?" - CALLING.sub("", t)) or LATER.search(CALLING.sub("", t)) # "Lumi, is it hard to ...?" + re.sub(_LEAD, "", CALLING.sub("", t), flags=re.I)) or LATER.search(CALLING.sub("", t)) # "Lumi, is it + # hard to ...?", "Lumi Lumi, are you still following me?" visitor = re.search(r"^\W*(?:can|may|could|should|shall) (?:i|we)\b", CALLING.sub("", t)) # "can I come closer?" for action, pat in INTENTS: m = re.search(pat, t, re.I) if not m: continue + if held and action not in ("quiet", "stop", "weather", "search", "sing"): + return None # a motion named, none ordered now + if action not in ("quiet", "stop", "weather", "search", "sing", "fetch") and _other_order(t, m, markers) and not ( + action in ("pick", "move_object") and any(_resolve(p, markers) not in (None, "here") + for p in re.finditer(_place_re(markers), t))): + return None # "pick up the cup, then look at the door": one part of two if action == "stop" and (STOP_TALK.search(t) or "?" in t and not STOP_ASK.match(CALLING.sub("", t)) or asks): return None # "where's your emergency stop?", "how do I stop you?" if action == "look_away": @@ -698,6 +811,8 @@ def intent(text, markers=()): return None # "the robot can drive to booth b by itself, right?", "she # told the robot 'go to dock 2' earlier": about it, no order name = wording.marker(word, markers) + if name and re.search(rf"(? 1 or named_place(text, name, markers)): # "a": not "go to a meeting room" return ("go_to", name) if re.fullmatch(r"p\d+", word): @@ -715,15 +830,34 @@ def intent(text, markers=()): return ("search", text) if action == "sing" and (SING_ECHO.match(text) or SONG_TALK.search(text)): return None # "오 노래?", "노래 좋아해?": talk about songs, no song + if action in ("fetch", "pick", "move_object") and (FLOOR.search(t) or DRINK.search(t)): + return None # "the cup on the floor", "커피 한 잔": not a pick (hand_request + # says why for the floor; the LLM for a drink) + far = any(_resolve(p, markers) not in (None, "here") for p in re.finditer(_place_re(markers), t)) or \ + re.search(r"\b(?:from|at|over at) (?:the )?(?!the\b|this\b|that\b|my\b|your\b|me\b|table\b|desk\b|floor\b|left\b|right\b|front\b|back\b|end\b|" + r"same\b|moment\b|once\b)[a-z]+", t) # a place named: not the table in front + if action == "fetch" and not far and re.search(r"\bfrom (?:the |this |that |my )?(?:table|desk)\b|(?:테이블|책상)에서", t): + continue # "take the green apple from the table": a pick here + if action == "fetch" and re.search(r"제자리|\bput (?:it|that|this) back\b", t): + continue # "컵 제자리에 갖다 놔": put it back if action == "fetch": return ("fetch", text) # parse_fetch() reads the details + if action == "spin" and re.search(r"\b(?:face|to) the other (?:side|way)\b|\bopposite\b|반대", t): + return ("turn", "around 180") # "spin around to face the other side": half a turn + deg = re.search(r"(\d+)\s*(?:degrees?|도)", t) + if action == "spin" and deg: # "spin fifteen degrees right": a turn that far + return ("turn", ("left" if re.search(r"left|왼쪽", t) else "right") + f" {deg.group(1)}") if action == "spin": # all the way round: two checked half turns (lumi.move_by) return ("turn", ("right" if re.search(r"\bright\b|오른쪽", t) else "left") + " 360") if action == "turn": if re.search(r"around|뒤로", t) or not re.search(r"left|right|왼쪽|오른쪽", t): # "왼쪽으로 돌아": left return ("turn", "around 180") - deg = re.search(r"(\d+)\s*(degrees?|도)", t) # "turn left 45 degrees" - return ("turn", ("left" if re.search(r"left|왼쪽", t) else "right") + f" {deg.group(1) if deg else 90}") + deg = re.search(r"(\d+)\s*(degrees?|도|°)", t) or re.search( + rf"\b({'|'.join({**wording.TEEN, **wording.EN_NUM})})\s*(?:degrees?|°)", t) # "turn left fifteen degrees" + ko = not deg and re.search(rf"(? "p3", "point one" -> "p1", with the map's markers "table front" -> "table_front").""" - t = unfill(wording.norm(text, markers)) + t = re.sub(r"\bhalf (?:a |an )?(cm|centimet(?:er|re)s?|mm|millimet(?:er|re)s?)\b|(? "1 of them" t = re.sub(rf"\b{word}\b", digit, t) return t @@ -948,11 +1105,14 @@ def _mentions(text, markers): for m in re.finditer(r"\bfrom (?:the )?([a-z]+)", t): # "from the kitchen": a place not on the map if not re.match(_place_re(markers), t[m.start(1):]) and "source" not in out: out["source"] = None + for m in re.finditer(r"(?:^|\s)([가-힣a-z0-9]+?)\s?에서(?![가-힣])", t): # "2층에서", "주방에서": not on the map + if not re.match(_place_re(markers), t[m.start(1):]) and "source" not in out: + out["source"] = None for m in re.finditer(rf"\b(?:to|into) (?:the )?([a-z]+)", t): if m.start() > after_obj and "dest" not in out and not re.match(rf"{_TABLE}|{_place_re(markers)}", t[m.start(1):]) \ and m.group(1) not in ("put", "place", "hold", "give", "keep", "bring", "leave"): out["dest"] = None - if "dest" not in out and re.search(r"\b(bring|get|fetch|give) (it |that |this )?(to )?me\b|\bto me\b|가져와|가지고 ?와|갖다 ?줘", t): + if "dest" not in out and re.search(r"\b(bring|get|fetch|give) (it |that |this )?(to )?me\b|\bto me\b|가져와|가지고 ?와|갖다 ?줘|가져다 ?(?:줘|주세요|줄래)", t): out["dest"] = "here" if re.search(rf"\b(put|place|leave|set) (it|that|this|the \w+)\b.*\b(on|onto) (the )?({_TABLE})\b|\bplace\b" rf"|놔|놓아|놓고|둬", t): @@ -1227,28 +1387,29 @@ _WHO = (r"(?:me|him|her|them|that (?:person|guy|man|woman|lady|kid|child)|the (? r"(?:him|her|them) over there|whoever is there)") _KO_WHO = r"(?:나|저|내 친구|제 친구|저 사람|그 사람|이 사람|이 ?분|저 ?분|그 ?분|친구|사람|저기 저 사람|저기 사람)" _THIS_KO = r"(?:이거|이것|이걸|그거|그걸|그것|저거|이|그)" -_TAIL = r"(?:[\s,]+(?:please|for me|now|then|real quick|quick|thanks|thank you|if you can|okay|lumi))*\s*[.!?]*$" +_TAIL = r"(?:[\s,]+(?:please|for me|now|then|real quick|quick|thanks|thank you|if you can|okay|lumi|i'?m (?:right )?(?:over )?here))*\s*[.!?]*$" RECEIVE_EN = re.compile( rf"(? 1 and got != ["pick", "give"]: # not "give me the cup" (picked first when the hand is empty) + if len(set(got)) > 1 and got != ["pick", "give"] and not (holding and got == ["go", "give"]): + # not "give me the cup" (picked first when the hand is empty), not "bring it to me" holding (here: no marker) return None # "take the cup, move back half a metre and hold it" if got and any(intent(u, markers) for u in unread): return None # "put it down and wave": the mission reader asks, never half done @@ -1300,6 +1483,9 @@ def hand_request(text, holding, b=None, markers=(), whole=True): return ("refuse", REFUSE_OPEN) if RECEIVE_KO.search(t) and not RECEIVE_EN.search(t) and PAID_Q.search(t): return None # "너 월급 받아?": about Lumi, nothing handed over + if named and re.search(r"\b(?:take|grab) (?:it|that|this)\s*(?:[.!?,]|$)", t) and not re.search(r"\bfrom me\b|\bmy hands?\b", t) \ + and not RECEIVE_KO.search(t): + return None # "the cup. grab it.": from the table or the hand? the LLM asks if RECEIVE_EN.search(t) or RECEIVE_KO.search(t): if holding and re.search(r"\bhold (?:it|that|on)\s*(?:$|[,.!?]|for\b|please\b|there\b)|^\W*(?:그거\s*)?들고 ?있어", t): return None # "just hold it": keep holding it @@ -1324,6 +1510,8 @@ def hand_request(text, holding, b=None, markers=(), whole=True): if on is None and re.search(r"\b(?:here|there)\b|여기|거기|저기", t): on = {"pointed": True} # "put it here / there": where the person points return ("place", on) + if holding and (intent(text, markers) or ("",))[0] in ("pick", "move_object"): + return ("refuse", REFUSE_PICK) # "take the bottle" with a cup in the hand: never a second pick return None @@ -1536,9 +1724,9 @@ SAME_ABOUT = re.compile(r"^\W*(?:and|so|what about|how about|and what about)\s+( KO_SAME_ABOUT = re.compile(r"^\W*(?:그럼\s*|그리고\s*)?(?:네\s*|너\s*|루미\s*)?(?!(?:너|루미|당신|저|나|그거|이거|그건|여기|거기)(?:은|는))([가-힣]{1,6}?)(?:은|는)요?\s*\?+\s*$") # the question before asked again about a part of Lumi ("팔은요?") FRAGMENT_CHARS = 160 # chars of the last answer's first sentence shown with a fragment -ABOUT_ANSWER = re.compile(r"^\W*(?:(?:but|and|so|then|oh|wait|hmm|okay|그럼|근데|아니|아|어)\W+)*(?:why(?: not| is that| so)?|" - r"how come|how (?:do|did|can) you (?:know|tell)(?: that| it)?|are you sure|really|for real|seriously|" - r"what do you mean|says who|왜(?:요|죠)?|왜 안 ?(?:돼|되)\S*|진짜(?:요|야|로)?|정말(?:요|이야)?|" +ABOUT_ANSWER = re.compile(r"^\W*(?:(?:but|and|so|then|oh|wait|hmm|okay|그럼|근데|아니|아|어)\W+)*(?:(?:why|wai|whai)(?: not| is that| so)?|와이|" + r"how come|how (?:do|did|can) you (?:know|tell)(?: that| it)?|are you sure|really|for real|fr|seriously|no way|" + r"what do you mean|says who|왜(?:요|죠)?|왜 안 ?(?:돼|되)\S*|진짜(?:요|야|로)?|정말(?:요|이야)?|레알|실화(?:야|예요|냐)?|참말\S*|" r"확실(?:해|한가|하)\S*|어떻게 알아\S*|그게 무슨 (?:뜻|말)\S*)\W*$", re.I) # asks about the answer just given: its reason, its source, or to confirm it LOOKUP_BEFORE_CHARS = 1500 # chars of the last lookup's results given again with a follow-up ("how old is she?") @@ -1709,8 +1897,9 @@ class Brain: header = self._after(self._action(first, text, markers), text) if header is None: # the model skipped the ACTION line header, buf = self._after({"action": "none", "target": ""}, text), first + " " + buf - if header["action"] == "unclear" and not retried and has_meaning(text) and \ - not other_latin_language(text): # 26b called short or broken but clear words unclear + if header["action"] == "unclear" and not retried and \ + (has_meaning(text) or self.history and ABOUT_ANSWER.match(text)) and \ + not other_latin_language(text): # 26b called short or broken but clear words unclear ("fr?") stream.close() retried, header, buf, full = True, None, "", "" messages[-1]["content"] += UNCLEAR_RETRY @@ -1763,8 +1952,8 @@ class Brain: return (f"(The visitor's question \"{self.history[-1][0]}\" asked again, now about {part.group(1)}: answer " f"that question for it, not other facts about it.)\n") if last and ABOUT_ANSWER.match(text): # "why?", "how do you know?", "진짜?" after a refusal too - return (f"(This asks about your answer \"{last[:FRAGMENT_CHARS * 2]}\": its reason, how you know it, or " - f"a confirmation of it.)\n") + return (f"(This asks about your answer \"{last[:FRAGMENT_CHARS * 2]}\": its reason or how you know it; " + f"a \"really?\" is answered yes with that fact itself said again.)\n") if not last or len(text.split()) > FRAGMENT_WORDS or not SHORT_Q.search(text) or is_backchannel(text) \ or ABOUT_YOU.search(text) or OWN_TOPIC.search(text): return "" @@ -2006,15 +2195,17 @@ class Brain: target = next((mk for mk in markers if wording._key(mk) == wording._key(said)), None) if not target and said.lower() not in ("", "none"): say = place_problem(f"go to {said}", markers) or no_place_say(said, markers, text) # "go_to kitchen" - if target and not named_place(text, target, markers): - target = None # "take me to the meeting room" -> p1: a guess, not driven - say = no_place_say("that", markers, text) + if target and (not named_place(text, target, markers) or re.search( + rf"(? p1, "hall B" -> hall_A: + say = no_place_say("that", markers, text) # a guess, not driven action = "go_to" if target else "none" - bare = CALLING.sub("", text) + bare = re.sub(_LEAD, "", CALLING.sub("", text), flags=re.I) # "Lumi Lumi, are you still following me?" if action in MOTIONS and (QUESTION_START.search(bare) and not (action in ("give", "receive") and re.match(r"(?:can|could|may) i\b", bare, re.I)) - or ABILITY_Q.search(text)): - action, target = "none", "" # "where is your charger?", "손 펼 수 있어요?": a question + or ABILITY_Q.search(text) or not_an_order(text, asked=False)): + action, target = "none", "" # "where is your charger?", "손 펼 수 있어요?": a question; + # "she said follow me", "in five minutes go ...": no order now if action in ("look", "lift"): # "left", "left 30", "up small"; anything else is dropped d, _, n = target.partition(" ") if d not in (LOOK_TARGETS if action == "look" else ("up", "down")): diff --git a/assistant/chain.py b/assistant/chain.py index d235f8a..f396f7f 100644 --- a/assistant/chain.py +++ b/assistant/chain.py @@ -18,7 +18,9 @@ _KO_ORDER = {"보": "봐", "흔들": "흔들어", "돌": "돌아", "올리": " ASK = re.compile(r"\?\s*$|^\W*(?:what|what'?s|where|when|who|why|how|which|is|are|do|does|did|tell me|explain|describe)\b|" r"몇 ?시|몇|뭐|무엇|어때|알려|언제|어디|누구|왜|얼마|날씨|설명해|말해 ?줘|얘기해", re.I) _SPLIT = re.compile(steps._SPLIT.pattern, re.I) -_FILL = re.compile(rf"(?:{steps._FILL}|루미야?|lumi|hey)", re.I) +FETCHING = re.compile(r"\b(?:bring|fetch|deliver|carry)\b|가져|갖다", re.I) # a part that carries something somewhere +_FILL = re.compile(rf"(?:{steps._FILL}|루미야?|lumi|hey|do me a favou?r|부탁(?:해|해요|할게)?|dear|sir|ma'?am|madam|buddy|" + r"my friend|robot|로봇아?|선생님?)", re.I) def _rule(words, markers): @@ -27,6 +29,10 @@ def _rule(words, markers): if not rule: ko = re.sub(r"(보|흔들|돌|올리|내리|높이|낮추|들)고$", lambda m: _KO_ORDER[m.group(1)], words) rule = brain.intent(ko, markers) if ko != words else None + m = not rule and re.fullmatch(r"(?:(나|저|날|나를|저를)\s+)?([a-z][a-z ]*?)\s*(?:하고|해|해요|해 ?줘)?", words.strip()) + if m: # Konglish: "나 look 하고" -> "look at me", "wave 해" -> "wave" + en = m.group(2) + ((" at me" if m.group(2) == "look" else " me") if m.group(1) else "") + rule = brain.intent(en, markers) return rule @@ -56,12 +62,17 @@ def plan(text, markers=(), cant=None): rule = _rule(p, markers) if got and not unread and not (rule and rule[0] in ("look", "lift", "wave", "come", "come_back", "follow")): out.append(["steps", p, got]) + elif rule and rule[0] == "fetch" or FETCHING.search(p): + return None # "go to the exit and bring an orange back": a fetch, whole elif rule and rule[0] in QUICK: out.append(["quick", p, rule]) elif ASK.search(p) or rule and rule[0] in ("weather", "search") or cant is not None and cant.match(p): out.append(["talk", p, None]) else: return None + out = [x for i, x in enumerate(out) if not (i and x[0] == "quick" and x[0::2] == out[i - 1][0::2])] + if len(out) < 2: + return None # "wave, wave, wave!": one wave, said with feeling kinds = [k for k, _, _ in out] if "talk" not in kinds and "quick" not in kinds or "steps" not in kinds and "quick" not in kinds: return None # all steps: a mission (read back); all talk: the LLM diff --git a/assistant/driving.py b/assistant/driving.py index 5147313..440c8b1 100644 --- a/assistant/driving.py +++ b/assistant/driving.py @@ -24,16 +24,19 @@ SPAN_M = 0.2 # m; "한 뼘", one hand span; estimate STEP_M = 0.5 # m; one step ("two steps", "한 걸음", "반 걸음"); estimate of a person's step TURN_MORE_DEG = 15.0 # deg; "a bit more" right after a turn: this much further the same way -DIRS = (("back", r"\bback(?:wards?)?\b|\bbackward\b|\breverse\b|^(?:let'?s )?(?:bake|big)\b(?= \d| half| a )|뒤로|뒤쪽|후진|" +DIRS = (("back", r"\bback(?:wards?)?\b(?! down\b)|\bbackward\b|\breverse\b|^(?:let'?s )?(?:bake|big)\b(?= \d| half| a )|뒤로|뒤쪽|후진|" r"물러"), # whisper's "let's bake / big one meter" ("forward", r"\bforwards?\b|\bahead\b|앞으로|앞쪽|전진"), ("left", r"\b(?:to the |to your )?left\b|왼쪽|좌측"), ("right", r"(? SPEAKER_MATCH_DEG): + track = self.vision.near_angle(self.voice_angle) if self.vision else None + angle = track.angle if track else self.voice_angle + else: + track = track or (self.vision.only_person() if self.vision else None) + angle = track.angle if track else None # no idea where they are: the head stays + self.turn_head(None if angle is None else HEAD_SIGN * max(-head.YAW_LIMIT, min(head.YAW_LIMIT, angle)), 10) elif action == "look" and target.split()[0:1] and (target.split()[0] in LOOK or target == "away"): self.look(target) elif action == "lift": @@ -1159,7 +1166,7 @@ class Lumi: if self.interrupted(): return True u = self.mic.next(0.0) - if u is None or not getattr(u, "during_speech", False) or u.seconds < 0.25: + if u is None or not getattr(u, "during_speech", False) or u.seconds < 0.25 or mouth.own_voice(u): return False text = (ears.transcribe(u.mono) or "").strip() if not text or self.own_echo(text) or not ears.understood(BARGE_IN_LOGPROB): @@ -1910,6 +1917,9 @@ class Lumi: return False if not getattr(u, "during_speech", False) or u.seconds < 0.25: return False + if mouth.own_voice(u): # the speaker's sound in the clip mic (mouth.echo) + log(f" ignored own voice (sound match {mouth.last_echo:.2f})") + return False text = (ears.transcribe(u.mono) or "").strip() if not text or self.own_echo(text): return False @@ -1936,7 +1946,7 @@ class Lumi: log(f" interrupted: {text!r} - stop talking, listen") return True if len(text.split()) >= 2 or brain_mod.WAKE_WORD_RE.search(text): - log(f" interrupted by a new question: {text!r}") + log(f" interrupted by a new question: {text!r} (sound match {mouth.last_echo and round(mouth.last_echo, 2)})") self.pending_text = text return True return False @@ -1992,6 +2002,9 @@ class Lumi: return True self.warm_llm() # the LLM's prompt start cached while they speak text, u = ears.listen(wait_s=4.0, on_start=lambda: log(" hearing speech"), abort=self.interrupted, full=True) + if text and mouth.own_voice(u): # the speaker's sound in the clip mic (mouth.echo) + log(f" ignored own voice (sound match {mouth.last_echo:.2f}): {text!r}") + text = None if text and self.own_echo(text) and (u is None or (u.during_speech if u.source == "clip" else len(text.split()) <= 2)): # Lumi heard itself: the clip mic while Lumi talked, or the room's echo of the last word on the head array @@ -2131,6 +2144,7 @@ class Lumi: """Use the sound direction: pick the visible person who spoke; meanwhile collect calibration samples.""" if not self.vision or u is None: return + self.voice_trusted = False # set again below only from this turn's own sound yaw = self.det_yaw() only = self.vision.only_person() if only is not None and only is self.current and only.distance <= 1.6 and u.seconds >= 0.8: @@ -2145,6 +2159,7 @@ class Lumi: ang, conf, _ = doa.estimate(u.mics, cal) if conf < DOA_MIN_CONF: return + self.voice_angle, self.voice_trusted = HEAD_SIGN * yaw + ang, True # "이쪽 봐": this voice, also out of view t = self.vision.near_angle(HEAD_SIGN * yaw + ang) if t is not None and t is not self.current: log(f" voice from {HEAD_SIGN * yaw + ang:+.0f} deg: person #{t.id} is speaking") @@ -2990,7 +3005,8 @@ def route(text, markers, b, holding=False, seen=None, last="", chain_ok=True): how = stuck and detour.read(text, markers, stuck["goal"]) if how: return "detour", how - plan = chain_ok and chain.plan(text, markers, NOT_A_STEP) + hold = brain_mod.not_an_order(text) # "when the show starts, go to the stage", "Jake, wave", "can you wave?" + plan = chain_ok and not brain_mod.not_an_order(text, asked=False) and chain.plan(text, markers, NOT_A_STEP) if plan: return "chain", plan got = seen(text) if seen else None @@ -2998,6 +3014,9 @@ def route(text, markers, b, holding=False, seen=None, last="", chain_ok=True): return "seeing", got if status_question(text): return "status", None + if hold: + return (("end", None) if talk_fate(text) == "end" else ("sing", None) if sing.asked(text, last) else + (None, None)) # no motion from a keyword: the LLM reads it from the talk cor = brain_mod.correction(text, b.history) if cor: return "correction", cor @@ -3009,7 +3028,7 @@ def route(text, markers, b, holding=False, seen=None, last="", chain_ok=True): read = read_mission(text, markers) if read: return "mission", read - if talk_fate(text) == "end": + if talk_fate(text) == "end" and (b.history or not HI_ANNYEONG.search(text)): # "루미 안녕!" first: hello return "end", None if sing.asked(text, last): return "sing", None diff --git a/assistant/wording.py b/assistant/wording.py index a9675eb..94f992d 100644 --- a/assistant/wording.py +++ b/assistant/wording.py @@ -55,7 +55,7 @@ KO_SPOKEN = {"start": ["스타트"], "end": ["엔드"], "final": ["파이널", " "init": ["이닛", "이니트"], "exit": ["엑시트", "엑싯"], "dock": ["도크"], "point": ["포인트"], "coffee": ["커피"], "corner": ["코너"], "info": ["인포"], "desk": ["데스크"], "gate": ["게이트"], "hall": ["홀"], "zone": ["존"], "photo": ["포토"], "lounge": ["라운지"], "lobby": ["로비"], "room": ["룸"], - "demo": ["데모"], "main": ["메인"], "cafe": ["카페"], "area": ["에어리어"], "center": ["센터"], + "demo": ["데모"], "bar": ["바"], "main": ["메인"], "cafe": ["카페"], "area": ["에어리어"], "center": ["센터"], "entrance": ["엔트런스"], "finish": ["피니시", "피니쉬"], "lab": ["랩"], "office": ["오피스"], "a": ["에이"], "b": ["비"], "c": ["씨"], "d": ["디"]} # letters only inside a longer name ("부스 에이") KO_NOT_ALONE = {"table", "point", "a", "b", "c", "d"} # "테이블에 놔" is the table, "포인트" a p-number, "비" rain: @@ -142,7 +142,8 @@ def numbers(t): lambda m: f"{float(m.group(1)) * 1000:g} m", t) t = re.sub(r"(\d+(?:\.\d+)?)\s*(?:miles?|마일)(?![a-z])", lambda m: f"{float(m.group(1)) * 1609.344:g} m", t) t = re.sub(r"(\d+(?:\.\d+)?)\s*(?:meters?|metres?|metals?|미터)", r"\1 m", t) - t = re.sub(r"(? max(a, 0): + ref[max(a, 0):b] = wav[max(0, -a):b - a] + if not ref.any(): + return None + m, r = _bands(np.asarray(audio, np.float32) / 32768.0), _bands(ref) + level = m.mean(1) + loud = level > level.max() - ECHO_TOP_DB / 10 * np.log(10) + if loud.sum() < ECHO_MIN_FRAMES: + return None + m = m[loud] - m[loud].mean(0) + best = 0.0 + for k in range(0, len(r) - len(loud) + 1, 2): # 20 ms steps over the lag window + seg = r[k:k + len(loud)][loud] + seg = seg - seg.mean(0) + den = np.sqrt((seg ** 2).sum() * (m ** 2).sum()) + if den > 0: + best = max(best, float((seg * m).sum() / den)) + return best + + +def own_voice(u): + """A clip-mic utterance (mic.Utterance) that is Lumi's own voice from its speaker (echo() >= ECHO_MIN).""" + global last_echo + if getattr(u, "source", "") != "clip" or getattr(u, "mono", None) is None: + return False + last_echo = echo(u.mono, u.t_end) + return last_echo is not None and last_echo >= ECHO_MIN + + def _synth(text, lang): if text in _cache: return _cache[text] diff --git a/knowledge/cutshion_en.md b/knowledge/cutshion_en.md index 8af640b..2ff7186 100644 --- a/knowledge/cutshion_en.md +++ b/knowledge/cutshion_en.md @@ -16,7 +16,7 @@ Cutshion is a young startup (founded in 2022, a certified venture business). Cut Cutshion awards: RoboWorld Award 2023 in robot services for GOMCOOK, RoboWorld Award 2024 in manufacturing robots for the mobile welding robot, the Excellence Award at the Venturium Demo Day (May 2026), and the VivaTech Tech for Change Award in Paris (June 2026). -Cutshion exhibitions: RoboWorld in Korea (2022, 2023), IFA Berlin (2023), Gangnam Robot Plus Festival (2023, 2024), Smart Life Week (2024), Korea ICT Expo in Japan (2024), CES in Las Vegas (2025 and 2026), the NRA Show in Chicago (2026) and VivaTech in Paris (2026). +Cutshion exhibitions: RoboWorld in Korea (2022, 2023), IFA Berlin (2023), Gangnam Robot Plus Festival (2023, 2024), Smart Life Week (2024), Korea ICT Expo in Japan (2024), CES in Las Vegas (2025 and 2026), the NRA Show in Chicago (2026) and VivaTech in Paris (2026). These are past shows; which exhibition Cutshion goes to next, and when, is not known to Lumi. 쿳션의 다음 전시회는 몰라요. Cutshion partners listed on its website include OMRON, Zimmer Group Korea, Screen HD Korea, Daesung Industrial, BorgWarner, THIRA Robotics, Calmantech, Sinsung F.A, Hyunwoo Automation, Deeplant, BizData, Ikseon 121, WithinNet, Cho & Company, Oldmug, Cake Drama and Bogate. diff --git a/tests/asr_cases5.py b/tests/asr_cases5.py new file mode 100644 index 0000000..794ec00 --- /dev/null +++ b/tests/asr_cases5.py @@ -0,0 +1,115 @@ +"""Spoken cases, set 5 (hearing round 2, 2026-10-22 night): short commands, numbers with units, and marker names +on several maps (tests/blind/maps.py), English, Korean and mixed. Format of tests/asr_cases.py plus "markers" (the +map the case is read against). + + .venv/bin/python tests/asr_check.py --cases 5 [--session] +""" +from tests.blind.maps import MAPS + +CASES = [] +OFFICE = MAPS["office"] + + +def add(lang, text, say=None, kind="command", markers=OFFICE): + """say: the words as spoken (numbers in words), in the case's language; mixed: [(lang, words), ...].""" + if isinstance(say, list): + pieces = say + else: + pieces = [("ko" if lang == "ko" else "en", say or text)] + CASES.append({"kind": kind, "lang": lang, "text": text, "say": pieces, "markers": markers}) + + +# ---- short commands, said alone +for t in ["Stop.", "Stop!", "Stop it.", "Wait.", "Wait a second.", "Wave.", "Wave to me.", "Hand.", "Your hand.", + "Come.", "Come here.", "Follow me.", "Here.", "Over here.", "Come back.", "Look back.", "Look behind you.", + "Look up.", "Look down.", "Look left.", "Look right.", "Look at me.", "Turn left.", "Turn right.", + "Turn around.", "Go home.", "Sing.", "Sing a song.", "Louder.", "Quieter.", "Speak slower.", "Open your hand.", + "Close your hand.", "Give it to me.", "Take it.", "Put it down.", "Go back.", "Move forward.", "Back up.", + "Lift up.", "Go down.", "Higher.", "Lower.", "Be quiet.", "What time is it?", "How's the weather?", + "Battery?", "Again.", "One more time.", "A bit more.", "Okay.", "Thanks.", "Bye.", "Never mind.", + "Hold on.", "Freeze.", "Halt.", "Enough."]: + add("en", t, kind="short") +for t, say in [("멈춰", None), ("멈춰!", None), ("그만", None), ("그만해", None), ("정지", None), ("스톱", None), + ("잠깐", None), ("잠깐만", None), ("손 흔들어", None), ("손 흔들어 줘", None), ("손", None), ("손 줘", None), + ("따라와", None), ("나 따라와", None), ("이리 와", None), ("와", None), ("여기", None), ("여기로", None), + ("돌아와", None), ("뒤 봐", None), ("뒤 돌아봐", None), ("고개 들어", None), ("고개 숙여", None), + ("위 봐", None), ("아래 봐", None), ("왼쪽 봐", None), ("오른쪽 봐", None), ("나 봐", None), + ("왼쪽으로 돌아", None), ("오른쪽으로 돌아", None), ("뒤로 돌아", None), ("집에 가", None), + ("홈으로 가", None), ("노래해", None), ("노래 불러 줘", None), ("크게 말해", None), ("작게 말해", None), + ("천천히 말해", None), ("손 펴", None), ("손 쥐어", None), ("줘", None), ("이거 받아", None), + ("내려놔", None), ("뒤로 가", None), ("앞으로 가", None), ("올라가", None), ("내려가", None), + ("조용히 해", None), ("몇 시야?", None), ("날씨 어때?", None), ("배터리 얼마야?", None), ("한 번 더", None), + ("조금 더", None), ("다시", None), ("고마워", None), ("잘 가", None), ("됐어", None), ("괜찮아", None)]: + add("ko", t, say, kind="short") + +# ---- numbers with units (said in words) +EN_MOVES = [("Go forward 1 meter.", "Go forward one meter."), ("Move back half a meter.", None), + ("Go forward 50 centimeters.", "Go forward fifty centimeters."), ("Move back 30 centimeters.", "Move back thirty centimeters."), + ("Go forward 2 meters.", "Go forward two meters."), ("Go back 1.5 meters.", "Go back one and a half meters."), + ("Move left 20 centimeters.", "Move left twenty centimeters."), ("Move right 1 meter.", "Move right one meter."), + ("Turn left 30 degrees.", "Turn left thirty degrees."), ("Turn right 90 degrees.", "Turn right ninety degrees."), + ("Turn left 45 degrees.", "Turn left forty five degrees."), ("Turn right 180 degrees.", "Turn right one hundred eighty degrees."), + ("Turn 60 degrees to the left.", "Turn sixty degrees to the left."), ("Forward 1 meter.", "Forward one meter."), + ("Back 50 centimeters.", "Back fifty centimeters."), ("Go 3 meters forward.", "Go three meters forward."), + ("Lift up 5 centimeters.", "Lift up five centimeters."), ("Lower 10 centimeters.", "Lower ten centimeters.")] +for t, say in EN_MOVES: + add("en", t, say) +KO_MOVES = [("1미터 앞으로 가", "일 미터 앞으로 가"), ("반 미터 뒤로 가", None), ("50센티 앞으로", "오십 센티 앞으로"), + ("30센티 뒤로", "삼십 센티 뒤로"), ("2미터 앞으로 가 줘", "이 미터 앞으로 가 줘"), + ("1미터 50센티 뒤로 가", "일 미터 오십 센티 뒤로 가"), ("왼쪽으로 20센티 가", "왼쪽으로 이십 센티 가"), + ("오른쪽으로 1미터 가", "오른쪽으로 일 미터 가"), ("왼쪽으로 30도 돌아", "왼쪽으로 삼십 도 돌아"), + ("오른쪽으로 90도 돌아", "오른쪽으로 구십 도 돌아"), ("45도 왼쪽으로 돌아", "사십오 도 왼쪽으로 돌아"), + ("180도 돌아", "백팔십 도 돌아"), ("30도 오른쪽", "삼십 도 오른쪽"), ("1미터", "일 미터"), + ("반 미터", None), ("50센티", "오십 센티"), ("30도", "삼십 도"), ("앞으로 3미터", "앞으로 삼 미터"), + ("5센티 올려", "오 센티 올려"), ("10센티 내려", "십 센티 내려"), ("한 걸음 앞으로", None), + ("1미터만 와", "일 미터만 와")] +for t, say in KO_MOVES: + add("ko", t, say) +for t, say in [("1미터 forward", [("ko", "일 미터"), ("en", "forward")]), + ("turn left 30도", [("en", "turn left"), ("ko", "삼십 도")]), + ("50센티 back", [("ko", "오십 센티"), ("en", "back")]), + ("go 1미터 앞으로", [("en", "go"), ("ko", "일 미터 앞으로")])]: + add("mix", t, say) + +# ---- marker names on several maps +CONF = MAPS["conference"] +for t, say in [("Go to the Main Stage.", None), ("Take me to Booth 12.", "Take me to booth twelve."), + ("Go to Registration.", None), ("Go to the photo zone.", None), ("Go to the lounge.", None), + ("Go to the Coffee Bar.", None), ("Go to Exit B.", None), ("Main Stage, please.", None), + ("Booth 12.", "Booth twelve."), ("Coffee Bar.", None), ("Lumi, go to the main stage.", None), + ("Bring me to registration.", None), ("Go home.", None), ("Go to dock 2 and charge.", "Go to dock two and charge.")]: + add("en", t, say, markers=CONF) +for t, say in [("메인 스테이지로 가", None), ("부스 12로 가", "부스 십이로 가"), ("부스 12로 가 줘", "부스 열둘로 가 줘"), + ("레지스트레이션으로 가", None), ("포토존으로 가", None), ("포토존 가자", None), ("라운지로 가", None), + ("라운지로 데려다 줘", None), ("커피 바로 가", None), ("커피바로 가 줘", None), ("엑시트 비로 가", None), + ("포토존", None), ("라운지", None), ("메인 스테이지", None), ("홈으로 가", None), ("도크 투로 가서 충전해", None)]: + add("ko", t, say, markers=CONF) +for t, say in [("Main Stage로 가", [("en", "Main Stage"), ("ko", "로 가")]), + ("Booth 12로 가 줘", [("en", "Booth twelve"), ("ko", "로 가 줘")]), + ("Coffee Bar로 가", [("en", "Coffee Bar"), ("ko", "로 가")]), + ("go to 포토존", [("en", "go to"), ("ko", "포토존")]), + ("go to 라운지", [("en", "go to"), ("ko", "라운지")])]: + add("mix", t, say, markers=CONF) +KOREAN_MAP = MAPS["korean"] +for t, say in [("커피코너로 가", None), ("부스3으로 가", "부스 삼으로 가"), ("입구로 가", None), ("무대로 가", None), + ("안내데스크로 가", None), ("휴게실로 가", None), ("회의실로 가 줘", None), ("커피코너", None)]: + add("ko", t, say, markers=KOREAN_MAP) +for t, say in [("Go to the 커피코너.", [("en", "Go to the"), ("ko", "커피코너")]), + ("Take me to 회의실.", [("en", "Take me to"), ("ko", "회의실")])]: + add("mix", t, say, markers=KOREAN_MAP) +EXPO, HALL = MAPS["expo"], MAPS["hall"] +for t, say, m in [("Go to booth A.", None, EXPO), ("Go to booth 3.", "Go to booth three.", EXPO), + ("Go to the entrance.", None, EXPO), ("Go to the info desk.", None, EXPO), + ("Go to the coffee corner.", None, EXPO), ("Go to gate 1.", "Go to gate one.", HALL), + ("Go to gate 2.", "Go to gate two.", HALL), ("Go to hall A.", None, HALL), + ("Go to the photo zone.", None, HALL), ("Go to the table front.", None, HALL)]: + add("en", t, say, markers=m) +for t, say, m in [("부스 에이로 가", None, EXPO), ("부스 쓰리로 가", None, EXPO), ("인포 데스크로 가", None, EXPO), + ("커피 코너로 가", None, EXPO), ("게이트 원으로 가", None, HALL), ("게이트 투로 가", None, HALL), + ("홀 에이로 가", None, HALL), ("포토 존으로 가", None, HALL)]: + add("ko", t, say, markers=m) +for n, ko in [(1, "일"), (3, "삼"), (5, "오"), (7, "칠"), (9, "구"), (10, "십")]: + add("ko", f"p{n}로 가", f"피 {ko}로 가") + add("en", f"Go to p{n}.", f"Go to p {['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten'][n - 1]}.") +for t, say in [("p3로 가 줘", "피쓰리로 가 줘"), ("p5", "피 파이브"), ("p8로", "피 에잇으로"), ("p2", "피 이")]: + add("ko", t, say) diff --git a/tests/asr_check.py b/tests/asr_check.py index d8ee8c5..9e3ba84 100644 --- a/tests/asr_check.py +++ b/tests/asr_check.py @@ -7,11 +7,13 @@ microphones, sent through ears.transcribe() exactly as Lumi does, then through L .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 --cases 5 # short commands, numbers with units, marker names (asr_cases5.py) .venv/bin/python tests/asr_check.py --cases tests/blind/train/hearing.py # any file with CASES (own markers) .venv/bin/python tests/asr_check.py --trim 0.3 # the audio without its last 0.3 s (early transcription) .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 + .venv/bin/python tests/asr_check.py --memo # whisper's answers kept (logs/asr_check/memo.jsonl), re-runs fast Needs a whisper-server; the check starts its own on STT_PORT (never the live one on 8096, which Lumi uses). A case is right when the text routes as the written text does (tests/command_check.rules: the same motion, or both @@ -37,7 +39,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 import asr_cases4, asr_cases5 from tests.command_check import rules ROOT = pathlib.Path(__file__).resolve().parents[1] @@ -190,10 +192,12 @@ def main(args): global STT_PORT STT_PORT = int(args[args.index("--port") + 1]) start_server() + if "--memo" in args: + memo() rng = np.random.default_rng(5) rows, t0 = [], time.time() which = args[args.index("--cases") + 1] if "--cases" in args else "1" - pool = {"1": CASES, "2": CASES2, "3": CASES3, "4": asr_cases4.CASES}.get(which) or load(which) + pool = {"1": CASES, "2": CASES2, "3": CASES3, "4": asr_cases4.CASES, "5": asr_cases5.CASES}.get(which) or load(which) trim = int(float(args[args.index("--trim") + 1]) * ears.RATE) if "--trim" in args else 0 cases = [c for c in pool if not only or re.search(only, c["text"])] for i, c in enumerate(cases): @@ -223,6 +227,31 @@ def main(args): report(rows, time.time() - t0, ROOT / "logs" / f"{name}.md") +def memo(): + """Every whisper call kept in logs/asr_check/memo.jsonl by its audio and arguments: a re-run with other choices in + ears asks whisper only for what it never heard (and gets the same answer, no sampling noise between runs).""" + f = OUT / "memo.jsonl" + seen = {} + if f.exists(): + for line in f.open(): + try: + k, v = json.loads(line) + seen[k] = tuple(v) + except ValueError: # a line cut by another process + pass + infer = ears._infer + + def cached(wav, prompt, language=None, **kw): + k = hashlib.md5(wav).hexdigest() + json.dumps([prompt, language, ears.BEAM_SIZE, sorted(kw.items())], + ensure_ascii=False) + if k not in seen: + seen[k] = infer(wav, prompt, language, **kw) + with f.open("a") as out: + out.write(json.dumps([k, seen[k]], ensure_ascii=False) + "\n") + return seen[k] + ears._infer = cached + + def load(path): """CASES of any case file (tests/blind/...: the same format, places with their own markers).""" import importlib.util diff --git a/tests/echo_check.py b/tests/echo_check.py new file mode 100644 index 0000000..89d8db0 --- /dev/null +++ b/tests/echo_check.py @@ -0,0 +1,111 @@ +"""Lumi's own voice in the clip mic (audio/mouth.py echo()): what the speaker played against what the mic heard. + + .venv/bin/python tests/echo_check.py # made cases, and the real clips in logs/asr_real/ when there + +Made cases: Lumi's lines (TTS voice F1) through a room as the clip mic hears the speaker (echo, noise, 0-0.8 s late, +the utterance a part of the sentence) must score >= mouth.ECHO_MIN; a visitor (other voices) close to the clip mic +while Lumi talks in the background (12-20 dB lower), also saying Lumi's own words, must score below it. Real: the +owner's clips against Lumi's lines (low), and the clips that were Lumi's own voice live (2026-10-22 18:25, 18:49) +against the line Lumi said then. The TTS samples differ each time it is made (a made line against itself made +again: 0.4-0.6 instead of 0.8), so the real own-voice scores here are lower than live, where mouth keeps the samples +it played: only the made cases decide ECHO_MIN; the live log's "own voice" lines show the real scores. +""" +import wave +from pathlib import Path + +import numpy as np + +from audio import mouth +from tests.asr_check import synth, room + +ROOT = Path(__file__).resolve().parents[1] +RATE = 16000 +LINES = ["I can see you through my cameras and sensors to make sure I navigate around you safely.", + "Your right hand is still empty.", "Okay, I'm looking to the left.", + "It is mainly clear right now with a temperature of 23 degrees, but you should be prepared for rain later.", + "네, 충전소로 갈게요. 잠시만 기다려 주세요.", "저는 커피를 직접 만들 수는 없지만, 커피 바까지 안내해 드릴 수 있어요."] +VISITOR = [("en", "Stop, please stop."), ("en", "Can you see me?"), ("en", "What is in my hand?"), + ("ko", "잠깐만, 그만해."), ("ko", "루미야, 이리 와."), ("en", "Let's follow me.")] +ARM = "My arm is in a position I don't know, so I won't move it." +OWN_REAL = {"1022/182501": ARM, # heard "I am dumb, so I won't move it." + "1022/182504": "Please bring it near its look pose by hand.", # "It's bringing your insulin to the hand." + "1022/182519": ARM, # "I won't move it." + "184903": "Your right hand is still empty."} # "It's still empty." (logs/heard) +NEAR_SPEAKER = dict(rt60=0.35, snr=20, peak=0.2, babble=False) # the speaker ~1 m from the clip mic + + +def lumi(text, speed=0.92): + return synth([("ko" if any("가" <= ch <= "힣" for ch in text) else "en", text)], "F1", speed) + + +def score(mic, played, lag): + """echo() with `played` started `lag` s before the mic heard it, the mic's audio ending now.""" + mouth._played.clear() + end = 1000.0 + start_mic = end - len(mic) / RATE + mouth._played.append([start_mic - lag, start_mic - lag + len(played) / RATE, played.astype(np.float32)]) + return mouth.echo(mic, end) + + +def made(): + rng = np.random.default_rng(3) + own, other = [], [] + for i, text in enumerate(LINES): + x = lumi(text) + for k in range(4): + lag = rng.uniform(0.0, 0.8) + a = int(rng.uniform(0, 0.5) * len(x)) + part = x[a:a + int(rng.uniform(1.2, 4.0) * RATE)] # the part the mic cut as one utterance + heard = room(part, NEAR_SPEAKER, rng) + # the mic hears part (from sample a) lag s after it played: played started (a/RATE + lag) s before + own.append(score(heard, x, a / RATE + lag - 0.3)) # room() puts 0.3 s before it + assert score(heard, x, a / RATE + len(x) / RATE + 2) is None # said after Lumi stopped: not judged + lang, words = VISITOR[(i + k) % len(VISITOR)] + v = synth([(lang, words)], ["M2", "F3", "M4", "F5"][k], 1.0) + for same in (False, True): + if same: # the visitor says Lumi's own words + v = synth([("ko" if any("가" <= ch <= "힣" for ch in text) else "en", text)], "M3", 1.0)[:len(part)] + bg = room(part[:len(v)], NEAR_SPEAKER, rng).astype(np.float32) + db = rng.uniform(12, 20) + n = min(len(v), len(bg)) + vv, bg = v[:n] * 32767 * 0.3, bg[:n] + mix = vv + bg * np.sqrt(np.mean(vv ** 2) / (np.mean(bg ** 2) + 1e-9)) / 10 ** (db / 20) + mix = np.concatenate([np.zeros(int(0.3 * RATE)), mix, np.zeros(int(0.3 * RATE))]) + other.append(score(mix.astype(np.int16), x, a / RATE + lag - 0.3)) + return own, other + + +def clip(name): + f = ROOT / "logs" / "asr_real" / f"{name}.wav" + f = f if f.exists() else ROOT / "logs" / "heard" / f"{name}.wav" + if not f.exists(): + return None + with wave.open(str(f)) as w: + return np.frombuffer(w.readframes(w.getnframes()), np.int16) + + +def best(mic, played): + """The best echo() over every lag (the real clips' play times are not known): harder for the visitor clips.""" + return max(score(mic, played, lag) or 0.0 for lag in np.arange(-len(mic) / RATE, len(played) / RATE, 1.0)) + + +def real(): + from tests.asr_live import REAL + own = {n: best(clip(n), lumi(t)) for n, t in OWN_REAL.items() if clip(n) is not None} + visitor = {n: max(best(clip("1022/" + n), lumi(t)) for t in set(OWN_REAL.values()) | {LINES[0]}) + for n, said in REAL.items() if said and clip("1022/" + n) is not None} + return own, visitor + + +if __name__ == "__main__": + own, other = made() + print(f"made: own voice {len(own)}: min {min(own):.2f}, median {np.median(own):.2f}; " + f"visitor over Lumi {len(other)}: max {max(other):.2f}, median {np.median(other):.2f}") + print(f" own below {mouth.ECHO_MIN}: {sum(s < mouth.ECHO_MIN for s in own)}, visitor at or above: " + f"{sum(s >= mouth.ECHO_MIN for s in other)}") + assert min(own) >= mouth.ECHO_MIN > max(other) + own_r, vis_r = real() + if own_r: + print("real own voice:", {k: round(v, 2) for k, v in own_r.items()}) + print(f"real visitor clips {len(vis_r)}: max {max(vis_r.values()):.2f}, at or above {mouth.ECHO_MIN}: " + f"{[k for k, v in vis_r.items() if v >= mouth.ECHO_MIN]}") diff --git a/tests/test_mouth.py b/tests/test_mouth.py index df53bb7..8600496 100644 --- a/tests/test_mouth.py +++ b/tests/test_mouth.py @@ -25,4 +25,32 @@ assert llm_direct.render([{"role": "system", "content": "S"}, {"role": "user", " # a prefill (system + turns) is the start of the next prompt, so the runner's cache holds it start = [{"role": "system", "content": "S"}, {"role": "user", "content": "Q"}, {"role": "assistant", "content": "A"}] assert llm_direct.render(start + [{"role": "user", "content": "Q2"}]).startswith(llm_direct.render(start, reply=False)) -print(f"ok: {len(CUTS)} cuts, the prompt, the prefill") + +# Lumi's own voice in the clip mic (mouth.echo): what the speaker played 0.4 s earlier, quieter, with noise -> high; a +# visitor's sound over it -> low; a sound after Lumi stopped -> no judgement. Speech-like test sounds: noise with a +# syllable-rate envelope in each of four bands (tests/echo_check.py uses real TTS) +import numpy as np # noqa: E402 +rng = np.random.default_rng(0) + + +def voice(seconds): + n = int(seconds * 16000) + out = np.zeros(n, np.float32) + for lo, hi in [(200, 600), (600, 1200), (1200, 2400), (2400, 4000)]: + spec = np.fft.rfft(rng.standard_normal(n)) + f = np.fft.rfftfreq(n, 1 / 16000) + spec[(f < lo) | (f > hi)] = 0 + env = np.repeat(rng.uniform(0, 1, n // 1600 + 1) ** 2, 1600)[:n] # a new level every 0.1 s + out += np.fft.irfft(spec, n).astype(np.float32) * env + return out / np.abs(out).max() * 0.5 + + +played, other = voice(3.0), voice(2.0) +mouth._played.clear() +mouth._played.append([100.0, 103.0, played]) # played from t = 100 s to 103 s +heard = played[8000:40000] * 0.3 + rng.standard_normal(32000).astype(np.float32) * 0.005 # 0.5-2.5 s of it, 0.4 s late +assert mouth.echo((heard * 32767).astype(np.int16), 102.9) >= mouth.ECHO_MIN +visitor = other * 0.5 + played[8000:40000] * 0.05 # a visitor close to the mic, Lumi 20 dB lower +assert mouth.echo((visitor * 32767).astype(np.int16), 102.9) < mouth.ECHO_MIN +assert mouth.echo((heard * 32767).astype(np.int16), 106.0) is None # said 1 s after Lumi stopped +print(f"ok: {len(CUTS)} cuts, the prompt, the prefill, own voice")