diff --git a/docs/TUNING.md b/docs/TUNING.md index 39c971b..fe31fee 100644 --- a/docs/TUNING.md +++ b/docs/TUNING.md @@ -196,7 +196,8 @@ Every value here is a constant at the top of its file, with a comment on what it | File | Name | Default | What it does | |---|---|---|---| | `tasks/wave_greet.py` | `GREET_M` | 3.0 m | People waving further away (head camera depth) are not answered | -| `tasks/wave_greet.py` | `HOLD_S` | 60 s | The hand stays up this long after the last wave seen, then goes down to `look` | +| `tasks/wave_greet.py` | `GONE_S` | 10 s | A greeted person out of both cameras' view this long is forgotten: their next wave gets an introduction again | +| `tasks/wave_greet.py` | `HOLD_S` | 40 s | The hand stays up this long after the last wave seen, then goes down to `look` | | `tasks/wave_greet.py` | `DOWN_SPEED` | "normal" | `motion.JOINT_SPEED` of the way down; the way up is `arm_route.SPEED` / `wave.ARRIVE_SPEED` (route, the Cobo π limit) | | `tasks/wave_greet.py` | `SWING_SPEED` | "swing" | `motion.JOINT_SPEED` of its swings (an asked wave uses `wave.SWING_SPEED`) | | `robot/motion.py` | `SPEED_ACCEL_FACTOR` | swing 4.0 | A joint speed with its own acceleration factor instead of `JOINT_ACCEL_FACTOR`: "swing" (60 °/s, 240 °/s²) for the greeting's short swings. Higher = snappier swings, more shaking | @@ -207,8 +208,10 @@ Every value here is a constant at the top of its file, with a comment on what it | `tasks/wave_greet.py` | `WAIST_PARTS` | 1, 0.75, 0.5, 0.25 | A waist turn whose sweep is blocked is tried again this much of the way; the head covers the rest | | `tasks/wave_greet.py` | `REFUSED_S` | 30 s | After a refused wave (arm off, busy, holding) the next try waits this long | | `vision/waving.py` | `WINDOW_S`, `MIN_FLIPS` | 2 s, 2 | A wave: the hand's sideways motion changes direction this often within this long. Shorter window = quicker start and stop, slow waves missed | +| `vision/waving.py` | `AT_HEAD`, `OVER_HEAD` | 0.3, 0.45 shoulder widths | A palm this near the face / ears, or this near the nose sideways (on or over the head), is not waving: scratching, a phone, hair, holding the head | +| `vision/waving.py` | `FOREARM_UP_DEG` | 40° | The forearm must point at least this far up from level: talking with the hands and pointing (~25°) do not count | | `vision/waving.py` | `FLOW_PX` | 1.0 px / frame | Sideways hand motion (half-size frame) that counts as a swing. Lower = smaller waves count, more false waves | -| `tasks/wave_lines.py` | `GREET`, `LONG` | 25 each | What Lumi says: greetings, and jokes for a long wave (English, Korean) | +| `tasks/wave_lines.py` | `INTRO`, `GREET`, `LONG` | 10, 25, 25 | What Lumi says: an introduction to someone new, a hello to someone greeted already, jokes for a long wave (English, Korean) | ## Voice diff --git a/tasks/wave_greet.py b/tasks/wave_greet.py index cfddfd7..565a750 100644 --- a/tasks/wave_greet.py +++ b/tasks/wave_greet.py @@ -3,9 +3,10 @@ either runs the assistant owns the robot and this waits. Runs in the API process Someone waving within GREET_M of either camera (vision/waving.py; the head camera may look elsewhere): the head turns to them and the arm goes up at once (manipulation/wave.py checks and plans the way, look -> wave_out -> wave_start, at the route speed), Lumi says a -greeting (tasks/wave_lines.py), swings once even when they stopped meanwhile, then turns the waist to face them -(fetch._waist_to, its sweep checked; the head stays on them). It swings while they wave, stops when they stop and -keeps the hand up; waving again swings again. A long wave gets a joke now and then. Nobody waving for HOLD_S: the arm +greeting (tasks/wave_lines.py; it introduces itself once to a person, until they leave the cameras' view: vision/reid.py +face, else clothes), swings once even when they stopped meanwhile, then turns the waist to face them (fetch._waist_to, +its sweep checked; the head stays on them). It swings back to back while they wave (one swing always queued behind +the running one, no stop between), stops when they stop and keeps the hand up; waving again swings again. A long wave gets a joke now and then. Nobody waving for HOLD_S: the arm goes down slowly to look, the waist to the front, the head to rest. Any stop or failure of the arm (STOP, a person too close while the arm goes up, a refused move) switches the greeting @@ -23,11 +24,16 @@ import numpy as np from manipulation import arm_route, wave from robot import head, motion from tasks import wave_lines -from vision import camview, pose, waving +from robot import arm +from vision import camview, pose, reid, waving CAMERAS = ("head", "torso") # both watched: the head may look away while the person is in the torso camera's view GREET_M = 3.0 # m; people waving further away are not answered -HOLD_S = 60.0 # s the hand stays up after the last wave seen, then down to look +HOLD_S = 40.0 # s the hand stays up after the last wave seen, then down to look (owner: 60 too long) +GONE_S = 10.0 # s a greeted person may be out of both cameras' view and still be known (no new intro) +SWING_POLL_S = 0.2 # s between looks at the controller's queue while swinging +SWING_S = 1.5 # s one swing takes (measured 1.5-1.6 at "swing"); with the queue reading, at most one swing +SWING_LEAD_S = 0.5 # is queued ahead: the next is sent only when the ones sent end within this FRESH_S = 0.5 # s a waving person seen counts as waving now NEW_WAVE_S = 5.0 # s without any waving after which a wave is greeted anew (a new greeting line) JOKE_AFTER_S = 10.0 # s of waving before the first joke ... @@ -49,6 +55,8 @@ CLOSE_FRESH_S = 1.5 # s a camera service detection counts for the too-c _seen = {c: {"t": 0.0, "wavers": []} for c in CAMERAS} # wavers: [(bearing deg from the waist's front, + left; # distance m)] in that camera, nearest first +_met = reid.People() # people greeted (introduced to), forgotten GONE_S after they leave the view +_met_lock = threading.Lock() _busy = threading.Event() # the arm is up or moving for a greeting _speaking = threading.Lock() _on = _free = _off = None # set by start() @@ -106,20 +114,42 @@ def _watch(cam): continue depth, yaw = camview.depth(cam), _head_yaw(cam) gray = cv2.cvtColor(cv2.resize(img, None, fx=waving.SCALE, fy=waving.SCALE), cv2.COLOR_BGR2GRAY) - wavers = [] + wavers, now = [], time.time() for p, is_waving in watcher.update(m, gray, pose.detect(img)): ls, rs = pose.seen(p["kp"], "left_shoulder"), pose.seen(p["kp"], "right_shoulder") - if not (is_waving and ls and rs): + if not (ls and rs): continue at = ((ls[0] + rs[0]) / 2, (ls[1] + rs[1]) / 2) d = _dist(depth, at) - if d is not None and d <= GREET_M: - wavers.append((yaw - math.degrees(math.atan((at[0] - intr["cx"]) / intr["fx"])), d)) + look = reid.look(img, p["box"]) + face = reid.face(img, p["box"]) if is_waving and d is not None and d <= reid.FACE_MAX_M else None + with _met_lock: # someone greeted, still in view: stays known + known = _known(look, face, now) + if known: + known.seen(look, face, now) + if is_waving and d is not None and d <= GREET_M: + wavers.append((yaw - math.degrees(math.atan((at[0] - intr["cx"]) / intr["fx"])), d, look, face)) _seen[cam].update(t=time.time(), wavers=sorted(wavers, key=lambda w: w[1])) +def _known(look, face, now): + """The greeted person this is (call with _met_lock held), None for someone new or gone longer than GONE_S.""" + _met.known = [k for k in _met.known if now - k.last_seen < GONE_S] + return _met.recall(look, face, now) + + +def _greeting(w): + """The lines to greet waver `w` with: an introduction for someone new (they are remembered), else a hello.""" + now = time.time() + with _met_lock: + if _known(w[2], w[3], now): + return wave_lines.GREET + _met.add(w[2], w[3], now) + return wave_lines.INTRO + + def _waver(): - """(bearing, distance) of the nearest person waving now in either camera, None when nobody waves.""" + """(bearing, distance, look, face) of the nearest person waving now in either camera, None when nobody waves.""" now = [w for s in _seen.values() if time.time() - s["t"] < FRESH_S for w in s["wavers"]] return min(now, key=lambda w: w[1], default=None) @@ -197,12 +227,48 @@ def _up(route): def _swing(): - """One swing, START -> SWING -> START, back to back.""" + """One swing, START -> SWING -> START, waited for.""" p, t0 = motion.poses(), time.time() motion.move_path([(p[wave.SWING], SWING_SPEED), (p[wave.START], SWING_SPEED)], queued=True) log(f"swing {time.time() - t0:.1f} s") +def _pending(): + """Moves the controller has still to run (its queue), 9 when it does not say.""" + r = arm.cmd("get_motion_state") + return r.get("queue", 9) if "queue" in r else 9 + + +def _swing_on(now): + """Keep the swings going back to back: one more swing is queued while the running one has at most its last move + left. Not waited for, so a STOP or a protective stop is looked for here (motion._wait does it for waited moves). + False when the arm is not at the wave any more (someone moved it).""" + if motion._stopped.is_set(): + raise motion.MotionError("stopped") + d = arm.cmd("get_data") + if d.get("protective_stop") or d.get("emergency_stop"): + raise motion.MotionError("the controller stopped the arm (protective / emergency stop)") + if _st["swing_end"] - now > SWING_LEAD_S: # the swings sent still run longer than that: never pile up + return True + n = _pending() + if n > 1: + return True + if n == 0 and arm_route.where() not in (wave.START, wave.SWING): + return False + p = motion.poses() + motion.move_path([(p[wave.SWING], SWING_SPEED), (p[wave.START], SWING_SPEED)], wait=False, queued=True) + _st["swing_end"] = max(now, _st["swing_end"]) + SWING_S + return True + + +def _settle(): + """Let the queued swings end at START before the waist turns or the arm goes down.""" + start = motion.poses()[wave.START] + motion._wait(lambda d: max(abs(a - b) for a, b in zip(d["joint_actual_position"], + motion.nearest(start, d["joint_actual_position"]))) < + motion.AT_JOINT_DEG, 10.0, queued=True) + + def _face(bearing): """Waist turned to the person (they face each other), the head staying on them; only the head when they are nearly in front. A turn whose sweep is not clear is tried part of the way (WAIST_PARTS); the head covers the @@ -217,8 +283,9 @@ def _face(bearing): _head_to(bearing) -def _greet(bearing, lang): +def _greet(w, lang): """Head to them, a greeting, the arm up, one swing, the waist to them. False when the arm is refused.""" + bearing = w[0] try: route, _ = wave.plan() except Exception as e: # refused (arm off, busy, holding) or the controller did not answer @@ -227,7 +294,7 @@ def _greet(bearing, lang): log(f"someone waves at {bearing:+.0f} deg: arm up") _busy.set() _head_to(bearing) - _say(wave_lines.GREET, lang) + _say(_greeting(w), lang) _up(route) _swing() # once, even if they stopped while the arm went up w = _waver() @@ -241,6 +308,8 @@ def _down(): from tasks import fetch _busy.set() try: + if _st["up"] and arm_route.where() is None: + _settle() # mid-swing: the queued swings end first fetch._stop.clear() _st["waist_out"] = not fetch._waist_to(0.0, in_place=True) if arm_route.where() in arm_route.WAVE_POSES: @@ -252,7 +321,8 @@ def _down(): _st = {"up": False, "last_wave": 0.0, "lang": 0, "next_joke": 0.0, "free": False, "free_at": 0.0, "refused_until": 0.0, - "waist_out": False, "follow_at": 0.0} # waist_out: the way back to the front was blocked, tried again later + "waist_out": False, "follow_at": 0.0, "swing_at": 0.0, + "swing_end": 0.0} # swing_end: when the swings sent so far should be done # waist_out: the way back to the front was blocked, tried again later def step(now): @@ -277,7 +347,7 @@ def step(now): st["last_wave"] = now if not st["up"]: if w and now > st["refused_until"]: - st["up"] = _greet(w[0], st["lang"]) + st["up"] = _greet(w, st["lang"]) if not st["up"]: st["refused_until"] = now + REFUSED_S elif not w and st["waist_out"] and now > st["refused_until"]: @@ -286,20 +356,21 @@ def step(now): st["waist_out"] = not fetch._waist_to(0.0, in_place=True) st["refused_until"] = now + REFUSED_S elif w: - if arm_route.where() not in (wave.START, wave.SWING): - st["up"] = False # someone moved the arm: the next wave starts from where it is - return if new: - _say(wave_lines.GREET, st["lang"]) + _say(_greeting(w), st["lang"]) elif now > st["next_joke"]: _say(wave_lines.LONG, st["lang"]) st["next_joke"] = now + JOKE_EVERY_S if abs(w[0]) > WAIST_FOLLOW_DEG and now > st["follow_at"]: st["follow_at"] = now + FOLLOW_EVERY_S + _settle() _face(w[0]) # they moved: the waist turns to them again, between two swings else: _head_to(w[0]) - _swing() + if now > st["swing_at"]: + st["swing_at"] = now + SWING_POLL_S + if not _swing_on(now): + st["up"] = False # someone moved the arm: the next wave starts from where it is elif now - st["last_wave"] > HOLD_S: _down() st["up"] = False diff --git a/tasks/wave_lines.py b/tasks/wave_lines.py index 3129a58..42d670c 100644 --- a/tasks/wave_lines.py +++ b/tasks/wave_lines.py @@ -1,7 +1,24 @@ """What Lumi says while it waves back at someone (tasks/wave_greet.py), (English, Korean). One language per wave, picked at random: a passer-by's language is not known. The lines fit a hello and a goodbye alike.""" +# the first wave of someone new: Lumi introduces itself (once, until they leave the view) +INTRO = [ + ("Hi! I'm Lumi. Nice to meet you!", "안녕하세요! 저는 루미예요. 만나서 반가워요!"), + ("Hello! I'm Lumi, the robot of Cutshion!", "안녕하세요! 저는 컷션의 로봇 루미예요!"), + ("Hi there! My name is Lumi. Have a great day!", "안녕하세요! 제 이름은 루미예요. 좋은 하루 보내세요!"), + ("Hello! I'm Lumi. Thanks for waving!", "안녕하세요! 루미예요. 손 흔들어 주셔서 고마워요!"), + ("Hey! I'm Lumi. Waving back at you!", "안녕하세요! 루미예요. 저도 손 흔들어요!"), + ("Hi! Lumi here. Lovely to see you!", "안녕하세요! 루미예요. 만나서 정말 좋아요!"), + ("Hello, hello! I'm Lumi, nice to meet you!", "안녕하세요! 저는 루미, 반갑습니다!"), + ("Hi! I'm Lumi. I love a friendly wave!", "안녕하세요! 저는 루미예요. 손 인사 정말 좋아해요!"), + ("Hello! I'm Lumi. You made my day!", "안녕하세요! 루미예요. 덕분에 기분이 좋아졌어요!"), + ("Hi! I'm Lumi, your robot friend!", "안녕하세요! 여러분의 로봇 친구 루미예요!"), +] + +# later waves of someone Lumi has already greeted GREET = [ + ("Hello again!", "또 만났네요!"), + ("Hi again! Still here?", "또 안녕하세요! 아직 계셨네요?"), ("Hi there! Have a wonderful day!", "안녕하세요! 좋은 하루 보내세요!"), ("Hello, hello! Nice to see you!", "안녕하세요! 반가워요!"), ("Hey! I see you!", "어! 저 보여요, 보여요!"), @@ -12,13 +29,11 @@ GREET = [ ("Hey there! Big wave for you!", "안녕하세요! 크게 흔들어 드릴게요!"), ("Hi! Thanks for saying hello!", "안녕하세요! 인사해 주셔서 고마워요!"), ("Hello! You have a great wave!", "안녕하세요! 손 흔드는 모습이 멋져요!"), - ("Hi! I'm Lumi. Nice to meet you!", "안녕하세요! 저는 루미예요. 만나서 반가워요!"), ("Hey! Have a good one!", "안녕하세요! 좋은 시간 보내세요!"), ("Hello! Smile, it's a good day!", "안녕하세요! 웃어요, 좋은 날이에요!"), ("Hi! You waved, so I wave!", "안녕하세요! 손 흔드시니까 저도 흔들어요!"), ("Hello there! See you around!", "안녕하세요! 또 만나요!"), ("Hi! Robots love waves too!", "안녕하세요! 로봇도 손 인사를 좋아해요!"), - ("Hey! Hello from Lumi!", "안녕하세요! 루미가 인사드려요!"), ("Hi! Hope everything goes well today!", "안녕하세요! 오늘 일 다 잘 되길 바라요!"), ("Hello! Thanks for noticing me!", "안녕하세요! 저를 봐 주셔서 고마워요!"), ("Hi there! Sending you good energy!", "안녕하세요! 좋은 기운 보내 드려요!"), diff --git a/tests/test_wave_greet.py b/tests/test_wave_greet.py index 71e02ac..6eb77c3 100644 --- a/tests/test_wave_greet.py +++ b/tests/test_wave_greet.py @@ -11,7 +11,12 @@ from vision import waving done = [] # what the robot did, in order arm = {"at": "look"} -waver = {"w": None} # (bearing, distance) of the person waving now +waver = {"w": None} # (bearing, distance, look, face) of the person waving now +A, B = [1.0, 0.0, 1.0, 0.0], [0.0, 1.0, 0.0, 1.0] # clothes signatures (vision/reid.py) of two people + + +def W(bearing, look=A): + return (bearing, 2.0, look, None) plan_error = {"e": None} POSES = {"look": [0.0] * 6, "wave_out": [1.0] * 6, "wave_start": [2.0] * 6, "wave": [3.0] * 6} @@ -56,6 +61,9 @@ switch = {"on": True, "free": True} g._on, g._free = (lambda: switch["on"]), (lambda: switch["free"]) g._off = lambda: switch.update(on=False) g._bg = lambda fn, *args: fn(*args) # the background parts run at once here +queue = {"n": 0} # moves the fake controller has queued +g.arm.cmd = lambda name, **k: {"queue": queue["n"]} if name == "get_motion_state" else {} +motion._wait = lambda *a, **k: done.append("settle") def run(t0, t1, dt=0.5): @@ -72,44 +80,56 @@ def fresh(): done.clear() said.clear() arm["at"] = "look" - g._st.update(up=False, last_wave=0.0, next_joke=0.0, free_at=0.0, refused_until=0.0, waist_out=False, follow_at=0.0) + g._st.update(up=False, last_wave=0.0, next_joke=0.0, free_at=0.0, refused_until=0.0, waist_out=False, follow_at=0.0, swing_at=0.0, swing_end=0.0) + g._met.known.clear() switch.update(on=True, free=True) plan_error["e"] = None # someone waves 30 deg on the left at 2 m: head to them, a greeting, arm up at the route speed, one swing, waist to them fresh() -waver["w"] = (30.0, 2.0) +waver["w"] = W(30.0) run(100.0, 100.0) assert done == ["head +30", "up route", "swing", "waist +30 look 30.0"], done -assert len(said) == 1 and said[0] in sum(g.wave_lines.GREET, ()), said +assert len(said) == 1 and said[0] in sum(g.wave_lines.INTRO, ()), said # someone new: Lumi introduces itself assert g.busy() # they keep waving: swings, and a joke after JOKE_AFTER_S, then not again before JOKE_EVERY_S done.clear() said.clear() run(100.5, 100.0 + g.JOKE_AFTER_S + 1) -assert done.count("swing") >= 10 and "up route" not in done, done +assert done.count("swing") >= g.JOKE_AFTER_S / g.SWING_S - 1 and "up route" not in done, done # one per SWING_S assert len(said) == 1 and said[0] in sum(g.wave_lines.LONG, ()), said # they move to the other side while waving: the waist turns to them again between swings, not more often than # FOLLOW_EVERY_S done.clear() -waver["w"] = (-40.0, 2.0) +waver["w"] = W(-40.0) g._st["follow_at"] = 0.0 # (the fake waver stays at +30 after each turn: turned again so far) run(111.5, 111.5 + g.FOLLOW_EVERY_S - 0.5) -assert done[0] == "waist -40 look -40.0" and done.count("waist -40 look -40.0") == 1, done -waver["w"] = (30.0, 2.0) +assert done[:2] == ["settle", "waist -40 look -40.0"] and done.count("waist -40 look -40.0") == 1, done # swings end first +waver["w"] = W(30.0) + +# never more than one swing queued ahead, even if the controller's queue always read empty +g._st["swing_end"], g._st["swing_at"] = 0.0, 0.0 +done.clear() +for _ in range(10): + g._swing_on(1000.0) +assert done.count("swing") == 1, done +g._st["swing_end"] -= g.SWING_S # it ended: the next is sent +g._swing_on(1000.0) +assert done.count("swing") == 2, done +g._st["swing_end"] = 0.0 # they stop: the hand stays up, no swings; waving again: swings again, no new greeting within NEW_WAVE_S waver["w"] = None done.clear() run(112.0, 115.0) assert done == [], done -waver["w"] = (30.0, 2.0) +waver["w"] = W(30.0) said.clear() run(115.5, 116.0) -assert done.count("swing") == 2 and said == [], (done, said) +assert done.count("swing") == 1 and said == [], (done, said) # nobody waves for HOLD_S: arm down slowly, waist to the front, head to rest; not before waver["w"] = None @@ -122,7 +142,7 @@ assert not g.busy() and arm["at"] == "look" # the waist's way back is blocked: the arm still goes down; the waist is tried again every REFUSED_S while nobody waves fresh() -waver["w"] = (30.0, 2.0) +waver["w"] = W(30.0) run(150.0, 150.0) waver["w"] = None blocked = {"n": 1} @@ -135,7 +155,7 @@ fetch._waist_to = lambda rel, in_place=False, look=None: done.append(f"waist {re # beside a wall the full waist turn is blocked: it turns as far as its sweep is clear, the head on the person fresh() -waver["w"] = (-66.0, 2.0) +waver["w"] = W(-66.0) fetch._waist_to = lambda rel, in_place=False, look=None: done.append(f"waist {rel:+.0f} look {look}") or abs(rel) < 40 run(160.0, 160.0) assert done[-3:] == ["waist -66 look -66.0", "waist -50 look -66.0", "waist -33 look -66.0"], done @@ -143,7 +163,7 @@ fetch._waist_to = lambda rel, in_place=False, look=None: done.append(f"waist {re # a wave nearly in front: only the head turns, the waist stays fresh() -waver["w"] = (5.0, 1.5) +waver["w"] = W(5.0) run(200.0, 200.0) assert done == ["up route", "swing"], done # the head looks there already (within HEAD_MIN_DEG) @@ -155,7 +175,7 @@ assert done[:2] == ["waist +0 look None", "down normal"], done # the arm stops (STOP, a person too close) during a swing: switched off, nothing moves after it fresh() -waver["w"] = (0.0, 2.0) +waver["w"] = W(0.0) run(300.0, 300.0) @@ -186,6 +206,29 @@ switch["free"] = False run(500.0, 505.0) assert done == [] and not g.busy(), done +# Lumi introduces itself once per person: the same person waving again (after NEW_WAVE_S) gets a hello, someone +# else an introduction, and the first person too once they were out of view for GONE_S +fresh() +waver["w"] = W(0.0) +run(600.0, 600.0) +waver["w"] = None +run(600.5, 600.0 + g.NEW_WAVE_S + 1) +waver["w"] = W(0.0) +run(607.0, 607.0) +waver["w"] = None +run(607.5, 607.0 + g.NEW_WAVE_S + 1) +waver["w"] = W(0.0, B) +run(614.0, 614.0) +assert [l in sum(g.wave_lines.INTRO, ()) for l in said] == [True, False, True], said +assert said[1] in sum(g.wave_lines.GREET, ()), said +for k in g._met.known: + k.last_seen -= g.GONE_S + 1 # both left the view +waver["w"] = None +run(614.5, 614.0 + g.NEW_WAVE_S + 1) +waver["w"] = W(0.0) +run(621.0, 621.0) +assert said[-1] in sum(g.wave_lines.INTRO, ()), said + # a hand at the head (scratching, a phone at the ear) is not a raised hand; the same hand held out to the side is import numpy as np # noqa: E402 kp = np.zeros((17, 3)) diff --git a/vision/wave_record.py b/vision/wave_record.py index dba5ee2..e1f4528 100644 --- a/vision/wave_record.py +++ b/vision/wave_record.py @@ -2,6 +2,7 @@ wave greeting is tuned and tested on. Moves nothing; Lumi only speaks (POST /say). python vision/wave_record.py [first_step] # writes tests/data/waves/