livekit-plugins-clova 1.0.0.dev4__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.

Potentially problematic release.


This version of livekit-plugins-clova might be problematic. Click here for more details.

@@ -0,0 +1,168 @@
1
+ **/.vscode
2
+ **/.DS_Store
3
+
4
+ # Byte-compiled / optimized / DLL files
5
+ __pycache__/
6
+ *.py[cod]
7
+ *$py.class
8
+
9
+ # C extensions
10
+ *.so
11
+
12
+ # Distribution / packaging
13
+ .Python
14
+ build/
15
+ develop-eggs/
16
+ dist/
17
+ downloads/
18
+ eggs/
19
+ .eggs/
20
+ lib/
21
+ lib64/
22
+ parts/
23
+ sdist/
24
+ var/
25
+ wheels/
26
+ share/python-wheels/
27
+ *.egg-info/
28
+ .installed.cfg
29
+ *.egg
30
+ MANIFEST
31
+
32
+ # PyInstaller
33
+ # Usually these files are written by a python script from a template
34
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
35
+ *.manifest
36
+ *.spec
37
+
38
+ # Installer logs
39
+ pip-log.txt
40
+ pip-delete-this-directory.txt
41
+
42
+ # Unit test / coverage reports
43
+ htmlcov/
44
+ .tox/
45
+ .nox/
46
+ .coverage
47
+ .coverage.*
48
+ .cache
49
+ nosetests.xml
50
+ coverage.xml
51
+ *.cover
52
+ *.py,cover
53
+ .hypothesis/
54
+ .pytest_cache/
55
+ cover/
56
+
57
+ # Translations
58
+ *.mo
59
+ *.pot
60
+
61
+ # Django stuff:
62
+ *.log
63
+ local_settings.py
64
+ db.sqlite3
65
+ db.sqlite3-journal
66
+
67
+ # Flask stuff:
68
+ instance/
69
+ .webassets-cache
70
+
71
+ # Scrapy stuff:
72
+ .scrapy
73
+
74
+ # Sphinx documentation
75
+ docs/_build/
76
+
77
+ # PyBuilder
78
+ .pybuilder/
79
+ target/
80
+
81
+ # Jupyter Notebook
82
+ .ipynb_checkpoints
83
+
84
+ # IPython
85
+ profile_default/
86
+ ipython_config.py
87
+
88
+ # pyenv
89
+ # For a library or package, you might want to ignore these files since the code is
90
+ # intended to run in multiple environments; otherwise, check them in:
91
+ # .python-version
92
+
93
+ # pipenv
94
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
95
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
96
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
97
+ # install all needed dependencies.
98
+ #Pipfile.lock
99
+
100
+ # poetry
101
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
102
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
103
+ # commonly ignored for libraries.
104
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
105
+ #poetry.lock
106
+
107
+ # pdm
108
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
109
+ #pdm.lock
110
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
111
+ # in version control.
112
+ # https://pdm.fming.dev/#use-with-ide
113
+ .pdm.toml
114
+
115
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
116
+ __pypackages__/
117
+
118
+ # Celery stuff
119
+ celerybeat-schedule
120
+ celerybeat.pid
121
+
122
+ # SageMath parsed files
123
+ *.sage.py
124
+
125
+ # Environments
126
+ .env
127
+ .venv
128
+ env/
129
+ venv/
130
+ ENV/
131
+ env.bak/
132
+ venv.bak/
133
+
134
+ # Spyder project settings
135
+ .spyderproject
136
+ .spyproject
137
+
138
+ # Rope project settings
139
+ .ropeproject
140
+
141
+ # mkdocs documentation
142
+ /site
143
+
144
+ # mypy
145
+ .mypy_cache/
146
+ .dmypy.json
147
+ dmypy.json
148
+
149
+ # Pyre type checker
150
+ .pyre/
151
+
152
+ # pytype static type analyzer
153
+ .pytype/
154
+
155
+ # Cython debug symbols
156
+ cython_debug/
157
+
158
+ # PyCharm
159
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
160
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
161
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
162
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
163
+ .idea/
164
+
165
+ node_modules
166
+
167
+ credentials.json
168
+ pyrightconfig.json
@@ -0,0 +1,36 @@
1
+ Metadata-Version: 2.4
2
+ Name: livekit-plugins-clova
3
+ Version: 1.0.0.dev4
4
+ Summary: LiveKit Agents Plugin for LINE Clova STT
5
+ Project-URL: Documentation, https://docs.livekit.io
6
+ Project-URL: Website, https://livekit.io/
7
+ Project-URL: Source, https://github.com/livekit/agents
8
+ Author-email: LiveKit <support@livekit.io>
9
+ License-Expression: Apache-2.0
10
+ Keywords: audio,livekit,realtime,video,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.0.0.dev4
22
+ Description-Content-Type: text/markdown
23
+
24
+ # LiveKit Plugins Clova
25
+
26
+ Agent Framework plugin for speech-to-text with [Clova](https://api.ncloud-docs.com/docs/)'s API. Currently supports speech-to-text.
27
+
28
+ ## Installation
29
+
30
+ ```bash
31
+ pip install livekit-plugins-clova
32
+ ```
33
+
34
+ ## Pre-requisites
35
+
36
+ You need invoke url and secret key from Naver cloud platform -> Clova Speech and set as environment variables: `CLOVA_STT_INVOKE_URL` & `CLOVA_STT_SECRET_KEY`
@@ -0,0 +1,13 @@
1
+ # LiveKit Plugins Clova
2
+
3
+ Agent Framework plugin for speech-to-text with [Clova](https://api.ncloud-docs.com/docs/)'s API. Currently supports speech-to-text.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ pip install livekit-plugins-clova
9
+ ```
10
+
11
+ ## Pre-requisites
12
+
13
+ You need invoke url and secret key from Naver cloud platform -> Clova Speech and set as environment variables: `CLOVA_STT_INVOKE_URL` & `CLOVA_STT_SECRET_KEY`
@@ -0,0 +1,30 @@
1
+ from .stt import STT
2
+ from .version import __version__
3
+
4
+ __all__ = [
5
+ "STT",
6
+ "__version__",
7
+ ]
8
+
9
+
10
+ from livekit.agents import Plugin
11
+
12
+
13
+ class ClovaSTTPlugin(Plugin):
14
+ def __init__(self):
15
+ super().__init__(__name__, __version__, __package__)
16
+
17
+ def download_files(self):
18
+ pass
19
+
20
+
21
+ Plugin.register_plugin(ClovaSTTPlugin())
22
+
23
+ # Cleanup docs of unexported modules
24
+ _module = dir()
25
+ NOT_IN_ALL = [m for m in _module if m not in __all__]
26
+
27
+ __pdoc__ = {}
28
+
29
+ for n in NOT_IN_ALL:
30
+ __pdoc__[n] = False
@@ -0,0 +1,13 @@
1
+ import io
2
+
3
+ from pydub import AudioSegment
4
+
5
+
6
+ def resample_audio(audio_bytes, original_sample_rate, target_sample_rate):
7
+ resampled_audio = AudioSegment.from_raw(
8
+ io.BytesIO(audio_bytes),
9
+ sample_width=2,
10
+ frame_rate=original_sample_rate,
11
+ channels=1,
12
+ ).set_frame_rate(target_sample_rate)
13
+ return resampled_audio.raw_data
@@ -0,0 +1,2 @@
1
+ CLOVA_INPUT_SAMPLE_RATE = 16000
2
+ LIVEKIT_INPUT_SAMPLE_RATE = 48000
@@ -0,0 +1,3 @@
1
+ import logging
2
+
3
+ logger = logging.getLogger("livekit.plugins.clova")
@@ -0,0 +1,15 @@
1
+ from typing import Literal
2
+
3
+ ClovaSttLanguages = Literal["ko-KR", "en-US", "enko", "ja", "zh-cn", "zh-tw"]
4
+
5
+ ClovaSpeechAPIType = Literal["recognizer/object-storage", "recognizer/url", "recognizer/upload"]
6
+
7
+ clova_languages_mapping = {
8
+ "en": "en-US",
9
+ "ko-KR": "ko-KR",
10
+ "en-US": "en-US",
11
+ "enko": "enko",
12
+ "ja": "ja",
13
+ "zh-cn": "zh-cn",
14
+ "zh-tw": "zh-tw",
15
+ }
@@ -0,0 +1,145 @@
1
+ # Copyright 2023 LiveKit, Inc.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from __future__ import annotations
16
+
17
+ import asyncio
18
+ import io
19
+ import json
20
+ import os
21
+ import time
22
+ import wave
23
+
24
+ import aiohttp
25
+
26
+ from livekit.agents import APIConnectOptions, APIStatusError, APITimeoutError, stt, utils
27
+ from livekit.agents.stt import SpeechEventType, STTCapabilities
28
+ from livekit.agents.utils import AudioBuffer, merge_frames
29
+ from livekit.plugins.clova.constants import CLOVA_INPUT_SAMPLE_RATE
30
+
31
+ from .common import resample_audio
32
+ from .log import logger
33
+ from .models import ClovaSpeechAPIType, ClovaSttLanguages, clova_languages_mapping
34
+
35
+
36
+ class STT(stt.STT):
37
+ def __init__(
38
+ self,
39
+ *,
40
+ language: ClovaSttLanguages = "en-US",
41
+ secret: str | None = None,
42
+ invoke_url: str | None = None,
43
+ http_session: aiohttp.ClientSession | None = None,
44
+ threshold: float = 0.5,
45
+ ):
46
+ """
47
+ Create a new instance of Clova STT.
48
+
49
+ ``secret`` and ``invoke_url`` must be set, either using arguments or by setting the
50
+ ``CLOVA_STT_SECRET_KEY`` and ``CLOVA_STT_INVOKE_URL`` environmental variables, respectively.
51
+ """
52
+
53
+ super().__init__(capabilities=STTCapabilities(streaming=False, interim_results=True))
54
+ self._secret = secret or os.environ.get("CLOVA_STT_SECRET_KEY")
55
+ self._invoke_url = invoke_url or os.environ.get("CLOVA_STT_INVOKE_URL")
56
+ self._language = clova_languages_mapping.get(language, language)
57
+ self._session = http_session
58
+ if self._secret is None:
59
+ raise ValueError(
60
+ "Clova STT secret key is required. It should be set with env CLOVA_STT_SECRET_KEY"
61
+ )
62
+ self.threshold = threshold
63
+
64
+ def update_options(self, *, language: str | None = None) -> None:
65
+ self._language = clova_languages_mapping.get(language, language) or self._language
66
+
67
+ def _ensure_session(self) -> aiohttp.ClientSession:
68
+ if not self._session:
69
+ self._session = utils.http_context.http_session()
70
+ return self._session
71
+
72
+ def url_builder(self, process_method: ClovaSpeechAPIType = "recognizer/upload") -> str:
73
+ return f"{self._invoke_url}/{process_method}"
74
+
75
+ async def _recognize_impl(
76
+ self,
77
+ buffer: AudioBuffer,
78
+ *,
79
+ language: ClovaSttLanguages | str | None,
80
+ conn_options: APIConnectOptions,
81
+ ) -> stt.SpeechEvent:
82
+ try:
83
+ url = self.url_builder()
84
+ payload = json.dumps({"language": self._language, "completion": "sync"})
85
+
86
+ buffer = merge_frames(buffer)
87
+ buffer_bytes = resample_audio(
88
+ buffer.data.tobytes(), buffer.sample_rate, CLOVA_INPUT_SAMPLE_RATE
89
+ )
90
+
91
+ io_buffer = io.BytesIO()
92
+ with wave.open(io_buffer, "wb") as wav:
93
+ wav.setnchannels(1)
94
+ wav.setsampwidth(2) # 16-bit
95
+ wav.setframerate(CLOVA_INPUT_SAMPLE_RATE)
96
+ wav.writeframes(buffer_bytes)
97
+ io_buffer.seek(0)
98
+
99
+ headers = {"X-CLOVASPEECH-API-KEY": self._secret}
100
+ form_data = aiohttp.FormData()
101
+ form_data.add_field("params", payload)
102
+ form_data.add_field("media", io_buffer, filename="audio.wav", content_type="audio/wav")
103
+ start = time.time()
104
+ async with self._ensure_session().post(
105
+ url,
106
+ data=form_data,
107
+ headers=headers,
108
+ timeout=aiohttp.ClientTimeout(
109
+ total=30,
110
+ sock_connect=conn_options.timeout,
111
+ ),
112
+ ) as response:
113
+ response_data = await response.json()
114
+ end = time.time()
115
+ text = response_data.get("text")
116
+ confidence = response_data.get("confidence")
117
+ logger.info(f"{text} | {confidence} | total_seconds: {end - start}")
118
+ if not text or "error" in response_data:
119
+ raise ValueError(f"Unexpected response: {response_data}")
120
+ if confidence < self.threshold:
121
+ raise ValueError(
122
+ f"Confidence: {confidence} is bellow threshold {self.threshold}. Skipping."
123
+ )
124
+ logger.info(f"final event: {response_data}")
125
+ return self._transcription_to_speech_event(text=text)
126
+
127
+ except asyncio.TimeoutError as e:
128
+ raise APITimeoutError() from e
129
+ except aiohttp.ClientResponseError as e:
130
+ raise APIStatusError(
131
+ message=e.message,
132
+ status_code=e.status,
133
+ request_id=None,
134
+ body=None,
135
+ ) from e
136
+
137
+ def _transcription_to_speech_event(
138
+ self,
139
+ event_type: SpeechEventType = stt.SpeechEventType.INTERIM_TRANSCRIPT,
140
+ text: str | None = None,
141
+ ) -> stt.SpeechEvent:
142
+ return stt.SpeechEvent(
143
+ type=event_type,
144
+ alternatives=[stt.SpeechData(text=text, language=self._language)],
145
+ )
@@ -0,0 +1,15 @@
1
+ # Copyright 2023 LiveKit, Inc.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ __version__ = "1.0.0.dev4"
@@ -0,0 +1,39 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "livekit-plugins-clova"
7
+ dynamic = ["version"]
8
+ description = "LiveKit Agents Plugin for LINE Clova STT"
9
+ readme = "README.md"
10
+ license = "Apache-2.0"
11
+ requires-python = ">=3.9.0"
12
+ authors = [{ name = "LiveKit", email = "support@livekit.io" }]
13
+ keywords = ["webrtc", "realtime", "audio", "video", "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.0.0.dev4"]
26
+
27
+ [project.urls]
28
+ Documentation = "https://docs.livekit.io"
29
+ Website = "https://livekit.io/"
30
+ Source = "https://github.com/livekit/agents"
31
+
32
+ [tool.hatch.version]
33
+ path = "livekit/plugins/clova/version.py"
34
+
35
+ [tool.hatch.build.targets.wheel]
36
+ packages = ["livekit"]
37
+
38
+ [tool.hatch.build.targets.sdist]
39
+ include = ["/livekit"]