voice: tolerate the wake-tail pause; harden the front end
Endpointing fix. The wake detector usually fires inside the wake phrase, so the first speech captured after it is the phrase's tail (plus the cue beep echoing back through the mic), not the command. A fixed 500 ms trailing-silence endpoint then ended the capture during the natural pause before the command: the utterance held 240-400 ms of speech and STT returned empty. In a recorded session 18 of 30 wakes dropped the command that way (only 10 transcribed). The endpoint now uses a longer silence tolerance (vad.initial_silence_ms, default 1500) until vad.min_command_ms (default 700) of speech is in hand, then reverts to vad.silence_ms, so a pause before the command is tolerated while a real command still ends promptly. Front-end hardening (the ways it was silently dying or losing work): - Utterances run on a worker thread, not the audio thread, and a task error is traced and spoken rather than propagated, so one bad command cannot stop the mic or take the front end down. - Capture-stream watchdog: read with a timeout and close/reopen the input after a sustained stall, so a wedged PortAudio/ALSA callback recovers instead of hanging the gateway (traced voice_stream_stalled/reopened). - faulthandler enabled (CLI + unit) so a fatal signal dumps every thread's stack to the journal. - The scheduler's answer-side entry points (answer, answer_question, resolve_repair, answer_approval) are guarded like submit_request: an EngineUnavailable is fatal-and-reported and any other resume/repair error returns a reply instead of propagating into a front end.
This commit is contained in:
1 parent
e86ed805ee
commit
f6ef66b532
9 files changed
+391
-33
No files matched your search
@@ -1149,8 +1149,22 @@ CLI, unit tests (24) + integration tests (2).
|
|||||||
so physical access is the authorization; a single configured `chat_id`
|
so physical access is the authorization; a single configured `chat_id`
|
||||||
identifies the session and `home_channel` defaults to it so background
|
identifies the session and `home_channel` defaults to it so background
|
||||||
notifications (timers, repair offers) are spoken too. `run(on_inbound,
|
notifications (timers, repair offers) are spoken too. `run(on_inbound,
|
||||||
outbound)` starts an outbound-pump thread (`OutboundMessage` → `speak`) and
|
outbound)` starts an outbound-pump thread (`OutboundMessage` → `speak`) and an
|
||||||
blocks in the mic loop. **Half-duplex**: capture frames are discarded while a
|
**inbound-worker thread**, and blocks in the mic loop. Utterances are handed to
|
||||||
|
the worker, not run on the audio thread: the scheduler is synchronous and can
|
||||||
|
block on the decision engine, so a slow task must not stop the mic being read,
|
||||||
|
and the worker traces + speaks a task error instead of letting it kill the
|
||||||
|
front end. **Capture-stream watchdog**: `_read_frame` reads with
|
||||||
|
`audio.read_timeout_s`; when the stream stalls continuously for
|
||||||
|
`audio.stall_timeout_s` (a wedged PortAudio/ALSA callback that never delivers
|
||||||
|
another frame) it traces `voice_stream_stalled` and closes/reopens the input
|
||||||
|
(`voice_stream_reopened`), so the loop recovers instead of blocking forever.
|
||||||
|
**Endpointing tolerates the wake tail**: the wake detector can fire inside the
|
||||||
|
wake phrase and the cue beep follows, so the first speech captured is the
|
||||||
|
phrase's tail, not the command — until `vad.min_command_ms` of speech is in
|
||||||
|
hand the trailing-silence endpoint uses `vad.initial_silence_ms`, so a natural
|
||||||
|
pause before the command does not end the capture (then `vad.silence_ms`).
|
||||||
|
**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);
|
||||||
after a reply a `follow_up_window_s` accepts the next utterance without the
|
after a reply a `follow_up_window_s` accepts the next utterance without the
|
||||||
wake word, so answering a question is conversational. `max_speak_chars`
|
wake word, so answering a question is conversational. `max_speak_chars`
|
||||||
@@ -1180,7 +1194,10 @@ CLI, unit tests (24) + integration tests (2).
|
|||||||
ownership across an updated request so its completion still routes home. A
|
ownership across an updated request so its completion still routes home. A
|
||||||
`needs_input` pause sets `pending_owner` from the pending run's source; the
|
`needs_input` pause sets `pending_owner` from the pending run's source; the
|
||||||
same chat's next message goes straight to `Scheduler.answer` (no
|
same chat's next message goes straight to `Scheduler.answer` (no
|
||||||
queue/navigation). A *different* chat — **including a chat on another
|
queue/navigation). The answer-side entry points (`answer`, `answer_question`,
|
||||||
|
`resolve_repair`, `answer_approval`) are guarded like `submit_request`: an
|
||||||
|
`EngineUnavailable` is fatal-and-reported and any other error returns a reply,
|
||||||
|
so a resume/repair failure never propagates into a front end. A *different* chat — **including a chat on another
|
||||||
platform** — during that pause is told to wait: the single-slot scheduler must
|
platform** — during that pause is told to wait: the single-slot scheduler must
|
||||||
not silently abandon the first chat's run, and one service fronts all
|
not silently abandon the first chat's run, and one service fronts all
|
||||||
adapters so the guard spans them. A background poll calls
|
adapters so the guard spans them. A background poll calls
|
||||||
|
|||||||
+8
-2
@@ -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 each reply the next utterance is accepted without the wake word for follow_up_window_s. 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.",
|
"_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 each reply the next utterance is accepted without the wake word for follow_up_window_s. 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.",
|
||||||
"enabled": false,
|
"enabled": false,
|
||||||
"chat_id": "voice",
|
"chat_id": "voice",
|
||||||
"display_name": "voice",
|
"display_name": "voice",
|
||||||
@@ -257,18 +257,24 @@
|
|||||||
"volume": 1.0
|
"volume": 1.0
|
||||||
},
|
},
|
||||||
"audio": {
|
"audio": {
|
||||||
|
"_comment": "Capture-stream watchdog: read_timeout_s is how long a frame read waits before it counts as a stall; when the stream stalls continuously for stall_timeout_s (a wedged PortAudio/ALSA callback stops delivering frames) the input is closed and reopened so the voice front end recovers instead of hanging forever. 0 for either restores the old blocking read with no recovery.",
|
||||||
"input_device": "",
|
"input_device": "",
|
||||||
"output_device": "",
|
"output_device": "",
|
||||||
"sample_rate": 16000,
|
"sample_rate": 16000,
|
||||||
"frame_ms": 80,
|
"frame_ms": 80,
|
||||||
"capture_sample_rate": 0,
|
"capture_sample_rate": 0,
|
||||||
"output_sample_rate": 0,
|
"output_sample_rate": 0,
|
||||||
"dc_removal": true
|
"dc_removal": true,
|
||||||
|
"read_timeout_s": 1.0,
|
||||||
|
"stall_timeout_s": 5.0
|
||||||
},
|
},
|
||||||
"vad": {
|
"vad": {
|
||||||
|
"_comment": "Endpointing. silence_ms is the trailing-silence endpoint once a command is underway. The wake detector can fire inside the wake phrase (and the cue beep follows), so the first speech captured is the phrase's tail, not the command: until min_command_ms of speech is in hand the endpoint uses initial_silence_ms instead, so a natural pause before the command does not end the capture. min_speech_ms rejects a blip; max_utterance_s caps a runaway.",
|
||||||
"silence_ms": 500,
|
"silence_ms": 500,
|
||||||
"min_speech_ms": 120,
|
"min_speech_ms": 120,
|
||||||
"max_utterance_s": 30,
|
"max_utterance_s": 30,
|
||||||
|
"min_command_ms": 700,
|
||||||
|
"initial_silence_ms": 1500,
|
||||||
"aggressiveness": 2,
|
"aggressiveness": 2,
|
||||||
"energy_threshold": 200.0
|
"energy_threshold": 200.0
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,6 +8,9 @@ Type=simple
|
|||||||
WorkingDirectory=@REPO@
|
WorkingDirectory=@REPO@
|
||||||
Environment=HF_HOME=@REPO@/.runtime/hf
|
Environment=HF_HOME=@REPO@/.runtime/hf
|
||||||
Environment=PYTHONUNBUFFERED=1
|
Environment=PYTHONUNBUFFERED=1
|
||||||
|
# Dump every thread's stack on a fatal signal so a wedged front end (e.g. the
|
||||||
|
# voice mic loop) leaves a trace in the journal instead of hanging silently.
|
||||||
|
Environment=PYTHONFAULTHANDLER=1
|
||||||
ExecStart=@REPO@/.runtime/venv/bin/python -m semif_agent.cli gateway --platform all
|
ExecStart=@REPO@/.runtime/venv/bin/python -m semif_agent.cli gateway --platform all
|
||||||
Restart=always
|
Restart=always
|
||||||
RestartSec=5
|
RestartSec=5
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ Run on a host with SemIf + a GGUF + a local OpenAI-compatible server:
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import argparse
|
import argparse
|
||||||
|
import faulthandler
|
||||||
import json
|
import json
|
||||||
import os
|
import os
|
||||||
import sys
|
import sys
|
||||||
@@ -822,6 +823,12 @@ def run_gateway(
|
|||||||
run two scheduler processes over one skill store), so each gets its own
|
run two scheduler processes over one skill store), so each gets its own
|
||||||
transport thread but they route through one `GatewayService`.
|
transport thread but they route through one `GatewayService`.
|
||||||
"""
|
"""
|
||||||
|
# Dump every thread's Python stack on a fatal signal (SIGSEGV/SIGABRT/...):
|
||||||
|
# a wedged front end (e.g. a voice loop stuck on the mic) leaves a trace in
|
||||||
|
# the journal instead of dying silently. Also enabled by the unit's
|
||||||
|
# PYTHONFAULTHANDLER=1; harmless when set twice.
|
||||||
|
faulthandler.enable()
|
||||||
|
|
||||||
gateway_cfg = config.get("gateway", {}) or {}
|
gateway_cfg = config.get("gateway", {}) or {}
|
||||||
platforms = _resolve_platforms(platform, gateway_cfg)
|
platforms = _resolve_platforms(platform, gateway_cfg)
|
||||||
|
|
||||||
|
|||||||
@@ -42,6 +42,11 @@ class VoiceAdapter(GatewayAdapter):
|
|||||||
#: `run()` blocks on the mic; this daemon owns capture/wake/STT/TTS.
|
#: `run()` blocks on the mic; this daemon owns capture/wake/STT/TTS.
|
||||||
self.daemon = VoiceDaemon(cfg, trace=trace, name=self.name)
|
self.daemon = VoiceDaemon(cfg, trace=trace, name=self.name)
|
||||||
self._on_inbound = None
|
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()
|
||||||
|
|
||||||
# ---- requirements ----
|
# ---- requirements ----
|
||||||
|
|
||||||
@@ -69,13 +74,42 @@ class VoiceAdapter(GatewayAdapter):
|
|||||||
self.daemon.speak(message.text)
|
self.daemon.speak(message.text)
|
||||||
|
|
||||||
threading.Thread(target=_pump, name="voice-outbound-pump", daemon=True).start()
|
threading.Thread(target=_pump, name="voice-outbound-pump", daemon=True).start()
|
||||||
self.daemon.run(self._on_utterance)
|
threading.Thread(
|
||||||
|
target=self._inbound_worker, name="voice-inbound-worker", daemon=True
|
||||||
|
).start()
|
||||||
|
try:
|
||||||
|
self.daemon.run(self._on_utterance)
|
||||||
|
finally:
|
||||||
|
self._inbound.put(None)
|
||||||
|
|
||||||
def close(self) -> None:
|
def close(self) -> None:
|
||||||
self.daemon.close()
|
self.daemon.close()
|
||||||
|
|
||||||
# ---- inbound ----
|
# ---- inbound ----
|
||||||
|
|
||||||
|
def _inbound_worker(self) -> None:
|
||||||
|
"""Run the scheduler off the audio thread, one utterance at a time.
|
||||||
|
|
||||||
|
The scheduler is synchronous and can block on the decision engine; a
|
||||||
|
slow task must not stop the mic being read, and a task error is traced
|
||||||
|
and spoken rather than propagated — one bad command must not take the
|
||||||
|
voice front end down with it.
|
||||||
|
"""
|
||||||
|
while True:
|
||||||
|
message = self._inbound.get()
|
||||||
|
if message is None:
|
||||||
|
return
|
||||||
|
self._handle(message)
|
||||||
|
|
||||||
|
def _handle(self, message: InboundMessage) -> None:
|
||||||
|
if self._on_inbound is None:
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
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.")
|
||||||
|
|
||||||
def _on_utterance(self, text: str) -> None:
|
def _on_utterance(self, text: str) -> None:
|
||||||
text = (text or "").strip()
|
text = (text or "").strip()
|
||||||
if not text:
|
if not text:
|
||||||
@@ -86,13 +120,13 @@ class VoiceAdapter(GatewayAdapter):
|
|||||||
display_name=self.display_name,
|
display_name=self.display_name,
|
||||||
chars=len(text),
|
chars=len(text),
|
||||||
)
|
)
|
||||||
message = InboundMessage(
|
self._inbound.put(
|
||||||
text=text,
|
InboundMessage(
|
||||||
chat_id=self.chat_id,
|
text=text,
|
||||||
chat_type="dm",
|
chat_id=self.chat_id,
|
||||||
contact_id=self.chat_id,
|
chat_type="dm",
|
||||||
display_name=self.display_name,
|
contact_id=self.chat_id,
|
||||||
raw={},
|
display_name=self.display_name,
|
||||||
|
raw={},
|
||||||
|
)
|
||||||
)
|
)
|
||||||
if self._on_inbound is not None:
|
|
||||||
self._on_inbound(message)
|
|
||||||
@@ -631,7 +631,21 @@ class Scheduler:
|
|||||||
a pre-act contract variable is left unset and marked skipped, and an
|
a pre-act contract variable is left unset and marked skipped, and an
|
||||||
act-driven pause receives the empty string (the body may then fail,
|
act-driven pause receives the empty string (the body may then fail,
|
||||||
which is assessed normally).
|
which is assessed normally).
|
||||||
|
|
||||||
|
Guarded like `submit_request`: a front end calls this synchronously
|
||||||
|
(the voice adapter from its worker thread), so an engine failure must
|
||||||
|
be fatal-and-reported, and any other error must come back as a reply
|
||||||
|
rather than propagate and take the front end down.
|
||||||
"""
|
"""
|
||||||
|
try:
|
||||||
|
return self._answer(text)
|
||||||
|
except EngineUnavailable as exc:
|
||||||
|
return SchedulerReply("fatal", self._mark_fatal(exc))
|
||||||
|
except Exception as exc:
|
||||||
|
self.trace.append("error", "?", phase="answer", message=str(exc))
|
||||||
|
return SchedulerReply("error", f"could not resume the run: {exc}")
|
||||||
|
|
||||||
|
def _answer(self, text: str) -> SchedulerReply:
|
||||||
with self._lock:
|
with self._lock:
|
||||||
if self.pending is None:
|
if self.pending is None:
|
||||||
return SchedulerReply("error", "no run is waiting for input")
|
return SchedulerReply("error", "no run is waiting for input")
|
||||||
@@ -818,8 +832,17 @@ class Scheduler:
|
|||||||
"""Answer a deferred question. An empty answer skips it.
|
"""Answer a deferred question. An empty answer skips it.
|
||||||
|
|
||||||
A repair question carries the detail the user wants the skill repaired
|
A repair question carries the detail the user wants the skill repaired
|
||||||
with; answering it starts the repair directly.
|
with; answering it starts the repair directly. Guarded so an engine or
|
||||||
|
repair failure is reported instead of propagating into the front end.
|
||||||
"""
|
"""
|
||||||
|
try:
|
||||||
|
return self._answer_question(question_id, text)
|
||||||
|
except EngineUnavailable as exc:
|
||||||
|
return "fatal", self._mark_fatal(exc)
|
||||||
|
except Exception as exc:
|
||||||
|
return "error", f"could not record the answer: {exc}"
|
||||||
|
|
||||||
|
def _answer_question(self, question_id: str, text: str) -> tuple[str, str]:
|
||||||
offer_id: str | None = None
|
offer_id: str | None = None
|
||||||
answer = (text or "").strip()
|
answer = (text or "").strip()
|
||||||
with self._lock:
|
with self._lock:
|
||||||
@@ -870,7 +893,16 @@ class Scheduler:
|
|||||||
The draft worker is blocked in `_request_approval`; setting the status
|
The draft worker is blocked in `_request_approval`; setting the status
|
||||||
and notifying releases it (True registers + writes the body, False
|
and notifying releases it (True registers + writes the body, False
|
||||||
aborts). The terminal trace event is written by the worker, not here.
|
aborts). The terminal trace event is written by the worker, not here.
|
||||||
|
Guarded so an unexpected failure is reported instead of propagating.
|
||||||
"""
|
"""
|
||||||
|
try:
|
||||||
|
return self._answer_approval(approval_id, approved)
|
||||||
|
except EngineUnavailable as exc:
|
||||||
|
return "fatal", self._mark_fatal(exc)
|
||||||
|
except Exception as exc:
|
||||||
|
return "error", f"could not record the approval: {exc}"
|
||||||
|
|
||||||
|
def _answer_approval(self, approval_id: str, approved: bool) -> tuple[str, str]:
|
||||||
with self._lock:
|
with self._lock:
|
||||||
approval = next(
|
approval = next(
|
||||||
(a for a in self.approvals if a.id == approval_id), None
|
(a for a in self.approvals if a.id == approval_id), None
|
||||||
@@ -915,8 +947,17 @@ class Scheduler:
|
|||||||
`retry` requeues the original request; `repair_skill` rewrites the body
|
`retry` requeues the original request; `repair_skill` rewrites the body
|
||||||
from the observed failure; `ask_user` posts a question whose answer
|
from the observed failure; `ask_user` posts a question whose answer
|
||||||
starts the repair; `no_repair` closes the offer. Repair writes are
|
starts the repair; `no_repair` closes the offer. Repair writes are
|
||||||
bounded by `codegen.repair.max_attempts` per skill.
|
bounded by `codegen.repair.max_attempts` per skill. Guarded so a retry
|
||||||
|
run or write failure is reported instead of propagating.
|
||||||
"""
|
"""
|
||||||
|
try:
|
||||||
|
return self._resolve_repair(offer_id, action)
|
||||||
|
except EngineUnavailable as exc:
|
||||||
|
return "fatal", self._mark_fatal(exc)
|
||||||
|
except Exception as exc:
|
||||||
|
return "error", f"could not execute the repair: {exc}"
|
||||||
|
|
||||||
|
def _resolve_repair(self, offer_id: str, action: str | None = None) -> tuple[str, str]:
|
||||||
with self._lock:
|
with self._lock:
|
||||||
offer = next((r for r in self.repairs if r.id == offer_id), None)
|
offer = next((r for r in self.repairs if r.id == offer_id), None)
|
||||||
if offer is None:
|
if offer is None:
|
||||||
|
|||||||
+102
-10
@@ -103,15 +103,17 @@ class Synthesizer:
|
|||||||
class AudioIO:
|
class AudioIO:
|
||||||
"""Mic capture and speaker playback.
|
"""Mic capture and speaker playback.
|
||||||
|
|
||||||
`read()` blocks for one frame and returns its bytes, or `None` once the
|
`read(timeout)` returns one frame's bytes; with a `timeout` it returns
|
||||||
input is closed (the loop exits on `None`). `open_output`/`write` may be
|
`b""` when no frame arrived in time, and `None` once the input is closed
|
||||||
called at any sample rate the synthesizer produced.
|
(the loop exits on `None`). The timeout is how the loop detects a stalled
|
||||||
|
capture stream and recovers from it. `open_output`/`write` may be called at
|
||||||
|
any sample rate the synthesizer produced.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def open_input(self, sample_rate: int, frame_ms: int, device: str = "") -> None:
|
def open_input(self, sample_rate: int, frame_ms: int, device: str = "") -> None:
|
||||||
raise NotImplementedError
|
raise NotImplementedError
|
||||||
|
|
||||||
def read(self) -> bytes | None:
|
def read(self, timeout: float | None = None) -> bytes | None:
|
||||||
raise NotImplementedError
|
raise NotImplementedError
|
||||||
|
|
||||||
def open_output(self, sample_rate: int, device: str = "") -> None:
|
def open_output(self, sample_rate: int, device: str = "") -> None:
|
||||||
@@ -442,8 +444,9 @@ class SoundDeviceAudio(AudioIO):
|
|||||||
def read(self, timeout: float | None = None) -> bytes | None:
|
def read(self, timeout: float | None = None) -> bytes | None:
|
||||||
"""Block for the next frame (or up to `timeout` seconds).
|
"""Block for the next frame (or up to `timeout` seconds).
|
||||||
|
|
||||||
Returns `None` once the input is closed, or on a `timeout` with no
|
Returns `None` once the input is closed (the sentinel `close()` puts on
|
||||||
frame — a caller that passes a timeout can detect a stalled stream
|
the queue), or `b""` when a `timeout` elapses with no frame — so a
|
||||||
|
caller that passes a timeout can detect a stalled capture stream
|
||||||
instead of blocking forever.
|
instead of blocking forever.
|
||||||
"""
|
"""
|
||||||
if timeout is None:
|
if timeout is None:
|
||||||
@@ -451,7 +454,7 @@ class SoundDeviceAudio(AudioIO):
|
|||||||
try:
|
try:
|
||||||
return self._frames.get(timeout=timeout)
|
return self._frames.get(timeout=timeout)
|
||||||
except queue.Empty:
|
except queue.Empty:
|
||||||
return None
|
return b""
|
||||||
|
|
||||||
def open_output(self, sample_rate: int, device: str = "") -> None:
|
def open_output(self, sample_rate: int, device: str = "") -> None:
|
||||||
pass # a raw stream is opened per utterance in `write`
|
pass # a raw stream is opened per utterance in `write`
|
||||||
@@ -610,10 +613,28 @@ class VoiceDaemon:
|
|||||||
self.sample_rate = int(audio_cfg.get("sample_rate", SAMPLE_RATE) or SAMPLE_RATE)
|
self.sample_rate = int(audio_cfg.get("sample_rate", SAMPLE_RATE) or SAMPLE_RATE)
|
||||||
self.frame_ms = int(audio_cfg.get("frame_ms", 80) or 80)
|
self.frame_ms = int(audio_cfg.get("frame_ms", 80) or 80)
|
||||||
self.input_device = str(audio_cfg.get("input_device", "") or "")
|
self.input_device = str(audio_cfg.get("input_device", "") or "")
|
||||||
|
#: Capture-stream watchdog. `read_timeout_s` is how long a frame read
|
||||||
|
#: waits before it counts as a stall; when the stream stalls
|
||||||
|
#: continuously for `stall_timeout_s` the input is closed and reopened
|
||||||
|
#: (a wedged PortAudio/ALSA callback otherwise blocks `read()` forever).
|
||||||
|
#: 0 for either restores the old blocking read with no recovery.
|
||||||
|
self.read_timeout_s = float(audio_cfg.get("read_timeout_s", 1.0) or 0.0)
|
||||||
|
self.stall_timeout_s = float(audio_cfg.get("stall_timeout_s", 5.0) or 0.0)
|
||||||
|
self._stall_since = 0.0
|
||||||
vad_cfg = cfg.get("vad", {}) or {}
|
vad_cfg = cfg.get("vad", {}) or {}
|
||||||
self.vad_silence_ms = int(vad_cfg.get("silence_ms", 1000) or 1000)
|
self.vad_silence_ms = int(vad_cfg.get("silence_ms", 1000) or 1000)
|
||||||
self.min_speech_ms = int(vad_cfg.get("min_speech_ms", 120) or 120)
|
self.min_speech_ms = int(vad_cfg.get("min_speech_ms", 120) or 120)
|
||||||
self.max_utterance_s = float(vad_cfg.get("max_utterance_s", 30) or 30)
|
self.max_utterance_s = float(vad_cfg.get("max_utterance_s", 30) or 30)
|
||||||
|
#: A longer silence tolerance while the utterance is still short. The
|
||||||
|
#: wake detector can fire inside the wake phrase (the cue beep follows),
|
||||||
|
#: so the first speech after it is the phrase's tail, not the command;
|
||||||
|
#: a natural pause before the command must not end the capture. Once
|
||||||
|
#: `min_command_ms` of speech is in hand, the normal `vad_silence_ms`
|
||||||
|
#: endpoint applies (so a real command still ends promptly).
|
||||||
|
self.min_command_ms = int(vad_cfg.get("min_command_ms", 700) or 0)
|
||||||
|
self.initial_silence_ms = max(
|
||||||
|
int(vad_cfg.get("initial_silence_ms", 1500) or 0), self.vad_silence_ms
|
||||||
|
)
|
||||||
self.follow_up_window = float(cfg.get("follow_up_window_s", 5.0) or 0.0)
|
self.follow_up_window = float(cfg.get("follow_up_window_s", 5.0) or 0.0)
|
||||||
self.max_speak_chars = int(cfg.get("max_speak_chars", 600) or 0)
|
self.max_speak_chars = int(cfg.get("max_speak_chars", 600) or 0)
|
||||||
cue = cfg.get("cue", {}) or {}
|
cue = cfg.get("cue", {}) or {}
|
||||||
@@ -698,9 +719,11 @@ class VoiceDaemon:
|
|||||||
|
|
||||||
def _loop(self, engines: VoiceEngines) -> None:
|
def _loop(self, engines: VoiceEngines) -> None:
|
||||||
while not self._stop.is_set():
|
while not self._stop.is_set():
|
||||||
pcm = engines.audio.read()
|
pcm = self._read_frame(engines)
|
||||||
if pcm is None:
|
if pcm is None:
|
||||||
return
|
return
|
||||||
|
if not pcm:
|
||||||
|
continue
|
||||||
if self._speaking.is_set():
|
if self._speaking.is_set():
|
||||||
continue
|
continue
|
||||||
armed = time.time() < self._follow_until
|
armed = time.time() < self._follow_until
|
||||||
@@ -763,9 +786,16 @@ class VoiceDaemon:
|
|||||||
break # a reply started; stop capturing so we don't transcribe it
|
break # a reply started; stop capturing so we don't transcribe it
|
||||||
if self.max_utterance_s > 0 and (time.time() - started) >= self.max_utterance_s:
|
if self.max_utterance_s > 0 and (time.time() - started) >= self.max_utterance_s:
|
||||||
break
|
break
|
||||||
pcm = engines.audio.read()
|
pcm = self._read_frame(engines)
|
||||||
if pcm is None:
|
if pcm is None:
|
||||||
break
|
break
|
||||||
|
if not pcm:
|
||||||
|
# No frame within the read timeout: keep waiting, but still
|
||||||
|
# honor the "command never started" deadline below.
|
||||||
|
if waiting and (time.time() - wait_started) * 1000.0 >= wait_for_speech_ms:
|
||||||
|
self._event("voice_no_command", waited_ms=wait_for_speech_ms)
|
||||||
|
return b""
|
||||||
|
continue
|
||||||
is_speech = engines.vad.is_speech(pcm, self.sample_rate)
|
is_speech = engines.vad.is_speech(pcm, self.sample_rate)
|
||||||
if waiting:
|
if waiting:
|
||||||
if not is_speech:
|
if not is_speech:
|
||||||
@@ -781,7 +811,15 @@ class VoiceDaemon:
|
|||||||
last_speech_ts = time.time()
|
last_speech_ts = time.time()
|
||||||
else:
|
else:
|
||||||
silence_ms += self.frame_ms
|
silence_ms += self.frame_ms
|
||||||
if silence_ms >= self.vad_silence_ms:
|
# Tolerate a longer pause until the command's speech is underway
|
||||||
|
# (see `initial_silence_ms`): the wake phrase's tail is captured
|
||||||
|
# first, and a pause before the actual command must not end it.
|
||||||
|
limit = (
|
||||||
|
self.initial_silence_ms
|
||||||
|
if speech_ms < self.min_command_ms
|
||||||
|
else self.vad_silence_ms
|
||||||
|
)
|
||||||
|
if silence_ms >= limit:
|
||||||
break
|
break
|
||||||
if speech_ms < self.min_speech_ms:
|
if speech_ms < self.min_speech_ms:
|
||||||
self._event(
|
self._event(
|
||||||
@@ -795,6 +833,60 @@ class VoiceDaemon:
|
|||||||
self._event("voice_utterance", frames=len(frames), speech_ms=speech_ms)
|
self._event("voice_utterance", frames=len(frames), speech_ms=speech_ms)
|
||||||
return b"".join(frames)
|
return b"".join(frames)
|
||||||
|
|
||||||
|
# ---- capture health ----
|
||||||
|
|
||||||
|
def _read_frame(self, engines: VoiceEngines) -> bytes | None:
|
||||||
|
"""Read one capture frame, recovering from a stalled stream.
|
||||||
|
|
||||||
|
Returns the frame bytes, `b""` when no frame arrived within
|
||||||
|
`read_timeout_s`, or `None` once the input is closed. When the stream
|
||||||
|
stalls continuously for `stall_timeout_s` — the PortAudio callback has
|
||||||
|
stopped delivering, so a blocking `read()` would hang the front end
|
||||||
|
forever — the input is closed and reopened so the loop recovers.
|
||||||
|
"""
|
||||||
|
timeout = self.read_timeout_s if self.read_timeout_s > 0 else None
|
||||||
|
pcm = engines.audio.read(timeout=timeout)
|
||||||
|
if pcm is None:
|
||||||
|
return None
|
||||||
|
if pcm:
|
||||||
|
self._stall_since = 0.0
|
||||||
|
return pcm
|
||||||
|
if timeout is None or self.stall_timeout_s <= 0:
|
||||||
|
return b""
|
||||||
|
now = time.time()
|
||||||
|
if not self._stall_since:
|
||||||
|
self._stall_since = now
|
||||||
|
return b""
|
||||||
|
if now - self._stall_since >= self.stall_timeout_s:
|
||||||
|
self._stall_since = 0.0
|
||||||
|
self._reopen_input(engines)
|
||||||
|
return b""
|
||||||
|
|
||||||
|
def _reopen_input(self, engines: VoiceEngines) -> None:
|
||||||
|
"""Close and reopen the capture stream after a stall (best-effort).
|
||||||
|
|
||||||
|
A stalled PortAudio/ALSA stream never delivers another frame, so the
|
||||||
|
blocking read would hang the whole front end. Reopening gives the
|
||||||
|
device a fresh stream; a hard failure is traced and backed off rather
|
||||||
|
than raised, so the loop keeps retrying instead of dying.
|
||||||
|
"""
|
||||||
|
self._event("voice_stream_stalled", stall_s=round(self.stall_timeout_s, 3))
|
||||||
|
try:
|
||||||
|
engines.audio.close()
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
try:
|
||||||
|
engines.audio.open_input(self.sample_rate, self.frame_ms, self.input_device)
|
||||||
|
except Exception as exc:
|
||||||
|
self._event("voice_stream_reopen_failed", message=str(exc)[:200])
|
||||||
|
time.sleep(min(2.0, self.stall_timeout_s or 1.0))
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
engines.wake.reset()
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
self._event("voice_stream_reopened")
|
||||||
|
|
||||||
# ---- speaking ----
|
# ---- speaking ----
|
||||||
|
|
||||||
def _cue(self, frequency: float, duration_ms: int) -> None:
|
def _cue(self, frequency: float, duration_ms: int) -> None:
|
||||||
|
|||||||
@@ -201,6 +201,37 @@ def test_service_routes_pending_answer_to_same_chat(tmp_path):
|
|||||||
assert any("AB123" in text for text in drain_outbound(service))
|
assert any("AB123" in text for text in drain_outbound(service))
|
||||||
|
|
||||||
|
|
||||||
|
def test_service_survives_answer_failure(tmp_path):
|
||||||
|
# A resume that raises must come back as a reply, never propagate into the
|
||||||
|
# front end (the voice adapter calls handle_inbound synchronously).
|
||||||
|
scheduler = build_scheduler(tmp_path)
|
||||||
|
service = build_service(scheduler)
|
||||||
|
scheduler._run_skill(need_input_skill([]), Request("track it", source="simplex:4"))
|
||||||
|
assert scheduler.pending is not None
|
||||||
|
|
||||||
|
def boom(*_args, **_kwargs):
|
||||||
|
raise RuntimeError("kaboom")
|
||||||
|
|
||||||
|
scheduler._answer = boom
|
||||||
|
service.handle_inbound(InboundMessage(text="AB123", chat_id="4", contact_id="4"))
|
||||||
|
assert any("kaboom" in text for text in drain_outbound(service))
|
||||||
|
|
||||||
|
|
||||||
|
def test_answer_engine_unavailable_is_fatal(tmp_path):
|
||||||
|
from semif_agent.engine import EngineUnavailable
|
||||||
|
|
||||||
|
scheduler = build_scheduler(tmp_path)
|
||||||
|
scheduler._run_skill(need_input_skill([]), Request("track it", source="simplex:4"))
|
||||||
|
|
||||||
|
def boom(*_args, **_kwargs):
|
||||||
|
raise EngineUnavailable("engine down")
|
||||||
|
|
||||||
|
scheduler._answer = boom
|
||||||
|
reply = scheduler.answer("AB123")
|
||||||
|
assert reply.status == "fatal"
|
||||||
|
assert scheduler.fatal is not None
|
||||||
|
|
||||||
|
|
||||||
def test_service_refuses_other_chat_during_pending(tmp_path):
|
def test_service_refuses_other_chat_during_pending(tmp_path):
|
||||||
scheduler = build_scheduler(tmp_path)
|
scheduler = build_scheduler(tmp_path)
|
||||||
service = build_service(scheduler)
|
service = build_service(scheduler)
|
||||||
|
|||||||
+133
-6
@@ -18,17 +18,22 @@ from semif_agent.voice_transport import VoiceDaemon, VoiceEngines
|
|||||||
|
|
||||||
|
|
||||||
class FakeAudio:
|
class FakeAudio:
|
||||||
def __init__(self, frames):
|
def __init__(self, frames, on_empty=None):
|
||||||
self.frames = list(frames)
|
self.frames = list(frames)
|
||||||
|
#: What `read()` returns when the script runs out: `None` = the input is
|
||||||
|
#: closed (the loop exits), `b""` = a read timeout (a stalled stream).
|
||||||
|
self.on_empty = on_empty
|
||||||
self.writes = []
|
self.writes = []
|
||||||
self.closed = False
|
self.closed = False
|
||||||
self.input_opened = False
|
self.input_opens = 0
|
||||||
|
|
||||||
def open_input(self, sample_rate, frame_ms, device=""):
|
def open_input(self, sample_rate, frame_ms, device=""):
|
||||||
self.input_opened = True
|
self.input_opens += 1
|
||||||
|
|
||||||
def read(self):
|
def read(self, timeout=None):
|
||||||
return self.frames.pop(0) if self.frames else None
|
if self.frames:
|
||||||
|
return self.frames.pop(0)
|
||||||
|
return self.on_empty
|
||||||
|
|
||||||
def open_output(self, sample_rate, device=""):
|
def open_output(self, sample_rate, device=""):
|
||||||
pass
|
pass
|
||||||
@@ -132,7 +137,7 @@ def test_wake_word_then_silence_produces_one_utterance():
|
|||||||
heard = []
|
heard = []
|
||||||
daemon.run(heard.append)
|
daemon.run(heard.append)
|
||||||
assert heard == ["hello"]
|
assert heard == ["hello"]
|
||||||
assert engines.audio.input_opened is True
|
assert engines.audio.input_opens == 1
|
||||||
assert engines.audio.closed is True
|
assert engines.audio.closed is True
|
||||||
# The wake detector is reset after firing.
|
# The wake detector is reset after firing.
|
||||||
assert engines.wake.resets >= 1
|
assert engines.wake.resets >= 1
|
||||||
@@ -182,6 +187,37 @@ def test_command_after_pause_is_captured():
|
|||||||
assert engines.stt.calls == [b"command" + b"SIL" * 2]
|
assert engines.stt.calls == [b"command" + b"SIL" * 2]
|
||||||
|
|
||||||
|
|
||||||
|
def test_pause_between_wake_and_command_is_tolerated():
|
||||||
|
# The wake detector can fire inside the wake phrase, so the frames after it
|
||||||
|
# are the phrase's tail, not the command; a natural pause before the command
|
||||||
|
# must not end the capture (the bug that made repeated asks fail).
|
||||||
|
daemon, engines = make_daemon(
|
||||||
|
[b"WAKE", b"tail", b"SIL", b"SIL", b"SIL", b"SIL", b"SIL", b"SIL",
|
||||||
|
b"command", b"SIL", b"SIL"]
|
||||||
|
)
|
||||||
|
heard = []
|
||||||
|
daemon.run(heard.append)
|
||||||
|
assert heard == ["hello"]
|
||||||
|
assert b"command" in engines.stt.calls[0]
|
||||||
|
|
||||||
|
|
||||||
|
def test_short_command_still_endpoints():
|
||||||
|
# Once enough speech is in hand the normal silence endpoint applies, so a
|
||||||
|
# command is not left waiting on the longer initial tolerance.
|
||||||
|
daemon, engines = make_daemon(
|
||||||
|
[b"WAKE", b"a", b"b", b"c", b"d", b"e", b"f", b"g", b"h",
|
||||||
|
b"SIL", b"SIL", b"SIL"],
|
||||||
|
config={"vad": {"silence_ms": 160, "min_speech_ms": 80,
|
||||||
|
"min_command_ms": 400, "initial_silence_ms": 2000}},
|
||||||
|
)
|
||||||
|
heard = []
|
||||||
|
daemon.run(heard.append)
|
||||||
|
assert heard == ["hello"]
|
||||||
|
# It ended on the 160 ms endpoint (two silent frames), not on the longer
|
||||||
|
# initial tolerance.
|
||||||
|
assert engines.stt.calls[0] == b"abcdefgh" + b"SIL" * 2
|
||||||
|
|
||||||
|
|
||||||
def test_wake_without_command_times_out(monkeypatch):
|
def test_wake_without_command_times_out(monkeypatch):
|
||||||
# Wake fires but the user never speaks a command: no utterance is produced
|
# Wake fires but the user never speaks a command: no utterance is produced
|
||||||
# (traced `voice_no_command`) instead of capturing the wake frame as one.
|
# (traced `voice_no_command`) instead of capturing the wake frame as one.
|
||||||
@@ -197,6 +233,67 @@ def test_wake_without_command_times_out(monkeypatch):
|
|||||||
assert "voice_no_command" in events
|
assert "voice_no_command" in events
|
||||||
|
|
||||||
|
|
||||||
|
# ---- capture-stream watchdog ----------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def test_capture_stall_reopens_input(monkeypatch):
|
||||||
|
# A stalled PortAudio/ALSA callback never delivers another frame; the loop
|
||||||
|
# must reopen the input instead of blocking forever.
|
||||||
|
import semif_agent.voice_transport as vt
|
||||||
|
|
||||||
|
daemon, engines = make_daemon([])
|
||||||
|
engines.audio.on_empty = b"" # every read times out (a stalled stream)
|
||||||
|
events = []
|
||||||
|
daemon._event = lambda kind, **kw: events.append(kind)
|
||||||
|
clock = iter([100.0, 100.5, 106.0])
|
||||||
|
monkeypatch.setattr(vt.time, "time", lambda: next(clock))
|
||||||
|
|
||||||
|
assert daemon._read_frame(engines) == b"" # first timeout: stall starts
|
||||||
|
assert daemon._read_frame(engines) == b"" # still stalled, below the limit
|
||||||
|
assert daemon._read_frame(engines) == b"" # past stall_timeout_s -> reopen
|
||||||
|
assert "voice_stream_stalled" in events
|
||||||
|
assert "voice_stream_reopened" in events
|
||||||
|
assert engines.audio.input_opens == 1
|
||||||
|
assert engines.audio.closed is True # closed before reopening
|
||||||
|
|
||||||
|
|
||||||
|
def test_capture_stall_reopen_failure_is_traced(monkeypatch):
|
||||||
|
import semif_agent.voice_transport as vt
|
||||||
|
|
||||||
|
daemon, engines = make_daemon([])
|
||||||
|
engines.audio.on_empty = b""
|
||||||
|
|
||||||
|
def boom(sample_rate, frame_ms, device=""):
|
||||||
|
raise RuntimeError("device busy")
|
||||||
|
|
||||||
|
engines.audio.open_input = boom
|
||||||
|
events = []
|
||||||
|
daemon._event = lambda kind, **kw: events.append(kind)
|
||||||
|
clock = iter([100.0, 106.0])
|
||||||
|
monkeypatch.setattr(vt.time, "time", lambda: next(clock))
|
||||||
|
monkeypatch.setattr(vt.time, "sleep", lambda *_: None)
|
||||||
|
|
||||||
|
daemon._read_frame(engines)
|
||||||
|
daemon._read_frame(engines)
|
||||||
|
assert "voice_stream_reopen_failed" in events
|
||||||
|
|
||||||
|
|
||||||
|
def test_watchdog_disabled_uses_blocking_read(monkeypatch):
|
||||||
|
# read_timeout_s=0 restores the old blocking read (no timeout kwarg passed).
|
||||||
|
daemon, engines = make_daemon(
|
||||||
|
[], config={"audio": {"frame_ms": 80, "sample_rate": 16000, "read_timeout_s": 0}}
|
||||||
|
)
|
||||||
|
seen = {}
|
||||||
|
|
||||||
|
def read(timeout=None):
|
||||||
|
seen["timeout"] = timeout
|
||||||
|
return None
|
||||||
|
|
||||||
|
engines.audio.read = read
|
||||||
|
assert daemon._read_frame(engines) is None
|
||||||
|
assert seen["timeout"] is None
|
||||||
|
|
||||||
|
|
||||||
# ---- half-duplex / speaking ------------------------------------------------
|
# ---- half-duplex / speaking ------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
@@ -259,6 +356,9 @@ def test_adapter_emits_inbound_message():
|
|||||||
seen = []
|
seen = []
|
||||||
adapter._on_inbound = seen.append
|
adapter._on_inbound = seen.append
|
||||||
adapter._on_utterance(" hello there ")
|
adapter._on_utterance(" hello there ")
|
||||||
|
# The utterance is queued for the worker, not run on the audio thread.
|
||||||
|
assert adapter._inbound.qsize() == 1
|
||||||
|
adapter._handle(adapter._inbound.get())
|
||||||
assert len(seen) == 1
|
assert len(seen) == 1
|
||||||
assert seen[0].text == "hello there"
|
assert seen[0].text == "hello there"
|
||||||
assert seen[0].chat_id == "mic"
|
assert seen[0].chat_id == "mic"
|
||||||
@@ -272,6 +372,33 @@ def test_adapter_ignores_empty_utterance():
|
|||||||
adapter._on_inbound = seen.append
|
adapter._on_inbound = seen.append
|
||||||
adapter._on_utterance(" ")
|
adapter._on_utterance(" ")
|
||||||
assert seen == []
|
assert seen == []
|
||||||
|
assert adapter._inbound.empty()
|
||||||
|
|
||||||
|
|
||||||
|
def test_adapter_worker_handles_then_stops():
|
||||||
|
adapter = VoiceAdapter({})
|
||||||
|
seen = []
|
||||||
|
adapter._on_inbound = seen.append
|
||||||
|
adapter._on_utterance("one")
|
||||||
|
adapter._inbound.put(None) # sentinel stops the worker
|
||||||
|
adapter._inbound_worker()
|
||||||
|
assert [m.text for m in seen] == ["one"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_adapter_contains_handler_error():
|
||||||
|
# A task that raises must not kill the front end: the worker traces it and
|
||||||
|
# speaks an apology instead of propagating.
|
||||||
|
adapter = VoiceAdapter({})
|
||||||
|
|
||||||
|
def boom(message):
|
||||||
|
raise RuntimeError("kaboom")
|
||||||
|
|
||||||
|
adapter._on_inbound = boom
|
||||||
|
spoken = []
|
||||||
|
adapter.daemon.speak = lambda text: spoken.append(text)
|
||||||
|
adapter._on_utterance("do the thing")
|
||||||
|
adapter._handle(adapter._inbound.get()) # must not raise
|
||||||
|
assert spoken and "wrong" in spoken[0]
|
||||||
|
|
||||||
|
|
||||||
def test_adapter_is_result_only():
|
def test_adapter_is_result_only():
|
||||||
|
|||||||
Reference in new issue
Block a user