Follow me: steady 10 Hz control with prediction between sightings, one kept-open base connection, head tracks on its own thread, the followed person kept by position and clothes; Lumi: no fate error, cut-off sentences joined, no promise without its action, song bank only on song words

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-22 15:23:57 +09:00
co-authored by Claude Opus 5.5
parent 08e748e5ed
commit 4ab14b3af3
12 changed files with 450 additions and 125 deletions
+11 -1
View File
@@ -1398,13 +1398,23 @@ PROMISE = { # Lumi's own sentence saying it does this now ("Okay! I'll sing a
"sing": re.compile(r"\b(?:i'll|i will|let me|i'm going to) sing\b|\bhere(?:'s| is| comes| goes) (?:a |my |one |the )?song\b|" "sing": re.compile(r"\b(?:i'll|i will|let me|i'm going to) sing\b|\bhere(?:'s| is| comes| goes) (?:a |my |one |the )?song\b|"
r"(?:불러|들려)\s*(?:드릴게요|드리겠습니다|줄게|볼게요)|부를게요", re.I), r"(?:불러|들려)\s*(?:드릴게요|드리겠습니다|줄게|볼게요)|부를게요", re.I),
"wave": re.compile(r"\b(?:i'll|i will|let me) wave\b|흔들어\s*(?:드릴게요|볼게요|줄게)|흔들게요", re.I), "wave": re.compile(r"\b(?:i'll|i will|let me) wave\b|흔들어\s*(?:드릴게요|볼게요|줄게)|흔들게요", re.I),
# any other motion: never done on the reply alone (the action line said none), lumi.answer() asks instead
"motion": re.compile(r"\b(?:i'll|i will|let me|i'm going to|i am going to)\s+(?:now\s+)?(?:follow|come|go(?! ahead)|drive|"
r"head (?:to|over|back)|move|turn (?:around|left|right|to)|look (?:at|left|right|down|around|behind)|"
r"pick|grab|bring|fetch|lift|raise|lower|reach out)\b|"
r"\b(?:i'm|i am) (?:coming|following|on my way)\b|\bhere i come\b|"
r"따라\s*(?:갈게요|가\s*볼게요|갈게|가겠습니다)|(?<![가-힣])(?:갈게요|가겠습니다|올게요|갈게)|가져다\s*드릴게요|"
r"가져올게요|집어\s*(?:드릴게요|볼게요)|집을게요|돌게요|돌아\s*(?:볼게요|갈게요)|쳐다\s*볼게요|"
r"움직일게요|올릴게요|내릴게요|건네\s*드릴게요|내려\s*놓을게요", re.I),
} }
NOT_NOW = re.compile(r"\b(?:if|when|later|after|once|next time)\b|나중에|끝나면|으면|다면", re.I) # "... if you'd like" NOT_NOW = re.compile(r"\b(?:if|when|later|after|once|next time)\b|나중에|끝나면|으면|다면", re.I) # "... if you'd like"
def promised(sentence): def promised(sentence):
"""'sing' / 'wave' when Lumi's sentence says it does that now, else None: lumi.answer() then does it although the """'sing' / 'wave' when Lumi's sentence says it does that now, else None: lumi.answer() then does it although the
model's action line was none ("Start with one." -> "Okay! I'll sing a song for you." and silence, 2026-10-22).""" model's action line was none ("Start with one." -> "Okay! I'll sing a song for you." and silence, 2026-10-22).
'motion' for any other move it says it makes ("Yeah." -> "Okay, I'll follow you!" and no follow, 2026-10-22):
not done on a guess, Lumi asks what to do."""
s = sentence or "" s = sentence or ""
return None if NOT_NOW.search(s) else next((a for a, r in PROMISE.items() if r.search(s)), None) return None if NOT_NOW.search(s) else next((a for a, r in PROMISE.items() if r.search(s)), None)
LOOK_MORE = re.compile(r"^\W*(?:and|now|then|and now)?\s*(up|down|left|right)\W*$|" LOOK_MORE = re.compile(r"^\W*(?:and|now|then|and now)?\s*(up|down|left|right)\W*$|"
+21 -8
View File
@@ -107,7 +107,9 @@ LOST_S = 2.0 # s not seen -> the person is gone (detection
PROMPT_S = 12.0 # s of silence before "How can I help you?" PROMPT_S = 12.0 # s of silence before "How can I help you?"
MAX_PROMPTS = 2 MAX_PROMPTS = 2
TOO_CLOSE = 0.45 # m, a running wave is stopped TOO_CLOSE = 0.45 # m, a running wave is stopped
MATCH_DEG = 12.0 # a detection belongs to the track with the closest angle within this MATCH_DEG = 12.0 # a detection belongs to the track with the closest angle within this ...
MATCH_DEG_PER_M = 10.0 # ... where each m of distance difference counts as this many deg: two people at
# about the same angle (one passing the followed person) keep their own tracks (estimate)
OCCLUSION_DROP = 0.3 # m; while the arm moves, a sudden drop in distance is the arm in front of OCCLUSION_DROP = 0.3 # m; while the arm moves, a sudden drop in distance is the arm in front of
# the person, not the person moving: ignore it # the person, not the person moving: ignore it
CLOSE_BOX = 0.85 # a person is really closer than TOO_CLOSE only if the box is this tall (frame part) CLOSE_BOX = 0.85 # a person is really closer than TOO_CLOSE only if the box is this tall (frame part)
@@ -450,7 +452,8 @@ class Vision(threading.Thread):
with self.lock: with self.lock:
free = list(self.tracks) free = list(self.tracks)
for p in sorted(people, key=lambda p: p["distance_m"]): for p in sorted(people, key=lambda p: p["distance_m"]):
best = min(free, default=None, key=lambda t: abs(t.angle - p["angle_deg"])) best = min(free, default=None, key=lambda t: abs(t.angle - p["angle_deg"])
+ MATCH_DEG_PER_M * abs(t.distance - p["distance_m"]))
if best and abs(best.angle - p["angle_deg"]) < MATCH_DEG: if best and abs(best.angle - p["angle_deg"]) < MATCH_DEG:
best.update(p, now, self.arm_watch, self.near_max) best.update(p, now, self.arm_watch, self.near_max)
free.remove(best) free.remove(best)
@@ -541,15 +544,16 @@ class Vision(threading.Thread):
return min(here, key=lambda t: t.distance, default=None) return min(here, key=lambda t: t.distance, default=None)
def follow_view(self, track): def follow_view(self, track):
"""(distance m, angle deg, age s) of the person being followed (tasks/follow.py), None once the track is """(distance m, angle deg, age s, clothes signature or None) of the person being followed (tasks/follow.py),
gone. The distance is the nearer of the median and the newest reading: the median lags when they stop.""" None once the track is gone. The distance is the nearer of the median and the newest reading: the median lags
when they stop."""
with self.lock: with self.lock:
if track not in self.tracks: if track not in self.tracks:
return None return None
return min(track.distance, track.history[-1]), track.angle, time.time() - track.last_seen return min(track.distance, track.history[-1]), track.angle, time.time() - track.last_seen, track.look
def follow_views(self): def follow_views(self):
"""[(see, distance m, angle deg, age s)] of everyone in view: tasks/follow.py re-locks onto one of them.""" """[(see, distance m, angle deg, age s, look)] of everyone in view: tasks/follow.py re-locks onto one of them."""
with self.lock: with self.lock:
tracks = list(self.tracks) tracks = list(self.tracks)
return [(lambda t=t: self.follow_view(t),) + v for t in tracks if (v := self.follow_view(t))] return [(lambda t=t: self.follow_view(t),) + v for t in tracks if (v := self.follow_view(t))]
@@ -2302,6 +2306,7 @@ class Lumi:
return return
# fate "close" ("okay", "thanks", "됐어요"): the LLM below reads it with the talk before (its action end ends # fate "close" ("okay", "thanks", "됐어요"): the LLM below reads it with the talk before (its action end ends
# the talk); when the talk goes on, silence ends it (closing_pending, set after the reply) # the talk); when the talk goes on, silence ends it (closing_pending, set after the reply)
fate = talk_fate(text)
if kind == "sing": # "sing a song", "노래 불러 줘", after a song "another one" if kind == "sing": # "sing a song", "노래 불러 줘", after a song "another one"
self.sing_song(text) self.sing_song(text)
return return
@@ -2388,6 +2393,14 @@ class Lumi:
self.sing_song(text) self.sing_song(text)
return return
self.act("wave", "") self.act("wave", "")
if promise == "motion": # "Okay, I'll follow you!" under the action none: ask
gen.close()
log(f" the reply promises a move the action line did not ({first[:60]!r}): asked")
say = "Sorry, what would you like me to do?" if self.lang == "en" else "죄송해요, 무엇을 해 드릴까요?"
self.brain.history.append((text, f"ACTION: none -\n{say}"))
mouth.say(say)
self.keep_listening()
return
if head_["action"] in ("none", "sing") and not repeating and look_up_unsure(about, first, text): if head_["action"] in ("none", "sing") and not repeating and look_up_unsure(about, first, text):
gen.close() # the model does not know: look it up instead gen.close() # the model does not know: look it up instead
log(f" not sure ({first[:60]!r}) - looking it up") log(f" not sure ({first[:60]!r}) - looking it up")
@@ -2636,7 +2649,7 @@ class Lumi:
if self.current and not self.vision.present(self.current): if self.current and not self.vision.present(self.current):
log(f"person #{self.current.id} left - stop talking") log(f"person #{self.current.id} left - stop talking")
self.current = self.vision.nearest_greeted() # someone else still here? self.current = None if following else self.vision.nearest_greeted() # someone else still here?
if self.current: if self.current:
self.turn_head(HEAD_SIGN * self.current.angle) self.turn_head(HEAD_SIGN * self.current.angle)
else: else:
@@ -2678,7 +2691,7 @@ class Lumi:
if self.talk_turn(): if self.talk_turn():
self.last_activity, self.prompts = time.time(), 0 self.last_activity, self.prompts = time.time(), 0
elif (not self.interrupted() and time.time() - self.last_activity > PROMPT_S and self.prompts < MAX_PROMPTS): elif (not following and not self.interrupted() and time.time() - self.last_activity > PROMPT_S and self.prompts < MAX_PROMPTS):
log(f"silent for {PROMPT_S:.0f} s - prompt") log(f"silent for {PROMPT_S:.0f} s - prompt")
mouth.say(PROMPT[self.lang], abort=self.interrupted) mouth.say(PROMPT[self.lang], abort=self.interrupted)
self.last_activity, self.prompts = time.time(), self.prompts + 1 self.last_activity, self.prompts = time.time(), self.prompts + 1
+3
View File
@@ -358,6 +358,9 @@ LIST = [
] ]
NO = [ NO = [
# cut-off starts (whisper heard only the beginning): never a song
"let's", "let's go", "can you", "could you", "please", "can you please", "lumi, can you", "wait", "hmm", "so",
"루미야 저기", "저기요", "루미야", "혹시", "그럼", "잠깐만", "있잖아",
# liking music, favourites # liking music, favourites
"do you like singing?", "do you like singing?",
"do you like music?", "do you like music?",
+20 -4
View File
@@ -50,12 +50,14 @@ def ensure_stt_server():
raise RuntimeError("whisper-server did not start, see whisper_server.log") raise RuntimeError("whisper-server did not start, see whisper_server.log")
def record(wait_s=8.0, on_start=None, abort=None): def record(wait_s=8.0, on_start=None, abort=None, since=None):
"""Wait up to wait_s for speech to start, then until it ends. Returns a mic.Utterance or None. """Wait up to wait_s for speech to start, then until it ends. Returns a mic.Utterance or None.
abort: optional function checked every 30 ms; when it returns True, stop and return None.""" abort: optional function checked every 30 ms; when it returns True, stop and return None.
since: take speech that ended after this time, also one already heard (the rest of a sentence)."""
m = mic.get() m = mic.get()
m.clear() # only speech that starts from now on if since is None:
t0, started = time.time(), False m.clear() # only speech that starts from now on
t0, started = since or time.time(), False
try: try:
while True: while True:
if abort and abort(): if abort and abort():
@@ -121,6 +123,12 @@ NOT_SAID = re.compile(r"^\W*$|^\s*-|자막|시청해\s*주셔서|thanks? (?:you
# whisper's subtitle habits on music: no word at all, a dialogue dash ("-끝-", "- 네."), # whisper's subtitle habits on music: no word at all, a dialogue dash ("-끝-", "- 네."),
# a caption credit ("자막 제공 및 광고를 포함하고 있습니다.") # a caption credit ("자막 제공 및 광고를 포함하고 있습니다.")
_vad = {} _vad = {}
CUT_OFF = re.compile(r"(?:\b(?:let'?s|can you|could you|would you|will you|can i|and|but|or|the|a|an|to|of|with|"
r"my|your|i want|i'd like|i need)|(?<![가-힣])(?:저기|그리고|근데|혹시|그래서|그러니까|있잖아))\W*$", re.I)
# a sentence cut off by a pause longer than mic.END_SILENCE ("Let's" of "Let's ...
# follow me", 2026-10-22 14:36; today's clips: the longest pause inside an utterance
# 0.39 s at the 90th percentile, 0.51 s at most, so one cut in 140 turns)
MERGE_WAIT_S = 1.5 # s waited for the rest of a cut-off sentence; it is heard with the first part
BEAM_SIZE = 0 # whisper beam search width (0: the server's greedy decoding) BEAM_SIZE = 0 # whisper beam search width (0: the server's greedy decoding)
HEARD_DIR = ROOT / "logs" / "heard" # the last HEARD_KEEP utterances as wav, to check what Lumi really heard HEARD_DIR = ROOT / "logs" / "heard" # the last HEARD_KEEP utterances as wav, to check what Lumi really heard
@@ -288,6 +296,14 @@ def listen(wait_s=8.0, on_start=None, abort=None, full=False):
if u is None or u.seconds < 0.4: if u is None or u.seconds < 0.4:
return (None, u) if full else None return (None, u) if full else None
text = transcribe(u.mono) or None text = transcribe(u.mono) or None
if text and CUT_OFF.search(text): # "Let's" ... "follow me": the rest after a pause, heard as one
rest = record(MERGE_WAIT_S, abort=abort, since=u.t_end)
if rest is not None and rest.seconds >= 0.3:
import numpy as np
joined = np.concatenate([u.mono, np.zeros(int(0.3 * RATE), np.int16), rest.mono])
text2 = transcribe(joined)
if text2:
text, u.mono, u.t_end = text2, joined, rest.t_end
return (text, u) if full else text return (text, u) if full else text
+8 -3
View File
@@ -49,6 +49,9 @@ LATE_S = 0.4 # s; a move this late is skipped (the previous o
RETURN_WAIT_S = 3.0 # s a new song waits for the head to get back from the last one RETURN_WAIT_S = 3.0 # s a new song waits for the head to get back from the last one
BANK_SIM = 0.80 # song bank (assistant/song_bank.py): the closest wording at least this similar ... BANK_SIM = 0.80 # song bank (assistant/song_bank.py): the closest wording at least this similar ...
BANK_MARGIN = 0.05 # ... and this much closer than the closest wording of another kind BANK_MARGIN = 0.05 # ... and this much closer than the closest wording of another kind
BANK_MIN_WORDS = 3 # the bank reads only words with a song or music word in them and at least this many
# words ("Let's", cut off from "Let's follow me", sang once, 2026-10-22)
SONG_WORD = re.compile(r"\bsing|\bsong|\bmusic|\btunes?\b|\bplaylist|k-?pop|노래|노레|노랠|음악|곡|불러|부르|틀어|들려|케이팝", re.I)
SING = re.compile(r"\bsing\b|\bsay (?:a |some )?songs?\b|" # whisper writes "let's say song" SING = re.compile(r"\bsing\b|\bsay (?:a |some )?songs?\b|" # whisper writes "let's say song"
r"\b(?:play|put on|turn on|start)(?: me| us)? (?:a |some |any |another |the |your )?(?:songs?|music|tunes?)\b|" r"\b(?:play|put on|turn on|start)(?: me| us)? (?:a |some |any |another |the |your )?(?:songs?|music|tunes?)\b|"
@@ -144,13 +147,15 @@ _bank = None
def bank_read(text, last=""): def bank_read(text, last=""):
"""'sing' / 'list' when these words mean the same as the bank's wordings of that kind (bge-m3 through """'sing' / 'list' when these words mean the same as the bank's wordings of that kind (bge-m3 through
assistant/knowledge.embed, ~20 ms), else None (the LLM decides; also when the closest are the bank's assistant/knowledge.embed, ~20 ms), else None (the LLM decides; also when the closest are the bank's
near misses, and for a 'sing' with any word that might be a title: "jingle bells please"). Negation, a condition or a later time, the near misses, and for a 'sing' with any word that might be a title: "jingle bells please"). Only words with a song
or music word and BANK_MIN_WORDS words are read: a cut-off start ("Let's", "can you", "루미야 저기") never sings. Negation, a condition or a later time, the
person singing, a question about liking music or "is / does ...?", and any words with a turn before them (the person singing, a question about liking music or "is / does ...?", and any words with a turn before them (the
talk decides what "yes" means) are never read here.""" talk decides what "yes" means) are never read here."""
global _bank global _bank
t = text or "" t = text or ""
if NOT_REQUEST.search(t) or NOT_ASKED.search(t) or re.match(r"\W*(?:is|are|was|were|does|did|has|have)\b", t, re.I) \ if not SONG_WORD.search(t) or len(re.findall(r"\w+", t)) < BANK_MIN_WORDS or NOT_REQUEST.search(t) or \
or re.search(r"\b(?:like|love|enjoy|favou?rite)\b|좋아|싫어", t, re.I) and re.search(r"\?|까요?\W*$|니\W*$", t) or last: NOT_ASKED.search(t) or re.match(r"\W*(?:is|are|was|were|does|did|has|have)\b", t, re.I) or \
re.search(r"\b(?:like|love|enjoy|favou?rite)\b|좋아|싫어", t, re.I) and re.search(r"\?|까요?\W*$|니\W*$", t) or last:
return None return None
from assistant import knowledge, song_bank from assistant import knowledge, song_bank
try: try:
+42 -15
View File
@@ -7,6 +7,7 @@
import json import json
import socket import socket
import sys import sys
import threading
import time import time
import uuid import uuid
@@ -14,27 +15,53 @@ AGV = ("192.168.10.10", 31001)
DOCK_FALLBACK = "충전위치로" # dock marker name on the old map; on any map the type-11 marker is used DOCK_FALLBACK = "충전위치로" # dock marker name on the old map; on any map the type-11 marker is used
MARKERS_FRESH_S = 5.0 # known_markers() reads the list again after this long: a new map is seen within it MARKERS_FRESH_S = 5.0 # known_markers() reads the list again after this long: a new map is seen within it
_known = {"t": 0.0, "names": []} _known = {"t": 0.0, "names": []}
# One connection kept open per process: the base answers the first command on a new connection only after ~100 ms
# (often 200-300), on an open one in 1-2 ms (robot_status) / 5-15 ms (distance_probe), measured 2026-10-22; an idle
# connection still answered after 90 s.
_conn = {"sock": None, "buf": ""}
_conn_lock = threading.Lock()
def _ask(command, tag, timeout):
s = _conn["sock"]
s.settimeout(timeout)
s.sendall(command.encode())
dec = json.JSONDecoder()
while True:
buf = _conn["buf"]
while buf.strip(): # replies to earlier timed-out commands are skipped by uuid
try:
msg, end = dec.raw_decode(buf.lstrip())
except json.JSONDecodeError:
break
buf = _conn["buf"] = buf.lstrip()[end:]
if msg.get("uuid") == tag:
return msg
chunk = s.recv(65536)
if not chunk: # the base closed the connection: never loop forever
raise ConnectionError(f"AGV closed the connection ({command.split('?')[0]})")
_conn["buf"] += chunk.decode()
def request(command, timeout=3.0): def request(command, timeout=3.0):
tag = uuid.uuid4().hex tag = uuid.uuid4().hex
command += ("&" if "?" in command else "?") + f"uuid={tag}" command += ("&" if "?" in command else "?") + f"uuid={tag}"
buf, dec = "", json.JSONDecoder() with _conn_lock:
with socket.create_connection(AGV, timeout=timeout) as s: for again in (True, False):
s.sendall(command.encode()) reused = _conn["sock"] is not None
while True: try:
chunk = s.recv(65536) if not reused:
if not chunk: # the base closed the connection: never loop forever _conn["sock"] = socket.create_connection(AGV, timeout=timeout)
raise ConnectionError(f"AGV closed the connection ({command.split('?')[0]})") _conn["sock"].setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
buf += chunk.decode() return _ask(command, tag, timeout)
while buf.strip(): except OSError as e:
try: try:
msg, end = dec.raw_decode(buf.lstrip()) _conn["sock"].close()
except json.JSONDecodeError: except (OSError, AttributeError):
break pass
buf = buf.lstrip()[end:] _conn.update(sock=None, buf="")
if msg.get("uuid") == tag: if not (again and reused) or isinstance(e, TimeoutError): # an old connection died: once more
return msg raise
def status(): def status():
+178 -73
View File
@@ -1,11 +1,16 @@
"""Follow a person with the base: "follow me" ... "stop" (lumi.py follow_me). """Follow a person with the base: "follow me" ... "stop" (lumi.py follow_me).
The person is a track of the assistant's Vision; `see()` gives (distance m, angle deg + left, age s) or None once the The person is a track of the assistant's Vision: `see()` gives (distance m, angle deg + left, age s, clothes signature)
track is gone, `people()` [(see, distance, angle, age)] of everyone in view: a track lost is swapped for a fresh one or None once the track is gone, `people()` [(see, distance, angle, age, look)] of everyone in view. Every sighting is
where the person was last (re-lock). The head turns toward the person (only this task moves the body meanwhile: put on the map (base pose + distance, angle) with a smoothed walking velocity, so between sightings the base drives
head.owners), the base turns after it, so they stay in view when they walk to the side or behind. The base is driven with joy_control (one command lasts 0.5 s: a stuck loop stops the base by itself), toward where the person is now, not where they were seen (no stop-and-go when frames are missed). A sighting far from
the arm in look and the waist at the front as for every fetch drive. Every command is checked first: where the base that place is someone else (a passer-by who took the track over); a lost track is swapped for a fresh one near that
and the arm would be BRAKE_S later must be clear (lidar + map, agv.clearance). place whose clothes are not clearly different (re-lock). The head turns toward the person in its own thread (only
this task moves the body meanwhile: head.owners), the base turns after it, so they stay in view when they walk to the
side or behind. The base is driven with joy_control every TICK_S (one command lasts 0.5 s: a stuck loop stops the base
by itself), the arm in look and the waist at the front as for every fetch drive. Every command is checked first: where
the base and the arm would be BRAKE_S later must be clear (lidar + map, agv.clearance); when not, the base stands, and
after BLOCKED_END_S it gives up.
stop() from any thread: the event is set and the base is sent 0 at once stop() from any thread: the event is set and the base is sent 0 at once
""" """
@@ -19,27 +24,39 @@ import numpy as np
from robot import agv, head, motion from robot import agv, head, motion
from tasks import fetch from tasks import fetch
from vision import reid
FOLLOW_GAP_M = 1.0 # m; keep this far from the person (camera distance); nearer: stand still FOLLOW_GAP_M = 1.0 # m; keep this far from the person (camera distance); nearer: no forward
FOLLOW_MAX_MS = 0.15 # m/s; forward speed cap (estimate, tune live) NEAR_STOP_M = 0.8 # m; nearer than this no turn either: the arm would swing close to them (estimate)
SPEED_GAIN = 0.8 # m/s per m the person is further than FOLLOW_GAP_M FOLLOW_MAX_MS = 0.3 # m/s; forward cap, first live run slow (joy_control clamps at 0.5, docs/05); raise to 0.5 after it
ACCEL_MS2 = 0.4 # m/s^2; speeding up at most this fast (slowing down at once) SPEED_GAIN = 0.8 # m/s per m the person is further than FOLLOW_GAP_M, on top of their walking speed
TURN_GAIN = 1.0 # rad/s per rad the person is off to the side ACCEL_MS2 = 0.5 # m/s^2; speeding up at most this fast (estimate, tune live)
TURN_MAX_RS = 0.5 # rad/s; turn speed cap (joy_control takes up to 1.0) DECEL_MS2 = 0.8 # m/s^2; slowing down this fast, and never faster than lets it stop at the gap (estimate)
TURN_GAIN = 1.5 # rad/s per rad the person is off to the side
TURN_MAX_RS = 0.6 # rad/s; turn speed cap (joy_control takes up to 1.0; the arm tips sweep 0.6 m out)
TURN_ACCEL_RS2 = 2.0 # rad/s^2; turn speed changes at most this fast (estimate)
TURN_DEAD_DEG = 5.0 # deg; the person this near the middle: no turn TURN_DEAD_DEG = 5.0 # deg; the person this near the middle: no turn
TURN_ONLY_DEG = 30.0 # deg; the person further aside: turn on the spot first, no forward TURN_ONLY_DEG = 35.0 # deg; the person further aside: turn on the spot first, no forward
STALE_S = 0.5 # s; a sighting older than this: stand still and wait for a new one STALE_S = 0.4 # s; a sighting older than this is not new (Vision gives one per head camera frame, 15/s)
LOST_S = 2.0 # s without a sighting -> "I lost you" (lumi.Vision drops a track after its own LOST_S, 2 s) COAST_S = 1.0 # s after the last sighting the base drives on toward where they should be; then it slows
LOST_S = 3.0 # s without a sighting -> "I lost you" (lumi.Vision drops a track after its own LOST_S, 2 s)
VEL_TAU_S = 0.5 # s; time constant of the walking velocity filter (depth jumps a few cm per frame)
WALK_MAX_MS = 2.0 # m/s; a faster walking estimate is noise
JUMP_M = 0.5 # m; a sighting this far from where the person should be is someone else (estimate) ...
GATE_GROW_MS = 0.7 # ... plus this much per s unseen (they may have turned): re-lock radius (estimate)
SWITCH_M = 0.15 # m; another track must be this much nearer to where they should be to be taken (estimate)
RELOCK_LOOK = 0.6 # reid.same below this: clearly other clothes, not taken (same person 0.66-0.91, reid.py)
BRAKE_S = 0.5 # s; the base and the arm must be clear where this command would take them by then BRAKE_S = 0.5 # s; the base and the arm must be clear where this command would take them by then
BLOCKED_END_S = 5.0 # s standing in front of an obstacle before giving up
ARM_CLEAR_M = fetch.ARM_CLEAR_M # m; arm points kept this far from anything the lidar / map shows ARM_CLEAR_M = fetch.ARM_CLEAR_M # m; arm points kept this far from anything the lidar / map shows
BASE_CLEAR_M = fetch.BASE_HALF_M + fetch.CLEAR_M # m; base centre kept this far, unless it gets further away BASE_CLEAR_M = fetch.BASE_HALF_M + fetch.CLEAR_M # m; base centre kept this far, unless it gets further away
TICK_S = 0.1 # s between commands (joy_control wants > 2 Hz) TICK_S = 0.1 # s between commands, steady (joy_control wants > 2 Hz; a tick takes ~10-30 ms)
LOG_S = 1.0 # s between "follow: v ... " lines (what the next live run is read from)
JOIN_S = 2.0 # s a new "follow me" waits for the old loop to end JOIN_S = 2.0 # s a new "follow me" waits for the old loop to end
RELOCK_DEG = 25.0 # deg; a fresh track this near the lost person's last angle is taken as them (estimate) HEAD_YAW_MAX = 120.0 # deg; the head turns toward the person up to this far (+ left; body API allows 180)
RELOCK_M = 0.8 # m; ... and this near their last distance (estimate)
HEAD_YAW_MAX = 90.0 # deg; the head turns toward the person up to this far (+ left; body API allows 180)
HEAD_PITCH = 10.0 # deg; head pitch while following, a little up toward a standing person (as "look at me") HEAD_PITCH = 10.0 # deg; head pitch while following, a little up toward a standing person (as "look at me")
HEAD_STEP_DEG = 5.0 # deg; a new head move only when the person is this far from where the head was sent HEAD_STEP_DEG = 3.0 # deg; a new head move only when the target is this far from where the head was sent
HEAD_LEAD_S = 0.3 # s; the head is sent where the person will be this much later (a moveto takes time)
HEAD_VEL = 50 # speed ratio %; the head is at its full speed from 50 (audio/sing.py, measured) HEAD_VEL = 50 # speed ratio %; the head is at its full speed from 50 (audio/sing.py, measured)
HEAD_TIMEOUT_S = 5 # s; one head move (90 deg at ~40 deg/s takes ~2.5 s) HEAD_TIMEOUT_S = 5 # s; one head move (90 deg at ~40 deg/s takes ~2.5 s)
@@ -85,34 +102,39 @@ def stop():
return was return was
def speeds(distance, angle_deg, v_last, dt=TICK_S): def speeds(distance, angle_deg, v_last, w_last=0.0, walk=0.0, go=True, dt=TICK_S):
"""(v m/s, w rad/s) toward a person `distance` m away at `angle_deg` (+ left); never forward inside the gap.""" """(v m/s, w rad/s) toward a person `distance` m away at `angle_deg` (+ left), walking `walk` m/s away: their
if distance <= FOLLOW_GAP_M: speed plus SPEED_GAIN per m beyond the gap, never faster than lets the base stop at the gap, changed smoothly.
return 0.0, 0.0 # close enough: stand still (no turn: the arm sweeps) Never forward inside the gap; nothing at all inside NEAR_STOP_M. go=False: only slow down (and turn)."""
if distance < NEAR_STOP_M:
return 0.0, 0.0
a = math.radians(angle_deg) a = math.radians(angle_deg)
w = 0.0 if abs(angle_deg) < TURN_DEAD_DEG else max(-TURN_MAX_RS, min(TURN_MAX_RS, TURN_GAIN * a)) w_want = 0.0 if abs(angle_deg) < TURN_DEAD_DEG else max(-TURN_MAX_RS, min(TURN_MAX_RS, TURN_GAIN * a))
v = 0.0 if abs(angle_deg) > TURN_ONLY_DEG else min(FOLLOW_MAX_MS, SPEED_GAIN * (distance - FOLLOW_GAP_M), w = w_last + max(-TURN_ACCEL_RS2 * dt, min(TURN_ACCEL_RS2 * dt, w_want - w_last))
v_last + ACCEL_MS2 * dt) room = distance - FOLLOW_GAP_M
if room <= 0:
return 0.0, w # at the gap: no forward now
v_want = 0.0 if not go or abs(angle_deg) > TURN_ONLY_DEG else \
min(FOLLOW_MAX_MS, max(0.0, walk) + SPEED_GAIN * room, math.sqrt(2 * DECEL_MS2 * room))
v = min(v_last + ACCEL_MS2 * dt, max(v_last - DECEL_MS2 * dt, v_want))
return max(0.0, v), w return max(0.0, v), w
def blocked(v, w, arm_pts): def blocked(v, w, arm_pts, pose=None):
"""True when the base or the arm would come too close to something within BRAKE_S at (v, w).""" """Why the base or the arm would come too close to something within BRAKE_S at (v, w), None when clear."""
x, y, th = agv.pose() x, y, th = pose or agv.pose()
th2 = th + w * BRAKE_S th2 = th + w * BRAKE_S
x2, y2 = x + v * BRAKE_S * math.cos(th), y + v * BRAKE_S * math.sin(th) x2, y2 = x + v * BRAKE_S * math.cos(th), y + v * BRAKE_S * math.sin(th)
if v > 0: if v > 0:
ahead = agv.clearance(x2, y2) ahead = agv.clearance(x2, y2)
if ahead < BASE_CLEAR_M and ahead < agv.clearance(x, y): if ahead < BASE_CLEAR_M and ahead < agv.clearance(x, y):
fetch.log(f"follow: an obstacle {ahead:.2f} m from the base's way") return f"an obstacle {ahead:.2f} m from the base's way"
return True
c, s = math.cos(th2), math.sin(th2) c, s = math.cos(th2), math.sin(th2)
for p in arm_pts: for p in arm_pts:
px, py = x2 + c * p[0] - s * p[1], y2 + s * p[0] + c * p[1] px, py = x2 + c * p[0] - s * p[1], y2 + s * p[0] + c * p[1]
if agv.clearance(px, py) < ARM_CLEAR_M: if agv.clearance(px, py) < ARM_CLEAR_M:
fetch.log(f"follow: my arm would hit something at ({px:.2f}, {py:.2f})") return f"my arm would hit something at ({px:.2f}, {py:.2f})"
return True return None
return False
def ready(): def ready():
@@ -150,27 +172,78 @@ def prepare():
return [np.asarray(p, float) for p in fetch.arm_points()] return [np.asarray(p, float) for p in fetch.arm_points()]
def _relock(people, last): def _to_map(pose, d, a):
"""The see() of the fresh track nearest to where the followed person was last (distance, angle), None when """Map point (x, y) of a sighting d m away at a deg (+ left) from the base at pose (the camera ~ the base centre)."""
nobody is near. ponytail: by position only, appearance (reid) would tell two people apart.""" x, y, th = pose
d0, a0 = last return np.array([x + d * math.cos(th + math.radians(a)), y + d * math.sin(th + math.radians(a))])
near = [(abs(a - a0), see) for see, d, a, age in people()
if age < STALE_S and abs(a - a0) <= RELOCK_DEG and abs(d - d0) <= RELOCK_M]
return min(near, key=lambda n: n[0], default=(0, None))[1]
def _head_follow(target, done, lift, waist): def _rel(pose, p):
"""(distance m, angle deg + left) of the map point p from the base at pose."""
x, y, th = pose
a = math.degrees(math.atan2(p[1] - y, p[0] - x) - th)
return math.hypot(p[0] - x, p[1] - y), (a + 180.0) % 360.0 - 180.0
class Person:
"""Where the followed person is on the map: the last sighting (p, t) and a smoothed walking velocity."""
def __init__(self):
self.p, self.t, self.vel = None, None, np.zeros(2)
def seen(self, p, t):
if self.p is not None:
if t <= self.t + 1e-3:
return # the same sighting read again
k = (t - self.t) / (VEL_TAU_S + t - self.t)
vel = (1 - k) * self.vel + k * (p - self.p) / (t - self.t)
speed = float(np.linalg.norm(vel))
self.vel = vel if speed <= WALK_MAX_MS else vel * WALK_MAX_MS / speed
self.p, self.t = p, t
def at(self, t):
"""Where they should be at t (the walk is carried on for COAST_S at most)."""
return self.p + self.vel * min(max(t - self.t, 0.0), COAST_S)
def _fresh(got):
return got is not None and got[2] < STALE_S
def _pick(see, got, people, person, pose, sig, now):
"""(see, sighting) of the followed person this tick: of their own track's sighting and every fresh one in view the
nearest to where they should be, within JUMP_M (growing while unseen) and not in clearly other clothes. A track
taken over by a passer-by jumps away from that place, the person's own new track is near it. Their own track is
kept unless another is SWITCH_M nearer (the same track also comes in people()). Sighting None: none."""
cands = [(see, got)] if _fresh(got) else []
cands += [(s, tuple(g)) for s, *g in (people() if people else ()) if _fresh(g)]
if person.p is None: # nothing to compare with yet: their own track
return see, (got if _fresh(got) else None)
gate = JUMP_M + GATE_GROW_MS * min(max(now - person.t - STALE_S, 0.0), LOST_S)
best = (float("inf"), see, None)
for s, g in cands:
e = float(np.linalg.norm(_to_map(pose, *g[:2]) - person.at(now - g[2])))
if e > gate or sig is not None and g[3] is not None and reid.same(sig, g[3]) < RELOCK_LOOK:
continue
e -= SWITCH_M if s is see else 0.0
if e < best[0]:
best = (e, s, g)
return best[1:]
def _head_follow(target, done, lift, waist, stats):
"""Turn the head to target[0] (yaw, pitch) whenever it is HEAD_STEP_DEG from where it was sent last. One moveto """Turn the head to target[0] (yaw, pitch) whenever it is HEAD_STEP_DEG from where it was sent last. One moveto
at a time, from this thread only: overlapping calls hang the body API.""" at a time, from this thread only: overlapping calls hang the body API. The drive loop never waits for it."""
sent = None sent = None
while not done.is_set(): while not done.is_set():
t = target[0] t = target[0]
if t is None or sent is not None and max(abs(t[0] - sent[0]), abs(t[1] - sent[1])) < HEAD_STEP_DEG: if t is None or sent is not None and max(abs(t[0] - sent[0]), abs(t[1] - sent[1])) < HEAD_STEP_DEG:
done.wait(TICK_S) done.wait(TICK_S / 2)
continue continue
try: try:
t0 = time.time()
head.moveto([lift, waist, *t], vel=HEAD_VEL, acc=HEAD_VEL, timeout=HEAD_TIMEOUT_S) head.moveto([lift, waist, *t], vel=HEAD_VEL, acc=HEAD_VEL, timeout=HEAD_TIMEOUT_S)
sent = t sent, stats["head"], stats["head_ms"] = t, t[0], round(1000 * (time.time() - t0))
except (ConnectionError, OSError, ValueError, KeyError) as e: except (ConnectionError, OSError, ValueError, KeyError) as e:
fetch.log(f"follow: head error {e!r}") fetch.log(f"follow: head error {e!r}")
done.wait(1.0) done.wait(1.0)
@@ -178,54 +251,86 @@ def _head_follow(target, done, lift, waist):
def _run(see, say, people): def _run(see, say, people):
"""The loop: until stop(), lost, or something in the way. Any failure ends with the base at 0 and a reason said.""" """The loop: until stop(), lost, or something in the way. Any failure ends with the base at 0 and a reason said."""
v, turning = 0.0, False v = w = 0.0
done, target = threading.Event(), [None] done, target, stats = threading.Event(), [None], {"head": None, "head_ms": None}
head.owners = (threading.current_thread(),) head.owners = (threading.current_thread(),)
person = Person()
try: try:
got = see() # where they are now: prepare() may turn the waist
sig = got[3] if got else None
if _fresh(got):
person.seen(_to_map(agv.pose(), *got[:2]), time.time() - got[2])
arm_pts = prepare() arm_pts = prepare()
lift, waist = head.status()[:2] lift, waist = head.status()[:2]
head_thread = threading.Thread(target=_head_follow, args=(target, done, lift, waist), daemon=True, head_thread = threading.Thread(target=_head_follow, args=(target, done, lift, waist, stats), daemon=True,
name="follow head") name="follow head")
head.owners += (head_thread,) head.owners += (head_thread,)
head_thread.start() head_thread.start()
seen_t, last = time.time(), None start_t = next_t = time.time() # lost counts from here: prepare() takes a few seconds
turning, blocked_t, hold_v, log_t, odd_t, log_pose = False, None, 0.0, 0.0, 0.0, agv.pose()
while not _stop.is_set(): while not _stop.is_set():
got = see()
now = time.time() now = time.time()
if (got is None or got[2] >= STALE_S) and last and people: pose = agv.pose()
new = _relock(people, last) mine, was = see(), see
if new is not None: see, got = _pick(see, mine, people, person, pose, sig, now)
fetch.log(f"follow: re-locked onto the person at {last[1]:+.0f} deg") if see is not was:
see, got = new, new() fetch.log(f"follow: re-locked onto the person at {got[0]:.2f} m {got[1]:+.0f} deg")
if got is not None and got[2] < STALE_S: elif got is None and _fresh(mine) and now - odd_t > LOG_S:
seen_t, last = now - got[2], got[:2] odd_t = now
cmd = speeds(got[0], got[1], v) fetch.log(f"follow: a sighting at {mine[0]:.2f} m {mine[1]:+.0f} deg is not them (someone else)")
target[0] = (max(-HEAD_YAW_MAX, min(HEAD_YAW_MAX, got[1])), HEAD_PITCH) if _fresh(got):
else: # stale or gone (Vision drops a track unseen for 2 s) p = _to_map(pose, *got[:2])
if now - seen_t >= LOST_S: person.seen(p, now - got[2])
fetch.log("follow: lost the person") near = [float(np.linalg.norm(_to_map(pose, *o[1:3]) - p)) for o in people() if _fresh(o[1:])] \
fetch._say(say, *LOST) if people else [0.0]
return if got[3] is not None and all(e > JUMP_M or e < 0.05 for e in near): # alone (or themselves):
cmd = (0.0, 0.0) sig = reid.blend(sig, got[3]) # these clothes are theirs
if now - max(person.t or 0.0, start_t) >= LOST_S:
fetch.log("follow: lost the person")
fetch._say(say, *LOST)
return
if person.p is None: # not seen yet (only before the first sighting)
cmd, d, a, walk = (0.0, 0.0), 0.0, 0.0, 0.0
else:
d, a = _rel(pose, person.at(now))
yaw = _rel(pose, person.at(now + HEAD_LEAD_S))[1]
target[0] = (max(-HEAD_YAW_MAX, min(HEAD_YAW_MAX, yaw)), HEAD_PITCH)
walk = float(person.vel @ np.array([math.cos(pose[2]), math.sin(pose[2])]))
cmd = speeds(d, a, v, w, walk, go=now - person.t <= COAST_S, dt=TICK_S)
spot = cmd[0] == 0.0 and cmd[1] != 0.0 # a turn on the spot (the person aside or behind) spot = cmd[0] == 0.0 and cmd[1] != 0.0 # a turn on the spot (the person aside or behind)
if spot and not turning: if spot and not turning:
hit = fetch.turn_hits(got[1]) # the arm's whole sweep toward them hit = fetch.turn_hits(a) # the arm's whole sweep toward them
if hit is not None: if hit is not None:
fetch.log(f"follow: turning {got[1]:+.0f} deg my arm would hit something at " fetch.log(f"follow: turning {a:+.0f} deg my arm would hit something at "
f"({hit[0]:.2f}, {hit[1]:.2f})") f"({hit[0]:.2f}, {hit[1]:.2f})")
fetch._say(say, "My arm can't turn here, something is in its way.", fetch._say(say, "My arm can't turn here, something is in its way.",
"팔이 부딪힐 수 있어서 돌 수 없어요.") "팔이 부딪힐 수 있어서 돌 수 없어요.")
return return
turning = spot turning = spot
if cmd != (0.0, 0.0) and blocked(*cmd, arm_pts): # stopped by something: on again only when the speed it was stopped at is clear (no creeping up to it)
fetch._say(say, "Something is in my way, so I stopped.", "앞이 막혀서 멈췄어요.") why = cmd != (0.0, 0.0) and blocked(max(cmd[0], hold_v) if cmd[0] else 0.0, cmd[1], arm_pts, pose)
return if why:
if blocked_t is None:
fetch.log(f"follow: standing, {why}")
blocked_t, hold_v, cmd = blocked_t or now, max(hold_v, cmd[0]), (0.0, 0.0)
if now - blocked_t >= BLOCKED_END_S:
fetch._say(say, "Something is in my way, so I stopped.", "앞이 막혀서 멈췄어요.")
return
elif cmd != (0.0, 0.0):
blocked_t, hold_v = None, 0.0
with _send: with _send:
if _stop.is_set(): if _stop.is_set():
return return
_joy(*cmd) _joy(*cmd)
v = cmd[0] v, w = cmd
_stop.wait(TICK_S) if now - log_t >= LOG_S: # driven: what the base really did since the last line (pose)
driven = math.hypot(pose[0] - log_pose[0], pose[1] - log_pose[1]) / max(now - log_t, 1e-3)
log_t, log_pose = now, pose
fetch.log(f"follow: v {v:.2f} w {w:+.2f} driven {driven:.2f} m/s | person {d:.2f} m {a:+.0f} deg, seen "
f"{now - (person.t or now):.2f} s ago, walking {walk:+.2f} m/s | head "
f"{stats['head'] or 0:+.0f} deg ({stats['head_ms']} ms) | tick {1000 * (time.time() - now):.0f} ms")
next_t = max(next_t + TICK_S, time.time()) # a steady rate; a slow tick is not caught up
_stop.wait(next_t - time.time())
except fetch.Stopped: except fetch.Stopped:
pass pass
except fetch.FetchError as e: except fetch.FetchError as e:
+2 -2
View File
@@ -94,8 +94,8 @@ def llm(text, state, marks, b):
head = next(gen) head = next(gen)
first = next(gen, "") or "" first = next(gen, "") or ""
gen.close() gen.close()
if head["action"] == "none" and brain.promised(first): # lumi.answer() does what the reply promises if head["action"] == "none" and brain.promised(first) in ("sing", "wave"): # lumi.answer() does what the reply
head = {"action": brain.promised(first), "target": ""} head = {"action": brain.promised(first), "target": ""} # promises (a move: it asks)
target = (brain._mentions(text, marks).get("object") or "") if head["action"] == "receive" else head["target"] target = (brain._mentions(text, marks).get("object") or "") if head["action"] == "receive" else head["target"]
return act(head["action"], target, first, state), f"{head['action']} {target}".strip(), first return act(head["action"], target, first, state), f"{head['action']} {target}".strip(), first
+17
View File
@@ -70,6 +70,23 @@ assert ears.transcribe(AUDIO) == "" and "from 0.20 s" in ears.last_stt["dropped"
ears.speech_seconds = lambda audio: 0.4 ears.speech_seconds = lambda audio: 0.4
assert ears.transcribe(AUDIO) == "감사합니다." assert ears.transcribe(AUDIO) == "감사합니다."
# the detector itself: silence and piano-like music have no speech (the model file is local, models/) # the detector itself: silence and piano-like music have no speech (the model file is local, models/)
# a sentence cut by a pause ("Let's" ... "follow me"): the rest is recorded and heard with the first part
import types
real_record, real_transcribe = ears.record, ears.transcribe
first = types.SimpleNamespace(mono=np.ones(8000, np.int16), t_end=10.0, peak=900.0, seconds=0.5)
rest = types.SimpleNamespace(mono=np.ones(12000, np.int16), t_end=11.5, peak=900.0, seconds=0.75)
calls = []
ears.record = lambda wait_s=8.0, on_start=None, abort=None, since=None: calls.append(since) or (first if since is None else rest)
ears.transcribe = lambda audio: "Let's" if len(audio) == 8000 else "Let's follow me."
assert ears.listen() == "Let's follow me." and calls == [None, 10.0], calls
ears.transcribe = lambda audio: "Can you see me?" # a whole sentence: nothing waited for
calls.clear()
assert ears.listen() == "Can you see me?" and calls == [None], calls
ears.record = lambda wait_s=8.0, on_start=None, abort=None, since=None: first if since is None else None
ears.transcribe = lambda audio: "Let's" # nothing more said: the part as heard
assert ears.listen() == "Let's"
ears.record, ears.transcribe = real_record, real_transcribe
if real_speech_seconds(AUDIO) is not None: if real_speech_seconds(AUDIO) is not None:
from tests.asr_cases4 import synth from tests.asr_cases4 import synth
assert real_speech_seconds(AUDIO) == 0.0 assert real_speech_seconds(AUDIO) == 0.0
+138 -18
View File
@@ -18,6 +18,7 @@ lumi.LOG_FILE = "/dev/null" # keep the assistant's real
tmp = Path(tempfile.mkdtemp()) tmp = Path(tempfile.mkdtemp())
fetch.STATE_FILE = tmp / "lumi_task.json" # never the real /dev/shm file fetch.STATE_FILE = tmp / "lumi_task.json" # never the real /dev/shm file
follow.TICK_S = 0.02 follow.TICK_S = 0.02
follow.FOLLOW_MAX_MS = 0.5 # the walks below are checked at the full clamp (joy_control 0.5)
M = ["home", "p1", "p3"] M = ["home", "p1", "p3"]
@@ -114,17 +115,22 @@ class World:
return self.person + self.walk * min(time.time() - self.t0, self.walk_s) return self.person + self.walk * min(time.time() - self.t0, self.walk_s)
def see(self): def see(self):
"""What lumi.Vision.follow_view gives: (distance, angle deg + left, age s).""" """What lumi.Vision.follow_view gives: (distance, angle deg + left, age s, look)."""
if self.hidden: if self.hidden:
return None return None
x, y, th = self.pose() d, a = self.sight(self.person_at())
px, py = self.person_at()
d = math.hypot(px - x, py - y)
self.dist.append(d) self.dist.append(d)
a = (math.degrees(math.atan2(py - y, px - x) - th) + 180) % 360 - 180
if self.fov and abs(a - body.pos[2]) > HALF_FOV: if self.fov and abs(a - body.pos[2]) > HALF_FOV:
return None return None
return d, a, 0.0 return d, a, 0.0, self.look
look = None
def sight(self, p):
"""(distance, angle deg + left) of the map point p from the base now."""
x, y, th = self.pose()
a = (math.degrees(math.atan2(p[1] - y, p[0] - x) - th) + 180) % 360 - 180
return math.hypot(p[0] - x, p[1] - y), a
said = [] said = []
@@ -142,7 +148,7 @@ def wait_end(s=3.0):
# follows a person walking away, at most FOLLOW_MAX_MS, never inside the gap, turns toward them # follows a person walking away, at most FOLLOW_MAX_MS, never inside the gap, turns toward them
follow.FOLLOW_MAX_MS = 0.4 # the walk below needs the full speed; the file value is tuned live MAX_MS, follow.FOLLOW_MAX_MS = follow.FOLLOW_MAX_MS, 0.4 # a lower cap: reached and kept
w = World(person=(2.2, 0.4), walk=(0.3, 0.05), walk_s=2.0) w = World(person=(2.2, 0.4), walk=(0.3, 0.05), walk_s=2.0)
follow.start(w.see, say) follow.start(w.see, say)
time.sleep(6.0) time.sleep(6.0)
@@ -157,9 +163,10 @@ assert w.dist[-1] < follow.FOLLOW_GAP_M + 0.15, w.dist[-1]
assert w.y > 0.1 and abs(w.see()[1]) < follow.TURN_DEAD_DEG + 1.0, (w.y, w.see()) # turned toward them assert w.y > 0.1 and abs(w.see()[1]) < follow.TURN_DEAD_DEG + 1.0, (w.y, w.see()) # turned toward them
assert w.cmds[-1][1:] == (0.0, 0.0) assert w.cmds[-1][1:] == (0.0, 0.0)
print(f"follow: ok (drove {w.x:.2f}, {w.y:.2f} m, top {max(vs):.2f} m/s, nearest {min(w.dist):.2f} m)") print(f"follow: ok (drove {w.x:.2f}, {w.y:.2f} m, top {max(vs):.2f} m/s, nearest {min(w.dist):.2f} m)")
follow.FOLLOW_MAX_MS = MAX_MS
# closer than the gap: stands still (no forward, no turn) # closer than NEAR_STOP_M: stands still (no forward, no turn)
w = World(person=(0.8, 0.3)) w = World(person=(0.6, 0.3))
follow.start(w.see, say) follow.start(w.see, say)
time.sleep(0.5) time.sleep(0.5)
follow.stop() follow.stop()
@@ -200,7 +207,7 @@ follow.stop()
assert wait_end(0.5) assert wait_end(0.5)
print("restart: ok") print("restart: ok")
# lost: no sighting for LOST_S -> "I lost you", the base stopped # lost: no sighting -> drives on toward where they were for COAST_S, slows to 0, after LOST_S "I lost you"
said.clear() said.clear()
w = World(person=(3.0, 0.0)) w = World(person=(3.0, 0.0))
follow.start(w.see, say) follow.start(w.see, say)
@@ -208,14 +215,17 @@ time.sleep(0.3)
w.hidden, t_lost = True, time.time() w.hidden, t_lost = True, time.time()
assert wait_end(follow.LOST_S + 1.0) assert wait_end(follow.LOST_S + 1.0)
assert said == [follow.LOST[0]], said assert said == [follow.LOST[0]], said
assert w.cmds[-1][1:] == (0.0, 0.0) and all(c[1:] == (0.0, 0.0) for c in w.cmds if c[0] > t_lost + 0.05) after = [c[1] for c in w.cmds if c[0] > t_lost + follow.COAST_S + 0.05]
assert w.cmds[-1][1:] == (0.0, 0.0) and after and all(b <= a + 1e-9 for a, b in zip(after, after[1:])), after
t_still = t_lost + follow.COAST_S + follow.FOLLOW_MAX_MS / follow.DECEL_MS2 + 0.1
assert all(c[1:] == (0.0, 0.0) for c in w.cmds if c[0] > t_still)
print("lost: ok") print("lost: ok")
# a stale sighting stands still, then counts as lost # a stale sighting stands still, then counts as lost
said.clear() said.clear()
w = World(person=(3.0, 0.0)) w = World(person=(3.0, 0.0))
t_old = time.time() - follow.STALE_S - 0.1 t_old = time.time() - follow.STALE_S - 0.1
follow.start(lambda: (3.0, 0.0, time.time() - t_old), say) follow.start(lambda: (3.0, 0.0, time.time() - t_old, None), say)
assert wait_end(follow.LOST_S + 1.0) and said == [follow.LOST[0]] and all(c[1:] == (0.0, 0.0) for c in w.cmds) assert wait_end(follow.LOST_S + 1.0) and said == [follow.LOST[0]] and all(c[1:] == (0.0, 0.0) for c in w.cmds)
print("stale: ok") print("stale: ok")
@@ -223,7 +233,7 @@ print("stale: ok")
said.clear() said.clear()
w = World(person=(3.0, 0.0), obstacles=[(1.5, 0.0)]) w = World(person=(3.0, 0.0), obstacles=[(1.5, 0.0)])
follow.start(w.see, say) follow.start(w.see, say)
assert wait_end(6.0) assert wait_end(4.0 + follow.BLOCKED_END_S)
assert said == ["Something is in my way, so I stopped."], said assert said == ["Something is in my way, so I stopped."], said
assert 0.3 < w.x and w.x + ARM[-1][0] < 1.5 - 0.05 and w.cmds[-1][1:] == (0.0, 0.0), w.x assert 0.3 < w.x and w.x + ARM[-1][0] < 1.5 - 0.05 and w.cmds[-1][1:] == (0.0, 0.0), w.x
print(f"obstacle: stopped at {w.x:.2f} m (finger tips {1.5 - w.x - ARM[-1][0]:.2f} m before it)") print(f"obstacle: stopped at {w.x:.2f} m (finger tips {1.5 - w.x - ARM[-1][0]:.2f} m before it)")
@@ -287,7 +297,7 @@ follow.stop()
assert wait_end(0.5) assert wait_end(0.5)
yaws = [m[4] for m in body.moves if m[1] == "follow head"] yaws = [m[4] for m in body.moves if m[1] == "follow head"]
assert body.overlaps == 0 and len(yaws) >= 3, (body.overlaps, len(yaws)) assert body.overlaps == 0 and len(yaws) >= 3, (body.overlaps, len(yaws))
assert max(yaws) > follow.TURN_ONLY_DEG - 1 and min(yaws) >= -follow.HEAD_STEP_DEG, yaws # left, toward them assert max(yaws) > 20.0 and min(yaws) >= -follow.HEAD_STEP_DEG, yaws # left, toward them
assert abs(yaws[-1]) < 15.0, yaws[-1] # back toward 0 assert abs(yaws[-1]) < 15.0, yaws[-1] # back toward 0
assert math.degrees(w.th) > 120.0 and all(m[5] == follow.HEAD_PITCH for m in body.moves), math.degrees(w.th) assert math.degrees(w.th) > 120.0 and all(m[5] == follow.HEAD_PITCH for m in body.moves), math.degrees(w.th)
print(f"walk behind: head up to {max(yaws):.0f} deg, base turned {math.degrees(w.th):.0f} deg, {len(yaws)} head moves") print(f"walk behind: head up to {max(yaws):.0f} deg, base turned {math.degrees(w.th):.0f} deg, {len(yaws)} head moves")
@@ -325,7 +335,7 @@ follow.start(lambda: None if gone[0] else w.see(), say, people=lambda: fresh)
time.sleep(0.3) time.sleep(0.3)
gone[0] = True # the track id is dropped gone[0] = True # the track id is dropped
time.sleep(0.5) time.sleep(0.5)
fresh.append((w.see, 3.0, 8.0, 0.0)) # a new track where they were fresh.append((w.see, 3.0, 8.0, 0.0, None)) # a new track where they were
t_new = time.time() t_new = time.time()
time.sleep(follow.LOST_S + 0.5) time.sleep(follow.LOST_S + 0.5)
assert follow.running() and not said, said assert follow.running() and not said, said
@@ -334,13 +344,122 @@ follow.stop()
assert wait_end(0.5) assert wait_end(0.5)
said.clear() said.clear()
w = World(person=(3.0, 0.0)) w = World(person=(3.0, 0.0))
fresh = [(lambda: (3.0, 80.0, 0.0), 3.0, 80.0, 0.0)] fresh = [(lambda: (3.0, 80.0, 0.0, None), 3.0, 80.0, 0.0, None)]
follow.start(lambda: None if w.hidden else w.see(), say, people=lambda: fresh) follow.start(lambda: None if w.hidden else w.see(), say, people=lambda: fresh)
time.sleep(0.3) time.sleep(0.3)
w.hidden = True w.hidden = True
assert wait_end(follow.LOST_S + 1.0) and said == [follow.LOST[0]], said assert wait_end(follow.LOST_S + 1.0) and said == [follow.LOST[0]], said
print("re-lock: ok") print("re-lock: ok")
def missing(world, every=1.0, gap=0.5):
"""world.see as Vision gives it with frames missed: for `gap` s of every `every` s the last sighting gets older."""
last = [None, 0.0]
def see():
t = time.time() - world.t0
if t % every < every - gap or last[0] is None:
last[:] = [world.see(), time.time()]
return last[0]
d, a, _, look = last[0]
return d, a, time.time() - last[1], look
return see
def steady(cmds, t_from, t_to):
"""Forward speeds sent between t_from and t_to (s after the start) and the biggest change from one to the next."""
t0 = cmds[0][0]
vs = [c[1] for c in cmds if t_from <= c[0] - t0 <= t_to]
return vs, max((abs(b - a) for a, b in zip(vs, vs[1:])), default=0.0)
step = max(follow.ACCEL_MS2, follow.DECEL_MS2) * follow.TICK_S + 1e-6
# walks away at 0.45 m/s with half the frames missed: drives on smoothly (no stop-and-go), keeps up
said.clear()
w = World(person=(2.0, 0.0), walk=(0.45, 0.0), walk_s=6.0)
follow.start(missing(w), say)
time.sleep(6.0)
assert follow.running() and not said, said
follow.stop()
assert wait_end(0.5)
vs, jump = steady(w.cmds, 1.5, 5.8)
assert min(vs) > 0.2 and jump <= step, (min(vs), jump) # never stopped, smooth
assert w.dist[-1] < 2.0 + 0.2, w.dist[-1] # did not fall behind
print(f"walk away, frames missed: {min(vs):.2f}-{max(vs):.2f} m/s, gap {w.dist[-1]:.2f} m")
# walks faster than the base (1.2 m/s for 2 s), then stops: full speed, never lost, slows smoothly, stops at the gap
said.clear()
w = World(person=(1.5, 0.0), walk=(1.2, 0.0), walk_s=2.0)
follow.start(w.see, say)
time.sleep(9.0)
assert follow.running() and not said, said
follow.stop()
assert wait_end(0.5)
vs, jump = steady(w.cmds, 0.0, 9.0)
assert max(vs) >= follow.FOLLOW_MAX_MS - 1e-6 and jump <= step + 0.03, (max(vs), jump) # the last cm/s at the gap: 0
assert min(w.dist) >= follow.FOLLOW_GAP_M - 0.02 and w.dist[-1] < follow.FOLLOW_GAP_M + 0.2, (min(w.dist), w.dist[-1])
print(f"faster than the base, then stops: top {max(vs):.2f} m/s, nearest {min(w.dist):.2f} m, stood at {w.dist[-1]:.2f} m")
# walks a curve (a quarter circle of 2.5 m to the left at 0.4 m/s): turns with them, stays close behind
said.clear()
R = 2.5
w = World(path=lambda t: (R * math.sin(min(t, 9.0) * 0.16), R - R * math.cos(min(t, 9.0) * 0.16) + 0.0 * t))
w.path0 = w.path
w.path = lambda t: (1.5 + w.path0(t)[0], w.path0(t)[1])
follow.start(w.see, say)
time.sleep(11.0)
assert follow.running() and not said, said
follow.stop()
assert wait_end(0.5)
assert math.degrees(w.th) > 45.0 and w.dist[-1] < follow.FOLLOW_GAP_M + 0.3, (math.degrees(w.th), w.dist[-1])
print(f"curve: base turned {math.degrees(w.th):.0f} deg, gap {w.dist[-1]:.2f} m")
# another person crosses between: the followed track jumps onto them (Vision matched them), the followed person gets a
# fresh track: the jump is not taken, Lumi re-locks onto the right one and follows them on
said.clear()
A = lambda t: (2.0 + 0.3 * min(t, 6.0), 0.0) # the followed person
B = lambda t: (1.7, 1.5 - 1.0 * t) # crosses in front, 1 m/s
w = World(path=A)
stolen = 1.2 # s; from here the track is B's
def followed():
t = time.time() - w.t0
if t < stolen:
return w.see()
return (*w.sight(B(t)), 0.0, None)
def everyone():
t = time.time() - w.t0
a = (lambda: w.see()) if t >= stolen + 0.1 else None # A's new track, a frame later
return [(followed, *followed())] + ([(a, *a())] if a else [])
follow.start(followed, say, people=everyone)
time.sleep(6.0)
assert follow.running() and not said, said
follow.stop()
assert wait_end(0.5)
t_end = time.time() - w.t0
assert abs(w.y) < 0.15 and w.dist[-1] < follow.FOLLOW_GAP_M + 0.4, (w.y, w.dist[-1]) # followed A
assert math.hypot(*(np.array(B(t_end)) - (w.x, w.y))) > 2.0
print(f"another person crossing: stayed with them (y {w.y:+.2f} m, gap {w.dist[-1]:.2f} m)")
# re-lock by clothes: someone where the person should be, in clearly other clothes, is not taken
n = len(lumi.reid.PARTS) * (lumi.reid.H_BINS * lumi.reid.S_BINS + lumi.reid.V_BINS) // len(lumi.reid.PARTS)
red, blue = np.zeros(2 * n), np.zeros(2 * n)
red[[0, n]], blue[[20, n + 20]] = 1.0, 1.0
p = follow.Person()
p.seen(np.array([3.0, 0.0]), time.time())
cand = [(lambda: None, 3.0, 2.0, 0.0, list(blue))]
gone = lambda: None
assert follow._pick(gone, None, lambda: cand, p, (0.0, 0.0, 0.0), list(red), time.time()) == (gone, None)
assert follow._pick(gone, None, lambda: cand, p, (0.0, 0.0, 0.0), list(blue), time.time())[1][:2] == (3.0, 2.0)
assert follow._pick(gone, None, lambda: cand, p, (0.0, 0.0, 0.0), None, time.time())[1] is not None
print("re-lock by clothes: ok")
# lumi: act("stop") ends following; follow_me locks onto the person talking, refuses when it must # lumi: act("stop") ends following; follow_me locks onto the person talking, refuses when it must
lumi.agv.cancel = lumi.skills.cancel = lumi.arm.stop = lambda: None lumi.agv.cancel = lumi.skills.cancel = lumi.arm.stop = lambda: None
w = World(person=(3.0, 0.0)) w = World(person=(3.0, 0.0))
@@ -353,7 +472,8 @@ spoken, started = [], []
lumi.mouth.say = lambda text, **k: spoken.append(text) lumi.mouth.say = lambda text, **k: spoken.append(text)
real_start = follow.start real_start = follow.start
follow.start = lambda see, say=None, people=None: started.append(see) follow.start = lambda see, say=None, people=None: started.append(see)
track = types.SimpleNamespace(id=7, distance=1.8, angle=10.0, greeted=False, history=[1.7], last_seen=time.time()) track = types.SimpleNamespace(id=7, distance=1.8, angle=10.0, greeted=False, history=[1.7], last_seen=time.time(),
look=None)
L.lang, L.voice_angle, L.voice_trusted = "en", 0.0, False L.lang, L.voice_angle, L.voice_trusted = "en", 0.0, False
L.modes = types.SimpleNamespace(drive=True, patrol=True) L.modes = types.SimpleNamespace(drive=True, patrol=True)
L.skill_busy = lambda: False L.skill_busy = lambda: False
@@ -365,7 +485,7 @@ L.current = track
L.find_caller = lambda angle, trusted: None L.find_caller = lambda angle, trusted: None
L.follow_me() L.follow_me()
assert started and "follow you" in spoken[-1], spoken assert started and "follow you" in spoken[-1], spoken
d, a, age = started[-1]() d, a, age, look = started[-1]()
assert (d, a) == (1.7, 10.0) and age < 1.0 # the nearer of median / newest assert (d, a) == (1.7, 10.0) and age < 1.0 # the nearer of median / newest
L.vision.tracks = [] L.vision.tracks = []
assert started[-1]() is None # track gone: lost assert started[-1]() is None # track gone: lost
+8
View File
@@ -76,6 +76,14 @@ for _ in range(20): # a song we don't have: sai
assert all(SONGS[sid]["title"] in en and SONGS[sid]["title_ko"] in ko for sid in SONGS), (en, ko) assert all(SONGS[sid]["title"] in en and SONGS[sid]["title_ko"] in ko for sid in SONGS), (en, ko)
assert "{" not in en + ko and "네 곡" in ko or "이렇게" not in ko, ko assert "{" not in en + ko and "네 곡" in ko or "이렇게" not in ko, ko
assert len({sing.unknown_reply("en") for _ in range(40)}) > 2 # not the same words every time assert len({sing.unknown_reply("en") for _ in range(40)}) > 2 # not the same words every time
# the song bank never reads a cut-off start or words without a song word (no embedding needed: refused first)
for t in ["Let's", "can you", "please", "루미야 저기", "let's go", "Lumi, can you", "follow me", "what time is it"]:
assert sing.bank_read(t) is None, t
from assistant import brain # a reply promising a move the action line did not: asked
for t, want in [("Okay, I'll follow you!", "motion"), ("네, 따라갈게요!", "motion"), ("I'm coming!", "motion"),
("Okay! I'll sing a song for you.", "sing"), ("I'll wave!", "wave"), ("I'll look into it.", None),
("I'll give you an example.", None), ("알려 드릴게요.", None), ("I can follow you if you like.", None)]:
assert brain.promised(t) == want, (t, brain.promised(t))
assert all(sing.stop_words(t) for t in ["stop", "Lumi stop", "멈춰", "그만", "그만해", "enough", "스톱"]) assert all(sing.stop_words(t) for t in ["stop", "Lumi stop", "멈춰", "그만", "그만해", "enough", "스톱"])
assert not any(sing.stop_words(t) for t in ["sing another song", "다른 노래", "what time is it"]) assert not any(sing.stop_words(t) for t in ["sing another song", "다른 노래", "what time is it"])
+2 -1
View File
@@ -55,7 +55,8 @@ REBOOT_IF_STUCK_AGAIN_S = 15.0 # s; stuck again this soon after a reopen -> re
REBOOT_WAIT_S = 6.0 # s for a rebooted camera to come back on USB REBOOT_WAIT_S = 6.0 # s for a rebooted camera to come back on USB
MAX_REBOOTS_10MIN = 3 # more than this -> the camera rests UNSTABLE_PAUSE_S before trying again MAX_REBOOTS_10MIN = 3 # more than this -> the camera rests UNSTABLE_PAUSE_S before trying again
UNSTABLE_PAUSE_S = 60.0 UNSTABLE_PAUSE_S = 60.0
HEAD_POLL_S = 0.2 # s between head yaw reads (head camera only) HEAD_POLL_S = 0.1 # s between head yaw reads (head camera only; a status read takes ~5 ms). A turning head
# (follow, ~40 deg/s estimated) moves ~4 deg in this time: a person's angle is off by up to that
def _profile(pipeline, sensor, mode): def _profile(pipeline, sensor, mode):