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:
2026-10-27 00:21:00 +09:00
co-authored by Claude Opus 5.5
parent 1b3f4568e1
commit d72eb52f66
39 changed files with 4853 additions and 294 deletions
+5
View File
@@ -60,3 +60,8 @@ docs/night3/
docs/night4/ docs/night4/
tests/blind/r9/ tests/blind/r9/
tests/blind/r10/ tests/blind/r10/
docs/night5/
tests/blind/r11/
tests/blind/r12/
tests/blind/r13/
data/bank_build.lock
+8 -2
View File
@@ -1129,7 +1129,8 @@ def task_parse(body: ParseBody):
problem = brain.place_problem(fixed, markers) problem = brain.place_problem(fixed, markers)
if problem: # quick_command says it: "I don't have a place called p12" if problem: # quick_command says it: "I don't have a place called p12"
return _talk(problem[0], kind="refuse") return _talk(problem[0], kind="refuse")
if held and kind is None and brain.held_command(fixed) and brain.direct_order(fixed) and not brain.not_an_order(fixed): if held and kind is None and (brain.held_command(fixed) and brain.direct_order(fixed) and not brain.not_an_order(fixed)
or brain.held_carry(fixed, markers)): # "p5로 가져가": a carry there
return _held_parse(body, markers) return _held_parse(body, markers)
if kind is None and body.llm: # the rules leave it: the LLM, one call, as by voice if kind is None and body.llm: # the rules leave it: the LLM, one call, as by voice
gen = brain.Brain().respond_stream(fixed, markers) gen = brain.Brain().respond_stream(fixed, markers)
@@ -1239,7 +1240,7 @@ def _held_parse(body, markers):
"""A command while something is held: what to do with it, read by the rules only (fast; the object named in it is """A command while something is held: what to do with it, read by the rules only (fast; the object named in it is
the held one, so "give me the cup" is a give, not a new fetch). A marker named anywhere in the text is where to the held one, so "give me the cup" is a give, not a new fetch). A marker named anywhere in the text is where to
bring it, else the dialog's To; then put it on a table, hand it over or keep holding it.""" bring it, else the dialog's To; then put it on a table, hand it over or keep holding it."""
from assistant import brain from assistant import brain, steps
from tasks import fetch from tasks import fetch
held, text = fetch.held_name(), brain.give_clause(body.text) # not where the person it is for goes held, text = fetch.held_name(), brain.give_clause(body.text) # not where the person it is for goes
m, t = brain._mentions(text, markers), brain._norm(text) m, t = brain._mentions(text, markers), brain._norm(text)
@@ -1258,6 +1259,11 @@ def _held_parse(body, markers):
(on or {}).get("prefer")) # "the lower one": which of several (on or {}).get("prefer")) # "the lower one": which of several
on_words = " ".join(w for w in (which, on.get("colour"), " or ".join(n.replace("dining table", table) for n in on_words = " ".join(w for w in (which, on.get("colour"), " or ".join(n.replace("dining table", table) for n in
[on["name"]] + on.get("alts", []))) if w) if on else "table" [on["name"]] + on.get("alts", []))) if w) if on else "table"
side = steps._side(t) if then == "place" else None # "왼쪽 테이블에 놔", "put it on the right side": the mission's
if dest is None and side: # place step turns to that side first (fetch.place does not)
got = [{"do": "place", "on": {"name": "dining table", "colour": None, **(on or {}), "side": side}}]
return {"action": "steps", "steps": got, "lang": "ko" if brain.HANGUL.search(text) else "en", "sender": None,
"read_by": "rules", **_steps_said(got, markers)}
if dest is None: if dest is None:
if then: if then:
return {"action": then, "task": {"on": on}, "problems": [], "choices": _choices(), return {"action": then, "task": {"on": on}, "problems": [], "choices": _choices(),
+45
View File
@@ -161,6 +161,51 @@ _BANK = {
("한 바퀴 돌아.", "turn left 360", "네, 한 바퀴 돌게요."), ("한 바퀴 돌아.", "turn left 360", "네, 한 바퀴 돌게요."),
], ],
}, },
"own_limits": { # a yes / no question on its own facts: the answer word first ("No," / "아니요,"), then the fact
"en": [
("Can you drive up a 12 degree slope?", "none", "No, at most 8 degrees."),
("What about a 3 cm bump on the floor?", "none", "No, I can only climb steps up to 1.5 cm."),
("If I jog at 3 metres a second, can you keep up?", "none", "No, my top speed is 1.2 metres a second."),
("Could two of you drive side by side in a one metre corridor?", "none", "No, each of us needs a passage at least 70 cm wide."),
("Could you carry my 5 kg backpack?", "none", "No, that's too heavy for me: about 1 kg in my hand."),
("Wave at me while you hold that cup.", "none", "Not while I'm holding the cup: it could fall. Shall I put it down first?"),
("How far away can you hear me?", "none", "From about 3 to 5 metres."),
("Rise up so we're face to face.", "lift up", "Sure, going up."),
("Spread those fingers of yours.", "arm open", "Opening my hand."),
],
"ko": [
("20도 언덕도 올라갈 수 있어?", "none", "아니요, 저는 8도까지만 올라갈 수 있어요."),
("3센티 턱은 넘으실 수 있으세요?", "none", "아니요, 1.5센티까지만 넘을 수 있어요."),
("80센티 복도에 루미 두 대가 나란히 지나갈 수 있습니까?", "none", "아니요, 저 하나가 지나가는 데 70센티가 필요해서 둘은 어렵습니다."),
("내가 초속 3미터로 뛰면 따라올 수 있어?", "none", "아니요, 제 최고 속도는 초속 1.2미터예요."),
("컵 든 채로 손 흔들어 줘~", "none", "컵을 들고 있어서 지금은 손을 흔들 수 없어요. 먼저 내려놓을까요?"),
("몇 미터 떨어져서 말해도 들리시나요?", "none", "3미터에서 5미터 정도까지 잘 들려요."),
("날 좀 똑바로 쳐다봐 주이소.", "look me", "네, 보고 있어요."),
("집게 좀 벌려 보십시오.", "arm open", "네, 손을 벌리겠습니다."),
],
},
"order_in_talk": { # an order said in the middle of a topic: the order now, the topic goes on after it
"en": [
("Keep telling me about the Moon, and look at me while you do.", "look me", "Sure, I'm looking at you. Where was I?"),
("Before the volcano part, shake my hand.", "wave", "Happily! Here's a wave."),
("While you explain, hold your hand out to me.", "arm reach", "Here's my hand."),
("Um, tell me the whale part again, and look up first.", "look up", "Looking up. Whales sing to find each other."),
("Hang on, give me your hand, then go on about the bees.", "arm reach", "Here you go. Now, the bees."),
("Your story about the palace was cute when you waved.", "none", "Thank you! Shall I tell you more about the palace?"),
("When you finish the Moon story, come here.", "none", "Okay, I'll finish the story first."),
],
"ko": [
("달력 얘기 하시면서 저 좀 봐 주시겠어요?", "look me", "네, 보면서 말씀드릴게요."),
("설명하시는 동안 저를 봐 주십시오.", "look me", "네, 보면서 설명드리겠습니다."),
("전기차 얘기 전에 악수부터 하자.", "wave", "좋아요, 손 흔들어 드릴게요!"),
("상어 얘기하믄서 손 쫌 내밀어 봐라.", "arm reach", "네, 손 내밀게요."),
("부엉이 얘기 하다가 잠깐 위 좀 봐 줄래?", "look up", "네, 위를 볼게요."),
("할머니께 손 좀 흔들어 드리면서 얘기해 주세요.", "wave", "네, 할머니, 안녕하세요!"),
("얘기하다가 나 한 번 봐 주라~", "look me", "네, 보고 있어요."),
("거북선 얘기 끝나면 무대 쪽으로 가 주십시오.", "none", "네, 거북선 얘기를 마치고 말씀해 주시면 가겠습니다."),
("아까 손 흔든 거 귀여웠어요.", "none", "고마워요! 또 흔들어 드릴까요?"),
],
},
"hand": { "hand": {
"en": [ "en": [
("Give it to me.", "give", "Here you go."), ("Give it to me.", "give", "Here you go."),
+380
View File
@@ -0,0 +1,380 @@
"""More arm and hand wordings for the intent bank (night 5, beyond assistant/bank_words/arm.py): new verbs, frames
and keywords for every arm / hand capability, side words for pick and put ("왼쪽에 있는 컵 집어", "put it down to your
right": the bank keeps them pick / put, the side itself is the rules' or the LLM's), Korean at every level (반말,
해요체, 하십시오체, 하게체, honorific, dialect, Konglish, slips), and hard negatives for "no" (questions about the arm,
remarks, applause and hand gestures Lumi has none of, past, other people's hands).
Endings are written plainly once per stem: the bank stores Korean as wording.ko_plain reads it, so "주십시오" and
"주세요" become one wording; what grows the bank is new verbs and frames, not more endings.
"""
from assistant.bank_words.arm import _ko, _en, ASK_SHORT
# speech levels the ASK lists of arm.py do not have (하게체, 하오체, honorific, more dialect, slips)
LEVELS = ["", " 줘", " 주세요", " 주십시오", " 주시게", " 주시오", " 주쇼", " 주이소", " 줘유", " 주랑께", " 주라", " 줘라",
" 봐", " 보래이", " 봐라잉", " 보소", " 봐유", " 주시지요", " 주시죠", " 주실 수 있으세요?", " 주시겠어요?",
" 줄래", " 줄래요?", " 줘요", " 조", " 쥬", " 도", " 주실래요?"]
SHORT = ["", " 줘", " 주세요", " 주십시오", " 주시게", " 주쇼", " 줘유", " 봐", " 보래이"]
# ---------- wave (every handshake form: the owner's meaning) ----------
WAVE = [
"give me a shake", "let's shake on it", "shake on it", "how about a shake", "can we shake hands",
"let's do a handshake", "handshake time", "time for a handshake", "a handshake, robot", "shake hands, robot",
"shake my hand, friend", "let me shake your hand", "i'd like to shake your hand", "i want to shake your hand",
"i want to shake hands with you", "i'd like a handshake", "shake hands with my son", "shake hands with grandma",
"shake hands with our guest", "shake hands with the kids", "go ahead and shake my hand", "come on, shake my hand",
"wave hi to my son", "wave bye to grandma", "wave them goodbye", "wave so long", "wave farewell",
"say bye-bye with your hand", "say bye bye with your arm", "flap your hand", "waggle your hand",
"wiggle your hand hello", "do the waving thing", "do the hand wave", "hand hello", "give the camera a wave",
"say hi to the camera with your hand", "wave to the nice lady", "wave at my kid", "wave at the baby",
"wave at my little sister", "wave to my brother", "show the kids your wave", "do your little wave",
"wave us goodbye", "wave them hello", "give my mom a wave", "give the kids a wave", "a little wave for the kids",
"one big wave for us", "wave like you mean it", "wave really big", "wave slowly", "wave nicely",
"you make wave", "do wave hand please", "wave hand to me robot", "hand wave for me", "make hand shake with me",
"make handshake with me please", "you and me handshake", "handshake with me", "shake hand me please",
"please hand shake", "robot hand shake", "robot, wave wave", "wave wave robot", "robot robot wave",
"say bye bye robot, wave", "bye bye wave robot", "hello wave robot", "gimme a wave", "throw me a wave",
"toss us a wave", "give us a little wave", "wave at your fans", "wave to your fans",
"would you be so kind as to wave", "would you kindly shake my hand", "would you kindly wave to us",
"be so kind as to wave", "i would appreciate a wave", "a wave would be lovely", "please greet us with your hand",
"greet my mother with a wave", "greet the guests with a wave", "welcome them with a wave",
"wave to welcome them", "wave to say goodbye", "wave to say hello",
*_en(["wave to my kids", "give me a shake", "shake on it", "wave them goodbye", "wave so long"]),
# Korean, every level
*_ko(["손 살랑살랑 흔들어", "손 흔들흔들 해", "손 좌우로 흔들어", "손 들어서 흔들어", "손 번쩍 들어 흔들어",
"손으로 빠이빠이 해", "손으로 작별 인사 해", "손 흔들어서 배웅해", "손 흔들어 배웅해", "손 흔들어 환영해",
"손 흔들어서 반겨", "손 흔들어 반겨", "손 흔들며 인사해", "손 흔들어 안녕 해", "반갑게 손 흔들어",
"크게 손 흔들어", "손 크게 한번 흔들어", "손 천천히 흔들어", "나한테 손 흔들어", "저한테 손 흔들어",
"우리 애한테 손 흔들어", "손녀한테 손 흔들어", "손자한테 손 흔들어", "엄마한테 손 흔들어", "아빠한테 손 흔들어",
"카메라에 손 흔들어", "사진 찍을 때처럼 손 흔들어", "악수 한번 해", "나랑 악수 한번 해", "악수로 인사해",
"핸드셰이크 해", "쉐이크 핸즈 해", "웨이빙 해", "핸드 웨이브 해", "바이 바이 해", "굿바이 손 흔들어",
"하이 손 흔들어"], LEVELS),
"손 흔드시게", "손 흔드시오", "손 흔드십시오", "손 흔드세요", "손 흔드셔요", "손 좀 흔드시지요", "손 흔들어 주시지요",
"악수 한번 하시지요", "악수 한번 하시죠", "악수 청합니다", "악수 부탁드립니다", "악수 부탁해요", "악수 좀 부탁해",
"악수 한번 합시다", "악수 한번 하세", "악수 하세나", "악수나 하세", "악수하시게", "악수 하시오",
"할아버지께 손 흔들어 드려", "할머니께 손 흔들어 드리세요", "선생님께 손 흔들어 드려요", "어르신께 손 흔들어 드리십시오",
"손님들께 손 흔들어 드리세요", "어르신께 손으로 인사드려", "손님께 손으로 인사드리세요", "할머니랑 악수해 드려",
"할아버지랑 악수 한번 해 드려요", "선생님이랑 악수하세요", "회장님께 악수 청해 드리세요",
"악수 하입시더", "악수 하자이", "악수 하장께", "악수 하드라고", "악수 하자 마", "악수 해 보이소", "악수 하쇼",
"손 쪼까 흔들어 봐", "손 흔들어 주소마", "손 흔들어 보래이", "손 흔들어 봐라잉", "손 흔드쇼", "손 흔드소",
"핸즈 쉐이크", "쉐이크 핸즈", "쉐이크 핸즈 플리즈", "웨이브 플리즈", "핸드 웨이브", "핸드 웨이브 플리즈",
"웨이빙 플리즈", "바이바이 플리즈", "하이 해 줘 손으로", "손으로 하이 해", "shake hands 해 주세요",
"wave 좀 해 주세요", "손 wave 해 주세요", "handshake 좀 해요", "악수 please", "please 악수",
"손 흔드러 조", "손 흔들러 줘", "손흔들어", "손흔들어줘", "손흔들어주세요", "악수해조", "악쑤 해 줘", "악수 해쥬",
"악수하쟝", "악수 해 주라", "악수하자구", "악수하자고", "손 흔들어 쥬세요", "손 흔드러 주세여", "손 흔들어 주세여",
"자 악수", "자, 악수하자", "그럼 악수하자", "반가워, 악수", "반갑습니다 악수 한번 하시죠", "만나서 반가워요 악수해요",
"잘 가 손 흔들어", "안녕 손 흔들어 줘", "빠빠이 손 흔들어", "바이바이 손 흔들어 줘",
]
# ---------- arm_reach: hold the arm out ("give me your hand", "손 줘", "손 내밀어") ----------
ARM_REACH = [
"give us your hand", "put out your hand", "put out your arm", "reach your hand to me", "reach me your hand",
"extend your hand to me", "extend your arm out", "extend your arm toward me", "hold your arm straight out",
"arm straight forward", "hand forward please", "can i get your hand", "let's see that hand", "bring your hand out",
"your arm, stretch it out", "out with your hand", "your hand, give it here", "your hand, hold it out",
"stretch your arm toward me", "stretch your hand to me", "reach your arm toward me", "reach your arm forward",
"arm out to me please", "arm toward me", "hand toward me", "reach over to me", "reach over here",
"hold out a hand", "hold a hand out", "offer a hand", "give me your paw", "give paw", "paw please",
"robot gimme hand", "give hand robot", "you give hand me", "hand give me", "your hand give me please",
"please you reach hand", "reach hand please", "you reach out please", "make arm long", "make your arm long",
"long arm", "big reach", "reach far", "reach as far as you can", "stretch as far as you can",
"would you be so kind as to give me your hand", "would you kindly hold out your hand",
"may i have your hand, please", "i'd like to hold your hand", "let me hold your hand", "let me see your arm out",
*_en(["give me your paw", "put out your hand", "extend your hand to me", "reach your hand to me"]),
*_ko(["손 뻗쳐", "팔 뻗쳐", "손 앞으로 쭉", "팔 앞으로 쭉 뻗어", "팔 쭉 내밀어", "손 이리 내", "손 내 봐", "손 좀 내",
"손 내어", "팔 내어", "손 쭉 뻗어", "팔 쭉 빼", "팔 앞으로 빼", "손 앞으로 빼", "팔 길게 내밀어", "팔 멀리 뻗어",
"나한테 팔 내밀어", "저한테 팔 뻗어", "이쪽으로 팔 뻗어", "나 쪽으로 손 뻗어", "내 쪽으로 손 내밀어",
"제 쪽으로 팔 뻗어", "손 줘 봐", "핸드 아웃 해", "암 아웃 해", "리치 아웃 해", "팔 익스텐드 해",
"팔 스트레치 해", "리치 해"], LEVELS),
"손 내미시게", "팔 뻗으시게", "손 내미시오", "팔 뻗으시오", "손 내미십시오", "팔 뻗으십시오", "손 내미세요",
"팔 뻗으세요", "손 내밀어 주시지요", "손 좀 내어 주시겠어요?", "손 내주세요", "손 내줘", "손 내줄래?",
"손 좀 내 주시겠습니까?", "할머니께 손 내밀어 드려", "어르신께 팔 뻗어 드리세요", "선생님께 손 내밀어 드리세요",
"손님께 손 내밀어 드려요", "손 내밀어 보래이", "손 쫌 내 봐라", "팔 뻗어 보랑께", "손 내밀어 주쇼", "손 내미소",
"팔 뻗어 봐라잉", "손 내밀어 보소", "팔 쫌 뻗어 보이소", "손 쪼까 내밀어 봐", "핸드 아웃", "암 아웃", "리치 아웃",
"핸드 플리즈", "hand 좀 줘 봐", "손 out 해", "arm 좀 뻗어 줘", "팔 쭉 reach 해", "손내밀어", "손내밀어줘",
"팔뻗어", "팔뻗어줘", "손 내미러 줘", "팔 뻐더 봐", "손 내미러", "팔 뻗어 쥬", "손 내밀어 쥬세요", "손 쥬", "손 조",
"손 주쇼", "손 주시게", "손 주시오", "손 좀 주시지요", "손 이리 주시게", "손 이리 내 봐", "자 손", "자, 손 줘",
"루미 손", "루미야 손 좀", "손 한번 줘 봐", "손 한 번만 줘", "팔 한번 뻗어 봐", "팔 한 번만 뻗어 줘",
]
# ---------- arm_fold: the arm back to its look pose ----------
ARM_FOLD = [
"arm back to normal", "back to your normal pose", "reset arm position",
"go back to resting position", "rest position", "arm to rest", "arm to rest position",
"put your arm back where it was", "pull in your arm", "bring your arm in close", "fold it up", "fold up",
"fold back", "retract", "retract it", "retract your hand", "pack your arm away", "stow your arm", "stow the arm",
"park your arm", "arm in please", "arm away please", "that's enough, arm back", "ok thanks, you can retract",
"withdraw your arm", "withdraw your hand", "take your hand away", "put that arm away", "arm back, robot", "arm back to look", "back to look", "look pose please",
"arm to the look pose", "you arm back please", "put arm in", "put arm down", "arm back now",
"all done, arm back", "we're done, fold your arm", "done shaking, arm back", "okay you can retract your arm",
"bring it back in", "bring your hand back", "pull your hand in", "draw your hand back", "arm back to start",
"arm to start position", "starting position, arm", "neutral position", "arm neutral", "arm to neutral",
"fold your arm away", "fold the arm in", "tuck your arm back in", "tuck the arm away",
"would you kindly put your arm down", "would you be so kind as to fold your arm",
*_en(["retract your arm", "stow your arm", "pull in your arm", "put your arm back where it was",
"bring your hand back"]),
*_ko(["팔 원래 자세로 해", "팔 기본 자세로 돌려", "팔 원상복구 해", "팔 원상태로 해", "팔 정위치 해", "팔 제자리에 둬",
"팔 다시 원래대로 해", "팔 집어넣어", "손 집어넣어", "팔 거둬들여", "팔 당겨", "팔 안으로 넣어", "팔 몸쪽으로 붙여",
"팔 붙여", "팔 회수해", "팔 복귀해", "팔 원위치 복귀해", "팔 정리해", "팔 다시 접어 놔", "팔 거둬 들여",
"손 다시 가져가", "손 거둬들여", "팔 리셋 해", "팔 폴드 해", "팔 룩 포즈로 해",
"팔 리트랙트 해", "팔 안쪽으로 접어", "팔 몸에 붙여"], SHORT),
"손 거두세요", "손 거두시오", "팔 거두시게", "팔 접으시게", "팔 접으시오", "팔 거두어 주십시오", "팔 거두어 주세요",
"팔 접어 주시지요", "팔 내리시게", "팔 내리시오", "손 거두시게", "팔 원위치 하십시오", "팔 원위치 해 주시죠",
"팔 접어라 마", "팔 접어 보래이", "팔 쫌 접으소", "팔 접어 주쇼", "팔 거둬 부러", "팔 접어 주랑께", "팔 접으쇼",
"팔 거둬유", "팔 쪼까 접어 봐", "암 폴드", "팔 폴드", "팔 리셋", "arm reset 해", "arm reset 해 줘",
"팔 룩 포즈로", "룩 포즈로 팔 접어", "팔 리트랙트", "retract 해 줘", "팔 retract 해",
"팔접어", "팔접어줘", "팔 저버 줘", "팔 거더 줘", "팔 너어", "팔 너어 줘", "팔 접어 쥬", "팔 접어 주세여", "팔내려",
"팔 원위치요", "팔 원위치 좀", "됐어, 팔 접어", "다 됐어 팔 거둬", "악수 끝, 팔 접어", "수고했어 팔 접어",
"고마워요 이제 팔 접으세요", "감사합니다 이제 팔 거두셔도 됩니다", "이제 손 거둬도 돼", "이제 팔 넣어",
]
# ---------- arm_open / arm_close: the gripper ----------
ARM_OPEN = [
"open your gripper wide", "open the fingers", "fingers apart", "spread the gripper", "open the claw", "unclamp",
"unclamp your gripper", "release the gripper", "gripper open please", "open up your gripper", "open your pincers",
"open hand please robot", "hand open you", "you open finger", "open finger", "open fingers please",
"open your hand all the way", "open the hand wide", "spread your hand", "spread your hand out", "palm open",
"relax your grip", "open the grip",
*_en(["open your gripper wide", "unclamp your gripper", "spread your hand", "open your pincers"]),
*_ko(["손가락 벌려", "그리퍼 벌려", "집게 펴", "손 쫙 벌려", "손 열어 봐", "손 오픈 해", "그리퍼 오픈 해", "손 펼쳐",
"손바닥 펼쳐", "손가락 쫙 펴", "손 활짝 열어", "그리퍼 활짝 열어", "집게 활짝 벌려", "손가락 벌려 봐",
"손 쫙 펼쳐"], SHORT),
"손 펴시게", "손 펴시오", "손 펴 보래이", "손 펴 주쇼", "손 펴 봐유", "손펴", "손펴줘", "손 벌려 주십시오",
"그리퍼 여시게", "그리퍼 여십시오", "손 여세요", "손 펴 주시지요", "핸드 오픈", "핸드 오픈 해 줘", "그리퍼 오픈 플리즈",
"open 해 줘 그리퍼", "gripper 열어", "hand open 해 줘", "손 펴 쥬", "손가락 펴 조",
]
ARM_CLOSE = [
"close your pincers", "clamp your gripper", "close the claw", "fingers together", "pinch your fingers",
"pinch your fingers together", "shut the gripper", "close up your hand", "squeeze your hand", "make a fist please",
"fist please", "close fingers", "you close finger", "hand close you", "close the hand all the way",
"close the fingers", "curl your fingers", "ball your hand", "make a fist for me",
*_en(["close your pincers", "clamp your gripper", "fingers together"]),
*_ko(["손가락 모아", "그리퍼 오므려", "집게 쥐어", "손 닫아 봐", "손 클로즈 해", "그리퍼 클로즈 해", "손 꽉 오므려",
"손가락 오므려 봐", "그리퍼 꽉 닫아", "집게 꽉 닫아", "주먹 쥐어 봐"], SHORT),
"주먹 쥐시게", "주먹 쥐시오", "손 쥐어 보래이", "손 오므려 봐유", "손쥐어", "주먹쥐어", "그리퍼닫아", "그리퍼 닫으십시오",
"손 닫으세요", "주먹 쥐어 주시지요", "핸드 클로즈", "핸드 클로즈 해 줘", "그리퍼 클로즈 플리즈", "close 해 줘 그리퍼",
"gripper 닫아", "hand close 해 줘", "주먹 쥐어 쥬", "손 오므려 조",
]
# ---------- pick: an object; the side words keep it a pick (the bank's quick pick takes no side: rules / LLM) ----------
SIDE_EN = ["on your left", "on your right", "to your left", "to your right", "on the left", "on the right",
"on the left side", "on the right side", "next to you", "beside you", "at your side", "in front of you",
"right in front of you", "over on the right", "over on the left", "on your left side", "on your right side"]
SIDE_KO = ["왼쪽에 있는", "오른쪽에 있는", "왼쪽", "오른쪽", "왼편에 있는", "오른편", "옆에 있는", "네 왼쪽에 있는",
"너 오른쪽에 있는", "앞에 있는", "바로 앞에 있는", "좌측", "우측", "왼쪽 테이블 위", "오른쪽 테이블에 있는",
"왼쪽 옆에 있는", "오른쪽 옆에 있는", "니 왼쪽에 있는"]
PICK = [
*[f"pick up the <obj> {s}" for s in SIDE_EN], *[f"grab the <obj> {s}" for s in SIDE_EN[:8]],
*[f"take the <obj> {s}" for s in SIDE_EN[4:10]],
"the <obj> on your right, pick it up", "the <obj> on your left, grab it", "get the <obj> on the left side",
"grab the left <obj>", "pick the right <obj>", "take the left one", "grab the one on the right",
"pick up the one on your left", "pick up the one to your right", "turn and pick up the <obj> on your left",
"pluck the <obj>", "scoop up the <obj>", "take hold of <obj>", "get a grip on the <obj>", "grab hold of the <obj>",
"snatch up the <obj>", "lift up that <obj>", "pick up the <obj>, would you", "robot take <obj>", "get <obj>",
"<obj>, pick up", "you get <obj>", "you lift <obj> please", "pick <obj> please", "grab <obj> please",
"would you kindly pick up the <obj>", "would you be so kind as to pick up the <obj>",
*_en(["pick up the <obj> on your left", "grab the <obj> on your right", "pick up the <obj> next to you"]),
*_ko([f"{s} <obj> {v}" for s in SIDE_KO for v in ("집어", "잡아")], ["", " 줘", " 주세요", " 주십시오", " 봐"]),
*_ko(["<obj> 잡아 들어", "<obj> 집어 들어", "<obj> 꽉 잡아", "<obj> 집어 봐", "<obj> 집어 올려 봐",
"<obj> 픽업 해", "<obj> 들어 올려 봐", "<obj> 그랩 해", "<obj> 테이크 해", "<obj> 쥐어 봐", "그 <obj> 잡아",
"저기 있는 <obj> 집어", "탁자 위에 <obj> 집어", "책상 위에 <obj> 집어", "<obj> 하나만 집어"], LEVELS),
"<obj> 집으시게", "<obj> 잡으시오", "<obj> 집으시오", "<obj> 잡으시게", "<obj> 집어 주시지요", "<obj> 집어 보래이",
"<obj> 쫌 집어 봐라", "<obj> 집어 주쇼", "<obj> 집어 봐라잉", "<obj> 잡아 보소", "<obj> 그랩", "<obj> 픽 업",
"<obj> 테이크", "<obj>집어", "<obj>집어줘", "<obj> 지버 줘", "<obj> 자바", "<obj> 자바 줘", "<obj> 집어 쥬",
]
# ---------- fetch: bring an object to the person ----------
FETCH = [
"bring the <obj> over", "bring the <obj> over here", "fetch me that <obj>", "bring the <obj> back to me",
"could you bring me that <obj>", "carry the <obj> over to me", "deliver me the <obj>", "bring <obj> please",
"<obj>, bring it here", "the <obj>, bring it to me", "fetch <obj> please", "bring cup", "get me <obj>",
"bring me <obj> please", "you bring me <obj>", "please bring <obj> to me", "bring <obj> to me please",
"would you kindly bring me the <obj>", "would you be so kind as to fetch the <obj>",
"go fetch me the <obj>", "fetch the <obj> for me", "bring the <obj> to me, please", "bring that <obj> here",
*_en(["bring the <obj> over here", "fetch me that <obj>", "bring the <obj> back to me"]),
*_ko(["<obj> 갖고 와", "<obj> 챙겨 와", "<obj> 챙겨다", "<obj> 이리 가져와", "<obj> 여기로 갖고 와", "<obj> 좀 챙겨 와",
"<obj> 가지고 와", "나한테 <obj> 갖고 와", "저한테 <obj> 챙겨 와", "<obj> 갖다 와"], SHORT),
"<obj> 가지고 오시게", "<obj> 가져오시오", "<obj> 가져오십시오", "<obj> 가져오세요", "<obj> 가 온나", "<obj> 가져 온나",
"<obj> 갖다 주쇼", "<obj> 가져와 부러", "<obj> 갖고 와유", "<obj> 가져와유", "<obj> 브링 해 줘", "<obj> 가져와줘",
"<obj>가져와", "<obj> 가져와 주시지요", "<obj> 좀 갖다 주시게", "<obj> 가저와 줘", "<obj> 갖고 와 쥬",
]
# ---------- the hand's (not acted on by the bank; kept apart from the motions): put, give, receive ----------
PUT = [
"put it down to your right", "put it down to your left", "put it down on your left", "put it down on your right",
"set it on the left side", "set it on the right side", "place it to the right", "place it to the left",
"put the <obj> down on the right side", "put the <obj> down on the left side", "put it on the table to your left",
"put it on the table to your right", "drop it off on the right", "set the <obj> down", "lay it down",
"lay it on the table", "rest it on the table", "leave it here", "leave it on the table", "put it there",
"put it back where you found it", "put it down beside you", "put it next to you", "put it down gently",
"set it down slowly", "place the <obj> on <place>", "put the <obj> at <place>", "drop the <obj> off at <place>",
"put it on the left table", "put it on the right table", "put it down on the table on your right",
"release it on the table", "put down the <obj>", "put the <obj> back", "set down the <obj> please",
"you put down please", "put down please", "you put it table", "cup down please", "put cup on table",
*_ko(["왼쪽에 내려놔", "오른쪽에 내려놔", "오른쪽 테이블에 내려놔", "왼쪽 테이블에 놔", "왼편에 놔", "옆에 내려놔",
"네 오른쪽에 내려놔", "좌측에 내려놔", "우측에 놔", "여기 놔", "거기 놔", "저기 내려놔", "<place>에 내려놔",
"<place>에 놔", "<place> 테이블에 갖다 놔", "<obj> 내려놔", "<obj> 테이블에 놔", "제자리에 갖다 놔",
"원래 자리에 둬", "살짝 내려놔", "천천히 내려놔", "테이블 위에 살며시 놔", "오른쪽 옆에 놔", "왼쪽 옆에 둬"],
["", " 줘", " 주세요", " 주십시오", " 주시게"]),
"내려놓으십시오", "내려놓으시게", "내려놓으시오", "내려놔 주쇼", "내려놔 보래이", "내려놔 부러", "내려놔유", "내려놓으소",
"풋 다운 해", "put down 해 줘", "테이블에 put 해", "내려놔 쥬", "내려나 조", "그거 놓으세요", "놓으십시오",
]
GIVE = [
"hand it here", "pass it over", "pass it here", "give it back", "give it over", "over here, give it",
"i'll take it", "i'll take it from you", "let me take it", "let me take that", "hand it on over", "pass that to me",
"give that to me now", "give it to me please", "give me the thing", "give it, please", "hand it",
"you give me please", "give me now", "now give me",
"그거 나 줘", "이리 내", "이리 내놔", "내놔", "그거 내놔", "그거 이리 넘겨", "건네 줘", "넘겨 줘", "저한테 넘겨 주세요",
"저 주십시오", "나한테 줘", "제게 주시겠어요?", "그거 받을게", "제가 받겠습니다", "주라", "줘 봐라", "그거 주소",
"이리 주이소", "그거 주쇼", "이리 도", "그거 나 도", "줘유", "기브 미", "give 해 줘", "그거 이리 주시게",
"저에게 건네 주십시오", "할머니 드려", "할머니께 드리세요", "선생님께 드려", "이리 주시지요",
]
RECEIVE = [
"here, take this", "hold this for me", "take this <obj> from me", "here's the <obj>", "this is for you, take it",
"can you take this", "would you hold this", "grab this", "hold onto this", "keep this", "take my <obj>",
"i'm giving you this", "please hold my <obj>", "here, hold it",
"이거 받아 주세요", "이거 들어 줘", "이거 좀 들고 있어 줘", "이거 잡아", "이거 잡아 줘", "이거 받으세요", "이거 받으십시오",
"이거 받으시게", "이거 받아라", "이거 받아 주이소", "받아유", "이것 좀 쥐고 있어",
"이 <obj> 좀 들고 있어", "이거 너 가져", "이거 너 줄게", "이거 테이크 해", "이거 홀드 해 줘", "자, 받아", "옜다 받아",
]
# ---------- no: about the arm and hand, past, other people, gestures Lumi has none of ----------
NO = [
"did you just wave", "you waved at me earlier", "why did you wave", "why are you waving", "can your arm reach the shelf",
"how far can your arm reach", "your arm reached the cup", "you reached out nicely", "no need to wave",
"you don't have to shake my hand", "my grandma likes it when robots wave", "the robot in the video waved",
"i'd rather not shake hands", "i don't shake hands", "no handshake please", "is your hand open",
"is your gripper closed", "why is your hand open", "your fingers are open", "your hand is closed",
"you dropped the cup", "you picked it up yesterday", "you picked the wrong cup", "that cup is heavy",
"what can you pick up", "who taught you to wave", "where did you learn to shake hands",
"the cup on your left is mine", "the cup on the right is empty", "there's a cup on your left",
"is there a cup on your right", "my cup is on the left", "i put the cup down", "i picked up the cup",
"she took the cup", "he gave me the cup", "someone left a cup on the table", "pick up the pace",
"pick up where we left off", "put up with it", "put your hands together for lumi", "give it up for lumi",
"give a hand to our guests", "let's give him a big hand", "hands up", "hands off", "keep your hands to yourself",
"hold your horses", "fold the paper", "fold the towel", "reach your goals", "shake it off", "shake the bottle",
"shake your head", "shake a leg", "wave the flag", "clap your hands", "give me a thumbs up", "do a peace sign",
"make a heart with your hands", "arm wrestle me", "do push ups", "high five me", "fist bump me", "pinky promise",
"the gripper looks strong", "your gripper is cool", "nice reach", "good grab", "nice pick", "you put it down well",
"손 흔들었어?", "아까 손 흔들었잖아", "왜 손 흔들어?", "손 흔드는 거 봤어요", "악수는 됐어", "악수 안 할래", "악수 안 해도 돼",
"팔 뻗는 거 무섭다", "팔이 어디까지 닿아?", "팔 얼마나 뻗을 수 있어?", "팔 길이가 몇이야?", "손 열려 있어?",
"그리퍼 닫혀 있네", "손가락이 몇 개야?", "컵 떨어뜨렸어", "아까 컵 집었잖아", "컵 잘 집네", "왼쪽에 컵 있어",
"오른쪽에 있는 컵 내 거야", "왼쪽 컵 비었어", "오른쪽에 컵 있나?", "컵 누가 놨어?", "컵 내가 내려놨어", "엄마가 컵 가져왔어",
"박수 쳐 줘", "손뼉 쳐 줘", "박수 쳐", "엄지 척 해 줘", "손가락 하트 해 줘", "손하트 해 줘", "브이 해 줘", "팔씨름 하자",
"팔 굽혀 펴기 해 봐", "컵 씻어 줘", "손 흔드는 거 처음 봐", "악수하는 로봇이네", "팔이 참 기네요", "손이 크시네요",
"아까 악수했잖아", "악수 벌써 했어", "팔 접는 소리 났어", "손 내미는 거 귀엽다", "할머니가 손 흔드셨어",
"손 흔들어 주시던데요", "악수는 나중에 하자", "악수는 다음에 해요", "손 흔드는 건 언제 배웠어?", "컵 집는 거 어려워?",
"컵 몇 개나 들어?", "그 컵 무거워?", "왼쪽에 있는 컵 뭐야?", "오른쪽 컵 무슨 색이야?", "왼손잡이야?", "오른손잡이야?",
]
# ---------- more frames and endings: "what I need is for you to …", "-주게나", "-주세유", "-주시길 바랍니다" ----------
FRAMES2 = ["what i need is for you to {}", "the plan is, you {}", "i said {}", "all i ask is that you {}", "time to {}",
"go on and {}", "{} if you would", "{}, would you", "{}, yeah", "your job now is to {}", "next, {}",
"{} right now", "{} quickly", "{} slowly", "{} for us", "{} one time", "you gotta {}", "you should {} now",
"hello lumi, {}", "excuse me robot, {}", "mister robot, {}", "lumi, buddy, {}", "{}, my friend"]
KO_END2 = [" 주게나", " 주세유", " 주시길 바랍니다", " 주셨으면 합니다", " 주시면 고맙겠습니다", " 주면 안 될까요?",
" 주실 수 있을까요?", " 줄 수 있겠니?", " 주겠니?", " 주겠나?", " 주시겠나?", " 주셔", " 줘 봐 응", " 주실래예",
" 주이소 마", " 줘 볼래?", " 주라 응", " 줘 얼른", " 줘 빨리요", " 주실 수 있나요?"]
def _en2(cores):
return [f.format(c) for c in cores for f in FRAMES2]
WAVE += _en2(["wave", "wave hello", "shake my hand", "do a little wave", "give us a wave", "shake hands with me"]) + \
_ko(["손 흔들어", "팔 흔들어", "악수해", "손 인사 해", "손 흔들어서 인사해", "바이바이 해"], KO_END2) + [
"you and me shake hand", "me and you, handshake", "let us shake hands", "a handshake for me please",
"i'd love a wave from you", "how about you wave hello", "show everyone your wave", "wave hi, lumi",
"say hi to my mom with a wave", "it's goodbye time, wave", "wave goodbye to me", "wave to me once",
"손 흔드세유", "손 흔들어 주시길 바랍니다", "wave 해 주시길 바랍니다", "웨이브 해 주시길 바랍니다", "악수 부탁드려요",
"악수해 주시면 고맙겠습니다", "인사 손으로 해 주게나", "우리 악수나 하자", "그럼 악수 한번 할까", "악수 한번 할래?"]
ARM_REACH += _en2(["give me your hand", "hold out your hand", "reach out your arm", "stretch out your arm",
"put your hand out"]) + _ko(["손 줘", "손 내밀어", "팔 뻗어", "손 앞으로 내밀어", "팔 앞으로 뻗어"], KO_END2) + [
"your hand, give me", "hand, give me", "your hand to me", "your arm to me, please", "me your hand please",
"give your hand to me now", "i'd like your hand", "hand over here", "arm over here please", "손 한번 주시게",
"손 한번 주게나", "손 좀 주세유", "손 줘 봐유", "팔 쭉 뻗어 주세유"]
ARM_FOLD += _en2(["fold your arm", "put your arm back", "pull your arm back in", "tuck your arm away", "lower your arm",
"bring your arm home"]) + _ko(["팔 접어", "팔 거둬", "손 내려", "팔 안으로 거둬", "팔 원위치 해"], KO_END2) + [
"bring your hadn home", "put arm back where it was", "you can put arm back where it was", "arm back where it was",
"put your arm where it was", "arm back to where it was", "fold you're arm", "fold your arms", "put your arms down",
"arms back", "arms in", "팔 안으로 거둬 줘", "팔을 안으로 거둬", "손 이제 내려 줘", "팔 이제 거둬 주게나", "암 백", "암 백 해 줘",
"arm back 해 줘", "팔 백 해 줘"]
ARM_OPEN += _en2(["open your hand", "release your grip", "open your fingers", "open the gripper"]) + \
_ko(["손가락 펴", "손 펴", "그리퍼 열어", "손 벌려"], KO_END2) + [
"let go of your grip", "loosen your fingers", "fingers open please", "open hand now", "손가락 펴 주게",
"손가락펴줘", "손가락 쫙 펴 주세유"]
ARM_CLOSE += _en2(["close your hand", "grip with your fingers", "make a fist", "close the gripper"]) + \
_ko(["주먹 쥐어", "손 쥐어", "그리퍼 닫아", "손가락 오므려"], KO_END2) + [
"grip with your fingers", "grip your fingers", "grip tight", "close your grip", "tighten your fingers",
"주먹 꽉 쥐어 주시겠습니까", "손 꽉 쥐어 주세유", "주먹쥐어줘"]
PICK += _en2(["pick up the <obj>", "grab the <obj>", "take the <obj>"]) + \
_ko(["<obj> 집어", "<obj> 잡아", "<obj> 들어"], KO_END2) + [
"peek up the <obj>", "<obj> 잡아 주게나", "<obj> 집어 주세유", "<obj> 들어 올려 주시길 바랍니다", "the <obj>, grab it",
"<obj>, take it", "that <obj> there, pick it up", "pick that <obj> up for me", "grab me that <obj>"]
FETCH += _en2(["bring me the <obj>", "fetch the <obj>"]) + _ko(["<obj> 가져와", "<obj> 갖다"], KO_END2)
NO += [
"she asked you to wave hi to me yesterday", "my grandson told you to shake hands", "you waved to her before",
"will you wave at the party tomorrow", "never grab that apple without asking", "don't ever pick up my phone",
"can robots wave", "do robots shake hands", "the robot shook my hand", "you shook my hand earlier",
"your hand is so cold when we shake", "i'm waving at you", "i'm shaking your hand now", "i'll wave back",
"look, i'm reaching out", "my arm is tired", "my hand is full", "my fingers are cold", "open your mind",
"close your eyes", "open your mouth", "close the curtains", "reach for the stars", "hold my beer",
"grab a seat", "take a seat", "get a grip", "get a grip on yourself", "pick a side", "take my word for it",
"give me your word", "give me your opinion", "give me your number", "lend me your ears", "fold your hands and pray",
"shake things up", "wave of the future", "hand me down clothes", "put your feet up", "put it on my account",
"아까 손자가 악수하라고 했어", "손 흔들라고 누가 그랬어?", "어제 손 흔들어 줬잖아", "내일 행사 때 손 흔들 거야?",
"손 흔드는 로봇 처음 봐요", "로봇이랑 악수했어요", "손 시려워", "손가락이 아파요", "팔이 아파서 못 들겠어",
"눈 감아", "입 벌려", "커튼 닫아", "마음 열어", "자리에 앉아", "정신 차려", "손 들어 질문 있어요", "손 씻으러 가자",
"의자 들어 줄래?", "가방 들어 줘", "백팩 집어 줘", "의자 잡아 줘", "책상 옮겨 줘", "pick up my backpack",
"grab that chair for me", "lift the table", "carry my bag", "hold the door",
]
# ---------- put and pick from any side, give while holding, receive ----------
SIDES_KO = ["왼쪽", "오른쪽", "왼편", "오른편", "좌측", "우측", "왼쪽 옆", "오른쪽 옆", "니 왼쪽", "네 오른쪽", "옆", "앞",
"바로 옆", "왼쪽 테이블", "오른쪽 테이블", "왼쪽 탁자", "오른쪽 책상"]
SIDES_EN = ["to your left", "to your right", "on your left", "on your right", "on the left side", "on the right side",
"to the left", "to the right", "beside you", "next to you", "at your left", "at your right",
"on the table to your left", "on the table to your right", "on the left table", "on the right table",
"over on your left", "over to the right", "by your side", "on your left-hand side", "on your right-hand side"]
PUT_END = ["", " 줘", " 주세요", " 주십시오", " 주시게", " 주세유", " 주이소", " 줘유", " 주게나", " 주시길 바랍니다", " 주쇼", " 봐"]
PUT += [f"put it down {s}" for s in SIDES_EN] + [f"set it down {s}" for s in SIDES_EN[:10]] + \
[f"place the <obj> {s}" for s in SIDES_EN[:8]] + [f"put the <obj> {s}" for s in SIDES_EN[8:16]] + \
[f"leave it {s}" for s in SIDES_EN[:6]] + [f"drop it {s}" for s in SIDES_EN[:4]] + \
_ko([f"{s}에 내려놔" for s in SIDES_KO] + [f"{s}에 놔" for s in SIDES_KO[:10]] + [f"{s}에 둬" for s in SIDES_KO[:6]] +
[f"그거 {s}에 내려놔" for s in SIDES_KO[:6]] + [f"<obj> {s}에 놔" for s in SIDES_KO[:6]] +
[f"{s}에 내려놓아" for s in SIDES_KO[:4]], PUT_END) + [
"왼쪽에다 내려놔", "오른쪽에다 놔 줘", "왼쪽에다가 놔", "오른쪽에다가 내려놓으세요", "레프트에 놔", "라이트 쪽에 내려놔",
"왼쪽 사이드에 놔", "오른쪽 사이드에 내려놔 줘", "put it 왼쪽에", "오른쪽에 put down 해", "왼쪽에 내려나", "오른쪽에 내려 나 줘",
"put it down at your left side", "on the right, put it down", "left side, put it down", "put down left side please",
"you put left side", "put cup right side", "the right side, set it there", "over there on the left, put it down",
]
PICK += [f"pick up the <obj> {s}" for s in SIDES_EN[8:]] + [f"take the <obj> {s}" for s in SIDES_EN[:4]] + \
[f"grab the <obj> sitting {s}" for s in SIDES_EN[:4]] + \
_ko([f"{s}에 있는 <obj> {v}" for s in SIDES_KO for v in ("집어", "잡아", "들어")], ["", " 줘", " 주세요", " 주십시오", " 주게나", " 주세유"]) + [
"왼쪽 거 집어", "오른쪽 거 잡아 줘", "왼쪽 것 좀 집어 주세요", "오른쪽에 있는 거 집어", "레프트 컵 집어", "라이트 쪽 <obj> 잡아",
"the <obj> at your left, take it", "the left <obj>, grab it", "the one on your right, pick it up",
]
GIVE += _ko(["그거 줘", "이리 줘", "나 줘", "저 줘", "그거 이리 건네", "그거 넘겨", "그 <obj> 줘", "들고 있는 거 줘",
"손에 든 거 줘", "그거 나한테 줘"], ["", " 봐", "요", " 주세유", " 주게나", " 주시길 바랍니다"]) + [
"give me what you're holding", "give me the thing you're holding", "hand me what you have", "pass me what you got",
"what you have, give me", "the <obj>, give it to me", "give it me", "give me", "gimme", "gimme it", "hand over",
"그거 주시게", "그거 주게나", "주세유", "그거 주셔", "줘 봐 응", "그거 건네주세요", "손에 든 거 이리 줘요", "그거 저 줘요",
]
RECEIVE += [
"here, this is yours", "take this from me please", "this one you hold", "now you here, take this",
"hold onto this for me", "take it, it's for you", "here, grab this from me", "i'm handing it to you", "keep it for me",
"이거 받아 주게나", "이거 받아 주세유", "이거 가지고 있어", "이거 들고 계세요", "이거 쥐고 있어 줘", "이것 좀 맡아 줘",
"이거 맡아 주세요", "자 이거", "옛다", "받으세유", "받아 주시길 바랍니다",
]
NO += [
"왼쪽에 놔둔 컵 누구 거야?", "오른쪽에 둔 거 뭐야?", "왼쪽에 내려놨어?", "오른쪽에 놓을까?", "왼쪽에 놓으면 돼?",
"어디에 내려놓을까?", "왼쪽이 좋아 오른쪽이 좋아?", "왼쪽 컵 예쁘다", "오른쪽에 있는 컵 누구 거예요?",
"did you put it on the left?", "should i put it on the right?", "the cup on the left is broken",
"put it on the left or the right?", "which side should i put it on", "the left one is mine", "i put it on your left",
"my cup is on your right", "is the cup on the left full?", "you put it down on the left yesterday",
"왼쪽에 컵 있어?", "오른쪽에 뭐 있어?", "옆에 컵 있네", "앞에 컵 있다",
]
INTENT = {"wave": WAVE, "arm_reach": ARM_REACH, "arm_fold": ARM_FOLD, "arm_open": ARM_OPEN, "arm_close": ARM_CLOSE,
"pick": PICK, "fetch": FETCH, "put": PUT, "give": GIVE, "receive": RECEIVE, "no": NO}
+24
View File
@@ -292,3 +292,27 @@ for _en, _ko_, _a in ROBOTS.values(): # where it stands, or asked to work: t
"i want to see the {r}", "show me the {r}"] for r in _en] "i want to see the {r}", "show me the {r}"] for r in _en]
QUICK["no"] += [f.format(r=r) for f in ["{r} 어디 있어", "{r} 어디 있어요", "{r} 어디예요", "{r}한테 데려가 줘", "{r} 보여 줘", "{r} 여기 있어요"] QUICK["no"] += [f.format(r=r) for f in ["{r} 어디 있어", "{r} 어디 있어요", "{r} 어디예요", "{r}한테 데려가 줘", "{r} 보여 줘", "{r} 여기 있어요"]
for r in _ko_] for r in _ko_]
# night 5: Konglish / 하게체 / non-native ways of asking the founding year and the office ("컴퍼니 오픈 언제예요?",
# "company made which year?", "회사 사무실 어딘가?"); in quick_answers.KINDS by the loop above's kinds
QUICK["co_founded"] = [
"company made which year", "company founded which year", "company start when", "your company open when", "company since when",
"which year company start", "when company made", "cutshion made which year", "cutshion start what year", "company birthday when",
"company how many years", "company how old"] + _ko(
["컴퍼니 오픈 언제", "회사 오픈 언제", "쿳션 오픈 언제", "회사 설립 언제", "쿳션 설립 언제", "회사 창립 언제", "회사 창업 언제",
"회사 생긴 게 언제", "회사 세운 게 언제", "쿳션 생긴 게 언제", "컴퍼니 설립 언제", "회사 몇 년도 설립"],
["예요", "야", "니", "입니까", "인가요", "인가", "고", "여", "임", "이에요", "일까요"]) + _ko(
["회사 몇 년 됐", "회사 생긴 지 몇 년 됐", "쿳션 생긴 지 얼마나 됐", "회사 차린 지 얼마나 됐"],
["어", "어요", "니", "습니까", "나요", "노", "어유", "는가"])
QUICK["co_hq"] = _ko(
["회사 사무실 어디", "회사 사무실 어딘", "쿳션 사무실 어디", "회사 위치 어디", "회사 주소 어디", "본사 어디",
"회사는 어디", "쿳션 본사 어디", "컴퍼니 어디", "회사 오피스 어디"],
["야", "예요", "에요", "니", "입니까", "인가요", "인가", "고", "여", "임"]) + _ko(
["회사 어디 있", "쿳션 어디 있", "회사 사무실 어디 있"], ["어", "어요", "니", "나요", "습니까", "노", "는가", "으세요"]) + [
"where is company", "company where", "company office where", "where your company", "company location please",
"office where", "where is the office of cutshion", "where's your company's office", "company address"]
QUICK["no"] += [
"오픈AI 대표 누구야", "오픈AI 대표 누군가", "오픈AI 대표 누구임", "오픈AI 대표 어떤 분이세요", "구글 대표 누구예요", "애플 CEO 누구야",
"엔비디아 대표 누구야", "테슬라 대표 누구예요", "삼성 회장 누구야", "who's the boss of openai", "who runs google",
"1달러에 원화로 얼마야", "1달러 원화로 얼만가", "환율 얼마예요", "달러 환율 알려 줘", "엔화 얼마야", "how much is a dollar in won",
"what's the exchange rate", "배터리 얼만가", "배터리 얼마예요", "배터리 얼마야", "배터리 얼마 남았는가"]
+63 -6
View File
@@ -161,10 +161,10 @@ QUICK_KINDS = {
"자율주행 어떻게 해요", "자율주행 돼요", "자율주행 하니", "혼자 다닐 수 있어요", "길은 어떻게 찾아요", "길 어떻게 찾아", "위치는 어떻게 알아요", "자율주행 어떻게 해요", "자율주행 돼요", "자율주행 하니", "혼자 다닐 수 있어요", "길은 어떻게 찾아요", "길 어떻게 찾아", "위치는 어떻게 알아요",
"어디 있는지 어떻게 알아", "지도 있어요", "지도 써요", "지도를 어떻게 만들어요", "GPS 써요", "내비게이션 어떻게 해요", "자율 주행입니까", "어디 있는지 어떻게 알아", "지도 있어요", "지도 써요", "지도를 어떻게 만들어요", "GPS 써요", "내비게이션 어떻게 해요", "자율 주행입니까",
"길 우째 찾노", "길 어떻게 찾아유", "혼자 길 찾아가세요", "navigation 어떻게 해요", "자율주행 how", "map 있어요", "SLAM 써요", "길 우째 찾노", "길 어떻게 찾아유", "혼자 길 찾아가세요", "navigation 어떻게 해요", "자율주행 how", "map 있어요", "SLAM 써요",
], {"en": ["I drive with a map of the room made with my lidar. I compare what the lidar sees with the map to know where I am, to within about 5 cm, and plan a path around people and obstacles.", ], {"en": ["I drive with a map of the room made with my lidar. I compare what the lidar sees with the map to know where I am, to within about 5 cm, and plan a path around people and obstacles. A separate small computer in my base runs the navigation.",
"With a lidar map: I know where I am on it to about 5 cm, and I drive to named places on my own, around people and obstacles."], "With a lidar map: I know where I am on it to about 5 cm, and I drive to named places on my own, around people and obstacles. A separate small computer in my base runs the navigation."],
"ko": ["라이다로 만든 지도에서 제 위치를 약 5cm 정확도로 알고, 지도 위의 장소까지 사람과 장애물을 피해 경로를 짜서 가요.", "ko": ["라이다로 만든 지도에서 제 위치를 약 5cm 정확도로 알고, 지도 위의 장소까지 사람과 장애물을 피해 경로를 짜서 가요. 내비게이션은 베이스 안의 별도 컴퓨터가 돌려요.",
"라이다 지도로 다녀요. 지도에서 제 위치를 5cm 정도로 알고, 이름 붙은 장소까지 혼자 장애물을 피해서 가요."]}), "라이다 지도로 다녀요. 지도에서 제 위치를 5cm 정도로 알고, 이름 붙은 장소까지 혼자 장애물을 피해서 가요. 내비게이션은 베이스 안의 별도 작은 컴퓨터가 맡아요."]}),
"obstacles": ([ "obstacles": ([
"how do you avoid obstacles", "how do you avoid people", "do you avoid obstacles", "will you bump into people", "how do you avoid obstacles", "how do you avoid people", "do you avoid obstacles", "will you bump into people",
"do you crash into things", "what if someone is in your way", "what happens if someone stands in front of you", "do you crash into things", "what if someone is in your way", "what happens if someone stands in front of you",
@@ -227,9 +227,9 @@ QUICK_KINDS = {
"ko": ["제 팔을 손으로 움직여서 가르치거나, 프로그램을 짜거나, VR 헤드셋으로 원격 조종해서 새 일을 가르칠 수 있어요. 시범을 보고 기술을 배울 수도 있어요."]}), "ko": ["제 팔을 손으로 움직여서 가르치거나, 프로그램을 짜거나, VR 헤드셋으로 원격 조종해서 새 일을 가르칠 수 있어요. 시범을 보고 기술을 배울 수도 있어요."]}),
"touch": ([ "touch": ([
"is it ok to touch you", "is it safe to touch you", "can people touch you", "may we touch you", "can kids touch you", "is it ok to touch you", "is it safe to touch you", "can people touch you", "may we touch you", "can kids touch you",
"can you be pushed", "is it okay to push you", "are you dangerous", "is it safe near you", "are you safe for kids", "can you be pushed", "is it okay to push you",
"만져도 돼", "만져도 돼요", "만져도 되니", "만져도 됩니까", "만져도 되나요", "만져 봐도 되세요", "만져도 괜찮아요", "만지면 안 돼요", "만져도 돼", "만져도 돼요", "만져도 되니", "만져도 됩니까", "만져도 되나요", "만져 봐도 되세요", "만져도 괜찮아요", "만지면 안 돼요",
"밀어도 돼요", "밀어도 되나", "애들이 만져도 돼요", "아이들 옆에 있어도 안전해요", "만져도 되나", "만지도 되나", "밀어도 돼요", "밀어도 되나", "애들이 만져도 돼요", "만져도 되나", "만지도 되나",
"만져도 되노", "만져도 돼유", "touch 해도 돼요", "만져도 OK예요", "만져도 되노", "만져도 돼유", "touch 해도 돼요", "만져도 OK예요",
], {"en": ["You may touch me, but please keep your hands away from my gripper fingers when they close, and please don't push me: I'm heavy.", ], {"en": ["You may touch me, but please keep your hands away from my gripper fingers when they close, and please don't push me: I'm heavy.",
"Yes, gently. Keep your hands away from my gripper fingers when they close, and don't push my base while I'm switched on."], "Yes, gently. Keep your hands away from my gripper fingers when they close, and don't push my base while I'm switched on."],
@@ -453,3 +453,60 @@ QUICK["no"] += [
"drive 3 meters ahead", "종이컵 집어 줘", "종이컵 잡아 줘", "pick up the paper cup", "grab my paper cup", "종이컵 가져와", "drive 3 meters ahead", "종이컵 집어 줘", "종이컵 잡아 줘", "pick up the paper cup", "grab my paper cup", "종이컵 가져와",
"팔 들어", "팔 내려", "raise your arm", "대통령 연세가 어떻게 됩니까", "대통령 몇 살이에요", "엄마 연세가 어떻게 되세요", "how old is the president", "팔 들어", "팔 내려", "raise your arm", "대통령 연세가 어떻게 됩니까", "대통령 몇 살이에요", "엄마 연세가 어떻게 되세요", "how old is the president",
"오픈AI는 누가 이끌고 있습니까", "오픈AI CEO가 누구야", "who runs openai", "who leads openai"] "오픈AI는 누가 이끌고 있습니까", "오픈AI CEO가 누구야", "who runs openai", "who leads openai"]
# night 5: is it safe near Lumi (the touch kind answers touching only)
QUICK_KINDS["safety"] = ([
"is it safe to stand next to you", "is it safe near you", "are you safe for kids", "are you dangerous", "are you safe",
"is this robot safe", "is it safe to be around you", "can you hurt someone", "could you hurt me", "will you hit me",
"can kids stand near you", "is it safe for children to be near you", "how do you keep people safe", "what about safety",
"are you safe around people", "is lumi safe", "is it dangerous to stand here", "do you have safety features",
"what safety features do you have", "you won't run me over will you", "safe to be near?"] + [
s + e for s in ["아이들 옆에 있어도 안전", "옆에 있어도 안전", "가까이 가도 안전", "너 옆에 서 있어도 안전", "로봇 옆에 있어도 안전",
"애들 옆에 둬도 안전", "사람 옆에서 안전", "너 안전", "이 로봇 안전"]
for e in ["해", "해요", "하니", "합니까", "한가요", "하세요", "하나", "하노", "해유", "하지"]] + [
s + e for s in ["너 위험", "이 로봇 위험", "옆에 있으면 위험", "가까이 가면 위험", "아이들한테 위험"]
for e in ["해", "해요", "하니", "합니까", "한가요", "하지 않아", "하지 않아요", "하나", "하노"]] + [
"사람 다치게 할 수 있어", "사람 칠 수도 있어요", "부딪히면 어떡해요", "아이들이 가까이 가도 돼요", "옆에 서 있어도 돼요",
"안전장치 있어요", "안전 기능 뭐 있어요", "안전은 어떻게 지켜요", "안전하게 만들어졌어요", "다칠 위험 없어요", "safety 괜찮아요",
"너 안전한 로봇이야", "안전한 로봇입니까", "안전하긴 하나", "옆에 있어도 괜찮아요",
], {"en": ["Yes. I drive slowly and stop for people in my way, and my arm is a collaborative arm: it detects collisions and stops. "
"There are red emergency stop buttons on my body and in my base. Please keep your hands away from my gripper fingers.",
"I'm made to work near people: I stop for people in my way, my arm stops when it bumps into something, and pressing "
"one of my red emergency stop buttons stops my arm and lift at once. Just don't push me, I'm heavy."],
"ko": ["네, 안전해요. 천천히 움직이고 앞에 사람이 있으면 멈춰요. 팔은 협동 로봇 팔이라 충돌을 느끼면 멈추고, 몸과 베이스에 "
"빨간 비상 정지 버튼도 있어요. 그리퍼 손가락에는 손을 가까이 대지 마세요.",
"사람 곁에서 일하도록 만들어졌어요. 길에 사람이 있으면 멈추고, 팔은 부딪히면 멈춰요. 빨간 비상 정지 버튼을 누르면 "
"팔과 리프트가 바로 멈춰요. 저는 무거우니까 밀지는 말아 주세요."]})
# night 5: the cameras and face recognition as facts (quick_answers.SPEC lets these past the camera guard)
_CAM_KO = ["카메라 몇 개", "카메라가 몇 개", "카메라 몇 대", "카메라는 몇 개", "카메라 뭐 쓰", "카메라 어떤 거 쓰", "카메라 기종이 뭐", "카메라 모델이 뭐",
"카메라 종류가 뭐", "카메라 사양이 어떻게 되", "카메라 스펙이 뭐", "카메라 무슨 제품"]
QUICK_KINDS["cameras"] = ([
"what cameras do you have", "what camera do you use", "how many cameras do you have", "which cameras do you use",
"what kind of camera do you have", "what type of cameras are in you", "what camera model do you use", "what's your camera model",
"what depth camera do you use", "do you use orbbec cameras", "what camera brand do you use", "how many cameras does lumi have",
"what camera is in your head", "what cameras does this robot use", "camera model?", "how many camera you have",
"카메라 몇 개야", "카메라 몇 개예요", "카메라 몇 개니", "카메라 몇 개입니까", "카메라 몇 개 달려 있어", "카메라 몇 대 있어요", "카메라 뭐 써",
"카메라 뭐 써요", "카메라 뭐 쓰세요", "카메라 뭐 쓰십니까", "카메라 뭐 쓰노", "카메라 어떤 거 써요", "카메라 기종이 뭐예요", "카메라 모델이 뭐야",
"카메라 종류가 뭐예요", "카메라 사양이 어떻게 돼요", "카메라 스펙이 뭐야", "카메라 무슨 제품이에요", "너 카메라 몇 개야", "루미 카메라 몇 개예요",
"카메라는 몇 개 달렸노", "카메라 몇 개 있어유", "camera 몇 개야", "camera 뭐 써요", "카메라 model 뭐야",
], {"en": ["I have three cameras that see colour and depth: an Orbbec Gemini 2 L in my head, another on my body, and a 3D camera "
"at the front of my base. They see from very close up to about 10 metres.",
"Three: two Orbbec Gemini 2 L depth cameras, one in my head and one on my body, and a 3D camera at the front of my base."],
"ko": ["카메라는 세 대예요. 머리와 몸에 오비벡(Orbbec) Gemini 2 L 깊이 카메라가 하나씩 있고, 베이스 앞에 3D 카메라가 하나 있어요. "
"아주 가까이에서 약 10m까지 봐요.",
"모두 세 대예요. 오비벡 Gemini 2 L 깊이 카메라 두 대(머리, 몸)와 베이스 앞의 3D 카메라 하나예요."]})
QUICK_KINDS["faces"] = ([
"can you recognize faces", "can you recognise faces", "do you recognize faces", "do you have face recognition",
"do you use face recognition", "can you remember faces", "do you remember who people are", "can you recognize people",
"is there face recognition", "face recognition?", "can lumi recognize faces",
"얼굴 인식 돼", "얼굴 인식 돼요", "얼굴 인식 되니", "얼굴 인식 됩니까", "얼굴 인식 되나요", "얼굴 인식 하세요", "얼굴 인식 기능 있어요",
"얼굴 알아볼 수 있어", "얼굴 알아볼 수 있어요", "얼굴 알아보니", "얼굴 알아봐요", "얼굴 기억해", "얼굴 기억할 수 있어요", "얼굴 인식 되노",
"얼굴 인식 돼유", "face recognition 돼요", "얼굴 인식 기능 있으십니까",
], {"en": ["No, I don't recognise faces or remember who people are. I can see that someone is there, but not who it is.",
"I don't do face recognition: I find people with my cameras, but I can't tell who they are or remember them."],
"ko": ["아니요, 저는 얼굴을 알아보거나 사람을 기억하지 못해요. 사람이 있는 건 보지만 누구인지는 알아보지 못해요.",
"얼굴 인식은 안 해요. 카메라로 사람은 찾지만, 누구인지 알아보거나 기억하지는 않아요."]})
QUICK["no"] += ["what can your camera see", "what do you see with your camera", "카메라로 뭐 보여", "카메라에 뭐 보여요", "카메라 켜 줘",
"camera on", "카메라 돌아가고 있어요", "do you recognize me", "나 알아봐", "내 얼굴 기억해", "remember my face",
"카메라 고장 났어", "is your camera on", "카메라 켜져 있어요"]
+129
View File
@@ -0,0 +1,129 @@
"""Korean wordings at every speech level, for the kinds Lumi acts on: each kind's fronts (object with a side, place,
way, body part, who to) x its verbs x the request endings people use, 반말 to 하십시오체, honorific -시-, 하게체,
dialect, friendly and written slips.
wording.ko_plain already reads most endings as the plain 반말 one before the bank compares ("집어 주십시오",
"집으세요", "집어 주이소" -> "집어 줘"), and the bank stores its wordings the same way, so those collapse into one
wording each; they are listed so every level is covered by name. The endings ko_plain leaves as they are ("집어
주라", "집어 줘 보소", "집어 주시겠소?", "집어 주는 거 어때?", "집어줘") are embedded as said.
"""
import itertools
import zlib
# verb: (반말 form "집어", stem before -세요 / -십시오 "집으" or None); a verb whose 반말 form needs 주다 after it
# ("갖다", "가져다") is marked by a trailing "~"
VERBS = {
"집": ("집어", "집으"), "잡": ("잡아", "잡으"), "들어올려": ("들어 올려", "들어 올리"), "쥐": ("쥐어", "쥐"),
"픽업": ("픽업해", "픽업하"),
"가": ("가", "가"), "이동": ("이동해", "이동하"), "움직": ("움직여", "움직이"), "와": ("와", "오"),
"다가와": ("다가와", "다가오"), "따라와": ("따라와", "따라오"), "쫓아와": ("쫓아와", "쫓아오"),
"따라다녀": ("따라다녀", "따라다니"), "돌아와": ("돌아와", "돌아오"), "돌아가": ("돌아가", "돌아가"),
"복귀": ("복귀해", "복귀하"), "돌아": ("돌아", "도"), "회전": ("회전해", "회전하"), "돌아서": ("돌아서", "돌아서"),
"봐": ("봐", "보"), "쳐다봐": ("쳐다봐", "쳐다보"), "바라봐": ("바라봐", "바라보"), "들어": ("들어", None),
"숙여": ("숙여", "숙이"), "돌려": ("돌려", "돌리"), "올려": ("올려", "올리"), "내려": ("내려", "내리"),
"높여": ("높여", "높이"), "낮춰": ("낮춰", "낮추"), "흔들어": ("흔들어", "흔드"), "악수": ("악수해", "악수하"),
"인사": ("인사해", "인사하"), "내밀어": ("내밀어", "내미"), "뻗어": ("뻗어", "뻗으"), "접어": ("접어", "접으"),
"넣어": ("넣어", "넣으"), "거둬": ("거둬", "거두"), "펴": ("펴", "펴"), "벌려": ("벌려", "벌리"), "열어": ("열어", "여"),
"닫아": ("닫아", "닫으"), "오므려": ("오므려", "오므리"), "가져와": ("가져와", "가져오"), "갖고와": ("갖고 와", "갖고 오"),
"챙겨와": ("챙겨 와", "챙겨 오"), "가져다": ("가져다~", None), "갖다": ("갖다~", None), "놔": ("놔", "놓으"),
"내려놔": ("내려놔", "내려놓으"), "둬": ("둬", "두"), "올려놔": ("올려놔", "올려놓으"),
}
# endings: {a} the 반말 form, {s} the stem before -시-. Levels in order: 반말, friendly, 해요체, honorific, 하십시오체,
# 하게체, dialect (경상 / 전라 / 충청), written slips and suggestions
ENDS = [
"{a}", "{a} 줘", "{a} 봐", "{a}라", "{a} 줄래?", "{a} 줄 수 있어?", "{a} 주라", "{a} 줘라", "{a} 봐 봐", "{a}줘", "{a}봐",
"{a} 줄래 응?", "{a} 주지 않을래?", "{a} 줄 수 있겠어?", "{a} 주는 거 어때?",
"{a}요", "{a} 줘요", "{a} 주세요", "{a} 봐요", "{a} 줄래요?", "{a} 주실래요?", "{a} 주시겠어요?", "{a} 주실 수 있어요?",
"{a} 주셔요", "{a} 주셔", "{a} 주시지 않겠어요?", "{a} 주셨으면 해요", "{a} 주시면 감사하겠습니다",
"{s}세요", "{s}시겠어요?", "{s}실래요?", "{s}시죠",
"{a} 주십시오", "{a} 주시기 바랍니다", "{a} 주시겠습니까?", "{a} 주시길 바랍니다", "{a} 주실 수 있겠습니까?", "{s}십시오",
"{a} 주게", "{a} 주게나", "{a} 주시게", "{a} 주시겠소?", "{a} 주시오", "{s}시오",
"{a} 도", "{a} 주이소", "{s}이소", "{a} 줘 보소", "{a} 주소", "{a}라잉", "{a} 줘라잉", "{a} 주랑께", "{a} 줘유", "{a} 봐유",
"{a} 주이라",
"{a}조", "{a} 줘용", "{a} 주세여", "{a} 줘염", "{a} 주세염", "{a} 주시겠어여?", "{a} 주실래여?", "{a} 주떼여", "{a} 달라",
]
def _say(front, verb, end):
a, s = VERBS[verb]
aux = a.endswith("~")
a = a.rstrip("~")
if "{s}" in end and not s or aux and not any(w in end for w in ("{a} 주", "{a} 줘", "{a}줘", "{a} 줄", "{a} 도",
"{a} 달라")):
return None
return " ".join((front + end.format(a=a, s=s or "")).split())
BASIC = ["{a}", "{a} 줘", "{a} 봐", "{a} 줄래?", "{a} 봐 봐"] # what ko_plain turns most endings into
RAW_SHARE = 0.2 # share of fronts x verbs said with each ending ko_plain keeps as it is (each one embedded)
def _make(fronts, verbs, share=RAW_SHARE):
"""Every front x verb x ending; an ending ko_plain does not read as a BASIC one on a fixed `share` of them."""
from assistant import wording
out = []
for f, v in itertools.product(fronts, verbs):
basic = {wording.ko_plain(t) for t in (_say(f, v, e) for e in BASIC) if t}
for e in ENDS:
t = _say(f, v, e)
if t and (wording.ko_plain(t) in basic or zlib.crc32(t.encode()) % 1000 < share * 1000):
out.append(t)
return list(dict.fromkeys(out))
_OBJ = ["<obj> ", "<obj> 좀 ", "그 <obj> ", "저 <obj> ", "이 <obj> ", "<obj> 하나 ", "저기 있는 <obj> ",
"테이블 위에 있는 <obj> ", "테이블에 있는 <obj> "]
_SIDE = ["왼쪽에 있는 <obj> ", "오른쪽에 있는 <obj> ", "왼쪽 <obj> ", "오른쪽 <obj> ", "왼편에 있는 <obj> ",
"오른편에 있는 <obj> ", "앞에 있는 <obj> ", "가운데 있는 <obj> ", "옆에 있는 <obj> ", "제일 가까운 <obj> ",
"왼쪽에 놓인 <obj> ", "오른쪽에 놓인 <obj> "]
_TO = ["", "저한테 ", "나한테 ", "여기로 ", "이리 "]
_DIRS = ["앞으로 ", "뒤로 ", "왼쪽으로 ", "오른쪽으로 "]
_HOW = ["", "조금 ", "살짝 ", "약간 ", "1 meter ", "한 걸음 ", "좀 "]
INTENT = {
"pick": _make(_OBJ, ["집", "잡", "들어올려", "픽업"]) + _make(_SIDE, ["집", "잡"], share=0.05), # a side said:
# the bank finds the kind, the pick reader leaves it to the rules / LLM (the quick pick takes no side)
"fetch": _make([t + o for t in _TO for o in ["<obj> ", "그 <obj> ", "<obj> 하나 ", "<obj> 좀 "]] +
["왼쪽에 있는 <obj> ", "오른쪽에 있는 <obj> ", "테이블에 있는 <obj> "],
["가져와", "갖고와", "챙겨와", "가져다", "갖다"]),
"put": _make(["<obj> ", "그거 ", "이거 ", "들고 있는 거 ", "왼쪽 테이블에 ", "오른쪽 테이블에 ", "테이블 위에 ", "여기 ",
"저기 ", "바닥에 ", "왼쪽에 ", "오른쪽에 ", "앞에 ", "옆 테이블에 ", "그거 왼쪽에 ", "그거 오른쪽 테이블에 "],
["놔", "내려놔", "둬", "올려놔"]),
"go_to": _make(["<place>로 ", "<place>까지 ", "<place> 쪽으로 ", "<place>에 ", "<place> 앞으로 ", "<place> 방향으로 "],
["가", "이동"]),
"come": _make(["이리 ", "여기로 ", "이쪽으로 ", "나한테 ", "저한테 ", "제 쪽으로 ", "가까이 ", "제 앞으로 ", "내 옆으로 ",
"제 옆으로 ", "일로 ", "좀 더 가까이 "], ["와", "다가와"]),
"follow": _make(["", "저 ", "저를 ", "나 ", "날 ", "제 뒤를 ", "저희를 ", "우리 ", "뒤에서 ", "잘 "],
["따라와", "쫓아와"]),
"come_back": _make(["원래 자리로 ", "제자리로 ", "아까 그 자리로 ", "처음 자리로 ", "원위치로 ", "아까 있던 곳으로 ",
"원래 있던 데로 ", "출발한 곳으로 "], ["돌아와", "돌아가", "복귀"]),
"move": _make([d + h for d in _DIRS for h in _HOW], ["가", "이동", "움직"]),
"turn": _make([d + h for d in ["왼쪽으로 ", "오른쪽으로 "] for h in ["", "90 degrees ", "살짝 ", "몸 ", "조금 "]] +
["뒤로 ", "몸 뒤로 "], ["돌아", "회전"]),
"look": _make(["위 ", "위쪽 ", "아래 ", "아래쪽 ", "왼쪽 ", "오른쪽 ", "저를 ", "절 ", "여기 ", "이쪽 ", "정면 ", "천장 ",
"바닥 ", "제 얼굴 "], ["봐", "쳐다봐", "바라봐"]) +
_make(["고개 ", "고개를 ", "고개 좀 ", "고개 살짝 ", "머리 "], ["들어", "숙여"]) +
_make(["고개 왼쪽으로 ", "고개 오른쪽으로 ", "고개를 왼쪽으로 ", "고개를 오른쪽으로 "], ["돌려"]),
"lift": _make([b + h for b in ["몸 ", "몸을 ", "키 ", "키를 ", "몸통 ", "상체 "] for h in ["", "좀 ", "조금 ", "살짝 ", "더 "]],
["올려", "내려", "높여", "낮춰"]),
"wave": _make(["손 ", "손을 ", "손 좀 ", "손 한번 ", "저한테 손 ", "우리한테 손 ", "애들한테 손 ", "손님들한테 손 ",
"반갑게 손 "], ["흔들어"]) +
_make(["", "저랑 ", "나랑 ", "우리 "], ["악수"]) + _make(["손으로 ", "손 흔들어 "], ["인사"]),
"arm_reach": _make(["손 ", "손을 ", "팔 ", "팔을 ", "손 좀 ", "팔 좀 ", "팔 앞으로 ", "손 앞으로 ", "팔 쭉 ", "저한테 손 "],
["내밀어", "뻗어"]),
"arm_fold": _make(["팔 ", "팔을 ", "팔 좀 ", "팔 다시 ", "팔 이제 "], ["접어", "넣어", "거둬", "내려"]),
"arm_open": _make(["손 ", "손을 ", "손가락 ", "그리퍼 ", "그리퍼를 ", "집게 ", "집게를 ", "손 좀 ", "그리퍼 좀 "],
["펴", "벌려", "열어"]),
"arm_close": _make(["손 ", "손을 ", "손가락 ", "그리퍼 ", "그리퍼를 ", "집게 ", "집게를 ", "그리퍼 좀 "],
["닫아", "오므려"]) + _make(["주먹 ", "주먹 꽉 ", "손 꽉 "], ["쥐"]),
}
# "손 줘" (give me your hand) has no verb of its own here: its levels written out
INTENT["arm_reach"] += [f"{w}{e}" for w in ["손 ", "손 좀 ", "손 이리 ", "저한테 손 "]
for e in ["줘", "줘 봐", "주세요", "줘요", "주십시오", "주실래요?", "줄래?", "주이소", "도", "줘유", "주게",
"주시겠어요?", "주시겠습니까?", "주라", "줘라잉", "주소", "주랑께"]]
if __name__ == "__main__":
for k, v in INTENT.items():
print(f"{k:10} {len(v)}")
print("total", sum(map(len, INTENT.values())))
+182 -3
View File
@@ -247,9 +247,8 @@ QUICK = {
# a greeting with a question after it: the question decides # a greeting with a question after it: the question decides
"안녕 루미 상 받은 거 있어", "안녕하세요 화장실 어디예요", "안녕 루미 날씨 어때", "안녕 루미 상 받은 거 있어", "안녕하세요 화장실 어디예요", "안녕 루미 날씨 어때",
"안녕 오늘 뭐 해", "안녕 오늘 뭐 해",
# not known: the battery's lifetime in years, being another company's robot # not known: being another company's robot (the battery's lifetime in years: quick_answers' guard)
"battery 수명 몇 년이에요", "배터리 수명이 몇 년이에요", "배터리 몇 년 써요", "배터리 교체 주기가 어떻게 돼요", "너 자카 로봇이야", "자카 거야",
"how many years does the battery last", "when does the battery need replacing", "너 자카 로봇이야", "자카 거야",
"jaka에서 만들었어", "are you a jaka robot", "are you made by jaka", "너 중국 회사 로봇 맞지", "hello where is the toilet", "hi what's the weather", "jaka에서 만들었어", "are you a jaka robot", "are you made by jaka", "너 중국 회사 로봇 맞지", "hello where is the toilet", "hi what's the weather",
"hello can you help me", "안녕하세요 질문 있어요", "hi i have a question", "hello can you help me", "안녕하세요 질문 있어요", "hi i have a question",
], ],
@@ -477,3 +476,183 @@ QUICK["name_meaning"] = QUICK.get("name_meaning", []) + [
for e in ["이에요", "이야", "이니", "입니까", "이고", "이여", "인가요", "이죠"]] + [ for e in ["이에요", "이야", "이니", "입니까", "이고", "이여", "인가요", "이죠"]] + [
"why is your name lumi", "why are you named lumi", "what does the name lumi mean", "why the name lumi", "why is your name lumi", "why are you named lumi", "what does the name lumi mean", "why the name lumi",
"왜 루미라고 불러", "왜 이름이 루미야", "왜 루미예요", "왜 루미라고 지었어요"] "왜 루미라고 불러", "왜 이름이 루미야", "왜 루미예요", "왜 루미라고 지었어요"]
# night 5: guesses the answer puts right ("You're Siri, aren't you?", "너 2미터지?"); a Korean "맞지 / 아니야" check is
# quick_answers.OTHER's (the LLM), the "-지?" guess is this kind's
_GUESS = {
"name": ["you're siri aren't you", "your name is alexa right", "are you siri", "are you alexa", "is your name siri",
"you must be siri", "you're bixby right", "your name is bob isn't it", "they call you robbie right",
"your name's wall-e isn't it", "you're r2d2 right", "is it siri", "are you called alexa",
"너 시리지", "너 시리야", "너 빅스비지", "니 이름 알렉사지", "이름이 시리예요", "너 이름이 철수지", "너 이름 로봇이지",
"너 시리니", "혹시 시리세요", "시리십니까", "니 시리제", "니 이름 빅스비 아이가", "이름이 알렉사예요", "너 빅스비야",
"you siri yes", "you are alexa yes", "니 이름 siri지"],
"maker": ["samsung made you right", "you're made by samsung aren't you", "lg made you didn't it", "did samsung make you",
"are you a samsung robot", "are you made by lg", "were you made in china", "did google build you",
"you're a tesla robot right", "is this an lg robot", "you are from samsung yes", "hyundai made you right",
"너 LG 로봇이지", "너 삼성 거지", "삼성이 만들었지", "LG가 만들었지", "너 삼성 로봇이야", "삼성에서 만들었어요",
"LG 제품이에요", "현대가 만들었나요", "구글이 만들었어", "중국에서 만들었지", "삼성 로봇입니까", "니 삼성 끼가",
"삼성 꺼 아이가", "LG에서 만드셨어요", "너 테슬라 로봇이지", "samsung이 만들었어", "LG 꺼야"],
"age": ["you're brand new like a week old", "you must be at least ten years old", "you're about five right",
"are you one year old", "you're new aren't you", "are you older than ten", "you're very young right",
"are you a baby robot", "you look new are you", "are you ten years old",
"너 열 살쯤 됐지", "너 나보다 나이 많아", "너 나보다 어려", "너 한 살이지", "너 신상이지", "너 새로 나왔지", "너 열 살 넘었지",
"다섯 살쯤 됐어요", "너 아기 로봇이지", "갓 나온 로봇이에요", "올해 나온 거예요", "작년에 만들었어요", "니 열 살 넘었제",
"한 살이세요", "몇 년 안 됐지", "만든 지 얼마 안 됐지", "나온 지 오래됐어"],
"height": ["you're two meters tall right", "are you taller than two meters", "you must be about 180 cm", "are you over 2 m",
"you're shorter than me right", "are you as tall as a person", "you're like 1 meter right", "are you 150 cm",
"너 2미터지", "너 2미터 넘지", "너 180 넘지", "키 2미터예요", "키가 1미터쯤 돼요", "사람만 해", "키 150이야",
"니 2미터 넘제", "키가 2미터 되십니까", "너 키 크지", "키 180쯤 돼", "키가 사람만 해요", "너 1미터 넘어"],
"weight": ["you weigh like 20 kilos right", "over 200 kilos i bet", "are you heavier than 100 kg", "you're light aren't you",
"are you very heavy", "do you weigh a ton", "you must weigh 50 kg", "are you lighter than a person",
"200킬로 넘지", "너 100킬로 넘지", "너 가볍지", "너 엄청 무겁지", "너 20킬로야", "무게 50킬로예요", "너 1톤이야",
"사람보다 무거워요", "100킬로 넘습니까", "니 무겁제", "무게 100kg 넘어", "너 몸무게 많이 나가지"],
"speed": ["you're slower than a snail", "are you fast", "you can't go very fast can you", "are you faster than a person",
"you're pretty slow right", "can you go 10 km per hour", "do you go fast", "are you quick",
"너 빨리 달릴 수 있어", "시속 10킬로 나오지", "너 느리지", "너 빨라", "너 달팽이보다 느리지", "사람보다 빨라요",
"너 빨리 갈 수 있어요", "빨리 움직일 수 있으세요", "니 빠르나", "속도 빠르십니까", "너 엄청 느리네", "빨리 달릴 수 있나요"],
"battery_life": ["your battery dies after an hour right", "do you last a whole day", "can you run all day", "does your battery last long",
"you need charging every hour right", "can you go a week without charging", "does the battery last all day",
"일주일 동안 충전 안 해도 되지", "하루 종일 가나", "하루 종일 버텨요", "배터리 금방 닳지", "한 시간이면 배터리 다 닳지",
"배터리 오래 가요", "배터리 하루 가요", "하루 종일 움직일 수 있어요", "배터리 오래가나", "배터리 오래 가십니까",
"배터리 빨리 닳아", "배터리 하루는 가제", "온종일 일할 수 있어"],
"languages": ["you speak ten languages right", "do you speak many languages", "you only speak english right", "are you bilingual",
"can you speak every language", "do you speak japanese too", "are you multilingual",
"너 영어만 하지", "너 외국어 잘하지", "너 다섯 개 언어 하지", "일본어도 하지", "외국어 몇 개 해", "너 중국어도 해",
"영어 잘하세요", "외국말도 하십니까", "니 영어 할 줄 아나", "어떤 말을 알아듣습니까", "어떤 말 알아들어", "무슨 말 알아들어요",
"어떤 언어 알아들으세요", "말 몇 개 국어 알아들어"],
"robot": ["you're just a toy right", "you're remote controlled aren't you", "is someone controlling you", "are you a toy",
"is this a remote control toy", "someone's driving you right",
"너 리모컨으로 조종하는 장난감이지", "너 장난감이지", "누가 조종하지", "리모컨으로 움직이는 거지", "사람이 조종해요",
"누가 원격으로 조종하나요", "니 장난감 아이가", "원격 조종입니까"],
"date_today": ["today is christmas right", "today is monday right", "is it monday today", "is today the 23rd", "is it october already",
"is it the weekend", "is it saturday", "it's friday today isn't it",
"오늘 월요일이지", "오늘 23일이지", "벌써 10월이야", "오늘 주말이야", "오늘 크리스마스예요", "오늘 금요일입니까",
"오늘 토요일이제", "오늘 월요일이죠", "벌써 시월이에요"],
"time_now": ["it's midnight isn't it", "is it noon", "is it late", "is it morning now", "is it already evening", "it's about 3 right",
"지금 자정이지", "지금 점심때야", "지금 오전이에요", "벌써 저녁이야", "지금 세 시쯤 됐지", "지금 밤이에요", "지금 새벽이야"],
}
for _k, _w in _GUESS.items():
QUICK[_k] = QUICK.get(_k, []) + _w
# the month (the date answer names it), and "배터리 수명" = how long it lasts on a charge (years: quick_answers' guard)
QUICK["date_today"] = QUICK.get("date_today", []) + [
"what month is it now", "which month are we in", "remind me what month it is", "month please", "what's the month",
"do you know what month it is", "current month", "what month 이야", "month 뭐야 지금", "몇 월 date야"] + [
s + e for s in ["이번 달 ", "이번 달이 몇 월", "지금 몇 월", "오늘이 몇 월", "몇 월", "요번 달이 몇 월", "이번 달이 무슨 달"]
for e in ["알려 줘", "알려 주세요", "이야", "이에요", "이지", "입니까", "이고", "이여", "이니", "인가요", "이죠"]] + [
"오늘 무신 요일이고", "오늘 무슨 요일이고", "오늘 무신 요일이여", "오늘 머 요일이야", "오늘 뭔 요일", "요일 좀 알려 줘",
"what day of the week might it be", "what day of the week would it be", "which weekday is today", "day of the week please",
"date please", "today's date", "the date please", "date?", "today date what", "today is what date", "what date today"]
QUICK["time_now"] = QUICK.get("time_now", []) + [
s + e for s in ["시간이 어떻게 ", "지금 시간이 어떻게 ", "현재 시간이 어떻게 ", "몇 시나 "]
for e in ["됐어", "됐어요", "됐니", "됐습니까", "됐나요", "되나", "됐노", "됐어유", "됐지", "되셨어요"]] + [
"몇 시나 됐을까", "지금 몇 시쯤이야", "현재 몇 시입니까", "시간 좀 여쭤봐도 될까요", "지금 몇 시인가", "시방 몇 시여", "지금 멧 시고",
"what's the time now please", "got the time", "time now please", "what hour is it", "time?", "what time it is now"]
QUICK["days_to_christmas"] = QUICK.get("days_to_christmas", []) + [
s + e for s in ["크리스마스까지 며칠 남았", "크리스마스 며칠 남았", "성탄절까지 며칠 남았", "크리스마스까지 몇 일 남았", "크리스마스 얼마나 남았",
"성탄절 며칠 뒤", "크리스마스 며칠 뒤", "크리스마스까지 얼마나 남았"]
for e in ["어", "어요", "니", "습니까", "나요", "노", "어유", "지", "야", "예요", "이야"]] + [
"how many days till christmas", "how many days to christmas", "christmas in how many days", "how far is christmas",
"how soon is christmas", "how long is it until christmas", "days until christmas", "christmas countdown", "christmas 얼마나 남았어요",
"christmas 며칠 남았어", "크리스마스 d-day 며칠이야", "크리스마스 디데이 며칠이에요"]
QUICK["battery_life"] = QUICK.get("battery_life", []) + [
s + e for s in ["배터리 수명이 ", "배터리 수명 ", "배터리 수명은 "]
for e in ["어떻게 돼", "어떻게 돼요", "어떻게 되세요", "어떻게 됩니까", "어떻게 되노", "얼마야", "얼마예요", "얼마나 돼", "얼마나 돼요",
"얼마나 되세요", "얼마나 됩니까", "얼마나 되나요", "얼마나 되는가", "얼마고", "얼마여", "얼만가", "몇 시간이야", "몇 시간이에요",
"얼마인지 알려 주세요", "얼마인지 알려 줘", "얼마나 가", "얼마나 가요"]] + [
"how long do you keep going on a full charge", "how long can you keep going", "how long do you last", "how long do you run on one charge",
"how long can you work without charging", "how many hours do you work", "what's your runtime", "what's your operating time",
"battery life?", "battery life please", "how long does a full battery last", "how long before your battery runs out",
"배터리 얼마나 가는가", "배터리 몇 시간 가는가", "충전하면 얼마나 가는가", "배터리 얼마나 가노", "배터리 얼마나 가유",
"배터리 얼마나 버텨", "배터리 몇 시간 버티세요", "배터리 다 닳으면 얼마나 가", "한 번 충전에 몇 시간 일하십니까", "배터리 runtime 얼마예요",
"battery 몇 시간 가요", "배터리 지속 시간 얼마고", "완충하면 몇 시간 써"]
QUICK["name_meaning"] += [
s + e for s in ["이름이 무슨 뜻", "이름 무슨 뜻", "이름 뜻이 뭐", "네 이름 무슨 뜻", "니 이름 뜻이 뭐", "이름은 무슨 뜻", "이름에 무슨 뜻"]
for e in ["이야", "이에요", "이니", "입니까", "인가요", "이고", "이여", "이죠", "이냐", "임"]] + [
"이름은 어디서 왔어", "이름은 어디서 왔어요", "이름 누가 지었어", "이름 누가 지어 줬어요", "이름 왜 그렇게 지었어", "이름 유래가 뭐예요",
"이름의 의미가 뭐예요", "이름에 담긴 뜻이 뭐예요", "이름 어디서 따 왔어", "이름은 어떻게 지어졌습니까", "이름 무신 뜻이고", "이름 뭔 뜻이여",
"where does your name come from", "what does your name mean", "what's the meaning of your name", "how did you get your name",
"who named you", "why are you called that", "what's the story behind your name", "name meaning?", "your name means what",
"이름 meaning이 뭐야", "lumi 무슨 뜻이야"]
# the clock in 하게체 / short forms ("이보게 루미, 지금 몇 시인가?" was read as the age)
QUICK["time_now"] += [s + e for s in ["몇 시", "지금 몇 시", "현재 몇 시", "시방 몇 시"]
for e in ["인가", "인가요", "임", "이야", "예요", "냐", "니", "인고", "이여", "일까", "인지 알려 줘"]] + [
"몇씨야", "몇 씨야", "지금 몇씨야", "멧 시야", "몇 시게", "몇 시나 됐나", "시간 몇 시인가"]
QUICK["date_today"] += [s + e for s in ["오늘 며칠", "오늘 무슨 요일", "오늘 요일이 뭐", "오늘 날짜가 뭐", "오늘이 며칠", "오늘 몇 월 며칠", "무슨 요일"]
for e in ["인가", "인가요", "임", "이냐", "인고", "이여", "일까", "인지 알려 줘", "이니"]]
# what Lumi holds or does now (status), commands and fragments heard in the train sets' first words: never a fact kind
QUICK["no"] += [
s + e for s in ["손에 뭐 ", "손에 뭘 ", "그리퍼에 뭐 ", "집게에 뭐 ", "지금 손에 뭐 ", "손에 들고 있는 거 뭐"]
for e in ["있어", "있어요", "있니", "있나요", "있습니까", "있노", "이써", "들었어", "들고 있어", "쥐고 있어", "잡고 있어", "야", "예요"]] + [
"what's in your hand", "whats in you hand", "what do you have in your hand", "what you have in hand", "what is in the gripper",
"do you have anything in your hand", "are you holding something", "what did you pick up", "what did you grab", "what have you got there",
"핸드폰 어느 손에 있어", "phone 어느 손에 있어", "내 폰 어느 손에 있어", "what are you doing", "wat u doin", "what u doing", "지금 뭐 해",
"뭐 하는 중이야", "지금 뭐 하고 있어요", "what's your battery", "how's your battery", "배터리 어때", "배터리 괜찮아",
"how do you know", "how do you know that", "어떻게 알아", "어떻게 알았어", "어떻게 아세요", "언제", "언제요", "언제야", "when", "when is it",
"위험해", "위험하다", "조심해", "조심해요", "위험해요 비켜", "watch out", "careful",
"360도 돌아", "한 바퀴 돌아", "turn around 360", "spin around", "raise yourself", "lift yourself up", "lift up", "올라가", "리프트 올려",
"please wave hello", "wave hello", "say hello", "손 흔들어", "손 좀 흔들어 주세요", "손 내밀어", "손 줘", "악수하자", "stop the robot",
"stop", "멈춰", "그만", "speak slower", "please speak more slowly", "please you speak more slow", "천천히 말해", "speak louder",
"let's walk together", "같이 걸어요", "같이 가요", "같이 걷자", "선물 받았어요", "선물이에요", "take the elevator", "엘리베이터 타고 가",
"can you take the elevator", "엘리베이터 탈 수 있어", "2층으로 올라갈 수 있어", "can you go to the second floor"]
# night 5, round 2: Konglish nouns (에이지, 웨이트, 스피드, 하이트, 메이커, 필링 ...), 하게체 / dialect endings and
# non-native English frames ("now time what?", "you how heavy?"), from the r9 / r8 train misses
_ASK_N = ["야", "예요", "에요", "니", "입니까", "인가요", "인가", "고", "여", "임", "유", "이야", "이에요", "인데", "일까요"]
_HOW_MUCH = ["얼마야", "얼마예요", "얼마니", "얼마입니까", "얼만가", "얼마고", "얼마여", "얼마임", "얼마유", "몇이야", "몇이에요", "몇이니",
"몇입니까", "몇인가", "몇이고", "몇이여", "몇임", "how much", "얼마나 돼", "얼마나 돼요", "얼마나 되세요", "얼마나 되는가"]
_WHAT = ["뭐야", "뭐예요", "뭐에요", "뭐니", "뭡니까", "무엇입니까", "뭔가요", "뭔가", "무엇인가", "뭐고", "뭐꼬", "뭐여", "뭐임", "머야",
"뭔데", "뭐유", "뭔지 알려 줘", "무엇인지 알려 주십시오", "무엇인지 알려 주시겠습니까", "어떻게 되세요", "어떻게 돼"]
QUICK["age"] += _ko(["에이지가 ", "에이지 ", "너 에이지 ", "니 에이지 ", "너 age ", "age가 "], _HOW_MUCH) + _ko(
["너 에이지 몇 살", "에이지 몇 살", "너 몇 살", "나이가 몇 살", "몇 살"], ["이에요", "이야", "인가", "인가요", "이유", "이고", "입니까", "이여", "임"]) + [
"your age is", "you age is", "your age what", "how many year you", "how many years you are", "you how old", "age please",
"나이 무엇입니까", "나이가 어떻게 되는가", "몇 살이신가", "몇 살 잡수셨어요", "연세가 어떻게 되시는가"]
QUICK["weight"] += _ko(["웨이트가 ", "웨이트 ", "너 웨이트 ", "너 weight ", "weight가 ", "너 무게 ", "무게가 ", "몸무게 ", "몸무게가 "], _HOW_MUCH) + _ko(
["몇 킬로", "너 몇 킬로", "몇 kg", "너 몇 키로"], ["유", "야", "예요", "인가", "입니까", "고", "여", "임", "이야", "이에요"]) + [
"how heavy 해요", "how heavy 해", "how heavy 이에요", "you how heavy", "how heavy you", "your weight how much", "weight please",
"you weight how much", "how many kilo you", "how many kilogram you are"]
QUICK["speed"] += _ko(["스피드가 ", "스피드 ", "맥스 스피드 ", "너 speed ", "speed가 ", "너 스피드 ", "최고 속도 ", "최고 속도가 ", "속도 ", "속도가 "],
_HOW_MUCH) + [
"your speed how much", "you speed how much", "how fast you go", "you how fast", "how fat can you drive", "how fat do you move",
"how fsat do you move", "max speed please", "speed?", "your speed what", "how fast 해요", "how fast 가요", "how fast 이에요"]
QUICK["height"] += _ko(["하이트가 ", "하이트 ", "너 하이트 ", "너 height ", "height가 ", "키 ", "키가 ", "너 키 ", "니 키 "], _HOW_MUCH) + _ko(
["너 몇 센티", "몇 센티", "키가 몇 센티", "몇 cm"], ["유", "야", "예요", "인가", "입니까", "고", "여", "임", "이야", "이에요"]) + [
"how tall 이에요", "how tall 이야", "how tall 해요", "키 how much", "키 how tall", "you how tall", "your height how much",
"your height what", "what is height of you", "height please", "how much tall you"]
QUICK["name"] += _ko(["네임이 ", "네임 ", "너 네임 ", "니 네임 ", "이룸이 ", "이룸 ", "이름이 ", "이름 ", "너 이름 ", "네 이름 ", "니 이름 "], _WHAT) + [
"you name is", "your name is", "name of you", "what is name of you", "your name what", "you name what", "what you name",
"이름이 what이에요", "name이 뭐야", "너 name 뭐야"]
QUICK["maker"] += _ko(["메이커가 ", "메이커 ", "너 메이커 ", "너 메이드 바이 ", "메이드 바이 ", "너 만든 회사 ", "너 만든 외사 ", "너 만든 company ",
"만든 회사 ", "만든 데가 ", "제조 회사 ", "제조사 "], ["어디야", "어디예요", "어디니", "어디입니까", "어딘가", "어디고", "어디여",
"어디임", "어디유", "어디당가", "어디요", "어디인가요", "어디 있어"]) + _ko(
["누가 너를 만들었", "누가 널 만들었", "어느 회사가 너를 만들었", "어느 회사가 널 만들었", "누가 너 만들었"],
["어", "어요", "니", "습니까", "나요", "나", "냐", "는교", "남유", "노", "어유", "는가", "지"]) + [
"who make you", "you made by which company", "made by which company", "which company make you", "who is your maker",
"made by who", "you made by who", "who makes you", "maker?", "your maker what"]
QUICK["robot"] += _ko(["리얼 휴먼", "너 리얼 휴먼", "진짜 사람", "너 진짜 사람"], ["이야", "이에요", "이니", "입니까", "인가", "이유", "이고", "임"]) + _ko(
["필링 있", "너 필링 있", "감정 있", "너도 감정 있", "필링이 있"], ["어", "어요", "니", "나요", "으세요", "습니까", "는가", "는교", "나"]) + _ko(
["살아 있", "너 살아 있", "혹시 살아 있"], ["는가", "는교", "나", "어", "어요", "니", "습니까", "남유"]) + [
"are you a rela person", "are you a real person", "you are alive", "you have feeling", "you have feelings", "you are human",
"are you real human", "you real person", "you alive"]
QUICK["model"] += _ko(["너 AI ", "너 AI가 ", "쓰는 AI 모델 ", "들어 있는 인공지능 ", "들어있는 인공지능 ", "탑재된 인공지능 ", "들어 있는 AI ",
"너 인공지능 ", "니 AI ", "쓰는 인공지능 "], _WHAT) + [
"your ai what", "you use which ai", "which ai you use", "your ai is what", "ai model what"]
QUICK["chatgpt"] += ["yuor ai is chatgpt", "your ai is chatgpt", "you are chatgpt", "you use chatgpt", "chatgpt inside you",
"you chatgpt", "inside is chatgpt"]
QUICK["languages"] += _ko(["할 수 있는 언어 ", "말할 수 있는 언어 ", "하는 언어 ", "할 줄 아는 언어 ", "알아듣는 언어 ", "너 언어 "], _WHAT) + [
"you speak which language", "which language you speak", "you speak what language", "language you speak what",
"korean 알아들어", "english 알아들어", "korean 할 줄 알아", "한국말 알아들어", "영어 알아들어요"]
QUICK["battery_life"] += _ko(["한 번 충전하면 사용 시간 ", "배터리 사용 시간 ", "충전하면 사용 시간 ", "사용 시간 "], _HOW_MUCH + ["얼마인지 알려 주시겠어요"]) + [
"battery how long", "batetry how long", "your battery how long", "battery how many hours", "how long battery", "how long 베터리 가요",
"how long 배터리 가요", "battery life 얼마야", "battery 얼마나 가요", "how many hurs can you run on one charge"]
QUICK["time_now"] += ["do you have the time", "what time now", "now time what", "time now what", "now what time", "what is time now",
"tell me time now", "time what now", "지금 타임 몇 시야"]
QUICK["date_today"] += ["today what day", "today what date", "what day today", "today day what", "date today what", "what is date today"]
# round 3: Konglish date / day, dialect -유 for the clock, words run together
QUICK["date_today"] += _ko(["투데이 데이트 ", "투데이 date ", "today 데이트 ", "오늘 데이트 ", "투데이 무슨 데이", "투데이 무슨 요일", "오늘 무슨 데이"],
["며칠이야", "며칠이에요", "뭐야", "뭐예요", "몇 일이야", "언제야", "야", "예요", "입니까", "고", "임"]) + [
"today date what", "tody date what", "tday date what", "date of today what", "today is which date", "today day what"]
QUICK["time_now"] += _ko(["몇 시", "지금 몇 시", "시방 몇 시"], ["유", "여유", "래유", "인감", "이당가"]) + [
"몇시입니까", "지금몇시야", "몇시임", "지금몇시예요", "몇시야", "지금몇시입니까", "몇시예요"]
QUICK["height"] += ["몇센티임", "너몇센티임", "키얼마유", "키가얼마유", "키 얼마나 된당가", "너 키 얼마나 된당가", "키howmuch"]
QUICK["weight"] += ["howheavy해요", "너무게얼마인지알려주시겠어요", "무게얼마인지알려주세요"]
+151 -31
View File
@@ -257,9 +257,10 @@ COMPANY_TALK = re.compile(r"\b(cutshion|company|companies|firm|ceo|founder|start
# the company example bank goes with company talk only: "tell me more" about the lidar got "which part of Cutshion?" # the company example bank goes with company talk only: "tell me more" about the lidar got "which part of Cutshion?"
def _examples(text, k=None, on_task=False): def _examples(text, k=None, on_task=False, world=False):
"""A few replies Lumi gave to similar words (assistant/talk_examples.py; on a task also """A few replies Lumi gave to similar words (assistant/talk_examples.py; on a task also
assistant/interrupt_examples.py), as a guide to tone and variety.""" assistant/interrupt_examples.py), as a guide to tone and variety. world: a question about a subject of its own
(Brain.world_talk): only world-knowledge examples ("윤초는 뭐예요?" was shown "이름이 뭐예요?" and the like)."""
from assistant import action_examples, interrupt_examples, talk_examples from assistant import action_examples, interrupt_examples, talk_examples
try: try:
from assistant import company_examples # questions about Cutshion Company and its robots from assistant import company_examples # questions about Cutshion Company and its robots
@@ -270,6 +271,8 @@ def _examples(text, k=None, on_task=False):
if on_task: if on_task:
bank += [("task", "ko" if HANGUL.search(u) else "en", u, r) bank += [("task", "ko" if HANGUL.search(u) else "en", u, r)
for _, _, u, d, r in interrupt_examples.EXAMPLES if d in ("answer", "refuse_redirect")] for _, _, u, d, r in interrupt_examples.EXAMPLES if d in ("answer", "refuse_redirect")]
if world:
bank = [e for e in bank if e[0] in WORLD_EXAMPLES]
picked = talk_examples.pick(text, "ko" if language(text) == "Korean" else "en", k=k or EXAMPLES_K, bank=bank) picked = talk_examples.pick(text, "ko" if language(text) == "Korean" else "en", k=k or EXAMPLES_K, bank=bank)
if not picked: if not picked:
return "" return ""
@@ -279,6 +282,9 @@ def _examples(text, k=None, on_task=False):
f"now in your own words):\n{lines}\n\n") f"now in your own words):\n{lines}\n\n")
WORLD_EXAMPLES = {"settled_fact", "off_topic"} # example kinds shown for a world question (talk / action_examples)
def _notes(hits): def _notes(hits):
"""The note chunks for the prompt. A chunk that goes on a section repeats the section's lead ("How fast I move: My """The note chunks for the prompt. A chunk that goes on a section repeats the section's lead ("How fast I move: My
base drives ... … I can climb"): left out when a chunk of that section is shown already (fewer tokens).""" base drives ... … I can climb"): left out when a chunk of that section is shown already (fewer tokens)."""
@@ -678,11 +684,11 @@ INTENTS = [ # (action, pattern) checked in order on what the visitor said
("fetch",rf"\b(fetch|bring|deliver|carry)\b.*\b({_OBJ}|it|that|this)s?\b|\b(take|get|grab)\b.*\b({_OBJ})s?\b.*\b(from|to)\b" ("fetch",rf"\b(fetch|bring|deliver|carry)\b.*\b({_OBJ}|it|that|this)s?\b|\b(take|get|grab)\b.*\b({_OBJ})s?\b.*\b(from|to)\b"
rf"|\b(go|drive) to\b.*\b(get|take|grab|pick up|fetch|bring)\b.*\b({_OBJ})s?\b" rf"|\b(go|drive) to\b.*\b(get|take|grab|pick up|fetch|bring)\b.*\b({_OBJ})s?\b"
rf"|\b(pick up|pick|take|grab|get)\b.*\b({_OBJ})s?\b.*\b(go|drive) to\b|({_OBJ}).*(집어서|들고).*가서" rf"|\b(pick up|pick|take|grab|get)\b.*\b({_OBJ})s?\b.*\b(go|drive) to\b|({_OBJ}).*(집어서|들고).*가서"
r"|가져와|가져다|갖다|가지고 ?와|갖고 ?(?:와|오)|챙겨 ?오|가져 ?오실|가저 ?(?:와|다)|에서.*\b(?:bring|fetch|brign|fech)\s*해|가져 ?오(?:세요|십시오|시오|너라|거라|게|라|실래요|시겠어요)|가지고 ?오(?:세요|십시오|시오|너라|거라|게|라|실래요|시겠어요)|챙겨 ?와|에서.*(옮겨|가져)" rf"|({_OBJ}).*(집고|들고|가지고).*(와|줘)"), r"|가져와|가져다|갖다|가지고 ?와|갖고 ?(?:와|오)|챙겨 ?오|가져 ?오실|가저 ?(?:와|다)|에서.*\b(?:bring|fetch|brign|fech)\s*해|가져 ?오(?:세요|십시오|시오|너라|거라|게|라|실래요|시겠어요)|가지고 ?오(?:세요|십시오|시오|너라|거라|게|라|실래요|시겠어요)|챙겨 ?와|에서.*(옮겨|가져)" rf"|({_OBJ}).*(집고|들고|가지고).*(와|줘)|({_OBJ})\S*\s.*\S(?:으로|로|까지)\s*(?:좀\s*)?옮겨|({_OBJ})\s*(?:이랑|랑|하고|과|와) (?:같이|함께)\s+\S+?(?:으로|로|까지|에)?\s*(?:좀\s*)?가(?![가-힣])"),
("come", r"\bcome (?:back )?(here|hear|to me|closer|over here|over|this way)\b|\bcome\b(?! back for (?:me|us)\b).*\bme\b|이리 ?(?:좀 ?)?(?:돌아 ?)?(?:와|오세요|오십시오|올래)|" ("come", r"\bcome (?:back )?(here|hear|to me|closer|over here|over|this way)\b|\bcome\b(?! back for (?:me|us)\b).*\bme\b|이리 ?(?:좀 ?)?(?:돌아 ?)?(?:와|오세요|오십시오|올래)|"
r"(?:여기로|이쪽으로) ?(?:좀 ?)?(?:돌아 ?)?(?:와|오세요|오십시오)|가까이 ?(?:좀 ?)?(?:와|오세요)|" r"(?:여기로|이쪽으로) ?(?:좀 ?)?(?:돌아 ?)?(?:와|오세요|오십시오)|가까이 ?(?:좀 ?)?(?:와|오세요)|"
r"나한테 ?(?:돌아 ?)?와"), r"나한테 ?(?:돌아 ?)?와"),
("go_home", r"\bgo (back )?(home|to (the |your )?(dock(?!2)|charger|charging))|\bhead (back )?to (the |your )(dock(?!2)|charger)\b|\bgo (re)?charge|충전하러|집(?:에|으로) ?가|충전기로"), ("go_home", r"\bgo (back )?(home|to (the |your )?(dock(?!2)|charger|charging))|\bhead (back )?to (the |your )(dock(?!2)|charger)\b|\bgo (re)?charge|충전하러|차지하러|집(?:에|으로) ?가|충전기로"),
("go_point", r"\b(?:go|drive|move|head|come|return|walk|roll|run|proceed|navigate|travel|hurry|make your way|get|take yourself)" ("go_point", r"\b(?:go|drive|move|head|come|return|walk|roll|run|proceed|navigate|travel|hurry|make your way|get|take yourself)"
r"(?: back)?(?: over| on| ahead)?(?: to| too| 2|to) (?:the )?(?:point |marker )?([a-z][a-z0-9_]*|[가-힣][가-힣0-9_]*?)\b|(\d+)\s*번\s*(?:으로|포인트)" r"(?: back)?(?: over| on| ahead)?(?: to| too| 2|to) (?:the )?(?:point |marker )?([a-z][a-z0-9_]*|[가-힣][가-힣0-9_]*?)\b|(\d+)\s*번\s*(?:으로|포인트)"
r"|^\W*(?:(?:루미야?|lumi|hey lumi)\W*)?(?:[a-z][a-z0-9_]*\s*말고\s+)?(?:좀\s*)?(?:point\s+)?([a-z][a-z0-9_]*|[가-힣][가-힣0-9_]*?)\s*(?:포인트\s*)?(?:앞|쪽|방향|지점|위치)?\s*" r"|^\W*(?:(?:루미야?|lumi|hey lumi)\W*)?(?:[a-z][a-z0-9_]*\s*말고\s+)?(?:좀\s*)?(?:point\s+)?([a-z][a-z0-9_]*|[가-힣][가-힣0-9_]*?)\s*(?:포인트\s*)?(?:앞|쪽|방향|지점|위치)?\s*"
@@ -730,7 +736,10 @@ INTENTS = [ # (action, pattern) checked in order on what the visitor said
r"(\d+(?:\.\d+)?)\s*m\s*(?:만\s*)?(뒤로|앞으로)\s*(?:좀\s*)?(?:가|와|이동|움직|후진)|(?:(\d+(?:\.\d+)?)\s*m\s*(?:만\s*)?)?(후진)|" r"(\d+(?:\.\d+)?)\s*m\s*(?:만\s*)?(뒤로|앞으로)\s*(?:좀\s*)?(?:가|와|이동|움직|후진)|(?:(\d+(?:\.\d+)?)\s*m\s*(?:만\s*)?)?(후진)|"
r"(앞으로|뒤로|왼쪽으로|오른쪽으로)\s*(?:조금만?|좀|살짝)?\s*(\d+(?:\.\d+)?)?\s*(?:미터|m)?\s*(?:만\s*)?(?:가|와|이동|움직)"), r"(앞으로|뒤로|왼쪽으로|오른쪽으로)\s*(?:조금만?|좀|살짝)?\s*(\d+(?:\.\d+)?)?\s*(?:미터|m)?\s*(?:만\s*)?(?:가|와|이동|움직)"),
("put", r"\bput (it|that|this|the \w+) (back|down)\b|\bput (it|that|this|the \w+) (on|onto) the table\b" ("put", r"\bput (it|that|this|the \w+) (back|down)\b|\bput (it|that|this|the \w+) (on|onto) the table\b"
r"|제자리에 ?(놓|둬|놔)|다시 ?(놓|둬|놔)|내려 ?(놓|둬|놔)|" + PUT_BACK), r"|제자리에 ?(놓|둬|놔)|다시 ?(놓|둬|놔)|내려 ?(놓|둬|놔)|" + PUT_BACK +
rf"|\b(?:put|set|place|leave|drop) (?:it|that|this|the (?:\w+ )?(?:{_OBJ})s?) (?:off |down )?(?:at|on|in|by) (?!(?:the )?(?:floor|ground)\b)"
rf"|(?:{_OBJ}|그거|그것|그걸|이거|이걸|저거)(?:을|를)?\s*(?:좀\s*)?(?:[가-힣a-z0-9 ]+(?:에|에다가?)\s*)?(?:갖다\s*|올려\s*|내려\s*)?(?:놔|놓아|둬)(?!\s*(?:가|와|버려|봐))"),
# ^ "컵 놔", "그거 놔 줘" (put down: never an open hand that drops it), "컵 p2에 놔", "put the cup at p3" (a fetch there)
("move_object", rf"\b(?:move|shift|slide) (?:the |that |this |a )?(?:({_COL}) )?({_OBJ})s?\b" ("move_object", rf"\b(?:move|shift|slide) (?:the |that |this |a )?(?:({_COL}) )?({_OBJ})s?\b"
rf"|(?:({_COL})\s*)?({_OBJ})\s*(?:을|를)?\s*옮겨"), rf"|(?:({_COL})\s*)?({_OBJ})\s*(?:을|를)?\s*옮겨"),
("pick", rf"\b(?:pick up|pick|take|grab|get|lift|hold|scoop up|scoop|snag|nab|seize|(?:take|get|grab) hold of) (?:up )?(?:me )?(?:the |that |this |a |an |my |your )?(?:({_COL}) )?({_OBJ})s?\b" ("pick", rf"\b(?:pick up|pick|take|grab|get|lift|hold|scoop up|scoop|snag|nab|seize|(?:take|get|grab) hold of) (?:up )?(?:me )?(?:the |that |this |a |an |my |your )?(?:({_COL}) )?({_OBJ})s?\b"
@@ -848,7 +857,7 @@ GREET_ONLY = re.compile( # a hello and a name, nothing asked: never a wave by
r"(?:(?:lumi|loomi|robot|there|everyone|buddy|루미야?|루미 ?씨|로봇아?|로봇 ?씨)\W*)*$", re.I) r"(?:(?:lumi|loomi|robot|there|everyone|buddy|루미야?|루미 ?씨|로봇아?|로봇 ?씨)\W*)*$", re.I)
CALLING = re.compile(r"^\W*(?:(?:hey|hi|okay|ok|so|um+|uh+|alright|please|well|now|저기요?|혹시|음+|자|야|어+|그럼|이제)\W+)*" CALLING = re.compile(r"^\W*(?:(?:hey|hi|okay|ok|so|um+|uh+|alright|please|well|now|저기요?|혹시|음+|자|야|어+|그럼|이제)\W+)*"
r"(?:(?:lumi|루미 ?씨|루미야?|루미|로봇아|로봇 ?씨|robot)\W+)?(?:(?:저기요?|혹시|음+|자|그럼|이제|now)\W+)*", re.I) # words that call Lumi or fill, before the request itself r"(?:(?:lumi|루미 ?씨|루미야?|루미|로봇아|로봇 ?씨|robot)\W+)?(?:(?:저기요?|혹시|음+|자|그럼|이제|now)\W+)*", re.I) # words that call Lumi or fill, before the request itself
_NOT_A_NAME = (r"Lumi|Okay|Ok|Yes|No|Wait|Well|Hey|Hi|So|Oh|Please|Sorry|Thanks|Now|Look|Wow|Alright|Great|Sure|Right|Hello|" _NOT_A_NAME = (r"Lumi|Okay|Ok|Yes|No|Yo|Kindly|Robot|Buddy|Wait|Well|Hey|Hi|So|Oh|Please|Sorry|Thanks|Now|Look|Wow|Alright|Great|Sure|Right|Hello|"
r"Come|Go|Then|And|But|Also|Here|There|Yeah|Nope|Cool|Nice|Maybe|Seoul|Korea|Um+|Uh+|Uhm|Er+m?|Hmm+|Ah+|" r"Come|Go|Then|And|But|Also|Here|There|Yeah|Nope|Cool|Nice|Maybe|Seoul|Korea|Um+|Uh+|Uhm|Er+m?|Hmm+|Ah+|"
r"Excuse|Actually|First|Just|Stop|Turn|Move|Take|Pick|Bring|Put|Give|Follow|Wave|Lift|Raise|Lower|Open|" r"Excuse|Actually|First|Just|Stop|Turn|Move|Take|Pick|Bring|Put|Give|Follow|Wave|Lift|Raise|Lower|Open|"
r"Close|Hold|Grab|Look|Let|Fine|Good|Thank|Booth|Hall|Gate|Point|Stage|Exit|Home|Dock|Room|Table|Info|" r"Close|Hold|Grab|Look|Let|Fine|Good|Thank|Booth|Hall|Gate|Point|Stage|Exit|Home|Dock|Room|Table|Info|"
@@ -956,7 +965,8 @@ ASKED = re.compile( # a question, not an order: "and when you carry a cup?", "
r"(?<!줄 )(?<!주실 )(?<!줘 )(?<!놓을 )(?<!받을 )수 ?있(?:어|나|니|을까|습니까)\S*\s*\?*\s*(?:궁금\S*)?\s*$|" r"(?<!줄 )(?<!주실 )(?<!줘 )(?<!놓을 )(?<!받을 )수 ?있(?:어|나|니|을까|습니까)\S*\s*\?*\s*(?:궁금\S*)?\s*$|"
r"\b(?:can|could) (?:it|the robot|lumi)\b|(?:돌|가|움직이|들)(?:아|어)?도 ?(?:돼|되)(?:요|나요|니)?\s*\??\s*$|거 보여", re.I) r"\b(?:can|could) (?:it|the robot|lumi)\b|(?:돌|가|움직이|들)(?:아|어)?도 ?(?:돼|되)(?:요|나요|니)?\s*\??\s*$|거 보여", re.I)
IDIOMS = re.compile(r"\bmove (?:forward|on|ahead) with\b|\bon hold\b|^\W*(?:okay,? |sure,? |yes,? )?go ahead\W*$|" IDIOMS = re.compile(r"\bmove (?:forward|on|ahead) with\b|\bon hold\b|^\W*(?:okay,? |sure,? |yes,? )?go ahead\W*$|"
r"\bback me up\b|\bput (?:yourself|myself) in\b|\bturn (?:it|this|that) (?:around|over) for\b|" r"\bback me up\b|\bput (?:yourself|myself) in\b|"
r"^\W*chin up\W*(?:(?:buddy|bro|pal|mate|friend|lumi|little guy|kiddo|okay|ok)\W*)*$|\bturn (?:it|this|that) (?:around|over) for\b|"
r"(?:택시|차|자리|기회|균형|중심|택배|범인|날짜|약속|시간|방)\s*(?:을|를)?\s*(?:좀\s*)?잡", re.I) r"(?:택시|차|자리|기회|균형|중심|택배|범인|날짜|약속|시간|방)\s*(?:을|를)?\s*(?:좀\s*)?잡", re.I)
# "move forward with the plan", "put that thought on hold", "택시 잡아": no motion meant # "move forward with the plan", "put that thought on hold", "택시 잡아": no motion meant
CANT_GO = re.compile(r"\b(?:stairs|upstairs|downstairs|staircase|steps up|escalators?)\b|계단|에스컬레이터", re.I) CANT_GO = re.compile(r"\b(?:stairs|upstairs|downstairs|staircase|steps up|escalators?)\b|계단|에스컬레이터", re.I)
@@ -988,12 +998,19 @@ def not_an_order(text, asked=True):
asked=False: questions do not count (a chain answers its question part: "wave and what time is it?").""" asked=False: questions do not count (a chain answers its question part: "wave and what time is it?")."""
t = unfill(wording.ko_plain(text or "")) # "날 따라오면 돼" is "날 따라와": no condition t = unfill(wording.ko_plain(text or "")) # "날 따라오면 돼" is "날 따라와": no condition
rest = instead_of(t) # "don't put your arm out, my baby will grab it" rest = instead_of(t) # "don't put your arm out, my baby will grab it"
return bool(to_someone_else(t) or CANT_GO.search(t) or DRINK.search(t) or IDIOMS.search(t) or CONDITION.search(t) or REMARK.search(t) or return bool(to_someone_else(t) or CANT_GO.search(t) or DRINK.search(t) or IDIOMS.search(t) or
CONDITION.search(WAIT_UNTIL.sub(" ", t)) or REMARK.search(t) or
TAKEN_BACK.search(t) or TAKEN_BACK.search(t) or
rest != t and REMARK.search(rest) or asked and ASKED.search(t) or NEGATED.search(t) or ko_told(t) or rest != t and REMARK.search(rest) or asked and ASKED.search(t) or NEGATED.search(t) or ko_told(t) or
ABOUT_IT.search(t) or LATER_SAID.search(t)) ABOUT_IT.search(t) or LATER_SAID.search(t))
WAIT_UNTIL = re.compile(r"\b(?:until|till) (?:someone|somebody|anyone|a person|the person|they|people|a guest|the guests?) "
r"(?:gives?|hands?|brings?|passes?)\b|(?:누가|누군가|사람이|손님이)\s+(?:\S+\s+){0,2}"
r"(?:줄|건네줄|가져다 ?줄|갖다 ?줄) 때까지", re.I)
# ^ "wait until someone gives you the cup", "누가 컵 줄 때까지 기다려": the wait is the order, not a condition on it
_TAKE_BACK = (r"아니(?:야|에요|요|오)?|아냐|아닐세|됐네|됐소|아닙니다|아니다|됐어|됐어요|됐습니다|됐다|괜찮아|괜찮아요|괜찮습니다|" _TAKE_BACK = (r"아니(?:야|에요|요|오)?|아냐|아닐세|됐네|됐소|아닙니다|아니다|됐어|됐어요|됐습니다|됐다|괜찮아|괜찮아요|괜찮습니다|"
r"장난(?:이야|이에요|입니다|이다|임)?|농담(?:이야|이에요|입니다|이다|임)?|취소(?:할게|할게요|하겠습니다|해)?|" r"장난(?:이야|이에요|입니다|이다|임)?|농담(?:이야|이에요|입니다|이다|임)?|취소(?:할게|할게요|하겠습니다|해)?|"
r"하지 ?마(?:세요|십시오)?|하지 않으셔도 (?:돼요|됩니다)|안 ?(?:해도|하셔도) (?:돼|돼요|됩니다)|그만|" r"하지 ?마(?:세요|십시오)?|하지 않으셔도 (?:돼요|됩니다)|안 ?(?:해도|하셔도) (?:돼|돼요|됩니다)|그만|"
@@ -1028,7 +1045,7 @@ _KO_ORDER = re.compile(
r"습니까)?|줄 수 있(?:어|어요|니|나요)?|해|해요|하세요|하십시오|하시오|해라|하게|하시게|하거라|하렴|봐|봐요|보세요|" r"습니까)?|줄 수 있(?:어|어요|니|나요)?|해|해요|하세요|하십시오|하시오|해라|하게|하시게|하거라|하렴|봐|봐요|보세요|"
r"보십시오|보시오|보거라|보게|가|가요|가세요|가십시오|가시오|가라|가거라|가게|가자|와|와요|오세요|오십시오|오시오|와라|오너라|" r"보십시오|보시오|보거라|보게|가|가요|가세요|가십시오|가시오|가라|가거라|가게|가자|와|와요|오세요|오십시오|오시오|와라|오너라|"
r"오게|돌아|돌아요|돌려|흔들어|올려|내려|놔|놓아|둬|집어|들어|멈춰|서|비켜|따라와|따라오세요|켜|꺼|줘봐|해봐|가봐|와봐|" r"오게|돌아|돌아요|돌려|흔들어|올려|내려|놔|놓아|둬|집어|들어|멈춰|서|비켜|따라와|따라오세요|켜|꺼|줘봐|해봐|가봐|와봐|"
r"(?:볼|할|갈|올|줄|해 줄|가 줄)래요?\s*\?|주시겠소|하시겠소|겠소|하시오|주시오|[가-힣]시오|[가-힣](?:아|어|여|라|게|렴|자|세요|십시오|시오|요))(?:\s*(?:요|좀|빨리|얼른|please|now|제발))*" r"(?:볼|할|갈|올|줄|해 줄|가 줄)래요?\s*\?|주시겠소|하시겠소|겠소|하시오|주시오|[가-힣]시오|[가-힣](?:아|어|여|라|게|렴|자|세요|십시오|시오|요)|[가-힣]?(?:려|춰|워|쳐|켜|겨|져))(?:\s*(?:요|좀|빨리|얼른|please|now|제발))*"
r"\s*[.!~?]*$") r"\s*[.!~?]*$")
_KO_NOT = re.compile(r"(?:다|네|지|걸|데|니까|는데|던데|군|구나|더라|더니|대|래|잖아|거야|거예요|건데|까|까요|니|냐|나요|" _KO_NOT = re.compile(r"(?:다|네|지|걸|데|니까|는데|던데|군|구나|더라|더니|대|래|잖아|거야|거예요|건데|까|까요|니|냐|나요|"
r"는지|ㄹ게|을게|할게|갈게|볼게)\s*[.!~?]*$|(?:^|\s)우리\s.*자\s*[.!~?]*$") r"는지|ㄹ게|을게|할게|갈게|볼게)\s*[.!~?]*$|(?:^|\s)우리\s.*자\s*[.!~?]*$")
@@ -1044,7 +1061,7 @@ _KO_TAIL = re.compile(r"(?:\s+(?:루미야?|로봇아?|lumi|robot|please|plz|pls
_KO_NOUN_ORDER = re.compile(r"(?:회전|이동|정지|출발|후진|전진|쭉|move|turn|go|grab|pick|wave|come|stop|rotate|please|plz)\W*$", re.I) _KO_NOUN_ORDER = re.compile(r"(?:회전|이동|정지|출발|후진|전진|쭉|move|turn|go|grab|pick|wave|come|stop|rotate|please|plz)\W*$", re.I)
_KO_ASK_ORDER = re.compile(r"(?:줄래|주실래|줄 수|주실 수|주시겠|줘|주세요|볼래|할래|해 줄|가 줄|갈래|올래|주시죠|주실까요|줄까|실래|" _KO_ASK_ORDER = re.compile(r"(?:줄래|주실래|줄 수|주실 수|주시겠|줘|주세요|볼래|할래|해 줄|가 줄|갈래|올래|주시죠|주실까요|줄까|실래|을래|둘래|릴래|"
r"(?:놓을|놔 줄|내려놓을|해 줄|가 줄) 수 있)[가-힣 ]*\?$") # "가 줄래?", "주시겠어요?"; not "봤어?" r"(?:놓을|놔 줄|내려놓을|해 줄|가 줄) 수 있)[가-힣 ]*\?$") # "가 줄래?", "주시겠어요?"; not "봤어?"
_KO_DIALECT = re.compile(r"(?:이소|보이소|주이소|가이소|하이소|온나|오이라|주시기 바랍니다|바랍니다|드려|드려요|드리세요|" _KO_DIALECT = re.compile(r"(?:이소|보이소|주이소|가이소|하이소|온나|오이라|주시기 바랍니다|바랍니다|드려|드려요|드리세요|"
r"낮춰|맞춰|멈춰|내려|올려|벌려|돌려|비켜|켜|꺼|봐|와|놔|둬|줘|바꿔|세워|키워|펴|접어)(?:\s*(?:요|좀|please|now))*\s*[.!~]*$") r"낮춰|맞춰|멈춰|내려|올려|벌려|돌려|비켜|켜|꺼|봐|와|놔|둬|줘|바꿔|세워|키워|펴|접어)(?:\s*(?:요|좀|please|now))*\s*[.!~]*$")
@@ -1072,13 +1089,14 @@ def _clause_order(c, alone=True):
if not c: if not c:
return False return False
if HANGUL.search(c) and (not re.match(r"[a-z]", c, re.I) or _KO_ORDER.search(c) or _KO_DIALECT.search(c) or if HANGUL.search(c) and (not re.match(r"[a-z]", c, re.I) or _KO_ORDER.search(c) or _KO_DIALECT.search(c) or
re.search(r"(?<=[가-힣\s])(?:다|요|어|아|여|지|네|해|줘|봐|라|게|자|까|니)\W*$", c)): re.search(r"(?<=[가-힣\s])(?:다|요|어|아|여|지|네|해|줘|봐|라|게|자|까|니|래)\W*$", c)):
return _ko_clause(c) or alone and len(c.split()) <= 5 and "?" not in c and not ko_told(c) and \ return _ko_clause(c) or alone and len(c.split()) <= 5 and "?" not in c and not ko_told(c) and \
not re.search(r"[가-힣](?:어|아|여|다|요|지|네|려|워)\W*$", c) not re.search(r"[가-힣](?:어|아|여|다|요|지|네|려|워)\W*$", c)
if c.endswith("?"): if c.endswith("?"):
return bool(re.match(rf"(?:please\s+)?(?:(?:{_VERBS})\b(?!s\b)(?!.*\b(?:or|is|are)\b)|you can {_YOU_CAN}\b(?!.*\b(?:or|by yourself|alone)\b)|(?:can|could|would|will|wo?n'?t) " return bool(re.match(rf"(?:please\s+)?(?:(?:{_VERBS})\b(?!s\b)(?!.*\b(?:or|is|are)\b)|you can {_YOU_CAN}\b(?!.*\b(?:or|by yourself|alone)\b)|(?:can|could|would|will|wo?n'?t) "
r"(?:you|u)\b|would you mind\b|mind \w+ing\b|can i (?:have|get) (?:it|that|this|the)\b|can i take (?:it|that|this)\W*$|" r"(?:you|u)\b|would you mind\b|mind \w+ing\b|can i (?:have|get) (?:it|that|this|the)\b|can i take (?:it|that|this)\W*$|"
r"why don'?t you\b|how about (?:you\b|\w+ing\b)|is it possible (?:for you )?to\b|could i trouble you\b)", c, re.I) or r"why don'?t you\b|how about (?:you\b|\w+ing\b)|(?:is|would|will) it be possible (?:for you )?to\b|is it possible (?:for you )?to\b|"
r"could i trouble you\b)", c, re.I) or
re.search(r"\b(?:okay|ok|alright|please)\s*\?$", c, re.I) and not _SUBJECT.match(c)) re.search(r"\b(?:okay|ok|alright|please)\s*\?$", c, re.I) and not _SUBJECT.match(c))
if _EN_ORDER.match(c) or re.match(r"(?:can|could|would|will) u\b|off you go\b|i need you\b|i said\b|" if _EN_ORDER.match(c) or re.match(r"(?:can|could|would|will) u\b|off you go\b|i need you\b|i said\b|"
r"can i (?:have|get) (?:it|that|this|the)\b|i'?ll take (?:it|that|this)\b|" r"can i (?:have|get) (?:it|that|this|the)\b|i'?ll take (?:it|that|this)\b|"
@@ -1103,7 +1121,8 @@ def direct_order(text):
short fragment command ("booth A", "faster", "left a bit", "회전"). Only then may a keyword rule act; anything else short fragment command ("booth A", "faster", "left a bit", "회전"). Only then may a keyword rule act; anything else
(a statement, a story, a plan between people, a question about ability or habit) is read by the LLM with the talk (a statement, a story, a plan between people, a question about ability or habit) is read by the LLM with the talk
before it. Each sentence / clause is checked; one order in it is enough (not_an_order weeds out the rest).""" before it. Each sentence / clause is checked; one order in it is enough (not_an_order weeds out the rest)."""
t = re.sub(_LEAD, "", unfill(wording.ko_plain(text or "")).strip(), flags=re.I) # every speech level as 반말 t = re.sub(_LEAD, "", unfill(wording.ko_plain(_MAY_NOT.sub(" 줘", text or ""))).strip(), flags=re.I) # every
# speech level as 반말
t = re.sub(r"[\s~]*(?:[ㅋㅎ]{2,}|ㅠ+|ㅜ+)[\s~]*$|~+(?=\s*[?!.]*\s*$)", "", t) # "가 줄래~?", "고개 내려 ㅎㅎ" t = re.sub(r"[\s~]*(?:[ㅋㅎ]{2,}|ㅠ+|ㅜ+)[\s~]*$|~+(?=\s*[?!.]*\s*$)", "", t) # "가 줄래~?", "고개 내려 ㅎㅎ"
t = re.sub(r"^(?:(?:hey |hi |ok |okay |yo |어이 )?(?:mister robot|lumi|loomi|rumi|robot|buddy|bro|dude|yeah|yes|yep|right|" t = re.sub(r"^(?:(?:hey |hi |ok |okay |yo |어이 )?(?:mister robot|lumi|loomi|rumi|robot|buddy|bro|dude|yeah|yes|yep|right|"
r"(?:[루누류]미|루비|로봇)\s*(?:야|아|씨|님|군|선생님?|양반)?)[\s,!]+)+", "", t, flags=re.I) r"(?:[루누류]미|루비|로봇)\s*(?:야|아|씨|님|군|선생님?|양반)?)[\s,!]+)+", "", t, flags=re.I)
@@ -1252,8 +1271,28 @@ def held_back(text):
return bool(HELD_BACK.search(text or "")) return bool(HELD_BACK.search(text or ""))
def _put_there(t, markers):
"""A thing named and put / delivered at a marker ("exit에 컵 갖다 놔", "컵을 p2 테이블에 놔", "put the cup at p3")."""
m = _mentions(t, markers)
return bool(m.get("object") and isinstance(m.get("dest"), dict) and m.get("finish") == "place")
def intent(text, markers=()): def intent(text, markers=()):
"""(action, target) for clear requests, or None. Backs up the LLM's ACTION line.""" """(action, target) for clear requests, or None. Backs up the LLM's ACTION line. Korean at any speech level the
rules miss ("컵 놓으십시오", "허리를 왼쪽으로 돌려 주셨으면 해요", "놔 주시면 안 될까요?") is read again as 반말."""
rule = _intent(text, markers)
if rule is None and HANGUL.search(text or ""):
plain = re.sub(r"줘\s*\?+\s*$", "줘", wording.ko_plain(_MAY_NOT.sub(" 줘", text))) # "놔 줘?": a request asked
if plain != text:
rule = _intent(plain, markers)
return rule
_MAY_NOT = re.compile(r"(?<=[가-힣]) ?주(?:시)?면 안 (?:될까요|되나요|되겠습니까|되겠어요|돼요|돼|될까|되니)\s*\?*")
# ^ "놔 주시면 안 될까요?": a polite request (wording.ko_plain keeps it as it is)
def _intent(text, markers=()):
held = not_an_order(text, asked=False) or held_back(text) # "민수야 이리 와 봐": to a friend; "she said follow me" held = not_an_order(text, asked=False) or held_back(text) # "민수야 이리 와 봐": to a friend; "she said follow me"
text = instead_of(text) text = instead_of(text)
text = re.sub(r"(에|로|으로|까지)\s*가서\s*(?:거기서?\s*)?(?:좀\s*)?(?:서|기다려|대기해)\s*(?:있(?:어|게|으십시오|으세요|어요)?)?" text = re.sub(r"(에|로|으로|까지)\s*가서\s*(?:거기서?\s*)?(?:좀\s*)?(?:서|기다려|대기해)\s*(?:있(?:어|게|으십시오|으세요|어요)?)?"
@@ -1261,7 +1300,7 @@ def intent(text, markers=()):
text = re.sub(r"\bgo (?:and )?(?:stand|wait) (?:at|by|near) ", "go to ", text, flags=re.I) # "go and stand at p10": the trip text = re.sub(r"\bgo (?:and )?(?:stand|wait) (?:at|by|near) ", "go to ", text, flags=re.I) # "go and stand at p10": the trip
t = _norm(text, markers) # "point five" -> "point 5" t = _norm(text, markers) # "point five" -> "point 5"
asks = re.search(r"^\s*(how(?! about (?:you|we) (?!\w+ing\b)\w)|why(?! don'?t you\b)|what if)\b|\b(how do you|how can you|can you carry|are you able)\b|" asks = re.search(r"^\s*(how(?! about (?:you|we) (?!\w+ing\b)\w)|why(?! don'?t you\b)|what if)\b|\b(how do you|how can you|can you carry|are you able)\b|"
r"\b(can|could) you (pick( up)?|lift|hold|grab|take) (a|an|any)\b|" # "can you pick up a bottle?" r"\b(can|could) you (pick( up)?|lift|hold|grab|take) (a|an|any)\b(?!.*\b(?:to|for me|over here|over to|here|please)\b)|" # "can you pick up a bottle?"
r"^\s*(what|when|which|at what|do you|does|is it(?! possible)|are you)\b|몇|언제|얼마|" # "at what level do you go back?" r"^\s*(what|when|which|at what|do you|does|is it(?! possible)|are you)\b|몇|언제|얼마|" # "at what level do you go back?"
rf"({_OBJ})(은|는)\s.*수 ?있|(루미가|로봇이)\s.*수 ?있|는 ?거 ?(돼|되나|가능)|" # "물컵은 가져다줄 수 있어요?" rf"({_OBJ})(은|는)\s.*수 ?있|(루미가|로봇이)\s.*수 ?있|는 ?거 ?(돼|되나|가능)|" # "물컵은 가져다줄 수 있어요?"
r"어떻게|왜|혼자|스스로|\bby yourself\b|\bsomeone\b|줄 ?알아|[을를] 줄 ?아(?:세요|십니까|시나요|나요?|니|노|요)?\s*\?|할 ?줄|\bcome here often\b|" r"어떻게|왜|혼자|스스로|\bby yourself\b|\bsomeone\b|줄 ?알아|[을를] 줄 ?아(?:세요|십니까|시나요|나요?|니|노|요)?\s*\?|할 ?줄|\bcome here often\b|"
@@ -1277,6 +1316,9 @@ def intent(text, markers=()):
continue continue
if held and action not in ("quiet", "stop", "weather", "search", "sing"): if held and action not in ("quiet", "stop", "weather", "search", "sing"):
return None # a motion named, none ordered now return None # a motion named, none ordered now
if action == "go_point" and re.search(rf"\bwith (?:the|a|an|this|that|my) (?:\w+ )?(?:{_OBJ})s?\b|"
rf"(?:{_OBJ})\s*(?:이랑|랑|하고|과|와) (?:같이|함께)", t):
return ("fetch", text) # "go to exit with the cup": the cup taken there
if action not in ("quiet", "stop", "weather", "search", "sing", "fetch") and _other_order(t, m, markers) and not ( if action not in ("quiet", "stop", "weather", "search", "sing", "fetch") and _other_order(t, m, markers) and not (
action in ("pick", "move_object") and any(_resolve(p, markers) not in (None, "here") action in ("pick", "move_object") and any(_resolve(p, markers) not in (None, "here")
for p in re.finditer(_place_re(markers), t))): for p in re.finditer(_place_re(markers), t))):
@@ -1323,6 +1365,8 @@ def intent(text, markers=()):
return None # "don't stop talking" return None # "don't stop talking"
if action == "quiet" and re.search(r"손|흔들", t) and not re.search(r"조용|말하지|말 ?그만|시끄러|\bquiet\b|\btalking\b", t): if action == "quiet" and re.search(r"손|흔들", t) and not re.search(r"조용|말하지|말 ?그만|시끄러|\bquiet\b|\btalking\b", t):
return None # "아직 손 인사 하지 마": about the wave, not the voice return None # "아직 손 인사 하지 마": about the wave, not the voice
if action in ("put", "fetch") and not re.search(r"제자리|원래|\bback\b", t) and _put_there(t, markers):
return ("fetch", text) # "exit에 컵 갖다 놔", "put the cup at p3": taken there, put down
if action == "fetch" and re.search(r"(?:갖다|가져다) ?(?:놓|놔|둬|두)|들고 ?있어|들고 ?계세요", t): if action == "fetch" and re.search(r"(?:갖다|가져다) ?(?:놓|놔|둬|두)|들고 ?있어|들고 ?계세요", t):
continue # "원래 자리에 갖다 놔": put back; "내 컵 들고 있어 줘": hold it continue # "원래 자리에 갖다 놔": put back; "내 컵 들고 있어 줘": hold it
if action == "come" and re.search(r"\bcome (?:down|up)\b|\b(?:lower|higher|taller|shorter)\b", t): if action == "come" and re.search(r"\bcome (?:down|up)\b|\b(?:lower|higher|taller|shorter)\b", t):
@@ -1483,11 +1527,15 @@ def intent(text, markers=()):
else "reach") else "reach")
if action == "grip_close" and re.search(rf"(?<![a-z])(?:{_OBJ})s?(?![a-z])", t): if action == "grip_close" and re.search(rf"(?<![a-z])(?:{_OBJ})s?(?![a-z])", t):
continue # "the cup. grab it.": from the table or my hand? not a fist continue # "the cup. grab it.": from the table or my hand? not a fist
if action == "grip_open" and any(_resolve(p, markers) not in (None, "here") for p in re.finditer(_place_re(markers), t)):
continue # "drop it at p3": a carry there, never an open hand here
if action in ("grip_open", "grip_close"): if action in ("grip_open", "grip_close"):
return ("arm", action[5:]) return ("arm", action[5:])
if action == "put": if action == "put":
return ("put", "back" if re.search(r"\bback\b|\breturn\b|\bwhere (?:it was|you)\b|\bits (?:spot|place)\b|제자리|다시|원래|원위치|있던|도로", t) return ("put", "back" if re.search(r"\bback\b|\breturn\b|\bwhere (?:it was|you)\b|\bits (?:spot|place)\b|제자리|다시|원래|원위치|있던|도로", t)
else "down") else "down")
if action == "pick" and re.search(r"\b(?:grab|get|fetch|pick up|take) me\b", t):
return ("fetch", text) # "go grab me a cup": brought to me, not only picked
if action in ("pick", "move_object") and far: if action in ("pick", "move_object") and far:
return ("fetch", text) # "get me an orange at gate one": a trip there, not a pick here return ("fetch", text) # "get me an orange at gate one": a trip there, not a pick here
if action in ("pick", "move_object"): if action in ("pick", "move_object"):
@@ -1712,6 +1760,21 @@ def unfill(t):
return re.sub(r"\b(the|a|to) \1\b", r"\1", t) return re.sub(r"\b(the|a|to) \1\b", r"\1", t)
KO_SLIPS = [ # Konglish, dialect and whisper's spellings of the cup / delivery verbs, as the readers know them
(r"(?:테이크|픽업|그랩|(?<![가-힣])픽)\s?해서", "집어서"), (r"(?:테이크|픽업|그랩|(?<![가-힣])픽)\s?하고", "집고"),
(r"(?:드랍|드롭)\s?해", "놔"), (r"기달려", "기다려"), (r"기달리", "기다리"), (r"(?<![가-힣])들구(?=\s|$)", "들고"),
(r"가저(?=와|다|가|오)", "가져"), (r"(?<![가-힣])날라(?=\s*(?:줘|주|다|$))", "옮겨"), (r"((?:갖다|가져다)\s?)도(?=\W*$)", r"\1줘"), (r"놓(?:그라|거라)", "놔"),
]
def ko_slips(t):
""""컵 테이크해서" -> "컵 집어서", "드랍해 줘" -> "놔 줘", "기달려" -> "기다려", "갖다 도" -> "갖다 줘"."""
if HANGUL.search(t):
for said, same in KO_SLIPS:
t = re.sub(said, same, t)
return t
def _norm(text, markers=()): def _norm(text, markers=()):
"""Lower case, marker names and numbers as written (wording.py: "피쓰리" -> "p3", "point one" -> "p1", with the """Lower case, marker names and numbers as written (wording.py: "피쓰리" -> "p3", "point one" -> "p1", with the
map's markers "table front" -> "table_front").""" map's markers "table front" -> "table_front")."""
@@ -1721,6 +1784,7 @@ def _norm(text, markers=()):
# metre; "레지스트레이션", "에이 부스": the map's names # metre; "레지스트레이션", "에이 부스": the map's names
for word, digit in NUMBER_WORDS.items(): # "one of them" -> "1 of them" for word, digit in NUMBER_WORDS.items(): # "one of them" -> "1 of them"
t = re.sub(rf"\b{word}\b", digit, t) t = re.sub(rf"\b{word}\b", digit, t)
t = ko_slips(t)
t = re.sub(r"(?<![가-힣])송(?=에\s*(?:좀\s*)?(?:올려|놔|놓|줘)|\s*(?:을\s*)?(?:(?:좀|앞으로|이리|한번|쫙|꽉)\s*)*(?:내밀|내미|뻗|줘|주|치워|흔들|흔드|펴|쥐|닫|열어|거둬|내려|인사|넣어|도\b))", t = re.sub(r"(?<![가-힣])송(?=에\s*(?:좀\s*)?(?:올려|놔|놓|줘)|\s*(?:을\s*)?(?:(?:좀|앞으로|이리|한번|쫙|꽉)\s*)*(?:내밀|내미|뻗|줘|주|치워|흔들|흔드|펴|쥐|닫|열어|거둬|내려|인사|넣어|도\b))",
"손", t) # whisper's 송 for 손: "송 앞으로 내밀어", "저한테 송 주십시오" "손", t) # whisper's 송 for 손: "송 앞으로 내밀어", "저한테 송 주십시오"
return t return t
@@ -1752,6 +1816,9 @@ _AT_OBJ_EN = rf"\b(?:{_OBJ})s?,? (?:that'?s |that is |which is |sitting |lying |
_AT_OBJ_KO = (rf"\s*(?:(?:테이블|탁자|책상|table)\s*)?(?:(?:위|쪽)\s*)?(?:에|의)\s*(?:(?:있는|있던|놓인|놓여\s*있는|둔|올려\s*둔|올려진|올라간|올라가\s*있는)\s*)?" _AT_OBJ_KO = (rf"\s*(?:(?:테이블|탁자|책상|table)\s*)?(?:(?:위|쪽)\s*)?(?:에|의)\s*(?:(?:있는|있던|놓인|놓여\s*있는|둔|올려\s*둔|올려진|올라간|올라가\s*있는)\s*)?"
rf"{_OBJ_ADJ}(?:{_OBJ})|\s*(?:(?:에|의)\s*)?(?:있는|있던|놓인|놓여\s*있는|둔)\s*(?:거|것|걸)") rf"{_OBJ_ADJ}(?:{_OBJ})|\s*(?:(?:에|의)\s*)?(?:있는|있던|놓인|놓여\s*있는|둔)\s*(?:거|것|걸)")
# ^ where the thing is ("the cup on p2", "p2에 있는 빨간 컵", "피원 컵", "p1의 컵"): the source, not where it goes # ^ where the thing is ("the cup on p2", "p2에 있는 빨간 컵", "피원 컵", "p1의 컵"): the source, not where it goes
_PUT_AT_EN = rf"\b(?:put|place|set|leave|drop|deliver|drop off)\s+(?:the |that |this |a |an |my |your )?(?:(?:{_COL}) )?(?:{_OBJ})s?(?: down| off)? (?:(?:on|onto) (?:the )?(?:\w+ )?(?:{_TABLE}) )?(?:on|at|in|by|near|to) (?:the )?$"
_PUT_KO = r"(?:갖다|가져다)\s*(?:놔|놓|둬|두|줘|주|드려|드리)|(?<![가-힣])(?:내려\s*)?(?:놔|놓아|둬)|올려\s*(?:놔|놓)"
# ^ a put / deliver: "<place>에 <thing> 갖다 놔" names where it goes (not "p2에 있는 컵 가져와": where it is)
def _mentions(text, markers): def _mentions(text, markers):
@@ -1767,7 +1834,12 @@ def _mentions(text, markers):
after_obj = objs[-1].end() if objs else 0 after_obj = objs[-1].end() if objs else 0
for m in re.finditer(_place_re(markers), t): for m in re.finditer(_place_re(markers), t):
before, after, place = t[:m.start()], t[m.end():], _resolve(m, markers) before, after, place = t[:m.start()], t[m.end():], _resolve(m, markers)
if re.search(r"\bfrom (the )?$", before) or re.match(r"\s*에서", after) \ if place == "here" and isinstance(out.get("dest"), dict):
continue # "put the cup at exit for me": "me" is not where it goes
if re.search(_PUT_AT_EN, before) or re.search(_PUT_KO, t) and re.match(r"\s*(?:테이블|탁자|책상)?\s*(?:위)?\s*(?:에다가?|에)\s+"
r"(?!있|놓|둔|올려|올라)", after):
out["dest"] = _as_place(place) # "put the cup at p3", "exit에 컵 갖다 놔": where it goes, not where it is
elif re.search(r"\bfrom (the )?$", before) or re.match(r"\s*에서", after) \
or (re.search(r"\b(go|drive|head|come) (over )?(to )?(the )?$", before) # "go (to) p1 and get the cup" or (re.search(r"\b(go|drive|head|come) (over )?(to )?(the )?$", before) # "go (to) p1 and get the cup"
and re.match(r"\s*(,|and|then)\s*(get|fetch|take|pick|grab|bring)", after)) \ and re.match(r"\s*(,|and|then)\s*(get|fetch|take|pick|grab|bring)", after)) \
or (re.match(r"\s+(?:까지\s*)?가서", after) and objs and m.start() < objs[-1].start()) \ or (re.match(r"\s+(?:까지\s*)?가서", after) and objs and m.start() < objs[-1].start()) \
@@ -1777,7 +1849,7 @@ def _mentions(text, markers):
out["source"] = _as_place(place) out["source"] = _as_place(place)
elif re.search(r"\b(to|into) (the )?$|\b(bring|fetch|give|get)( it| that| this)? $", before) \ elif re.search(r"\b(to|into) (the )?$|\b(bring|fetch|give|get)( it| that| this)? $", before) \
or re.search(r"\b(go|drive|head|walk|carry it|take it|bring it)( over)? (the )?$", before) \ or re.search(r"\b(go|drive|head|walk|carry it|take it|bring it)( over)? (the )?$", before) \
or re.match(r"\s*(?:(?:포인트|point|지점|테이블|탁자|책상)\s*(?:위\s*)?)?(으로|로|에다|에|한테)(?!서)", after) or place == "here" \ or re.match(r"\s*(?:(?:포인트|point|지점|테이블|탁자|책상)\s*(?:위\s*)?)?(으로|로|에다|에|한테|까지(?!\s*가서))(?!서)", after) or place == "here" \
or re.match(r"\s+(?:까지\s*)?(?:가(?:서|요|\s*줘|\s*주세요)?|이동)(?![가-힣])", after): or re.match(r"\s+(?:까지\s*)?(?:가(?:서|요|\s*줘|\s*주세요)?|이동)(?![가-힣])", after):
# ^ "and go exit point", "exit 가서", "exit 까지 가 줘": a drive there, said without "to" / 로 # ^ "and go exit point", "exit 가서", "exit 까지 가 줘": a drive there, said without "to" / 로
out["dest"] = _as_place(place) out["dest"] = _as_place(place)
@@ -1791,7 +1863,8 @@ def _mentions(text, markers):
if m.start() > after_obj and "dest" not in out and not re.match(rf"{_TABLE}|{_place_re(markers)}", t[m.start(1):]) \ if m.start() > after_obj and "dest" not in out and not re.match(rf"{_TABLE}|{_place_re(markers)}", t[m.start(1):]) \
and m.group(1) not in ("put", "place", "hold", "give", "keep", "bring", "leave"): and m.group(1) not in ("put", "place", "hold", "give", "keep", "bring", "leave"):
out["dest"] = None out["dest"] = None
if "dest" not in out and re.search(r"\b(bring|get|fetch|give) (it |that |this )?(to )?me\b|\bto me\b|가져와|가지고 ?와|갖고 ?와|갖다 ?줘|가져다 ?(?:줘|주세요|줄래)", t): tk = t + " | " + wording.ko_plain(t) if HANGUL.search(t) else t # "가져오십시오", "놓으세요" read as 반말 too
if "dest" not in out and re.search(r"\b(bring|get|fetch|give|grab) (it |that |this )?(to )?me\b|\bto me\b|가져와|가지고 ?와|갖고 ?와|갖다 ?줘|가져다 ?(?:줘|주세요|줄래)", tk):
out["dest"] = "here" out["dest"] = "here"
if "dest" not in out and (re.search(r"\b(?:bring|fetch)(?:ing)?\b", t) and isinstance(out.get("source"), dict) if "dest" not in out and (re.search(r"\b(?:bring|fetch)(?:ing)?\b", t) and isinstance(out.get("source"), dict)
and not re.search(r"\b(?:to|for) (?!me\b|us\b)\w", t) and not re.search(r"\b(?:to|for) (?!me\b|us\b)\w", t)
@@ -1800,8 +1873,9 @@ def _mentions(text, markers):
re.findall(r"([가-힣]+?)\s*(?:한테|에게|께)(?!서)", t))): re.findall(r"([가-힣]+?)\s*(?:한테|에게|께)(?!서)", t))):
out["dest"] = "here" # "fetch the cup from p2", "p2에서 컵 갖다 주시겠어요?": to the one who asks, not to out["dest"] = "here" # "fetch the cup from p2", "p2에서 컵 갖다 주시겠어요?": to the one who asks, not to
# "Minsu" ("민수한테 갖다 줘", "bring it to Minsu": a person is asked about) # "Minsu" ("민수한테 갖다 줘", "bring it to Minsu": a person is asked about)
if re.search(rf"\b(put|place|leave|set) (it|that|this|the \w+)\b.*\b(on|onto) (the )?({_TABLE})\b|\bplace\b" if re.search(rf"\b(put|place|leave|set) (it|that|this|the \w+)\b.*\b(on|onto) (the )?({_TABLE})\b|\bplace\b|{_PUT_AT_EN[:-1]}"
rf"|놔|놓아|놓고|둬", t): rf"|\b(?:put|set|leave) (?:it|that|this|the (?:\w+ )?\w+) down\b|\bleave (?:it|that|this) (?:there|on|at)\b"
rf"|놔|놓아|놓고|놓(?=을|으)|둬", tk):
out["finish"] = "place" out["finish"] = "place"
elif re.search(r"\b(just )?(hold|keep) (it|that|this|on to it|onto it)\b|\bhold\b|들고 ?(있어|기다려)", t): elif re.search(r"\b(just )?(hold|keep) (it|that|this|on to it|onto it)\b|\bhold\b|들고 ?(있어|기다려)", t):
out["finish"] = "hold" out["finish"] = "hold"
@@ -1864,9 +1938,22 @@ def place_problem(text, markers):
return f"Did you mean {place_said(close[0])}?", f"{place_said(close[0])} 말씀이세요?" return f"Did you mean {place_said(close[0])}?", f"{place_said(close[0])} 말씀이세요?"
if re.fullmatch(r"p\d+", word) and not close: if re.fullmatch(r"p\d+", word) and not close:
return no_place_say(word, markers) return no_place_say(word, markers)
for m in _GO_KO.finditer(_norm(text, markers)): # "출구로 가": a Korean word that is no marker (never
word = m.group(1) # translated into one: asked)
if len(word) > 1 and word not in _NOT_PLACE_KO and not re.search(r"(?:쪽|편|방향|자리|위치|곳|데|미터|센티|미리|바퀴|하러|한테|에게|께)$", word) and \
not re.fullmatch(_place_re(markers), word):
return no_place_say(word, markers, m.group(0).strip())
return None return None
_GO_KO = re.compile(r"(?<![가-힣a-z0-9_])([가-힣]+?)\s*(?:으로|(?<!으)로|까지)\s*(?:좀\s*)?(?:어서\s*)?(?:가(?![가-힣])|가서|가 ?줘|가요|가세요|"
r"가 ?주|가자|이동|돌아가|가져가|가지고 ?가|갖고 ?가|들고 ?가|와(?![가-힣])|와 ?줘|오세요)")
_NOT_PLACE_KO = {"앞", "뒤", "왼쪽", "오른쪽", "옆", "위", "아래", "이쪽", "저쪽", "그쪽", "여기", "저기", "거기", "이리", "저리", "집",
"홈", "제자리", "원래", "충전기", "충전소", "도크", "밖", "안", "가운데", "중앙", "정면", "처음", "나", "저", "너",
"사람", "그분", "저분", "손님", "천천히", "빨리", "조금", "똑바로", "직진", "후진", "반대로", "거꾸로", "다시",
"그대로", "이대로", "나한테", "저한테", "내게", "제게", "엄마", "아빠", "친구", "아까", "방금", "출발점", "시작점"}
def fetch_problems(task): def fetch_problems(task):
"""'object' / 'place' (source) / 'dest': what is still missing or unknown in a task.""" """'object' / 'place' (source) / 'dest': what is still missing or unknown in a task."""
return [p for p, f in (("object", "object"), ("place", "source"), ("dest", "dest")) if task.get(f) is None] return [p for p, f in (("object", "object"), ("place", "source"), ("dest", "dest")) if task.get(f) is None]
@@ -1945,7 +2032,7 @@ def spoken(sentence, lang):
HELD_GIVE = re.compile(r"\b(give|hand)\b|\bbring it\b|줘|주세요|건네", re.I) HELD_GIVE = re.compile(r"\b(give|hand)\b|\bbring it\b|줘|주세요|건네", re.I)
HELD_PLACE = re.compile(r"\b(put|place|set)\b|놔|놓|둬", re.I) HELD_PLACE = re.compile(r"\b(put|place|set)\b|\b(?:drop|leave) (?:it|that|this|the \w+)(?: off| down)? (?:at|on|by)\b|놔|놓|둬", re.I)
def fetch_from_text(text, markers=()): def fetch_from_text(text, markers=()):
@@ -2065,7 +2152,7 @@ def held_command(text):
it on wins ("bring it to p5 and put it on the table" is a place).""" it on wins ("bring it to p5 and put it on the table" is a place)."""
if HELD_PLACE.search(text) and place_on(text): if HELD_PLACE.search(text) and place_on(text):
return "place" return "place"
if HELD_GIVE.search(text): if HELD_GIVE.search(re.sub(r"(?:놔|놓아|둬|올려|내려|(?<![갖다])가|가져가|들고 가|옮겨|와|이동해)\s*(?:좀\s*|쫌\s*)?(?:줘|주|드려|드리)", "놔", text)): # "그거 놔 줘": 줘 helps the put
return "give" return "give"
if HELD_PLACE.search(text): if HELD_PLACE.search(text):
return "place" return "place"
@@ -2328,6 +2415,22 @@ def held_place(text, markers=()):
return bool(PLACE_HELD_EN.search(t) or PLACE_HELD_KO.search(t)) return bool(PLACE_HELD_EN.search(t) or PLACE_HELD_KO.search(t))
CARRY_HELD = re.compile(r"\b(?:take|bring|carry|move|get) (?:it|that|this|them|the \w+)(?: over| along)? (?:to|towards?) |"
r"\b(?:drop|leave|put|set) (?:it|that|this|them|the \w+)(?: off| down)? (?:at|by|near|on) |"
r"(?:으로|로|에|까지)\s*(?:좀\s*)?(?:가져가|가지고 ?가|갖고 ?가|들고 ?가|옮겨|가져다 ?놔|가 ?줘|가)", re.I)
def held_carry(text, markers=()):
"""With something in the hand: the words ask to take it to a marker ("take it to p5", "p5로 가져가 주세요",
"그거 p5로 옮겨 줘"); a direct order that names a place on this map."""
text = _MAY_NOT.sub(" 줘", text or "")
if not text or not_an_order(text) or held_back(text) or not direct_order(text):
return False
t = _norm(wording.ko_plain(text) if HANGUL.search(text) else text, markers)
return bool(CARRY_HELD.search(t) and any(_resolve(m, markers) not in (None, "here")
for m in re.finditer(_place_re(markers), t)))
def give_clause(text): def give_clause(text):
"""The words without a clause about the person it is for ("give it to him, he's going to Gate A3" -> "give it """The words without a clause about the person it is for ("give it to him, he's going to Gate A3" -> "give it
to him"): where that person goes is never where Lumi drives.""" to him"): where that person goes is never where Lumi drives."""
@@ -2448,7 +2551,9 @@ def hand_request(text, holding, b=None, markers=(), whole=True):
return None # "놔", "drop it" with the hand empty: open it (intent) return None # "놔", "drop it" with the hand empty: open it (intent)
if (PLACE_EN.search(t) or PLACE_KO.search(t)) and "팔" not in t and not re.fullmatch(r"\W*leave (?:it|that|this)\W*", t) and \ if (PLACE_EN.search(t) or PLACE_KO.search(t)) and "팔" not in t and not re.fullmatch(r"\W*leave (?:it|that|this)\W*", t) and \
not re.search(r"손\s*(?:을\s*)?(?:(?:좀|쫌|쪼까|쪼끔|조금|살짝|얼른|이제|다시|빨리|어서)\s*)*(?:내려|거둬)", t) and \ not re.search(r"손\s*(?:을\s*)?(?:(?:좀|쫌|쪼까|쪼끔|조금|살짝|얼른|이제|다시|빨리|어서)\s*)*(?:내려|거둬)", t) and \
not BODY_PART.search(t) and not re.search(r"\barms?\b", t): # "손쫌내려줘유", "you put down arm please" not BODY_PART.search(t) and not re.search(r"\barms?\b", t) and \
not re.search(r"(?:아래로|밑으로|위로)\s*(?:좀\s*|쫌\s*)?(?:내려|올려)(?!\s*(?:놔|놓|둬))", t): # "손쫌내려줘유", "you
# put down arm please"; "20cm 아래로 내려 줘": the lift
# not "팔 거둬" / "팔 내려" (the arm), not a bare "leave it" (never mind) # not "팔 거둬" / "팔 내려" (the arm), not a bare "leave it" (never mind)
if named and not holding: if named and not holding:
return None # "put the cup on the table": the put intent / a mission return None # "put the cup on the table": the put intent / a mission
@@ -2665,7 +2770,9 @@ FORCED_LANG = {} # {"lang": "en"|"ko"} set by lumi.py from the
def now_line(): def now_line():
"""The date and time for the prompt, also written the Korean way: with the English form alone the model """The date and time for the prompt, also written the Korean way: with the English form alone the model
said "10월 21일" on 20 October.""" said "10월 21일" on 20 October."""
return f"{web.now_text()} ({time.strftime('%Y년 %-m월 %-d일 %H시 %M분')})" t = time.localtime() # Korean the way it is said: "오후 10시 45분" (was "22시 45분" in replies)
return (f"{web.now_text()} ({t.tm_year}년 {t.tm_mon}월 {t.tm_mday}일 {'월화수목금토일'[t.tm_wday]}요일 "
f"{'오전' if t.tm_hour < 12 else '오후'} {t.tm_hour % 12 or 12}시 {t.tm_min}분)")
def reply_language(text): def reply_language(text):
@@ -2873,6 +2980,12 @@ _PRONOUN_KO = r"그거|이거|저거|그것|이것|저것|거기|여기|저기|
OWN_SUBJECT = re.compile(rf"(?<=\S )(?!I\b|Lumi\b|OK\b|Okay\b)[A-Z][a-z]+|(?<![가-힣A-Za-z])(?!(?:{_PRONOUN_KO})(?:은|는|이|가)(?![가-힣]))" OWN_SUBJECT = re.compile(rf"(?<=\S )(?!I\b|Lumi\b|OK\b|Okay\b)[A-Z][a-z]+|(?<![가-힣A-Za-z])(?!(?:{_PRONOUN_KO})(?:은|는|이|가)(?![가-힣]))"
r"[가-힣A-Za-z]{2,}(?:은|는|이|가)(?=[\s?!.~,]|요|$)") r"[가-힣A-Za-z]{2,}(?:은|는|이|가)(?=[\s?!.~,]|요|$)")
# a short question that names its own subject ("BTS는 언제 데뷔했어요?", "Who was Sejong?") # a short question that names its own subject ("BTS는 언제 데뷔했어요?", "Who was Sejong?")
NOT_SUBJECT_KO = re.compile(r"(?:으로|적으로|에서|에|까지|부터|보다|한테|에게)는$")
# "공식적으로는", "옛날에는", "서울에서는": a time / place / manner, not the subject
WHAT_IS = re.compile(r"(?:뭐|무엇|뭔|머)(?:예요|에요|야|이야|입니까|인가요|이에요|가요|죠|지|냐|고|여|임|래요|래)?\W*$|"
r"^\W*what(?:'s| is| are| does)\b", re.I) # "X는 뭐예요?", "What is X?": a definition
THAT_ONE_KO = re.compile(rf"(?<![가-힣A-Za-z])(?!(?:{_PRONOUN_KO})\s)([가-힣A-Za-z]{{2,}})\s+(?:그거|그게|그건|이거|이게|이건|저거|저게|저건)")
# "경복궁 그거 언제 지었노?": the palace is the subject (said without 은 / 는)
EN_SUBJECT = re.compile(r"\b(?i:do|does|did|can|could|are|is|were|was|will|would)\s+(?:the\s+|an?\s+)?" EN_SUBJECT = re.compile(r"\b(?i:do|does|did|can|could|are|is|were|was|will|would)\s+(?:the\s+|an?\s+)?"
r"(?!(?:you|i|we|they|he|she|it|people|there|this|that|these|those|your|my|our|me|not|so|very)\b)" r"(?!(?:you|i|we|they|he|she|it|people|there|this|that|these|those|your|my|our|me|not|so|very)\b)"
r"([a-z]{3,})\b") # "Why do whales sing?": the whales (world_talk; lower case, so not OWN_SUBJECT) r"([a-z]{3,})\b") # "Why do whales sing?": the whales (world_talk; lower case, so not OWN_SUBJECT)
@@ -2979,12 +3092,15 @@ class Brain:
elif follow and about_answer(text) and len(hits) > 1: # "really?" / "why?": the answer is in the talk, its elif follow and about_answer(text) and len(hits) > 1: # "really?" / "why?": the answer is in the talk, its
notes = _notes(hits[:1]) # reason in the best chunk (~200 tokens less, ~0.25 s) notes = _notes(hits[:1]) # reason in the best chunk (~200 tokens less, ~0.25 s)
elif world: # "부엉이는 고개를 몇 도까지 돌려요?": notes on Lumi's own head elif world: # "부엉이는 고개를 몇 도까지 돌려요?": notes on Lumi's own head
notes = "(none needed: not about you)" # turned the owl into Lumi ("제 고개는 180도까지") notes = "(none needed: general knowledge, not about you)" # turned the owl into Lumi ("제 고개는 180도까지")
if len(world) > 1: # "심장은 몇 개고?" after the octopus: the octopus's hearts if len(world) > 1: # "심장은 몇 개고?" after the octopus: the octopus's hearts
world = [f"{world[0]} (its {', '.join(world[1:])}, when that is a part or a kind of it)"] world = [f"{world[0]} (its {', '.join(world[1:])}, when that is a part or a kind of it)"]
world = (f"(This is about {', '.join(world)}, not about you: never answer it with your own head, eyes, arms or " world = (f"(This is about {', '.join(world)}, not about you: never answer it with your own head, eyes, arms or "
f"body.)\n") if world else "" # "부엉이 목 그거 을매나 돌아가노?" got "제 머리는 180도까지" with no notes f"body. What stays the same (what it is, how or why, who made it, its history) you answer yourself at "
messages.append({"role": "user", "content": f"Reference notes:\n{notes}\n\n{_examples(about, k=2 if follow else None, on_task=bool(now) and 'not doing any task' not in now)}" f"once, ACTION none; search only what changes: news, prices, scores, who holds an office now.)\n"
) if world else "" # "부엉이 목 그거 을매나 돌아가노?" got "제 머리는 180도까지" with no notes;
# without the second sentence "윤초는 뭐예요?" was searched
messages.append({"role": "user", "content": f"Reference notes:\n{notes}\n\n{_examples(about, k=2 if follow else None, on_task=bool(now) and 'not doing any task' not in now, world=bool(world))}"
f"{follow}" f"{follow}"
f"Now it is {now_line()}.\n\n" + memory.turn_lines(self, text) + f"Now it is {now_line()}.\n\n" + memory.turn_lines(self, text) +
f"Visitor: {text}\n\n" + self._fragment_hint(text) + world + f"Visitor: {text}\n\n" + self._fragment_hint(text) + world +
@@ -3140,10 +3256,13 @@ class Brain:
"""The words (or the question they follow) name a subject of their own that is not Lumi, its parts or the """The words (or the question they follow) name a subject of their own that is not Lumi, its parts or the
companies ("부엉이는 ...?", "How high is Mount Fuji?"): Lumi's notes are left out. A subject that is one of companies ("부엉이는 ...?", "How high is Mount Fuji?"): Lumi's notes are left out. A subject that is one of
Lumi's own things ("속도는 얼마예요?", "이름이 뭐예요?") keeps them. Returns those subjects, the question before first ([] when none).""" Lumi's own things ("속도는 얼마예요?", "이름이 뭐예요?") keeps them. Returns those subjects, the question before first ([] when none)."""
def named(t): def named(t): # "공식적으로는 언제로 쳐요?" names no subject (an adverb + 는)
return [m.group(0) for m in OWN_SUBJECT.finditer(core(t))] + [m.group(1) for m in EN_SUBJECT.finditer(core(t))] return [m.group(0) for m in OWN_SUBJECT.finditer(core(t)) if not NOT_SUBJECT_KO.search(m.group(0))] + \
[m.group(1) for m in EN_SUBJECT.finditer(core(t))] + [m.group(1) for m in THAT_ONE_KO.finditer(core(t))]
qs = [topic_turn(self.history)[0]] + [h[0] for h in reversed(self.history[-3:])] if self.history else [""] qs = [topic_turn(self.history)[0]] + [h[0] for h in reversed(self.history[-3:])] if self.history else [""]
q = next((x for x in qs if named(x)), qs[0]) # "문어 피는?" "왜?" "심장은?": the octopus, two turns back q = next((x for x in qs if named(x)), qs[0]) # "문어 피는?" "왜?" "심장은?": the octopus, two turns back
if named(text) and WHAT_IS.search(core(text)):
q = "" # "윤초는 뭐예요?" after a birthday: a new subject, alone
both = re.sub(r"(?<=[A-Za-z])(?=[가-힣])", " ", f"{text} {q}") # "Gemma는": the word for LUMI_TOPIC both = re.sub(r"(?<=[A-Za-z])(?=[가-힣])", " ", f"{text} {q}") # "Gemma는": the word for LUMI_TOPIC
if LUMI_TOPIC.search(both) or COMPANY_TALK.search(both): if LUMI_TOPIC.search(both) or COMPANY_TALK.search(both):
return [] return []
@@ -3252,8 +3371,9 @@ class Brain:
if (LOOKUP_MORE.search(text) or FOLLOW_UP.search(text) or AND_ALSO.match(text) or REPAIR.search(text) or if (LOOKUP_MORE.search(text) or FOLLOW_UP.search(text) or AND_ALSO.match(text) or REPAIR.search(text) or
SHORT_Q.search(text) and len(text.split()) <= 6) \ SHORT_Q.search(text) and len(text.split()) <= 6) \
and not re.search(r"cutshion|쿳션", text, re.I) and not ABOUT_YOU.search(text) \ and not re.search(r"cutshion|쿳션", text, re.I) and not ABOUT_YOU.search(text) \
and not NOW_Q.search(text): # "Where?", "몇 살이야?", "who's the CEO?" after a lookup and not NOW_Q.search(text) and not (WHAT_IS.search(core(text)) and OWN_SUBJECT.search(core(text))):
return {"action": "search", "target": f"{last_q} {text}"} return {"action": "search", "target": f"{last_q} {text}"} # "Where?", "몇 살이야?", "who's the CEO?" after a
# lookup; "윤초는 뭐예요?" names its own subject: the model's
return header return header
def _redo(self, text): def _redo(self, text):
+10 -2
View File
@@ -57,12 +57,15 @@ def _restated(words, before):
if not said or len(said) > 3 or not re.fullmatch(r"[가-힣]{2,}|[가와]", said[-1]): if not said or len(said) > 3 or not re.fullmatch(r"[가-힣]{2,}|[가와]", said[-1]):
return False return False
last = said[-1] last = said[-1]
return any(last == w or len(w) > 1 and (w.startswith(last) or last.startswith(w)) return any(last == w or len(w) > 1 and len(last) > 1 and (w.startswith(last) or last.startswith(w)) # "가" is no "가지고"
for w in re.findall(r"\w+", wording.ko_plain(before)) if re.fullmatch(r"[가-힣]+", w)) for w in re.findall(r"\w+", wording.ko_plain(before)) if re.fullmatch(r"[가-힣]+", w))
def _rule(words, markers): def _rule(words, markers):
"""brain.intent of a part, also of a Korean -고 form ("나 보고" read as "나 봐").""" """brain.intent of a part, also of a Korean -고 form ("나 보고" read as "나 봐")."""
words = re.sub(r"^\W*(?:first(?:ly)?|then|next|after that|and then|and|lastly|finally|먼저|그다음에?|그리고)\W+", "", words,
flags=re.I) or words # "first look me, then follow me"
words = re.sub(r"\blook me\b", "look at me", words, flags=re.I)
rule = brain.intent(words, markers) rule = brain.intent(words, markers)
ko = _KO_AND.sub(lambda m: _KO_ORDER[m.group(1)], words.strip()) ko = _KO_AND.sub(lambda m: _KO_ORDER[m.group(1)], words.strip())
if not rule and ko != words.strip(): if not rule and ko != words.strip():
@@ -95,6 +98,10 @@ def parts(text):
return [p for p in out if p and not re.fullmatch(rf"(?:{_FILL.pattern}|\W)+", p, re.I)] return [p for p in out if p and not re.fullmatch(rf"(?:{_FILL.pattern}|\W)+", p, re.I)]
CALL_ONLY = re.compile(r"\W*(?:(?:excuse me|hey|hi|hello|yo|okay|ok|lumi|robot|buddy|루미 ?씨|루미야?|로봇아?|야|어이|저기요?|"
r"이보게)\W*)+", re.I)
def plan(text, markers=(), cant=None): def plan(text, markers=(), cant=None):
"""See the module's doc. cant: a regex of orders Lumi can't do ("dance", "jump"): answered, the rest done.""" """See the module's doc. cant: a regex of orders Lumi can't do ("dance", "jump"): answered, the rest done."""
from assistant import intent_bank from assistant import intent_bank
@@ -113,7 +120,8 @@ def plan(text, markers=(), cant=None):
return None # "turn around and look": the head looks behind return None # "turn around and look": the head looks behind
out = [] out = []
for p in ps: for p in ps:
if SELF_PROMISE.search(p) or out and _restated(p, out[-1][1]) or brain.GREET_ONLY.match(p): # "hello robot, …" if SELF_PROMISE.search(p) or out and _restated(p, out[-1][1]) or brain.GREET_ONLY.match(p) or CALL_ONLY.fullmatch(p):
# "hello robot, …", "야 루미, …", "excuse me robot, …": the call, no part
continue # "흰색 머그컵 잡아!, 아 잡아 줄 수 있어요?": the order once continue # "흰색 머그컵 잡아!, 아 잡아 줄 수 있어요?": the order once
got, unread = steps.rules(p, markers) got, unread = steps.rules(p, markers)
rule = _rule(p, markers) rule = _rule(p, markers)
+37 -14
View File
@@ -63,7 +63,8 @@ NOT_TO_LUMI = re.compile(
r"are asked|are requested)\b|\bare (?:kindly )?(?:asked|requested) to\b|안내 ?말씀|(?<![가-힣])여러분(?!한테|에게|께)|" r"are asked|are requested)\b|\bare (?:kindly )?(?:asked|requested) to\b|안내 ?말씀|(?<![가-힣])여러분(?!한테|에게|께)|"
r"관람객|방문객|승객|" # announcements r"관람객|방문객|승객|" # announcements
r"\bso (?:well|nicely|smoothly|fast|good)\b|\b(?:really|very) (?:well|nicely|smoothly)\b|\bthe way you\b|" r"\bso (?:well|nicely|smoothly|fast|good)\b|\b(?:really|very) (?:well|nicely|smoothly)\b|\bthe way you\b|"
r"\blove how\b|[가-힣](?:네|네요|구나|군요|더라|던데)\s*[!.~]*$|[가-힣](?<!니)다\s*[!.~]*$", re.I) r"\blove how\b|[가-힣](?:네|네요|구나|군요|더라|던데)\s*[!.~]*$|[가-힣](?<!니)다\s*[!.~]*$|"
r"(?:좋|멋지|예쁘|이쁘|귀엽|크|작|길|세|대단하|신기하|웃기)(?:네|네요|구나|군요)(?=[\s,.!~])", re.I)
# plans, hypotheticals, announcements, praise and remarks: nobody asked Lumi to do anything now # plans, hypotheticals, announcements, praise and remarks: nobody asked Lumi to do anything now
QUESTION = re.compile(r"^\W*(?:(?:hey|so|um+|uh+|lumi|okay|ok)\W+)*(?:what|where|why|how|when|who|whose|which|is|are|was|" QUESTION = re.compile(r"^\W*(?:(?:hey|so|um+|uh+|lumi|okay|ok)\W+)*(?:what|where|why|how|when|who|whose|which|is|are|was|"
r"were|do(?=\s+(?:you|i|we|they|robots?)\b)|does|did|have|has|had|should|shall i|may i|can i|could i)\b(?! about\b)|" r"were|do(?=\s+(?:you|i|we|they|robots?)\b)|does|did|have|has|had|should|shall i|may i|can i|could i)\b(?! about\b)|"
@@ -89,6 +90,9 @@ SEVERAL = re.compile(r"\b(?<!hundred )and\b(?! a half\b)|\bwait\w*|\bcorrection\
# several requests or a stay ("go to p3 and wait", "가서 기다려", "p3에 가 있어"): steps.read's # several requests or a stay ("go to p3 and wait", "가서 기다려", "p3에 가 있어"): steps.read's
HAND_WORDS = re.compile(r"\byou(?:'re| are) holding\b|\b(?:in|from) my hand\b|\bhere'?s\b|\bhanding\b|\bi'?ll give\b|" HAND_WORDS = re.compile(r"\byou(?:'re| are) holding\b|\b(?:in|from) my hand\b|\bhere'?s\b|\bhanding\b|\bi'?ll give\b|"
r"\bhold this\b|\bfrom me\b|\bmy hand\b|\bhand ?에|\bhand it (?:over|to me)\b|\bhand over\b|내 손|제 손|손에 ?(?:줘|놔|주세요|쥐어)|\bi'?m holding\b|\bi am holding\b|들고 있는|손에 있는|받아|드릴게|줄게|가져가세요", re.I) # the hand reader's (brain.hand_request) r"\bhold this\b|\bfrom me\b|\bmy hand\b|\bhand ?에|\bhand it (?:over|to me)\b|\bhand over\b|내 손|제 손|손에 ?(?:줘|놔|주세요|쥐어)|\bi'?m holding\b|\bi am holding\b|들고 있는|손에 있는|받아|드릴게|줄게|가져가세요", re.I) # the hand reader's (brain.hand_request)
GROUP_CALL = re.compile(r"(?:^|[,:;.!?]\s*)(?:(?:hey|ok|okay|alright|so|come on)\s+)?(?:(?:you )?guys|folks|y'?all|"
r"you all|everyone|everybody|team|kids|people|ladies|gentlemen)\s*(?:[,:;!.]|$)|"
r"얘들아|애들아|친구들아|여러분[,\s]", re.I) # "guys, get me the bottle": said to the people around
NAME_CALL = re.compile(r"^\W*(?:(?:ah|oh|hey|hi|okay|ok|so|um|uh|look|and)\W+)?([A-Z][a-z]+)\s*,") # "Jake, follow me": said to Jake NAME_CALL = re.compile(r"^\W*(?:(?:ah|oh|hey|hi|okay|ok|so|um|uh|look|and)\W+)?([A-Z][a-z]+)\s*,") # "Jake, follow me": said to Jake
NOT_A_NAME = {"lumi", "loomi", "rumi", "okay", "ok", "please", "hey", "hi", "hello", "so", "well", "now", "alright", NOT_A_NAME = {"lumi", "loomi", "rumi", "okay", "ok", "please", "hey", "hi", "hello", "so", "well", "now", "alright",
"yes", "yeah", "no", "sorry", "um", "uh", "oh", "wait", "look", "then", "first", "also", "and", "but", "yes", "yeah", "no", "sorry", "um", "uh", "oh", "wait", "look", "then", "first", "also", "and", "but",
@@ -750,7 +754,7 @@ def guarded(text):
return "length" return "length"
for name, rx in (("negation", NEGATION), ("later", LATER), ("ability", ABILITY), ("question", QUESTION), for name, rx in (("negation", NEGATION), ("later", LATER), ("ability", ABILITY), ("question", QUESTION),
("self", SELF_TALK), ("several", SEVERAL), ("hand", HAND_WORDS), ("other sense", OTHER_SENSE), ("self", SELF_TALK), ("several", SEVERAL), ("hand", HAND_WORDS), ("other sense", OTHER_SENSE),
("repeat", REPEAT), ("past", PAST_EN), ("tag", TAG), ("wonder", WONDER), ("not to lumi", NOT_TO_LUMI)): ("repeat", REPEAT), ("group", GROUP_CALL), ("past", PAST_EN), ("tag", TAG), ("wonder", WONDER), ("not to lumi", NOT_TO_LUMI)):
if rx.search(t): if rx.search(t):
return name return name
if brain.LATER.search(t): if brain.LATER.search(t):
@@ -859,6 +863,7 @@ CARRY = (r"\b(?:bring(?! yourself)|fetch|deliver|carry)\b|\bget me\b|\b(?:to|for
COME_SAID = (r"\bcome\b|\bcum\b|\bkum\b|\bget over\b|\bapproach|\bcloser\b|\bhither\b|\bnear me\b|" COME_SAID = (r"\bcome\b|\bcum\b|\bkum\b|\bget over\b|\bapproach|\bcloser\b|\bhither\b|\bnear me\b|"
r"\bget closer\b|\broll over\b|\bdrive over\b|\bmy side\b|\bnext to me\b|\bto me\b|와|오세요|오십시오|오시|올래|" r"\bget closer\b|\broll over\b|\bdrive over\b|\bmy side\b|\bnext to me\b|\bto me\b|와|오세요|오십시오|오시|올래|"
r"(?<![가-힣])컴(?= ?히어|(?![가-힣]))") # Konglish "컴 히어 해 줘", "이리 컴" r"(?<![가-힣])컴(?= ?히어|(?![가-힣]))") # Konglish "컴 히어 해 줘", "이리 컴"
HOME_SAID = r"\b(?:home|dock|charger|charging)\b|집|충전|도크|홈" # brain.named_place also reads a bare "go back" as home
LIFT_SAID_MAX_M = 0.3 # m; a longer lift amount said is no lift request ("grow to three meters tall") LIFT_SAID_MAX_M = 0.3 # m; a longer lift amount said is no lift request ("grow to three meters tall")
LIFT_BODY = (r"\b(?:yourself|your (?:body|torso|upper body)|body|make you|taller|shorter|smaller|small|tall|high|lift|rise|grow|" LIFT_BODY = (r"\b(?:yourself|your (?:body|torso|upper body)|body|make you|taller|shorter|smaller|small|tall|high|lift|rise|grow|"
r"shrink|come down|go up|go down|move up|move down|raise up|lower down|come up|sink down|elevate|squat|height|" r"shrink|come down|go up|go down|move up|move down|raise up|lower down|come up|sink down|elevate|squat|height|"
@@ -867,13 +872,13 @@ LIFT_BODY = (r"\b(?:yourself|your (?:body|torso|upper body)|body|make you|taller
MOVE_VERB = (r"\b(?:move|go|step|back up|backup|scoot|slide|shift|drive|roll|reverse|inch|come|forward|backward|ahead|" MOVE_VERB = (r"\b(?:move|go|step|back up|backup|scoot|slide|shift|drive|roll|reverse|inch|come|forward|backward|ahead|"
r"moov|moove|bak)|가|이동|물러|비켜|후진|와|빠져|걸음|발짝|move|back|go") # a bare "왼쪽으로" may be a look r"moov|moove|bak)|가|이동|움직|물러|비켜|후진|와|빠져|걸음|발짝|move|back|go") # a bare "왼쪽으로" may be a look
LOOK_DIR = {"left": r"\bleft|왼|레프트|(?:^|\s)좌로|좌측", "right": r"\bright|\brite\b|오른|라이트|(?:^|\s)우로|우측", LOOK_DIR = {"left": r"\bleft|왼|레프트|(?:^|\s)좌로|좌측", "right": r"\bright|\brite\b|오른|라이트|(?:^|\s)우로|우측",
"up": r"\bup|\bupward|\bceiling|\bsky\b|\bhigher\b|천장|하늘|(?<!원)위", "down": r"\bdown|\bfloor|\bground|\bfeet\b|바닥|땅|아래|밑"} "up": r"\bup|\bupward|\bceiling|\bsky\b|\bhigher\b|천장|하늘|(?<!원)위", "down": r"\bdown|\bfloor|\bground|\bfeet\b|바닥|땅|아래|밑"}
LOOK_ME = (r"\b(?:at|on|to|toward|towards) (?:me|us|나)\b|\bthis way\b|\bover here\b|\bmy way\b|\bhere\b|\bwatch me\b|" LOOK_ME = (r"\b(?:at|on|to|toward|towards) (?:me|us|나)\b|\bthis way\b|\bover here\b|\bmy way\b|\bhere\b|\bwatch me\b|"
r"\bme in the eye|\bmy face\b|나한테|저한테|쳐다봐|(?:^|\s)(?:여기|이쪽|저|나|날|절)(?:를|을)?\s*(?:(?:좀|한 ?번|잠깐|잠시|다시)\s*)*(?:바라|쳐다)?(?:봐|보세요|look)") r"\bme in the eye|\bmy face\b|(?:제|내) 얼굴|나한테|저한테|쳐다봐|(?:^|\s)(?:여기|이쪽|저|나|날|절)(?:를|을)?\s*(?:(?:좀|한 ?번|잠깐|잠시|다시)\s*)*(?:바라|쳐다)?(?:봐|보세요|look)")
EN_NUM = {w: i for i, w in enumerate("zero one two three four five six seven eight nine ten eleven twelve thirteen " EN_NUM = {w: i for i, w in enumerate("zero one two three four five six seven eight nine ten eleven twelve thirteen "
@@ -1016,7 +1021,8 @@ def _slot(kind, text, markers, holding):
not re.search(rf"(?<![a-z0-9]){re.escape(named[0].lower())}(?![0-9])", said): not re.search(rf"(?<![a-z0-9]){re.escape(named[0].lower())}(?![0-9])", said):
return None # "exit a" with only Exit_B, "booth 13" with Booth_12: asked return None # "exit a" with only Exit_B, "booth 13" with Booth_12: asked
return ("go_to", named[0]) return ("go_to", named[0])
if kind == "come" and (re.search(CARRY + r"|따라", t) or not re.search(COME_SAID, t)): if kind == "come" and (re.search(CARRY + r"|따라|\bover there\b|\bpoint(?:ing|ed)?\b|\bthat way\b|저기|저쪽|거기|가리키", t) or
not re.search(COME_SAID, t)):
return None # "나한테 가져와", "이리 줘": not a trip to the person return None # "나한테 가져와", "이리 줘": not a trip to the person
if kind == "come" and re.search(r"\bwith (?:me|us)\b|함께|같이", t): if kind == "come" and re.search(r"\bwith (?:me|us)\b|함께|같이", t):
return ("follow", "") # "just come with me": walk along return ("follow", "") # "just come with me": walk along
@@ -1024,9 +1030,10 @@ def _slot(kind, text, markers, holding):
n, exact = driving.amount(t) # drive (A2) n, exact = driving.amount(t) # drive (A2)
return ("move", f"forward {n:g}") if exact and driving.MOVE_MIN_M <= n <= brain.MOVE_MAX_M else None return ("move", f"forward {n:g}") if exact and driving.MOVE_MIN_M <= n <= brain.MOVE_MAX_M else None
if kind == "come_back" and (re.search(r"\bpose\b|\barm\b|\bhead\b|팔|고개|\bpick|\bput\b|\bit\b|그거|놓|놔", t) or if kind == "come_back" and (re.search(r"\bpose\b|\barm\b|\bhead\b|팔|고개|\bpick|\bput\b|\bit\b|그거|놓|놔", t) or
any(brain.named_place(text, m, markers) for m in markers)): any(brain.named_place(text, m, markers) for m in markers
if m != "home" or re.search(HOME_SAID, t))):
return None # "go back to your dock", "go back to your look pose": not here return None # "go back to your dock", "go back to your look pose": not here
if kind == "come_back" and re.search(r"\bhere\b|\bto me\b|이리|여기|나한테|저한테", t): if kind == "come_back" and re.search(r"\b(?:back|over|right|come|get) here\b|\bto me\b|이리|여기|나한테|저한테", t):
return ("come", "") # "come back here": to the person, not to the old spot return ("come", "") # "come back here": to the person, not to the old spot
if kind == "follow" and (re.search(r"\bfollow (?:you|him|her|them|it|that)\b", t) or not re.search(FOLLOW_WORD, t)): if kind == "follow" and (re.search(r"\bfollow (?:you|him|her|them|it|that)\b", t) or not re.search(FOLLOW_WORD, t)):
return None # "follow you": not "follow me"; "가자 이제": let's go, where? return None # "follow you": not "follow me"; "가자 이제": let's go, where?
@@ -1062,7 +1069,7 @@ def _slot(kind, text, markers, holding):
not re.search(r"\bface\b|\bother (?:side|way)\b|\d+\s*(?:degrees?|도)", t.replace("360", "")) and \ not re.search(r"\bface\b|\bother (?:side|way)\b|\d+\s*(?:degrees?|도)", t.replace("360", "")) and \
said_amount(text)[1] in (None, 360): said_amount(text)[1] in (None, 360):
return ("turn", ("right" if re.search(r"\bright\b|오른쪽", t) else "left") + " 360") return ("turn", ("right" if re.search(r"\bright\b|오른쪽", t) else "left") + " 360")
if re.search(r"\baround\b|\bu-?turn\b|유턴|뒤로 (?:(?:좀|한 ?번|얼른|빨리)\s*)?돌|뒤돌|\bother way\b|\babout face\b|한 바퀴", t): if re.search(r"\baround\b|\bu-?turn\b|유턴|뒤로 (?:(?:좀|한 ?번|얼른|빨리)\s*)?(?:돌|회전)|뒤돌|\bother way\b|\babout face\b|한 바퀴", t):
return None if re.search(r"\bleft|\bright\b|왼|오른", t) else ("turn", "around 180") return None if re.search(r"\bleft|\bright\b|왼|오른", t) else ("turn", "around 180")
d = [x for x in _dirs(t) if x in ("left", "right")] d = [x for x in _dirs(t) if x in ("left", "right")]
if not d and said_amount(text)[1] == 180: if not d and said_amount(text)[1] == 180:
@@ -1130,8 +1137,9 @@ def _slot(kind, text, markers, holding):
r"\b(?:throw|toss|kick|break|eat|drink|wash|clean|buy|sell|" r"\b(?:throw|toss|kick|break|eat|drink|wash|clean|buy|sell|"
r"put|place|set|drop|leave|this|hold (?:this|my|it|on)|my)\b|놔|놓|내려", t) or \ r"put|place|set|drop|leave|this|hold (?:this|my|it|on)|my)\b|놔|놓|내려", t) or \
not re.search(CARRY, t) and re.search(r"\bfrom\b|\bgo get\b|에서", t) or \ not re.search(CARRY, t) and re.search(r"\bfrom\b|\bgo get\b|에서", t) or \
(holding() if callable(holding) else holding): (holding() if callable(holding) else holding) or re.search(r"\breturn\b|돌려|반납|반환", t):
return None # "put the banana on the table", "hold this apple": the hand's return None # "put the banana on the table", "hold this apple": the hand's;
# "return the cup", "컵 돌려줘": give back, not a pick
if re.search(r"\b(?:give|hand|pass)\b|건네", t) or \ if re.search(r"\b(?:give|hand|pass)\b|건네", t) or \
re.search(r"줘|주세요|주실|줄래", t) and not re.search(r"집|잡|들어|쥐|픽|pick|grab|take|" + CARRY, t): re.search(r"줘|주세요|주실|줄래", t) and not re.search(r"집|잡|들어|쥐|픽|pick|grab|take|" + CARRY, t):
return None # "컵 좀 줘": bring it to me, a mission (pick, then give) return None # "컵 좀 줘": bring it to me, a mission (pick, then give)
@@ -1142,8 +1150,11 @@ def _slot(kind, text, markers, holding):
return None # "from the cafeteria" (not on the map), "go home, bring it": asked return None # "from the cafeteria" (not on the map), "go home, bring it": asked
return ("fetch", text) return ("fetch", text)
if got.get("source") or got.get("dest") or any(brain.named_place(text, m, markers) for m in markers) or \ if got.get("source") or got.get("dest") or any(brain.named_place(text, m, markers) for m in markers) or \
re.search(r"\b(?:to|at|ask|tell|say|pass\w*|want|need|is on|are on)\b|있는|옮겨|에게|한테|께", t): re.search(r"\b(?:to|at|ask|tell|say|pass\w*|want|need|is on|are on)\b|(?<!테이블에 )(?<!위에 )(?<!저기 )"
return None # "take the cup to p4", "I want the mug, the one at the entrance" r"(?<!거기 )(?<!^)있는|옮겨|에게|한테|께", t) or got.get("prefer"):
return None # a side or size said ("왼쪽 컵", "the smaller one"): the
# quick pick takes none, the rules / LLM read it;
# "take the cup to p4", "I want the mug, the one at the entrance"
return ("pick", f"{got['colour']} {got['object']}" if got.get("colour") else got["object"]) return ("pick", f"{got['colour']} {got['object']}" if got.get("colour") else got["object"])
if kind == "put": if kind == "put":
if not (holding() if callable(holding) else holding): if not (holding() if callable(holding) else holding):
@@ -1174,7 +1185,7 @@ def read(text, markers=(), holding=False):
return ("fetch", said) if got and got[0] == "fetch" else got return ("fetch", said) if got and got[0] == "fetch" else got
PICK_VERB = re.compile(r"집|잡|들어|들고|가져|갖다|챙겨|\b(?:pick|grab|take|get|fetch|bring|hold)\b", re.I) PICK_VERB = re.compile(r"집|잡|들어|들고|가져|갖다|갖고|챙겨|픽업|\b(?:pick|grab|take|get|fetch|bring|hold)\b", re.I)
LOOK_VERB = re.compile(r"봐|보세|쳐다|바라|\b(?:look|see|watch)\b", re.I) LOOK_VERB = re.compile(r"봐|보세|쳐다|바라|\b(?:look|see|watch)\b", re.I)
PUT_VERB = re.compile(r"놓|놔|둬|두|내려|\b(?:put|place|drop|set|leave)\b", re.I) PUT_VERB = re.compile(r"놓|놔|둬|두|내려|\b(?:put|place|drop|set|leave)\b", re.I)
BACK_VERB = re.compile(r"돌아|복귀|컴백|리턴|가|와|\b(?:return|go|come|head|back)\b", re.I) BACK_VERB = re.compile(r"돌아|복귀|컴백|리턴|가|와|\b(?:return|go|come|head|back)\b", re.I)
@@ -1198,6 +1209,13 @@ def _verb_conflict(kind, text, holding):
return True # "라이트로 살짝 가 줘": a drive return True # "라이트로 살짝 가 줘": a drive
if kind == "arm_reach" and (HAND_SHAPE.search(text) or COME_VERB.search(text) and not ARM_WORD.search(text)): if kind == "arm_reach" and (HAND_SHAPE.search(text) or COME_VERB.search(text) and not ARM_WORD.search(text)):
return True # "손 펴 주시겠어요" (open), "할머니한테 와 줘" (come) return True # "손 펴 주시겠어요" (open), "할머니한테 와 줘" (come)
if kind == "look" and re.search(r"\bcome\b(?! on\b)|오세요|오십시오|(?<![가-힣])와(?: ?줘| ?주|\s|$)", text, re.I) and \
not HEAD_WORD.search(text):
return True # "I'd love to see you come this way": come, not a look
if kind in ("arm_reach", "arm_fold") and BODY_WORD.search(text) and not ARM_WORD.search(text):
return True # "you must straighten your waist": the waist, not the arm
if kind == "arm_open" and not OPEN_WORD.search(text) or kind == "arm_close" and not CLOSE_WORD.search(text):
return True # "grip immediately": no open word, no gripper opening
if kind == "wave" and not WAVE_VERB.search(text): if kind == "wave" and not WAVE_VERB.search(text):
return True # "손 벌려 줘", "손 쥐어 빨리", "손 좀 주이소" return True # "손 벌려 줘", "손 쥐어 빨리", "손 좀 주이소"
return holding and kind in ("arm_open", "arm_fold", "arm_reach", "arm_close") return holding and kind in ("arm_open", "arm_fold", "arm_reach", "arm_close")
@@ -1209,7 +1227,12 @@ GO_VERB = re.compile(r"(?<![가-힣])가(?: ?줘| ?주|$|\s)|이동|움직|무
HAND_SHAPE = re.compile(r"펴|펼|쥐|주먹|넣|접|내려|오므|놔|놓|\b(?:open|close|fist|tuck|fold|lower)\b", re.I) HAND_SHAPE = re.compile(r"펴|펼|쥐|주먹|넣|접|내려|오므|놔|놓|\b(?:open|close|fist|tuck|fold|lower)\b", re.I)
COME_VERB = re.compile(r"(?<![가-힣])와(?![가-힣])|와 ?(?:줘|주)|오세요|오십시오|\bcome\b", re.I) COME_VERB = re.compile(r"(?<![가-힣])와(?![가-힣])|와 ?(?:줘|주)|오세요|오십시오|\bcome\b", re.I)
ARM_WORD = re.compile(r"손|팔|\b(?:hand|arm)\b", re.I) ARM_WORD = re.compile(r"손|팔|\b(?:hand|arm)\b", re.I)
WAVE_VERB = re.compile(r"흔들|흔드|악수|인사|빠이|바이|웨이브|하이|\b(?:wave|waving|hello|hi|hey|shake|greet|bye)\b", re.I) WAVE_VERB = re.compile(r"흔들|흔드|악수|인사|빠이|바이|웨이브|하이|\b(?:wave|waving|hello|hi|hey|shake|greet|bye)\b|"
r"handshake|shaking|goodbye", re.I)
OPEN_WORD = re.compile(r"펴|펼|벌려|벌리|열|오픈|풀어|놔|놓|\b(?:open|release|let go|loosen|unclench|spread|relax|widen|"
r"opn|apart)", re.I)
CLOSE_WORD = re.compile(r"쥐|닫|오므|모아|모으|주먹|클로즈|꽉|잡|\b(?:close|clos|shut|grip|clench|fist|squeeze|tighten|grasp|curl|"
r"pinch|together)", re.I)
if __name__ == "__main__": if __name__ == "__main__":
+5 -4
View File
@@ -134,7 +134,8 @@ WAKE = re.compile(rf"\b(hi|hey|hello|okay|ok|hai|high|{WAKE_UP_EN})?[\s,.!]*(lum
WAKE_REPLY = {"en": "Yes? How can I help?", "ko": "네? 무엇을 도와드릴까요?"} WAKE_REPLY = {"en": "Yes? How can I help?", "ko": "네? 무엇을 도와드릴까요?"}
NAME_ONLY = re.compile(r"^\s*(hi |hey |hello )?(lumi|loomi|rumi|루미)[\s,.!?]*$", re.I) NAME_ONLY = re.compile(r"^\s*(hi |hey |hello )?(lumi|loomi|rumi|루미)[\s,.!?]*$", re.I)
FETCH_STOP = re.compile(r"\b(sto+pp?|stob|halt|freeze|don'?t move)\b|^\W*(?:lumi\W+)?stopped\W*$|스탑|스텁|멈추(?:세요|십시오)|^\W*abort\W*$|\babort (?:the |this |your )?(?:mission|task|trip)\b|\bcancel (?:the |this |your )?(?:mission|task|trip)\b|" FETCH_STOP = re.compile(r"\b(sto+pp?|stob|halt|freeze|don'?t move)\b|^\W*(?:lumi\W+)?stopped\W*$|스탑|스텁|멈추(?:세요|십시오)|^\W*abort\W*$|\babort (?:the |this |your )?(?:mission|task|trip)\b|\bcancel (?:the |this |your )?(?:mission|task|trip)\b|"
r"머+엄*춰|머+엄*추(?:세요|십시오)|멈춰|그만|정지|스톱|미션 ?취소|작업 ?취소|거기 ?서(?=[\s!.~,]*$)|움직이지 ?마|" r"머+엄*춰|머+엄*추(?:세요|십시오)|멈춰|멈추(?:게|시게|게나|시오|어라)|그만|정지|스톱|스땁|스떱|미션 ?취소|작업 ?취소|"
r"거기 ?서(?: ?봐| ?있어)?(?=[\s!.~,]*$)|움직이지 ?마|\bemergency stop\b|\b(?:stay|hold|keep) still\b|"
r"^\W*(?:wait|잠깐|잠깐만|기다려)\W*$", re.I) # not "거기서 기다려" r"^\W*(?:wait|잠깐|잠깐만|기다려)\W*$", re.I) # not "거기서 기다려"
FETCH_GIVE = re.compile(r"\bgive (it|that|this|the \w+)( to me)?\b|\bhand (it )?(over|to me)\b|줘|주세요|건네", re.I) FETCH_GIVE = re.compile(r"\bgive (it|that|this|the \w+)( to me)?\b|\bhand (it )?(over|to me)\b|줘|주세요|건네", re.I)
FETCH_PLACE = re.compile(r"\b(put|place|set) (it|that|this|the \w+) (down|on the table)\b|테이블에 ?(놔|놓|둬)|내려 ?(놔|놓)", re.I) FETCH_PLACE = re.compile(r"\b(put|place|set) (it|that|this|the \w+) (down|on the table)\b|테이블에 ?(놔|놓|둬)|내려 ?(놔|놓)", re.I)
@@ -3241,7 +3242,7 @@ NOT_STOP = re.compile( # a stop word that orders no stop: negated, about someo
r"\bstop-motion\b|\bone-stop\b|\bwhy(?:'d| did| do| does)? (?:you|it|lumi) (?:freeze|stop|halt)|\b(?:would|should|could|might|will) stop\b|\blet'?s stop (?:at|for|by)\b|" r"\bstop-motion\b|\bone-stop\b|\bwhy(?:'d| did| do| does)? (?:you|it|lumi) (?:freeze|stop|halt)|\b(?:would|should|could|might|will) stop\b|\blet'?s stop (?:at|for|by)\b|"
r"\bstop (?:for|at the|at a) (?:coffee|lunch|a (?:bit|while|break)|the \w+ (?:place|shop|store|cafe))|" r"\bstop (?:for|at the|at a) (?:coffee|lunch|a (?:bit|while|break)|the \w+ (?:place|shop|store|cafe))|"
r"\b(?:when|if|once|whenever|after) [^,]{1,40},?\s*(?:you )?stop\b|" r"\b(?:when|if|once|whenever|after) [^,]{1,40},?\s*(?:you )?stop\b|"
r"그만(?:두|뒀|둘)|그만 ?(?:먹|마시|자|놀|울|웃|싸우|뛰)|" r"그만(?:두(?!세요|십시오|시오|어라|라|게)|뒀|둘)|그만 ?(?:먹|마시|자|놀|울|웃|싸우|뛰)|" # "회사 그만뒀어"; "그만두세요" stops
r"(?<![가-힣])(?!루미|로봇|누미|아야|말이야|얘야)(?:엄마|아빠|얘들아|형|언니|누나|오빠|[가-힣]{1,3}야|[가-힣]{1,3}아)\s+(?:좀\s+|거기\s+)?(?:그만|멈춰|정지)|" r"(?<![가-힣])(?!루미|로봇|누미|아야|말이야|얘야)(?:엄마|아빠|얘들아|형|언니|누나|오빠|[가-힣]{1,3}야|[가-힣]{1,3}아)\s+(?:좀\s+|거기\s+)?(?:그만|멈춰|정지)|"
r"(?-i:\b(?!(?:Lumi|Loomi|Rumi|Robot|Hey|Hi|Okay|Ok|No|Please|Now|Wait|Hello|So|Oh|Yo)\b)[A-Z][a-z]+), stop \w+ing\b", re.I) r"(?-i:\b(?!(?:Lumi|Loomi|Rumi|Robot|Hey|Hi|Okay|Ok|No|Please|Now|Wait|Hello|So|Oh|Yo)\b)[A-Z][a-z]+), stop \w+ing\b", re.I)
# also: another meaning, someone else told off ("엄마 그만 찍어", "Jake, stop touching the robot!"), a condition # also: another meaning, someone else told off ("엄마 그만 찍어", "Jake, stop touching the robot!"), a condition
@@ -3273,7 +3274,7 @@ STOP_PAD = re.compile(r"^(?:\W*(?:hey|hi|yo|oh|okay|ok|so|um+|uh+|listen|right|a
r"(?:\W*\b(?:please|plz|pls|bro|now|right now|real quick|thanks|thank you|okay|ok|would you|will you|" r"(?:\W*\b(?:please|plz|pls|bro|now|right now|real quick|thanks|thank you|okay|ok|would you|will you|"
r"right|already|lumi|robot|빨리|좀|제발|당장|루미야?)\b)+\W*$", re.I) r"right|already|lumi|robot|빨리|좀|제발|당장|루미야?)\b)+\W*$", re.I)
STOP_ONLY = re.compile( # a whole sentence that only says stop / enough / stay (after calls and fillers): stop at once STOP_ONLY = re.compile( # a whole sentence that only says stop / enough / stay (after calls and fillers): stop at once
r"(?:(?:sto+p|stahp|stob|top it|enough|that'?s enough|that is enough|no more|quit it|cut it out|knock it off|whoa,? there|whoa(?:,? whoa)+|kill it|abort|" r"(?:(?:sto+p|stahp|stob|top it|emergency stop|enough|that'?s enough|that is enough|no more|quit it|cut it out|knock it off|whoa,? there|whoa(?:,? whoa)+|kill it|abort|"
r"stop (?:everything|driving|moving|it|that|the robot|right there|right now)|enough (?:music|of that)|" r"stop (?:everything|driving|moving|it|that|the robot|right there|right now)|enough (?:music|of that)|"
r"hold it(?: (?:right )?(?:there|here))?|stop 해|그만|그만해|그만해요|그만하세요|그만하십시오|그만해 ?줄래요?|" r"hold it(?: (?:right )?(?:there|here))?|stop 해|그만|그만해|그만해요|그만하세요|그만하십시오|그만해 ?줄래요?|"
r"그만해 ?주세요|그마내|그만둬|멈춰|멈쳐|멈처|멈추라고|멈춰 ?봐|거기까지|고마 ?(?:서라|해라|해|하이소)|서|don'?t go|가지 ?마|그마+안|" r"그만해 ?주세요|그마내|그만둬|멈춰|멈쳐|멈처|멈추라고|멈춰 ?봐|거기까지|고마 ?(?:서라|해라|해|하이소)|서|don'?t go|가지 ?마|그마+안|"
@@ -3502,7 +3503,7 @@ def read_mission(text, markers):
if unread and got and ({s["do"] for s in got} & steps.MISSION_ONLY or steps.is_mission(got)): if unread and got and ({s["do"] for s in got} & steps.MISSION_ONLY or steps.is_mission(got)):
got, unread, by = steps.read(text, markers) # clearly several steps: the LLM may read it got, unread, by = steps.read(text, markers) # clearly several steps: the LLM may read it
elif unread and got and any((brain_mod.intent(u, markers) or ("",))[0] not in ("", "weather", "search", "fetch") elif unread and got and any((brain_mod.intent(u, markers) or ("",))[0] not in ("", "weather", "search", "fetch")
or NOT_A_STEP.match(u) for u in unread): or NOT_A_STEP.match(u) or brain_mod.place_problem(u, markers) for u in unread):
return got, unread, by # "go to the stage and wave": no task step, asked, never half done return got, unread, by # "go to the stage and wave": no task step, asked, never half done
elif unread: elif unread:
return None # "come here, I need help": the old paths (rules, the LLM) answer it return None # "come here, I need help": the old paths (rules, the LLM) answer it
+20 -19
View File
@@ -1,6 +1,7 @@
"""Marker names said in other ways than wording.py reads them: the other language ("information desk" for 안내데스크, """Marker names said in other ways than wording.py reads them: as they sound in the other language ("인포 데스크"
"레지스트레이션" for Registration), the words of a two-word name the other way round ("에이 부스" for booth_A, "삼 번 부스" for info_desk, "레지스트레이션" for Registration; never a translation: 출구 is no "exit"), the words of a two-word
for 부스3), letters and numbers as said ("booth bee", "부스 십이", "gate won"), and whisper's spellings ("hole A", "카패"). name the other way round ("에이 부스" for booth_A, "삼 번 부스" for 부스3), letters and numbers as said ("booth bee",
"부스 십이", "gate won"), and whisper's spellings ("hole A", "카패").
apply(t, markers) writes them as the marker's written name (wording.written) in text already normalised by apply(t, markers) writes them as the marker's written name (wording.written) in text already normalised by
wording.norm, so every reader after it (brain.named_place, the go rules, the intent bank) sees the marker. wording.norm, so every reader after it (brain.named_place, the go rules, the intent bank) sees the marker.
@@ -14,23 +15,22 @@ import sys
from assistant import wording from assistant import wording
EN_KO = { # an English word of a name -> how it is said in Korean, and other spellings EN_KO = { # an English word of a name -> how it sounds in Korean, and other spellings. Never a translation: "출구" is
"registration": ["레지스트레이션", "레지스트레이숀", "등록"], "gallery": ["갤러리", "겔러리", "갤러리이"], # not "exit" (the owner, 2026-10-26: a word that only means the place is asked about, never mapped to a marker)
"information": ["인포메이션", "안내"], "info": ["인포", "information", "인포메이션", "안내"], "registration": ["레지스트레이션", "레지스트레이숀"], "gallery": ["갤러리", "겔러리", "갤러리이"],
"information": ["인포메이션"], "info": ["인포", "information", "인포메이션"],
"desk": ["데스크", "대스크", "데스끄"], "cafe": ["카페", "카패", "까페", "café"], "coffee": ["커피", "코피"], "desk": ["데스크", "대스크", "데스끄"], "cafe": ["카페", "카패", "까페", "café"], "coffee": ["커피", "코피"],
"corner": ["코너"], "elevator": ["엘리베이터", "엘레베이터", "엘베"], "lift": ["리프트"], "entrance": ["엔트런스", "입구"], "corner": ["코너"], "elevator": ["엘리베이터", "엘레베이터", "엘베"], "lift": ["리프트"], "entrance": ["엔트런스"],
"exit": ["엑시트", "엑싯", "출구"], "stage": ["스테이지", "무대"], "main": ["메인"], "booth": ["부스", "boot", "bootH"], "exit": ["엑시트", "엑싯", "엑짓", "이그짓", "익싯", "익시트", "에그짓"], "stage": ["스테이지"], "main": ["메인"], "booth": ["부스", "boot", "bootH"],
"hall": ["홀", "hole", "hol"], "gate": ["게이트", "gait"], "photo": ["포토", "foto", "사진"], "zone": ["존", "zon"], "hall": ["홀", "hole", "hol"], "gate": ["게이트", "gait"], "photo": ["포토", "foto"], "zone": ["존", "zon"],
"lounge": ["라운지", "휴게실"], "lobby": ["로비"], "bar": ["바"], "table": ["테이블", "table"], "front": ["프론트", "프런트", "앞"], "lounge": ["라운지"], "lobby": ["로비"], "bar": ["바"], "table": ["테이블", "table"], "front": ["프론트", "프런트"],
"restroom": ["화장실"], "toilet": ["화장실"], "meeting": ["미팅", "회의"], "room": ["룸", "실"], "shop": ["샵", "숍"], "restroom": ["레스트룸"], "toilet": ["토일렛"], "meeting": ["미팅"], "room": ["룸"], "shop": ["샵", "숍"],
"gift": ["기프트", "기념품"], "dock": ["도크", "독"], "demo": ["데모"], "lab": ["랩"], "office": ["오피스", "사무실"], "gift": ["기프트"], "dock": ["도크", "독"], "demo": ["데모"], "lab": ["랩"], "office": ["오피스"],
} }
KO_EN = { # a Korean word of a name -> how it is said in English KO_EN = { # a Korean word of a name -> how it sounds in English (and its spellings); never a translation
"안내": ["information", "info", "인포", "인포메이션"], "데스크": ["desk", "대스크"], "커피": ["coffee"], "코너": ["corner"], "인포": ["info"], "인포메이션": ["information"], "데스크": ["desk", "대스크"], "커피": ["coffee"], "코너": ["corner"],
"포토": ["photo", "foto"], "존": ["zone"], "입구": ["entrance", "엔트런스"], "출구": ["exit", "엑시트"], "포토": ["photo", "foto"], "존": ["zone"], "엔트런스": ["entrance"], "스테이지": ["stage"], "라운지": ["lounge"],
"무대": ["stage", "스테이지"], "휴게실": ["lounge", "break room", "rest area", "라운지"], "회의실": ["meeting room", "conference room"], "부스": ["booth"], "로비": ["lobby"], "카페": ["cafe", "café", "카패"], "갤러리": ["gallery"], "홀": ["hall"],
"화장실": ["restroom", "toilet", "bathroom", "washroom"], "앞": ["front"], "부스": ["booth"], "라운지": ["lounge"],
"기념품점": ["gift shop", "souvenir shop"], "로비": ["lobby"], "카페": ["cafe", "café", "카패"], "갤러리": ["gallery"],
} }
LETTER = {"a": ["a", "에이", "ay", "에이에"], "b": ["b", "bee", "be", "비", "삐"], "c": ["c", "see", "sea", "씨"], LETTER = {"a": ["a", "에이", "ay", "에이에"], "b": ["b", "bee", "be", "비", "삐"], "c": ["c", "see", "sea", "씨"],
"d": ["d", "dee", "디"], "e": ["e", "이"]} "d": ["d", "dee", "디"], "e": ["e", "이"]}
@@ -74,7 +74,8 @@ def _patterns(markers):
continue continue
parts = ["(?:" + "|".join(sorted({re.escape(a).replace(r"\ ", r"\s?") for a in _alts(t, len(toks) == 1)}, parts = ["(?:" + "|".join(sorted({re.escape(a).replace(r"\ ", r"\s?") for a in _alts(t, len(toks) == 1)},
key=len, reverse=True)) + ")" for t in toks] key=len, reverse=True)) + ")" for t in toks]
orders = [parts] + ([parts[::-1]] if len(parts) == 2 else []) orders = [parts] + ([parts[::-1]] if len(parts) == 2 else [parts[1:] + parts[:1]] if len(parts) > 2 else [])
# ^ "에이 부스" for booth_A, "비 세븐 게이트" for Gate_B7: the first word said last
body = "|".join(SEP.join(p) for p in orders) body = "|".join(SEP.join(p) for p in orders)
out.append((m, re.compile(rf"(?<![a-z0-9_가-힣])(?:the )?(?:{body})(?![a-z0-9_])(?:(?<=[a-z0-9])|{wording._KO_END})"))) out.append((m, re.compile(rf"(?<![a-z0-9_가-힣])(?:the )?(?:{body})(?![a-z0-9_])(?:(?<=[a-z0-9])|{wording._KO_END})")))
return out return out
+131 -9
View File
@@ -268,6 +268,11 @@ NO = [t for t in NO if t not in _said] # a wording
CAMERA = re.compile(r"\b(?:see|seeing|saw|look(?:s|ing)?|watch|camera|wearing|holding|in front of|behind|colou?r|" CAMERA = re.compile(r"\b(?:see|seeing|saw|look(?:s|ing)?|watch|camera|wearing|holding|in front of|behind|colou?r|"
r"recogni[sz]e|remember)\b|보여|보이|보니|(?<!해 )(?<!해)(?<!쭤 )(?<!쭤)(?<!여쭈어 )봐(?!도 ?(?:돼|되|될|괜찮))|봤|입었|들고|색|카메라|앞에|뒤에|알아봐|기억", re.I) r"recogni[sz]e|remember)\b|보여|보이|보니|(?<!해 )(?<!해)(?<!쭤 )(?<!쭤)(?<!여쭈어 )봐(?!도 ?(?:돼|되|될|괜찮))|봤|입었|들고|색|카메라|앞에|뒤에|알아봐|기억", re.I)
SPEC = re.compile(r"\b(?:what|which|how many|what kind of|what type of|what sort of) (?:depth )?cameras?\b|\bcameras? (?:do you (?:have|use)|"
r"model|brand|type|range|resolution)\b|\b(?:recogni[sz]e|remember) (?:faces|people|anyone|who people are)\b|"
r"\bface recognition\b|카메라(?:가|는|를)? ?(?:몇 ?개|몇 ?대|뭐 ?써|뭘 ?써|뭐 ?쓰|어떤 ?거|기종|모델|종류|제품|사양|스펙)|"
r"얼굴 ?(?:인식|알아보|알아봐|기억)", re.I)
# the cameras and face recognition as facts ("what cameras do you have?", "얼굴 인식 돼요?"), not what they see now
ABOUT_ME = re.compile(r"\b(?:(?<!can )(?<!could )(?<!may )i(?! (?:call|address) you\b)(?! (?:talk|speak|chat) (?:to|with) you\b)|i'm|am i|my|" ABOUT_ME = re.compile(r"\b(?:(?<!can )(?<!could )(?<!may )i(?! (?:call|address) you\b)(?! (?:talk|speak|chat) (?:to|with) you\b)|i'm|am i|my|"
r"(?<!tell )(?<!give )(?<!let )(?<!show )me|mine)\b|(?:^|\s)(?:나|내|제|저|난|전)(?:는|가|를|의)?\s", re.I) r"(?<!tell )(?<!give )(?<!let )(?<!show )me|mine)\b|(?:^|\s)(?:나|내|제|저|난|전)(?:는|가|를|의)?\s", re.I)
FRAGMENT = re.compile(r"^\W*(?:and|so|but|then|or|also|why|really|seriously|wait|what about|how about|how come|are you sure)\b|" FRAGMENT = re.compile(r"^\W*(?:and|so|but|then|or|also|why|really|seriously|wait|what about|how about|how come|are you sure)\b|"
@@ -275,18 +280,39 @@ FRAGMENT = re.compile(r"^\W*(?:and|so|but|then|or|also|why|really|seriously|wait
r"\b(?:that|(?<!is )(?<!was )(?<!is it )(?<!how's )(?<!how is )it(?! is (?:now|today))|they|them|" r"\b(?:that|(?<!is )(?<!was )(?<!is it )(?<!how's )(?<!how is )it(?! is (?:now|today))|they|them|"
r"(?<!hello )(?<!hi )(?<!hey )(?<!is )(?<!are )there(?! (?:is|are)\b)|this one)\b|" r"(?<!hello )(?<!hi )(?<!hey )(?<!is )(?<!are )there(?! (?:is|are)\b)|this one)\b|"
r"그거|그건|거기|그분|그 회사|걔", re.I) # not the clock's "it": "what day is it?" r"그거|그건|거기|그분|그 회사|걔", re.I) # not the clock's "it": "what day is it?"
OTHER = re.compile(r"\b(?:lift|carry|hold|items?|(?<!this )things?|stuff|price|cost)\b|들 ?수|(?<!만)(?<!알아)(?<!뭐 )들어|물건|" OTHER = re.compile(r"\b(?:lift|carry|hold|items?|(?<!this )things?|stuff|price|cost)\b|들 ?수|(?<!만)(?<!알아)(?<!뭐 )들어(?! ?있)|물건|"
r"^(?!.*(?:키|무게|체중|신장|속도|시간|나이|높이|길이|크기)).*얼마(?:야|예요)|" r"^(?!.*(?:키|무게|체중|신장|속도|시간|나이|높이|길이|크기|수명|배터리|하이트|웨이트|스피드|에이지|height|weight|speed|age|battery|life))"
r".*얼마(?:야|예요)|"
r"맞(?:아|지|죠|나|습니까)|아니(?:야|에요|죠)", re.I) # what it can hold, the price, a check: the LLM r"맞(?:아|지|죠|나|습니까)|아니(?:야|에요|죠)", re.I) # what it can hold, the price, a check: the LLM
SEVERAL = re.compile(r"\band\b(?!\s+(?:built|made|\w+ed)\s+(?:you|lumi|this robot)\b)|\bthen\b|그리고|[??].+\S|하고\s|랑\s|" SEVERAL = re.compile(r"\band\b(?!\s+(?:built|made|\w+ed)\s+(?:you|lumi|this robot)\b)|\bthen\b|그리고|[??].+\S|하고\s|랑\s|"
r"[가-힣](?<![최광참사창공경재원라])(?<!그리)고\s+(?!싶|있|계)", re.I) # "고개 숙이고 몇 시야?", "보고 시간 알려 줘" r"[가-힣](?<![최광참사창공경재원라])(?<!그리)고\s+(?!싶|있|계)", re.I) # "고개 숙이고 몇 시야?", "보고 시간 알려 줘"
EVENT_TIME = re.compile(r"\b(?:what time|what day|which day|what date) (?:does|do|did|will|is|are|was|were|should|can)\b" EVENT_TIME = re.compile(r"\b(?:what time|what day|which day|what date) (?:does|do|did|will|is|are|was|were|should|can)\b"
r"(?!\s+(?:it|today)\b)|몇 ?시(?:에|부터|까지|쯤에)|며칠(?:에|까지|부터)|무슨 요일(?:에|까지|부터)|" r"(?!\s+(?:it|today)\b)|몇 ?시(?:에|부터|까지|쯤에)|며칠(?:에|까지|부터)|무슨 요일(?:에|까지|부터)|"
r"\b(?:open|close)\b(?!\s+(?:a|the|my|your|this|that|doors?)\b)|\b(?:start|end|begin|finish)\b|열어요|닫아요|시작|끝나", re.I) # an event's time: the LLM r"\b(?:open|close)\b(?!\s+(?:a|the|my|your|this|that|doors?)\b)|\b(?:start|end|begin|finish)\b|열어요|닫아요|시작|끝나", re.I) # an event's time: the LLM
OTHER_FIRM = re.compile(r"\b(?:openai|google|samsung|apple|lg|microsoft|tesla|nvidia|hyundai|naver|kakao|meta|amazon|sony)\b|"
r"오픈 ?ai|오픈에이아이|구글|삼성|애플|엘지|마이크로소프트|테슬라|엔비디아|현대|네이버|카카오|메타|아마존|소니", re.I)
OTHER_ROBOT = re.compile(r"\b(?:jaka|jacka|k1[wl]?|kargo|peitian|tusk)\b|자카|작카|节卡|페이톈|페이티엔|터스크", re.I)
NAMES_LUMI = re.compile(r"\b(?:you|your|yourself|u|ur|lumi)\b|(?:^|\s)(?:너|넌|니|네|당신|루미|본인|자기)", re.I) NAMES_LUMI = re.compile(r"\b(?:you|your|yourself|u|ur|lumi)\b|(?:^|\s)(?:너|넌|니|네|당신|루미|본인|자기)", re.I)
_bank = None _bank = None
_named = None # (kind names, int code per bank row) for intent_bank._top _named = None
_exact_kinds = None
def _squeezed(t):
return re.sub(r"[\s,.!?~]", "", t).lower()
def _exact():
"""{wording without spaces: kind} of the wordings only one kind has: speech written without spaces (whisper does it
in Korean) found as the wording it is."""
global _exact_kinds
if _exact_kinds is None:
seen = {}
for t, k in examples():
seen.setdefault(_squeezed(t), set()).add(k)
_exact_kinds = {t: ks.pop() for t, ks in seen.items() if len(ks) == 1}
return _exact_kinds # (kind names, int code per bank row) for intent_bank._top
def examples(): def examples():
@@ -307,20 +333,54 @@ def _load():
ASKING = re.compile(r"^\W*(?:(?:hang on|wait|okay|ok|so|um+|uh+|hey|excuse me|sorry|just out of curiosity|out of curiosity|" ASKING = re.compile(r"^\W*(?:(?:hang on|wait|okay|ok|so|um+|uh+|hey|excuse me|sorry|just out of curiosity|out of curiosity|"
r"i(?:'m| am) curious|quick question|one question|let me ask(?: (?:it|you|him|her))?|i bet (?:it'?s|you'?re) \w+|" r"i(?:'m| am) curious|quick question|one question|let me ask(?: (?:it|you|him|her))?|i bet (?:it'?s|you'?re) \w+|"
r"(?:may|can|could|might) i (?:ask|know)(?: you)?|i(?:'d| would) like to know|i want(?:ed)? to (?:ask|know)|" r"(?:may|can|could|might) i (?:ask|know)(?: you)?|i(?:'d| would) like to know|i want(?:ed)? to (?:ask|know)|"
r"i wonder|do you mind (?:telling me|if i ask)|(?:(?:can|could|would|will) you )?tell me|might i trouble you for|could i trouble you for|잠깐(?:만)?|저기(?:요|유|예)?|이보게|자네|보소|" r"i wonder|i was wondering|i'?m wondering|i'?d love to know|(?:would|do) you mind (?:telling me|if i ask)|"
r"(?:could|can|would) you let me know|let me know|i have a question|may i know|please tell me|tell me please|(?:(?:can|could|would|will) you )?tell me|might i trouble you for|could i trouble you for|잠깐(?:만)?|저기(?:요|유|예)?|이보게|자네|보소|"
r"야야|궁금한 ?게 있는데(?:요)?|하나 여쭤봐도 될까요\??|여쭤봐도 될까요\??|궁금한데(?:요)?|궁금해서(?:요)?|" r"야야|궁금한 ?게 있는데(?:요)?|하나 여쭤봐도 될까요\??|여쭤봐도 될까요\??|궁금한데(?:요)?|궁금해서(?:요)?|"
r"하나 물어봐도 (?:돼|될까)요?|여쭤봐도 될까요|물어볼게(?:요)?|질문(?: 하나)?(?: 있어요| 있는데요?)?)" r"하나 물어봐도 (?:돼|될까)요?|여쭤봐도 될까요|물어볼게(?:요)?|질문(?: 하나)?(?: 있어요| 있는데요?)?)"
r"\b[\s,.!?~:-]*)+", re.I) r"\b[\s,.!?~:-]*)+", re.I)
# "May I ask your age?", "Hang on, let me ask it. What's your name?", "궁금한데, 몇 살이에요?": the question after # "May I ask your age?", "Hang on, let me ask it. What's your name?", "궁금한데, 몇 살이에요?": the question after
OPENER = re.compile(r"^\W*(?:(?:hello|hi|hllo|helo|hey|excuse me|well|okay|ok|oh|ah|g'?day|oppa|grabe|so like|dear|buddy|mate|"
r"sir|ma'?am|my (?:new )?friend|little robot|big robot|mr\.? robot|"
r"어이|이보게|여보게|야야|아야|우리|애기야|브로|bro|큰 로봇아|(?:오빠|언니|이쁜이|선배님|사장님|기사님|아가씨|로봇 양반|양반)(?=\s*,)|"
r"얘|쟤|마|야|저기|저기요|잠깐(?:만)?|대박|사와디캅|참|아 맞다|맞다|"
r"(?:야|아야|우리|이보게|어이|야야) ?(?:루미야|루미|로봇아|로봇)|실례합니다|실례지만|실례할게요|하나 묻겠습니다|하나 물을게(?:요)?|루미루미|누미야|"
r"루미 ?(?:님|군|상|씨|언니|오빠|누나|형)|루미야|루미|로봇(?:아|님|씨)?|robot|lumi)(?![\w가-힣])[\s,.!?~:-]*)+", re.I)
# calling words before the question ("hello robot, ...", "루미 님, ...", "실례합니다. ..."): left out of the meaning
REMARK = re.compile(r"(?:quick question|just (?:curious|wondering|asking)|(?:i'?m )?curious|i want to know|i'd like to know|"
r"please|thanks?|thank you|tell me(?: please)?|any idea|ㅎ+|ㅋ+|\^+|그냥 궁금해서(?:요)?|궁금하다|궁금해(?:요)?|"
r"궁금하네(?:요)?|궁금합니다|알고 싶어(?:요)?|알고 싶습니다|(?:좀 )?(?:알려|말해|가르쳐) ?(?:줘|줄래|줄래요|주세요|"
r"주실래요|주시겠어요|주시겠습니까|주십시오|봐)|진짜 궁금해(?:요)?|"
r"(?:하나 ?|뭐 ?하나 ?|질문 ?하나 ?)?(?:여쭤|여쭈어|물어) ?(?:봐|바|보)도 ?(?:될까요|돼요|되나요|됩니까|될까|돼)|"
r"질문 ?(?:하나 ?)?(?:해도 ?(?:될까요|돼요|되나요)|있어요|있습니다|있는데요?)|궁금한 ?게 ?있(?:는데요?|어요|습니다)|"
r"하나 ?묻겠습니다|실례합니다|실례지만|(?:may|can|could) i ask (?:you )?(?:something|a question)|"
r"i have a question|one question)", re.I)
# a sentence that only asks to be told or says why: "Christmas 얼마나 남았어요? 알고 싶어요."
SENTENCES = re.compile(r"(?<=[??!])\s*|(?<=\.)\s+")
def _tidy(text):
"""Stutters and words said twice taken out ("키가 얼— 얼마예요?", "너 너 몇 살이야"), laughs at the end."""
t = re.sub(r"(?<![\w])(\w{1,4})[—–-]+\s*(?=\1)", "", text or "")
t = re.sub(r"\b(\w+)(?:[\s,]+\1\b)+", r"\1", t)
return re.sub(r"(?<=\S)[\s~^ㅎㅋ]+(?=[??!.]*$)|(?<=[??!.])[\s~^ㅎㅋ]+$", "", t).strip()
def _core(text): def _core(text):
from assistant import brain from assistant import brain
t = ASKING.sub("", brain.CALLING.sub("", brain.unfill(text or "")).strip()).strip() or text or "" t = brain.unfill(text or "")
rest = OPENER.sub("", t)
if len(rest.split()) >= 2 or re.search(r"[가-힣]{4}", rest): # "hello there", "hi lumi" stay whole
t = rest
t = ASKING.sub("", brain.CALLING.sub("", t).strip()).strip() or text or ""
if not re.search(r"\b(?:is|was|name|named|called)\s+lumi\W*$", t, re.I): # the subject: "How wide is Lumi?" if not re.search(r"\b(?:is|was|name|named|called)\s+lumi\W*$", t, re.I): # the subject: "How wide is Lumi?"
t = re.sub(r"[\s,]*(?:lumi|루미야|루미)?[\s,.!?~]*$", "", t, flags=re.I).strip() t = re.sub(r"[\s,]*(?:lumi|루미야|루미)?[\s,.!?~]*$", "", t, flags=re.I).strip()
if re.fullmatch(r"(?:무슨|뭔|무엇의?) ?뜻\S*", t) and "루미" in (text or ""): if re.fullmatch(r"(?:무슨|뭔|무엇의?) ?뜻\S*", t) and "루미" in (text or ""):
t = "루미 " + t # "루미 무슨 뜻이에요?": what the name means t = "루미 " + t # "루미 무슨 뜻이에요?": what the name means
t = re.sub(r"\b(?:do|have) you (?:have|got) the time\b", "what time is it", t, flags=re.I) # the clock, not "free?"
t = re.sub(r"([가-힣])인지 (?:궁금|알고 싶|알려|말해|알 수 있|여쭤)\S*(?: \S+)?$",
lambda m: m.group(1) + ("이에요" if (ord(m.group(1)) - 0xAC00) % 28 else "예요"), t)
t = re.sub(r"(?<=[가-힣])는지 (?:궁금|알고 싶|알려|말해|알 수 있|여쭤)\S*(?: \S+)?$", "나요", t) # "몇 살인지 궁금해요"
t = re.sub(r"(?:뭔가|무엇인가)$", "뭐예요", re.sub(r"(?<=[가-힣])(?:는교|남유|는감)$", "나요", t)) # 하게체, dialect
t = re.sub(r"얼만가$", "얼마예요", re.sub(r"(?<=[가-힣])는가$", "나요", re.sub(r"(?<=[가-힣])인가$", "인가요", t))) t = re.sub(r"얼만가$", "얼마예요", re.sub(r"(?<=[가-힣])는가$", "나요", re.sub(r"(?<=[가-힣])인가$", "인가요", t)))
return t or (text or "").strip(" ,.!?~") # 하게체 questions ("키 얼만가", "얼마나 되는가") as 해요체 return t or (text or "").strip(" ,.!?~") # 하게체 questions ("키 얼만가", "얼마나 되는가") as 해요체
@@ -333,7 +393,7 @@ def guarded(text, history=()):
return "length" return "length"
if re.search(r"\b(?:good ?bye|bye|see you|farewell)\b|잘 ?가|안녕히|다음에 봐", t, re.I): if re.search(r"\b(?:good ?bye|bye|see you|farewell)\b|잘 ?가|안녕히|다음에 봐", t, re.I):
return "closing" # "goodbye" is never a hello return "closing" # "goodbye" is never a hello
if CAMERA.search(t): if CAMERA.search(SPEC.sub(" ", t)):
return "camera" return "camera"
if ABOUT_ME.search(t): if ABOUT_ME.search(t):
return "about the visitor" return "about the visitor"
@@ -351,13 +411,72 @@ def guarded(text, history=()):
return "other" return "other"
if EVENT_TIME.search(t) and not re.search(r"\bwhen did\b", t, re.I): # "when did Cutshion start?": a founding if EVENT_TIME.search(t) and not re.search(r"\bwhen did\b", t, re.I): # "when did Cutshion start?": a founding
return "event time" return "event time"
if re.search(r"타워|빌딩|건물|(?<![가-힣])탑|에펠|남산|한라산|백두산|\b(?:tower|building|mountain|bridge|skyscraper)\b", t, re.I):
return "another thing" # "롯데타워 하이트 얼마야?": not Lumi's height
if OTHER_ROBOT.search(t):
return "another robot" # JAKA's / PEITIAN's: the LLM with its notes
if OTHER_FIRM.search(t) and re.search(r"대표|사장|회장|창업자|설립자|\b(?:ceo|boss|founder|chairman|president|head)\b", t, re.I):
return "another company" # "오픈AI 대표 누군가?": a lookup, never Lumi's model or maker
if re.search(r"환율|달러|원화|엔화|유로|위안|비트코인|주가|\b(?:dollars?|euros?|yen|exchange rate|bitcoin|stocks?)\b", t, re.I):
return "lookup" # "1달러에 원화로 얼만가?": not the price of Lumi
if re.search(r"배터리|battery", t, re.I) and re.search(r"몇 ?년|\byears?\b|교체|replace", t, re.I):
return "battery lifetime" # how many years it lasts is not known; "배터리 수명" alone is hours
if history and not NAMES_LUMI.search(t): if history and not NAMES_LUMI.search(t):
return "in a talk, not naming Lumi" # "how old?" / "몇 살이에요?" after the company: about that return "in a talk, not naming Lumi" # "how old?" / "몇 살이에요?" after the company: about that
return None return None
def kind_of(text, history=()): ASKS = re.compile(r"[??]\W*$|\b(?:what|who|whom|whose|how|where|when|why|which)\b|^\W*(?:can|could|do|does|did|are|is|was|"
"""The kind of question, when sure; else None.""" r"will|would|may|have|has)\b|뭐|뭔|무엇|무슨|누구|누가|어디|언제|왜|몇|얼마|어떻게|어떤|어느|"
r"(?:까|니|냐|나요|가요|래|죠)\W*$", re.I) # words that ask something
ORDER = re.compile(r"^\W*(?:please\s+)?(?:go|come|turn|take|bring|pick|put|give|follow|wave|look|move|lift|raise|lower|stop|sing|"
r"dance|fold|reach|grab|show|open|close|hold|drive|walk|fly|speak|say|tell|let'?s|wait|stand|sit)\b|"
r"(?:줘|줘요|주세요|주십시오|주시오|주라|해라|하자|가자|와라|봐라|내밀어|흔들어|돌아|돌려|들어|내려|접어|펴|가|와|멈춰|그만)\s*[!.~…]*$", re.I)
# a command (said before a question, or as one sentence of several): never left out for the question
CORRECTION = re.compile(r"(?:^|[\s,.])(?:아 아니|아니 아니|아니 그러니까|아니다|아니 잠깐|no wait|wait no|i mean|scratch that|sorry i mean)"
r"(?=[\s,.])[\s,.]*", re.I)
CONNECT = re.compile(r"^\W*(?:(?:아|어|오|음|oh|ah|um+|uh+)\W+)?(?:그리고|그러면|그럼|근데|그런데|그건 그렇고|그나저나|참|아 맞다|맞다|"
r"and|so|then|but|also|anyway|by the way|btw|next test|quick one|one more)\b[\s,.:!-]*", re.I)
# a connective at the start of a first question: "그러면 키가 몇이에요?", "아 그리고 몇 개 국어 해?"
def kind_of(text, history=(), _whole=True):
"""The kind of question, when sure; else None. Several sentences: those that only call Lumi, ask to be told or say
something without asking are left out; what is left must be one question, or the same question said twice ("Do
robots have names? What's yours?" stays with the LLM, "얘 몇 살일까? 너 몇 살이야?" is the age). Not sure of the
whole: the question after a connective ("그러면 키가 몇이에요?") or after the last comma when the words before it
ask nothing ("셀카 찍을 거니까, 너 몇 살이야?", "형 비켜 봐, 키가 몇이에요?")."""
text = _tidy(text)
fix = list(CORRECTION.finditer(text))
if fix and len(text[fix[-1].end():].split()) >= 2:
text = text[fix[-1].end():] # "배터리, 아 아니, 지금 뭐 해?": what is said after the correction
parts = [p for p in SENTENCES.split(text) if p.strip() and not REMARK.fullmatch(p.strip(" ,.!??~"))
and OPENER.sub("", p).strip(" ,.!??~")]
if len(parts) > 1:
if any(ORDER.search(p) for p in parts):
return None # "fold it! your arm!", "손! 손 내밀어!": a command, the rules'
asked = [p for p in parts if ASKS.search(p)]
kinds = {kind_of(p, history) for p in asked}
return kinds.pop() if len(kinds) == 1 else None
if parts and parts[0] != text:
return kind_of(parts[0], history)
got = _kind(text, history)
if got or not _whole:
return got
m = CONNECT.match(text)
rest = text[m.end():] if m else text
if rest != text and len(rest.split()) >= 2 and ASKS.search(rest):
got = kind_of(rest, history, False)
if got:
return got
head, comma, tail = rest.rpartition(",")
if comma and len(tail.split()) >= (2 if re.search(r"[가-힣]", tail) else 3) and ASKS.search(tail) and \
not ASKS.search(head) and not ORDER.search(head): # "Your voice, what program?": the head is the topic
return kind_of(tail, history, False)
return None
def _kind(text, history):
if guarded(text, history): if guarded(text, history):
return None return None
from assistant import knowledge from assistant import knowledge
@@ -374,7 +493,10 @@ def kind_of(text, history=()):
_named = ([str(n) for n in names], codes) _named = ([str(n) for n in names], codes)
best, top, margin, agree, _ = intent_bank._top(vecs @ q, _named, k=AGREE_K) best, top, margin, agree, _ = intent_bank._top(vecs @ q, _named, k=AGREE_K)
sure = top >= SIM_MIN and margin >= MARGIN or agree and top >= SIM_AGREE and margin >= MARGIN_AGREE sure = top >= SIM_MIN and margin >= MARGIN or agree and top >= SIM_AGREE and margin >= MARGIN_AGREE
if best == "no" or not sure: core = _core(text)
if not sure: # "누가너를만들었습니까": a wording run together (whisper)
best = _exact().get(_squeezed(core)) if re.fullmatch(r"\S*[가-힣]{4}\S*", core) else None
if best in (None, "no"):
return None return None
if best == "hello" and history: if best == "hello" and history:
return None # hello in the middle of a talk: the LLM return None # hello in the middle of a talk: the LLM
+3
View File
@@ -1477,6 +1477,9 @@ def answer(text, lang="en", frames=None, slow_line=None):
elif _last["thing"] is None or last not in SEE_KINDS or re.search(r"\bit\s+(?:to|from)\b", t, re.I) or \ elif _last["thing"] is None or last not in SEE_KINDS or re.search(r"\bit\s+(?:to|from)\b", t, re.I) or \
not (IT.search(t) or FAR_BARE.match(t)): not (IT.search(t) or FAR_BARE.match(t)):
return None # "how far is Seoul?": not about the cameras return None # "how far is Seoul?": not about the cameras
from assistant import quick_answers
if not last and quick_answers.kind_of(text):
return None # "머리에 컴퓨터 있어?", "Is it safe to stand next to you?": a fact
_last["kind"], _last["asked"], _last["at"] = kind, (kind, t), time.time() _last["kind"], _last["asked"], _last["at"] = kind, (kind, t), time.time()
frames = _look(frames, asked_at) frames = _look(frames, asked_at)
if not frames: if not frames:
+41 -18
View File
@@ -39,7 +39,8 @@ _FILL = (r"(?:(?:저기 |그 )?(?:이보게(?: 루미)?|어이(?: 로봇아?|
r"루미 ?(?:님|씨|군|양)(?:께서|께)?|로봇 ?씨|여보세요|실례지만|실례합니다|죄송한데요?|죄송하지만|죄송합니다만|" r"루미 ?(?:님|씨|군|양)(?:께서|께)?|로봇 ?씨|여보세요|실례지만|실례합니다|죄송한데요?|죄송하지만|죄송합니다만|"
r"번거로우시겠지만)|" # calls of every level ("이보게 루미", "루미 님께서") before "루미" alone r"번거로우시겠지만)|" # calls of every level ("이보게 루미", "루미 님께서") before "루미" alone
r"please|let'?s|lets|hey lumi|hi lumi|hey|hi|lumi|loomi|rumi|okay|ok|alright|all right|so|well|real quick|if you can|if you could|자|저기|저기요|혹시|instead|um+|uh+|er|hmm|thank you|thanks|now|then|and|also|first|next|" r"please|let'?s|lets|hey lumi|hi lumi|hey|hi|lumi|loomi|rumi|okay|ok|alright|all right|so|well|real quick|if you can|if you could|자|저기|저기요|혹시|instead|um+|uh+|er|hmm|thank you|thanks|now|then|and|also|first|next|"
r"finally|after that|there|for me|for us|again|carefully|slowly|could you|can you|would you|will you|lumi야|루미야|루미|음|응|어|야 로봇|로봇아|로봇야|" r"finally|after that|there|for me|for us|again|carefully|slowly|could you|can you|would you|will you|could u|can u|would u|will u|"
r"pls|plz|yo|would it be possible to|is it possible to|could i ask you to|would you mind|lumi야|루미야|루미|음|응|어|야 로봇|로봇아|로봇야|"
r"감사합니다|고마워요|고마워|고맙습니다|좀|먼저|우선|일단|그다음|그 다음|마지막으로|다시|lastly|first of all|" r"감사합니다|고마워요|고마워|고맙습니다|좀|먼저|우선|일단|그다음|그 다음|마지막으로|다시|lastly|first of all|"
r"(?:i'?d|i would) like you to|i want you to|i need you to|you should|kindly|go ahead and|maybe|possibly|" r"(?:i'?d|i would) like you to|i want you to|i need you to|you should|kindly|go ahead and|maybe|possibly|"
r"do me a favou?r and|be a dear and|right away|quickly|if you don'?t mind|excuse me|sorry|" r"do me a favou?r and|be a dear and|right away|quickly|if you don'?t mind|excuse me|sorry|"
@@ -55,7 +56,7 @@ _SPLIT_KO = re.compile(r"(?<=[가-힣](?:고|서))(?<!라고)(?<!다고)(?<!자
def _norm(text, markers=()): def _norm(text, markers=()):
"""Lower case, marker names and numbers as written (assistant/wording.py: "피쓰리로" -> "p3로", "half a meter" -> """Lower case, marker names and numbers as written (assistant/wording.py: "피쓰리로" -> "p3로", "half a meter" ->
"0.5 m", "오십 센치" -> "0.5 m", "table front" -> "table_front" on a map with it), titles without their dot.""" "0.5 m", "오십 센치" -> "0.5 m", "table front" -> "table_front" on a map with it), titles without their dot."""
t = re.sub(r"\b(mr|mrs|ms|dr|prof)\. ", r"\1 ", wording.durations(brain.unfill(wording.norm(text, markers))) + " ") t = re.sub(r"\b(mr|mrs|ms|dr|prof)\. ", r"\1 ", wording.durations(brain.unfill(brain.ko_slips(wording.norm(text, markers)))) + " ")
t = re.sub(r"\b(?:take|pick up|pick|grab)\s?(?:해서|하고)", "집어서", t) # "컵 take해서": mixed t = re.sub(r"\b(?:take|pick up|pick|grab)\s?(?:해서|하고)", "집어서", t) # "컵 take해서": mixed
t = re.sub(r"(?<=[가-힣])고\s*나서(?=[\s,]|$)", "고", t) # "가고 나서" = "가고" t = re.sub(r"(?<=[가-힣])고\s*나서(?=[\s,]|$)", "고", t) # "가고 나서" = "가고"
t = re.sub(r"(?<![가-힣])(집었|잡았)다가(?=[\s,]|$)", lambda m: m.group(1)[0] + "고", t) # "컵 집었다가" = "컵 집고" t = re.sub(r"(?<![가-힣])(집었|잡았)다가(?=[\s,]|$)", lambda m: m.group(1)[0] + "고", t) # "컵 집었다가" = "컵 집고"
@@ -73,6 +74,9 @@ _SAME = [ # wordings read as the plain one (the blind mission sets, 2026-10-22
(r"\bmake a (left|right) turn\b", r"turn \1"), (r"\bmake a (left|right) turn\b", r"turn \1"),
(r"\bturn (\d+(?:\.\d+)?) degrees? (?:to (?:the |your )?)?(left|right)\b", r"turn \2 \1"), (r"\bturn (\d+(?:\.\d+)?) degrees? (?:to (?:the |your )?)?(left|right)\b", r"turn \2 \1"),
(r"\breverse (?=\d)", "move back "), (r"\bkeep it in your hands?\b", "hold it"), (r"\breverse (?=\d)", "move back "), (r"\bkeep it in your hands?\b", "hold it"),
(r"\b((?:take|bring|carry) (?:it|that|this|the \w+|a \w+)) (?:with you|along)\b", r"\1"), # "take the cup with you to p5"
(r"^(?:go|head|drive)(?: over)? to (\S+) with (the|a|this|that) ((?:\w+ )?\w+)\s*$", r"take \2 \3 to \1"), # "go to
# exit with the cup": the cup taken there
(r"\bcome back to where (?:i am|you are|we are)\b", "come back"), (r"\bcome back to where (?:i am|you are|we are)\b", "come back"),
(r"\buntil (?:someone|somebody|they|i|we) (?:says?|tells? you)(?: to)? (?:go on|continue|move on)\b" (r"\buntil (?:someone|somebody|they|i|we) (?:says?|tells? you)(?: to)? (?:go on|continue|move on)\b"
r"|\buntil you(?:'re| are) told to (?:go on|continue|move on)\b", "until i tell you to go on"), r"|\buntil you(?:'re| are) told to (?:go on|continue|move on)\b", "until i tell you to go on"),
@@ -456,7 +460,7 @@ def _wait(c, markers, after):
m = re.fullmatch(rf"(?:go (?:and )?)?(?:wait|stay|remain)(?: for me)? (?:at|by|in|near) (?:the )?(.+?)(?: for {_DUR})?(?: for me)?", c) m = re.fullmatch(rf"(?:go (?:and )?)?(?:wait|stay|remain)(?: for me)? (?:at|by|in|near) (?:the )?(.+?)(?: for {_DUR})?(?: for me)?", c)
if m and _at_place(m.group(1), markers): if m and _at_place(m.group(1), markers):
return [{"do": "go", "to": _at_place(m.group(1), markers)}, {"do": "wait", "s": _secs(m.group(2), m.group(3))}] return [{"do": "go", "to": _at_place(m.group(1), markers)}, {"do": "wait", "s": _secs(m.group(2), m.group(3))}]
m = re.fullmatch(rf"(.+?)(?:에서|에)\s*(?:가\s*)?{_KO_WAIT}(?:\s*줘)?", c) m = re.fullmatch(rf"(.+?)(?:에서|에)\s*(?:가\s*)?(?:(?:나|저|날|나를|저를|우리를?)\s*)?{_KO_WAIT}(?:\s*줘)?", c) # "p5에서 나 기다려"
if m and _at_place(m.group(1), markers): if m and _at_place(m.group(1), markers):
return [{"do": "go", "to": _at_place(m.group(1), markers)}, {"do": "wait", "s": None}] return [{"do": "go", "to": _at_place(m.group(1), markers)}, {"do": "wait", "s": None}]
if re.fullmatch(rf"{_STAY_EN}(?: (?:right )?(?:there|here))? (?:for|until) (?:my|our) (?:call|signal|word|go)", c): if re.fullmatch(rf"{_STAY_EN}(?: (?:right )?(?:there|here))? (?:for|until) (?:my|our) (?:call|signal|word|go)", c):
@@ -728,7 +732,11 @@ def _clause_steps(c, markers, after=None):
return [] return []
if re.fullmatch(r"(?:(?:it'?s |this is )?from|on behalf of) [a-z][a-z'-]+|[가-힣 ]+(?:이|가) (?:보내는|보낸) (?:거야|건데)", c): if re.fullmatch(r"(?:(?:it'?s |this is )?from|on behalf of) [a-z][a-z'-]+|[가-힣 ]+(?:이|가) (?:보내는|보낸) (?:거야|건데)", c):
return [] return []
m = re.fullmatch(rf"(?:(?:pass|hand|give|get|bring|fetch) me|(?:can|could|may) i (?:have|get|grab|take)|lemme have|let me have|" m = re.fullmatch(r"(.+\s받아)\s*(?:와|와 ?줘|오너라|오게)", c)
if m and (got := _clause_steps(m.group(1), markers, after)) and got[-1]["do"] == "receive":
return got + [{"do": "go", "to": "here"}] # "사라한테 컵 받아 와": taken from her, then brought back here
c = re.sub(r"^go (?:and )?(?=(?:grab|get) me\b)", "", c) # "go grab me a cup"
m = re.fullmatch(rf"(?:(?:pass|hand|give|get|grab|bring|fetch) me|(?:can|could|may) i (?:have|get|grab|take)|lemme have|let me have|"
rf"(?:would you )?mind (?:passing|handing|giving) me) (?:the |that |this |a |an |one )?" rf"(?:would you )?mind (?:passing|handing|giving) me) (?:the |that |this |a |an |one )?"
rf"(?:({COL}) )?({OBJ})s?(?: (?:on|from|off) the table| over(?: here)?| there| please)?" rf"(?:({COL}) )?({OBJ})s?(?: (?:on|from|off) the table| over(?: here)?| there| please)?"
rf"|(?:(?:나|저)(?:한테|에게)?\s*)?(?:({COL})\s*)?({OBJ})\s*(?:을|를)?\s*(?:하나만?\s*)?(?:(?:나|저)(?:한테|에게)\s*)?" rf"|(?:(?:나|저)(?:한테|에게)?\s*)?(?:({COL})\s*)?({OBJ})\s*(?:을|를)?\s*(?:하나만?\s*)?(?:(?:나|저)(?:한테|에게)\s*)?"
@@ -751,11 +759,16 @@ def _clause_steps(c, markers, after=None):
c = re.sub(r"\bstraight ahead\b", "forward", c) c = re.sub(r"\bstraight ahead\b", "forward", c)
c = re.sub(r"\bthe gripper\b", "your hand", c) c = re.sub(r"\bthe gripper\b", "your hand", c)
c = c.replace("그리퍼", "손") c = c.replace("그리퍼", "손")
m = re.fullmatch(r"(.+?)에 (?:있는|계신) (?:사람|분|손님)(?:한테|에게|께)\s*(?:(?:갖다|가져다|건네) ?(?:줘|주고|주세요|드려|드리고)?|" m = re.fullmatch(r"(?:(?:(?P<col>" + COL + r")\s*)?(?P<obj>" + OBJ + r")(?:을|를)?\s+)?(?P<at>.+?)에 (?:있는|계신) (?:사람|분|손님|[가-힣]{1,4}(?: ?(?:님|씨))?)"
r"줘|주고|드려|드리고)", c) r"(?:한테|에게|께)\s*(?:(?:갖다|가져다|건네) ?(?:줘|주고|주세요|드려|드리고)?|줘|주고|드려|드리고)|"
if m: r"(?:bring|take|carry|deliver|give) (?:the |a |an |this |that )?(?:(?P<col2>" + COL + r") )?(?P<obj2>" + OBJ +
to = _places(m.group(1), markers) r")s? to (?:the |a )?(?:person|people|guests?|someone|somebody|whoever is|boss|man|woman|lady|guy|gentleman|kid|"
return to and len(to) == 1 and [{"do": "go", "to": to[0]}, {"do": "give"}] or None r"child|staff|teacher|manager|customer|visitor|host)s? (?:at|in|by|near) (?:the )?(?P<at2>.+)", c)
if m: # "컵 p5에 있는 사람한테 갖다 줘", "bring the cup to the person at p5"
to = _places(m["at"] or m["at2"], markers)
obj = m["obj"] or m["obj2"]
pick = [dict(zip(("do", "object", "colour"), ("pick",) + tuple(_thing(m["col"] or m["col2"], obj))))] if obj else []
return to and len(to) == 1 and pick + [{"do": "go", "to": to[0]}, {"do": "give"}] or None
m = re.fullmatch(rf"(?:the|a) (?:({COL}) )?({OBJ})s?", c) # "Kim sends the bottle": that one, picked here m = re.fullmatch(rf"(?:the|a) (?:({COL}) )?({OBJ})s?", c) # "Kim sends the bottle": that one, picked here
if m and c != raw: if m and c != raw:
obj, col = _thing(m.group(1), m.group(2)) obj, col = _thing(m.group(1), m.group(2))
@@ -777,6 +790,9 @@ def _clause_steps(c, markers, after=None):
s = _wait(c, markers, after) s = _wait(c, markers, after)
if s is not None: if s is not None:
return s return s
s = after and after["do"] in ("pick", "receive") and _place_at(c, markers, after)
if s:
return s # "컵 집어서 | exit에 갖다 줘": delivered there, not only a drive
for f in (_go, _move, _turn, _give, _hold, _arm): for f in (_go, _move, _turn, _give, _hold, _arm):
s = f(c, markers) if f is _go else f(c) s = f(c, markers) if f is _go else f(c)
if s: if s:
@@ -797,7 +813,7 @@ def _clause_steps(c, markers, after=None):
m = re.fullmatch(r"(.+?)(?:으로|로|에) (?:가져가|가지고 가|갖고 가|들고 가)(?:서| 줘)?", c) m = re.fullmatch(r"(.+?)(?:으로|로|에) (?:가져가|가지고 가|갖고 가|들고 가)(?:서| 줘)?", c)
if m and (to := _places(m.group(1), markers)) and len(to) == 1: if m and (to := _places(m.group(1), markers)) and len(to) == 1:
return [{"do": "go", "to": to[0]}] # "피사로 가져가": as "take it to p4" return [{"do": "go", "to": to[0]}] # "피사로 가져가": as "take it to p4"
s = _place_at(c, markers) or _fetch_clause(c, markers) s = _place_at(c, markers, after) or _fetch_clause(c, markers)
if s: if s:
return s return s
s = _place_step(c) or _say(c) s = _place_step(c) or _say(c)
@@ -808,7 +824,7 @@ _PUT_KO = r"(?:놔|놓아|놓고|내려놔|내려 ?놓고|둬|두고|놔두고|
_GIVE_AT_KO = r"(?:갖다 ?주고|갖다 ?줘|가져다 ?주고|가져다 ?줘|갖다 ?드리고|갖다 ?드려|전해 ?주고|전해 ?줘|배달해 ?주고|배달해)" _GIVE_AT_KO = r"(?:갖다 ?주고|갖다 ?줘|가져다 ?주고|가져다 ?줘|갖다 ?드리고|갖다 ?드려|전해 ?주고|전해 ?줘|배달해 ?주고|배달해)"
def _place_at(c, markers): def _place_at(c, markers, after=None):
""""put it on p3", "deliver the cup to p5", "컵을 p5에 갖다 놓고", "p3에 갖다 줘": (the named thing picked here,) a """"put it on p3", "deliver the cup to p5", "컵을 p5에 갖다 놓고", "p3에 갖다 줘": (the named thing picked here,) a
drive there, then put down (put / leave / 놔) or handed over (deliver / 갖다 줘). None otherwise.""" drive there, then put down (put / leave / 놔) or handed over (deliver / 갖다 줘). None otherwise."""
m = re.fullmatch(rf"(put|place|set|leave|drop|deliver|drop off) (?:it|that|this|the ((?:(?:{COL}) )?(?:{OBJ}))s?)" m = re.fullmatch(rf"(put|place|set|leave|drop|deliver|drop off) (?:it|that|this|the ((?:(?:{COL}) )?(?:{OBJ}))s?)"
@@ -816,12 +832,19 @@ def _place_at(c, markers):
if m: if m:
verb, thing, where = m.groups() verb, thing, where = m.groups()
else: else:
m = re.fullmatch(rf"(?:(?:이거|그거|이걸|그걸|((?:(?:{COL})\s*)?(?:{OBJ}))(?:을|를)?)\s+)?(.+?)(?:에다가?|에|로|으로) " thing = rf"(?:이거|그거|이걸|그걸|(?P<{{}}>(?:(?:{COL})\s*)?(?:{OBJ}))(?:을|를)?)"
rf"(?:(갖다|가져다|가져가서) ?)?({_PUT_KO}|{_GIVE_AT_KO})(?: 줘| 주고)?", c) m = re.fullmatch(rf"(?:{thing.format('a')}\s+)?(?P<where>.+?)(?:에다가?|에|로|으로) (?:{thing.format('b')}\s+)?"
if not m or (m.group(4) in ("갖다 줘", "갖다줘", "가져다 줘", "가져다줘") and not m.group(1)): rf"(?:(?:갖다|가져다|가져가서) ?)?(?P<verb>{_PUT_KO}|{_GIVE_AT_KO})(?: 줘| 주고)?", c) # "exit에 컵 갖다 놔" too
return None # "p3에 갖다 줘" alone: a fetch / give, not this if not m or (m["verb"] in ("갖다 줘", "갖다줘", "가져다 줘", "가져다줘") and not (m["a"] or m["b"]) and
thing, where = m.group(1), m.group(2) not (after and after["do"] in ("pick", "receive"))):
verb = "put" if re.fullmatch(_PUT_KO, m.group(4)) else "deliver" return None # "p3에 갖다 줘" alone: a fetch / give, not this (after
# "컵 집어서" / "받아서": the thing in hand, delivered there)
thing, where = m["a"] or m["b"], m["where"]
verb = "put" if re.fullmatch(_PUT_KO, m["verb"]) else "deliver"
on = None
sup = re.fullmatch(rf"(.+?)\s+((?:(?:{COL})\s*)?(?:{_SUP_KO}))(?:\s*위)?|((?:(?:{COL}) )?(?:{_SUP})s?) (?:at|in|by|near) (?:the )?(.+)", where)
if sup and verb == "put": # "exit 테이블에 놔", "put it on the table at p3": there, on that
where, on = sup.group(1) or sup.group(4), _support("on the " + sup.group(3) if sup.group(3) else sup.group(2))
to = _places(where, markers) to = _places(where, markers)
if not to or len(to) != 1 or to == ["here"]: if not to or len(to) != 1 or to == ["here"]:
return None return None
@@ -830,7 +853,7 @@ def _place_at(c, markers):
t = re.fullmatch(rf"(?:({COL})\s*)?({OBJ})", thing.strip()) t = re.fullmatch(rf"(?:({COL})\s*)?({OBJ})", thing.strip())
obj, col = _thing(t.group(1), t.group(2)) obj, col = _thing(t.group(1), t.group(2))
pick = [{"do": "pick", "object": obj, "colour": col}] pick = [{"do": "pick", "object": obj, "colour": col}]
return pick + [{"do": "go", "to": to[0]}, {"do": "give"} if verb == "deliver" else {"do": "place", "on": None}] return pick + [{"do": "go", "to": to[0]}, {"do": "give"} if verb == "deliver" else {"do": "place", "on": on}]
_FETCH_VERB = re.compile(r"\b(?:bring|fetch|get|carry|move)\b|가져|갖다|가지고|갖고|옮겨") _FETCH_VERB = re.compile(r"\b(?:bring|fetch|get|carry|move)\b|가져|갖다|가지고|갖고|옮겨")
+9
View File
@@ -70,6 +70,15 @@ Every value here is a constant at the top of its file, with a comment on what it
| `tasks/fetch.py` | `SEARCH_BASE_DEG` | 180°, 90° | Then the base turns towards the busier side, the first of these whose sweep is clear, and all again | | `tasks/fetch.py` | `SEARCH_BASE_DEG` | 180°, 90° | Then the base turns towards the busier side, the first of these whose sweep is clear, and all again |
| `tasks/fetch.py` | `LIFT_TRIES` | 0, 105 mm (`LIFT_RANGE`) | Nothing found: all of it again at the other end | | `tasks/fetch.py` | `LIFT_TRIES` | 0, 105 mm (`LIFT_RANGE`) | Nothing found: all of it again at the other end |
| `tasks/fetch.py` | `APPROACH_TRIES` | 5 | Base moves to bring an object into reach before asking the person | | `tasks/fetch.py` | `APPROACH_TRIES` | 5 | Base moves to bring an object into reach before asking the person |
| `tasks/fetch.py` | `PROGRESS_MM` | 40 mm | A base move that brought the object less than this nearer its goal (odometry) did nothing: that way is not tried again from there |
| `tasks/fetch.py` | `GOAL_SHIFTS_MM` | 0, −120, +120 mm | The straight way in aims the object at the pick zone, then this far to either side of it (a small turn and in) |
| `tasks/fetch.py` | `APPROACH_SIDES` | 0, ±45, ±90, ±135, 180° | Then navigation to each of these sides of the object, once; a side where the base can't stand near enough is skipped |
| `manipulation/skills.py` | `COMFORT_R_MM` | 710 mm | A cup further than this from the arm base (where the waist can bring it) is brought nearer by the base first when it can. Estimate |
| `manipulation/skills.py` | `TRUSTED_YAW_DEG` | 15° | Grasp turns up to this are tried first; larger ones only when the base can't bring the cup nearer |
| `tasks/fetch.py` | `KEPT_MM`, `TORSO_HALF_DEG` | 150 mm, 30° | After a base move the object is the one seen this near where its map place says; the waist turns the torso camera to it when it is further than this off the view |
| `tasks/fetch.py` | `GOAL_OUT_MM`, `VIEW_MARGIN_PX` | 0–200 mm in 20 mm steps, 10 px | The base brings a cup further out than the pick zone when the torso camera would not see its middle there (a low table); "in view" is this far inside the image |
| `tasks/fetch.py` | `NEAR_GAP_M`, `NEAR_BACK_M` | 0.15 m, 0.3 m | Nothing seen ahead and something this near the base: back off this much and look again before the whole search |
| `tasks/fetch.py` | `FAR_SPOTS` | 4 | Spots of a table seen further away tried from where the base stands before going closer |
| `tasks/fetch.py` | `WAIST_REACH_STEPS` | 0, ±15, ±30° | A pick out of reach: waist turns tried around the one bringing the object to the pick zone's bearing, before a base move | | `tasks/fetch.py` | `WAIST_REACH_STEPS` | 0, ±15, ±30° | A pick out of reach: waist turns tried around the one bringing the object to the pick zone's bearing, before a base move |
| `tasks/fetch.py` | `WAIST_FOUND_MM` | 80 mm | After that waist turn the object must be seen this near where it should be | | `tasks/fetch.py` | `WAIST_FOUND_MM` | 80 mm | After that waist turn the object must be seen this near where it should be |
| `manipulation/skills.py` | `IK_SEEDS` | ready, look, carry, give | Taught poses whose arm configurations (and wrist flips) seed the pick / place IK | | `manipulation/skills.py` | `IK_SEEDS` | ready, look, carry, give | Taught poses whose arm configurations (and wrist flips) seed the pick / place IK |
+167 -17
View File
@@ -7,6 +7,9 @@ point between the fingers where the cup's axis sits 4 cm below the rim. Down fro
python manipulation/skills.py plan [cup] [--to X Y] # dry run: object, place spot, every waypoint with IK joints python manipulation/skills.py plan [cup] [--to X Y] # dry run: object, place spot, every waypoint with IK joints
python manipulation/skills.py pick cup # pick it up and hold it 3 cm above the table python manipulation/skills.py pick cup # pick it up and hold it 3 cm above the table
python manipulation/skills.py move cup [--to X Y] # pick it up and put it down at X Y (mm, base frame) or a free spot python manipulation/skills.py move cup [--to X Y] # pick it up and put it down at X Y (mm, base frame) or a free spot
python manipulation/skills.py hover cup [TURN] # live check: the open hooks 6 cm over the cup's rim, grasp
# turned TURN deg; Enter goes back (docs/night5/P2.md)
python manipulation/skills.py offset T1 DX1 DY1 T2 DX2 DY2 [...] # hover readings -> the grasp point's error
Ctrl+C, cancel() (STOP in the API, "stop" by voice) or any motion error stops the arm; the gripper keeps its state. Ctrl+C, cancel() (STOP in the API, "stop" by voice) or any motion error stops the arm; the gripper keeps its state.
The API and the assistant call pick(), put_down(), move_object() and cancel() in their own process. The API and the assistant call pick(), put_down(), move_object() and cancel() in their own process.
@@ -27,6 +30,7 @@ from robot import arm
from vision import calib from vision import calib
from vision import camview from vision import camview
from robot import gripper from robot import gripper
from robot import kinematics
from robot import motion from robot import motion
from vision import objects from vision import objects
@@ -83,6 +87,8 @@ SPOT_DX = (-60, -90, -120, 60, 90, 120) # mm; candidate offsets from th
SPOT_DY = (0, -20, -40, 20) SPOT_DY = (0, -20, -40, 20)
TABLE_RING_MM = 50.0 # a place spot is checked at its centre and 8 points this far around TABLE_RING_MM = 50.0 # a place spot is checked at its centre and 8 points this far around
TABLE_TOL_MM = 25.0 # ... each must be table: depth within this of the table height TABLE_TOL_MM = 25.0 # ... each must be table: depth within this of the table height
TABLE_XY_MM = 20.0 # ... and the sight line aimed at that height meets it this near the
# point (X1's sweep: a spot 17 mm off the near edge passed, it fell)
TABLE_NEAR_RING_MM = 25.0 # a ring point on the near side the camera can't see (below its view TABLE_NEAR_RING_MM = 25.0 # a ring point on the near side the camera can't see (below its view
# at table height) is checked this far from the centre instead # at table height) is checked this far from the centre instead
LOCATE_MM = 90.0 # locate(): looked for this far around where an object was last seen, LOCATE_MM = 90.0 # locate(): looked for this far around where an object was last seen,
@@ -144,8 +150,28 @@ IK_SEEDS = ("ready", "look", "carry", "give") # taught poses whose arm configu
# seed, so one seed alone misses cups another configuration reaches # seed, so one seed alone misses cups another configuration reaches
WRIST_MIN_DEG = 10.0 # deg; |J5| at least this at above, grasp and lift (estimate: the WRIST_MIN_DEG = 10.0 # deg; |J5| at least this at above, grasp and lift (estimate: the
# proven picks had J5 +20; near 0 J4 / J6 swing round) # proven picks had J5 +20; near 0 J4 / J6 swing round)
RETRIES = 4 # the controller now and then answers with nothing: ask again TRUSTED_YAW_DEG = 15.0 # deg; grasp turns up to this picked live (-10, -15: 3 of 3); -30 and
RETRY_S = 0.2 # -45 missed 4 of 4 (2026-10-26, a finger end on the rim). The taught
# grasp point's horizontal error turns with the grasp (docs/night5/P2.md):
# a waist turn or a base move comes before a larger turn
COMFORT_R_MM = 710.0 # mm, cup's horizontal distance from the arm base origin: picks proven
# up to here (furthest live success (-68, 703)); further, the base moves
# in first when it can (tasks/fetch.py). Estimate until measured live
CARRY_UP_MM = (100.0, 200.0) # holding the cup: when the straight line to carry is refused (a joint
# jumps: carry has the elbow almost straight), straight up this much
# first, then one checked joint move to carry (carry_up)
HOVER_MM = 60.0 # hover(): the grasp point this far over the top (the fingers lie level
# near its height, owner's tape on the tips grasp; TIP_MM is a margin)
LINE_STEPS = 10 # ... that straight up is IK-checked at this many points
LINE_STEP_DEG = 25.0 # ... no joint turning more than this between two of them
OFFLINE_KINE = True # kine_forward / kine_inverse answered by robot/kinematics.py (fitted
# to the controller, < 0.5 mm): a plan asks hundreds, and the controller
# drops its connection under such bursts (2026-10-26 18:46). The
# controller confirms only the chosen plan (confirm)
CONFIRM_MM = 2.0 # mm; the controller's forward kinematics of planned joints within this
CONFIRM_DEG = 2.0 # deg; its inverse kinematics within this of the offline answer
RETRIES = 4 # the controller now and then answers with nothing: ask again,
RETRY_S = 0.2 # waiting this long, twice as long each time (it drops connections)
OPEN_AI = gripper.CLOSED_AI # AI_1 below this after opening = released OPEN_AI = gripper.CLOSED_AI # AI_1 below this after opening = released
_held = {} # what pick() holds: {"top_mm", "x", "y"} for place() / put_down() _held = {} # what pick() holds: {"top_mm", "x", "y"} for place() / put_down()
@@ -543,12 +569,23 @@ def on_table(spots_xy, table_mm=None):
ring = [(0.0, 0.0)] + [(TABLE_RING_MM * math.cos(a), TABLE_RING_MM * math.sin(a)) for a in angles] ring = [(0.0, 0.0)] + [(TABLE_RING_MM * math.cos(a), TABLE_RING_MM * math.sin(a)) for a in angles]
inner = [(0.0, 0.0)] + [(TABLE_NEAR_RING_MM * math.cos(a), TABLE_NEAR_RING_MM * math.sin(a)) for a in angles] inner = [(0.0, 0.0)] + [(TABLE_NEAR_RING_MM * math.cos(a), TABLE_NEAR_RING_MM * math.sin(a)) for a in angles]
guess = table_mm if table_mm is not None else -400.0 # only to find the pixels; the depth decides guess = table_mm if table_mm is not None else -400.0 # only to find the pixels; the depth decides
def heights(pts): # z of the surface at each point: the sight line aimed again at the height
first = surface_points(pts, guess) # it met must meet it at the point itself (a line just past the near
aim = [(p[0], p[1], q[2]) for p, q in zip(pts, first) if q is not None] # edge meets the top further on)
second = dict(zip([a[:2] for a in aim], surface_points(aim) if aim else []))
out = []
for p, q in zip(pts, first):
r = None if q is None else second[(p[0], p[1])]
out.append(None if r is None or math.hypot(r[0] - p[0], r[1] - p[1]) > TABLE_XY_MM else r[2])
return out
out = [] out = []
for x, y in spots_xy: for x, y in spots_xy:
zs = surface_heights([(x + dx, y + dy) for dx, dy in ring], guess) zs = heights([(x + dx, y + dy) for dx, dy in ring])
again = [i for i, z in enumerate(zs) if z is None and ring[i][1] < -1e-6] again = [i for i, z in enumerate(zs) if z is None and ring[i][1] < -1e-6]
if again: if again:
for i, z in zip(again, surface_heights([(x + inner[i][0], y + inner[i][1]) for i in again], guess)): for i, z in zip(again, heights([(x + inner[i][0], y + inner[i][1]) for i in again])):
zs[i] = z zs[i] = z
if None in zs: if None in zs:
continue continue
@@ -559,9 +596,18 @@ def on_table(spots_xy, table_mm=None):
# ---------- checking with the controller ---------- # ---------- checking with the controller ----------
def _ask(name, **args): def _offline():
"""arm.cmd with retries for empty answers / dropped connections.""" """Plans use the offline kinematics: OFFLINE_KINE and the real controller behind arm.cmd (a test's stand-in arm
for _ in range(RETRIES): answers its own kinematics)."""
return OFFLINE_KINE and arm.cmd is _ARM_CMD
def _ask(name, controller=False, **args):
"""arm.cmd with retries for empty answers / dropped connections; kine_forward / kine_inverse offline (_offline)
unless `controller`."""
if not controller and name in ("kine_forward", "kine_inverse") and _offline():
return kinematics.ask(name, **args)
for i in range(RETRIES):
try: try:
r = arm.cmd(name, **args) r = arm.cmd(name, **args)
except (ConnectionError, OSError): except (ConnectionError, OSError):
@@ -572,10 +618,34 @@ def _ask(name, **args):
r["jointPosition"] = r["jointPosition"][:6] # some answers carry a 7th (external axis) value r["jointPosition"] = r["jointPosition"][:6] # some answers carry a 7th (external axis) value
if "errorCode" in r and not empty: if "errorCode" in r and not empty:
return r # ("0" without the answer happens too: ask again) return r # ("0" without the answer happens too: ask again)
time.sleep(RETRY_S) time.sleep(RETRY_S * 2 ** i)
raise SkillError("The arm controller is not answering.") raise SkillError("The arm controller is not answering.")
def confirm(waypoints, ja):
"""The controller agrees with an offline plan (waypoints from `ja`, the joints at the first one): its forward
kinematics of `ja` is the first pose (CONFIRM_MM) and its inverse kinematics of the next one from `ja` is the
offline answer (CONFIRM_DEG: the same arm configuration). Two asks. True without asking for a plan made by a
stand-in (a test's _ask or arm)."""
if not _offline() or _ask is not _ASK:
return True
c = _ask("kine_forward", controller=True, jointPosition=[float(v) for v in ja])["cartPosition"]
if np.linalg.norm(np.subtract(c[:3], waypoints[0][1][:3])) > CONFIRM_MM:
log(f"the controller puts {[round(v) for v in c[:3]]} for the plan's {[round(v) for v in waypoints[0][1][:3]]}")
return False
r = _ask("kine_inverse", controller=True, jointPosition=[float(v) for v in ja], cartPosition=list(waypoints[1][1]))
mine = _ask("kine_inverse", jointPosition=[float(v) for v in ja], cartPosition=list(waypoints[1][1]))
if r["errorCode"] != "0" or mine["errorCode"] != "0" or \
max(abs(a - b) for a, b in zip(motion.nearest(r["jointPosition"], mine["jointPosition"]),
mine["jointPosition"])) > CONFIRM_DEG:
log(f"the controller's IK of {waypoints[1][0]} differs from the plan's")
return False
return True
_ASK, _ARM_CMD = _ask, arm.cmd
def _joints(): def _joints():
for _ in range(RETRIES): for _ in range(RETRIES):
try: try:
@@ -688,16 +758,24 @@ def checked(waypoints, start_joints):
return rows return rows
def pick_options(obj, start): def pick_options(obj, start, max_yaw=None):
"""(waypoints, joints above) of every grasp turn (GRASP_YAWS) and wrist solution reachable from `start`: a joint """(waypoints, joints above) of every grasp turn (GRASP_YAWS; within `max_yaw` deg when given) and wrist solution
move down to above that stays above it, then straight down and up. Objects of the wrong width raise.""" reachable from `start`: a joint move down to above that stays above it, then straight down and up; the controller
confirms each one given. Objects of the wrong width raise."""
plan_pick(obj) plan_pick(obj)
tried = []
for seeds in (IK_SEEDS[:1], IK_SEEDS[1:]): # the proven `ready` configuration at every turn first for seeds in (IK_SEEDS[:1], IK_SEEDS[1:]): # the proven `ready` configuration at every turn first
for yaw in GRASP_YAWS: for yaw in GRASP_YAWS:
if max_yaw is not None and abs(yaw) > max_yaw:
continue
waypoints = plan_pick(obj, yaw) waypoints = plan_pick(obj, yaw)
for ja in above_joints(waypoints[0][1], start, seeds): for ja in above_joints(waypoints[0][1], start, seeds):
if any(y == yaw and max(abs(a - b) for a, b in zip(t, ja)) <= 1.0 for y, t in tried):
continue # another seed found the same solution
tried.append((yaw, ja))
rows = ik_chain(waypoints[1:], ja) rows = ik_chain(waypoints[1:], ja)
if not rows[-1][3] and wrist_ok([ja] + [r[2] for r in rows]) and move_ok(start, ja): if not rows[-1][3] and wrist_ok([ja] + [r[2] for r in rows]) and move_ok(start, ja) and \
confirm(waypoints, ja):
yield waypoints, ja yield waypoints, ja
@@ -729,7 +807,7 @@ def place_options(x, y, top_mm, start):
for ja in above_joints(way[0][1], start): for ja in above_joints(way[0][1], start):
rows = ik_chain(way[1:], ja) rows = ik_chain(way[1:], ja)
if not rows[-1][3] and wrist_ok([ja] + [r[2] for r in rows]) and move_ok(start, ja) and \ if not rows[-1][3] and wrist_ok([ja] + [r[2] for r in rows]) and move_ok(start, ja) and \
tilt_on(start, ja) <= MAX_TILT_DEG: tilt_on(start, ja) <= MAX_TILT_DEG and confirm(way, ja):
yield way, ja yield way, ja
@@ -741,16 +819,46 @@ def place_turned(way, ja):
_do_place(way) _do_place(way)
def reachable_pick(obj, start=None, accept=lambda waypoints, ja: True): def carry_up(above, ja):
"""(waypoints, joints above) of the first pick option from `start` (home) that `accept` also takes, else None.""" """Another way to carry for a held cup whose straight line from above the pick spot (flange pose `above`, joints
for waypoints, ja in pick_options(obj, home_joints() if start is None else start): `ja`) to carry is refused: straight up CARRY_UP_MM (IK at LINE_STEPS points, no joint turning more than
LINE_STEP_DEG between two, J5 off 0), then one joint move to carry, the cup upright, clear of the head, no dip
(arm_route.check_moves). (pose up there, carry joints) or None."""
from manipulation import arm_route
for dz in CARRY_UP_MM:
rows = ik_chain([(f"up {k}", up(above, dz * k / LINE_STEPS)) for k in range(1, LINE_STEPS + 1)], ja)
if rows[-1][3]:
continue
js = [list(ja)] + [r[2] for r in rows]
if max(abs(b - a) for p, q in zip(js, js[1:]) for a, b in zip(p, q)) > LINE_STEP_DEG or not wrist_ok(js):
continue
try:
return rows[-1][1], arm_route.check_moves(js[-1], [motion.poses()["carry"]], holding=True)[0]
except arm_route.RouteError:
continue
return None
def carry_by_joints(plan):
"""Run a carry_up() plan from above the pick spot: straight up, then the joint move to carry."""
_line("up to carry", plan[0])
_go_on()
log("carry: joint move")
motion.move_joints(plan[1], HOLDING_SPEED)
def reachable_pick(obj, start=None, accept=lambda waypoints, ja: True, max_yaw=None):
"""(waypoints, joints above) of the first pick option from `start` (home), grasp turned at most `max_yaw` deg
(e.g. TRUSTED_YAW_DEG; None: any), that `accept` also takes, else None."""
for waypoints, ja in pick_options(obj, home_joints() if start is None else start, max_yaw):
if accept(waypoints, ja): if accept(waypoints, ja):
yaw = round(yaw_of(waypoints[1][1])) yaw = round(yaw_of(waypoints[1][1]))
how = "between the tips" if grip_width(obj) < BELLY_MIN_MM else "in the hooks" how = "between the tips" if grip_width(obj) < BELLY_MIN_MM else "in the hooks"
log(f"grasp {how}, turned {yaw:+d} deg, wrist J5 {ja[4]:+.0f}" if yaw else log(f"grasp {how}, turned {yaw:+d} deg, wrist J5 {ja[4]:+.0f}" if yaw else
f"grasp {how}, wrist J5 {ja[4]:+.0f}") f"grasp {how}, wrist J5 {ja[4]:+.0f}")
return waypoints, ja return waypoints, ja
log(f"plan refused: no grasp turn reaches ({obj['x']:.0f}, {obj['y']:.0f})") log(f"plan refused: no grasp turn{'' if max_yaw is None else f' within {max_yaw:.0f} deg'} reaches "
f"({obj['x']:.0f}, {obj['y']:.0f})")
return None return None
@@ -935,6 +1043,41 @@ def move_object(name="cup", colour=None, to=None):
return xy return xy
def hover(name="cup", yaw=0.0):
"""Live check of the grasp point (docs/night5/P2.md): the pick of `name` planned with the grasp turned `yaw` deg,
slow, down to the grasp point HOVER_MM above its top (the hooks' ring over the rim, nothing touches, the gripper
stays open); Enter: back up and home. The owner reads how far the ring's centre is from the rim's centre."""
_cancel.clear()
obj = find(name)
log(f"found {obj['colour']} {obj['name']} at ({obj['x']:.0f}, {obj['y']:.0f}) top {obj['top_mm']:.0f}")
way, ja = next(((w, j) for w, j in pick_options(obj, home_joints()) if round(yaw_of(w[1][1])) == round(yaw)),
(None, None))
if way is None:
raise SkillError(f"No grasp turned {yaw:+.0f} deg reaches it.")
_prepare()
_go_on()
log(f"above: joint move, grasp turned {yaw:+.0f} deg, wrist J5 {ja[4]:+.0f}")
motion.move_joints(ja, HOLDING_SPEED)
_line("hover", up(way[1][1], obj["top_mm"] - grasp_height(obj) + HOVER_MM))
input(f"hooks {HOVER_MM:.0f} mm over the rim, cup seen at ({obj['x']:.0f}, {obj['y']:.0f}): read the offset, "
f"then Enter ")
_line("up", way[0][1])
_back_home()
def offset_fix(reports):
"""From hover() readings [(grasp turn deg, ring centre minus rim centre (dx, dy) mm, arm frame)] at one cup spot,
with at least two turns: (u, e, new tcp_offset_flange). u: the taught grasp point's horizontal error (it turns
with the grasp), e: the camera's error at that spot (it does not). Reading = e - Rz(turn) u, least squares."""
A, b = [], []
for yaw, d in reports:
A += list(np.hstack([np.eye(2), -_rz(yaw)[:2, :2]]))
b += list(d)
e_u = np.linalg.lstsq(np.array(A), np.array(b, float), rcond=None)[0]
u = np.array([*e_u[2:], 0.0])
return u[:2], e_u[:2], GRASP_OFFSET - calib.rpy_matrix(*GRASP_RPY).T @ u
def _dry_run(name, to): def _dry_run(name, to):
seen = look() seen = look()
for o in seen: for o in seen:
@@ -966,6 +1109,13 @@ if __name__ == "__main__":
pick(a[1] if len(a) > 1 else "cup") pick(a[1] if len(a) > 1 else "cup")
elif a[:1] == ["move"]: elif a[:1] == ["move"]:
move_object(a[1] if len(a) > 1 else "cup", to=to) move_object(a[1] if len(a) > 1 else "cup", to=to)
elif a[:1] == ["hover"]:
hover(a[1] if len(a) > 1 else "cup", float(a[2]) if len(a) > 2 else 0.0)
elif a[:1] == ["offset"] and len(a) >= 7 and len(a) % 3 == 1:
v = [float(x) for x in a[1:]]
u, e, new = offset_fix([(v[i], v[i + 1:i + 3]) for i in range(0, len(v), 3)])
print(f"grasp point error {u.round(1)} mm, camera error {e.round(1)} mm; "
f"tcp_offset_flange {[round(float(x), 1) for x in new]} (was {GRASP_OFFSET.tolist()})")
else: else:
sys.exit(__doc__) sys.exit(__doc__)
except SkillError as e: except SkillError as e:
+9 -8
View File
@@ -26,7 +26,7 @@ URDF_JOINTS = (((0, 0, 0), (3.1416, 1.5708, 0)), # jaka_lumi.u
((0.1303, 0, 0.0185), (-1.5708, 0, -1.5708)), ((0.1303, 0, 0.0185), (-1.5708, 0, -1.5708)),
((0, -0.01805, 0.0802), (1.5708, 1.5708, 0)), ((0, -0.01805, 0.0802), (1.5708, 1.5708, 0)),
((-0.1233, 0, 0.01805), (1.5708, 0, -1.5708))) ((-0.1233, 0, 0.01805), (1.5708, 0, -1.5708)))
IK_ITERS = 60 # Newton steps at most IK_ITERS = 30 # Newton steps at most (a reachable pose took at most 19)
IK_TOL_MM, IK_TOL_RAD = 0.01, 1e-5 # converged when the pose is this close IK_TOL_MM, IK_TOL_RAD = 0.01, 1e-5 # converged when the pose is this close
IK_STEP_DEG = 20.0 # no joint turns more than this in one step (keeps the seed's branch) IK_STEP_DEG = 20.0 # no joint turns more than this in one step (keeps the seed's branch)
@@ -70,9 +70,9 @@ def chain(joints, model=None):
for F, q, off in zip(frames, joints, offsets): for F, q, off in zip(frames, joints, offsets):
T = T @ F T = T @ F
a = math.radians(q) + off a = math.radians(q) + off
Rz = np.eye(4) c, s = math.cos(a), math.sin(a)
Rz[:2, :2] = [[math.cos(a), -math.sin(a)], [math.sin(a), math.cos(a)]] T = T.copy()
T = T @ Rz T[:, :2] = np.stack([c * T[:, 0] + s * T[:, 1], c * T[:, 1] - s * T[:, 0]], axis=1) # T @ Rz(a)
out.append(T) out.append(T)
return out return out
@@ -115,10 +115,11 @@ def ik(target, seed):
e = np.concatenate([goal[:3, 3] - T[:3, 3], T[:3, :3] @ _rotvec(T[:3, :3].T @ goal[:3, :3])]) e = np.concatenate([goal[:3, 3] - T[:3, 3], T[:3, :3] @ _rotvec(T[:3, :3].T @ goal[:3, :3])])
if np.linalg.norm(e[:3]) < IK_TOL_MM and np.linalg.norm(e[3:]) < IK_TOL_RAD: if np.linalg.norm(e[:3]) < IK_TOL_MM and np.linalg.norm(e[3:]) < IK_TOL_RAD:
return [float(v) for v in (q + 180.0) % 360.0 - 180.0] # the same pose; within +-180 like a fresh answer return [float(v) for v in (q + 180.0) % 360.0 - 180.0] # the same pose; within +-180 like a fresh answer
J = np.zeros((6, 6)) F = np.array(frames[1:7])
for i in range(6): Z, O = F[:, :3, 2], F[:, :3, 3] # each joint's axis and origin
z, o = frames[i + 1][:3, 2], frames[i + 1][:3, 3] d = T[:3, 3] - O
J[:3, i], J[3:, i] = np.cross(z, T[:3, 3] - o), z J = np.vstack([np.array([Z[:, 1] * d[:, 2] - Z[:, 2] * d[:, 1], Z[:, 2] * d[:, 0] - Z[:, 0] * d[:, 2],
Z[:, 0] * d[:, 1] - Z[:, 1] * d[:, 0]]), Z.T]) # axis x (flange - origin), axis
e[3:] *= 100.0 # 1 rad weighs as 100 mm e[3:] *= 100.0 # 1 rad weighs as 100 mm
J[3:] *= 100.0 J[3:] *= 100.0
dq = np.degrees(np.linalg.lstsq(J, e, rcond=None)[0]) dq = np.degrees(np.linalg.lstsq(J, e, rcond=None)[0])
+334 -83
View File
@@ -66,6 +66,9 @@ FAR_HALF_DEG = 45 # ... within this of where the camera looks
FAR_STEP_DEG = 3 # ... every this many degrees FAR_STEP_DEG = 3 # ... every this many degrees
FAR_IN_MM = 150.0 # the base brings the table point this far in from its nearest one (the edge) to FAR_IN_MM = 150.0 # the base brings the table point this far in from its nearest one (the edge) to
# PLACE_GOAL: the place grid then lies on the table # PLACE_GOAL: the place grid then lies on the table
BIG_TOPS = ("dining table", "desk", "bed") # things named for a place whose YOLO box centre is no place to aim at
FAR_REACH_MM = 850.0 # mm from the arm base; level points of a far table past this are out of reach
FAR_SPOTS = 4 # spots of a table further away tried from where the base is (_place_far)
TOP_NEAR_MM = 1500.0 # mm from the arm base; a named thing's top measured further away is not trusted TOP_NEAR_MM = 1500.0 # mm from the arm base; a named thing's top measured further away is not trusted
# (2026-10-20 a white thing 3.8 m away read -258, then -620 mm): go closer first # (2026-10-20 a white thing 3.8 m away read -258, then -620 mm): go closer first
KNOWN_M = 0.5 # m; a thing seen this near where it was taught is that thing KNOWN_M = 0.5 # m; a thing seen this near where it was taught is that thing
@@ -74,6 +77,7 @@ NEAR_THING_MM = 400.0 # mm; place grid spots this near a named th
SUPPORT_NEAR_MM = 400.0 # mm; a surface is named after the thing the camera sees this near it ("the grey table") SUPPORT_NEAR_MM = 400.0 # mm; a surface is named after the thing the camera sees this near it ("the grey table")
FURNITURE = {"dining table", "chair", "couch", "bench", "bed", "sink", "toilet", "desk"} # camera classes the FURNITURE = {"dining table", "chair", "couch", "bench", "bed", "sink", "toilet", "desk"} # camera classes the
# cameras mix up for one piece of furniture: a named one matches any of them # cameras mix up for one piece of furniture: a named one matches any of them
LOW_TABLE_Z = -420.0 # mm, arm frame at lift 0: a lower table top is seen only out of the arm's reach (X1's sweep)
TABLE_PROVEN_Z = -403.0 # mm, arm base frame: the table top of every proven pick and place (lift 75 mm) TABLE_PROVEN_Z = -403.0 # mm, arm base frame: the table top of every proven pick and place (lift 75 mm)
SURFACE_Z = (-560.0, -30.0) # mm, arm frame, after the lift: table tops the arm can pick from / put on at all (IK of SURFACE_Z = (-560.0, -30.0) # mm, arm frame, after the lift: table tops the arm can pick from / put on at all (IK of
# the grasp, 2026-10-16: -578 4 of 9 spots, -528 7 of 9, -28 9 of 9). Lower: a floor or a # the grasp, 2026-10-16: -578 4 of 9 spots, -528 7 of 9, -28 9 of 9). Lower: a floor or a
@@ -94,12 +98,23 @@ SAME_BASE_RAD = 0.035
WAIST_REACH_STEPS = (0.0, 15.0, -15.0, 30.0, -30.0) # deg; a pick out of reach: waist turns tried around the one WAIST_REACH_STEPS = (0.0, 15.0, -15.0, 30.0, -30.0) # deg; a pick out of reach: waist turns tried around the one
# that brings the object to PICK_ZONE_CENTRE's bearing about the column (the waist carries # that brings the object to PICK_ZONE_CENTRE's bearing about the column (the waist carries
# the arm round the column: what it reaches beside it, it reaches ahead), before a base move # the arm round the column: what it reaches beside it, it reaches ahead), before a base move
GOAL_OUT_MM = range(0, 201, 20) # mm; the pick goal moves this far out from PICK_ZONE_CENTRE when the torso camera
# would not see the cup there (a low table at lift 0)
VIEW_MARGIN_PX = 10 # px; "in view" means this far inside the torso camera's image
KEPT_MM = 150.0 # mm; after a base move the thing is the one seen this near where its map place says
TORSO_HALF_DEG = 30.0 # deg; a kept thing further than this to a side of the torso camera's view: the waist turns
WAIST_FOUND_MM = 80.0 # mm; after that turn the object is looked for this near where it should be seen WAIST_FOUND_MM = 80.0 # mm; after that turn the object is looked for this near where it should be seen
APPROACH_TRIES = 5 # base moves to bring an object out of reach to PICK_ZONE_CENTRE before asking the person APPROACH_TRIES = 5 # base moves to bring an object out of reach to PICK_ZONE_CENTRE before asking the person
STRAIGHT_MAX_M = 0.6 # m; a straight drive (after a turn on the spot) at most this long, else navigation STRAIGHT_MAX_M = 0.6 # m; a straight drive (after a turn on the spot) at most this long, else navigation
STANDOFF_M = 0.4 # m; navigation goes to this far back from the pick pose, then straight in STANDOFF_M = 0.4 # m; navigation goes to this far back from the pick pose, then straight in
APPROACH_SIDES = (0, 45, -45, 90, -90, 135, -135, 180) # deg; ways in to the object tried by navigation, the APPROACH_SIDES = (0, 45, -45, 90, -90, 135, -135, 180) # deg; ways in to the object tried by navigation, the
# direct one first (a table side may be blocked) # direct one first (a table side may be blocked)
GOAL_SHIFTS_MM = (0.0, -120.0, 120.0) # mm, arm x; the straight way in aims the object at the goal, then this far to
# either side of it (a small turn and in: the arm reaches there too, R1's reach map)
ROOMY_M = 0.2 # m; sides whose stand has this much more room than the base needs are driven to first
NAV_SAME_M = 0.15 # m; a navigation goal this near one that left the base where it was is not sent again
PROGRESS_MM = 40.0 # mm; a base move that brought the object less than this nearer its goal (odometry) did
# nothing (the base stood still at a table, 2026-10-26: +0.13 m "driven" six times)
BASE_HALF_M = 0.255 # m; half the base's 510 mm (docs/01) ... BASE_HALF_M = 0.255 # m; half the base's 510 mm (docs/01) ...
CLEAR_M = 0.05 # ... plus this: a straight drive stops where the base would get closer to an obstacle CLEAR_M = 0.05 # ... plus this: a straight drive stops where the base would get closer to an obstacle
PROBE_STEP_M = 0.05 # m between the points checked along a straight drive PROBE_STEP_M = 0.05 # m between the points checked along a straight drive
@@ -108,6 +123,9 @@ FURNITURE_ANGLES = (45, 90, 135) # deg left / right of the heading ...
FURNITURE_RANGES = (0.6, 1.0, 1.4) # ... and m from the base centre where the first search turn looks for things FURNITURE_RANGES = (0.6, 1.0, 1.4) # ... and m from the base centre where the first search turn looks for things
FURNITURE_HIT_M = 0.3 # ... the lidar sees now (closer than this) and the map does not have (nothing FURNITURE_HIT_M = 0.3 # ... the lidar sees now (closer than this) and the map does not have (nothing
FURNITURE_MAP_M = 0.5 # on the map this near): tables, chairs, boxes, where an object most likely stands FURNITURE_MAP_M = 0.5 # on the map this near): tables, chairs, boxes, where an object most likely stands
NEAR_GAP_M = 0.4 # m; something this near the base's outline when nothing is seen ahead: back off ...
NEAR_BACK_M = 0.3 # ... this much and look again before the whole search (a cup < ~450 mm from the column
# is below both cameras, X1's sweep)
LOST_BACK_M = 0.15 # an object lost after a base move: back off this much (the camera sees more) ... LOST_BACK_M = 0.15 # an object lost after a base move: back off this much (the camera sees more) ...
LOST_TURN_DEG = 20.0 # ... and turn this much each way, looking again (YOLO, then depth where it should be) LOST_TURN_DEG = 20.0 # ... and turn this much each way, looking again (YOLO, then depth where it should be)
ARM_CLEAR_M = 0.10 # m; flange, grasp point and finger tips kept this far from anything the lidar or the map ARM_CLEAR_M = 0.10 # m; flange, grasp point and finger tips kept this far from anything the lidar or the map
@@ -173,6 +191,8 @@ PICK_TRIES = 2 # a pick that missed or slipped is looked for and t
MISSES = ("I missed it.", "It slipped out of my hand.") # skills._do_pick's reasons for those MISSES = ("I missed it.", "It slipped out of my hand.") # skills._do_pick's reasons for those
_lock = threading.RLock() # _finish sets the state while it holds it _lock = threading.RLock() # _finish sets the state while it holds it
_width_far = {"moves": 0} # base moves of this _reach so far (_reachable believes a far width after one)
_last_held = {} # held_object and skills._held of the thing forgotten last (_hold_again)
_stop = threading.Event() # set by stop(): every step and every wait gives up _stop = threading.Event() # set by stop(): every step and every wait gives up
_release = threading.Event() # set by release_now() ("thank you" / Release while giving) _release = threading.Event() # set by release_now() ("thank you" / Release while giving)
_proceed = threading.Event() # set by proceed() ("go on" while a mission waits): the wait ends _proceed = threading.Event() # set by proceed() ("go on" while a mission waits): the wait ends
@@ -977,23 +997,26 @@ def _find(task, seen=None):
def _carry_ok(waypoints, ja): def _carry_ok(waypoints, ja):
"""After the pick the arm goes straight up to above, then straight to carry with the cup: check that line now.""" """After the pick the arm goes straight up to above, then straight to carry with the cup (or, when that line jumps,
further up and one joint move: skills.carry_up): check that now."""
target = skills._ask("kine_forward", jointPosition=[float(v) for v in motion.poses()["carry"]])["cartPosition"] target = skills._ask("kine_forward", jointPosition=[float(v) for v in motion.poses()["carry"]])["cartPosition"]
try: try:
_line_rows(target, "to carry", start=(waypoints[0][1], ja)) _line_rows(target, "to carry", start=(waypoints[0][1], ja))
return True return True
except FetchError: except FetchError:
return False return skills.carry_up(waypoints[0][1], ja) is not None
def _reachable(obj): def _reachable(obj, max_yaw=skills.TRUSTED_YAW_DEG):
"""(waypoints, joints above) of a pick from look (any grasp turn, either wrist) after which the cup can go """(waypoints, joints above) of a pick from look (grasp turns up to `max_yaw`, None: any; either wrist) after which
straight to carry, else None. Wrong-size objects raise, but only when measured near: from further away the width the cup can go to carry, else None. Wrong-size objects raise, but only when measured near: from further away the
is not trusted, the base goes closer and it is measured again.""" width is not trusted, the base goes closer once and it is measured again (after that move it is believed: a
small cup was chased again and again, X1's sweep)."""
try: try:
return skills.reachable_pick(obj, accept=_carry_ok) return skills.reachable_pick(obj, accept=_carry_ok, max_yaw=max_yaw)
except skills.SkillError: except skills.SkillError:
if math.hypot(obj["x"] - PICK_ZONE_CENTRE[0], obj["y"] - PICK_ZONE_CENTRE[1]) <= WIDTH_NEAR_MM: if math.hypot(obj["x"] - PICK_ZONE_CENTRE[0], obj["y"] - PICK_ZONE_CENTRE[1]) <= WIDTH_NEAR_MM or \
_width_far["moves"]:
raise raise
log(f"width {obj.get('width_mm')} mm measured from further away: I'll measure it again up close") log(f"width {obj.get('width_mm')} mm measured from further away: I'll measure it again up close")
return None return None
@@ -1099,7 +1122,15 @@ def _see(task, say=None):
tried, close = set(), [] tried, close = set(), []
attempt = lambda: _find_any(task, close) or _head_seen(lambda o: _is_task(o, task)) attempt = lambda: _find_any(task, close) or _head_seen(lambda o: _is_task(o, task))
for i in range(APPROACH_TRIES + 1): for i in range(APPROACH_TRIES + 1):
obj = _look_around(attempt, say=say) if i == 0 else _look_at(0.0, attempt) # one whole search obj = _look_at(0.0, attempt)
if obj is None and i == 0 and not stay_put and not _charging():
x, y, _ = agv.pose()
if agv.clearance(x, y) < BASE_HALF_M + NEAR_GAP_M: # a table right at the base: a cup on it is under
log("something right in front of me: backing off to see what is on it") # both cameras' view
_straight_clear(-NEAR_BACK_M)
obj = _look_at(0.0, attempt)
if obj is None and i == 0:
obj = _look_around(attempt, say=say) # one whole search
if obj is None: if obj is None:
break break
if not obj.get("head"): if not obj.get("head"):
@@ -1179,67 +1210,105 @@ def _straight_clear(dist, speed=None, stop=True):
return free return free
def _straight_went(dist):
"""_straight_clear, but the distance the base pose really went (m): a base that stood still (its own obstacle
stop, 2026-10-26: the same +0.15 m "driven" three times, the cup never nearer) counts as blocked."""
x0, y0, th0 = agv.pose()
driven = _straight_clear(dist)
x, y, _ = agv.pose()
real = abs((x - x0) * math.cos(th0) + (y - y0) * math.sin(th0))
if driven >= MOVED_CHECK_M and real < MOVED_MIN_PART * driven:
log(f"the base went {real:.2f} m of {driven:.2f} m driven: another way")
return real
return driven
def rolling_lead(speed): def rolling_lead(speed):
"""How far (m) the base can roll on at `speed` (m/s or a function) after its last joy_control command.""" """How far (m) the base can roll on at `speed` (m/s or a function) after its last joy_control command."""
return (speed() if callable(speed) else speed or AXIS_SPEED) * JOY_HOLD_S return (speed() if callable(speed) else speed or AXIS_SPEED) * JOY_HOLD_S
def _approach(obj, yaw, tried, goal=PICK_ZONE_CENTRE, holding=False): def _approach(obj, yaw, tried, goal=PICK_ZONE_CENTRE, holding=False):
"""One base move that should bring `obj` (x, y in the arm frame) to `goal`: turn on the spot and drive straight """One base move that brings `obj` (x, y in the arm frame) nearer `goal`: turn on the spot and drive straight when
when the way is short and free; else navigation (around obstacles) to a stand-off point on a side of it not in the way is short and free (to the goal, then to the goal shifted sideways by GOAL_SHIFTS_MM: a small turn and in);
`tried`, facing it. FetchError when no side can be reached, or Patrol is off (stay_put).""" else navigation (around obstacles) to a stand-off point on a side of it not in `tried`, facing it. Every move is
measured by the base's odometry: one that did not bring the object PROGRESS_MM nearer the goal (the base stood
still: a table in front, its own safety stop) is not tried again from there (kept in `tried`), nor a navigation
goal that left the base where it was; the next way follows at once; sides with room to stand first. True when the
base moved, False when it is where it can bring the object already. FetchError saying so when no way is left, or
Patrol is off (stay_put)."""
if stay_put: if stay_put:
raise FetchError(*NEED_PATROL) raise FetchError(*NEED_PATROL)
t = arm_xy() t = arm_xy()
move = approach_move((obj["x"], obj["y"]), yaw, t, goal) x0, y0, th0 = agv.pose()
if move is None: world = np.array([x0, y0]) + _rot(math.degrees(th0)) @ to_base((obj["x"], obj["y"]), yaw, t)
def now(): # the object in the arm frame now (mm), by odometry
x, y, th = agv.pose()
return _rot(-yaw) @ (_rot(-math.degrees(th)) @ (world - [x, y]) - t) * 1000.0
left = lambda: math.hypot(now()[0] - goal[0], now()[1] - goal[1])
if approach_move(now(), yaw, t, goal) is None:
log("it is too near me: backing off") log("it is too near me: backing off")
if _straight_clear(-STANDOFF_M) < PROBE_STEP_M: if _straight_clear(-STANDOFF_M) < PROBE_STEP_M:
raise FetchError("It is too close to me and I can't back off.") raise FetchError("It is too close to me and I can't back off.", "너무 가까운데 뒤로 물러날 수 없어요.")
return return True
why = []
for dx in GOAL_SHIFTS_MM: # the straight way in, then a small turn and in
x, y, _ = agv.pose()
g, before = (goal[0] + dx, goal[1]), left()
move = approach_move(now(), yaw, t, g)
if dx and agv.clearance(x, y) < BASE_HALF_M + CLEAR_M + PROBE_STEP_M:
break # flush at something: a small turn won't get it in (X1's sweep)
if move is None or abs(move[1]) > STRAIGHT_MAX_M or any(
k[0] == "straight" and k[3] == dx and math.hypot(k[1] - x, k[2] - y) < SAME_PLACE_M
for k in tried if isinstance(k, tuple)):
continue
turn, s = move turn, s = move
log(f"to bring it to ({goal[0]:.0f}, {goal[1]:.0f}): turn {turn:+.0f} deg, straight {s:+.2f} m") if abs(turn) < TURN_MIN_DEG and abs(s) < PROBE_STEP_M:
if abs(s) <= STRAIGHT_MAX_M: log("I am where the base can bring it already")
turned = abs(turn) < TURN_MIN_DEG or _turn(turn, holding, why="to face it") return False # there already: not a move
if turned: tried.add(("straight", x, y, dx))
turn = 0.0 log(f"to bring it to ({g[0]:.0f}, {g[1]:.0f}): turn {turn:+.0f} deg, straight {s:+.2f} m")
if turned and (abs(s) < PROBE_STEP_M or _straight_went(s) >= PROBE_STEP_M): if abs(turn) >= TURN_MIN_DEG and not _turn(turn, holding, why="to face it"):
return # else the turn or the straight way is blocked: go round why.append("turning")
continue
if abs(s) >= PROBE_STEP_M:
_straight_clear(s)
gain = before - left()
if gain >= PROGRESS_MM:
return True
log(f"that move brought it only {gain:.0f} mm nearer: another way")
why.append("something in front of me")
x, y, th = agv.pose() x, y, th = agv.pose()
world = np.array([x, y]) + _rot(math.degrees(th)) @ to_base((obj["x"], obj["y"]), yaw, t) move = approach_move(now(), yaw, t, goal)
facing = th + math.radians(turn) facing = th + math.radians(move[0] if move else 0.0)
_waist_front() # the lift stays: a short move, the look after it is at this lift _waist_front() # the lift stays: a short move, the look after it is at this lift
sides = []
for side in APPROACH_SIDES: for side in APPROACH_SIDES:
if side in tried: if side in tried:
continue continue
tried.add(side)
sx, sy, sth = side_pose(world, facing + math.radians(side), yaw, t, goal=goal) sx, sy, sth = side_pose(world, facing + math.radians(side), yaw, t, goal=goal)
sth = (sth + math.pi) % (2 * math.pi) - math.pi px, py, _ = side_pose(world, facing + math.radians(side), yaw, t, back=0.0, goal=goal)
n = max(1, math.ceil(STANDOFF_M / PROBE_STEP_M))
room = min(agv.clearance(sx + (px - sx) * k / n, sy + (py - sy) * k / n) for k in range(1, n + 1))
if room < BASE_HALF_M + CLEAR_M: # where it would reach it from, or the way in to there: in the
log(f"from {side:+d} deg I can't get near enough ({px:.2f}, {py:.2f})") # table, a chair, a wall
why.append("no room to stand")
elif any(k[0] == "nav" and math.hypot(k[1] - sx, k[2] - sy) < NAV_SAME_M for k in tried if isinstance(k, tuple)):
log(f"from {side:+d} deg: navigation already left me where I was going there")
else:
sides.append((room < BASE_HALF_M + CLEAR_M + ROOMY_M, side, sx, sy, (sth + math.pi) % (2 * math.pi) - math.pi))
for _, side, sx, sy, sth in sorted(sides, key=lambda c: c[0]): # sides with room to stand first (a chair in front)
tried.add(side) # (one skipped for room is looked at again from the next place)
log(f"driving round to ({sx:.2f}, {sy:.2f}) to come in from {side:+d} deg") log(f"driving round to ({sx:.2f}, {sy:.2f}) to come in from {side:+d} deg")
go = lambda: agv.go_point(sx, sy, sth) go = lambda: agv.go_point(sx, sy, sth)
ok, msg = go() ok, msg = go()
if not ok: if not ok:
log(f"no way there: {msg}") log(f"no way there: {msg}")
why.append("no way round")
continue continue
try: try:
_wait_drive(watch_holding=holding, again=go, goal=(sx, sy, sth)) _wait_drive(watch_holding=holding, again=go, goal=(sx, sy, sth))
return
except FetchError as e: except FetchError as e:
log(f"no way there: {e}") log(f"no way there: {e}")
raise FetchError("I can't find a way to get close to it.", "가까이 갈 길을 못 찾겠어요.") why.append("no way round")
continue
p = agv.pose()
if math.hypot(p[0] - x, p[1] - y) >= PROGRESS_MM / 1000.0 or \
abs((p[2] - th + math.pi) % (2 * math.pi) - math.pi) >= math.radians(TURN_MIN_DEG):
return True # at another side: the straight way in follows from there
tried.add(("nav", sx, sy))
log("navigation left me where I was: another side")
why.append("navigation did not move me")
log(f"no way left to get closer ({', '.join(dict.fromkeys(why)) or 'every side tried'})")
raise FetchError("I can't get closer to it: every way I tried was blocked.",
"가까이 가려고 여러 방향을 해 봤는데 다 막혀 있어요.")
def _learn_offset(before, after, yaw): def _learn_offset(before, after, yaw):
@@ -1281,12 +1350,31 @@ def expected(mem, yaw):
return (float(xy[0]), float(xy[1])), mem["top"] - down, mem["table"] - down return (float(xy[0]), float(xy[1])), mem["top"] - down, mem["table"] - down
def _kept(task, mem):
"""The task's thing the torso camera sees steadily nearest where `mem` keeps it on the map (within KEPT_MM of where
it should be seen from here), None when not there."""
xy = expected(mem, arm_yaw())[0]
hits = [o for o in skills.look() if _is_task(o, task) and o["seen"] >= skills.MIN_SEEN
and o["spread"] <= skills.SPREAD_MM and o["top_mm"] is not None]
o = min(hits, key=lambda o: math.hypot(o["x"] - xy[0], o["y"] - xy[1]), default=None)
return o if o is not None and math.hypot(o["x"] - xy[0], o["y"] - xy[1]) <= KEPT_MM else None
def _see_again(task, mem, yaw, say): def _see_again(task, mem, yaw, say):
"""After a base move: the object by YOLO (its box measured with depth: what a pick may use). Not found: depth """After a base move: first the thing kept in `mem`, looked for where it must be now (the base's odometry): the
where it should be now (`mem`) says whether it is still there; back off a little, turn a little each way and waist turns the torso camera to it when it is off to a side (TORSO_HALF_DEG), the one seen nearest that spot is
look again. Depth sees only table where it was: someone took it, the whole search. Depth sees it but YOLO never taken (never another of its kind, never a new search). Not there: the object by YOLO (its box measured with
does: ask the person. A pick never uses the depth-only position: it was 45 mm off once and the gripper knocked depth: what a pick may use); not found: depth where it should be now says whether it is still there; back off a
the cup over (2026-10-16).""" little, turn a little each way and look again. Depth sees only table where it was: someone took it, the whole
search. Depth sees it but YOLO never does: ask the person. A pick never uses the depth-only position: it was 45 mm
off once and the gripper knocked the cup over (2026-10-16)."""
xy = expected(mem, arm_yaw())[0]
side = math.degrees(math.atan2(-xy[0], xy[1])) # + left of where the torso camera looks
obj = _look_at(_waist_turn() + (side if abs(side) > TORSO_HALF_DEG else 0.0),
lambda: _kept(task, mem))
if obj is not None:
log(f"the {task['object']} is where I kept it: ({obj['x']:.0f}, {obj['y']:.0f})")
return _fitted(task, obj)
there = False there = False
for move in (None, -LOST_BACK_M, LOST_TURN_DEG, -2 * LOST_TURN_DEG): for move in (None, -LOST_BACK_M, LOST_TURN_DEG, -2 * LOST_TURN_DEG):
if move is not None and abs(move) < 1: if move is not None and abs(move) < 1:
@@ -1329,13 +1417,76 @@ def _other_here(task, obj):
return None return None
def _reach(task, obj, say): def at_edge(obj):
"""Step 5: (obj, waypoints, joints above) of a pick that passes IK. Out of reach: move the base (_approach) and look """The object would stay further than skills.COMFORT_R_MM from the arm base even after the waist brought it round
again, up to APPROACH_TRIES times (never on the charger); then ask the person to move it.""" to PICK_ZONE_CENTRE's bearing (the waist turns about the column: its distance from there stays); as it is when the
yaw, tried = arm_yaw(), set() head's place (the column) is not measured. Live 2026-10-26: (-104, 694), (-99, 738), (262, 774) failed or knocked
for i in range(APPROACH_TRIES + 1): the cup over; picks near 600 mm worked."""
c = head_cam.head_centre()
if c is None:
return math.hypot(obj["x"], obj["y"]) > skills.COMFORT_R_MM
c, zone = np.asarray(c[:2], float), np.asarray(PICK_ZONE_CENTRE, float)
ahead = c + (zone - c) / np.linalg.norm(zone - c) * math.hypot(obj["x"] - c[0], obj["y"] - c[1])
return float(np.linalg.norm(ahead)) > skills.COMFORT_R_MM
def in_view(x, y, z):
"""The torso camera sees the arm-frame point (x, y, z mm) VIEW_MARGIN_PX inside its image; True when its
calibration or intrinsics are not known (nothing to go by)."""
T, K = objects.base_from_camera(), camview.intrinsics("torso")
if T is None or K is None:
return True
c = np.linalg.inv(T) @ [x, y, z, 1.0]
if c[2] <= 0:
return False
u, v = c[0] / c[2] * K["fx"] + K["cx"], c[1] / c[2] * K["fy"] + K["cy"]
m = VIEW_MARGIN_PX
return m <= u <= K["width"] - m and m <= v <= K["height"] - m
def pick_goal(obj):
"""Where the base brings `obj` (arm frame mm): PICK_ZONE_CENTRE, or further out (GOAL_OUT_MM steps, within the
comfort reach) when the torso camera would not see the cup's middle there: it looks level, at lift 0 it sees down
to z ~-375 at y 580 only (a cup on a lower table was lost at the pick zone and chased again, X1's sweep). No goal
both seen and reached: FetchError saying so at once (a low table at lift 0), never a goal out of view."""
z = obj["top_mm"] - (obj.get("height_mm") or 2 * skills.BELOW_RIM_MM) / 2
for dy in GOAL_OUT_MM:
g = (PICK_ZONE_CENTRE[0], PICK_ZONE_CENTRE[1] + dy)
if at_edge({"x": g[0], "y": g[1]}):
break
if in_view(g[0], g[1], z) and (not dy or _reach_at(obj, g)):
return g
raise FetchError("The table is too low for me: where my arm reaches the cup, my camera can't see it.",
"테이블이 너무 낮아요. 팔이 닿는 곳에서는 카메라로 컵이 보이지 않아요.")
def _reach_at(obj, g):
"""A pick of `obj` would plan were it at `g` (mm, arm frame): low cups seen only further out are out of the arm's
reach there (X1's sweep: a cup at (-92, 708), top -332)."""
try: try:
plan = _reachable(obj) return skills.reachable_pick({**obj, "x": g[0], "y": g[1]}, accept=_carry_ok,
max_yaw=skills.TRUSTED_YAW_DEG) is not None
except skills.SkillError:
return True # the width decides up close
def _reach(task, obj, say):
"""Step 5: (obj, waypoints, joints above) of a pick that passes IK. A cup past COMFORT_R_MM (the arm almost
straight knocks it over) is not taken from here while the base can bring it in; out of reach: the waist, then a
base move (_approach to pick_goal, every move measured, a way that did nothing not tried again). After every
attempt to move, also one that failed half way, the cup is looked at again where it is kept (_see_again): a plan
never uses a position from before a move. Up to APPROACH_TRIES times (never on the charger). A cup the base can't
bring nearer is taken from where it stands (any grasp turn as the last resort); else ask the person, saying why."""
yaw, tried, why = arm_yaw(), set(), None # grasp turns past skills.TRUSTED_YAW_DEG only when the base can't help
_width_far["moves"] = 0
for i in range(APPROACH_TRIES + 1):
can_move = yaw is not None and i < APPROACH_TRIES and not _charging() and "stuck" not in tried
edge = can_move and not stay_put and "edge" not in tried and at_edge(obj)
if edge:
log(f"the {task['object']} at ({obj['x']:.0f}, {obj['y']:.0f}) is at the edge of my reach: closer first")
else:
try:
plan = _reachable(obj) or ((not can_move or "edge" in tried) and _reachable(obj, None))
except skills.SkillError: # too big / small: another one of them here may do except skills.SkillError: # too big / small: another one of them here may do
other = _other_here(task, obj) if i == 0 else None other = _other_here(task, obj) if i == 0 else None
if other: if other:
@@ -1349,25 +1500,57 @@ def _reach(task, obj, say):
got = _waist_reach(task, obj, say) # the waist brings the arm round to it: no base move got = _waist_reach(task, obj, say) # the waist brings the arm round to it: no base move
if got: if got:
return got return got
if yaw is None or i == APPROACH_TRIES or _charging(): if not can_move:
break break
w = _waist_turn() before, mem, w, blocked = (agv.pose(), (obj["x"], obj["y"])), remember(obj, yaw), _waist_turn(), None
try:
goal = pick_goal(obj) if abs(w) < TURN_MIN_DEG else PICK_ZONE_CENTRE
except FetchError as e: # a low table: no stand both sees and reaches it
if edge:
tried.add("edge")
continue
plan = _reachable(obj, None)
if plan:
return (obj, *plan)
raise
try:
if abs(w) >= TURN_MIN_DEG: # seen with the waist turned: the base turns that way instead if abs(w) >= TURN_MIN_DEG: # seen with the waist turned: the base turns that way instead
_step("turning to face it", say) _step("turning to face it", say)
_pose(_look()) _pose(_look())
if not _turn(w, why="to face it"): blocked = None if _turn(w, why="to face it") else "I can't turn to it"
break else:
obj, yaw = _see(task, say), arm_yaw()
continue
_step(f"moving to reach it ({i + 1}/{APPROACH_TRIES})", say, _step(f"moving to reach it ({i + 1}/{APPROACH_TRIES})", say,
*(("Let me get closer to it.", "가까이 가 볼게요.") if i == 0 else ())) *(("Let me get closer to it.", "가까이 가 볼게요.") if i == 0 else ()))
before, mem = (agv.pose(), (obj["x"], obj["y"])), remember(obj, yaw)
_pose(_look()) _pose(_look())
_approach(obj, yaw, tried) if _approach(obj, yaw, tried, goal=goal) is False:
obj = _see_again(task, mem, yaw, say) blocked = "I am as near as the base can bring it"
_width_far["moves"] += 1
except FetchError as e:
if e.args[:1] == NEED_PATROL[:1]:
raise
blocked = "every way closer was blocked"
if "turn back to the front" in e.args[0]: # the waist is held turned beside a table: no base move
blocked = "my arm can't turn back to the front"
tried.add("stuck")
obj = _see_again(task, mem, arm_yaw(), say) # also after a move that failed half way: never a stale spot
if not blocked and abs(w) < TURN_MIN_DEG:
_learn_offset(before, (agv.pose(), (obj["x"], obj["y"])), yaw) _learn_offset(before, (agv.pose(), (obj["x"], obj["y"])), yaw)
_step("asking to move it closer", say, "I can't reach it, please move it closer to me.", yaw = arm_yaw()
"손이 닿지 않아요. 저에게 조금 더 가까이 놓아 주세요.") if blocked:
if edge or "stuck" in tried:
tried.add("edge") # the base can't bring it in: take it from here
continue
why = blocked
break
if why:
plan = _reachable(obj, None) # the base can't do better: any grasp turn (P2: the last resort)
if plan:
return (obj, *plan)
log(f"asking for help: {why}")
_step("asking to move it closer", say, *(
("I can't get closer to it, something is in my way. Please move it closer to me.",
"가는 길이 막혀서 가까이 갈 수 없어요. 저에게 조금 더 가까이 놓아 주세요.") if why and "near" not in why else
("I can't reach it, please move it closer to me.", "손이 닿지 않아요. 저에게 조금 더 가까이 놓아 주세요.")))
deadline = time.time() + ASK_WAIT_S deadline = time.time() + ASK_WAIT_S
while time.time() < deadline: while time.time() < deadline:
if _stop.wait(ASK_EVERY_S): if _stop.wait(ASK_EVERY_S):
@@ -1439,9 +1622,33 @@ def _top_on(top0, table):
def _place_view(top0): def _place_view(top0):
"""At one view of the search: put it down in reach (True), else a table further away to go to (far_table), else """At one view of the search: put it down in reach (True), else on a table seen further away when the arm reaches a
None.""" spot of it from here (True), else that table to go to (far_table), else None."""
return _place_here(top0) or (far_table() if arm_yaw() is not None else None) if _place_here(top0):
return True
far = far_table() if arm_yaw() is not None else None
return True if far and _place_far(top0, far) else far
def _place_far(top0, far):
"""Put it down on the table far_table() found when the arm reaches a spot of it from here: its level points nearest
PLACE_GOAL that the depth camera sees as table all round (skills.on_table) and free, at most FAR_SPOTS of them
(IK is asked for each). At lift 0 the torso camera sees a table at -328 only from y ~650 on (2026-10-26: the table
was "further away" right in front, and the base could not get nearer). Only at the lift it has now: a table that
needs another lift is gone to first. True when it is down."""
lift = lift_for(far["table"])
if lift is None or abs(lift - head.status()[0]) >= LIFT_TOL_MM:
return None
seen = skills.look()
spots = sorted({(round(x), round(y)) for x, y in far["points"] if math.hypot(x, y) <= FAR_REACH_MM
and all(math.hypot(x - o["x"], y - o["y"]) >= skills.FREE_MM for o in seen)},
key=lambda p: (at_edge({"x": p[0], "y": p[1]}), # comfortable spots first
math.hypot(p[0] - PLACE_GOAL[0], p[1] - PLACE_GOAL[1])))
spots = skills.on_table(spots, far["table"])[:FAR_SPOTS]
if not spots:
return None
log(f"the table further away at {far['table']:.0f} mm: trying spots in reach from here")
return _place_at(spots, _top_on(top0, far["table"]))
def _place_at(tries, top): def _place_at(tries, top):
@@ -1481,7 +1688,8 @@ def _place_at(tries, top):
def far_table(): def far_table():
"""A table seen further away by the torso camera, else by the head camera as it is turned: {"x", "y"} (mm, arm """A table seen further away by the torso camera, else by the head camera as it is turned: {"x", "y"} (mm, arm
frame now) FAR_IN_MM in from the point of its level top nearest PLACE_GOAL (that is its edge), "table" (its height, frame now) FAR_IN_MM in from the point of its level top nearest PLACE_GOAL (that is its edge), "table" (its height,
mm), "camera"; None when neither sees a level top at a height some lift can work at (surface_band).""" mm), "camera", "points" (x, y of its level top seen by the torso camera, for _place_far); None when neither sees a
level top at a height some lift can work at (surface_band)."""
band = surface_band() band = surface_band()
views = [("torso", skills.objects.base_from_camera())] views = [("torso", skills.objects.base_from_camera())]
if _head_ok(): if _head_ok():
@@ -1498,7 +1706,8 @@ def far_table():
p = np.array(min(((q[0], q[1]) for q in top[1]), p = np.array(min(((q[0], q[1]) for q in top[1]),
key=lambda q: math.hypot(q[0] - PLACE_GOAL[0], q[1] - PLACE_GOAL[1]))) key=lambda q: math.hypot(q[0] - PLACE_GOAL[0], q[1] - PLACE_GOAL[1])))
p += FAR_IN_MM * p / max(float(np.linalg.norm(p)), 1.0) p += FAR_IN_MM * p / max(float(np.linalg.norm(p)), 1.0)
return {"x": float(p[0]), "y": float(p[1]), "table": top[0], "camera": cam} return {"x": float(p[0]), "y": float(p[1]), "table": top[0], "camera": cam,
"points": [(q[0], q[1]) for q in top[1]] if cam == "torso" else []}
return None return None
@@ -1664,6 +1873,12 @@ def _put_on(top0, on, say):
return _put_instead(top0, on, label, usable, tried, say) return _put_instead(top0, on, label, usable, tried, say)
surface = None if thing.get("head") else _workable(thing) surface = None if thing.get("head") else _workable(thing)
can_move = arm_yaw() is not None and i < APPROACH_TRIES and not _charging() can_move = arm_yaw() is not None and i < APPROACH_TRIES and not _charging()
big = on["name"] in BIG_TOPS
far = None
if surface is None and big: # a table's box centre moves with the view (2026-10-26 18:55:
surface = table_ahead() # (22, 623), then (-349, 647) for the same table): its level top
far = far_table() if surface is None else None # in front or further away instead
surface = far["table"] if far else surface
if surface is None: if surface is None:
if not can_move: if not can_move:
raise FetchError(f"I can't see the top of the {label} well enough.", "윗면이 잘 안 보여요.") raise FetchError(f"I can't see the top of the {label} well enough.", "윗면이 잘 안 보여요.")
@@ -1676,15 +1891,16 @@ def _put_on(top0, on, say):
thing = _support(on) # look again from the new height, the same way thing = _support(on) # look again from the new height, the same way
continue continue
top = _top_on(top0, surface) top = _top_on(top0, surface)
spots = skills.on_table([(thing["x"] + dx, thing["y"] + dy) for dx in (0, -50, 50) for dy in (0, -50, 50)], centre = [(thing["x"] + dx, thing["y"] + dy) for dx in (0, -50, 50) for dy in (0, -50, 50)]
surface) grid = [p for p in place_spots(skills._held, agv.pose(), skills.look(), surface) # a big top (a table):
spots += [p for p in place_spots(skills._held, agv.pose(), skills.look(), surface) # a big top (a table): if math.hypot(p[0] - thing["x"], p[1] - thing["y"]) <= NEAR_THING_MM] # its near part
if math.hypot(p[0] - thing["x"], p[1] - thing["y"]) <= NEAR_THING_MM and p not in spots] # its near part spots = grid + [p for p in skills.on_table(centre, surface) if p not in grid] if big else \
if spots and _place_at(spots, top): skills.on_table(centre, surface) + grid
if spots and _place_at(list(dict.fromkeys(spots)), top) or far and _place_far(top0, far):
return True return True
if not can_move: if not can_move:
break break
_go_to(thing, PLACE_GOAL, tried, holding=True) _go_to(far or thing, PLACE_GOAL, tried, holding=True)
thing = _look_at(0.0, lambda: _support(on)) thing = _look_at(0.0, lambda: _support(on))
raise FetchError(f"I couldn't reach a free spot on the {label}.", "놓을 자리에 손이 닿지 않아요.") raise FetchError(f"I couldn't reach a free spot on the {label}.", "놓을 자리에 손이 닿지 않아요.")
@@ -1780,13 +1996,27 @@ def _put_down(say=None, on=None):
if got is not None and arm_yaw() is not None and not _charging(): if got is not None and arm_yaw() is not None and not _charging():
log(f"a table at {got['table']:.0f} mm further away ({got['camera']} camera), at ({got['x']:.0f}, " log(f"a table at {got['table']:.0f} mm further away ({got['camera']} camera), at ({got['x']:.0f}, "
f"{got['y']:.0f}): going closer") f"{got['y']:.0f}): going closer")
try:
_go_to(got, PLACE_GOAL, tried, holding=True) _go_to(got, PLACE_GOAL, tried, holding=True)
if _place_near(top, tried): if _place_near(top, tried):
return return
except FetchError as e:
_too_low(got, e)
raise
_too_low(got)
_lift_to(LIFT_DRIVE_MM) _lift_to(LIFT_DRIVE_MM)
raise FetchError("I can't find a free place on a table around me.", "주변에 내려놓을 빈 자리를 못 찾았어요.") raise FetchError("I can't find a free place on a table around me.", "주변에 내려놓을 빈 자리를 못 찾았어요.")
def _too_low(table, cause=None):
"""A table lower than LOW_TABLE_Z with the lift at its bottom: the torso camera sees its top only where the arm
can't reach down to it (X1's sweep: places on tables -420 .. -460 at lift 0): say that, not "blocked"."""
if table["table"] < LOW_TABLE_Z and head.status()[0] <= LIFT_RANGE[0] + LIFT_TOL_MM:
_lift_to(LIFT_DRIVE_MM)
raise FetchError("This table is too low for me right now: I can't see a place on it where my arm reaches.",
"테이블이 너무 낮아서 지금은 팔이 닿는 곳에 놓을 자리가 안 보여요.") from cause
def _give(say): def _give(say):
"""Look -> give (straight), open on "thank you" / Release, then look. No release within GIVE_WAIT_S: """Look -> give (straight), open on "thank you" / Release, then look. No release within GIVE_WAIT_S:
back to look, still holding it; returns "kept".""" back to look, still holding it; returns "kept"."""
@@ -1862,8 +2092,14 @@ def _pick_here(task, say):
_say(say, "I've got it.", "잡았어요.") _say(say, "I've got it.", "잡았어요.")
_step("carry") _step("carry")
skills._guarded(skills._line, "up", waypoints[0][1]) # straight up to the approach height first skills._guarded(skills._line, "up", waypoints[0][1]) # straight up to the approach height first
try:
_line_holding("carry") # straight: the cup stays upright (a turned grasp _line_holding("carry") # straight: the cup stays upright (a turned grasp
_line_holding(LOOK_POSE) # can't go straight to look), then look to drive except FetchError: # can't go straight to look) ...
plan = skills.carry_up(waypoints[0][1], ja) # ... or, when that line jumps (carry has the elbow
if plan is None: # almost straight), further up and one joint move
raise
skills._guarded(skills.carry_by_joints, plan)
_line_holding(LOOK_POSE) # then look to drive
def _fail(e, say): def _fail(e, say):
@@ -1982,16 +2218,27 @@ def check_hand():
if _state["holding"] and not held: if _state["holding"] and not held:
_forget_held() _forget_held()
elif held and not _state["holding"]: elif held and not _state["holding"]:
_set(holding=True) _hold_again()
return held return held
def _forget_held(): def _forget_held():
log("the state says holding, but the hand is empty: nothing is held") log("the state says holding, but the hand is empty: nothing is held")
_last_held.update(held_object=_state.get("held_object"), held=dict(skills._held))
_set(holding=False, **({"status": "idle", "step": ""} if _state["status"] == "holding" else {})) _set(holding=False, **({"status": "idle", "step": ""} if _state["status"] == "holding" else {}))
skills._held.clear() skills._held.clear()
def _hold_again():
"""The hand holds something the state does not: it is the thing forgotten last (_forget_held), its name and what
put down needs. Live 2026-10-26 18:53:00 one hand read said empty with the cup in it; after that every reply said
"something" and put down had no height. ponytail: the last forgotten thing is assumed; a thing put in the hand
without receive would get its name."""
if not skills._held and _last_held.get("held"):
skills._held.update(_last_held["held"])
_set(holding=True, held_object=_state.get("held_object") or _last_held.get("held_object"))
def start(task, say=None): def start(task, say=None):
"""Start `task` in the background. FetchError when busy, holding something or the task is invalid.""" """Start `task` in the background. FetchError when busy, holding something or the task is invalid."""
_adopt() _adopt()
@@ -2002,7 +2249,7 @@ def start(task, say=None):
if _state["holding"] and not held: # taken out of the hand since: forget it if _state["holding"] and not held: # taken out of the hand since: forget it
_forget_held() _forget_held()
if held: if held:
_set(holding=True) _hold_again()
raise FetchError(f"I'm holding {held_name()}, where should I put it first?") raise FetchError(f"I'm holding {held_name()}, where should I put it first?")
problems = validate(task, agv.markers() if _needs_markers(task) else []) problems = validate(task, agv.markers() if _needs_markers(task) else [])
if problems: if problems:
@@ -2029,7 +2276,7 @@ def _finish(fn, say):
_forget_held() _forget_held()
raise FetchError("My hand is empty, I'm not holding anything.", "손에 아무것도 없어요.") raise FetchError("My hand is empty, I'm not holding anything.", "손에 아무것도 없어요.")
if not _state["holding"]: if not _state["holding"]:
_set(holding=True) # the state was lost; give still works, place needs skills._held _hold_again() # the state was lost; give still works, place needs skills._held
_new_run() _new_run()
_set(status="running") _set(status="running")
@@ -2100,7 +2347,7 @@ def run_steps(steps, say=None, sender=None):
if _state["holding"] and not held: if _state["holding"] and not held:
_forget_held() _forget_held()
if held and not _state["holding"]: if held and not _state["holding"]:
_set(holding=True) _hold_again()
problems = steps_mod.check(steps, held, agv.markers()) problems = steps_mod.check(steps, held, agv.markers())
if problems: if problems:
raise FetchError(" ".join(problems)) raise FetchError(" ".join(problems))
@@ -2534,13 +2781,17 @@ def _arm(pose):
_pose("give") _pose("give")
def held_name(): def held_name(lang="en"):
""""the white cup" / "the cup": the held object (held_object, kept in the state file across tasks and restarts), """"the white cup" / "the cup" ("흰 컵" / "컵" for lang "ko"): the held object (held_object, kept in the state file
for "I'm holding the cup"; "something" when it is not known (taken over from the hand).""" across tasks and restarts), for "I'm holding the cup"; "something" ("물건") when it is not known (taken over from
the hand)."""
s = state() s = state()
h = _state.get("held_object") or s.get("held_object") or {} h = _state.get("held_object") or s.get("held_object") or {}
if not h and (_state["holding"] or s.get("holding")): # the state lost it: kept with the pick's data too if not h and (_state["holding"] or s.get("holding")): # the state lost it: kept with the pick's data too
h = skills._held.get("what") or (s.get("held") or {}).get("what") or {} h = skills._held.get("what") or (s.get("held") or {}).get("what") or {}
if lang == "ko":
return " ".join(w for w in (COLOURS.get(h.get("colour")), OBJECTS.get(h.get("object"), h.get("object"))) if w) \
if h.get("object") else "물건"
return " ".join(["the"] + [w for w in (h.get("colour"), h.get("object")) if w]) if h.get("object") else "something" return " ".join(["the"] + [w for w in (h.get("colour"), h.get("object")) if w]) if h.get("object") else "something"
+36 -2
View File
@@ -102,6 +102,35 @@ def judge(expect, got):
ROUNDS = [] # --rounds r1,r2: only these blind rounds (r1 = tests/blind/train) 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): def main(args):
@@ -111,12 +140,13 @@ def main(args):
if "--out" in args: if "--out" in args:
OUT = OUT.with_name(args[args.index("--out") + 1]) OUT = OUT.with_name(args[args.index("--out") + 1])
marks = markers() marks = markers()
save_queries = _cached_embed()
stress, verbose = "--stress" in args, "-v" in args stress, verbose = "--stress" in args, "-v" in args
from assistant import steps from assistant import steps
steps._ollama = lambda *a: (_ for _ in ()).throw(command_check.NoLLM()) steps._ollama = lambda *a: (_ for _ in ()).throw(command_check.NoLLM())
real = intent_bank.read real = intent_bank.read
by = collections.defaultdict(collections.Counter) by = collections.defaultdict(collections.Counter)
wrong, hits, times = [], [], [] wrong, hits, times, missed = [], [], [], []
from assistant import detour from assistant import detour
no_stuck = detour.recent no_stuck = detour.recent
for name, text, expect, state, mk, before, *goal in cases("--blind" in args): 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) times.append(time.time() - t0)
if not got: if not got:
by[name]["llm" if ruled in (None, "llm?") else "rules"] += 1 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 continue
g = f"action:{got[0]} {got[1]}".strip() g = f"action:{got[0]} {got[1]}".strip()
verdict = judge(expect, g) verdict = judge(expect, g)
@@ -154,6 +186,7 @@ def main(args):
by[name][tag] += 1 by[name][tag] += 1
hits.append(f"- [{name}/{state}] {text!r} -> {g}") hits.append(f"- [{name}/{state}] {text!r} -> {g}")
detour.recent = no_stuck detour.recent = no_stuck
save_queries()
for c in by.values(): for c in by.values():
c["cases"] = sum(c.values()) c["cases"] = sum(c.values())
total = sum(by.values(), collections.Counter()) total = sum(by.values(), collections.Counter())
@@ -167,7 +200,8 @@ def main(args):
for k in sorted(by) + ["ALL"]: for k in sorted(by) + ["ALL"]:
c = total if k == "ALL" else by[k] 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.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") OUT.write_text("\n".join(lines) + "\n")
print("\n".join(lines[:len(by) + 9])) print("\n".join(lines[:len(by) + 9]))
print("\n".join(["", "Wrong:"] + wrong[:80])) print("\n".join(["", "Wrong:"] + wrong[:80]))
+200
View File
@@ -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 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): texts), `dlg10.py` (dialogues); `check_r10.py` (round 9's checks plus no held text in train and the English share):
0 problems. 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
View File
@@ -50,6 +50,7 @@ import importlib
import json import json
import pathlib import pathlib
import re import re
re._MAXCACHE = 50000 # the readers build many patterns per map: the default 512 recompiles them per case
import sys import sys
import time import time
from unittest import mock 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_stop", "commands_status", "commands_chain", "commands_detour", "speed_short", "commands_sing",
"commands_missions", "seeing_dialogues", "followup_dialogues", "dialogues_mixed", "unknowns", "silence_noise", "commands_missions", "seeing_dialogues", "followup_dialogues", "dialogues_mixed", "unknowns", "silence_noise",
"hearing", "questions_world", "memory_dialogues", "commands_come", "commands_hand", "commands_point", "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; # 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 # 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) # 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']}" key = f"{j + 1}|{turn['say']}"
if turn.get("reply") is not None and not turn.get("scored", True): # a setup: Lumi said this 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"])) 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 continue
if "scene" in turn: if "scene" in turn:
SCENE["now"] = turn["scene"] SCENE["now"] = turn["scene"]
@@ -494,7 +498,7 @@ def score_dialogue(d, old, use_llm, judge=False):
rows[-1]["closing"] = turn["closing"] rows[-1]["closing"] = turn["closing"]
b.history.append((turn["say"], "")) b.history.append((turn["say"], ""))
continue 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 state = "idle" # handed over / put down: the hand is empty now
if r == "none" and reply in FORGOT: if r == "none" and reply in FORGOT:
r = "forget" # memory_dialogues: the talks deleted and said so 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 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): def run_set(split, name, old_rows, use_llm, cached, limit, sample=None):
cases = load(split, name) 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) if sample and len(cases) > sample: # the same N cases every run (seeded by the set's name)
import random import random
cases = random.Random(name).sample(cases, sample) 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}")) rows.append(row(str(c)[:200], "error", "-", f"{str(c)[:150]} -> {e!r}"))
for r in rows[n:]: for r in rows[n:]:
r["lang"] = lang_of(c, r) 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: if r["verdict"] in ("wrong", "motion", "error") and "-v" in sys.argv:
print(f" {r['verdict'].upper():6} {r['show'][:200]}", flush=True) print(f" {r['verdict'].upper():6} {r['show'][:200]}", flush=True)
return rows 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*") 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): def by_level(saved):
"""right / cases per speech level over every set (r9 / r6 _i: as labelled; "*": guessed from the endings), and the """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.""" closing turns (closing_context) by kind."""
@@ -863,7 +910,7 @@ def report(split, saved, secs):
n = sum(tot.values()) n = sum(tot.values())
lines.append(f"| ALL | | {n} | {tot['right']} | {100 * tot['right'] // max(1, n)} | {tot['wrong']} | " lines.append(f"| ALL | | {n} | {tot['right']} | {100 * tot['right'] // max(1, n)} | {tot['wrong']} | "
f"{tot['motion']} | {tot['llm?']} | {tot['error']} | |") 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): for name in ordered(saved):
rows = saved[name]["rows"] rows = saved[name]["rows"]
dl = {} dl = {}
@@ -876,7 +923,7 @@ def report(split, saved, secs):
r["show"].replace("\n", "\n ") for r in bad] or ["- none"] r["show"].replace("\n", "\n ") for r in bad] or ["- none"]
out = ROOT / "logs" / f"blind_{split}.md" out = ROOT / "logs" / f"blind_{split}.md"
out.write_text("\n".join(lines) + "\n") 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): 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 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__"] 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 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 if not use_llm: # the mission reader's LLM pass only with the LLM
steps._ollama = lambda *a: (_ for _ in ()).throw(command_check.NoLLM()) steps._ollama = lambda *a: (_ for _ in ()).throw(command_check.NoLLM())
from assistant import knowledge # the whole index read now (dialogue_check does so too) from assistant import knowledge # the whole index read now (dialogue_check does so too)
+104
View File
@@ -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)
+424
View File
@@ -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:])
+963
View File
@@ -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()
+32 -6
View File
@@ -1,12 +1,33 @@
"""Every first utterance (commands: 'text' with no 'before'; dialogues: first turn 'say') of the blind train sets """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 import glob, importlib, sys
sys.path.insert(0, __file__.rsplit("/tests/", 1)[0]) sys.path.insert(0, __file__.rsplit("/tests/", 1)[0])
from assistant import quick_answers as qa 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() 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")): 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("/", ".") mod = f[:-3].replace("/", ".")
if mod.endswith("__init__"): continue if mod.endswith("__init__") or "questions_world" in mod: # those are scored by blind_check
continue
m = importlib.import_module(mod) m = importlib.import_module(mod)
texts = [] texts = []
for c in getattr(m, "CASES", []): for c in getattr(m, "CASES", []):
@@ -17,8 +38,13 @@ for f in sorted(glob.glob("tests/blind/train/*.py") + glob.glob("tests/blind/r[2
if t and t[0].get("say"): if t and t[0].get("say"):
texts.append((t[0]["say"], t[0].get("expect_action"))) texts.append((t[0]["say"], t[0].get("expect_action")))
for t, e in texts: for t, e in texts:
if t in seen: continue if t not in seen:
seen.add(t) 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) k = qa.kind_of(t)
if k: print(f"{k:12} {mod.split('.')[-2]}/{mod.split('.')[-1]:20} {t!r} want={e}") if k:
print("texts", len(seen)) hits += 1
print(f"{k:12} {where:22} {t!r} want={e}")
print("texts", len(seen), "quick", hits)
+143
View File
@@ -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:])
+70
View File
@@ -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
View File
@@ -1,8 +1,13 @@
"""The dashboard's Command box (/tasks/parse) reads a sentence exactly as voice does (Lumi.answer, both on """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): 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 import types
re._MAXCACHE = 100000 # the readers use more patterns than re's cache holds: 3x faster
from assistant import brain, lumi from assistant import brain, lumi
from tasks import fetch 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 # 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", "왼쪽 쳐다봐", "오른쪽을 보십시오", "시선 좀 돌려 줘", "고개 숙이고 몸 좀 내려", "so glance to your right and then look up",
"나 쳐다보고 follow me", "speak louder", "목소리 좀 줄여 줘", "더", "one more time", "what do you see?", "what are you doing?", "나 쳐다보고 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 ---------- # ---------- voice: Lumi.answer with every handler recorded, nothing moves, no LLM ----------
@@ -58,8 +66,8 @@ def quick(text, rule=None):
return False return False
if rule[0] == "fetch": if rule[0] == "fetch":
return rec("fetch") return rec("fetch")
if rule[0] in ("weather", "search"): if rule[0] in ("weather", "search") or rule[0] == "put":
return rec("talk") return rec("talk") # put with the hand empty (voice: idle here): "my hand is empty"
s = steps_of(rule) s = steps_of(rule)
return rec("steps", s) if s else rec("command", rule[0]) 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"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") print(f"{len(SENTENCES) - len(bad)}/{len(SENTENCES)} the same by voice and in the Command box")
assert not bad 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") print("command box ok")
+99 -19
View File
@@ -121,7 +121,7 @@ def fake_status():
return {"move_status": "running" if base["polls"] % 3 else "succeeded", "charge_state": base.get("charging", False)} 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",)) calls.append(("ik",))
return (skills.plan_pick(obj), [0.0] * 6) if reach["ok"] else None 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.pose = lambda: base["pose"]
fetch.agv.status = fake_status fetch.agv.status = fake_status
fetch.agv.go = lambda m: (calls.append(("go", m)), (True, "OK"))[1] 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.cancel = lambda: calls.append(("cancel",))
fetch.agv.clearance = lambda x, y: room["clear"](x, y) 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])) 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"))} 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.agv.probe = lambda x, y: room["probe"](x, y)
fetch.AXIS_SPEED, fetch.COAST_S = 100.0, 0.0 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) 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 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]))) 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"]} 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.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] 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.")) else (_ for _ in ()).throw(skills.SkillError("I can't see a thing."))
skills.reachable_pick = fake_reachable skills.reachable_pick = fake_reachable
skills.look = lambda frames=None, **kw: [] skills.look = lambda frames=None, **kw: []
@@ -208,7 +232,7 @@ def run(fn, *a):
def reset(): def reset():
fetch._state.update(status="idle", holding=False, step="") 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) arm.update(j=[5.0] * 6)
found["obj"], reach["ok"] = CUP, True found["obj"], reach["ok"] = CUP, True
hand.update(holding=False, closed=False) hand.update(holding=False, closed=False)
@@ -290,9 +314,10 @@ skills.find = find_low
reset() reset()
st = run(fetch.start, {**ok, "source": "here", "dest": "here"}) st = run(fetch.start, {**ok, "source": "here", "dest": "here"})
lifts = [c[1] for c in calls if c[0] == "lift"] 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 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 skills.find = real_find
surface["z"] = -403.0 surface["z"] = -403.0
fetch._set(holding=False, status="idle") 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 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) \ 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] 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) st = run(fetch.place)
skills.on_table, surface["z"] = real_on_table, -403.0
names = [c[0] for c in calls] 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 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"] 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 ---------- # ---------- out of reach, base axis not measured: no shift, ask, then failed ----------
reset() reset()
@@ -408,14 +450,16 @@ assert st["status"] == "holding" and ("pick", "apple") in calls, st["log"]
fetch._set(holding=False, status="idle") 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 # the straight way is blocked (an obstacle next to the base on the way): navigation round to a side, one side a try
reset() reset()
found["obj"], reach["ok"] = far_cup, False
fetch.CALIB_FILE.write_text(json.dumps({"arm_yaw_in_base_deg": -86.2})) 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 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"}) st = run(fetch.start, {**ok, "source": "here", "dest": "here"})
room["clear"] = lambda x, y: 1.0 room["clear"] = lambda x, y: 1.0
rounds = [l for l in st["log"] if "driving round" in l] tries = [l for l in st["log"] if "driving round" in l or "can't get near enough" in l] # (no room anywhere here)
assert st["status"] == "failed" and len(rounds) == fetch.APPROACH_TRIES and not any(c[0] == "joy" for c in calls), st["log"] drives = [l for l in tries if "driving round" in l]
assert len({l.split("from ")[-1] for l in rounds}) == fetch.APPROACH_TRIES # every time another side 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 found["obj"] = CUP
# ---------- the state still says holding, but the hand is open (someone took it): a new fetch starts ---------- # ---------- 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 ---------- # ---------- too wide from far away: go closer and measure again; too wide up close: refused ----------
real_reach = skills.reachable_pick 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",)) calls.append(("ik",))
skills.plan_pick(obj) # raises when too wide skills.plan_pick(obj) # raises when too wide
return (skills.plan_pick(obj), [0.0] * 6) if obj["y"] < 700 else None 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} 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 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"}) 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") fetch._set(holding=False, status="idle")
hand.update(holding=False, closed=False) hand.update(holding=False, closed=False)
reset() reset()
@@ -681,10 +726,6 @@ fetch.DRIVE_START_S, fetch.agv.status = real_start, real_agv_status
t0 = time.time() t0 = time.time()
fetch._straight(0.01, 1.0) fetch._straight(0.01, 1.0)
assert time.time() - t0 < 0.2 and skills.moved_at["torso"] > t0, skills.moved_at 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 ---------- # ---------- 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}] 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" assert fetch.held_name() == "the white cup"
fetch._set(holding=False) fetch._set(holding=False)
skills._held.clear() 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) # 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 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} NEAR = {**CUP, "x": 60.0, "y": 560.0}
skills.look = lambda frames=None, **kw: [FAR, NEAR] skills.look = lambda frames=None, **kw: [FAR, NEAR]
found["obj"] = FAR 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() reset()
found["obj"] = FAR found["obj"] = FAR
st = run(fetch.start, {**ok, "source": "here", "dest": "here"}) 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) (st["log"][-6:], calls)
fetch._set(holding=False, status="idle") fetch._set(holding=False, status="idle")
skills._held.clear() 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: if obj["x"] < 0:
raise skills.SkillError("The apple is too big for my hand.") raise skills.SkillError("The apple is too big for my hand.")
return skills.plan_pick(obj), [0.0] * 6 return skills.plan_pick(obj), [0.0] * 6
+5 -2
View File
@@ -71,6 +71,9 @@ def flat(pts, guess_z=-400.0, camera="torso", T=None):
skills.surface_heights, skills.flat_points = depth, flat 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 skills.FRESH_WAIT_S = 0.0
fetch.head_cam.base_from_head = lambda yaw, pitch: None # the torso camera only (head: below) 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 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"] objects.base_from_camera = lambda: REC["T"]
fetch.head.status = lambda: [63.0, -20.3, 0.0, 0.0] fetch.head.status = lambda: [63.0, -20.3, 0.0, 0.0]
TABLE_LIVE = -386.0 # its level top, checked by eye 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() assert abs(fetch.table_ahead() - TABLE_LIVE) < 10.0, fetch.table_ahead()
far = fetch.far_table() far = fetch.far_table()
assert far and abs(far["table"] - TABLE_LIVE) < 10.0, far 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]] 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 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 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, # ---------- 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 ---------- # the place grid then lies on its top ----------
+391
View File
@@ -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")
+5 -2
View File
@@ -83,11 +83,14 @@ CONF = ["home", "dock2", "Main_Stage", "Booth_12", "Registration", "포토존",
KOREAN = ["home", "커피코너", "부스3", "입구", "무대", "안내데스크", "휴게실", "회의실"] KOREAN = ["home", "커피코너", "부스3", "입구", "무대", "안내데스크", "휴게실", "회의실"]
for t, mk, want in (("Go to booth bee.", EXPO, "booth_B"), ("에이 부스로 가 줘", EXPO, "booth_A"), for t, mk, want in (("Go to booth bee.", EXPO, "booth_B"), ("에이 부스로 가 줘", EXPO, "booth_A"),
("인포 대스크로 가 줘", EXPO, "info_desk"), ("레지스트레이션으로 가 줘", CONF, "Registration"), ("인포 대스크로 가 줘", EXPO, "info_desk"), ("레지스트레이션으로 가 줘", CONF, "Registration"),
("부스 십이로 가 줘", CONF, "Booth_12"), ("출구 B로 가 봐", CONF, "Exit_B"), ("부스 십이로 가 줘", CONF, "Booth_12"), ("엑시트 비로 가 봐", CONF, "Exit_B"),
("삼 번 부스로 가", KOREAN, "부스3"), ("go to the information desk", KOREAN, "안내데스크"), ("삼 번 부스로 가", KOREAN, "부스3"), ("인포 데스크로 가", EXPO, "info_desk"),
("roll over to the coffee corner", KOREAN, "커피코너"), ("Would you mind heading to dock 2?", EXPO, "dock2")): ("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 [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 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 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 ---------- # ---------- "go where I point" in many wordings (vision/pointing.asked); not a place, a negation, later ----------
+34
View File
@@ -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")
+51
View File
@@ -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
View File
@@ -13,8 +13,24 @@ from manipulation import arm_route, skills
from tasks import fetch from tasks import fetch
# ---------- the offline kinematics: the controller's own answers ---------- # ---------- the offline kinematics: the controller's own answers ----------
mm, deg = kinematics.errors() SAMPLES = ( # joints, the flange pose the controller reported (calibration
assert mm < 0.5 and deg < 0.1, (mm, deg) ([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 for name, j in motion.poses().items(): # IK from a seed 8 deg off: the same flange pose
p = kinematics.pose(j) p = kinematics.pose(j)
s = kinematics.ik(p, [a + 8.0 for a in 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, 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} "width_mm": 76.0, "seen": 8, "spread": 1.0}
reach = lambda o: skills.reachable_pick(o, accept=fetch._carry_ok) 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) 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 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 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) 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 # a held IK answer with J4 one turn round (the same pose) is not a joint-limit or flip refusal
real_ask = skills._ask real_ask = skills._ask
def turned_j4(name, **a): 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 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) 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) 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]), 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 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 for r, b in ((1000, 0), (950, 40)): # too far for any waist turn: the base has to move
o = around(r, b) 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 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))) assert all(body["waist"] + d <= 140.0 for d in fetch.waist_for(around(600, 80)))
body["waist"] = -20.31 body["waist"] = -20.31
@@ -127,4 +168,20 @@ calls.clear()
scene["cup"] = around(600, -70) # the cup was moved away while the waist turned scene["cup"] = around(600, -70) # the cup was moved away while the waist turned
skills.look = lambda *a, **k: [] skills.look = lambda *a, **k: []
assert fetch._waist_reach(task, scene["cup"], None) is None and any(c[0] == "waist" for c in calls) 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") print("reach ok")
+32 -1
View File
@@ -1,9 +1,12 @@
"""Self-check of the skills.py geometry, no robot: python tests/test_skills.py""" """Self-check of the skills.py geometry, no robot: python tests/test_skills.py"""
import numpy as np import numpy as np
from vision import calib from vision import calib, head_cam
from manipulation import skills 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} 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) R = calib.rpy_matrix(*skills.GRASP_RPY)
g = np.array([cup["x"], cup["y"], cup["top_mm"] - 40]) 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["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 assert got["cup"]["shoulder_mm"] is None and got["cup"]["body_mm"] is None
print("skills bottle ok") 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")
+79
View File
@@ -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()