read-aloud: stream a long text over the voice gateways

A skill that resolves a long text (a book) can hand it to the scheduler's
speech channel and return immediately; the gateway that owns the chat drains it
and streams it with text-to-speech until the user stops it.

- semif_agent/speech.py: SpeechService + ReadAloud. A bounded queue a front end
  drains, plus a per-source streaming predicate (set_stream_check/supports) so a
  skill asks before it posts one. Neutral and stdlib-only.
- semif_agent/reading.py: the bookmarks.json beside the saved books (load/save/
  read a key -> last offset, atomic write) and a deterministic speakable
  chunker at paragraph/sentence boundaries.
- Scheduler owns the channel (scheduler.speech); SkillRunner passes it into
  every run's ActionContext, so a body reaches it as ctx.speech.
- gateway/service: registers stream_ready as the channel's capability
  predicate, and surface() routes a drained read to the platform that owns the
  run (a non-streaming adapter is traced and skipped, never handed a message it
  would drop).
- gateway/voice: streams the saved text through the daemon's Piper voice chunk
  by chunk, writing the bookmark before each chunk; a barge-in "stop" or any new
  command ends it.
- gateway/lxmf: a read goes to a chat that last messaged by voice as a sequence
  of Sideband HQ voice messages (Piper -> Opus/OGG, backpressure so a stop is
  prompt), with the same bookmark-per-chunk resume; a "stop" message or any new
  command interrupts it.
- A run that registers a read is terminal (read_aloud_terminal): the read is the
  answer, so assess:outcome must not re-dispatch the request (which otherwise
  authored a spurious skill).
- config.example.json regenerated with the new voice/lxmf read blocks.
This commit is contained in:
gabby committed 2026-10-17 23:29:53 +00:00
1 parent faebe8a53a
commit 894a85ec2d
18 files changed
+1478 -53

No files matched your search

