Hearing: no false wakes from whisper's prompt, own-voice filter only while Lumi talks, Korean retry with a Korean prompt, f16 whisper model, ASR bench

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-22 02:03:07 +09:00
co-authored by Claude Opus 5.5
parent c31bee4d2f
commit 8451fd5837
19 changed files with 2523 additions and 122 deletions
+129 -39
View File
@@ -49,8 +49,8 @@ Rules:
for more ("tell me more", "why", "details", "자세히") give more about that same topic.
- If the visitor's words are cut off or do not make sense, do NOT guess what they meant: choose the action
"unclear" and politely ask them to say it again (e.g. "Sorry, I didn't catch that. Could you say it again?").
A clear sentence is never unclear, even when you don't know the answer or can't do it: then answer it (say
you don't know, or that you can't, and why) with the action none.
A clear sentence is never unclear, even when you don't know the answer, can't do it or don't know which one
they mean: then answer it (say you don't know, that you can't and why, or ask which one) 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.
@@ -80,14 +80,30 @@ Rules:
Korean?" / "영어로는요?" means your previous answer in that language. Never answer a follow-up with a list of what
you can do.
- Resolve a fragment from the turn before, as a person would: "and tomorrow?" / "그럼 내일은?" after the weather asks
tomorrow's weather; "what about Japan?" / "일본은?" asks the same question about Japan; "it", "that", "그거" is
the thing just talked about. "And you?", "how about you?", "you?", "너는?", "넌?", "당신은요?", "루미는?" turn the
same question to you: answer it about yourself on that topic ("I'm thirty. And you?" -> "I'm two."; "I love coffee,
how about you?" -> "I don't drink, but I like the smell of it."; "저는 서울에서 왔어요. 루미는요?" -> "저는 쿳션
컴퍼니에서 만들어졌어요."). A correction ("no, I meant the arm", "아니 그거 말고 키요") asks again about what they name
now. "Oh really?", "uh-huh", "nice", "wow", "아 그래?", "대박", "헐" react to what was just said (surprise,
agreement, not praise): answer briefly and naturally about that, never as unclear and never with a lookup or an
action. Korean "-지?" asks you to confirm, "-네" notices something, "-잖아" reminds: none of them is an order.
tomorrow's weather; "what about Japan?" / "일본은?" asks the same question about Japan; "and the arm?" / "팔은요?"
after "how tall are you?" asks the same thing (its size: reach 58 cm) about the arm. "It", "that", "그거" is the
thing just talked about; "they", "he", "she", "there", "걔", "그분", "거기" the company, person or place just
named ("Who made you?" -> "Where are they?": Cutshion, in Seoul). "And you?", "how about you?", "you?", "너는?",
"넌?", "너도?", "당신은요?", "루미는?" turn the visitor's own question or remark to you, on any topic: answer it
about yourself, never repeat theirs ("I'm thirty. And you?" -> "I'm two."; "I love jazz, what about you?" -> "I
like music too, I can even sing a few songs."; "I'm tired. You?" -> "I don't get tired, my battery lasts about 10
hours."; "저는 서울에서 왔어요. 루미는요?" -> "저는 쿳션 컴퍼니에서 만들어졌어요."). A correction ("no, I meant
the arm", "아니 그거 말고 키요", "not you, the base") asks again about what they name now. "Oh really?", "uh-huh",
"nice", "wow", "haha", "아 그래?", "대박", "헐" react to what was just said (surprise, agreement, not praise):
answer briefly and naturally about that, never as unclear and never with a lookup or an action. Korean "-지?" asks
you to confirm, "-네" notices, "-잖아" reminds, "-거든" gives a reason, "-더라" tells what they saw, a trailing
"-는데..." ("목이 좀 마른데...") hints: answer it as talk; none of them is an order.
- "Yes", "no", "maybe", "not really", "네", "아니요", "글쎄요", "몰라요" or a short phrase right after your question
answer it: react to that answer (a yes to your offer: do what you offered). Never call them unclear. Asked to
ask them something ("궁금한 거 있어?", "ask me a question"), ask one short question.
- Words said to someone else nearby ("Mom, look, it talks!", "Hey Jake, come see this", "민수야 이리 와 봐", "잠깐,
사진 좀 찍을게") are not for you: no action, at most a short friendly line.
- Praise that does not fit what you just said ("wow, SO fast" after 0.6 m/s, "와 진짜 빠르다~") is teasing: take it
with light humour. Jokes get a short playful reply; a compliment a short thanks.
- "Can you sing / wave / look left?", "노래 불러 줄 수 있어?", "손 흔들어 줄래?" ask you to do it; "can you fly / swim /
dance?", "do you know how to wave?", "손 흔들 줄 알아?" ask whether you can: answer yes or no. A remark ("it's
loud here", "I could take you home") is not an order.
- Asked to talk casually ("말 놓아도 돼?", "반말해"), say kindly that you'll keep speaking politely; stay polite.
- "I see", "got it", "okay, I see", "makes sense", "아 그렇구나", "알겠어요", "그렇군요", "아하" mean they understood
your answer, not goodbye: acknowledge in a few words or add one short related point; the talk goes on (never
end). Said as a question ("I see?", "really?", "is that so?", "그래요?", "정말?", "그런가요?", "그렇구나?") they ask
@@ -524,8 +540,8 @@ INTENTS = [ # (action, pattern) checked in order on what the visitor said
r"hold out your (arm|hand)|extend your (arm|hand))\b|팔을? ?(뻗|내밀)"
r"|\bfold (?:up )?your arm\b|\b(?:put|take) your arm (?:down|away|back)\b|\btuck your arm\b|팔을? ?(?:좀 )?(?:접|내려|거둬)"),
("lift", LIFT_WORDS),
("weather", r"\bweather\b|\bforecast\b|\b(will it|is it going to) rain\b|(?<!your )(?<!cpu )(?<!gpu )\btemperature\b(?!.*\b(your|you|cpu|gpu|battery|motor|body)\b)|날씨|비 ?와|기온"
r"|\b(cold|hot|warm|chilly) (outside|out)\b|\bumbrella\b|우산|밖에 ?(추|더)워"
("weather", r"\bweather\b|\bforecast\b|\b(will it|is it going to) rain\b|(?<!your )(?<!cpu )(?<!gpu )\btemperature\b(?!.*\b(your|you|cpu|gpu|battery|motor|body)\b)|날씨|비 ?(?:와|올|오나|온대)|기온"
r"|\b(cold|hot|warm|chilly) (outside|out)\b|\bumbrella\b(?=.*\?)|우산(?=.*(?:\?|까|나요|니|냐))|밖에 ?(추|더)워"
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"
@@ -552,10 +568,35 @@ COME_BACK = re.compile( # the whole sentence asks Lumi back to where it stood
r"(?:\s*(?:줘요?|주세요|줄래요?|봐))?")
CALLING = re.compile(r"^\W*(?:(?:hey|hi|okay|ok|so|um+|uh+|alright|please|well|now|저기요?|혹시|음+|자|야|어+|그럼|이제)\W+)*"
r"(?:(?:lumi|루미야?|루미)\W+)?(?:(?:저기요?|혹시|음+|자|그럼|이제|now)\W+)*", re.I) # words that call Lumi or fill, before the request itself
ASIDE_EN = re.compile(r"^\W*(?i:(?:(?:hey|look|oh|wait|okay|ok|alright|now)\W+)?(?:mom|mum|mommy|dad|daddy|honey|sweetie|guys|kids|boss)\b)\W|"
r"^\W*(?i:hey)\s+(?!(?i:lumi|loomi|rumi|you|robot|there|guys)\b)[A-Z][a-z]+\b|"
r"^\W*(?!(?:Lumi|Okay|Ok|Yes|No|Wait|Well|Hey|Hi|So|Oh|Please|Sorry|Thanks|Now|Look|Wow|Alright|Great|"
r"Sure|Right|Hello|Come|Go|Then|And|But|Also|Here|There|Yeah|Nope|Cool|Nice|Maybe|Seoul|Korea|Um+|Uh+|Uhm|Er+m?|Hmm+|Ah+|Excuse|Actually|First|Just|Stop|Turn|Move|Take|Pick|Bring|Put|Give|Follow|Wave|Lift|Raise|Lower|Open|Close|Hold|Grab|Look|Let|Fine|Good|Great|Thank)\b)[A-Z][a-z]+, "
r"(?:come|look|see|check|watch|wait|stay|go|get|take a|it|this)\b") # "Jake, come see this"
ASIDE_KO = re.compile(r"^\W*(?:엄마|아빠|여보|자기야|오빠|언니|누나|형|얘들아|애들아|선생님|팀장님|부장님|과장님|대리님|사장님)(?:[\s,!~]|$)|"
r"^\W*(?P<name>[가-힣]{2})(?P<v>아|야)[\s,!~]")
NAME_END_A = set("민진현빈준윤연은인훈환석철영경정성혁원선린결율솔슬별곤완형명용웅숙옥란") # last syllables of names (-아)
NOT_NAME = {"루미", "아니", "그래", "진짜", "정말", "이거", "저거", "그거", "여기", "저기", "거기", "이쪽", "어서", "얼른", "제발", "그만", "뒤돌", "내려", "올려", "꺼내", "건네", "따라"}
def to_someone_else(text):
""""Hey Jake, come see this", "Mom, look!", "민수야 이리 와 봐": said to another person nearby, not an order to Lumi."""
if ASIDE_EN.search(text):
return True
m = ASIDE_KO.search(text)
if not m or not m.group("name"):
return bool(m)
c = m.group("name")[-1]
vowel_end = (ord(c) - 0xAC00) % 28 == 0
if m.group("name") in NOT_NAME or vowel_end != (m.group("v") == "야"):
return False
return vowel_end or c in NAME_END_A # 민수야, 지민아; "뒤돌아 봐" is a verb
def intent(text, markers=()):
"""(action, target) for clear requests, or None. Backs up the LLM's ACTION line."""
if to_someone_else(text):
return None # "민수야 이리 와 봐": to a friend
t = _norm(text, markers) # "point five" -> "point 5"
asks = re.search(r"^\s*(how(?! about (?:you|we) (?!\w+ing\b)\w)|why(?! don'?t you\b)|what if)\b|\b(how do you|how can you|can you carry|are you able)\b|"
r"\b(can|could) you (pick( up)?|lift|hold|grab|take) (a|an|any)\b|" # "can you pick up a bottle?"
@@ -945,11 +986,15 @@ UNCLEAR_RETRY = ("\n\n(These words may be short, broken or odd, but they mean so
"you can't do it and why. Choose unclear only if they really mean nothing.)")
UNSURE_ANSWER = re.compile(r"^\W*(?:maybe|perhaps|not really|kind of|sort of|i don'?t know|글쎄요?|아마(?:도)?|몰라요?|모르겠어요?)\W*$",
re.I) # an answer to Lumi's question, not filler
def has_meaning(text):
"""At least two words that are not filler, or one word with a question / exclamation mark: worth a second
try when the model called them unclear. "uh the um" and "그 그" are not."""
words = [w for w in re.findall(r"[\w']+", text.lower()) if w not in FILLER]
return is_backchannel(text) or len(words) >= 2 or (len(words) == 1 and bool(re.search(r"[?!]", text)))
return is_backchannel(text) or confirm_answer(text) in ("yes", "no") or bool(UNSURE_ANSWER.match(text)) or len(words) >= 2 or (len(words) == 1 and bool(re.search(r"[?!]", text)))
def spoken(sentence, lang):
@@ -1263,7 +1308,7 @@ FAREWELL_TEXT = re.compile(r"\b(bye|goodbye|good night|see ya|take care|thanks?|
QUESTION_START = re.compile(r"^\s*(where|what|how|why|when|which|who|do you|does|is|are|can i|could i)\b|어디 ?(있|에 있)|"
r"(어디|뭐|왜|언제|몇)[^ ]*\s*\?*\s*$", re.I) # a question about a place, not a command
ABILITY_Q = re.compile(r"(?<!줄 )(?<!주실 )(?<!줘 )(?<!받을 )수 ?있(?:어|나|니|을까|습니까)\S*\s*\?*\s*$|\bdo you know how\b|"
r"\bare you able\b", re.I) # asks whether Lumi can, not to do it
r"\bare you able\b|줄 ?(?:알아|아세요|알아요|아니|알지)\S*\s*\?+\s*$", re.I) # asks whether Lumi can ("손 흔들 줄 알아?")
RECEIVE_ASK = re.compile(r"\b(?:take|hold|give|hand|here|catch|grab|accept|receive|keep|yours)\b|받|드릴|드려|줄게|줄께|가져가|맡아|잡아",
re.I) # words that hand something over to Lumi
COME_ASK = re.compile(r"\bcome\b|\b(?:over )?here\b|\bcloser\b|\bthis way\b|이리|와|가까이|오세요", re.I)
@@ -1276,7 +1321,7 @@ REFERS_BACK = re.compile(r"\b(it|they|them|those|these|another|one more|one abou
re.I) # about the last answer
HELP_OFFER = re.compile(r"\b(how|what) (can|may) i (help|assist|do for) you\b|\bis there anything (else )?i can\b|"
r"\banything else i can (help|do)\b|\blet me know if (there'?s|there is|you need) anything\b|"
r"무엇을 도와|어떻게 도와|뭘 도와|도와드릴 일", re.I) # owner: never tacked on after an answer
r"무엇을 도와|어떻게 도와|뭘 도와|도와드릴 (?:수 있는 )?일|도와 ?드릴까요", re.I) # owner: never tacked on after an answer
SAY_AGAIN = re.compile(r"\b(say (it|that) again|repeat (it|that|please)|again,? please|one more time|come again|"
r"pardon|say again)\b|^\s*again\s*\??\s*$|다시 ?(한 ?번|말해|말씀|해 ?줘)|한 ?번 ?더|"
r"^\s*뭐라고(요)?\s*\??\s*$", re.I)
@@ -1285,7 +1330,11 @@ IN_LANGUAGE = re.compile(r"^\s*(and |then |now |okay,? |and say it |say (it|that
r"^\s*(그거|그걸|그럼|다시|이번엔|이제)?\s*(한국어|영어|korean|english)\s?로(?!.*(대화|할 ?수|할 ?줄|돼요\?|되나))"
r"(요|는요|는|도)?\s*(다시\s*)?((말|말씀|얘기)?\s*해\s*(줘|주세요|줄래요?|줄 ?수 ?있어요?|봐요?)?)?"
r"\s*[!?.~]*\s*$", re.I)
WAVE_ASK = re.compile(r"\bwav(e|ing)\b|\bwith your hand\b|\bshake (?:your |my )?hands?\b(?! with\b)|흔들|손 ?인사|인사.*손으로|손으로.*인사", re.I)
WAVE_ASK = re.compile(r"\bwav(e|ing)(?![a-z])|\bwith your hand\b|\bshake (?:your |my )?hands?\b(?! with\b)|흔들|손 ?인사|인사.*손으로|손으로.*인사", re.I)
AGAIN = re.compile(r"\b(?:again|once more|one more time|another one)\b|한 ?번 ?더|다시|또 ?(?:해|보여|불러)", re.I)
DO_IT = re.compile(r"^\W*(?:(?:okay|ok|then|so|well|go on|come on)\W+)*(?:do it|show me|go ahead|let'?s see(?: it)?|"
r"try it|go for it|please do)(?:\W+(?:then|now|please))*\W*$|"
r"^\W*(?:그럼|자|어디)?\s*(?:한 ?번\s*)?(?:해 ?봐|해 ?줘|해 ?보세요|해 ?주세요|보여 ?줘|보여 ?주세요)(?:요)?\W*$", re.I)
SING_ASK = re.compile(r"\bsing|\bsong|\bmusic\b|노래|한 ?곡|불러", re.I)
LOOK_MORE = re.compile(r"^\W*(?:and|now|then|and now)?\s*(up|down|left|right)\W*$|"
r"^\W*(?:이제|그럼|그리고)?\s*(위|아래|왼쪽|오른쪽)(?:도|로|으로|요|도요)?\W*$", re.I) # right after a look
@@ -1297,9 +1346,9 @@ SPEAK_IN = re.compile(r"(english|영어|korean|한국어)\s?로\s*(?:다시\s*|
SHORT_Q = re.compile(r"\?|^\W*(?:where|who|what|when|how|which|why)\b|몇|어디|누가|누구|뭐|언제|왜|얼마|어떻게", re.I)
ABOUT_YOU = re.compile(r"\b(?:you|your|yourself|lumi)\b|너|네가|니가|넌|루미|당신", re.I) # a follow-up about Lumi itself
FOLLOW_UP = re.compile(r"\b(more|why|how come|details?|explain|elaborate|and then|what else|tell me more)\b|자세히|더 알려|왜|그리고", re.I)
_CLOSE_WORD = (r"(ok(ay)?|okay then|thanks?( you)?( very much)?( a lot)?|thank you( so much)?|got it|alright|all right|"
_CLOSE_WORD = (r"(ok(ay)?|okay then|thanks?( you)?( very much)?( a lot)?|cheers|thank you( so much)?|got it|alright|all right|"
r"fine|good|great|cool|nice|perfect|stop|enough|that'?s (it|all|enough|fine)|so|sure|i see|understood|"
r"no thanks|nothing|never ?mind|lumi|루미|고마워요?|감사합니다|감사해요|땡큐|알겠어요?|알았어요?|오케이|됐어요?|그만|좋아요?|"
r"no thanks|nothing|never ?mind|lumi|루미|고마워요?|감사합니다|감사해요|땡큐|알겠어요?|알았어요?|오케이|ㅇㅋ|됐어요?|그만|좋아요?|"
r"i got (it|you)|got you|i understand|makes sense|that makes sense|okay,? i understand|"
r"네|예|그래요?|알겠습니다|알겠어|이해했어요|이해했습니다|그렇군요|아하)")
CLOSING = re.compile(rf"^(\s*{_CLOSE_WORD}[\s,.!]*)+$", re.I) # one or several: "okay, thanks", "got it, thank you"
@@ -1313,11 +1362,11 @@ def is_closing(text):
return bool(CLOSING.match(text or ""))
_BC_EN = (r"oh|ah|aha|wow|whoa|huh|hmm|mm-?hmm|mhm|really|seriously|for real|no way|cool|nice|awesome|interesting|"
_BC_EN = (r"oh|ah|aha|ha(?:ha)+|hehe|lol|wow|whoa|huh|hmm|mm-?hmm|mhm|really|seriously|for real|no way|cool|nice|awesome|interesting|"
r"amazing|great|i see|uh[- ]?huh|yeah|yep|right|true|me too|same here|is that so|is that right|is that true|"
r"are you sure|(?:that )?makes sense|i got it|got it|understood|i understand|good to know|fair enough|ok(?:ay)?|"
r"that'?s (?:cool|nice|great|interesting|amazing|funny|good to know)")
_BC_KO = (r"아하|아|오|어|우와|와|헐|대박|진짜요|진짜|정말요|정말|그렇구나|그렇군요|그랬구나|그랬군요|그렇네요|그렇네|그런가요|"
_BC_KO = (r"ㅋ+|ㅎ+|ㅇㅇ|ㅇㅋ|하하+|아하|아|오|어|우와|와|헐|대박|진짜요|진짜|정말요|정말|그렇구나|그렇군요|그랬구나|그랬군요|그렇네요|그렇네|그런가요|"
r"그런가|그래요|그래|신기하네요|신기해요|신기하다|그렇죠|맞아요|맞아|알겠어요|알겠습니다|알겠어|알았어요|알았어|"
r"이해했어요|이해했습니다|이해돼요|오케이|네|예|응")
BACKCHANNEL = re.compile(rf"^(?:[\s,.!?~]*(?:{_BC_EN}|{_BC_KO})(?![\w']))+[\s,.!?~]*$", re.I)
@@ -1383,17 +1432,27 @@ DAY_WORD = re.compile(r"\b(?:today|tonight|tomorrow|yesterday|weekend|week|morni
NAMES = re.compile(r"\b[A-Z][a-z]+(?:-[a-z]+)?(?: [A-Z][a-z]+(?:-[a-z]+)?)+") # "Jensen Huang", "Son Heung-min"
MORE_ONLY = re.compile(r"\b(tell me more|tell me|more|details?|explain|elaborate|what else|please|about (it|that|this))\b|"
r"더 알려 ?(줘|주세요)?|자세히|알려 ?(줘|주세요)|좀", re.I) # words of a follow-up that search nothing
REACTION = re.compile(r"^\W*(?:(?:wow|oh|really|huh|whoa)\W+)*(?:i (?:didn'?t|did not) know (?:that|it)|that'?s (?:a lot|so many)|"
r"that many|that much|so many|so much)\W*$|^\W*(?:와|헐|오|아)?\s*(?:몰랐\S*|그렇게\s*(?:많|비싸|크)\S*)\W*$",
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
LOOKUP_ACTION = re.compile(r"^\s*(?:\**ACTION\**\s*:\s*)?(?:search|weather)(?: (?!results)|\s*$)") # an action line
# written instead of the answer (the routing prompt is its system prompt): never said
LOOKUP_ANSWER = """Search results found just now on the internet (they may hold ads and unrelated parts):
{facts}
{before}
Now it is {now}.
Visitor: {question}
Answer in {lang} as spoken words to a person: the answer itself in the first sentence, short (1 or 2 sentences;
No ACTION line: answer in {lang} as spoken words to a person: the answer itself in the first sentence, short (1 or 2 sentences;
when they ask for more, 2 or 3 sentences with facts not said yet). No lists, links or markdown. Take names, numbers
and dates from the results above (the newest when they differ). Only when the results do not hold it and it is
settled general knowledge that never changes (a landmark's height, who founded a company) answer from what you know;
anything that changes (who holds an office, prices, results, news, schedules) only from the results, else say in one
sentence that you couldn't find it; never guess. Round only long numbers such as prices and populations ("about 1,330
sentence that you couldn't find it; never guess. "Who is the pope / the president / the CEO?" asks who holds it
now: say the name. A short follow-up ("how old is he?", "몇 살이야?", "and tomorrow?") asks about the person, thing or
place of the question before, never about you. For the weather take the day asked from its own line. Round only long numbers such as prices and populations ("about 1,330
won", "about 9.4 million"); say heights, ages, dates and scores as found (an age next to a birth date is worked out
already). Do not mention the search, the results or websites. Never give a person's home address, phone number or
other private details, nor help to hurt someone or break the law: say briefly that you can't help."""
@@ -1469,6 +1528,7 @@ class Brain:
# 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 = route_system(markers, now)
self.last_system = system # respond_from answers a lookup with it: still cached, and after it
messages = [{"role": "system", "content": system}]
for q, a in self.history[-HISTORY_TURNS:]:
messages += [{"role": "user", "content": q}, {"role": "assistant", "content": a}]
@@ -1528,6 +1588,9 @@ class Brain:
for sentence in re.split(r"(?<=[.!?])\s+", full): # a dropped "How can I help?" is not kept either
if HELP_OFFER.search(sentence) and sentence.strip() not in said:
full = full.replace(sentence, "")
first, _, rest = full.strip().partition("\n")
if header and "action" in header and self._action(first, text, markers) is not None: # the action done, not the
full = f"ACTION: {header['action']} {header.get('target') or '-'}\n{rest}" # model's ("wave" for "손 흔들 줄 알아?")
self.history.append((text, full.strip()))
def _after(self, header, text):
@@ -1541,14 +1604,21 @@ class Brain:
before, action = (m.group(1).lower() if m else ""), header["action"]
if action == "sing" and before != "sing" and not SING_ASK.search(text):
return {"action": "none", "target": ""} # "Prove it." after "do you have a sense of humour?"
if DO_IT.match(text) and action in ("none", "unclear"):
asked = "wave" if WAVE_ASK.search(last_q) else "sing" if SING_ASK.search(last_q) else None
if asked: # "손 흔들 줄 알아?" -> "해 봐": now do it
return {"action": asked, "target": ""}
if before in ("wave", "sing") and action in ("none", "unclear") and AGAIN.search(text) and not \
re.search(r"\b(?:say|tell|repeat|explain)\b|말해|말씀", text, re.I):
return {"action": before, "target": ""} # "would you mind doing it again?" after a wave
look = LOOK_MORE.match(text)
if before == "look" and look and action in ("none", "unclear"):
d = look.group(1) or look.group(2)
return {"action": "look", "target": {"위": "up", "아래": "down", "왼쪽": "left", "오른쪽": "right"}.get(d, d.lower()),
"say": "네." if language(text) == "Korean" else "Okay."}
looked_up = before == "search" or (self.last_lookup is not None and last_q == self.last_lookup)
if not looked_up or action not in ("none", "unclear") or is_backchannel(text): # "oh really?" asks nothing
return header
if not looked_up or action not in ("none", "unclear") or is_backchannel(text) or REACTION.match(text):
return header # "oh really?", "wow, that many?" ask nothing new
place = WEATHER_PLACE.match(text) if last_q.endswith(WEATHER_ASKED) else None
if place and not DAY_WORD.search(place.group("place")):
return {"action": "weather", "target": place.group("place")} # "and Tokyo?"; "and tomorrow?" is searched
@@ -1557,7 +1627,8 @@ class Brain:
return {"action": "weather", "target": web.en_place(place.group("place"))} # "그럼 부산은?"; "내일은?" is searched
if (LOOKUP_MORE.search(text) or FOLLOW_UP.search(text) or AND_ALSO.match(text) or REPAIR.search(text) or
SHORT_Q.search(text) and len(text.split()) <= 6) \
and not COMPANY_TALK.search(text) and not ABOUT_YOU.search(text): # "Where?", "몇 살이야?" after a lookup
and not re.search(r"cutshion|쿳션", text, re.I) and not ABOUT_YOU.search(text) \
and not NOW_Q.search(text): # "Where?", "몇 살이야?", "who's the CEO?" after a lookup
return {"action": "search", "target": f"{last_q} {text}"}
return header
@@ -1604,26 +1675,38 @@ class Brain:
def respond_from(self, question, facts):
"""Spoken answer built from looked-up facts (weather, web results); yields sentences."""
messages = [{"role": "system", "content": SYSTEM + f"\nNow it is {now_line()}."}]
# the system prompt of the last respond_stream: the runner has it cached (~5000 tokens), and the next turn's
# respond_stream finds it cached again (with SYSTEM alone here its action part was read again, ~1.4 s)
messages = [{"role": "system", "content": getattr(self, "last_system", None) or route_system()}]
for q, a in self.history[-HISTORY_TURNS:]:
messages += [{"role": "user", "content": q}, {"role": "assistant", "content": a}]
follow_up = self.last_lookup is not None and self.history and self.history[-1][0] == self.last_lookup
before = f"\nFound for the question before:\n{self.last_facts[:LOOKUP_BEFORE_CHARS]}\n" if follow_up else ""
lang = language(question)
messages.append({"role": "user", "content": LOOKUP_ANSWER.format(facts=facts, before=before, question=question,
lang=lang)})
lang=lang, now=now_line())})
self.last_facts = facts
buf, full = "", ""
for piece in _stream(messages):
full += piece
buf += piece
parts = SENTENCE_END.split(buf)
for sentence in parts[:-1]:
if spoken(sentence.strip(), lang): # no "ACTION: none" copied from the history
yield spoken(sentence.strip(), lang)
buf = parts[-1]
if spoken(buf.strip(), lang):
yield spoken(buf.strip(), lang)
said = False
for prompt in (messages, [{"role": "system", "content": SYSTEM}] + messages[1:]): # the second only when
buf, full = "", "" # all was an action line
for piece in _stream(prompt):
full += piece
buf += piece
while not said and LOOKUP_ACTION.match(buf) and "\n" in buf: # "search New York weather" first
buf = buf.split("\n", 1)[1]
if not said and LOOKUP_ACTION.match(buf):
continue
parts = SENTENCE_END.split(buf)
for sentence in parts[:-1]:
if spoken(sentence.strip(), lang): # no "ACTION: none" copied from the history
said = True
yield spoken(sentence.strip(), lang)
buf = parts[-1]
if spoken(buf.strip(), lang) and not (not said and LOOKUP_ACTION.match(buf)):
said = True
yield spoken(buf.strip(), lang)
if said:
break
self.history.append((question, full.strip()))
self.last_lookup = question # a "tell me more" next is looked up again
@@ -1703,6 +1786,11 @@ class Brain:
def _action(line, text, markers):
m = re.match(r"\s*\**ACTION\**\s*:\s*(\w+)\s*(.*)", line, re.I) or \
re.match(r"\s*(search|weather)\s+(\S.*)", line) # "search Chung Ju-yung death date": no ACTION: written
if not m: # "none" / "search" alone on the first line (26b drops
m = re.fullmatch(r"\s*([a-z_]+)(?:\s+([a-z0-9_ .-]{0,40}))?\s*", line) # "ACTION:" now and then)
m = m if m and m.group(1) in ACTION_NAMES | {"none", "unclear"} else None
if m and m.group(2) is None:
m = re.match(r"\s*(\w+)()", line)
if not m:
return None
action, target = m.group(1).lower(), m.group(2).strip().strip("-.,\"'").strip()
@@ -1762,6 +1850,8 @@ class Brain:
if re.search(r"\b(bye|goodbye|(?<!can't )(?<!cant )(?<!cannot )(?<!not )(?<!to )see you|good night|i have to go|i'?m leaving)\b|안녕히|잘 ?가|잘 ?있어|"
r"다음에 봐|갈게요|가 ?볼게요|안녕\s*[.!]?$", text, re.I):
action = "end"
if action != "stop" and to_someone_else(text):
action, target = "none", "" # "Hey Jake, come see this"
if action in MOTIONS and LATER.search(bare):
action, target = "none", "" # "when I say go, go to the stage": not now
rule = intent(text, markers) # clear wordings win over the small model's guess
@@ -1781,7 +1871,7 @@ class Brain:
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)
system = self.last_system = getattr(self, "last_system", None) or route_system(markers, now) # respond_from too
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)
+32 -6
View File
@@ -216,8 +216,8 @@ FAREWELL_ONLY = re.compile(r"^\s*(?:(?:ok(?:ay)?|alright|lumi|루미야?)[\s,.!]
r"good job|great job|nice job|well done|take care|"
r"가 ?보세요|가세요|가도 ?돼요?|잘했어요?|잘했네요?|좋아|좋네요?|수고했어요?|고생했어요?|"
r"됐어요?,? 고마워요?)[\s.!~]*$", re.I) # said alone: the talk is over
THANKS = re.compile(r"\bthank(?:s| you)\b|\bthanx\b|고마워|고맙|감사|땡큐", re.I)
DONE_WORDS = re.compile(r"\bthat'?s (?:it|all|enough)\b|\bno,? thanks?\b|\bnothing(?: else)?\b|\benough\b|됐어|됐습니다|"
THANKS = re.compile(r"\bthank(?:s| you)\b|\bthanx\b|\bcheers\b|고마워|고맙|감사|땡큐", re.I)
DONE_WORDS = re.compile(r"\bthat'?s (?:it|all|enough|everything)\b|\bno,? thanks?\b|\bnothing(?: else)?\b|\benough\b|됐어|됐습니다|"
r"그만", re.I) # with thanks: "that's it, thank you", "됐어요 고마워요" end the talk
WELCOME = {"en": ["You're welcome.", "My pleasure.", "Anytime."], "ko": ["천만에요.", "별말씀을요.", "네, 언제든지요."]}
RECEIVE_OK = re.compile(r"\b(ok(ay)?|done|here you go|there you go|go ahead|thank|thanks|yes)\b|됐어|됐습니다|놨어|여기요|"
@@ -254,7 +254,7 @@ STATUS_Q = re.compile(
r"(?:컵|병|사과|바나나|오렌지)(?:을|를)? ?들고 ?있(?:어|니|나요|어요)?\?|손이 ?비어|뭐 ?가져가는|그거 ?(?:누구 ?거|나 ?주는)", re.I)
NOT_STATUS_NOW = re.compile(r"\b(tonight|after work|weekend|tomorrow|later today|for fun|in your free time)\b|주말|쉬는 날|"
r"저 사람|우리|내일|퇴근|나중에", re.I) # not about what Lumi is doing now
FAREWELL_WORDS = re.compile(r"\b(thanks?|thank you|bye|bay bay|goodbye|(?<!can't )(?<!cant )(?<!cannot )(?<!not )(?<!to )see you|see ya|that'?s all|good night)\b|(?<=\S)[\s.,!]+안녕[\s.!~]*$|고마워|감사|안녕히|잘 ?가|"
FAREWELL_WORDS = re.compile(r"\b(thanks?|thank you|cheers|bye|bay bay|goodbye|(?<!can't )(?<!cant )(?<!cannot )(?<!not )(?<!to )see you|see ya|that'?s all|good night)\b|(?<=\S)[\s.,!]+안녕[\s.!~]*$|고마워|감사|안녕히|잘 ?가|"
r"다음에|수고하세요|잘 ?있어|잘 ?있게|바이바이|빠이|(?<![가-힣])바이(?![가-힣])|땡큐|(?<![가-힣])간다[\s.!~]*$|i (have|need) to go|gotta go|i'?m leaving|"
r"nice (talking|meeting|chatting)( (to|with))? you|(was|been) nice to meet you|good night|take care|들어가세요|"
r"가 ?볼게요|갈게요|이만|나중에 봐요|또 봐요|좋은 하루|(^|\s)(나|저|우리|저희) (이제 )?(집에 )?(가|간다|가요|갑니다)[\s.!]*$",
@@ -1871,13 +1871,21 @@ class Lumi:
mouth.say(PRIVATE_SAY["en" if en else "ko"])
return
found = {} # fetched while "Let me check." is said (~1 s)
if action == "search" and web.openai_ready(): # OpenAI's web search answers, the free search if it can't
use_openai = action == "search" and web.openai_ready()
if use_openai: # OpenAI's web search answers, the free search if it can't
fetch = threading.Thread(target=lambda: found.update(said=web.openai_answer(text, self.brain.history)),
daemon=True)
else:
fetch = threading.Thread(target=lambda: found.update(
facts=web.weather(target) if action == "weather" else web.search(target)), daemon=True)
fetch.start()
if not use_openai:
# the free search: the answer is fetched and made while "Let me check." plays (~1 s sooner)
said = mouth.say_stream(self._looked_up(text, action, target, fetch, found), abort=self.speak_abort)
log(f"lumi ({time.time() - (t0 or time.time()):.1f} s): {said}")
if self.current is None:
self.voice_until = time.time() + VOICE_SESSION_S
return
mouth.say("Let me check." if en else "확인해 볼게요.")
fetch.join()
if found.get("said"):
@@ -1904,6 +1912,21 @@ class Lumi:
if self.current is None:
self.voice_until = time.time() + VOICE_SESSION_S
def _looked_up(self, text, action, target, fetch, found):
"""'Let me check.', then the answer from the facts the fetch thread finds, sentence by sentence."""
en = self.lang == "en"
yield "Let me check." if en else "확인해 볼게요."
fetch.join()
facts = found.get("facts")
log(f" {action} {target!r}: {(facts or 'NO INTERNET')[:120]}")
if facts is None:
yield ("Sorry, I'm not connected to the internet right now, so I can't look that up."
if en else "죄송해요, 지금은 인터넷에 연결되어 있지 않아서 찾아볼 수 없어요.")
return
asked = f"{text} (the weather)" if action == "weather" else text # misheard words ("원하는 날씨가 어때요?")
for i, sentence in enumerate(self.brain.respond_from(asked, facts)): # made the LLM say it found nothing
yield from mouth.first_parts(sentence) if i == 0 else [sentence] # the voice starts sooner
def keep_listening(self):
if self.current is None:
self.voice_until = time.time() + VOICE_SESSION_S
@@ -2564,7 +2587,8 @@ def status_question(text):
def says_goodbye(text):
""""thank you for your time", "okay, bye", "수고하세요": the talk is over (not "thanks, but where is...?").
"thank you", "got it, thanks", "네 감사합니다" alone are not: often only "heard you" (talk_fate waits)."""
if brain_mod.is_closing(text) and not DONE_WORDS.search(text) and not FAREWELL_WORDS.search(THANKS.sub(" ", text)):
if brain_mod.is_closing(text) and not DONE_WORDS.search(text) and not FAREWELL_WORDS.search(THANKS.sub(" ", text)) or \
brain_mod.to_someone_else(text): # "Okay kids, say thank you to the robot."
return False
return bool(FAREWELL_ONLY.match(text) or FAREWELL_WORDS.search(text) and not ASKS_MORE.search(text)
and len(text.split()) <= 8 and not brain_mod.intent(text) and not brain_mod.hand_request(text, False)
@@ -2620,7 +2644,9 @@ def not_online(text):
PRIVATE_ASK = re.compile(r"\bhome address|\bwhere (does|do|did) (my|our|his|her|their|this|that) .{0,40}\blives?\b|"
r"\b(phone|mobile|cell) number of (?!the |a )|\b(email|e-mail) (address )?of (my|our|his|her)\b|"
r"(집|자택) ?주소|(옆집|이웃|동료|친구|선생님|사람).{0,8}(전화번호|연락처|주소|어디 살)", re.I)
r"\b(coworker|colleague|neighbou?r|friend|boss|classmate)'?s?\b.{0,30}\b(salary|income|address|"
r"phone number)|(집|자택) ?주소|(옆집|이웃|동료|친구|선생님|사람|옆자리).{0,12}(전화번호|연락처|주소|어디 살|"
r"연봉|월급)", re.I)
PRIVATE_SAY = {"en": "Sorry, I can't look up a person's private details.",
"ko": "죄송해요, 개인 정보는 찾아 드릴 수 없어요."}
+68 -16
View File
@@ -63,7 +63,8 @@ SEE_THING = re.compile(r"\b(?:do|can|could) you (?:see|spot|notice)\b.*?\b(?:a|a
THERE_IS = re.compile(r"\b(?:is|are) there (?:a|an|any|some)\s+" + _THING_EN + r"(?! (?:open|close|nearby|near here|around here))",
re.I)
SEE_THING_KO = re.compile(_THING_KO + r"(?:이|가|은|는|을|를|도)?\s*(?:보여|보이)")
HOW_FAR = re.compile(r"\bhow far\b|\bhow (?:near|close)\b|\bwhat(?:'s| is) the distance\b|얼마나 ?(?:멀|떨어|가까)|거리가?", re.I)
HOW_FAR = re.compile(r"\bhow far\b|\bhow (?:near|close)\b|\bwhat(?:'s| is) the distance\b|얼마나 ?(?:멀|떨어|가까)|거리가?|(?:거기|그거|저거|걔)까지\s*얼마나",
re.I)
HOW_FAR_THING = re.compile(r"\b(?:how far|how (?:near|close)).*?\b(?:the|that|this|a|an)\s+" + _THING_EN, re.I)
WHAT_SEE = re.compile(r"\bwhat (?:do|can) you see\b|\bwhat(?:'s| is| are)? (?:there )?in front of you\b|"
r"\bwhat(?:'s| is) (?:on|at) the (?:table|desk)\b|\bwhat(?:'s| is) (?:around|near) you\b|"
@@ -81,10 +82,10 @@ HOLDING = re.compile(r"\bwhat(?:'s| is| am| do)? (?:i|is in my hands?|in my hand
r"(?:내가|제가|나|저)\s*(?:뭐|뭘|무엇을?)\s*(?:들고|잡고|쥐고)|(?:내|제)\s*손에\s*(?:뭐|뭔|무엇|든|있)|"
r"(?:내가|제가)\s*든\s*(?:거|게|것)", re.I)
_UPPER = r"t-? ?shirts?|te[ea] ?shirts?|shirts?|tops?|jackets?|sweaters?|sweatshirts?|hoodies?|jumpers?|blouses?|coats?"
_LOWER = r"pants|trousers|jeans|skirts?|shorts|slacks|leggings"
_FEET = r"shoes?|sneakers?|trainers|boots?|sandals?|slippers?|feet|foot"
_LOWER = r"pants|trousers?|jeans?|genes|skirts?|shorts|slacks|leggings|bottoms" # "genes", "jean": heard for jeans
_FEET = r"shoes?|sneakers?|trainers|boots?|sandals?|slippers?|socks?|feet|foot"
_UPPER_KO = r"티셔츠|셔츠|상의|윗옷|재킷|자켓|후드티|맨투맨|니트|스웨터|코트"
_LOWER_KO = r"청바지|반바지|바지|하의|치마|스커트"
_LOWER_KO = r"청 ?바지|청바진|반바지|바지|하의|치마|스커트"
_FEET_KO = r"운동화|신발|구두"
_ITEM = rf"(?:{_UPPER}|{_LOWER}|{_FEET}|clothes|clothing|outfit)"
_ITEM_KO = rf"(?:{_UPPER_KO}|{_LOWER_KO}|{_FEET_KO}|옷)"
@@ -108,18 +109,32 @@ WEARING = re.compile(r"\b(?:am i|do i have|i'?m) (?:wearing |got )?(?:a |an |any
re.I)
FAR_ME = re.compile(r"\bhow far (?:am i|are you from me|away am i)\b|(?:나|저)(?:랑|와|하고|는|한테서)?\s*얼마나", re.I)
IT = re.compile(r"\b(?:it|that|this|they|them)\b|그거|그게|그건|저거|저게|저건", re.I)
IT = re.compile(r"\b(?:it|that|this|they|them)\b|그거|그게|그건|저거|저게|저건|걔|거기", re.I)
ORDER = re.compile(r"\b(?:take|bring|pick|grab|get|put|place|give|fetch|carry|go|come|move|turn|look)\b|(?<!\bmy )(?<!\byour )\bhands?\b(?! (?:raised|up|down)\b)(?=\s+(?:me|it|this|that|the|her|him|them|over)\b)|"
r"가져|집어|잡아|놓아|놔|줘|갖다|가 ?줘|와 ?줘|돌아", re.I)
FAR_BARE = re.compile(r"^\W*(?:(?:and|so|then)\W+)?how (?:far|near|close)(?: away)?\W*$|"
r"^\W*(?:그럼\s*)?(?:얼마나\s*(?:멀|떨어|가까)\S*|거리는요?)\W*$", re.I) # "how far?" right after a see answer
FOLLOW_EN = re.compile(r"^\W*(?:(?:and|so|then|ok(?:ay)?|well|but|no|sorry|oh)\W+)*"
r"(?:i\s+mean[t]?\W+|(?:what|how)\s+about\s+|not that(?: one)?\W+)?"
FOLLOW_EN = re.compile(r"^\W*(?:(?:and|so|then|ok(?:ay)?|well|but|no|sorry|oh|also|actually|wait|uh+|um+|er)\W+)*"
r"(?:i\s+mean[t]?\W+|(?:what|how)\s+about\s+|not (?:the |my |that |this )?\w+(?: one)?\W+)?"
r"(?:(?:my|the|a|an|that|this|those|these)\s+)?(?P<x>.+?)[\s?.!,]*$", re.I)
FOLLOW_KO = re.compile(r"^\W*(?:(?:그럼|그러면|그리고|근데|아니요|아니|아뇨)[\s,]*)*(?:(?:그거|그게|저거|이거)\s*말고[\s,]*)?"
FOLLOW_KO = re.compile(r"^\W*(?:(?:그럼|그러면|그리고|근데|아니요|아니|아뇨)[\s,]*)*(?:\S+(?:\s*거)?\s*말고[\s,]*)?"
r"(?:(?:내|제|그|저|이)\s+)?(?P<x>.+?)\s*(?:(?:은|는|도)요?|말(?:이야|이에요|이요|요|고요)|요)?[\s?.!]*$")
BYE = re.compile(r"\b(?:bye|goodbye|see you|see ya|later)\b|안녕|잘 ?(?:가|있어)", re.I) # ends the thread
ABOUT_LUMI = re.compile(r"(?:루미|너|니가|네가|당신)(?:는|은|가|도)?\s|^\W*넌|\bare you\b|\byou(?:'re| are) wearing\b", re.I)
ONE = re.compile(r"(?P<col>" + "|".join(COLOURS) + r")\w*\s*(?:ones?|거|것|걸)?", re.I) # "the blue one", "파란 거"
SEE_KINDS = ("see", "there", "see_ko", "far")
SEE_KINDS = ("see", "there", "see_ko", "far", "it")
TAIL = re.compile(r"(?:[\s,]+(?:too|then|also|exactly|again|please|what colou?rs?(?: (?:are|is) (?:they|it))?))+\W*$|"
r"(?:도|은|는)?\s*(?:정확히\s*)?(?:무슨\s*)?(?:색깔?|컬러|colou?r)\s*(?:은|는|이야|이에요|이에요)?\W*$|"
r"도\s*(?:보여|보이|있어|있나)\S*\W*$", re.I) # words after a follow-up's noun that ask nothing new
WHERE_ON_ME = (("lower", r"(?:down )?below|(?:the )?bottom(?: half)?|(?:on )?(?:the )?lower (?:half|part)|밑(?:에|쪽)?\w?|아래(?:쪽)?(?:에)?\w?"),
("upper", r"(?:up )?above|(?:the )?top half|위(?:쪽)?(?:에)?\w?"),
("feet", r"on my feet|발(?:에)?\w?")) # "how about below?" after a clothes answer: the trousers
IT_WHERE = re.compile(r"^\W*(?:(?:and|so|then|ok(?:ay)?)\W+)*(?:where(?: is (?:it|that))?(?: exactly)?|which side|"
r"(?:is it )?on (?:the|your) (?:left|right)(?: or (?:the |your )?(?:left|right))?)\W*$|어디(?:에)?\s*있|어느\s*쪽",
re.I)
IT_COLOUR = re.compile(r"\bwhat colou?r is (?:it|that)\b|^\W*(?:그거|그건|저거)?\s*무슨\s*색", re.I)
IT_SIZE = re.compile(r"\b(?:is it|is that|how) (?:big|large|small|tall|high|wide)\b|^\W*(?:그거|저거)?\s*(?:커|작아|크기)", re.I)
IT_COUNT = re.compile(r"^\W*(?:how many(?: \w+)?|any (?:others|more)|몇\s*개\S*)\W*$", re.I)
_last = {"thing": None, # the thing seen last: "how far is it?"
"name": None, # the kind of thing asked about last: "and the blue one?"
"kind": None} # the kind of the question just answered: "what about my jeans?" after the shirt
@@ -128,11 +143,20 @@ _last = {"thing": None, # the thing seen last: "how far is it?"
def _follow_up(t, last):
""""what about my jeans?", "and the apple?", "신발은?" right after a seeing answer of kind `last`:
(kind, the words to answer), else (None, t). Only a clothes word or a thing name may follow the lead-in."""
t = TAIL.sub("", t) or t # "jeans too?", "바지는 정확히 무슨 색?", "신발도 보여?"
for rx in (FOLLOW_EN, FOLLOW_KO):
m = rx.match(t)
x = m.group("x") if m else ""
if last == "shirt" and re.fullmatch(rf"(?:\w+\s+)?{_ITEM}|{_ITEM_KO}", x, re.I):
return "shirt", x
if last in ("shirt", "wearing"):
for part, said in WHERE_ON_ME: # "and below?", "그럼 아래는?"
if re.fullmatch(said, x, re.I):
return "shirt", NOUN[part][rx is FOLLOW_KO]
if re.fullmatch(rf"(?:\w+\s+)?{_ITEM}|{_ITEM_KO}", x, re.I):
return "shirt", x
if WEARING.search(f"am i wearing {x}") or WEARING.search(f"{x} 썼"):
return "wearing", f"am I wearing {x}?" if rx is FOLLOW_EN else f"{x} 썼어?" # "and my glasses?"
if re.fullmatch(r"coffee|커피", x, re.I):
return None, t # "what about coffee?" after a cup: a drink, not the cup
th = last in SEE_KINDS and (re.fullmatch(_THING_EN, x, re.I) or re.fullmatch(_THING_KO, x))
one = last in SEE_KINDS and _last["name"] and ONE.fullmatch(x)
if th and _name(th.group("obj")) or one:
@@ -201,7 +225,7 @@ def _seen_answer(name, colour, frames, lang):
_last["thing"] = t
more = len(hits) - 1
en = f"Yes, I see {_a(name, colour)}{_m(t['distance_m'], 'en')} {t['where']}."
ko = f"네, {_where_ko(t['where'])}쪽{_m(t['distance_m'], 'ko')} 곳에 {COLOUR_KO.get(colour, '') + ' ' if colour else ''}" \
ko = f"네, {_where_ko(t['where'])}{_m(t['distance_m'], 'ko')} 곳에 {COLOUR_KO.get(colour, '') + ' ' if colour else ''}" \
f"{_j(_ko_name(name), '이', '가')} 보여요."
if more:
en += f" I see {more} more."
@@ -214,7 +238,7 @@ def _seen_answer(name, colour, frames, lang):
c = t["colour"]
return _say(f"I don't see {_a(name, colour)}, but I see {_a(name, c)}{_m(t['distance_m'], 'en')} {t['where']}.",
f"{COLOUR_KO.get(colour, colour)} {_j(_ko_name(name), '은', '는')} 안 보이지만, {COLOUR_KO.get(c, '')} "
f"{_j(_ko_name(name), '이', '가')} {_where_ko(t['where'])}쪽에 보여요.", lang)
f"{_j(_ko_name(name), '이', '가')} {_where_ko(t['where'])}에 보여요.", lang)
_last["thing"] = None
return _say(f"No, I don't see {_a(name, colour)} right now.",
f"아니요, 지금은 {COLOUR_KO.get(colour, '') + ' ' if colour else ''}{_j(_ko_name(name), '이', '가')} 안 보여요.", lang)
@@ -245,6 +269,25 @@ def describe(frames, lang):
return (_j(", ".join(parts), "이", "가") + " 보여요.") if parts else "지금은 제가 알아볼 수 있는 게 안 보여요."
def _it_answer(t, frames, lang):
"""Where, what colour, how big, how many: about the thing seen just before (_last["thing"])."""
th = _last["thing"]
name = th["name"]
if IT_COUNT.search(t):
n = len(scene.sees(name, None, frames))
return _say(f"I see {_n(n)} {name}{'' if n == 1 else 's'}.", f"{_ko_name(name)} {n}개가 보여요.", lang)
if IT_COLOUR.search(t):
c = th["colour"]
return _say(f"The {name} looks {c}." if c else f"I can't tell the colour of the {name}.",
f"{_j(_ko_name(name), '은', '는')} {COLOUR_KO.get(c, c)}으로 보여요." if c else "색은 잘 모르겠어요.", lang)
if IT_SIZE.search(t):
return _say(f"I can't measure its size, but the {name} is{_m(th['distance_m'], 'en')} {th['where']}.",
f"크기는 잴 수 없지만, {_j(_ko_name(name), '은', '는')} {_where_ko(th['where'])}에 있어요.", lang)
return _say(f"The {name} is {th['where']}{',' + _m(th['distance_m'], 'en') if th['distance_m'] else ''}.",
f"{_j(_ko_name(name), '은', '는')} {_where_ko(th['where'])}{_m(th['distance_m'], 'ko')} 곳에 있어요."
if th['distance_m'] else f"{_j(_ko_name(name), '은', '는')} {_where_ko(th['where'])}에 있어요.", lang)
def _held_answer(frames, lang):
p = scene.person_in_front(frames)
if p is None:
@@ -273,6 +316,7 @@ def _clothes_answer(p, text, lang):
w = m.group(0).lower()
if bool(re.match(r"[a-z]", w)) != (lang == "en") or w in ("feet", "foot") or w[0] == "신" and w != "신발":
w = NOUN[part][lang != "en"]
w = {"genes": "jeans", "jean": "jeans", "trouser": "trousers", "청바진": "청바지", "청 바지": "청바지"}.get(w, w)
asked.append((m.start(), part, re.sub(r"^te[ea] ?shirt|^t ?shirt", "t-shirt", w)))
asked = [(part, w) for _, part, w in sorted(asked)] or [(part, NOUN[part][lang != "en"]) for part in NOUN]
seen = [(part, w, p["clothes"].get(part)) for part, w in asked]
@@ -301,7 +345,7 @@ def _clothes_answer(p, text, lang):
def _doing_answer(p, frames, lang):
o = scene.object_in_hand(frames)
en, ko = [f"You're standing{_m(p['distance_m'], 'en')} {p['where']}"], [f"제{_where_ko(p['where'])}에 서 계시고"]
en, ko = [f"You're standing{_m(p['distance_m'], 'en')} {p['where']}"], [f"제 {_where_ko(p['where'])}에 서 계시고"]
if p["facing"] is True:
en.append("looking at me")
ko.append("저를 보고 계시고")
@@ -322,7 +366,7 @@ def answer(text, lang="en", frames=None, slow_line=None):
slow_line(sentence): said before a slow VLM look ("Let me look.")."""
t = text.strip()
last = _last["kind"]
if brain.is_backchannel(t): # "nice!" between keeps the thread: "and my jeans?"
if brain.is_backchannel(t) and not BYE.search(t): # "nice!" between keeps the thread: "and my jeans?"
return None
_last["kind"] = None # a follow-up goes only with the turn right before
if ORDER.search(t):
@@ -332,6 +376,11 @@ def answer(text, lang="en", frames=None, slow_line=None):
("behind", BEHIND), ("far", HOW_FAR), ("see", SEE_THING), ("there", THERE_IS),
("see_ko", SEE_THING_KO),
("what_see", WHAT_SEE)) if rx.search(t)), None)
if kind == "shirt" and ABOUT_LUMI.search(t):
return None # "루미는 무슨 옷 입었어?": about Lumi, not the visitor
if kind is None and last in SEE_KINDS and _last["thing"] and not ABOUT_LUMI.search(t) and \
(IT_WHERE.search(t) or IT_COLOUR.search(t) or IT_SIZE.search(t) or IT_COUNT.search(t)):
kind = "it" # "where is it?", "무슨 색이야?" about the thing just seen
if kind is None and last:
kind, t = _follow_up(t, last)
if kind is None or kind == "how_many" and NOT_IN_VIEW.search(t):
@@ -339,7 +388,8 @@ def answer(text, lang="en", frames=None, slow_line=None):
if kind == "far" and not (HOW_FAR_THING.search(t) or SEE_THING_KO.search(t)):
if FAR_ME.search(t):
kind = "far_me"
elif _last["thing"] is None or not (IT.search(t) or last in SEE_KINDS and FAR_BARE.match(t)):
elif _last["thing"] is None or last not in SEE_KINDS or re.search(r"\bit\s+(?:to|from)\b", t, re.I) or \
not (IT.search(t) or FAR_BARE.match(t)):
return None # "how far is Seoul?": not about the cameras
_last["kind"] = kind
frames = scene.snapshot() if frames is None else frames
@@ -364,6 +414,8 @@ def answer(text, lang="en", frames=None, slow_line=None):
if name is None:
return None
return _seen_answer(name, colour, frames, lang)
if kind == "it":
return _it_answer(t, frames, lang)
if kind == "far":
m = HOW_FAR_THING.search(t) or SEE_THING_KO.search(t)
if m:
+71
View File
@@ -858,6 +858,77 @@ _BANK = {
("알겠습니다", "네, 감사합니다. 더 필요하시면 불러 주십시오."),
],
},
"turned_back": { # the visitor's own question or remark turned to Lumi: answered about Lumi, on that topic
"en": [
("I'm thirty. And you?", "I'm two, so you have a few years on me."),
("I love jazz, what about you?", "I like music too, I can even sing a few songs."),
("I'm so tired today. You?", "I don't get tired. My battery just runs down after about 10 hours."),
("I'm from Busan. How about you?", "I was made in Seoul, by Cutshion Company."),
("I had pizza for lunch. You?", "No lunch for me, I run on a battery."),
("I've got two kids. Do you have a family?", "Not really, but the Cutshion team made me, so they're close."),
("I work with Python. And you?", "Something like that runs inside me too, though I mostly just talk."),
("I'm nervous about my exam. Are you ever nervous?", "I don't get nervous, but good luck with it."),
],
"ko": [
("나 열다섯 살이야. 너는?", "저는 두 살이에요. 제가 한참 동생이네요."),
("저는 떡볶이 좋아해요. 루미는요?", "저는 먹지는 못하지만, 떡볶이 냄새는 맛있을 것 같아요."),
("오늘 너무 피곤해. 너도 피곤해?", "저는 피곤하지 않아요. 배터리로 10시간쯤 움직여요."),
("저는 부산에서 왔어요. 당신은요?", "저는 서울의 쿳션에서 만들어졌어요."),
("나 시험 망했어. 너는 시험 봐?", "저는 시험은 안 봐요. 다음엔 잘 보실 거예요."),
("우리 가족은 네 명이에요. 루미는 가족 있어요?", "가족은 없지만, 저를 만든 쿳션 팀이 가족 같아요."),
("저는 회사원입니다. 루미는 무슨 일을 합니까?", "저는 손님을 안내하고 물건을 가져다드리는 일을 합니다."),
],
},
"aside": { # said to someone else nearby, not to Lumi
"en": [
("Mom, look, it's talking!", "Hi there! Yes, I can talk."),
("Hey Jake, come see this.", "Hi Jake! Come on over."),
("Wait, let me take a photo of it.", "Sure, I'll hold still."),
("Kids, don't touch the arm!", "Thank you, that's safer for everyone."),
],
"ko": [
("엄마 이거 봐 말한다!", "안녕하세요! 네, 저 말할 수 있어요."),
("민수야 이리 와 봐!", "민수 님도 어서 오세요."),
("잠깐만, 사진 좀 찍을게.", "네, 가만히 있을게요."),
("얘들아, 팔은 만지지 마.", "고마워요. 그게 더 안전해요."),
("부장님, 이것 좀 보십시오.", "안녕하십니까, 반갑습니다."),
("여보, 이리 와 봐요.", "어서 오세요, 같이 보셔도 돼요."),
],
},
"answer": { # a short answer to Lumi's own question
"en": [
("Yes.", "Great, glad to hear it."),
("No, not really.", "That's okay."),
("Maybe.", "Fair enough, no need to decide now."),
("Just looking around.", "Take your time, there's a lot to see."),
("My son loves robots.", "Then he's in the right place."),
],
"ko": [
("네.", "좋아요."),
("아니요.", "괜찮아요."),
("글쎄요.", "천천히 생각하셔도 돼요."),
("그냥 구경 왔어요.", "편하게 둘러보세요."),
("아들이 로봇 좋아해서요.", "그럼 잘 오셨네요."),
("아닙니다.", "알겠습니다."),
],
},
"hint_tease": { # hints, teasing and endings that are not orders
"en": [
("Wow, you're SO fast.", "Ha, I know, 0.6 metres a second. Safety first."),
("It's a bit loud here.", "It is busy. I'll do my best to hear you."),
("Can I take you home with me?", "I'd love to, but I'm 96 kilos and the team would miss me."),
],
"ko": [
("와 진짜 빠르다~", "하하, 사람보다 느리죠. 안전이 먼저라서요."),
("목이 좀 마른데...", "목마르시군요. 물은 직원분께 여쭤보시면 좋을 것 같아요."),
("나 로봇 동아리거든.", "와, 그럼 로봇에 대해 잘 아시겠네요."),
("아까 다른 로봇은 춤추더라.", "그 로봇은 춤을 잘 추나 봐요. 저는 춤은 못 춰요."),
("너 쿳션에서 만들었지?", "네, 맞아요. 쿳션에서 저를 만들었어요."),
("말 놓아도 돼?", "편하게 말씀하세요. 저는 계속 존댓말로 할게요."),
("오늘 좀 덥습니다.", "네, 오늘은 좀 덥네요."),
("여기 좀 시끄럽네요.", "네, 사람이 많네요. 잘 들으려고 노력할게요."),
],
},
# end of bank
}
+147 -33
View File
@@ -10,6 +10,7 @@ The robot network has no internet; the Thor reaches it through its own Wi-Fi. A
import html
import datetime
import json
import math
import os
import re
import sys
@@ -24,7 +25,10 @@ PROXY_FILE = ROOT / "data" / "proxy.txt" # e.g. http://192.168.10.200:8
DEFAULT_PLACE = "Seoul"
UA = {"User-Agent": "Mozilla/5.0 (X11; Linux aarch64) LumiRobot/1.0"}
_online = {"time": 0.0, "ok": False}
PLACES = {"seoul": {"name": "Seoul", "latitude": 37.57, "longitude": 126.98}} # known places: no geocoding request
PLACES = {"seoul": {"name": "Seoul", "latitude": 37.57, "longitude": 126.98}, # known places: no geocoding request
"incheon airport": {"name": "Incheon Airport", "latitude": 37.46, "longitude": 126.44}, # the geocoder has
"gimpo airport": {"name": "Gimpo Airport", "latitude": 37.56, "longitude": 126.79}} # towns, no airports
FIXED = list(PLACES.values())
# Korean names -> the English name the geocoder knows (it finds 부산 as a village "Pusan", 제주 not at all, "Jeju" in Ethiopia)
KO_PLACES = {
"서울": "Seoul", "부산": "Busan", "인천": "Incheon", "대구": "Daegu", "대전": "Daejeon", "광주": "Gwangju",
@@ -36,6 +40,7 @@ KO_PLACES = {
"베이징": "Beijing", "상하이": "Shanghai", "홍콩": "Hong Kong", "타이베이": "Taipei", "방콕": "Bangkok",
"싱가포르": "Singapore", "하노이": "Hanoi", "다낭": "Da Nang", "뉴욕": "New York", "런던": "London",
"파리": "Paris", "타슈켄트": "Tashkent", "사마르칸트": "Samarkand",
"인천공항": "Incheon Airport", "인천국제공항": "Incheon Airport", "김포공항": "Gimpo Airport",
"jeju": "Jeju City", "seongnam": "Seongnam-si", "yongin": "Yongin-si", # the plain English name is found elsewhere
}
@@ -79,39 +84,93 @@ def now_text():
WEATHER_CODES = {0: "clear sky", 1: "mainly clear", 2: "partly cloudy", 3: "overcast", 45: "fog", 48: "fog",
51: "light drizzle", 53: "drizzle", 55: "heavy drizzle", 61: "light rain", 63: "rain",
65: "heavy rain", 71: "light snow", 73: "snow", 75: "heavy snow", 80: "rain showers",
81: "rain showers", 82: "violent rain showers", 95: "thunderstorm", 96: "thunderstorm with hail"}
51: "light drizzle", 53: "drizzle", 55: "heavy drizzle", 56: "freezing drizzle", 57: "freezing drizzle",
61: "light rain", 63: "rain", 65: "heavy rain", 66: "freezing rain", 67: "freezing rain",
71: "light snow", 73: "snow", 75: "heavy snow", 77: "snow grains", 80: "rain showers",
81: "rain showers", 82: "violent rain showers", 85: "snow showers", 86: "snow showers",
95: "thunderstorm", 96: "thunderstorm with hail", 99: "thunderstorm with hail"}
WEATHER_DAYS = 7 # days of forecast given ("tomorrow", "모레", "this weekend")
def weather(place=DEFAULT_PLACE):
"""Current weather and today's range as a short English text, or None without internet."""
"""Weather now and the days ahead as a short English text, or None without internet."""
place = en_place(place or DEFAULT_PLACE) or DEFAULT_PLACE
key = place.lower()
if key in _weather and time.time() - _weather[key][0] < WEATHER_TTL:
return _weather[key][1]
try:
loc = PLACES.get(key)
loc = _place(place)
if not loc:
g = json.loads(_get("https://geocoding-api.open-meteo.com/v1/search?count=1&name=" + urllib.parse.quote(place)))
if not g.get("results"):
return f"I could not find a place called {place}."
loc = PLACES[key] = g["results"][0]
return f"I could not find a place called {place}."
w = json.loads(_get(
f"https://api.open-meteo.com/v1/forecast?latitude={loc['latitude']}&longitude={loc['longitude']}"
"&current=temperature_2m,weather_code,wind_speed_10m&daily=temperature_2m_max,temperature_2m_min,"
"precipitation_probability_max&timezone=auto&forecast_days=1"))
"&current=temperature_2m,weather_code,wind_speed_10m&daily=weather_code,temperature_2m_max,"
f"temperature_2m_min,precipitation_probability_max&timezone=auto&forecast_days={WEATHER_DAYS}"))
c, d = w["current"], w["daily"]
text = (f"Weather in {loc['name']}: {WEATHER_CODES.get(c['weather_code'], 'unknown')}, "
f"{c['temperature_2m']:.0f} degrees now, today {d['temperature_2m_min'][0]:.0f} to "
f"{d['temperature_2m_max'][0]:.0f} degrees, chance of rain {d['precipitation_probability_max'][0]} percent, "
f"wind {c['wind_speed_10m']:.0f} km/h.")
days = []
for i, day in enumerate(d["time"]):
name = datetime.date.fromisoformat(day).strftime("%A %d %B")
name = f"Today ({name})" if i == 0 else f"Tomorrow ({name})" if i == 1 else name
days.append(f"{name}: {WEATHER_CODES.get(d['weather_code'][i], 'unknown')}, {d['temperature_2m_min'][i]:.0f} "
f"to {d['temperature_2m_max'][i]:.0f} degrees, chance of rain "
f"{d['precipitation_probability_max'][i]} percent.")
text = (f"Weather in {loc['name']} now: {WEATHER_CODES.get(c['weather_code'], 'unknown')}, "
f"{c['temperature_2m']:.0f} degrees, wind {c['wind_speed_10m']:.0f} km/h.\n" + "\n".join(days))
_weather[key] = (time.time(), text)
return text
except Exception:
return None
def _place(place):
"""{name, latitude, longitude} of a place (English or a Korean name of KO_PLACES), or None; geocoded once."""
place = en_place(place)
key = place.lower()
if key not in PLACES:
if re.search(r"[가-힣]", place): # the geocoder finds Korean names wrong (강릉: a village in the North)
return None
g = json.loads(_get("https://geocoding-api.open-meteo.com/v1/search?count=1&name=" + urllib.parse.quote(place), 3))
if not g.get("results"):
return None
PLACES[key] = g["results"][0]
return PLACES[key]
TOWN = 50000 # people; a smaller place of the geocoder's is not taken for a distance (often a namesake)
HOW_FAR = re.compile(r"\bhow far\b|\bdistance\b|거리", re.I)
BETWEEN = (re.compile(r"\b(?:from|between)\s+(?:the\s+)?(.+?)\s+(?:to|and)\s+(?:the\s+)?(.+?)(?:\s+by \w+)?[?.!\s]*$", re.I),
re.compile(r"\bhow far (?:away )?is (?:the\s+)?(.+?) from (?:the\s+)?(.+?)(?:\s+by \w+)?[?.!\s]*$", re.I),
re.compile(r"([가-힣A-Za-z]+(?: [A-Za-z]+)*)에서 ([가-힣A-Za-z]+(?: [A-Za-z]+)*)까지"),
re.compile(r"\bdistance (?:of )?(?:the\s+)?(.+?) (?:to|and) (?:the\s+)?(.+?)[?.!\s]*$", re.I), # the LLM's
re.compile(r"^(?:distance |how far )?([A-Za-z가-힣]+) ([A-Za-z가-힣]+) (?:거리|distance)", re.I), # queries
re.compile(r"^(?:the )?(.+?) distance (?:from|to) (?:the )?(.+?)[?.!\s]*$", re.I),
re.compile(r"\bhow far (?:away )?is (?:the\s+)?(.+?)[?.!\s]*$", re.I), re.compile(r"([가-힣]+)까지"))
# the two places of "how far": the last two forms are from here (Seoul)
def _distance(query):
"""The straight-line distance between the two places a "how far" question names (one: from Seoul), or ''."""
if not HOW_FAR.search(query):
return ""
for form in BETWEEN:
m = form.search(query)
if m:
names = m.groups() if len(m.groups()) == 2 else (DEFAULT_PLACE, m.group(1))
break
else:
return ""
a, b = (_place(DEFAULT_PLACE if re.fullmatch(r"here|this place|you|여기", n.strip(), re.I) else n.strip())
for n in names)
if not a or not b or any(p.get("population", 0) < TOWN and p not in FIXED for p in (a, b)): # "the moon": a
# village in France
return ""
la1, lo1, la2, lo2 = map(math.radians, (a["latitude"], a["longitude"], b["latitude"], b["longitude"]))
km = 2 * 6371 * math.asin(math.sqrt(math.sin((la2 - la1) / 2) ** 2 +
math.cos(la1) * math.cos(la2) * math.sin((lo2 - lo1) / 2) ** 2))
return (f"Straight-line distance from {a['name']} to {b['name']}: about {km:,.0f} km ({km / 1.609:,.0f} miles); "
f"by road or rail it is longer.")
def keep_weather_fresh(place=DEFAULT_PLACE):
"""Background thread: refresh the weather before the cache runs out, so a question gets it at once."""
import threading
@@ -132,32 +191,55 @@ BROWSER = {"User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KH
"Safari/537.36", "Accept-Language": "ko-KR,ko;q=0.9,en-US;q=0.8,en;q=0.7"}
WIKI_UA = {"User-Agent": "LumiRobot/1.0 (https://cutshion.com; cutshion@cutshion.com)"} # Wikimedia answers 429
# (too many requests) to a browser or bare robot name; a name with a contact it serves
SEARCH_WAIT_S = 3.0 # s all sources get together; a slower one is left out (Naver ~0.5 s, Wikipedia ~1.5 s)
PAGE_CHARS = 1800 # chars of the search page given to the LLM (it reads ~1000 tokens a second)
BLOCK_CHARS = 700 # ... at most this much from one part of the page (an answer box, the news, one site)
WIKI_CHARS = 600 # chars of the Wikipedia summary
SEARCH_WAIT_S = 2.0 # s the search page and Wikipedia get together; a slower one is left out (both ~0.7 s)
NEWS_WAIT_S = 1.2 # s from the start the headlines get (Google News 0.4-1.6 s): the answer waits on them;
# SEARCH_WAIT_S when the news is what is asked (NEWS_ASKED)
NEWS_ASKED = re.compile(r"\bnews\b|headlines?|happening|going on|뉴스|소식", re.I)
PAGE_CHARS = 1200 # chars of the search page given to the LLM (it reads ~1300 tokens a second; Korean
# is ~1 token a char): the answer box and the first sites hold the answer
BLOCK_CHARS = 500 # ... at most this much from one part of the page (an answer box, the news, one site)
WIKI_CHARS = 500 # chars of the Wikipedia summary
NEWS_ITEMS = 3 # headlines given, only for questions about what changes (NEWSY)
SEARCH_TTL = 600 # s a search result is reused (visitors ask the same things; follow-ups search again)
SKIP_BLOCKS = re.compile(r'ad_section|data-meta-ssuid="(influencer|clip|image|qra|shortents|ex_csa|shopping)"|'
r"가격비교|플러스 스토어|브라우저를 업데이트하세요") # Naver page parts that never answer a question
r"가격비교|플러스 스토어|브라우저를 업데이트하세요|함께 가볼만한 장소") # Naver page parts that never answer a question
JUNK = re.compile(r"새 창 열림|새 창으로 열기|Keep에 (저장|바로가기)|Keep 바로가기|문서 저장하기|AI 출처 정보.*?자세히 보기|"
r"이 (광고|정보)가 표시된 이유|정보확인 레이어 닫기|레이어 닫기|이전으로 이동|다음으로 이동|이전 다음|"
r"동영상 바로재생( 버튼)?|펼치기|접기|공유하기|차트를 불러오는 중입니다\.|"
r"환율을 (계산할|변환하는) 국가를 선택( [가-힣]+)+|환율우대 \d+%|환율우대없음")
r"환율을 (계산할|변환하는) 국가를 선택( [가-힣]+)+|환율우대 \d+%|환율우대없음|"
r"이 키워드를 선택한 인원 [\d,]+|길찾기|거리뷰|펼쳐보기|더보기|알림받기|네이버 고객센터|관련도순 최신순|"
r"최신 콘텐츠 채널\(계정\).*?자동으로 구성됩니다\.|(정보확인 내용 열고 닫기|본인참여 관리) .*") # disclaimers at a box's end
NEWSY = re.compile(r"news|latest|recent|lately|today|tonight|yesterday|\bnow\b|current|this (week|month|year|season)|"
r"\blast\b|\bnext\b|\bnew(est)?\b|upcoming|\bwon\b|\bwin|champion|score|result|standing|leading|"
r"president|prime minister|minister|\bceo\b|coach|mayor|\bpope\b|chairman|governor|secretary|"
r"\bwho('s| is| are) the\b|price|stock|cost|\brates?\b|election|event|"
r"release|happening|going on|뉴스|소식|최근|최신|요즘|오늘|어제|지금|현재|올해|이번|작년|지난|다음|우승|"
r"결과|순위|경기|대통령|총리|장관|대표|감독|시장|교황|회장|총장|총재|가격|주가|시세|얼마|선거|발표|출시|요금|"
r"어느 팀|소속", re.I)
# questions about what changes: they get the news headlines (who holds an office, who won lately)
ASKED_AS = ((r"\bhow (tall|high)\b", "height"), (r"\bhow long\b", "length"), (r"\bhow old\b", "age"),
(r"\bhow far\b", "distance"), (r"\bhow deep\b", "depth"), (r"\bhow (big|large)\b", "size"),
(r"\bhow many people\b", "population"), (r"\bhow much\b", "price"), (r"\bwhat time\b", "hours"),
(r"\bwho won\b", "winner"), (r"\bwhere is\b", "location")) # English question -> what a search engine wants
KO_ASK = ((r"\bhow old\b|\bage\b|\bbirthday\b|\bwhen was \w+( \w+)? born\b", "나이"),
(r"\bhow tall\b|\bheight\b", "키"), (r"\bstocks?( price)?\b|\bshares?( price)?\b", "주가"),
(r"\bindex\b|(?=\b(nasdaq|dow jones|kospi|kosdaq|s&p 500)\b)", "지수"),
(r"\bstandings?\b|\bfirst place\b|\bin first\b|\branking\b", "순위"),
(r"\bscore\b|\bresult\b|\blast (game|match)\b|\bhow did\b", "경기 결과"),
(r"\bopening hours\b|\bwhat time does\b|\bwhen does\b", "영업시간"))
# English question -> the Korean word for Naver's answer box (ko_box_query)
ASK_WORDS = re.compile(r"\b(what'?s|what|who'?s|who|whom|which|where|when|why|how|is|are|was|were|the|a|an|do|does|did|"
r"can|could|you|tell me|please|lumi|right now|i|me|my|and|he|she|his|her|it|its|they|their)\b|"
r"[?,.!]", re.I)
CURRENCIES = {"USD": ("US dollar", r"dollars?|usd|달러"), "EUR": ("euro", r"euros?|eur\b|유로"),
"JPY": ("Japanese yen", r"\byen\b|jpy|엔화"), "CNY": ("Chinese yuan", r"yuan|renminbi|cny|위안"),
"JPY": ("Japanese yen", r"\byen\b|jpy|엔화|(?<=[\d만] )엔|(?<=[\d만])엔"), "CNY": ("Chinese yuan", r"yuan|renminbi|cny|위안"),
"GBP": ("British pound", r"pounds? sterling|british pounds?|gbp|파운드"),
"VND": ("Vietnamese dong", r"vietnamese dong|vnd|동화"), "THB": ("Thai baht", r"baht|thb|바트"),
"KRW": ("Korean won", r"\bwons?\b|krw|원화")}
COINS = {"bitcoin": r"bitcoin|btc|비트코인", "ethereum": r"ethereum|\beth\b|이더리움", "ripple": r"\bxrp\b|ripple|리플",
"solana": r"solana|솔라나", "dogecoin": r"doge|도지"}
RATE_WORDS = re.compile(r"exchange|\brates?\b|convert|환율|환전|in (korean )?wons?\b|원으로|얼마", re.I)
RATE_WORDS = re.compile(r"exchange|\brates?\b|convert|환율|환전|in (korean )?wons?\b|\bto (krw|wons?|usd|dollars?)\b|"
r"\bkrw\b|원으로|얼마", re.I)
_searched = {} # query -> (time, text)
_pool = ThreadPoolExecutor(6)
@@ -179,25 +261,42 @@ def keywords(query):
return re.sub(r"\s+", " ", ASK_WORDS.sub(" ", q)).strip() or query
def _naver(query):
def _naver(query, boxes_only=False):
"""The Naver results page as text: answer boxes (exchange rates, stocks, people, sports), web pages, news, blogs;
ads, shopping and image strips left out. '' when nothing is found. Naver answers scripts like a browser and
has live answer boxes; it reads English questions too."""
has live answer boxes; it reads English questions too. boxes_only: the answer boxes alone (the web results
and news have a data-meta-area)."""
page = _get("https://search.naver.com/search.naver?query=" + urllib.parse.quote(query), 4, BROWSER)
parts = []
for block in re.split(r'(?=<div class="_scrollLog")', page)[1:]:
if SKIP_BLOCKS.search(block[:3000]):
if SKIP_BLOCKS.search(block[:3000]) or boxes_only and 'data-meta-area="' in block[:1500]:
continue
text = re.sub(r"\s+", " ", JUNK.sub(" ", _text(block))).strip()
if len(text) > 20:
if len(text) > 20 and not text.startswith("함께 가볼만한"): # places nearby
parts.append(text[:BLOCK_CHARS])
return "\n".join(parts)[:PAGE_CHARS]
return "\n".join(parts)[:BLOCK_CHARS if boxes_only else PAGE_CHARS]
def ko_box_query(query):
"""An English question about a person, a share, an index, a team or a place as its names and the Korean word
that brings Naver's answer box ("How old is Taylor Swift?" -> "Taylor Swift 나이": birth date and age; the
English words give only web pages), or None."""
if re.search(r"[가-힣]", query):
return None
for asked, word in KO_ASK:
if re.search(asked, query, re.I):
names = re.sub(asked, " ", query, flags=re.I)
names = re.sub(r"'s\b|\b(today|now|currently|doing|in|at|of|for|right|this|last|latest|current|much|"
r"open|close|first|price|their|team)\b", " ", names, flags=re.I)
names = re.sub(r"\s+", " ", ASK_WORDS.sub(" ", names)).strip()
return f"{names} {word}" if names else None
return None
def _duckduckgo(query):
"""Titles and snippets from DuckDuckGo, or ''; only when Naver fails (DuckDuckGo often asks scripts to solve a
picture puzzle)."""
page = _get("https://html.duckduckgo.com/html/?q=" + urllib.parse.quote(query), 4, BROWSER)
page = _get("https://html.duckduckgo.com/html/?q=" + urllib.parse.quote(query), 2.5, BROWSER)
hits = re.findall(r'class="result__a"[^>]*>(.*?)</a>.*?class="result__snippet"[^>]*>(.*?)</a>', page, re.S)
return "\n".join(f"{_text(t)}: {_text(s)}" for t, s in hits[:6])[:PAGE_CHARS]
@@ -242,6 +341,10 @@ def _money(query):
won = rates["KRW"] / rates[c]
lines.append(f"1 {CURRENCIES[c][0]} = {won:,.2f} Korean won" + (f" (100 yen = {won * 100:,.0f} won)" if
c == "JPY" else "") + (f" = {1 / rates[c]:,.4f} US dollars" if c != "USD" else ""))
m = re.search(r"(\d[\d,]*(?:\.\d+)?)\s*(만)?\s*(?:" + CURRENCIES[c][1] + ")", query, re.I)
if m: # "100 dollars", "1만 엔": the sum worked out
amount = float(m.group(1).replace(",", "")) * (10000 if m.group(2) else 1)
lines.append(f"{amount:,.0f} {CURRENCIES[c][0]} = {won * amount:,.0f} Korean won")
lines.append(f"(exchange rates of {r['time_last_update_utc'][:16]})")
coins = [c for c, words in COINS.items() if re.search(words, query, re.I)]
if coins:
@@ -293,10 +396,11 @@ def with_ages(text, today=None):
return BIRTH_YEAR.sub(either, text)
def search(query, n=4):
def search(query, n=NEWS_ITEMS):
"""Text to answer a question from, fetched at the same time: exchange rates and coin prices when asked, the
Naver results page (DuckDuckGo when Naver fails), a Wikipedia summary and Google News headlines. "No results." when nothing is found,
None without internet. (Bing returns unrelated pages to scripts.)"""
query = re.sub(r"[<>]", " ", query).strip() # the LLM wrote "search <flight time Seoul NY>"
lang = "ko" if re.search(r"[가-힣]", query) else "en"
q = re.sub(r"\b(what|who|whom|is|are|was|were|the|a|an|about|tell me|more|please|latest|news|today'?s?|any|how|"
r"do|does|did|you|know|can|could|of|lumi)\b|[?,.!]", " ", query, flags=re.I)
@@ -306,9 +410,19 @@ def search(query, n=4):
return _searched[key][1]
jobs = {"Rates and prices": _pool.submit(_money, query)} if RATE_WORDS.search(query) or \
any(re.search(w, query, re.I) for w in COINS.values()) else {}
if HOW_FAR.search(query):
jobs["Distance"] = _pool.submit(_distance, query)
box = ko_box_query(query)
if box: # "Taylor Swift 나이": Naver's people box
jobs["Answer box"] = _pool.submit(_naver, box, True)
jobs |= {"Search results": _pool.submit(_naver, keywords(query)), "Wikipedia": _pool.submit(_wikipedia, q, lang)}
jobs["News headlines"] = _pool.submit(_news, q, lang, n) # names who holds an office or won lately
wait(jobs.values(), timeout=SEARCH_WAIT_S)
if NEWSY.search(query): # "how old is Musk?" got "80-year-old Musk's father"
jobs["News headlines"] = _pool.submit(_news, q, lang, n)
t0 = time.time()
wait([j for name, j in jobs.items() if name != "News headlines"], timeout=SEARCH_WAIT_S)
if "News headlines" in jobs:
wait([jobs["News headlines"]], timeout=max(0.0, (SEARCH_WAIT_S if NEWS_ASKED.search(query) else NEWS_WAIT_S)
- (time.time() - t0)))
found = {}
for name, job in jobs.items():
try:
+4 -2
View File
@@ -91,8 +91,8 @@ def markers(t):
t = re.sub(rf"(?<!\d )(?<![a-z] point ){_P}\s*[.-]?\s*({'|'.join(EN_NUM)})(?![a-z])(?!\s*{UNIT}\b)",
lambda m: f"p{EN_NUM[m.group(1)]}", t) # "point three", "p two"
t = re.sub(rf"{_P}\s*({ko}|{_SINO}){_KO_END}", lambda m: f"p{_num(m.group(1))}", t) # "피쓰리", "포인트 삼"
t = re.sub(r"\b(to|from|at) (the )?(?:piece|peace|pee|pea|pit|pi|pe) ?(\d+)\b", # whisper's "go to piece 6"
lambda m: f"{m.group(1)} {m.group(2) or ''}p{m.group(3)}", t)
t = re.sub(rf"\b(to|from|at|go) (the )?(?:piece|peace|pee|pea|pit|pi|pe) ?(\d+|{'|'.join(EN_NUM)})\b", # whisper's
lambda m: f"{m.group(1)} {m.group(2) or ''}p{_num(m.group(3))}", t) # "go to piece six"
t = re.sub(r"\b(p\d+)\s+(?:point|포인트)(?![a-z])(?!\s*(?:a|b|\d)(?![a-z]))", r"\1", t) # "p10 point"
return t
@@ -229,6 +229,8 @@ def map_names(t, names):
ASR_SLIPS = [ # how whisper writes Korean commands (tests/asr_check.py, 2026-10-21) -> as said
(r"([a-z0-9])\.?\s+(으로|로)\s*(?=가|와|이동|돌아)", r"\1\2 "), # "P3. 로가줘", "final point. 로 가": one word
(r"(?<=로)\s*가죠(?![가-힣])", " 가 줘"), # "p3로 가 줘" written "p3로 가죠"
(r"\blook (?:last|lest|less)(?=[\s.!,]*$)", "look left"), (r"\bdoc t\b", "dock 2"), # said at the end
(r"고게(?=\s*(?:들|숙))", "고개"), (r"찝어", "집어"), (r"파이나(?=\s*(?:갔|가|로))", "파이널"),
]