voice: wake-word barge-in (interrupt a spoken reply)

While a reply is speaking the wake word is still scored, so the user can
interrupt it. On a wake the daemon aborts the playback, mutes further
speech while the interrupt is captured/handled, and hands the following
command to the front end. A bare "stop"/"cancel" aborts the reply and
drops anything queued behind it; anything else runs as a new command.

- voice_transport: AudioIO.play(pcm, rate, stop_event); SoundDeviceAudio
  streams in ~50 ms chunks and aborts the output stream on a stop.
  VoiceDaemon gains barge_in.{enabled,wait_s,threshold} and the
  on_barge_in(active) callback; speak() drops text while muted and plays
  through the interruptible path.
- gateway/voice: tags the interrupt utterance (raw["barge_in"]),
  classifies stop vs new command (_is_stop_command), drops queued replies
  on stop, and unmutes once handled.
- config: gateway.voice.barge_in block; config.example.json regenerated.
- tests: wake-abort, mute release, threshold gate, stop/new-command
  classification, sentinel preservation.
This commit is contained in:
gabby committed 2026-10-17 16:56:44 +00:00
1 parent a8ca65a6e4
commit faebe8a53a
6 files changed
+542 -57

No files matched your search

+10 -1
View File
@@ -237,7 +237,16 @@ CORE_SCHEMA: dict[str, Any] = {'tau': {'default': 0.6, 'type': 'float', 'doc': '
'initial_silence_ms': {'default': 1500, 'type': 'int'},
'aggressiveness': {'default': 2, 'type': 'int'},
'energy_threshold': {'default': 200.0, 'type': 'float'}},
'follow_up_window_s': {'default': 0.0, 'type': 'float'}}},
'follow_up_window_s': {'default': 0.0, 'type': 'float'},
# Interrupt a spoken reply with the wake word: stop the
# playback, listen for a command, and either abort (a
# bare "stop"/"cancel") or run the new command. Disable
# for strict half-duplex (the agent never listens while
# speaking). `wait_s` bounds how long to wait for the
# interrupted playback to release the audio device.
'barge_in': {'enabled': {'default': True, 'type': 'bool'},
'wait_s': {'default': 2.0, 'type': 'float'},
'threshold': {'default': 0.0, 'type': 'float'}}}},
'dashboard': {'port': {'default': 8765, 'type': 'int'},
'host': {'default': '127.0.0.1', 'type': 'str'}},
'skill_packs': {'default': 'packs',
+108 -1
View File
@@ -27,6 +27,55 @@ from semif_agent.voice_transport import VoiceDaemon
from .base import GatewayAdapter, InboundMessage, OutboundMessage
#: Words/phrases that abort a spoken reply when heard after a barge-in. The
#: match is on the whole normalized utterance (so "stop the timer" stays a real
#: command) with a first-word fallback only for a short utterance with trailing
#: filler ("stop please", "cancel that").
_STOP_PHRASES = {
"stop",
"stop it",
"stop talking",
"stop please",
"cancel",
"cancel that",
"cancel please",
"quiet",
"quiet down",
"be quiet",
"silence",
"hush",
"shut up",
"never mind",
"nevermind",
"enough",
}
_STOP_FIRST_WORDS = {"stop", "cancel", "quiet", "silence", "hush", "shut", "enough"}
_STOP_FILLER = {"please", "now", "it", "that", "talking", "down", "up", "already"}
#: Characters stripped from a spoken utterance's edges before matching.
_PUNCT = " \t\r\n.,!?;:\"'()[]{}"
def _is_stop_command(text: str) -> bool:
"""Whether an interrupt utterance means "stop talking" (vs a new command).
Deterministic vocabulary, no model: a bare "stop"/"cancel" (or a short
variant like "stop please") aborts the spoken reply. Anything longer is a
real command and is submitted as a new request.
"""
cleaned = (text or "").strip().lower().strip(_PUNCT)
if not cleaned:
return False
if cleaned in _STOP_PHRASES:
return True
words = cleaned.split()
if len(words) > 3:
return False
first = words[0].strip(_PUNCT)
if first not in _STOP_FIRST_WORDS:
return False
return all(word.strip(_PUNCT) in _STOP_FILLER for word in words[1:])
class VoiceAdapter(GatewayAdapter):
name = "voice"
@@ -41,12 +90,19 @@ class VoiceAdapter(GatewayAdapter):
self.display_name = str(cfg.get("display_name") or self.chat_id)
#: `run()` blocks on the mic; this daemon owns capture/wake/STT/TTS.
self.daemon = VoiceDaemon(cfg, trace=trace, name=self.name)
#: Set by the daemon while a barge-in command is being captured, so the
#: transcribed utterance is classified as an interrupt.
self._barged_in = False
self.daemon.on_barge_in = self._on_barge_in
self._on_inbound = None
#: Utterances are handed to a worker thread, not run on the audio
#: thread: the scheduler is synchronous and can block on the decision
#: engine, and a slow or failing task must neither stop the mic being
#: read nor kill the front end. `None` asks the worker to stop.
self._inbound: "queue.Queue[InboundMessage | None]" = queue.Queue()
#: The outbound reply queue (set in `run`), so a "stop" can drop replies
#: that were already queued behind the interrupted one.
self._outbound: "queue.Queue[OutboundMessage | None] | None" = None
# ---- requirements ----
@@ -71,6 +127,7 @@ class VoiceAdapter(GatewayAdapter):
outbound: "queue.Queue[OutboundMessage | None]",
) -> None:
self._on_inbound = on_inbound
self._outbound = outbound
def _pump() -> None:
# Drain the service's replies onto the daemon's speaker. Speaking
@@ -112,6 +169,27 @@ class VoiceAdapter(GatewayAdapter):
self._handle(message)
def _handle(self, message: InboundMessage) -> None:
if message.raw.get("barge_in"):
if _is_stop_command(message.text):
# A "stop"/"cancel" after a barge-in aborts the spoken reply and
# is not a request: the daemon already cut the playback, and any
# reply still queued behind it is stale output the user stopped.
self.daemon._event("gateway_barge_in_stop", chars=len(message.text))
self._drop_pending_speech()
self.daemon.set_muted(False)
return
# A new command after a barge-in: the playback was already aborted,
# so just run it (and unmute once it has been handled).
self.daemon._event("gateway_barge_in_command", chars=len(message.text))
try:
if self._on_inbound is not None:
self._on_inbound(message)
except Exception as exc:
self.daemon._event("gateway_handler_failed", message=str(exc)[:300])
self.daemon.speak("Sorry, something went wrong handling that.")
finally:
self.daemon.set_muted(False)
return
if self._on_inbound is None:
return
try:
@@ -120,10 +198,39 @@ class VoiceAdapter(GatewayAdapter):
self.daemon._event("gateway_handler_failed", message=str(exc)[:300])
self.daemon.speak("Sorry, something went wrong handling that.")
def _drop_pending_speech(self) -> None:
"""Discard replies already queued behind an interrupted one.
The daemon aborted the in-flight playback; anything waiting on the
outbound queue is output the user asked to stop, so it is dropped rather
than spoken next.
"""
outbound = self._outbound
if outbound is None:
return
dropped = 0
while True:
try:
message = outbound.get_nowait()
except queue.Empty:
break
if message is None:
outbound.put(None) # preserve the pump's shutdown sentinel
break
dropped += 1
if dropped:
self.daemon._event("gateway_speech_dropped", count=dropped)
def _on_barge_in(self, active: bool) -> None:
"""Daemon callback: mark a barge-in session (True) and its end (False)."""
self._barged_in = bool(active)
def _on_utterance(self, text: str) -> None:
text = (text or "").strip()
if not text:
return
barge_in = self._barged_in
self._barged_in = False
self.daemon._event(
"gateway_message",
contact_id=self.chat_id,
@@ -137,6 +244,6 @@ class VoiceAdapter(GatewayAdapter):
chat_type="dm",
contact_id=self.chat_id,
display_name=self.display_name,
raw={},
raw={"barge_in": True} if barge_in else {},
)
)
+204 -42
View File
@@ -15,8 +15,14 @@ Audio contract: 16 kHz, mono, signed 16-bit little-endian PCM, read in fixed
resampling is done in the loop.
Design notes:
- **Half-duplex.** Capture frames are discarded while a reply is being spoken,
so the agent never transcribes its own voice (no barge-in yet).
- **Half-duplex by default, barge-in optional.** Capture frames are normally
discarded while a reply is being spoken, so the agent never transcribes its
own voice. With barge-in enabled (`barge_in.enabled`), the wake word is still
scored during playback: the user can interrupt a spoken reply, the playback
is aborted, and the following command is captured and handed to the front end
(which decides whether it is a stop or a new request). Speech is muted while
the interrupt command is captured and handled, so the interrupted reply does
not resume over the user.
- The engine interfaces are plain classes so tests can inject fakes and drive
the loop without hardware or the optional packages.
"""
@@ -150,6 +156,17 @@ class AudioIO:
def write(self, pcm16: bytes, sample_rate: int) -> None:
raise NotImplementedError
def play(self, pcm16: bytes, sample_rate: int, stop_event=None) -> bool:
"""Play PCM, returning `False` if aborted early via `stop_event`.
The default plays the whole buffer in one `write`. The real device
overrides this to stream in small chunks so a barge-in stops the reply
promptly instead of after the whole buffer; a fake that only implements
`write` still plays through here.
"""
self.write(pcm16, sample_rate)
return True
def flush(self) -> None:
"""Drop any buffered capture frames (called after speaking to clear echo)."""
@@ -562,6 +579,40 @@ class SoundDeviceAudio(AudioIO):
) as stream:
stream.write(pcm16)
def play(self, pcm16: bytes, sample_rate: int, stop_event=None) -> bool:
"""Stream PCM in small chunks so a barge-in can abort playback.
A single `write` of the whole buffer blocks until the device drains it,
so an interrupt could only take effect after the reply had finished. The
buffer is played in ~50 ms chunks instead, checking `stop_event` between
them; on a stop the stream is aborted (discarding what is still buffered)
and `False` is returned. One output stream is opened for the whole
buffer, so the chunks play gaplessly.
"""
import sounddevice as sd
rate = self.output_sample_rate or self._device_rate(
self.output_device, "output"
)
if rate != int(sample_rate):
pcm16 = _resample_pcm16(pcm16, int(sample_rate), rate)
chunk = max(BYTES_PER_SAMPLE, int(rate * 0.05) * BYTES_PER_SAMPLE) # 50 ms
with sd.RawOutputStream(
samplerate=rate,
channels=1,
dtype="int16",
device=self.output_device,
) as stream:
for offset in range(0, len(pcm16), chunk):
if stop_event is not None and stop_event.is_set():
try:
stream.abort()
except Exception:
pass
return False
stream.write(pcm16[offset : offset + chunk])
return True
def flush(self) -> None:
try:
while not self._frames.empty():
@@ -889,7 +940,7 @@ class VoiceDaemon:
"""
def __init__(self, cfg: dict | None = None, trace=None, engines: VoiceEngines | None = None,
name: str = "voice", input_ready=None):
name: str = "voice", input_ready=None, on_barge_in=None):
cfg = cfg or {}
self.config = cfg
self.trace = trace
@@ -899,6 +950,11 @@ class VoiceDaemon:
#: is still running the current request), so a second command cannot be
#: started before the first reaches a result. None = always ready.
self.input_ready = input_ready
#: Optional callback the loop invokes around a barge-in: `True` when the
#: wake word is heard over a spoken reply (playback aborted, listening
#: begins), `False` once that listening session ends. The front end uses
#: it to classify the following utterance as an interrupt.
self.on_barge_in = on_barge_in
self.wake_threshold = float((cfg.get("wake", {}) or {}).get("threshold", 0.2))
#: After the wake word, how long to wait for the command's speech to
#: begin before giving up (a natural pause after "hey <word>" — e.g.
@@ -944,12 +1000,29 @@ class VoiceDaemon:
self.cue_submit_notes = _parse_notes(cue.get("submit_notes"))
self.cue_note_gap_ms = int(cue.get("note_gap_ms", 20) or 0)
#: Barge-in: keep scoring the wake word while a reply is playing, abort
#: the playback on a wake, and mute speech while the interrupt command
#: is captured/handled. `wait_s` bounds how long to wait for the
#: interrupted playback to release the audio device. `threshold`
#: overrides the wake threshold for barge-in only (a higher bar keeps
#: the agent's own TTS from self-triggering; 0 = use `wake.threshold`).
barge_cfg = cfg.get("barge_in", {}) or {}
self.barge_in_enabled = bool(barge_cfg.get("enabled", True))
self.barge_in_wait_s = float(barge_cfg.get("wait_s", 2.0) or 0.0)
self.barge_in_threshold = (
float(barge_cfg.get("threshold", 0.0) or 0.0) or self.wake_threshold
)
self._engines = engines
self._engines_lock = threading.Lock()
self._audio_lock = threading.Lock() # serialize cue/speak playback
self._on_utterance: UtteranceHandler | None = None
self._stop = threading.Event()
self._speaking = threading.Event()
#: Set while a reply is being played; `_interrupt` aborts that playback.
self._interrupt = threading.Event()
#: While set, `speak` drops text (a barge-in is being captured/handled).
self._mute = threading.Event()
# ---- requirements ----
@@ -1022,49 +1095,111 @@ class VoiceDaemon:
return
if not pcm:
continue
barge_in = False
if self._speaking.is_set():
continue
score = engines.wake.score(pcm)
if score < self.wake_threshold:
continue
if self.input_ready is not None and not self.input_ready():
# The single scheduler slot is still running the current
# request: hold the wake word until it reaches a result (or
# pauses for the user's answer), so a new command cannot start
# while one is in flight. Reset the detector so the same wake
# phrase does not immediately re-fire once the slot frees.
# Half-duplex by default: the agent's own voice is discarded.
# With barge-in enabled the wake word is still scored, so the
# user can interrupt a spoken reply ("hey <word>, stop").
if not self.barge_in_enabled:
continue
score = engines.wake.score(pcm)
if score < self.barge_in_threshold:
continue
barge_in = True
self._begin_barge_in(engines, score)
else:
score = engines.wake.score(pcm)
if score < self.wake_threshold:
continue
delivered = False
try:
if self.input_ready is not None and not self.input_ready():
# The single scheduler slot is still running the current
# request: hold the wake word until it reaches a result (or
# pauses for the user's answer), so a new command cannot
# start while one is in flight. Reset the detector so the
# same wake phrase does not immediately re-fire once the
# slot frees.
try:
engines.wake.reset()
except Exception:
pass
self._event("voice_wake_blocked", score=round(float(score), 3))
continue
if not barge_in:
self._event("voice_wake", score=round(float(score), 3))
try:
engines.wake.reset()
except Exception:
pass
self._event("voice_wake_blocked", score=round(float(score), 3))
continue
self._event("voice_wake", score=round(float(score), 3))
self._cue(self.cue_frequency, self.cue_duration_ms)
# Wait for the command to start rather than assuming it is glued
# to the wake word (the wake frame + a natural pause are
# discarded so the command is not truncated).
wait_for_speech_ms = self.listen_timeout_ms
utterance = self._collect(engines, pcm, wait_for_speech_ms=wait_for_speech_ms)
if not utterance:
continue
try:
text = engines.stt.transcribe(utterance)
except Exception as exc:
self._event("voice_stt_failed", message=str(exc)[:300])
continue
text = (text or "").strip()
if not text:
self._event("voice_stt_empty", samples=len(utterance) // BYTES_PER_SAMPLE)
continue
self._event("voice_transcribed", chars=len(text))
self._bling()
delivered = True
if self._on_utterance is not None:
self._on_utterance(text)
finally:
if barge_in:
self._end_barge_in(delivered)
def _begin_barge_in(self, engines: VoiceEngines, score: float) -> None:
"""Abort the current reply and start listening for an interrupt.
The playback is stopped (the daemon's `play` watches `_interrupt`) and
speech is muted so the interrupted reply cannot resume over the user
while the interrupt command is captured and handled. The front end is
told via `on_barge_in(True)` so it can classify the next utterance.
"""
self._event("voice_barge_in", score=round(float(score), 3))
self._mute.set()
self._interrupt.set()
if self.on_barge_in is not None:
try:
engines.wake.reset()
self.on_barge_in(True)
except Exception:
pass
self._cue(self.cue_frequency, self.cue_duration_ms)
# Wait for the command to start rather than assuming it is glued to
# the wake word (the wake frame + a natural pause are discarded so
# the command is not truncated).
wait_for_speech_ms = self.listen_timeout_ms
utterance = self._collect(engines, pcm, wait_for_speech_ms=wait_for_speech_ms)
if not utterance:
continue
# Wait for the interrupted playback to release the audio device so the
# wake cue and the captured command are not played over it.
deadline = time.time() + self.barge_in_wait_s
while self._speaking.is_set() and time.time() < deadline:
time.sleep(0.005)
try:
engines.audio.flush() # drop the reply's echo captured while speaking
except Exception:
pass
def _end_barge_in(self, delivered: bool) -> None:
"""Close a barge-in session.
`delivered` is True when a command was transcribed and handed to the
front end; the front end then owns un-muting (it un-mutes only after the
interrupt has been handled, so the interrupted reply never resumes). A
barge-in that captured nothing un-mutes here.
"""
self._interrupt.clear()
if self.on_barge_in is not None:
try:
text = engines.stt.transcribe(utterance)
except Exception as exc:
self._event("voice_stt_failed", message=str(exc)[:300])
continue
text = (text or "").strip()
if not text:
self._event("voice_stt_empty", samples=len(utterance) // BYTES_PER_SAMPLE)
continue
self._event("voice_transcribed", chars=len(text))
self._bling()
if self._on_utterance is not None:
self._on_utterance(text)
self.on_barge_in(False)
except Exception:
pass
if not delivered or self.on_barge_in is None:
self._mute.clear()
def _collect(self, engines: VoiceEngines, first_frame: bytes, wait_for_speech_ms: int = 0) -> bytes:
"""Accumulate frames from the wake word until trailing silence.
@@ -1243,15 +1378,34 @@ class VoiceDaemon:
except Exception as exc:
self._event("voice_cue_failed", message=str(exc)[:200])
def set_muted(self, muted: bool) -> None:
"""Mute/unmute spoken replies (used around a barge-in)."""
if muted:
self._mute.set()
else:
self._mute.clear()
def speak(self, text: str) -> None:
"""Synthesize and play `text`; called from the outbound pump thread."""
text = (text or "").strip()
if not text:
return
if self._mute.is_set():
# A barge-in is in progress: the user interrupted and is giving a
# new command, so a pending reply is dropped rather than played over
# them. Replies after the interrupt is handled are spoken normally.
self._event("voice_speak_suppressed", chars=len(text))
return
if self.max_speak_chars and len(text) > self.max_speak_chars:
clipped = text[: self.max_speak_chars].rsplit(" ", 1)[0]
text = (clipped or text[: self.max_speak_chars]) + "…"
engines = self._ensure_engines()
# Start from a clean wake-detector state so the reply's own audio does
# not inherit a stale partial match.
try:
engines.wake.reset()
except Exception:
pass
self._speaking.set()
self._event("voice_speak_start", chars=len(text))
try:
@@ -1266,11 +1420,19 @@ class VoiceDaemon:
else 0.0,
)
if pcm:
with self._audio_lock:
engines.audio.open_output(sample_rate)
# The instant the first reply audio is handed to the device.
self._event("voice_playback_start", ts=time.time(), chars=len(text))
engines.audio.write(pcm, sample_rate)
if self._interrupt.is_set():
# A barge-in landed during synthesis; skip playback.
self._event("voice_speak_aborted", chars=len(text))
else:
with self._audio_lock:
engines.audio.open_output(sample_rate)
# The instant the first reply audio is handed to the device.
self._event("voice_playback_start", ts=time.time(), chars=len(text))
completed = engines.audio.play(
pcm, sample_rate, stop_event=self._interrupt
)
if not completed:
self._event("voice_speak_interrupted", chars=len(text))
self._event("voice_spoke", chars=len(text))
except Exception as exc:
self._event("voice_speak_failed", message=str(exc)[:300])