pipecat-deepdub 0.1.0__py3-none-any.whl
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.
- pipecat_deepdub/__init__.py +17 -0
- pipecat_deepdub/models.py +133 -0
- pipecat_deepdub/stt.py +498 -0
- pipecat_deepdub/tts.py +532 -0
- pipecat_deepdub-0.1.0.dist-info/METADATA +175 -0
- pipecat_deepdub-0.1.0.dist-info/RECORD +8 -0
- pipecat_deepdub-0.1.0.dist-info/WHEEL +4 -0
- pipecat_deepdub-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
#
|
|
2
|
+
# Copyright (c) 2025-2026, Deepdub AI
|
|
3
|
+
#
|
|
4
|
+
# SPDX-License-Identifier: MIT
|
|
5
|
+
#
|
|
6
|
+
|
|
7
|
+
"""Deepdub text-to-speech and speech-to-text services for Pipecat."""
|
|
8
|
+
|
|
9
|
+
from pipecat_deepdub.stt import DeepdubSTTService, DeepdubSTTSettings
|
|
10
|
+
from pipecat_deepdub.tts import DeepdubTTSService, DeepdubTTSSettings
|
|
11
|
+
|
|
12
|
+
__all__ = [
|
|
13
|
+
"DeepdubSTTService",
|
|
14
|
+
"DeepdubSTTSettings",
|
|
15
|
+
"DeepdubTTSService",
|
|
16
|
+
"DeepdubTTSSettings",
|
|
17
|
+
]
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
#
|
|
2
|
+
# Copyright (c) 2025-2026, Deepdub AI
|
|
3
|
+
#
|
|
4
|
+
# SPDX-License-Identifier: MIT
|
|
5
|
+
#
|
|
6
|
+
|
|
7
|
+
"""Deepdub endpoints, models, voices and languages."""
|
|
8
|
+
|
|
9
|
+
DEFAULT_TTS_URL = "wss://wss.deepdub.ai/ws"
|
|
10
|
+
"""US streaming text-to-speech endpoint. The EU endpoint is ``wss://wss.eu.deepdub.ai/ws``."""
|
|
11
|
+
|
|
12
|
+
DEFAULT_STT_URL = "wss://wsgw.deepdub.ai/transcribe-websocket"
|
|
13
|
+
"""Real-time speech-to-text endpoint (US only)."""
|
|
14
|
+
|
|
15
|
+
DEFAULT_TTS_MODEL = "dd-etts-4.0"
|
|
16
|
+
DEFAULT_STT_MODEL = "stt-egf"
|
|
17
|
+
|
|
18
|
+
DEFAULT_VOICE_PROMPT_ID = "b2abb241-ac92-48bf-a890-fec03f43e209"
|
|
19
|
+
"""English preset "Call Center Agent (Neutral)". See https://docs.deepdub.ai/voice-presets."""
|
|
20
|
+
|
|
21
|
+
DEFAULT_LOCALE = "en-US"
|
|
22
|
+
|
|
23
|
+
TTS_SAMPLE_RATES = (8000, 16000, 22050, 24000, 32000, 36000, 44100, 48000)
|
|
24
|
+
"""Output sample rates Deepdub can stream, in Hz."""
|
|
25
|
+
|
|
26
|
+
TTS_LOCALES = frozenset(
|
|
27
|
+
{
|
|
28
|
+
"ar-LB",
|
|
29
|
+
"ar-QA",
|
|
30
|
+
"ar-SA",
|
|
31
|
+
"ar-SY",
|
|
32
|
+
"cs-CZ",
|
|
33
|
+
"da-DK",
|
|
34
|
+
"de-DE",
|
|
35
|
+
"el-GR",
|
|
36
|
+
"en-AU",
|
|
37
|
+
"en-GB",
|
|
38
|
+
"en-US",
|
|
39
|
+
"es-419",
|
|
40
|
+
"es-ES",
|
|
41
|
+
"es-MX",
|
|
42
|
+
"et-EE",
|
|
43
|
+
"fi-FI",
|
|
44
|
+
"fr-FR",
|
|
45
|
+
"he-IL",
|
|
46
|
+
"hi-IN",
|
|
47
|
+
"hu-HU",
|
|
48
|
+
"id-ID",
|
|
49
|
+
"it-IT",
|
|
50
|
+
"ja-JP",
|
|
51
|
+
"ko-KR",
|
|
52
|
+
"mk-MK",
|
|
53
|
+
"nb-NO",
|
|
54
|
+
"nl-NL",
|
|
55
|
+
"pl-PL",
|
|
56
|
+
"pt-BR",
|
|
57
|
+
"ro-RO",
|
|
58
|
+
"ru-RU",
|
|
59
|
+
"sv-SE",
|
|
60
|
+
"ta-IN",
|
|
61
|
+
"th-TH",
|
|
62
|
+
"tr-TR",
|
|
63
|
+
}
|
|
64
|
+
)
|
|
65
|
+
"""Locales Deepdub text-to-speech can speak."""
|
|
66
|
+
|
|
67
|
+
DEFAULT_LOCALE_FOR_LANGUAGE = {
|
|
68
|
+
"ar": "ar-SA",
|
|
69
|
+
"cs": "cs-CZ",
|
|
70
|
+
"da": "da-DK",
|
|
71
|
+
"de": "de-DE",
|
|
72
|
+
"el": "el-GR",
|
|
73
|
+
"en": "en-US",
|
|
74
|
+
"es": "es-ES",
|
|
75
|
+
"et": "et-EE",
|
|
76
|
+
"fi": "fi-FI",
|
|
77
|
+
"fr": "fr-FR",
|
|
78
|
+
"he": "he-IL",
|
|
79
|
+
"hi": "hi-IN",
|
|
80
|
+
"hu": "hu-HU",
|
|
81
|
+
"id": "id-ID",
|
|
82
|
+
"it": "it-IT",
|
|
83
|
+
"ja": "ja-JP",
|
|
84
|
+
"ko": "ko-KR",
|
|
85
|
+
"mk": "mk-MK",
|
|
86
|
+
"nb": "nb-NO",
|
|
87
|
+
"no": "nb-NO",
|
|
88
|
+
"nl": "nl-NL",
|
|
89
|
+
"pl": "pl-PL",
|
|
90
|
+
"pt": "pt-BR",
|
|
91
|
+
"ro": "ro-RO",
|
|
92
|
+
"ru": "ru-RU",
|
|
93
|
+
"sv": "sv-SE",
|
|
94
|
+
"ta": "ta-IN",
|
|
95
|
+
"th": "th-TH",
|
|
96
|
+
"tr": "tr-TR",
|
|
97
|
+
}
|
|
98
|
+
"""Locale used when only a base language such as ``"en"`` is given."""
|
|
99
|
+
|
|
100
|
+
STT_LANGUAGES = frozenset({"en", "he"})
|
|
101
|
+
"""Languages Deepdub speech-to-text recognizes."""
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def locale_for(language: str) -> str | None:
|
|
105
|
+
"""Return the Deepdub text-to-speech locale for a language or locale code.
|
|
106
|
+
|
|
107
|
+
Args:
|
|
108
|
+
language: A code such as ``"en-US"``, ``"en_us"`` or ``"he"``.
|
|
109
|
+
|
|
110
|
+
Returns:
|
|
111
|
+
The Deepdub locale, or None if Deepdub doesn't speak the language.
|
|
112
|
+
"""
|
|
113
|
+
parts = language.replace("_", "-").split("-")
|
|
114
|
+
code = parts[0].lower()
|
|
115
|
+
if len(parts) > 1:
|
|
116
|
+
region = parts[1] if parts[1].isdigit() else parts[1].upper()
|
|
117
|
+
locale = f"{code}-{region}"
|
|
118
|
+
if locale in TTS_LOCALES:
|
|
119
|
+
return locale
|
|
120
|
+
return DEFAULT_LOCALE_FOR_LANGUAGE.get(code)
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def stt_language_for(language: str) -> str | None:
|
|
124
|
+
"""Return the Deepdub speech-to-text language for a language or locale code.
|
|
125
|
+
|
|
126
|
+
Args:
|
|
127
|
+
language: A code such as ``"he-IL"`` or ``"en"``.
|
|
128
|
+
|
|
129
|
+
Returns:
|
|
130
|
+
``"en"`` or ``"he"``, or None if Deepdub doesn't recognize the language.
|
|
131
|
+
"""
|
|
132
|
+
code = language.replace("_", "-").split("-")[0].lower()
|
|
133
|
+
return code if code in STT_LANGUAGES else None
|
pipecat_deepdub/stt.py
ADDED
|
@@ -0,0 +1,498 @@
|
|
|
1
|
+
#
|
|
2
|
+
# Copyright (c) 2025-2026, Deepdub AI
|
|
3
|
+
#
|
|
4
|
+
# SPDX-License-Identifier: MIT
|
|
5
|
+
#
|
|
6
|
+
|
|
7
|
+
"""Deepdub real-time speech-to-text service.
|
|
8
|
+
|
|
9
|
+
Streams audio to ``wss://wsgw.deepdub.ai/transcribe-websocket`` and turns Deepdub's
|
|
10
|
+
tokens into Pipecat transcription frames. Deepdub recognizes Hebrew and English, and
|
|
11
|
+
can tell which one is spoken in each utterance.
|
|
12
|
+
|
|
13
|
+
- The first message configures the session; audio follows as binary PCM frames.
|
|
14
|
+
- Tokens arrive as they are recognized, provisional at first and then final.
|
|
15
|
+
- An ``<end>`` token marks an endpoint (the speaker finished), and ``<fin>`` answers
|
|
16
|
+
a ``finalize`` request.
|
|
17
|
+
- An empty text message ends the audio, and Deepdub answers with ``finished``.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
import json
|
|
21
|
+
from collections import Counter
|
|
22
|
+
from collections.abc import AsyncGenerator
|
|
23
|
+
from dataclasses import dataclass, field
|
|
24
|
+
from typing import Any
|
|
25
|
+
|
|
26
|
+
from loguru import logger
|
|
27
|
+
from pipecat.frames.frames import (
|
|
28
|
+
CancelFrame,
|
|
29
|
+
EndFrame,
|
|
30
|
+
Frame,
|
|
31
|
+
InterimTranscriptionFrame,
|
|
32
|
+
ProposedUserStartedSpeakingFrame,
|
|
33
|
+
ProposedUserStoppedSpeakingFrame,
|
|
34
|
+
STTMetadataFrame,
|
|
35
|
+
VADUserStartedSpeakingFrame,
|
|
36
|
+
VADUserStoppedSpeakingFrame,
|
|
37
|
+
)
|
|
38
|
+
from pipecat.processors.frame_processor import FrameDirection, FrameProcessorSetup
|
|
39
|
+
from pipecat.services.settings import STTSettings
|
|
40
|
+
from pipecat.services.stt_service import WebsocketSTTService
|
|
41
|
+
from pipecat.transcriptions.language import Language
|
|
42
|
+
from pipecat.turns.user_turn_strategies import ExternalUserTurnStrategies
|
|
43
|
+
from pipecat.utils.errors import ErrorCategory
|
|
44
|
+
from pipecat.utils.time import time_now_iso8601
|
|
45
|
+
from pipecat.utils.tracing.service_decorators import traced_stt
|
|
46
|
+
from pipecat.utils.types import NOT_GIVEN, NotGiven, is_given
|
|
47
|
+
from websockets.protocol import State
|
|
48
|
+
|
|
49
|
+
from pipecat_deepdub.models import DEFAULT_STT_MODEL, DEFAULT_STT_URL, stt_language_for
|
|
50
|
+
|
|
51
|
+
_END_TOKEN = "<end>"
|
|
52
|
+
_FINALIZED_TOKEN = "<fin>"
|
|
53
|
+
_KEEPALIVE_MESSAGE = json.dumps({"type": "keepalive"})
|
|
54
|
+
_FINALIZE_MESSAGE = json.dumps({"type": "finalize"})
|
|
55
|
+
|
|
56
|
+
DEEPDUB_TTFS_P99 = 0.35
|
|
57
|
+
"""P99 seconds from the end of speech to the final transcript, after a finalize."""
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
@dataclass
|
|
61
|
+
class DeepdubSTTSettings(STTSettings):
|
|
62
|
+
"""Settings for DeepdubSTTService.
|
|
63
|
+
|
|
64
|
+
``language`` (``"en"`` or ``"he"``) tells Deepdub which language to expect. Leave
|
|
65
|
+
it unset to let Deepdub detect Hebrew or English in each utterance.
|
|
66
|
+
|
|
67
|
+
Parameters:
|
|
68
|
+
language_hints_strict: Whether to recognize only the hinted language, rather
|
|
69
|
+
than treat it as a preference.
|
|
70
|
+
context_terms: Words and names to recognize reliably, such as product names.
|
|
71
|
+
context_text: Background text about the conversation, to improve accuracy.
|
|
72
|
+
max_endpoint_delay_ms: Longest wait, in milliseconds, after speech stops
|
|
73
|
+
before Deepdub reports an endpoint (500 to 3000).
|
|
74
|
+
client_reference_id: Your own identifier for the session, for support.
|
|
75
|
+
"""
|
|
76
|
+
|
|
77
|
+
language_hints_strict: bool | None | NotGiven = field(default_factory=lambda: NOT_GIVEN)
|
|
78
|
+
context_terms: list[str] | None | NotGiven = field(default_factory=lambda: NOT_GIVEN)
|
|
79
|
+
context_text: str | None | NotGiven = field(default_factory=lambda: NOT_GIVEN)
|
|
80
|
+
max_endpoint_delay_ms: int | None | NotGiven = field(default_factory=lambda: NOT_GIVEN)
|
|
81
|
+
client_reference_id: str | None | NotGiven = field(default_factory=lambda: NOT_GIVEN)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
class DeepdubSTTService(WebsocketSTTService):
|
|
85
|
+
"""Deepdub real-time speech-to-text for Hebrew and English.
|
|
86
|
+
|
|
87
|
+
Interim transcripts stream while the user speaks. A final transcript is pushed at
|
|
88
|
+
each endpoint, or as soon as the local VAD reports the user stopped speaking, which
|
|
89
|
+
sends Deepdub a ``finalize``.
|
|
90
|
+
|
|
91
|
+
Example::
|
|
92
|
+
|
|
93
|
+
stt = DeepdubSTTService(
|
|
94
|
+
api_key=os.environ["DEEPDUB_API_KEY"],
|
|
95
|
+
settings=DeepdubSTTService.Settings(language="he"),
|
|
96
|
+
)
|
|
97
|
+
"""
|
|
98
|
+
|
|
99
|
+
Settings = DeepdubSTTSettings
|
|
100
|
+
_settings: Settings
|
|
101
|
+
|
|
102
|
+
def __init__(
|
|
103
|
+
self,
|
|
104
|
+
*,
|
|
105
|
+
api_key: str,
|
|
106
|
+
url: str = DEFAULT_STT_URL,
|
|
107
|
+
sample_rate: int | None = None,
|
|
108
|
+
vad_force_turn_endpoint: bool = True,
|
|
109
|
+
should_interrupt: bool = True,
|
|
110
|
+
ttfs_p99_latency: float | None = DEEPDUB_TTFS_P99,
|
|
111
|
+
settings: Settings | None = None,
|
|
112
|
+
**kwargs,
|
|
113
|
+
):
|
|
114
|
+
"""Initialize the Deepdub STT service.
|
|
115
|
+
|
|
116
|
+
Args:
|
|
117
|
+
api_key: Deepdub API key.
|
|
118
|
+
url: Speech-to-text endpoint.
|
|
119
|
+
sample_rate: Input sample rate in Hz. If None, uses the pipeline's input rate.
|
|
120
|
+
vad_force_turn_endpoint: Turn detection mode. When True (the default),
|
|
121
|
+
Pipecat's turn strategies decide when the user's turn ends, and a VAD
|
|
122
|
+
stop sends ``finalize`` so the transcript arrives sooner. When False,
|
|
123
|
+
Deepdub's endpoint detection ends the turn: the service proposes a turn
|
|
124
|
+
start on the local VAD (or the first word) and a turn stop at each
|
|
125
|
+
endpoint.
|
|
126
|
+
should_interrupt: Whether the user speaking interrupts the bot, in Deepdub
|
|
127
|
+
turn detection mode (``vad_force_turn_endpoint=False``).
|
|
128
|
+
ttfs_p99_latency: P99 seconds from the end of speech to the final
|
|
129
|
+
transcript. Override it for your deployment.
|
|
130
|
+
settings: Runtime-updatable settings.
|
|
131
|
+
**kwargs: Additional arguments passed to the parent WebsocketSTTService.
|
|
132
|
+
"""
|
|
133
|
+
default_settings = self.Settings(
|
|
134
|
+
model=DEFAULT_STT_MODEL,
|
|
135
|
+
language=None,
|
|
136
|
+
language_hints_strict=None,
|
|
137
|
+
context_terms=None,
|
|
138
|
+
context_text=None,
|
|
139
|
+
max_endpoint_delay_ms=None,
|
|
140
|
+
client_reference_id=None,
|
|
141
|
+
)
|
|
142
|
+
if settings is not None:
|
|
143
|
+
default_settings.apply_update(settings)
|
|
144
|
+
_validate(default_settings)
|
|
145
|
+
|
|
146
|
+
super().__init__(
|
|
147
|
+
sample_rate=sample_rate,
|
|
148
|
+
ttfs_p99_latency=ttfs_p99_latency,
|
|
149
|
+
keepalive_timeout=1,
|
|
150
|
+
keepalive_interval=5,
|
|
151
|
+
settings=default_settings,
|
|
152
|
+
**kwargs,
|
|
153
|
+
)
|
|
154
|
+
|
|
155
|
+
self._api_key = api_key
|
|
156
|
+
self._url = url
|
|
157
|
+
self._vad_force_turn_endpoint = vad_force_turn_endpoint
|
|
158
|
+
self._should_interrupt = should_interrupt
|
|
159
|
+
|
|
160
|
+
self._receive_task = None
|
|
161
|
+
self._final_tokens: list[dict[str, Any]] = []
|
|
162
|
+
self._user_turn_open = False
|
|
163
|
+
|
|
164
|
+
def can_generate_metrics(self) -> bool:
|
|
165
|
+
"""Check if this service can generate processing metrics.
|
|
166
|
+
|
|
167
|
+
Returns:
|
|
168
|
+
True, as Deepdub STT supports metrics generation.
|
|
169
|
+
"""
|
|
170
|
+
return True
|
|
171
|
+
|
|
172
|
+
def language_to_service_language(self, language: Language) -> str | None:
|
|
173
|
+
"""Convert a Language to a Deepdub speech-to-text language.
|
|
174
|
+
|
|
175
|
+
Args:
|
|
176
|
+
language: The language to convert.
|
|
177
|
+
|
|
178
|
+
Returns:
|
|
179
|
+
``"en"`` or ``"he"``, or None if Deepdub doesn't recognize the language.
|
|
180
|
+
"""
|
|
181
|
+
return stt_language_for(str(language.value))
|
|
182
|
+
|
|
183
|
+
def service_metadata_frame(self) -> STTMetadataFrame:
|
|
184
|
+
"""Recommend external turn strategies in Deepdub turn detection mode.
|
|
185
|
+
|
|
186
|
+
Returns:
|
|
187
|
+
The STT metadata frame, recommending that the user aggregator follow this
|
|
188
|
+
service's turn proposals when ``vad_force_turn_endpoint`` is False.
|
|
189
|
+
"""
|
|
190
|
+
frame = super().service_metadata_frame()
|
|
191
|
+
if not self._vad_force_turn_endpoint:
|
|
192
|
+
frame.user_turn_strategies = ExternalUserTurnStrategies(
|
|
193
|
+
enable_interruptions=self._should_interrupt,
|
|
194
|
+
)
|
|
195
|
+
return frame
|
|
196
|
+
|
|
197
|
+
async def _update_settings(self, delta: STTSettings) -> dict[str, Any]:
|
|
198
|
+
"""Apply a settings delta, reconnecting so the new session configuration applies.
|
|
199
|
+
|
|
200
|
+
Args:
|
|
201
|
+
delta: A settings delta.
|
|
202
|
+
|
|
203
|
+
Returns:
|
|
204
|
+
Dict mapping changed field names to their previous values.
|
|
205
|
+
"""
|
|
206
|
+
changed = await super()._update_settings(delta)
|
|
207
|
+
if changed:
|
|
208
|
+
_validate(self._settings)
|
|
209
|
+
await self._request_reconnect()
|
|
210
|
+
return changed
|
|
211
|
+
|
|
212
|
+
async def setup(self, setup: FrameProcessorSetup):
|
|
213
|
+
"""Set up the service and connect.
|
|
214
|
+
|
|
215
|
+
Args:
|
|
216
|
+
setup: Configuration object containing setup parameters.
|
|
217
|
+
"""
|
|
218
|
+
await super().setup(setup)
|
|
219
|
+
await self._connect()
|
|
220
|
+
|
|
221
|
+
async def stop(self, frame: EndFrame):
|
|
222
|
+
"""End the audio, then close the connection.
|
|
223
|
+
|
|
224
|
+
Args:
|
|
225
|
+
frame: The end frame.
|
|
226
|
+
"""
|
|
227
|
+
if self._is_open():
|
|
228
|
+
try:
|
|
229
|
+
await self._get_websocket().send("")
|
|
230
|
+
except Exception as e:
|
|
231
|
+
logger.warning(f"{self}: end-of-audio send failed: {e}")
|
|
232
|
+
await super().stop(frame)
|
|
233
|
+
|
|
234
|
+
async def cancel(self, frame: CancelFrame):
|
|
235
|
+
"""Close the connection without waiting for the remaining transcript.
|
|
236
|
+
|
|
237
|
+
Args:
|
|
238
|
+
frame: The cancel frame.
|
|
239
|
+
"""
|
|
240
|
+
await super().cancel(frame)
|
|
241
|
+
await self._disconnect()
|
|
242
|
+
|
|
243
|
+
async def run_stt(self, audio: bytes) -> AsyncGenerator[Frame | None, None]:
|
|
244
|
+
"""Send audio to Deepdub. Transcripts arrive on the receive task.
|
|
245
|
+
|
|
246
|
+
Args:
|
|
247
|
+
audio: Raw 16-bit mono PCM audio.
|
|
248
|
+
|
|
249
|
+
Yields:
|
|
250
|
+
Frame: None, as transcripts arrive via the WebSocket receive task.
|
|
251
|
+
"""
|
|
252
|
+
if self._is_open():
|
|
253
|
+
try:
|
|
254
|
+
await self._get_websocket().send(audio)
|
|
255
|
+
except Exception as e:
|
|
256
|
+
logger.warning(f"{self}: send failed: {e}")
|
|
257
|
+
yield None
|
|
258
|
+
|
|
259
|
+
async def process_frame(self, frame: Frame, direction: FrameDirection):
|
|
260
|
+
"""Process a frame, finalizing the transcript when the user stops speaking.
|
|
261
|
+
|
|
262
|
+
Args:
|
|
263
|
+
frame: The frame to process.
|
|
264
|
+
direction: The direction of frame processing.
|
|
265
|
+
"""
|
|
266
|
+
await super().process_frame(frame, direction)
|
|
267
|
+
|
|
268
|
+
if isinstance(frame, VADUserStartedSpeakingFrame):
|
|
269
|
+
await self._user_turn_started()
|
|
270
|
+
elif isinstance(frame, VADUserStoppedSpeakingFrame) and self._vad_force_turn_endpoint:
|
|
271
|
+
if self._is_open():
|
|
272
|
+
try:
|
|
273
|
+
await self._get_websocket().send(_FINALIZE_MESSAGE)
|
|
274
|
+
self.request_finalize()
|
|
275
|
+
except Exception as e:
|
|
276
|
+
logger.warning(f"{self}: finalize send failed: {e}")
|
|
277
|
+
|
|
278
|
+
@traced_stt
|
|
279
|
+
async def _handle_transcription(
|
|
280
|
+
self, transcript: str, is_final: bool, language: Language | None = None
|
|
281
|
+
):
|
|
282
|
+
"""Record a transcription for tracing."""
|
|
283
|
+
pass
|
|
284
|
+
|
|
285
|
+
#
|
|
286
|
+
# Turns (Deepdub turn detection mode only)
|
|
287
|
+
#
|
|
288
|
+
|
|
289
|
+
async def _user_turn_started(self):
|
|
290
|
+
if self._vad_force_turn_endpoint or self._user_turn_open:
|
|
291
|
+
return
|
|
292
|
+
self._user_turn_open = True
|
|
293
|
+
await self.broadcast_frame(ProposedUserStartedSpeakingFrame)
|
|
294
|
+
|
|
295
|
+
async def _user_turn_stopped(self):
|
|
296
|
+
if self._vad_force_turn_endpoint or not self._user_turn_open:
|
|
297
|
+
return
|
|
298
|
+
self._user_turn_open = False
|
|
299
|
+
await self.broadcast_frame(ProposedUserStoppedSpeakingFrame)
|
|
300
|
+
|
|
301
|
+
#
|
|
302
|
+
# Connection
|
|
303
|
+
#
|
|
304
|
+
|
|
305
|
+
async def _connect(self):
|
|
306
|
+
await self._connect_websocket()
|
|
307
|
+
await super()._connect()
|
|
308
|
+
# Started even when the connection failed: with no socket the receive loop
|
|
309
|
+
# goes straight to its reconnect path, which retries the connect.
|
|
310
|
+
if not self._receive_task:
|
|
311
|
+
self._receive_task = self.create_task(self._receive_task_handler(self._report_error))
|
|
312
|
+
|
|
313
|
+
async def _disconnect(self):
|
|
314
|
+
await super()._disconnect()
|
|
315
|
+
if self._receive_task:
|
|
316
|
+
await self.cancel_task(self._receive_task)
|
|
317
|
+
self._receive_task = None
|
|
318
|
+
await self._disconnect_websocket()
|
|
319
|
+
|
|
320
|
+
async def _connect_websocket(self):
|
|
321
|
+
try:
|
|
322
|
+
if self._is_open():
|
|
323
|
+
return
|
|
324
|
+
logger.debug(f"{self}: connecting to {self._url}")
|
|
325
|
+
self._websocket = await self._websocket_connect(
|
|
326
|
+
self._url, additional_headers={"Authorization": f"Bearer {self._api_key}"}
|
|
327
|
+
)
|
|
328
|
+
self._final_tokens = []
|
|
329
|
+
await self._websocket.send(json.dumps(self._config_message()))
|
|
330
|
+
await self._call_event_handler("on_connected")
|
|
331
|
+
except Exception as e:
|
|
332
|
+
self._websocket = None
|
|
333
|
+
await self.push_error(error_msg=f"Unable to connect to Deepdub STT: {e}", exception=e)
|
|
334
|
+
|
|
335
|
+
async def _disconnect_websocket(self):
|
|
336
|
+
try:
|
|
337
|
+
if self._websocket:
|
|
338
|
+
logger.debug(f"{self}: disconnecting from Deepdub STT")
|
|
339
|
+
await self._websocket.close()
|
|
340
|
+
except Exception as e:
|
|
341
|
+
logger.warning(f"{self}: error closing websocket: {e}")
|
|
342
|
+
finally:
|
|
343
|
+
self._websocket = None
|
|
344
|
+
await self._call_event_handler("on_disconnected")
|
|
345
|
+
|
|
346
|
+
def _is_open(self) -> bool:
|
|
347
|
+
return self._websocket is not None and self._websocket.state is State.OPEN
|
|
348
|
+
|
|
349
|
+
def _get_websocket(self):
|
|
350
|
+
if self._websocket:
|
|
351
|
+
return self._websocket
|
|
352
|
+
raise Exception("Websocket not connected")
|
|
353
|
+
|
|
354
|
+
async def _send_keepalive(self, silence: bytes):
|
|
355
|
+
"""Send Deepdub's keepalive message instead of silent audio.
|
|
356
|
+
|
|
357
|
+
Args:
|
|
358
|
+
silence: Silent PCM audio (unused).
|
|
359
|
+
"""
|
|
360
|
+
if self._websocket is not None:
|
|
361
|
+
await self._websocket.send(_KEEPALIVE_MESSAGE)
|
|
362
|
+
|
|
363
|
+
def _config_message(self) -> dict[str, Any]:
|
|
364
|
+
s = self._settings
|
|
365
|
+
config: dict[str, Any] = {
|
|
366
|
+
"model": s.model,
|
|
367
|
+
"audio_format": "pcm_s16le",
|
|
368
|
+
"sample_rate": self.sample_rate,
|
|
369
|
+
"num_channels": 1,
|
|
370
|
+
"enable_endpoint_detection": True,
|
|
371
|
+
}
|
|
372
|
+
if s.language:
|
|
373
|
+
config["language_hints"] = [s.language]
|
|
374
|
+
if s.language_hints_strict is not None:
|
|
375
|
+
config["language_hints_strict"] = s.language_hints_strict
|
|
376
|
+
if s.max_endpoint_delay_ms is not None:
|
|
377
|
+
config["max_endpoint_delay_ms"] = s.max_endpoint_delay_ms
|
|
378
|
+
context: dict[str, Any] = {}
|
|
379
|
+
if s.context_terms:
|
|
380
|
+
context["terms"] = list(s.context_terms)
|
|
381
|
+
if s.context_text:
|
|
382
|
+
context["text"] = s.context_text
|
|
383
|
+
if context:
|
|
384
|
+
config["context"] = context
|
|
385
|
+
if s.client_reference_id:
|
|
386
|
+
config["client_reference_id"] = s.client_reference_id
|
|
387
|
+
return config
|
|
388
|
+
|
|
389
|
+
#
|
|
390
|
+
# Server messages
|
|
391
|
+
#
|
|
392
|
+
|
|
393
|
+
async def _receive_messages(self):
|
|
394
|
+
async for message in self._get_websocket():
|
|
395
|
+
try:
|
|
396
|
+
content = json.loads(message)
|
|
397
|
+
except json.JSONDecodeError:
|
|
398
|
+
logger.warning(f"{self}: ignoring a message that isn't JSON")
|
|
399
|
+
continue
|
|
400
|
+
|
|
401
|
+
if content.get("error_code") or content.get("error_message"):
|
|
402
|
+
await self._end_utterance()
|
|
403
|
+
await self.push_error(
|
|
404
|
+
error_msg=(
|
|
405
|
+
f"Deepdub STT error {content.get('error_code')}"
|
|
406
|
+
f" ({content.get('error_type')}): {content.get('error_message')}"
|
|
407
|
+
),
|
|
408
|
+
category=_error_category(content.get("error_code")),
|
|
409
|
+
)
|
|
410
|
+
continue
|
|
411
|
+
|
|
412
|
+
non_final: list[dict[str, Any]] = []
|
|
413
|
+
for token in content.get("tokens") or []:
|
|
414
|
+
text = token.get("text", "")
|
|
415
|
+
is_marker = text in (_END_TOKEN, _FINALIZED_TOKEN)
|
|
416
|
+
if not is_marker:
|
|
417
|
+
await self._user_turn_started()
|
|
418
|
+
if token.get("is_final"):
|
|
419
|
+
if text == _FINALIZED_TOKEN:
|
|
420
|
+
self.confirm_finalize()
|
|
421
|
+
await self._end_utterance()
|
|
422
|
+
elif text == _END_TOKEN:
|
|
423
|
+
await self._end_utterance()
|
|
424
|
+
else:
|
|
425
|
+
self._final_tokens.append(token)
|
|
426
|
+
elif not is_marker:
|
|
427
|
+
non_final.append(token)
|
|
428
|
+
|
|
429
|
+
# Final words are held until the endpoint, so the transcript is pushed
|
|
430
|
+
# whole; until then they show in the interim transcript.
|
|
431
|
+
if self._final_tokens or non_final:
|
|
432
|
+
tokens = self._final_tokens + non_final
|
|
433
|
+
await self.push_frame(
|
|
434
|
+
InterimTranscriptionFrame(
|
|
435
|
+
text="".join(t.get("text", "") for t in tokens),
|
|
436
|
+
user_id=self._user_id,
|
|
437
|
+
timestamp=time_now_iso8601(),
|
|
438
|
+
language=_language_of(tokens),
|
|
439
|
+
result=tokens,
|
|
440
|
+
)
|
|
441
|
+
)
|
|
442
|
+
|
|
443
|
+
if content.get("finished"):
|
|
444
|
+
await self._end_utterance()
|
|
445
|
+
return
|
|
446
|
+
|
|
447
|
+
async def _end_utterance(self):
|
|
448
|
+
"""Push the final transcript at an endpoint, and close the turn it ends."""
|
|
449
|
+
if self._final_tokens:
|
|
450
|
+
tokens, self._final_tokens = self._final_tokens, []
|
|
451
|
+
text = "".join(t.get("text", "") for t in tokens).strip()
|
|
452
|
+
if text:
|
|
453
|
+
language = _language_of(tokens)
|
|
454
|
+
# Usage goes out first so tracing attaches it to the span the
|
|
455
|
+
# transcript closes.
|
|
456
|
+
await self.emit_stt_usage_metrics()
|
|
457
|
+
await self._push_transcription_runs(
|
|
458
|
+
[(None, text)], language=language, result=tokens, finalized=True
|
|
459
|
+
)
|
|
460
|
+
await self._handle_transcription(text, is_final=True, language=language)
|
|
461
|
+
else:
|
|
462
|
+
# A finalize that found nothing left to transcribe still confirms the
|
|
463
|
+
# transcripts already pushed.
|
|
464
|
+
await self._push_transcription_finalized()
|
|
465
|
+
await self._user_turn_stopped()
|
|
466
|
+
|
|
467
|
+
|
|
468
|
+
def _language_of(tokens: list[dict[str, Any]]) -> Language | None:
|
|
469
|
+
counts: Counter[str] = Counter()
|
|
470
|
+
for token in tokens:
|
|
471
|
+
if language := token.get("language"):
|
|
472
|
+
counts[language] += len(token.get("text", ""))
|
|
473
|
+
if not counts:
|
|
474
|
+
return None
|
|
475
|
+
try:
|
|
476
|
+
return Language(counts.most_common(1)[0][0])
|
|
477
|
+
except ValueError:
|
|
478
|
+
return None
|
|
479
|
+
|
|
480
|
+
|
|
481
|
+
def _error_category(code: Any) -> ErrorCategory:
|
|
482
|
+
if code in (401, 403):
|
|
483
|
+
return ErrorCategory.AUTHENTICATION
|
|
484
|
+
if code == 429:
|
|
485
|
+
return ErrorCategory.RATE_LIMIT
|
|
486
|
+
if isinstance(code, int) and 400 <= code < 500:
|
|
487
|
+
return ErrorCategory.INVALID_REQUEST
|
|
488
|
+
return ErrorCategory.SERVER
|
|
489
|
+
|
|
490
|
+
|
|
491
|
+
def _validate(settings: DeepdubSTTSettings):
|
|
492
|
+
language = settings.language
|
|
493
|
+
code = str(language.value) if isinstance(language, Language) else str(language)
|
|
494
|
+
if is_given(language) and language and stt_language_for(code) is None:
|
|
495
|
+
raise ValueError(f"Deepdub speech-to-text recognizes English and Hebrew, got {language!r}")
|
|
496
|
+
delay = settings.max_endpoint_delay_ms
|
|
497
|
+
if is_given(delay) and delay is not None and not 500 <= delay <= 3000:
|
|
498
|
+
raise ValueError(f"max_endpoint_delay_ms must be between 500 and 3000, got {delay}")
|