lxmf: Sideband voice messages (transcribe + Piper voice replies)

The LXMF gateway now handles Sideband push-to-talk voice messages end to end.

Inbound: a PTT message carries its audio in LXMF.FIELD_AUDIO
(`[audio_mode, bytes]`); `lxmf_transport.parse_audio_field` normalizes it and
the adapter transcribes it into an ordinary command when
`gateway.lxmf.voice.enabled` is set. HQ Opus/OGG goes through faster-whisper
(requirements/transcribe.txt); non-HQ Codec2 through the optional pycodec2
bindings (requirements/codec2.txt). No microphone stack is needed.

Outbound: a chat that last messaged by voice is answered with a synthesized
voice message when `gateway.lxmf.voice.reply_with_voice` is on (the default).
`voice_transport.build_synthesizer` speaks the reply with Piper and
`voice_transport.pcm_to_opus_ogg` encodes it to OGG/Opus (48 kHz, PyAV's
libopus); `lxmf_transport.audio_fields` attaches it as a Sideband HQ PTT
message, with the reply text as the content so a text-only client still sees
it. The reply mode follows the chat's most recent inbound message. A missing
synthesizer or any synthesis/encode failure is traced and the reply falls back
to text. Deps: requirements/tts.txt (piper-tts + PyAV), still no microphone.

Also make LXMF replies result-only (`LxmfAdapter.result_only`, overridable via
`gateway.lxmf.result_only: false`): send the skill's result line, dropping
scheduler bookkeeping and the `<skill>: ok —` wrapper.

Wiring: new config keys under `gateway.lxmf` (result_only) and
`gateway.lxmf.voice` (reply_with_voice, max_speak_chars, reply_bitrate, tts);
regenerated config.example.json; the setup interview asks how to handle voice
messages and the install plan adds `install_lxmf_tts` (bootstrap installs
requirements/tts.txt and downloads the reply voice); cli anchors the LXMF
voice_dir to .runtime/voice/tts.

Tests cover the audio field shape, the outbound queue, the adapter's
voice-chat tracking and synthesis fallbacks, result-only routing, the
synthesis/encode helpers, and the setup plan. Docs updated.
This commit is contained in:
gabby committed 2026-10-17 04:53:51 +00:00
1 parent b1a7bfd272
commit ed894bd329
21 files changed
+1804 -78

No files matched your search

