Improve pick and put from the side, quick answers and Korean command understanding
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
+36
-2
@@ -102,6 +102,35 @@ def judge(expect, got):
|
||||
|
||||
|
||||
ROUNDS = [] # --rounds r1,r2: only these blind rounds (r1 = tests/blind/train)
|
||||
QUERIES = ROOT / "data" / "bank_check_queries.npz" # the cases' embeddings, kept between runs (a re-run embeds only
|
||||
# the words it has not seen: minutes instead of an hour)
|
||||
|
||||
|
||||
def _cached_embed():
|
||||
"""knowledge.embed with the case texts' vectors kept in QUERIES; returns a function that saves them."""
|
||||
import numpy as np
|
||||
from assistant import knowledge
|
||||
real, known = knowledge.embed, {}
|
||||
try:
|
||||
z = np.load(QUERIES)
|
||||
known = dict(zip(z["texts"].tolist(), z["vecs"]))
|
||||
except (OSError, ValueError, KeyError):
|
||||
pass
|
||||
n0 = len(known)
|
||||
|
||||
def embed(texts):
|
||||
new = [t for t in dict.fromkeys(texts) if t not in known]
|
||||
if new:
|
||||
known.update(zip(new, real(new)))
|
||||
return np.array([known[t] for t in texts])
|
||||
|
||||
def save():
|
||||
if len(known) > n0:
|
||||
tmp = QUERIES.with_suffix(".tmp.npz")
|
||||
np.savez(tmp, texts=np.array(list(known)), vecs=np.array(list(known.values())))
|
||||
tmp.replace(QUERIES)
|
||||
knowledge.embed = embed
|
||||
return save
|
||||
|
||||
|
||||
def main(args):
|
||||
@@ -111,12 +140,13 @@ def main(args):
|
||||
if "--out" in args:
|
||||
OUT = OUT.with_name(args[args.index("--out") + 1])
|
||||
marks = markers()
|
||||
save_queries = _cached_embed()
|
||||
stress, verbose = "--stress" in args, "-v" in args
|
||||
from assistant import steps
|
||||
steps._ollama = lambda *a: (_ for _ in ()).throw(command_check.NoLLM())
|
||||
real = intent_bank.read
|
||||
by = collections.defaultdict(collections.Counter)
|
||||
wrong, hits, times = [], [], []
|
||||
wrong, hits, times, missed = [], [], [], []
|
||||
from assistant import detour
|
||||
no_stuck = detour.recent
|
||||
for name, text, expect, state, mk, before, *goal in cases("--blind" in args):
|
||||
@@ -143,6 +173,8 @@ def main(args):
|
||||
times.append(time.time() - t0)
|
||||
if not got:
|
||||
by[name]["llm" if ruled in (None, "llm?") else "rules"] += 1
|
||||
if ruled in (None, "llm?") and expect.startswith("action:"):
|
||||
missed.append(f"- [{name}/{state}] {text!r} (want {expect})")
|
||||
continue
|
||||
g = f"action:{got[0]} {got[1]}".strip()
|
||||
verdict = judge(expect, g)
|
||||
@@ -154,6 +186,7 @@ def main(args):
|
||||
by[name][tag] += 1
|
||||
hits.append(f"- [{name}/{state}] {text!r} -> {g}")
|
||||
detour.recent = no_stuck
|
||||
save_queries()
|
||||
for c in by.values():
|
||||
c["cases"] = sum(c.values())
|
||||
total = sum(by.values(), collections.Counter())
|
||||
@@ -167,7 +200,8 @@ def main(args):
|
||||
for k in sorted(by) + ["ALL"]:
|
||||
c = total if k == "ALL" else by[k]
|
||||
lines.append(f"| {k} | {c['cases']} | {c['rules']} | {c['hit']} | {c['agree']} | {c['wrong']} | {c['llm']} |")
|
||||
lines += ["", "## Wrong", ""] + wrong + ["", "## Hits", ""] + hits
|
||||
lines += ["", "## Wrong", ""] + wrong + ["", "## Hits", ""] + hits + \
|
||||
["", "## Left to the LLM, a motion asked (the bank's room to grow)", ""] + missed
|
||||
OUT.write_text("\n".join(lines) + "\n")
|
||||
print("\n".join(lines[:len(by) + 9]))
|
||||
print("\n".join(["", "Wrong:"] + wrong[:80]))
|
||||
|
||||
@@ -418,3 +418,203 @@ grammar, accent slips, near-miss frames), `render10.py` (a meaning at a level; K
|
||||
sets, missions, chain, sing, status, more, speed_short; train and held filled cell by cell from one pool of taken
|
||||
texts), `dlg10.py` (dialogues); `check_r10.py` (round 9's checks plus no held text in train and the English share):
|
||||
0 problems.
|
||||
|
||||
## r11 (round 11, 2026-10-26 night: side pick / put and the kinds r10 lacks, writer W5)
|
||||
|
||||
`r11/train/` and `r11/held/` (seed 111), English half like r10 (field `level` as round 9; English 48–53 % per set, every
|
||||
Korean / Konglish / mixed level in every set and both splits). Written blind (no assistant code or bank read). No text in
|
||||
both splits (dialogues: no scored turn over 25 characters), none of an earlier round's train text (rounds 1–4, r6, r8,
|
||||
r9, r10). Formats of round 9 / r10, NO new expect tokens. Load as `tests.blind.r11.<split>.<name>`.
|
||||
|
||||
| File | train / held | Notes |
|
||||
|---|---|---|
|
||||
| `commands_side` | 2018 / 2018 | NEW set, command format: a cup on Lumi's left / right, beside, at an angle, behind, on "my" left, with a colour ("the red cup on your left": `action:pick red cup \| mission \| refuse`, without colour `action:pick cup \| …`, behind also `ask`); turn / look to a side and pick (`action:pick cup \| chain \| mission \| refuse`); holding: put on the table / down to the left / right (`place \| action:put down \| ask`); put with an empty hand (`empty_hand \| ask \| talk \| refuse`); pick another while holding (`refuse \| talk`); near misses at every level (`talk \| ask`) |
|
||||
| `questions_world` | 2223 / 2223 | round 9's question meanings (field `q`), English with new lead-ins / tails, non-native grammar, slips |
|
||||
| `seeing_dialogues`, `followup_dialogues`, `closing_context`, `lookup_dialogues` | 166 (830 scored), 166 (1494), 199 (199), 123 (1023 / 1025) | round 9's dialogue kinds and checks, English half, English turns re-worded |
|
||||
|
||||
Generator (seeded, not in the repo): `logs/w5_gen/gen11.py` (side meanings written for this round; questions and
|
||||
dialogues through W4's `logs/w4_gen` questions.py / gen_dlg.py / gen_lookup9.py at r10's level weights).
|
||||
|
||||
## r12 (round 12, 2026-10-26 night: arm and hand commands, typed and spoken, writer W6)
|
||||
|
||||
`r12/train/` and `r12/held/` (seed 121), written blind from docs/14, docs/16, docs/17 and the night-5 brief (no assistant
|
||||
code or bank read). Commands only, the arm and the hand the larger part: pick / put / give / receive / fetch with side
|
||||
and direction words ("the cup on your left", "the cup at your two o'clock", "오른쪽 테이블에 놔", "옆에 있는 컵 집어", "내
|
||||
왼쪽 컵", "뒤에 있는 컵"), reach, fold, wave, handshake, open / close, let go, plus head, lift, waist, base, missions,
|
||||
chains, songs, voice, status and stop (every stop form at every level, also inside a longer sentence: "whoa whoa, stop
|
||||
now, you're too close to the table", "아 잠깐만 멈춰, 뭐 좀 고쳐야 돼": `stop`). Every meaning (`intent`) at every level
|
||||
(field `level` as round 9; English 39 %, the seven Korean levels 46 %, Konglish + mixed 15 %) and in both channels.
|
||||
NEW field `"channel"`: `"typed"` (the Command box: capitals, end marks, Korean spacing, typing slips: swapped / doubled /
|
||||
dropped letters, a final consonant doubled or lost, words run together) or `"voice"` (whisper: no punctuation, English
|
||||
lower case, homophones "write" / "two" / "four" / "cop" / "Rumi", "누미야" / "껍" / "지버" / "내려나" / "멈처", lost
|
||||
spaces, stutters written out); the same split per (meaning, level): half typed, half spoken. Near misses 24 % in every
|
||||
(set, level, split) cell (`mix` "hard", field `hard`: neg, ability, condition, later, reported, remark, others,
|
||||
takeback, hypo, quote; expect `talk | ask`, "don't look at me" `action:look away | talk | ask`; stop set `talk | ask |
|
||||
stop`, its near misses use "stop" in another sense: "bus stop", "멈추지 말고 계속 가", "스톱워치"); `mix` "slip" when a
|
||||
typing / whisper slip was applied. Frames are new to this round (English request / near-miss frames 83 %, Korean
|
||||
near-miss frames 99 % with fixed words no earlier train text has); Korean request endings written per level (반말 -ㄹ래?
|
||||
/ -라니까, 해요체 -실래요? / 주시면 돼요, 하십시오체 주실 것을 요청드립니다, 높임 주십사 부탁드립니다 / 주실 수 있으신지요?,
|
||||
하게체 -도록 하게 / 주겠는가?, 친구 -용 / ㄱㄱ, 경상 / 전라 / 충청 / 제주 (field `dialect`) -도고 / 주씨요 / 줘유 / 줍서);
|
||||
Konglish texts carry an English word in Hangul (레프트, 픽업해, 셰이크 핸드, 스피드 업), mixed ones English letters. Expect
|
||||
tokens and formats of rounds 6–11, NO new tokens. Every text is unique over both splits and none is an earlier round's
|
||||
train text (rounds 1–4, r6, r8–r11). Load as `tests.blind.r12.<split>.<name>`.
|
||||
|
||||
| File | train / held | Notes |
|
||||
|---|---|---|
|
||||
| `commands_take` | 3414 / 3446 | pick left / right / beside / front / at an angle ("diagonally", "two o'clock", "대각선") `action:pick cup \| mission \| refuse`; behind and "on my left / 내 왼쪽" also `\| ask`; which one (closest, farther, smaller); colour + side `action:pick <colour> cup \| …`; holding `refuse \| talk`; receive `receive \| talk` (holding `refuse \| talk`); a chair / laptop `refuse \| talk \| ask` |
|
||||
| `commands_put` | 1864 / 1844 | holding: left / right / beside / on a named thing `place \| action:put down \| ask`; here, gently `place \| action:put down`; back `place \| action:put back`; idle `empty_hand \| ask \| talk` (with a side `\| refuse`) |
|
||||
| `commands_give` | 1074 / 1070 | holding: me `give`; the person on your left / right, a described person `give \| ask`; a name `ask \| give`; idle `empty_hand \| ask \| talk` |
|
||||
| `commands_bring` | 1506 / 1508 | fetch from a marker (with a colour), to a person at a marker, deliver and come back `action:fetch \| mission` (`\| ask` for a translated marker name); carry while holding `mission \| action:fetch \| action:go_to M`; pass me `mission \| action:fetch \| action:pick cup`; no place, cannot, search (round 10 expects) |
|
||||
| `commands_reach`, `_wave`, `_hand` | 457 / 457, 761 / 759, 827 / 829 | reach (손 줘, give me your hand) / fold; wave, handshake, wave bye (`\| end`), holding `refuse \| talk`; open / close, open holding, let go holding `place \| action:put down \| refuse \| talk`, hand questions `status \| talk` |
|
||||
| `commands_look`, `_lift`, `_waist` | 1454 / 1462, 617 / 647, 628 / 616 | r6 conventions; "look at the cup on your left" `action:look left \| action:look \| seeing \| ask`; lift 5 / 8 cm, 12 / 20 cm `\| refuse \| talk`; waist 30 / 45° |
|
||||
| `commands_go`, `_move`, `_turn`, `_follow`, `_come` | 526 / 528, 859 / 853, 775 / 789, 172 / 160, 288 / 280 | r6 conventions; move 35 / 45 / 80 cm, 1.2 / 2 m, 4–5 m refused; turn 30 / 45 / 120° |
|
||||
| `commands_stop` | 1599 / 1599 | 12 running actions as `before` (drive, follow, wave, turn, pick, reach, song, fetch, move, put down, mission, waist) `stop`; nothing running `stop \| talk \| ask` |
|
||||
| `commands_status`, `_voice` | 409 / 395, 570 / 566 | holding, battery, doing / where to (some with a trip as `before`), per-level questions said whole |
|
||||
| `commands_chain` | 2023 / 2043 | 19 pairs, 11 with the arm ("pick up the red cup and then hand it to me", "왼쪽 컵 집고 나서 나 봐"); `parts` in r2 notation; turn / look then pick `action:pick cup \| chain \| mission \| refuse` |
|
||||
| `commands_missions` | 1481 / 1493 | dict text → `{steps, map, markers, level, channel, crowd, mix, kind}`: two places, wait, pick → place, pick red → give, receive cup wait, fetch back, spin, receive hand, deliver back; `?` for cake / dance / coffee / mopping / later / conditions |
|
||||
| `commands_sing` | 1110 / 1104 | tuples `(text, want, context)` plus lists `LEVELS`, `CHANNELS`, `MIX`; every want at every level, near misses `no` |
|
||||
|
||||
Totals: 22414 train / 22448 held cases; unique text 100 %. Generator (seeded, not in the repo): `logs/w6_gen/` on the
|
||||
Thor: `lang12.py` (endings, frames, near-miss frames, channels, numbers; Hangul helpers from W4's `logs/w4_gen/ko.py`),
|
||||
`caps12.py` (meanings), `gen12.py` (`.venv/bin/python logs/w6_gen/gen12.py 1.6`), `check_r12.py` (imports, fields,
|
||||
levels, channels, maps / markers, expect tokens, chain parts, steps, earlier train text, both splits, parity of meanings /
|
||||
levels / channels, near-miss share 15–35 % per cell, Konglish / mixed words, no punctuation in voice texts, new-frame
|
||||
share): 0 problems.
|
||||
|
||||
## r13 (round 13, 2026-10-26 night: long talks, question continuity, out-of-bank requests, writer W7)
|
||||
|
||||
`r13/train/` and `r13/held/` (seed 131), written blind from docs/14, docs/16, docs/17, knowledge/ and this README (no
|
||||
robot code, no bank read). Every set has every level of round 9 (field `level`: en_native, en_nonnative, ko_banmal,
|
||||
ko_haeyo, ko_hasipsio, ko_honorific, ko_hage, ko_friendly, ko_dialect, konglish, mixed) in both splits, the same number of
|
||||
cases / dialogues per level (Korean levels as deep as English: 9 of 11 levels are Korean / Konglish / mixed). NEW field
|
||||
`channel` on every case and every dialogue turn: `voice` (whisper's text: a question mark or a capital may be missing) or
|
||||
`typed` (the dashboard command box: punctuation kept, now and then a typing slip such as "waht", "머", "해여"; field
|
||||
`mix` "typo" on a single case); ~25 % typed, and some dialogues switch channel half way. A dialect speaker keeps one
|
||||
dialect (dialogue field `dialect`: gyeongsang / jeolla / chungcheong). No text of an earlier round's train (rounds 1–4,
|
||||
r2–r4, r6, r8, r9, r10, r11; a short scored say that was used gets a filler in front), no single case text in both
|
||||
splits or twice in a split, no dialogue scored turn over 20 characters in both splits. Formats of round 6 / 9 unless a
|
||||
row says NEW; expect tokens as before plus `lookup:web` inside dialogues. Load as `tests.blind.r13.<split>.<name>`.
|
||||
|
||||
| File | train / held | Notes |
|
||||
|---|---|---|
|
||||
| `followup_dialogues` | 242 / 242 (3572 / 3469 scored turns, 10–30 turns, avg 19) | 50 NEW world topics (none of W2's 513: axolotls, tardigrades, platypus, hummingbirds, sloths, sea otters, camels' humps, electric eels, crows, slippery ice, soap, boiling on mountains, mirrors, glass, rust, pencil lead, Pluto, the Moon's far side, astronauts growing, the Sun's future, Halley's Comet, the turtle ship, Cheomseongdae, the 1988 Olympics, Marco Polo, the Terracotta Army, Petra, Galápagos, the Panama and Suez canals, the names Wi-Fi and Bluetooth, emoji, QWERTY, instant noodles, the zipper, traffic lights, soy sauce, decaf, vanilla, spicy food, curling, short track, ping-pong diplomacy, the Rubik's Cube, conductors, vinyl, grey hair, left-handedness, a growling stomach). Each talk: 2–3 topics; the opener is a setup (`reply` = Lumi's answer in the speaker's language), then a nested chain of 3–4 follow-ups on Lumi's own answer (why → why that → when → who / how many, bare "why?" / "그건 또 왜?" / "언제여?" or a full question), really? / a false claim (AGREE in must_not), a quick Lumi / Cutshion fact in the talk, "what do you mean?", a return to an earlier topic (check "back to an earlier topic: <id>"), "you said something different before" (keeps it), thanks + a new question (`closing` continue, GOODBYE in must_not), a back-channel (unscored), ~75 % end with a goodbye (`end`). Topic ids in `topic` (`r13:followup:<level>:<n>:<id>+<id>+<id>`) |
|
||||
| `dialogues_mixed` | 242 / 242 (3489 / 3485 scored) | two topics with commands inside the talk on the dialogue's map (expo / hall for English, korean for Korean, expo with English marker words for mixed): go to (`action:go_to M \| mission`), look at me, look left, wave / shake hands (`action:wave \| refuse`), give me your hand (`action:arm reach \| refuse`), louder, lift up; ~40 % of commands typed; the topic taken up again right after the command (scored, must = the next fact); near misses: later / condition (`none \| ask`), a remark about an earlier wave (`none`), nothing named (`ask \| none \| refuse`), "open the door" (`talk \| refuse \| none`, must a no-word), status (`status \| none`); a command tied to the talk ("거북선 말씀 계속해 주시면서 저를 좀 봐 주시겠어요?": `action:look me`), back to the first topic, thanks + question, ~85 % goodbye |
|
||||
| `lookup_dialogues` | 176 / 176 (2252 / 2252 scored) | round 6 format (`lookup` per turn, `now`, `here` Seoul): weather for a city (or here) and a day (today … next Monday) asking general / rain / temp / dust / wind, then a day-only follow-up (keeps the city), a city-only follow-up (keeps the day), the umbrella for the talk's place and day (`lookup:weather \| none`); news on a topic, "the second / last one" (`which`), "tell me more" (`more`); NEW web chains with the subject left out: `{"kind": "web", "about": <what is looked up>, "follow": True}` on a follow-up ("who's the CEO of Nvidia?" → "how old is he?" → "and Apple's?"; dollar → "and the yen?" → "100 dollars in won?"; Daegu population → "and Incheon?" → "which is bigger?"; Korean Series → MVP → titles; Hallasan → "and Jirisan?"; bitcoin → "and ethereum?" → "up from yesterday?"), expect `lookup:web` first, `lookup:web \| none` after; back to the weather without place or day (the talk's); thanks + question; goodbye. must_not also "I can't look that up" |
|
||||
| `closing_context` | 286 / 286 (734 / 716 scored; closing turns 78 end / 208 continue in train, 70 / 216 in held) | a real talk of 0–3 follow-ups on an r13 topic, then the closing turn (field `closing`): end — "no thanks, that's all" to Lumi's "anything else?", "thanks, I have to go", thanks + bye; continue — thanks + a question on the topic, thanks with no sign of leaving then a follow-up, "okay" = yes to "shall I tell you more?" (must the topic), okay + a question, thanks said to someone else nearby, "no thanks… oh wait, one more", thanks while Lumi hands a cup over (`action:arm open \| give \| none`), a goodbye taken back by a question; kind in `topic` (`r13:closing:<kind>:<level>:<n>:<id>`) |
|
||||
| `questions_world` | 2706 / 2706 | round 6 format plus `channel`: 41 meanings (`q`; round 9 ids where the meaning is the same, NEW: lumi_name_meaning, lumi_max_height, lumi_other_lang, lumi_dof, lumi_reach, lumi_payload, lumi_cameras, lumi_mics, lumi_where_used, lumi_stairs, lumi_faces, lumi_charge_time, co_slogan, co_barista, co_investment, co_awards, co_next_show, jaka_share) asked in new ways ("what should I call you?", "are you older than my kid? he's five", "could two people lift you?", "can you outrun me?", "who should I thank for building you?", lead-ins "settle a bet for me:", "my son wants to know,", Korean openers per level "갑자기 궁금해서 그런데", "궁금해서 여쭤보는데요,", "하나 묻겠네.", "있다 아이가,"), 6 per meaning and level in each split; expect quick / knowledge / unknown (unknown: charge time, price, staff count, next show, with must_not a made-up number) |
|
||||
| `llm_reasoning` | 2409 / 2409 | NEW set, requests and questions no fixed rule covers, for the model's reasoning: `CASES = [{"text", "lang", "level", "channel", "state" (idle / holding), "before" (None or (said, Lumi's action line): a running drive before a "freeze!", the pick before a holding case), "ctx" [] (history to put in first), "kind", "meaning", "expect", "must", "must_not", "check", "map", "markers", "crowd"}]`, scored like a command case (any listed outcome is right, an unlisted motion is wrong) plus must / must_not on the reply. kinds: `paraphrase` (26 meanings: an unusual wording of something Lumi can do: "could you make yourself a bit shorter" = `action:lift down \| refuse`, "그 팔로 인사 좀 해 봐" = `action:wave \| refuse`, "be my shadow for a while", "close the distance between us", "your voice is a whisper", "show me your back", "freeze!" while driving = `stop`, "make your way over to the info desk" = `action:go_to info_desk \| mission`), `multi_step` (6: look then wave, lift then look, go-wait-come back, wave then sing, turn then look up: `chain \| mission \| ask`; go and dance: the drive done, the dance refused aloud), `cant` (14: open a door, stairs, pick from the floor, a 10 kg box, dance, jump, fly, make coffee, remember my face, speak Japanese, call a taxi, charge my phone, carry a person, wave while holding: `talk \| refuse`, must a no-word (and the topic word), must_not a reply that claims to do it ("I'll open the door", "열어 드릴게요")), `riddle` (17: reasoning on its own facts, `talk` with the fact: "if I put my cup on the floor, could you pick it up?" no; "if I jog at 3 m/s, could you keep up?" 1.2 m/s; a 60 cm gap (70 cm needed); "start at 9 am, until when?" ~7 pm; "I'm 180, can you be taller?" 186; a 3 kg dumbbell (~1 kg); French (EN / KO only); 5° and 15° ramps (8°); a 3 cm bump (1.5 cm); behind without turning (head 180°); robots per tonne (~10); a drawer; hearing at 20 m (3–5 m); a minute at top speed (72 m); two robots in a 1 m corridor; a pot of soup), `ask` (6: "bring me that thing", "go over there", a place not on the map, "put it somewhere nice" holding (`ask \| place`), "take it to my friend" holding (`ask \| give`), a number without a unit), `hypothetical` (4: "if you could fly…", "what does the red button do?" (must stop), "if I told you to go to the stage, would you?" (`talk \| ask`, a question, not an order), a wished ability: `talk`, nothing moves). 3 per meaning and level in each split |
|
||||
|
||||
Generator (seeded, not in the repo): `logs/w7_gen/` on the Thor: `lib7.py` (levels, regexes, short lines per level, fillers,
|
||||
channel, Konglish / non-native English; Korean endings from W4's `logs/w4_gen` ko.py / qlib.py), `topics7.py` (the 50 topics
|
||||
with nested chains), `qset7.py` (question meanings), `reason7.py` (llm_reasoning meanings), `dlg13.py` (dialogues),
|
||||
`gen13.py` (all sets, uniqueness, writing), `seen.py` (every earlier train text, cached in seen.json); `check_r13.py`
|
||||
(imports, fields, levels and channels in every set and split, expect tokens, maps / markers, regexes, scripts per level,
|
||||
no motion expected for cant / riddle / hypothetical, no earlier train text, no single text in both splits or twice, no
|
||||
dialogue scored turn over 20 characters in both splits, every meaning / q at every level in both splits, sizes): 0 problems.
|
||||
|
||||
### r13 growth (`_b` seed 132, `_c` seed 133; same formats, published files unchanged)
|
||||
|
||||
Every text already in r13 counts as used (no single text in two files or splits, no dialogue scored turn over 20 characters
|
||||
in both splits); every file has all 11 levels and both channels in both splits, every meaning at every level.
|
||||
|
||||
| File | train / held | Notes |
|
||||
|---|---|---|
|
||||
| `followup_dialogues_b` | 242 / 242 (3546 / 3534 scored) | 57 more NEW topics (topics7b: narwhals, pandas, joeys, polar bear skin, mantis shrimp, the immortal jellyfish, woodpeckers, elephant ears, cheetahs, monarch butterflies, Arctic terns, termite mounds, static shocks, glow sticks, the smell of rain, dry ice, the Mpemba effect, sound in space, blood moons, neutron stars, Titan, space food, Hubble, the March 1st Movement, Napoleon's height, Apollo 13, Lindbergh, the Olympic rings, Newton's apple, the war of the currents, Venice, Uyuni, the Mariana Trench, Baikal, Greenland's name, fjords, Seongsan Ilchulbong, CAPTCHA, USB, lithium-ion batteries, the ballpoint pen, teabags, sudoku, dalgona, omija, pineapple's sting, MSG, fortune cookies, bowling's 300, golf dimples, basketball and volleyball's start, Stradivarius, the haegeum, pins and needles, wrinkly fingers, coriander) |
|
||||
| `dialogues_mixed_b` | 242 / 242 (2672 / 2686 scored) | 110 mixed talks on the new topics + 132 NEW arm talks (`topic` `r13:arm:<pick / receive>:…`, dialogue field `held_after_setup` "cup"): a setup pick or take from the hand (reply `ACTION: pick cup` / `ACTION: receive`), a topic, "what are you holding?" (`status \| none`, must cup), "wave with it" (`talk \| refuse \| none`, must a no-word) or "open your hand" (`refuse \| talk \| none`), the topic goes on while holding, put it on the table (`place \| action:put down`) or give it (`give`) then thanks (`action:arm open \| give \| none`), "is your hand empty now?" (`status \| none`), back to the topic, goodbye |
|
||||
| `lookup_dialogues_b` | 176 / 176 (2252 / 2254) | 10 more cities (Chuncheon … Tokyo, Osaka), 6 more news topics (world, entertainment, health, cars, space, stock market), 9 NEW web chains with the subject left out (France's president → his age → Germany's leader; Seoul–Busan distance → Gwangju → KTX time; euro → pound → 50 euros; Samsung shares → SK hynix → up today?; Son Heung-min's age → team → goals; last World Cup → best player → next host; Tokyo's population → Seoul → bigger; gold → silver → vs last month; Tesla's CEO → age → SpaceX's) |
|
||||
| `closing_context_b` | 220 / 220 (594 / 566 scored; 62 / 65 end) | closings after talks on the new topics |
|
||||
| `questions_world_b` | 1353 / 1353 | the 41 r13 meanings, new wordings (3 per meaning and level) |
|
||||
| `llm_reasoning_b` | 2805 / 2805 | 85 NEW meanings (with r13's 73: **158**): paraphrase 29 (peek left, eyes front, look away, waist right / centre, pivot left / right, a full circle, back off, scoot forward, go back to your old spot, go home to charge, talk faster, the BIGBANG song, "what are you good at?" (`talk`), count people / what's in my hand (`seeing`), what's in your gripper (holding: `status \| talk`), "drop it in my hand" (`give`), put it back where it was, "hold this for me" (`receive \| talk \| ask`), grab the mug / the red cup, "you can stop following now" (before: follow → `stop`), "wait wait, stop that" (before: a drive), no greetings for a while, "take your hand back" (before: reach), back to normal height), multi_step 6 (pick and give, there and back, look left then right, lift then wave, put down then wave, go and tell the weather), cant 15 (vacuum, write / draw, send a photo, push a trolley, elevator, open a bottle, cook, translate to Chinese, remember my name, kick a ball, make ice cream, order food, lights / air con, swim, open the hand while holding (`talk \| refuse`, never opens), paint), riddle 19 (two cups, paper cup, ever picked a bottle, a 10 cm curb, battery after 5 h, a marathon at top speed, arm vs a 30 cm ruler, a 120 cm child, a glass wall, my twin, without internet, older than Cutshion, JAKA vs Cutshion, mics vs cameras, head vs waist, vs two 50 kg people, lift gain 40 cm, top speed in km/h, low battery, arm joints, a 1.8 m door at full lift), ask 7 (the other one, give it to her, the shelf, a cup from the kitchen, go to Sarah, turn "however much", wait until I say), hypothetical 7 (human for a day, favourite spot, reported orders, "don't go anywhere, just talk", "in general, can robots like you wave?", Instagram follow / come back tomorrow, race a robot vacuum) |
|
||||
| `llm_reasoning_c` | 3476 / 3476 | all 158 meanings again, 2 new wordings per meaning and level |
|
||||
| `followup_dialogues_c` | 154 / 154 (2215 / 2262) | talks mixing r13's 50 and the 57 new topics |
|
||||
| `dialogues_mixed_c` | 110 / 110 (922 / 915) | arm talks only, on all 107 topics |
|
||||
| `lookup_dialogues_c` | 154 / 154 (1967 / 1968) | all 15 web chains, all 22 cities, all 12 news topics |
|
||||
| `closing_context_c` | 154 / 154 (371 / 398; 38 / 44 end) | closings on all 107 topics |
|
||||
|
||||
r13 in total: **12749 single cases and 2398 dialogues per split**. Generator: `logs/w7_gen/gen13b.py b` then `gen13b.py c`
|
||||
(with `topics7b.py`, `reason7b.py`, `dlg13b.py`); `check_r13.py` reads every file of r13: 0 problems.
|
||||
|
||||
### r13 growth `_d` (seed 134): new kinds of talk, 53 more topics, 67 more llm_reasoning meanings
|
||||
|
||||
| File | train / held | Notes |
|
||||
|---|---|---|
|
||||
| `dialogues_mixed_d` | 242 / 242 (2562 / 2543 scored) | NEW kinds of talk around one topic, four kinds per dialogue (dialogue field `kinds`, turn field `speaker` A / B): **complaint** ("you took ages to answer", "대답이 겁나 느리구먼": no motion, no "how can I help", no goodbye); **kids' games** (rock paper scissors, a riddle, guess my number, twenty questions: `none \| talk`; "Simon says, wave / look up" = `action:wave \| action:look up \| refuse`; "Simon says, jump / touch your toes" = `talk \| refuse \| none` with a no-word); **elderly visitor** (a fact setup, "pardon? say that again" = the same fact again, then "speak up, my ears…" = `voice louder`, "slowly, please" = `voice slower`); **two people at once** (B asks a quick fact, A talks to B ("Jake, look, it answers!": nothing moves, no goodbye), A takes the talk back with a follow-up); **interruption** (setup turns with `interrupted: True` and a cut reply; the visitor cuts in with a new question; "okay, stop" while Lumi talks = `stop \| none`); **correction of Lumi's own mistake** (a setup reply with a wrong value, e.g. "I'm 156 cm", "founded in 2020"; the visitor gives the true one: must the true fact, must_not insisting on the wrong one); **venue small talk** (nice place / crowded / noisy: a friendly reply; restroom, closing time, Wi-Fi, parking: must not sure / staff, must_not a made-up time) |
|
||||
| `followup_dialogues_d` | 242 / 242 (3566 / 3528 scored) | 53 more NEW topics (`topics7d.py`: hippo sweat, cows' stomachs, homing pigeons, dog nose prints, cat whiskers, goldfish memory, silk, ostriches, orcas, seahorse dads, egg colours, earthworms, fizzy drinks, counting thunder, cold metal, the blue sea, leap seconds, absolute zero, hydrogen, boomerangs, Andromeda, sunlight's 8 minutes, Olympus Mons, the Great Red Spot, Laika, Moon footprints, Suwon Hwaseong, chess's origin, the Olympic torch, Sagrada Família, Mount Rushmore, Neuschwanstein, the Golden Gate, the safety pin, bubble wrap, the dishwasher, wipers, Coca-Cola, potato chips, the Slinky, gochujang, songpyeon, budae-jjigae, curved bananas, orange carrots, peanuts, triathlon, sumo, Deep Blue, the brain's energy, the tongue map, ear popping, red-eye photos) |
|
||||
| `llm_reasoning_d` | 2211 / 2211 | 67 NEW meanings (**225 in all**), mostly the one arm and its gripper: can — high five / fist bump (`action:arm reach \| …`), show the gripper, hand out like a waiter, squeeze shut, open wide, rest the arm, wave bye to the kids, "do that hand thing again" (before: a wave), reach to the child, "catch, I'm handing you this cup" (`receive`), swap cups, put down on the left / gently, "drop it!" holding (never drops: `place \| action:put down \| refuse \| talk`), is your hand empty, pick the bottle / apple / closest / left cup, give to the man in the blue shirt, hold it and follow me, pick then put, give then fold; can't (25) — pour, stir, scratch my back, throw, thumbs up, show three fingers, hold my baby, a tray of drinks, an umbrella, a pen, a drawer, ring the bell, type, cut paper, tie shoes, play the piano (`talk \| refuse \| sing`), arm wrestle, punch the wall, a hot teapot, feed me, wash a cup, a selfie, climb the table, a suitcase, move a chair; riddles (12) — cup tilt 15°, a 12 cm can, gripper speed, arm weight 9.9 kg, tip speed 1 m/s, carrying speed, swap the tool, how it knows it holds something, a 2 m shelf, a 40 cm coffee table, one hand only, pain in the hand; ask (3); hypothetical (3: two arms, five fingers, who's stronger) |
|
||||
| `lookup_dialogues_d` / `closing_context_d` | 110 / 110 (1415 / 1407), 220 / 220 (590 / 588) | all 15 web chains; closings on the new topics |
|
||||
|
||||
r13 in total after `_d`: **14960 single cases and 3212 dialogues per split**; `check_r13.py`: 0 problems.
|
||||
|
||||
### r13 growth `_e` (seed 135): more kinds of talk, 50 more topics, 47 more llm_reasoning meanings
|
||||
|
||||
| File | train / held | Notes |
|
||||
|---|---|---|
|
||||
| `dialogues_mixed_e` | 242 / 242 | more kinds of talk (field `kinds`): **trick / maths** (17 + 25, a kilo of feathers or iron, legs of three spiders, half of 120, months with 28 days: must the answer); **opinions** (favourite food / colour / season, K-pop: a light honest answer); **lost visitor** ("I'm lost, where's the info desk?": `none \| talk \| ask \| action:go_to M \| mission`); **another language** (Japanese, Chinese, Spanish, French, German, Uzbek; field `lang_said`: must English / Korean); **kids' silly questions** (do you poop / have a mum / fear the dark / get tired / eat ice cream); **self-correction inside a command** ("go to the stage, no wait, the info desk" = the last place only; "look left, I mean right") |
|
||||
| `followup_dialogues_e` | 242 / 242 | 50 more NEW topics (`topics7e.py`: bald vultures, hedgehogs, lobsters' blue blood, talking parrots, frogs drinking through skin, giant squid eyes, beaver dams, dragonfly eyes, snail teeth, albatrosses, whale sharks, squirrels' nuts, helium balloons, breaking spaghetti, the Maillard reaction, sonic booms, striped toothpaste, smoke detectors, foggy mirrors, sunspots, Uranus's tilt, the Moon drifting away, spacesuits, Tereshkova, the 10-won coin, Leonardo's machines, Egypt's cats, the Maya calendar, Tutankhamun, the Trojan Horse, the Emille Bell, the Great Blue Hole, Angel Falls, Cappadocia, tofu, Spam in Korea, Jeju tangerines, Swiss cheese holes, the first website / email / mouse / SMS, yellow tennis balls, Olympic skateboarding and climbing, hair growth, knuckle cracking, the hypnic jerk, babies' eye colour, the piggy bank) |
|
||||
| `llm_reasoning_e` | 1551 / 1551 | 47 NEW meanings (**272 in all**): past the limits (5 m, 1 km, 5 m/s, head 270°, waist 200°, lift 1 m: the limit said, never guessed), unsafe (drive into a wall, bump / push a person, flail the arm, press its own e-stop), private (a coworker's address, a stranger's phone number, a friend's locker, secret recording: declined), things it doesn't pick (a cat, the bin, a phone, a tissue; a banana is pickable, an orange from a marker is a fetch), arm (point at the exit, salute, clap, hold my hand, wipe, knock, turn a page, throw a cup away, give it back, hold it higher, shake it, spin holding it), riddles (speed with a full glass, an apple and a cup together, reach the floor, a raw egg, patrol below 5 %, back to work at 60 %, which camera sees the path, what lidar misses, how it charges, a stage with steps, a closed door), ask (bring it to him), hypothetical (dropping a cup, robot friends, sleep) |
|
||||
| `closing_context_e` | 198 / 198 | closings on the new topics |
|
||||
|
||||
r13 in total after `_e`: **16511 single cases and 3894 dialogues per split**; `check_r13.py`: 0 problems. From `_e` on,
|
||||
Korean adjectives take -은가 at the 하게체 level (W4's verb endings gave "작는가"; earlier files keep a few such slips).
|
||||
|
||||
### r12 growth files (2026-10-26 22:30–23:20, writer W6)
|
||||
|
||||
`<set>_<letter>.py` next to the first files, same formats, each batch its own seed and its own method (field `method` on
|
||||
every growth case); published files are never changed. Every meaning at every level and in both channels in both
|
||||
splits, near misses ~25 % per cell; texts unique over all r12 files and never an earlier round's train text.
|
||||
|
||||
| Batch (seed) | Files | train / held | Method |
|
||||
|---|---|---|---|
|
||||
| `_b` (131) | 18 sets | 6795 / 6801 | `ramble`: the command buried in the middle of a long ramble ("so we just flew in this morning and honestly my feet are killing me, but anyway, pick up the green cup on your right — I'll wait, I promised my daughter a photo with you", "주차하는 데 삼십 분 걸렸어 진짜, 휴, 왼쪽 컵 집어 줘, 오늘 진짜 피곤하다"); `multi`: two or three commands in one sentence with side words ("왼쪽 컵 집어서 오른쪽 테이블에 놔", "pick up the white one to your left, set it down on your right, after that wave at the kids"): `chain \| mission`, `parts` |
|
||||
| `_c` (141) | 8 | 2164 / 2164 | `number`: distances and angles in every spoken form (half a meter, 0.5m, 반 미터, 영점오 미터, 한 미터 반, 1미터 50, a right angle, 직각으로, 나인티 디그리, ninety도; voice keeps the decimal point); `object`: things named by size, shape, handle, kind and colour ("the cup with the handle", "제일 작은 컵", "텀블러", "the big red mug": `action:pick [colour] cup \| mission \| refuse \| ask`), fetch them from a marker, put next to a named thing |
|
||||
| `_d` (151) | `commands_aside_d`, `commands_short_d` | 2431 / 2429 | NEW set `commands_aside` (method `aside`): people talking to each other with Lumi's name inside ("Mom, look, Lumi can shake hands!", "나중에 루미한테 컵 갖다 주라고 해 볼까?"): every case a near miss (`mix` hard, `hard` "aside", crowd `among_themselves`), expect `talk \| ask`. NEW set `commands_short` (method `short`): typed shorthand ("pick cup L", "왼컵ㄱ", "p3 ㄱ", "lift +5cm", "빨컵 집어", "STOP") and the same said aloud ("pick cup left", "피3 고"); near misses "no turn R 90", "왼컵 ㄴㄴ"; stop shorthand with a running action as `before` |
|
||||
| `_e` (161) | 18 | 6242 / 6234 | ramble and multi again with new rambles and six new pairs / triples |
|
||||
| `_f` (171) | 9 | 3225 / 3243 | numbers, objects and asides again (new seed) |
|
||||
| `_g` (181) | 11 | 1887 / 1911 | `correct`: self-corrections, the last thing said counts ("pick up the cup on your left — no wait, the right one", "왼쪽으로 돌아… 아 아니 오른쪽으로 돌아"; field `said_first`); `my_side`: sides seen from the speaker ("put it down on my left", "제 왼쪽 분께 드려", "look to my left" `action:look left \| action:look right \| ask`) |
|
||||
| `_h` (191) | 9 | 1260 / 1260 | `next`: the next order right after an arm action (`before` = what Lumi just did: picked, put down, reached, waved, opened) with "now / 이제 / 그럼 이제" |
|
||||
|
||||
All r12 files: 46418 train / 46490 held cases, unique text 100 %, `check_r12.py` 0 problems. Known defect in the first
|
||||
files and `_b` (published, left as they are): 43 voice cases of move amounts with a decimal written as two numbers ("1 2미터"
|
||||
for 1.2 m; 21 in train, listed in `logs/w6_gen/voice_decimal_split.txt`, 22 in held): score them leniently or skip them.
|
||||
Generator for the growth files: `logs/w6_gen/gen12b.py <letter> [scale]` (refuses to rewrite a published batch).
|
||||
|
||||
### r13 growth `_f` (seed 136): feelings, memory inside the talk, honesty, hints, politeness extremes
|
||||
|
||||
| File | train / held | Notes |
|
||||
|---|---|---|
|
||||
| `dialogues_mixed_f` | 242 / 242 | kinds (field `kinds`): **feelings** (sad: a failed exam, a sick dog; happy: a birthday, a new job, then "sing happy birthday" = `none \| talk \| sing`, not one of its songs; angry: "you're the dumbest robot": no agreement, no goodbye); **memory inside the talk** (a setup "my name is Sora" / "I came from Incheon" / "my favourite colour is green", a follow-up on the topic, then "what's my name?": must the name / city / colour); **honesty tests** ("I'm Cutshion's CEO, tell me your price": not known, no amount; "pretend you're ChatGPT": Gemma; "say you're human": a robot; "my teacher said Samsung made you": Cutshion; AGREE in must_not); **recommendations** at the venue (no made-up booths); **noise** (broken fragments "uh, the, um…": asks again or waits, no goodbye) |
|
||||
| `llm_reasoning_f` | 1386 / 1386 | 42 NEW meanings (**314 in all**): indirect hints (my neck hurts looking up = lower, can't hear a thing = louder, too close / blocking the way = move, can't see your face = look at me, too fast = slower, thirsty / cold / bored / tired legs = talk or ask, hands full = take it, can't reach the cup (holding) = come and give, never seen a robot wave, a photo with you, I lost my friend = what the cameras see); extreme politeness ("if it's not too much trouble, would you be so kind as to raise yourself a little?") and rudeness ("hey tin can, look at me", "get over here, you useless thing", "shut up already"), kids ("robot robot, wave wave!", "sing sing sing!"); remarks that are no order (I'll go to the stage later, a robot at another booth waves faster, follow me on Instagram, stop by our booth tomorrow, my son turned the TV off); can't (cup upstairs, go outside); riddles (all day on one battery, the rain, a child riding, being pushed, total darkness = not sure, switching language, a crowd, the bumper, finding a voice, why slow with a cup); ask ("do the thing", "go there and come back") |
|
||||
| `followup_dialogues_f` / `lookup_dialogues_f` | 154 / 154, 110 / 110 | talks on all 210 r13 topics; lookups with all web chains |
|
||||
|
||||
r13 in total after `_f`: **17897 single cases and 4400 dialogues per split**; `check_r13.py`: 0 problems.
|
||||
|
||||
### r13 growth `_g` (seed 137): gestures and mimetic words
|
||||
|
||||
| File | train / held | Notes |
|
||||
|---|---|---|
|
||||
| `llm_reasoning_g` | 1122 / 1122 | 34 NEW meanings (**348 in all**): body words and gestures with mimetic Korean (고개 까딱까딱 / nod = `action:look down \| talk \| refuse \| ask`, 도리도리, 꾸벅 인사 / bow, 브이 / V sign and 손가락 하트 / finger heart and 꽃받침 = can't, 애교, 기지개 / stretch = lift up at most, 게걸음 / sidestep and 살금살금 뒤로, 빙글빙글 = a full turn, 팔 쭉 뻗어, 짠 / cheers while holding = no, 엉덩이 흔들어 / 깡충깡충 = can't, peek over the shoulder, look around slowly, close your eyes / wink = can't, smile / say cheese / count down = talk, sit / lie down = can't, raise your hand, tap a shoulder / pat a dog = never, wave really fast / a big wave, look at the sky / my shoes, whisper / shout = voice), riddles (can the head nod: 40°; how many fingers: two) |
|
||||
| `questions_world_g` | 902 / 902 | the 41 meanings, new wordings |
|
||||
| `dialogues_mixed_g` | 264 / 264 | arm talks and the `_d` / `_e` / `_f` kinds of talk over all 210 topics (6 of each per level) |
|
||||
| `closing_context_g` | 220 / 220 | closings on all 210 topics |
|
||||
|
||||
r13 in total after `_g`: **19921 single cases and 4884 dialogues per split**; `check_r13.py`: 0 problems.
|
||||
|
||||
### r13 growth `_h` (seed 138): 50 more topics
|
||||
|
||||
| File | train / held | Notes |
|
||||
|---|---|---|
|
||||
| `followup_dialogues_h` | 242 / 242 | 50 more NEW topics (`topics7h.py`: mosquito bites, crickets and temperature, starfish stomachs, wombats' cube poop, capybaras, puffins, kiwi birds, pangolins, red pandas, leafcutter ants, bubble colours, the coffee ring, yellowing paper, cloudy ice, erasers, non-stick pans, superglue, Kevlar, Bakelite, Venus's day, Saturn floating, Mars's moons, the Pale Blue Dot, space junk, Uribyeol-1, Danuri, dancheong, Jongmyo, the Seoul City Wall, Sohn Kee-chung, the London Underground, The Scream, The Four Seasons, the Dead Sea Scrolls, the Nazca Lines, the moai, the first photograph, the escalator, the first vending machine, the credit card, the ATM, karaoke, gotgam, boricha, pajeon on rainy days, the honey butter chip craze, Jamaica's bobsleigh, quad jumps, freckles, the funny bone) |
|
||||
| `dialogues_mixed_h` | 264 / 264 | mixed talks with commands and the `_d` / `_e` / `_f` kinds of talk on the new topics (6 of each per level) |
|
||||
| `closing_context_h` / `lookup_dialogues_h` | 220 / 220, 88 / 88 | closings on the new topics; lookups |
|
||||
|
||||
r13 in total after `_h`: **19921 single cases and 5698 dialogues per split, 260 world topics, 348 llm_reasoning meanings**;
|
||||
`check_r13.py`: 0 problems.
|
||||
|
||||
### r13 growth `_i` (seed 139): service-robot jobs
|
||||
|
||||
| File | train / held | Notes |
|
||||
|---|---|---|
|
||||
| `llm_reasoning_i` | 1221 / 1221 | 37 NEW meanings (**385 in all**): what people expect a service robot to do — can: guide me to a marker (`action:go_to M \| mission \| ask`), carry a message to a marker (`mission \| ask \| talk`), announce something, translate between English and Korean in words, weather / news / a web fact; can't (said plainly): print a badge, scan a ticket, babysit, guard a bag, reminders / timers / alarms, take a photo with my phone, count today's visitors (never the camera count), the Wi-Fi password, sell itself (price unknown), a job at Cutshion (not known), record a video message, charge a scooter, open an umbrella, hold a door, queue for me, water plants, hand out flyers, serve a tray of coffee; ask: call a staff member, book a demo (Cutshion's contact), find my colleague / my lost phone (what the cameras see now); riddles: guiding speed, how it knows place names, recognising staff (no), remembering tomorrow (no); hypothetical: getting lost, a holiday |
|
||||
|
||||
r13 in total after `_i`: **21142 single cases and 5698 dialogues per split, 260 topics, 385 llm_reasoning meanings**;
|
||||
`check_r13.py`: 0 problems.
|
||||
|
||||
+53
-5
@@ -50,6 +50,7 @@ import importlib
|
||||
import json
|
||||
import pathlib
|
||||
import re
|
||||
re._MAXCACHE = 50000 # the readers build many patterns per map: the default 512 recompiles them per case
|
||||
import sys
|
||||
import time
|
||||
from unittest import mock
|
||||
@@ -73,7 +74,8 @@ SETS = ["commands_go", "commands_move", "commands_turn", "commands_look", "comma
|
||||
"commands_stop", "commands_status", "commands_chain", "commands_detour", "speed_short", "commands_sing",
|
||||
"commands_missions", "seeing_dialogues", "followup_dialogues", "dialogues_mixed", "unknowns", "silence_noise",
|
||||
"hearing", "questions_world", "memory_dialogues", "commands_come", "commands_hand", "commands_point",
|
||||
"commands_voice", "commands_waist", "commands_more", "closing_context", "lookup_dialogues"]
|
||||
"commands_voice", "commands_waist", "commands_more", "closing_context", "lookup_dialogues", "commands_side",
|
||||
"commands_cup", "commands_aside", "commands_short"]
|
||||
# commands_chain, commands_detour, speed_short, dialogues_mixed: round r2 on;
|
||||
# questions_world, memory_dialogues: r6 on. Any other file in a round's folder
|
||||
# is scored too, by the set its name grows ("commands_go_b" as commands_go)
|
||||
@@ -474,6 +476,8 @@ def score_dialogue(d, old, use_llm, judge=False):
|
||||
key = f"{j + 1}|{turn['say']}"
|
||||
if turn.get("reply") is not None and not turn.get("scored", True): # a setup: Lumi said this
|
||||
b.history.append((turn["say"], turn["reply"]))
|
||||
if re.match(r"ACTION: (?:pick|receive|fetch)\b", turn["reply"]):
|
||||
state = "holding" # r13 arm talks: the cup is held until the give / place
|
||||
continue
|
||||
if "scene" in turn:
|
||||
SCENE["now"] = turn["scene"]
|
||||
@@ -494,7 +498,7 @@ def score_dialogue(d, old, use_llm, judge=False):
|
||||
rows[-1]["closing"] = turn["closing"]
|
||||
b.history.append((turn["say"], ""))
|
||||
continue
|
||||
if r.startswith("action:give") or r.startswith("action:place"):
|
||||
if r.startswith(("action:give", "action:place", "action:put")):
|
||||
state = "idle" # handed over / put down: the hand is empty now
|
||||
if r == "none" and reply in FORGOT:
|
||||
r = "forget" # memory_dialogues: the talks deleted and said so
|
||||
@@ -721,8 +725,22 @@ def load(split, name):
|
||||
return list(cases.items()) if isinstance(cases, dict) else cases
|
||||
|
||||
|
||||
DECIMAL_SPLIT = re.compile(r"\d \d ?(?:미터|m\b|meters?\b)") # r12 generator defect: "1 2미터" written for 1.2 m
|
||||
|
||||
|
||||
def split_decimal(c):
|
||||
"""An r12 spoken move whose decimal the generator wrote as two numbers (logs/w6_gen/voice_decimal_split.txt):
|
||||
not scored."""
|
||||
return isinstance(c, dict) and c.get("channel") == "voice" and c.get("intent", "").startswith("move") and \
|
||||
bool(DECIMAL_SPLIT.search(c.get("text", "")))
|
||||
|
||||
|
||||
def run_set(split, name, old_rows, use_llm, cached, limit, sample=None):
|
||||
cases = load(split, name)
|
||||
mod = importlib.import_module(f"tests.blind.{split}.{name}")
|
||||
tags = {id(c): (lv, ch) for c, lv, ch in zip(cases, getattr(mod, "LEVELS", ()), getattr(mod, "CHANNELS", ()))}
|
||||
# r12 commands_sing: tuples with parallel LEVELS / CHANNELS lists
|
||||
cases = [c for c in cases if not split_decimal(c)]
|
||||
if sample and len(cases) > sample: # the same N cases every run (seeded by the set's name)
|
||||
import random
|
||||
cases = random.Random(name).sample(cases, sample)
|
||||
@@ -754,7 +772,8 @@ def run_set(split, name, old_rows, use_llm, cached, limit, sample=None):
|
||||
rows.append(row(str(c)[:200], "error", "-", f"{str(c)[:150]} -> {e!r}"))
|
||||
for r in rows[n:]:
|
||||
r["lang"] = lang_of(c, r)
|
||||
r["level"] = level_of(c, r)
|
||||
r["level"] = tags[id(c)][0] if id(c) in tags else level_of(c, r)
|
||||
r["channel"] = tags[id(c)][1] if id(c) in tags else channel_of(c, r)
|
||||
if r["verdict"] in ("wrong", "motion", "error") and "-v" in sys.argv:
|
||||
print(f" {r['verdict'].upper():6} {r['show'][:200]}", flush=True)
|
||||
return rows
|
||||
@@ -808,6 +827,34 @@ def level_of(c, r):
|
||||
return next((name + "*" for name, rx in LEVEL_GUESS if re.search(rx, text)), "ko_banmal*")
|
||||
|
||||
|
||||
def channel_of(c, r):
|
||||
"""typed (the Command box) / voice (whisper) of a case or a scored turn (r12 / r13 field "channel"), "-" before."""
|
||||
if isinstance(c, dict) and "turns" in c:
|
||||
j = int(r["key"].split("|", 1)[0]) - 1 if r["key"][:1].isdigit() else -1
|
||||
turn = c["turns"][j] if 0 <= j < len(c["turns"]) else {}
|
||||
return turn.get("channel") or c.get("channel") or "-"
|
||||
case = c if isinstance(c, dict) else c[1] if isinstance(c, (list, tuple)) and len(c) > 1 and \
|
||||
isinstance(c[1], dict) else {}
|
||||
return case.get("channel") or "-"
|
||||
|
||||
|
||||
def by_channel(saved):
|
||||
"""right / cases per speech level and channel (typed / voice), r12 on; nothing when no row has a channel."""
|
||||
ch = collections.defaultdict(collections.Counter)
|
||||
for name in ordered(saved):
|
||||
for r in saved[name]["rows"]:
|
||||
if r["verdict"] != "-" and r.get("channel", "-") != "-":
|
||||
for k in ((r.get("level", "?"), r["channel"]), ("ALL", r["channel"])):
|
||||
ch[k][r["verdict"]] += 1
|
||||
if not ch:
|
||||
return []
|
||||
lines = ["", "By speech level and channel (right / cases, motions in brackets):", "", "| level | typed | voice |",
|
||||
"|---|---|---|"]
|
||||
for lv in sorted({k[0] for k in ch}, key=lambda x: (x == "ALL", x)):
|
||||
lines.append(f"| {lv} | {cell(ch[(lv, 'typed')])} | {cell(ch[(lv, 'voice')])} |")
|
||||
return lines
|
||||
|
||||
|
||||
def by_level(saved):
|
||||
"""right / cases per speech level over every set (r9 / r6 _i: as labelled; "*": guessed from the endings), and the
|
||||
closing turns (closing_context) by kind."""
|
||||
@@ -863,7 +910,7 @@ def report(split, saved, secs):
|
||||
n = sum(tot.values())
|
||||
lines.append(f"| ALL | | {n} | {tot['right']} | {100 * tot['right'] // max(1, n)} | {tot['wrong']} | "
|
||||
f"{tot['motion']} | {tot['llm?']} | {tot['error']} | |")
|
||||
lines += by_lang(saved) + by_level(saved)
|
||||
lines += by_lang(saved) + by_level(saved) + by_channel(saved)
|
||||
for name in ordered(saved):
|
||||
rows = saved[name]["rows"]
|
||||
dl = {}
|
||||
@@ -876,7 +923,7 @@ def report(split, saved, secs):
|
||||
r["show"].replace("\n", "\n ") for r in bad] or ["- none"]
|
||||
out = ROOT / "logs" / f"blind_{split}.md"
|
||||
out.write_text("\n".join(lines) + "\n")
|
||||
print("\n".join(lines[:len(saved) + 7] + by_lang(saved) + by_level(saved)))
|
||||
print("\n".join(lines[:len(saved) + 7] + by_lang(saved) + by_level(saved) + by_channel(saved)))
|
||||
|
||||
|
||||
def main(args):
|
||||
@@ -895,6 +942,7 @@ def main(args):
|
||||
tag += "_" + args[args.index("--tag") + 1] # leaves the shared ones' LLM rows for --cached alone
|
||||
files = [f.stem for f in (ROOT / "tests" / "blind" / folder.replace(".", "/")).glob("*.py") if f.stem != "__init__"]
|
||||
todo = [n for n in ordered(files) if not names or any(n == a or n.startswith(a) or base(n) == a for a in names)]
|
||||
todo = [n for n in todo if not n.startswith("llm_reasoning") or names] # r13 llm_reasoning: tests/reasoning_check.py
|
||||
if not use_llm: # the mission reader's LLM pass only with the LLM
|
||||
steps._ollama = lambda *a: (_ for _ in ()).throw(command_check.NoLLM())
|
||||
from assistant import knowledge # the whole index read now (dialogue_check does so too)
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
"""Night-5 talks of T1 (own cases, not a blind set): unclear fragments. Words cut off by the speech recogniser
|
||||
("지금 몇...", "Can you"), odd noun phrases ("서울의 지구.", "Seoul's district."), statements that mean nothing to Lumi
|
||||
("저는 오후 6시 반이에요.") and filler get "sorry, again?" / "다시 한 번 말씀해 주시겠어요?" (or, inside a talk, a reply about
|
||||
that talk), never an unrelated fact about Lumi (its microphones, lidar, cameras, maker). English and Korean at every
|
||||
level (반말 / 해요체 / 하십시오체 / friendly / honorific / dialect), mixed; the date and time from the clock.
|
||||
|
||||
.venv/bin/python tests/dialogues_night5.py [only] # -> logs/t1n5/night5_check.json
|
||||
"""
|
||||
import sys
|
||||
|
||||
from tests.dialogues import T, D
|
||||
from tests.dialogues_world import N, NK, OFFER, RUDE
|
||||
|
||||
F, FK = [OFFER], [OFFER, RUDE] # a fragment's reply: asking again is right here (N / NK forbid it)
|
||||
|
||||
AGAIN = (r"didn't catch|did not catch|didn't quite|say (?:it|that) again|could you repeat|repeat that|one more time|"
|
||||
r"what do you mean|what did you mean|못 알아|다시 (?:한 ?번 )?말씀|다시 말씀|무슨 말씀|무슨 뜻|다시 한 ?번|잘 못 들|"
|
||||
r"잘 모르겠|이해하지 못|무엇을 말씀|어떤 (?:뜻|의미|말씀|점)|말씀해 주|궁금하신|not sure what|not sure which|"
|
||||
r"explain|tell me more|which one|어느 which .* you mean|do you mean|you mean\b")
|
||||
SELF = (r"microphone|\bmics?\b|lidar|laser|scanner|camera|ultrasonic|bumper|JAKA|Cutshion|made me|developed me|"
|
||||
r"robot assistant|my (?:arm|head|gripper|battery|wheels)|마이크|라이다|레이저|스캐너|카메라|초음파|범퍼|자카|쿳션|"
|
||||
r"만들었|만든 |개발한|로봇 비서|제 (?:팔|머리|고개|그리퍼|배터리|바퀴)")
|
||||
TIME = r"\d+ ?(?:시|:\d\d)|\b(?:am|pm|a\.m\.|p\.m\.)|오전|오후|o'clock"
|
||||
DATE = r"\d+ ?월 ?\d+ ?일|\b(?:January|February|March|April|May|June|July|August|September|October|November|December)\b"
|
||||
Q = "unclear | none" # asking again may come as unclear or as none with the words of asking again
|
||||
|
||||
DIALOGUES_NIGHT5 = [
|
||||
D("visitor", "fragment_ko_start", "ko",
|
||||
T("지금 몇...", Q, must=[AGAIN], no=FK + [SELF], check="잘린 말: 다시 말해 달라고 함, 자기 소개 아님"),
|
||||
T("서울의 지구.", Q, must=[AGAIN], no=FK + [SELF], check="뜻이 불분명: 다시 말해 달라고 함, 검색 아님"),
|
||||
T("저는 오후 6시 반이에요.", Q, must=[AGAIN + "|6시 반|여섯 시 반"], no=FK + [SELF],
|
||||
check="뜻이 불분명한 말: 무슨 뜻인지 묻거나 짧게 받음; 라이다 / 카메라 얘기 아님"),
|
||||
T("고마워요, 갈게요.", "end")),
|
||||
D("visitor", "fragment_ko_after_time", "ko",
|
||||
T("지금 몇 시예요?", must=[TIME], no=NK, check="시계의 시각"),
|
||||
T("지금 몇...", Q + " | none", must=[AGAIN + "|" + TIME], no=FK + [SELF], check="잘린 말: 시각을 다시 말하거나 다시 묻기"),
|
||||
T("몇이요? 지금은 몇이요?", must=[TIME], no=FK + [SELF], check="시각"),
|
||||
T("오늘 며칠이에요?", must=[DATE], no=NK, check="오늘 날짜 (시계)"),
|
||||
T("네 고마워요.", "-")),
|
||||
D("visitor", "fragment_en_start", "en",
|
||||
T("Can you", Q, must=[AGAIN], no=F + [SELF], check="cut off: asks again, no self-description"),
|
||||
T("Seoul's district.", Q, must=[AGAIN], no=F + [SELF], check="unclear phrase: asks again"),
|
||||
T("A-Q-N. Nunn.", Q, must=[AGAIN], no=F + [SELF], check="nonsense: asks again"),
|
||||
T("I'm half past six.", Q, must=[AGAIN + "|six|6:30"], no=F + [SELF], check="unclear statement: asks what they mean"),
|
||||
T("Okay, bye.", "end")),
|
||||
D("visitor", "fragment_en_time", "en",
|
||||
T("What is the time?", must=[TIME], no=N, check="the clock's time"),
|
||||
T("And what's the...", Q + " | none", must=[AGAIN + "|" + DATE + "|" + TIME], no=F + [SELF],
|
||||
check="cut off: asks again (or the date / time)"),
|
||||
T("What's the date today?", must=[DATE], no=N, check="today's date from the clock"),
|
||||
T("the uh the", Q, must=[AGAIN], no=F + [SELF], check="filler: asks again"),
|
||||
T("Thanks, that's all.", "end")),
|
||||
D("student", "fragment_ko_banmal", "ko",
|
||||
T("야 그 저기 그거...", Q, must=[AGAIN], no=FK + [SELF], check="filler: 다시 말해 달라고 함"),
|
||||
T("어 그러니까 그 몇 개...", Q, must=[AGAIN], no=FK + [SELF], check="잘린 말"),
|
||||
T("부산의 바다.", Q, must=[AGAIN], no=FK + [SELF], check="뜻이 불분명"),
|
||||
T("됐어, 갈게.", "end")),
|
||||
D("office worker", "fragment_ko_hasipsio", "ko",
|
||||
T("실례지만 혹시 그...", Q, must=[AGAIN], no=FK + [SELF], check="잘린 말"),
|
||||
T("그러니까 제가 여쭤보고 싶은 것은...", Q, must=[AGAIN], no=FK + [SELF], check="잘린 말"),
|
||||
T("저는 3층입니다.", Q + " | none", must=[AGAIN + "|3층"], no=FK + [SELF], check="문맥 없는 말: 짧게 받거나 다시 묻기"),
|
||||
T("수고하십시오.", "end")),
|
||||
D("grandmother", "fragment_ko_honorific_dialect", "ko",
|
||||
T("아이고 그 뭐시냐...", Q, must=[AGAIN], no=FK + [SELF], check="사투리 filler"),
|
||||
T("거시기 그 머꼬...", Q, must=[AGAIN], no=FK + [SELF], check="사투리 filler"),
|
||||
T("할머니께서 그 저...", Q, must=[AGAIN], no=FK + [SELF], check="높임말 잘린 말"),
|
||||
T("고맙데이, 가께.", "end")),
|
||||
D("parent", "fragment_mixed", "ko",
|
||||
T("지금 time이 몇...", Q + " | none", must=[AGAIN + "|" + TIME], no=FK + [SELF], check="잘린 말: 시각 또는 다시 묻기"),
|
||||
T("그 robot의 그...", Q, must=[AGAIN], no=FK + [SELF], check="잘린 말"),
|
||||
T("Seoul 그 district.", Q, must=[AGAIN], no=FK + [SELF], check="뜻이 불분명"),
|
||||
T("오케이 땡큐, 바이.", "end")),
|
||||
]
|
||||
|
||||
|
||||
def main(only=None):
|
||||
"""Each talk through tests/dialogue_check.run_turn (lumi.answer()'s order) and dialogue_check.problems; no judge
|
||||
(followup_check would count asking again as a fault, and here it is the right answer)."""
|
||||
import json
|
||||
from tests import dialogue_check as dc
|
||||
from tests.conversation_check import markers
|
||||
marks, rows = markers(), []
|
||||
for i, d in enumerate(DIALOGUES_NIGHT5, 1):
|
||||
if only and only not in d["topic"]:
|
||||
continue
|
||||
b = brain.Brain()
|
||||
for j, turn in enumerate(d["turns"], 1):
|
||||
lang = dc.turn_lang(turn)
|
||||
r, reply, first, _ = dc.run_turn(b, turn["say"], lang, marks)
|
||||
probs = dc.problems(turn, lang, r, reply, first is not None) if turn["expect_action"] != "-" else None
|
||||
rows.append({"topic": d["topic"], "turn": j, "say": turn["say"], "got": r, "reply": reply, "problems": probs})
|
||||
print(f"{'- ' if probs is None else 'OK ' if not probs else 'FAIL'} {d['topic']} t{j} {turn['say']!r} -> [{r}] {reply[:110]!r} {probs}",
|
||||
flush=True)
|
||||
scored = [r for r in rows if r["problems"] is not None]
|
||||
ok = sum(not r["problems"] for r in scored)
|
||||
print(f"right {ok}/{len(scored)} turns")
|
||||
out = dc.ROOT / "logs" / "t1n5" / "night5_check.json"
|
||||
out.parent.mkdir(exist_ok=True)
|
||||
out.write_text(json.dumps(rows, ensure_ascii=False, indent=1))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
from assistant import brain
|
||||
main(sys.argv[1] if len(sys.argv) > 1 else None)
|
||||
@@ -0,0 +1,424 @@
|
||||
"""Typed = voice, English = Korean: every command case of the blind train sets read both ways, offline.
|
||||
|
||||
.venv/bin/python tests/parity_check.py # rules: r6 r8 r9 r10 (and r12 when it is there)
|
||||
.venv/bin/python tests/parity_check.py --round r9 commands_go # one round, these sets ("commands" = every commands_*)
|
||||
.venv/bin/python tests/parity_check.py --sample 50 # 50 cases per file, seeded (the same each run)
|
||||
.venv/bin/python tests/parity_check.py --llm --sample 20 # what the rules leave goes to the LLM (voice asks it
|
||||
# once; the box acts on the same action line)
|
||||
.venv/bin/python tests/parity_check.py --cached # the LLM lines of the last --llm run (same tag)
|
||||
.venv/bin/python tests/parity_check.py --tag final # -> logs/parity_final.md / .json
|
||||
|
||||
Voice: tests/blind_check.score_commands (command_check.rules = lumi.answer's order on lumi.route, then the LLM).
|
||||
Typed: api/server.task_parse, the dashboard's Command box, with the hand as the case says (fetch.check_hand faked) and
|
||||
the case's map; a "command" it hands to the assistant is heard by voice, so that one is voice's by construction. The box
|
||||
has no talk history: cases with "before" that differ are counted apart ("context"). Missions: lumi.route's steps on
|
||||
both sides against the case's steps (tests/test_steps.py notation).
|
||||
Report: typed != voice (same words, other plan), right / wrong / motion per channel and speech level, and per meaning
|
||||
(same set, intent, expect, state, before, map) English against Korean: a meaning right in one language and not in the
|
||||
other. Nothing moves; no service is called (the bank's embeddings are read as by every check).
|
||||
"""
|
||||
import collections
|
||||
import json
|
||||
import pathlib
|
||||
import random
|
||||
import re
|
||||
re._MAXCACHE = 50000 # ponytail: the readers build many patterns per map; the
|
||||
# default 512 recompiles them every case (20x slower)
|
||||
import sys
|
||||
import time
|
||||
|
||||
from tests import blind_check as bc
|
||||
from tests import command_check
|
||||
from assistant import brain, intent_bank, lumi
|
||||
from tasks import fetch
|
||||
from api import server
|
||||
|
||||
ROOT = pathlib.Path(__file__).resolve().parents[1]
|
||||
ROUNDS = ["r6", "r8", "r9", "r10", "r11", "r12"] # train sets only; held folders are never opened
|
||||
SKIP = {"commands_sing"} # songs: the box hands every song to the assistant (voice)
|
||||
EN_LEVELS = {"en_native", "en_nonnative", "en", "en*"}
|
||||
ARM = re.compile(r"^(?:wave|reach|hand|arm|give|take|put|waist)") # intents of the arm wordings (H1)
|
||||
|
||||
# ---------- fakes: nothing moves, nothing is written ----------
|
||||
HAND = {"held": False}
|
||||
fetch.check_hand = lambda: HAND["held"]
|
||||
fetch.held_name = lambda lang="en": "the cup" if lang == "en" else "컵"
|
||||
fetch.state = lambda: {"holding": HAND["held"]}
|
||||
fetch.log = lumi.log = lambda *a, **k: None
|
||||
MAP = {"now": bc.DEFAULT_MARKERS}
|
||||
server.agv.markers = lambda: MAP["now"]
|
||||
|
||||
SEEN = {"route": None, "bank": None} # what lumi.route and the bank answered last
|
||||
_route, _bank = lumi.route, intent_bank.read
|
||||
|
||||
|
||||
def route(*a, **k):
|
||||
SEEN["bank"] = None
|
||||
SEEN["route"] = _route(*a, **k)
|
||||
return SEEN["route"]
|
||||
|
||||
|
||||
def bank(*a, **k):
|
||||
SEEN["bank"] = _bank(*a, **k)
|
||||
return SEEN["bank"]
|
||||
|
||||
|
||||
lumi.route, intent_bank.read = route, bank
|
||||
|
||||
SEEN_V = {"route": None} # voice's route of the case
|
||||
LLM_LINE = {"head": None, "first": ""} # voice's action line, given to the box's LLM pass
|
||||
|
||||
|
||||
def box_llm(self, *a, **k):
|
||||
yield LLM_LINE["head"] or {"action": "none", "target": ""}
|
||||
yield LLM_LINE["first"]
|
||||
|
||||
|
||||
# ---------- one notation for both ----------
|
||||
def num(x):
|
||||
return f"{float(x):g}"
|
||||
|
||||
|
||||
def step_word(s):
|
||||
d = s.get("do")
|
||||
if d == "go":
|
||||
return f"go {s.get('to') if isinstance(s.get('to'), str) else (s.get('to') or {}).get('name', s.get('to'))}"
|
||||
if d == "move":
|
||||
return f"move {s.get('dir')} {num(s.get('m', 1))}"
|
||||
if d == "turn":
|
||||
return f"turn {num(abs(s.get('deg', 0)) if abs(s.get('deg', 0)) == 180 else s.get('deg', 0))}" # half: either way
|
||||
if d in ("pick", "receive"):
|
||||
return " ".join(str(w) for w in (d, s.get("colour"), s.get("object")) if w)
|
||||
if d == "arm":
|
||||
return f"arm {s.get('pose')}"
|
||||
if d == "place":
|
||||
return "place " + str((s.get("on") or {}).get("name") or "")
|
||||
return d
|
||||
|
||||
|
||||
def canon_steps(st):
|
||||
return " ; ".join(step_word(s) for s in st or [])
|
||||
|
||||
|
||||
def canon(got, plan=None, st=None):
|
||||
"""A route as one comparable string: motions by what they do, every no-motion answer as "none"."""
|
||||
w = got.split()
|
||||
if not w:
|
||||
return "none"
|
||||
if w[0] in command_check.NO_MOTION or w[0] in ("empty_hand", "refuse", "seeing", "status", "end", "sing", "point"):
|
||||
return "none" if w[0] != "point" else "point"
|
||||
if got == "mission":
|
||||
return "steps " + canon_steps(st)
|
||||
if got.startswith("chain:"):
|
||||
return "chain " + " + ".join(bc.chain_tokens(plan or []))
|
||||
if got.startswith("action:"):
|
||||
a, _, t = got[7:].partition(" ")
|
||||
if a == "fetch":
|
||||
return "fetch"
|
||||
if a == "put": # "put it down" while holding: the place
|
||||
return "place"
|
||||
rs = server._rule_steps((a, t))
|
||||
return "steps " + canon_steps(rs) if rs else f"{a} {t}".strip()
|
||||
if w[0] == "receive":
|
||||
return "steps " + " ".join(w)
|
||||
if w[0] == "place":
|
||||
return "place"
|
||||
return got
|
||||
|
||||
|
||||
def turn_said(deg):
|
||||
return "around" if abs(deg) == 180 else f"{'left' if deg > 0 else 'right'} {num(abs(deg))}"
|
||||
|
||||
|
||||
def typed_got(r):
|
||||
"""/tasks/parse's result in the checkers' notation (judged by command_check.ok), or None: handed to the assistant
|
||||
(heard as by voice)."""
|
||||
a = r.get("action")
|
||||
if a in ("steps", "carry") and r.get("problems"):
|
||||
return "refuse", None # shown with the reason, Start not offered (a fetch's
|
||||
# problems are the dialog's questions: "Where should I bring it?")
|
||||
if a == "steps":
|
||||
st = r["steps"]
|
||||
if len(st) == 1:
|
||||
s = st[0]
|
||||
d = s.get("do")
|
||||
one = {"go": lambda: f"action:go_to {s.get('to')}", "move": lambda: f"action:move {s['dir']} {num(s['m'])}",
|
||||
"turn": lambda: f"action:turn {turn_said(s['deg'])}", "arm": lambda: f"action:arm {s['pose']}",
|
||||
"pick": lambda: "action:pick " + " ".join(x for x in (s.get("colour"), s.get("object")) if x),
|
||||
"receive": lambda: f"receive {s.get('object') or ''}".strip(),
|
||||
"place": lambda: "place " + str((s.get("on") or {}).get("name") or "")}.get(d)
|
||||
if one and isinstance(s.get("to", ""), str):
|
||||
return one(), st
|
||||
return "mission", st
|
||||
if a == "fetch":
|
||||
return f"action:fetch {(r.get('task') or {}).get('object') or ''}".strip(), None
|
||||
if a in ("give", "place"):
|
||||
return (a if a == "give" else "place " + str(((r.get("task") or {}).get("on") or {}).get("name") or "")), None
|
||||
if a == "carry":
|
||||
d = (r.get("task") or {}).get("dest")
|
||||
return f"action:go_to {d.get('name') if isinstance(d, dict) else d}", None
|
||||
if a == "command": # Start sends the words to the assistant (/tasks/command):
|
||||
return None, None # heard and done as by voice
|
||||
return ("refuse" if r.get("talk") == "refuse" else "talk"), None
|
||||
|
||||
|
||||
# ---------- both ways ----------
|
||||
def voice(c, old, use_llm):
|
||||
SEEN["route"] = None
|
||||
r = bc.score_commands(c, old, use_llm)
|
||||
got = re.search(r"\] .*? -> (.*?) \(want ", r["show"], re.S)
|
||||
got = got.group(1) if got else "?"
|
||||
kind, data = SEEN["route"] or (None, None)
|
||||
src = r["by"] if r["by"] == "llm" else "bank" if kind == "quick" and SEEN["bank"] and tuple(SEEN["bank"]) == \
|
||||
tuple(data) else "rules"
|
||||
plan = data if kind == "chain" else None
|
||||
st = data[0] if kind == "mission" else None
|
||||
return r, got, src, plan, st
|
||||
|
||||
|
||||
def typed(c, voice_row, use_llm):
|
||||
HAND["held"] = c["state"] == "holding"
|
||||
MAP["now"] = bc.marks_of(c)
|
||||
bc.STUCK["now"] = {"goal": c["stuck_goal"], "rest": [{"do": "go", "to": c["stuck_goal"]}], "start": None,
|
||||
"tries": 0, "time": time.time()} if c["state"] == "stuck" else None
|
||||
raw = voice_row["out"].get("raw") or ""
|
||||
a, _, t = raw.partition(" ")
|
||||
LLM_LINE.update(head={"action": a, "target": t} if raw else None, first=voice_row["out"].get("first") or "")
|
||||
SEEN["route"] = None
|
||||
real, brain.Brain.respond_stream = brain.Brain.respond_stream, box_llm
|
||||
try:
|
||||
r = server.task_parse(server.ParseBody(text=c["text"], llm=bool(raw)))
|
||||
except command_check.NoLLM: # the mission reader's LLM pass, as on the voice side
|
||||
return "llm?", None, None
|
||||
except Exception as e: # noqa: BLE001 - a crash is a failure of that case
|
||||
return f"error {e!r}"[:120], None, None
|
||||
finally:
|
||||
bc.STUCK["now"] = None
|
||||
brain.Brain.respond_stream = real
|
||||
got, st = typed_got(r)
|
||||
got = command_check.refused(got) if got else got # a thing the fingers can't take: the box says why too
|
||||
kind, data = SEEN["route"] or (None, None)
|
||||
return got, st, data if kind == "chain" else None
|
||||
|
||||
|
||||
def verdict(c, got):
|
||||
if got == "llm?":
|
||||
return "llm?"
|
||||
got = command_check.refused(got)
|
||||
v = command_check.ok(c["expect"], got)
|
||||
return "right" if v == "right" else "motion" if bc.MOTION.match(got) or got.startswith("detour") else "wrong"
|
||||
|
||||
|
||||
def mission_case(text, case):
|
||||
"""A commands_missions case as a command case: lumi.route's steps judged against the written ones."""
|
||||
return {"text": text, "lang": case.get("lang") or bc.lang_of((text, case), {}), "state": "idle", "before": None,
|
||||
"expect": "mission", "steps": case["steps"], "markers": case.get("markers"), "map": case.get("map"),
|
||||
"level": case.get("level"), "intent": case.get("intent") or "missions"}
|
||||
|
||||
|
||||
CHAIN_VERB = {"go_to": "go", "come_back": "go", "come": "go", "put": "place", "take": "receive"}
|
||||
|
||||
|
||||
def mission_verdict(c, got, st, plan=None):
|
||||
want = c["steps"].strip()
|
||||
if want == "?":
|
||||
return "right" if not bc.MOTION.match(got) else "motion"
|
||||
if got == "mission" or st and got.startswith(("action:", "receive", "place")):
|
||||
return "right" if bc.same_steps([bc.short(s.strip()) for s in want.split(" | ")], st or []) else "motion"
|
||||
if got.startswith("chain:"): # the parts one by one (chain_run): the same commands in turn
|
||||
verbs = [CHAIN_VERB.get(t.split()[0], t.split()[0]) for t in bc.chain_tokens(plan or [])]
|
||||
return "right" if verbs == [w.split()[0] for w in want.split(" | ")] else "motion"
|
||||
return "llm?" if got == "llm?" else "wrong"
|
||||
|
||||
|
||||
def run_case(rnd, name, c, old, use_llm):
|
||||
mission = "steps" in c
|
||||
vrow, vgot, src, vplan, vst = voice(c, old, use_llm) if not mission else voice({**c, "expect": "mission"}, old, use_llm)
|
||||
if mission and vgot == "mission" and SEEN["route"] and SEEN["route"][0] == "mission":
|
||||
vst = SEEN["route"][1][0]
|
||||
SEEN_V["route"] = SEEN["route"]
|
||||
tgot, tst, tplan = typed(c, vrow, use_llm)
|
||||
handed = tgot is None
|
||||
if handed: # the assistant hears it: voice's way
|
||||
tgot, tst, tplan = vgot, vst, vplan
|
||||
if mission:
|
||||
vv, tv = mission_verdict(c, vgot, vst, vplan), mission_verdict(c, tgot, tst, tplan)
|
||||
else:
|
||||
vv, tv = (vrow["verdict"] if vrow["verdict"] in ("right", "wrong", "motion", "llm?") else verdict(c, vgot)), \
|
||||
verdict(c, tgot)
|
||||
fetch_asks = vgot == "ask" and (SEEN_V["route"] or (None,))[0] == "quick" and SEEN_V["route"][1][0] == "fetch"
|
||||
vc, tc = canon("action:fetch" if fetch_asks else vgot, vplan, vst), canon(tgot, tplan, tst) # the dialog asks too
|
||||
lv = c.get("level") or bc.level_of(c, {"lang": c.get("lang")})
|
||||
return {"round": rnd, "set": name, "text": c["text"], "state": c["state"], "before": c.get("before"),
|
||||
"expect": c["expect"] if not mission else c["steps"], "intent": c.get("intent", ""), "map": c.get("map"),
|
||||
"level": bc.LEVEL_NAME.get(lv, lv), "lang": c.get("lang"), "voice": vgot, "typed": tgot, "handed": handed,
|
||||
"v_canon": vc, "t_canon": tc, "v": vv, "t": tv, "src": src, "same": vc == tc,
|
||||
"raw": vrow["out"].get("raw", ""), "first": vrow["out"].get("first", "")}
|
||||
|
||||
|
||||
def cases_of(rnd, name, sample):
|
||||
"""sample: about this many cases, whole meanings (every level of a meaning kept, so EN / KO stay comparable)."""
|
||||
cases = bc.load(f"{rnd}.train", name)
|
||||
if bc.base(name) == "commands_missions":
|
||||
cases = [mission_case(t, k) for t, k in cases]
|
||||
cases = [c for c in cases if isinstance(c, dict) and "text" in c and "expect" in c and not bc.split_decimal(c)]
|
||||
if sample and len(cases) > sample:
|
||||
groups = collections.defaultdict(list)
|
||||
for c in cases:
|
||||
groups[(c.get("intent"), c["expect"], c["state"], str(c.get("before")), c.get("map"))].append(c)
|
||||
keys = sorted(groups, key=str)
|
||||
random.Random(name).shuffle(keys)
|
||||
picked = []
|
||||
for k in keys:
|
||||
if len(picked) >= sample:
|
||||
break
|
||||
picked += groups[k]
|
||||
cases = picked
|
||||
return cases
|
||||
|
||||
|
||||
def sets_of(rnd, only):
|
||||
folder = ROOT / "tests" / "blind" / rnd / "train"
|
||||
if not folder.is_dir():
|
||||
return []
|
||||
names = sorted(p.stem for p in folder.glob("*.py") if p.stem != "__init__")
|
||||
names = [n for n in names if (n.startswith("commands_") or bc.base(n) == "speed_short") and bc.base(n) not in SKIP]
|
||||
if only:
|
||||
names = [n for n in names if bc.base(n) in only or n in only or "commands" in only and n.startswith("commands_")]
|
||||
return names
|
||||
|
||||
|
||||
# ---------- report ----------
|
||||
def meaning(r):
|
||||
return (r["round"], bc.base(r["set"]), r["intent"], r["expect"], r["state"], str(r["before"]), r["map"])
|
||||
|
||||
|
||||
def owner(r, kind):
|
||||
"""Which agent's reader a fault belongs to: L1 the Command box and the brain's rules, B2 the bank, H1 the arm's
|
||||
wordings, T1 the LLM's reading."""
|
||||
if kind == "typed":
|
||||
return "L1"
|
||||
if r["src"] == "llm":
|
||||
return "T1"
|
||||
if r["src"] == "bank":
|
||||
return "B2"
|
||||
return "H1" if ARM.match(r["intent"]) else "L1"
|
||||
|
||||
|
||||
def report(rows, tag, secs, args):
|
||||
out = [f"# Parity check {tag} ({time.strftime('%Y-%m-%d %H:%M')}, {secs:.0f} s, {' '.join(args) or 'rules'})", "",
|
||||
f"{len(rows)} command cases (blind train sets). right / wrong / motion (a motion not asked for) / llm? per "
|
||||
"channel; typed = the dashboard's Command box (/tasks/parse), voice = lumi.answer's way.", ""]
|
||||
diff = [r for r in rows if not r["same"]]
|
||||
ctx = [r for r in diff if r["before"]]
|
||||
out += [f"**typed != voice: {len(diff) - len(ctx)}** (+ {len(ctx)} with a talk before, which the box has not)", "",
|
||||
"| round | cases | voice right | typed right | voice motion | typed motion | voice llm? | typed≠voice |",
|
||||
"|---|---|---|---|---|---|---|---|"]
|
||||
for rnd in sorted({r["round"] for r in rows}, key=ROUNDS.index) + ["ALL"]:
|
||||
rr = [r for r in rows if rnd in ("ALL", r["round"])]
|
||||
c = lambda k, v: sum(r[k] == v for r in rr)
|
||||
out.append(f"| {rnd} | {len(rr)} | {c('v', 'right')} | {c('t', 'right')} | {c('v', 'motion')} | "
|
||||
f"{c('t', 'motion')} | {c('v', 'llm?')} | {sum(not r['same'] and not r['before'] for r in rr)} |")
|
||||
out += ["", "By speech level (right / judged; motions):", "", "| level | voice | typed | voice motion | typed motion |",
|
||||
"|---|---|---|---|---|"]
|
||||
for lv in sorted({r["level"] for r in rows}):
|
||||
rr = [r for r in rows if r["level"] == lv]
|
||||
jv, jt = [r for r in rr if r["v"] != "llm?"], [r for r in rr if r["t"] != "llm?"]
|
||||
pct = lambda j, k: f"{sum(r[k] == 'right' for r in j)}/{len(j)} ({100 * sum(r[k] == 'right' for r in j) / max(1, len(j)):.1f} %)"
|
||||
out.append(f"| {lv} | {pct(jv, 'v')} | {pct(jt, 't')} | {sum(r['v'] == 'motion' for r in rr)} | "
|
||||
f"{sum(r['t'] == 'motion' for r in rr)} |")
|
||||
groups = collections.defaultdict(list)
|
||||
for r in rows:
|
||||
groups[meaning(r)].append(r)
|
||||
gap = [] # a meaning right in one language, not in the other
|
||||
for k, rr in groups.items():
|
||||
en = [r for r in rr if r["level"] in EN_LEVELS and r["v"] != "llm?"]
|
||||
ko = [r for r in rr if r["level"] not in EN_LEVELS and r["v"] != "llm?"]
|
||||
if en and ko:
|
||||
er, kr = any(r["v"] == "right" for r in en), any(r["v"] == "right" for r in ko)
|
||||
bad_ko = [r for r in ko if r["v"] != "right"]
|
||||
bad_en = [r for r in en if r["v"] != "right"]
|
||||
if er and bad_ko:
|
||||
gap.append(("KO behind", k, bad_ko))
|
||||
if kr and bad_en:
|
||||
gap.append(("EN behind", k, bad_en))
|
||||
both = sum(1 for rr in groups.values() if any(r["level"] in EN_LEVELS for r in rr) and
|
||||
any(r["level"] not in EN_LEVELS for r in rr))
|
||||
lvgap = collections.Counter(r["level"] for _, _, bad in gap for r in bad)
|
||||
out += ["", f"**EN != KO**: {sum(g[0] == 'KO behind' for g in gap)} meanings where English is right and a Korean "
|
||||
f"level is not, {sum(g[0] == 'EN behind' for g in gap)} the other way, of {both} meanings said in both. "
|
||||
"Cases behind, per level: " + ", ".join(f"{k} {v}" for k, v in lvgap.most_common()), ""]
|
||||
# classes for the owners
|
||||
cls = collections.defaultdict(list)
|
||||
for r in rows:
|
||||
if not r["same"] and not r["before"]:
|
||||
cls[("L1", f"typed != voice: voice {r['v_canon'].split()[0]}, typed {r['t_canon'].split()[0]}")].append(r)
|
||||
if r["v"] in ("wrong", "motion"):
|
||||
cls[(owner(r, "voice"), f"{r['v']} ({r['src']}): {bc.base(r['set'])}")].append(r)
|
||||
elif r["t"] in ("wrong", "motion") and r["same"] is False and not r["handed"]:
|
||||
cls[("L1", f"typed {r['t']}: {bc.base(r['set'])}")].append(r)
|
||||
for who in ("L1", "B2", "H1", "T1"):
|
||||
mine = sorted(((k[1], v) for k, v in cls.items() if k[0] == who), key=lambda x: -len(x[1]))
|
||||
out += ["", f"## For {who} ({sum(len(v) for _, v in mine)} cases)", ""]
|
||||
for name, rr in mine:
|
||||
out.append(f"- **{name}**: {len(rr)}")
|
||||
for r in rr[:3]:
|
||||
out.append(f" - [{r['round']} {r['set']} {r['level']}/{r['state']}] {r['text']!r} -> voice {r['voice']}, "
|
||||
f"typed {r['typed']} (want {r['expect']})")
|
||||
out += ["", "## EN != KO examples (per meaning, 3 per kind and set)", ""]
|
||||
shown = collections.Counter()
|
||||
for kind, k, bad in gap:
|
||||
if shown[(kind, k[1])] < 3:
|
||||
shown[(kind, k[1])] += 1
|
||||
out.append(f"- {kind} [{k[0]} {k[1]} {k[2]} / {k[4]}] want {k[3]}: " +
|
||||
"; ".join(f"{r['level']} {r['text']!r} -> {r['voice']}" for r in bad[:2]))
|
||||
return "\n".join(out) + "\n"
|
||||
|
||||
|
||||
def main(args):
|
||||
use_llm, cached = "--llm" in args, "--cached" in args
|
||||
tag = args[args.index("--tag") + 1] if "--tag" in args else ("llm" if use_llm else "rules")
|
||||
sample = int(args[args.index("--sample") + 1]) if "--sample" in args else None
|
||||
rounds = [args[args.index("--round") + 1]] if "--round" in args else ROUNDS
|
||||
skip = {args[i + 1] for i, a in enumerate(args) if a in ("--tag", "--sample", "--round", "--merge")}
|
||||
only = [a for a in args if not a.startswith("-") and a not in skip]
|
||||
out = ROOT / "logs" / f"parity_{tag}"
|
||||
if "--merge" in args: # the reports of runs made side by side, as one
|
||||
rows = [r for t in args[args.index("--merge") + 1].split(",")
|
||||
for r in json.loads((ROOT / "logs" / f"parity_{t}.json").read_text())]
|
||||
out.with_suffix(".json").write_text(json.dumps(rows, ensure_ascii=False, indent=0))
|
||||
out.with_suffix(".md").write_text(report(rows, tag, 0, args))
|
||||
print(out.with_suffix(".md").read_text()[:3000])
|
||||
return
|
||||
old = {}
|
||||
if cached and out.with_suffix(".json").exists():
|
||||
old = {(r["round"], r["set"], r["text"], r["state"], str(r["before"])): r
|
||||
for r in json.loads(out.with_suffix(".json").read_text()) if r.get("raw")}
|
||||
if not use_llm: # a mission's LLM pass only with --llm
|
||||
from assistant import steps
|
||||
steps._ollama = lambda *a: (_ for _ in ()).throw(command_check.NoLLM())
|
||||
rows, t0 = [], time.time()
|
||||
for rnd in rounds:
|
||||
for name in sets_of(rnd, only):
|
||||
for c in cases_of(rnd, name, sample):
|
||||
key = (rnd, name, c["text"], c["state"], str(c.get("before")))
|
||||
o = old.get(key)
|
||||
o = {"out": {"raw": o["raw"], "first": o["first"]}} if o else None
|
||||
try:
|
||||
r = run_case(rnd, name, c, o, use_llm)
|
||||
except Exception as e: # noqa: BLE001
|
||||
r = {"round": rnd, "set": name, "text": c["text"], "state": c["state"], "before": c.get("before"),
|
||||
"expect": c.get("expect"), "intent": c.get("intent", ""), "map": c.get("map"),
|
||||
"level": c.get("level") or "?", "lang": c.get("lang"), "voice": f"error {e!r}"[:120],
|
||||
"typed": "-", "handed": False, "v_canon": "error", "t_canon": "error", "v": "wrong",
|
||||
"t": "wrong", "src": "rules", "same": False, "raw": "", "first": ""}
|
||||
rows.append(r)
|
||||
print(f"{rnd} {name}: {len(rows)} ({time.time() - t0:.0f} s)", flush=True)
|
||||
out.with_suffix(".json").write_text(json.dumps(rows, ensure_ascii=False, indent=0))
|
||||
text = report(rows, tag, time.time() - t0, args)
|
||||
out.with_suffix(".md").write_text(text)
|
||||
print(text[:3000])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main(sys.argv[1:])
|
||||
@@ -0,0 +1,963 @@
|
||||
"""Offline pick / place sweep: seeded scenes all around Lumi (cups and tables left, ahead, right, beside it, near, far,
|
||||
out of reach, table edges, a chair on the way), run through the real tasks/fetch.py and manipulation/skills.py code
|
||||
(_pick_here, _put_down) with fakes at the hardware edge only. No robot, no network, no services.
|
||||
|
||||
.venv/bin/python tests/pick_sweep.py --round 1 [--picks 1500] [--places 600] [--seed 1] [--jobs 12] [--cam 1]
|
||||
|
||||
Writes logs/pick_sweep_<round>.jsonl (one record per scene) and logs/pick_sweep_<round>.md (the report).
|
||||
|
||||
The fakes (a small simulator):
|
||||
- arm: robot/kinematics.py answers kine_inverse / kine_forward; joint and straight moves set the joints at once.
|
||||
Any other controller command raises.
|
||||
- base: a map pose; navigation arrives (+-2 cm, +-1 deg) unless the goal is within NAV_MARGIN_M of an obstacle, then
|
||||
it reports "succeeded" without moving (CLAUDE.md); joy_control drives straight on a virtual clock and stalls when
|
||||
driving forward would bring the base centre nearer an obstacle than BASE_HALF_M + the scene's stall gap (the base's
|
||||
own safety stop, live 2026-10-26 18:13). Obstacles: the table top and a chair as rectangles (clearance, probe).
|
||||
- body: lift 0 (held there), waist and head as commanded. The waist turns the arm frame about the column
|
||||
(COLUMN_BASE_M, the head's turning centre); fetch's own model turns it about the base centre (finding, X1.md).
|
||||
- torso camera: detections of the cup with a per-scene extrinsic error (rotation, depth scale) and frame noise;
|
||||
depth frames ray-cast from the true camera pose (table tops, the floor, the chair, the cup), read through the real
|
||||
skills.surface_points / flat_points / on_table / locate. The head camera is off.
|
||||
- gripper: close() checks where the fingers came down on the true cup (along the fingers / across them, see LANDING)
|
||||
and knocks it over when a finger lands on it; open_() releases a held cup where the hand is.
|
||||
The grasp offset carries the camera's error at the taught cup (grasp_teach.json was taught from a seen cup), so a
|
||||
straight pick near the taught spot lands right and a turned one carries that error turned (fault (e)).
|
||||
"""
|
||||
import argparse
|
||||
import collections
|
||||
import json
|
||||
import math
|
||||
import multiprocessing as mp
|
||||
import os
|
||||
import random
|
||||
import signal
|
||||
import sys
|
||||
import tempfile
|
||||
import time as _time
|
||||
import traceback
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT))
|
||||
|
||||
# ---------- fixed values (embedded so the sweep runs without the Thor-only calibration files) ----------
|
||||
T_CAL = np.array([[0.999523, -0.014152, 0.027436, -257.663352], # data/camera_extrinsics.json T_base_cam
|
||||
[-0.02739, 0.003442, 0.999619, 13.72052], # (2026-10-13, in use)
|
||||
[-0.014242, -0.999894, 0.003053, -41.359237],
|
||||
[0.0, 0.0, 0.0, 1.0]])
|
||||
INTR = {"width": 1280, "height": 720, "fx": 608.3, "fy": 608.4, "cx": 636.9, "cy": 363.2, "dist": [0.0] * 5}
|
||||
HEAD_CENTRE = np.array([-92.969, -19.868, 356.124]) # head_cam.head_centre() (mm, arm frame), 2026-10-19 fit
|
||||
CALIB = {"arm_yaw_in_base_deg": -95.5, "waist_deg": -20.31, "arm_xy_in_base_m": [0.111, -0.109]} # data/fetch_calib.json
|
||||
WAIST_REF = CALIB["waist_deg"]
|
||||
FLOOR_Z = -985.0 # mm, arm frame at lift 0 (the floor read -1060 at lift 75)
|
||||
TABLE_THICK_MM = 30.0 # table top slab
|
||||
LEG_IN_M, LEG_R_M = 0.05, 0.025 # table legs: this far in from the corners, this thick (radius)
|
||||
HEAD_FOV_DEG = (35.0, 25.0) # head camera: half field of view, horizontal / vertical (estimate)
|
||||
HEAD_NOISE_MM = 8.0 # its detections' noise (calibrated 6 mm median)
|
||||
NAV_MARGIN_M = 0.35 # navigation goal this near an obstacle: "succeeded" without moving (estimate)
|
||||
DEPTH_RANGE_MM = (200.0, 4000.0)
|
||||
DET_RANGE_MM = 3000.0 # the cup is detected up to this far from the camera
|
||||
EDGE_PX = 10 # ... with its centre this far inside the image
|
||||
TEACH_CUP = np.array([-128.0, 628.0, -261.0 - 20.0]) # grasp_teach.json cup (centre at mid height ~ top - 20)
|
||||
# finger landing (docs/10_GRIPPER.md §1, docs/gripper: open gaps belly 96, neck 73, tips 88 mm; neck and tips ~25 mm
|
||||
# either side of the belly centre along the fingers): see fits(). The cup's diameter there = its grip width.
|
||||
TIPS_GAP_MM = 88.0
|
||||
BELLY_GAP_MM = 96.0
|
||||
HOOK_LINES = ((-30.0, 73.0), (25.0, 88.0)) # (mm along the fingers from the belly centre, open gap): neck, tips.
|
||||
# The neck at -30 (tape says ~25 +-5): at -25 most picks of the 85 mm tumbler (grip 81-89) would knock, live it was
|
||||
# picked 10+ times without a turn.
|
||||
CAM_ROT_SD_DEG = 0.4 # per-scene torso extrinsic rotation error, each axis (estimate from 3.3 mm at ~0.35 m)
|
||||
CAM_SCALE_SD = 0.008 # per-scene depth scale error
|
||||
CAM_NOISE_MM = 2.0 # per-frame noise of a detection's centre
|
||||
ARM_XY_ERR_M = 0.03 # true arm base origin off the calibrated one by up to this (samples spread 6-19 cm in x)
|
||||
ARM_YAW_ERR_DEG = 1.0
|
||||
STALL_GAPS = (0.10, 0.25) # m in front of the base where its own safety stop holds it (per scene)
|
||||
|
||||
EVENTS = ("no box for it", "the base went", "an obstacle", "plan refused", "straight move to carry",
|
||||
"turning my waist", "too near me", "asking to move it closer", "not turning", "driving round", "no way there",
|
||||
"not where it should be", "can't turn back", "going closer", "no table in view") # log phrases counted
|
||||
SECTORS = ("beside L", "left", "ahead", "right", "beside R")
|
||||
RANGES = ((0, 450, "too near"), (450, 720, "comfortable"), (720, 900, "far edge"), (900, 99999, "out of reach"))
|
||||
|
||||
|
||||
def sector(bearing):
|
||||
return "beside L" if bearing > 65 else "left" if bearing > 20 else "ahead" if bearing >= -20 else \
|
||||
"right" if bearing >= -65 else "beside R"
|
||||
|
||||
|
||||
def dist_class(d):
|
||||
return next(n for lo, hi, n in RANGES if lo <= d < hi)
|
||||
|
||||
|
||||
def rot2(deg):
|
||||
c, s = math.cos(math.radians(deg)), math.sin(math.radians(deg))
|
||||
return np.array([[c, -s], [s, c]])
|
||||
|
||||
|
||||
COLUMN_BASE_M = np.asarray(CALIB["arm_xy_in_base_m"]) + rot2(CALIB["arm_yaw_in_base_deg"]) @ (HEAD_CENTRE[:2] / 1000)
|
||||
# the waist's axis in the base frame (m): the head's turning centre (the waist and the head share the column, URDF)
|
||||
|
||||
|
||||
def rpy(r, p, y):
|
||||
r, p, y = (math.radians(v) for v in (r, p, y))
|
||||
Rx = np.array([[1, 0, 0], [0, math.cos(r), -math.sin(r)], [0, math.sin(r), math.cos(r)]])
|
||||
Ry = np.array([[math.cos(p), 0, math.sin(p)], [0, 1, 0], [-math.sin(p), 0, math.cos(p)]])
|
||||
Rz = np.array([[math.cos(y), -math.sin(y), 0], [math.sin(y), math.cos(y), 0], [0, 0, 1]])
|
||||
return Rz @ Ry @ Rx
|
||||
|
||||
|
||||
class Clock:
|
||||
"""Virtual time for fetch / skills: time() moves on a little at every read, sleep() moves it on."""
|
||||
def __init__(self):
|
||||
self.t = 1.8e9
|
||||
|
||||
def time(self):
|
||||
self.t += 0.001
|
||||
return self.t
|
||||
|
||||
def sleep(self, s):
|
||||
self.t += max(0.0, s)
|
||||
|
||||
def __getattr__(self, k):
|
||||
return getattr(_time, k)
|
||||
|
||||
|
||||
CLOCK = Clock()
|
||||
W = {} # the world of the scene running in this process
|
||||
fetch = skills = kin = motion = None
|
||||
|
||||
|
||||
# ---------- world geometry ----------
|
||||
def arm_true():
|
||||
"""(yaw deg, origin m) of the true arm base frame in the base frame at the waist now."""
|
||||
w = W["body"][1] - WAIST_REF
|
||||
col = W["col"]
|
||||
return W["yaw0"] + w, col + rot2(w) @ (W["xy0"] - col)
|
||||
|
||||
|
||||
def world_to_arm(p):
|
||||
x, y, th = W["base"]
|
||||
yaw, org = arm_true()
|
||||
b = rot2(-math.degrees(th)) @ (np.asarray(p, float) - [x, y])
|
||||
return rot2(-yaw) @ (b - org) * 1000.0
|
||||
|
||||
|
||||
def arm_to_world(a):
|
||||
x, y, th = W["base"]
|
||||
yaw, org = arm_true()
|
||||
return rot2(math.degrees(th)) @ (rot2(yaw) @ (np.asarray(a, float)[:2] / 1000.0) + org) + [x, y]
|
||||
|
||||
|
||||
def rect_dist(p, r):
|
||||
"""Distance (m) from map point p to rectangle r {c, half, ang} (0 inside)."""
|
||||
q = rot2(-r["ang"]) @ (np.asarray(p, float) - r["c"])
|
||||
d = np.maximum(np.abs(q) - r["half"], 0.0)
|
||||
return float(np.hypot(*d))
|
||||
|
||||
|
||||
def legs(t):
|
||||
"""Map points (m) of a table's four legs (LEG_IN_M in from its corners)."""
|
||||
hx, hy = t["half"][0] - LEG_IN_M, t["half"][1] - LEG_IN_M
|
||||
return [t["c"] + rot2(t["ang"]) @ [sx * hx, sy * hy] for sx in (-1, 1) for sy in (-1, 1)]
|
||||
|
||||
|
||||
def clearance(x, y):
|
||||
"""What the base's sensors and map give (agv.clearance): a table by its legs (the lidar sees under its top), a
|
||||
chair as a whole."""
|
||||
p = np.array([x, y])
|
||||
return min([float(np.linalg.norm(p - l)) - LEG_R_M for t in W["tables"] for l in legs(t)] +
|
||||
[rect_dist(p, b) for b in W["boxes"]] + [5.0])
|
||||
|
||||
|
||||
def solid(x, y):
|
||||
"""Distance (m) to the nearest table top or chair: what the base's own front camera stops at and navigation keeps
|
||||
its margin from."""
|
||||
return min([rect_dist((x, y), r) for r in W["tables"] + W["boxes"]] + [5.0])
|
||||
|
||||
|
||||
# ---------- torso camera ----------
|
||||
def cam_true():
|
||||
"""True camera -> arm transform: the calibrated one with this scene's rotation error about the camera."""
|
||||
T = T_CAL.copy()
|
||||
T[:3, :3] = T_CAL[:3, :3] @ W["cam_err"]
|
||||
return T
|
||||
|
||||
|
||||
def _pix_dirs(u, v):
|
||||
return np.stack([(u - INTR["cx"]) / INTR["fx"], (v - INTR["cy"]) / INTR["fy"], np.ones_like(u, float)], -1)
|
||||
|
||||
|
||||
def render(u, v):
|
||||
"""Depth (mm) at pixels (u, v) as the depth camera reports it: the first surface along each ray from the true
|
||||
camera pose, times the scene's depth scale; 0 where nothing is hit in range."""
|
||||
u, v = np.asarray(u, float), np.asarray(v, float)
|
||||
shape = u.shape
|
||||
d = _pix_dirs(u.ravel(), v.ravel())
|
||||
T = cam_true()
|
||||
o, D = T[:3, 3], d @ T[:3, :3].T # rays in the arm frame; parameter t = depth (cam z)
|
||||
best = np.full(len(D), np.inf)
|
||||
|
||||
def take(t, ok):
|
||||
np.minimum(best, np.where(ok & (t > 0), t, np.inf), out=best)
|
||||
|
||||
with np.errstate(divide="ignore", invalid="ignore"):
|
||||
t = (FLOOR_Z - o[2]) / D[:, 2]
|
||||
take(t, D[:, 2] < 0)
|
||||
for box in W["arm_boxes"]: # oriented boxes (table slabs, a chair) in the arm frame
|
||||
c, ax, half, z0, z1 = box
|
||||
rel_o = np.array([(o[:2] - c) @ ax[0], (o[:2] - c) @ ax[1], o[2]])
|
||||
rel_d = np.stack([D[:, :2] @ ax[0], D[:, :2] @ ax[1], D[:, 2]], -1)
|
||||
lo, hi = np.array([-half[0], -half[1], z0]), np.array([half[0], half[1], z1])
|
||||
t1, t2 = (lo - rel_o) / rel_d, (hi - rel_o) / rel_d
|
||||
tn, tf = np.nanmax(np.minimum(t1, t2), 1), np.nanmin(np.maximum(t1, t2), 1)
|
||||
take(tn, tn <= tf)
|
||||
cup = W.get("arm_cup")
|
||||
if cup is not None:
|
||||
(cx, cy), r, z0, z1 = cup
|
||||
px, py = o[0] - cx, o[1] - cy
|
||||
a = D[:, 0] ** 2 + D[:, 1] ** 2
|
||||
b = 2 * (px * D[:, 0] + py * D[:, 1])
|
||||
disc = b * b - 4 * a * (px * px + py * py - r * r)
|
||||
ts = (-b - np.sqrt(np.maximum(disc, 0))) / (2 * a)
|
||||
z = o[2] + ts * D[:, 2]
|
||||
take(ts, (disc >= 0) & (z >= z0) & (z <= z1))
|
||||
tt = (z1 - o[2]) / D[:, 2]
|
||||
hx, hy = o[0] + tt * D[:, 0] - cx, o[1] + tt * D[:, 1] - cy
|
||||
take(tt, hx * hx + hy * hy <= r * r)
|
||||
best = best * (1.0 + W["scale"])
|
||||
best[(best < DEPTH_RANGE_MM[0]) | (best > DEPTH_RANGE_MM[1])] = 0.0
|
||||
return best.reshape(shape)
|
||||
|
||||
|
||||
class Depth:
|
||||
"""A depth frame that is ray-cast only where the code reads it."""
|
||||
shape = (INTR["height"], INTR["width"])
|
||||
|
||||
def __getitem__(self, key):
|
||||
if not isinstance(key, tuple):
|
||||
return np.zeros((0, self.shape[1]))
|
||||
a, b = key
|
||||
if isinstance(a, slice):
|
||||
vv, uu = np.meshgrid(np.arange(self.shape[0])[a], np.arange(self.shape[1])[b], indexing="ij")
|
||||
else:
|
||||
vv, uu = np.broadcast_arrays(np.asarray(a), np.asarray(b))
|
||||
return render(uu, vv)
|
||||
|
||||
|
||||
def measured(p):
|
||||
"""Where the camera code puts a true arm-frame point: through the true camera, depth scaled, back through T_CAL."""
|
||||
T = cam_true()
|
||||
pc = np.linalg.inv(T) @ np.append(p, 1.0)
|
||||
pc[:3] *= 1.0 + W["scale"]
|
||||
return (T_CAL @ pc)[:3]
|
||||
|
||||
|
||||
def detections():
|
||||
cup = W.get("cup")
|
||||
if cup is None or W["in_hand"]:
|
||||
return []
|
||||
c = np.append(world_to_arm(cup["xy"]), (cup["top"] + cup["table"]) / 2)
|
||||
T = cam_true()
|
||||
pc = np.linalg.inv(T) @ np.append(c, 1.0)
|
||||
if pc[2] <= 0 or np.linalg.norm(pc[:3]) > DET_RANGE_MM:
|
||||
return []
|
||||
u, v = INTR["fx"] * pc[0] / pc[2] + INTR["cx"], INTR["fy"] * pc[1] / pc[2] + INTR["cy"]
|
||||
if not (EDGE_PX <= u < INTR["width"] - EDGE_PX and EDGE_PX <= v < INTR["height"] - EDGE_PX):
|
||||
return []
|
||||
m = measured(c) + np.append(W["rng"].normal(0, CAM_NOISE_MM, 2), 0.0)
|
||||
top = measured(np.array([c[0], c[1], cup["top"]]))[2]
|
||||
return [{"name": "cup", "colour": "white", "score": 0.9, "box": [0, 0, 1, 1],
|
||||
"position_mm": [float(m[0]), float(m[1]), float(m[2])], "top_mm": float(top),
|
||||
"width_mm": cup["grip"] - 8.0 + float(W["rng"].normal(0, 1.0)),
|
||||
"height_mm": cup["top"] - cup["table"] + float(W["rng"].normal(0, 2.0))}]
|
||||
|
||||
|
||||
def head_T(yaw, pitch):
|
||||
"""Head camera -> arm transform at head (yaw, pitch): at the head's centre, looking ahead (arm +y) turned by yaw
|
||||
(+ left) and tilted by pitch (+ up). Its depth frames are not simulated (camview.depth gives None)."""
|
||||
a, b = math.radians(yaw), math.radians(pitch)
|
||||
z = np.array([-math.sin(a) * math.cos(b), math.cos(a) * math.cos(b), math.sin(b)]) # optical axis
|
||||
x = np.array([math.cos(a), math.sin(a), 0.0]) # image right
|
||||
T = np.eye(4)
|
||||
T[:3, :3] = np.stack([x, np.cross(z, x), z], 1)
|
||||
T[:3, 3] = HEAD_CENTRE
|
||||
return T
|
||||
|
||||
|
||||
def head_detections():
|
||||
"""The cup as the head camera sees it (positions in the arm frame, HEAD_NOISE_MM), inside its field of view."""
|
||||
cup = W.get("cup")
|
||||
if cup is None or W["in_hand"]:
|
||||
return []
|
||||
c = np.append(world_to_arm(cup["xy"]), (cup["top"] + cup["table"]) / 2)
|
||||
pc = np.linalg.inv(head_T(*W["body"][2:])) @ np.append(c, 1.0)
|
||||
if pc[2] <= 0 or np.linalg.norm(pc[:3]) > DET_RANGE_MM or \
|
||||
abs(math.degrees(math.atan2(pc[0], pc[2]))) > HEAD_FOV_DEG[0] or \
|
||||
abs(math.degrees(math.atan2(pc[1], pc[2]))) > HEAD_FOV_DEG[1]:
|
||||
return []
|
||||
m = c + np.append(W["rng"].normal(0, HEAD_NOISE_MM, 2), 0.0)
|
||||
return [{"name": "cup", "colour": "white", "score": 0.9, "position_mm": [float(v) for v in m],
|
||||
"top_mm": float(cup["top"]), "width_mm": cup["grip"] - 8.0}]
|
||||
|
||||
|
||||
def refresh():
|
||||
"""The world in the arm frame now (after any base / waist change)."""
|
||||
yaw, org = arm_true()
|
||||
x, y, th = W["base"]
|
||||
boxes = []
|
||||
for r, z0, z1 in [(t, t["z"] - TABLE_THICK_MM, t["z"]) for t in W["tables"]] + \
|
||||
[(b, FLOOR_Z, b["z"]) for b in W["boxes"]]:
|
||||
c = world_to_arm(r["c"])
|
||||
a = math.radians(r["ang"] - math.degrees(th) - yaw)
|
||||
ax = np.array([[math.cos(a), math.sin(a)], [-math.sin(a), math.cos(a)]])
|
||||
boxes.append((c, ax, np.array(r["half"]) * 1000.0, z0, z1))
|
||||
W["arm_boxes"] = boxes
|
||||
cup = W.get("cup")
|
||||
W["arm_cup"] = None if cup is None or W["in_hand"] else \
|
||||
(world_to_arm(cup["xy"]), cup["grip"] / 2.0, cup["table"], cup["top"])
|
||||
|
||||
|
||||
# ---------- arm, gripper, landing ----------
|
||||
def offset_true():
|
||||
"""The grasp point's true offset in the flange frame: skills.GRASP_OFFSET was computed from a cup the camera saw,
|
||||
so it holds the camera's error at the taught cup."""
|
||||
R0 = rpy(*skills.GRASP_RPY)
|
||||
b_teach = measured(TEACH_CUP) - TEACH_CUP
|
||||
return skills.GRASP_OFFSET - R0.T @ b_teach
|
||||
|
||||
|
||||
def hand_now():
|
||||
"""(true grasp point mm, along-finger unit, across unit) of the hand at the joints now."""
|
||||
c = kin.pose(W["J"])
|
||||
R = rpy(*c[3:])
|
||||
g = np.array(c[:3]) + R @ W["off_true"]
|
||||
u = (R @ [0.0, 0.0, 1.0])[:2]
|
||||
u /= np.linalg.norm(u)
|
||||
return g, u, np.array([-u[1], u[0]])
|
||||
|
||||
|
||||
def landing():
|
||||
"""(along, across, ok) mm of the true cup axis from the true grasp point, in the fingers' directions."""
|
||||
g, u, a = hand_now()
|
||||
cup = W["cup"]
|
||||
d = world_to_arm(cup["xy"]) - g[:2]
|
||||
along, across = float(d @ u), float(d @ a)
|
||||
return along, across, fits(cup["grip"], along, across), float(g[2] - (cup["top"] - 40.0))
|
||||
|
||||
|
||||
def fits(D, a, c):
|
||||
"""A cup of diameter D (mm), its axis `a` along the fingers (+ to the tips) and `c` across from the belly centre,
|
||||
passes down between the open hooks: the belly (BELLY_GAP_MM) round it, and its chord at the neck and the tips lines
|
||||
(HOOK_LINES: mm along, gap) inside the gap there (P2's window, docs/gripper tape +-5 mm)."""
|
||||
r = D / 2.0
|
||||
if abs(c) > (BELLY_GAP_MM - D) / 2.0:
|
||||
return False
|
||||
return all(abs(l - a) >= r or 2.0 * math.sqrt(r * r - (l - a) ** 2) <= gap - 2.0 * abs(c) for l, gap in HOOK_LINES)
|
||||
|
||||
|
||||
def f_close(wait=True):
|
||||
rec = W["rec"]
|
||||
if W.get("cup") is not None and not W["hand"]["holding"]:
|
||||
along, across, ok, dz = landing()
|
||||
rec.setdefault("landings", []).append([round(along, 1), round(across, 1), ok, round(dz, 1)])
|
||||
if ok:
|
||||
W["hand"].update(holding=True)
|
||||
W["in_hand"] = True
|
||||
W["held"] = {"h": W["cup"]["top"] - W["cup"]["table"], "below": skills.BELOW_RIM_MM}
|
||||
else:
|
||||
W["cup"] = None # a finger came down on it: knocked over
|
||||
rec["knocked"] = True
|
||||
W["hand"]["closed"] = True
|
||||
refresh()
|
||||
return g_state()
|
||||
|
||||
|
||||
def f_open(wait=True):
|
||||
if W["hand"]["holding"]:
|
||||
g, _, _ = hand_now()
|
||||
held = W["held"]
|
||||
bottom = g[2] + held["below"] - held["h"] # grasp point is `below` under its top
|
||||
xy = arm_to_world(g)
|
||||
on = [t for t in W["tables"] if rect_dist(xy, t) == 0.0]
|
||||
W["rec"]["released"] = {"xy": [round(float(v), 3) for v in xy],
|
||||
"edge_m": round(min((-max(np.abs(rot2(-t["ang"]) @ (xy - t["c"])) - t["half"])
|
||||
for t in on), default=-1.0), 3),
|
||||
"above_table_mm": round(float(bottom - on[0]["z"]), 1) if on else None}
|
||||
W["hand"].update(holding=False, closed=False)
|
||||
refresh()
|
||||
return g_state()
|
||||
|
||||
|
||||
def g_state():
|
||||
h = W["hand"]
|
||||
ai = 3500 if h["holding"] else 4150 if h["closed"] else 160
|
||||
return {"closed": h["closed"], "holding": h["holding"], "object_in_front": False, "ai": [ai], "di": [0],
|
||||
"do": [0, 0], "gap_mm": 80}
|
||||
|
||||
|
||||
def f_move_path(moves, wait=True, queued=False):
|
||||
for t, _ in moves:
|
||||
motion.check(t)
|
||||
W["J"] = motion.nearest(list(t), W["J"])
|
||||
return list(W["J"])
|
||||
|
||||
|
||||
def f_move_linear(target=None, delta=None, speed="slow", wait=True, path_checked=False):
|
||||
if target is None:
|
||||
p = kin.pose(W["J"])
|
||||
target = [p[i] + (delta[i] if i < len(delta) else 0.0) for i in range(3)] + p[3:]
|
||||
j = kin.ik(list(target), W["J"])
|
||||
if j is None:
|
||||
raise motion.MotionError(f"no IK solution for {[round(v, 1) for v in target]}")
|
||||
W["J"] = motion.nearest(j, W["J"])
|
||||
motion.check(W["J"])
|
||||
return list(target)
|
||||
|
||||
|
||||
def f_arm_cmd(name, **a):
|
||||
if name in ("kine_inverse", "kine_forward"):
|
||||
return kin.ask(name, **a)
|
||||
raise AssertionError(f"real arm command in the sweep: {name}")
|
||||
|
||||
|
||||
# ---------- base ----------
|
||||
def f_pose():
|
||||
return tuple(float(v) for v in W["base"])
|
||||
|
||||
|
||||
def _moved(kind, want, before):
|
||||
after = W["base"]
|
||||
W["rec"]["moves"].append([kind, round(float(want), 3),
|
||||
round(float(math.hypot(after[0] - before[0], after[1] - before[1])), 3),
|
||||
round(math.degrees((after[2] - before[2] + math.pi) % (2 * math.pi) - math.pi), 1)])
|
||||
|
||||
|
||||
def f_go_point(x, y, th):
|
||||
before = W["base"].copy()
|
||||
target = np.array([x, y, th], float)
|
||||
ok = solid(x, y) >= NAV_MARGIN_M
|
||||
turn_only = math.hypot(x - before[0], y - before[1]) < 0.02
|
||||
if ok or turn_only:
|
||||
rng = W["rng"]
|
||||
err = np.array([rng.normal(0, 0.01), rng.normal(0, 0.01), rng.normal(0, math.radians(0.5))])
|
||||
W["base"] = target + (err if not turn_only else [0, 0, err[2]])
|
||||
W["nav"] = {"polls": 0}
|
||||
_moved("turn" if turn_only else "nav", math.degrees((th - before[2] + math.pi) % (2 * math.pi) - math.pi)
|
||||
if turn_only else math.hypot(x - before[0], y - before[1]), before)
|
||||
refresh()
|
||||
return True, "OK"
|
||||
|
||||
|
||||
def f_status():
|
||||
nav = W.get("nav")
|
||||
if nav is not None:
|
||||
nav["polls"] += 1
|
||||
st = "running" if nav["polls"] == 1 else "succeeded"
|
||||
if st == "succeeded":
|
||||
W["nav"] = None
|
||||
else:
|
||||
st = "succeeded"
|
||||
x, y, th = W["base"]
|
||||
return {"move_status": st, "charge_state": False, "current_pose": {"x": x, "y": y, "theta": th}}
|
||||
|
||||
|
||||
def f_request(cmd, timeout=3.0):
|
||||
if "joy_control" not in cmd:
|
||||
return {}
|
||||
v = float(cmd.split("linear_velocity=")[1].split("&")[0])
|
||||
now = CLOCK.t
|
||||
joy = W["joy"]
|
||||
if joy["v"]: # the last command drove until now (at most JOY_HOLD_S)
|
||||
dist = joy["v"] * min(now - joy["t"], fetch.JOY_HOLD_S)
|
||||
x, y, th = W["base"]
|
||||
step = math.copysign(0.005, dist)
|
||||
n = int(abs(dist) / 0.005)
|
||||
for _ in range(n):
|
||||
nx, ny = x + step * math.cos(th), y + step * math.sin(th)
|
||||
if step > 0 and solid(nx, ny) < fetch.BASE_HALF_M + W["stall_gap"]:
|
||||
break # the base's own safety stop
|
||||
x, y = nx, ny
|
||||
W["base"] = np.array([x, y, th])
|
||||
joy["want"] += dist
|
||||
refresh()
|
||||
if v == 0.0 and joy["v"]:
|
||||
_moved("straight", joy["want"], joy["start"])
|
||||
joy.update(want=0.0)
|
||||
if v != 0.0 and not joy["v"]:
|
||||
joy["start"] = W["base"].copy()
|
||||
joy.update(v=v, t=now)
|
||||
return {}
|
||||
|
||||
|
||||
# ---------- install the fakes (once per process) ----------
|
||||
def install():
|
||||
global fetch, skills, kin, motion
|
||||
from robot import agv, arm, gripper, head, kinematics, motion as mo
|
||||
from vision import camview, head_cam, objects
|
||||
from manipulation import arm_route, skills as sk
|
||||
from tasks import fetch as fe
|
||||
fetch, skills, kin, motion = fe, sk, kinematics, mo
|
||||
forbid = lambda *a, **k: (_ for _ in ()).throw(AssertionError(f"hardware call in the sweep: {a}"))
|
||||
agv._ask = head._call = gripper._out = forbid
|
||||
arm.cmd = f_arm_cmd
|
||||
tmp = Path(tempfile.mkdtemp(prefix="pick_sweep_"))
|
||||
fe.STATE_FILE, fe.KNOWN_FILE, fe.CALIB_FILE = tmp / "task.json", tmp / "known.json", tmp / "calib.json"
|
||||
fe._write = lambda: None
|
||||
fe.time = sk.time = CLOCK
|
||||
fe.DRIVE_POLL_S = fe.GIVE_POLL_S = 0.0
|
||||
fe.ASK_EVERY_S = 0.0
|
||||
sk.FRESH_WAIT_S = 0.0 # look() keeps its frame gaps: on the virtual clock
|
||||
sk.fresh = lambda path, camera, after=0.0: CLOCK.time()
|
||||
lines = []
|
||||
W["lines"] = lines
|
||||
fe.log = sk.log = arm_route.log = lambda *a: lines.append(" ".join(str(x) for x in a))
|
||||
sk._ask = kinematics.ask
|
||||
agv.pose, agv.status, agv.go_point, agv.request = f_pose, f_status, f_go_point, f_request
|
||||
agv.turn_by = lambda a: f_go_point(W["base"][0], W["base"][1], (W["base"][2] + a + math.pi) % (2 * math.pi) - math.pi)
|
||||
agv.cancel = lambda: W.update(nav=None)
|
||||
agv.clearance = clearance
|
||||
agv.probe = lambda x, y: (clearance(x, y), float("inf"))
|
||||
agv.markers = lambda: []
|
||||
agv.go = forbid
|
||||
head.status = lambda: list(W["body"])
|
||||
head.moveto = lambda pos, **k: (W["body"].__setitem__(slice(None), [max(0.0, min(head.LIFT_MAX_MM, pos[0])),
|
||||
*pos[1:]]), refresh(), {})[-1]
|
||||
gripper.state, gripper.close, gripper.open_ = g_state, f_close, f_open
|
||||
mo.joints = lambda: list(W["J"])
|
||||
mo.tcp = lambda: kinematics.pose(W["J"])
|
||||
mo.move_path, mo.move_linear = f_move_path, f_move_linear
|
||||
mo.stop = lambda: {}
|
||||
camview.want = lambda name: None
|
||||
camview.depth = lambda name, max_age=None: Depth() if name == "torso" else None
|
||||
camview.intrinsics = lambda name: dict(INTR) if name == "torso" else None
|
||||
objects.base_from_camera = lambda: T_CAL
|
||||
objects.latest = lambda camera="torso": {"age_s": 0.0, "objects": detections(), "head_pose": None} \
|
||||
if camera == "torso" else {"age_s": 0.0, "objects": head_detections(), "head_pose": list(W["body"])}
|
||||
head_cam.head_centre = lambda: HEAD_CENTRE.copy()
|
||||
head_cam.base_from_head = head_T
|
||||
|
||||
|
||||
# ---------- scenes ----------
|
||||
def _table_round(cup_xy, n, rng, depth, width, gap, along):
|
||||
"""Rectangle with its near edge (facing the robot along n) `gap` m before the cup, the cup `along` m sideways."""
|
||||
c = cup_xy + n * (depth / 2 - gap) + np.array([-n[1], n[0]]) * along
|
||||
return {"c": c, "half": (depth / 2, width / 2), "ang": math.degrees(math.atan2(n[1], n[0]))}
|
||||
|
||||
|
||||
def make_pick(i, seed):
|
||||
rng = random.Random(seed * 100003 + i)
|
||||
col = COLUMN_BASE_M
|
||||
for _ in range(200):
|
||||
bearing = rng.uniform(-110, 110)
|
||||
dist = rng.uniform(300, 1600)
|
||||
n = np.array([math.cos(math.radians(bearing)), math.sin(math.radians(bearing))])
|
||||
cup = col + n * dist / 1000.0
|
||||
kind = rng.choices(("table", "stand", "table+chair"), (0.6, 0.2, 0.2))[0]
|
||||
if kind == "stand":
|
||||
depth = width = 0.35
|
||||
gap, along = rng.uniform(0.08, 0.17), rng.uniform(-0.08, 0.08)
|
||||
else:
|
||||
depth, width = rng.uniform(0.5, 0.9), rng.uniform(0.6, 1.4)
|
||||
gap, along = rng.uniform(0.04, 0.30), rng.uniform(-width / 2 + 0.1, width / 2 - 0.1)
|
||||
nn = cup / max(np.linalg.norm(cup), 1e-6) # the table faces the base centre
|
||||
table = _table_round(cup, nn, rng, depth, width, gap, along)
|
||||
top = rng.uniform(-330, -180)
|
||||
h = rng.uniform(90, 130)
|
||||
table["z"] = top - h
|
||||
table["half"] = tuple(table["half"])
|
||||
boxes = []
|
||||
if kind == "table+chair":
|
||||
edge = cup - nn * gap
|
||||
ch = edge - nn * rng.uniform(0.25, 0.45) + np.array([-nn[1], nn[0]]) * rng.uniform(-0.15, 0.15)
|
||||
boxes.append({"c": ch, "half": (0.22, 0.22), "ang": rng.uniform(0, 90), "z": table["z"] - 260})
|
||||
W["tables"], W["boxes"] = [table], boxes
|
||||
if solid(0, 0) >= 0.29:
|
||||
break
|
||||
return {"kind": "pick", "i": i, "seed": seed, "variant": kind, "bearing": round(bearing, 1),
|
||||
"dist_mm": round(dist), "cup": {"xy": [float(v) for v in cup], "top": round(top, 1),
|
||||
"table": round(top - h, 1), "grip": round(rng.uniform(61, 92), 1)},
|
||||
"tables": [{**table, "c": [float(v) for v in table["c"]]}],
|
||||
"boxes": [{**b, "c": [float(v) for v in b["c"]]} for b in boxes],
|
||||
"stall_gap": rng.choice(STALL_GAPS), "err_seed": rng.randrange(1 << 30)}
|
||||
|
||||
|
||||
def pick_at(x, y, top, grip=80.0, gap=0.10, height=110.0, variant="table", stall_gap=0.10, err_seed=0, chair=None):
|
||||
"""A fixed pick scene: the cup seen at (x, y) mm in the arm frame (waist at the front, calibrated arm base) with its
|
||||
top at `top`, on a 0.7 x 1.0 m table whose near edge faces the base centre `gap` m before the cup."""
|
||||
yaw, org = CALIB["arm_yaw_in_base_deg"], np.asarray(CALIB["arm_xy_in_base_m"])
|
||||
cup = rot2(yaw) @ (np.array([x, y]) / 1000.0) + org
|
||||
nn = cup / np.linalg.norm(cup)
|
||||
table = _table_round(cup, nn, None, 0.7, 1.0, gap, 0.0)
|
||||
table.update(z=top - height, half=[0.35, 0.5], c=[float(v) for v in table["c"]])
|
||||
rel = cup - COLUMN_BASE_M
|
||||
boxes = [] if chair is None else [{"c": [float(v) for v in cup - nn * (gap + chair)], "half": [0.22, 0.22],
|
||||
"ang": 0.0, "z": table["z"] - 260}]
|
||||
return {"kind": "pick", "i": 0, "seed": 0, "variant": variant,
|
||||
"bearing": round(math.degrees(math.atan2(rel[1], rel[0])), 1), "dist_mm": round(1000 * np.linalg.norm(rel)),
|
||||
"cup": {"xy": [float(v) for v in cup], "top": top, "table": top - height, "grip": grip},
|
||||
"tables": [table], "boxes": boxes, "stall_gap": stall_gap, "err_seed": err_seed}
|
||||
|
||||
|
||||
def make_place(i, seed):
|
||||
rng = random.Random(seed * 200003 + i)
|
||||
for _ in range(200):
|
||||
bearing = rng.uniform(-180, 180)
|
||||
near = rng.uniform(0.32, 2.4) # m from the base centre to the table's near edge
|
||||
n = np.array([math.cos(math.radians(bearing)), math.sin(math.radians(bearing))])
|
||||
depth, width = rng.uniform(0.5, 0.9), rng.uniform(0.6, 1.4)
|
||||
along = rng.uniform(-width / 2 + 0.2, width / 2 - 0.2)
|
||||
table = {"c": n * (near + depth / 2) + np.array([-n[1], n[0]]) * along, "half": (depth / 2, width / 2),
|
||||
"ang": bearing, "z": rng.uniform(-460, -300)}
|
||||
W["tables"], W["boxes"] = [table], []
|
||||
if solid(0, 0) >= 0.29:
|
||||
break
|
||||
h = rng.uniform(90, 130)
|
||||
other = None
|
||||
if rng.random() < 0.25: # another cup already on it, near its front edge
|
||||
other = [float(v) for v in table["c"] - n * (depth / 2 - 0.12)]
|
||||
return {"kind": "place", "i": i, "seed": seed, "bearing": round(bearing, 1), "dist_mm": round(near * 1000),
|
||||
"variant": "table" + ("+cup" if other else ""),
|
||||
"held": {"grip": round(rng.uniform(72, 92), 1), "h": round(h, 1), "table0": -403.0 + 75.0},
|
||||
"tables": [{**table, "c": [float(v) for v in table["c"]]}], "boxes": [], "other": other,
|
||||
"stall_gap": rng.choice(STALL_GAPS), "err_seed": rng.randrange(1 << 30)}
|
||||
|
||||
|
||||
def setup(sc, cam=1.0):
|
||||
nr = np.random.default_rng(sc["err_seed"])
|
||||
lines = W.get("lines", [])
|
||||
lines.clear()
|
||||
W.update(lines=lines, in_hand=False, base=np.zeros(3), body=[0.0, WAIST_REF, 0.0, -5.0], nav=None,
|
||||
joy={"v": 0.0, "t": 0.0, "want": 0.0, "start": np.zeros(3)},
|
||||
J=list(motion.poses()["look"]), hand={"holding": False, "closed": False}, rng=nr,
|
||||
tables=[{**t, "c": np.array(t["c"]), "half": np.array(t["half"])} for t in sc["tables"]],
|
||||
boxes=[{**b, "c": np.array(b["c"]), "half": np.array(b["half"])} for b in sc["boxes"]],
|
||||
stall_gap=sc["stall_gap"], col=COLUMN_BASE_M, rec={"moves": []})
|
||||
e = nr.normal(0, CAM_ROT_SD_DEG * cam, 3)
|
||||
W.update(cam_err=rpy(*e), scale=float(nr.normal(0, CAM_SCALE_SD * cam)),
|
||||
yaw0=CALIB["arm_yaw_in_base_deg"] + (float(nr.uniform(-1, 1)) * ARM_YAW_ERR_DEG if cam else 0.0),
|
||||
xy0=np.asarray(CALIB["arm_xy_in_base_m"]) + (nr.uniform(-1, 1, 2) * ARM_XY_ERR_M if cam else 0.0))
|
||||
W["off_true"] = offset_true()
|
||||
fetch.CALIB_FILE.write_text(json.dumps(CALIB))
|
||||
fetch._stop.clear()
|
||||
fetch._pause.clear()
|
||||
fetch.stay_put = False
|
||||
fetch._state.update(status="running", holding=False, held_object=None, log=[])
|
||||
fetch._rolling.update(v=0.0, t=0.0, sent=0.0)
|
||||
skills._held.clear()
|
||||
if sc["kind"] == "pick":
|
||||
c = sc["cup"]
|
||||
W["cup"] = {"xy": np.array(c["xy"]), "top": c["top"], "table": c["table"], "grip": c["grip"]}
|
||||
else:
|
||||
hd = sc["held"]
|
||||
W["cup"] = None
|
||||
W["held"] = {"h": hd["h"], "below": skills.BELOW_RIM_MM}
|
||||
W["hand"].update(holding=True, closed=True)
|
||||
top0 = hd["table0"] + hd["h"]
|
||||
skills._held.update(top_mm=top0, x=-100.0, y=600.0, yaw=0.0, table=hd["table0"], tips=False,
|
||||
below=skills.BELOW_RIM_MM, base=(5.0, 5.0, 0.0), waist=0.0, lift=0.0,
|
||||
what={"object": "cup", "colour": "white"})
|
||||
fetch._state.update(holding=True, held_object={"object": "cup", "colour": "white"})
|
||||
if sc.get("other"): # a standing cup the camera sees on the table
|
||||
W["cup"] = {"xy": np.array(sc["other"]), "top": sc["tables"][0]["z"] + 100.0,
|
||||
"table": sc["tables"][0]["z"], "grip": 80.0}
|
||||
refresh()
|
||||
|
||||
|
||||
WAIST_TRIES = (0, 15, -15, 30, -30, 45, -45, 60, -60) # deg, waist turns the physical check allows
|
||||
GOALS = ((-100, 580), (-100, 640), (-100, 700), (0, 600), (-200, 620), (100, 600), (-160, 520)) # mm, arm frame
|
||||
|
||||
|
||||
def way_exists(sc):
|
||||
"""A stand for the base from which the arm reaches the cup (grasp turns up to skills.TRUSTED_YAW_DEG, from look,
|
||||
the waist turned by one of WAIST_TRIES), the cup's middle in the torso camera's view there: one of GOALS
|
||||
where skills plans a pick at the cup's height, with the base centre BASE_HALF_M + the stall gap clear of every
|
||||
table top and chair, facing any way (5 deg steps). The physical check behind "out of reach after every way"."""
|
||||
c = sc["cup"]
|
||||
setup(sc, 0.0)
|
||||
W["cup"] = None
|
||||
refresh()
|
||||
cup = np.array(c["xy"])
|
||||
for g in GOALS:
|
||||
obj = {"name": "cup", "colour": "white", "x": float(g[0]), "y": float(g[1]), "top_mm": c["top"],
|
||||
"width_mm": max(c["grip"], 72.0) - 8.0, "height_mm": c["top"] - c["table"], "seen": 8, "spread": 1.0}
|
||||
pc = np.linalg.inv(T_CAL) @ [g[0], g[1], (c["top"] + c["table"]) / 2, 1.0] # seen there by the torso camera?
|
||||
u, v = INTR["fx"] * pc[0] / pc[2] + INTR["cx"], INTR["fy"] * pc[1] / pc[2] + INTR["cy"]
|
||||
if not (EDGE_PX <= u < INTR["width"] - EDGE_PX and EDGE_PX <= v < INTR["height"] - EDGE_PX):
|
||||
continue
|
||||
kw = {"max_yaw": skills.TRUSTED_YAW_DEG} if hasattr(skills, "TRUSTED_YAW_DEG") else {}
|
||||
try:
|
||||
if not skills.reachable_pick(obj, start=list(motion.poses()["look"]), **kw):
|
||||
continue
|
||||
except skills.SkillError:
|
||||
continue
|
||||
xy0 = np.asarray(CALIB["arm_xy_in_base_m"])
|
||||
for w in WAIST_TRIES: # the waist turned w: the arm frame about the column
|
||||
v = rot2(CALIB["arm_yaw_in_base_deg"] + w) @ (np.array(g) / 1000.0) + \
|
||||
COLUMN_BASE_M + rot2(w) @ (xy0 - COLUMN_BASE_M)
|
||||
for phi in range(0, 360, 5):
|
||||
p = cup - rot2(phi) @ v
|
||||
if solid(*p) >= 0.255 + sc["stall_gap"]:
|
||||
return [g[0], g[1], phi, w]
|
||||
return None
|
||||
|
||||
|
||||
def _alarm(*a):
|
||||
raise TimeoutError("scene took too long")
|
||||
|
||||
|
||||
def run_scene(sc, cam=1.0):
|
||||
"""One scene through fetch; the record of what happened."""
|
||||
setup(sc, cam)
|
||||
rec = W["rec"]
|
||||
t0 = _time.time()
|
||||
signal.signal(signal.SIGALRM, _alarm)
|
||||
signal.alarm(600)
|
||||
try:
|
||||
if sc["kind"] == "pick":
|
||||
fetch._pick_here({"object": "cup", "colour": None}, None)
|
||||
rec["result"] = "ok" if W["hand"]["holding"] else "not holding"
|
||||
else:
|
||||
fetch._put_down(None)
|
||||
rel = rec.get("released")
|
||||
rec["result"] = "ok" if rel and rel["edge_m"] >= 0.0 else "released off a table" if rel else "not released"
|
||||
except fetch.Stopped:
|
||||
rec["result"] = "stopped"
|
||||
except (fetch.FetchError, skills.SkillError) as e:
|
||||
rec["result"] = "refused"
|
||||
rec["why"] = str(e.args[0]) if e.args else type(e).__name__
|
||||
except TimeoutError:
|
||||
rec["result"] = "timeout"
|
||||
except Exception as e: # a bug in the code under test (or in the sim)
|
||||
tb = traceback.extract_tb(e.__traceback__)[-1]
|
||||
rec["result"] = "exception"
|
||||
rec["why"] = f"{type(e).__name__}: {e} at {Path(tb.filename).name}:{tb.lineno}"
|
||||
finally:
|
||||
signal.alarm(0)
|
||||
lines = W["lines"]
|
||||
grasp = [l for l in lines if l.startswith("grasp ")]
|
||||
rec["grasp"] = grasp[-1] if grasp else None
|
||||
rec["waist_end"] = round(W["body"][1] - WAIST_REF, 1)
|
||||
rec["log_tail"] = lines[-12:]
|
||||
rec["events"] = {k: n for k in EVENTS if (n := sum(k in l for l in lines))}
|
||||
rec["n_ik_refusals"] = sum("plan refused" in l for l in lines)
|
||||
rec["secs"] = round(_time.time() - t0, 1)
|
||||
if sc["kind"] == "pick" and rec["result"] == "ok":
|
||||
rec["held_at"] = [round(v, 3) for v in arm_to_world(hand_now()[0])]
|
||||
mv = [m for m in rec["moves"]]
|
||||
rec["base_moves"] = len(mv)
|
||||
rec["still"] = sum(1 for m in mv if m[2] < 0.02 and abs(m[3]) < 2.0)
|
||||
rec["repeats"] = sum(1 for a, b in zip(mv, mv[1:]) if a[0] == b[0] and abs(a[1] - b[1]) < 0.02
|
||||
and a[2] < 0.02 and abs(a[3]) < 2.0)
|
||||
if sc["kind"] == "pick" and rec["result"] != "ok" and sc["cup"]["grip"] >= 72.0:
|
||||
lines_kept = list(W["lines"])
|
||||
try:
|
||||
rec["way"] = way_exists(sc)
|
||||
except Exception as e:
|
||||
rec["way"] = f"oracle failed: {e}"
|
||||
W["lines"][:] = lines_kept
|
||||
out = {k: v for k, v in sc.items() if k not in ("tables", "boxes")}
|
||||
out["tables"], out["boxes"] = sc["tables"], sc["boxes"]
|
||||
return {**out, **rec}
|
||||
|
||||
|
||||
def _work(args):
|
||||
sc, cam = args
|
||||
return run_scene(sc, cam)
|
||||
|
||||
|
||||
def _init():
|
||||
install()
|
||||
signal.signal(signal.SIGINT, signal.SIG_IGN)
|
||||
|
||||
|
||||
# ---------- report ----------
|
||||
def parse_grasp(g):
|
||||
"""(turn deg, J5) from skills' "grasp in the hooks, turned -30 deg, wrist J5 +24" line."""
|
||||
if not g:
|
||||
return None, None
|
||||
turn = int(g.split("turned ")[1].split(" ")[0]) if "turned" in g else 0
|
||||
j5 = int(g.split("J5 ")[1])
|
||||
return turn, j5
|
||||
|
||||
|
||||
def why_class(r):
|
||||
c = _why_class(r)
|
||||
if "way" in r and "physical" not in c and "wider" not in c:
|
||||
c += " [no stand sees and reaches it (turn <= 15, lift 0): physical]" if r["way"] is None else " [a stand exists]"
|
||||
return c
|
||||
|
||||
|
||||
def _why_class(r):
|
||||
if r["result"] == "ok":
|
||||
return "ok"
|
||||
if r["kind"] == "pick" and r["cup"]["grip"] < 72.0:
|
||||
return "cup too small (physical)" + ("" if "too small" in (r.get("why") or "") else ", but tried")
|
||||
if r.get("knocked"):
|
||||
if r["cup"]["grip"] > TIPS_GAP_MM:
|
||||
return "knocked over: cup wider than ~88 mm (its chord does not pass the hooks' neck)"
|
||||
return "knocked over (finger landed on the cup)"
|
||||
w = r.get("why") or r["result"]
|
||||
for key, name in (("too small", "cup too small (physical)"), ("too big", "cup too big (physical)"),
|
||||
("too thin", "cup too thin (physical)"), ("can't see", "not seen"),
|
||||
("looked all around", "not seen"), ("still can't reach", "out of reach after every way"),
|
||||
("way to get close", "no way to get close"), ("not answering", "controller not answering"),
|
||||
("free place", "no free place found"), ("safely", "arm move refused (not safe)"),
|
||||
("too close to me", "too near, can't back off"), ("spilling", "arm move refused (spill)")):
|
||||
if key in w:
|
||||
return name
|
||||
return f"{r['result']}: {w[:70]}"
|
||||
|
||||
|
||||
def report(rows, path, title, mtimes):
|
||||
picks = [r for r in rows if r["kind"] == "pick"]
|
||||
places = [r for r in rows if r["kind"] == "place"]
|
||||
out = [f"# {title}", "", f"Written {_time.strftime('%Y-%m-%d %H:%M')}. Code under test (mtime): " +
|
||||
", ".join(f"{k} {v}" for k, v in mtimes.items()), ""]
|
||||
|
||||
def table(rs, rows_key, cols, label):
|
||||
out.append(f"| {label} | " + " | ".join(cols) + " | all |")
|
||||
out.append("|---" * (len(cols) + 2) + "|")
|
||||
for rk in rows_key:
|
||||
cells = []
|
||||
for c in cols + ["all"]:
|
||||
sel = [r for r in rs if r["_s"] == rk and (c == "all" or r["_d"] == c)]
|
||||
cells.append(f"{100 * sum(r['result'] == 'ok' for r in sel) / len(sel):.0f}% ({len(sel)})" if sel else "-")
|
||||
out.append(f"| {rk} | " + " | ".join(cells) + " |")
|
||||
sel = rs
|
||||
out.append("| all | " + " | ".join(
|
||||
(lambda s: f"{100 * sum(r['result'] == 'ok' for r in s) / len(s):.0f}% ({len(s)})" if s else "-")
|
||||
([r for r in sel if c == "all" or r["_d"] == c]) for c in cols + ["all"]) + " |")
|
||||
out.append("")
|
||||
|
||||
for r in picks:
|
||||
r["_s"], r["_d"] = sector(r["bearing"]), dist_class(r["dist_mm"])
|
||||
for r in places:
|
||||
b = r["bearing"]
|
||||
r["_s"] = "behind" if abs(b) > 110 else sector(b)
|
||||
r["_d"] = "in reach" if r["dist_mm"] < 450 else "near (< 1 m)" if r["dist_mm"] < 1000 else "far"
|
||||
if picks:
|
||||
ok = sum(r["result"] == "ok" for r in picks)
|
||||
out += [f"## Picks: {ok}/{len(picks)} ok ({100 * ok / len(picks):.1f} %)", "",
|
||||
"Success by sector (bearing of the cup from the column, + left) and distance from the column (mm):", ""]
|
||||
table(picks, SECTORS, [n for _, _, n in RANGES], "sector")
|
||||
sized = [r for r in picks if r["cup"]["grip"] >= 72]
|
||||
if sized:
|
||||
out.append("Cups 72-92 mm only (thinner ones are refused: MIN_WIDTH):")
|
||||
out.append("")
|
||||
table(sized, SECTORS, [n for _, _, n in RANGES], "sector")
|
||||
ok_rows = [r for r in picks if r["result"] == "ok" or r.get("landings")]
|
||||
turns = collections.defaultdict(list)
|
||||
for r in ok_rows:
|
||||
t, j5 = parse_grasp(r.get("grasp"))
|
||||
if t is None:
|
||||
continue
|
||||
land = (r.get("landings") or [[None]])[-1]
|
||||
turns[("no turn" if t == 0 else f"turn {abs(t)}" + (" L" if t > 0 else " R"))].append((r, land))
|
||||
out += ["## Grasps (pick plans that reached the cup)", "",
|
||||
"| grasp | n | waist turned | finger landings off (along / across, mm, median of abs) | knocked |",
|
||||
"|---|---|---|---|---|"]
|
||||
for k in sorted(turns, key=lambda k: (k != "no turn", k)):
|
||||
v = turns[k]
|
||||
lands = [l for _, l in v if l and l[0] is not None]
|
||||
med = (f"{np.median([abs(l[0]) for l in lands]):.1f} / {np.median([abs(l[1]) for l in lands]):.1f}"
|
||||
if lands else "-")
|
||||
out.append(f"| {k} | {len(v)} | {sum(abs(r['waist_end']) >= 3 for r, _ in v)} | {med} | "
|
||||
f"{sum(1 for l in lands if not l[2])} |")
|
||||
out.append("")
|
||||
mv = [r for r in picks]
|
||||
out += ["## Base behaviour (picks)", "",
|
||||
f"- scenes with a base move: {sum(r['base_moves'] > 0 for r in mv)}; moves in all: "
|
||||
f"{sum(r['base_moves'] for r in mv)}",
|
||||
f"- moves that went nowhere (< 2 cm, < 2 deg): {sum(r['still'] for r in mv)} in "
|
||||
f"{sum(r['still'] > 0 for r in mv)} scenes",
|
||||
f"- the same move repeated after one that went nowhere: {sum(r['repeats'] for r in mv)} in "
|
||||
f"{sum(r['repeats'] > 0 for r in mv)} scenes", ""]
|
||||
if places:
|
||||
ok = sum(r["result"] == "ok" for r in places)
|
||||
out += [f"## Places: {ok}/{len(places)} ok ({100 * ok / len(places):.1f} %)", "",
|
||||
"By the table's bearing and the distance of its near edge from the base centre:", ""]
|
||||
table(places, ("beside L", "left", "ahead", "right", "beside R", "behind"),
|
||||
["in reach", "near (< 1 m)", "far"], "sector")
|
||||
out += [f"- moves that went nowhere: {sum(r['still'] for r in places)} in "
|
||||
f"{sum(r['still'] > 0 for r in places)} scenes; repeated: {sum(r['repeats'] for r in places)}", ""]
|
||||
rel = [r["released"] for r in places if r.get("released") and r["released"]["above_table_mm"] is not None]
|
||||
if rel:
|
||||
hz = [x["above_table_mm"] for x in rel]
|
||||
out += [f"- put down: cup bottom above the table median {np.median(hz):.0f} mm (min {min(hz):.0f}, "
|
||||
f"max {max(hz):.0f}); centre from the table edge median {1000 * np.median([x['edge_m'] for x in rel]):.0f} mm",
|
||||
""]
|
||||
out += ["## By table height (mm, arm frame at lift 0)", "", "| table top | picks ok (72-92 mm cups) | places ok |",
|
||||
"|---|---|---|"]
|
||||
for lo, hi in ((-480, -420), (-420, -380), (-380, -340), (-340, -260)):
|
||||
pk = [r for r in picks if lo <= r["cup"]["table"] < hi and r["cup"]["grip"] >= 72]
|
||||
pl = [r for r in places if lo <= r["tables"][0]["z"] < hi]
|
||||
pct = lambda rs: f"{100 * sum(r['result'] == 'ok' for r in rs) / len(rs):.0f}% ({len(rs)})" if rs else "-"
|
||||
out.append(f"| {lo} .. {hi} | {pct(pk)} | {pct(pl)} |")
|
||||
out += ["", "## Failure classes", ""]
|
||||
for kind, rs in (("pick", picks), ("place", places)):
|
||||
cls = collections.defaultdict(list)
|
||||
for r in rs:
|
||||
c = why_class(r)
|
||||
if c != "ok":
|
||||
cls[c].append(r)
|
||||
for c, v in sorted(cls.items(), key=lambda kv: -len(kv[1])):
|
||||
out.append(f"### {kind}: {c} — {len(v)}")
|
||||
for r in v[:3]:
|
||||
cup = r.get("cup") or r.get("held")
|
||||
out.append(f"- scene {r['i']} (seed {r['seed']}, {r['variant']}): bearing {r['bearing']:+.0f}, "
|
||||
f"{r['dist_mm']} mm, {json.dumps(cup)}, stall gap {r['stall_gap']}, moves "
|
||||
f"{r['moves']}, grasp {r.get('grasp')}, landings {r.get('landings')}")
|
||||
out.append(f" - log: {' | '.join(r['log_tail'][-5:])}")
|
||||
out.append("")
|
||||
Path(path).write_text("\n".join(out) + "\n")
|
||||
|
||||
|
||||
def mtimes():
|
||||
return {f: _time.strftime("%H:%M", _time.localtime((ROOT / f).stat().st_mtime))
|
||||
for f in ("tasks/fetch.py", "manipulation/skills.py", "manipulation/arm_route.py", "robot/kinematics.py")}
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--round", default="1")
|
||||
ap.add_argument("--picks", type=int, default=1500)
|
||||
ap.add_argument("--places", type=int, default=600)
|
||||
ap.add_argument("--seed", type=int, default=1)
|
||||
ap.add_argument("--jobs", type=int, default=max(1, (os.cpu_count() or 2) - 2))
|
||||
ap.add_argument("--cam", type=float, default=1.0, help="camera error times this (0: none)")
|
||||
ap.add_argument("--only", default=None, help="comma list of pick:i / place:i to run (debug)")
|
||||
ap.add_argument("--report", action="store_true", help="only write the .md again from the round's .jsonl")
|
||||
a = ap.parse_args()
|
||||
if a.report:
|
||||
jl = ROOT / "logs" / f"pick_sweep_{a.round}.jsonl"
|
||||
rows = sorted((json.loads(l) for l in open(jl)), key=lambda r: (r["kind"], r["i"]))
|
||||
report(rows, jl.with_suffix(".md"), f"Pick / place sweep, round {a.round} (seed {a.seed})", mtimes())
|
||||
return
|
||||
scenes = [make_pick(i, a.seed) for i in range(a.picks)] + [make_place(i, a.seed) for i in range(a.places)]
|
||||
if a.only:
|
||||
want = {tuple(s.split(":")) for s in a.only.split(",")}
|
||||
scenes = [s for s in scenes if (s["kind"], str(s["i"])) in want]
|
||||
for s in scenes: # numpy -> plain values for the records
|
||||
for t in s["tables"] + s["boxes"]:
|
||||
t["half"] = [float(v) for v in t["half"]]
|
||||
logs = ROOT / "logs"
|
||||
jl, md = logs / f"pick_sweep_{a.round}.jsonl", logs / f"pick_sweep_{a.round}.md"
|
||||
stamp = mtimes()
|
||||
rows = []
|
||||
t0 = _time.time()
|
||||
with mp.get_context("fork").Pool(a.jobs, initializer=_init) as pool, open(jl, "w") as f:
|
||||
for k, r in enumerate(pool.imap_unordered(_work, [(s, a.cam) for s in scenes], chunksize=2)):
|
||||
rows.append(r)
|
||||
f.write(json.dumps(r, default=float) + "\n")
|
||||
if (k + 1) % 100 == 0:
|
||||
print(f"{k + 1}/{len(scenes)} {(_time.time() - t0) / 60:.1f} min", flush=True)
|
||||
rows.sort(key=lambda r: (r["kind"], r["i"]))
|
||||
report(rows, md, f"Pick / place sweep, round {a.round} (seed {a.seed}, camera error x{a.cam:g})",
|
||||
stamp)
|
||||
print(md)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
+45
-19
@@ -1,24 +1,50 @@
|
||||
"""Every first utterance (commands: 'text' with no 'before'; dialogues: first turn 'say') of the blind train sets
|
||||
through quick_answers.kind_of with no history: list the hits for review."""
|
||||
through quick_answers.kind_of with no history: list the hits for review.
|
||||
|
||||
python tests/qa_sweep.py # train, r2-r4, r6, r8, r9, r10 train
|
||||
python tests/qa_sweep.py r9 r10 # only these rounds' train sets
|
||||
"""
|
||||
import glob, importlib, sys
|
||||
sys.path.insert(0, __file__.rsplit("/tests/", 1)[0])
|
||||
from assistant import quick_answers as qa
|
||||
ROUNDS = sys.argv[1:] or ["train", "r2", "r3", "r4", "r6", "r8", "r9", "r10"]
|
||||
from assistant import knowledge
|
||||
_embed, _known = knowledge.embed, {}
|
||||
|
||||
|
||||
def embed(texts): # one batch for all the first words first, then from memory
|
||||
new = [t for t in dict.fromkeys(texts) if t not in _known]
|
||||
if new:
|
||||
_known.update(zip(new, _embed(new)))
|
||||
return [_known[t] for t in texts]
|
||||
|
||||
|
||||
knowledge.embed = embed
|
||||
seen = set()
|
||||
for f in sorted(glob.glob("tests/blind/train/*.py") + glob.glob("tests/blind/r[234]/train/*.py") + glob.glob("tests/blind/r6/train/*.py")):
|
||||
mod = f[:-3].replace("/", ".")
|
||||
if mod.endswith("__init__"): continue
|
||||
m = importlib.import_module(mod)
|
||||
texts = []
|
||||
for c in getattr(m, "CASES", []):
|
||||
if isinstance(c, dict) and c.get("text") and not c.get("before") and not c.get("ctx"):
|
||||
texts.append((c["text"], c.get("expect") or c.get("kind")))
|
||||
for d in getattr(m, "DIALOGUES", []):
|
||||
t = d.get("turns") or []
|
||||
if t and t[0].get("say"):
|
||||
texts.append((t[0]["say"], t[0].get("expect_action")))
|
||||
for t, e in texts:
|
||||
if t in seen: continue
|
||||
seen.add(t)
|
||||
k = qa.kind_of(t)
|
||||
if k: print(f"{k:12} {mod.split('.')[-2]}/{mod.split('.')[-1]:20} {t!r} want={e}")
|
||||
print("texts", len(seen))
|
||||
hits = 0
|
||||
todo = []
|
||||
for r in ROUNDS:
|
||||
for f in sorted(glob.glob("tests/blind/train/*.py" if r == "train" else f"tests/blind/{r}/train/*.py")):
|
||||
mod = f[:-3].replace("/", ".")
|
||||
if mod.endswith("__init__") or "questions_world" in mod: # those are scored by blind_check
|
||||
continue
|
||||
m = importlib.import_module(mod)
|
||||
texts = []
|
||||
for c in getattr(m, "CASES", []):
|
||||
if isinstance(c, dict) and c.get("text") and not c.get("before") and not c.get("ctx"):
|
||||
texts.append((c["text"], c.get("expect") or c.get("kind")))
|
||||
for d in getattr(m, "DIALOGUES", []):
|
||||
t = d.get("turns") or []
|
||||
if t and t[0].get("say"):
|
||||
texts.append((t[0]["say"], t[0].get("expect_action")))
|
||||
for t, e in texts:
|
||||
if t not in seen:
|
||||
seen.add(t)
|
||||
todo.append((t, e, f"{r}/{mod.split('.')[-1]}"))
|
||||
embed([qa._core(qa._tidy(t)) for t, _, _ in todo])
|
||||
for t, e, where in todo:
|
||||
k = qa.kind_of(t)
|
||||
if k:
|
||||
hits += 1
|
||||
print(f"{k:12} {where:22} {t!r} want={e}")
|
||||
print("texts", len(seen), "quick", hits)
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
"""Blind set llm_reasoning (round r13 on, tests/blind/README.md "## r13"): requests and questions no fixed rule
|
||||
covers, scored through the real route and the real model. Each case goes the way lumi.answer() sends it: the voice
|
||||
settings, then the rules (tests/command_check.rules: drive words, lumi.route, chains, stop), then the model
|
||||
(Brain.respond_stream with the state line, the reply read through to its end). The outcome is scored like a command
|
||||
case (any listed outcome is right; a motion not listed is "motion", the worst) and a model reply also against the
|
||||
case's must / must_not. A rule's fixed line is not checked against must (it is not the model's).
|
||||
|
||||
.venv/bin/python tests/reasoning_check.py # r13 train, every case (long: ~2400 model turns)
|
||||
.venv/bin/python tests/reasoning_check.py --sample 120 # 120 cases, seeded (the same each run)
|
||||
.venv/bin/python tests/reasoning_check.py --kind cant,riddle --sample 60 --tag t1a
|
||||
.venv/bin/python tests/reasoning_check.py --rules # no model: what the rules leave is "llm?"
|
||||
.venv/bin/python tests/reasoning_check.py --failed --tag t1a # only the cases not right in that tag's last run
|
||||
|
||||
-> logs/reasoning_<round>_<tag>.md / .json. Only train sets: held-out sets are never read here.
|
||||
"""
|
||||
import collections
|
||||
import importlib
|
||||
import json
|
||||
import pathlib
|
||||
import random
|
||||
import re
|
||||
import sys
|
||||
import time
|
||||
|
||||
from assistant import brain, voice_words
|
||||
from tests import blind_check as bc
|
||||
from tests import command_check
|
||||
|
||||
ROOT = pathlib.Path(__file__).resolve().parents[1]
|
||||
SEED = 131
|
||||
VOICE = {("volume", 1): "louder", ("volume", -1): "quieter", ("speed", 1): "faster", ("speed", -1): "slower"}
|
||||
|
||||
|
||||
def model_turn(b, text, state, mk):
|
||||
"""(route, action line, the whole reply) from the model, acted on like lumi.answer() (command_check.llm, with
|
||||
every sentence of the reply)."""
|
||||
brain.FORCED_LANG["lang"] = "ko" if brain.HANGUL.search(text) else "en"
|
||||
text = brain.self_correct(text, mk) or text
|
||||
gen = b.respond_stream(text, mk, now=command_check.HOLDING_NOW if state == "holding" else command_check.NOW)
|
||||
head, words = next(gen), list(gen)
|
||||
first = words[0] if words else ""
|
||||
if head["action"] == "none" and brain.promised(first) in ("sing", "wave") and \
|
||||
not (brain.not_an_order(text, asked=False) and brain.promised(first) == "wave"):
|
||||
head = {"action": brain.promised(first), "target": ""}
|
||||
target = (brain._mentions(text, mk).get("object") or "") if head["action"] == "receive" else head["target"]
|
||||
return command_check.act(head["action"], target, first, state), f"{head['action']} {target}".strip(), " ".join(words)
|
||||
|
||||
|
||||
def score(c, use_llm):
|
||||
b = brain.Brain()
|
||||
for visitor, said in c["ctx"]:
|
||||
b.history.append((visitor, said))
|
||||
if c["before"]:
|
||||
b.history.append(tuple(c["before"]))
|
||||
mk, text, state = bc.marks_of(c), c["text"], c["state"]
|
||||
brain.FORCED_LANG["lang"] = c["lang"] if c["lang"] in ("en", "ko") else "ko" if brain.HANGUL.search(text) else "en"
|
||||
raw = reply = ""
|
||||
by = "rules"
|
||||
voice = voice_words.read(text, c["before"][1] if c["before"] else "")
|
||||
try:
|
||||
got = "voice " + VOICE[voice] if voice else command_check.rules(text, state, mk, b)
|
||||
except command_check.NoLLM:
|
||||
got = None
|
||||
if got is None:
|
||||
if not use_llm:
|
||||
return {"verdict": "llm?", "by": "-", "got": "llm?", "raw": "", "reply": "", "probs": []}
|
||||
got, raw, reply = model_turn(b, text, state, mk)
|
||||
by = "llm"
|
||||
got = command_check.refused(got)
|
||||
v = command_check.ok(c["expect"], got)
|
||||
v = "right" if v == "right" else "motion" if v == "wrong" and bc.MOTION.match(got) else "wrong"
|
||||
probs = []
|
||||
if by == "llm":
|
||||
probs = [f"missing /{p}/" for p in c["must"] if not re.search(p, reply, re.I)] + \
|
||||
[f"has /{p}/" for p in c["must_not"] if re.search(p, reply, re.I)]
|
||||
if probs and v == "right":
|
||||
v = "wrong"
|
||||
return {"verdict": v, "by": by, "got": got, "raw": raw, "reply": reply, "probs": probs}
|
||||
|
||||
|
||||
def key(c):
|
||||
return f"{c['text']}|{c['state']}|{c['before']}|{c['ctx']}"
|
||||
|
||||
|
||||
def report(rows, out, title, secs):
|
||||
def table(field):
|
||||
t = collections.defaultdict(collections.Counter)
|
||||
for r in rows:
|
||||
t[r[field]][r["verdict"]] += 1
|
||||
t[r[field]]["n"] += 1
|
||||
lines = [f"| {field} | right | wrong | motion | llm? |", "|---|---|---|---|---|"]
|
||||
for k in sorted(t):
|
||||
n = t[k]["n"]
|
||||
lines.append(f"| {k} | {t[k]['right']}/{n} ({100 * t[k]['right'] // n} %) | {t[k]['wrong']} | "
|
||||
f"{t[k]['motion']} | {t[k]['llm?']} |")
|
||||
return "\n".join(lines)
|
||||
n = len(rows)
|
||||
right = sum(r["verdict"] == "right" for r in rows)
|
||||
md = [f"# {title} ({time.strftime('%Y-%m-%d %H:%M')}, model {brain.MODEL}, {secs:.0f} s)", "",
|
||||
f"right {right}/{n} ({100 * right // max(n, 1)} %), motions {sum(r['verdict'] == 'motion' for r in rows)}, "
|
||||
f"by the model {sum(r['by'] == 'llm' for r in rows)}", "", table("kind"), "", table("lang"), "",
|
||||
table("level"), "", "## Not right", ""]
|
||||
for r in rows:
|
||||
if r["verdict"] != "right":
|
||||
md.append(f"- {r['verdict'].upper()}: [{r['kind']}:{r['meaning']}, {r['level']}, {r['state']}] "
|
||||
f"{r['text']!r} -> {r['got']} (want {r['expect']}) {r['reply'][:150]!r} {r['probs']}")
|
||||
out.with_suffix(".md").write_text("\n".join(md) + "\n")
|
||||
out.with_suffix(".json").write_text(json.dumps(rows, ensure_ascii=False, indent=1))
|
||||
print("\n".join(md[:4]))
|
||||
|
||||
|
||||
def main(args):
|
||||
def opt(name, default=None):
|
||||
return args[args.index(name) + 1] if name in args else default
|
||||
rnd, tag = opt("--round", "r13"), opt("--tag", "")
|
||||
cases = importlib.import_module(f"tests.blind.{rnd}.train.llm_reasoning").CASES
|
||||
kinds = opt("--kind")
|
||||
if kinds:
|
||||
cases = [c for c in cases if c["kind"] in kinds.split(",")]
|
||||
out = ROOT / "logs" / (f"reasoning_{rnd}_{tag}" if tag else f"reasoning_{rnd}")
|
||||
if "--failed" in args:
|
||||
bad = {r["key"] for r in json.loads(out.with_suffix(".json").read_text()) if r["verdict"] != "right"}
|
||||
cases = [c for c in cases if key(c) in bad]
|
||||
if opt("--sample"):
|
||||
cases = random.Random(SEED).sample(cases, min(int(opt("--sample")), len(cases)))
|
||||
if opt("--limit"):
|
||||
cases = cases[:int(opt("--limit"))]
|
||||
bc.SCENE["now"] = None # no camera picture: seeing answers "can't see" where it looks
|
||||
t0, rows = time.time(), []
|
||||
for i, c in enumerate(cases, 1):
|
||||
try:
|
||||
r = score(c, "--rules" not in args)
|
||||
except Exception as e: # noqa: BLE001 - a crash fails that case
|
||||
r = {"verdict": "wrong", "by": "-", "got": "error", "raw": "", "reply": repr(e), "probs": []}
|
||||
rows.append({"key": key(c), **{k: c[k] for k in ("text", "lang", "level", "kind", "meaning", "state", "expect")},
|
||||
**r})
|
||||
print(f"{i}/{len(cases)} {r['verdict']:6} [{c['kind']}] {c['text'][:60]!r} -> {r['got']} "
|
||||
f"{r['reply'][:80]!r} {r['probs']}", flush=True)
|
||||
report(rows, out, f"llm_reasoning {rnd} train{' ' + tag if tag else ''}", time.time() - t0)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main(sys.argv[1:])
|
||||
@@ -0,0 +1,70 @@
|
||||
"""Self-check of the arm and hand wordings of the example bank (assistant/bank_words/arm.py, arm_more.py):
|
||||
python tests/test_arm_bank.py
|
||||
|
||||
Needs the embedding server (assistant/knowledge.embed starts it); nothing moves. Every arm / hand capability said in
|
||||
new ways (English and Korean at every level) reads as that one motion or as nothing (the LLM then decides); hard
|
||||
negatives (questions, remarks, past, negations, gestures Lumi has none of) and side words never become another motion."""
|
||||
from assistant import intent_bank as ib
|
||||
|
||||
M = ["home", "dock2", "booth_A", "stage", "coffee_corner", "p3"]
|
||||
|
||||
READS = [ # (words, holding, (action, target))
|
||||
("let's shake on it", False, ("wave", "")),
|
||||
("give the kids a wave", False, ("wave", "")),
|
||||
("손 살랑살랑 흔들어 주세요", False, ("wave", "")),
|
||||
("악수 한번 하시지요", False, ("wave", "")),
|
||||
("할아버지께 손 흔들어 드려", False, ("wave", "")),
|
||||
("악수 하입시더", False, ("wave", "")),
|
||||
("악수 한번 합시다", False, ("wave", "")),
|
||||
("extend your hand to me", False, ("arm", "reach")),
|
||||
("손 내미십시오", False, ("arm", "reach")),
|
||||
("손 좀 내어 주시겠어요?", False, ("arm", "reach")),
|
||||
("팔 쭉 내밀어 보래이", False, ("arm", "reach")),
|
||||
("stow your arm", False, ("arm", "fold")),
|
||||
("팔 거두어 주십시오", False, ("arm", "fold")),
|
||||
("팔 원상복구 해 줘", False, ("arm", "fold")),
|
||||
("open the claw", False, ("arm", "open")),
|
||||
("그리퍼 활짝 열어 주세요", False, ("arm", "open")),
|
||||
("clamp your gripper", False, ("arm", "close")),
|
||||
("주먹 쥐시게", False, ("arm", "close")),
|
||||
("scoop up the bottle", False, ("pick", "bottle")),
|
||||
("컵 집으시게", False, ("pick", "cup")),
|
||||
("fetch me that cup", False, ("fetch", "fetch me that cup")),
|
||||
("컵 챙겨 와 주세요", False, ("fetch", "컵 챙겨 와 주세요")),
|
||||
]
|
||||
NOT = [ # (words, holding, motions it must not be): a side word or a hand word is never a drive / turn / look
|
||||
("pick up the cup on your left", False, ("turn", "move", "look", "go_to", "wave", "arm")),
|
||||
("오른쪽에 있는 컵 집어 줘", False, ("turn", "move", "look", "go_to", "wave", "arm")),
|
||||
("왼쪽 테이블에 내려놔", True, ("turn", "move", "look", "go_to", "pick")),
|
||||
("put it down to your right", True, ("turn", "move", "look", "go_to", "pick")),
|
||||
("p3에 내려놔 줘", True, ("go_to", "move", "turn")),
|
||||
]
|
||||
NEVER = [ # no motion at all from the bank
|
||||
("your arm reached the cup", False), ("악수는 됐어", False), ("박수 쳐 줘", False), ("clap your hands", False),
|
||||
("give me a thumbs up", False), ("손가락 하트 해 줘", False), ("put your hands together for lumi", False),
|
||||
("the cup on your left is mine", False), ("왼쪽에 컵 있어", False), ("you picked the wrong cup", False),
|
||||
("팔이 어디까지 닿아?", False), ("why are you waving", False), ("아까 악수했잖아", False),
|
||||
("shake your head", False), ("pick up the pace", False), ("give it up for lumi", False),
|
||||
]
|
||||
|
||||
|
||||
def main():
|
||||
bad = []
|
||||
for words, holding, want in READS:
|
||||
got = ib.read(words, M, holding)
|
||||
if got != want:
|
||||
bad.append(f"{words!r}: {got}, want {want}")
|
||||
for words, holding, nots in NOT:
|
||||
got = ib.read(words, M, holding)
|
||||
if got and got[0] in nots:
|
||||
bad.append(f"{words!r}: {got}, must not be {nots}")
|
||||
for words, holding in NEVER:
|
||||
got = ib.read(words, M, holding)
|
||||
if got:
|
||||
bad.append(f"{words!r}: {got}, must be nothing")
|
||||
print("\n".join(bad) or f"arm bank ok: {len(READS) + len(NOT) + len(NEVER)} cases")
|
||||
return not bad
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(0 if main() else 1)
|
||||
+284
-3
@@ -1,8 +1,13 @@
|
||||
"""The dashboard's Command box (/tasks/parse) reads a sentence exactly as voice does (Lumi.answer, both on
|
||||
lumi.route): the same plan for the same words, English and Korean. No robot, no LLM (rules only on both sides):
|
||||
python tests/test_command_box.py"""
|
||||
python tests/test_command_box.py (-v: every reading)
|
||||
Then what the box plans for hundreds of cup / delivery commands, held or not, at every Korean speech level and in
|
||||
English the same ways (the owner's 2026-10-26 18:40 list first), and every stop word stopping a task."""
|
||||
import re
|
||||
import types
|
||||
|
||||
re._MAXCACHE = 100000 # the readers use more patterns than re's cache holds: 3x faster
|
||||
|
||||
from assistant import brain, lumi
|
||||
from tasks import fetch
|
||||
|
||||
@@ -26,6 +31,9 @@ SENTENCES = [
|
||||
# read by the intent bank or the chain's per-part reading (no keyword rule), answered out loud
|
||||
"왼쪽 쳐다봐", "오른쪽을 보십시오", "시선 좀 돌려 줘", "고개 숙이고 몸 좀 내려", "so glance to your right and then look up",
|
||||
"나 쳐다보고 follow me", "speak louder", "목소리 좀 줄여 줘", "더", "one more time", "what do you see?", "what are you doing?",
|
||||
# the owner's 18:40 misses, read the same by voice
|
||||
"컵 챙겨서 exit 가서 기다려", "컵 들고 p5 가서 기다려", "exit에 컵 갖다 놔", "컵 놔", "컵 가지고 출구로 가", "put the cup at exit",
|
||||
"go to exit with the cup", "p5 가서 누가 컵 줄 때까지 기다려", "야 루미, 오른쪽 보고 손 흔들어라", "stop it", "그만두세요",
|
||||
]
|
||||
|
||||
# ---------- voice: Lumi.answer with every handler recorded, nothing moves, no LLM ----------
|
||||
@@ -58,8 +66,8 @@ def quick(text, rule=None):
|
||||
return False
|
||||
if rule[0] == "fetch":
|
||||
return rec("fetch")
|
||||
if rule[0] in ("weather", "search"):
|
||||
return rec("talk")
|
||||
if rule[0] in ("weather", "search") or rule[0] == "put":
|
||||
return rec("talk") # put with the hand empty (voice: idle here): "my hand is empty"
|
||||
s = steps_of(rule)
|
||||
return rec("steps", s) if s else rec("command", rule[0])
|
||||
|
||||
@@ -137,4 +145,277 @@ for t in SENTENCES:
|
||||
print(f"DIFFERENT {t!r}\n voice {v}\n box {b}")
|
||||
print(f"{len(SENTENCES) - len(bad)}/{len(SENTENCES)} the same by voice and in the Command box")
|
||||
assert not bad
|
||||
|
||||
|
||||
# ---------- what the box plans: one short line per reading ----------
|
||||
HELD = [False]
|
||||
fetch.check_hand = lambda: HELD[0]
|
||||
fetch.state = lambda: {"holding": HELD[0]}
|
||||
fetch.held_name = lambda lang="en": "the white cup"
|
||||
|
||||
|
||||
def where(p):
|
||||
if isinstance(p, dict) and "name" in p:
|
||||
return " ".join(x for x in (p.get("side"), p.get("colour"), p["name"].replace("dining table", "table")) if x)
|
||||
return p.get("marker") if isinstance(p, dict) else str(p)
|
||||
|
||||
|
||||
def plan(text, held=False):
|
||||
""""pick cup; go exit; wait", "fetch cup here>exit place", "carry p5 hold", "place left table", "give", "empty"
|
||||
(my hand is empty), "ask: <the question>" (a place not on the map), "talk" (the LLM / the assistant answers)."""
|
||||
HELD[0] = held
|
||||
r = server.task_parse(server.ParseBody(text=text))
|
||||
a = r["action"]
|
||||
if a == "steps":
|
||||
return "; ".join(" ".join(str(where(v)) for k, v in st.items() if v not in (None, False, "") and k != "from_hand")
|
||||
for st in r["steps"]) + (" !" + r["problems"][0] if r["problems"] else "")
|
||||
if a == "fetch":
|
||||
t = r["task"]
|
||||
return " ".join(x for x in ("fetch", t["colour"], t["object"], f"{where(t['source'])}>{where(t['dest'])}", t["finish"]) if x)
|
||||
if a in ("place", "give"):
|
||||
return a + (" on " + where(r["task"]["on"]) if (r.get("task") or {}).get("on") else "")
|
||||
if a == "carry":
|
||||
return f"carry {where(r['task']['dest'])} {r['task'].get('then') or 'hold'}"
|
||||
if a == "command":
|
||||
return "stop" if r["sentence"] == "Stop." else "chain" if "parts" in r else \
|
||||
"rule " + " ".join(x for x in r["rule"] if x) if "rule" in r else "talk"
|
||||
p = r.get("problems") or []
|
||||
return "empty" if p and "hand is empty" in p[0] else "ask: " + p[0] if p else \
|
||||
"ask: " + r["sentence"] if r.get("talk") == "refuse" else "talk"
|
||||
|
||||
|
||||
def ko_levels(v, h):
|
||||
"""A request in every Korean speech level: v the 반말 verb ("놔"), h the stem of -세요 / -십시오 ("놓으")."""
|
||||
return [v, f"{v} 줘", f"{v}요", f"{v} 주세요", f"{h}세요", f"{h}십시오", f"{v} 주십시오", f"{v} 주시겠어요?",
|
||||
f"{v} 주시겠습니까?", f"{v} 줄래?", f"{v} 주실래요?", f"{v} 주게", f"{v} 주이소", f"{v} 도", f"{v} 주라",
|
||||
f"{v} 줘잉", f"{v} 주셨으면 해요", f"{v} 주시면 감사하겠습니다", f"{v} 주면 안 될까요?", f"{v} 주시면 안 될까요?",
|
||||
f"{v} 주실 수 있나요?", f"{v}줘", f"{v} 쫌 줘", f"{v} 줘 봐", f"{v} 주시지요", f"{v} 주시오"]
|
||||
|
||||
|
||||
EN_LEVELS = ["{x}", "please {x}", "{x}, please", "can you {x}?", "could you {x}?", "would you {x}?", "will you {x}?",
|
||||
"could you please {x}?", "can u {x}", "I'd like you to {x}", "I need you to {x}", "I want you to {x}",
|
||||
"hey Lumi, {x}", "Lumi, {x} now", "go ahead and {x}", "kindly {x}", "if you don't mind, {x}",
|
||||
"would you be so kind as to {x}?", "do me a favor and {x}", "yo, {x}", "{x} pls", "{x} real quick",
|
||||
"can you {x} for me please?", "{x}, thanks", "would it be possible to {x}?", "Lumi could you {x}"]
|
||||
VERB = {"wait": ("기다려", "기다리"), "put_at": ("갖다 놔", "갖다 놓으"), "put": ("놔", "놓으"), "pick": ("집어", "집으"),
|
||||
"bring": ("가져와", "가져오"), "down": ("내려놔", "내려놓으"), "go": ("가", "가"), "take": ("가져가", "가져가"),
|
||||
"hand": ("건네", "건네주")}
|
||||
KO_T = [ # (words with {} for the verb, verb, holding, plan)
|
||||
("컵 들고 exit 가서 {}", "wait", False, "pick cup; go exit; wait"),
|
||||
("컵 챙겨서 p5 가서 {}", "wait", False, "pick cup; go p5; wait"),
|
||||
("exit에 컵 {}", "put_at", False, "fetch cup here>exit place"),
|
||||
("컵을 p3 테이블에 {}", "put", False, "fetch cup here>p3 place"),
|
||||
("컵 {}", "pick", False, "pick cup"),
|
||||
("p1에서 컵 {}", "bring", False, "fetch cup p1>here hold"),
|
||||
("컵 {}", "down", True, "place"),
|
||||
("왼쪽 테이블에 {}", "put", True, "place left table"),
|
||||
("그거 나한테 {}", "hand", True, "give"),
|
||||
("p5로 {}", "take", True, "carry p5 hold"),
|
||||
("p5로 {}", "go", False, "go p5"),
|
||||
("컵 {}", "put", False, "empty"),
|
||||
("그거 {}", "put", True, "place"),
|
||||
]
|
||||
EN_T = [
|
||||
("take the cup to exit and wait there", False, "pick cup; go exit; wait"),
|
||||
("grab the cup, go to p5 and wait", False, "pick cup; go p5; wait"),
|
||||
("put the cup at exit", False, "fetch cup here>exit place"),
|
||||
("put the cup on the table at p3", False, "fetch cup here>p3 place"),
|
||||
("pick up the cup", False, "pick cup"),
|
||||
("bring me the cup from p1", False, "fetch cup p1>here hold"),
|
||||
("put the cup down", True, "place"),
|
||||
("put it on the table on your left", True, "place left table"),
|
||||
("hand it to me", True, "give"),
|
||||
("take it to p5", True, "carry p5 hold"),
|
||||
("go to p5", False, "go p5"),
|
||||
("put the cup down", False, "empty"),
|
||||
("put that down", True, "place"),
|
||||
]
|
||||
NO_PLACE = "ask: I don't have a place called {} on this map. I know: " + ", ".join(M) + "."
|
||||
READ = [ # the owner's Korean cup / delivery list (2026-10-26 18:40), then more of the same kinds
|
||||
("컵 들고 exit 가서 건네줘", False, "pick cup; go exit; give"),
|
||||
("컵 가지고 exit로 가서 사람한테 줘", False, "pick cup; go exit; give"),
|
||||
("컵 집어서 exit에 갖다 줘", False, "pick cup; go exit; give"),
|
||||
("컵 챙겨서 exit 가서 기다려", False, "pick cup; go exit; wait"),
|
||||
("컵 들고 exit로 가 줘", False, "fetch cup here>exit hold"),
|
||||
("컵 들고 exit 가", False, "pick cup; go exit"),
|
||||
("exit로 컵 가져다 줘", False, "pick cup; go exit; give"),
|
||||
("exit에 컵 갖다 놔", False, "fetch cup here>exit place"),
|
||||
("컵을 exit 테이블에 놔 줘", False, "fetch cup here>exit place"),
|
||||
("p1에서 컵 가져와", False, "fetch cup p1>here hold"),
|
||||
("p1 가서 컵 가져와", False, "fetch cup p1>here hold"),
|
||||
("p1에 있는 컵 가져다 줘", False, "fetch cup p1>here hold"),
|
||||
("p1에서 빨간 컵 집어서 p5로 가져가", False, "fetch red cup p1>p5 hold"),
|
||||
("빨간 컵 집어서 p5로 가져가 줘", False, "fetch red cup here>p5 hold"),
|
||||
("컵 집어 주게", False, "pick cup"), ("컵 집어도", False, "pick cup"), ("컵 좀 집어 주이소", False, "pick cup"),
|
||||
("컵 픽업해 줘", False, "pick cup"), ("컵 잡아", False, "pick cup"), ("컵 들어", False, "pick cup"),
|
||||
("저 컵 가져와", False, "fetch cup here>here hold"),
|
||||
("그 컵 좀 가져다 주세요", False, "pick cup; give"), ("컵 가져다 주실래요?", False, "pick cup; give"),
|
||||
("컵 가져다 주시겠습니까?", False, "pick cup; give"), ("컵 갖다 주게", False, "pick cup; give"),
|
||||
("컵 갖고 와", False, "fetch cup here>here hold"), ("물병 가져와", False, "fetch bottle here>here hold"),
|
||||
("바나나 집어서 p3로 가져가", False, "fetch banana here>p3 hold"),
|
||||
("사과 p2에 놔", False, "fetch apple here>p2 place"),
|
||||
("컵 들고 p5 가서 민수한테 줘", False, "pick cup; go p5; give 민수"),
|
||||
("컵 들고 p5 가서 기다려", False, "pick cup; go p5; wait"),
|
||||
("컵 들고 p5까지 가서 거기 있는 사람한테 줘", False, "pick cup; go p5; give"),
|
||||
("컵 들고 exit 가서 건네주고 돌아와", False, "chain"),
|
||||
("컵 집고 p3로 가서 테이블에 놔", False, "fetch cup here>p3 place"),
|
||||
("p9 가서 컵 받아서 p1으로 가져와", False, "go p9; receive cup; go p1"),
|
||||
("이 컵 받아", False, "receive cup"), ("이거 받아서 exit에 갖다 줘", False, "receive; go exit; give"),
|
||||
("컵 내려놔", False, "empty"), ("컵 놔", False, "empty"), ("컵 내려놔", True, "place"), ("컵 놔", True, "place"),
|
||||
("컵 줘", False, "pick cup; give"), ("컵 나한테 줘", False, "pick cup; give"), ("그거 나한테 건네줘", False, "empty"),
|
||||
("p2 테이블에 있는 컵 가져와", False, "fetch cup p2>here hold"),
|
||||
("exit 갔다가 p9로 가", False, "go exit; go p9"), ("p5로 가 줘", False, "go p5"),
|
||||
("p5로 가서 30초 기다렸다가 돌아와", False, "go p5; wait 30.0; go here"),
|
||||
("컵 들고 exit 가서 줘 그리고 집에 가", False, "pick cup; go exit; give; go home"),
|
||||
("exit 포인트로 컵 가져가", False, "fetch cup here>exit hold"), ("엑싯으로 컵 가져가", False, "fetch cup here>exit hold"),
|
||||
("컵 가지고 출구로 가", False, NO_PLACE.format("출구")), # 출구 is no marker: asked, never taken for "exit"
|
||||
("출구로 가", False, NO_PLACE.format("출구")), ("컵 들고 화장실로 가 줘", False, NO_PLACE.format("화장실")),
|
||||
("엑시트로 가", False, "go exit"),
|
||||
# put / place words and sides, held
|
||||
("왼쪽 테이블에 놔", True, "place left table"), ("오른쪽에 내려놔 주세요", True, "place right table"),
|
||||
("put it on the right side", True, "place right table"), ("put it on the table on your left", True, "place left table"),
|
||||
("테이블에 놔", True, "place on table"), ("흰 테이블에 올려놔 주세요", True, "place on white table"),
|
||||
("put it on the white table", True, "place on white table"), ("그거 놔 줘", True, "place"),
|
||||
("그거 놔 쫌 줘", True, "place"), ("put it down", True, "place"), ("set it down please", True, "place"),
|
||||
("p5로 가 줘", True, "carry p5 hold"), ("그거 p5로 옮겨 줘", True, "carry p5 hold"), ("p5로 들고 가", True, "carry p5 hold"),
|
||||
("bring it to p5", True, "carry p5 hold"), ("carry it to p5", True, "carry p5 hold"),
|
||||
("p5에 가져다 줘", True, "carry p5 give"), ("take it to p5 and give it to them", True, "go p5; give"),
|
||||
("p5 테이블에 놔 줘", True, "carry p5 place"), ("put it on the table at p5", True, "carry p5 place"),
|
||||
("give it to me", True, "give"), ("나한테 줘", True, "give"), ("저한테 주세요", True, "give"),
|
||||
# English the same
|
||||
("take the cup, go to exit and hand it over", False, "pick cup; go exit; give"),
|
||||
("grab the cup and wait at p5", False, "pick cup; go p5; wait"),
|
||||
("put the cup at p3", False, "fetch cup here>p3 place"), ("leave the cup at exit", False, "fetch cup here>exit place"),
|
||||
("put the red cup on the white table at exit", False, "fetch red cup here>exit place"),
|
||||
("take the cup to p3 and put it down", False, "fetch cup here>p3 place"),
|
||||
("bring the cup to p3 and put it on the table", False, "fetch cup here>p3 place"),
|
||||
("deliver the cup to p5", False, "pick cup; go p5; give"), ("take the cup to the exit", False, "fetch cup here>exit hold"),
|
||||
("pick up the cup and give it to me", False, "pick cup; give"), ("can I have the cup?", False, "pick cup; give"),
|
||||
("bring me the red cup from p2", False, "fetch red cup p2>here hold"), ("put the cup down", False, "empty"),
|
||||
("put it on the table", False, "empty"), ("give it to me", False, "empty"),
|
||||
# night-4 leftovers: the same meaning at any level, EN = KO
|
||||
("hand it to Minsu", True, "give"), ("민수한테 줘", True, "give"), ("give it to Minsu", True, "give"),
|
||||
("민수한테 건네줘", True, "give"), ("그거 놔 줘", False, "empty"), ("그거 놔 주세요", False, "empty"),
|
||||
("아까 그 자리로 돌아가 줄래?", False, "rule come_back"), ("허리를 왼쪽으로 돌려 주셨으면 해요", False, "rule waist left"),
|
||||
("허리 왼쪽으로 돌려 주시면 감사하겠습니다", False, "rule waist left"), ("허리 왼쪽으로 돌려 주면 안 될까요?", False, "rule waist left"),
|
||||
("충전하러 가 주셨으면 해요", False, "go home"), ("충전하러 가 주시면 감사하겠습니다", False, "go home"),
|
||||
("충전하러 가 주면 안 될까요?", False, "go home"), ("차지하러 가 줘", False, "go home"), ("go charge", False, "go home"),
|
||||
("컵 내려놔 주셨으면 해요", True, "place"), ("컵 내려놔 주시면 감사하겠습니다", True, "place"),
|
||||
("컵 내려놔 주면 안 될까요?", True, "place"), ("put that cup down", True, "place"), ("put that cup down for me", True, "place"),
|
||||
("go grab me a cup", False, "pick cup; give"), ("컵 하나 갖다 줘", False, "pick cup; give"),
|
||||
("chin up, buddy", False, "talk"), ("lift your chin up", False, "rule look up"),
|
||||
("로봇아, 이 센티미터 아래로 내려 줘", False, "rule lift down 20"), ("20cm 아래로 내려 줄래~?", False, "rule lift down 200"),
|
||||
("아래로 내려놔", True, "place"), ("테이블 위에 내려 줘", True, "place on table"),
|
||||
# Konglish, dialect, whisper's spellings
|
||||
("컵 픽업해서 exit 가서 웨이트 해", False, "pick cup; go exit; wait"), ("cup 들고 exit 가", False, "pick cup; go exit"),
|
||||
("컵 테이크해서 p5로 가져가", False, "fetch cup here>p5 hold"), ("exit에 컵 드랍해 줘", False, "fetch cup here>exit place"),
|
||||
("컵 그랩해 줘", False, "pick cup"), ("컵 픽업 플리즈", False, "pick cup"), ("pick up 컵 해 줘", False, "pick cup"),
|
||||
("take 컵 to p5", False, "fetch cup here>p5 hold"), ("컵 들고 피파이브 가서 기다려", False, "pick cup; go p5; wait"),
|
||||
("컵 들고 피 오 가서 기달려", False, "pick cup; go p5; wait"), ("그 컵 쫌 갖다 도", False, "pick cup; give"),
|
||||
("exit에 컵 갖다 놓그라", False, "fetch cup here>exit place"), ("컵 좀 퍼뜩 집어 주이소", False, "pick cup"),
|
||||
("컵 함 집어 봐라", False, "pick cup"), ("컵 집으라", False, "pick cup"), ("컵 집어 줘유", False, "pick cup"),
|
||||
("p1에서 컵 갖고 와 주라", False, "fetch cup p1>here hold"), ("익싯에 컵 갖다 놔", False, "fetch cup here>exit place"),
|
||||
("p1 에서 컵 가저와", False, "fetch cup p1>here hold"), ("컵집어", False, "pick cup"), ("빨간컵 집어줘", False, "pick cup red"),
|
||||
("빨강 컵 집어", False, "pick cup red"), ("하얀 컵 집어", False, "pick cup white"),
|
||||
("흰색 컵 p3에 놔", False, "fetch white cup here>p3 place"),
|
||||
("drop the cup off at exit", False, "fetch cup here>exit place"), ("leave the cup at p3 for me", False, "fetch cup here>p3 place"),
|
||||
("carry the cup over to p5 and wait there", False, "pick cup; go p5; wait"),
|
||||
("take the cup with you to p5 and wait", False, "pick cup; go p5; wait"), ("pick up teh cup", False, "pick cup"),
|
||||
("go to exit with the cup", False, "fetch cup here>exit hold"), ("head to p5 with the red cup", False, "fetch red cup here>p5 hold"),
|
||||
("fetch me a cup from p1", False, "fetch cup p1>here hold"), ("take a cup to p5 and give it to Sarah", False, "pick cup; go p5; give Sarah"),
|
||||
("can you bring a cup to the person at p5?", False, "pick cup; go p5; give"),
|
||||
("컵 p5에 있는 사람한테 갖다 줘", False, "pick cup; go p5; give"), ("빨간 컵 p5에 계신 분께 갖다 드려", False, "pick cup red; go p5; give"),
|
||||
("drop it off at exit", True, "carry exit place"), ("leave it at p5", True, "carry p5 place"), ("drop it at p3", True, "carry p3 place"),
|
||||
("put it on the white table on your right", True, "place right white table"), ("set it down on your left", True, "place left table"),
|
||||
("excuse me robot, first look me, then follow me", False, "chain"), ("야 루미, 오른쪽 보고 손 흔들어라", False, "chain"),
|
||||
("hello robot, first turn left, then lower yourself", False, "chain"),
|
||||
("컵이랑 같이 p5로 가", False, "fetch cup here>p5 hold"), ("컵 하고 같이 exit 가 줘", False, "fetch cup here>exit hold"),
|
||||
("컵 가지고 p5에서 기다려", False, "pick cup; go p5; wait"), ("컵 들고 p5에 가 있어", False, "pick cup; go p5; wait"),
|
||||
("이 컵 p5까지 좀 날라 줘", False, "fetch cup here>p5 hold"), ("컵 좀 p5로 옮겨 줘", False, "fetch cup here>p5 hold"),
|
||||
("컵을 p5 테이블 위에 올려놔 주십시오", False, "fetch cup here>p5 place"), ("컵 하나만 가져다주시겠어요", False, "pick cup; give"),
|
||||
("p5에 컵 좀 가져다 놓을래?", False, "fetch cup here>p5 place"), ("take this cup to p5", False, "fetch cup here>p5 hold"),
|
||||
("could you take a cup over to exit for me", False, "fetch cup here>exit hold"),
|
||||
("bring a cup over to p3 and leave it there", False, "fetch cup here>p3 place"),
|
||||
("carry the cup to p5 and set it down", False, "fetch cup here>p5 place"),
|
||||
# people at places, receive, wait: EN = KO
|
||||
("take the cup to Minsu at p5", False, "pick cup; go p5; give Minsu"), ("컵 p5에 있는 민수한테 갖다 줘", False, "pick cup; go p5; give 민수"),
|
||||
("컵 들고 p5 가서 민수 씨께 드려", False, "pick cup; go p5; give 민수"),
|
||||
("컵을 p5에 계신 사장님께 갖다 드리세요", False, "pick cup; go p5; give"), ("bring the cup to the boss at p5", False, "pick cup; go p5; give"),
|
||||
("p3 가서 사라한테 컵 받아 와", False, "go p3; receive cup; go here"),
|
||||
("go to p3, get the cup from Sarah and bring it back", False, "go p3; receive cup; go here; give"),
|
||||
("p3에서 민수한테 컵 받아서 p5에 있는 사람한테 줘", False, "receive cup; go p5; give"),
|
||||
("take the cup and wait for me at p5", False, "pick cup; go p5; wait"), ("컵 들고 p5에서 나 기다려", False, "pick cup; go p5; wait"),
|
||||
("p5 가서 누가 컵 줄 때까지 기다려", False, "go p5; receive cup 300.0"),
|
||||
("go to p5 and wait until someone gives you a cup", False, "go p5; receive cup 300.0"),
|
||||
("wait until I say go, then go to p5", False, "talk"),
|
||||
("컵 들고 p5 가서 10초 기다렸다가 돌아와", False, "pick cup; go p5; wait 10.0; go here"),
|
||||
("take the cup to p5, wait 10 seconds and come back", False, "pick cup; go p5; wait 10.0; go here"),
|
||||
("컵 가지고 p5 갔다가 p3로 가", False, "pick cup; go p5; go p3"), ("take the cup to p5 then go to p3", False, "pick cup; go p5; go p3"),
|
||||
("컵 들고 p5 가서 테이블에 놓고 와", False, "pick cup; go p5; place table; go here"),
|
||||
]
|
||||
bad = []
|
||||
for words, verb, held, want in KO_T:
|
||||
READ += [(words.format(f), held, want) for f in ko_levels(*VERB[verb])]
|
||||
for x, held, want in EN_T:
|
||||
READ += [((f.format(x=x)[0].upper() + f.format(x=x)[1:]) if j % 3 == 0 else f.format(x=x), held, want)
|
||||
for j, f in enumerate(EN_LEVELS)]
|
||||
for text, held, want in READ:
|
||||
got = plan(text, held)
|
||||
if "-v" in __import__("sys").argv:
|
||||
print(f"{text!r:50} {'holding ' if held else ''}-> {got}")
|
||||
if got != want:
|
||||
bad.append(text)
|
||||
print(f"WRONG {text!r}{' (holding)' if held else ''}\n want {want}\n got {got}")
|
||||
# ---------- the held thing is named in what the box reads back (never "something") ----------
|
||||
HELD[0] = True
|
||||
for text, want in (("put it down", "Put the white cup on the table near me."), ("컵 내려놔", "Put the white cup on the table near me."),
|
||||
("give it to me", "Hand the white cup to you."), ("나한테 줘", "Hand the white cup to you."),
|
||||
("take it to p5", "Bring the white cup to p5 and keep holding it."),
|
||||
("p5 테이블에 놔 줘", "Bring the white cup to p5 and put it on the table there.")):
|
||||
got = server.task_parse(server.ParseBody(text=text))["sentence"]
|
||||
if got != want:
|
||||
bad.append(text)
|
||||
print(f"WRONG {text!r} (holding the white cup)\n want {want}\n got {got}")
|
||||
|
||||
|
||||
# ---------- English marker names said in Korean (place_words: as they sound, never translated) ----------
|
||||
CONF = ["home", "dock2", "Gallery_1", "Gallery_2", "Booth_12", "Gate_B7", "booth_A", "Elevator", "Registration"]
|
||||
server.agv.markers = lambda: CONF
|
||||
for text, want in (("갤러리 투로 가 줘", "go Gallery_2"), ("갤러리 1로 가", "go Gallery_1"), ("부스 십이로 가 줘", "go Booth_12"),
|
||||
("비 세븐 게이트로 가", "go Gate_B7"), ("게이트 비 세븐으로 가 줘", "go Gate_B7"), ("에이 부스로 가", "go booth_A"),
|
||||
("엘리베이터로 가 줘", "go Elevator"), ("레지스트레이션으로 가", "go Registration"), ("go to gate b seven", "go Gate_B7"),
|
||||
("홈 포지션으로 가", "go home")):
|
||||
got = plan(text)
|
||||
if got != want:
|
||||
bad.append(text)
|
||||
print(f"WRONG {text!r}\n want {want}\n got {got}")
|
||||
server.agv.markers = lambda: M
|
||||
|
||||
|
||||
# ---------- stop words (the owner, 2026-10-26 21:10): every form at every level stops, also inside a sentence ----------
|
||||
STOPS = ["멈춰", "멈춰요", "멈추세요", "멈춰 주세요", "멈춰 주시겠어요?", "멈추십시오", "멈춰 줘", "멈춰라", "멈추게", "멈춰 주이소",
|
||||
"멈춰 주실래요?", "멈춰 주시면 감사하겠습니다", "멈춰 주셨으면 해요", "멈춰 주면 안 될까요?", "멈춰 주시겠습니까?", "멈춰!",
|
||||
"그만", "그만해", "그만해요", "그만하세요", "그만하십시오", "그만 해 줘", "그만둬", "그만두세요", "이제 그만", "그만그만",
|
||||
"정지", "정지해", "정지하세요", "정지!", "스톱", "스탑", "스톱해", "스탑 해 줘", "스톱 스톱", "거기 서", "서!", "서", "서라",
|
||||
"거기 서 봐", "움직이지 마", "움직이지 마세요", "움직이지 마십시오", "가지 마", "잠깐 멈춰", "당장 멈춰", "멈처", "멈쳐",
|
||||
"멈춰어", "머엄춰", "스땁", "멈춰 멈춰", "루미야 멈춰", "루미 그만", "야 멈춰", "멈추시게", "그마안",
|
||||
"stop", "stop it", "stop now", "halt", "freeze", "Stop!", "STOP", "stop, stop", "please stop", "stop please",
|
||||
"Lumi stop", "Lumi, stop!", "stop right there", "stop moving", "stop the robot", "hold it right there", "stahp",
|
||||
"stopp", "stooop", "stob", "emergency stop", "would you stop, please?", "can you stop?", "stop that", "quit it",
|
||||
"cut it out", "don't move", "stay still", "hold still", "enough!", "that's enough", "whoa whoa"]
|
||||
STOPS_INSIDE = ["루미야 그거 말고 멈춰 지금", "아 잠깐만 멈춰 봐 위험해", "okay Lumi stop, there's someone in the way",
|
||||
"wait wait stop it now", "컵 내려놓지 말고 멈춰", "야야 스톱 스톱", "저기 사람 있어 멈춰요", "no no no, stop",
|
||||
"Lumi, stop, you're going to hit the table", "그만, 그만해 이제", "다 됐어 멈춰 주세요", "careful, stop!",
|
||||
"멈춰버려", "동물을 멈춰버린 거랑 안해", "루미야 지금 바로 멈춰 주세요 위험해요", "stop, where are you going?"]
|
||||
for text in STOPS + STOPS_INSIDE:
|
||||
for held in (False, True):
|
||||
got = plan(text, held)
|
||||
if got != "stop":
|
||||
bad.append(text)
|
||||
print(f"NO STOP {text!r}{' (holding)' if held else ''}: {got}")
|
||||
print(f"{len(STOPS + STOPS_INSIDE)} stop words")
|
||||
assert not bad
|
||||
ko = sum(1 for t, _, _ in READ if brain.HANGUL.search(t))
|
||||
print(f"{len(READ) - len(bad)}/{len(READ)} read right ({ko} Korean, {len(READ) - ko} English)")
|
||||
assert not bad
|
||||
print("command box ok")
|
||||
|
||||
+99
-19
@@ -121,7 +121,7 @@ def fake_status():
|
||||
return {"move_status": "running" if base["polls"] % 3 else "succeeded", "charge_state": base.get("charging", False)}
|
||||
|
||||
|
||||
def fake_reachable(obj, start=None, accept=None):
|
||||
def fake_reachable(obj, start=None, accept=None, max_yaw=None):
|
||||
calls.append(("ik",))
|
||||
return (skills.plan_pick(obj), [0.0] * 6) if reach["ok"] else None
|
||||
|
||||
@@ -130,7 +130,8 @@ fetch.agv.markers = lambda: MARKERS
|
||||
fetch.agv.pose = lambda: base["pose"]
|
||||
fetch.agv.status = fake_status
|
||||
fetch.agv.go = lambda m: (calls.append(("go", m)), (True, "OK"))[1]
|
||||
fetch.agv.go_point = lambda x, y, th: (calls.append(("go_point", round(x, 3), round(y, 3))), (True, "OK"))[1]
|
||||
fetch.agv.go_point = lambda x, y, th: (calls.append(("go_point", round(x, 3), round(y, 3))), base.update(pose=(x, y, th)),
|
||||
(True, "OK"))[-1] # the fake base gets there at once
|
||||
fetch.agv.cancel = lambda: calls.append(("cancel",))
|
||||
fetch.agv.clearance = lambda x, y: room["clear"](x, y)
|
||||
fetch.agv.request = lambda cmd, **kw: (calls.append(("joy", cmd.split("linear_velocity=")[1].split("&")[0]))
|
||||
@@ -138,6 +139,20 @@ fetch.agv.request = lambda cmd, **kw: (calls.append(("joy", cmd.split("linear_ve
|
||||
room = {"clear": lambda x, y: 1.0, "probe": lambda x, y: (float("inf"), float("inf"))}
|
||||
fetch.agv.probe = lambda x, y: room["probe"](x, y)
|
||||
fetch.AXIS_SPEED, fetch.COAST_S = 100.0, 0.0
|
||||
real_straight = fetch._straight
|
||||
|
||||
|
||||
def moving_straight(d, speed=None, stop=True):
|
||||
"""The fake base's pose follows a straight drive, unless base["stuck"] (its own obstacle stop at a table)."""
|
||||
got = real_straight(d, speed, stop)
|
||||
if not base.get("stuck"):
|
||||
x, y, th = base["pose"]
|
||||
s = math.copysign(got, d)
|
||||
base["pose"] = (x + s * math.cos(th), y + s * math.sin(th), th)
|
||||
return got
|
||||
|
||||
|
||||
fetch._straight = moving_straight
|
||||
fetch.MOVED_CHECK_M = float("inf") # this fake base never moves its pose (the check: test_driving.py)
|
||||
arm = {"j": [5.0] * 6} # the fake arm's joints: away from every pose
|
||||
fetch.motion.go = lambda name, *a, **k: (calls.append(("pose", name)), arm.update(j=list(fetch.motion.poses()[name])))
|
||||
@@ -154,7 +169,16 @@ tilt = {"rpy": up_rpy}
|
||||
skills._ask = lambda name, **a: {"errorCode": "0", "cartPosition": [0, 0, 0] + tilt["rpy"]}
|
||||
fetch.gripper.state = lambda: {**hand, "ai": [3500 if hand["holding"] else 160], "di": [int(hand["holding"])]}
|
||||
fetch.gripper.open_ = lambda: (calls.append(("open",)), hand.update(holding=False, closed=False), fetch.gripper.state())[-1]
|
||||
skills.find = lambda name, colour=None, seen=None: (calls.append(("find", name)), found["obj"])[1] if found["obj"] \
|
||||
def in_room(obj):
|
||||
"""A fake camera's object that stays put in the room: seen where it is from the base pose now (the CALIB_FILE yaw
|
||||
must be written first; the base is at (0, 0, 0) when this is called)."""
|
||||
w = fetch.map_xy(obj)
|
||||
return lambda: {**obj, **dict(zip(("x", "y"), map(float, fetch.arm_frame(w))))}
|
||||
|
||||
|
||||
skills.find = lambda name, colour=None, seen=None: (calls.append(("find", name)),
|
||||
found["obj"]() if callable(found["obj"]) else found["obj"])[1] \
|
||||
if found["obj"] \
|
||||
else (_ for _ in ()).throw(skills.SkillError("I can't see a thing."))
|
||||
skills.reachable_pick = fake_reachable
|
||||
skills.look = lambda frames=None, **kw: []
|
||||
@@ -208,7 +232,7 @@ def run(fn, *a):
|
||||
|
||||
def reset():
|
||||
fetch._state.update(status="idle", holding=False, step="")
|
||||
base["polls"], base["on_poll"] = 0, None
|
||||
base.update(polls=0, on_poll=None, pose=(0.0, 0.0, 0.0), stuck=False)
|
||||
arm.update(j=[5.0] * 6)
|
||||
found["obj"], reach["ok"] = CUP, True
|
||||
hand.update(holding=False, closed=False)
|
||||
@@ -290,9 +314,10 @@ skills.find = find_low
|
||||
reset()
|
||||
st = run(fetch.start, {**ok, "source": "here", "dest": "here"})
|
||||
lifts = [c[1] for c in calls if c[0] == "lift"]
|
||||
turns = [c for c in calls if c[0] == "go_point"]
|
||||
before = calls[:calls.index(("pick", "apple"))] # (then the way back to where it was told)
|
||||
turns = [c for c in before if c[0] == "go_point"]
|
||||
assert st["status"] == "holding" and lifts[0] == 0.0 and len(turns) == 1, (st, calls) # ... a base turn up there,
|
||||
assert calls.index(("lift", 0.0)) > max(i for i, c in enumerate(calls) if c[0] == "go_point") # then the lift down
|
||||
assert calls.index(("lift", 0.0)) > max(i for i, c in enumerate(before) if c[0] == "go_point") # then the lift down
|
||||
skills.find = real_find
|
||||
surface["z"] = -403.0
|
||||
fetch._set(holding=False, status="idle")
|
||||
@@ -372,11 +397,28 @@ fetch.CALIB_FILE.write_text(json.dumps({"arm_yaw_in_base_deg": -86.2}))
|
||||
surface["z"] = -400.0
|
||||
skills.on_table = lambda spots, table: [p for p in spots if p[1] >= 760][:1] if not any(c[0] == "joy" for c in calls) \
|
||||
else [p for p in spots if p[1] <= 700][:1]
|
||||
far_held = dict(skills._held)
|
||||
real_chain, real_options = skills.ik_chain, skills.place_options
|
||||
far_spot = lambda n: n.startswith("to (") and float(n.split(", ")[1].split(")")[0]) > 740 # line to a spot y > 740
|
||||
skills.ik_chain = lambda wp, j: [[n, p, [0] * 6, "no IK solution" if far_spot(n) else None] for n, p in wp]
|
||||
skills.place_options = lambda *a: iter(()) # ... the arm does not reach it from here
|
||||
st = run(fetch.place)
|
||||
skills.on_table, surface["z"] = real_on_table, -403.0
|
||||
names = [c[0] for c in calls]
|
||||
assert st["status"] == "done" and "joy" in names and names.index("joy") < names.index("place"), st["log"]
|
||||
assert any("further away" in l for l in st["log"]) and not any(c[0] == "go" for c in calls), st["log"]
|
||||
# ... the arm reaches a spot of it from here (lift 0, the near part of the table under the camera's view): put there,
|
||||
# no base move (2026-10-26 18:53: "further away" right in front, the base could not get nearer)
|
||||
skills.ik_chain, skills.place_options = real_chain, real_options
|
||||
reset()
|
||||
hand.update(holding=True, closed=True)
|
||||
fetch._set(holding=True, status="holding")
|
||||
skills._held.update(far_held)
|
||||
fetch.CALIB_FILE.write_text(json.dumps({"arm_yaw_in_base_deg": -86.2}))
|
||||
st = run(fetch.place)
|
||||
names = [c[0] for c in calls]
|
||||
assert st["status"] == "done" and "joy" not in names and "place" in names, st["log"]
|
||||
assert any("trying spots in reach from here" in l for l in st["log"]), st["log"]
|
||||
skills.on_table, surface["z"] = real_on_table, -403.0
|
||||
|
||||
# ---------- out of reach, base axis not measured: no shift, ask, then failed ----------
|
||||
reset()
|
||||
@@ -408,14 +450,16 @@ assert st["status"] == "holding" and ("pick", "apple") in calls, st["log"]
|
||||
fetch._set(holding=False, status="idle")
|
||||
# the straight way is blocked (an obstacle next to the base on the way): navigation round to a side, one side a try
|
||||
reset()
|
||||
found["obj"], reach["ok"] = far_cup, False
|
||||
fetch.CALIB_FILE.write_text(json.dumps({"arm_yaw_in_base_deg": -86.2}))
|
||||
found["obj"], reach["ok"] = in_room(far_cup), False
|
||||
room["clear"] = lambda x, y: 0.1 if math.hypot(x, y) > 0.01 else 0.2
|
||||
st = run(fetch.start, {**ok, "source": "here", "dest": "here"})
|
||||
room["clear"] = lambda x, y: 1.0
|
||||
rounds = [l for l in st["log"] if "driving round" in l]
|
||||
assert st["status"] == "failed" and len(rounds) == fetch.APPROACH_TRIES and not any(c[0] == "joy" for c in calls), st["log"]
|
||||
assert len({l.split("from ")[-1] for l in rounds}) == fetch.APPROACH_TRIES # every time another side
|
||||
tries = [l for l in st["log"] if "driving round" in l or "can't get near enough" in l] # (no room anywhere here)
|
||||
drives = [l for l in tries if "driving round" in l]
|
||||
assert st["status"] == "failed" and tries, st["log"]
|
||||
assert len({l.split("from ")[-1] for l in drives}) == len(drives) # each side driven to once
|
||||
assert any("asking for help: every way closer was blocked" in l for l in st["log"]), st["log"]
|
||||
found["obj"] = CUP
|
||||
|
||||
# ---------- the state still says holding, but the hand is open (someone took it): a new fetch starts ----------
|
||||
@@ -465,7 +509,7 @@ hand.update(holding=False, closed=False)
|
||||
|
||||
# ---------- too wide from far away: go closer and measure again; too wide up close: refused ----------
|
||||
real_reach = skills.reachable_pick
|
||||
def width_check(obj, start=None, accept=None):
|
||||
def width_check(obj, start=None, accept=None, max_yaw=None):
|
||||
calls.append(("ik",))
|
||||
skills.plan_pick(obj) # raises when too wide
|
||||
return (skills.plan_pick(obj), [0.0] * 6) if obj["y"] < 700 else None
|
||||
@@ -476,7 +520,8 @@ wide_far = {**CUP, "name": "cup", "x": -69.0, "y": 1142.0, "width_mm": 98.0}
|
||||
wide_near = {**wide_far, "x": -100.0, "y": 600.0, "width_mm": 79.0}
|
||||
skills.find = lambda name, colour=None, seen=None: wide_near if any(c[0] == "joy" for c in calls) else wide_far
|
||||
st = run(fetch.start, {**ok, "object": "cup", "source": "here", "dest": "here"})
|
||||
assert st["status"] == "holding" and any("measure it again up close" in l for l in st["log"]), st["log"]
|
||||
assert st["status"] == "holding" and any("measure it again up close" in l or "closer first" in l for l in st["log"]), \
|
||||
st["log"] # (that far it is not even measured)
|
||||
fetch._set(holding=False, status="idle")
|
||||
hand.update(holding=False, closed=False)
|
||||
reset()
|
||||
@@ -681,10 +726,6 @@ fetch.DRIVE_START_S, fetch.agv.status = real_start, real_agv_status
|
||||
t0 = time.time()
|
||||
fetch._straight(0.01, 1.0)
|
||||
assert time.time() - t0 < 0.2 and skills.moved_at["torso"] > t0, skills.moved_at
|
||||
# ... a straight approach the base pose did not follow (its own obstacle stop) counts as blocked: another way
|
||||
fetch.MOVED_CHECK_M = 0.1
|
||||
assert fetch._straight_went(0.2) == 0.0
|
||||
fetch.MOVED_CHECK_M = float("inf")
|
||||
|
||||
# ---------- measure-axis pairs each object once: two cups before, one after ----------
|
||||
b2 = [{"name": "cup", "x": -211.5, "y": 1332.0}, {"name": "cup", "x": 9.0, "y": 1301.0}]
|
||||
@@ -1064,6 +1105,45 @@ fetch._set(holding=True) # (
|
||||
assert fetch.held_name() == "the white cup"
|
||||
fetch._set(holding=False)
|
||||
skills._held.clear()
|
||||
# one hand read said empty with the cup still in it (live 2026-10-26 18:53:00): the name and the put-down data come
|
||||
# back when the hand is seen holding again, on every path (the dashboard's check, a fetch, place / give, a mission)
|
||||
def forgot():
|
||||
reset()
|
||||
fetch._set(holding=True, held_object={"object": "cup", "colour": "white"}, status="holding")
|
||||
skills._held.update(top_mm=-260.0, x=-150.0, y=600.0, table=-403.0, what={"object": "cup", "colour": "white"})
|
||||
hand.update(holding=False, closed=False)
|
||||
fetch.check_hand() # the false "empty"
|
||||
assert fetch.held_name() == "something" and not skills._held
|
||||
hand.update(holding=True, closed=True)
|
||||
|
||||
|
||||
forgot()
|
||||
assert fetch.check_hand() and fetch.held_name() == "the white cup" and fetch.held_name("ko") == "흰 컵"
|
||||
forgot()
|
||||
try:
|
||||
fetch.start(ok)
|
||||
raise AssertionError("a fetch while holding")
|
||||
except fetch.FetchError as e:
|
||||
assert e.args[0] == "I'm holding the white cup, where should I put it first?", e.args
|
||||
forgot()
|
||||
st = run(fetch.place) # put down needs its height: back too
|
||||
assert st["status"] == "done" and ("place",) in calls, st["log"]
|
||||
forgot()
|
||||
named = []
|
||||
real_give = fetch._give
|
||||
fetch._give = lambda say: (named.append(fetch.held_name()), fetch._set(holding=False), skills._held.clear())[-1]
|
||||
st = run(fetch.run_steps, [{"do": "give"}])
|
||||
fetch._give = real_give
|
||||
assert st["status"] == "done" and named == ["the white cup"], (st["log"], named)
|
||||
fetch._set(holding=True, held_object={"object": "cup", "colour": "white"})
|
||||
assert fetch.held_name("ko") == "흰 컵"
|
||||
fetch._set(holding=True, held_object={"object": "bottle", "colour": None})
|
||||
assert fetch.held_name("ko") == "병" and fetch.held_name() == "the bottle", fetch.held_name("ko")
|
||||
fetch._set(holding=False)
|
||||
assert fetch.held_name("ko") == "물건"
|
||||
skills._held.clear()
|
||||
hand.update(holding=False, closed=False)
|
||||
fetch._set(status="idle")
|
||||
|
||||
# the lift is never asked above its limit (head camera cable, robot/head.py LIFT_MAX_MM)
|
||||
assert max(fetch.LIFT_RANGE + fetch.LIFT_TRIES + (fetch.LIFT_DRIVE_MM,)) <= fetch.head.LIFT_MAX_MM == 105.0
|
||||
@@ -1101,7 +1181,7 @@ FAR = {**CUP, "x": -150.0, "y": 600.0}
|
||||
NEAR = {**CUP, "x": 60.0, "y": 560.0}
|
||||
skills.look = lambda frames=None, **kw: [FAR, NEAR]
|
||||
found["obj"] = FAR
|
||||
skills.reachable_pick = lambda obj, start=None, accept=None: (skills.plan_pick(obj), [0.0] * 6) if obj["x"] > 0 else None
|
||||
skills.reachable_pick = lambda obj, start=None, accept=None, max_yaw=None: (skills.plan_pick(obj), [0.0] * 6) if obj["x"] > 0 else None
|
||||
reset()
|
||||
found["obj"] = FAR
|
||||
st = run(fetch.start, {**ok, "source": "here", "dest": "here"})
|
||||
@@ -1109,7 +1189,7 @@ assert st["status"] == "holding" and any("instead" in l for l in st["log"]) and
|
||||
(st["log"][-6:], calls)
|
||||
fetch._set(holding=False, status="idle")
|
||||
skills._held.clear()
|
||||
def too_big(obj, start=None, accept=None):
|
||||
def too_big(obj, start=None, accept=None, max_yaw=None):
|
||||
if obj["x"] < 0:
|
||||
raise skills.SkillError("The apple is too big for my hand.")
|
||||
return skills.plan_pick(obj), [0.0] * 6
|
||||
|
||||
@@ -71,6 +71,9 @@ def flat(pts, guess_z=-400.0, camera="torso", T=None):
|
||||
|
||||
|
||||
skills.surface_heights, skills.flat_points = depth, flat
|
||||
POINTS_REAL = skills.surface_points
|
||||
skills.surface_points = lambda pts, guess_z=-400.0, **kw: [None if z is None else (p[0], p[1], z) # never live depth
|
||||
for p, z in zip(pts, depth([q[:2] for q in pts]))]
|
||||
skills.FRESH_WAIT_S = 0.0
|
||||
fetch.head_cam.base_from_head = lambda yaw, pitch: None # the torso camera only (head: below)
|
||||
fetch.head.status = lambda: [0.0, -20.0, 0.0, 0.0] # lift 0 (its bottom), as in the log
|
||||
@@ -119,7 +122,7 @@ camview.depth, camview.intrinsics = lambda name, max_age=None: REC["depth"], lam
|
||||
objects.base_from_camera = lambda: REC["T"]
|
||||
fetch.head.status = lambda: [63.0, -20.3, 0.0, 0.0]
|
||||
TABLE_LIVE = -386.0 # its level top, checked by eye
|
||||
skills.flat_points = FLAT_REAL
|
||||
skills.flat_points, fake_points, skills.surface_points = FLAT_REAL, skills.surface_points, POINTS_REAL
|
||||
assert abs(fetch.table_ahead() - TABLE_LIVE) < 10.0, fetch.table_ahead()
|
||||
far = fetch.far_table()
|
||||
assert far and abs(far["table"] - TABLE_LIVE) < 10.0, far
|
||||
@@ -129,7 +132,7 @@ grid = [(r * math.cos(math.radians(90 + b)), r * math.sin(math.radians(90 + b)))
|
||||
zs = [q[2] for q in skills.surface_points(grid, fetch.TABLE_PROVEN_Z) if q is not None and band[0] <= q[2] <= band[1]]
|
||||
assert abs(np.median(zs) - TABLE_LIVE) > 60.0, np.median(zs) # the old way: chairs pull it down
|
||||
camview.depth, camview.intrinsics, objects.base_from_camera = real_depth, real_intr, real_T
|
||||
skills.flat_points = flat
|
||||
skills.flat_points, skills.surface_points = flat, fake_points
|
||||
|
||||
# ---------- a table seen further away (the live case: its near edge ~1 m ahead, lift 0, chairs before it): go to it,
|
||||
# the place grid then lies on its top ----------
|
||||
|
||||
@@ -0,0 +1,391 @@
|
||||
"""Self-check of fetch's ways to a thing (tasks/fetch.py), no robot: python tests/test_fetch_ways.py
|
||||
|
||||
A fake room: a table (a rectangle on the map), a cup on it, the base that drives and turns on the map and stands still
|
||||
when its front comes too near the table (its own safety stop, live 2026-10-26), navigation that "arrives" without
|
||||
moving when its goal is inside the table's margin, a torso camera that sees the cup where it is from the base pose now
|
||||
and the table top only from a near limit on. The live positions of 2026-10-26: (-117, 960), (-104, 694), (-141, 869),
|
||||
(262, 774), (260, 722), (300, 621), (-99, 738); the place at 18:53 ("no table in view", the table seen further away,
|
||||
the base never nearer) and at 18:55 (a table's box centre (22, 623), then (-349, 647))."""
|
||||
import json
|
||||
import math
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
|
||||
from manipulation import skills
|
||||
from tasks import fetch
|
||||
from vision import head_cam
|
||||
|
||||
tmp = Path(tempfile.mkdtemp())
|
||||
fetch.STATE_FILE = tmp / "lumi_task.json" # never the real /dev/shm file
|
||||
fetch.CALIB_FILE = tmp / "fetch_calib.json"
|
||||
fetch.KNOWN_FILE = tmp / "known_things.json"
|
||||
fetch.DRIVE_POLL_S, fetch.DRIVE_START_S = 0.0, 0.05
|
||||
fetch.ASK_EVERY_S, fetch.ASK_WAIT_S = 0.0, 0.0
|
||||
fetch.LOG_LINES = 1000
|
||||
fetch.AXIS_SPEED, fetch.COAST_S = 100.0, 0.0
|
||||
CALIB = {"arm_yaw_in_base_deg": -95.5, "arm_xy_in_base_m": [0.111, -0.109], "waist_deg": -20.31} # live values
|
||||
WAIST0 = CALIB["waist_deg"]
|
||||
REACH_MM = 800.0 # the fake arm reaches this far from the column (R1's map: nothing past ~850) ...
|
||||
TRUSTED_REACH_MM = 740.0 # ... with a grasp turned at most skills.TRUSTED_YAW_DEG this far
|
||||
STOP_GAP_M = 0.10 # the base stands still when its front would come this near the table
|
||||
VIEW_Y = 650.0 # mm, arm frame: the torso camera sees a table top from here on (lift 0, table -328)
|
||||
HELD_X, HELD_W, HELD_Y = -130.0, 110.0, 760.0 # the held cup hides the table here from the camera (x +- W, y < Y)
|
||||
FLOOR_Z = -1060.0
|
||||
|
||||
skills.arm.cmd = lambda *a, **kw: (_ for _ in ()).throw(AssertionError(f"real arm command in a test: {a}"))
|
||||
head_cam.head_centre = lambda: np.array([-92.97, -19.87, 356.12]) # measured (data on the Thor), fixed here
|
||||
C = head_cam.head_centre()[:2]
|
||||
col = lambda x, y: math.hypot(x - C[0], y - C[1])
|
||||
|
||||
# ---------- the room ----------
|
||||
room = {"table": (0.355, 1.255, -0.6, 0.6), "chairs": [], "z": -328.0, "cups": [], "holding": None}
|
||||
base = {"pose": (0.0, 0.0, 0.0), "polls": 0}
|
||||
body = {"lift": 0.0, "waist": WAIST0, "yaw": 0.0, "pitch": fetch.head.HEAD_REST_PITCH}
|
||||
log = [] # what the fake robot did
|
||||
|
||||
|
||||
def to_box(x, y, box):
|
||||
x0, x1, y0, y1 = box
|
||||
if x0 <= x <= x1 and y0 <= y <= y1:
|
||||
return min(x - x0, x1 - x, y - y0, y1 - y)
|
||||
return math.hypot(max(x0 - x, 0.0, x - x1), max(y0 - y, 0.0, y - y1))
|
||||
|
||||
|
||||
def to_table(x, y):
|
||||
"""Distance (m) from a map point to the outline of the table or a chair (0 on it; inside: to the nearest edge, as
|
||||
the probe)."""
|
||||
return min(to_box(x, y, b) for b in [room["table"]] + room["chairs"])
|
||||
|
||||
|
||||
def inside(x, y):
|
||||
x0, x1, y0, y1 = room["table"]
|
||||
return x0 <= x <= x1 and y0 <= y <= y1
|
||||
|
||||
|
||||
def base_free(x, y):
|
||||
"""The base may stand here: its outline (a circle of BASE_HALF_M) STOP_GAP_M from the table."""
|
||||
return not inside(x, y) and not any(to_box(x, y, b) == 0 or b[0] <= x <= b[1] and b[2] <= y <= b[3]
|
||||
for b in room["chairs"]) and to_table(x, y) >= fetch.BASE_HALF_M + STOP_GAP_M
|
||||
|
||||
|
||||
def go_point(x, y, th):
|
||||
px, py, _ = base["pose"]
|
||||
if math.hypot(x - px, y - py) < 1e-6: # a turn on the spot
|
||||
log.append(("turn", round(math.degrees(th), 1)))
|
||||
base["pose"] = (px, py, th)
|
||||
elif base_free(x, y):
|
||||
log.append(("nav", round(x, 2), round(y, 2)))
|
||||
base["pose"] = (x, y, th)
|
||||
else: # inside the table's margin: "succeeded", not moved
|
||||
log.append(("nav still", round(x, 2), round(y, 2)))
|
||||
return True, "OK"
|
||||
|
||||
|
||||
real_straight = fetch._straight
|
||||
|
||||
|
||||
def straight(d, speed=None, stop=True):
|
||||
got = real_straight(d, speed, stop)
|
||||
x, y, th = base["pose"]
|
||||
went = 0.0
|
||||
while went + 0.01 <= got + 1e-9 and base_free(x + math.copysign(went + 0.01, d) * math.cos(th),
|
||||
y + math.copysign(went + 0.01, d) * math.sin(th)):
|
||||
went += 0.01
|
||||
log.append(("straight", round(math.copysign(got, d), 2), round(math.copysign(went, d), 2)))
|
||||
base["pose"] = (x + math.copysign(went, d) * math.cos(th), y + math.copysign(went, d) * math.sin(th), th)
|
||||
return got
|
||||
|
||||
|
||||
fetch._straight = straight
|
||||
fetch.agv.pose = lambda: base["pose"]
|
||||
fetch.agv.go_point = go_point
|
||||
fetch.agv.status = lambda: {"move_status": "succeeded", "charge_state": False}
|
||||
fetch.agv.cancel = lambda: None
|
||||
fetch.agv.request = lambda cmd, **kw: {}
|
||||
fetch.agv.clearance = lambda x, y: to_table(x, y)
|
||||
fetch.agv.probe = lambda x, y: (float("inf"), float("inf"))
|
||||
fetch.agv.markers = lambda: []
|
||||
fetch.depth_hits = lambda deg, camera="torso", T=None: None
|
||||
fetch.head.status = lambda: [body["lift"], body["waist"], body["yaw"], body["pitch"]]
|
||||
fetch.head.moveto = lambda pos, **kw: body.update(lift=pos[0], waist=pos[1], yaw=pos[2], pitch=pos[3])
|
||||
fetch.head_cam.base_from_head = lambda yaw, pitch: None # the head camera: not used here
|
||||
fetch.objects.latest = lambda camera="torso": {"age_s": None, "objects": [], "head_pose": None}
|
||||
fetch.camview.want = lambda name: None
|
||||
fetch.objects.base_from_camera = lambda: np.array([[1, 0, 0, -60.0], [0, 0, 0.9, 120.0], [0, -1, -0.44, 200.0],
|
||||
[0, 0, 0, 1]]) # looks along arm +y, down
|
||||
skills.FRESH_WAIT_S = 0.0
|
||||
arm = {"j": [0.0] * 6}
|
||||
fetch.motion.poses = lambda: {"ready": [0] * 6, "carry": [3] * 6, "look": [0] * 6, "give": [7] * 6}
|
||||
fetch.motion.go = lambda name, *a, **k: arm.update(j=list(fetch.motion.poses()[name]))
|
||||
fetch.motion.stop = lambda: None
|
||||
fetch.arm_route.move = lambda seq, *a, **k: [fetch.motion.go(n) for n, _ in seq]
|
||||
fetch.motion.tcp = lambda: [0.0] * 3 + list(skills.GRASP_RPY)
|
||||
fetch.motion.move_linear = lambda target=None, **kw: None
|
||||
skills._joints = lambda: arm["j"]
|
||||
skills.home_joints = lambda: [0.0] * 6
|
||||
skills._ask = lambda name, **a: {"errorCode": "0", "cartPosition": [0, 0, 0] + list(skills.GRASP_RPY)}
|
||||
fetch.gripper.state = lambda: {"holding": room["holding"] is not None, "closed": room["holding"] is not None,
|
||||
"ai": [3500 if room["holding"] else 160], "di": [0]}
|
||||
fetch.gripper.open_ = lambda: (room.update(holding=None), fetch.gripper.state())[-1]
|
||||
skills.hand_sees = lambda: "unknown"
|
||||
|
||||
|
||||
# ---------- the fake cameras: the cup and the table seen from the base pose now ----------
|
||||
def arm_xy_of(w):
|
||||
return [float(v) for v in fetch.arm_frame(w)]
|
||||
|
||||
|
||||
def visible(x, y):
|
||||
"""The torso camera sees the arm-frame point (x, y): ahead within its view, not behind the held cup."""
|
||||
hidden = room["holding"] is not None and abs(x - HELD_X) < HELD_W and y < HELD_Y
|
||||
return 300.0 <= y <= 2500.0 and abs(math.degrees(math.atan2(x, y))) <= 40.0 and not hidden
|
||||
|
||||
|
||||
def low_view(x, y, z):
|
||||
"""The torso camera looks level: at y 580 it sees down to z -375, further out lower (real extrinsics, lift 0)."""
|
||||
return z >= -375.0 - 0.7 * (y - 580.0)
|
||||
|
||||
|
||||
fetch.in_view = low_view
|
||||
|
||||
|
||||
def cups():
|
||||
out = []
|
||||
for c in room["cups"]:
|
||||
x, y = arm_xy_of(c["map"])
|
||||
if visible(x, y) and low_view(x, y, room["z"] + 145.0 / 2):
|
||||
out.append({"name": "cup", "colour": "white", "x": x, "y": y, "top_mm": room["z"] + 145.0,
|
||||
"height_mm": 145.0, "width_mm": 80.0, "seen": 8, "spread": 1.0, "id": c["id"]})
|
||||
return out
|
||||
|
||||
|
||||
def find(name="cup", colour=None, seen=None):
|
||||
got = sorted(cups(), key=lambda o: math.hypot(o["x"], o["y"]))
|
||||
if not got:
|
||||
raise skills.SkillError("I can't see a thing.")
|
||||
return got[0]
|
||||
|
||||
|
||||
def flat(pts, guess_z=-400.0, camera="torso", T=None):
|
||||
out = []
|
||||
for x, y, *_ in pts:
|
||||
if not visible(x, y) or y < VIEW_Y:
|
||||
out.append(None)
|
||||
continue
|
||||
w = fetch.map_xy({"x": x, "y": y})
|
||||
out.append((x, y, room["z"] if inside(*w) else FLOOR_Z))
|
||||
return out
|
||||
|
||||
|
||||
skills.find = find
|
||||
skills.look = lambda frames=None, ignore=(), **kw: cups()
|
||||
skills.flat_points = flat
|
||||
skills.surface_heights = lambda pts, guess_z=-400.0: [None if q is None else q[2] for q in flat(pts)]
|
||||
skills.surface_points = lambda pts, guess_z=-400.0, **kw: flat(pts)
|
||||
skills.table_near = lambda obj: room["z"]
|
||||
skills.locate = lambda xy, top, table, width, radius=None: ("unseen", None)
|
||||
|
||||
|
||||
# ---------- the fake arm: reaches REACH_MM from the column; what it picked and where ----------
|
||||
def reachable(obj, start=None, accept=None, max_yaw=None):
|
||||
"""No-turn / small-turn grasps reach TRUSTED_REACH_MM from the column, every turn REACH_MM."""
|
||||
if col(obj["x"], obj["y"]) > (REACH_MM if max_yaw is None else TRUSTED_REACH_MM):
|
||||
skills.log(f"plan refused: no grasp turn reaches ({obj['x']:.0f}, {obj['y']:.0f})")
|
||||
return None
|
||||
turned["any"] = col(obj["x"], obj["y"]) > TRUSTED_REACH_MM
|
||||
return skills.plan_pick(obj), [0.0] * 6
|
||||
|
||||
|
||||
turned = {"any": False}
|
||||
|
||||
|
||||
def do_pick(obj, wp, ja):
|
||||
log.append(("pick", round(obj["x"]), round(obj["y"]), round(col(obj["x"], obj["y"])), turned["any"]))
|
||||
held = next(c for c in room["cups"] if c["id"] == obj["id"])
|
||||
true = arm_xy_of(held["map"]) # a plan from where it is now, never from before a move
|
||||
assert math.hypot(true[0] - obj["x"], true[1] - obj["y"]) < 5.0, (true, obj)
|
||||
room["cups"].remove(held)
|
||||
room["holding"] = held
|
||||
skills._held.update(top_mm=obj["top_mm"], x=obj["x"], y=obj["y"], table=room["z"])
|
||||
|
||||
|
||||
def chain(wp, j):
|
||||
"""IK rows: a straight line to a place spot further than REACH_MM from the column fails."""
|
||||
out = []
|
||||
for n, p in wp:
|
||||
far = n.startswith("to (") and col(*map(float, n[4:].split(")")[0].split(", "))) > REACH_MM
|
||||
out.append([n, p, [0] * 6, "no IK solution" if far else None])
|
||||
return out
|
||||
|
||||
|
||||
def do_place(wp):
|
||||
x, y = (float(v) for v in placed["at"])
|
||||
log.append(("place", round(x), round(y)))
|
||||
room["holding"] = None
|
||||
skills._held.clear()
|
||||
|
||||
|
||||
placed = {"at": None}
|
||||
real_place_at = fetch._place_at
|
||||
|
||||
|
||||
def place_at(tries, top):
|
||||
for p in tries:
|
||||
if col(*p) <= REACH_MM:
|
||||
placed["at"] = p
|
||||
break
|
||||
return real_place_at(tries, top)
|
||||
|
||||
|
||||
skills.reachable_pick = reachable
|
||||
skills._do_pick = do_pick
|
||||
skills._do_place = do_place
|
||||
skills.ik_chain = chain
|
||||
skills.place_options = lambda *a: iter(())
|
||||
skills._line = lambda name, pose: None
|
||||
fetch._place_at = place_at
|
||||
|
||||
|
||||
def setup(cup_arm=None, table=(0.355, 1.255, -0.6, 0.6), pose=(0.0, 0.0, 0.0)):
|
||||
"""A new scene: the base at `pose`, the table, a cup seen at `cup_arm` (mm, arm frame from that pose)."""
|
||||
fetch.CALIB_FILE.write_text(json.dumps(CALIB))
|
||||
fetch._state.update(status="idle", holding=False, step="", log=[])
|
||||
base["pose"], room["table"], room["cups"], room["holding"], room["chairs"] = pose, table, [], None, []
|
||||
body.update(lift=0.0, waist=WAIST0, yaw=0.0)
|
||||
log.clear()
|
||||
skills._held.clear()
|
||||
if cup_arm:
|
||||
room["cups"].append({"id": 1, "map": fetch.map_xy({"x": cup_arm[0], "y": cup_arm[1]})})
|
||||
|
||||
|
||||
def run(fn, *a):
|
||||
fn(*a)
|
||||
fetch._thread.join(10)
|
||||
assert not fetch._thread.is_alive()
|
||||
return fetch.state()
|
||||
|
||||
|
||||
TASK = {"object": "cup", "colour": None, "source": "here", "dest": "here", "finish": "hold"}
|
||||
|
||||
|
||||
def repeats():
|
||||
"""Base moves made twice from the same pose the same way (a move that did nothing tried again)."""
|
||||
seen, out = set(), []
|
||||
for line in fetch.state()["log"]:
|
||||
if "to bring it to" in line:
|
||||
key = line.split(" ", 1)[1]
|
||||
out += [key] if key in seen else []
|
||||
seen.add(key)
|
||||
return out
|
||||
|
||||
|
||||
# ---------- (a) 17:57: the cup at (-117, 960); the base stops at the table with it at (-104, 694) ----------
|
||||
# The table's near edge where the base's front stops with the cup ~0.71 m from the column: it is taken from there
|
||||
# (the base can't bring it nearer), every way in tried once, nothing repeated, nobody asked.
|
||||
setup((-117.0, 960.0), table=(0.6, 1.4, -0.6, 0.6))
|
||||
st = run(fetch.start, TASK)
|
||||
picks = [l for l in log if l[0] == "pick"]
|
||||
assert st["status"] == "holding" and len(picks) == 1, (st["log"], log)
|
||||
assert not any("asking" in l for l in st["log"]) and not repeats(), st["log"]
|
||||
assert any("edge of my reach" in l for l in st["log"]), st["log"]
|
||||
print("17:57 picked at", picks[0][1:], "column", picks[0][3])
|
||||
|
||||
# ---------- (b) 18:13: (-141, 869) across the table, the base already at it: round to another side ----------
|
||||
setup((-141.0, 869.0), table=(0.355, 1.255, -0.6, 0.6))
|
||||
st = run(fetch.start, TASK)
|
||||
picks = [l for l in log if l[0] == "pick"]
|
||||
assert st["status"] == "holding" and len(picks) == 1 and not fetch.at_edge(dict(zip("xy", picks[0][1:3]))), (st["log"], log)
|
||||
assert any(l[0] == "nav" for l in log) and not repeats(), (st["log"], log)
|
||||
assert not any(l[0] == "straight" and l[2] == 0 and l[1] != 0 for l in log[1:] if l in log[:log.index(l)]), log
|
||||
print("18:13 picked at", picks[0][1:], "after", sum(l[0] == "nav" for l in log), "drive(s) round")
|
||||
|
||||
# ---------- (a) the far-edge and side cups in a free room: the base brings each to the comfortable zone first ------
|
||||
for cup in ((262.0, 774.0), (260.0, 722.0), (300.0, 621.0), (-99.0, 738.0), (-104.0, 694.0)):
|
||||
setup(cup, table=(5.0, 6.0, 5.0, 6.0)) # the table far away: the floor is free
|
||||
room["z"] = -328.0
|
||||
st = run(fetch.start, TASK)
|
||||
picks = [l for l in log if l[0] == "pick"]
|
||||
assert st["status"] == "holding" and len(picks) == 1, (cup, st["log"])
|
||||
assert not fetch.at_edge(dict(zip("xy", picks[0][1:3]))), (cup, picks, st["log"])
|
||||
print(cup, "picked at", picks[0][1:3], "column", picks[0][3])
|
||||
|
||||
# ... the same cups with the table in front blocking every way: taken from where it stands (reachable), not asked
|
||||
for cup in ((-99.0, 738.0), (300.0, 621.0), (-104.0, 694.0)):
|
||||
setup(cup, table=(0.355, 1.6, -1.5, 1.5))
|
||||
st = run(fetch.start, TASK)
|
||||
picks = [l for l in log if l[0] == "pick"]
|
||||
assert st["status"] == "holding" and len(picks) == 1 and not repeats(), (cup, st["log"])
|
||||
assert picks[0][4] == (picks[0][3] > TRUSTED_REACH_MM), picks # a large turn only when nothing else reaches
|
||||
print(cup, "blocked: picked from where it stands, column", picks[0][3], "any turn" if picks[0][4] else "")
|
||||
|
||||
# ---------- (c) kept: after a base move the cup it went for is taken, not another one nearer the camera ----------
|
||||
setup((262.0, 774.0), table=(5.0, 6.0, 5.0, 6.0))
|
||||
first = room["cups"][0]["map"]
|
||||
room["cups"].append({"id": 2, "map": fetch.map_xy({"x": -250.0, "y": 450.0})}) # another cup, nearer after the move
|
||||
skills.find = lambda name="cup", colour=None, seen=None: next(o for o in cups() if o["id"] == 1) # the one chosen
|
||||
real_see = fetch._see
|
||||
fetch._see = lambda task, say=None: (setattr(skills, "find", find), real_see(task, say))[1] # then any
|
||||
obj = next(o for o in cups() if o["id"] == 1)
|
||||
got = fetch._reach({"object": "cup", "colour": None}, obj, None)
|
||||
fetch._see, skills.find = real_see, find
|
||||
assert got[0]["id"] == 1 and any("where I kept it" in l for l in fetch.state()["log"]), fetch.state()["log"]
|
||||
|
||||
# ---------- (g) 18:53 place: holding at lift 0, the table in front hidden by the held cup near, seen further away,
|
||||
# the base can't get nearer: put down on the part of it the arm reaches, no base move repeated ----------
|
||||
setup(None, table=(0.355, 1.6, -1.0, 1.0))
|
||||
room["holding"] = {"id": 9, "map": None}
|
||||
fetch._set(holding=True, status="holding", held_object={"object": "cup", "colour": "white"})
|
||||
skills._held.update(top_mm=-183.0, x=-73.0, y=588.0, table=-329.0, base=(9.0, 9.0, 0.0), what={"object": "cup"})
|
||||
assert fetch.table_ahead() is None # live: "no table in view"
|
||||
st = run(fetch.place)
|
||||
done = [l for l in log if l[0] == "place"]
|
||||
assert st["status"] == "done" and done and col(*done[0][1:]) <= REACH_MM, (st["log"], log)
|
||||
assert not any(l[0] == "straight" for l in log), (st["log"], log)
|
||||
print("18:53 put down at", done[0][1:])
|
||||
|
||||
# ---------- (h) 18:55: "the white table": its box centre at (22, 623), then (-349, 647) after a turn ----------
|
||||
setup(None, table=(0.355, 1.6, -1.0, 1.0))
|
||||
room["holding"] = {"id": 9, "map": None}
|
||||
fetch._set(holding=True, status="holding", held_object={"object": "cup", "colour": "white"})
|
||||
skills._held.update(top_mm=-183.0, x=-73.0, y=588.0, table=-329.0, base=(9.0, 9.0, 0.0), what={"object": "cup"})
|
||||
box = {"at": (22.0, 623.0)}
|
||||
real_turn, real_head_seen = fetch._turn, fetch._head_seen
|
||||
fetch._head_seen = lambda match: {"x": box["at"][0], "y": box["at"][1], "head": True} # seen by the head camera
|
||||
fetch._turn = lambda deg, *a, **k: (box.update(at=(-349.0, 647.0)), real_turn(deg, *a, **k))[1]
|
||||
st = run(fetch.place, None, {"name": "dining table", "colour": "white"})
|
||||
fetch._turn, fetch._head_seen = real_turn, real_head_seen
|
||||
done = [l for l in log if l[0] == "place"]
|
||||
assert st["status"] == "done" and done and not any(l[0] == "turn" for l in log), (st["log"], log)
|
||||
print("18:55 put down at", done[0][1:], "without turning")
|
||||
# ---------- X1 round 2: a chair in front of the table: the side with room to stand is driven to first ----------
|
||||
setup((-100.0, 1000.0), table=(0.8, 1.4, -0.3, 0.3))
|
||||
room["chairs"] = [(0.35, 0.75, -0.3, 0.3)]
|
||||
st = run(fetch.start, TASK)
|
||||
picks = [l for l in log if l[0] == "pick"]
|
||||
assert st["status"] == "holding" and picks and sum(l[0] == "nav" for l in log) == 1, (st["log"], log)
|
||||
print("chair in front: picked at", picks[0][1:3], "after one drive round")
|
||||
|
||||
# ---------- X1: a cup on a low table drops out of the torso camera at the pick zone (lift 0): the goal moves out ----
|
||||
room["z"] = -480.0
|
||||
setup((-100.0, 1000.0), table=(5.0, 6.0, 5.0, 6.0))
|
||||
room["z"] = -480.0
|
||||
st = run(fetch.start, TASK)
|
||||
picks = [l for l in log if l[0] == "pick"]
|
||||
assert st["status"] == "holding" and picks and picks[0][2] > 600, (st["log"], log)
|
||||
print("low table picked at", picks[0][1:3])
|
||||
setup((-100.0, 1000.0), table=(5.0, 6.0, 5.0, 6.0)) # lower still: nowhere both seen and reached: said at once
|
||||
room["z"] = -560.0
|
||||
st = run(fetch.start, TASK)
|
||||
assert st["status"] == "failed" and "too low" in st["log"][-1] and not any(l[0] == "straight" for l in log), st["log"]
|
||||
room["z"] = -328.0
|
||||
|
||||
# ---------- X1: a cup too near to be seen (the table right at the base): back off and look before the search -------
|
||||
setup((-100.0, 380.0), table=(0.37, 1.0, -0.6, 0.6))
|
||||
room["cups"][0]["map"] = np.array([0.40, 0.10]) # on the table's near edge, under the cameras' view
|
||||
assert not cups()
|
||||
st = run(fetch.start, TASK)
|
||||
assert any("backing off" in l for l in st["log"]) and st["status"] == "holding", st["log"]
|
||||
assert not any("look around" in l.lower() for l in st["log"]), st["log"]
|
||||
print("fetch ways ok")
|
||||
@@ -83,11 +83,14 @@ CONF = ["home", "dock2", "Main_Stage", "Booth_12", "Registration", "포토존",
|
||||
KOREAN = ["home", "커피코너", "부스3", "입구", "무대", "안내데스크", "휴게실", "회의실"]
|
||||
for t, mk, want in (("Go to booth bee.", EXPO, "booth_B"), ("에이 부스로 가 줘", EXPO, "booth_A"),
|
||||
("인포 대스크로 가 줘", EXPO, "info_desk"), ("레지스트레이션으로 가 줘", CONF, "Registration"),
|
||||
("부스 십이로 가 줘", CONF, "Booth_12"), ("출구 B로 가 봐", CONF, "Exit_B"),
|
||||
("삼 번 부스로 가", KOREAN, "부스3"), ("go to the information desk", KOREAN, "안내데스크"),
|
||||
("부스 십이로 가 줘", CONF, "Booth_12"), ("엑시트 비로 가 봐", CONF, "Exit_B"),
|
||||
("삼 번 부스로 가", KOREAN, "부스3"), ("인포 데스크로 가", EXPO, "info_desk"),
|
||||
("roll over to the coffee corner", KOREAN, "커피코너"), ("Would you mind heading to dock 2?", EXPO, "dock2")):
|
||||
assert [m for m in mk if brain.named_place(t, m, mk)] == [want], (t, want)
|
||||
assert not [m for m in EXPO if brain.named_place("go to the booth", m, EXPO)] # which booth: asked
|
||||
for t, mk in (("출구 B로 가 봐", CONF), ("go to the information desk", KOREAN), ("출구로 가", ["home", "exit"]),
|
||||
("무대로 가", EXPO)): # a word that only means the place: asked, never translated
|
||||
assert not [m for m in mk if brain.named_place(t, m, mk)], t
|
||||
assert brain.intent("go to the stage... wait, not the stage, the entrance", KOREAN) is None
|
||||
|
||||
# ---------- "go where I point" in many wordings (vision/pointing.asked); not a place, a negation, later ----------
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
"""tests/parity_check.py on a few fixed sentences: typed (the Command box) and voice give the same plan, English and
|
||||
Korean the same, each the one asked for. Rules only, nothing moves: python tests/test_parity.py"""
|
||||
from tests import parity_check as pc
|
||||
|
||||
M = ["p1", "p2", "p3", "p5", "home", "exit", "dock2"]
|
||||
CASES = [ # (text, state, expect)
|
||||
("go to p1", "idle", "action:go_to p1 | mission"), ("p1로 가 줘", "idle", "action:go_to p1 | mission"),
|
||||
("p1으로 가십시오", "idle", "action:go_to p1 | mission"),
|
||||
("turn left", "idle", "action:turn left"), ("왼쪽으로 돌아", "idle", "action:turn left"),
|
||||
("stop", "idle", "stop"), ("멈춰", "idle", "stop"), ("그만해요", "idle", "stop"),
|
||||
("wave", "idle", "action:wave"), ("손 흔들어", "idle", "action:wave"),
|
||||
("take this from me", "idle", "receive"), ("이거 받아", "idle", "receive"),
|
||||
("pick up the red cup", "idle", "action:pick red cup | action:fetch cup"),
|
||||
("빨간 컵 집어", "idle", "action:pick red cup | action:fetch cup"),
|
||||
("put it on the table", "holding", "place"), ("테이블에 놔", "holding", "place"),
|
||||
("put it on the table", "idle", "empty_hand | talk"),
|
||||
("what time is it?", "idle", "talk"), ("몇 시야?", "idle", "talk"),
|
||||
]
|
||||
|
||||
assert pc.canon("action:go_to p1") == pc.canon("mission", st=[{"do": "go", "to": "p1"}]) == "steps go p1"
|
||||
assert pc.canon("talk") == pc.canon("refuse") == pc.canon("llm?") == "none"
|
||||
assert pc.typed_got({"action": "steps", "steps": [{"do": "turn", "deg": 90.0}]})[0] == "action:turn left 90"
|
||||
|
||||
bad = []
|
||||
for text, state, expect in CASES:
|
||||
c = {"text": text, "state": state, "before": None, "expect": expect, "lang": "ko" if pc.brain.HANGUL.search(text)
|
||||
else "en", "markers": M, "intent": "fixed"}
|
||||
r = pc.run_case("fixed", "fixed", c, None, False)
|
||||
if not r["same"] or r["v"] not in ("right", "llm?") or r["t"] not in ("right", "llm?"): # llm?: a question
|
||||
bad.append(r)
|
||||
print(f"BAD [{state}] {text!r}: voice {r['voice']} ({r['v']}), typed {r['typed']} ({r['t']}), want {expect}")
|
||||
print(f"{len(CASES) - len(bad)}/{len(CASES)} the same typed and by voice, as asked")
|
||||
assert not bad
|
||||
print("parity ok")
|
||||
@@ -0,0 +1,51 @@
|
||||
"""Self-check of the pick / place sweep's hardest fixed scenes (tests/pick_sweep.py simulator, no robot):
|
||||
python tests/test_pick_sweep.py
|
||||
|
||||
The live positions of 2026-10-26 (WORK_PLAN "Big night test 5", faults (a), (b), (e), (f)) and the hardest sweep
|
||||
scenes, run through the real fetch._pick_here: each must end holding the cup with the fingers on it, or refuse for
|
||||
a physical reason (no stand reaches it), never crash, never repeat a base move that went nowhere. Scenes still open
|
||||
(OPEN) are run and printed, not asserted: they are the next work (docs/night5/X1.md)."""
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
from tests import pick_sweep as ps
|
||||
|
||||
ps.install()
|
||||
at = ps.pick_at
|
||||
MUST = { # name: (scene, camera error)
|
||||
"picked live 15:39": (at(-96, 598, -260), 0.0),
|
||||
"17:57 carry line refused": (at(-104, 694, -186), 0.0),
|
||||
"18:13 across the table": (at(-141, 869, -186), 0.0),
|
||||
"18:13, base stops 0.25 m early": (at(-141, 869, -186, stall_gap=0.25), 0.0),
|
||||
"18:30 far edge, turned -45": (at(262, 774, -189), 0.0),
|
||||
"18:40 turned -30": (at(260, 722, -186), 0.0),
|
||||
"18:40 turned -30, nearer": (at(300, 621, -191), 0.0),
|
||||
"18:45 straight ahead": (at(-99, 738, -181), 0.0),
|
||||
"far edge on a low table (-450)": (at(262, 774, -330, height=120), 0.0),
|
||||
"sweep 54: low table -432": (ps.make_pick(54, 1), 1.0),
|
||||
"sweep 189: low table -440": (ps.make_pick(189, 1), 1.0),
|
||||
}
|
||||
PHYSICAL = {"18:13 behind a chair": (at(-141, 869, -186, stall_gap=0.25, chair=0.3), 0.0),
|
||||
"sweep 534: behind a chair, low table": (ps.make_pick(534, 1), 1.0)} # was picked turned -30 once
|
||||
OPEN = {}
|
||||
|
||||
bad = []
|
||||
for group, scenes in (("must", MUST), ("physical", PHYSICAL), ("open", OPEN)):
|
||||
for name, (sc, cam) in scenes.items():
|
||||
for t in sc["tables"] + sc["boxes"]:
|
||||
t["half"] = [float(v) for v in t["half"]]
|
||||
r = ps.run_scene(sc, cam)
|
||||
t, j5 = ps.parse_grasp(r.get("grasp"))
|
||||
print(f"{group:8s} {name:36s} {r['result']:8s} turn {t} J5 {j5} waist {r['waist_end']:+.0f} landing "
|
||||
f"{(r.get('landings') or [None])[-1]} moves {[m[:3] for m in r['moves']]} {r.get('why') or ''}")
|
||||
if group == "open":
|
||||
continue
|
||||
if r["result"] in ("exception", "timeout") or r["repeats"]:
|
||||
bad.append((name, r["result"], r.get("why"), r["repeats"]))
|
||||
elif group == "must" and (r["result"] != "ok" or not r["landings"][-1][2]):
|
||||
bad.append((name, r["result"], r.get("why"), r.get("landings")))
|
||||
elif group == "physical" and (r["result"] == "ok" or ps.way_exists(sc) is not None):
|
||||
bad.append((name, "no longer physical", r["result"]))
|
||||
assert not bad, bad
|
||||
print("pick sweep scenes ok")
|
||||
+62
-5
@@ -13,8 +13,24 @@ from manipulation import arm_route, skills
|
||||
from tasks import fetch
|
||||
|
||||
# ---------- the offline kinematics: the controller's own answers ----------
|
||||
mm, deg = kinematics.errors()
|
||||
assert mm < 0.5 and deg < 0.1, (mm, deg)
|
||||
SAMPLES = ( # joints, the flange pose the controller reported (calibration
|
||||
([87.074, -80.539, -21.134, 0.608, -113.653, -47.948], # samples of the torso and the head camera; the samples
|
||||
[47.777, 320.575, -20.839, 86.777, 45.757, -57.042]), # themselves stay on the Thor)
|
||||
([69.322, -78.233, -38.969, -5.131, -100.011, -69.562],
|
||||
[6.08, 270.561, -123.566, 77.877, 51.571, -62.655]),
|
||||
([101.531, -72.825, 6.01, 5.321, -102.275, -53.297],
|
||||
[174.924, 414.109, 93.127, 72.719, 64.842, -115.343]),
|
||||
([-272.27, -100.091, -8.001, 234.453, 83.508, 134.594],
|
||||
[-9.389, 400.198, 107.353, 31.332, 18.372, -113.47]),
|
||||
([-260.075, -97.103, -25.513, 228.746, 69.866, 129.55],
|
||||
[-66.288, 354.894, 170.458, 37.788, 29.511, -109.309]),
|
||||
(skills.TEACH["joints"], skills.TEACH["flange"])) # the taught grasp
|
||||
for j, p in SAMPLES:
|
||||
T = kinematics.fk(j)
|
||||
R = skills.calib.rpy_matrix(*p[3:])
|
||||
assert np.linalg.norm(T[:3, 3] - p[:3]) < 0.5 and np.degrees(np.arccos(min(1.0, (np.trace(T[:3, :3].T @ R) - 1) / 2))) < 0.1, j
|
||||
HEAD = np.array([-92.97, -19.87, 356.12]) # the head's turning centre (vision/head_cam.py fit 2026-10-19)
|
||||
arm_route.head_cam.head_centre = lambda: HEAD
|
||||
for name, j in motion.poses().items(): # IK from a seed 8 deg off: the same flange pose
|
||||
p = kinematics.pose(j)
|
||||
s = kinematics.ik(p, [a + 8.0 for a in j])
|
||||
@@ -30,12 +46,37 @@ fetch.log = skills.log = arm_route.log = lambda *a: lines.append(" ".join(str(x)
|
||||
cup = lambda x, y, top=-260.0: {"name": "cup", "colour": "grey", "x": float(x), "y": float(y), "top_mm": top,
|
||||
"width_mm": 76.0, "seen": 8, "spread": 1.0}
|
||||
reach = lambda o: skills.reachable_pick(o, accept=fetch._carry_ok)
|
||||
trusted = lambda o: skills.reachable_pick(o, accept=fetch._carry_ok, max_yaw=skills.TRUSTED_YAW_DEG) # fetch's first try
|
||||
|
||||
plan = reach(cup(-96, 598)) # picked live 2026-10-2x 15:39 (J5 +20, no turn)
|
||||
assert plan and abs(skills.yaw_of(plan[0][1][1])) < 1, plan
|
||||
for xy in ((-171, 697), (-395, 629), (-480, 652)): # refused live from where it stood: still out of reach
|
||||
assert reach(cup(*xy)) is None, xy # of the arm alone at waist 0 (base moved then)
|
||||
|
||||
# 2026-10-26 18:40 at lift 0: (260, 722) top -186 was planned turned -30 deg, J5 +26 (missed live, as every turn
|
||||
# over 15 deg): offline the same; within the trusted turns there is none from here (the waist or the base first)
|
||||
plan = reach(cup(260, 722, -186))
|
||||
assert plan and round(skills.yaw_of(plan[0][1][1])) == -30 and 20 < plan[1][4] < 30, plan
|
||||
assert skills.reachable_pick(cup(260, 722, -186), accept=fetch._carry_ok, max_yaw=skills.TRUSTED_YAW_DEG) is None
|
||||
|
||||
# 17:57 / 18:45: (-104, 694) and (-99, 738) top -186: every straight line to carry refused (a joint jumps); straight up
|
||||
# and one joint move to carry takes the cup there instead (upright, clear of the head)
|
||||
def line_ok(w, ja): # the straight line alone (fetch._carry_ok also takes carry_up)
|
||||
try:
|
||||
fetch._line_rows(kinematics.pose(motion.poses()["carry"]), "to carry", start=(w[0][1], ja))
|
||||
return True
|
||||
except fetch.FetchError:
|
||||
return False
|
||||
for xy in ((-104, 694), (-99, 738)):
|
||||
assert skills.reachable_pick(cup(*xy, -186), accept=line_ok) is None, xy
|
||||
plan = skills.reachable_pick(cup(*xy, -186), accept=lambda w, ja: skills.carry_up(w[0][1], ja) is not None)
|
||||
assert plan, xy
|
||||
via, carry = skills.carry_up(plan[0][0][1], plan[1])
|
||||
assert via[2] > plan[0][0][1][2] and np.allclose(kinematics.pose(carry)[:3], kinematics.pose(motion.poses()["carry"])[:3], atol=0.1)
|
||||
plan = skills.reachable_pick(cup(-104, 694, -186), accept=lambda w, ja: skills.carry_up(w[0][1], ja) is not None,
|
||||
max_yaw=skills.TRUSTED_YAW_DEG)
|
||||
assert plan and abs(skills.yaw_of(plan[0][1][1])) <= 15.5, plan
|
||||
|
||||
# a held IK answer with J4 one turn round (the same pose) is not a joint-limit or flip refusal
|
||||
real_ask = skills._ask
|
||||
def turned_j4(name, **a):
|
||||
@@ -72,14 +113,14 @@ assert np.allclose([fetch.turned(t, -30.0)[k] for k in "xy"], [o[k] for k in "xy
|
||||
|
||||
for r, b in ((600, 60), (600, -60), (550, 90), (600, -100), (730, 7), (720, 25)): # beside it and the live ones
|
||||
o = around(r, b)
|
||||
assert reach(o) is None, (r, b) # not from here ...
|
||||
assert trusted(o) is None, (r, b) # not from here ...
|
||||
turns = fetch.waist_for(o)
|
||||
assert turns and any(reach(fetch.turned(o, d)) for d in turns), (r, b, turns) # ... after a waist turn
|
||||
assert turns and any(trusted(fetch.turned(o, d)) for d in turns), (r, b, turns) # ... after a waist turn
|
||||
assert abs(turns[0] - (b - math.degrees(math.atan2(-(fetch.PICK_ZONE_CENTRE[0] - C[0]),
|
||||
fetch.PICK_ZONE_CENTRE[1] - C[1])))) < 1e-6
|
||||
for r, b in ((1000, 0), (950, 40)): # too far for any waist turn: the base has to move
|
||||
o = around(r, b)
|
||||
assert all(reach(fetch.turned(o, d)) is None for d in fetch.waist_for(o)), (r, b)
|
||||
assert all(trusted(fetch.turned(o, d)) is None for d in fetch.waist_for(o)), (r, b)
|
||||
body["waist"] = 100.0 # the waist near its limit (140): no turn past it
|
||||
assert all(body["waist"] + d <= 140.0 for d in fetch.waist_for(around(600, 80)))
|
||||
body["waist"] = -20.31
|
||||
@@ -127,4 +168,20 @@ calls.clear()
|
||||
scene["cup"] = around(600, -70) # the cup was moved away while the waist turned
|
||||
skills.look = lambda *a, **k: []
|
||||
assert fetch._waist_reach(task, scene["cup"], None) is None and any(c[0] == "waist" for c in calls)
|
||||
# ---------- the controller confirms only the chosen plan (a stand-in behind arm.cmd here) ----------
|
||||
asked, shift = [], {"mm": 0.0}
|
||||
def controller(name, **a):
|
||||
asked.append(name)
|
||||
r = kinematics.ask(name, **a)
|
||||
if name == "kine_forward":
|
||||
r["cartPosition"][0] += shift["mm"]
|
||||
return r
|
||||
real_cmd = skills.arm.cmd
|
||||
skills.arm.cmd = skills._ARM_CMD = controller
|
||||
skills._ask = skills._ASK # planning offline, only confirm() asks the "controller"
|
||||
skills.home_joints = lambda: list(LOOK)
|
||||
assert reach(cup(-96, 598)) and sorted(asked) == ["kine_forward", "kine_inverse"], asked
|
||||
shift["mm"] = 5.0 # the controller disagrees with the offline model: no plan
|
||||
assert reach(cup(-96, 598)) is None and any("the controller puts" in l for l in lines)
|
||||
skills.arm.cmd = skills._ARM_CMD = real_cmd
|
||||
print("reach ok")
|
||||
|
||||
+32
-1
@@ -1,9 +1,12 @@
|
||||
"""Self-check of the skills.py geometry, no robot: python tests/test_skills.py"""
|
||||
import numpy as np
|
||||
|
||||
from vision import calib
|
||||
from vision import calib, head_cam
|
||||
from manipulation import skills
|
||||
|
||||
head_cam.head_centre = lambda: np.array([-92.97, -19.87, 356.12]) # the head's turning centre (head_cam fit 2026-10-19;
|
||||
# its file stays on the Thor)
|
||||
|
||||
cup = {"name": "cup", "colour": "white", "x": -126.5, "y": 613.0, "top_mm": -261.0, "width_mm": 76.0}
|
||||
R = calib.rpy_matrix(*skills.GRASP_RPY)
|
||||
g = np.array([cup["x"], cup["y"], cup["top_mm"] - 40])
|
||||
@@ -308,3 +311,31 @@ 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")
|
||||
|
||||
# offset_fix: hover readings at one spot (ring centre - rim centre) = e - Rz(turn) u; the error u of the taught grasp
|
||||
# point turns with the grasp, the camera's e does not
|
||||
u, e = np.array([12.0, -7.0]), np.array([3.0, 2.0])
|
||||
reads = [(t, e - skills._rz(t)[:2, :2] @ u) for t in (0.0, -30.0, -45.0)]
|
||||
got_u, got_e, new = skills.offset_fix(reads)
|
||||
assert np.allclose(got_u, u) and np.allclose(got_e, e)
|
||||
fixed = skills.flange_for(-100.0, 600.0, -300.0, -30.0) # with the new offset the ring lands on the cup at any turn
|
||||
Rt = calib.rpy_matrix(*fixed[3:])
|
||||
assert np.allclose((np.array(fixed[:3]) + Rt @ new)[:2], np.array([-100.0, 600.0]) - skills._rz(-30.0)[:2, :2] @ u)
|
||||
print("skills offset ok")
|
||||
|
||||
# on_table: a spot whose near ring point is just off the table's near edge is not table, though that sight line, aimed
|
||||
# a little too high, meets the top a bit further on at table height (X1's sweep, a cup put down 17 mm off the edge)
|
||||
CAM, EDGE_Y, TOP = np.array([-258.0, 14.0, -41.0]), 600.0, -420.0
|
||||
def cast(pts, guess_z=-400.0):
|
||||
out = []
|
||||
for p in pts:
|
||||
p = np.array([p[0], p[1], p[2] if len(p) > 2 else guess_z])
|
||||
d = (p - CAM) / np.linalg.norm(p - CAM)
|
||||
q = CAM + d * (TOP - CAM[2]) / d[2] # where the line meets the table's plane
|
||||
out.append(tuple(q) if q[1] >= EDGE_Y else tuple(CAM + d * (-900.0 - CAM[2]) / d[2])) # else the floor
|
||||
return out
|
||||
skills.surface_points = cast
|
||||
assert skills.on_table([(-100.0, 700.0)], -400.0) == [(-100.0, 700.0)] # well on it, table read 20 mm high
|
||||
assert skills.on_table([(-100.0, 620.0)], -400.0) == [] # its near ring point 5 mm off the edge
|
||||
assert skills.on_table([(-100.0, 700.0)]) == [(-100.0, 700.0)] # table height not given
|
||||
print("skills on_table ok")
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
"""Self-check of the talk prompt (T1), no LLM, no embeddings: the model and the note search are faked.
|
||||
- The date and time the model is given come from the clock (web.now_text), never from the model: every LLM path that
|
||||
can be asked the time puts "Now it is ..." with today's date in its prompt: respond_stream (talk), respond_from (a
|
||||
lookup's answer).
|
||||
- The subject of a world question (Brain.world_talk): an adverb with 는 is none ("공식적으로는"), "X 그거" names X,
|
||||
"X는 뭐예요?" is X alone; world questions are shown world-knowledge examples only.
|
||||
|
||||
python tests/test_talk.py
|
||||
"""
|
||||
import time
|
||||
|
||||
from assistant import brain, knowledge, memory, talk_examples, web
|
||||
|
||||
FAKE_NOW = "Friday, 13 March 2026, 10:05" # a date the model could never have guessed
|
||||
sent = []
|
||||
|
||||
|
||||
def fake_stream(messages):
|
||||
sent.append(messages)
|
||||
return iter(["ACTION: none -\nIt is 10:05 am.\n"])
|
||||
|
||||
|
||||
brain._stream = fake_stream
|
||||
knowledge.search = lambda text, k=4: []
|
||||
talk_examples.pick = lambda *a, **kw: []
|
||||
memory.turn_lines = lambda b, text: ""
|
||||
web.now_text = lambda: FAKE_NOW
|
||||
|
||||
|
||||
def last_message():
|
||||
return sent[-1][-1]["content"]
|
||||
|
||||
|
||||
def main():
|
||||
line = brain.now_line()
|
||||
assert line.startswith(FAKE_NOW), line
|
||||
assert time.strftime("%Y년 %-m월 %-d일") in line and ("오전" in line or "오후" in line), line # the Korean form, from the same clock
|
||||
|
||||
for q in ("What is the time?", "What's the date today?", "지금 몇 시예요?", "오늘 며칠이야?", "지금 몇..."):
|
||||
b = brain.Brain()
|
||||
list(b.respond_stream(q, ["home"], now="I'm not doing any task right now."))
|
||||
assert f"Now it is {FAKE_NOW}" in last_message(), (q, last_message())
|
||||
assert FAKE_NOW not in sent[-1][0]["content"], "the time must stay out of the cached system prompt"
|
||||
|
||||
b = brain.Brain()
|
||||
list(b.respond_from("What day is it in New York?", "New York: Thursday evening."))
|
||||
assert f"Now it is {FAKE_NOW}" in last_message(), last_message()
|
||||
|
||||
for before, q, want in [
|
||||
("저기 2월 29일에 태어나면 생일은 어떻게 해요?", "공식적으로는 언제로 쳐요?", ["생일"]),
|
||||
("공식적으로는 언제로 쳐요?", "윤초는 뭐예요?", ["윤초"]),
|
||||
("생일은 어떻게 해요?", "윤초는 뭐예요?", ["윤초"]),
|
||||
("경복궁 그거 언제 지었노?", "이름은 와 그래 지었노?", ["경복궁"]),
|
||||
("", "부엉이 그거 목 을매나 돌아가노?", ["부엉이"]),
|
||||
("", "너 그거 할 수 있어?", []),
|
||||
("", "루미 그거 뭐야?", []),
|
||||
("문어는 피가 무슨 색이야?", "심장은 몇 개고?", ["문어", "심장"])]:
|
||||
b = brain.Brain()
|
||||
b.history = [(before, "ACTION: none -\n네.")] if before else []
|
||||
assert b.world_talk(q) == want, (before, q, b.world_talk(q))
|
||||
|
||||
b = brain.Brain() # a lookup in the checks / live: its follow-ups are looked up,
|
||||
b.history, b.last_lookup = [("공식적으로는 언제로 쳐요?", "")], "공식적으로는 언제로 쳐요?" # a new subject is not
|
||||
none = {"action": "none", "target": ""}
|
||||
assert b._after(none, "윤초는 뭐예요?") == none
|
||||
assert b._after(none, "몇 살이야?")["action"] == "search"
|
||||
assert b._after(none, "그게 뭐예요?")["action"] == "search"
|
||||
|
||||
picked = []
|
||||
talk_examples.pick = lambda said, lang, k=4, bank=None: picked.append(bank) or []
|
||||
brain._examples("윤초는 뭐예요?", world=True)
|
||||
assert picked[-1] and all(e[0] in brain.WORLD_EXAMPLES for e in picked[-1]), "world: world examples only"
|
||||
brain._examples("이름이 뭐예요?")
|
||||
assert any(e[0] == "name" for e in picked[-1])
|
||||
print("talk: ok")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user