Conversation and web: closings by context, follow-up lookups keep the name and place, office holders and prices looked up; reach toward the person; bottles by their body (belly grasp only); music never a turn (speech detector); songs: a promise is done; two-stop drives in the Command box

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-22 14:07:56 +09:00
co-authored by Claude Opus 5.5
parent 9cd8e5706b
commit 88a5349b04
34 changed files with 838 additions and 491 deletions
+94
View File
@@ -0,0 +1,94 @@
"""Music in the room, for tests/asr_check.py --cases 4 (2026-10-22: soft music, nobody speaking, became "-끝-" -> goodbye):
music only (kind "noise": right is no wake word and no motion, nothing said), and speech over soft music (the speech
cases' own judgement). The music is made here: piano-like chords, bass, a melody and a hi-hat in four tempos, or
an excerpt of Lumi's public domain songs (data/songs/<id>.wav, sung words over chords; never data/songs/mine).
A case's "music" is "synth:<seed>:<seconds>" or "song:<id>:<start s>:<seconds>"; "music_db" is how far the speech is
above the music (rms).
"""
import pathlib
import random
import wave
import numpy as np
from tests.asr_cases import CASES as SPOKEN
RATE = 16000
SONGS = pathlib.Path(__file__).resolve().parents[1] / "data" / "songs"
MUSIC_DB = 6.0 # speech this much louder than the music (soft background music at a booth)
CASES = []
def synth(seed, seconds):
"""Instrumental music: a I-V-vi-IV progression, decaying piano-like notes with harmonics, a bass, a melody
and a hi-hat on the beat. float32, peak 1."""
rng = np.random.default_rng(seed)
bpm = [72, 96, 118, 140][seed % 4]
beat = 60.0 / bpm
root = 48 + seed % 7 # MIDI note of the key
chords = [(0, 4, 7), (7, 11, 14), (9, 12, 16), (5, 9, 12)]
n = int(seconds * RATE)
out = np.zeros(n + 4 * RATE) # room for the last bar past the end
def note(midi, start, dur, gain, harmonics=4):
f = 440.0 * 2 ** ((midi - 69) / 12)
t = np.arange(int(dur * RATE)) / RATE
tone = sum(np.sin(2 * np.pi * f * k * t) / k ** 1.5 for k in range(1, harmonics + 1))
i = int(start * RATE)
if i >= len(out):
return
seg = tone * np.exp(-3.0 * t / dur) * gain
out[i:i + len(seg)] += seg[:len(out) - i]
t, bar = 0.0, 0
while t < seconds:
ch = chords[bar % 4]
for k in ch:
note(root + 12 + k, t, 4 * beat, 0.25)
note(root - 12 + ch[0], t, 2 * beat, 0.5, 2)
note(root - 12 + ch[0], t + 2 * beat, 2 * beat, 0.5, 2)
for b in range(4):
note(root + 24 + ch[rng.integers(0, 3)] + rng.choice([0, 12]), t + b * beat, beat, 0.2)
i = int((t + b * beat) * RATE)
hat = rng.standard_normal(int(0.03 * RATE)) * np.exp(-np.arange(int(0.03 * RATE)) / 80) * 0.15
out[i:i + len(hat)] += hat[:len(out) - i]
t, bar = t + 4 * beat, bar + 1
out = out[:n]
return (out / (np.abs(out).max() + 1e-9)).astype(np.float32)
def song(sid, start, seconds):
"""An excerpt of data/songs/<sid>.wav at 16 kHz, peak 1."""
with wave.open(str(SONGS / f"{sid}.wav")) as w:
rate = w.getframerate()
x = np.frombuffer(w.readframes(w.getnframes()), np.int16).astype(np.float32)
x = x[int(start * rate):int((start + seconds) * rate)]
x = np.interp(np.arange(0, len(x), rate / RATE), np.arange(len(x)), x)
return (x / (np.abs(x).max() + 1e-9)).astype(np.float32)
def music(spec, seconds=None):
"""The case's music; `seconds` (under speech: the speech's length) instead of the spec's."""
kind, *a = spec.split(":")
if kind == "synth":
return synth(int(a[0]), seconds or float(a[1]))
return song(a[0], float(a[1]), seconds or float(a[2]))
for k in range(16):
CASES.append({"kind": "noise", "lang": "none", "text": f"(music {k})", "say": [],
"music": f"synth:{k}:{[1.5, 2.5, 4.0, 6.0][k % 4]}"})
for sid in ["arirang", "happy_birthday", "row_row", "three_bears", "twinkle"]:
for start in (2.0, 14.0):
CASES.append({"kind": "noise", "lang": "none", "text": f"({sid} at {start:.0f} s)", "say": [],
"music": f"song:{sid}:{start}:3.0"})
R = random.Random(4)
for i, c in enumerate(R.sample(SPOKEN, 40)):
CASES.append({**c, "music": f"synth:{100 + i}:1.0", "music_db": MUSIC_DB})
for i, (lang, t) in enumerate([("en", "Sing a song."), ("en", "Let's do some music."), ("en", "Lumi, stop."),
("en", "Hi Lumi."), ("ko", "노래 불러 줘."), ("ko", "음악 틀어 줘."), ("ko", "루미야."),
("ko", "멈춰.")]):
kind = "wake" if "Lumi." in t or t == "루미야." else "command"
CASES.append({"kind": kind, "lang": lang, "text": t, "say": [(lang, t)], "music": f"synth:{200 + i}:1.0",
"music_db": MUSIC_DB})
+14 -2
View File
@@ -6,6 +6,8 @@ microphones, sent through ears.transcribe() exactly as Lumi does, then through L
.venv/bin/python tests/asr_check.py --prompt "..." # another whisper prompt than ears.PROMPT
.venv/bin/python tests/asr_check.py --cases 2 # the second set (tests/asr_cases2.py)
.venv/bin/python tests/asr_check.py --cases 3 # noise and talk not to Lumi (tests/asr_cases3.py)
.venv/bin/python tests/asr_check.py --cases 4 # music only, and speech over soft music (tests/asr_cases4.py)
.venv/bin/python tests/asr_check.py --no-vad # without the speech detector and the subtitle-text filter
.venv/bin/python tests/asr_check.py --heard # also the real clips in logs/heard/ (text only, no judgement)
.venv/bin/python tests/asr_check.py --set LANG_RETRY=False --tag before # an ears constant; -> logs/asr_check_before.md
@@ -33,6 +35,7 @@ from audio import ears
from tests.asr_cases import CASES
from tests.asr_cases2 import CASES as CASES2
from tests.asr_cases3 import CASES as CASES3
from tests import asr_cases4
from tests.command_check import rules
ROOT = pathlib.Path(__file__).resolve().parents[1]
@@ -140,6 +143,8 @@ def judge(c, heard, stt):
if heard and (lumi.WAKE.search(heard) or lumi.HELLO_ONLY.match(heard)):
return "slip", "wake word"
got = route(heard, brain.Brain()) if heard else "llm"
if c.get("music") and heard and ears.understood(): # in a conversation any text taken is a turn
return "slip", f"a turn ({got})"
return ("slip", got) if heard and ears.understood() and re.match(
r"action|receive|give|place|stop|mission|sing", got) else ("right", "")
if not heard:
@@ -174,20 +179,27 @@ def main(args):
setattr(ears, k, type(getattr(ears, k))(eval(v)))
only = args[args.index("--only") + 1] if "--only" in args else None
tag = args[args.index("--tag") + 1] if "--tag" in args else ""
if "--no-vad" in args: # before 2026-10-22: every sound went to whisper
ears.MIN_SPEECH_S, ears.SPEECH_PER_SYLLABLE, ears.NOT_SAID = -1.0, 0.0, re.compile(r"(?!)")
if "--port" in args: # a whisper-server already running there
global STT_PORT
STT_PORT = int(args[args.index("--port") + 1])
start_server()
rng = np.random.default_rng(5)
rows, t0 = [], time.time()
pool = {"1": CASES, "2": CASES2, "3": CASES3}[args[args.index("--cases") + 1] if "--cases" in args else "1"]
pool = {"1": CASES, "2": CASES2, "3": CASES3, "4": asr_cases4.CASES}[args[args.index("--cases") + 1] if "--cases" in args else "1"]
cases = [c for c in pool if not only or re.search(only, c["text"])]
for i, c in enumerate(cases):
voice, speed = VOICES[i % len(VOICES)], [0.85, 0.95, 1.05, 1.15][(i // len(VOICES)) % 4]
x = synth(c["say"], voice, speed)
if c.get("music") and not c["say"]: # music only
x = asr_cases4.music(c["music"])
elif c.get("music"): # speech over music, music_db below it
m = asr_cases4.music(c["music"], len(x) / ears.RATE)[:len(x)]
x = x + m * np.sqrt(np.mean(x ** 2) / (np.mean(m ** 2) + 1e-12)) / 10 ** (c["music_db"] / 20)
for rname in rooms:
others = [synth(pool[(i * 7 + k * 13) % len(pool)]["say"], VOICES[(i + k + 3) % 10], 1.0) * 0.5
for k in range(3)] if ROOMS[rname]["babble"] else ()
for k in range(3)] if ROOMS[rname]["babble"] and c["say"] else () # music alone: no people
audio = room(x, ROOMS[rname], rng, others)
t1 = time.time()
heard = ears.transcribe(audio, ears.PROMPT)
+1 -1
View File
@@ -35,7 +35,7 @@ def route(lang, ctx, said):
first = next(gen, "")
secs = time.time() - t
reply = " ".join([first] + list(gen))
if head["action"] == "end":
if head["action"] == "end" and (fate != "close" or lumi.kept_goodbye(reply)): # as lumi.answer
return "end", secs, reply
return ("wait" if fate == "close" else "on"), secs, reply
+5
View File
@@ -312,4 +312,9 @@ for t, want in [("Let's go P5 (point).", "action:go_to p5"), ("Let's go P9.", "a
("let's go eat", "talk")]:
CASES.append({"intent": "new:go", "text": t, "lang": "en", "state": "idle", "before": None, "expect": want,
"markers": ["home", "dock2", "exit", "final"] + [f"p{i}" for i in range(1, 11)]}) # the owner's map
for t in ["let's go exit point and go p9 point", "go to exit then p9", "first exit then p9", "exit 갔다가 p9로 가",
"exit 포인트 갔다가 p9 포인트로 가", "먼저 final 가고 그다음 p2로 가", "let's go final point and go p9 point"]:
CASES.append({"intent": "new:mission", "text": t, "lang": "ko" if any("가" <= ch <= "힣" for ch in t) else "en",
"state": "idle", "before": None, "expect": "mission",
"markers": ["home", "dock2", "exit", "final"] + [f"p{i}" for i in range(1, 11)]}) # the owner's map
R.shuffle(CASES) # the report lists them by intent; the order only spreads the LLM's load
+1 -1
View File
@@ -373,7 +373,7 @@ add("fetch", "bring the cup from start to table front", "action:fetch | mission"
add("fetch", "pass me the cup", "mission | action:fetch")
add("fetch", "can I have the apple?", "mission | action:fetch")
add("fetch", "컵 좀 줘", "mission | action:fetch")
add("fetch_refuse", "bring me a bottle from the stage", "refuse | talk | ask")
add("fetch", "bring me a bottle from the stage", "action:fetch | mission") # bottles by their body since 2026-10-22
add("fetch_unknown", "bring me a cup from the kitchen", "refuse | talk | ask | action:fetch") # parse_fetch asks
add("fetch_not", "I brought my own cup", "talk")
+8 -4
View File
@@ -6,6 +6,7 @@
# the same (fast, after a rule change)
.venv/bin/python tests/command_check.py receive # only this intent
.venv/bin/python tests/command_check.py --new # only the second set (tests/command_cases2.py); --old the first
.venv/bin/python tests/command_check.py --songs # only the song set (tests/song_cases.py) -> logs/song_check.*
-> logs/command_check.md / .json (rules only: logs/command_check_rules.*). The order is lumi.answer()'s with nothing running and the hand empty ("idle") or
holding something ("holding"): stop, what the cameras see (seeing.answer), status, the hand (brain.hand_request), mission, goodbye / closing words, song,
@@ -23,6 +24,7 @@ from audio import sing
from tests.command_cases import CASES as CASES1
from tests.command_cases2 import CASES as CASES2 # 2026-10-21 night: new wordings, the conference map
from tests.command_cases3 import CASES as CASES3 # the same night, written blind from docs/14 and docs/17
from tests.song_cases import CASES as SONGS # 2026-10-22: song requests and near misses, written blind
from tests.conversation_check import NOW, markers
ROOT = pathlib.Path(__file__).resolve().parents[1]
@@ -86,9 +88,7 @@ def rules(text, state, marks, b):
return "talk" if read[1] else "refuse" if steps.check(read[0], holding, marks) else "mission"
if lumi.talk_fate(text) == "end":
return "end"
if lumi.talk_fate(text) == "close": # read by the LLM with the talk before: no command
return "talk"
if sing.asked(text):
if sing.asked(text, b.history[-1][1] if b.history else ""):
return "sing"
rule = brain.intent(text, marks)
if rule and rule[0] in QUICK:
@@ -104,6 +104,8 @@ def llm(text, state, marks, b):
head = next(gen)
first = next(gen, "") or ""
gen.close()
if head["action"] == "none" and brain.promised(first): # lumi.answer() does what the reply promises
head = {"action": brain.promised(first), "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
@@ -155,7 +157,9 @@ def main(args):
global OUT
marks = markers()
use_llm, cached = "--llm" in args, "--cached" in args
cases = CASES2 if "--new" in args else CASES3 if "--blind" in args else CASES1 if "--old" in args else \
if "--songs" in args:
OUT = OUT.with_name("song_check")
cases = SONGS if "--songs" in args else CASES2 if "--new" in args else CASES3 if "--blind" in args else CASES1 if "--old" in args else \
CASES1 + CASES2 + CASES3
only = [a for a in args if not a.startswith("-")]
old = {}
+2 -2
View File
@@ -108,8 +108,8 @@ def llm_route(action, target, words, text, about, lang, repeating=False):
return action, "" # lumi.answer() closes the stream and looks it up
if action == "unclear":
return action, " ".join(words)
if action == "none" and lumi.talk_fate(text) == "close": # "thanks" taken as heard: silence ends the talk
return "chat", " ".join(words)
if lumi.talk_fate(text) == "close" and (action == "none" or action == "end" and not lumi.kept_goodbye(" ".join(words))):
return "chat", " ".join(words) # "thanks" taken as heard: silence ends the talk
if action in ("none", "sing") and not repeating and lumi.look_up_unsure(about, words[0] if words else "", text):
return "search(unsure)", " ".join(words)
return ("none" if action == "none" else f"action:{action} {target}".strip()), " ".join(words)
+4
View File
@@ -386,4 +386,8 @@ CASES_MORE = [
"refused|llm", "the toilets of this building"),
C([T("그럼 뭐 좋아해?", "저는 노래 부르는 걸 좋아해요.")], "오 노래?", "llm", "되묻는 말: 노래 시작 아님"),
C([T("What do you like?", "I like singing.")], "Oh, a song?", "llm", "an echo, not a request"),
C([], "노래 좋아해?", "llm", "노래 얘기: 부르라는 말 아님"),
C([], "너 무슨 노래 부를 수 있어?", "llm|act:sing", "부를 수 있는 노래 목록 (lumi: 목록을 말함)"),
C([], "Hmm, I wonder if it's going to rain later.", "weather", "an indirect weather question"),
C([T("고마워 루미야", "천만에요!")], "thank you 해", "llm", "부모가 아이에게: 인사하라는 말, 끝 아님"),
]
+49
View File
@@ -0,0 +1,49 @@
"""Song requests and near misses (2026-10-22), written blind after the live talk of 12:20 (music playing, "Let's do
music." / "Start with one." got no song): ways people ask for a song or for music, English, Korean and mixed, also
whisper's slips, and short answers right after Lumi offered its songs. The near misses talk about music or songs
and must not start one. Same notation as tests/command_cases3.py; run with tests/command_check.py --songs.
"""
CASES = []
OFFER = ("Can you make music?", "ACTION: none -\nI can't make new music, but I can sing several songs for you, such as "
"Happy Birthday or Arirang. Which one would you like to hear?")
OFFER_KO = ("음악 할 수 있어?", "ACTION: none -\n작곡은 못 하지만 노래는 몇 곡 불러 드릴 수 있어요. 어떤 노래 불러 드릴까요?")
LIKES = ("Do you like music?", "ACTION: none -\nI love music! I even sing a few songs.")
def add(text, expect, before=None):
lang = "ko" if any("가" <= ch <= "힣" for ch in text) else "en"
CASES.append({"intent": "song:" + ("ask" if expect == "sing" else "not"), "text": text, "lang": lang,
"state": "idle", "before": before, "expect": expect})
for t in ["Sing a song.", "Sing me something.", "Could you sing for us?", "Will you sing a song for me?",
"Let's do music.", "Let's have some music.", "Play some music.", "Play music, please.", "Make some music!",
"Can you make some music for us?", "Start the music.", "Music, please.", "Give us a song.",
"How about a song?", "Any song is fine, just sing.", "Sing anything you like.", "Sing your favourite one.",
"I want to hear you sing.", "Let me hear a song.", "Do a song for the kids.", "Perform a song for us.",
"Can you sing happy birthday?", "Sing Arirang, please.", "Sing twinkle twinkle.",
"Could you put on some music?", "Lumi, sing!", "Sing one more.", "Hit it, Lumi, music!",
"It sings one music.", "Can you sing song?", "Let's say song.", "Sing a Korean song."]:
add(t, "sing")
for t in ["노래 불러 줘.", "노래 한 곡 해 줘.", "음악 틀어 줘.", "노래 좀 해 봐.", "한 곡 뽑아 봐.", "노래 들려줘.",
"노래 하나 불러 줄래요?", "아무 노래나 불러 줘.", "음악 좀 틀어 주세요.", "생일 축하 노래 불러 줘.",
"아리랑 불러 주세요.", "노래해 줘.", "노래 부탁해요.", "루미야 노래!", "신나는 노래 하나 해 줘.",
"노래 불러 주실 수 있어요?", "한국 노래 불러 줘.", "음악 좀 해 줘.", "노래 한 번 들어 보고 싶어요.",
"노래 불러 줄 수 있어?", "Lumi 노래 해 줘.", "song 하나 불러 줘."]:
add(t, "sing")
for t, before in [("Start with one.", OFFER), ("Any one.", OFFER), ("You choose.", OFFER), ("Surprise me.", OFFER),
("Yes, please.", OFFER), ("The first one.", OFFER), ("Whatever you like.", OFFER),
("아무거나.", OFFER_KO), ("네, 불러 주세요.", OFFER_KO), ("아무거나 해 줘.", OFFER_KO),
("니가 골라.", OFFER_KO), ("첫 번째 거요.", OFFER_KO), ("좋아요, 해 주세요.", OFFER_KO),
("Sure, go ahead.", LIKES), ("Then show me.", LIKES), ("그럼 해 봐.", LIKES)]:
add(t, "sing", before)
for t in ["I like music.", "What music do you like?", "Do you like singing?", "Who is your favourite singer?",
"Can I make music?", "My daughter sings in a choir.", "The music here is loud.",
"Is that music coming from you?", "What songs do you know?", "Music is my hobby.",
"I'll sing later at the party.",
"노래 좋아해?", "무슨 노래 좋아해?", "음악 소리가 너무 커요.", "저 노래 잘 못 불러요.",
"어제 노래방 갔어요.", "이 음악 누가 틀었어?", "가수 누구 좋아해?", "노래 잘하네."]:
add(t, "talk | ask")
add("Stop the music.", "talk | ask | stop")
for t in ["Don't sing, please.", "노래 부르지 마."]: # no song; Lumi staying quiet a while is a fair reading too
add(t, "talk | ask | action:quiet")
+5
View File
@@ -188,6 +188,11 @@ CASES.update({
"컵 집었다가 제자리에 놔": "pick cup | place",
"컵 집고 제자리에 다시 놔 줘": "pick cup | place",
"take the cup, go to the stage and put it back": "?",
"let's go stage point and go booth two point": "go stage | go booth_2",
"first the stage, then the end": "go stage | go end",
"go to the start point then the end point": "go start | go end",
"스테이지 포인트 갔다가 엔드 포인트로 가": "go stage | go end",
"먼저 미들 가고 그다음 파이널로 가": "go middle | go final",
"look at me and wave": "?",
"웨이브 하고 나 봐": "?",
"나 보고 손 흔들어": "?",
+2 -2
View File
@@ -67,7 +67,7 @@ CASES = {
"go to the middle and dance": "?",
"if nobody is there, come back": "?",
"go to the stage and if nobody is there, come back": "?",
"pick up the bottle and take it to the end": "?",
"pick up the bottle and take it to the end": "pick bottle | go end",
"take the banana to the stage": "?",
"move forward 5 meters and then turn left": "?",
"go to the end and wait there for an hour": "?",
@@ -101,7 +101,7 @@ CASES = {
"주방 갔다 와": "?",
"스테이지 가서 손 흔들어": "?",
"엔드 가서 춤춰": "?",
"병 들고 스테이지로 가": "?",
"병 들고 스테이지로 가": "pick bottle | go stage",
# ---- Korean 해요체 ----
"컵 들고 부스 투로 가서 제임스한테 줘요": "pick cup | go booth_2 | give 제임스",
"스테이지로 가서 안녕하세요라고 말해 주세요": "go stage | say 안녕하세요",
+24
View File
@@ -9,6 +9,8 @@ from audio import ears
ears.ensure_stt_server = lambda: None
ears.HEARD_DIR = ears.ROOT / "logs" / "asr_check" / "heard_test"
AUDIO = np.zeros(16000, np.int16)
real_speech_seconds = ears.speech_seconds
ears.speech_seconds = lambda audio: 1.0 # the cases below are speech; the detector is checked at the end
def fake(answers):
@@ -50,4 +52,26 @@ assert ears.transcribe(AUDIO) == "" and asked == [None, "no prompt"], asked
# the name really said: kept
asked = fake({None: ("Hey Lumi.", "english", 0.9, -0.05), "no prompt": ("Hey, Liumu!", "english", 0.9, -0.8)})
assert ears.transcribe(AUDIO) == "Hey Lumi." and asked == [None, "no prompt"], asked
# music or noise (no speech frames): whisper is not asked
ears.speech_seconds = lambda audio: 0.03
asked = fake({None: ("-끝-", "korean", 0.9, -0.01)})
assert ears.transcribe(AUDIO) == "" and asked == [] and "no speech" in ears.last_stt["dropped"], asked
# whisper's subtitle texts for music, with some speech frames: dropped
ears.speech_seconds = lambda audio: 0.4
for text in ["-끝.", "- 네.", "-", "...", "자막 제공 및 광고를 포함하고 있습니다.", "Thanks for watching!"]:
fake({None: (text, "korean", 0.9, -0.01)})
assert ears.transcribe(AUDIO) == "", text
fake({None: ("네.", "korean", 0.9, -0.1)})
assert ears.transcribe(AUDIO) == "네."
# more words than the speech held: "감사합니다." from 0.2 s of speech frames is music; from 0.4 s it was said
ears.speech_seconds = lambda audio: 0.2
fake({None: ("감사합니다.", "korean", 0.9, -0.01)})
assert ears.transcribe(AUDIO) == "" and "from 0.20 s" in ears.last_stt["dropped"]
ears.speech_seconds = lambda audio: 0.4
assert ears.transcribe(AUDIO) == "감사합니다."
# the detector itself: silence and piano-like music have no speech (the model file is local, models/)
if real_speech_seconds(AUDIO) is not None:
from tests.asr_cases4 import synth
assert real_speech_seconds(AUDIO) == 0.0
assert real_speech_seconds((synth(0, 3.0) * 8000).astype(np.int16)) < ears.MIN_SPEECH_S
print("ears ok")
+41 -4
View File
@@ -916,6 +916,43 @@ threading.Timer(0.1, lambda: (hand.update(front=True), fetch.release_now())).sta
st = run(fetch.run_steps, [P(do="receive", object="cup", from_hand=True)], say)
assert st["status"] == "holding" and not [l for l, t in reach_to if l == "to the hand"], (st, reach_to)
fetch._set(holding=False, status="idle")
# "reach out to me": to give along the pose graph (via carry), then 150 mm towards their nearer seen hand
ahead = lambda mm, side=0.0: [g0[0] + mm, g0[1] + side, g0[2]]
scene["person_in_front"] = {"position_mm": ahead(900.0), "hands": {"left": {"position_mm": ahead(600.0, 100.0),
"distance_m": 1.1}, "right": {"position_mm": ahead(400.0), "distance_m": 0.9}}}
turns = []
real_turn = fetch._turn
fetch._turn = lambda deg, holding=False, why="": turns.append(deg) or deg < 90
def reached(angle=0.0):
reach_to.clear()
reset()
st = run(fetch.reach, angle, say)
return st, [t[:3] for l, t in reach_to if l == "to the hand"]
st, moves = reached()
assert st["status"] == "done" and poses() == ["carry", "give"] and not turns, (st, poses())
assert len(moves) == 1 and np.allclose(moves[0], [fetch.RECEIVE_REACH_MM, 0, 0]), moves
scene["person_in_front"]["hands"]["right"]["position_mm"] = ahead(180.0) # stops RECEIVE_SHORT_MM before it
assert np.allclose(reached()[1][0], [80.0, 0, 0])
scene["person_in_front"]["hands"] = {"left": None, "right": {"position_mm": None, "distance_m": None}}
scene["person_in_front"]["position_mm"] = ahead(fetch.REACH_BODY_MM + 60.0) # no hand seen: REACH_BODY_MM before
assert np.allclose(reached()[1][0], [60.0, 0, 0]) # the body
scene["person_in_front"]["position_mm"] = ahead(fetch.REACH_BODY_MM + 10.0) # too short a move: left out
st, moves = reached()
assert st["status"] == "done" and poses()[-1] == "give" and not moves, (st, moves)
scene["person_in_front"] = None # nobody seen: the hand at give
st, moves = reached()
assert st["status"] == "done" and poses()[-1] == "give" and not moves, (st, moves)
st, moves = reached(40.0) # to the side (Patrol): the base turns first, by the
assert turns == [40.0 + fetch._waist_turn()] and poses()[-1] == "give", (turns, poses()) # waist's offset too
turns.clear()
said.clear()
st, moves = reached(120.0) # the turn refused (charger, sweep): the arm stays
assert st["status"] == "failed" and not poses() and said[-1] == fetch.TURN_TO_PERSON[0], (st, said)
fetch._turn = real_turn
fetch._line_rows, fetch._scene = real_line_rows, real_scene
hand["front"] = False
# the cup is in the hand but nobody says okay: the hand never closes (their fingers may be in it)
@@ -1032,7 +1069,7 @@ assert moves == [[75.0, -15.0, *fetch.HEAD_AHEAD]], moves
fetch.head.status, fetch.head.moveto = real_status, real_move
# ---------- objects the fingers can't take: refused in words, before anything moves ----------
assert "narrow" in fetch.validate({**ok, "object": "bottle"}, MARKERS)[0]
assert "break" in fetch.validate({**ok, "object": "wine glass"}, MARKERS)[0]
assert "thin" in fetch.validate({**ok, "object": "banana"}, MARKERS)[0]
assert fetch.validate({**ok, "object": "giraffe"}, MARKERS)[0].startswith("Which object? I can pick up cup, apple")
assert all(fetch.validate({**ok, "object": n}, MARKERS) == [] for n in fetch.PICKABLE)
@@ -1040,10 +1077,10 @@ assert fetch.describe({**ok, "object": "sports ball"}, "ko").startswith("p1 위
reset()
said.clear()
try: # steps.check refuses it before the mission starts (read-back included)
st = run(fetch.run_steps, [P(do="pick", object="bottle", colour=None)], say)
assert st["status"] == "failed" and "narrow" in said[-1], (st, said)
st = run(fetch.run_steps, [P(do="pick", object="wine glass", colour=None)], say)
assert st["status"] == "failed" and "break" in said[-1], (st, said)
except fetch.FetchError as e:
assert "narrow" in str(e), e
assert "break" in str(e), e
assert not any(c[0] in ("pick", "go_point", "find") for c in calls), calls
# ---------- several of them: the chosen one out of reach (or the wrong size) -> another one here that is not ----------
+5
View File
@@ -262,6 +262,11 @@ for text, said, prefer in (("take the smaller cup to p1", "Take the smaller cup
r = server.task_parse(server.ParseBody(text="bring me the cup from p1, no, from p8"))
assert r["action"] == "fetch" and r["task"]["source"] == {"marker": "p8"}, r
assert server.task_parse(server.ParseBody(text="go to p1, never mind"))["problems"] == ["Taken back: nothing to do."]
# two places in a row is a mission by the rules (live 2026-10-22: it was read as a fetch of nothing by the LLM)
r = server.task_parse(server.ParseBody(text="let's go p1 point and go p8 point"))
assert r["action"] == "steps" and r["steps"] == [{"do": "go", "to": "p1"}, {"do": "go", "to": "p8"}], r
r = server.task_parse(server.ParseBody(text="go from p1 to p8 and dance"))
assert r["action"] is None and r["task"] is None and r["read_by"] == "rules", r # no object named: never a fetch
two = [{**cups[0], "x": -100.0, "y": 600.0, "width_mm": 80.0}, {**cups[0], "x": 120.0, "y": 650.0, "width_mm": 66.0}]
find = lambda **t: fetch._find({"object": "cup", "colour": None, **t}, two)
assert find() == two[0] and find(prefer="small") == two[1] and find(prefer="big") == two[0]
+104 -10
View File
@@ -37,19 +37,19 @@ for bad in (88, 30, 50): # seen widths: +SEEN_UNDER_MM over
# ---------- the object table: what the cup fingers take, and why not ----------
for name in ("cup", "apple", "orange", "sports ball"):
assert skills.refusal(name) is None, name
for name, word in (("bottle", "narrow"), ("wine glass", "break"), ("banana", "thin"), ("cell phone", "thin"),
for name, word in (("wine glass", "break"), ("banana", "thin"), ("cell phone", "thin"),
("book", "flat"), ("bowl", "shallow"), ("sandwich", "soft"), ("laptop", "big")):
en, ko = skills.refusal(name)
assert word in en and name in en and ko, (name, en, ko)
assert skills.refusal("bottle")[1] == "병은 윗부분이 좁아서 제 손가락으로 잡을 수 없어요." # 은 after a final consonant
assert skills.refusal("vase")[1] == "꽃병은 깨질 수 있어서 잡지 않을게요." # 은 after a final consonant
assert skills.refusal("banana")[1].startswith("바나나는 ")
assert "giraffe" in skills.refusal("giraffe")[0] # not in the table at all
assert all(n in skills.objects.COCO for n in skills.GRASPS), [n for n in skills.GRASPS if n not in skills.objects.COCO]
try: # refused before any geometry
skills.plan_pick({**cup, "name": "bottle"})
raise AssertionError("a bottle planned")
skills.plan_pick({**cup, "name": "wine glass"})
raise AssertionError("a wine glass planned")
except skills.SkillError as e:
assert e.args == skills.refusal("bottle")
assert e.args == skills.refusal("wine glass")
# a cup: the proven grasp, 40 mm below its top, whatever its height
assert skills.grasp_height(cup) == cup["top_mm"] - skills.BELOW_RIM_MM
assert skills.grasp_height({**cup, "height_mm": 80.0}) == cup["top_mm"] - skills.BELOW_RIM_MM
@@ -134,17 +134,33 @@ assert skills.hand_sees() == "unknown"
assert len(skills.GRASP_YAWS) == 24 and set(skills.GRASP_YAWS) == set(range(-165, 181, 15))
print("skills ok")
# ---------- the fingers point straight down in the grasp (the tips: TIP_MM along them, below the grasp point)
# ---------- FINGER_DIR is straight down in the grasp (the hand's lowest part: TIP_MM along it, below the grasp point)
assert abs(np.linalg.norm(skills.FINGER_DIR) - 1.0) < 1e-9 and \
(calib.rpy_matrix(*skills.GRASP_RPY) @ skills.FINGER_DIR)[2] < -0.99
# a cup thinner than the belly closes to is held between the tips: the arm stops TIPS_GRASP_MM higher
# the tips grasp is off (MIN_WIDTH 72, 2026-10-22): a 66 mm cup is refused; the checks below turn it back on
try:
skills.plan_pick({**cup, "width_mm": 58.0})
raise AssertionError("66 mm cup planned with the tips grasp off")
except skills.SkillError as e:
assert "too small" in e.args[0]
skills.MIN_WIDTH = 61.0
# a cup thinner than the belly closes to is held between the tips: its axis at the tips (TIPS_OFFSET from the
# belly's centre, level, almost along the flange z axis), at every grasp turn
thin = {**cup, "width_mm": 58.0} # 66 mm at the fingers
g_belly, g_tips = skills.plan_pick(cup)[1][1], skills.plan_pick(thin)[1][1]
assert abs(g_tips[2] - g_belly[2] - skills.TIPS_GRASP_MM) < 1.0 and np.allclose(g_tips[:2], g_belly[:2], atol=1.0)
for yaw in (0, -45, 90):
g_belly, g_tips = skills.plan_pick(cup, yaw)[1][1], skills.plan_pick(thin, yaw)[1][1]
Ry = calib.rpy_matrix(*g_tips[3:])
assert np.allclose(np.array(g_tips[:3]) + Ry @ (skills.GRASP_OFFSET + skills.TIPS_OFFSET), g, atol=1e-6)
shift = np.subtract(g_belly[:3], g_tips[:3])
assert 25 < np.hypot(*shift[:2]) < 32 and abs(shift[2]) < 3, (yaw, shift) # 28 mm, level
skills._held.update(tips=True)
d = skills.plan_place(-200, 600, thin["top_mm"])[1][1] # put down held the same way
assert abs(d[2] - skills.plan_place(-200, 600, thin["top_mm"], tips=False)[1][1][2] - skills.TIPS_GRASP_MM) < 1.0
assert np.allclose(np.array(d[:3]) + R @ (skills.GRASP_OFFSET + skills.TIPS_OFFSET), [-200, 600, g[2] + 3])
skills._held.clear()
# the owner's taught tips grasp of the spray can (grasp_tips_teach.json): the same flange within a few mm, 2 deg
t = skills.TIPS_TEACH
f = skills.flange_for(*t["can_seen"], t["grasp_point_code"][2], skills.yaw_of(t["flange"]), tips=True)
assert np.linalg.norm(np.subtract(f[:3], t["flange"][:3])) < 10, f
# ---------- frames after a move: wait for one written after it ended, never longer than FRESH_WAIT_S ----------
import tempfile
@@ -214,3 +230,81 @@ assert skills.place(-200.0, 600.0) == (-200.0, 600.0)
assert lines_ == ["carry"] and turned[0][1][4] < 0 and abs(round(skills.yaw_of(turned[0][0][1][1]))) == 45, turned
skills._held.clear()
print("skills pick stores ok")
# ---------- a bottle: held by its body, under where the neck widens (objects.body on a depth profile) ----------
H_CAM, D_CAM = -100.0, 600.0 # camera 300 mm above a table at z -400, the bottle's axis 600 mm ahead
T_CAM = np.eye(4)
T_CAM[:3, :3], T_CAM[:3, 3] = [[1, 0, 0], [0, 0, 1], [0, -1, 0]], [0.0, 0.0, H_CAM] # looking along y, level
INTR = {"fx": 600.0, "fy": 600.0, "cx": 320.0, "cy": 100.0, "dist": [0.0] * 5}
BOX = (250, 120, 390, 420)
def depth_of(radius):
"""A level depth camera's frame of an upright round thing on a table at z -400: radius(z) mm, 0 = nothing."""
d = np.zeros((480, 640), np.uint16)
u, v = np.meshgrid(np.arange(BOX[0], BOX[2]), np.arange(BOX[1], BOX[3]))
xn, yn = (u - INTR["cx"]) / INTR["fx"], (v - INTR["cy"]) / INTR["fy"]
for t in np.arange(D_CAM - 60.0, D_CAM, 0.5)[::-1]: # far to near: the nearest surface stays
z = H_CAM - t * yn
r = np.vectorize(radius)(z)
hit = (t * xn) ** 2 + (t - D_CAM) ** 2 <= r ** 2
d[v[hit], u[hit]] = round(t)
return d
def bottle_r(body, shoulder=-230.0, neck=14.0, top=-150.0):
"""A bottle: body radius up to `shoulder`, a 30 mm shoulder narrowing to the neck, the neck up to `top`."""
return lambda z: 0.0 if z < -400 or z > top else body if z <= shoulder else \
neck if z >= shoulder + 30 else body + (neck - body) * (z - shoulder) / 30
from vision import objects
prof = objects.body(depth_of(bottle_r(33.0)), BOX, INTR, T_CAM) # 66 mm body, 28 mm neck
assert -232 <= prof["shoulder_mm"] <= -212 and 60 <= prof["body_mm"] <= 67 and prof["low_mm"] < -390, prof
cup_prof = objects.body(depth_of(lambda z: 0.0 if z < -400 or z > -305 else 40.0 - (-305 - z) * 0.05), BOX, INTR, T_CAM)
assert cup_prof["shoulder_mm"] >= -320, cup_prof # a cup: widest at its top, no neck
skills._held.clear()
bottle = {"name": "bottle", "colour": "blue", "x": -195.0, "y": 600.0, "top_mm": -150.0, "width_mm": 63.0,
"height_mm": None, "shoulder_mm": -203.0, "body_mm": 58.0, "low_mm": -365.0} # the spray can 2026-10-22
assert skills.refusal("bottle") is None and skills.grip_width(bottle) == 66.0 # its body, not the mid band
z = skills.grasp_height(bottle)
assert z == -203.0 - skills.BELOW_SHOULDER_MM and z - skills.TIP_MM >= bottle["low_mm"] + skills.TIP_CLEAR_MM
(_, b_above), (_, b_grasp), (_, b_lift) = skills.plan_pick(bottle)
assert np.allclose(np.array(b_grasp[:3]) + R @ (skills.GRASP_OFFSET + skills.TIPS_OFFSET), [bottle["x"], bottle["y"], z])
assert np.isclose(b_above[2] - b_grasp[2], bottle["top_mm"] - z + skills.TIP_MM) # tips come down from over its top
assert np.isclose(b_lift[2] - b_grasp[2], skills.LIFT_MM)
assert skills.grip_width(bottle) < skills.BELLY_MIN_MM < skills.grip_width({**bottle, "body_mm": 70.0}) # tips / belly
way = dict(skills.plan_place(-130, 600, bottle["top_mm"], below=bottle["top_mm"] - z))
assert np.isclose(way["release up"][2] - way["place"][2], bottle["top_mm"] - z + skills.TIP_MM) # up over its top
assert np.isclose(way["above place"][2] - way["place"][2], skills.ABOVE_MM)
cup_way = dict(skills.plan_place(-130, 600, cup["top_mm"], below=skills.BELOW_RIM_MM)) # a cup: as before
assert np.isclose(cup_way["release up"][2] - cup_way["place"][2], skills.ABOVE_MM)
assert skills.grasp_height({**bottle, "low_mm": -300.0, "table_mm": -396.0}) == z # bottom out of view: the table
for bad, words in (({"body_mm": 50.0}, ("too small", "작아서")),
({"low_mm": -300.0}, ("hit the table", "테이블에 닿아요")), # ... not measured: its lowest point # a too narrow body: 58 at the fingers
({"body_mm": 90.0}, ("too big", "너무 커요")),
({"shoulder_mm": -280.0}, ("hit the table", "테이블에 닿아요")), # the tips would reach the table
({"shoulder_mm": None}, ("body well enough", "몸통이 잘"))):
try:
skills.plan_pick({**bottle, **bad})
raise AssertionError(f"bottle {bad} planned")
except skills.SkillError as e:
assert words[0] in e.args[0] and words[1] in e.args[1] and e.args[1].startswith("병"), (bad, e.args)
# look(): the profile of each frame's bottle box, medians of them; nothing for a cup
frames_ = [{"age_s": 0.1, "objects": [{"name": "bottle", "box": BOX, "colour": "blue", "position_mm": [-195, 600, -280],
"top_mm": -150, "width_mm": 63, "height_mm": 250},
{"name": "cup", "box": BOX, "colour": "white", "position_mm": [0, 600, -350],
"top_mm": -310, "width_mm": 76, "height_mm": 90}]}] * 2
skills.camview.want = lambda name: None
skills.fresh = lambda path, camera, after=0.0: None
skills.objects.latest = lambda camera=objects.CAMERA: frames_[0]
skills.camview.depth = lambda name, max_age=1.0: depth_of(bottle_r(33.0))
skills.camview.intrinsics = lambda name: INTR
skills.objects.base_from_camera = lambda: T_CAM
skills.FRAME_GAP_S = 0.0
got = {o["name"]: o for o in skills.look(frames=2)}
assert got["bottle"]["shoulder_mm"] == prof["shoulder_mm"] and got["bottle"]["body_mm"] == prof["body_mm"], got
assert got["cup"]["shoulder_mm"] is None and got["cup"]["body_mm"] is None
print("skills bottle ok")
+10
View File
@@ -77,6 +77,16 @@ CASES = {
"go to p10, then go left one meter and give it to the person": "go p10 | move left 1 | give",
# 2026-10-21, said by voice: "let's", "P10 point", "10p point", "p ten"
"Let's go P10 point and wait 30 seconds then come back here again.": "go p10 | wait 30 | go here",
# 2026-10-22 live (dashboard): two places in a row, "point" / "포인트" after any marker name
"let's go exit point and go p9 point": "go exit | go p9",
"let's go final point and go p9 point": "go final | go p9",
"go to exit then p9": "go exit | go p9",
"first exit then p9": "go exit | go p9",
"first go to the final point, then p2": "go final | go p2",
"exit 갔다가 p9로 가": "go exit | go p9",
"exit 포인트 갔다가 p9 포인트로 가": "go exit | go p9",
"먼저 exit 가고 그다음 p9로 가": "go exit | go p9",
"dock2 포인트로 갔다가 home으로 가": "go dock2 | go home",
"let's go to 10p point then wait 30 seconds and come back here again": "go p10 | wait 30 | go here",
"go to p ten, wait 30 seconds and come back here": "go p10 | wait 30 | go here",
"go to point 10 and let's back 1 meter": "go p10 | move back 1",
+30
View File
@@ -170,5 +170,35 @@ moved.clear()
L.act("go_to", "p3")
assert moved == ["start_trip"]
follow.stop, fetch.stop = real_follow_stop, real_fetch_stop
# ---------- "reach out to me": toward the person; Greeter never turns the base for it, asks them in front ----------
assert lumi.reach_turn(None, True) is None and lumi.reach_turn(10.0, False) == 0.0
assert lumi.reach_turn(-35.0, True) == -35.0 and lumi.reach_turn(35.0, False) is None
reached = []
real_reach = fetch.reach
fetch.reach = lambda angle=0.0, say=None: reached.append(angle)
L.fetch_finish = lambda how, **k: moved.append(how)
L.skill_thread, L.voice_trusted = None, False
person = types.SimpleNamespace(angle=35.0)
L.vision = types.SimpleNamespace(present=lambda t: False, near_angle=lambda a, d=25: None, only_person=lambda: person)
for patrol, angle, want in ((False, 35.0, None), (True, 35.0, [35.0]), (False, -12.0, [0.0]), (True, -12.0, [0.0])):
L.modes.patrol, person.angle = patrol, angle
reached.clear(), said.clear(), moved.clear()
got = L.reach_out(False)
if want is None: # nothing moves, not even the head
assert got is None and not reached and said == [lumi.STAND_IN_FRONT_SAY[0]] and not moved, (angle, said)
else:
assert got and reached == want and moved == ["head"], (patrol, angle, reached, moved)
L.vision = None # nobody seen, the voice's direction not trusted: ask
reached.clear(), said.clear()
assert L.reach_out(False) is None and not reached and said == [lumi.STAND_IN_FRONT_SAY[0]]
L.voice_trusted, L.voice_angle, L.modes.patrol = True, -50.0, True # heard from the right: turn to the voice
assert L.reach_out(False) and reached == [-50.0]
moved.clear(), reached.clear(), said.clear()
L.fetch_status = lambda: "holding"
assert lumi.Lumi.arm_pose(L, "reach") is None and moved == ["give"] and not reached # holding: hand it over
assert lumi.Lumi.arm_pose(L, "open") is None and said == [lumi.brain_mod.REFUSE_OPEN[0]] # never dropped
L.fetch_status = lambda: None
fetch.reach = real_reach
print(f"switches ok: {len(BASE)} base phrases refused with Greeter only, {len(IN_PLACE)} in place done; "
"arm off asks; Patrol allows all; stop always")