voice: hold the wake word until the scheduler reaches a result
Gate the wake word on the scheduler's single slot being free: a wake that fires while the current request is still running is ignored (traced voice_wake_blocked), so a second command cannot start mid-run. The gate is GatewayService.input_ready (False while a run executes, True when idle or paused for the user's answer), handed to adapters via set_input_ready; the voice adapter passes it to VoiceDaemon.input_ready.
This commit is contained in:
1 parent
ff94ea938c
commit
88700898be
8 files changed
+130
-7
No files matched your search
@@ -558,7 +558,9 @@ CLI, unit tests (24) + integration tests (2).
|
|||||||
`voice:<chat_id>`, and every reply is spoken. No remote peer and no allowlist
|
`voice:<chat_id>`, and every reply is spoken. No remote peer and no allowlist
|
||||||
(physical mic access is the authorization). Half-duplex: capture is discarded
|
(physical mic access is the authorization). Half-duplex: capture is discarded
|
||||||
while a reply is speaking (no barge-in yet); the wake word is required before
|
while a reply is speaking (no barge-in yet); the wake word is required before
|
||||||
every command. The
|
every command and is held while the scheduler's single slot is still running
|
||||||
|
the current request (`GatewayService.input_ready`), so a second command cannot
|
||||||
|
start until the first reaches a result (or pauses for the user's answer). The
|
||||||
whole voice stack is optional and lazy-imported (`requirements/voice.txt`,
|
whole voice stack is optional and lazy-imported (`requirements/voice.txt`,
|
||||||
pinned separately from the engine set since it is hardware-dependent); the
|
pinned separately from the engine set since it is hardware-dependent); the
|
||||||
gateway refuses to start with an install hint. `bootstrap.sh --voice`
|
gateway refuses to start with an install hint. `bootstrap.sh --voice`
|
||||||
@@ -1173,7 +1175,11 @@ CLI, unit tests (24) + integration tests (2).
|
|||||||
pause before the command does not end the capture (then `vad.silence_ms`).
|
pause before the command does not end the capture (then `vad.silence_ms`).
|
||||||
**Half-duplex**: capture frames are discarded while a
|
**Half-duplex**: capture frames are discarded while a
|
||||||
reply is speaking, so the agent never transcribes itself (no barge-in yet);
|
reply is speaking, so the agent never transcribes itself (no barge-in yet);
|
||||||
the wake word is required before every command. `max_speak_chars`
|
the wake word is required before every command, and is **held while the
|
||||||
|
scheduler slot is busy** (`GatewayService.input_ready`): a wake that fires
|
||||||
|
while the current request is still running is ignored (traced
|
||||||
|
`voice_wake_blocked`), so a second command cannot start until the first
|
||||||
|
reaches a result. `max_speak_chars`
|
||||||
truncates long replies before speaking, and a short sine `cue` beep plays on
|
truncates long replies before speaking, and a short sine `cue` beep plays on
|
||||||
wake (optionally again on transcription) so the user knows they were heard.
|
wake (optionally again on transcription) so the user knows they were heard.
|
||||||
**Result-only output**: `VoiceAdapter.result_only` (default true; per-platform
|
**Result-only output**: `VoiceAdapter.result_only` (default true; per-platform
|
||||||
|
|||||||
@@ -682,7 +682,10 @@ python -m semif_agent.cli gateway --platform voice
|
|||||||
run lower than the official models, the seeded `wake.threshold` is `0.2` (the
|
run lower than the official models, the seeded `wake.threshold` is `0.2` (the
|
||||||
official models score ~0.99 and use `0.5`).
|
official models score ~0.99 and use `0.5`).
|
||||||
- **Behavior.** Half-duplex — capture is discarded while a reply is speaking, so
|
- **Behavior.** Half-duplex — capture is discarded while a reply is speaking, so
|
||||||
the agent never transcribes itself (no barge-in yet). A short beep plays when
|
the agent never transcribes itself (no barge-in yet). The wake word is required
|
||||||
|
before every command and is held while the scheduler is still running the
|
||||||
|
current request, so a second command cannot start until the first reaches a
|
||||||
|
result. A short beep plays when
|
||||||
the wake word fires (`gateway.voice.cue`), so you know you're being heard; a
|
the wake word fires (`gateway.voice.cue`), so you know you're being heard; a
|
||||||
short multi-note "bling" (`cue.submit_notes`, each entry
|
short multi-note "bling" (`cue.submit_notes`, each entry
|
||||||
`[frequency_hz, duration_ms]`, spaced by `cue.note_gap_ms`) plays once the
|
`[frequency_hz, duration_ms]`, spaced by `cue.note_gap_ms`) plays once the
|
||||||
|
|||||||
+1
-1
@@ -217,7 +217,7 @@
|
|||||||
"text_batch_delay": 0.8
|
"text_batch_delay": 0.8
|
||||||
},
|
},
|
||||||
"voice": {
|
"voice": {
|
||||||
"_comment": "Voice command adapter: a local microphone front end with wake word + speech-to-text + text-to-speech. Requires the optional voice stack (requirements/voice.txt; sounddevice + openwakeword + faster-whisper + piper-tts + onnxruntime; the system needs libportaudio2). Lazy-imported; the gateway refuses to start with an install hint. Runs best in the user's audio session (foreground `gateway --platform voice`), not a headless systemd user service. Audio is 16 kHz mono int16; capture/playback run at the device's native rate and are resampled to/from 16 kHz (capture_sample_rate/output_sample_rate override it; 0 = the device default). wake.model is an openWakeWord model name or path (official models download into the venv and resolve by name; a pinned community model such as the default 'hey_computer' is fetched into model_dir, .runtime/voice/wake); stt.model is a faster-whisper size/path (cached under .runtime/hf); tts.voice is a Piper voice id or path (bootstrap downloads it under .runtime/voice/tts). After the wake word, listen_timeout_s is how long to wait for the command to start before giving up, so a pause before speaking does not truncate it. result_only speaks just the skill's result line (dropping queue/urgency bookkeeping and the `<skill>: ok —` wrapper) instead of the full scheduler output; set false for the complete text. max_speak_chars truncates long replies before speaking. chat_id identifies the single local session; home_channel defaults to it so timers/repair offers are spoken too. A stalled capture stream (the PortAudio callback stops delivering frames) is detected via audio.read_timeout_s and recovered by closing and reopening the input after audio.stall_timeout_s, so the front end no longer hangs silently. Utterances run on a worker thread (not the audio thread), so a slow or failing task neither stops the mic being read nor kills the front end.",
|
"_comment": "Voice command adapter: a local microphone front end with wake word + speech-to-text + text-to-speech. Requires the optional voice stack (requirements/voice.txt; sounddevice + openwakeword + faster-whisper + piper-tts + onnxruntime; the system needs libportaudio2). Lazy-imported; the gateway refuses to start with an install hint. Runs best in the user's audio session (foreground `gateway --platform voice`), not a headless systemd user service. Audio is 16 kHz mono int16; capture/playback run at the device's native rate and are resampled to/from 16 kHz (capture_sample_rate/output_sample_rate override it; 0 = the device default). wake.model is an openWakeWord model name or path (official models download into the venv and resolve by name; a pinned community model such as the default 'hey_computer' is fetched into model_dir, .runtime/voice/wake); stt.model is a faster-whisper size/path (cached under .runtime/hf); tts.voice is a Piper voice id or path (bootstrap downloads it under .runtime/voice/tts). After the wake word, listen_timeout_s is how long to wait for the command to start before giving up, so a pause before speaking does not truncate it. The wake word is required before every command and is held while the scheduler is still running the current request, so a new command cannot start until it reaches a result. result_only speaks just the skill's result line (dropping queue/urgency bookkeeping and the `<skill>: ok —` wrapper) instead of the full scheduler output; set false for the complete text. max_speak_chars truncates long replies before speaking. chat_id identifies the single local session; home_channel defaults to it so timers/repair offers are spoken too. A stalled capture stream (the PortAudio callback stops delivering frames) is detected via audio.read_timeout_s and recovered by closing and reopening the input after audio.stall_timeout_s, so the front end no longer hangs silently. Utterances run on a worker thread (not the audio thread), so a slow or failing task neither stops the mic being read nor kills the front end.",
|
||||||
"enabled": false,
|
"enabled": false,
|
||||||
"chat_id": "voice",
|
"chat_id": "voice",
|
||||||
"display_name": "voice",
|
"display_name": "voice",
|
||||||
|
|||||||
@@ -128,6 +128,13 @@ class GatewayService:
|
|||||||
humanize_cfg = humanize_cfg if isinstance(humanize_cfg, dict) else {}
|
humanize_cfg = humanize_cfg if isinstance(humanize_cfg, dict) else {}
|
||||||
self._humanize_default = bool(humanize_cfg.get("enabled", False))
|
self._humanize_default = bool(humanize_cfg.get("enabled", False))
|
||||||
self.humanizer = self._build_humanizer(humanize_cfg)
|
self.humanizer = self._build_humanizer(humanize_cfg)
|
||||||
|
#: Let an adapter that needs it gate input on the scheduler being free
|
||||||
|
#: (the voice gateway holds the wake word until the current request
|
||||||
|
#: reaches a result). Generic hook; only some adapters implement it.
|
||||||
|
for adapter in self.adapters.values():
|
||||||
|
setter = getattr(adapter, "set_input_ready", None)
|
||||||
|
if callable(setter):
|
||||||
|
setter(self.input_ready)
|
||||||
self._owners: dict[str, Target] = {}
|
self._owners: dict[str, Target] = {}
|
||||||
self._parents: dict[str, str] = {}
|
self._parents: dict[str, str] = {}
|
||||||
self._pending_owner: Target | None = None
|
self._pending_owner: Target | None = None
|
||||||
@@ -275,6 +282,22 @@ class GatewayService:
|
|||||||
return (platform, source[len(prefix):])
|
return (platform, source[len(prefix):])
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
def input_ready(self) -> bool:
|
||||||
|
"""Whether a new command may start now.
|
||||||
|
|
||||||
|
False while the single scheduler slot is executing a run; True when the
|
||||||
|
scheduler is idle or paused for the user's answer to a question (the run
|
||||||
|
is not running, so the answer must be accepted). The voice gateway uses
|
||||||
|
this to hold the wake word until the current request has reached a
|
||||||
|
result. Reads the scheduler's flags without its lock on purpose — the
|
||||||
|
lock is held for the whole run, so acquiring it here would block the
|
||||||
|
audio loop for the duration of the run.
|
||||||
|
"""
|
||||||
|
scheduler = self.scheduler
|
||||||
|
if getattr(scheduler, "pending", None) is not None:
|
||||||
|
return True
|
||||||
|
return getattr(scheduler, "current", None) is None
|
||||||
|
|
||||||
def handle_inbound(self, msg: InboundMessage, platform: str | None = None) -> None:
|
def handle_inbound(self, msg: InboundMessage, platform: str | None = None) -> None:
|
||||||
"""Handle one authorized inbound command. Called by the adapter."""
|
"""Handle one authorized inbound command. Called by the adapter."""
|
||||||
if platform is None:
|
if platform is None:
|
||||||
|
|||||||
@@ -53,6 +53,16 @@ class VoiceAdapter(GatewayAdapter):
|
|||||||
def check_requirements(self) -> tuple[bool, str | None]:
|
def check_requirements(self) -> tuple[bool, str | None]:
|
||||||
return self.daemon.check_requirements()
|
return self.daemon.check_requirements()
|
||||||
|
|
||||||
|
def set_input_ready(self, ready) -> None:
|
||||||
|
"""Gate the wake word on the scheduler being able to accept a command.
|
||||||
|
|
||||||
|
`ready` is a callable returning whether a new command may start now
|
||||||
|
(`GatewayService.input_ready`). While it returns False the wake word is
|
||||||
|
ignored, so a second command cannot be started before the current
|
||||||
|
request has reached a result.
|
||||||
|
"""
|
||||||
|
self.daemon.input_ready = ready
|
||||||
|
|
||||||
# ---- transport ----
|
# ---- transport ----
|
||||||
|
|
||||||
def run(
|
def run(
|
||||||
|
|||||||
@@ -633,11 +633,16 @@ class VoiceDaemon:
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
def __init__(self, cfg: dict | None = None, trace=None, engines: VoiceEngines | None = None,
|
def __init__(self, cfg: dict | None = None, trace=None, engines: VoiceEngines | None = None,
|
||||||
name: str = "voice"):
|
name: str = "voice", input_ready=None):
|
||||||
cfg = cfg or {}
|
cfg = cfg or {}
|
||||||
self.config = cfg
|
self.config = cfg
|
||||||
self.trace = trace
|
self.trace = trace
|
||||||
self.name = name
|
self.name = name
|
||||||
|
#: Optional predicate: whether a new command may start now. While it
|
||||||
|
#: returns False the wake word is ignored (the scheduler's single slot
|
||||||
|
#: 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
|
||||||
self.wake_threshold = float((cfg.get("wake", {}) or {}).get("threshold", 0.2))
|
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
|
#: 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.
|
#: begin before giving up (a natural pause after "hey <word>" — e.g.
|
||||||
@@ -766,6 +771,18 @@ class VoiceDaemon:
|
|||||||
score = engines.wake.score(pcm)
|
score = engines.wake.score(pcm)
|
||||||
if score < self.wake_threshold:
|
if score < self.wake_threshold:
|
||||||
continue
|
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.
|
||||||
|
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._event("voice_wake", score=round(float(score), 3))
|
||||||
try:
|
try:
|
||||||
engines.wake.reset()
|
engines.wake.reset()
|
||||||
|
|||||||
@@ -186,6 +186,39 @@ def test_service_submit_error_is_replied(tmp_path):
|
|||||||
assert outbound, "expected a reply"
|
assert outbound, "expected a reply"
|
||||||
|
|
||||||
|
|
||||||
|
def test_service_input_ready_tracks_scheduler(tmp_path):
|
||||||
|
# The voice gateway holds the wake word on this: not ready while a run is
|
||||||
|
# executing, ready when idle or paused for the user's answer.
|
||||||
|
scheduler = build_scheduler(tmp_path)
|
||||||
|
service = build_service(scheduler)
|
||||||
|
assert service.input_ready() is True # idle
|
||||||
|
scheduler.busy("working")
|
||||||
|
assert service.input_ready() is False # a run is executing
|
||||||
|
scheduler.pending = object() # paused for the answer
|
||||||
|
assert service.input_ready() is True
|
||||||
|
scheduler.pending = None
|
||||||
|
scheduler.current = None
|
||||||
|
assert service.input_ready() is True
|
||||||
|
|
||||||
|
|
||||||
|
def test_service_wires_input_ready_into_voice_adapter(tmp_path):
|
||||||
|
# A constructed service hands its `input_ready` to an adapter that exposes
|
||||||
|
# `set_input_ready` (the voice gateway).
|
||||||
|
class ReadyAdapter:
|
||||||
|
name = "voice"
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
self.ready = None
|
||||||
|
|
||||||
|
def set_input_ready(self, fn):
|
||||||
|
self.ready = fn
|
||||||
|
|
||||||
|
scheduler = build_scheduler(tmp_path)
|
||||||
|
adapter = ReadyAdapter()
|
||||||
|
service = GatewayService(scheduler, adapter, config={})
|
||||||
|
assert adapter.ready == service.input_ready
|
||||||
|
|
||||||
|
|
||||||
def test_service_routes_pending_answer_to_same_chat(tmp_path):
|
def test_service_routes_pending_answer_to_same_chat(tmp_path):
|
||||||
scheduler = build_scheduler(tmp_path)
|
scheduler = build_scheduler(tmp_path)
|
||||||
service = build_service(scheduler)
|
service = build_service(scheduler)
|
||||||
|
|||||||
@@ -84,7 +84,7 @@ class FakeTts:
|
|||||||
return b"PCM", 22050
|
return b"PCM", 22050
|
||||||
|
|
||||||
|
|
||||||
def make_daemon(frames, stt_text="hello", config=None):
|
def make_daemon(frames, stt_text="hello", config=None, input_ready=None):
|
||||||
audio = FakeAudio(frames)
|
audio = FakeAudio(frames)
|
||||||
engines = VoiceEngines(
|
engines = VoiceEngines(
|
||||||
wake=FakeWake(),
|
wake=FakeWake(),
|
||||||
@@ -100,7 +100,7 @@ def make_daemon(frames, stt_text="hello", config=None):
|
|||||||
}
|
}
|
||||||
if config:
|
if config:
|
||||||
cfg.update(config)
|
cfg.update(config)
|
||||||
return VoiceDaemon(cfg, engines=engines), engines
|
return VoiceDaemon(cfg, engines=engines, input_ready=input_ready), engines
|
||||||
|
|
||||||
|
|
||||||
# ---- requirements ----------------------------------------------------------
|
# ---- requirements ----------------------------------------------------------
|
||||||
@@ -150,6 +150,37 @@ def test_no_wake_word_produces_nothing():
|
|||||||
assert engines.stt.calls == []
|
assert engines.stt.calls == []
|
||||||
|
|
||||||
|
|
||||||
|
# ---- input gating (hold the wake word while the scheduler is busy) ---------
|
||||||
|
|
||||||
|
|
||||||
|
def test_wake_blocked_while_input_not_ready():
|
||||||
|
# While the scheduler slot is busy the wake word is ignored: no cue, no
|
||||||
|
# capture, no transcription (traced `voice_wake_blocked`).
|
||||||
|
ready = {"ok": False}
|
||||||
|
daemon, engines = make_daemon(
|
||||||
|
[b"WAKE", b"speech", b"SIL", b"SIL"], input_ready=lambda: ready["ok"]
|
||||||
|
)
|
||||||
|
events = []
|
||||||
|
daemon._event = lambda kind, **kw: events.append(kind)
|
||||||
|
heard = []
|
||||||
|
daemon.run(heard.append)
|
||||||
|
assert heard == []
|
||||||
|
assert engines.stt.calls == []
|
||||||
|
assert engines.audio.writes == []
|
||||||
|
assert "voice_wake_blocked" in events
|
||||||
|
assert "voice_wake" not in events
|
||||||
|
|
||||||
|
|
||||||
|
def test_wake_allowed_when_input_ready():
|
||||||
|
ready = {"ok": True}
|
||||||
|
daemon, engines = make_daemon(
|
||||||
|
[b"WAKE", b"speech", b"SIL", b"SIL"], input_ready=lambda: ready["ok"]
|
||||||
|
)
|
||||||
|
heard = []
|
||||||
|
daemon.run(heard.append)
|
||||||
|
assert heard == ["hello"]
|
||||||
|
|
||||||
|
|
||||||
def test_max_utterance_caps_collection(monkeypatch):
|
def test_max_utterance_caps_collection(monkeypatch):
|
||||||
import semif_agent.voice_transport as vt
|
import semif_agent.voice_transport as vt
|
||||||
|
|
||||||
|
|||||||
Reference in new issue
Block a user