From e3fcfd30ab527ac3d70cef46afbd15f3ffde4e53 Mon Sep 17 00:00:00 2001 From: Cutshion Date: Mon, 26 Oct 2026 15:30:06 +0900 Subject: [PATCH] Improve command, cup task and talk understanding in English and Korean Co-Authored-By: Claude Opus 5.5 --- assistant/action_examples.py | 27 +- assistant/bank_words/fetch.py | 47 ++++ assistant/bank_words/korean.py | 24 ++ assistant/brain.py | 445 +++++++++++++++++++++++++++------ assistant/chain.py | 40 ++- assistant/detour.py | 4 + assistant/driving.py | 16 +- assistant/intent_bank.py | 73 +++++- assistant/lumi.py | 94 +++++-- assistant/steps.py | 134 ++++++++-- assistant/voice_words.py | 8 +- assistant/wording.py | 53 +++- tests/blind/README.md | 80 ++++++ tests/blind_check.py | 70 +++++- tests/command_check.py | 5 +- tests/dialogue_check.py | 6 +- tests/dialogues_night4.py | 71 +++++- tests/ko_levels_check.py | 13 +- tests/test_fetch_words.py | 151 +++++++++++ tests/test_followup.py | 23 ++ tests/test_ko_levels.py | 17 ++ tests/test_route_words.py | 142 +++++++++++ tests/test_wake.py | 4 +- 23 files changed, 1380 insertions(+), 167 deletions(-) create mode 100644 assistant/bank_words/fetch.py create mode 100644 tests/test_fetch_words.py create mode 100644 tests/test_ko_levels.py create mode 100644 tests/test_route_words.py diff --git a/assistant/action_examples.py b/assistant/action_examples.py index db9c634..332e707 100644 --- a/assistant/action_examples.py +++ b/assistant/action_examples.py @@ -211,6 +211,17 @@ _BANK = { ("What's the capital of Australia?", "none", "Canberra, not Sydney."), ("Who's the president of France right now?", "search", "Let me check."), ("What's the score of today's Dodgers game?", "search", "Let me check."), + ("how fast can a cheetah run?", "none", "Up to about 110 km/h, in short sprints."), + ("Why so fast?", "none", "A light body, a very bendy spine and long legs make each stride huge."), + ("A giraffe neck, how many bones it has?", "none", "Seven, the same as ours; each bone is just very long."), + ("How long does a baby kangaroo stay in the pouch?", "none", "About six to eight months, then it hops out."), + ("how much does a sloth sleep, like per day?", "none", "About 15 hours a day in the wild."), + ("Namsan tower height is how much?", "none", "N Seoul Tower is about 236 metres; on the mountain top about 480 metres above the sea."), + ("How quickly does a sunflower grow?", "none", "In good sun up to a few centimetres a day; it reaches two to three metres in a summer."), + ("Can elephants really not jump?", "none", "Yes, they can't: their legs are built to carry weight, and one foot always stays on the ground."), + ("Oh right, what's a hanok?", "none", "A traditional Korean house, with a tiled or thatched roof and floor heating."), + ("Wait, what's the coldest place on Earth?", "none", "Antarctica; near Vostok station it once fell to about minus 89 °C."), + ("What's the newest iPhone?", "search", "Let me check."), ], "ko": [ ("사람이 달에 처음 간 게 언제야?", "none", "1969년 7월, 아폴로 11호 때예요."), @@ -230,7 +241,21 @@ _BANK = { ("에펠탑은 언제 세워지셨는지 여쭤봐도 될까요?", "none", "1889년 파리 만국박람회 때 완공됐어요."), ("호주 수도가 어디게?", "none", "캔버라예요. 시드니가 아니에요."), ("지금 프랑스 대통령 누구야?", "search", "확인해 볼게요."), - ("오늘 야구 결과 어떻게 됐어요?", "search", "확인해 볼게요."), + ("오늘 야구 몇 대 몇으로 끝났어요?", "search", "확인해 볼게요."), + ("된장은 어떻게 만듭니까?", "none", "삶은 콩으로 메주를 쑤어 띄운 뒤 소금물에 담가 숙성시키고, 건더기를 건져 만듭니다."), + ("김치 맛을 시게 만드는 건 뭐임?", "none", "유산균이에요. 익으면서 젖산을 만들어서 신맛이 나요."), + ("치타는 을매나 빨리 뛰노?", "none", "짧게는 시속 110킬로미터쯤까지 달려요."), + ("기린 목뼈 그거 몇 개야?", "none", "일곱 개예요. 사람이랑 같은데 하나하나가 아주 길어요."), + ("캥거루 새끼는 주머니에 얼마나 있습니까?", "none", "약 6개월에서 8개월 동안 주머니에서 지냅니다."), + ("나무늘보는 하루에 얼마나 자요?", "none", "야생에서는 하루에 15시간쯤 자요."), + ("남산타워 height 몇 m예요?", "none", "N서울타워는 약 236미터이고, 산 위라서 해발로는 480미터쯤이에요."), + ("해바라기는 얼마나 빨리 커?", "none", "햇빛이 좋으면 하루에 몇 센티미터씩, 여름 한철에 2~3미터까지 자라요."), + ("코끼리가 점프를 못 한다는 게 참말이가?", "none", "네, 맞아요. 다리가 무게를 받치게 생겨서 항상 한 발은 땅에 있어요."), + ("고래는 숨을 얼마나 참으실 수 있는지 여쭤봐도 될까요?", "none", "향유고래는 한 시간 넘게도 참을 수 있어요."), + ("아 맞다, 판소리가 뭐야?", "none", "북 장단에 맞춰 한 사람이 노래와 말로 긴 이야기를 들려주는 우리 전통 음악이에요."), + ("잠깐, 세상에서 제일 긴 강은?", "none", "나일강이에요. 약 6,650킬로미터예요."), + ("그건 그렇고 정확히 몇 킬로?", "none", "약 6,650킬로미터예요. 아마존강과 비슷해서 재는 방법에 따라 달라요."), + ("요즘 나온 갤럭시 최신 모델 뭐야?", "search", "확인해 볼게요."), ], }, } diff --git a/assistant/bank_words/fetch.py b/assistant/bank_words/fetch.py new file mode 100644 index 0000000..e5193ce --- /dev/null +++ b/assistant/bank_words/fetch.py @@ -0,0 +1,47 @@ +"""Cup-task wordings for the intent bank (F1, night 4): fetch from a place said in every way ("the cup on p2", +"p2에 있는 컵", "피원 컵을", "move the cup from A to B", "옮겨"), at every Korean level; and "no": the same words +reported, asked about, put off or taken back (nothing moves). The words decide the fields (brain.parse_fetch).""" + +_KO_FETCH = ["에 있는 가져와", "에 있는 좀 갖다 줘", "에 놓인 가져와", + " 가져와", "의 가져다 줘", " 위에 있는 가져와", + "에서 집어서 가져와", "에서 들고 와", "에 있는 을 여기로 가져와", + "에서 좀 챙겨 와", "에 있는 옮겨 와"] +_KO_END = [("가져와", ["가져와", "가져와요", "가져오세요", "가져오십시오", "가져와 주세요", "가져와 주시겠어요?", + "가져와 주시겠습니까?", "가져와 줄래?", "가져오게", "가져와 주게나", "가져온나", "가져와유", + "가져와 주이소", "가져와 주실 수 있으신가요?", "가져와 주시면 감사하겠습니다"]), + ("갖다 줘", ["갖다 줘", "갖다 주세요", "갖다 주십시오", "갖다 주실래요?", "갖다 주게", "갖다 줘유", + "갖다 주이소", "갖다 주시겠어요?", "갖다 드려 주세요"]), + ("가져다 줘", ["가져다 줘", "가져다 주세요", "가져다 주십시오", "가져다 주시겠습니까?", "가져다 주게나"]), + ("들고 와", ["들고 와", "들고 와요", "들고 오세요", "들고 오십시오"]), + ("챙겨 와", ["챙겨 와", "챙겨 와요", "챙겨 오세요"]), + ("옮겨 와", ["옮겨 와", "옮겨 와 주세요", "옮겨 오십시오"])] + +_EN_FETCH = ["bring me the on ", "get me the that's on ", "fetch the sitting at ", + "grab the at and bring it here", "bring the over from ", + " , bring it to me", "go to , get the and bring it back to me", + "pick up the at and bring it to me", "the on , could you fetch it", + "move the from over here", "carry the from to me"] +_EN_FRAME = ["{}", "please {}", "could you {}", "would you mind, {}", "can you {} for me", "{} please", "lumi, {}", + "hey robot, {}", "excuse me, {}", "i need you to {}", "{} real quick", "do me a favour and {}"] + +_NO = ["did you bring the from ?", "you brought the from yesterday", "can you bring cups at all?", + "don't bring the from ", "i'll bring the from myself", "tomorrow bring the ", + "maybe later you can bring the from ", "my friend brought the from ", + "she asked whether you can fetch things", "bring me the from , no wait, never mind", + "에서 가져왔어?", "어제 가져왔지?", "에서 가져오지 마", "내가 가져올게", + "나중에 가져와 줘", " 가져올 수 있어?", "친구가 에서 가져왔대", " 가져오는 거 봤어", + "에서 가져와, 아 아니다 됐어", " 가져오시면 안 됩니다", " 가져다 주실 필요 없어요", + "할머니가 가져오라고 하셨는데 괜찮아", " 가져오는 건 내일 해", "에서 가져다 줄 수 있나 궁금하네"] + + +def _ko(): + """Each wording with the endings of every level for its verb.""" + out = [] + for base in _KO_FETCH: + for verb, ends in _KO_END: + if base.endswith(verb): + out += [f"{base[:-len(verb)].rstrip()} {e}" for e in ends] + return out + + +INTENT = {"fetch": sorted(set(_ko() + [f.format(c) for c in _EN_FETCH for f in _EN_FRAME])), "no": _NO} diff --git a/assistant/bank_words/korean.py b/assistant/bank_words/korean.py index 7ba7b70..f312dc5 100644 --- a/assistant/bank_words/korean.py +++ b/assistant/bank_words/korean.py @@ -227,3 +227,27 @@ QUICK["no"] = QUICK.get("no", []) + [ "시간 괜찮아요", "시간 돼요", "give me a second", "give me a minute", "give me some time", "do you have time", "이름 지어 줄까", "내 이름은 민수야", "제 이름 기억해요", "우리 애 몇 살 같아요", "제가 몇 살 같아요", "나 몇 살로 보여", "누가 이겼어", "누가 더 빨라", "몇 시에 끝나요", "몇 시에 시작해요"] + +# ---------- night 4: Konglish verbs and short dialect forms ko_plain does not turn into the plain verb ---------- +INTENT["pick"] += _v([" 그랩 해", " 그랩", " 픽 해", " 픽업해", " 캐치 해", " 홀드 해", + " 잡아 봐라", " 집어 도", " 쫌 집어"], ("", " 줘")) +INTENT["fetch"] += _v([" 겟 해 와", " 겟해 와", " 브링 해", " 가져와 봐라", " 갖고 온나", + " 퍼뜩 가져와", " 쫌 갖다 도", "나한테 브링"], ("", " 줘")) +INTENT["follow"] += _v(["팔로우 해", "나 팔로우", "날 팔로우", "come with 나", "나랑 같이 가", "같이 가자 루미", + "내 뒤로 붙어", "졸졸 따라 댕겨", "따라 온나"], ("", " 줘")) +INTENT["come"] += _v(["컴 히어", "컴온 히어", "이리로 컴", "여기로 컴", "가까이 컴", "이리 온나", "일로 온나", "이리 오이라"], + ("", " 해", " 해 줘")) +INTENT["wave"] += _v(["웨이브 해", "하이 해", "바이바이 해", "빠이빠이 해", "손 인사 해", "손으로 인사 해", "핸드 웨이브 해", + "손 흔들어 봐라", "손 쫌 흔들어"], ("", " 줘", " 봐")) +INTENT["arm_reach"] += _v(["손 줘라", "핸드 줘", "암 내밀어", "핸드 아웃 해", "손 쭉 내밀어 봐라", "팔 뻗어 봐라", + "손 이리 도", "손 쫌 도"], ("", " 줘")) +INTENT["arm_fold"] += _v(["암 다운 해", "암 폴드 해", "arm fold 해", "팔 원위치 해", "팔 집어넣어", "손 거둬 들여", + "팔 접어 봐라"], ("", " 줘")) +INTENT["look"] += _v(["룩 업 해", "룩 다운 해", "업 봐", "다운 봐", "레프트 봐", "라이트 봐", "위로 룩", "아래로 룩", + "고개 쫌 들어", "고개 쫌 숙여", "고개 들어 봐라", "고개 숙여 봐라"], ("", " 줘")) +INTENT["lift"] += _v(["바디 업", "바디 다운", "키 업", "키 다운", "몸 업", "몸 다운", "몸 쫌 올려", "몸 쫌 내려", + "키 쫌 키워", "키 쫌 줄여"], ("", " 해", " 해 줘")) +INTENT["turn"] += _v(["턴 해", "레프트 턴", "라이트 턴", "라이트로 턴", "레프트로 턴", "백 턴", "유턴 쫌", "한 바퀴 턴", + "왼쪽으로 돌아 봐라", "오른쪽으로 돌아 봐라"], ("", " 해", " 해 줘")) +INTENT["move"] += _v(["무브 포워드", "고 백", "백 해", "앞으로 무브", "뒤로 무브", "레프트로 무브", "라이트로 무브", + "앞으로 쪼매 가 봐라", "뒤로 쫌 빠져"], ("", " 줘")) diff --git a/assistant/brain.py b/assistant/brain.py index b02a3bc..1519c75 100644 --- a/assistant/brain.py +++ b/assistant/brain.py @@ -191,10 +191,13 @@ Facts you know (say the one that is asked, also in a short follow-up; nothing mo a passage at least 70 cm wide, no stairs. Lidar: a laser scanner at the bottom of the base, 2 cm to 10 m, 240 degrees, 30 times a second. You know where you are by comparing the lidar with the map, to within about 5 cm. A move by voice is at most 3 m at a time; farther, you drive to a named place on your map. -- 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). +- Battery: 24-volt lithium-ion, 45 Ah; lasts about 10 hours on a charge ("how long on a charge?", "배터리 몇 시간 + 가?", "three hours, right?": 10 hours, kept against a wrong number; how far you go is given in hours, no distance + is known; only how long charging itself takes is not known). On patrol below 5 percent you drive home to charge + and go on (start again) at 60 percent. - You are made for shops, hotels, schools, labs and exhibitions. You cannot dance, walk, jump or fly: say so. -- Computer ("processor", "chip", "칩", "컴퓨터"): NVIDIA Jetson AGX Thor (its graphics processor: Blackwell, 2070 TOPS). +- Computer ("processor", "chip", "칩", "컴퓨터"): NVIDIA Jetson AGX Thor (its graphics processor: Blackwell, 2070 TOPS; + 14 processor cores, 122 GB of memory / 메모리). - 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. - Cutshion: makes barista, AI drawing, cooking, ice cream, candy ball, welding, palletizing and educational @@ -289,7 +292,9 @@ def _notes(hits): return "\n\n".join(out) or "(no matching notes)" -SAID_BEFORE = re.compile(r"\byou said\b|\bearlier you\b|\byou told me\b|아까는|아까 .*(?:라며|했잖|말했)|전에는 .*(?:라며|했잖)", re.I) +SAID_BEFORE = re.compile(r"\byou said\b|\bearlier you\b|\byou told me\b|\bthat'?s not what you said\b|\b(?:changed|changing) your (?:answer|story)\b|" + r"\bdifferent (?:from|than) (?:before|earlier|what you said)\b|아까는|아까 .*(?:라며|했잖|말했)|전에는 .*(?:라며|했잖)|" + r"아까(?:랑|하고|와|캉|카고|이랑)\s*(?:\S+\s+)?(?:다르|달라|틀리|바뀌|바꼈)|말(?:이|을)?\s*(?:바뀐|바뀌|바꼈|바꾸|다르|달라)", re.I) # the visitor holds Lumi's own answer against it: the fact stays FOLLOW_EXAMPLES_K = 2 # follow-up examples (talk_examples.FOLLOWUPS) shown with a short follow-up @@ -406,7 +411,11 @@ Short Korean commands are commands: "컵 가져다 줘" -> fetch cup, "컵 옮 - 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...). Do not use search for things in the reference notes, the date or the time, nor for opinions, advice, fun - facts, recommendations or well-known general knowledge: answer those yourself. + facts, recommendations or well-known general knowledge: answer those yourself. Search only what changes or is + new (news, prices, scores, schedules, who holds an office now, the newest products). Everything that stays the + same is none, answered at once in any wording, dialect or mixed: what a word, a custom or a thing is ("윤초는 + 뭐예요?"), how it is made or works, why, an animal's or plant's body and life, a famous building's height or floors + ("부엉이 목 을매나 돌아가노?", "tower height 몇 m예요?"), and every follow-up on them. - Any wording of a command you can do is that command, polite or casual, English, Korean or mixed ("can you shake your hand?" -> wave, "고개 왼쪽으로 돌려" -> look left, "뒤로 1미터 가" -> move back 1). What your body can't do (jump, dance, fly, climb stairs, open doors, lift heavy things) is none: say plainly that you can't. A person, a @@ -494,7 +503,7 @@ OBJECTS = {"cup": "cup", "mug": "cup", "glass": "cup", "tumbler": "cup", "bottle "backpack": "backpack", "백팩": "backpack", "suitcase": "suitcase", "캐리어": "suitcase", "여행가방": "suitcase", "hair dryer": "hair drier", "hair drier": "hair drier", "드라이기": "hair drier", "toaster": "toaster", "토스터": "toaster", "보틀": "bottle", "물컵": "cup", "유리컵": "cup", "머그잔": "cup", - "글라스": "cup"} + "글라스": "cup", "애플": "apple", "바틀": "bottle"} # spoken word -> camera class; the classes are skills.GRASPS (tests/test_intents.py checks it): a pick of one the # fingers can't take gets its reason (skills.refusal). Not here on purpose: umbrella / 우산 (weather words), 책 (책상) _KO_WORD = {"공", "칼"} # one syllable inside other words (공항, 칼국수): only as a word of its own @@ -529,12 +538,15 @@ BEHIND_WORDS = (r"\blook(?:ing)? (?:over |to(?:wards?)? |at |in )?(?:the |your ) HEAD_WORDS = (r"\blook (?:straight )?(?:up|down|left|right|ahead|forward|straight|at me|behind|this way|over here|to (?:the|your|my) (?:left|right))\b" r"|\blook (?:a (?:little |bit )?)?(?:more |further )?(?:at|to|towards?|on|over|in) (?:the |your |my )?(?:left|right|front)(?: side)?\b" r"|\blook (?:a (?:little |bit )?)?(?:more|further) (?:to (?:the |your )?)?(?:left|right|up|down)\b" # "look at the left side" + r"|(?:왼쪽|오른쪽|좌측|우측)(?:(?:을|를|쪽)?\s*(?:한번\s*|좀\s*)?돌아\s?(?:봐|보)|으로\s*(?:한번\s*|좀\s*)?돌아(?:봐|보))" + # "왼쪽을 돌아봐", "오른쪽으로 돌아봐 줄래요?": the head; "왼쪽으로 돌아 봐" (try turning) is the base r"|" + BEHIND_WORDS + r"|\blook at (?:my|this|that|our) (?:son|daughter|kid|child|baby|friend|wife|husband|boy|girl|mom|dad)\b" 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)*(?:원위치|원래대로|제자리)|\bhead back to (?:the )?(?:centre|center|middle)\b" # the head, not put back + r"|(? "left" | "left 30" | "up small" | "me" | "center"; None for "look up the news".""" t = re.sub(r"^\W*(?:right|alright|all right|okay|ok)\s*[,.!]\s*", "", t) # "right, look at the floor": okay - 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): + t = re.sub(r"\b(?:right|straight|directly) (?=at (?:me|us)\b)|\bgo ahead and\b", "", t) # "look right at me": at me + if re.search(r"\blook up\b\s+(?!(?:a |please|lumi|slightly|again|at|to|\d|now|and|then|too|more)\b)(?!for (?:me|us)\W*$)[a-z]", t): return None if re.search(r"\b(?:straight|ahead|forward|center|centre|front)\b|정면|가운데|원위치|원래대로|제자리|(?:^|\s)앞(?:을|으로|쪽)?\s*(?:좀\s*)?(?:봐|보)", t): return "center" @@ -560,13 +573,13 @@ def head_target(t): side = "right" if re.search(r"\bright\b|오른쪽", t) else "left" # "over your right shoulder"; left when none return f"{side} {HEAD_YAW[1]:g}" for d, words in (("left", r"\bleft\b|왼쪽"), ("right", r"\bright\b|오른쪽"), - ("up", r"\bup\b|\braise\b|\blift\b|\bceiling\b|\bsky\b|위|들어|올려|천장|하늘"), - ("down", r"\bdown\b|\blower\b|\bdrop\b|\b(?:my |your |the )?(?:feet|shoes?|floor|ground)\b|아래|밑|숙여|내려|" + ("up", r"\bup\b|\braise\b|\blift\b|\bceiling\b|\bsky\b|위|들어(?!가|오|와)|올려|천장|하늘|룩\s*업"), + ("down", r"\bdown\b|\blower\b|\bdrop\b|\b(?:my |your |the )?(?:feet|shoes?|floor|ground)\b|아래|밑|숙여|내려|룩\s*다운|" r"바닥|발(?:을|밑|끝)?\s*(?:좀\s*)?봐|신발")): if re.search(words, t): deg = re.search(r"(\d+)\s*(?:degrees?|도)?", t) # a bare number on the head is degrees return f"{d} {deg.group(1)}" if deg else (f"{d} small" if SMALL.search(t) or MORE.search(t) else d) - if re.search(r"\b(?:at me|face me)\b|(?:^|\s)(?:나|날|저|절|나를|저를)\s*(?:좀\s*)?봐|\blook at (?:my|this|that|our) \w+|" + if re.search(r"\b(?:at me|face me)\b|룩\s*앳\s*미|(?:^|\s)(?:나|날|저|절|나를|저를)\s*(?:좀\s*)?봐|\blook at (?:my|this|that|our) \w+|" r"(?:우리|내|제) (?:애|아이|아들|딸|친구)", t): # "look at my son": towards whoever speaks return "me" # after the directions: "look down at me" is down return None @@ -634,7 +647,7 @@ PUT_BACK = ( # the held thing back where it was picked: "put the banana back w 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*)*(?:놓|둬|놔|두)" + r"|(?:제자리|원래 ?(?:자리|위치|있던 ?(?:자리|곳|데))|있던 ?(?:자리|곳|데)|원위치)\s*(?:에|로|에다)?\W*(?:(?:갖다|도로|다시|좀|그냥|지금|당장|얼른|빨리|어서|퍼뜩|싸게)\s*)*(?:놓|둬|놔|두)" r"|\breturn (?:it|that|this|the (?:\w+ )?\w+) to (?:its|the|your) (?:spot|place)\b|\bputt (?:it|that|this) back\b" r"|^\W*(?:(?:robot|lumi|please|now|okay|ok)\W+)*return (?:it|that|this|the (?:\w+ )?\w+)\W*$|(?:원래 ?자리|제자리)\s*(?:로\s*)?back\b|\breturn\s*해") INTENTS = [ # (action, pattern) checked in order on what the visitor said @@ -650,13 +663,13 @@ INTENTS = [ # (action, pattern) checked in order on what the visitor said ("stop", r"\b(stop|halt|freeze|don'?t move)\b|멈춰|정지|그만 ?가|거기 ?서(?=[\s!.~,]*$)|스톱|움직이지 ?마|^\s*(서[\s,!.]*){2,}$"), ("waist", r"\b(?:turn|rotate|twist|swivel|swing|move|bring|point|face|put)\b[^.?!]{0,25}\b(?:your |the )?(?:waist|upper body|" r"torso|hips?)\b|\b(?:waist|upper body|torso)\b[^.?!]{0,20}\b(?:left|right|front|forward|center|centre|straight|back|" - r"\d+)|(?:허리|상체|몸통|윗몸)(?:를|을|만|좀|\s)*[^.?!]{0,15}(?:돌려|돌리|틀어|비틀|돌아|원위치|정면|가운데|앞으로|원래대로)|" + r"\d+)|(?:허리|상체|몸통(?!째)|윗몸|웨이스트)(?:를|을|만|좀|\s)*[^.?!]{0,15}(?:돌려|돌리|돌릴|틀어|비틀|돌아|원위치|정면|가운데|앞으로|원래대로)|" r"\bwaist\b\s*(?:left|right|turn|돌려|왼쪽|오른쪽)|(?:왼쪽|오른쪽)으?로?\s*(?:허리|상체)|" r"\b(?:turn|swivel|twist|rotate) your (?:body|trunk)\b[^.?!]{0,30}\bwithout (?:driving|moving (?:your )?(?:base|wheels))|" r"\b(?:turn|swivel|twist|rotate) your trunk\b|허리(?:를)? ?(?:좀 ?)?(?:펴|곧게)|\btorso\b.{0,6}(?:정면|front)"), # ^ the waist (upper body) only, never the base: "turn your waist left", "허리 왼쪽으로 돌려", "상체 정면으로" ("follow", r"\b(?:follow|following|come with|come along with|come together with|walk with|tag along with)\s+(?:me|us)\b(?!\s+(?:on|at)\b)|" # not "follow - r"\bcome along\b|(?[가-힣]{2})(?P아|야)[\s,!~]|" r"(?:thank you|땡큐|고맙습니다|감사합니다|안녕하세요|인사)\s*(?:해야지|해|하세요|해 ?봐|드려야지|드려)[\s.!~]*$") # "thank you 해": a parent to a child @@ -850,7 +881,7 @@ NOT_NAME = {"루미", "누미", "류미", "무미", "루비", "루니", "아니" def to_someone_else(text): """"Hey Jake, come see this", "Mom, look!", "민수야 이리 와 봐": said to another person nearby, not an order to Lumi.""" if ASIDE_EN.search(text) or re.match(r"^\W*(?:야|얘)[\s,!]+(?!.*(?:루미|로봇|lumi))", text, re.I) or \ - re.match(r"^\W*my (?:friend|dear|buddy)\s*,", text, re.I): + re.match(r"^\W*my (?:friend|dear|buddy|son|daughter|boy|girl|kid|baby|love|darling)\s*,", text, re.I): return True # "야 그 사과 좀 집어 줘", "my friend, you follow me" for m in re.finditer(r"[,\s]([가-힣]{2})(아|야)(?=[\s,!~.]|$)", text): # "그거 내려놔, 지훈아 깨져" c = m.group(1)[-1] @@ -878,14 +909,15 @@ CONDITION = re.compile( # a condition or a later time: "when the show starts, 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|\W*$)|[가-힣](? "팔 뻗어", "reach out, no, fold it" -> "fold your arm"; None when the right part is no arm move.""" bare = re.sub(r"^(?:(?:그냥|just|then|좀)\s+)+", "", right.strip(" ,.!?")) - noun = "손" if re.search(r"손|\bhand\b", left) and not re.search(r"팔|\barm\b", left) else "팔" + noun ="손" if re.search(r"손|\bhand\b", left) and not re.search(r"팔|\barm\b", left) else "팔" for c in (bare, f"{noun} {bare}", re.sub(r"\b(?:it|that)\b", "your arm", bare)): if (intent(c, markers) or ("",))[0] in ("arm", "wave"): return c @@ -1501,7 +1578,13 @@ def self_correct(text, markers=()): re.search(r"\b(?:stop|halt|freeze|don'?t move)\b|멈춰|정지|그만(?!두|둬)|스톱|움직이지 ?마|거기 ?서", text, re.I): return text # a message to say may hold any words; a stop always wins # ("그만둬" / "그만두게" is a take-back: below) - t = wording.ko_plain(wording.norm(text, markers)) # "왼쪽 보세요, 아 아니 정면이요": every speech level as 반말 + cut = re.sub(r"(?<=\S)(?=[—–]+\s*(?:아니|아\s|잘못|no\b|nope\b|wait\b|scratch\b|actually\b))", " ", text, flags=re.I) + # ^ "135도 돌아— 아니 왼편으로": a cut-off, not norm's stutter ("돌아— 아니" read as "아— 아" said twice) + t = wording.ko_plain(wording.norm(cut, markers)) # "왼쪽 보세요, 아 아니 정면이요": every speech level as 반말 + if TAKEN_BACK.search(t) or re.search(r"[,.!?]\s*(?:아니(?:야|요)?\s*)?그냥 ?(?:있어|계세요|둬|놔둬|들고 있어)(?:요)?\W*$", t): + return "" # "이제 팔 접어 좀. 아니야 그냥 있어": taken back + if DRINK.search(t) and FIX.search(t): + return None # "사과 가져와 아니 아니 커피 한 잔 가져와": a drink, never a cup t = re.sub(r"\s*(?:[—–…]+|--|\.{3})\s*(?:(?:no|actually|wait|oh|아니|아)\W+)*(?:keep it|hold (?:it|on to it)|leave it|" r"just keep it|never ?mind|forget it|그냥 (?:둬|놔둬|들고 있어)(?:요)?|(?:아니\s*)?됐어(?:요)?)(?:\W+(?:keep it|" r"hold (?:it|on to it)|just keep it|그냥 (?:둬|놔둬)(?:요)?))*\W*$", ", never mind", t) # "give it to me — never @@ -1541,6 +1624,13 @@ def self_correct(text, markers=()): continue first, *rest = steps._SPLIT.split(right, maxsplit=1) lk, rk = _fix_kinds(left, markers), _fix_kinds(first, markers) + from assistant import chain + if not rest and chain._restated(first, left) and _reads(left, markers) and \ + all(w in left for w in re.findall(r"[가-힣]+", wording.ko_plain(first))[:-1] + if w not in ("좀", "혹시", "그럼", "그냥", "다시", "제발")) and \ + not set(rk) - {"direction"} and not re.search(r"\d|왼|오른|좌|우측|앞|뒤로|\b(?:left|right|forward|back)\b", first): + t = left # "좌측으로 20센티 움직여 줘, 아니 움직이실래요?": the same order + continue # said again more politely, not a new one tail = re.sub(r"\s+", " ", "".join( ch for ch in re.sub("|".join(x.group(0).replace(".", r"\.") for k in rk for x in rk[k]) or r"(?!)", " ", first))) tail = re.sub(r"^(?:\s*(?:the|a|an|one|to|으로|로|을|를|에|만|instead|then|please|is|it'?s)\b\s*)+|" @@ -1557,6 +1647,10 @@ def self_correct(text, markers=()): return f"{keep}, {first}" if keep else first if rk and tail and set(rk) >= set(_fix_kinds(clauses[-1], markers)) and _reads(first, markers): new = instead() # "go to start, no, go to end", "start로 가, 아니 end로 가서 줘" + elif "direction" in rk and tail and _reads(first, markers) and \ + {x.group(0) for x in rk["direction"]} != {x.group(0) for x in lk.get("direction", [])}: + new = instead() # "오른쪽으로 135도 돌아, 아 잘못 말했다, 몸통째 왼쪽으로 돌려": a new + # order said in full, nothing of the first one kept elif not rk and re.fullmatch(r"\d+(?:\.\d+)?", first) and (nums := list(re.finditer(r"\d+(?:\.\d+)?", left))): x = nums[-1] # "turn left 45 degrees, no, 30": the number fixed = left[:x.start()] + first + left[x.end():] @@ -1653,6 +1747,13 @@ def _as_place(name): return name if name in ("here", None) else {"marker": name} +_OBJ_ADJ = rf"(?:(?:{_COL}|작은|큰|왼쪽|오른쪽|가까운|먼|제일|가장)\s*)*+" # possessive: no backtracking +_AT_OBJ_EN = rf"\b(?:{_OBJ})s?,? (?:that'?s |that is |which is |sitting |lying |standing |left )?(?:on|at|by|near) (?:the )?$" +_AT_OBJ_KO = (rf"\s*(?:(?:위|쪽)\s*)?(?:에|의)\s*(?:(?:있는|있던|놓인|놓여\s*있는|둔|올려\s*둔|올려진|올라간|올라가\s*있는)\s*)?" + rf"{_OBJ_ADJ}(?:{_OBJ})|\s*(?:(?:에|의)\s*)?(?:있는|있던|놓인|놓여\s*있는|둔)\s*(?:거|것|걸)") +# ^ where the thing is ("the cup on p2", "p2에 있는 빨간 컵", "피원 컵", "p1의 컵"): the source, not where it goes + + def _mentions(text, markers): """What the words name: {"object", "colour", "prefer", "source", "dest", "finish"}, only the fields mentioned. "object" / "source" / "dest" is None when the word is there but unknown.""" @@ -1668,7 +1769,10 @@ def _mentions(text, markers): before, after, place = t[:m.start()], t[m.end():], _resolve(m, markers) if re.search(r"\bfrom (the )?$", before) or re.match(r"\s*에서", after) \ or (re.search(r"\b(go|drive|head|come) (over )?to (the )?$", before) # "go to p1 and get the cup" - and re.match(r"\s*(,|and|then)\s*(get|fetch|take|pick|grab|bring)", after)): + and re.match(r"\s*(,|and|then)\s*(get|fetch|take|pick|grab|bring)", after)) \ + or re.search(_AT_OBJ_EN, before) or re.match(_AT_OBJ_KO, after) \ + or (re.match(rf"\s+{_OBJ_ADJ}(?:{_OBJ})", after) and not re.search(r"\b(to|into|onto) (the )?$", before)): + # ^ "the cup on p2", "p2에 있는 컵", "피원 컵을", "p1 red cup bring me" out["source"] = _as_place(place) elif re.search(r"\b(to|into) (the )?$|\b(bring|fetch|give|get)( it| that| this)? $", before) \ or re.match(r"\s*(으로|로|에다|에|한테)(?!서)", after) or place == "here": @@ -1685,6 +1789,13 @@ def _mentions(text, markers): 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): out["dest"] = "here" + if "dest" not in out and (re.search(r"\b(?:bring|fetch)(?:ing)?\b", t) and isinstance(out.get("source"), dict) + and not re.search(r"\b(?:to|for) (?!me\b|us\b)\w", t) + or re.search(r"(?:갖다|가져다|갖고|가지고)\s*(?:좀\s*)?(?:줘|주|조|드려|드리)", t) + and not any(p not in ("나", "저", "내", "제") for p in + re.findall(r"([가-힣]+?)\s*(?:한테|에게|께)(?!서)", t))): + out["dest"] = "here" # "fetch the cup from p2", "p2에서 컵 갖다 주시겠어요?": to the one who asks, not to + # "Minsu" ("민수한테 갖다 줘", "bring it to Minsu": a person is asked about) 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): out["finish"] = "place" @@ -1800,6 +1911,12 @@ UNCLEAR_RETRY = ("\n\n(These words may be short, broken or odd, but they mean so "you can't do it and why. Choose unclear only if they really mean nothing.)") +ASKS_AGAIN = re.compile(r"\bdidn'?t (?:quite )?(?:catch|understand|get)\b|\b(?:could|can|would) you (?:please )?(?:say|repeat) " + r"(?:that|it|them)\b|\bsay (?:that|it) again\b|\bnot sure what you(?:'re| are)? (?:mean|referring)|" + r"\bplease clarify\b|\bcould you (?:please )?clarify\b|잘 ?못 알아들|다시 (?:한 ?번 ?)?말씀해|" + r"\bwhat do you mean by\b|\bwhich \w+ do you mean\b|이해하지 못했|무슨 말씀이신지|무슨 뜻인지 (?:잘 )?모르|" + r"(?:어떤|무슨|어느) \S+(?:을|를)? 말씀하시는|불분명", re.I) + # a reply that asks to hear the words again UNSURE_ANSWER = re.compile(r"^\W*(?:maybe|perhaps|not really|kind of|sort of|i don'?t know|글쎄요?|아마(?:도)?|몰라요?|모르겠어요?)\W*$", re.I) # an answer to Lumi's question, not filler @@ -1868,7 +1985,7 @@ SUPPORTS = {**{c: c for c in objects.COCO if c != "person" and c not in OBJECTS. "책상": "dining table", "식탁": "dining table", "의자": "chair", "소파": "couch", "벤치": "bench", "침대": "bed"} # word -> camera class -MISSPELT = {"dinning": "dining", "dinner table": "dining table", "dinining": "dining", "tabel": "table", +MISSPELT = {"dinning": "dining", "dinner table": "dining table", "dinining": "dining", "tabel": "table", "talbe": "table", "tabe": "table", "tabble": "table", "chiar": "chair", "chari": "chair", "char": "chair", "sofaa": "sofa"} # typed / heard support words -> the word (place_on) PREFER = {"lower": "low", "low": "low", "lowest": "low", "shorter": "low", "smaller": "small", "small": "small", @@ -1903,7 +2020,7 @@ def pick_prefer(text): if m: return m.group(2), t[:m.end(1)] + t[m.end():] m = re.search(rf"(?:(?:제일|가장|더)\s*)?(작은|큰|왼쪽(?:에\s*있는|의)?|오른쪽(?:에\s*있는|의)?|가까운|가까이\s*있는|먼|" - rf"멀리\s*있는)\s*(?=(?:(?:{_COL})\s*)?(?:{_OBJ}))", t) + rf"멀리\s*있는)\s*(?=(?:(?:{_COL})\s*)?(?:{_OBJ})|(?:거|것|걸)(?![가-힣]))", t) if m: return next(v for k, v in PICK_PREFER_KO if m.group(1).startswith(k)), t[:m.start()] + t[m.end():] return None, text @@ -1971,7 +2088,8 @@ RECEIVE_EN = re.compile( 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"(? (task, changed). field: the field a bare answer is about ("source" / "dest"), when Lumi just asked for it ("p2" -> that field).""" - m, task = _mentions(text, markers), dict(task) + m, task, t = _mentions(text, markers), dict(task), _norm(text, markers) if field in ("source", "dest") and not {"source", "dest"} & set(m): - p = re.search(_place_re(markers), _norm(text, markers)) + p = re.search(_place_re(markers), t) if p: m[field] = _as_place(_resolve(p, markers)) - changed = [k for k, v in m.items() if task.get(k) != v and not (k == "colour" and "object" not in m)] + ps = [_as_place(_resolve(p, markers)) for p in re.finditer(_place_re(markers), t)] + if not {"source", "dest"} & set(m) and len(ps) == 2 and re.search(r"\bnot\b|말고|아니고|아니라", t): + k = next((k for k in ("source", "dest") if task.get(k) == ps[0]), None) # "not p1, p2": the one it was + if k: + m[k] = ps[1] + col = re.search(rf"(? 1: # "really?" / "why?": the answer is in the talk, its + notes = _notes(hits[:1]) # reason in the best chunk (~200 tokens less, ~0.25 s) + elif world: # "부엉이는 고개를 몇 도까지 돌려요?": notes on Lumi's own head + notes = "(none needed: not about you)" # turned the owl into Lumi ("제 고개는 180도까지") + if len(world) > 1: # "심장은 몇 개고?" after the octopus: the octopus's hearts + world = [f"{world[0]} (its {', '.join(world[1:])}, when that is a part or a kind of it)"] + world = (f"(This is about {', '.join(world)}, not about you: never answer it with your own head, eyes, arms or " + f"body.)\n") if world else "" # "부엉이 목 그거 을매나 돌아가노?" got "제 머리는 180도까지" with no notes messages.append({"role": "user", "content": f"Reference notes:\n{notes}\n\n{_examples(about, k=2 if follow else None, on_task=bool(now) and 'not doing any task' not in now)}" f"{follow}" f"Now it is {now_line()}.\n\n" + memory.turn_lines(self, text) + - f"Visitor: {text}\n\n" + self._fragment_hint(text) + + f"Visitor: {text}\n\n" + self._fragment_hint(text) + world + f"(Reply in {lang}.)"}) buf, full, header, said, muted = "", "", None, [], False - stream, retried = _stream(messages), False + stream, retried, skip_head, held = _stream(messages), False, False, None try: for piece in iter(lambda: next(stream, None), None): full += piece @@ -2808,7 +3007,8 @@ class Brain: buf = rest if NONE_LINE.match(first) and LOOKUP_ACTION.match(rest.lstrip()): first = re.search(r"search|weather", rest).group(0) # read as the action, never said - header = self._after(self._action(first, text, markers), text) + raw = self._action(first, text, markers) + header = self._after(raw, 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 \ @@ -2820,7 +3020,10 @@ class Brain: stream = _stream(messages) continue muted = bool(header.pop("held", None)) # a motion the words did not order: talk only - yield header + if raw and raw["action"] == header["action"] == "search" and not CHANGES.search(text): + held = header # "윤초는 뭐예요?" -> "search" with the answer after it: + else: # its first sentence decides (below) + yield header if header.get("say"): # the model's words don't fit the action any more said.append(header.pop("say")) yield said[0] @@ -2831,7 +3034,23 @@ class Brain: yield said[0] buf, full = "", f"{first}\n{said[0]}" break + if held: # settled knowledge the model answered anyway: said, not + if len(SENTENCE_END.split(buf)) < 2: # looked up; "Let me check." keeps the search + continue + header, held = self._settled(held, buf, text), None + yield header + if skip_head: # the retry's own action line: the header stands + if "\n" not in buf: + continue + head, rest = buf.split("\n", 1) + buf, skip_head = (rest if re.match(r"\s*\**ACTION", head) else buf), False parts = SENTENCE_END.split(buf) + if not said and not retried and len(parts) > 1 and self._asks_again(header, parts[0], text): + stream.close() # "Sorry, I didn't catch that." to clear words: once more + retried, skip_head, buf, full = True, True, "", "" + messages[-1]["content"] += UNCLEAR_RETRY + stream = _stream(messages) + continue for sentence in parts[:-1]: if muted != "said" and sentence.strip() and not (said and HELP_OFFER.search(sentence)): said.append(spoken(sentence.strip(), lang)) @@ -2848,12 +3067,25 @@ class Brain: yield {"action": "none", "target": ""} header = {} buf += " Sorry, could you say that again?" + if held: # the whole reply was one sentence + header, held = self._settled(held, buf, text), None + yield header 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 skip_head and re.match(r"\s*\**ACTION", buf): + buf = buf.partition("\n")[2] + if not said and not retried and buf.strip() and self._asks_again(header, buf, text): + try: # a one-sentence "say it again?" to clear words + again = _chat(messages[:-1] + [dict(messages[-1], content=messages[-1]["content"] + UNCLEAR_RETRY)]) + again = "\n".join(ln for ln in again.splitlines() if not re.match(r"\s*\**ACTION", ln)).strip() + if again and not ASKS_AGAIN.search(again): + buf = full = again + except Exception: # noqa: BLE001 - say the first reply then + pass if buf.strip() and not (said and HELP_OFFER.search(buf)): said.append(spoken(buf.strip(), lang)) cut = muted and self._unpromise(said, lang) @@ -2870,6 +3102,24 @@ class Brain: full = "ACTION: none -\n" + " ".join(said) self.history.append((text, full.strip())) + @staticmethod + def _settled(search, words, text): + """The model chose search for words with nothing that changes, then answered in its first sentence ("윤초는 + 지구 자전과 ... 맞추는 1초예요."): that answer is said, action none. A first sentence that promises a lookup or + doesn't know ("확인해 볼게요.", "Let me check.") keeps the search.""" + first = SENTENCE_END.split(words.strip())[0].strip() + asked = set(re.findall(r"\w+", text.lower())) + echo = len(asked & set(re.findall(r"\w+", first.lower()))) >= 0.6 * len(asked) + return search if not first or LOOKS_UP.search(first) or LOOKUP_ACTION.match(first) or echo or \ + first.endswith("?") or re.search(r"궁금|\bwonder|good question|좋은 질문", first, re.I) \ + else {"action": "none", "target": ""} # the query written out, "궁금하시군요." then "잠시만요": a lookup + + def _asks_again(self, header, sentence, text): + """The model talks (action none) but asks to hear clear words again ("I'm not sure what you mean, could you + say it again?" to "Why the 15th?"): it is asked once more with UNCLEAR_RETRY.""" + return bool(header) and header.get("action") == "none" and bool(ASKS_AGAIN.search(sentence)) and \ + (has_meaning(text) or bool(self.history) and about_answer(text)) and not other_latin_language(text) + @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 @@ -2882,6 +3132,21 @@ class Brain: said.pop() return "dropped" + def world_talk(self, text): + """The words (or the question they follow) name a subject of their own that is not Lumi, its parts or the + companies ("부엉이는 ...?", "How high is Mount Fuji?"): Lumi's notes are left out. A subject that is one of + Lumi's own things ("속도는 얼마예요?", "이름이 뭐예요?") keeps them. Returns those subjects, the question before first ([] when none).""" + def named(t): + return [m.group(0) for m in OWN_SUBJECT.finditer(core(t))] + [m.group(1) for m in EN_SUBJECT.finditer(core(t))] + qs = [topic_turn(self.history)[0]] + [h[0] for h in reversed(self.history[-3:])] if self.history else [""] + q = next((x for x in qs if named(x)), qs[0]) # "문어 피는?" "왜?" "심장은?": the octopus, two turns back + both = re.sub(r"(?<=[A-Za-z])(?=[가-힣])", " ", f"{text} {q}") # "Gemma는": the word for LUMI_TOPIC + if LUMI_TOPIC.search(both) or COMPANY_TALK.search(both): + return [] + subjects = [w for t in (q, text) if t for w in named(t)] + return list(dict.fromkeys(re.sub(r"[은는가]$", "", w) for w in subjects # "부엉이" keeps its 이 + if not SELF_THINGS.match(w[:-1] if HANGUL.search(w) else w))) + 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.""" @@ -2894,9 +3159,11 @@ class Brain: return f"(This follows your answer \"{last[:FRAGMENT_CHARS * 2]}\": if it said you can do something, do it now: its ACTION line is that action (wave, sing, look ...), not none.)\n" part = SAME_ABOUT.match(text) or KO_SAME_ABOUT.match(text) if last and part: # "What about your cameras?" / "카메라는요?" after "can I wipe you?" - 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: # past a back-channel ("헐 대박") to the answer before it + return (f"(The visitor's question \"{self.history[-1][0]}\" goes on, now about {part.group(1)}: the same " + f"question for {part.group(1)}, or {part.group(1)} of the thing just talked about (\"height는요?\" " + f"after a tower: its height), whichever fits; not other facts.)\n") + if self.history: # past a back-channel ("헐 대박") to the answer before it, + # also past a motion done without words ("are u sure" after a lift) last = " ".join(ln for ln in topic_turn(self.history)[1].splitlines() if not re.match(r"\s*\**ACTION", ln)).strip() c = core(text) # "루미 양반, 언제야?" asks "언제야?", not about Lumi if last and (THANKS_ONLY.match(c) or THANKS_ONLY.match(re.split(r"[,:]\s*", c)[-1])) and \ @@ -2904,11 +3171,20 @@ class Brain: return "(Only thanks for your answer, not a goodbye: say you're welcome in a few words; no goodbye, no question.)\n" if BYE_WORDS.search(text) and SHORT_Q.search(re.split(r"(?<=[,.!~])\s*", text.strip())[-1]): return "(A goodbye with one more question: answer the question; no goodbye in your words yet.)\n" + if re.search(r"\bthanks?\b|thank you|고마|고맙|감사|땡큐", text, re.I) and len(re.split(r"(?<=[,.!~])\s*", text.strip())) > 1 and \ + (text.rstrip().endswith("?") or SHORT_Q.search(re.split(r"(?<=[,.!~])\s*", text.strip())[-1])): + return "(Thanks and then a new question: answer the question itself now, a few words of thanks back at most.)\n" + if self.history and SAID_BEFORE.search(text) and not re.search(r"\btold me to\b|\byou said you(?:'d| would| will| can)\b", text, re.I): + return ("(The visitor says your earlier answer was different: say again, in one or two sentences, the facts you " + "gave earlier in this talk about the thing they name (its numbers, names, reasons), and keep them; never " + "ask which part, never change them.)\n") if last and about_answer(text): # "why?", "how do you know?", "진짜?" after a refusal too return (f"(This asks about your answer \"{last[:FRAGMENT_CHARS * 2]}\": its reason or how you know it; " f"a \"really?\" / \"sure?\" is answered \"Yes,\" with that answer's own facts said again (its numbers, names or the " f"things it listed, never just \"that\" / \"those\"), no new fact.)\n") - pronoun = NAMED_BEFORE.search(c) or REFERS_BACK.search(c) # "when was it built?", "how old are they?" + pronoun = NAMED_BEFORE.search(c) or REFERS_BACK.search(c) or \ + re.match(r"\W*(?:(?:and|so|but|why|how about|what about)\W+)?the\s+\w+\W*$", c, re.I) + # "when was it built?", "how old are they?", "Why the name?" if not last or len(c.split()) > (FOLLOW_UP_WORDS + 2 if pronoun else FRAGMENT_WORDS) or not SHORT_Q.search(c) \ or is_backchannel(c) or ABOUT_YOU.search(c) or (OWN_TOPIC.search(c) or OWN_SUBJECT.search(c)) and not pronoun: return "" @@ -2918,7 +3194,8 @@ 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) or sing.list_asked(text)): + if header and header["action"] == "sing" and (sing.NOT_ASKED.search(text) or sing.list_asked(text) or + SAID_BEFORE.search(text) or re.search(r"노래\s*(?:얘기|이야기)", 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 @@ -3251,6 +3528,10 @@ class Brain: action, target = rule if action == "stop" and "?" in text: action = "none" # "how do I stop you?": a question about stopping + tail = re.split(r"근데|그런데|아 맞다|\bbut\b|\bby the way\b|\bone more (?:thing|question)\b", text, flags=re.I) + if action == "end" and len(tail) > 1 and re.search(r"\w{2}", tail[-1]) and not BYE_WORDS.search(tail[-1]) and \ + not re.search(r"가 ?봐야|이만|leav|head (?:out|off)|\bgo now\b|\bget going\b", tail[-1], re.I): + action = model if model in ("search", "weather") else "none" # "갈게요 아 근데 라이다 있어": asked more if action == "end" and "?" in re.split(r"(?<=[.!?~])\s+", text.strip())[-1]: action = model if model in ("search", "weather") else "none" # "갈게요, 근데 후지산은 얼마나 높아?": its target = target if action != "none" else "" # lookup stays (else "search 후지산 높이" was said aloud) diff --git a/assistant/chain.py b/assistant/chain.py index e72f465..03a5ff4 100644 --- a/assistant/chain.py +++ b/assistant/chain.py @@ -29,13 +29,15 @@ FETCHING = re.compile(r"\b(?:bring|fetch|deliver|carry)\b|가져|갖다", re.I) _FILL = re.compile(rf"(?:{steps._FILL}|루미야?|lumi|hey|do me a favou?r|부탁(?:해|해요|할게)?|dear|sir|ma'?am|madam|buddy|" r"my friend|robot|로봇아?|선생님?|yo|bro|dude|okay lumi|ok lumi|robot please|루미 ?씨|로봇 양반|여보세요|" r"go ahead|okay\?|ok\?|right\?|thanks|thank you|yes|yeah|yep|yes\?|네|응|그래|will ya|will you|won'?t you|" - r"can\?|can|do it|do it now|just do it|alright\?|please\?|혹시|아 뭐라 그래야 되지|뭐라 그래야 되지|뭐더라|" + r"can\?|can|do it|do it now|just do it|alright\?|please\?|over here\??|this way\??|어디 ?한번|어디 ?보자|얼마나 걸리나|(?:pls |please )?(?:eh|huh|da|see|ya|yah|innit)\??|혹시|아 뭐라 그래야 되지|뭐라 그래야 되지|뭐더라|" r"(?:아\s*)?영어로 ?뭐더라|(?:아\s*)?뭐라고 ?하지|" r"(?:거기서?\s*)?(?:서|가만히)\s*있(?:어|게|으세요|으십시오)\s*(?:줄래|줄 ?수 ?있어요?|주실래요|주세요|줘|줘잉|주라|" r"주면 ?안 ?될까요?|주면 ?좋겠어요?|주실 ?수 ?있어요?|주십시오|주이소)?|" r"(?:거기서?\s*)?기다려\s*(?:줄래|주세요|줘)?)", re.I) # tags, hesitations, "...가서 서 있어 줄래?" RELATIVE = re.compile(r"^\W*(?:where|which|who|that|when)\s+(?:the|my|your|his|her|our|their|a|an|this|that|these|those|" r"people|everyone|it|he|she|they|we|i)\b", re.I) # "look right, where the door is": no question +SPEED_Q = re.compile(r"속도|몇으로|얼마나 (?:빨리|빠르게|천천히)|\bhow (?:fast|quick(?:ly)?|slow(?:ly)?)\b|\bwhat speed\b", re.I) +GREET = re.compile(r"인사|작별|\b(?:hello|hi|goodbye|bye)\b", re.I) # a greeting made by waving PAST = re.compile(r"\byou (?:got|went|were|did|turned|looked|moved|came|said|told)\b|\b(?:earlier|before|yesterday)\b", re.I) BANK_KINDS = {"look", "lift", "turn", "move", "come", "come_back", "follow", "wave", "arm", "go_to"} # a part the # keyword rules miss, read by the intent bank (same slot rules) @@ -43,6 +45,22 @@ CHAIN_ONLY = {"look", "lift", "wave", "come", "come_back", "follow"} # a part # a sentence the mission reader reads whole is still a chain +BACKGROUND = re.compile(r"[가-힣](?:는|은|인|던)(?:데|디)(?:요)?\W*$") # "…말하는데," a clause that only sets the scene +SELF_PROMISE = re.compile(r"(?:^|\W)(?:i'?ll|i will|let me|i'?m going to|i can) (?:hold|take|keep|get|catch|grab) (?:it|that|this|them)\W*$|" + r"(?:^|\W)(?:내가|제가) (?:들|받|잡)(?:게|을게|을게요|게요|을께)\W*$", re.I) # the speaker's part + + +def _restated(words, before): + """A Korean part that says the order before it again in another level ("손 거둬!", "아 거두시겠어요?").""" + from assistant import wording + said = [w for w in re.findall(r"\w+", wording.ko_plain(words)) if not re.fullmatch(r"(?:줘|봐|주|좀|요)[가-힣]?|허허|하하|호호|헤헤|아|어", w)] + if not said or len(said) > 3 or not re.fullmatch(r"[가-힣]{2,}|[가와]", said[-1]): + return False + last = said[-1] + return any(last == w or len(w) > 1 and (w.startswith(last) or last.startswith(w)) + for w in re.findall(r"\w+", wording.ko_plain(before)) if re.fullmatch(r"[가-힣]+", w)) + + def _rule(words, markers): """brain.intent of a part, also of a Korean -고 form ("나 보고" read as "나 봐").""" rule = brain.intent(words, markers) @@ -57,6 +75,8 @@ def _rule(words, markers): from assistant import intent_bank # "glance to your right", "고개 숙이고": the bank, by meaning got = intent_bank.read(ko, markers) rule = got if got and got[0] in BANK_KINDS else None + if rule and rule[0] == "come_back" and re.fullmatch(r"\W*(?:루미야?\s*)?(?:원래 ?자리|제자리)(?:에|로)?\W*", words): + rule = None # "제자리에, 손 내밀어": "ready", no drive back return rule @@ -69,6 +89,9 @@ def parts(text): for p in _SPLIT.split(cut): out += [q for q in steps._SPLIT_KO.split(p) if q.strip()] out = [re.sub(r"§(\d+)§", lambda m: f'"{says[int(m.group(1))]}"', p).strip(" ,.!") for p in out] + for i in range(len(out) - 1, 0, -1): # "뒤로 물러서 줘": 서 is the verb's, 줘 no part of its own + if re.fullmatch(r"(?:줘|줘요|주세요|주십시오|줄래요?\??|주실래요?\??|주라|주게|주이소|봐|봐요|보세요)\W*", out[i]): + out[i - 1] += " " + out.pop(i) return [p for p in out if p and not re.fullmatch(rf"(?:{_FILL.pattern}|\W)+", p, re.I)] @@ -90,6 +113,8 @@ def plan(text, markers=(), cant=None): return None # "turn around and look": the head looks behind out = [] for p in ps: + if SELF_PROMISE.search(p) or out and _restated(p, out[-1][1]) or brain.GREET_ONLY.match(p): # "hello robot, …" + continue # "흰색 머그컵 잡아!, 아 잡아 줄 수 있어요?": the order once got, unread = steps.rules(p, markers) rule = _rule(p, markers) if got and not unread and not (rule and rule[0] in ("look", "lift", "wave", "come", "come_back", "follow")): @@ -100,6 +125,13 @@ def plan(text, markers=(), cant=None): out.append(["quick", p, rule]) elif RELATIVE.search(p): return None # a part that tells more about the one before + elif BACKGROUND.search(p): + continue # "이장이 말하는디, 팔 제자리로 해", "I'll hold it, give it here" + elif out and out[-1][0] in ("quick", "steps") and _restated(p, out[-1][1]): + continue # "손 거둬!, 아 거두시겠어요?": the same order again, politely + elif out and out[-1][0] == "quick" and out[-1][2][0] == "wave" and re.search(r"(?:면서|며|서)\W*$", out[-1][1]) and \ + GREET.search(p) and not rule: + continue # "손 흔들면서 인사하고 고개 숙여": the wave is the greeting 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: @@ -112,6 +144,12 @@ def plan(text, markers=(), cant=None): said[i] and said[i] == said[i - 1]))] if len(out) < 2: return None # "wave, wave, wave!": one wave, said with feeling + if any(k == "talk" and SPEED_Q.search(p) and i and re.search(r"고$|\b(?:holding|carrying|with)\b", out[i - 1][1], re.I) + for i, (k, p, _) in enumerate(out)): + return None # "컵 들고 몇으로 가?": how fast it goes so, no order + if any(k == "quick" and w[0] == "wave" and re.search(r"(? "go to p3").""" from assistant import brain t = TAIL.sub("", brain.CALLING.sub("", plain(text))).strip(" ,.!?~") or text + t = re.sub(r"(? +head yaw (checked: + = robot's left) LOOK = {"left": (40, None), "right": (-40, None), "center": (0, head.HEAD_REST_PITCH), "up": (None, 20), "down": (None, -5)} # ^ yaw/pitch in degrees for "look" commands: +yaw = left, +pitch = up (checked on the dashboard 2026-10-12) -WAKE = re.compile(r"\b(hi|hey|hello|okay|ok|hai|high)?[\s,.!]*(lumi|lumia|loomi|loomy|lumie|lumee|lumy|lummy|lummi|looney|lu-mi|rumi|rumy|roomie)\b" - r"|루미|누미", re.I) +WAKE_UP_EN = r"wake up|wakey wakey|time to wake up" +WAKE_UP_KO = r"(?:일어나|깨어나)(?:요|세요|십시오|라|봐|봐요)?|기상" +WAKE = re.compile(rf"\b(hi|hey|hello|okay|ok|hai|high|{WAKE_UP_EN})?[\s,.!]*(lumi|lumia|loomi|loomy|lumie|lumee|lumy|lummy|lummi|looney|lu-mi|rumi|rumy|roomie)\b" + rf"(?:[\s,.!]*(?:{WAKE_UP_EN})\b)?" + rf"|(?:(?:{WAKE_UP_KO})[\s,.!~]*)?(?:헤이 ?|하이 ?)?(?:루미|누미)(?:야|아)?(?:[\s,.!~]*(?:{WAKE_UP_KO}))?" + rf"|^\W*(?:(?:hey|ok|okay|come on)\W+)?(?:{WAKE_UP_EN})\W*$|^\W*(?:(?:자|이제|얼른)\s+)?(?:{WAKE_UP_KO})[\s.!~]*$", re.I) +# ^ "Hey Lumi", "Lumi", "wake up (Lumi)", "Lumi, wake up", "루미야", "헤이 루미", "루미야 일어나", "일어나세요"; +# a bare "wake up" / "일어나" only as the whole utterance ("I wake up at 7" is no call) WAKE_REPLY = {"en": "Yes? How can I help?", "ko": "네? 무엇을 도와드릴까요?"} NAME_ONLY = re.compile(r"^\s*(hi |hey |hello )?(lumi|loomi|rumi|루미)[\s,.!?]*$", re.I) FETCH_STOP = re.compile(r"\b(sto+pp?|stob|halt|freeze|don'?t move)\b|^\W*(?:lumi\W+)?stopped\W*$|스탑|스텁|멈추(?:세요|십시오)|^\W*abort\W*$|\babort (?:the |this |your )?(?:mission|task|trip)\b|\bcancel (?:the |this |your )?(?:mission|task|trip)\b|" @@ -313,7 +319,7 @@ HELLO_ONLY = re.compile(r"^(?=\W*\w)\s*(?:(?:hi|hey|hello|hiya|hai|hallo|helo|hi r"(?:how are you(?: doing)?(?: today)?[\s,.!?]*)?$|" # "how are you?" r"^\s*(?:안녕|안녕하세요|안녕하십니까|하이)[\s.!~?]*$", re.I) # "안녕하세요", "하이" CALL_REST = re.compile(r"^(?:[\W_]|\b(?:hi|hey|hello|hiya|hai|ok|okay|there|how are you(?: doing)?(?: today)?)\b|" - r"안녕(?:하세요|하십니까)?|하이|야|아)*$", re.I) # what is left of a call without the name + r"안녕(?:하세요|하십니까)?|하이|헤이|야|아)*$", re.I) # what is left of a call without the name CAMERA_HALF_FOV = 42.0 # deg; half the camera's view (+ the head's YAW_LIMIT for the head camera) WAKE_MAX_S = 6.0 # s; longer utterances are not checked for the wake word BARGE_IN_LOGPROB = -0.6 # an interruption must be heard more clearly than a normal answer (-1.0) @@ -3255,35 +3261,53 @@ STOP_UNSAID = re.compile( # a stop that is taken back, for later, said about t r"\bstop it,? (?-i:(?!Lumi\b|Robot\b)[A-Z][a-z]+)\b", re.I) +STOP_LATER = re.compile( # a stop for later ("내일 그만하시게", "행사가 끝난 후에 멈춰 주세요") or reported ("아까 직원분이 + # 그만하라고 지시했습니다"); "내가 멈추라고 했지!" is said now + r"(?:^|\s)(?:나중에|이따가?|있다가|내일|모레|다음에|다음 ?번에)\s|(?:끝난|끝나고|마친|마치고|끝내고) ?(?:후|뒤|다음)?에?\s|" + r"[가-힣]고 ?나서\s|(? "멈춰 줘?", "can you stop for me?" + r"\W*(?:(?:좀|지금|당장|잠깐|잠시|거기서?|이제)\s*)*(?:멈춰|멈춰 서|정지해|그만해|스톱해|스탑해|서)(?: ?줘)?\W*|" + r"\W*(?:(?:please|lumi|hey|okay|ok)\W+)*(?:can|could|would|will) (?:you|u) (?:please |just |kindly )?(?:stop|halt|freeze)" + r"(?: (?:right )?(?:now|here|there|please))?(?: for (?:me|us|a (?:second|sec|moment|bit|minute)))?(?:,? please)?\W*|" + r"\W*(?:would|do) you mind stopping(?: (?:now|here|there))?(?: for (?:me|us|a (?:second|moment)))?(?:,? please)?\W*", re.I) + + def stop_order(text, markers): """"stop", "freeze", "멈춰": stop everything at once. Not "stop talking" and not a question about the stop button; "can you stop?", "멈출 수 있어?" and "stop, where are you going?" do stop. Not a negated stop ("don't stop", "계속 해"), talk about stopping ("he said stop", "bus stop", "my laptop freezes", "내 다리도 자주 멈춰"); a short bare stop word always stops (also stretched: "stooop", "머엄춰").""" - if NOT_STOP.search(text) and not re.fullmatch(r"\W*(?:(?:no|ok|okay|lumi|루미야?|hey)\W+)*(?:sto+pp?|stob|stopped|halt|freeze|멈춰|머+엄*춰|" + if NOT_STOP.search(text) and not re.fullmatch(r"\W*(?:(?:lumi|robot|hey|okay|ok)\W+)*(?:would|do) you mind stopping" + r"(?:,? (?:now|here|there|please|for (?:me|us|a (?:second|moment))))*\W*", text, re.I) \ + and not re.fullmatch(r"\W*(?:(?:no|ok|okay|lumi|루미야?|hey)\W+)*(?:sto+pp?|stob|stopped|halt|freeze|멈춰|머+엄*춰|" r"그만|정지|스톱|스탑|stop it|stop now)\W*", text, re.I): return False - if STOP_UNSAID.search(text): - return False + if STOP_UNSAID.search(text) or STOP_LATER.search(text): + return False # "이따가 멈춰 주세요": a stop for later bare = STOP_PAD.sub("", text.strip()).strip(" ,.!?~") if bare and STOP_ONLY.fullmatch(bare): return True # "hi Lumi, stop, okay?", "enough already", "Lumi, wait" # (watch out / 위험해 / "Lumi, wait" / hold on: on a mission these halt it (mission_talk), never end it) - asked = bool(brain_mod.STOP_ASK.match(brain_mod.CALLING.sub("", text)) or + from assistant import wording + plain = brain_mod.CALLING.sub("", wording.ko_plain(text)).strip() + asked = bool(brain_mod.STOP_ASK.match(brain_mod.CALLING.sub("", text)) or STOP_POLITE.fullmatch(plain) or re.match(r"^\W*(?:stop|halt|freeze|멈춰|정지|스톱)\W*[,.!]", text, re.I)) return bool(FETCH_STOP.search(text) or asked) and (brain_mod.intent(text, markers) or ("",))[0] not in ("quiet", "look") \ and not brain_mod.STOP_TALK.search(text) and ("?" not in text or asked) @@ -3299,14 +3323,16 @@ HAND_STATE_Q = re.compile( # how the hand is now (A1): "is your hand open?", " r"\b(?:is|are|r|was) (?:your|ur|the) (?:hand|gripper|claw|fingers?|arm)s? (?:still |now |already )?(?:open|opened|closed|shut|out|" r"extended|empty|folded|in|up|down|stretched)\b|\b(?:hand|gripper|arm) (?:open|closed?|out)\s*(?:이야|이에요|인가요?|이니|상태|\?)|" r"^\W*(?:(?:right|um|basically|next|so|okay)\W+)*did (?:you|u) drop (?:it|that|something|the \w+)\W*$|" - r"(?:손|그리퍼|집게|손가락|팔)(?:이|은|는|가)? ?(?:지금 |아직 |다 )?(?:open|close|펴져|펴진|열려|열린|닫혀|닫힌|접혀|접힌|뻗어져|오므려져|" + r"(?:손|그리퍼|집게|손가락|팔)(?:이|은|는|가)? ?(?:지금 |아직 |다 )?(?:open|close|오픈|클로즈|펴져|펴진|열려|열린|닫혀|닫힌|접혀|접힌|뻗어져|오므려져|" r"쥐어져)\s*(?:있|상태|이야|인가)", re.I) def status_question(text): """"What are you doing?", "where are you going?", "is your hand open?": answered from the task state ("들고 있는 거 줘" is a request).""" - return bool(HAND_STATE_Q.search(text)) or bool(STATUS_Q.search(text)) and not NOT_STATUS_NOW.search(text) and not EMPTY_HAND.search(text) + hand = HAND_STATE_Q.search(text) and not re.search(r"\b(?:stretch|stick|hold|put|reach|extend|get|move|bring)\b", text, re.I) + return bool(hand) or bool(STATUS_Q.search(text)) and not NOT_STATUS_NOW.search(text) and not EMPTY_HAND.search(text) + # hand: not "may I ask you to stretch your arm out?" (an order) def says_goodbye(text): @@ -3338,6 +3364,11 @@ NOT_A_STEP = re.compile(r"^\W*(?:(?:please|and|then|also)\s+)*(?:dance|jump|fly| r"bring|take|give|hand|put|carry|deliver)\b|.*(?:춤|점프|날아|수영|박수)", re.I) # a part not read: asked +CAN_TOLD = re.compile(r"\b(?:you|u) (?:can|could|are able to|know how to)\b|(? 1 and all(st == got[0] for st in got) and got[0]["do"] in ("arm", "wave", "look", "lift"): got = got[:1] # "reach out, reach out to me": one reach, said twice - plain = not steps.is_mission(got) and (len(got) == 1 or (brain_mod.intent(text, markers) or ("",))[0] == "fetch") + one_part = len(steps._split(steps._norm(steps._cut_says(text)[0], markers), markers)) == 1 + plain = not steps.is_mission(got) and (len(got) == 1 or one_part or (brain_mod.intent(text, markers) or ("",))[0] == "fetch") + # ^ "컵 가져와 주셨으면 해요": one part a plain fetch can do stays the fetch, not a mission if not unread and (plain or (len(got) == 1 and got[0]["do"] in ("move", "turn", "arm"))): # "take the cup and put return None # it on the chair": two steps, not a pick return got, unread, by diff --git a/assistant/steps.py b/assistant/steps.py index 6f9a612..837d709 100644 --- a/assistant/steps.py +++ b/assistant/steps.py @@ -35,16 +35,21 @@ _SUP_KO = "|".join(k for k in brain.SUPPORTS if not k.isascii()) _NUM = r"(\d+(?:\.\d+)?)" _DIR = r"(forward|ahead|straight|back(?:wards?)?|left|right)" _DIR_KO = r"(앞으로|뒤로|왼쪽으로|오른쪽으로)" -_FILL = (r"(?:please|let'?s|lets|hey lumi|hi lumi|hey|hi|lumi|loomi|rumi|okay|ok|alright|all right|so|well|real quick|if you can|if you could|자|저기|저기요|혹시|instead|um+|uh+|er|hmm|thank you|thanks|now|then|and|also|first|next|" - r"finally|after that|there|for me|again|carefully|slowly|could you|can you|would you|will you|lumi야|루미야|루미|음|응|어|야 로봇|로봇아|로봇야|" +_FILL = (r"(?:(?:저기 |그 )?(?:이보게(?: 루미)?|어이(?: 로봇아?| 루미야?)?|아야(?: 루미)?|야야(?: 루미)?|우리 루미|보소|자네|" + r"루미 ?(?:님|씨|군|양)(?:께서|께)?|로봇 ?씨|여보세요|실례지만|실례합니다|죄송한데요?|죄송하지만|죄송합니다만|" + r"번거로우시겠지만)|" # calls of every level ("이보게 루미", "루미 님께서") before "루미" alone + r"please|let'?s|lets|hey lumi|hi lumi|hey|hi|lumi|loomi|rumi|okay|ok|alright|all right|so|well|real quick|if you can|if you could|자|저기|저기요|혹시|instead|um+|uh+|er|hmm|thank you|thanks|now|then|and|also|first|next|" + r"finally|after that|there|for me|for us|again|carefully|slowly|could you|can you|would you|will you|lumi야|루미야|루미|음|응|어|야 로봇|로봇아|로봇야|" r"감사합니다|고마워요|고마워|고맙습니다|좀|먼저|우선|일단|그다음|그 다음|마지막으로|다시|lastly|first of all|" r"(?:i'?d|i would) like you to|i want you to|i need you to|you should|kindly|go ahead and|maybe|possibly|" - r"do me a favou?r and|be a dear and|right away|quickly|if you don'?t mind)") + r"do me a favou?r and|be a dear and|right away|quickly|if you don'?t mind|excuse me|sorry|" + r"거시기|에구|에이그|아|얘|no|nope|actually|change of plans?|아니|아니야|아니요|아뇨|아니 아니|" # "no, bring it to p4 instead": the new order + r"ㅎㅎ+|ㅋㅋ+|응\??|한 ?번만|쪼까|쫌|퍼뜩|얼른|빨리|어서|우리|거기서|그|robot)") _PEOPLE = r"(?:them|him|her|someone|somebody|the person(?: there)?|people|the people|everyone|everybody|the guests?)" # where one step ends and the next starts _SPLIT = re.compile(r"\s*(?:,|;|\.(?=\s|$)|\band then\b|\bthen\b|\band\b|\bafter that\b|\bafterwards\b|\bonce you'?re there\b|" r"\bwhen you get there\b|그리고 나서|그러고 나서|그런 다음에?|그 후에?|그리고|그 ?다음에?|그담에|다음에)\s*") -_SPLIT_KO = re.compile(r"(?<=[가-힣](?:고|서))(? 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 wording._key(mk) == wording._key(w)), None) # "coffee_corner", "부스 3" if exact: @@ -294,12 +304,17 @@ def _give(c): if re.fullmatch(rf"(?:give|hand) (?:it|that|this|the (?:(?:{COL}) )?(?:{OBJ})s?)?(?: over)?" rf"(?: to (?:me|you|{_PEOPLE}|the person there|whoever is(?: there)?|anyone(?: there)?|anybody(?: there)?|" rf"the (?:first )?(?:person|one) you (?:see|meet)))?(?: there)?" - r"|wait (?:there )?(?:until|till) (?:someone|somebody|anyone|they|he|she) takes? it(?: from you)?" + rf"|wait (?:there )?(?:until|till) (?:someone|somebody|anyone|they|he|she) (?:takes?|comes? (?:and|to) (?:take|get)s?) " + rf"(?:it|the (?:(?:{COL}) )?(?:{OBJ})s?)(?: from you)?" + r"|(?:누가|누군가|사람이|손님이|그 사람이|그분이)\s*(?:(?:그거|그걸|컵을?|이거)\s*)?(?:가져갈|받을|가지러 올|찾으러 올)\s*때까지\s*" + r"(?:기다려|기다리고|기다렸다가|대기해|있어)" r"|hand it over|(?:give|hand) it", c) or \ re.fullmatch(rf"(?:그거|그것을?|(?:(?:{COL})\s*)?(?:{OBJ})(?:을|를)?)?\s*(?:줘|주고|주세요|건네 ?줘|건네주고|" rf"건네 ?주세요|건네|전해 ?줘|전해 ?주고|전해 ?주세요|전해)", c): return {"do": "give"} - if re.fullmatch(r"(?:거기 (?:있는|계신)\s*)?(?:나한테|저한테|나에게|저에게|그 사람한테|사람한테|그분께|분께|분한테)\s*" + if re.fullmatch(r"(?:나|저) (?:줘|주세요|주고)", c) or \ + re.fullmatch(r"(?:(?:그거|그걸|이거|이걸)\s+)?(?:거기 (?:있는|계신)\s*)?(?:나한테|저한테|나에게|저에게|(?:그|저|이) ?사람(?:한테|에게)|사람한테|" + r"(?:그|저|이) ?분(?:께|한테)|분께|분한테)\s*" rf"(?:(?:이거|그거|이것|그것|이걸|그걸|(?:(?:이|그)\s*)?(?:{OBJ})(?:을|를)?)\s*)?" r"(?:줘|주고|주세요|건네|건네줘|건네주고|건네주세요|건네 ?줘|건네 ?주세요|드려|드리고|갖다 ?줘|갖다 ?주세요)", c) or \ re.fullmatch(r"(?:이|그|저|두|세|네) ?분(?:께|한테|에게)\s*(?:줘|주고|드려|드리고|건네|건네 ?줘|건네 ?드려)", c): @@ -407,12 +422,12 @@ def _wait(c, markers, after): m = re.fullmatch(rf"(?:(.+?)에서\s*)?(?:(\d+(?:\.\d+)?) s\s*(?:동안|정도|만)?\s*)?{_KO_GIVER}\s*(?:({COL})\s*)?({OBJ}|물건|뭔가|무언가|그거|뭐|무엇을|뭘|이거)?\s*" r"(?:을|를)?\s*(?:주면|건네주면|건네면|갖다주면|가져다주면|가져다 주면|줄 때까지|건네줄 때까지|줄 거야|" r"줄 거예요|가져올 거야)\s*(?:기다렸다가|기다려서|기다리고|기다려|기다려요)?\s*" - r"(받아서|받아|받고|받아와|받아 와|받아요)?", c) + r"(받아서|받아 ?가지고 ?와|받아 ?가지고|받아|받고|받아와|받아 와|받아요)?", c) if m and (m.group(1) is None or _at_place(m.group(1), markers)): obj = brain.OBJECTS.get(m.group(4) or "") return ([{"do": "go", "to": _at_place(m.group(1), markers)}] if m.group(1) else []) + \ [{"do": "receive", "object": obj, "wait_s": float(m.group(2)) if m.group(2) else WAIT_GIVE_S}] + \ - ([{"do": "go", "to": "here"}] if m.group(5) in ("받아 와", "받아와") else []) + ([{"do": "go", "to": "here"}] if re.fullmatch(r"받아 ?(?:가지고 ?)?와", m.group(5) or "") else []) if after and re.fullmatch(r"(?:거기|여기)(?:서|에서)", c): return [] # "p3로 가서 | 거기서 | 기다려": the place of the next step if after and after["do"] == "receive" and after.get("wait_s") and re.fullmatch(r"받아서|받아|받고|받아 와|받아와|받아요", c): @@ -461,10 +476,10 @@ def _wait(c, markers, after): _POLITE = re.compile(r"(?<=[가-힣])\s*(?:주십시오|주시겠어요|주시겠습니까|주실 수 있나요|주실 수 있습니까|주실 수 있어요|" - r"줄 수 있어요|줄 수 있어|주실래요|줄래요?|줘 ?봐요?|줘요?|주세요|죠)\??$") # every speech level + r"줄 수 있어요|줄 수 있어|주실래요|줄래요?|줘 ?봐요?|줘요?|주세요|주라|죠)\??$") # every speech level _HONORIFIC = [(r"(가|와|놔|돌아|집어|잡어|잡아|들어|줘) ?봐요?$", r"\1"), # "가봐", "놔 봐": try / do it (r"(?<=[가-힣]) ?주시고$", "고"), (r"(?<=[가-힣]) ?주셔서$", "서"), # "가 주시고": 가고 - (r"가(?:십시오|세요|시죠|요)$", "가"), (r"오(?:십시오|세요|시죠)$", "와"), (r"도(?:십시오|세요)$", "돌아"), + (r"가(?:십시오|세요|시죠|요)$", "가"), (r"((?:으로|로|에) )가게나?$", r"\1가"), (r"오(?:십시오|세요|시죠)$", "와"), (r"도(?:십시오|세요)$", "돌아"), (r"드리(?:십시오|세요)$", "드려"), (r"(?:주|드리)십시오$", "줘"), (r"물러나(?:세요|십시오|요)?$", "가"), (r"회전(?:해|하세요|하십시오|해요)$", "돌아"), (r"말씀(?:해|하세요|하십시오|해요|해 주세요)$", "말해"), (r"놓으(?:십시오|세요)$", "놔"), (r"기다리(?:십시오|세요|시죠|셔요)$", "기다려"), @@ -684,9 +699,10 @@ def _clause(c, markers, after=None): def _clause_steps(c, markers, after=None): c = re.sub(r"^(?:second(?:ly)?|third(?:ly)?|fourth|first(?:ly)?|last(?:ly)?|step \d)[\s,]+", "", c.strip(" .!?")) # "second, go to ..." - c = re.sub(rf"^(?:{_FILL}[\s,]+)+|(?:[\s,]+{_FILL})+$", "", c).strip(" .!?,") + c = re.sub(rf"^(?:{_FILL}(?:[\s,]+|$))+|(?:[\s,]+{_FILL})+$", "", c).strip(" .!?,") if re.search(r"[가-힣]", c): - c = re.sub(r"\s+", " ", c) + c = re.sub(r"\s+", " ", wording.ko_plain(c)).strip(" .!?~") # every speech level / dialect as 반말: "돌아오게나", + c = re.sub(rf"^(?:{_FILL}(?:[\s,]+|$))+|(?:[\s,]+{_FILL})+$", "", c).strip(" .!?,~") # "가 주시겄슈" -> "돌아와", "가 줘" c = re.sub(r"\s좀\s", " ", c) c = re.sub(r"^(?:야\s+)?로봇(?:아|야)?[,\s]+|^야[,\s]+(?!로봇)", "", c) # "야 로봇", "로봇아", "야": calling it c = c.replace("그리퍼를", "손을").replace("물러나", "뒤로 물러나") if "뒤로" not in c else c.replace("그리퍼를", "손을") @@ -705,7 +721,7 @@ def _clause_steps(c, markers, after=None): c = re.sub(r"^\S+ 말고\s+", "", c) # "미나 말고 사라한테": not Mina, Sara c = re.sub(r"^\S+ (?:없으니까|없어서|없대서)\s+", "", c) # "현우 없으니까 ...": the reason, not a step c = re.sub(r"\s+(?:거기로|내가) 갈게$", "", c) - c = re.sub(r"(?<=[a-z0-9가-힣]) (?:하고|해서|하고서|하고 나서|한 다음에?)$", "", c) # "turn left 하고 p2로 가", + c = re.sub(r"(?<=[a-z0-9가-힣])(? digits and metres: "half a meter" -> "0.5 m", "오십 센치" -> "0.5 m", "일 미터 반" -> "1.5 m", "구십 도" -> "90도".""" + t = re.sub(rf"(? the Korean word ("레프트로 반 미터 가 줘요", "라이트 턴 해") + (r"왼쭉|왼족", "왼쪽"), (r"멈처|멈쳐", "멈춰"), (r"슴니(?=다|까)", "습니"), (r"(? the Korean word ("레 (r"(고개|머리|헤드|얼굴)\s*(?:를|을)?\s*업(?![가-힣])", r"\1 들어"), (r"(고개|머리|헤드|얼굴)\s*(?:를|을)?\s*다운(?![가-힣])", r"\1 숙여"), (_NO + r"헤드(?=\s)", "고개"), + (_NO + r"웨이스트(?=\s|를|을|는|가)", "허리"), ] @@ -415,8 +434,17 @@ _END_NOT_ASKED = r"(?=(?:\s+(?:빨리|얼른|어서|좀|제발|당장|지금|ple _HON = r"(?:세요|세용|세여|십시오|시오|셔요|시죠|실래요|실래|시겠어요|시겠습니까|시겠어|시게|이소(?:마|예)?|거라|너라|렴|라고요?|랑께요?|래이|이라|쇼|시라|시지요|실래예|씨요|세예)" _LOOK_AT = r"(왼쪽|오른쪽|위|위쪽|아래|아래쪽|뒤|뒤쪽|앞|하늘|천장|바닥|여기|이쪽|저쪽|나|날|저|정면|좌측|우측)" KO_PLAIN = [ + *((re.compile(a), b) for a, b in KONGLISH[:8]), # slips / Konglish above + (re.compile(r"(?<=[가-힣?!.~]) +(?:허허|하하|헤헤|호호|히히|ㅋ+|ㅎ+)[\s!.~]*$"), ""), # a laugh after it: "돌아 봐요 허허" + (re.compile(r"(? 1 and stem not in ("다시",): + stem = stem[:-1].removesuffix("으") or stem # honorific: "트실 수" -> 트, "도실 수" -> 도, "집으실" -> 집 + return {"드": "들", "도": "돌", "트": "틀", "여": "열", "미": "밀", "내미": "내밀", "흔드": "흔들"}.get(stem, stem) def _can_you(m, kind): @@ -508,12 +541,14 @@ def ko_plain(t): for rx, to in KO_PLAIN: if to in ("CAN_L", "CAN_N"): t = rx.sub(lambda m: _can_you(m, to), t) - elif to == "STEM": + elif to in ("STEM", "STEMQ"): def stem(m): w = m.group(1) if KO_SOCIAL_BEFORE.search(m.string[:m.start()]): return m.group(0) got = _stem_aform(w[:-1] if w.endswith("으") and len(w) > 1 and _jamo(w[-2]) and _jamo(w[-2])[2] else w) + if to == "STEMQ" and got: + return got + ("?" if got == "줘" else " 줘?") return got if got else m.group(0) t = rx.sub(stem, t) else: @@ -536,7 +571,7 @@ def norm(text, names=()): """Lower case, whisper's slips (ASR_SLIPS), Konglish directions (KONGLISH), numbers first ("point five meters" is a distance), then marker names (names: the map's).""" t = " " + (text or "").lower().replace("’", "'") + " " - t = re.sub(r"(\S+)[—–-]+\s*(?=\1)", "", t) # a stutter: "육십 센— 센티", "go ah— ahead" + t = re.sub(r"(?`), whisper slips (mix `slip`). Formats are round 6's (r6 commands / r6 +dialogues sections), NO new expect tokens. De-duplicated inside a split, held against train and both against every +earlier round's train text (exact; a dialogue's scored say used before gets a filler in front). Load as +`tests.blind.r9..`. + +| File | train / held | Notes | +|---|---|---| +| `commands_go`, `_move`, `_turn`, `_look`, `_lift`, `_waist` | 2842/2814, 2524/2527, 1773/1772, 2304/2290, 1225/1225, 884/884 | r6 conventions; numbers in every form (digits, 일 / 이 / 삼, 한 / 두, English words, 원 / 투 / 쓰리) | +| `commands_wave`, `_reach`, `_hand`, `_give`, `_take`, `_put`, `_bring` | 869/836, 869/864, 1006/896, 761/731, 1182/1175, 768/757, 2042/2038 | handshakes = wave, 손 줘 / give me a hand = reach; hand includes "is your hand open?" (`status \| talk`) | +| `commands_follow`, `_come`, `_point`, `_stop`, `_status`, `_voice` | 585/573, 768/753, 483/478, 812/813, 943/741, 977/959 | stop: every running action as `before`; status `_b`: near misses (don't tell, my phone's battery, words to another person, reported, later) | +| `commands_more`, `_chain`, `_detour` | 703/458, 1499/1492, 1759/1688 | more `_b`: near misses at every level; detour `_b`: "why did you stop?" at every level (`talk \| status`) | +| `commands_missions`, `commands_sing`, `speed_short` | 1495/1485, 698/580, 1263/1093 | sing `_b`: every song and the song list at every level; speed_short (≤ 3 words, `fast: True`) `_b`: every short meaning at every level + short near misses | +| `questions_world` | 6311/3659 | quick / knowledge / unknown / lookup / time meanings (field `q`) at every level; held is smaller: same-text questions were kept only in train | +| `dialogues_mixed` | 440/440 (4569/4539 scored turns) | a fact, really? / a false claim / a follow-up, a command on the dialogue's map, a near miss, status, thanks + a question, goodbye; one level per dialogue | +| `followup_dialogues` | 330/330 (2970/2970) | follow-ups on Lumi's answer, contradictions (AGREE in must_not) | +| `closing_context` | 429/414 | field `closing` end / continue | +| `seeing_dialogues` | 328/324 (1640/1620) | r6 person fields; the scene changes | +| `memory_dialogues` | 207/199 (1242/1194) | r6 memory format | +| `lookup_dialogues` | 154/154 (1279/1289) | r6 lookup format (`lookup` field per turn): weather (city / here, day, ask general / rain / temp / dust / wind), day-only / city-only follow-ups, umbrella / 몇 도 / 미세먼지 for the talk's place and day (`lookup:weather \| none`), climate knowledge (장마철, 황사, 태풍: `none` + must), a remark, near misses (already checked, don't tell me, a friend asked, a plan if it rains, news later: `none`, lookup None), news (topic, more, the second / last one), thanks + a new question, goodbye; one speaker = one dialect; the hello is not scored | + +A file `_b.py` is a growth file (`logs/w4_gen/gen_grow9.py`) filling the cells the first write left empty; +published files are never changed. Totals: 37345 train / 33581 held cases, 1888 train / 1861 held dialogues. Per +level (cases + scored turns) 7.5–10.1 % each (en_nonnative lowest, ko_dialect highest); near misses 19–26 % at every +level. Unique text 72 % (the same wording on several maps / states / before-actions is one text). + +Generators (seeded, not in the repo): `logs/w4_gen/` on the Thor: `ko.py` (Hangul, request endings per level, +negation / ability / condition / later / reported / remark / others / take-back frames, numbers, slips), `qlib.py` +(question endings per level), `caps.py` (command meanings), `spoken9.py` (marker forms), `render.py`, `gen_cmd.py`, +`questions.py`, `gen_dlg.py`, `gen_all.py` (the first write), `gen_lookup9.py`, `gen_grow9.py`; `check_r9.py` checks +imports, fields, levels, maps / markers, expect tokens, steps, regexes, no earlier train text, no case in both splits, +and parity (every set has every level in both splits, every meaning `intent` / `q` / song at every level in both +splits, near misses at every level in every command set, dialogues_mixed and lookup_dialogues): 0 problems. + +## r10 (round 10, 2026-10-26: English half, cup tasks, writer W5) + +`r10/train/` and `r10/held/`, written blind from docs/14, docs/16 and docs/17 (no assistant code or bank read). The +owner's complaint: round 9 was only ~17 % English. Here English is **half of every set** (en_native 27 %, en_nonnative +23 %), the nine Korean / Konglish / mixed levels of round 9 share the other half (5.6 % each), and every meaning is said +at every level in both splits. English wordings: plain, polite and indirect ("would you mind …ing", "could you +possibly …", "I was wondering if you could …", "I need you to …"), questions that are requests ("can you …?", "how about +…ing?", "any chance you could …?"), casual, rude, long and rambling ("sorry to bother you, but …", "my hands are full, +so …"), children; non-native English (broken frames "you can …?", "I want that you …", articles dropped); accent and +whisper slips ("tern lef", "pleace", "kup", "tay bull"). Near misses at every level in every command set: negation, +ability questions that are no request ("is it possible for a robot like you to …, in general?"), condition, later, +reported, remark, words to others, take-back, hypothetical, quote (`:hard_`, expect `talk | ask`; "don't look at +me" = `action:look away | talk | ask`). Field `level` as round 9, `style` on English cases (plain, polite, direct, +question, casual, rude, long, child, nonnative, nn_whole, whole). No text in both splits, none of an earlier round's +train text (rounds 1–4, r6, r8, r9). Formats of round 9; NO new expect tokens. Load as `tests.blind.r10..`. + +| File | train / held | Notes | +|---|---|---| +| `commands_go`, `_move`, `_turn`, `_look`, `_lift`, `_waist` | 1754, 2036, 1372, 1975, 782, 697 (each split) | r6 conventions; amounts new to this round (move 15 / 25 / 40 / 60 / 70 cm, 2.5 / 3 m, 3.5 m refused; turn 20–150°; look 5–50°; lift 3–15 cm; waist 20 / 60 / 90°) | +| `commands_wave`, `_reach`, `_hand`, `_give`, `_take`, `_put`, `_bring` | 826, 712, 724, 526, 730, 526, 1029 | handshakes = wave, "lend me your hand" = reach; give / take / put / bring here are apples, oranges and "it" (the cups are in `commands_cup`) | +| `commands_follow`, `_come`, `_point`, `_stop`, `_status`, `_voice` | 524, 712, 473, 968, 1023 / 965, 922 | stop with every running action as `before`; status includes "what's in your hand?", "where are you taking that cup?" and near misses (my phone's battery, don't tell me) | +| `commands_more`, `_chain`, `_detour` | 853 / 846, 1402, 1282 | chain: 45 % cup chains ("pick up the cup and look at me", holding "put the cup down and give us a wave": `chain \| mission`, `parts` "pick cup", "pick red cup", "put down", "give") | +| `commands_missions` | 1800 | step notation of tests/test_steps.py; cup missions: `pick red cup \| go M \| give`, `pick cup \| go M \| place`, `go M \| receive cup wait \| go here`, `go M \| give Sarah`, `pick cup \| go M \| give \| go here`, `go M \| place \| go here`, `receive hand \| go M`, `pick white cup \| give`, `go M \| pick cup \| go here`, `pick cup \| go M \| place dining table`, plus waits, two places, an instruction wait; `?` for coffee, dancing, later, conditions (field `kind` P1–P14 / hard) | +| `commands_sing`, `speed_short` | 828 / 804, 1024 / 1000 | sing: every song at every level; speed_short ≤ 3 words, `fast: True`, every capability at every level incl. the cup ("hand it over", "set it down") | +| `commands_cup` | 11114 | NEW set, command format (scored like the other command sets). Idle: pick by colour (`action:pick red cup \| mission \| refuse`) or by which one ("the cup on the left", "the smaller cup", "제일 가까운 컵": `action:pick cup \| …`); search ("look for the red cup": `seeing \| action:look \| action:pick red cup \| mission \| action:fetch \| ask \| talk`); take from a hand (`receive \| talk`); "pass me the cup" (`mission \| action:fetch \| action:pick cup`); fetch from a marker, from one marker to another, to a named person at a marker, deliver and come back (`action:fetch \| mission`, `\| ask` for a translated marker name); "wait here until I tell you" (`talk \| stop \| ask`); "give me the cup" idle (`empty_hand \| ask \| talk \| mission \| action:fetch \| action:pick cup`). Holding (state `holding`, 44 %): give to me (`give`), to a described person ("the man in the blue shirt", "her": `give \| ask`), to a name only (`ask \| give`), put here / on a named thing / back, carry to a marker (`mission \| action:fetch \| action:go_to M`), carry and put on the table there; new orders on the way (before `("bring the cup to Sarah at the stage", "ACTION: mission")`): stop, wait here (`stop \| talk \| ask`), "no, the other table" (`place \| ask \| talk`), "give it to her instead" (`give \| ask`), "go to M instead", "never mind, bring it back". Whole-sentence corrections are not wrapped in request frames (style `whole`) | +| `dialogues_mixed` (+ `_b`) | 303 (2121 scored turns), _b 502 (2644 / 2646) | one level per dialogue; mixed: 4 commands in a talk, a near miss, status, goodbye. `_b` cup talks: (A) pick → "what are you holding?" → give (`give \| empty_hand \| none`, the checker keeps the start's hand) → thanks (`action:arm open \| give \| none`); (B) holding: put on a named table → "no, the other table" → give to a described person → a near miss; (C) fetch from a marker → stop → to a named person; (D) take from the hand → carry to a marker → "don't move until I say so" → come here → give | +| `memory_dialogues` | 161 (644 scored turns) | r6 memory format with cup memory: `seen` a cup today (where), `self.holding` a cup or nothing, a talk yesterday with the command "bring the red cup to stage"; turns: where was the cup seen, what are you holding (`status \| none`), what did I ask yesterday (cup + place), "do what we said" (`ask \| none`, the place read back) | + +Totals: 36614 train / 36501 held cases, 966 / 966 dialogues; per level (cases + scored turns) English 49.8 % +(en_native 26.9, en_nonnative 22.9), each Korean / Konglish / mixed level 5.6 %. Unique text 89.8 %. + +Generators (seeded, not in the repo): `logs/w5_gen/` on the Thor: `en10.py` (English frames, -ing forms, non-native +grammar, accent slips, near-miss frames), `render10.py` (a meaning at a level; Korean endings from W4's +`logs/w4_gen/ko.py` plus indirect ones), `caps10.py` (single commands), `cup10.py` (cup tasks), `gen10.py` (all command +sets, missions, chain, sing, status, more, speed_short; train and held filled cell by cell from one pool of taken +texts), `dlg10.py` (dialogues); `check_r10.py` (round 9's checks plus no held text in train and the English share): +0 problems. diff --git a/tests/blind_check.py b/tests/blind_check.py index c58d4eb..4fdf402 100644 --- a/tests/blind_check.py +++ b/tests/blind_check.py @@ -73,7 +73,7 @@ SETS = ["commands_go", "commands_move", "commands_turn", "commands_look", "comma "commands_stop", "commands_status", "commands_chain", "commands_detour", "speed_short", "commands_sing", "commands_missions", "seeing_dialogues", "followup_dialogues", "dialogues_mixed", "unknowns", "silence_noise", "hearing", "questions_world", "memory_dialogues", "commands_come", "commands_hand", "commands_point", - "commands_voice", "commands_waist", "commands_more", "closing_context"] + "commands_voice", "commands_waist", "commands_more", "closing_context", "lookup_dialogues"] # commands_chain, commands_detour, speed_short, dialogues_mixed: round r2 on; # questions_world, memory_dialogues: r6 on. Any other file in a round's folder # is scored too, by the set its name grows ("commands_go_b" as commands_go) @@ -164,6 +164,7 @@ def _persons(frames=None): scene.snapshot = lambda cameras=None, since=None: [SCENE["now"]] if SCENE["now"] is not None else [] scene.things, scene.people, scene._persons = _things, _people, _persons +scene.speaker_key = lambda d, b: 0 # scene._front's stable sort keeps _persons' order: the speaker A first (A6) VLM_ASKED = [("glasses", r"glass|안경|선글"), ("hat", r"\bhat|\bcap\b|beanie|모자|캡"), ("hair", r"hair|머리"), ("bag", r"bag|backpack|가방|배낭"), ("top_pattern", r"pattern|stripe|check|dot|print|무늬|줄무늬|체크|땡땡이"), ("bottom_kind", r"jeans|trousers|pants|skirt|shorts|바지|청바지|치마|반바지"), @@ -222,6 +223,8 @@ def turn_route(b, say, lang, mk, state="idle", use_llm=True): """One turn the way lumi.answer() goes: command_check.rules (drive words, then lumi.route) with seeing.answer on the fake scene; what the rules leave through dialogue_check.run_turn with the cameras' facts (and the hand) in the prompt. (route in dialogue_check's notation, reply, by). A rule's fixed line is "" (not judged).""" + if lang not in ("en", "ko"): # r9 "mix" turns: Lumi answers in Korean or English + lang = "ko" if brain.HANGUL.search(say) else "en" brain.FORCED_LANG["lang"] = lang said = {} @@ -256,6 +259,9 @@ def turn_route(b, say, lang, mk, state="idle", use_llm=True): got if got.startswith("action:") else "action:" + got) if r.startswith("action:") or r == "mission": b.history.append((say, f"ACTION: {r.split(':', 1)[1] if ':' in r else r}")) + elif r in ("weather", "search"): # lumi.look_up keeps the question (+ WEATHER_ASKED) + b.last_lookup = say + brain.WEATHER_ASKED if r == "weather" else say + b.history.append((b.last_lookup, "")) return r, "", "rules" if not use_llm: return "llm?", "", "-" @@ -452,6 +458,7 @@ def score_missions(c, old, use_llm): got=json.loads(json.dumps(got)), unread=unread) +LOOKUP = {"lookup:weather": "weather", "lookup:news": "search", "lookup:web": "search"} # lookup_dialogues (r9) FORGOT = set(__import__("assistant.memory", fromlist=["FORGOT"]).FORGOT.values()) @@ -483,6 +490,8 @@ def score_dialogue(d, old, use_llm, judge=False): r, reply, by = turn_route(b, turn["say"], lang, mk, state, use_llm) if r == "llm?": rows.append(row(key, "llm?" if scored else "-", "-", "", route="", reply="")) + if turn.get("closing"): + rows[-1]["closing"] = turn["closing"] b.history.append((turn["say"], "")) continue if r.startswith("action:give") or r.startswith("action:place"): @@ -492,7 +501,7 @@ def score_dialogue(d, old, use_llm, judge=False): if not scored: rows.append(row(key, "-", by, "", route=r, reply=reply)) continue - want = dict(turn, expect_action=" | ".join(a.strip().removeprefix("action:") + want = dict(turn, expect_action=" | ".join(LOOKUP.get(a.strip(), a.strip()).removeprefix("action:") for a in turn.get("expect_action", "none").split(" | "))) looked_up = r in ("weather", "search", "search(unsure)") and \ not dialogue_check.action_ok(want["expect_action"], r) # a lookup's answer is talk (not checked) @@ -512,6 +521,8 @@ def score_dialogue(d, old, use_llm, judge=False): r, reply, by, probs, note, v = "error", repr(e), "-", [repr(e)], "", "error" rows.append(row(key, v, by, f"{d['topic']} t{j + 1} {turn['say']!r} -> [{r}] {reply[:120]!r} {probs}{note} " f"(check: {turn.get('check')})", route=r, reply=reply, judged=judged)) + if turn.get("closing"): + rows[-1]["closing"] = turn["closing"] # closing_context: "end" / "continue", counted apart return rows @@ -743,6 +754,7 @@ def run_set(split, name, old_rows, use_llm, cached, limit, sample=None): rows.append(row(str(c)[:200], "error", "-", f"{str(c)[:150]} -> {e!r}")) for r in rows[n:]: r["lang"] = lang_of(c, r) + r["level"] = level_of(c, r) if r["verdict"] in ("wrong", "motion", "error") and "-v" in sys.argv: print(f" {r['verdict'].upper():6} {r['show'][:200]}", flush=True) return rows @@ -764,6 +776,56 @@ def lang_of(c, r): return "mix" if ko and en else "ko" if ko else "en" +LEVEL_NAME = {"banmal": "ko_banmal", "haeyo": "ko_haeyo", "hapsyo": "ko_hasipsio", "friendly": "ko_friendly", + "honorific": "ko_honorific", "dialect": "ko_dialect"} # W2's names (r6 _i files) -> r9's +LEVEL_GUESS = [("ko_dialect", r"(?:주이소|하이소|하입시더|하이소|데이|카이|라예|랑께|허자잉|줘유|해유|줍서|헙서|마씸|아이가|머꼬|와이라|" + r"하모|맞제|그라제|했노|하노|하나\?|가\?)[.?!~]*$|잉[.?!~]*$|(?:주소|해 ?도)[.?!]*$"), + ("ko_hage", r"(?:하게|주게|하네|하세|보게|오게|가게나|하시게)[.?!~]*$|자네"), + ("ko_honorific", r"(?:시[어겠었]|으시|하시|주시|가시|보시|께서|드리|드릴|드려|여쭤|여쭙|계세|계십|잡수|주무|말씀)"), + ("ko_hasipsio", r"(?:습니다|습니까|[가-힣]니다|[가-힣]니까|십시오|시오|하십시다)[.?!~]*$"), + ("ko_friendly", r"ㅋ|ㅎㅎ|~|임\?|ㄱㄱ|ㅇㅇ|ㄹㅇ|당[.?!]*$|용[.?!]*$|쥬[.?!]*$"), + ("ko_haeyo", r"요[.?!~,]*(?:\s|$)")] + + +def level_of(c, r): + """The speech level of a case or a scored turn: its "level" field (r9; W2's names in r6 _i files read as r9's), + else guessed from the Korean endings (marked "*"); English "en*", mixed "mixed*".""" + turn = {} + if isinstance(c, dict) and "turns" in c and r["key"][:1].isdigit(): + j = int(r["key"].split("|", 1)[0]) - 1 + turn = c["turns"][j] if 0 <= j < len(c["turns"]) else {} + case = c if isinstance(c, dict) else c[1] if isinstance(c, (list, tuple)) and len(c) > 1 and \ + isinstance(c[1], dict) else {} + lv = turn.get("level") or (case.get("level") if not turn or "turns" not in case else None) + if lv: + return LEVEL_NAME.get(lv, lv) + if r.get("lang") == "en": + return "en*" + if r.get("lang") == "mix": + return "mixed*" + text = turn.get("say") or case.get("text") or case.get("heard") or (c[0] if isinstance(c, (list, tuple)) else "") + text = (text or "").strip() + return next((name + "*" for name, rx in LEVEL_GUESS if re.search(rx, text)), "ko_banmal*") + + +def by_level(saved): + """right / cases per speech level over every set (r9 / r6 _i: as labelled; "*": guessed from the endings), and the + closing turns (closing_context) by kind.""" + lv, cl = collections.defaultdict(collections.Counter), collections.defaultdict(collections.Counter) + for name in ordered(saved): + for r in saved[name]["rows"]: + if r["verdict"] != "-": + lv[r.get("level", "?")][r["verdict"]] += 1 + if r.get("closing"): + cl[r["closing"]][r["verdict"]] += 1 + lines = ["", "By speech level (right / cases, motions in brackets; * = guessed from the endings):", "", + "| level | right | wrong | motion | llm? |", "|---|---|---|---|---|"] + lines += [f"| {k} | {cell(lv[k])} | {lv[k]['wrong']} | {lv[k]['motion']} | {lv[k]['llm?']} |" for k in sorted(lv)] + if cl: + lines += ["", "Closing turns: " + ", ".join(f"{k} {cell(cl[k])}" for k in sorted(cl))] + return lines + + def cell(k): n = sum(k.values()) return f"{k['right']}/{n} ({100 * k['right'] // max(1, n)} %)" + (f" [{k['motion']}]" if k["motion"] else "") if n else "-" @@ -801,7 +863,7 @@ def report(split, saved, secs): n = sum(tot.values()) lines.append(f"| ALL | | {n} | {tot['right']} | {100 * tot['right'] // max(1, n)} | {tot['wrong']} | " f"{tot['motion']} | {tot['llm?']} | {tot['error']} | |") - lines += by_lang(saved) + lines += by_lang(saved) + by_level(saved) for name in ordered(saved): rows = saved[name]["rows"] dl = {} @@ -814,7 +876,7 @@ def report(split, saved, secs): r["show"].replace("\n", "\n ") for r in bad] or ["- none"] out = ROOT / "logs" / f"blind_{split}.md" out.write_text("\n".join(lines) + "\n") - print("\n".join(lines[:len(saved) + 7] + by_lang(saved))) + print("\n".join(lines[:len(saved) + 7] + by_lang(saved) + by_level(saved))) def main(args): diff --git a/tests/command_check.py b/tests/command_check.py index d6a0530..2d68ce6 100644 --- a/tests/command_check.py +++ b/tests/command_check.py @@ -87,8 +87,9 @@ def rules(text, state, marks, b): return "refuse" # Lumi.wave refuses with something held (wave.HOLDING) if data[0] == "put" and not holding: return "empty_hand" # skills.put_down: nothing picked, nothing moves - if data[0] == "fetch" and not holding and {"object", "place"} & set(brain.parse_fetch(text, marks)[1]): - return "ask" # fetch_dialog asks what is missing before anything moves + if data[0] == "fetch" and (holding or {"object", "place"} & set(brain.parse_fetch(text, marks)[1])): + return "ask" # fetch_dialog asks what is missing before anything moves; + # holding: lumi.fetch_request asks where to put it first return data[0] if data[0] in ("weather", "search") else f"action:{data[0]} {data[1]}".strip() return None diff --git a/tests/dialogue_check.py b/tests/dialogue_check.py index 029614d..fc5f6dc 100644 --- a/tests/dialogue_check.py +++ b/tests/dialogue_check.py @@ -87,7 +87,11 @@ def run_turn(b, text, lang, marks): bye = b.farewell(text, lang) b.reset() return r, bye, time.time() - t0, time.time() - t0 - if r.startswith("action:") or r in ("weather", "search"): # quick_command keeps it in the history + if r in ("weather", "search"): # lumi.look_up: the question (+ WEATHER_ASKED) is kept + asked = text + brain.WEATHER_ASKED if r == "weather" else text # so "도쿄는?" / "how about Daegu?" follow it + b.history.append((asked, by_rule[1] or "")) + b.last_lookup = asked + elif r.startswith("action:"): # quick_command keeps it in the history a = r.split(":", 1)[-1].split(" ", 1) b.history.append((text, f"ACTION: {a[0]} {a[1] if len(a) > 1 else '-'}")) return r, by_rule[1], None, time.time() - t0 diff --git a/tests/dialogues_night4.py b/tests/dialogues_night4.py index 888de57..49ae4b4 100644 --- a/tests/dialogues_night4.py +++ b/tests/dialogues_night4.py @@ -5,7 +5,8 @@ part?"), "really?" / "are you sure?" right after a motion (about the talk before number, settled facts after thanks (answered, not looked up), short follow-ups never answered "say it again". English, Korean (반말 / 해요체 / 하십시오체 / friendly / honorific / dialect) and mixed; Korean replies polite. - .venv/bin/python tests/dialogues_night4.py [only] # through tests/followup_check.main -> logs/a4n4/night4_check.* + .venv/bin/python tests/dialogues_night4.py [only] [--b] # through tests/followup_check.main -> logs/a4n4/night4_check.* + # (--b: round 2 -> night4b_check.*) """ import sys @@ -81,14 +82,78 @@ DIALOGUES_NIGHT4 = [ T("말씀하신 거 아까랑 좀 다른 것 같은데요?", must=[r"유칼립투스|잎|에너지|6|여섯|개월|18|20"], no=NK + [WHICH], check="같은 사실을 다시"), T("감사합니다, 많이 배웠어요. 안녕히 계세요.", "end")), + D("grandfather", "owl_ko_dialect", "ko", + T("부엉이 목 그거 을매나 돌아가노?", must=[r"270|이백칠십"], no=NK + [ME], check="270도; Lumi의 고개가 아님"), + T("그래 돌리믄 피는 우째 되노?", must=[r"피|혈관|혈액|핏줄|흐르|막히"], no=NK + [ME], check="혈관이 특별해서 피가 계속 흐름; " + FU), + T("눈은 와 안 움직이노?", must=[r"크|커|뼈|고정|관|원통"], no=NK + [ME], check="눈이 커서 고정; " + FU), + T("어... 그... 뭐였더라...", "-"), + T("참말이가?", must=[r"네|정말|맞|크|고정|270|피"], no=NK + [ME], check="부엉이 얘기를 다시 (못 알아들은 턴 전의 얘기)"), + T("욕봤다, 간데이.", "end")), + D("engineer", "lotte_mixed_konglish", "ko", + T("롯데월드타워 height 몇 m예요?", must=[r"555|오백오십오"], no=NK, check="555m"), + T("floor는 몇 개?", must=[r"123|백이십삼"], no=NK, check="123층; " + FU), + T("uh... what was it... 그...", "-"), + T("are you sure?", must=[r"555|123|yes|네|맞"], no=NK, rl="en", check="롯데월드타워 숫자를 다시 (못 알아들은 턴 전)"), + T("Okay, thanks. Bye!", "end")), +] + +# round 2 (10:50): parts named after a world subject ("심장은 몇 개고?", "Why the name?"), lower-case English subjects, +# Lumi's own numbers asked casually and very politely, "really?" after an uncaught turn, a topic taken up again +DIALOGUES_NIGHT4B = [ + D("student", "giraffe_en_native", "en", + T("Why do giraffes have such long necks?", must=[r"leaves|tree|reach|food|fight|eat"], no=N + [ME], check="to reach high leaves"), + T("How many bones are in it?", must=[r"seven|7"], no=N + [ME], check="seven, like ours; " + FU), + T("And the heart, is it big?", must=[r"kilo|kg|big|large|pump|blood|11|60 ?cm"], no=N + [ME], check="about 11 kg; " + FU), + T("hmm... the... uh...", "-"), + T("Really?", must=[r"yes|seven|7|kilo|kg|big"], no=N, check="yes, the giraffe facts again (before the uncaught turn)"), + T("Cool, thanks. Bye!", "end")), + D("grandmother", "lumi_specs_ko_honorific", "ko", + T("루미 님 머리에 든 컴퓨터는 메모리가 얼마나 되시는지요?", must=[r"122|백이십이"], no=NK, check="122GB"), + T("팔로는 얼마나 무거운 걸 드실 수 있으세요?", must=[r"2 ?(?:kg|킬로)|1 ?(?:kg|킬로)|이 ?킬로|일 ?킬로"], no=NK, + check="팔 2kg, 손에는 약 1kg"), + T("아이고 그래요? 정말이세요?", must=[r"네|2|1|킬로|맞"], no=NK, check="네, 같은 숫자를 다시"), + T("고마워요. 그럼 키는 어떻게 되세요?", must=[r"146|186|백사십"], no=NK, check="146cm, 올리면 186cm"), + T("잘 들었어요, 수고하세요.", "end")), + D("friend", "octopus_ko_banmal", "ko", + T("문어 피는 무슨 색이야?", must=[r"파란|푸른|청색"], no=NK + [ME], check="파란색"), + T("왜?", must=[r"구리|헤모시아닌|산소"], no=NK + [ME], check="구리가 든 헤모시아닌; " + FU), + T("심장은 몇 개야?", must=[r"3|세 ?개|셋"], no=NK + [ME], check="3개 (문어의 심장)"), + T("아까 피 색깔 뭐라 했지?", must=[r"파란|푸른|청색"], no=NK, check="파란색 (앞의 얘기로 돌아감)"), + T("ㅇㅋ 고마워, 간다~", "end")), + D("tourist", "namsan_mixed_konglish", "ko", + T("남산타워 언제 오픈했어요?", must=[r"1975|1980|칠십|팔십"], no=NK, check="1975년 완공, 1980년 개방"), + T("height는요?", must=[r"236|480|미터"], no=NK, check="약 236m; " + FU), + T("why 이름이 N이에요?", must=[r"남산|new|새|N"], no=NK + [r"제 이름|루미"], check="Namsan / new; 루미의 이름이 아님"), + T("Okay 땡큐!", "end")), + D("engineer", "sound_ko_hasipsio", "ko", + T("빛의 속도는 초속 몇 킬로미터입니까?", must=[r"30만|300,?000|삼십만|299"], no=NK, check="약 30만 km/s"), + T("소리는 어떻습니까?", must=[r"340|343|삼백사십"], no=NK + [ME], check="공기 중 약 340m/s; " + FU), + T("물속에서는 얼마나 빠릅니까?", must=[r"1,?500|1,?480|천오백|4|네 ?배"], no=NK, check="약 1,500m/s"), + T("확실하십니까?", must=[r"네|1,?500|천오백|맞|확실"], no=NK, check="네, 물속 숫자를 다시"), + T("수고하십시오.", "end")), + D("parent", "lumi_battery_en_nonnative", "en", + T("your battery, how many hour it go?", must=[r"10|ten"], no=N, check="about 10 hours"), + T("and when it is empty, you go charging alone?", must=[r"yes|myself|by myself|on my own|dock|charg"], no=N, + check="yes, goes to the charger by itself"), + T("hm ok, and the arm can carry how much?", must=[r"2 ?kg|two|1 ?kg|one|kilo"], no=N, check="2 kg with the gripper, ~1 kg in the hand"), + T("Sure?", must=[r"yes|2|two|1|one|kilo"], no=N, check="yes, the same numbers"), + T("Okay, see you.", "end")), + D("grandfather", "palace_ko_dialect", "ko", + T("경복궁 그거 언제 지었노?", must=[r"1395|조선|태조"], no=NK, check="1395년"), + T("이름은 와 그래 지었노?", must=[r"복|큰|하늘|복을|경사|시경|백성|태평"], no=NK + [r"제 이름|루미"], + check="큰 복을 누리라는 뜻; 루미의 이름이 아님"), + T("불은 몇 번 났노?", must=[r"임진왜란|1592|불|탔|화재|여러"], no=NK, check="임진왜란 때 탔고 1867년 다시 지음; " + FU), + T("고맙데이, 수고하그래이.", "end")), ] if __name__ == "__main__": from tests import followup_check as fc from tests import dialogue_check as dc - fc.DIALOGUES = DIALOGUES_NIGHT4 + b = "--b" in sys.argv # round 2: its own report + fc.DIALOGUES = DIALOGUES_NIGHT4B if b else DIALOGUES_NIGHT4 (dc.ROOT / "logs" / "a4n4").mkdir(exist_ok=True) - dc.OUT_JSON, dc.OUT_MD = dc.ROOT / "logs" / "a4n4" / "night4_check.json", dc.ROOT / "logs" / "a4n4" / "night4_check.md" + name = "night4b_check" if b else "night4_check" + dc.OUT_JSON, dc.OUT_MD = dc.ROOT / "logs" / "a4n4" / f"{name}.json", dc.ROOT / "logs" / "a4n4" / f"{name}.md" args = [a for a in sys.argv[1:] if not a.startswith("--")] fc.main(args[0] if args else None, failed="--failed" in sys.argv) diff --git a/tests/ko_levels_check.py b/tests/ko_levels_check.py index 994b3c6..76d35d3 100644 --- a/tests/ko_levels_check.py +++ b/tests/ko_levels_check.py @@ -44,6 +44,16 @@ CAPS = { "sing": ("sing a song", "노래", "부르", "불러", ["노래 싱 해 줘"]), "louder": ("speak louder", "더 크게", "말하", "말해", []), "slower": ("speak slower", "좀 천천히", "말하", "말해", []), + "quieter": ("speak more quietly", "좀 작게", "말하", "말해", []), + "look_dn": ("look down", "아래를", "보", "봐", ["다운 봐 줘", "look down 해 주세요"]), + "look_me": ("look at me", "저를", "보", "봐", ["룩 앳 미 해 줘"]), + "around": ("turn around", "뒤로", "돌", "돌아", ["유턴 해 줘", "turn around 해 주세요"]), + "come_back": ("come back", "", "돌아오", "돌아와", ["컴백 해 줘"]), + "waist": ("turn your waist left", "허리를 왼쪽으로", "돌리", "돌려", ["웨이스트 레프트로 돌려 줘"]), + "body_up": ("raise your body", "몸을", "올리", "올려", ["리프트 업 해 줘", "바디 업 해 줘"]), + "open": ("open your hand", "손", "펴", "펴", ["핸드 오픈 해 줘"]), + "put": ("put the cup down", "컵 내려", "놓", "놔", []), + "charge": ("go charge", "충전하러", "가", "가", ["차지하러 가 줘"]), } EN_FORMS = ["{}", "please {}", "{}, please", "could you {}?", "can you {} for me?", "would you {}, please?", "I'd like you to {}", "I'd love it if you could {}", "{}, if you don't mind", "lumi, {}", @@ -138,7 +148,8 @@ def check(names=None): "missed" if got is None or got.split()[0] in command_check.NO_MOTION else "wrong")) for t in not_now(pre, stem, a): got = read(t) - moves = got is not None and got.split()[0] not in command_check.NO_MOTION + moves = got is not None and got.split()[0] not in command_check.NO_MOTION and \ + not (got == "action:look away" and "지 마" in t) # "저를 보지 마세요": looking away is asked rows.append((name, "not_now", t, got, "no motion", "right" if not moves else "wrong" if got in ("stop", "sing") else "motion")) # a stop or a song moves nothing return rows diff --git a/tests/test_fetch_words.py b/tests/test_fetch_words.py new file mode 100644 index 0000000..e2a2349 --- /dev/null +++ b/tests/test_fetch_words.py @@ -0,0 +1,151 @@ +"""Self-check of cup-task wordings (night 4, F1), no robot, no LLM: python tests/test_fetch_words.py + +1. brain.parse_fetch: where the thing is (source), where it goes (dest), which one (prefer), at every speech level. +2. steps.rules: cup tasks of several parts (fetch then more, deliver and come back, put it at a place, wait until + someone takes it, Korean calls / endings of every level, Korean written without spaces). +Notation of tests/test_steps.py.""" +from assistant import brain, steps + + +def short(s): + """The notation of tests/test_steps.py, the kinds used here.""" + w = s.split() + if w[0] == "go": + return {"do": "go", "to": w[1]} + if w[0] == "pick": + return {"do": "pick", "object": w[-1], "colour": w[1] if len(w) == 3 else None} + if w[0] == "receive": + return {"do": "receive", "object": w[1], **({"wait_s": steps.WAIT_GIVE_S} if w[-1] == "wait" else {})} + if w[0] == "wait": + if w[1:2] == ["order"]: + return {"do": "wait", "s": steps.WAIT_ORDER_S, "until": "instruction"} + return {"do": "wait", "s": float(w[1]) if len(w) > 1 else None} + if w[0] == "turn": + return {"do": "turn", "deg": float(w[1])} + if w[0] == "place": + return {"do": "place", "on": {"name": "dining table", "colour": None, "side": None} if len(w) > 1 else None} + if w[0] == "give" and len(w) > 1: + return {"do": "give", "person": s[5:]} + return {"do": w[0]} + +M = ["home", "p1", "p2", "p3", "p4", "p5", "Registration", "Main_Stage", "Coffee_Bar"] +P = lambda n: {"marker": n} + +# ---- 1. one fetch: (object, colour, source, dest, finish[, prefer]); None = asked ---- +FETCH = { + "bring me the red cup from p3": ("cup", "red", P("p3"), "here", "hold"), + "could you grab me the cup that's on p2?": ("cup", None, P("p2"), "here", "hold"), + "get me the cup on the left from p1": ("cup", None, P("p1"), "here", "hold", "left"), + "fetch the white cup from the coffee bar": ("cup", "white", P("Coffee_Bar"), "here", "hold"), + "would you mind bringing the cup over from p5": ("cup", None, P("p5"), "here", "hold"), + "p1 red cup bring me please": ("cup", "red", P("p1"), "here", "hold"), + "bring the cup on p1 to p4": ("cup", None, P("p1"), P("p4"), "hold"), + "take the cup from p1 to p4": ("cup", None, P("p1"), P("p4"), "hold"), + "bring the cup to p1": ("cup", None, "here", P("p1"), "hold"), + "p3에서 빨간 컵 가져와": ("cup", "red", P("p3"), "here", "hold"), + "피삼에 있는 컵 좀 가져다줄래?": ("cup", None, P("p3"), "here", "hold"), + "피투에 있는 왼쪽 컵 가져와 줘": ("cup", None, P("p2"), "here", "hold", "left"), + "피원 컵 가져와": ("cup", None, P("p1"), "here", "hold"), + "p1의 컵 가져와": ("cup", None, P("p1"), "here", "hold"), + "커피 바에서 하얀 컵 갖다 주시겠어요?": ("cup", "white", P("Coffee_Bar"), "here", "hold"), + "피오에서 작은 컵 좀 가져다 주십시오": ("cup", None, P("p5"), "here", "hold", "small"), + "일 번 포인트에 있는 컵 좀 갖다 줘": ("cup", None, P("p1"), "here", "hold"), + "피원에서 컵 가져다가 피사에 있는 테이블에 놔": ("cup", None, P("p1"), P("p4"), "place"), + "컵을 p1에 갖다 놔": ("cup", None, "here", P("p1"), "place"), + # a person, not a place: asked + "bring the cup from p2 to Minsu": ("cup", None, P("p2"), None, "hold"), + "p2에서 컵 가져다가 민수한테 줘": ("cup", None, P("p2"), None, "hold"), + "빨간 옷 입은 여자분께 컵 갖다 드려": ("cup", None, "here", None, "hold"), +} +bad = [] +for text, want in FETCH.items(): + task, _ = brain.parse_fetch(text, M) + got = (task["object"], task["colour"], task["source"], task["dest"], task["finish"]) + \ + ((task["prefer"],) if task.get("prefer") else ()) + if got != want: + bad.append(f"FAIL fetch {text!r}\n want {want}\n got {got}") + +# ---- 2. several parts ---- +STEPS = { + "deliver the cup to p5 and come back": "pick cup | go p5 | give | go here", + "take the cup to p5, leave it there and come back": "pick cup | go p5 | place | go here", + "컵을 p5에 갖다 주고 돌아와": "pick cup | go p5 | give | go here", + "컵 피오에 갖다 놓고 돌아와 주세요": "pick cup | go p5 | place | go here", + "컵을 피오에 갖다 드리고 돌아오십시오": "pick cup | go p5 | give | go here", + "bring me the cup from p2 and then go back home": "go p2 | pick cup | go here | give | go home", + "p2에서 컵 가져다 주고 충전기로 가": "go p2 | pick cup | go here | give | go home", + "p1에서 병 가져다 p2에 놔 주고 여기로 돌아와": "go p1 | pick bottle | go p2 | place | go here", + "p1에 있는 컵을 p4로 가져다 놔": "go p1 | pick cup | go p4 | place", + "go to p3 and wait until someone takes the cup": "go p3 | give", + "피삼에 가서 누가 가져갈 때까지 기다려": "go p3 | give", + "피삼에 가서 누가 받을 때까지 기다려 주세요": "go p3 | give", + "p3에 가서 민수한테 컵 받아서 가져와": "go p3 | receive cup | go here", + "go to p3, take the cup from Minsu and bring it to me": "go p3 | receive cup | go here | give", + "컵 들고 p2로 가서 거기 있는 사람한테 줘": "pick cup | go p2 | give", + "빨간 컵을 p4에 있는 민수한테 갖다 줘": "pick red cup | go p4 | give 민수", + "fetch the cup from p1, then wait here": "go p1 | pick cup | go here | wait", + "피원에서 빨간 컵 가져다가 피삼에 놔 줘": "go p1 | pick red cup | go p3 | place", + "피일에서 컵 가져다 주시고 홈으로 가십시오": "go p1 | pick cup | go here | give | go home", + "take the bottle to p2 and wait there until someone takes it, then come back": "pick bottle | go p2 | give | go here", + "병 들고 피투로 가서 누가 가져갈 때까지 기다렸다가 돌아와": "pick bottle | go p2 | give | go here", + "컵 피삼에 갖다 주고 10초 기다렸다가 홈으로 가": "pick cup | go p3 | give | wait 10 | go home", + "빨간 컵을 피사에 갖다 놓으시고 돌아오세요": "pick red cup | go p4 | place | go here", + "take the cup to the main stage and hand it to whoever is there": "pick cup | go Main_Stage | give", + "find the red cup and bring it to me": "pick red cup | go here | give", + "빨간 컵 찾아서 나한테 가져다 줘": "pick red cup | go here | give", + "point one에서 빨간 컵 가져와서 P5에 있는 사람한테 줘": "go p1 | pick red cup | go p5 | give", + "take the banana to the main stage and give it too Mr. Kim": "pick banana | go Main_Stage | give Mr. Kim", + "에구 하얀 컵 집어서 p4로 가져가서 테이블에 놔, 응": "pick white cup | go p4 | place dining table", + "p4에 가서 누가 빨간 컵 주면 받아 가지고 와": "go p4 | receive cup wait | go here", + "p4 가서 십 초 wait 하고 와": "go p4 | wait 10 | go here", + # a new order on the way (lumi.mission_talk reads it with steps.read) + "no, bring it to p4 instead": "go p4", + "아니야 피사로 가져가 줘": "go p4", + "change of plan, go to p4 and put it down": "go p4 | place", + "그거 저 사람한테 줘": "give", + # calls and endings of every level, Konglish, no spaces + "이보게 루미, 피삼에 가서 30초 기다렸다가 돌아오게나": "go p3 | wait 30 | go here", + "루미 님께서 피삼으로 가서 30초 기다렸다가 돌아와 주시길 부탁드립니다": "go p3 | wait 30 | go here", + "아야 루미, 피투로 가서 1분 기다렸다가 돌아와 주시겄슈": "go p2 | wait 60 | go here", + "우리 루미, 피투로 가서 한 바퀴 돌고 돌아와 주라~": "go p2 | turn 360 | go here", + "자네, 피투로 가서 오더 받고 컴백해 주게나": "go p2 | wait order | go here", + "피사에가서5분있다가다시오세요": "go p4 | wait 300 | go here", + "홈 포지션에 들렀다가 피투로 가게나": "go home | go p2", +} +for text, want in STEPS.items(): + got, unread = steps.rules(text, M) + if unread or got != [short(s.strip()) for s in want.split(" | ")]: + bad.append(f"FAIL steps {text!r}\n want {want}\n got {got}\n unread {unread}") + +# ---- 3. holding: put it at a place = a drive there and a put-down ---- +for text in ("put it on p3", "p3에 갖다 놔", "피삼에 놔 줘", "leave it at the registration"): + got, unread = steps.rules(text, M) + if unread or [s["do"] for s in got] != ["go", "place"]: + bad.append(f"FAIL put at {text!r}: {got} {unread}") + +# ---- near misses: nothing is read as a task part ---- +NEAR = ["did you bring the cup from p1 and go home?", "don't bring the cup from p1, go home", "I'll bring the cup from p1 myself", + "tomorrow bring me the cup from p1 and go to p2", "my friend brought the cup from p1 and went home", + "p1에서 컵 가져오지 마", "내가 p1에서 컵 가져올게", "어제 p1에서 컵 가져왔지?", "컵을 p5에 갖다 줬어?", + "p3에 갖다 놓지 마", "did you deliver the cup to p5?"] +for text in NEAR: + got, unread = steps.rules(text, M) + if not unread and got: + bad.append(f"FAIL near miss {text!r}: {got}") + +# ---- 4. a correction after the read-back (fetch_dialog): what changes ---- +T = {"object": "cup", "colour": "red", "source": P("p1"), "dest": "here", "finish": "hold"} +FIX = {"no, the blue one": {"colour": "blue"}, "아니 파란 거": {"colour": "blue"}, "not p1, p2": {"source": P("p2")}, + "피원 말고 피투": {"source": P("p2")}, "the one on the left": {"prefer": "left"}, "왼쪽 거": {"prefer": "left"}, + "the smaller one": {"prefer": "small"}, "아니 작은 거": {"prefer": "small"}, "no, from p2": {"source": P("p2")}, + "아니 피사로": {"dest": P("p4")}, "no, the bottle": {"object": "bottle", "colour": None}, + "the other one": {}, "아니 다른 거": {}} # not said which: nothing changes, Lumi asks what to change +for text, want in FIX.items(): + task, changed = brain.parse_correction(text, T, M) + if {k: task.get(k) for k in changed} != want: + bad.append(f"FAIL correction {text!r}: want {want}, got {({k: task.get(k) for k in changed})}") + +print("\n".join(bad)) +print(f"{len(FETCH) + len(STEPS) + len(FIX) + len(NEAR) + 4 - len(bad)}/{len(FETCH) + len(STEPS) + len(FIX) + len(NEAR) + 4} right") +assert not bad +print("fetch words ok") diff --git a/tests/test_followup.py b/tests/test_followup.py index fb71150..7077af2 100644 --- a/tests/test_followup.py +++ b/tests/test_followup.py @@ -203,4 +203,27 @@ if __name__ == "__main__": assert brain._follow_examples(t, h), t for t in ("Where is p3?", "세종대왕이 누구예요?", "oh cool", "What's your name?", "Tell me about the Korean War."): assert not brain._follow_examples(t, h), t + # a world subject keeps Lumi's notes out (also lower-case English and a part named after it); Lumi's own things keep them + b = brain.Brain() + for h, t, want in (([], "Why do whales sing?", ["whales"]), ([], "부엉이는 고개를 몇 도까지 돌려요?", ["부엉이"]), + ([("Why do whales sing?", "ACTION: none -\nTo find mates.")], "How far can the song go?", ["whales"]), + ([("문어는 다리가 몇 개고?", "ACTION: none -\n여덟 개예요.")], "심장은 몇 개고?", ["문어", "다리", "심장"]), + ([], "속도는 얼마예요?", []), ([], "How fast can you go?", []), ([], "Is the song yours?", []), + ([], "Can the arm lift 2 kg?", [])): + b.history = list(h) + assert b.world_talk(t) == want, (t, b.world_talk(t)) + # "really?" after a turn Lumi did not catch asks about the answer before it + h = [("롯데월드타워 높이 몇 m예요?", "ACTION: none -\n555미터예요."), + ("uh... what was it... 그...", "ACTION: unclear -\n죄송해요, 다시 말씀해 주시겠어요?")] + assert brain.topic_turn(h)[0].startswith("롯데월드타워"), brain.topic_turn(h) + # the model's "search" with its answer after it: said (none); a lookup promise or "don't know" keeps the search + s = {"action": "search", "target": "x"} + q = "윤초는 뭐예요?" + for w in ("윤초는 지구 자전과 시계를 맞추는 1초예요.", "Mount Fuji is 3,776 metres high."): + assert brain.Brain._settled(s, w, q)["action"] == "none", w + for w in ("확인해 볼게요.", "Let me check.", "search whale song distance", "잘 모르겠어요.", "", "윤초는 뭐예요?", + "윤초가 궁금하시군요. 잠시만요.", "What exactly do you mean?"): + assert brain.Brain._settled(s, w, q) is s, w + assert brain.CHANGES.search("지금 비트코인 얼마야?") and brain.CHANGES.search("Who won the game yesterday?") + assert not brain.CHANGES.search("윤초는 뭐예요?") and not brain.CHANGES.search("How do bees dance?") print("followup ok") diff --git a/tests/test_ko_levels.py b/tests/test_ko_levels.py new file mode 100644 index 0000000..b793453 --- /dev/null +++ b/tests/test_ko_levels.py @@ -0,0 +1,17 @@ +"""Korean speech levels read as the English request (a fixed part of tests/ko_levels_check.py): every level of a few +capabilities gives the same action, and the same phrase said as a past, a negation, a later time or a condition +gives no motion. No robot; the embedding server answers the bank. + + .venv/bin/python tests/test_ko_levels.py +""" +from tests import ko_levels_check + +CAPS = {"wave", "turn45", "head_up", "follow", "fetch", "go_to"} + +rows = ko_levels_check.check(CAPS) +bad = [r for r in rows if r[-1] != "right"] +for name, level, text, got, want, v in bad: + print(f"FAIL {name} [{level}] {text!r} -> {got} (want {want}, {v})") +assert not bad, f"{len(bad)} of {len(rows)} not right" +assert len(rows) > 400, len(rows) +print(f"ok: {len(rows)} forms") diff --git a/tests/test_route_words.py b/tests/test_route_words.py new file mode 100644 index 0000000..d442cc4 --- /dev/null +++ b/tests/test_route_words.py @@ -0,0 +1,142 @@ +"""Commands, questions and asides through the voice / Command box route (command_check.rules = lumi.route without the +LLM), night 4: tag questions, take-backs at every Korean level, other people addressed, polite stops, chains that are +one order, amounts not read. A wrong motion is the worst error: None (the LLM reads it) is right for the no-motion +cases. No robot. + + .venv/bin/python tests/test_route_words.py +""" +from assistant import brain, detour +from tests import command_check + +M = ["p1", "p2", "p3", "p5", "p6", "home", "dock2"] +CASES = [ # (text, state, route) + # a statement with a tag, an ability said back: asked + ("you went to P5 earlier, right?", "idle", None), ("you can lift your arm, right?", "idle", None), + ("너 팔 접을 수 있지, 그치?", "idle", None), ("너 팔 접을 수 있지?", "idle", None), ("wave, right?", "idle", "action:wave"), + ("손 흔들고 나 봐, 알았지?", "idle", "chain:wave+look_me"), ("팔 접어, 알겠죠?", "idle", "action:arm fold"), + ("팔 뻗을 줄 아세요?", "idle", None), ("팔을 뻗을 줄 압니까?", "idle", None), ("robot, you know how reach out to me?", "idle", None), + ("robot can say hi with your hand or not? I just ask", "idle", None), ("멸 센티까지 잡아?", "idle", None), + ("Back to your arm, what did you say?", "idle", None), + # one order, not a chain + ("손 흔들어서 작별 인사 해 주시겠어요?", "idle", "action:wave"), ("손 흔들어서 인사해", "idle", "action:wave"), + ("컵 들고 몇으로 가?", "idle", None), ("잔 들고 천천히 가는 속도가 얼마야?", "idle", None), + ("하객분들 앞에서 손 거둬!, 아 거두시겠어요?", "idle", "action:arm fold"), + ("로봇아, 좌측으로 10 센티미터 움직여라, 아 움직여 주실래요?", "idle", "action:move left 0.1"), + ("이장이 말하는디, 팔 제자리로 해", "idle", "action:arm fold"), ("take your hand back, da?", "idle", "action:arm fold"), + ("so, robot, head to p6, da?", "idle", "action:go_to p6"), ("could you possibly hand it over?, eh?", "holding", "give"), + ("exactly please I'll hold it, give it here", "holding", "give"), + ("pick up the cup, how fast do you go?", "idle", "chain:steps+talk"), ("고개 들고 몇 시야?", "idle", "chain:look_up+talk"), + ("치수 불러 줄게, 내 머리 무슨 색이야?", "idle", "seeing"), + # handed over or not + ("이거 줄게", "idle", "receive"), ("컵 줄게요", "idle", "receive cup"), ("사진 찍어 줄게", "idle", None), + ("자 그럼 Lumi, wave your hand 해 봐요", "holding", "refuse"), ("give 해 줘", "holding", "give"), + ("it'd be cool if you could give me the cup someday", "holding", None), + # polite stops, calls, Konglish + ("멈춰 주시겠어요?", "idle", "stop"), ("멈춰 주실래요?", "idle", "stop"), ("정지해 주시겠습니까?", "idle", "stop"), + ("can you stop for me?", "idle", "stop"), ("루미 씨, 잠깐 멈춰 주실 수 있나요?", "idle", "stop"), + ("can you stop for coffee?", "idle", None), ("루미 씨, 팔 접어 주세요", "idle", "action:arm fold"), + ("컴 히어 해 줘", "idle", "action:come"), ("이리 컴", "idle", "action:come"), ("컴퓨터 꺼 줘", "idle", None), + # other people addressed + ("쉿 아기 자니까 엄마 그거 나 줘", "holding", None), ("질문을 바꿔서, 엄마 그거 나 줘", "holding", None), + ("이륙 전 점검, 할머니 이제 팔 접어 좀", "idle", None), ("어머님, 컵을 들어 보세요, 저기 로봇 있어요", "idle", None), + ("김 군, 자네도 팔 뻗어 보게", "idle", None), ("우리 아들, 빠빠이 해 봐 봐~", "idle", None), + ("shh, Sarah, make your way to p2", "idle", None), ("우리 p3 갈까 여보", "idle", None), + ("루미야 할머니한테 손 흔들어 줘", "idle", "action:wave"), ("okay, Lumi, go to p5", "idle", "action:go_to p5"), + # taken back, later, negated: every level + ("로봇 씨, 손 흔들어 주시길 바랍니다, 아, 하지 않으셔도 됩니다", "idle", "talk"), ("저기유, 손 흔들어 줘유, 아녀, 됐슈", "idle", None), + ("악수해 주십시오, 아닙니다, 취소하겠습니다", "idle", "talk"), ("루미야~ 나랑 악수해~, 장난이야~", "idle", "talk"), + ("wave 해 줄 수 있지?, 아냐 아냐 됐어 ㅋㅋ", "idle", "talk"), ("음악 나오믄 악수해 보이소", "idle", None), + ("나중에~ 손 wave 해~", "idle", None), ("행사가 끝난 후에 나한테 손 흔드십시오", "idle", None), + ("robot, if I say go, then reach out to me", "idle", None), ("you not give me the cup", "holding", None), + ("no hold out your hand, please", "idle", None), + ("no need to return it to where it was", "holding", None), ("put down 하지 않으셔도 됩니다", "holding", None), + ("파란 컵 좀 들지 마이소", "idle", None), ("자네 컵 잡는 거 제법이더군", "idle", None), + # 하게체 / dialect requests to Lumi, floor, status + ("자네, 손을 흔들어 주게나", "idle", "action:wave"), ("이보게 루미, 악수하게", "idle", "action:wave"), + ("나한테 손 흔들어 줄 수 있지?", "idle", "action:wave"), ("어이 로봇아, 손 흔들어 주드라고", "idle", "action:wave"), + ("바닥에 내려놔 주이소", "holding", "refuse"), ("의자 밑에 놔", "holding", "refuse"), ("의자 위에 놔", "holding", "place chair"), + ("그리퍼 오픈 상태야?", "idle", "status"), ("is it possible for you to open your fingers, in general?", "idle", None), + ("can you look up for me?", "idle", "action:look up"), ("would you stop, please?", "idle", "stop"), + ("흰색 머그컵 잡아!, 아 잡아 줄 수 있어요?", "idle", "action:pick white cup"), + ("제자리에, 루미, 손 앞으로 내밀어 봐", "idle", "action:arm reach"), ("Lumi, I heard you can put that back", "holding", None), + # gives at every level, self-corrections said again, head / body / base words + ("로봇아, 선생님께 드려라", "holding", "give"), ("자네, 할머니께 드리시게", "holding", "give"), + ("grandma한테주십시오", "holding", "give"), ("루미, 이리 좀 조", "holding", "give"), ("루미야, 기브 미 해 주세여", "holding", "give"), + ("로봇아, 그거 주세요", "idle", "empty_hand"), ("좌측으로 20센티 움직여 줘, 아니 움직이실래요?", "idle", "action:move left 0.2"), + ("루미야 우측으로 15도 돌아 봐, 아니 돌아 봐요 허허", "idle", "action:turn right 15"), ("p6로 가, 아니지 p2로 가", "idle", "action:go_to p2"), + ("이제 팔 접어 좀. 아니야 그냥 있어", "idle", "talk"), ("두 걸음 뒤로 물러서 줘, 부탁해", "idle", "action:move back 1"), + ("어이로봇아,상체오른쪽으로십오도쫌돌려줘유", "idle", None), ("저기 루미야, 웨이스트 레프트로 좀 돌리세요", "idle", "action:waist left"), + ("몸통째 왼쪽으로 돌려", "idle", "action:turn left 90"), ("실례합니다. 왼쪽을 돌아봐 주시겠습니까?", "idle", "action:look left"), + ("look right at me 해 하하", "idle", "action:look me"), ("Lumi go ahead and look down at the ground", "idle", "action:look down"), + ("루미 씨, 발 밑 바라보지 마세요", "idle", None), ("쳐다보지 마", "idle", "action:look away"), + ("prove you're smart: come on back", "idle", "action:come_back"), ("루미 360 돌아 봐", "idle", "action:turn right 360"), + ("dude, stick your hand out", "idle", None), ("dude, halt", "idle", "stop"), ("손님상에 여보 후진 2미터 반 움직여 봐", "idle", None), + ("이따가 멈춰 주세요", "idle", None), + # amounts + ("루미,앞으로삼십센티미터가", "idle", "ask"), ("뒤로1미터50이동해부러", "idle", "action:move back 1.5"), + ("앞으로 30센티 가", "idle", "action:move forward 0.3"), + # a stop for later or reported (night 4, round 3) + ("행사가 끝난 후에 멈춰 주시길 바랍니다", "idle", None), ("내일 그만하시게", "idle", None), + ("아까 직원분이 그만하라고 지시했습니다", "idle", None), ("루미 군, 그만하시게", "idle", "stop"), + ("저기요, 당장 멈춰 주시길 바랍니다", "idle", "stop"), + # turn (try turning) or look round; a correction said as a new order in full + ("왼쪽으로 돌아 봐", "idle", "action:turn left 90"), ("오른쪽으로 돌아봐 줄래요?", "idle", "action:look right"), + ("왼쪽으로 돌아보시게", "idle", "action:look left"), ("레프트 턴 해 봐", "idle", "action:turn left 90"), + ("루미 오른편으로 135도 돌아— 아니 왼편으로 백이십 도 돌아 주세요~", "idle", "action:turn left 120"), + ("우리 루미, 오른쪽으로 백삼십오 도 돌아... 아 잘못 말했다, 몸통째 왼쪽으로 돌려 주세요", "idle", "action:turn left 90"), + ("go forward half a metre, no wait, back up 10 cm", "idle", "action:move back 0.1"), + ("turn left 45 degrees, no, right", "idle", "action:turn right 45"), + ("좌측으로 20센티 움직여 줘, 아니 움직이실래요?", "idle", "action:move left 0.2"), + ("부스 B로 가서 왼쪽으로 돌아요", "idle", "talk"), ("hello robot, please come back for me, thank you", "idle", "action:come_back"), + ("애플 그랩 해", "idle", "action:pick apple"), ("실례합니다. 제자리에 지금 갖다 놓으십시오", "holding", "action:put back"), + # round 4: new wordings + ("back to your arm. what was it again?", "idle", None), ("now face the other way", "idle", "action:turn around 180"), + ("do a 180, please", "idle", "action:turn around 180"), ("룩 다운 해 주세요", "idle", "action:look down"), + ("룩 앳 미 해 줘", "idle", "action:look me"), ("룩 업 할 수 있어?", "idle", None), + ("바이바이 좀 하세요", "idle", "action:wave"), ("어이 로봇, 빠빠이 하시게", "idle", "action:wave"), + ("멈추시게", "idle", "stop"), ("hold it right there", "idle", "stop"), ("내일 멈추시게", "idle", None), + ("you put down arm please", "idle", "action:arm fold"), ("어이 로봇아, 손 쪼까 내려 줘", "idle", "action:arm fold"), + ("Lumi, may I ask you to stretch your arm out?", "idle", "action:arm reach"), ("is your arm out?", "idle", "status"), + ("Lumi, robot, put it down ok?", "holding", "place"), ("I put it down, now?", "holding", "seeing"), + ("할머니 드려라", "holding", "give"), ("우리 할머니 드리십시오", "holding", "give"), ("전화 드려", "holding", None), + ("인사 드려", "holding", None), ("연락 줘", "holding", None), + ("손 흔들면서 인사하고 고개 숙여", "idle", "chain:wave+look_down"), + ("왔던 길로 돌아가", "idle", "action:come_back"), ("원래 있던 자리로 가 주세요", "idle", "action:come_back"), + ("go back the way you came", "idle", "action:come_back"), ("원래 있던 자리로 가지 마", "idle", None), + ("어제 왔던 길로 가면 돼요", "idle", None), ("knock it off, Lumi", "idle", "stop"), ("whoa there", "idle", "stop"), + ("whoa, that's cool", "idle", None), ("lemme have it", "holding", "give"), + # "would you mind …ing", polite conditions and "-주시면 안 될까요" (lead, 11:30) + ("would you mind shaking hands", "idle", "action:wave"), ("would you mind coming here?", "idle", "action:come"), + ("do you mind waving at the kids?", "idle", "action:wave"), ("would you mind stopping here, please", "idle", "stop"), + ("would you mind if I took a photo?", "idle", None), ("would you mind not moving?", "idle", None), + ("손 흔들어 주시면 안 될까요?", "idle", "action:wave"), ("괜찮으시면 악수해 주실래요?", "idle", "action:wave"), + ("p3로 가 주시면 안 될까요?", "idle", "action:go_to p3"), ("실례가 안 된다면 이리 와 주시겠어요?", "idle", "action:come"), + ("혹시 괜찮으시면 컵 좀 집어 주실 수 있을까요?", "idle", "action:pick cup"), ("if you don't mind, wave at me", "idle", "action:wave"), + ("괜찮으시면 손 흔들지 마세요", "idle", None), ("괜찮으시면 내일 p3로 가 주세요", "idle", None), + ("괜찮으시면 저한테 주시면 안 될까요?", "holding", "give"), ("hello robot", "idle", None), + ("hello robot, wave", "idle", "action:wave"), +] + +DETOUR = [ # right after a blocked drive to p2: (text, detour.read) + ("아까 저 아저씨가 루미한테 다시 가라고 했어", None), ("아까 재시도하는 거 정말 신기했어요", None), + ("다른 루트로 가시겠어요?, 아, 아닙니다, 괜찮습니다", None), ("얘 뒤로 조금 갔다가 다시 가는 거 봤냐?", None), + ("지가 말하믄 재시도해부러", None), ("다시 시도할 줄은 알아?", None), ("그냥 돌아올 줄 아는가?", None), + ("다시 시도해 줘", "retry"), ("다른 길로 가 주세요", "around"), ("루미야 포기하지 마", "retry"), + ("never mind that, just try again", "retry"), + ("루미야, 다른 길 있나 민수야?", None), ("여러분, 모두 포기하고 돌아와 보시기 바랍니다", None), +] + + +def main(): + detour.recent = lambda: None # no blocked drive just now (whatever the live state says) + bad = [f"detour {t!r} -> {detour.read(t, M, 'p2')!r} (want {w!r})" for t, w in DETOUR if detour.read(t, M, "p2") != w] + for text, state, want in CASES: + got = command_check.rules(text, state, M, brain.Brain()) + if got != want: + bad.append(f"{text!r} [{state}] -> {got!r} (want {want!r})") + print("\n".join(bad) or f"route words ok ({len(CASES)} cases)") + assert not bad + + +if __name__ == "__main__": + main() diff --git a/tests/test_wake.py b/tests/test_wake.py index edbe659..075ba5f 100644 --- a/tests/test_wake.py +++ b/tests/test_wake.py @@ -118,7 +118,8 @@ said = lambda: [d[1] for d in done if isinstance(d, tuple) and d[0] == "say"] # ---- the calls that wake Lumi (EN + KO + whisper slips) and what does not ---- for call in ("Lumi.", "Hi Lumi.", "Hi.", "Hello Lumi!", "Hello.", "Hey Lumi", "How are you?", "Hi, how are you?", "루미야.", "루미.", "안녕.", "안녕하세요.", "하이.", "하이 루미!", "Hi, Loomi.", "Hello, Rumi.", "Hai.", - "Lummy?", "누미야", "안녕하십니까."): + "Lummy?", "누미야", "안녕하십니까.", "Wake up.", "Wake up, Lumi!", "Hey Lumi.", "Lumi, wake up.", + "헤이 루미", "루미야 일어나", "루미 일어나세요.", "일어나세요.", "깨어나 루미야"): L = fresh() L.mic = Mic(U(call)) assert L.check_wake(), call @@ -128,6 +129,7 @@ for heard in ("Let's make music.", "What is that?", "We make it.", "Let's.", "It L.mic = Mic(U(heard)) assert not L.check_wake(), heard # 16:57:00, 17:05:03 live: "(no wake word)" assert not lumi.call_only("Lumi, what time is it?") and not lumi.call_only("루미야 노래 불러줘") +assert not lumi.WAKE.search("I wake up at 7 every day") and not lumi.WAKE.search("일어나서 밥 먹었어") # no call L = fresh() # "How are you?" is answered, not "Yes? How can I help?" L.mic = Mic(U("How are you?")) L.check_wake()