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
+170 -19
View File
@@ -383,7 +383,7 @@ HEAD_WORDS = (r"\blook (?:straight )?(?:up|down|left|right|ahead|forward|straigh
r"|(?:고개|머리)(?:를|좀|살짝|조금|약간|\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)"
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"|몸(?:을)? ?(?:좀 )?(?:[\d.]+ ?(?:m|mm|cm) ?(?:만 ?)?)?(?:올려|내려|낮춰|높여)"
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"그만 ?(?:좀 ?)?(?:쳐다|바라)(?:봐|보세요)|"
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
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"
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}).*(집어서|들고).*가서"
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"나한테 ?(?:돌아 ?)?와"),
("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:
r"|^\W*(?:(?:루미야?|lumi|hey lumi)\W*)?(?:좀\s*)?(?:point\s+)?([a-z][a-z0-9_]*)\s*(?:으로|로|에)\s*(?:좀\s*)?" # "p3로 가 줘":
r"(?:가|와|이동해|돌아가|돌아 ?와)" # all of it
r"(?:\s*줘요?|\s*주세요|요|자|줄래)?\s*[.!?]*$"),
("go_point", r"\b(?:go|drive|move|head|come|return|walk|roll|run|proceed|navigate|travel|hurry|make your way|get|take yourself)"
r"(?: back)?(?: over| on| ahead)?(?: to| too| 2|to) (?:the )?(?:point |marker )?([a-z][a-z0-9_]*)\b|(\d+)\s*번\s*(?:으로|포인트)"
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*)?(?:가|와|이동해|돌아가|돌아 ?와)" # "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|노래"),
("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|뒤로 ?돌|돌아 ?봐|왼쪽으로 ?돌|오른쪽으로 ?돌"),
("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|비켜|자리 ?(좀 )?(비워|옮겨)|길 ?(좀 )?(비켜|터)"),
@@ -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
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)"
@@ -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"^\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.*수 ?있|는 ?거 ?(돼|되나|가능)|" # "물컵은 가져다줄 수 있어요?"
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:
m = re.search(pat, t, re.I)
if not m:
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?"
if action == "look_away":
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",
"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
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):
return None # "did you follow me?": do you understand
if action == "go_home":
@@ -558,7 +581,8 @@ def intent(text, markers=()):
return None # "나 이제 집에 가": the visitor goes home
return ("go_to", "home") if "home" in markers else None
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)
if name and (len(name) > 1 or named_place(text, name, markers)): # "a": not "go to a meeting room"
return ("go_to", name)
@@ -625,6 +649,108 @@ def intent(text, markers=()):
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 ----------
_HERE = r"here|me|여기|이쪽|나한테|저한테|나에게|저에게"
_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
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=()):
"""Lower case, marker names and numbers as written (wording.py: "피쓰리" -> "p3", "point one" -> "p1", with the
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"
t = re.sub(rf"\b{word}\b", digit, 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)
GIVE_KO = re.compile(
rf"^\W*(?:{_THIS_KO}|(?:\S+\s+)?(?:{_OBJ}))?(?:을|를)?\s*(?:좀\s*)?(?:이제\s*)?(?:이리|여기|빨리)?\s*(?:좀\s*)?"
rf"(?:{_KO_WHO}(?:한테|에게|께))?\s*(?:좀\s*)?(?:{_THIS_KO}(?:을|를)?\s*)?(?:좀\s*)?"
r"(?:줘|주세요|줘요|주라|건네 ?줘|건네 ?주세요|건네|드려|드려요|드리세요|주실래요|줄래요?|내놔|내놓아|내놓으세요)(?:\s*봐요?)?\s*[.!?~]*$"
rf"(?:{_KO_WHO}(?:한테|에게|께)|(?:나|저)(?=\s))?\s*(?:좀\s*)?(?:{_THIS_KO}(?:을|를)?\s*)?(?:좀\s*)?"
r"(?:줘|주세요|줘요|주라|건네 ?줘|건네 ?주세요|건네|드려|드려요|드리세요|주실래요|줄래요?|주시겠어요|주십시오|주실 수 있어요|"
r"내놔|내놓아|내놓으세요)(?:\s*봐요?)?\s*[.!?~]*$"
rf"|^\W*{_KO_WHO}\s*(?:줘|줘요|주세요)\W*$", re.I)
PLACE_EN = re.compile(
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+.+)?"
rf"{_TAIL}|\b(?:put|set) (?:it |that |this )?down\b", re.I)
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|"
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|"
@@ -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."""
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:
def __init__(self):
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
# 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"
system = 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 "")
system = route_system(markers, now)
messages = [{"role": "system", "content": system}]
for q, a in self.history[-HISTORY_TURNS:]:
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
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):
self.history = []
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
SPAN_M = 0.2 # m; "한 뼘", one hand span; estimate
STEP_M = 0.5 # m; one step ("two steps", "한 걸음", "반 걸음"); estimate of a person's step
TURN_MORE_DEG = 15.0 # deg; "a bit more" right after a turn: this much further the same way
DIRS = (("back", r"\bback(?:wards?)?\b|\bbackward\b|\breverse\b|^(?:let'?s )?(?:bake|big)\b(?= \d| half| a )|뒤로|뒤쪽|후진|"
r"물러"), # whisper's "let's bake / big one meter"
@@ -130,7 +131,7 @@ def speed(t):
def read(t, last=None, talking=False):
"""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
`talking` (the turn before was conversation) "more" is left to the conversation, else it is asked about."""
t = clean(t)
@@ -142,6 +143,10 @@ def read(t, last=None, talking=False):
return None if talking else ("ask", "") # "more" of what?
if LESS.search(t):
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
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센티 더"
@@ -160,12 +165,14 @@ def _checked(d, n, exact):
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:
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:
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":
return ("speed", int(m.group(2)))
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
_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):
"""Ollama's gemma4 prompt (the runner adds <bos>)."""
def render(messages, reply=True):
"""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"
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):
@@ -88,6 +89,37 @@ def stream(messages, model, temperature=0.3, num_predict=200):
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):
with 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)
WAKE_REPLY = {"en": "Yes? How can I help?", "ko": "네? 무엇을 도와드릴까요?"}
NAME_ONLY = re.compile(r"^\s*(hi |hey |hello )?(lumi|loomi|rumi|루미)[\s,.!?]*$", re.I)
FETCH_STOP = re.compile(r"\b(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_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
@@ -147,6 +147,8 @@ MOVING_ACTIONS = {"go_to", "come", "come_back", "follow", "move", "turn", "arm",
"lift"}
BASE_ACTIONS = {"go_to", "come", "come_back", "follow", "move", "turn"} # need the base: Patrol on
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 /
"지금은 이동하거나 허리를 돌릴 수 없어요. 패트롤을 켜 주세요.") # waist motion asked for
ARM_OFF_SAY = ("Please enable my arm first.", "먼저 제 팔을 켜 주세요.") # an arm action with the arm switched off
@@ -912,6 +914,17 @@ class Lumi:
return True
else:
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":
d, n = got[1].split()
say = driving.say_refused(d, float(n), lang)
@@ -1328,6 +1341,9 @@ class Lumi:
if unread:
log(f" mission: unread {unread} ({by})")
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.keep_listening()
@@ -1760,12 +1776,17 @@ class Lumi:
self.turn_head(HEAD_SIGN * track.angle) # speech only: a greeting never moves the arm
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):
"""Listen once; answer if something was said. Returns True if the visitor spoke."""
if self.pending_text: # asked while Lumi was talking
text, self.pending_text = self.pending_text, None
self.answer(text)
return True
self.warm_llm() # the LLM's prompt start cached while they speak
text, u = ears.listen(wait_s=4.0, on_start=lambda: log(" hearing speech"), abort=self.interrupted, full=True)
if text and 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
@@ -2039,6 +2060,14 @@ class Lumi:
mouth.say("Sorry, I only understand English and Korean." if self.lang == "en" else "죄송해요, 영어와 한국어만 이해해요.")
self.keep_listening()
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"
return
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"))
if self.vision:
self.vision.start()
self.warm_llm()
log("ready")
self.run_camera() if self.vision else self.run_desk()
def stop_order(text, markers):
""""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 \
not brain_mod.STOP_TALK.search(text) and "?" not in text
asked = bool(brain_mod.STOP_ASK.match(brain_mod.CALLING.sub("", text))) # "can you stop?", "멈출 수 있어?": stop
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=""):
@@ -2546,6 +2577,11 @@ def talk_fate(text):
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):
"""(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."""
@@ -2558,8 +2594,11 @@ def read_mission(text, markers):
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)):
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:
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:
return None
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"(앞으로|뒤로|왼쪽으로|오른쪽으로)"
_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"감사합니다|고마워요|고마워|고맙습니다|좀)")
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?)"
# 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
# joining two steps, not a quote
def _norm(text, markers=()):
"""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."""
t = re.sub(r"\b(mr|mrs|ms|dr|prof)\. ", r"\1 ", wording.durations(wording.norm(text, markers)) + " ")
return re.sub(r"\b(?:take|pick up|pick|grab)\s?(?:해서|하고)", "집어서", t).strip() # "컵 take해서": mixed
t = re.sub(r"\b(mr|mrs|ms|dr|prof)\. ", r"\1 ", wording.durations(brain.unfill(wording.norm(text, markers))) + " ")
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 ----------
@@ -95,7 +114,8 @@ def _support(t):
def _go(c, markers):
if brain.COME_BACK.fullmatch(re.sub(r"(?<=[와가])(?:서|고)$", "", c)):
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)
if m:
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)
if m:
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*"
r"(?:으로|로|에|까지)?\s*(?:가져가|가져와|가져다 ?줘|가져다|갖다 ?줘|갖다|가|와|가 ?줘|돌아가|돌아와|갔다가)"
r"(?:으로|로|에|까지)?\s*(?:가져가|가져와|가져다 ?줘|가져다|갖다 ?줘|갖다|가|와|가 ?줘|돌아가|돌아와|갔다가|이동해|이동하고|이동해서|이동)"
r"(?:서|고|세요|줘|요)?|(\S+?)(?:으로|로)", c)
if m:
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",
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"{_DIR_KO}\s*{_NUM} m\s*(?:가|가고|가서|이동|이동해|움직여|와)(?:세요|줘)?")
rf"{_DIR_KO}\s*{_NUM} m\s*(?:가|가고|가서|이동|이동해|움직여|와|갔다가|갔다)(?:세요|줘)?",
rf"(){_NUM} m\s*(?:더\s*)?(?:가|가고|가서|이동해|이동하고|이동해서|전진|전진해|전진하고)(?:세요|줘)?") # "1미터 가": forward
for p in pats:
m = re.fullmatch(p, c)
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},
{"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?"
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:
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)):
@@ -207,7 +234,8 @@ def _pick_receive(c, markers):
return None
out.insert(0, {"do": "go", "to": src[0]})
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:
to = _places(m.group(3), markers)
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))
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
m = re.fullmatch(rf"(?:({COL})\s*)?({OBJ})\s*(?:을|를)?\s*(?:들고|잡고|집고|들어|잡아|집어|챙겨|집어줘|잡아줘|들어줘)(?:서)?", c)
m = re.fullmatch(rf"(?:({COL})\s*)?({OBJ})\s*(?:을|를)?\s*(?:들고|잡고|집고|들어|잡아|집어|챙겨|챙기고|가지고|집어줘|잡아줘|들어줘)(?:서)?", c)
if m:
obj, col = _thing(m.group(1), m.group(2))
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
@@ -234,12 +266,15 @@ def _say(c):
def _give(c):
if re.fullmatch(rf"(?:give|hand) (?:it|that|this|the (?:(?:{COL}) )?(?:{OBJ})s?)?(?: over)?"
rf"(?: to (?:me|you|{_PEOPLE}|the person there|whoever is there))?(?: 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 \
re.fullmatch(rf"(?:그거|그것을?|(?:(?:{COL})\s*)?(?:{OBJ})(?:을|를)?)?\s*(?:줘|주고|주세요|건네 ?줘|건네주고|"
rf"건네 ?주세요|건네)", c):
return {"do": "give"}
if re.fullmatch(r"(?:거기 있는\s*)?(?:나한테|저한테|나에게|저에게|그 사람한테|사람한테|그분께|분께|분한테)\s*"
if re.fullmatch(r"(?:거기 (?:있는|계신)\s*)?(?:나한테|저한테|나에게|저에게|그 사람한테|사람한테|그분께|분께|분한테)\s*"
rf"(?:(?:이거|그거|이것|그것|이걸|그걸|(?:(?:이|그)\s*)?(?:{OBJ})(?:을|를)?)\s*)?"
r"(?:줘|주고|주세요|건네|건네줘|건네주고|건네주세요|건네 ?줘|건네 ?주세요|드려|드리고|갖다 ?줘|갖다 ?주세요)", c) or \
re.fullmatch(r"(?:이|그|저|두|세|네) ?분(?:께|한테|에게)\s*(?:줘|주고|드려|드리고|건네|건네 ?줘|건네 ?드려)", c):
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))|"\
r"one (?:moment|second|sec)|briefly|just a (?:moment|second|sec)))" # wording.durations wrote "<n> 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)*"
_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'-]+)")
@@ -382,8 +418,10 @@ def _wait(c, markers, after):
m = re.fullmatch(rf"(.+?)(?:에서|에)\s*(?:가\s*)?{_KO_WAIT}(?:\s*줘)?", c)
if m and _at_place(m.group(1), markers):
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"
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):
return [{"do": "wait", "s": None}]
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*(?:주십시오|주시겠어요|주시겠습니까|주실 수 있나요|주실 수 있습니까|주실 수 있어요|"
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"말씀(?:해|하세요|하십시오|해요|해 주세요)$", "말해"),
@@ -476,6 +515,17 @@ def _person(c, markers):
return None
out.append({"do": "go", "to": to[0]})
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) )?"
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")):
@@ -497,7 +547,7 @@ def _person(c, markers):
return out
# Korean
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)
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)
@@ -511,7 +561,7 @@ def _person(c, markers):
m = re.fullmatch(rf"(?:이거 |이것 )?여기 있는 {_KNAME}(?:한테|에게|께)\s*{_GIVE_KO}", c)
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}]
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:
to = _places(m.group(2), markers)
if not to or len(to) > 1:
@@ -519,9 +569,12 @@ def _person(c, markers):
if re.search(_GIVE_KO + "$", c):
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]}]
m = re.fullmatch(rf"{_KNAME}\s*(?:씨)?(?:한테|에게|께)\s*{_GIVE_KO}", c)
if m and _ko_name(m.group(1)) not in _NOT_KNAME:
return [{"do": "give", "person": _ko_name(m.group(1)), "where": False}]
m = re.fullmatch(rf"(?:(?:({COL})\s*)?({OBJ})(?:을|를)?\s+)?{_KNAME}\s*(?:씨)?(?:한테|에게|께)\s*(?:(?:이|그|저)\s*)?"
rf"(?:(?:{COL})\s*)?(?:(?:{OBJ})(?:을|를)?|이거|그거)?\s*{_GIVE_KO}", c)
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)
if m and _ko_name(m.group(2)) not in _NOT_KNAME:
to = _places(m.group(1), markers)
@@ -601,11 +654,12 @@ def _clause(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):
c = re.sub(r"\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 = re.sub(r"(\d m)만", r"\1", c) # "1미터만"
bare = _POLITE.sub("", c).strip()
@@ -628,17 +682,24 @@ def _clause_steps(c, markers, after=None):
return []
if re.fullmatch(r"(?:(?:it'?s |this is )?from|on behalf of) [a-z][a-z'-]+|[가-힣 ]+(?:이|가) (?:보내는|보낸) (?:거야|건데)", c):
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"(?:({COL}) )?({OBJ})s?(?: (?:on|from|off) the table| over(?: here)?| there| please)?"
rf"|(?:(?:나|저)(?:한테|에게)?\s*)?(?:({COL})\s*)?({OBJ})\s*(?:을|를)?\s*(?:하나만?\s*)?(?:(?:나|저)(?:한테|에게)\s*)?"
r"(?:줘|주세요|줘요|건네 ?줘|건네 ?주세요|건네|주실래요|줄래요?|주시겠어요)", c)
if m and after is None: # "pass me the cup", "컵 좀 줘": from the table in front, then over
obj, col = _thing(m.group(1) or m.group(3), m.group(2) or m.group(4))
return [{"do": "pick", "object": obj, "colour": col}, {"do": "give"}]
r"(?:줘|주세요|줘요|건네 ?줘|건네 ?주세요|건네|주실래요|줄래요?|주시겠어요|갖다 ?줘|가져다 ?줘|갖다 ?주세요|가져다 ?주세요)", c)
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)) # front, then over; after a drive: back
# 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)
if who is not None:
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"^(go|move|drive) write\b", r"\1 right", c) # whisper's "go write 1 meter"
c = re.sub(r"\bstraight ahead\b", "forward", c)
@@ -657,7 +718,8 @@ def _clause_steps(c, markers, after=None):
r"(?:요| ?주세요)?", c):
return [{"do": "go", "to": "here"}, {"do": "give"}]
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"}]
s = _wait(c, markers, after)
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):
s = f(c, markers) if f is _go else f(c)
if s:
return [s]
return s if isinstance(s, list) else [s]
s = _pick_receive(c, markers)
if s:
return s
@@ -680,7 +742,7 @@ def _clause_steps(c, markers, after=None):
# ---------- whole commands ----------
_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")
_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|"
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)
@@ -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)")
_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=()):
"""(steps, unread clauses). Steps are merged where two clauses mean one ("look for the table" + "put it there")."""
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)
if got is None and steps and steps[-1] == {"do": "go", "to": "home"} and re.fullmatch(r"charge(?: yourself)?|충전해", c):
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)
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):
unread.append(re.sub(r"§(\d+)§", lambda x: says[int(x.group(1))], c))
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
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."""
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:
if s["do"] == "_at":
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:
where = s.pop("where")
if not where:
@@ -1146,8 +1238,9 @@ def _en(s, last=False):
if d == "go":
to = s["to"]
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 "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 s["dir"] in ("left", "right"):
return f"turn {s['dir']} and drive {s['m']:g} m"
@@ -1187,8 +1280,8 @@ def _ko(s, last=False):
if d == "go":
to = s["to"]
if isinstance(to, list):
return f"{', '.join(to)} 중 한 곳으로 가고"
return "여기로 돌아오고" if to == "here" else "충전소로 가고" if to == "home" else f"{to} 위치로 가고"
return f"{', '.join(brain.place_said(x) for x in to)} 중 한 곳으로 가고"
return "여기로 돌아오고" if to == "here" else "충전소로 가고" if to == "home" else f"{brain.place_said(to)} 위치로 가고"
if d == "move":
side = {"forward": "앞으로", "back": "뒤로", "left": "왼쪽으로", "right": "오른쪽으로"}[s["dir"]]
return f"{side} {s['m']:g}미터 가고"