"""Singing: play one of the owner's songs (data/songs/mine/.wav, made by audio/sing_mine.py from the owner's own files, local only, never copied off the robot) and move the head with it. Lumi sings only these. python audio/sing.py # list the songs python audio/sing.py # sing one (plays on the speaker and moves the head) Each .json holds the title, the names it is asked by, the lyrics and the head moves timed to the beat. The song is played through mouth._play (the microphone is muted the same way as for speech, and abort() stops it within 50 ms). The head turns to the centre yaw (the person talked to; 0 by default) / pitch 0 and dances around it in a thread, following the music: small diagonal bobs landing on the beats in energetic parts, a quick sweep with a dip on a bar's accent or a phrase start, slower sways in calm parts, each move called early enough (the owner's measured head timing) to land on its beat, one call at a time; it goes back to the centre yaw / pitch 0 when the song ends or is stopped. Never the lift, the waist or the arm. """ import difflib import json import pathlib import random import re import sys import threading import time import numpy as np from robot.head import YAW_LIMIT ROOT = pathlib.Path(__file__).resolve().parents[1] MINE = ROOT / "data" / "songs" / "mine" # the owner's songs: local only YAW_SWAY = 40.0 # deg; head yaw stays within +- this while singing (owner: wider, 2026-10-21) PITCH_RANGE = (0.0, 28.0) # deg, absolute head pitch while singing (0 = level, + = up; owner: higher) # head timing measured by the owner (2026-10-20, body API, vel = acc = 100, head.status polled every 20 ms): the head # starts 0.2 s after the call and turns ~40 deg/s after that (15 / 6 deg diagonal reached at 0.87 s, 25 / 10 deg at # 1.12 s); the call returns ~0.1 s after it arrives. Speed is no higher above vel 50. Overlapping moveto calls hang # the body API: a move is sent only after the last one returned. REACH_S = 0.5 # s from the call until a small move arrives (start delay + speeding up) RETURN_S = 0.6 # s from the call until it returns, for a small move HEAD_DEG_S = 40.0 # deg/s of the larger axis at vel >= VEL_FULL VEL_FULL = 50 # speed ratio % from which the head is at its full speed VEL_LIVELY, VEL_CALM, VEL_CALMEST = 100, 100, 80 # speed ratio %: energetic / calm / the calmest parts ENERGETIC = 0.4 # music energy (0..1) from which the head bobs on the beat CALMEST = 0.15 # below this energy the head sways slowly BOB_DEG = (7.0, 12.0) # deg, a beat's bob (diagonal nod / tilt), alternating sides ACCENT_DEG = (25.0, 38.0) # deg, a bar's or phrase's accent: a quick sweep with a dip SWAY_DEG = (12.0, 20.0) # deg, a calm sway ACCENT_EVERY_S = 1.2 # s, at least this between two accents CENTRE_PITCH = 12.0 # deg; the dance moves around the centre yaw (sing's centre_yaw), this pitch GAP_S = 0.02 # s between a call returning and the next one MIN_CHANGE = (1.5, 0.8) # deg; every move changes yaw and pitch at least this much MIN_TURN_DEG = 20.0 # two moves in a row differ in direction by at least this (never one line) HEAD_VEL = 70 # speed ratio % for turning to the centre yaw / pitch 0 after the song LATE_S = 0.4 # s; a move this late is skipped (the previous one took longer) RETURN_WAIT_S = 3.0 # s a new song waits for the head to get back from the last one BANK_SIM = 0.80 # song bank (assistant/song_bank.py): the closest wording at least this similar ... BANK_MARGIN = 0.05 # ... and this much closer than the closest wording of another kind BANK_MIN_WORDS = 3 # the bank reads only words with a song or music word in them and at least this many # words ("Let's", cut off from "Let's follow me", sang once, 2026-10-22) REPEAT_S = 10.0 # s after a song starts in which its request said again is a repeat, not a new request # ("Let's make music." said again while the reply took 5.6 s cut the song 2 s in, 2026-10-27) SPEECH_PER_SYLLABLE = 0.12 # s of speech (Silero VAD, ears.speech_seconds) per syllable that words heard over a song # need, else whisper read the music: "Last hole." from 0.26 s (0.09 per syllable) cut a # song; the owner's requests over songs had 0.2-0.3 (logs/heard 2026-10-27). Stricter # than ears.SPEECH_PER_SYLLABLE (0.05) for normal listening; stop words skip it SONG_WORD = re.compile(r"\bsing|\bsong|\bmusic|\btunes?\b|\bplaylist|k-?pop|노래|노레|노랠|음악|곡|불러|부르|틀어|들려|케이팝", re.I) SING = re.compile(r"\bsing\b|\bsay (?:a |some )?songs?\b|" # whisper writes "let's say song" r"\b(?:play|put on|turn on|start)(?: me| us)? (?:a |some |any |another |the |your )?(?:songs?|music|tunes?)\b|" r"\b(?:another|different|next|new|other) (?:song|tune)\b|\b(?:change|switch)(?: the| this| that)? (?:songs?|music|tunes?)\b|" r"(?:노래|음악|곡)\s*(?:좀\s*)?바꿔|\b(?:(?:want|like|love) to|(?:can|could|may) (?:we|i)) hear (?:a |some |one of your )?(?:songs?|music)\b|\bgive (?:us|me) (?:a |some )?(?:song|tune|music)\b|" r"^\W*(?:lumi\W*)?(?:a |some )?(?:song|music)(?:\W+(?:please|lumi))*\W*$|" r"(?:노래|음악|(? "yes" if picked(t, last): return True return bool(SING.search(t)) or bool(SING_TITLE.search(t) and (_title(t, songs()) or re.search( r"[a-z]{2}.*(?:불러|들려|틀어)", t, re.I) and _other_song(t, songs()))) or \ bool(TITLE_ASKED.search(t) and _title(t, songs(), plain=bool(re.search(r"불러|들려|틀어|불르|부르|부를", t)))) # "Let it go 불러 줘": not ours _bank = None # right after the list of songs: which one ("the first one", "두 번째 거", "the last", "아무거나") ORDINAL = [re.compile(r"\b(?:first|1st|number one)\b|첫\s*(?:번째|곡|거|노래)|첫번째|1번", re.I), re.compile(r"\b(?:second|2nd|number two)\b|두\s*번째|둘째|2번", re.I), re.compile(r"\b(?:third|3rd|number three)\b|세\s*번째|셋째|3번", re.I), re.compile(r"\b(?:fourth|4th|number four)\b|네\s*번째|넷째|4번", re.I)] LAST_ONE = re.compile(r"\b(?:the )?last(?: one)?\b|마지막", re.I) ANY_ONE = re.compile(r"\b(?:any(?:thing|one)?|whatever|you (?:choose|pick|decide)|random|surprise me|doesn'?t matter|" r"up to you)\b|아무\s*거나|아무\s*노래|아무\s*곡|알아서|(?:네가|니가|루미가)\s*(?:골라|정해)|상관\s*없", re.I) def picked(text, last=""): """Right after Lumi said its songs ("ACTION: none songs": the list, or "I can't sing that one"): the song these words choose, a title ("Fantastic Baby", "판타스틱", "BAD") or its place in the list ("the first one", "두 번째", "the last one"), or any one ("아무거나", "you choose"); else None.""" if not (last or "").startswith("ACTION: none songs") or NOT_ASKED.search(text or ""): return None all_songs = songs() ids = list(all_songs) # the order the list says them in (_titles) named = _title(text, all_songs) if named: return named for i, r in enumerate(ORDINAL): if r.search(text or "") and i < len(ids): return ids[i] if ids and LAST_ONE.search(text or ""): return ids[-1] if ids and ANY_ONE.search(text or ""): return random.choice(ids) return None def bank_read(text, last=""): """'sing' / 'list' when these words mean the same as the bank's wordings of that kind (bge-m3 through assistant/knowledge.embed, ~20 ms), else None (the LLM decides; also when the closest are the bank's near misses, and for a 'sing' with any word that might be a title: "jingle bells please"). Only words with a song or music word and BANK_MIN_WORDS words are read: a cut-off start ("Let's", "can you", "루미야 저기") never sings. Negation, a condition or a later time, the person singing, a question about liking music or "is / does ...?", and any words with a turn before them (the talk decides what "yes" means) are never read here.""" global _bank t = text or "" if not SONG_WORD.search(t) or len(re.findall(r"\w+", t)) < BANK_MIN_WORDS or NOT_REQUEST.search(t) or \ NOT_ASKED.search(t) or re.match(r"\W*(?:is|are|was|were|does|did|has|have)\b", t, re.I) or \ re.search(r"\b(?:like|love|enjoy|favou?rite)\b|좋아|싫어", t, re.I) and re.search(r"\?|까요?\W*$|니\W*$", t) or last: return None from assistant import knowledge, song_bank try: q = knowledge.embed([t])[0] except OSError as e: # no embedding server: the LLM decides print(f"song bank: {e}") return None if _bank is None: texts = song_bank.SING + song_bank.LIST + song_bank.NO labels = ["sing"] * len(song_bank.SING) + ["list"] * len(song_bank.LIST) + ["no"] * len(song_bank.NO) _bank = (knowledge.embed(texts), np.array(labels)) vecs, labels = _bank sims = vecs @ q best = int(sims.argmax()) other = sims[labels != labels[best]].max() if sims[best] < BANK_SIM or sims[best] - other < BANK_MARGIN or labels[best] == "no": return None return "sing" if labels[best] == "sing" and choose(t, whole=True) else "list" if labels[best] == "list" else None def list_asked(text): """"What songs can you sing?", "무슨 노래 알아?": the titles are said.""" return bool(SONG_LIST.search(text or "")) and not NOT_REQUEST.search(text or "") def stop_words(text): return bool(STOP.search(text or "")) def ignored_over_song(text, request, sung_s, speech_s): """Why words heard while singing (no stop word) leave the song going, or None when they end it (a change: "another song", "다른 노래", a title; a question or command). Ignored: words with too little speech in them (the music read by whisper), a single word, and a song asked for again (any time "sing a song"; within REPEAT_S the request's own words). request: the words that started the song; sung_s: s since it started; speech_s: last_stt's.""" from audio import ears change = ANOTHER.search(text) or _title(text, songs(), plain=False) if speech_s is not None and speech_s < SPEECH_PER_SYLLABLE * ears.syllables(text): return f"{speech_s:.2f} s of speech: the music" if len(text.split()) < 2 and not change: return "one word" if not change and (asked(text) or sung_s < REPEAT_S and difflib.SequenceMatcher( None, ears._letters(text), ears._letters(request or "")).ratio() >= ears.SAME_WORDS): return "the song asked for again" return None def _name_re(name): """A song's name in any spacing ("big bang", "러브어택", "a teez"); Latin names as whole words ("bad" is not in "badminton").""" body = r"\s*".join(re.escape(c) for c in name.replace(" ", "")) return rf"(? 4 and difflib.get_close_matches(w, FILLER, 1, 0.8)): return True # "pleaase", "anothre": slips of filler words continue if w in FILLER_KO or VERB_KO.match(w): continue if len(w) > 1 and w.endswith(_ADNOMINAL) or re.search(r"(?:한테|에게|께|께서|니까|는데|데요|지만|해서|면|합니다)$", w): break if _PARTICLE.sub("", w) not in FILLER_KO: return True return False def choose(text, lang="en", last=None, whole=False): """The song to sing for these words, or None when they ask for a song we don't have (another title or singer, or a language none of ours is in; with `whole` any word that is no filler is a title: "jingle bells please"). A named song first; the last one again when asked; else any of ours, not the last.""" all_songs = songs() if _other_song(text, all_songs, whole): return None named = _title(text, all_songs) other = [m.start() for m in ANOTHER.finditer(text or "")] if named and (not other or other[-1] < _title_at(text, all_songs)): return named # "다음은 러브 어택", "그거 말고 BAD": that one; "BAD 말고 다른 거": another if last in all_songs and AGAIN.search(text or "") and not ANOTHER.search(text or ""): return last # "sing it again", "한 번 더" want = "ko" if KOREAN.search(text or "") else "en" if ENGLISH.search(text or "") else None if want and not any(s["lang"] == want for s in all_songs.values()): return None # "an English song": all of ours are Korean pool = [sid for sid, s in all_songs.items() if want in (None, s["lang"]) and sid != last] or list(all_songs) return random.choice(pool) if pool else None def _titles(lang): names = [s["title_ko" if lang == "ko" else "title"] for s in songs().values()] if lang == "ko" or len(names) < 2: return ", ".join(names) return ", ".join(names[:-1]) + " and " + names[-1] def unknown_reply(lang): """A song we don't have was asked for: said kindly, our songs offered (one of several wordings).""" n = len(songs()) return random.choice(UNKNOWN[lang]).format(_titles(lang), n=COUNT_KO.get(n, f"{n} ")) def list_reply(lang): """Every title: "I can sing BAD, ... and Love Attack. Which one would you like?".""" names = _titles(lang) if lang == "ko": names += "를" if _no_final(names[-1]) else "을" return LIST[lang].format(names) def _no_final(word): """Korean: the last syllable has no final consonant (를 rather than 을).""" c = ord(word[-1]) - 0xAC00 return not (0 <= c < 11172) or c % 28 == 0 def song_beats(song): """[(seconds, energy 0..1, accent 0..1, a sung phrase starts)] per beat, from the instrumental (loudness, onsets) and the vocal (phrases), written by audio/sing_mine.py.""" return [tuple(b) if len(b) == 4 else (b[0], b[1], 0.5, False) for b in song["beats"]] def _speed(vel): return HEAD_DEG_S * min(1.0, vel / VEL_FULL) def reach_time(dy, dp, vel): """s from the call until the head arrives (the owner's measurements).""" return REACH_S + max(abs(dy), abs(dp)) / _speed(vel) def move_time(dy, dp, vel): """s from the call until moveto returns.""" return RETURN_S + max(abs(dy), abs(dp)) / _speed(vel) def _turn(a, b): """deg between two move directions (0 = same line forward, 180 = straight back).""" na, nb = np.hypot(*a), np.hypot(*b) return float(np.degrees(np.arccos(np.clip(np.dot(a, b) / (na * nb + 1e-9), -1, 1)))) def _fit(v, d, lo, hi, least): """A step d from v of at least `least`, ending inside lo..hi (turned toward the middle when it would not).""" d = d if abs(d) >= least else least * (1 if d >= 0 else -1) if lo <= v + d <= hi: return d if lo <= v - d <= hi: return -d toward = 1 if v < (lo + hi) / 2 else -1 return toward * max(least, min(abs(d), hi - v if toward > 0 else v - lo)) def p_room(pp): """+1 when the pitch has more room upward, -1 when downward.""" lo, hi = PITCH_RANGE return 1 if hi - pp >= pp - lo else -1 def _bend(py, pp, dy, dp, last): """The move (dy, dp) from (py, pp) made to change both axes (MIN_CHANGE), to turn away from the last move's line (MIN_TURN_DEG) and to end inside the limits: as planned, with the pitch the other way, else bent to either side.""" lo, hi = PITCH_RANGE for side in (0, "flip", 1, -1, 2, -2): if side == "flip": # a sweep back: rise where the last one fell, and the other way dy2, dp2 = dy, -dp if abs(dp) >= 2 else (2.5 if p_room(pp) > 0 else -2.5) elif side and last is not None: # add a part across the last move's direction n = np.hypot(*last) + 1e-9 size = max(np.hypot(dy, dp), 3.0) * 0.6 * abs(side) dy2, dp2 = dy - last[1] / n * size * np.sign(side), dp + last[0] / n * size * np.sign(side) else: dy2, dp2 = dy, dp dy2, dp2 = _fit(py, dy2, -YAW_SWAY, YAW_SWAY, MIN_CHANGE[0]), _fit(pp, dp2, lo, hi, MIN_CHANGE[1]) if last is None or MIN_TURN_DEG <= _turn(last, (dy2, dp2)) <= 180 - MIN_TURN_DEG: break return dy2, dp2 def head_targets(song, seed=0): """[(call s, yaw deg, pitch deg, speed %)] around yaw 0 / pitch CENTRE_PITCH, each move timed to land ON a beat (called reach_time before it) and never before the last call returned. Energetic parts: a small diagonal bob on every beat that leaves time (alternating sides, vel 100), and on a bar's accent or a phrase start a quick 15-25 deg sweep with a dip. Calm parts: slower sways. Every move changes both axes and turns away from the last move's line (_bend).""" rng = random.Random(seed) beats = song_beats(song) lo, hi = PITCH_RANGE y, p, free = 0.0, 0.0, 0.0 # the pose and when the last call returns (starts at 0 / 0) side, last, last_accent, out, pending = rng.choice((-1, 1)), None, -9.0, [], False for k, (t, e, accent, phrase) in enumerate(beats): if t < 0.8: # the head is still turning to 0 / 0 continue pending = pending or ((accent >= 0.7 or phrase) and t - last_accent >= ACCENT_EVERY_S and e >= 0.3) if pending: # an accent waits for the first beat it fits on kind, vel = "accent", VEL_LIVELY elif e >= ENERGETIC: kind, vel = "bob", VEL_LIVELY else: kind, vel = "sway", VEL_CALM if e >= CALMEST else VEL_CALMEST if kind != "bob" or rng.random() < 0.85: side = -side if kind == "accent": # a sweep across to the other side, dipping side = -1 if y > 0 else 1 ty = side * rng.uniform(*ACCENT_DEG) * 0.7 + 0.3 * y tp = rng.choice((max(lo, min(p, CENTRE_PITCH + 2) - rng.uniform(6, 10)), min(hi, CENTRE_PITCH + rng.uniform(8, 14)))) # dip or lift elif kind == "bob": size = rng.uniform(*BOB_DEG) ty = y + side * size * rng.uniform(0.7, 1.0) tp = (p - size * 0.8 if p > CENTRE_PITCH else p + size * 0.8) + rng.uniform(-1, 1) # diagonal else: ty = side * rng.uniform(*SWAY_DEG) tp = CENTRE_PITCH + rng.uniform(-8, 8) ty -= 0.15 * y if kind == "bob" else 0.0 # bobs drift back toward the middle dy, dp = _bend(y, p, ty - y, tp - p, last) call = t - reach_time(dy, dp, vel) # lands on the beat for _ in range(8): # too little time: a smaller move (an accent stays big) if call >= free + GAP_S or max(abs(dy), abs(dp)) <= (ACCENT_DEG[0] if kind == "accent" else 3.0): break dy, dp = _bend(y, p, dy * 0.8, dp * 0.8, last) call = t - reach_time(dy, dp, vel) if last is not None and not MIN_TURN_DEG <= _turn(last, (dy, dp)) <= 180 - MIN_TURN_DEG: n = np.hypot(*last) + 1e-9 # still on the last line: a small step across it instead for size in (4.0, -4.0, 6.0, -6.0, 2.5, -2.5): dy = _fit(y, -last[1] / n * size, -YAW_SWAY, YAW_SWAY, MIN_CHANGE[0] + 0.2) dp = _fit(p, last[0] / n * size, lo, hi, MIN_CHANGE[1] + 0.2) if MIN_TURN_DEG <= _turn(last, (dy, dp)) <= 180 - MIN_TURN_DEG: break call = t - reach_time(dy, dp, vel) if call < free + GAP_S or last is not None and not MIN_TURN_DEG <= _turn(last, (dy, dp)) <= 180 - MIN_TURN_DEG: continue # no time or no fitting move for this beat: a later one out.append((round(float(call), 3), round(float(y + dy), 2), round(float(p + dp), 2), int(vel))) free = call + move_time(dy, dp, vel) last, y, p = (dy, dp), y + dy, p + dp if kind == "accent": last_accent, pending = t, False return out def around(centre, y): """A dance yaw y (within +-YAW_SWAY of 0) moved to the centre yaw; the side toward YAW_LIMIT squeezed to fit.""" centre = max(-YAW_LIMIT, min(YAW_LIMIT, centre)) room = min(YAW_SWAY, YAW_LIMIT - abs(centre)) if y * centre > 0 else YAW_SWAY return round(centre + y * room / YAW_SWAY, 2) def _move_head(song, seed, stop, head_api, centre=0.0): """Turn the head to the centre yaw / pitch 0, follow the head targets around it until the song ends or stop is set, then go back to the centre yaw / pitch 0. One call at a time (each blocks until the head arrives).""" try: lift, waist, _, _ = head_api.status() except Exception as e: print(f"sing: head status failed: {e}") return t0 = time.time() try: head_api.moveto([lift, waist, around(centre, 0.0), 0.0], VEL_LIVELY, VEL_LIVELY) for t, yaw, pitch, vel in head_targets(song, seed): while not stop.is_set() and time.time() - t0 < t: stop.wait(0.02) if stop.is_set(): break if time.time() - t0 - t > LATE_S: continue head_api.moveto([lift, waist, around(centre, yaw), pitch], vel, vel) except Exception as e: print(f"sing: head move failed: {e}") finally: try: head_api.moveto([lift, waist, around(centre, 0.0), 0.0], HEAD_VEL, HEAD_VEL) except Exception as e: print(f"sing: head return failed: {e}") def sing(song_id, abort=None, play=None, head_api=None, load=None, centre_yaw=0.0): """Sing one song; blocks until it ends (True) or abort() becomes True (False). The head dances around centre_yaw (deg, toward the listener) and returns in its own thread, so a stop is at once. play / head_api / load are for tests (default: the speaker and the real head).""" global _head_thread from audio import mouth if play is None: mouth._set_volume() play = mouth._play if head_api is None: from robot import head as head_api if load is None: import soundfile as sf def load(path): return sf.read(path, dtype="float32") song = songs()[song_id] wav, rate = load(song["wav"]) wav = np.asarray(wav) if wav.ndim == 2: # the owner's songs are stereo; the speaker is one channel wav = wav.mean(1) if _head_thread is not None: _head_thread.join(RETURN_WAIT_S) # the head is still going back from the last song # the clip mic hears the song: its words are Lumi's own voice until 30 s after its end (mouth.recent_speech) mouth._recent.append((time.time() + len(wav) / rate, song["lyrics"])) stop = threading.Event() _head_thread = threading.Thread(target=_move_head, args=(song, time.time(), stop, head_api, centre_yaw), daemon=True) _head_thread.start() try: return bool(play(wav, rate, abort)) finally: stop.set() if __name__ == "__main__": if len(sys.argv) < 2: for sid, s in songs().items(): print(f"{sid:24} {s['lang']} {s['title']}") else: print("finished" if sing(sys.argv[1]) else "stopped") if _head_thread: _head_thread.join()