Improve held object and colour recognition; add posture answers
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
+238
-46
@@ -1,6 +1,6 @@
|
||||
"""Spoken answers about what Lumi sees, from vision/scene.py: "do you see the red apple?", "how far is it?", "what's on
|
||||
the table?", "how many people are here?", "what am I holding?", "what colour is my shirt?", "is my hand raised?",
|
||||
"am I wearing glasses?" (the slow VLM), English and Korean.
|
||||
"am I wearing glasses?" (the slow VLM), "am I sitting or standing?", English and Korean.
|
||||
|
||||
answer(text, lang, frames=None, slow_line=None) -> spoken sentence, or None when the words are not such a question
|
||||
facts() -> one line of what the cameras see now, for the conversation model; facts_for(text) only when the words
|
||||
@@ -9,18 +9,25 @@ the table?", "how many people are here?", "what am I holding?", "what colour is
|
||||
python assistant/seeing.py "do you see a cup?" # answer from the cameras now
|
||||
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.
|
||||
Only what the detections give is said; anything else is "I can't tell". "What am I holding?" tries harder first: fresh
|
||||
looks until two agree (a weak detector box counts then), the same thing's colour kept steady for STEADY_S, then a close
|
||||
look by gemma4 at the hand picture with the measured facts ("Let me look closely."), and when still unsure what it seems
|
||||
to be and a request for a hint, looked at again with the hint. 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 threading
|
||||
import time
|
||||
from collections import Counter
|
||||
from pathlib import Path
|
||||
|
||||
from assistant import brain
|
||||
from vision import objects, pose, scene
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1] # the project folder
|
||||
NEAR_SAY = 6 # 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
|
||||
@@ -131,7 +138,7 @@ NOT_IN_VIEW = re.compile(r"\b(?:work|works|working|employ\w*|staff|company|compa
|
||||
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|"
|
||||
r"\bwhat(?:'s| is)(?: it| this| that)? (?:in|on) my (?:left |right |other )?hands?\b|\bwhat(?:'s| is) my (?:left |right |other )?hands?\?|\bwhat (?:do )?i have (?:in|on) my (?:left |right |other )?hands?\b|\bam i holding\b|"
|
||||
r"\bwhat(?:'s| is)(?: it| this| that)? (?:in|on|with) my (?:left |right |other )?hands?\b|\bwhat(?:'s| is) my (?:left |right |other )?hands?\?|\bwhat (?:do )?i have (?:in|on) my (?:left |right |other )?hands?\b|\bam i holding\b|"
|
||||
r"\bis there (?:something|anything) in my hand\b|\bwhat is this\b(?=.*\bhand\b)|\bwhat am i hold in\b|\banything (?:in|on) my (?:left |right |other )?hands?\b|"
|
||||
r"\bwhat\b.{0,25}\b(?:i'?m|i am) (?:holding|carrying)\b|\bwhat(?:'ve| have| do) i (?:got|have)\b(?! to)|"
|
||||
r"\bwhat(?:'s| is) this(?: thing)?\W*$|\bwhat i(?:'ve| have) got\b|hold\s*했\S*\W+.*뭐|"
|
||||
@@ -179,6 +186,13 @@ FRIEND = re.compile(r"\b(?:do|can) you (?:still )?see (?:my (?:friend|colleague)
|
||||
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|"
|
||||
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
|
||||
# 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|"
|
||||
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|"
|
||||
@@ -266,6 +280,8 @@ _last = {"thing": None, # the thing seen last: "how far is it?"
|
||||
"asked": None, # (kind, words) of that question: "really?", "and now?" ask it again
|
||||
"hand": None, # the hand the last "what's in my hand" answer was about: "and the other one?"
|
||||
"parts": [], # [(part, word, colour)] said in the clothes answer: "it's white" is about these
|
||||
"held": None, # {name, colour, at} of the held thing said last: its colour stays steady
|
||||
"unsure": 0.0, # time.time() Lumi last asked "could you tell me what it is?"
|
||||
"at": 0.0} # time.time() of the last seeing answer
|
||||
|
||||
|
||||
@@ -360,9 +376,22 @@ def _say(en, ko, lang):
|
||||
return en if lang == "en" else ko
|
||||
|
||||
|
||||
EMPTY_HANDS = ("I don't see anything I can recognise in your hands{}. Small things like a watch, a ring or a pen "
|
||||
"I can't make out.", "{}손에 제가 알아볼 수 있는 건 없어요. 시계, 반지, 펜 같은 작은 건 제 카메라로는 알아보기 어려워요.")
|
||||
EMPTY_HANDS = ("I don't see anything in your hands{}.", "{}손에 든 게 없어 보여요.")
|
||||
NO_CAMERA = ("My cameras aren't giving me a picture right now, so I can't tell.", "지금은 카메라 화면이 없어서 잘 모르겠어요.")
|
||||
LOOKS = 3 # fresh looks at most at the hands before the close look (each 0.1-1 s)
|
||||
SURE = 0.35 # a held thing seen once with this detector score is trusted (person.OBJECT_SCORE);
|
||||
# a weaker one when two looks agree
|
||||
STEADY_S = 30.0 # s; the same kind of thing asked about again this soon keeps its colour unless two
|
||||
# new looks agree on another (a yellow cup read white, then yellow, 2026-10-23)
|
||||
HINT_S = 60.0 # s; after "could you tell me what it is?" this long, the next words are the hint
|
||||
SAVE_DIR = ROOT / "logs" / "seeing" # the frames of each live "what am I holding" (to measure misses later)
|
||||
SAVE_KEEP = 40 # ... the newest this many questions kept
|
||||
HINT = re.compile(r"^\W*(?:(?:no|nope|well|ok(?:ay)?|so|oh|it'?s|it is|this is|that'?s|i'?m holding|i have|they'?re)\W+)+"
|
||||
r"(?:(?:a|an|my|the|some|just)\s+)?(?P<x>[a-z][a-z -]{1,30}?)\W*$|"
|
||||
r"^\W*(?:이거|이건|그거|그건|제가\s*든\s*(?:건|거)|아니\S*)?\s*(?P<k>[가-힣A-Za-z ]{1,15}?)\s*"
|
||||
r"(?:이야|야|예요|이에요|에요|입니다|이요|요)\W*$", re.I) # "it's my wallet", "이거 지갑이야"
|
||||
UNSURE_SAID = re.compile(r"UNSURE|can'?t tell|not sure|모르겠|알 수 없|확실하지", re.I) # the close look gave up
|
||||
TURNED = re.compile(r"\bturn(?:ed)?\b|\bhow about (?:now|this)\b|\bcan you see (?:it|now)\b|돌렸|이제\s*보여|보여\s*\?", re.I)
|
||||
|
||||
|
||||
def _seen_answer(name, colour, frames, lang):
|
||||
@@ -440,43 +469,175 @@ def _it_answer(t, frames, lang):
|
||||
if th['distance_m'] else f"{_j(_ko_name(name), '은', '는')} {_where_ko(th['where'])}에 있어요.", lang)
|
||||
|
||||
|
||||
def _held_answer(frames, lang, side=None):
|
||||
"""What the person holds; side ("left" / "right", the person's own): only what is in that hand."""
|
||||
KO_SIDE = {"left": "왼", "right": "오른"}
|
||||
|
||||
|
||||
def _from(p, side=None):
|
||||
"""The thing in that hand (None: right first, then left) of a person_in_front, with "hand", or None."""
|
||||
for s in ((side,) if side else ("right", "left")):
|
||||
h = p["hands"].get(s)
|
||||
if h and h.get("object"):
|
||||
return {**h["object"], "hand": s}
|
||||
return None
|
||||
|
||||
|
||||
def _vote(got):
|
||||
"""The thing several looks agree on: {name, colour, hand, score, sure, doubt} or None. sure: one look with a
|
||||
detector score >= SURE or two looks; the colour is the one most looks gave, the colour said before for the same
|
||||
kind of thing (STEADY_S) unless two looks now agree on another; doubt: the newest look disagrees with that."""
|
||||
if not got:
|
||||
return None
|
||||
names = Counter(x["name"] for x in got)
|
||||
best = max(names, key=lambda n: (names[n], max(x.get("score", 1.0) for x in got if x["name"] == n)))
|
||||
mine = [x for x in got if x["name"] == best]
|
||||
cols = Counter(x["colour"] for x in mine if x["colour"])
|
||||
colour = max(cols, key=lambda c: (cols[c], max(i for i, x in enumerate(mine) if x["colour"] == c)), default=None)
|
||||
mem = _last["held"]
|
||||
doubt = False
|
||||
if mem and mem["name"] == best and time.time() - mem["at"] < STEADY_S and mem["colour"] and colour != mem["colour"] \
|
||||
and cols[colour] < 2:
|
||||
colour, doubt = mem["colour"], True # one look against the colour said seconds ago: look again
|
||||
score = max(x.get("score", 1.0) for x in mine)
|
||||
return {**mine[-1], "colour": colour, "score": score, "sure": score >= SURE or len(mine) >= 2, "doubt": doubt}
|
||||
|
||||
|
||||
def _held_look(frames, p, side, more):
|
||||
"""Up to LOOKS fresh looks (more(): new frames, None in tests with saved frames) until the looks agree on a thing.
|
||||
(sure thing or None, weak guess or None, the last frames, the person in them)."""
|
||||
got = []
|
||||
for i in range(LOOKS):
|
||||
if i:
|
||||
nxt = more() if more else None
|
||||
q = scene.person_in_front(nxt) if nxt else None
|
||||
if q is None:
|
||||
break
|
||||
frames, p = nxt, q
|
||||
o = _from(p, side)
|
||||
if o:
|
||||
got.append(o)
|
||||
pick = _vote(got)
|
||||
if pick and pick["sure"] and not pick["doubt"]:
|
||||
break
|
||||
pick = _vote(got)
|
||||
if pick and pick["sure"]:
|
||||
return pick, None, frames, p
|
||||
return None, pick, frames, p
|
||||
|
||||
|
||||
def _save(frames):
|
||||
"""The frames of a live question to logs/seeing/ (the newest SAVE_KEEP kept), in the background."""
|
||||
def run():
|
||||
try:
|
||||
SAVE_DIR.mkdir(parents=True, exist_ok=True)
|
||||
scene.save(str(SAVE_DIR / time.strftime("%Y%m%d_%H%M%S")), frames)
|
||||
old = sorted(SAVE_DIR.glob("*.json"))[:-2 * SAVE_KEEP]
|
||||
for j in old:
|
||||
for x in SAVE_DIR.glob(j.stem + ".*"):
|
||||
x.unlink()
|
||||
except Exception as e:
|
||||
print(f"seeing: frames not saved ({e})", flush=True)
|
||||
threading.Thread(target=run, daemon=True).start()
|
||||
|
||||
|
||||
def _held_answer(frames, lang, side=None, more=None, slow_line=None, hint=None):
|
||||
"""What the person holds; side ("left" / "right", the person's own): only what is in that hand. Tries hard
|
||||
before giving up: fresh looks until two agree (_held_look), then gemma4 on the picture of the hand with what the
|
||||
cameras measured; still unsure: what it seems to be and a request for a hint (hint: the words they gave)."""
|
||||
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 side:
|
||||
return _hand_answer(p, side, lang)
|
||||
o = scene.object_in_hand(frames)
|
||||
_last["hand"] = side # "and the other one?" next
|
||||
o, weak, frames, p = _held_look(frames, p, side, more)
|
||||
if more and all("color" in f for f in frames): # live frames (tests fake them)
|
||||
_save(frames)
|
||||
if o:
|
||||
_last["hand"] = o["hand"]
|
||||
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[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 _empty_hands(lang)
|
||||
return _say("I can't see your hands well enough to tell.", "손이 잘 안 보여서 모르겠어요.", lang)
|
||||
return _held_said(o, lang, side, hint)
|
||||
sides = (side,) if side else ("left", "right")
|
||||
seen = {s: p["hands"][s] for s in sides if p["hands"].get(s)}
|
||||
blobs = {s: h["something"]["colour"] for s, h in seen.items() if (h.get("something") or {}).get("colour")}
|
||||
k = KO_SIDE.get(side, "")
|
||||
if not seen and not weak:
|
||||
return _say(f"I can't see your {side + ' hand' if side else 'hands'} well enough to tell.",
|
||||
f"{k}손이 잘 안 보여서 모르겠어요.", lang)
|
||||
if not weak and not blobs and all(h.get("distance_m") is not None for h in seen.values()) and not hint:
|
||||
if side and side in p["raised"]: # depth at the wrist and nothing but the hand there
|
||||
return _say(f"Your {side} hand is up and I don't see anything in it.",
|
||||
f"{k}손을 들고 계신데, 그 손에는 든 게 안 보여요.", lang)
|
||||
_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)
|
||||
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"]) +
|
||||
[f"in their {s} hand something {c}" for s, c in blobs.items()] +
|
||||
([f"about {weak['width_mm'] // 10:.0f} cm wide"] if weak and weak.get("width_mm") else []) +
|
||||
([f"they say it is {_a(hint)}"] if hint else []))
|
||||
if slow_line:
|
||||
slow_line(_say("Let me look closely.", "자세히 볼게요.", lang))
|
||||
said = scene.ask_vlm_hand(evidence, lang, frames, side)
|
||||
print(f"seeing: close look ({evidence}) -> {said}", flush=True)
|
||||
if said and not UNSURE_SAID.search(said):
|
||||
_last["unsure"], _last["held"] = 0.0, None
|
||||
return said
|
||||
if hint:
|
||||
_last["unsure"] = 0.0
|
||||
return _say(f"I still can't make it out well, so I'll take your word: it's {_a(hint)}.",
|
||||
f"아직 잘 안 보이지만, {hint}(이)라고 믿을게요.", lang)
|
||||
_last["unsure"] = time.time()
|
||||
s, c = next(iter(blobs.items()), ((weak or {}).get("hand") or side, None))
|
||||
where = f" in your {s} hand" if s else ""
|
||||
if weak:
|
||||
en = f"It might be {_a(weak['name'], weak['colour'])}{where}, but I'm not sure."
|
||||
ko = f"{KO_SIDE.get(s, '')}손에 든 게 {_ko_name(weak['name'])}인 것 같은데 확실하지 않아요."
|
||||
elif c:
|
||||
en, ko = f"I see something {c}{where}, but I can't tell what it is.", \
|
||||
f"{KO_SIDE.get(s, '')}손에 {COLOUR_KO.get(c, c)} 뭔가가 보이는데, 뭔지는 모르겠어요."
|
||||
else:
|
||||
en, ko = f"I can't make out what's{where or ' in your hand'}.", "손에 든 게 뭔지 잘 안 보여요."
|
||||
return _say(en + " Could you turn it toward me, or tell me what it is?",
|
||||
ko + " 저한테 보이게 돌려 주시거나, 뭔지 말씀해 주시겠어요?", lang)
|
||||
|
||||
|
||||
def _hand_answer(p, side, lang):
|
||||
"""The one hand asked about ("what about my left hand?"), never the other hand's thing: what is in it, that it is
|
||||
up with nothing seen in it, or that nothing known is in it."""
|
||||
_last["hand"] = side
|
||||
h, k = p["hands"].get(side), {"left": "왼", "right": "오른"}[side]
|
||||
o = h and h["object"]
|
||||
if o:
|
||||
def _held_said(o, lang, side=None, hint=None):
|
||||
"""The sentence for a thing seen in a hand (the hand asked about first), remembered so its colour stays steady."""
|
||||
_last["hand"], _last["unsure"] = o["hand"], 0.0
|
||||
_last["held"] = {"name": o["name"], "colour": o["colour"], "at": time.time()}
|
||||
h, k = o["hand"], KO_SIDE[o["hand"]]
|
||||
col_ko = COLOUR_KO[o["colour"]] + " " if o["colour"] in COLOUR_KO else ""
|
||||
named = hint and (_said_thing(hint) or _name(hint.split()[-1]))
|
||||
if named and named != o["name"]:
|
||||
return _say(f"To my camera it looks like {_a(o['name'], o['colour'])}, not {_a(named)}, but I may be wrong.",
|
||||
f"제 카메라에는 {_j(_ko_name(named), '이', '가')} 아니라 {col_ko}{_ko_name(o['name'])}(으)로 보여요. "
|
||||
f"틀릴 수도 있어요.", lang)
|
||||
if hint:
|
||||
return _say(f"Yes, now I see it: {_a(o['name'], o['colour'])} in your {h} hand.",
|
||||
f"네, 이제 보여요. {k}손에 {col_ko}{_j(_ko_name(o['name']), '이', '가')} 있어요.", lang)
|
||||
if side:
|
||||
return _say(f"In your {side} hand I see {_a(o['name'], o['colour'])}.",
|
||||
f"{k}손에 {COLOUR_KO[o['colour']] + ' ' if o['colour'] in COLOUR_KO else ''}"
|
||||
f"{_j(_ko_name(o['name']), '이', '가')} 보여요.", lang)
|
||||
if side in p["raised"]:
|
||||
return _say(f"Your {side} hand is up and I don't see anything in it.",
|
||||
f"{k}손을 들고 계신데, 그 손에는 든 게 안 보여요.", lang)
|
||||
if h is None:
|
||||
return _say(f"I can't see your {side} hand well enough to tell.", f"{k}손이 잘 안 보여서 모르겠어요.", lang)
|
||||
return _say(f"I don't see anything I can recognise in your {side} hand.",
|
||||
f"{k}손에는 제가 알아볼 수 있는 게 안 보여요.", lang)
|
||||
f"{k}손에 {col_ko}{_j(_ko_name(o['name']), '이', '가')} 보여요.", lang)
|
||||
return _say(f"You're holding {_a(o['name'], o['colour'])} in your {h} hand.",
|
||||
f"{k}손에 {col_ko}{_j(_ko_name(o['name']), '을', '를')} 들고 계세요.", lang)
|
||||
|
||||
|
||||
def _steady(o):
|
||||
"""A thing in a hand (object_in_hand) with the colour said for it seconds ago (STEADY_S), for other answers."""
|
||||
mem = _last["held"]
|
||||
if o and mem and mem["name"] == o["name"] and time.time() - mem["at"] < STEADY_S:
|
||||
return {**o, "colour": mem["colour"]}
|
||||
return o
|
||||
|
||||
|
||||
def _hint(t):
|
||||
"""The thing named after "could you tell me what it is?": "it's my wallet", "이거 지갑이야" -> "my wallet" / "지갑",
|
||||
else None."""
|
||||
m = "?" not in t and HINT.match(t.strip())
|
||||
x = m and (m.group("x") or m.group("k") or "").strip()
|
||||
if not x or re.fullmatch(r"(?:it|this|that|right|left|okay|ok|sure|yes|no|here|now|hand|네|아니|맞아|여기|이거|그거)",
|
||||
x, re.I) or _side(t):
|
||||
return None
|
||||
return x
|
||||
|
||||
|
||||
def _asked_hand(t):
|
||||
@@ -530,9 +691,28 @@ def _clothes_answer(p, text, lang):
|
||||
return _say(en, ko, lang)
|
||||
|
||||
|
||||
POSE_SAID = {"standing": ("You're standing", "서 계시고"), "sitting": ("You're sitting", "앉아 계시고"),
|
||||
"crouching": ("You're crouching", "쪼그려 앉아 계시고")}
|
||||
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")
|
||||
if got is None:
|
||||
return _say("I can't see your legs well enough to tell whether you're sitting or standing.",
|
||||
"다리가 잘 안 보여서 앉아 계신지 서 계신지 모르겠어요.", lang)
|
||||
asked = [k for k, rx in POSE_WORD.items() if re.search(rx, t, re.I)]
|
||||
lead = ("Yes, " if asked == [got] else "No, " if len(asked) == 1 else "", "네, " if asked == [got] else
|
||||
"아니요, " if len(asked) == 1 else "")
|
||||
ko = {"standing": "서 계세요.", "sitting": "앉아 계세요.", "crouching": "쪼그려 앉아 계세요."}[got]
|
||||
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 = scene.object_in_hand(frames)
|
||||
en, ko = [f"You're standing{_m(p['distance_m'], 'en')} {p['where']}"], [f"제 {_where_ko(p['where'])}에 서 계시고"]
|
||||
o = _steady(scene.object_in_hand(frames))
|
||||
pose_en, pose_ko = POSE_SAID.get(p.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:
|
||||
en.append("looking at me")
|
||||
ko.append("저를 보고 계시고")
|
||||
@@ -553,7 +733,7 @@ HELD_ASKED = re.compile(r"\bhold|\bhave it\b|\bin my\b|\bit\b|들고|쥐고|잡
|
||||
|
||||
|
||||
KINDS = (("wearing", WEARING), ("holding", HOLDING), ("shirt", SHIRT), ("raised", RAISED), ("where", WHERE_THING), ("hand", WHICH_HAND),
|
||||
("pointing", POINTING), ("doing", DOING), ("friend", FRIEND), ("see_me", SEE_ME), ("how_many", HOW_MANY), ("behind", BEHIND),
|
||||
("pointing", POINTING), ("posture", POSTURE), ("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),
|
||||
("see_more", SEE_MORE), ("what_see", WHAT_SEE))
|
||||
|
||||
@@ -564,9 +744,10 @@ def answer(text, lang="en", frames=None, slow_line=None):
|
||||
t = 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
|
||||
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
|
||||
got = _check(t, lang, frames, asked_at, slow_line, more) # "really?", "and now?", "it's white": a new look
|
||||
if got:
|
||||
_last["at"] = time.time()
|
||||
return got
|
||||
@@ -598,7 +779,7 @@ 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)
|
||||
return _reply(kind, t, frames, lang, slow_line, more)
|
||||
|
||||
|
||||
def _look(frames, since):
|
||||
@@ -678,7 +859,7 @@ def _verdict(c, said, denied, en, ko, verb, lang, before=None):
|
||||
f"제 카메라에는 아직 {_j(ko, '이', '가')} {k}으로 보여요. 조명 때문에 틀릴 수도 있어요.", lang)
|
||||
|
||||
|
||||
def _check(t, lang, frames, since, slow_line):
|
||||
def _check(t, lang, frames, since, slow_line, more=None):
|
||||
"""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."""
|
||||
@@ -691,7 +872,12 @@ def _check(t, lang, frames, since, slow_line):
|
||||
if side: # "what about the left hand?": that hand, from a new look
|
||||
_last["kind"], _last["asked"] = "holding", ("holding", f"what is in my {side} hand?")
|
||||
frames = _look(frames, since)
|
||||
return _held_answer(frames, lang, side) if frames else _say(*NO_CAMERA, lang)
|
||||
return _held_answer(frames, lang, side, more, slow_line) if frames else _say(*NO_CAMERA, lang)
|
||||
hint = _hint(t) if kind == "holding" and time.time() - _last["unsure"] < HINT_S else None
|
||||
if hint or kind == "holding" and _last["unsure"] and TURNED.search(t): # after "could you tell me what it is?"
|
||||
frames = _look(frames, since)
|
||||
_last["kind"] = kind
|
||||
return _held_answer(frames, lang, _asked_hand(asked), more, slow_line, hint) if frames else _say(*NO_CAMERA, lang)
|
||||
said, denied = _colours(t) if short and kind in ("shirt", "holding", "hand") else (None, set())
|
||||
named = _said_thing(t) if short and kind in ("holding", "hand") and not hand else None
|
||||
count = _said_count(t) if short and kind == "how_many" else None
|
||||
@@ -709,7 +895,7 @@ def _check(t, lang, frames, since, slow_line):
|
||||
return _say(f"I count {_n(n)} {'person' if n == 1 else 'people'} in view now, not {count}; someone may be out of "
|
||||
f"my view.", f"제 카메라에는 지금 {n}명이 보여요. 화면 밖에 계신 분이 있을 수도 있어요.", lang)
|
||||
if not (hand or said or denied or named):
|
||||
got = _reply(kind, asked, frames, lang, slow_line)
|
||||
got = _reply(kind, asked, frames, lang, slow_line, more)
|
||||
return got and _say("I looked again. ", "다시 봤어요. ", lang) + got
|
||||
p = scene.person_in_front(frames)
|
||||
if p is None:
|
||||
@@ -761,7 +947,7 @@ def _check(t, lang, frames, since, slow_line):
|
||||
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):
|
||||
def _reply(kind, t, frames, lang, slow_line=None, more=None):
|
||||
"""The answer to a question of this kind (answer() read it) from these frames."""
|
||||
if kind == "behind":
|
||||
return _say("My cameras look forward, so I can't see what's behind me. " + describe(frames, "en"),
|
||||
@@ -801,7 +987,7 @@ def _reply(kind, t, frames, lang, slow_line=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":
|
||||
return _held_answer(frames, lang, _asked_hand(t))
|
||||
return _held_answer(frames, lang, _asked_hand(t), more, slow_line)
|
||||
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)
|
||||
@@ -833,8 +1019,9 @@ def _reply(kind, t, frames, lang, slow_line=None):
|
||||
if kind == "hand": # "which hand?": the one holding something, else one raised
|
||||
up = UP_ASKED.search(t) # "left or right, which one's up?"
|
||||
if not up and (HELD_ASKED.search(t) or scene.object_in_hand(frames) or not p["raised"]):
|
||||
return _held_answer(frames, lang)
|
||||
return _held_answer(frames, lang, None, more, slow_line)
|
||||
kind = "raised"
|
||||
_last["kind"], _last["asked"] = kind, (kind, t) # "and now?" asks about the raised hand again
|
||||
if kind == "raised":
|
||||
if p["raised"]:
|
||||
return _say(f"Yes, your {' and '.join(p['raised'])} hand is up.",
|
||||
@@ -861,6 +1048,8 @@ def _reply(kind, t, frames, lang, slow_line=None):
|
||||
"손으로 가리키시는 건 보이는데, 무엇인지는 모르겠어요.", lang)
|
||||
if kind == "doing":
|
||||
return _doing_answer(p, frames, lang)
|
||||
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))
|
||||
@@ -883,10 +1072,12 @@ ABOUT_VIEW = re.compile(r"\b(?:see|seeing|look(?:ing)? at|camera|cameras|in fron
|
||||
|
||||
|
||||
def warm_up():
|
||||
"""Load the pose and object models now, so the first question is answered in ~0.1 s, not ~1 s."""
|
||||
"""Load the pose and object models now, so the first question is answered in ~0.1 s, not ~1 s; the close look's
|
||||
model in the background."""
|
||||
try:
|
||||
pose.load()
|
||||
scene._box_net()
|
||||
threading.Thread(target=scene.warm_vlm_hand, daemon=True).start() # the close look's model, ~12 s
|
||||
except Exception as e:
|
||||
print(f"seeing: models not loaded ({e})", flush=True)
|
||||
|
||||
@@ -907,8 +1098,9 @@ def facts(frames=None):
|
||||
line = describe(frames, "en")
|
||||
p = scene.person_in_front(frames)
|
||||
if p:
|
||||
o = scene.object_in_hand(frames)
|
||||
o = _steady(scene.object_in_hand(frames))
|
||||
line += f" The person in front is{_m(p['distance_m'], 'en')}" + \
|
||||
(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 "") + "."
|
||||
|
||||
@@ -142,6 +142,12 @@ Every value here is a constant at the top of its file, with a comment on what it
|
||||
| `vision/reid.py` | `FORGET_S` | 600 s | Someone not seen this long is new again: the full greeting |
|
||||
| `assistant/lumi.py` | `RECENT_S` | 150 s | Back within this while the talk was open: Lumi listens on without a word; later, or after a goodbye: "Welcome back! How can I help you?" |
|
||||
| `vision/person.py` | `ZOOM` | 3 torso crops | Parts of the frame looked at a second time, bigger |
|
||||
| `vision/scene.py` | `HAND_CROPS_PX`, `HELD_SCORE` | 320, 640 px; 0.2 | Squares around each hand the detector looks at again; handheld classes count there from this score |
|
||||
| `assistant/seeing.py` | `LOOKS`, `SURE`, `STEADY_S` | 3, 0.35, 30 s | "What am I holding": fresh looks at most; a held box this sure counts from one look (weaker: two looks agree); the same thing keeps its colour this long unless two looks agree on another |
|
||||
| `vision/scene.py` | `COLOUR_CORE`, `WB_V_PCT`, `WB_MAX_S`, `WB_GAIN` | 0.6; 90, 100; 0.8–1.25 | A held thing's colour from this middle part of its box; white balance from the scene's brightest pale pixels, gains limited |
|
||||
| `vision/scene.py` | `PALM`, `BLOB_MM`, `BLOB_SHARE` | 0.6 / 0.35 forearm, 100 mm, 0.25 | Something without a class in a hand: not-skin pixels past the wrist at its depth over this share (estimates) |
|
||||
| `vision/scene.py` | `SIT_THIGH`, `STAND_THIGH`, `CROUCH_THIGH`, `CROUCH_DROP` | 0.45, 0.6, 0.1, 0.8 | Posture: knee below hip / ankle below hip as parts of the torso length (estimates) |
|
||||
| `vision/scene.py` | `VLM_HAND_MODEL`, `VLM_HAND_WIDTH`, `VLM_HAND_TIMEOUT_S` | gemma4:e4b, 320 px, 12 s | The model, picture width and wait for the close look at a hand (26b took 18–33 s per picture, e4b 2–13 s) |
|
||||
| `manipulation/skills.py` | `MIN_SEEN` | 5 of 8 frames | An object must be seen this often at the same place |
|
||||
| `manipulation/skills.py` | `HAND_PROBE_MM`, `HAND_NEAR_MM`, `HAND_FAR_MM` | 30/50/70, 60, 250 mm | In-hand check by depth (`hand_sees`) |
|
||||
|
||||
|
||||
@@ -142,6 +142,52 @@ assert seeing._clothes_answer(p, "what colour are my shoes?", "en") == "Your sho
|
||||
assert seeing._clothes_answer(p, "신발 뭐 신었어?", "ko") == "신발은 흰색으로 보여요."
|
||||
assert seeing._clothes_answer(p, "내가 뭐 입고 있어?", "ko") == "빨간색 상의에 검은색 바지를 입고, 흰색 신발을 신고 계세요."
|
||||
|
||||
# ---------- a held cup's colour under a warm lamp: the box's middle, the light taken out (2026-10-23 live: a yellow cup
|
||||
# read "white", then "yellow"); fingers over the box bottom; the old whole-box reading said orange / red ----------
|
||||
WARM = np.array((0.68, 0.86, 1.0)) # B, G, R of the lamp
|
||||
for want, true in (("yellow", (40, 210, 240)), ("white", (235, 235, 235)), ("blue", (200, 90, 30))):
|
||||
for light in (WARM, np.ones(3)):
|
||||
img = (np.full((720, 1280, 3), 250.0) * light).astype(np.uint8) # a white wall
|
||||
img[560:640, 850:900] = (np.array(true) * light).astype(np.uint8)
|
||||
img[630:660, 840:910] = (np.array((110, 140, 200)) * light).astype(np.uint8) # the fingers
|
||||
depth = np.full((720, 1280), 2500, np.uint16)
|
||||
depth[100:700, 500:900] = 1000
|
||||
frame = {"camera": "torso", "color": img, "depth": depth, "people": [], "head_yaw": 0.0, "intr": intr,
|
||||
"T": np.eye(4), "objects": [{"name": "cup", "score": 0.8, "box": (845, 555, 905, 660)}]}
|
||||
got = scene._held(frame, k, "left", 600)["object"]["colour"]
|
||||
assert got == want, (want, light, got)
|
||||
for name in ("holding_cup_back", "white_shirt_near"): # a neutral room: no change
|
||||
assert all(abs(g - 1) < 0.08 for f in fx(name) for g in scene._gains(f["color"])), name
|
||||
|
||||
# ---------- something in a hand the detector has no class for: not skin, at the hand's depth ----------
|
||||
img = np.full((720, 1280, 3), 200, np.uint8)
|
||||
depth = np.full((720, 1280), 2500, np.uint16)
|
||||
depth[100:700, 500:900] = 1000
|
||||
frame = {"camera": "torso", "color": img, "depth": depth, "people": [], "head_yaw": 0.0, "intr": intr, "T": np.eye(4),
|
||||
"objects": []}
|
||||
img[560:640, 845:905] = (40, 160, 40) # a green thing past the wrist
|
||||
h = scene._held(frame, k, "left", 600)
|
||||
assert h["object"] is None and h["something"]["colour"] == "green", h
|
||||
depth[575:700, 830:920] = 1250 # the body 25 cm behind: empty
|
||||
assert scene._held(frame, k, "left", 600)["something"] == {"colour": None, "share": 0.0}
|
||||
|
||||
# ---------- sitting / standing / crouching from keypoints (torso 300 px) ----------
|
||||
legs = {"standing": dict(left_knee=(680, 860), right_knee=(600, 860), left_ankle=(680, 1100), right_ankle=(600, 1100)),
|
||||
"sitting": dict(left_knee=(690, 640), right_knee=(590, 640), left_ankle=(690, 900), right_ankle=(590, 900)),
|
||||
"crouching": dict(left_knee=(720, 610), right_knee=(560, 610), left_ankle=(690, 800), right_ankle=(590, 800))}
|
||||
for want, kn in legs.items():
|
||||
assert scene._posture(kp(**body, **kn)) == want, want
|
||||
assert scene._posture(kp(**body)) is None # no knees in view
|
||||
for said, posture, lang, want in (("Am I sitting or standing?", "sitting", "en", "You're sitting."),
|
||||
("I am standing or sitting.", "standing", "en", "You're standing."), # 2026-10-23
|
||||
("am I standing?", "sitting", "en", "No, you're sitting."),
|
||||
("am I sitting?", "sitting", "en", "Yes, you're sitting."),
|
||||
("내가 앉아 있어 서 있어?", "crouching", "ko", "쪼그려 앉아 계세요."),
|
||||
("나 서 있어?", "standing", "ko", "네, 서 계세요."),
|
||||
("Am I sitting or standing?", None, "en", "I can't see your legs")):
|
||||
assert next(k for k, rx in seeing.KINDS if rx.search(said)) == "posture", said
|
||||
assert seeing._posture_answer({"posture": posture}, said, lang).startswith(want), (said, want)
|
||||
|
||||
# ---------- words that are not about the cameras ----------
|
||||
f = fx("empty_room")
|
||||
for text in ("how far is Seoul?", "what time is it?", "is there a cafe nearby?", "what are you doing?",
|
||||
|
||||
@@ -59,9 +59,14 @@ def _person(p):
|
||||
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))
|
||||
hands = {s: ({"position_mm": None, "distance_m": 0.8, "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")}
|
||||
for s, h in hands.items(): # the palm check: something without a class shows as a colour
|
||||
raw = p.get(f"{s}_hand")
|
||||
if h is not None:
|
||||
h["something"] = None if h["object"] else {"colour": (raw[1] if isinstance(raw, (list, tuple)) else None) or
|
||||
"grey", "share": 0.5} if raw else {"colour": None, "share": 0.0}
|
||||
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,
|
||||
@@ -111,6 +116,22 @@ scene.pointing_target = lambda frames=None: None
|
||||
scene.ask_vlm = lambda q, lang="en", frames=None: None
|
||||
|
||||
|
||||
def ask_vlm_hand(evidence, lang="en", frames=None, side=None):
|
||||
"""The close look names a thing the detector has no class for (a watch), as gemma4 does on the hand picture."""
|
||||
p = _front(frames)
|
||||
for s in ((side,) if side else ("right", "left")):
|
||||
raw = p and p.get(f"{s}_hand")
|
||||
name = raw and (raw[0] if isinstance(raw, (list, tuple)) else raw)
|
||||
if name and not _thing(name, None):
|
||||
k = {"watch": "시계"}.get(name, name)
|
||||
return f"You're holding a {name} in your {s} hand." if lang == "en" else \
|
||||
f"{seeing.KO_SIDE[s]}손에 {seeing._j(k, '을', '를')} 들고 계세요."
|
||||
return None
|
||||
|
||||
|
||||
scene.ask_vlm_hand = ask_vlm_hand
|
||||
|
||||
|
||||
def lang_of(text):
|
||||
return "ko" if re.search(r"[가-힣]", text) else "en"
|
||||
|
||||
@@ -118,7 +139,7 @@ def lang_of(text):
|
||||
def run(dialogues):
|
||||
ok, bad, asked = 0, [], 0
|
||||
for n, d in enumerate(dialogues):
|
||||
seeing._last.update(thing=None, name=None, kind=None, asked=None, parts=[], at=0.0)
|
||||
seeing._last.update(thing=None, name=None, kind=None, asked=None, parts=[], held=None, unsure=0.0, at=0.0)
|
||||
b = brain.Brain()
|
||||
marks = d.get("markers") or MARKS
|
||||
for i, turn in enumerate(d["turns"]):
|
||||
|
||||
@@ -35,7 +35,7 @@ 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")}
|
||||
hands = {s: {"position_mm": None, "distance_m": 0.8, "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}
|
||||
@@ -59,6 +59,7 @@ 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.ask_vlm_hand = lambda evidence, lang="en", frames=None, side=None: None
|
||||
scene.things = lambda frames=None: []
|
||||
|
||||
|
||||
@@ -75,7 +76,7 @@ def say(text):
|
||||
|
||||
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)
|
||||
seeing._last.update(thing=None, name=None, kind=None, asked=None, parts=[], held=None, unsure=0.0, at=0.0)
|
||||
for words, change, want in turns:
|
||||
if change:
|
||||
world.update(change)
|
||||
@@ -151,7 +152,7 @@ dialogue([("What is my hand?", None, r"black laptop in your right hand"),
|
||||
("and the other hand?", None, r"^In your right hand I see a black laptop"),
|
||||
("and this one?", None, LEFT_UP),
|
||||
("really?", None, r"looked again.*left hand is up"),
|
||||
("What about Inna's left hand?", {"raised": []}, r"^I don't see anything I can recognise in your left hand"),
|
||||
("What about Inna's left hand?", {"raised": []}, r"^I don't see anything in your left hand"),
|
||||
("What's in my right hand?", None, r"^In your right hand I see a black laptop"),
|
||||
("No, it's my left hand.", None, r"laptop in your right hand, but I may be wrong")]) # a claim stays a claim
|
||||
world.update(raised=["left"])
|
||||
@@ -167,8 +168,8 @@ world.update(raised=[])
|
||||
# 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"),
|
||||
("and now?", {"hand": None}, r"don't see anything in your hands"),
|
||||
("it's in my right hand", None, r"don't see anything 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
|
||||
@@ -234,4 +235,64 @@ assert lumi.Lumi.own_echo("The school is over.", share=lumi.ECHO_LIKELY_SHARE)
|
||||
assert not lumi.Lumi.own_echo("What about Busan?", share=lumi.ECHO_LIKELY_SHARE)
|
||||
assert not lumi.Lumi.own_echo("Look it up.", share=lumi.ECHO_LIKELY_SHARE)
|
||||
|
||||
# "what am I holding" tries hard before giving up: fresh looks until two agree, the colour steady across questions,
|
||||
# then the close look (gemma4 on the hand picture), then a request for a hint and a new look after it (2026-10-23 live:
|
||||
# a phone found only sometimes, a laptop "I can't tell" 4-5 times, a yellow cup "white" then "yellow")
|
||||
def person(right=None, something=None):
|
||||
"""A person in front whose right hand holds `right` ((name, colour, score) or None)."""
|
||||
obj = right and {"name": right[0], "colour": right[1], "score": right[2], "position_mm": None, "distance_m": 0.8,
|
||||
"width_mm": None}
|
||||
hand = {"position_mm": None, "distance_m": 0.8, "object": obj, "something": something or {"colour": None, "share": 0}}
|
||||
return {"hands": {"right": hand, "left": {**hand, "object": None, "something": {"colour": None, "share": 0}}},
|
||||
"raised": [], "posture": None}
|
||||
|
||||
|
||||
def held(views, said="what am I holding?", vlm=None, hint=None):
|
||||
"""The answer when the first look sees views[0] and each new look (more()) the next; also the close look's words
|
||||
and what Lumi said before it."""
|
||||
views, spoken, asked_vlm = list(views), [], []
|
||||
scene.person_in_front = lambda frames: frames[0]["p"]
|
||||
scene.ask_vlm_hand = lambda evidence, lang="en", frames=None, side=None: asked_vlm.append(evidence) or vlm
|
||||
more = lambda: [{"p": views.pop(0)}] if views else None
|
||||
got = seeing._held_answer([{"p": views.pop(0)}], "en", None, more, spoken.append, hint)
|
||||
return got, spoken, asked_vlm
|
||||
|
||||
|
||||
seeing._last.update(held=None, unsure=0.0)
|
||||
PHONE = ("cell phone", "black", 0.22) # a weak box: true only when two looks agree
|
||||
got, spoken, _ = held([person(PHONE), person(PHONE)])
|
||||
assert got == "You're holding a black cell phone in your right hand." and not spoken, got
|
||||
got, spoken, ev = held([person(PHONE), person(), person()], vlm="UNSURE")
|
||||
assert spoken == ["Let me look closely."] and "cell phone (score 0.22" in ev[0], (spoken, ev)
|
||||
assert got == "It might be a black cell phone in your right hand, but I'm not sure. Could you turn it toward me, or " \
|
||||
"tell me what it is?", got
|
||||
got, _, _ = held([person(), person(), person()], hint="phone", vlm=None)
|
||||
assert got == "I still can't make it out well, so I'll take your word: it's a phone.", got
|
||||
got, _, _ = held([person(("cell phone", "black", 0.5))], hint="phone")
|
||||
assert got.startswith("Yes, now I see it: a black cell phone"), got
|
||||
LAPTOP = ("laptop", "grey", 0.6)
|
||||
got, spoken, _ = held([person(), person(), person(LAPTOP)]) # found on the third look: no close look
|
||||
assert got == "You're holding a grey laptop in your right hand." and not spoken, got
|
||||
got, spoken, ev = held([person(something={"colour": "green", "share": 0.6})] * 3, vlm="You're holding a green ball.")
|
||||
assert got == "You're holding a green ball." and "something green" in ev[0], (got, ev)
|
||||
got, _, _ = held([person(something={"colour": "green", "share": 0.6})] * 3, vlm=None)
|
||||
assert got.startswith("I see something green in your right hand, but I can't tell what it is. Could you turn"), got
|
||||
got, spoken, _ = held([person()] * 3) # depth at the hands, nothing there
|
||||
assert got == "I don't see anything in your hands." and not spoken, got
|
||||
|
||||
seeing._last.update(held=None) # the colour stays steady ...
|
||||
assert held([person(("cup", "yellow", 0.8))])[0].endswith("a yellow cup in your right hand.")
|
||||
assert held([person(("cup", "white", 0.8)), person(("cup", "yellow", 0.8))])[0].endswith("a yellow cup in your right hand.")
|
||||
assert held([person(("cup", "white", 0.8)), person(("cup", "orange", 0.8)), person(("cup", "yellow", 0.8))])[0] \
|
||||
.endswith("a yellow cup in your right hand.")
|
||||
assert held([person(("cup", "white", 0.8)), person(("cup", "white", 0.8))])[0].endswith("a white cup in your right hand.")
|
||||
seeing._last["held"]["at"] -= seeing.STEADY_S + 1 # ... for STEADY_S, then a new look decides
|
||||
assert held([person(("cup", "yellow", 0.8))])[0].endswith("a yellow cup in your right hand.")
|
||||
# the model is told the same colour
|
||||
assert seeing._steady({"name": "cup", "colour": "white"})["colour"] == "yellow"
|
||||
|
||||
for said, want in (("it's my wallet", "wallet"), ("이거 지갑이야", "지갑"), ("no, it's a phone", "phone"),
|
||||
("it's my right hand", None), ("okay", None), ("제가 서 있나요 앉아 있나요?", None)):
|
||||
assert seeing._hint(said) == want, (said, seeing._hint(said))
|
||||
|
||||
print("seeing fresh ok")
|
||||
|
||||
+4
-3
@@ -181,8 +181,9 @@ def load_net():
|
||||
return CvNet()
|
||||
|
||||
|
||||
def detect_boxes(net, color):
|
||||
"""YOLOv8 boxes: list of (x1, y1, x2, y2, score, COCO class id); class 0 is a person."""
|
||||
def detect_boxes(net, color, object_score=OBJECT_SCORE):
|
||||
"""YOLOv8 boxes: list of (x1, y1, x2, y2, score, COCO class id); class 0 is a person. object_score: the floor for
|
||||
things other than people and cups (scene.py looks at a hand crop with a lower one)."""
|
||||
h, w = color.shape[:2]
|
||||
scale = SIZE / max(h, w)
|
||||
canvas = np.zeros((SIZE, SIZE, 3), np.uint8) # letterbox, keep aspect ratio
|
||||
@@ -191,7 +192,7 @@ def detect_boxes(net, color):
|
||||
# (8400, 84): cx, cy, w, h, 80 class scores
|
||||
cls = out[:, 4:].argmax(axis=1)
|
||||
scores = out[np.arange(len(out)), 4 + cls]
|
||||
floor = np.array([WEAK_SCORE.get(int(c), OBJECT_SCORE) for c in cls])
|
||||
floor = np.array([WEAK_SCORE.get(int(c), object_score) for c in cls])
|
||||
keep = scores > np.where(cls == 0, MIN_SCORE, floor)
|
||||
if not keep.any():
|
||||
return []
|
||||
|
||||
+173
-23
@@ -2,12 +2,15 @@
|
||||
|
||||
sees(name=None, colour=None) -> [{name, colour, distance_m, bearing_deg, where, camera, position_mm, score}]
|
||||
people() -> [{distance_m, bearing_deg, camera}] everyone in view, both cameras merged
|
||||
person_in_front() -> {distance_m, bearing_deg, where, position_mm, camera, facing, gesture, raised, pointing,
|
||||
clothes: {upper, lower, feet}, hands: {"left"|"right": {"position_mm", "object"}}} or None
|
||||
person_in_front() -> {distance_m, bearing_deg, where, position_mm, camera, facing, gesture, raised, pointing, posture,
|
||||
clothes: {upper, lower, feet}, hands: {"left"|"right": {"position_mm", "distance_m", "object",
|
||||
"something" (a thing without a class: {colour, share}), "px"}}} or None
|
||||
person_holds(object=None) -> True / False / None (None: can't tell)
|
||||
object_in_hand() -> {name, colour, hand, position_mm, distance_m, width_mm} or None
|
||||
pointing_target() -> {"position_mm", "distance_m"} or None
|
||||
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)
|
||||
|
||||
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, ...)
|
||||
@@ -56,7 +59,20 @@ HAND_R = 0.5 # hand region radius as a part of the forearm l
|
||||
NO_DEPTH_R = 0.5 # without depth the box centre must be this part of the radius from the hand
|
||||
WRIST_PCT = 20 # depth percentile at the wrist: the nearer part of the patch is the arm, not the room
|
||||
HAND_DEPTH_M = 0.35 # m; an object this much further or nearer than the wrist is not in the hand
|
||||
HAND_CROP_PX = 320 # px; the detector looks again at a square this big around each hand (small things)
|
||||
HAND_CROPS_PX = (320, 640) # px; the detector looks again at squares this big around each hand: small things,
|
||||
# and a laptop or a book held up (a 320 crop cut a laptop in half)
|
||||
HELD_SCORE = 0.2 # in those crops a handheld class counts from this score (the whole frame: 0.35); a
|
||||
# phone held up scored 0.2-0.35 and was missed (2026-10-23). seeing.py trusts a weak
|
||||
# one only when two looks agree, or says it is a guess
|
||||
COLOUR_CORE = 0.6 # a held thing's colour from this middle part of its box (the edges are hand and room)
|
||||
WB_V_PCT, WB_MAX_S = 90, 100 # white balance: the scene's brightest pixels (this V percentile) with HSV S under
|
||||
WB_GAIN = (0.8, 1.25) # this are taken as white; per-channel gain limits (a beige wall is not grey)
|
||||
PALM = (0.6, 0.35) # something in a hand without a class: pixels around wrist + 0.6 x forearm, radius
|
||||
BLOB_MM, BLOB_SHARE = 100, 0.25 # 0.35 x forearm, within this depth of the wrist and not skin, over this share
|
||||
# (estimates, 2026-10-23; not yet measured live)
|
||||
SIT_THIGH, STAND_THIGH = 0.45, 0.6 # posture: knee below hip by under / over this part of the torso length (hip -
|
||||
CROUCH_THIGH, CROUCH_DROP = 0.1, 0.8 # shoulder) is sitting / standing; crouching: hip at knee level and the ankle
|
||||
# under this part of the torso below the hip (estimates from body proportions)
|
||||
HANDHELD = {"bottle", "wine glass", "cup", "fork", "knife", "spoon", "bowl", "banana", "apple", "sandwich", "orange",
|
||||
"broccoli", "carrot", "hot dog", "pizza", "donut", "cake", "cell phone", "remote", "mouse", "book",
|
||||
"scissors", "toothbrush", "hair drier", "sports ball", "frisbee", "umbrella", "handbag", "backpack",
|
||||
@@ -89,6 +105,18 @@ VLM_TIMEOUT_S = 12.0
|
||||
VLM_PROMPT = ("You are the eyes of a service robot. Look at the picture and answer the question in one short spoken "
|
||||
"sentence in {lang}. Say only what is clearly visible. If it is not clearly visible, say that you "
|
||||
"can't tell. Question: {q}")
|
||||
VLM_HAND_MODEL = "gemma4:e4b" # the close look at a hand: gemma4:26b took 18-33 s for each new picture (measured
|
||||
# 2026-10-23 17:30, quiet or busy GPU alike; 1.3 s only for a picture seen before),
|
||||
# e4b 2-13 s once loaded (12.6 s to load; seeing.warm_up loads it). Both name
|
||||
# things wrongly on unclear pictures, so the answer starts "It looks like"
|
||||
VLM_HAND_WIDTH = 320 # px; the hand picture sent
|
||||
VLM_HAND_TIMEOUT_S = 12.0 # s; longer: Lumi says it can't make it out and asks for a hint
|
||||
VLM_HAND_PROMPT = ("You are the eyes of a friendly service robot. The picture shows a person's hand close up; they "
|
||||
"asked what they are holding. What your cameras measured: {evidence}. Answer in {lang} in one short, "
|
||||
"natural spoken sentence to them (\"you're holding ...\"): what the thing is, its colour, and its "
|
||||
"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.")
|
||||
|
||||
_det_lock = threading.RLock()
|
||||
_det = {"net": None}
|
||||
@@ -277,14 +305,53 @@ def _box_net():
|
||||
|
||||
|
||||
def _hand_boxes(f, cx, cy):
|
||||
"""Object boxes (x1, y1, x2, y2, score, cls) found by a second, zoomed look at the square around a hand."""
|
||||
"""Object boxes (x1, y1, x2, y2, score, cls) found by second, zoomed looks at squares around a hand, handheld
|
||||
classes from HELD_SCORE."""
|
||||
img = f["color"]
|
||||
h, w = img.shape[:2]
|
||||
s = HAND_CROP_PX // 2
|
||||
x1, y1 = int(max(0, min(w - 2 * s, cx - s))), int(max(0, min(h - 2 * s, cy - s)))
|
||||
with _det_lock:
|
||||
boxes = person.detect_boxes(_box_net(), img[y1:y1 + 2 * s, x1:x1 + 2 * s])
|
||||
return [(a + x1, b + y1, c + x1, d + y1, sc, cl) for a, b, c, d, sc, cl in boxes]
|
||||
out = []
|
||||
for size in HAND_CROPS_PX:
|
||||
s = min(size, h, w) // 2
|
||||
x1, y1 = int(max(0, min(w - 2 * s, cx - s))), int(max(0, min(h - 2 * s, cy - s)))
|
||||
with _det_lock:
|
||||
boxes = person.detect_boxes(_box_net(), img[y1:y1 + 2 * s, x1:x1 + 2 * s], object_score=HELD_SCORE)
|
||||
out += [(a + x1, b + y1, c + x1, d + y1, sc, cl) for a, b, c, d, sc, cl in boxes]
|
||||
return out
|
||||
|
||||
|
||||
def _gains(img):
|
||||
"""Per-channel (B, G, R) gains that make the scene's bright, pale pixels grey: the light's colour taken out (a warm
|
||||
lamp makes a white cup cream and a cream one yellow). Limited to WB_GAIN."""
|
||||
small = img[::8, ::8].reshape(-1, 3)
|
||||
hsv = cv2.cvtColor(small.reshape(-1, 1, 3), cv2.COLOR_BGR2HSV).reshape(-1, 3)
|
||||
white = small[(hsv[:, 2] >= np.percentile(hsv[:, 2], WB_V_PCT)) & (hsv[:, 1] < WB_MAX_S)]
|
||||
if len(white) < 20:
|
||||
return np.ones(3)
|
||||
m = white.astype(np.float32).mean(axis=0) + 1
|
||||
return np.clip(m.mean() / m, *WB_GAIN)
|
||||
|
||||
|
||||
def _balanced(f, px):
|
||||
"""Pixels with the scene's light taken out (_gains, once per frame)."""
|
||||
if "_wb" not in f:
|
||||
f["_wb"] = _gains(f["color"])
|
||||
return np.clip(px.astype(np.float32) * f["_wb"], 0, 255).astype(np.uint8)
|
||||
|
||||
|
||||
def _core(box, part=COLOUR_CORE):
|
||||
"""The middle part of a box (x1, y1, x2, y2), int px."""
|
||||
x1, y1, x2, y2 = box
|
||||
dx, dy = (x2 - x1) * (1 - part) / 2, (y2 - y1) * (1 - part) / 2
|
||||
return int(x1 + dx), int(y1 + dy), int(max(x1 + dx + 1, x2 - dx)), int(max(y1 + dy + 1, y2 - dy))
|
||||
|
||||
|
||||
def _skin_mask(px, skin):
|
||||
"""True for the pixels (N, 3 BGR) of the skin colour (hue, saturation); all False without a skin reference."""
|
||||
if skin is None or len(px) == 0:
|
||||
return np.zeros(len(px), bool)
|
||||
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])
|
||||
return (np.minimum(dh, 180 - dh) <= SKIN_HUE) & (np.abs(hsv[:, 1] - skin[1]) <= SKIN_SAT)
|
||||
|
||||
|
||||
def _skin(f, kp):
|
||||
@@ -303,16 +370,15 @@ def _skin(f, kp):
|
||||
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:
|
||||
if 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))
|
||||
keep = ~_skin_mask(px, skin)
|
||||
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()."""
|
||||
"""{position_mm, distance_m, object, something, px, camera} 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
|
||||
@@ -343,16 +409,41 @@ def _held(f, kp, side, body_h, skin=None):
|
||||
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)
|
||||
a, b, c, d = _core((x1, y1, x2, y2)) # the middle of the box, the light taken out
|
||||
m["colour"] = _thing_colour(_balanced(f, f["color"][b:d, a:c].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]:
|
||||
best = ((gap, -score), o)
|
||||
hand["object"] = best[1] if best else None
|
||||
hand["px"], hand["camera"] = (float(cx), float(cy), float(r)), f["camera"] # the other camera may fill a hand in
|
||||
hips = [p[1] for p in (pose.seen(kp, "left_hip"), pose.seen(kp, "right_hip")) if p]
|
||||
shown = not hips or wr[1] < min(hips) # a hand held up shows a thing; one hanging by the trousers
|
||||
hand["something"] = None if best or el is None else \
|
||||
_blob(f, wr, el, z, skin) if shown else {"colour": None, "share": 0.0} # has them at its depth (2026-10-21)
|
||||
return hand
|
||||
|
||||
|
||||
def _blob(f, wr, el, z, skin):
|
||||
"""{colour, share}: share of the palm disc that is not skin at the hand's depth, just past the wrist, and the
|
||||
colour of it when over BLOB_SHARE (something the detector has no class for), else colour None (an empty hand).
|
||||
None: no depth to tell."""
|
||||
if f["depth"] is None or z is None:
|
||||
return None
|
||||
fore = np.subtract(wr, el)
|
||||
cx, cy = np.add(wr, PALM[0] * fore)
|
||||
r = max(6, int(PALM[1] * np.hypot(*fore)))
|
||||
h, w = f["depth"].shape
|
||||
yy, xx = np.ogrid[:h, :w]
|
||||
disc = (xx - cx) ** 2 + (yy - cy) ** 2 <= r * r
|
||||
near = disc & (f["depth"] > 0) & (np.abs(f["depth"].astype(np.float32) - z) < BLOB_MM)
|
||||
px = f["color"][near]
|
||||
px = px[~_skin_mask(px, skin)]
|
||||
share = len(px) / max(1, disc.sum())
|
||||
return {"colour": objects.colour_name(_balanced(f, px)) if share >= BLOB_SHARE else None,
|
||||
"share": round(float(share), 2)}
|
||||
|
||||
|
||||
def _named(f, mask, ref_z=None, skin_v=None):
|
||||
"""Colour name of the pixels in mask, or None (too few). Depth near ref_z (default: their own median) keeps the
|
||||
room out; objects.colour_name takes the main hue (a logo or a bit of floor does not move it). skin_v: the face's
|
||||
@@ -461,6 +552,26 @@ def _gesture(kp):
|
||||
return raised, pointing
|
||||
|
||||
|
||||
def _posture(kp):
|
||||
""""standing" / "sitting" / "crouching" from where the knees and ankles are against the torso length in the
|
||||
picture, or None (no hips or knees in view)."""
|
||||
def y(names):
|
||||
pts = [pose.seen(kp, n) for n in names]
|
||||
pts = [p[1] for p in pts if p]
|
||||
return np.mean(pts) if pts else None
|
||||
sh, hip, knee = y(("left_shoulder", "right_shoulder")), y(("left_hip", "right_hip")), y(("left_knee", "right_knee"))
|
||||
ankle = y(("left_ankle", "right_ankle"))
|
||||
if None in (sh, hip, knee) or hip - sh <= 0:
|
||||
return None
|
||||
torso = hip - sh
|
||||
thigh = (knee - hip) / torso # 0.8-0.9 standing; small when the thigh points at us
|
||||
if thigh > STAND_THIGH:
|
||||
return "standing"
|
||||
if thigh < CROUCH_THIGH and ankle is not None and (ankle - hip) / torso < CROUCH_DROP:
|
||||
return "crouching"
|
||||
return "sitting" if thigh < SIT_THIGH else None
|
||||
|
||||
|
||||
def _facing(kp):
|
||||
eyes = [pose.seen(kp, n) for n in ("left_eye", "right_eye")]
|
||||
if all(eyes) and pose.seen(kp, "nose"):
|
||||
@@ -484,7 +595,7 @@ def _describe_person(f, p):
|
||||
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,
|
||||
"facing": _facing(kp), "raised": raised, "pointing": pointing, "posture": _posture(kp),
|
||||
"gesture": "hand_raised" if raised else "pointing" if pointing else None,
|
||||
"clothes": _clothes(f, kp, z),
|
||||
"hands": hands, "seen": int((kp[:, 2] > pose.KP_SEEN).sum()), "_f": f, "_kp": kp}
|
||||
@@ -550,6 +661,7 @@ def _front(frames):
|
||||
me["clothes"][k] = me["clothes"][k] or other["clothes"][k]
|
||||
if me["facing"] is None:
|
||||
me["facing"] = other["facing"]
|
||||
me["posture"] = me["posture"] or other["posture"] # the torso camera sees the legs the head camera can't
|
||||
return me
|
||||
|
||||
|
||||
@@ -582,7 +694,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"]}
|
||||
"distance_m": o["distance_m"], "width_mm": o["width_mm"], "score": o["score"]}
|
||||
return None
|
||||
|
||||
|
||||
@@ -644,21 +756,59 @@ def ask_vlm(question, lang="en", frames=None):
|
||||
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"]
|
||||
img = cv2.resize(img, (VLM_WIDTH, max(1, int(img.shape[0] * VLM_WIDTH / img.shape[1]))))
|
||||
return _vlm(img, VLM_PROMPT.format(lang="Korean" if lang == "ko" else "English", q=question))
|
||||
|
||||
|
||||
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."""
|
||||
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": VLM_MODEL, "stream": False, "think": False, "keep_alive": -1,
|
||||
body = {"model": model, "stream": False, "think": False, "keep_alive": -1,
|
||||
"options": {"temperature": 0, "num_predict": 60},
|
||||
"messages": [{"role": "user", "images": [b64],
|
||||
"content": VLM_PROMPT.format(lang="Korean" if lang == "ko" else "English", q=question)}]}
|
||||
"messages": [{"role": "user", "images": [b64], "content": content}]}
|
||||
try:
|
||||
req = urllib.request.Request(VLM_URL, json.dumps(body).encode(), {"Content-Type": "application/json"})
|
||||
with urllib.request.urlopen(req, timeout=VLM_TIMEOUT_S) as r:
|
||||
with urllib.request.urlopen(req, timeout=timeout) as r:
|
||||
return json.loads(r.read())["message"]["content"].strip() or None
|
||||
except Exception as e:
|
||||
print(f"scene: VLM gave no answer ({e})", flush=True)
|
||||
return None
|
||||
|
||||
|
||||
def hand_crop(frames=None, side=None):
|
||||
"""The picture around the hand(s) of the person in front (a square of 5 hand radii, at least 320 px), or None."""
|
||||
frames = snapshot() if frames is None else frames
|
||||
p = _front(frames)
|
||||
if p is None:
|
||||
return None
|
||||
hands = [h for s, h in p["hands"].items() if h and h.get("px") and side in (None, s)]
|
||||
if not hands:
|
||||
return None
|
||||
hands = [h for h in hands if h["camera"] == hands[0]["camera"]]
|
||||
img = next(f["color"] for f in frames if f["camera"] == hands[0]["camera"])
|
||||
xs, ys = [h["px"][0] for h in hands], [h["px"][1] for h in hands]
|
||||
half = max(160, 2.5 * max(h["px"][2] for h in hands), (max(xs) - min(xs)) / 2 + 160, (max(ys) - min(ys)) / 2 + 160)
|
||||
cx, cy = (max(xs) + min(xs)) / 2, (max(ys) + min(ys)) / 2
|
||||
x1, y1 = int(max(0, cx - half)), int(max(0, cy - half))
|
||||
crop = img[y1:int(cy + half), x1:int(cx + half)]
|
||||
return crop if crop.size else None
|
||||
|
||||
|
||||
def ask_vlm_hand(evidence, lang="en", frames=None, side=None):
|
||||
"""One spoken sentence on what the person in front holds, from gemma4 with the picture around their hand(s) and
|
||||
what the cameras measured (evidence: a line of facts), or "UNSURE" / None (can't tell, timeout). Slow: 1-30 s."""
|
||||
img = hand_crop(frames, side)
|
||||
if img is None:
|
||||
return None
|
||||
return _vlm(img, VLM_HAND_PROMPT.format(lang="Korean" if lang == "ko" else "English", evidence=evidence),
|
||||
width=VLM_HAND_WIDTH, timeout=VLM_HAND_TIMEOUT_S, model=VLM_HAND_MODEL)
|
||||
|
||||
|
||||
def warm_vlm_hand():
|
||||
"""Loads the close-look model (VLM_HAND_MODEL) with a tiny picture, so the first close look is not 12 s slower."""
|
||||
_vlm(np.zeros((32, 32, 3), np.uint8), "Say OK.", width=32, timeout=60, model=VLM_HAND_MODEL)
|
||||
|
||||
|
||||
def _print(frames):
|
||||
t = time.time()
|
||||
p = person_in_front(frames)
|
||||
|
||||
Reference in New Issue
Block a user