Improve attention, voice direction, reach, pick and follow from live feedback
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
+95
-19
@@ -9,7 +9,9 @@ offset + sign * k * 60 deg. Angles are in the head frame: 0 = where the head loo
|
||||
|
||||
Calibration needs people at known angles. lumi.py collects them on its own: while it talks with a person
|
||||
the head camera sees, each utterance of that person is a sample (camera angle = truth). After MIN_SAMPLES
|
||||
samples spread over at least SPREAD_DEG it fits sign / offset / radius and writes doa_calib.json.
|
||||
samples spread over at least SPREAD_DEG it fits sign / offset / radius and writes doa_calib.json, unless the fit is
|
||||
worse than the saved one. With the clip mic a sample is weighted by the clip voice like estimate(), and is skipped
|
||||
when that voice is not found in the array audio.
|
||||
Or by hand:
|
||||
|
||||
python audio/doa.py --calibrate # stand in front of the head camera, talk, move left / right, Ctrl+C to fit
|
||||
@@ -31,6 +33,10 @@ NFFT, HOP = 512, 256
|
||||
BAND = (300.0, 3500.0) # Hz used
|
||||
GRID = np.arange(-180, 180, 2.0) # deg
|
||||
MIN_SAMPLES, SPREAD_DEG = 6, 30.0
|
||||
CLIP_MAX_LAG_S = 0.3 # s searched for the clip mic's voice in the head array audio (radio delay + buffers;
|
||||
# the array window is cut by the clip's own times, so they differ by tens of ms)
|
||||
USE_CLIP_REF = False # weight the direction by the clip mic's voice; off: the plain array estimate
|
||||
CLIP_MIN_SCORE = 8.0 # clip voice found in the array: correlation peak over its spread (unrelated audio ~4-5)
|
||||
PAIRS = [(i, j) for i in range(6) for j in range(i + 1, 6)]
|
||||
|
||||
_freqs = np.fft.rfftfreq(NFFT, 1 / RATE)
|
||||
@@ -46,20 +52,55 @@ def load_calib():
|
||||
return {"radius": 0.04, "offset": 0.0, "sign": 1, "fitted": False}
|
||||
|
||||
|
||||
def cross_spectra(mics):
|
||||
"""Average PHAT-normalised cross-spectra of all mic pairs: (15, n_band) complex, or None if too short."""
|
||||
def _spectra(x):
|
||||
"""Band spectra of 50 % overlapping windows: (t, F, channels)."""
|
||||
win = np.hanning(NFFT).astype(np.float32)
|
||||
frames = np.stack([x[i:i + NFFT] * win[:, None] for i in range(0, len(x) - NFFT, HOP)]) # (t, NFFT, ch)
|
||||
return np.fft.rfft(frames, axis=1)[:, _band, :]
|
||||
|
||||
|
||||
def clip_lag(mics, ref):
|
||||
"""Where the clip mic's voice sits in the head array audio: (lag, score). Clip sample k is array sample k + lag;
|
||||
score = GCC-PHAT peak (clip against the array's mean, speech band) over the spread of the correlation."""
|
||||
a, c = mics.astype(np.float32).mean(1), np.asarray(ref, np.float32)
|
||||
n = 1 << int(np.ceil(np.log2(len(a) + len(c))))
|
||||
f = np.fft.rfftfreq(n, 1 / RATE)
|
||||
x = np.fft.rfft(a, n) * np.conj(np.fft.rfft(c, n))
|
||||
x = np.where((f >= BAND[0]) & (f <= BAND[1]), x / (np.abs(x) + 1e-9), 0)
|
||||
cc = np.fft.irfft(x, n)
|
||||
m = int(CLIP_MAX_LAG_S * RATE)
|
||||
cc = np.concatenate([cc[-m:], cc[:m + 1]]) # lags -m .. +m
|
||||
k = int(np.argmax(cc))
|
||||
return k - m, float(cc[k] / (cc.std() + 1e-12))
|
||||
|
||||
|
||||
def cross_spectra(mics, ref=None):
|
||||
"""Average PHAT-normalised cross-spectra of all mic pairs: (15, n_band) complex, or None if too short.
|
||||
|
||||
ref: the clip mic's audio of the same utterance (worn by the person talking to Lumi). The array then hears that
|
||||
person faintly under louder room sound, so the louder-frames rule picks the room. Instead the clip is lined up
|
||||
with the array (clip_lag) and each time-frequency bin is weighted by the clip's power there: bins where the wearer
|
||||
talks count, the room in between and in other frequencies does not (a fixed share of the strongest bins worked
|
||||
too, but the right share changed with how loud the room was). When the clip voice is not found in the array the
|
||||
plain estimate is made (the louder frames), as without a clip."""
|
||||
x = mics.astype(np.float32)
|
||||
if len(x) < NFFT:
|
||||
return None
|
||||
win = np.hanning(NFFT).astype(np.float32)
|
||||
frames = np.stack([x[i:i + NFFT] * win[:, None] for i in range(0, len(x) - NFFT, HOP)]) # (t, NFFT, 6)
|
||||
spec = np.fft.rfft(frames, axis=1)[:, _band, :] # (t, F, 6)
|
||||
energy = (np.abs(spec) ** 2).sum((1, 2))
|
||||
keep = energy >= np.percentile(energy, 50) # the louder half of the frames: the voice, not pauses
|
||||
spec = spec[keep]
|
||||
spec = _spectra(x) # (t, F, 6)
|
||||
lag, score = clip_lag(x, ref) if ref is not None and len(ref) else (0, 0.0)
|
||||
if score < CLIP_MIN_SCORE:
|
||||
energy = (np.abs(spec) ** 2).sum((1, 2))
|
||||
w = (energy >= np.percentile(energy, 50))[:, None] * np.ones(spec.shape[1]) # the louder half of the frames:
|
||||
else: # the voice, not pauses
|
||||
c = np.zeros(len(x), np.float32) # the clip at the array's sample times
|
||||
src = np.asarray(ref, np.float32)[max(0, -lag):]
|
||||
c[max(0, lag):max(0, lag) + len(src)] = src[:len(x) - max(0, lag)]
|
||||
p = np.abs(_spectra(c[:, None])[:, :, 0]) ** 2 # (t, F) clip power
|
||||
w = p / (p.max() + 1e-12)
|
||||
g = np.stack([(spec[:, :, i] * np.conj(spec[:, :, j])) for i, j in PAIRS]) # (15, t, F)
|
||||
g = g / (np.abs(g) + 1e-9)
|
||||
return g.mean(1) # (15, F)
|
||||
return (g * w[None]).sum(1) / w.sum(0).max() # weighted mean over the frames: (15, F); a frequency
|
||||
# where the clip voice is weak counts little
|
||||
|
||||
|
||||
def _steering(radius, offset, sign):
|
||||
@@ -82,10 +123,33 @@ def _power(g, calib):
|
||||
return np.real((_cache[key] * g[None]).sum((1, 2))) # (n_grid,)
|
||||
|
||||
|
||||
def estimate(mics, calib=None):
|
||||
"""(angle deg in the head frame, confidence 0..1, raw angle with the default geometry)."""
|
||||
def clip_ref(u):
|
||||
"""The clip mic's audio of an utterance cut from it (its wearer's voice is the one to find), else None. Off
|
||||
(USE_CLIP_REF): live, the clip-weighted direction came out at confidence 0.03-0.07, too weak to trust."""
|
||||
return u.mono if USE_CLIP_REF and getattr(u, "source", None) == "clip" else None
|
||||
|
||||
|
||||
def clip_found(mics, ref):
|
||||
"""Is the clip mic's voice clearly in the head array audio (then the estimate is its wearer's direction)?"""
|
||||
if ref is None or mics is None or len(mics) < NFFT or not len(ref):
|
||||
return False
|
||||
return clip_lag(mics, ref)[1] >= CLIP_MIN_SCORE
|
||||
|
||||
|
||||
def clip_note(mics, ref):
|
||||
"""For the log: how clearly the clip voice was found in the array audio, "" without a clip."""
|
||||
if ref is None or mics is None or len(mics) < NFFT or not len(ref):
|
||||
return ""
|
||||
lag, score = clip_lag(mics, ref)
|
||||
if score < CLIP_MIN_SCORE:
|
||||
return f", clip not found (score {score:.1f})"
|
||||
return f", clip score {score:.0f} at {lag * 1000 / RATE:+.0f} ms"
|
||||
|
||||
|
||||
def estimate(mics, calib=None, ref=None):
|
||||
"""(angle deg in the head frame, confidence 0..1, raw angle with the default geometry). ref: see cross_spectra."""
|
||||
calib = calib or load_calib()
|
||||
g = cross_spectra(mics)
|
||||
g = cross_spectra(mics, ref)
|
||||
if g is None:
|
||||
return 0.0, 0.0, 0.0
|
||||
p = _power(g, calib)
|
||||
@@ -96,9 +160,14 @@ def estimate(mics, calib=None):
|
||||
|
||||
|
||||
# ---------- calibration ----------
|
||||
def add_sample(mics, true_deg):
|
||||
"""Store one utterance with its true head-frame angle; refit when there are enough. Returns the new calib or None."""
|
||||
g = cross_spectra(mics)
|
||||
def add_sample(mics, true_deg, ref=None):
|
||||
"""Store one utterance with its true head-frame angle; refit when there are enough. Returns the new calib, or None
|
||||
(too few samples, or the refit explains the samples worse than the saved calibration did: that one is kept).
|
||||
ref: the clip mic's audio (clip_ref): the sample is the wearer's voice as estimate() hears it; an utterance whose
|
||||
clip voice is not found in the array audio is no sample (the array heard the room, not the wearer)."""
|
||||
if ref is not None and len(ref) and len(mics) >= NFFT and clip_lag(mics, ref)[1] < CLIP_MIN_SCORE:
|
||||
return None
|
||||
g = cross_spectra(mics, ref)
|
||||
if g is None:
|
||||
return None
|
||||
try:
|
||||
@@ -111,12 +180,13 @@ def add_sample(mics, true_deg):
|
||||
gs, ts = gs[-60:], ts[-60:]
|
||||
np.savez(SAMPLES, g=np.array(gs), t=np.array(ts))
|
||||
if len(ts) >= MIN_SAMPLES and max(ts) - min(ts) >= SPREAD_DEG:
|
||||
return fit(np.array(gs), np.array(ts))
|
||||
return fit(np.array(gs), np.array(ts), keep_better=True)
|
||||
return None
|
||||
|
||||
|
||||
def fit(gs, ts):
|
||||
"""Grid search sign / offset / radius that best explains the samples; saves doa_calib.json."""
|
||||
def fit(gs, ts, keep_better=False):
|
||||
"""Grid search sign / offset / radius that best explains the samples; saves doa_calib.json. keep_better: only when
|
||||
its median error is no worse than the saved calibration's (else None, the saved one stays)."""
|
||||
best = None
|
||||
for sign in (1, -1):
|
||||
for radius in (0.03, 0.035, 0.04, 0.045, 0.05):
|
||||
@@ -130,6 +200,12 @@ def fit(gs, ts):
|
||||
if best is None or score < best[0]:
|
||||
best = (score, c)
|
||||
score, c = best
|
||||
if keep_better:
|
||||
try:
|
||||
if round(score, 1) > float(json.loads(CALIB.read_text())["median_error_deg"]):
|
||||
return None
|
||||
except (FileNotFoundError, ValueError, KeyError):
|
||||
pass
|
||||
c["median_error_deg"] = round(score, 1)
|
||||
c["samples"] = len(ts)
|
||||
c["time"] = time.strftime("%Y-%m-%d %H:%M")
|
||||
|
||||
@@ -273,6 +273,14 @@ def transcribe(audio, prompt=None):
|
||||
return text
|
||||
|
||||
|
||||
def quick(audio):
|
||||
"""transcribe() for a short window of speech still going on (mic.peek()): not kept in HEARD_DIR, no early run."""
|
||||
text, stt = _hear(audio, None)
|
||||
last_stt.clear()
|
||||
last_stt.update(stt, early=False)
|
||||
return text
|
||||
|
||||
|
||||
def early(audio):
|
||||
"""mic.py, in a pause of an utterance still going on: whisper starts on what was said so far, in the background
|
||||
(one run at a time: a newer one waits for the older)."""
|
||||
|
||||
+56
-21
@@ -11,7 +11,8 @@ cuts utterances: speech starts when the level stays above START_FACTOR x the bac
|
||||
START_FRAMES frames and ends after END_SILENCE of quiet.
|
||||
While Lumi itself speaks (mouth.py calls speaking()), the head array records nothing (the speaker is ~25x
|
||||
louder than a voice there). The clip mic keeps listening (BARGE_IN): its utterances are marked during_speech, so
|
||||
lumi.py can stop talking when the visitor says "stop" / "thanks" or asks something new.
|
||||
lumi.py can stop talking when the visitor says "stop" / "thanks" or asks something new. Lumi's voice in the clip mic
|
||||
can keep an utterance from ending, so while Lumi talks its last PEEK_WINDOW_S are also offered every PEEK_S (peek()).
|
||||
|
||||
python audio/mic.py # print every utterance: source, length, level and the direction
|
||||
"""
|
||||
@@ -49,7 +50,15 @@ MAX_UTTERANCE = 8.0 # s (12 s: in a room with music an utterance ne
|
||||
PRE_ROLL = 10 # frames kept before the start (300 ms)
|
||||
AFTER_SPEAKING = 0.4 # s still ignored after Lumi stopped talking (room echo)
|
||||
BARGE_IN = True # clip mic: keep listening while Lumi talks (interruptions)
|
||||
PEEK_S = 0.7 # clip mic while Lumi talks: every this many s of an utterance still going on ...
|
||||
PEEK_WINDOW_S = 2.0 # ... its last this many s go to peek() (a stop word: ~0.5 s of whisper on the GPU).
|
||||
# Lumi's voice in the clip mic kept an utterance going to MAX_UTTERANCE: "Stop. Stop.
|
||||
# Stop." was heard only when a 17.9 s answer ended (logs/heard/192150.wav, 2026-10-27)
|
||||
PEEK_MIN_S = 0.5 # s an utterance needs before its first peek
|
||||
RING_S = 20.0 # s of head-array audio kept for the sound direction of clip-mic utterances
|
||||
DUMP_FLAG = ROOT / "data" / "doa_dump_on" # while this file exists each clip-mic utterance is saved with its
|
||||
DUMP_DIR = ROOT / "logs" / "doa_dump" # head-array audio (npz), to check the sound direction offline
|
||||
DUMP_MARGIN_S = 1.0 # s of head-array audio saved before and after the clip's times ("wide")
|
||||
|
||||
|
||||
class Utterance:
|
||||
@@ -132,6 +141,8 @@ class Mic(threading.Thread):
|
||||
self.external = None # ALSA device of the clip mic, when found
|
||||
self.muted_until = 0.0
|
||||
self.speaking_now = False
|
||||
self.talking_since = None # Lumi started talking at (clip mic, during_speech)
|
||||
self.peeked, self.peeked_at = None, 0.0 # see peek()
|
||||
self.error = None
|
||||
|
||||
# the active detector's state (ears.py reads these)
|
||||
@@ -190,6 +201,13 @@ class Mic(threading.Thread):
|
||||
frames = [x for t, x in self.ring if t_start <= t <= t_end + 0.05]
|
||||
return np.concatenate(frames) if frames else np.zeros((0, 6), np.int16)
|
||||
|
||||
def _dump(self, u):
|
||||
"""Save a clip-mic utterance with the head array's audio of its time and DUMP_MARGIN_S around it."""
|
||||
DUMP_DIR.mkdir(parents=True, exist_ok=True)
|
||||
wide = self.head_audio(u.t_start - DUMP_MARGIN_S, u.t_end + DUMP_MARGIN_S)
|
||||
np.savez(DUMP_DIR / time.strftime("%H%M%S.npz"), mics=u.mics, mono=u.mono, wide=wide,
|
||||
t_start=u.t_start, t_end=u.t_end)
|
||||
|
||||
# ---------- recording threads ----------
|
||||
def run(self):
|
||||
threading.Thread(target=self._clip_loop, daemon=True).start()
|
||||
@@ -249,32 +267,49 @@ class Mic(threading.Thread):
|
||||
proc = subprocess.Popen(["arecord", "-q", "-D", dev, "-f", "S16_LE", "-r", str(RATE), "-c", "1", "-t", "raw"],
|
||||
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
|
||||
nbytes = FRAME * 2
|
||||
talking_since = None # Lumi started talking at (for during_speech)
|
||||
self.talking_since = None
|
||||
try:
|
||||
while True:
|
||||
raw = proc.stdout.read(nbytes)
|
||||
if len(raw) < nbytes:
|
||||
return
|
||||
x = np.frombuffer(raw, np.int16)
|
||||
now = time.time()
|
||||
if self.muted():
|
||||
if not BARGE_IN:
|
||||
self.clip_seg.reset()
|
||||
continue
|
||||
talking_since = talking_since or now
|
||||
elif talking_since and not self.clip_seg.in_speech:
|
||||
talking_since = None
|
||||
level = float(np.sqrt(np.mean(x.astype(np.float32) ** 2)))
|
||||
done = self.clip_seg.feed(x, level, now)
|
||||
if done:
|
||||
frames, t0, t1, peak = done
|
||||
during = talking_since is not None and t1 >= talking_since
|
||||
self._put(Utterance(self.head_audio(t0, t1), np.concatenate(frames), t0, t1, peak, "clip", during))
|
||||
elif on_quiet and self.clip_seg.quiet_now():
|
||||
on_quiet(np.concatenate(self.clip_seg.frames))
|
||||
self._clip_frame(np.frombuffer(raw, np.int16), time.time())
|
||||
finally:
|
||||
proc.kill()
|
||||
|
||||
def _clip_frame(self, x, now):
|
||||
"""One 30 ms clip-mic frame (int16 mono)."""
|
||||
if self.muted():
|
||||
if not BARGE_IN:
|
||||
self.clip_seg.reset()
|
||||
return
|
||||
self.talking_since = self.talking_since or now # Lumi started talking at (for during_speech)
|
||||
elif self.talking_since and not self.clip_seg.in_speech:
|
||||
self.talking_since = None
|
||||
level = float(np.sqrt(np.mean(x.astype(np.float32) ** 2)))
|
||||
done = self.clip_seg.feed(x, level, now)
|
||||
if done:
|
||||
frames, t0, t1, peak = done
|
||||
during = self.talking_since is not None and t1 >= self.talking_since
|
||||
u = Utterance(self.head_audio(t0, t1), np.concatenate(frames), t0, t1, peak, "clip", during)
|
||||
if DUMP_FLAG.exists():
|
||||
self._dump(u)
|
||||
self._put(u)
|
||||
elif on_quiet and self.clip_seg.quiet_now():
|
||||
on_quiet(np.concatenate(self.clip_seg.frames))
|
||||
elif self.speaking_now and self.clip_seg.in_speech and now - self.peeked_at >= PEEK_S and \
|
||||
len(self.clip_seg.frames) * FRAME >= PEEK_MIN_S * RATE:
|
||||
# Lumi's own voice in the clip mic keeps the utterance from ending: its last seconds are offered now
|
||||
mono = np.concatenate(self.clip_seg.frames[-round(PEEK_WINDOW_S * RATE / FRAME):])
|
||||
self.peeked = Utterance(np.zeros((0, 6), np.int16), mono, now - len(mono) / RATE, now,
|
||||
self.clip_seg.peak, "clip", True)
|
||||
self.peeked_at = now
|
||||
|
||||
def peek(self):
|
||||
"""The newest window of a clip-mic utterance still going on while Lumi talks (a mic.Utterance, once), or None:
|
||||
lumi.py looks for a stop word in it."""
|
||||
u, self.peeked = self.peeked, None
|
||||
return u
|
||||
|
||||
_mic = None
|
||||
_lock = threading.Lock()
|
||||
@@ -306,8 +341,8 @@ if __name__ == "__main__":
|
||||
u = m.next(1.0)
|
||||
if u is None:
|
||||
continue
|
||||
ang = doa.estimate(u.mics) if len(u.mics) else (0.0, 0.0, 0.0)
|
||||
ang = doa.estimate(u.mics, ref=doa.clip_ref(u)) if len(u.mics) else (0.0, 0.0, 0.0)
|
||||
print(f"[{u.source}] {u.seconds:4.1f} s peak {u.peak:5.0f} noise {m.noise:4.0f} "
|
||||
f"direction {ang[0]:+5.0f} deg (confidence {ang[1]:.2f})")
|
||||
f"direction {ang[0]:+5.0f} deg (confidence {ang[1]:.2f}{doa.clip_note(u.mics, doa.clip_ref(u))})")
|
||||
except KeyboardInterrupt:
|
||||
pass
|
||||
|
||||
@@ -66,6 +66,13 @@ last_echo = None # echo() of the last own_voice() c
|
||||
last_voice = 0.0 # time.time() when the last say_stream() began to play (lumi.py logs it)
|
||||
|
||||
|
||||
def saying(since):
|
||||
"""What Lumi has been saying from `since` (time.time()) on: the sentence playing then and those after it."""
|
||||
texts = [t for when, t in _recent if when > since]
|
||||
before = [t for when, t in _recent if since - 20.0 < when <= since] # a long sentence takes 15 s and more
|
||||
return " ".join(before[-1:] + texts)
|
||||
|
||||
|
||||
def recent_speech(seconds=30.0):
|
||||
"""What Lumi said in the last seconds (lumi.py ignores its own voice picked up by the clip mic).
|
||||
Long sentences take 15 s and more to say, so the window is long."""
|
||||
|
||||
+50
-14
@@ -6,10 +6,12 @@ files, local only, never copied off the robot) and move the head with it. Lumi s
|
||||
|
||||
Each <id>.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 yaw 0 / pitch 0 and dances around it in a thread, following the
|
||||
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 yaw 0 / pitch 0 when the song ends or is stopped. Never the lift, the waist or the arm.
|
||||
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
|
||||
@@ -22,6 +24,8 @@ 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)
|
||||
@@ -41,17 +45,23 @@ BOB_DEG = (7.0, 12.0) # deg, a beat's bob (diagonal nod / tilt), alter
|
||||
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 yaw 0, this pitch
|
||||
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 yaw 0 / pitch 0 before and after the song
|
||||
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"
|
||||
@@ -245,6 +255,23 @@ 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")."""
|
||||
@@ -495,9 +522,16 @@ def head_targets(song, seed=0):
|
||||
return out
|
||||
|
||||
|
||||
def _move_head(song, seed, stop, head_api):
|
||||
"""Turn the head to yaw 0 / pitch 0, follow the head targets until the song ends or stop is set, then go back
|
||||
to yaw 0 / pitch 0. One call at a time (each blocks until the head arrives)."""
|
||||
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:
|
||||
@@ -505,7 +539,7 @@ def _move_head(song, seed, stop, head_api):
|
||||
return
|
||||
t0 = time.time()
|
||||
try:
|
||||
head_api.moveto([lift, waist, 0.0, 0.0], VEL_LIVELY, VEL_LIVELY)
|
||||
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)
|
||||
@@ -513,19 +547,20 @@ def _move_head(song, seed, stop, head_api):
|
||||
break
|
||||
if time.time() - t0 - t > LATE_S:
|
||||
continue
|
||||
head_api.moveto([lift, waist, yaw, pitch], vel, vel)
|
||||
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, 0.0, 0.0], HEAD_VEL, HEAD_VEL)
|
||||
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):
|
||||
"""Sing one song; blocks until it ends (True) or abort() becomes True (False). The head 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)."""
|
||||
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:
|
||||
@@ -547,7 +582,8 @@ def sing(song_id, abort=None, play=None, head_api=None, load=None):
|
||||
# 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), daemon=True)
|
||||
_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))
|
||||
|
||||
Reference in New Issue
Block a user