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.
- package/README.md +27 -4
- package/package.json +33 -10
- 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 +392 -0
- package/sophon_harness/episode_recording.py +59 -0
- package/sophon_harness/ornith.py +596 -20
- package/sophon_harness/portal_server.py +87 -3
- package/sophon_harness/pulse_audio.py +77 -0
- package/sophon_harness/regex_tools.py +337 -0
- package/sophon_harness/tools.py +52 -12
- package/sophon_harness/voice.py +46 -16
package/sophon_harness/tools.py
CHANGED
|
@@ -14,6 +14,7 @@ import httpx
|
|
|
14
14
|
|
|
15
15
|
from .news import NEWS_TOOL, get_headlines
|
|
16
16
|
from .portal_server import read_token
|
|
17
|
+
from .regex_tools import REGEX_BUILD_TOOL, REGEX_EXAMPLE_TOOL, REGEX_FIELDS_TOOL, build_regex, infer_workspace_field_regex, read_regex_example
|
|
17
18
|
from .wifi import WIFI_SCAN_TOOL, wifi_observation
|
|
18
19
|
|
|
19
20
|
CORE_TOOLS = (
|
|
@@ -21,6 +22,7 @@ CORE_TOOLS = (
|
|
|
21
22
|
"safe_math_eval", "scan_wifi_networks", "get_news_headlines", "web_search", "web_fetch", "request_camera_view",
|
|
22
23
|
)
|
|
23
24
|
VOICE_TOOL_ROUNDS = 6
|
|
25
|
+
FILE_TOOL_ROUNDS = 8
|
|
24
26
|
REPEATABLE_READS = frozenset({
|
|
25
27
|
"get_current_time", "get_system_snapshot", "get_user_location", "get_portal_capabilities",
|
|
26
28
|
"safe_math_eval", "memory_read", "memory_search", "document_search", "session_search",
|
|
@@ -30,7 +32,10 @@ MAX_RESPONSE = 24 * 1024 * 1024
|
|
|
30
32
|
MAX_RECEIPT = 12_000
|
|
31
33
|
_NAME = re.compile(r"[A-Za-z0-9_.-]{1,128}\Z")
|
|
32
34
|
_DEVICE_TOOLS = {"serial": "serial_io", "bluetooth_controllers": "bluetooth_io", "network": "network_io"}
|
|
33
|
-
_TOOL_DIRECTIVE = re.compile(
|
|
35
|
+
_TOOL_DIRECTIVE = re.compile(
|
|
36
|
+
r"(?:^|[.!?,;]\s+|\b(?:and|then)\s+)\s*(?:please\s+)?(?:use|call|invoke|run)\s+(?:(?:your|the)\s+)?`?",
|
|
37
|
+
re.I,
|
|
38
|
+
)
|
|
34
39
|
_TOOL_ALIASES = {"safe_math_eval": "calculator"}
|
|
35
40
|
|
|
36
41
|
|
|
@@ -41,24 +46,26 @@ def current_turn(messages, audio_index):
|
|
|
41
46
|
return messages[user_index + 1:]
|
|
42
47
|
|
|
43
48
|
|
|
44
|
-
def
|
|
45
|
-
"""Match
|
|
46
|
-
if not isinstance(request_text, str)
|
|
47
|
-
return
|
|
48
|
-
|
|
49
|
+
def requested_tools(definitions, request_text):
|
|
50
|
+
"""Match registered tool names explicitly invoked in the user's current turn."""
|
|
51
|
+
if not isinstance(request_text, str):
|
|
52
|
+
return set()
|
|
53
|
+
phrases = [request_text[match.end():].casefold().replace("_", " ")
|
|
54
|
+
for match in _TOOL_DIRECTIVE.finditer(request_text)]
|
|
55
|
+
names = set()
|
|
49
56
|
for item in definitions:
|
|
50
57
|
name = item["function"]["name"]
|
|
51
58
|
labels = (name.casefold().replace("_", " "), _TOOL_ALIASES.get(name))
|
|
52
|
-
if any(
|
|
53
|
-
|
|
54
|
-
|
|
59
|
+
if any(re.match(rf"{re.escape(label)}\b", phrase)
|
|
60
|
+
for label in labels if label for phrase in phrases):
|
|
61
|
+
names.add(name)
|
|
62
|
+
return names
|
|
55
63
|
|
|
56
64
|
|
|
57
|
-
def active_tools(definitions, messages, audio_index, *, explicitly_requested=
|
|
65
|
+
def active_tools(definitions, messages, audio_index, *, explicitly_requested=()):
|
|
58
66
|
"""Retain exact typed schemas revealed during the current committed turn."""
|
|
59
67
|
chosen = set(CORE_TOOLS)
|
|
60
|
-
|
|
61
|
-
chosen.add(explicitly_requested)
|
|
68
|
+
chosen.update(explicitly_requested)
|
|
62
69
|
for message in current_turn(messages, audio_index):
|
|
63
70
|
if message.get("role") != "tool":
|
|
64
71
|
continue
|
|
@@ -102,6 +109,21 @@ def _text_receipt(value, token: str):
|
|
|
102
109
|
return value
|
|
103
110
|
|
|
104
111
|
|
|
112
|
+
def _compact_episodic_receipt(receipt):
|
|
113
|
+
if not isinstance(receipt.get("results"), list):
|
|
114
|
+
return receipt
|
|
115
|
+
fields = ("event_id", "episode", "modality", "actor", "authority", "occurred_at", "channels")
|
|
116
|
+
results = [{**{key: row[key] for key in fields if key in row}, "text": str(row.get("text", ""))[:1300]}
|
|
117
|
+
for row in receipt["results"] if isinstance(row, dict)]
|
|
118
|
+
facts = list(receipt.get("facts", ()))
|
|
119
|
+
compact = {**receipt, "results": results, "facts": facts}
|
|
120
|
+
while len(_json(compact)) > MAX_RECEIPT and facts:
|
|
121
|
+
facts.pop()
|
|
122
|
+
while len(_json(compact)) > MAX_RECEIPT and len(results) > 1:
|
|
123
|
+
results.pop()
|
|
124
|
+
return compact
|
|
125
|
+
|
|
126
|
+
|
|
105
127
|
class PortalTools:
|
|
106
128
|
"""Use the authenticated tool API, independent of its language endpoint."""
|
|
107
129
|
|
|
@@ -158,6 +180,10 @@ class PortalTools:
|
|
|
158
180
|
if "tool_search" not in tools:
|
|
159
181
|
raise ValueError("the tool API does not expose typed tool discovery")
|
|
160
182
|
tools.setdefault("get_news_headlines", NEWS_TOOL)
|
|
183
|
+
tools.setdefault("regex_build", REGEX_BUILD_TOOL)
|
|
184
|
+
if "workspace_file" in tools:
|
|
185
|
+
tools.setdefault("regex_example", REGEX_EXAMPLE_TOOL)
|
|
186
|
+
tools.setdefault("regex_infer_fields", REGEX_FIELDS_TOOL)
|
|
161
187
|
if "network_io" in tools:
|
|
162
188
|
tools.setdefault("scan_wifi_networks", WIFI_SCAN_TOOL)
|
|
163
189
|
return tools
|
|
@@ -179,6 +205,12 @@ class PortalTools:
|
|
|
179
205
|
return self._request("DELETE", "/api/harness/location")
|
|
180
206
|
return self._request("POST", "/api/harness/location", json=location)
|
|
181
207
|
|
|
208
|
+
def memory_status(self) -> dict:
|
|
209
|
+
return self._request("GET", "/api/harness/memory", timeout=4)
|
|
210
|
+
|
|
211
|
+
def remember_episode(self, episode: dict) -> dict:
|
|
212
|
+
return self._request("POST", "/api/harness/memory", json=episode, timeout=4)
|
|
213
|
+
|
|
182
214
|
def submit_password(self, handle: str, password: str) -> bool:
|
|
183
215
|
try:
|
|
184
216
|
value = self._request("POST", "/api/harness/terminal-password",
|
|
@@ -227,6 +259,12 @@ class PortalTools:
|
|
|
227
259
|
return {"ok": False, "error": "unknown_tool"}
|
|
228
260
|
if name == "get_news_headlines":
|
|
229
261
|
return get_headlines(arguments)
|
|
262
|
+
if name == "regex_build":
|
|
263
|
+
return build_regex(arguments)
|
|
264
|
+
if name == "regex_example":
|
|
265
|
+
return read_regex_example(self.invoke)
|
|
266
|
+
if name == "regex_infer_fields":
|
|
267
|
+
return infer_workspace_field_regex(arguments, self.invoke)
|
|
230
268
|
if name == "request_camera_view":
|
|
231
269
|
return {"ok": False, "error": "camera_requires_visual_session",
|
|
232
270
|
"message": "This camera request needs an active backplane with image input."}
|
|
@@ -243,6 +281,8 @@ class PortalTools:
|
|
|
243
281
|
if standalone_wifi:
|
|
244
282
|
value = wifi_observation(value)
|
|
245
283
|
receipt = _text_receipt(value, self.token)
|
|
284
|
+
if name == "episodic_search":
|
|
285
|
+
receipt = _compact_episodic_receipt(receipt)
|
|
246
286
|
serialized = _json(receipt)
|
|
247
287
|
if len(serialized) > MAX_RECEIPT:
|
|
248
288
|
# Keep executor status and routing information even when output is large.
|
package/sophon_harness/voice.py
CHANGED
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
from __future__ import annotations
|
|
4
4
|
|
|
5
5
|
from collections import deque
|
|
6
|
+
import hashlib
|
|
6
7
|
import inspect
|
|
7
8
|
import json
|
|
8
9
|
from pathlib import Path
|
|
@@ -31,6 +32,7 @@ from .tools import VOICE_TOOL_ROUNDS, PortalTools, active_tools
|
|
|
31
32
|
|
|
32
33
|
RATE = 16_000
|
|
33
34
|
FRAME = 512
|
|
35
|
+
SOPHON_VAD_SHA256 = "1a153a22f4509e292a94e67d6f9b85e8deb25b4988682b7e174c65279d8788e3"
|
|
34
36
|
_MARKER = re.compile(r"\ufdd0([0-9]+)\ufdd1")
|
|
35
37
|
|
|
36
38
|
|
|
@@ -48,6 +50,7 @@ class SpeechDetector:
|
|
|
48
50
|
def reset(self):
|
|
49
51
|
self.state = np.zeros((2, 1, 128), dtype=np.float32)
|
|
50
52
|
self.context = np.zeros(64, dtype=np.float32)
|
|
53
|
+
self.pending = bytearray()
|
|
51
54
|
|
|
52
55
|
def probability(self, audio) -> float:
|
|
53
56
|
signal = np.concatenate((self.context, audio))[None, :]
|
|
@@ -57,6 +60,15 @@ class SpeechDetector:
|
|
|
57
60
|
self.context = audio[-64:].copy()
|
|
58
61
|
return float(score[0, 0])
|
|
59
62
|
|
|
63
|
+
def stream_probabilities(self, pcm: bytes) -> list[float]:
|
|
64
|
+
self.pending.extend(pcm)
|
|
65
|
+
values = []
|
|
66
|
+
while len(self.pending) >= FRAME * 2:
|
|
67
|
+
frame = np.frombuffer(self.pending[:FRAME * 2], dtype="<i2").astype(np.float32) / 32768
|
|
68
|
+
del self.pending[:FRAME * 2]
|
|
69
|
+
values.append(self.probability(frame))
|
|
70
|
+
return values
|
|
71
|
+
|
|
60
72
|
|
|
61
73
|
def capture_turn(source: str, vad: SpeechDetector, channels: int, channel: int, *, after_playback=False,
|
|
62
74
|
ready=None):
|
|
@@ -199,13 +211,13 @@ def start_player(sink):
|
|
|
199
211
|
)
|
|
200
212
|
|
|
201
213
|
|
|
202
|
-
def
|
|
214
|
+
def password_status(pcm, pending, runtime, tools):
|
|
203
215
|
handle, deadline = pending
|
|
204
216
|
if time.monotonic() > deadline:
|
|
205
217
|
status = "The password input expired. Ask me to check the terminal again."
|
|
206
218
|
else:
|
|
207
219
|
try:
|
|
208
|
-
password = spoken_password(runtime.backplane.recognize_password(
|
|
220
|
+
password = spoken_password(runtime.backplane.recognize_password(pcm))
|
|
209
221
|
if password is None:
|
|
210
222
|
status = "Password entry cancelled."
|
|
211
223
|
elif tools.submit_password(handle, password):
|
|
@@ -214,6 +226,11 @@ def respond_to_password(audio, pending, runtime, tools, language, sink):
|
|
|
214
226
|
status = "I couldn't confirm password submission. Ask me to check the terminal."
|
|
215
227
|
except (RuntimeError, OSError, ValueError):
|
|
216
228
|
status = "I couldn't transcribe the password. Ask me to check the terminal again."
|
|
229
|
+
return status
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def respond_to_password(audio, pending, runtime, tools, language, sink):
|
|
233
|
+
status = password_status(pcm16(audio), pending, runtime, tools)
|
|
217
234
|
player = start_player(sink)
|
|
218
235
|
try:
|
|
219
236
|
for frame in runtime.speech.frames(status, language):
|
|
@@ -245,7 +262,8 @@ def conduct_turn(audio, history, profile, runtime, embed, tools, *, sink=None, f
|
|
|
245
262
|
try:
|
|
246
263
|
for event in tools.run_committed_turn(
|
|
247
264
|
runtime, messages, media=media, cancelled=cancel,
|
|
248
|
-
max_new_tokens=profile["max_new_tokens"],
|
|
265
|
+
max_new_tokens=profile["max_new_tokens"],
|
|
266
|
+
max_tool_rounds=getattr(runtime.backplane, "tool_rounds", VOICE_TOOL_ROUNDS),
|
|
249
267
|
language=profile["language"],
|
|
250
268
|
):
|
|
251
269
|
if isinstance(event, NativeAssistantTurn):
|
|
@@ -302,9 +320,11 @@ def start(args):
|
|
|
302
320
|
def embed(pcm, _cancel):
|
|
303
321
|
return AudioTurn(pcm, image=image_part(args.image) if args.image is not None else None)
|
|
304
322
|
|
|
305
|
-
|
|
323
|
+
transcription_url = profile.get("transcription_url")
|
|
324
|
+
with OrnithBackplane(args.ornith_url, args.ornith_model, transcription_url=transcription_url) as backplane:
|
|
306
325
|
run_voice(args, profile, backplane, embed, {
|
|
307
|
-
"backplane": args.ornith_model,
|
|
326
|
+
"backplane": args.ornith_model,
|
|
327
|
+
"audio_path": "configured_transcription_worker" if transcription_url else "trained_transcript_bridge",
|
|
308
328
|
"image_attached": args.image is not None,
|
|
309
329
|
})
|
|
310
330
|
return
|
|
@@ -336,24 +356,34 @@ def run_voice(args, profile, backplane, embed, metadata):
|
|
|
336
356
|
log(event="fixture_complete", fixture=path.name, reply=reply, tools=results)
|
|
337
357
|
if args.probe_only:
|
|
338
358
|
return
|
|
359
|
+
ready_file = getattr(args, "ready_file", None)
|
|
360
|
+
|
|
361
|
+
def listening(capture_source, playback_sink):
|
|
362
|
+
log(event="listening", source=capture_source, sink=playback_sink)
|
|
363
|
+
if ready_file is not None:
|
|
364
|
+
ready_file.touch()
|
|
365
|
+
|
|
366
|
+
if args.ornith_url and (args.duplex or profile.get("duplex", False)):
|
|
367
|
+
from .duplex_voice import run_microphone
|
|
368
|
+
|
|
369
|
+
if hashlib.sha256(args.vad.read_bytes()).hexdigest() != SOPHON_VAD_SHA256:
|
|
370
|
+
raise ValueError("duplex capture requires the pinned Sophon Silero model")
|
|
371
|
+
vad = SpeechDetector(args.vad)
|
|
372
|
+
run_microphone(args.source, args.sink, args.channels, args.channel, vad, profile, runtime, embed, tools,
|
|
373
|
+
start_player, lambda pcm, pending: password_status(pcm, pending, runtime, tools),
|
|
374
|
+
log, listening, with_aec=not args.echo_cancelled_input)
|
|
375
|
+
return
|
|
339
376
|
source = args.source or subprocess.check_output(["pactl", "get-default-source"], text=True).strip()
|
|
340
377
|
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
378
|
if ready_file is not None:
|
|
346
379
|
with start_player(sink) as player:
|
|
347
380
|
player.communicate(input=bytes(960), timeout=10)
|
|
348
381
|
if player.returncode:
|
|
349
382
|
raise RuntimeError("speaker playback could not start")
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
ready_file.touch()
|
|
355
|
-
|
|
356
|
-
first_capture = listening
|
|
383
|
+
vad = SpeechDetector(args.vad)
|
|
384
|
+
history = deque(maxlen=6)
|
|
385
|
+
after_playback = False
|
|
386
|
+
first_capture = lambda: listening(source, sink)
|
|
357
387
|
while True:
|
|
358
388
|
audio = capture_turn(source, vad, args.channels, args.channel, after_playback=after_playback,
|
|
359
389
|
ready=first_capture)
|