Improve seeing and memory answers
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
+164
-58
@@ -31,9 +31,10 @@ PLACE_M = 1.5 # m; within this of a marker Lumi is "at" it
|
||||
SEEN_SAME_S = 600 # s; the same thing at the same place again within this only updates the time
|
||||
SEEN_SCORE = 0.3 # detections weaker than this are not kept (seeing.DESCRIBE_SCORE)
|
||||
MIN_TURNS = 2 # a talk of fewer turns is not saved
|
||||
RECALL_MIN = 0.40 # cosine of the question's topic words to a talk's title + summary; below: not offered
|
||||
# (r6 train: 118 / 120 meant talks over it; a near one offered is a question, not a yes)
|
||||
WORD_BONUS = 0.2 # added when a topic word is in the talk's own words
|
||||
RECALL_MIN = 0.62 # cosine of the question's topic words to a talk (English or Korean title + summary)
|
||||
# when none of its words was said; unrelated short topics score 0.3-0.5, meant 0.5-0.8
|
||||
RECALL_PART = 0.50 # the cosine needed when only some of the topic words are the talk's own
|
||||
RECENT_TURNS = 3 # a recalled talk is "it" / "what you said" for this many turns after
|
||||
RECALL_OFFER = 3 # at most this many talks offered one after another
|
||||
IDLE_WAIT_S = 900 # s a summary waits for Lumi to be idle (no talk) before it is made anyway
|
||||
EARLIER_N = 5 # visitor lines with facts kept from turns that left the LLM's window
|
||||
@@ -93,7 +94,8 @@ TODAY = re.compile(r"\btoday(?![a-z])|\bthis (?:morning|afternoon|evening)(?![a-
|
||||
YESTERDAY = re.compile(r"\byesterday(?![a-z])|\blast night(?![a-z])|어제|어젯밤", re.I)
|
||||
TOO_OLD = re.compile(r"\b(?:last|past|previous) (?:week|month|year|monday|tuesday|wednesday|thursday|friday|saturday|sunday)(?![a-z])|"
|
||||
r"\b(?:a|one|two|three|several|few|\d+) (?:weeks?|months?|years?) ago\b|\b(?:three|four|five|\d+|few|several) days ago\b|"
|
||||
r"\blong (?:time )?ago\b|지난 ?(?:주|달|해|번 ?주)|저번 ?(?:주|달)|며칠 ?전|"
|
||||
r"\blong (?:time )?ago\b|\b(?:last|past|previous) weekend\b|\b(?:a|one|last) week (?:ago|back)\b|"
|
||||
r"지난 ?(?:주|달|해|번 ?주)|저번 ?(?:주|달)|며칠 ?전|(?:사흘|나흘|닷새|엿새|열흘|보름) ?(?:전|前)|"
|
||||
r"(?:[3-9]|세|네|다섯|여러) ?일 ?전|(?:[2-9]|두|세|네|다섯|여러) ?(?:주|달|개월|년) ?전|일주일 ?전|한 ?달 ?전|작년|옛날", re.I)
|
||||
DAY_BEFORE = re.compile(r"\bday before yesterday(?![a-z])|\btwo days ago(?![a-z])|그저께|그제(?![가-힣])|이틀 ?전", re.I)
|
||||
ONLY_TWO_DAYS = {"en": "I only remember the last two days.", "ko": "저는 최근 이틀 동안의 일만 기억해요."}
|
||||
@@ -231,8 +233,9 @@ HAND_Q = re.compile( # questions about the hand / arm now (not orders: "open y
|
||||
r"\b(?:are|do) you (?:holding|have|carrying) (?:anything|something)(?: in your (?:hand|gripper))?\b|"
|
||||
r"\bwhat(?:'s| is) (?:in|on) your (?:hand|gripper)\b|\bstate of your (?:hand|arm|gripper)\b|"
|
||||
r"(?:손|팔|그리퍼|arm|hand|gripper)(?:은|는|이|가)?\s*(?:지금\s*)?(?:어디|어떻게|(?:무슨|어떤)\s*상태|상태)|"
|
||||
r"(?:손|그리퍼)(?:은|는|이|가)?\s*(?:지금\s*)?(?:펴져|펼쳐져|벌어져|열려|닫혀|오므려져|쥐어져|비어|비었)\s*(?:있)?(?:어|니|나|나요|어요|습니까|있어|있니|있나요|있어요)?\s*\?|"
|
||||
r"손에\s*(?:뭐|뭔가|무엇|아무것도)\s*(?:있|들|쥐)", re.I)
|
||||
r"(?:손|그리퍼)(?:은|는|이|가)?\s*(?:지금\s*)?(?:펴져|펼쳐져|벌어져|열려|닫혀|오므려져|쥐어져|비어|비었|펴졌|열렸|닫혔|오므려졌|쥐어졌)\s*(?:있)?(?:어|니|나|나요|어요|습니까|있어|있니|있나요|있어요|냐|노|나요)?\s*\?|"
|
||||
r"(?:팔|arm)(?:은|는|이|가)?\s*(?:지금\s*)?(?:어떤|무슨)\s*자세|"
|
||||
r"(?:손|hand|gripper|그리퍼)에\s*(?:뭐|뭔가|무엇|뭘|아무것도|든 거|있는 거)(?:을|를|이|가)?\s*(?:있|들|쥐|잡|가지)", re.I)
|
||||
ARM_WHERE = {"look": ("My arm is in its resting pose, folded in front of me.", "팔은 앞에 접어 둔 기본 자세예요."),
|
||||
"ready": ("My arm is in its ready pose.", "팔은 준비 자세예요."),
|
||||
"carry": ("My arm is in its carry pose, close to my body.", "팔은 물건을 나르는 자세로 몸 가까이 있어요."),
|
||||
@@ -272,7 +275,8 @@ def self_answer(text, lang="en"):
|
||||
ko = lang == "ko"
|
||||
if PLACE_Q.search(text):
|
||||
return None if not _state.get("place") else \
|
||||
f"지금 {_state['place']}에 있어요." if ko else f"I'm at {_state['place']} right now."
|
||||
("지금 홈에 있어요." if _state["place"] == "home" else f"지금 {_state['place']} 근처에 있어요.") if ko \
|
||||
else f"I'm at {_state['place']} right now."
|
||||
if LIFT_Q.search(text):
|
||||
mm = _state.get("lift")
|
||||
if mm is None:
|
||||
@@ -363,17 +367,20 @@ def _thing_words(e, lang):
|
||||
return seeing._a(e["name"], e.get("colour"))
|
||||
|
||||
|
||||
def seen_answer(text, lang="en", now=None):
|
||||
"""The answer to "did you see an apple today?" from what was kept, else None (not such a question)."""
|
||||
if not SEEN_Q.search(text) or NOW_Q.search(text):
|
||||
return None
|
||||
days = _asked_days(text)
|
||||
def seen_answer(text, lang="en", now=None, days="ask"):
|
||||
"""The answer to "did you see an apple today?" from what was kept, else None (not such a question). days: a
|
||||
follow-up ("and a green apple?") asks the days of the question before."""
|
||||
if days == "ask":
|
||||
if not SEEN_Q.search(text) or NOW_Q.search(text) and _asked_days(text) is None: # "오늘 사과 본 적 있어요?"
|
||||
return None
|
||||
days = _asked_days(text)
|
||||
if days == "too old":
|
||||
return ONLY_TWO_DAYS[lang]
|
||||
name = _object(text)
|
||||
if name is None:
|
||||
return None # a thing the cameras can't name: the LLM, with the seen list
|
||||
now = clock() if now is None else now
|
||||
_recall["seen"] = (now, days)
|
||||
from assistant import seeing
|
||||
seen = [e for e in _load("seen") if e["name"] == name]
|
||||
hits = [e for e in seen if days is None or _day(e["t"], now) in days]
|
||||
@@ -467,8 +474,9 @@ def keep_talk(history, person=None, t=None, chat=None, embed=None, name=None):
|
||||
s = summarise(history, chat)
|
||||
if not s["title"] and not s["summary"]:
|
||||
return None
|
||||
s.update(t=clock() if t is None else t, person=person, name=name,
|
||||
vec=[round(float(x), 4) for x in embed([f"{s['title']}. {s['summary']}"])[0]])
|
||||
en, ko = embed([f"{s['title']}. {s['summary']}", f"{s['title_ko']}. {s['summary_ko']}"])
|
||||
s.update(t=clock() if t is None else t, person=person, name=name, vec=[round(float(x), 4) for x in en],
|
||||
vec_ko=[round(float(x), 4) for x in ko]) # a Korean question is matched to the Korean words too
|
||||
with _lock:
|
||||
talks = _load("talks")
|
||||
talks.append(s)
|
||||
@@ -513,23 +521,27 @@ RECALL_Q = re.compile( # a question about an earlier talk; "I remember when ..
|
||||
r"\bdid we have (?:a|any) (?:talk|chat|conversation)\b|\bdid i (?:tell|give) you\b|\bwhat (?:we|you) (?:said|told me|talked about)\b|"
|
||||
r"(?:말해|알려|얘기해|이야기해) ?(?:줬|주었|드렸)(?:던|었|지|잖|죠)|(?:했던|나눴던|한) (?:얘기|이야기|대화)|"
|
||||
r"(?:얘기|이야기|대화)\s*(?:\S+\s+)?(?:했잖|했었|했던|나눴)|무슨\s*(?:topic|주제)(?:였|이었)|"
|
||||
r"기억(?:나|해|하니|하세요|하시|하냐|하지|하죠|나요|날|하고|하는지|할)|(?:얘기|이야기|대화|말)(?:를|을)?\s*(?:했던|했었|나눴|나누었|한 거|했지|했잖|했는|했죠|했어)",
|
||||
r"기억\s*(?:이\s*)?(?:나|해|하|날)|생각\s*(?:이\s*)?나|"
|
||||
r"(?:얘기|이야기|대화|말)(?:를|을)?\s*(?:했던|했었|나눴|나누었|나누셨|하셨|한 거|했지|했잖|했는|했죠|했어|했노|했나|했니|했냐|했더라|했습니까|했을까)",
|
||||
re.I)
|
||||
NOT_RECALL = re.compile(r"\bremember (?:to|that you|my|me)\b|\bremember me\?$|\b(?:i|we) (?:don'?t |do not )?remember\b|"
|
||||
r"\b(?:can|could|will|would) you remember\b(?! (?:what|when|our|that we|we))|기억력|기억해\s*(?:줘|주세요|둬|놔)", re.I)
|
||||
GENERIC = re.compile(r"\b(?:what|which) did (?:we|i) (?:talk|speak|chat|say)(?: about)?\W*(?:today|yesterday|earlier|last time|before)?\W*$|"
|
||||
r"무슨 ?(?:얘기|이야기|대화|말)|뭐(?:라고)? ?(?:얘기|이야기|말)", re.I)
|
||||
_ASK_EN = r"^\W*(?:(?:please|lumi|ok(?:ay)?|now|just|and|so|hey|can you|could you|would you|will you)\W+)*"
|
||||
FORGET = re.compile( # an order to forget: "did you forget me?", "제 이름 잊어버렸어요?" are not
|
||||
_ASK_EN + r"(?:forget (?:this|me|everything|all (?:of )?(?:this|that|it)|what (?:i|we) (?:said|told|talked)|"
|
||||
r"our (?:talk|chat|conversation)|(?:this|that|the) (?:talk|chat|conversation)|about me|my name)\b|"
|
||||
r"(?:delete|erase|clear|remove) (?:this|our|my|the) (?:conversation|talk|chat|data|memory|memories)\b|"
|
||||
r"don'?t (?:remember|keep|save|store) (?:this|me|that|our|anything|what|any(?:thing)? of (?:this|it|that))\b|"
|
||||
r"(?:wipe|erase|delete|clear|remove|forget) (?:out )?(?:what (?:we|i) (?:said|talked about|told you|discussed)|it all|everything|"
|
||||
FORGET = re.compile( # an order to forget: "did you forget me?", "제 이름 잊어버렸어요?", "I forget what we said" are not
|
||||
r"(?<!\bdid you )(?<!\bdo you )(?<!\bhave you )(?<!\bwill you )(?<!\bi )(?<!\bwe )(?<!n't )(?<!\bnot )(?<!\bnever )\b"
|
||||
r"(?:forget (?:this|me|everything|all (?:of )?(?:this|that|it)|what (?:i|we) (?:said|told|talked|discussed|chatted)|"
|
||||
r"(?:our|this|that|the|my) (?:talk|chat|conversation|data|info)|about (?:me|this|our talk)|my name|i was here)\b|"
|
||||
r"(?:delete|erase|clear|remove|wipe) (?:out )?(?:this|our|my|the|that) (?:conversation|talk|chat|data|memory|memories|record|records|history)\b|"
|
||||
r"(?:wipe|erase|delete|clear|remove) (?:out )?(?:what (?:we|i) (?:said|talked about|told you|discussed)|it all|everything|"
|
||||
r"all (?:of )?(?:it|that|this)|my (?:data|info|information|details))\b)|"
|
||||
r"(?:얘기|이야기|말|대화|기록|내용|정보)(?:을|를|은|는)?\s*(?:다\s*|전부\s*|모두\s*)?(?:지워|삭제|잊어)|"
|
||||
r"잊어\s*(?:줘|주세요|주라|버려|버리세요|줄래|줄래요|주실래요|주시겠어요)(?![가-힣])|잊어버려(?:요)?(?![가-힣])|잊으세요|"
|
||||
r"기억(?:에서)?\s*(?:지워|삭제)|기억하지\s*마|(?:대화|기록)\s*(?:지워|삭제)", re.I)
|
||||
r"\bdon'?t (?:remember|keep|save|store) (?:this|me|that|our|anything|what|any(?:thing)? of (?:this|it|that))\b|"
|
||||
r"\b(?:you )?(?:didn'?t|did not|wouldn'?t) (?:keep|save|store|record|remember) (?:that|this|it|any of (?:this|that|it)|our)\b|"
|
||||
r"(?:얘기|이야기|말|대화|기록|내용|정보|데이터|메모리|history|record|data)(?:을|를|은|는|도)?\s*(?:다\s*|전부\s*|모두\s*|싹\s*|좀\s*)?"
|
||||
r"(?:지워|지우|지아|삭제|잊어|잊어버|없애|delete|erase|forget|remove|clear|wipe)|"
|
||||
r"잊어\s*(?:줘|주세요|주라|주십시오|주시겠|주시기|주실래|주시면|줄래|줄 수|버려|버리|삐|뿌|도\s*돼|도 됩|달라)|잊어버려(?:요)?(?![가-힣])|"
|
||||
r"잊으세요|잊으십시오|잊어라|잊어 ?도(?![가-힣])|기억(?:에서)?\s*(?:지워|삭제|없애)|기억하지\s*(?:마|말아|마세요|마십시오|말아 ?주)|"
|
||||
r"(?:대화|기록)\s*(?:지워|삭제)|^\W*(?:다\s*)?지워\s*(?:줘|주세요|주십시오|주실래요|줄래)\W*$|(?:delete|forget|erase|remove)\s*(?:해|하|시켜)\s*(?:줘|주|줄|라|요|봐)", re.I)
|
||||
FORGOT = {"en": "Okay, I've forgotten our conversation.", "ko": "네, 우리 대화는 잊을게요."}
|
||||
CANT_REMEMBER = {"en": "I can't remember that.", "ko": "그건 기억이 안 나요."}
|
||||
OFFER_WAIT_S = 60 # s a "do you mean ...?" waits for yes / no
|
||||
@@ -558,22 +570,25 @@ def _offer(s, lang, first=True, now=None):
|
||||
if lang == "ko":
|
||||
return f"{'' if first else '아니면 '}{when(s['t'], 'ko', now)}에 {_title_ko(s)}에 대해 " \
|
||||
f"이야기한 거 말씀이세요?"
|
||||
title = s["title"][:1].lower() + s["title"][1:] if s["title"][1:2].islower() else s["title"] # not "TV", "NASA"
|
||||
return f"{'Do you mean' if first else 'Or was it'} our talk about {title} " \
|
||||
return f"{'Do you mean' if first else 'Or was it'} our talk about {_lower(s['title'])} " \
|
||||
f"{when(s['t'], 'en', now)}?"
|
||||
|
||||
|
||||
def _lower(title):
|
||||
return title[:1].lower() + title[1:] if title[1:2].islower() else title # not "TV", "NASA"
|
||||
|
||||
|
||||
def _title_ko(s):
|
||||
return s.get("title_ko") or f"'{s['title']}'"
|
||||
|
||||
|
||||
def _told(s, lang, detail=False):
|
||||
def _told(s, lang, detail=False, turn=-99):
|
||||
"""The answer once a talk is confirmed (or its details asked): its summary and facts; None in Korean when the
|
||||
talk has no Korean summary (the LLM then says it from the talk in its prompt)."""
|
||||
_recall.update(talk=s, offered=[], left=[])
|
||||
_recall.update(talk=s, offered=[], left=[], turn=turn)
|
||||
facts = " ".join(f if f.endswith(".") else f + "." for f in s.get("facts", [])[:3])
|
||||
if lang == "ko":
|
||||
ko = s.get("facts_ko") if detail else s.get("summary_ko")
|
||||
ko = (s.get("facts_ko") or s.get("summary_ko")) if detail else s.get("summary_ko")
|
||||
return f"{'' if detail else '네, 기억나요. '}{' '.join(ko) if isinstance(ko, list) else ko}" if ko else None
|
||||
if detail:
|
||||
return f"I told you that {facts[:1].lower() + facts[1:]}" if facts else f"We talked about this: {s['summary']}"
|
||||
@@ -585,38 +600,99 @@ spoken chat chatted chatting discuss discussed conversation conversations say sa
|
||||
that this it its was were is are had have has yesterday today tonight earlier morning afternoon evening last time before ago
|
||||
day days two right again what which so and oh going back to in on at of with still can could would will any something thing
|
||||
things then there when where how much go ahead just okay ok well there's what's we've i've you've anything that's again,
|
||||
tell, remember, now yes yeah no""".split())
|
||||
tell, remember, now yes yeah no topic topics subject subjects um uh hmm oh wait right pls bro hey talk? chatted?
|
||||
by way anyway also too stuff""".split())
|
||||
_STOP_KO = re.compile(r"^(?:기억|얘기|이야기|대화|말|했|한|하|어제|오늘|아까|그저께|그제|이틀|우리|저|제가|내가|나랑|저랑|저와|나와|"
|
||||
r"루미|그때|그거|그것|뭐|무슨|나눴|나누|거|것|요|혹시|있잖|맞|좀|다시|알려|아침|오전|오후|저녁|지난|전에|"
|
||||
r"그래서|결론|요점|그러니까|줄|주|줘|알|있|없|해|할|뭔|어떤|무엇|어디|언제|remember|recall|talk|yesterday|today)")
|
||||
r"그래서|결론|요점|그러니까|줄|주|줘|알|있|없|해|할|뭔|어떤|무엇|어디|언제|이었|였|이에|예요|입니|이야|주제|remember|recall|talk|yesterday|today)")
|
||||
_KO_TAIL = re.compile(r"(?:에\s*대해서?|에\s*관해서?|이랑|랑|하고|얘기|이야기|은|는|을|를|도|에|의|요)+$")
|
||||
|
||||
|
||||
FOCUS = re.compile(r"\babout\b(.+)|\b(?:remember|recall)\b(.+)|((?:[가-힣A-Za-z0-9']+\s+){0,2}[가-힣A-Za-z0-9']+)\s*"
|
||||
r"(?:에\s*대해서?|에\s*관해서?|에\s*대한|얘기|이야기)", re.I)
|
||||
|
||||
|
||||
def topic(text):
|
||||
"""The words of a recall question that name its topic ("remember we talked about birds yesterday?" -> "birds");
|
||||
"" when it names none ("what did we talk about?")."""
|
||||
"" when it names none ("what did we talk about?"). The words after "about" / "remember" or before "얘기" first,
|
||||
so a filler ("Class, listen: ...", "Jason, look") is not taken for a topic."""
|
||||
m = FOCUS.search(text)
|
||||
part = next((g for g in m.groups() if g), text) if m else text
|
||||
return (_words(part) if m else "") or _words(text)
|
||||
|
||||
|
||||
def _words(text):
|
||||
out = []
|
||||
for w in re.findall(r"[A-Za-z][A-Za-z'.-]*|[가-힣]+|\d+", text):
|
||||
if re.match(r"[A-Za-z]", w):
|
||||
if w.lower().strip(".'") not in _STOP_EN and len(w) > 1:
|
||||
out.append(w.lower().strip(".'"))
|
||||
elif not _STOP_KO.match(w):
|
||||
else:
|
||||
w = re.sub(r"^(?:우리|저랑|나랑|제가|내가)(?=[가-힣]{1,})", "", w) # "우리달 얘기" (no space)
|
||||
if _STOP_KO.match(w):
|
||||
continue
|
||||
w = _KO_TAIL.sub("", w)
|
||||
if w and not _STOP_KO.match(w):
|
||||
out.append(w)
|
||||
return " ".join(out)
|
||||
|
||||
|
||||
def _hits(words, s):
|
||||
"""The share of the topic words found in a talk's own words (English and Korean title, summary, facts); a
|
||||
one-syllable Korean word only alone or with a particle ("달" is not in "달해요")."""
|
||||
text = " ".join([s["title"], s["summary"], s.get("title_ko", ""), s.get("summary_ko", "")] + s.get("facts", [])).lower()
|
||||
n = 0
|
||||
for w in words:
|
||||
if w.isascii():
|
||||
n += w in text or len(w) > 3 and w.rstrip("s") in text
|
||||
elif len(w) > 1:
|
||||
n += w in text
|
||||
else:
|
||||
n += bool(re.search(rf"(?<![가-힣]){w}(?:[은는이가을를도의]|에서|에)?(?![가-힣])", text))
|
||||
return n / len(words) if words else 0.0
|
||||
|
||||
|
||||
def _rank(about, talks, embed):
|
||||
"""The talks that may be the one meant, best first. The words decide first (the embedding of one or two words
|
||||
is weak: unrelated short topics score 0.3-0.5); a talk none of whose words were said needs a close meaning."""
|
||||
import numpy as np
|
||||
q = embed([about])[0]
|
||||
words = [w for w in about.split() if len(w) > 2 or not w.isascii()]
|
||||
out = []
|
||||
for s in talks:
|
||||
cos = max(float(np.dot(q, s["vec"])), float(np.dot(q, s["vec_ko"])) if s.get("vec_ko") else 0.0)
|
||||
hit = max(_hits(words, s), _title_said(about, s))
|
||||
if hit >= 0.99 or hit and cos >= RECALL_PART or cos >= RECALL_MIN:
|
||||
out.append((hit, cos, s))
|
||||
return [s for _, _, s in sorted(out, key=lambda x: (-x[0], -x[1]))]
|
||||
|
||||
|
||||
def _title_said(about, s):
|
||||
"""1.0 when every word of the talk's title (English or Korean) was said: "부산 날씨랑 새 얘기" names both the talk
|
||||
"부산 날씨" and the talk "새"."""
|
||||
said = set(about.lower().split())
|
||||
for title in (s["title"], s.get("title_ko") or ""):
|
||||
ws = [w for w in _words(title).split() if len(w) > 2 or not w.isascii()]
|
||||
if ws and all(w in said or len(w) > 3 and w.rstrip("s") in {x.rstrip("s") for x in said} for w in ws):
|
||||
return 1.0
|
||||
return 0.0
|
||||
|
||||
|
||||
PRONOUN = re.compile(r"\b(?:it|that|this|then|that time)\b|그거|그것|그때|그 ?얘기|그 ?이야기|거기", re.I)
|
||||
|
||||
|
||||
def recall(text, lang="en", now=None, embed=None, history=()):
|
||||
"""The answer to "do you remember we talked about birds?" and to the yes / no after it, else None. history: the
|
||||
talk now (a topic of this talk: "what were we saying about the moon?" is the LLM's, not a memory)."""
|
||||
from assistant import brain
|
||||
now = clock() if now is None else now
|
||||
past = list(history[:-1] if history and history[-1][0] == text else history)
|
||||
about = topic(text)
|
||||
if _recall["offered"] and now - _recall["at"] < OFFER_WAIT_S:
|
||||
other_q = HAND_Q.search(text) or SEEN_Q.search(text) or PLACE_Q.search(text) or LIFT_Q.search(text)
|
||||
if _recall["offered"] and now - _recall["at"] < OFFER_WAIT_S and not other_q:
|
||||
yes = brain.confirm_answer(text)
|
||||
if yes == "yes" or yes == "correction" and re.match(r"\W*(?:yes|yeah|yep|right|exactly|네|응|맞아|그래)\b", text, re.I):
|
||||
return _told(_recall["offered"][-1], lang)
|
||||
return _told(_recall["offered"][-1], lang, turn=len(past))
|
||||
if yes in ("no", "cancel") or yes == "correction" and re.match(r"\W*(?:no|nope|not that|아니|아뇨)\b", text, re.I):
|
||||
if yes == "cancel":
|
||||
_recall.update(offered=[], left=[])
|
||||
@@ -624,52 +700,47 @@ def recall(text, lang="en", now=None, embed=None, history=()):
|
||||
if _recall["left"]:
|
||||
s = _recall["left"].pop(0)
|
||||
_recall["offered"].append(s)
|
||||
_recall.update(at=now, talk=s)
|
||||
_recall.update(at=now, talk=s, turn=len(past))
|
||||
return _offer(s, lang, first=False, now=now)
|
||||
_recall.update(offered=[], left=[], talk=None)
|
||||
return CANT_REMEMBER[lang]
|
||||
if DO_SAID.search(text) and not NOT_DO.search(text):
|
||||
return do_said(text, lang, now)
|
||||
if _recall.get("talk") and DETAIL.search(text) and not about: # "remind me what you said", "결론이 뭐였어요?"
|
||||
return _told(_recall["talk"], lang, detail=True)
|
||||
out = do_said(text, lang, now)
|
||||
_recall["turn"] = len(past)
|
||||
return out
|
||||
recent = _recall.get("talk") and len(past) - _recall.get("turn", -99) <= RECENT_TURNS
|
||||
if recent and DETAIL.search(text) and (not about or PRONOUN.search(text) or _hits(about.split(), _recall["talk"]) >= 0.5):
|
||||
return _told(_recall["talk"], lang, detail=True, turn=len(past)) # "remind me what you said", "결론이 뭐였어요?"
|
||||
if NAME_Q.search(text):
|
||||
return name_answer(lang)
|
||||
if not (RECALL_Q.search(text) or SAID_THEN.search(text) and _asked_days(text) is not None) or NOT_RECALL.search(text):
|
||||
return None
|
||||
days = _asked_days(text)
|
||||
if about and days is None and any(w in a.lower() for _, a in history[:-1] for w in about.split()
|
||||
if len(w) > 2 or len(w) > 1 and not w.isascii()):
|
||||
return None # a topic Lumi spoke about in this talk: the LLM has it
|
||||
words = [w for w in about.split() if len(w) > 2 or len(w) > 1 and not w.isascii()]
|
||||
if words and days in (None, {0}) and any(w in f"{q} {a}".lower() for q, a in past for w in words):
|
||||
return None # a topic of this talk ("아까 배터리에 대해 뭐라고 하셨죠?"): the LLM has it
|
||||
if days == "too old":
|
||||
return ONLY_TWO_DAYS[lang]
|
||||
talks = [s for s in _load("talks") if (days is None or _day(s["t"], now) in days) and _mine(s)]
|
||||
if not talks:
|
||||
return ONLY_TWO_DAYS[lang] if days == {2} else CANT_REMEMBER[lang]
|
||||
return CANT_REMEMBER[lang]
|
||||
if not about: # "what did we talk about yesterday?": the talks of then
|
||||
ranked = sorted(talks, key=lambda s: s["t"])[-RECALL_OFFER:]
|
||||
if len(ranked) > 1:
|
||||
return _listed(ranked, days, lang)
|
||||
return _listed(sorted(talks, key=lambda s: s["t"])[-RECALL_OFFER:], days, lang, now, len(past))
|
||||
else:
|
||||
import numpy as np
|
||||
if embed is None:
|
||||
from assistant import knowledge
|
||||
embed = knowledge.embed
|
||||
q = embed([about])[0]
|
||||
words = [w for w in about.split() if len(w) > 2 or not w.isascii()]
|
||||
scored = sorted(((float(np.dot(q, s["vec"])) + WORD_BONUS * any(
|
||||
w in " ".join([s["title"], s["summary"], s.get("title_ko", "")] + s.get("facts", [])).lower() for w in words), s)
|
||||
for s in talks), key=lambda x: -x[0])
|
||||
ranked = [s for score, s in scored if score >= RECALL_MIN]
|
||||
ranked = _rank(about, talks, embed)
|
||||
if not ranked:
|
||||
return CANT_REMEMBER[lang]
|
||||
ranked = ranked[:RECALL_OFFER]
|
||||
_recall.update(offered=[ranked[0]], left=ranked[1:], at=now, talk=ranked[0], listed=[])
|
||||
_recall.update(offered=[ranked[0]], left=ranked[1:], at=now, talk=ranked[0], listed=[], turn=len(past))
|
||||
return _offer(ranked[0], lang, now=now)
|
||||
|
||||
|
||||
SAID_THEN = re.compile(r"\bwhat did you (?:say|tell me)\b|뭐라고\s*(?:하셨|했|말했|말씀하셨)|무슨 말(?:을|씀을)?\s*(?:했|하셨)", re.I)
|
||||
NAME_Q = re.compile(r"\b(?:you (?:still )?(?:remember|know|recall)|what(?:'s| is)) my name\b|\bremember my name\?|\bdid i (?:tell|give) you my name\b|\bwho (?:am|was) i\b|"
|
||||
r"(?:제|내|my) ?(?:이름|name)\s*(?:을|를|은|는)?\s*(?:기억|알아|아세요|아십니까|뭐|말했|말씀)", re.I)
|
||||
r"(?:제|내|my) ?(?:이름|name)\s*(?:을|를|은|는|이|가)?\s*(?:기억|알아|아세요|아십니까|아시|뭐|무엇|말했|말씀)", re.I)
|
||||
NO_NAME = {"en": "I don't remember you telling me your name. What is it?", "ko": "성함은 기억에 없어요. 성함이 어떻게 되세요?"}
|
||||
|
||||
|
||||
@@ -713,10 +784,18 @@ def do_said(text, lang="en", now=None):
|
||||
return f"{when(s['t'], 'en', now)[:1].upper() + when(s['t'], 'en', now)[1:]} we agreed: \"{cmd}\". Shall I do that now?"
|
||||
|
||||
|
||||
def _listed(talks, days, lang):
|
||||
""""Yesterday I talked about bibimbap, dinosaurs and Lumi's cameras." (the next turn's prompt has them all)."""
|
||||
def _listed(talks, days, lang, now=0.0, turn=-99):
|
||||
""""Yesterday I talked about bibimbap, dinosaurs and Lumi's cameras." (the next turn's prompt has them all). One
|
||||
talk: "Yesterday we talked about birds. Would you like to hear more?", and a yes tells it."""
|
||||
_recall.update(offered=[], left=[], talk=None, listed=talks)
|
||||
d = next(iter(days)) if days else None
|
||||
if len(talks) == 1:
|
||||
s = talks[0]
|
||||
_recall.update(offered=[s], talk=s, listed=[], at=now, turn=turn)
|
||||
if lang == "ko":
|
||||
return f"{ {None: '최근 이틀 동안', 0: '오늘은', 1: '어제는', 2: '그저께는'}[d]} {_title_ko(s)}에 대해 이야기했어요. 더 들어 보실래요?"
|
||||
return f"{ {None: 'In the last two days', 0: 'Today', 1: 'Yesterday', 2: 'The day before yesterday'}[d]} we talked " \
|
||||
f"about {_lower(s['title'])} at about {_clock(s['t'], 'en')}. Would you like to hear more?"
|
||||
if lang == "ko":
|
||||
names = ", ".join(_title_ko(s) for s in talks)
|
||||
return f"{ {None: '최근 이틀 동안', 0: '오늘은', 1: '어제는', 2: '그저께는'}[d]} {names}에 대해 이야기했어요. 더 듣고 싶은 이야기가 있으세요?"
|
||||
@@ -730,12 +809,39 @@ def _mine(s):
|
||||
return not (s.get("name") and _talk["name"] and s["name"] != _talk["name"])
|
||||
|
||||
|
||||
CHAT_EN = {"ur": "your", "u": "you", "pls": "please", "plz": "please", "da": "the", "dat": "that", "wat": "what", "r": "are"}
|
||||
|
||||
|
||||
def _clean(text):
|
||||
"""Whisper slips and chat spelling out: "w— what we talked" -> "what we talked", "is ur hand open" -> "is your
|
||||
hand open"."""
|
||||
text = re.sub(r"(?<![\w])(\w{1,3})\s*[—–-]+\s+(?=\1)", "", text)
|
||||
return re.sub(r"(?<![\w'])(?:ur|u|pls|plz|da|dat|wat|r)(?![\w'])", lambda m: CHAT_EN[m.group(0).lower()], text, flags=re.I)
|
||||
|
||||
|
||||
SEEN_MORE = re.compile(r"\W*(?:(?:and|what about|how about|or|then|so|also|그럼|그러면|그리고|아니면|또|혹시)\W+)*(?:the |an? |any )?"
|
||||
r"(?:[\w가-힣]+\s+)?([\w가-힣]+?)(?:은요|는요|이요|은|는|도|이나|나)?(?: either| too| then)?\W*", re.I)
|
||||
|
||||
|
||||
def _seen_more(text):
|
||||
""""And a green apple?", "그럼 빨간 컵은?": a short follow-up naming only a thing (a colour or one word before it),
|
||||
after a "did you see ...?" answer; "do you see an apple?", "그럼 빨간 컵 가져와" are not."""
|
||||
text = re.split(r"[:,;]\s*", text.strip())[-1] # "Right, use case: and a green apple?"
|
||||
m = SEEN_MORE.fullmatch(text)
|
||||
return bool(m and _object(m.group(1)) and (re.search(r"[??]|[은는도]\W*요?\W*$|^\W*(?:and|what about|how about|or)\b", text, re.I)))
|
||||
|
||||
|
||||
def reply(text, lang="en", now=None, history=()):
|
||||
"""What to say at once for a memory question ("forget this", "do you remember ...?", "did you see a cup today?"),
|
||||
else None. lumi.py asks it before the other routes."""
|
||||
text = _clean(text)
|
||||
if FORGET.search(text) and not re.search(r"\b(?:don'?t|never) forget\b|잊지\s*마", text, re.I):
|
||||
forget()
|
||||
return FORGOT[lang]
|
||||
now = clock() if now is None else now
|
||||
seen = _recall.get("seen")
|
||||
if seen and now - seen[0] < OFFER_WAIT_S and not SEEN_Q.search(text) and _seen_more(text):
|
||||
return seen_answer(text, lang, now, days=_asked_days(text) or seen[1] if _asked_days(text) != "too old" else seen[1]) # "흰 병 봤어?" -> "그럼 빨간 컵은?"
|
||||
return recall(text, lang, now, history=history) or seen_answer(text, lang, now) or self_answer(text, lang)
|
||||
|
||||
|
||||
|
||||
+111
-17
@@ -77,7 +77,7 @@ KO_CANON = ((r"있습니까|있나요|있냐|있니|있노|있는교|있심니
|
||||
(r"입니까|인가요|이냐|이니|이노|인교|입니꺼", "이야"), (r"(미터|명|개)고(?=\s*\?)", r"\1야"),
|
||||
(r"아닙니다|아입니다|아이다", "아니야"), (r"(?<=[가-힣])입니다", "이야"), (r"말씀해", "말해"),
|
||||
(r"(?<![가-힣])내(?=하고|랑)", "나"), (r"(?<![가-힣])니(?=하고|랑)", "너"), (r"(?:나|저)하고\s*(?:너|루미)하고", "나하고"),
|
||||
(r"(?<![가-힣])함(?=\s)", "한번"), (r"려어(?=놨|놓)", "려"), (r"(?<=[\s가-힣])(?:보십시오|보세요|봐요|보이소|봐라|봐\s*주세요|봐\s*줘)", "봐"))
|
||||
(r"(?<![가-힣])함(?=\s)", "한번"), (r"^(\W*(?:\S+\s+)?)(그럼|그러면|근데|그리고)(?=[가-힣])", r"\1\2 "), (r"려어(?=놨|놓)", "려"), (r"(?<=[\s가-힣])(?:보십시오|보세요|봐요|보이소|봐라|봐\s*주세요|봐\s*줘)", "봐"))
|
||||
EN_IN_KO = ((r"\bwhat\s*(?:colou?r|색)", "무슨 색"), (r"\bcolou?rs?\b", "색"), (r"\bwhich side\b", "어느 쪽"),
|
||||
(r"\b(?:you\s+)?see\b", "보여"), (r"\bhow far\b", "얼마나 떨어져"), (r"\bdistance\b", "거리"),
|
||||
(r"\bnow\b", "지금"), (r"\breally\b", "진짜"), (r"\bholding\b|\bhold\b", "들고"), (r"\bhow many\b", "몇"),
|
||||
@@ -94,7 +94,7 @@ EN_IN_KO = tuple((rx.replace(r"\b", r"(?<![A-Za-z])", 1).replace(r"\b", r"(?![A-
|
||||
KO_IN_EN = ((r"색깔?|컬러", "colour"), (r"상의|윗옷", "top"), (r"바지", "trousers"), (r"(?<![가-힣])(?:나|저)(?![가-힣])", "me"),
|
||||
(r"(?<![가-힣])(?:내|제)(?![가-힣])", "my"), (r"손가락", "fingers"), (r"주머니", "pocket"), (r"사람", "people"),
|
||||
(r"오른손", "right hand"), (r"왼손", "left hand"), (r"신발", "shoes"), (r"셔츠", "shirt"), (r"보여", "see"))
|
||||
EN_CANON = ((r"\bpeoples\b", "people"), (r"\bwhat (?:do )?i hold\b", "what am I holding"),
|
||||
EN_CANON = ((r"\bpeoples\b", "people"), (r"\b(is|are) dare\b", r"\1 there"), (r"\bready,? (?:set|steady),? go\b\W*", ""), (r"\bu\b", "you"), (r"\bda\b", "the"), (r"\bwhat (?:do )?i hold\b", "what am I holding"),
|
||||
(r"\bwhat i am (wearing|holding|doing)\b", r"what am I \1"), (r"\bwhat (?:clothes )?(?:do )?i wear(?:ing)?\b", "what am I wearing"),
|
||||
(r"\bwhat you see\b", "what do you see"), (r"\b(?:would|will) you be able to see\b|\bare you able to see\b", "can you see"),
|
||||
(r"^\W*(?:a |an |the )?(?!(?:do|does|can|could|would|will|did|i|you|and|so|what|which|how)\b)([a-z]+(?: [a-z]+)?) "
|
||||
@@ -173,6 +173,8 @@ def canon(t):
|
||||
t = self_fixed(t)
|
||||
for rx, to in KO_CANON:
|
||||
t = re.sub(rx, to, t)
|
||||
t = GLUED_COLOUR.sub(r"\1 ", t)
|
||||
t = re.sub(r"(?<![가-힣])(제|내)(?=머리|바지|옷|윗옷|셔츠|티셔츠|신발|모자|안경|가방|손|자세)", r"\1 ", t) # "제머리색 뭐예요?" # "분홍색바나나 보여?" -> "분홍색 바나나 보여?"
|
||||
if not re.search(r"[가-힣]", t):
|
||||
for rx, to in EN_CANON:
|
||||
t = re.sub(rx, to, t, flags=re.I)
|
||||
@@ -194,6 +196,8 @@ _THING_EN = r"(?:(?P<col>" + "|".join(c for c in COLOURS if c.isascii()) + r")\s
|
||||
_THING_KO = r"(?:(?P<col>" + "|".join(c for c in COLOURS if not c.isascii()) + r")\w*\s*)?(?<![가-힣])(?<!몇 )(?P<obj>" + \
|
||||
"|".join(sorted(KO_WORDS, key=len, reverse=True)) + r")(?=[\s?.,!~]|$|[은는이가을를도의에랑와과요야]|까지|하고)"
|
||||
# a whole word: not 연 (kite) in 연구소, 개 (dog) in "몇 개"
|
||||
GLUED_COLOUR = re.compile(r"((?:" + "|".join(c for c in COLOURS if not c.isascii()) + r")색)(?=(?:" +
|
||||
"|".join(sorted(KO_WORDS, key=len, reverse=True)) + r"))")
|
||||
|
||||
SEE_ME = re.compile(r"^\W*(?:wait,?\s*)?you see me\b|" r"(?<![가-힣])(?:나|저)\s*(?:를|가)?\s*잘\s*보여|" r"\b(do|can) you see me\b|\bam i (visible|in (your )?view)\b|(?<![가-힣])(나|저)(를|)? ?보여|(?<![가-힣])(나|저) ?보이|(?:내가|제가)\s*보여", re.I)
|
||||
SEE_THING = re.compile(r"(?<!what )\b(?:do|can|could) you (?:still )?(?:see|spot|notice)\b.*?\b(?:a|an|the|any|some|my)?\s*" + _THING_EN, re.I)
|
||||
@@ -247,13 +251,16 @@ SIDE_Q = re.compile(r"\bwhat(?:'s| is| do you see| can you see)? (?:there )?(?:o
|
||||
HOW_MANY = re.compile(r"\bhow many (?:people|persons|visitors|humans|folks|guys)\b|\bhow many of us\b|몇 ?(?:명|사람)|몇\s*분이?나?\s*(?:보여|있)|"
|
||||
r"몇\s*분\s*(?:이\s*)?계|\bcount (?:the )?(?:people|persons|heads|us)\b|사람\s*(?:count|how many)|"
|
||||
r"\bare we (?:\w+ )?(?:or|two|three|four)\b.*\bhow many\b|"
|
||||
r"^\W*(?:(?:and|so|okay)\W+)?(?:(?:지금|이제|now)\s*(?:은|는)?\s*how many|how many(?: do you see| are there)? now)\W*$",
|
||||
re.I) # "How many now?"
|
||||
r"^\W*(?:(?:and|so|okay)\W+)?(?:(?:지금|이제|now)\s*(?:은|는)?\s*how many|how many(?: do you see| are there)? now)\W*$|"
|
||||
r"\bhow many(?: (?:people|of us))?(?: do you see| are there| (?:are )?(?:here|left))? now\b",
|
||||
re.I) # "How many now?", "someone left. How many now?"
|
||||
NOT_IN_VIEW = re.compile(r"\b(?:work|works|working|employ\w*|staff|company|companies|campy|firm|cutshion|country|city|"
|
||||
r"live|lives|living|world|team|office|branch|developers?|engineers?|built|made|came|visited|talked|met)\b|"
|
||||
r"직원|회사|쿳션|일하|일해|근무|나라|국가|도시|살아|사는|인구|팀|지사|만든|만들|개발자|엔지니어|왔었|다녀갔|만났|얘기했|이야기했",
|
||||
re.I) # "how many people work at Cutshion?": the company, not the cameras
|
||||
HOLDING = re.compile(r"(?<![가-힣])손(?:에는|엔|에)\s*(?:뭐|뭘|무엇)(?:가|이)?\s*(?:들었|있|쥐|잡)|" r"\bi'?m holding (?:an? |the |my )?(?:\w+ )?\w+,? (?:right|correct|yes)\s*\?|" r"^\W*(?:\S+\s+)?(?:이거|이건|이게|이기|이것)\s*\S+\s*맞(?:죠|지|제|아|나요|습니까|나)|" r"(?:사람|분|person|친구)\S*\s*(?:은|는)?\s*(?:지금\s*)?(?:손에\s*)?(?:뭐|뭘|무엇을?)\s*(?:들었|들고|holding|쥐고)|" r"\bwhat (?:thing )?(?:do )?i hold\b|" r"\bwhat(?:'s| is| am| do)? (?:i|is (?:in|on) my (?:left |right |other )?hands?|(?:in|on) my (?:left |right |other )?hands?)\b.*?\b(?:holding|carrying|have)\b|"
|
||||
HOLDING = re.compile(r"\bi (?:just )?picked (?:something|it|this|that|one) up\b.*\bwhat\b|"
|
||||
r"(?:뭐|뭘|무엇을?|뭔가|하나)\s*(?:집었|주웠|잡았)\S*\W*(?:\S+\s+)?(?:뭐|뭔|무엇|what)|"
|
||||
r"(?<![가-힣])손(?:에는|엔|에)\s*(?:뭐|뭘|무엇)(?:가|이)?\s*(?:들었|있|쥐|잡)|" r"\bi'?m holding (?:an? |the |my )?(?:\w+ )?\w+,? (?:right|correct|yes)\s*\?|" r"^\W*(?:\S+\s+)?(?:이거|이건|이게|이기|이것)\s*\S+\s*맞(?:죠|지|제|아|나요|습니까|나)|" r"(?:사람|분|person|친구)\S*\s*(?:은|는)?\s*(?:지금\s*)?(?:손에\s*)?(?:뭐|뭘|무엇을?)\s*(?:들었|들고|holding|쥐고)|" r"\bwhat (?:thing )?(?:do )?i hold\b|" r"\bwhat(?:'s| is| am| do)? (?:i|is (?:in|on) my (?:left |right |other )?hands?|(?:in|on) my (?:left |right |other )?hands?)\b.*?\b(?:holding|carrying|have)\b|"
|
||||
r"\bwhat(?:'s| is)(?: it| this| that)? (?:in|on|with) my (?:left |right |other )?hands?\b|\bwhat(?:'s| is) my (?:left |right |other )?hands?\?|\bwhat (?:do )?i have (?:in|on) my (?:left |right |other )?hands?\b|\bam i holding\b|"
|
||||
r"\bis there (?:something|anything) in my hand\b|\bwhat is this\b(?=.*\bhand\b)|\bwhat am i hold in\b|\banything (?:in|on) my (?:left |right |other )?hands?\b|"
|
||||
r"\bwhat\b.{0,25}\b(?:i'?m|i am) (?:holding|carrying)\b|\bwhat(?:'ve| have| do) i (?:got|have)\b(?! to)|"
|
||||
@@ -362,7 +369,9 @@ _TYPES_EN = rf"{_UPPER}|{_LOWER}|{_FEET}|dress(?:es)?|vests?|blazers?|cardigans?
|
||||
WEAR_ITEM = re.compile(rf"\b(?:i'?ve got|i have|i'?m wearing|i am wearing)\s+(?:an?\s+)?(?:\w+\s+)?(?:{_TYPES_EN})(?:\s+on)?,?\s+(?:right|correct|yes|yeah)\s*\?|" rf"^\W*(?:\w+\s+)?(?:{_TYPES_EN}),?\s+(?:i'?m|am i)\s+right\s*\?|" rf"\b(?:{_TYPES_EN})\b or (?:an? )?(?:{_TYPES_EN})\b.{{0,20}}\b(?:i'?ve got on|i(?:'m| am) wearing|on me)\b|" rf"\b(?:am i|is (?:she|he|my friend|the other (?:person|guy|man|woman)))\s+(?:wearing|in|dressed in)\s+"
|
||||
rf"(?:a |an |any |my )?(?:[\w-]+\s+)?(?:{_TYPES_EN})\b|\bdo i have (?:a |an |any )?(?:\w+\s+)?(?:{_TYPES_EN}) on\b|"
|
||||
rf"(?:{_UPPER_KO}|{_LOWER_KO}|{_FEET_KO}|원피스|조끼|블라우스|후드|부츠|샌들)\s*(?:을|를)?\s*"
|
||||
r"(?:입었|입고|입으셨|입으신|신었|신고|신으셨)(?:\s*(?:있|계))?\S*\s*\??\W*$", re.I)
|
||||
r"(?:입었|입고|입으셨|입으신|신었|신고|신으셨)(?:\s*(?:있|계))?\S*\s*\??\W*$|"
|
||||
rf"(?:{_UPPER_KO}|{_LOWER_KO}|원피스)\S*\s*(?:입었|입고|입으셨)\S*\s*(?:아니면\s*|or\s*)?"
|
||||
rf"(?:{_UPPER_KO}|{_LOWER_KO}|원피스)\S*\s*(?:입었|입고|입으셨)", re.I) # "청바지 입었어 치마 입었어?"
|
||||
# "am I wearing a jacket?", "is she in jeans?", "청바지 입었어?"
|
||||
PATTERN_Q = re.compile(r"\bis this (?:\w+ )?(?:shirt|top|t-shirt|jacket|sweater|hoodie) (?:striped|checked|plain|printed|dotted|patterned)\b|" rf"\b(?:my|her|his)\s+(?:\w+\s+)?(?:{_UPPER}|{_LOWER}|clothes)\b.{{0,30}}\b(?:striped|stripes|stripy|checked|"
|
||||
r"checkered|plaid|patterns?|patterned|plain|printed|dotted|polka)\b|"
|
||||
@@ -390,7 +399,20 @@ FOLLOW_EN = re.compile(r"^\W*(?:(?:and|so|then|ok(?:ay)?|well|but|no|sorry|oh|al
|
||||
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)
|
||||
ABOUT_LUMI = re.compile(r"(?:루미|너|니가|네가|당신)(?:는|은|가|도|의)\s|(?<![가-힣])(?:너|니가|네가|당신)\s|루미\s+머리|^\W*넌|"
|
||||
r"\bare you\b|\byou(?:'re| are) wearing\b", re.I) # "루미 바지 무슨 색이야?": a call (Lumi wears none)
|
||||
VOCATIVE = re.compile(r"(?:루미|로봇|\blumi|\brobot|\bloomy|\brumi)\s*(?:(?:쌤|선생님|선배님?|프로|선수|님|아저씨|양반|친구|군|양|짱|사장님|"
|
||||
r"착하지|야|아)(?![가-힣])|씨)|"
|
||||
r"(?:루미|로봇)\s*[,!]|(?:^|(?<=[\s,]))(?:친구|동료)(?:야|아|님)?\s*[,!]", re.I)
|
||||
# "루미 씨, ...", "로봇 친구", "동료, 제 바지 ...": a call, not whom it is about
|
||||
FIRST_PERSON = re.compile(r"(?<![가-힣])(?:제가|내가|저는|나는|제|내|나|저(?!\s*(?:사람|분|쪽|기|거)))(?![가-힣])|"
|
||||
r"\b(?:i|me|my|mine|i'?m)\b", re.I)
|
||||
|
||||
|
||||
def _about_lumi(t):
|
||||
""""루미는 무슨 옷 입었어?", "루미 머리 무슨 색이야?": about Lumi; "루미 씨, 제 바지 무슨 색이에요?": about the speaker."""
|
||||
u = VOCATIVE.sub(" ", t)
|
||||
return bool(ABOUT_LUMI.search(u)) and not FIRST_PERSON.search(u)
|
||||
ONE = re.compile(r"(?P<col>" + "|".join(COLOURS) + r")\w*\s*(?:ones?|거|것|걸)?", re.I) # "the blue one", "파란 거"
|
||||
UP_ASKED = re.compile(r"\bup\b|\braised?\b|\braising\b|올라|올렸|손\s*(?:을\s*)?들(?:고|었)", re.I)
|
||||
HELD_ASKED = re.compile(r"\bhold|\bhave it\b|\bin my\b|\bit\b|\b(?:that|this) in\b|들고|쥐고|잡고|있(?:어|습|나|니)|들었게", re.I)
|
||||
@@ -844,6 +866,7 @@ def _clothes_answer(p, text, lang, looks=None):
|
||||
kinds = {part: _type_of(part, looks) for part in NOUN}
|
||||
asked = [(part, (kinds[part] if lang == "en" else TYPE_KO.get(kinds[part], w)) if kinds[part] and GENERIC.fullmatch(w) else w)
|
||||
for _, part, w in sorted(asked)] # "my bottoms" -> "your jeans" when the looks know the kind
|
||||
named = bool(asked) # pieces named: each one is answered, seen or not
|
||||
asked = asked or \
|
||||
[(part, (kinds[part] if lang == "en" else TYPE_KO.get(kinds[part])) if kinds[part] else NOUN[part][lang != "en"])
|
||||
for part in NOUN]
|
||||
@@ -858,7 +881,9 @@ def _clothes_answer(p, text, lang, looks=None):
|
||||
return _say(f"Your {w} {'look' if w.endswith('s') else 'looks'} {c}.",
|
||||
f"{_j(w, '은', '는')} {COLOUR_KO.get(c, c)}으로 보여요.", lang)
|
||||
shown = [(part, w, c) for part, w, c in seen if c]
|
||||
hidden = [w for _, w, c in seen if not c]
|
||||
hidden = [w for part, w, c in seen if not c and (named or part != "feet" or not seen[1][2])]
|
||||
# "what am I wearing?": shoes out of view are not said alone (the head camera seldom
|
||||
# sees the feet); with the trousers out of view too, both are
|
||||
if not shown:
|
||||
return _say("I can't see your clothes well enough to tell.", "옷이 잘 안 보여서 모르겠어요.", lang)
|
||||
en = [f"{c} {w}" for _, w, c in shown]
|
||||
@@ -957,7 +982,7 @@ FAMILY = {"t-shirt": "top", "tee": "top", "shirt": "top", "blouse": "top", "polo
|
||||
# what counts as the same kind of piece ("shirt" asked, a t-shirt seen: yes)
|
||||
EXACT = {"jeans": ("jeans", "jean", "genes", "청바지")} # asked by these words, only jeans is a yes
|
||||
PATTERN_ASKED = re.compile(r"\b(?:striped|stripes?|stripy|checked|checkered|chequered|plaid|patterns?|patterned|plain|"
|
||||
r"printed|prints?|dotted|dots|polka|logo)\b|무늬|줄무늬|체크|민무늬|프린트|그림|로고|도트|땡땡이", re.I)
|
||||
r"printed|prints?|dotted|dots|polka|logo)\b|무늬|줄무늬|체크(?!\s*(?:하|해|했|좀))|민무늬|프린트|그림|로고|도트|땡땡이", re.I)
|
||||
PATTERN_SAID = {"plain": ("plain", "무늬가 없어"), "striped": ("striped", "줄무늬가 있어"), "checked": ("checked", "체크무늬가 있어"),
|
||||
"printed": ("printed", "프린트가 있어"), "dotted": ("dotted", "물방울무늬가 있어")}
|
||||
LENGTHS = {"short": ("short", "짧아"), "medium": ("medium length", "중간 길이예요"), "long": ("long", "길어"),
|
||||
@@ -994,6 +1019,7 @@ PLURAL_WEAR = re.compile(r"\b(?:jeans|pants|trousers|shorts|leggings|shoes|sneak
|
||||
def _who(t):
|
||||
"""Whom a question about a person asks about: "front" (the one talking), "other", or "left" / "right" (the person
|
||||
on that side as Lumi sees it)."""
|
||||
t = VOCATIVE.sub(" ", t) # "로봇 친구, 제가 뭐 하고 있어요?": the speaker
|
||||
m = SIDE_WHO.search(t)
|
||||
if m:
|
||||
side = (m.group("s") or m.group("s2") or {"왼": "left", "오른": "right"}.get(m.group("k"))).lower()
|
||||
@@ -1232,7 +1258,8 @@ def _wearing_answer(t, p, frames, lang, slow_line, more, who):
|
||||
ko = _ko_thing(v)
|
||||
return _say(f"Yes, you {en_v} {noun}.", f"네, {_j(ko, '을', '를') if ko else obj} {verb} 계세요.", lang)
|
||||
word = {"glasses": "glasses", "hat": "a hat", "mask": "a mask", "bag": "a bag"}[acc]
|
||||
return _say(f"No, I don't see {word} on you.", f"아니요, {obj[:-1]}{'은' if obj[-2] in '경' else '는'} 안 보여요.", lang)
|
||||
return _say(f"No, you don't have {word} on." if acc != "bag" else "No, you don't have a bag.",
|
||||
f"아니요, {_j(obj[:-1], '은', '는')} 안 {verb} 계세요.", lang)
|
||||
|
||||
|
||||
def _hair_answer(t, looks, lang):
|
||||
@@ -1428,7 +1455,7 @@ def answer(text, lang="en", frames=None, slow_line=None):
|
||||
kind = own
|
||||
if kind == "posture" and (FAR_ME.search(t) or HOW_FAR.search(t)):
|
||||
kind = "far" # "how far am I standing?": the distance
|
||||
if kind in ("shirt", "wearing", "hair", "describe", "wear_item") and ABOUT_LUMI.search(t):
|
||||
if kind in ("shirt", "wearing", "hair", "describe", "wear_item") and _about_lumi(t):
|
||||
return None # "루미는 무슨 옷 입었어?": about Lumi, not the visitor
|
||||
_last["after"] = 0.0 # a new question: looks of the last LOOKS_S do
|
||||
if kind in PERSON_KINDS:
|
||||
@@ -1436,12 +1463,12 @@ def answer(text, lang="en", frames=None, slow_line=None):
|
||||
elif kind is None and last in PERSON_KINDS and _last["asked"] and (WHO_ELSE.search(t) or ME_AGAIN.search(t)):
|
||||
kind, t = last, _last["asked"][1] # "what about her?", "그 사람은?", "and me?": the same question
|
||||
_last["who"] = "other" if WHO_ELSE.search(text) else "front"
|
||||
if kind is None and last in SEE_KINDS and _last["thing"] and not ABOUT_LUMI.search(t) and \
|
||||
if kind is None and last in SEE_KINDS and _last["thing"] and not _about_lumi(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) or \
|
||||
if kind is None or kind == "how_many" and NOT_IN_VIEW.search(t) and not NOW_END.search(t) or \
|
||||
kind == "where" and _thing(WHERE_THING.search(t))[0] in BIG:
|
||||
return None # "where is the toilet?": the way there, not the cameras
|
||||
if kind == "far" and not (FAR_THING.search(t) or SEE_THING_KO.search(t)):
|
||||
@@ -1455,12 +1482,13 @@ def answer(text, lang="en", frames=None, slow_line=None):
|
||||
if not frames:
|
||||
return _say(*NO_CAMERA, lang)
|
||||
said = _reply(kind, t, frames, lang, slow_line, more)
|
||||
_last["state"] = _state(frames) # "and now?" next: what changed besides the question
|
||||
if _live(frames, more) and kind in PERSON_KINDS + ("see_me", "how_many", "closest", "friend"):
|
||||
threading.Thread(target=prefetch, args=(frames,), daemon=True).start() # the next question about them: at once
|
||||
return said
|
||||
|
||||
|
||||
CHANGED = re.compile(r"\bput (?:\w+ )?\w+ on\b|\boff\b|\bsit\b|\bstand\b|다른\s*(?:거|것|걸)\s*들었|벗었|벗어|썼어요|썼습니다|꼈|앉았|일어섰|일어났|내렸|내려놨|옮겼|바꿨|놨|놓았|\btook (?:it |them |my \w+ )?off\b|"
|
||||
CHANGED = re.compile(r"\bput (?:\w+ )?\w+ on\b|\boff\b|\bsit\b|\bstand\b|다른\s*(?:거|것|걸)\s*들었|벗었|벗어|썼어요|썼습니다|썼어(?=\s*[.,!])|꼈|앉았|일어섰|일어났|내렸|내려놨|옮겼|바꿨|놨|놓았|\btook (?:it |them |my \w+ )?off\b|"
|
||||
r"\bput (?:on|down|it down|them on)\b|\b(?:sat|stood) (?:down|up)\b|\bswitched\b|\bmoved\b|\bchanged\b|"
|
||||
r"\blowered\b|\bremoved\b|\b(?:is|are) (?:gone|off)\b|'s (?:gone|off)\b|\bnow\b|지금|이제", re.I)
|
||||
CHANGE_KINDS = ((r"선글라스|sunglasses", "wearing", "am I wearing sunglasses?", "선글라스 썼어?"),
|
||||
@@ -1493,7 +1521,7 @@ def _piece_of_someone(t):
|
||||
def _changed(t, last):
|
||||
""""I took my glasses off, now?", "모자를 벗었습니다. 지금은 쓰고 있습니까?", "앉았어요, 지금은?": the question about
|
||||
what they say changed, asked anew: (kind, words) or None."""
|
||||
if not (CHANGED.search(t) and (AGAIN.search(t) or "?" in t or re.search(r"어때|어떻|보여|보이", t))):
|
||||
if not (CHANGED.search(t) and (AGAIN.search(t) or "?" in t or re.search(r"어때|어떻|보여|보이|\bnow\W*$|\bwhich one\b", t, re.I))):
|
||||
return None
|
||||
for rx, kind, en, ko in CHANGE_KINDS:
|
||||
if re.search(rx, t, re.I):
|
||||
@@ -1615,8 +1643,10 @@ def _check(t, lang, frames, since, slow_line, more=None):
|
||||
return _say(f"I count {_n(n)} {'person' if n == 1 else 'people'} in view now, not {count}; someone may be out of "
|
||||
f"my view.", f"제 카메라에는 지금 {n}명이 보여요. 화면 밖에 계신 분이 있을 수도 있어요.", lang)
|
||||
if not (hand or said or denied or named):
|
||||
old, _last["state"] = _last.get("state"), _state(frames)
|
||||
got = _reply(kind, asked, frames, lang, slow_line, more)
|
||||
return got and _say("I looked again. ", "다시 봤어요. ", lang) + got
|
||||
moved = _changes(old, _last["state"], kind, lang) if NOW_ASKED.search(t) else ""
|
||||
return got and _say("I looked again. ", "다시 봤어요. ", lang) + got + moved
|
||||
p = scene.person_in_front(frames)
|
||||
if p is None:
|
||||
return _say("I can't see you well enough to tell. Could you step in front of me?",
|
||||
@@ -1669,6 +1699,70 @@ def _check(t, lang, frames, since, slow_line, more=None):
|
||||
return _verdict(o["colour"], said, denied, f"the {o['name']}", _ko_name(o["name"]), "looks", lang)
|
||||
|
||||
|
||||
NOW_END = re.compile(r"\bhow many\b[^.?!]{0,25}\bnow\W*$", re.I) # "my friend just came. How many now?": the view
|
||||
NOW_ASKED = re.compile(r"\bnow\b|\bknow\b|\bthis time\b|지금|이제|이번", re.I) # "and now?": a change is news too
|
||||
SKIP = {"posture": ("posture",), "holding": ("held",), "hand": ("held", "raised"), "raised": ("raised",),
|
||||
"wearing": ("glasses", "hat", "bag"), "how_many": ("n",), "doing": ("posture", "held", "raised")}
|
||||
# the fields the question itself answers: not said again as a change
|
||||
|
||||
|
||||
def _state(frames):
|
||||
"""What "and now?" compares: the person in front's posture, held things, raised hands, glasses / hat / bag (from
|
||||
looks already had, never a new VLM look) and the number of people; None when nobody is in front."""
|
||||
try:
|
||||
p = scene.person_in_front(frames)
|
||||
if p is None:
|
||||
return None
|
||||
lk = (p.get("looks") if "looks" in p else _cached_looks("front", p)) or {}
|
||||
held = {s: h["object"]["name"] for s, h in p["hands"].items() if h and h.get("object")}
|
||||
return {"posture": p.get("posture") or (lk.get("posture") if lk.get("posture") in POSE_SAID else None),
|
||||
"held": held if all(p["hands"].values()) or held else None, "raised": tuple(p["raised"]),
|
||||
**{k: lk.get(k) for k in ("glasses", "hat", "bag")}, "n": len(scene.people(frames))}
|
||||
except Exception as e: # noqa: BLE001 - stand-in cameras
|
||||
print(f"seeing: no state ({e})", flush=True)
|
||||
return None
|
||||
|
||||
|
||||
def _changes(old, new, kind, lang):
|
||||
"""" And now you're sitting.": what changed on the person in front since the answer before, beside what was asked
|
||||
again ("" when nothing did or either look is missing)."""
|
||||
if not old or not new:
|
||||
return ""
|
||||
en, ko = [], []
|
||||
skip = SKIP.get(kind, ())
|
||||
a, b = old["posture"], new["posture"]
|
||||
if "posture" not in skip and a and b and a != b:
|
||||
en.append(f"now you're {b}")
|
||||
ko.append({"standing": "지금은 서 계세요", "sitting": "지금은 앉아 계세요", "crouching": "지금은 쪼그려 앉아 계세요"}[b])
|
||||
a, b = old["held"], new["held"]
|
||||
if "held" not in skip and a is not None and b is not None and a != b:
|
||||
for s, x in b.items():
|
||||
if a.get(s) != x:
|
||||
en.append(f"now you're holding {_a(x)} in your {s} hand")
|
||||
ko.append(f"지금은 {KO_SIDE[s]}손에 {_j(_ko_name(x), '을', '를')} 들고 계세요")
|
||||
for x in set(a.values()) - set(b.values()):
|
||||
en.append(f"you're not holding the {x} any more")
|
||||
ko.append(f"이제 {_j(_ko_name(x), '은', '는')} 안 들고 계세요")
|
||||
a, b = old["raised"], new["raised"]
|
||||
if "raised" not in skip and a != b:
|
||||
en.append(f"your {' and '.join(b)} hand is up now" if b else "your hand is down now")
|
||||
ko.append(f"지금은 {'·'.join(KO_SIDE[x] + '손' for x in b)}을 들고 계세요" if b else "지금은 손을 내리셨어요")
|
||||
for k, on_en, on_ko, off_ko in (("glasses", "glasses", "안경을 쓰고 계세요", "안경을 벗으셨어요"),
|
||||
("hat", "a hat on", "모자를 쓰고 계세요", "모자를 벗으셨어요"),
|
||||
("bag", "a bag", "가방을 메고 계세요", "가방을 내려놓으셨어요")):
|
||||
a, b = old[k], new[k]
|
||||
if k in skip or a is None or b is None or bool(a) == bool(b):
|
||||
continue
|
||||
en.append(f"now you have {on_en}" if b else f"you've taken your {'glasses' if k == 'glasses' else k} off")
|
||||
ko.append(f"지금은 {on_ko}" if b else off_ko)
|
||||
if "n" not in skip and old["n"] != new["n"]:
|
||||
en.append(f"I see {_n(new['n'])} {'person' if new['n'] == 1 else 'people'} now")
|
||||
ko.append(f"지금은 {new['n']}명이 보여요")
|
||||
if not en:
|
||||
return ""
|
||||
return _say(" And " + ", and ".join(en) + ".", " 그리고 " + ". ".join(ko) + ".", lang)
|
||||
|
||||
|
||||
def _reply(kind, t, frames, lang, slow_line=None, more=None):
|
||||
"""The answer to a question of this kind (answer() read it) from these frames."""
|
||||
if kind == "behind":
|
||||
@@ -1761,7 +1855,7 @@ def _reply(kind, t, frames, lang, slow_line=None, more=None):
|
||||
f"네, 다른 사람 {n}명이 더 보여요.", lang)
|
||||
return _say("No, I only see you now." if p else "No, I don't see anyone right now.",
|
||||
"아니요, 지금은 한 분만 보여요." if p else "아니요, 지금은 아무도 안 보여요.", lang)
|
||||
if kind == "shirt" and (OTHER.search(t) or _last.get("who", "front") != "front"): # "what is my friend wearing?", "옆 사람 셔츠는 무슨 색이에요?"
|
||||
if kind == "shirt" and (OTHER.search(VOCATIVE.sub(" ", t)) or _last.get("who", "front") != "front"): # "what is my friend wearing?", "옆 사람 셔츠는 무슨 색이에요?"
|
||||
q = _someone(frames, _last.get("who") if _last.get("who", "front") != "front" else "other")
|
||||
if q is None:
|
||||
return _say("I only see you right now.", "지금은 한 분만 보여요.", lang)
|
||||
|
||||
Reference in New Issue
Block a user