Improve Korean understanding at every speech level and long talks

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-26 07:36:03 +09:00
co-authored by Claude Opus 5.5
parent 284638a22d
commit 1411676269
13 changed files with 1006 additions and 71 deletions
+161 -36
View File
@@ -59,7 +59,10 @@ Rules:
you don't know, or that you can't, and why) with the action none.
- If you do not know a fact about the world (people, places, events, products, prices, sports, news, anything
after your training), do not guess: choose the action "search" so it is looked up on the internet. Well-known
general knowledge (what a robot or AI is, science, history, geography) and opinions you answer yourself.
general knowledge (what a robot or AI is, science, history, geography) and opinions you answer yourself: settled
facts that do not change (a mountain's height, a building's floors, how many bones, how long a marathon is, who
painted or invented something, when a war or an Olympics was, what an animal eats, why the sky is blue) are
answered at once, never searched; search what changes or is new (news, prices, today's scores, schedules).
- For facts about yourself and Cutshion Company use ONLY the reference notes. Only if the notes do not contain the
answer, say you are not sure. Never say you were made or developed by any other company.
- The company's Korean name is 쿳션 (주식회사 쿳션); never write 컷션 or 커션.
@@ -291,19 +294,26 @@ SAID_BEFORE = re.compile(r"\byou said\b|\bearlier you\b|\byou told me\b|아까
FOLLOW_EXAMPLES_K = 2 # follow-up examples (talk_examples.FOLLOWUPS) shown with a short follow-up
LUMI_TOPIC = re.compile(r"\b(?:you|your|yourself|lumi|robots?|arm|gripper|battery|cameras?|lidar|base|wheels?|lift|"
r"jaka|cutshion|company|ceo|gemma|whisper|jetson|thor)\b|너|네가|니가|넌|루미|당신|로봇|팔|그리퍼|"
r"배터리|카메라|라이다|바퀴|리프트|자카|쿳션|회사|대표|젬마|위스퍼|젯슨", re.I)
# a talk about Lumi, its parts or the companies: the notes stay with its follow-ups
def _follow_examples(text, history):
"""For a short follow-up on the last answer ("why?", "and then?", "진짜?", "그게 무슨 말이야?"): two small talks
where such words were answered about the answer before them, so the model keeps the topic and answers at once."""
asked = bool(history) and history[-1][1].rstrip().endswith("?") and confirm_answer(text) is not None # "네" to
if not history or len(text.split()) > 7 or is_backchannel(text) and not ABOUT_ANSWER.match(text) and not asked:
c = core(text) # "음 루미아, 정말요?" asks what "정말요?" asks
if not history or len(c.split()) > 7 or is_backchannel(c) and not about_answer(text) and not asked:
return "" # "더 알려 드릴까요?": do what was offered
if not (asked or ABOUT_ANSWER.match(text) or AND_ALSO.match(text) or FOLLOW_UP.search(text) or SAID_BEFORE.search(text) or
SHORT_Q.search(text) and len(text.split()) <= FRAGMENT_WORDS and not re.search(r"\d", text) and
not ABOUT_YOU.search(text) and (NAMED_BEFORE.search(text) or REFERS_BACK.search(text) or
len(text.strip(" ?!.~")) <= (6 if HANGUL.search(text) else 10))):
if not (asked or about_answer(text) or AND_ALSO.match(c) or FOLLOW_UP.search(c) or SAID_BEFORE.search(text) or
SHORT_Q.search(c) and len(c.split()) <= FRAGMENT_WORDS and not re.search(r"\d", c) and
not ABOUT_YOU.search(c) and (NAMED_BEFORE.search(c) or REFERS_BACK.search(c) or
len(c.strip(" ?!.~")) <= (6 if HANGUL.search(c) else 10))):
return "" # "where is p3?", "세종대왕이 누구예요?" are new questions
from assistant import talk_examples
q, a = history[-1]
q, a = history[-1] if asked else topic_turn(history)
a = " ".join(ln for ln in a.splitlines() if not re.match(r"\s*\**ACTION", ln)).strip()
if not a:
return ""
@@ -483,7 +493,8 @@ OBJECTS = {"cup": "cup", "mug": "cup", "glass": "cup", "tumbler": "cup", "bottle
"화분": "potted plant", "clock": "clock", "handbag": "handbag", "purse": "handbag", "핸드백": "handbag",
"backpack": "backpack", "백팩": "backpack", "suitcase": "suitcase", "캐리어": "suitcase", "여행가방": "suitcase",
"hair dryer": "hair drier", "hair drier": "hair drier", "드라이기": "hair drier", "toaster": "toaster",
"토스터": "toaster"}
"토스터": "toaster", "보틀": "bottle", "물컵": "cup", "유리컵": "cup", "머그잔": "cup",
"글라스": "cup"}
# spoken word -> camera class; the classes are skills.GRASPS (tests/test_intents.py checks it): a pick of one the
# fingers can't take gets its reason (skills.refusal). Not here on purpose: umbrella / 우산 (weather words), 책 (책상)
_KO_WORD = {"공", "칼"} # one syllable inside other words (공항, 칼국수): only as a word of its own
@@ -632,8 +643,9 @@ INTENTS = [ # (action, pattern) checked in order on what the visitor said
("look_away", r"\b(?:look away|look somewhere else|look elsewhere|look the other way|stop (?:looking|staring)(?: at me)?|"
r"stop watching me|quit watching me|"
r"(?:don'?t|do not|please don'?t) (?:look|stare) at me|quit (?:staring|looking))\b|(?:쳐다|바라)보지 ?마|"
r"그만 ?(?:좀 ?)?(?:쳐다|바라)(?:봐|보세요|보십시오|봐요|봐 ?줘|봐 ?주세요)|"
r"(?:날|나를?|저를?|절)\s*(?:좀\s*)?그만\s*(?:봐|보세요|봐요|쳐다봐)|"
r"그만 ?(?:좀 ?)?(?:쳐다|바라)(?:봐|보세요|보십시오|보시게|봐라|봐요|봐 ?줘|봐 ?주세요)|"
r"(?:날|나를?|저를?|절)\s*(?:좀\s*)?그만\s*(?:봐|보세요|봐요|쳐다봐)|(?:^|[\s,—–-])그만\s*(?:좀\s*)?(?:봐|보세요|봐요|보시게|봐라|"
r"보십시오)\W*$|"
r"(?:날|나를?|저를?|절)\s*(?:좀\s*)?(?:보지|쳐다보지) ?마|다른 ?(?:데|곳|쪽)(?:을|를)? ?(?:좀 )?봐"),
("stop", r"\b(stop|halt|freeze|don'?t move)\b|멈춰|정지|그만 ?가|거기 ?서(?=[\s!.~,]*$)|스톱|움직이지 ?마|^\s*(서[\s,!.]*){2,}$"),
("waist", r"\b(?:turn|rotate|twist|swivel|swing|move|bring|point|face|put)\b[^.?!]{0,25}\b(?:your |the )?(?:waist|upper body|"
@@ -716,7 +728,7 @@ INTENTS = [ # (action, pattern) checked in order on what the visitor said
+ LET_GO),
("grip_close", r"\b(close (your |the )?(hand|gripper|fingers|claw)|close it|make a fist|clench (your )?(fist|hand)|grab (it|this)|grip (it|this)|"
r"hand closed?|squeeze (your )?(hand|fingers)( shut)?)\b|^\W*grip\W*$"
r"|손을? ?(?:꽉 |좀 )*(쥐|오므려|닫아)|\bclose\s*해\s*손|손가락\s*(?:을\s*)?(?:좀\s*|한번\s*|다\s*)*모아|주먹 ?(을 )?쥐|잡아(?!먹|당)|손 ?close|(그리퍼|집게)(를|을)? ?(좀 )?(닫아|오므려)"),
r"|손을? ?(?:꽉 |좀 )*(쥐|오므려|닫아)|\bclose\s*해\s*손|손가락\s*(?:을\s*)?(?:좀\s*|한번\s*|다\s*)*모아|주먹 ?(을 )?쥐|잡아(?!먹|당| ?보자| ?봐도| ?볼래)|손 ?close|(그리퍼|집게)(를|을)? ?(좀 )?(닫아|오므려)"),
("arm", r"\b(reach out(?! to (?!me\b))|stretch (out )?your (arm|hand)|put your (arm|hand) (out|forward)|hand forward|"
r"hold out your (arm|hand|gripper|claw|fingers)|extend your (arm|hand|gripper)|give me your hand|offer me your hand|"
r"give me (?:a|ur|you) hand(?!\s+(?:with|to|for|in|on|carrying|moving|lifting)\b)|"
@@ -731,13 +743,16 @@ INTENTS = [ # (action, pattern) checked in order on what the visitor said
r"\bgive hand\b|\bhand 이쪽|손을? ?(?:좀 |쭉 )+(?:내밀|뻗)"
r"|\bhand back\b(?=\s*(?:해|하|ㄱ))|기본 ?(?:pose|포즈|자세|위치)\s*(?:로|으로)|\bwithdraw (?:your |the )?(?:hand|arm)\b|"
r"\bretract (?:your |the )?(?:arm|hand)\b|\barm back to normal\b|\barm (?:back )?home\b|\bbring (?:the |your )?arm (?:home|back)\b|\bback to (?:your |the )?look pose\b|"
r"\byou can fold it\b|^\W*(?:이제\s*)?접어|손 ?(?:을 )?다시 넣어|^\W*(?:됐어\W*)?넣어\W*$|팔 ?(?:을 )?(?:원래대로|제자리로|다시 넣어|넣어)"),
r"\byou can fold it\b|^\W*(?:이제\s*)?접어|손 ?(?:을 )?(?:좀 |다시 |이제 )*넣(?:어|으)|"
r"손 ?(?:을 )?(?:좀 |쫌 |한번 |한 번 )*잡(?:—\s*잡)?아 ?(?:보자|봐도|볼래|봐야지|보고 ?싶)|\blet me (?:hold|shake|touch) your hand\b|"
r"(?:^|[\s,.])(?<!한테 )(?<!에게 )(?<!께 )손 ?(?:을 )?(?:(?:좀|이리|한번|한 번)\s*)*(?:줘|주세요|줄래요?|도|주쇼|주십시오|주시오|"
r"주시겠어요|주실래요|주라|주게|주이소|줘요)\W*$|^\W*(?:됐어\W*)?넣어\W*$|팔 ?(?:을 )?(?:원래대로|제자리로|다시 넣어|넣어)"),
("lift", LIFT_WORDS + r"|^\W*(?:go\s+|get\s+|even\s+)?"
r"(?:higher|taller|lower|shorter)(?:\s+(?:please|now|still))?\W*$|"
r"^\W*(?:조금 ?|좀 ?|약간 ?|살짝 ?)?더 ?(?:높이|높게|낮게|낮춰|올려|내려|높여)(?:\s*(?:줘|주세요|봐))?\W*$|"
r"키 ?(?:좀 ?)?(?:높여|낮춰|올려|내려|줄여|키워)"), # "higher", "더 높이", "키 높여": the lift
("weather", r"\bweather\b|\bforecast\b|\b(will it|is it going to) rain\b|(?<!your )(?<!cpu )(?<!gpu )(?<!operating )(?<!working )\btemperature\b(?!.*\b(your|you|cpu|gpu|battery|motor|body)\b)|날씨|비 ?(?:와|올|오나|온대)|기온"
r"|\b(?:going to|gonna) (?:rain|snow)\b|\b(cold|hot|warm|chilly) (outside|out)\b|\bumbrella\b(?=.*\?)|\b(?:need|bring|take)\b.*\bumbrella\b|우산(?=.*(?:\?|까|나요|니|냐))|밖에 ?(추|더)워"
r"|\b(?:going to|gonna) (?:rain|snow)\b|\b(cold|hot|warm|chilly) (outside|out)\b|\bumbrella\b(?=.*\?)|\b(?:need|bring|take)\b.*\bumbrella\b|우산(?!\S*\s*(?:어디|어딨|잃어|두고|놓고|빌려|사))(?=.*(?:\?|까|나요|니|냐))|밖에 ?(추|더)워"
r"|\bhow (hot|cold|warm) is it\b|\b(is it|will it be) (sunny|cloudy|windy|raining|snowing)\b|\bwill it snow\b"
r"|눈 ?(이 )?(와|올 ?까|오나|온대|오니)|(오늘|내일|밖|바깥)(은|에|이)? ?(덥|춥|더워|추워)"
r"|\b(coat|jacket) when i (leave|go out)\b|\bneed (a )?(jacket|coat)\b|\btyphoon\b|\b(foggy|humid|humidity)\b|\bis it windy\b"
@@ -758,7 +773,9 @@ INTENTS = [ # (action, pattern) checked in order on what the visitor said
r"monday|tuesday|wednesday|thursday|friday|saturday|sunday|outside)\b)"
r"|\b(?:today|tomorrow|tonight|weekend)\b.*\b(?:warm|warmer|cold|colder|hot|hotter|sunny|cloudy)\b"
r"|(?:오늘|내일|모레|주말|이번 ?주|다음 ?주|지금)\S*\s*(?:\S+\s*)?(?:맑|흐리|흐려|따뜻|추워|추울|더워|더울|쌀쌀|춥|덥)"
r"|\bhow'?s the weekend (?:looking|going to be)\b"),
r"|\bhow'?s the weekend (?:looking|going to be)\b"
r"|\b(?:should|do|must) (?:i|we) (?:bring|take|wear|need) (?:a |my )?(?:jacket|coat|umbrella)\b|\brain\b ?(?:와|올|오)"
r"|비 ?(?:옵니까|오노|오니|오냐|와유|오남)|우산\s*(?:챙겨야|가져가야|들고 가야|필요)|\bany (?:rain|snow)\b|\bumbrellas?\b.*\b(?:today|tomorrow|tonight)\b"),
("search", r"\b(news|latest|headlines?|who won|score of|price of|exchange rate|stock)\b|뉴스|환율|(?<![가-힣])주가|"
r"\bwhat'?s (?:happening|going on) in the world\b|\bwhat happened in the world\b|(?:최근|최신|요즘|새) ?소식|"
r"누가 이겼|경기 결과|\btop (?:stories|headlines)\b|요즘 ?경제|경제 ?(?:뉴스|상황|소식|어때|어떻)|"
@@ -779,7 +796,7 @@ INTENTS = [ # (action, pattern) checked in order on what the visitor said
r"코스피|kospi|코스닥|kosdaq|주식 ?시장|\bstock market\b|\bwhat'?s new (?:from|in|about)\b|"
r"\bwhat'?s happening in the\b|\banything (?:big|new) (?:happen|about)|\bwhat'?s everyone talking about\b|"
r"큰일 있었|다들 무슨 얘기|\bhow is the economy\b|"
r"\bhow (?:tall|high) is (?:the )?[a-z]+(?: world)? (?:tower|building|mountain|bridge)\b|\bhow many floors\b|"
r"\bhow (?:tall|high) is (?:the )?[a-z]+(?: world)? (?:tower|building|mountain|bridge)\b|\bhow many floors\b(?!.*\b(?:this|here|we're in)\b)|"
r"(?:타워|빌딩|건물|탑)\S*\s*(?:몇 ?미터|높이|얼마나 높)"), # "how many people live there?"
]
SING_ECHO = re.compile(r"^\W*(?:(?:오+|아+|와|어|우와|oh+|ah+|ooh|wow|really)\W+)?(?:a\s+)?(?:노래|음악|songs?|singing|music)"
@@ -1134,6 +1151,18 @@ ARM_BACK = re.compile( # the arm back to look (fold), said after a reach;
r"\b(?:your |the |ur )?arm (?:back|down|in)\b(?=\W*(?:$|now|please|해|thanks|lumi|,))|\b(?:let'?s see you|you) arm (?:down|back|in)\b|\bclose (?:your |the )?arm\b|"
r"손 ?(?:을 )?(?:좀 |이제 |다시 |빨리 |얼른 )*(?:내려|거둬|접어|넣어|치워)|팔 ?(?:을 )?(?:좀 |이제 |다시 |빨리 |얼른 )*(?:내려|거둬|접어|넣어|치워|원위치)", re.I)
ARM_BACK_NOT = re.compile(r"(?<!why )\b(?:don'?t|do not|never|no need to)\b|[가-힣]지 ?마(?:세요|요|라)?(?![가-힣])")
ARM_TALK = re.compile( # words about the arm / hand that order nothing now (A1): hearsay, ability, the past, someday,
# sarcasm, a word's meaning, a cheer; dialect negations ("흔들지 맙서", "흔들지 마유", "흔들지 마민수야")
r"\bif (?:you|u) could\b.*\b(?:someday|some ?time|one day|in the future|later|next time)\b|\bsomeday\b|\bin a (?:few|couple of) "
r"(?:minutes|mins|seconds|hours)\b|\bi (?:heard|hear|read|was told|bet)\b|\b(?:are|r) (?:you|u) (?:even |really |actually )?able to\b|"
r"\bwere (?:you|u) (?:built|made|designed|programmed|taught)\b|\bdo (?:you|u) (?:even )?know how to\b|\bshould (?:we|i) ask\b|"
r"\b(?:did|have) (?:you|u)\b.*\b(?:earlier|before|yesterday|last time|ever)\b|\bearlier\b|\b(?:it|he|she|lumi|the robot) "
r"(?:refused|tried|failed|forgot|wanted|used) to\b|\bfly to the moon\b|\bwhen pigs fly\b|\byeah,? right\b|\bdid the wa\w*\b|"
r"\bpolicy\b|\bin (?:english|korean)\b|\bwhat does .* mean\b|"
r"퍽이나|리가 (?:있|없)|수 ?있으면 ?(?:좋겠|대박|최고|멋|재밌)|만약에?|줄은 ?알|는 ?거 ?해도 ?(?:돼|되)|"
r"는 ?거 ?(?:진짜 |너무 |정말 |완전 )?(?:신기|멋있|멋지|귀엽|웃기|재밌|재미있)|기도 ?해\s*\?|수 ?있겠다|"
r"파이팅|화이팅|\bfighting\b|영어로|한국어로|무슨 ?뜻|뜻이 ?뭐|얘기 ?들었|들어 ?봤|본 ?적|해 ?봤어\s*\?|봤어\s*\?|"
r"[가-힣]지 ?(?:맙|마유|마소|마이소|마셈|마시오|마십시오|말라|말랑께|말어)|[가-힣]지 ?마(?=[가-힣]+(?:야|아)(?:\s|\W|$))", re.I)
HELD_BACK = re.compile( # the whole sentence asks for no motion now (A2): it starts with a no, a later time, or is taken back
@@ -1169,7 +1198,7 @@ def intent(text, markers=()):
re.sub(_LEAD, "", CALLING.sub("", t), flags=re.I)) or LATER.search(CALLING.sub("", t)) # "Lumi, is it
# hard to ...?", "Lumi Lumi, are you still following me?"
visitor = re.search(r"^\W*(?:can|may|could|should|shall) (?:i|we)\b", CALLING.sub("", t)) # "can I come closer?"
if ARM_BACK.search(t) and not (held or asks or visitor or ARM_BACK_NOT.search(t)):
if ARM_BACK.search(t) and not (held or asks or visitor or ARM_BACK_NOT.search(t) or ARM_TALK.search(t)):
return ("arm", "fold") # "take your hand back", "back to look position": never the base
for action, pat in INTENTS:
m = re.search(pat, t, re.I)
@@ -1205,6 +1234,8 @@ def intent(text, markers=()):
return ("waist", f"{side} {n}" if n else side)
if action == "look_away":
return None if asks or "?" in t else ("look", "away") # "don't look at me", "쳐다보지 마"
if action in ("arm", "grip_open", "grip_close", "wave") and ARM_TALK.search(t):
return None # "I heard you can wave", "주먹 쥐고 파이팅!" (A1)
if action != "quiet" and re.search(r"(?<!why )\b(don'?t|do not|never|no need to)\b|[가-힣]지 ?마(?:세요|요|라)?(?![가-힣])|"
r"필요 ?(?:없|는 없)", t) and action != "stop":
return None # "don't go to p1", "손 펴지 마": not an order
@@ -1250,6 +1281,8 @@ def intent(text, markers=()):
if re.search(r"\b(?:do|did|would|you|i|we) (?:like|love|enjoy|prefer|hate)\b|\bfavou?rite\b|좋아하|좋아해|싫어|"
r"\bmeans?\b|\bmeaning\b|뜻", t):
return None # "do you like rainy weather?": talk, no lookup
if re.search(r"\bin here\b|\bthis room\b|\binside\b|실내|방 안|안에(?:서)?\s*(?:더워|추워|덥|춥)", t):
return None # "is it hot in here?": the room, not the weather
place = re.search(r"\bin ([A-Za-z][A-Za-z ]+?)(\?|$|\.| today| tomorrow| right now| now| this)", text)
if place and web.asked_day("in " + place.group(1)) is None: # "in three days" is a day, no place
return ("weather", place.group(1).strip())
@@ -1340,7 +1373,7 @@ def intent(text, markers=()):
if n == "?" or not driving.MOVE_MIN_M <= n <= MOVE_MAX_M:
return None
return ("move", f"{driving.direction(driving.clean(t))} {n:g}")
if action == "make_way" and re.search(r"\bover there\b|\bthat (?:spot|place|way)\b|\bwhere i\b", t):
if action == "make_way" and re.search(r"\bover (?:there|dare|dere|thar)\b|\bthat (?:spot|place|way)\b|\bwhere i\b", t):
return None # "move over there": the spot pointed at (pointing.py), no back-off
if action == "make_way":
return ("move", "back 1") # owner: a checked 1 m back-off (lumi.move_by)
@@ -1368,7 +1401,7 @@ def intent(text, markers=()):
return None # asked about / refused with the limit (driving.read)
return ("move", f"{d} {n:g}")
if action == "arm":
return ("arm", "fold" if re.search(r"fold|tuck|down|away|back|home|look pose|\bin\b|withdraw|retract|normal|접|내려|거둬|넣어|"
return ("arm", "fold" if re.search(r"fold|tuck|down|away|back|home|look pose|\bin\b|withdraw|retract|normal|접|내려|거둬|넣어|넣으|"
r"원래|제자리|치워|기본", t)
else "reach")
if action == "grip_close" and re.search(rf"(?<![a-z])(?:{_OBJ})s?(?![a-z])", t):
@@ -1396,12 +1429,13 @@ def intent(text, markers=()):
# ---------- 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"아니(?:야|다|요|에요|지)?|아니 아니|정정|그게 아니라|그거 말고|미안(?:해요?)?|죄송해요|죄송합니다|잘못 말했(?:다|어|어요|네요?|습니다)|"
r"아니(?:야|다|요|에요|지)?|아니 아니|정정|그게 아니라|그거 말고|미안(?:해요?)?|(?<!면 )죄송해요|(?<!면 )죄송합니다|잘못 말했(?:다|어|어요|네요?|습니다)|"
rf"wait(?=\W+(?:(?:the|a|an|that|this)\s+)?(?:(?:{_COL})\s+)?(?:{_OBJ})s?\b)") # "the white cup, wait, the apple"
_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'가-힣])(?!(?<=no)\s+(?:wave|waving|follow|following|turn|turning|move|moving|look|"
rf"looking|going|coming|lift|reach|touch|pick|music|photos?)\b)"
rf"(?!(?<=sorry)\s+(?:if|for|to|about|that|but|i|i'm|again)\b)" # "..., sorry if that's rude": an apology
rf"(?!\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|아니|잘못 말했")
@@ -1462,6 +1496,7 @@ def self_correct(text, markers=()):
"" 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
text = wording.polite(text) # "wave, if you don't mind" -> "wave" on every path
if re.search(r"\b(?:say|tell|announce)\b|말해|(?<!그거 )(?<!이거 )(?<!그걸 )(?<!이걸 )전해|[\"“”]", text, re.I) or \
re.search(r"\b(?:stop|halt|freeze|don'?t move)\b|멈춰|정지|그만(?!두|둬)|스톱|움직이지 ?마|거기 ?서", text, re.I):
return text # a message to say may hold any words; a stop always wins
@@ -1578,7 +1613,8 @@ FILLER_IN = re.compile(r"(?:,\s*)?(?<![\w'])(?:u+h+m*|u+m+|e+r+m*|hmm+)(?![\w'])
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 = re.sub(r" {2,}", " ", FILLER_IN.sub(" ", wording.now_not_later(t))).strip() # "now, not later": no later time
t = re.sub(r" {2,}", " ", FILLER_IN.sub(" ", wording.polite(wording.now_not_later(t)))).strip() # "now, not later": no
# later time; "wave, if you don't mind": no condition
return re.sub(r"\b(the|a|to) \1\b", r"\1", t)
@@ -1982,6 +2018,18 @@ REFUSE_FLOOR = ("I can't reach the floor with my arm, only things on a table.",
IDIOM = re.compile(r"\bput (?:\w+ ){0,3}(?:on (?:my|the|your|our|their) (?:tab|list|bill|account|calendar|schedule|agenda|"
r"to-?do list|menu)|on hold)\b|\blet'?s put\b|"
r"\bbring it on\b|^\W*hold it\W*$|\bgive me (?:five|a high five|some skin)\b|\bhigh five\b", re.I) # "put it on my tab", "hold it!" (wait): no hand
NOT_A_THING = re.compile( # "give me the top stories", "give me the short version", "힌트 좀 줘": words, not a thing in the hand
r"\b(?:give|hand|pass|bring|gimme|tell|send|show)\s+(?:me|us)?\s*(?:(?:the|a|an|some|your|any|more|quick|short|brief|"
r"latest|top|full|long|real|honest|little|few|good|best|main)\s+)*(?:\w+\s+)?(?:news|stories|story|headlines?|version|summary|"
r"rundown|overview|update|updates|details?|info|information|answer|answers|example|examples|reason|reasons|idea|ideas|tip|tips|"
r"hint|hints|advice|recommendations?|suggestions?|list|number|numbers|name|names|address|directions|time|minute|second|moment|"
r"break|chance|call|ride|hug|smile|kiss|quote|price|forecast|weather|facts?|jokes?|words?|review|report|brief(?:ing)?|recap|"
r"explanation|definition|translation|lowdown|scoop|gist|highlights|scores?|results?|lyrics|tour|demo|presentation|intro(?:duction)?|"
r"feedback|opinions?|thoughts|status|percentage|guess|rating|estimate|ideas?|options?|choices?|minutes|seconds|space|room|"
r"reply|response|clue|clues|sign|signal|wave|nod|look|try|go|shot|rest|lift|push)\b|"
r"(?:뉴스|소식|정보|힌트|팁|설명|대답|답변|답|요약|시간|기회|이름|번호|전화번호|주소|조언|추천|의견|피드백|예시|이유|"
r"아이디어|답장|연락|칭찬|박수|사인|신호|용기|자유|휴식|여유)\s*(?:을|를|좀|도|만)?\s*(?:좀\s*)?(?:더\s*)?"
r"(?:줘|주세요|줘요|주라|줄래|주실래요|주십시오|주시겠어요|주쇼|주이소)", re.I)
_POL = r"(?:\W+(?:please|pls|plz|now|lumi|robot|thanks|thank you|okay|ok|then|already|quick|빨리|얼른|어서|좀|제발|루미야?))*"
GIVE_LOOSE = re.compile( # with something in the hand, the whole sentence asks for it: give it to the speaker
rf"\W*(?:(?:you|please|now|lumi|robot|okay|ok|hey|so|just|me)\W+)*(?:gimme|give|hand|pass)(?: (?:it|that|this|that one|"
@@ -2025,7 +2073,7 @@ GIVE_HELD_NOT = re.compile( # a cancel, a past, a place word, "not yet": never
r"\band\b(?! (?:give|hand|pass|now)\b)|\b(?:then|after that|also)\b|[가-힣](?<![들쥐이말])고\s|그리고|다음에|가서", re.I) # one part of several: the chain's
_OTHER_CLAUSE = re.compile(r"[,.;]\s*(?:and |because |since |cause )?(?:he|she|they)(?:'s|'re| is| are| was| will|'ll| has| "
r"needs?| wants?| goes| going)\b.*$|[,.]\s*(?:그분|그 ?사람|저 ?분|이 ?분|걔|그 ?친구|그녀)\S*\s.*$", re.I)
_KO_VERB_BEFORE = re.compile(r"(?:아|어|여|해|와|봐|워|켜|꺼|려|펴|쳐|져|겨|셔|혀|며|녀|벼|떠|써)$") # "뻗어 줘", "가져와 줘", "인사 해 줘": another verb's request
_KO_VERB_BEFORE = re.compile(r"(?:아|어|여|해|와|봐|워|켜|꺼|려|펴|쳐|져|겨|셔|혀|며|녀|벼|떠|써|러|라)$") # "뻗어 줘", "가져와 줘", "인사 해 줘": another verb's request
_KO_NOT_VERB = {"이리", "여기", "거기", "저기", "좀", "나", "저", "날", "빨리", "어서", "얼른"}
@@ -2150,8 +2198,9 @@ def held_give(text, markers=()):
condition, a cancel, a past, words to someone else, a trip to a marker ("bring it to James at booth A")."""
if re.search(r"^\W*(?:(?:okay|ok|alright|네|그럼|자)\W+)*(?:제가|내가)\s*(?:받을|가져갈)(?:게|께)요?\W*$", CALLING.sub("", text or "")):
return True # "제가 가져갈게요": I'll take it (from the hand)
if not text or re.search(r'["“”]', text) or to_someone_else(re.sub(r"^(\W*루미야)(?=\S)", r"\1 ", text)):
return False # "야 그 컵 나 줘 봐": said to a friend (the call is cut below)
if not text or re.search(r'["“”]', text) or to_someone_else(re.sub(r"^(\W*루미야)(?=\S)", r"\1 ", text)) or \
NOT_A_THING.search(text):
return False # "야 그 컵 나 줘 봐": said to a friend; "give me the news"
text = hand_text(text)
if not text or not_an_order(text):
return False
@@ -2180,8 +2229,8 @@ def hand_request(text, holding, b=None, markers=(), whole=True):
hand while holding; None for anything else (a pick from the table, a mission of several steps, a question).
holding: something is in the hand now. "give me the cup" with the hand empty is a pick and give (a mission).
whole: the words are a whole command (not one clause of a mission): several steps in it are the mission reader's."""
if re.search(r'["“”]', text or ""):
return None # '"give it to me" is a nice English phrase'
if re.search(r'["“”]', text or "") or NOT_A_THING.search(text or ""):
return None # '"give it to me" is a nice English phrase', "give me the news"
text = hand_text(instead_of(text))
t = CALLING.sub("", _norm(text, markers).strip()) # "루미야, 이리 줘", "혹시 저 줘요", "um, put it down"
if holding and re.search(r"\bi mean\b|\S\W*\bsorry\b", t):
@@ -2483,8 +2532,56 @@ ABOUT_ANSWER = re.compile(r"^\W*(?:(?:but|and|so|then|oh|wait|hmm|okay|come on|
r"how come|how (?:do|did|can) you (?:know|tell)(?: that| it)?|(?:are )?you sure(?: about (?:that|it|this))?|sure about that|really|for real|fr|seriously|no way|"
r"what do you mean|says who|(?:you'?re |you are )?(?:lying|kidding)(?: me)?|(?:no|don'?t) lie|거짓말(?:하지 ?마\S*|이지\S*|이야\S*)?|설마\S*|"
r"왜(?:요|죠)?|왜 안 ?(?:돼|되)\S*|진짜(?:요|야|로)?|정말(?:요|이야)?|레알|실화(?:야|예요|냐)?|참말\S*|"
r"확실(?:해|한가|하)\S*|어떻게 알아\S*|그게 무슨 (?:뜻|말)\S*)\W*$", re.I)
r"확실(?:해|한가|하)\S*|어떻게 알아\S*|그게 무슨 (?:뜻|말)\S*|"
r"(?:are )?u sure|(?:are )?you serious|serious|is (?:that|it) (?:right|true|so)|no kidding|you'?re joking|"
r"(?:그게 |그거 |그 말 )?맞(?:아|아요|나|나요|습니까|는 거야|는 거예요|지)|진짜(?:예요|입니까|이가|가|냐)|"
r"정말(?:이에요|입니까|이가|이냐)|참(?:말|말이가|말이야|말이에요|말입니까)|말도 안 ?(?:돼|되)\S*|"
r"그럴 ?리가\S*|농담\S*|ㄹㅇ|에이 ?설마\S*|왜 그(?:래|런|렇)\S*|에이)\W*$", re.I)
# asks about the answer just given: its reason, its source, or to confirm it
_CORE_LEAD = re.compile( # words before what a follow-up asks: fillers, calling Lumi, "by the way", "wait"
r"^\W*(?:(?:hey|hi|yo|okay|ok|so|um+|uh+|ah+|oh+|hmm+|alright|well|now|and|but|then|wait|look|listen|right|hold on|"
r"quick one|quick question|one more thing|by the way|btw|lumi|loomy|loomi|rumi|robot|buddy|yeah|"
r"음+|어+|아+|흠+|에|자|참|저기요?|잠깐만?|잠깡|근데|그런데|그럼|그러면|그리고|그래서|아 맞다|맞다|그건 그렇고|"
r"궁금한 (?:게|건데|거|것)|있잖아요?|여보게|이보게|보이소|아야|거시기|어이|야|헐|대박|아니|"
r"(?:루미|로봇|누미|류미)(?:야|아|씨|님|양반|선배님|프로|군|양)?(?:\s+(?:씨|님|양반|선배님|프로))?)(?![\w가-힣'])[\s,.!~:]*)+",
re.I)
_CUT_WORD = re.compile(r"[^\s,]*[—–]\s*") # whisper's broken-off word: "참— 참말이가", "루— 루미 양반"
def core(text):
"""What a short follow-up asks, without the words around it: "음 루미아, 정말요?" -> "정말요?", "아 맞다, 여러분
보세요,어디 있어?" -> "어디 있어?" (the last of several short parts), "Jason, look, Lumi seriously?" -> "seriously?".
Only for reading what kind of follow-up it is; the model gets the words as said."""
t = _CUT_WORD.sub("", text or "").strip().rstrip(".~ ").strip()
t = _CORE_LEAD.sub("", t).strip() or t
last = _CORE_LEAD.sub("", re.split(r"[,:]\s*", t)[-1]).strip()
return last if last and t != last and len(last.split()) <= FOLLOW_UP_WORDS + 1 and \
(ABOUT_ANSWER.match(last) or SHORT_Q.search(last)) else t
THANKS_ONLY = re.compile(r"^\W*(?:thanks?(?: (?:a lot|so much|very much))?|thank you(?: (?:so much|very much|a lot))?|thx|"
r"cheers|ty|고마워(?:요)?|고맙(?:습니다|다|데이|구먼)|감사(?:합니다|해요|해|하다)|땡큐(?: 베리 ?머치)?)"
r"(?:\W+(?:lumi|robot|루미야?|로봇아?))?\W*$", re.I) # thanks and nothing else
BYE_WORDS = re.compile(r"\b(?:bye|goodbye|see you|gotta go|i (?:have|need) to go)\b|안녕(?!하)|갈게|가 ?볼게|가야|잘 ?있어|"
r"수고하", re.I) # with a question after it: one more question before leaving
def topic_turn(history):
"""The last turn that said something of its own: a back-channel ("헐 대박", "Oh, I see.") and Lumi's short reply
to it are passed over, so "really?" / "where is it?" after them asks about the answer before."""
for q, a in reversed(history[-4:]):
if about_answer(q) or not (is_backchannel(q) or UNDERSTOOD.search(q) and len(q.split()) <= 4):
return q, a
return history[-1]
def about_answer(text):
"""The words ask about the answer just given (ABOUT_ANSWER), also with words around them."""
c = core(text)
w = c.split()[-1] if c.split() else ""
return bool(ABOUT_ANSWER.match(text or "") or ABOUT_ANSWER.match(c) or len(c.split()) <= 3 and
(ABOUT_ANSWER.match(w) or re.search(r"(?:정말|진짜|참말|설마)(?:요|이야|이에요|이가|로)?\W*$", w)))
# "투자자 앞에서 진짜?", whisper's "어정말요?"
LOOKUP_BEFORE_CHARS = 1500 # chars of the last lookup's results given again with a follow-up ("how old is she?")
FOLLOW_UP_WORDS = 5 # "why did Samsung stock fall today?" is a new question, "tell me more about it" is not
AND_ALSO = re.compile(r"^\s*(and|what about|how about|also|그럼|그리고)\b", re.I) # "and the yen?": a follow-up
@@ -2492,7 +2589,9 @@ WEATHER_ASKED = " (the weather)" # lumi.look_up adds it to a weather question;
WEATHER_PLACE = re.compile(r"^\W*(?i:(?:and|so|then|ok(?:ay)?)\W+)*(?i:(?:what|how)\s+about\s+)?(?i:in\s+)?"
r"(?!(?:Why|What|When|Where|Who|Whose|How|Which|Is|Are|Was|Will|Can|Could|Do|Does|Did|Should|Lumi)\b)(?P<place>[A-Z][\w'-]*(?:\s+[A-Z][\w'-]*)*)[\s?.!]*$") # "what about Busan?" after the weather
KO_WEATHER_PLACE = re.compile(r"^\W*(?:(?:그럼|그러면|그리고|아니)\W*)?(?P<place>[가-힣]+?)(?:시|도)?(?:\s*날씨)?"
r"(?:은|는|도|에는|에서는|이요|요)*[\s?.!~]*$") # "그럼 부산은?": a place of web.KO_PLACES only
r"(?:은|는|도|에는|에서는|이요|요)*(?:\s*(?:날씨는?\s*)?(?:어때요?|어때유|어떻습니까|어떠세요|어떠신가요|어떻노|어떻나요?|"
r"어뗘|어떠냐|어떻니|어떤가요|어떻게 ?(?:돼요?|됩니까|되나요|되노)|우째 ?되노))?[\s?.!~]*$")
# "그럼 부산은?", "부산은 어떻노?": a place of web.KO_PLACES only
REPAIR = re.compile(r"^\W*(?:(?:no|nope|sorry|oh)\W+)*i\s+mean[t]?\b|^\W*(?:아니|아뇨|아니요)[\s,]|말고\b|"
r"말(?:이야|이에요|이요)\W*$", re.I) # "no, I meant North Korea", "아니 서울 말이야"
LEAD = re.compile(r"^\s*(?:(?:and|what about|how about|also|no|nope|sorry|oh|그럼|그리고|아니|아뇨|아니요)\b[\s,]*)*"
@@ -2515,9 +2614,16 @@ REACTION = re.compile(r"^\W*(?:(?:wow|oh|really|huh|whoa)\W+)*(?:i (?:didn'?t|di
re.I) # a reaction to what was found, not a new question
NOW_Q = re.compile(r"\bwhat time is it\b|\bwhat'?s the time\b|\bwhat(?:'s| is) (?:the date|today)\b|지금 몇 ?시|오늘 며칠",
re.I) # asked of the clock, not of the lookup before
WEATHER_WORDS = re.compile(r"\b(?:and|so|then|too|also|as well|ok(?:ay)?|what|how|about|is|it|the|weather|like|for|on|in|at|will|be|going|"
WEATHER_WORDS = re.compile(r"\b(?:how's|what's|looking|look|and|so|then|too|also|as well|ok(?:ay)?|what|how|about|is|it|the|weather|like|for|on|in|at|will|be|going|"
r"to|forecast|rain|there|that|then|please|sorry|no|i|mean|meant)\b|그럼|그러면|그리고|날씨|어때요|어때|어떤가요|어떨까요|어떻게|돼요|"
r"비|와요|올까요|오나요|알려|줘|주세요", re.I) # the rest of "and the weather on Friday then?"
r"비|와요|올까요|오나요|알려|줘|주세요|어떻습니까|어떠세요|어떠신가요|어떻노|어떻나요|어떻나|어뗘|어떠냐|어떻니|"
r"어때유|우째|되노|됩니까|되나요|될까요|돼|어떤가요|어떻게|좀", re.I) # the rest of "and the weather on Friday then?"
WEATHER_ONLY = re.compile(r"^\W*(?:(?:and|so|then|그럼|그러면)\W+)?(?:is it|will it|is it going to|does it|do i need|should i (?:bring|take)|"
r"any|how)\b.{0,25}\b(?:rain\w*|snow\w*|windy|umbrella|jacket|coat)\b[\w\s]*\W*$|"
r"^\W*(?:그럼\s*)?(?:비|눈|소나기|미세먼지|황사|바람)(?:은|는|도|가|이)?\s*(?:와|와요|오나요?|올까요?|옵니까|오니|오노|와유|"
r"어때요?|어떻습니까|많이 불어요?|불어요?|심해요?|나빠요?|있어요?)?[\s?.!~요]*$|"
r"^\W*우산\s*(?:챙겨야|가져가야|필요)", re.I) # a weather question that names no day or place;
# "is it cold?" / "추워요?" is answered from the weather just said (the LLM)
PARTICLES = re.compile(r"^[은는도요의에이가서엔]+$") # "월요일은요" less the day
CHECKING = re.compile(r"^\W*(?:let me (?:check|see|look)|one moment|just a moment|확인해 ?볼게요|잠시만요?)\W*$", re.I)
# lumi says it before the lookup: never again inside the answer
@@ -2526,8 +2632,10 @@ CHECKING = re.compile(r"^\W*(?:let me (?:check|see|look)|one moment|just a momen
def weather_follow(text):
"""A short weather follow-up that names a day and maybe a place ("내일은요?", "and Friday?", "what about Busan
tomorrow?", "다음 주 월요일 어때요?"): the place ("" = the one asked before), else None."""
if len(text.split()) > 8 or web.asked_day(text) is None:
if len(text.split()) > 8:
return None
if web.asked_day(text) is None: # "비는 와?", "is it cold?" right after the weather: the same
return "" if WEATHER_ONLY.search(text) and not re.search(r"(?<=\s)(?!I\b)[A-Z]", text) else None # day and place
rest = web.DAY_PHRASE.sub(" ", text)
ko = next((k for k in sorted(web.KO_PLACES, key=len, reverse=True) if k in rest), None)
rest = WEATHER_WORDS.sub(" ", rest.replace(ko, " ") if ko else rest)
@@ -2670,6 +2778,9 @@ class Brain:
for q, a in self.window():
messages += [{"role": "user", "content": q}, {"role": "assistant", "content": a}]
follow = _follow_examples(text, self.history) # with them, fewer plain examples (a shorter prompt)
if follow and not LUMI_TOPIC.search("{} {}".format(core(topic_turn(self.history)[0]), topic_turn(self.history)[1])):
notes = "(none needed: the answer is in this talk)" # "when was it built?" after the Eiffel Tower: notes
# on Lumi ("When was I built? 2 years") only misled
messages.append({"role": "user", "content": f"Reference notes:\n{notes}\n\n{_examples(about, k=2 if follow else None, on_task=bool(now) and 'not doing any task' not in now)}"
f"{follow}"
f"Now it is {now_line()}.\n\n" + memory.turn_lines(self, text) +
@@ -2701,7 +2812,7 @@ class Brain:
if header is None: # the model skipped the ACTION line
header, buf = self._after({"action": "none", "target": ""}, text), first + " " + buf
if header["action"] == "unclear" and not retried and \
(has_meaning(text) or self.history and ABOUT_ANSWER.match(text)) and \
(has_meaning(text) or self.history and about_answer(text)) and \
not other_latin_language(text): # 26b called short or broken but clear words unclear ("fr?")
stream.close()
retried, header, buf, full = True, None, "", ""
@@ -2785,12 +2896,21 @@ class Brain:
if last and part: # "What about your cameras?" / "카메라는요?" after "can I wipe you?"
return (f"(The visitor's question \"{self.history[-1][0]}\" asked again, now about {part.group(1)}: answer "
f"that question for it, not other facts about it.)\n")
if last and ABOUT_ANSWER.match(text): # "why?", "how do you know?", "진짜?" after a refusal too
if last: # past a back-channel ("헐 대박") to the answer before it
last = " ".join(ln for ln in topic_turn(self.history)[1].splitlines() if not re.match(r"\s*\**ACTION", ln)).strip()
c = core(text) # "루미 양반, 언제야?" asks "언제야?", not about Lumi
if last and (THANKS_ONLY.match(c) or THANKS_ONLY.match(re.split(r"[,:]\s*", c)[-1])) and \
not self._last_said().rstrip().endswith("?"): # "궁금한 게, 고마워요~", "Then oh thank you."
return "(Only thanks for your answer, not a goodbye: say you're welcome in a few words; no goodbye, no question.)\n"
if BYE_WORDS.search(text) and SHORT_Q.search(re.split(r"(?<=[,.!~])\s*", text.strip())[-1]):
return "(A goodbye with one more question: answer the question; no goodbye in your words yet.)\n"
if last and about_answer(text): # "why?", "how do you know?", "진짜?" after a refusal too
return (f"(This asks about your answer \"{last[:FRAGMENT_CHARS * 2]}\": its reason or how you know it; "
f"a \"really?\" / \"sure?\" is answered \"Yes,\" with that answer's own facts said again (its numbers, names or the "
f"things it listed, never just \"that\" / \"those\"), no new fact.)\n")
if not last or len(text.split()) > FRAGMENT_WORDS or not SHORT_Q.search(text) or is_backchannel(text) \
or ABOUT_YOU.search(text) or OWN_TOPIC.search(text):
pronoun = NAMED_BEFORE.search(c) or REFERS_BACK.search(c) # "when was it built?", "how old are they?"
if not last or len(c.split()) > (FOLLOW_UP_WORDS + 2 if pronoun else FRAGMENT_WORDS) or not SHORT_Q.search(c) \
or is_backchannel(c) or ABOUT_YOU.search(c) or (OWN_TOPIC.search(c) or OWN_SUBJECT.search(c)) and not pronoun:
return ""
return f"(This follows your answer \"{SENTENCE_END.split(last)[0][:FRAGMENT_CHARS]}\": it asks about that.)\n"
@@ -2809,7 +2929,7 @@ class Brain:
if header.get("held", ("none",))[0] != "none" and (self._redo(text) or DO_IT.match(text) or confirm_answer(text) == "yes" and
self._last_said().rstrip().endswith("?")):
return {"action": header["held"][0], "target": header["held"][1]} # "yes" to "Shall I go there?"
if header["action"] == "quiet" and ABOUT_ANSWER.match(text):
if header["action"] == "quiet" and about_answer(text):
return {"action": "none", "target": ""} # "에이, 거짓말하지 마" doubts the answer, not "be quiet"
redo = self._redo(text)
if redo and header["action"] == "none": # "do it again" after a wave answered "Okay!" with none
@@ -2972,6 +3092,9 @@ class Brain:
f"in your own words: {' / '.join(ideas)}. "
+ (f"Said to other visitors lately, so do not use these again: {avoid}. "
if avoid else "") +
"It must say goodbye in plain words (bye, see you, take care / "
"안녕히 가세요, 조심히 가세요, 다음에 또 만나요, 또 오세요), not only "
"thanks or 'enjoy'. "
"Do not begin with 'You're welcome' or '천만에요'; never say 'Have a "
"great day', 'It was nice talking with you' or 'It was my pleasure'; "
"in Korean polite (-요)."})
@@ -3129,7 +3252,9 @@ class Brain:
if action == "stop" and "?" in text:
action = "none" # "how do I stop you?": a question about stopping
if action == "end" and "?" in re.split(r"(?<=[.!?~])\s+", text.strip())[-1]:
action = "none" # "thanks, and where is p3?": a question is no goodbye; the
action = model if model in ("search", "weather") else "none" # "갈게요, 근데 후지산은 얼마나 높아?": its
target = target if action != "none" else "" # lookup stays (else "search 후지산 높이" was said aloud)
# "thanks, and where is p3?": a question is no goodbye; the
# model reads "okay" / "됐어요" with the talk before (owner)
out = {"action": action, "target": target or ""}
if held and action == "none":