diff --git a/assistant/seeing.py b/assistant/seeing.py index 6887a16..bd5d14b 100644 --- a/assistant/seeing.py +++ b/assistant/seeing.py @@ -10,23 +10,32 @@ the table?", "how many people are here?", "what am I holding?", "what colour is python assistant/seeing.py --load tests/data/scene_white_shirt_near "what colour is my shirt?" Only what the detections give is said; anything else is "I can't tell". Nothing here moves the head. +Every answer comes from frames taken after the words (scene.snapshot(since=...)), also a follow-up right after one +("really?", "and now?", "다시 봐": the same question again) and a correction ("it's white", "오른손이야"), which is +checked against the camera and agreed with only when the camera sees it so. """ import re import sys +import time from assistant import brain from vision import objects, pose, scene NEAR_SAY = 4 # at most this many kinds of things named in "what do you see" DESCRIBE_SCORE = 0.3 # weaker boxes (depth-checked cups) count for "do you see a cup", not in the list +THREAD_S = 60.0 # s; this long after a seeing answer the conversation model gets a new look too +CLAIM_WORDS = 14 # words; a correction is short: "no, it's my right hand", "아니야 흰색이야" BIG = {"dining table", "chair", "couch", "bed", "refrigerator", "sink", "oven", "tv", "toilet", "bench"} # not "on a table" COLOURS = {"white": "white", "red": "red", "blue": "blue", "green": "green", "yellow": "yellow", "black": "black", "orange": "orange", "grey": "grey", "gray": "grey", "purple": "purple", "pink": "pink", + "brown": "brown", "흰": "white", "하얀": "white", "빨간": "red", "파란": "blue", "초록": "green", "노란": "yellow", "검은": "black", - "까만": "black", "주황": "orange", "회색": "grey", "보라": "purple", "분홍": "pink", "핑크": "pink"} + "까만": "black", "주황": "orange", "회색": "grey", "보라": "purple", "분홍": "pink", "핑크": "pink", + "하양": "white", "빨강": "red", "파랑": "blue", "노랑": "yellow", "검정": "black", "까망": "black", "갈색": "brown", + "브라운": "brown"} # "brown" is only said by people: the camera names browns orange COLOUR_KO = {"white": "흰색", "red": "빨간색", "blue": "파란색", "green": "초록색", "yellow": "노란색", "black": "검은색", - "orange": "주황색", "grey": "회색", "purple": "보라색", "pink": "분홍색"} + "orange": "주황색", "grey": "회색", "purple": "보라색", "pink": "분홍색", "brown": "갈색"} 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", @@ -59,49 +68,70 @@ _THING_KO = r"(?:(?P" + "|".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"\b(do|can) you see me\b|\bam i (visible|in (your )?view)\b|(나|저)(를|)? ?보여|(나|저) ?보이", re.I) -SEE_THING = re.compile(r"\b(?:do|can|could) you (?:see|spot|notice)\b.*?\b(?:a|an|the|any|some|my)?\s*" + _THING_EN, re.I) -THERE_IS = re.compile(r"\b(?:is|are) there (?:a|an|any|some)\s+" + _THING_EN + r"(?! (?:open|close|nearby|near here|around here))", - re.I) -SEE_THING_KO = re.compile(_THING_KO + r"(?:이|가|은|는|을|를|도)?\s*(?:보여|보이)") +SEE_THING = re.compile(r"(?" + "|".join(COLOURS) + r")\w*\s*(?:ones?|거|것|걸)?", re.I) # "the blue one", "파란 거" -SEE_KINDS = ("see", "there", "see_ko", "far", "it") +SEE_KINDS = ("see", "there", "still", "see_ko", "far", "it") TAIL = re.compile(r"(?:[\s,]+(?:too|then|also|exactly|again|please|what colou?rs?(?: (?:are|is) (?:they|it))?))+\W*$|" r"(?:도|은|는)?\s*(?:정확히\s*)?(?:무슨\s*)?(?:색깔?|컬러|colou?r)\s*(?:은|는|이야|이에요|이에요)?\W*$|" - r"도\s*(?:보여|보이|있어|있나)\S*\W*$", re.I) # words after a follow-up's noun that ask nothing new + r"도\s*(?:보여|보이|있어|있나)\S*\W*$|(?:은|는)?\s*(?:어때|어떻|어떤가)\S*\W*$", + re.I) # words after a follow-up's noun that ask nothing new WHERE_ON_ME = (("lower", r"(?:down )?below|(?:the )?bottom(?: half)?|(?:on )?(?:the )?lower (?:half|part)|밑(?:에|쪽)?\w?|아래(?:쪽)?(?:에)?\w?"), ("upper", r"(?:up )?above|(?:the )?top half|위(?:쪽)?(?:에)?\w?"), ("feet", r"on my feet|발(?:에)?\w?")) # "how about below?" after a clothes answer: the trousers @@ -135,9 +166,34 @@ IT_WHERE = re.compile(r"^\W*(?:(?:and|so|then|ok(?:ay)?)\W+)*(?:where(?: is (?:i IT_COLOUR = re.compile(r"\bwhat colou?r is (?:it|that)\b|^\W*(?:그거|그건|저거)?\s*무슨\s*색", re.I) IT_SIZE = re.compile(r"\b(?:is it|is that|how) (?:big|large|small|tall|high|wide)\b|^\W*(?:그거|저거)?\s*(?:커|작아|크기)", re.I) IT_COUNT = re.compile(r"^\W*(?:how many(?: \w+)?|any (?:others|more)|몇\s*개\S*)\W*$", re.I) +_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)?|" + r"what(?:'s| is)? (?:it|that)|is it|right|just) )?(?: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|" + r"\blook (?:closer|carefully|properly)\b|^\W*again\W*$|" + r"\bare you (?:sure|shore|certain|positive)\b|^\W*(?:\w+\W+){0,2}(?:really|seriously|for real)\W*$|" + r"^\W*(?:you(?:'re)?\s+)?(?:sure|positive|certain)\S{0,2}\s*\?|" + r"\bis (?:it|that|this) (?:really|right|true|correct|so)\b|\breally\b.{0,25}\?|" + r"^\W*(?:(?:그럼|근데|아니)\s*)?(?:(?:진짜|정말)\S{0,2}\s*)?(?:진짜|정말|확실|맞아|맞나|맞습니까|틀림없)\S{0,4}\s*\?|" + r"^\W*(?:진짜|정말)\S{0,3}\W*$|지금은|이제는|\bnow\s*(?:은|는)|^\W*(?:그럼\s*)?(?:지금|이제)\s*\??\W*$|" + r"(?:지금|이제)\S{0,2}\s*(?:어때|어떻|어떤가)|^\W*(?:지금|이제|now)\s+(?:손에\s*)?(?:뭐|뭘|무엇을?)\s*(?:들고|쥐고|있)|" + r"다시\s*(?:한\s*번\s*|한번\s*)?(?:봐|보|확인|check|체크)|자세히\s*(?:다시\s*)?봐|잘\s*봐|또\s*봐", re.I) + # a new look at the same question: "are you sure?", "다시 한번 확인해 줄래요?" +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", + 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) +COLOUR_SAID = re.compile(r"(?P\bnot (?:\w+ ){0,2}|n't (?:\w+ ){0,2})?\b(?P" + "|".join(c for c in COLOURS if c.isascii()) + + r")\b|(?P" + "|".join(c for c in COLOURS if not c.isascii()) + r")\w*(?P\s*아니)?", re.I) _last = {"thing": None, # the thing seen last: "how far is it?" "name": None, # the kind of thing asked about last: "and the blue one?" - "kind": None} # the kind of the question just answered: "what about my jeans?" after the shirt + "kind": None, # the kind of the question just answered: "what about my jeans?" after the shirt + "asked": None, # (kind, words) of that question: "really?", "and now?" ask it again + "parts": [], # [(part, word, colour)] said in the clothes answer: "it's white" is about these + "at": 0.0} # time.time() of the last seeing answer def _follow_up(t, last): @@ -147,7 +203,7 @@ def _follow_up(t, last): for rx in (FOLLOW_EN, FOLLOW_KO): m = rx.match(t) x = m.group("x") if m else "" - if last in ("shirt", "wearing"): + if last: # "바지는?" after any seeing answer for part, said in WHERE_ON_ME: # "and below?", "그럼 아래는?" if re.fullmatch(said, x, re.I): return "shirt", NOUN[part][rx is FOLLOW_KO] @@ -297,9 +353,10 @@ def _held_answer(frames, lang): if o: hand = {"left": ("left", "왼"), "right": ("right", "오른")}[o["hand"]] return _say(f"You're holding {_a(o['name'], o['colour'])} in your {hand[0]} hand.", - f"{hand[1]}손에 {COLOUR_KO.get(o['colour'], '')} {_j(_ko_name(o['name']), '을', '를')} 들고 계세요.", lang) + f"{hand[1]}손에 {COLOUR_KO[o['colour']] + ' ' if o['colour'] in COLOUR_KO else ''}" + f"{_j(_ko_name(o['name']), '을', '를')} 들고 계세요.", lang) if scene.person_holds(None, frames) is False: - return _say("I don't see anything in your hands.", "손에 든 게 안 보여요.", lang) + return _say("I don't see anything I can recognise in your hands.", "손에 제가 알아볼 수 있는 건 없어요.", lang) return _say("I can't see your hands well enough to tell.", "손이 잘 안 보여서 모르겠어요.", lang) @@ -316,10 +373,11 @@ def _clothes_answer(p, text, lang): w = m.group(0).lower() if bool(re.match(r"[a-z]", w)) != (lang == "en") or w in ("feet", "foot") or w[0] == "신" and w != "신발": w = NOUN[part][lang != "en"] - w = {"genes": "jeans", "jean": "jeans", "trouser": "trousers", "청바진": "청바지", "청 바지": "청바지"}.get(w, w) + 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] + _last["parts"] = seen if len(seen) == 1: part, w, c = seen[0] if c is None: @@ -361,21 +419,30 @@ def _doing_answer(p, frames, lang): return _say(", ".join(en) + ".", " ".join(ko).rstrip("고").rstrip("시") + "세요.", lang) +KINDS = (("wearing", WEARING), ("holding", HOLDING), ("shirt", SHIRT), ("raised", RAISED), ("hand", WHICH_HAND), + ("pointing", POINTING), ("doing", DOING), ("friend", FRIEND), ("see_me", SEE_ME), ("how_many", HOW_MANY), ("behind", BEHIND), + ("far", HOW_FAR), ("see", SEE_THING), ("there", THERE_IS), ("still", STILL_THERE), ("see_ko", SEE_THING_KO), + ("what_see", WHAT_SEE)) + + 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() + asked_at = time.time() # the answer comes from frames taken after this last = _last["kind"] + own = next((k for k, rx in KINDS if rx.search(t)), None) # a whole question of its own is answered as asked + if last and _last["asked"] and own is None: + got = _check(t, lang, frames, asked_at, slow_line) # "really?", "and now?", "it's white": a new look + if got: + _last["at"] = time.time() + return got if brain.is_backchannel(t) and not BYE.search(t): # "nice!" between keeps the thread: "and my jeans?" return None _last["kind"] = None # a follow-up goes only with the turn right before - if ORDER.search(t): + if ORDER.search(t) and not PUT_ON.search(t): return None # "find the red cup and bring it": a fetch, not a question - kind = next((k for k, rx in (("wearing", WEARING), ("holding", HOLDING), ("shirt", SHIRT), ("raised", RAISED), - ("pointing", POINTING), ("doing", DOING), ("see_me", SEE_ME), ("how_many", HOW_MANY), - ("behind", BEHIND), ("far", HOW_FAR), ("see", SEE_THING), ("there", THERE_IS), - ("see_ko", SEE_THING_KO), - ("what_see", WHAT_SEE)) if rx.search(t)), None) + kind = own if kind == "shirt" and ABOUT_LUMI.search(t): return None # "루미는 무슨 옷 입었어?": about Lumi, not the visitor if kind is None and last in SEE_KINDS and _last["thing"] and not ABOUT_LUMI.search(t) and \ @@ -391,10 +458,127 @@ def answer(text, lang="en", frames=None, slow_line=None): elif _last["thing"] is None or last not in SEE_KINDS or re.search(r"\bit\s+(?:to|from)\b", t, re.I) or \ not (IT.search(t) or FAR_BARE.match(t)): return None # "how far is Seoul?": not about the cameras - _last["kind"] = kind - frames = scene.snapshot() if frames is None else frames + _last["kind"], _last["asked"], _last["at"] = kind, (kind, t), time.time() + frames = _look(frames, asked_at) if not frames: return _say(*NO_CAMERA, lang) + return _reply(kind, t, frames, lang, slow_line) + + +def _look(frames, since): + """The frames given (tests), else the cameras' frames taken after `since` (the question), never older ones.""" + return scene.snapshot(since=since) if frames is None else frames + + +def _side(t): + """The hand a correction names: "it's in my right hand", "not right, the left", "왼손이야" -> "left" / "right".""" + said, denied = [], set() + for m in HAND_SAID.finditer(NOT_A_HAND.sub(" ", t)): + s = (m.group("s") or {"왼": "left", "오른": "right"}[m.group("k")]).lower() + (denied.add(s) if m.group("n") or m.group("kn") else said.append(s)) + if said: + return said[-1] + return {"left": "right", "right": "left"}[denied.pop()] if len(denied) == 1 else None + + +def _colours(t): + """(colour said, colours denied) in a correction: "no, it's not blue, it's white" -> ("white", {"blue"}). A colour + before a noun asks about that thing ("what about my blue jeans?").""" + said, denied = [], set() + if LIKED.search(t): + return None, denied + for m in COLOUR_SAID.finditer(t): + if re.match(rf"\s+(?:(?:{_ITEM})\b|{_THING_EN})", t[m.end():], re.I): + continue + c = COLOURS[(m.group("c") or m.group("k")).lower()] + (denied.add(c) if m.group("n") or m.group("kn") else said.append(c)) + return (said[-1] if said else None), denied - set(said[-1:]) + + +def _verdict(c, said, denied, en, ko, verb, lang, before=None): + """A colour the person said (or denied) against the colour the camera sees now: agree only when it agrees. + before: the colour said in the answer before.""" + if c is None: + return _say(f"I can't see {en} well enough right now.", f"지금은 {_j(ko, '이', '가')} 잘 안 보여요.", lang) + k = COLOUR_KO.get(c, c) + if said == c or said is None and c not in denied: + lead = ("Yes, " if said else "You're right, looking again ", "네, " if said else "맞아요, 다시 보니 ") + return _say(f"{lead[0]}{en} {verb} {c}.", f"{lead[1]}{_j(ko, '은', '는')} {k}으로 보여요.", lang) + if said and {said, c} <= objects.LIGHT: # white in shade reads grey: both may be true + return _say(f"To my camera {en} {verb} {c}; in this light it may well be {said}.", + f"제 카메라에는 {k}으로 보이는데, 이 조명에서는 {COLOUR_KO.get(said, said)}일 수도 있어요.", lang) + if c != before: # the new look sees otherwise than the answer before + return _say(f"Looking again, {en} {verb} {c}" + (f", not {said}." if said else "."), + f"다시 보니 {_j(ko, '은', '는')} {k}으로 보여요.", lang) + return _say(f"My camera still sees {en} as {c}, but I may be wrong; the light can change colours.", + f"제 카메라에는 아직 {_j(ko, '이', '가')} {k}으로 보여요. 조명 때문에 틀릴 수도 있어요.", lang) + + +def _check(t, lang, frames, since, slow_line): + """A follow-up right after a seeing answer, from a new look: "really?", "and now?", "look again", "다시 봐" ask the + same question again; "it's white", "no, it's in my right hand", "아니야 흰색이야" are checked against the camera + (agreed only when it sees so, else what it sees and that it may be wrong). None: not such a follow-up.""" + kind, asked = _last["asked"] + again = AGAIN.search(t) + short = len(t.split()) <= CLAIM_WORDS and \ + not (ORDER.search(re.sub(r"\W+look\W*$", "", t)) and not again) # "put it in my right hand"; "..., look" + hand = _side(t) if short and kind in ("holding", "hand", "raised") else None + said, denied = _colours(t) if short and kind in ("shirt", "holding", "hand") else (None, set()) + if not (hand or said or denied or again): + return None + frames = _look(frames, since) + _last["kind"] = kind # the thread goes on: "and now?" again + if not frames: + return _say(*NO_CAMERA, lang) + if not (hand or said or denied): + got = _reply(kind, asked, frames, lang, slow_line) + return got and _say("I looked again. ", "다시 봤어요. ", lang) + got + 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?", + "잘 안 보여서 모르겠어요. 제 앞으로 와 주시겠어요?", lang) + if kind == "shirt": + parts = [(part, w) for part, w, _ in _last["parts"]] or [("upper", NOUN["upper"][lang != "en"])] + named = [part for part, rx in PARTS if re.search(rx, t, re.I)] # "my pants are black" + part, w = next(((a, w) for a, w in parts if a in named), None) or \ + ((named[0], NOUN[named[0]][lang != "en"]) if named else None) or \ + next(((a, w) for a, w, c in _last["parts"] if c in denied), parts[0]) + before = next((c for a, _, c in _last["parts"] if a == part), None) + c = p["clothes"].get(part) + _last["parts"] = [(a, x, c if a == part else y) for a, x, y in _last["parts"]] # "still" next time + if bool(re.match(r"[a-z]", w)) != (lang == "en"): + w = NOUN[part][lang != "en"] + return _verdict(c, said, denied, f"your {w}", w, "look" if w.endswith("s") else "looks", lang, before) + side = {"left": "왼", "right": "오른"} + if kind == "raised": # "it's my left hand" after "is my hand up?" + up = p["raised"] + if hand in up: + return _say(f"Yes, your {hand} hand is up.", f"네, {side[hand]}손을 들고 계세요.", lang) + if up: + return _say(f"I see your {up[0]} hand up, but I may be wrong.", + f"제 카메라에는 {side[up[0]]}손을 드신 걸로 보여요. 틀릴 수도 있어요.", lang) + return _say("I don't see a hand raised now.", "지금은 손을 들고 계시지 않아요.", lang) + o = scene.object_in_hand(frames) + if hand: + inn = ((p["hands"].get(hand) or {}).get("object")) + o = {**inn, "hand": hand} if inn else o + if o is None: + if scene.person_holds(None, frames) is False: + return _say("I don't see anything I can recognise in your hands now.", "지금은 손에 제가 알아볼 수 있는 건 없어요.", lang) + return _say("I can't see your hands well enough to tell.", "손이 잘 안 보여서 모르겠어요.", lang) + thing = (_a(o["name"], o["colour"]), _ko_name(o["name"])) + if o["hand"] == hand: + return _say(f"Yes, I see {thing[0]} in your {hand} hand.", + f"네, {side[hand]}손에 {_j(thing[1], '이', '가')} 보여요.", lang) + 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: + return _say("I don't see anything I can recognise in your hands now.", "지금은 손에 제가 알아볼 수 있는 건 없어요.", lang) + return _verdict(o["colour"], said, denied, f"the {o['name']}", _ko_name(o["name"]), "looks", lang) + + +def _reply(kind, t, frames, lang, slow_line=None): + """The answer to a question of this kind (answer() read it) from these frames.""" 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) @@ -408,8 +592,8 @@ def answer(text, lang="en", frames=None, slow_line=None): n = len(scene.people(frames)) return _say(f"I see {_n(n)} {'person' if n == 1 else 'people'} right now." if n else "I don't see anyone right now.", f"지금 {n}명이 보여요." if n else "지금은 아무도 안 보여요.", lang) - if kind in ("see", "there", "see_ko"): - m = {"see": SEE_THING, "there": THERE_IS, "see_ko": SEE_THING_KO}[kind].search(t) + if kind in ("see", "there", "still", "see_ko"): + m = {"see": SEE_THING, "there": THERE_IS, "still": STILL_THERE, "see_ko": SEE_THING_KO}[kind].search(t) name, colour = _thing(m) if name is None: return None @@ -434,6 +618,19 @@ def answer(text, lang="en", frames=None, slow_line=None): if kind == "holding": return _held_answer(frames, lang) p = scene.person_in_front(frames) + if kind == "friend": # "do you still see my friend?": anyone besides them + n = len(scene.people(frames)) - (p is not None) + if n > 0: + return _say(f"Yes, I see {_n(n)} other {'person' if n == 1 else 'people'} besides you.", + 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 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)) if kind == "see_me": if p is None and not scene.people(frames): return _say("No, I can't see you right now.", "아니요, 지금은 안 보여요.", lang) @@ -448,13 +645,17 @@ def answer(text, lang="en", frames=None, slow_line=None): return _say(f"You're about {p['distance_m']:.1f} metres from me.", f"저한테서 {p['distance_m']:.1f}미터쯤 떨어져 계세요.", lang) if kind == "shirt": return _clothes_answer(p, t, lang) + if kind == "hand": # "which hand?": the one holding something, else one raised + if scene.object_in_hand(frames) or not p["raised"]: + return _held_answer(frames, lang) + kind = "raised" if kind == "raised": if p["raised"]: return _say(f"Yes, your {' and '.join(p['raised'])} hand is up.", "네, " + " ".join({"left": "왼손", "right": "오른손"}[s] for s in p["raised"]) + "을 들고 계세요.", lang) if not any(p["hands"].values()): return _say("I can't see your hands well enough to tell.", "손이 잘 안 보여서 모르겠어요.", lang) - return _say("No, your hands are down.", "아니요, 손을 들고 계시지 않아요.", lang) + return _say("No, your hands are down.", "아니요, 지금은 손을 안 들고 계세요.", lang) if kind == "pointing": if not p["pointing"]: return _say("I don't see you pointing.", "가리키고 계신 게 안 보여요.", lang) @@ -496,15 +697,16 @@ def warm_up(): def facts_for(text): - """" " + facts() for words about what Lumi sees that answer() did not take, else "" (the model then answers - from what the cameras see instead of guessing).""" - return " " + facts() if ABOUT_VIEW.search(text) else "" + """" " + facts() for words about what Lumi sees that answer() did not take, and for anything said soon after a + seeing answer, else "" (the model then answers from what the cameras see now, not from what it said before).""" + recent = time.time() - _last["at"] < THREAD_S + return " " + facts() if ABOUT_VIEW.search(text) or recent else "" def facts(frames=None): """One line of what the cameras see now, for the conversation model's prompt ("" when nothing / no camera).""" try: - frames = scene.snapshot() if frames is None else frames + frames = _look(frames, time.time()) if not frames: return "" line = describe(frames, "en") @@ -515,7 +717,7 @@ def facts(frames=None): (", 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 "") + "." - return "Your cameras see now: " + line + 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) return "" diff --git a/tests/followup_cases_more.py b/tests/followup_cases_more.py index 15f3c01..c082c20 100644 --- a/tests/followup_cases_more.py +++ b/tests/followup_cases_more.py @@ -126,12 +126,12 @@ CASES_MORE = [ C([SHIRT], "does it suit me?", "llm", "an opinion, not a camera fact"), C([SHIRT_KO], "잘 어울려?", "llm", "의견: 카메라 사실이 아님"), C([SHIRT], "is white your favourite colour?", "llm", "about Lumi's taste"), - C([SHIRT], "are you sure?", "llm", "a check of the last answer"), - C([SHIRT_KO], "확실해?", "llm", "확인 질문"), + C([SHIRT], "are you sure?", "seeing", "a check of the last answer: a new look (2026-10-22)", r"looked again.*white"), + C([SHIRT_KO], "확실해?", "seeing", "확인 질문: 다시 보기 (2026-10-22)", r"다시 봤어요.*흰색"), C([SHIRT], "why?", "llm", "why does it look white: the model explains"), C([SHIRT], "nope", "llm", "the user says the answer is wrong"), - C([SHIRT], "wrong, it's grey", "llm", "a correction of Lumi, not a new question"), - C([SHIRT_KO], "아닌데? 회색인데", "llm", "루미 답 정정: 새 질문 아님"), + C([SHIRT], "wrong, it's grey", "seeing", "a correction is checked against the camera (2026-10-22)", r"looks white; in this light it may well be grey"), + C([SHIRT_KO], "아닌데? 회색인데", "seeing", "정정은 카메라로 확인 (2026-10-22)", r"흰색으로 보이는데.*회색일 수도"), # ---------- anaphora after a thing seen (room frames) ---------- C([PLANT], "where is it?", "seeing", "where is the plant", SIDE, fr="room"), @@ -215,7 +215,7 @@ CASES_MORE = [ C([SHIRT, T("okay thanks", "You're welcome.")], "and my shoes?", "seeing", "thanks between, then one more clothes question", NO_FEET), # back-channels as the turn itself: a reaction, not a camera question - C([PLANT], "진짜?", "talk", "mixed: a reaction", fr="room"), + C([PLANT], "진짜?", "seeing", "a doubt right after a seeing answer: a new look (2026-10-22)", r"다시 봤어요", fr="room"), C([PLANT], "oh nice", "talk", "a reaction", fr="room"), C([CUP], "wow", "talk", "a reaction", fr="room"), C([PLANT_KO], "헐 대박", "talk", "놀람", fr="room"), diff --git a/tests/test_scene.py b/tests/test_scene.py index 3c4992c..1f53c67 100644 --- a/tests/test_scene.py +++ b/tests/test_scene.py @@ -74,7 +74,8 @@ f = fx("holding_cup_back") p = scene.person_in_front(f) assert p and p["clothes"]["upper"] == "blue" and p["pointing"] is None and p["facing"] is False, p assert scene.object_in_hand(f) is None and scene.person_holds("cup", f) is None # depth stale: can't tell -assert say("what am I wearing?", f) == "You're wearing a blue top and blue trousers. I can't see your shoes from here." +assert say("what am I wearing?", f) == "You're wearing a blue top and black trousers. I can't see your shoes from here." + # the trousers are near black (V ~48): no hue there (2026-10-22 live: "blue") # ---------- a white shirt against a bright window: the pixels read grey (V 107), the face darker still (V 70) ---------- f = fx("white_shirt_backlit") diff --git a/tests/test_seeing_dialogues.py b/tests/test_seeing_dialogues.py new file mode 100644 index 0000000..04f006e --- /dev/null +++ b/tests/test_seeing_dialogues.py @@ -0,0 +1,141 @@ +"""The blind seeing dialogues (tests/blind/train/seeing_dialogues.py, scenes that change between turns) through +lumi.route with seeing.answer, on fake cameras that show each turn's scene; no robot, no LLM. A turn passes when it +goes the way it should (seeing / not seeing) and a seeing reply matches every `must` and no `must_not`. Turns the +conversation model answers are only checked for their route. + + python tests/test_seeing_dialogues.py # score, the failures to logs/seeing_dialogues.log + python tests/test_seeing_dialogues.py --min 0.9 # fails below this part of the turns right +""" +import re +import sys +import time +from pathlib import Path + +from assistant import brain, lumi, seeing +from tests.blind.train.seeing_dialogues import DIALOGUES +from vision import scene + +MARKS = ["home", "dock2", "p1", "p2", "p3", "p4", "p5"] +LOG = Path(__file__).resolve().parents[1] / "logs" / "seeing_dialogues.log" +BEARING = {"front": 0.0, "left": 30.0, "right": -30.0} +now = {"scene": {"people": [], "objects": []}} + + +def _where(side): + return scene.where(BEARING.get(side, 0.0)) + + +def snapshot(cameras=scene.CAMERAS, since=None): + assert since is not None and since <= time.time() + return [{"camera": "head", "scene": now["scene"]}] + + +def _scene(frames): + return frames[0]["scene"] + + +def _front(frames): + near = [p for p in _scene(frames)["people"] if (p.get("dist_m") or 0) <= scene.FRONT_M] + return min(near, key=lambda p: p.get("dist_m") or 99) if near else None + + +def _thing(name, colour): + """A held thing as the detector gives it, None for one it has no class for (a watch: COCO has none).""" + name = seeing._name(name) or None + return name and {"name": name, "colour": colour, "position_mm": None, "distance_m": None, "width_mm": None} + + +def person_in_front(frames=None): + p = _front(frames) + if p is None: + return None + seen = p.get("hands_visible", True) + hands = {s: ({"position_mm": None, "object": _thing(*p[f"{s}_hand"]) if isinstance(p.get(f"{s}_hand"), (list, tuple)) + else (_thing(p[f"{s}_hand"], None) if p.get(f"{s}_hand") else None)} if seen else None) + for s in ("left", "right")} + return {"distance_m": p.get("dist_m"), "bearing_deg": BEARING.get(p.get("side"), 0.0), "where": _where(p.get("side")), + "position_mm": None, "camera": "head", "facing": True, "gesture": None, + "raised": [p["raised"]] if p.get("raised") else [], "pointing": None, "hands": hands, + "clothes": {"upper": p.get("top"), "lower": p.get("bottom"), "feet": p.get("feet")}} + + +def other_person(frames=None): + me = _front(frames) + rest = sorted((p for p in _scene(frames)["people"] if p is not me), key=lambda p: p.get("dist_m") or 99) + if me is None or not rest: + return None + return person_in_front([{"scene": {"people": [rest[0]], "objects": []}}]) + + +def object_in_hand(frames=None): + p = person_in_front(frames) + for s in ("right", "left"): + h = p and p["hands"][s] + if h and h["object"]: + return {**h["object"], "hand": s} + return None + + +def person_holds(obj=None, frames=None): + p = person_in_front(frames) + if p is None or not any(p["hands"].values()): + return None + return object_in_hand(frames) is not None + + +def things(frames=None): + out = [{"name": o["name"], "colour": o.get("colour"), "distance_m": o.get("dist_m"), + "bearing_deg": BEARING.get(o.get("side"), 0.0), "where": _where(o.get("side")), "camera": "head", + "position_mm": None, "score": 0.9, "box": (0, 0, 1, 1)} for o in _scene(frames)["objects"]] + return sorted(out, key=lambda t: t["distance_m"] or 99) + + +scene.snapshot = snapshot +scene.person_in_front = person_in_front +scene.other_person = other_person +scene.object_in_hand = object_in_hand +scene.person_holds = person_holds +scene.things = things +scene.people = lambda frames=None: [{"distance_m": p.get("dist_m"), "bearing_deg": BEARING.get(p.get("side"), 0.0), + "camera": "head"} for p in _scene(frames)["people"]] +scene.pointing_target = lambda frames=None: None +scene.ask_vlm = lambda q, lang="en", frames=None: None + + +def lang_of(text): + return "ko" if re.search(r"[가-힣]", text) else "en" + + +def run(): + ok, bad = 0, [] + for n, d in enumerate(DIALOGUES): + seeing._last.update(thing=None, name=None, kind=None, asked=None, parts=[], at=0.0) + b = brain.Brain() + for i, turn in enumerate(d["turns"]): + now["scene"] = turn["scene"] + text, lang = turn["say"], lang_of(turn["say"]) + brain.FORCED_LANG["lang"] = lang + kind, data = lumi.route(text, MARKS, b, seen=lambda x: seeing.answer(x, lang)) + got = data if kind == "seeing" else None + if got: + b.history.append((text, f"ACTION: none -\n{got}")) + want = turn["route"] + if want == "seeing": + good = bool(got) and all(re.search(m, got, re.I) for m in turn["must"]) and \ + not any(re.search(m, got, re.I) for m in turn["must_not"]) + else: + good = not got + ok += good + if not good: + bad.append(f"[{n} {d['topic']} #{i}] {text!r} -> {kind}: {got!r}\n want {want} {turn['must']} " + f"not {turn['must_not']} ({turn['check']})") + return ok, bad + + +if __name__ == "__main__": + ok, bad = run() + n = ok + len(bad) + LOG.write_text(f"seeing dialogues (train) {time.strftime('%Y-%m-%d %H:%M')}: {ok}/{n} turns right\n\n" + "\n".join(bad)) + print(f"seeing dialogues: {ok}/{n} turns right ({LOG})") + if "--min" in sys.argv: + assert ok >= float(sys.argv[sys.argv.index("--min") + 1]) * n diff --git a/tests/test_seeing_fresh.py b/tests/test_seeing_fresh.py new file mode 100644 index 0000000..a33582e --- /dev/null +++ b/tests/test_seeing_fresh.py @@ -0,0 +1,189 @@ +"""Self-check: every seeing answer, follow-up ("really?", "and now?", "다시 봐") and correction ("it's white", +"no, it's in my right hand", "아니야 흰색이야") is answered from a new look taken after the words, never from what was +said before; a correction is agreed with only when the camera sees it so. Fake cameras whose world changes between +turns; no robot, no LLM. python tests/test_seeing_fresh.py +""" +import json +import re +import tempfile +import time +from pathlib import Path + +import cv2 +import numpy as np + +from assistant import brain, lumi, seeing +from vision import camview, objects, scene + +MARKS = ["home", "dock2", "p1", "p2", "p3", "p4", "p5"] +world = {} # what is in front of the fake cameras now; the test changes it between turns +looks = [] # (since, frame number) of every snapshot asked for + + +def snapshot(cameras=scene.CAMERAS, since=None): + assert since is not None and since <= time.time(), "a look must be taken after the question" + looks.append((since, len(looks))) + return [{"camera": "head", "n": len(looks)}] + + +def _now(frames): + assert frames[0]["n"] == len(looks), "answered from an older look" + return world + + +def person_in_front(frames=None): + w = _now(frames) + if not w.get("person", True): + return None + hands = {s: {"position_mm": None, "object": None} for s in ("left", "right")} + if w.get("hand"): + hands[w["hand"]]["object"] = {"name": w["thing"], "colour": w["colour"], "position_mm": None, + "distance_m": 0.8, "width_mm": None} + return {"distance_m": 1.0, "bearing_deg": 0.0, "where": "in front of me", "position_mm": None, "camera": "head", + "facing": True, "gesture": None, "raised": [], "pointing": None, "hands": hands, + "clothes": {"upper": w.get("upper"), "lower": w.get("lower"), "feet": None}} + + +def object_in_hand(frames=None): + w = _now(frames) + if not w.get("hand"): + return None + return {"name": w["thing"], "colour": w["colour"], "hand": w["hand"], "position_mm": None, "distance_m": 0.8, + "width_mm": None} + + +real_snapshot = scene.snapshot +scene.snapshot = snapshot +scene.person_in_front = person_in_front +scene.object_in_hand = object_in_hand +scene.person_holds = lambda obj=None, frames=None: bool(_now(frames).get("hand")) +scene.people = lambda frames=None: [{}] if _now(frames).get("person", True) else [] +scene.ask_vlm = lambda q, lang="en", frames=None: "VLM" +scene.things = lambda frames=None: [] + + +def lang_of(text): + return "ko" if re.search(r"[가-힣]", text) else "en" + + +def say(text): + """What lumi.answer() does with the words: lumi.route with seeing.answer first; "llm" when it goes on to the model.""" + b = brain.Brain() + kind, data = lumi.route(text, MARKS, b, seen=lambda x: seeing.answer(x, lang_of(x))) + return data if kind == "seeing" else "llm" + + +def dialogue(turns): + """turns: (words, world change before them or None, regex the answer must match; "llm": not a seeing answer).""" + seeing._last.update(thing=None, name=None, kind=None, asked=None, parts=[], at=0.0) + for words, change, want in turns: + if change: + world.update(change) + n = len(looks) + t = time.time() + got = say(words) + if want == "llm": + assert got == "llm", f"{words!r} -> {got!r} (want the conversation model)" + continue + assert got != "llm" and re.search(want, got, re.I), f"{words!r} -> {got!r} (want {want!r})" + assert len(looks) > n and looks[-1][0] >= t, f"{words!r}: answered without a new look" + + +START = {"person": True, "hand": "left", "thing": "cell phone", "colour": "grey", "upper": "white", "lower": "black"} + +# the owner's live dialogues of 2026-10-22 +world.update(START) +dialogue([("What is my hand?", None, r"grey cell phone in your left hand"), + ("What about now?", {"hand": "right"}, r"looked again.*right hand"), + ("and now?", {"hand": "left"}, r"looked again.*left hand"), + ("Right now.", {"hand": "right"}, r"right hand"), + ("No, it's my left hand.", None, r"^I see .* in your right hand, but I may be wrong"), + ("It's in the right.", None, r"^Yes, I see a grey cell phone in your right hand"), + ("Look at the again. It's not right hand. It's the left hand.", {"hand": "left"}, r"^Yes, .*left hand"), + ("So, where is it now?", {"hand": "right"}, r"right hand"), + ("Left hand.", None, r"right hand, but I may be wrong")]) + +world.update(START) +dialogue([("What is the color of my t-shirt?", {"upper": "blue"}, r"t-shirt looks blue"), + ("Is it really blue?", {"upper": "white"}, r"^Looking again, your t-shirt looks white, not blue"), + ("really?", None, r"looked again.*white"), + ("are you sure?", {"upper": "blue"}, r"looked again.*blue"), + ("No, it's white.", None, r"still sees your t-shirt as blue, but I may be wrong"), + ("it's white", {"upper": "white"}, r"^Yes, your t-shirt looks white"), + ("It's grey.", None, r"looks white; in this light it may well be grey"), + ("look again", {"upper": "blue"}, r"looked again.*blue")]) + +world.update(START) +dialogue([("Okay, what's the color of my pants?", {"lower": "blue"}, r"pants look blue"), + ("Is that blue?", {"lower": "black"}, r"^Looking again, your pants look black, not blue"), + ("No, it's not blue.", None, r"^You're right, .*pants look black"), + ("What is the color of the pants?", None, r"pants look black"), + ("what about my blue jeans?", None, r"jeans look black"), + ("is white your favourite colour?", None, "llm")]) + +world.update(START) +dialogue([("내 티셔츠 무슨 색이야?", {"upper": "blue"}, r"티셔츠는 파란색"), + ("아니야 흰색이야", None, r"파란색으로 보여요. 조명 때문에 틀릴 수도"), + ("다시 봐", {"upper": "white"}, r"다시 봤어요.*흰색"), + ("진짜?", None, r"다시 봤어요.*흰색"), + ("흰색 맞지?", None, r"^네, .*흰색"), + ("내 손에 뭐 있어?", None, r"왼손에 .*휴대폰"), + ("지금은?", {"hand": "right"}, r"다시 봤어요.*오른손"), + ("이제는?", {"hand": "left"}, r"다시 봤어요.*왼손"), + ("오른손이야", None, r"왼손에 휴대폰이 보여요. 틀릴 수도"), + ("오른손 아니고 왼손이야", None, r"^네, 왼손에"), + ("What about now?", {"hand": "right"}, r"looked again.*right hand"), # mixed: the answer in their language + ("그럼 지금은?", {"hand": "left"}, r"다시 봤어요.*왼손")]) + +world.update(START) +dialogue([("Can you see me?", {"person": False}, r"can't see you"), + ("What about now?", {"person": True}, r"looked again.*yes, i can see you"), + ("Lumi, look at the left side.", None, "llm")]) # a head turn, not a seeing follow-up + +# nothing in the hand any more, or nobody there +world.update(START) +dialogue([("what am I holding?", None, r"left hand"), + ("and now?", {"hand": None}, r"don't see anything I can recognise in your hands"), + ("it's in my right hand", None, r"don't see anything I can recognise in your hands"), + ("what about now?", {"person": False}, r"can't see you")]) + +# no follow-up without a seeing answer just before; an order is never a correction +world.update(START) +dialogue([("what time is it now?", None, "llm"), ("really?", None, "llm")]) +dialogue([("what am I holding?", None, r"left hand"), ("put it in my right hand", None, "llm")]) + +# the conversation model gets a new look too right after a seeing answer +seeing._last["at"] = time.time() +n = len(looks) +assert seeing.facts_for("tell me a joke").startswith(" Your cameras see now") and len(looks) == n + 1 +seeing._last["at"] = 0.0 +assert seeing.facts_for("tell me a joke") == "" + +# colour naming: the hand's skin is not the held thing's colour; near-black has no hue (black trousers read "blue") +SKIN = (110, 140, 200) # BGR of a face / hand +hsv = cv2.cvtColor(np.uint8([[SKIN]]), cv2.COLOR_BGR2HSV)[0, 0] +skin = (float(hsv[0]), float(hsv[1])) +phone_in_hand = np.array([SKIN] * 40 + [(128, 128, 128)] * 60, np.uint8) +assert objects.colour_name(phone_in_hand) != "grey" and scene._thing_colour(phone_in_hand, skin) == "grey" +assert scene._thing_colour(np.array([(0, 120, 255)] * 80 + [SKIN] * 20, np.uint8), skin) == "orange" # an orange thing +assert objects.colour_name(np.array([(48, 36, 30)] * 100, np.uint8)) == "black" # V 48, S 96 +assert objects.colour_name(np.array([(90, 50, 35)] * 100, np.uint8)) == "blue" # jeans, V 90 + +# scene.snapshot(since): a detection made before the question is not "now", one after it is (files faked) +tmp = Path(tempfile.mkdtemp()) +cv2.imwrite(str(tmp / "raw.jpg"), np.zeros((8, 8, 3), np.uint8)) +camview.want = lambda c: None +camview.raw_path = lambda c: tmp / "raw.jpg" +camview.det_path = lambda c: tmp / f"det_{c}.json" +camview.depth = lambda c, max_age=None: None +camview.intrinsics = lambda c: None +scene._transform = lambda c, d: None +scene.SINCE_WAIT_S = 0.3 +asked = time.time() +(tmp / "det_head.json").write_text(json.dumps({"time": asked - 0.5, "people": [], "objects": []})) +assert real_snapshot(("head",), since=asked) == [] +assert len(real_snapshot(("head",))) == 1 # without `since`: anything under FRESH_S +(tmp / "det_head.json").write_text(json.dumps({"time": time.time(), "people": [], "objects": []})) +assert len(real_snapshot(("head",), since=asked)) == 1 + +print("seeing fresh ok") diff --git a/vision/objects.py b/vision/objects.py index 7c67034..40f1e09 100644 --- a/vision/objects.py +++ b/vision/objects.py @@ -31,6 +31,8 @@ MAX_POINTS = 4000 # depth pixels used per object (random subset) MID_BAND = (0.3, 0.7) # width is measured on this height band of the object (the table edge stays out) EDGE_PCT = (1, 99) # percentiles taken as the object's edges (robust to stray depth pixels) MIN_SATURATION = 50 # HSV S below this is white / grey / black +DARK_V = 60 # HSV V below this has no hue the camera can tell (black trousers: V ~48, S ~95, read + # "blue"; blue jeans V ~90, 2026-10-22) EDGE_PX = 4 # a box this close to the bottom of the frame is cut off: height and centre z unknown STALE_S = 1.5 # s; an older detection file means the camera service is not live SURE_SCORE = 0.35 # a box scoring less (person.WEAK_SCORE) is kept only when depth measures this size there: @@ -85,10 +87,10 @@ def colour_name(bgr_pixels): if len(bgr_pixels) == 0: return None hsv = cv2.cvtColor(bgr_pixels.reshape(-1, 1, 3).astype(np.uint8), cv2.COLOR_BGR2HSV).reshape(-1, 3) - vivid = hsv[hsv[:, 1] >= MIN_SATURATION] + vivid = hsv[(hsv[:, 1] >= MIN_SATURATION) & (hsv[:, 2] >= DARK_V)] if len(vivid) < 0.25 * len(hsv): v = np.median(hsv[:, 2]) - return "white" if v > 170 else "black" if v < 60 else "grey" + return "white" if v > 170 else "black" if v < DARK_V else "grey" hist = np.bincount(vivid[:, 0], minlength=181) hist[:8] += hist[170:].sum() # red wraps around 0 hist[170:] = 0 diff --git a/vision/scene.py b/vision/scene.py index 42cc414..eb8353b 100644 --- a/vision/scene.py +++ b/vision/scene.py @@ -35,7 +35,10 @@ ROOT = Path(__file__).resolve().parents[1] # the project folder CAMERAS = ("head", "torso") # the head camera watches people; the torso camera the table and the hands from below FRESH_S = 1.5 # s; older detections are not "now" WAIT_S = 1.2 # s to wait for a fresh detection when the camera service runs slow (idle: 1 per s) +SINCE_WAIT_S = 2.0 # s to wait for a detection made after the question (idle service: 1 per s, woken) DEPTH_AGE_S = 2.0 # s; depth frames are written every 0.5 s +DEPTH_BEFORE_S = 0.5 # s; with `since`, depth written at most this long before the question (a hand that + # moved while asking is measured where it is, else no depth: the colour-only checks) FRONT_M = 3.0 # m; the person "in front" is nearer than this SIDE_DEG = 15.0 # deg; a thing further left / right than this is "on my left / right" SAME_DEG, SAME_M = 8.0, 0.35 # two cameras' detections closer than this (angle, distance) are the same thing @@ -70,6 +73,9 @@ THIGH = (0.1, 0.6) # the trousers colour from this part of hip -> LEG_W = 0.35 # thigh band width as a part of the hip keypoint distance FOOT = (0.05, 0.35) # the shoe: this part of the shin length past the ankle, away from the knee FOOT_W = 0.3 # shoe band width as a part of the shin length +SKIN_R = 6 # px; half size of the face patch at the nose that gives the skin colour +SKIN_HUE, SKIN_SAT = 6, 50 # a held thing's pixels this close to the skin (HSV hue, saturation) are the hand +SKIN_KEEP = 0.3 # ... unless fewer than this part of the box is left (estimates, not yet measured live) WHITE_VS_SKIN = 1.2 # "grey" clothes this much brighter than the face are white in shade or against a # bright window (a white shirt read V 107 by a nose at 70, 2026-10-21) VLM_MODEL = "gemma4:26b" # multimodal; the conversation model, already loaded @@ -94,25 +100,31 @@ def _transform(camera, d): return None -def snapshot(cameras=CAMERAS): - """[{camera, color, depth (mm uint16 or None), people, objects, head_yaw, intr, T}] of the cameras now.""" +def snapshot(cameras=CAMERAS, since=None): + """[{camera, color, depth (mm uint16 or None), people, objects, head_yaw, intr, T}] of the cameras now. + since: a time.time(); only detections made after it count (a question is answered from frames taken after it + was asked, not from the second before, while the hand still moved). A camera without one is left out.""" for c in cameras: camview.want(c) # wakes an idle camera service to full speed frames = [] for c in cameras: - end = time.time() + WAIT_S + end = time.time() + (SINCE_WAIT_S if since else WAIT_S) + + def fresh(d): + return d and time.time() - d["time"] < FRESH_S and (since is None or d["time"] >= since) while True: try: d = json.loads(camview.det_path(c).read_text()) except (FileNotFoundError, ValueError): d = None - if (d and time.time() - d["time"] < FRESH_S) or time.time() > end: + if fresh(d) or time.time() > end: break time.sleep(0.05) color = cv2.imread(str(camview.raw_path(c))) - if d is None or color is None or time.time() - d["time"] > FRESH_S: + if not fresh(d) or color is None: continue - frames.append({"camera": c, "color": color, "depth": camview.depth(c, DEPTH_AGE_S), "people": d["people"], + age = DEPTH_AGE_S if since is None else min(DEPTH_AGE_S, time.time() - since + DEPTH_BEFORE_S) + frames.append({"camera": c, "color": color, "depth": camview.depth(c, age), "people": d["people"], "objects": d["objects"], "head_yaw": d.get("head_yaw") or 0.0, "intr": camview.intrinsics(c), "T": _transform(c, d)}) return frames @@ -269,8 +281,32 @@ def _hand_boxes(f, cx, cy): return [(a + x1, b + y1, c + x1, d + y1, sc, cl) for a, b, c, d, sc, cl in boxes] -def _held(f, kp, side, body_h): - """{position_mm, distance_m, object} for one hand, or None when the wrist is not seen.""" +def _skin(f, kp): + """(hue, saturation) medians of the face around the nose (HSV), or None: the hand holding a thing has this colour.""" + nose = pose.seen(kp, "nose") + if nose is None: + return None + x, y = int(nose[0]), int(nose[1]) + patch = f["color"][max(0, y - SKIN_R):y + SKIN_R, max(0, x - SKIN_R):x + SKIN_R] + if patch.size == 0: + return None + hsv = cv2.cvtColor(patch, cv2.COLOR_BGR2HSV).reshape(-1, 3) + return float(np.median(hsv[:, 0])), float(np.median(hsv[:, 1])) + + +def _thing_colour(px, skin): + """Colour of a held thing's box pixels without the hand's skin (a grey phone in a hand read "orange", 2026-10-22); + the box as it is when the skin leaves too little (an orange thing itself).""" + if skin is None or len(px) == 0: + return objects.colour_name(px) + hsv = cv2.cvtColor(px.reshape(-1, 1, 3).astype(np.uint8), cv2.COLOR_BGR2HSV).reshape(-1, 3).astype(np.float32) + dh = np.abs(hsv[:, 0] - skin[0]) + keep = ~((np.minimum(dh, 180 - dh) <= SKIN_HUE) & (np.abs(hsv[:, 1] - skin[1]) <= SKIN_SAT)) + return objects.colour_name(px[keep] if keep.mean() >= SKIN_KEEP else px) + + +def _held(f, kp, side, body_h, skin=None): + """{position_mm, distance_m, object} for one hand, or None when the wrist is not seen. skin: _skin().""" wr, el = pose.seen(kp, f"{side}_wrist"), pose.seen(kp, f"{side}_elbow") if wr is None: return None @@ -301,6 +337,8 @@ def _held(f, kp, side, body_h): if f["depth"] is not None and (z is None or m["distance_m"] is None or abs(m["distance_m"] - z / 1000) > HAND_DEPTH_M): continue # behind or before the hand: not in it + if skin is not None: + m["colour"] = _thing_colour(f["color"][int(y1):int(y2), int(x1):int(x2)].reshape(-1, 3), skin) o = {"name": name, "colour": m["colour"], "score": round(float(score), 2), "box": (x1, y1, x2, y2), "distance_m": m["distance_m"], "position_mm": m.get("position_mm"), "width_mm": m.get("width_mm")} if best is None or (gap, -score) < best[0]: @@ -433,7 +471,8 @@ def _describe_person(f, p): chest = (chest[0], chest[1] + 0.3 * (np.mean([h[1] for h in hips if h]) - chest[1])) z = _depth_at(f, *chest, r=3 * DEPTH_R) raised, pointing = _gesture(kp) - hands = {s: _held(f, kp, s, body_h) for s in ("left", "right")} + skin = _skin(f, kp) + hands = {s: _held(f, kp, s, body_h, skin) for s in ("left", "right")} out = {"camera": f["camera"], "box": p["box"], "distance_m": None if z is None else round(z / 1000, 2), "bearing_deg": _bearing(f, chest[0]), "position_mm": _mm(_to_base(f, chest[0], chest[1], z)), "facing": _facing(kp), "raised": raised, "pointing": pointing, @@ -499,6 +538,19 @@ def _front(frames): return me +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 + 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 None + + def person_in_front(frames=None): """The person nearest in front (see the module docstring), or None when nobody is within FRONT_M.""" p = _front(snapshot() if frames is None else frames)