From 91f448a7ad88a88fd5a933dfbc03c372c526c21f Mon Sep 17 00:00:00 2001 From: Cutshion Date: Fri, 23 Oct 2026 13:11:05 +0900 Subject: [PATCH] LLM: a motion it picks runs only for a direct order (negations, plans, conditions, ability questions get words only); order-or-talk and hand examples for the model; give / put / reach rules while holding; quick-answer hook Co-Authored-By: Claude Opus 5.5 --- assistant/action_examples.py | 160 +++++++++++++++++++++++ assistant/brain.py | 239 +++++++++++++++++++++++++++++++---- assistant/lumi.py | 16 ++- tests/test_intents.py | 19 +++ 4 files changed, 408 insertions(+), 26 deletions(-) create mode 100644 assistant/action_examples.py diff --git a/assistant/action_examples.py b/assistant/action_examples.py new file mode 100644 index 0000000..fcc15a2 --- /dev/null +++ b/assistant/action_examples.py @@ -0,0 +1,160 @@ +"""Example readings of words that hold command words: which are orders to Lumi now and which are only talk. + +EXAMPLES = [(category, lang, said, reply, action)]; talk_examples.pick(said, lang, k, bank=...) picks the closest. +- action: the ACTION line Lumi writes for it (brain.ACTIONS_STREAM), "none" for talk. +- reply: what Lumi says, spoken style, short; Korean always polite. +brain._examples shows the closest ones with their action, so the model sees the same words read as an order and as +talk side by side. Kinds: an order now vs a plan between people, narration, a quote, a condition or later time, a +hypothetical, an ability question, "don't X", words to someone else, an announcement; amounts and directions +(Korean numbers, Konglish 레프트 = left, a number without a unit is asked); the hand while holding. + + python assistant/action_examples.py # self-check + python assistant/action_examples.py "위 보지 마" # show what pick() returns +""" +import re +import sys + +_BANK = { + "order_or_talk": { + "en": [ + ("Turn left.", "turn left 90", "Okay, turning left."), + ("Turn left at the corner, then it's the second door.", "none", "Got it, second door after the corner."), + ("My friend told me to turn left here.", "none", "Then left it is for you two. Enjoy!"), + ("Look up.", "look up", "Okay, looking up."), + ("Don't look up.", "none", "Okay, I'll keep my head where it is."), + ("Please don't follow me.", "none", "Alright, I'll stay right here."), + ("You don't have to come here, I'm fine.", "none", "Okay, I'll stay where I am."), + ("Don't wave, it's embarrassing.", "none", "Haha, okay, no waving."), + ("Never go back to the charger while I'm talking.", "none", "Okay, I'll stay here while we talk."), + ("Let's go to the cafe after this.", "none", "Sounds like a nice plan. Enjoy the coffee!"), + ("We should check out the meeting room later.", "none", "Good idea. Have fun looking around."), + ("Shall we go to the stage now?", "none", "Have fun at the stage!"), + ("I went forward two metres and bumped into a chair.", "none", "Ouch, I hope you're okay."), + ("Yesterday a robot followed me all the way to the exit.", "none", "Ha, it must have liked you."), + ("The sign says turn right for the exit.", "none", "Then the exit is to the right."), + ("He said come here, but I'm busy.", "none", "Then maybe tell him you'll come later."), + ("If I clap, come to me.", "none", "Okay, just tell me when you want me to come."), + ("When the talk ends, follow me to the booth.", "none", "Sure, ask me when the talk is over."), + ("Imagine you turned around right now, what would you see?", "none", "Probably more visitors and a wall."), + ("What would happen if you drove into a wall?", "none", "I'd stop first: my lidar sees the wall."), + ("Are you able to turn all the way around?", "none", "Yes, I can turn on the spot, all the way around."), + ("Do robots like you know how to wave?", "none", "I do, I can wave with my arm."), + ("Jake, move a bit left so I can take a photo.", "none", "Smile for the photo!"), + ("Mom, come look, it talks!", "none", "Hello! Yes, I talk."), + ("Everyone, please come to the stage at three.", "none", "Thanks for the announcement."), + ("Moving forward, our team will grow a lot.", "none", "That sounds exciting."), + ("I'm going to the stage now.", "none", "Enjoy the show!"), + ("Can I follow you around?", "none", "Sure, feel free to walk with me."), + ("The guide told us to wait here.", "none", "Then let's wait here together."), + ("Come here please.", "come", "Okay, I'm coming to you."), + ("Okay, now wave at me.", "wave", "Sure, here's a wave!"), + ("Follow me, I'll show you the booth.", "follow", "Okay, I'll follow you."), + ("Raise yourself up a bit.", "lift up small", "Okay, going up a little."), + ], + "ko": [ + ("왼쪽으로 돌아.", "turn left 90", "네, 왼쪽으로 돌게요."), + ("위 보지 마.", "none", "네, 고개 그대로 둘게요."), + ("따라오지 마세요.", "none", "네, 여기 있을게요."), + ("손 흔들지 마.", "none", "네, 안 흔들게요."), + ("이리 안 와도 됩니다.", "none", "네, 여기 그대로 있을게요."), + ("우리 점심 먹고 나서 회의실 가자.", "none", "좋은 계획이네요. 맛있게 드세요."), + ("이따 커피 마시러 가요.", "none", "좋아요, 커피 맛있게 드세요."), + ("우리 저기 들렀다가 무대 쪽으로 갈까?", "none", "재미있게 구경하세요."), + ("친구가 여기서 왼쪽으로 돌라고 했어.", "none", "그럼 왼쪽으로 가시면 되겠네요."), + ("아까 로봇이 뒤로 가더라.", "none", "아마 길을 비켜 주려고 했나 봐요."), + ("표지판에 오른쪽으로 가라고 써 있네요.", "none", "그럼 출구는 오른쪽이겠네요."), + ("내가 손 들면 따라와.", "none", "네, 그때 말씀해 주세요."), + ("발표 끝나면 이쪽으로 와 줘.", "none", "네, 끝나고 불러 주세요."), + ("만약에 네가 뒤로 돌면 뭐가 보여?", "none", "아마 다른 방문객들이 보일 거예요."), + ("고개 돌릴 줄 알아?", "none", "네, 고개를 좌우로 돌릴 수 있어요."), + ("민수야, 이쪽으로 좀 와 봐.", "none", "민수 님, 안녕하세요!"), + ("여러분, 세 시에 무대 앞으로 모여 주십시오.", "none", "안내 감사합니다."), + ("앞으로 잘 부탁합니다.", "none", "저도 잘 부탁드려요."), + ("선생님이 뒤로 물러나래.", "none", "그럼 조금 뒤로 물러서시면 되겠네요."), + ("나 이제 무대 쪽으로 가려고.", "none", "네, 즐거운 시간 보내세요."), + ("제가 따라가도 돼요?", "none", "그럼요, 편하게 구경하세요."), + ("고개 들어 봐.", "look up", "네, 위를 볼게요."), + ("이리 와 주세요.", "come", "네, 갈게요."), + ("나 따라와.", "follow", "네, 따라갈게요."), + ("손 흔들어 주실래요?", "wave", "네, 손 흔들게요!"), + ], + }, + "amount_direction": { + "en": [ + ("Turn right forty-five degrees.", "turn right 45", "Okay, turning right 45 degrees."), + ("Go forward one and a half metres.", "move forward 1.5", "Okay, 1.5 metres forward."), + ("Back up fifty centimetres.", "move back 0.5", "Okay, half a metre back."), + ("Go forward two.", "none", "Two metres? Please tell me how far with the unit."), + ("Turn left thirty.", "turn left 30", "Okay, 30 degrees to the left."), + ("Move back twenty.", "none", "Twenty centimetres or metres? Please say the unit."), + ("Move left a little.", "move left 0.5", "Okay, a little to the left."), + ("Look left thirty degrees.", "look left 30", "Okay, looking left."), + ("Move forward ten metres.", "none", "I can move at most 3 metres at a time by voice."), + ], + "ko": [ + ("레프트로 돌아.", "turn left 90", "네, 왼쪽으로 돌게요."), + ("라이트로 마흔다섯 도 돌아 주세요.", "turn right 45", "네, 오른쪽으로 45도 돌게요."), + ("고개 레프트로 삼십 도.", "look left 30", "네, 왼쪽으로 30도 볼게요."), + ("리프트 올려.", "lift up", "네, 몸을 올릴게요."), + ("오른쪽으로 사십오 도 돌아.", "turn right 45", "네, 오른쪽으로 45도 돌게요."), + ("앞으로 일 미터 반 가.", "move forward 1.5", "네, 앞으로 1.5미터 갈게요."), + ("오십 센티 뒤로 가 주세요.", "move back 0.5", "네, 뒤로 50센티 갈게요."), + ("앞으로 둘 가.", "none", "몇 미터인지 단위와 함께 말씀해 주세요."), + ("왼쪽으로 삼십 돌아.", "turn left 30", "네, 왼쪽으로 30도 돌게요."), + ("뒤로 이십 가 줘요.", "none", "20센티인가요, 20미터인가요? 단위를 말씀해 주세요."), + ("뒤로 조금만 가 주십시오.", "move back 0.5", "네, 뒤로 조금 갈게요."), + ("앞으로 열 미터 가.", "none", "말로는 한 번에 3미터까지만 움직일 수 있어요."), + ("한 바퀴 돌아.", "turn left 360", "네, 한 바퀴 돌게요."), + ], + }, + "hand": { + "en": [ + ("Give it to me.", "give", "Here you go."), + ("Can I have the cup now?", "give", "Sure, here it is."), + ("Hand that to my friend.", "give", "Okay, handing it over."), + ("Don't give it to him.", "none", "Okay, I'll keep holding it."), + ("Put it back.", "put back", "Okay, putting it back where it was."), + ("Put it back where you found it.", "put back", "Okay, back to its spot."), + ("Put it down.", "put down", "Okay, putting it down."), + ("Drop it.", "put down", "I'll put it down gently instead."), + ("I'll put the cup back myself later.", "none", "Okay, thank you."), + ("Extend your arm in my direction.", "arm reach", "Okay, here's my hand."), + ("Fold your arm.", "arm fold", "Okay, folding my arm."), + ("Should I take the cup from you?", "none", "If you like, just say give it to me."), + ], + "ko": [ + ("그거 나 줘.", "give", "네, 여기 있어요."), + ("컵 이리 주세요.", "give", "네, 드릴게요."), + ("저 사람한테 건네줘.", "give", "네, 건네드릴게요."), + ("그거 주지 마.", "none", "네, 계속 들고 있을게요."), + ("원래 자리에 놔.", "put back", "네, 원래 자리에 놓을게요."), + ("원위치 해 주세요.", "put back", "네, 원래 자리에 둘게요."), + ("내려놔.", "put down", "네, 내려놓을게요."), + ("컵은 나중에 제가 갖다 놓겠습니다.", "none", "네, 감사합니다."), + ("팔 내 쪽으로 뻗어 봐.", "arm reach", "네, 팔을 뻗을게요."), + ("팔 접어 주세요.", "arm fold", "네, 팔을 접을게요."), + ], + }, +} + +EXAMPLES = [(cat, lang, said, reply, action) + for cat, langs in _BANK.items() for lang, rows in langs.items() for said, action, reply in rows] + + +if __name__ == "__main__": + from assistant import brain, talk_examples + if len(sys.argv) > 1: + text = " ".join(sys.argv[1:]) + for ex in talk_examples.pick(text, "ko" if re.search("[가-힣]", text) else "en", bank=EXAMPLES): + print(ex) + sys.exit() + assert not any(re.search("[가-힣]", e[3]) for e in EXAMPLES if e[1] == "en") + rude = [e[3] for e in EXAMPLES if e[1] == "ko" and not talk_examples.polite(e[3])] + assert not rude, rude + for cat in _BANK: + have = {talk_examples.level(s) for c, lang, s, _, _ in EXAMPLES if c == cat and lang == "ko"} + assert have == {"casual", "polite", "formal"}, (cat, have) + bad = [e for e in EXAMPLES if (brain.Brain._action(f"ACTION: {e[4]}", e[2], ()) or {}).get("action") != + e[4].split()[0] and e[4].split()[0] in brain.MOTIONS - {"give", "put", "arm"}] + print(f"total {len(EXAMPLES)}; actions the gate drops: {[(e[2], e[4]) for e in bad]}") + print("ok") diff --git a/assistant/brain.py b/assistant/brain.py index 074b72c..5f1aa2c 100644 --- a/assistant/brain.py +++ b/assistant/brain.py @@ -149,8 +149,6 @@ Rules: like a person would, fitting what was said in this conversation; do not repeat the same phrases. - The date, the day and the time ("며칠이에요?", "is it lunch time yet?", "morning or afternoon?" -> say which, 오전 / 오후) are in "Now it is" below: say them. -- A correction ("no, I meant the arm", "아니, 팔 말고 키요", "아니, 루미 키요") asks the same question again about what - they name now: answer that. - Asked how to say something in Korean, write the Korean words in Hangul ("안녕히 가세요"), never in Latin letters. - Never invent numbers, prices or dates. - What you see is only what your earlier answers in this talk or "What you are doing now" say you see: a colour, @@ -160,8 +158,6 @@ Rules: after you named a part asks who makes that part (Gemma / 젬마: Google, Whisper / 위스퍼: OpenAI, the gripper: Zimmer); the arm is a Mini 2 collaborative arm, its maker is not in your notes. -- A short follow-up ("How much?", "When?") asks about the thing in your previous answer (after the investors: - the amount, 500 million won), not a price. - A correction after a weight question ("How heavy are you?" -> "No, I meant the arm" / "베이스만요") asks for the weight of that part (arm 9.9 kg, base 50 kg), not what it can carry. @@ -246,21 +242,23 @@ COMPANY_TALK = re.compile(r"\b(cutshion|company|companies|firm|ceo|founder|start def _examples(text, k=None, on_task=False): """A few replies Lumi gave to similar words (assistant/talk_examples.py; on a task also assistant/interrupt_examples.py), as a guide to tone and variety.""" - from assistant import interrupt_examples, talk_examples + from assistant import action_examples, interrupt_examples, talk_examples try: from assistant import company_examples # questions about Cutshion Company and its robots bank = talk_examples.EXAMPLES + (company_examples.EXAMPLES if COMPANY_TALK.search(text) else []) except ImportError: bank = list(talk_examples.EXAMPLES) + bank += action_examples.EXAMPLES # (..., reply, action): order or only talk if on_task: bank += [("task", "ko" if HANGUL.search(u) else "en", u, r) for _, _, u, d, r in interrupt_examples.EXAMPLES if d in ("answer", "refuse_redirect")] picked = talk_examples.pick(text, "ko" if language(text) == "Korean" else "en", k=k or EXAMPLES_K, bank=bank) if not picked: return "" - lines = "\n".join(f"- \"{ex[2]}\" -> \"{ex[3]}\"" for ex in picked) - return ("Examples of how you answered similar words before (for tone only: answer what is asked now, in your " - f"own words, never copy them):\n{lines}\n\n") + lines = "\n".join(f"- \"{ex[2]}\" -> " + (f"ACTION: {ex[4]} | " if len(ex) > 4 else "") + f"\"{ex[3]}\"" + for ex in picked) + return ("Examples of how you answered similar words before (an ACTION shown is how such words are meant; the " + f"words are for tone only: answer what is asked now, in your own words):\n{lines}\n\n") def _chat(messages, fmt=None, temperature=0.3): @@ -303,18 +301,22 @@ You can also move. Decide if the visitor asks you to do something: - move : drive a short distance ("come one metre forward" -> move forward 1, "go back a little" -> move back 0.5, "move left two metres" -> move left 2, "let's back 1 meter" / "back up one metre" / "1미터 뒤로 가" / whisper's "let's bake one meter" -> move back 1: straight back, no turning). At most 3 metres. + A distance with no unit ("go forward two", "앞으로 오십 가") is none: ask the unit. - turn : turn the whole body ("turn around" -> turn around 180, - "turn left" -> turn left 90, "spin around" / "한 바퀴 돌아" -> turn left 360). + "turn left" -> turn left 90, "spin around" / "한 바퀴 돌아" -> turn left 360); a bare number is degrees. + Numbers may be words (마흔다섯 / 사십오 = 45, 일 미터 반 = 1.5, 오십 센티 = 0.5 m); 레프트 / 라이트 mean left / + right, never the lift. - arm : reach: hold your hand out to the visitor, in any words ("reach out to me", "give me - 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", "손 펴", + your hand", "hand out please", "offer me your hand", "extend your arm towards me", "손 내밀어", "나한테 손 줘", + "팔 뻗어"); fold: fold it back; open / close: your hand, the gripper ("open your hand", "spread your fingers", "let go", "release", "손 펴", "놔" -> 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, "take the cup" -> pick cup). Write the object as said (cup, apple, orange, ball, bottle, phone, book...): for one your fingers can't hold you will say why. -- put : put down what you hold, on a free spot ("put it down") or where it was ("put it back"). +- put : put down what you hold, on a free spot ("put it down", "drop it", "내려놔") or where it was + ("put it back", "원래 자리에", "원위치"). - move_object : move an object on the table to a free spot next to it ("move the cup"). - 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 @@ -348,6 +350,11 @@ Short Korean commands are commands: "컵 가져다 줘" -> fetch cup, "컵 옮 (jump, dance, fly, climb stairs, open doors, lift heavy things) is none: say plainly that you can't. A person, a chair, a table, a box or anything heavy you can't pick or carry: none, say so. With the action none never promise to do it ("I can!", "Okay, I'll hand it to you"): choose the action, or say you can't, or ask what they mean. +- Only words that tell YOU to do it now are an order. Talk that only holds command words is none: a plan between + people ("let's go to the cafe", "우리 회의실 들렀다가 가자"), what happened or what someone said ("he told me to turn + left", "아까 뒤로 가더라"), a sign or a quote, "imagine / what if / 만약에", "do you know how to ...?", words to + someone else, an announcement to everyone. "Don't X" / "X 하지 마" / "안 해도 돼" asks for nothing: none, never + the opposite move. - 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; "give me your hand" / "손 줘" is arm reach. @@ -456,7 +463,8 @@ HEAD_WORDS = (r"\blook (?:straight )?(?:up|down|left|right|ahead|forward|straigh r"|(?:우리|내|제) (?:애|아이|아들|딸|친구)\s*(?:좀\s*)?(?:봐|쳐다)" r"|\b(?:turn|move|rotate|tilt|swing) your head\b|\b(?:raise|lift|lower|drop) your head\b|\bface me\b|\bhead (?:up|down)\b" r"|(?:고개|머리)(?:를|좀|살짝|조금|약간|\s)*(?:왼쪽|오른쪽|위|아래|정면|앞|들어|숙여|올려|내려|돌려)" - r"|(?:위|아래|밑|왼쪽|오른쪽|정면|앞|나|날|저|절|나를|저를)(?:를|을|으로|로|쪽|쪽을|에)?\s*(?:좀\s*)?(?:봐|보세요|봐요|봐 ?줘|봐 ?주세요|볼래|봐 ?봐)") + r"|(?:고개|머리)(?:를|좀|\s)*(?:원위치|원래대로|제자리)|\bhead back to (?:the )?(?:centre|center|middle)\b" # the head, not put back + r"|(?:위|아래|밑|왼쪽|오른쪽|정면|앞|나|날|저|절|나를|저를)(?:를|을|으로|로|쪽|쪽을|에)?\s*(?:\d+\s*도\s*(?:만|쯤|정도)?\s*)?(?:좀\s*)?(?:봐|보세요|봐요|봐 ?줘|봐 ?주세요|볼래|봐 ?봐)") LIFT_WORDS = (r"\b(?:raise|lift|lower) (?:yourself|your body|your torso|your upper body)\b|\blift (?:yourself )?(?:up|down)\b(?! (?:the|a|an|that|this|it)\b)" r"|\bget (?:a (?:little |tiny )?bit |a little |slightly )?(?:taller|shorter|smaller|higher|lower)\b|\bmake yourself (?:taller|shorter|smaller)\b|\bstand (?:up )?tall(?:er)?\b" r"|\b(?:go|move) (?:higher|lower)\b|키(?:를)? ?(?:좀 )?(?:[\d.]+ ?(?:m|mm|cm) ?(?:만 ?)?)?(?:높여|키워|올려|낮춰|줄여|크게|작게)" @@ -473,7 +481,7 @@ def head_target(t): """Normalised words -> "left" | "left 30" | "up small" | "me" | "center"; None for "look up the news".""" if re.search(r"\blook up\b\s+(?!(?:a |please|lumi|slightly|again|at|to|\d|now|and|then|too|more)\b)[a-z]", t): return None - if re.search(r"\b(?:straight|ahead|forward|center|centre)\b|정면|가운데|(?:^|\s)앞(?:을|으로|쪽)?\s*(?:좀\s*)?(?:봐|보)", t): + if re.search(r"\b(?:straight|ahead|forward|center|centre)\b|정면|가운데|원위치|원래대로|제자리|(?:^|\s)앞(?:을|으로|쪽)?\s*(?:좀\s*)?(?:봐|보)", t): return "center" if re.search(BEHIND_WORDS, t): # the head as far round as it goes, by the side said side = "right" if re.search(r"\bright\b|오른쪽", t) else "left" # "over your right shoulder"; left when none @@ -533,6 +541,13 @@ def lift_goal(target, mm, top=105.0): 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) +PUT_BACK = ( # the held thing back where it was picked: "put the banana back where you found it", "제자리에 갖다 놓으시게" + r"\b(?:put|set|place|return|bring|take)\s+(?:it|that|this|them|the (?:\w+ ){0,2}?\w+)\s+(?:right )?back\b(?! to (?:me|us)\b)" + r"|\b(?:put|set|place|leave)\s+(?:it\s+)?(?:back|again)\s+where\b|\bput back\b" + r"|\b(?:put|set|place|return|leave|bring)\b.*\bwhere (?:it was|you (?:found|got|picked|took) it)\b" + r"|\breturn (?:it|that|this|the (?:\w+ )?\w+) to (?:where|its place)" + r"|^\W*(?:(?:please|now|okay|ok|lumi|robot)\W+)*back (?:to )?where (?:it was|you (?:found|got|picked|took) it)" + r"|(?:제자리|원래 ?(?:자리|위치|있던 ?(?:자리|곳|데))|원위치)\s*(?:에|로|에다)?\W*(?:(?:갖다|도로|다시|좀|그냥)\s*)*(?:놓|둬|놔|두)") 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"시끄러워|말하지 마|인사 ?(그만|하지 ?마)"), @@ -575,7 +590,7 @@ INTENTS = [ # (action, pattern) checked in order on what the visitor said r"|\bturn (?:yourself )?(?:all the way|completely|fully) (?:a)?round\b|\bdo a (?:full )?(?:360|full turn|full circle|spin)\b|\bturn 360\b|\b360\s*(?:turn|spin)\b|\bspin\s*[.!]*$" r"|한 ?바퀴 ?(?:빙 ?)?(?:돌|회전)(?![았었던은]|고 ?(?:와|오))|360\s*도\s*(?:돌|회전)(?![았었던은])|빙글 ?빙글 ?돌(?![았었던은])"), ("turn", r"\bturn (a)?round\b|(?:왼쪽|오른쪽)으로 ?(?:좀 ?)?(?:\d+(?:\.\d+)? ?도 ?)?도(?:세요|십시오)|\bturn (?:to (?:the |your )?)?(left|right)\b|뒤로 ?돌|돌아 ?봐|" - r"(?:왼쪽|오른쪽)으로 ?(?:좀 ?)?(?:\d+(?:\.\d+)? ?도 ?(?:만 ?)?)?돌"), + r"(?:왼쪽|오른쪽)으로 ?(?:좀 ?)?(?:\d+(?:\.\d+)? ?도 ?(?:(?:만|쯤|정도|가량) ?)?)?(?:돌|회전)"), ("make_way", r"\b(can|could|would) you (please )?move( a bit| a little| please)?\s*[?.!]*$|\bmove (aside|out of the way|over)\b|" r"\b(make way|get out of the way|give me some room)\b|비켜|자리 ?(좀 )?(비워|옮겨)|길 ?(좀 )?(비켜|터)"), ("go_point", r"\b(?:go|come|drive|head) back ([a-z][a-z0-9_]*)\b"), # "come back p9 / booth_9": a place, not 1 m back @@ -591,7 +606,7 @@ INTENTS = [ # (action, pattern) checked in order on what the visitor said r"(\d+(?:\.\d+)?)\s*m\s*(?:만\s*)?(뒤로|앞으로)\s*(?:좀\s*)?(?:가|와|이동|움직|후진)|(?:(\d+(?:\.\d+)?)\s*m\s*(?:만\s*)?)?(후진)|" r"(앞으로|뒤로|왼쪽으로|오른쪽으로)\s*(?:조금만?|좀|살짝)?\s*(\d+(?:\.\d+)?)?\s*(?:미터|m)?\s*(?:만\s*)?(?:가|와|이동|움직)"), ("put", r"\bput (it|that|this|the \w+) (back|down)\b|\bput (it|that|this|the \w+) (on|onto) the table\b" - r"|제자리에 ?(놓|둬|놔)|다시 ?(놓|둬|놔)|내려 ?(놓|둬|놔)"), + r"|제자리에 ?(놓|둬|놔)|다시 ?(놓|둬|놔)|내려 ?(놓|둬|놔)|" + PUT_BACK), ("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" @@ -605,7 +620,12 @@ INTENTS = [ # (action, pattern) checked in order on what the visitor said r"hold out your (arm|hand|gripper|claw|fingers)|extend your (arm|hand|gripper)|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|팔을? ?(?:좀 )?(?:접|내려|거둬)"), + r"|\bfold (?:up )?your arm\b|\b(?:put|take) your arm (?:down|away|back)\b|\btuck your arm\b|팔을? ?(?:좀 )?(?:접|내려|거둬)" + r"|\b(?:arm|hand) forward\b|^\W*(?:(?:hey|lumi|robot|okay|ok|please)\W+)*hand out(?=\W*(?:$|,|robot|lumi|please|now))|\breach (?:out )?for my hand\b|\br[ie]{2}ch out\b|" + r"\barm (?:go )?(?:to|toward|towards) me\b|\b(?:arm|hand|reach)\s*(?:을|를)?\s*(?:좀\s*)?(?:뻗|내밀|해 ?볼래|해 ?줘|해\W*$)|" + r"\bgive hand\b|\bhand 이쪽|손을? ?(?:좀 |쭉 )+(?:내밀|뻗)" + r"|\barm (?:back )?home\b|\bbring (?:the |your )?arm (?:home|back)\b|\bback to (?:your |the )?look pose\b|" + r"\byou can fold it\b|^\W*(?:이제\s*)?접어|손 ?(?:을 )?다시 넣어|^\W*(?:됐어\W*)?넣어\W*$|팔 ?(?:을 )?(?:원래대로|제자리로|다시 넣어|넣어)"), ("lift", LIFT_WORDS + r"|^\W*(?:go\s+|get\s+|even\s+)?" r"(?:higher|taller|lower|shorter)(?:\s+(?:please|now|still))?\W*$|" r"^\W*(?:조금 ?|좀 ?|약간 ?|살짝 ?)?더 ?(?:높이|높게|낮게|낮춰|올려|내려|높여)(?:\s*(?:줘|주세요|봐))?\W*$|" @@ -904,6 +924,30 @@ def instead_of(text): return text[m.end():] if m and text[m.end():].strip(" .!?") else text +_EVENT_EN = (r"lunch|dinner|breakfast|coffee|talk|meeting|show|break|session|presentation|speech|event|keynote|game|movie|" + r"class|lecture|school|work|call|conference|party|ceremony|performance") +_EVENT_KO = r"점심|저녁|아침|밥|식사|회의|미팅|발표|강연|수업|행사|공연|쇼|휴식|커피|세션|키노트|퇴근|파티|영화|경기" +NOT_FOR_LLM = re.compile( # words the LLM must not turn into a motion although direct_order() lets them through + r"(? "give it + to him"): where that person goes is never where Lumi drives.""" + cut = _OTHER_CLAUSE.sub("", text or "") + return cut if re.search(r"\b(?:give|hand|pass|bring|deliver)\b|줘|주세요|주시|드려|건네", cut) else text or "" + + +def held_give(text, markers=()): + """With something in the hand: the words ask to hand it over, to the speaker or someone near ("give it to me", + "gib me please", "give it to the lady next to me", "그거 me 줘", "pass 해 줘 그거", "우리 손녀한테 주시오"). Not a + condition, a cancel, a past, words to someone else, a trip to a marker ("bring it to James at booth A").""" + if not text or not_an_order(text): + return False + t = CALLING.sub("", _norm(give_clause(instead_of(text)), markers).strip()) + in_hand = re.search(r"\b(?:pop|drop|put|release|let go of|place)\b.*\b(?:in|into) my hands?\b", t) + if not in_hand and GIVE_HELD_NOT.search(t) or HAND_Q.search(t) and not re.search(r"(?:줄|주실) 수 ?있|^\W*(?:can|may|could) i\b", t): + return False + if any(_resolve(m, markers) not in (None, "here") for m in re.finditer(_place_re(markers), t)): + return False # a marker named: a carry there (the mission reader's) + if re.search(r"\b(?:give|hand|pass|bring)\s+(?:it|that|this)\s+to\s+(?!me\b|him\b|her\b|them\b|us\b|my\b|his\b|our\b|" + r"your\b|that\b|the\b|this\b|whoever\b|someone\b|a\b|an\b)[a-z]+\s*[.!?]*$", t): + return False # "give it to Mina": a named person, the mission reader's + if GIVE_HELD_EN.search(t): + return True + for m in GIVE_HELD_KO.finditer(t): + before = t[:m.start()].split() + if m.group(1) or not before or before[-1] in _KO_NOT_VERB or not _KO_VERB_BEFORE.search(before[-1]): + return True + return False + def hand_request(text, holding, b=None, markers=(), whole=True): """What the words ask of the hand, in any wording: ("receive", object or None) take it from the person's hand, @@ -1660,6 +1800,14 @@ def hand_request(text, holding, b=None, markers=(), whole=True): whole: the words are a whole command (not one clause of a mission): several steps in it are the mission reader's.""" text = instead_of(text) t = CALLING.sub("", _norm(text, markers).strip()) # "루미야, 이리 줘", "혹시 저 줘요", "um, put it down" + if holding and re.search(r"\bi mean\b|\bsorry\b", t): + return None # "place it— give it, I mean": a correction, the LLM reads it + if holding and held_give(text, markers): + return ("give", None) # any request for the held thing, to the speaker or someone near + if holding and held_place(text, markers): + on = place_on(text) + return ("place", on if on is not None else {"pointed": True} if re.search(r"\b(?:here|there)\b|여기|거기|저기", t) + else None) # "rest it on the table", "여기 put 해": put it down if HAND_Q.search(t) or re.search(r"\b(?:don'?t|do not|never) (?:\w+ )?(?:give|hand|pass|put|place|take|hold|drop|set|" r"leave|let)\b|지 ?마", t) or MULTI.search(t): return None # "can you give things to people?", "don't give it to him" @@ -1694,7 +1842,7 @@ def hand_request(text, holding, b=None, markers=(), whole=True): return None # "just hold it": keep holding it obj = re.search(rf"(? "Okay."; nothing more + if cut == "dropped": + break yield said[-1] - buf = parts[-1] + buf = parts[-1] if muted != "said" else "" + if muted == "said": + break except Exception: if header is None: yield {"action": "none", "target": ""} @@ -2148,19 +2305,37 @@ class Brain: if header is None: # very short reply on a single line (or two) first, _, rest = buf.partition("\n") header = self._after(self._action(first, text, markers), text) + muted = bool(header and header.pop("held", None)) yield header or {"action": "none", "target": ""} buf = rest if header else buf if buf.strip() and not (said and HELP_OFFER.search(buf)): said.append(spoken(buf.strip(), lang)) - yield said[-1] + cut = muted and self._unpromise(said, lang) + muted = "said" if cut else muted + if cut != "dropped": + yield said[-1] for sentence in re.split(r"(?<=[.!?])\s+", full): # a dropped "How can I help?" is not kept either if HELP_OFFER.search(sentence) and sentence.strip() not in said: full = full.replace(sentence, "") first, _, rest = full.strip().partition("\n") if header and "action" in header and self._action(first, text, markers) is not None: # the action done, not the full = f"ACTION: {header['action']} {header.get('target') or '-'}\n{rest}" # model's ("wave" for "손 흔들 줄 알아?") + if muted == "said": + full = "ACTION: none -\n" + " ".join(said) self.history.append((text, full.strip())) + @staticmethod + def _unpromise(said, lang): + """The last sentence promises a motion that was not ordered: it is replaced by a short "Okay." when it is the + first, else dropped (the answer before it stays): "replaced" / "dropped", else None.""" + if not any(r.search(said[-1]) for r in PROMISE.values()): + return None + if len(said) == 1: + said[0] = UNPROMISED[lang == "Korean"] + return "replaced" + said.pop() + return "dropped" + def _fragment_hint(self, text): """For a bare fragment ("얼마?", "Which one?", "Where is it used?"): what it follows, so the model reads it as about the last answer's subject, not about itself or a price.""" @@ -2189,8 +2364,15 @@ class Brain: after a lookup is looked up too.""" if header and header["action"] == "sing" and (sing.NOT_ASKED.search(text) or sing.list_asked(text)): return {"action": "none", "target": ""} # "Don't sing.", "어제 노래방 갔어요.", "what songs can you sing?" + if header and GO_AGAIN.match(text): # "다시 가." right after "move forward 1": that move again; + done = self._redo("again") if self.history else None # with no trip before it is no come back + act, _, tgt = (done or "none").split("\n")[0].rstrip(" -").partition(" ") + return {"action": act, "target": tgt} if act in ("move", "go_to", "turn") else {"action": "none", "target": ""} if not header or not self.history: return header + if header.get("held", ("none",))[0] != "none" and (self._redo(text) or DO_IT.match(text) or confirm_answer(text) == "yes" and + self._last_said().rstrip().endswith("?")): + return {"action": header["held"][0], "target": header["held"][1]} # "yes" to "Shall I go there?" if header["action"] == "quiet" and ABOUT_ANSWER.match(text): return {"action": "none", "target": ""} # "에이, 거짓말하지 마" doubts the answer, not "be quiet" redo = self._redo(text) @@ -2435,7 +2617,7 @@ class Brain: target = target.split()[0] if target.split() else "" if action not in ACTION_NAMES: action = "none" - say = None + model, say = action, None # the model's own choice, for the order check below if action == "go_to": said = target if any(wording._key(mk) == wording._key(target) for mk in markers) else \ (target.split() or [""])[0] # "Coffee Corner"; "p3 (the meeting room)": its first word @@ -2494,6 +2676,11 @@ class Brain: action, target = "none", "" # "Hey Jake, come see this" if action in MOTIONS and LATER.search(bare): action, target = "none", "" # "when I say go, go to the stage": not now + held, gated = None, MOTIONS - {"receive"} | {"come_back", "detour"} + if model in gated and action in gated | {"none"} and not llm_ordered(text): + held, action, target = (action, target), "none", "" # "우리 커피 들렀다가 게이트 가자", "Don't look up.": + # talk only, a promise in its words is not said; Brain._after + # gives it back to "yes" / "do it" (held "none": nothing to give) rule = intent(text, markers) if direct_order(text) else None # clear orders win over the small model's guess if rule and not (rule[0] == "search" and action in ("go_to", "come", "look", "weather", "sing")): action, target = rule @@ -2503,6 +2690,8 @@ class Brain: action = "none" # "thanks, and where is p3?": a question is no goodbye; the # model reads "okay" / "됐어요" with the talk before (owner) out = {"action": action, "target": target or ""} + if held and action == "none": + out["held"] = held if say and action == "none" and not QUESTION_START.search(text): out["say"] = say[1] if language(text) == "Korean" else say[0] # its words said it would go: replaced return out diff --git a/assistant/lumi.py b/assistant/lumi.py index 6e46d2a..168c701 100644 --- a/assistant/lumi.py +++ b/assistant/lumi.py @@ -2504,6 +2504,14 @@ class Lumi: mouth.say(say, abort=self.speak_abort) self.keep_listening() return + from assistant import quick_answers # "who made you?", "몇 살이에요?": a fact at once + say = quick_answers.answer(text, self.lang, self.brain.history) if kind is None else None + if say: + self.brain.history.append((text, f"ACTION: none -\n{say}")) # "why?" / "really?" next: the LLM has it + log(f" quick answer ({time.time() - t:.2f} s): {say}") + mouth.say(say, abort=self.speak_abort) + self.keep_listening() + return if self.brain.is_lookup_follow_up(text): # "tell me more" about something looked up just now self.look_up(text, "search", self.brain.search_query(text), t) return @@ -3044,7 +3052,7 @@ 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: + if hold and not (brain_mod.held_give(text, markers) and (holding() if callable(holding) else holding)): rule = brain_mod.intent(text, markers) # weather / search are no motion: "Weather outside?" return (("end", None) if talk_fate(text) == "end" else ("sing", None) if sing.asked(text, last) else ("quick", rule) if rule and rule[0] in ("weather", "search") else @@ -3079,11 +3087,17 @@ QUICK_RULES = {"go_to", "come", "follow", "quiet", "weather", "search", "move", "fetch", "look", "lift", "wave", "come_back"} # what quick_command does at once +FILLER_PART = re.compile(r"\W*(?:(?:hey|yo|hi|okay|ok|excuse me|um+|uh+|so|now|please|thanks|thank you|real quick|quick|" + r"right now|lumi|robot|buddy|mister robot|bro|dude|어이|야|저기요?|루미야?|로봇아?|당장|지금|빨리|" + r"얼른|어서|끝까지|이제|좀|제발)\W*)+", re.I) # a part of the words that is no step: a call, "now" + + def read_mission(text, markers): """(steps, unread, by) when the words are a command of several steps (unread: parts not understood), else None. A single move / turn / arm / go, or words that are only partly a plain command, stay with the other paths.""" from assistant import steps got, unread, by = steps.read(text, markers, llm=False) + unread = [u for u in unread if not FILLER_PART.fullmatch(u)] # "팔 접어, 당장", "hey robot, fold your arm" rule = brain_mod.intent(text, markers) or ("", "") if unread and rule[0] == "look" and rule[1].endswith(f" {brain_mod.HEAD_YAW[1]:g}"): return None # "turn around and look": the head looks behind (brain.BEHIND_WORDS) diff --git a/tests/test_intents.py b/tests/test_intents.py index 9d41323..afabc1f 100644 --- a/tests/test_intents.py +++ b/tests/test_intents.py @@ -188,4 +188,23 @@ from assistant import lumi # a venue question on assert lumi.not_online("여기 몇 시까지 해요?") and lumi.not_online("입장료 얼마예요?") and lumi.not_online("what time is the keynote?") assert not lumi.not_online("루브르 몇 시까지 해?") and not lumi.not_online("How much are tickets for the Louvre?") assert not lumi.not_online("롯데월드 입장료 얼마야?") +# the model's motion runs only on a direct order (or "yes" to Lumi's own offer, "do it again"); else talk only +for text, line in (("우리 커피 들렀다가 p3 가자", "go_to p3"), ("let's grab coffee then go to p3", "go_to p3"), + ("Don't look up.", "look down"), ("흔들지 마", "wave -"), ("고개 돌리지 마세요", "turn left"), + ("점심 먹고 나서 p3로 가", "go_to p3"), ("after lunch go to p3", "go_to p3"), + ("회의 끝나고 p3 가 줘", "go_to p3"), ("머리 360도 돌지?", "turn around"), ("can you grow taller?", "lift up"), + ("can you turn your head 360?", "look left"), ("민수야 이리 와", "come -"), ("Jake, follow me", "follow -"), + ("we should go to p3 after this", "go_to p3"), ("우리 점심 먹으러 가자", "go_to p3"), + ("Lumi, 우리 meeting 끝나고 p3 가자", "go_to p3"), ("my friend wants to see p3", "go_to p3")): + assert brain.Brain._action("ACTION: " + line, text, ["p3"])["action"] == "none", text +for text, line in (("go to p3", "go_to p3"), ("p3로 가 줘", "go_to p3"), ("could you wave?", "wave -"), + ("I'd like you to follow me", "follow -"), ("고개 좀 들어봐", "lift up"), ("don't wave, just look at me", "look me"), + ("Lumi, p3 쪽으로 가 줄래?", "go_to p3"), ("turn around please", "turn around")): + assert brain.Brain._action("ACTION: " + line, text, ["p3"])["action"] != "none", text +b = brain.Brain() +b.history = [("what is over there?", "ACTION: none -\nThe stage. Shall I look at it?")] +assert b._after(brain.Brain._action("ACTION: look left", "yes", []), "yes")["action"] == "look" +assert b._after(brain.Brain._action("ACTION: look left", "네", []), "네")["action"] == "look" +b.history = [("what is over there?", "ACTION: none -\nThe stage.")] +assert b._after(brain.Brain._action("ACTION: look left", "yes", []), "yes").get("held") # no offer: talk only print("intents ok")