+59 -1
View File
@@ -35,16 +35,74 @@ class InboundMessage:
@dataclass
class OutboundMessage:
"""One reply destined for an external chat."""
"""One reply destined for an external chat.
`text` is the reply. `stream` optionally carries a long-form read-aloud
request (a `semif_agent.speech.ReadAloud`) instead of a plain line: the
voice front end streams it chunk-by-chunk with text-to-speech until the user
stops it. A platform that does not stream leaves it None and speaks `text`.
"""
chat_id: str
text: str
stream: Any = None
#: Callback the adapter invokes for each authorized inbound message.
InboundHandler = Callable[[InboundMessage], None]
#: Words/phrases that abort a long-form read-aloud (and a spoken reply) when
#: heard/typed. The match is on the whole normalized utterance (so "stop the
#: timer" stays a real command) with a first-word fallback only for a short
#: utterance with trailing filler ("stop please", "cancel that"). Shared by the
#: voice and LXMF adapters, which both stream read-aloud text.
_STOP_PHRASES = {
"stop",
"stop it",
"stop talking",
"stop please",
"cancel",
"cancel that",
"cancel please",
"quiet",
"quiet down",
"be quiet",
"silence",
"hush",
"shut up",
"never mind",
"nevermind",
"enough",
}
_STOP_FIRST_WORDS = {"stop", "cancel", "quiet", "silence", "hush", "shut", "enough"}
_STOP_FILLER = {"please", "now", "it", "that", "talking", "down", "up", "already"}
#: Characters stripped from a spoken utterance's edges before matching.
_STOP_PUNCT = " \t\r\n.,!?;:\"'()[]{}"
def is_stop_command(text: str) -> bool:
"""Whether an utterance means "stop talking" (vs a new command).
Deterministic vocabulary, no model: a bare "stop"/"cancel" (or a short
variant like "stop please") aborts a spoken reply / long-form read. Anything
longer is a real command and is submitted as a new request.
"""
cleaned = (text or "").strip().lower().strip(_STOP_PUNCT)
if not cleaned:
return False
if cleaned in _STOP_PHRASES:
return True
words = cleaned.split()
if len(words) > 3:
return False
first = words[0].strip(_STOP_PUNCT)
if first not in _STOP_FIRST_WORDS:
return False
return all(word.strip(_STOP_PUNCT) in _STOP_FILLER for word in words[1:])
class GatewayAdapter(ABC):
"""Transport contract for a messenger platform."""
+145 -1
View File
@@ -44,8 +44,10 @@ from __future__ import annotations
import os
import queue
import threading
import time
from semif_agent.lxmf_transport import LxmfDaemon
from semif_agent.reading import DEFAULT_CHUNK_CHARS, chunk_text, save_bookmark
from semif_agent.voice_transport import (
OPUS_OGG_BITRATE,
build_synthesizer,
@@ -58,7 +60,7 @@ from semif_agent.voice_transport import (
pcm_to_wav,
)
from .base import GatewayAdapter, InboundMessage, OutboundMessage
from .base import GatewayAdapter, InboundMessage, OutboundMessage, is_stop_command
#: 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.
@@ -141,6 +143,38 @@ class LxmfAdapter(GatewayAdapter):
self._timers: dict[str, threading.Timer] = {}
self._lock = threading.Lock()
self._on_inbound = None
#: Read-aloud: a book is streamed to a voice chat as a sequence of
#: voice messages, one Piper-synthesized chunk each, until the user
#: sends "stop" or a new command. Only a voice chat can receive it, so
#: a text chat keeps the skill's saved-file summary.
read_cfg = self.voice_cfg.get("read", {}) or {}
self._read_enabled = bool(read_cfg.get("enabled", True))
self._read_chunk_chars = max(
1, int(read_cfg.get("chunk_chars", DEFAULT_CHUNK_CHARS) or DEFAULT_CHUNK_CHARS)
)
#: How many messages may be queued on the daemon ahead of the stream
#: (backpressure so a stop is prompt).
self._read_max_lead = max(1, int(read_cfg.get("max_lead", 4) or 4))
self._read_lock = threading.Lock()
self._read_stop = threading.Event()
self._read_key: str | None = None
self._read_chat: str | None = None
@property
def supports_speech_stream(self) -> bool:
"""Whether this adapter can deliver a read-aloud at all.
Only when voice replies are on: a read-aloud is sent as voice messages.
Whether a *particular* chat can receive one is `speech_stream_ready`.
"""
return bool(self.voice_enabled and self.reply_with_voice and self._read_enabled)
def speech_stream_ready(self, chat: str) -> bool:
"""Whether `chat` should get a read-aloud (it last messaged by voice)."""
if not self.supports_speech_stream:
return False
with self._lock:
return str(chat) in self._voice_chats
# ---- requirements ----
@@ -182,6 +216,15 @@ class LxmfAdapter(GatewayAdapter):
if message is None:
self.daemon.enqueue(None)
return
if message.stream is not None:
try:
self._stream(message.stream)
except Exception as exc:
# A read failure must never kill the outbound pump.
self.daemon._event(
"lxmf_read_failed", message=str(exc)[:300]
)
continue
audio = self._voice_reply(message)
self.daemon.enqueue(message.chat_id, message.text, audio=audio)
@@ -252,6 +295,14 @@ class LxmfAdapter(GatewayAdapter):
"""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")
# Any command interrupts a read-aloud playing to this chat; a bare
# "stop"/"cancel" is not submitted as a request.
if self._stop_read_for_command(source_hash):
self.daemon._event(
"lxmf_read_stopped", contact_id=source_hash, chars=len(text)
)
if is_stop_command(text):
return
self.daemon._event(
"gateway_message",
contact_id=source_hash,
@@ -488,3 +539,96 @@ class LxmfAdapter(GatewayAdapter):
self.daemon._event("lxmf_voice_tts_unavailable", message=str(exc)[:300])
return None
return self._synthesizer
# ---- read-aloud (a book streamed as voice messages) ----
def _stop_read_for_command(self, chat: str) -> bool:
"""Stop a read-aloud playing to `chat`; report whether one was active."""
with self._read_lock:
if self._read_key is None or self._read_chat != str(chat):
return False
self._read_stop.set()
return True
def _synthesize_chunk(self, text: str) -> bytes | None:
"""Piper-synthesize one chunk to Opus/OGG, or None (send it as text)."""
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:
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
return audio
def _stream(self, read) -> None:
"""Stream a read-aloud request as a sequence of voice messages.
Runs on the outbound pump thread: each chunk is synthesized and queued
to the daemon, and the bookmark is written before it is sent so a stop
leaves the position at the interrupted chunk. The read ends when the
text is finished or the user interrupts (a stop flag set by `_deliver`).
"""
chat = str(read.source or "").split(":", 1)[-1]
with self._read_lock:
self._read_stop.set() # supersede any prior read
stop = threading.Event()
self._read_stop = stop
self._read_key = read.key
self._read_chat = chat
try:
if not chat or not self.speech_stream_ready(chat):
return
try:
with open(read.path, "r", encoding="utf-8", errors="replace") as handle:
text = handle.read()
except OSError as exc:
self.daemon._event(
"lxmf_read_failed", contact_id=chat, message=str(exc)[:200]
)
return
chunk_chars = min(
self._read_chunk_chars,
max(1, int(read.chunk_chars or self._read_chunk_chars)),
)
if self.voice_max_chars > 0:
chunk_chars = min(chunk_chars, self.voice_max_chars)
self.daemon._event(
"lxmf_read_start",
contact_id=chat,
key=read.key,
start=read.start,
chars=len(text),
)
sent = 0
for offset, chunk in chunk_text(text, read.start, chunk_chars):
# Keep only a few messages queued ahead so a stop takes effect
# promptly instead of after a large backlog drains.
while not stop.is_set() and self.daemon.pending_sends() >= self._read_max_lead:
time.sleep(0.05)
if stop.is_set():
break
save_bookmark(read.bookmarks_path, read.key, offset, read.title)
self.daemon.enqueue(chat, chunk, audio=self._synthesize_chunk(chunk))
sent += 1
if stop.is_set():
self.daemon._event(
"lxmf_read_interrupted", contact_id=chat, key=read.key, chunks=sent
)
else:
save_bookmark(read.bookmarks_path, read.key, len(text), read.title)
self.daemon._event(
"lxmf_read_done", contact_id=chat, key=read.key, chunks=sent
)
finally:
with self._read_lock:
if self._read_stop is stop:
self._read_key = None
self._read_chat = None
+66
View File
@@ -179,6 +179,13 @@ class GatewayService:
setter = getattr(adapter, "set_input_ready", None)
if callable(setter):
setter(self.input_ready)
#: Tell the scheduler's speech channel which sources this service can
#: stream a read-aloud to, so a skill asks before it posts one.
speech = getattr(self.scheduler, "speech", None)
if speech is not None:
setter = getattr(speech, "set_stream_check", None)
if callable(setter):
setter(self.stream_ready)
self._owners: dict[str, Target] = {}
self._parents: dict[str, str] = {}
self._pending_owner: Target | None = None
@@ -342,6 +349,29 @@ class GatewayService:
return True
return getattr(scheduler, "current", None) is None
def stream_ready(self, source: str) -> bool:
"""Whether this service can stream a read-aloud to `source`.
The owning platform's adapter decides: the voice gateway always can
(when `read.enabled`); the LXMF adapter only for a chat that last
messaged by voice (a text chat keeps the saved-file summary). A source
with no known owner is not streamed.
"""
target = self._owner_from_source(source)
if target is None:
return False
platform, chat = target
adapter = self.adapters.get(platform)
if adapter is None:
return False
check = getattr(adapter, "speech_stream_ready", None)
if callable(check):
try:
return bool(check(chat))
except Exception:
return False
return bool(getattr(adapter, "supports_speech_stream", False))
def handle_inbound(self, msg: InboundMessage, platform: str | None = None) -> None:
"""Handle one authorized inbound command. Called by the adapter."""
if platform is None:
@@ -519,6 +549,16 @@ class GatewayService:
if target:
self._reply(*target, fired.message, kind="notice")
# Long-form read-aloud requests a skill posted for a voice front end:
# route each to the platform that owns the run. Only a streaming adapter
# (the voice gateway) can deliver one; others are traced and skipped.
speech = getattr(self.scheduler, "speech", None)
if speech is not None:
for read in speech.drain():
target = self._resolve_target(read.run_id, origin)
if target:
self._enqueue_stream(target, read)
# ---- scheduler requeue hook (called under the scheduler lock) ----
def on_request_requeued(self, parent_id: str, child_id: str) -> None:
@@ -593,3 +633,29 @@ class GatewayService:
return
self._trace("gateway_reply_queued", reply_kind=kind, chars=len(text))
target_queue.put(OutboundMessage(chat_id=str(chat_id), text=text))
def _enqueue_stream(self, target: Target, read) -> None:
"""Queue a read-aloud stream for the platform that can stream it.
Only an adapter that declares `supports_speech_stream` (the voice
gateway) can speak a long-form stream; a platform that cannot is traced
and skipped rather than handed a message it would drop silently.
"""
platform, chat_id = target
adapter = self.adapters.get(platform)
if adapter is None or not getattr(adapter, "supports_speech_stream", False):
self._trace(
"gateway_stream_unsupported",
platform=platform,
key=getattr(read, "key", ""),
)
return
self._trace(
"gateway_stream_queued",
platform=platform,
key=getattr(read, "key", ""),
start=getattr(read, "start", 0),
)
self.outbound[platform].put(
OutboundMessage(chat_id=str(chat_id), text="", stream=read)
)
+129 -50
View File
@@ -23,58 +23,14 @@ from __future__ import annotations
import queue
import threading
from semif_agent.reading import DEFAULT_CHUNK_CHARS, chunk_text, save_bookmark
from semif_agent.voice_transport import VoiceDaemon
from .base import GatewayAdapter, InboundMessage, OutboundMessage
from .base import GatewayAdapter, InboundMessage, OutboundMessage, is_stop_command
#: Words/phrases that abort a spoken reply when heard after a barge-in. The
#: match is on the whole normalized utterance (so "stop the timer" stays a real
#: command) with a first-word fallback only for a short utterance with trailing
#: filler ("stop please", "cancel that").
_STOP_PHRASES = {
"stop",
"stop it",
"stop talking",
"stop please",
"cancel",
"cancel that",
"cancel please",
"quiet",
"quiet down",
"be quiet",
"silence",
"hush",
"shut up",
"never mind",
"nevermind",
"enough",
}
_STOP_FIRST_WORDS = {"stop", "cancel", "quiet", "silence", "hush", "shut", "enough"}
_STOP_FILLER = {"please", "now", "it", "that", "talking", "down", "up", "already"}
#: Characters stripped from a spoken utterance's edges before matching.
_PUNCT = " \t\r\n.,!?;:\"'()[]{}"
def _is_stop_command(text: str) -> bool:
"""Whether an interrupt utterance means "stop talking" (vs a new command).
Deterministic vocabulary, no model: a bare "stop"/"cancel" (or a short
variant like "stop please") aborts the spoken reply. Anything longer is a
real command and is submitted as a new request.
"""
cleaned = (text or "").strip().lower().strip(_PUNCT)
if not cleaned:
return False
if cleaned in _STOP_PHRASES:
return True
words = cleaned.split()
if len(words) > 3:
return False
first = words[0].strip(_PUNCT)
if first not in _STOP_FIRST_WORDS:
return False
return all(word.strip(_PUNCT) in _STOP_FILLER for word in words[1:])
#: The stop vocabulary lives in `gateway.base` (shared with the LXMF adapter,
#: which also streams read-aloud text). Kept under the old name for callers.
_is_stop_command = is_stop_command
class VoiceAdapter(GatewayAdapter):
@@ -103,6 +59,22 @@ class VoiceAdapter(GatewayAdapter):
#: The outbound reply queue (set in `run`), so a "stop" can drop replies
#: that were already queued behind the interrupted one.
self._outbound: "queue.Queue[OutboundMessage | None] | None" = None
#: Long-form read-aloud: the adapter streams a saved text through the
#: daemon's Piper voice one chunk at a time, and any inbound command
#: interrupts it. `read.enabled` (default on) gates the whole path;
#: `read.chunk_chars` bounds one spoken chunk (clamped to the speakable
#: budget so a chunk is never truncated).
read_cfg = cfg.get("read", {}) or {}
self.supports_speech_stream = bool(read_cfg.get("enabled", True))
self._read_chunk_chars = max(
1, int(read_cfg.get("chunk_chars", DEFAULT_CHUNK_CHARS) or DEFAULT_CHUNK_CHARS)
)
self._read_lock = threading.Lock()
#: Set to ask the active read to stop; swapped per read so a stale read
#: never observes a new read's stop signal.
self._read_stop = threading.Event()
#: The bookmark key of the active read (None when nothing is being read).
self._read_key: str | None = None
# ---- requirements ----
@@ -131,12 +103,23 @@ class VoiceAdapter(GatewayAdapter):
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.
# blocks (it plays audio), so this runs off the listening thread. A
# read-aloud stream blocks here for as long as the user listens.
while True:
message = outbound.get()
if message is None:
self.daemon.stop()
return
if message.stream is not None:
try:
self._stream(message.stream)
except Exception as exc:
# A read failure must never kill the outbound pump (and
# with it the front end).
self.daemon._event(
"gateway_read_failed", message=str(exc)[:300]
)
continue
self.daemon._event("gateway_reply_dequeued", chars=len(message.text))
self.daemon.speak(message.text)
@@ -169,6 +152,11 @@ class VoiceAdapter(GatewayAdapter):
self._handle(message)
def _handle(self, message: InboundMessage) -> None:
# Any inbound command interrupts an in-progress read-aloud: the user
# either said "stop" or wants to do something else. The bookmark already
# points at the chunk that was interrupted, so a later request resumes
# there.
was_reading = self._stop_read_for_command(message)
if message.raw.get("barge_in"):
if _is_stop_command(message.text):
# A "stop"/"cancel" after a barge-in aborts the spoken reply and
@@ -190,6 +178,12 @@ class VoiceAdapter(GatewayAdapter):
finally:
self.daemon.set_muted(False)
return
if was_reading and _is_stop_command(message.text):
# A bare "stop" heard between chunks (not a barge-in) stops the
# reading and is not submitted as a request.
self.daemon._event("gateway_read_stopped", chars=len(message.text))
self._drop_pending_speech()
return
if self._on_inbound is None:
return
try:
@@ -198,6 +192,91 @@ class VoiceAdapter(GatewayAdapter):
self.daemon._event("gateway_handler_failed", message=str(exc)[:300])
self.daemon.speak("Sorry, something went wrong handling that.")
# ---- read-aloud (long-form streaming) ----
def _read_active(self) -> bool:
with self._read_lock:
return self._read_key is not None
def _stop_read_for_command(self, message: InboundMessage) -> bool:
"""Stop an active read when a command arrives; report whether one was."""
if not self._read_active():
return False
reason = "barge_in" if message.raw.get("barge_in") else "new_command"
self._stop_reading(reason)
return True
def _stop_reading(self, reason: str) -> None:
"""Ask the active read to stop at the next chunk boundary.
The bookmark was already written for the chunk being spoken, so the
position is correct without any extra bookkeeping here.
"""
with self._read_lock:
if self._read_key is None:
return
key = self._read_key
self._read_stop.set()
self.daemon._event("gateway_read_stop", key=key, reason=reason)
def _stream(self, read) -> None:
"""Stream a read-aloud request through the daemon's Piper voice.
Chunks are spoken one at a time; the bookmark is written before each
chunk so a stop (or a crash) leaves the position at the interrupted
chunk. The read ends when the text is finished or the user interrupts
(a stop flag set by `_handle`, or a barge-in muting playback).
"""
with self._read_lock:
self._read_stop.set() # supersede any prior read
stop = threading.Event()
self._read_stop = stop
self._read_key = read.key
try:
try:
with open(read.path, "r", encoding="utf-8", errors="replace") as handle:
text = handle.read()
except OSError as exc:
self.daemon._event(
"gateway_read_failed", key=read.key, message=str(exc)[:200]
)
return
chunk_chars = min(
self._read_chunk_chars,
max(1, int(read.chunk_chars or self._read_chunk_chars)),
)
# Never exceed the daemon's speakable budget, or a chunk would be
# truncated and text would be lost.
speak_limit = int(getattr(self.daemon, "max_speak_chars", 0) or 0)
if speak_limit > 0:
chunk_chars = min(chunk_chars, speak_limit)
self.daemon._event(
"gateway_read_start", key=read.key, start=read.start, chars=len(text)
)
spoken = 0
for offset, chunk in chunk_text(text, read.start, chunk_chars):
if stop.is_set() or self.daemon.stopping():
break
save_bookmark(read.bookmarks_path, read.key, offset, read.title)
self.daemon.speak(chunk)
spoken += 1
# A barge-in mutes playback synchronously on the audio thread;
# break promptly so we do not skip through suppressed chunks
# before the transcribed "stop" reaches `_handle`.
if stop.is_set() or self.daemon.muted():
break
if stop.is_set() or self.daemon.stopping():
self.daemon._event("gateway_read_interrupted", key=read.key, chunks=spoken)
else:
# Finished: park the bookmark at the end so a later request
# starts over rather than replaying the final chunk.
save_bookmark(read.bookmarks_path, read.key, len(text), read.title)
self.daemon._event("gateway_read_done", key=read.key, chunks=spoken)
finally:
with self._read_lock:
if self._read_stop is stop:
self._read_key = None
def _drop_pending_speech(self) -> None:
"""Discard replies already queued behind an interrupted one.