phosphor-harness 0.4.4 → 0.4.5

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.
@@ -0,0 +1,392 @@
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
+ import time
11
+
12
+ import numpy as np
13
+ from training_suite.models.native_turn import NativeAssistantTurn
14
+ from training_suite.sophon_acoustic_session import (
15
+ INPUT_FRAME_BYTES, AcousticTurnCancelled, AcousticTurnDone, AcousticTurnSession,
16
+ )
17
+ from training_suite.sophon_runtime import NativeSpeechFailure, NativeSpeechFrame, NativeToolResult
18
+ from training_suite.sophon_vad import SophonVoiceBoundaries
19
+
20
+ from .episode_recording import EpisodeRecorder
21
+ from .pulse_audio import AudioRouteChanged, _inventory, echo_cancel, restore_capture, select_devices
22
+ from .terminal_input import PASSWORD_REQUEST, TERMINAL_HANDLE
23
+
24
+
25
+ PLAYBACK_BYTES_PER_SECOND = 48_000
26
+ MERGE_WINDOW_SECONDS = 2.0
27
+ PREROLL_FRAMES = 20
28
+
29
+
30
+ @contextmanager
31
+ def _stop_on_signal():
32
+ def stop(_signal, _frame):
33
+ raise SystemExit(0)
34
+
35
+ previous = signal.signal(signal.SIGTERM, stop)
36
+ try:
37
+ yield
38
+ finally:
39
+ signal.signal(signal.SIGTERM, previous)
40
+
41
+
42
+ @dataclass
43
+ class _Speech:
44
+ message: dict
45
+ start: int
46
+ end: int | None = None
47
+
48
+ def heard(self, count):
49
+ if self.end is None or self.end <= self.start or count <= self.start:
50
+ return ""
51
+ text = self.message["content"]
52
+ if count >= self.end:
53
+ return text
54
+ cutoff = int(len(text) * (count - self.start) / (self.end - self.start))
55
+ return text[:cutoff].rsplit(" ", 1)[0] if " " in text[:cutoff] else ""
56
+
57
+
58
+ @dataclass
59
+ class _Turn:
60
+ number: int
61
+ prefix: bytes = b""
62
+ generation: int | None = None
63
+ committed_at: float | None = None
64
+ pcm: bytes = b""
65
+ heard: str = ""
66
+ password: tuple | None = None
67
+ launched_tools: bool = False
68
+ messages: list = field(default_factory=list)
69
+ speech: list = field(default_factory=list)
70
+ prompts: set = field(default_factory=set)
71
+ received: int = 0
72
+ submitted: int = 0
73
+ playback_started: float | None = None
74
+ prebuffer_started: float | None = None
75
+ first_generated_pcm: bool = False
76
+ first_pcm: bool = False
77
+ ended: bool = False
78
+ failed: bool = False
79
+
80
+ def close_segment(self):
81
+ if self.speech and self.speech[-1].end is None:
82
+ self.speech[-1].end = self.received
83
+
84
+ def history(self, interrupted=False, now=None):
85
+ if not self.heard or self.password is not None:
86
+ return []
87
+ user = {"role": "user", "content": self.heard}
88
+ if not interrupted:
89
+ return [user, *self.messages]
90
+ drained = 0 if self.playback_started is None else min(
91
+ self.submitted, max(0, int((now - self.playback_started - 0.20) * PLAYBACK_BYTES_PER_SECOND)),
92
+ )
93
+ segments = {id(segment.message): segment.heard(drained) for segment in self.speech}
94
+ results = {message["tool_call_id"] for message in self.messages if message["role"] == "tool"}
95
+ retained = [user]
96
+ allowed_results = set()
97
+ for message in self.messages:
98
+ if message["role"] == "tool":
99
+ if message["tool_call_id"] in allowed_results:
100
+ retained.append(message)
101
+ continue
102
+ calls = message.get("tool_calls") or ()
103
+ if calls and all(call["id"] in results for call in calls):
104
+ retained.append({**message, "content": segments.get(id(message), "")})
105
+ allowed_results.update(call["id"] for call in calls)
106
+ elif spoken := segments.get(id(message)):
107
+ retained.append({"role": "assistant", "content": spoken})
108
+ return retained
109
+
110
+
111
+ class DuplexVoice:
112
+ """Keep a single generation lane while input and speaker output remain independent."""
113
+
114
+ def __init__(self, profile, runtime, embed, tools, boundary, player, password_reply, log, *,
115
+ history=None, recorder=None):
116
+ self.profile, self.runtime, self.embed, self.tools = profile, runtime, embed, tools
117
+ self.boundary, self.start_player, self.password_reply, self.log = boundary, player, password_reply, log
118
+ self.history = history if history is not None else deque(maxlen=6)
119
+ self.recorder = recorder
120
+ self.turn = None
121
+ self.pending_audio = bytearray()
122
+ prebuffer_ms = profile.get("playback_prebuffer_ms", 500)
123
+ if type(prebuffer_ms) is not int or not 0 <= prebuffer_ms <= 1_000:
124
+ raise ValueError("playback_prebuffer_ms must be an integer between 0 and 1000")
125
+ self.prebuffer_bytes = prebuffer_ms * PLAYBACK_BYTES_PER_SECOND // 1_000
126
+ self.player = None
127
+ self.prefix = b""
128
+ self.speaking = False
129
+ self.number = 0
130
+ self.session = AcousticTurnSession(self._generate, lambda pcm, _cancel: pcm, max_output_events=8)
131
+
132
+ def close(self):
133
+ try:
134
+ self._stop_player()
135
+ finally:
136
+ self.session.close()
137
+
138
+ def _generate(self, messages, *, media, cancelled, await_commit):
139
+ turn = self.turn
140
+ if turn is None or turn.number != messages[-1].get("voice_turn"):
141
+ return
142
+ turn.pcm = (turn.prefix + media)[-960_000:]
143
+ with self.runtime.backplane.interruptible(cancelled):
144
+ if turn.password is not None:
145
+ if await_commit() and not cancelled.is_set():
146
+ reply = self.password_reply(turn.pcm, turn.password)
147
+ for pcm in self.runtime.speech.frames(reply, self.profile["language"], cancelled=cancelled):
148
+ yield NativeSpeechFrame(pcm)
149
+ return
150
+ user = {"role": "user", "content": ""}
151
+ model_audio = self.embed(turn.pcm, cancelled)
152
+ try:
153
+ for event in self.tools.run_committed_turn(
154
+ self.runtime, [*messages[:-1], user], media=model_audio, cancelled=cancelled,
155
+ await_commit=await_commit, max_new_tokens=self.profile["max_new_tokens"],
156
+ max_tool_rounds=self.runtime.backplane.tool_rounds, language=self.profile["language"],
157
+ ):
158
+ turn.heard = model_audio.user_text or ""
159
+ if isinstance(event, NativeAssistantTurn) and event.calls:
160
+ turn.launched_tools = True
161
+ yield event
162
+ finally:
163
+ turn.heard = model_audio.user_text or ""
164
+
165
+ def _draft(self, through):
166
+ self.number += 1
167
+ messages = [{"role": "system", "content": self.profile["system_prompt"]}]
168
+ for previous in self.history:
169
+ messages.extend(previous)
170
+ messages.append({"role": "user", "content": "", "voice_turn": self.number})
171
+ turn = self.turn = _Turn(self.number, self.prefix, password=self.tools.password_request)
172
+ turn.generation = self.session.speech_stopped(messages, through_seq=through)
173
+ self.log(event="draft_started", generation=turn.generation)
174
+
175
+ def _stop_player(self):
176
+ self.pending_audio.clear()
177
+ if self.player is None:
178
+ return
179
+ player, self.player = self.player, None
180
+ if player.poll() is None:
181
+ player.kill()
182
+ player.stdin.close()
183
+ player.wait(timeout=3)
184
+
185
+ def _speech_started(self, resumed):
186
+ old = self.turn
187
+ self.session.speech_started()
188
+ self.turn = None
189
+ self.speaking = True
190
+ if old is None:
191
+ return
192
+ if old.committed_at is None:
193
+ self.log(event="draft_revised", generation=old.generation)
194
+ return
195
+ now = time.monotonic()
196
+ self._stop_player()
197
+ merge = bool(old.password is None and old.pcm and not old.launched_tools
198
+ and now - old.committed_at < MERGE_WINDOW_SECONDS)
199
+ if merge:
200
+ self.prefix = old.pcm
201
+ else:
202
+ self._retain(old.history(interrupted=True, now=now))
203
+ self.log(event="barge_in", generation=old.generation, merged=merge, resumed=resumed)
204
+
205
+ def _retain(self, messages):
206
+ if messages:
207
+ self.history.append(messages)
208
+ if self.recorder is not None:
209
+ self.recorder.record(messages)
210
+
211
+ def feed(self, seq, pcm):
212
+ self.session.append_audio(seq, pcm)
213
+ for event in self.boundary.feed(seq, pcm):
214
+ if event.kind in {"speech_started", "speech_resumed"}:
215
+ self._speech_started(event.kind == "speech_resumed")
216
+ elif event.kind == "draft" and self.turn is None:
217
+ self._draft(event.through_seq)
218
+ elif event.kind == "commit" and self.turn is not None and self.turn.committed_at is None:
219
+ turn = self.turn
220
+ turn.committed_at = time.monotonic()
221
+ if turn.password is not None:
222
+ self.tools.password_request = None
223
+ self.session.commit(turn.generation)
224
+ self.prefix = b""
225
+ self.speaking = False
226
+ self.log(event="turn_committed", generation=turn.generation)
227
+ if not self.speaking:
228
+ self.session.discard_before(max(0, seq + 1 - PREROLL_FRAMES))
229
+
230
+ def _event(self, turn, event):
231
+ if isinstance(event, NativeSpeechFrame):
232
+ if turn.prebuffer_started is None:
233
+ turn.prebuffer_started = time.monotonic()
234
+ if not turn.first_generated_pcm and np.any(np.abs(np.frombuffer(event.pcm, dtype="<i2").astype(np.int32)) > 30):
235
+ turn.first_generated_pcm = True
236
+ self.log(event="first_generated_pcm", generation=turn.generation,
237
+ after_turn_commit_s=round(time.monotonic() - turn.committed_at, 3))
238
+ turn.received += len(event.pcm)
239
+ self.pending_audio.extend(event.pcm)
240
+ return
241
+ if isinstance(event, NativeSpeechFailure):
242
+ turn.failed = True
243
+ return
244
+ if not turn.failed:
245
+ turn.close_segment()
246
+ if isinstance(event, NativeAssistantTurn):
247
+ message = event.as_message()
248
+ turn.messages.append(message)
249
+ if event.text:
250
+ turn.speech.append(_Speech(message, turn.received))
251
+ if event.calls:
252
+ self.log(event="tool_call", names=[call.name for call in event.calls], generation=turn.generation)
253
+ elif isinstance(event, NativeToolResult):
254
+ turn.messages.append(event.as_message())
255
+ self.log(event="tool_result", name=event.call.name, status=event.status, generation=turn.generation)
256
+ if event.call.name == "terminal_session" and event.status == "ok" and isinstance(event.data, dict):
257
+ handle = event.data.get("terminal_password_prompt")
258
+ if isinstance(handle, str) and TERMINAL_HANDLE.fullmatch(handle):
259
+ turn.prompts.add(handle)
260
+ elif isinstance(event, AcousticTurnDone):
261
+ turn.ended = True
262
+ turn.failed |= event.status != "ok"
263
+
264
+ def play(self):
265
+ turn = self.turn
266
+ if turn is None or turn.committed_at is None:
267
+ return
268
+ while not turn.ended and (not self.pending_audio or (
269
+ self.player is None and len(self.pending_audio) < self.prebuffer_bytes
270
+ )):
271
+ output = self.session.receive(timeout=0)
272
+ if output is None:
273
+ break
274
+ if output.generation != turn.generation or isinstance(output.event, AcousticTurnCancelled):
275
+ continue
276
+ self._event(turn, output.event)
277
+ waited = turn.prebuffer_started is not None and time.monotonic() - turn.prebuffer_started >= 0.75
278
+ if self.pending_audio and (self.player is not None or turn.ended or waited
279
+ or len(self.pending_audio) >= self.prebuffer_bytes):
280
+ if self.player is None:
281
+ self.player = self.start_player()
282
+ os.set_blocking(self.player.stdin.fileno(), False)
283
+ turn.playback_started = time.monotonic()
284
+ try:
285
+ written = os.write(self.player.stdin.fileno(), self.pending_audio)
286
+ except BlockingIOError:
287
+ return
288
+ except BrokenPipeError:
289
+ self._speech_started(False)
290
+ self.speaking = False
291
+ self.log(event="turn_failed", error_type="PlaybackPipeClosed")
292
+ return
293
+ if not turn.first_pcm and np.any(np.abs(np.frombuffer(
294
+ self.pending_audio[:written & ~1], dtype="<i2",
295
+ ).astype(np.int32)) > 30):
296
+ turn.first_pcm = True
297
+ self.log(event="first_non_silent_pcm", generation=turn.generation, speaker_stream=True,
298
+ after_turn_commit_s=round(time.monotonic() - turn.committed_at, 3))
299
+ turn.submitted += written
300
+ del self.pending_audio[:written]
301
+ if turn.ended and self.player is not None and not self.pending_audio and not self.player.stdin.closed:
302
+ self.player.stdin.close()
303
+ if turn.ended and (self.player is None or self.player.poll() is not None):
304
+ if not turn.failed and turn.first_pcm and (self.player is None or self.player.returncode == 0):
305
+ self._retain(turn.history())
306
+ if len(turn.prompts) == 1 and turn.messages and turn.messages[-1]["content"] == PASSWORD_REQUEST:
307
+ self.tools.password_request = next(iter(turn.prompts)), time.monotonic() + 75
308
+ self.log(event="turn_complete", generation=turn.generation, retained_turns=len(self.history))
309
+ else:
310
+ self._retain(turn.history(interrupted=True, now=time.monotonic()))
311
+ self.log(event="turn_failed", generation=turn.generation, error_type="DuplexTurnFailed")
312
+ self.player = None
313
+ self.session.playback_finished(turn.generation)
314
+ self.turn = None
315
+
316
+
317
+ def _capture_stream(source, channels, channel, loop, verify_route, ready):
318
+ command = ["parec", "--raw", "--device", source, "--format=s16le", "--rate=16000",
319
+ f"--channels={channels}", "--latency-msec=35", "--client-name=Phosphor microphone",
320
+ "--stream-name=Phosphor duplex input"]
321
+ with subprocess.Popen(command, stdout=subprocess.PIPE) as capture:
322
+ try:
323
+ size = INPUT_FRAME_BYTES * channels
324
+ seq, pending = 0, bytearray()
325
+ fd = capture.stdout.fileno()
326
+ last_capture = time.monotonic()
327
+ check_at = last_capture + 0.25
328
+ while True:
329
+ now = time.monotonic()
330
+ if now >= check_at:
331
+ verify_route(capture.pid)
332
+ check_at = now + 0.35
333
+ if select.select([fd], [], [], 0.015)[0]:
334
+ payload = os.read(fd, size - len(pending))
335
+ if not payload:
336
+ raise AudioRouteChanged("the microphone stream ended")
337
+ last_capture = time.monotonic()
338
+ pending.extend(payload)
339
+ if len(pending) == size:
340
+ pcm = bytes(pending) if channels == 1 else np.frombuffer(
341
+ pending, dtype="<i2").reshape(-1, channels)[:, channel].tobytes()
342
+ pending.clear()
343
+ if seq == 0:
344
+ ready()
345
+ loop.feed(seq, pcm)
346
+ seq += 1
347
+ elif now - last_capture >= 3:
348
+ raise AudioRouteChanged("the microphone stream stopped sending audio")
349
+ loop.play()
350
+ finally:
351
+ capture.terminate()
352
+ capture.wait(timeout=4)
353
+
354
+
355
+ def run_microphone(source, sink, channels, channel, vad, profile, runtime, embed, tools,
356
+ player, password_reply, log, ready, *, with_aec=True):
357
+ history = deque(maxlen=6)
358
+ if with_aec:
359
+ channels, channel = 1, 0
360
+ waiting = False
361
+ recording = EpisodeRecorder(tools, log) if profile.get("episodic_memory", False) else nullcontext()
362
+ with _stop_on_signal(), recording as recorder:
363
+ while True:
364
+ try:
365
+ physical = select_devices(source, sink)
366
+ with echo_cancel(*physical, with_aec) as (microphone, speaker):
367
+ vad.reset()
368
+ detector = SophonVoiceBoundaries(vad.stream_probabilities, start_ms=128)
369
+ loop = DuplexVoice(profile, runtime, embed, tools, detector, lambda: player(speaker),
370
+ password_reply, log, history=history, recorder=recorder)
371
+
372
+ def verify_route(pid):
373
+ sources = _inventory("sources")
374
+ if select_devices(source, sink, sources) != physical:
375
+ raise AudioRouteChanged("the selected audio device changed")
376
+ if restore_capture(pid, microphone, sources):
377
+ log(event="microphone_route_restored", source=microphone)
378
+
379
+ def listening():
380
+ nonlocal waiting
381
+ ready(*physical)
382
+ waiting = False
383
+
384
+ try:
385
+ _capture_stream(microphone, channels, channel, loop, verify_route, listening)
386
+ finally:
387
+ loop.close()
388
+ except AudioRouteChanged as error:
389
+ if not waiting:
390
+ log(event="microphone_reconnecting", reason=str(error))
391
+ waiting = True
392
+ 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__)