phosphor-harness 0.4.4 → 0.4.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +29 -4
- package/package.json +33 -10
- package/pyproject.toml +1 -1
- package/quickstart.sh +3 -3
- package/scripts/context_size.py +28 -0
- package/scripts/run_service.sh +8 -0
- package/scripts/run_transcription_worker.py +91 -0
- package/sophon_harness/cli.py +4 -0
- package/sophon_harness/duplex_voice.py +476 -0
- package/sophon_harness/episode_recording.py +59 -0
- package/sophon_harness/ornith.py +688 -22
- package/sophon_harness/portal_server.py +104 -3
- package/sophon_harness/pulse_audio.py +77 -0
- package/sophon_harness/regex_tools.py +337 -0
- package/sophon_harness/speak_thinking.py +183 -0
- package/sophon_harness/tools.py +62 -12
- package/sophon_harness/voice.py +46 -16
|
@@ -0,0 +1,476 @@
|
|
|
1
|
+
"""Run the native acoustic session over a continuously open local audio stream."""
|
|
2
|
+
|
|
3
|
+
from collections import deque
|
|
4
|
+
from contextlib import contextmanager, nullcontext
|
|
5
|
+
from dataclasses import dataclass, field
|
|
6
|
+
import os
|
|
7
|
+
import select
|
|
8
|
+
import signal
|
|
9
|
+
import subprocess
|
|
10
|
+
from threading import Event
|
|
11
|
+
import time
|
|
12
|
+
|
|
13
|
+
import httpx
|
|
14
|
+
import numpy as np
|
|
15
|
+
from training_suite.models.native_turn import NativeAssistantTurn
|
|
16
|
+
from training_suite.sophon_acoustic_session import (
|
|
17
|
+
INPUT_FRAME_BYTES, AcousticTurnCancelled, AcousticTurnDone, AcousticTurnSession,
|
|
18
|
+
)
|
|
19
|
+
from training_suite.sophon_runtime import NativeSpeechFailure, NativeSpeechFrame, NativeToolResult
|
|
20
|
+
from training_suite.sophon_vad import SophonVoiceBoundaries
|
|
21
|
+
|
|
22
|
+
from .episode_recording import EpisodeRecorder
|
|
23
|
+
from .pulse_audio import AudioRouteChanged, _inventory, echo_cancel, restore_capture, select_devices
|
|
24
|
+
from .speak_thinking import LiveProgressCue, TOOL_NAME as THINKING_TOOL
|
|
25
|
+
from .terminal_input import PASSWORD_REQUEST, TERMINAL_HANDLE
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
PLAYBACK_BYTES_PER_SECOND = 48_000
|
|
29
|
+
MERGE_WINDOW_SECONDS = 2.0
|
|
30
|
+
PREROLL_FRAMES = 20
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@contextmanager
|
|
34
|
+
def _stop_on_signal():
|
|
35
|
+
def stop(_signal, _frame):
|
|
36
|
+
raise SystemExit(0)
|
|
37
|
+
|
|
38
|
+
previous = signal.signal(signal.SIGTERM, stop)
|
|
39
|
+
try:
|
|
40
|
+
yield
|
|
41
|
+
finally:
|
|
42
|
+
signal.signal(signal.SIGTERM, previous)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
@dataclass
|
|
46
|
+
class _Speech:
|
|
47
|
+
message: dict
|
|
48
|
+
start: int
|
|
49
|
+
end: int | None = None
|
|
50
|
+
|
|
51
|
+
def heard(self, count):
|
|
52
|
+
if self.end is None or self.end <= self.start or count <= self.start:
|
|
53
|
+
return ""
|
|
54
|
+
text = self.message["content"]
|
|
55
|
+
if count >= self.end:
|
|
56
|
+
return text
|
|
57
|
+
cutoff = int(len(text) * (count - self.start) / (self.end - self.start))
|
|
58
|
+
return text[:cutoff].rsplit(" ", 1)[0] if " " in text[:cutoff] else ""
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
@dataclass
|
|
62
|
+
class _Turn:
|
|
63
|
+
number: int
|
|
64
|
+
prefix: bytes = b""
|
|
65
|
+
generation: int | None = None
|
|
66
|
+
committed_at: float | None = None
|
|
67
|
+
pcm: bytes = b""
|
|
68
|
+
heard: str = ""
|
|
69
|
+
password: tuple | None = None
|
|
70
|
+
launched_tools: bool = False
|
|
71
|
+
messages: list = field(default_factory=list)
|
|
72
|
+
speech: list = field(default_factory=list)
|
|
73
|
+
prompts: set = field(default_factory=set)
|
|
74
|
+
received: int = 0
|
|
75
|
+
submitted: int = 0
|
|
76
|
+
playback_started: float | None = None
|
|
77
|
+
prebuffer_started: float | None = None
|
|
78
|
+
first_generated_pcm: bool = False
|
|
79
|
+
first_pcm: bool = False
|
|
80
|
+
ended: bool = False
|
|
81
|
+
failed: bool = False
|
|
82
|
+
reasoning: tuple[float, float] | None = None
|
|
83
|
+
progress_cancelled: Event = field(default_factory=Event)
|
|
84
|
+
progress_cue: LiveProgressCue | None = None
|
|
85
|
+
|
|
86
|
+
def close_segment(self):
|
|
87
|
+
if self.speech and self.speech[-1].end is None:
|
|
88
|
+
self.speech[-1].end = self.received
|
|
89
|
+
|
|
90
|
+
def history(self, interrupted=False, now=None):
|
|
91
|
+
if not self.heard or self.password is not None:
|
|
92
|
+
return []
|
|
93
|
+
user = {"role": "user", "content": self.heard}
|
|
94
|
+
if not interrupted:
|
|
95
|
+
return [user, *self.messages]
|
|
96
|
+
drained = 0 if self.playback_started is None else min(
|
|
97
|
+
self.submitted, max(0, int((now - self.playback_started - 0.20) * PLAYBACK_BYTES_PER_SECOND)),
|
|
98
|
+
)
|
|
99
|
+
segments = {id(segment.message): segment.heard(drained) for segment in self.speech}
|
|
100
|
+
results = {message["tool_call_id"] for message in self.messages if message["role"] == "tool"}
|
|
101
|
+
retained = [user]
|
|
102
|
+
allowed_results = set()
|
|
103
|
+
for message in self.messages:
|
|
104
|
+
if message["role"] == "tool":
|
|
105
|
+
if message["tool_call_id"] in allowed_results:
|
|
106
|
+
retained.append(message)
|
|
107
|
+
continue
|
|
108
|
+
calls = message.get("tool_calls") or ()
|
|
109
|
+
if calls and all(call["id"] in results for call in calls):
|
|
110
|
+
retained.append({**message, "content": segments.get(id(message), "")})
|
|
111
|
+
allowed_results.update(call["id"] for call in calls)
|
|
112
|
+
elif spoken := segments.get(id(message)):
|
|
113
|
+
retained.append({"role": "assistant", "content": spoken})
|
|
114
|
+
return retained
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
class DuplexVoice:
|
|
118
|
+
"""Keep a single generation lane while input and speaker output remain independent."""
|
|
119
|
+
|
|
120
|
+
def __init__(self, profile, runtime, embed, tools, boundary, player, password_reply, log, *,
|
|
121
|
+
history=None, recorder=None, progress_enabled=False):
|
|
122
|
+
self.profile, self.runtime, self.embed, self.tools = profile, runtime, embed, tools
|
|
123
|
+
self.boundary, self.start_player, self.password_reply, self.log = boundary, player, password_reply, log
|
|
124
|
+
self.history = history if history is not None else deque(maxlen=6)
|
|
125
|
+
self.recorder = recorder
|
|
126
|
+
self.turn = None
|
|
127
|
+
self.pending_audio = bytearray()
|
|
128
|
+
prebuffer_ms = profile.get("playback_prebuffer_ms", 500)
|
|
129
|
+
if type(prebuffer_ms) is not int or not 0 <= prebuffer_ms <= 1_000:
|
|
130
|
+
raise ValueError("playback_prebuffer_ms must be an integer between 0 and 1000")
|
|
131
|
+
self.prebuffer_bytes = prebuffer_ms * PLAYBACK_BYTES_PER_SECOND // 1_000
|
|
132
|
+
self.player = None
|
|
133
|
+
self.progress_enabled = progress_enabled
|
|
134
|
+
self.progress_player = None
|
|
135
|
+
self.progress_audio = bytearray()
|
|
136
|
+
self.prefix = b""
|
|
137
|
+
self.speaking = False
|
|
138
|
+
self.number = 0
|
|
139
|
+
self.session = AcousticTurnSession(self._generate, lambda pcm, _cancel: pcm, max_output_events=8)
|
|
140
|
+
|
|
141
|
+
def close(self):
|
|
142
|
+
try:
|
|
143
|
+
self._stop_player()
|
|
144
|
+
finally:
|
|
145
|
+
self.session.close()
|
|
146
|
+
|
|
147
|
+
def _generate(self, messages, *, media, cancelled, await_commit):
|
|
148
|
+
turn = self.turn
|
|
149
|
+
if turn is None or turn.number != messages[-1].get("voice_turn"):
|
|
150
|
+
return
|
|
151
|
+
turn.pcm = (turn.prefix + media)[-960_000:]
|
|
152
|
+
def progress(rate):
|
|
153
|
+
if turn.committed_at is not None and not cancelled.is_set():
|
|
154
|
+
turn.reasoning = (time.monotonic(), rate)
|
|
155
|
+
|
|
156
|
+
options = {"progress": progress} if self.progress_enabled else {}
|
|
157
|
+
with self.runtime.backplane.interruptible(cancelled, **options):
|
|
158
|
+
if turn.password is not None:
|
|
159
|
+
if await_commit() and not cancelled.is_set():
|
|
160
|
+
reply = self.password_reply(turn.pcm, turn.password)
|
|
161
|
+
for pcm in self.runtime.speech.frames(reply, self.profile["language"], cancelled=cancelled):
|
|
162
|
+
yield NativeSpeechFrame(pcm)
|
|
163
|
+
return
|
|
164
|
+
user = {"role": "user", "content": ""}
|
|
165
|
+
model_audio = self.embed(turn.pcm, cancelled)
|
|
166
|
+
try:
|
|
167
|
+
for event in self.tools.run_committed_turn(
|
|
168
|
+
self.runtime, [*messages[:-1], user], media=model_audio, cancelled=cancelled,
|
|
169
|
+
await_commit=await_commit, max_new_tokens=self.profile["max_new_tokens"],
|
|
170
|
+
max_tool_rounds=self.runtime.backplane.tool_rounds, language=self.profile["language"],
|
|
171
|
+
):
|
|
172
|
+
turn.heard = model_audio.user_text or ""
|
|
173
|
+
if isinstance(event, NativeAssistantTurn):
|
|
174
|
+
if event.text:
|
|
175
|
+
turn.progress_cancelled.set()
|
|
176
|
+
if turn.progress_cue is not None:
|
|
177
|
+
turn.progress_cue.thread.join(timeout=0.10)
|
|
178
|
+
if event.calls:
|
|
179
|
+
turn.launched_tools = True
|
|
180
|
+
yield event
|
|
181
|
+
finally:
|
|
182
|
+
turn.heard = model_audio.user_text or ""
|
|
183
|
+
|
|
184
|
+
def _draft(self, through):
|
|
185
|
+
self.number += 1
|
|
186
|
+
messages = [{"role": "system", "content": self.profile["system_prompt"]}]
|
|
187
|
+
for previous in self.history:
|
|
188
|
+
messages.extend(previous)
|
|
189
|
+
messages.append({"role": "user", "content": "", "voice_turn": self.number})
|
|
190
|
+
turn = self.turn = _Turn(self.number, self.prefix, password=self.tools.password_request)
|
|
191
|
+
turn.generation = self.session.speech_stopped(messages, through_seq=through)
|
|
192
|
+
self.log(event="draft_started", generation=turn.generation)
|
|
193
|
+
|
|
194
|
+
def _stop_player(self):
|
|
195
|
+
self._stop_progress()
|
|
196
|
+
self.pending_audio.clear()
|
|
197
|
+
if self.player is None:
|
|
198
|
+
return
|
|
199
|
+
player, self.player = self.player, None
|
|
200
|
+
if player.poll() is None:
|
|
201
|
+
player.kill()
|
|
202
|
+
player.stdin.close()
|
|
203
|
+
player.wait(timeout=3)
|
|
204
|
+
|
|
205
|
+
def _stop_progress(self):
|
|
206
|
+
if self.turn is not None:
|
|
207
|
+
self.turn.progress_cancelled.set()
|
|
208
|
+
self.progress_audio.clear()
|
|
209
|
+
if self.progress_player is not None:
|
|
210
|
+
player, self.progress_player = self.progress_player, None
|
|
211
|
+
if player.poll() is None:
|
|
212
|
+
player.kill()
|
|
213
|
+
player.stdin.close()
|
|
214
|
+
player.wait(timeout=3)
|
|
215
|
+
|
|
216
|
+
def _play_progress(self, turn):
|
|
217
|
+
if turn.progress_cancelled.is_set() or turn.ended:
|
|
218
|
+
self._stop_progress()
|
|
219
|
+
return
|
|
220
|
+
if turn.progress_cue is None:
|
|
221
|
+
if turn.reasoning is None or time.monotonic() - turn.reasoning[0] >= 0.45:
|
|
222
|
+
return
|
|
223
|
+
turn.progress_cue = LiveProgressCue(self.runtime.speech, self.profile["language"],
|
|
224
|
+
turn.reasoning[1], turn.progress_cancelled)
|
|
225
|
+
cue = turn.progress_cue
|
|
226
|
+
if not self.progress_audio:
|
|
227
|
+
self.progress_audio.extend(cue.next_frame())
|
|
228
|
+
if not self.progress_audio:
|
|
229
|
+
if not cue.thread.is_alive():
|
|
230
|
+
if cue.failed:
|
|
231
|
+
self.log(event="progress_voice_unavailable", generation=turn.generation)
|
|
232
|
+
if self.progress_player is not None and not self.progress_player.stdin.closed:
|
|
233
|
+
self.progress_player.stdin.close()
|
|
234
|
+
if self.progress_player is None or self.progress_player.poll() is not None:
|
|
235
|
+
self._stop_progress()
|
|
236
|
+
return
|
|
237
|
+
if self.progress_player is None:
|
|
238
|
+
try:
|
|
239
|
+
self.progress_player = self.start_player()
|
|
240
|
+
os.set_blocking(self.progress_player.stdin.fileno(), False)
|
|
241
|
+
except OSError:
|
|
242
|
+
self._stop_progress()
|
|
243
|
+
self.log(event="progress_voice_unavailable", generation=turn.generation)
|
|
244
|
+
return
|
|
245
|
+
self.log(event="progress_voice", generation=turn.generation, reasoning_tokens_per_second=round(cue.rate, 2),
|
|
246
|
+
speed=round(cue.speed, 2), gain_db=-5,
|
|
247
|
+
first_frame_s=round(time.monotonic() - cue.started, 3))
|
|
248
|
+
try:
|
|
249
|
+
written = os.write(self.progress_player.stdin.fileno(), self.progress_audio)
|
|
250
|
+
except BlockingIOError:
|
|
251
|
+
return
|
|
252
|
+
except BrokenPipeError:
|
|
253
|
+
self._stop_progress()
|
|
254
|
+
return
|
|
255
|
+
del self.progress_audio[:written]
|
|
256
|
+
|
|
257
|
+
def _speech_started(self, resumed):
|
|
258
|
+
old = self.turn
|
|
259
|
+
self.session.speech_started()
|
|
260
|
+
self.turn = None
|
|
261
|
+
self.speaking = True
|
|
262
|
+
if old is None:
|
|
263
|
+
return
|
|
264
|
+
old.progress_cancelled.set()
|
|
265
|
+
if old.committed_at is None:
|
|
266
|
+
self.log(event="draft_revised", generation=old.generation)
|
|
267
|
+
return
|
|
268
|
+
now = time.monotonic()
|
|
269
|
+
self._stop_player()
|
|
270
|
+
merge = bool(old.password is None and old.pcm and not old.launched_tools
|
|
271
|
+
and now - old.committed_at < MERGE_WINDOW_SECONDS)
|
|
272
|
+
if merge:
|
|
273
|
+
self.prefix = old.pcm
|
|
274
|
+
else:
|
|
275
|
+
self._retain(old.history(interrupted=True, now=now))
|
|
276
|
+
self.log(event="barge_in", generation=old.generation, merged=merge, resumed=resumed)
|
|
277
|
+
|
|
278
|
+
def _retain(self, messages):
|
|
279
|
+
if messages:
|
|
280
|
+
self.history.append(messages)
|
|
281
|
+
if self.recorder is not None:
|
|
282
|
+
self.recorder.record(messages)
|
|
283
|
+
|
|
284
|
+
def feed(self, seq, pcm):
|
|
285
|
+
self.session.append_audio(seq, pcm)
|
|
286
|
+
for event in self.boundary.feed(seq, pcm):
|
|
287
|
+
if event.kind in {"speech_started", "speech_resumed"}:
|
|
288
|
+
self._speech_started(event.kind == "speech_resumed")
|
|
289
|
+
elif event.kind == "draft" and self.turn is None:
|
|
290
|
+
self._draft(event.through_seq)
|
|
291
|
+
elif event.kind == "commit" and self.turn is not None and self.turn.committed_at is None:
|
|
292
|
+
turn = self.turn
|
|
293
|
+
turn.committed_at = time.monotonic()
|
|
294
|
+
if turn.password is not None:
|
|
295
|
+
self.tools.password_request = None
|
|
296
|
+
self.session.commit(turn.generation)
|
|
297
|
+
self.prefix = b""
|
|
298
|
+
self.speaking = False
|
|
299
|
+
self.log(event="turn_committed", generation=turn.generation)
|
|
300
|
+
if not self.speaking:
|
|
301
|
+
self.session.discard_before(max(0, seq + 1 - PREROLL_FRAMES))
|
|
302
|
+
|
|
303
|
+
def _event(self, turn, event):
|
|
304
|
+
if isinstance(event, NativeSpeechFrame):
|
|
305
|
+
if turn.prebuffer_started is None:
|
|
306
|
+
turn.prebuffer_started = time.monotonic()
|
|
307
|
+
if not turn.first_generated_pcm and np.any(np.abs(np.frombuffer(event.pcm, dtype="<i2").astype(np.int32)) > 30):
|
|
308
|
+
turn.first_generated_pcm = True
|
|
309
|
+
self.log(event="first_generated_pcm", generation=turn.generation,
|
|
310
|
+
after_turn_commit_s=round(time.monotonic() - turn.committed_at, 3))
|
|
311
|
+
turn.received += len(event.pcm)
|
|
312
|
+
self.pending_audio.extend(event.pcm)
|
|
313
|
+
return
|
|
314
|
+
if isinstance(event, NativeSpeechFailure):
|
|
315
|
+
turn.failed = True
|
|
316
|
+
return
|
|
317
|
+
if not turn.failed:
|
|
318
|
+
turn.close_segment()
|
|
319
|
+
if isinstance(event, NativeAssistantTurn):
|
|
320
|
+
message = event.as_message()
|
|
321
|
+
turn.messages.append(message)
|
|
322
|
+
if event.text:
|
|
323
|
+
turn.speech.append(_Speech(message, turn.received))
|
|
324
|
+
if event.calls:
|
|
325
|
+
self.log(event="tool_call", names=[call.name for call in event.calls], generation=turn.generation)
|
|
326
|
+
elif isinstance(event, NativeToolResult):
|
|
327
|
+
turn.messages.append(event.as_message())
|
|
328
|
+
self.log(event="tool_result", name=event.call.name, status=event.status, generation=turn.generation)
|
|
329
|
+
if event.call.name == THINKING_TOOL and event.status == "ok" and isinstance(event.data, dict):
|
|
330
|
+
self.progress_enabled = event.data.get("enabled") is True
|
|
331
|
+
if event.call.name == "terminal_session" and event.status == "ok" and isinstance(event.data, dict):
|
|
332
|
+
handle = event.data.get("terminal_password_prompt")
|
|
333
|
+
if isinstance(handle, str) and TERMINAL_HANDLE.fullmatch(handle):
|
|
334
|
+
turn.prompts.add(handle)
|
|
335
|
+
elif isinstance(event, AcousticTurnDone):
|
|
336
|
+
turn.ended = True
|
|
337
|
+
turn.failed |= event.status != "ok"
|
|
338
|
+
|
|
339
|
+
def play(self):
|
|
340
|
+
turn = self.turn
|
|
341
|
+
if turn is None or turn.committed_at is None:
|
|
342
|
+
return
|
|
343
|
+
while not turn.ended and (not self.pending_audio or (
|
|
344
|
+
self.player is None and len(self.pending_audio) < self.prebuffer_bytes
|
|
345
|
+
)):
|
|
346
|
+
output = self.session.receive(timeout=0)
|
|
347
|
+
if output is None:
|
|
348
|
+
break
|
|
349
|
+
if output.generation != turn.generation or isinstance(output.event, AcousticTurnCancelled):
|
|
350
|
+
continue
|
|
351
|
+
self._event(turn, output.event)
|
|
352
|
+
waited = turn.prebuffer_started is not None and time.monotonic() - turn.prebuffer_started >= 0.75
|
|
353
|
+
if self.pending_audio and (self.player is not None or turn.ended or waited
|
|
354
|
+
or len(self.pending_audio) >= self.prebuffer_bytes):
|
|
355
|
+
if self.player is None:
|
|
356
|
+
self._stop_progress()
|
|
357
|
+
self.player = self.start_player()
|
|
358
|
+
os.set_blocking(self.player.stdin.fileno(), False)
|
|
359
|
+
turn.playback_started = time.monotonic()
|
|
360
|
+
try:
|
|
361
|
+
written = os.write(self.player.stdin.fileno(), self.pending_audio)
|
|
362
|
+
except BlockingIOError:
|
|
363
|
+
return
|
|
364
|
+
except BrokenPipeError:
|
|
365
|
+
self._speech_started(False)
|
|
366
|
+
self.speaking = False
|
|
367
|
+
self.log(event="turn_failed", error_type="PlaybackPipeClosed")
|
|
368
|
+
return
|
|
369
|
+
if not turn.first_pcm and np.any(np.abs(np.frombuffer(
|
|
370
|
+
self.pending_audio[:written & ~1], dtype="<i2",
|
|
371
|
+
).astype(np.int32)) > 30):
|
|
372
|
+
turn.first_pcm = True
|
|
373
|
+
self.log(event="first_non_silent_pcm", generation=turn.generation, speaker_stream=True,
|
|
374
|
+
after_turn_commit_s=round(time.monotonic() - turn.committed_at, 3))
|
|
375
|
+
turn.submitted += written
|
|
376
|
+
del self.pending_audio[:written]
|
|
377
|
+
elif self.player is None:
|
|
378
|
+
self._play_progress(turn)
|
|
379
|
+
if turn.ended and self.player is not None and not self.pending_audio and not self.player.stdin.closed:
|
|
380
|
+
self.player.stdin.close()
|
|
381
|
+
if turn.ended and (self.player is None or self.player.poll() is not None):
|
|
382
|
+
self._stop_progress()
|
|
383
|
+
if not turn.failed and turn.first_pcm and (self.player is None or self.player.returncode == 0):
|
|
384
|
+
self._retain(turn.history())
|
|
385
|
+
if len(turn.prompts) == 1 and turn.messages and turn.messages[-1]["content"] == PASSWORD_REQUEST:
|
|
386
|
+
self.tools.password_request = next(iter(turn.prompts)), time.monotonic() + 75
|
|
387
|
+
self.log(event="turn_complete", generation=turn.generation, retained_turns=len(self.history))
|
|
388
|
+
else:
|
|
389
|
+
self._retain(turn.history(interrupted=True, now=time.monotonic()))
|
|
390
|
+
self.log(event="turn_failed", generation=turn.generation, error_type="DuplexTurnFailed")
|
|
391
|
+
self.player = None
|
|
392
|
+
self.session.playback_finished(turn.generation)
|
|
393
|
+
self.turn = None
|
|
394
|
+
|
|
395
|
+
|
|
396
|
+
def _capture_stream(source, channels, channel, loop, verify_route, ready):
|
|
397
|
+
command = ["parec", "--raw", "--device", source, "--format=s16le", "--rate=16000",
|
|
398
|
+
f"--channels={channels}", "--latency-msec=35", "--client-name=Phosphor microphone",
|
|
399
|
+
"--stream-name=Phosphor duplex input"]
|
|
400
|
+
with subprocess.Popen(command, stdout=subprocess.PIPE) as capture:
|
|
401
|
+
try:
|
|
402
|
+
size = INPUT_FRAME_BYTES * channels
|
|
403
|
+
seq, pending = 0, bytearray()
|
|
404
|
+
fd = capture.stdout.fileno()
|
|
405
|
+
last_capture = time.monotonic()
|
|
406
|
+
check_at = last_capture + 0.25
|
|
407
|
+
while True:
|
|
408
|
+
now = time.monotonic()
|
|
409
|
+
if now >= check_at:
|
|
410
|
+
verify_route(capture.pid)
|
|
411
|
+
check_at = now + 0.35
|
|
412
|
+
if select.select([fd], [], [], 0.015)[0]:
|
|
413
|
+
payload = os.read(fd, size - len(pending))
|
|
414
|
+
if not payload:
|
|
415
|
+
raise AudioRouteChanged("the microphone stream ended")
|
|
416
|
+
last_capture = time.monotonic()
|
|
417
|
+
pending.extend(payload)
|
|
418
|
+
if len(pending) == size:
|
|
419
|
+
pcm = bytes(pending) if channels == 1 else np.frombuffer(
|
|
420
|
+
pending, dtype="<i2").reshape(-1, channels)[:, channel].tobytes()
|
|
421
|
+
pending.clear()
|
|
422
|
+
if seq == 0:
|
|
423
|
+
ready()
|
|
424
|
+
loop.feed(seq, pcm)
|
|
425
|
+
seq += 1
|
|
426
|
+
elif now - last_capture >= 3:
|
|
427
|
+
raise AudioRouteChanged("the microphone stream stopped sending audio")
|
|
428
|
+
loop.play()
|
|
429
|
+
finally:
|
|
430
|
+
capture.terminate()
|
|
431
|
+
capture.wait(timeout=4)
|
|
432
|
+
|
|
433
|
+
|
|
434
|
+
def run_microphone(source, sink, channels, channel, vad, profile, runtime, embed, tools,
|
|
435
|
+
player, password_reply, log, ready, *, with_aec=True):
|
|
436
|
+
history = deque(maxlen=6)
|
|
437
|
+
if with_aec:
|
|
438
|
+
channels, channel = 1, 0
|
|
439
|
+
waiting = False
|
|
440
|
+
recording = EpisodeRecorder(tools, log) if profile.get("episodic_memory", False) else nullcontext()
|
|
441
|
+
with _stop_on_signal(), recording as recorder:
|
|
442
|
+
while True:
|
|
443
|
+
try:
|
|
444
|
+
physical = select_devices(source, sink)
|
|
445
|
+
with echo_cancel(*physical, with_aec) as (microphone, speaker):
|
|
446
|
+
vad.reset()
|
|
447
|
+
detector = SophonVoiceBoundaries(vad.stream_probabilities, start_ms=128)
|
|
448
|
+
try:
|
|
449
|
+
progress_enabled = tools.thinking_status()
|
|
450
|
+
except (httpx.HTTPError, ValueError):
|
|
451
|
+
progress_enabled = False
|
|
452
|
+
loop = DuplexVoice(profile, runtime, embed, tools, detector, lambda: player(speaker),
|
|
453
|
+
password_reply, log, history=history, recorder=recorder,
|
|
454
|
+
progress_enabled=progress_enabled)
|
|
455
|
+
|
|
456
|
+
def verify_route(pid):
|
|
457
|
+
sources = _inventory("sources")
|
|
458
|
+
if select_devices(source, sink, sources) != physical:
|
|
459
|
+
raise AudioRouteChanged("the selected audio device changed")
|
|
460
|
+
if restore_capture(pid, microphone, sources):
|
|
461
|
+
log(event="microphone_route_restored", source=microphone)
|
|
462
|
+
|
|
463
|
+
def listening():
|
|
464
|
+
nonlocal waiting
|
|
465
|
+
ready(*physical)
|
|
466
|
+
waiting = False
|
|
467
|
+
|
|
468
|
+
try:
|
|
469
|
+
_capture_stream(microphone, channels, channel, loop, verify_route, listening)
|
|
470
|
+
finally:
|
|
471
|
+
loop.close()
|
|
472
|
+
except AudioRouteChanged as error:
|
|
473
|
+
if not waiting:
|
|
474
|
+
log(event="microphone_reconnecting", reason=str(error))
|
|
475
|
+
waiting = True
|
|
476
|
+
time.sleep(0.5)
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
"""Persist settled voice history through the local adapter's episodic store."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
from queue import Empty, Full, Queue
|
|
5
|
+
from threading import Event, Thread
|
|
6
|
+
from uuid import uuid4
|
|
7
|
+
|
|
8
|
+
import httpx
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class EpisodeRecorder:
|
|
12
|
+
def __init__(self, tools, log):
|
|
13
|
+
self.tools = tools
|
|
14
|
+
self.log = log
|
|
15
|
+
self.pending = Queue(maxsize=16)
|
|
16
|
+
self.stop = Event()
|
|
17
|
+
self.worker = Thread(target=self._write, name="phosphor-episodic-recording", daemon=True)
|
|
18
|
+
|
|
19
|
+
def __enter__(self):
|
|
20
|
+
status = self.tools.memory_status()
|
|
21
|
+
if status.get("enabled") is not True:
|
|
22
|
+
raise RuntimeError("the configured voice episode store is disabled")
|
|
23
|
+
self.log(event="episodic_memory_ready", episodes=status.get("episodes", 0),
|
|
24
|
+
facts=status.get("facts", 0), cpu_embeddings=status.get("cpu_embeddings", False))
|
|
25
|
+
self.worker.start()
|
|
26
|
+
return self
|
|
27
|
+
|
|
28
|
+
def __exit__(self, *_):
|
|
29
|
+
self.stop.set()
|
|
30
|
+
self.worker.join(timeout=5)
|
|
31
|
+
|
|
32
|
+
def record(self, messages):
|
|
33
|
+
transcript = messages[0]["content"]
|
|
34
|
+
reply = " ".join(message["content"] for message in messages[1:]
|
|
35
|
+
if message["role"] == "assistant" and message.get("content"))
|
|
36
|
+
receipts = []
|
|
37
|
+
for message in messages[1:]:
|
|
38
|
+
if message["role"] == "tool":
|
|
39
|
+
receipt = json.loads(message["content"])
|
|
40
|
+
receipts.append({"name": message["name"], "ok": receipt.get("status") == "ok"})
|
|
41
|
+
if not transcript.strip():
|
|
42
|
+
return
|
|
43
|
+
try:
|
|
44
|
+
self.pending.put_nowait({"id": str(uuid4()), "transcript": transcript[:16_384], "reply": reply[:18_000],
|
|
45
|
+
"tools": receipts[:32]})
|
|
46
|
+
except Full:
|
|
47
|
+
self.log(event="episodic_memory_write_failed", error_type="QueueFull")
|
|
48
|
+
|
|
49
|
+
def _write(self):
|
|
50
|
+
while not self.stop.is_set() or not self.pending.empty():
|
|
51
|
+
try:
|
|
52
|
+
episode = self.pending.get(timeout=0.25)
|
|
53
|
+
except Empty:
|
|
54
|
+
continue
|
|
55
|
+
try:
|
|
56
|
+
if self.tools.remember_episode(episode).get("recorded") is not True:
|
|
57
|
+
raise ValueError("the episode store did not confirm the write")
|
|
58
|
+
except (httpx.HTTPError, RuntimeError, ValueError) as error:
|
|
59
|
+
self.log(event="episodic_memory_write_failed", error_type=type(error).__name__)
|