livekit-murf 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,210 @@
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[codz]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
+
39
+ # Unit test / coverage reports
40
+ htmlcov/
41
+ .tox/
42
+ .nox/
43
+ .coverage
44
+ .coverage.*
45
+ .cache
46
+ nosetests.xml
47
+ coverage.xml
48
+ *.cover
49
+ *.py.cover
50
+ .hypothesis/
51
+ .pytest_cache/
52
+ cover/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ .pybuilder/
76
+ target/
77
+
78
+ # Jupyter Notebook
79
+ .ipynb_checkpoints
80
+
81
+ # IPython
82
+ profile_default/
83
+ ipython_config.py
84
+
85
+ # pyenv
86
+ # For a library or package, you might want to ignore these files since the code is
87
+ # intended to run in multiple environments; otherwise, check them in:
88
+ # .python-version
89
+
90
+ # pipenv
91
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
93
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
94
+ # install all needed dependencies.
95
+ #Pipfile.lock
96
+
97
+ # UV
98
+ # Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
99
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
100
+ # commonly ignored for libraries.
101
+ #uv.lock
102
+
103
+ # poetry
104
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
105
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
106
+ # commonly ignored for libraries.
107
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
108
+ #poetry.lock
109
+ #poetry.toml
110
+
111
+ # pdm
112
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
113
+ # pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python.
114
+ # https://pdm-project.org/en/latest/usage/project/#working-with-version-control
115
+ #pdm.lock
116
+ #pdm.toml
117
+ .pdm-python
118
+ .pdm-build/
119
+
120
+ # pixi
121
+ # Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control.
122
+ #pixi.lock
123
+ # Pixi creates a virtual environment in the .pixi directory, just like venv module creates one
124
+ # in the .venv directory. It is recommended not to include this directory in version control.
125
+ .pixi
126
+
127
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
128
+ __pypackages__/
129
+
130
+ # Celery stuff
131
+ celerybeat-schedule
132
+ celerybeat.pid
133
+
134
+ # SageMath parsed files
135
+ *.sage.py
136
+
137
+ # Environments
138
+ .env
139
+ .envrc
140
+ .venv
141
+ env/
142
+ venv/
143
+ ENV/
144
+ env.bak/
145
+ venv.bak/
146
+
147
+ # Spyder project settings
148
+ .spyderproject
149
+ .spyproject
150
+
151
+ # Rope project settings
152
+ .ropeproject
153
+
154
+ # mkdocs documentation
155
+ /site
156
+
157
+ # mypy
158
+ .mypy_cache/
159
+ .dmypy.json
160
+ dmypy.json
161
+
162
+ # Pyre type checker
163
+ .pyre/
164
+
165
+ # pytype static type analyzer
166
+ .pytype/
167
+
168
+ # Cython debug symbols
169
+ cython_debug/
170
+
171
+ # PyCharm
172
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
173
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
174
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
175
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
176
+ #.idea/
177
+
178
+ # Abstra
179
+ # Abstra is an AI-powered process automation framework.
180
+ # Ignore directories containing user credentials, local state, and settings.
181
+ # Learn more at https://abstra.io/docs
182
+ .abstra/
183
+
184
+ # Visual Studio Code
185
+ # Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore
186
+ # that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore
187
+ # and can be added to the global gitignore or merged into this file. However, if you prefer,
188
+ # you could uncomment the following to ignore the entire vscode folder
189
+ # .vscode/
190
+
191
+ # Ruff stuff:
192
+ .ruff_cache/
193
+
194
+ # PyPI configuration file
195
+ .pypirc
196
+
197
+ # Cursor
198
+ # Cursor is an AI-powered code editor. `.cursorignore` specifies files/directories to
199
+ # exclude from AI features like autocomplete and code analysis. Recommended for sensitive data
200
+ # refer to https://docs.cursor.com/context/ignore-files
201
+ .cursorignore
202
+ .cursorindexingignore
203
+
204
+ # Marimo
205
+ marimo/_static/
206
+ marimo/_lsp/
207
+ __marimo__/
208
+
209
+ #Idea
210
+ .idea/
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Murf Inc.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,88 @@
1
+ Metadata-Version: 2.4
2
+ Name: livekit-murf
3
+ Version: 0.1.0
4
+ Summary: LiveKit Agents Plugin for Murf
5
+ Project-URL: Repository, https://github.com/murf-ai/livekit-murf
6
+ Project-URL: Issues, https://github.com/murf-ai/livekit-murf/issues
7
+ Author-email: Gaurav Singh <gaurav.singh@murf.ai>
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Keywords: audio,livekit,realtime,webrtc
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: License :: OSI Approved :: Apache Software License
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3 :: Only
15
+ Classifier: Programming Language :: Python :: 3.9
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Topic :: Multimedia :: Sound/Audio
18
+ Classifier: Topic :: Multimedia :: Video
19
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
20
+ Requires-Python: >=3.9.0
21
+ Requires-Dist: livekit-agents>=1.2.18
22
+ Description-Content-Type: text/markdown
23
+
24
+ # Livekit Murf
25
+
26
+ ![Murf AI Logo](https://murf.ai/public-assets/home/Murf_Logo.png)
27
+
28
+
29
+ Official [Murf AI](https://murf.ai/api) Text-to-Speech integration for [Livekit Agents](https://github.com/livekit/agents) - a framework for building voice and multimodal conversational AI applications.
30
+
31
+ > **Note**: This integration is maintained by Murf AI. As the official provider of the TTS service, we are committed to actively maintaining and updating this integration.
32
+
33
+
34
+ ## Installation
35
+
36
+ ```bash
37
+ pip install livekit-murf
38
+ ```
39
+
40
+ ## Livekit Starter Project
41
+
42
+ ```python
43
+ from livekit.agents import JobContext, WorkerOptions, cli, JobProcess, get_job_context
44
+ from livekit.agents.voice import Agent, AgentSession
45
+ from livekit.plugins import murf, openai, silero, deepgram
46
+
47
+ class MyAgent(Agent):
48
+ def __init__(self) -> None:
49
+ super().__init__(
50
+ instructions="You are a voice agent build using Murf TTS",
51
+ stt=deepgram.STT(model="nova-3"),
52
+ llm=openai.LLM(model="gpt-4o"),
53
+ tts=murf.TTS(voice="en-US-matthew", style="Conversation"),
54
+ vad=get_job_context().proc.userdata["vad"],
55
+ )
56
+
57
+ async def on_enter(self):
58
+ await self.session.say("Hi, I am a voice agent powered by Murf, how can I help you?")
59
+
60
+
61
+
62
+ async def entrypoint(ctx: JobContext):
63
+ await ctx.connect()
64
+ ctx.log_context_fields = {
65
+ "room": ctx.room.name,
66
+ }
67
+
68
+ session = AgentSession()
69
+
70
+ await session.start(
71
+ agent=MyAgent(),
72
+ room=ctx.room
73
+ )
74
+
75
+
76
+ def prewarm(proc: JobProcess):
77
+ proc.userdata["vad"] = silero.VAD.load()
78
+
79
+
80
+ if __name__ == "__main__":
81
+ cli.run_app(WorkerOptions(entrypoint_fnc=entrypoint, prewarm_fnc=prewarm))
82
+ ```
83
+
84
+ ## Pre-requisites
85
+
86
+ You'll need an API key from [Murf AI](https://murf.ai/api). It can be set as an environment variable: `MURF_API_KEY`
87
+
88
+ > **Compatibility**: Requires livekit-agents >= 1.2.18.
@@ -0,0 +1,65 @@
1
+ # Livekit Murf
2
+
3
+ ![Murf AI Logo](https://murf.ai/public-assets/home/Murf_Logo.png)
4
+
5
+
6
+ Official [Murf AI](https://murf.ai/api) Text-to-Speech integration for [Livekit Agents](https://github.com/livekit/agents) - a framework for building voice and multimodal conversational AI applications.
7
+
8
+ > **Note**: This integration is maintained by Murf AI. As the official provider of the TTS service, we are committed to actively maintaining and updating this integration.
9
+
10
+
11
+ ## Installation
12
+
13
+ ```bash
14
+ pip install livekit-murf
15
+ ```
16
+
17
+ ## Livekit Starter Project
18
+
19
+ ```python
20
+ from livekit.agents import JobContext, WorkerOptions, cli, JobProcess, get_job_context
21
+ from livekit.agents.voice import Agent, AgentSession
22
+ from livekit.plugins import murf, openai, silero, deepgram
23
+
24
+ class MyAgent(Agent):
25
+ def __init__(self) -> None:
26
+ super().__init__(
27
+ instructions="You are a voice agent build using Murf TTS",
28
+ stt=deepgram.STT(model="nova-3"),
29
+ llm=openai.LLM(model="gpt-4o"),
30
+ tts=murf.TTS(voice="en-US-matthew", style="Conversation"),
31
+ vad=get_job_context().proc.userdata["vad"],
32
+ )
33
+
34
+ async def on_enter(self):
35
+ await self.session.say("Hi, I am a voice agent powered by Murf, how can I help you?")
36
+
37
+
38
+
39
+ async def entrypoint(ctx: JobContext):
40
+ await ctx.connect()
41
+ ctx.log_context_fields = {
42
+ "room": ctx.room.name,
43
+ }
44
+
45
+ session = AgentSession()
46
+
47
+ await session.start(
48
+ agent=MyAgent(),
49
+ room=ctx.room
50
+ )
51
+
52
+
53
+ def prewarm(proc: JobProcess):
54
+ proc.userdata["vad"] = silero.VAD.load()
55
+
56
+
57
+ if __name__ == "__main__":
58
+ cli.run_app(WorkerOptions(entrypoint_fnc=entrypoint, prewarm_fnc=prewarm))
59
+ ```
60
+
61
+ ## Pre-requisites
62
+
63
+ You'll need an API key from [Murf AI](https://murf.ai/api). It can be set as an environment variable: `MURF_API_KEY`
64
+
65
+ > **Compatibility**: Requires livekit-agents >= 1.2.18.
@@ -0,0 +1,31 @@
1
+ """Murf AI plugin for LiveKit Agents"""
2
+
3
+ from .tts import TTS, ChunkedStream
4
+ from .version import __version__
5
+
6
+ __all__ = [
7
+ "TTS",
8
+ "ChunkedStream",
9
+ "__version__",
10
+ ]
11
+
12
+ from livekit.agents import Plugin
13
+
14
+ from .log import logger
15
+
16
+
17
+ class MurfPlugin(Plugin):
18
+ def __init__(self) -> None:
19
+ super().__init__(__name__, __version__, __package__, logger)
20
+
21
+
22
+ Plugin.register_plugin(MurfPlugin())
23
+
24
+ # Cleanup docs of unexported modules
25
+ _module = dir()
26
+ NOT_IN_ALL = [m for m in _module if m not in __all__]
27
+
28
+ __pdoc__ = {}
29
+
30
+ for n in NOT_IN_ALL:
31
+ __pdoc__[n] = False
@@ -0,0 +1,3 @@
1
+ import logging
2
+
3
+ logger = logging.getLogger("livekit.plugins.murf")
@@ -0,0 +1,61 @@
1
+ from typing import Literal
2
+
3
+ TTSLocales = Literal[
4
+ "en-US",
5
+ "en-UK",
6
+ "en-AU",
7
+ "en-IN",
8
+ "en-SCOTT",
9
+ "es-ES",
10
+ "es-MX",
11
+ "hi-IN",
12
+ "ta-IN",
13
+ "bn-IN",
14
+ "fr-FR",
15
+ "de-DE",
16
+ "it-IT",
17
+ "pt-BR",
18
+ "zh-CN",
19
+ "nl-NL",
20
+ "ja-JP",
21
+ "id-ID",
22
+ "ko-KR",
23
+ "ro-RO",
24
+ "tr-TR",
25
+ "pl-PL",
26
+ "sk-SK",
27
+ "hr-HR",
28
+ "el-GR",
29
+ "bg-BG",
30
+ ]
31
+
32
+ TTSModels = Literal["GEN2", "FALCON"]
33
+
34
+ TTSStyles = Literal[
35
+ "Promo",
36
+ "Narration",
37
+ "Calm",
38
+ "Conversation",
39
+ "Conversational",
40
+ "Sad",
41
+ "Angry",
42
+ "Sports Commentary",
43
+ "Newscast",
44
+ "Terrified",
45
+ "Inspirational",
46
+ "Customer Support Agent",
47
+ "Narration",
48
+ "Audiobook",
49
+ "Storytelling",
50
+ "Furious",
51
+ "Sobbing",
52
+ "Wizard",
53
+ "Clown",
54
+ ]
55
+
56
+ TTSEncoding = Literal[
57
+ "pcm", # pcm_s16le
58
+ ]
59
+
60
+ TTSDefaultVoiceId = "en-US-matthew"
61
+ TTSDefaultVoiceStyle = "Conversation"
@@ -0,0 +1,395 @@
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ import base64
5
+ import json
6
+ import os
7
+ import weakref
8
+ from dataclasses import dataclass, replace
9
+ from typing import Any
10
+
11
+ import aiohttp
12
+
13
+ from livekit.agents import (
14
+ APIConnectionError,
15
+ APIConnectOptions,
16
+ APIStatusError,
17
+ APITimeoutError,
18
+ tokenize,
19
+ tts,
20
+ utils,
21
+ )
22
+ from livekit.agents.types import DEFAULT_API_CONNECT_OPTIONS, NOT_GIVEN, NotGivenOr
23
+ from livekit.agents.utils import is_given
24
+
25
+ from .log import logger
26
+ from .models import (
27
+ TTSDefaultVoiceId,
28
+ TTSDefaultVoiceStyle,
29
+ TTSEncoding,
30
+ TTSLocales,
31
+ TTSModels,
32
+ TTSStyles,
33
+ )
34
+
35
+ API_AUTH_HEADER = "api-key"
36
+
37
+
38
+ @dataclass
39
+ class _TTSOptions:
40
+ api_key: str
41
+ locale: TTSLocales | str | None
42
+ model: TTSModels | str
43
+ voice: str
44
+ style: str | None
45
+ speed: int | None
46
+ pitch: int | None
47
+ sample_rate: int
48
+ encoding: TTSEncoding
49
+ base_url: str
50
+
51
+ def get_http_url(self, path: str) -> str:
52
+ return f"{self.base_url}{path}"
53
+
54
+ def get_ws_url(self, path: str) -> str:
55
+ return f"{self.base_url.replace('http', 'ws', 1)}{path}"
56
+
57
+
58
+ class TTS(tts.TTS):
59
+ def __init__(
60
+ self,
61
+ *,
62
+ api_key: str | None = None,
63
+ model: TTSModels | str = "FALCON",
64
+ locale: TTSLocales | str | None = None,
65
+ voice: str = TTSDefaultVoiceId,
66
+ style: TTSStyles | str | None = None,
67
+ speed: int | None = None,
68
+ pitch: int | None = None,
69
+ sample_rate: int = 24000,
70
+ encoding: TTSEncoding = "pcm",
71
+ base_url: str = "https://global.api.murf.ai",
72
+ http_session: aiohttp.ClientSession | None = None,
73
+ tokenizer: NotGivenOr[tokenize.SentenceTokenizer] = NOT_GIVEN,
74
+ text_pacing: tts.SentenceStreamPacer | bool = False,
75
+ ) -> None:
76
+ """
77
+ Create a new instance of Murf AI TTS.
78
+
79
+ See https://murf.ai/api/docs/api-reference/text-to-speech/stream-input for more details on the the Murf AI API.
80
+
81
+ Args:
82
+ api_key (str | None, optional): The Murf AI API key. If not provided, it will be read from the MURF_API_KEY environment variable.
83
+ model (TTSModels | str, optional): The Murf AI TTS model to use. Defaults to "FALCON".
84
+ locale (str | None, optional): The locale for synthesis (e.g., "en-US", "en-UK"). If not provided, will be inferred from voice.
85
+ voice (str, optional): The voice ID from Murf AI's voice library (e.g., "en-US-matthew"). Defaults to TTSDefaultVoiceId.
86
+ style (TTSStyles | str | None, optional): The voice style to apply (e.g., "Conversation"). Can be None for default style.
87
+ speed (int | None, optional): The speech speed control. Higher values = faster speech. None for default speed.
88
+ pitch (int | None, optional): The speech pitch control. Higher values = higher pitch. None for default pitch.
89
+ sample_rate (int, optional): The audio sample rate in Hz. Defaults to 24000.
90
+ encoding (str, optional): The audio encoding format. Defaults to "pcm".
91
+ http_session (aiohttp.ClientSession | None, optional): An existing aiohttp ClientSession to use. If not provided, a new session will be created.
92
+ base_url (str, optional): The base URL for the Murf AI API. Defaults to "https://global.api.murf.ai".
93
+ tokenizer (tokenize.SentenceTokenizer, optional): The tokenizer to use. Defaults to tokenize.basic.SentenceTokenizer(min_sentence_len=BUFFERED_WORDS_COUNT).
94
+ text_pacing (tts.SentenceStreamPacer | bool, optional): Stream pacer for the TTS. Set to True to use the default pacer, False to disable.
95
+ """ # noqa: E501
96
+
97
+ super().__init__(
98
+ capabilities=tts.TTSCapabilities(streaming=True),
99
+ sample_rate=sample_rate,
100
+ num_channels=1,
101
+ )
102
+
103
+ murf_api_key = api_key or os.environ.get("MURF_API_KEY")
104
+ if not murf_api_key:
105
+ raise ValueError("MURF_API_KEY must be set")
106
+
107
+ self._opts = _TTSOptions(
108
+ api_key=murf_api_key,
109
+ model=model,
110
+ locale=locale,
111
+ voice=voice,
112
+ style=style or TTSDefaultVoiceStyle,
113
+ speed=speed,
114
+ pitch=pitch,
115
+ sample_rate=sample_rate,
116
+ encoding=encoding,
117
+ base_url=base_url,
118
+ )
119
+ self._session = http_session
120
+ self._pool = utils.ConnectionPool[aiohttp.ClientWebSocketResponse](
121
+ connect_cb=self._connect_ws,
122
+ close_cb=self._close_ws,
123
+ max_session_duration=300,
124
+ mark_refreshed_on_get=True,
125
+ )
126
+ self._streams = weakref.WeakSet[SynthesizeStream]()
127
+ self._sentence_tokenizer = (
128
+ tokenizer if is_given(tokenizer) else tokenize.blingfire.SentenceTokenizer()
129
+ )
130
+ self._stream_pacer: tts.SentenceStreamPacer | None = None
131
+ if text_pacing is True:
132
+ self._stream_pacer = tts.SentenceStreamPacer()
133
+ elif isinstance(text_pacing, tts.SentenceStreamPacer):
134
+ self._stream_pacer = text_pacing
135
+
136
+ @property
137
+ def model(self) -> str:
138
+ return self._opts.model
139
+
140
+ @property
141
+ def provider(self) -> str:
142
+ return "Murf"
143
+
144
+ async def _connect_ws(self, timeout: float) -> aiohttp.ClientWebSocketResponse:
145
+ session = self._ensure_session()
146
+ url = self._opts.get_ws_url(
147
+ f"/v1/speech/stream-input?api-key={self._opts.api_key}&sample_rate={self._opts.sample_rate}&format={self._opts.encoding}&model={self._opts.model}"
148
+ )
149
+ return await asyncio.wait_for(session.ws_connect(url), timeout)
150
+
151
+ async def _close_ws(self, ws: aiohttp.ClientWebSocketResponse) -> None:
152
+ await ws.close()
153
+
154
+ def _ensure_session(self) -> aiohttp.ClientSession:
155
+ if not self._session:
156
+ self._session = utils.http_context.http_session()
157
+
158
+ return self._session
159
+
160
+ def prewarm(self) -> None:
161
+ self._pool.prewarm()
162
+
163
+ def update_options(
164
+ self,
165
+ *,
166
+ locale: NotGivenOr[str] = NOT_GIVEN,
167
+ voice: NotGivenOr[str] = NOT_GIVEN,
168
+ style: NotGivenOr[str | None] = NOT_GIVEN,
169
+ speed: NotGivenOr[int | None] = NOT_GIVEN,
170
+ pitch: NotGivenOr[int | None] = NOT_GIVEN,
171
+ ) -> None:
172
+ """
173
+ Update the Text-to-Speech (TTS) configuration options.
174
+
175
+ This method allows updating the TTS settings, including model, locale, voice, style,
176
+ speed and pitch. If any parameter is not provided, the existing value will be retained.
177
+
178
+ Args:
179
+ locale (str, optional): The locale for synthesis (e.g., "en-US", "en-UK").
180
+ voice (str, optional): The voice ID from Murf AI's voice library. (e.g. "en-US-matthew")
181
+ style (str | None, optional): The voice style to apply (e.g., "Conversation", "Promo").
182
+ speed (int | None, optional): Controls the speech speed. Positive values increase speed, negative values decrease it. Valid range: -50 to 50.
183
+ pitch (int | None, optional): Controls the speech pitch. Positive values raise pitch, negative values lower it. Valid range: -50 to 50.
184
+ """
185
+ if is_given(locale):
186
+ self._opts.locale = locale
187
+ if is_given(voice):
188
+ self._opts.voice = voice
189
+ if is_given(style):
190
+ self._opts.style = style
191
+ if is_given(speed):
192
+ self._opts.speed = speed
193
+ if is_given(pitch):
194
+ self._opts.pitch = pitch
195
+
196
+ def synthesize(
197
+ self, text: str, *, conn_options: APIConnectOptions = DEFAULT_API_CONNECT_OPTIONS
198
+ ) -> ChunkedStream:
199
+ return ChunkedStream(tts=self, input_text=text, conn_options=conn_options)
200
+
201
+ def stream(
202
+ self, *, conn_options: APIConnectOptions = DEFAULT_API_CONNECT_OPTIONS
203
+ ) -> SynthesizeStream:
204
+ stream = SynthesizeStream(tts=self, conn_options=conn_options)
205
+ self._streams.add(stream)
206
+ return stream
207
+
208
+ async def aclose(self) -> None:
209
+ for stream in list(self._streams):
210
+ await stream.aclose()
211
+
212
+ self._streams.clear()
213
+ await self._pool.aclose()
214
+
215
+
216
+ class ChunkedStream(tts.ChunkedStream):
217
+ """Synthesize chunked text using the http streaming output endpoint"""
218
+
219
+ def __init__(self, *, tts: TTS, input_text: str, conn_options: APIConnectOptions) -> None:
220
+ super().__init__(tts=tts, input_text=input_text, conn_options=conn_options)
221
+ self._tts: TTS = tts
222
+ self._opts = replace(tts._opts)
223
+
224
+ async def _run(self, output_emitter: tts.AudioEmitter) -> None:
225
+ try:
226
+ async with self._tts._ensure_session().post(
227
+ self._opts.get_http_url("/v1/speech/stream"),
228
+ headers={API_AUTH_HEADER: self._opts.api_key},
229
+ json={
230
+ "text": self._input_text,
231
+ "model": self._opts.model,
232
+ "multiNativeLocale": self._opts.locale,
233
+ "voice_id": self._opts.voice,
234
+ "style": self._opts.style,
235
+ "rate": self._opts.speed,
236
+ "pitch": self._opts.pitch,
237
+ "format": self._opts.encoding,
238
+ "sample_rate": self._opts.sample_rate,
239
+ },
240
+ timeout=aiohttp.ClientTimeout(total=30, sock_connect=self._conn_options.timeout),
241
+ ) as resp:
242
+ resp.raise_for_status()
243
+
244
+ output_emitter.initialize(
245
+ request_id=utils.shortuuid(),
246
+ sample_rate=self._opts.sample_rate,
247
+ num_channels=1,
248
+ mime_type="audio/pcm",
249
+ )
250
+
251
+ async for data, _ in resp.content.iter_chunks():
252
+ output_emitter.push(data)
253
+
254
+ output_emitter.flush()
255
+ except asyncio.TimeoutError:
256
+ raise APITimeoutError() from None
257
+ except aiohttp.ClientResponseError as e:
258
+ raise APIStatusError(
259
+ message=e.message, status_code=e.status, request_id=None, body=None
260
+ ) from None
261
+ except Exception as e:
262
+ raise APIConnectionError() from e
263
+
264
+
265
+ class SynthesizeStream(tts.SynthesizeStream):
266
+ def __init__(self, *, tts: TTS, conn_options: APIConnectOptions):
267
+ super().__init__(tts=tts, conn_options=conn_options)
268
+ self._tts: TTS = tts
269
+ self._opts = replace(tts._opts)
270
+
271
+ async def _run(self, output_emitter: tts.AudioEmitter) -> None:
272
+ request_id = utils.shortuuid()
273
+ output_emitter.initialize(
274
+ request_id=request_id,
275
+ sample_rate=self._opts.sample_rate,
276
+ num_channels=1,
277
+ mime_type="audio/pcm",
278
+ stream=True,
279
+ )
280
+
281
+ input_sent_event = asyncio.Event()
282
+
283
+ sent_tokenizer_stream = self._tts._sentence_tokenizer.stream()
284
+ if self._tts._stream_pacer:
285
+ sent_tokenizer_stream = self._tts._stream_pacer.wrap(
286
+ sent_stream=sent_tokenizer_stream,
287
+ audio_emitter=output_emitter,
288
+ )
289
+
290
+ async def _sentence_stream_task(ws: aiohttp.ClientWebSocketResponse) -> None:
291
+ context_id = utils.shortuuid()
292
+ base_pkt = _to_murf_websocket_pkt(self._opts)
293
+ async for ev in sent_tokenizer_stream:
294
+ token_pkt = base_pkt.copy()
295
+ token_pkt["context_id"] = context_id
296
+ token_pkt["text"] = ev.token + " "
297
+ self._mark_started()
298
+ await ws.send_str(json.dumps(token_pkt))
299
+ input_sent_event.set()
300
+
301
+ end_pkt = base_pkt.copy()
302
+ end_pkt["context_id"] = context_id
303
+ end_pkt["end"] = True
304
+ await ws.send_str(json.dumps(end_pkt))
305
+ input_sent_event.set()
306
+
307
+ async def _input_task() -> None:
308
+ async for data in self._input_ch:
309
+ if isinstance(data, self._FlushSentinel):
310
+ sent_tokenizer_stream.flush()
311
+ continue
312
+
313
+ sent_tokenizer_stream.push_text(data)
314
+
315
+ sent_tokenizer_stream.end_input()
316
+
317
+ async def _recv_task(ws: aiohttp.ClientWebSocketResponse) -> None:
318
+ current_segment_id: str | None = None
319
+ await input_sent_event.wait()
320
+ while True:
321
+ msg = await ws.receive()
322
+ if msg.type in (
323
+ aiohttp.WSMsgType.CLOSED,
324
+ aiohttp.WSMsgType.CLOSE,
325
+ aiohttp.WSMsgType.CLOSING,
326
+ ):
327
+ raise APIStatusError(
328
+ "Murf AI connection closed unexpectedly", request_id=request_id
329
+ )
330
+
331
+ if msg.type != aiohttp.WSMsgType.TEXT:
332
+ logger.warning("unexpected Murf AI message type %s", msg.type)
333
+ continue
334
+
335
+ data = json.loads(msg.data)
336
+ segment_id = data.get("context_id")
337
+ if current_segment_id is None:
338
+ current_segment_id = segment_id
339
+ output_emitter.start_segment(segment_id=current_segment_id)
340
+ if data.get("audio"):
341
+ b64data = base64.b64decode(data["audio"])
342
+ output_emitter.push(b64data)
343
+ elif data.get("final"):
344
+ if sent_tokenizer_stream.closed:
345
+ # close only if the input stream is closed
346
+ output_emitter.end_input()
347
+ break
348
+ else:
349
+ logger.warning("unexpected message %s", data)
350
+
351
+ try:
352
+ async with self._tts._pool.connection(timeout=self._conn_options.timeout) as ws:
353
+ tasks = [
354
+ asyncio.create_task(_input_task()),
355
+ asyncio.create_task(_sentence_stream_task(ws)),
356
+ asyncio.create_task(_recv_task(ws)),
357
+ ]
358
+
359
+ try:
360
+ await asyncio.gather(*tasks)
361
+ finally:
362
+ input_sent_event.set()
363
+ await sent_tokenizer_stream.aclose()
364
+ await utils.aio.gracefully_cancel(*tasks)
365
+ except asyncio.TimeoutError:
366
+ raise APITimeoutError() from None
367
+ except aiohttp.ClientResponseError as e:
368
+ raise APIStatusError(
369
+ message=e.message, status_code=e.status, request_id=None, body=None
370
+ ) from None
371
+ except Exception as e:
372
+ raise APIConnectionError() from e
373
+
374
+
375
+ def _to_murf_websocket_pkt(opts: _TTSOptions) -> dict[str, Any]:
376
+ voice_config: dict[str, Any] = {}
377
+
378
+ if opts.voice:
379
+ voice_config["voice_id"] = opts.voice
380
+
381
+ if opts.style:
382
+ voice_config["style"] = opts.style
383
+
384
+ if opts.speed:
385
+ voice_config["rate"] = opts.speed
386
+
387
+ if opts.pitch:
388
+ voice_config["pitch"] = opts.pitch
389
+
390
+ if opts.locale:
391
+ voice_config["multi_native_locale"] = opts.locale
392
+
393
+ return {
394
+ "voice_config": voice_config,
395
+ }
@@ -0,0 +1 @@
1
+ __version__ = "0.1.0"
@@ -0,0 +1,38 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "livekit-murf"
7
+ dynamic = ["version"]
8
+ description = "LiveKit Agents Plugin for Murf"
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ requires-python = ">=3.9.0"
12
+ authors = [{ name = "Gaurav Singh", email = "gaurav.singh@murf.ai" }]
13
+ keywords = ["webrtc", "realtime", "audio", "livekit"]
14
+ classifiers = [
15
+ "Intended Audience :: Developers",
16
+ "License :: OSI Approved :: Apache Software License",
17
+ "Topic :: Multimedia :: Sound/Audio",
18
+ "Topic :: Multimedia :: Video",
19
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
20
+ "Programming Language :: Python :: 3",
21
+ "Programming Language :: Python :: 3.9",
22
+ "Programming Language :: Python :: 3.10",
23
+ "Programming Language :: Python :: 3 :: Only",
24
+ ]
25
+ dependencies = ["livekit-agents>=1.2.18"]
26
+
27
+ [project.urls]
28
+ Repository = "https://github.com/murf-ai/livekit-murf"
29
+ Issues = "https://github.com/murf-ai/livekit-murf/issues"
30
+
31
+ [tool.hatch.version]
32
+ path = "livekit/plugins/murf/version.py"
33
+
34
+ [tool.hatch.build.targets.wheel]
35
+ packages = ["livekit"]
36
+
37
+ [tool.hatch.build.targets.sdist]
38
+ include = ["/livekit"]