+8
View File
@@ -838,6 +838,14 @@ def _build_gateway_adapter(platform: str, cfg: dict, trace):
# Contain Reticulum's config + identity under the checkout's .runtime/.
cfg.setdefault("config_dir", str(REPO_ROOT / ".runtime" / "lxmf" / "reticulum"))
cfg.setdefault("storage_path", str(REPO_ROOT / ".runtime" / "lxmf" / "router"))
# A voice reply's Piper voice lives with the voice gateway's, under the
# checkout's .runtime/ (bootstrap downloads it there).
voice_cfg = dict(cfg.get("voice") or {})
tts_cfg = dict(voice_cfg.get("tts") or {})
if not tts_cfg.get("voice_dir"):
tts_cfg["voice_dir"] = str(REPO_ROOT / ".runtime" / "voice" / "tts")
voice_cfg["tts"] = tts_cfg
cfg["voice"] = voice_cfg
return LxmfAdapter(cfg, trace=trace)
if platform == "voice":
from .gateway.voice import VoiceAdapter
+25 -1
View File
@@ -166,7 +166,31 @@ CORE_SCHEMA: dict[str, Any] = {'tau': {'default': 0.6, 'type': 'float', 'doc': '
'storage_path': {'default': '', 'type': 'str'},
'home_channel': {'default': '', 'type': 'str'},
'reply_prefix': {'default': '', 'type': 'str'},
'text_batch_delay': {'default': 0.8, 'type': 'float'}},
'text_batch_delay': {'default': 0.8, 'type': 'float'},
# Reply with the skill's result line only (drop queue/
# urgency chatter and the `<skill>: ok —` wrapper).
'result_only': {'default': True, 'type': 'bool'},
# Transcribe Sideband push-to-talk voice messages
# (FIELD_AUDIO) into commands and (when reply_with_voice)
# answer a voice chat with a Piper voice reply. Needs only
# faster-whisper (requirements/transcribe.txt) plus
# piper-tts + PyAV (requirements/tts.txt) for replies,
# not the microphone stack.
'voice': {'enabled': {'default': False, 'type': 'bool'},
'reply_with_voice': {'default': True, 'type': 'bool'},
'max_speak_chars': {'default': 600, 'type': 'int'},
'reply_bitrate': {'default': 24000, 'type': 'int'},
'stt': {'model': {'default': 'base.en', 'type': 'str'},
'device': {'default': 'cpu', 'type': 'str'},
'compute_type': {'default': 'int8', 'type': 'str'},
'language': {'default': 'en', 'type': 'str'}},
'tts': {'voice': {'default': 'en_US-lessac-medium',
'type': 'str'},
'voice_dir': {'default': '', 'type': 'str'},
'speaker_id': {'default': 0, 'type': 'int'},
'length_scale': {'default': 1.0,
'type': 'float'},
'volume': {'default': 1.0, 'type': 'float'}}}},
'voice': {'enabled': {'default': False, 'type': 'bool'},
'chat_id': {'default': 'voice', 'type': 'str'},
'display_name': {'default': 'voice', 'type': 'str'},
+4 -4
View File
@@ -51,10 +51,10 @@ class GatewayAdapter(ABC):
#: short platform name used in request sources (`"simplex:<chat_id>"`)
name: str = "gateway"
#: Spoken front ends (the voice gateway) set this so the service speaks only
#: the skill's result line, not the scheduler's bookkeeping (queue/urgency
#: status) and not the `<skill>: ok —` wrapper. A per-platform config
#: `result_only` overrides it. Plain chat adapters leave it False.
#: Front ends that should send only the skill's result line set this, so the
#: service drops the scheduler's bookkeeping (queue/urgency status) and the
#: `<skill>: ok —` wrapper. The voice gateway and the LXMF gateway set it; a
#: per-platform config `result_only` overrides it either way.
result_only: bool = False
@abstractmethod
+349 -24
View File
@@ -11,6 +11,32 @@ This adapter is the policy layer over the neutral `LxmfDaemon` transport in
and hands authorized text to the scheduler. Unlike the SimpleX adapter there is
no external daemon and no event loop — Reticulum runs in-process on its own
threads, so batching uses a per-chat `threading.Timer`.
**Voice commands.** A Sideband push-to-talk message arrives as LXMF content with
an empty body and the audio in `FIELD_AUDIO` (`[audio_mode, bytes]`); the
transport surfaces it as a normalized `audio` dict. When `voice.enabled` is set,
this adapter transcribes that payload to text and dispatches the transcript as an
ordinary command — so the same allowlist, batching-free delivery, and reply path
apply. Both PTT shapes are handled: HQ Opus/OGG goes through
`WhisperTranscriber.transcribe_bytes` (faster-whisper's bundled PyAV decodes the
container), and non-HQ Codec2 is decoded to 8 kHz PCM by `voice_transport.
decode_codec2` (the optional `pycodec2` bindings), wrapped in a WAV, and
transcribed the same way. Transcription needs only `faster-whisper`
(`requirements/transcribe.txt`), never the microphone voice stack; Codec2
additionally needs `pycodec2` (`requirements/codec2.txt`). A missing transcriber,
missing Codec2 decoder, or undecodable mode is traced and reported, never
silently dropped; the audio itself is transient and never stored, exactly like
the voice gateway.
**Voice replies.** When `voice.reply_with_voice` is on (the default), a reply to
a chat that last messaged by voice is synthesized with Piper and sent back as a
Sideband HQ push-to-talk voice message (the reply text is encoded to Opus/OGG
and rides `FIELD_AUDIO`), so a voice user hears the answer. The reply *mode*
follows the chat's most recent inbound message: a text message reverts it to
text replies. It needs `piper-tts` + PyAV (`requirements/tts.txt`), never the
microphone stack; a missing synthesizer, a synthesis failure, or an encode
failure is traced and the reply falls back to text — never dropped. The reply
text is also sent as the message content, so a text-only client still sees it.
"""
from __future__ import annotations
@@ -20,14 +46,50 @@ import queue
import threading
from semif_agent.lxmf_transport import LxmfDaemon
from semif_agent.voice_transport import (
OPUS_OGG_BITRATE,
build_synthesizer,
build_transcriber,
check_codec2_requirements,
check_synthesis_requirements,
check_transcription_requirements,
decode_codec2,
pcm_to_opus_ogg,
pcm_to_wav,
)
from .base import GatewayAdapter, InboundMessage, OutboundMessage
#: Sent (once) when a voice message can't be transcribed at all. A spoken or
#: typed command still works, so the user is not left guessing.
VOICE_FAILED_MESSAGE = (
"Sorry, I couldn't make out that voice message — please resend it or type "
"your command."
)
#: Sent when the codec is one we can't decode (the raw Opus `AM_OPUS_*` modes
#: and the binding-less 450 Codec2 modes; HQ Opus is the default and works).
VOICE_UNSUPPORTED_MESSAGE = (
"I can't read that voice format yet — send an HQ (Opus) voice message, or "
"type your command."
)
#: Sent for a Codec2 voice message when the optional Codec2 decoder is absent.
VOICE_CODEC2_MESSAGE = (
"I can't read that Codec2 voice message — the codec2 decoder isn't "
"installed. Send an HQ (Opus) voice message, or type your command."
)
class LxmfAdapter(GatewayAdapter):
name = "lxmf"
#: Send the skill's result line only — drop the scheduler's queue/urgency
#: bookkeeping and the `<skill>: ok —` wrapper, so a reply (text or voice) is
#: the answer, not the internals. Override with `gateway.lxmf.result_only:
#: false` for the full scheduler output.
result_only = True
def __init__(self, cfg: dict | None = None, trace=None):
def __init__(
self, cfg: dict | None = None, trace=None, transcriber=None, synthesizer=None
):
cfg = cfg or {}
self.allowed_users = [str(u) for u in cfg.get("allowed_users", []) or []]
self.allow_all_users = bool(cfg.get("allow_all_users", False))
@@ -51,8 +113,31 @@ class LxmfAdapter(GatewayAdapter):
)
self.config_dir = config_dir
self.storage_path = storage_path
#: Voice-message transcription (`gateway.lxmf.voice`). The transcriber is
#: built lazily from `voice.stt` (faster-whisper only) on the first
#: voice message; a test can inject one instead.
self.voice_cfg = cfg.get("voice", {}) or {}
self.voice_enabled = bool(self.voice_cfg.get("enabled", False))
#: Reply to a voice chat with a synthesized voice message (Piper). The
#: reply mode follows the chat's most recent inbound message.
self.reply_with_voice = bool(self.voice_cfg.get("reply_with_voice", True))
self.voice_max_chars = int(self.voice_cfg.get("max_speak_chars", 600) or 0)
self.voice_bitrate = int(
self.voice_cfg.get("reply_bitrate", OPUS_OGG_BITRATE) or OPUS_OGG_BITRATE
)
self._transcriber = transcriber
self._transcriber_unavailable = False
self._synthesizer = synthesizer
self._synthesizer_unavailable = False
#: Chats whose most recent inbound message was voice: their replies go
#: back as voice (until a text message reverts them).
self._voice_chats: set[str] = set()
self._voice_queue: "queue.Queue[tuple[dict, dict] | None]" = queue.Queue()
self._voice_thread: threading.Thread | None = None
self._voice_lock = threading.Lock()
self._outbound: "queue.Queue[OutboundMessage | None] | None" = None
self._buffers: dict[str, str] = {}
self._buffered: dict[str, InboundMessage] = {}
self._buffered: dict[str, dict] = {}
self._timers: dict[str, threading.Timer] = {}
self._lock = threading.Lock()
self._on_inbound = None
@@ -60,6 +145,9 @@ class LxmfAdapter(GatewayAdapter):
# ---- requirements ----
def check_requirements(self) -> tuple[bool, str | None]:
# Only the transport is mandatory: text commands work without the
# optional transcription stack, and a voice message then traces
# `lxmf_voice_unavailable` rather than taking the whole gateway down.
return self.daemon.check_requirements()
# ---- authorization ----
@@ -82,17 +170,20 @@ class LxmfAdapter(GatewayAdapter):
outbound: "queue.Queue[OutboundMessage | None]",
) -> None:
self._on_inbound = on_inbound
self._outbound = outbound
def _pump() -> None:
# Translate the service's OutboundMessage queue onto the daemon's
# (chat_id, text) queue without letting scheduler work touch the
# Reticulum callback threads.
# (chat_id, text, audio) queue without letting scheduler work touch
# the Reticulum callback threads. Synthesis runs here (off the router
# thread), so a slow Piper render never stalls the transport.
while True:
message = outbound.get()
if message is None:
self.daemon.enqueue(None)
return
self.daemon.enqueue(message.chat_id, message.text)
audio = self._voice_reply(message)
self.daemon.enqueue(message.chat_id, message.text, audio=audio)
threading.Thread(
target=_pump, name="lxmf-outbound-pump", daemon=True
@@ -105,6 +196,7 @@ class LxmfAdapter(GatewayAdapter):
self._timers.clear()
for timer in timers:
timer.cancel()
self._voice_queue.put(None)
self.daemon.close()
# ---- inbound ----
@@ -121,23 +213,23 @@ class LxmfAdapter(GatewayAdapter):
display_name=display_name,
)
return
inbound = InboundMessage(
text=message.get("content") or "",
chat_id=source_hash,
chat_type="dm",
contact_id=source_hash,
display_name=display_name,
raw=message.get("raw") or {},
)
self._schedule_flush(inbound)
audio = message.get("audio")
if audio:
# A voice message puts the chat in voice-reply mode (when the reply
# path is on); a later text message reverts it.
if self.voice_enabled and self.reply_with_voice:
self._mark_voice_chat(source_hash)
self._handle_audio(message, audio)
return
self._unmark_voice_chat(source_hash)
self._schedule_flush(message)
def _schedule_flush(self, message: InboundMessage) -> None:
chat = message.chat_id
def _schedule_flush(self, message: dict) -> None:
chat = str(message.get("source_hash") or "")
text = message.get("content") or ""
with self._lock:
existing = self._buffers.get(chat)
self._buffers[chat] = (
f"{existing}\n{message.text}" if existing else message.text
)
self._buffers[chat] = f"{existing}\n{text}" if existing else text
self._buffered[chat] = message
timer = self._timers.get(chat)
if timer is not None:
@@ -154,12 +246,245 @@ class LxmfAdapter(GatewayAdapter):
self._timers.pop(chat, None)
if message is None or not text:
return
message.text = text
self._deliver(message, text)
def _deliver(self, message: dict, text: str) -> None:
"""Hand one command to the service (never called on the router thread)."""
source_hash = str(message.get("source_hash") or "")
display_name = message.get("display_name")
self.daemon._event(
"gateway_message",
contact_id=message.contact_id,
display_name=message.display_name,
contact_id=source_hash,
display_name=display_name,
chars=len(text),
)
if self._on_inbound is not None:
self._on_inbound(message)
if self._on_inbound is None:
return
self._on_inbound(
InboundMessage(
text=text,
chat_id=source_hash,
chat_type="dm",
contact_id=source_hash,
display_name=display_name,
raw=message.get("raw") or {},
)
)
# ---- voice messages (Sideband push-to-talk) ----
def _handle_audio(self, message: dict, audio: dict) -> None:
"""Route a received voice message to transcription, or report why not.
Runs on the Reticulum callback thread, so it only enqueues: the actual
(slow) transcription happens on the worker thread, keeping the router
responsive. An ignored/undecodable payload keeps any caption text.
"""
source_hash = str(message.get("source_hash") or "")
codec = audio.get("codec_name")
content = message.get("content") or ""
if not self.voice_enabled:
self.daemon._event(
"lxmf_voice_ignored", contact_id=source_hash, codec=codec
)
if content:
self._schedule_flush(message)
return
kind = audio.get("kind")
if kind == "codec2":
# Codec2 needs the optional pycodec2 bindings; report a missing one
# up front rather than queueing a transcription that can't happen.
ok, _hint = check_codec2_requirements()
if not ok:
self.daemon._event(
"lxmf_voice_codec2_unavailable", contact_id=source_hash, codec=codec
)
if content:
self._schedule_flush(message)
else:
self._notify(message, VOICE_CODEC2_MESSAGE)
return
elif kind != "opus_ogg":
self.daemon._event(
"lxmf_voice_unsupported_codec", contact_id=source_hash, codec=codec
)
if content:
self._schedule_flush(message)
else:
self._notify(message, VOICE_UNSUPPORTED_MESSAGE)
return
self._ensure_voice_worker()
self._voice_queue.put((message, audio))
def _ensure_voice_worker(self) -> None:
with self._voice_lock:
if self._voice_thread is not None and self._voice_thread.is_alive():
return
self._voice_thread = threading.Thread(
target=self._voice_worker, name="lxmf-voice-worker", daemon=True
)
self._voice_thread.start()
def _voice_worker(self) -> None:
"""Transcribe queued voice messages off the Reticulum callback thread."""
while True:
item = self._voice_queue.get()
if item is None:
return
message, audio = item
text = self._transcribe(audio)
content = (message.get("content") or "").strip()
if not text:
if content:
self._deliver(message, content)
else:
self._notify(message, VOICE_FAILED_MESSAGE)
continue
self._deliver(message, f"{content}\n{text}" if content else text)
def _transcribe(self, audio: dict) -> str:
"""Transcribe one audio payload to text; "" (traced) on any failure."""
transcriber = self._ensure_transcriber()
if transcriber is None:
return ""
data = audio.get("data") or b""
if not data:
self.daemon._event("lxmf_voice_empty", codec=audio.get("codec_name"))
return ""
if audio.get("kind") == "codec2":
# Codec2 decodes to raw 8 kHz PCM; wrap it in a WAV so faster-whisper's
# PyAV decodes and resamples it like any other container.
pcm = decode_codec2(data, audio.get("codec2_rate") or 0)
if not pcm:
self.daemon._event(
"lxmf_voice_codec2_failed", codec=audio.get("codec_name")
)
return ""
payload = pcm_to_wav(pcm, 8000)
else:
payload = data
try:
text = transcriber.transcribe_bytes(payload)
except NotImplementedError:
self.daemon._event(
"lxmf_voice_transcribe_unsupported", codec=audio.get("codec_name")
)
return ""
except Exception as exc:
self.daemon._event(
"lxmf_voice_transcribe_failed", message=str(exc)[:300]
)
return ""
text = (text or "").strip()
if not text:
self.daemon._event(
"lxmf_voice_empty_transcript", codec=audio.get("codec_name")
)
return ""
self.daemon._event(
"lxmf_voice_transcribed", codec=audio.get("codec_name"), chars=len(text)
)
return text
def _ensure_transcriber(self):
"""Build (once) and return the transcriber, or None (traced) if absent."""
with self._voice_lock:
if self._transcriber is not None:
return self._transcriber
if self._transcriber_unavailable:
return None
ok, hint = check_transcription_requirements()
if not ok:
self._transcriber_unavailable = True
self.daemon._event("lxmf_voice_unavailable", message=hint)
return None
try:
self._transcriber = build_transcriber(self.voice_cfg)
except Exception as exc:
self._transcriber_unavailable = True
self.daemon._event("lxmf_voice_unavailable", message=str(exc)[:300])
return None
return self._transcriber
def _notify(self, message: dict, text: str) -> None:
"""Send a transport-level notice back to the sender (best-effort).
A transcription failure is reported to the user rather than silently
dropped; the audio itself is never stored or forwarded.
"""
chat = str(message.get("source_hash") or "")
outbound = self._outbound
if outbound is None or not chat:
return
outbound.put(OutboundMessage(chat_id=chat, text=text))
# ---- voice replies (Piper -> Opus/OGG) ----
def _mark_voice_chat(self, chat: str) -> None:
with self._lock:
self._voice_chats.add(chat)
def _unmark_voice_chat(self, chat: str) -> None:
with self._lock:
self._voice_chats.discard(chat)
def _voice_reply(self, message) -> bytes | None:
"""Synthesize a voice reply for a voice chat, or None to send text.
Runs on the outbound pump thread. Returns an OGG/Opus container (a
Sideband HQ push-to-talk payload) or None — for a text chat, an empty
reply, or any synthesis/encode failure (traced), in which case the
caller sends the text reply unchanged.
"""
if not self.reply_with_voice:
return None
chat = str(message.chat_id)
with self._lock:
is_voice = chat in self._voice_chats
if not is_voice:
return None
text = (message.text or "").strip()
if not text:
return None
if self.voice_max_chars and len(text) > self.voice_max_chars:
clipped = text[: self.voice_max_chars].rsplit(" ", 1)[0]
text = clipped or text[: self.voice_max_chars]
synthesizer = self._ensure_synthesizer()
if synthesizer is None:
return None
try:
pcm, sample_rate = synthesizer.synthesize(text)
except Exception as exc:
self.daemon._event("lxmf_voice_synth_failed", message=str(exc)[:300])
return None
if not pcm:
self.daemon._event("lxmf_voice_synth_empty")
return None
audio = pcm_to_opus_ogg(pcm, sample_rate, self.voice_bitrate)
if not audio:
self.daemon._event("lxmf_voice_encode_failed", chars=len(text))
return None
self.daemon._event(
"lxmf_voice_reply", chars=len(text), audio_bytes=len(audio)
)
return audio
def _ensure_synthesizer(self):
"""Build (once) and return the Piper synthesizer, or None (traced)."""
with self._voice_lock:
if self._synthesizer is not None:
return self._synthesizer
if self._synthesizer_unavailable:
return None
ok, hint = check_synthesis_requirements()
if not ok:
self._synthesizer_unavailable = True
self.daemon._event("lxmf_voice_tts_unavailable", message=hint)
return None
try:
self._synthesizer = build_synthesizer(self.voice_cfg)
except Exception as exc:
self._synthesizer_unavailable = True
self.daemon._event("lxmf_voice_tts_unavailable", message=str(exc)[:300])
return None
return self._synthesizer
+132 -9
View File
@@ -31,6 +31,91 @@ MessageHandler = Callable[[InboundDict], None]
#: Zero-argument callback invoked once the router is ready to receive.
ConnectedHandler = Callable[[], None]
#: The LXMF `FIELD_AUDIO` (0x07) field a Sideband push-to-talk voice message
#: rides in. `LXMF` is optional and lazy-imported, so its stable, committed wire
#: constants are mirrored here (the same way `simplex_ws` mirrors the v7 shapes).
FIELD_AUDIO = 0x07
#: Audio modes — the first element of a `FIELD_AUDIO` value (mirrors
#: `LXMF.AM_*`). `AM_OPUS_OGG` is a complete OGG/Opus container a decoder (PyAV,
#: which `faster-whisper` bundles) reads directly; the Codec2 modes are raw
#: frames decoded by `pycodec2`.
AM_OPUS_OGG = 0x10
AUDIO_MODE_NAMES = {
0x01: "codec2_450pwb", 0x02: "codec2_450", 0x03: "codec2_700c",
0x04: "codec2_1200", 0x05: "codec2_1300", 0x06: "codec2_1400",
0x07: "codec2_1600", 0x08: "codec2_2400", 0x09: "codec2_3200",
0x10: "opus_ogg", 0x11: "opus_lbw", 0x12: "opus_mbw", 0x13: "opus_ptt",
0x14: "opus_rt_hdx", 0x15: "opus_rt_fdx", 0x16: "opus_standard",
0x17: "opus_hq", 0x18: "opus_broadcast", 0x19: "opus_lossless",
}
#: Codec2 audio modes -> the codec2 bitrate (bits/s) they decode at. `pycodec2`
#: has bindings for these; 450PWB/450 (0x01/0x02) have none, so they stay
#: undecodable. (Mirrors Sideband's `audioproc.codec2_modes`.)
CODEC2_MODE_RATES = {
0x03: 700, 0x04: 1200, 0x05: 1300, 0x06: 1400,
0x07: 1600, 0x08: 2400, 0x09: 3200,
}
def audio_mode_name(codec: int) -> str:
"""A human-readable name for an audio mode id (e.g. `AM_OPUS_OGG` ->
`opus_ogg`); an unknown id is rendered as hex."""
return AUDIO_MODE_NAMES.get(codec, f"0x{codec:02x}")
def audio_decode_kind(codec: int) -> str:
"""The decode path for an audio mode.
`"opus_ogg"` (a self-contained OGG/Opus container), `"codec2"` (raw Codec2
frames), or `"unknown"` (no decode path — e.g. the raw Opus `AM_OPUS_*`
modes and the binding-less 450 Codec2 modes).
"""
if codec == AM_OPUS_OGG:
return "opus_ogg"
if codec in CODEC2_MODE_RATES:
return "codec2"
return "unknown"
def parse_audio_field(value: Any) -> dict[str, Any] | None:
"""Normalize an LXMF `FIELD_AUDIO` value into a plain dict.
The wire value is `[audio_mode, data]` (see `LXMF.FIELD_AUDIO`): an integer
codec id and the raw audio bytes. Returns
`{"codec", "codec_name", "data", "kind", "codec2_rate"}` or None when
malformed. `kind` is the decode path (`opus_ogg`/`codec2`/`unknown`);
`codec2_rate` is the bitrate for a Codec2 mode, else None.
"""
if not isinstance(value, (list, tuple)) or len(value) < 2:
return None
data = value[1]
if not isinstance(data, (bytes, bytearray)):
return None
try:
codec = int(value[0])
except (TypeError, ValueError):
return None
return {
"codec": codec,
"codec_name": audio_mode_name(codec),
"data": bytes(data),
"kind": audio_decode_kind(codec),
"codec2_rate": CODEC2_MODE_RATES.get(codec),
}
def audio_fields(audio: bytes | None) -> dict[int, Any] | None:
"""The LXMF fields for an outbound voice reply, or None for a text message.
A voice reply rides `FIELD_AUDIO` as `[AM_OPUS_OGG, ogg_bytes]` — the
Sideband HQ push-to-talk shape. Pure so the wire construction is testable
without a Reticulum router.
"""
if not audio:
return None
return {FIELD_AUDIO: [AM_OPUS_OGG, bytes(audio)]}
def _as_text(value: Any) -> str:
"""Best-effort UTF-8 text for a `str`/`bytes`/`None` LXMF field."""
@@ -87,12 +172,24 @@ def normalize_message(message: Any) -> InboundDict:
if source is not None:
display_name = _as_text(getattr(source, "display_name", None))
fields = getattr(message, "fields", None)
if not isinstance(fields, dict):
fields = {}
# A Sideband push-to-talk voice message carries its Opus/Codec2 payload in
# `FIELD_AUDIO` and an empty content; surface it as a normalized `audio` dict
# so a front end can transcribe it without knowing the wire shape.
audio = None
if FIELD_AUDIO in fields:
audio = parse_audio_field(fields.get(FIELD_AUDIO))
return {
"source_hash": source_hash,
"display_name": display_name or None,
"title": title,
"content": content,
"timestamp": getattr(message, "timestamp", None),
"fields": fields,
"audio": audio,
"raw": message,
}
@@ -138,7 +235,11 @@ class LxmfDaemon:
self._reticulum = None
self._destination = None
self._address = ""
self._outbound: "queue.Queue[tuple[str, str] | None]" = queue.Queue()
#: Outbound items are `(chat_id, text, audio)`; `audio` is an OGG/Opus
#: container for a Sideband HQ push-to-talk voice reply, else None.
self._outbound: "queue.Queue[tuple[str, str, bytes | None] | None]" = (
queue.Queue()
)
self._stop = threading.Event()
self._on_message: MessageHandler | None = None
@@ -237,12 +338,19 @@ class LxmfDaemon:
while not self._stop.wait(self._announce_wait()):
self._announce()
def enqueue(self, chat_id: str | None, text: str = "") -> None:
"""Queue an outbound send. `chat_id=None` is the stop sentinel."""
def enqueue(
self, chat_id: str | None, text: str = "", audio: bytes | None = None
) -> None:
"""Queue an outbound send. `chat_id=None` is the stop sentinel.
`audio` is an OGG/Opus container: it rides the LXMF `FIELD_AUDIO` field
(a Sideband HQ push-to-talk voice reply) with `text` as the message
content, so a text-only client still sees the reply.
"""
if chat_id is None:
self._outbound.put(None)
else:
self._outbound.put((str(chat_id), text))
self._outbound.put((str(chat_id), text, audio))
def close(self) -> None:
self._stop.set()
@@ -309,17 +417,27 @@ class LxmfDaemon:
item = self._outbound.get()
if item is None:
return
chat_id, text = item
chat_id, text, audio = item
try:
self.send(chat_id, text)
self.send(chat_id, text, audio=audio)
except Exception as exc:
self._event(
"lxmf_send_failed", contact=chat_id, message=str(exc)[:300]
)
def send(self, destination_hex: str, text: str, timeout: float = 15.0) -> None:
def send(
self,
destination_hex: str,
text: str,
audio: bytes | None = None,
timeout: float = 15.0,
) -> None:
"""Send `text` to an LXMF address (destination hash hex).
When `audio` (an OGG/Opus container) is given it is attached in the
LXMF `FIELD_AUDIO` field as a Sideband HQ push-to-talk voice message
(`[AM_OPUS_OGG, audio]`), with `text` as the message content.
Recalls the peer identity from the network; when the path is not yet
known it requests it and waits briefly. Raises (never silently drops)
when the destination cannot be resolved — a reply must be real.
@@ -351,9 +469,14 @@ class LxmfDaemon:
if self.desired_method == "opportunistic"
else LXMF.LXMessage.DIRECT
)
message = LXMF.LXMessage(dest, self._destination, text, desired_method=method)
fields = audio_fields(audio)
message = LXMF.LXMessage(
dest, self._destination, text, desired_method=method, fields=fields
)
self._router.handle_outbound(message)
self._event("lxmf_sent", contact=destination_hex, chars=len(text))
self._event(
"lxmf_sent", contact=destination_hex, chars=len(text), audio=bool(audio)
)
# ---- tracing ----
+62
View File
@@ -99,6 +99,13 @@ class Answers:
# Gateway platforms to enable.
gateways: list[str] = field(default_factory=list)
# LXMF gateway: transcribe Sideband push-to-talk voice messages into
# commands (install `requirements/transcribe.txt`; faster-whisper only) and
# reply to a voice chat with a Piper voice message (install
# `requirements/tts.txt`; piper-tts + PyAV).
lxmf_voice: bool = False
lxmf_voice_reply: bool = True
# IANA timezone; empty uses the host zone.
timezone: str = ""
@@ -462,6 +469,29 @@ def run_interview(
default=answers.gateways,
)
# 5b. LXMF voice messages (Sideband push-to-talk).
if "lxmf" in answers.gateways:
output("")
output("LXMF voice messages")
output(
" Sideband can send push-to-talk voice messages. The agent can\n"
" transcribe them into commands, and reply to a voice chat with a\n"
" synthesized voice message (Piper)."
)
mode = _ask_choice(
input_fn,
output,
"lxmf voice",
[
("off", "ignore voice messages"),
("transcribe", "transcribe to commands, reply with text"),
("reply", "transcribe, and reply with a synthesized voice"),
],
3,
)
answers.lxmf_voice = mode in ("transcribe", "reply")
answers.lxmf_voice_reply = mode == "reply"
# 6. Timezone.
output("")
answers.timezone = _ask_text(
@@ -568,6 +598,12 @@ def build_config(answers: Answers, packs: Sequence[SkillPack]) -> dict:
for platform in ("simplex", "lxmf", "voice"):
gateway.setdefault(platform, {})["enabled"] = platform in answers.gateways
gateway.setdefault("humanize", {})["enabled"] = bool(answers.gateways)
# Sideband voice messages are transcribed only when the LXMF gateway is on
# and the answer opted in; needs faster-whisper (requirements/transcribe.txt).
# A voice reply adds Piper + PyAV (requirements/tts.txt).
voice_block = gateway.setdefault("lxmf", {}).setdefault("voice", {})
voice_block["enabled"] = bool("lxmf" in answers.gateways and answers.lxmf_voice)
voice_block["reply_with_voice"] = bool(answers.lxmf_voice_reply)
return config
@@ -632,6 +668,17 @@ def build_plan(answers: Answers, packs: Sequence[SkillPack]) -> dict:
"install_simplex_forward": "simplex" in answers.packs,
"install_browser": "browser" in answers.packs,
"install_voice": "voice" in answers.gateways,
# faster-whisper only (no microphone stack): transcribe Sideband voice
# messages when the LXMF gateway is on and the answer opted in.
"install_transcribe": "lxmf" in answers.gateways and bool(answers.lxmf_voice),
# Piper + PyAV (no microphone stack): reply to a voice chat with a
# synthesized voice message when the LXMF gateway handles voice and the
# answer wants voice replies.
"install_lxmf_tts": (
"lxmf" in answers.gateways
and bool(answers.lxmf_voice)
and bool(answers.lxmf_voice_reply)
),
}
@@ -665,6 +712,21 @@ def plan_from_config(config: dict, packs: Sequence[SkillPack]) -> dict:
"install_simplex_forward": "simplex" in enabled,
"install_browser": "browser" in enabled,
"install_voice": "voice" in gateways,
"install_transcribe": bool(
(((config.get("gateway", {}) or {}).get("lxmf", {}) or {})
.get("voice", {}) or {})
.get("enabled")
),
"install_lxmf_tts": bool(
(((config.get("gateway", {}) or {}).get("lxmf", {}) or {})
.get("voice", {}) or {})
.get("enabled")
)
and bool(
(((config.get("gateway", {}) or {}).get("lxmf", {}) or {})
.get("voice", {}) or {})
.get("reply_with_voice", True)
),
}
+275 -19
View File
@@ -48,6 +48,28 @@ _REQUIRED_MODULES: tuple[tuple[str, str], ...] = (
("onnxruntime", "onnxruntime"),
)
#: The one package a transcribe-only front end needs (see
#: `check_transcription_requirements`). `faster-whisper` bundles PyAV, whose
#: ffmpeg decodes an incoming Opus/OGG voice message to PCM.
_TRANSCRIBE_MODULES: tuple[tuple[str, str], ...] = (
("faster_whisper", "faster-whisper"),
)
#: The packages a voice-reply front end needs (see
#: `check_synthesis_requirements`): Piper for text-to-speech and PyAV for the
#: Opus/OGG container a Sideband HQ push-to-talk reply rides in. No microphone,
#: wake word, or transcription is implied — a headless host can synthesize a
#: reply without the hardware voice stack.
_SYNTHESIS_MODULES: tuple[tuple[str, str], ...] = (
("piper", "piper-tts"),
("av", "av (PyAV, Opus/OGG encoding)"),
)
#: Sideband's HQ push-to-talk container (`LXMF.AM_OPUS_OGG`) is 48 kHz mono
#: OGG/Opus; a reply's PCM is resampled to that rate before encoding.
OPUS_OGG_SAMPLE_RATE = 48000
OPUS_OGG_BITRATE = 24000
# --------------------------------------------------------------------------- #
# Engine interfaces (fakes are injected in tests)
@@ -83,6 +105,15 @@ class Transcriber:
def transcribe(self, pcm16: bytes) -> str:
raise NotImplementedError
def transcribe_bytes(self, data: bytes) -> str:
"""Transcribe an encoded audio container (e.g. OGG/Opus) to text.
Default: not supported. `WhisperTranscriber` overrides it so a received
voice message (a Sideband PTT Opus/OGG payload) is transcribed without a
separate decode step.
"""
raise NotImplementedError
def close(self) -> None:
pass
@@ -236,6 +267,10 @@ class WhisperTranscriber(Transcriber):
self._model = WhisperModel(str(model or "base.en"), device=str(device or "cpu"),
compute_type=str(compute_type or "int8"))
@staticmethod
def _join(segments) -> str:
return " ".join(segment.text.strip() for segment in segments).strip()
def transcribe(self, pcm16: bytes) -> str:
import numpy as np
@@ -246,7 +281,25 @@ class WhisperTranscriber(Transcriber):
beam_size=self.beam_size,
vad_filter=self.vad_filter,
)
return " ".join(segment.text.strip() for segment in segments).strip()
return self._join(segments)
def transcribe_bytes(self, data: bytes) -> str:
"""Transcribe an encoded audio container (e.g. OGG/Opus).
faster-whisper decodes the container to 16 kHz mono internally via PyAV
(its own bundled ffmpeg), so a PTT voice message's Opus/OGG payload is
transcribed directly — no separate decode step and no system ffmpeg.
`data` is the raw container bytes.
"""
import io
segments, _info = self._model.transcribe(
io.BytesIO(bytes(data)),
language=self.language,
beam_size=self.beam_size,
vad_filter=self.vad_filter,
)
return self._join(segments)
class PiperSynthesizer(Synthesizer):
@@ -572,10 +625,228 @@ def _build_vad(cfg: dict) -> VadGate:
return EnergyVadGate(threshold=float(vad_cfg.get("energy_threshold", 200.0)))
def build_transcriber(cfg: dict) -> Transcriber:
"""Build just the speech-to-text engine from an `stt` config block.
`build_engines` also needs a microphone, a wake word, and TTS; a headless
front end that only transcribes received audio — the LXMF gateway handling a
Sideband PTT voice message — uses this instead, so it needs only
`faster-whisper` and none of the hardware voice stack.
"""
stt_cfg = (cfg or {}).get("stt", {}) or {}
return 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"),
)
def check_transcription_requirements() -> tuple[bool, str | None]:
"""Return `(ok, install_hint)` for the transcribe-only path.
Unlike `VoiceDaemon.check_requirements` this needs no microphone, wake word,
or TTS — only `faster-whisper` — so a headless host can transcribe incoming
voice messages without the hardware voice stack. Never raises.
"""
missing = []
for module, hint in _TRANSCRIBE_MODULES:
try:
importlib.import_module(module)
except Exception:
missing.append(hint)
if missing:
return False, (
"install the transcription stack (requirements/transcribe.txt): "
+ "; ".join(missing)
)
return True, None
def check_synthesis_requirements() -> tuple[bool, str | None]:
"""Return `(ok, install_hint)` for the voice-reply (Piper) path.
A voice reply needs Piper (text-to-speech) and PyAV (to encode the
synthesized PCM into the Opus/OGG container a Sideband HQ push-to-talk
message rides in). Neither a microphone, a wake word, nor transcription is
implied — the headless counterpart of `VoiceDaemon.check_requirements`.
Never raises.
"""
missing = []
for module, hint in _SYNTHESIS_MODULES:
try:
importlib.import_module(module)
except Exception:
missing.append(hint)
if missing:
return False, (
"install the voice-reply stack (requirements/tts.txt): "
+ "; ".join(missing)
)
return True, None
def pcm_to_opus_ogg(
pcm16: bytes, sample_rate: int, bitrate: int = OPUS_OGG_BITRATE
) -> bytes:
"""Encode 16-bit mono PCM into an OGG/Opus container (Sideband HQ PTT).
A received voice message is Opus/OGG (`LXMF.AM_OPUS_OGG`), so a voice reply
is encoded to the same container: the PCM is resampled to 48 kHz (Opus's
fullband rate) with PyAV's `AudioResampler` and muxed into OGG by its
bundled libopus. Returns `b""` on any failure (the caller falls back to a
text reply) — never raises, so a missing PyAV degrades gracefully.
"""
if not pcm16 or len(pcm16) < BYTES_PER_SAMPLE:
return b""
try:
import av
except Exception:
return b""
try:
rate = int(sample_rate or OPUS_OGG_SAMPLE_RATE)
source = av.AudioFrame(
format="s16", layout="mono", samples=len(pcm16) // BYTES_PER_SAMPLE
)
source.sample_rate = rate
source.planes[0].update(pcm16)
if rate == OPUS_OGG_SAMPLE_RATE:
frames = [source]
else:
resampler = av.AudioResampler(
format="s16", layout="mono", rate=OPUS_OGG_SAMPLE_RATE
)
# PyAV's `resample` returns a list of frames (older versions a single
# frame or None); normalize both shapes.
frames = resampler.resample(source)
if not isinstance(frames, list):
frames = [frames]
tail = resampler.resample(None)
frames += tail if isinstance(tail, list) else [tail]
frames = [frame for frame in frames if frame is not None]
if not frames:
return b""
buffer = io.BytesIO()
container = av.open(buffer, mode="w", format="ogg")
stream = container.add_stream("libopus", rate=OPUS_OGG_SAMPLE_RATE)
stream.layout = "mono"
stream.bit_rate = int(bitrate or OPUS_OGG_BITRATE)
try: # voice-optimised mode (Sideband's HQ PTT uses the voice profile)
stream.codec_context.options = {"application": "voip"}
except Exception:
pass
for frame in frames:
for packet in stream.encode(frame):
container.mux(packet)
for packet in stream.encode(None):
container.mux(packet)
container.close()
return buffer.getvalue()
except Exception:
return b""
def check_codec2_requirements() -> tuple[bool, str | None]:
"""Return `(ok, install_hint)` for Codec2 voice-message decoding.
Codec2 (Sideband's non-HQ push-to-talk) needs the optional `pycodec2`
bindings, which compile against the system `libcodec2`. Never raises.
"""
try:
importlib.import_module("pycodec2")
except Exception:
return False, (
"pip install pycodec2 (needs the system libcodec2: "
"apt install libcodec2-dev)"
)
return True, None
def decode_codec2(data: bytes, rate: int) -> bytes | None:
"""Decode a raw Codec2 bitstream to 8 kHz mono int16 PCM.
`rate` is the codec2 bitrate in bits/s (700..3200). Returns None when the
optional `pycodec2` bindings (or the mode) are unavailable, so the caller
reports the message unsupported rather than guessing. Frames shorter than a
full codec frame are dropped; decoding mirrors Sideband's per-frame loop.
"""
if not data or not rate:
return None
try:
import pycodec2
except Exception:
return None
try:
codec = pycodec2.Codec2(int(rate))
bytes_per_frame = int(codec.bytes_per_frame())
except Exception:
return None
if bytes_per_frame <= 0:
return None
try:
import numpy as np
except Exception:
return None
frames = [
np.asarray(codec.decode(data[offset : offset + bytes_per_frame]), dtype=np.int16)
for offset in range(0, len(data) - bytes_per_frame + 1, bytes_per_frame)
]
if not frames:
return None
return np.concatenate(frames).astype(np.int16).tobytes()
def pcm_to_wav(pcm16: bytes, sample_rate: int, channels: int = 1) -> bytes:
"""Wrap raw int16 PCM in a minimal in-memory WAV container (stdlib).
Lets a non-container payload (Codec2 frames decoded to 8 kHz PCM) ride the
same transcription path as an Opus/OGG message: faster-whisper's PyAV decodes
the WAV and resamples it to 16 kHz, so the boundary needs no manual resample.
"""
import io
import wave
buffer = io.BytesIO()
with wave.open(buffer, "wb") as wav:
wav.setnchannels(int(channels))
wav.setsampwidth(2)
wav.setframerate(int(sample_rate))
wav.writeframes(pcm16)
return buffer.getvalue()
def _build_piper(tts_cfg: dict) -> PiperSynthesizer:
"""Build the Piper synthesizer from a `tts` config block (shared by the
microphone front end and the headless LXMF voice-reply path)."""
tts_voice = resolve_model_path(
str(tts_cfg.get("voice", "") or ""),
str(tts_cfg.get("voice_dir", "") or ""),
(".onnx",),
)
return 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),
)
def build_synthesizer(cfg: dict) -> Synthesizer:
"""Build just the text-to-speech engine from a `tts` config block.
`build_engines` also needs a microphone, a wake word, and speech-to-text; a
headless front end that only synthesizes a reply — the LXMF gateway
answering a Sideband push-to-talk voice message with a Piper voice message —
uses this instead, so it needs only `piper-tts` (and PyAV to encode the
reply), none of the hardware voice stack.
"""
tts_cfg = (cfg or {}).get("tts", {}) or {}
return _build_piper(tts_cfg)
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 {}
@@ -584,11 +855,6 @@ def build_engines(cfg: dict, trace=None) -> VoiceEngines:
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,
@@ -596,18 +862,8 @@ def build_engines(cfg: dict, trace=None) -> VoiceEngines:
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),
),
stt=build_transcriber(cfg),
tts=_build_piper(tts_cfg),
audio=SoundDeviceAudio(
input_device=str(audio_cfg.get("input_device", "") or ""),
output_device=str(audio_cfg.get("output_device", "") or ""),