Faster replies: TTS on the GPU, LLM prompt cache kept warm

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-21 20:11:04 +09:00
co-authored by Claude Opus 5.5
parent fe8319bc95
commit 334b5f5b2b
16 changed files with 1180 additions and 83 deletions
+1
View File
@@ -206,6 +206,7 @@ Logs are in `logs/`: `lumi.log` (assistant), `lumi_console.log` (its stderr), `a
| `models/face_detection_yunet_2023mar.onnx`, `models/face_recognition_sface_2021dec.onnx` | face detector and embedding for `vision/reid.py` (without them only clothes are used) | github.com/opencv/opencv_zoo | | `models/face_detection_yunet_2023mar.onnx`, `models/face_recognition_sface_2021dec.onnx` | face detector and embedding for `vision/reid.py` (without them only clothes are used) | github.com/opencv/opencv_zoo |
| `models/ggml-large-v3-turbo-q5_0.bin` | whisper model | Hugging Face `ggerganov/whisper.cpp` | | `models/ggml-large-v3-turbo-q5_0.bin` | whisper model | Hugging Face `ggerganov/whisper.cpp` |
| `models/supertonic3/` | TTS model | Hugging Face `Supertone/supertonic-3` | | `models/supertonic3/` | TTS model | Hugging Face `Supertone/supertonic-3` |
| `models/supertonic3_vector_estimator.engine`, `models/supertonic3_vocoder.engine` | the TTS's two slow parts on the GPU (`audio/tts_gpu.py`; without them the CPU, 5–10x slower). Bound to this TensorRT and GPU: rebuild after a JetPack or TensorRT change | `.venv/bin/python audio/tts_gpu.py build` (~3 min), then `check` |
| `whisper.cpp/` | v1.9.5, built with CUDA | `cmake -B build -DGGML_CUDA=ON -DCMAKE_CUDA_ARCHITECTURES=110 -DCMAKE_BUILD_TYPE=Release && cmake --build build -j 12 --target whisper-server whisper-cli` | | `whisper.cpp/` | v1.9.5, built with CUDA | `cmake -B build -DGGML_CUDA=ON -DCMAKE_CUDA_ARCHITECTURES=110 -DCMAKE_BUILD_TYPE=Release && cmake --build build -j 12 --target whisper-server whisper-cli` |
| `~/models/bge-m3-Q8_0.gguf` | embedding model for the knowledge base | Hugging Face | | `~/models/bge-m3-Q8_0.gguf` | embedding model for the knowledge base | Hugging Face |
| `knowledge/index.npz` | knowledge vectors | `assistant/knowledge.py build` | | `knowledge/index.npz` | knowledge vectors | `assistant/knowledge.py build` |
+170 -19
View File
@@ -383,7 +383,7 @@ HEAD_WORDS = (r"\blook (?:straight )?(?:up|down|left|right|ahead|forward|straigh
r"|(?:고개|머리)(?:를|좀|살짝|조금|약간|\s)*(?:왼쪽|오른쪽|위|아래|정면|앞|들어|숙여|올려|내려|돌려)" r"|(?:고개|머리)(?:를|좀|살짝|조금|약간|\s)*(?:왼쪽|오른쪽|위|아래|정면|앞|들어|숙여|올려|내려|돌려)"
r"|(?:위|아래|밑|왼쪽|오른쪽|정면|앞|나|날|저|절|나를|저를)(?:를|을|으로|로|쪽|쪽을|에)?\s*(?:좀\s*)?(?:봐|보세요|봐요|봐 ?줘|봐 ?주세요|볼래|봐 ?봐)") r"|(?:위|아래|밑|왼쪽|오른쪽|정면|앞|나|날|저|절|나를|저를)(?:를|을|으로|로|쪽|쪽을|에)?\s*(?:좀\s*)?(?:봐|보세요|봐요|봐 ?줘|봐 ?주세요|볼래|봐 ?봐)")
LIFT_WORDS = (r"\b(?:raise|lift|lower) (?:yourself|your body|your torso|your upper body)\b|\blift (?:yourself )?(?:up|down)\b(?! (?:the|a|an|that|this|it)\b)" LIFT_WORDS = (r"\b(?:raise|lift|lower) (?:yourself|your body|your torso|your upper body)\b|\blift (?:yourself )?(?:up|down)\b(?! (?:the|a|an|that|this|it)\b)"
r"|\bget (?:taller|shorter|smaller)\b|\bmake yourself (?:taller|shorter|smaller)\b|\bstand (?:up )?tall(?:er)?\b" r"|\bget (?:a (?:little |tiny )?bit |a little |slightly )?(?:taller|shorter|smaller|higher|lower)\b|\bmake yourself (?:taller|shorter|smaller)\b|\bstand (?:up )?tall(?:er)?\b"
r"|\b(?:go|move) (?:higher|lower)\b|키(?:를)? ?(?:좀 )?(?:[\d.]+ ?(?:m|mm|cm) ?(?:만 ?)?)?(?:높여|키워|올려|낮춰|줄여|크게|작게)" r"|\b(?:go|move) (?:higher|lower)\b|키(?:를)? ?(?:좀 )?(?:[\d.]+ ?(?:m|mm|cm) ?(?:만 ?)?)?(?:높여|키워|올려|낮춰|줄여|크게|작게)"
r"|몸(?:을)? ?(?:좀 )?(?:[\d.]+ ?(?:m|mm|cm) ?(?:만 ?)?)?(?:올려|내려|낮춰|높여)" r"|몸(?:을)? ?(?:좀 )?(?:[\d.]+ ?(?:m|mm|cm) ?(?:만 ?)?)?(?:올려|내려|낮춰|높여)"
r"|리프트(?:를)? ?(?:좀 )?(?:올려|내려|위로|아래로)|상체(?:를)? ?(?:좀 )?(?:올려|내려|들어)") r"|리프트(?:를)? ?(?:좀 )?(?:올려|내려|위로|아래로)|상체(?:를)? ?(?:좀 )?(?:올려|내려|들어)")
@@ -463,23 +463,34 @@ INTENTS = [ # (action, pattern) checked in order on what the visitor said
r"(?:don'?t|do not|please don'?t) (?:look|stare) at me|quit (?:staring|looking))\b|(?:쳐다|바라)보지 ?마|" r"(?:don'?t|do not|please don'?t) (?:look|stare) at me|quit (?:staring|looking))\b|(?:쳐다|바라)보지 ?마|"
r"그만 ?(?:좀 ?)?(?:쳐다|바라)(?:봐|보세요)|" r"그만 ?(?:좀 ?)?(?:쳐다|바라)(?:봐|보세요)|"
r"(?:날|나를?|저를?|절)\s*(?:좀\s*)?(?:보지|쳐다보지) ?마|다른 ?(?:데|곳|쪽)(?:을|를)? ?(?:좀 )?봐"), r"(?:날|나를?|저를?|절)\s*(?:좀\s*)?(?:보지|쳐다보지) ?마|다른 ?(?:데|곳|쪽)(?:을|를)? ?(?:좀 )?봐"),
("stop", r"\b(stop|halt|freeze|don'?t move)\b|멈춰|정지|그만 ?가|거기 ?서|스톱|움직이지 ?마|^\s*(서[\s,!.]*){2,}$"), ("stop", r"\b(stop|halt|freeze|don'?t move)\b|멈춰|정지|그만 ?가|거기 ?서(?=[\s!.~,]*$)|스톱|움직이지 ?마|^\s*(서[\s,!.]*){2,}$"),
("follow", r"\b(?:follow|come with|come along with|walk with|tag along with)\s+(?:me|us)\b(?!\s+(?:on|at)\b)|" # not "follow ("follow", r"\b(?:follow|come with|come along with|walk with|tag along with)\s+(?:me|us)\b(?!\s+(?:on|at)\b)|" # not "follow
r"\bcome along\b|따라\s?(?:와|오세요|오십시오|올래)|(?<!로 )(?:같이|함께)\s?(?:가자|가요|갑시다|걸어)"), # me on instagram" r"\bcome along\b|(?<!말 )(?<!말을 )따라\s?(?:와|오세요|오십시오|올래)|(?<!로 )(?:같이|함께)\s?(?:가자|가요|갑시다|걸어)"), # me on instagram"
("fetch",rf"\b(fetch|bring|deliver|carry)\b.*\b({_OBJ}|it|that|this)s?\b|\b(take|get|grab)\b.*\b({_OBJ})s?\b.*\b(from|to)\b" ("fetch",rf"\b(fetch|bring|deliver|carry)\b.*\b({_OBJ}|it|that|this)s?\b|\b(take|get|grab)\b.*\b({_OBJ})s?\b.*\b(from|to)\b"
rf"|\b(go|drive) to\b.*\b(get|take|grab|pick up|fetch|bring)\b.*\b({_OBJ})s?\b" rf"|\b(go|drive) to\b.*\b(get|take|grab|pick up|fetch|bring)\b.*\b({_OBJ})s?\b"
rf"|\b(pick up|pick|take|grab|get)\b.*\b({_OBJ})s?\b.*\b(go|drive) to\b|({_OBJ}).*(집어서|들고).*가서" rf"|\b(pick up|pick|take|grab|get)\b.*\b({_OBJ})s?\b.*\b(go|drive) to\b|({_OBJ}).*(집어서|들고).*가서"
r"|가져와|가져다|갖다|가지고 ?와|에서.*(옮겨|가져)" rf"|({_OBJ}).*(집고|들고|가지고).*(와|줘)"), r"|가져와|가져다|갖다|가지고 ?와|에서.*(옮겨|가져)" rf"|({_OBJ}).*(집고|들고|가지고).*(와|줘)"),
("come", r"\bcome (?:back )?(here|to me|closer|over here|over)\b|\bcome\b.*\bme\b|이리 ?(?:돌아 ?)?와|여기로 ?(?:돌아 ?)?와|가까이 ?와|" ("come", r"\bcome (?:back )?(here|hear|to me|closer|over here|over)\b|\bcome\b.*\bme\b|이리 ?(?:좀 ?)?(?:돌아 ?)?(?:와|오세요|오십시오|올래)|"
r"여기로 ?(?:좀 ?)?(?:돌아 ?)?(?:와|오세요|오십시오)|가까이 ?(?:좀 ?)?(?:와|오세요)|"
r"나한테 ?(?:돌아 ?)?와"), r"나한테 ?(?:돌아 ?)?와"),
("go_home", r"\bgo (back )?(home|to (the |your )?(dock(?!2)|charger|charging))|\bgo charge|충전하러|집(?:에|으로) ?가|충전기로"), ("go_home", r"\bgo (back )?(home|to (the |your )?(dock(?!2)|charger|charging))|\bgo charge|충전하러|집(?:에|으로) ?가|충전기로"),
("go_point", r"\b(?:go|drive|move|head|come|return)(?: back)? to (?:the )?(?:point |marker )?([a-z][a-z0-9_]*)\b|(\d+)\s*번\s*(?:으로|포인트)" # after _norm: ("go_point", r"\b(?:go|drive|move|head|come|return|walk|roll|run|proceed|navigate|travel|hurry|make your way|get|take yourself)"
r"|^\W*(?:(?:루미야?|lumi|hey lumi)\W*)?(?:좀\s*)?(?:point\s+)?([a-z][a-z0-9_]*)\s*(?:으로|로|에)\s*(?:좀\s*)?" # "p3로 가 줘": r"(?: back)?(?: over| on| ahead)?(?: to| too| 2|to) (?:the )?(?:point |marker )?([a-z][a-z0-9_]*)\b|(\d+)\s*번\s*(?:으로|포인트)"
r"(?:가|와|이동해|돌아가|돌아 ?와)" # all of it r"|^\W*(?:(?:루미야?|lumi|hey lumi)\W*)?(?:[a-z][a-z0-9_]*\s*말고\s+)?(?:좀\s*)?(?:point\s+)?([a-z][a-z0-9_]*)\s*(?:앞|쪽|방향|지점|위치)?\s*"
r"(?:\s*줘요?|\s*주세요|요|자|줄래)?\s*[.!?]*$"), r"(?:으로|로|에|까지)?\s*(?:좀\s*)?(?:가|와|이동해|돌아가|돌아 ?와)" # "p3로 가 줘", "stage 가": all of it
r"(?:\s*(?:줘요?|주세요|줄래요?|주실래요?|주시겠어요|주십시오|줄 수 있(?:어요?|니|나요)|봐요?|보세요|볼까요?|"
r"주라|주시면 감사하겠습니다|줬으면 좋겠어요?|주면 좋겠어요?)|요|자|야 ?해요?|면 안 ?돼요?)?\s*[.!?]*$"
r"|^\W*(?:(?:루미야?|lumi|hey lumi)\W*)?(?:point\s+)?([a-z][a-z0-9_]*)\s*(?:으로|로)\s*(?:좀\s*)?"
r"(?:가십시오|가시겠어요|가시죠|가실래요)\s*[.!?]*$"
r"|^\W*(?:(?:hey|hi|okay|ok|so|um+|uh+|alright|please|well|now|lumi)\W+)*(?:go|drive|head)\s+([a-z][a-z0-9_]*)"
r"\W*(?:(?:please|now|for me|thanks)\W*)*$"), # whisper drops the "to": "go stage"
("sing", r"\bsing\b|\ba song\b|노래"), ("sing", r"\bsing\b|\ba song\b|노래"),
("look", HEAD_WORDS), # head_target() reads the direction and amount ("look", HEAD_WORDS), # head_target() reads the direction and amount
("wave", r"\bwave\b|\bshake (?:your |a |my )?hands?\b|\bsay (?:hi|hello|bye) with your hand\b|손 ?(?:을 |좀 |도 )?흔들|손 ?인사"), ("wave", r"(?:^|[,.!?]\s*)(?:(?:hey|hi|okay|ok|so|um+|uh+|alright|please|now|lumi|and|then)\W+)*(?:(?:can|could|would|will) you "
r"(?:please )?|please |let'?s |go ahead and |i'?d like you to |i want you to )?wave\b(?!s)|"
r"\bwave (?:at|to|your|hello|hi|bye|goodbye|back|again|for)\b|\bgimme a wave\b|\b(?:why don'?t you|if you (?:could|can|would)|"
r"you (?:could|should|can|might)|could you|would you|can you|will you) (?:please |just )?wave\b(?!s)|\bgive (?:(?:them|him|her|us|me|everyone|the \w+) )?"
r"a (?:little |quick |big |friendly )?wave\b|\bwave\s?(?:해|좀)|\bshake (?:your |a |my )?hands?\b(?! with\b)|\bsay (?:hi|hello|bye) with your hand\b|손 ?(?:을 |좀 |도 )?흔들|손 ?인사"),
("turn", r"\bturn (a)?round\b|\bturn (left|right)\b|뒤로 ?돌|돌아 ?봐|왼쪽으로 ?돌|오른쪽으로 ?돌"), ("turn", r"\bturn (a)?round\b|\bturn (left|right)\b|뒤로 ?돌|돌아 ?봐|왼쪽으로 ?돌|오른쪽으로 ?돌"),
("make_way", r"\b(can|could|would) you (please )?move( a bit| a little| please)?\s*[?.!]*$|\bmove (aside|out of the way|over)\b|" ("make_way", r"\b(can|could|would) you (please )?move( a bit| a little| please)?\s*[?.!]*$|\bmove (aside|out of the way|over)\b|"
r"\b(make way|get out of the way|give me some room)\b|비켜|자리 ?(좀 )?(비워|옮겨)|길 ?(좀 )?(비켜|터)"), r"\b(make way|get out of the way|give me some room)\b|비켜|자리 ?(좀 )?(비워|옮겨)|길 ?(좀 )?(비켜|터)"),
@@ -518,6 +529,10 @@ INTENTS = [ # (action, pattern) checked in order on what the visitor said
] ]
STOP_ASK = re.compile(r"(?:(?:can|could|would|will) you (?:please |just )?stop(?: (?:now|please|moving|driving|here|there))?|"
r"멈출 수 있(?:어|어요|니|나요)|멈춰 줄래요?|멈춰 줄 수 있(?:어|어요))\W*$", re.I) # "can you stop?": stop
COME_BACK = re.compile( # the whole sentence asks Lumi back to where it stood before its last trip COME_BACK = re.compile( # the whole sentence asks Lumi back to where it stood before its last trip
r"(?:(?:please|can you|could you|would you|will you|now|just|ok|okay|alright|so|and|lumi)\s+)*" r"(?:(?:please|can you|could you|would you|will you|now|just|ok|okay|alright|so|and|lumi)\s+)*"
r"(?:come back|return|(?:go|head|drive) back(?= ))(?: to)?(?: (?:where you (?:were|was|started|came from|were standing)" r"(?:come back|return|(?:go|head|drive) back(?= ))(?: to)?(?: (?:where you (?:were|was|started|came from|were standing)"
@@ -537,12 +552,16 @@ def intent(text, markers=()):
r"\b(can|could) you (pick( up)?|lift|hold|grab|take) (a|an|any)\b|" # "can you pick up a bottle?" r"\b(can|could) you (pick( up)?|lift|hold|grab|take) (a|an|any)\b|" # "can you pick up a bottle?"
r"^\s*(what|when|which|at what|do you|does|is it|are you)\b|몇|언제|얼마|" # "at what level do you go back?" r"^\s*(what|when|which|at what|do you|does|is it|are you)\b|몇|언제|얼마|" # "at what level do you go back?"
rf"({_OBJ})(은|는)\s.*수 ?있|(루미가|로봇이)\s.*수 ?있|는 ?거 ?(돼|되나|가능)|" # "물컵은 가져다줄 수 있어요?" rf"({_OBJ})(은|는)\s.*수 ?있|(루미가|로봇이)\s.*수 ?있|는 ?거 ?(돼|되나|가능)|" # "물컵은 가져다줄 수 있어요?"
r"어떻게|왜|혼자|스스로|\bby yourself\b|\bsomeone\b", CALLING.sub("", t)) # "Lumi, is it hard to ...?" r"어떻게|왜|혼자|스스로|\bby yourself\b|\bsomeone\b|줄 ?알아|할 ?줄|\bcome here often\b|"
r"^\s*(?:after|once|if|as soon as|before|unless|until)\b(?! (?:that|this|you (?:can|could|don'?t mind|would|please))\b)|"
r"\b(?:later|tomorrow|tonight|next time|in an hour)\b|(?:하|가|끝나|되|부르|말하)면\s(?!안 ?돼)|(?:^|\s)(?:나중에|이따가?|내일)\s",
CALLING.sub("", t)) # "Lumi, is it hard to ...?", "after the talk ends, go to p1", "내가 가라고 하면"
visitor = re.search(r"^\W*(?:can|may|could|should|shall) (?:i|we)\b", CALLING.sub("", t)) # "can I come closer?"
for action, pat in INTENTS: for action, pat in INTENTS:
m = re.search(pat, t, re.I) m = re.search(pat, t, re.I)
if not m: if not m:
continue continue
if action == "stop" and (STOP_TALK.search(t) or "?" in t or asks): if action == "stop" and (STOP_TALK.search(t) or "?" in t and not STOP_ASK.match(CALLING.sub("", t)) or asks):
return None # "where's your emergency stop?", "how do I stop you?" return None # "where's your emergency stop?", "how do I stop you?"
if action == "look_away": if action == "look_away":
return None if asks or "?" in t else ("look", "away") # "don't look at me", "쳐다보지 마" return None if asks or "?" in t else ("look", "away") # "don't look at me", "쳐다보지 마"
@@ -551,6 +570,10 @@ def intent(text, markers=()):
if asks and action in ("go_home", "go_point", "move", "make_way", "turn", "pick", "put", "move_object", "fetch", "come", if asks and action in ("go_home", "go_point", "move", "make_way", "turn", "pick", "put", "move_object", "fetch", "come",
"arm", "grip_open", "grip_close", "wave", "look", "lift", "follow", "come_back"): "arm", "grip_open", "grip_close", "wave", "look", "lift", "follow", "come_back"):
return None # "how do you pick up a cup?": a question, not an order return None # "how do you pick up a cup?": a question, not an order
if visitor and action in ("go_home", "go_point", "move", "turn", "come", "wave", "look", "lift", "follow", "come_back"):
return None # "can I come closer?": the visitor asks for themselves
if action == "quiet" and re.search(r"\b(?:don'?t|do not|never) stop\b|그만하지 ?마", t):
return None # "don't stop talking"
if action == "follow" and re.search(r"\bdid you\b|\bso far\b", t): if action == "follow" and re.search(r"\bdid you\b|\bso far\b", t):
return None # "did you follow me?": do you understand return None # "did you follow me?": do you understand
if action == "go_home": if action == "go_home":
@@ -558,7 +581,8 @@ def intent(text, markers=()):
return None # "나 이제 집에 가": the visitor goes home return None # "나 이제 집에 가": the visitor goes home
return ("go_to", "home") if "home" in markers else None return ("go_to", "home") if "home" in markers else None
if action == "go_point": if action == "go_point":
word = m.group(1) or m.group(3) or f"p{m.group(2)}" g = m.groups() + (None,) * 5
word = g[0] or g[2] or g[3] or g[4] or f"p{g[1]}"
name = next((mk for mk in markers if mk.lower() == word), None) name = next((mk for mk in markers if mk.lower() == word), None)
if name and (len(name) > 1 or named_place(text, name, markers)): # "a": not "go to a meeting room" if name and (len(name) > 1 or named_place(text, name, markers)): # "a": not "go to a meeting room"
return ("go_to", name) return ("go_to", name)
@@ -625,6 +649,108 @@ def intent(text, markers=()):
return None return None
# ---------- a correction inside one sentence ("go to start, no, end", "컵 집어, 아니 병") ----------
_FIX_WORD = (r"no+|nope|sorry|i mean|i meant|actually|or rather|rather|make that|scratch that|correction|my bad|oops|"
r"아니(?:야|다|요|에요|지)?|아니 아니|정정|그게 아니라|그거 말고|미안(?:해요?)?|죄송해요|죄송합니다")
_FIX_PAD = r"oh|uh|um|ah|er|wait|hold on|hang on|아|어|음|잠깐만?"
FIX = re.compile(rf"(?:^|(?<=[\s,.;!?]))(?:(?:{_FIX_PAD}|{_FIX_WORD})(?![\w'가-힣])\s*[,.;!?]*\s*)*"
rf"(?:{_FIX_WORD})(?![\w'가-힣])(?!\s+(?:thanks|thank|problem|one|more|way|matter|need|longer|rush|hurry|"
rf"worries|pressure)\b)\s*[,.;!?]*\s*(?:(?:{_FIX_PAD}|{_FIX_WORD})(?![\w'가-힣])\s*[,.;!?]*\s*)*")
_STRONG_NO = re.compile(r"\b(?:no+|nope)\b|아니")
FIX_CANCEL = re.compile(r"^\W*(?:never ?mind|forget (?:it|that|about it)|cancel(?: that| it)?|nothing|don'?t(?: do it| bother)?|"
r"no need|됐어요?|됐다|됐습니다|괜찮아요?|취소(?:해 ?줘|해요?)?|하지 ?마(?:세요)?|아무것도 하지 마(?:세요)?|관둬요?|"
r"말아 ?줘|가지 마(?:세요)?)\W*$")
_FIX_DIR = r"\b(?:left|right|forward|ahead|back(?:wards?)?|up|down)\b|왼쪽|오른쪽|앞|뒤|위|아래"
def _fix_kinds(t, markers):
"""The values in t a correction may replace: {kind: [match, ...]}: place, distance, angle, direction, object, colour."""
names = sorted((re.escape(m.lower()) for m in markers if len(m) > 1), key=len, reverse=True)
pats = {"place": rf"(?<![a-z0-9_])(?:p\d+|{'|'.join(names) or 'p0'})(?![a-z0-9_])",
"angle": r"\d+(?:\.\d+)?\s*(?:degrees?|도)", "distance": r"\d+(?:\.\d+)? m\b", "direction": _FIX_DIR,
"time": r"\d+(?:\.\d+)?\s*(?:seconds?|secs?|minutes?|mins?|초|분)(?![a-z가-힣])",
"object": rf"(?<![a-z])(?:{_OBJ})s?(?![a-z])", "colour": rf"(?<![a-z])(?:{_COL})(?![a-z])"}
out = {}
for kind, p in pats.items():
found = [m for m in re.finditer(p, t) if not (kind == "distance" and re.match(r"\s*(?:degrees?|도)", t[m.end():]))]
if kind == "direction": # "back" of "come back" is no direction
found = [m for m in found if not (m.group(0) == "back" and re.search(r"\b(?:come|bring it|take it|get) $",
t[:m.start()]))]
if found:
out[kind] = found
return out
def _reads(t, markers):
from assistant import steps
got, unread = steps.rules(t, markers)
return bool(got and not unread) or intent(t, markers) is not None
def self_correct(text, markers=()):
"""The words with a correction made inside them applied ("go to start, no, end" -> "go to end", "turn left, I mean
right", "앞으로 1미터, 아니 2미터 가" -> "앞으로 2 m 가", "go to the stage, no, pick up the cup" -> "pick up the cup").
"" when the command was taken back ("go to the stage, never mind", "스테이지로 가, 아니 됐어"); None when a
correction is there but can't be read for sure (Lumi asks again, nothing moves); the text itself otherwise."""
from assistant import steps
if re.search(r"\b(?:say|tell|announce)\b|말해|전해|[\"“”]", text, re.I):
return text # a message to say may hold any words
t = wording.norm(text, markers)
end = re.search(r"[\s,.;!?]+(?:(?:oh|uh|um|아|음)\W+)?(?:never ?mind|forget (?:it|that|about it)|cancel (?:that|it)|"
r"(?:아니\s*)?(?:됐어요?|됐다|취소))\W*$", t)
if end and t[:end.start()].strip(" ,.;!?") and not FIX.search(t[:end.start()]) and _reads(t[:end.start()], markers):
return "" # "go to the stage, never mind": taken back
for _ in range(3):
m = next((m for m in FIX.finditer(t) if m.start() > 0 and t[:m.start()].strip(" ,.;!?")), None)
if not m:
return t if _ else text
left, right, said = t[:m.start()].strip(" ,.;!?"), t[m.end():].strip(" ,.;!?"), m.group(0)
if not _reads(left, markers) and not {"distance", "angle", "direction"} & set(_fix_kinds(left, markers)):
return t if _ else text # "I like apples, no, I love them": talk, not a command
if not right or FIX_CANCEL.match(right):
if right or _STRONG_NO.search(said):
return "" # taken back
t = left # "go to the stage, sorry": politeness
continue
first, *rest = steps._SPLIT.split(right, maxsplit=1)
lk, rk = _fix_kinds(left, markers), _fix_kinds(first, markers)
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*)+|"
r"\b(?:the|one|instead|please)\b|^\s*(?:으로|로|을|를|에|만)(?![가-힣])", " ", tail).strip(" ,.")
tail = re.sub(r"\s+", " ", tail).strip()
new, clauses = None, steps._split(left)
def instead(): # the last clause of the left part replaced by the right one
keep = left[:left.rfind(clauses[-1])].strip(" ,.;!?") if len(clauses) > 1 else ""
keep = re.sub(r"\s*(?:\band then|\bthen|\band|\bafter that|그리고|다음에)$", "", keep)
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 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():]
new = fixed if _reads(fixed, markers) else None
elif rk and (set(rk) <= set(lk) or set(rk) == {"colour"} and "object" in lk):
fixed = left
for kind in sorted(rk, key=lambda k: -lk[k][-1].start() if k in lk else 0):
if kind in lk:
x = lk[kind][-1]
fixed = fixed[:x.start()] + rk[kind][-1].group(0) + fixed[x.end():]
else: # "the cup, no, the red one": the colour before the object
x = lk["object"][-1]
fixed = fixed[:x.start()] + rk[kind][-1].group(0) + " " + fixed[x.start():]
said_again = all(w in fixed.split() for w in tail.split()) # "turn left, no, turn right": "turn"
new = next((c for c in ([] if said_again else [f"{fixed} {tail}"]) + [fixed] if _reads(c, markers)), None)
if new is None and _reads(first, markers):
new = instead()
if new is None:
return None
t = f"{new}, {rest[0]}" if rest else new
return t
# ---------- fetch tasks (docs/16 §4): strict parsing, nothing is guessed ---------- # ---------- fetch tasks (docs/16 §4): strict parsing, nothing is guessed ----------
_HERE = r"here|me|여기|이쪽|나한테|저한테|나에게|저에게" _HERE = r"here|me|여기|이쪽|나한테|저한테|나에게|저에게"
_HOME = r"home|charger|charging station|dock|충전기|충전소" _HOME = r"home|charger|charging station|dock|충전기|충전소"
@@ -633,10 +759,19 @@ _PLACE_WORD = rf"(?:point|marker|포인트)\s*(\d+)|(?<![a-z])p\s?(\d+)(?!\d)|(\
_NOT_OBJ = r"(?:not|instead of) (?:the |a |an )?$" # "not the apple, the cup": the apple is not meant _NOT_OBJ = r"(?:not|instead of) (?:the |a |an )?$" # "not the apple, the cup": the apple is not meant
FILLER_IN = re.compile(r"(?<![\w'])(?:u+h+m*|u+m+|e+r+m*|hmm+)(?![\w'])[,.]*\s*|(?<![가-힣])(?:음+|어+)(?![가-힣])[,.]*\s*")
def unfill(t):
"""'go to the um the stage' -> 'go to the stage': fillers inside the words and the word said twice around them."""
t = FILLER_IN.sub("", t)
return re.sub(r"\b(the|a|to) \1\b", r"\1", t)
def _norm(text, markers=()): def _norm(text, markers=()):
"""Lower case, marker names and numbers as written (wording.py: "피쓰리" -> "p3", "point one" -> "p1", with the """Lower case, marker names and numbers as written (wording.py: "피쓰리" -> "p3", "point one" -> "p1", with the
map's markers "table front" -> "table_front").""" map's markers "table front" -> "table_front")."""
t = wording.norm(text, markers) t = unfill(wording.norm(text, markers))
for word, digit in NUMBER_WORDS.items(): # "one of them" -> "1 of them" for word, digit in NUMBER_WORDS.items(): # "one of them" -> "1 of them"
t = re.sub(rf"\b{word}\b", digit, t) t = re.sub(rf"\b{word}\b", digit, t)
return t return t
@@ -972,15 +1107,16 @@ GIVE_EN = re.compile(
rf"\blet me (?:have|take) (?:{_IT})\b|^\W*(?:okay,? )?give (?:{_IT})\W*$|^\W*gimme(?: (?:{_IT}))?{_TAIL}", re.I) rf"\blet me (?:have|take) (?:{_IT})\b|^\W*(?:okay,? )?give (?:{_IT})\W*$|^\W*gimme(?: (?:{_IT}))?{_TAIL}", re.I)
GIVE_KO = re.compile( GIVE_KO = re.compile(
rf"^\W*(?:{_THIS_KO}|(?:\S+\s+)?(?:{_OBJ}))?(?:을|를)?\s*(?:좀\s*)?(?:이제\s*)?(?:이리|여기|빨리)?\s*(?:좀\s*)?" rf"^\W*(?:{_THIS_KO}|(?:\S+\s+)?(?:{_OBJ}))?(?:을|를)?\s*(?:좀\s*)?(?:이제\s*)?(?:이리|여기|빨리)?\s*(?:좀\s*)?"
rf"(?:{_KO_WHO}(?:한테|에게|께))?\s*(?:좀\s*)?(?:{_THIS_KO}(?:을|를)?\s*)?(?:좀\s*)?" rf"(?:{_KO_WHO}(?:한테|에게|께)|(?:나|저)(?=\s))?\s*(?:좀\s*)?(?:{_THIS_KO}(?:을|를)?\s*)?(?:좀\s*)?"
r"(?:줘|주세요|줘요|주라|건네 ?줘|건네 ?주세요|건네|드려|드려요|드리세요|주실래요|줄래요?|내놔|내놓아|내놓으세요)(?:\s*봐요?)?\s*[.!?~]*$" r"(?:줘|주세요|줘요|주라|건네 ?줘|건네 ?주세요|건네|드려|드려요|드리세요|주실래요|줄래요?|주시겠어요|주십시오|주실 수 있어요|"
r"내놔|내놓아|내놓으세요)(?:\s*봐요?)?\s*[.!?~]*$"
rf"|^\W*{_KO_WHO}\s*(?:줘|줘요|주세요)\W*$", re.I) rf"|^\W*{_KO_WHO}\s*(?:줘|줘요|주세요)\W*$", re.I)
PLACE_EN = re.compile( PLACE_EN = re.compile(
rf"\b(?:put|set|place|leave|drop|lay)\s+(?:{_IT}|the \w+|that \w+|this \w+)(?:\s+down)?" rf"\b(?:put|set|place|leave|drop|lay)\s+(?:{_IT}|the \w+|that \w+|this \w+)(?:\s+down)?"
r"(?:\s+(?:here|there|over there|somewhere|anywhere))?(?:\s+(?:on|onto|next to|beside|by|near|in front of)\s+.+)?" r"(?:\s+(?:here|there|over there|somewhere|anywhere))?(?:\s+(?:on|onto|next to|beside|by|near|in front of)\s+.+)?"
rf"{_TAIL}|\b(?:put|set) (?:it |that |this )?down\b", re.I) rf"{_TAIL}|\b(?:put|set) (?:it |that |this )?down\b", re.I)
PLACE_KO = re.compile(r"(?<!내)(?<!그냥 )(?<!가만히 )(?<!내버려 )(?:놔|놓아|놓으|둬|두세요|올려 ?놔|올려 ?놓|내려 ?놔|내려 ?놓|내려 ?줘|내려 ?주세요|내려 ?둬)" PLACE_KO = re.compile(r"(?<!내)(?<!그냥 )(?<!가만히 )(?<!내버려 )(?:놔|놓아|놓으|둬|두세요|올려 ?놔|올려 ?놓|내려 ?놔|내려 ?놓|내려 ?줘|내려 ?주세요|내려 ?둬)"
r"\s*(?:줘|주세요|요|줄래요?)?\s*[.!?~]*$") r"\s*(?:줘|주세요|요|줄래요?|주시겠어요|주실래요|주십시오|줄 수 있어요?|주실 수 있어요)?\s*[.!?~]*$")
OPEN_HAND = re.compile(r"\bopen (?:your |the )?(?:hand|gripper|fingers)\b|\bopen it\b|\blet (?:it )?go\b|" OPEN_HAND = re.compile(r"\bopen (?:your |the )?(?:hand|gripper|fingers)\b|\bopen it\b|\blet (?:it )?go\b|"
r"손을? ?(?:좀 )?(?:펴|벌려|열어)|손 ?open|hand open", re.I) r"손을? ?(?:좀 )?(?:펴|벌려|열어)|손 ?open|hand open", re.I)
HAND_Q = re.compile(r"^\W*(?:what|how|why|when|where|which|who|do|does|did|is|are|was|were|have you|has)\b|" HAND_Q = re.compile(r"^\W*(?:what|how|why|when|where|which|who|do|does|did|is|are|was|were|have you|has)\b|"
@@ -1249,6 +1385,14 @@ already). Do not mention the search, the results or websites. Never give a perso
other private details, nor help to hurt someone or break the law: say briefly that you can't help.""" other private details, nor help to hurt someone or break the law: say briefly that you can't help."""
def route_system(markers=(), now=None):
"""The system prompt of respond_stream: the same from turn to turn but for what Lumi is doing now, at its end."""
return SYSTEM + "\n" + ACTIONS_STREAM.format(markers=", ".join(markers) or "(none)", yaw=f"{HEAD_YAW[1]:g}",
pitch_down=f"{-HEAD_PITCH[0]:g}", pitch_up=f"{HEAD_PITCH[1]:g}",
lift=f"{head_hw.LIFT_MAX_MM:g}") + \
(f"\nWhat you are doing now: {now}" if now else "")
class Brain: class Brain:
def __init__(self): def __init__(self):
self.history = [] # [(question, answer)] self.history = [] # [(question, answer)]
@@ -1310,9 +1454,7 @@ class Brain:
# the long fixed part comes first and stays the same from turn to turn, so the runner keeps it cached (else ~3 s # the long fixed part comes first and stays the same from turn to turn, so the runner keeps it cached (else ~3 s
# more per turn); the time goes into the last message. What Lumi does now stays here: in the last message it # more per turn); the time goes into the last message. What Lumi does now stays here: in the last message it
# read "leave it" while holding a cup as "put it down" # read "leave it" while holding a cup as "put it down"
system = SYSTEM + "\n" + ACTIONS_STREAM.format(markers=", ".join(markers) or "(none)", yaw=f"{HEAD_YAW[1]:g}", system = route_system(markers, now)
pitch_down=f"{-HEAD_PITCH[0]:g}", pitch_up=f"{HEAD_PITCH[1]:g}",
lift=f"{head_hw.LIFT_MAX_MM:g}") + (f"\nWhat you are doing now: {now}" if now else "")
messages = [{"role": "system", "content": system}] messages = [{"role": "system", "content": system}]
for q, a in self.history[-HISTORY_TURNS:]: for q, a in self.history[-HISTORY_TURNS:]:
messages += [{"role": "user", "content": q}, {"role": "assistant", "content": a}] messages += [{"role": "user", "content": q}, {"role": "assistant", "content": a}]
@@ -1618,6 +1760,15 @@ class Brain:
out["say"] = say[1] if language(text) == "Korean" else say[0] # its words said it would go: replaced out["say"] = say[1] if language(text) == "Korean" else say[0] # its words said it would go: replaced
return out return out
def warm(self, markers=(), now=None):
"""Before the next question (lumi.py calls it when it starts to listen and when it starts): the runner processes
the next prompt's start now (the last system prompt, or the first one, + the turns kept), so the question only
costs its own last message, also after a lookup, a farewell, a mission read-back or a picture used the
runner's one slot (else ~3.5 s more)."""
system = getattr(self, "last_system", None) or route_system(markers, now)
turns = [{"role": r, "content": c} for q, a in self.history[-HISTORY_TURNS:] for r, c in (("user", q), ("assistant", a))]
llm_direct.prefill([{"role": "system", "content": system}] + turns, MODEL)
def reset(self): def reset(self):
self.history = [] self.history = []
self.last_lookup = None self.last_lookup = None
+10 -3
View File
@@ -22,6 +22,7 @@ LITTLE_M = 0.5 # m; "a little", "a bit", "조금", "좀" (as befor
TINY_M = 0.05 # m; "a tiny bit", "a hair", "a few centimetres", "살짝"; estimate TINY_M = 0.05 # m; "a tiny bit", "a hair", "a few centimetres", "살짝"; estimate
SPAN_M = 0.2 # m; "한 뼘", one hand span; estimate SPAN_M = 0.2 # m; "한 뼘", one hand span; estimate
STEP_M = 0.5 # m; one step ("two steps", "한 걸음", "반 걸음"); estimate of a person's step STEP_M = 0.5 # m; one step ("two steps", "한 걸음", "반 걸음"); estimate of a person's step
TURN_MORE_DEG = 15.0 # deg; "a bit more" right after a turn: this much further the same way
DIRS = (("back", r"\bback(?:wards?)?\b|\bbackward\b|\breverse\b|^(?:let'?s )?(?:bake|big)\b(?= \d| half| a )|뒤로|뒤쪽|후진|" DIRS = (("back", r"\bback(?:wards?)?\b|\bbackward\b|\breverse\b|^(?:let'?s )?(?:bake|big)\b(?= \d| half| a )|뒤로|뒤쪽|후진|"
r"물러"), # whisper's "let's bake / big one meter" r"물러"), # whisper's "let's bake / big one meter"
@@ -130,7 +131,7 @@ def speed(t):
def read(t, last=None, talking=False): def read(t, last=None, talking=False):
"""What a sentence asks of the base, or None (not about driving): """What a sentence asks of the base, or None (not about driving):
("move", "back 0.2", exact) | ("speed", +1 | -1) | ("refuse", "back 5") | ("ask", "back" | ""). ("move", "back 0.2", exact) | ("turn", "left 90") | ("speed", +1 | -1) | ("refuse", "back 5") | ("ask", "back" | "").
`last` is the move / speed just before (last_command(history)): "more" / "again" repeat it. With none and `last` is the move / speed just before (last_command(history)): "more" / "again" repeat it. With none and
`talking` (the turn before was conversation) "more" is left to the conversation, else it is asked about.""" `talking` (the turn before was conversation) "more" is left to the conversation, else it is asked about."""
t = clean(t) t = clean(t)
@@ -142,6 +143,10 @@ def read(t, last=None, talking=False):
return None if talking else ("ask", "") # "more" of what? return None if talking else ("ask", "") # "more" of what?
if LESS.search(t): if LESS.search(t):
return ("speed", -1) if last[0] == "speed" else None return ("speed", -1) if last[0] == "speed" else None
if last[0] == "turn" and re.search(r"\b(?:more|bit|little)\b|조금|좀|살짝|약간", t) and \
not re.search(r"\bagain\b|한 ?번|똑같이|아까처럼|(?:one|1) more time|once more", t):
side = last[1].split()[0] # "a bit more" after "turn left": a little further
return ("turn", f"{side} {TURN_MORE_DEG:g}") if side in ("left", "right") else ("ask", "")
return last return last
if last and last[0] == "move" and re.search(r"\bmore\b|더", t) and direction(t) is None and not JOINED.search(t): if last and last[0] == "move" and re.search(r"\bmore\b|더", t) and direction(t) is None and not JOINED.search(t):
n, exact = amount(t) # "just a few centimetres more", "10센티 더" n, exact = amount(t) # "just a few centimetres more", "10센티 더"
@@ -160,12 +165,14 @@ def _checked(d, n, exact):
def last_command(history): def last_command(history):
"""The move or speed change of the turn just before, from brain history ("ACTION: move back 0.2"), else None.""" """The move, turn or speed change of the turn just before, from brain history ("ACTION: move back 0.2"), else None."""
if not history: if not history:
return None return None
m = re.match(r"ACTION: (move|speed) (\S+)(?: (\S+))?", history[-1][1] or "") m = re.match(r"ACTION: (move|speed|turn) (\S+)(?: (\S+))?", history[-1][1] or "")
if not m: if not m:
return None return None
if m.group(1) == "turn": # "turn left" then "again": the same turn
return ("turn", "around 180" if m.group(2) == "around" else f"{m.group(2)} {m.group(3) or 90}")
if m.group(1) == "speed": if m.group(1) == "speed":
return ("speed", int(m.group(2))) return ("speed", int(m.group(2)))
return ("move", f"{m.group(2)} {m.group(3)}", True) if m.group(3) else None return ("move", f"{m.group(2)} {m.group(3)}", True) if m.group(3) else None
+35 -3
View File
@@ -26,13 +26,14 @@ KEEP_EVERY_S = 60.0 # s; Ollama is told this ofte
_ports = {} # model -> the runner's port, found once _ports = {} # model -> the runner's port, found once
_kept = {} # model -> when Ollama was last told to keep it _kept = {} # model -> when Ollama was last told to keep it
_filled = {} # model -> (prompt, the runner's task id) of the last prefill
def render(messages): def render(messages, reply=True):
"""Ollama's gemma4 prompt (the runner adds <bos>).""" """Ollama's gemma4 prompt (the runner adds <bos>); reply=False: the turns only, the start of a longer prompt."""
turns = "".join(f"<|turn>{'model' if m['role'] == 'assistant' else m['role']}\n{m['content']}<turn|>\n" turns = "".join(f"<|turn>{'model' if m['role'] == 'assistant' else m['role']}\n{m['content']}<turn|>\n"
for m in messages) for m in messages)
return f"{turns}<|turn>model\n{NO_THINKING}" return f"{turns}<|turn>model\n{NO_THINKING}" if reply else turns
def _find_port(model): def _find_port(model):
@@ -88,6 +89,37 @@ def stream(messages, model, temperature=0.3, num_predict=200):
return None return None
def prefill(messages, model):
"""In the background, have the runner process these messages (the start of the next prompt) now, so the next
request only processes its own last message. The runner has one slot: any other prompt in between (a lookup, a
farewell, a mission read-back, a picture) leaves only ~1000 tokens of ours cached and the next answer ~3.5 s
slower. Nothing is sent when the runner has done nothing since the same prefill (its /slots task id)."""
if not model.startswith("gemma4"):
return
prompt = render(messages, reply=False)
def run():
try:
if model not in _ports:
_ports[model] = _find_port(model)
base = f"http://127.0.0.1:{_ports[model]}"
if _filled.get(model, (None,))[0] == prompt and _filled[model][1] == _task(base):
return
body = json.dumps({"prompt": prompt, "n_predict": 0, "cache_prompt": True}).encode()
urllib.request.urlopen(urllib.request.Request(f"{base}/completion", body,
{"Content-Type": "application/json"}), timeout=60).read()
_filled[model] = (prompt, _task(base))
except (OSError, ValueError, KeyError, TypeError, AttributeError):
_ports.pop(model, None)
threading.Thread(target=run, daemon=True).start()
def _task(base):
"""The id of the last task the runner's slot ran."""
with urllib.request.urlopen(f"{base}/slots", timeout=2) as r:
return json.loads(r.read())[0]["id_task"]
def _pieces(r): def _pieces(r):
with r: with r:
for line in r: for line in r:
+43 -4
View File
@@ -117,7 +117,7 @@ WAKE = re.compile(r"\b(hi|hey|hello|okay|ok|hai|high)?[\s,.!]*(lumi|loomi|lumie|
r"|루미|누미", re.I) r"|루미|누미", re.I)
WAKE_REPLY = {"en": "Yes? How can I help?", "ko": "네? 무엇을 도와드릴까요?"} WAKE_REPLY = {"en": "Yes? How can I help?", "ko": "네? 무엇을 도와드릴까요?"}
NAME_ONLY = re.compile(r"^\s*(hi |hey |hello )?(lumi|loomi|rumi|루미)[\s,.!?]*$", re.I) NAME_ONLY = re.compile(r"^\s*(hi |hey |hello )?(lumi|loomi|rumi|루미)[\s,.!?]*$", re.I)
FETCH_STOP = re.compile(r"\b(stop|halt|freeze|don'?t move)\b|멈춰|그만|정지|스톱|거기 ?서|움직이지 ?마", re.I) FETCH_STOP = re.compile(r"\b(stop|halt|freeze|don'?t move)\b|멈춰|그만|정지|스톱|거기 ?서(?=[\s!.~,]*$)|움직이지 ?마", re.I) # not "거기서 기다려"
FETCH_GIVE = re.compile(r"\bgive (it|that|this|the \w+)( to me)?\b|\bhand (it )?(over|to me)\b|줘|주세요|건네", re.I) FETCH_GIVE = re.compile(r"\bgive (it|that|this|the \w+)( to me)?\b|\bhand (it )?(over|to me)\b|줘|주세요|건네", re.I)
FETCH_PLACE = re.compile(r"\b(put|place|set) (it|that|this|the \w+) (down|on the table)\b|테이블에 ?(놔|놓|둬)|내려 ?(놔|놓)", re.I) FETCH_PLACE = re.compile(r"\b(put|place|set) (it|that|this|the \w+) (down|on the table)\b|테이블에 ?(놔|놓|둬)|내려 ?(놔|놓)", re.I)
FETCH_BRING_IT = re.compile(r"\bbring (it|that|this)\b|가져와|가져다 ?줘|갖다 ?줘", re.I) # no object named FETCH_BRING_IT = re.compile(r"\bbring (it|that|this)\b|가져와|가져다 ?줘|갖다 ?줘", re.I) # no object named
@@ -147,6 +147,8 @@ MOVING_ACTIONS = {"go_to", "come", "come_back", "follow", "move", "turn", "arm",
"lift"} "lift"}
BASE_ACTIONS = {"go_to", "come", "come_back", "follow", "move", "turn"} # need the base: Patrol on BASE_ACTIONS = {"go_to", "come", "come_back", "follow", "move", "turn"} # need the base: Patrol on
DRIVE_STEPS = {"go", "move", "turn"} # mission steps that drive DRIVE_STEPS = {"go", "move", "turn"} # mission steps that drive
FIX_SAY = (("Okay.", "네."), # a command taken back in the same sentence
("Sorry, which one did you mean? Please say it again.", "죄송해요, 어느 쪽 말씀이세요? 다시 한 번 말씀해 주세요."))
BASE_OFF_SAY = ("I can't drive or turn my waist right now. Switch on Patrol for that.", # Greeter only: a base / BASE_OFF_SAY = ("I can't drive or turn my waist right now. Switch on Patrol for that.", # Greeter only: a base /
"지금은 이동하거나 허리를 돌릴 수 없어요. 패트롤을 켜 주세요.") # waist motion asked for "지금은 이동하거나 허리를 돌릴 수 없어요. 패트롤을 켜 주세요.") # waist motion asked for
ARM_OFF_SAY = ("Please enable my arm first.", "먼저 제 팔을 켜 주세요.") # an arm action with the arm switched off ARM_OFF_SAY = ("Please enable my arm first.", "먼저 제 팔을 켜 주세요.") # an arm action with the arm switched off
@@ -912,6 +914,17 @@ class Lumi:
return True return True
else: else:
say = driving.say_move(d, float(n), got[2], lang) say = driving.say_move(d, float(n), got[2], lang)
elif got[0] == "turn": # "again" / "a bit more" after a turn
hist.append((text, f"ACTION: turn {got[1]}"))
if self.base_off("turn"):
return True
log(f" action turn {got[1]} (again)")
if not self.modes.drive:
say = "Sorry, driving is switched off." if lang == "en" else "죄송해요, 지금은 이동할 수 없어요."
elif not self.move_by("turn", got[1]):
return True
else:
say = "Okay." if lang == "en" else "네."
elif got[0] == "refuse": elif got[0] == "refuse":
d, n = got[1].split() d, n = got[1].split()
say = driving.say_refused(d, float(n), lang) say = driving.say_refused(d, float(n), lang)
@@ -1328,6 +1341,9 @@ class Lumi:
if unread: if unread:
log(f" mission: unread {unread} ({by})") log(f" mission: unread {unread} ({by})")
problem = brain_mod.place_problem(" ".join(unread), self.markers) # "go to booth" with two booths problem = brain_mod.place_problem(" ".join(unread), self.markers) # "go to booth" with two booths
if not problem and all(brain_mod.intent(u, self.markers) for u in unread):
problem = (f"Sorry, I can't do that as part of a task: {', '.join(unread)}. Please ask me one thing at a time.",
"죄송해요, 그건 작업 중에 함께 할 수 없어요. 하나씩 말씀해 주세요.")
self.fetch_say(*(problem or (f"Sorry, I didn't understand: {', '.join(unread)}. Please say it again.", self.fetch_say(*(problem or (f"Sorry, I didn't understand: {', '.join(unread)}. Please say it again.",
"죄송해요, 일부를 이해하지 못했어요. 다시 말씀해 주세요."))) "죄송해요, 일부를 이해하지 못했어요. 다시 말씀해 주세요.")))
self.keep_listening() self.keep_listening()
@@ -1760,12 +1776,17 @@ class Lumi:
self.turn_head(HEAD_SIGN * track.angle) # speech only: a greeting never moves the arm self.turn_head(HEAD_SIGN * track.angle) # speech only: a greeting never moves the arm
mouth.say(GREETING) # cached at start: plays at once mouth.say(GREETING) # cached at start: plays at once
def warm_llm(self):
"""brain.warm in the background (markers and the task state are read there, listening starts at once)."""
threading.Thread(target=lambda: safe(lambda: self.brain.warm(self.markers, self.now_doing()[0])), daemon=True).start()
def talk_turn(self): def talk_turn(self):
"""Listen once; answer if something was said. Returns True if the visitor spoke.""" """Listen once; answer if something was said. Returns True if the visitor spoke."""
if self.pending_text: # asked while Lumi was talking if self.pending_text: # asked while Lumi was talking
text, self.pending_text = self.pending_text, None text, self.pending_text = self.pending_text, None
self.answer(text) self.answer(text)
return True return True
self.warm_llm() # the LLM's prompt start cached while they speak
text, u = ears.listen(wait_s=4.0, on_start=lambda: log(" hearing speech"), abort=self.interrupted, full=True) text, u = ears.listen(wait_s=4.0, on_start=lambda: log(" hearing speech"), abort=self.interrupted, full=True)
if text and self.own_echo(text) and (u is None or u.source == "clip" or len(text.split()) <= 2): if text and self.own_echo(text) and (u is None or u.source == "clip" or len(text.split()) <= 2):
# Lumi heard itself: the clip mic, or the room's echo of the last word on the head array (muted while Lumi # Lumi heard itself: the clip mic, or the room's echo of the last word on the head array (muted while Lumi
@@ -2039,6 +2060,14 @@ class Lumi:
mouth.say("Sorry, I only understand English and Korean." if self.lang == "en" else "죄송해요, 영어와 한국어만 이해해요.") mouth.say("Sorry, I only understand English and Korean." if self.lang == "en" else "죄송해요, 영어와 한국어만 이해해요.")
self.keep_listening() self.keep_listening()
return return
fixed = brain_mod.self_correct(text, self.markers) # "go to start, no, end", "컵 집어, 아니 병"
if fixed != text:
log(f" corrected in the sentence: {fixed!r}")
if not fixed: # None: not read for sure, asked; "": taken back ("never mind")
mouth.say(FIX_SAY[fixed is None][self.lang != "en"])
self.keep_listening()
return
text = fixed
if self.voice_setting(text, last): # "speak louder", "천천히 말해", then "조금 더": before drive "again" if self.voice_setting(text, last): # "speak louder", "천천히 말해", then "조금 더": before drive "again"
return return
if self.fixed_answer(text, last): # "what can you do?" then "yes", the songs, after a song "again" if self.fixed_answer(text, last): # "what can you do?" then "yes", the songs, after a song "again"
@@ -2504,14 +2533,16 @@ class Lumi:
"talking with one person in view")) "talking with one person in view"))
if self.vision: if self.vision:
self.vision.start() self.vision.start()
self.warm_llm()
log("ready") log("ready")
self.run_camera() if self.vision else self.run_desk() self.run_camera() if self.vision else self.run_desk()
def stop_order(text, markers): def stop_order(text, markers):
""""stop", "freeze", "멈춰": stop everything at once. Not "stop talking" and not a question about the stop button.""" """"stop", "freeze", "멈춰": stop everything at once. Not "stop talking" and not a question about the stop button."""
return bool(FETCH_STOP.search(text)) and (brain_mod.intent(text, markers) or ("",))[0] not in ("quiet", "look") and \ asked = bool(brain_mod.STOP_ASK.match(brain_mod.CALLING.sub("", text))) # "can you stop?", "멈출 수 있어?": stop
not brain_mod.STOP_TALK.search(text) and "?" not in text 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)
def own_command(text, last=""): def own_command(text, last=""):
@@ -2546,6 +2577,11 @@ def talk_fate(text):
return "talk" return "talk"
NOT_A_STEP = re.compile(r"^\W*(?:(?:please|and|then|also)\s+)*(?:dance|jump|fly|swim|climb|sit(?: down)?|sleep|cook|draw|"
r"sing|clap|spin|bow|kneel|do a (?:dance|flip|trick)|tell|ask|say|show|call|find|look for|search|"
r"bring|take|give|hand|put|carry|deliver)\b|.*(?:춤|점프|날아|수영|박수)", re.I) # a part not read: asked
def read_mission(text, markers): def read_mission(text, markers):
"""(steps, unread, by) when the words are a command of several steps (unread: parts not understood), else None. """(steps, unread, by) when the words are a command of several steps (unread: parts not understood), else None.
A single move / turn / arm / go, or words that are only partly a plain command, stay with the other paths.""" A single move / turn / arm / go, or words that are only partly a plain command, stay with the other paths."""
@@ -2558,8 +2594,11 @@ def read_mission(text, markers):
return None # "say hello in Korean", "say again?": talk, not a task return None # "say hello in Korean", "say again?": talk, not a task
if unread and got and ({s["do"] for s in got} & steps.MISSION_ONLY or steps.is_mission(got)): if unread and got and ({s["do"] for s in got} & steps.MISSION_ONLY or steps.is_mission(got)):
got, unread, by = steps.read(text, markers) # clearly several steps: the LLM may read it got, unread, by = steps.read(text, markers) # clearly several steps: the LLM may read it
elif unread and got and any((brain_mod.intent(u, markers) or ("",))[0] not in ("", "weather", "search", "fetch")
or NOT_A_STEP.match(u) for u in unread):
return got, unread, by # "go to the stage and wave": no task step, asked, never half done
elif unread: elif unread:
return None # "go to p1 and wait": the old paths (rules, the LLM) answer it return None # "come here, I need help": the old paths (rules, the LLM) answer it
if not got: if not got:
return None return None
plain = not steps.is_mission(got) and (len(got) == 1 or (brain_mod.intent(text, markers) or ("",))[0] == "fetch") plain = not steps.is_mission(got) and (len(got) == 1 or (brain_mod.intent(text, markers) or ("",))[0] == "fetch")
+128 -35
View File
@@ -37,18 +37,37 @@ _DIR = r"(forward|ahead|straight|back(?:wards?)?|left|right)"
_DIR_KO = r"(앞으로|뒤로|왼쪽으로|오른쪽으로)" _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|" _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야|루미야|루미|음|응|어|야 로봇|로봇아|로봇야|" r"finally|after that|there|for me|again|carefully|slowly|could you|can you|would you|will you|lumi야|루미야|루미|음|응|어|야 로봇|로봇아|로봇야|"
r"감사합니다|고마워요|고마워|고맙습니다|좀)") 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)")
_PEOPLE = r"(?:them|him|her|someone|somebody|the person(?: there)?|people|the people|everyone|everybody|the guests?)" _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 # where one step ends and the next starts
_SPLIT = re.compile(r"\s*(?:,|;|\.(?=\s|$)|\band then\b|\bthen\b|\band\b|\bafter that\b|그리고|그 다음에?|다음에)\s*") _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"(?<=[가-힣](?:고|서))(?<!라고)(?<!다고)(?<!자고)(?<!냐고)(?<!에서)(?<!말고)\s+(?!있)|(?<=다가)\s+") # "들고 ", "가서 ": a verb _SPLIT_KO = re.compile(r"(?<=[가-힣](?:고|서))(?<!라고)(?<!다고)(?<!자고)(?<!냐고)(?<!에서)(?<!말고)\s+(?!있)|(?<=다가)\s+") # "들고 ", "가서 ": a verb
# joining two steps, not a quote # joining two steps, not a quote
def _norm(text, markers=()): def _norm(text, markers=()):
"""Lower case, marker names and numbers as written (assistant/wording.py: "피쓰리로" -> "p3로", "half a meter" -> """Lower case, marker names and numbers as written (assistant/wording.py: "피쓰리로" -> "p3로", "half a meter" ->
"0.5 m", "오십 센치" -> "0.5 m", "table front" -> "table_front" on a map with it), titles without their dot.""" "0.5 m", "오십 센치" -> "0.5 m", "table front" -> "table_front" on a map with it), titles without their dot."""
t = re.sub(r"\b(mr|mrs|ms|dr|prof)\. ", r"\1 ", wording.durations(wording.norm(text, markers)) + " ") t = re.sub(r"\b(mr|mrs|ms|dr|prof)\. ", r"\1 ", wording.durations(brain.unfill(wording.norm(text, markers))) + " ")
return re.sub(r"\b(?:take|pick up|pick|grab)\s?(?:해서|하고)", "집어서", t).strip() # "컵 take해서": mixed t = re.sub(r"\b(?:take|pick up|pick|grab)\s?(?:해서|하고)", "집어서", t) # "컵 take해서": mixed
t = re.sub(r"(?<=[가-힣])고\s*나서(?=[\s,]|$)", "고", t) # "가고 나서" = "가고"
for honour, plain in _HON_KO: # "가셔서" = "가서", "받으시고" = "받고"
t = re.sub(rf"(?<![가-힣]){honour}(?=[\s,.!?]|$)", plain, t)
return re.sub(r"(?<![가-힣])(간|온|집은|잡은|든|받은|준|놓은|돈|기다린|들른|가신|오신|기다리신|받으신|집으신|잡으신|드신|주신|놓으신)"
r"\s*(?:다음에?|후에?|뒤에?)(?=[\s,]|$)",
lambda m: _AFTER_KO[m.group(1)], t).strip() # "p3에 간 다음에" = "p3에 가고"
_AFTER_KO = {"간": "가고", "온": "오고", "집은": "집고", "잡은": "잡고", "든": "들고", "받은": "받고", "준": "주고", "놓은": "놓고",
"돈": "돌고", "기다린": "기다리고", "들른": "들르고", "가신": "가고", "오신": "오고", "기다리신": "기다리고",
"받으신": "받고", "집으신": "집고", "잡으신": "잡고", "드신": "들고", "주신": "주고", "놓으신": "놓고"}
_HON_KO = [("가셔서", "가서"), ("가시고", "가고"), ("가셨다가", "갔다가"), ("오셔서", "와서"), ("오시고", "오고"),
("돌아오셔서", "돌아와서"), ("기다리셔서", "기다려서"), ("기다리시고", "기다리고"), ("기다리셨다가", "기다렸다가"),
("드시고", "들고"), ("드셔서", "들어서"), ("받으시고", "받고"),
("받으셔서", "받아서"), ("집으시고", "집고"), ("집으셔서", "집어서"), ("잡으시고", "잡고"), ("잡으셔서", "잡아서"),
("놓으시고", "놓고"), ("놓으셔서", "놓아서"), ("드리시고", "드리고")]
# ---------- one clause -> one step ---------- # ---------- one clause -> one step ----------
@@ -95,7 +114,8 @@ def _support(t):
def _go(c, markers): def _go(c, markers):
if brain.COME_BACK.fullmatch(re.sub(r"(?<=[와가])(?:서|고)$", "", c)): if brain.COME_BACK.fullmatch(re.sub(r"(?<=[와가])(?:서|고)$", "", c)):
return {"do": "go", "to": "here"} # "come back", "go back where you were", "원래 자리로 돌아와" return {"do": "go", "to": "here"} # "come back", "go back where you were", "원래 자리로 돌아와"
m = re.fullmatch(r"(?:(?:go|drive|head|come|move|return|get)(?: back)?(?: over)?|(?:bring|take|carry) it(?: back)?)" m = re.fullmatch(r"(?:(?:go|drive|head|come|move|return|get|walk|roll|run|proceed|navigate|travel|hurry|make your way|"
r"take yourself)(?: back)?(?: over| on| ahead)?|(?:bring|take|carry) it(?: back)?)"
r" to (?:the )?(?:(?:a )?random (?:one )?of |one of |any of )?(?:the )?(.+?)(?: point| marker)?", c) r" to (?:the )?(?:(?:a )?random (?:one )?of |one of |any of )?(?:the )?(.+?)(?: point| marker)?", c)
if m: if m:
to = _places(m.group(1), markers) to = _places(m.group(1), markers)
@@ -112,8 +132,11 @@ def _go(c, markers):
m = re.fullmatch(r"(?:bring|take|carry) it (?:back )?here", c) m = re.fullmatch(r"(?:bring|take|carry) it (?:back )?here", c)
if m: if m:
return {"do": "go", "to": "here"} return {"do": "go", "to": "here"}
m = re.fullmatch(r"(.+?)\s*(?:에|으로|로)?\s*(?:갔다 ?와|갔다 ?오고|갔다 ?와서|다녀와|다녀오고|다녀와서|갔다 ?올래|다녀올래)(?:요|줘)?", c)
if m and (to := _places(m.group(1), markers)) and len(to) == 1:
return [{"do": "go", "to": to[0]}, {"do": "go", "to": "here"}] # "p3 갔다 와": there and back
m = re.fullmatch(r"(?:(?:이거|이것|그거)\s+)?(.+?)\s*(?:중에서?|중)?\s*(?:아무 ?데나|아무 ?곳에나|하나|한 ?곳)?\s*" m = re.fullmatch(r"(?:(?:이거|이것|그거)\s+)?(.+?)\s*(?:중에서?|중)?\s*(?:아무 ?데나|아무 ?곳에나|하나|한 ?곳)?\s*"
r"(?:으로|로|에|까지)?\s*(?:가져가|가져와|가져다 ?줘|가져다|갖다 ?줘|갖다|가|와|가 ?줘|돌아가|돌아와|갔다가)" r"(?:으로|로|에|까지)?\s*(?:가져가|가져와|가져다 ?줘|가져다|갖다 ?줘|갖다|가|와|가 ?줘|돌아가|돌아와|갔다가|이동해|이동하고|이동해서|이동)"
r"(?:서|고|세요|줘|요)?|(\S+?)(?:으로|로)", c) r"(?:서|고|세요|줘|요)?|(\S+?)(?:으로|로)", c)
if m: if m:
to = _places(re.sub(r"\s*(?:중에서?|중)\s*(?:아무 ?데나|아무 ?곳에나|하나|한 ?곳)?$", "", m.group(1) or m.group(2)), to = _places(re.sub(r"\s*(?:중에서?|중)\s*(?:아무 ?데나|아무 ?곳에나|하나|한 ?곳)?$", "", m.group(1) or m.group(2)),
@@ -132,7 +155,8 @@ def _move(c):
pats = (rf"(?:(?:go|move|drive|step|walk|come|back up|head)\s+)?(?:to (?:the |your )?)?{_DIR}\s+(?:by\s+)?{_NUM} m", pats = (rf"(?:(?:go|move|drive|step|walk|come|back up|head)\s+)?(?:to (?:the |your )?)?{_DIR}\s+(?:by\s+)?{_NUM} m",
rf"(?:(?:go|move|drive|step|walk|come|back up|head)\s+)?{_NUM} m\s+(?:to (?:the |your )?)?{_DIR}", rf"(?:(?:go|move|drive|step|walk|come|back up|head)\s+)?{_NUM} m\s+(?:to (?:the |your )?)?{_DIR}",
rf"(?:go|move|drive|step|walk|head)\s+{_NUM} m()", rf"(?:go|move|drive|step|walk|head)\s+{_NUM} m()",
rf"{_DIR_KO}\s*{_NUM} m\s*(?:가|가고|가서|이동|이동해|움직여|와)(?:세요|줘)?") rf"{_DIR_KO}\s*{_NUM} m\s*(?:가|가고|가서|이동|이동해|움직여|와|갔다가|갔다)(?:세요|줘)?",
rf"(){_NUM} m\s*(?:더\s*)?(?:가|가고|가서|이동해|이동하고|이동해서|전진|전진해|전진하고)(?:세요|줘)?") # "1미터 가": forward
for p in pats: for p in pats:
m = re.fullmatch(p, c) m = re.fullmatch(p, c)
if m: if m:
@@ -195,7 +219,10 @@ def _pick_receive(c, markers):
return src and to and len(src) == 1 and [{"do": "go", "to": src[0]}, {"do": "pick", "object": obj, "colour": col}, return src and to and len(src) == 1 and [{"do": "go", "to": src[0]}, {"do": "pick", "object": obj, "colour": col},
{"do": "go", "to": to if len(to) > 1 else to[0]}] or None {"do": "go", "to": to if len(to) > 1 else to[0]}] or None
m = re.fullmatch(rf"(?:pick up|pick|take|grab|get|lift)(?: up)? (?:the |a |an |that |this )?(?:({COL}) )?({OBJ})s?" m = re.fullmatch(rf"(?:pick up|pick|take|grab|get|lift)(?: up)? (?:the |a |an |that |this )?(?:({COL}) )?({OBJ})s?"
rf"(?: up)?(?: from (?:the )?(.+?))?", c) rf"(?: up)?(?: (?:from|at|off) (?:the )?(.+?))?", c)
if m and m.group(3) and re.fullmatch(r"(?:the )?table(?: (?:there|here))?|there|here", m.group(3)):
obj, col = _thing(m.group(1), m.group(2)) # "take a cup from the table there": here
return [{"do": "pick", "object": obj, "colour": col}]
if m: if m:
obj, col = _thing(m.group(1), m.group(2)) obj, col = _thing(m.group(1), m.group(2))
if m.group(3) and re.fullmatch(r"me|my hands?|(?:the )?person|him|her|them", m.group(3)): if m.group(3) and re.fullmatch(r"me|my hands?|(?:the )?person|him|her|them", m.group(3)):
@@ -207,7 +234,8 @@ def _pick_receive(c, markers):
return None return None
out.insert(0, {"do": "go", "to": src[0]}) out.insert(0, {"do": "go", "to": src[0]})
return out return out
m = re.fullmatch(rf"(?:pick up|pick|take|grab|get) (?:the |a |an )?(?:({COL}) )?({OBJ})s? (?:to|over to) (.+)", c) m = re.fullmatch(rf"(?:pick up|pick|take|grab|get|bring|carry) (?:the |a |an |this |that )?(?:({COL}) )?({OBJ})s? "
rf"(?:over )?to (.+)", c)
if m: if m:
to = _places(m.group(3), markers) to = _places(m.group(3), markers)
obj, col = _thing(m.group(1), m.group(2)) obj, col = _thing(m.group(1), m.group(2))
@@ -219,10 +247,14 @@ def _pick_receive(c, markers):
obj, col = _thing(m.group(2), m.group(3)) obj, col = _thing(m.group(2), m.group(3))
back = [{"do": "go", "to": "here", "implied": True}] if m.group(4).startswith("가져") else [] # "bring" back = [{"do": "go", "to": "here", "implied": True}] if m.group(4).startswith("가져") else [] # "bring"
return src and len(src) == 1 and [{"do": "go", "to": src[0]}, {"do": "pick", "object": obj, "colour": col}] + back return src and len(src) == 1 and [{"do": "go", "to": src[0]}, {"do": "pick", "object": obj, "colour": col}] + back
m = re.fullmatch(rf"(?:({COL})\s*)?({OBJ})\s*(?:을|를)?\s*(?:들고|잡고|집고|들어|잡아|집어|챙겨|집어줘|잡아줘|들어줘)(?:서)?", c) m = re.fullmatch(rf"(?:({COL})\s*)?({OBJ})\s*(?:을|를)?\s*(?:들고|잡고|집고|들어|잡아|집어|챙겨|챙기고|가지고|집어줘|잡아줘|들어줘)(?:서)?", c)
if m: if m:
obj, col = _thing(m.group(1), m.group(2)) obj, col = _thing(m.group(1), m.group(2))
return [{"do": "pick", "object": obj, "colour": col}] return [{"do": "pick", "object": obj, "colour": col}]
m = re.fullmatch(rf"(?:({COL})\s*)?({OBJ})\s*(?:을|를)?\s*(?:가져오고|가져와서|가져와|가지고 ?오고|가지고 ?와서|가지고 ?와)", c)
if m: # "p2 가서 | 컵 가져오고": pick there, then back (unless a drive follows)
obj, col = _thing(m.group(1), m.group(2))
return [{"do": "pick", "object": obj, "colour": col}, {"do": "go", "to": "here", "implied": True}]
return None return None
@@ -234,12 +266,15 @@ def _say(c):
def _give(c): def _give(c):
if re.fullmatch(rf"(?:give|hand) (?:it|that|this|the (?:(?:{COL}) )?(?:{OBJ})s?)?(?: over)?" 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))?(?: there)?" 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)?"
r"|hand it over|(?:give|hand) it", c) or \ r"|hand it over|(?:give|hand) it", c) or \
re.fullmatch(rf"(?:그거|그것을?|(?:(?:{COL})\s*)?(?:{OBJ})(?:을|를)?)?\s*(?:줘|주고|주세요|건네 ?줘|건네주고|" re.fullmatch(rf"(?:그거|그것을?|(?:(?:{COL})\s*)?(?:{OBJ})(?:을|를)?)?\s*(?:줘|주고|주세요|건네 ?줘|건네주고|"
rf"건네 ?주세요|건네)", c): rf"건네 ?주세요|건네)", c):
return {"do": "give"} return {"do": "give"}
if re.fullmatch(r"(?:거기 있는\s*)?(?:나한테|저한테|나에게|저에게|그 사람한테|사람한테|그분께|분께|분한테)\s*" if re.fullmatch(r"(?:거기 (?:있는|계신)\s*)?(?:나한테|저한테|나에게|저에게|그 사람한테|사람한테|그분께|분께|분한테)\s*"
rf"(?:(?:이거|그거|이것|그것|이걸|그걸|(?:(?:이|그)\s*)?(?:{OBJ})(?:을|를)?)\s*)?"
r"(?:줘|주고|주세요|건네|건네줘|건네주고|건네주세요|건네 ?줘|건네 ?주세요|드려|드리고|갖다 ?줘|갖다 ?주세요)", c) or \ r"(?:줘|주고|주세요|건네|건네줘|건네주고|건네주세요|건네 ?줘|건네 ?주세요|드려|드리고|갖다 ?줘|갖다 ?주세요)", c) or \
re.fullmatch(r"(?:이|그|저|두|세|네) ?분(?:께|한테|에게)\s*(?:줘|주고|드려|드리고|건네|건네 ?줘|건네 ?드려)", c): re.fullmatch(r"(?:이|그|저|두|세|네) ?분(?:께|한테|에게)\s*(?:줘|주고|드려|드리고|건네|건네 ?줘|건네 ?드려)", c):
return {"do": "give"} return {"do": "give"}
@@ -290,7 +325,8 @@ def _arm(c):
_DUR = r"(?:(\d+(?:\.\d+)?) s|(a (?:moment|second|sec|bit|little(?: bit| while)?|short (?:time|while))|"\ _DUR = r"(?:(\d+(?:\.\d+)?) s|(a (?:moment|second|sec|bit|little(?: bit| while)?|short (?:time|while))|"\
r"one (?:moment|second|sec)|briefly|just a (?:moment|second|sec)))" # wording.durations wrote "<n> s" r"one (?:moment|second|sec)|briefly|just a (?:moment|second|sec)))" # wording.durations wrote "<n> s"
_DUR_KO = r"(?:(\d+(?:\.\d+)?) s|(잠깐만|잠시만|조금만|잠깐|잠시|조금))" _DUR_KO = r"(?:(\d+(?:\.\d+)?) s|(잠깐만|잠시만|조금만|잠깐|잠시|조금))"
_STAY_EN = r"(?:wait|stay|remain|pause|hang on|hold on|stand by|stay put|sit tight|wait around|stand there|stay there)" _STAY_EN = (r"(?:wait|stay|remain|pause|hang on|hold on|stand by|stay put|sit tight|wait around|stand there|stay there|"
r"hang around|stick around|hang out|chill)")
_THERE = r"(?: (?:right )?(?:there|here)| for me)*" _THERE = r"(?: (?:right )?(?:there|here)| for me)*"
_GIVER = (r"(?:someone|somebody|anyone|anybody|a person|the person(?: there)?|they|people|a guest|the guests?|" _GIVER = (r"(?:someone|somebody|anyone|anybody|a person|the person(?: there)?|they|people|a guest|the guests?|"
r"someone there|he|she|them|him|her|a visitor|[a-z][a-z'-]+)") r"someone there|he|she|them|him|her|a visitor|[a-z][a-z'-]+)")
@@ -382,8 +418,10 @@ def _wait(c, markers, after):
m = re.fullmatch(rf"(.+?)(?:에서|에)\s*(?:가\s*)?{_KO_WAIT}(?:\s*줘)?", c) m = re.fullmatch(rf"(.+?)(?:에서|에)\s*(?:가\s*)?{_KO_WAIT}(?:\s*줘)?", c)
if m and _at_place(m.group(1), markers): if m and _at_place(m.group(1), markers):
return [{"do": "go", "to": _at_place(m.group(1), markers)}, {"do": "wait", "s": None}] return [{"do": "go", "to": _at_place(m.group(1), markers)}, {"do": "wait", "s": None}]
if re.fullmatch(rf"{_STAY_EN}(?: (?:right )?(?:there|here))? (?:for|until) (?:my|our) (?:call|signal|word|go)", c):
return [{"do": "wait", "s": None}] # "wait for my call": until told to go on
if re.fullmatch(rf"{_STAY_EN}(?: (?:right )?(?:there|here)| for me| until (?:i|we) (?:come back|call you|tell you" if re.fullmatch(rf"{_STAY_EN}(?: (?:right )?(?:there|here)| for me| until (?:i|we) (?:come back|call you|tell you"
r"(?: to go(?: on)?)?|say so)| until further notice| until (?:someone|somebody|they) tells? you to go(?: on)?)+" r"(?: to (?:go(?: on)?|come back|return|move on))?|say so)| until further notice| until (?:someone|somebody|they) tells? you to go(?: on)?)+"
r"|(?:거기|여기|그 ?자리)(?:서|에서|에)?\s*" + _KO_WAIT + r"(?:\s*줘)?|가만히 있어", c): r"|(?:거기|여기|그 ?자리)(?:서|에서|에)?\s*" + _KO_WAIT + r"(?:\s*줘)?|가만히 있어", c):
return [{"do": "wait", "s": None}] return [{"do": "wait", "s": None}]
if after and re.fullmatch(rf"(?:wait|stay|remain|stand by|stay put|wait around)|{_KO_BARE}(?:\s*줘)?", c): if after and re.fullmatch(rf"(?:wait|stay|remain|stand by|stay put|wait around)|{_KO_BARE}(?:\s*줘)?", c):
@@ -398,7 +436,8 @@ def _wait(c, markers, after):
_POLITE = re.compile(r"(?<=[가-힣])\s*(?:주십시오|주시겠어요|주시겠습니까|주실 수 있나요|주실 수 있습니까|주실 수 있어요|" _POLITE = re.compile(r"(?<=[가-힣])\s*(?:주십시오|주시겠어요|주시겠습니까|주실 수 있나요|주실 수 있습니까|주실 수 있어요|"
r"줄 수 있어요|줄 수 있어|주실래요|줄래요?|줘 ?봐요?|줘요?|주세요|죠)\??$") # every speech level r"줄 수 있어요|줄 수 있어|주실래요|줄래요?|줘 ?봐요?|줘요?|주세요|죠)\??$") # every speech level
_HONORIFIC = [(r"(가|와|놔|돌아|집어|잡어|잡아|들어|줘)봐요?$", r"\1"), # "가봐", "놔봐": try / do it _HONORIFIC = [(r"(가|와|놔|돌아|집어|잡어|잡아|들어|줘) ?봐요?$", r"\1"), # "가봐", "놔 봐": try / do it
(r"(?<=[가-힣]) ?주시고$", "고"), (r"(?<=[가-힣]) ?주셔서$", "서"), # "가 주시고": 가고
(r"가(?:십시오|세요|시죠|요)$", "가"), (r"오(?:십시오|세요|시죠)$", "와"), (r"도(?:십시오|세요)$", "돌아"), (r"가(?:십시오|세요|시죠|요)$", "가"), (r"오(?:십시오|세요|시죠)$", "와"), (r"도(?:십시오|세요)$", "돌아"),
(r"드리(?:십시오|세요)$", "드려"), (r"(?:주|드리)십시오$", "줘"), (r"물러나(?:세요|십시오|요)?$", "가"), (r"드리(?:십시오|세요)$", "드려"), (r"(?:주|드리)십시오$", "줘"), (r"물러나(?:세요|십시오|요)?$", "가"),
(r"회전(?:해|하세요|하십시오|해요)$", "돌아"), (r"말씀(?:해|하세요|하십시오|해요|해 주세요)$", "말해"), (r"회전(?:해|하세요|하십시오|해요)$", "돌아"), (r"말씀(?:해|하세요|하십시오|해요|해 주세요)$", "말해"),
@@ -476,6 +515,17 @@ def _person(c, markers):
return None return None
out.append({"do": "go", "to": to[0]}) out.append({"do": "go", "to": to[0]})
return out + [{"do": "give", "person": m.group(3), "where": bool(where)}] return out + [{"do": "give", "person": m.group(3), "where": bool(where)}]
m = re.fullmatch(rf"(?:go|drive|head) (?:over )?to {_NAME} (?:at|in|by) (.+)", c)
if m and _is_name(m.group(1), markers) and (to := _places(m.group(2), markers)) and len(to) == 1:
return [{"do": "go", "to": to[0]}, {"do": "_for", "person": m.group(1)}] # the next give is for them
m = re.fullmatch(rf"(?:bring|take|carry|fetch) (him|her|them|{_NAME}) (?:the |a |an |this |that )?(?:({COL}) )?({OBJ})s?", c)
if m and (m.group(1) in ("him", "her", "them") or _is_name(m.group(1), markers)):
obj, col = _thing(m.group(3), m.group(4)) # "bring her the cup": pick it, then to her (_NAME is group 2)
who = "_them" if m.group(1) in ("him", "her", "them") else m.group(1)
return [{"do": "pick", "object": obj, "colour": col}, {"do": "give", "person": who, "where": False}]
m = re.fullmatch(r"who(?:'s| is| are) (?:(?:waiting|standing|sitting) )?(?:at|in|by) (.+)", c)
if m and (to := _places(m.group(1), markers)) and len(to) == 1:
return [{"do": "_at", "person": None, "to": to[0]}] # "bring it to Sarah, who is at booth two"
m = re.fullmatch(rf"(?:{_NAME}(?: is| 's)|(?:he|she|they)(?:'s| is| are)) (?:(?:waiting|standing|sitting) )?" m = re.fullmatch(rf"(?:{_NAME}(?: is| 's)|(?:he|she|they)(?:'s| is| are)) (?:(?:waiting|standing|sitting) )?"
rf"(?:(?:at|in|by) (.+)|(?:right )?(here))", c) rf"(?:(?:at|in|by) (.+)|(?:right )?(here))", c)
if m and (m.group(1) is None or _is_name(m.group(1), markers) or m.group(1) in ("he", "she", "they")): if m and (m.group(1) is None or _is_name(m.group(1), markers) or m.group(1) in ("he", "she", "they")):
@@ -497,7 +547,7 @@ def _person(c, markers):
return out return out
# Korean # Korean
m = re.fullmatch(rf"(?:이거|이것(?:을)?|이 (?:{OBJ})(?:을|를)?|(?:({COL})\s*)?({OBJ})(?:을|를)?)?\s*(?:들고|집어서|잡고)?\s*" m = re.fullmatch(rf"(?:이거|이것(?:을)?|이 (?:{OBJ})(?:을|를)?|(?:({COL})\s*)?({OBJ})(?:을|를)?)?\s*(?:들고|집어서|잡고)?\s*"
rf"(.+?)에 (?:있는|계신) {_KNAME}\s*(?:씨)?(?:한테|에게|께)\s*(?:(?:({COL})\s*)?({OBJ})(?:을|를)?\s*)?" rf"(.+?)에 (?:있는|계신) {_KNAME}\s*(?:씨)?(?:한테|에게|께)\s*(?:(?:이|그|저)\s*)?(?:(?:({COL})\s*)?({OBJ})(?:을|를)?\s*)?"
rf"{_GIVE_KO}", c) rf"{_GIVE_KO}", c)
if m and m.group(6): # "p6에 있는 제임스한테 컵 갖다줘": the object after the name if m and m.group(6): # "p6에 있는 제임스한테 컵 갖다줘": the object after the name
return _person(f"{m.group(5) or ''} {m.group(6)} {m.group(3)}에 있는 {m.group(4)}한테 줘".strip(), markers) return _person(f"{m.group(5) or ''} {m.group(6)} {m.group(3)}에 있는 {m.group(4)}한테 줘".strip(), markers)
@@ -511,7 +561,7 @@ def _person(c, markers):
m = re.fullmatch(rf"(?:이거 |이것 )?여기 있는 {_KNAME}(?:한테|에게|께)\s*{_GIVE_KO}", c) m = re.fullmatch(rf"(?:이거 |이것 )?여기 있는 {_KNAME}(?:한테|에게|께)\s*{_GIVE_KO}", c)
if m and _ko_name(m.group(1)) not in _NOT_KNAME: if m and _ko_name(m.group(1)) not in _NOT_KNAME:
return [{"do": "go", "to": "here"}, {"do": "give", "person": _ko_name(m.group(1)), "where": True}] return [{"do": "go", "to": "here"}, {"do": "give", "person": _ko_name(m.group(1)), "where": True}]
m = re.fullmatch(rf"{_KNAME}(?:이|가) (.+?)에(?:서)? (?:있어|있어요|있대|기다려|기다려요|기다리고 있어)(?:,? (?:이거 )?{_GIVE_KO})?", c) m = re.fullmatch(rf"{_KNAME}(?:이|가|은|는) (.+?)에(?:서)? (?:있어|있어요|있대|기다려|기다려요|기다리고 있어)(?:,? (?:이거 )?{_GIVE_KO})?", c)
if m and _ko_name(m.group(1)) not in _NOT_KNAME: if m and _ko_name(m.group(1)) not in _NOT_KNAME:
to = _places(m.group(2), markers) to = _places(m.group(2), markers)
if not to or len(to) > 1: if not to or len(to) > 1:
@@ -519,9 +569,12 @@ def _person(c, markers):
if re.search(_GIVE_KO + "$", c): if re.search(_GIVE_KO + "$", c):
return [{"do": "go", "to": to[0]}, {"do": "give", "person": _ko_name(m.group(1)), "where": True}] return [{"do": "go", "to": to[0]}, {"do": "give", "person": _ko_name(m.group(1)), "where": True}]
return [{"do": "_at", "person": _ko_name(m.group(1)), "to": to[0]}] return [{"do": "_at", "person": _ko_name(m.group(1)), "to": to[0]}]
m = re.fullmatch(rf"{_KNAME}\s*(?:씨)?(?:한테|에게|께)\s*{_GIVE_KO}", c) m = re.fullmatch(rf"(?:(?:({COL})\s*)?({OBJ})(?:을|를)?\s+)?{_KNAME}\s*(?:씨)?(?:한테|에게|께)\s*(?:(?:이|그|저)\s*)?"
if m and _ko_name(m.group(1)) not in _NOT_KNAME: rf"(?:(?:{COL})\s*)?(?:(?:{OBJ})(?:을|를)?|이거|그거)?\s*{_GIVE_KO}", c)
return [{"do": "give", "person": _ko_name(m.group(1)), "where": False}] if m and _ko_name(m.group(3)) not in _NOT_KNAME:
pick = [{"do": "pick", "object": brain.OBJECTS[m.group(2)], "colour": brain.COLOURS.get(m.group(1))}] \
if m.group(2) else [] # "컵을 사라한테 갖다 줘": take it first
return pick + [{"do": "give", "person": _ko_name(m.group(3)), "where": False}]
m = re.fullmatch(rf"(.+?)에 있는 {_KNAME}(?:한테|에게|께)\s*(?:({COL})\s*)?({OBJ})(?:을|를)?\s*받(?:아|아서|고)", c) m = re.fullmatch(rf"(.+?)에 있는 {_KNAME}(?:한테|에게|께)\s*(?:({COL})\s*)?({OBJ})(?:을|를)?\s*받(?:아|아서|고)", c)
if m and _ko_name(m.group(2)) not in _NOT_KNAME: if m and _ko_name(m.group(2)) not in _NOT_KNAME:
to = _places(m.group(1), markers) to = _places(m.group(1), markers)
@@ -601,11 +654,12 @@ def _clause(c, markers, after=None):
def _clause_steps(c, markers, after=None): def _clause_steps(c, markers, after=None):
c = re.sub(rf"^(?:{_FILL}[\s,]+)+|(?:[\s,]+{_FILL})+$", "", c.strip(" .!?")).strip(" .!?,") c = re.sub(r"^(?:second(?:ly)?|third(?:ly)?|fourth|first(?:ly)?|step \d)[\s,]+", "", c.strip(" .!?")) # "second, go to ..."
c = re.sub(rf"^(?:{_FILL}[\s,]+)+|(?:[\s,]+{_FILL})+$", "", c).strip(" .!?,")
if re.search(r"[가-힣]", c): if re.search(r"[가-힣]", c):
c = re.sub(r"\s+", " ", c) c = re.sub(r"\s+", " ", c)
c = re.sub(r"\s좀\s", " ", c) c = re.sub(r"\s좀\s", " ", c)
c = re.sub(r"^(?:야\s+)?로봇(?:아|야)?[,\s]+", "", c) # "야 로봇", "로봇아": calling it c = re.sub(r"^(?:야\s+)?로봇(?:아|야)?[,\s]+|^야[,\s]+(?!로봇)", "", c) # "야 로봇", "로봇아", "야": calling it
c = c.replace("그리퍼를", "손을").replace("물러나", "뒤로 물러나") if "뒤로" not in c else c.replace("그리퍼를", "손을") c = c.replace("그리퍼를", "손을").replace("물러나", "뒤로 물러나") if "뒤로" not in c else c.replace("그리퍼를", "손을")
c = re.sub(r"(\d m)만", r"\1", c) # "1미터만" c = re.sub(r"(\d m)만", r"\1", c) # "1미터만"
bare = _POLITE.sub("", c).strip() bare = _POLITE.sub("", c).strip()
@@ -628,17 +682,24 @@ def _clause_steps(c, markers, after=None):
return [] return []
if re.fullmatch(r"(?:(?:it'?s |this is )?from|on behalf of) [a-z][a-z'-]+|[가-힣 ]+(?:이|가) (?:보내는|보낸) (?:거야|건데)", c): if re.fullmatch(r"(?:(?:it'?s |this is )?from|on behalf of) [a-z][a-z'-]+|[가-힣 ]+(?:이|가) (?:보내는|보낸) (?:거야|건데)", c):
return [] return []
m = re.fullmatch(rf"(?:(?:pass|hand|give|get) me|(?:can|could|may) i (?:have|get|grab|take)|lemme have|let me have|" m = re.fullmatch(rf"(?:(?:pass|hand|give|get|bring|fetch) me|(?:can|could|may) i (?:have|get|grab|take)|lemme have|let me have|"
rf"(?:would you )?mind (?:passing|handing|giving) me) (?:the |that |this |a |an |one )?" rf"(?:would you )?mind (?:passing|handing|giving) me) (?:the |that |this |a |an |one )?"
rf"(?:({COL}) )?({OBJ})s?(?: (?:on|from|off) the table| over(?: here)?| there| please)?" rf"(?:({COL}) )?({OBJ})s?(?: (?:on|from|off) the table| over(?: here)?| there| please)?"
rf"|(?:(?:나|저)(?:한테|에게)?\s*)?(?:({COL})\s*)?({OBJ})\s*(?:을|를)?\s*(?:하나만?\s*)?(?:(?:나|저)(?:한테|에게)\s*)?" rf"|(?:(?:나|저)(?:한테|에게)?\s*)?(?:({COL})\s*)?({OBJ})\s*(?:을|를)?\s*(?:하나만?\s*)?(?:(?:나|저)(?:한테|에게)\s*)?"
r"(?:줘|주세요|줘요|건네 ?줘|건네 ?주세요|건네|주실래요|줄래요?|주시겠어요)", c) r"(?:줘|주세요|줘요|건네 ?줘|건네 ?주세요|건네|주실래요|줄래요?|주시겠어요|갖다 ?줘|가져다 ?줘|갖다 ?주세요|가져다 ?주세요)", c)
if m and after is None: # "pass me the cup", "컵 좀 줘": from the table in front, then over if m and (after or not re.match(r"(?:bring|fetch) me\b", c)): # "pass me the cup", "컵 좀 줘": from the table in
obj, col = _thing(m.group(1) or m.group(3), m.group(2) or m.group(4)) obj, col = _thing(m.group(1) or m.group(3), m.group(2) or m.group(4)) # front, then over; after a drive: back
return [{"do": "pick", "object": obj, "colour": col}, {"do": "give"}] # here first; "bring me the cup" alone stays the plain fetch
back = [{"do": "go", "to": "here", "implied": True}] if after and after["do"] in ("go", "move", "turn") else []
return [{"do": "pick", "object": obj, "colour": col}] + back + [{"do": "give"}]
who = _person(c, markers) who = _person(c, markers)
if who is not None: if who is not None:
return who return who
m = re.fullmatch(r"(?:after|once|when|as soon as) you(?:'ve| have)? (?:get|got|arrive|arrived|reach|reached|are|'re|come)"
r"(?: (?:at|to|in))? (?:the )?(.+?)(?: point)?", c)
if m and (to := _places(m.group(1), markers)) and len(to) == 1:
return [{"do": "go", "to": to[0]}] # "after you get to the stage, ...": there first
c = re.sub(r"^go (?:and )?(?=(?:grab|get|pick|take|fetch)\b)", "", c) # "go grab the cup"
c = re.sub(r"^back ?up\b", "move back", c) c = re.sub(r"^back ?up\b", "move back", c)
c = re.sub(r"^(go|move|drive) write\b", r"\1 right", c) # whisper's "go write 1 meter" c = re.sub(r"^(go|move|drive) write\b", r"\1 right", c) # whisper's "go write 1 meter"
c = re.sub(r"\bstraight ahead\b", "forward", c) c = re.sub(r"\bstraight ahead\b", "forward", c)
@@ -657,7 +718,8 @@ def _clause_steps(c, markers, after=None):
r"(?:요| ?주세요)?", c): r"(?:요| ?주세요)?", c):
return [{"do": "go", "to": "here"}, {"do": "give"}] return [{"do": "go", "to": "here"}, {"do": "give"}]
if re.fullmatch(r"(?:여기로\s*)?(?:돌아와|돌아오고|돌아와서|와)(?:요|줘)?|(?:여기로|이리) 와(?:서|요|줘)?" if re.fullmatch(r"(?:여기로\s*)?(?:돌아와|돌아오고|돌아와서|와)(?:요|줘)?|(?:여기로|이리) 와(?:서|요|줘)?"
r"|이리와|come (?:back )?here|come back", c): r"|이리와|come (?:back )?here|come back|(?:come |go |get )?(?:right |straight )?back (?:here|to me)|"
r"come (?:right|straight) back(?: here)?", c):
return [{"do": "go", "to": "here"}] return [{"do": "go", "to": "here"}]
s = _wait(c, markers, after) s = _wait(c, markers, after)
if s is not None: if s is not None:
@@ -665,7 +727,7 @@ def _clause_steps(c, markers, after=None):
for f in (_go, _move, _turn, _give, _hold, _arm): for f in (_go, _move, _turn, _give, _hold, _arm):
s = f(c, markers) if f is _go else f(c) s = f(c, markers) if f is _go else f(c)
if s: if s:
return [s] return s if isinstance(s, list) else [s]
s = _pick_receive(c, markers) s = _pick_receive(c, markers)
if s: if s:
return s return s
@@ -680,7 +742,7 @@ def _clause_steps(c, markers, after=None):
# ---------- whole commands ---------- # ---------- whole commands ----------
_STEP_VERB = (r"(?:go|come|drive|head|return|give|hand|put|place|set|leave|take|pick|grab|get|bring|carry|turn|move|" _STEP_VERB = (r"(?:go|come|drive|head|return|give|hand|put|place|set|leave|take|pick|grab|get|bring|carry|turn|move|"
r"wait|hold|keep|open|close|reach|fold|receive|ask|find|look for)\b") r"wait|hold|keep|open|close|reach|fold|receive|ask|find|look for)\b")
_SAY_EN = re.compile(rf"\b(?:(?:say|announce)\b|tell {_PEOPLE}(?: that)?)\s*[:.,]?\s*(?:[\"“‘']([^\"”’]+?)[\"”’']" _SAY_EN = re.compile(rf"\b(?:(?:say|announce)\b|tell (?:{_PEOPLE}|(?!me\b|us\b|you\b|it\b)[a-z][a-z'-]+)(?: that)?)\s*[:.,]?\s*(?:[\"“‘']([^\"”’]+?)[\"”’']"
rf"|(.+?)(?=\s*(?:[,.]?\s*(?:and\s+|then\s+|and then\s+)+{_STEP_VERB}|[,.]\s*then\b|" rf"|(.+?)(?=\s*(?:[,.]?\s*(?:and\s+|then\s+|and then\s+)+{_STEP_VERB}|[,.]\s*then\b|"
r"[,.]\s*(?:wait|stay) (?:for |there|here|until|\d|a |an |one |two |three |five |ten |half )|" r"[,.]\s*(?:wait|stay) (?:for |there|here|until|\d|a |an |one |two |three |five |ten |half )|"
rf"(?<!\bmr)(?<!\bms)(?<!\bdr)(?<!\bmrs)(?<!\bprof)\.\s+[a-z]|$)))", re.I) rf"(?<!\bmr)(?<!\bms)(?<!\bdr)(?<!\bmrs)(?<!\bprof)\.\s+[a-z]|$)))", re.I)
@@ -726,6 +788,23 @@ _INTERJECTION = re.compile(r"^(?:(?:(?:oh|ah|um|uh) )?(?:wait(?: wait)*|hold on|
r"\s*[,.!]+\s*)+(?!then\b|and\b|after\b)(?=\S)") r"\s*[,.!]+\s*)+(?!then\b|and\b|after\b)(?=\S)")
_PIECE = re.compile(r"\s+(?=(?:go|come|wait|turn|pick up|grab|give|hand|put|bring|drive|move|head|return|stay)\b)")
def _pieces(c, markers, after):
"""A clause read as several steps when it splits at step verbs and every piece reads; else None."""
parts = _PIECE.split(c)
if len(parts) < 2 or re.search(r"[가-힣]", c):
return None
out = []
for p in parts:
got = _clause(p, markers, out[-1] if out else after)
if not got:
return None
out += got
return out
def rules(text, markers=()): def rules(text, markers=()):
"""(steps, unread clauses). Steps are merged where two clauses mean one ("look for the table" + "put it there").""" """(steps, unread clauses). Steps are merged where two clauses mean one ("look for the table" + "put it there")."""
cut, says = _cut_says(text) cut, says = _cut_says(text)
@@ -738,9 +817,15 @@ def rules(text, markers=()):
got = [{"do": "say", "text": says[int(m.group(1))]}] if m else _clause(c, markers, steps[-1] if steps else None) got = [{"do": "say", "text": says[int(m.group(1))]}] if m else _clause(c, markers, steps[-1] if steps else None)
if got is None and steps and steps[-1] == {"do": "go", "to": "home"} and re.fullmatch(r"charge(?: yourself)?|충전해", c): if got is None and steps and steps[-1] == {"do": "go", "to": "home"} and re.fullmatch(r"charge(?: yourself)?|충전해", c):
continue continue
if got is None and steps and steps[-1]["do"] == "go": no = re.fullmatch(r"(?:but |and )?(?:not|never) (?:to )?(?:the )?(.+?)", c.strip())
if got is None and no and (to := _places(no.group(1), markers)):
if not any(s_["do"] == "go" and s_["to"] in to for s_ in steps):
continue # "take the cup to the stage, not booth two"
elif got is None and steps and steps[-1]["do"] == "go":
to = _places(re.sub(r"^(?:(?:and )?then )?(?:to )?(?:the )?", "", c.strip()), markers) to = _places(re.sub(r"^(?:(?:and )?then )?(?:to )?(?:the )?", "", c.strip()), markers)
got = to and [{"do": "go", "to": to if len(to) > 1 else to[0]}] got = to and [{"do": "go", "to": to if len(to) > 1 else to[0]}]
if got is None and not m and "§" not in c:
got = _pieces(c, markers, steps[-1] if steps else None) # whisper wrote no commas: "go to p3 wait 10 s come back"
if got is None or (not m and "§" in c): if got is None or (not m and "§" in c):
unread.append(re.sub(r"§(\d+)§", lambda x: says[int(x.group(1))], c)) unread.append(re.sub(r"§(\d+)§", lambda x: says[int(x.group(1))], c))
continue continue
@@ -773,10 +858,17 @@ def _people(steps, unread, text):
"""Put a give to a named person together with where they are ("bring it to James, he is at p6"): a drive there """Put a give to a named person together with where they are ("bring it to James, he is at p6"): a drive there
before it. A named person nobody says where: unread (Lumi asks), unless Lumi drives somewhere first. A give before it. A named person nobody says where: unread (Lumi asks), unless Lumi drives somewhere first. A give
followed by a put-down there ("... and put it on his desk"): the put-down is what is meant.""" followed by a put-down there ("... and put it on his desk"): the put-down is what is meant."""
ats, out = [s for s in steps if s["do"] == "_at"], [] ats, out, for_ = [s for s in steps if s["do"] == "_at"], [], None
for s in steps: for s in steps:
if s["do"] == "_at": if s["do"] == "_at":
continue continue
if s["do"] == "_for":
for_ = s["person"]
continue
if s == {"do": "give"} and for_:
s, for_ = {"do": "give", "person": _orig(for_, text)}, None # "go to Sarah at the stage and give her the cup"
elif s == {"do": "give"} and any(a["person"] for a in ats):
s = {"do": "give", "person": next(a["person"] for a in ats if a["person"]), "where": False} # "사라는 ... 컵 갖다줘"
if s["do"] == "give" and "where" in s: if s["do"] == "give" and "where" in s:
where = s.pop("where") where = s.pop("where")
if not where: if not where:
@@ -1146,8 +1238,9 @@ def _en(s, last=False):
if d == "go": if d == "go":
to = s["to"] to = s["to"]
if isinstance(to, list): if isinstance(to, list):
to = [brain.place_said(x) for x in to]
return f"go to one of {', '.join(to[:-1])} or {to[-1]}" return f"go to one of {', '.join(to[:-1])} or {to[-1]}"
return "come back here" if to == "here" else "go to my dock" if to == "home" else f"go to {to}" return "come back here" if to == "here" else "go to my dock" if to == "home" else f"go to {brain.place_said(to)}"
if d == "move": if d == "move":
if s["dir"] in ("left", "right"): if s["dir"] in ("left", "right"):
return f"turn {s['dir']} and drive {s['m']:g} m" return f"turn {s['dir']} and drive {s['m']:g} m"
@@ -1187,8 +1280,8 @@ def _ko(s, last=False):
if d == "go": if d == "go":
to = s["to"] to = s["to"]
if isinstance(to, list): if isinstance(to, list):
return f"{', '.join(to)} 중 한 곳으로 가고" return f"{', '.join(brain.place_said(x) for x in to)} 중 한 곳으로 가고"
return "여기로 돌아오고" if to == "here" else "충전소로 가고" if to == "home" else f"{to} 위치로 가고" return "여기로 돌아오고" if to == "here" else "충전소로 가고" if to == "home" else f"{brain.place_said(to)} 위치로 가고"
if d == "move": if d == "move":
side = {"forward": "앞으로", "back": "뒤로", "left": "왼쪽으로", "right": "오른쪽으로"}[s["dir"]] side = {"forward": "앞으로", "back": "뒤로", "left": "왼쪽으로", "right": "오른쪽으로"}[s["dir"]]
return f"{side} {s['m']:g}미터 가고" return f"{side} {s['m']:g}미터 가고"
+15 -6
View File
@@ -1,4 +1,4 @@
"""Speaking: text -> speech (Supertonic-3, English and Korean, on the robot) -> USB speaker. """Speaking: text -> speech (Supertonic-3, English and Korean, on the robot's GPU: audio/tts_gpu.py) -> USB speaker.
python audio/mouth.py "Hello, I am Lumi." python audio/mouth.py "Hello, I am Lumi."
python audio/mouth.py "안녕하세요, 저는 루미예요." python audio/mouth.py "안녕하세요, 저는 루미예요."
@@ -27,8 +27,9 @@ VOICE = "F1" # F1-F5 female, M1-M5 male
STEPS = 4 # quality/speed: 4 fast ... 8 best STEPS = 4 # quality/speed: 4 fast ... 8 best
SPEED = 0.92 # < 1 = slower; 1.05 sounded rushed SPEED = 0.92 # < 1 = slower; 1.05 sounded rushed
SPEED_MIN, SPEED_MAX = 0.72, 1.2 # what "speak slower / faster" may set (Supertonic takes 0.7 to 2.0) SPEED_MIN, SPEED_MAX = 0.72, 1.2 # what "speak slower / faster" may set (Supertonic takes 0.7 to 2.0)
SPLIT_WORDS = 8 # a first sentence this long is said in two parts, cut after its first SPLIT_WORDS = 8 # TTS on the CPU only: a first sentence this long is said in two parts,
# comma: the first part is synthesised in ~0.7 s instead of ~1.8 s # cut after its first comma (first part ~0.7 s instead of ~1.8 s); on
# the GPU a whole sentence takes 0.07-0.2 s and is said in one piece
VOLUME = 55 # % of the USB speaker mixer (100 % disturbed people in the office) VOLUME = 55 # % of the USB speaker mixer (100 % disturbed people in the office)
CACHED = ["Hi, I'm Lumi, the assistant robot. How can I help you?", "안녕하세요, 저는 루미예요. 무엇을 도와드릴까요?", CACHED = ["Hi, I'm Lumi, the assistant robot. How can I help you?", "안녕하세요, 저는 루미예요. 무엇을 도와드릴까요?",
"Yes?", "네?", "Okay, I'm coming.", "네, 갈게요.", "I'm right here.", "Yes?", "네?", "Okay, I'm coming.", "네, 갈게요.", "I'm right here.",
@@ -41,6 +42,7 @@ CACHED = ["Hi, I'm Lumi, the assistant robot. How can I help you?", "안녕하
_tts = None _tts = None
_style = None _style = None
_gpu = False # synthesis on the GPU (audio/tts_gpu.py engines loaded)
_cache = {} _cache = {}
_volume_set = False _volume_set = False
_recent = [] # (time, sentence) Lumi said lately: to tell its own echo from a visitor _recent = [] # (time, sentence) Lumi said lately: to tell its own echo from a visitor
@@ -95,13 +97,19 @@ def _set_volume():
def _load(): def _load():
global _tts, _style global _tts, _style, _gpu
_set_volume() _set_volume()
if _tts is None: if _tts is None:
from supertonic import TTS from supertonic import TTS
from audio import tts_gpu
_tts = TTS(model="supertonic-3", model_dir=ROOT / "models/supertonic3", auto_download=False, _tts = TTS(model="supertonic-3", model_dir=ROOT / "models/supertonic3", auto_download=False,
intra_op_num_threads=8) intra_op_num_threads=8)
_style = _tts.get_voice_style(VOICE) _style = _tts.get_voice_style(VOICE)
try:
tts_gpu.use(_tts.model)
_gpu = True
except Exception as e: # no engine file, no GPU, no TensorRT: the CPU, 5-10x slower
print(f"mouth: TTS on the CPU ({e})", flush=True)
return _tts return _tts
@@ -115,9 +123,10 @@ def sentences(text):
def first_parts(sentence): def first_parts(sentence):
"""A long first sentence cut after its first comma (3 words in or later), so the voice starts sooner.""" """TTS on the CPU: a long first sentence cut after its first comma (3 words in or later), so the voice starts
sooner."""
m = re.search(r"[,;]\s", sentence) m = re.search(r"[,;]\s", sentence)
if len(sentence.split()) < SPLIT_WORDS or not m or len(sentence[:m.start()].split()) < 3: if _gpu or len(sentence.split()) < SPLIT_WORDS or not m or len(sentence[:m.start()].split()) < 3:
return [sentence] return [sentence]
return [sentence[:m.start() + 1], sentence[m.end():]] return [sentence[:m.start() + 1], sentence[m.end():]]
+157
View File
@@ -0,0 +1,157 @@
"""Supertonic's vector estimator and vocoder (nearly all of the TTS time) on the GPU through TensorRT.
.venv/bin/python audio/tts_gpu.py build # once on this Thor, after a JetPack / TensorRT change (~90 s)
.venv/bin/python audio/tts_gpu.py check # GPU against CPU: time and difference on a few sentences
On the CPU the vector estimator takes 0.1-0.27 s per step (4 steps a sentence) and the vocoder 0.06-0.17 s. mouth.py
puts Engine in place of the onnxruntime sessions when the engine files load, else the CPU stays (it says why).
The engines are bound to this Thor's TensorRT and GPU, like models/yolov8s.engine.
"""
import pathlib
import sys
import threading
import time
import numpy as np
ROOT = pathlib.Path(__file__).resolve().parents[1] # the project folder
MODELS = {"vector_estimator": "vector_est_ort", "vocoder": "vocoder_ort"} # file -> attribute in supertonic's model;
# the text encoder and durations take ~20 ms, they stay on the CPU
MAX_LEN = 640 # text / latent frames the engine takes (latent ~14.5 frames per s of speech:
# 44 s; a TTS chunk is at most 300 characters). Longer: the CPU session
def onnx(name):
return ROOT / f"models/supertonic3/onnx/{name}.onnx"
def engine_file(name):
return ROOT / f"models/supertonic3_{name}.engine"
def build(name):
import tensorrt as trt
logger = trt.Logger(trt.Logger.WARNING)
builder = trt.Builder(logger)
net = builder.create_network(0)
parser = trt.OnnxParser(net, logger)
if not parser.parse_from_file(str(onnx(name))):
raise SystemExit("\n".join(str(parser.get_error(i)) for i in range(parser.num_errors)))
cfg = builder.create_builder_config()
cfg.set_flag(trt.BuilderFlag.TF32)
prof = builder.create_optimization_profile()
for i in range(net.num_inputs): # batch 1; text_length / latent_length 1 ... MAX_LEN
t = net.get_input(i)
dims = [list(t.shape) for _ in range(3)]
for j, d in enumerate(t.shape):
if d == -1:
dims[0][j], dims[1][j], dims[2][j] = (1, 1, 1) if j == 0 else (1, 80, MAX_LEN)
prof.set_shape(t.name, *dims)
cfg.add_optimization_profile(prof)
engine = builder.build_serialized_network(net, cfg)
if engine is None:
raise SystemExit("engine not built")
engine_file(name).write_bytes(engine)
print("wrote", engine_file(name))
class Engine:
"""Drop-in for the onnxruntime session: run(None, feed) -> [output]. Inputs longer than MAX_LEN go to `cpu`."""
def __init__(self, name, cpu):
import tensorrt as trt
from cuda.bindings import runtime as cr
self.cr, self.cpu = cr, cpu
self.engine = trt.Runtime(trt.Logger(trt.Logger.ERROR)).deserialize_cuda_engine(engine_file(name).read_bytes())
if self.engine is None:
raise RuntimeError(f"cannot load {engine_file(name)}")
self.ctx = self.engine.create_execution_context()
self.names = [self.engine.get_tensor_name(i) for i in range(self.engine.num_io_tensors)]
self.out = next(n for n in self.names if self.engine.get_tensor_mode(n) == trt.TensorIOMode.OUTPUT)
self.stream = self._ok(cr.cudaStreamCreate())
self.dev = {} # name -> (device pointer, bytes), grown when needed
self.lock = threading.Lock() # one run at a time (a skill's result is spoken from another thread)
def _ok(self, r):
err, *val = r if isinstance(r, tuple) else (r,)
if err != self.cr.cudaError_t.cudaSuccess:
raise RuntimeError(f"CUDA error {err}")
return val[0] if val else None
def _buf(self, name, nbytes):
ptr, size = self.dev.get(name, (None, 0))
if size < nbytes:
if ptr is not None:
self._ok(self.cr.cudaFree(ptr))
ptr, size = self._ok(self.cr.cudaMalloc(nbytes)), nbytes
self.dev[name] = (ptr, size)
self.ctx.set_tensor_address(name, int(ptr))
return ptr
def run(self, _outputs, feed):
if any(x.shape[0] != 1 or x.shape[-1] > MAX_LEN for x in feed.values()): # the lengths are the last axis
return self.cpu.run(_outputs, feed)
with self.lock:
return self._run(feed)
def _run(self, feed):
cr = self.cr
h2d, d2h = cr.cudaMemcpyKind.cudaMemcpyHostToDevice, cr.cudaMemcpyKind.cudaMemcpyDeviceToHost
keep = [] # host arrays stay alive until the copies are done
for name, x in feed.items():
x = np.ascontiguousarray(x, np.float32)
keep.append(x)
self.ctx.set_input_shape(name, x.shape)
self._ok(cr.cudaMemcpyAsync(self._buf(name, x.nbytes), x.ctypes.data, x.nbytes, h2d, self.stream))
out = np.empty(tuple(self.ctx.get_tensor_shape(self.out)), np.float32)
ptr = self._buf(self.out, out.nbytes)
if not self.ctx.execute_async_v3(int(self.stream)):
raise RuntimeError("TensorRT run failed")
self._ok(cr.cudaMemcpyAsync(out.ctypes.data, ptr, out.nbytes, d2h, self.stream))
self._ok(cr.cudaStreamSynchronize(self.stream))
return [out]
def use(model):
"""Put the GPU engines into a loaded supertonic model (TTS().model). Raises when an engine does not load."""
for name, attr in MODELS.items():
cpu = getattr(model, attr)
if not isinstance(cpu, Engine):
setattr(model, attr, Engine(name, cpu))
def check():
"""Each sentence on the CPU and on the GPU (same noise): synthesis time and the difference in the sound."""
from audio import mouth
mouth._set_volume = lambda: None # nothing is played or changed
tts = mouth._load()
m = tts.model
use(m) # mouth.py has done it when the engines load
gpu = {a: getattr(m, a) for a in MODELS.values()}
cpu = {a: e.cpu for a, e in gpu.items()}
for s in ["Lumi.", "I was developed by Cutshion Company.", "고마워요! 그렇게 말씀해 주시니 기쁘네요.",
"I can talk with you in English and Korean, answer questions about Cutshion, and guide you around."]:
wavs = []
for sessions in (cpu, gpu):
for a, sess in sessions.items():
setattr(m, a, sess)
np.random.seed(0)
t = time.time()
wav, _ = tts.synthesize(s, voice_style=mouth._style, lang=mouth.lang_of(s), total_steps=mouth.STEPS,
speed=mouth.speed())
wavs.append((time.time() - t, wav.reshape(-1)))
(tc, a), (tg, b) = wavs
n = min(len(a), len(b))
print(f"cpu {tc:4.2f} s gpu {tg:4.2f} s max diff {np.abs(a[:n] - b[:n]).max():.4f} "
f"rms diff / rms {np.sqrt(np.mean((a[:n] - b[:n]) ** 2)) / np.sqrt(np.mean(a[:n] ** 2)):.4f} {s[:40]}")
if __name__ == "__main__":
if sys.argv[1:] == ["build"]:
for n in MODELS:
build(n)
elif sys.argv[1:] == ["check"]:
from audio import tts_gpu # the module mouth.py loads, not __main__ (another Engine class)
tts_gpu.check()
else:
sys.exit(__doc__)
+1 -1
View File
@@ -203,7 +203,7 @@ for word, val in OBJ_KO[:5]:
for t in ["take the cup, go to p3 and give it to Mina", "pick up the bottle, turn around and give it to me", for t in ["take the cup, go to p3 and give it to Mina", "pick up the bottle, turn around and give it to me",
"go to p2, wait 10 seconds and come back", "컵 집어서 p3로 가서 줘", "pick up the apple and hand it to me", "go to p2, wait 10 seconds and come back", "컵 집어서 p3로 가서 줘", "pick up the apple and hand it to me",
"take the cup and put it on the chair", "사과 집어서 나한테 줘"]: "take the cup and put it on the chair", "사과 집어서 나한테 줘"]:
add("mission", t, "mission | action:fetch") add("mission", t, "mission | action:fetch | refuse" if "bottle" in t else "mission | action:fetch") # the bottle: why not
# ---------- status ---------- # ---------- status ----------
for t in ["what are you holding?", "what's in your hand?", "where are you going?", "what are you doing?", "뭐 하고 있어?", for t in ["what are you holding?", "what's in your hand?", "where are you going?", "what are you doing?", "뭐 하고 있어?",
+275
View File
@@ -0,0 +1,275 @@
"""Second command set (2026-10-21 night): every ability in wordings the first set (tests/command_cases.py) does not
have: polite / casual / 반말 / 존댓말, indirect ("could you maybe ...", "I'd like you to ...", "~해 줄래?", "~할 수 있어?"),
negation ("don't go to the stage", "가지 마"), conditions ("when I say go ..."), corrections inside the sentence
("go to start, no, end", "컵 집어, 아니 병"), fillers, code-mixing, the conference map's marker names (start, end, init,
final, middle, table_front, booth_2, stage) and whisper's slips. Same notation as tests/command_cases.py; every case
carries the map it is said on ("markers"). The intent names start with "new:" so the report keeps both sets apart.
Forbidden motions are what "wrong" counts: any motion that is not one of the expected alternatives.
"""
import random
R = random.Random(21)
CONF = ["home", "start", "end", "init", "final", "middle", "table_front", "stage", "booth_2", "dock2"]
CASES = []
def add(intent, text, expect, state="idle", before=None):
lang = "ko" if any("가" <= ch <= "힣" for ch in text) else "en"
CASES.append({"intent": "new:" + intent, "text": text, "lang": lang, "state": state, "before": before,
"expect": expect, "markers": CONF})
def ro(word):
"""The Korean 'to' particle after a word: 스테이지로, 이닛으로, 테이블 프론트로."""
c = word[-1]
if not "가" <= c <= "힣":
return word + "로"
final = (ord(c) - 0xAC00) % 28
return word + ("으로" if final and final != 8 else "로")
def each(intent, templates, fills, expect, state="idle", before=None):
for tpl in templates:
for word, val in fills:
add(intent, tpl.format(o=word, ro=ro(word) if word else ""), expect.format(o=val), state, before)
PLACES_EN = [("the stage", "stage"), ("booth two", "booth_2"), ("table front", "table_front"), ("the start", "start"),
("the end", "end"), ("init", "init"), ("the final point", "final"), ("the middle", "middle")]
PLACES_KO = [("스테이지", "stage"), ("부스 투", "booth_2"), ("테이블 프론트", "table_front"), ("스타트", "start"),
("엔드", "end"), ("미들", "middle"), ("파이널", "final"), ("이닛", "init")]
PAIRS_EN = [("the start", "the end", "end"), ("the stage", "booth two", "booth_2"), ("the middle", "table front", "table_front"),
("booth two", "the stage", "stage"), ("init", "the final point", "final")]
PAIRS_KO = [("스타트", "엔드", "end"), ("스테이지", "부스 투", "booth_2"), ("미들", "테이블 프론트", "table_front"),
("부스 투", "스테이지", "stage"), ("이닛", "파이널", "final")]
# ---------- go to a marker ----------
each("go", ["go to {o}", "could you maybe go to {o}?", "I'd like you to go to {o}", "head over to {o}, please",
"please make your way to {o}", "can you drive to {o}", "let's go to {o}", "navigate to {o}",
"off you go to {o}", "proceed to {o}", "um, go to, uh, {o}", "Lumi, would you go to {o} for me?",
"why don't you go to {o}", "I want you to go to {o} now"], PLACES_EN, "action:go_to {o} | mission")
each("go", ["{ro} 가", "{ro} 가 줘", "{ro} 가 줄래?", "{ro} 가 주실래요?", "{ro} 이동해 주세요", "{o}까지 가 줘", "{o} 가",
"{o} 쪽으로 가 봐", "{ro} 가 주시겠어요?", "{ro} 가십시오", "{ro} 가 줄 수 있어요?", "루미야, {ro} 좀 가 줘",
"음 {ro} 가 줘요"], PLACES_KO, "action:go_to {o} | mission")
each("go", ["go to {o} 해 줘", "{o}로 go"], [("stage", "stage"), ("booth 2", "booth_2")], "action:go_to {o} | mission | talk")
# not a drive now: negation, a question about the place, a condition for later
each("go_not", ["don't go to {o}", "please don't go to {o}", "you don't need to go to {o}", "never go to {o} alone",
"how far is {o}?", "where is {o}?", "have you been to {o} today?", "how long does it take to go to {o}?",
"is {o} on your map?", "when I say go, go to {o}", "after the talk ends, go to {o}",
"I'm going to {o}", "my friend is at {o}"], PLACES_EN[:5], "talk | ask | stop | end")
each("go_not", ["{ro} 가지 마", "{ro} 가지 마세요", "{o}에는 가지 마", "{o} 어디예요?", "{o}까지 얼마나 걸려요?",
"{o}에 가 봤어?", "제가 {o}에 갈게요", "내가 가라고 하면 {ro} 가", "제 친구가 {o}에 있어요"],
PLACES_KO[:5], "talk | ask | stop | end") # "제가 스테이지에 갈게요": may be a goodbye
# corrections inside the sentence: the last place said; the first one is never driven to
for a, b, v in PAIRS_EN:
for tpl in ["go to {a}, no, {b}", "go to {a}, sorry, I mean {b}", "go to {a}, actually, {b}", "go to {a}, wait, no, {b}",
"go to {a}. No wait, go to {b}", "go to {a}, oops, {b}", "drive to {a}, I mean {b}, please"]:
add("correct", tpl.format(a=a, b=b), f"action:go_to {v} | mission")
for a, b, v in PAIRS_KO:
for tpl in ["{ra} 가, 아니 {rb}", "{ra} 가, 아니 {rb} 가 줘", "{ra} 가 줘. 아 아니, {rb}", "{ra}, 아니다 {rb} 가 줘"]:
add("correct", tpl.format(ra=ro(a), rb=ro(b)), f"action:go_to {v} | mission")
for t in ["go to the stage, never mind", "go to the stage, no, forget it", "go to booth two, actually never mind",
"come here, never mind", "turn left, no, never mind", "pick up the cup, no, forget it",
"스테이지로 가, 아니 됐어", "이리 와, 아니야 됐어", "왼쪽으로 돌아, 아니 됐어요", "컵 집어, 아니 취소"]:
add("correct", t, "talk")
for t, want in [("move forward 1 meter, no, 2 meters", "action:move forward 2"),
("move back 50 centimeters, sorry, 30 centimeters", "action:move back 0.3"),
("go back 1 meter, no, forward", "action:move forward 1"),
("turn left, no, right", "action:turn right"), ("turn left, I mean right", "action:turn right"),
("turn right 45 degrees, no, 30", "action:turn right 30"),
("look left, no, right", "action:look right"), ("look up, sorry, down", "action:look down"),
("pick up the cup, no, the bottle", "action:pick bottle | mission"),
("grab the apple, I mean the banana", "action:pick banana | mission"),
("pick up the cup, no, the red one", "action:pick red cup | mission"),
("go to the stage, no, pick up the cup", "action:pick cup | mission"),
("go to the stage, no, the kitchen", "ask | talk"), ("go to the stage, no, dance", "ask | talk"),
("앞으로 1미터, 아니 2미터 가", "action:move forward 2"), ("뒤로 1미터, 아니 50센티만 가 줘", "action:move back 0.5"),
("왼쪽으로 돌아, 아니 오른쪽", "action:turn right"), ("왼쪽 봐, 아니 오른쪽", "action:look right"),
("컵 집어, 아니 병", "action:pick bottle | mission"), ("사과 집어 줘, 아니 바나나", "action:pick banana | mission"),
("go to 스테이지, 아니 부스 투", "action:go_to booth_2 | mission")]:
add("correct", t, want)
# ---------- come, come back, follow ----------
for t in ["come here", "come over here, please", "could you come here for a sec?", "come to me", "come closer",
"get over here", "come this way", "Lumi, I need you over here, come here", "can you come over to me?",
"이리 와", "이리 와 줄래?", "이쪽으로 와 주세요", "가까이 와", "여기로 와 봐", "나한테 와", "저한테 와 주실래요?",
"루미야 이리 와 줘", "come here 해 줘"]:
add("come", t, "action:come")
for t in ["don't come here", "please don't come closer", "오지 마", "가까이 오지 마세요", "I'll come to you", "can I come closer?",
"come here often?", "제가 갈게요"]:
add("come_not", t, "talk | stop | action:move back | end")
for t in ["come back", "come back please", "return to where you were", "go back to your spot", "could you go back where you were?",
"come back to where you started", "돌아와", "다시 돌아와 줘", "원래 자리로 돌아가", "아까 있던 데로 돌아가 줘",
"제자리로 돌아와 주세요"]:
add("come_back", t, "action:come_back | mission")
for t in ["I'll come back later", "come back tomorrow", "she will come back soon", "나중에 다시 올게요", "내일 다시 와"]:
add("come_back_not", t, "talk | end")
for t in ["follow me", "follow me please", "can you follow me?", "come with me", "walk with me", "keep following me",
"come along", "Lumi, follow me to the booth", "따라와", "따라와 줄래?", "나 따라와", "저 따라오세요", "같이 가자",
"저랑 같이 가요", "follow me 해 줘"]:
add("follow", t, "action:follow")
for t in ["don't follow me", "따라오지 마", "follow me on instagram", "did you follow what I said?", "I follow you on youtube",
"do you follow me?", "제 말 따라와요?"]:
add("follow_not", t, "talk | stop")
add("follow_not", "stop following me", "stop")
add("follow_not", "그만 따라와", "stop")
# ---------- short moves, turns ----------
for t, want in [("move forward 1 meter", "action:move forward 1"), ("could you go forward half a meter?", "action:move forward 0.5"),
("back up 30 centimeters please", "action:move back 0.3"), ("I'd like you to move back 1 meter", "action:move back 1"),
("scoot back a little", "action:move back"), ("move 2 meters ahead", "action:move forward 2"),
("go left 1 meter", "action:move left 1"), ("move to the right 50 cm", "action:move right 0.5"),
("앞으로 1미터 가 줘", "action:move forward 1"), ("뒤로 50센티만 가", "action:move back 0.5"),
("왼쪽으로 1미터 이동해 줄래요?", "action:move left 1"), ("뒤로 좀 물러나 주세요", "action:move back"),
("앞으로 조금만 와", "action:move forward"), ("한 걸음 앞으로", "action:move forward 0.5"),
("move back 20 cm, no, 10 cm", "action:move back 0.1"),
("move back", "action:move back"), ("move forward 4 meters", "refuse"), ("앞으로 10미터 가", "refuse"),
("move back twenty", "ask")]:
add("move", t, want)
for t, want in [("turn left", "action:turn left 90"), ("turn to the right please", "action:turn right 90"),
("turn around", "action:turn around"), ("could you turn left 30 degrees?", "action:turn left 30"),
("turn right 45 degrees", "action:turn right 45"), ("왼쪽으로 돌아", "action:turn left 90"),
("오른쪽으로 돌아 줘", "action:turn right 90"), ("뒤로 돌아", "action:turn around"),
("왼쪽으로 45도 돌아 주세요", "action:turn left 45"), ("한 바퀴 돌아 봐", "action:turn around"),
("turn left 하고", "action:turn left | talk")]:
add("turn", t, want)
for t in ["don't turn", "돌지 마", "turn off the light", "turn up the volume", "it's your turn", "turn the page"]:
add("turn_not", t, "talk | stop")
TURNED = ("turn left", "ACTION: turn left 90")
for t, want in [("again", "action:turn left 90"), ("한 번 더", "action:turn left 90"), ("one more time", "action:turn left 90"),
("a bit more", "action:turn left 15"), ("조금 더", "action:turn left 15")]:
add("again", t, want, before=TURNED)
MOVED = ("move forward 1 meter", "ACTION: move forward 1")
for t, want in [("again", "action:move forward 1"), ("do it again", "action:move forward 1"), ("same again please", "action:move forward 1"),
("한 번 더", "action:move forward 1"), ("10센티 더", "action:move forward 0.1")]:
add("again", t, want, before=MOVED)
for t in ["again", "do that again", "한 번 더 해 줘"]:
add("again", t, "ask") # nothing before it: "more of what?"
# ---------- look, lift ----------
for t, want in [("look left", "action:look left"), ("look to your right", "action:look right"), ("look up", "action:look up"),
("look down at the table", "action:look down"), ("look at me", "action:look me"),
("could you look at me please?", "action:look me"), ("look straight ahead", "action:look center"),
("turn your head left", "action:look left"), ("look behind you", "action:look"),
("왼쪽 봐", "action:look left"), ("위를 봐", "action:look up"), ("나 봐", "action:look me"),
("고개 숙여", "action:look down"), ("정면 봐 줘", "action:look center"), ("고개 오른쪽으로 돌려 줄래?", "action:look right"),
("look away", "action:look away"), ("stop staring at me", "action:look away"),
("look up the weather", "weather | search | talk"), ("look at that!", "talk | action:look"),
("I'm looking for the toilet", "talk"), ("look what I have", "talk | seeing | action:look")]:
add("look", t, want)
for t, want in [("raise yourself", "action:lift up"), ("lift yourself up a bit", "action:lift up"),
("lower yourself", "action:lift down"), ("could you get a little lower?", "action:lift down | talk"),
("키 좀 높여 줘", "action:lift up"), ("몸 좀 낮춰", "action:lift down"), ("몸 5센티만 올려", "action:lift up"),
("lift the cup", "action:pick cup | mission"), ("lift my spirits", "talk")]:
add("lift", t, want)
# ---------- wave, bye-bye ----------
for t in ["wave", "wave at them", "wave your hand", "wave hello", "give them a wave", "can you wave?", "wave to the camera",
"say hi with your hand", "손 흔들어", "손 흔들어 줄래?", "손 인사 해 줘", "손 좀 흔들어 주세요", "애들한테 손 흔들어 줘",
"wave 해 줘", "손 wave 해 봐"]:
add("wave", t, "action:wave")
for t in ["do you know how to wave?", "손 흔들 줄 알아?", "I saw you wave yesterday", "the wave was nice", "shake hands with me",
"a new wave of visitors is coming"]:
add("wave_not", t, "talk")
for t in ["bye bye", "bye-bye!", "바이바이", "빠이빠이", "잘 가", "okay, bye!", "see you, Lumi"]:
add("bye", t, "end")
# ---------- pick, put, give, receive, the hand ----------
for t, want in [("would you mind picking up the cup?", "action:pick cup | mission"),
("I'd like you to grab the bottle", "action:pick bottle | mission"),
("could you maybe take the apple?", "action:pick apple | mission"),
("pick the banana up for me, would you?", "action:pick banana | mission"),
("go ahead and pick up the red cup", "action:pick red cup | mission"),
("컵 좀 집어 줄래?", "action:pick cup | mission"), ("사과 좀 들어 줄 수 있어요?", "action:pick apple | mission"),
("빨간 컵 잡아 주세요", "action:pick red cup | mission"), ("병 좀 집어 줘요", "action:pick bottle | mission"),
("pick up the 컵", "action:pick cup | mission"), ("cup 집어", "action:pick cup | mission"),
("don't pick up the cup", "talk"), ("컵 집지 마", "talk"), ("can you pick up a cup?", "talk"),
("how do you pick up cups?", "talk"), ("I picked up a cup today", "talk")]:
add("pick", t, want)
for t, want in [("put it down please", "place"), ("set it down", "place"), ("place it on the table", "place"),
("테이블에 내려놔 줘", "place"), ("여기 내려놓아 주세요", "place"), ("put it down, no, give it to me", "give"),
("hand it over", "give"), ("give it to me please", "give"), ("I'll take it", "give"), ("can I have it?", "give"),
("이리 줘", "give"), ("저 주세요", "give"), ("그거 저한테 건네 주실래요?", "give"),
("don't drop it", "talk"), ("떨어뜨리지 마", "talk"), ("open your hand", "refuse")]:
add("held", t, want, state="holding")
for t, want in [("here, take this", "receive"), ("can you hold this for me?", "receive"), ("이거 받아 줄래요?", "receive"),
("이거 좀 들고 있어 줘", "receive"), ("I have a cup for you, take it", "receive cup"),
("open your hand", "action:arm open"), ("open the gripper please", "action:arm open"), ("손 펴 줘", "action:arm open"),
("close your fingers", "action:arm close"), ("손 오므려", "action:arm close"), ("don't open your hand", "talk"),
("give it to me", "empty_hand | talk"), ("put it down", "empty_hand | talk")]:
add("hand", t, want)
# ---------- fetch, missions on this map ----------
for t in ["bring me the cup from the stage", "get the bottle from booth two", "could you fetch the apple from table front?",
"go to the stage and bring me the apple", "스테이지에서 컵 가져와", "부스 투에서 사과 가져다 줘",
"엔드에 있는 병 가져와 줄래?", "fetch the banana from the end for me"]:
add("fetch", t, "action:fetch | mission | refuse") # a bottle or banana: the reason why not
for t in ["take the cup to booth two and come back", "go to the stage, wait 10 seconds, then come back",
"스테이지 갔다 와", "부스 투 다녀와 줄래?", "먼저 스테이지 가서 컵 가져오고 그다음 여기로 와서 줘",
"go to start, then middle, then end", "pick up the cup, go to the end and give it to Sarah"]:
add("mission", t, "mission | action:fetch")
for t in ["go to the stage and wave", "go to the stage and follow me", "pick up the cup and lift yourself up",
"go to booth two and look left", "스테이지 가서 손 흔들어"]:
add("mission_part", t, "talk | ask") # a part that is no task step: asked, never half done
# ---------- stop, speed ----------
for t in ["stop", "stop it", "stop right now", "halt", "freeze", "stop, stop!", "wait, stop", "Lumi stop", "멈춰", "그만", "정지",
"스톱", "멈춰 주세요", "거기 서", "stop 해"]:
add("stop", t, "stop")
for t in ["how do I stop you?", "where is your stop button?", "멈추는 방법이 뭐예요?"]:
add("stop_not", t, "talk")
add("stop_not", "bus stop", "talk | stop") # a stop is never a harmful motion
add("stop_not", "don't stop talking", "talk | stop")
for t, want in [("go faster", "speed faster"), ("speed up a little", "speed faster"), ("can you go quicker?", "speed faster"),
("slow down", "speed slower"), ("not so fast please", "speed slower"), ("더 빨리 가", "speed faster"),
("천천히 가 줘", "speed slower"), ("속도 좀 줄여 주세요", "speed slower"), ("you're too fast", "speed slower"),
("speak slower", "talk"), ("천천히 말해 줘", "talk"), ("you speak too fast", "talk")]:
add("speed", t, want)
# ---------- every Korean speech level, slang and whisper's spellings (second round) ----------
for t, want, st in [
("스테이지로 가십시오", "action:go_to stage", "idle"), ("스테이지로 가시겠어요?", "action:go_to stage", "idle"),
("스테이지로 가 줄 수 있니?", "action:go_to stage", "idle"), ("스테이지로 좀 가 봐요", "action:go_to stage", "idle"),
("스테이지로 가자", "action:go_to stage", "idle"), ("스테이지로 가 볼까?", "action:go_to stage | talk", "idle"),
("스테이지로 가면 안 돼?", "action:go_to stage | talk", "idle"), ("스테이지로 가야 해", "action:go_to stage", "idle"),
("스테이지로 가 줬으면 좋겠어", "action:go_to stage", "idle"), ("스테이지 가 주라", "action:go_to stage", "idle"),
("스테이지로 가 주시면 감사하겠습니다", "action:go_to stage | talk | end", "idle"),
("이리 오세요", "action:come", "idle"), ("이리 와 주시겠어요?", "action:come", "idle"), ("이리 좀 와 볼래?", "action:come", "idle"),
("여기로 와 주실 수 있나요?", "action:come", "idle"), ("따라오세요", "action:follow", "idle"),
("따라와 주시겠어요?", "action:follow", "idle"), ("저를 따라와 주세요", "action:follow", "idle"),
("앞으로 오십 센티 가 주세요", "action:move forward 0.5", "idle"), ("뒤로 조금만 물러나 주실래요?", "action:move back", "idle"),
("왼쪽으로 돌아 주십시오", "action:turn left", "idle"), ("고개를 왼쪽으로 돌려 주세요", "action:look left", "idle"),
("위를 봐 주실래요?", "action:look up", "idle"), ("손을 흔들어 주시겠어요?", "action:wave", "idle"),
("손 좀 흔들어 줄 수 있어?", "action:wave", "idle"), ("컵을 집어 주시겠습니까?", "action:pick cup | mission", "idle"),
("컵 좀 집어 주실 수 있나요?", "action:pick cup | mission", "idle"), ("그 컵 좀 집어 줘 봐", "action:pick cup | mission", "idle"),
("멈춰 주세요", "stop", "idle"), ("그만하세요", "stop", "idle"), ("천천히 가 주세요", "speed slower", "idle"),
("좀 더 빨리 가 줄래요?", "speed faster", "idle"),
("그거 저 주세요", "give", "holding"), ("테이블에 놓아 주시겠어요?", "place", "holding"), ("저한테 주실래요?", "give", "holding"),
("gimme a wave", "action:wave", "idle"), ("yo come here", "action:come", "idle"), ("c'mon follow me", "action:follow", "idle"),
("go 2 the stage", "action:go_to stage", "idle"), ("goto the stage", "action:go_to stage", "idle"),
("go too the stage", "action:go_to stage", "idle"), ("go to the stag", "action:go_to stage", "idle"),
("go to stage pls", "action:go_to stage", "idle"), ("plz come here", "action:come", "idle"), ("come hear", "action:come", "idle"),
("move forward a metre and a half", "action:move forward 1.5", "idle"), ("turn lefft", "action:turn left | talk | ask", "idle"),
("look write", "action:look right | talk | ask", "idle"), ("lemme see you wave", "action:wave | talk | end", "idle")]:
add("levels", t, want, st)
for t, want in [("go ahead to the stage", "action:go_to stage"), ("you may go to booth two", "action:go_to booth_2"),
("feel free to go to the stage", "action:go_to stage"), ("time to go to the stage", "action:go_to stage"),
("I was wondering if you could go to the stage", "action:go_to stage"),
("would it be possible for you to go to the stage?", "action:go_to stage | talk"),
("is it okay if you go to the stage?", "action:go_to stage | talk"), ("mind going to the stage?", "action:go_to stage | talk"),
("stop and come back", "stop"), ("wait, don't go there", "talk | stop"), ("no no no, stop", "stop"),
("스테이지 가서 거기서 기다려", "mission"), ("거기 서!", "stop"), ("거기 서", "stop"),
("look at the stage", "talk | ask | action:look"), ("face the stage", "talk | ask | action:look | action:turn")]:
add("levels", t, want)
# "can you ...?" asks it done (owner, 2026-10-20); "do you know how / can you X people" asks whether it can
for t, want in [("can you raise yourself?", "action:lift up"), ("could you get a bit taller", "action:lift up"),
("can you look to the left?", "action:look left"), ("could you turn around please", "action:turn around"),
("can you move back a little?", "action:move back"), ("can you stop?", "stop"), ("멈출 수 있어?", "stop"),
("Lumi, could you stop please?", "stop"), ("can you close your hand?", "action:arm close"),
("왼쪽으로 돌아 줄 수 있어요?", "action:turn left"), ("이리 와 줄 수 있어요?", "action:come"),
("turn left, would you?", "action:turn left"), ("turn around for me, will you?", "action:turn around"),
("do you know how to follow people?", "talk"), ("can you follow people?", "talk | action:follow"),
("do you turn left?", "talk"), ("can you stop talking?", "talk | action:quiet"),
("can you pick that up?", "talk | ask"), ("how about turning left", "talk | action:turn left"),
("would you mind looking at me?", "talk | action:look me")]:
add("levels", t, want)
R.shuffle(CASES) # the report lists them by intent; the order only spreads the LLM's load
+32 -8
View File
@@ -5,8 +5,9 @@
.venv/bin/python tests/command_check.py --cached # the LLM's answers from the last --llm run where the text is .venv/bin/python tests/command_check.py --cached # the LLM's answers from the last --llm run where the text is
# the same (fast, after a rule change) # the same (fast, after a rule change)
.venv/bin/python tests/command_check.py receive # only this intent .venv/bin/python tests/command_check.py receive # only this intent
.venv/bin/python tests/command_check.py --new # only the second set (tests/command_cases2.py); --old the first
-> logs/command_check.md / .json. The order is lumi.answer()'s with nothing running and the hand empty ("idle") or -> logs/command_check.md / .json (rules only: logs/command_check_rules.*). The order is lumi.answer()'s with nothing running and the hand empty ("idle") or
holding something ("holding"): stop, what the cameras see (seeing.answer), status, the hand (brain.hand_request), mission, goodbye / closing words, song, holding something ("holding"): stop, what the cameras see (seeing.answer), status, the hand (brain.hand_request), mission, goodbye / closing words, song,
keyword rules, then the LLM's action line acted on as lumi.answer() does. Nothing moves; the LLM is only asked. keyword rules, then the LLM's action line acted on as lumi.answer() does. Nothing moves; the LLM is only asked.
""" """
@@ -19,15 +20,20 @@ import time
from assistant import brain, driving, lumi, seeing from assistant import brain, driving, lumi, seeing
from audio import sing from audio import sing
from tests.command_cases import CASES from tests.command_cases import CASES as CASES1
from tests.command_cases2 import CASES as CASES2 # 2026-10-21 night: new wordings, the conference map
from tests.conversation_check import NOW, markers from tests.conversation_check import NOW, markers
ROOT = pathlib.Path(__file__).resolve().parents[1] ROOT = pathlib.Path(__file__).resolve().parents[1]
OUT = ROOT / "logs" / "command_check" OUT = ROOT / "logs" / "command_check"
HOLDING_NOW = "I'm holding a cup and waiting for what to do with it." HOLDING_NOW = "I'm holding a cup and waiting for what to do with it."
NO_MOTION = {"seeing", "talk", "unclear", "status", "empty_hand", "refuse", "search", "weather", "llm?", "ask", "speed"} NO_MOTION = {"seeing", "talk", "unclear", "status", "empty_hand", "refuse", "search", "weather", "llm?", "ask", "speed"}
QUICK = {"go_to", "come", "quiet", "weather", "search", "move", "turn", "arm", "pick", "put", "move_object", "fetch", QUICK = {"go_to", "come", "follow", "come_back", "quiet", "weather", "search", "move", "turn", "arm", "pick", "put",
"look", "lift", "wave"} # lumi.quick_command "move_object", "fetch", "look", "lift", "wave"} # lumi.quick_command
class NoLLM(Exception):
"""A rules-only run reached the mission reader's LLM pass."""
def seen(text): def seen(text):
@@ -46,10 +52,15 @@ def rules(text, state, marks, b):
holding = state == "holding" holding = state == "holding"
if lumi.FOREIGN_SCRIPT.search(text): if lumi.FOREIGN_SCRIPT.search(text):
return "unclear" return "unclear"
fixed = brain.self_correct(text, marks) # "go to start, no, end"
if not fixed:
return "ask" if fixed is None else "talk"
text = fixed
t = brain._norm(text) # lumi.drive_words: speed, "again", how far?, too far t = brain._norm(text) # lumi.drive_words: speed, "again", how far?, too far
drive = driving.read(t, driving.last_command(b.history), driving.talking(b.history)) drive = driving.read(t, driving.last_command(b.history), driving.talking(b.history))
if drive and (drive[0] != "move" or drive != driving.read(t, None, True)): if drive and (drive[0] != "move" or drive != driving.read(t, None, True)):
return {"speed": lambda d: f"speed {'faster' if d[1] > 0 else 'slower'}", "move": lambda d: f"action:move {d[1]}", return {"speed": lambda d: f"speed {'faster' if d[1] > 0 else 'slower'}", "move": lambda d: f"action:move {d[1]}",
"turn": lambda d: f"action:turn {d[1]}",
"refuse": lambda d: "refuse", "ask": lambda d: "ask"}[drive[0]](drive) "refuse": lambda d: "refuse", "ask": lambda d: "ask"}[drive[0]](drive)
if lumi.NAME_ONLY.match(text): if lumi.NAME_ONLY.match(text):
return "talk" return "talk"
@@ -70,7 +81,8 @@ def rules(text, state, marks, b):
"refuse": lambda h: "refuse", "ask": lambda h: "talk"}[hand[0]](hand).strip() "refuse": lambda h: "refuse", "ask": lambda h: "talk"}[hand[0]](hand).strip()
read = lumi.read_mission(text, marks) read = lumi.read_mission(text, marks)
if read: if read:
return "talk" if read[1] else "mission" from assistant import steps # lumi.mission_request: refused before anything moves
return "talk" if read[1] else "refuse" if steps.check(read[0], holding, marks) else "mission"
if lumi.talk_fate(text) == "end": if lumi.talk_fate(text) == "end":
return "end" return "end"
if lumi.talk_fate(text) == "wait": if lumi.talk_fate(text) == "wait":
@@ -86,6 +98,7 @@ def rules(text, state, marks, b):
def llm(text, state, marks, b): def llm(text, state, marks, b):
"""(route, action line, first sentence) from the real model, acted on like lumi.answer().""" """(route, action line, first sentence) from the real model, acted on like lumi.answer()."""
brain.FORCED_LANG["lang"] = "ko" if brain.HANGUL.search(text) else "en" brain.FORCED_LANG["lang"] = "ko" if brain.HANGUL.search(text) else "en"
text = brain.self_correct(text, marks) or text
gen = b.respond_stream(text, marks, now=HOLDING_NOW if state == "holding" else NOW) gen = b.respond_stream(text, marks, now=HOLDING_NOW if state == "holding" else NOW)
head = next(gen) head = next(gen)
first = next(gen, "") or "" first = next(gen, "") or ""
@@ -136,20 +149,31 @@ def ok(expect, got):
def main(args): def main(args):
global OUT
marks = markers() marks = markers()
use_llm, cached = "--llm" in args, "--cached" in args use_llm, cached = "--llm" in args, "--cached" in args
cases = CASES2 if "--new" in args else CASES1 if "--old" in args else CASES1 + CASES2
only = [a for a in args if not a.startswith("-")] only = [a for a in args if not a.startswith("-")]
old = {} old = {}
if cached and OUT.with_suffix(".json").exists(): if cached and OUT.with_suffix(".json").exists():
old = {(r["text"], r["state"], str(r["before"])): r for r in json.loads(OUT.with_suffix(".json").read_text()) old = {(r["text"], r["state"], str(r["before"])): r for r in json.loads(OUT.with_suffix(".json").read_text())
if r.get("raw")} if r.get("raw")}
if not use_llm and not cached:
OUT = OUT.with_name("command_check_rules") # a rules-only run keeps the last LLM run's report
if not use_llm: # a mission's LLM pass (lumi.read_mission) only with --llm
from assistant import steps
steps._ollama = lambda *a: (_ for _ in ()).throw(NoLLM())
rows, t0 = [], time.time() rows, t0 = [], time.time()
for i, c in enumerate(c for c in CASES if not only or c["intent"] in only): for i, c in enumerate(c for c in cases if not only or c["intent"] in only):
b = brain.Brain() b = brain.Brain()
if c["before"]: if c["before"]:
b.history.append(tuple(c["before"])) b.history.append(tuple(c["before"]))
brain.FORCED_LANG["lang"] = c["lang"] if c["lang"] in ("en", "ko") else "ko" brain.FORCED_LANG["lang"] = c["lang"] if c["lang"] in ("en", "ko") else "ko"
got, raw, first = rules(c["text"], c["state"], marks, b), "", "" mk = c.get("markers") or marks
try:
got, raw, first = rules(c["text"], c["state"], mk, b), "", ""
except NoLLM:
got, raw, first = "llm?", "", ""
if got is None: if got is None:
key = (c["text"], c["state"], str(c["before"])) key = (c["text"], c["state"], str(c["before"]))
if key in old: if key in old:
@@ -158,7 +182,7 @@ def main(args):
got = act(a, tgt, first, c["state"]) got = act(a, tgt, first, c["state"])
elif use_llm: elif use_llm:
try: try:
got, raw, first = llm(c["text"], c["state"], marks, b) got, raw, first = llm(c["text"], c["state"], mk, b)
except Exception as e: # noqa: BLE001 - a crash is a failure of that case except Exception as e: # noqa: BLE001 - a crash is a failure of that case
got, raw = "error", repr(e) got, raw = "error", repr(e)
else: else:
+197
View File
@@ -0,0 +1,197 @@
"""Missions (docs/17), seventh round (2026-10-21 night): three or four steps said in one breath, English, Korean and
mixed, on the conference map (CONF: start, end, init, final, middle, table_front, stage, booth_2, home, dock2), with
then / and / after that / 그리고 / 다음에 / -고 / -서, fillers ("먼저", "그다음", "I'd like you to"), waits, named
people, "갔다 와" / "다녀와". Same notation as tests/test_steps.py; "?" = some words must stay unread (nothing runs).
FIXED: said with a correction inside ("go to start, no, end, then come back"): brain.self_correct first, then read.
READ_BACK: the sentence Lumi says before starting (steps.describe), English and Korean.
"""
CONF = ["home", "start", "end", "init", "final", "middle", "table_front", "stage", "booth_2", "dock2"]
CASES = {
# ---- the owner's examples, on this map ----
"take the cup, go to booth two, give it to James and come back": "pick cup | go booth_2 | give James | go here",
"먼저 스테이지 가서 컵 가져오고 그다음 여기로 와서 줘": "go stage | pick cup | go here | give",
"take the cup, go to the stage, give it to the person there and come back here": "pick cup | go stage | give | go here",
# ---- English: then / and / after that ----
"pick up the cup, then go to the end, then give it to Sarah": "pick cup | go end | give Sarah",
"grab the apple and take it to table front and put it on the table": "pick apple | go table_front | place dining table",
"go to booth two, pick up the cup, and bring it back to me": "go booth_2 | pick cup | go here | give",
"go to the stage, wait 10 seconds, then come back": "go stage | wait 10 | go here",
"go to start, after that go to middle, after that go to end": "go start | go middle | go end",
"first go to start, then go to the middle, and finally come back here": "go start | go middle | go here",
"go to the stage and wait there for 2 minutes, then go to booth two and come back": "go stage | wait 120 | go booth_2 | go here",
"take the cup to the stage, put it on the table and come back": "pick cup | go stage | place dining table | go here",
"could you take the cup to the stage and then come back here please": "pick cup | go stage | go here",
"I'd like you to take the cup, go to the end and hand it to Sarah": "pick cup | go end | give Sarah",
"I want you to go to the stage, say hello everyone, and come back": "go stage | say hello everyone | go here",
"go to init, turn around and come back": "go init | turn 180 | go here",
"turn left, go forward one meter, turn right and go forward half a meter": "turn 90 | move forward 1 | turn -90 | move forward 0.5",
"go forward 1 meter then turn around then go forward 1 meter": "move forward 1 | turn 180 | move forward 1",
"go to booth 2, wait until someone gives you a cup, then bring it here": "go booth_2 | receive cup wait | go here",
"go to the stage and do what they tell you": "go stage | wait order",
"go to table front, ask them for the cup, then bring it to the stage": "go table_front | receive cup | go stage",
"take the cup from start to end and give it to Mr. Kim": "go start | pick cup | go end | give Mr. Kim",
"pick up the red cup, go to the final point, and hold it": "pick red cup | go final | hold",
"go to the middle, then booth two, then the stage": "go middle | go booth_2 | go stage",
"go to start, middle and end": "go start | go middle | go end",
"go to the stage, after 30 seconds go to end": "go stage | wait 30 | go end",
"wait 5 seconds then go to the stage and come back": "wait 5 | go stage | go here",
"bring the cup to James at the stage": "pick cup | go stage | give James",
"take this cup to Anna, she is at booth two": "go booth_2 | give Anna",
"go to the end and stay there": "go end | wait",
"go to the stage, wait there, then go home": "go stage | wait | go home",
"Lumi, go to start and then come back, thanks": "go start | go here",
"um, take the cup, uh, go to the stage and give it to them": "pick cup | go stage | give",
"please go to the stage, after that come back and give it to me": "go stage | go here | give",
"go to the stage, then come back and turn left": "go stage | go here | turn 90",
"go to the stage once you're there say welcome and then come back": "go stage | say welcome | go here",
"go to booth 2 and tell them the demo starts at 3, then go to the stage": "go booth_2 | say the demo starts at 3 | go stage",
"take the cup and bring it to one of start, middle or end": "pick cup | go start,middle,end",
"head to table front, then make your way to the stage and come back": "go table_front | go stage | go here",
"navigate to the stage and then return here": "go stage | go here",
# ---- Korean: -고 / -서 / 그리고 / 다음에, every speech level ----
"스테이지 가서 컵 가져오고 여기로 와": "go stage | pick cup | go here",
"컵 집고 스테이지로 가서 제임스한테 줘": "pick cup | go stage | give 제임스",
"컵 가지고 스테이지 가서 김 대리님께 드려": "pick cup | go stage | give 김 대리님",
"스타트로 가서 10초 기다렸다가 엔드로 가": "go start | wait 10 | go end",
"부스 투에서 병 집어서 테이블 프론트로 가져가": "go booth_2 | pick bottle | go table_front",
"스테이지 가서 안녕하세요라고 말하고 돌아와": "go stage | say 안녕하세요 | go here",
"스테이지 갔다 와": "go stage | go here",
"부스 투 다녀와 줄래?": "go booth_2 | go here",
"스테이지 갔다가 엔드로 가 줘": "go stage | go end",
"앞으로 1미터 가고 왼쪽으로 돌고 다시 1미터 가": "move forward 1 | turn 90 | move forward 1",
"먼저 미들로 가고 그다음 엔드로 가 주세요": "go middle | go end",
"스타트로 가고 그리고 미들로 가고 마지막으로 엔드로 가": "go start | go middle | go end",
"컵 들고 스테이지로 가서 테이블에 놔 줘": "pick cup | go stage | place dining table",
"컵 잡고 엔드로 가서 사라한테 주고 돌아와": "pick cup | go end | give 사라 | go here",
"부스 투에 가서 누가 컵 주면 받아서 여기로 가져와": "go booth_2 | receive cup wait | go here",
"스테이지에 가서 2분 기다리고 돌아오세요": "go stage | wait 120 | go here",
"엔드로 가서 거기서 기다려": "go end | wait",
"스테이지 가서 거기 있는 사람이 시키는 거 해": "go stage | wait order",
"테이블 프론트에 가서 컵 받아서 스테이지로 가져가": "go table_front | receive cup | go stage",
"스타트 갔다가 다시 돌아와 줄래요?": "go start | go here",
"컵을 집어서 파이널로 가 주시고 거기 계신 분께 드리세요": "pick cup | go final | give",
"사과 들고 미들로 가서 들고 있어": "pick apple | go middle | hold",
"뒤로 돌아서 앞으로 2미터 가고 오른쪽으로 돌아": "turn 180 | move forward 2 | turn -90",
"5초 있다가 스테이지로 가": "wait 5 | go stage",
"스테이지로 가서 이 분 기다렸다가 돌아와": "go stage | wait 120 | go here",
"이닛으로 가서 뒤로 돌고 와": "go init | turn 180 | go here",
# ---- mixed ----
"take the cup 하고 스테이지로 가서 줘": "pick cup | go stage | give",
"스테이지 가서 pick up the cup 하고 돌아와": "go stage | pick cup | go here",
"go to 스테이지, wait 10 seconds, 그리고 돌아와": "go stage | wait 10 | go here",
"컵 take해서 booth 2로 가져가": "pick cup | go booth_2",
"go to 부스 투 and then come back": "go booth_2 | go here",
# ---- must not run: unread or not on the map ----
"go to the stage and wave": "?",
"go to the stage and follow me": "?",
"pick up the cup and lift yourself up": "?",
"go to booth two and look left": "?",
"go to the stage and dance": "?",
"go to the kitchen, then come back": "?",
"take the cup to p3 and come back": "?", # p3 is not on this map
"go to booth, then come back": "?", # which booth? never guessed
"go to the stage for a while and come back": "?", # how long? never guessed
"스테이지 가서 춤추고 와": "?",
"부엌에 가서 컵 가져와": "?",
"go to the stage and give it to him": "?", # nothing in the hand before: refused by check
}
# second round: Korean "-고 나서" / "-ㄴ 다음에", a gift with the object in between, no commas (whisper), ordinals,
# "after you get to ...", "hang around", "wait for my call", "come right back"
CASES.update({
"스테이지에 가고 나서 엔드로 가": "go stage | go end",
"스테이지에 간 다음에 엔드로 가 줘": "go stage | go end",
"컵을 집은 다음에 스테이지로 가": "pick cup | go stage",
"컵 집고 나서 스테이지로 가져가": "pick cup | go stage",
"스테이지에 갔다가 부스 투로 가서 컵 받아 와": "go stage | go booth_2 | receive cup | go here",
"스테이지로 가서 10초만 기다렸다가 돌아와": "go stage | wait 10 | go here",
"스테이지 가서 잠깐 기다렸다가 와": "go stage | wait 10 | go here",
"스테이지까지 가서 사라 씨한테 컵 전해 줘": "go stage | give 사라",
"엔드로 가서 거기 있는 분한테 이거 드리고 와": "go end | give | go here",
"부스 투에 있는 제임스한테 이 컵 갖다줘": "pick cup | go booth_2 | give 제임스",
"go to the stage then wait ten secs then come back": "go stage | wait 10 | go here",
"go to the stage, hang around for 10 seconds, then come back": "go stage | wait 10 | go here",
"go to start, then to middle, then back here": "go start | go middle | go here",
"take the cup over to booth two and come right back": "pick cup | go booth_2 | go here",
"bring the cup over to the stage and leave it on the table": "pick cup | go stage | place dining table",
"go grab the cup, bring it to the stage": "pick cup | go stage",
"go to the stage and get me the cup": "go stage | pick cup | go here | give",
"after you get to the stage, wait 5 seconds and come back": "go stage | wait 5 | go here",
"when you get to the stage, say hello": "go stage | say hello",
"go to stage wait 10 seconds come back": "go stage | wait 10 | go here",
"first take the cup, second go to the stage, third give it to Sarah": "pick cup | go stage | give Sarah",
"take the cup and go to booth two, then wait there until someone takes it": "pick cup | go booth_2 | give",
"go to the stage and give the cup to whoever is there": "go stage | give",
"go to the stage and hand the cup to the first person you see": "go stage | give",
"go to booth two and wait for my call": "go booth_2 | wait",
"booth 2 가서 컵 가져오고 스테이지로 가": "go booth_2 | pick cup | go stage",
"go to 엔드 and 컵 가져와": "go end | pick cup | go here",
})
# third round: "not booth two", a message to a named person, people and places in any order
CASES.update({
"take the cup to the stage, not booth two": "pick cup | go stage",
"스테이지 말고 부스 투로 가서 컵 줘": "go booth_2 | pick cup | go here | give",
"go to the stage and tell Sarah the meeting is at 3": "go stage | say the meeting is at 3",
"go to Sarah at the stage and give her the cup": "go stage | give Sarah",
"Sarah is at booth two, bring her the cup": "pick cup | go booth_2 | give Sarah",
"사라는 부스 투에 있어, 컵 갖다줘": "pick cup | go booth_2 | give 사라",
"컵을 사라한테 갖다 줘, 사라는 부스 투에 있어": "pick cup | go booth_2 | give 사라",
"go to the stage, and if nobody is there, come back": "?", # no conditions in a task: asked
"go to the stage, wait a few minutes, then come back": "?", # how long? never guessed
"스테이지 가서 몇 분 기다렸다가 와": "?",
"go to the stage, wait 30 seconds, go to booth two, wait 30 seconds, then come back":
"go stage | wait 30 | go booth_2 | wait 30 | go here",
"can you go to booth 2 and ask for a cup and bring it to me": "go booth_2 | receive cup | go here | give",
"turn around, take the cup and give it to me": "turn 180 | pick cup | give",
"take the cup and put it on the chair at the stage": "pick cup | go stage | place chair",
})
# fourth round: 하십시오체 / 해요체 with -시- ("가셔서", "받으시고", "기다리신 후에"), "거기서 기다려" (no stop),
# "who is at", "from the table there", "at the stage"
CASES.update({
"컵을 들고 스테이지로 가신 다음에 테이블에 올려 주세요": "pick cup | go stage | place dining table",
"스테이지에 가셔서 10초 기다리신 후에 돌아오세요": "go stage | wait 10 | go here",
"부스 투에 가셔서 컵을 받으시고 여기로 가져와 주십시오": "go booth_2 | receive cup | go here",
"먼저 컵을 집으시고 엔드로 가셔서 사라 씨께 드리세요": "pick cup | go end | give 사라",
"스테이지로 가서 컵 가져오고, 그 다음에 부스 투로 가서 제임스한테 줘": "go stage | pick cup | go booth_2 | give 제임스",
"컵 집어서 스테이지로 가져가서 테이블에 놓고 돌아와": "pick cup | go stage | place dining table | go here",
"스테이지 갔다가 부스 투 갔다가 돌아와": "go stage | go booth_2 | go here",
"앞으로 1미터 갔다가 다시 돌아와": "move forward 1 | go here",
"오른쪽으로 돌고 앞으로 50센티 가고 컵 집어": "turn -90 | move forward 0.5 | pick cup",
"스테이지로 가서 30초 있다가 엔드로 가서 기다려": "go stage | wait 30 | go end | wait",
"야 스테이지 가서 컵 좀 가져와 봐": "go stage | pick cup | go here",
"스테이지 가서 거기서 기다려": "go stage | wait",
"스테이지 가서 기다리다가 누가 컵 주면 받아서 와": "go stage | receive cup wait | go here",
"go to the stage, take a cup from the table there and bring it to booth two": "go stage | pick cup | go booth_2",
"go pick up the cup at the stage and bring it to me": "go stage | pick cup | go here | give",
"take the cup and bring it to Sarah, who is at booth two": "pick cup | go booth_2 | give Sarah",
"go to the stage and wait there until I tell you to come back": "go stage | wait",
"go ahead to the stage and come back": "go stage | go here",
"pick up the cup, go forward half a meter, turn right, go forward one meter and put it on the table":
"pick cup | move forward 0.5 | turn -90 | move forward 1 | place dining table",
})
# said with a correction inside: brain.self_correct reads it first (lumi.answer)
FIXED = {
"take the cup, go to start, no, end, and give it to James": "pick cup | go end | give james",
"go to start, sorry, I mean the stage, then come back": "go stage | go here",
"go to the stage, wait 10 seconds, no, 20 seconds, then come back": "go stage | wait 20 | go here",
"컵 들고 스타트로 가, 아니 엔드로 가서 줘": "pick cup | go end | give",
"pick up the cup, no, the apple, and bring it to the stage": "pick apple | go stage",
}
# the read-back (steps.describe) for a few of them
READ_BACK = {
"pick cup | go booth_2 | give James | go here":
("Take the cup, go to booth 2, hand it to James, then come back here.",
"컵을 집고 booth 2 위치로 가고 James에게 건네주고 여기로 돌아올게요."),
"go stage | pick cup | go here | give":
("Go to stage, take the cup, come back here, then hand it over.",
"stage 위치로 가고 컵을 집고 여기로 돌아오고 건네줄게요."),
"go table_front | wait 30 | go home":
("Go to table front, wait 30 seconds, then go to my dock.",
"table front 위치로 가고 30초 기다리고 충전소로 갈게요."),
}
+7
View File
@@ -151,4 +151,11 @@ for m, v in ((0.01, "-0.050"), (0.3, "-0.120")):
assert vel == {v}, (m, vel) assert vel == {v}, (m, vel)
fetch.speed_factor = 1.0 fetch.speed_factor = 1.0
fetch.agv.request, skills.moved = real_request, real_moved fetch.agv.request, skills.moved = real_request, real_moved
# "again" / "a bit more" right after a turn (2026-10-21)
_turn = driving.last_command([("turn left", "ACTION: turn left 90")])
assert _turn == ("turn", "left 90"), _turn
for _t, _want in {"again": ("turn", "left 90"), "한 번 더": ("turn", "left 90"), "one more time": ("turn", "left 90"),
"a bit more": ("turn", "left 15"), "조금 더": ("turn", "left 15")}.items():
assert driving.read(brain._norm(_t), _turn) == _want, (_t, driving.read(brain._norm(_t), _turn))
assert driving.read("a bit more", ("turn", "around 180")) == ("ask", "")
print("driving: all self-checks passed") print("driving: all self-checks passed")
+78
View File
@@ -0,0 +1,78 @@
"""Self-check of commands of several steps said by voice, the way lumi.answer() takes them (docs/17 §2, §6): the
correction inside the sentence (brain.self_correct), lumi.read_mission (a mission, the plain fetch, or asked again:
a part that is no task step is never done half), the read-back sentence, and the Greeter-only rule (a mission that
drives is refused with one line, one that stays in place runs). Fake robot; the mission reader's LLM pass faked
(it reads nothing):
python tests/test_mission_route.py"""
import types
from assistant import brain, lumi, steps
from tasks import fetch
from tests import steps_cases7 as c7
M = c7.CONF
def forbid(*a, **k):
raise AssertionError("a test reached the robot")
refusal = lumi.skills.refusal # a table of what the fingers can't take, no robot
for mod in (lumi.agv, lumi.head, lumi.arm, lumi.gripper, lumi.motion, lumi.skills): # nothing may reach the robot
for name in dir(mod):
if not name.startswith("_") and callable(getattr(mod, name)) and not isinstance(getattr(mod, name), type):
setattr(mod, name, forbid)
lumi.skills.refusal = refusal
steps._ollama = lambda messages, fmt: {"language": "English"} if fmt == "json" else {"steps": [{"do": "unknown"}]}
lumi.log = fetch.log = lambda *a: None
# ---------- every mission of the conference set: read whole, or the plain fetch; "?": asked, nothing moves ----------
bad = []
for text, want in list(c7.CASES.items()) + list(c7.FIXED.items()):
t = brain.self_correct(text, M)
read = lumi.read_mission(t, M)
rule = brain.intent(t, M)
if want == "?":
asked = read is not None and read[1]
refused = read is not None and not read[1] and steps.check(read[0], False, M)
if not (asked or refused or read is None and (rule is None or rule[0] == "fetch")):
bad.append((text, read, rule))
elif not (read and not read[1] or read is None and rule and rule[0] == "fetch"):
bad.append((text, read, rule))
assert not bad, bad
# ---------- the corrections said by voice ----------
FIX = {"go to start, no, end": "go to end", "스타트로 가, 아니 엔드로": "end로 가", "turn left, I mean right": "turn right",
"앞으로 1미터, 아니 2미터 가": "앞으로 2 m 가", "컵 집어, 아니 병": "병 집어", "go to the stage, never mind": "",
"스테이지로 가, 아니 됐어": "", "go to the stage, no, the kitchen": None, "I like apples, no, I love them": None,
"go to the stage, no rush": None, "no, go to the end": None}
for text, want in FIX.items():
got = brain.self_correct(text, M)
assert got == (text if want is None and text in ("I like apples, no, I love them", "go to the stage, no rush",
"no, go to the end") else want), (text, got)
# ---------- Greeter only: a mission that drives is refused, one in place runs ----------
said, started = [], []
L = lumi.Lumi.__new__(lumi.Lumi)
L.lang, L.markers, L.current = "en", M, None
L.brain = types.SimpleNamespace(history=[])
L.keep_listening = lambda: None
L.fetch_say = lambda en, ko=None: said.append(en)
L.fetch_status = lambda: None
L.modes = types.SimpleNamespace(greeter=True, patrol=False, drive=True, wave=True)
fetch.check_hand = lambda: False
lumi.fetch_dialog = types.SimpleNamespace(run_steps=lambda s, hear, say, describe, start: started.append(s) or "started")
for text in ("take the cup, go to booth two, give it to James and come back", "스테이지 갔다 와",
"go to the stage, wait 10 seconds, then come back"):
said.clear(), started.clear()
assert L.mission_request(text) and said == [lumi.BASE_OFF_SAY[0]] and not started, (text, said, started)
for text in ("pick up the cup and give it to me", "컵 집어서 나한테 줘"):
said.clear(), started.clear()
assert L.mission_request(text) and started and not said, (text, said, started)
said.clear()
assert L.mission_request("go to the stage and wave") and said and said[0].startswith("Sorry, I can't do that as part"), said
L.modes.patrol = True
said.clear(), started.clear()
assert L.mission_request("take the cup, go to booth two, give it to James and come back") and started
assert steps.describe(started[0]) == "Take the cup, go to booth 2, hand it to James, then come back here."
print("mission route ok")
+4 -1
View File
@@ -22,4 +22,7 @@ assert llm_direct.render([{"role": "system", "content": "S"}, {"role": "user", "
{"role": "assistant", "content": "A"}, {"role": "user", "content": "Q2"}]) == \ {"role": "assistant", "content": "A"}, {"role": "user", "content": "Q2"}]) == \
("<|turn>system\nS<turn|>\n<|turn>user\nQ<turn|>\n<|turn>model\nA<turn|>\n<|turn>user\nQ2<turn|>\n" ("<|turn>system\nS<turn|>\n<|turn>user\nQ<turn|>\n<|turn>model\nA<turn|>\n<|turn>user\nQ2<turn|>\n"
"<|turn>model\n<|channel>thought\n<channel|>") "<|turn>model\n<|channel>thought\n<channel|>")
print(f"ok: {len(CUTS)} cuts, the prompt") # a prefill (system + turns) is the start of the next prompt, so the runner's cache holds it
start = [{"role": "system", "content": "S"}, {"role": "user", "content": "Q"}, {"role": "assistant", "content": "A"}]
assert llm_direct.render(start + [{"role": "user", "content": "Q2"}]).startswith(llm_direct.render(start, reply=False))
print(f"ok: {len(CUTS)} cuts, the prompt, the prefill")
+27 -3
View File
@@ -213,7 +213,7 @@ print("steps ok")
fake = {} fake = {}
steps._ollama = lambda messages, fmt: fake["lang"] if fmt == "json" else fake["steps"] steps._ollama = lambda messages, fmt: fake["lang"] if fmt == "json" else fake["steps"]
fake["lang"] = {"language": "English"} fake["lang"] = {"language": "English"}
cmd = "grab the bottle and then kindly roll over to p4, after that put it onto the white table" cmd = "grab the bottle and then kindly zip over to p4, after that put it onto the white table"
fake["steps"] = {"steps": [{"do": "pick", "object": "bottle"}, {"do": "go", "to": ["p4"]}, fake["steps"] = {"steps": [{"do": "pick", "object": "bottle"}, {"do": "go", "to": ["p4"]},
{"do": "place", "on": {"name": "dining table", "colour": "white"}}]} {"do": "place", "on": {"name": "dining table", "colour": "white"}}]}
got, unread, by = steps.read(cmd, M) got, unread, by = steps.read(cmd, M)
@@ -251,8 +251,8 @@ assert llm_says("go to p1, then roll back 1.5 m and wiggle", [{"do": "go", "to":
assert llm_says("kindly roll forward 1 m and then wiggle", [{"do": "move", "dir": "forward", "m": 1}, assert llm_says("kindly roll forward 1 m and then wiggle", [{"do": "move", "dir": "forward", "m": 1},
{"do": "move", "dir": "forward", "m": 1}])[2] == "rules" # said once, driven twice {"do": "move", "dir": "forward", "m": 1}])[2] == "rules" # said once, driven twice
assert llm_says("don't take the cup, just roll over to p1", [{"do": "go", "to": ["p1"]}])[2] == "rules" assert llm_says("don't take the cup, just roll over to p1", [{"do": "go", "to": ["p1"]}])[2] == "rules"
assert llm_says("take the cup and then roll over to p1", [{"do": "go", "to": ["p1"]}])[2] == "rules" # pick left out assert llm_says("take the cup and then zip over to p1", [{"do": "go", "to": ["p1"]}])[2] == "rules" # pick left out
got = llm_says("take the cup and then roll over to p1", [{"do": "pick", "object": "cup"}, {"do": "go", "to": ["p1"]}]) got = llm_says("take the cup and then zip over to p1", [{"do": "pick", "object": "cup"}, {"do": "go", "to": ["p1"]}])
assert got[2] == "llm" and got[0] == S("pick cup | go p1"), got assert got[2] == "llm" and got[0] == S("pick cup | go p1"), got
# ---- lists: only "or" / one of / 중 is a choice; "and" is both, in turn ---- # ---- lists: only "or" / one of / 중 is a choice; "and" is both, in turn ----
@@ -293,3 +293,27 @@ assert llm_says("go to p2, then chill there and wiggle", [{"do": "go", "to": ["p
assert llm_says("go to p2, then chill there and do whatever the visitors tell you", [{"do": "go", "to": ["p2"]}, assert llm_says("go to p2, then chill there and do whatever the visitors tell you", [{"do": "go", "to": ["p2"]},
{"do": "wait", "s": None, "until": "instruction"}])[0] == S("go p2 | wait order") {"do": "wait", "s": None, "until": "instruction"}])[0] == S("go p2 | wait order")
print("steps wait ok") print("steps wait ok")
# ---- three or four steps in one breath on the conference map (tests/steps_cases7.py) ----
from assistant import brain
from tests import steps_cases7 as c7
failed = []
for text, want in list(c7.CASES.items()) + [(brain.self_correct(t, c7.CONF), w) for t, w in c7.FIXED.items()]:
got, unread = steps.rules(text, c7.CONF)
if want == "?":
ok = bool(unread) or bool(steps.check(got, False, c7.CONF))
else:
ok = not unread and got == [short(x.strip()) for x in want.split(" | ")]
if not ok:
failed.append(text)
print(f"FAIL {text!r}\n want {want}\n got {got}\n unread {unread}")
for want, (en, ko) in c7.READ_BACK.items():
s_ = [short(x.strip()) for x in want.split(" | ")]
for lang, said in (("en", en), ("ko", ko)):
if steps.describe(s_, lang) != said:
failed.append(want)
print(f"FAIL read-back {lang} {want!r}\n want {said}\n got {steps.describe(s_, lang)}")
print(f"{len(c7.CASES) + len(c7.FIXED) - sum(1 for f in failed if f in c7.CASES or f in c7.FIXED.values())}/"
f"{len(c7.CASES) + len(c7.FIXED)} read right on the conference map")
assert not failed
print("steps conference ok")