livekit-plugins-duplexjev-detectors 1.9.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- livekit/plugins/duplexjev_detectors/__init__.py +55 -0
- livekit/plugins/duplexjev_detectors/client.py +154 -0
- livekit/plugins/duplexjev_detectors/interruption.py +892 -0
- livekit/plugins/duplexjev_detectors/log.py +3 -0
- livekit/plugins/duplexjev_detectors/turn_detector.py +502 -0
- livekit/plugins/duplexjev_detectors/version.py +1 -0
- livekit_plugins_duplexjev_detectors-1.9.0.dist-info/METADATA +25 -0
- livekit_plugins_duplexjev_detectors-1.9.0.dist-info/RECORD +9 -0
- livekit_plugins_duplexjev_detectors-1.9.0.dist-info/WHEEL +4 -0
|
@@ -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
|