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:
1 parent
faebe8a53a
commit
894a85ec2d
18 files changed
+1478
-53
No files matched your search
@@ -894,6 +894,230 @@ def test_lxmf_voice_reply_bounds_length(monkeypatch):
|
||||
assert len(synth.calls[0]) <= 10
|
||||
|
||||
|
||||
# ---- LXMF read-aloud (a book streamed as voice messages) -------------------
|
||||
|
||||
def _read_aloud(chat, path, bookmarks, start=0, key="k", title="T"):
|
||||
from semif_agent.speech import ReadAloud
|
||||
|
||||
return ReadAloud(
|
||||
path=str(path),
|
||||
key=key,
|
||||
bookmarks_path=str(bookmarks),
|
||||
source=f"lxmf:{chat}",
|
||||
start=start,
|
||||
title=title,
|
||||
)
|
||||
|
||||
|
||||
def _drain_lxmf_daemon(adapter):
|
||||
items = []
|
||||
while not adapter.daemon._outbound.empty():
|
||||
items.append(adapter.daemon._outbound.get_nowait())
|
||||
return items
|
||||
|
||||
|
||||
def test_lxmf_speech_stream_ready_only_for_voice_chats():
|
||||
from semif_agent.gateway.lxmf import LxmfAdapter
|
||||
|
||||
adapter = LxmfAdapter(
|
||||
{"allow_all_users": True, "voice": {"enabled": True}},
|
||||
synthesizer=FakeSynthesizer(),
|
||||
)
|
||||
assert adapter.supports_speech_stream is True
|
||||
assert adapter.speech_stream_ready("ab") is False
|
||||
adapter._mark_voice_chat("ab")
|
||||
assert adapter.speech_stream_ready("ab") is True
|
||||
|
||||
# Voice replies off: no read-aloud at all.
|
||||
off = LxmfAdapter(
|
||||
{"allow_all_users": True, "voice": {"enabled": True, "reply_with_voice": False}},
|
||||
synthesizer=FakeSynthesizer(),
|
||||
)
|
||||
off._mark_voice_chat("ab")
|
||||
assert off.supports_speech_stream is False
|
||||
assert off.speech_stream_ready("ab") is False
|
||||
|
||||
|
||||
def test_lxmf_streams_a_read_aloud_as_voice_messages(tmp_path, monkeypatch):
|
||||
import semif_agent.gateway.lxmf as lxmf
|
||||
from semif_agent.gateway.lxmf import LxmfAdapter
|
||||
from semif_agent.reading import read_offset
|
||||
|
||||
monkeypatch.setattr(lxmf, "pcm_to_opus_ogg", lambda pcm, rate, bitrate=0: b"OGG")
|
||||
chat = "ab" * 16
|
||||
adapter = LxmfAdapter(
|
||||
{"allow_all_users": True, "voice": {"enabled": True, "read": {"max_lead": 100000}}},
|
||||
synthesizer=FakeSynthesizer(),
|
||||
)
|
||||
adapter._mark_voice_chat(chat)
|
||||
text = "Sentence one. " * 80
|
||||
book = tmp_path / "book.txt"
|
||||
book.write_text(text, encoding="utf-8")
|
||||
bookmarks = tmp_path / "bookmarks.json"
|
||||
|
||||
adapter._stream(_read_aloud(chat, book, bookmarks))
|
||||
|
||||
items = _drain_lxmf_daemon(adapter)
|
||||
assert len(items) > 1, "the book must be sent as several messages"
|
||||
assert all(item[0] == chat for item in items)
|
||||
assert all(item[2] == b"OGG" for item in items)
|
||||
# The chunks reconstruct the text, and completion parks the bookmark at the end.
|
||||
assert "".join(item[1] for item in items).replace(" ", "") == text.replace(" ", "")
|
||||
assert read_offset(bookmarks, "k") == len(text)
|
||||
|
||||
|
||||
def test_lxmf_read_aloud_stops_on_a_stop_command(tmp_path, monkeypatch):
|
||||
import semif_agent.gateway.lxmf as lxmf
|
||||
from semif_agent.gateway.lxmf import LxmfAdapter
|
||||
from semif_agent.reading import read_offset
|
||||
|
||||
monkeypatch.setattr(lxmf, "pcm_to_opus_ogg", lambda pcm, rate, bitrate=0: b"OGG")
|
||||
chat = "ab" * 16
|
||||
seen: list = []
|
||||
|
||||
class StoppingSynth(FakeSynthesizer):
|
||||
def synthesize(self, text):
|
||||
if len(self.calls) == 1: # during the second chunk
|
||||
adapter._deliver({"source_hash": chat}, "stop")
|
||||
return super().synthesize(text)
|
||||
|
||||
adapter = LxmfAdapter(
|
||||
{"allow_all_users": True, "voice": {"enabled": True}},
|
||||
synthesizer=StoppingSynth(),
|
||||
)
|
||||
adapter._on_inbound = seen.append
|
||||
adapter._mark_voice_chat(chat)
|
||||
text = "Sentence one. " * 80
|
||||
book = tmp_path / "book.txt"
|
||||
book.write_text(text, encoding="utf-8")
|
||||
bookmarks = tmp_path / "bookmarks.json"
|
||||
|
||||
adapter._stream(_read_aloud(chat, book, bookmarks))
|
||||
|
||||
assert seen == [], "a bare stop must not be submitted as a request"
|
||||
items = _drain_lxmf_daemon(adapter)
|
||||
assert len(items) == 2, "the read stops at the next chunk"
|
||||
offset = read_offset(bookmarks, "k")
|
||||
assert 0 < offset < len(text)
|
||||
|
||||
|
||||
def test_lxmf_new_command_stops_the_read_and_is_forwarded(tmp_path, monkeypatch):
|
||||
import semif_agent.gateway.lxmf as lxmf
|
||||
from semif_agent.gateway.lxmf import LxmfAdapter
|
||||
|
||||
monkeypatch.setattr(lxmf, "pcm_to_opus_ogg", lambda pcm, rate, bitrate=0: b"OGG")
|
||||
chat = "ab" * 16
|
||||
seen: list = []
|
||||
|
||||
class StoppingSynth(FakeSynthesizer):
|
||||
def synthesize(self, text):
|
||||
if len(self.calls) == 1:
|
||||
adapter._deliver({"source_hash": chat}, "what time is it")
|
||||
return super().synthesize(text)
|
||||
|
||||
adapter = LxmfAdapter(
|
||||
{"allow_all_users": True, "voice": {"enabled": True}},
|
||||
synthesizer=StoppingSynth(),
|
||||
)
|
||||
adapter._on_inbound = seen.append
|
||||
adapter._mark_voice_chat(chat)
|
||||
book = tmp_path / "book.txt"
|
||||
book.write_text("Sentence one. " * 80, encoding="utf-8")
|
||||
|
||||
adapter._stream(_read_aloud(chat, book, tmp_path / "bookmarks.json"))
|
||||
assert [m.text for m in seen] == ["what time is it"]
|
||||
|
||||
|
||||
def test_lxmf_read_aloud_skips_a_non_voice_chat(tmp_path, monkeypatch):
|
||||
import semif_agent.gateway.lxmf as lxmf
|
||||
from semif_agent.gateway.lxmf import LxmfAdapter
|
||||
|
||||
monkeypatch.setattr(lxmf, "pcm_to_opus_ogg", lambda pcm, rate, bitrate=0: b"OGG")
|
||||
chat = "ab" * 16
|
||||
adapter = LxmfAdapter(
|
||||
{"allow_all_users": True, "voice": {"enabled": True}},
|
||||
synthesizer=FakeSynthesizer(),
|
||||
)
|
||||
# Not marked as a voice chat: nothing is streamed.
|
||||
book = tmp_path / "book.txt"
|
||||
book.write_text("Sentence one. " * 80, encoding="utf-8")
|
||||
adapter._stream(_read_aloud(chat, book, tmp_path / "bookmarks.json"))
|
||||
assert _drain_lxmf_daemon(adapter) == []
|
||||
|
||||
|
||||
def test_lxmf_read_aloud_backpressures_the_outbound_queue(tmp_path, monkeypatch):
|
||||
# The stream keeps only a few messages queued ahead, so a stop is prompt
|
||||
# even though the transport sends them slowly.
|
||||
import threading
|
||||
|
||||
import semif_agent.gateway.lxmf as lxmf
|
||||
from semif_agent.gateway.lxmf import LxmfAdapter
|
||||
|
||||
monkeypatch.setattr(lxmf, "pcm_to_opus_ogg", lambda pcm, rate, bitrate=0: b"OGG")
|
||||
chat = "ab" * 16
|
||||
adapter = LxmfAdapter(
|
||||
{"allow_all_users": True, "voice": {"enabled": True, "read": {"max_lead": 3}}},
|
||||
synthesizer=FakeSynthesizer(),
|
||||
)
|
||||
adapter._mark_voice_chat(chat)
|
||||
book = tmp_path / "book.txt"
|
||||
book.write_text("Sentence one. " * 400, encoding="utf-8")
|
||||
read = _read_aloud(chat, book, tmp_path / "bookmarks.json")
|
||||
|
||||
done = threading.Event()
|
||||
|
||||
def run():
|
||||
adapter._stream(read)
|
||||
done.set()
|
||||
|
||||
threading.Thread(target=run, daemon=True).start()
|
||||
deadline = time.time() + 3
|
||||
while adapter.daemon.pending_sends() < 3 and time.time() < deadline:
|
||||
time.sleep(0.01)
|
||||
time.sleep(0.1)
|
||||
assert adapter.daemon.pending_sends() == 3, "the stream must not outrun the queue"
|
||||
assert not done.is_set(), "the stream waits while the queue is full"
|
||||
|
||||
adapter._deliver({"source_hash": chat}, "stop")
|
||||
assert done.wait(timeout=2), "a stop releases the waiting stream"
|
||||
assert adapter._read_key is None
|
||||
|
||||
|
||||
def test_service_marks_streamable_sources(tmp_path):
|
||||
from semif_agent.gateway.lxmf import LxmfAdapter
|
||||
|
||||
scheduler = build_scheduler(tmp_path)
|
||||
chat = "ab" * 16
|
||||
adapter = LxmfAdapter(
|
||||
{"allow_all_users": True, "voice": {"enabled": True}},
|
||||
synthesizer=FakeSynthesizer(),
|
||||
)
|
||||
service = GatewayService(scheduler, adapter, config={})
|
||||
assert scheduler.speech.supports(f"lxmf:{chat}") is False
|
||||
adapter._mark_voice_chat(chat)
|
||||
assert scheduler.speech.supports(f"lxmf:{chat}") is True
|
||||
|
||||
# A read registered for that chat is routed to the adapter's outbound queue.
|
||||
scheduler.speech.read_aloud(
|
||||
path="/books/f.txt",
|
||||
key="k",
|
||||
bookmarks_path="/books/bookmarks.json",
|
||||
run_id="r1",
|
||||
source=f"lxmf:{chat}",
|
||||
)
|
||||
service._owners["r1"] = ("lxmf", chat)
|
||||
service.surface()
|
||||
message = service.outbound["lxmf"].get_nowait()
|
||||
assert message.stream is not None
|
||||
assert message.stream.key == "k"
|
||||
|
||||
|
||||
def test_service_marks_voice_gateway_streamable(tmp_path):
|
||||
scheduler = build_scheduler(tmp_path)
|
||||
GatewayService(scheduler, FakeStreamAdapter(), config={})
|
||||
assert scheduler.speech.supports("voice:c") is True
|
||||
|
||||
|
||||
# ---- service: multiple platforms ----
|
||||
|
||||
class FakeLxmfAdapter:
|
||||
@@ -928,3 +1152,51 @@ def test_service_reply_routes_to_owning_platform(tmp_path):
|
||||
)
|
||||
assert not service.outbound["lxmf"].empty()
|
||||
assert service.outbound["simplex"].empty()
|
||||
|
||||
|
||||
# ---- service: read-aloud streams route to a streaming front end ------------
|
||||
|
||||
|
||||
class FakeStreamAdapter:
|
||||
name = "voice"
|
||||
supports_speech_stream = True
|
||||
|
||||
|
||||
def test_service_routes_read_aloud_to_streaming_adapter(tmp_path):
|
||||
scheduler = build_scheduler(tmp_path)
|
||||
service = GatewayService(scheduler, FakeStreamAdapter(), config={})
|
||||
scheduler.speech.read_aloud(
|
||||
path="/books/p.txt",
|
||||
key="gutenberg-1342",
|
||||
bookmarks_path="/books/bookmarks.json",
|
||||
run_id="r1",
|
||||
source="voice:c",
|
||||
title="Pride and Prejudice",
|
||||
start=10,
|
||||
)
|
||||
service._owners["r1"] = ("voice", "c")
|
||||
service.surface()
|
||||
|
||||
message = service.outbound["voice"].get_nowait()
|
||||
assert message.stream is not None
|
||||
assert message.stream.key == "gutenberg-1342"
|
||||
assert message.stream.start == 10
|
||||
assert message.text == ""
|
||||
|
||||
|
||||
def test_service_skips_read_aloud_for_a_non_streaming_platform(tmp_path):
|
||||
scheduler = build_scheduler(tmp_path)
|
||||
service = build_service(scheduler) # FakeAdapter (simplex) cannot stream
|
||||
scheduler.speech.read_aloud(
|
||||
path="/books/p.txt",
|
||||
key="gutenberg-1342",
|
||||
bookmarks_path="/books/bookmarks.json",
|
||||
run_id="r1",
|
||||
source="simplex:4",
|
||||
)
|
||||
service._owners["r1"] = ("simplex", "4")
|
||||
service.surface()
|
||||
assert service.outbound["simplex"].empty()
|
||||
assert any(
|
||||
e["kind"] == "gateway_stream_unsupported" for e in scheduler.trace.read()
|
||||
)
|
||||
@@ -0,0 +1,144 @@
|
||||
"""Pure-stdlib tests for the reading helpers and the scheduler speech channel.
|
||||
|
||||
`semif_agent.reading` owns bookmark persistence and deterministic speakable
|
||||
chunking; `semif_agent.speech` owns the queue a skill posts a read-aloud request
|
||||
to. Neither touches audio, the scheduler, or a gateway.
|
||||
"""
|
||||
|
||||
import json
|
||||
|
||||
from semif_agent.reading import (
|
||||
BOOKMARKS_FILE,
|
||||
bookmarks_file,
|
||||
chunk_text,
|
||||
load_bookmarks,
|
||||
read_offset,
|
||||
save_bookmark,
|
||||
)
|
||||
from semif_agent.speech import ReadAloud, SpeechService
|
||||
|
||||
|
||||
# ---- chunking --------------------------------------------------------------
|
||||
|
||||
|
||||
def test_chunk_text_splits_and_offsets_are_contiguous():
|
||||
text = "One. Two. Three. Four. Five. Six."
|
||||
chunks = list(chunk_text(text, 0, 12))
|
||||
assert len(chunks) > 1
|
||||
for offset, chunk in chunks:
|
||||
assert text[offset : offset + len(chunk)] == chunk
|
||||
# The concatenation (whitespace-insensitive) is the original text.
|
||||
assert "".join(chunk for _o, chunk in chunks).replace(" ", "") == text.replace(" ", "")
|
||||
|
||||
|
||||
def test_chunk_text_resumes_deterministically_from_a_saved_offset():
|
||||
text = "Alpha beta gamma. Delta epsilon zeta. Eta theta iota. Kappa lambda mu."
|
||||
chunks = list(chunk_text(text, 0, 20))
|
||||
assert len(chunks) >= 3
|
||||
resume_offset = chunks[2][0]
|
||||
# Resuming from a chunk boundary reproduces the tail exactly.
|
||||
tail = list(chunk_text(text, resume_offset, 20))
|
||||
assert tail == chunks[2:]
|
||||
|
||||
|
||||
def test_chunk_text_respects_max_chars_without_a_good_break():
|
||||
text = "x" * 100
|
||||
chunks = list(chunk_text(text, 0, 30))
|
||||
assert [len(chunk) for _o, chunk in chunks] == [30, 30, 30, 10]
|
||||
|
||||
|
||||
def test_chunk_text_prefers_a_paragraph_break():
|
||||
text = "A" * 40 + "\n\n" + "B" * 40
|
||||
chunks = list(chunk_text(text, 0, 60))
|
||||
# The first chunk ends at the paragraph break, not mid-word.
|
||||
assert chunks[0][1] == "A" * 40
|
||||
|
||||
|
||||
def test_chunk_text_empty_and_start_past_end():
|
||||
assert list(chunk_text("", 0, 10)) == []
|
||||
assert list(chunk_text("short", 999, 10)) == []
|
||||
|
||||
|
||||
def test_chunk_text_skips_leading_whitespace_at_resume():
|
||||
text = " hello world"
|
||||
chunks = list(chunk_text(text, 0, 50))
|
||||
assert chunks == [(2, "hello world")]
|
||||
|
||||
|
||||
# ---- bookmarks -------------------------------------------------------------
|
||||
|
||||
|
||||
def test_bookmarks_file_lives_in_the_books_directory(tmp_path):
|
||||
assert bookmarks_file(tmp_path) == tmp_path / BOOKMARKS_FILE
|
||||
|
||||
|
||||
def test_save_and_read_bookmark_roundtrip(tmp_path):
|
||||
path = bookmarks_file(tmp_path)
|
||||
assert read_offset(path, "gutenberg-1342") == 0
|
||||
save_bookmark(path, "gutenberg-1342", 1234, "Pride and Prejudice")
|
||||
assert read_offset(path, "gutenberg-1342") == 1234
|
||||
entry = load_bookmarks(path)["gutenberg-1342"]
|
||||
assert entry["offset"] == 1234
|
||||
assert entry["title"] == "Pride and Prejudice"
|
||||
assert "updated_at" in entry
|
||||
# A second save keeps the other keys.
|
||||
save_bookmark(path, "gutenberg-84", 7, "Frankenstein")
|
||||
assert read_offset(path, "gutenberg-1342") == 1234
|
||||
assert read_offset(path, "gutenberg-84") == 7
|
||||
|
||||
|
||||
def test_save_bookmark_leaves_no_temp_file(tmp_path):
|
||||
path = bookmarks_file(tmp_path)
|
||||
save_bookmark(path, "k", 5)
|
||||
assert not (tmp_path / (BOOKMARKS_FILE + ".tmp")).exists()
|
||||
|
||||
|
||||
def test_bookmark_tolerates_missing_and_malformed(tmp_path):
|
||||
path = bookmarks_file(tmp_path)
|
||||
assert load_bookmarks(path) == {}
|
||||
path.write_text("{not json")
|
||||
assert load_bookmarks(path) == {}
|
||||
assert read_offset(path, "k") == 0
|
||||
# A legacy bare-integer entry is still read.
|
||||
path.write_text(json.dumps({"k": 42}))
|
||||
assert read_offset(path, "k") == 42
|
||||
# A non-dict top level is ignored.
|
||||
path.write_text(json.dumps([1, 2, 3]))
|
||||
assert load_bookmarks(path) == {}
|
||||
|
||||
|
||||
# ---- speech service --------------------------------------------------------
|
||||
|
||||
|
||||
def test_speech_service_queues_and_drains():
|
||||
service = SpeechService()
|
||||
service.read_aloud(
|
||||
path="/books/x.txt",
|
||||
key="gutenberg-1",
|
||||
bookmarks_path="/books/bookmarks.json",
|
||||
run_id="r1",
|
||||
source="voice:mic",
|
||||
title="X",
|
||||
start=10,
|
||||
)
|
||||
assert len(service.pending()) == 1
|
||||
reads = service.drain()
|
||||
assert len(reads) == 1
|
||||
read = reads[0]
|
||||
assert isinstance(read, ReadAloud)
|
||||
assert read.key == "gutenberg-1"
|
||||
assert read.start == 10
|
||||
assert read.run_id == "r1"
|
||||
# Drained once; the queue is empty afterwards.
|
||||
assert service.drain() == []
|
||||
assert service.pending() == []
|
||||
|
||||
|
||||
def test_speech_service_is_bounded():
|
||||
service = SpeechService(max_pending=2)
|
||||
for index in range(5):
|
||||
service.read_aloud(
|
||||
path=f"/b/{index}.txt", key=str(index), bookmarks_path="/b/bookmarks.json"
|
||||
)
|
||||
assert len(service.pending()) == 2 # oldest dropped
|
||||
assert [r.key for r in service.drain()] == ["3", "4"]
|
||||
@@ -223,6 +223,35 @@ def test_scheduler_exposes_a_read_only_catalog(tmp_path):
|
||||
assert house_ctx.admin is scheduler
|
||||
assert plain_ctx.admin is None
|
||||
assert plain_ctx.catalog is scheduler.catalog
|
||||
# The scheduler's speech channel rides on every run context (a skill can
|
||||
# post a long-form read-aloud for a voice front end).
|
||||
assert plain_ctx.speech is scheduler.speech
|
||||
|
||||
|
||||
def test_a_run_that_registers_a_read_is_terminal(tmp_path):
|
||||
"""A run that hands off to a long-form read is the answer: a `continue`
|
||||
assessment must not re-dispatch it (which authored a spurious skill)."""
|
||||
scheduler = _scheduler(
|
||||
tmp_path, choices={"additional work to be done": "continue"}
|
||||
)
|
||||
|
||||
def act(ctx, request):
|
||||
ctx.speech.read_aloud(
|
||||
path="/b/x.txt",
|
||||
key="k",
|
||||
bookmarks_path="/b/bookmarks.json",
|
||||
run_id=request.id,
|
||||
source=request.source,
|
||||
)
|
||||
return ActionResult(action_log="Reading X aloud.", new_state="ok")
|
||||
|
||||
skill = Skill(name="read_book", category="books", description="Read.", act=act)
|
||||
scheduler.tree.setdefault("books", []).append(skill)
|
||||
result = scheduler._run_skill(skill, Request("read x", source="voice:c"))
|
||||
assert result.intermediate is False, "a read-registering run must not continue"
|
||||
kinds = [entry["kind"] for entry in scheduler.trace.read()]
|
||||
assert "read_aloud_terminal" in kinds
|
||||
assert "continued" not in kinds
|
||||
|
||||
|
||||
def test_fidelity_gate_state_is_whole_body_without_the_request(tmp_path):
|
||||
|
||||
@@ -927,3 +927,206 @@ def test_download_wake_file_rejects_sha_mismatch(tmp_path):
|
||||
with pytest.raises(SystemExit):
|
||||
module.download_wake_file("hey_computer", ref, wake_dir)
|
||||
assert not (wake_dir / "hey_computer.onnx").exists()
|
||||
|
||||
|
||||
# ---- read-aloud (long-form streaming) --------------------------------------
|
||||
|
||||
|
||||
class FakeReadDaemon:
|
||||
"""A daemon double for the read-aloud loop: records events and speech."""
|
||||
|
||||
def __init__(self, on_speak=None, max_speak_chars=600):
|
||||
self.events = []
|
||||
self.spoken = []
|
||||
self._muted = False
|
||||
self._stopping = False
|
||||
self.on_speak = on_speak
|
||||
self.max_speak_chars = max_speak_chars
|
||||
|
||||
def _event(self, kind, **fields):
|
||||
self.events.append((kind, fields))
|
||||
|
||||
def speak(self, text):
|
||||
self.spoken.append(text)
|
||||
if self.on_speak is not None:
|
||||
self.on_speak(self, text)
|
||||
|
||||
def set_muted(self, muted):
|
||||
self._muted = muted
|
||||
|
||||
def muted(self):
|
||||
return self._muted
|
||||
|
||||
def stopping(self):
|
||||
return self._stopping
|
||||
|
||||
def stop(self):
|
||||
self._stopping = True
|
||||
|
||||
|
||||
def _adapter_with_daemon(on_speak=None, config=None):
|
||||
adapter = VoiceAdapter(config or {})
|
||||
daemon = FakeReadDaemon(on_speak=on_speak)
|
||||
adapter.daemon = daemon
|
||||
return adapter, daemon
|
||||
|
||||
|
||||
def _book(tmp_path, text):
|
||||
path = tmp_path / "book.txt"
|
||||
path.write_text(text, encoding="utf-8")
|
||||
return path
|
||||
|
||||
|
||||
def _read(path, bookmarks, key="gutenberg-1", start=0, title="T"):
|
||||
from semif_agent.speech import ReadAloud
|
||||
|
||||
return ReadAloud(
|
||||
path=str(path),
|
||||
key=key,
|
||||
bookmarks_path=str(bookmarks),
|
||||
start=start,
|
||||
title=title,
|
||||
)
|
||||
|
||||
|
||||
def test_adapter_streams_chunks_and_records_completion(tmp_path):
|
||||
from semif_agent.reading import read_offset
|
||||
|
||||
text = "One two three. " * 60
|
||||
book = _book(tmp_path, text)
|
||||
bookmarks = tmp_path / "bookmarks.json"
|
||||
adapter, daemon = _adapter_with_daemon()
|
||||
adapter._stream(_read(book, bookmarks))
|
||||
|
||||
assert len(daemon.spoken) > 1, "the text must be spoken in chunks"
|
||||
assert all(chunk.strip() for chunk in daemon.spoken)
|
||||
kinds = [kind for kind, _ in daemon.events]
|
||||
assert "gateway_read_start" in kinds
|
||||
assert "gateway_read_done" in kinds
|
||||
# Finished: the bookmark sits at the end so a later request starts over.
|
||||
assert read_offset(bookmarks, "gutenberg-1") == len(text)
|
||||
assert adapter._read_active() is False
|
||||
|
||||
|
||||
def test_adapter_stream_resumes_from_a_saved_offset(tmp_path):
|
||||
from semif_agent.reading import read_offset, save_bookmark
|
||||
|
||||
text = "Sentence one. Sentence two. Sentence three. Sentence four."
|
||||
book = _book(tmp_path, text)
|
||||
bookmarks = tmp_path / "bookmarks.json"
|
||||
save_bookmark(bookmarks, "gutenberg-1", 14, "T") # start of "Sentence two."
|
||||
adapter, daemon = _adapter_with_daemon()
|
||||
adapter._stream(_read(book, bookmarks, start=14))
|
||||
|
||||
spoken = " ".join(daemon.spoken)
|
||||
assert spoken.startswith("Sentence two")
|
||||
assert "Sentence one" not in spoken
|
||||
assert read_offset(bookmarks, "gutenberg-1") == len(text)
|
||||
|
||||
|
||||
def test_adapter_stream_stops_on_a_stop_signal(tmp_path):
|
||||
from semif_agent.reading import read_offset
|
||||
|
||||
text = "Alpha beta gamma delta. " * 80
|
||||
book = _book(tmp_path, text)
|
||||
bookmarks = tmp_path / "bookmarks.json"
|
||||
|
||||
def on_speak(daemon, _text):
|
||||
if len(daemon.spoken) == 2:
|
||||
adapter._stop_reading("stop")
|
||||
|
||||
adapter, daemon = _adapter_with_daemon(on_speak=on_speak)
|
||||
adapter._stream(_read(book, bookmarks))
|
||||
|
||||
assert len(daemon.spoken) == 2, "the read must stop at the next boundary"
|
||||
kinds = [kind for kind, _ in daemon.events]
|
||||
assert "gateway_read_stop" in kinds
|
||||
assert "gateway_read_interrupted" in kinds
|
||||
offset = read_offset(bookmarks, "gutenberg-1")
|
||||
assert 0 < offset < len(text), "the interrupted chunk's start is the resume point"
|
||||
assert adapter._read_active() is False
|
||||
|
||||
|
||||
def test_adapter_stream_stops_when_a_barge_in_mutes(tmp_path):
|
||||
text = "Alpha. Beta. Gamma. Delta. Epsilon. Zeta."
|
||||
book = _book(tmp_path, text)
|
||||
bookmarks = tmp_path / "bookmarks.json"
|
||||
|
||||
def on_speak(daemon, _text):
|
||||
if len(daemon.spoken) == 1:
|
||||
daemon.set_muted(True) # a barge-in landed during the first chunk
|
||||
|
||||
adapter, daemon = _adapter_with_daemon(on_speak=on_speak)
|
||||
adapter._stream(_read(book, bookmarks))
|
||||
assert len(daemon.spoken) == 1
|
||||
assert adapter._read_active() is False
|
||||
|
||||
|
||||
def test_adapter_stream_missing_file_is_traced_not_raised(tmp_path):
|
||||
adapter, daemon = _adapter_with_daemon()
|
||||
read = _read(tmp_path / "nope.txt", tmp_path / "bookmarks.json")
|
||||
adapter._stream(read) # must not raise
|
||||
assert daemon.spoken == []
|
||||
assert any(kind == "gateway_read_failed" for kind, _ in daemon.events)
|
||||
assert adapter._read_active() is False
|
||||
|
||||
|
||||
def test_adapter_stream_chunks_never_exceed_the_speakable_budget(tmp_path):
|
||||
# A chunk larger than the daemon's `max_speak_chars` would be truncated and
|
||||
# lose text, so the stream clamps its chunk size below that budget.
|
||||
text = "word " * 200
|
||||
book = _book(tmp_path, text)
|
||||
bookmarks = tmp_path / "bookmarks.json"
|
||||
adapter, daemon = _adapter_with_daemon(config={"read": {"chunk_chars": 500}})
|
||||
daemon.max_speak_chars = 40
|
||||
adapter._stream(_read(book, bookmarks))
|
||||
assert daemon.spoken
|
||||
assert max(len(chunk) for chunk in daemon.spoken) <= 40
|
||||
|
||||
|
||||
def test_adapter_supports_speech_stream_by_default_and_can_disable():
|
||||
assert VoiceAdapter({}).supports_speech_stream is True
|
||||
assert VoiceAdapter({"read": {"enabled": False}}).supports_speech_stream is False
|
||||
|
||||
|
||||
def test_adapter_handle_stop_command_ends_the_read_without_forwarding(tmp_path):
|
||||
import queue
|
||||
|
||||
text = "Alpha. Beta. Gamma. Delta."
|
||||
book = _book(tmp_path, text)
|
||||
adapter, daemon = _adapter_with_daemon()
|
||||
adapter._on_inbound = lambda message: None
|
||||
adapter._outbound = queue.Queue()
|
||||
# Mark a read active (as the pump would while streaming).
|
||||
with adapter._read_lock:
|
||||
adapter._read_key = "gutenberg-1"
|
||||
adapter._on_utterance("stop")
|
||||
adapter._handle(adapter._inbound.get())
|
||||
assert adapter._read_stop.is_set(), "the active read must be asked to stop"
|
||||
assert daemon._muted is False # a normal stop never mutes
|
||||
|
||||
|
||||
def test_adapter_handle_new_command_stops_the_read_and_forwards():
|
||||
adapter, _daemon = _adapter_with_daemon()
|
||||
seen = []
|
||||
adapter._on_inbound = seen.append
|
||||
with adapter._read_lock:
|
||||
adapter._read_key = "gutenberg-1"
|
||||
adapter._on_utterance("turn on the lights")
|
||||
adapter._handle(adapter._inbound.get())
|
||||
assert adapter._read_stop.is_set(), "a new command interrupts the read"
|
||||
assert [m.text for m in seen] == ["turn on the lights"]
|
||||
|
||||
|
||||
def test_adapter_barge_in_stop_also_ends_the_read():
|
||||
adapter, _daemon = _adapter_with_daemon()
|
||||
seen = []
|
||||
adapter._on_inbound = seen.append
|
||||
adapter._barged_in = True
|
||||
with adapter._read_lock:
|
||||
adapter._read_key = "gutenberg-1"
|
||||
adapter._on_utterance("stop")
|
||||
adapter._handle(adapter._inbound.get())
|
||||
assert adapter._read_stop.is_set(), "a barge-in stop ends the read"
|
||||
assert seen == []
|
||||
|
||||
Reference in new issue
Block a user