Compare commits

..
5 Commits
10 changed files with 1677 additions and 30 deletions

No files matched your search

+90 -14
View File
@@ -192,12 +192,17 @@ gateway/ messenger COMMAND intake/reply — and nothing else. base.py:
SimplexAdapter — command simplex-chat daemon over its JSON
WebSocket API (lazy `websockets`, allowlist, batching,
structured `/_send`). lxmf.py: LxmfAdapter — LXMF/Reticulum
(lazy `lxmf`), in-process, allowlist + batching. Run with
`python -m semif_agent.cli gateway [--platform simplex,lxmf|all]
[--dashboard]`; config under `gateway.simplex` /
`gateway.lxmf`. The gateway MUST NOT read history, show/create
invite links, or compose messages — see "gateway isolation"
below.
(lazy `lxmf`), in-process, allowlist + batching. voice.py:
VoiceAdapter — the local microphone front end (wake word +
speech-to-text + text-to-speech) over the neutral
`semif_agent/voice_transport.py`; no remote peer and no
allowlist (physical mic access is the authorization), a single
configured `chat_id`, replies spoken back. Run with
`python -m semif_agent.cli gateway [--platform
simplex,lxmf,voice|all] [--dashboard]`; config under
`gateway.simplex` / `gateway.lxmf` / `gateway.voice`. The
gateway MUST NOT read history, show/create invite links, or
compose messages — see "gateway isolation" below.
bridges/ standalone third-party API bridges (SimpleX first, plus the
LLM bridge). base.py:
BridgeInfo + BridgeService (shared localhost JSON HTTP layer,
@@ -228,6 +233,16 @@ lxmf_transport.py
loop, inbound normalization, outbound send queue. Lazy `RNS`/
`LXMF` imports keep the module stdlib-only. Knows nothing about
the scheduler or the gateway.
voice_transport.py
neutral voice transport: a 16 kHz mono capture loop with an
always-on wake word (openWakeWord), VAD endpointing
(webrtcvad, energy fallback), speech-to-text (faster-whisper)
and text-to-speech (Piper) over `sounddevice`; half-duplex
(capture discarded while speaking) with a follow-up window so a
reply can be answered without the wake word. Every heavy dep is
lazy-imported, keeping the module stdlib-only; the engine
interfaces are plain classes so tests inject fakes. Knows
nothing about the scheduler or the gateway.
```
## Run / verify
@@ -436,6 +451,24 @@ CLI, unit tests (24) + integration tests (2).
and one scheduler (`--platform simplex,lxmf|all`). DMs only for the first cut;
groups/attachments/reactions are future work. See "### gateway (messenger
intake)".
- **Voice gateway (wake word + STT + TTS)** (Oct 2026): `gateway/voice.py`
(`VoiceAdapter`, platform `voice`) is the local microphone front end over the
neutral `semif_agent/voice_transport.py`: an always-on openWakeWord wake word,
`webrtcvad` endpointing, faster-whisper speech-to-text, and Piper
text-to-speech over `sounddevice`. It is a normal `GatewayAdapter`, so the
single-session routing, `needs_input` questions, repairs, and approvals all
work through `GatewayService` unchanged — a spoken command is just text from
`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
while a reply is speaking (no barge-in yet); after each reply a
`follow_up_window_s` accepts the next utterance without the wake word. The
whole voice stack is optional and lazy-imported (`requirements/voice.txt`,
pinned separately from the engine set since it is hardware-dependent); the
gateway refuses to start with an install hint. `bootstrap.sh --voice`
installs the deps and downloads its models (the openWakeWord models land in
the venv under `.runtime/venv`, the Piper voice under `.runtime/voice/tts`,
the faster-whisper model in the `.runtime/hf` cache). See
"### gateway (messenger intake)".
- **Bridge services (SimpleX first)** (Sep 2026): messaging *UX* — invite links,
reading incoming messages, composing sends — is decoupled from the command
gateway. `semif_agent.bridges` is a folder of standalone third-party API
@@ -522,7 +555,10 @@ CLI, unit tests (24) + integration tests (2).
`config.example.json`; edit that to set `llm.model`/`codegen.model` and the
endpoints. Flags (`--llm-url`, `--codegen-url`, `--llm-model`,
`--codegen-model`) override the values read from `config.json` **for that run
only** and are never written back. The script must be run from a checkout —
only** and are never written back. `--voice` additionally installs the
optional voice-gateway stack (`requirements/voice.txt` + system
`libportaudio2` + `alsa-utils`) and downloads its models into `.runtime/voice/` via
`scripts/voice-models.py`. The script must be run from a checkout —
it reads pins from that checkout's `pins.json` and never re-clones the agent
repo (only the SemIf engine and the simplex-chat binary). Idempotent and
rerunnable; every stage no-ops on existing state, so it also boots an
@@ -532,7 +568,8 @@ CLI, unit tests (24) + integration tests (2).
model, and WARNs if `llm.model`/`codegen.model` are unset.
- **All installation artifacts live inside the checkout under a gitignored
`.runtime/`** (`venv/`, `engine/`, `models/`, `hf/`, `bin/simplex-chat`,
`simplex/`, `systemd/`), so an end user can find and debug the whole stack in
`simplex/`, `systemd/`, and `voice/` for the optional voice models), so an
end user can find and debug the whole stack in
one tree. Only operationally-forced artifacts live outside: the SSH key
(`~/.ssh`) and the real systemd user dir + linger (the rendered units are
stored in `.runtime/systemd/` and symlinked into `~/.config/systemd/user/`).
@@ -833,7 +870,7 @@ CLI, unit tests (24) + integration tests (2).
### gateway (messenger intake)
- **Run mode.** `python -m semif_agent.cli gateway [--platform simplex,lxmf|all]
- **Run mode.** `python -m semif_agent.cli gateway [--platform simplex,lxmf,voice|all]
[--dashboard]` builds the normal scheduler (engine lazy) and runs the enabled
adapters in the foreground. `--platform` takes a comma-separated list or
`all`; default is `simplex`. **All adapters share one process and one
@@ -841,7 +878,9 @@ CLI, unit tests (24) + integration tests (2).
gets its own transport thread but they route through a single
platform-aware `GatewayService`. `--dashboard` co-serves the browser UI from
a daemon thread. Config lives under `gateway.<platform>` in `config.json`;
`enabled` defaults false. On a bootstrap-provisioned host
`enabled` defaults false. The voice platform is foreground-only by design (a
headless systemd user service does not share the user's audio session). On a
bootstrap-provisioned host
`scripts/bootstrap.sh` renders and enables the `semif-simplex.service` bot
daemon (pinned `simplex-chat` in **bot mode**, profile under
`.runtime/simplex/`, port from `simplex_chat.port`) and the
@@ -905,6 +944,34 @@ CLI, unit tests (24) + integration tests (2).
Reticulum` and `LXMF.LXMRouter` install process signal handlers, which only
work on the main thread** — `run_gateway` calls `daemon.prepare()` on the main
thread before the transport threads start, and `run()` reuses it.
- **Voice adapter** (`gateway/voice.py`): the local microphone front end. It is
a policy layer over the neutral `semif_agent/voice_transport.py` (`VoiceDaemon`)
— openWakeWord wake word → `webrtcvad` endpointing → faster-whisper
speech-to-text, and Piper text-to-speech, all over `sounddevice` at 16 kHz
mono int16 (capture/playback run at the device's native rate and are resampled
to/from 16 kHz; a per-block DC removal handles mics with a constant offset).
There is **no external daemon and no allowlist**: the mic is local,
so physical access is the authorization; a single configured `chat_id`
identifies the session and `home_channel` defaults to it so background
notifications (timers, repair offers) are spoken too. `run(on_inbound,
outbound)` starts an outbound-pump thread (`OutboundMessage` → `speak`) and
blocks in the mic loop. **Half-duplex**: capture frames are discarded while a
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
wake word, so answering a question is conversational. `max_speak_chars`
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.
Every heavy dep
(`sounddevice`/`openwakeword`/`faster_whisper`/`piper`/`onnxruntime`) is
**lazy-imported**; `check_requirements()` returns an install hint and the
gateway refuses to start without the stack. The engine interfaces are plain
classes (`WakeWordDetector`/`VadGate`/`Transcriber`/`Synthesizer`/`AudioIO`),
so tests inject fakes and drive the loop with no hardware. It runs best in the
user's audio session (foreground `gateway --platform voice`), not a headless
systemd user service; `bootstrap.sh --voice` installs the deps and downloads
the models (openWakeWord into the venv's package dir under `.runtime/venv`,
the Piper voice into `.runtime/voice/tts`, the faster-whisper model into the
`.runtime/hf` cache).
- **Scheduler glue** (`gateway/service.py`): inbound text →
`Scheduler.submit_request(text, source=f"{platform}:{chat_id}")`; the returned
request id maps to the `(platform, chat)` (`owners`), and
@@ -951,12 +1018,21 @@ CLI, unit tests (24) + integration tests (2).
daemon close on stop, catalog/`describe_bridges()`).
`tests/test_seed_skills.py` hermetically tests every
`seeds/<category>/<name>/` package, including `simplex.next_message` and
`simplex.connect_link`. The live `websockets` transport against a real daemon
and the live LXMF transport against a real Reticulum network are
live-integration concerns.
`simplex.connect_link`. `tests/test_voice_gateway.py` drives the voice loop
with injected fake engines (wake gating, endpointing, half-duplex,
follow-up window, `speak` truncation/failure, adapter + CLI wiring) — no
hardware, network, or heavy packages. The live `websockets` transport against
a real daemon, the live LXMF transport against a real Reticulum network, and
the live voice pipeline against a real microphone are live-integration
concerns.
- **Deps.** `websockets` and `lxmf`/`rns` are pinned in
`requirements/staging.txt` (staging only); both are lazy-imported and the core
stays stdlib-only.
stays stdlib-only. The voice stack is pinned separately in
`requirements/voice.txt` (hardware-dependent: `sounddevice`, `openwakeword`,
`faster-whisper`, `piper-tts`, `onnxruntime`, `webrtcvad-wheels`, plus the
system `libportaudio2` + `alsa-utils`); it is lazy-imported too, and `bootstrap.sh --voice`
installs it and downloads the models (openWakeWord into the venv package dir,
the Piper voice into `.runtime/voice/tts`, faster-whisper into `.runtime/hf`).
### bridges (third-party API services)
+97 -14
View File
@@ -36,7 +36,8 @@ A successful release of this could be defined by a single question: "Can I use t
- [REPL](#repl)
- [Scripted mode](#scripted-mode)
- [Dashboard](#dashboard)
- [Messenger gateway (SimpleX)](#messenger-gateway-simplex)
- [Messenger gateway (SimpleX + LXMF)](#messenger-gateway-simplex--lxmf)
- [Voice gateway](#voice-gateway)
- [Bridge services](#bridge-services)
- [Dream report](#dream-report)
- [Skills in detail](#skills-in-detail)
@@ -341,7 +342,9 @@ fine-tuning loop — it is not yet the fine-tune itself.
with prompt hashes, tokens and timing.
- **Run lifecycle tracing** — `runs.jsonl` keyed by `run_id`, powering a
Redux-DevTools-style dashboard.
- **Messenger command gateway (SimpleX)** — take commands and reply over DM.
- **Messenger command gateway (SimpleX + LXMF)** — take commands and reply over DM.
- **Voice gateway** — a local microphone front end: wake word + speech-to-text +
text-to-speech, all local (openWakeWord / faster-whisper / Piper).
- **Standalone bridge services** — a token-guarded localhost HTTP layer in front
of third-party systems, so generated bodies never speak native protocols.
- **Seeds** — shipped real starter skills: `calendar.create_event` (the
@@ -379,7 +382,9 @@ semif_agent/
dashboard.py stdlib HTTP + JSON API + static UI
static/ dashboard frontend (html/js/css)
simplex_ws.py neutral SimpleX daemon protocol (shared by gateway + bridge)
gateway/ messenger COMMAND intake/reply (SimpleX first)
voice_transport.py neutral voice transport: mic capture, wake word, VAD,
speech-to-text (faster-whisper), text-to-speech (Piper)
gateway/ messenger COMMAND intake/reply (SimpleX, LXMF, voice)
bridges/ standalone third-party API bridges (SimpleX + the LLM bridge)
seeds/ committed starter skills (calendar, simplex)
scripts/ bootstrap.sh, simplex-address.py, systemd/*.in
@@ -450,6 +455,10 @@ The script is idempotent (every stage no-ops on existing state) and:
Flags (`--llm-url`, `--codegen-url`, `--llm-model`, `--codegen-model`,
`--copy-data SRC`) override the values read from `config.json` for that run only.
`--voice` additionally installs the optional voice-gateway stack
(`requirements/voice.txt` + system PortAudio) and downloads its models (the
openWakeWord models into the venv under `.runtime/venv`, the Piper voice into
`.runtime/voice/tts`, the faster-whisper model into the `.runtime/hf` cache).
Run `scripts/bootstrap.sh -h` for the full list.
It installs **no ollama**; it expects one for `llm` and pulls `llm.model`,
@@ -498,6 +507,7 @@ Key blocks:
| `queue` | `max_size`, `age_rate` |
| `skill_bodies` / `skill_seeds` / `log` / `trace` / `category_registry` | runtime paths (anchored to the checkout) |
| `gateway.simplex` | command gateway: ws_url, allowlist, batching |
| `gateway.voice` | voice gateway: wake/STT/TTS engines + models, audio devices, VAD, follow-up window |
| `bridges.simplex` | forwarding bridge: host/port/token/ws_url |
| `simplex_bridge_url` / `simplex_bridge_token` | what skill bodies call |
| `bridges.llm` | LLM bridge: host/port/token (model comes from `llm`) |
@@ -530,7 +540,7 @@ python -m semif_agent.cli skills # print the skill tree
python -m semif_agent.cli status # current process + queue
python -m semif_agent.cli relabel <id> <outcome>
python -m semif_agent.cli dashboard [--port 8765] [--host 0.0.0.0] [--replay]
python -m semif_agent.cli gateway [--platform simplex] [--dashboard]
python -m semif_agent.cli gateway [--platform simplex,lxmf,voice|all] [--dashboard]
python -m semif_agent.cli bridge [--name simplex]
```
@@ -579,19 +589,90 @@ POST /api/submit /api/answer /api/questions /api/restart /api/repair /api/relabe
Live mode warms the engine; `--replay` reads the logs without loading SemIf
(submit degrades to a JSON error). Binds `127.0.0.1:8765` by default.
### Messenger gateway (SimpleX)
### Messenger gateway (SimpleX + LXMF)
`cli gateway` connects to the local `simplex-chat` daemon over its JSON WebSocket
API and feeds authorized DM text through the normal gate/score/queue/dispatch
pipeline. Results, authoring questions and repair offers go back to the
originating chat. It is **default-deny**: put allowed contactIds or display names
in `gateway.simplex.allowed_users`. Requires the optional `websockets` package
(lazy import; the gateway refuses to start without it).
`cli gateway` runs one or more command transports in a single process that
shares one scheduler/skill store. `--platform` takes a comma-separated list or
`all` and defaults to `simplex`:
```sh
python -m semif_agent.cli gateway [--platform simplex,lxmf,voice|all] [--dashboard]
```
Each platform feeds authorized DM text through the normal gate/score/queue/
dispatch pipeline. Results, authoring questions and repair offers go back to the
originating chat. Config lives under `gateway.<platform>` in `config.json`;
`enabled` defaults to false. Both transports are **default-deny** — put allowed
identities in `gateway.<platform>.allowed_users` (or set `allow_all_users` for
dev) — and **all adapters share one process** (never run two gateway processes
over one skill store). On a provisioned host `semif-gateway.service` runs
`gateway --platform all`, so it survives logout/reboot.
**SimpleX.** Connects to the local `simplex-chat` daemon over its JSON WebSocket
API (`gateway.simplex.ws_url`, which must match `simplex_chat.port`). Requires
the optional `websockets` package (lazy import; the gateway refuses to start
without it). `allowed_users` entries match a numeric contactId or a display
name. The daemon must run in **bot mode** (`simplex-chat -p PORT
--create-bot-display-name NAME`), not `--headless`/`--relay` — in v7 those mean
"chat relay" and yield a relay address, not a user contact address. Add the
bot's contact link to reach it: `scripts/simplex-address.py` shows/creates it
(bootstrap prints it), and the gateway prints it once on connect.
**LXMF (Reticulum).** Runs **in-process — there is no external daemon**;
`pip install lxmf` provides the transport (optional, lazy import; the gateway
refuses to start with an install hint otherwise). The bot's reachable address is
its LXMF delivery destination hash (32 hex chars), printed once on connect; the
identity is persisted under `gateway.lxmf.storage_path` (default
`.runtime/lxmf/router`) so the address is stable across restarts. `allowed_users`
matches the peer's LXMF address (32 hex) or a best-effort display name.
`desired_method` is `direct` (reliable link) or `opportunistic` (single packet),
and an optional `propagation_node` enables store-and-forward. Add the printed
address as a contact in your LXMF client and DM it.
> **Gateway isolation is non-negotiable.** The gateway takes commands and sends
> replies — nothing else. It never reads history, shows or creates invite links,
> or composes messages. That is messaging UX and lives in the bridges.
### Voice gateway
`gateway --platform voice` turns the machine's microphone into a command front
end: an always-on **wake word** (openWakeWord), **speech-to-text**
(faster-whisper), and **text-to-speech** (Piper), all local — no cloud. A spoken
command is fed through the same gate/score/queue/dispatch pipeline as a typed or
messaged one, and every reply is spoken back. It is a normal gateway adapter, so
`needs_input` questions, repair offers, and approvals are spoken and answered by
voice too.
```sh
python -m semif_agent.cli gateway --platform voice
```
- **Requirements.** The voice stack is optional and lazy-imported; install it
with `scripts/bootstrap.sh --voice` (or
`.runtime/venv/bin/pip install -r requirements/voice.txt`) plus the system
PortAudio lib and ALSA mixer tools (`apt install libportaudio2 alsa-utils`).
The gateway refuses to start with an install hint if the stack is missing.
PortAudio has no volume control — use `alsamixer`/`amixer` (then
`sudo alsactl store`) to unmute and set the mic/speaker levels.
- **Models.** `gateway.voice.wake.model` is an openWakeWord model (default
`hey_mycroft`), `stt.model` a faster-whisper size (default `base.en`), and
`tts.voice` a Piper voice (default `en_US-lessac-medium`). Bootstrap downloads
the openWakeWord models into the venv's package dir (under `.runtime/venv`)
and the Piper voice into `.runtime/voice/tts`; the faster-whisper model lands
in the `.runtime/hf` cache.
- **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 wake word fires (`gateway.voice.cue`), so you know you're being heard; set
`cue.submit_frequency > 0` for a second beep once the utterance is
transcribed. After a reply, the next
utterance is accepted **without** the wake word for `follow_up_window_s`, so
answering a question is conversational. `max_speak_chars` truncates long
replies before speaking. There is no allowlist: the mic is local, so physical
access is the authorization.
- **Run mode.** Foreground, in the user's audio session — a headless systemd
user service does not share the user's audio session, so voice is not rendered
as a unit.
### Bridge services
`cli bridge` runs standalone bridges: each is a process that stands up a small,
@@ -707,8 +788,9 @@ python3 -m pytest tests/ -q --ignore=tests/integration
Unit tests use the `ScriptedEngine` double (`tests/conftest.py`) to drive
scheduling mechanics without a GGUF; data-structure tests cover queue ordering,
dream cost and contract serialization. Integration tests exercise the real
engine + LLM end to end.
dream cost and contract serialization. `tests/test_voice_gateway.py` drives the
voice loop with injected fake engines (no hardware, network, or heavy packages).
Integration tests exercise the real engine + LLM end to end.
**Fixtures are not the runtime.** Skill tests use real local endpoints (a
loopback server, never a mock); a real run is the only proof an integration
@@ -725,7 +807,8 @@ contract → test → auto-run → re-dispatch); tiered config + first-fire
collection; runtime repair loop; the closed `response` canned tree; real
integrations with `INTEGRATION` declarations; the SimpleX command gateway and the
standalone SimpleX bridge + seeds (contact-list refresh, daemon-backed message
history / true unread).
history / true unread); the LXMF gateway; and the voice gateway (wake word +
speech-to-text + text-to-speech).
**Next.** Real fine-tuning from grounded decision rows ("dreaming") with
validation + pinned-revision swap; queue persistence; more intake sources
+54
View File
@@ -158,6 +158,60 @@
"home_channel": "",
"reply_prefix": "",
"text_batch_delay": 0.8
},
"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 (bootstrap downloads models into the venv, where they resolve by name; model_dir is an optional local dir for a custom model file); 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. 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.",
"enabled": false,
"chat_id": "voice",
"display_name": "voice",
"home_channel": "voice",
"reply_prefix": "",
"max_speak_chars": 600,
"follow_up_window_s": 5.0,
"cue": {
"_comment": "Audible feedback. A short sine beep plays when the wake word fires so you know you're being heard; set submit_frequency > 0 for a second beep once the utterance is transcribed. volume is 0..1.",
"enabled": true,
"frequency": 880,
"duration_ms": 120,
"volume": 0.9,
"submit_frequency": 0,
"submit_duration_ms": 100
},
"wake": {
"model": "hey_mycroft",
"threshold": 0.5,
"inference_framework": "onnx",
"model_dir": ""
},
"stt": {
"model": "base.en",
"device": "cpu",
"compute_type": "int8",
"language": "en"
},
"tts": {
"voice": "en_US-lessac-medium",
"voice_dir": "",
"speaker_id": 0,
"length_scale": 1.0,
"volume": 1.0
},
"audio": {
"input_device": "",
"output_device": "",
"sample_rate": 16000,
"frame_ms": 80,
"capture_sample_rate": 0,
"output_sample_rate": 0,
"dc_removal": true
},
"vad": {
"silence_ms": 1000,
"min_speech_ms": 120,
"max_utterance_s": 30,
"aggressiveness": 2,
"energy_threshold": 200.0
}
}
},
"dashboard": {"port": 8765, "host": "127.0.0.1"}
+35
View File
@@ -0,0 +1,35 @@
# Voice gateway deps (optional, hardware-dependent).
#
# Only needed on a host that runs the voice front end
# (`python -m semif_agent.cli gateway --platform voice`). Lazy-imported by
# semif_agent/voice_transport.py, so the core stays stdlib-only on every other
# host. Install with scripts/bootstrap.sh --voice, or:
# .runtime/venv/bin/pip install -r requirements/voice.txt
# .runtime/venv/bin/pip install --no-deps openwakeword==0.6.0
#
# System prerequisites (not pip): PortAudio + ALSA mixer tools, e.g.
# `apt-get install -y libportaudio2 alsa-utils`. PortAudio is the I/O backend;
# alsa-utils provides amixer/alsamixer/alsactl to unmute and set mic/speaker
# levels (PortAudio itself has no volume control).
#
# The audio pipeline is 16 kHz mono int16:
# sounddevice mic capture + speaker playback (raw PortAudio streams)
# faster-whisper CTranslate2 Whisper speech-to-text (model from HF cache)
# piper-tts local neural text-to-speech (voice .onnx under .runtime/voice/tts)
# onnxruntime inference backend for openwakeword + piper
# webrtcvad-wheels VAD endpointing (imports as `webrtcvad`; prebuilt wheels)
#
# openWakeWord is installed SEPARATELY with --no-deps: its Linux metadata
# hard-requires tflite-runtime, which has no py3.12+ wheel. The onnxruntime
# backend (used here) does not need it. Its own runtime deps are pinned below
# so this file alone is enough for the rest of the stack.
sounddevice==0.5.6
onnxruntime==1.30.0
faster-whisper==1.2.1
piper-tts==1.8.0
webrtcvad-wheels==2.0.14.post1
# openwakeword runtime deps (installed here because openwakeword is --no-deps).
scipy==1.18.1
scikit-learn==1.9.1
requests==2.34.2
tqdm==4.70.1
+65 -2
View File
@@ -32,7 +32,7 @@
#
# Usage:
# scripts/bootstrap.sh [--llm-url URL] [--codegen-url URL] [--llm-model MODEL]
# [--codegen-model MODEL] [--copy-data SRC] [-h]
# [--codegen-model MODEL] [--copy-data SRC] [--voice] [-h]
#
# Run as the human user; sudo is used internally for system bits.
set -euo pipefail
@@ -42,6 +42,7 @@ CODEGEN_URL=""
LLM_MODEL=""
CODEGEN_MODEL=""
COPY_DATA=""
VOICE=0
usage() {
sed -n '2,35p' "${BASH_SOURCE[0]}" | sed 's/^# \{0,1\}//'
@@ -51,6 +52,7 @@ usage() {
echo " --llm-model MODEL override llm.model from config.json for this run (pulled if the local ollama lacks it)"
echo " --codegen-model MODEL override codegen.model from config.json for this run"
echo " --copy-data SRC rsync SRC (e.g. user@host:/path/to/semif-agent/data) to data/ — opt-in"
echo " --voice install the optional voice-gateway stack + download its models"
echo " -h this help"
exit "${1:-0}"
}
@@ -62,6 +64,7 @@ while [[ $# -gt 0 ]]; do
--llm-model) LLM_MODEL="$2"; shift 2 ;;
--codegen-model) CODEGEN_MODEL="$2"; shift 2 ;;
--copy-data) COPY_DATA="$2"; shift 2 ;;
--voice) VOICE=1; shift ;;
-h|--help) usage 0 ;;
*) echo "unknown option: $1" >&2; usage 1 ;;
esac
@@ -178,7 +181,7 @@ echo "== pins: semif @ $SEMIF_REF | gguf sha256 ${GGUF_SHA256:0:12}… | simplex
echo "== llm $LLM_URL (local, model $LLM_MODEL) | codegen $CODEGEN_URL"
echo "== runtime tree: $RUNTIME"
mkdir -p "$RUNTIME" "$MODELS" "$HF_CACHE" "$TOOLDIR" "$SIMPLEX_DB" "$RUNTIME/simplex-forward" "$RUNTIME/lxmf" "$UNITS" "$USER_UNITS"
mkdir -p "$RUNTIME" "$MODELS" "$HF_CACHE" "$TOOLDIR" "$SIMPLEX_DB" "$RUNTIME/simplex-forward" "$RUNTIME/lxmf" "$RUNTIME/voice" "$UNITS" "$USER_UNITS"
# --- stage 0: system prereqs + linger ----------------------------------------
PKGS=(ca-certificates curl git rsync build-essential python3-dev python3-venv pkg-config cmake util-linux)
@@ -241,6 +244,31 @@ echo "== installing engine deps into $VENV"
CMAKE_BUILD_PARALLEL_LEVEL=6 MAKEFLAGS=-j6 "$PIP" install -r "$REPO_ROOT/requirements/staging.txt"
"$PIP" install -e "$REPO_ROOT" --no-deps
# --- stage 3b: optional voice-gateway stack (--voice) --------------------------
# Hardware-dependent: only the host with a microphone/speaker needs it. The
# stack is lazy-imported, so a host without it still runs every other front end.
if [[ "$VOICE" = 1 ]]; then
# libportaudio2 is the I/O backend sounddevice needs; alsa-utils provides
# amixer/alsamixer/alsactl so the operator can unmute and set the mic/speaker
# levels (PortAudio itself has no volume control).
VOICE_SYS_PKGS=(libportaudio2 alsa-utils)
voice_missing=()
for p in "${VOICE_SYS_PKGS[@]}"; do
dpkg -s "$p" >/dev/null 2>&1 || voice_missing+=("$p")
done
if [[ ${#voice_missing[@]} -gt 0 ]]; then
echo "== installing voice system prereqs: ${voice_missing[*]}"
sudo apt-get update
sudo apt-get install -y "${voice_missing[@]}"
fi
echo "== installing voice deps into $VENV"
"$PIP" install -r "$REPO_ROOT/requirements/voice.txt"
# openWakeWord's Linux metadata hard-requires tflite-runtime (no py3.12+
# wheel); the onnxruntime backend does not need it, so install it --no-deps
# (its own runtime deps are pinned in voice.txt).
"$PIP" install --no-deps openwakeword==0.6.0
fi
# --- stage 4: GGUF --------------------------------------------------------------
GGUF_NAME="$(basename "$GGUF_URL")"
GGUF="$MODELS/$GGUF_NAME"
@@ -264,6 +292,18 @@ from transformers import AutoTokenizer
AutoTokenizer.from_pretrained(sys.argv[1], revision=sys.argv[2])
PY
# --- stage 5b: optional voice models (--voice) ----------------------------------
# Downloads the openWakeWord models (into the venv) + the Piper voice (into
# .runtime/voice/tts) and warms the faster-whisper model into the HF cache.
# Reads gateway.voice from config.json
# so the models match the configured names. Best-effort: a download failure
# warns (the gateway reports the missing model at startup) rather than aborting.
if [[ "$VOICE" = 1 ]]; then
echo "== downloading voice models (openWakeWord + Piper + faster-whisper)"
HF_HOME="$HF_CACHE" "$PYTHON" "$REPO_ROOT/scripts/voice-models.py" --config "$CONFIG" \
|| echo "WARN: voice model download failed; re-run scripts/voice-models.py" >&2
fi
# --- stage 6: simplex-chat daemon binary -------------------------------------------
SIMPLEX_BIN="$TOOLDIR/simplex-chat"
simplex_ok() {
@@ -498,3 +538,26 @@ LLM bridge (generation for skills):
model (configured once) and serves a generic POST /chat; skills call it via
the top-level llm_bridge_url (default http://127.0.0.1:5229).
EOF
if [[ "$VOICE" = 1 ]]; then
cat <<EOF
Voice command gateway (wake word + speech-to-text + text-to-speech):
- The stack is installed and its models downloaded (openWakeWord into the
venv, the Piper voice into .runtime/voice/tts, faster-whisper into .runtime/hf).
Enable it in config.json with gateway.voice.enabled = true, then run it in
the foreground (it needs your audio session; it is NOT a systemd unit):
HF_HOME="$HF_CACHE" "$PYTHON" -m semif_agent.cli gateway --platform voice
- Say the wake word (gateway.voice.wake.model, default 'hey_mycroft') and
speak; the reply is spoken back. After each reply the next utterance needs
no wake word for gateway.voice.follow_up_window_s.
- If the mic or speaker is silent/quiet, set the ALSA mixer (PortAudio has no
volume control) and persist it:
alsamixer # or: amixer -c <card> sset 'Speaker' unmute
sudo alsactl store
List devices with: $PYTHON -c "import sounddevice as sd; print(sd.query_devices())"
and put the input/output device indices in gateway.voice.audio.
- Re-download / switch models any time with:
HF_HOME="$HF_CACHE" "$PYTHON" scripts/voice-models.py --config config.json
EOF
fi
+113
View File
@@ -0,0 +1,113 @@
#!/usr/bin/env python3
"""Download the voice-gateway models into the checkout's `.runtime/voice` tree.
Run after installing `requirements/voice.txt` (bootstrap does this with
`--voice`). Idempotent: a model already on disk is skipped. Reads
`gateway.voice` from config.json so the downloaded models match the configured
names, or take explicit flags.
- **Wake word** (openWakeWord): downloaded by `openwakeword.utils.download_models`
into the venv's package resources dir (inside `.runtime/venv/`, so still
contained in the checkout). The detector resolves the model by name there.
- **TTS** (Piper): the voice `.onnx` + `.onnx.json` are fetched from the
`rhasspy/piper-voices` HF repo into `.runtime/voice/tts/`.
- **STT** (faster-whisper): instantiating the model warms it into the HF cache
(`.runtime/hf`); the runner reuses that cache at runtime.
"""
from __future__ import annotations
import argparse
import json
import shutil
from pathlib import Path
REPO_ROOT = Path(__file__).resolve().parent.parent
RUNTIME = REPO_ROOT / ".runtime" / "voice"
PIPER_REPO = "rhasspy/piper-voices"
def piper_hf_path(voice: str) -> str:
"""Map a Piper voice id to its file path in the `rhasspy/piper-voices` repo.
`en_US-lessac-medium` -> `en/en_US/lessac/medium/en_US-lessac-medium.onnx`
(the voice name may itself contain dashes).
"""
parts = voice.split("-")
if len(parts) < 3:
raise ValueError(f"unrecognized piper voice id {voice!r}")
locale, quality = parts[0], parts[-1]
name = "-".join(parts[1:-1])
lang = locale.split("_")[0]
return f"{lang}/{locale}/{name}/{quality}/{voice}.onnx"
def download_wake(name: str) -> None:
import openwakeword.utils as utils
print(f"== wake word model: {name}")
# Default target: the venv's package resources dir (inside .runtime/venv).
# openWakeWord resolves the model (and its shared mel/embedding models) by
# name from there.
utils.download_models(model_names=[name])
def download_voice(voice: str, target: Path) -> None:
from huggingface_hub import hf_hub_download
target.mkdir(parents=True, exist_ok=True)
rel = piper_hf_path(voice)
for suffix in ("", ".json"):
dest = target / f"{voice}.onnx{suffix}"
if dest.is_file():
print(f"== tts voice: {dest.name} (present)")
continue
print(f"== tts voice: {voice}{suffix or '.onnx'} -> {dest}")
cached = hf_hub_download(repo_id=PIPER_REPO, filename=rel + suffix)
shutil.copyfile(cached, dest)
def download_stt(model: str) -> None:
from faster_whisper import WhisperModel
print(f"== stt model: {model} (warming HF cache)")
WhisperModel(model, device="cpu", compute_type="int8")
def _config_voice(config_path: Path) -> dict:
try:
config = json.loads(config_path.read_text())
except Exception:
return {}
return (config.get("gateway", {}) or {}).get("voice", {}) or {}
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--config", default=str(REPO_ROOT / "config.json"))
parser.add_argument("--wake", default=None, help="openWakeWord model name")
parser.add_argument("--stt", default=None, help="faster-whisper model size/path")
parser.add_argument("--tts", default=None, help="Piper voice id")
parser.add_argument("--tts-dir", default=str(RUNTIME / "tts"))
parser.add_argument("--skip-wake", action="store_true")
parser.add_argument("--skip-stt", action="store_true")
parser.add_argument("--skip-tts", action="store_true")
args = parser.parse_args(argv)
voice_cfg = _config_voice(Path(args.config))
wake = args.wake or (voice_cfg.get("wake", {}) or {}).get("model") or "hey_mycroft"
stt = args.stt or (voice_cfg.get("stt", {}) or {}).get("model") or "base.en"
tts = args.tts or (voice_cfg.get("tts", {}) or {}).get("voice") or "en_US-lessac-medium"
if not args.skip_wake:
download_wake(wake)
if not args.skip_tts:
download_voice(tts, Path(args.tts_dir))
if not args.skip_stt:
download_stt(stt)
print("== voice models ready")
return 0
if __name__ == "__main__":
raise SystemExit(main())
+16
View File
@@ -638,6 +638,22 @@ def _build_gateway_adapter(platform: str, cfg: dict, trace):
cfg.setdefault("config_dir", str(REPO_ROOT / ".runtime" / "lxmf" / "reticulum"))
cfg.setdefault("storage_path", str(REPO_ROOT / ".runtime" / "lxmf" / "router"))
return LxmfAdapter(cfg, trace=trace)
if platform == "voice":
from .gateway.voice import VoiceAdapter
cfg = dict(cfg or {})
# Contain downloaded wake-word / TTS models under the checkout's
# .runtime/ (the faster-whisper model lands in the HF cache instead).
voice_dir = REPO_ROOT / ".runtime" / "voice"
wake_cfg = dict(cfg.get("wake") or {})
if not wake_cfg.get("model_dir"):
wake_cfg["model_dir"] = str(voice_dir / "wake")
cfg["wake"] = wake_cfg
tts_cfg = dict(cfg.get("tts") or {})
if not tts_cfg.get("voice_dir"):
tts_cfg["voice_dir"] = str(voice_dir / "tts")
cfg["tts"] = tts_cfg
return VoiceAdapter(cfg, trace=trace)
return None
+93
View File
@@ -0,0 +1,93 @@
"""Voice command-gateway adapter.
The gateway is the agent's **command** surface. This adapter is the policy layer
over the neutral `VoiceDaemon` transport in `semif_agent.voice_transport`: it
listens on the local microphone, applies the wake word + VAD endpointing +
speech-to-text, and hands the transcribed command to the scheduler; the reply is
spoken back through text-to-speech. All the routing — gate/score/queue/dispatch,
`needs_input` questions, repairs, approvals — lives in `GatewayService`, exactly
as for the SimpleX and LXMF adapters.
Unlike a messenger transport there is no remote peer and no allowlist: the
microphone is local, so physical access is the authorization. A single
configured `chat_id` identifies the session, and `home_channel` defaults to it
so background notifications (timers, repair offers) are spoken too.
Gateway isolation still holds: this adapter takes commands and speaks replies,
nothing else. It never records, stores, or exposes audio; transcription is
transient and the only artifact is the same text a typed command would carry.
"""
from __future__ import annotations
import queue
import threading
from semif_agent.voice_transport import VoiceDaemon
from .base import GatewayAdapter, InboundMessage, OutboundMessage
class VoiceAdapter(GatewayAdapter):
name = "voice"
def __init__(self, cfg: dict | None = None, trace=None):
cfg = cfg or {}
self.chat_id = str(cfg.get("chat_id", "voice") or "voice")
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)
self._on_inbound = None
# ---- requirements ----
def check_requirements(self) -> tuple[bool, str | None]:
return self.daemon.check_requirements()
# ---- transport ----
def run(
self,
on_inbound,
outbound: "queue.Queue[OutboundMessage | None]",
) -> None:
self._on_inbound = on_inbound
def _pump() -> None:
# Drain the service's replies onto the daemon's speaker. Speaking
# blocks (it plays audio), so this runs off the listening thread.
while True:
message = outbound.get()
if message is None:
self.daemon.stop()
return
self.daemon.speak(message.text)
threading.Thread(target=_pump, name="voice-outbound-pump", daemon=True).start()
self.daemon.run(self._on_utterance)
def close(self) -> None:
self.daemon.close()
# ---- inbound ----
def _on_utterance(self, text: str) -> None:
text = (text or "").strip()
if not text:
return
self.daemon._event(
"gateway_message",
contact_id=self.chat_id,
display_name=self.display_name,
chars=len(text),
)
message = InboundMessage(
text=text,
chat_id=self.chat_id,
chat_type="dm",
contact_id=self.chat_id,
display_name=self.display_name,
raw={},
)
if self._on_inbound is not None:
self._on_inbound(message)
+805
View File
@@ -0,0 +1,805 @@
"""Low-level voice transport (neutral): mic capture, wake word, VAD, STT, TTS.
This module owns the audio mechanics only: a continuous 16 kHz mono capture
stream, an always-on wake-word detector, silence endpointing (VAD), speech to
text, and text to speech. It knows nothing about the SemIf scheduler or the
command gateway — a front end builds on top of it (`semif_agent.gateway.voice`).
Every heavy dependency (`sounddevice`, `openwakeword`, `faster_whisper`,
`piper`, `onnxruntime`, `webrtcvad`) is imported lazily, so importing this
module stays stdlib-only on a machine without the optional voice stack. The
gateway refuses to start with an install hint instead (`check_requirements`).
Audio contract: 16 kHz, mono, signed 16-bit little-endian PCM, read in fixed
`frame_ms` blocks. That is what openWakeWord and faster-whisper both want, so no
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).
- **Follow-up window.** After a reply, the next utterance is accepted without
the wake word for `follow_up_window_s`, so answering a question is
conversational.
- The engine interfaces are plain classes so tests can inject fakes and drive
the loop without hardware or the optional packages.
"""
from __future__ import annotations
import importlib.util
import io
import queue
import threading
import time
import wave
from dataclasses import dataclass
from typing import Callable
#: Callback invoked for each transcribed utterance (the spoken text).
UtteranceHandler = Callable[[str], None]
#: The one audio format the whole pipeline uses.
SAMPLE_RATE = 16000
BYTES_PER_SAMPLE = 2
#: Required optional packages -> install hint shown by `check_requirements`.
_REQUIRED_MODULES: tuple[tuple[str, str], ...] = (
("sounddevice", "sounddevice (needs the system PortAudio lib: apt install libportaudio2)"),
("openwakeword", "openwakeword"),
("faster_whisper", "faster-whisper"),
("piper", "piper-tts"),
("onnxruntime", "onnxruntime"),
)
# --------------------------------------------------------------------------- #
# Engine interfaces (fakes are injected in tests)
# --------------------------------------------------------------------------- #
class WakeWordDetector:
"""Scores one PCM frame; a score >= threshold fires the wake word."""
def score(self, pcm16: bytes) -> float:
raise NotImplementedError
def reset(self) -> None:
"""Clear detector state (called after a fire and after speaking)."""
def close(self) -> None:
pass
class VadGate:
"""Decides whether one PCM frame contains speech (for endpointing)."""
def is_speech(self, pcm16: bytes, sample_rate: int) -> bool:
raise NotImplementedError
def close(self) -> None:
pass
class Transcriber:
"""Transcribes a complete utterance (16 kHz int16 PCM) to text."""
def transcribe(self, pcm16: bytes) -> str:
raise NotImplementedError
def close(self) -> None:
pass
class Synthesizer:
"""Synthesizes text to `(pcm16, sample_rate)`."""
def synthesize(self, text: str) -> tuple[bytes, int]:
raise NotImplementedError
def close(self) -> None:
pass
class AudioIO:
"""Mic capture and speaker playback.
`read()` blocks for one frame and returns its bytes, or `None` once the
input is closed (the loop exits on `None`). `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:
raise NotImplementedError
def read(self) -> bytes | None:
raise NotImplementedError
def open_output(self, sample_rate: int, device: str = "") -> None:
pass
def write(self, pcm16: bytes, sample_rate: int) -> None:
raise NotImplementedError
def flush(self) -> None:
"""Drop any buffered capture frames (called after speaking to clear echo)."""
def close(self) -> None:
pass
@dataclass
class VoiceEngines:
"""The bundle of engines the loop drives."""
wake: WakeWordDetector
vad: VadGate
stt: Transcriber
tts: Synthesizer
audio: AudioIO
# --------------------------------------------------------------------------- #
# Real engines (lazy imports)
# --------------------------------------------------------------------------- #
class OpenWakeWordDetector(WakeWordDetector):
"""openWakeWord detector. `model` is a bundled name or a `.onnx`/`.tflite` path."""
def __init__(self, model: str, threshold: float = 0.5, inference_framework: str = "onnx"):
from openwakeword.model import Model
self.threshold = float(threshold)
self._model = Model(
wakeword_models=[model] if model else None,
inference_framework=str(inference_framework or "onnx"),
)
def score(self, pcm16: bytes) -> float:
import numpy as np
audio = np.frombuffer(pcm16, dtype=np.int16)
predictions = self._model.predict(audio)
if not predictions:
return 0.0
return float(max(predictions.values()))
def reset(self) -> None:
try:
self._model.reset()
except Exception:
pass
class WebRtcVadGate(VadGate):
"""`webrtcvad` endpointing. Splits a frame into 20 ms sub-frames and votes."""
def __init__(self, aggressiveness: int = 2):
import webrtcvad
self._vad = webrtcvad.Vad(int(aggressiveness))
def is_speech(self, pcm16: bytes, sample_rate: int) -> bool:
chunk = int(sample_rate * 0.02) * BYTES_PER_SAMPLE # 20 ms
if chunk <= 0:
return False
votes = 0
total = 0
for offset in range(0, len(pcm16) - chunk + 1, chunk):
total += 1
try:
if self._vad.is_speech(pcm16[offset : offset + chunk], sample_rate):
votes += 1
except Exception:
return False
return total > 0 and votes * 2 >= total
class EnergyVadGate(VadGate):
"""Stdlib fallback endpointing: int16 RMS above a threshold.
Less robust than `webrtcvad`, but keeps the loop usable when the optional
package is absent.
"""
def __init__(self, threshold: float = 200.0):
self.threshold = float(threshold)
def is_speech(self, pcm16: bytes, sample_rate: int) -> bool:
count = len(pcm16) // BYTES_PER_SAMPLE
if count == 0:
return False
total = 0
for index in range(0, count * BYTES_PER_SAMPLE, BYTES_PER_SAMPLE):
sample = int.from_bytes(pcm16[index : index + BYTES_PER_SAMPLE], "little", signed=True)
total += sample * sample
rms = (total / count) ** 0.5
return rms >= self.threshold
class WhisperTranscriber(Transcriber):
"""faster-whisper (CTranslate2) transcription. `model` is a size or a path."""
def __init__(
self,
model: str = "base.en",
device: str = "cpu",
compute_type: str = "int8",
language: str = "en",
):
from faster_whisper import WhisperModel
self.language = str(language or "en") or None
self._model = WhisperModel(str(model or "base.en"), device=str(device or "cpu"),
compute_type=str(compute_type or "int8"))
def transcribe(self, pcm16: bytes) -> str:
import numpy as np
audio = np.frombuffer(pcm16, dtype=np.int16).astype("float32") / 32768.0
segments, _info = self._model.transcribe(
audio,
language=self.language,
beam_size=1,
vad_filter=True,
)
return " ".join(segment.text.strip() for segment in segments).strip()
class PiperSynthesizer(Synthesizer):
"""Piper TTS. `voice` is a voice name (resolved to a `.onnx`) or a path."""
def __init__(self, voice: str, speaker_id: int = 0, length_scale: float = 1.0,
volume: float = 1.0):
from piper import PiperVoice
self._voice = PiperVoice.load(str(voice))
self._syn_config = _piper_syn_config(speaker_id, length_scale, volume)
def synthesize(self, text: str) -> tuple[bytes, int]:
buffer = io.BytesIO()
with wave.open(buffer, "wb") as wav_file:
wav_fn = getattr(self._voice, "synthesize_wav", None)
if callable(wav_fn):
# piper-tts >= 1.3: synthesize_wav(text, wav_file, syn_config=...)
wav_fn(text, wav_file, syn_config=self._syn_config)
else:
# older piper-tts: synthesize(text, wav_file)
try:
self._voice.synthesize(text, wav_file, syn_config=self._syn_config)
except TypeError:
self._voice.synthesize(text, wav_file)
buffer.seek(0)
with wave.open(buffer, "rb") as wav_file:
return wav_file.readframes(wav_file.getnframes()), wav_file.getframerate()
def _piper_syn_config(speaker_id: int, length_scale: float, volume: float = 1.0):
"""A piper `SynthesisConfig` when the installed version provides one."""
try:
from piper import SynthesisConfig
except Exception:
return None
kwargs: dict = {}
if speaker_id:
kwargs["speaker_id"] = int(speaker_id)
if length_scale and float(length_scale) != 1.0:
kwargs["length_scale"] = float(length_scale)
if volume and float(volume) != 1.0:
kwargs["volume"] = float(volume)
if not kwargs:
return None
try:
return SynthesisConfig(**kwargs)
except Exception:
return None
def _remove_dc(pcm16: bytes) -> bytes:
"""Subtract the per-block mean (kills a DC offset some mics carry)."""
import numpy as np
samples = np.frombuffer(pcm16, dtype=np.int16).astype(np.float32)
if samples.size == 0:
return pcm16
samples = samples - samples.mean()
return np.clip(samples, -32768, 32767).astype(np.int16).tobytes()
def _tone_pcm(frequency: float, duration_ms: int, sample_rate: int, volume: float) -> bytes:
"""Generate a short sine beep as 16-bit mono PCM (stdlib only).
A 10 ms fade in/out avoids clicks. Used for the wake-word cue; it needs no
audio asset and no numpy, so it works on the stdlib-only path too.
"""
import math
import struct
count = int(sample_rate * max(0, duration_ms) / 1000)
if count <= 0 or frequency <= 0:
return b""
amplitude = int(max(0.0, min(1.0, volume)) * 32767)
fade = max(1, int(sample_rate * 0.01)) # 10 ms
frames = bytearray()
for index in range(count):
envelope = min(1.0, index / fade, (count - index) / fade)
value = int(amplitude * envelope * math.sin(2 * math.pi * frequency * index / sample_rate))
frames += struct.pack("<h", value)
return bytes(frames)
def _device_arg(value):
"""Coerce a config device value to a PortAudio argument.
PortAudio takes an int index or a name substring; a numeric string like
"5" is treated as a name and fails to match, so digits become an int.
Empty means the system default.
"""
if value is None:
return None
text = str(value).strip()
if not text:
return None
if text.lstrip("-").isdigit():
return int(text)
return text
def _resample_pcm16(pcm16: bytes, source_rate: int, target_rate: int) -> bytes:
"""Linear-interpolate int16 PCM from `source_rate` to `target_rate`.
numpy is a voice-stack dependency and this is only reached by the real
`SoundDeviceAudio` engine, so the core stays stdlib-only. Audio hardware
rarely accepts 16 kHz directly, so capture blocks are resampled down and
synthesized PCM is resampled up to the device's native rate.
"""
if source_rate == target_rate or not pcm16:
return pcm16
import numpy as np
source = np.frombuffer(pcm16, dtype=np.int16).astype(np.float32)
count = int(round(len(source) * target_rate / source_rate))
if count <= 0:
return b""
positions = np.linspace(0.0, len(source) - 1, count)
resampled = np.interp(positions, np.arange(len(source)), source)
return np.clip(resampled, -32768, 32767).astype(np.int16).tobytes()
class SoundDeviceAudio(AudioIO):
"""PortAudio capture/playback via `sounddevice` (raw int16 streams).
Real audio devices rarely accept the 16 kHz processing rate directly, so
capture runs at the device's native rate and each block is resampled down to
the processing rate; playback resamples the synthesized PCM up to the output
device's native rate. The native rate defaults to the device's reported
`default_samplerate` and can be pinned with `capture_sample_rate` /
`output_sample_rate`.
"""
def __init__(self, input_device: str = "", output_device: str = "",
capture_sample_rate: int = 0, output_sample_rate: int = 0,
dc_removal: bool = True):
self.input_device = _device_arg(input_device)
self.output_device = _device_arg(output_device)
self.capture_sample_rate = int(capture_sample_rate or 0)
self.output_sample_rate = int(output_sample_rate or 0)
self.dc_removal = bool(dc_removal)
self._stream = None
self._process_rate = SAMPLE_RATE
self._capture_rate = 0
self._frames: "queue.Queue[bytes | None]" = queue.Queue(maxsize=128)
self._closed = threading.Event()
def _device_rate(self, device, kind: str) -> int:
"""The device's native sample rate (or a sane fallback)."""
import sounddevice as sd
try:
info = sd.query_devices(device, kind)
rate = int(info.get("default_samplerate") or 0)
except Exception:
rate = 0
return rate or 48000
def open_input(self, sample_rate: int, frame_ms: int, device: str = "") -> None:
import sounddevice as sd
self._closed.clear()
while not self._frames.empty(): # drop any stale sentinel/frames
self._frames.get_nowait()
self._process_rate = int(sample_rate)
dev = _device_arg(device) or self.input_device
self._capture_rate = self.capture_sample_rate or self._device_rate(dev, "input")
block = max(1, int(self._capture_rate * frame_ms / 1000))
self._stream = sd.RawInputStream(
samplerate=self._capture_rate,
channels=1,
dtype="int16",
blocksize=block,
device=dev,
callback=self._callback,
)
self._stream.start()
def _callback(self, indata, frames, time_info, status) -> None: # noqa: ANN001
if self._closed.is_set():
return
data = bytes(indata)
if self.dc_removal:
data = _remove_dc(data)
if self._capture_rate and self._capture_rate != self._process_rate:
data = _resample_pcm16(data, self._capture_rate, self._process_rate)
try:
self._frames.put_nowait(data)
except queue.Full:
pass # a slow consumer (STT) drops stale frames; the mic is real-time
def read(self) -> bytes | None:
return self._frames.get()
def open_output(self, sample_rate: int, device: str = "") -> None:
pass # a raw stream is opened per utterance in `write`
def write(self, pcm16: bytes, sample_rate: int) -> None:
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)
with sd.RawOutputStream(
samplerate=rate,
channels=1,
dtype="int16",
device=self.output_device,
) as stream:
stream.write(pcm16)
def flush(self) -> None:
try:
while not self._frames.empty():
self._frames.get_nowait()
except queue.Empty:
pass
def close(self) -> None:
self._closed.set()
stream, self._stream = self._stream, None
if stream is not None:
try:
stream.stop()
stream.close()
except Exception:
pass
try: # clear stale frames so the sentinel is what the reader gets next
while not self._frames.empty():
self._frames.get_nowait()
except queue.Empty:
pass
try:
self._frames.put_nowait(None) # unblock a pending read()
except queue.Full:
pass
# --------------------------------------------------------------------------- #
# Engine construction
# --------------------------------------------------------------------------- #
def resolve_model_path(name: str, directory: str, suffixes: tuple[str, ...]) -> str:
"""Return `name` as-is if it is a file, else `directory/<name><suffix>`.
Lets config carry a short model name (downloaded by bootstrap into
`.runtime/voice/...`) while still accepting an explicit path. A versioned
file (`<name>_v0.1.onnx`) also matches by prefix.
"""
if not name:
return name
import glob
import os
if os.path.isfile(name):
return name
for suffix in suffixes:
candidate = os.path.join(directory, f"{name}{suffix}")
if os.path.isfile(candidate):
return candidate
matches = sorted(glob.glob(os.path.join(directory, f"{name}*{suffix}")))
if matches:
return matches[0]
return name
def _build_vad(cfg: dict) -> VadGate:
vad_cfg = cfg.get("vad", {}) or {}
if importlib.util.find_spec("webrtcvad") is not None:
return WebRtcVadGate(aggressiveness=int(vad_cfg.get("aggressiveness", 2)))
return EnergyVadGate(threshold=float(vad_cfg.get("energy_threshold", 200.0)))
def build_engines(cfg: dict, trace=None) -> VoiceEngines:
"""Construct the real engine bundle from a `gateway.voice` config block."""
wake_cfg = cfg.get("wake", {}) or {}
stt_cfg = cfg.get("stt", {}) or {}
tts_cfg = cfg.get("tts", {}) or {}
audio_cfg = cfg.get("audio", {}) or {}
wake_model = resolve_model_path(
str(wake_cfg.get("model", "hey_mycroft") or ""),
str(wake_cfg.get("model_dir", "") or ""),
(".onnx", ".tflite"),
)
tts_voice = resolve_model_path(
str(tts_cfg.get("voice", "") or ""),
str(tts_cfg.get("voice_dir", "") or ""),
(".onnx",),
)
return VoiceEngines(
wake=OpenWakeWordDetector(
wake_model,
threshold=float(wake_cfg.get("threshold", 0.5)),
inference_framework=str(wake_cfg.get("inference_framework", "onnx")),
),
vad=_build_vad(cfg),
stt=WhisperTranscriber(
model=str(stt_cfg.get("model", "base.en") or "base.en"),
device=str(stt_cfg.get("device", "cpu") or "cpu"),
compute_type=str(stt_cfg.get("compute_type", "int8") or "int8"),
language=str(stt_cfg.get("language", "en") or "en"),
),
tts=PiperSynthesizer(
tts_voice,
speaker_id=int(tts_cfg.get("speaker_id", 0) or 0),
length_scale=float(tts_cfg.get("length_scale", 1.0) or 1.0),
volume=float(tts_cfg.get("volume", 1.0) or 1.0),
),
audio=SoundDeviceAudio(
input_device=str(audio_cfg.get("input_device", "") or ""),
output_device=str(audio_cfg.get("output_device", "") or ""),
capture_sample_rate=int(audio_cfg.get("capture_sample_rate", 0) or 0),
output_sample_rate=int(audio_cfg.get("output_sample_rate", 0) or 0),
dc_removal=bool(audio_cfg.get("dc_removal", True)),
),
)
# --------------------------------------------------------------------------- #
# The loop
# --------------------------------------------------------------------------- #
class VoiceDaemon:
"""Drives the engines: listen for the wake word, endpoint, transcribe, speak.
`run(on_utterance)` blocks on the mic until `stop()` (or the input closes),
calling `on_utterance(text)` for each transcribed utterance. `speak(text)`
synthesizes and plays a reply; it is safe to call from another thread (the
adapter's outbound pump) while `run` is listening.
"""
def __init__(self, cfg: dict | None = None, trace=None, engines: VoiceEngines | None = None,
name: str = "voice"):
cfg = cfg or {}
self.config = cfg
self.trace = trace
self.name = name
self.wake_threshold = float((cfg.get("wake", {}) or {}).get("threshold", 0.5))
audio_cfg = cfg.get("audio", {}) or {}
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.input_device = str(audio_cfg.get("input_device", "") or "")
vad_cfg = cfg.get("vad", {}) or {}
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.max_utterance_s = float(vad_cfg.get("max_utterance_s", 30) or 30)
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)
cue = cfg.get("cue", {}) or {}
self.cue_enabled = bool(cue.get("enabled", True))
self.cue_frequency = float(cue.get("frequency", 880) or 0)
self.cue_duration_ms = int(cue.get("duration_ms", 120) or 0)
self.cue_volume = float(cue.get("volume", 0.25) or 0)
self.cue_submit_frequency = float(cue.get("submit_frequency", 0) or 0)
self.cue_submit_duration_ms = int(cue.get("submit_duration_ms", 100) or 0)
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()
self._follow_until = 0.0
# ---- requirements ----
def check_requirements(self) -> tuple[bool, str | None]:
"""Return `(ok, install_hint)`. Never raises on a missing optional dep.
Actually imports each module (not just `find_spec`): `sounddevice`
raises `OSError` at import when the system PortAudio library is absent,
which a spec lookup would miss.
"""
missing = []
for module, hint in _REQUIRED_MODULES:
try:
importlib.import_module(module)
except Exception:
missing.append(hint)
if missing:
return False, (
"install the voice stack (requirements/voice.txt): " + "; ".join(missing)
)
return True, None
# ---- lifecycle ----
def _ensure_engines(self) -> VoiceEngines:
with self._engines_lock:
if self._engines is None:
self._engines = build_engines(self.config, trace=self.trace)
return self._engines
def run(self, on_utterance: UtteranceHandler) -> None:
self._on_utterance = on_utterance
self._stop.clear()
engines = self._ensure_engines()
engines.audio.open_input(self.sample_rate, self.frame_ms, self.input_device)
self._event("voice_listening", sample_rate=self.sample_rate, frame_ms=self.frame_ms)
try:
self._loop(engines)
finally:
self._close_engines()
def stop(self) -> None:
self._stop.set()
engines = self._engines
if engines is not None:
try:
engines.audio.close() # unblocks a pending read
except Exception:
pass
def close(self) -> None:
self.stop()
def _close_engines(self) -> None:
engines = self._engines
if engines is None:
return
for engine in (engines.wake, engines.vad, engines.stt, engines.tts, engines.audio):
try:
engine.close()
except Exception:
pass
# ---- listening ----
def _loop(self, engines: VoiceEngines) -> None:
while not self._stop.is_set():
pcm = engines.audio.read()
if pcm is None:
return
if self._speaking.is_set():
continue
armed = time.time() < self._follow_until
if not armed:
score = engines.wake.score(pcm)
if score < self.wake_threshold:
continue
self._event("voice_wake", score=round(float(score), 3))
try:
engines.wake.reset()
except Exception:
pass
self._cue(self.cue_frequency, self.cue_duration_ms)
self._follow_until = 0.0
utterance = self._collect(engines, pcm)
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._cue(self.cue_submit_frequency, self.cue_submit_duration_ms)
if self._on_utterance is not None:
self._on_utterance(text)
def _collect(self, engines: VoiceEngines, first_frame: bytes) -> bytes:
"""Accumulate frames from the wake word until trailing silence."""
frames = [first_frame]
speech_ms = self.frame_ms
silence_ms = 0
started = time.time()
while not self._stop.is_set():
if self._speaking.is_set():
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:
break
pcm = engines.audio.read()
if pcm is None:
break
frames.append(pcm)
if engines.vad.is_speech(pcm, self.sample_rate):
speech_ms += self.frame_ms
silence_ms = 0
else:
silence_ms += self.frame_ms
if silence_ms >= self.vad_silence_ms:
break
if speech_ms < self.min_speech_ms:
self._event(
"voice_short_utterance",
frames=len(frames),
speech_ms=speech_ms,
silence_ms=silence_ms,
)
return b""
self._event("voice_utterance", frames=len(frames), speech_ms=speech_ms)
return b"".join(frames)
# ---- speaking ----
def _cue(self, frequency: float, duration_ms: int) -> None:
"""Play a short beep (wake / submit cue). Silent on failure."""
if not self.cue_enabled or frequency <= 0 or duration_ms <= 0:
return
engines = self._engines
if engines is None:
return
pcm = _tone_pcm(frequency, duration_ms, self.sample_rate, self.cue_volume)
if not pcm:
return
with self._audio_lock:
try:
engines.audio.open_output(self.sample_rate)
engines.audio.write(pcm, self.sample_rate)
self._event("voice_cue", frequency=frequency, duration_ms=duration_ms)
except Exception as exc:
self._event("voice_cue_failed", message=str(exc)[:200])
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.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()
self._speaking.set()
try:
pcm, sample_rate = engines.tts.synthesize(text)
if pcm:
with self._audio_lock:
engines.audio.open_output(sample_rate)
engines.audio.write(pcm, sample_rate)
self._event("voice_spoke", chars=len(text))
except Exception as exc:
self._event("voice_speak_failed", message=str(exc)[:300])
finally:
self._speaking.clear()
try:
engines.audio.flush() # clear any TTS echo captured while speaking
except Exception:
pass
if self.follow_up_window > 0:
self._follow_until = time.time() + self.follow_up_window
try:
engines.wake.reset()
except Exception:
pass
# ---- tracing ----
def _event(self, kind: str, **fields) -> None:
if self.trace is not None:
self.trace.append(kind, "?", **fields)
+309
View File
@@ -0,0 +1,309 @@
"""Pure-stdlib tests for the voice gateway (adapter + neutral transport).
The voice stack (sounddevice/openwakeword/faster-whisper/piper) is optional and
lazy-imported, so these tests inject fake engines and drive the loop without
hardware, network, or the heavy packages. The live pipeline against a real mic
is a live-integration concern.
Frame constants: the fake wake word fires on `b"WAKE"`, the fake VAD calls any
non-`b"SIL"` frame speech, and the fake STT returns a fixed string.
"""
from semif_agent.cli import _build_gateway_adapter, _resolve_platforms
from semif_agent.gateway.voice import VoiceAdapter
from semif_agent.voice_transport import VoiceDaemon, VoiceEngines
# ---- fakes -----------------------------------------------------------------
class FakeAudio:
def __init__(self, frames):
self.frames = list(frames)
self.writes = []
self.closed = False
self.input_opened = False
def open_input(self, sample_rate, frame_ms, device=""):
self.input_opened = True
def read(self):
return self.frames.pop(0) if self.frames else None
def open_output(self, sample_rate, device=""):
pass
def write(self, pcm16, sample_rate):
self.writes.append((pcm16, sample_rate))
def flush(self):
pass # the scripted `frames` are input, not a capture buffer
def close(self):
self.closed = True
class FakeWake:
def __init__(self, trigger=b"WAKE"):
self.trigger = trigger
self.resets = 0
def score(self, pcm16):
return 1.0 if pcm16 == self.trigger else 0.0
def reset(self):
self.resets += 1
class FakeVad:
def is_speech(self, pcm16, sample_rate):
return pcm16 != b"SIL"
class FakeStt:
def __init__(self, text="hello"):
self.text = text
self.calls = []
def transcribe(self, pcm16):
self.calls.append(pcm16)
return self.text
class FakeTts:
def __init__(self):
self.spoken = []
def synthesize(self, text):
self.spoken.append(text)
return b"PCM", 22050
def make_daemon(frames, stt_text="hello", config=None):
audio = FakeAudio(frames)
engines = VoiceEngines(
wake=FakeWake(),
vad=FakeVad(),
stt=FakeStt(stt_text),
tts=FakeTts(),
audio=audio,
)
cfg = {
"audio": {"frame_ms": 80, "sample_rate": 16000},
"vad": {"silence_ms": 160, "min_speech_ms": 80, "max_utterance_s": 30},
"follow_up_window_s": 5.0,
"max_speak_chars": 600,
}
if config:
cfg.update(config)
return VoiceDaemon(cfg, engines=engines), engines
# ---- requirements ----------------------------------------------------------
def test_check_requirements_never_raises():
# Either the voice stack is installed (True) or an install hint is returned;
# the daemon must never raise on a machine without the optional deps.
ok, hint = VoiceDaemon({}).check_requirements()
assert isinstance(ok, bool)
if not ok:
assert "requirements/voice.txt" in hint
def test_check_requirements_reports_missing(monkeypatch):
import semif_agent.voice_transport as vt
def boom(name):
raise ImportError(name)
monkeypatch.setattr(vt.importlib, "import_module", boom)
ok, hint = VoiceDaemon({}).check_requirements()
assert ok is False
assert "requirements/voice.txt" in hint
assert "sounddevice" in hint
# ---- wake gating / endpointing --------------------------------------------
def test_wake_word_then_silence_produces_one_utterance():
daemon, engines = make_daemon([b"noise", b"WAKE", b"speech", b"SIL", b"SIL"])
heard = []
daemon.run(heard.append)
assert heard == ["hello"]
assert engines.audio.input_opened is True
assert engines.audio.closed is True
# The wake detector is reset after firing.
assert engines.wake.resets >= 1
def test_no_wake_word_produces_nothing():
daemon, engines = make_daemon([b"noise", b"noise", b"SIL"])
heard = []
daemon.run(heard.append)
assert heard == []
assert engines.stt.calls == []
def test_max_utterance_caps_collection(monkeypatch):
import semif_agent.voice_transport as vt
ticks = iter([0.0, 5.0, 5.0, 5.0])
monkeypatch.setattr(vt.time, "time", lambda: next(ticks))
daemon, engines = make_daemon(
[b"a", b"b", b"c"],
config={"vad": {"silence_ms": 160, "min_speech_ms": 80, "max_utterance_s": 1.0}},
)
utterance = daemon._collect(engines, b"first")
assert utterance == b"first"
def test_min_speech_rejects_short_utterance():
daemon, engines = make_daemon(
[b"WAKE", b"SIL", b"SIL"],
config={"vad": {"silence_ms": 160, "min_speech_ms": 200, "max_utterance_s": 30}},
)
heard = []
daemon.run(heard.append)
assert heard == []
assert engines.stt.calls == []
# ---- half-duplex / speaking ------------------------------------------------
def test_frames_ignored_while_speaking():
daemon, engines = make_daemon([b"WAKE", b"speech", b"SIL"])
daemon._speaking.set()
heard = []
daemon.run(heard.append)
assert heard == []
assert engines.stt.calls == []
def test_speak_synthesizes_and_plays():
daemon, engines = make_daemon([])
daemon.speak(" hello there ")
assert engines.tts.spoken == ["hello there"]
assert engines.audio.writes == [(b"PCM", 22050)]
# A reply opens the follow-up window (no wake word needed next).
assert daemon._follow_until > 0
def test_follow_up_window_accepts_without_wake():
daemon, engines = make_daemon([b"speech", b"SIL", b"SIL"])
daemon.speak("are you there?") # opens the follow-up window
heard = []
daemon.run(heard.append)
assert heard == ["hello"]
def test_speak_truncates_long_text():
daemon, engines = make_daemon([], config={"max_speak_chars": 10})
daemon.speak("one two three four five")
assert engines.tts.spoken[0] == "one two…"
def test_speak_failure_is_traced_not_raised():
class BoomTts(FakeTts):
def synthesize(self, text):
raise RuntimeError("no audio device")
daemon, engines = make_daemon([])
engines.tts = BoomTts()
daemon._engines = engines
daemon.speak("hello") # must not raise
assert engines.audio.writes == []
# ---- adapter ---------------------------------------------------------------
def test_adapter_defaults():
adapter = VoiceAdapter({})
assert adapter.name == "voice"
assert adapter.chat_id == "voice"
assert adapter.daemon.sample_rate == 16000
def test_adapter_emits_inbound_message():
adapter = VoiceAdapter({"chat_id": "mic", "display_name": "desk"})
seen = []
adapter._on_inbound = seen.append
adapter._on_utterance(" hello there ")
assert len(seen) == 1
assert seen[0].text == "hello there"
assert seen[0].chat_id == "mic"
assert seen[0].display_name == "desk"
assert seen[0].chat_type == "dm"
def test_adapter_ignores_empty_utterance():
adapter = VoiceAdapter({})
seen = []
adapter._on_inbound = seen.append
adapter._on_utterance(" ")
assert seen == []
# ---- CLI wiring ------------------------------------------------------------
def test_build_gateway_adapter_voice_anchors_model_dirs():
adapter = _build_gateway_adapter("voice", {"enabled": True}, None)
assert isinstance(adapter, VoiceAdapter)
assert adapter.daemon.config["wake"]["model_dir"].endswith(".runtime/voice/wake")
assert adapter.daemon.config["tts"]["voice_dir"].endswith(".runtime/voice/tts")
def test_resolve_platforms_includes_enabled_voice():
platforms = _resolve_platforms(
"all",
{"simplex": {"enabled": False}, "voice": {"enabled": True}},
)
assert platforms == ["voice"]
# ---- wake cue (beep) -------------------------------------------------------
def test_tone_pcm_length():
from semif_agent.voice_transport import _tone_pcm
pcm = _tone_pcm(880, 100, 16000, 0.25)
assert len(pcm) == 1600 * 2 # 100 ms @ 16 kHz, int16
assert _tone_pcm(0, 100, 16000, 0.25) == b""
def test_wake_plays_cue():
daemon, engines = make_daemon([b"WAKE", b"speech", b"SIL", b"SIL"])
daemon.run(lambda text: None)
# exactly one cue played on wake, at the processing rate
assert len(engines.audio.writes) == 1
pcm, rate = engines.audio.writes[0]
assert rate == 16000
assert len(pcm) == int(16000 * 120 / 1000) * 2
def test_cue_disabled_suppresses_beep():
daemon, engines = make_daemon(
[b"WAKE", b"speech", b"SIL", b"SIL"], config={"cue": {"enabled": False}}
)
daemon.run(lambda text: None)
assert engines.audio.writes == []
# ---- resampling (numpy is a voice-stack dep; skip without it) --------------
def test_resample_pcm16():
import pytest
np = pytest.importorskip("numpy")
from semif_agent.voice_transport import _resample_pcm16
pcm = np.arange(441, dtype=np.int16).tobytes()
assert len(_resample_pcm16(pcm, 44100, 16000)) // 2 == 160
assert _resample_pcm16(pcm, 44100, 44100) == pcm
assert _resample_pcm16(b"", 44100, 16000) == b""