diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index f58f8c4..b50ec1a 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -3,8 +3,16 @@ on: push: branches: - main + pull_request: + branches: + - main + permissions: contents: write + pull-requests: write + deployments: write + pages: write + jobs: deploy: runs-on: ubuntu-latest @@ -17,12 +25,26 @@ jobs: - uses: actions/setup-python@v5 with: python-version: 3.x - - run: echo "cache_id=$(date --utc '+%V')" >> $GITHUB_ENV + - run: echo "cache_id=$(date --utc '+%V')" >> $GITHUB_ENV - uses: actions/cache@v4 with: key: mkdocs-material-${{ env.cache_id }} path: .cache restore-keys: | mkdocs-material- - - run: pip install mkdocs-material - - run: mkdocs gh-deploy --force \ No newline at end of file + - run: pip install mkdocs-material + - name: Build docs + run: mkdocs build + + - name: Deploy to GH Pages (main) + if: github.event_name == 'push' + run: mkdocs gh-deploy --force + + - name: Deploy PR Preview + if: github.event_name == 'pull_request' + uses: rossjrw/pr-preview-action@v1 + with: + source-dir: ./site + preview-branch: gh-pages + umbrella-dir: pr-preview + action: auto diff --git a/.gitignore b/.gitignore index a9ed25c..73403da 100644 --- a/.gitignore +++ b/.gitignore @@ -13,6 +13,12 @@ node_modules backend/**/templates/ demo/MobileNetSSD_deploy.caffemodel demo/MobileNetSSD_deploy.prototxt.txt +demo/scratch +.gradio +.vscode .DS_Store test/ -.env \ No newline at end of file +.env + +.vscode/* +.venv* diff --git a/CNAME b/CNAME new file mode 100644 index 0000000..a35e970 --- /dev/null +++ b/CNAME @@ -0,0 +1 @@ +fastrtc.org \ No newline at end of file diff --git a/README.md b/README.md index f263bea..da83ee8 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,13 @@ -

Gradio WebRTC ⚡️

+
+

FastRTC

+ FastRTC Logo +
-Static Badge -Static Badge -Static Badge +Static Badge +Static Badge
中文|English @@ -24,12 +28,12 @@ gradio cc build --no-generate-docs ``` ```bash -pip install dist/gradio_webrtc-0.0.30.dev0-py3-none-any.whl +pip install dist/fastrtc-0.0.15.dev0-py3-none-any.whl ``` ## Docs -https://freddyaboulton.github.io/gradio-webrtc/ +[https://fastrtc.org](https://fastrtc.org) ## Examples diff --git a/README_EN.md b/README_EN.md new file mode 100644 index 0000000..8e0f960 --- /dev/null +++ b/README_EN.md @@ -0,0 +1,182 @@ +

Gradio WebRTC ⚡️

+ +
+Static Badge +Static Badge +Static Badge +
+
+中文|English +
+This repository is forked from the original gradio_webrtc repository, primarily adding `video_chat` as an allowed parameter to be enabled by default. This mode is consistent with the behavior of the original `modality="audio-video"` and `mode="send-receive"`, but the UI has been rewritten to include more interactive capabilities (more microphone controls, and the ability to display local video information). The visual presentation is shown below. + +If `video_chat` is manually set to `False`, its usage is consistent with the original repository https://freddyaboulton.github.io/gradio-webrtc/ + +![picture-in-picture](docs/image.png) +![side-by-side](docs/image2.png) + +## Installation + +```bash +gradio cc install +gradio cc build --no-generate-docs +``` + +```bash +pip install dist/gradio_webrtc-0.0.30.dev0-py3-none-any.whl +``` + +## Docs + +https://freddyaboulton.github.io/gradio-webrtc/ + +## Examples + +When using it, you need a handler as the entry parameter of the component and implement code similar to the following: + +```python +import asyncio +import base64 +from io import BytesIO + +import gradio as gr +import numpy as np +from gradio_webrtc import ( + AsyncAudioVideoStreamHandler, + WebRTC, + VideoEmitType, + AudioEmitType, +) +from PIL import Image + + +def encode_audio(data: np.ndarray) -> dict: + """Encode Audio data to send to the server""" + return {"mime_type": "audio/pcm", "data": base64.b64encode(data.tobytes()).decode("UTF-8")} + + +def encode_image(data: np.ndarray) -> dict: + with BytesIO() as output_bytes: + pil_image = Image.fromarray(data) + pil_image.save(output_bytes, "JPEG") + bytes_data = output_bytes.getvalue() + base64_str = str(base64.b64encode(bytes_data), "utf-8") + return {"mime_type": "image/jpeg", "data": base64_str} + + +class VideoChatHandler(AsyncAudioVideoStreamHandler): + def __init__( + self, expected_layout="mono", output_sample_rate=24000, output_frame_size=480 + ) -> None: + super().__init__( + expected_layout, + output_sample_rate, + output_frame_size, + input_sample_rate=24000, + ) + self.audio_queue = asyncio.Queue() + self.video_queue = asyncio.Queue() + self.quit = asyncio.Event() + self.session = None + self.last_frame_time = 0 + + def copy(self) -> "VideoChatHandler": + return VideoChatHandler( + expected_layout=self.expected_layout, + output_sample_rate=self.output_sample_rate, + output_frame_size=self.output_frame_size, + ) + + #Process video data uploaded by the client + async def video_receive(self, frame: np.ndarray): + newFrame = np.array(frame) + newFrame[0:, :, 0] = 255 - newFrame[0:, :, 0] + self.video_queue.put_nowait(newFrame) + + #Prepare the video data sent by the server + async def video_emit(self) -> VideoEmitType: + return await self.video_queue.get() + + #Process audio data uploaded by the client + async def receive(self, frame: tuple[int, np.ndarray]) -> None: + frame_size, array = frame + self.audio_queue.put_nowait(array) + + #Prepare the audio data sent by the server + async def emit(self) -> AudioEmitType: + if not self.args_set.is_set(): + await self.wait_for_args() + array = await self.audio_queue.get() + return (self.output_sample_rate, array) + + def shutdown(self) -> None: + self.quit.set() + self.connection = None + self.args_set.clear() + self.quit.clear() + + + +css = """ +footer { + display: none !important; +} +""" + +with gr.Blocks(css=css) as demo: + webrtc = WebRTC( + label="Video Chat", + modality="audio-video", + mode="send-receive", + video_chat=True, + elem_id="video-source", + ) + webrtc.stream( + VideoChatHandler(), + inputs=[webrtc], + outputs=[webrtc], + time_limit=150, + concurrency_limit=2, + ) + + +if __name__ == "__main__": + demo.launch() + +``` + +## Deployment + +When deploying in a cloud environment (like Hugging Face Spaces, EC2, etc), you need to set up a TURN server to relay the WebRTC traffic. +The easiest way to do this is to use a service like Twilio. + +```python +from twilio.rest import Client +import os + +account_sid = os.environ.get("TWILIO_ACCOUNT_SID") +auth_token = os.environ.get("TWILIO_AUTH_TOKEN") + +client = Client(account_sid, auth_token) + +token = client.tokens.create() + +rtc_configuration = { + "iceServers": token.ice_servers, + "iceTransportPolicy": "relay", +} + +with gr.Blocks() as demo: + ... + rtc = WebRTC(rtc_configuration=rtc_configuration, ...) + ... +``` + +## Contributors + +[csxh47](https://github.com/xhup) +[bingochaos](https://github.com/bingochaos) +[sudowind](https://github.com/sudowind) +[emililykimura](https://github.com/emililykimura) +[Tony](https://github.com/raidios) +[Cheng Gang](https://github.com/lovepope) diff --git a/backend/fastrtc/__init__.py b/backend/fastrtc/__init__.py new file mode 100644 index 0000000..4c646e5 --- /dev/null +++ b/backend/fastrtc/__init__.py @@ -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", +] diff --git a/backend/fastrtc/credentials.py b/backend/fastrtc/credentials.py new file mode 100644 index 0000000..884753e --- /dev/null +++ b/backend/fastrtc/credentials.py @@ -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'") diff --git a/backend/fastrtc/pause_detection/__init__.py b/backend/fastrtc/pause_detection/__init__.py new file mode 100644 index 0000000..ab18632 --- /dev/null +++ b/backend/fastrtc/pause_detection/__init__.py @@ -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", +] diff --git a/backend/fastrtc/pause_detection/protocol.py b/backend/fastrtc/pause_detection/protocol.py new file mode 100644 index 0000000..e73859a --- /dev/null +++ b/backend/fastrtc/pause_detection/protocol.py @@ -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: ... diff --git a/backend/fastrtc/pause_detection/silero.py b/backend/fastrtc/pause_detection/silero.py new file mode 100644 index 0000000..ecbcd61 --- /dev/null +++ b/backend/fastrtc/pause_detection/silero.py @@ -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 diff --git a/backend/fastrtc/reply_on_pause.py b/backend/fastrtc/reply_on_pause.py new file mode 100644 index 0000000..1e3215d --- /dev/null +++ b/backend/fastrtc/reply_on_pause.py @@ -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 diff --git a/backend/fastrtc/reply_on_stopwords.py b/backend/fastrtc/reply_on_stopwords.py new file mode 100644 index 0000000..7d082d7 --- /dev/null +++ b/backend/fastrtc/reply_on_stopwords.py @@ -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, + ) diff --git a/backend/fastrtc/speech_to_text/__init__.py b/backend/fastrtc/speech_to_text/__init__.py new file mode 100644 index 0000000..92fc2d8 --- /dev/null +++ b/backend/fastrtc/speech_to_text/__init__.py @@ -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"] diff --git a/backend/fastrtc/speech_to_text/stt_.py b/backend/fastrtc/speech_to_text/stt_.py new file mode 100644 index 0000000..f8d7a6c --- /dev/null +++ b/backend/fastrtc/speech_to_text/stt_.py @@ -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 + ] + ) diff --git a/backend/fastrtc/speech_to_text/test_file.wav b/backend/fastrtc/speech_to_text/test_file.wav new file mode 100644 index 0000000..a87858b Binary files /dev/null and b/backend/fastrtc/speech_to_text/test_file.wav differ diff --git a/backend/fastrtc/stream.py b/backend/fastrtc/stream.py new file mode 100644 index 0000000..7047449 --- /dev/null +++ b/backend/fastrtc/stream.py @@ -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""" +

+ {ui_args.get("title", "Video Streaming (Powered by FastRTC ⚡️)")} +

+ """ + ) + if ui_args.get("subtitle"): + gr.Markdown( + f""" +
+ {ui_args.get("subtitle")} +
+ """ + ) + 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""" +

+ {ui_args.get("title", "Video Streaming (Powered by FastRTC ⚡️)")} +

+ """ + ) + if ui_args.get("subtitle"): + gr.Markdown( + f""" +
+ {ui_args.get("subtitle")} +
+ """ + ) + 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""" +

+ {ui_args.get("title", "Video Streaming (Powered by FastRTC ⚡️)")} +

+ """ + ) + if ui_args.get("subtitle"): + gr.Markdown( + f""" +
+ {ui_args.get("subtitle")} +
+ """ + ) + 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""" +

+ {ui_args.get("title", "Audio Streaming (Powered by FastRTC ⚡️)")} +

+ """ + ) + if ui_args.get("subtitle"): + gr.Markdown( + f""" +
+ {ui_args.get("subtitle")} +
+ """ + ) + 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""" +

+ {ui_args.get("title", "Audio Streaming (Powered by FastRTC ⚡️)")} +

+ """ + ) + if ui_args.get("subtitle"): + gr.Markdown( + f""" +
+ {ui_args.get("subtitle")} +
+ """ + ) + 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""" +

+ {ui_args.get("title", "Audio Streaming (Powered by FastRTC ⚡️)")} +

+ """ + ) + if ui_args.get("subtitle"): + gr.Markdown( + f""" +
+ {ui_args.get("subtitle")} +
+ """ + ) + 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""" +

+ {ui_args.get("title", "Audio Video Streaming (Powered by FastRTC ⚡️)")} +

+ """ + ) + if ui_args.get("subtitle"): + gr.Markdown( + f""" +
+ {ui_args.get("subtitle")} +
+ """ + ) + 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() diff --git a/backend/fastrtc/text_to_speech/__init__.py b/backend/fastrtc/text_to_speech/__init__.py new file mode 100644 index 0000000..2cc082a --- /dev/null +++ b/backend/fastrtc/text_to_speech/__init__.py @@ -0,0 +1,3 @@ +from .tts import KokoroTTSOptions, get_tts_model + +__all__ = ["get_tts_model", "KokoroTTSOptions"] diff --git a/backend/fastrtc/text_to_speech/test_tts.py b/backend/fastrtc/text_to_speech/test_tts.py new file mode 100644 index 0000000..e3abaf7 --- /dev/null +++ b/backend/fastrtc/text_to_speech/test_tts.py @@ -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() diff --git a/backend/fastrtc/text_to_speech/tts.py b/backend/fastrtc/text_to_speech/tts.py new file mode 100644 index 0000000..bee94e3 --- /dev/null +++ b/backend/fastrtc/text_to_speech/tts.py @@ -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 diff --git a/backend/fastrtc/tracks.py b/backend/fastrtc/tracks.py new file mode 100644 index 0000000..0a9c5aa --- /dev/null +++ b/backend/fastrtc/tracks.py @@ -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() diff --git a/backend/fastrtc/utils.py b/backend/fastrtc/utils.py new file mode 100644 index 0000000..53e9d8c --- /dev/null +++ b/backend/fastrtc/utils.py @@ -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 \ No newline at end of file diff --git a/backend/fastrtc/webrtc.py b/backend/fastrtc/webrtc.py new file mode 100644 index 0000000..02e6a75 --- /dev/null +++ b/backend/fastrtc/webrtc.py @@ -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"} diff --git a/backend/fastrtc/webrtc_connection_mixin.py b/backend/fastrtc/webrtc_connection_mixin.py new file mode 100644 index 0000000..2c7c6a1 --- /dev/null +++ b/backend/fastrtc/webrtc_connection_mixin.py @@ -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, + } diff --git a/backend/fastrtc/websocket.py b/backend/fastrtc/websocket.py new file mode 100644 index 0000000..4d182b9 --- /dev/null +++ b/backend/fastrtc/websocket.py @@ -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) diff --git a/demo/app.py b/demo/app.py index f943011..a3ba6a4 100644 --- a/demo/app.py +++ b/demo/app.py @@ -1,10 +1,17 @@ import asyncio import base64 from io import BytesIO +import json +import math +import queue +import time +import uuid +import threading +from fastrtc.utils import Message import gradio as gr import numpy as np -from gradio_webrtc import ( +from fastrtc import ( AsyncAudioVideoStreamHandler, WebRTC, VideoEmitType, @@ -26,6 +33,7 @@ def encode_image(data: np.ndarray) -> dict: base64_str = str(base64.b64encode(bytes_data), "utf-8") return {"mime_type": "image/jpeg", "data": base64_str} +frame_queue = queue.Queue(maxsize=100) class VideoChatHandler(AsyncAudioVideoStreamHandler): def __init__( @@ -38,7 +46,7 @@ class VideoChatHandler(AsyncAudioVideoStreamHandler): input_sample_rate=24000, ) self.audio_queue = asyncio.Queue() - self.video_queue = asyncio.Queue() + self.video_queue = frame_queue self.quit = asyncio.Event() self.session = None self.last_frame_time = 0 @@ -50,6 +58,25 @@ class VideoChatHandler(AsyncAudioVideoStreamHandler): output_frame_size=self.output_frame_size, ) + chat_id = '' + async def on_chat_datachannel(self,message: Message,channel): + # 返回 + # {"type":"chat",id:"标识属于同一段话", "message":"Hello, world!"} + # {"type":"avatar_end"} 表示本次对话结束 + if message['type'] == 'stop_chat': + self.chat_id = '' + channel.send(json.dumps({'type':'avatar_end'})) + else: + id = uuid.uuid4().hex + self.chat_id = id + data = message["data"] + halfLen = math.floor(data.__len__()/2) + channel.send(json.dumps({"type":"chat","id":id,"message":data[:halfLen]})) + await asyncio.sleep(5) + if self.chat_id == id: + channel.send(json.dumps({"type":"chat","id":id,"message":data[halfLen:]})) + channel.send(json.dumps({'type':'avatar_end'})) + async def video_receive(self, frame: np.ndarray): # if self.session: # # send image every 1 second @@ -61,10 +88,11 @@ class VideoChatHandler(AsyncAudioVideoStreamHandler): # print(frame.shape) newFrame = np.array(frame) newFrame[0:, :, 0] = 255 - newFrame[0:, :, 0] - self.video_queue.put_nowait(newFrame) + # self.video_queue.put_nowait(newFrame) async def video_emit(self) -> VideoEmitType: - return await self.video_queue.get() + # print('123123',frame_queue.qsize()) + return frame_queue.get() async def receive(self, frame: tuple[int, np.ndarray]) -> None: frame_size, array = frame @@ -114,14 +142,35 @@ with gr.Blocks(css=css) as demo: }, } ) + handler = VideoChatHandler() webrtc.stream( - VideoChatHandler(), + handler, inputs=[webrtc], outputs=[webrtc], - time_limit=150, + time_limit=1500, concurrency_limit=2, ) - + # 线程函数:随机生成 numpy 帧 + def generate_frames(width=480, height=960, channels=3): + while True: + try: + # 随机生成一个 RGB 图像帧 + frame = np.random.randint(188, 256, (height, width, channels), dtype=np.uint8) + + # 将帧放入队列 + frame_queue.put(frame) + # print("生成一帧数据,形状:", frame.shape, frame_queue.qsize()) + + # 模拟实时性:避免过度消耗 CPU + time.sleep(0.03) # 每秒约生成 30 帧 + except Exception as e: + print(f"生成帧时出错: {e}") + break + thread = threading.Thread(target=generate_frames, daemon=True) + thread.start() if __name__ == "__main__": demo.launch() + + + diff --git a/demo/echo_audio/README.md b/demo/echo_audio/README.md new file mode 100644 index 0000000..c02c1c3 --- /dev/null +++ b/demo/echo_audio/README.md @@ -0,0 +1,15 @@ +--- +title: Echo Audio +emoji: 🪩 +colorFrom: purple +colorTo: red +sdk: gradio +sdk_version: 5.16.0 +app_file: app.py +pinned: false +license: mit +short_description: Simple echo stream - simplest FastRTC demo +tags: [webrtc, websocket, gradio, secret|TWILIO_ACCOUNT_SID, secret|TWILIO_AUTH_TOKEN] +--- + +Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference \ No newline at end of file diff --git a/demo/echo_audio/app.py b/demo/echo_audio/app.py new file mode 100644 index 0000000..18f1e71 --- /dev/null +++ b/demo/echo_audio/app.py @@ -0,0 +1,45 @@ +import numpy as np +from fastapi import FastAPI +from fastapi.responses import RedirectResponse +from fastrtc import ReplyOnPause, Stream, get_twilio_turn_credentials +from gradio.utils import get_space + + +def detection(audio: tuple[int, np.ndarray]): + # Implement any iterator that yields audio + # See "LLM Voice Chat" for a more complete example + yield audio + + +stream = Stream( + handler=ReplyOnPause(detection), + modality="audio", + mode="send-receive", + rtc_configuration=get_twilio_turn_credentials() if get_space() else None, + concurrency_limit=5 if get_space() else None, + time_limit=90 if get_space() else None, +) + +app = FastAPI() + +stream.mount(app) + + +@app.get("/") +async def index(): + return RedirectResponse( + url="/ui" if not get_space() else "https://fastrtc-echo-audio.hf.space/ui/" + ) + + +if __name__ == "__main__": + import os + + if (mode := os.getenv("MODE")) == "UI": + stream.ui.launch(server_port=7860) + elif mode == "PHONE": + stream.fastphone(port=7860) + else: + import uvicorn + + uvicorn.run(app, host="0.0.0.0", port=7860) diff --git a/demo/echo_audio/requirements.txt b/demo/echo_audio/requirements.txt new file mode 100644 index 0000000..eef4c22 --- /dev/null +++ b/demo/echo_audio/requirements.txt @@ -0,0 +1,3 @@ +fastrtc[vad] +twilio +python-dotenv diff --git a/demo/gemini_audio_video/README.md b/demo/gemini_audio_video/README.md new file mode 100644 index 0000000..9a622c5 --- /dev/null +++ b/demo/gemini_audio_video/README.md @@ -0,0 +1,15 @@ +--- +title: Gemini Audio Video +emoji: ♊️ +colorFrom: purple +colorTo: red +sdk: gradio +sdk_version: 5.16.0 +app_file: app.py +pinned: false +license: mit +short_description: Gemini understands audio and video! +tags: [webrtc, websocket, gradio, secret|TWILIO_ACCOUNT_SID, secret|TWILIO_AUTH_TOKEN, secret|GEMINI_API_KEY] +--- + +Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference \ No newline at end of file diff --git a/demo/gemini_audio_video/app.py b/demo/gemini_audio_video/app.py new file mode 100644 index 0000000..f8e01a7 --- /dev/null +++ b/demo/gemini_audio_video/app.py @@ -0,0 +1,185 @@ +import asyncio +import base64 +import os +import time +from io import BytesIO + +import gradio as gr +import numpy as np +from dotenv import load_dotenv +from fastrtc import ( + AsyncAudioVideoStreamHandler, + Stream, + WebRTC, + get_twilio_turn_credentials, +) +from google import genai +from gradio.utils import get_space +from PIL import Image + +load_dotenv() + + +def encode_audio(data: np.ndarray) -> dict: + """Encode Audio data to send to the server""" + return { + "mime_type": "audio/pcm", + "data": base64.b64encode(data.tobytes()).decode("UTF-8"), + } + + +def encode_image(data: np.ndarray) -> dict: + with BytesIO() as output_bytes: + pil_image = Image.fromarray(data) + pil_image.save(output_bytes, "JPEG") + bytes_data = output_bytes.getvalue() + base64_str = str(base64.b64encode(bytes_data), "utf-8") + return {"mime_type": "image/jpeg", "data": base64_str} + + +class GeminiHandler(AsyncAudioVideoStreamHandler): + def __init__( + self, + ) -> None: + super().__init__( + "mono", + output_sample_rate=24000, + output_frame_size=480, + input_sample_rate=16000, + ) + self.audio_queue = asyncio.Queue() + self.video_queue = asyncio.Queue() + self.quit = asyncio.Event() + self.session = None + self.last_frame_time = 0 + self.quit = asyncio.Event() + + def copy(self) -> "GeminiHandler": + return GeminiHandler() + + async def start_up(self): + client = genai.Client( + api_key=os.getenv("GEMINI_API_KEY"), http_options={"api_version": "v1alpha"} + ) + config = {"response_modalities": ["AUDIO"]} + async with client.aio.live.connect( + model="gemini-2.0-flash-exp", config=config + ) as session: + self.session = session + print("set session") + while not self.quit.is_set(): + turn = self.session.receive() + async for response in turn: + if data := response.data: + audio = np.frombuffer(data, dtype=np.int16).reshape(1, -1) + self.audio_queue.put_nowait(audio) + + async def video_receive(self, frame: np.ndarray): + if self.session: + # send image every 1 second + print(time.time() - self.last_frame_time) + if time.time() - self.last_frame_time > 1: + self.last_frame_time = time.time() + await self.session.send(input=encode_image(frame)) + if self.latest_args[1] is not None: + await self.session.send(input=encode_image(self.latest_args[1])) + + self.video_queue.put_nowait(frame) + + async def video_emit(self): + return await self.video_queue.get() + + async def receive(self, frame: tuple[int, np.ndarray]) -> None: + _, array = frame + array = array.squeeze() + audio_message = encode_audio(array) + if self.session: + await self.session.send(input=audio_message) + + async def emit(self): + array = await self.audio_queue.get() + return (self.output_sample_rate, array) + + async def shutdown(self) -> None: + if self.session: + self.quit.set() + await self.session._websocket.close() + self.quit.clear() + + +stream = Stream( + handler=GeminiHandler(), + modality="audio-video", + mode="send-receive", + rtc_configuration=get_twilio_turn_credentials() + if get_space() == "spaces" + else None, + time_limit=90 if get_space() else None, + additional_inputs=[ + gr.Image(label="Image", type="numpy", sources=["upload", "clipboard"]) + ], + ui_args={ + "icon": "https://www.gstatic.com/lamda/images/gemini_favicon_f069958c85030456e93de685481c559f160ea06b.png", + "pulse_color": "rgb(255, 255, 255)", + "icon_button_color": "rgb(255, 255, 255)", + "title": "Gemini Audio Video Chat", + }, +) + +css = """ +#video-source {max-width: 600px !important; max-height: 600 !important;} +""" + +with gr.Blocks(css=css) as demo: + gr.HTML( + """ +
+
+ +
+
+

Gen AI SDK Voice Chat

+

Speak with Gemini using real-time audio + video streaming

+

Powered by Gradio and WebRTC⚡️

+

Get an API Key here

+
+
+ """ + ) + with gr.Row() as row: + with gr.Column(): + webrtc = WebRTC( + label="Video Chat", + modality="audio-video", + mode="send-receive", + elem_id="video-source", + rtc_configuration=get_twilio_turn_credentials() + if get_space() == "spaces" + else None, + icon="https://www.gstatic.com/lamda/images/gemini_favicon_f069958c85030456e93de685481c559f160ea06b.png", + pulse_color="rgb(255, 255, 255)", + icon_button_color="rgb(255, 255, 255)", + ) + with gr.Column(): + image_input = gr.Image( + label="Image", type="numpy", sources=["upload", "clipboard"] + ) + + webrtc.stream( + GeminiHandler(), + inputs=[webrtc, image_input], + outputs=[webrtc], + time_limit=60 if get_space() else None, + concurrency_limit=2 if get_space() else None, + ) + +stream.ui = demo + + +if __name__ == "__main__": + if (mode := os.getenv("MODE")) == "UI": + stream.ui.launch(server_port=7860) + elif mode == "PHONE": + raise ValueError("Phone mode not supported for this demo") + else: + stream.ui.launch(server_port=7860) diff --git a/demo/gemini_audio_video/requirements.txt b/demo/gemini_audio_video/requirements.txt new file mode 100644 index 0000000..e8cbeb2 --- /dev/null +++ b/demo/gemini_audio_video/requirements.txt @@ -0,0 +1,4 @@ +fastrtc +python-dotenv +google-genai +twilio diff --git a/demo/gemini_conversation/README.md b/demo/gemini_conversation/README.md new file mode 100644 index 0000000..b20332f --- /dev/null +++ b/demo/gemini_conversation/README.md @@ -0,0 +1,15 @@ +--- +title: Gemini Talking to Gemini +emoji: ♊️ +colorFrom: purple +colorTo: red +sdk: gradio +sdk_version: 5.17.0 +app_file: app.py +pinned: false +license: mit +short_description: Have two Gemini agents talk to each other +tags: [webrtc, websocket, gradio, secret|TWILIO_ACCOUNT_SID, secret|TWILIO_AUTH_TOKEN, secret|GEMINI_API_KEY] +--- + +Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference \ No newline at end of file diff --git a/demo/gemini_conversation/app.py b/demo/gemini_conversation/app.py new file mode 100644 index 0000000..907693b --- /dev/null +++ b/demo/gemini_conversation/app.py @@ -0,0 +1,232 @@ +import asyncio +import base64 +import os +from pathlib import Path +from typing import AsyncGenerator + +import librosa +import numpy as np +from dotenv import load_dotenv +from fastrtc import ( + AsyncStreamHandler, + Stream, + get_tts_model, + wait_for_item, +) +from fastrtc.utils import audio_to_int16 +from google import genai +from google.genai.types import ( + Content, + LiveConnectConfig, + Part, + PrebuiltVoiceConfig, + SpeechConfig, + VoiceConfig, +) + +load_dotenv() + +cur_dir = Path(__file__).parent + +SAMPLE_RATE = 24000 + +tts_model = get_tts_model() + + +class GeminiHandler(AsyncStreamHandler): + """Handler for the Gemini API""" + + def __init__( + self, + ) -> None: + super().__init__( + expected_layout="mono", + output_sample_rate=24000, + output_frame_size=480, + input_sample_rate=24000, + ) + self.input_queue: asyncio.Queue = asyncio.Queue() + self.output_queue: asyncio.Queue = asyncio.Queue() + self.quit: asyncio.Event = asyncio.Event() + + def copy(self) -> "GeminiHandler": + return GeminiHandler() + + async def start_up(self): + voice_name = "Charon" + client = genai.Client( + api_key=os.getenv("GEMINI_API_KEY"), + http_options={"api_version": "v1alpha"}, + ) + + config = LiveConnectConfig( + response_modalities=["AUDIO"], # type: ignore + speech_config=SpeechConfig( + voice_config=VoiceConfig( + prebuilt_voice_config=PrebuiltVoiceConfig( + voice_name=voice_name, + ) + ) + ), + system_instruction=Content( + parts=[Part(text="You are a helpful assistant.")], + role="system", + ), + ) + async with client.aio.live.connect( + model="gemini-2.0-flash-exp", config=config + ) as session: + async for audio in session.start_stream( + stream=self.stream(), mime_type="audio/pcm" + ): + if audio.data: + array = np.frombuffer(audio.data, dtype=np.int16) + self.output_queue.put_nowait((self.output_sample_rate, array)) + + async def stream(self) -> AsyncGenerator[bytes, None]: + while not self.quit.is_set(): + try: + audio = await asyncio.wait_for(self.input_queue.get(), 0.1) + yield audio + except (asyncio.TimeoutError, TimeoutError): + pass + + async def receive(self, frame: tuple[int, np.ndarray]) -> None: + _, array = frame + array = array.squeeze() + audio_message = base64.b64encode(array.tobytes()).decode("UTF-8") + self.input_queue.put_nowait(audio_message) + + async def emit(self) -> tuple[int, np.ndarray] | None: + return await wait_for_item(self.output_queue) + + def shutdown(self) -> None: + self.quit.set() + + +class GeminiHandler2(GeminiHandler): + async def start_up(self): + starting_message = tts_model.tts("Can you help me make an omelette?") + starting_message = librosa.resample( + starting_message[1], + orig_sr=starting_message[0], + target_sr=self.output_sample_rate, + ) + starting_message = audio_to_int16((self.output_sample_rate, starting_message)) + await self.output_queue.put((self.output_sample_rate, starting_message)) + voice_name = "Puck" + client = genai.Client( + api_key=os.getenv("GEMINI_API_KEY"), + http_options={"api_version": "v1alpha"}, + ) + + config = LiveConnectConfig( + response_modalities=["AUDIO"], # type: ignore + speech_config=SpeechConfig( + voice_config=VoiceConfig( + prebuilt_voice_config=PrebuiltVoiceConfig( + voice_name=voice_name, + ) + ) + ), + system_instruction=Content( + parts=[ + Part( + text="You are a cooking student who wants to learn how to make an omelette." + ), + Part( + text="You are currently in the kitchen with a teacher who is helping you make an omelette." + ), + Part( + text="Please wait for the teacher to tell you what to do next. Follow the teacher's instructions carefully." + ), + ], + role="system", + ), + ) + async with client.aio.live.connect( + model="gemini-2.0-flash-exp", config=config + ) as session: + async for audio in session.start_stream( + stream=self.stream(), mime_type="audio/pcm" + ): + if audio.data: + array = np.frombuffer(audio.data, dtype=np.int16) + self.output_queue.put_nowait((self.output_sample_rate, array)) + + def copy(self) -> "GeminiHandler2": + return GeminiHandler2() + + +gemini_stream = Stream( + GeminiHandler(), + modality="audio", + mode="send-receive", + ui_args={ + "title": "Gemini Teacher", + "icon": "https://www.gstatic.com/lamda/images/gemini_favicon_f069958c85030456e93de685481c559f160ea06b.png", + "pulse_color": "rgb(74, 138, 213)", + "icon_button_color": "rgb(255, 255, 255)", + }, +) + +gemini_stream_2 = Stream( + GeminiHandler2(), + modality="audio", + mode="send-receive", + ui_args={ + "title": "Gemini Student", + "icon": "https://www.gstatic.com/lamda/images/gemini_favicon_f069958c85030456e93de685481c559f160ea06b.png", + "pulse_color": "rgb(132, 112, 196)", + "icon_button_color": "rgb(255, 255, 255)", + }, +) + +if __name__ == "__main__": + import gradio as gr + from gradio.utils import get_space + + if not get_space(): + with gr.Blocks() as demo: + gr.HTML( + """ +
+

Gemini Conversation

+
+ """ + ) + gr.Markdown( + """# How to run this demo + + - Clone the repo - top right of the page click the vertical three dots and select "Clone repository" + - Open the repo in a terminal and install the dependencies + - Get a gemini API key [here](https://ai.google.dev/gemini-api/docs/api-key) + - Create a `.env` file in the root of the repo and add the following: + ``` + GEMINI_API_KEY= + ``` + - Run the app with `python app.py` + - This will print the two URLs of the agents running locally + - Use ngrok to exponse one agent to the internet. This is so that you can acces it from your phone + - Use the ngrok URL to access the agent from your phone + - Now, start the "teacher gemini" agent first. Then, start the "student gemini" agent. The student gemini will start talking to the teacher gemini. And the teacher gemini will respond! + + Important: + - Make sure the audio sources are not too close to each other or too loud. Sometimes that causes them to talk over each other.. + - Feel free to modify the `system_instruction` to change the behavior of the agents. + - You can also modify the `voice_name` to change the voice of the agents. + - Have fun! + """ + ) + demo.launch() + + import time + + _ = gemini_stream.ui.launch(server_port=7860, prevent_thread_lock=True) + _ = gemini_stream_2.ui.launch(server_port=7861, prevent_thread_lock=True) + try: + while True: + time.sleep(1) + except KeyboardInterrupt: + gemini_stream.ui.close() + gemini_stream_2.ui.close() diff --git a/demo/hello_computer/README.md b/demo/hello_computer/README.md new file mode 100644 index 0000000..e85e2de --- /dev/null +++ b/demo/hello_computer/README.md @@ -0,0 +1,15 @@ +--- +title: Hello Computer +emoji: 💻 +colorFrom: purple +colorTo: red +sdk: gradio +sdk_version: 5.16.0 +app_file: app.py +pinned: false +license: mit +short_description: Say computer before asking your question +tags: [webrtc, websocket, gradio, secret|TWILIO_ACCOUNT_SID, secret|TWILIO_AUTH_TOKEN, secret|SAMBANOVA_API_KEY] +--- + +Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference \ No newline at end of file diff --git a/demo/hello_computer/README_gradio.md b/demo/hello_computer/README_gradio.md new file mode 100644 index 0000000..843605f --- /dev/null +++ b/demo/hello_computer/README_gradio.md @@ -0,0 +1,15 @@ +--- +title: Hello Computer (Gradio) +emoji: 💻 +colorFrom: purple +colorTo: red +sdk: gradio +sdk_version: 5.16.0 +app_file: app.py +pinned: false +license: mit +short_description: Say computer (Gradio) +tags: [webrtc, websocket, gradio, secret|TWILIO_ACCOUNT_SID, secret|TWILIO_AUTH_TOKEN, secret|SAMBANOVA_API_KEY] +--- + +Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference \ No newline at end of file diff --git a/demo/hello_computer/app.py b/demo/hello_computer/app.py new file mode 100644 index 0000000..6a60496 --- /dev/null +++ b/demo/hello_computer/app.py @@ -0,0 +1,145 @@ +import base64 +import json +import os +from pathlib import Path + +import gradio as gr +import huggingface_hub +import numpy as np +from dotenv import load_dotenv +from fastapi import FastAPI +from fastapi.responses import HTMLResponse, StreamingResponse +from fastrtc import ( + AdditionalOutputs, + ReplyOnStopWords, + Stream, + get_stt_model, + get_twilio_turn_credentials, +) +from gradio.utils import get_space +from pydantic import BaseModel + +load_dotenv() + +curr_dir = Path(__file__).parent + + +client = huggingface_hub.InferenceClient( + api_key=os.environ.get("SAMBANOVA_API_KEY"), + provider="sambanova", +) +model = get_stt_model() + + +def response( + audio: tuple[int, np.ndarray], + gradio_chatbot: list[dict] | None = None, + conversation_state: list[dict] | None = None, +): + gradio_chatbot = gradio_chatbot or [] + conversation_state = conversation_state or [] + text = model.stt(audio) + print("STT in handler", text) + sample_rate, array = audio + gradio_chatbot.append( + {"role": "user", "content": gr.Audio((sample_rate, array.squeeze()))} + ) + yield AdditionalOutputs(gradio_chatbot, conversation_state) + + conversation_state.append({"role": "user", "content": text}) + + request = client.chat.completions.create( + model="meta-llama/Llama-3.2-3B-Instruct", + messages=conversation_state, # type: ignore + temperature=0.1, + top_p=0.1, + ) + response = {"role": "assistant", "content": request.choices[0].message.content} + + conversation_state.append(response) + gradio_chatbot.append(response) + + yield AdditionalOutputs(gradio_chatbot, conversation_state) + + +chatbot = gr.Chatbot(type="messages", value=[]) +state = gr.State(value=[]) +stream = Stream( + ReplyOnStopWords( + response, # type: ignore + stop_words=["computer"], + input_sample_rate=16000, + ), + mode="send", + modality="audio", + additional_inputs=[chatbot, state], + additional_outputs=[chatbot, state], + additional_outputs_handler=lambda *a: (a[2], a[3]), + concurrency_limit=5 if get_space() else None, + time_limit=90 if get_space() else None, + rtc_configuration=get_twilio_turn_credentials() if get_space() else None, +) +app = FastAPI() +stream.mount(app) + + +class Message(BaseModel): + role: str + content: str + + +class InputData(BaseModel): + webrtc_id: str + chatbot: list[Message] + state: list[Message] + + +@app.get("/") +async def _(): + rtc_config = get_twilio_turn_credentials() if get_space() else None + html_content = (curr_dir / "index.html").read_text() + html_content = html_content.replace("__RTC_CONFIGURATION__", json.dumps(rtc_config)) + return HTMLResponse(content=html_content) + + +@app.post("/input_hook") +async def _(data: InputData): + body = data.model_dump() + stream.set_input(data.webrtc_id, body["chatbot"], body["state"]) + + +def audio_to_base64(file_path): + audio_format = "wav" + with open(file_path, "rb") as audio_file: + encoded_audio = base64.b64encode(audio_file.read()).decode("utf-8") + return f"data:audio/{audio_format};base64,{encoded_audio}" + + +@app.get("/outputs") +async def _(webrtc_id: str): + async def output_stream(): + async for output in stream.output_stream(webrtc_id): + chatbot = output.args[0] + state = output.args[1] + data = { + "message": state[-1], + "audio": audio_to_base64(chatbot[-1]["content"].value["path"]) + if chatbot[-1]["role"] == "user" + else None, + } + yield f"event: output\ndata: {json.dumps(data)}\n\n" + + return StreamingResponse(output_stream(), media_type="text/event-stream") + + +if __name__ == "__main__": + import os + + if (mode := os.getenv("MODE")) == "UI": + stream.ui.launch(server_port=7860) + elif mode == "PHONE": + raise ValueError("Phone mode not supported") + else: + import uvicorn + + uvicorn.run(app, host="0.0.0.0", port=7860) diff --git a/demo/hello_computer/index.html b/demo/hello_computer/index.html new file mode 100644 index 0000000..3e453b4 --- /dev/null +++ b/demo/hello_computer/index.html @@ -0,0 +1,486 @@ + + + + + + + Hello Computer 💻 + + + + + +
+
+ +
+
+
+
+
+
+
+
+
+
+
+ +
+
+ + + + + + \ No newline at end of file diff --git a/demo/hello_computer/requirements.txt b/demo/hello_computer/requirements.txt new file mode 100644 index 0000000..d17d5a3 --- /dev/null +++ b/demo/hello_computer/requirements.txt @@ -0,0 +1,4 @@ +fastrtc[stopword] +python-dotenv +huggingface_hub>=0.29.0 +twilio \ No newline at end of file diff --git a/demo/llama_code_editor/README.md b/demo/llama_code_editor/README.md new file mode 100644 index 0000000..8608630 --- /dev/null +++ b/demo/llama_code_editor/README.md @@ -0,0 +1,16 @@ +--- +title: Llama Code Editor +emoji: 🦙 +colorFrom: indigo +colorTo: pink +sdk: gradio +sdk_version: 5.16.0 +app_file: app.py +pinned: false +license: mit +short_description: Create interactive HTML web pages with your voice +tags: [webrtc, websocket, gradio, secret|TWILIO_ACCOUNT_SID, secret|TWILIO_AUTH_TOKEN, +secret|SAMBANOVA_API_KEY, secret|GROQ_API_KEY] +--- + +Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/demo/llama_code_editor/app.py b/demo/llama_code_editor/app.py new file mode 100644 index 0000000..5e8aa1c --- /dev/null +++ b/demo/llama_code_editor/app.py @@ -0,0 +1,45 @@ +from fastapi import FastAPI +from fastapi.responses import RedirectResponse +from fastrtc import Stream +from gradio.utils import get_space + +try: + from demo.llama_code_editor.handler import ( + CodeHandler, + ) + from demo.llama_code_editor.ui import demo as ui +except (ImportError, ModuleNotFoundError): + from handler import CodeHandler + from ui import demo as ui + + +stream = Stream( + handler=CodeHandler, + modality="audio", + mode="send-receive", + concurrency_limit=10 if get_space() else None, + time_limit=90 if get_space() else None, +) + +stream.ui = ui + +app = FastAPI() + + +@app.get("/") +async def _(): + url = "/ui" if not get_space() else "https://fastrtc-llama-code-editor.hf.space/ui/" + return RedirectResponse(url) + + +if __name__ == "__main__": + import os + + if (mode := os.getenv("MODE")) == "UI": + stream.ui.launch(server_port=7860, server_name="0.0.0.0") + elif mode == "PHONE": + stream.fastphone(host="0.0.0.0", port=7860) + else: + import uvicorn + + uvicorn.run(app, host="0.0.0.0", port=7860) diff --git a/demo/llama_code_editor/assets/sandbox.html b/demo/llama_code_editor/assets/sandbox.html new file mode 100644 index 0000000..39326ac --- /dev/null +++ b/demo/llama_code_editor/assets/sandbox.html @@ -0,0 +1,37 @@ +
+
+
📦
+
+

No Application Created

+
\ No newline at end of file diff --git a/demo/llama_code_editor/assets/spinner.html b/demo/llama_code_editor/assets/spinner.html new file mode 100644 index 0000000..0621d44 --- /dev/null +++ b/demo/llama_code_editor/assets/spinner.html @@ -0,0 +1,60 @@ +
+ +
+ +
+ +
+
+ + +

Generating your application...

+ +

This may take a few moments

+ + +
\ No newline at end of file diff --git a/demo/llama_code_editor/handler.py b/demo/llama_code_editor/handler.py new file mode 100644 index 0000000..fee8dfc --- /dev/null +++ b/demo/llama_code_editor/handler.py @@ -0,0 +1,73 @@ +import base64 +import os +import re +from pathlib import Path + +import numpy as np +import openai +from dotenv import load_dotenv +from fastrtc import ( + AdditionalOutputs, + ReplyOnPause, + audio_to_bytes, +) +from groq import Groq + +load_dotenv() + +groq_client = Groq(api_key=os.environ.get("GROQ_API_KEY")) + +client = openai.OpenAI( + api_key=os.environ.get("SAMBANOVA_API_KEY"), + base_url="https://api.sambanova.ai/v1", +) + +path = Path(__file__).parent / "assets" + +spinner_html = open(path / "spinner.html").read() + + +system_prompt = "You are an AI coding assistant. Your task is to write single-file HTML applications based on a user's request. Only return the necessary code. Include all necessary imports and styles. You may also be asked to edit your original response." +user_prompt = "Please write a single-file HTML application to fulfill the following request.\nThe message:{user_message}\nCurrent code you have written:{code}" + + +def extract_html_content(text): + """ + Extract content including HTML tags. + """ + match = re.search(r".*?", text, re.DOTALL) + return match.group(0) if match else None + + +def display_in_sandbox(code): + encoded_html = base64.b64encode(code.encode("utf-8")).decode("utf-8") + data_uri = f"data:text/html;charset=utf-8;base64,{encoded_html}" + return f'' + + +def generate(user_message: tuple[int, np.ndarray], history: list[dict], code: str): + yield AdditionalOutputs(history, spinner_html) + + text = groq_client.audio.transcriptions.create( + file=("audio-file.mp3", audio_to_bytes(user_message)), + model="whisper-large-v3-turbo", + response_format="verbose_json", + ).text + + user_msg_formatted = user_prompt.format(user_message=text, code=code) + history.append({"role": "user", "content": user_msg_formatted}) + + response = client.chat.completions.create( + model="Meta-Llama-3.1-70B-Instruct", + messages=history, # type: ignore + temperature=0.1, + top_p=0.1, + ) + + output = response.choices[0].message.content + html_code = extract_html_content(output) + history.append({"role": "assistant", "content": output}) + yield AdditionalOutputs(history, html_code) + + +CodeHandler = ReplyOnPause(generate) # type: ignore diff --git a/demo/llama_code_editor/requirements.in b/demo/llama_code_editor/requirements.in new file mode 100644 index 0000000..8a5354d --- /dev/null +++ b/demo/llama_code_editor/requirements.in @@ -0,0 +1,5 @@ +fastrtc[vad] +groq +openai +python-dotenv +twilio \ No newline at end of file diff --git a/demo/llama_code_editor/requirements.txt b/demo/llama_code_editor/requirements.txt new file mode 100644 index 0000000..3b73b6a --- /dev/null +++ b/demo/llama_code_editor/requirements.txt @@ -0,0 +1,295 @@ +# This file was autogenerated by uv via the following command: +# uv pip compile demo/llama_code_editor/requirements.in -o demo/llama_code_editor/requirements.txt +aiofiles==23.2.1 + # via gradio +aiohappyeyeballs==2.4.6 + # via aiohttp +aiohttp==3.11.12 + # via + # aiohttp-retry + # twilio +aiohttp-retry==2.9.1 + # via twilio +aioice==0.9.0 + # via aiortc +aiortc==1.10.1 + # via fastrtc +aiosignal==1.3.2 + # via aiohttp +annotated-types==0.7.0 + # via pydantic +anyio==4.6.2.post1 + # via + # gradio + # groq + # httpx + # openai + # starlette +attrs==25.1.0 + # via aiohttp +audioread==3.0.1 + # via librosa +av==12.3.0 + # via aiortc +certifi==2024.8.30 + # via + # httpcore + # httpx + # requests +cffi==1.17.1 + # via + # aiortc + # cryptography + # pylibsrtp + # soundfile +charset-normalizer==3.4.0 + # via requests +click==8.1.7 + # via + # typer + # uvicorn +coloredlogs==15.0.1 + # via onnxruntime +cryptography==43.0.3 + # via + # aiortc + # pyopenssl +decorator==5.1.1 + # via librosa +distro==1.9.0 + # via + # groq + # openai +dnspython==2.7.0 + # via aioice +fastapi==0.115.5 + # via gradio +fastrtc==0.0.2.post4 + # via -r demo/llama_code_editor/requirements.in +ffmpy==0.4.0 + # via gradio +filelock==3.16.1 + # via huggingface-hub +flatbuffers==24.3.25 + # via onnxruntime +frozenlist==1.5.0 + # via + # aiohttp + # aiosignal +fsspec==2024.10.0 + # via + # gradio-client + # huggingface-hub +google-crc32c==1.6.0 + # via aiortc +gradio==5.16.0 + # via fastrtc +gradio-client==1.7.0 + # via gradio +groq==0.18.0 + # via -r demo/llama_code_editor/requirements.in +h11==0.14.0 + # via + # httpcore + # uvicorn +httpcore==1.0.7 + # via httpx +httpx==0.27.2 + # via + # gradio + # gradio-client + # groq + # openai + # safehttpx +huggingface-hub==0.28.1 + # via + # gradio + # gradio-client +humanfriendly==10.0 + # via coloredlogs +idna==3.10 + # via + # anyio + # httpx + # requests + # yarl +ifaddr==0.2.0 + # via aioice +jinja2==3.1.4 + # via gradio +jiter==0.7.1 + # via openai +joblib==1.4.2 + # via + # librosa + # scikit-learn +lazy-loader==0.4 + # via librosa +librosa==0.10.2.post1 + # via fastrtc +llvmlite==0.43.0 + # via numba +markdown-it-py==3.0.0 + # via rich +markupsafe==2.1.5 + # via + # gradio + # jinja2 +mdurl==0.1.2 + # via markdown-it-py +mpmath==1.3.0 + # via sympy +msgpack==1.1.0 + # via librosa +multidict==6.1.0 + # via + # aiohttp + # yarl +numba==0.60.0 + # via librosa +numpy==2.0.2 + # via + # gradio + # librosa + # numba + # onnxruntime + # pandas + # scikit-learn + # scipy + # soxr +onnxruntime==1.20.1 + # via fastrtc +openai==1.54.4 + # via -r demo/llama_code_editor/requirements.in +orjson==3.10.11 + # via gradio +packaging==24.2 + # via + # gradio + # gradio-client + # huggingface-hub + # lazy-loader + # onnxruntime + # pooch +pandas==2.2.3 + # via gradio +pillow==11.0.0 + # via gradio +platformdirs==4.3.6 + # via pooch +pooch==1.8.2 + # via librosa +propcache==0.2.1 + # via + # aiohttp + # yarl +protobuf==5.28.3 + # via onnxruntime +pycparser==2.22 + # via cffi +pydantic==2.9.2 + # via + # fastapi + # gradio + # groq + # openai +pydantic-core==2.23.4 + # via pydantic +pydub==0.25.1 + # via gradio +pyee==12.1.1 + # via aiortc +pygments==2.18.0 + # via rich +pyjwt==2.10.1 + # via twilio +pylibsrtp==0.10.0 + # via aiortc +pyopenssl==24.2.1 + # via aiortc +python-dateutil==2.9.0.post0 + # via pandas +python-dotenv==1.0.1 + # via -r demo/llama_code_editor/requirements.in +python-multipart==0.0.20 + # via gradio +pytz==2024.2 + # via pandas +pyyaml==6.0.2 + # via + # gradio + # huggingface-hub +requests==2.32.3 + # via + # huggingface-hub + # pooch + # twilio +rich==13.9.4 + # via typer +ruff==0.9.6 + # via gradio +safehttpx==0.1.6 + # via gradio +scikit-learn==1.5.2 + # via librosa +scipy==1.14.1 + # via + # librosa + # scikit-learn +semantic-version==2.10.0 + # via gradio +shellingham==1.5.4 + # via typer +six==1.16.0 + # via python-dateutil +sniffio==1.3.1 + # via + # anyio + # groq + # httpx + # openai +soundfile==0.12.1 + # via librosa +soxr==0.5.0.post1 + # via librosa +starlette==0.42.0 + # via + # fastapi + # gradio +sympy==1.13.3 + # via onnxruntime +threadpoolctl==3.5.0 + # via scikit-learn +tomlkit==0.12.0 + # via gradio +tqdm==4.67.0 + # via + # huggingface-hub + # openai +twilio==9.4.5 + # via -r demo/llama_code_editor/requirements.in +typer==0.13.1 + # via gradio +typing-extensions==4.12.2 + # via + # fastapi + # gradio + # gradio-client + # groq + # huggingface-hub + # librosa + # openai + # pydantic + # pydantic-core + # pyee + # typer +tzdata==2024.2 + # via pandas +urllib3==2.2.3 + # via requests +uvicorn==0.32.0 + # via gradio +websockets==12.0 + # via gradio-client +yarl==1.18.3 + # via aiohttp diff --git a/demo/llama_code_editor/ui.py b/demo/llama_code_editor/ui.py new file mode 100644 index 0000000..cfe08d9 --- /dev/null +++ b/demo/llama_code_editor/ui.py @@ -0,0 +1,75 @@ +from pathlib import Path + +import gradio as gr +from dotenv import load_dotenv +from fastrtc import WebRTC, get_twilio_turn_credentials +from gradio.utils import get_space + +try: + from demo.llama_code_editor.handler import ( + CodeHandler, + display_in_sandbox, + system_prompt, + ) +except (ImportError, ModuleNotFoundError): + from handler import CodeHandler, display_in_sandbox, system_prompt + +load_dotenv() + +path = Path(__file__).parent / "assets" + +with gr.Blocks(css=".code-component {max-height: 500px !important}") as demo: + history = gr.State([{"role": "system", "content": system_prompt}]) + with gr.Row(): + with gr.Column(scale=1): + gr.HTML( + """ +

+ Llama Code Editor +

+

+ Powered by SambaNova and Gradio-WebRTC ⚡️ +

+

+ Create and edit single-file HTML applications with just your voice! +

+

+ Each conversation is limited to 90 seconds. Once the time limit is up you can rejoin the conversation. +

+ """ + ) + webrtc = WebRTC( + rtc_configuration=get_twilio_turn_credentials() + if get_space() + else None, + mode="send", + modality="audio", + ) + with gr.Column(scale=10): + with gr.Tabs(): + with gr.Tab("Sandbox"): + sandbox = gr.HTML(value=open(path / "sandbox.html").read()) + with gr.Tab("Code"): + code = gr.Code( + language="html", + max_lines=50, + interactive=False, + elem_classes="code-component", + ) + with gr.Tab("Chat"): + cb = gr.Chatbot(type="messages") + + webrtc.stream( + CodeHandler, + inputs=[webrtc, history, code], + outputs=[webrtc], + time_limit=90 if get_space() else None, + concurrency_limit=10 if get_space() else None, + ) + webrtc.on_additional_outputs( + lambda history, code: (history, code, history), outputs=[history, code, cb] + ) + code.change(display_in_sandbox, code, sandbox, queue=False) + +if __name__ == "__main__": + demo.launch() diff --git a/demo/llm_voice_chat/README.md b/demo/llm_voice_chat/README.md new file mode 100644 index 0000000..355a28b --- /dev/null +++ b/demo/llm_voice_chat/README.md @@ -0,0 +1,15 @@ +--- +title: LLM Voice Chat +emoji: 💻 +colorFrom: purple +colorTo: red +sdk: gradio +sdk_version: 5.16.0 +app_file: app.py +pinned: false +license: mit +short_description: Talk to an LLM with ElevenLabs +tags: [webrtc, websocket, gradio, secret|TWILIO_ACCOUNT_SID, secret|TWILIO_AUTH_TOKEN, secret|GROQ_API_KEY, secret|ELEVENLABS_API_KEY] +--- + +Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference \ No newline at end of file diff --git a/demo/llm_voice_chat/README_gradio.md b/demo/llm_voice_chat/README_gradio.md new file mode 100644 index 0000000..f36f353 --- /dev/null +++ b/demo/llm_voice_chat/README_gradio.md @@ -0,0 +1,15 @@ +--- +title: LLM Voice Chat (Gradio) +emoji: 💻 +colorFrom: purple +colorTo: red +sdk: gradio +sdk_version: 5.16.0 +app_file: app.py +pinned: false +license: mit +short_description: LLM Voice by ElevenLabs (Gradio) +tags: [webrtc, websocket, gradio, secret|TWILIO_ACCOUNT_SID, secret|TWILIO_AUTH_TOKEN, secret|GROQ_API_KEY, secret|ELEVENLABS_API_KEY] +--- + +Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference \ No newline at end of file diff --git a/demo/llm_voice_chat/app.py b/demo/llm_voice_chat/app.py new file mode 100644 index 0000000..9de3c89 --- /dev/null +++ b/demo/llm_voice_chat/app.py @@ -0,0 +1,97 @@ +import os +import time + +import gradio as gr +import numpy as np +from dotenv import load_dotenv +from elevenlabs import ElevenLabs +from fastapi import FastAPI +from fastrtc import ( + AdditionalOutputs, + ReplyOnPause, + Stream, + get_stt_model, + get_twilio_turn_credentials, +) +from gradio.utils import get_space +from groq import Groq +from numpy.typing import NDArray + +load_dotenv() +groq_client = Groq() +tts_client = ElevenLabs(api_key=os.getenv("ELEVENLABS_API_KEY")) +stt_model = get_stt_model() + + +# See "Talk to Claude" in Cookbook for an example of how to keep +# track of the chat history. +def response( + audio: tuple[int, NDArray[np.int16 | np.float32]], + chatbot: list[dict] | None = None, +): + chatbot = chatbot or [] + messages = [{"role": d["role"], "content": d["content"]} for d in chatbot] + start = time.time() + text = stt_model.stt(audio) + print("transcription", time.time() - start) + print("prompt", text) + chatbot.append({"role": "user", "content": text}) + yield AdditionalOutputs(chatbot) + messages.append({"role": "user", "content": text}) + response_text = ( + groq_client.chat.completions.create( + model="llama-3.1-8b-instant", + max_tokens=200, + messages=messages, # type: ignore + ) + .choices[0] + .message.content + ) + + chatbot.append({"role": "assistant", "content": response_text}) + + for i, chunk in enumerate( + tts_client.text_to_speech.convert_as_stream( + text=response_text, # type: ignore + voice_id="JBFqnCBsd6RMkjVDRZzb", + model_id="eleven_multilingual_v2", + output_format="pcm_24000", + ) + ): + if i == 0: + yield AdditionalOutputs(chatbot) + audio_array = np.frombuffer(chunk, dtype=np.int16).reshape(1, -1) + yield (24000, audio_array) + + +chatbot = gr.Chatbot(type="messages") +stream = Stream( + modality="audio", + mode="send-receive", + handler=ReplyOnPause(response, input_sample_rate=16000), + additional_outputs_handler=lambda a, b: b, + additional_inputs=[chatbot], + additional_outputs=[chatbot], + rtc_configuration=get_twilio_turn_credentials() if get_space() else None, + concurrency_limit=5 if get_space() else None, + time_limit=90 if get_space() else None, + ui_args={"title": "LLM Voice Chat (Powered by Groq, ElevenLabs, and WebRTC ⚡️)"}, +) + +# Mount the STREAM UI to the FastAPI app +# Because I don't want to build the UI manually +app = FastAPI() +app = gr.mount_gradio_app(app, stream.ui, path="/") + + +if __name__ == "__main__": + import os + + os.environ["GRADIO_SSR_MODE"] = "false" + + if (mode := os.getenv("MODE")) == "UI": + stream.ui.launch(server_port=7860) + elif mode == "PHONE": + stream.fastphone(host="0.0.0.0", port=7860) + else: + stream.ui.launch(server_port=7860) diff --git a/demo/llm_voice_chat/requirements.txt b/demo/llm_voice_chat/requirements.txt new file mode 100644 index 0000000..c83b692 --- /dev/null +++ b/demo/llm_voice_chat/requirements.txt @@ -0,0 +1,6 @@ +fastrtc[stopword] +python-dotenv +openai +twilio +groq +elevenlabs diff --git a/demo/moonshine_live/README.md b/demo/moonshine_live/README.md new file mode 100644 index 0000000..d541a3d --- /dev/null +++ b/demo/moonshine_live/README.md @@ -0,0 +1,16 @@ +--- +title: Moonshine Live Transcription +emoji: 🌕 +colorFrom: purple +colorTo: red +sdk: gradio +sdk_version: 5.17.0 +app_file: app.py +pinned: false +license: mit +short_description: Real-time captions with Moonshine ONNX +tags: [webrtc, websocket, gradio, secret|TWILIO_ACCOUNT_SID, secret|TWILIO_ACCOUNT_SID, secret|TWILIO_AUTH_TOKEN] +models: [onnx-community/moonshine-base-ONNX, UsefulSensors/moonshine-base] +--- + +Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference \ No newline at end of file diff --git a/demo/moonshine_live/app.py b/demo/moonshine_live/app.py new file mode 100644 index 0000000..f6db735 --- /dev/null +++ b/demo/moonshine_live/app.py @@ -0,0 +1,73 @@ +from functools import lru_cache +from typing import Generator, Literal + +import gradio as gr +import numpy as np +from dotenv import load_dotenv +from fastrtc import ( + AdditionalOutputs, + ReplyOnPause, + Stream, + audio_to_float32, + get_twilio_turn_credentials, +) +from moonshine_onnx import MoonshineOnnxModel, load_tokenizer +from numpy.typing import NDArray + +load_dotenv() + + +@lru_cache(maxsize=None) +def load_moonshine( + model_name: Literal["moonshine/base", "moonshine/tiny"], +) -> MoonshineOnnxModel: + return MoonshineOnnxModel(model_name=model_name) + + +tokenizer = load_tokenizer() + + +def stt( + audio: tuple[int, NDArray[np.int16 | np.float32]], + model_name: Literal["moonshine/base", "moonshine/tiny"], + captions: str, +) -> Generator[AdditionalOutputs, None, None]: + moonshine = load_moonshine(model_name) + sr, audio_np = audio # type: ignore + if audio_np.dtype == np.int16: + audio_np = audio_to_float32(audio) + if audio_np.ndim == 1: + audio_np = audio_np.reshape(1, -1) + tokens = moonshine.generate(audio_np) + yield AdditionalOutputs( + (captions + "\n" + tokenizer.decode_batch(tokens)[0]).strip() + ) + + +captions = gr.Textbox(label="Captions") +stream = Stream( + ReplyOnPause(stt, input_sample_rate=16000), + modality="audio", + mode="send", + ui_args={ + "title": "Live Captions by Moonshine", + "icon": "default-favicon.ico", + "icon_button_color": "#5c5c5c", + "pulse_color": "#a7c6fc", + "icon_radius": 0, + }, + rtc_configuration=get_twilio_turn_credentials(), + additional_inputs=[ + gr.Radio( + choices=["moonshine/base", "moonshine/tiny"], + value="moonshine/base", + label="Model", + ), + captions, + ], + additional_outputs=[captions], + additional_outputs_handler=lambda prev, current: (prev + "\n" + current).strip(), +) + +if __name__ == "__main__": + stream.ui.launch() diff --git a/demo/moonshine_live/default-favicon.ico b/demo/moonshine_live/default-favicon.ico new file mode 100644 index 0000000..0a7c372 Binary files /dev/null and b/demo/moonshine_live/default-favicon.ico differ diff --git a/demo/moonshine_live/requirements.txt b/demo/moonshine_live/requirements.txt new file mode 100644 index 0000000..acde84b --- /dev/null +++ b/demo/moonshine_live/requirements.txt @@ -0,0 +1,3 @@ +fastrtc[vad] +useful-moonshine-onnx@git+https://git@github.com/usefulsensors/moonshine.git#subdirectory=moonshine-onnx +twilio \ No newline at end of file diff --git a/demo/nextjs_voice_chat/README.md b/demo/nextjs_voice_chat/README.md new file mode 100644 index 0000000..3e3dce5 --- /dev/null +++ b/demo/nextjs_voice_chat/README.md @@ -0,0 +1,74 @@ +# FastRTC POC +A simple POC for a fast real-time voice chat application using FastAPI and FastRTC by [rohanprichard](https://github.com/rohanprichard). I wanted to make one as an example with more production-ready languages, rather than just Gradio. + +## Setup +1. Set your API keys in an `.env` file based on the `.env.example` file +2. Create a virtual environment and install the dependencies + ```bash + python3 -m venv env + source env/bin/activate + pip install -r requirements.txt + ``` + +3. Run the server + ```bash + ./run.sh + ``` +4. Navigate into the frontend directory in another terminal + ```bash + cd frontend/fastrtc-demo + ``` +5. Run the frontend + ```bash + npm install + npm run dev + ``` +6. Go to the URL and click the microphone icon to start chatting! + +7. Reset chats by clicking the trash button on the bottom right + +## Notes +You can choose to not install the requirements for TTS and STT by removing the `[tts, stt]` from the specifier in the `requirements.txt` file. + +- The STT is currently using the ElevenLabs API. +- The LLM is currently using the OpenAI API. +- The TTS is currently using the ElevenLabs API. +- The VAD is currently using the Silero VAD model. +- You may need to install ffmpeg if you get errors in STT + +The prompt can be changed in the `backend/server.py` file and modified as you like. + +### Audio Parameters + +#### AlgoOptions + +- **audio_chunk_duration**: Length of audio chunks in seconds. Smaller values allow for faster processing but may be less accurate. +- **started_talking_threshold**: If a chunk has more than this many seconds of speech, the system considers that the user has started talking. +- **speech_threshold**: After the user has started speaking, if a chunk has less than this many seconds of speech, the system considers that the user has paused. + +#### SileroVadOptions + +- **threshold**: Speech probability threshold (0.0-1.0). Values above this are considered speech. Higher values are more strict. +- **min_speech_duration_ms**: Speech segments shorter than this (in milliseconds) are filtered out. +- **min_silence_duration_ms**: The system waits for this duration of silence (in milliseconds) before considering speech to be finished. +- **speech_pad_ms**: Padding added to both ends of detected speech segments to prevent cutting off words. +- **max_speech_duration_s**: Maximum allowed duration for a speech segment in seconds. Prevents indefinite listening. + +### Tuning Recommendations + +- If the AI interrupts you too early: + - Increase `min_silence_duration_ms` + - Increase `speech_threshold` + - Increase `speech_pad_ms` + +- If the AI is slow to respond after you finish speaking: + - Decrease `min_silence_duration_ms` + - Decrease `speech_threshold` + +- If the system fails to detect some speech: + - Lower the `threshold` value + - Decrease `started_talking_threshold` + + +## Credits: +Credit for the UI components goes to Shadcn, Aceternity UI and Kokonut UI. diff --git a/demo/nextjs_voice_chat/backend/env.py b/demo/nextjs_voice_chat/backend/env.py new file mode 100644 index 0000000..f678f64 --- /dev/null +++ b/demo/nextjs_voice_chat/backend/env.py @@ -0,0 +1,7 @@ +from dotenv import load_dotenv +import os + +load_dotenv() + +LLM_API_KEY = os.getenv("LLM_API_KEY") +ELEVENLABS_API_KEY = os.getenv("ELEVENLABS_API_KEY") diff --git a/demo/nextjs_voice_chat/backend/server.py b/demo/nextjs_voice_chat/backend/server.py new file mode 100644 index 0000000..f0a1eb1 --- /dev/null +++ b/demo/nextjs_voice_chat/backend/server.py @@ -0,0 +1,129 @@ +import fastapi +from fastrtc import ReplyOnPause, Stream, AlgoOptions, SileroVadOptions +from fastrtc.utils import audio_to_bytes +from openai import OpenAI +import logging +import time +from fastapi.middleware.cors import CORSMiddleware +from elevenlabs import VoiceSettings, stream +from elevenlabs.client import ElevenLabs +import numpy as np + +from .env import LLM_API_KEY, ELEVENLABS_API_KEY + + +sys_prompt = """ +You are a helpful assistant. You are witty, engaging and fun. You love being interactive with the user. +You also can add minimalistic utterances like 'uh-huh' or 'mm-hmm' to the conversation to make it more natural. However, only vocalization are allowed, no actions or other non-vocal sounds. +Begin a conversation with a self-deprecating joke like 'I'm not sure if I'm ready for this...' or 'I bet you already regret clicking that button...' +""" + +messages = [{"role": "system", "content": sys_prompt}] + +openai_client = OpenAI(api_key=LLM_API_KEY) + +elevenlabs_client = ElevenLabs(api_key=ELEVENLABS_API_KEY) + +logging.basicConfig(level=logging.INFO) + + +def echo(audio): + stt_time = time.time() + + logging.info("Performing STT") + + transcription = elevenlabs_client.speech_to_text.convert( + file=audio_to_bytes(audio), + model_id="scribe_v1", + tag_audio_events=False, + language_code="eng", + diarize=False, + ) + prompt = transcription.text + if prompt == "": + logging.info("STT returned empty string") + return + logging.info(f"STT response: {prompt}") + + messages.append({"role": "user", "content": prompt}) + + logging.info(f"STT took {time.time() - stt_time} seconds") + + llm_time = time.time() + + def text_stream(): + global full_response + full_response = "" + + response = openai_client.chat.completions.create( + model="gpt-3.5-turbo", messages=messages, max_tokens=200, stream=True + ) + + for chunk in response: + if chunk.choices[0].finish_reason == "stop": + break + if chunk.choices[0].delta.content: + full_response += chunk.choices[0].delta.content + yield chunk.choices[0].delta.content + + audio_stream = elevenlabs_client.generate( + text=text_stream(), + voice="Rachel", # Cassidy is also really good + voice_settings=VoiceSettings( + similarity_boost=0.9, stability=0.6, style=0.4, speed=1 + ), + model="eleven_multilingual_v2", + output_format="pcm_24000", + stream=True, + ) + + for audio_chunk in audio_stream: + audio_array = ( + np.frombuffer(audio_chunk, dtype=np.int16).astype(np.float32) / 32768.0 + ) + yield (24000, audio_array) + + messages.append({"role": "assistant", "content": full_response + " "}) + logging.info(f"LLM response: {full_response}") + logging.info(f"LLM took {time.time() - llm_time} seconds") + + +stream = Stream( + ReplyOnPause( + echo, + algo_options=AlgoOptions( + audio_chunk_duration=0.5, + started_talking_threshold=0.1, + speech_threshold=0.03, + ), + model_options=SileroVadOptions( + threshold=0.75, + min_speech_duration_ms=250, + min_silence_duration_ms=1500, + speech_pad_ms=400, + max_speech_duration_s=15, + ), + ), + modality="audio", + mode="send-receive", +) + +app = fastapi.FastAPI() + +app.add_middleware( + CORSMiddleware, + allow_origins=["*"], + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], +) + +stream.mount(app) + + +@app.get("/reset") +async def reset(): + global messages + logging.info("Resetting chat") + messages = [{"role": "system", "content": sys_prompt}] + return {"status": "success"} diff --git a/demo/nextjs_voice_chat/frontend/fastrtc-demo/.gitignore b/demo/nextjs_voice_chat/frontend/fastrtc-demo/.gitignore new file mode 100644 index 0000000..5ef6a52 --- /dev/null +++ b/demo/nextjs_voice_chat/frontend/fastrtc-demo/.gitignore @@ -0,0 +1,41 @@ +# See https://help.github.com/articles/ignoring-files/ for more about ignoring files. + +# dependencies +/node_modules +/.pnp +.pnp.* +.yarn/* +!.yarn/patches +!.yarn/plugins +!.yarn/releases +!.yarn/versions + +# testing +/coverage + +# next.js +/.next/ +/out/ + +# production +/build + +# misc +.DS_Store +*.pem + +# debug +npm-debug.log* +yarn-debug.log* +yarn-error.log* +.pnpm-debug.log* + +# env files (can opt-in for committing if needed) +.env* + +# vercel +.vercel + +# typescript +*.tsbuildinfo +next-env.d.ts diff --git a/demo/nextjs_voice_chat/frontend/fastrtc-demo/README.md b/demo/nextjs_voice_chat/frontend/fastrtc-demo/README.md new file mode 100644 index 0000000..e215bc4 --- /dev/null +++ b/demo/nextjs_voice_chat/frontend/fastrtc-demo/README.md @@ -0,0 +1,36 @@ +This is a [Next.js](https://nextjs.org) project bootstrapped with [`create-next-app`](https://nextjs.org/docs/app/api-reference/cli/create-next-app). + +## Getting Started + +First, run the development server: + +```bash +npm run dev +# or +yarn dev +# or +pnpm dev +# or +bun dev +``` + +Open [http://localhost:3000](http://localhost:3000) with your browser to see the result. + +You can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file. + +This project uses [`next/font`](https://nextjs.org/docs/app/building-your-application/optimizing/fonts) to automatically optimize and load [Geist](https://vercel.com/font), a new font family for Vercel. + +## Learn More + +To learn more about Next.js, take a look at the following resources: + +- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API. +- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial. + +You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js) - your feedback and contributions are welcome! + +## Deploy on Vercel + +The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js. + +Check out our [Next.js deployment documentation](https://nextjs.org/docs/app/building-your-application/deploying) for more details. diff --git a/demo/nextjs_voice_chat/frontend/fastrtc-demo/app/favicon.ico b/demo/nextjs_voice_chat/frontend/fastrtc-demo/app/favicon.ico new file mode 100644 index 0000000..718d6fe Binary files /dev/null and b/demo/nextjs_voice_chat/frontend/fastrtc-demo/app/favicon.ico differ diff --git a/demo/nextjs_voice_chat/frontend/fastrtc-demo/app/globals.css b/demo/nextjs_voice_chat/frontend/fastrtc-demo/app/globals.css new file mode 100644 index 0000000..7ae6ba4 --- /dev/null +++ b/demo/nextjs_voice_chat/frontend/fastrtc-demo/app/globals.css @@ -0,0 +1,130 @@ +@import "tailwindcss"; + +@plugin "tailwindcss-animate"; + +@custom-variant dark (&:is(.dark *)); + +@theme inline { + --color-background: var(--background); + --color-foreground: var(--foreground); + --font-sans: var(--font-geist-sans); + --font-mono: var(--font-geist-mono); + --color-sidebar-ring: var(--sidebar-ring); + --color-sidebar-border: var(--sidebar-border); + --color-sidebar-accent-foreground: var(--sidebar-accent-foreground); + --color-sidebar-accent: var(--sidebar-accent); + --color-sidebar-primary-foreground: var(--sidebar-primary-foreground); + --color-sidebar-primary: var(--sidebar-primary); + --color-sidebar-foreground: var(--sidebar-foreground); + --color-sidebar: var(--sidebar); + --color-chart-5: var(--chart-5); + --color-chart-4: var(--chart-4); + --color-chart-3: var(--chart-3); + --color-chart-2: var(--chart-2); + --color-chart-1: var(--chart-1); + --color-ring: var(--ring); + --color-input: var(--input); + --color-border: var(--border); + --color-destructive-foreground: var(--destructive-foreground); + --color-destructive: var(--destructive); + --color-accent-foreground: var(--accent-foreground); + --color-accent: var(--accent); + --color-muted-foreground: var(--muted-foreground); + --color-muted: var(--muted); + --color-secondary-foreground: var(--secondary-foreground); + --color-secondary: var(--secondary); + --color-primary-foreground: var(--primary-foreground); + --color-primary: var(--primary); + --color-popover-foreground: var(--popover-foreground); + --color-popover: var(--popover); + --color-card-foreground: var(--card-foreground); + --color-card: var(--card); + --radius-sm: calc(var(--radius) - 4px); + --radius-md: calc(var(--radius) - 2px); + --radius-lg: var(--radius); + --radius-xl: calc(var(--radius) + 4px); +} + +:root { + --background: oklch(1 0 0); + --foreground: oklch(0.129 0.042 264.695); + --card: oklch(1 0 0); + --card-foreground: oklch(0.129 0.042 264.695); + --popover: oklch(1 0 0); + --popover-foreground: oklch(0.129 0.042 264.695); + --primary: oklch(0.208 0.042 265.755); + --primary-foreground: oklch(0.984 0.003 247.858); + --secondary: oklch(0.968 0.007 247.896); + --secondary-foreground: oklch(0.208 0.042 265.755); + --muted: oklch(0.968 0.007 247.896); + --muted-foreground: oklch(0.554 0.046 257.417); + --accent: oklch(0.968 0.007 247.896); + --accent-foreground: oklch(0.208 0.042 265.755); + --destructive: oklch(0.577 0.245 27.325); + --destructive-foreground: oklch(0.577 0.245 27.325); + --border: oklch(0.929 0.013 255.508); + --input: oklch(0.929 0.013 255.508); + --ring: oklch(0.704 0.04 256.788); + --chart-1: oklch(0.646 0.222 41.116); + --chart-2: oklch(0.6 0.118 184.704); + --chart-3: oklch(0.398 0.07 227.392); + --chart-4: oklch(0.828 0.189 84.429); + --chart-5: oklch(0.769 0.188 70.08); + --radius: 0.625rem; + --sidebar: oklch(0.984 0.003 247.858); + --sidebar-foreground: oklch(0.129 0.042 264.695); + --sidebar-primary: oklch(0.208 0.042 265.755); + --sidebar-primary-foreground: oklch(0.984 0.003 247.858); + --sidebar-accent: oklch(0.968 0.007 247.896); + --sidebar-accent-foreground: oklch(0.208 0.042 265.755); + --sidebar-border: oklch(0.929 0.013 255.508); + --sidebar-ring: oklch(0.704 0.04 256.788); +} + +.dark { + --background: oklch(0.129 0.042 264.695); + --foreground: oklch(0.984 0.003 247.858); + --card: oklch(0.129 0.042 264.695); + --card-foreground: oklch(0.984 0.003 247.858); + --popover: oklch(0.129 0.042 264.695); + --popover-foreground: oklch(0.984 0.003 247.858); + --primary: oklch(0.984 0.003 247.858); + --primary-foreground: oklch(0.208 0.042 265.755); + --secondary: oklch(0.279 0.041 260.031); + --secondary-foreground: oklch(0.984 0.003 247.858); + --muted: oklch(0.279 0.041 260.031); + --muted-foreground: oklch(0.704 0.04 256.788); + --accent: oklch(0.279 0.041 260.031); + --accent-foreground: oklch(0.984 0.003 247.858); + --destructive: oklch(0.396 0.141 25.723); + --destructive-foreground: oklch(0.637 0.237 25.331); + --border: oklch(0.279 0.041 260.031); + --input: oklch(0.279 0.041 260.031); + --ring: oklch(0.446 0.043 257.281); + --chart-1: oklch(0.488 0.243 264.376); + --chart-2: oklch(0.696 0.17 162.48); + --chart-3: oklch(0.769 0.188 70.08); + --chart-4: oklch(0.627 0.265 303.9); + --chart-5: oklch(0.645 0.246 16.439); + --sidebar: oklch(0.208 0.042 265.755); + --sidebar-foreground: oklch(0.984 0.003 247.858); + --sidebar-primary: oklch(0.488 0.243 264.376); + --sidebar-primary-foreground: oklch(0.984 0.003 247.858); + --sidebar-accent: oklch(0.279 0.041 260.031); + --sidebar-accent-foreground: oklch(0.984 0.003 247.858); + --sidebar-border: oklch(0.279 0.041 260.031); + --sidebar-ring: oklch(0.446 0.043 257.281); +} + +@layer base { + * { + @apply border-border outline-ring/50; + } + body { + @apply bg-background text-foreground; + } +} + +.no-transitions * { + transition: none !important; +} diff --git a/demo/nextjs_voice_chat/frontend/fastrtc-demo/app/layout.tsx b/demo/nextjs_voice_chat/frontend/fastrtc-demo/app/layout.tsx new file mode 100644 index 0000000..428c1d1 --- /dev/null +++ b/demo/nextjs_voice_chat/frontend/fastrtc-demo/app/layout.tsx @@ -0,0 +1,44 @@ +import type { Metadata } from "next"; +import { Geist, Geist_Mono } from "next/font/google"; +import "./globals.css"; +import { ThemeProvider } from "@/components/theme-provider"; +import { ThemeTransition } from "@/components/ui/theme-transition"; + +const geistSans = Geist({ + variable: "--font-geist-sans", + subsets: ["latin"], +}); + +const geistMono = Geist_Mono({ + variable: "--font-geist-mono", + subsets: ["latin"], +}); + +export const metadata: Metadata = { + title: "FastRTC Demo", + description: "Interactive WebRTC demo with audio visualization", +}; + +export default function RootLayout({ + children, +}: Readonly<{ + children: React.ReactNode; +}>) { + return ( + + + + {children} + + + + + ); +} diff --git a/demo/nextjs_voice_chat/frontend/fastrtc-demo/app/page.tsx b/demo/nextjs_voice_chat/frontend/fastrtc-demo/app/page.tsx new file mode 100644 index 0000000..fe41cea --- /dev/null +++ b/demo/nextjs_voice_chat/frontend/fastrtc-demo/app/page.tsx @@ -0,0 +1,16 @@ +import { BackgroundCircleProvider } from "@/components/background-circle-provider"; +import { ThemeToggle } from "@/components/ui/theme-toggle"; +import { ResetChat } from "@/components/ui/reset-chat"; +export default function Home() { + return ( +
+ +
+ +
+
+ +
+
+ ); +} diff --git a/demo/nextjs_voice_chat/frontend/fastrtc-demo/components.json b/demo/nextjs_voice_chat/frontend/fastrtc-demo/components.json new file mode 100644 index 0000000..a08feaa --- /dev/null +++ b/demo/nextjs_voice_chat/frontend/fastrtc-demo/components.json @@ -0,0 +1,21 @@ +{ + "$schema": "https://ui.shadcn.com/schema.json", + "style": "new-york", + "rsc": true, + "tsx": true, + "tailwind": { + "config": "", + "css": "app/globals.css", + "baseColor": "slate", + "cssVariables": true, + "prefix": "" + }, + "aliases": { + "components": "@/components", + "utils": "@/lib/utils", + "ui": "@/components/ui", + "lib": "@/lib", + "hooks": "@/hooks" + }, + "iconLibrary": "lucide" +} \ No newline at end of file diff --git a/demo/nextjs_voice_chat/frontend/fastrtc-demo/components/background-circle-provider.tsx b/demo/nextjs_voice_chat/frontend/fastrtc-demo/components/background-circle-provider.tsx new file mode 100644 index 0000000..eb0925b --- /dev/null +++ b/demo/nextjs_voice_chat/frontend/fastrtc-demo/components/background-circle-provider.tsx @@ -0,0 +1,123 @@ +"use client" + +import { useState, useEffect, useRef, useCallback } from "react"; +import { BackgroundCircles } from "@/components/ui/background-circles"; +import { AIVoiceInput } from "@/components/ui/ai-voice-input"; +import { WebRTCClient } from "@/lib/webrtc-client"; + +export function BackgroundCircleProvider() { + const [currentVariant, setCurrentVariant] = + useState("octonary"); + const [isConnected, setIsConnected] = useState(false); + const [webrtcClient, setWebrtcClient] = useState(null); + const [audioLevel, setAudioLevel] = useState(0); + const audioRef = useRef(null); + + // Memoize callbacks to prevent recreation on each render + const handleConnected = useCallback(() => setIsConnected(true), []); + const handleDisconnected = useCallback(() => setIsConnected(false), []); + + const handleAudioStream = useCallback((stream: MediaStream) => { + if (audioRef.current) { + audioRef.current.srcObject = stream; + } + }, []); + + const handleAudioLevel = useCallback((level: number) => { + // Apply some smoothing to the audio level + setAudioLevel(prev => prev * 0.7 + level * 0.3); + }, []); + + // Get all available variants + const variants = Object.keys( + COLOR_VARIANTS + ) as (keyof typeof COLOR_VARIANTS)[]; + + // Function to change to the next color variant + const changeVariant = () => { + const currentIndex = variants.indexOf(currentVariant); + const nextVariant = variants[(currentIndex + 1) % variants.length]; + setCurrentVariant(nextVariant); + }; + + useEffect(() => { + // Initialize WebRTC client with memoized callbacks + const client = new WebRTCClient({ + onConnected: handleConnected, + onDisconnected: handleDisconnected, + onAudioStream: handleAudioStream, + onAudioLevel: handleAudioLevel + }); + setWebrtcClient(client); + + return () => { + client.disconnect(); + }; + }, [handleConnected, handleDisconnected, handleAudioStream, handleAudioLevel]); + + const handleStart = () => { + webrtcClient?.connect(); + }; + + const handleStop = () => { + webrtcClient?.disconnect(); + }; + + return ( +
+ +
+ +
+
+ ); +} + +export default { BackgroundCircleProvider } + +const COLOR_VARIANTS = { + primary: { + border: [ + "border-emerald-500/60", + "border-cyan-400/50", + "border-slate-600/30", + ], + gradient: "from-emerald-500/30", + }, + secondary: { + border: [ + "border-violet-500/60", + "border-fuchsia-400/50", + "border-slate-600/30", + ], + gradient: "from-violet-500/30", + }, + senary: { + border: [ + "border-blue-500/60", + "border-sky-400/50", + "border-slate-600/30", + ], + gradient: "from-blue-500/30", + }, // blue + octonary: { + border: [ + "border-red-500/60", + "border-rose-400/50", + "border-slate-600/30", + ], + gradient: "from-red-500/30", + }, +} as const; \ No newline at end of file diff --git a/demo/nextjs_voice_chat/frontend/fastrtc-demo/components/theme-provider.tsx b/demo/nextjs_voice_chat/frontend/fastrtc-demo/components/theme-provider.tsx new file mode 100644 index 0000000..896e023 --- /dev/null +++ b/demo/nextjs_voice_chat/frontend/fastrtc-demo/components/theme-provider.tsx @@ -0,0 +1,101 @@ +"use client"; + +import { createContext, useContext, useEffect, useState } from "react"; + +type Theme = "light" | "dark" | "system"; + +type ThemeProviderProps = { + children: React.ReactNode; + defaultTheme?: Theme; + storageKey?: string; + attribute?: string; + enableSystem?: boolean; + disableTransitionOnChange?: boolean; +}; + +type ThemeProviderState = { + theme: Theme; + setTheme: (theme: Theme) => void; +}; + +const initialState: ThemeProviderState = { + theme: "system", + setTheme: () => null, +}; + +const ThemeProviderContext = createContext(initialState); + +export function ThemeProvider({ + children, + defaultTheme = "system", + storageKey = "theme", + attribute = "class", + enableSystem = true, + disableTransitionOnChange = false, + ...props +}: ThemeProviderProps) { + const [theme, setTheme] = useState(defaultTheme); + + useEffect(() => { + const savedTheme = localStorage.getItem(storageKey) as Theme | null; + + if (savedTheme) { + setTheme(savedTheme); + } else if (defaultTheme === "system" && enableSystem) { + const systemTheme = window.matchMedia("(prefers-color-scheme: dark)").matches + ? "dark" + : "light"; + setTheme(systemTheme); + } + }, [defaultTheme, storageKey, enableSystem]); + + useEffect(() => { + const root = window.document.documentElement; + + if (disableTransitionOnChange) { + root.classList.add("no-transitions"); + + // Force a reflow + window.getComputedStyle(root).getPropertyValue("opacity"); + + setTimeout(() => { + root.classList.remove("no-transitions"); + }, 0); + } + + root.classList.remove("light", "dark"); + + if (theme === "system" && enableSystem) { + const systemTheme = window.matchMedia("(prefers-color-scheme: dark)").matches + ? "dark" + : "light"; + root.classList.add(systemTheme); + } else { + root.classList.add(theme); + } + + localStorage.setItem(storageKey, theme); + }, [theme, storageKey, enableSystem, disableTransitionOnChange]); + + const value = { + theme, + setTheme: (theme: Theme) => { + setTheme(theme); + }, + }; + + return ( + + {children} + + ); +} + +export const useTheme = () => { + const context = useContext(ThemeProviderContext); + + if (context === undefined) + throw new Error("useTheme must be used within a ThemeProvider"); + + return context; +}; diff --git a/demo/nextjs_voice_chat/frontend/fastrtc-demo/components/ui/ai-voice-input.tsx b/demo/nextjs_voice_chat/frontend/fastrtc-demo/components/ui/ai-voice-input.tsx new file mode 100644 index 0000000..f3558b8 --- /dev/null +++ b/demo/nextjs_voice_chat/frontend/fastrtc-demo/components/ui/ai-voice-input.tsx @@ -0,0 +1,114 @@ +"use client"; + +import { Mic, Square } from "lucide-react"; +import { useState, useEffect } from "react"; +import { cn } from "@/lib/utils"; + +interface AIVoiceInputProps { + onStart?: () => void; + onStop?: (duration: number) => void; + isConnected?: boolean; + className?: string; +} + +export function AIVoiceInput({ + onStart, + onStop, + isConnected = false, + className +}: AIVoiceInputProps) { + const [active, setActive] = useState(false); + const [time, setTime] = useState(0); + const [isClient, setIsClient] = useState(false); + const [status, setStatus] = useState<'disconnected' | 'connecting' | 'connected'>('disconnected'); + + useEffect(() => { + setIsClient(true); + }, []); + + useEffect(() => { + let intervalId: NodeJS.Timeout; + + if (active) { + intervalId = setInterval(() => { + setTime((t) => t + 1); + }, 1000); + } else { + setTime(0); + } + + return () => clearInterval(intervalId); + }, [active]); + + useEffect(() => { + if (isConnected) { + setStatus('connected'); + setActive(true); + } else { + setStatus('disconnected'); + setActive(false); + } + }, [isConnected]); + + const formatTime = (seconds: number) => { + const mins = Math.floor(seconds / 60); + const secs = seconds % 60; + return `${mins.toString().padStart(2, "0")}:${secs.toString().padStart(2, "0")}`; + }; + + const handleStart = () => { + setStatus('connecting'); + onStart?.(); + }; + + const handleStop = () => { + onStop?.(time); + setStatus('disconnected'); + }; + + return ( +
+
+
+ {status === 'connected' ? 'Connected' : status === 'connecting' ? 'Connecting...' : 'Disconnected'} +
+ + + + + {formatTime(time)} + +
+
+ ); +} \ No newline at end of file diff --git a/demo/nextjs_voice_chat/frontend/fastrtc-demo/components/ui/background-circles.tsx b/demo/nextjs_voice_chat/frontend/fastrtc-demo/components/ui/background-circles.tsx new file mode 100644 index 0000000..c899496 --- /dev/null +++ b/demo/nextjs_voice_chat/frontend/fastrtc-demo/components/ui/background-circles.tsx @@ -0,0 +1,309 @@ +"use client"; + +import { motion } from "framer-motion"; +import clsx from "clsx"; +import { useState, useEffect } from "react"; + +interface BackgroundCirclesProps { + title?: string; + description?: string; + className?: string; + variant?: keyof typeof COLOR_VARIANTS; + audioLevel?: number; + isActive?: boolean; +} + +const COLOR_VARIANTS = { + primary: { + border: [ + "border-emerald-500/60", + "border-cyan-400/50", + "border-slate-600/30", + ], + gradient: "from-emerald-500/30", + }, + secondary: { + border: [ + "border-violet-500/60", + "border-fuchsia-400/50", + "border-slate-600/30", + ], + gradient: "from-violet-500/30", + }, + tertiary: { + border: [ + "border-orange-500/60", + "border-yellow-400/50", + "border-slate-600/30", + ], + gradient: "from-orange-500/30", + }, + quaternary: { + border: [ + "border-purple-500/60", + "border-pink-400/50", + "border-slate-600/30", + ], + gradient: "from-purple-500/30", + }, + quinary: { + border: [ + "border-red-500/60", + "border-rose-400/50", + "border-slate-600/30", + ], + gradient: "from-red-500/30", + }, // red + senary: { + border: [ + "border-blue-500/60", + "border-sky-400/50", + "border-slate-600/30", + ], + gradient: "from-blue-500/30", + }, // blue + septenary: { + border: [ + "border-gray-500/60", + "border-gray-400/50", + "border-slate-600/30", + ], + gradient: "from-gray-500/30", + }, + octonary: { + border: [ + "border-red-500/60", + "border-rose-400/50", + "border-slate-600/30", + ], + gradient: "from-red-500/30", + }, +} as const; + +const AnimatedGrid = () => ( + +
+ +); + +export function BackgroundCircles({ + title = "", + description = "", + className, + variant = "octonary", + audioLevel = 0, + isActive = false, +}: BackgroundCirclesProps) { + const variantStyles = COLOR_VARIANTS[variant]; + const [animationParams, setAnimationParams] = useState({ + scale: 1, + duration: 5, + intensity: 0 + }); + const [isLoaded, setIsLoaded] = useState(false); + + // Initial page load animation + useEffect(() => { + // Small delay to ensure the black screen is visible first + const timer = setTimeout(() => { + setIsLoaded(true); + }, 300); + + return () => clearTimeout(timer); + }, []); + + // Update animation based on audio level + useEffect(() => { + if (isActive && audioLevel > 0) { + // Simple enhancement of audio level for more dramatic effect + const enhancedLevel = Math.min(1, audioLevel * 1.5); + + setAnimationParams({ + scale: 1 + enhancedLevel * 0.3, + duration: Math.max(2, 5 - enhancedLevel * 3), + intensity: enhancedLevel + }); + } else if (animationParams.intensity > 0) { + // Only reset if we need to (prevents unnecessary updates) + const timer = setTimeout(() => { + setAnimationParams({ + scale: 1, + duration: 5, + intensity: 0 + }); + }, 300); + + return () => clearTimeout(timer); + } + }, [audioLevel, isActive, animationParams.intensity]); + + return ( + <> + {/* Initial black overlay that fades out */} + + +
+ + + {[0, 1, 2].map((i) => ( + +
+ + ))} + + +
+ + + + {/* Additional glow that appears only during high audio levels */} + {isActive && animationParams.intensity > 0.4 && ( + + )} +
+
+ + ); +} + +export function DemoCircles() { + const [currentVariant, setCurrentVariant] = + useState("octonary"); + + const variants = Object.keys( + COLOR_VARIANTS + ) as (keyof typeof COLOR_VARIANTS)[]; + + function getNextVariant() { + const currentIndex = variants.indexOf(currentVariant); + const nextVariant = variants[(currentIndex + 1) % variants.length]; + return nextVariant; + } + + return ( + <> + +
+ +
+ + ); +} diff --git a/demo/nextjs_voice_chat/frontend/fastrtc-demo/components/ui/reset-chat.tsx b/demo/nextjs_voice_chat/frontend/fastrtc-demo/components/ui/reset-chat.tsx new file mode 100644 index 0000000..b53a21a --- /dev/null +++ b/demo/nextjs_voice_chat/frontend/fastrtc-demo/components/ui/reset-chat.tsx @@ -0,0 +1,18 @@ +"use client" + +import { Trash } from "lucide-react" + +export function ResetChat() { + return ( + + ) +} + diff --git a/demo/nextjs_voice_chat/frontend/fastrtc-demo/components/ui/theme-toggle.tsx b/demo/nextjs_voice_chat/frontend/fastrtc-demo/components/ui/theme-toggle.tsx new file mode 100644 index 0000000..a6ef0d8 --- /dev/null +++ b/demo/nextjs_voice_chat/frontend/fastrtc-demo/components/ui/theme-toggle.tsx @@ -0,0 +1,61 @@ +"use client"; + +import { useTheme } from "@/components/theme-provider"; +import { cn } from "@/lib/utils"; +import { Moon, Sun } from "lucide-react"; +import { useRef } from "react"; + +interface ThemeToggleProps { + className?: string; +} + +export function ThemeToggle({ className }: ThemeToggleProps) { + const { theme } = useTheme(); + const buttonRef = useRef(null); + + const toggleTheme = () => { + // Instead of directly changing the theme, dispatch a custom event + const newTheme = theme === "light" ? "dark" : "light"; + + // Dispatch custom event with the new theme + window.dispatchEvent( + new CustomEvent('themeToggleRequest', { + detail: { theme: newTheme } + }) + ); + }; + + return ( + + ); +} \ No newline at end of file diff --git a/demo/nextjs_voice_chat/frontend/fastrtc-demo/components/ui/theme-transition.tsx b/demo/nextjs_voice_chat/frontend/fastrtc-demo/components/ui/theme-transition.tsx new file mode 100644 index 0000000..caf9601 --- /dev/null +++ b/demo/nextjs_voice_chat/frontend/fastrtc-demo/components/ui/theme-transition.tsx @@ -0,0 +1,120 @@ +"use client"; + +import { useTheme } from "@/components/theme-provider"; +import { useEffect, useState } from "react"; +import { motion, AnimatePresence } from "framer-motion"; + +interface ThemeTransitionProps { + className?: string; +} + +export function ThemeTransition({ className }: ThemeTransitionProps) { + const { theme, setTheme } = useTheme(); + const [position, setPosition] = useState({ x: 0, y: 0 }); + const [isAnimating, setIsAnimating] = useState(false); + const [pendingTheme, setPendingTheme] = useState(null); + const [visualTheme, setVisualTheme] = useState(theme); + + // Track mouse/touch position for click events + useEffect(() => { + const handleMouseMove = (e: MouseEvent) => { + setPosition({ x: e.clientX, y: e.clientY }); + }; + + const handleTouchMove = (e: TouchEvent) => { + if (e.touches[0]) { + setPosition({ x: e.touches[0].clientX, y: e.touches[0].clientY }); + } + }; + + window.addEventListener("mousemove", handleMouseMove); + window.addEventListener("touchmove", handleTouchMove); + + return () => { + window.removeEventListener("mousemove", handleMouseMove); + window.removeEventListener("touchmove", handleTouchMove); + }; + }, []); + + // Listen for theme toggle requests + useEffect(() => { + // Custom event for theme toggle requests + const handleThemeToggle = (e: CustomEvent) => { + if (isAnimating) return; // Prevent multiple animations + + const newTheme = e.detail.theme; + if (newTheme === theme) return; + + // Store the pending theme but don't apply it yet + setPendingTheme(newTheme); + setIsAnimating(true); + + // The actual theme will be applied mid-animation + }; + + window.addEventListener('themeToggleRequest' as any, handleThemeToggle as EventListener); + + return () => { + window.removeEventListener('themeToggleRequest' as any, handleThemeToggle as EventListener); + }; + }, [theme, isAnimating]); + + // Apply the theme change mid-animation + useEffect(() => { + if (isAnimating && pendingTheme) { + // Set visual theme immediately for the animation + setVisualTheme(pendingTheme); + + // Apply the actual theme change after a delay (mid-animation) + const timer = setTimeout(() => { + setTheme(pendingTheme as any); + }, 400); // Half of the animation duration + + // End the animation after it completes + const endTimer = setTimeout(() => { + setIsAnimating(false); + setPendingTheme(null); + }, 1000); // Match with animation duration + + return () => { + clearTimeout(timer); + clearTimeout(endTimer); + }; + } + }, [isAnimating, pendingTheme, setTheme]); + + return ( + + {isAnimating && ( + + + + )} + + ); +} \ No newline at end of file diff --git a/demo/nextjs_voice_chat/frontend/fastrtc-demo/eslint.config.mjs b/demo/nextjs_voice_chat/frontend/fastrtc-demo/eslint.config.mjs new file mode 100644 index 0000000..521f586 --- /dev/null +++ b/demo/nextjs_voice_chat/frontend/fastrtc-demo/eslint.config.mjs @@ -0,0 +1,28 @@ +import { dirname } from "path"; +import { fileURLToPath } from "url"; +import { FlatCompat } from "@eslint/eslintrc"; + +const __filename = fileURLToPath(import.meta.url); +const __dirname = dirname(__filename); + +const compat = new FlatCompat({ + baseDirectory: __dirname, +}); + +const eslintConfig = [ + ...compat.extends("next/core-web-vitals", "next/typescript"), + { + rules: { + "no-unused-vars": "off", + "no-explicit-any": "off", + "no-console": "off", + "no-debugger": "off", + "eqeqeq": "off", + "curly": "off", + "quotes": "off", + "semi": "off", + }, + }, +]; + +export default eslintConfig; diff --git a/demo/nextjs_voice_chat/frontend/fastrtc-demo/lib/utils.ts b/demo/nextjs_voice_chat/frontend/fastrtc-demo/lib/utils.ts new file mode 100644 index 0000000..bd0c391 --- /dev/null +++ b/demo/nextjs_voice_chat/frontend/fastrtc-demo/lib/utils.ts @@ -0,0 +1,6 @@ +import { clsx, type ClassValue } from "clsx" +import { twMerge } from "tailwind-merge" + +export function cn(...inputs: ClassValue[]) { + return twMerge(clsx(inputs)) +} diff --git a/demo/nextjs_voice_chat/frontend/fastrtc-demo/lib/webrtc-client.ts b/demo/nextjs_voice_chat/frontend/fastrtc-demo/lib/webrtc-client.ts new file mode 100644 index 0000000..72ea3ac --- /dev/null +++ b/demo/nextjs_voice_chat/frontend/fastrtc-demo/lib/webrtc-client.ts @@ -0,0 +1,189 @@ +interface WebRTCClientOptions { + onConnected?: () => void; + onDisconnected?: () => void; + onMessage?: (message: any) => void; + onAudioStream?: (stream: MediaStream) => void; + onAudioLevel?: (level: number) => void; +} + +export class WebRTCClient { + private peerConnection: RTCPeerConnection | null = null; + private mediaStream: MediaStream | null = null; + private dataChannel: RTCDataChannel | null = null; + private options: WebRTCClientOptions; + private audioContext: AudioContext | null = null; + private analyser: AnalyserNode | null = null; + private dataArray: Uint8Array | null = null; + private animationFrameId: number | null = null; + + constructor(options: WebRTCClientOptions = {}) { + this.options = options; + } + + async connect() { + try { + this.peerConnection = new RTCPeerConnection(); + + // Get user media + try { + this.mediaStream = await navigator.mediaDevices.getUserMedia({ + audio: true + }); + } catch (mediaError: any) { + console.error('Media error:', mediaError); + if (mediaError.name === 'NotAllowedError') { + throw new Error('Microphone access denied. Please allow microphone access and try again.'); + } else if (mediaError.name === 'NotFoundError') { + throw new Error('No microphone detected. Please connect a microphone and try again.'); + } else { + throw mediaError; + } + } + + this.setupAudioAnalysis(); + + this.mediaStream.getTracks().forEach(track => { + if (this.peerConnection) { + this.peerConnection.addTrack(track, this.mediaStream!); + } + }); + + this.peerConnection.addEventListener('track', (event) => { + if (this.options.onAudioStream) { + this.options.onAudioStream(event.streams[0]); + } + }); + + this.dataChannel = this.peerConnection.createDataChannel('text'); + + this.dataChannel.addEventListener('message', (event) => { + try { + const message = JSON.parse(event.data); + console.log('Received message:', message); + + if (this.options.onMessage) { + this.options.onMessage(message); + } + } catch (error) { + console.error('Error parsing message:', error); + } + }); + + // Create and send offer + const offer = await this.peerConnection.createOffer(); + await this.peerConnection.setLocalDescription(offer); + + // Use same-origin request to avoid CORS preflight + const response = await fetch('http://localhost:8000/webrtc/offer', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'Accept': 'application/json' + }, + mode: 'cors', // Explicitly set CORS mode + credentials: 'same-origin', + body: JSON.stringify({ + sdp: offer.sdp, + type: offer.type, + webrtc_id: Math.random().toString(36).substring(7) + }) + }); + + const serverResponse = await response.json(); + await this.peerConnection.setRemoteDescription(serverResponse); + + if (this.options.onConnected) { + this.options.onConnected(); + } + } catch (error) { + console.error('Error connecting:', error); + this.disconnect(); + throw error; + } + } + + private setupAudioAnalysis() { + if (!this.mediaStream) return; + + try { + this.audioContext = new AudioContext(); + this.analyser = this.audioContext.createAnalyser(); + this.analyser.fftSize = 256; + + const source = this.audioContext.createMediaStreamSource(this.mediaStream); + source.connect(this.analyser); + + const bufferLength = this.analyser.frequencyBinCount; + this.dataArray = new Uint8Array(bufferLength); + + this.startAnalysis(); + } catch (error) { + console.error('Error setting up audio analysis:', error); + } + } + + private startAnalysis() { + if (!this.analyser || !this.dataArray || !this.options.onAudioLevel) return; + + // Add throttling to prevent too many updates + let lastUpdateTime = 0; + const throttleInterval = 100; // Only update every 100ms + + const analyze = () => { + this.analyser!.getByteFrequencyData(this.dataArray!); + + const currentTime = Date.now(); + // Only update if enough time has passed since last update + if (currentTime - lastUpdateTime > throttleInterval) { + // Calculate average volume level (0-1) + let sum = 0; + for (let i = 0; i < this.dataArray!.length; i++) { + sum += this.dataArray![i]; + } + const average = sum / this.dataArray!.length / 255; + + this.options.onAudioLevel!(average); + lastUpdateTime = currentTime; + } + + this.animationFrameId = requestAnimationFrame(analyze); + }; + + this.animationFrameId = requestAnimationFrame(analyze); + } + + private stopAnalysis() { + if (this.animationFrameId !== null) { + cancelAnimationFrame(this.animationFrameId); + this.animationFrameId = null; + } + + if (this.audioContext) { + this.audioContext.close(); + this.audioContext = null; + } + + this.analyser = null; + this.dataArray = null; + } + + disconnect() { + this.stopAnalysis(); + + if (this.mediaStream) { + this.mediaStream.getTracks().forEach(track => track.stop()); + this.mediaStream = null; + } + + if (this.peerConnection) { + this.peerConnection.close(); + this.peerConnection = null; + } + + this.dataChannel = null; + + if (this.options.onDisconnected) { + this.options.onDisconnected(); + } + } +} \ No newline at end of file diff --git a/demo/nextjs_voice_chat/frontend/fastrtc-demo/next.config.ts b/demo/nextjs_voice_chat/frontend/fastrtc-demo/next.config.ts new file mode 100644 index 0000000..e9ffa30 --- /dev/null +++ b/demo/nextjs_voice_chat/frontend/fastrtc-demo/next.config.ts @@ -0,0 +1,7 @@ +import type { NextConfig } from "next"; + +const nextConfig: NextConfig = { + /* config options here */ +}; + +export default nextConfig; diff --git a/demo/nextjs_voice_chat/frontend/fastrtc-demo/package.json b/demo/nextjs_voice_chat/frontend/fastrtc-demo/package.json new file mode 100644 index 0000000..93c285e --- /dev/null +++ b/demo/nextjs_voice_chat/frontend/fastrtc-demo/package.json @@ -0,0 +1,33 @@ +{ + "name": "fastrtc-demo", + "version": "0.1.0", + "private": true, + "scripts": { + "dev": "next dev --turbopack", + "build": "next build --no-lint", + "start": "next start", + "lint": "next lint" + }, + "dependencies": { + "class-variance-authority": "^0.7.1", + "clsx": "^2.1.1", + "framer-motion": "^12.4.10", + "lucide-react": "^0.477.0", + "next": "15.2.2-canary.1", + "react": "^19.0.0", + "react-dom": "^19.0.0", + "tailwind-merge": "^3.0.2", + "tailwindcss-animate": "^1.0.7" + }, + "devDependencies": { + "@eslint/eslintrc": "^3", + "@tailwindcss/postcss": "^4", + "@types/node": "^20", + "@types/react": "^19", + "@types/react-dom": "^19", + "eslint": "^9", + "eslint-config-next": "15.2.2-canary.1", + "tailwindcss": "^4", + "typescript": "^5" + } +} diff --git a/demo/nextjs_voice_chat/frontend/fastrtc-demo/postcss.config.mjs b/demo/nextjs_voice_chat/frontend/fastrtc-demo/postcss.config.mjs new file mode 100644 index 0000000..c7bcb4b --- /dev/null +++ b/demo/nextjs_voice_chat/frontend/fastrtc-demo/postcss.config.mjs @@ -0,0 +1,5 @@ +const config = { + plugins: ["@tailwindcss/postcss"], +}; + +export default config; diff --git a/demo/nextjs_voice_chat/frontend/fastrtc-demo/public/file.svg b/demo/nextjs_voice_chat/frontend/fastrtc-demo/public/file.svg new file mode 100644 index 0000000..004145c --- /dev/null +++ b/demo/nextjs_voice_chat/frontend/fastrtc-demo/public/file.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/demo/nextjs_voice_chat/frontend/fastrtc-demo/public/globe.svg b/demo/nextjs_voice_chat/frontend/fastrtc-demo/public/globe.svg new file mode 100644 index 0000000..567f17b --- /dev/null +++ b/demo/nextjs_voice_chat/frontend/fastrtc-demo/public/globe.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/demo/nextjs_voice_chat/frontend/fastrtc-demo/public/next.svg b/demo/nextjs_voice_chat/frontend/fastrtc-demo/public/next.svg new file mode 100644 index 0000000..5174b28 --- /dev/null +++ b/demo/nextjs_voice_chat/frontend/fastrtc-demo/public/next.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/demo/nextjs_voice_chat/frontend/fastrtc-demo/public/vercel.svg b/demo/nextjs_voice_chat/frontend/fastrtc-demo/public/vercel.svg new file mode 100644 index 0000000..7705396 --- /dev/null +++ b/demo/nextjs_voice_chat/frontend/fastrtc-demo/public/vercel.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/demo/nextjs_voice_chat/frontend/fastrtc-demo/public/window.svg b/demo/nextjs_voice_chat/frontend/fastrtc-demo/public/window.svg new file mode 100644 index 0000000..b2b2a44 --- /dev/null +++ b/demo/nextjs_voice_chat/frontend/fastrtc-demo/public/window.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/demo/nextjs_voice_chat/frontend/fastrtc-demo/tsconfig.json b/demo/nextjs_voice_chat/frontend/fastrtc-demo/tsconfig.json new file mode 100644 index 0000000..d8b9323 --- /dev/null +++ b/demo/nextjs_voice_chat/frontend/fastrtc-demo/tsconfig.json @@ -0,0 +1,27 @@ +{ + "compilerOptions": { + "target": "ES2017", + "lib": ["dom", "dom.iterable", "esnext"], + "allowJs": true, + "skipLibCheck": true, + "strict": true, + "noEmit": true, + "esModuleInterop": true, + "module": "esnext", + "moduleResolution": "bundler", + "resolveJsonModule": true, + "isolatedModules": true, + "jsx": "preserve", + "incremental": true, + "plugins": [ + { + "name": "next" + } + ], + "paths": { + "@/*": ["./*"] + } + }, + "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"], + "exclude": ["node_modules"] +} diff --git a/demo/nextjs_voice_chat/requirements.txt b/demo/nextjs_voice_chat/requirements.txt new file mode 100644 index 0000000..d9f0bb3 --- /dev/null +++ b/demo/nextjs_voice_chat/requirements.txt @@ -0,0 +1,5 @@ +openai +fastapi +python-dotenv +elevenlabs +fastrtc[vad, stt, tts] \ No newline at end of file diff --git a/demo/nextjs_voice_chat/run.sh b/demo/nextjs_voice_chat/run.sh new file mode 100755 index 0000000..814e8bd --- /dev/null +++ b/demo/nextjs_voice_chat/run.sh @@ -0,0 +1 @@ +uvicorn backend.server:app --host 0.0.0.0 --port 8000 \ No newline at end of file diff --git a/demo/object_detection/README.md b/demo/object_detection/README.md new file mode 100644 index 0000000..22f9552 --- /dev/null +++ b/demo/object_detection/README.md @@ -0,0 +1,15 @@ +--- +title: Object Detection +emoji: 📸 +colorFrom: purple +colorTo: red +sdk: gradio +sdk_version: 5.16.0 +app_file: app.py +pinned: false +license: mit +short_description: Use YOLOv10 to detect objects in real-time +tags: [webrtc, websocket, gradio, secret|TWILIO_ACCOUNT_SID, secret|TWILIO_AUTH_TOKEN] +--- + +Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference \ No newline at end of file diff --git a/demo/object_detection/app.py b/demo/object_detection/app.py new file mode 100644 index 0000000..06bd1ac --- /dev/null +++ b/demo/object_detection/app.py @@ -0,0 +1,77 @@ +import json +from pathlib import Path + +import cv2 +import gradio as gr +from fastapi import FastAPI +from fastapi.responses import HTMLResponse +from fastrtc import Stream, get_twilio_turn_credentials +from gradio.utils import get_space +from huggingface_hub import hf_hub_download +from pydantic import BaseModel, Field + +try: + from demo.object_detection.inference import YOLOv10 +except (ImportError, ModuleNotFoundError): + from inference import YOLOv10 + + +cur_dir = Path(__file__).parent + +model_file = hf_hub_download( + repo_id="onnx-community/yolov10n", filename="onnx/model.onnx" +) + +model = YOLOv10(model_file) + + +def detection(image, conf_threshold=0.3): + image = cv2.resize(image, (model.input_width, model.input_height)) + print("conf_threshold", conf_threshold) + new_image = model.detect_objects(image, conf_threshold) + return cv2.resize(new_image, (500, 500)) + + +stream = Stream( + handler=detection, + modality="video", + mode="send-receive", + additional_inputs=[gr.Slider(minimum=0, maximum=1, step=0.01, value=0.3)], + rtc_configuration=get_twilio_turn_credentials() if get_space() else None, + concurrency_limit=2 if get_space() else None, +) + +app = FastAPI() + +stream.mount(app) + + +@app.get("/") +async def _(): + rtc_config = get_twilio_turn_credentials() if get_space() else None + html_content = open(cur_dir / "index.html").read() + html_content = html_content.replace("__RTC_CONFIGURATION__", json.dumps(rtc_config)) + return HTMLResponse(content=html_content) + + +class InputData(BaseModel): + webrtc_id: str + conf_threshold: float = Field(ge=0, le=1) + + +@app.post("/input_hook") +async def _(data: InputData): + stream.set_input(data.webrtc_id, data.conf_threshold) + + +if __name__ == "__main__": + import os + + if (mode := os.getenv("MODE")) == "UI": + stream.ui.launch(server_port=7860) + elif mode == "PHONE": + stream.fastphone(host="0.0.0.0", port=7860) + else: + import uvicorn + + uvicorn.run(app, host="0.0.0.0", port=7860) diff --git a/demo/object_detection/index.html b/demo/object_detection/index.html new file mode 100644 index 0000000..daad1f5 --- /dev/null +++ b/demo/object_detection/index.html @@ -0,0 +1,340 @@ + + + + + + + Object Detection + + + + + +
+
+

Real-time Object Detection

+

Using YOLOv10 to detect objects in your webcam feed

+
+ +
+
+
+ + +
+ +
+
+ + + + + \ No newline at end of file diff --git a/demo/object_detection/inference.py b/demo/object_detection/inference.py new file mode 100644 index 0000000..fd2e424 --- /dev/null +++ b/demo/object_detection/inference.py @@ -0,0 +1,153 @@ +import time + +import cv2 +import numpy as np +import onnxruntime + +try: + from demo.object_detection.utils import draw_detections +except (ImportError, ModuleNotFoundError): + from utils import draw_detections + + +class YOLOv10: + def __init__(self, path): + # Initialize model + self.initialize_model(path) + + def __call__(self, image): + return self.detect_objects(image) + + def initialize_model(self, path): + self.session = onnxruntime.InferenceSession( + path, providers=onnxruntime.get_available_providers() + ) + # Get model info + self.get_input_details() + self.get_output_details() + + def detect_objects(self, image, conf_threshold=0.3): + input_tensor = self.prepare_input(image) + + # Perform inference on the image + new_image = self.inference(image, input_tensor, conf_threshold) + + return new_image + + def prepare_input(self, image): + self.img_height, self.img_width = image.shape[:2] + + input_img = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) + + # Resize input image + input_img = cv2.resize(input_img, (self.input_width, self.input_height)) + + # Scale input pixel values to 0 to 1 + input_img = input_img / 255.0 + input_img = input_img.transpose(2, 0, 1) + input_tensor = input_img[np.newaxis, :, :, :].astype(np.float32) + + return input_tensor + + def inference(self, image, input_tensor, conf_threshold=0.3): + start = time.perf_counter() + outputs = self.session.run( + self.output_names, {self.input_names[0]: input_tensor} + ) + + print(f"Inference time: {(time.perf_counter() - start) * 1000:.2f} ms") + ( + boxes, + scores, + class_ids, + ) = self.process_output(outputs, conf_threshold) + return self.draw_detections(image, boxes, scores, class_ids) + + def process_output(self, output, conf_threshold=0.3): + predictions = np.squeeze(output[0]) + + # Filter out object confidence scores below threshold + scores = predictions[:, 4] + predictions = predictions[scores > conf_threshold, :] + scores = scores[scores > conf_threshold] + + if len(scores) == 0: + return [], [], [] + + # Get the class with the highest confidence + class_ids = predictions[:, 5].astype(int) + + # Get bounding boxes for each object + boxes = self.extract_boxes(predictions) + + return boxes, scores, class_ids + + def extract_boxes(self, predictions): + # Extract boxes from predictions + boxes = predictions[:, :4] + + # Scale boxes to original image dimensions + boxes = self.rescale_boxes(boxes) + + # Convert boxes to xyxy format + # boxes = xywh2xyxy(boxes) + + return boxes + + def rescale_boxes(self, boxes): + # Rescale boxes to original image dimensions + input_shape = np.array( + [self.input_width, self.input_height, self.input_width, self.input_height] + ) + boxes = np.divide(boxes, input_shape, dtype=np.float32) + boxes *= np.array( + [self.img_width, self.img_height, self.img_width, self.img_height] + ) + return boxes + + def draw_detections( + self, image, boxes, scores, class_ids, draw_scores=True, mask_alpha=0.4 + ): + return draw_detections(image, boxes, scores, class_ids, mask_alpha) + + def get_input_details(self): + model_inputs = self.session.get_inputs() + self.input_names = [model_inputs[i].name for i in range(len(model_inputs))] + + self.input_shape = model_inputs[0].shape + self.input_height = self.input_shape[2] + self.input_width = self.input_shape[3] + + def get_output_details(self): + model_outputs = self.session.get_outputs() + self.output_names = [model_outputs[i].name for i in range(len(model_outputs))] + + +if __name__ == "__main__": + import tempfile + + import requests + from huggingface_hub import hf_hub_download + + model_file = hf_hub_download( + repo_id="onnx-community/yolov10s", filename="onnx/model.onnx" + ) + + yolov8_detector = YOLOv10(model_file) + + with tempfile.NamedTemporaryFile(suffix=".jpg", delete=False) as f: + f.write( + requests.get( + "https://live.staticflickr.com/13/19041780_d6fd803de0_3k.jpg" + ).content + ) + f.seek(0) + img = cv2.imread(f.name) + + # # Detect Objects + combined_image = yolov8_detector.detect_objects(img) + + # Draw detections + cv2.namedWindow("Output", cv2.WINDOW_NORMAL) + cv2.imshow("Output", combined_image) + cv2.waitKey(0) diff --git a/demo/object_detection/requirements.txt b/demo/object_detection/requirements.txt new file mode 100644 index 0000000..b3fbe78 --- /dev/null +++ b/demo/object_detection/requirements.txt @@ -0,0 +1,4 @@ +fastrtc +opencv-python +twilio +onnxruntime-gpu \ No newline at end of file diff --git a/demo/object_detection/utils.py b/demo/object_detection/utils.py new file mode 100644 index 0000000..896f6c7 --- /dev/null +++ b/demo/object_detection/utils.py @@ -0,0 +1,237 @@ +import cv2 +import numpy as np + +class_names = [ + "person", + "bicycle", + "car", + "motorcycle", + "airplane", + "bus", + "train", + "truck", + "boat", + "traffic light", + "fire hydrant", + "stop sign", + "parking meter", + "bench", + "bird", + "cat", + "dog", + "horse", + "sheep", + "cow", + "elephant", + "bear", + "zebra", + "giraffe", + "backpack", + "umbrella", + "handbag", + "tie", + "suitcase", + "frisbee", + "skis", + "snowboard", + "sports ball", + "kite", + "baseball bat", + "baseball glove", + "skateboard", + "surfboard", + "tennis racket", + "bottle", + "wine glass", + "cup", + "fork", + "knife", + "spoon", + "bowl", + "banana", + "apple", + "sandwich", + "orange", + "broccoli", + "carrot", + "hot dog", + "pizza", + "donut", + "cake", + "chair", + "couch", + "potted plant", + "bed", + "dining table", + "toilet", + "tv", + "laptop", + "mouse", + "remote", + "keyboard", + "cell phone", + "microwave", + "oven", + "toaster", + "sink", + "refrigerator", + "book", + "clock", + "vase", + "scissors", + "teddy bear", + "hair drier", + "toothbrush", +] + +# Create a list of colors for each class where each color is a tuple of 3 integer values +rng = np.random.default_rng(3) +colors = rng.uniform(0, 255, size=(len(class_names), 3)) + + +def nms(boxes, scores, iou_threshold): + # Sort by score + sorted_indices = np.argsort(scores)[::-1] + + keep_boxes = [] + while sorted_indices.size > 0: + # Pick the last box + box_id = sorted_indices[0] + keep_boxes.append(box_id) + + # Compute IoU of the picked box with the rest + ious = compute_iou(boxes[box_id, :], boxes[sorted_indices[1:], :]) + + # Remove boxes with IoU over the threshold + keep_indices = np.where(ious < iou_threshold)[0] + + # print(keep_indices.shape, sorted_indices.shape) + sorted_indices = sorted_indices[keep_indices + 1] + + return keep_boxes + + +def multiclass_nms(boxes, scores, class_ids, iou_threshold): + unique_class_ids = np.unique(class_ids) + + keep_boxes = [] + for class_id in unique_class_ids: + class_indices = np.where(class_ids == class_id)[0] + class_boxes = boxes[class_indices, :] + class_scores = scores[class_indices] + + class_keep_boxes = nms(class_boxes, class_scores, iou_threshold) + keep_boxes.extend(class_indices[class_keep_boxes]) + + return keep_boxes + + +def compute_iou(box, boxes): + # Compute xmin, ymin, xmax, ymax for both boxes + xmin = np.maximum(box[0], boxes[:, 0]) + ymin = np.maximum(box[1], boxes[:, 1]) + xmax = np.minimum(box[2], boxes[:, 2]) + ymax = np.minimum(box[3], boxes[:, 3]) + + # Compute intersection area + intersection_area = np.maximum(0, xmax - xmin) * np.maximum(0, ymax - ymin) + + # Compute union area + box_area = (box[2] - box[0]) * (box[3] - box[1]) + boxes_area = (boxes[:, 2] - boxes[:, 0]) * (boxes[:, 3] - boxes[:, 1]) + union_area = box_area + boxes_area - intersection_area + + # Compute IoU + iou = intersection_area / union_area + + return iou + + +def xywh2xyxy(x): + # Convert bounding box (x, y, w, h) to bounding box (x1, y1, x2, y2) + y = np.copy(x) + y[..., 0] = x[..., 0] - x[..., 2] / 2 + y[..., 1] = x[..., 1] - x[..., 3] / 2 + y[..., 2] = x[..., 0] + x[..., 2] / 2 + y[..., 3] = x[..., 1] + x[..., 3] / 2 + return y + + +def draw_detections(image, boxes, scores, class_ids, mask_alpha=0.3): + det_img = image.copy() + + img_height, img_width = image.shape[:2] + font_size = min([img_height, img_width]) * 0.0006 + text_thickness = int(min([img_height, img_width]) * 0.001) + + # det_img = draw_masks(det_img, boxes, class_ids, mask_alpha) + + # Draw bounding boxes and labels of detections + for class_id, box, score in zip(class_ids, boxes, scores): + color = colors[class_id] + + draw_box(det_img, box, color) # type: ignore + + label = class_names[class_id] + caption = f"{label} {int(score * 100)}%" + draw_text(det_img, caption, box, color, font_size, text_thickness) # type: ignore + + return det_img + + +def draw_box( + image: np.ndarray, + box: np.ndarray, + color: tuple[int, int, int] = (0, 0, 255), + thickness: int = 2, +) -> np.ndarray: + x1, y1, x2, y2 = box.astype(int) + return cv2.rectangle(image, (x1, y1), (x2, y2), color, thickness) + + +def draw_text( + image: np.ndarray, + text: str, + box: np.ndarray, + color: tuple[int, int, int] = (0, 0, 255), + font_size: float = 0.001, + text_thickness: int = 2, +) -> np.ndarray: + x1, y1, x2, y2 = box.astype(int) + (tw, th), _ = cv2.getTextSize( + text=text, + fontFace=cv2.FONT_HERSHEY_SIMPLEX, + fontScale=font_size, + thickness=text_thickness, + ) + th = int(th * 1.2) + + cv2.rectangle(image, (x1, y1), (x1 + tw, y1 - th), color, -1) + + return cv2.putText( + image, + text, + (x1, y1), + cv2.FONT_HERSHEY_SIMPLEX, + font_size, + (255, 255, 255), + text_thickness, + cv2.LINE_AA, + ) + + +def draw_masks( + image: np.ndarray, boxes: np.ndarray, classes: np.ndarray, mask_alpha: float = 0.3 +) -> np.ndarray: + mask_img = image.copy() + + # Draw bounding boxes and labels of detections + for box, class_id in zip(boxes, classes): + color = colors[class_id] + + x1, y1, x2, y2 = box.astype(int) + + # Draw fill rectangle in mask image + cv2.rectangle(mask_img, (x1, y1), (x2, y2), color, -1) # type: ignore + + return cv2.addWeighted(mask_img, mask_alpha, image, 1 - mask_alpha, 0) diff --git a/demo/phonic_chat/README.md b/demo/phonic_chat/README.md new file mode 100644 index 0000000..86e347b --- /dev/null +++ b/demo/phonic_chat/README.md @@ -0,0 +1,16 @@ +--- +title: Phonic AI Chat +emoji: 🎙️ +colorFrom: purple +colorTo: red +sdk: gradio +sdk_version: 5.16.0 +app_file: app.py +pinned: false +license: mit +short_description: Talk to Phonic AI's speech-to-speech model +tags: [webrtc, websocket, gradio, secret|TWILIO_ACCOUNT_SID, secret|TWILIO_AUTH_TOKEN, secret|PHONIC_API_KEY] +python_version: 3.11 +--- + +Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference \ No newline at end of file diff --git a/demo/phonic_chat/app.py b/demo/phonic_chat/app.py new file mode 100644 index 0000000..b968bc2 --- /dev/null +++ b/demo/phonic_chat/app.py @@ -0,0 +1,116 @@ +import asyncio +import base64 +import os + +import gradio as gr +from gradio.utils import get_space +import numpy as np +from dotenv import load_dotenv +from fastrtc import ( + AdditionalOutputs, + AsyncStreamHandler, + Stream, + get_twilio_turn_credentials, + audio_to_float32, + wait_for_item, +) +from phonic.client import PhonicSTSClient, get_voices + +load_dotenv() + +STS_URI = "wss://api.phonic.co/v1/sts/ws" +API_KEY = os.environ["PHONIC_API_KEY"] +SAMPLE_RATE = 44_100 +voices = get_voices(API_KEY) +voice_ids = [voice["id"] for voice in voices] + + +class PhonicHandler(AsyncStreamHandler): + def __init__(self): + super().__init__(input_sample_rate=SAMPLE_RATE, output_sample_rate=SAMPLE_RATE) + self.output_queue = asyncio.Queue() + self.client = None + + def copy(self) -> AsyncStreamHandler: + return PhonicHandler() + + async def start_up(self): + await self.wait_for_args() + voice_id = self.latest_args[1] + async with PhonicSTSClient(STS_URI, API_KEY) as client: + self.client = client + sts_stream = client.sts( # type: ignore + input_format="pcm_44100", + output_format="pcm_44100", + system_prompt="You are a helpful voice assistant. Respond conversationally.", + # welcome_message="Hello! I'm your voice assistant. How can I help you today?", + voice_id=voice_id, + ) + async for message in sts_stream: + message_type = message.get("type") + if message_type == "audio_chunk": + audio_b64 = message["audio"] + audio_bytes = base64.b64decode(audio_b64) + await self.output_queue.put( + (SAMPLE_RATE, np.frombuffer(audio_bytes, dtype=np.int16)) + ) + if text := message.get("text"): + msg = {"role": "assistant", "content": text} + await self.output_queue.put(AdditionalOutputs(msg)) + elif message_type == "input_text": + msg = {"role": "user", "content": message["text"]} + await self.output_queue.put(AdditionalOutputs(msg)) + + async def emit(self): + return await wait_for_item(self.output_queue) + + async def receive(self, frame: tuple[int, np.ndarray]) -> None: + if not self.client: + return + audio_float32 = audio_to_float32(frame) + await self.client.send_audio(audio_float32) # type: ignore + + async def shutdown(self): + if self.client: + await self.client._websocket.close() + return super().shutdown() + + +def add_to_chatbot(chatbot, message): + chatbot.append(message) + return chatbot + + +chatbot = gr.Chatbot(type="messages", value=[]) +stream = Stream( + handler=PhonicHandler(), + mode="send-receive", + modality="audio", + additional_inputs=[ + gr.Dropdown( + choices=voice_ids, + value="victoria", + label="Voice", + info="Select a voice from the dropdown", + ) + ], + additional_outputs=[chatbot], + additional_outputs_handler=add_to_chatbot, + ui_args={ + "title": "Phonic Chat (Powered by FastRTC ⚡️)", + }, + rtc_configuration=get_twilio_turn_credentials() if get_space() else None, + concurrency_limit=5 if get_space() else None, + time_limit=90 if get_space() else None, +) + +# with stream.ui: +# state.change(lambda s: s, inputs=state, outputs=chatbot) + +if __name__ == "__main__": + if (mode := os.getenv("MODE")) == "UI": + stream.ui.launch(server_port=7860) + elif mode == "PHONE": + stream.fastphone(host="0.0.0.0", port=7860) + else: + stream.ui.launch(server_port=7860) diff --git a/demo/phonic_chat/requirements.txt b/demo/phonic_chat/requirements.txt new file mode 100644 index 0000000..14146ab --- /dev/null +++ b/demo/phonic_chat/requirements.txt @@ -0,0 +1,74 @@ +# This file was autogenerated by uv via the following command: +# uv pip compile requirements.in -o requirements.txt +aiohappyeyeballs==2.4.6 + # via aiohttp +aiohttp==3.11.12 + # via + # aiohttp-retry + # twilio +aiohttp-retry==2.9.1 + # via twilio +aiosignal==1.3.2 + # via aiohttp +attrs==25.1.0 + # via aiohttp +certifi==2025.1.31 + # via requests +cffi==1.17.1 + # via sounddevice +charset-normalizer==3.4.1 + # via requests +fastrtc==0.0.1 + # via -r requirements.in +frozenlist==1.5.0 + # via + # aiohttp + # aiosignal +idna==3.10 + # via + # requests + # yarl +isort==6.0.0 + # via phonic-python +loguru==0.7.3 + # via phonic-python +multidict==6.1.0 + # via + # aiohttp + # yarl +numpy==2.2.3 + # via + # phonic-python + # scipy +phonic-python==0.1.3 + # via -r requirements.in +propcache==0.3.0 + # via + # aiohttp + # yarl +pycparser==2.22 + # via cffi +pyjwt==2.10.1 + # via twilio +python-dotenv==1.0.1 + # via + # -r requirements.in + # phonic-python +requests==2.32.3 + # via + # phonic-python + # twilio +scipy==1.15.2 + # via phonic-python +sounddevice==0.5.1 + # via phonic-python +twilio==9.4.6 + # via -r requirements.in +typing-extensions==4.12.2 + # via phonic-python +urllib3==2.3.0 + # via requests +websockets==15.0 + # via phonic-python +yarl==1.18.3 + # via aiohttp diff --git a/demo/talk_to_claude/README.md b/demo/talk_to_claude/README.md new file mode 100644 index 0000000..195950b --- /dev/null +++ b/demo/talk_to_claude/README.md @@ -0,0 +1,15 @@ +--- +title: Talk to Claude +emoji: 👨‍🦰 +colorFrom: purple +colorTo: red +sdk: gradio +sdk_version: 5.16.0 +app_file: app.py +pinned: false +license: mit +short_description: Talk to Anthropic's Claude +tags: [webrtc, websocket, gradio, secret|TWILIO_ACCOUNT_SID, secret|TWILIO_AUTH_TOKEN, secret|GROQ_API_KEY, secret|ANTHROPIC_API_KEY, secret|ELEVENLABS_API_KEY] +--- + +Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference \ No newline at end of file diff --git a/demo/talk_to_claude/app.py b/demo/talk_to_claude/app.py new file mode 100644 index 0000000..ddc95bf --- /dev/null +++ b/demo/talk_to_claude/app.py @@ -0,0 +1,134 @@ +import json +import os +import time +from pathlib import Path + +import anthropic +import gradio as gr +import numpy as np +from dotenv import load_dotenv +from elevenlabs import ElevenLabs +from fastapi import FastAPI +from fastapi.responses import HTMLResponse, StreamingResponse +from fastrtc import ( + AdditionalOutputs, + ReplyOnPause, + Stream, + get_tts_model, + get_twilio_turn_credentials, +) +from fastrtc.utils import audio_to_bytes +from gradio.utils import get_space +from groq import Groq +from pydantic import BaseModel + +load_dotenv() + +groq_client = Groq() +claude_client = anthropic.Anthropic() +tts_client = ElevenLabs(api_key=os.environ["ELEVENLABS_API_KEY"]) + +curr_dir = Path(__file__).parent + +tts_model = get_tts_model() + + +def response( + audio: tuple[int, np.ndarray], + chatbot: list[dict] | None = None, +): + chatbot = chatbot or [] + messages = [{"role": d["role"], "content": d["content"]} for d in chatbot] + prompt = groq_client.audio.transcriptions.create( + file=("audio-file.mp3", audio_to_bytes(audio)), + model="whisper-large-v3-turbo", + response_format="verbose_json", + ).text + chatbot.append({"role": "user", "content": prompt}) + yield AdditionalOutputs(chatbot) + messages.append({"role": "user", "content": prompt}) + response = claude_client.messages.create( + model="claude-3-5-haiku-20241022", + max_tokens=512, + messages=messages, # type: ignore + ) + response_text = " ".join( + block.text # type: ignore + for block in response.content + if getattr(block, "type", None) == "text" + ) + chatbot.append({"role": "assistant", "content": response_text}) + + start = time.time() + + print("starting tts", start) + for i, chunk in enumerate(tts_model.stream_tts_sync(response_text)): + print("chunk", i, time.time() - start) + yield chunk + print("finished tts", time.time() - start) + yield AdditionalOutputs(chatbot) + + +chatbot = gr.Chatbot(type="messages") +stream = Stream( + modality="audio", + mode="send-receive", + handler=ReplyOnPause(response), + additional_outputs_handler=lambda a, b: b, + additional_inputs=[chatbot], + additional_outputs=[chatbot], + rtc_configuration=get_twilio_turn_credentials() if get_space() else None, + concurrency_limit=5 if get_space() else None, + time_limit=90 if get_space() else None, +) + + +class Message(BaseModel): + role: str + content: str + + +class InputData(BaseModel): + webrtc_id: str + chatbot: list[Message] + + +app = FastAPI() +stream.mount(app) + + +@app.get("/") +async def _(): + rtc_config = get_twilio_turn_credentials() if get_space() else None + html_content = (curr_dir / "index.html").read_text() + html_content = html_content.replace("__RTC_CONFIGURATION__", json.dumps(rtc_config)) + return HTMLResponse(content=html_content, status_code=200) + + +@app.post("/input_hook") +async def _(body: InputData): + stream.set_input(body.webrtc_id, body.model_dump()["chatbot"]) + return {"status": "ok"} + + +@app.get("/outputs") +def _(webrtc_id: str): + async def output_stream(): + async for output in stream.output_stream(webrtc_id): + chatbot = output.args[0] + yield f"event: output\ndata: {json.dumps(chatbot[-1])}\n\n" + + return StreamingResponse(output_stream(), media_type="text/event-stream") + + +if __name__ == "__main__": + import os + + if (mode := os.getenv("MODE")) == "UI": + stream.ui.launch(server_port=7860) + elif mode == "PHONE": + stream.fastphone(host="0.0.0.0", port=7860) + else: + import uvicorn + + uvicorn.run(app, host="0.0.0.0", port=7860) diff --git a/demo/talk_to_claude/index.html b/demo/talk_to_claude/index.html new file mode 100644 index 0000000..c76e74b --- /dev/null +++ b/demo/talk_to_claude/index.html @@ -0,0 +1,546 @@ + + + + + + + RetroChat Audio + + + + + +
+
+
+
+ +
+
+
+
+
+
+
+
+
+
+
+ +
+
+ +
+
+ + + + + + \ No newline at end of file diff --git a/demo/talk_to_claude/requirements.txt b/demo/talk_to_claude/requirements.txt new file mode 100644 index 0000000..3912bed --- /dev/null +++ b/demo/talk_to_claude/requirements.txt @@ -0,0 +1,6 @@ +fastrtc[vad, tts] +elevenlabs +groq +anthropic +twilio +python-dotenv diff --git a/demo/talk_to_gemini/README.md b/demo/talk_to_gemini/README.md new file mode 100644 index 0000000..b6fbbcc --- /dev/null +++ b/demo/talk_to_gemini/README.md @@ -0,0 +1,15 @@ +--- +title: Talk to Gemini +emoji: ♊️ +colorFrom: purple +colorTo: red +sdk: gradio +sdk_version: 5.16.0 +app_file: app.py +pinned: false +license: mit +short_description: Talk to Gemini using Google's multimodal API +tags: [webrtc, websocket, gradio, secret|TWILIO_ACCOUNT_SID, secret|TWILIO_AUTH_TOKEN, secret|GEMINI_API_KEY] +--- + +Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference \ No newline at end of file diff --git a/demo/talk_to_gemini/README_gradio.md b/demo/talk_to_gemini/README_gradio.md new file mode 100644 index 0000000..a224a1a --- /dev/null +++ b/demo/talk_to_gemini/README_gradio.md @@ -0,0 +1,15 @@ +--- +title: Talk to Gemini (Gradio UI) +emoji: ♊️ +colorFrom: purple +colorTo: red +sdk: gradio +sdk_version: 5.16.0 +app_file: app.py +pinned: false +license: mit +short_description: Talk to Gemini (Gradio UI) +tags: [webrtc, websocket, gradio, secret|TWILIO_ACCOUNT_SID, secret|TWILIO_AUTH_TOKEN, secret|GEMINI_API_KEY] +--- + +Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference \ No newline at end of file diff --git a/demo/talk_to_gemini/app.py b/demo/talk_to_gemini/app.py new file mode 100644 index 0000000..db5dcff --- /dev/null +++ b/demo/talk_to_gemini/app.py @@ -0,0 +1,181 @@ +import asyncio +import base64 +import json +import os +import pathlib +from typing import AsyncGenerator, Literal + +import gradio as gr +import numpy as np +from dotenv import load_dotenv +from fastapi import FastAPI +from fastapi.responses import HTMLResponse +from fastrtc import ( + AsyncStreamHandler, + Stream, + get_twilio_turn_credentials, + wait_for_item, +) +from google import genai +from google.genai.types import ( + LiveConnectConfig, + PrebuiltVoiceConfig, + SpeechConfig, + VoiceConfig, +) +from gradio.utils import get_space +from pydantic import BaseModel + +current_dir = pathlib.Path(__file__).parent + +load_dotenv() + + +def encode_audio(data: np.ndarray) -> str: + """Encode Audio data to send to the server""" + return base64.b64encode(data.tobytes()).decode("UTF-8") + + +class GeminiHandler(AsyncStreamHandler): + """Handler for the Gemini API""" + + def __init__( + self, + expected_layout: Literal["mono"] = "mono", + output_sample_rate: int = 24000, + output_frame_size: int = 480, + ) -> None: + super().__init__( + expected_layout, + output_sample_rate, + output_frame_size, + input_sample_rate=16000, + ) + self.input_queue: asyncio.Queue = asyncio.Queue() + self.output_queue: asyncio.Queue = asyncio.Queue() + self.quit: asyncio.Event = asyncio.Event() + + def copy(self) -> "GeminiHandler": + return GeminiHandler( + expected_layout="mono", + output_sample_rate=self.output_sample_rate, + output_frame_size=self.output_frame_size, + ) + + async def start_up(self): + if not self.phone_mode: + await self.wait_for_args() + api_key, voice_name = self.latest_args[1:] + else: + api_key, voice_name = None, "Puck" + + client = genai.Client( + api_key=api_key or os.getenv("GEMINI_API_KEY"), + http_options={"api_version": "v1alpha"}, + ) + + config = LiveConnectConfig( + response_modalities=["AUDIO"], # type: ignore + speech_config=SpeechConfig( + voice_config=VoiceConfig( + prebuilt_voice_config=PrebuiltVoiceConfig( + voice_name=voice_name, + ) + ) + ), + ) + async with client.aio.live.connect( + model="gemini-2.0-flash-exp", config=config + ) as session: + async for audio in session.start_stream( + stream=self.stream(), mime_type="audio/pcm" + ): + if audio.data: + array = np.frombuffer(audio.data, dtype=np.int16) + self.output_queue.put_nowait((self.output_sample_rate, array)) + + async def stream(self) -> AsyncGenerator[bytes, None]: + while not self.quit.is_set(): + try: + audio = await asyncio.wait_for(self.input_queue.get(), 0.1) + yield audio + except (asyncio.TimeoutError, TimeoutError): + pass + + async def receive(self, frame: tuple[int, np.ndarray]) -> None: + _, array = frame + array = array.squeeze() + audio_message = encode_audio(array) + self.input_queue.put_nowait(audio_message) + + async def emit(self) -> tuple[int, np.ndarray] | None: + return await wait_for_item(self.output_queue) + + def shutdown(self) -> None: + self.quit.set() + + +stream = Stream( + modality="audio", + mode="send-receive", + handler=GeminiHandler(), + rtc_configuration=get_twilio_turn_credentials() if get_space() else None, + concurrency_limit=5 if get_space() else None, + time_limit=90 if get_space() else None, + additional_inputs=[ + gr.Textbox( + label="API Key", + type="password", + value=os.getenv("GEMINI_API_KEY") if not get_space() else "", + ), + gr.Dropdown( + label="Voice", + choices=[ + "Puck", + "Charon", + "Kore", + "Fenrir", + "Aoede", + ], + value="Puck", + ), + ], +) + + +class InputData(BaseModel): + webrtc_id: str + voice_name: str + api_key: str + + +app = FastAPI() + +stream.mount(app) + + +@app.post("/input_hook") +async def _(body: InputData): + stream.set_input(body.webrtc_id, body.api_key, body.voice_name) + return {"status": "ok"} + + +@app.get("/") +async def index(): + rtc_config = get_twilio_turn_credentials() if get_space() else None + html_content = (current_dir / "index.html").read_text() + html_content = html_content.replace("__RTC_CONFIGURATION__", json.dumps(rtc_config)) + return HTMLResponse(content=html_content) + + +if __name__ == "__main__": + import os + + if (mode := os.getenv("MODE")) == "UI": + stream.ui.launch(server_port=7860) + elif mode == "PHONE": + stream.fastphone(host="0.0.0.0", port=7860) + else: + import uvicorn + + uvicorn.run(app, host="0.0.0.0", port=7860) diff --git a/demo/talk_to_gemini/index.html b/demo/talk_to_gemini/index.html new file mode 100644 index 0000000..a6ae8be --- /dev/null +++ b/demo/talk_to_gemini/index.html @@ -0,0 +1,452 @@ + + + + + + + Gemini Voice Chat + + + + + + +
+
+

Gemini Voice Chat

+

Speak with Gemini using real-time audio streaming

+

+ Get a Gemini API key + here +

+
+
+
+
+ + +
+
+ + +
+
+ +
+
+ +
+
+ + +
+ + + + + + + \ No newline at end of file diff --git a/demo/talk_to_gemini/requirements.txt b/demo/talk_to_gemini/requirements.txt new file mode 100644 index 0000000..e8cbeb2 --- /dev/null +++ b/demo/talk_to_gemini/requirements.txt @@ -0,0 +1,4 @@ +fastrtc +python-dotenv +google-genai +twilio diff --git a/demo/talk_to_openai/README.md b/demo/talk_to_openai/README.md new file mode 100644 index 0000000..7efde7d --- /dev/null +++ b/demo/talk_to_openai/README.md @@ -0,0 +1,15 @@ +--- +title: Talk to OpenAI +emoji: 🗣️ +colorFrom: purple +colorTo: red +sdk: gradio +sdk_version: 5.16.0 +app_file: app.py +pinned: false +license: mit +short_description: Talk to OpenAI using their multimodal API +tags: [webrtc, websocket, gradio, secret|TWILIO_ACCOUNT_SID, secret|TWILIO_AUTH_TOKEN, secret|OPENAI_API_KEY] +--- + +Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference \ No newline at end of file diff --git a/demo/talk_to_openai/README_gradio.md b/demo/talk_to_openai/README_gradio.md new file mode 100644 index 0000000..f495327 --- /dev/null +++ b/demo/talk_to_openai/README_gradio.md @@ -0,0 +1,15 @@ +--- +title: Talk to OpenAI (Gradio UI) +emoji: 🗣️ +colorFrom: purple +colorTo: red +sdk: gradio +sdk_version: 5.16.0 +app_file: app.py +pinned: false +license: mit +short_description: Talk to OpenAI (Gradio UI) +tags: [webrtc, websocket, gradio, secret|TWILIO_ACCOUNT_SID, secret|TWILIO_AUTH_TOKEN, secret|OPENAI_API_KEY] +--- + +Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference \ No newline at end of file diff --git a/demo/talk_to_openai/app.py b/demo/talk_to_openai/app.py new file mode 100644 index 0000000..e60ec1f --- /dev/null +++ b/demo/talk_to_openai/app.py @@ -0,0 +1,141 @@ +import asyncio +import base64 +import json +from pathlib import Path + +import gradio as gr +import numpy as np +import openai +from dotenv import load_dotenv +from fastapi import FastAPI +from fastapi.responses import HTMLResponse, StreamingResponse +from fastrtc import ( + AdditionalOutputs, + AsyncStreamHandler, + Stream, + get_twilio_turn_credentials, + wait_for_item, +) +from gradio.utils import get_space +from openai.types.beta.realtime import ResponseAudioTranscriptDoneEvent + +load_dotenv() + +cur_dir = Path(__file__).parent + +SAMPLE_RATE = 24000 + + +class OpenAIHandler(AsyncStreamHandler): + def __init__( + self, + ) -> None: + super().__init__( + expected_layout="mono", + output_sample_rate=SAMPLE_RATE, + output_frame_size=480, + input_sample_rate=SAMPLE_RATE, + ) + self.connection = None + self.output_queue = asyncio.Queue() + + def copy(self): + return OpenAIHandler() + + async def start_up( + self, + ): + """Connect to realtime API. Run forever in separate thread to keep connection open.""" + self.client = openai.AsyncOpenAI() + async with self.client.beta.realtime.connect( + model="gpt-4o-mini-realtime-preview-2024-12-17" + ) as conn: + await conn.session.update( + session={"turn_detection": {"type": "server_vad"}} + ) + self.connection = conn + async for event in self.connection: + if event.type == "response.audio_transcript.done": + await self.output_queue.put(AdditionalOutputs(event)) + if event.type == "response.audio.delta": + await self.output_queue.put( + ( + self.output_sample_rate, + np.frombuffer( + base64.b64decode(event.delta), dtype=np.int16 + ).reshape(1, -1), + ), + ) + + async def receive(self, frame: tuple[int, np.ndarray]) -> None: + if not self.connection: + return + _, array = frame + array = array.squeeze() + audio_message = base64.b64encode(array.tobytes()).decode("utf-8") + await self.connection.input_audio_buffer.append(audio=audio_message) # type: ignore + + async def emit(self) -> tuple[int, np.ndarray] | AdditionalOutputs | None: + return await wait_for_item(self.output_queue) + + async def shutdown(self) -> None: + if self.connection: + await self.connection.close() + self.connection = None + + +def update_chatbot(chatbot: list[dict], response: ResponseAudioTranscriptDoneEvent): + chatbot.append({"role": "assistant", "content": response.transcript}) + return chatbot + + +chatbot = gr.Chatbot(type="messages") +latest_message = gr.Textbox(type="text", visible=False) +stream = Stream( + OpenAIHandler(), + mode="send-receive", + modality="audio", + additional_inputs=[chatbot], + additional_outputs=[chatbot], + additional_outputs_handler=update_chatbot, + rtc_configuration=get_twilio_turn_credentials() if get_space() else None, + concurrency_limit=5 if get_space() else None, + time_limit=90 if get_space() else None, +) + +app = FastAPI() + +stream.mount(app) + + +@app.get("/") +async def _(): + rtc_config = get_twilio_turn_credentials() if get_space() else None + html_content = (cur_dir / "index.html").read_text() + html_content = html_content.replace("__RTC_CONFIGURATION__", json.dumps(rtc_config)) + return HTMLResponse(content=html_content) + + +@app.get("/outputs") +def _(webrtc_id: str): + async def output_stream(): + import json + + async for output in stream.output_stream(webrtc_id): + s = json.dumps({"role": "assistant", "content": output.args[0].transcript}) + yield f"event: output\ndata: {s}\n\n" + + return StreamingResponse(output_stream(), media_type="text/event-stream") + + +if __name__ == "__main__": + import os + + if (mode := os.getenv("MODE")) == "UI": + stream.ui.launch(server_port=7860) + elif mode == "PHONE": + stream.fastphone(host="0.0.0.0", port=7860) + else: + import uvicorn + + uvicorn.run(app, host="0.0.0.0", port=7860) diff --git a/demo/talk_to_openai/index.html b/demo/talk_to_openai/index.html new file mode 100644 index 0000000..8ba7876 --- /dev/null +++ b/demo/talk_to_openai/index.html @@ -0,0 +1,404 @@ + + + + + + + OpenAI Real-Time Chat + + + + + +
+
+ +
+
+
+
+ +
+
+ + + + + + \ No newline at end of file diff --git a/demo/talk_to_openai/requirements.txt b/demo/talk_to_openai/requirements.txt new file mode 100644 index 0000000..0480de2 --- /dev/null +++ b/demo/talk_to_openai/requirements.txt @@ -0,0 +1,4 @@ +fastrtc[vad] +openai +twilio +python-dotenv \ No newline at end of file diff --git a/demo/talk_to_sambanova/README.md b/demo/talk_to_sambanova/README.md new file mode 100644 index 0000000..62c88c4 --- /dev/null +++ b/demo/talk_to_sambanova/README.md @@ -0,0 +1,15 @@ +--- +title: Talk to Sambanova +emoji: 💻 +colorFrom: purple +colorTo: red +sdk: gradio +sdk_version: 5.16.0 +app_file: app.py +pinned: false +license: mit +short_description: Llama 3.2 - SambaNova API +tags: [webrtc, websocket, gradio, secret|TWILIO_ACCOUNT_SID, secret|TWILIO_AUTH_TOKEN, secret|SAMBANOVA_API_KEY] +--- + +Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference \ No newline at end of file diff --git a/demo/talk_to_sambanova/README_gradio.md b/demo/talk_to_sambanova/README_gradio.md new file mode 100644 index 0000000..866848c --- /dev/null +++ b/demo/talk_to_sambanova/README_gradio.md @@ -0,0 +1,15 @@ +--- +title: Talk to Sambanova (Gradio) +emoji: 💻 +colorFrom: purple +colorTo: red +sdk: gradio +sdk_version: 5.16.0 +app_file: app.py +pinned: false +license: mit +short_description: Llama 3.2 - SambaNova API (Gradio) +tags: [webrtc, websocket, gradio, secret|TWILIO_ACCOUNT_SID, secret|TWILIO_AUTH_TOKEN, secret|SAMBANOVA_API_KEY] +--- + +Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference \ No newline at end of file diff --git a/demo/talk_to_sambanova/app.py b/demo/talk_to_sambanova/app.py new file mode 100644 index 0000000..7add9ef --- /dev/null +++ b/demo/talk_to_sambanova/app.py @@ -0,0 +1,144 @@ +import base64 +import json +import os +from pathlib import Path + +import gradio as gr +import huggingface_hub +import numpy as np +from dotenv import load_dotenv +from fastapi import FastAPI +from fastapi.responses import HTMLResponse, StreamingResponse +from fastrtc import ( + AdditionalOutputs, + ReplyOnPause, + Stream, + get_stt_model, + get_twilio_turn_credentials, +) +from gradio.utils import get_space +from pydantic import BaseModel + +load_dotenv() + +curr_dir = Path(__file__).parent + + +client = huggingface_hub.InferenceClient( + api_key=os.environ.get("SAMBANOVA_API_KEY"), + provider="sambanova", +) +stt_model = get_stt_model() + + +def response( + audio: tuple[int, np.ndarray], + gradio_chatbot: list[dict] | None = None, + conversation_state: list[dict] | None = None, +): + gradio_chatbot = gradio_chatbot or [] + conversation_state = conversation_state or [] + print("chatbot", gradio_chatbot) + + text = stt_model.stt(audio) + sample_rate, array = audio + gradio_chatbot.append( + {"role": "user", "content": gr.Audio((sample_rate, array.squeeze()))} + ) + yield AdditionalOutputs(gradio_chatbot, conversation_state) + + conversation_state.append({"role": "user", "content": text}) + request = client.chat.completions.create( + model="meta-llama/Llama-3.2-3B-Instruct", + messages=conversation_state, # type: ignore + temperature=0.1, + top_p=0.1, + ) + response = {"role": "assistant", "content": request.choices[0].message.content} + + conversation_state.append(response) + gradio_chatbot.append(response) + + yield AdditionalOutputs(gradio_chatbot, conversation_state) + + +chatbot = gr.Chatbot(type="messages", value=[]) +state = gr.State(value=[]) +stream = Stream( + ReplyOnPause( + response, # type: ignore + input_sample_rate=16000, + ), + mode="send", + modality="audio", + additional_inputs=[chatbot, state], + additional_outputs=[chatbot, state], + additional_outputs_handler=lambda *a: (a[2], a[3]), + concurrency_limit=20 if get_space() else None, + rtc_configuration=get_twilio_turn_credentials() if get_space() else None, +) + +app = FastAPI() +stream.mount(app) + + +class Message(BaseModel): + role: str + content: str + + +class InputData(BaseModel): + webrtc_id: str + chatbot: list[Message] + state: list[Message] + + +@app.get("/") +async def _(): + rtc_config = get_twilio_turn_credentials() if get_space() else None + html_content = (curr_dir / "index.html").read_text() + html_content = html_content.replace("__RTC_CONFIGURATION__", json.dumps(rtc_config)) + return HTMLResponse(content=html_content) + + +@app.post("/input_hook") +async def _(data: InputData): + body = data.model_dump() + stream.set_input(data.webrtc_id, body["chatbot"], body["state"]) + + +def audio_to_base64(file_path): + audio_format = "wav" + with open(file_path, "rb") as audio_file: + encoded_audio = base64.b64encode(audio_file.read()).decode("utf-8") + return f"data:audio/{audio_format};base64,{encoded_audio}" + + +@app.get("/outputs") +async def _(webrtc_id: str): + async def output_stream(): + async for output in stream.output_stream(webrtc_id): + chatbot = output.args[0] + state = output.args[1] + data = { + "message": state[-1], + "audio": audio_to_base64(chatbot[-1]["content"].value["path"]) + if chatbot[-1]["role"] == "user" + else None, + } + yield f"event: output\ndata: {json.dumps(data)}\n\n" + + return StreamingResponse(output_stream(), media_type="text/event-stream") + + +if __name__ == "__main__": + import os + + if (mode := os.getenv("MODE")) == "UI": + stream.ui.launch(server_port=7860) + elif mode == "PHONE": + raise ValueError("Phone mode not supported") + else: + import uvicorn + + uvicorn.run(app, host="0.0.0.0", port=7860) diff --git a/demo/talk_to_sambanova/index.html b/demo/talk_to_sambanova/index.html new file mode 100644 index 0000000..d4e206a --- /dev/null +++ b/demo/talk_to_sambanova/index.html @@ -0,0 +1,487 @@ + + + + + + + Talk to Sambanova + + + + + +
+
+ +
+
+
+
+
+
+
+
+
+
+
+ +
+
+ + + + + + \ No newline at end of file diff --git a/demo/talk_to_sambanova/requirements.txt b/demo/talk_to_sambanova/requirements.txt new file mode 100644 index 0000000..5642a08 --- /dev/null +++ b/demo/talk_to_sambanova/requirements.txt @@ -0,0 +1,4 @@ +fastrtc[vad, stt] +python-dotenv +huggingface_hub>=0.29.0 +twilio \ No newline at end of file diff --git a/demo/talk_to_smolagents/README.md b/demo/talk_to_smolagents/README.md new file mode 100644 index 0000000..79c593c --- /dev/null +++ b/demo/talk_to_smolagents/README.md @@ -0,0 +1,98 @@ +--- +title: Talk to Smolagents +emoji: 💻 +colorFrom: purple +colorTo: red +sdk: gradio +sdk_version: 5.16.0 +app_file: app.py +pinned: false +license: mit +short_description: FastRTC Voice Agent with smolagents +tags: [webrtc, websocket, gradio, secret|HF_TOKEN, secret|TWILIO_ACCOUNT_SID, secret|TWILIO_AUTH_TOKEN] +--- + +# Voice LLM Agent with Image Generation + +A voice-enabled AI assistant powered by FastRTC that can: +1. Stream audio in real-time using WebRTC +2. Listen and respond with natural pauses in conversation +3. Generate images based on your requests +4. Maintain conversation context across exchanges + +This app combines the real-time communication capabilities of FastRTC with the powerful agent framework of smolagents. + +## Key Features + +- **Real-time Streaming**: Uses FastRTC's WebRTC-based audio streaming +- **Voice Activation**: Automatic detection of speech pauses to trigger responses +- **Multi-modal Interaction**: Combines voice and image generation in a single interface + +## Setup + +1. Install Python 3.9+ and create a virtual environment: + ```bash + python -m venv .venv + source .venv/bin/activate # On Windows: .venv\Scripts\activate + ``` + +2. Install dependencies: + ```bash + pip install -r requirements.txt + ``` + +3. Create a `.env` file with the following: + ``` + HF_TOKEN=your_huggingface_api_key + MODE=UI # Use 'UI' for Gradio interface, leave blank for HTML interface + ``` + +## Running the App + +### With Gradio UI (Recommended) + +```bash +MODE=UI python app.py +``` + +This launches a Gradio UI at http://localhost:7860 with: +- FastRTC's built-in streaming audio components +- A chat interface showing the conversation +- An image display panel for generated images + +## How to Use + +1. Click the microphone button to start streaming your voice. +2. Speak naturally - the app will automatically detect when you pause. +3. Ask the agent to generate an image, for example: + - "Create an image of a magical forest with glowing mushrooms." + - "Generate a picture of a futuristic city with flying cars." +4. View the generated image and hear the agent's response. + +## Technical Architecture + +### FastRTC Components + +- **Stream**: Core component that handles WebRTC connections and audio streaming +- **ReplyOnPause**: Detects when the user stops speaking to trigger a response +- **get_stt_model/get_tts_model**: Provides optimized speech-to-text and text-to-speech models + +### smolagents Components + +- **CodeAgent**: Intelligent agent that can use tools based on natural language inputs +- **Tool.from_space**: Integration with Hugging Face Spaces for image generation +- **HfApiModel**: Connection to powerful language models for understanding requests + +### Integration Flow + +1. FastRTC streams and processes audio input in real-time +2. Speech is converted to text and passed to the smolagents CodeAgent +3. The agent processes the request and calls tools when needed +4. Responses and generated images are streamed back through FastRTC +5. The UI updates to show both text responses and generated images + +## Advanced Features + +- Conversation history is maintained across exchanges +- Error handling ensures the app continues working even if agent processing fails +- The application leverages FastRTC's streaming capabilities for efficient audio transmission \ No newline at end of file diff --git a/demo/talk_to_smolagents/app.py b/demo/talk_to_smolagents/app.py new file mode 100644 index 0000000..0638c7b --- /dev/null +++ b/demo/talk_to_smolagents/app.py @@ -0,0 +1,99 @@ +from pathlib import Path +from typing import Dict, List + +from dotenv import load_dotenv +from fastrtc import ( + ReplyOnPause, + Stream, + get_stt_model, + get_tts_model, + get_twilio_turn_credentials, +) +from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel + +# Load environment variables +load_dotenv() + +# Initialize file paths +curr_dir = Path(__file__).parent + +# Initialize models +stt_model = get_stt_model() +tts_model = get_tts_model() + +# Conversation state to maintain history +conversation_state: List[Dict[str, str]] = [] + +# System prompt for agent +system_prompt = """You are a helpful assistant that can helps with finding places to +workremotely from. You should specifically check against reviews and ratings of the +place. You should use this criteria to find the best place to work from: +- Price +- Reviews +- Ratings +- Location +- WIFI +Only return the name, address of the place, and a short description of the place. +Always search for real places. +Only return real places, not fake ones. +If you receive anything other than a location, you should ask for a location. + +User: I am in Paris, France. Can you find me a place to work from? +Assistant: I found a place called "Le Café de la Paix" at 123 Rue de la Paix, +Paris, France. It has good reviews and is in a great location. + + +User: I am in London, UK. Can you find me a place to work from? +Assistant: I found a place called "The London Coffee Company". + + +User: How many people are in the room? +Assistant: I only respond to requests about finding places to work from. + + +""" + +model = HfApiModel(provider="together", model="Qwen/Qwen2.5-Coder-32B-Instruct") + +agent = CodeAgent( + tools=[ + DuckDuckGoSearchTool(), + ], + model=model, + max_steps=10, + verbosity_level=2, + description="Search the web for cafes to work from.", +) + + +def process_response(audio): + """Process audio input and generate LLM response with TTS""" + # Convert speech to text using STT model + text = stt_model.stt(audio) + if not text.strip(): + return + + input_text = f"{system_prompt}\n\n{text}" + # Get response from agent + response_content = agent.run(input_text) + + # Convert response to audio using TTS model + for audio_chunk in tts_model.stream_tts_sync(response_content or ""): + # Yield the audio chunk + yield audio_chunk + + +stream = Stream( + handler=ReplyOnPause(process_response, input_sample_rate=16000), + modality="audio", + mode="send-receive", + ui_args={ + "pulse_color": "rgb(255, 255, 255)", + "icon_button_color": "rgb(255, 255, 255)", + "title": "🧑‍💻The Coworking Agent", + }, + rtc_configuration=get_twilio_turn_credentials(), +) + +if __name__ == "__main__": + stream.ui.launch(server_port=7860) diff --git a/demo/talk_to_smolagents/requirements.txt b/demo/talk_to_smolagents/requirements.txt new file mode 100644 index 0000000..4293ca6 --- /dev/null +++ b/demo/talk_to_smolagents/requirements.txt @@ -0,0 +1,136 @@ +# This file was autogenerated by uv via the following command: +# uv export --format requirements-txt --no-hashes +aiofiles==23.2.1 +aiohappyeyeballs==2.4.6 +aiohttp==3.11.13 +aiohttp-retry==2.9.1 +aioice==0.9.0 +aiortc==1.10.1 +aiosignal==1.3.2 +annotated-types==0.7.0 +anyio==4.8.0 +async-timeout==5.0.1 ; python_full_version < '3.11' +attrs==25.1.0 +audioop-lts==0.2.1 ; python_full_version >= '3.13' +audioread==3.0.1 +av==13.1.0 +babel==2.17.0 +beautifulsoup4==4.13.3 +certifi==2025.1.31 +cffi==1.17.1 +charset-normalizer==3.4.1 +click==8.1.8 +colorama==0.4.6 +coloredlogs==15.0.1 +colorlog==6.9.0 +cryptography==44.0.1 +csvw==3.5.1 +decorator==5.2.1 +dlinfo==2.0.0 +dnspython==2.7.0 +duckduckgo-search==7.5.0 +espeakng-loader==0.2.4 +exceptiongroup==1.2.2 ; python_full_version < '3.11' +fastapi==0.115.8 +fastrtc==0.0.8.post1 +fastrtc-moonshine-onnx==20241016 +ffmpy==0.5.0 +filelock==3.17.0 +flatbuffers==25.2.10 +frozenlist==1.5.0 +fsspec==2025.2.0 +google-crc32c==1.6.0 +gradio==5.19.0 +gradio-client==1.7.2 +h11==0.14.0 +httpcore==1.0.7 +httpx==0.28.1 +huggingface-hub==0.29.1 +humanfriendly==10.0 +idna==3.10 +ifaddr==0.2.0 +isodate==0.7.2 +jinja2==3.1.5 +joblib==1.4.2 +jsonschema==4.23.0 +jsonschema-specifications==2024.10.1 +kokoro-onnx==0.4.3 +language-tags==1.2.0 +lazy-loader==0.4 +librosa==0.10.2.post1 +llvmlite==0.44.0 +lxml==5.3.1 +markdown-it-py==3.0.0 +markdownify==1.0.0 +markupsafe==2.1.5 +mdurl==0.1.2 +mpmath==1.3.0 +msgpack==1.1.0 +multidict==6.1.0 +numba==0.61.0 +numpy==2.1.3 +onnxruntime==1.20.1 +orjson==3.10.15 +packaging==24.2 +pandas==2.2.3 +phonemizer-fork==3.3.1 +pillow==11.1.0 +platformdirs==4.3.6 +pooch==1.8.2 +primp==0.14.0 +propcache==0.3.0 +protobuf==5.29.3 +pycparser==2.22 +pydantic==2.10.6 +pydantic-core==2.27.2 +pydub==0.25.1 +pyee==12.1.1 +pygments==2.19.1 +pyjwt==2.10.1 +pylibsrtp==0.11.0 +pyopenssl==25.0.0 +pyparsing==3.2.1 +pyreadline3==3.5.4 ; sys_platform == 'win32' +python-dateutil==2.9.0.post0 +python-dotenv==1.0.1 +python-multipart==0.0.20 +pytz==2025.1 +pyyaml==6.0.2 +rdflib==7.1.3 +referencing==0.36.2 +regex==2024.11.6 +requests==2.32.3 +rfc3986==1.5.0 +rich==13.9.4 +rpds-py==0.23.1 +ruff==0.9.7 ; sys_platform != 'emscripten' +safehttpx==0.1.6 +scikit-learn==1.6.1 +scipy==1.15.2 +segments==2.3.0 +semantic-version==2.10.0 +shellingham==1.5.4 ; sys_platform != 'emscripten' +six==1.17.0 +smolagents==1.9.2 +sniffio==1.3.1 +soundfile==0.13.1 +soupsieve==2.6 +soxr==0.5.0.post1 +standard-aifc==3.13.0 ; python_full_version >= '3.13' +standard-chunk==3.13.0 ; python_full_version >= '3.13' +standard-sunau==3.13.0 ; python_full_version >= '3.13' +starlette==0.45.3 +sympy==1.13.3 +threadpoolctl==3.5.0 +tokenizers==0.21.0 +tomlkit==0.13.2 +tqdm==4.67.1 +twilio==9.4.6 +typer==0.15.1 ; sys_platform != 'emscripten' +typing-extensions==4.12.2 +tzdata==2025.1 +uritemplate==4.1.1 +urllib3==2.3.0 +uvicorn==0.34.0 ; sys_platform != 'emscripten' +websockets==15.0 +yarl==1.18.3 diff --git a/demo/video.mp4 b/demo/video.mp4 new file mode 100644 index 0000000..09e49ec Binary files /dev/null and b/demo/video.mp4 differ diff --git a/demo/voice_text_editor/README.md b/demo/voice_text_editor/README.md new file mode 100644 index 0000000..710bf91 --- /dev/null +++ b/demo/voice_text_editor/README.md @@ -0,0 +1,19 @@ +--- +title: Voice Text Editor +emoji: 📝 +colorFrom: purple +colorTo: red +sdk: gradio +sdk_version: 5.16.0 +app_file: app.py +pinned: false +license: mit +short_description: Edit text documents with your voice! +tags: [webrtc, websocket, gradio, secret|HF_TOKEN, secret|SAMBANOVA_API_KEY] +--- + +# Voice Text Editor + +Edit text documents with your voice! + + diff --git a/demo/voice_text_editor/app.py b/demo/voice_text_editor/app.py new file mode 100644 index 0000000..744b51e --- /dev/null +++ b/demo/voice_text_editor/app.py @@ -0,0 +1,113 @@ +import os + +import gradio as gr +from dotenv import load_dotenv +from fastrtc import AdditionalOutputs, ReplyOnPause, Stream, get_stt_model +from openai import OpenAI + +load_dotenv() + +sambanova_client = OpenAI( + api_key=os.getenv("SAMBANOVA_API_KEY"), base_url="https://api.sambanova.ai/v1" +) +stt_model = get_stt_model() + + +SYSTEM_PROMPT = """You are an intelligent voice-activated text editor assistant. Your purpose is to help users create and modify text documents through voice commands. + +For each interaction: +1. You will receive the current state of a text document and a voice input from the user. +2. Determine if the input is: + a) A command to modify the document (e.g., "delete the last line", "capitalize that") + b) Content to be added to the document (e.g., "buy 12 eggs at the store") + c) A modification to existing content (e.g., "actually make that 24" to change "12" to "24") +3. Return ONLY the new document state after the changes have been applied. + +Example: + +CURRENT DOCUMENT: + + +Meeting notes: +- Buy GPUs +- Meet with Joe + +USER INPUT: Make that 100 GPUS + +NEW DOCUMENT STATE: + +Meeting notes: +- Buy 100 GPUs +- Meet with Joe + +Example 2: + +CURRENT DOCUMENT: + +Project Proposal + +USER INPUT: Make that a header + +NEW DOCUMENT STATE: + +# Project Proposal + +When handling commands: +- Apply the requested changes precisely to the document +- Support operations like adding, deleting, modifying, and moving text +- Understand contextual references like "that", "the last line", "the second paragraph" + +When handling content additions: +- Add the new text at the appropriate location (usually at the end or cursor position) +- Format it appropriately based on the document context +- If the user says to "add" or "insert" do not remove text that was already in the document. + +When handling content modifications: +- Identify what part of the document the user is referring to +- Apply the requested change while preserving the rest of the content +- Be smart about contextual references (e.g., "make that 24" should know to replace a number) + +NEVER include any text in the new document state that is not part of the user's input. +NEVER include the phrase "CURRENT DOCUMENT" in the new document state. +NEVER reword the user's input unless you are explicitly asked to do so. +""" + + +def edit(audio, current_document: str): + prompt = stt_model.stt(audio) + print(f"Prompt: {prompt}") + response = sambanova_client.chat.completions.create( + model="Meta-Llama-3.3-70B-Instruct", + messages=[ + {"role": "system", "content": SYSTEM_PROMPT}, + { + "role": "user", + "content": f"CURRENT DOCUMENT:\n\n{current_document}\n\nUSER INPUT: {prompt}", + }, + ], + max_tokens=200, + ) + doc = response.choices[0].message.content + yield AdditionalOutputs(doc) + + +doc = gr.Textbox(value="", label="Current Document") + + +stream = Stream( + ReplyOnPause(edit), + modality="audio", + mode="send", + additional_inputs=[doc], + additional_outputs=[doc], + additional_outputs_handler=lambda prev, current: current, + ui_args={"title": "Voice Text Editor with FastRTC 🗣️"}, +) + +if __name__ == "__main__": + if (mode := os.getenv("MODE")) == "UI": + stream.ui.launch(server_port=7860) + elif mode == "PHONE": + stream.fastphone(host="0.0.0.0", port=7860) + else: + stream.ui.launch(server_port=7860) diff --git a/demo/voice_text_editor_local/app.py b/demo/voice_text_editor_local/app.py new file mode 100644 index 0000000..1e6e61f --- /dev/null +++ b/demo/voice_text_editor_local/app.py @@ -0,0 +1,126 @@ +import os + +import gradio as gr +import requests +from dotenv import load_dotenv +from fastrtc import AdditionalOutputs, ReplyOnPause, Stream, get_stt_model + +load_dotenv() + +stt_model = get_stt_model() + +SYSTEM_PROMPT = """You are an intelligent voice-activated text editor assistant. Your purpose is to help users create and modify text documents through voice commands. + +For each interaction: +1. You will receive the current state of a text document and a voice input from the user. +2. Determine if the input is: + a) A command to modify the document (e.g., "delete the last line", "capitalize that") + b) Content to be added to the document (e.g., "buy 12 eggs at the store") + c) A modification to existing content (e.g., "actually make that 24" to change "12" to "24") +3. Return ONLY the new document state after the changes have been applied. + +Example: + +CURRENT DOCUMENT: + +Meeting notes: +- Buy GPUs +- Meet with Joe + +USER INPUT: Make that 100 GPUS + +NEW DOCUMENT STATE: + +Meeting notes: +- Buy 100 GPUs +- Meet with Joe + +Example 2: + +CURRENT DOCUMENT: + +Project Proposal + +USER INPUT: Make that a header + +NEW DOCUMENT STATE: + +# Project Proposal + +When handling commands: +- Apply the requested changes precisely to the document +- Support operations like adding, deleting, modifying, and moving text +- Understand contextual references like "that", "the last line", "the second paragraph" + +When handling content additions: +- Add the new text at the appropriate location (usually at the end or cursor position) +- Format it appropriately based on the document context +- If the user says to "add" or "insert" do not remove text that was already in the document. + +When handling content modifications: +- Identify what part of the document the user is referring to +- Apply the requested change while preserving the rest of the content +- Be smart about contextual references (e.g., "make that 24" should know to replace a number) + +NEVER include any text in the new document state that is not part of the user's input. +NEVER include the phrase "CURRENT DOCUMENT" in the new document state. +NEVER reword the user's input unless you are explicitly asked to do so. +""" + + +def edit(audio, current_document: str): + prompt = stt_model.stt(audio) + print(f"Prompt: {prompt}") + + # Construct the prompt for ollama + full_prompt = ( + f"{SYSTEM_PROMPT}\n\n" + f"User: CURRENT DOCUMENT:\n\n{current_document}\n\nUSER INPUT: {prompt}\n\n" + f"Assistant:" + ) + + try: + # Send request to ollama's API + response = requests.post( + "http://localhost:11434/api/generate", + json={ + "model": "qwen2.5", + "prompt": full_prompt, + "stream": False, + "max_tokens": 200, + }, + ) + response.raise_for_status() # Raise an exception for bad status codes + + # Parse the response + doc = response.json()["response"] + # Clean up the response to remove "Assistant:" and any extra whitespace + doc = doc.strip().lstrip("Assistant:").strip() + yield AdditionalOutputs(doc) + + except requests.RequestException as e: + # Handle API errors gracefully + error_message = "Error: Could not connect to ollama. Please ensure it's running and qwen2.5 is loaded." + print(f"API Error: {e}") + yield AdditionalOutputs(error_message) + + +doc = gr.Textbox(value="", label="Current Document") + +stream = Stream( + ReplyOnPause(edit), + modality="audio", + mode="send", + additional_inputs=[doc], + additional_outputs=[doc], + additional_outputs_handler=lambda prev, current: current, + ui_args={"title": "Voice Text Editor with FastRTC 🗣️"}, +) + +if __name__ == "__main__": + if (mode := os.getenv("MODE")) == "UI": + stream.ui.launch(server_port=7860) + elif mode == "PHONE": + stream.fastphone(host="0.0.0.0", port=7860) + else: + stream.ui.launch(server_port=7860) diff --git a/demo/webrtc_vs_websocket/README.md b/demo/webrtc_vs_websocket/README.md new file mode 100644 index 0000000..60a8b10 --- /dev/null +++ b/demo/webrtc_vs_websocket/README.md @@ -0,0 +1,15 @@ +--- +title: Webrtc Vs Websocket +emoji: 🧪 +colorFrom: purple +colorTo: red +sdk: gradio +sdk_version: 5.16.0 +app_file: app.py +pinned: false +license: mit +short_description: Compare Round Trip Times between WebRTC and Websockets +tags: [webrtc, websocket, gradio, secret|TWILIO_ACCOUNT_SID, secret|TWILIO_AUTH_TOKEN, secret|ELEVENLABS_API_KEY, secret|GROQ_API_KEY, secret|ANTHROPIC_API_KEY] +--- + +Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference \ No newline at end of file diff --git a/demo/webrtc_vs_websocket/app.py b/demo/webrtc_vs_websocket/app.py new file mode 100644 index 0000000..36e4e5b --- /dev/null +++ b/demo/webrtc_vs_websocket/app.py @@ -0,0 +1,147 @@ +import json +import logging +import os +from pathlib import Path + +import anthropic +import gradio as gr +import numpy as np +from dotenv import load_dotenv +from elevenlabs import ElevenLabs +from fastapi import FastAPI +from fastapi.responses import HTMLResponse, StreamingResponse +from fastrtc import AdditionalOutputs, ReplyOnPause, Stream, get_twilio_turn_credentials +from fastrtc.utils import aggregate_bytes_to_16bit, audio_to_bytes +from gradio.utils import get_space +from groq import Groq +from pydantic import BaseModel + +# Configure the root logger to WARNING to suppress debug messages from other libraries +logging.basicConfig(level=logging.WARNING) + +# Create a console handler +console_handler = logging.FileHandler("gradio_webrtc.log") +console_handler.setLevel(logging.DEBUG) + +# Create a formatter +formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s") +console_handler.setFormatter(formatter) + +# Configure the logger for your specific library +logger = logging.getLogger("fastrtc") +logger.setLevel(logging.DEBUG) +logger.addHandler(console_handler) + + +load_dotenv() + +groq_client = Groq() +claude_client = anthropic.Anthropic() +tts_client = ElevenLabs(api_key=os.environ["ELEVENLABS_API_KEY"]) + +curr_dir = Path(__file__).parent + + +def response( + audio: tuple[int, np.ndarray], + chatbot: list[dict] | None = None, +): + chatbot = chatbot or [] + messages = [{"role": d["role"], "content": d["content"]} for d in chatbot] + prompt = groq_client.audio.transcriptions.create( + file=("audio-file.mp3", audio_to_bytes(audio)), + model="whisper-large-v3-turbo", + response_format="verbose_json", + ).text + print("prompt", prompt) + chatbot.append({"role": "user", "content": prompt}) + messages.append({"role": "user", "content": prompt}) + response = claude_client.messages.create( + model="claude-3-5-haiku-20241022", + max_tokens=512, + messages=messages, # type: ignore + ) + response_text = " ".join( + block.text # type: ignore + for block in response.content + if getattr(block, "type", None) == "text" + ) + chatbot.append({"role": "assistant", "content": response_text}) + yield AdditionalOutputs(chatbot) + iterator = tts_client.text_to_speech.convert_as_stream( + text=response_text, + voice_id="JBFqnCBsd6RMkjVDRZzb", + model_id="eleven_multilingual_v2", + output_format="pcm_24000", + ) + for chunk in aggregate_bytes_to_16bit(iterator): + audio_array = np.frombuffer(chunk, dtype=np.int16).reshape(1, -1) + yield (24000, audio_array, "mono") + + +chatbot = gr.Chatbot(type="messages") +stream = Stream( + modality="audio", + mode="send-receive", + handler=ReplyOnPause(response), + additional_outputs_handler=lambda a, b: b, + additional_inputs=[chatbot], + additional_outputs=[chatbot], + rtc_configuration=get_twilio_turn_credentials() if get_space() else None, + concurrency_limit=20 if get_space() else None, +) + + +class Message(BaseModel): + role: str + content: str + + +class InputData(BaseModel): + webrtc_id: str + chatbot: list[Message] + + +app = FastAPI() + +stream.mount(app) + + +@app.get("/") +async def _(): + rtc_config = get_twilio_turn_credentials() if get_space() else None + html_content = (curr_dir / "index.html").read_text() + html_content = html_content.replace("__RTC_CONFIGURATION__", json.dumps(rtc_config)) + return HTMLResponse(content=html_content, status_code=200) + + +@app.post("/input_hook") +async def _(body: InputData): + stream.set_input(body.webrtc_id, body.model_dump()["chatbot"]) + return {"status": "ok"} + + +@app.get("/outputs") +def _(webrtc_id: str): + print("outputs", webrtc_id) + + async def output_stream(): + async for output in stream.output_stream(webrtc_id): + chatbot = output.args[0] + yield f"event: output\ndata: {json.dumps(chatbot[-2])}\n\n" + yield f"event: output\ndata: {json.dumps(chatbot[-1])}\n\n" + + return StreamingResponse(output_stream(), media_type="text/event-stream") + + +if __name__ == "__main__": + import os + + if (mode := os.getenv("MODE")) == "UI": + stream.ui.launch(server_port=7860, server_name="0.0.0.0") + elif mode == "PHONE": + stream.fastphone(host="0.0.0.0", port=7860) + else: + import uvicorn + + uvicorn.run(app, host="0.0.0.0", port=7860) diff --git a/demo/webrtc_vs_websocket/index.html b/demo/webrtc_vs_websocket/index.html new file mode 100644 index 0000000..cbc72b0 --- /dev/null +++ b/demo/webrtc_vs_websocket/index.html @@ -0,0 +1,630 @@ + + + + + + + WebRTC vs WebSocket Benchmark + + + + + + + +
+ This page compares the WebRTC Round-Trip-Time calculated from getStats() to the time taken to + process a ping/pong response pattern over websockets. It may not be a gold standard benchmark. Both WebRTC and + Websockets have their merits/advantages which is why FastRTC supports both. Artifacts in the WebSocket playback + audio are due to gaps in my frontend processing code and not FastRTC web server. +
+ +
+
+

WebRTC Connection

+
+
+
RTT (Round Trip Time): -
+
+ +
+ +
+

WebSocket Connection

+
+
+
RTT (Round Trip Time): 0
+
+ +
+
+ + + + +
+ + + + + \ No newline at end of file diff --git a/demo/webrtc_vs_websocket/requirements.txt b/demo/webrtc_vs_websocket/requirements.txt new file mode 100644 index 0000000..dd9323b --- /dev/null +++ b/demo/webrtc_vs_websocket/requirements.txt @@ -0,0 +1,6 @@ +fastrtc[vad] +elevenlabs +groq +anthropic +twilio +python-dotenv diff --git a/demo/whisper_realtime/README.md b/demo/whisper_realtime/README.md new file mode 100644 index 0000000..ec7e6cc --- /dev/null +++ b/demo/whisper_realtime/README.md @@ -0,0 +1,15 @@ +--- +title: Whisper Realtime Transcription +emoji: 👂 +colorFrom: purple +colorTo: red +sdk: gradio +sdk_version: 5.16.0 +app_file: app.py +pinned: false +license: mit +short_description: Transcribe audio in realtime with Whisper +tags: [webrtc, websocket, gradio, secret|TWILIO_ACCOUNT_SID, secret|TWILIO_AUTH_TOKEN, secret|GROQ_API_KEY] +--- + +Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference \ No newline at end of file diff --git a/demo/whisper_realtime/README_gradio.md b/demo/whisper_realtime/README_gradio.md new file mode 100644 index 0000000..37b8d2f --- /dev/null +++ b/demo/whisper_realtime/README_gradio.md @@ -0,0 +1,22 @@ +--- +app_file: app.py +colorFrom: purple +colorTo: red +emoji: 👂 +license: mit +pinned: false +sdk: gradio +sdk_version: 5.16.0 +short_description: Transcribe audio in realtime - Gradio UI version +tags: +- webrtc +- websocket +- gradio +- secret|TWILIO_ACCOUNT_SID +- secret|TWILIO_AUTH_TOKEN +- secret|GROQ_API_KEY +title: Whisper Realtime Transcription (Gradio UI) +--- + + +Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference \ No newline at end of file diff --git a/demo/whisper_realtime/app.py b/demo/whisper_realtime/app.py new file mode 100644 index 0000000..a364830 --- /dev/null +++ b/demo/whisper_realtime/app.py @@ -0,0 +1,93 @@ +import json +from pathlib import Path + +import gradio as gr +import numpy as np +from dotenv import load_dotenv +from fastapi import FastAPI +from fastapi.responses import HTMLResponse, StreamingResponse +from fastrtc import ( + AdditionalOutputs, + ReplyOnPause, + Stream, + audio_to_bytes, + get_twilio_turn_credentials, +) +from gradio.utils import get_space +from groq import AsyncClient +from pydantic import BaseModel + +cur_dir = Path(__file__).parent + +load_dotenv() + + +groq_client = AsyncClient() + + +async def transcribe(audio: tuple[int, np.ndarray], transcript: str): + response = await groq_client.audio.transcriptions.create( + file=("audio-file.mp3", audio_to_bytes(audio)), + model="whisper-large-v3-turbo", + response_format="verbose_json", + ) + yield AdditionalOutputs(transcript + "\n" + response.text) + + +transcript = gr.Textbox(label="Transcript") +stream = Stream( + ReplyOnPause(transcribe), + modality="audio", + mode="send", + additional_inputs=[transcript], + additional_outputs=[transcript], + additional_outputs_handler=lambda a, b: b, + rtc_configuration=get_twilio_turn_credentials() if get_space() else None, + concurrency_limit=5 if get_space() else None, + time_limit=90 if get_space() else None, +) + +app = FastAPI() + +stream.mount(app) + + +class SendInput(BaseModel): + webrtc_id: str + transcript: str + + +@app.post("/send_input") +def send_input(body: SendInput): + stream.set_input(body.webrtc_id, body.transcript) + + +@app.get("/transcript") +def _(webrtc_id: str): + async def output_stream(): + async for output in stream.output_stream(webrtc_id): + transcript = output.args[0].split("\n")[-1] + yield f"event: output\ndata: {transcript}\n\n" + + return StreamingResponse(output_stream(), media_type="text/event-stream") + + +@app.get("/") +def index(): + rtc_config = get_twilio_turn_credentials() if get_space() else None + html_content = (cur_dir / "index.html").read_text() + html_content = html_content.replace("__RTC_CONFIGURATION__", json.dumps(rtc_config)) + return HTMLResponse(content=html_content) + + +if __name__ == "__main__": + import os + + if (mode := os.getenv("MODE")) == "UI": + stream.ui.launch(server_port=7860) + elif mode == "PHONE": + stream.fastphone(host="0.0.0.0", port=7860) + else: + import uvicorn + + uvicorn.run(app, host="0.0.0.0", port=7860) diff --git a/demo/whisper_realtime/index.html b/demo/whisper_realtime/index.html new file mode 100644 index 0000000..d757040 --- /dev/null +++ b/demo/whisper_realtime/index.html @@ -0,0 +1,435 @@ + + + + + + + Real-time Whisper Transcription + + + + + +
+
+

Real-time Transcription

+

Powered by Groq and FastRTC

+
+ +
+
+
+
+ +
+
+ + + + + \ No newline at end of file diff --git a/demo/whisper_realtime/requirements.txt b/demo/whisper_realtime/requirements.txt new file mode 100644 index 0000000..5ade2d4 --- /dev/null +++ b/demo/whisper_realtime/requirements.txt @@ -0,0 +1,4 @@ +fastrtc[vad] +groq +python-dotenv +twilio \ No newline at end of file diff --git a/dist/fastrtc-0.0.15.dev0-py3-none-any.whl b/dist/fastrtc-0.0.15.dev0-py3-none-any.whl new file mode 100644 index 0000000..c153408 Binary files /dev/null and b/dist/fastrtc-0.0.15.dev0-py3-none-any.whl differ diff --git a/docs/CNAME b/docs/CNAME new file mode 100644 index 0000000..a35e970 --- /dev/null +++ b/docs/CNAME @@ -0,0 +1 @@ +fastrtc.org \ No newline at end of file diff --git a/docs/Discord-Symbol-White.svg b/docs/Discord-Symbol-White.svg new file mode 100644 index 0000000..bd25430 --- /dev/null +++ b/docs/Discord-Symbol-White.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/docs/advanced-configuration.md b/docs/advanced-configuration.md index 4dae09b..8c388d9 100644 --- a/docs/advanced-configuration.md +++ b/docs/advanced-configuration.md @@ -1,3 +1,5 @@ +Any of the parameters for the `Stream` class can be passed to the [`WebRTC`](../userguide/gradio) component directly. + ## Track Constraints You can specify the `track_constraints` parameter to control how the data is streamed to the server. The full documentation on track constraints is [here](https://developer.mozilla.org/en-US/docs/Web/API/MediaTrackConstraints#constraints). @@ -10,21 +12,21 @@ track_constraints = { "height": {"exact": 500}, "frameRate": {"ideal": 30}, } -webrtc = WebRTC(track_constraints=track_constraints, - modality="video", - mode="send-receive") +webrtc = Stream( + handler=..., + track_constraints=track_constraints, + modality="video", + mode="send-receive") ``` - !!! warning - WebRTC may not enforce your constaints. For example, it may rescale your video - (while keeping the same resolution) in order to maintain the desired (or reach a better) frame rate. If you - really want to enforce height, width and resolution constraints, use the `rtp_params` parameter as set `"degradationPreference": "maintain-resolution"`. +WebRTC may not enforce your constraints. For example, it may rescale your video +(while keeping the same resolution) in order to maintain the desired frame rate (or reach a better one). If you really want to enforce height, width and resolution constraints, use the `rtp_params` parameter as set `"degradationPreference": "maintain-resolution"`. ```python - image = WebRTC( - label="Stream", + image = Stream( + modality="video", mode="send", track_constraints=track_constraints, rtp_params={"degradationPreference": "maintain-resolution"} @@ -36,7 +38,8 @@ webrtc = WebRTC(track_constraints=track_constraints, You can configure how the connection is created on the client by passing an `rtc_configuration` parameter to the `WebRTC` component constructor. See the list of available arguments [here](https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/RTCPeerConnection#configuration). -When deploying on a remote server, an `rtc_configuration` parameter must be passed in. See [Deployment](/deployment). +!!! warning +When deploying on a remote server, the `rtc_configuration` parameter must be passed in. See [Deployment](../deployment). ## Reply on Pause Voice-Activity-Detection @@ -50,58 +53,52 @@ The `ReplyOnPause` class runs a Voice Activity Detection (VAD) algorithm to dete The following parameters control this argument: ```python -from gradio_webrtc import AlgoOptions, ReplyOnPause, WebRTC - +from fastrtc import AlgoOptions, ReplyOnPause, Stream options = AlgoOptions(audio_chunk_duration=0.6, # (1) started_talking_threshold=0.2, # (2) speech_threshold=0.1, # (3) ) -with gr.Blocks as demo: - audio = WebRTC(...) - audio.stream(ReplyOnPause(..., algo_options=algo_options) - ) - -demo.launch() +Stream( + handler=ReplyOnPause(..., algo_options=algo_options), + modality="audio", + mode="send-receive" +) ``` 1. This is the length (in seconds) of audio chunks. 2. If the chunk has more than 0.2 seconds of speech, the user started talking. 3. If, after the user started speaking, there is a chunk with less than 0.1 seconds of speech, the user stopped speaking. - ## Stream Handler Input Audio You can configure the sampling rate of the audio passed to the `ReplyOnPause` or `StreamHandler` instance with the `input_sampling_rate` parameter. The current default is `48000` ```python -from gradio_webrtc import ReplyOnPause, WebRTC +from fastrtc import ReplyOnPause, Stream -with gr.Blocks as demo: - audio = WebRTC(...) - audio.stream(ReplyOnPause(..., input_sampling_rate=24000) - ) - -demo.launch() +stream = Stream( + handler=ReplyOnPause(..., input_sampling_rate=24000), + modality="audio", + mode="send-receive" +) ``` - ## Stream Handler Output Audio -You can configure the output audio chunk size of `ReplyOnPause` (and any `StreamHandler`) +You can configure the output audio chunk size of `ReplyOnPause` (and any `StreamHandler`) with the `output_sample_rate` and `output_frame_size` parameters. The following code (which uses the default values of these parameters), states that each output chunk will be a frame of 960 samples at a frame rate of `24,000` hz. So it will correspond to `0.04` seconds. ```python -from gradio_webrtc import ReplyOnPause, WebRTC +from fastrtc import ReplyOnPause, Stream -with gr.Blocks as demo: - audio = WebRTC(...) - audio.stream(ReplyOnPause(..., output_sample_rate=24000, output_frame_size=960) - ) - -demo.launch() +stream = Stream( + handler=ReplyOnPause(..., output_sample_rate=24000, output_frame_size=960), + modality="audio", + mode="send-receive" +) ``` !!! tip @@ -109,7 +106,6 @@ demo.launch() In general it is best to leave these settings untouched. In some cases, lowering the output_frame_size can yield smoother audio playback. - ## Audio Icon You can display an icon of your choice instead of the default wave animation for audio streaming. @@ -117,7 +113,15 @@ Pass any local path or url to an image (svg, png, jpeg) to the components `icon` You can control the button color and pulse color with `icon_button_color` and `pulse_color` parameters. They can take any valid css color. -=== "Code" +# <<<<<<< HEAD + +!!! warning + + The `icon` parameter is only supported in the `WebRTC` component. + +> > > > > > > video-chat +> > > > > > > === "Code" + ``` python audio = WebRTC( label="Stream", @@ -128,8 +132,9 @@ You can control the button color and pulse color with `icon_button_color` and `p ) ``` + === "Code Custom colors" - ``` python +`python audio = WebRTC( label="Stream", rtc_configuration=rtc_configuration, @@ -139,16 +144,23 @@ You can control the button color and pulse color with `icon_button_color` and `p icon_button_color="black", pulse_color="black", ) - ``` - - + ` + ## Changing the Button Text You can supply a `button_labels` dictionary to change the text displayed in the `Start`, `Stop` and `Waiting` buttons that are displayed in the UI. The keys must be `"start"`, `"stop"`, and `"waiting"`. -``` python +# <<<<<<< HEAD + +!!! warning + + The `button_labels` parameter is only supported in the `WebRTC` component. + +> > > > > > > video-chat + +```python webrtc = WebRTC( label="Video Chat", modality="audio-video", diff --git a/docs/cookbook.md b/docs/cookbook.md index 0cb7910..31db8b1 100644 --- a/docs/cookbook.md +++ b/docs/cookbook.md @@ -1,172 +1,340 @@ + + +A collection of applications built with FastRTC. Click on the tags below to find the app you're looking for! + +
+ + + + + + + + + + + + + + + +
+ + +
-- :speaking_head:{ .lg .middle }:eyes:{ .lg .middle } __Gemini Audio Video Chat__ +- :speaking_head:{ .lg .middle }:eyes:{ .lg .middle } **Gemini Audio Video Chat** + {: data-tags="audio,video,real-time-api"} - --- + --- - Stream BOTH your webcam video and audio feeds to Google Gemini. You can also upload images to augment your conversation! + Stream BOTH your webcam video and audio feeds to Google Gemini. You can also upload images to augment your conversation! - + - [:octicons-arrow-right-24: Demo](https://huggingface.co/spaces/freddyaboulton/gemini-audio-video-chat) - - [:octicons-code-16: Code](https://huggingface.co/spaces/freddyaboulton/gemini-audio-video-chat/blob/main/app.py) + [:octicons-arrow-right-24: Demo](https://huggingface.co/spaces/fastrtc/gemini-audio-video) -- :speaking_head:{ .lg .middle } __Google Gemini Real Time Voice API__ + [:octicons-arrow-right-24: Gradio UI](https://huggingface.co/spaces/fastrtc/gemini-audio-video) - --- + [:octicons-code-16: Code](https://huggingface.co/spaces/fastrtc/gemini-audio-video/blob/main/app.py) - Talk to Gemini in real time using Google's voice API. +- :speaking_head:{ .lg .middle } **Google Gemini Real Time Voice API** + {: data-tags="audio,real-time-api,voice-chat"} - + --- - [:octicons-arrow-right-24: Demo](https://huggingface.co/spaces/freddyaboulton/gemini-voice) - - [:octicons-code-16: Code](https://huggingface.co/spaces/freddyaboulton/gemini-voice/blob/main/app.py) + Talk to Gemini in real time using Google's voice API. -- :speaking_head:{ .lg .middle } __OpenAI Real Time Voice API__ + - --- + [:octicons-arrow-right-24: Demo](https://huggingface.co/spaces/fastrtc/talk-to-gemini) - Talk to ChatGPT in real time using OpenAI's voice API. + [:octicons-arrow-right-24: Gradio UI](https://huggingface.co/spaces/fastrtc/talk-to-gemini-gradio) - + [:octicons-code-16: Code](https://huggingface.co/spaces/fastrtc/talk-to-gemini/blob/main/app.py) - [:octicons-arrow-right-24: Demo](https://huggingface.co/spaces/freddyaboulton/openai-realtime-voice) - - [:octicons-code-16: Code](https://huggingface.co/spaces/freddyaboulton/openai-realtime-voice/blob/main/app.py) +- :speaking_head:{ .lg .middle } **OpenAI Real Time Voice API** + {: data-tags="audio,real-time-api,voice-chat"} -- :speaking_head:{ .lg .middle } __Hello Llama: Stop Word Detection__ + --- - --- + Talk to ChatGPT in real time using OpenAI's voice API. - A code editor built with Llama 3.3 70b that is triggered by the phrase "Hello Llama". - Build a Siri-like coding assistant in 100 lines of code! + - + [:octicons-arrow-right-24: Demo](https://huggingface.co/spaces/fastrtc/talk-to-openai) - [:octicons-arrow-right-24: Demo](hhttps://huggingface.co/spaces/freddyaboulton/hey-llama-code-editor) - - [:octicons-code-16: Code](https://huggingface.co/spaces/freddyaboulton/hey-llama-code-editor/blob/main/app.py) + [:octicons-arrow-right-24: Gradio UI](https://huggingface.co/spaces/fastrtc/talk-to-openai-gradio) -- :robot:{ .lg .middle } __Llama Code Editor__ + [:octicons-code-16: Code](https://huggingface.co/spaces/fastrtc/talk-to-openai/blob/main/app.py) - --- +- :robot:{ .lg .middle } **Hello Computer** + {: data-tags="llm,stopword,sambanova"} - Create and edit HTML pages with just your voice! Powered by SambaNova systems. + --- - + Say computer before asking your question! + - [:octicons-arrow-right-24: Demo](https://huggingface.co/spaces/freddyaboulton/llama-code-editor) - - [:octicons-code-16: Code](https://huggingface.co/spaces/freddyaboulton/llama-code-editor/blob/main/app.py) + [:octicons-arrow-right-24: Demo](https://huggingface.co/spaces/fastrtc/hello-computer) -- :speaking_head:{ .lg .middle } __Audio Input/Output with mini-omni2__ + [:octicons-arrow-right-24: Gradio UI](https://huggingface.co/spaces/fastrtc/hello-computer-gradio) - --- + [:octicons-code-16: Code](https://huggingface.co/spaces/fastrtc/hello-computer/blob/main/app.py) - Build a GPT-4o like experience with mini-omni2, an audio-native LLM. +- :robot:{ .lg .middle } **Llama Code Editor** + {: data-tags="audio,llm,code-generation,groq,stopword"} - + --- - [:octicons-arrow-right-24: Demo](https://huggingface.co/spaces/freddyaboulton/mini-omni2-webrtc) - - [:octicons-code-16: Code](https://huggingface.co/spaces/freddyaboulton/mini-omni2-webrtc/blob/main/app.py) + Create and edit HTML pages with just your voice! Powered by Groq! -- :speaking_head:{ .lg .middle } __Talk to Claude__ + - --- + [:octicons-arrow-right-24: Demo](https://huggingface.co/spaces/fastrtc/llama-code-editor) - Use the Anthropic and Play.Ht APIs to have an audio conversation with Claude. + [:octicons-code-16: Code](https://huggingface.co/spaces/fastrtc/llama-code-editor/blob/main/app.py) - +- :speaking_head:{ .lg .middle } **SmolAgents with Voice** + {: data-tags="audio,llm,voice-chat,agentic"} - [:octicons-arrow-right-24: Demo](https://huggingface.co/spaces/freddyaboulton/talk-to-claude) - - [:octicons-code-16: Code](https://huggingface.co/spaces/freddyaboulton/talk-to-claude/blob/main/app.py) + --- -- :speaking_head:{ .lg .middle } __Kyutai Moshi__ + Build a voice-based smolagent to find a coworking space! - --- + - Kyutai's moshi is a novel speech-to-speech model for modeling human conversations. + [:octicons-arrow-right-24: Demo](https://huggingface.co/spaces/burtenshaw/coworking_agent/) - + [:octicons-code-16: Code](https://huggingface.co/spaces/burtenshaw/coworking_agent/blob/main/app.py) - [:octicons-arrow-right-24: Demo](https://huggingface.co/spaces/freddyaboulton/talk-to-moshi) - - [:octicons-code-16: Code](https://huggingface.co/spaces/freddyaboulton/talk-to-moshi/blob/main/app.py) +- :speaking_head:{ .lg .middle } **Talk to Claude** + {: data-tags="audio,llm,voice-chat"} -- :speaking_head:{ .lg .middle } __Talk to Ultravox__ + --- - --- + Use the Anthropic and Play.Ht APIs to have an audio conversation with Claude. - Talk to Fixie.AI's audio-native Ultravox LLM with the transformers library. + - + [:octicons-arrow-right-24: Demo](https://huggingface.co/spaces/burtenshaw/coworking_agent) - [:octicons-arrow-right-24: Demo](https://huggingface.co/spaces/freddyaboulton/talk-to-ultravox) + [:octicons-arrow-right-24: Gradio UI](https://huggingface.co/spaces/burtenshaw/coworking_agent) - [:octicons-code-16: Code](https://huggingface.co/spaces/freddyaboulton/talk-to-ultravox/blob/main/app.py) + [:octicons-code-16: Code](https://huggingface.co/spaces/fastrtc/talk-to-claude/blob/main/app.py) +- :musical_note:{ .lg .middle } **LLM Voice Chat** + {: data-tags="audio,llm,voice-chat,groq,elevenlabs"} -- :speaking_head:{ .lg .middle } __Talk to Llama 3.2 3b__ + --- - --- + Talk to an LLM with ElevenLabs! - Use the Lepton API to make Llama 3.2 talk back to you! + - + [:octicons-arrow-right-24: Demo](https://huggingface.co/spaces/fastrtc/llm-voice-chat) - [:octicons-arrow-right-24: Demo](https://huggingface.co/spaces/freddyaboulton/llama-3.2-3b-voice-webrtc) + [:octicons-arrow-right-24: Gradio UI](https://huggingface.co/spaces/fastrtc/llm-voice-chat-gradio) - [:octicons-code-16: Code](https://huggingface.co/spaces/freddyaboulton/llama-3.2-3b-voice-webrtc/blob/main/app.py) + [:octicons-code-16: Code](https://huggingface.co/spaces/fastrtc/llm-voice-chat/blob/main/app.py) +- :musical_note:{ .lg .middle } **Whisper Transcription** + {: data-tags="audio,transcription,groq"} -- :robot:{ .lg .middle } __Talk to Qwen2-Audio__ + --- - --- + Have whisper transcribe your speech in real time! - Qwen2-Audio is a SOTA audio-to-text LLM developed by Alibaba. + - + [:octicons-arrow-right-24: Demo](https://huggingface.co/spaces/fastrtc/whisper-realtime) - [:octicons-arrow-right-24: Demo](https://huggingface.co/spaces/freddyaboulton/talk-to-qwen-webrtc) + [:octicons-arrow-right-24: Gradio UI](https://huggingface.co/spaces/fastrtc/whisper-realtime-gradio) - [:octicons-code-16: Code](https://huggingface.co/spaces/freddyaboulton/talk-to-qwen-webrtc/blob/main/app.py) + [:octicons-code-16: Code](https://huggingface.co/spaces/fastrtc/whisper-realtime/blob/main/app.py) +- :robot:{ .lg .middle } **Talk to Sambanova** + {: data-tags="llm,stopword,sambanova"} -- :camera:{ .lg .middle } __Yolov10 Object Detection__ + --- - --- + Talk to Llama 3.2 with the SambaNova API. + - Run the Yolov10 model on a user webcam stream in real time! + [:octicons-arrow-right-24: Demo](https://huggingface.co/spaces/fastrtc/talk-to-sambanova) - + [:octicons-arrow-right-24: Gradio UI](https://huggingface.co/spaces/fastrtc/talk-to-sambanova-gradio) - [:octicons-arrow-right-24: Demo](https://huggingface.co/spaces/freddyaboulton/webrtc-yolov10n) + [:octicons-code-16: Code](https://huggingface.co/spaces/fastrtc/talk-to-sambanova/blob/main/app.py) - [:octicons-code-16: Code](https://huggingface.co/spaces/freddyaboulton/webrtc-yolov10n/blob/main/app.py) +- :speaking_head:{ .lg .middle } **Hello Llama: Stop Word Detection** + {: data-tags="audio,llm,code-generation,stopword,sambanova"} -- :camera:{ .lg .middle } __Video Object Detection with RT-DETR__ + --- - --- + A code editor built with Llama 3.3 70b that is triggered by the phrase "Hello Llama". + Build a Siri-like coding assistant in 100 lines of code! - Upload a video and stream out frames with detected objects (powered by RT-DETR) model. + - [:octicons-arrow-right-24: Demo](https://huggingface.co/spaces/freddyaboulton/rt-detr-object-detection-webrtc) + [:octicons-arrow-right-24: Demo](https://huggingface.co/spaces/freddyaboulton/hey-llama-code-editor) - [:octicons-code-16: Code](https://huggingface.co/spaces/freddyaboulton/rt-detr-object-detection-webrtc/blob/main/app.py) + [:octicons-code-16: Code](https://huggingface.co/spaces/freddyaboulton/hey-llama-code-editor/blob/main/app.py) -- :speaker:{ .lg .middle } __Text-to-Speech with Parler__ +- :speaking_head:{ .lg .middle } **Audio Input/Output with mini-omni2** + {: data-tags="audio,llm,voice-chat"} - --- + --- - Stream out audio generated by Parler TTS! + Build a GPT-4o like experience with mini-omni2, an audio-native LLM. - [:octicons-arrow-right-24: Demo](https://huggingface.co/spaces/freddyaboulton/parler-tts-streaming-webrtc) + - [:octicons-code-16: Code](https://huggingface.co/spaces/freddyaboulton/parler-tts-streaming-webrtc/blob/main/app.py) + [:octicons-arrow-right-24: Demo](https://huggingface.co/spaces/freddyaboulton/mini-omni2-webrtc) + [:octicons-code-16: Code](https://huggingface.co/spaces/freddyaboulton/mini-omni2-webrtc/blob/main/app.py) -
\ No newline at end of file +- :speaking_head:{ .lg .middle } **Kyutai Moshi** + {: data-tags="audio,llm,voice-chat,kyutai"} + + --- + + Kyutai's moshi is a novel speech-to-speech model for modeling human conversations. + + + + [:octicons-arrow-right-24: Demo](https://huggingface.co/spaces/freddyaboulton/talk-to-moshi) + + [:octicons-code-16: Code](https://huggingface.co/spaces/freddyaboulton/talk-to-moshi/blob/main/app.py) + +- :speaking_head:{ .lg .middle } **Talk to Ultravox** + {: data-tags="audio,llm,voice-chat"} + + --- + + Talk to Fixie.AI's audio-native Ultravox LLM with the transformers library. + + + + [:octicons-arrow-right-24: Demo](https://huggingface.co/spaces/freddyaboulton/talk-to-ultravox) + + [:octicons-code-16: Code](https://huggingface.co/spaces/freddyaboulton/talk-to-ultravox/blob/main/app.py) + +- :speaking_head:{ .lg .middle } **Talk to Llama 3.2 3b** + {: data-tags="audio,llm,voice-chat"} + + --- + + Use the Lepton API to make Llama 3.2 talk back to you! + + + + [:octicons-arrow-right-24: Demo](https://huggingface.co/spaces/freddyaboulton/llama-3.2-3b-voice-webrtc) + + [:octicons-code-16: Code](https://huggingface.co/spaces/freddyaboulton/llama-3.2-3b-voice-webrtc/blob/main/app.py) + +- :robot:{ .lg .middle } **Talk to Qwen2-Audio** + {: data-tags="audio,llm,voice-chat"} + + --- + + Qwen2-Audio is a SOTA audio-to-text LLM developed by Alibaba. + + + + [:octicons-arrow-right-24: Demo](https://huggingface.co/spaces/freddyaboulton/talk-to-qwen-webrtc) + + [:octicons-code-16: Code](https://huggingface.co/spaces/freddyaboulton/talk-to-qwen-webrtc/blob/main/app.py) + +- :camera:{ .lg .middle } **Yolov10 Object Detection** + {: data-tags="video,computer-vision"} + + --- + + Run the Yolov10 model on a user webcam stream in real time! + + + + [:octicons-arrow-right-24: Demo](https://huggingface.co/spaces/fastrtc/object-detection) + + [:octicons-code-16: Code](https://huggingface.co/spaces/fastrtc/object-detection/blob/main/app.py) + +- :camera:{ .lg .middle } **Video Object Detection with RT-DETR** + {: data-tags="video,computer-vision"} + + --- + + Upload a video and stream out frames with detected objects (powered by RT-DETR) model. + + [:octicons-arrow-right-24: Demo](https://huggingface.co/spaces/freddyaboulton/rt-detr-object-detection-webrtc) + + [:octicons-code-16: Code](https://huggingface.co/spaces/freddyaboulton/rt-detr-object-detection-webrtc/blob/main/app.py) + +- :speaker:{ .lg .middle } **Text-to-Speech with Parler** + {: data-tags="audio"} + + --- + + Stream out audio generated by Parler TTS! + + [:octicons-arrow-right-24: Demo](https://huggingface.co/spaces/freddyaboulton/parler-tts-streaming-webrtc) + + [:octicons-code-16: Code](https://huggingface.co/spaces/freddyaboulton/parler-tts-streaming-webrtc/blob/main/app.py) + +- :speaking_head:{ .lg .middle } **Real Time Transcription with On-device Whisper 🤗** + {: data-tags="audio,transcription,local"} + + --- + + Transcribe speech in real time using Whisper via the Transformers library, running on your device! + + [:octicons-code-16: Code](https://github.com/sofi444/realtime-transcription-fastrtc/blob/main/main.py) + + - :speaking_head:{ .lg .middle } __Talk to Claude - Electron App__ + + {: data-tags="audio,electron"} + + --- + + An Electron desktop application that uses FastRTC to enable voice conversations with Claude. + + + + [:octicons-arrow-right-24: Demo](https://github.com/swairshah/voice-agent) + + [:octicons-code-16: Code](https://github.com/swairshah/voice-agent) + +
diff --git a/docs/deployment.md b/docs/deployment.md index 2ab85b9..f7e3199 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -1,43 +1,47 @@ -When deploying in a cloud environment (like Hugging Face Spaces, EC2, etc), you need to set up a TURN server to relay the WebRTC traffic. +When deploying in cloud environments with firewalls (like Hugging Face Spaces, RunPod), your WebRTC connections may be blocked from making direct connections. In these cases, you need a TURN server to relay the audio/video traffic between users. This guide covers different options for setting up FastRTC to connect to a TURN server. + +!!! tip +The `rtc_configuration` parameter of the `Stream` class also be passed to the [`WebRTC`](../userguide/gradio) component directly if you're building a standalone gradio app. ## Community Server Hugging Face graciously provides a TURN server for the community. -In order to use it, you need to first create a Hugging Face account by going to the [huggingface.co](https://huggingface.co/). +In order to use it, you need to first create a Hugging Face account by going to [huggingface.co](https://huggingface.co/). -Then navigate to this [space](https://huggingface.co/spaces/freddyaboulton/turn-server-login) and follow the instructions on the page. You just have to click the "Log in" button and then the "Sign Up" button. +Then navigate to this [space](https://huggingface.co/spaces/fastrtc/turn-server-login) and follow the instructions on the page. You just have to click the "Log in" button and then the "Sign Up" button. -![turn_login](https://github.com/user-attachments/assets/d077c3a3-7059-45d6-8e50-eb3d8a4aa43f) +![turn_login](https://github.com/user-attachments/assets/cefa8dec-487e-47d8-bb96-1a14a701f6e5) Then you can use the `get_hf_turn_credentials` helper to get your credentials: ```python -from gradio_webrtc import get_hf_turn_credentials, WebRTC +from fastrtc import get_hf_turn_credentials, Stream # Pass a valid access token for your Hugging Face account -# or set the HF_TOKEN environment variable +# or set the HF_TOKEN environment variable credentials = get_hf_turn_credentials(token=None) -with gr.Blcocks() as demo: - webrtc = WebRTC(rtc_configuration=credentials) - ... - -demo.launch() +Stream( + handler=..., + rtc_configuration=credentials, + modality="audio", + mode="send-receive" +) ``` !!! warning This is a shared resource so we make no latency/availability guarantees. - For more robust options, see the Twilio and self-hosting options below. - + For more robust options, see the Twilio, Cloudflare and self-hosting options below. ## Twilio API -The easiest way to do this is to use a service like Twilio. +An easy way to do this is to use a service like Twilio. Create a **free** [account](https://login.twilio.com/u/signup) and the install the `twilio` package with pip (`pip install twilio`). You can then connect from the WebRTC component like so: ```python +from fastrtc import Stream from twilio.rest import Client import os @@ -53,13 +57,15 @@ rtc_configuration = { "iceTransportPolicy": "relay", } -with gr.Blocks() as demo: - ... - rtc = WebRTC(rtc_configuration=rtc_configuration, ...) - ... +Stream( + handler=..., + rtc_configuration=rtc_configuration, + modality="audio", + mode="send-receive" +) ``` -!!! tip "Automatic Login" +!!! tip "Automatic login" You can log in automatically with the `get_twilio_turn_credentials` helper @@ -71,6 +77,50 @@ with gr.Blocks() as demo: rtc_configuration = get_twilio_turn_credentials() ``` +## Cloudflare Calls API + +Cloudflare also offers a managed TURN server with [Cloudflare Calls](https://www.cloudflare.com/en-au/developer-platform/products/cloudflare-calls/). + +Create a **free** [account](https://developers.cloudflare.com/fundamentals/setup/account/create-account/) and head to the [Calls section in your dashboard](https://dash.cloudflare.com/?to=/:account/calls). + +Choose `Create -> TURN App`, give it a name (like `fastrtc-demo`), and then hit the Create button. + +Take note of the Turn Token ID (often exported as `TURN_KEY_ID`) and API Token (exported as `TURN_KEY_API_TOKEN`). + +You can then connect from the WebRTC component like so: + +```python +from fastrtc import Stream +import requests +import os + +turn_key_id = os.environ.get("TURN_KEY_ID") +turn_key_api_token = os.environ.get("TURN_KEY_API_TOKEN") +ttl = 86400 # Can modify TTL, here it's set to 24 hours + +response = requests.post( + f"https://rtc.live.cloudflare.com/v1/turn/keys/{turn_key_id}/credentials/generate-ice-servers", + headers={ + "Authorization": f"Bearer {turn_key_api_token}", + "Content-Type": "application/json", + }, + json={"ttl": ttl}, +) +if response.ok: + rtc_configuration = response.json() +else: + raise Exception( + f"Failed to get TURN credentials: {response.status_code} {response.text}" + ) + +stream = Stream( + handler=..., + rtc_configuration=rtc_configuration, + modality="audio", + mode="send-receive", +) +``` + ## Self Hosting We have developed a script that can automatically deploy a TURN server to Amazon Web Services (AWS). You can follow the instructions [here](https://github.com/freddyaboulton/turn-server-deploy) or this guide. @@ -84,7 +134,6 @@ Log into your AWS account and create an IAM user with the following permissions: - [AWSCloudFormationFullAccess](https://us-east-1.console.aws.amazon.com/iam/home?region=us-east-1#/policies/details/arn%3Aaws%3Aiam%3A%3Aaws%3Apolicy%2FAWSCloudFormationFullAccess) - [AmazonEC2FullAccess](https://us-east-1.console.aws.amazon.com/iam/home?region=us-east-1#/policies/details/arn%3Aaws%3Aiam%3A%3Aaws%3Apolicy%2FAmazonEC2FullAccess) - Create a key pair for this user and write down the "access key" and "secret access key". Then log into the aws cli with these credentials (`aws configure`). Finally, create an ec2 keypair (replace `your-key-name` with the name you want to give it). @@ -102,7 +151,6 @@ Open the `parameters.json` file and fill in the correct values for all the param - `TurnPassword`: The password needed to connect to the server. - `InstanceType`: One of the following values `t3.micro`, `t3.small`, `t3.medium`, `c4.large`, `c5.large`. - Then run the deployment script: ```bash @@ -132,24 +180,23 @@ The `server-info.json` file will have the server's public IP and public DNS: ```json [ - { - "OutputKey": "PublicIP", - "OutputValue": "35.173.254.80", - "Description": "Public IP address of the TURN server" - }, - { - "OutputKey": "PublicDNS", - "OutputValue": "ec2-35-173-254-80.compute-1.amazonaws.com", - "Description": "Public DNS name of the TURN server" - } + { + "OutputKey": "PublicIP", + "OutputValue": "35.173.254.80", + "Description": "Public IP address of the TURN server" + }, + { + "OutputKey": "PublicDNS", + "OutputValue": "ec2-35-173-254-80.compute-1.amazonaws.com", + "Description": "Public DNS name of the TURN server" + } ] ``` Finally, you can connect to your EC2 server from the gradio WebRTC component via the `rtc_configuration` argument: ```python -import gradio as gr -from gradio_webrtc import WebRTC +from fastrtc import Stream rtc_configuration = { "iceServers": [ { @@ -159,7 +206,10 @@ rtc_configuration = { }, ] } - -with gr.Blocks() as demo: - webrtc = WebRTC(rtc_configuration=rtc_configuration) -``` \ No newline at end of file +Stream( + handler=..., + rtc_configuration=rtc_configuration, + modality="audio", + mode="send-receive" +) +``` diff --git a/docs/faq.md b/docs/faq.md index f3a69f6..4f23a4c 100644 --- a/docs/faq.md +++ b/docs/faq.md @@ -1,34 +1,37 @@ ## Demo does not work when deploying to the cloud -Make sure you are using a TURN server. See [deployment](/deployment). +Make sure you are using a TURN server. See [deployment](../deployment). ## Recorded input audio sounds muffled during output audio playback -By default, the microphone is [configured](https://github.com/freddyaboulton/gradio-webrtc/blob/903f1f70bd586f638ad3b5a3940c7a8ec70ad1f5/backend/gradio_webrtc/webrtc.py#L575) to do echoCancellation. +By default, the microphone is [configured](https://github.com/freddyaboulton/gradio-webrtc/blob/903f1f70bd586f638ad3b5a3940c7a8ec70ad1f5/backend/gradio_webrtc/webrtc.py#L575) to do echo cancellation. This is what's causing the recorded audio to sound muffled when the streamed audio starts playing. -You can disable this via the `track_constraints` (see [advanced configuration](./advanced-configuration])) with the following code: +You can disable this via the `track_constraints` (see [Advanced Configuration](../advanced-configuration)) with the following code: ```python - audio = WebRTC( - label="Stream", - track_constraints={ - "echoCancellation": False, - "noiseSuppression": {"exact": True}, - "autoGainControl": {"exact": True}, - "sampleRate": {"ideal": 24000}, - "sampleSize": {"ideal": 16}, - "channelCount": {"exact": 1}, - }, - rtc_configuration=None, - mode="send-receive", - modality="audio", - ) +stream = Stream( + track_constraints={ + "echoCancellation": False, + "noiseSuppression": {"exact": True}, + "autoGainControl": {"exact": True}, + "sampleRate": {"ideal": 24000}, + "sampleSize": {"ideal": 16}, + "channelCount": {"exact": 1}, + }, + rtc_configuration=None, + mode="send-receive", + modality="audio", +) ``` ## How to raise errors in the UI You can raise `WebRTCError` in order for an error message to show up in the user's screen. This is similar to how `gr.Error` works. +!!! warning + + The `WebRTCError` class is only supported in the `WebRTC` component. + Here is a simple example: ```python @@ -64,4 +67,4 @@ with gr.Blocks() as demo: ) demo.launch() -``` \ No newline at end of file +``` diff --git a/docs/fastrtc_logo.png b/docs/fastrtc_logo.png new file mode 100644 index 0000000..680bd75 Binary files /dev/null and b/docs/fastrtc_logo.png differ diff --git a/docs/fastrtc_logo_small.png b/docs/fastrtc_logo_small.png new file mode 100644 index 0000000..51faff2 Binary files /dev/null and b/docs/fastrtc_logo_small.png differ diff --git a/docs/gradio-logo-with-title.svg b/docs/gradio-logo-with-title.svg new file mode 100644 index 0000000..ff8df41 --- /dev/null +++ b/docs/gradio-logo-with-title.svg @@ -0,0 +1,20 @@ + + + + + + + + + + + + + + + + + + + + diff --git a/docs/gradio-logo.svg b/docs/gradio-logo.svg new file mode 100644 index 0000000..7f57eba --- /dev/null +++ b/docs/gradio-logo.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/docs/hf-logo-with-title.svg b/docs/hf-logo-with-title.svg new file mode 100644 index 0000000..7e25408 --- /dev/null +++ b/docs/hf-logo-with-title.svg @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/docs/hf-logo.svg b/docs/hf-logo.svg new file mode 100644 index 0000000..ab959d1 --- /dev/null +++ b/docs/hf-logo.svg @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/docs/index.md b/docs/index.md index 92923e7..c0564ca 100644 --- a/docs/index.md +++ b/docs/index.md @@ -1,30 +1,192 @@ -

Gradio WebRTC ⚡️

+
+

FastRTC

+ FastRTC Logo +
-Static Badge -Static Badge +Static Badge +Static Badge

-Stream video and audio in real time with Gradio using WebRTC. +The Real-Time Communication Library for Python.

+Turn any python function into a real-time audio and video stream over WebRTC or WebSockets. + + + ## Installation ```bash -pip install gradio_webrtc +pip install fastrtc ``` -to use built-in pause detection (see [ReplyOnPause](/user-guide/#reply-on-pause)), install the `vad` extra: +to use built-in pause detection (see [ReplyOnPause](userguide/audio/#reply-on-pause)), speech-to-text (see [Speech To Text](userguide/audio/#speech-to-text)), and text to speech (see [Text To Speech](userguide/audio/#text-to-speech)), install the `vad`, `stt`, and `tts` extras: ```bash -pip install gradio_webrtc[vad] +pip install "fastrtc[vad, stt, tts]" ``` -For stop word detection (see [ReplyOnStopWords](/user-guide/#reply-on-stopwords)), install the `stopword` extra: -```bash -pip install gradio_webrtc[stopword] -``` +## Quickstart + +Import the [Stream](userguide/streams) class and pass in a [handler](userguide/streams/#handlers). +The `Stream` has three main methods: + +- `.ui.launch()`: Launch a built-in UI for easily testing and sharing your stream. Built with [Gradio](https://www.gradio.app/). +- `.fastphone()`: Get a free temporary phone number to call into your stream. Hugging Face token required. +- `.mount(app)`: Mount the stream on a [FastAPI](https://fastapi.tiangolo.com/) app. Perfect for integrating with your already existing production system. + +=== "Echo Audio" + + ```python + from fastrtc import Stream, ReplyOnPause + import numpy as np + + def echo(audio: tuple[int, np.ndarray]): + # The function will be passed the audio until the user pauses + # Implement any iterator that yields audio + # See "LLM Voice Chat" for a more complete example + yield audio + + stream = Stream( + handler=ReplyOnPause(echo), + modality="audio", + mode="send-receive", + ) + ``` + +=== "LLM Voice Chat" + + ```py + import os + + from fastrtc import (ReplyOnPause, Stream, get_stt_model, get_tts_model) + from openai import OpenAI + + sambanova_client = OpenAI( + api_key=os.getenv("SAMBANOVA_API_KEY"), base_url="https://api.sambanova.ai/v1" + ) + stt_model = get_stt_model() + tts_model = get_tts_model() + + def echo(audio): + prompt = stt_model.stt(audio) + response = sambanova_client.chat.completions.create( + model="Meta-Llama-3.2-3B-Instruct", + messages=[{"role": "user", "content": prompt}], + max_tokens=200, + ) + prompt = response.choices[0].message.content + for audio_chunk in tts_model.stream_tts_sync(prompt): + yield audio_chunk + + stream = Stream(ReplyOnPause(echo), modality="audio", mode="send-receive") + ``` + +=== "Webcam Stream" + + ```python + from fastrtc import Stream + import numpy as np + + + def flip_vertically(image): + return np.flip(image, axis=0) + + + stream = Stream( + handler=flip_vertically, + modality="video", + mode="send-receive", + ) + ``` + +=== "Object Detection" + + ```python + from fastrtc import Stream + import gradio as gr + import cv2 + from huggingface_hub import hf_hub_download + from .inference import YOLOv10 + + model_file = hf_hub_download( + repo_id="onnx-community/yolov10n", filename="onnx/model.onnx" + ) + + # git clone https://huggingface.co/spaces/fastrtc/object-detection + # for YOLOv10 implementation + model = YOLOv10(model_file) + + def detection(image, conf_threshold=0.3): + image = cv2.resize(image, (model.input_width, model.input_height)) + new_image = model.detect_objects(image, conf_threshold) + return cv2.resize(new_image, (500, 500)) + + stream = Stream( + handler=detection, + modality="video", + mode="send-receive", + additional_inputs=[ + gr.Slider(minimum=0, maximum=1, step=0.01, value=0.3) + ] + ) + ``` + +Run: +=== "UI" + + ```py + stream.ui.launch() + ``` + +=== "Telephone" + + ```py + stream.fastphone() + ``` + +=== "FastAPI" + + ```py + app = FastAPI() + stream.mount(app) + + # Optional: Add routes + @app.get("/") + async def _(): + return HTMLResponse(content=open("index.html").read()) + + # uvicorn app:app --host 0.0.0.0 --port 8000 + ``` + +Learn more about the [Stream](userguide/streams) in the user guide. + +## Key Features + +:speaking_head:{ .lg } Automatic Voice Detection and Turn Taking built-in, only worry about the logic for responding to the user. + +:material-laptop:{ .lg } Automatic UI - Use the `.ui.launch()` method to launch the webRTC-enabled built-in Gradio UI. + +:material-lightning-bolt:{ .lg } Automatic WebRTC Support - Use the `.mount(app)` method to mount the stream on a FastAPI app and get a webRTC endpoint for your own frontend! + +:simple-webstorm:{ .lg } Websocket Support - Use the `.mount(app)` method to mount the stream on a FastAPI app and get a websocket endpoint for your own frontend! + +:telephone:{ .lg } Automatic Telephone Support - Use the `fastphone()` method of the stream to launch the application and get a free temporary phone number! + +:robot:{ .lg } Completely customizable backend - A `Stream` can easily be mounted on a FastAPI app so you can easily extend it to fit your production application. See the [Talk To Claude](https://huggingface.co/spaces/fastrtc/talk-to-claude) demo for an example on how to serve a custom JS frontend. ## Examples -See the [cookbook](/cookbook) \ No newline at end of file + +See the [cookbook](/cookbook). + +Follow and join or [organization](https://huggingface.co/fastrtc) on Hugging Face! + +
+ + +
diff --git a/docs/speech_to_text_gallery.md b/docs/speech_to_text_gallery.md new file mode 100644 index 0000000..22e0091 --- /dev/null +++ b/docs/speech_to_text_gallery.md @@ -0,0 +1,117 @@ + + +A collection of Speech-to-Text models ready to use with FastRTC. Click on the tags below to find the STT model you're looking for! + +!!! tip "Note" + The model you want to use does not have to be in the gallery. This is just a collection of models with a common interface that are easy to "plug and play" into your FastRTC app. But You can use any model you want without having to do any special setup. Simply use it from your stream handler! + + +
+ +
+ + + + +
+ +- :speaking_head:{ .lg .middle }:eyes:{ .lg .middle } distil-whisper-FastRTC +{: data-tags="pytorch"} + + --- + + Description: + [Distil-whisper](https://github.com/huggingface/distil-whisper) from Hugging Face wraped in a pypi package for plug and play! + + Install Instructions + ```python + pip install distil-whisper-fastrtc + ``` + Use it the same way you would the native fastRTC TTS model! + + + [:octicons-arrow-right-24: Demo](https://huggingface.co/spaces/Codeblockz/llm-voice-chat/) + + [:octicons-code-16: Repository](https://github.com/Codeblockz/distil-whisper-FastRTC) + +- :speaking_head:{ .lg .middle }:eyes:{ .lg .middle } __Your STT Model__ +{: data-tags="pytorch"} + + --- + + Description + + Install Instructions + + Usage + + [:octicons-arrow-right-24: Demo](Your demo here) + + [:octicons-code-16: Repository](Code here) + +
+ +## How to add your own STT model + +1. Your model can be implemented in **any** framework you want but it must implement the `STTModel` protocol. + + ```python + class STTModel(Protocol): + def stt(self, audio: tuple[int, NDArray[np.int16 | np.float32]]) -> str: ... + ``` + + * The `stt` method should take in an audio tuple `(sample_rate, audio_array)` and return a string of the transcribed text. + + * The `audio` tuple should be of the form `(sample_rate, audio_array)` where `sample_rate` is the sample rate of the audio array and `audio_array` is a numpy array of the audio data. It can be of type `np.int16` or `np.float32`. + +2. Once you have your model implemented, you can use it in your handler! + + ```python + from fastrtc import Stream, AdditionalOutputs, ReplyOnPause + from your_model import YourModel + + model = YourModel() # implement the STTModel protocol + + def echo(audio): + text = model.stt(audio) + yield AdditionalOutputs(text) + + stream = Stream(ReplyOnPause(echo), mode="send-receive", modality="audio", + additional_outputs=[gr.Textbox(label="Transcription")], + additional_outputs_handler=lambda old,new:old + new) + stream.ui.launch() + ``` + +3. Open a [PR](https://github.com/freddyaboulton/fastrtc/edit/main/docs/speech_to_text_gallery.md) to add your model to the gallery! Ideally you model package should be pip installable so other can try it out easily. \ No newline at end of file diff --git a/docs/stylesheets/extra.css b/docs/stylesheets/extra.css new file mode 100644 index 0000000..a64f0fc --- /dev/null +++ b/docs/stylesheets/extra.css @@ -0,0 +1,63 @@ +:root { + --white: #ffffff; + --galaxy: #393931; + --space: #2d2d2a; + --rock: #2d2d2a; + --cosmic: #ffdd00c5; + --radiate: #d6cec0; + --sun: #ffac2f; + --neutron: #F7F5F6; + --supernova: #ffdd00; + --asteroid: #d6cec0; +} + +[data-md-color-scheme="fastrtc-dark"] { + --md-default-bg-color: var(--galaxy); + --md-default-fg-color: var(--white); + --md-default-fg-color--light: var(--white); + --md-default-fg-color--lighter: var(--white); + --md-primary-fg-color: var(--space); + --md-primary-bg-color: var(--white); + --md-accent-fg-color: var(--sun); + + --md-typeset-color: var(--white); + --md-typeset-a-color: var(--supernova); + --md-typeset-mark-color: var(--sun); + + --md-code-fg-color: var(--white); + --md-code-bg-color: var(--rock); + + --md-code-hl-comment-color: var(--asteroid); + --md-code-hl-punctuation-color: var(--supernova); + --md-code-hl-generic-color: var(--supernova); + --md-code-hl-variable-color: var(--white); + --md-code-hl-string-color: var(--radiate); + --md-code-hl-keyword-color: var(--supernova); + --md-code-hl-operator-color: var(--supernova); + --md-code-hl-number-color: var(--radiate); + --md-code-hl-special-color: var(--supernova); + --md-code-hl-function-color: var(--neutron); + --md-code-hl-constant-color: var(--radiate); + --md-code-hl-name-color: var(--md-code-fg-color); + + --md-typeset-del-color: hsla(6, 90%, 60%, 0.15); + --md-typeset-ins-color: hsla(150, 90%, 44%, 0.15); + + --md-typeset-table-color: hsla(0, 0%, 100%, 0.12); + --md-typeset-table-color--light: hsla(0, 0%, 100%, 0.035); +} + +[data-md-color-scheme="fastrtc-dark"] div.admonition { + color: var(--md-code-fg-color); + background-color: var(--galaxy); +} + + +[data-md-color-scheme="fastrtc-dark"] .grid.cards>ul>li { + border-color: var(--rock); + border-width: thick; +} + +[data-md-color-scheme="fastrtc-dark"] .grid.cards>ul>li>hr { + border-color: var(--rock); +} \ No newline at end of file diff --git a/docs/turn_taking_gallery.md b/docs/turn_taking_gallery.md new file mode 100644 index 0000000..d2e2fd1 --- /dev/null +++ b/docs/turn_taking_gallery.md @@ -0,0 +1,144 @@ + + +A collection of Turn Taking Algorithms and Voice Activity Detection (VAD) models ready to use with FastRTC. Click on the tags below to find the model you're looking for! + +
+ + +
+ + + +## Gallery + +
+ +- :speaking_head:{ .lg .middle }:eyes:{ .lg .middle } __Walkie Talkie__ +{: data-tags="turn-taking-algorithm"} + + --- + + Description + The user's turn ends when they finish a sentence with the word "over". + For example, "Hello, how are you? Over." would send end the user's turn and trigger the response. + This is intended as a simple reference implementation for how to implement a custom-turn-taking algorithm. + + Install Instructions + ```bash + pip install fastrtc-walkie-talkie + ``` + + + + [:octicons-arrow-right-24: Demo](https://github.com/freddyaboulton/fastrtc-walkie-talkie/blob/main/scratch.py) + + [:octicons-code-16: Repository](https://github.com/freddyaboulton/fastrtc-walkie-talkie/blob/main/src/fastrtc_walkie_talkie/__init__.py) + +
+ +## What is this for? + +By default, FastRTC uses the `ReplyOnPause` class to handle turn-taking. However, you may want to tweak this behavior to better fit your use case. + +In this gallery, you can find a collection of turn-taking algorithms and VAD models that you can use to customize the turn-taking behavior to your needs. Each card contains install and usage instructions. + +## How to add your own Turn-taking Algorithm or VAD model + +### Turn-taking Algorithm + +1. Typically you will want to subclass the `ReplyOnPause` class and override the `determine_pause` method. + + ```python + from fastrtc.reply_on_pause import ReplyOnPause, AppState + class MyTurnTakingAlgorithm(ReplyOnPause): + def determine_pause(self, audio: np.ndarray, sampling_rate: int, state: AppState) -> bool: + return super().determine_pause(audio, sampling_rate, state) + ``` + +2. Then package your class into a pip installable package and publish it to [pypi](https://pypi.org/). + +3. Open a [PR](https://github.com/freddyaboulton/fastrtc-walkie-talkie/blob/main/src/fastrtc_walkie_talkie/__init__.py) to add your model to the gallery! + +!!! tip "Example Implementation" + See the [Walkie Talkie](https://github.com/freddyaboulton/fastrtc-walkie-talkie/) package for an example implementation of a turn-taking algorithm. + +### VAD Model + +1. Your model can be implemented in **any** framework you want but it must implement the `PauseDetectionModel` protocol. + ```python + 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: ... + ``` + + * The `vad` method should take a numpy array of audio data and return a tuple of the form `(speech_duration, and list[AudioChunk])` where `speech_duration` is the duration of the human speech in the audio chunk and `AudioChunk` is a dictionary with the following fields: `(start, end)` where `start` and `end` are the start and end times of the human speech in the audio array. + + * The `audio` tuple should be of the form `(sample_rate, audio_array)` where `sample_rate` is the sample rate of the audio array and `audio_array` is a numpy array of the audio data. It can be of type `np.int16` or `np.float32`. + + * The `warmup` method is optional but recommended to warm up the model when the server starts. + +2. Once you have your model implemented, you can use it in the `ReplyOnPause` class by passing in the model and any options you need. + + ```python + from fastrtc import ReplyOnPause, Stream + from your_model import YourModel + + def echo(audio): + yield audio + + model = YourModel() # implement the PauseDetectionModel protocol + reply_on_pause = ReplyOnPause( + echo, + model=model, + options=YourModelOptions(), + ) + stream = Stream(reply_on_pause, mode="send-receive", modality="audio") + stream.ui.launch() + ``` + +3. Open a [PR](https://github.com/freddyaboulton/fastrtc/edit/main/docs/turn_taking_gallery.md) to add your model to the gallery! Ideally you model package should be pip installable so other can try it out easily. + +!!! tip "Package Naming Convention" + It is recommended to name your package `fastrtc-` so developers can easily find it on [pypi](https://pypi.org/search/?q=fastrtc-). \ No newline at end of file diff --git a/docs/userguide/api.md b/docs/userguide/api.md new file mode 100644 index 0000000..4ff8cdb --- /dev/null +++ b/docs/userguide/api.md @@ -0,0 +1,461 @@ +# Connecting via API + +Before continuing, select the `modality`, `mode` of your `Stream` and whether you're using `WebRTC` or `WebSocket`s. + +
+
+ + +
+
+ + +
+
+ + +
+ +
+ +### Sample Code +
+ +### Message Format + +Over both WebRTC and WebSocket, the server can send messages of the following format: + +```json +{ + "type": `send_input` | `fetch_output` | `stopword` | `error` | `warning` | `log`, + "data": string | object +} +``` + +- `send_input`: Send any input data for the handler to the server. See [`Additional Inputs`](#additional-inputs) for more details. +- `fetch_output`: An instance of [`AdditionalOutputs`](#additional-outputs) is sent to the server. +- `stopword`: The stopword has been detected. See [`ReplyOnStopWords`](../audio/#reply-on-stopwords) for more details. +- `error`: An error occurred. The `data` will be a string containing the error message. +- `warning`: A warning occurred. The `data` will be a string containing the warning message. +- `log`: A log message. The `data` will be a string containing the log message. + +The `ReplyOnPause` handler can also send the following `log` messages. + +```json +{ + "type": "log", + "data": "pause_detected" | "response_starting" +} +``` + +!!! tip + When using WebRTC, the messages will be encoded as strings, so parse as JSON before using. + +### Additional Inputs + +When the `send_input` message is received, update the inputs of your handler however you like by using the `set_input` method of the `Stream` object. + +A common pattern is to use a `POST` request to send the updated data. The first argument to the `set_input` method is the `webrtc_id` of the handler. + +```python +from pydantic import BaseModel, Field + +class InputData(BaseModel): + webrtc_id: str + conf_threshold: float = Field(ge=0, le=1) + + +@app.post("/input_hook") +async def _(data: InputData): + stream.set_input(data.webrtc_id, data.conf_threshold) +``` + +The updated data will be passed to the handler on the **next** call. + +### Additional Outputs + +The `fetch_output` message is sent to the client whenever an instance of [`AdditionalOutputs`](../streams/#additional-outputs) is available. You can access the latest output data by calling the `fetch_latest_output` method of the `Stream` object. + +However, rather than fetching each output manually, a common pattern is to fetch the entire stream of output data by calling the `output_stream` method. + +Here is an example: +```python +from fastapi.responses import StreamingResponse + +@app.get("/updates") +async def stream_updates(webrtc_id: str): + async def output_stream(): + async for output in stream.output_stream(webrtc_id): + # Output is the AdditionalOutputs instance + # Be sure to serialize it however you would like + yield f"data: {output.args[0]}\n\n" + + return StreamingResponse( + output_stream(), + media_type="text/event-stream" + ) +``` + +### Handling Errors + +When connecting via `WebRTC`, the server will respond to the `/webrtc/offer` route with a JSON response. If there are too many connections, the server will respond with a 200 error. + +```json +{ + "status": "failed", + "meta": { + "error": "concurrency_limit_reached", + "limit": 10 + } +``` + +Over `WebSocket`, the server will send the same message before closing the connection. + +!!! tip + The server will sends a 200 status code because otherwise the gradio client will not be able to process the json response and display the error. + + + + + diff --git a/docs/userguide/audio-video.md b/docs/userguide/audio-video.md new file mode 100644 index 0000000..e602a50 --- /dev/null +++ b/docs/userguide/audio-video.md @@ -0,0 +1,27 @@ +# Audio-Video Streaming + +You can simultaneously stream audio and video using `AudioVideoStreamHandler` or `AsyncAudioVideoStreamHandler`. +They are identical to the audio `StreamHandlers` with the addition of `video_receive` and `video_emit` methods which take and return a `numpy` array, respectively. + +Here is an example of the video handling functions for connecting with the Gemini multimodal API. In this case, we simply reflect the webcam feed back to the user but every second we'll send the latest webcam frame (and an additional image component) to the Gemini server. + +Please see the "Gemini Audio Video Chat" example in the [cookbook](../../cookbook) for the complete code. + +``` python title="Async Gemini Video Handling" + +async def video_receive(self, frame: np.ndarray): + """Send video frames to the server""" + if self.session: + # send image every 1 second + # otherwise we flood the API + if time.time() - self.last_frame_time > 1: + self.last_frame_time = time.time() + await self.session.send(encode_image(frame)) + if self.latest_args[2] is not None: + await self.session.send(encode_image(self.latest_args[2])) + self.video_queue.put_nowait(frame) + +async def video_emit(self) -> VideoEmitType: + """Return video frames to the client""" + return await self.video_queue.get() +``` \ No newline at end of file diff --git a/docs/userguide/audio.md b/docs/userguide/audio.md new file mode 100644 index 0000000..81cf657 --- /dev/null +++ b/docs/userguide/audio.md @@ -0,0 +1,388 @@ + +## Reply On Pause + +Typically, you want to run a python function whenever a user has stopped speaking. This can be done by wrapping a python generator with the `ReplyOnPause` class and passing it to the `handler` argument of the `Stream` object. The `ReplyOnPause` class will handle the voice detection and turn taking logic automatically! + + +=== "Code" + ```python + from fastrtc import ReplyOnPause, Stream + + def response(audio: tuple[int, np.ndarray]): # (1) + sample_rate, audio_array = audio + # Generate response + for audio_chunk in generate_response(sample_rate, audio_array): + yield (sample_rate, audio_chunk) # (2) + + stream = Stream( + handler=ReplyOnPause(response), + modality="audio", + mode="send-receive" + ) + ``` + + 1. The python generator will receive the **entire** audio up until the user stopped. It will be a tuple of the form (sampling_rate, numpy array of audio). The array will have a shape of (1, num_samples). You can also pass in additional input components. + + 2. The generator must yield audio chunks as a tuple of (sampling_rate, numpy audio array). Each numpy audio array must have a shape of (1, num_samples). + +=== "Notes" + 1. The python generator will receive the **entire** audio up until the user stopped. It will be a tuple of the form (sampling_rate, numpy array of audio). The array will have a shape of (1, num_samples). You can also pass in additional input components. + + 2. The generator must yield audio chunks as a tuple of (sampling_rate, numpy audio array). Each numpy audio array must have a shape of (1, num_samples). + +!!! tip "Asynchronous" + You can also use an async generator with `ReplyOnPause`. + +!!! tip "Parameters" + You can customize the voice detection parameters by passing in `algo_options` and `model_options` to the `ReplyOnPause` class. + ```python + from fastrtc import AlgoOptions, SileroVadOptions + + stream = Stream( + handler=ReplyOnPause( + response, + algo_options=AlgoOptions( + audio_chunk_duration=0.6, + started_talking_threshold=0.2, + speech_threshold=0.1 + ), + model_options=SileroVadOptions( + threshold=0.5, + min_speech_duration_ms=250, + min_silence_duration_ms=100 + ) + ) + ) + ``` + +### Interruptions + +By default, the `ReplyOnPause` handler will allow you to interrupt the response at any time by speaking again. If you do not want to allow interruption, you can set the `can_interrupt` parameter to `False`. + +```python +from fastrtc import Stream, ReplyOnPause + +stream = Stream( + handler=ReplyOnPause( + response, + can_interrupt=True, + ) +) +``` + + + + +!!! tip "Muting Response Audio" + You can directly talk over the output audio and the interruption will still work. However, in these cases, the audio transcription may be incorrect. To prevent this, it's best practice to mute the output audio before talking over it. + +### Startup Function + +You can pass in a `startup_fn` to the `ReplyOnPause` class. This function will be called when the connection is first established. It is helpful for generating intial responses. + +```python +from fastrtc import get_tts_model, Stream, ReplyOnPause + +tts_client = get_tts_model() + + +def detection(audio: tuple[int, np.ndarray]): + # Implement any iterator that yields audio + # See "LLM Voice Chat" for a more complete example + yield audio + + +def startup(): + for chunk in tts_client.stream_tts_sync("Welcome to the echo audio demo!"): + yield chunk + + +stream = Stream( + handler=ReplyOnPause(detection, startup_fn=startup), + modality="audio", + mode="send-receive", + ui_args={"title": "Echo Audio"}, +) +``` + + + +## Reply On Stopwords + +You can configure your AI model to run whenever a set of "stop words" are detected, like "Hey Siri" or "computer", with the `ReplyOnStopWords` class. + +The API is similar to `ReplyOnPause` with the addition of a `stop_words` parameter. + +=== "Code" + ``` py + from fastrtc import Stream, ReplyOnStopWords + + def response(audio: tuple[int, np.ndarray]): + """This function must yield audio frames""" + ... + for numpy_array in generated_audio: + yield (sampling_rate, numpy_array, "mono") + + stream = Stream( + handler=ReplyOnStopWords(generate, + input_sample_rate=16000, + stop_words=["computer"]), # (1) + modality="audio", + mode="send-receive" + ) + ``` + + 1. The `stop_words` can be single words or pairs of words. Be sure to include common misspellings of your word for more robust detection, e.g. "llama", "lamma". In my experience, it's best to use two very distinct words like "ok computer" or "hello iris". + +=== "Notes" + 1. The `stop_words` can be single words or pairs of words. Be sure to include common misspellings of your word for more robust detection, e.g. "llama", "lamma". In my experience, it's best to use two very distinct words like "ok computer" or "hello iris". + +!!! tip "Extra Dependencies" + The `ReplyOnStopWords` class requires the the `stopword` extra. Run `pip install fastrtc[stopword]` to install it. + +!!! warning "English Only" + The `ReplyOnStopWords` class is currently only supported for English. + +## Stream Handler + +`ReplyOnPause` and `ReplyOnStopWords` are implementations of a `StreamHandler`. The `StreamHandler` is a low-level abstraction that gives you arbitrary control over how the input audio stream and output audio stream are created. The following example echos back the user audio. + +=== "Code" + ``` py + import gradio as gr + from gradio_webrtc import WebRTC, StreamHandler + from queue import Queue + + class EchoHandler(StreamHandler): + def __init__(self) -> None: + super().__init__() + self.queue = Queue() + + def receive(self, frame: tuple[int, np.ndarray]) -> None: # (1) + self.queue.put(frame) + + def emit(self) -> None: # (2) + return self.queue.get() + + def copy(self) -> StreamHandler: + return EchoHandler() + + def shutdown(self) -> None: # (3) + pass + + def start_up(self) -> None: # (4) + pass + + stream = Stream( + handler=EchoHandler(), + modality="audio", + mode="send-receive" + ) + ``` + + 1. The `StreamHandler` class implements three methods: `receive`, `emit` and `copy`. The `receive` method is called when a new frame is received from the client, and the `emit` method returns the next frame to send to the client. The `copy` method is called at the beginning of the stream to ensure each user has a unique stream handler. + 2. The `emit` method SHOULD NOT block. If a frame is not ready to be sent, the method should return `None`. If you need to wait for a frame, use [`wait_for_item`](../../utils#wait_for_item) from the `utils` module. + 3. The `shutdown` method is called when the stream is closed. It should be used to clean up any resources. + 4. The `start_up` method is called when the stream is first created. It should be used to initialize any resources. See [Talk To OpenAI](https://huggingface.co/spaces/fastrtc/talk-to-openai-gradio) or [Talk To Gemini](https://huggingface.co/spaces/fastrtc/talk-to-gemini-gradio) for an example of a `StreamHandler` that uses the `start_up` method to connect to an API. +=== "Notes" + 1. The `StreamHandler` class implements three methods: `receive`, `emit` and `copy`. The `receive` method is called when a new frame is received from the client, and the `emit` method returns the next frame to send to the client. The `copy` method is called at the beginning of the stream to ensure each user has a unique stream handler. + 2. The `emit` method SHOULD NOT block. If a frame is not ready to be sent, the method should return `None`. If you need to wait for a frame, use [`wait_for_item`](../../utils#wait_for_item) from the `utils` module. + 3. The `shutdown` method is called when the stream is closed. It should be used to clean up any resources. + 4. The `start_up` method is called when the stream is first created. It should be used to initialize any resources. See [Talk To OpenAI](https://huggingface.co/spaces/fastrtc/talk-to-openai-gradio) or [Talk To Gemini](https://huggingface.co/spaces/fastrtc/talk-to-gemini-gradio) for an example of a `StreamHandler` that uses the `start_up` method to connect to an API. + +!!! tip + See this [Talk To Gemini](https://huggingface.co/spaces/fastrtc/talk-to-gemini-gradio) for a complete example of a more complex stream handler. + +!!! warning + The `emit` method should not block. If you need to wait for a frame, use [`wait_for_item`](../../utils#wait_for_item) from the `utils` module. + +## Async Stream Handlers + +It is also possible to create asynchronous stream handlers. This is very convenient for accessing async APIs from major LLM developers, like Google and OpenAI. The main difference is that `receive`, `emit`, and `start_up` are now defined with `async def`. + +Here is aa simple example of using `AsyncStreamHandler`: + +=== "Code" + ``` py + from fastrtc import AsyncStreamHandler, wait_for_item, Stream + import asyncio + import numpy as np + + class AsyncEchoHandler(AsyncStreamHandler): + """Simple Async Echo Handler""" + + def __init__(self) -> None: + super().__init__(input_sample_rate=24000) + self.queue = asyncio.Queue() + + async def receive(self, frame: tuple[int, np.ndarray]) -> None: + await self.queue.put(frame) + + async def emit(self) -> None: + return await wait_for_item(self.queue) + + def copy(self): + return AsyncEchoHandler() + + async def shutdown(self): + pass + + async def start_up(self) -> None: + pass + ``` + +!!! tip + See [Talk To Gemini](https://huggingface.co/spaces/fastrtc/talk-to-gemini), [Talk To Openai](https://huggingface.co/spaces/fastrtc/talk-to-openai) for complete examples of `AsyncStreamHandler`s. + + +## Text To Speech + +You can use an on-device text to speech model if you have the `tts` extra installed. +Import the `get_tts_model` function and call it with the model name you want to use. +At the moment, the only model supported is `kokoro`. + +The `get_tts_model` function returns an object with three methods: + +- `tts`: Synchronous text to speech. +- `stream_tts_sync`: Synchronous text to speech streaming. +- `stream_tts`: Asynchronous text to speech streaming. + +```python +from fastrtc import get_tts_model + +model = get_tts_model(model="kokoro") + +for audio in model.stream_tts_sync("Hello, world!"): + yield audio + +async for audio in model.stream_tts("Hello, world!"): + yield audio + +audio = model.tts("Hello, world!") +``` + +!!! tip + You can customize the audio by passing in an instace of `KokoroTTSOptions` to the method. + See [here](https://huggingface.co/hexgrad/Kokoro-82M/blob/main/VOICES.md) for a list of available voices. + ```python + from fastrtc import KokoroTTSOptions, get_tts_model + + model = get_tts_model(model="kokoro") + + options = KokoroTTSOptions( + voice="af_heart", + speed=1.0, + lang="en-us" + ) + + audio = model.tts("Hello, world!", options=options) + ``` + +## Speech To Text + +You can use an on-device speech to text model if you have the `stt` or `stopword` extra installed. +Import the `get_stt_model` function and call it with the model name you want to use. +At the moment, the only models supported are `moonshine/base` and `moonshine/tiny`. + +The `get_stt_model` function returns an object with the following method: + +- `stt`: Synchronous speech to text. + +```python +from fastrtc import get_stt_model + +model = get_stt_model(model="moonshine/base") + +audio = (16000, np.random.randint(-32768, 32768, size=(1, 16000))) +text = model.stt(audio) +``` + +!!! tip "Example" + See [LLM Voice Chat](https://huggingface.co/spaces/fastrtc/llm-voice-chat) for an example of using the `stt` method in a `ReplyOnPause` handler. + +!!! warning "English Only" + The `stt` model is currently only supported for English. + +## Requesting Inputs + +In `ReplyOnPause` and `ReplyOnStopWords`, any additional input data is automatically passed to your generator. For `StreamHandler`s, you must manually request the input data from the client. + +You can do this by calling `await self.wait_for_args()` (for `AsyncStreamHandler`s) in either the `emit` or `receive` methods. For a `StreamHandler`, you can call `self.wait_for_args_sync()`. + + +We can access the value of this component via the `latest_args` property of the `StreamHandler`. The `latest_args` is a list storing each of the values. The 0th index is the dummy string `__webrtc_value__`. + +## Considerations for Telephone Use + +In order for your handler to work over the phone, you must make sure that your handler is not expecting any additional input data besides the audio. + +If you call `await self.wait_for_args()` your stream will wait forever for the additional input data. + +The stream handlers have a `phone_mode` property that is set to `True` if the stream is running over the phone. You can use this property to determine if you should wait for additional input data. + +```python +def emit(self): + if self.phone_mode: + self.latest_args = [None] + else: + await self.wait_for_args() +``` + +### `ReplyOnPause` and telephone use + +The generator you pass to `ReplyOnPause` must have default arguments for all arguments except audio. + +If you yield `AdditionalOutputs`, they will be passed in as the input arguments to the generator the next time it is called. + +!!! tip + See [Talk To Claude](https://huggingface.co/spaces/fastrtc/talk-to-claude) for an example of a `ReplyOnPause` handler that is compatible with telephone usage. Notice how the input chatbot history is yielded as an `AdditionalOutput` on each invocation. + +## Telephone Integration + +You can integrate a `Stream` with a SIP provider like Twilio to set up your own phone number for your application. + +### Setup Process + +1. **Create a Twilio Account**: Sign up for a [Twilio](https://login.twilio.com/u/signup) account and purchase a phone number with voice capabilities. With a trial account, only the phone number you used during registration will be able to connect to your `Stream`. + +2. **Mount Your Stream**: Add your `Stream` to a FastAPI app using `stream.mount(app)` and run the server. + +3. **Configure Twilio Webhook**: Point your Twilio phone number to your webhook URL. + +### Configuring Twilio + +To configure your Twilio phone number: + +1. In your Twilio dashboard, navigate to `Manage` → `TwiML Apps` in the left sidebar +2. Click `Create TwiML App` +3. Set the `Voice URL` to your FastAPI app's URL with `/telephone/incoming` appended (e.g., `https://your-app-url.com/telephone/incoming`) + +![Twilio TwiML Apps Navigation](https://github.com/user-attachments/assets/9cd7b7de-d3e6-4fc8-9e50-ffe946d19c73) +![Twilio Voice URL Configuration](https://github.com/user-attachments/assets/b8490e59-9f2c-4bb4-af59-a304100a5eaf) + +!!! tip "Local Development with Ngrok" + For local development, use [ngrok](https://ngrok.com/) to expose your local server: + ```bash + ngrok http + ``` + Then set your Twilio Voice URL to `https://your-ngrok-subdomain.ngrok.io/telephone/incoming-call` + +### Code Example + +Here's a simple example of setting up a Twilio endpoint: + + +```py +from fastrtc import Stream, ReplyOnPause +from fastapi import FastAPI + +def echo(audio): + yield audio + +app = FastAPI() + +stream = Stream(ReplyOnPause(echo), modality="audio", mode="send-receive") +stream.mount(app) + +# run with `uvicorn main:app` +``` diff --git a/docs/userguide/gradio.md b/docs/userguide/gradio.md new file mode 100644 index 0000000..ba1682b --- /dev/null +++ b/docs/userguide/gradio.md @@ -0,0 +1,96 @@ +# Gradio Component + +The automatic gradio UI is a great way to test your stream. However, you may want to customize the UI to your liking or simply build a standalone Gradio application. + +## The WebRTC Component + +To build a standalone Gradio application, you can use the `WebRTC` component and implement the `stream` event. +Similarly to the `Stream` object, you must set the `mode` and `modality` arguments and pass in a `handler`. + +In the `stream` event, you pass in your handler as well as the input and output components. + +``` py +import gradio as gr +from fastrtc import WebRTC, ReplyOnPause + +def response(audio: tuple[int, np.ndarray]): + """This function must yield audio frames""" + ... + yield audio + + +with gr.Blocks() as demo: + gr.HTML( + """ +

+ Chat (Powered by WebRTC ⚡️) +

+ """ + ) + with gr.Column(): + with gr.Group(): + audio = WebRTC( + mode="send-receive", + modality="audio", + ) + audio.stream(fn=ReplyOnPause(response), + inputs=[audio], outputs=[audio], + time_limit=60) +demo.launch() +``` + +## Additional Outputs + +In order to modify other components from within the WebRTC stream, you must yield an instance of `AdditionalOutputs` and add an `on_additional_outputs` event to the `WebRTC` component. + +This is common for displaying a multimodal text/audio conversation in a Chatbot UI. + +=== "Code" + + ``` py title="Additional Outputs" + from fastrtc import AdditionalOutputs, WebRTC + + def transcribe(audio: tuple[int, np.ndarray], + transformers_convo: list[dict], + gradio_convo: list[dict]): + response = model.generate(**inputs, max_length=256) + transformers_convo.append({"role": "assistant", "content": response}) + gradio_convo.append({"role": "assistant", "content": response}) + yield AdditionalOutputs(transformers_convo, gradio_convo) # (1) + + + with gr.Blocks() as demo: + gr.HTML( + """ +

+ Talk to Qwen2Audio (Powered by WebRTC ⚡️) +

+ """ + ) + transformers_convo = gr.State(value=[]) + with gr.Row(): + with gr.Column(): + audio = WebRTC( + label="Stream", + mode="send", # (2) + modality="audio", + ) + with gr.Column(): + transcript = gr.Chatbot(label="transcript", type="messages") + + audio.stream(ReplyOnPause(transcribe), + inputs=[audio, transformers_convo, transcript], + outputs=[audio], time_limit=90) + audio.on_additional_outputs(lambda s,a: (s,a), # (3) + outputs=[transformers_convo, transcript], + queue=False, show_progress="hidden") + demo.launch() + ``` + + 1. Pass your data to `AdditionalOutputs` and yield it. + 2. In this case, no audio is being returned, so we set `mode="send"`. However, if we set `mode="send-receive"`, we could also yield generated audio and `AdditionalOutputs`. + 3. The `on_additional_outputs` event does not take `inputs`. It's common practice to not run this event on the queue since it is just a quick UI update. +=== "Notes" + 1. Pass your data to `AdditionalOutputs` and yield it. + 2. In this case, no audio is being returned, so we set `mode="send"`. However, if we set `mode="send-receive"`, we could also yield generated audio and `AdditionalOutputs`. + 3. The `on_additional_outputs` event does not take `inputs`. It's common practice to not run this event on the queue since it is just a quick UI update. \ No newline at end of file diff --git a/docs/userguide/streams.md b/docs/userguide/streams.md new file mode 100644 index 0000000..b0ba5af --- /dev/null +++ b/docs/userguide/streams.md @@ -0,0 +1,236 @@ +# Core Concepts + + +The core of FastRTC is the `Stream` object. It can be used to stream audio, video, or both. + +Here's a simple example of creating a video stream that flips the video vertically. We'll use it to explain the core concepts of the `Stream` object. Click on the plus icons to get a link to the relevant section. + +```python +from fastrtc import Stream +import gradio as gr +import numpy as np + +def detection(image, slider): + return np.flip(image, axis=0) + +stream = Stream( + handler=detection, # (1) + modality="video", # (2) + mode="send-receive", # (3) + additional_inputs=[ + gr.Slider(minimum=0, maximum=1, step=0.01, value=0.3) # (4) + ], + additional_outputs=None, # (5) + additional_outputs_handler=None # (6) +) +``` + +1. See [Handlers](#handlers) for more information. +2. See [Modalities](#modalities) for more information. +3. See [Stream Modes](#stream-modes) for more information. +4. See [Additional Inputs](#additional-inputs) for more information. +5. See [Additional Outputs](#additional-outputs) for more information. +6. See [Additional Outputs Handler](#additional-outputs) for more information. +7. Mount the `Stream` on a `FastAPI` app with `stream.mount(app)` and you can add custom routes to it. See [Custom Routes and Frontend Integration](#custom-routes-and-frontend-integration) for more information. +8. See [Built-in Routes](#built-in-routes) for more information. + +Run: +=== "UI" + + ```py + stream.ui.launch() + ``` +=== "FastAPI" + + ```py + app = FastAPI() + stream.mount(app) + + # uvicorn app:app --host 0.0.0.0 --port 8000 + ``` + +### Stream Modes + +FastRTC supports three streaming modes: + +- `send-receive`: Bidirectional streaming (default) +- `send`: Client-to-server only +- `receive`: Server-to-client only + +### Modalities + +FastRTC supports three modalities: + +- `video`: Video streaming +- `audio`: Audio streaming +- `audio-video`: Combined audio and video streaming + +### Handlers + +The `handler` argument is the main argument of the `Stream` object. A handler should be a function or a class that inherits from `StreamHandler` or `AsyncStreamHandler` depending on the modality and mode. + + +| Modality | send-receive | send | receive | +|----------|--------------|------|----------| +| video | Function that takes a video frame and returns a new video frame | Function that takes a video frame and returns a new frame | Function that takes a video frame and returns a new frame | +| audio | `StreamHandler` or `AsyncStreamHandler` subclass | `StreamHandler` or `AsyncStreamHandler` subclass | Generator yielding audio frames | +| audio-video | `AudioVideoStreamHandler` or `AsyncAudioVideoStreamHandler` subclass | Not Supported Yet | Not Supported Yet | + + +## Methods + +The `Stream` has three main methods: + +- `.ui.launch()`: Launch a built-in UI for easily testing and sharing your stream. Built with [Gradio](https://www.gradio.app/). You can change the UI by setting the `ui` property of the `Stream` object. Also see the [Gradio guide](../gradio.md) for building Gradio apss with fastrtc. +- `.fastphone()`: Get a free temporary phone number to call into your stream. Hugging Face token required. +- `.mount(app)`: Mount the stream on a [FastAPI](https://fastapi.tiangolo.com/) app. Perfect for integrating with your already existing production system or for building a custom UI. + +!!! warning + Websocket docs are only available for audio streams. Telephone docs are only available for audio streams in `send-receive` mode. + +## Additional Inputs + +You can add additional inputs to your stream using the `additional_inputs` argument. These inputs will be displayed in the generated Gradio UI and they will be passed to the handler as additional arguments. + +!!! tip + For audio `StreamHandlers`, please read the special [note](../audio#requesting-inputs) on requesting inputs. + +In the automatic gradio UI, these inputs will be the same python type corresponding to the Gradio component. In our case, we used a `gr.Slider` as the additional input, so it will be passed as a float. See the [Gradio documentation](https://www.gradio.app/docs/gradio) for a complete list of components and their corresponding types. + +### Input Hooks + +Outside of the gradio UI, you are free to update the inputs however you like by using the `set_input` method of the `Stream` object. + +A common pattern is to use a `POST` request to send the updated data. + +```python +from pydantic import BaseModel, Field +from fastapi import FastAPI + +class InputData(BaseModel): + webrtc_id: str + conf_threshold: float = Field(ge=0, le=1) + +app = FastAPI() +stream.mount(app) + +@app.post("/input_hook") +async def _(data: InputData): + stream.set_input(data.webrtc_id, data.conf_threshold) +``` + +The updated data will be passed to the handler on the **next** call. + + +## Additional Outputs + +You can return additional output from the handler by returning an instance of `AdditionalOutputs` from the handler. +Let's modify our previous example to also return the number of detections in the frame. + +```python +from fastrtc import Stream, AdditionalOutputs +import gradio as gr + +def detection(image, conf_threshold=0.3): + processed_frame, n_objects = process_frame(image, conf_threshold) + return processed_frame, AdditionalOutputs(n_objects) + +stream = Stream( + handler=detection, + modality="video", + mode="send-receive", + additional_inputs=[ + gr.Slider(minimum=0, maximum=1, step=0.01, value=0.3) + ], + additional_outputs=[gr.Number()], # (5) + additional_outputs_handler=lambda component, n_objects: n_objects +) +``` + +We added a `gr.Number()` to the additional outputs and we provided an `additional_outputs_handler`. + +The `additional_outputs_handler` is **only** needed for the gradio UI. It is a function that takes the current state of the `component` and the instance of `AdditionalOutputs` and returns the updated state of the `component`. In our case, we want to update the `gr.Number()` with the number of detections. + +!!! tip + Since the webRTC is very low latency, you probably don't want to return an additional output on each frame. + +### Output Hooks + +Outside of the gradio UI, you are free to access the output data however you like by calling the `output_stream` method of the `Stream` object. + +A common pattern is to use a `GET` request to get a stream of the output data. + +```python +from fastapi.responses import StreamingResponse + +@app.get("/updates") +async def stream_updates(webrtc_id: str): + async def output_stream(): + async for output in stream.output_stream(webrtc_id): + # Output is the AdditionalOutputs instance + # Be sure to serialize it however you would like + yield f"data: {output.args[0]}\n\n" + + return StreamingResponse( + output_stream(), + media_type="text/event-stream" + ) +``` + +## Custom Routes and Frontend Integration + +You can add custom routes for serving your own frontend or handling additional functionality once you have mounted the stream on a FastAPI app. + +```python +from fastapi.responses import HTMLResponse +from fastapi import FastAPI +from fastrtc import Stream + +stream = Stream(...) + +app = FastAPI() +stream.mount(app) + +# Serve a custom frontend +@app.get("/") +async def serve_frontend(): + return HTMLResponse(content=open("index.html").read()) + +``` + +## Telephone Integration + +FastRTC provides built-in telephone support through the `fastphone()` method: + +```python +# Launch with a temporary phone number +stream.fastphone( + # Optional: If None, will use the default token in your machine or read from the HF_TOKEN environment variable + token="your_hf_token", + host="127.0.0.1", + port=8000 +) +``` + +This will print out a phone number along with your temporary code you can use to connect to the stream. You are limited to **10 minutes** of calls per calendar month. + +!!! warning + + See this [section](../audio#telephone-integration) on making sure your stream handler is compatible for telephone usage. + +!!! tip + + If you don't have a HF token, you can get one [here](https://huggingface.co/settings/tokens). + +## Concurrency + +1. You can limit the number of concurrent connections by setting the `concurrency_limit` argument. +2. You can limit the amount of time (in seconds) a connection can stay open by setting the `time_limit` argument. + +```python +stream = Stream( + handler=handler, + concurrency_limit=10, + time_limit=3600 +) +``` \ No newline at end of file diff --git a/docs/userguide/video.md b/docs/userguide/video.md new file mode 100644 index 0000000..a05d10a --- /dev/null +++ b/docs/userguide/video.md @@ -0,0 +1,57 @@ +# Video Streaming + +## Input/Output Streaming + +We already saw this example in the [Quickstart](../../#quickstart) and the [Core Concepts](../streams) section. + +=== "Code" + + ``` py title="Input/Output Streaming" + from fastrtc import Stream + import gradio as gr + + def detection(image, conf_threshold=0.3): # (1) + processed_frame = process_frame(image, conf_threshold) + return processed_frame # (2) + + stream = Stream( + handler=detection, + modality="video", + mode="send-receive", # (3) + additional_inputs=[ + gr.Slider(minimum=0, maximum=1, step=0.01, value=0.3) + ], + ) + ``` + + 1. The webcam frame will be represented as a numpy array of shape (height, width, RGB). + 2. The function must return a numpy array. It can take arbitrary values from other components. + 3. Set the `modality="video"` and `mode="send-receive"` +=== "Notes" + 1. The webcam frame will be represented as a numpy array of shape (height, width, RGB). + 2. The function must return a numpy array. It can take arbitrary values from other components. + 3. Set the `modality="video"` and `mode="send-receive"` + +## Server-to-Client Only + +In this case, we stream from the server to the client so we will write a generator function that yields the next frame from the video (as a numpy array) +and set the `mode="receive"` in the `WebRTC` component. + +=== "Code" + ``` py title="Server-To-Client" + from fastrtc import Stream + + def generation(): + url = "https://download.tsi.telecom-paristech.fr/gpac/dataset/dash/uhd/mux_sources/hevcds_720p30_2M.mp4" + cap = cv2.VideoCapture(url) + iterating = True + while iterating: + iterating, frame = cap.read() + yield frame + + stream = Stream( + handler=generation, + modality="video", + mode="receive" + ) + ``` diff --git a/docs/userguide/webrtc_docs.md b/docs/userguide/webrtc_docs.md new file mode 100644 index 0000000..7270b43 --- /dev/null +++ b/docs/userguide/webrtc_docs.md @@ -0,0 +1,160 @@ +# FastRTC Docs + +## Connecting + +To connect to the server, you need to create a new RTCPeerConnection object and call the `setupWebRTC` function below. +{% if mode in ["send-receive", "receive"] %} +This code snippet assumes there is an html element with an id of `{{ modality }}_output_component_id` where the output will be displayed. It should be {{ "a `