From f2de0633a9a1f0b33b7eae93a71f41aa4bd6e43d Mon Sep 17 00:00:00 2001 From: Cutshion Date: Mon, 26 Oct 2026 03:14:07 +0900 Subject: [PATCH] Improve seeing people: clothes, hair, glasses and posture Co-Authored-By: Claude Opus 5.5 --- assistant/seeing.py | 924 +++++++++++++++++++++++++++++++++--- tests/test_seeing_people.py | 158 ++++++ vision/scene.py | 70 ++- 3 files changed, 1078 insertions(+), 74 deletions(-) create mode 100644 tests/test_seeing_people.py diff --git a/assistant/seeing.py b/assistant/seeing.py index d39896c..0e5bd00 100644 --- a/assistant/seeing.py +++ b/assistant/seeing.py @@ -40,9 +40,10 @@ COLOURS = {"white": "white", "red": "red", "blue": "blue", "green": "green", "ye "흰": "white", "하얀": "white", "빨간": "red", "파란": "blue", "초록": "green", "노란": "yellow", "검은": "black", "까만": "black", "주황": "orange", "회색": "grey", "보라": "purple", "분홍": "pink", "핑크": "pink", "하양": "white", "빨강": "red", "파랑": "blue", "노랑": "yellow", "검정": "black", "까망": "black", "갈색": "brown", "하늘": "light blue", - "브라운": "brown"} # "brown" is only said by people: the camera names browns orange + "브라운": "brown", "beige": "beige", "베이지": "beige"} # "brown", "beige" are only said by people: the camera + # names browns orange COLOUR_KO = {"white": "흰색", "red": "빨간색", "blue": "파란색", "green": "초록색", "yellow": "노란색", "black": "검은색", - "orange": "주황색", "grey": "회색", "purple": "보라색", "pink": "분홍색", "brown": "갈색", "light blue": "하늘색"} + "orange": "주황색", "grey": "회색", "purple": "보라색", "pink": "분홍색", "brown": "갈색", "light blue": "하늘색", "beige": "베이지색"} SYNONYMS = {"mug": "cup", "glass": "cup", "tumbler": "cup", "coffee": "cup", "phone": "cell phone", "mobile": "cell phone", "smartphone": "cell phone", "plant": "potted plant", "flower": "potted plant", "table": "dining table", "desk": "dining table", "monitor": "tv", "screen": "tv", "television": "tv", "computer": "laptop", @@ -69,6 +70,115 @@ KO_WORDS = {**{v: k for k, v in KO.items()}, "폰": "cell phone", "핸드폰": " "식탁": "dining table", "배낭": "backpack", "컴퓨터": "laptop", "티비": "tv", "가방": "handbag", "물병": "bottle", "탁자": "dining table"} +KO_CANON = ((r"있습니까|있나요|있냐|있니|있노|있는교|있심니꺼|있습니꺼|있는가|있나(?=\s*\?|$)", "있어"), + (r"보입니까|보이나요|보이냐|보이니|보이노|보이는교|보이십니까|보이세요|보이시나요|보이시죠|보이죠|보이는가|보입니꺼|보이나(?=\s*\?|$)", "보여"), + (r"하는\s*중이(?:게|야|에요|예요|냐|니|노|지)?|하고\s*있게", "하고 있"), (r"어데|어디메", "어디"), + (r"참말로|참말|레알", "진짜"), (r"무엇을", "뭘"), (r"무엇이", "뭐가"), (r"무엇", "뭐"), (r"뭣", "뭐"), + (r"입니까|인가요|이냐|이니|이노|인교|입니꺼", "이야"), (r"(미터|명|개)고(?=\s*\?)", r"\1야"), + (r"아닙니다|아입니다|아이다", "아니야"), (r"(?<=[가-힣])입니다", "이야"), (r"말씀해", "말해"), + (r"(?= en else [b, t, a] # "빨간 apple 보여?" -> "빨간 사과 보여?" first + + +def _swap(t, rules): + for rx, to in rules: + t = re.sub(rx, to, t, flags=re.I) + return t + + +_PIECE = r"\bhair\b|\bsunglasses\b|\bglasses\b|\bhats?\b|\bcaps?\b|\bmask\b|\bbag\b|\bbackpack\b|\bshirt\b|\bt-shirt\b|" \ + r"\btop\b|\bjacket\b|\bpants\b|\btrousers\b|\bjeans\b|\bshoes\b|\bskirt\b|\bshorts\b|" \ + r"머리|안경|선글라스|모자|마스크|가방|백팩|티셔츠|셔츠|상의|윗옷|웃옷|바지|청바지|하의|치마|신발|재킷|자켓" +SELF_FIX = re.compile(r"(?:\.{2,}|[,!?.]|\s)\s*(?:아\s+)?(?:아니(?:요|야)?|아냐|아뇨|no+|nope|sorry|wait|i mean|uh+|um+|er+|" + r"or rather)\b[\s,!.]*(?:(?:i mean|sorry|i meant)\b[\s,]*)?(?P[^?]*?)(?:,?\s*i mean)?\W*$", re.I) + + +def self_fixed(t): + """A thing named again after "no" / "아 아니" / "sorry, I mean" in the same question: the question about that one + ("do you see an umbrella... no, a teddy bear?" -> "do you see a teddy bear?"); else t.""" + m = SELF_FIX.search(t) + if not m or not m.group("rest"): + return t + rest, head = m.group("rest"), t[:m.start()] + piece = re.match(rf"(?:(?:a|an|the|my|내|제)\s+)?(?P{_PIECE})", rest, re.I) + if piece: # "what colour is my hat, uh, my hair?", "가방, 아니 모자 썼어?" + old = list(re.finditer(_PIECE, head, re.I)) + if old: + o = old[-1] + return head[:o.start()] + piece.group("w") + head[o.end():] + rest[piece.end():] + \ + ("?" if t.rstrip().endswith("?") else "") + new = re.fullmatch(r"(?:(?:a|an|the|my)\s+)?" + _THING_EN, rest, re.I) or \ + re.fullmatch(_THING_KO + r"(?:이|가|요|야|이야|이요)?", rest) + if not new or not _name(new.group("obj")): + return t + old = list(re.finditer(_THING_EN, head, re.I)) or list(re.finditer(_THING_KO, head)) + if not old: + return t + o = old[-1] + said = re.sub(r"^(?:the|a|an|my)\s+", "", new.group(0), flags=re.I) + return head[:o.start()] + said + head[o.end():].rstrip(" ?.!,") + "?" + + +def canon(t): + """A question in one plain form for the readers: Korean dialect and speech levels as 반말 ("사과 있냐?", "가방 어데 + 있노?", "보이십니까?"), English words in a Korean sentence as Korean ("바지 what color야?" -> "바지 무슨 색야?") and + Korean words in an English one as English ("What 색 is my 상의?"), non-native English as plain ("me far how + much?", "what clothes I wear?", "backpack is here?").""" + t = re.sub(r"\S*[—–]\s*", "", t) # a stutter: "있— 있어요", "O— Oh" + t = re.sub(r"\s*(?:\.{2,}|…)\s*$", "?", t) # trailing dots for a question mark + t = self_fixed(t) + for rx, to in KO_CANON: + t = re.sub(rx, to, t) + if not re.search(r"[가-힣]", t): + for rx, to in EN_CANON: + t = re.sub(rx, to, t, flags=re.I) + return t + + class _Any: """Several patterns asked as one: .search gives the first match (each has its own col / obj groups).""" def __init__(self, *rxs): @@ -85,12 +195,12 @@ _THING_KO = r"(?:(?P" + "|".join(c for c in COLOURS if not c.isascii()) + r "|".join(sorted(KO_WORDS, key=len, reverse=True)) + r")(?=[\s?.,!~]|$|[은는이가을를도의에랑와과요야]|까지|하고)" # a whole word: not 연 (kite) in 연구소, 개 (dog) in "몇 개" -SEE_ME = re.compile(r"\b(do|can) you see me\b|\bam i (visible|in (your )?view)\b|(나|저)(를|)? ?보여|(나|저) ?보이", re.I) +SEE_ME = re.compile(r"^\W*(?:wait,?\s*)?you see me\b|" r"(?left|right)(?: side)?\s*\?|" + r"\b(?:can|do) you see (?:what(?:'s| is)|anything|anyone|something) (?:on|to|at) (?:your|the) (?Pleft|right)\b|" + r"(?왼|오른)쪽에\s*(?:뭐|무엇|뭔가|누가|누구)\S*\s*(?:있|보여|보이)" + r"(?!.*(?:봐|보세요|봐\s*줘|봐\s*주세요|보십시오|봐라)\W*$)", re.I) + # "can you see what's on your right?", "왼쪽에 뭐 있어?": the cameras now (a question, + # not "peek / glance to your right": the look rule, brain) # behind you?" (a head turn) +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*$", @@ -137,7 +253,7 @@ NOT_IN_VIEW = re.compile(r"\b(?:work|works|working|employ\w*|staff|company|compa 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"\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"(?your|the|my)\s+(?Pleft|right)\b|\b(?:your|the)\s+(?Pleft|right)(?:-hand)?\s+(?:person|one)\b|" + r"(?P왼|오른)쪽\s*(?:에\s*)?(?:있는|계신|서\s*있는|앉은|앉아\s*있는)?\s*(?:사람|분|person|애|아이|친구)", re.I) + # "the person on your left", "왼쪽에 계신 분": the side as Lumi sees it ("on my left": theirs) OTHER = re.compile(r"\b(?:friend|colleague|partner|she|he|his|her|their)\b|\bthe (?:other|second) (?:person|guy|man|woman|one)\b|" r"\b(?:person|man|woman|guy|lady) (?:next to|beside|behind|with) me\b|친구|동료|옆\s*(?:에\s*)?(?:있는\s*)?(?:사람|분)|" - r"다른\s*(?:사람|분)|그\s*(?:사람|분)", re.I) # someone else than the person talking + r"다른\s*(?:사람|분)|그\s*(?:사람|분)|저\s*(?:사람|분)|그분|저분", re.I) # someone else than the person talking FRIEND = re.compile(r"\b(?:do|can) you (?:still )?see (?:my (?:friend|colleague)|the other (?:person|guy|man|woman))\b|" r"\bis (?:my (?:friend|colleague)|the other (?:person|guy|man|woman)) still (?:here|there|in view)\b|" r"(?:친구|동료|그\s*사람|다른\s*(?:사람|분)|옆\s*사람)\S*\s*(?:아직도?\s*|still\s*)?(?:보여|보이|있어|있나|있습)", re.I) -DOING = re.compile(r"\bwhat am i doing\b|\bwhat(?:'m| am) i up to\b|(?:내가|제가|나|저)\s*(?:지금\s*)?(?:뭐|뭘|무엇을?)\s*하고\s*있", re.I) -POSTURE = re.compile(r"\b(?:am i|is (?:he|she|my friend))\s+(?:\w+\s+)?(?:sitting|standing|seated|" +DOING = re.compile(r"(?:내가|제가)\s*(?:지금\s*)?(?:뭐|뭘|무엇을?)\s*하는지|" r"\bwhat i(?:'m| am) doing\b|" r"\bwhat (?:is|are) (?:he|she|they) doing\b|" r"\b(?:on|to) (?:your|the) (?:left|right),? what (?:is|are) (?:he|she|they) doing\b|" r"(?:사람|분|person|친구)\S*\s*(?:은|는)?\s*(?:지금\s*)?(?:뭐|뭘|무엇을?)\s*(?:해|하|하고|하는)|" r"\bwhat am i doing\b|\bwhat(?:'m| am) i up to\b|(?:내가|제가|나|저)\s*(?:지금\s*)?(?:뭐|뭘|무엇을?)\s*하고\s*있|" + r"\bwhat(?:'s| is) (?:she|he|my friend|the (?:other )?(?:person|man|woman|guy|lady)(?: (?:on|to) (?:your|the|my) (?:left|right))?) doing\b|" + r"(?:사람|분|person|친구)\S*\s*(?:은|는)?\s*(?:지금\s*)?(?:뭐|뭘|무엇을?)\s*(?:하고|하세요|하시|해)", re.I) +POSTURE = re.compile(r"\bi'?m on my feet\b|\bam i on my feet\b|" r"(?:내가|제가)\s*(?:지금\s*)?(?:앉아|서)\s*(?:있|계)는지|" r"\b(?:am i|is (?:he|she|my friend))\s+(?:\w+\s+)?(?:sitting|standing|seated|" r"crouching|squatting)\b|\b(?:sitting|standing|seated|crouching|squatting)\s+or\s+(?:sitting|standing|" r"seated|crouching|squatting|not)\b|\bwhat(?:'s| is) my (?:posture|pose)\b|\bdo i (?:sit|stand)\b|" r"(?:앉아|서|쪼그려\s*앉아)\s*(?:있|계)\S*\s*(?:아니면|or)?\s*(?:앉아|서)\s*(?:있|계)|" r"(?:내가|제가|나|저)\s*(?:지금\s*)?(?:앉아|서|쪼그려\s*앉아)\s*(?:있|계)\S*\s*\?|" - r"(?:앉았|섰)\S*\s*(?:아니면\s*)?(?:서|앉아|섰|앉았)\S*|(?:내|제)\s*자세", re.I) # 2026-10-23 live: "I am + r"(?:앉았|섰)\S*\s*(?:아니면\s*)?(?:서|앉아|섰|앉았)\S*|(?:내|제)\s*자세|" + r"(?:사람|분|person|친구)\S*\s*(?:지금\s*)?(?:앉아|서|쪼그려\s*앉아)\s*(?:있|계)|" + r"\bis (?:the )?(?:person|man|woman|guy|lady|one) (?:on|to) (?:your|the|my) (?:left|right) (?:sitting|standing|crouching)\b", re.I) # 2026-10-23 live: "I am # standing or sitting." got "nice to meet you" -RAISED = re.compile(r"\bwhich (?:hand|arm) (?:do i have|have i got) (?:up|raised)\b|\b(?:is|are) my (?:hand|hands|arm|arms) (?:raised|up)\b|\bam i raising (?:my )?(?:hand|arm)\b|" +RAISED = re.compile(r"\b(?:is|are) my (?:hand|hands|arm|arms) still (?:raised|up)\b|" r"손\s*(?:을\s*)?(?:올린|든)\s*(?:거|게)\s*보여|" r"\bwhich (?:hand|arm) (?:do i have|have i got) (?:up|raised)\b|\b(?:is|are) my (?:hand|hands|arm|arms) (?:raised|up)\b|\bam i raising (?:my |a |an |any |one )?(?:hand|arm)s?\b|" r"\bdid i raise my hand\b|\bwhich hand (?:did i raise|is (?:up|raised)|am i (?:raising|holding up|lifting))\b|" r"\bwhich (?:hand|arm) is (?:up|raised)\b|\b(?:see|tell) (?:if|whether) (?:i'?m|i am) raising\b|" r"\b(?:see|is) my (?:hand|arm)s? (?:up|raised)\b|\bhands? up or (?:not|down)\b|\bmy (?:hand|arm) is (?:up|raised)\b|" r"\bi'?m raising (?:my |a )?(?:hand|arm)\b|\bi am raising\b|\b(?:is )?one of my hands (?:is )?up\b|" r"(?:손|hand)\s*(?:을\s*)?(?:들었|들고\s*있|올라가|올렸|올리고\s*있|up\s*했|raise)|어떤\s*손이\s*(?:올라|들)", re.I) POINTING = re.compile(r"\bwhat am i pointing (?:at|to)\b|\bwhere am i pointing\b|(?:내가|제가)?\s*(?:뭘|어디를?)\s*가리키", re.I) -WEARING = re.compile(r"\b(?:am i|do i have|i'?m) (?:wearing |got )?(?:a |an |any )?(glasses|sunglasses|hat|cap|mask|" - r"watch|earrings|necklace|scarf|tie|beard|moustache|mustache)\b|" - r"(안경|선글라스|모자|마스크|시계|목걸이|귀걸이|넥타이|수염)\s*(?:을|를)?\s*(?:썼|쓰고|꼈|끼고|했|하고|있|찼|차고|기르)", - re.I) +_WHO = r"(?:am i|do i(?: have)?|have i got|i'?m|is (?:she|he|my friend|the other (?:person|guy|man|woman|one))|" \ + r"does (?:she|he|my friend) have)" +_ACCESSORY = r"glasses|eyeglasses|spectacles|sunglasses|shades|hats?|caps?|beanie|mask|face mask|bags?|backpack|handbag|" \ + r"purse|shoulder bag|watch|earrings|necklace|scarf|tie|beard|moustache|mustache" +WEARING = re.compile(r"\b(?:are )?(?:these|my) (sunglasses|glasses) visible\b|" r"\bis there an? (hat|cap|beanie|bag|mask|backpack) on me\b|" r"\b(?:do|does) (?:they|he|she) (?:carry|have|wear) (?:an? |any )?(?:\w+ )?(bag|backpack|hat|cap|glasses|sunglasses|mask)\b|" r"(안경|선글라스|모자|마스크|가방)\S*\s*(?:wearing|wear|착용)|" r"머리\s*위에\s*(?:뭐|뭔가|무엇)|" r"(?:내|제)\s*(가방|백팩|모자)\s*(?:무슨\s*)?(?:종류|type)|" rf"\b{_WHO} (?:wearing |got |have |carrying |holding )?(?:on )?(?:a |an |any |my )?(?:\w+ )?({_ACCESSORY})\b|" + rf"\bcolou?r\b.{{0,20}}\b(?:my|her|his) (?:\w+ )?(hats?|caps?|beanie|mask|bags?|backpack|glasses)\b|" + r"\bwhat(?:'s| is) on my (?:head|face)\b|\b(?:anything|something) on my head\b|\bwhat about my head\b|" + r"(?" + "|".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|들고|쥐고|잡고|있(?:어|습|나|니)|들었게", re.I) +HELD_ASKED = re.compile(r"\bhold|\bhave it\b|\bin my\b|\bit\b|\b(?:that|this) in\b|들고|쥐고|잡고|있(?:어|습|나|니)|들었게", re.I) SEE_KINDS = ("see", "there", "still", "see_ko", "see_more", "where", "far", "it") -TAIL = re.compile(r"(?:[\s,]+(?:too|then|also|exactly|again|please|what colou?rs?(?: (?:are|is) (?:they|it))?))+\W*$|" +TAIL = re.compile(r"(?:[\s,]+(?:too|then|also|exactly|again|please|dear|sir|ma'?am|lumi|robot|what colou?rs?(?: (?:are|is) (?:they|it))?))+\W*$|" r"(?:도|은|는)?\s*(?:정확히\s*)?(?:무슨\s*)?(?:색깔?|컬러|colou?r)\s*(?:은|는|이야|이에요|이에요)?\W*$|" r"도\s*(?:보여|보이|있어|있나)\S*\W*$|(?:은|는)?\s*(?:어때|어떻|어떤가)\S*\W*$", re.I) # words after a follow-up's noun that ask nothing new @@ -244,7 +409,7 @@ IT_COLOUR = re.compile(r"\bwhat colou?r is (?:it|that)\b|^\W*(?:그거|그건| 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) _LEAD = r"^\W*(?:(?:and|so|but|okay|ok|well|then|hmm+|uh+|um+|oh|no|wait)\W+)*" -AGAIN = re.compile(_LEAD + r"(?:(?:what|how) about |(?:where(?:'s| is)? (?:it|that|they)|which hand(?: is it)?|" +AGAIN = re.compile(r"\band now\s*\??\s*$|" + _LEAD + r"(?:(?:what|how) about |(?:where(?:'s| is)? (?:it|that|they)|which hand(?: is it)?|" r"what(?:'s| is)? (?:it|that)|is it|right|just|look|check) )?(?:now|know)\b(?:,? lumi)?" r"(?:\W+anything (?:new|else|different))?\W*$|\bone more time\b|" # "and now?" ("and know?") r"\b(?:look|check|see)\b.{0,15}\b(?:again|one more time)\b|\btake another look\b|" @@ -263,7 +428,8 @@ AGAIN = re.compile(_LEAD + r"(?:(?:what|how) about |(?:where(?:'s| is)? (?:it|th LOOK_SAID = re.compile(r"\blook\b(?=\s*(?:[,.!]|$))", re.I) # "Lumi, look, what am I holding?": not a head turn PUT_ON = re.compile(r"\bi(?:'ve| have)? (?:just )?(?:put on|took off|taken off)\b", re.I) # clothes, not an order LIKED = re.compile(r"\bfavou?rite\b|\b(?:like|love)\b|좋아하", re.I) # "is white your favourite colour?": not a check -NOT_A_HAND = re.compile(r"\b(?:that'?s|that is|you'?re|you are|all|is that|is it) right\b|\bright (?:now|away|here|there)\b", +NOT_A_HAND = re.compile(r"\b(?:that'?s|that is|you'?re|you are|all|is that|is it) right\b|\bright (?:now|away|here|there)\b|" + r",\s*right\W*$", # "you see the phone in my hand, right?": a tag, not the right hand re.I) HAND_SAID = re.compile(r"(?P\bnot (?:in )?(?:the |my |your )?|\bisn'?t (?:in )?(?:the |my |your )?)?\b(?Pleft|right)\b" r"(?=\s*(?:hand|one|side)(?![a-z])|\W*$)|(?P왼|오른)\s*(?:손|쪽|편)\S{0,3}(?P\s*아니)?", re.I) @@ -401,6 +567,8 @@ def _seen_answer(name, colour, frames, lang): return _say(f"Yes, I see {_n(n)} {'person' if n == 1 else 'people'}." if n else "No, I don't see anyone right now.", f"네, 사람 {n}명이 보여요." if n else "아니요, 지금은 아무도 안 보여요.", lang) hits = _sees(name, colour, frames) + if colour and hits and not any(h["colour"] == colour for h in hits): + hits = [] # a grey chair asked as white: said as seen, not agreed if hits: t = hits[0] _last["thing"] = t @@ -568,6 +736,11 @@ def _held_answer(frames, lang, side=None, more=None, slow_line=None, hint=None): _last["held"] = None return _say(f"I don't see anything in your {side} hand." if side else EMPTY_HANDS[0].format(""), f"{k}손에는 든 게 없어 보여요." if side else EMPTY_HANDS[1].format(""), lang) + lk = _looks(p, frames, lang, None, more, wait=False) # the person's looks of seconds ago name the thing + got = lk and not hint and next(((s, lk[f"{s}_hand"]) for s in sides if lk.get(f"{s}_hand")), None) + if got: + s, w = got + return _say(f"It looks like {_a(w)} in your {s} hand.", f"{KO_SIDE[s]}손에 {_j(_ko_thing(w), '이', '가')} 있는 것 같아요.", lang) evidence = "; ".join( ([f"the object detector's best guess is a {weak['name']} (score {weak['score']:.2f}, unsure)"] if weak else ["the object detector knows no class for it"]) + @@ -651,12 +824,15 @@ def _empty_hands(lang, now=False): NOUN = {"upper": ("top", "상의"), "lower": ("trousers", "바지"), "feet": ("shoes", "신발")} +GENERIC = re.compile(r"tops?|bottoms?|bottom half|lower half|upper half|legs?|down below|clothes|outfit|상의|하의|아래(?:쪽)?|밑|" + r"다리|윗옷|웃옷|옷", re.I) # words for a piece that name no kind -def _clothes_answer(p, text, lang): +def _clothes_answer(p, text, lang, looks=None): """The colour of each piece asked about (all three for "what am I wearing?"), in the asker's own word ("your - jeans look blue"); a piece out of the picture is said to be out of view, never guessed.""" - asked = [] # (part, noun) in the order said + jeans look blue"), else the kind the VLM's looks give ("a white t-shirt"); a piece out of the picture is said to + be out of view, never guessed (the looks' colour when the camera can't measure it).""" + asked = [] # (start, part, noun) in the order said for part, rx in PARTS: m = re.search(rx, text, re.I) if m: @@ -665,8 +841,15 @@ def _clothes_answer(p, text, lang): w = NOUN[part][lang != "en"] w = {"genes": "jeans", "jean": "jeans", "short": "shirt", "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] + 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 + 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] + seen = [(part, w, p["clothes"].get(part) or + ((looks or {}).get({"upper": "top", "lower": "bottom", "feet": "feet"}[part]) or {}).get("colour")) + for part, w in asked] _last["parts"] = seen if len(seen) == 1: part, w, c = seen[0] @@ -696,9 +879,10 @@ POSE_SAID = {"standing": ("You're standing", "서 계시고"), "sitting": ("You' POSE_WORD = {"standing": r"stand|서|섰", "sitting": r"sit|seated|앉", "crouching": r"crouch|squat|쪼그"} -def _posture_answer(p, t, lang): - """"Am I sitting or standing?": from the knees and ankles (scene._posture); "No, ..." when they guessed another.""" - got = p.get("posture") +def _posture_answer(p, t, lang, looks=None): + """"Am I sitting or standing?": from the knees and ankles (scene._posture), else the VLM's look; "No, ..." when + they guessed another.""" + got = p.get("posture") or ((looks or {}).get("posture") if (looks or {}).get("posture") in POSE_SAID else None) if got is None: return _say("I can't see your legs well enough to tell whether you're sitting or standing.", "다리가 잘 안 보여서 앉아 계신지 서 계신지 모르겠어요.", lang) @@ -709,11 +893,21 @@ def _posture_answer(p, t, lang): return _say(f"{lead[0]}{POSE_SAID[got][0].replace('You', 'you' if lead[0] else 'You')}.", f"{lead[1]}{ko}", lang) -def _doing_answer(p, frames, lang): - o = _steady(scene.object_in_hand(frames)) - pose_en, pose_ko = POSE_SAID.get(p.get("posture"), ("You're", "계시고")) +ACTION_KO = (("wav", "손을 흔들고 계세요"), ("phone call|on the phone|calling", "통화하고 계세요"), + ("phone", "휴대폰을 보고 계세요"), ("read", "뭔가 읽고 계세요"), ("drink", "뭔가 마시고 계세요"), + ("eat", "뭔가 드시고 계세요"), ("talk", "이야기하고 계세요"), ("walk", "걷고 계세요"), + ("photo|picture", "사진을 찍고 계세요"), ("typ", "타자를 치고 계세요"), ("writ", "뭔가 쓰고 계세요"), + ("point", "뭔가 가리키고 계세요"), ("clap", "박수를 치고 계세요"), ("danc", "춤추고 계세요"), + ("smil|laugh", "웃고 계세요"), ("stretch", "스트레칭하고 계세요"), ("carry", "뭔가 들고 계세요"), + ("look", "뭔가 보고 계세요")) # the VLM's English action said in Korean when it gave no action_ko + + +def _doing_answer(p, frames, lang, looks=None, own=True): + act = (looks or {}).get("action") # the VLM's words: "looking at a phone" + o = None if act else _steady(scene.object_in_hand(frames)) if own else _from(p) + pose_en, pose_ko = POSE_SAID.get(p.get("posture") or (looks or {}).get("posture"), ("You're", "계시고")) en, ko = [f"{pose_en}{_m(p['distance_m'], 'en')} {p['where']}"], [f"제 {_where_ko(p['where'])}에 {pose_ko}"] - if p["facing"] is True: + if p["facing"] is True and not act: en.append("looking at me") ko.append("저를 보고 계시고") if o: @@ -725,15 +919,480 @@ def _doing_answer(p, frames, lang): elif p["pointing"]: en.append(f"pointing with your {p['pointing']} hand") ko.append("손으로 가리키고 계시고") - return _say(", ".join(en) + ".", " ".join(ko).rstrip("고").rstrip("시") + "세요.", lang) + if act and not (o and o["name"] in act): + en.append(act if act.split()[0].endswith("ing") else f"and {act}") + ko_s = " ".join(ko).rstrip("고").rstrip("시") + "세요." + act_ko = act and ((looks or {}).get("action_ko") or next((k for w, k in ACTION_KO if re.search(w, act)), None)) + if act_ko: + ko_s += " " + act_ko.strip().rstrip(".") + "." + return _say(", ".join(en) + ".", ko_s, lang) + + +# ---------- looks: one VLM pass describes the person (clothes types, hair, glasses, hat, mask, bag, action) ---------- +LOOKS_S = 10.0 # s; a person's looks are reused this long for follow-up questions (one VLM pass) +LOOKS_WAIT_S = 16.0 # s; a question that needs the looks waits this long for the VLM (scene timeout 15 s) +LOOKS_SAME_DEG = 15.0 # deg; looks cached for a person at this bearing are theirs +NONE_WORDS = {"", "null", "none", "no", "unknown", "n/a", "not visible", "false", "nothing"} +COLOUR_KO_MORE = {"navy": "남색", "beige": "베이지색", "khaki": "카키색", "dark": "어두운 색", "gold": "금색", + "silver": "은색", "cream": "크림색", "blond": "금발", "dyed": "염색한 색", "dark blue": "남색", + "light grey": "밝은 회색", "dark grey": "짙은 회색", "multicoloured": "여러 색", "colourful": "알록달록한 색"} +TYPE_KO = {"t-shirt": "티셔츠", "shirt": "셔츠", "jacket": "재킷", "hoodie": "후드티", "sweater": "스웨터", "coat": "코트", + "blouse": "블라우스", "dress": "원피스", "vest": "조끼", "blazer": "재킷", "cardigan": "카디건", "polo": "셔츠", + "jeans": "청바지", "trousers": "바지", "pants": "바지", "shorts": "반바지", "skirt": "치마", "leggings": "레깅스", + "sneakers": "운동화", "shoes": "신발", "boots": "부츠", "sandals": "샌들", "slippers": "슬리퍼", + "cap": "모자", "hat": "모자", "beanie": "비니", "backpack": "백팩", "handbag": "핸드백", "bag": "가방", + "shoulder bag": "숄더백", "purse": "지갑", "mask": "마스크", "face mask": "마스크", "glasses": "안경", + "sunglasses": "선글라스"} +FAMILY = {"t-shirt": "top", "tee": "top", "shirt": "top", "blouse": "top", "polo": "top", "top": "top", "티셔츠": "top", + "셔츠": "top", "블라우스": "top", "상의": "top", + "jacket": "jacket", "coat": "jacket", "blazer": "jacket", "재킷": "jacket", "자켓": "jacket", "코트": "jacket", + "hoodie": "hoodie", "sweatshirt": "hoodie", "후드": "hoodie", "후드티": "hoodie", "맨투맨": "hoodie", + "sweater": "sweater", "jumper": "sweater", "cardigan": "sweater", "니트": "sweater", "스웨터": "sweater", + "dress": "dress", "원피스": "dress", "vest": "vest", "조끼": "vest", + "jeans": "trousers", "jean": "trousers", "genes": "trousers", "trousers": "trousers", "pants": "trousers", + "slacks": "trousers", "leggings": "trousers", "청바지": "trousers", "바지": "trousers", "하의": "trousers", + "shorts": "shorts", "반바지": "shorts", "skirt": "skirt", "치마": "skirt", "스커트": "skirt", + "sneakers": "shoes", "trainers": "shoes", "shoes": "shoes", "boots": "shoes", "sandals": "sandals", + "slippers": "sandals", "운동화": "shoes", "신발": "shoes", "구두": "shoes", "부츠": "shoes", "샌들": "sandals"} + # 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) +PATTERN_SAID = {"plain": ("plain", "무늬가 없어"), "striped": ("striped", "줄무늬가 있어"), "checked": ("checked", "체크무늬가 있어"), + "printed": ("printed", "프린트가 있어"), "dotted": ("dotted", "물방울무늬가 있어")} +LENGTHS = {"short": ("short", "짧아"), "medium": ("medium length", "중간 길이예요"), "long": ("long", "길어"), + "bald": ("shaved", "거의 없어")} +HAIR_KO = {"black": "검은", "brown": "갈색", "blond": "금발", "grey": "회색", "white": "흰", "red": "붉은", "dyed": "염색한"} +LEN_ASKED = re.compile(r"\b(?:long|short|length|bald|medium)\b|길|짧|길이|대머리|단발|장발", re.I) +HAIR_COL_ASKED = re.compile(r"\bcolou?r|\b(?:black|brown|blond|blonde|grey|gray|white|red|dyed)\b|색|컬러|금발|염색", re.I) +WHO_ELSE = re.compile(r"^\W*(?:(?:and|so|then|okay|ok|what|how)\W+)*(?:about\s+)?(?:her|him|them|my friend|the other (?:one|person|guy|man|woman)|" + r"(?:the )?(?:person|man|woman|guy|lady) (?:next to|beside|behind) me)\W*$|" + r"^\W*(?:그럼\s*)?(?:그\s*(?:분|사람)|옆\s*(?:에\s*)?(?:있는\s*)?(?:분|사람)|친구|저\s*(?:분|사람)|다른\s*(?:분|사람))" + r"\s*(?:은|는|도)?요?\s*\??\W*$", re.I) # "what about her?", "그 사람은?" after a question about someone +ME_AGAIN = re.compile(r"^\W*(?:(?:and|so|then|okay|ok|my turn)\W+)*(?:(?:what|how)\s+about\s+)?(?:me|mine|myself)(?:\s+too)?\W*$|" + r"\b(?:what|how) about (?:me|mine)\b|^\W*(?:그럼\s*)?(?:나|저|내\s*거|제\s*거|제\s*것|내\s*것)\s*(?:는|도|은)요?\s*(?:\?|$)|" + r"나도\s*(?:해|봐)\s*줘|저도\s*(?:해|봐)\s*주세요|(?:내|제)\s*(?:거|것)\S*\s*(?:은|는)?\s*(?:무슨\s*색|어때)", re.I) +PERSON_KINDS = ("wearing", "hair", "describe", "shirt", "wear_item", "posture", "doing", "holding", "raised") +_looks_cache = {"front": None, "other": None} # {"at", "bearing", "looks"} per person asked about +_looks_lock = threading.Lock() +_looks_jobs = {} # who -> (thread, started at) + + +def _flag(v): + """glasses / hat / mask / bag: False when clearly not worn ("none", false), None when not in view (null), else + the phrase ("black cap").""" + if v is False or isinstance(v, str) and v.strip().lower() in ("none", "no", "false", "nothing"): + return False + w = _word(v) + return None if w is None else w + + +PLURAL_WEAR = re.compile(r"\b(?:jeans|pants|trousers|shorts|leggings|shoes|sneakers|trainers|boots|socks|sandals|" + r"glasses|sunglasses|gloves)\b", re.I) + + +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).""" + m = SIDE_WHO.search(t) + if m: + side = (m.group("s") or m.group("s2") or {"왼": "left", "오른": "right"}.get(m.group("k"))).lower() + return {"left": "right", "right": "left"}[side] if (m.group("o") or "").lower() == "my" else side + if OTHER.search(t) or re.search(r"\b(?:they|them|their)\b", t, re.I) and not re.search(r"\b(?:i|me|my|i'?m)\b", t, re.I) \ + and not PLURAL_WEAR.search(t): # "the jeans, what colour are they?": they = the jeans + return "other" + return "front" + + +def _someone(frames, who): + """The person a question is about when it is not the one talking: on that side (who "left" / "right"), else the + nearest other one; None when nobody else is in view.""" + if who in ("left", "right"): + try: + front = scene.person_in_front(frames) + for q in scene._persons(frames): + if q.get("where") == f"on my {who}" and not (front and q.get("bearing_deg") == front.get("bearing_deg") + and q.get("distance_m") == front.get("distance_m")): + return scene._public(q) + except Exception as e: # noqa: BLE001 - stand-in cameras without _persons + print(f"seeing: no side look ({e})", flush=True) + return scene.other_person(frames) + + +def _word(v): + """A VLM value as a plain lower-case word or phrase, None for null / none / unknown.""" + if isinstance(v, dict): + v = " ".join(str(x) for x in (v.get("colour") or v.get("color"), + v.get("object") or v.get("type") or v.get("kind") or v.get("name")) + if x and str(x).lower() not in NONE_WORDS) + if v is True: + return "yes" + if v is None or v is False: + return None + v = str(v).strip().lower().replace("gray", "grey").replace("colored", "coloured") + return None if v in NONE_WORDS else v + + +def _piece(v): + """{type, colour, pattern} from the VLM's top / bottom / feet (a dict or a phrase).""" + if isinstance(v, dict): + out = {k: _word(v.get(k) if k != "colour" else v.get("colour", v.get("color"))) for k in ("type", "colour", "pattern")} + return out if any(out.values()) else None + w = _word(v) + if not w: + return None + c = next((c for c in sorted(list(COLOUR_KO) + list(COLOUR_KO_MORE), key=len, reverse=True) if w.startswith(c + " ")), None) + return {"type": w[len(c) + 1:] if c else w, "colour": c, "pattern": None} + + +def norm_looks(raw): + """The VLM's JSON (scene.ask_vlm_person) as {top, bottom, feet: {type, colour, pattern} or None, hair: {colour, + length} or None, glasses, hat, mask, bag, left_hand, right_hand, posture, action, action_ko: a phrase or None}.""" + if not isinstance(raw, dict): + return None + hair = raw.get("hair") + if isinstance(hair, dict): + hair = {"colour": _word(hair.get("colour", hair.get("color"))), "length": _word(hair.get("length"))} + elif _word(hair): + w = _word(hair) + hair = {"colour": next((c for c in HAIR_KO if c in w), None), "length": next((n for n in LENGTHS if n in w), None)} + else: + hair = None + glasses = _flag(raw.get("glasses")) + if glasses == "yes": + glasses = "glasses" + if _word(raw.get("sunglasses")) == "yes": + glasses = "sunglasses" + elif glasses is None and raw.get("sunglasses") is False: + glasses = False + out = {"top": _piece(raw.get("top")), "bottom": _piece(raw.get("bottom")), "feet": _piece(raw.get("feet")), + "hair": hair if hair and any(hair.values()) else None, "glasses": glasses, + **{k: _flag(raw.get(k)) for k in ("hat", "mask", "bag")}, + **{k: _word(raw.get(k)) for k in ("left_hand", "right_hand", "posture", "action")}, + "action_ko": raw.get("action_ko") or None} + for k in ("hat", "mask", "bag"): + if out[k] == "yes": + out[k] = k + return out + + +def scene_looks(person): + """looks (norm_looks) from a blind test scene's person (tests/blind/README.md seeing format, plus the r6 fields + hair, glasses, hat, mask, bag, action, top_type, bottom_type, pattern, shoes), for a checker's fake person_in_front: + put it under "looks" there; None when the person has none of these fields.""" + q = person + keys = ("hair", "hair_colour", "hair_color", "hair_length", "glasses", "sunglasses", "hat", "mask", "bag", "action", + "top_type", "bottom_type", "bottom_kind", "pattern", "top_pattern", "shoes", "posture") + if not any(k in q for k in keys): + return None + hair = q.get("hair") + if not isinstance(hair, dict) and (q.get("hair_colour") or q.get("hair_color") or q.get("hair_length")): + hair = {"colour": q.get("hair_colour") or q.get("hair_color"), "length": q.get("hair_length")} + pattern = q.get("top_pattern", q.get("pattern")) + action = {"phone": "looking at a phone"}.get(q.get("action"), q.get("action")) + return norm_looks({"top": {"type": q.get("top_type"), "colour": q.get("top"), + "pattern": {"print": "printed"}.get(pattern, pattern)}, + "bottom": {"type": q.get("bottom_type") or q.get("bottom_kind"), "colour": q.get("bottom")}, + "feet": q.get("shoes"), "hair": hair, "glasses": q.get("glasses"), + "sunglasses": q.get("sunglasses"), "hat": q.get("hat") or ("none" if "hat" in q else None), + "mask": q.get("mask") or ("none" if q.get("mask") is False else None), + "bag": q.get("bag") or ("none" if "bag" in q else None), "left_hand": q.get("left_hand"), "right_hand": q.get("right_hand"), + "posture": q.get("posture"), "action": action, "action_ko": q.get("action_ko")}) + + +def _live(frames, more): + return bool(more) and bool(frames) and all("color" in f for f in frames) + + +def _looks_job(frames, who, bearing): + """The VLM look at that person in the background (one per person at a time); the thread.""" + with _looks_lock: + job = _looks_jobs.get(who) + if job and job[0].is_alive(): + return job[0] + + def run(): + t = time.time() + got = norm_looks(scene.ask_vlm_person(frames, other=who != "front", bearing=bearing if who != "front" else None)) + print(f"seeing: looks of the {who} person in {time.time() - t:.1f} s: {got}", flush=True) + if got: + _looks_cache[who] = {"at": t, "bearing": bearing, "looks": got} + th = threading.Thread(target=run, daemon=True) + _looks_jobs[who] = (th, time.time()) + th.start() + return th + + +def _cached_looks(who, p, after=0.0): + c = _looks_cache.get(who) + if c and c["at"] >= max(after, time.time() - LOOKS_S) and \ + abs((c["bearing"] or 0) - (p.get("bearing_deg") or 0)) <= LOOKS_SAME_DEG: + return c["looks"] + return None + + +def _looks(p, frames, lang, slow_line=None, more=None, who="front", wait=True): + """What the person looks like (norm_looks): the fake scene's ("looks" in p), else the VLM's from a look taken after + _last["after"] (a "really?": a new one) or within LOOKS_S; wait: run it now (saying "Let me look." first), else + only what is cached (and a run started in the background). None when it can't be had.""" + if "looks" in p: + return p["looks"] + if not _live(frames, more): + return None + after = _last.get("after") or 0.0 + got = _cached_looks(who, p, after) + if got or not wait: + if not got: + _looks_job(frames, who, p.get("bearing_deg")) + return got + job = _looks_job(frames, who, p.get("bearing_deg")) + if slow_line: + slow_line(_say("Let me look.", "잠깐 볼게요.", lang)) + job.join(LOOKS_WAIT_S) + return _cached_looks(who, p, after) + + +def prefetch(frames=None): + """Start the VLM look at the person in front in the background (lumi may call it when a talk starts), so the first + question about their looks is answered at once.""" + try: + frames = scene.snapshot() if frames is None else frames + p = scene.person_in_front(frames) if frames else None + if p and all("color" in f for f in frames) and not _cached_looks("front", p): + _looks_job(frames, "front", p.get("bearing_deg")) + except Exception as e: + print(f"seeing: no prefetch ({e})", flush=True) + + +def _ck(c): + return COLOUR_KO.get(c) or COLOUR_KO_MORE.get(c) or c + + +def _ko_thing(phrase): + """"black cap" -> "검은색 모자": the colour and the kind in Korean when known, else the words as they are.""" + if not phrase: + return "" + c = next((c for c in sorted(list(COLOUR_KO) + list(COLOUR_KO_MORE), key=len, reverse=True) + if phrase.startswith(c + " ")), None) + rest = phrase[len(c) + 1:] if c else phrase + noun = TYPE_KO.get(rest) or next((v for k, v in TYPE_KO.items() if rest.endswith(k)), None) or KO.get(rest) or rest + return f"{_ck(c)} {noun}" if c else noun + + +def _them(said, lang): + """A "you" sentence about the person in front turned to another person: "Your shirt" -> "Their shirt".""" + if lang != "en": + return said if said.startswith(("네", "아니", "그분", "지금은")) else "그분은 " + said + said = re.sub(r"\byou're\b", "they're", re.sub(r"\bYou're\b", "They're", said)) + said = re.sub(r"\bYou are\b", "They are", re.sub(r"\byou are\b", "they are", said)) + said = re.sub(r"\byou have\b", "they have", re.sub(r"\bYou have\b", "They have", said)) + said = re.sub(r"\bon you\b", "on them", said) + return re.sub(r"\b([Yy])our\b", lambda m: "Their" if m.group(1) == "Y" else "their", said) + + +ACCESSORY_OF = (("glasses", r"glass|spectacle|shades|안경|선글라스"), ("hat", r"hat|cap|beanie|head|모자|머리에|머리\s*위"), + ("mask", r"mask|face|마스크"), ("bag", r"bag|backpack|purse|가방|백팩|배낭")) +ACC_KO = {"glasses": ("안경을", "쓰고"), "hat": ("모자를", "쓰고"), "mask": ("마스크를", "쓰고"), "bag": ("가방을", "메고")} + + +def _wearing_answer(t, p, frames, lang, slow_line, more, who): + """Glasses, a hat, a mask, a bag: from the looks; other things (a watch, earrings) the VLM is asked as before.""" + m = WEARING.search(t) + item = next((g for g in (m.groups() if m else ()) if g), t) + acc = next((k for k, rx in ACCESSORY_OF if re.search(rx, item, re.I)), None) + looks = _looks(p, frames, lang, slow_line, more, who) if acc else None + if looks is None: # live, the looks timed out: no second slow look + if acc and _live(frames, more): + return _say("I can't see that well enough to tell.", "그건 잘 안 보여서 모르겠어요.", lang) + if slow_line and not acc: + slow_line(_say("Let me look.", "잠깐 볼게요.", lang)) + said = scene.ask_vlm(t, lang, frames) + return said or _say("I can't see that well enough to tell.", "그건 잘 안 보여서 모르겠어요.", lang) + v = looks.get(acc) + if v is None: # not in view (the face, the shoulders): never guessed + part = {"glasses": ("face", "얼굴이"), "hat": ("head", "머리가"), "mask": ("face", "얼굴이"), + "bag": ("shoulders", "어깨가")}[acc] + return _say(f"I can't see your {part[0]} well enough to tell.", f"{part[1]} 잘 안 보여서 모르겠어요.", lang) + sun = bool(re.search(r"sun|shades|선글라스", item, re.I)) + if acc == "glasses": + if v and (not sun or v == "sunglasses"): + return _say(f"Yes, you're wearing {v}.", f"네, {'선글라스를' if v == 'sunglasses' else '안경을'} 쓰고 계세요.", lang) + if v: # glasses asked as sunglasses + return _say("You're wearing glasses, not sunglasses.", "선글라스가 아니라 안경을 쓰고 계세요.", lang) + return _say(f"No, you're not wearing {'sunglasses' if sun else 'glasses'}.", + f"아니요, {'선글라스는' if sun else '안경은'} 안 쓰고 계세요.", lang) + obj, verb = ACC_KO[acc] + if v and re.search(r"colou?r|색|컬러", t, re.I): # "what colour is my cap?" + return _say(f"It's {_a(v)}." if v != acc else f"I can't tell the colour of your {acc}.", + f"{_ko_thing(v)}예요." if v != acc else "색은 잘 모르겠어요.", lang) + if v: + en_v = {"bag": "have", "hat": "are wearing", "mask": "are wearing"}[acc] + noun = v if v != acc else ("a " + acc) + noun = noun if noun.startswith(("a ", "an ")) or noun.endswith("s") else _a(noun) + 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) + + +def _hair_answer(t, looks, lang): + h = (looks or {}).get("hair") + if not h: + return _say("I can't see your hair well enough to tell.", "머리가 잘 안 보여서 모르겠어요.", lang) + col, ln = h.get("colour"), h.get("length") + ask_len, ask_col = bool(LEN_ASKED.search(t)), bool(HAIR_COL_ASKED.search(t)) + lead_en = lead_ko = "" + said_len = next((n for n in LENGTHS if re.search(n, t, re.I)), None) or \ + ("long" if re.search(r"길|장발", t) else "short" if re.search(r"짧|단발", t) else None) + said_col = next((c for c in HAIR_KO if re.search(rf"\b{c}", t, re.I)), None) or ("blond" if "금발" in t else None) + if said_len and ln and not ask_col: + lead_en, lead_ko = ("Yes, ", "네, ") if said_len == ln else ("No, ", "아니요, ") + elif said_col and col and not ask_len: + lead_en, lead_ko = ("Yes, ", "네, ") if said_col == col else ("No, ", "아니요, ") + if ask_len and not ask_col or col is None: + if ln is None: + return _say("I can't tell how long your hair is from here.", "머리 길이는 여기서 잘 모르겠어요.", lang) + return _say(f"{lead_en}{'your' if lead_en else 'Your'} hair looks {LENGTHS[ln][0]}.", + f"{lead_ko}머리가 {LENGTHS[ln][1]} 보여요." if ln != "medium" else f"{lead_ko}중간 길이 머리로 보여요.", lang) + if ask_col and not ask_len or ln is None: + return _say(f"{lead_en}{'your' if lead_en else 'Your'} hair looks {col}.", + f"{lead_ko}{HAIR_KO.get(col, col)} 머리로 보여요." if col != "blond" else f"{lead_ko}금발로 보여요.", lang) + return _say(f"{lead_en}{'your' if lead_en else 'Your'} hair looks {LENGTHS[ln][0]} and {col}.", + f"{lead_ko}{HAIR_KO.get(col, col)} 머리이고 {LENGTHS[ln][1]} 보여요.", lang) + + +def _type_of(part, looks): + piece = (looks or {}).get({"upper": "top", "lower": "bottom", "feet": "feet"}[part]) + return piece and piece.get("type") + + +def _wear_item_answer(t, p, frames, lang, slow_line, more, who): + """"Am I wearing a jacket?", "is she in jeans?", "청바지 입었어?": the kind of piece from the looks, its colour from the + camera (the looks' colour when the camera can't measure it).""" + asked = [(m.start(), part, m.group(0).lower()) for part, rx in PARTS for m in [re.search(rx, t, re.I)] if m] + extra = re.search(r"\b(dress(?:es)?|vests?|blazers?|cardigans?|polos?)\b|원피스|조끼|블라우스|후드|부츠|샌들", t, re.I) + if extra: + w = extra.group(0).lower().rstrip("s") if extra.group(0).isascii() else extra.group(0) + asked.append((extra.start(), "feet" if w in ("부츠", "샌들") else "upper", w)) + if not asked: + return None + _, part, word = min(asked) + word = re.sub(r"^te[ea] ?shirts?|^t ?shirts?", "t-shirt", word).rstrip("?") + word = word[:-1] if word.endswith("s") and word not in ("jeans", "trousers", "pants", "shorts", "slacks", "leggings", + "glasses", "dress", "genes") else word + said_c = next((COLOURS[(m.group("c") or m.group("k")).lower()] for m in COLOUR_SAID.finditer(t) + if not (m.group("n") or m.group("kn"))), None) # "am I wearing a blue hoodie?" + looks = _looks(p, frames, lang, slow_line, more, who) + kind = _type_of(part, looks) + piece = (looks or {}).get({"upper": "top", "lower": "bottom", "feet": "feet"}[part]) or {} + c = p["clothes"].get(part) or piece.get("colour") + if kind is None: + if c is None: + return _say(f"I can't see your {word} well enough to tell.", f"{_j(TYPE_KO.get(word, word), '이', '가')} 잘 안 보여서 모르겠어요.", lang) + noun = NOUN[part] + return _say(f"I can see your {noun[0]} {'look' if noun[0].endswith('s') else 'looks'} {c}, but I can't tell if it's {_a(word) if not word.endswith('s') else word}.", + f"{_j(noun[1], '은', '는')} {_ck(c)}으로 보이는데, {TYPE_KO.get(word, word)}인지는 잘 모르겠어요.", lang) + fam = FAMILY.get(word, word) + same = FAMILY.get(kind, kind) == fam or fam == "top" and FAMILY.get(kind) in ("top",) or \ + (word in EXACT["jeans"] and kind == "jeans") or (fam == "trousers" and word not in EXACT["jeans"] and FAMILY.get(kind) == "trousers") + if word in EXACT["jeans"] and kind != "jeans": + same = False + if said_c and c and said_c != c: + same = False + what_en = f"{c + ' ' if c else ''}{kind}" + what_en = what_en if kind.endswith("s") and kind not in ("dress",) else _a(what_en) + what_ko = f"{_ck(c) + ' ' if c else ''}{TYPE_KO.get(kind, kind)}" + verb_ko = "신고" if part == "feet" else "입고" + if same: + return _say(f"Yes, you're wearing {what_en}.", f"네, {_j(what_ko, '을', '를')} {verb_ko} 계세요.", lang) + return _say(f"No, you're wearing {what_en}.", f"아니요, {_j(what_ko, '을', '를')} {verb_ko} 계세요.", lang) + + +def _pattern_answer(p, looks, lang): + top = (looks or {}).get("top") or {} + pat = top.get("pattern") + w = top.get("type") or "top" + if not pat: + return _say("I can't make out the pattern from here.", "무늬는 여기서 잘 안 보여요.", lang) + en, ko = PATTERN_SAID.get(pat, (pat, f"{pat} 무늬가 있어")) + return _say(f"Your {w} looks {en}.", f"{_j(TYPE_KO.get(w, '상의'), '은', '는')} {ko} 보여요.", lang) + + +def _describe_me(p, frames, lang, slow_line, more, who): + """"What do I look like?": clothes (kinds from the looks, colours from the camera), hair, glasses, hat, posture.""" + looks = _looks(p, frames, lang, slow_line, more, who) or {} + en, ko = [], [] + worn = [] + for part, key in (("upper", "top"), ("lower", "bottom"), ("feet", "feet")): + piece = looks.get(key) or {} + c = p["clothes"].get(part) or piece.get("colour") + kind = piece.get("type") or (NOUN[part][lang != "en"] if c else None) + if kind: + worn.append((part, c, kind)) + if worn: + ws = [f"{c + ' ' if c else ''}{k}" for _, c, k in worn] + ws[0] = ws[0] if worn[0][2].endswith("s") else _a(ws[0]) + en.append("you're wearing " + (ws[0] if len(ws) == 1 else ", ".join(ws[:-1]) + " and " + ws[-1])) + ko.append(" ".join(f"{_ck(c) + ' ' if c else ''}{TYPE_KO.get(k, k)}" for _, c, k in worn) + " 차림이시고") + h = looks.get("hair") + if h and (h.get("colour") or h.get("length")): + en.append(f"you have {' '.join(x for x in (LENGTHS.get(h.get('length'), ('',))[0], h.get('colour')) if x)} hair") + ko.append(f"{HAIR_KO.get(h.get('colour'), '')} 머리".strip() + "이시고") + if looks.get("glasses"): + en.append(f"you're wearing {looks['glasses']}") + ko.append("안경을 쓰셨고" if looks["glasses"] != "sunglasses" else "선글라스를 쓰셨고") + if looks.get("hat"): + en.append(f"you have {_a(looks['hat'])} on") + ko.append(f"{_j(_ko_thing(looks['hat']), '을', '를')} 쓰셨고") + if looks.get("bag"): + en.append(f"you have {_a(looks['bag'])}") + ko.append(f"{_j(_ko_thing(looks['bag']), '을', '를')} 메셨고") + pose_ = p.get("posture") or looks.get("posture") + if pose_ in POSE_SAID: + en.append(f"you're {pose_}") + ko.append(POSE_SAID[pose_][1]) + act = looks.get("action") + act_ko = act and (looks.get("action_ko") or next((k for w, k in ACTION_KO if re.search(w, act)), None)) + if act: + en.append(f"you're {act}" if act.split()[0].endswith("ing") else act) + if not en: + return _say("I can't see you well enough to describe you. Could you step in front of me?", + "잘 안 보여서 설명하기 어려워요. 제 앞으로 와 주시겠어요?", lang) + s_en = ", ".join(en[:-1]) + (" and " if len(en) > 1 else "") + en[-1] + s_ko = (" ".join(ko).rstrip("고").rstrip("시").rstrip("셨") + "세요.") if ko else "" + if act_ko: + s_ko = (s_ko + " " + act_ko.strip().rstrip(".") + ".").strip() + return _say(s_en[0].upper() + s_en[1:] + ".", s_ko or "잘 안 보여서 설명하기 어려워요.", lang) + + +def _closest_answer(frames, lang): + """"Who is closest to you?": the person in front (taken as the speaker) or someone else nearer, with where they are.""" + p, q = scene.person_in_front(frames), scene.other_person(frames) + if p is None and q is None: + n = len(scene.people(frames)) + return _say("I don't see anyone near me right now." if not n else "I see someone, but I can't tell how far they are.", + "지금은 가까이에 아무도 안 보여요." if not n else "사람은 보이는데 거리는 잘 모르겠어요.", lang) + if p and (q is None or (q["distance_m"] or 99) >= (p["distance_m"] or 99)): + return _say(f"You are, about {_metres(p['distance_m'])} from me." if p["distance_m"] else "You are the closest.", + f"손님이 제일 가까워요. 저한테서 {_d(p['distance_m'])}미터쯤 떨어져 계세요." if p["distance_m"] else + "손님이 제일 가까워요.", lang) + top = q["clothes"].get("upper") + return _say(f"The person {q['where']}{' in ' + _a(top) + ' top' if top else ''} is closest, about {_metres(q['distance_m'])} away.", + f"제 {_where_ko(q['where'])}에 계신{' ' + _ck(top) + ' 상의를 입은' if top else ''} 분이 제일 가까워요. " + f"{_d(q['distance_m'])}미터쯤 떨어져 계세요.", lang) 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|들고|쥐고|잡고|있(?:어|습|나|니)|들었게", re.I) +HELD_ASKED = re.compile(r"\bhold|\bhave it\b|\bin my\b|\bit\b|\b(?:that|this) in\b|들고|쥐고|잡고|있(?:어|습|나|니)|들었게", re.I) -KINDS = (("wearing", WEARING), ("holding", HOLDING), ("shirt", SHIRT), ("raised", RAISED), ("where", WHERE_THING), ("hand", WHICH_HAND), - ("pointing", POINTING), ("posture", POSTURE), ("doing", DOING), ("friend", FRIEND), ("see_me", SEE_ME), ("how_many", HOW_MANY), ("behind", BEHIND), +CANT = re.compile(r"\b(?:how many|count|guess)\b.{0,25}\bfingers?\b|\bfingers?\b.{0,15}(?:\bhow many\b|몇)|" + r"손가락\S*\s*(?:몇|how many)|(?:\bhow many\b|몇)\s*(?:개\s*)?손가락|" + r"\b(?:in|inside) (?:my|her|his) (?:\w+ )?pockets?\b|\bpockets?\b.{0,10}\bwhat\b|" + r"주머니\S*\s*(?:안에|속에|에)?\s*(?:뭐|뭘|무엇|무슨|what)", re.I) # fingers, a pocket: the cameras can't +KINDS = (("cant", CANT), ("wearing", WEARING), ("hair", HAIR), ("describe", DESCRIBE_ME), ("closest", CLOSEST), ("holding", HOLDING), ("shirt", SHIRT), + ("wear_item", WEAR_ITEM), ("shirt", PATTERN_Q), ("raised", RAISED), ("where", WHERE_THING), ("hand", WHICH_HAND), + ("pointing", POINTING), ("posture", POSTURE), ("doing", DOING), ("friend", FRIEND), ("see_me", SEE_ME), ("how_many", HOW_MANY), ("behind", BEHIND), ("side", SIDE_Q), ("far", HOW_FAR), ("see", SEE_THING), ("there", THERE_IS), ("still", STILL_THERE), ("see_ko", SEE_THING_KO), ("see_more", SEE_MORE), ("what_see", WHAT_SEE)) @@ -741,11 +1400,18 @@ KINDS = (("wearing", WEARING), ("holding", HOLDING), ("shirt", SHIRT), ("raised" def answer(text, lang="en", frames=None, slow_line=None): """The spoken answer when `text` asks about what Lumi sees, else None. frames: scene.load(...) for tests. slow_line(sentence): said before a slow VLM look ("Let me look.").""" - t = text.strip() + ways = canons(text.strip()) asked_at = time.time() # the answer comes from frames taken after this last = _last["kind"] more = (lambda: scene.snapshot(since=time.time())) if frames is None else None # new looks (saved frames: none) - own = next((k for k, rx in KINDS if rx.search(t)), None) # a whole question of its own is answered as asked + own, t = next(((k, w) for w in ways for k, rx in KINDS if rx.search(w)), (None, canon(text.strip()))) + # a whole question of its own is answered as asked, in the first form that asks it + if own is None: # "안경을 벗었습니다. 지금은 어떻습니까?": asked anew + own, t = _changed(t, last) or (None, t) + if own is None: # "저 사람 윗옷은?", "그 사람 glasses는?", "the one on your left?" + own, t = next((g for w in ways if (g := _piece_of_someone(w))), (None, t)) + if own is None and len(ways) > 1 and last: # a mixed follow-up: "진짜 really?", "지금은 now?" + t = next((w for w in ways if AGAIN.search(w) or _follow_up(w, last)[0]), t) if last and _last["asked"] and own is None: got = _check(t, lang, frames, asked_at, slow_line, more) # "really?", "and now?", "it's white": a new look if got: @@ -755,12 +1421,21 @@ def answer(text, lang="en", frames=None, slow_line=None): return None if last and own is None and (HEAD.search(t) or PRAISE.search(t)): return None # "look up" / "nice!" between: "and now?" still asks again - _last["kind"] = None # a follow-up goes only with the turn right before - if ORDER.search(DONE.sub(" ", LOOK_SAID.sub(" ", t))) and not PUT_ON.search(t): + _last["kind"], _last["prev"] = None, last # a follow-up goes only with the turn right before + if own != "describe" and ORDER.search(DONE.sub(" ", LOOK_SAID.sub(" ", re.sub(r"(?:좀\s*)?봐\s*(?:줘|주세요|주십시오|줄래)" if own else "^$", " ", t)))) \ + and not PUT_ON.search(t): return None # "find the red cup and bring it": a fetch, not a question kind = own - if kind == "shirt" and ABOUT_LUMI.search(t): + 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): 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: + _last["who"] = _who(t) + 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 \ (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 @@ -779,7 +1454,51 @@ def answer(text, lang="en", frames=None, slow_line=None): frames = _look(frames, asked_at) if not frames: return _say(*NO_CAMERA, lang) - return _reply(kind, t, frames, lang, slow_line, more) + said = _reply(kind, t, frames, lang, slow_line, more) + 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|" + 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?", "선글라스 썼어?"), + (r"안경|glasses", "wearing", "am I wearing glasses?", "안경 썼어?"), + (r"모자|\bhat\b|\bcap\b|beanie|\bhead\b|머리에", "wearing", "am I wearing a hat?", "모자 썼어?"), + (r"가방|백팩|\bbag\b|backpack", "wearing", "do I have a bag?", "가방 메고 있어?"), + (r"앉았|앉아|일어섰|일어났|\bsat\b|\bstood\b|sitting|standing|\bsit\b|\bstand\b", "posture", "am I sitting or standing?", + "내가 앉아 있어 서 있어?"), + (r"(?:손|hand)\S*\s*(?:을\s*)?(?:내렸|내려|올렸|들었)|\bhands? (?:down|up)\b|lowered|raised", "raised", + "is my hand raised?", "손 들었어?"), + (r"다른\s*손|다른\s*(?:거|것|걸)|옮겼|switched|other hand|put (?:it )?down|내려놨|내려놓|놓았|놨|picked up|something else", "holding", "what am I holding?", + "내가 뭘 들고 있어?"), + (r"재킷|자켓|jacket|겉옷|coat|hoodie|sweater", "shirt", "what colour is my top?", "상의 무슨 색이야?")) + + +def _piece_of_someone(t): + """A piece of another person named without a question word ("저 사람 윗옷은?", "혹시 그분 상의는요?", "그 사람 + glasses는?"): (kind, the question in full) or None.""" + if not (SIDE_WHO.search(t) or re.search(r"(?:저|그|옆)\s*(?:사람|분)|그분|\b(?:her|his|their)\b", t, re.I)): + return None + if re.search(r"머리|\bhair\b", t, re.I): + return "hair", t + (" 무슨 색이야?" if re.search(r"[가-힣]", t) else " what colour?") + if re.search(r"안경|선글라스|모자|마스크|가방|백팩|\b(?:glasses|hat|cap|mask|bag|backpack)\b", t, re.I): + return "wearing", t + if re.search(rf"{_ITEM_KO}|\b(?:{_ITEM})\b", t, re.I): + return "shirt", t + (" 무슨 색이야?" if re.search(r"[가-힣]", t) else " what colour?") + return None + + +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))): + return None + for rx, kind, en, ko in CHANGE_KINDS: + if re.search(rx, t, re.I): + return kind, ko if re.search(r"[가-힣]", t) else en + return None def _look(frames, since): @@ -886,6 +1605,7 @@ def _check(t, lang, frames, since, slow_line, more=None): return None frames = _look(frames, since) _last["kind"] = kind # the thread goes on: "and now?" again + _last["after"] = since # looks (glasses, hair ...) from a new VLM look too if not frames: return _say(*NO_CAMERA, lang) if count: # "no, there are four of us": counted again @@ -937,6 +1657,8 @@ def _check(t, lang, frames, since, slow_line, more=None): return _say(f"I see {thing[0]} in your {o['hand']} hand, but I may be wrong.", f"제 카메라에는 {side[o['hand']]}손에 {_j(thing[1], '이', '가')} 보여요. 틀릴 수도 있어요.", lang) if o is None: + if named and any(((h or {}).get("something") or {}).get("colour") for h in p["hands"].values()): + return _held_answer(frames, lang, None, more, slow_line, hint=named) # "no, it's a bottle": a close look return _empty_hands(lang, now=True) if named: # "nope, this is a book": checked, not agreed if o["name"] == named: @@ -952,6 +1674,24 @@ def _reply(kind, t, frames, lang, slow_line=None, more=None): if kind == "behind": return _say("My cameras look forward, so I can't see what's behind me. " + describe(frames, "en"), "제 카메라는 앞만 보여서 뒤는 볼 수 없어요. " + describe(frames, "ko"), lang) + if kind == "side": # "what's on your right?": what the cameras see there + m = SIDE_Q.search(t) + side = (m.group("e") or m.group("e2") or {"왼": "left", "오른": "right"}[m.group("k")]).lower() + there = f"on my {side}" + n = sum(1 for q in scene.people(frames) if scene.where(q["bearing_deg"]) == there) + names = [] + for h in scene.things(frames): + if h["where"] == there and (h["score"] or 0) >= DESCRIBE_SCORE and h["name"] not in names: + names.append(h["name"]) + names = names[:NEAR_SAY] + en = ([f"{_n(n)} {'person' if n == 1 else 'people'}"] if n else []) + [_a(x) for x in names] + ko = ([f"사람 {n}명"] if n else []) + [_ko_name(x) for x in names] + k = {"left": "왼쪽", "right": "오른쪽"}[side] + if not en: + return _say(f"I don't see anything I can name on my {side} right now.", + f"지금 제 {k}에는 제가 알아볼 수 있는 게 안 보여요.", lang) + return _say(f"On my {side} I see " + (en[0] if len(en) == 1 else ", ".join(en[:-1]) + " and " + en[-1]) + ".", + f"제 {k}에 {_j(', '.join(ko), '이', '가')} 보여요.", lang) if kind == "what_see": if re.search(r"table|desk|테이블|탁자|책상", t, re.I): things = _listing(frames, lang, small_only=True) @@ -986,9 +1726,34 @@ def _reply(kind, t, frames, lang, slow_line=None, more=None): if d is None: return _say("I can't measure how far it is.", "거리는 잴 수 없어요.", lang) return _say(f"The {name} is about {_metres(d)} from me.", f"{_j(_ko_name(name), '은', '는')} 저한테서 {_d(d)}미터쯤 떨어져 있어요.", lang) + if kind == "holding" and _last.get("who", "front") != "front": # "왼쪽에 계신 분 손에 뭐 있어요?" + q = _someone(frames, _last["who"]) + if q is None: + return _say("I only see you right now.", "지금은 한 분만 보여요.", lang) + o = _from(q) + if o: + return _say(f"They're holding {_a(o['name'], o['colour'])} in their {o['hand']} hand.", + f"그분은 {KO_SIDE[o['hand']]}손에 {_j(_ko_name(o['name']), '을', '를')} 들고 계세요.", lang) + if not any(q["hands"].values()): + return _say("I can't see their hands well enough to tell.", "그분 손이 잘 안 보여서 모르겠어요.", lang) + return _say("I don't see anything in their hands.", "그분 손에는 든 게 없어 보여요.", lang) if kind == "holding": return _held_answer(frames, lang, _asked_hand(t), more, slow_line) + if kind == "closest": + return _closest_answer(frames, lang) + if kind == "cant": + if re.search(r"pocket|주머니", t, re.I): + return _say("I can't see inside your pocket.", "주머니 안은 안 보여서 알 수 없어요.", lang) + return _say("I can't count fingers with my cameras; I see the hand, not each finger.", + "제 카메라로는 손가락 개수까지는 알 수 없어요.", lang) p = scene.person_in_front(frames) + if kind in ("wearing", "hair", "describe", "wear_item") and p is not None: + if _last.get("who", "front") != "front": # "is she wearing glasses?", "what about her?" + q = _someone(frames, _last["who"]) + if q is None: + return _say("I only see you right now.", "지금은 한 분만 보여요.", lang) + return _them(_person_reply(kind, t, q, frames, lang, slow_line, more, _last["who"]), lang) + return _person_reply(kind, t, p, frames, lang, slow_line, more, "front") if kind == "friend": # "do you still see my friend?": anyone besides them n = len(scene.people(frames)) - (p is not None) if n > 0: @@ -996,12 +1761,11 @@ 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): # "what is my friend wearing?", "옆 사람 셔츠는 무슨 색이에요?" - q = scene.other_person(frames) + if kind == "shirt" and (OTHER.search(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) - said = _clothes_answer(q, t, lang) - return re.sub(r"\bYou're\b", "They're", re.sub(r"\b([Yy])our\b", lambda m: "Their" if m.group(1) == "Y" else "their", said)) + return _them(_clothes_answer(q, t, lang, _looks(q, frames, lang, None, more, _last.get("who") or "other", wait=False)), lang) if kind == "see_me": if p is None and not scene.people(frames): return _say("No, I can't see you right now.", "아니요, 지금은 안 보여요.", lang) @@ -1014,10 +1778,14 @@ def _reply(kind, t, frames, lang, slow_line=None, more=None): if p["distance_m"] is None: return _say("I can't measure how far you are.", "거리는 잴 수 없어요.", lang) return _say(f"You're about {_metres(p['distance_m'])} from me.", f"저한테서 {_d(p['distance_m'])}미터쯤 떨어져 계세요.", lang) + looks = _looks(p, frames, lang, None, more, wait=False) # only what is cached: never slower for these if kind == "shirt": - return _clothes_answer(p, t, lang) + if PATTERN_ASKED.search(t): # "is my shirt striped?": the VLM's look + return _pattern_answer(p, _looks(p, frames, lang, slow_line, more), lang) + return _clothes_answer(p, t, lang, looks) if kind == "hand": # "which hand?": the one holding something, else one raised - up = UP_ASKED.search(t) # "left or right, which one's up?" + up = UP_ASKED.search(t) or _last.get("prev") == "raised" and not HELD_ASKED.search(t) + # "left or right, which one's up?"; "which hand?" after "is my hand up?" if not up and (HELD_ASKED.search(t) or scene.object_in_hand(frames) or not p["raised"]): return _held_answer(frames, lang, None, more, slow_line) kind = "raised" @@ -1046,18 +1814,30 @@ def _reply(kind, t, frames, lang, slow_line=None, more=None): f"{_j(_ko_name(near['name']), '을', '를')} 가리키시는 것 같아요.", lang) return _say(f"You're pointing with {side} hand, but I can't tell at what.", "손으로 가리키시는 건 보이는데, 무엇인지는 모르겠어요.", lang) + if kind in ("doing", "posture") and _last.get("who", "front") != "front": # "what about her?" after "what am I doing?" + q = _someone(frames, _last["who"]) + if q is None: + return _say("I only see you right now.", "지금은 한 분만 보여요.", lang) + lk = _looks(q, frames, lang, None, more, _last["who"], wait=False) + return _them(_doing_answer(q, frames, lang, lk, own=False) if kind == "doing" else _posture_answer(q, t, lang, lk), lang) if kind == "doing": - return _doing_answer(p, frames, lang) + return _doing_answer(p, frames, lang, looks) if kind == "posture": - return _posture_answer(p, t, lang) - if kind == "wearing": # detections can't tell: ask the picture (slow) - if slow_line: - slow_line(_say("Let me look.", "잠깐 볼게요.", lang)) - said = scene.ask_vlm(t, lang, frames) - return said or _say("Sorry, I can't tell.", "죄송해요, 잘 모르겠어요.", lang) + return _posture_answer(p, t, lang, looks) return None +def _person_reply(kind, t, p, frames, lang, slow_line, more, who): + """Glasses / hat / mask / bag, hair, "what do I look like", "am I wearing a jacket?" about person p.""" + if kind == "wearing": + return _wearing_answer(t, p, frames, lang, slow_line, more, who) + if kind == "hair": + return _hair_answer(t, _looks(p, frames, lang, slow_line, more, who), lang) + if kind == "describe": + return _describe_me(p, frames, lang, slow_line, more, who) + return _wear_item_answer(t, p, frames, lang, slow_line, more, who) or _clothes_answer(p, t, lang) + + RECHECK_S = 30.0 # s; a one-word "really?" this soon after a seeing answer is a new look, also said # while Lumi still talks @@ -1089,6 +1869,24 @@ def facts_for(text): return " " + facts() if ABOUT_VIEW.search(text) or recent else "" +def _looks_line(p): + """" They have short black hair, glasses, ..." from the person's looks of the last LOOKS_S (no new VLM look).""" + lk = p.get("looks") if "looks" in p else _cached_looks("front", p) + if not lk: + return "" + bits = [] + h = lk.get("hair") or {} + if h.get("colour") or h.get("length"): + bits.append(f"{' '.join(x for x in (h.get('length'), h.get('colour')) if x)} hair") + for k, none in (("glasses", "no glasses"), ("hat", "no hat"), ("bag", "no bag")): + if lk.get(k): + bits.append(lk[k] if k != "hat" else f"{lk[k]} on the head") + elif lk.get(k) is False: + bits.append(none) + return ((" They have " + ", ".join(bits) + ".") if bits else "") + \ + (f" They are {lk['action']}." if lk.get("action") else "") + + def facts(frames=None): """One line of what the cameras see now, for the conversation model's prompt ("" when nothing / no camera).""" try: @@ -1103,7 +1901,7 @@ def facts(frames=None): (f", {p['posture']}" if p.get("posture") else "") + \ (", wearing " + ", ".join(f"{c} {NOUN[k][0]}" for k, c in p["clothes"].items() if c) if any(p["clothes"].values()) else "") + \ - (f", holding {_a(o['name'], o['colour'])}" if o else "") + "." + (f", holding {_a(o['name'], o['colour'])}" if o else "") + "." + _looks_line(p) return "Your cameras see now (a new look; it replaces anything said about them before): " + line except Exception as e: print(f"seeing: no facts ({e})", flush=True) diff --git a/tests/test_seeing_people.py b/tests/test_seeing_people.py new file mode 100644 index 0000000..ee47765 --- /dev/null +++ b/tests/test_seeing_people.py @@ -0,0 +1,158 @@ +"""Self-check: questions about a person's looks (glasses, hat, mask, bag, hair, the kind and pattern of clothes, what +they do, who is closest, "what about her?") answered at once from the looks (seeing.norm_looks / scene_looks) and +the measured colours, EN and KO; "really?" asks for a new look; the VLM's JSON normalised; questions about Lumi left +alone. Fake people, no robot, no VLM. python tests/test_seeing_people.py +""" +import re + +from assistant import seeing +from vision import scene + +ME = {"top": "red", "bottom": "black", "top_type": "hoodie", "bottom_type": "jeans", "hair": "long brown", + "glasses": True, "hat": "black cap", "mask": False, "bag": "blue backpack", "action": "looking at a phone", + "pattern": "striped"} +HER = {"top": "blue", "hair": "short black", "glasses": False, "hat": None, "action": "waving"} + + +def person(bearing, dist, clothes, looks): + return {"camera": "head", "box": [0, 0, 1, 1], "distance_m": dist, "bearing_deg": bearing, "position_mm": None, + "facing": True, "raised": [], "pointing": None, "gesture": None, "posture": "standing", + "clothes": clothes, "hands": {"left": {"object": None, "distance_m": dist}, + "right": {"object": None, "distance_m": dist}}, + "seen": 17, "where": scene.where(bearing), "looks": looks} + + +world = {"people": []} +scene._persons = lambda frames=None: world["people"] +scene.people = lambda frames=None: [{"distance_m": p["distance_m"], "bearing_deg": p["bearing_deg"], "camera": "head"} + for p in sorted(world["people"], key=lambda p: p["distance_m"])] +scene.things = lambda frames=None: [] +scene.ask_vlm = lambda *a, **k: None +scene.ask_vlm_person = lambda *a, **k: (_ for _ in ()).throw(AssertionError("the VLM asked in a test")) +FRAMES = [{"camera": "head"}] + + +def setup(me=ME, her=HER, her_nearer=False): + world["people"] = [person(0.0, 1.0, {"upper": me.get("top"), "lower": me.get("bottom"), "feet": None}, + seeing.scene_looks(me))] + if her: + world["people"].append(person(30.0, 0.8 if her_nearer else 2.0, {"upper": her.get("top"), "lower": None, + "feet": None}, seeing.scene_looks(her))) + + +def ask(text): + lang = "ko" if re.search(r"[가-힣]", text) else "en" + return seeing.answer(text, lang, FRAMES) + + +CASES = [ # (question, regex the answer must match; None: not a seeing question) + ("am I wearing glasses?", r"^Yes, you're wearing glasses"), + ("do I have sunglasses on?", r"glasses, not sunglasses"), + ("Lumi, am I wearing a hat?", r"^Yes.*black cap"), + ("what colour is my cap?", r"black cap"), + ("do I have a bag?", r"^Yes.*blue backpack"), + ("am I wearing a mask?", r"^No, I don't see a mask"), + ("what colour is my hair?", r"hair looks brown"), + ("is my hair short?", r"^No, your hair looks long"), + ("is my hair long?", r"^Yes, your hair looks long"), + ("describe me", r"red hoodie.*black jeans.*long brown hair.*glasses"), + ("what do I look like?", r"red hoodie"), + ("who is closest to you?", r"^You are, about 1 metre"), + ("am I wearing a jacket?", r"^No, you're wearing a red hoodie"), + ("am I wearing a hoodie?", r"^Yes, you're wearing a red hoodie"), + ("am I wearing jeans?", r"^Yes, you're wearing black jeans"), + ("am I wearing a blue hoodie?", r"^No, you're wearing a red hoodie"), + ("is my shirt striped?", r"hoodie looks striped"), + ("what am I wearing?", r"red hoodie and black jeans"), + ("what am I doing?", r"looking at a phone"), + ("is she wearing glasses?", r"^No, they're not wearing glasses"), + ("what colour is her hair?", r"^Their hair looks black"), + ("안경 썼어?", r"^네, 안경을 쓰고"), + ("안경 쓰셨나요?", r"^네, 안경을"), + ("모자 쓰고 있어요?", r"검은색 모자를 쓰고"), + ("가방 메고 있습니까?", r"파란색 백팩을 메고"), + ("마스크 썼어?", r"^아니요, 마스크는 안 보여요"), + ("내 머리 무슨 색이야?", r"갈색 머리"), + ("머리 길어?", r"^네, 머리가 길어"), + ("제 머리 짧아요?", r"^아니요, 머리가 길어"), + ("나 어떻게 생겼어?", r"빨간색 후드티.*갈색 머리"), + ("누가 제일 가까워?", r"손님이 제일 가까워요"), + ("청바지 입었어?", r"^네, 검은색 청바지를 입고"), + ("자켓 입고 있어요?", r"^아니요, 빨간색 후드티를 입고"), + ("내가 뭐 입었어?", r"빨간색 후드티에 검은색 청바지"), + ("내가 지금 뭐 하고 있어?", r"휴대폰을 보고 계세요"), + ("그분 머리 무슨 색이에요?", r"검은 머리"), + ("셔츠에 무늬 있어?", r"줄무늬"), + ("루미 머리 무슨 색이야?", None), + ("are you wearing glasses?", None), + ("what colour is your hair?", None), + ("머리 돌려", None), + ("I need a new hat", None), +] + +setup() +bad = 0 +for q, want in CASES: + seeing._last.update(kind=None, asked=None) + got = ask(q) + ok = got is None if want is None else bool(got and re.search(want, got)) + if not ok: + bad += 1 + print(f"FAIL {q!r} -> {got!r} (want {want!r})") + +# follow-ups: "what about her?" / "그 사람은?" ask the same about the other person; "and me?" back +seeing._last.update(kind=None, asked=None) +assert re.search(r"^Yes, you're wearing glasses", ask("am I wearing glasses?")) +assert re.search(r"^No, they're not wearing glasses", ask("what about her?")), seeing._last +assert re.search(r"^Yes, you're wearing glasses", ask("and me?")) +seeing._last.update(kind=None, asked=None) +assert re.search(r"갈색 머리", ask("내 머리 무슨 색이야?")) +assert re.search(r"^그분은 검은 머리", ask("그 사람은?")) +seeing._last.update(kind=None, asked=None) +assert re.search(r"looking at a phone", ask("what am I doing?")) +assert re.search(r"^They're standing.*waving", ask("what about her?")) + +# someone else nearer than the speaker +setup(her_nearer=True) +seeing._last.update(kind=None, asked=None) +assert re.search(r"person on my left in a blue top is closest", ask("who is closest?")) + +# "really?" after a looks answer: a new look (the scene changed: the glasses are off now) +setup() +seeing._last.update(kind=None, asked=None) +assert ask("am I wearing glasses?").startswith("Yes") +setup(me={**ME, "glasses": False}) +assert re.search(r"I looked again\. No, you're not wearing glasses", ask("are you sure?")) + +# a face not in view: no guess; a scene's hat / bag None means none (tests/blind/r6 format) +setup(me={**ME, "glasses": None, "hat": None, "bag": {"kind": "handbag", "colour": "red"}}) +seeing._last.update(kind=None, asked=None) +assert re.search(r"can't see your face", ask("am I wearing glasses?")) +assert re.search(r"^No, I don't see a hat", ask("am I wearing a hat?")) +assert re.search(r"red handbag", ask("do I have a bag?")) +assert re.search(r"빨간색 핸드백", ask("가방 메고 있어요?")) + +# no looks (an older test scene): plain "can't tell", never a guess; the clothes colours still answered +world["people"] = [person(0.0, 1.0, {"upper": "white", "lower": None, "feet": None}, None)] +for p in world["people"]: + del p["looks"] +seeing._last.update(kind=None, asked=None) +assert re.search(r"can't see", ask("am I wearing a hat?")) +assert re.search(r"can't see your hair", ask("what colour is my hair?")) +assert re.search(r"top looks white, but I can't tell if it's a jacket", ask("am I wearing a jacket?")) + +# the VLM's JSON in its several shapes +n = seeing.norm_looks({"top": {"type": "T-shirt", "color": "Gray", "pattern": "plain"}, "bottom": "dark blue jeans", + "hair": {"colour": "black", "length": "short"}, "glasses": False, "sunglasses": True, + "hat": "null", "mask": "none", "bag": {"object": "backpack", "colour": "black"}, + "left_hand": {"object": "cup", "colour": "yellow"}, "right_hand": None, "posture": "standing", + "action": "Waving"}) +assert n["top"] == {"type": "t-shirt", "colour": "grey", "pattern": "plain"}, n["top"] +assert n["bottom"] == {"type": "jeans", "colour": "dark blue", "pattern": None}, n["bottom"] +assert n["glasses"] == "sunglasses" and n["hat"] is None and n["mask"] is False # null: not in view; "none": none +assert n["bag"] == "black backpack" and n["left_hand"] == "yellow cup" and n["action"] == "waving" +assert seeing.norm_looks("not json") is None +assert seeing.scene_looks({"id": "A", "top": "red"}) is None # an older scene: no looks fields + +assert not bad, f"{bad} failed" +print(f"seeing people ok ({len(CASES)} questions)") diff --git a/vision/scene.py b/vision/scene.py index 8800ec6..6b334e1 100644 --- a/vision/scene.py +++ b/vision/scene.py @@ -11,6 +11,8 @@ ask_vlm(question, lang="en") -> one spoken sentence from gemma4 on the picture of the person, or None (slow: 3-20 s) ask_vlm_hand(evidence, lang="en") -> the same about what the person holds, from the picture around the hands and the measured facts; "UNSURE" when it can't tell (slow: 1-30 s) + ask_vlm_person(frames) -> {top, bottom, feet, hair, glasses, hat, mask, bag, left_hand, right_hand, posture, + action} of the person in front from one VLM pass on their picture, or None (slow: 2-15 s) python vision/scene.py # print all of it for the cameras now python vision/scene.py --save tests/data/x # save the frames now as a test fixture (x_head.jpg/.npz/.json, ...) @@ -117,6 +119,23 @@ VLM_HAND_PROMPT = ("You are the eyes of a friendly service robot. The picture sh "shape if that helps, beginning \"It looks like\" unless it is plain to see. Trust the picture over the " "measurements. If the hand is clearly empty, say so. If you can't tell what it is, answer exactly " "UNSURE.") +VLM_PERSON_MODEL = VLM_HAND_MODEL # one look at the whole person: e4b 7-8 s, gemma4:26b 17 s, qwen2.5vl:7b 10 s on the + # same picture with the GPU busy (measured 2026-10-23 23:00); e4b is kept loaded anyway +VLM_PERSON_WIDTH = 320 # px; the person picture sent (448 was not better, only slower) +VLM_PERSON_TIMEOUT_S = 15.0 +VLM_PERSON_PROMPT = ( + "You are the eyes of a service robot. Describe the person nearest the camera as JSON with exactly these keys: " + '"top": {"type": "t-shirt" / "shirt" / "jacket" / "hoodie" / "sweater" / "coat" / "blouse" / "dress" / "vest", ' + '"colour": one colour word, "pattern": "plain" / "striped" / "checked" / "printed" / "dotted"}, ' + '"bottom": {"type": "trousers" / "jeans" / "shorts" / "skirt", "colour": one colour word}, ' + '"feet": {"type": "sneakers" / "shoes" / "boots" / "sandals" / "slippers", "colour": one colour word}, ' + '"hair": {"colour": "black" / "brown" / "blond" / "grey" / "white" / "red" / "dyed", "length": "short" / "medium" / ' + '"long" / "bald"}, "glasses": "none" or "glasses" or "sunglasses", "hat": "none" or what it is with its colour ' + '("black cap"), "mask": "none" or the mask with its colour, "bag": "none" or the bag with its colour ("brown ' + 'backpack"); for these four use null only when that part of the person is not in the picture, ' + '"left_hand": null or the thing in their own left hand with its colour, "right_hand": the same for their right ' + 'hand, "posture": "standing" / "sitting" / "crouching", "action": what they are doing in a few words ("looking at ' + 'a phone", "waving", "carrying a jacket"), "action_ko": the same in polite Korean ("휴대폰을 보고 계세요"). Use null for a part that is not visible. Only what is clearly visible.') _det_lock = threading.RLock() _det = {"net": None} @@ -668,13 +687,17 @@ def _front(frames): def other_person(frames=None): """The nearest person in view other than the one in front (another bearing), described as person_in_front, or None: "what is my friend wearing?".""" - frames = snapshot() if frames is None else frames + p = _other(snapshot() if frames is None else frames) + return _public(p) if p else None + + +def _other(frames): me = _front(frames) if me is None: return None for p in _persons(frames): if abs(p["bearing_deg"] - me["bearing_deg"]) > _same_deg(me["distance_m"]): - return _public(p) + return p return None @@ -694,7 +717,7 @@ def object_in_hand(frames=None): if h and h["object"]: o = h["object"] return {"name": o["name"], "colour": o["colour"], "hand": s, "position_mm": o["position_mm"], - "distance_m": o["distance_m"], "width_mm": o["width_mm"], "score": o["score"]} + "distance_m": o["distance_m"], "width_mm": o["width_mm"], "score": o.get("score")} return None @@ -749,23 +772,48 @@ def ask_vlm(question, lang="en", frames=None): frames = snapshot() if frames is None else frames if not frames: return None - p = _front(frames) + return _vlm(_person_img(frames), VLM_PROMPT.format(lang="Korean" if lang == "ko" else "English", q=question)) + + +def _person_img(frames, p=None): + """The picture of person p (default: the one in front) with a margin, or the whole head view when nobody is there.""" + p = p or _front(frames) if p is not None: f, (x1, y1, x2, y2) = p["_f"], p["box"] mx, my = (x2 - x1) // 6, (y2 - y1) // 10 - img = f["color"][max(0, y1 - my):y2 + my, max(0, x1 - mx):x2 + mx] - else: - img = next((f for f in frames if f["camera"] == "head"), frames[0])["color"] - return _vlm(img, VLM_PROMPT.format(lang="Korean" if lang == "ko" else "English", q=question)) + return f["color"][max(0, y1 - my):y2 + my, max(0, x1 - mx):x2 + mx] + return next((f for f in frames if f["camera"] == "head"), frames[0])["color"] -def _vlm(img, content, width=VLM_WIDTH, timeout=VLM_TIMEOUT_S, model=VLM_MODEL): - """gemma4's words about a picture, or None on a timeout / error.""" +def ask_vlm_person(frames=None, other=False, bearing=None): + """What the person in front (other: the nearest one besides them; bearing: the one seen nearest that bearing) looks + like, from one VLM pass on their picture (VLM_PERSON_PROMPT's keys; None for what it can't see), or None: nobody + there, a timeout or no JSON. Slow: 2-15 s.""" + frames = snapshot() if frames is None else frames + p = (_other if other else _front)(frames) if frames else None + if p is not None and bearing is not None: + p = min(_persons(frames), key=lambda q: abs(q["bearing_deg"] - bearing)) + if p is None: + return None + said = _vlm(_person_img(frames, p), VLM_PERSON_PROMPT, width=VLM_PERSON_WIDTH, timeout=VLM_PERSON_TIMEOUT_S, + model=VLM_PERSON_MODEL, fmt="json", tokens=200) + try: + got = json.loads(said or "") + except ValueError: + print(f"scene: VLM person look gave no JSON ({said!r})", flush=True) + return None + return got if isinstance(got, dict) else None + + +def _vlm(img, content, width=VLM_WIDTH, timeout=VLM_TIMEOUT_S, model=VLM_MODEL, fmt=None, tokens=60): + """gemma4's words about a picture, or None on a timeout / error. fmt "json": the model must answer JSON.""" img = cv2.resize(img, (width, max(1, int(img.shape[0] * width / img.shape[1])))) b64 = base64.b64encode(cv2.imencode(".jpg", img, [cv2.IMWRITE_JPEG_QUALITY, 85])[1]).decode() body = {"model": model, "stream": False, "think": False, "keep_alive": -1, - "options": {"temperature": 0, "num_predict": 60}, + "options": {"temperature": 0, "num_predict": tokens}, "messages": [{"role": "user", "images": [b64], "content": content}]} + if fmt: + body["format"] = fmt try: req = urllib.request.Request(VLM_URL, json.dumps(body).encode(), {"Content-Type": "application/json"}) with urllib.request.urlopen(req, timeout=timeout) as r: