dtelecom-pipecat 0.1.0__tar.gz

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.
@@ -0,0 +1,11 @@
1
+ .venv/
2
+ __pycache__/
3
+ *.py[cod]
4
+ .pytest_cache/
5
+ .ruff_cache/
6
+ dist/
7
+ build/
8
+ *.egg-info/
9
+ .env
10
+ .env.*
11
+ !.env.example
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,51 @@
1
+ Metadata-Version: 2.5
2
+ Name: dtelecom-pipecat
3
+ Version: 0.1.0
4
+ Summary: dTelecom room transport and speech services for Pipecat
5
+ License-Expression: Apache-2.0
6
+ License-File: LICENSE
7
+ Requires-Python: >=3.11
8
+ Requires-Dist: dtelecom-server-sdk==0.1.0
9
+ Requires-Dist: pipecat-ai<1.18,>=1.17.0
10
+ Provides-Extra: rtc
11
+ Requires-Dist: dtelecom-rtc==0.1.0; extra == 'rtc'
12
+ Description-Content-Type: text/markdown
13
+
14
+ # dTelecom for Pipecat
15
+
16
+ Use dTelecom streaming speech in a Pipecat pipeline, or join a dTelecom room with the RTC transport. Speech services accept a dTelecom Cloud client or a single-use speech key with a refresh callback.
17
+
18
+ Install `dtelecom-pipecat` for speech services. Install `dtelecom-pipecat[rtc]` to send audio and application messages in a room. Supply the URL, participant token and ranked fallbacks from your backend. Room credentials and speech credentials have different scopes.
19
+
20
+ Use `DTelecomSTTService` and `DTelecomTTSService` from `dtelecom_pipecat`, or import `DTelecomTransport` from `dtelecom_pipecat.transport`. Each component can be used independently. Recognition expects mono PCM and associates transcripts with the input participant. Synthesis produces 48 kHz mono PCM. Service readiness and partial retirement events carry the original service metadata in `SpeechSessionFrame`.
21
+
22
+ The [room voice agent](examples/room_agent.py) uses dTelecom for its room, recognition and voice, and OpenRouter for its LLM. Set the dTelecom Cloud variables and the LLM credentials on the server. The example issues the bot's grant and prints the generated room name. Give a browser participant its own grant for that room through your backend. The example uses the provider's final recognition result to propose a turn end. When using Pipecat's own turn strategy, leave `propose_turns=False`.
23
+
24
+ To synthesize SSML, pass an entire document to the speech client or use a Pipecat TTS service configured with `input_format="ssml"` where the upstream processor provides one complete document per request. Optional watermarking requires server support. For translation or file jobs, a Pipecat function or processor can call the same `CloudClient` used to issue the room grant.
25
+
26
+ ## Run the room example
27
+
28
+ Install the RTC extra and Pipecat's OpenRouter integration in the same environment. Set `DTELECOM_CLOUD_URL`, `DTELECOM_API_KEY`, `DTELECOM_API_SECRET`, and `OPENROUTER_API_KEY` on your server. Use the same room name in the agent and your browser grant issuer.
29
+
30
+ ```sh
31
+ python -m pip install 'dtelecom-pipecat[rtc]' 'pipecat-ai[openrouter]>=1.17,<1.18'
32
+ ROOM_NAME=voice-demo python examples/room_agent.py
33
+ ```
34
+
35
+ For a browser client and local grant issuer, use the [FastAPI example](https://github.com/dTelecom/server-sdk-python/tree/main/examples/fastapi) with `DTELECOM_EXAMPLE_ROOM=voice-demo`.
36
+
37
+ ## Call another Cloud service from a Pipecat tool
38
+
39
+ An LLM tool can invoke translation on demand. Reuse the call ID as the idempotency key if the operation is retried. Register the handler for the corresponding tool schema in your existing pipeline.
40
+
41
+ ```python
42
+ from pipecat.services.llm_service import FunctionCallParams
43
+
44
+ async def translate(params: FunctionCallParams):
45
+ request = await cloud.translate(
46
+ params.arguments["text"],
47
+ params.arguments["target"],
48
+ idempotency_key=params.tool_call_id,
49
+ )
50
+ await params.result_callback(request.model_dump(mode="json"))
51
+ ```
@@ -0,0 +1,38 @@
1
+ # dTelecom for Pipecat
2
+
3
+ Use dTelecom streaming speech in a Pipecat pipeline, or join a dTelecom room with the RTC transport. Speech services accept a dTelecom Cloud client or a single-use speech key with a refresh callback.
4
+
5
+ Install `dtelecom-pipecat` for speech services. Install `dtelecom-pipecat[rtc]` to send audio and application messages in a room. Supply the URL, participant token and ranked fallbacks from your backend. Room credentials and speech credentials have different scopes.
6
+
7
+ Use `DTelecomSTTService` and `DTelecomTTSService` from `dtelecom_pipecat`, or import `DTelecomTransport` from `dtelecom_pipecat.transport`. Each component can be used independently. Recognition expects mono PCM and associates transcripts with the input participant. Synthesis produces 48 kHz mono PCM. Service readiness and partial retirement events carry the original service metadata in `SpeechSessionFrame`.
8
+
9
+ The [room voice agent](examples/room_agent.py) uses dTelecom for its room, recognition and voice, and OpenRouter for its LLM. Set the dTelecom Cloud variables and the LLM credentials on the server. The example issues the bot's grant and prints the generated room name. Give a browser participant its own grant for that room through your backend. The example uses the provider's final recognition result to propose a turn end. When using Pipecat's own turn strategy, leave `propose_turns=False`.
10
+
11
+ To synthesize SSML, pass an entire document to the speech client or use a Pipecat TTS service configured with `input_format="ssml"` where the upstream processor provides one complete document per request. Optional watermarking requires server support. For translation or file jobs, a Pipecat function or processor can call the same `CloudClient` used to issue the room grant.
12
+
13
+ ## Run the room example
14
+
15
+ Install the RTC extra and Pipecat's OpenRouter integration in the same environment. Set `DTELECOM_CLOUD_URL`, `DTELECOM_API_KEY`, `DTELECOM_API_SECRET`, and `OPENROUTER_API_KEY` on your server. Use the same room name in the agent and your browser grant issuer.
16
+
17
+ ```sh
18
+ python -m pip install 'dtelecom-pipecat[rtc]' 'pipecat-ai[openrouter]>=1.17,<1.18'
19
+ ROOM_NAME=voice-demo python examples/room_agent.py
20
+ ```
21
+
22
+ For a browser client and local grant issuer, use the [FastAPI example](https://github.com/dTelecom/server-sdk-python/tree/main/examples/fastapi) with `DTELECOM_EXAMPLE_ROOM=voice-demo`.
23
+
24
+ ## Call another Cloud service from a Pipecat tool
25
+
26
+ An LLM tool can invoke translation on demand. Reuse the call ID as the idempotency key if the operation is retried. Register the handler for the corresponding tool schema in your existing pipeline.
27
+
28
+ ```python
29
+ from pipecat.services.llm_service import FunctionCallParams
30
+
31
+ async def translate(params: FunctionCallParams):
32
+ request = await cloud.translate(
33
+ params.arguments["text"],
34
+ params.arguments["target"],
35
+ idempotency_key=params.tool_call_id,
36
+ )
37
+ await params.result_callback(request.model_dump(mode="json"))
38
+ ```
@@ -0,0 +1,74 @@
1
+ """Run a Pipecat voice agent in a dTelecom room. Set ROOM_NAME to select the room."""
2
+
3
+ import asyncio
4
+ import os
5
+ from uuid import uuid4
6
+
7
+ from dtelecom_pipecat import DTelecomSTTService, DTelecomTTSService
8
+ from dtelecom_pipecat.transport import DTelecomTransport
9
+ from dtelecom_server import CloudClient
10
+ from dtelecom_server.speech import SpeechCredentials
11
+ from pipecat.pipeline.pipeline import Pipeline
12
+ from pipecat.pipeline.worker import PipelineWorker
13
+ from pipecat.processors.aggregators.llm_context import LLMContext
14
+ from pipecat.processors.aggregators.llm_response_universal import (
15
+ LLMContextAggregatorPair,
16
+ LLMUserAggregatorParams,
17
+ )
18
+ from pipecat.services.openrouter.llm import OpenRouterLLMService
19
+ from pipecat.turns.user_turn_strategies import ExternalUserTurnStrategies
20
+ from pipecat.workers.runner import WorkerRunner
21
+
22
+
23
+ def voice_pipeline(source, sink, credentials):
24
+ settings = OpenRouterLLMService.Settings(
25
+ model=os.environ.get("OPENROUTER_MODEL", "openai/gpt-4o-mini"),
26
+ system_instruction="Answer the speaker in one short sentence.",
27
+ )
28
+ llm = OpenRouterLLMService(
29
+ api_key=os.environ["OPENROUTER_API_KEY"], settings=settings
30
+ )
31
+ turns = LLMContextAggregatorPair(
32
+ LLMContext(),
33
+ user_params=LLMUserAggregatorParams(
34
+ user_turn_strategies=ExternalUserTurnStrategies()
35
+ ),
36
+ )
37
+ return Pipeline(
38
+ [
39
+ source,
40
+ DTelecomSTTService(
41
+ credentials,
42
+ language="en",
43
+ partials=True,
44
+ smart_turn=True,
45
+ propose_turns=True,
46
+ ),
47
+ turns.user(),
48
+ llm,
49
+ DTelecomTTSService(credentials),
50
+ sink,
51
+ turns.assistant(),
52
+ ]
53
+ )
54
+
55
+
56
+ async def main():
57
+ name = os.getenv("ROOM_NAME") or "pipecat-" + uuid4().hex[:10]
58
+ async with CloudClient() as cloud:
59
+ grant = await cloud.create_token(name, "assistant", ttl="15m")
60
+ room = DTelecomTransport(
61
+ grant.ws_url, grant.token, fallback_urls=grant.fallback_urls
62
+ )
63
+ credentials = SpeechCredentials(cloud=cloud, webrtc_session_id=grant.session_id)
64
+ worker = PipelineWorker(
65
+ voice_pipeline(room.input(), room.output(), credentials), enable_rtvi=False
66
+ )
67
+ runner = WorkerRunner()
68
+ await runner.add_workers(worker)
69
+ print(f"Join room {name} with a separate participant grant.", flush=True)
70
+ await runner.run()
71
+
72
+
73
+ if __name__ == "__main__":
74
+ asyncio.run(main())
@@ -0,0 +1,19 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.27"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "dtelecom-pipecat"
7
+ version = "0.1.0"
8
+ description = "dTelecom room transport and speech services for Pipecat"
9
+ readme = "README.md"
10
+ requires-python = ">=3.11"
11
+ license = "Apache-2.0"
12
+ license-files = ["LICENSE"]
13
+ dependencies = ["pipecat-ai>=1.17.0,<1.18", "dtelecom-server-sdk==0.1.0"]
14
+
15
+ [project.optional-dependencies]
16
+ rtc = ["dtelecom-rtc==0.1.0"]
17
+
18
+ [tool.hatch.build.targets.wheel]
19
+ packages = ["src/dtelecom_pipecat"]
@@ -0,0 +1,5 @@
1
+ """dTelecom integrations for Pipecat. Import room transport from .transport."""
2
+
3
+ from .services import DTelecomSTTService, DTelecomTTSService
4
+
5
+ __all__ = ["DTelecomSTTService", "DTelecomTTSService"]
@@ -0,0 +1,19 @@
1
+ from dataclasses import dataclass
2
+ from typing import Any
3
+
4
+ from pipecat.frames.frames import DataFrame
5
+
6
+
7
+ @dataclass
8
+ class SpeechSessionFrame(DataFrame):
9
+ """Provider readiness and partial retirement, scoped to an input participant."""
10
+
11
+ user_id: str
12
+ event: dict[str, Any]
13
+
14
+
15
+ @dataclass
16
+ class ParticipantLeftFrame(DataFrame):
17
+ """End recognition for the specified participant on room leave."""
18
+
19
+ user_id: str
File without changes
@@ -0,0 +1,276 @@
1
+ """Pipecat speech services backed by the dTelecom speech clients."""
2
+
3
+ import asyncio
4
+ from collections.abc import AsyncIterator
5
+ from contextlib import aclosing
6
+ from typing import Any
7
+
8
+ import numpy as np
9
+ from dtelecom_server.speech import SpeechCredentials, STTStream, TTSStream
10
+ from pipecat.audio.utils import create_stream_resampler
11
+ from pipecat.frames.frames import (
12
+ CancelFrame,
13
+ EndFrame,
14
+ Frame,
15
+ InputAudioRawFrame,
16
+ InterimTranscriptionFrame,
17
+ ProposedUserStartedSpeakingFrame,
18
+ ProposedUserStoppedSpeakingFrame,
19
+ TranscriptionFrame,
20
+ TTSAudioRawFrame,
21
+ )
22
+ from pipecat.processors.frame_processor import FrameDirection
23
+ from pipecat.services.settings import STTSettings, TTSSettings
24
+ from pipecat.services.stt_service import STTService
25
+ from pipecat.services.tts_service import TTSService
26
+ from pipecat.transcriptions.language import Language
27
+ from pipecat.utils.time import time_now_iso8601
28
+
29
+ from .frames import ParticipantLeftFrame, SpeechSessionFrame
30
+
31
+
32
+ class DTelecomSTTService(STTService):
33
+ def __init__(
34
+ self,
35
+ credentials: SpeechCredentials,
36
+ *,
37
+ language: str = "auto",
38
+ partials: bool = True,
39
+ smart_turn: bool = False,
40
+ force_whisper: bool = False,
41
+ propose_turns: bool = False,
42
+ **kwargs,
43
+ ):
44
+ super().__init__(
45
+ sample_rate=16000,
46
+ settings=STTSettings(
47
+ language=language, model="whisper" if force_whisper else None
48
+ ),
49
+ **kwargs,
50
+ )
51
+ self._credentials = credentials
52
+ self._options = dict(partials=partials, smart_turn=smart_turn)
53
+ self._propose = propose_turns
54
+ self._streams: dict[str, STTStream] = {}
55
+ self._readers: dict[str, asyncio.Task] = {}
56
+ self._resamplers: dict[str, Any] = {}
57
+ self._speaking: dict[str, str | None] = {}
58
+
59
+ @property
60
+ def send_sample_rate(self):
61
+ return 16000
62
+
63
+ async def _resample_audio_frame(self, frame: InputAudioRawFrame) -> bytes:
64
+ user = getattr(frame, "user_id", "")
65
+ if user not in self._resamplers:
66
+ self._resamplers[user] = create_stream_resampler()
67
+ pcm = frame.audio
68
+ if frame.num_channels > 1:
69
+ samples = np.frombuffer(pcm, dtype="<i2").reshape(-1, frame.num_channels)
70
+ pcm = np.rint(samples.mean(axis=1)).astype("<i2").tobytes()
71
+ return await self._resamplers[user].resample(pcm, frame.sample_rate, 16000)
72
+
73
+ async def run_stt(self, audio: bytes) -> AsyncIterator[Frame | None]:
74
+ user = self._user_id
75
+ if user not in self._streams:
76
+ stream = STTStream(
77
+ self._credentials,
78
+ language=self._settings.language or "auto",
79
+ force_whisper=self._settings.model == "whisper",
80
+ **self._options,
81
+ )
82
+ self._streams[user] = stream
83
+ await stream.start()
84
+ self._readers[user] = asyncio.create_task(self._receive(user, stream))
85
+ await self._streams[user].send_audio(audio)
86
+ yield None
87
+
88
+ async def _receive(self, user: str, stream: STTStream) -> None:
89
+ try:
90
+ async for event in stream:
91
+ await self._event(user, event)
92
+ except Exception as exc:
93
+ await self.push_error("dTelecom recognition failed", exception=exc)
94
+
95
+ async def _event(self, user: str, event: dict[str, Any]) -> None:
96
+ kind = event.get("type")
97
+ if kind in ("ready", "partial_end"):
98
+ await self.push_frame(SpeechSessionFrame(user, event))
99
+ if (
100
+ kind == "partial_end"
101
+ and event.get("reason") in {"discarded", "replaced", "reconfigured"}
102
+ and user in self._speaking
103
+ and self._speaking[user] == event.get("utterance_id")
104
+ ):
105
+ await self._end_turn(user)
106
+ return
107
+ if kind not in ("transcription_partial", "transcription") or not event.get(
108
+ "text"
109
+ ):
110
+ return
111
+ final = kind == "transcription" and event.get("is_final") is True
112
+ if self._propose:
113
+ if not self._speaking:
114
+ await self.push_frame(ProposedUserStartedSpeakingFrame())
115
+ if not final or user not in self._speaking:
116
+ self._speaking[user] = event.get("utterance_id")
117
+ language = event.get("language")
118
+ try:
119
+ language = Language(language) if language else None
120
+ except ValueError:
121
+ language = None
122
+ fields = dict(
123
+ text=event["text"],
124
+ user_id=user,
125
+ timestamp=time_now_iso8601(),
126
+ language=language,
127
+ result=event,
128
+ )
129
+ if final:
130
+ await self.push_frame(TranscriptionFrame(**fields, finalized=True))
131
+ if self._propose and (
132
+ not event.get("utterance_id")
133
+ or self._speaking[user] in (None, event["utterance_id"])
134
+ ):
135
+ await self._end_turn(user)
136
+ else:
137
+ await self.push_frame(InterimTranscriptionFrame(**fields))
138
+
139
+ async def _end_turn(self, user: str) -> None:
140
+ if user in self._speaking:
141
+ del self._speaking[user]
142
+ if not self._speaking:
143
+ await self.push_frame(ProposedUserStoppedSpeakingFrame())
144
+
145
+ async def _retire(self, user: str) -> None:
146
+ stream = self._streams.pop(user, None)
147
+ reader = self._readers.pop(user, None)
148
+ self._resamplers.pop(user, None)
149
+ if reader:
150
+ reader.cancel()
151
+ await asyncio.gather(reader, return_exceptions=True)
152
+ if stream:
153
+ await stream.close()
154
+ await self._end_turn(user)
155
+
156
+ async def process_frame(self, frame, direction: FrameDirection):
157
+ if isinstance(frame, ParticipantLeftFrame):
158
+ await self._retire(frame.user_id)
159
+ await super().process_frame(frame, direction)
160
+
161
+ async def _update_settings(self, delta):
162
+ changed = await super()._update_settings(delta)
163
+ if "language" in changed or "model" in changed:
164
+ for stream in self._streams.values():
165
+ await stream.set_language(
166
+ self._settings.language or "auto", self._settings.model == "whisper"
167
+ )
168
+ return changed
169
+
170
+ async def stop(self, frame: EndFrame):
171
+ for user in list(self._streams):
172
+ await self._retire(user)
173
+ await super().stop(frame)
174
+
175
+ async def cancel(self, frame: CancelFrame):
176
+ for user in list(self._streams):
177
+ await self._retire(user)
178
+ await super().cancel(frame)
179
+
180
+
181
+ class DTelecomTTSService(TTSService):
182
+ def __init__(
183
+ self,
184
+ credentials: SpeechCredentials,
185
+ *,
186
+ voice: str = "M5",
187
+ language: str = "en",
188
+ speed: float = 1.0,
189
+ watermark: bool = False,
190
+ input_format: str = "text",
191
+ **kwargs,
192
+ ):
193
+ super().__init__(
194
+ sample_rate=48000,
195
+ settings=TTSSettings(voice=voice, language=language, model=None),
196
+ push_start_frame=True,
197
+ push_stop_frames=True,
198
+ **kwargs,
199
+ )
200
+ self._stream = TTSStream(
201
+ credentials,
202
+ voice=voice,
203
+ language=language,
204
+ speed=speed,
205
+ watermark=watermark,
206
+ )
207
+ self._format = input_format
208
+ self._active: dict[str, asyncio.Task] = {}
209
+
210
+ async def run_tts(self, text: str, context_id: str) -> AsyncIterator[Frame | None]:
211
+ # A dedicated producer can be cancelled without cancelling the pipeline's processor task.
212
+ buffer: asyncio.Queue = asyncio.Queue(4)
213
+
214
+ async def produce():
215
+ try:
216
+ async with aclosing(
217
+ self._stream.synthesize(
218
+ text,
219
+ input_format=self._format,
220
+ voice=self._settings.voice,
221
+ language=self._settings.language,
222
+ )
223
+ ) as chunks:
224
+ async for pcm in chunks:
225
+ await buffer.put(pcm)
226
+ except Exception as exc:
227
+ await buffer.put(exc)
228
+ await buffer.put(None)
229
+
230
+ task = asyncio.create_task(produce())
231
+ self._active[context_id] = task
232
+ try:
233
+ while not task.cancelled() and self._active.get(context_id) is task:
234
+ wait = asyncio.create_task(buffer.get())
235
+ try:
236
+ await asyncio.wait(
237
+ [wait, task], return_when=asyncio.FIRST_COMPLETED
238
+ )
239
+ if task.cancelled() or self._active.get(context_id) is not task:
240
+ break
241
+ item = await wait
242
+ finally:
243
+ if not wait.done():
244
+ wait.cancel()
245
+ await asyncio.gather(wait, return_exceptions=True)
246
+ if item is None:
247
+ break
248
+ if isinstance(item, Exception):
249
+ raise item
250
+ yield TTSAudioRawFrame(
251
+ audio=item, sample_rate=48000, num_channels=1, context_id=context_id
252
+ )
253
+ finally:
254
+ if self._active.get(context_id) is task:
255
+ self._active.pop(context_id)
256
+ task.cancel()
257
+ await asyncio.gather(task, return_exceptions=True)
258
+
259
+ async def on_audio_context_interrupted(self, context_id: str):
260
+ task = self._active.pop(context_id, None)
261
+ if task:
262
+ task.cancel()
263
+ await asyncio.gather(task, return_exceptions=True)
264
+
265
+ async def _close(self):
266
+ for context_id in list(self._active):
267
+ await self.on_audio_context_interrupted(context_id)
268
+ await self._stream.close()
269
+
270
+ async def stop(self, frame: EndFrame):
271
+ await super().stop(frame)
272
+ await self._close()
273
+
274
+ async def cancel(self, frame: CancelFrame):
275
+ await self._close()
276
+ await super().cancel(frame)
@@ -0,0 +1,259 @@
1
+ """Pipecat audio and application messages in a dTelecom room (rtc extra)."""
2
+
3
+ import asyncio
4
+ import json
5
+
6
+ from dtelecom_rtc import AudioFrame, AudioSource, Room
7
+ from pipecat.frames.frames import (
8
+ InputTransportMessageFrame,
9
+ InterruptionFrame,
10
+ UserAudioRawFrame,
11
+ )
12
+ from pipecat.transports.base_input import BaseInputTransport
13
+ from pipecat.transports.base_output import BaseOutputTransport
14
+ from pipecat.transports.base_transport import BaseTransport, TransportParams
15
+
16
+ from .frames import ParticipantLeftFrame
17
+
18
+
19
+ class DTelecomTransport(BaseTransport):
20
+ def __init__(
21
+ self,
22
+ url: str,
23
+ token: str,
24
+ *,
25
+ fallback_urls=(),
26
+ params: TransportParams | None = None,
27
+ message_topic: str = "pipecat.app",
28
+ room: Room | None = None,
29
+ **kwargs,
30
+ ):
31
+ super().__init__(**kwargs)
32
+ self.room = room if room is not None else Room()
33
+ self._url, self._token, self._urls = url, token, tuple(fallback_urls)
34
+ self.message_topic = message_topic
35
+ self._started: set[str] = set()
36
+ self._participants: set[str] = set()
37
+ self._lock = asyncio.Lock()
38
+ self._stopping = False
39
+ params = params or TransportParams(
40
+ audio_in_enabled=True,
41
+ audio_out_enabled=True,
42
+ audio_in_sample_rate=16000,
43
+ audio_out_sample_rate=48000,
44
+ )
45
+ self._in = _Input(self, params)
46
+ self._out = _Output(self, params)
47
+ for event in (
48
+ "on_client_connected",
49
+ "on_client_disconnected",
50
+ "on_room_disconnected",
51
+ ):
52
+ self._register_event_handler(event)
53
+ self.room.on("participant_connected", self._connected)
54
+ self.room.on("reconnected", self._reconcile_participants)
55
+ self.room.on("participant_disconnected", self._left)
56
+ self.room.on("disconnected", self._disconnected)
57
+ self.room.on("track_subscribed", self._in.subscribed)
58
+ self.room.on("track_unsubscribed", self._in.unsubscribed)
59
+ self.room.on("data_received", self._in.message)
60
+
61
+ def input(self):
62
+ return self._in
63
+
64
+ def output(self):
65
+ return self._out
66
+
67
+ def update_connection_token(self, token: str, fallback_urls=None):
68
+ self._token = token
69
+ if fallback_urls is not None:
70
+ self._urls = tuple(fallback_urls)
71
+ self.room.update_connection_token(token, fallback_urls)
72
+
73
+ async def _acquire(self, owner):
74
+ async with self._lock:
75
+ if not self._started:
76
+ self._stopping = False
77
+ await self.room.connect(
78
+ self._url, self._token, fallback_urls=self._urls
79
+ )
80
+ self._started.add(owner)
81
+
82
+ async def _release(self, owner):
83
+ async with self._lock:
84
+ if owner not in self._started:
85
+ return
86
+ self._started.remove(owner)
87
+ if not self._started:
88
+ self._stopping = True
89
+ await self.room.disconnect()
90
+
91
+ def _connected(self, participant):
92
+ identity = participant.identity
93
+ if identity not in self._participants:
94
+ self._participants.add(identity)
95
+ return self._call_event_handler("on_client_connected", identity)
96
+
97
+ def _left(self, participant):
98
+ # The RTC client rebuilds its local roster during transport recovery.
99
+ # Keep the speaker's recognition session until the new roster is known.
100
+ if self.room.state != "reconnecting":
101
+ return self._departed(participant.identity)
102
+
103
+ async def _departed(self, identity):
104
+ if identity not in self._participants:
105
+ return
106
+ self._participants.remove(identity)
107
+ if not self._stopping and "input" in self._started:
108
+ await self._in.push_frame(ParticipantLeftFrame(identity))
109
+ await self._call_event_handler("on_client_disconnected", identity)
110
+
111
+ async def _reconcile_participants(self):
112
+ present = {peer.identity for peer in self.room.remote_participants.values()}
113
+ for identity in self._participants - present:
114
+ await self._departed(identity)
115
+
116
+ async def _disconnected(self, reason):
117
+ await self._call_event_handler("on_room_disconnected", reason)
118
+ if not self._stopping and self._started:
119
+ await self._in.push_error(
120
+ "dTelecom room disconnected", force_treat_as_permanent=True
121
+ )
122
+
123
+
124
+ class _Input(BaseInputTransport):
125
+ def __init__(self, transport, params):
126
+ super().__init__(params)
127
+ self.transport = transport
128
+ self._readers = {}
129
+ self._ready = asyncio.Event()
130
+
131
+ async def start(self, frame):
132
+ await super().start(frame)
133
+ await self.set_transport_ready(frame)
134
+ self._ready.set()
135
+ await self.transport._acquire("input")
136
+
137
+ def subscribed(self, track, publication, participant):
138
+ if self._params.audio_in_enabled:
139
+ self.unsubscribed(track, publication, participant)
140
+ self._readers[publication.sid] = asyncio.create_task(
141
+ self._receive(track, participant)
142
+ )
143
+
144
+ def unsubscribed(self, track, publication, participant):
145
+ task = self._readers.pop(publication.sid, None)
146
+ if task:
147
+ task.cancel()
148
+
149
+ async def _receive(self, track, participant):
150
+ try:
151
+ await self._ready.wait()
152
+ async for pcm in track.stream(sample_rate=self.sample_rate):
153
+ await self.push_audio_frame(
154
+ UserAudioRawFrame(
155
+ audio=pcm.data,
156
+ sample_rate=pcm.sample_rate,
157
+ num_channels=pcm.channels,
158
+ user_id=participant.identity,
159
+ )
160
+ )
161
+ except Exception as exc:
162
+ await self.push_error("Could not receive room audio", exception=exc)
163
+
164
+ async def message(self, data, participant, kind, topic):
165
+ if topic != self.transport.message_topic or participant is None:
166
+ return
167
+ try:
168
+ payload = json.loads(data)
169
+ except (ValueError, UnicodeDecodeError):
170
+ return
171
+ await self.push_frame(
172
+ InputTransportMessageFrame(
173
+ {"sender": participant.identity, "message": payload}
174
+ )
175
+ )
176
+
177
+ async def _close(self):
178
+ self._ready.clear()
179
+ tasks = list(self._readers.values())
180
+ self._readers.clear()
181
+ for task in tasks:
182
+ task.cancel()
183
+ await asyncio.gather(*tasks, return_exceptions=True)
184
+ await self.transport._release("input")
185
+
186
+ async def stop(self, frame):
187
+ await self._close()
188
+ await super().stop(frame)
189
+
190
+ async def cancel(self, frame):
191
+ await self._close()
192
+ await super().cancel(frame)
193
+
194
+
195
+ class _Output(BaseOutputTransport):
196
+ def __init__(self, transport, params):
197
+ super().__init__(params)
198
+ self.transport = transport
199
+ self._source = None
200
+ self._publication = None
201
+
202
+ async def start(self, frame):
203
+ await super().start(frame)
204
+ await self.transport._acquire("output")
205
+ if self._params.audio_out_enabled:
206
+ self._source = AudioSource(
207
+ self.sample_rate, self._params.audio_out_channels
208
+ )
209
+ self._publication = await self.transport.room.publish_audio(
210
+ "agent", self._source
211
+ )
212
+ await self.set_transport_ready(frame)
213
+
214
+ async def write_audio_frame(self, frame):
215
+ if self._source is None:
216
+ return False
217
+ await self._source.capture_frame(
218
+ AudioFrame(frame.audio, frame.sample_rate, frame.num_channels)
219
+ )
220
+ return True
221
+
222
+ async def send_message(self, frame):
223
+ await self.transport.room.publish_data(
224
+ json.dumps(frame.message), topic=self.transport.message_topic
225
+ )
226
+
227
+ async def process_frame(self, frame, direction):
228
+ if isinstance(frame, InterruptionFrame) and self._source:
229
+ self._source.clear_queue()
230
+ await super().process_frame(frame, direction)
231
+
232
+ async def _close(self, *, drain: bool):
233
+ source, self._source = self._source, None
234
+ publication, self._publication = self._publication, None
235
+ try:
236
+ if source and drain and self.transport.room.is_connected:
237
+ # The source buffers at most 400ms. A lost peer must not strand teardown.
238
+ try:
239
+ await asyncio.wait_for(source.drain(), timeout=1)
240
+ except TimeoutError:
241
+ source.clear_queue()
242
+ if publication and "input" in self.transport._started:
243
+ await self.transport.room.unpublish_audio(publication)
244
+ finally:
245
+ if source:
246
+ source.close()
247
+ await self.transport._release("output")
248
+
249
+ async def stop(self, frame):
250
+ try:
251
+ await super().stop(frame)
252
+ finally:
253
+ await self._close(drain=True)
254
+
255
+ async def cancel(self, frame):
256
+ try:
257
+ await super().cancel(frame)
258
+ finally:
259
+ await self._close(drain=False)
@@ -0,0 +1,116 @@
1
+ import asyncio
2
+ from contextlib import aclosing
3
+ from unittest.mock import AsyncMock
4
+
5
+ import pytest
6
+ from dtelecom_pipecat import DTelecomSTTService, DTelecomTTSService
7
+ from dtelecom_pipecat.frames import SpeechSessionFrame
8
+ from dtelecom_server.speech import SpeechCredentials
9
+ from pipecat.frames.frames import (
10
+ InterimTranscriptionFrame,
11
+ ProposedUserStartedSpeakingFrame,
12
+ ProposedUserStoppedSpeakingFrame,
13
+ TranscriptionFrame,
14
+ )
15
+
16
+
17
+ def credentials():
18
+ return SpeechCredentials(server_url="wss://example.test", session_key="single-use")
19
+
20
+
21
+ @pytest.mark.asyncio
22
+ async def test_two_speakers_keep_distinct_revisions_and_one_turn():
23
+ service = DTelecomSTTService(credentials(), propose_turns=True)
24
+ service.push_frame = AsyncMock()
25
+ for user in ("a", "b"):
26
+ await service._event(
27
+ user,
28
+ {
29
+ "type": "transcription_partial",
30
+ "text": user,
31
+ "utterance_id": "one",
32
+ "revision": 1,
33
+ },
34
+ )
35
+ await service._event(
36
+ "a", {"type": "transcription", "text": "first", "is_final": True}
37
+ )
38
+ await service._event(
39
+ "b", {"type": "partial_end", "utterance_id": "one", "reason": "finalizing"}
40
+ )
41
+ await service._event(
42
+ "b", {"type": "transcription", "text": "second", "is_final": True}
43
+ )
44
+ frames = [args.args[0] for args in service.push_frame.await_args_list]
45
+ assert list(map(type, frames)) == [
46
+ ProposedUserStartedSpeakingFrame,
47
+ InterimTranscriptionFrame,
48
+ InterimTranscriptionFrame,
49
+ TranscriptionFrame,
50
+ SpeechSessionFrame,
51
+ TranscriptionFrame,
52
+ ProposedUserStoppedSpeakingFrame,
53
+ ]
54
+ assert [f.user_id for f in frames if hasattr(f, "user_id")] == [
55
+ "a",
56
+ "b",
57
+ "a",
58
+ "b",
59
+ "b",
60
+ ]
61
+ assert frames[2].result["revision"] == 1
62
+
63
+
64
+ @pytest.mark.asyncio
65
+ async def test_interrupt_context_finishes_stream_before_next_audio():
66
+ tts = DTelecomTTSService(credentials())
67
+ clear = asyncio.Event()
68
+
69
+ class Speech:
70
+ async def synthesize(self, text, **kwargs):
71
+ try:
72
+ yield text.encode()
73
+ if text == "old":
74
+ await asyncio.Event().wait()
75
+ finally:
76
+ if text == "old":
77
+ clear.set()
78
+
79
+ tts._stream = Speech()
80
+ async with aclosing(tts.run_tts("old", "old-id")) as first:
81
+ assert (await anext(first)).audio == b"old"
82
+ await tts.on_audio_context_interrupted("old-id")
83
+ assert clear.is_set()
84
+ assert await anext(first, None) is None
85
+ frames = [frame async for frame in tts.run_tts("new", "new-id")]
86
+ assert [(f.audio, f.context_id, f.sample_rate) for f in frames] == [
87
+ (b"new", "new-id", 48000)
88
+ ]
89
+
90
+
91
+ @pytest.mark.asyncio
92
+ @pytest.mark.parametrize("reason", ["discarded", "replaced", "reconfigured"])
93
+ async def test_retired_partial_releases_only_its_own_turn(reason):
94
+ service = DTelecomSTTService(credentials(), propose_turns=True)
95
+ service.push_frame = AsyncMock()
96
+ for utterance in ("older", "current"):
97
+ await service._event(
98
+ "a",
99
+ {
100
+ "type": "transcription_partial",
101
+ "text": "draft",
102
+ "utterance_id": utterance,
103
+ },
104
+ )
105
+ for utterance in ("older", "current"):
106
+ await service._event(
107
+ "a", {"type": "partial_end", "reason": reason, "utterance_id": utterance}
108
+ )
109
+ assert ("a" in service._speaking) == (utterance == "older")
110
+ await service._event(
111
+ "b", {"type": "transcription", "text": "next", "is_final": True}
112
+ )
113
+ frames = [call.args[0] for call in service.push_frame.await_args_list]
114
+ assert sum(isinstance(f, ProposedUserStoppedSpeakingFrame) for f in frames) == 2
115
+ assert sum(isinstance(f, ProposedUserStartedSpeakingFrame) for f in frames) == 2
116
+ assert [f.text for f in frames if type(f) is TranscriptionFrame] == ["next"]
@@ -0,0 +1,52 @@
1
+ import asyncio
2
+ from types import SimpleNamespace
3
+ from unittest.mock import AsyncMock
4
+
5
+ import pytest
6
+ from dtelecom_pipecat.frames import ParticipantLeftFrame
7
+ from dtelecom_pipecat.transport import DTelecomTransport
8
+ from dtelecom_rtc import AudioFrame, AudioSource, Room
9
+
10
+
11
+ @pytest.mark.asyncio
12
+ async def test_reconnect_preserves_existing_speaker_and_retires_authoritative_departures():
13
+ room = Room()
14
+ transport = DTelecomTransport("wss://room.example", "test", room=room)
15
+ transport._started.add("input")
16
+ transport.input().push_frame = AsyncMock()
17
+ transport._call_event_handler = AsyncMock()
18
+ for identity in ["stays", "leaves"]:
19
+ await transport._connected(SimpleNamespace(identity=identity))
20
+ room.state = "reconnecting"
21
+ assert transport._left(SimpleNamespace(identity="stays")) is None
22
+ assert transport._left(SimpleNamespace(identity="leaves")) is None
23
+ room.remote_participants["sid"] = SimpleNamespace(identity="stays")
24
+ room.state = "connected"
25
+ await transport._reconcile_participants()
26
+ frame = transport.input().push_frame.await_args.args[0]
27
+ assert isinstance(frame, ParticipantLeftFrame) and frame.user_id == "leaves"
28
+ assert transport._participants == {"stays"}
29
+ assert transport._connected(SimpleNamespace(identity="stays")) is None
30
+ await transport._left(SimpleNamespace(identity="stays"))
31
+ assert not transport._participants
32
+
33
+
34
+ @pytest.mark.asyncio
35
+ async def test_graceful_output_shutdown_drains_pcm_and_retires_only_its_publication():
36
+ room = Room()
37
+ room.state = "connected"
38
+ room.unpublish_audio = AsyncMock()
39
+ transport = DTelecomTransport("wss://room.example", "test", room=room)
40
+ transport._started.update(["input", "output"])
41
+ output = transport.output()
42
+ source = output._source = AudioSource()
43
+ publication = output._publication = object()
44
+ pcm = b"\x01\0" * 960
45
+ await source.capture_frame(AudioFrame(pcm, 48000))
46
+ stopping = asyncio.create_task(output._close(drain=True))
47
+ await asyncio.sleep(0)
48
+ assert not stopping.done()
49
+ assert source._read() == pcm
50
+ await asyncio.wait_for(stopping, 1)
51
+ room.unpublish_audio.assert_awaited_once_with(publication)
52
+ assert transport._started == {"input"}