+ """
+ )
+ 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/gradio_webrtc/utils.py b/backend/fastrtc/utils.py
similarity index 62%
rename from backend/gradio_webrtc/utils.py
rename to backend/fastrtc/utils.py
index a2823ad..53e9d8c 100644
--- a/backend/gradio_webrtc/utils.py
+++ b/backend/fastrtc/utils.py
@@ -1,14 +1,18 @@
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, Protocol, TypedDict, cast
+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__)
@@ -17,6 +21,10 @@ logger = logging.getLogger(__name__)
AUDIO_PTIME = 0.020
+class Message(TypedDict):
+ type: str
+ data: Any
+
class AudioChunk(TypedDict):
start: int
end: int
@@ -31,6 +39,20 @@ 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
)
@@ -48,7 +70,6 @@ def _send_log(message: str, type: str) -> None:
)
if channel := current_channel.get():
- print("channel", channel)
try:
loop = asyncio.get_running_loop()
asyncio.run_coroutine_threadsafe(_send(channel), loop)
@@ -131,7 +152,7 @@ async def player_worker_decode(
and channel()
):
set_additional_outputs(outputs)
- cast(DataChannel, channel()).send("change")
+ cast(DataChannel, channel()).send(create_message("fetch_output", []))
if frame is None:
if quit_on_none:
@@ -139,6 +160,11 @@ async def player_worker_decode(
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"
@@ -153,6 +179,9 @@ async def player_worker_decode(
)
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
@@ -167,7 +196,6 @@ async def player_worker_decode(
processed_frame.time_base = audio_time_base
audio_samples += processed_frame.samples
await queue.put(processed_frame)
- logger.debug("Queue size utils.py: %s", queue.qsize())
except (TimeoutError, asyncio.TimeoutError):
logger.warning(
@@ -178,12 +206,15 @@ async def player_worker_decode(
import traceback
exec = traceback.format_exc()
- logger.debug("traceback %s", exec)
- logger.error("Error processing frame: %s", str(e))
- continue
+ 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, np.ndarray]) -> bytes:
+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.
@@ -217,7 +248,7 @@ def audio_to_bytes(audio: tuple[int, np.ndarray]) -> bytes:
return audio_buffer.getvalue()
-def audio_to_file(audio: tuple[int, np.ndarray]) -> str:
+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.
@@ -247,7 +278,9 @@ def audio_to_file(audio: tuple[int, np.ndarray]) -> str:
return f.name
-def audio_to_float32(audio: tuple[int, np.ndarray]) -> np.ndarray:
+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.
@@ -273,41 +306,151 @@ def audio_to_float32(audio: tuple[int, np.ndarray]) -> np.ndarray:
return audio[1].astype(np.float32) / 32768.0
-def aggregate_bytes_to_16bit(chunks_iterator):
- leftover = b"" # Store incomplete bytes between chunks
+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:
- # Combine with any leftover bytes from previous chunk
current_bytes = leftover + chunk
- # Calculate complete samples
- n_complete_samples = len(current_bytes) // 2 # int16 = 2 bytes
+ n_complete_samples = len(current_bytes) // 2
bytes_to_process = n_complete_samples * 2
- # Split into complete samples and leftover
to_process = current_bytes[:bytes_to_process]
leftover = current_bytes[bytes_to_process:]
- if to_process: # Only yield if we have complete samples
+ 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):
- leftover = b"" # Store incomplete bytes between chunks
+ """
+ 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:
- # Combine with any leftover bytes from previous chunk
current_bytes = leftover + chunk
- # Calculate complete samples
- n_complete_samples = len(current_bytes) // 2 # int16 = 2 bytes
+ n_complete_samples = len(current_bytes) // 2
bytes_to_process = n_complete_samples * 2
- # Split into complete samples and leftover
to_process = current_bytes[:bytes_to_process]
leftover = current_bytes[bytes_to_process:]
- if to_process: # Only yield if we have complete samples
+ 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/backend/gradio_webrtc/pause_detection/__init__.py b/backend/gradio_webrtc/pause_detection/__init__.py
deleted file mode 100644
index e4874b7..0000000
--- a/backend/gradio_webrtc/pause_detection/__init__.py
+++ /dev/null
@@ -1,3 +0,0 @@
-from .vad import SileroVADModel, SileroVadOptions
-
-__all__ = ["SileroVADModel", "SileroVadOptions"]
diff --git a/backend/gradio_webrtc/speech_to_text/__init__.py b/backend/gradio_webrtc/speech_to_text/__init__.py
deleted file mode 100644
index 8569c11..0000000
--- a/backend/gradio_webrtc/speech_to_text/__init__.py
+++ /dev/null
@@ -1,3 +0,0 @@
-from .stt_ import get_stt_model, stt, stt_for_chunks
-
-__all__ = ["stt", "stt_for_chunks", "get_stt_model"]
diff --git a/backend/gradio_webrtc/speech_to_text/stt_.py b/backend/gradio_webrtc/speech_to_text/stt_.py
deleted file mode 100644
index 6b2f696..0000000
--- a/backend/gradio_webrtc/speech_to_text/stt_.py
+++ /dev/null
@@ -1,53 +0,0 @@
-from dataclasses import dataclass
-from functools import lru_cache
-from typing import Callable
-
-import numpy as np
-from numpy.typing import NDArray
-
-from ..utils import AudioChunk
-
-
-@dataclass
-class STTModel:
- encoder: Callable
- decoder: Callable
-
-
-@lru_cache
-def get_stt_model() -> STTModel:
- from silero import silero_stt
-
- model, decoder, _ = silero_stt(language="en", version="v6", jit_model="jit_xlarge")
- return STTModel(model, decoder)
-
-
-def stt(audio: tuple[int, NDArray[np.int16]]) -> str:
- model = get_stt_model()
- sr, audio_np = audio
- if audio_np.dtype != np.float32:
- print("converting")
- audio_np = audio_np.astype(np.float32) / 32768.0
- try:
- import torch
- except ImportError:
- raise ImportError(
- "PyTorch is required to run speech-to-text for stopword detection. Run `pip install torch`."
- )
- audio_torch = torch.tensor(audio_np, dtype=torch.float32)
- if audio_torch.ndim == 1:
- audio_torch = audio_torch.unsqueeze(0)
- assert audio_torch.ndim == 2, "Audio must have a batch dimension"
- print("before")
- res = model.decoder(model.encoder(audio_torch)[0])
- print("after")
- return res
-
-
-def stt_for_chunks(
- audio: tuple[int, NDArray[np.int16]], chunks: list[AudioChunk]
-) -> str:
- sr, audio_np = audio
- return " ".join(
- [stt((sr, audio_np[chunk["start"] : chunk["end"]])) for chunk in chunks]
- )
diff --git a/backend/gradio_webrtc/webrtc.py b/backend/gradio_webrtc/webrtc.py
deleted file mode 100644
index 2dcd676..0000000
--- a/backend/gradio_webrtc/webrtc.py
+++ /dev/null
@@ -1,1161 +0,0 @@
-"""gr.WebRTC() component."""
-
-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 import defaultdict
-from collections.abc import Callable
-from typing import (
- TYPE_CHECKING,
- Any,
- Concatenate,
- Generator,
- Iterable,
- Literal,
- ParamSpec,
- Sequence,
- TypeAlias,
- TypeVar,
- Union,
- cast,
-)
-
-import anyio.to_thread
-import av
-import numpy as np
-from aiortc import (
- AudioStreamTrack,
- MediaStreamTrack,
- RTCPeerConnection,
- RTCSessionDescription,
- VideoStreamTrack,
-)
-from aiortc.contrib.media import AudioFrame, MediaRelay, VideoFrame # type: ignore
-from aiortc.mediastreams import MediaStreamError
-from gradio import wasm_utils
-from gradio.components.base import Component, server
-from gradio_client import handle_file
-from numpy import typing as npt
-
-from gradio_webrtc.utils import (
- AdditionalOutputs,
- DataChannel,
- current_channel,
- player_worker_decode,
- split_output,
-)
-
-if TYPE_CHECKING:
- from gradio.blocks import Block
- from gradio.components import Timer
- from gradio.events import Dependency
-
-
-if wasm_utils.IS_WASM:
- raise ValueError("Not supported in gradio-lite!")
-
-
-logger = logging.getLogger(__name__)
-
-VideoEmitType = Union[
- AdditionalOutputs, tuple[npt.ArrayLike, AdditionalOutputs], npt.ArrayLike, None
-]
-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
-
- 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("change")
- 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)
-
-
-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()
-
- @property
- def loop(self) -> asyncio.AbstractEventLoop:
- return cast(asyncio.AbstractEventLoop, self._loop)
-
- @property
- def channel(self) -> DataChannel | None:
- return self._channel
-
- def set_channel(self, channel: DataChannel):
- self._channel = channel
- self.channel_set.set()
-
- async def fetch_args(
- self,
- ):
- if self.channel:
- self.channel.send("tick")
- logger.debug("Sent tick")
-
- async def wait_for_args(self):
- await self.fetch_args()
- await self.args_set.wait()
-
- def wait_for_args_sync(self):
- asyncio.run_coroutine_threadsafe(self.wait_for_args(), self.loop).result()
-
- 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
-
- @abstractmethod
- def copy(self) -> "StreamHandlerBase":
- 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 = Union[
- tuple[int, np.ndarray],
- tuple[int, np.ndarray, Literal["mono", "stereo"]],
- AdditionalOutputs,
- tuple[tuple[int, np.ndarray], AdditionalOutputs],
- None,
-]
-AudioEmitType = EmitType
-
-
-class StreamHandler(StreamHandlerBase):
- @abstractmethod
- def receive(self, frame: tuple[int, np.ndarray]) -> None:
- pass
-
- @abstractmethod
- def emit(
- self,
- ) -> EmitType:
- pass
-
-
-class AsyncStreamHandler(StreamHandlerBase):
- @abstractmethod
- async def receive(self, frame: tuple[int, np.ndarray]) -> None:
- pass
-
- @abstractmethod
- async def emit(
- self,
- ) -> EmitType:
- pass
-
-
-StreamHandlerImpl = Union[StreamHandler, AsyncStreamHandler]
-
-
-class AudioVideoStreamHandler(StreamHandlerBase):
- @abstractmethod
- def video_receive(self, frame: npt.NDArray) -> None:
- pass
-
- @abstractmethod
- def video_emit(
- self,
- ) -> VideoEmitType:
- pass
-
-
-class AsyncAudioVideoStreamHandler(StreamHandlerBase):
- @abstractmethod
- async def video_receive(self, frame: npt.NDArray) -> None:
- pass
-
- @abstractmethod
- async def video_emit(
- self,
- ) -> VideoEmitType:
- pass
-
-
-VideoStreamHandlerImpl = Union[AudioVideoStreamHandler, AsyncAudioVideoStreamHandler]
-AudioVideoStreamHandlerImpl = Union[
- AudioVideoStreamHandler, AsyncAudioVideoStreamHandler
-]
-AsyncHandler = Union[AsyncStreamHandler, AsyncAudioVideoStreamHandler]
-
-
-class VideoStreamHander(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)
- except MediaStreamError:
- self.stop()
-
- def start(self):
- if not self.has_started:
- asyncio.create_task(self.process_frames())
- self.has_started = True
-
- async def recv(self): # type: ignore
- 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("change")
- 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.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 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)
-
- 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)
- )
- 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
-
- def start(self):
- if not self.has_started:
- loop = asyncio.get_running_loop()
- if isinstance(self.event_handler, AsyncHandler):
- callable = self.event_handler.emit
- else:
- callable = functools.partial(
- loop.run_in_executor, None, self.event_handler.emit
- )
- asyncio.create_task(self.process_input_frames())
- 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.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)
-
- 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()
-
- def shutdown(self):
- self.event_handler.shutdown()
-
-
-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()
- if self.generator is None:
- self.generator = cast(
- Generator[Any, None, Any], self.event_handler(*self.latest_args)
- )
- current_channel.set(self.channel)
- 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("change")
- 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 ", exec)
-
-
-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.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 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()
-
- 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
-
- 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)
-
- def stop(self):
- logger.debug("audio-to-client stop callback")
- self.thread_quit.set()
- super().stop()
-
-
-# For the return type
-R = TypeVar("R")
-# For the parameter specification
-P = ParamSpec("P")
-
-
-class WebRTC(Component):
- """
- 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
- """
-
- pcs: set[RTCPeerConnection] = set([])
- relay = MediaRelay()
- connections: dict[
- str,
- list[VideoCallback | ServerToClientVideo | ServerToClientAudio | AudioCallback],
- ] = defaultdict(list)
- data_channels: dict[str, DataChannel] = {}
- additional_outputs: dict[str, list[AdditionalOutputs]] = {}
- handlers: dict[str, StreamHandlerBase | Callable] = {}
-
- 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",
- show_local_video: Literal['picture-in-picture', 'left-right', None] = None,
- video_chat: bool = True,
- rtp_params: dict[str, Any] | None = None,
- icon: str | None = None,
- icon_button_color: str | None = None,
- pulse_color: str | None = None,
- button_labels: dict | None = None,
- ):
- """
- 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".
- show_local_video: in send-receive mode and audio-video modality, whether to show the local video stream. - "picture-in-picture" or "left-right".
- 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.
- """
- 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.show_local_video = show_local_video
- self.video_chat = video_chat
- self.icon_button_color = icon_button_color
- self.pulse_color = pulse_color
- self.rtp_params = rtp_params or {}
- self.button_labels = {
- "start": "",
- "stop": "",
- "waiting": "",
- **(button_labels or {}),
- }
- if video_chat is True:
- # ensure modality and mode when video_chat is True
- self.modality = "audio-video"
- self.mode = "send-receive"
- 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 set_additional_outputs(
- self, webrtc_id: str
- ) -> Callable[[AdditionalOutputs], None]:
- def set_outputs(outputs: AdditionalOutputs):
- if webrtc_id not in self.additional_outputs:
- self.additional_outputs[webrtc_id] = []
- self.additional_outputs[webrtc_id].append(outputs)
-
- return set_outputs
-
- 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 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))
-
- 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)
-
- def handler(webrtc_id: str, *args):
- if (
- webrtc_id in self.additional_outputs
- and len(self.additional_outputs[webrtc_id]) > 0
- ):
- next_outputs = self.additional_outputs[webrtc_id].pop(0)
- return fn(*args, *next_outputs.args) # type: ignore
- return (
- tuple([None for _ in range(len(outputs))])
- if isinstance(outputs, Iterable)
- else None
- )
-
- 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=show_progress,
- queue=queue,
- trigger_mode="multiple",
- )
-
- def stream(
- self,
- fn: Callable[..., Any]
- | StreamHandlerImpl
- | AudioVideoStreamHandlerImpl
- | 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: Dependency | 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 = (
- 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,
- )
-
- @staticmethod
- async def wait_for_time_limit(pc: RTCPeerConnection, time_limit: float):
- await asyncio.sleep(time_limit)
- await pc.close()
-
- def clean_up(self, webrtc_id: str):
- self.handlers.pop(webrtc_id, None)
- connection = self.connections.pop(webrtc_id, [])
- for conn in connection:
- if isinstance(conn, AudioCallback):
- conn.event_handler.shutdown()
- self.additional_outputs.pop(webrtc_id, None)
- self.data_channels.pop(webrtc_id, None)
- return connection
-
- @server
- async def offer(self, body):
- logger.debug("Starting to handle offer")
- logger.debug("Offer body %s", body)
- if len(self.connections) >= cast(int, self.concurrency_limit):
- return {"status": "failed"}
-
- 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()
- else:
- handler = cast(Callable, self.event_handler)
-
- self.handlers[body["webrtc_id"]] = handler
-
- set_outputs = self.set_additional_outputs(body["webrtc_id"])
-
- @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 on_connectionstatechange():
- 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":
- if self.time_limit is not None:
- asyncio.create_task(self.wait_for_time_limit(pc, self.time_limit))
-
- @pc.on("track")
- def on_track(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(VideoEventHandler, handler),
- set_additional_outputs=set_outputs,
- mode=cast(Literal["send", "send-receive"], self.mode),
- )
- elif self.modality == "audio-video" and track.kind == "video":
- cb = VideoStreamHander(
- 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":
- 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 on_datachannel(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 on_message(message):
- logger.debug(f"Received message: {message}")
- if channel.readyState == "open":
- channel.send(f"Server received: {message}")
-
- # handle offer
- await pc.setRemoteDescription(offer)
-
- # 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,
- }
-
- 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/demo/README.md b/demo/README.md
deleted file mode 100644
index 16e1307..0000000
--- a/demo/README.md
+++ /dev/null
@@ -1,44 +0,0 @@
----
-license: mit
-tags:
-- object-detection
-- computer-vision
-- yolov10
-datasets:
-- detection-datasets/coco
-sdk: gradio
-sdk_version: 5.0.0b1
----
-
-### Model Description
-[YOLOv10: Real-Time End-to-End Object Detection](https://arxiv.org/abs/2405.14458v1)
-
-- arXiv: https://arxiv.org/abs/2405.14458v1
-- github: https://github.com/THU-MIG/yolov10
-
-### Installation
-```
-pip install supervision git+https://github.com/THU-MIG/yolov10.git
-```
-
-### Yolov10 Inference
-```python
-from ultralytics import YOLOv10
-import supervision as sv
-import cv2
-
-IMAGE_PATH = 'dog.jpeg'
-
-model = YOLOv10.from_pretrained('jameslahm/yolov10{n/s/m/b/l/x}')
-model.predict(IMAGE_PATH, show=True)
-```
-
-### BibTeX Entry and Citation Info
- ```
-@article{wang2024yolov10,
- title={YOLOv10: Real-Time End-to-End Object Detection},
- author={Wang, Ao and Chen, Hui and Liu, Lihao and Chen, Kai and Lin, Zijia and Han, Jungong and Ding, Guiguang},
- journal={arXiv preprint arXiv:2405.14458},
- year={2024}
-}
-```
\ No newline at end of file
diff --git a/demo/also_return_text.py b/demo/also_return_text.py
deleted file mode 100644
index 85a682a..0000000
--- a/demo/also_return_text.py
+++ /dev/null
@@ -1,105 +0,0 @@
-import logging
-import os
-
-import gradio as gr
-import numpy as np
-from gradio_webrtc import AdditionalOutputs, WebRTC
-from pydub import AudioSegment
-from twilio.rest import Client
-
-# 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("gradio_webrtc")
-logger.setLevel(logging.DEBUG)
-logger.addHandler(console_handler)
-
-
-account_sid = os.environ.get("TWILIO_ACCOUNT_SID")
-auth_token = os.environ.get("TWILIO_AUTH_TOKEN")
-
-if account_sid and auth_token:
- client = Client(account_sid, auth_token)
-
- token = client.tokens.create()
-
- rtc_configuration = {
- "iceServers": token.ice_servers,
- "iceTransportPolicy": "relay",
- }
-else:
- rtc_configuration = None
-
-
-def generation(num_steps):
- for i in range(num_steps):
- segment = AudioSegment.from_file(
- "/Users/freddy/sources/gradio/demo/scratch/audio-streaming/librispeech.mp3"
- )
- yield (
- (
- segment.frame_rate,
- np.array(segment.get_array_of_samples()).reshape(1, -1),
- ),
- AdditionalOutputs(
- f"Hello, from step {i}!",
- "/Users/freddy/sources/gradio/demo/scratch/audio-streaming/librispeech.mp3",
- ),
- )
-
-
-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() as demo:
- gr.HTML(
- """
-
- Audio Streaming (Powered by WebRTC ⚡️)
-
- """
- )
- with gr.Column(elem_classes=["my-column"]):
- with gr.Group(elem_classes=["my-group"]):
- audio = WebRTC(
- label="Stream",
- rtc_configuration=rtc_configuration,
- mode="receive",
- modality="audio",
- )
- num_steps = gr.Slider(
- label="Number of Steps",
- minimum=1,
- maximum=10,
- step=1,
- value=5,
- )
- button = gr.Button("Generate")
- textbox = gr.Textbox(placeholder="Output will appear here.")
- audio_file = gr.Audio()
-
- audio.stream(
- fn=generation, inputs=[num_steps], outputs=[audio], trigger=button.click
- )
- audio.on_additional_outputs(
- fn=lambda t, a: (f"State changed to {t}.", a),
- outputs=[textbox, audio_file],
- )
-
-
-if __name__ == "__main__":
- demo.launch(
- allowed_paths=[
- "/Users/freddy/sources/gradio/demo/scratch/audio-streaming/librispeech.mp3"
- ]
- )
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/app_.py b/demo/app_.py
deleted file mode 100644
index 378a8a5..0000000
--- a/demo/app_.py
+++ /dev/null
@@ -1,367 +0,0 @@
-import os
-
-import gradio as gr
-
-_docs = {
- "WebRTC": {
- "description": "Stream audio/video with WebRTC",
- "members": {
- "__init__": {
- "rtc_configuration": {
- "type": "dict[str, Any] | None",
- "default": "None",
- "description": "The configration dictionary to pass to the RTCPeerConnection constructor. If None, the default configuration is used.",
- },
- "height": {
- "type": "int | str | None",
- "default": "None",
- "description": "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": {
- "type": "int | str | None",
- "default": "None",
- "description": "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": {
- "type": "str | None",
- "default": "None",
- "description": "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.",
- },
- "show_label": {
- "type": "bool | None",
- "default": "None",
- "description": "if True, will display label.",
- },
- "container": {
- "type": "bool",
- "default": "True",
- "description": "if True, will place the component in a container - providing some extra padding around the border.",
- },
- "scale": {
- "type": "int | None",
- "default": "None",
- "description": "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": {
- "type": "int",
- "default": "160",
- "description": "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": {
- "type": "bool | None",
- "default": "None",
- "description": "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": {
- "type": "bool",
- "default": "True",
- "description": "if False, component will be hidden.",
- },
- "elem_id": {
- "type": "str | None",
- "default": "None",
- "description": "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": {
- "type": "list[str] | str | None",
- "default": "None",
- "description": "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": {
- "type": "bool",
- "default": "True",
- "description": "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": {
- "type": "int | str | None",
- "default": "None",
- "description": "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": {
- "type": "bool",
- "default": "True",
- "description": "if True webcam will be mirrored. Default is True.",
- },
- },
- "events": {"tick": {"type": None, "default": None, "description": ""}},
- },
- "__meta__": {"additional_interfaces": {}, "user_fn_refs": {"WebRTC": []}},
- }
-}
-
-
-abs_path = os.path.join(os.path.dirname(__file__), "css.css")
-
-with gr.Blocks(
- css_paths=abs_path,
- theme=gr.themes.Default(
- font_mono=[
- gr.themes.GoogleFont("Inconsolata"),
- "monospace",
- ],
- ),
-) as demo:
- gr.Markdown(
- """
-
Gradio WebRTC ⚡️
-
-
-
-
-
-""",
- elem_classes=["md-custom"],
- header_links=True,
- )
- gr.Markdown(
- """
-## Installation
-
-```bash
-pip install gradio_webrtc
-```
-
-## Examples:
-1. [Object Detection from Webcam with YOLOv10](https://huggingface.co/spaces/freddyaboulton/webrtc-yolov10n) 📷
-2. [Streaming Object Detection from Video with RT-DETR](https://huggingface.co/spaces/freddyaboulton/rt-detr-object-detection-webrtc) 🎥
-3. [Text-to-Speech](https://huggingface.co/spaces/freddyaboulton/parler-tts-streaming-webrtc) 🗣️
-4. [Conversational AI](https://huggingface.co/spaces/freddyaboulton/omni-mini-webrtc) 🤖🗣️
-
-## Usage
-
-The WebRTC component supports the following three use cases:
-1. [Streaming video from the user webcam to the server and back](#h-streaming-video-from-the-user-webcam-to-the-server-and-back)
-2. [Streaming Video from the server to the client](#h-streaming-video-from-the-server-to-the-client)
-3. [Streaming Audio from the server to the client](#h-streaming-audio-from-the-server-to-the-client)
-4. [Streaming Audio from the client to the server and back (conversational AI)](#h-conversational-ai)
-
-
-## Streaming Video from the User Webcam to the Server and Back
-
-```python
-import gradio as gr
-from gradio_webrtc import WebRTC
-
-
-def detection(image, conf_threshold=0.3):
- ... your detection code here ...
-
-
-with gr.Blocks() as demo:
- image = WebRTC(label="Stream", mode="send-receive", modality="video")
- conf_threshold = gr.Slider(
- label="Confidence Threshold",
- minimum=0.0,
- maximum=1.0,
- step=0.05,
- value=0.30,
- )
- image.stream(
- fn=detection,
- inputs=[image, conf_threshold],
- outputs=[image], time_limit=10
- )
-
-if __name__ == "__main__":
- demo.launch()
-
-```
-* Set the `mode` parameter to `send-receive` and `modality` to "video".
-* The `stream` event's `fn` parameter is a function that receives the next frame from the webcam
-as a **numpy array** and returns the processed frame also as a **numpy array**.
-* Numpy arrays are in (height, width, 3) format where the color channels are in RGB format.
-* The `inputs` parameter should be a list where the first element is the WebRTC component. The only output allowed is the WebRTC component.
-* The `time_limit` parameter is the maximum time in seconds the video stream will run. If the time limit is reached, the video stream will stop.
-
-## Streaming Video from the server to the client
-
-```python
-import gradio as gr
-from gradio_webrtc import WebRTC
-import cv2
-
-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
-
-with gr.Blocks() as demo:
- output_video = WebRTC(label="Video Stream", mode="receive", modality="video")
- button = gr.Button("Start", variant="primary")
- output_video.stream(
- fn=generation, inputs=None, outputs=[output_video],
- trigger=button.click
- )
-
-if __name__ == "__main__":
- demo.launch()
-```
-
-* Set the "mode" parameter to "receive" and "modality" to "video".
-* The `stream` event's `fn` parameter is a generator function that yields the next frame from the video as a **numpy array**.
-* The only output allowed is the WebRTC component.
-* The `trigger` parameter the gradio event that will trigger the webrtc connection. In this case, the button click event.
-
-## Streaming Audio from the Server to the Client
-
-```python
-import gradio as gr
-from pydub import AudioSegment
-
-def generation(num_steps):
- for _ in range(num_steps):
- segment = AudioSegment.from_file("/Users/freddy/sources/gradio/demo/audio_debugger/cantina.wav")
- yield (segment.frame_rate, np.array(segment.get_array_of_samples()).reshape(1, -1))
-
-with gr.Blocks() as demo:
- audio = WebRTC(label="Stream", mode="receive", modality="audio")
- num_steps = gr.Slider(
- label="Number of Steps",
- minimum=1,
- maximum=10,
- step=1,
- value=5,
- )
- button = gr.Button("Generate")
-
- audio.stream(
- fn=generation, inputs=[num_steps], outputs=[audio],
- trigger=button.click
- )
-```
-
-* Set the "mode" parameter to "receive" and "modality" to "audio".
-* The `stream` event's `fn` parameter is a generator function that yields the next audio segment as a tuple of (frame_rate, audio_samples).
-* The numpy array should be of shape (1, num_samples).
-* The `outputs` parameter should be a list with the WebRTC component as the only element.
-
-## Conversational AI
-
-```python
-import gradio as gr
-import numpy as np
-from gradio_webrtc import WebRTC, StreamHandler
-from queue import Queue
-import time
-
-
-class EchoHandler(StreamHandler):
- def __init__(self) -> None:
- super().__init__()
- self.queue = Queue()
-
- def receive(self, frame: tuple[int, np.ndarray] | np.ndarray) -> None:
- self.queue.put(frame)
-
- def emit(self) -> None:
- return self.queue.get()
-
-
-with gr.Blocks() as demo:
- with gr.Column():
- with gr.Group():
- audio = WebRTC(
- label="Stream",
- rtc_configuration=None,
- mode="send-receive",
- modality="audio",
- )
-
- audio.stream(fn=EchoHandler(), inputs=[audio], outputs=[audio], time_limit=15)
-
-
-if __name__ == "__main__":
- demo.launch()
-```
-
-* Instead of passing a function to the `stream` event's `fn` parameter, pass a `StreamHandler` implementation. The `StreamHandler` above simply echoes the audio back to the client.
-* The `StreamHandler` class has two methods: `receive` and `emit`. 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.
-* An audio frame is represented as a tuple of (frame_rate, audio_samples) where `audio_samples` is a numpy array of shape (num_channels, num_samples).
-* You can also specify the audio layout ("mono" or "stereo") in the emit method by retuning it as the third element of the tuple. If not specified, the default is "mono".
-* The `time_limit` parameter is the maximum time in seconds the conversation will run. If the time limit is reached, the audio stream will stop.
-* The `emit` method SHOULD NOT block. If a frame is not ready to be sent, the method should return None.
-
-## 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, ...)
- ...
-```
-""",
- elem_classes=["md-custom"],
- header_links=True,
- )
-
- gr.Markdown(
- """
-##
-""",
- elem_classes=["md-custom"],
- header_links=True,
- )
-
- gr.ParamViewer(value=_docs["WebRTC"]["members"]["__init__"], linkify=[])
-
- demo.load(
- None,
- js=r"""function() {
- const refs = {};
- const user_fn_refs = {
- WebRTC: [], };
- requestAnimationFrame(() => {
-
- Object.entries(user_fn_refs).forEach(([key, refs]) => {
- if (refs.length > 0) {
- const el = document.querySelector(`.${key}-user-fn`);
- if (!el) return;
- refs.forEach(ref => {
- el.innerHTML = el.innerHTML.replace(
- new RegExp("\\b"+ref+"\\b", "g"),
- `${ref}`
- );
- })
- }
- })
-
- Object.entries(refs).forEach(([key, refs]) => {
- if (refs.length > 0) {
- const el = document.querySelector(`.${key}`);
- if (!el) return;
- refs.forEach(ref => {
- el.innerHTML = el.innerHTML.replace(
- new RegExp("\\b"+ref+"\\b", "g"),
- `${ref}`
- );
- })
- }
- })
- })
-}
-
-""",
- )
-
-demo.launch()
diff --git a/demo/app_orig.py b/demo/app_orig.py
deleted file mode 100644
index 31f3b3f..0000000
--- a/demo/app_orig.py
+++ /dev/null
@@ -1,73 +0,0 @@
-import os
-
-import cv2
-import gradio as gr
-from gradio_webrtc import WebRTC
-from huggingface_hub import hf_hub_download
-from inference import YOLOv10
-from twilio.rest import Client
-
-model_file = hf_hub_download(
- repo_id="onnx-community/yolov10n", filename="onnx/model.onnx"
-)
-
-model = YOLOv10(model_file)
-
-account_sid = os.environ.get("TWILIO_ACCOUNT_SID")
-auth_token = os.environ.get("TWILIO_AUTH_TOKEN")
-
-if account_sid and auth_token:
- client = Client(account_sid, auth_token)
-
- token = client.tokens.create()
-
- rtc_configuration = {
- "iceServers": token.ice_servers,
- "iceTransportPolicy": "relay",
- }
-else:
- rtc_configuration = None
-
-
-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))
-
-
-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(
- """
-
+ """
+ )
+ 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 💻
+
+
+
+
+
+
+
+
+
Hello Computer 💻
+
Say 'Computer' before asking your question
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ 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".*?