livekit-plugins-duplexjev-detectors 1.9.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,190 @@
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
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
+
110
+ # pdm
111
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
112
+ #pdm.lock
113
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
114
+ # in version control.
115
+ # https://pdm.fming.dev/latest/usage/project/#working-with-version-control
116
+ .pdm.toml
117
+ .pdm-python
118
+ .pdm-build/
119
+
120
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
121
+ __pypackages__/
122
+
123
+ # Celery stuff
124
+ celerybeat-schedule
125
+ celerybeat.pid
126
+
127
+ # SageMath parsed files
128
+ *.sage.py
129
+
130
+ # Environments
131
+ .env
132
+ .venv
133
+ env/
134
+ venv/
135
+ ENV/
136
+ env.bak/
137
+ venv.bak/
138
+
139
+ # Spyder project settings
140
+ .spyderproject
141
+ .spyproject
142
+
143
+ # Rope project settings
144
+ .ropeproject
145
+
146
+ # mkdocs documentation
147
+ /site
148
+
149
+ # mypy
150
+ .mypy_cache/
151
+ .dmypy.json
152
+ dmypy.json
153
+
154
+ # Pyre type checker
155
+ .pyre/
156
+
157
+ # pytype static type analyzer
158
+ .pytype/
159
+
160
+ # Cython debug symbols
161
+ cython_debug/
162
+
163
+ # PyCharm
164
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
165
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
166
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
167
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
168
+ #.idea/
169
+
170
+ # Ruff stuff:
171
+ .ruff_cache/
172
+
173
+ # PyPI configuration file
174
+ .pypirc
175
+
176
+ # tests
177
+ test.py
178
+
179
+ .python-version
180
+
181
+ *.ipynb
182
+ config.yaml
183
+
184
+ # Documentation website
185
+ website/node_modules/
186
+ website/out/
187
+ website/.next/
188
+ .cursor
189
+
190
+ .DS_Store
@@ -0,0 +1,25 @@
1
+ Metadata-Version: 2.4
2
+ Name: livekit-plugins-duplexjev-detectors
3
+ Version: 1.9.0
4
+ Summary: DuplexJev turn detection and interruption detection for LiveKit Agents
5
+ Author-email: wangmengdi <790990241@qq.com>
6
+ Keywords: audio,duplexjev,livekit,realtime,turn-detection,webrtc
7
+ Classifier: Intended Audience :: Developers
8
+ Classifier: License :: OSI Approved :: Apache Software License
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Programming Language :: Python :: 3 :: Only
11
+ Classifier: Programming Language :: Python :: 3.10
12
+ Classifier: Topic :: Multimedia :: Sound/Audio
13
+ Classifier: Topic :: Multimedia :: Video
14
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
15
+ Requires-Python: >=3.10
16
+ Requires-Dist: aiohttp>=3.10.10
17
+ Requires-Dist: livekit-agents<1.10,>=1.9.0
18
+ Requires-Dist: numpy>=1.26
19
+ Description-Content-Type: text/markdown
20
+
21
+ # livekit-plugins-duplexjev-detectors
22
+
23
+ 面向 LiveKit Agents 的 DuplexJev 插件,用同一套语音模型做轮次检测和打断检测。判断来自音频,不依赖转写。
24
+
25
+ 📚 完整文档:[https://di-osc.github.io/livekit-plugins-chinese/plugins/duplexjev-detectors](https://di-osc.github.io/livekit-plugins-chinese/plugins/duplexjev-detectors)
@@ -0,0 +1,5 @@
1
+ # livekit-plugins-duplexjev-detectors
2
+
3
+ 面向 LiveKit Agents 的 DuplexJev 插件,用同一套语音模型做轮次检测和打断检测。判断来自音频,不依赖转写。
4
+
5
+ 📚 完整文档:[https://di-osc.github.io/livekit-plugins-chinese/plugins/duplexjev-detectors](https://di-osc.github.io/livekit-plugins-chinese/plugins/duplexjev-detectors)
@@ -0,0 +1,55 @@
1
+ """DuplexJev turn detection and interruption detection for LiveKit Agents.
2
+
3
+ from livekit.agents import AgentSession
4
+ from livekit.plugins import duplexjev_detectors, silero
5
+
6
+ session = AgentSession(
7
+ vad=silero.VAD.load(min_silence_duration=0.25),
8
+ turn_handling={
9
+ "turn_detection": duplexjev_detectors.TurnDetector(api_url="http://localhost:8420"),
10
+ "interruption": duplexjev_detectors.interruption_options(),
11
+ },
12
+ )
13
+ """
14
+
15
+ from livekit.agents import Plugin
16
+
17
+ from .client import DEFAULT_URL, SAMPLE_RATE, TURN_QUESTION
18
+ from .interruption import (
19
+ InterruptionDetector,
20
+ InterruptionStream,
21
+ install,
22
+ interruption_options,
23
+ )
24
+ from .log import logger
25
+ from .turn_detector import TurnDetector, TurnDetectorStream
26
+ from .version import __version__
27
+
28
+ __all__ = [
29
+ "TurnDetector",
30
+ "TurnDetectorStream",
31
+ "InterruptionDetector",
32
+ "InterruptionStream",
33
+ "interruption_options",
34
+ "install",
35
+ "DEFAULT_URL",
36
+ "SAMPLE_RATE",
37
+ "TURN_QUESTION",
38
+ "__version__",
39
+ ]
40
+
41
+
42
+ class DuplexJevDetectorsPlugin(Plugin):
43
+ def __init__(self) -> None:
44
+ super().__init__(__name__, __version__, __package__, logger)
45
+
46
+
47
+ Plugin.register_plugin(DuplexJevDetectorsPlugin())
48
+
49
+ _module = dir()
50
+ NOT_IN_ALL = [m for m in _module if m not in __all__]
51
+
52
+ __pdoc__ = {}
53
+
54
+ for n in NOT_IN_ALL:
55
+ __pdoc__[n] = False
@@ -0,0 +1,154 @@
1
+ """Shared DuplexJev gateway helpers for turn and interruption detection."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import io
6
+ import wave
7
+ from collections.abc import AsyncIterator, Mapping
8
+ from contextlib import asynccontextmanager
9
+ from typing import Any
10
+
11
+ import aiohttp
12
+ import numpy as np
13
+
14
+ from livekit.agents import utils
15
+
16
+ SAMPLE_RATE = 16000
17
+ DEFAULT_URL = "https://api.adventists.cn/duplexjev"
18
+
19
+ TURN_QUESTION = {
20
+ "en": {
21
+ "id": "turn",
22
+ "text": "Has the user finished speaking?",
23
+ "options": [
24
+ "finished, the assistant can reply",
25
+ "not finished, still talking",
26
+ "just a backchannel, not taking the turn",
27
+ "hesitating or asking to wait",
28
+ ],
29
+ "lang": "en",
30
+ },
31
+ }
32
+
33
+ BARGE_IN_QUESTION = {
34
+ "id": "barge_in",
35
+ "text": (
36
+ "Is the user trying to interrupt or take over the conversation? "
37
+ "Answer no for a brief listener acknowledgment such as 'mm-hmm' or 'uh-huh'. "
38
+ "Answer yes if the user is asking the assistant to stop or intends to take the floor."
39
+ ),
40
+ "options": ["yes", "no"],
41
+ "lang": "en",
42
+ }
43
+
44
+ TURN_CLASSES = ["finished", "not_finished", "backchannel", "hesitating"]
45
+
46
+ HOSTED_PREDICTION_TIMEOUT = 4.0
47
+ SELF_HOSTED_PREDICTION_TIMEOUT = 1.0
48
+ # How much of each side of the exchange a log line keeps.
49
+ SNIPPET_CHARS = 40
50
+
51
+
52
+ def snippet(text: str, limit: int = SNIPPET_CHARS) -> str:
53
+ """Collapse whitespace and keep the tail, for readable log lines."""
54
+ text = " ".join((text or "").split())
55
+ return text if len(text) <= limit else "…" + text[-limit:]
56
+
57
+
58
+ def wav16k(pcm: np.ndarray) -> bytes:
59
+ """16 kHz mono int16 samples as WAV bytes."""
60
+ buf = io.BytesIO()
61
+ with wave.open(buf, "wb") as handle:
62
+ handle.setnchannels(1)
63
+ handle.setsampwidth(2)
64
+ handle.setframerate(SAMPLE_RATE)
65
+ handle.writeframes(np.asarray(pcm, dtype="<i2").tobytes())
66
+ return buf.getvalue()
67
+
68
+
69
+ def trim_leading_silence(
70
+ pcm: np.ndarray, *, preroll_s: float = 0.3, block_s: float = 0.05
71
+ ) -> np.ndarray:
72
+ """Drop quiet audio before the first loud block, keeping ``preroll_s``."""
73
+ block = int(block_s * SAMPLE_RATE)
74
+ if len(pcm) < 2 * block:
75
+ return pcm
76
+ blocks = pcm[: len(pcm) // block * block].astype(np.float32).reshape(-1, block)
77
+ rms = np.sqrt(np.mean(blocks * blocks, axis=1))
78
+ peak = float(rms.max())
79
+ if peak < 100.0:
80
+ return pcm
81
+ first = int(np.argmax(rms >= max(0.1 * peak, 60.0)))
82
+ start = max(0, first * block - int(preroll_s * SAMPLE_RATE))
83
+ return pcm[start:]
84
+
85
+
86
+ def assistant_text(chat_ctx: Any) -> str:
87
+ """Last assistant message in a LiveKit chat context, collapsed to 300 characters."""
88
+ items = getattr(chat_ctx, "items", None)
89
+ if not items:
90
+ return ""
91
+ for item in reversed(list(items)):
92
+ if getattr(item, "role", None) != "assistant":
93
+ continue
94
+ text = getattr(item, "text_content", None)
95
+ if callable(text):
96
+ text = text()
97
+ if text and str(text).strip():
98
+ return " ".join(str(text).split())[-300:]
99
+ return ""
100
+
101
+
102
+ class InvalidGatewayResponse(ValueError):
103
+ """The gateway did not return a usable decision."""
104
+
105
+
106
+ def decision_answer(
107
+ data: Any, question: Mapping[str, Any]
108
+ ) -> tuple[dict[str, Any], dict[str, float]]:
109
+ question_id = question["id"]
110
+ options = question["options"]
111
+ try:
112
+ answer = data["answers"][question_id]
113
+ choice = answer["answer"]
114
+ probabilities = answer["probs"]
115
+ except (KeyError, TypeError) as exc:
116
+ raise InvalidGatewayResponse(f"missing decision for {question_id}") from exc
117
+
118
+ if (
119
+ choice not in options
120
+ or not isinstance(probabilities, dict)
121
+ or choice not in probabilities
122
+ ):
123
+ raise InvalidGatewayResponse(
124
+ f"invalid answer or probabilities for {question_id}"
125
+ )
126
+
127
+ scores: dict[str, float] = {}
128
+ # Older gateways can omit scores for some unselected options.
129
+ for option, probability in probabilities.items():
130
+ if option not in options:
131
+ raise InvalidGatewayResponse(f"unknown option for {question_id}")
132
+ if (
133
+ isinstance(probability, bool)
134
+ or not isinstance(probability, (int, float))
135
+ or not 0.0 <= probability <= 1.0
136
+ ):
137
+ raise InvalidGatewayResponse(f"invalid probability for {question_id}")
138
+ scores[option] = float(probability)
139
+
140
+ if not any(scores.values()) or sum(scores.values()) > 1.00001:
141
+ raise InvalidGatewayResponse(f"invalid probability total for {question_id}")
142
+ return answer, scores
143
+
144
+
145
+ @asynccontextmanager
146
+ async def http_session(
147
+ explicit: aiohttp.ClientSession | None = None,
148
+ ) -> AsyncIterator[aiohttp.ClientSession]:
149
+ """Borrow a supplied or job client, or open a client for this request."""
150
+ if explicit is not None and not explicit.closed:
151
+ yield explicit
152
+ else:
153
+ async with utils.http_context.open() as session:
154
+ yield session