mirror of
https://github.com/HumanAIGC-Engineering/gradio-webrtc.git
synced 2026-02-05 01:49:23 +08:00
[feat] update some feature
sync code of fastrtc, add text support through datachannel, fix safari connect problem support chat without camera or mic
This commit is contained in:
76
backend/fastrtc/__init__.py
Normal file
76
backend/fastrtc/__init__.py
Normal file
@@ -0,0 +1,76 @@
|
||||
from .credentials import (
|
||||
get_hf_turn_credentials,
|
||||
get_turn_credentials,
|
||||
get_twilio_turn_credentials,
|
||||
)
|
||||
from .pause_detection import (
|
||||
ModelOptions,
|
||||
PauseDetectionModel,
|
||||
SileroVadOptions,
|
||||
get_silero_model,
|
||||
)
|
||||
from .reply_on_pause import AlgoOptions, ReplyOnPause
|
||||
from .reply_on_stopwords import ReplyOnStopWords
|
||||
from .speech_to_text import MoonshineSTT, get_stt_model
|
||||
from .stream import Stream, UIArgs
|
||||
from .text_to_speech import KokoroTTSOptions, get_tts_model
|
||||
from .tracks import (
|
||||
AsyncAudioVideoStreamHandler,
|
||||
AsyncStreamHandler,
|
||||
AudioEmitType,
|
||||
AudioVideoStreamHandler,
|
||||
StreamHandler,
|
||||
VideoEmitType,
|
||||
)
|
||||
from .utils import (
|
||||
AdditionalOutputs,
|
||||
Warning,
|
||||
WebRTCError,
|
||||
aggregate_bytes_to_16bit,
|
||||
async_aggregate_bytes_to_16bit,
|
||||
audio_to_bytes,
|
||||
audio_to_file,
|
||||
audio_to_float32,
|
||||
audio_to_int16,
|
||||
wait_for_item,
|
||||
)
|
||||
from .webrtc import (
|
||||
WebRTC,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"AsyncStreamHandler",
|
||||
"AudioVideoStreamHandler",
|
||||
"AudioEmitType",
|
||||
"AsyncAudioVideoStreamHandler",
|
||||
"AlgoOptions",
|
||||
"AdditionalOutputs",
|
||||
"aggregate_bytes_to_16bit",
|
||||
"async_aggregate_bytes_to_16bit",
|
||||
"audio_to_bytes",
|
||||
"audio_to_file",
|
||||
"audio_to_float32",
|
||||
"audio_to_int16",
|
||||
"get_hf_turn_credentials",
|
||||
"get_twilio_turn_credentials",
|
||||
"get_turn_credentials",
|
||||
"ReplyOnPause",
|
||||
"ReplyOnStopWords",
|
||||
"SileroVadOptions",
|
||||
"get_stt_model",
|
||||
"MoonshineSTT",
|
||||
"StreamHandler",
|
||||
"Stream",
|
||||
"VideoEmitType",
|
||||
"WebRTC",
|
||||
"WebRTCError",
|
||||
"Warning",
|
||||
"get_tts_model",
|
||||
"KokoroTTSOptions",
|
||||
"wait_for_item",
|
||||
"UIArgs",
|
||||
"ModelOptions",
|
||||
"PauseDetectionModel",
|
||||
"get_silero_model",
|
||||
"SileroVadOptions",
|
||||
]
|
||||
52
backend/fastrtc/credentials.py
Normal file
52
backend/fastrtc/credentials.py
Normal file
@@ -0,0 +1,52 @@
|
||||
import os
|
||||
from typing import Literal
|
||||
|
||||
import requests
|
||||
|
||||
|
||||
def get_hf_turn_credentials(token=None):
|
||||
if token is None:
|
||||
token = os.getenv("HF_TOKEN")
|
||||
credentials = requests.get(
|
||||
"https://fastrtc-turn-server-login.hf.space/credentials",
|
||||
headers={"X-HF-Access-Token": token},
|
||||
)
|
||||
if not credentials.status_code == 200:
|
||||
raise ValueError("Failed to get credentials from HF turn server")
|
||||
return {
|
||||
"iceServers": [
|
||||
{
|
||||
"urls": "turn:gradio-turn.com:80",
|
||||
**credentials.json(),
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
|
||||
def get_twilio_turn_credentials(twilio_sid=None, twilio_token=None):
|
||||
try:
|
||||
from twilio.rest import Client
|
||||
except ImportError:
|
||||
raise ImportError("Please install twilio with `pip install twilio`")
|
||||
|
||||
if not twilio_sid and not twilio_token:
|
||||
twilio_sid = os.environ.get("TWILIO_ACCOUNT_SID")
|
||||
twilio_token = os.environ.get("TWILIO_AUTH_TOKEN")
|
||||
|
||||
client = Client(twilio_sid, twilio_token)
|
||||
|
||||
token = client.tokens.create()
|
||||
|
||||
return {
|
||||
"iceServers": token.ice_servers,
|
||||
"iceTransportPolicy": "relay",
|
||||
}
|
||||
|
||||
|
||||
def get_turn_credentials(method: Literal["hf", "twilio"] = "hf", **kwargs):
|
||||
if method == "hf":
|
||||
return get_hf_turn_credentials(**kwargs)
|
||||
elif method == "twilio":
|
||||
return get_twilio_turn_credentials(**kwargs)
|
||||
else:
|
||||
raise ValueError("Invalid method. Must be 'hf' or 'twilio'")
|
||||
10
backend/fastrtc/pause_detection/__init__.py
Normal file
10
backend/fastrtc/pause_detection/__init__.py
Normal file
@@ -0,0 +1,10 @@
|
||||
from .protocol import ModelOptions, PauseDetectionModel
|
||||
from .silero import SileroVADModel, SileroVadOptions, get_silero_model
|
||||
|
||||
__all__ = [
|
||||
"SileroVADModel",
|
||||
"SileroVadOptions",
|
||||
"PauseDetectionModel",
|
||||
"ModelOptions",
|
||||
"get_silero_model",
|
||||
]
|
||||
20
backend/fastrtc/pause_detection/protocol.py
Normal file
20
backend/fastrtc/pause_detection/protocol.py
Normal file
@@ -0,0 +1,20 @@
|
||||
from typing import Any, Protocol, TypeAlias
|
||||
|
||||
import numpy as np
|
||||
from numpy.typing import NDArray
|
||||
|
||||
from ..utils import AudioChunk
|
||||
|
||||
ModelOptions: TypeAlias = Any
|
||||
|
||||
|
||||
class PauseDetectionModel(Protocol):
|
||||
def vad(
|
||||
self,
|
||||
audio: tuple[int, NDArray[np.int16] | NDArray[np.float32]],
|
||||
options: ModelOptions,
|
||||
) -> tuple[float, list[AudioChunk]]: ...
|
||||
|
||||
def warmup(
|
||||
self,
|
||||
) -> None: ...
|
||||
329
backend/fastrtc/pause_detection/silero.py
Normal file
329
backend/fastrtc/pause_detection/silero.py
Normal file
@@ -0,0 +1,329 @@
|
||||
import logging
|
||||
import warnings
|
||||
from dataclasses import dataclass
|
||||
from functools import lru_cache
|
||||
from typing import List
|
||||
|
||||
import click
|
||||
import numpy as np
|
||||
from huggingface_hub import hf_hub_download
|
||||
from numpy.typing import NDArray
|
||||
|
||||
from ..utils import AudioChunk
|
||||
from .protocol import PauseDetectionModel
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# The code below is adapted from https://github.com/snakers4/silero-vad.
|
||||
# The code below is adapted from https://github.com/gpt-omni/mini-omni/blob/main/utils/vad.py
|
||||
|
||||
|
||||
@lru_cache
|
||||
def get_silero_model() -> PauseDetectionModel:
|
||||
"""Returns the VAD model instance and warms it up with dummy data."""
|
||||
# Warm up the model with dummy data
|
||||
|
||||
try:
|
||||
import importlib.util
|
||||
|
||||
mod = importlib.util.find_spec("onnxruntime")
|
||||
if mod is None:
|
||||
raise RuntimeError("Install fastrtc[vad] to use ReplyOnPause")
|
||||
except (ValueError, ModuleNotFoundError):
|
||||
raise RuntimeError("Install fastrtc[vad] to use ReplyOnPause")
|
||||
model = SileroVADModel()
|
||||
print(click.style("INFO", fg="green") + ":\t Warming up VAD model.")
|
||||
model.warmup()
|
||||
print(click.style("INFO", fg="green") + ":\t VAD model warmed up.")
|
||||
return model
|
||||
|
||||
|
||||
@dataclass
|
||||
class SileroVadOptions:
|
||||
"""VAD options.
|
||||
|
||||
Attributes:
|
||||
threshold: Speech threshold. Silero VAD outputs speech probabilities for each audio chunk,
|
||||
probabilities ABOVE this value are considered as SPEECH. It is better to tune this
|
||||
parameter for each dataset separately, but "lazy" 0.5 is pretty good for most datasets.
|
||||
min_speech_duration_ms: Final speech chunks shorter min_speech_duration_ms are thrown out.
|
||||
max_speech_duration_s: Maximum duration of speech chunks in seconds. Chunks longer
|
||||
than max_speech_duration_s will be split at the timestamp of the last silence that
|
||||
lasts more than 100ms (if any), to prevent aggressive cutting. Otherwise, they will be
|
||||
split aggressively just before max_speech_duration_s.
|
||||
min_silence_duration_ms: In the end of each speech chunk wait for min_silence_duration_ms
|
||||
before separating it
|
||||
window_size_samples: Audio chunks of window_size_samples size are fed to the silero VAD model.
|
||||
WARNING! Silero VAD models were trained using 512, 1024, 1536 samples for 16000 sample rate.
|
||||
Values other than these may affect model performance!!
|
||||
speech_pad_ms: Final speech chunks are padded by speech_pad_ms each side
|
||||
speech_duration: If the length of the speech is less than this value, a pause will be detected.
|
||||
"""
|
||||
|
||||
threshold: float = 0.5
|
||||
min_speech_duration_ms: int = 250
|
||||
max_speech_duration_s: float = float("inf")
|
||||
min_silence_duration_ms: int = 2000
|
||||
window_size_samples: int = 1024
|
||||
speech_pad_ms: int = 400
|
||||
|
||||
|
||||
class SileroVADModel:
|
||||
@staticmethod
|
||||
def download_model() -> str:
|
||||
return hf_hub_download(
|
||||
repo_id="freddyaboulton/silero-vad", filename="silero_vad.onnx"
|
||||
)
|
||||
|
||||
def __init__(self):
|
||||
try:
|
||||
import onnxruntime
|
||||
except ImportError as e:
|
||||
raise RuntimeError(
|
||||
"Applying the VAD filter requires the onnxruntime package"
|
||||
) from e
|
||||
|
||||
path = self.download_model()
|
||||
|
||||
opts = onnxruntime.SessionOptions()
|
||||
opts.inter_op_num_threads = 1
|
||||
opts.intra_op_num_threads = 1
|
||||
opts.log_severity_level = 4
|
||||
|
||||
self.session = onnxruntime.InferenceSession(
|
||||
path,
|
||||
providers=["CPUExecutionProvider"],
|
||||
sess_options=opts,
|
||||
)
|
||||
|
||||
def get_initial_state(self, batch_size: int):
|
||||
h = np.zeros((2, batch_size, 64), dtype=np.float32)
|
||||
c = np.zeros((2, batch_size, 64), dtype=np.float32)
|
||||
return h, c
|
||||
|
||||
@staticmethod
|
||||
def collect_chunks(audio: np.ndarray, chunks: List[AudioChunk]) -> np.ndarray:
|
||||
"""Collects and concatenates audio chunks."""
|
||||
if not chunks:
|
||||
return np.array([], dtype=np.float32)
|
||||
|
||||
return np.concatenate(
|
||||
[audio[chunk["start"] : chunk["end"]] for chunk in chunks]
|
||||
)
|
||||
|
||||
def get_speech_timestamps(
|
||||
self,
|
||||
audio: np.ndarray,
|
||||
vad_options: SileroVadOptions,
|
||||
**kwargs,
|
||||
) -> List[AudioChunk]:
|
||||
"""This method is used for splitting long audios into speech chunks using silero VAD.
|
||||
|
||||
Args:
|
||||
audio: One dimensional float array.
|
||||
vad_options: Options for VAD processing.
|
||||
kwargs: VAD options passed as keyword arguments for backward compatibility.
|
||||
|
||||
Returns:
|
||||
List of dicts containing begin and end samples of each speech chunk.
|
||||
"""
|
||||
|
||||
threshold = vad_options.threshold
|
||||
min_speech_duration_ms = vad_options.min_speech_duration_ms
|
||||
max_speech_duration_s = vad_options.max_speech_duration_s
|
||||
min_silence_duration_ms = vad_options.min_silence_duration_ms
|
||||
window_size_samples = vad_options.window_size_samples
|
||||
speech_pad_ms = vad_options.speech_pad_ms
|
||||
|
||||
if window_size_samples not in [512, 1024, 1536]:
|
||||
warnings.warn(
|
||||
"Unusual window_size_samples! Supported window_size_samples:\n"
|
||||
" - [512, 1024, 1536] for 16000 sampling_rate"
|
||||
)
|
||||
|
||||
sampling_rate = 16000
|
||||
min_speech_samples = sampling_rate * min_speech_duration_ms / 1000
|
||||
speech_pad_samples = sampling_rate * speech_pad_ms / 1000
|
||||
max_speech_samples = (
|
||||
sampling_rate * max_speech_duration_s
|
||||
- window_size_samples
|
||||
- 2 * speech_pad_samples
|
||||
)
|
||||
min_silence_samples = sampling_rate * min_silence_duration_ms / 1000
|
||||
min_silence_samples_at_max_speech = sampling_rate * 98 / 1000
|
||||
|
||||
audio_length_samples = len(audio)
|
||||
|
||||
state = self.get_initial_state(batch_size=1)
|
||||
|
||||
speech_probs = []
|
||||
for current_start_sample in range(0, audio_length_samples, window_size_samples):
|
||||
chunk = audio[
|
||||
current_start_sample : current_start_sample + window_size_samples
|
||||
]
|
||||
if len(chunk) < window_size_samples:
|
||||
chunk = np.pad(chunk, (0, int(window_size_samples - len(chunk))))
|
||||
speech_prob, state = self(chunk, state, sampling_rate)
|
||||
speech_probs.append(speech_prob)
|
||||
|
||||
triggered = False
|
||||
speeches = []
|
||||
current_speech = {}
|
||||
neg_threshold = threshold - 0.15
|
||||
|
||||
# to save potential segment end (and tolerate some silence)
|
||||
temp_end = 0
|
||||
# to save potential segment limits in case of maximum segment size reached
|
||||
prev_end = next_start = 0
|
||||
|
||||
for i, speech_prob in enumerate(speech_probs):
|
||||
if (speech_prob >= threshold) and temp_end:
|
||||
temp_end = 0
|
||||
if next_start < prev_end:
|
||||
next_start = window_size_samples * i
|
||||
|
||||
if (speech_prob >= threshold) and not triggered:
|
||||
triggered = True
|
||||
current_speech["start"] = window_size_samples * i
|
||||
continue
|
||||
|
||||
if (
|
||||
triggered
|
||||
and (window_size_samples * i) - current_speech["start"]
|
||||
> max_speech_samples
|
||||
):
|
||||
if prev_end:
|
||||
current_speech["end"] = prev_end
|
||||
speeches.append(current_speech)
|
||||
current_speech = {}
|
||||
# previously reached silence (< neg_thres) and is still not speech (< thres)
|
||||
if next_start < prev_end:
|
||||
triggered = False
|
||||
else:
|
||||
current_speech["start"] = next_start
|
||||
prev_end = next_start = temp_end = 0
|
||||
else:
|
||||
current_speech["end"] = window_size_samples * i
|
||||
speeches.append(current_speech)
|
||||
current_speech = {}
|
||||
prev_end = next_start = temp_end = 0
|
||||
triggered = False
|
||||
continue
|
||||
|
||||
if (speech_prob < neg_threshold) and triggered:
|
||||
if not temp_end:
|
||||
temp_end = window_size_samples * i
|
||||
# condition to avoid cutting in very short silence
|
||||
if (
|
||||
window_size_samples * i
|
||||
) - temp_end > min_silence_samples_at_max_speech:
|
||||
prev_end = temp_end
|
||||
if (window_size_samples * i) - temp_end < min_silence_samples:
|
||||
continue
|
||||
else:
|
||||
current_speech["end"] = temp_end
|
||||
if (
|
||||
current_speech["end"] - current_speech["start"]
|
||||
) > min_speech_samples:
|
||||
speeches.append(current_speech)
|
||||
current_speech = {}
|
||||
prev_end = next_start = temp_end = 0
|
||||
triggered = False
|
||||
continue
|
||||
|
||||
if (
|
||||
current_speech
|
||||
and (audio_length_samples - current_speech["start"]) > min_speech_samples
|
||||
):
|
||||
current_speech["end"] = audio_length_samples
|
||||
speeches.append(current_speech)
|
||||
|
||||
for i, speech in enumerate(speeches):
|
||||
if i == 0:
|
||||
speech["start"] = int(max(0, speech["start"] - speech_pad_samples))
|
||||
if i != len(speeches) - 1:
|
||||
silence_duration = speeches[i + 1]["start"] - speech["end"]
|
||||
if silence_duration < 2 * speech_pad_samples:
|
||||
speech["end"] += int(silence_duration // 2)
|
||||
speeches[i + 1]["start"] = int(
|
||||
max(0, speeches[i + 1]["start"] - silence_duration // 2)
|
||||
)
|
||||
else:
|
||||
speech["end"] = int(
|
||||
min(audio_length_samples, speech["end"] + speech_pad_samples)
|
||||
)
|
||||
speeches[i + 1]["start"] = int(
|
||||
max(0, speeches[i + 1]["start"] - speech_pad_samples)
|
||||
)
|
||||
else:
|
||||
speech["end"] = int(
|
||||
min(audio_length_samples, speech["end"] + speech_pad_samples)
|
||||
)
|
||||
|
||||
return speeches
|
||||
|
||||
def warmup(self):
|
||||
for _ in range(10):
|
||||
dummy_audio = np.zeros(102400, dtype=np.float32)
|
||||
self.vad((24000, dummy_audio), None)
|
||||
|
||||
def vad(
|
||||
self,
|
||||
audio: tuple[int, NDArray[np.float32] | NDArray[np.int16]],
|
||||
options: None | SileroVadOptions,
|
||||
) -> tuple[float, list[AudioChunk]]:
|
||||
sampling_rate, audio_ = audio
|
||||
logger.debug("VAD audio shape input: %s", audio_.shape)
|
||||
try:
|
||||
if audio_.dtype != np.float32:
|
||||
audio_ = audio_.astype(np.float32) / 32768.0
|
||||
sr = 16000
|
||||
if sr != sampling_rate:
|
||||
try:
|
||||
import librosa # type: ignore
|
||||
except ImportError as e:
|
||||
raise RuntimeError(
|
||||
"Applying the VAD filter requires the librosa if the input sampling rate is not 16000hz"
|
||||
) from e
|
||||
audio_ = librosa.resample(audio_, orig_sr=sampling_rate, target_sr=sr)
|
||||
|
||||
if not options:
|
||||
options = SileroVadOptions()
|
||||
speech_chunks = self.get_speech_timestamps(audio_, options)
|
||||
logger.debug("VAD speech chunks: %s", speech_chunks)
|
||||
audio_ = self.collect_chunks(audio_, speech_chunks)
|
||||
logger.debug("VAD audio shape: %s", audio_.shape)
|
||||
duration_after_vad = audio_.shape[0] / sr
|
||||
return duration_after_vad, speech_chunks
|
||||
except Exception as e:
|
||||
import math
|
||||
import traceback
|
||||
|
||||
logger.debug("VAD Exception: %s", str(e))
|
||||
exec = traceback.format_exc()
|
||||
logger.debug("traceback %s", exec)
|
||||
return math.inf, []
|
||||
|
||||
def __call__(self, x, state, sr: int):
|
||||
if len(x.shape) == 1:
|
||||
x = np.expand_dims(x, 0)
|
||||
if len(x.shape) > 2:
|
||||
raise ValueError(
|
||||
f"Too many dimensions for input audio chunk {len(x.shape)}"
|
||||
)
|
||||
if sr / x.shape[1] > 31.25: # type: ignore
|
||||
raise ValueError("Input audio chunk is too short")
|
||||
|
||||
h, c = state
|
||||
|
||||
ort_inputs = {
|
||||
"input": x,
|
||||
"h": h,
|
||||
"c": c,
|
||||
"sr": np.array(sr, dtype="int64"),
|
||||
}
|
||||
|
||||
out, h, c = self.session.run(None, ort_inputs)
|
||||
state = (h, c)
|
||||
|
||||
return out, state
|
||||
261
backend/fastrtc/reply_on_pause.py
Normal file
261
backend/fastrtc/reply_on_pause.py
Normal file
@@ -0,0 +1,261 @@
|
||||
import asyncio
|
||||
import inspect
|
||||
from dataclasses import dataclass, field
|
||||
from logging import getLogger
|
||||
from threading import Event
|
||||
from typing import Any, AsyncGenerator, Callable, Generator, Literal, cast
|
||||
|
||||
import numpy as np
|
||||
from numpy.typing import NDArray
|
||||
|
||||
from .pause_detection import ModelOptions, PauseDetectionModel, get_silero_model
|
||||
from .tracks import EmitType, StreamHandler
|
||||
from .utils import create_message, split_output
|
||||
|
||||
logger = getLogger(__name__)
|
||||
|
||||
|
||||
@dataclass
|
||||
class AlgoOptions:
|
||||
"""Algorithm options."""
|
||||
|
||||
audio_chunk_duration: float = 0.6
|
||||
started_talking_threshold: float = 0.2
|
||||
speech_threshold: float = 0.1
|
||||
|
||||
|
||||
@dataclass
|
||||
class AppState:
|
||||
stream: np.ndarray | None = None
|
||||
sampling_rate: int = 0
|
||||
pause_detected: bool = False
|
||||
started_talking: bool = False
|
||||
responding: bool = False
|
||||
stopped: bool = False
|
||||
buffer: np.ndarray | None = None
|
||||
responded_audio: bool = False
|
||||
interrupted: asyncio.Event = field(default_factory=asyncio.Event)
|
||||
|
||||
def new(self):
|
||||
return AppState()
|
||||
|
||||
|
||||
ReplyFnGenerator = (
|
||||
Callable[
|
||||
[tuple[int, NDArray[np.int16]], Any],
|
||||
Generator[EmitType, None, None],
|
||||
]
|
||||
| Callable[
|
||||
[tuple[int, NDArray[np.int16]]],
|
||||
Generator[EmitType, None, None],
|
||||
]
|
||||
| Callable[
|
||||
[tuple[int, NDArray[np.int16]]],
|
||||
AsyncGenerator[EmitType, None],
|
||||
]
|
||||
| Callable[
|
||||
[tuple[int, NDArray[np.int16]], Any],
|
||||
AsyncGenerator[EmitType, None],
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
async def iterate(generator: Generator) -> Any:
|
||||
return next(generator)
|
||||
|
||||
|
||||
class ReplyOnPause(StreamHandler):
|
||||
def __init__(
|
||||
self,
|
||||
fn: ReplyFnGenerator,
|
||||
startup_fn: Callable | None = None,
|
||||
algo_options: AlgoOptions | None = None,
|
||||
model_options: ModelOptions | None = None,
|
||||
can_interrupt: bool = True,
|
||||
expected_layout: Literal["mono", "stereo"] = "mono",
|
||||
output_sample_rate: int = 24000,
|
||||
output_frame_size: int = 480,
|
||||
input_sample_rate: int = 48000,
|
||||
model: PauseDetectionModel | None = None,
|
||||
):
|
||||
super().__init__(
|
||||
expected_layout,
|
||||
output_sample_rate,
|
||||
output_frame_size,
|
||||
input_sample_rate=input_sample_rate,
|
||||
)
|
||||
self.can_interrupt = can_interrupt
|
||||
self.expected_layout: Literal["mono", "stereo"] = expected_layout
|
||||
self.output_sample_rate = output_sample_rate
|
||||
self.output_frame_size = output_frame_size
|
||||
self.model = model or get_silero_model()
|
||||
self.fn = fn
|
||||
self.is_async = inspect.isasyncgenfunction(fn)
|
||||
self.event = Event()
|
||||
self.state = AppState()
|
||||
self.generator: (
|
||||
Generator[EmitType, None, None] | AsyncGenerator[EmitType, None] | None
|
||||
) = None
|
||||
self.model_options = model_options
|
||||
self.algo_options = algo_options or AlgoOptions()
|
||||
self.startup_fn = startup_fn
|
||||
|
||||
@property
|
||||
def _needs_additional_inputs(self) -> bool:
|
||||
return len(inspect.signature(self.fn).parameters) > 1
|
||||
|
||||
def start_up(self):
|
||||
if self.startup_fn:
|
||||
if self._needs_additional_inputs:
|
||||
self.wait_for_args_sync()
|
||||
args = self.latest_args[1:]
|
||||
else:
|
||||
args = ()
|
||||
self.generator = self.startup_fn(*args)
|
||||
self.event.set()
|
||||
|
||||
def copy(self):
|
||||
return ReplyOnPause(
|
||||
self.fn,
|
||||
self.startup_fn,
|
||||
self.algo_options,
|
||||
self.model_options,
|
||||
self.can_interrupt,
|
||||
self.expected_layout,
|
||||
self.output_sample_rate,
|
||||
self.output_frame_size,
|
||||
self.input_sample_rate,
|
||||
self.model,
|
||||
)
|
||||
|
||||
def determine_pause(
|
||||
self, audio: np.ndarray, sampling_rate: int, state: AppState
|
||||
) -> bool:
|
||||
"""Take in the stream, determine if a pause happened"""
|
||||
duration = len(audio) / sampling_rate
|
||||
|
||||
if duration >= self.algo_options.audio_chunk_duration:
|
||||
dur_vad, _ = self.model.vad((sampling_rate, audio), self.model_options)
|
||||
logger.debug("VAD duration: %s", dur_vad)
|
||||
if (
|
||||
dur_vad > self.algo_options.started_talking_threshold
|
||||
and not state.started_talking
|
||||
):
|
||||
state.started_talking = True
|
||||
logger.debug("Started talking")
|
||||
if state.started_talking:
|
||||
if state.stream is None:
|
||||
state.stream = audio
|
||||
else:
|
||||
state.stream = np.concatenate((state.stream, audio))
|
||||
state.buffer = None
|
||||
if dur_vad < self.algo_options.speech_threshold and state.started_talking:
|
||||
return True
|
||||
return False
|
||||
|
||||
def process_audio(self, audio: tuple[int, np.ndarray], state: AppState) -> None:
|
||||
frame_rate, array = audio
|
||||
array = np.squeeze(array)
|
||||
if not state.sampling_rate:
|
||||
state.sampling_rate = frame_rate
|
||||
if state.buffer is None:
|
||||
state.buffer = array
|
||||
else:
|
||||
state.buffer = np.concatenate((state.buffer, array))
|
||||
|
||||
pause_detected = self.determine_pause(
|
||||
state.buffer, state.sampling_rate, self.state
|
||||
)
|
||||
state.pause_detected = pause_detected
|
||||
|
||||
def receive(self, frame: tuple[int, np.ndarray]) -> None:
|
||||
if self.state.responding and not self.can_interrupt:
|
||||
return
|
||||
self.process_audio(frame, self.state)
|
||||
if self.state.pause_detected:
|
||||
self.event.set()
|
||||
if self.can_interrupt and self.state.responding:
|
||||
self._close_generator()
|
||||
self.generator = None
|
||||
if self.can_interrupt:
|
||||
self.clear_queue()
|
||||
|
||||
def _close_generator(self):
|
||||
"""Properly close the generator to ensure resources are released."""
|
||||
if self.generator is None:
|
||||
return
|
||||
|
||||
try:
|
||||
if self.is_async:
|
||||
# For async generators, we need to call aclose()
|
||||
if hasattr(self.generator, "aclose"):
|
||||
asyncio.run_coroutine_threadsafe(
|
||||
cast(AsyncGenerator[EmitType, None], self.generator).aclose(),
|
||||
self.loop,
|
||||
).result(timeout=1.0) # Add timeout to prevent blocking
|
||||
else:
|
||||
# For sync generators, we can just exhaust it or close it
|
||||
if hasattr(self.generator, "close"):
|
||||
cast(Generator[EmitType, None, None], self.generator).close()
|
||||
except Exception as e:
|
||||
logger.debug(f"Error closing generator: {e}")
|
||||
|
||||
def reset(self):
|
||||
super().reset()
|
||||
if self.phone_mode:
|
||||
self.args_set.set()
|
||||
self.generator = None
|
||||
self.event.clear()
|
||||
self.state = AppState()
|
||||
|
||||
async def async_iterate(self, generator) -> EmitType:
|
||||
return await anext(generator)
|
||||
|
||||
def emit(self):
|
||||
if not self.event.is_set():
|
||||
return None
|
||||
else:
|
||||
if not self.generator:
|
||||
self.send_message_sync(create_message("log", "pause_detected"))
|
||||
if self._needs_additional_inputs and not self.args_set.is_set():
|
||||
if not self.phone_mode:
|
||||
self.wait_for_args_sync()
|
||||
else:
|
||||
self.latest_args = [None]
|
||||
self.args_set.set()
|
||||
logger.debug("Creating generator")
|
||||
audio = cast(np.ndarray, self.state.stream).reshape(1, -1)
|
||||
if self._needs_additional_inputs:
|
||||
self.latest_args[0] = (self.state.sampling_rate, audio)
|
||||
self.generator = self.fn(*self.latest_args) # type: ignore
|
||||
else:
|
||||
self.generator = self.fn((self.state.sampling_rate, audio)) # type: ignore
|
||||
logger.debug("Latest args: %s", self.latest_args)
|
||||
self.state = self.state.new()
|
||||
self.state.responding = True
|
||||
try:
|
||||
if self.is_async:
|
||||
output = asyncio.run_coroutine_threadsafe(
|
||||
self.async_iterate(self.generator), self.loop
|
||||
).result()
|
||||
else:
|
||||
output = next(self.generator) # type: ignore
|
||||
audio, additional_outputs = split_output(output)
|
||||
if audio is not None:
|
||||
self.send_message_sync(create_message("log", "response_starting"))
|
||||
self.state.responded_audio = True
|
||||
if self.phone_mode:
|
||||
if additional_outputs:
|
||||
self.latest_args = [None] + list(additional_outputs.args)
|
||||
return output
|
||||
except (StopIteration, StopAsyncIteration):
|
||||
if not self.state.responded_audio:
|
||||
self.send_message_sync(create_message("log", "response_starting"))
|
||||
self.reset()
|
||||
except Exception as e:
|
||||
import traceback
|
||||
|
||||
traceback.print_exc()
|
||||
logger.debug("Error in ReplyOnPause: %s", e)
|
||||
self.reset()
|
||||
raise e
|
||||
163
backend/fastrtc/reply_on_stopwords.py
Normal file
163
backend/fastrtc/reply_on_stopwords.py
Normal file
@@ -0,0 +1,163 @@
|
||||
import asyncio
|
||||
import logging
|
||||
import re
|
||||
from typing import Callable, Literal
|
||||
|
||||
import numpy as np
|
||||
|
||||
from .reply_on_pause import (
|
||||
AlgoOptions,
|
||||
AppState,
|
||||
ModelOptions,
|
||||
PauseDetectionModel,
|
||||
ReplyFnGenerator,
|
||||
ReplyOnPause,
|
||||
)
|
||||
from .speech_to_text import get_stt_model, stt_for_chunks
|
||||
from .utils import audio_to_float32, create_message
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class ReplyOnStopWordsState(AppState):
|
||||
stop_word_detected: bool = False
|
||||
post_stop_word_buffer: np.ndarray | None = None
|
||||
started_talking_pre_stop_word: bool = False
|
||||
|
||||
def new(self):
|
||||
return ReplyOnStopWordsState()
|
||||
|
||||
|
||||
class ReplyOnStopWords(ReplyOnPause):
|
||||
def __init__(
|
||||
self,
|
||||
fn: ReplyFnGenerator,
|
||||
stop_words: list[str],
|
||||
startup_fn: Callable | None = None,
|
||||
algo_options: AlgoOptions | None = None,
|
||||
model_options: ModelOptions | None = None,
|
||||
can_interrupt: bool = True,
|
||||
expected_layout: Literal["mono", "stereo"] = "mono",
|
||||
output_sample_rate: int = 24000,
|
||||
output_frame_size: int = 480,
|
||||
input_sample_rate: int = 48000,
|
||||
model: PauseDetectionModel | None = None,
|
||||
):
|
||||
super().__init__(
|
||||
fn,
|
||||
algo_options=algo_options,
|
||||
startup_fn=startup_fn,
|
||||
model_options=model_options,
|
||||
can_interrupt=can_interrupt,
|
||||
expected_layout=expected_layout,
|
||||
output_sample_rate=output_sample_rate,
|
||||
output_frame_size=output_frame_size,
|
||||
input_sample_rate=input_sample_rate,
|
||||
model=model,
|
||||
)
|
||||
self.stop_words = stop_words
|
||||
self.state = ReplyOnStopWordsState()
|
||||
self.stt_model = get_stt_model("moonshine/base")
|
||||
|
||||
def stop_word_detected(self, text: str) -> bool:
|
||||
for stop_word in self.stop_words:
|
||||
stop_word = stop_word.lower().strip().split(" ")
|
||||
if bool(
|
||||
re.search(
|
||||
r"\b" + r"\s+".join(map(re.escape, stop_word)) + r"[.,!?]*\b",
|
||||
text.lower(),
|
||||
)
|
||||
):
|
||||
logger.debug("Stop word detected: %s", stop_word)
|
||||
return True
|
||||
return False
|
||||
|
||||
async def _send_stopword(
|
||||
self,
|
||||
):
|
||||
if self.channel:
|
||||
self.channel.send(create_message("stopword", ""))
|
||||
logger.debug("Sent stopword")
|
||||
|
||||
def send_stopword(self):
|
||||
asyncio.run_coroutine_threadsafe(self._send_stopword(), self.loop)
|
||||
|
||||
def determine_pause( # type: ignore
|
||||
self, audio: np.ndarray, sampling_rate: int, state: ReplyOnStopWordsState
|
||||
) -> bool:
|
||||
"""Take in the stream, determine if a pause happened"""
|
||||
import librosa
|
||||
|
||||
duration = len(audio) / sampling_rate
|
||||
|
||||
if duration >= self.algo_options.audio_chunk_duration:
|
||||
if not state.stop_word_detected:
|
||||
audio_f32 = audio_to_float32((sampling_rate, audio))
|
||||
audio_rs = librosa.resample(
|
||||
audio_f32, orig_sr=sampling_rate, target_sr=16000
|
||||
)
|
||||
if state.post_stop_word_buffer is None:
|
||||
state.post_stop_word_buffer = audio_rs
|
||||
else:
|
||||
state.post_stop_word_buffer = np.concatenate(
|
||||
(state.post_stop_word_buffer, audio_rs)
|
||||
)
|
||||
if len(state.post_stop_word_buffer) / 16000 > 2:
|
||||
state.post_stop_word_buffer = state.post_stop_word_buffer[-32000:]
|
||||
dur_vad, chunks = self.model.vad(
|
||||
(16000, state.post_stop_word_buffer),
|
||||
self.model_options,
|
||||
)
|
||||
text = stt_for_chunks(
|
||||
self.stt_model, (16000, state.post_stop_word_buffer), chunks
|
||||
)
|
||||
logger.debug(f"STT: {text}")
|
||||
state.stop_word_detected = self.stop_word_detected(text)
|
||||
if state.stop_word_detected:
|
||||
logger.debug("Stop word detected")
|
||||
self.send_stopword()
|
||||
state.buffer = None
|
||||
else:
|
||||
dur_vad, _ = self.model.vad((sampling_rate, audio), self.model_options)
|
||||
logger.debug("VAD duration: %s", dur_vad)
|
||||
if (
|
||||
dur_vad > self.algo_options.started_talking_threshold
|
||||
and not state.started_talking
|
||||
and state.stop_word_detected
|
||||
):
|
||||
state.started_talking = True
|
||||
logger.debug("Started talking")
|
||||
if state.started_talking:
|
||||
if state.stream is None:
|
||||
state.stream = audio
|
||||
else:
|
||||
state.stream = np.concatenate((state.stream, audio))
|
||||
state.buffer = None
|
||||
if (
|
||||
dur_vad < self.algo_options.speech_threshold
|
||||
and state.started_talking
|
||||
and state.stop_word_detected
|
||||
):
|
||||
return True
|
||||
return False
|
||||
|
||||
def reset(self):
|
||||
super().reset()
|
||||
self.generator = None
|
||||
self.event.clear()
|
||||
self.state = ReplyOnStopWordsState()
|
||||
|
||||
def copy(self):
|
||||
return ReplyOnStopWords(
|
||||
self.fn,
|
||||
self.stop_words,
|
||||
self.startup_fn,
|
||||
self.algo_options,
|
||||
self.model_options,
|
||||
self.can_interrupt,
|
||||
self.expected_layout,
|
||||
self.output_sample_rate,
|
||||
self.output_frame_size,
|
||||
self.input_sample_rate,
|
||||
self.model,
|
||||
)
|
||||
3
backend/fastrtc/speech_to_text/__init__.py
Normal file
3
backend/fastrtc/speech_to_text/__init__.py
Normal file
@@ -0,0 +1,3 @@
|
||||
from .stt_ import MoonshineSTT, get_stt_model, stt_for_chunks
|
||||
|
||||
__all__ = ["get_stt_model", "MoonshineSTT", "get_stt_model", "stt_for_chunks"]
|
||||
76
backend/fastrtc/speech_to_text/stt_.py
Normal file
76
backend/fastrtc/speech_to_text/stt_.py
Normal file
@@ -0,0 +1,76 @@
|
||||
from functools import lru_cache
|
||||
from pathlib import Path
|
||||
from typing import Literal, Protocol
|
||||
|
||||
import click
|
||||
import librosa
|
||||
import numpy as np
|
||||
from numpy.typing import NDArray
|
||||
|
||||
from ..utils import AudioChunk, audio_to_float32
|
||||
|
||||
curr_dir = Path(__file__).parent
|
||||
|
||||
|
||||
class STTModel(Protocol):
|
||||
def stt(self, audio: tuple[int, NDArray[np.int16 | np.float32]]) -> str: ...
|
||||
|
||||
|
||||
class MoonshineSTT(STTModel):
|
||||
def __init__(
|
||||
self, model: Literal["moonshine/base", "moonshine/tiny"] = "moonshine/base"
|
||||
):
|
||||
try:
|
||||
from moonshine_onnx import MoonshineOnnxModel, load_tokenizer
|
||||
except (ImportError, ModuleNotFoundError):
|
||||
raise ImportError(
|
||||
"Install fastrtc[stt] for speech-to-text and stopword detection support."
|
||||
)
|
||||
|
||||
self.model = MoonshineOnnxModel(model_name=model)
|
||||
self.tokenizer = load_tokenizer()
|
||||
|
||||
def stt(self, audio: tuple[int, NDArray[np.int16 | np.float32]]) -> str:
|
||||
sr, audio_np = audio # type: ignore
|
||||
if audio_np.dtype == np.int16:
|
||||
audio_np = audio_to_float32(audio)
|
||||
if sr != 16000:
|
||||
audio_np: NDArray[np.float32] = librosa.resample(
|
||||
audio_np, orig_sr=sr, target_sr=16000
|
||||
)
|
||||
if audio_np.ndim == 1:
|
||||
audio_np = audio_np.reshape(1, -1)
|
||||
tokens = self.model.generate(audio_np)
|
||||
return self.tokenizer.decode_batch(tokens)[0]
|
||||
|
||||
|
||||
@lru_cache
|
||||
def get_stt_model(
|
||||
model: Literal["moonshine/base", "moonshine/tiny"] = "moonshine/base",
|
||||
) -> STTModel:
|
||||
import os
|
||||
|
||||
os.environ["TOKENIZERS_PARALLELISM"] = "false"
|
||||
m = MoonshineSTT(model)
|
||||
from moonshine_onnx import load_audio
|
||||
|
||||
audio = load_audio(str(curr_dir / "test_file.wav"))
|
||||
print(click.style("INFO", fg="green") + ":\t Warming up STT model.")
|
||||
|
||||
m.stt((16000, audio))
|
||||
print(click.style("INFO", fg="green") + ":\t STT model warmed up.")
|
||||
return m
|
||||
|
||||
|
||||
def stt_for_chunks(
|
||||
stt_model: STTModel,
|
||||
audio: tuple[int, NDArray[np.int16 | np.float32]],
|
||||
chunks: list[AudioChunk],
|
||||
) -> str:
|
||||
sr, audio_np = audio
|
||||
return " ".join(
|
||||
[
|
||||
stt_model.stt((sr, audio_np[chunk["start"] : chunk["end"]]))
|
||||
for chunk in chunks
|
||||
]
|
||||
)
|
||||
BIN
backend/fastrtc/speech_to_text/test_file.wav
Normal file
BIN
backend/fastrtc/speech_to_text/test_file.wav
Normal file
Binary file not shown.
721
backend/fastrtc/stream.py
Normal file
721
backend/fastrtc/stream.py
Normal file
@@ -0,0 +1,721 @@
|
||||
import logging
|
||||
from pathlib import Path
|
||||
from typing import (
|
||||
Any,
|
||||
AsyncContextManager,
|
||||
Callable,
|
||||
Literal,
|
||||
TypedDict,
|
||||
cast,
|
||||
)
|
||||
|
||||
import gradio as gr
|
||||
from fastapi import FastAPI, Request, WebSocket
|
||||
from fastapi.responses import HTMLResponse
|
||||
from gradio import Blocks
|
||||
from gradio.components.base import Component
|
||||
from pydantic import BaseModel
|
||||
from typing_extensions import NotRequired
|
||||
|
||||
from .tracks import HandlerType, StreamHandlerImpl
|
||||
from .webrtc import WebRTC
|
||||
from .webrtc_connection_mixin import WebRTCConnectionMixin
|
||||
from .websocket import WebSocketHandler
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
curr_dir = Path(__file__).parent
|
||||
|
||||
|
||||
class Body(BaseModel):
|
||||
sdp: str
|
||||
type: str
|
||||
webrtc_id: str
|
||||
|
||||
|
||||
class UIArgs(TypedDict):
|
||||
title: NotRequired[str]
|
||||
"""Title of the demo"""
|
||||
subtitle: NotRequired[str]
|
||||
"""Subtitle of the demo. Text will be centered and displayed below the title."""
|
||||
icon: NotRequired[str]
|
||||
"""Icon to display on the button instead of the wave animation. The icon should be a path/url to a .svg/.png/.jpeg file."""
|
||||
icon_button_color: NotRequired[str]
|
||||
"""Color of the icon button. Default is var(--color-accent) of the demo theme."""
|
||||
pulse_color: NotRequired[str]
|
||||
"""Color of the pulse animation. Default is var(--color-accent) of the demo theme."""
|
||||
icon_radius: NotRequired[int]
|
||||
"""Border radius of the icon button expressed as a percentage of the button size. Default is 50%."""
|
||||
|
||||
|
||||
class Stream(WebRTCConnectionMixin):
|
||||
def __init__(
|
||||
self,
|
||||
handler: HandlerType,
|
||||
*,
|
||||
additional_outputs_handler: Callable | None = None,
|
||||
mode: Literal["send-receive", "receive", "send"] = "send-receive",
|
||||
modality: Literal["video", "audio", "audio-video"] = "video",
|
||||
concurrency_limit: int | None | Literal["default"] = "default",
|
||||
time_limit: float | None = None,
|
||||
rtp_params: dict[str, Any] | None = None,
|
||||
rtc_configuration: dict[str, Any] | None = None,
|
||||
additional_inputs: list[Component] | None = None,
|
||||
additional_outputs: list[Component] | None = None,
|
||||
ui_args: UIArgs | None = None,
|
||||
):
|
||||
WebRTCConnectionMixin.__init__(self)
|
||||
self.mode = mode
|
||||
self.modality = modality
|
||||
self.rtp_params = rtp_params
|
||||
self.event_handler = handler
|
||||
self.concurrency_limit = cast(
|
||||
(int | float),
|
||||
1 if concurrency_limit in ["default", None] else concurrency_limit,
|
||||
)
|
||||
self.time_limit = time_limit
|
||||
self.additional_output_components = additional_outputs
|
||||
self.additional_input_components = additional_inputs
|
||||
self.additional_outputs_handler = additional_outputs_handler
|
||||
self.rtc_configuration = rtc_configuration
|
||||
self._ui = self._generate_default_ui(ui_args)
|
||||
self._ui.launch = self._wrap_gradio_launch(self._ui.launch)
|
||||
|
||||
def mount(self, app: FastAPI):
|
||||
app.router.post("/webrtc/offer")(self.offer)
|
||||
app.router.websocket("/telephone/handler")(self.telephone_handler)
|
||||
app.router.post("/telephone/incoming")(self.handle_incoming_call)
|
||||
app.router.websocket("/websocket/offer")(self.websocket_offer)
|
||||
lifespan = self._inject_startup_message(app.router.lifespan_context)
|
||||
app.router.lifespan_context = lifespan
|
||||
|
||||
@staticmethod
|
||||
def print_error(env: Literal["colab", "spaces"]):
|
||||
import click
|
||||
|
||||
print(
|
||||
click.style("ERROR", fg="red")
|
||||
+ f":\t Running in {env} is not possible without providing a valid rtc_configuration. "
|
||||
+ "See "
|
||||
+ click.style("https://fastrtc.org/deployment/", fg="cyan")
|
||||
+ " for more information."
|
||||
)
|
||||
raise RuntimeError(
|
||||
f"Running in {env} is not possible without providing a valid rtc_configuration. "
|
||||
+ "See https://fastrtc.org/deployment/ for more information."
|
||||
)
|
||||
|
||||
def _check_colab_or_spaces(self):
|
||||
from gradio.utils import colab_check, get_space
|
||||
|
||||
if colab_check() and not self.rtc_configuration:
|
||||
self.print_error("colab")
|
||||
if get_space() and not self.rtc_configuration:
|
||||
self.print_error("spaces")
|
||||
|
||||
def _wrap_gradio_launch(self, callable):
|
||||
import contextlib
|
||||
|
||||
def wrapper(*args, **kwargs):
|
||||
lifespan = kwargs.get("app_kwargs", {}).get("lifespan", None)
|
||||
|
||||
@contextlib.asynccontextmanager
|
||||
async def new_lifespan(app: FastAPI):
|
||||
if lifespan is None:
|
||||
self._check_colab_or_spaces()
|
||||
yield
|
||||
else:
|
||||
async with lifespan(app):
|
||||
self._check_colab_or_spaces()
|
||||
yield
|
||||
|
||||
if "app_kwargs" not in kwargs:
|
||||
kwargs["app_kwargs"] = {}
|
||||
kwargs["app_kwargs"]["lifespan"] = new_lifespan
|
||||
return callable(*args, **kwargs)
|
||||
|
||||
return wrapper
|
||||
|
||||
def _inject_startup_message(
|
||||
self, lifespan: Callable[[FastAPI], AsyncContextManager] | None = None
|
||||
):
|
||||
import contextlib
|
||||
|
||||
import click
|
||||
|
||||
def print_startup_message():
|
||||
self._check_colab_or_spaces()
|
||||
print(
|
||||
click.style("INFO", fg="green")
|
||||
+ ":\t Visit "
|
||||
+ click.style("https://fastrtc.org/userguide/api/", fg="cyan")
|
||||
+ " for WebRTC or Websocket API docs."
|
||||
)
|
||||
|
||||
@contextlib.asynccontextmanager
|
||||
async def new_lifespan(app: FastAPI):
|
||||
if lifespan is None:
|
||||
print_startup_message()
|
||||
yield
|
||||
else:
|
||||
async with lifespan(app):
|
||||
print_startup_message()
|
||||
yield
|
||||
|
||||
return new_lifespan
|
||||
|
||||
def _generate_default_ui(
|
||||
self,
|
||||
ui_args: UIArgs | None = None,
|
||||
):
|
||||
ui_args = ui_args or {}
|
||||
same_components = []
|
||||
additional_input_components = self.additional_input_components or []
|
||||
additional_output_components = self.additional_output_components or []
|
||||
if additional_output_components and not self.additional_outputs_handler:
|
||||
raise ValueError(
|
||||
"additional_outputs_handler must be provided if there are additional output components."
|
||||
)
|
||||
if additional_input_components and additional_output_components:
|
||||
same_components = [
|
||||
component
|
||||
for component in additional_input_components
|
||||
if component in additional_output_components
|
||||
]
|
||||
for component in additional_output_components:
|
||||
if component in same_components:
|
||||
same_components.append(component)
|
||||
if self.modality == "video" and self.mode == "receive":
|
||||
with gr.Blocks() as demo:
|
||||
gr.HTML(
|
||||
f"""
|
||||
<h1 style='text-align: center'>
|
||||
{ui_args.get("title", "Video Streaming (Powered by FastRTC ⚡️)")}
|
||||
</h1>
|
||||
"""
|
||||
)
|
||||
if ui_args.get("subtitle"):
|
||||
gr.Markdown(
|
||||
f"""
|
||||
<div style='text-align: center'>
|
||||
{ui_args.get("subtitle")}
|
||||
</div>
|
||||
"""
|
||||
)
|
||||
with gr.Row():
|
||||
with gr.Column():
|
||||
if additional_input_components:
|
||||
for component in additional_input_components:
|
||||
component.render()
|
||||
button = gr.Button("Start Stream", variant="primary")
|
||||
with gr.Column():
|
||||
output_video = WebRTC(
|
||||
label="Video Stream",
|
||||
rtc_configuration=self.rtc_configuration,
|
||||
mode="receive",
|
||||
modality="video",
|
||||
)
|
||||
for component in additional_output_components:
|
||||
if component not in same_components:
|
||||
component.render()
|
||||
output_video.stream(
|
||||
fn=self.event_handler,
|
||||
inputs=self.additional_input_components,
|
||||
outputs=[output_video],
|
||||
trigger=button.click,
|
||||
time_limit=self.time_limit,
|
||||
concurrency_limit=self.concurrency_limit, # type: ignore
|
||||
)
|
||||
if additional_output_components:
|
||||
assert self.additional_outputs_handler
|
||||
output_video.on_additional_outputs(
|
||||
self.additional_outputs_handler,
|
||||
inputs=additional_output_components,
|
||||
outputs=additional_output_components,
|
||||
)
|
||||
elif self.modality == "video" and self.mode == "send":
|
||||
with gr.Blocks() as demo:
|
||||
gr.HTML(
|
||||
f"""
|
||||
<h1 style='text-align: center'>
|
||||
{ui_args.get("title", "Video Streaming (Powered by FastRTC ⚡️)")}
|
||||
</h1>
|
||||
"""
|
||||
)
|
||||
if ui_args.get("subtitle"):
|
||||
gr.Markdown(
|
||||
f"""
|
||||
<div style='text-align: center'>
|
||||
{ui_args.get("subtitle")}
|
||||
</div>
|
||||
"""
|
||||
)
|
||||
with gr.Row():
|
||||
if additional_input_components:
|
||||
with gr.Column():
|
||||
for component in additional_input_components:
|
||||
component.render()
|
||||
with gr.Column():
|
||||
output_video = WebRTC(
|
||||
label="Video Stream",
|
||||
rtc_configuration=self.rtc_configuration,
|
||||
mode="send",
|
||||
modality="video",
|
||||
)
|
||||
for component in additional_output_components:
|
||||
if component not in same_components:
|
||||
component.render()
|
||||
output_video.stream(
|
||||
fn=self.event_handler,
|
||||
inputs=[output_video] + additional_input_components,
|
||||
outputs=[output_video],
|
||||
time_limit=self.time_limit,
|
||||
concurrency_limit=self.concurrency_limit, # type: ignore
|
||||
)
|
||||
if additional_output_components:
|
||||
assert self.additional_outputs_handler
|
||||
output_video.on_additional_outputs(
|
||||
self.additional_outputs_handler,
|
||||
inputs=additional_output_components,
|
||||
outputs=additional_output_components,
|
||||
)
|
||||
elif self.modality == "video" and self.mode == "send-receive":
|
||||
css = """.my-group {max-width: 600px !important; max-height: 600 !important;}
|
||||
.my-column {display: flex !important; justify-content: center !important; align-items: center !important};"""
|
||||
|
||||
with gr.Blocks(css=css) as demo:
|
||||
gr.HTML(
|
||||
f"""
|
||||
<h1 style='text-align: center'>
|
||||
{ui_args.get("title", "Video Streaming (Powered by FastRTC ⚡️)")}
|
||||
</h1>
|
||||
"""
|
||||
)
|
||||
if ui_args.get("subtitle"):
|
||||
gr.Markdown(
|
||||
f"""
|
||||
<div style='text-align: center'>
|
||||
{ui_args.get("subtitle")}
|
||||
</div>
|
||||
"""
|
||||
)
|
||||
with gr.Column(elem_classes=["my-column"]):
|
||||
with gr.Group(elem_classes=["my-group"]):
|
||||
image = WebRTC(
|
||||
label="Stream",
|
||||
rtc_configuration=self.rtc_configuration,
|
||||
mode="send-receive",
|
||||
modality="video",
|
||||
)
|
||||
for component in additional_input_components:
|
||||
component.render()
|
||||
if additional_output_components:
|
||||
with gr.Column():
|
||||
for component in additional_output_components:
|
||||
if component not in same_components:
|
||||
component.render()
|
||||
|
||||
image.stream(
|
||||
fn=self.event_handler,
|
||||
inputs=[image] + additional_input_components,
|
||||
outputs=[image],
|
||||
time_limit=self.time_limit,
|
||||
concurrency_limit=self.concurrency_limit, # type: ignore
|
||||
)
|
||||
if additional_output_components:
|
||||
assert self.additional_outputs_handler
|
||||
image.on_additional_outputs(
|
||||
self.additional_outputs_handler,
|
||||
inputs=additional_output_components,
|
||||
outputs=additional_output_components,
|
||||
)
|
||||
elif self.modality == "audio" and self.mode == "receive":
|
||||
with gr.Blocks() as demo:
|
||||
gr.HTML(
|
||||
f"""
|
||||
<h1 style='text-align: center'>
|
||||
{ui_args.get("title", "Audio Streaming (Powered by FastRTC ⚡️)")}
|
||||
</h1>
|
||||
"""
|
||||
)
|
||||
if ui_args.get("subtitle"):
|
||||
gr.Markdown(
|
||||
f"""
|
||||
<div style='text-align: center'>
|
||||
{ui_args.get("subtitle")}
|
||||
</div>
|
||||
"""
|
||||
)
|
||||
with gr.Row():
|
||||
with gr.Column():
|
||||
for component in additional_input_components:
|
||||
component.render()
|
||||
button = gr.Button("Start Stream", variant="primary")
|
||||
if additional_output_components:
|
||||
with gr.Column():
|
||||
output_video = WebRTC(
|
||||
label="Audio Stream",
|
||||
rtc_configuration=self.rtc_configuration,
|
||||
mode="receive",
|
||||
modality="audio",
|
||||
icon=ui_args.get("icon"),
|
||||
icon_button_color=ui_args.get("icon_button_color"),
|
||||
pulse_color=ui_args.get("pulse_color"),
|
||||
icon_radius=ui_args.get("icon_radius"),
|
||||
)
|
||||
for component in additional_output_components:
|
||||
if component not in same_components:
|
||||
component.render()
|
||||
output_video.stream(
|
||||
fn=self.event_handler,
|
||||
inputs=self.additional_input_components,
|
||||
outputs=[output_video],
|
||||
trigger=button.click,
|
||||
time_limit=self.time_limit,
|
||||
concurrency_limit=self.concurrency_limit, # type: ignore
|
||||
)
|
||||
if additional_output_components:
|
||||
assert self.additional_outputs_handler
|
||||
output_video.on_additional_outputs(
|
||||
self.additional_outputs_handler,
|
||||
inputs=additional_output_components,
|
||||
outputs=additional_output_components,
|
||||
)
|
||||
elif self.modality == "audio" and self.mode == "send":
|
||||
with gr.Blocks() as demo:
|
||||
gr.HTML(
|
||||
f"""
|
||||
<h1 style='text-align: center'>
|
||||
{ui_args.get("title", "Audio Streaming (Powered by FastRTC ⚡️)")}
|
||||
</h1>
|
||||
"""
|
||||
)
|
||||
if ui_args.get("subtitle"):
|
||||
gr.Markdown(
|
||||
f"""
|
||||
<div style='text-align: center'>
|
||||
{ui_args.get("subtitle")}
|
||||
</div>
|
||||
"""
|
||||
)
|
||||
with gr.Row():
|
||||
with gr.Column():
|
||||
with gr.Group():
|
||||
image = WebRTC(
|
||||
label="Stream",
|
||||
rtc_configuration=self.rtc_configuration,
|
||||
mode="send",
|
||||
modality="audio",
|
||||
icon=ui_args.get("icon"),
|
||||
icon_button_color=ui_args.get("icon_button_color"),
|
||||
pulse_color=ui_args.get("pulse_color"),
|
||||
icon_radius=ui_args.get("icon_radius"),
|
||||
)
|
||||
for component in additional_input_components:
|
||||
if component not in same_components:
|
||||
component.render()
|
||||
if additional_output_components:
|
||||
with gr.Column():
|
||||
for component in additional_output_components:
|
||||
component.render()
|
||||
image.stream(
|
||||
fn=self.event_handler,
|
||||
inputs=[image] + additional_input_components,
|
||||
outputs=[image],
|
||||
time_limit=self.time_limit,
|
||||
concurrency_limit=self.concurrency_limit, # type: ignore
|
||||
)
|
||||
if additional_output_components:
|
||||
assert self.additional_outputs_handler
|
||||
image.on_additional_outputs(
|
||||
self.additional_outputs_handler,
|
||||
inputs=additional_output_components,
|
||||
outputs=additional_output_components,
|
||||
)
|
||||
elif self.modality == "audio" and self.mode == "send-receive":
|
||||
with gr.Blocks() as demo:
|
||||
gr.HTML(
|
||||
f"""
|
||||
<h1 style='text-align: center'>
|
||||
{ui_args.get("title", "Audio Streaming (Powered by FastRTC ⚡️)")}
|
||||
</h1>
|
||||
"""
|
||||
)
|
||||
if ui_args.get("subtitle"):
|
||||
gr.Markdown(
|
||||
f"""
|
||||
<div style='text-align: center'>
|
||||
{ui_args.get("subtitle")}
|
||||
</div>
|
||||
"""
|
||||
)
|
||||
with gr.Row():
|
||||
with gr.Column():
|
||||
with gr.Group():
|
||||
image = WebRTC(
|
||||
label="Stream",
|
||||
rtc_configuration=self.rtc_configuration,
|
||||
mode="send-receive",
|
||||
modality="audio",
|
||||
icon=ui_args.get("icon"),
|
||||
icon_button_color=ui_args.get("icon_button_color"),
|
||||
pulse_color=ui_args.get("pulse_color"),
|
||||
icon_radius=ui_args.get("icon_radius"),
|
||||
)
|
||||
for component in additional_input_components:
|
||||
if component not in same_components:
|
||||
component.render()
|
||||
if additional_output_components:
|
||||
with gr.Column():
|
||||
for component in additional_output_components:
|
||||
component.render()
|
||||
|
||||
image.stream(
|
||||
fn=self.event_handler,
|
||||
inputs=[image] + additional_input_components,
|
||||
outputs=[image],
|
||||
time_limit=self.time_limit,
|
||||
concurrency_limit=self.concurrency_limit, # type: ignore
|
||||
)
|
||||
if additional_output_components:
|
||||
assert self.additional_outputs_handler
|
||||
image.on_additional_outputs(
|
||||
self.additional_outputs_handler,
|
||||
inputs=additional_output_components,
|
||||
outputs=additional_output_components,
|
||||
)
|
||||
elif self.modality == "audio-video" and self.mode == "send-receive":
|
||||
with gr.Blocks() as demo:
|
||||
gr.HTML(
|
||||
f"""
|
||||
<h1 style='text-align: center'>
|
||||
{ui_args.get("title", "Audio Video Streaming (Powered by FastRTC ⚡️)")}
|
||||
</h1>
|
||||
"""
|
||||
)
|
||||
if ui_args.get("subtitle"):
|
||||
gr.Markdown(
|
||||
f"""
|
||||
<div style='text-align: center'>
|
||||
{ui_args.get("subtitle")}
|
||||
</div>
|
||||
"""
|
||||
)
|
||||
with gr.Row():
|
||||
with gr.Column():
|
||||
with gr.Group():
|
||||
image = WebRTC(
|
||||
label="Stream",
|
||||
rtc_configuration=self.rtc_configuration,
|
||||
mode="send-receive",
|
||||
modality="audio-video",
|
||||
icon=ui_args.get("icon"),
|
||||
icon_button_color=ui_args.get("icon_button_color"),
|
||||
pulse_color=ui_args.get("pulse_color"),
|
||||
icon_radius=ui_args.get("icon_radius"),
|
||||
)
|
||||
for component in additional_input_components:
|
||||
if component not in same_components:
|
||||
component.render()
|
||||
if additional_output_components:
|
||||
with gr.Column():
|
||||
for component in additional_output_components:
|
||||
component.render()
|
||||
|
||||
image.stream(
|
||||
fn=self.event_handler,
|
||||
inputs=[image] + additional_input_components,
|
||||
outputs=[image],
|
||||
time_limit=self.time_limit,
|
||||
concurrency_limit=self.concurrency_limit, # type: ignore
|
||||
)
|
||||
if additional_output_components:
|
||||
assert self.additional_outputs_handler
|
||||
image.on_additional_outputs(
|
||||
self.additional_outputs_handler,
|
||||
inputs=additional_output_components,
|
||||
outputs=additional_output_components,
|
||||
)
|
||||
else:
|
||||
raise ValueError(f"Invalid modality: {self.modality} and mode: {self.mode}")
|
||||
return demo
|
||||
|
||||
@property
|
||||
def ui(self) -> Blocks:
|
||||
return self._ui
|
||||
|
||||
@ui.setter
|
||||
def ui(self, blocks: Blocks):
|
||||
self._ui = blocks
|
||||
|
||||
async def offer(self, body: Body):
|
||||
return await self.handle_offer(
|
||||
body.model_dump(), set_outputs=self.set_additional_outputs(body.webrtc_id)
|
||||
)
|
||||
|
||||
async def handle_incoming_call(self, request: Request):
|
||||
from twilio.twiml.voice_response import Connect, VoiceResponse
|
||||
|
||||
response = VoiceResponse()
|
||||
response.say("Connecting to the AI assistant.")
|
||||
connect = Connect()
|
||||
connect.stream(url=f"wss://{request.url.hostname}/telephone/handler")
|
||||
response.append(connect)
|
||||
response.say("The call has been disconnected.")
|
||||
return HTMLResponse(content=str(response), media_type="application/xml")
|
||||
|
||||
async def telephone_handler(self, websocket: WebSocket):
|
||||
handler = cast(StreamHandlerImpl, self.event_handler.copy()) # type: ignore
|
||||
handler.phone_mode = True
|
||||
|
||||
async def set_handler(s: str, a: WebSocketHandler):
|
||||
if len(self.connections) >= self.concurrency_limit: # type: ignore
|
||||
await cast(WebSocket, a.websocket).send_json(
|
||||
{
|
||||
"status": "failed",
|
||||
"meta": {
|
||||
"error": "concurrency_limit_reached",
|
||||
"limit": self.concurrency_limit,
|
||||
},
|
||||
}
|
||||
)
|
||||
await websocket.close()
|
||||
return
|
||||
|
||||
ws = WebSocketHandler(
|
||||
handler, set_handler, lambda s: None, lambda s: lambda a: None
|
||||
)
|
||||
await ws.handle_websocket(websocket)
|
||||
|
||||
async def websocket_offer(self, websocket: WebSocket):
|
||||
handler = cast(StreamHandlerImpl, self.event_handler.copy()) # type: ignore
|
||||
handler.phone_mode = False
|
||||
|
||||
async def set_handler(s: str, a: WebSocketHandler):
|
||||
if len(self.connections) >= self.concurrency_limit: # type: ignore
|
||||
await cast(WebSocket, a.websocket).send_json(
|
||||
{
|
||||
"status": "failed",
|
||||
"meta": {
|
||||
"error": "concurrency_limit_reached",
|
||||
"limit": self.concurrency_limit,
|
||||
},
|
||||
}
|
||||
)
|
||||
await websocket.close()
|
||||
return
|
||||
|
||||
self.connections[s] = [a] # type: ignore
|
||||
|
||||
def clean_up(s):
|
||||
self.clean_up(s)
|
||||
|
||||
ws = WebSocketHandler(
|
||||
handler, set_handler, clean_up, lambda s: self.set_additional_outputs(s)
|
||||
)
|
||||
await ws.handle_websocket(websocket)
|
||||
|
||||
def fastphone(
|
||||
self,
|
||||
token: str | None = None,
|
||||
host: str = "127.0.0.1",
|
||||
port: int = 8000,
|
||||
**kwargs,
|
||||
):
|
||||
import atexit
|
||||
import secrets
|
||||
import threading
|
||||
import time
|
||||
import urllib.parse
|
||||
|
||||
import click
|
||||
import httpx
|
||||
import uvicorn
|
||||
from gradio.networking import setup_tunnel
|
||||
from gradio.tunneling import CURRENT_TUNNELS
|
||||
from huggingface_hub import get_token
|
||||
|
||||
app = FastAPI()
|
||||
|
||||
self.mount(app)
|
||||
|
||||
t = threading.Thread(
|
||||
target=uvicorn.run,
|
||||
args=(app,),
|
||||
kwargs={"host": host, "port": port, **kwargs},
|
||||
)
|
||||
t.start()
|
||||
|
||||
url = setup_tunnel(
|
||||
host, port, share_token=secrets.token_urlsafe(32), share_server_address=None
|
||||
)
|
||||
host = urllib.parse.urlparse(url).netloc
|
||||
|
||||
URL = "https://api.fastrtc.org"
|
||||
try:
|
||||
r = httpx.post(
|
||||
URL + "/register",
|
||||
json={"url": host},
|
||||
headers={"Authorization": token or get_token() or ""},
|
||||
)
|
||||
except Exception:
|
||||
URL = "https://fastrtc-fastphone.hf.space"
|
||||
r = httpx.post(
|
||||
URL + "/register",
|
||||
json={"url": host},
|
||||
headers={"Authorization": token or get_token() or ""},
|
||||
)
|
||||
r.raise_for_status()
|
||||
data = r.json()
|
||||
code = f"{data['code']}"
|
||||
phone_number = data["phone"]
|
||||
reset_date = data["reset_date"]
|
||||
print(
|
||||
click.style("INFO", fg="green")
|
||||
+ ":\t Your FastPhone is now live! Call "
|
||||
+ click.style(phone_number, fg="cyan")
|
||||
+ " and use code "
|
||||
+ click.style(code, fg="cyan")
|
||||
+ " to connect to your stream."
|
||||
)
|
||||
minutes = str(int(data["time_remaining"] // 60)).zfill(2)
|
||||
seconds = str(int(data["time_remaining"] % 60)).zfill(2)
|
||||
print(
|
||||
click.style("INFO", fg="green")
|
||||
+ ":\t You have "
|
||||
+ click.style(f"{minutes}:{seconds}", fg="cyan")
|
||||
+ " minutes remaining in your quota (Resetting on "
|
||||
+ click.style(f"{reset_date}", fg="cyan")
|
||||
+ ")"
|
||||
)
|
||||
print(
|
||||
click.style("INFO", fg="green")
|
||||
+ ":\t Visit "
|
||||
+ click.style(
|
||||
"https://fastrtc.org/userguide/audio/#telephone-integration",
|
||||
fg="cyan",
|
||||
)
|
||||
+ " for information on making your handler compatible with phone usage."
|
||||
)
|
||||
|
||||
def unregister():
|
||||
httpx.post(
|
||||
URL + "/unregister",
|
||||
json={"url": host, "code": code},
|
||||
headers={"Authorization": token or get_token() or ""},
|
||||
)
|
||||
|
||||
atexit.register(unregister)
|
||||
|
||||
try:
|
||||
while True:
|
||||
time.sleep(0.1)
|
||||
except (KeyboardInterrupt, OSError):
|
||||
print(
|
||||
click.style("INFO", fg="green")
|
||||
+ ":\t Keyboard interruption in main thread... closing server."
|
||||
)
|
||||
unregister()
|
||||
t.join(timeout=5)
|
||||
for tunnel in CURRENT_TUNNELS:
|
||||
tunnel.kill()
|
||||
3
backend/fastrtc/text_to_speech/__init__.py
Normal file
3
backend/fastrtc/text_to_speech/__init__.py
Normal file
@@ -0,0 +1,3 @@
|
||||
from .tts import KokoroTTSOptions, get_tts_model
|
||||
|
||||
__all__ = ["get_tts_model", "KokoroTTSOptions"]
|
||||
13
backend/fastrtc/text_to_speech/test_tts.py
Normal file
13
backend/fastrtc/text_to_speech/test_tts.py
Normal file
@@ -0,0 +1,13 @@
|
||||
from fastrtc.text_to_speech.tts import get_tts_model
|
||||
|
||||
|
||||
def test_tts_long_prompt():
|
||||
model = get_tts_model()
|
||||
prompt = "It may be that this communication will be considered as a madman's freak but at any rate it must be admitted that in its clearness and frankness it left nothing to be desired The serious part of it was that the Federal Government had undertaken to treat a sale by auction as a valid concession of these undiscovered territories Opinions on the matter were many Some readers saw in it only one of those prodigious outbursts of American humbug which would exceed the limits of puffism if the depths of human credulity were not unfathomable"
|
||||
|
||||
for i, chunk in enumerate(model.stream_tts_sync(prompt)):
|
||||
print(f"Chunk {i}: {chunk[1].shape}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_tts_long_prompt()
|
||||
135
backend/fastrtc/text_to_speech/tts.py
Normal file
135
backend/fastrtc/text_to_speech/tts.py
Normal file
@@ -0,0 +1,135 @@
|
||||
import asyncio
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from functools import lru_cache
|
||||
from typing import AsyncGenerator, Generator, Literal, Protocol
|
||||
|
||||
import numpy as np
|
||||
from huggingface_hub import hf_hub_download
|
||||
from numpy.typing import NDArray
|
||||
|
||||
|
||||
class TTSOptions:
|
||||
pass
|
||||
|
||||
|
||||
class TTSModel(Protocol):
|
||||
def tts(self, text: str) -> tuple[int, NDArray[np.float32]]: ...
|
||||
|
||||
async def stream_tts(
|
||||
self, text: str, options: TTSOptions | None = None
|
||||
) -> AsyncGenerator[tuple[int, NDArray[np.float32]], None]: ...
|
||||
|
||||
def stream_tts_sync(
|
||||
self, text: str, options: TTSOptions | None = None
|
||||
) -> Generator[tuple[int, NDArray[np.float32]], None, None]: ...
|
||||
|
||||
|
||||
@dataclass
|
||||
class KokoroTTSOptions(TTSOptions):
|
||||
voice: str = "af_heart"
|
||||
speed: float = 1.0
|
||||
lang: str = "en-us"
|
||||
|
||||
|
||||
@lru_cache
|
||||
def get_tts_model(model: Literal["kokoro"] = "kokoro") -> TTSModel:
|
||||
m = KokoroTTSModel()
|
||||
m.tts("Hello, world!")
|
||||
return m
|
||||
|
||||
|
||||
class KokoroFixedBatchSize:
|
||||
# Source: https://github.com/thewh1teagle/kokoro-onnx/issues/115#issuecomment-2676625392
|
||||
def _split_phonemes(self, phonemes: str) -> list[str]:
|
||||
MAX_PHONEME_LENGTH = 510
|
||||
max_length = MAX_PHONEME_LENGTH - 1
|
||||
batched_phonemes = []
|
||||
while len(phonemes) > max_length:
|
||||
# Find best split point within limit
|
||||
split_idx = max_length
|
||||
|
||||
# Try to find the last period before max_length
|
||||
period_idx = phonemes.rfind(".", 0, max_length)
|
||||
if period_idx != -1:
|
||||
split_idx = period_idx + 1 # Include period
|
||||
|
||||
else:
|
||||
# Try other punctuation
|
||||
match = re.search(
|
||||
r"[!?;,]", phonemes[:max_length][::-1]
|
||||
) # Search backwards
|
||||
if match:
|
||||
split_idx = max_length - match.start()
|
||||
|
||||
else:
|
||||
# Try last space
|
||||
space_idx = phonemes.rfind(" ", 0, max_length)
|
||||
if space_idx != -1:
|
||||
split_idx = space_idx
|
||||
|
||||
# If no good split point is found, force split at max_length
|
||||
chunk = phonemes[:split_idx].strip()
|
||||
batched_phonemes.append(chunk)
|
||||
|
||||
# Move to the next part
|
||||
phonemes = phonemes[split_idx:].strip()
|
||||
|
||||
# Add remaining phonemes
|
||||
if phonemes:
|
||||
batched_phonemes.append(phonemes)
|
||||
return batched_phonemes
|
||||
|
||||
|
||||
class KokoroTTSModel(TTSModel):
|
||||
def __init__(self):
|
||||
from kokoro_onnx import Kokoro
|
||||
|
||||
self.model = Kokoro(
|
||||
model_path=hf_hub_download("fastrtc/kokoro-onnx", "kokoro-v1.0.onnx"),
|
||||
voices_path=hf_hub_download("fastrtc/kokoro-onnx", "voices-v1.0.bin"),
|
||||
)
|
||||
|
||||
self.model._split_phonemes = KokoroFixedBatchSize()._split_phonemes
|
||||
|
||||
def tts(
|
||||
self, text: str, options: KokoroTTSOptions | None = None
|
||||
) -> tuple[int, NDArray[np.float32]]:
|
||||
options = options or KokoroTTSOptions()
|
||||
a, b = self.model.create(
|
||||
text, voice=options.voice, speed=options.speed, lang=options.lang
|
||||
)
|
||||
return b, a
|
||||
|
||||
async def stream_tts(
|
||||
self, text: str, options: KokoroTTSOptions | None = None
|
||||
) -> AsyncGenerator[tuple[int, NDArray[np.float32]], None]:
|
||||
options = options or KokoroTTSOptions()
|
||||
|
||||
sentences = re.split(r"(?<=[.!?])\s+", text.strip())
|
||||
|
||||
for s_idx, sentence in enumerate(sentences):
|
||||
if not sentence.strip():
|
||||
continue
|
||||
|
||||
chunk_idx = 0
|
||||
async for chunk in self.model.create_stream(
|
||||
sentence, voice=options.voice, speed=options.speed, lang=options.lang
|
||||
):
|
||||
if s_idx != 0 and chunk_idx == 0:
|
||||
yield chunk[1], np.zeros(chunk[1] // 7, dtype=np.float32)
|
||||
chunk_idx += 1
|
||||
yield chunk[1], chunk[0]
|
||||
|
||||
def stream_tts_sync(
|
||||
self, text: str, options: KokoroTTSOptions | None = None
|
||||
) -> Generator[tuple[int, NDArray[np.float32]], None, None]:
|
||||
loop = asyncio.new_event_loop()
|
||||
|
||||
# Use the new loop to run the async generator
|
||||
iterator = self.stream_tts(text, options).__aiter__()
|
||||
while True:
|
||||
try:
|
||||
yield loop.run_until_complete(iterator.__anext__())
|
||||
except StopAsyncIteration:
|
||||
break
|
||||
731
backend/fastrtc/tracks.py
Normal file
731
backend/fastrtc/tracks.py
Normal file
@@ -0,0 +1,731 @@
|
||||
"""WebRTC tracks."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import functools
|
||||
import inspect
|
||||
import logging
|
||||
import threading
|
||||
import time
|
||||
import traceback
|
||||
from abc import ABC, abstractmethod
|
||||
from collections.abc import Callable
|
||||
from typing import (
|
||||
Any,
|
||||
Generator,
|
||||
Literal,
|
||||
TypeAlias,
|
||||
Union,
|
||||
cast,
|
||||
)
|
||||
|
||||
import anyio.to_thread
|
||||
import av
|
||||
import numpy as np
|
||||
from aiortc import (
|
||||
AudioStreamTrack,
|
||||
MediaStreamTrack,
|
||||
VideoStreamTrack,
|
||||
)
|
||||
from aiortc.contrib.media import AudioFrame, VideoFrame # type: ignore
|
||||
from aiortc.mediastreams import MediaStreamError
|
||||
from numpy import typing as npt
|
||||
|
||||
from fastrtc.utils import (
|
||||
AdditionalOutputs,
|
||||
DataChannel,
|
||||
WebRTCError,
|
||||
create_message,
|
||||
current_channel,
|
||||
player_worker_decode,
|
||||
split_output,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
VideoNDArray: TypeAlias = Union[
|
||||
np.ndarray[Any, np.dtype[np.uint8]],
|
||||
np.ndarray[Any, np.dtype[np.uint16]],
|
||||
np.ndarray[Any, np.dtype[np.float32]],
|
||||
]
|
||||
|
||||
VideoEmitType = (
|
||||
VideoNDArray | tuple[VideoNDArray, AdditionalOutputs] | AdditionalOutputs
|
||||
)
|
||||
VideoEventHandler = Callable[[npt.ArrayLike], VideoEmitType]
|
||||
|
||||
|
||||
class VideoCallback(VideoStreamTrack):
|
||||
"""
|
||||
This works for streaming input and output
|
||||
"""
|
||||
|
||||
kind = "video"
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
track: MediaStreamTrack,
|
||||
event_handler: VideoEventHandler,
|
||||
channel: DataChannel | None = None,
|
||||
set_additional_outputs: Callable | None = None,
|
||||
mode: Literal["send-receive", "send"] = "send-receive",
|
||||
) -> None:
|
||||
super().__init__() # don't forget this!
|
||||
self.track = track
|
||||
self.event_handler = event_handler
|
||||
self.latest_args: str | list[Any] = "not_set"
|
||||
self.channel = channel
|
||||
self.set_additional_outputs = set_additional_outputs
|
||||
self.thread_quit = asyncio.Event()
|
||||
self.mode = mode
|
||||
self.channel_set = asyncio.Event()
|
||||
self.has_started = False
|
||||
|
||||
def set_channel(self, channel: DataChannel):
|
||||
self.channel = channel
|
||||
current_channel.set(channel)
|
||||
self.channel_set.set()
|
||||
|
||||
def set_args(self, args: list[Any]):
|
||||
self.latest_args = ["__webrtc_value__"] + list(args)
|
||||
|
||||
def add_frame_to_payload(
|
||||
self, args: list[Any], frame: np.ndarray | None
|
||||
) -> list[Any]:
|
||||
new_args = []
|
||||
for val in args:
|
||||
if isinstance(val, str) and val == "__webrtc_value__":
|
||||
new_args.append(frame)
|
||||
else:
|
||||
new_args.append(val)
|
||||
return new_args
|
||||
|
||||
def array_to_frame(self, array: np.ndarray) -> VideoFrame:
|
||||
return VideoFrame.from_ndarray(array, format="bgr24")
|
||||
|
||||
async def process_frames(self):
|
||||
while not self.thread_quit.is_set():
|
||||
try:
|
||||
await self.recv()
|
||||
except TimeoutError:
|
||||
continue
|
||||
|
||||
async def start(
|
||||
self,
|
||||
):
|
||||
asyncio.create_task(self.process_frames())
|
||||
|
||||
def stop(self):
|
||||
super().stop()
|
||||
logger.debug("video callback stop")
|
||||
self.thread_quit.set()
|
||||
|
||||
async def wait_for_channel(self):
|
||||
if not self.channel_set.is_set():
|
||||
await self.channel_set.wait()
|
||||
if current_channel.get() != self.channel:
|
||||
current_channel.set(self.channel)
|
||||
|
||||
async def recv(self): # type: ignore
|
||||
try:
|
||||
try:
|
||||
frame = cast(VideoFrame, await self.track.recv())
|
||||
except MediaStreamError:
|
||||
self.stop()
|
||||
return
|
||||
|
||||
await self.wait_for_channel()
|
||||
frame_array = frame.to_ndarray(format="bgr24")
|
||||
if self.latest_args == "not_set":
|
||||
return frame
|
||||
|
||||
args = self.add_frame_to_payload(cast(list, self.latest_args), frame_array)
|
||||
|
||||
array, outputs = split_output(self.event_handler(*args))
|
||||
if (
|
||||
isinstance(outputs, AdditionalOutputs)
|
||||
and self.set_additional_outputs
|
||||
and self.channel
|
||||
):
|
||||
self.set_additional_outputs(outputs)
|
||||
self.channel.send(create_message("fetch_output", []))
|
||||
if array is None and self.mode == "send":
|
||||
return
|
||||
|
||||
new_frame = self.array_to_frame(array)
|
||||
if frame:
|
||||
new_frame.pts = frame.pts
|
||||
new_frame.time_base = frame.time_base
|
||||
else:
|
||||
pts, time_base = await self.next_timestamp()
|
||||
new_frame.pts = pts
|
||||
new_frame.time_base = time_base
|
||||
|
||||
return new_frame
|
||||
except Exception as e:
|
||||
logger.debug("exception %s", e)
|
||||
exec = traceback.format_exc()
|
||||
logger.debug("traceback %s", exec)
|
||||
if isinstance(e, WebRTCError):
|
||||
raise e
|
||||
else:
|
||||
raise WebRTCError(str(e)) from e
|
||||
|
||||
|
||||
class StreamHandlerBase(ABC):
|
||||
def __init__(
|
||||
self,
|
||||
expected_layout: Literal["mono", "stereo"] = "mono",
|
||||
output_sample_rate: int = 24000,
|
||||
output_frame_size: int = 960,
|
||||
input_sample_rate: int = 48000,
|
||||
) -> None:
|
||||
self.expected_layout = expected_layout
|
||||
self.output_sample_rate = output_sample_rate
|
||||
self.output_frame_size = output_frame_size
|
||||
self.input_sample_rate = input_sample_rate
|
||||
self.latest_args: list[Any] = []
|
||||
self._resampler = None
|
||||
self._channel: DataChannel | None = None
|
||||
self._loop: asyncio.AbstractEventLoop
|
||||
self.args_set = asyncio.Event()
|
||||
self.channel_set = asyncio.Event()
|
||||
self._phone_mode = False
|
||||
self._clear_queue: Callable | None = None
|
||||
|
||||
@property
|
||||
def clear_queue(self) -> Callable:
|
||||
return cast(Callable, self._clear_queue)
|
||||
|
||||
@property
|
||||
def loop(self) -> asyncio.AbstractEventLoop:
|
||||
return cast(asyncio.AbstractEventLoop, self._loop)
|
||||
|
||||
@property
|
||||
def channel(self) -> DataChannel | None:
|
||||
return self._channel
|
||||
|
||||
@property
|
||||
def phone_mode(self) -> bool:
|
||||
return self._phone_mode
|
||||
|
||||
@phone_mode.setter
|
||||
def phone_mode(self, value: bool):
|
||||
self._phone_mode = value
|
||||
|
||||
def set_channel(self, channel: DataChannel):
|
||||
self._channel = channel
|
||||
self.channel_set.set()
|
||||
|
||||
async def fetch_args(
|
||||
self,
|
||||
):
|
||||
if self.channel:
|
||||
self.channel.send(create_message("send_input", []))
|
||||
logger.debug("Sent send_input")
|
||||
|
||||
async def wait_for_args(self):
|
||||
if not self.phone_mode:
|
||||
await self.fetch_args()
|
||||
await self.args_set.wait()
|
||||
else:
|
||||
self.args_set.set()
|
||||
|
||||
def wait_for_args_sync(self):
|
||||
try:
|
||||
asyncio.run_coroutine_threadsafe(self.wait_for_args(), self.loop).result()
|
||||
except Exception:
|
||||
import traceback
|
||||
|
||||
traceback.print_exc()
|
||||
|
||||
async def send_message(self, msg: str):
|
||||
if self.channel:
|
||||
self.channel.send(msg)
|
||||
logger.debug("Sent msg %s", msg)
|
||||
|
||||
def send_message_sync(self, msg: str):
|
||||
try:
|
||||
asyncio.run_coroutine_threadsafe(self.send_message(msg), self.loop).result()
|
||||
logger.debug("Sent msg %s", msg)
|
||||
except Exception as e:
|
||||
logger.debug("Exception sending msg %s", e)
|
||||
|
||||
def set_args(self, args: list[Any]):
|
||||
logger.debug("setting args in audio callback %s", args)
|
||||
self.latest_args = ["__webrtc_value__"] + list(args)
|
||||
self.args_set.set()
|
||||
|
||||
def reset(self):
|
||||
self.args_set.clear()
|
||||
|
||||
def shutdown(self):
|
||||
pass
|
||||
|
||||
def resample(self, frame: AudioFrame) -> Generator[AudioFrame, None, None]:
|
||||
if self._resampler is None:
|
||||
self._resampler = av.AudioResampler( # type: ignore
|
||||
format="s16",
|
||||
layout=self.expected_layout,
|
||||
rate=self.input_sample_rate,
|
||||
frame_size=frame.samples,
|
||||
)
|
||||
yield from self._resampler.resample(frame)
|
||||
|
||||
|
||||
EmitType: TypeAlias = (
|
||||
tuple[int, npt.NDArray[np.int16 | np.float32]]
|
||||
| tuple[int, npt.NDArray[np.int16 | np.float32], Literal["mono", "stereo"]]
|
||||
| AdditionalOutputs
|
||||
| tuple[tuple[int, npt.NDArray[np.int16 | np.float32]], AdditionalOutputs]
|
||||
| None
|
||||
)
|
||||
AudioEmitType = EmitType
|
||||
|
||||
|
||||
class StreamHandler(StreamHandlerBase):
|
||||
@abstractmethod
|
||||
def receive(self, frame: tuple[int, npt.NDArray[np.int16]]) -> None:
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def emit(self) -> EmitType:
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def copy(self) -> StreamHandler:
|
||||
pass
|
||||
|
||||
def start_up(self):
|
||||
pass
|
||||
|
||||
|
||||
class AsyncStreamHandler(StreamHandlerBase):
|
||||
@abstractmethod
|
||||
async def receive(self, frame: tuple[int, npt.NDArray[np.int16]]) -> None:
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
async def emit(self) -> EmitType:
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def copy(self) -> AsyncStreamHandler:
|
||||
pass
|
||||
|
||||
async def start_up(self):
|
||||
pass
|
||||
|
||||
|
||||
StreamHandlerImpl = StreamHandler | AsyncStreamHandler
|
||||
|
||||
|
||||
class AudioVideoStreamHandler(StreamHandler):
|
||||
@abstractmethod
|
||||
def video_receive(self, frame: VideoFrame) -> None:
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def video_emit(self) -> VideoEmitType:
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def copy(self) -> AudioVideoStreamHandler:
|
||||
pass
|
||||
|
||||
|
||||
class AsyncAudioVideoStreamHandler(AsyncStreamHandler):
|
||||
@abstractmethod
|
||||
async def video_receive(self, frame: npt.NDArray[np.float32]) -> None:
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
async def video_emit(self) -> VideoEmitType:
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def copy(self) -> AsyncAudioVideoStreamHandler:
|
||||
pass
|
||||
|
||||
|
||||
VideoStreamHandlerImpl = AudioVideoStreamHandler | AsyncAudioVideoStreamHandler
|
||||
AudioVideoStreamHandlerImpl = AudioVideoStreamHandler | AsyncAudioVideoStreamHandler
|
||||
AsyncHandler = AsyncStreamHandler | AsyncAudioVideoStreamHandler
|
||||
|
||||
HandlerType = StreamHandlerImpl | VideoStreamHandlerImpl | VideoEventHandler | Callable
|
||||
|
||||
|
||||
class VideoStreamHandler(VideoCallback):
|
||||
async def process_frames(self):
|
||||
while not self.thread_quit.is_set():
|
||||
try:
|
||||
await self.channel_set.wait()
|
||||
frame = cast(VideoFrame, await self.track.recv())
|
||||
frame_array = frame.to_ndarray(format="bgr24")
|
||||
handler = cast(VideoStreamHandlerImpl, self.event_handler)
|
||||
if inspect.iscoroutinefunction(handler.video_receive):
|
||||
await handler.video_receive(frame_array)
|
||||
else:
|
||||
handler.video_receive(frame_array) # type: ignore
|
||||
except MediaStreamError:
|
||||
self.stop()
|
||||
|
||||
async def start(self):
|
||||
if not self.has_started:
|
||||
asyncio.create_task(self.process_frames())
|
||||
self.has_started = True
|
||||
|
||||
async def recv(self): # type: ignore
|
||||
await self.start()
|
||||
try:
|
||||
handler = cast(VideoStreamHandlerImpl, self.event_handler)
|
||||
if inspect.iscoroutinefunction(handler.video_emit):
|
||||
outputs = await handler.video_emit()
|
||||
else:
|
||||
outputs = handler.video_emit()
|
||||
|
||||
array, outputs = split_output(outputs)
|
||||
if (
|
||||
isinstance(outputs, AdditionalOutputs)
|
||||
and self.set_additional_outputs
|
||||
and self.channel
|
||||
):
|
||||
self.set_additional_outputs(outputs)
|
||||
self.channel.send(create_message("fetch_output", []))
|
||||
if array is None and self.mode == "send":
|
||||
return
|
||||
|
||||
new_frame = self.array_to_frame(array)
|
||||
|
||||
# Will probably have to give developer ability to set pts and time_base
|
||||
pts, time_base = await self.next_timestamp()
|
||||
new_frame.pts = pts
|
||||
new_frame.time_base = time_base
|
||||
|
||||
return new_frame
|
||||
except Exception as e:
|
||||
logger.debug("exception %s", e)
|
||||
exec = traceback.format_exc()
|
||||
logger.debug("traceback %s", exec)
|
||||
|
||||
|
||||
class AudioCallback(AudioStreamTrack):
|
||||
kind = "audio"
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
track: MediaStreamTrack,
|
||||
event_handler: StreamHandlerBase,
|
||||
channel: DataChannel | None = None,
|
||||
set_additional_outputs: Callable | None = None,
|
||||
) -> None:
|
||||
super().__init__()
|
||||
self.track = track
|
||||
self.event_handler = cast(StreamHandlerImpl, event_handler)
|
||||
self.event_handler._clear_queue = self.clear_queue
|
||||
self.current_timestamp = 0
|
||||
self.latest_args: str | list[Any] = "not_set"
|
||||
self.queue = asyncio.Queue()
|
||||
self.thread_quit = asyncio.Event()
|
||||
self._start: float | None = None
|
||||
self.has_started = False
|
||||
self.last_timestamp = 0
|
||||
self.channel = channel
|
||||
self.set_additional_outputs = set_additional_outputs
|
||||
|
||||
def clear_queue(self):
|
||||
logger.debug("clearing queue")
|
||||
logger.debug("queue size: %d", self.queue.qsize())
|
||||
i = 0
|
||||
while not self.queue.empty():
|
||||
self.queue.get_nowait()
|
||||
i += 1
|
||||
logger.debug("popped %d items from queue", i)
|
||||
self._start = None
|
||||
|
||||
async def wait_for_channel(self):
|
||||
if not self.event_handler.channel_set.is_set():
|
||||
await self.event_handler.channel_set.wait()
|
||||
if current_channel.get() != self.event_handler.channel:
|
||||
current_channel.set(self.event_handler.channel)
|
||||
|
||||
def set_channel(self, channel: DataChannel):
|
||||
self.channel = channel
|
||||
self.event_handler.set_channel(channel)
|
||||
|
||||
def set_args(self, args: list[Any]):
|
||||
self.event_handler.set_args(args)
|
||||
|
||||
def event_handler_receive(self, frame: tuple[int, np.ndarray]) -> None:
|
||||
current_channel.set(self.event_handler.channel)
|
||||
return cast(Callable, self.event_handler.receive)(frame)
|
||||
|
||||
def event_handler_emit(self) -> EmitType:
|
||||
current_channel.set(self.event_handler.channel)
|
||||
return cast(Callable, self.event_handler.emit)()
|
||||
|
||||
async def process_input_frames(self) -> None:
|
||||
while not self.thread_quit.is_set():
|
||||
try:
|
||||
frame = cast(AudioFrame, await self.track.recv())
|
||||
for frame in self.event_handler.resample(frame):
|
||||
numpy_array = frame.to_ndarray()
|
||||
if isinstance(self.event_handler, AsyncHandler):
|
||||
await self.event_handler.receive(
|
||||
(frame.sample_rate, numpy_array) # type: ignore
|
||||
)
|
||||
else:
|
||||
await anyio.to_thread.run_sync(
|
||||
self.event_handler_receive, (frame.sample_rate, numpy_array)
|
||||
)
|
||||
except MediaStreamError:
|
||||
logger.debug("MediaStreamError in process_input_frames")
|
||||
break
|
||||
|
||||
async def start(self):
|
||||
if not self.has_started:
|
||||
loop = asyncio.get_running_loop()
|
||||
await self.wait_for_channel()
|
||||
if isinstance(self.event_handler, AsyncHandler):
|
||||
callable = self.event_handler.emit
|
||||
start_up = self.event_handler.start_up()
|
||||
if not inspect.isawaitable(start_up):
|
||||
raise WebRTCError(
|
||||
"In AsyncStreamHandler, start_up must be a coroutine (async def)"
|
||||
)
|
||||
|
||||
else:
|
||||
callable = functools.partial(
|
||||
loop.run_in_executor, None, self.event_handler_emit
|
||||
)
|
||||
start_up = anyio.to_thread.run_sync(self.event_handler.start_up)
|
||||
self.process_input_task = asyncio.create_task(self.process_input_frames())
|
||||
self.process_input_task.add_done_callback(
|
||||
lambda _: logger.debug("process_input_done")
|
||||
)
|
||||
self.start_up_task = asyncio.create_task(start_up)
|
||||
self.start_up_task.add_done_callback(
|
||||
lambda _: logger.debug("start_up_done")
|
||||
)
|
||||
self.decode_task = asyncio.create_task(
|
||||
player_worker_decode(
|
||||
callable,
|
||||
self.queue,
|
||||
self.thread_quit,
|
||||
lambda: self.channel,
|
||||
self.set_additional_outputs,
|
||||
False,
|
||||
self.event_handler.output_sample_rate,
|
||||
self.event_handler.output_frame_size,
|
||||
)
|
||||
)
|
||||
self.decode_task.add_done_callback(lambda _: logger.debug("decode_done"))
|
||||
self.has_started = True
|
||||
|
||||
async def recv(self): # type: ignore
|
||||
try:
|
||||
if self.readyState != "live":
|
||||
raise MediaStreamError
|
||||
|
||||
if not self.event_handler.channel_set.is_set():
|
||||
await self.event_handler.channel_set.wait()
|
||||
if current_channel.get() != self.event_handler.channel:
|
||||
current_channel.set(self.event_handler.channel)
|
||||
await self.start()
|
||||
|
||||
frame = await self.queue.get()
|
||||
logger.debug("frame %s", frame)
|
||||
|
||||
data_time = frame.time
|
||||
|
||||
if time.time() - self.last_timestamp > 10 * (
|
||||
self.event_handler.output_frame_size
|
||||
/ self.event_handler.output_sample_rate
|
||||
):
|
||||
self._start = None
|
||||
|
||||
# control playback rate
|
||||
if self._start is None:
|
||||
self._start = time.time() - data_time # type: ignore
|
||||
else:
|
||||
wait = self._start + data_time - time.time()
|
||||
await asyncio.sleep(wait)
|
||||
self.last_timestamp = time.time()
|
||||
return frame
|
||||
except Exception as e:
|
||||
logger.debug("exception %s", e)
|
||||
exec = traceback.format_exc()
|
||||
logger.debug("traceback %s", exec)
|
||||
|
||||
def stop(self):
|
||||
logger.debug("audio callback stop")
|
||||
self.thread_quit.set()
|
||||
super().stop()
|
||||
|
||||
|
||||
class ServerToClientVideo(VideoStreamTrack):
|
||||
"""
|
||||
This works for streaming input and output
|
||||
"""
|
||||
|
||||
kind = "video"
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
event_handler: Callable,
|
||||
channel: DataChannel | None = None,
|
||||
set_additional_outputs: Callable | None = None,
|
||||
) -> None:
|
||||
super().__init__() # don't forget this!
|
||||
self.event_handler = event_handler
|
||||
self.args_set = asyncio.Event()
|
||||
self.latest_args: str | list[Any] = "not_set"
|
||||
self.generator: Generator[Any, None, Any] | None = None
|
||||
self.channel = channel
|
||||
self.set_additional_outputs = set_additional_outputs
|
||||
|
||||
def array_to_frame(self, array: np.ndarray) -> VideoFrame:
|
||||
return VideoFrame.from_ndarray(array, format="bgr24")
|
||||
|
||||
def set_channel(self, channel: DataChannel):
|
||||
self.channel = channel
|
||||
|
||||
def set_args(self, args: list[Any]):
|
||||
self.latest_args = list(args)
|
||||
self.args_set.set()
|
||||
|
||||
async def recv(self): # type: ignore
|
||||
try:
|
||||
pts, time_base = await self.next_timestamp()
|
||||
await self.args_set.wait()
|
||||
current_channel.set(self.channel)
|
||||
if self.generator is None:
|
||||
self.generator = cast(
|
||||
Generator[Any, None, Any], self.event_handler(*self.latest_args)
|
||||
)
|
||||
try:
|
||||
next_array, outputs = split_output(next(self.generator))
|
||||
if (
|
||||
isinstance(outputs, AdditionalOutputs)
|
||||
and self.set_additional_outputs
|
||||
and self.channel
|
||||
):
|
||||
self.set_additional_outputs(outputs)
|
||||
self.channel.send(create_message("fetch_output", []))
|
||||
except StopIteration:
|
||||
self.stop()
|
||||
return
|
||||
|
||||
next_frame = self.array_to_frame(next_array)
|
||||
next_frame.pts = pts
|
||||
next_frame.time_base = time_base
|
||||
return next_frame
|
||||
except Exception as e:
|
||||
logger.debug("exception %s", e)
|
||||
exec = traceback.format_exc()
|
||||
logger.debug("traceback %s %s", e, exec)
|
||||
if isinstance(e, WebRTCError):
|
||||
raise e
|
||||
else:
|
||||
raise WebRTCError(str(e)) from e
|
||||
|
||||
|
||||
class ServerToClientAudio(AudioStreamTrack):
|
||||
kind = "audio"
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
event_handler: Callable,
|
||||
channel: DataChannel | None = None,
|
||||
set_additional_outputs: Callable | None = None,
|
||||
) -> None:
|
||||
self.generator: Generator[Any, None, Any] | None = None
|
||||
self.event_handler = event_handler
|
||||
self.event_handler._clear_queue = self.clear_queue
|
||||
self.current_timestamp = 0
|
||||
self.latest_args: str | list[Any] = "not_set"
|
||||
self.args_set = threading.Event()
|
||||
self.queue = asyncio.Queue()
|
||||
self.thread_quit = asyncio.Event()
|
||||
self.channel = channel
|
||||
self.set_additional_outputs = set_additional_outputs
|
||||
self.has_started = False
|
||||
self._start: float | None = None
|
||||
super().__init__()
|
||||
|
||||
def clear_queue(self):
|
||||
while not self.queue.empty():
|
||||
self.queue.get_nowait()
|
||||
self._start = None
|
||||
|
||||
def set_channel(self, channel: DataChannel):
|
||||
self.channel = channel
|
||||
|
||||
def set_args(self, args: list[Any]):
|
||||
self.latest_args = list(args)
|
||||
self.args_set.set()
|
||||
|
||||
def next(self) -> tuple[int, np.ndarray] | None:
|
||||
self.args_set.wait()
|
||||
current_channel.set(self.channel)
|
||||
if self.generator is None:
|
||||
self.generator = self.event_handler(*self.latest_args)
|
||||
if self.generator is not None:
|
||||
try:
|
||||
frame = next(self.generator)
|
||||
return frame
|
||||
except StopIteration:
|
||||
self.thread_quit.set()
|
||||
|
||||
async def start(self):
|
||||
if not self.has_started:
|
||||
loop = asyncio.get_running_loop()
|
||||
callable = functools.partial(loop.run_in_executor, None, self.next)
|
||||
asyncio.create_task(
|
||||
player_worker_decode(
|
||||
callable,
|
||||
self.queue,
|
||||
self.thread_quit,
|
||||
lambda: self.channel,
|
||||
self.set_additional_outputs,
|
||||
True,
|
||||
)
|
||||
)
|
||||
self.has_started = True
|
||||
|
||||
async def recv(self): # type: ignore
|
||||
try:
|
||||
if self.readyState != "live":
|
||||
raise MediaStreamError
|
||||
|
||||
await self.start()
|
||||
data = await self.queue.get()
|
||||
if data is None:
|
||||
self.stop()
|
||||
return
|
||||
|
||||
data_time = data.time
|
||||
|
||||
# control playback rate
|
||||
if data_time is not None:
|
||||
if self._start is None:
|
||||
self._start = time.time() - data_time # type: ignore
|
||||
else:
|
||||
wait = self._start + data_time - time.time()
|
||||
await asyncio.sleep(wait)
|
||||
|
||||
return data
|
||||
except Exception as e:
|
||||
logger.debug("exception %s", e)
|
||||
exec = traceback.format_exc()
|
||||
logger.debug("traceback %s", exec)
|
||||
if isinstance(e, WebRTCError):
|
||||
raise e
|
||||
else:
|
||||
raise WebRTCError(str(e)) from e
|
||||
|
||||
def stop(self):
|
||||
logger.debug("audio-to-client stop callback")
|
||||
self.thread_quit.set()
|
||||
super().stop()
|
||||
456
backend/fastrtc/utils.py
Normal file
456
backend/fastrtc/utils.py
Normal file
@@ -0,0 +1,456 @@
|
||||
import asyncio
|
||||
import fractions
|
||||
import functools
|
||||
import inspect
|
||||
import io
|
||||
import json
|
||||
import logging
|
||||
import tempfile
|
||||
import traceback
|
||||
from contextvars import ContextVar
|
||||
from typing import Any, Callable, Literal, Protocol, TypedDict, cast
|
||||
|
||||
import av
|
||||
import numpy as np
|
||||
from numpy.typing import NDArray
|
||||
from pydub import AudioSegment
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
AUDIO_PTIME = 0.020
|
||||
|
||||
|
||||
class Message(TypedDict):
|
||||
type: str
|
||||
data: Any
|
||||
|
||||
class AudioChunk(TypedDict):
|
||||
start: int
|
||||
end: int
|
||||
|
||||
|
||||
class AdditionalOutputs:
|
||||
def __init__(self, *args) -> None:
|
||||
self.args = args
|
||||
|
||||
|
||||
class DataChannel(Protocol):
|
||||
def send(self, message: str) -> None: ...
|
||||
|
||||
|
||||
def create_message(
|
||||
type: Literal[
|
||||
"send_input",
|
||||
"fetch_output",
|
||||
"stopword",
|
||||
"error",
|
||||
"warning",
|
||||
"log",
|
||||
],
|
||||
data: list[Any] | str,
|
||||
) -> str:
|
||||
return json.dumps({"type": type, "data": data})
|
||||
|
||||
|
||||
current_channel: ContextVar[DataChannel | None] = ContextVar(
|
||||
"current_channel", default=None
|
||||
)
|
||||
|
||||
|
||||
def _send_log(message: str, type: str) -> None:
|
||||
async def _send(channel: DataChannel) -> None:
|
||||
channel.send(
|
||||
json.dumps(
|
||||
{
|
||||
"type": type,
|
||||
"message": message,
|
||||
}
|
||||
)
|
||||
)
|
||||
|
||||
if channel := current_channel.get():
|
||||
try:
|
||||
loop = asyncio.get_running_loop()
|
||||
asyncio.run_coroutine_threadsafe(_send(channel), loop)
|
||||
except RuntimeError:
|
||||
asyncio.run(_send(channel))
|
||||
|
||||
|
||||
def Warning( # noqa: N802
|
||||
message: str = "Warning issued.",
|
||||
):
|
||||
"""
|
||||
Send a warning message that is deplayed in the UI of the application.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
audio : str
|
||||
The warning message to send
|
||||
|
||||
Returns
|
||||
-------
|
||||
None
|
||||
"""
|
||||
_send_log(message, "warning")
|
||||
|
||||
|
||||
class WebRTCError(Exception):
|
||||
def __init__(self, message: str) -> None:
|
||||
super().__init__(message)
|
||||
_send_log(message, "error")
|
||||
|
||||
|
||||
def split_output(data: tuple | Any) -> tuple[Any, AdditionalOutputs | None]:
|
||||
if isinstance(data, AdditionalOutputs):
|
||||
return None, data
|
||||
if isinstance(data, tuple):
|
||||
# handle the bare audio case
|
||||
if 2 <= len(data) <= 3 and isinstance(data[1], np.ndarray):
|
||||
return data, None
|
||||
if not len(data) == 2:
|
||||
raise ValueError(
|
||||
"The tuple must have exactly two elements: the data and an instance of AdditionalOutputs."
|
||||
)
|
||||
if not isinstance(data[-1], AdditionalOutputs):
|
||||
raise ValueError(
|
||||
"The last element of the tuple must be an instance of AdditionalOutputs."
|
||||
)
|
||||
return data[0], cast(AdditionalOutputs, data[1])
|
||||
return data, None
|
||||
|
||||
|
||||
async def player_worker_decode(
|
||||
next_frame: Callable,
|
||||
queue: asyncio.Queue,
|
||||
thread_quit: asyncio.Event,
|
||||
channel: Callable[[], DataChannel | None] | None,
|
||||
set_additional_outputs: Callable | None,
|
||||
quit_on_none: bool = False,
|
||||
sample_rate: int = 48000,
|
||||
frame_size: int = int(48000 * AUDIO_PTIME),
|
||||
):
|
||||
audio_samples = 0
|
||||
audio_time_base = fractions.Fraction(1, sample_rate)
|
||||
audio_resampler = av.AudioResampler( # type: ignore
|
||||
format="s16",
|
||||
layout="stereo",
|
||||
rate=sample_rate,
|
||||
frame_size=frame_size,
|
||||
)
|
||||
|
||||
while not thread_quit.is_set():
|
||||
try:
|
||||
# Get next frame
|
||||
frame, outputs = split_output(
|
||||
await asyncio.wait_for(next_frame(), timeout=60)
|
||||
)
|
||||
if (
|
||||
isinstance(outputs, AdditionalOutputs)
|
||||
and set_additional_outputs
|
||||
and channel
|
||||
and channel()
|
||||
):
|
||||
set_additional_outputs(outputs)
|
||||
cast(DataChannel, channel()).send(create_message("fetch_output", []))
|
||||
|
||||
if frame is None:
|
||||
if quit_on_none:
|
||||
await queue.put(None)
|
||||
break
|
||||
continue
|
||||
|
||||
if not isinstance(frame, tuple) and not isinstance(frame[1], np.ndarray):
|
||||
raise WebRTCError(
|
||||
"The frame must be a tuple containing a sample rate and a numpy array."
|
||||
)
|
||||
|
||||
if len(frame) == 2:
|
||||
sample_rate, audio_array = frame
|
||||
layout = "mono"
|
||||
elif len(frame) == 3:
|
||||
sample_rate, audio_array, layout = frame
|
||||
|
||||
logger.debug(
|
||||
"received array with shape %s sample rate %s layout %s",
|
||||
audio_array.shape, # type: ignore
|
||||
sample_rate,
|
||||
layout, # type: ignore
|
||||
)
|
||||
format = "s16" if audio_array.dtype == "int16" else "fltp" # type: ignore
|
||||
|
||||
if audio_array.ndim == 1:
|
||||
audio_array = audio_array.reshape(1, -1)
|
||||
|
||||
# Convert to audio frame and resample
|
||||
# This runs in the same timeout context
|
||||
frame = av.AudioFrame.from_ndarray( # type: ignore
|
||||
audio_array, # type: ignore
|
||||
format=format,
|
||||
layout=layout, # type: ignore
|
||||
)
|
||||
frame.sample_rate = sample_rate
|
||||
|
||||
for processed_frame in audio_resampler.resample(frame):
|
||||
processed_frame.pts = audio_samples
|
||||
processed_frame.time_base = audio_time_base
|
||||
audio_samples += processed_frame.samples
|
||||
await queue.put(processed_frame)
|
||||
|
||||
except (TimeoutError, asyncio.TimeoutError):
|
||||
logger.warning(
|
||||
"Timeout in frame processing cycle after %s seconds - resetting", 60
|
||||
)
|
||||
continue
|
||||
except Exception as e:
|
||||
import traceback
|
||||
|
||||
exec = traceback.format_exc()
|
||||
print("traceback %s", exec)
|
||||
print("Error processing frame: %s", str(e))
|
||||
if isinstance(e, WebRTCError):
|
||||
raise e
|
||||
else:
|
||||
continue
|
||||
|
||||
|
||||
def audio_to_bytes(audio: tuple[int, NDArray[np.int16 | np.float32]]) -> bytes:
|
||||
"""
|
||||
Convert an audio tuple containing sample rate and numpy array data into bytes.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
audio : tuple[int, np.ndarray]
|
||||
A tuple containing:
|
||||
- sample_rate (int): The audio sample rate in Hz
|
||||
- data (np.ndarray): The audio data as a numpy array
|
||||
|
||||
Returns
|
||||
-------
|
||||
bytes
|
||||
The audio data encoded as bytes, suitable for transmission or storage
|
||||
|
||||
Example
|
||||
-------
|
||||
>>> sample_rate = 44100
|
||||
>>> audio_data = np.array([0.1, -0.2, 0.3]) # Example audio samples
|
||||
>>> audio_tuple = (sample_rate, audio_data)
|
||||
>>> audio_bytes = audio_to_bytes(audio_tuple)
|
||||
"""
|
||||
audio_buffer = io.BytesIO()
|
||||
segment = AudioSegment(
|
||||
audio[1].tobytes(),
|
||||
frame_rate=audio[0],
|
||||
sample_width=audio[1].dtype.itemsize,
|
||||
channels=1,
|
||||
)
|
||||
segment.export(audio_buffer, format="mp3")
|
||||
return audio_buffer.getvalue()
|
||||
|
||||
|
||||
def audio_to_file(audio: tuple[int, NDArray[np.int16 | np.float32]]) -> str:
|
||||
"""
|
||||
Save an audio tuple containing sample rate and numpy array data to a file.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
audio : tuple[int, np.ndarray]
|
||||
A tuple containing:
|
||||
- sample_rate (int): The audio sample rate in Hz
|
||||
- data (np.ndarray): The audio data as a numpy array
|
||||
|
||||
Returns
|
||||
-------
|
||||
str
|
||||
The path to the saved audio file
|
||||
|
||||
Example
|
||||
-------
|
||||
>>> sample_rate = 44100
|
||||
>>> audio_data = np.array([0.1, -0.2, 0.3]) # Example audio samples
|
||||
>>> audio_tuple = (sample_rate, audio_data)
|
||||
>>> file_path = audio_to_file(audio_tuple)
|
||||
>>> print(f"Audio saved to: {file_path}")
|
||||
"""
|
||||
bytes_ = audio_to_bytes(audio)
|
||||
with tempfile.NamedTemporaryFile(suffix=".mp3", delete=False) as f:
|
||||
f.write(bytes_)
|
||||
return f.name
|
||||
|
||||
|
||||
def audio_to_float32(
|
||||
audio: tuple[int, NDArray[np.int16 | np.float32]],
|
||||
) -> NDArray[np.float32]:
|
||||
"""
|
||||
Convert an audio tuple containing sample rate (int16) and numpy array data to float32.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
audio : tuple[int, np.ndarray]
|
||||
A tuple containing:
|
||||
- sample_rate (int): The audio sample rate in Hz
|
||||
- data (np.ndarray): The audio data as a numpy array
|
||||
|
||||
Returns
|
||||
-------
|
||||
np.ndarray
|
||||
The audio data as a numpy array with dtype float32
|
||||
|
||||
Example
|
||||
-------
|
||||
>>> sample_rate = 44100
|
||||
>>> audio_data = np.array([0.1, -0.2, 0.3]) # Example audio samples
|
||||
>>> audio_tuple = (sample_rate, audio_data)
|
||||
>>> audio_float32 = audio_to_float32(audio_tuple)
|
||||
"""
|
||||
return audio[1].astype(np.float32) / 32768.0
|
||||
|
||||
|
||||
def audio_to_int16(
|
||||
audio: tuple[int, NDArray[np.int16 | np.float32]],
|
||||
) -> NDArray[np.int16]:
|
||||
"""
|
||||
Convert an audio tuple containing sample rate and numpy array data to int16.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
audio : tuple[int, np.ndarray]
|
||||
A tuple containing:
|
||||
- sample_rate (int): The audio sample rate in Hz
|
||||
- data (np.ndarray): The audio data as a numpy array
|
||||
|
||||
Returns
|
||||
-------
|
||||
np.ndarray
|
||||
The audio data as a numpy array with dtype int16
|
||||
|
||||
Example
|
||||
-------
|
||||
>>> sample_rate = 44100
|
||||
>>> audio_data = np.array([0.1, -0.2, 0.3], dtype=np.float32) # Example audio samples
|
||||
>>> audio_tuple = (sample_rate, audio_data)
|
||||
>>> audio_int16 = audio_to_int16(audio_tuple)
|
||||
"""
|
||||
if audio[1].dtype == np.int16:
|
||||
return audio[1] # type: ignore
|
||||
elif audio[1].dtype == np.float32:
|
||||
# Convert float32 to int16 by scaling to the int16 range
|
||||
return (audio[1] * 32767.0).astype(np.int16)
|
||||
else:
|
||||
raise TypeError(f"Unsupported audio data type: {audio[1].dtype}")
|
||||
|
||||
|
||||
def aggregate_bytes_to_16bit(chunks_iterator):
|
||||
"""
|
||||
Aggregate bytes to 16-bit audio samples.
|
||||
|
||||
This function takes an iterator of chunks and aggregates them into 16-bit audio samples.
|
||||
It handles incomplete samples and combines them with the next chunk.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
chunks_iterator : Iterator[bytes]
|
||||
An iterator of byte chunks to aggregate
|
||||
|
||||
Returns
|
||||
-------
|
||||
Iterator[NDArray[np.int16]]
|
||||
"""
|
||||
leftover = b""
|
||||
for chunk in chunks_iterator:
|
||||
current_bytes = leftover + chunk
|
||||
|
||||
n_complete_samples = len(current_bytes) // 2
|
||||
bytes_to_process = n_complete_samples * 2
|
||||
|
||||
to_process = current_bytes[:bytes_to_process]
|
||||
leftover = current_bytes[bytes_to_process:]
|
||||
|
||||
if to_process:
|
||||
audio_array = np.frombuffer(to_process, dtype=np.int16).reshape(1, -1)
|
||||
yield audio_array
|
||||
|
||||
|
||||
async def async_aggregate_bytes_to_16bit(chunks_iterator):
|
||||
"""
|
||||
Aggregate bytes to 16-bit audio samples.
|
||||
|
||||
This function takes an iterator of chunks and aggregates them into 16-bit audio samples.
|
||||
It handles incomplete samples and combines them with the next chunk.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
chunks_iterator : Iterator[bytes]
|
||||
An iterator of byte chunks to aggregate
|
||||
|
||||
Returns
|
||||
-------
|
||||
Iterator[NDArray[np.int16]]
|
||||
An iterator of 16-bit audio samples
|
||||
"""
|
||||
leftover = b""
|
||||
|
||||
async for chunk in chunks_iterator:
|
||||
current_bytes = leftover + chunk
|
||||
|
||||
n_complete_samples = len(current_bytes) // 2
|
||||
bytes_to_process = n_complete_samples * 2
|
||||
|
||||
to_process = current_bytes[:bytes_to_process]
|
||||
leftover = current_bytes[bytes_to_process:]
|
||||
|
||||
if to_process:
|
||||
audio_array = np.frombuffer(to_process, dtype=np.int16).reshape(1, -1)
|
||||
yield audio_array
|
||||
|
||||
|
||||
def webrtc_error_handler(func):
|
||||
"""Decorator to catch exceptions and raise WebRTCError with stacktrace."""
|
||||
|
||||
@functools.wraps(func)
|
||||
async def async_wrapper(*args, **kwargs):
|
||||
try:
|
||||
return await func(*args, **kwargs)
|
||||
except Exception as e:
|
||||
traceback.print_exc()
|
||||
if isinstance(e, WebRTCError):
|
||||
raise e
|
||||
else:
|
||||
raise WebRTCError(str(e)) from e
|
||||
|
||||
@functools.wraps(func)
|
||||
def sync_wrapper(*args, **kwargs):
|
||||
try:
|
||||
return func(*args, **kwargs)
|
||||
except Exception as e:
|
||||
traceback.print_exc()
|
||||
if isinstance(e, WebRTCError):
|
||||
raise e
|
||||
else:
|
||||
raise WebRTCError(str(e)) from e
|
||||
|
||||
return async_wrapper if inspect.iscoroutinefunction(func) else sync_wrapper
|
||||
|
||||
|
||||
async def wait_for_item(queue: asyncio.Queue, timeout: float = 0.1) -> Any:
|
||||
"""
|
||||
Wait for an item from an asyncio.Queue with a timeout.
|
||||
|
||||
This function attempts to retrieve an item from the queue using asyncio.wait_for.
|
||||
If the timeout is reached, it returns None.
|
||||
|
||||
This is useful to avoid blocking `emit` when the queue is empty.
|
||||
"""
|
||||
|
||||
try:
|
||||
return await asyncio.wait_for(queue.get(), timeout=timeout)
|
||||
except (TimeoutError, asyncio.TimeoutError):
|
||||
return None
|
||||
|
||||
def parse_json_safely(str: str):
|
||||
try:
|
||||
result = json.loads(str)
|
||||
return result, None
|
||||
except json.JSONDecodeError as e:
|
||||
print(f"JSON解析错误: {e.msg}")
|
||||
return None, e
|
||||
370
backend/fastrtc/webrtc.py
Normal file
370
backend/fastrtc/webrtc.py
Normal file
@@ -0,0 +1,370 @@
|
||||
"""gr.WebRTC() component."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
# logging.basicConfig(level=logging.DEBUG)
|
||||
from collections.abc import Callable
|
||||
from typing import (
|
||||
TYPE_CHECKING,
|
||||
Any,
|
||||
Concatenate,
|
||||
Iterable,
|
||||
Literal,
|
||||
ParamSpec,
|
||||
Sequence,
|
||||
TypeVar,
|
||||
cast,
|
||||
)
|
||||
|
||||
from gradio import wasm_utils
|
||||
from gradio.components.base import Component, server
|
||||
from gradio_client import handle_file
|
||||
|
||||
from .tracks import (
|
||||
AudioVideoStreamHandlerImpl,
|
||||
StreamHandler,
|
||||
StreamHandlerBase,
|
||||
StreamHandlerImpl,
|
||||
VideoEventHandler,
|
||||
)
|
||||
from .webrtc_connection_mixin import WebRTCConnectionMixin
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from gradio.blocks import Block
|
||||
from gradio.components import Timer
|
||||
|
||||
if wasm_utils.IS_WASM:
|
||||
raise ValueError("Not supported in gradio-lite!")
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
# For the return type
|
||||
R = TypeVar("R")
|
||||
# For the parameter specification
|
||||
P = ParamSpec("P")
|
||||
|
||||
|
||||
class WebRTC(Component, WebRTCConnectionMixin):
|
||||
"""
|
||||
Creates a video component that can be used to upload/record videos (as an input) or display videos (as an output).
|
||||
For the video to be playable in the browser it must have a compatible container and codec combination. Allowed
|
||||
combinations are .mp4 with h264 codec, .ogg with theora codec, and .webm with vp9 codec. If the component detects
|
||||
that the output video would not be playable in the browser it will attempt to convert it to a playable mp4 video.
|
||||
If the conversion fails, the original video is returned.
|
||||
|
||||
Demos: video_identity_2
|
||||
"""
|
||||
|
||||
EVENTS = ["tick", "state_change"]
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
value: None = None,
|
||||
height: int | str | None = None,
|
||||
width: int | str | None = None,
|
||||
label: str | None = None,
|
||||
every: Timer | float | None = None,
|
||||
inputs: Component | Sequence[Component] | set[Component] | None = None,
|
||||
show_label: bool | None = None,
|
||||
container: bool = True,
|
||||
scale: int | None = None,
|
||||
min_width: int = 160,
|
||||
interactive: bool | None = None,
|
||||
visible: bool = True,
|
||||
elem_id: str | None = None,
|
||||
elem_classes: list[str] | str | None = None,
|
||||
render: bool = True,
|
||||
key: int | str | None = None,
|
||||
mirror_webcam: bool = True,
|
||||
rtc_configuration: dict[str, Any] | None = None,
|
||||
track_constraints: dict[str, Any] | None = None,
|
||||
time_limit: float | None = None,
|
||||
mode: Literal["send-receive", "receive", "send"] = "send-receive",
|
||||
modality: Literal["video", "audio", "audio-video"] = "video",
|
||||
rtp_params: dict[str, Any] | None = None,
|
||||
icon: str | None = None,
|
||||
icon_button_color: str | None = None,
|
||||
pulse_color: str | None = None,
|
||||
icon_radius: int | None = None,
|
||||
button_labels: dict | None = None,
|
||||
video_chat: bool = True,
|
||||
):
|
||||
"""
|
||||
Parameters:
|
||||
value: path or URL for the default value that WebRTC component is going to take. Can also be a tuple consisting of (video filepath, subtitle filepath). If a subtitle file is provided, it should be of type .srt or .vtt. Or can be callable, in which case the function will be called whenever the app loads to set the initial value of the component.
|
||||
format: the file extension with which to save video, such as 'avi' or 'mp4'. This parameter applies both when this component is used as an input to determine which file format to convert user-provided video to, and when this component is used as an output to determine the format of video returned to the user. If None, no file format conversion is done and the video is kept as is. Use 'mp4' to ensure browser playability.
|
||||
height: The height of the component, specified in pixels if a number is passed, or in CSS units if a string is passed. This has no effect on the preprocessed video file, but will affect the displayed video.
|
||||
width: The width of the component, specified in pixels if a number is passed, or in CSS units if a string is passed. This has no effect on the preprocessed video file, but will affect the displayed video.
|
||||
label: the label for this component. Appears above the component and is also used as the header if there are a table of examples for this component. If None and used in a `gr.Interface`, the label will be the name of the parameter this component is assigned to.
|
||||
every: continously calls `value` to recalculate it if `value` is a function (has no effect otherwise). Can provide a Timer whose tick resets `value`, or a float that provides the regular interval for the reset Timer.
|
||||
inputs: components that are used as inputs to calculate `value` if `value` is a function (has no effect otherwise). `value` is recalculated any time the inputs change.
|
||||
show_label: if True, will display label.
|
||||
container: if True, will place the component in a container - providing some extra padding around the border.
|
||||
scale: relative size compared to adjacent Components. For example if Components A and B are in a Row, and A has scale=2, and B has scale=1, A will be twice as wide as B. Should be an integer. scale applies in Rows, and to top-level Components in Blocks where fill_height=True.
|
||||
min_width: minimum pixel width, will wrap if not sufficient screen space to satisfy this value. If a certain scale value results in this Component being narrower than min_width, the min_width parameter will be respected first.
|
||||
interactive: if True, will allow users to upload a video; if False, can only be used to display videos. If not provided, this is inferred based on whether the component is used as an input or output.
|
||||
visible: if False, component will be hidden.
|
||||
elem_id: an optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles.
|
||||
elem_classes: an optional list of strings that are assigned as the classes of this component in the HTML DOM. Can be used for targeting CSS styles.
|
||||
render: if False, component will not render be rendered in the Blocks context. Should be used if the intention is to assign event listeners now but render the component later.
|
||||
key: if assigned, will be used to assume identity across a re-render. Components that have the same key across a re-render will have their value preserved.
|
||||
mirror_webcam: if True webcam will be mirrored. Default is True.
|
||||
rtc_configuration: WebRTC configuration options. See https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/RTCPeerConnection . If running the demo on a remote server, you will need to specify a rtc_configuration. See https://freddyaboulton.github.io/gradio-webrtc/deployment/
|
||||
track_constraints: Media track constraints for WebRTC. For example, to set video height, width use {"width": {"exact": 800}, "height": {"exact": 600}, "aspectRatio": {"exact": 1.33333}}
|
||||
time_limit: Maximum duration in seconds for recording.
|
||||
mode: WebRTC mode - "send-receive", "receive", or "send".
|
||||
modality: Type of media - "video" or "audio".
|
||||
rtp_params: See https://developer.mozilla.org/en-US/docs/Web/API/RTCRtpSender/setParameters. If you are changing the video resolution, you can set this to {"degradationPreference": "maintain-framerate"} to keep the frame rate consistent.
|
||||
icon: Icon to display on the button instead of the wave animation. The icon should be a path/url to a .svg/.png/.jpeg file.
|
||||
icon_button_color: Color of the icon button. Default is var(--color-accent) of the demo theme.
|
||||
pulse_color: Color of the pulse animation. Default is var(--color-accent) of the demo theme.
|
||||
button_labels: Text to display on the audio or video start, stop, waiting buttons. Dict with keys "start", "stop", "waiting" mapping to the text to display on the buttons.
|
||||
icon_radius: Border radius of the icon button expressed as a percentage of the button size. Default is 50%
|
||||
"""
|
||||
WebRTCConnectionMixin.__init__(self)
|
||||
self.time_limit = time_limit
|
||||
self.height = height
|
||||
self.width = width
|
||||
self.mirror_webcam = mirror_webcam
|
||||
self.concurrency_limit = 1
|
||||
self.rtc_configuration = rtc_configuration
|
||||
self.mode = mode
|
||||
self.modality = modality
|
||||
self.icon_button_color = icon_button_color
|
||||
self.icon_radius = icon_radius
|
||||
self.pulse_color = pulse_color
|
||||
self.rtp_params = rtp_params or {}
|
||||
self.video_chat = video_chat
|
||||
self.button_labels = {
|
||||
"start": "",
|
||||
"stop": "",
|
||||
"waiting": "",
|
||||
**(button_labels or {}),
|
||||
}
|
||||
if track_constraints is None and modality == "audio":
|
||||
track_constraints = {
|
||||
"echoCancellation": True,
|
||||
"noiseSuppression": {"exact": True},
|
||||
"autoGainControl": {"exact": True},
|
||||
"sampleRate": {"ideal": 24000},
|
||||
"sampleSize": {"ideal": 16},
|
||||
"channelCount": {"exact": 1},
|
||||
}
|
||||
if track_constraints is None and modality == "video":
|
||||
track_constraints = {
|
||||
"facingMode": "user",
|
||||
"width": {"ideal": 500},
|
||||
"height": {"ideal": 500},
|
||||
"frameRate": {"ideal": 30},
|
||||
}
|
||||
if track_constraints is None and modality == "audio-video":
|
||||
track_constraints = {
|
||||
"video": {
|
||||
"facingMode": "user",
|
||||
"width": {"ideal": 500},
|
||||
"height": {"ideal": 500},
|
||||
"frameRate": {"ideal": 30},
|
||||
},
|
||||
"audio": {
|
||||
"echoCancellation": True,
|
||||
"noiseSuppression": {"exact": True},
|
||||
"autoGainControl": {"exact": True},
|
||||
"sampleRate": {"ideal": 24000},
|
||||
"sampleSize": {"ideal": 16},
|
||||
"channelCount": {"exact": 1},
|
||||
},
|
||||
}
|
||||
self.track_constraints = track_constraints
|
||||
self.event_handler: Callable | StreamHandler | None = None
|
||||
super().__init__(
|
||||
label=label,
|
||||
every=every,
|
||||
inputs=inputs,
|
||||
show_label=show_label,
|
||||
container=container,
|
||||
scale=scale,
|
||||
min_width=min_width,
|
||||
interactive=interactive,
|
||||
visible=visible,
|
||||
elem_id=elem_id,
|
||||
elem_classes=elem_classes,
|
||||
render=render,
|
||||
key=key,
|
||||
value=value,
|
||||
)
|
||||
# need to do this here otherwise the proxy_url is not set
|
||||
self.icon = (
|
||||
icon if not icon else cast(dict, self.serve_static_file(icon)).get("url")
|
||||
)
|
||||
|
||||
def preprocess(self, payload: str) -> str:
|
||||
"""
|
||||
Parameters:
|
||||
payload: An instance of VideoData containing the video and subtitle files.
|
||||
Returns:
|
||||
Passes the uploaded video as a `str` filepath or URL whose extension can be modified by `format`.
|
||||
"""
|
||||
return payload
|
||||
|
||||
def postprocess(self, value: Any) -> str:
|
||||
"""
|
||||
Parameters:
|
||||
value: Expects a {str} or {pathlib.Path} filepath to a video which is displayed, or a {Tuple[str | pathlib.Path, str | pathlib.Path | None]} where the first element is a filepath to a video and the second element is an optional filepath to a subtitle file.
|
||||
Returns:
|
||||
VideoData object containing the video and subtitle files.
|
||||
"""
|
||||
return value
|
||||
|
||||
def on_additional_outputs(
|
||||
self,
|
||||
fn: Callable[Concatenate[P], R],
|
||||
inputs: Block | Sequence[Block] | set[Block] | None = None,
|
||||
outputs: Block | Sequence[Block] | set[Block] | None = None,
|
||||
js: str | None = None,
|
||||
concurrency_limit: int | None | Literal["default"] = "default",
|
||||
concurrency_id: str | None = None,
|
||||
show_progress: Literal["full", "minimal", "hidden"] = "full",
|
||||
queue: bool = True,
|
||||
):
|
||||
inputs = inputs or []
|
||||
if inputs and not isinstance(inputs, Iterable):
|
||||
inputs = [inputs]
|
||||
inputs = list(inputs)
|
||||
|
||||
async def handler(webrtc_id: str, *args):
|
||||
async for next_outputs in self.output_stream(webrtc_id):
|
||||
yield fn(*args, *next_outputs.args) # type: ignore
|
||||
|
||||
return self.state_change( # type: ignore
|
||||
fn=handler,
|
||||
inputs=[self] + cast(list, inputs),
|
||||
outputs=outputs,
|
||||
js=js,
|
||||
concurrency_limit=concurrency_limit,
|
||||
concurrency_id=concurrency_id,
|
||||
show_progress="minimal",
|
||||
queue=queue,
|
||||
trigger_mode="once",
|
||||
)
|
||||
|
||||
def stream(
|
||||
self,
|
||||
fn: (
|
||||
Callable[..., Any]
|
||||
| StreamHandlerImpl
|
||||
| AudioVideoStreamHandlerImpl
|
||||
| VideoEventHandler
|
||||
| None
|
||||
) = None,
|
||||
inputs: Block | Sequence[Block] | set[Block] | None = None,
|
||||
outputs: Block | Sequence[Block] | set[Block] | None = None,
|
||||
js: str | None = None,
|
||||
concurrency_limit: int | None | Literal["default"] = "default",
|
||||
concurrency_id: str | None = None,
|
||||
time_limit: float | None = None,
|
||||
trigger: Callable | None = None,
|
||||
):
|
||||
from gradio.blocks import Block
|
||||
|
||||
if inputs is None:
|
||||
inputs = []
|
||||
if outputs is None:
|
||||
outputs = []
|
||||
if isinstance(inputs, Block):
|
||||
inputs = [inputs]
|
||||
if isinstance(outputs, Block):
|
||||
outputs = [outputs]
|
||||
|
||||
self.concurrency_limit = cast(
|
||||
int, (1 if concurrency_limit in ["default", None] else concurrency_limit)
|
||||
)
|
||||
self.event_handler = fn # type: ignore
|
||||
self.time_limit = time_limit
|
||||
|
||||
if (
|
||||
self.mode == "send-receive"
|
||||
and self.modality in ["audio", "audio-video"]
|
||||
and not isinstance(self.event_handler, StreamHandlerBase)
|
||||
):
|
||||
raise ValueError(
|
||||
"In the send-receive mode for audio, the event handler must be an instance of StreamHandlerBase."
|
||||
)
|
||||
|
||||
if self.mode == "send-receive" or self.mode == "send":
|
||||
if cast(list[Block], inputs)[0] != self:
|
||||
raise ValueError(
|
||||
"In the webrtc stream event, the first input component must be the WebRTC component."
|
||||
)
|
||||
|
||||
if (
|
||||
len(cast(list[Block], outputs)) != 1
|
||||
and cast(list[Block], outputs)[0] != self
|
||||
):
|
||||
raise ValueError(
|
||||
"In the webrtc stream event, the only output component must be the WebRTC component."
|
||||
)
|
||||
for input_component in inputs[1:]: # type: ignore
|
||||
if hasattr(input_component, "change"):
|
||||
input_component.change( # type: ignore
|
||||
self.set_input,
|
||||
inputs=inputs,
|
||||
outputs=None,
|
||||
concurrency_id=concurrency_id,
|
||||
concurrency_limit=None,
|
||||
time_limit=None,
|
||||
js=js,
|
||||
)
|
||||
return self.tick( # type: ignore
|
||||
self.set_input,
|
||||
inputs=inputs,
|
||||
outputs=None,
|
||||
concurrency_id=concurrency_id,
|
||||
concurrency_limit=None,
|
||||
time_limit=None,
|
||||
js=js,
|
||||
)
|
||||
elif self.mode == "receive":
|
||||
if isinstance(inputs, list) and self in cast(list[Block], inputs):
|
||||
raise ValueError(
|
||||
"In the receive mode stream event, the WebRTC component cannot be an input."
|
||||
)
|
||||
if (
|
||||
len(cast(list[Block], outputs)) != 1
|
||||
and cast(list[Block], outputs)[0] != self
|
||||
):
|
||||
raise ValueError(
|
||||
"In the receive mode stream, the only output component must be the WebRTC component."
|
||||
)
|
||||
if trigger is None:
|
||||
raise ValueError(
|
||||
"In the receive mode stream event, the trigger parameter must be provided"
|
||||
)
|
||||
trigger(lambda: "start_webrtc_stream", inputs=None, outputs=self)
|
||||
self.tick( # type: ignore
|
||||
self.set_input,
|
||||
inputs=[self] + list(inputs),
|
||||
outputs=None,
|
||||
concurrency_id=concurrency_id,
|
||||
)
|
||||
|
||||
@server
|
||||
async def offer(self, body):
|
||||
return await self.handle_offer(
|
||||
body, self.set_additional_outputs(body["webrtc_id"])
|
||||
)
|
||||
|
||||
def example_payload(self) -> Any:
|
||||
return {
|
||||
"video": handle_file(
|
||||
"https://github.com/gradio-app/gradio/raw/main/demo/video_component/files/world.mp4"
|
||||
),
|
||||
}
|
||||
|
||||
def example_value(self) -> Any:
|
||||
return "https://github.com/gradio-app/gradio/raw/main/demo/video_component/files/world.mp4"
|
||||
|
||||
def api_info(self) -> Any:
|
||||
return {"type": "number"}
|
||||
311
backend/fastrtc/webrtc_connection_mixin.py
Normal file
311
backend/fastrtc/webrtc_connection_mixin.py
Normal file
@@ -0,0 +1,311 @@
|
||||
"""Mixin for handling WebRTC connections."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import asyncio
|
||||
import inspect
|
||||
import logging
|
||||
from collections import defaultdict
|
||||
from collections.abc import Callable
|
||||
from dataclasses import dataclass, field
|
||||
from typing import (
|
||||
AsyncGenerator,
|
||||
Literal,
|
||||
ParamSpec,
|
||||
TypeVar,
|
||||
cast,
|
||||
)
|
||||
|
||||
from aiortc import (
|
||||
RTCPeerConnection,
|
||||
RTCSessionDescription,
|
||||
)
|
||||
from aiortc.contrib.media import MediaRelay # type: ignore
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
from fastrtc.tracks import (
|
||||
AudioCallback,
|
||||
HandlerType,
|
||||
ServerToClientAudio,
|
||||
ServerToClientVideo,
|
||||
StreamHandlerBase,
|
||||
StreamHandlerImpl,
|
||||
VideoCallback,
|
||||
VideoStreamHandler,
|
||||
)
|
||||
from fastrtc.utils import (
|
||||
AdditionalOutputs,
|
||||
Message,
|
||||
create_message,
|
||||
parse_json_safely,
|
||||
webrtc_error_handler,
|
||||
)
|
||||
|
||||
Track = (
|
||||
VideoCallback
|
||||
| VideoStreamHandler
|
||||
| AudioCallback
|
||||
| ServerToClientAudio
|
||||
| ServerToClientVideo
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
logger.setLevel(logging.DEBUG)
|
||||
|
||||
|
||||
# For the return type
|
||||
R = TypeVar("R")
|
||||
# For the parameter specification
|
||||
P = ParamSpec("P")
|
||||
|
||||
|
||||
@dataclass
|
||||
class OutputQueue:
|
||||
queue: asyncio.Queue[AdditionalOutputs] = field(default_factory=asyncio.Queue)
|
||||
quit: asyncio.Event = field(default_factory=asyncio.Event)
|
||||
|
||||
|
||||
class WebRTCConnectionMixin:
|
||||
def __init__(self):
|
||||
self.pcs = set([])
|
||||
self.relay = MediaRelay()
|
||||
self.connections = defaultdict(list)
|
||||
self.data_channels = {}
|
||||
self.additional_outputs = defaultdict(OutputQueue)
|
||||
self.handlers = {}
|
||||
self.connection_timeouts = defaultdict(asyncio.Event)
|
||||
# These attributes should be set by subclasses:
|
||||
self.concurrency_limit: int | float | None
|
||||
self.event_handler: HandlerType | None
|
||||
self.time_limit: float | None
|
||||
self.modality: Literal["video", "audio", "audio-video"]
|
||||
self.mode: Literal["send", "receive", "send-receive"]
|
||||
|
||||
@staticmethod
|
||||
async def wait_for_time_limit(pc: RTCPeerConnection, time_limit: float):
|
||||
await asyncio.sleep(time_limit)
|
||||
await pc.close()
|
||||
|
||||
async def connection_timeout(
|
||||
self,
|
||||
pc: RTCPeerConnection,
|
||||
webrtc_id: str,
|
||||
time_limit: float,
|
||||
):
|
||||
try:
|
||||
await asyncio.wait_for(
|
||||
self.connection_timeouts[webrtc_id].wait(), time_limit
|
||||
)
|
||||
except (asyncio.TimeoutError, TimeoutError):
|
||||
await pc.close()
|
||||
self.connection_timeouts[webrtc_id].clear()
|
||||
self.clean_up(webrtc_id)
|
||||
|
||||
def clean_up(self, webrtc_id: str):
|
||||
self.handlers.pop(webrtc_id, None)
|
||||
self.connection_timeouts.pop(webrtc_id, None)
|
||||
connection = self.connections.pop(webrtc_id, [])
|
||||
for conn in connection:
|
||||
if isinstance(conn, AudioCallback):
|
||||
if inspect.iscoroutinefunction(conn.event_handler.shutdown):
|
||||
asyncio.create_task(conn.event_handler.shutdown())
|
||||
conn.event_handler.reset()
|
||||
else:
|
||||
conn.event_handler.shutdown()
|
||||
conn.event_handler.reset()
|
||||
output = self.additional_outputs.pop(webrtc_id, None)
|
||||
if output:
|
||||
logger.debug("setting quit for webrtc id %s", webrtc_id)
|
||||
output.quit.set()
|
||||
self.data_channels.pop(webrtc_id, None)
|
||||
return connection
|
||||
|
||||
def set_input(self, webrtc_id: str, *args):
|
||||
if webrtc_id in self.connections:
|
||||
for conn in self.connections[webrtc_id]:
|
||||
conn.set_args(list(args))
|
||||
|
||||
async def output_stream(
|
||||
self, webrtc_id: str
|
||||
) -> AsyncGenerator[AdditionalOutputs, None]:
|
||||
outputs = self.additional_outputs[webrtc_id]
|
||||
while not outputs.quit.is_set():
|
||||
try:
|
||||
yield await asyncio.wait_for(outputs.queue.get(), 10)
|
||||
except (asyncio.TimeoutError, TimeoutError):
|
||||
logger.debug("Timeout waiting for output")
|
||||
|
||||
async def fetch_latest_output(self, webrtc_id: str) -> AdditionalOutputs:
|
||||
outputs = self.additional_outputs[webrtc_id]
|
||||
return await asyncio.wait_for(outputs.queue.get(), 10)
|
||||
|
||||
def set_additional_outputs(
|
||||
self, webrtc_id: str
|
||||
) -> Callable[[AdditionalOutputs], None]:
|
||||
def set_outputs(outputs: AdditionalOutputs):
|
||||
self.additional_outputs[webrtc_id].queue.put_nowait(outputs)
|
||||
|
||||
return set_outputs
|
||||
|
||||
async def handle_offer(self, body, set_outputs):
|
||||
logger.debug("Starting to handle offer")
|
||||
logger.debug("Offer body %s", body)
|
||||
if len(self.connections) >= cast(int, self.concurrency_limit):
|
||||
return JSONResponse(
|
||||
status_code=200,
|
||||
content={
|
||||
"status": "failed",
|
||||
"meta": {
|
||||
"error": "concurrency_limit_reached",
|
||||
"limit": self.concurrency_limit,
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
offer = RTCSessionDescription(sdp=body["sdp"], type=body["type"])
|
||||
|
||||
pc = RTCPeerConnection()
|
||||
self.pcs.add(pc)
|
||||
|
||||
if isinstance(self.event_handler, StreamHandlerBase):
|
||||
handler = self.event_handler.copy()
|
||||
handler.emit = webrtc_error_handler(handler.emit) # type: ignore
|
||||
handler.receive = webrtc_error_handler(handler.receive) # type: ignore
|
||||
handler.start_up = webrtc_error_handler(handler.start_up) # type: ignore
|
||||
handler.shutdown = webrtc_error_handler(handler.shutdown) # type: ignore
|
||||
if hasattr(handler, "video_receive"):
|
||||
handler.video_receive = webrtc_error_handler(handler.video_receive) # type: ignore
|
||||
if hasattr(handler, "video_emit"):
|
||||
handler.video_emit = webrtc_error_handler(handler.video_emit) # type: ignore
|
||||
if hasattr(handler, "on_chat_datachannel"):
|
||||
handler.on_chat_datachannel = webrtc_error_handler(handler.on_chat_datachannel) # type: ignore
|
||||
else:
|
||||
handler = webrtc_error_handler(cast(Callable, self.event_handler))
|
||||
|
||||
self.handlers[body["webrtc_id"]] = handler
|
||||
|
||||
@pc.on("iceconnectionstatechange")
|
||||
async def on_iceconnectionstatechange():
|
||||
logger.debug("ICE connection state change %s", pc.iceConnectionState)
|
||||
if pc.iceConnectionState == "failed":
|
||||
await pc.close()
|
||||
self.connections.pop(body["webrtc_id"], None)
|
||||
self.pcs.discard(pc)
|
||||
|
||||
@pc.on("connectionstatechange")
|
||||
async def _():
|
||||
print("pc.connectionState %s", pc.connectionState)
|
||||
logger.debug("pc.connectionState %s", pc.connectionState)
|
||||
if pc.connectionState in ["failed", "closed"]:
|
||||
await pc.close()
|
||||
connection = self.clean_up(body["webrtc_id"])
|
||||
if connection:
|
||||
for conn in connection:
|
||||
conn.stop()
|
||||
self.pcs.discard(pc)
|
||||
if pc.connectionState == "connected":
|
||||
self.connection_timeouts[body["webrtc_id"]].set()
|
||||
if self.time_limit is not None:
|
||||
asyncio.create_task(self.wait_for_time_limit(pc, self.time_limit))
|
||||
|
||||
@pc.on("track")
|
||||
def _(track):
|
||||
relay = MediaRelay()
|
||||
handler = self.handlers[body["webrtc_id"]]
|
||||
if self.modality == "video" and track.kind == "video":
|
||||
cb = VideoCallback(
|
||||
relay.subscribe(track),
|
||||
event_handler=cast(Callable, handler),
|
||||
set_additional_outputs=set_outputs,
|
||||
mode=cast(Literal["send", "send-receive"], self.mode),
|
||||
)
|
||||
elif self.modality == "audio-video" and track.kind == "video":
|
||||
cb = VideoStreamHandler(
|
||||
relay.subscribe(track),
|
||||
event_handler=handler, # type: ignore
|
||||
set_additional_outputs=set_outputs,
|
||||
)
|
||||
elif self.modality in ["audio", "audio-video"] and track.kind == "audio":
|
||||
eh = cast(StreamHandlerImpl, handler)
|
||||
eh._loop = asyncio.get_running_loop()
|
||||
cb = AudioCallback(
|
||||
relay.subscribe(track),
|
||||
event_handler=eh,
|
||||
set_additional_outputs=set_outputs,
|
||||
)
|
||||
else:
|
||||
raise ValueError("Modality must be either video, audio, or audio-video")
|
||||
if body["webrtc_id"] not in self.connections:
|
||||
self.connections[body["webrtc_id"]] = []
|
||||
|
||||
self.connections[body["webrtc_id"]].append(cb)
|
||||
if body["webrtc_id"] in self.data_channels:
|
||||
for conn in self.connections[body["webrtc_id"]]:
|
||||
conn.set_channel(self.data_channels[body["webrtc_id"]])
|
||||
if self.mode == "send-receive":
|
||||
logger.debug("Adding track to peer connection %s", cb)
|
||||
pc.addTrack(cb)
|
||||
elif self.mode == "send":
|
||||
asyncio.create_task(cast(AudioCallback | VideoCallback, cb).start())
|
||||
|
||||
if self.mode == "receive":
|
||||
if self.modality == "video":
|
||||
cb = ServerToClientVideo(
|
||||
cast(Callable, self.event_handler),
|
||||
set_additional_outputs=set_outputs,
|
||||
)
|
||||
elif self.modality == "audio":
|
||||
cb = ServerToClientAudio(
|
||||
cast(Callable, self.event_handler),
|
||||
set_additional_outputs=set_outputs,
|
||||
)
|
||||
else:
|
||||
raise ValueError("Modality must be either video or audio")
|
||||
|
||||
logger.debug("Adding track to peer connection %s", cb)
|
||||
pc.addTrack(cb)
|
||||
self.connections[body["webrtc_id"]].append(cb)
|
||||
cb.on("ended", lambda: self.clean_up(body["webrtc_id"]))
|
||||
|
||||
@pc.on("datachannel")
|
||||
def _(channel):
|
||||
logger.debug(f"Data channel established: {channel.label}")
|
||||
|
||||
self.data_channels[body["webrtc_id"]] = channel
|
||||
|
||||
async def set_channel(webrtc_id: str):
|
||||
while not self.connections.get(webrtc_id):
|
||||
await asyncio.sleep(0.05)
|
||||
logger.debug("setting channel for webrtc id %s", webrtc_id)
|
||||
for conn in self.connections[webrtc_id]:
|
||||
conn.set_channel(channel)
|
||||
|
||||
asyncio.create_task(set_channel(body["webrtc_id"]))
|
||||
|
||||
@channel.on("message")
|
||||
def _(message):
|
||||
logger.debug(f"Received message: {message}")
|
||||
if channel.readyState == "open":
|
||||
msg_dict,error = parse_json_safely(message)
|
||||
if(error is None and msg_dict['type'] in ['chat','stop_chat']):
|
||||
msg_dict = cast(Message, json.loads(message))
|
||||
asyncio.create_task(self.handlers[body["webrtc_id"]].on_chat_datachannel(msg_dict,channel))
|
||||
else:
|
||||
channel.send(
|
||||
create_message("log", data=f"Server received: {message}")
|
||||
)
|
||||
|
||||
# handle offer
|
||||
await pc.setRemoteDescription(offer)
|
||||
asyncio.create_task(self.connection_timeout(pc, body["webrtc_id"], 30))
|
||||
# send answer
|
||||
answer = await pc.createAnswer()
|
||||
await pc.setLocalDescription(answer) # type: ignore
|
||||
logger.debug("done handling offer about to return")
|
||||
await asyncio.sleep(0.1)
|
||||
|
||||
return {
|
||||
"sdp": pc.localDescription.sdp,
|
||||
"type": pc.localDescription.type,
|
||||
}
|
||||
215
backend/fastrtc/websocket.py
Normal file
215
backend/fastrtc/websocket.py
Normal file
@@ -0,0 +1,215 @@
|
||||
import asyncio
|
||||
import audioop
|
||||
import base64
|
||||
import logging
|
||||
from typing import Any, Awaitable, Callable, Optional, cast
|
||||
|
||||
import anyio
|
||||
import librosa
|
||||
import numpy as np
|
||||
from fastapi import WebSocket
|
||||
|
||||
from .tracks import AsyncStreamHandler, StreamHandlerImpl
|
||||
from .utils import AdditionalOutputs, DataChannel, split_output
|
||||
|
||||
|
||||
class WebSocketDataChannel(DataChannel):
|
||||
def __init__(self, websocket: WebSocket, loop: asyncio.AbstractEventLoop):
|
||||
self.websocket = websocket
|
||||
self.loop = loop
|
||||
|
||||
def send(self, message: str) -> None:
|
||||
asyncio.run_coroutine_threadsafe(self.websocket.send_text(message), self.loop)
|
||||
|
||||
|
||||
logger = logging.getLogger(__file__)
|
||||
|
||||
|
||||
def convert_to_mulaw(
|
||||
audio_data: np.ndarray, original_rate: int, target_rate: int
|
||||
) -> bytes:
|
||||
"""Convert audio data to 8kHz mu-law format"""
|
||||
|
||||
if audio_data.dtype != np.float32:
|
||||
audio_data = audio_data.astype(np.float32) / 32768.0
|
||||
|
||||
if original_rate != target_rate:
|
||||
audio_data = librosa.resample(audio_data, orig_sr=original_rate, target_sr=8000)
|
||||
|
||||
audio_data = (audio_data * 32768).astype(np.int16)
|
||||
|
||||
return audioop.lin2ulaw(audio_data, 2) # type: ignore
|
||||
|
||||
|
||||
run_sync = anyio.to_thread.run_sync # type: ignore
|
||||
|
||||
|
||||
class WebSocketHandler:
|
||||
def __init__(
|
||||
self,
|
||||
stream_handler: StreamHandlerImpl,
|
||||
set_handler: Callable[[str, "WebSocketHandler"], Awaitable[None]],
|
||||
clean_up: Callable[[str], None],
|
||||
additional_outputs_factory: Callable[
|
||||
[str], Callable[[AdditionalOutputs], None]
|
||||
],
|
||||
):
|
||||
self.stream_handler = stream_handler
|
||||
self.stream_handler._clear_queue = self._clear_queue
|
||||
self.websocket: Optional[WebSocket] = None
|
||||
self._emit_task: Optional[asyncio.Task] = None
|
||||
self.stream_id: Optional[str] = None
|
||||
self.set_additional_outputs_factory = additional_outputs_factory
|
||||
self.set_additional_outputs: Callable[[AdditionalOutputs], None]
|
||||
self.set_handler = set_handler
|
||||
self.quit = asyncio.Event()
|
||||
self.clean_up = clean_up
|
||||
self.queue = asyncio.Queue()
|
||||
|
||||
def _clear_queue(self):
|
||||
old_queue = self.queue
|
||||
self.queue = asyncio.Queue()
|
||||
logger.debug("clearing queue")
|
||||
i = 0
|
||||
while not old_queue.empty():
|
||||
try:
|
||||
old_queue.get_nowait()
|
||||
i += 1
|
||||
except asyncio.QueueEmpty:
|
||||
break
|
||||
logger.debug("popped %d items from queue", i)
|
||||
|
||||
def set_args(self, args: list[Any]):
|
||||
self.stream_handler.set_args(args)
|
||||
|
||||
async def handle_websocket(self, websocket: WebSocket):
|
||||
await websocket.accept()
|
||||
loop = asyncio.get_running_loop()
|
||||
self.loop = loop
|
||||
self.websocket = websocket
|
||||
self.data_channel = WebSocketDataChannel(websocket, loop)
|
||||
self.stream_handler._loop = loop
|
||||
self.stream_handler.set_channel(self.data_channel)
|
||||
self._emit_task = asyncio.create_task(self._emit_loop())
|
||||
self._emit_to_queue_task = asyncio.create_task(self._emit_to_queue())
|
||||
if isinstance(self.stream_handler, AsyncStreamHandler):
|
||||
start_up = self.stream_handler.start_up()
|
||||
else:
|
||||
start_up = anyio.to_thread.run_sync(self.stream_handler.start_up) # type: ignore
|
||||
|
||||
self.start_up_task = asyncio.create_task(start_up)
|
||||
try:
|
||||
while not self.quit.is_set():
|
||||
message = await websocket.receive_json()
|
||||
|
||||
if message["event"] == "media":
|
||||
audio_payload = base64.b64decode(message["media"]["payload"])
|
||||
|
||||
audio_array = np.frombuffer(
|
||||
audioop.ulaw2lin(audio_payload, 2), dtype=np.int16
|
||||
)
|
||||
|
||||
if self.stream_handler.input_sample_rate != 8000:
|
||||
audio_array = audio_array.astype(np.float32) / 32768.0
|
||||
audio_array = librosa.resample(
|
||||
audio_array,
|
||||
orig_sr=8000,
|
||||
target_sr=self.stream_handler.input_sample_rate,
|
||||
)
|
||||
audio_array = (audio_array * 32768).astype(np.int16)
|
||||
if isinstance(self.stream_handler, AsyncStreamHandler):
|
||||
await self.stream_handler.receive(
|
||||
(self.stream_handler.input_sample_rate, audio_array)
|
||||
)
|
||||
else:
|
||||
await run_sync(
|
||||
self.stream_handler.receive,
|
||||
(self.stream_handler.input_sample_rate, audio_array),
|
||||
)
|
||||
|
||||
elif message["event"] == "start":
|
||||
if self.stream_handler.phone_mode:
|
||||
self.stream_id = cast(str, message["streamSid"])
|
||||
else:
|
||||
self.stream_id = cast(str, message["websocket_id"])
|
||||
self.set_additional_outputs = self.set_additional_outputs_factory(
|
||||
self.stream_id
|
||||
)
|
||||
await self.set_handler(self.stream_id, self)
|
||||
elif message["event"] == "stop":
|
||||
self.quit.set()
|
||||
self.clean_up(cast(str, self.stream_id))
|
||||
return
|
||||
elif message["event"] == "ping":
|
||||
await websocket.send_json({"event": "pong"})
|
||||
|
||||
except Exception as e:
|
||||
print(e)
|
||||
import traceback
|
||||
|
||||
traceback.print_exc()
|
||||
logger.debug("Error in websocket handler %s", e)
|
||||
finally:
|
||||
if self._emit_task:
|
||||
self._emit_task.cancel()
|
||||
if self._emit_to_queue_task:
|
||||
self._emit_to_queue_task.cancel()
|
||||
if self.start_up_task:
|
||||
self.start_up_task.cancel()
|
||||
await websocket.close()
|
||||
|
||||
async def _emit_to_queue(self):
|
||||
try:
|
||||
while not self.quit.is_set():
|
||||
if isinstance(self.stream_handler, AsyncStreamHandler):
|
||||
output = await self.stream_handler.emit()
|
||||
else:
|
||||
output = await run_sync(self.stream_handler.emit)
|
||||
self.queue.put_nowait(output)
|
||||
except asyncio.CancelledError:
|
||||
logger.debug("Emit loop cancelled")
|
||||
except Exception as e:
|
||||
import traceback
|
||||
|
||||
traceback.print_exc()
|
||||
logger.debug("Error in emit loop: %s", e)
|
||||
|
||||
async def _emit_loop(self):
|
||||
try:
|
||||
while not self.quit.is_set():
|
||||
output = await self.queue.get()
|
||||
|
||||
if output is not None:
|
||||
frame, output = split_output(output)
|
||||
if output is not None:
|
||||
self.set_additional_outputs(output)
|
||||
if not isinstance(frame, tuple):
|
||||
continue
|
||||
target_rate = (
|
||||
self.stream_handler.output_sample_rate
|
||||
if not self.stream_handler.phone_mode
|
||||
else 8000
|
||||
)
|
||||
mulaw_audio = convert_to_mulaw(
|
||||
frame[1], frame[0], target_rate=target_rate
|
||||
)
|
||||
audio_payload = base64.b64encode(mulaw_audio).decode("utf-8")
|
||||
|
||||
if self.websocket and self.stream_id:
|
||||
payload = {
|
||||
"event": "media",
|
||||
"media": {"payload": audio_payload},
|
||||
}
|
||||
if self.stream_handler.phone_mode:
|
||||
payload["streamSid"] = self.stream_id
|
||||
await self.websocket.send_json(payload)
|
||||
|
||||
await asyncio.sleep(0.02)
|
||||
|
||||
except asyncio.CancelledError:
|
||||
logger.debug("Emit loop cancelled")
|
||||
except Exception as e:
|
||||
import traceback
|
||||
|
||||
traceback.print_exc()
|
||||
logger.debug("Error in emit loop: %s", e)
|
||||
Reference in New Issue
Block a user