forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstreaming.py
More file actions
1836 lines (1610 loc) · 72.2 KB
/
Copy pathstreaming.py
File metadata and controls
1836 lines (1610 loc) · 72.2 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
import asyncio
import inspect
import io
import json
import os
import threading
import urllib.parse
import wave as _wave
from enum import Enum
from typing import Any, Awaitable, Callable, Dict, Final, List, Optional, Tuple, cast
import numpy as np
import websockets
from deepgram import DeepgramClient, DeepgramClientOptions, LiveTranscriptionEvents
from deepgram.clients.live.v1 import LiveOptions
from config.stt_provider_policy import (
DEEPGRAM_PROVIDERS,
MODULATE_PROVIDER,
PARAKEET_PROVIDER,
SONIOX_PROVIDER,
STTServingSurface,
deepgram_provider_for_runtime,
default_models_for_surface,
modulate_supports_language,
normalized_stt_language,
parakeet_supports_language,
provider_for_model_token,
provider_is_enabled,
supports_live_multilingual_mode,
)
from utils.async_tasks import create_named_task
from utils.byok import get_byok_key
from utils.executors import sync_executor, run_blocking
from utils.metrics import OMI_LIVE_STT_MISALIGNED_FRAMES_TOTAL
from utils.http_client import get_stt_client, get_stt_semaphore
from utils.stt.safe_socket import SafeDeepgramSocket # noqa: F401 — re-exported for backward compat
from utils.stt.socket import STTSocket
from utils.stt.soniox import SafeSonioxSocket, process_audio_soniox # fmt: skip # pyright: ignore[reportUnusedImport] # noqa: F401 — re-exported for backward compat
from utils.stt.provider_resilience import (
EXPECTED_REJECTIONS,
ProviderCircuitBreaker,
close_rejected_socket,
fallback_socket_is_serving,
)
from utils.stt.speaker_embedding import (
async_extract_embedding_from_bytes,
compare_embeddings,
)
from utils.stt.speaker_clustering import select_speaker_cluster
from utils.observability.fallback import record_fallback
from utils.other.backoff import calculate_backoff_with_jitter
import logging
logger = logging.getLogger(__name__)
class STTService(str, Enum):
deepgram = "deepgram"
modulate = "modulate"
parakeet = "parakeet"
soniox = "soniox"
@staticmethod
def get_model_name(value: 'STTService') -> Optional[str]:
if value == STTService.deepgram:
return 'deepgram_streaming'
if value == STTService.modulate:
return 'modulate_streaming'
if value == STTService.parakeet:
return 'parakeet_streaming'
if value == STTService.soniox:
return 'soniox_streaming'
class ParakeetConnectionError(RuntimeError):
def __init__(self, reason: str, detail: str = '') -> None:
self.reason = reason
super().__init__(detail or reason)
_parakeet_circuit = ProviderCircuitBreaker(
failure_threshold=int(os.getenv('PARAKEET_CIRCUIT_FAILURE_THRESHOLD', '3')),
cooldown_seconds=float(os.getenv('PARAKEET_CIRCUIT_COOLDOWN_SECONDS', '30')),
)
_deepgram_circuit = ProviderCircuitBreaker(
failure_threshold=int(os.getenv('DEEPGRAM_CIRCUIT_FAILURE_THRESHOLD', '3')),
cooldown_seconds=float(os.getenv('DEEPGRAM_CIRCUIT_COOLDOWN_SECONDS', '30')),
)
_modulate_circuit = ProviderCircuitBreaker(
failure_threshold=int(os.getenv('MODULATE_CIRCUIT_FAILURE_THRESHOLD', '3')),
cooldown_seconds=float(os.getenv('MODULATE_CIRCUIT_COOLDOWN_SECONDS', '30')),
)
_soniox_circuit = ProviderCircuitBreaker(
failure_threshold=int(os.getenv('MODULATE_CIRCUIT_FAILURE_THRESHOLD', '3')),
cooldown_seconds=float(os.getenv('MODULATE_CIRCUIT_COOLDOWN_SECONDS', '30')),
)
def _circuit_for_primary(primary_service: STTService) -> ProviderCircuitBreaker:
if primary_service == STTService.parakeet:
return _parakeet_circuit
if primary_service == STTService.deepgram:
return _deepgram_circuit
if primary_service == STTService.modulate:
return _modulate_circuit
if primary_service == STTService.soniox:
return _soniox_circuit
raise ValueError(f'connection fallback is not defined for a {primary_service.value} primary')
def open_provider_selection_circuit(provider: str | None, *, reason: str) -> bool:
"""Open a provider's process-local selection circuit after a serve-time death.
Selection normally learns from connect-time outcomes alone, so a provider
that accepts the upgrade and dies while serving audio is invisible to it:
the next reconnect's successful connect resets the failure counter. The
live-session terminal path calls this so reconnecting clients skip the
provider that just died for one cooldown window. Returns whether a known
provider's circuit was opened; unknown provider names are tolerated
(same shapes metrics accept) and simply report ``False``.
"""
if not provider:
return False
try:
service = STTService(provider)
except ValueError:
return False
circuit = _circuit_for_primary(service)
logger.warning('Opening %s selection circuit after serve-time death reason=%s', provider, reason)
circuit.record_serve_failure()
return True
def _primary_streaming_service() -> Optional[STTService]:
"""Return the STT service leading ``STT_SERVICE_MODELS`` for streaming.
Walks the same policy-owned preference list ``get_stt_service_for_language``
selects from, so a provider migration (e.g. Deepgram -> Modulate) that
reorders that list is honored here automatically instead of leaving a
call site naming a provider that stopped being primary.
"""
for model in (m.strip() for m in stt_service_models):
provider = provider_for_model_token(model)
if provider is None:
continue
if provider in DEEPGRAM_PROVIDERS:
return STTService.deepgram
if provider == MODULATE_PROVIDER:
return STTService.modulate
if provider == PARAKEET_PROVIDER:
return STTService.parakeet
if provider == SONIOX_PROVIDER:
return STTService.soniox
return None
def is_stt_available() -> bool:
"""Best-effort, process-local signal for a client pre-flight check.
Reuses the existing per-process circuit breaker (a latency optimization,
not a fleet-wide coordinator - see provider_resilience.py) for whichever
provider is currently configured as the streaming primary, rather than a
provider hardcoded at the call site: false only while that provider's
breaker is open and its cooldown hasn't elapsed yet after repeated recent
failures. Uses ``cooldown_elapsed()`` rather than raw ``state`` because
the open->half_open transition otherwise only happens inside
``allow_request()`` — without this, a quiet process with no concurrent
listen traffic would stay reporting "unavailable" forever after the
provider actually recovered.
"""
primary = _primary_streaming_service()
if primary is None:
return True
return _circuit_for_primary(primary).cooldown_elapsed()
def _fallback_failure_reason(error: BaseException) -> str:
"""Classify why a fallback provider could not serve, for the next leg's telemetry."""
if isinstance(error, (asyncio.TimeoutError, TimeoutError)):
return 'timeout'
detail = str(error).lower()
if 'limit' in detail or 'quota' in detail or 'exhausted' in detail or 'balance' in detail:
return 'quota' # incl. Soniox 402 'organization_balance_exhausted'
return 'provider_5xx'
# Deepgram and Parakeet refuse at connect time, so a returned socket is proof
# enough. Velma-2 accepts the upgrade and only then answers "Monthly usage limit
# reached.", so a Modulate socket is not evidence that the session is served.
_POST_CONNECT_REJECTING_PRIMARIES: Final = frozenset({STTService.modulate})
async def _primary_is_serving(primary_service: STTService, socket: STTSocket) -> bool:
"""Return whether a connected primary is actually serving the session.
Only providers that reject after the upgrade pay the liveness grace, so live
session setup keeps its hot path for the providers that fail at connect.
"""
if primary_service not in _POST_CONNECT_REJECTING_PRIMARIES:
return True
return await fallback_socket_is_serving(socket)
async def _connect_serving_fallback(
connect: Callable[[], Awaitable[Optional[STTSocket]]], service: STTService
) -> STTSocket:
"""Connect a fallback provider and prove it is actually serving before adopting it."""
socket = await connect()
if socket is None:
raise RuntimeError(f'{service.value} returned no socket')
if not await fallback_socket_is_serving(socket):
detail = getattr(socket, 'death_reason', None) or 'stream rejected'
close_rejected_socket(socket)
raise RuntimeError(f'{service.value} rejected the stream: {detail}')
return socket
async def connect_stt_socket_with_fallback(
*,
primary_service: STTService,
connect_primary: Callable[[], Awaitable[Optional[STTSocket]]],
connect_modulate: Optional[Callable[[], Awaitable[Optional[STTSocket]]]] = None,
connect_deepgram: Optional[Callable[[], Awaitable[Optional[STTSocket]]]] = None,
connect_parakeet: Optional[Callable[[], Awaitable[Optional[STTSocket]]]] = None,
) -> Tuple[STTSocket, STTService]:
"""Connect the selected primary before audio starts, walking the configured fallbacks.
``STT_SERVICE_MODELS`` states an ordered preference, so a primary that
cannot open a socket must advance to the next configured provider instead
of failing the session — a Deepgram account rejecting every connect with
HTTP 402 otherwise takes the whole deployment's live transcription down
(#11695). The chain must not stop at Modulate either: with Deepgram at HTTP
402 and Modulate answering 500/over quota, an English session died while a
healthy Parakeet deployment sat idle behind them in the same list (#11752).
Modulate is a primary as well as a fallback: a deployment listing
``modulate-velma-2,dg-nova-3,parakeet`` lost 100% of its sessions for ~50
minutes because a Modulate primary bypassed this helper entirely (#11752).
The circuit is deliberately process-local and never owns capacity. The
Parakeet service rejects excess streams at its GPU boundary; this helper
only avoids repeated connection latency while a provider is unhealthy.
"""
circuit = _circuit_for_primary(primary_service)
reason = 'circuit_open'
if circuit.allow_request():
try:
socket = await connect_primary()
if socket is None:
reason = 'config_incomplete'
circuit.record_failure()
elif await _primary_is_serving(primary_service, socket):
circuit.record_success()
return socket, primary_service
else:
# The primary took the session and then refused it. Release the
# socket and walk the chain instead of serving a dead stream.
detail = getattr(socket, 'death_reason', None) or 'stream rejected'
close_rejected_socket(socket)
reason = _fallback_failure_reason(RuntimeError(detail))
circuit.record_failure()
except ParakeetConnectionError as error:
reason = error.reason
if reason in EXPECTED_REJECTIONS:
circuit.record_rejection(reason)
else:
circuit.record_failure()
except (asyncio.TimeoutError, TimeoutError):
reason = 'timeout'
circuit.record_failure()
except Exception:
reason = 'provider_5xx'
circuit.record_failure()
# A provider is never offered its own failure as a fallback, so the chain
# excludes the primary: a Modulate primary walks Deepgram then Parakeet
# (#11752). The relative order of the fallback legs is fixed here and is not
# parsed out of STT_SERVICE_MODELS; it matches the declared deployment
# config, and callers already gate each leg on whether the deployment can
# serve it. Reading the true order off the policy list is a separate change.
ordered: List[Tuple[STTService, Optional[Callable[[], Awaitable[Optional[STTSocket]]]]]] = [
(STTService.modulate, connect_modulate),
(STTService.deepgram, connect_deepgram),
(STTService.parakeet, connect_parakeet),
]
candidates: List[Tuple[STTService, Callable[[], Awaitable[Optional[STTSocket]]]]] = [
(service, connect) for service, connect in ordered if connect is not None and service != primary_service
]
from_mode = primary_service.value
for service, connect in candidates:
try:
fallback_socket = await _connect_serving_fallback(connect, service)
except Exception as error:
record_fallback(
component='stt_selection',
from_mode=from_mode,
to_mode=service.value,
reason=reason,
outcome='exhausted',
)
if service == candidates[-1][0]:
raise
from_mode = service.value
reason = _fallback_failure_reason(error)
continue
record_fallback(
component='stt_selection',
from_mode=from_mode,
to_mode=service.value,
reason=reason,
outcome='recovered',
)
return fallback_socket, service
raise RuntimeError('No STT fallback provider was configured')
async def drain_stt_socket(socket: STTSocket) -> None:
"""Await a serving socket's tail drain, with a synchronous close fallback."""
drain_and_close = getattr(socket, 'drain_and_close', None)
if not callable(drain_and_close):
socket.finish()
return
drain_result = drain_and_close()
if inspect.isawaitable(drain_result):
await drain_result
return
logger.warning('STT provider lacks async tail drain')
socket.finish()
deepgram_nova3_multi_languages = {
"multi",
"en",
"en-US",
"en-AU",
"en-GB",
"en-IN",
"en-NZ",
"es",
"es-419",
"fr",
"fr-CA",
"de",
"hi",
"ru",
"pt",
"pt-BR",
"pt-PT",
"ja",
"it",
"nl",
}
deepgram_nova3_languages = {
"ar",
"ar-AE",
"ar-SA",
"ar-QA",
"ar-KW",
"ar-SY",
"ar-LB",
"ar-PS",
"ar-JO",
"ar-EG",
"ar-SD",
"ar-TD",
"ar-MA",
"ar-DZ",
"ar-TN",
"ar-IQ",
"ar-IR",
"be",
"bg",
"bn",
"bs",
"ca",
"cs",
"da",
"da-DK",
"de",
"de-CH",
"el",
"en",
"en-US",
"en-AU",
"en-GB",
"en-IN",
"en-NZ",
"es",
"es-419",
"et",
"fa",
"fi",
"fr",
"fr-CA",
"he",
"hi",
"hr",
"hu",
"id",
"it",
"ja",
"kn",
"ko",
"ko-KR",
"lt",
"lv",
"mk",
"mr",
"ms",
"nl",
"nl-BE",
"no",
"pl",
"pt",
"pt-BR",
"pt-PT",
"ro",
"ru",
"sk",
"sl",
"sr",
"sv",
"sv-SE",
"ta",
"te",
"th",
"th-TH",
"tl",
"tr",
"uk",
"ur",
"vi",
"zh",
"zh-CN",
"zh-Hans",
"zh-HK",
"zh-Hant",
"zh-TW",
}
# Compatibility export for callers. Its value is owned by stt_provider_policy.
DEFAULT_STT_SERVICE_MODELS = default_models_for_surface(STTServingSurface.STREAMING)
stt_service_models = os.getenv('STT_SERVICE_MODELS', ','.join(DEFAULT_STT_SERVICE_MODELS)).split(',')
def modulate_is_configured_fallback(language: Optional[str]) -> bool:
"""Return whether Modulate may take over a session whose primary failed.
``STT_SERVICE_MODELS`` is an ordered preference list, so Modulate serves a
failed primary only where the deployment actually lists it and Velma-2
accepts the session language.
"""
return (
'modulate-velma-2' in (model.strip() for model in stt_service_models)
and provider_is_enabled(MODULATE_PROVIDER, STTServingSurface.STREAMING)
and modulate_supports_language(language)
)
def deepgram_fallback_model(language: Optional[str]) -> Optional[str]:
"""Return the Deepgram model that may take over a session whose primary failed.
Same contract as ``modulate_is_configured_fallback``, but it resolves a model
rather than answering yes/no: a Modulate primary resolved ``stt_model`` and
``stt_language`` for Velma-2, so the caller has no Deepgram model to reuse and
cannot know which ``dg-*`` deployment the runtime actually lists. ``None``
means Deepgram must not be offered the session at all.
"""
if not provider_is_enabled(deepgram_provider_for_runtime(is_dg_self_hosted), STTServingSurface.STREAMING):
return None
if not _deepgram_is_available():
return None
if language not in deepgram_nova3_multi_languages and language not in deepgram_nova3_languages:
return None
for model in (model.strip() for model in stt_service_models):
if model.startswith('dg-'):
return model.replace('dg-', '', 1)
return None
def parakeet_is_configured_fallback(language: Optional[str]) -> bool:
"""Return whether Parakeet may take over a session whose earlier providers failed.
Same contract as ``modulate_is_configured_fallback``, one provider further
down the ordered ``STT_SERVICE_MODELS`` preference: the deployment must list
Parakeet, the policy must serve it, its endpoint must be configured, and it
must support the session's resolved provider language.
"""
return (
STTService.parakeet.value in (model.strip() for model in stt_service_models)
and provider_is_enabled(PARAKEET_PROVIDER, STTServingSurface.STREAMING)
and bool(os.getenv('HOSTED_PARAKEET_API_URL'))
and parakeet_supports_language(STTServingSurface.STREAMING, language or 'en')
)
def _stt_selection_from_mode(_language: str, base_lang: str) -> str:
if base_lang and base_lang != 'en':
return 'requested_non_en'
if any(m.strip() for m in stt_service_models):
return 'configured'
return 'none'
def _requested_stt_language(
language: Optional[str], base_lang: str, *, multi_lang_enabled: bool, surface: STTServingSurface
) -> str:
"""Resolve the provider language while retaining PTT's explicit input language.
Live sessions with multi-language enabled must select a provider's auto-detect
mode. PTT does not load the user's transcription preference, so it keeps its
explicit language unless the client itself sends the ``multi`` sentinel.
"""
if base_lang == 'multi' or (
surface == STTServingSurface.STREAMING
and multi_lang_enabled
and language
and supports_live_multilingual_mode(language)
):
return 'multi'
return base_lang
def _models_with_preferred_service(
models: List[str] | Tuple[str, ...], *, preferred_service: Optional[str]
) -> Tuple[str, ...]:
"""Honor a recognized client engine preference within the serving policy."""
normalized_preference = (preferred_service or '').strip().lower()
if normalized_preference != STTService.parakeet.value:
return tuple(models)
return tuple(model for model in models if model.strip() == STTService.parakeet.value) + tuple(
model for model in models if model.strip() != STTService.parakeet.value
)
def get_stt_service_for_language(
language: Optional[str],
multi_lang_enabled: bool = True,
*,
surface: STTServingSurface = STTServingSurface.STREAMING,
preferred_service: Optional[str] = None,
exclude: frozenset[str] = frozenset(),
) -> Tuple[Optional[STTService], Optional[str], Optional[str]]:
"""Select a serving STT provider allowed for the requested product surface.
``exclude`` holds provider tokens that already died for this session, so a
mid-session failover asks for the next provider down the chain rather than
reselecting the one that just failed.
A ``dg-*`` configuration serves from whichever Deepgram deployment the
runtime is configured for — self-hosted when its endpoint is set, otherwise
the hosted API. Without credentials it falls through to the policy-owned
alternatives rather than failing the session.
"""
# Missing language metadata historically meant English. Preserve that
# behavior without opening a retired-provider fallback for unknown values.
base_lang = normalized_stt_language(language) or 'en'
requested_language = _requested_stt_language(
language,
base_lang,
multi_lang_enabled=multi_lang_enabled,
surface=surface,
)
def select(
models: List[str] | Tuple[str, ...],
) -> Tuple[Optional[Tuple[STTService, str, str]], Optional[str]]:
parakeet_fallback_reason: Optional[str] = None
for model in _models_with_preferred_service(models, preferred_service=preferred_service):
model = model.strip()
if provider_for_model_token(model) in exclude:
continue
if (
model.startswith('dg-')
and provider_is_enabled(deepgram_provider_for_runtime(is_dg_self_hosted), surface)
and _deepgram_is_available()
):
dg_model = model.replace('dg-', '', 1)
if multi_lang_enabled and language in deepgram_nova3_multi_languages:
return (STTService.deepgram, 'multi', dg_model), parakeet_fallback_reason
if language in deepgram_nova3_languages:
return (STTService.deepgram, language, dg_model), parakeet_fallback_reason
continue
if model == 'parakeet':
if provider_is_enabled(PARAKEET_PROVIDER, surface) and os.getenv('HOSTED_PARAKEET_API_URL'):
if parakeet_supports_language(surface, requested_language):
return (STTService.parakeet, requested_language, 'parakeet'), parakeet_fallback_reason
else:
parakeet_fallback_reason = 'capability_mismatch'
else:
parakeet_fallback_reason = 'config_incomplete'
if (
model == 'modulate-velma-2'
and provider_is_enabled(MODULATE_PROVIDER, surface)
and modulate_supports_language(requested_language)
):
return (STTService.modulate, requested_language, 'velma-2'), parakeet_fallback_reason
if model == 'soniox' and provider_is_enabled(SONIOX_PROVIDER, surface) and os.getenv('SONIOX_API_KEY'):
# Soniox identifies the language itself, so every requested language
# including 'multi' is serviceable.
return (STTService.soniox, requested_language, 'soniox'), parakeet_fallback_reason
return None, parakeet_fallback_reason
prefers_parakeet = (preferred_service or '').strip().lower() == STTService.parakeet.value
def record_selected_fallback(
selected: Tuple[STTService, str, str], *, used_default: bool, parakeet_fallback_reason: Optional[str]
) -> None:
if selected[0] != STTService.parakeet and (prefers_parakeet or parakeet_fallback_reason):
record_fallback(
component='stt_selection',
from_mode=STTService.parakeet.value,
to_mode=selected[0].value,
reason=parakeet_fallback_reason
or (
'capability_mismatch'
if not parakeet_supports_language(surface, requested_language)
else 'config_incomplete'
),
outcome='degraded',
)
elif used_default:
record_fallback(
component='stt_selection',
from_mode=_stt_selection_from_mode(language or '', base_lang),
to_mode=selected[0].value,
reason='config_incomplete',
outcome='degraded',
)
selected, parakeet_fallback_reason = select(stt_service_models)
if selected is not None:
record_selected_fallback(selected, used_default=False, parakeet_fallback_reason=parakeet_fallback_reason)
return selected
selected, parakeet_fallback_reason = select(default_models_for_surface(surface))
if selected is not None:
record_selected_fallback(selected, used_default=True, parakeet_fallback_reason=parakeet_fallback_reason)
return selected
record_fallback(
component='stt_selection',
from_mode=_stt_selection_from_mode(language or '', base_lang),
to_mode='unavailable',
reason='capability_mismatch',
outcome='exhausted',
)
return None, None, None
def should_preserve_filler_words(language: str) -> bool:
"""Return True if filler words should be preserved for the given Deepgram language.
English filler sounds ("um", "uh") are safe to strip. But in other languages
those sounds are real words — e.g. Portuguese "um" means "a/one" (#6575).
"""
return not language.startswith('en')
# The endpoint is always set explicitly, never the SDK default.
DEEPGRAM_CLOUD_ENDPOINT: Final = 'https://api.deepgram.com'
is_dg_self_hosted = os.getenv('DEEPGRAM_SELF_HOSTED_ENABLED', '').lower() == 'true'
deepgram: Optional[DeepgramClient] = None
def _deepgram_options(endpoint: str) -> DeepgramClientOptions:
"""Build options per client, pinned to an endpoint, never the SDK default.
DeepgramClient.__init__ writes its key into what it is handed, so a shared
object strands the managed client on whichever BYOK key came last."""
options = DeepgramClientOptions(options={"termination_exception_connect": "true"})
options.url = endpoint
return options
def _require_self_hosted_deepgram_endpoint(endpoint: str) -> str:
"""Reject the hosted endpoint where a self-hosted one was promised.
Falling back to the hosted API would bill the wrong account and hide a
broken self-hosted deployment behind working transcription.
"""
if not endpoint:
raise ValueError("DEEPGRAM_SELF_HOSTED_URL must be set when DEEPGRAM_SELF_HOSTED_ENABLED is true")
if urllib.parse.urlparse(endpoint).hostname == 'api.deepgram.com':
raise ValueError('DEEPGRAM_SELF_HOSTED_URL must not point to api.deepgram.com')
return endpoint
_managed_deepgram_lock = threading.RLock()
_managed_deepgram_ready = False
def _build_managed_deepgram_client() -> Optional[DeepgramClient]:
"""Build the account-owned client, or None when no credential is configured."""
if is_dg_self_hosted:
endpoint = _require_self_hosted_deepgram_endpoint(os.getenv('DEEPGRAM_SELF_HOSTED_URL') or '')
logger.info(f'Using Deepgram self-hosted at: {endpoint}')
return DeepgramClient(os.getenv('DEEPGRAM_API_KEY') or '', _deepgram_options(endpoint))
api_key = os.getenv('DEEPGRAM_API_KEY')
if not api_key:
return None
logger.info('Using Deepgram hosted API')
return DeepgramClient(api_key, _deepgram_options(DEEPGRAM_CLOUD_ENDPOINT))
def _managed_deepgram_client() -> Optional[DeepgramClient]:
"""Return the account client, constructing it on first use.
Deferred so importing this module never depends on Deepgram configuration:
schema export, test collection and other non-serving entry points import it
without credentials. Mirrors the lazy client in ``utils/stt/pre_recorded.py``.
"""
global deepgram, _managed_deepgram_ready
if _managed_deepgram_ready:
return deepgram
with _managed_deepgram_lock:
if not _managed_deepgram_ready:
deepgram = _build_managed_deepgram_client()
_managed_deepgram_ready = True
return deepgram
def _deepgram_is_available() -> bool:
"""Return whether this request could reach Deepgram at all.
A BYOK user brings their own credential, so Deepgram stays selectable on a
runtime that has no account key of its own.
"""
return _managed_deepgram_client() is not None or bool(get_byok_key('deepgram'))
async def process_audio_dg(
stream_transcript: Callable[[List[Dict[str, Any]]], None],
language: str,
sample_rate: int,
channels: int,
model: str = 'nova-3',
keywords: Optional[List[str]] = None,
is_active: Optional[Callable[[], bool]] = None,
) -> Optional[SafeDeepgramSocket]:
logger.info(f'process_audio_dg {language} {sample_rate} {channels}')
def on_message(self: Any, result: Any, **kwargs: Any) -> None:
sentence = result.channel.alternatives[0].transcript
if len(sentence) == 0:
return
segments: List[Dict[str, Any]] = []
for word in result.channel.alternatives[0].words:
if not segments:
segments.append(
{
'speaker': f"SPEAKER_{word.speaker}",
'start': word.start,
'end': word.end,
'text': word.punctuated_word,
'is_user': False,
'person_id': None,
}
)
else:
last_segment = segments[-1]
if last_segment['speaker'] == f"SPEAKER_{word.speaker}":
last_segment['text'] += f" {word.punctuated_word}"
last_segment['end'] = word.end
else:
segments.append(
{
'speaker': f"SPEAKER_{word.speaker}",
'start': word.start,
'end': word.end,
'text': word.punctuated_word,
'is_user': False,
'person_id': None,
}
)
stream_transcript(segments)
def on_error(self: Any, error: Any, **kwargs: Any) -> None:
logger.error(f"Deepgram error: {error}")
logger.info("Connecting to Deepgram") # Log before connection attempt
dg_connection = await connect_to_deepgram_with_backoff(
on_message, on_error, language, sample_rate, channels, model, keywords or [], is_active=is_active
)
if dg_connection is None:
return None
# Always wrap with SafeDeepgramSocket for dead-connection detection (#5870)
safe_conn = SafeDeepgramSocket(dg_connection)
# Register close-reason handlers that feed into SafeDeepgramSocket
def on_dg_close(self: Any, close: Any, **kwargs: Any) -> None:
reason = f'DG close event: {close}'
logger.info('Deepgram connection closed: %s', close)
safe_conn.set_close_reason(reason)
def on_dg_error(self: Any, error: Any, **kwargs: Any) -> None:
reason = f'DG error event: {error}'
logger.warning('Deepgram error (close-reason capture): %s', error)
safe_conn.set_close_reason(reason)
dg_connection.on(LiveTranscriptionEvents.Close, on_dg_close)
dg_connection.on(LiveTranscriptionEvents.Error, on_dg_error)
return safe_conn
async def connect_to_deepgram_with_backoff(
on_message: Callable[..., Any],
on_error: Callable[..., Any],
language: str,
sample_rate: int,
channels: int,
model: str,
keywords: List[str] = [],
retries: int = 3,
is_active: Optional[Callable[[], bool]] = None,
) -> Optional[Any]:
logger.info("connect_to_deepgram_with_backoff")
for attempt in range(retries):
if is_active is not None and not is_active():
logger.warning("Session ended, aborting Deepgram retry")
return None
try:
result = await run_blocking(
sync_executor,
connect_to_deepgram,
on_message,
on_error,
language,
sample_rate,
channels,
model,
keywords,
)
if result is not None:
return result
# start() returned False — retry unless this is the last attempt
if attempt == retries - 1:
logger.error('Deepgram start() returned False on all %d attempts — giving up', retries)
return None
logger.warning('Deepgram start() returned False (attempt %d/%d), retrying...', attempt + 1, retries)
except Exception as error:
logger.error(f'An error occurred: {error}')
if attempt == retries - 1: # Last attempt
raise
backoff_delay = calculate_backoff_with_jitter(attempt)
logger.warning(f"Waiting {backoff_delay:.0f}ms before next retry...")
await asyncio.sleep(backoff_delay / 1000) # Convert ms to seconds for sleep
raise Exception(f'Could not open socket: All retry attempts failed.')
def _dg_keywords_set(options: LiveOptions, keywords: List[str]):
if options.model in ['nova-3']:
options.keyterm = keywords
return options
options.keywords = keywords
return options
def _deepgram_client_for_request() -> DeepgramClient:
"""Return the Deepgram client for the current request.
BYOK users pay Deepgram directly, so their key serves their requests.
Self-hosted has no per-user billing and ignores BYOK.
"""
managed = _managed_deepgram_client()
if is_dg_self_hosted:
if managed is None:
raise RuntimeError('Self-hosted Deepgram is not configured')
return managed
byok = get_byok_key('deepgram')
if byok:
return DeepgramClient(byok, _deepgram_options(DEEPGRAM_CLOUD_ENDPOINT))
if managed is None:
raise RuntimeError('Deepgram is not configured; set DEEPGRAM_API_KEY or provide a BYOK key')
return managed
def connect_to_deepgram(
on_message: Callable[..., Any],
on_error: Callable[..., Any],
language: str,
sample_rate: int,
channels: int,
model: str,
keywords: List[str] = [],
) -> Optional[Any]:
try:
dg_connection: Any = _deepgram_client_for_request().listen.websocket.v("1")
dg_connection.on(LiveTranscriptionEvents.Transcript, on_message)
dg_connection.on(LiveTranscriptionEvents.Error, on_error)
def on_open(self: Any, open: Any, **kwargs: Any) -> None:
logger.info("Connection Open")
def on_metadata(self: Any, metadata: Any, **kwargs: Any) -> None:
logger.info(f"Metadata: {metadata}")
def on_speech_started(self: Any, speech_started: Any, **kwargs: Any) -> None:
logger.info("Speech Started")
def on_utterance_end(self: Any, utterance_end: Any, **kwargs: Any) -> None:
pass
def on_close(self: Any, close: Any, **kwargs: Any) -> None:
logger.info("Connection Closed")
def on_unhandled(self: Any, unhandled: Any, **kwargs: Any) -> None:
logger.error(f"Unhandled Websocket Message: {unhandled}")
dg_connection.on(LiveTranscriptionEvents.Open, on_open)
dg_connection.on(LiveTranscriptionEvents.Metadata, on_metadata)
dg_connection.on(LiveTranscriptionEvents.SpeechStarted, on_speech_started)
dg_connection.on(LiveTranscriptionEvents.UtteranceEnd, on_utterance_end)
dg_connection.on(LiveTranscriptionEvents.Close, on_close)
dg_connection.on(LiveTranscriptionEvents.Unhandled, on_unhandled)
options = LiveOptions(
punctuate=True,
no_delay=True,
endpointing=300,
language=language,
interim_results=False,
smart_format=True,
profanity_filter=False,
diarize=True,
filler_words=should_preserve_filler_words(language),
channels=channels,
multichannel=channels > 1,
model=model,
sample_rate=sample_rate,
encoding='linear16',
)
# `keywords` can be None (e.g. the multi-channel / phone-call path opens the
# socket without passing a vocabulary list). Guard against `len(None)`, which
# previously raised "object of type 'NoneType' has no len()" and aborted the
# socket open, leaving the client stuck in a reconnect loop.
if keywords:
options = _dg_keywords_set(options, keywords)
result: Any = dg_connection.start(options)
logger.info(f'Deepgram connection started: {result}')
if not result:
logger.error('Deepgram connection start() returned False — connection not established')
return None
return dg_connection
except websockets.exceptions.WebSocketException as e:
raise Exception(f'Could not open socket: WebSocketException {e}')
except Exception as e:
raise Exception(f'Could not open socket: {e}')
# ---------------------------------------------------------------------------
# Modulate (Velma-2) streaming
# ---------------------------------------------------------------------------
def _build_wav_header(sample_rate: int, bits_per_sample: int = 16, channels: int = 1) -> bytes: # type: ignore[reportUnusedFunction] # exported, exercised by tests/unit/test_modulate_stt.py
buf = io.BytesIO()
with _wave.open(buf, 'wb') as wf:
wf.setnchannels(channels)
wf.setsampwidth(bits_per_sample // 8)
wf.setframerate(sample_rate)
wf.writeframes(b'')
return buf.getvalue()
MODULATE_DEATH_SERVE_ERROR: Final = 'modulate_serve_error'
# Velma's in-stream error frames are free text, so the fault boundary is
# matched on normalized text. Server-fault shapes say the provider could not
# serve the stream it accepted (5xx wording, or an explicit account-state
# refusal); everything else — invalid audio we sent, rate limits — is either
# our fault or this session's, and must not bench the provider fleet-wide.
_MODULATE_SERVER_FAULT_MARKERS: Final = (
'internal server error',
'internal error',
'unable to complete the request',
'server error',
'monthly usage limit', # account-state refusal: no stream can be served
'usage limit reached',
'quota exceeded',
)
def modulate_death_reason(err: Any) -> Optional[str]:
"""Bound a Velma in-stream error frame to a typed death reason.