phosphor-harness 0.0.0-stage → 0.4.0
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/LICENSE +201 -0
- package/README.md +134 -2
- package/bin/phosphor.cjs +24 -0
- package/ornith-profile.example.json +7 -0
- package/package.json +16 -4
- package/profile.example.json +11 -0
- package/pyproject.toml +15 -0
- package/quickstart.sh +305 -0
- package/requirements-orin-voice.txt +16 -0
- package/scripts/fetch_ornith_weights.py +40 -0
- package/scripts/fetch_phosphor.py +50 -0
- package/scripts/fetch_sources.py +45 -0
- package/scripts/phosphor-weights.sha256 +11 -0
- package/scripts/run_service.sh +74 -0
- package/sophon_harness/__init__.py +1 -0
- package/sophon_harness/cli.py +76 -0
- package/sophon_harness/news.py +96 -0
- package/sophon_harness/ornith.py +377 -0
- package/sophon_harness/playback_rearm.py +21 -0
- package/sophon_harness/portal_server.py +229 -0
- package/sophon_harness/talker.py +57 -0
- package/sophon_harness/terminal_input.py +124 -0
- package/sophon_harness/tools.py +288 -0
- package/sophon_harness/voice.py +371 -0
- package/sources.lock.json +79 -0
|
@@ -0,0 +1,288 @@
|
|
|
1
|
+
"""Discover and call the adapter's authoritative tool definitions."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import base64
|
|
6
|
+
import hashlib
|
|
7
|
+
import json
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
import re
|
|
10
|
+
from threading import Event
|
|
11
|
+
from urllib.parse import quote, urlsplit
|
|
12
|
+
|
|
13
|
+
import httpx
|
|
14
|
+
|
|
15
|
+
from .news import NEWS_TOOL, get_headlines
|
|
16
|
+
from .portal_server import read_token
|
|
17
|
+
|
|
18
|
+
CORE_TOOLS = (
|
|
19
|
+
"tool_search", "get_current_time", "get_user_location", "get_system_snapshot", "peripheral_inventory",
|
|
20
|
+
"safe_math_eval",
|
|
21
|
+
"memory_write", "memory_read", "memory_search", "get_news_headlines", "web_search", "web_fetch", "request_camera_view",
|
|
22
|
+
)
|
|
23
|
+
VOICE_TOOL_ROUNDS = 6
|
|
24
|
+
REPEATABLE_READS = frozenset({
|
|
25
|
+
"get_current_time", "get_system_snapshot", "get_user_location", "get_portal_capabilities",
|
|
26
|
+
"safe_math_eval", "memory_read", "memory_search", "document_search", "session_search",
|
|
27
|
+
"tool_search", "web_search", "web_fetch", "get_news_headlines", "peripheral_inventory",
|
|
28
|
+
})
|
|
29
|
+
MAX_RESPONSE = 24 * 1024 * 1024
|
|
30
|
+
MAX_RECEIPT = 12_000
|
|
31
|
+
_NAME = re.compile(r"[A-Za-z0-9_.-]{1,128}\Z")
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def current_turn(messages, audio_index):
|
|
35
|
+
user_index = audio_index if audio_index is not None else next(
|
|
36
|
+
(index for index in range(len(messages) - 1, -1, -1) if messages[index].get("role") == "user"), -1,
|
|
37
|
+
)
|
|
38
|
+
return messages[user_index + 1:]
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def active_tools(definitions, messages, audio_index):
|
|
42
|
+
"""Retain exact typed schemas revealed during the current committed turn."""
|
|
43
|
+
chosen = set(CORE_TOOLS)
|
|
44
|
+
for message in current_turn(messages, audio_index):
|
|
45
|
+
if message.get("role") != "tool":
|
|
46
|
+
continue
|
|
47
|
+
try:
|
|
48
|
+
envelope = json.loads(message.get("content", ""))
|
|
49
|
+
except (TypeError, ValueError):
|
|
50
|
+
continue
|
|
51
|
+
if not isinstance(envelope, dict):
|
|
52
|
+
continue
|
|
53
|
+
data = envelope.get("data")
|
|
54
|
+
if isinstance(data, dict):
|
|
55
|
+
if message.get("name") == "tool_search" and data.get("allowlisted_only") is True:
|
|
56
|
+
chosen.update(name for name in data.get("available_tools", []) if isinstance(name, str))
|
|
57
|
+
if envelope.get("status") == "error" and data.get("retry_mode") == "change_capability":
|
|
58
|
+
chosen.update(name for name in data.get("alternative_tools", []) if isinstance(name, str))
|
|
59
|
+
if message.get("name") == "peripheral_inventory" and envelope.get("status") == "ok":
|
|
60
|
+
chosen.update(("serial_io", "bluetooth_io", "network_io"))
|
|
61
|
+
return [item for item in definitions if item["function"]["name"] in chosen]
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _json(value) -> str:
|
|
65
|
+
return json.dumps(value, sort_keys=True, ensure_ascii=False, allow_nan=False)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _text_receipt(value, token: str):
|
|
69
|
+
if isinstance(value, str):
|
|
70
|
+
return value.replace(token, "[private token]")[:MAX_RECEIPT]
|
|
71
|
+
if isinstance(value, list):
|
|
72
|
+
return [_text_receipt(item, token) for item in value]
|
|
73
|
+
if isinstance(value, dict):
|
|
74
|
+
image = value.get("encoding") == "base64" or value.get("type") in {"image", "audio"}
|
|
75
|
+
return {
|
|
76
|
+
key: "[binary artifact]" if (image and key == "data") or key == "blob"
|
|
77
|
+
else _text_receipt(item, token)
|
|
78
|
+
for key, item in value.items()
|
|
79
|
+
}
|
|
80
|
+
return value
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
class PortalTools:
|
|
84
|
+
"""Use the authenticated tool API, independent of its language endpoint."""
|
|
85
|
+
|
|
86
|
+
def __init__(self, url: str, token_file: Path, *,
|
|
87
|
+
transport: httpx.BaseTransport | None = None, tool_timeout_s: float = 20):
|
|
88
|
+
origin = urlsplit(url)
|
|
89
|
+
if (origin.scheme != "http" or origin.hostname not in {"127.0.0.1", "::1", "localhost"}
|
|
90
|
+
or origin.username or origin.password or origin.query or origin.fragment
|
|
91
|
+
or origin.path not in {"", "/"}):
|
|
92
|
+
raise ValueError("connect the tool API through a local address")
|
|
93
|
+
self.token = read_token(token_file)
|
|
94
|
+
if not 0 < tool_timeout_s <= 295:
|
|
95
|
+
raise ValueError("tool_timeout_s must be between 0 and 295 seconds")
|
|
96
|
+
self.tool_timeout_s = tool_timeout_s
|
|
97
|
+
self.session = hashlib.sha256(b"omni-voice-session\0" + self.token.encode()).hexdigest()
|
|
98
|
+
self.password_request: tuple[str, float] | None = None
|
|
99
|
+
self.client = httpx.Client(
|
|
100
|
+
base_url=url, headers={"Authorization": f"Bearer {self.token}"},
|
|
101
|
+
cookies={"omni_portal_session": self.session},
|
|
102
|
+
follow_redirects=False, timeout=httpx.Timeout(tool_timeout_s, connect=min(tool_timeout_s, 5)),
|
|
103
|
+
trust_env=False, transport=transport,
|
|
104
|
+
)
|
|
105
|
+
self._definitions = self._discover()
|
|
106
|
+
|
|
107
|
+
def __enter__(self):
|
|
108
|
+
return self
|
|
109
|
+
|
|
110
|
+
def __exit__(self, *_):
|
|
111
|
+
self.client.close()
|
|
112
|
+
|
|
113
|
+
def _request(self, method: str, path: str, **kwargs) -> dict:
|
|
114
|
+
with self.client.stream(method, path, **kwargs) as response:
|
|
115
|
+
response.raise_for_status()
|
|
116
|
+
payload = bytearray()
|
|
117
|
+
for part in response.iter_bytes():
|
|
118
|
+
if len(payload) + len(part) > MAX_RESPONSE:
|
|
119
|
+
raise ValueError("tool response exceeded the byte limit")
|
|
120
|
+
payload.extend(part)
|
|
121
|
+
value = json.loads(payload)
|
|
122
|
+
if not isinstance(value, dict):
|
|
123
|
+
raise ValueError("the tool API returned an invalid response")
|
|
124
|
+
return value
|
|
125
|
+
|
|
126
|
+
def _discover(self) -> dict[str, dict]:
|
|
127
|
+
result = self._request("GET", "/api/tools")
|
|
128
|
+
tools = {}
|
|
129
|
+
for definition in result["tools"]:
|
|
130
|
+
function = definition["function"]
|
|
131
|
+
name = function["name"]
|
|
132
|
+
if (definition["type"] != "function" or not _NAME.fullmatch(name)
|
|
133
|
+
or name in tools or function["parameters"]["type"] != "object"):
|
|
134
|
+
raise ValueError("invalid or duplicate adapter tool definition")
|
|
135
|
+
tools[name] = definition
|
|
136
|
+
if "tool_search" not in tools:
|
|
137
|
+
raise ValueError("the tool API does not expose typed tool discovery")
|
|
138
|
+
tools.setdefault("get_news_headlines", NEWS_TOOL)
|
|
139
|
+
return tools
|
|
140
|
+
|
|
141
|
+
@property
|
|
142
|
+
def definitions(self) -> list[dict]:
|
|
143
|
+
return list(self._definitions.values())
|
|
144
|
+
|
|
145
|
+
def attach(self, path: Path) -> dict:
|
|
146
|
+
import mimetypes
|
|
147
|
+
|
|
148
|
+
with path.open("rb") as handle:
|
|
149
|
+
media = mimetypes.guess_type(path.name)[0] or "application/octet-stream"
|
|
150
|
+
return self._request("POST", "/api/harness/attachments",
|
|
151
|
+
files={"file": (path.name, handle, media)})
|
|
152
|
+
|
|
153
|
+
def set_location(self, location: dict | None) -> dict:
|
|
154
|
+
if location is None:
|
|
155
|
+
return self._request("DELETE", "/api/harness/location")
|
|
156
|
+
return self._request("POST", "/api/harness/location", json=location)
|
|
157
|
+
|
|
158
|
+
def submit_password(self, handle: str, password: str) -> bool:
|
|
159
|
+
try:
|
|
160
|
+
value = self._request("POST", "/api/harness/terminal-password",
|
|
161
|
+
json={"handle": handle, "password": password})
|
|
162
|
+
except (httpx.HTTPError, ValueError):
|
|
163
|
+
return False
|
|
164
|
+
return value.get("submitted") is True
|
|
165
|
+
|
|
166
|
+
def _camera_result(self, call, observe, question, cancelled):
|
|
167
|
+
from training_suite.sophon_runtime import NativeToolResult
|
|
168
|
+
|
|
169
|
+
if cancelled.is_set():
|
|
170
|
+
return NativeToolResult(call, "cancelled", None)
|
|
171
|
+
mode = call.arguments.get("mode", "still")
|
|
172
|
+
if observe is None:
|
|
173
|
+
result = self.invoke(call.name, call.arguments)
|
|
174
|
+
else:
|
|
175
|
+
try:
|
|
176
|
+
capture = self._request("POST", "/api/harness/camera", json={"mode": mode})
|
|
177
|
+
if cancelled.is_set():
|
|
178
|
+
return NativeToolResult(call, "cancelled", None)
|
|
179
|
+
if capture.get("ok") is False:
|
|
180
|
+
result = capture
|
|
181
|
+
else:
|
|
182
|
+
frame = capture["frame"]
|
|
183
|
+
encoded = frame["data"]
|
|
184
|
+
if frame["mime_type"] != "image/jpeg" or not isinstance(encoded, str):
|
|
185
|
+
raise ValueError("invalid camera MIME type")
|
|
186
|
+
raw = base64.b64decode(encoded, validate=True)
|
|
187
|
+
if not raw.startswith(b"\xff\xd8\xff") or len(raw) > 8 * 1024 * 1024:
|
|
188
|
+
raise ValueError("invalid camera frame")
|
|
189
|
+
image = {"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{encoded}"}}
|
|
190
|
+
evidence = observe(image, question())
|
|
191
|
+
if cancelled.is_set():
|
|
192
|
+
return NativeToolResult(call, "cancelled", None)
|
|
193
|
+
result = {"ok": True, "source": "live_local_camera", "camera_count": capture["camera_count"],
|
|
194
|
+
"visual_observation": evidence}
|
|
195
|
+
except (httpx.HTTPError, RuntimeError, KeyError, TypeError, ValueError):
|
|
196
|
+
result = {"ok": False, "error": "camera_view_failed",
|
|
197
|
+
"message": "A live camera image could not be inspected for this request."}
|
|
198
|
+
failure = self.failure_receipt(call.name, result)
|
|
199
|
+
return NativeToolResult(call, "error", failure) if failure else NativeToolResult(call, "ok", result)
|
|
200
|
+
|
|
201
|
+
def invoke(self, name: str, arguments: dict) -> dict:
|
|
202
|
+
if name not in self._definitions:
|
|
203
|
+
return {"ok": False, "error": "unknown_tool"}
|
|
204
|
+
if name == "get_news_headlines":
|
|
205
|
+
return get_headlines(arguments)
|
|
206
|
+
if name == "request_camera_view":
|
|
207
|
+
return {"ok": False, "error": "camera_requires_visual_session",
|
|
208
|
+
"message": "This camera request needs an active backplane with image input."}
|
|
209
|
+
try:
|
|
210
|
+
value = self._request("POST", f"/api/tools/{quote(name, safe='')}/call",
|
|
211
|
+
json={"arguments": arguments})["result"]
|
|
212
|
+
if not isinstance(value, dict):
|
|
213
|
+
raise ValueError("expected an object tool receipt")
|
|
214
|
+
receipt = _text_receipt(value, self.token)
|
|
215
|
+
serialized = _json(receipt)
|
|
216
|
+
if len(serialized) > MAX_RECEIPT:
|
|
217
|
+
# Keep executor status and routing information even when output is large.
|
|
218
|
+
bounded = {key: receipt[key] for key in (
|
|
219
|
+
"ok", "error", "message", "exit_code", "timed_out", "available",
|
|
220
|
+
"retryable", "disposition", "alternative_tools", "failure_scope",
|
|
221
|
+
) if key in receipt}
|
|
222
|
+
bounded.update(truncated=True, receipt_preview=serialized[: MAX_RECEIPT // 3])
|
|
223
|
+
return bounded
|
|
224
|
+
return receipt
|
|
225
|
+
except httpx.HTTPStatusError as failure:
|
|
226
|
+
status = failure.response.status_code
|
|
227
|
+
return {"ok": False, "error": "tool_http_error", "http_status": status,
|
|
228
|
+
"retryable": status in {429, 502, 503, 504}}
|
|
229
|
+
except (httpx.ConnectError, httpx.TimeoutException):
|
|
230
|
+
return {
|
|
231
|
+
"ok": False, "error": "tool_transport_unavailable", "retryable": True,
|
|
232
|
+
"message": "The tool portal did not return a result. The operation may already have run.",
|
|
233
|
+
}
|
|
234
|
+
except (httpx.HTTPError, KeyError, ValueError):
|
|
235
|
+
return {"ok": False, "error": "tool_request_failed"}
|
|
236
|
+
|
|
237
|
+
def failure_receipt(self, name: str, result: dict) -> dict | None:
|
|
238
|
+
result = dict(result)
|
|
239
|
+
if name == "get_user_location" and result.get("available") is False:
|
|
240
|
+
result["error"] = "location_unavailable"
|
|
241
|
+
if name == "shell" and (result.get("timed_out") or result.get("exit_code", 0) != 0):
|
|
242
|
+
result.setdefault("error", "shell_timeout" if result.get("timed_out") else "shell_exit_nonzero")
|
|
243
|
+
if result.get("ok") is not False and not result.get("error"):
|
|
244
|
+
return None
|
|
245
|
+
error = result.get("error")
|
|
246
|
+
alternatives = result.get("alternative_tools")
|
|
247
|
+
if not isinstance(alternatives, list):
|
|
248
|
+
alternatives = []
|
|
249
|
+
result["alternative_tools"] = [tool for tool in alternatives
|
|
250
|
+
if isinstance(tool, str) and tool in self._definitions]
|
|
251
|
+
if error == "location_unavailable":
|
|
252
|
+
mode = "needs_location"
|
|
253
|
+
elif result["alternative_tools"] and result.get("disposition") == "change_capability":
|
|
254
|
+
mode = "change_capability"
|
|
255
|
+
elif name in REPEATABLE_READS and result.get("retryable") is True:
|
|
256
|
+
mode = "repeat_read_once"
|
|
257
|
+
elif error == "ToolInputError" or (name == "shell" and error == "shell_exit_nonzero"
|
|
258
|
+
and result.get("intent") in {"inspect", "verify"}):
|
|
259
|
+
mode = "correct_arguments"
|
|
260
|
+
else:
|
|
261
|
+
mode = "report_failure"
|
|
262
|
+
result["retry_mode"] = mode
|
|
263
|
+
return result
|
|
264
|
+
|
|
265
|
+
def dispatch(self, call, cancelled: Event):
|
|
266
|
+
from training_suite.sophon_runtime import NativeToolResult
|
|
267
|
+
|
|
268
|
+
if cancelled.is_set():
|
|
269
|
+
return NativeToolResult(call, "cancelled", None)
|
|
270
|
+
result = self.invoke(call.name, call.arguments)
|
|
271
|
+
failure = self.failure_receipt(call.name, result)
|
|
272
|
+
return NativeToolResult(call, "error", failure) if failure else NativeToolResult(call, "ok", result)
|
|
273
|
+
|
|
274
|
+
def run_committed_turn(self, runtime, messages, **options):
|
|
275
|
+
options.setdefault("tool_timeout_s", self.tool_timeout_s + 2)
|
|
276
|
+
observe = getattr(runtime.backplane, "observe_camera", None)
|
|
277
|
+
media = options.get("media")
|
|
278
|
+
|
|
279
|
+
def dispatch(call, cancelled):
|
|
280
|
+
if call.name == "request_camera_view":
|
|
281
|
+
return self._camera_result(
|
|
282
|
+
call, observe, lambda: getattr(media, "user_text", None) or messages[-1]["content"], cancelled,
|
|
283
|
+
)
|
|
284
|
+
return self.dispatch(call, cancelled)
|
|
285
|
+
|
|
286
|
+
yield from runtime.run_committed_turn(
|
|
287
|
+
messages, tools=self.definitions, dispatch=dispatch, **options,
|
|
288
|
+
)
|
|
@@ -0,0 +1,371 @@
|
|
|
1
|
+
"""Feed microphone turns into a structured backplane and the original Talker."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections import deque
|
|
6
|
+
import inspect
|
|
7
|
+
import json
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
import re
|
|
10
|
+
import subprocess
|
|
11
|
+
from threading import Event
|
|
12
|
+
import time
|
|
13
|
+
|
|
14
|
+
import numpy as np
|
|
15
|
+
import onnxruntime as ort
|
|
16
|
+
from scipy.signal import resample_poly
|
|
17
|
+
import soundfile as sf
|
|
18
|
+
import torch
|
|
19
|
+
from jsonschema import ValidationError
|
|
20
|
+
from training_suite.models.backplane import NativeAudioBackplane
|
|
21
|
+
from training_suite.models.native_turn import NativeAssistantTurn, decode_native_turn
|
|
22
|
+
from training_suite.sophon_native_server import load_acoustic_stack, read_profile
|
|
23
|
+
import training_suite.sophon_native_server as native_server
|
|
24
|
+
from training_suite.sophon_runtime import NativeSpeechFailure, NativeSpeechFrame, NativeToolResult, NativeTurnRuntime
|
|
25
|
+
from training_suite.sophon_speech import SophonSpeech
|
|
26
|
+
from training_suite.training.omni_encoder_bridge import PackedLanguageInputs
|
|
27
|
+
|
|
28
|
+
from .playback_rearm import PlaybackRearm
|
|
29
|
+
from .terminal_input import PASSWORD_REQUEST, TERMINAL_HANDLE, spoken_password
|
|
30
|
+
from .tools import VOICE_TOOL_ROUNDS, PortalTools, active_tools
|
|
31
|
+
|
|
32
|
+
RATE = 16_000
|
|
33
|
+
FRAME = 512
|
|
34
|
+
_MARKER = re.compile(r"\ufdd0([0-9]+)\ufdd1")
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def log(**fields):
|
|
38
|
+
print(json.dumps(fields), flush=True)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class SpeechDetector:
|
|
42
|
+
def __init__(self, model: Path):
|
|
43
|
+
options = ort.SessionOptions()
|
|
44
|
+
options.intra_op_num_threads = options.inter_op_num_threads = 1
|
|
45
|
+
self.session = ort.InferenceSession(str(model), sess_options=options, providers=["CPUExecutionProvider"])
|
|
46
|
+
self.reset()
|
|
47
|
+
|
|
48
|
+
def reset(self):
|
|
49
|
+
self.state = np.zeros((2, 1, 128), dtype=np.float32)
|
|
50
|
+
self.context = np.zeros(64, dtype=np.float32)
|
|
51
|
+
|
|
52
|
+
def probability(self, audio) -> float:
|
|
53
|
+
signal = np.concatenate((self.context, audio))[None, :]
|
|
54
|
+
score, self.state = self.session.run(None, {
|
|
55
|
+
"input": signal, "state": self.state, "sr": np.array(RATE, dtype=np.int64),
|
|
56
|
+
})
|
|
57
|
+
self.context = audio[-64:].copy()
|
|
58
|
+
return float(score[0, 0])
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def capture_turn(source: str, vad: SpeechDetector, channels: int, channel: int, *, after_playback=False,
|
|
62
|
+
ready=None):
|
|
63
|
+
command = [
|
|
64
|
+
"parec", "--raw", "--device", source, "--format=s16le", f"--rate={RATE}",
|
|
65
|
+
f"--channels={channels}", "--latency-msec=35",
|
|
66
|
+
]
|
|
67
|
+
with subprocess.Popen(command, stdout=subprocess.PIPE) as capture:
|
|
68
|
+
try:
|
|
69
|
+
vad.reset()
|
|
70
|
+
rearm = PlaybackRearm() if after_playback else None
|
|
71
|
+
lead = deque(maxlen=10)
|
|
72
|
+
speech = []
|
|
73
|
+
voiced = quiet = 0
|
|
74
|
+
frame_size = FRAME * channels * 2
|
|
75
|
+
while raw := capture.stdout.read(frame_size):
|
|
76
|
+
if len(raw) != frame_size:
|
|
77
|
+
break
|
|
78
|
+
if ready is not None:
|
|
79
|
+
ready()
|
|
80
|
+
ready = None
|
|
81
|
+
mono = np.frombuffer(raw, dtype="<i2").reshape(FRAME, channels)[:, channel]
|
|
82
|
+
audio = mono.astype(np.float32) / 32768
|
|
83
|
+
probability = vad.probability(audio)
|
|
84
|
+
if rearm is not None:
|
|
85
|
+
if rearm.advance(probability):
|
|
86
|
+
log(event="microphone_rearmed", delay_ms=rearm.frames_seen * FRAME * 1000 // RATE)
|
|
87
|
+
rearm = None
|
|
88
|
+
continue
|
|
89
|
+
if not speech:
|
|
90
|
+
lead.append(audio)
|
|
91
|
+
voiced = voiced + 1 if probability >= 0.6 else 0
|
|
92
|
+
if voiced >= 5:
|
|
93
|
+
speech.extend(lead)
|
|
94
|
+
log(event="speech_detected")
|
|
95
|
+
continue
|
|
96
|
+
speech.append(audio)
|
|
97
|
+
quiet = quiet + 1 if probability < 0.38 else 0
|
|
98
|
+
if quiet >= 15 or len(speech) >= 625:
|
|
99
|
+
return np.concatenate(speech)
|
|
100
|
+
finally:
|
|
101
|
+
capture.terminate()
|
|
102
|
+
capture.wait(timeout=4)
|
|
103
|
+
raise RuntimeError("microphone capture ended")
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def configure_orin(memory_limit_mib: int):
|
|
107
|
+
if torch.cuda.device_count() != 1 or torch.cuda.get_device_capability(0) != (8, 7):
|
|
108
|
+
raise RuntimeError("the Orin profile requires one SM87 CUDA device")
|
|
109
|
+
capacity = torch.cuda.get_device_properties(0).total_memory
|
|
110
|
+
if not 0 < memory_limit_mib * 1024**2 <= capacity:
|
|
111
|
+
raise ValueError("invalid Orin CUDA memory limit")
|
|
112
|
+
torch.cuda.set_per_process_memory_fraction(memory_limit_mib * 1024**2 / capacity, device=0)
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def configure_encoder_compatibility():
|
|
116
|
+
from transformers.models.qwen3_omni_moe.modeling_qwen3_omni_moe import Qwen3OmniMoeAudioEncoder
|
|
117
|
+
|
|
118
|
+
forward = Qwen3OmniMoeAudioEncoder.forward
|
|
119
|
+
parameters = inspect.signature(forward).parameters
|
|
120
|
+
if "return_dict" not in parameters and not any(
|
|
121
|
+
parameter.kind is inspect.Parameter.VAR_KEYWORD for parameter in parameters.values()
|
|
122
|
+
):
|
|
123
|
+
def compatible_forward(self, *args, return_dict=None, **kwargs):
|
|
124
|
+
return forward(self, *args, **kwargs)
|
|
125
|
+
Qwen3OmniMoeAudioEncoder.forward = compatible_forward
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
class VoiceBackplane(NativeAudioBackplane):
|
|
129
|
+
"""Retain bounded acoustic spans and render only the active tool schemas."""
|
|
130
|
+
|
|
131
|
+
prior_audio = ()
|
|
132
|
+
|
|
133
|
+
def pack(self, messages, media=None, *, tools=None, audio_index=None):
|
|
134
|
+
if not self.prior_audio or media is None:
|
|
135
|
+
return super().pack(messages, media, tools=tools, audio_index=audio_index)
|
|
136
|
+
positions = {**dict(self.prior_audio), audio_index: media}
|
|
137
|
+
rendered_messages = [
|
|
138
|
+
{**message, "content": f"\ufdd0{index}\ufdd1\n" + message["content"]}
|
|
139
|
+
if index in positions else message
|
|
140
|
+
for index, message in enumerate(messages)
|
|
141
|
+
]
|
|
142
|
+
text = self.tokenizer.apply_chat_template(
|
|
143
|
+
rendered_messages, tools=tools, tokenize=False, add_generation_prompt=True,
|
|
144
|
+
)
|
|
145
|
+
markers = list(_MARKER.finditer(text))
|
|
146
|
+
if [int(marker.group(1)) for marker in markers] != sorted(positions):
|
|
147
|
+
raise ValueError("the native chat template moved an audio span")
|
|
148
|
+
table = self.model.get_input_embeddings()
|
|
149
|
+
device = table.weight.device
|
|
150
|
+
embedding_parts, mask_parts = [], []
|
|
151
|
+
|
|
152
|
+
def append_text(segment):
|
|
153
|
+
ids = self.tokenizer.encode(segment, add_special_tokens=False, return_tensors="pt").to(device)
|
|
154
|
+
embedding_parts.append(table(ids))
|
|
155
|
+
mask_parts.append(torch.ones_like(ids, dtype=torch.bool))
|
|
156
|
+
|
|
157
|
+
offset = 0
|
|
158
|
+
for marker in markers:
|
|
159
|
+
append_text(text[offset:marker.start()])
|
|
160
|
+
span = positions[int(marker.group(1))]
|
|
161
|
+
embedding_parts.append(span.embeddings.to(device=device, dtype=table.weight.dtype))
|
|
162
|
+
mask_parts.append(span.attention_mask.to(device=device, dtype=torch.bool))
|
|
163
|
+
offset = marker.end()
|
|
164
|
+
append_text(text[offset:])
|
|
165
|
+
return PackedLanguageInputs(torch.cat(embedding_parts, dim=1), torch.cat(mask_parts, dim=1), None)
|
|
166
|
+
|
|
167
|
+
def complete_turn(self, messages, *, media=None, tools=None, audio_index=None,
|
|
168
|
+
max_new_tokens, cancelled):
|
|
169
|
+
allowed = active_tools(tools or [], messages, audio_index)
|
|
170
|
+
with torch.inference_mode():
|
|
171
|
+
packed = self.pack(messages, media, tools=allowed, audio_index=audio_index)
|
|
172
|
+
ids = self.generate(packed, max_new_tokens=max_new_tokens, cancelled=cancelled)
|
|
173
|
+
raw = self.tokenizer.decode(ids[0], skip_special_tokens=False, clean_up_tokenization_spaces=False)
|
|
174
|
+
if cancelled.is_set():
|
|
175
|
+
return None
|
|
176
|
+
turn = decode_native_turn(self.signature.architecture, raw)
|
|
177
|
+
names = {item["function"]["name"] for item in allowed}
|
|
178
|
+
if any(call.name not in names for call in turn.calls):
|
|
179
|
+
raise ValueError("the model requested a tool outside its current catalog")
|
|
180
|
+
return turn
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def read_wave(path: Path):
|
|
184
|
+
audio, rate = sf.read(path, dtype="float32")
|
|
185
|
+
if audio.ndim != 1:
|
|
186
|
+
raise ValueError("use a mono WAV for replay")
|
|
187
|
+
return resample_poly(audio, RATE, rate).astype(np.float32)
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def pcm16(audio):
|
|
191
|
+
return (np.clip(audio, -1, 32767 / 32768) * 32768).astype("<i2").tobytes()
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def start_player(sink):
|
|
195
|
+
return subprocess.Popen(
|
|
196
|
+
["pacat", "--raw", "--playback", "--device", sink, "--format=s16le",
|
|
197
|
+
"--rate=24000", "--channels=1", "--latency-msec=65", "--client-name=Sophon standalone"],
|
|
198
|
+
stdin=subprocess.PIPE,
|
|
199
|
+
)
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def respond_to_password(audio, pending, runtime, tools, language, sink):
|
|
203
|
+
handle, deadline = pending
|
|
204
|
+
if time.monotonic() > deadline:
|
|
205
|
+
status = "The password input expired. Ask me to check the terminal again."
|
|
206
|
+
else:
|
|
207
|
+
try:
|
|
208
|
+
password = spoken_password(runtime.backplane.recognize_password(pcm16(audio)))
|
|
209
|
+
if password is None:
|
|
210
|
+
status = "Password entry cancelled."
|
|
211
|
+
elif tools.submit_password(handle, password):
|
|
212
|
+
status = "I sent the password to the terminal. Ask me to check what happened next."
|
|
213
|
+
else:
|
|
214
|
+
status = "I couldn't confirm password submission. Ask me to check the terminal."
|
|
215
|
+
except (RuntimeError, OSError, ValueError):
|
|
216
|
+
status = "I couldn't transcribe the password. Ask me to check the terminal again."
|
|
217
|
+
player = start_player(sink)
|
|
218
|
+
try:
|
|
219
|
+
for frame in runtime.speech.frames(status, language):
|
|
220
|
+
player.stdin.write(frame)
|
|
221
|
+
finally:
|
|
222
|
+
player.stdin.close()
|
|
223
|
+
if player.wait(timeout=12) != 0:
|
|
224
|
+
raise RuntimeError("speaker playback failed")
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def conduct_turn(audio, history, profile, runtime, embed, tools, *, sink=None, fixture=None):
|
|
228
|
+
start = time.monotonic()
|
|
229
|
+
cancel = Event()
|
|
230
|
+
media = embed(pcm16(audio), cancel)
|
|
231
|
+
messages = [{"role": "system", "content": profile["system_prompt"]}]
|
|
232
|
+
prior_audio = []
|
|
233
|
+
for earlier_audio, earlier_messages in history:
|
|
234
|
+
prior_audio.append((len(messages), earlier_audio))
|
|
235
|
+
messages.extend(earlier_messages)
|
|
236
|
+
user = {"role": "user", "content": ""}
|
|
237
|
+
messages.append(user)
|
|
238
|
+
transcript = [user]
|
|
239
|
+
runtime.backplane.prior_audio = prior_audio
|
|
240
|
+
first = player = None
|
|
241
|
+
reply = ""
|
|
242
|
+
results = []
|
|
243
|
+
password_prompts = set()
|
|
244
|
+
tools.password_request = None
|
|
245
|
+
try:
|
|
246
|
+
for event in tools.run_committed_turn(
|
|
247
|
+
runtime, messages, media=media, cancelled=cancel,
|
|
248
|
+
max_new_tokens=profile["max_new_tokens"], max_tool_rounds=VOICE_TOOL_ROUNDS,
|
|
249
|
+
language=profile["language"],
|
|
250
|
+
):
|
|
251
|
+
if isinstance(event, NativeAssistantTurn):
|
|
252
|
+
transcript.append(event.as_message())
|
|
253
|
+
if event.calls:
|
|
254
|
+
log(event="tool_call", names=[call.name for call in event.calls], fixture=fixture)
|
|
255
|
+
else:
|
|
256
|
+
reply = event.text
|
|
257
|
+
elif isinstance(event, NativeToolResult):
|
|
258
|
+
if event.call.name == "terminal_session" and event.status == "ok" and isinstance(event.data, dict):
|
|
259
|
+
handle = event.data.get("terminal_password_prompt")
|
|
260
|
+
if isinstance(handle, str) and TERMINAL_HANDLE.fullmatch(handle):
|
|
261
|
+
password_prompts.add(handle)
|
|
262
|
+
transcript.append(event.as_message())
|
|
263
|
+
results.append({"name": event.call.name, "status": event.status})
|
|
264
|
+
error_code = event.data.get("error") if event.status == "error" and isinstance(event.data, dict) else None
|
|
265
|
+
fields = {"error_code": error_code} if isinstance(error_code, str) and re.fullmatch(
|
|
266
|
+
r"[A-Za-z_]{1,64}", error_code,
|
|
267
|
+
) else {}
|
|
268
|
+
log(event="tool_result", name=event.call.name, status=event.status, fixture=fixture, **fields)
|
|
269
|
+
elif isinstance(event, NativeSpeechFailure):
|
|
270
|
+
raise RuntimeError(event.message)
|
|
271
|
+
elif isinstance(event, NativeSpeechFrame):
|
|
272
|
+
payload = event.pcm
|
|
273
|
+
if first is None and len(payload) and np.max(np.abs(np.frombuffer(payload, dtype="<i2").astype(np.int32))) > 30:
|
|
274
|
+
first = round(time.monotonic() - start, 3)
|
|
275
|
+
log(event="first_non_silent_pcm", after_turn_commit_s=first,
|
|
276
|
+
speaker_stream=bool(sink), fixture=fixture)
|
|
277
|
+
if sink:
|
|
278
|
+
if player is None:
|
|
279
|
+
player = start_player(sink)
|
|
280
|
+
player.stdin.write(payload)
|
|
281
|
+
finally:
|
|
282
|
+
cancel.set()
|
|
283
|
+
runtime.backplane.prior_audio = ()
|
|
284
|
+
if player is not None:
|
|
285
|
+
player.stdin.close()
|
|
286
|
+
if player.wait(timeout=12) != 0:
|
|
287
|
+
raise RuntimeError("speaker playback failed")
|
|
288
|
+
if not reply.strip() or first is None:
|
|
289
|
+
raise RuntimeError("turn produced no audible final response")
|
|
290
|
+
if reply == PASSWORD_REQUEST and len(password_prompts) == 1:
|
|
291
|
+
tools.password_request = next(iter(password_prompts)), time.monotonic() + 75
|
|
292
|
+
history.append((media, transcript))
|
|
293
|
+
return reply, results
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
def start(args):
|
|
297
|
+
if args.ornith_url:
|
|
298
|
+
from .ornith import AudioTurn, OrnithBackplane, image_part
|
|
299
|
+
|
|
300
|
+
profile = json.loads(args.profile.read_text(encoding="utf-8"))
|
|
301
|
+
|
|
302
|
+
def embed(pcm, _cancel):
|
|
303
|
+
return AudioTurn(pcm, image=image_part(args.image) if args.image is not None else None)
|
|
304
|
+
|
|
305
|
+
with OrnithBackplane(args.ornith_url, args.ornith_model) as backplane:
|
|
306
|
+
run_voice(args, profile, backplane, embed, {
|
|
307
|
+
"backplane": args.ornith_model, "audio_path": "trained_transcript_bridge",
|
|
308
|
+
"image_attached": args.image is not None,
|
|
309
|
+
})
|
|
310
|
+
return
|
|
311
|
+
if args.orin:
|
|
312
|
+
native_server.configure_scoped_cuda = configure_orin
|
|
313
|
+
configure_encoder_compatibility()
|
|
314
|
+
torch.set_num_threads(2)
|
|
315
|
+
profile = read_profile(args.profile)
|
|
316
|
+
backplane, embed, metadata = load_acoustic_stack(profile, args.memory_mib)
|
|
317
|
+
if backplane.signature.architecture != "qwen3":
|
|
318
|
+
raise ValueError("the acoustic history profile requires a Qwen3 backplane")
|
|
319
|
+
backplane = VoiceBackplane(backplane.model, backplane.tokenizer)
|
|
320
|
+
run_voice(args, profile, backplane, embed, metadata)
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
def run_voice(args, profile, backplane, embed, metadata):
|
|
324
|
+
runtime = NativeTurnRuntime(backplane, SophonSpeech(profile["speech_worker_url"], voice=profile.get("voice")))
|
|
325
|
+
replay_history = deque(maxlen=6)
|
|
326
|
+
with PortalTools(args.tools_url, args.token_file, tool_timeout_s=profile.get("tool_timeout_s", 20)) as tools:
|
|
327
|
+
log(event="voice_ready", catalog_size=len(tools.definitions), **metadata)
|
|
328
|
+
for path in args.probe:
|
|
329
|
+
try:
|
|
330
|
+
history = replay_history if args.probe_history else deque(maxlen=6)
|
|
331
|
+
reply, results = conduct_turn(read_wave(path), history, profile, runtime,
|
|
332
|
+
embed, tools, fixture=path.name)
|
|
333
|
+
except (RuntimeError, OSError, ValueError, ValidationError) as error:
|
|
334
|
+
log(event="fixture_failed", fixture=path.name, error_type=type(error).__name__)
|
|
335
|
+
continue
|
|
336
|
+
log(event="fixture_complete", fixture=path.name, reply=reply, tools=results)
|
|
337
|
+
if args.probe_only:
|
|
338
|
+
return
|
|
339
|
+
source = args.source or subprocess.check_output(["pactl", "get-default-source"], text=True).strip()
|
|
340
|
+
sink = args.sink or subprocess.check_output(["pactl", "get-default-sink"], text=True).strip()
|
|
341
|
+
vad = SpeechDetector(args.vad)
|
|
342
|
+
history = deque(maxlen=6)
|
|
343
|
+
after_playback = False
|
|
344
|
+
ready_file = getattr(args, "ready_file", None)
|
|
345
|
+
if ready_file is not None:
|
|
346
|
+
with start_player(sink) as player:
|
|
347
|
+
player.communicate(input=bytes(960), timeout=10)
|
|
348
|
+
if player.returncode:
|
|
349
|
+
raise RuntimeError("speaker playback could not start")
|
|
350
|
+
|
|
351
|
+
def listening():
|
|
352
|
+
log(event="listening", source=source, sink=sink)
|
|
353
|
+
if ready_file is not None:
|
|
354
|
+
ready_file.touch()
|
|
355
|
+
|
|
356
|
+
first_capture = listening
|
|
357
|
+
while True:
|
|
358
|
+
audio = capture_turn(source, vad, args.channels, args.channel, after_playback=after_playback,
|
|
359
|
+
ready=first_capture)
|
|
360
|
+
first_capture = None
|
|
361
|
+
after_playback = True
|
|
362
|
+
try:
|
|
363
|
+
if tools.password_request is not None:
|
|
364
|
+
pending, tools.password_request = tools.password_request, None
|
|
365
|
+
respond_to_password(audio, pending, runtime, tools, profile["language"], sink)
|
|
366
|
+
continue
|
|
367
|
+
conduct_turn(audio, history, profile, runtime, embed, tools, sink=sink)
|
|
368
|
+
except (RuntimeError, OSError, ValueError, ValidationError) as error:
|
|
369
|
+
log(event="turn_failed", error_type=type(error).__name__)
|
|
370
|
+
continue
|
|
371
|
+
log(event="turn_complete", retained_turns=len(history))
|