-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathhttp_api.py
More file actions
3444 lines (2896 loc) · 126 KB
/
Copy pathhttp_api.py
File metadata and controls
3444 lines (2896 loc) · 126 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Mod³ HTTP API — REST interface for TTS synthesis, VAD, and dashboard.
Endpoints:
POST /v1/synthesize — text → audio bytes (WAV/PCM/OGG-Opus) + structured metrics
POST /v1/audio/speech — OpenAI-compatible TTS endpoint
POST /v1/vad — audio file → speech detection result
POST /v1/transcribe — audio file → transcript (Whisper STT)
POST /v1/filter — text → hallucination check
GET /v1/voices — list available engines and voices
GET /v1/jobs — list recent generation jobs with full metrics
GET /v1/jobs/{id} — get a specific job's metrics
GET /health — server health check
POST /shutdown — graceful server shutdown (kernel lifecycle)
GET /capabilities — machine-readable capability manifest
WS /ws/chat — dashboard voice/text chat
GET /dashboard — dashboard UI
POST /v1/sessions/{id}/seats — register a channel-client seat
DELETE /v1/sessions/{id}/seats/{seat_id} — revoke a seat
GET /v1/sessions/{id}/seats/{seat_id}/events — SSE event stream for a seat
GET /v1/sessions/{id}/seats — list seats in a session
POST /v1/sessions/{id}/messages — fan dashboard text to all seats in session
GET /v1/sessions/{id}/messages — recent chat history for hydration
POST /v1/sessions/broadcast-message — fan dashboard text to ALL seats (all sessions)
POST /v1/dashboard-chat — REST dashboard-chat (for channel clients)
GET /v1/logs/chat-flow — recent chat-flow events (JSON)
GET /v1/logs/chat-flow/stream — live SSE stream of chat-flow events
"""
import asyncio
import io
import json
import logging
import os
import signal
import struct
import time
import uuid
import wave
from collections import OrderedDict
from contextlib import asynccontextmanager
from pathlib import Path
from threading import Lock
from typing import TYPE_CHECKING, Optional
if TYPE_CHECKING:
from modules.voice import WhisperDecoder
from fastapi import FastAPI, Request, Response, UploadFile, WebSocket
from fastapi.responses import FileResponse, JSONResponse
from fastapi.staticfiles import StaticFiles
from _version import __version__
from audio_subscribers import get_default_audio_subscribers
from bus import ModalityBus
from chat_flow_log import (
CHAT_FAN_OUT,
CHAT_MESSAGE_RECEIVED,
CHAT_MESSAGE_SENT,
get_chat_flow_log,
)
from engine import MODELS, generate_audio, get_loaded_engines
from modality import EncodedOutput, ModalityType
from modules.text import TextModule
from modules.voice import VoiceModule
from schemas.http import (
BusActRequest,
ComposeProfileRequest,
CompositionCreateRequest,
CompositionUpdateRequest,
RegisterProfileRequest,
SessionRegisterRequest,
ShutdownRequest,
SpeakRequest,
SpeechRequest,
SynthesizeRequest,
VadFilterRequest,
)
from session_registry import (
get_default_registry,
resolve_output_device,
)
from vad import detect_speech_file, is_hallucination
from vad import is_model_loaded as vad_loaded
from voice_profiles import VoiceProfileRegistry
logger = logging.getLogger("mod3.http")
_server_start_time = time.time()
_shutting_down = False
# Voice profile registry — mkdir only; no IO on import.
_registry = VoiceProfileRegistry()
# Composition (draft) registry — mkdir only; no IO on import.
from compositions import Composition, CompositionRegistry, Segment # noqa: E402
_compositions = CompositionRegistry()
@asynccontextmanager
async def _lifespan(application: FastAPI):
"""Unified FastAPI lifespan — replaces all @app.on_event hooks.
Startup order (pre-yield):
1. Kokoro warmup — spawns a daemon thread; non-blocking, never fails startup.
2. Kernel-bus → dashboard bridge — subscribes to cycle-trace events.
Non-blocking: the subscriber's backoff loop handles an unreachable kernel.
3. Auto-create the 'main' session in the voice-TTS session registry.
channel_client.py targets this session by default (clients/channel_client.py:79).
Idempotent: re-registration on restart updates metadata without touching voice.
Shutdown order (post-yield, reverse of startup):
2. Stop kernel-bus bridge.
1. STT executor drain.
Each phase catches and logs its own errors so a failure in one phase does not
prevent the remaining phases from running.
"""
import threading
from bus_bridge_runner import start_bridge, stop_bridge
# --- startup ---
# 1. Kokoro warmup (thread spawn; never blocks or fails startup)
def _do_warmup():
try:
from engine import get_model
get_model("kokoro")
logger.info("Kokoro TTS engine pre-warmed successfully")
except Exception as e:
logger.warning("Kokoro pre-warm failed (will lazy-load on first request): %s", e)
threading.Thread(target=_do_warmup, daemon=True, name="kokoro-warmup").start()
# 2. Kernel-bus → dashboard bridge
try:
await start_bridge(application.state)
except Exception as e: # noqa: BLE001 — never fail startup on bridge wiring
logger.warning("bus-bridge startup failed (non-fatal): %s", e)
# 3. Ensure the 'main' session exists.
#
# channel_client.py uses _DEFAULT_SESSION_ID = "main" (clients/channel_client.py:79).
# POST /v1/sessions/main/seats registers seats into a *seat* registry keyed by
# session_id — that path auto-creates the seat bucket — but the voice-TTS
# session_registry (GET /v1/sessions) is a separate registry that requires an
# explicit register call before it will list the session. Without this, the
# dashboard sees "No active sessions" and /v1/sessions returns {sessions: []}
# even when 3 channel clients are running.
#
# We only guarantee 'main'; other sessions are created on explicit request.
# Idempotent: re-registering an existing session_id updates metadata without
# touching the assigned voice (see SessionRegistry.register).
_MAIN_SESSION_ID = "main"
try:
_sr = get_default_registry()
_sr_result = _sr.register(
session_id=_MAIN_SESSION_ID,
participant_id="channel-client-pool",
participant_type="agent",
preferred_voice=None,
preferred_output_device="system-default",
)
if _sr_result.created:
logger.info("auto-created session '%s' on startup", _MAIN_SESSION_ID)
else:
logger.debug("session '%s' already registered (idempotent restart)", _MAIN_SESSION_ID)
except Exception as e: # noqa: BLE001 — never fail startup on session init
logger.warning("auto-create 'main' session failed (non-fatal): %s", e)
# 3b. Wire seat-liveness ↔ session-lifecycle so orphaned sessions get reaped.
#
# A seat with no live SSE stream is not a seat (per the
# seat-as-coordination-surface model). Two hooks close the loop:
# * liveness_check: the reaper asks the seat registry whether a
# session still has a live SSE connection before pruning it, so a
# live-but-quiet seat is preserved.
# * on_session_idle: when a session's last SSE stream closes (client
# killed/crashed/closed without the graceful DELETE-seat hook), the
# seat registry tells the session registry to deregister it. 'main'
# is never reaped — it is the daemon's persistent pool.
try:
from seats import get_seat_registry as _get_seat_registry
from session_registry import MAIN_SESSION_ID as _MAIN_SID
from session_registry import get_default_registry as _get_session_registry
_seat_reg = _get_seat_registry()
_sess_reg = _get_session_registry()
_sess_reg.set_liveness_check(_seat_reg.has_live_stream)
def _on_session_idle(session_id: str) -> None:
if session_id == _MAIN_SID:
return
res = _sess_reg.deregister(session_id)
if res.get("status") == "ok":
logger.info("deregistered session '%s' on last-SSE-stream close", session_id)
_seat_reg.set_on_session_idle(_on_session_idle)
except Exception as e: # noqa: BLE001 — never fail startup on liveness wiring
logger.warning("seat-liveness wiring failed (non-fatal): %s", e)
yield # application is running
# --- shutdown (reverse order) ---
# 2. Stop kernel-bus bridge
try:
await stop_bridge(application.state, timeout_s=2.0)
except Exception as e: # noqa: BLE001
logger.debug("bus-bridge shutdown error (non-fatal): %s", e)
# 1. Drain and shut down the dedicated STT executor (§4 of ARCHITECTURE.md).
# Allows any in-flight mlx_whisper.transcribe() to finish before exit.
try:
from channels import shutdown_stt_executor
shutdown_stt_executor(wait=True)
logger.debug("STT executor shut down")
except Exception as e: # noqa: BLE001
logger.debug("STT executor shutdown error (non-fatal): %s", e)
app = FastAPI(
title="Mod³",
description="Local multi-model TTS on Apple Silicon",
lifespan=_lifespan,
)
try:
from server import _bus as _shared_bus
except Exception:
_shared_bus = ModalityBus()
_bus = _shared_bus
_bus_vad_lock = Lock()
_stt_transcribe_lock = Lock()
_stt_decoder: "WhisperDecoder | None" = None
def _get_stt_decoder() -> "WhisperDecoder":
"""Lazy-load WhisperDecoder with large-v3-turbo for /v1/transcribe."""
global _stt_decoder
if _stt_decoder is None:
from modules.voice import WhisperDecoder
_stt_decoder = WhisperDecoder(
model="mlx-community/whisper-large-v3-turbo",
load_base=False,
)
return _stt_decoder
def _ensure_bus_modules() -> None:
modules = getattr(_bus, "_modules", {})
if ModalityType.TEXT not in modules:
_bus.register(TextModule())
if ModalityType.VOICE not in modules:
_bus.register(VoiceModule())
def _get_voice_module() -> VoiceModule | None:
module = getattr(_bus, "_modules", {}).get(ModalityType.VOICE)
return module if isinstance(module, VoiceModule) else None
def _resolve_voice_via_bus(voice: str) -> str:
voice_module = _get_voice_module()
if voice_module is None or voice_module.encoder is None:
raise ValueError("Voice module is not registered on the ModalityBus.")
for cfg in MODELS.values():
if voice in cfg["voices"]:
return voice
# Voice profile registry surfaces cloned voices as first-class names.
if _registry.get(voice) is not None:
return voice
raise ValueError(f"Unknown voice '{voice}'. Use /v1/voices to see options.")
def _read_wav_as_mono_float32(raw_wav: bytes) -> tuple[bytes, int]:
import numpy as np
with wave.open(io.BytesIO(raw_wav), "rb") as wav_file:
sample_rate = wav_file.getframerate()
n_channels = wav_file.getnchannels()
sample_width = wav_file.getsampwidth()
frames = wav_file.readframes(wav_file.getnframes())
if sample_width == 2:
audio = np.frombuffer(frames, dtype=np.int16).astype(np.float32) / 32768.0
elif sample_width == 4:
audio = np.frombuffer(frames, dtype=np.int32).astype(np.float32) / 2147483648.0
else:
audio = np.frombuffer(frames, dtype=np.float32)
if n_channels > 1:
audio = audio.reshape(-1, n_channels).mean(axis=1)
return audio.astype(np.float32).tobytes(), sample_rate
_ensure_bus_modules()
# ---------------------------------------------------------------------------
# Job ledger — full lifecycle tracking for every generation
# ---------------------------------------------------------------------------
MAX_JOBS = 100
_jobs: OrderedDict[str, dict] = OrderedDict()
_jobs_lock = Lock()
def _record_job(job: dict) -> str:
job_id = uuid.uuid4().hex[:8]
job["job_id"] = job_id
with _jobs_lock:
_jobs[job_id] = job
while len(_jobs) > MAX_JOBS:
_jobs.popitem(last=False)
return job_id
def _update_job(job_id: str, updates: dict):
with _jobs_lock:
if job_id in _jobs:
_jobs[job_id].update(updates)
# ---------------------------------------------------------------------------
# WAV encoding
# ---------------------------------------------------------------------------
def encode_wav(samples, sample_rate: int) -> bytes:
"""Encode float32 samples as 16-bit PCM WAV."""
import numpy as np
pcm = (np.clip(samples, -1.0, 1.0) * 32767).astype(np.int16)
buf = io.BytesIO()
num_samples = len(pcm)
data_size = num_samples * 2 # 16-bit = 2 bytes per sample
# WAV header (44 bytes)
buf.write(b"RIFF")
buf.write(struct.pack("<I", 36 + data_size))
buf.write(b"WAVE")
buf.write(b"fmt ")
buf.write(struct.pack("<I", 16)) # chunk size
buf.write(struct.pack("<H", 1)) # PCM format
buf.write(struct.pack("<H", 1)) # mono
buf.write(struct.pack("<I", sample_rate)) # sample rate
buf.write(struct.pack("<I", sample_rate * 2)) # byte rate
buf.write(struct.pack("<H", 2)) # block align
buf.write(struct.pack("<H", 16)) # bits per sample
buf.write(b"data")
buf.write(struct.pack("<I", data_size))
buf.write(pcm.tobytes())
return buf.getvalue()
# Opus only accepts these sample rates (RFC 7587).
_OPUS_VALID_RATES = frozenset({8000, 12000, 16000, 24000, 48000})
def encode_ogg(samples, sample_rate: int) -> bytes:
"""Encode float32 samples as OGG/Opus.
Mirrors encode_wav() — takes the same inputs, returns raw bytes.
Opus requires one of {8000, 12000, 16000, 24000, 48000} Hz; if the
engine produces a non-standard rate (e.g. 22050) the samples are
resampled to 24000 before encoding.
Target bitrate is controlled by soundfile/libopus defaults (~24 kbps
for speech at 24 kHz mono).
"""
import numpy as np
import soundfile as sf
samples = np.asarray(samples, dtype=np.float32)
if sample_rate not in _OPUS_VALID_RATES:
# Resample to 24000 — nearest Opus-compatible rate to most TTS engines.
try:
import math
from scipy.signal import resample_poly
target_rate = 24000
gcd = math.gcd(target_rate, sample_rate)
up, down = target_rate // gcd, sample_rate // gcd
samples = resample_poly(samples, up, down).astype(np.float32)
sample_rate = target_rate
except ImportError:
raise RuntimeError(
f"OGG/Opus encoding requires sample_rate in {sorted(_OPUS_VALID_RATES)}; "
f"got {sample_rate} Hz and scipy is not available for resampling."
)
buf = io.BytesIO()
sf.write(buf, samples, sample_rate, format="OGG", subtype="OPUS")
return buf.getvalue()
# ---------------------------------------------------------------------------
# Request / Response models — imported from schemas.http
# (SynthesizeRequest, SpeechRequest, ShutdownRequest, SessionRegisterRequest,
# RegisterProfileRequest, BusActRequest, VadFilterRequest)
# ---------------------------------------------------------------------------
# Shutdown middleware — reject new requests once shutdown is initiated
# ---------------------------------------------------------------------------
@app.middleware("http")
async def _reject_during_shutdown(request: Request, call_next):
"""Return 503 for new requests once graceful shutdown has been initiated."""
if _shutting_down and request.url.path != "/health":
return JSONResponse(
status_code=503,
content={"error": "server is shutting down"},
)
return await call_next(request)
# ---------------------------------------------------------------------------
# localhost CSRF / DNS-rebinding guard
# ---------------------------------------------------------------------------
#
# Threat model: a malicious web page the user visits can issue cross-origin
# requests to the localhost daemon (localhost CSRF). With DNS rebinding the
# attacker also controls the Host header. The browser sends an Origin header
# on cross-origin fetches and same-site form POST; it does NOT send Origin on
# same-origin requests from the dashboard or on programmatic non-browser
# clients (httpx / MCP clients).
#
# Defence — two layers applied only to state-changing methods (POST, PUT,
# PATCH, DELETE):
#
# 1. Host-header allowlist: must be localhost / 127.0.0.1 (with optional
# port). Blocks DNS-rebinding attacks where the attacker substitutes a
# hostname that resolves to 127.0.0.1.
#
# 2. Origin / Referer check (when the header is present): the origin must
# be in the allowed set. Same-origin requests from the dashboard omit
# Origin entirely — those are always permitted. Non-browser clients
# (httpx, MCP) also omit Origin — permitted. Only cross-origin browser
# requests carry Origin, and those are rejected unless explicitly listed.
#
# Allowed origins are configured via MOD3_ALLOWED_ORIGINS (comma-separated
# scheme+host[:port]). The default covers all common localhost variants so
# the dashboard and channel client work without configuration.
#
# Read-only GET / HEAD / OPTIONS requests are deliberately NOT gated — they
# are lower-risk and blocking them would break CORS preflight and monitoring.
_SAFE_METHODS = frozenset({"GET", "HEAD", "OPTIONS"})
_LOCALHOST_HOSTS = frozenset({"localhost", "127.0.0.1", "[::1]", "::1"})
# Build the allowed origins set once at import time.
# Default: all localhost variants on the canonical port and no port.
_DEFAULT_ALLOWED_ORIGINS: frozenset[str] = frozenset(
{
"http://localhost",
"http://localhost:7860",
"http://127.0.0.1",
"http://127.0.0.1:7860",
"http://[::1]",
"http://[::1]:7860",
}
)
def _build_allowed_origins() -> frozenset[str]:
"""Return the effective allowed-origin set from env + defaults."""
raw = os.environ.get("MOD3_ALLOWED_ORIGINS", "").strip()
if not raw:
return _DEFAULT_ALLOWED_ORIGINS
extras = frozenset(o.strip().rstrip("/") for o in raw.split(",") if o.strip())
return _DEFAULT_ALLOWED_ORIGINS | extras
_ALLOWED_ORIGINS: frozenset[str] = _build_allowed_origins()
def _is_localhost_host(host_header: str) -> bool:
"""Return True when the Host header is a loopback address (with optional port)."""
# Strip port: "localhost:7860" → "localhost"
bare = host_header.split(":")[0].lower().strip("[]")
return bare in {"localhost", "127.0.0.1", "::1"}
def _origin_is_allowed(origin: str) -> bool:
"""Return True when origin is in the allowed set (exact match after stripping trailing slash)."""
return origin.rstrip("/") in _ALLOWED_ORIGINS
@app.middleware("http")
async def _localhost_csrf_guard(request: Request, call_next):
"""Reject cross-origin state-changing requests (CSRF / DNS-rebinding guard).
Skips read-only methods (GET, HEAD, OPTIONS) and the /health probe.
Applies to all mutating methods (POST, PUT, PATCH, DELETE).
Rules:
1. Host header must be a loopback address (stops DNS rebinding).
2. If Origin is present it must be in the allowed set.
3. Absent Origin is always permitted (non-browser or same-origin).
On violation: 403 with a JSON body describing which check failed.
"""
method = request.method.upper()
path = request.url.path
# Read-only methods and the health probe are never gated.
if method in _SAFE_METHODS or path == "/health":
return await call_next(request)
# --- 1. Host header check (DNS-rebinding) ---
host = request.headers.get("host", "")
if host and not _is_localhost_host(host):
logger.warning(
"CSRF guard: rejected %s %s — disallowed Host header %r",
method,
path,
host,
)
return JSONResponse(
status_code=403,
content={
"error": "forbidden",
"detail": (
f"Host header {host!r} is not a localhost address. "
"mod3 only accepts requests addressed to localhost."
),
},
)
# --- 2. Origin check ---
origin = request.headers.get("origin", "")
if origin and not _origin_is_allowed(origin):
logger.warning(
"CSRF guard: rejected %s %s — disallowed Origin %r",
method,
path,
origin,
)
return JSONResponse(
status_code=403,
content={
"error": "forbidden",
"detail": (f"Origin {origin!r} is not allowed. Set MOD3_ALLOWED_ORIGINS to add origins."),
},
)
return await call_next(request)
# ---------------------------------------------------------------------------
# Endpoints
# ---------------------------------------------------------------------------
@app.post("/v1/synthesize")
def synthesize(req: SynthesizeRequest):
"""Synthesize text to audio. Returns raw audio bytes + full metrics in headers and job ledger."""
import numpy as np
t_request = time.perf_counter()
# ADR-082 Phase 1: session routing. If the request names a session, we
# honor the session's assigned voice (unless the caller explicitly
# picked a non-default voice) and account the job against the session's
# queue + serializer so multi-session callers can see round-robin.
session_id = req.session_id
session_payload: dict | None = None
if session_id:
registry = get_default_registry()
session = registry.get(session_id)
if session is None:
return JSONResponse(
status_code=404,
content={
"error": f"session '{session_id}' is not registered — POST /v1/sessions/register first",
},
)
if req.voice == "bm_lewis" and session.assigned_voice != "bm_lewis":
req.voice = session.assigned_voice
# Register the submission with the serializer for accounting only.
# The synthesize endpoint is non-blocking on the audio side (we
# return bytes synchronously), so we do not run the registry's
# dispatcher here — we just record the submission.
try:
registry.submit(session_id, {"type": "synthesize", "text": req.text[:200]})
except Exception as exc: # noqa: BLE001
logger.debug("session submit accounting failed: %s", exc)
session_payload = {
"session_id": session.session_id,
"assigned_voice": session.assigned_voice,
"preferred_output_device": session.preferred_output_device,
}
job_id = _record_job(
{
"type": "synthesize",
"status": "generating",
"requested_at": time.time(),
"text": req.text[:200],
"voice": req.voice,
"speed": req.speed,
"emotion": req.emotion,
"format": req.format,
"engine": None,
"session_id": session_id,
"timeline": [{"event": "request_received", "t": 0.0}],
}
)
try:
req.voice = _resolve_voice_via_bus(req.voice)
except ValueError as e:
_update_job(job_id, {"status": "error", "error": str(e)})
return JSONResponse(status_code=400, content={"error": str(e), "job_id": job_id})
t_gen_start = time.perf_counter()
_update_job(job_id, {"timeline_append": True})
_append_timeline(job_id, "generation_start", t_gen_start - t_request)
chunks = list(
generate_audio(
req.text,
voice=req.voice,
speed=req.speed,
emotion=req.emotion,
stream=False,
ref_audio=req.ref_audio,
)
)
t_gen_end = time.perf_counter()
if not chunks:
_update_job(job_id, {"status": "error", "error": "No audio generated"})
return JSONResponse(status_code=400, content={"error": "No audio generated", "job_id": job_id})
sample_rate = chunks[0].sample_rate
all_samples = np.concatenate([c.samples for c in chunks])
duration = len(all_samples) / sample_rate
gen_time = t_gen_end - t_gen_start
# Per-chunk metrics
chunk_metrics = []
for c in chunks:
if c.metadata:
chunk_metrics.append(c.metadata)
t_encode_start = time.perf_counter()
if req.format == "pcm":
pcm = (np.clip(all_samples, -1.0, 1.0) * 32767).astype(np.int16)
audio_bytes = pcm.tobytes()
media_type = "audio/pcm"
wav_for_ws = encode_wav(all_samples, sample_rate) # dashboard always gets WAV
elif req.format == "ogg":
audio_bytes = encode_ogg(all_samples, sample_rate)
media_type = "audio/ogg; codecs=opus"
wav_for_ws = encode_wav(all_samples, sample_rate) # dashboard always gets WAV
else:
audio_bytes = encode_wav(all_samples, sample_rate)
media_type = "audio/wav"
wav_for_ws = audio_bytes
t_encode_end = time.perf_counter()
total_time = t_encode_end - t_request
engine = chunks[0].metadata.get("engine", "") if chunks[0].metadata else ""
# Finalize job record
_append_timeline(job_id, "generation_complete", t_gen_end - t_request)
_append_timeline(job_id, "encoding_complete", t_encode_end - t_request)
# Wave 4.3 — route to any dashboard WebSocket subscribers for this
# session before returning the HTTP response. Mod3 emits the WAV over
# the /ws/audio/{session_id} channel; the MCP shim and the kernel both
# consult /v1/sessions/{id}/subscribers to skip local playback when
# this path fired, so there's no double-play. Pure HTTP callers without
# a session (or without a subscriber) still get their bytes in the
# response body exactly as before.
ws_delivered = 0
if session_id:
subs = get_default_audio_subscribers()
try:
ws_delivered = subs.emit_wav(
session_id,
wav_for_ws,
job_id=job_id,
duration_sec=round(duration, 3),
sample_rate=sample_rate,
)
except Exception as exc: # noqa: BLE001 — never fail synthesize on a WS push
logger.debug("ws audio emit failed: %s", exc)
_update_job(
job_id,
{
"status": "complete",
"engine": engine,
"metrics": {
"audio_duration_sec": round(duration, 3),
"total_samples": len(all_samples),
"sample_rate": sample_rate,
"generation_time_sec": round(gen_time, 3),
"encoding_time_sec": round(t_encode_end - t_encode_start, 4),
"total_time_sec": round(total_time, 3),
"rtf": round(duration / gen_time, 2) if gen_time > 0 else 0,
"chunks": len(chunk_metrics),
"per_chunk": chunk_metrics,
"output_bytes": len(audio_bytes),
"output_format": req.format,
"ws_subscribers_delivered": ws_delivered,
},
},
)
headers = {
"X-Mod3-Job-Id": job_id,
"X-Mod3-Engine": engine,
"X-Mod3-Voice": req.voice,
"X-Mod3-Duration-Sec": f"{duration:.3f}",
"X-Mod3-Sample-Rate": str(sample_rate),
"X-Mod3-Gen-Time-Sec": f"{gen_time:.3f}",
"X-Mod3-Total-Time-Sec": f"{total_time:.3f}",
"X-Mod3-RTF": f"{duration / gen_time:.2f}" if gen_time > 0 else "0",
"X-Mod3-Chunks": str(len(chunk_metrics)),
"X-Mod3-WS-Subscribers": str(ws_delivered),
}
if session_payload is not None:
headers["X-Mod3-Session-Id"] = session_payload["session_id"]
# Update last_used_at for registered voice profiles (fire-and-forget; never
# blocks or fails the response).
try:
_registry.update_last_used_at(req.voice)
except Exception: # noqa: BLE001
pass
return Response(content=audio_bytes, media_type=media_type, headers=headers)
@app.post("/v1/audio/speech")
def audio_speech(req: SpeechRequest):
"""OpenAI-compatible TTS endpoint. Accepts OpenAI format, returns WAV audio."""
import numpy as np
t_request = time.perf_counter()
# ADR-082 Phase 1: optional session routing. Same semantics as
# /v1/synthesize — the session's assigned voice overrides ``voice`` when
# the caller passed the default, and the submission is accounted against
# the session's queue.
session_id = req.session_id
if session_id:
registry = get_default_registry()
session = registry.get(session_id)
if session is None:
return JSONResponse(
status_code=404,
content={
"error": f"session '{session_id}' is not registered — POST /v1/sessions/register first",
},
)
# OpenAI default is af_heart; if the caller left it at the default,
# prefer the session's voice.
if req.voice == "af_heart" and session.assigned_voice != "af_heart":
req.voice = session.assigned_voice
try:
registry.submit(session_id, {"type": "audio_speech", "text": req.input[:200]})
except Exception as exc: # noqa: BLE001
logger.debug("session submit accounting failed: %s", exc)
voice = req.voice
try:
voice = _resolve_voice_via_bus(voice)
except ValueError:
voice = "af_heart"
job_id = _record_job(
{
"type": "audio_speech",
"status": "generating",
"requested_at": time.time(),
"text": req.input[:200],
"voice": voice,
"speed": req.speed,
"session_id": session_id,
"timeline": [{"event": "request_received", "t": 0.0}],
}
)
chunks = list(
generate_audio(
req.input,
voice=voice,
speed=req.speed,
stream=False,
)
)
t_gen_end = time.perf_counter()
if not chunks:
_update_job(job_id, {"status": "error", "error": "No audio generated"})
return JSONResponse(status_code=500, content={"error": "No audio generated", "job_id": job_id})
sample_rate = chunks[0].sample_rate
all_samples = np.concatenate([c.samples for c in chunks])
duration = len(all_samples) / sample_rate
gen_time = t_gen_end - t_request
audio_bytes = encode_wav(all_samples, sample_rate)
total_time = time.perf_counter() - t_request
engine = chunks[0].metadata.get("engine", "") if chunks[0].metadata else ""
_update_job(
job_id,
{
"status": "complete",
"engine": engine,
"metrics": {
"audio_duration_sec": round(duration, 3),
"generation_time_sec": round(gen_time, 3),
"total_time_sec": round(total_time, 3),
"rtf": round(duration / gen_time, 2) if gen_time > 0 else 0,
},
},
)
headers = {
"X-Mod3-Job-Id": job_id,
"X-Mod3-Engine": engine,
"X-Mod3-Voice": voice,
"X-Mod3-Duration-Sec": f"{duration:.3f}",
"X-Mod3-Sample-Rate": str(sample_rate),
"X-Mod3-Gen-Time-Sec": f"{gen_time:.3f}",
"X-Mod3-Total-Time-Sec": f"{total_time:.3f}",
}
if session_id:
headers["X-Mod3-Session-Id"] = session_id
# Update last_used_at for registered voice profiles.
try:
_registry.update_last_used_at(voice)
except Exception: # noqa: BLE001
pass
return Response(content=audio_bytes, media_type="audio/wav", headers=headers)
@app.post("/v1/vad")
async def vad_check(file: UploadFile):
"""Check if an audio file contains speech. Returns VAD result with timing."""
import tempfile
t_start = time.perf_counter()
job_id = _record_job(
{
"type": "vad",
"status": "processing",
"requested_at": time.time(),
"timeline": [{"event": "request_received", "t": 0.0}],
}
)
content = await file.read()
t_load = time.perf_counter()
voice_module = _get_voice_module()
if voice_module is not None and voice_module.gate is not None:
raw_audio, sample_rate = _read_wav_as_mono_float32(content)
with _bus_vad_lock:
gate_result = voice_module.gate.check(raw_audio, sample_rate=sample_rate, sample_width=4)
_bus.perceive(
raw_audio,
modality=ModalityType.VOICE,
channel="http:v1/vad",
sample_rate=sample_rate,
sample_width=4,
transcript="speech detected",
)
class _Result:
has_speech = gate_result.passed
confidence = gate_result.confidence
speech_ratio = gate_result.metadata.get("speech_ratio", 0.0)
num_segments = gate_result.metadata.get("num_segments", 0)
total_speech_sec = gate_result.metadata.get("total_speech_sec", 0.0)
total_audio_sec = gate_result.metadata.get("total_audio_sec", 0.0)
result = _Result()
else:
with tempfile.NamedTemporaryFile(suffix=".wav", delete=True) as tmp:
tmp.write(content)
tmp.flush()
result = detect_speech_file(tmp.name)
t_end = time.perf_counter()
processing_time = t_end - t_start
_update_job(
job_id,
{
"status": "complete",
"metrics": {
"has_speech": result.has_speech,
"confidence": result.confidence,
"speech_ratio": result.speech_ratio,
"num_segments": result.num_segments,
"total_speech_sec": result.total_speech_sec,
"total_audio_sec": result.total_audio_sec,
"processing_time_sec": round(processing_time, 4),
"file_load_time_sec": round(t_load - t_start, 4),
"vad_time_sec": round(t_end - t_load, 4),
},
},
)
return {
"job_id": job_id,
"has_speech": result.has_speech,
"confidence": result.confidence,
"speech_ratio": result.speech_ratio,
"num_segments": result.num_segments,
"total_speech_sec": result.total_speech_sec,
"total_audio_sec": result.total_audio_sec,
"processing_time_sec": round(processing_time, 4),
}
@app.post("/v1/filter")
async def filter_transcription(req: VadFilterRequest):
"""Check if a transcription is a known Whisper hallucination.
Body: {"text": "thank you"}
Returns: {"is_hallucination": true, "text": "thank you"}
"""
return {
"is_hallucination": is_hallucination(req.text),
"text": req.text,
}
@app.post("/v1/transcribe")
async def transcribe_audio(file: UploadFile):
"""Transcribe an audio file to text using Whisper.
Accepts WAV, OGG, MP3, M4A audio files.
Returns transcript with language detection and timing metrics.
"""
import subprocess
import tempfile
import numpy as np
content = await file.read()
if not content:
return JSONResponse(
status_code=400,
content={"error": "Empty audio file"},
)
# Determine format from content-type or filename extension
filename = file.filename or ""
content_type = file.content_type or ""
is_wav = (
filename.lower().endswith(".wav")
or content_type == "audio/wav"
or content_type == "audio/x-wav"
or content[:4] == b"RIFF"
)
try:
if is_wav:
raw_audio, sample_rate = _read_wav_as_mono_float32(content)
audio = np.frombuffer(raw_audio, dtype=np.float32)
else:
# Convert non-WAV to WAV using ffmpeg
with tempfile.NamedTemporaryFile(suffix=".audio", delete=False) as tmp_in:
tmp_in.write(content)
tmp_in_path = tmp_in.name
tmp_out_path = tmp_in_path + ".wav"
try:
subprocess.run(
[
"ffmpeg",
"-y",
"-i",
tmp_in_path,
"-ar",