mirror of
https://github.com/HumanAIGC-Engineering/gradio-webrtc.git
synced 2026-02-05 18:09:23 +08:00
Audio in only (#15)
* Audio + Video / test Audio * Add code * Fix demo * support additional inputs * Add code * Add code
This commit is contained in:
3
.gitignore
vendored
3
.gitignore
vendored
@@ -13,4 +13,5 @@ backend/**/templates/
|
|||||||
demo/MobileNetSSD_deploy.caffemodel
|
demo/MobileNetSSD_deploy.caffemodel
|
||||||
demo/MobileNetSSD_deploy.prototxt.txt
|
demo/MobileNetSSD_deploy.prototxt.txt
|
||||||
.DS_Store
|
.DS_Store
|
||||||
test/
|
test/
|
||||||
|
.env
|
||||||
@@ -2,11 +2,14 @@ from dataclasses import dataclass
|
|||||||
from functools import lru_cache
|
from functools import lru_cache
|
||||||
from logging import getLogger
|
from logging import getLogger
|
||||||
from threading import Event
|
from threading import Event
|
||||||
from typing import Callable, Generator, Literal, cast
|
import inspect
|
||||||
|
from typing import Any, Callable, Generator, Literal, Union, cast
|
||||||
|
import asyncio
|
||||||
|
|
||||||
import numpy as np
|
import numpy as np
|
||||||
|
|
||||||
from gradio_webrtc.pause_detection import SileroVADModel, SileroVadOptions
|
from gradio_webrtc.pause_detection import SileroVADModel, SileroVadOptions
|
||||||
|
from gradio_webrtc.utils import AdditionalOutputs
|
||||||
from gradio_webrtc.webrtc import StreamHandler
|
from gradio_webrtc.webrtc import StreamHandler
|
||||||
|
|
||||||
logger = getLogger(__name__)
|
logger = getLogger(__name__)
|
||||||
@@ -40,12 +43,29 @@ class AppState:
|
|||||||
buffer: np.ndarray | None = None
|
buffer: np.ndarray | None = None
|
||||||
|
|
||||||
|
|
||||||
ReplyFnGenerator = Callable[
|
ReplyFnGenerator = Union[
|
||||||
[tuple[int, np.ndarray]],
|
# For two arguments
|
||||||
Generator[
|
Callable[
|
||||||
tuple[int, np.ndarray] | tuple[int, np.ndarray, Literal["mono", "stereo"]],
|
[tuple[int, np.ndarray], list[dict[Any, Any]]],
|
||||||
None,
|
Generator[
|
||||||
None,
|
tuple[int, np.ndarray]
|
||||||
|
| tuple[int, np.ndarray, Literal["mono", "stereo"]]
|
||||||
|
| AdditionalOutputs
|
||||||
|
| tuple[tuple[int, np.ndarray], AdditionalOutputs],
|
||||||
|
None,
|
||||||
|
None,
|
||||||
|
],
|
||||||
|
],
|
||||||
|
Callable[
|
||||||
|
[tuple[int, np.ndarray]],
|
||||||
|
Generator[
|
||||||
|
tuple[int, np.ndarray]
|
||||||
|
| tuple[int, np.ndarray, Literal["mono", "stereo"]]
|
||||||
|
| AdditionalOutputs
|
||||||
|
| tuple[tuple[int, np.ndarray], AdditionalOutputs],
|
||||||
|
None,
|
||||||
|
None,
|
||||||
|
],
|
||||||
],
|
],
|
||||||
]
|
]
|
||||||
|
|
||||||
@@ -71,6 +91,12 @@ class ReplyOnPause(StreamHandler):
|
|||||||
self.generator = None
|
self.generator = None
|
||||||
self.model_options = model_options
|
self.model_options = model_options
|
||||||
self.algo_options = algo_options or AlgoOptions()
|
self.algo_options = algo_options or AlgoOptions()
|
||||||
|
self.latest_args: list[Any] = []
|
||||||
|
self.args_set = Event()
|
||||||
|
|
||||||
|
@property
|
||||||
|
def _needs_additional_inputs(self) -> bool:
|
||||||
|
return len(inspect.signature(self.fn).parameters) > 1
|
||||||
|
|
||||||
def copy(self):
|
def copy(self):
|
||||||
return ReplyOnPause(
|
return ReplyOnPause(
|
||||||
@@ -130,17 +156,38 @@ class ReplyOnPause(StreamHandler):
|
|||||||
self.event.set()
|
self.event.set()
|
||||||
|
|
||||||
def reset(self):
|
def reset(self):
|
||||||
|
self.args_set.clear()
|
||||||
self.generator = None
|
self.generator = None
|
||||||
self.event.clear()
|
self.event.clear()
|
||||||
self.state = AppState()
|
self.state = AppState()
|
||||||
|
|
||||||
|
def set_args(self, args: list[Any]):
|
||||||
|
super().set_args(args)
|
||||||
|
self.args_set.set()
|
||||||
|
|
||||||
|
async def fetch_args(
|
||||||
|
self,
|
||||||
|
):
|
||||||
|
if self.channel:
|
||||||
|
self.channel.send("tick")
|
||||||
|
logger.debug("Sent tick")
|
||||||
|
|
||||||
def emit(self):
|
def emit(self):
|
||||||
if not self.event.is_set():
|
if not self.event.is_set():
|
||||||
return None
|
return None
|
||||||
else:
|
else:
|
||||||
if not self.generator:
|
if not self.generator:
|
||||||
|
if self._needs_additional_inputs and not self.args_set.is_set():
|
||||||
|
asyncio.run_coroutine_threadsafe(self.fetch_args(), self.loop)
|
||||||
|
self.args_set.wait()
|
||||||
|
logger.debug("Creating generator")
|
||||||
audio = cast(np.ndarray, self.state.stream).reshape(1, -1)
|
audio = cast(np.ndarray, self.state.stream).reshape(1, -1)
|
||||||
self.generator = self.fn((self.state.sampling_rate, audio))
|
if self._needs_additional_inputs:
|
||||||
|
self.latest_args[0] = (self.state.sampling_rate, audio)
|
||||||
|
self.generator = self.fn(*self.latest_args)
|
||||||
|
else:
|
||||||
|
self.generator = self.fn((self.state.sampling_rate, audio)) # type: ignore
|
||||||
|
logger.debug("Latest args: %s", self.latest_args)
|
||||||
self.state.responding = True
|
self.state.responding = True
|
||||||
try:
|
try:
|
||||||
return next(self.generator)
|
return next(self.generator)
|
||||||
|
|||||||
@@ -22,6 +22,8 @@ class DataChannel(Protocol):
|
|||||||
|
|
||||||
|
|
||||||
def split_output(data: tuple | Any) -> tuple[Any, AdditionalOutputs | None]:
|
def split_output(data: tuple | Any) -> tuple[Any, AdditionalOutputs | None]:
|
||||||
|
if isinstance(data, AdditionalOutputs):
|
||||||
|
return None, data
|
||||||
if isinstance(data, tuple):
|
if isinstance(data, tuple):
|
||||||
# handle the bare audio case
|
# handle the bare audio case
|
||||||
if 2 <= len(data) <= 3 and isinstance(data[1], np.ndarray):
|
if 2 <= len(data) <= 3 and isinstance(data[1], np.ndarray):
|
||||||
|
|||||||
@@ -72,6 +72,7 @@ class VideoCallback(VideoStreamTrack):
|
|||||||
event_handler: Callable,
|
event_handler: Callable,
|
||||||
channel: DataChannel | None = None,
|
channel: DataChannel | None = None,
|
||||||
set_additional_outputs: Callable | None = None,
|
set_additional_outputs: Callable | None = None,
|
||||||
|
mode: Literal["send-receive", "send"] = "send-receive",
|
||||||
) -> None:
|
) -> None:
|
||||||
super().__init__() # don't forget this!
|
super().__init__() # don't forget this!
|
||||||
self.track = track
|
self.track = track
|
||||||
@@ -79,6 +80,14 @@ class VideoCallback(VideoStreamTrack):
|
|||||||
self.latest_args: str | list[Any] = "not_set"
|
self.latest_args: str | list[Any] = "not_set"
|
||||||
self.channel = channel
|
self.channel = channel
|
||||||
self.set_additional_outputs = set_additional_outputs
|
self.set_additional_outputs = set_additional_outputs
|
||||||
|
self.thread_quit = asyncio.Event()
|
||||||
|
self.mode = mode
|
||||||
|
|
||||||
|
def set_channel(self, channel: DataChannel):
|
||||||
|
self.channel = channel
|
||||||
|
|
||||||
|
def set_args(self, args: list[Any]):
|
||||||
|
self.latest_args = ["__webrtc_value__"] + list(args)
|
||||||
|
|
||||||
def add_frame_to_payload(
|
def add_frame_to_payload(
|
||||||
self, args: list[Any], frame: np.ndarray | None
|
self, args: list[Any], frame: np.ndarray | None
|
||||||
@@ -94,11 +103,29 @@ class VideoCallback(VideoStreamTrack):
|
|||||||
def array_to_frame(self, array: np.ndarray) -> VideoFrame:
|
def array_to_frame(self, array: np.ndarray) -> VideoFrame:
|
||||||
return VideoFrame.from_ndarray(array, format="bgr24")
|
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 recv(self):
|
async def recv(self):
|
||||||
try:
|
try:
|
||||||
try:
|
try:
|
||||||
frame = cast(VideoFrame, await self.track.recv())
|
frame = cast(VideoFrame, await self.track.recv())
|
||||||
except MediaStreamError:
|
except MediaStreamError:
|
||||||
|
self.stop()
|
||||||
return
|
return
|
||||||
frame_array = frame.to_ndarray(format="bgr24")
|
frame_array = frame.to_ndarray(format="bgr24")
|
||||||
|
|
||||||
@@ -115,6 +142,8 @@ class VideoCallback(VideoStreamTrack):
|
|||||||
):
|
):
|
||||||
self.set_additional_outputs(outputs)
|
self.set_additional_outputs(outputs)
|
||||||
self.channel.send("change")
|
self.channel.send("change")
|
||||||
|
if array is None and self.mode == "send":
|
||||||
|
return
|
||||||
|
|
||||||
new_frame = self.array_to_frame(array)
|
new_frame = self.array_to_frame(array)
|
||||||
if frame:
|
if frame:
|
||||||
@@ -142,7 +171,25 @@ class StreamHandler(ABC):
|
|||||||
self.expected_layout = expected_layout
|
self.expected_layout = expected_layout
|
||||||
self.output_sample_rate = output_sample_rate
|
self.output_sample_rate = output_sample_rate
|
||||||
self.output_frame_size = output_frame_size
|
self.output_frame_size = output_frame_size
|
||||||
|
self.latest_args: str | list[Any] = "not_set"
|
||||||
self._resampler = None
|
self._resampler = None
|
||||||
|
self._channel: DataChannel | None = None
|
||||||
|
self._loop: asyncio.AbstractEventLoop
|
||||||
|
|
||||||
|
@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
|
||||||
|
|
||||||
|
def set_args(self, args: list[Any]):
|
||||||
|
logger.debug("setting args in audio callback %s", args)
|
||||||
|
self.latest_args = ["__webrtc_value__"] + list(args)
|
||||||
|
|
||||||
@abstractmethod
|
@abstractmethod
|
||||||
def copy(self) -> "StreamHandler":
|
def copy(self) -> "StreamHandler":
|
||||||
@@ -190,6 +237,13 @@ class AudioCallback(AudioStreamTrack):
|
|||||||
self.set_additional_outputs = set_additional_outputs
|
self.set_additional_outputs = set_additional_outputs
|
||||||
super().__init__()
|
super().__init__()
|
||||||
|
|
||||||
|
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)
|
||||||
|
|
||||||
async def process_input_frames(self) -> None:
|
async def process_input_frames(self) -> None:
|
||||||
while not self.thread_quit.is_set():
|
while not self.thread_quit.is_set():
|
||||||
try:
|
try:
|
||||||
@@ -284,6 +338,13 @@ class ServerToClientVideo(VideoStreamTrack):
|
|||||||
def array_to_frame(self, array: np.ndarray) -> VideoFrame:
|
def array_to_frame(self, array: np.ndarray) -> VideoFrame:
|
||||||
return VideoFrame.from_ndarray(array, format="bgr24")
|
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):
|
async def recv(self):
|
||||||
try:
|
try:
|
||||||
pts, time_base = await self.next_timestamp()
|
pts, time_base = await self.next_timestamp()
|
||||||
@@ -338,6 +399,13 @@ class ServerToClientAudio(AudioStreamTrack):
|
|||||||
self._start: float | None = None
|
self._start: float | None = None
|
||||||
super().__init__()
|
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:
|
def next(self) -> tuple[int, np.ndarray] | None:
|
||||||
self.args_set.wait()
|
self.args_set.wait()
|
||||||
if self.generator is None:
|
if self.generator is None:
|
||||||
@@ -447,7 +515,7 @@ class WebRTC(Component):
|
|||||||
rtc_configuration: dict[str, Any] | None = None,
|
rtc_configuration: dict[str, Any] | None = None,
|
||||||
track_constraints: dict[str, Any] | None = None,
|
track_constraints: dict[str, Any] | None = None,
|
||||||
time_limit: float | None = None,
|
time_limit: float | None = None,
|
||||||
mode: Literal["send-receive", "receive"] = "send-receive",
|
mode: Literal["send-receive", "receive", "send"] = "send-receive",
|
||||||
modality: Literal["video", "audio"] = "video",
|
modality: Literal["video", "audio"] = "video",
|
||||||
):
|
):
|
||||||
"""
|
"""
|
||||||
@@ -549,17 +617,11 @@ class WebRTC(Component):
|
|||||||
"""
|
"""
|
||||||
return value
|
return value
|
||||||
|
|
||||||
def set_output(self, webrtc_id: str, *args):
|
def set_input(self, webrtc_id: str, *args):
|
||||||
if webrtc_id in self.connections:
|
if webrtc_id in self.connections:
|
||||||
if self.mode == "send-receive":
|
self.connections[webrtc_id].set_args(list(args))
|
||||||
self.connections[webrtc_id].latest_args = ["__webrtc_value__"] + list(
|
|
||||||
args
|
|
||||||
)
|
|
||||||
elif self.mode == "receive":
|
|
||||||
self.connections[webrtc_id].latest_args = list(args)
|
|
||||||
self.connections[webrtc_id].args_set.set() # type: ignore
|
|
||||||
|
|
||||||
def change(
|
def on_additional_outputs(
|
||||||
self,
|
self,
|
||||||
fn: Callable[Concatenate[P], R],
|
fn: Callable[Concatenate[P], R],
|
||||||
inputs: Block | Sequence[Block] | set[Block] | None = None,
|
inputs: Block | Sequence[Block] | set[Block] | None = None,
|
||||||
@@ -628,7 +690,7 @@ class WebRTC(Component):
|
|||||||
"In the send-receive mode for audio, the event handler must be an instance of StreamHandler."
|
"In the send-receive mode for audio, the event handler must be an instance of StreamHandler."
|
||||||
)
|
)
|
||||||
|
|
||||||
if self.mode == "send-receive":
|
if self.mode == "send-receive" or self.mode == "send":
|
||||||
if cast(list[Block], inputs)[0] != self:
|
if cast(list[Block], inputs)[0] != self:
|
||||||
raise ValueError(
|
raise ValueError(
|
||||||
"In the webrtc stream event, the first input component must be the WebRTC component."
|
"In the webrtc stream event, the first input component must be the WebRTC component."
|
||||||
@@ -642,7 +704,7 @@ class WebRTC(Component):
|
|||||||
"In the webrtc stream event, the only output component must be the WebRTC component."
|
"In the webrtc stream event, the only output component must be the WebRTC component."
|
||||||
)
|
)
|
||||||
return self.tick( # type: ignore
|
return self.tick( # type: ignore
|
||||||
self.set_output,
|
self.set_input,
|
||||||
inputs=inputs,
|
inputs=inputs,
|
||||||
outputs=None,
|
outputs=None,
|
||||||
concurrency_id=concurrency_id,
|
concurrency_id=concurrency_id,
|
||||||
@@ -669,7 +731,7 @@ class WebRTC(Component):
|
|||||||
)
|
)
|
||||||
trigger(lambda: "start_webrtc_stream", inputs=None, outputs=self)
|
trigger(lambda: "start_webrtc_stream", inputs=None, outputs=self)
|
||||||
self.tick( # type: ignore
|
self.tick( # type: ignore
|
||||||
self.set_output,
|
self.set_input,
|
||||||
inputs=[self] + list(inputs),
|
inputs=[self] + list(inputs),
|
||||||
outputs=None,
|
outputs=None,
|
||||||
concurrency_id=concurrency_id,
|
concurrency_id=concurrency_id,
|
||||||
@@ -680,6 +742,12 @@ class WebRTC(Component):
|
|||||||
await asyncio.sleep(time_limit)
|
await asyncio.sleep(time_limit)
|
||||||
await pc.close()
|
await pc.close()
|
||||||
|
|
||||||
|
def clean_up(self, webrtc_id: str):
|
||||||
|
connection = self.connections.pop(webrtc_id, None)
|
||||||
|
self.additional_outputs.pop(webrtc_id, None)
|
||||||
|
self.data_channels.pop(webrtc_id, None)
|
||||||
|
return connection
|
||||||
|
|
||||||
@server
|
@server
|
||||||
async def offer(self, body):
|
async def offer(self, body):
|
||||||
logger.debug("Starting to handle offer")
|
logger.debug("Starting to handle offer")
|
||||||
@@ -707,7 +775,7 @@ class WebRTC(Component):
|
|||||||
logger.debug("pc.connectionState %s", pc.connectionState)
|
logger.debug("pc.connectionState %s", pc.connectionState)
|
||||||
if pc.connectionState in ["failed", "closed"]:
|
if pc.connectionState in ["failed", "closed"]:
|
||||||
await pc.close()
|
await pc.close()
|
||||||
connection = self.connections.pop(body["webrtc_id"], None)
|
connection = self.clean_up(body["webrtc_id"])
|
||||||
if connection:
|
if connection:
|
||||||
connection.stop()
|
connection.stop()
|
||||||
self.pcs.discard(pc)
|
self.pcs.discard(pc)
|
||||||
@@ -723,20 +791,26 @@ class WebRTC(Component):
|
|||||||
relay.subscribe(track),
|
relay.subscribe(track),
|
||||||
event_handler=cast(Callable, self.event_handler),
|
event_handler=cast(Callable, self.event_handler),
|
||||||
set_additional_outputs=set_outputs,
|
set_additional_outputs=set_outputs,
|
||||||
|
mode=cast(Literal["send", "send-receive"], self.mode),
|
||||||
)
|
)
|
||||||
elif self.modality == "audio":
|
elif self.modality == "audio":
|
||||||
|
handler = cast(StreamHandler, self.event_handler).copy()
|
||||||
|
handler._loop = asyncio.get_running_loop()
|
||||||
cb = AudioCallback(
|
cb = AudioCallback(
|
||||||
relay.subscribe(track),
|
relay.subscribe(track),
|
||||||
event_handler=cast(StreamHandler, self.event_handler).copy(),
|
event_handler=handler,
|
||||||
set_additional_outputs=set_outputs,
|
set_additional_outputs=set_outputs,
|
||||||
)
|
)
|
||||||
self.connections[body["webrtc_id"]] = cb
|
self.connections[body["webrtc_id"]] = cb
|
||||||
if body["webrtc_id"] in self.data_channels:
|
if body["webrtc_id"] in self.data_channels:
|
||||||
self.connections[body["webrtc_id"]].channel = self.data_channels[
|
self.connections[body["webrtc_id"]].set_channel(
|
||||||
body["webrtc_id"]
|
self.data_channels[body["webrtc_id"]]
|
||||||
]
|
)
|
||||||
logger.debug("Adding track to peer connection %s", cb)
|
if self.mode == "send-receive":
|
||||||
pc.addTrack(cb)
|
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.mode == "receive":
|
||||||
if self.modality == "video":
|
if self.modality == "video":
|
||||||
@@ -753,21 +827,19 @@ class WebRTC(Component):
|
|||||||
logger.debug("Adding track to peer connection %s", cb)
|
logger.debug("Adding track to peer connection %s", cb)
|
||||||
pc.addTrack(cb)
|
pc.addTrack(cb)
|
||||||
self.connections[body["webrtc_id"]] = cb
|
self.connections[body["webrtc_id"]] = cb
|
||||||
cb.on("ended", lambda: self.connections.pop(body["webrtc_id"], None))
|
cb.on("ended", lambda: self.clean_up(body["webrtc_id"]))
|
||||||
|
|
||||||
@pc.on("datachannel")
|
@pc.on("datachannel")
|
||||||
def on_datachannel(channel):
|
def on_datachannel(channel):
|
||||||
print("data channel established")
|
|
||||||
logger.debug(f"Data channel established: {channel.label}")
|
logger.debug(f"Data channel established: {channel.label}")
|
||||||
|
|
||||||
self.data_channels[body["webrtc_id"]] = channel
|
self.data_channels[body["webrtc_id"]] = channel
|
||||||
|
|
||||||
async def set_channel(webrtc_id: str):
|
async def set_channel(webrtc_id: str):
|
||||||
print("webrtc_id", webrtc_id)
|
|
||||||
while not self.connections.get(webrtc_id):
|
while not self.connections.get(webrtc_id):
|
||||||
await asyncio.sleep(0.05)
|
await asyncio.sleep(0.05)
|
||||||
print("setting channel")
|
logger.debug("setting channel for webrtc id %s", webrtc_id)
|
||||||
self.connections[webrtc_id].channel = channel
|
self.connections[webrtc_id].set_channel(channel)
|
||||||
|
|
||||||
asyncio.create_task(set_channel(body["webrtc_id"]))
|
asyncio.create_task(set_channel(body["webrtc_id"]))
|
||||||
|
|
||||||
|
|||||||
105
demo/also_return_text.py
Normal file
105
demo/also_return_text.py
Normal file
@@ -0,0 +1,105 @@
|
|||||||
|
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(
|
||||||
|
"""
|
||||||
|
<h1 style='text-align: center'>
|
||||||
|
Audio Streaming (Powered by WebRTC ⚡️)
|
||||||
|
</h1>
|
||||||
|
"""
|
||||||
|
)
|
||||||
|
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"
|
||||||
|
]
|
||||||
|
)
|
||||||
138
demo/app.py
138
demo/app.py
@@ -1,27 +1,92 @@
|
|||||||
|
|
||||||
import os
|
import os
|
||||||
|
|
||||||
import gradio as gr
|
import gradio as gr
|
||||||
|
|
||||||
_docs = {'WebRTC':
|
_docs = {
|
||||||
{'description': 'Stream audio/video with WebRTC',
|
"WebRTC": {
|
||||||
'members': {'__init__':
|
"description": "Stream audio/video with WebRTC",
|
||||||
{
|
"members": {
|
||||||
'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."},
|
"__init__": {
|
||||||
'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.'},
|
"rtc_configuration": {
|
||||||
'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.'},
|
"type": "dict[str, Any] | None",
|
||||||
'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.'},
|
"default": "None",
|
||||||
'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.'},
|
"description": "The configration dictionary to pass to the RTCPeerConnection constructor. If None, the default configuration is used.",
|
||||||
'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.'},
|
"height": {
|
||||||
'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.'},
|
"type": "int | str | None",
|
||||||
'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.'},
|
"default": "None",
|
||||||
'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.'},
|
"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.",
|
||||||
'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.'},
|
"width": {
|
||||||
'mirror_webcam': {'type': 'bool', 'default': 'True', 'description': 'if True webcam will be mirrored. Default is True.'},
|
"type": "int | str | None",
|
||||||
},
|
"default": "None",
|
||||||
'events': {'tick': {'type': None, 'default': None, 'description': ''}}}, '__meta__': {'additional_interfaces': {}, 'user_fn_refs': {'WebRTC': []}}}
|
"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": []}},
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -37,16 +102,19 @@ with gr.Blocks(
|
|||||||
),
|
),
|
||||||
) as demo:
|
) as demo:
|
||||||
gr.Markdown(
|
gr.Markdown(
|
||||||
"""
|
"""
|
||||||
<h1 style='text-align: center; margin-bottom: 1rem'> Gradio WebRTC ⚡️ </h1>
|
<h1 style='text-align: center; margin-bottom: 1rem'> Gradio WebRTC ⚡️ </h1>
|
||||||
|
|
||||||
<div style="display: flex; flex-direction: row; justify-content: center">
|
<div style="display: flex; flex-direction: row; justify-content: center">
|
||||||
<img style="display: block; padding-right: 5px; height: 20px;" alt="Static Badge" src="https://img.shields.io/badge/version%20-%200.0.6%20-%20orange">
|
<img style="display: block; padding-right: 5px; height: 20px;" alt="Static Badge" src="https://img.shields.io/badge/version%20-%200.0.6%20-%20orange">
|
||||||
<a href="https://github.com/freddyaboulton/gradio-webrtc" target="_blank"><img alt="Static Badge" src="https://img.shields.io/badge/github-white?logo=github&logoColor=black"></a>
|
<a href="https://github.com/freddyaboulton/gradio-webrtc" target="_blank"><img alt="Static Badge" src="https://img.shields.io/badge/github-white?logo=github&logoColor=black"></a>
|
||||||
</div>
|
</div>
|
||||||
""", elem_classes=["md-custom"], header_links=True)
|
""",
|
||||||
|
elem_classes=["md-custom"],
|
||||||
|
header_links=True,
|
||||||
|
)
|
||||||
gr.Markdown(
|
gr.Markdown(
|
||||||
"""
|
"""
|
||||||
## Installation
|
## Installation
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
@@ -242,17 +310,24 @@ with gr.Blocks() as demo:
|
|||||||
rtc = WebRTC(rtc_configuration=rtc_configuration, ...)
|
rtc = WebRTC(rtc_configuration=rtc_configuration, ...)
|
||||||
...
|
...
|
||||||
```
|
```
|
||||||
""", elem_classes=["md-custom"], header_links=True)
|
""",
|
||||||
|
elem_classes=["md-custom"],
|
||||||
|
header_links=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
gr.Markdown(
|
||||||
gr.Markdown("""
|
"""
|
||||||
##
|
##
|
||||||
""", elem_classes=["md-custom"], header_links=True)
|
""",
|
||||||
|
elem_classes=["md-custom"],
|
||||||
|
header_links=True,
|
||||||
|
)
|
||||||
|
|
||||||
gr.ParamViewer(value=_docs["WebRTC"]["members"]["__init__"], linkify=[])
|
gr.ParamViewer(value=_docs["WebRTC"]["members"]["__init__"], linkify=[])
|
||||||
|
|
||||||
|
demo.load(
|
||||||
demo.load(None, js=r"""function() {
|
None,
|
||||||
|
js=r"""function() {
|
||||||
const refs = {};
|
const refs = {};
|
||||||
const user_fn_refs = {
|
const user_fn_refs = {
|
||||||
WebRTC: [], };
|
WebRTC: [], };
|
||||||
@@ -286,6 +361,7 @@ with gr.Blocks() as demo:
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
""")
|
""",
|
||||||
|
)
|
||||||
|
|
||||||
demo.launch()
|
demo.launch()
|
||||||
|
|||||||
367
demo/app_.py
Normal file
367
demo/app_.py
Normal file
@@ -0,0 +1,367 @@
|
|||||||
|
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(
|
||||||
|
"""
|
||||||
|
<h1 style='text-align: center; margin-bottom: 1rem'> Gradio WebRTC ⚡️ </h1>
|
||||||
|
|
||||||
|
<div style="display: flex; flex-direction: row; justify-content: center">
|
||||||
|
<img style="display: block; padding-right: 5px; height: 20px;" alt="Static Badge" src="https://img.shields.io/badge/version%20-%200.0.6%20-%20orange">
|
||||||
|
<a href="https://github.com/freddyaboulton/gradio-webrtc" target="_blank"><img alt="Static Badge" src="https://img.shields.io/badge/github-white?logo=github&logoColor=black"></a>
|
||||||
|
</div>
|
||||||
|
""",
|
||||||
|
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"),
|
||||||
|
`<a href="#h-${ref.toLowerCase()}">${ref}</a>`
|
||||||
|
);
|
||||||
|
})
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
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"),
|
||||||
|
`<a href="#h-${ref.toLowerCase()}">${ref}</a>`
|
||||||
|
);
|
||||||
|
})
|
||||||
|
}
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
""",
|
||||||
|
)
|
||||||
|
|
||||||
|
demo.launch()
|
||||||
@@ -21,8 +21,6 @@ if account_sid and auth_token:
|
|||||||
else:
|
else:
|
||||||
rtc_configuration = None
|
rtc_configuration = None
|
||||||
|
|
||||||
import time
|
|
||||||
|
|
||||||
|
|
||||||
def generation(num_steps):
|
def generation(num_steps):
|
||||||
for _ in range(num_steps):
|
for _ in range(num_steps):
|
||||||
@@ -34,6 +32,7 @@ def generation(num_steps):
|
|||||||
np.array(segment.get_array_of_samples()).reshape(1, -1),
|
np.array(segment.get_array_of_samples()).reshape(1, -1),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
css = """.my-group {max-width: 600px !important; max-height: 600 !important;}
|
css = """.my-group {max-width: 600px !important; max-height: 600 !important;}
|
||||||
.my-column {display: flex !important; justify-content: center !important; align-items: center !important};"""
|
.my-column {display: flex !important; justify-content: center !important; align-items: center !important};"""
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import os
|
import os
|
||||||
|
import time
|
||||||
|
|
||||||
import gradio as gr
|
import gradio as gr
|
||||||
import numpy as np
|
import numpy as np
|
||||||
@@ -21,8 +22,6 @@ if account_sid and auth_token:
|
|||||||
else:
|
else:
|
||||||
rtc_configuration = None
|
rtc_configuration = None
|
||||||
|
|
||||||
import time
|
|
||||||
|
|
||||||
|
|
||||||
def generation(num_steps):
|
def generation(num_steps):
|
||||||
for _ in range(num_steps):
|
for _ in range(num_steps):
|
||||||
|
|||||||
99
demo/docs.py
Normal file
99
demo/docs.py
Normal file
@@ -0,0 +1,99 @@
|
|||||||
|
_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.",
|
||||||
|
},
|
||||||
|
"postprocess": {
|
||||||
|
"value": {
|
||||||
|
"type": "typing.Any",
|
||||||
|
"description": "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.",
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"preprocess": {
|
||||||
|
"return": {
|
||||||
|
"type": "str",
|
||||||
|
"description": "Passes the uploaded video as a `str` filepath or URL whose extension can be modified by `format`.",
|
||||||
|
},
|
||||||
|
"value": None,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
"events": {"tick": {"type": None, "default": None, "description": ""}},
|
||||||
|
},
|
||||||
|
"__meta__": {"additional_interfaces": {}, "user_fn_refs": {"WebRTC": []}},
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,4 +1,9 @@
|
|||||||
import logging
|
import logging
|
||||||
|
from queue import Queue
|
||||||
|
|
||||||
|
import gradio as gr
|
||||||
|
import numpy as np
|
||||||
|
from gradio_webrtc import StreamHandler, WebRTC
|
||||||
|
|
||||||
# Configure the root logger to WARNING to suppress debug messages from other libraries
|
# Configure the root logger to WARNING to suppress debug messages from other libraries
|
||||||
logging.basicConfig(level=logging.WARNING)
|
logging.basicConfig(level=logging.WARNING)
|
||||||
@@ -17,14 +22,6 @@ logger.setLevel(logging.DEBUG)
|
|||||||
logger.addHandler(console_handler)
|
logger.addHandler(console_handler)
|
||||||
|
|
||||||
|
|
||||||
import time
|
|
||||||
from queue import Queue
|
|
||||||
|
|
||||||
import gradio as gr
|
|
||||||
import numpy as np
|
|
||||||
from gradio_webrtc import StreamHandler, WebRTC
|
|
||||||
|
|
||||||
|
|
||||||
class EchoHandler(StreamHandler):
|
class EchoHandler(StreamHandler):
|
||||||
def __init__(self) -> None:
|
def __init__(self) -> None:
|
||||||
super().__init__()
|
super().__init__()
|
||||||
@@ -35,7 +32,7 @@ class EchoHandler(StreamHandler):
|
|||||||
|
|
||||||
def emit(self) -> None:
|
def emit(self) -> None:
|
||||||
return self.queue.get()
|
return self.queue.get()
|
||||||
|
|
||||||
def copy(self) -> StreamHandler:
|
def copy(self) -> StreamHandler:
|
||||||
return EchoHandler()
|
return EchoHandler()
|
||||||
|
|
||||||
|
|||||||
74
demo/old_app.py
Normal file
74
demo/old_app.py
Normal file
@@ -0,0 +1,74 @@
|
|||||||
|
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(frame, conf_threshold=0.3):
|
||||||
|
frame = cv2.flip(frame, 0)
|
||||||
|
return cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
|
||||||
|
|
||||||
|
|
||||||
|
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(
|
||||||
|
"""
|
||||||
|
<h1 style='text-align: center'>
|
||||||
|
YOLOv10 Webcam Stream (Powered by WebRTC ⚡️)
|
||||||
|
</h1>
|
||||||
|
"""
|
||||||
|
)
|
||||||
|
gr.HTML(
|
||||||
|
"""
|
||||||
|
<h3 style='text-align: center'>
|
||||||
|
<a href='https://arxiv.org/abs/2405.14458' target='_blank'>arXiv</a> | <a href='https://github.com/THU-MIG/yolov10' target='_blank'>github</a>
|
||||||
|
</h3>
|
||||||
|
"""
|
||||||
|
)
|
||||||
|
with gr.Column(elem_classes=["my-column"]):
|
||||||
|
with gr.Group(elem_classes=["my-group"]):
|
||||||
|
image = WebRTC(label="Stream", rtc_configuration=rtc_configuration)
|
||||||
|
conf_threshold = gr.Slider(
|
||||||
|
label="Confidence Threshold",
|
||||||
|
minimum=0.0,
|
||||||
|
maximum=1.0,
|
||||||
|
step=0.05,
|
||||||
|
value=0.30,
|
||||||
|
)
|
||||||
|
number = gr.Number()
|
||||||
|
|
||||||
|
image.stream(
|
||||||
|
fn=detection, inputs=[image, conf_threshold], outputs=[image], time_limit=10
|
||||||
|
)
|
||||||
|
image.on_additional_outputs(lambda n: n, outputs=[number])
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
demo.launch()
|
||||||
67
demo/stream_whisper.py
Normal file
67
demo/stream_whisper.py
Normal file
@@ -0,0 +1,67 @@
|
|||||||
|
import logging
|
||||||
|
import tempfile
|
||||||
|
|
||||||
|
import gradio as gr
|
||||||
|
import numpy as np
|
||||||
|
from dotenv import load_dotenv
|
||||||
|
from gradio_webrtc import AdditionalOutputs, ReplyOnPause, WebRTC
|
||||||
|
from openai import OpenAI
|
||||||
|
from pydub import AudioSegment
|
||||||
|
|
||||||
|
load_dotenv()
|
||||||
|
|
||||||
|
|
||||||
|
# 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.StreamHandler()
|
||||||
|
console_handler.setLevel(logging.DEBUG)
|
||||||
|
|
||||||
|
# Create a formatter
|
||||||
|
formatter = logging.Formatter("%(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)
|
||||||
|
|
||||||
|
|
||||||
|
client = OpenAI()
|
||||||
|
|
||||||
|
|
||||||
|
def transcribe(audio: tuple[int, np.ndarray], transcript: list[dict]):
|
||||||
|
segment = AudioSegment(
|
||||||
|
audio[1].tobytes(),
|
||||||
|
frame_rate=audio[0],
|
||||||
|
sample_width=audio[1].dtype.itemsize,
|
||||||
|
channels=1,
|
||||||
|
)
|
||||||
|
|
||||||
|
with tempfile.NamedTemporaryFile(suffix=".mp3") as temp_audio:
|
||||||
|
segment.export(temp_audio.name, format="mp3")
|
||||||
|
next_chunk = client.audio.transcriptions.create(
|
||||||
|
model="whisper-1", file=open(temp_audio.name, "rb")
|
||||||
|
).text
|
||||||
|
transcript.append({"role": "user", "content": next_chunk})
|
||||||
|
yield AdditionalOutputs(transcript)
|
||||||
|
|
||||||
|
|
||||||
|
with gr.Blocks() as demo:
|
||||||
|
with gr.Row():
|
||||||
|
with gr.Column():
|
||||||
|
audio = WebRTC(
|
||||||
|
label="Stream",
|
||||||
|
mode="send",
|
||||||
|
modality="audio",
|
||||||
|
)
|
||||||
|
with gr.Column():
|
||||||
|
transcript = gr.Chatbot(label="transcript", type="messages")
|
||||||
|
|
||||||
|
audio.stream(ReplyOnPause(transcribe), inputs=[audio, transcript], outputs=[audio],
|
||||||
|
time_limit=30)
|
||||||
|
audio.on_additional_outputs(lambda s: s, outputs=transcript)
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
demo.launch()
|
||||||
97
demo/video_send_output.py
Normal file
97
demo/video_send_output.py
Normal file
@@ -0,0 +1,97 @@
|
|||||||
|
import logging
|
||||||
|
import os
|
||||||
|
import random
|
||||||
|
|
||||||
|
import cv2
|
||||||
|
import gradio as gr
|
||||||
|
from gradio_webrtc import AdditionalOutputs, WebRTC
|
||||||
|
from huggingface_hub import hf_hub_download
|
||||||
|
from inference import YOLOv10
|
||||||
|
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)
|
||||||
|
|
||||||
|
|
||||||
|
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(frame, conf_threshold=0.3):
|
||||||
|
frame = cv2.flip(frame, 0)
|
||||||
|
global count
|
||||||
|
if random.random() > 0.98:
|
||||||
|
return AdditionalOutputs(count)
|
||||||
|
count += 1
|
||||||
|
|
||||||
|
|
||||||
|
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(
|
||||||
|
"""
|
||||||
|
<h1 style='text-align: center'>
|
||||||
|
YOLOv10 Webcam Stream (Powered by WebRTC ⚡️)
|
||||||
|
</h1>
|
||||||
|
"""
|
||||||
|
)
|
||||||
|
gr.HTML(
|
||||||
|
"""
|
||||||
|
<h3 style='text-align: center'>
|
||||||
|
<a href='https://arxiv.org/abs/2405.14458' target='_blank'>arXiv</a> | <a href='https://github.com/THU-MIG/yolov10' target='_blank'>github</a>
|
||||||
|
</h3>
|
||||||
|
"""
|
||||||
|
)
|
||||||
|
with gr.Column(elem_classes=["my-column"]):
|
||||||
|
with gr.Group(elem_classes=["my-group"]):
|
||||||
|
image = WebRTC(
|
||||||
|
label="Stream", rtc_configuration=rtc_configuration, mode="send"
|
||||||
|
)
|
||||||
|
conf_threshold = gr.Slider(
|
||||||
|
label="Confidence Threshold",
|
||||||
|
minimum=0.0,
|
||||||
|
maximum=1.0,
|
||||||
|
step=0.05,
|
||||||
|
value=0.30,
|
||||||
|
)
|
||||||
|
number = gr.Number()
|
||||||
|
|
||||||
|
image.stream(
|
||||||
|
fn=detection, inputs=[image, conf_threshold], outputs=[image], time_limit=10
|
||||||
|
)
|
||||||
|
image.change(lambda n: n, outputs=[number])
|
||||||
|
|
||||||
|
demo.launch()
|
||||||
@@ -31,11 +31,11 @@
|
|||||||
export let rtc_configuration: Object;
|
export let rtc_configuration: Object;
|
||||||
export let time_limit: number | null = null;
|
export let time_limit: number | null = null;
|
||||||
export let modality: "video" | "audio" = "video";
|
export let modality: "video" | "audio" = "video";
|
||||||
export let mode: "send-receive" | "receive" = "send-receive";
|
export let mode: "send-receive" | "receive" | "send" = "send-receive";
|
||||||
export let track_constraints: MediaTrackConstraints = {};
|
export let track_constraints: MediaTrackConstraints = {};
|
||||||
|
|
||||||
const on_change_cb = () => {
|
const on_change_cb = (msg: "change" | "tick") => {
|
||||||
gradio.dispatch("state_change");
|
gradio.dispatch(msg === "change" ? "state_change" : "tick");
|
||||||
}
|
}
|
||||||
|
|
||||||
let dragging = false;
|
let dragging = false;
|
||||||
@@ -87,7 +87,7 @@
|
|||||||
on:tick={() => gradio.dispatch("tick")}
|
on:tick={() => gradio.dispatch("tick")}
|
||||||
on:error={({ detail }) => gradio.dispatch("error", detail)}
|
on:error={({ detail }) => gradio.dispatch("error", detail)}
|
||||||
/>
|
/>
|
||||||
{:else if mode === "send-receive" && modality === "video"}
|
{:else if (mode === "send-receive" || mode == "send") && modality === "video"}
|
||||||
<Video
|
<Video
|
||||||
bind:value={value}
|
bind:value={value}
|
||||||
{label}
|
{label}
|
||||||
@@ -97,6 +97,7 @@
|
|||||||
{server}
|
{server}
|
||||||
{rtc_configuration}
|
{rtc_configuration}
|
||||||
{time_limit}
|
{time_limit}
|
||||||
|
{mode}
|
||||||
{on_change_cb}
|
{on_change_cb}
|
||||||
on:clear={() => gradio.dispatch("clear")}
|
on:clear={() => gradio.dispatch("clear")}
|
||||||
on:play={() => gradio.dispatch("play")}
|
on:play={() => gradio.dispatch("play")}
|
||||||
@@ -113,7 +114,7 @@
|
|||||||
>
|
>
|
||||||
<UploadText i18n={gradio.i18n} type="video" />
|
<UploadText i18n={gradio.i18n} type="video" />
|
||||||
</Video>
|
</Video>
|
||||||
{:else if mode === "send-receive" && modality === "audio"}
|
{:else if (mode === "send-receive" || mode === "send") && modality === "audio"}
|
||||||
<InteractiveAudio
|
<InteractiveAudio
|
||||||
bind:value={value}
|
bind:value={value}
|
||||||
{on_change_cb}
|
{on_change_cb}
|
||||||
@@ -123,6 +124,7 @@
|
|||||||
{rtc_configuration}
|
{rtc_configuration}
|
||||||
{time_limit}
|
{time_limit}
|
||||||
{track_constraints}
|
{track_constraints}
|
||||||
|
{mode}
|
||||||
i18n={gradio.i18n}
|
i18n={gradio.i18n}
|
||||||
on:tick={() => gradio.dispatch("tick")}
|
on:tick={() => gradio.dispatch("tick")}
|
||||||
on:error={({ detail }) => gradio.dispatch("error", detail)}
|
on:error={({ detail }) => gradio.dispatch("error", detail)}
|
||||||
|
|||||||
@@ -6,4 +6,4 @@ export default {
|
|||||||
build: {
|
build: {
|
||||||
target: "modules",
|
target: "modules",
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|||||||
18
frontend/package-lock.json
generated
18
frontend/package-lock.json
generated
@@ -24,7 +24,8 @@
|
|||||||
"mrmime": "^2.0.0"
|
"mrmime": "^2.0.0"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@gradio/preview": "0.12.0"
|
"@gradio/preview": "0.12.0",
|
||||||
|
"prettier": "3.3.3"
|
||||||
},
|
},
|
||||||
"peerDependencies": {
|
"peerDependencies": {
|
||||||
"svelte": "^4.0.0"
|
"svelte": "^4.0.0"
|
||||||
@@ -4112,6 +4113,21 @@
|
|||||||
"node": "^10 || ^12 || >=14"
|
"node": "^10 || ^12 || >=14"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/prettier": {
|
||||||
|
"version": "3.3.3",
|
||||||
|
"resolved": "https://registry.npmjs.org/prettier/-/prettier-3.3.3.tgz",
|
||||||
|
"integrity": "sha512-i2tDNA0O5IrMO757lfrdQZCc2jPNDVntV0m/+4whiDfWaTKfMNgR7Qz0NAeGz/nRqF4m5/6CLzbP4/liHt12Ew==",
|
||||||
|
"dev": true,
|
||||||
|
"bin": {
|
||||||
|
"prettier": "bin/prettier.cjs"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=14"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"url": "https://github.com/prettier/prettier?sponsor=1"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/prismjs": {
|
"node_modules/prismjs": {
|
||||||
"version": "1.29.0",
|
"version": "1.29.0",
|
||||||
"resolved": "https://registry.npmjs.org/prismjs/-/prismjs-1.29.0.tgz",
|
"resolved": "https://registry.npmjs.org/prismjs/-/prismjs-1.29.0.tgz",
|
||||||
|
|||||||
@@ -22,7 +22,8 @@
|
|||||||
"mrmime": "^2.0.0"
|
"mrmime": "^2.0.0"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@gradio/preview": "0.12.0"
|
"@gradio/preview": "0.12.0",
|
||||||
|
"prettier": "3.3.3"
|
||||||
},
|
},
|
||||||
"exports": {
|
"exports": {
|
||||||
"./package.json": "./package.json",
|
"./package.json": "./package.json",
|
||||||
|
|||||||
@@ -3,13 +3,12 @@
|
|||||||
|
|
||||||
export let numBars = 16;
|
export let numBars = 16;
|
||||||
export let stream_state: "open" | "closed" | "waiting" = "closed";
|
export let stream_state: "open" | "closed" | "waiting" = "closed";
|
||||||
export let audio_source: HTMLAudioElement;
|
export let audio_source_callback: () => MediaStream;
|
||||||
|
|
||||||
let audioContext: AudioContext;
|
let audioContext: AudioContext;
|
||||||
let analyser: AnalyserNode;
|
let analyser: AnalyserNode;
|
||||||
let dataArray: Uint8Array;
|
let dataArray: Uint8Array;
|
||||||
let animationId: number;
|
let animationId: number;
|
||||||
let is_muted = false;
|
|
||||||
|
|
||||||
$: containerWidth = `calc((var(--boxSize) + var(--gutter)) * ${numBars})`;
|
$: containerWidth = `calc((var(--boxSize) + var(--gutter)) * ${numBars})`;
|
||||||
|
|
||||||
@@ -27,7 +26,7 @@
|
|||||||
function setupAudioContext() {
|
function setupAudioContext() {
|
||||||
audioContext = new (window.AudioContext || window.webkitAudioContext)();
|
audioContext = new (window.AudioContext || window.webkitAudioContext)();
|
||||||
analyser = audioContext.createAnalyser();
|
analyser = audioContext.createAnalyser();
|
||||||
const source = audioContext.createMediaStreamSource(audio_source.srcObject);
|
const source = audioContext.createMediaStreamSource(audio_source_callback());
|
||||||
|
|
||||||
// Only connect to analyser, not to destination
|
// Only connect to analyser, not to destination
|
||||||
source.connect(analyser);
|
source.connect(analyser);
|
||||||
|
|||||||
@@ -5,19 +5,25 @@
|
|||||||
import type { I18nFormatter } from "@gradio/utils";
|
import type { I18nFormatter } from "@gradio/utils";
|
||||||
import { createEventDispatcher } from "svelte";
|
import { createEventDispatcher } from "svelte";
|
||||||
import { onMount } from "svelte";
|
import { onMount } from "svelte";
|
||||||
|
import { fade } from "svelte/transition";
|
||||||
import { StreamingBar } from "@gradio/statustracker";
|
import { StreamingBar } from "@gradio/statustracker";
|
||||||
import {
|
import {
|
||||||
Circle,
|
Circle,
|
||||||
Square,
|
Square,
|
||||||
Spinner,
|
Spinner,
|
||||||
Music
|
Music,
|
||||||
|
DropdownArrow,
|
||||||
|
Microphone
|
||||||
} from "@gradio/icons";
|
} from "@gradio/icons";
|
||||||
|
|
||||||
import { start, stop } from "./webrtc_utils";
|
import { start, stop } from "./webrtc_utils";
|
||||||
|
import { get_devices, set_available_devices } from "./stream_utils";
|
||||||
import AudioWave from "./AudioWave.svelte";
|
import AudioWave from "./AudioWave.svelte";
|
||||||
|
import WebcamPermissions from "./WebcamPermissions.svelte";
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
export let mode: "send-receive" | "send";
|
||||||
export let value: string | null = null;
|
export let value: string | null = null;
|
||||||
export let label: string | undefined = undefined;
|
export let label: string | undefined = undefined;
|
||||||
export let show_label = true;
|
export let show_label = true;
|
||||||
@@ -25,7 +31,9 @@
|
|||||||
export let i18n: I18nFormatter;
|
export let i18n: I18nFormatter;
|
||||||
export let time_limit: number | null = null;
|
export let time_limit: number | null = null;
|
||||||
export let track_constraints: MediaTrackConstraints = {};
|
export let track_constraints: MediaTrackConstraints = {};
|
||||||
export let on_change_cb: () => void;
|
export let on_change_cb: (mg: "tick" | "change") => void;
|
||||||
|
|
||||||
|
let options_open = false;
|
||||||
|
|
||||||
let _time_limit: number | null = null;
|
let _time_limit: number | null = null;
|
||||||
|
|
||||||
@@ -37,6 +45,16 @@
|
|||||||
let audio_player: HTMLAudioElement;
|
let audio_player: HTMLAudioElement;
|
||||||
let pc: RTCPeerConnection;
|
let pc: RTCPeerConnection;
|
||||||
let _webrtc_id = null;
|
let _webrtc_id = null;
|
||||||
|
let stream: MediaStream;
|
||||||
|
let available_audio_devices: MediaDeviceInfo[];
|
||||||
|
let selected_device: MediaDeviceInfo | null = null;
|
||||||
|
let mic_accessed = false;
|
||||||
|
|
||||||
|
const audio_source_callback = () => {
|
||||||
|
console.log("stream in callback", stream);
|
||||||
|
if(mode==="send") return stream;
|
||||||
|
else return audio_player.srcObject as MediaStream
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
const dispatch = createEventDispatcher<{
|
const dispatch = createEventDispatcher<{
|
||||||
@@ -48,22 +66,41 @@
|
|||||||
}>();
|
}>();
|
||||||
|
|
||||||
|
|
||||||
|
async function access_mic(): Promise<void> {
|
||||||
|
|
||||||
onMount(() => {
|
try {
|
||||||
window.setInterval(() => {
|
const constraints = selected_device ? { deviceId: { exact: selected_device.deviceId }, ...track_constraints } : track_constraints;
|
||||||
if (stream_state == "open") {
|
const stream_ = await navigator.mediaDevices.getUserMedia({ audio: constraints });
|
||||||
dispatch("tick");
|
stream = stream_;
|
||||||
|
} catch (err) {
|
||||||
|
if (!navigator.mediaDevices) {
|
||||||
|
dispatch("error", i18n("audio.no_device_support"));
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
}, 1000);
|
if (err instanceof DOMException && err.name == "NotAllowedError") {
|
||||||
|
dispatch("error", i18n("audio.allow_recording_access"));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
throw err;
|
||||||
}
|
}
|
||||||
)
|
available_audio_devices = set_available_devices(await get_devices(), "audioinput");
|
||||||
|
mic_accessed = true;
|
||||||
|
const used_devices = stream
|
||||||
|
.getTracks()
|
||||||
|
.map((track) => track.getSettings()?.deviceId)[0];
|
||||||
|
|
||||||
|
selected_device = used_devices
|
||||||
|
? available_audio_devices.find((device) => device.deviceId === used_devices) ||
|
||||||
|
available_audio_devices[0]
|
||||||
|
: available_audio_devices[0];
|
||||||
|
}
|
||||||
|
|
||||||
async function start_stream(): Promise<void> {
|
async function start_stream(): Promise<void> {
|
||||||
if( stream_state === "open"){
|
if( stream_state === "open"){
|
||||||
stop(pc);
|
stop(pc);
|
||||||
stream_state = "closed";
|
stream_state = "closed";
|
||||||
_time_limit = null;
|
_time_limit = null;
|
||||||
|
await access_mic();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
_webrtc_id = Math.random().toString(36).substring(2);
|
_webrtc_id = Math.random().toString(36).substring(2);
|
||||||
@@ -89,10 +126,10 @@
|
|||||||
}
|
}
|
||||||
)
|
)
|
||||||
stream_state = "waiting"
|
stream_state = "waiting"
|
||||||
let stream = null
|
stream = null
|
||||||
|
|
||||||
try {
|
try {
|
||||||
stream = await navigator.mediaDevices.getUserMedia({ audio: track_constraints });
|
await access_mic();
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
if (!navigator.mediaDevices) {
|
if (!navigator.mediaDevices) {
|
||||||
dispatch("error", i18n("audio.no_device_support"));
|
dispatch("error", i18n("audio.no_device_support"));
|
||||||
@@ -106,13 +143,51 @@
|
|||||||
}
|
}
|
||||||
if (stream == null) return;
|
if (stream == null) return;
|
||||||
|
|
||||||
start(stream, pc, audio_player, server.offer, _webrtc_id, "audio", on_change_cb).then((connection) => {
|
start(stream, pc, mode === "send" ? null: audio_player, server.offer, _webrtc_id, "audio", on_change_cb).then((connection) => {
|
||||||
pc = connection;
|
pc = connection;
|
||||||
}).catch(() => {
|
}).catch(() => {
|
||||||
console.info("catching")
|
console.info("catching")
|
||||||
dispatch("error", "Too many concurrent users. Come back later!");
|
dispatch("error", "Too many concurrent users. Come back later!");
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function handle_click_outside(event: MouseEvent): void {
|
||||||
|
event.preventDefault();
|
||||||
|
event.stopPropagation();
|
||||||
|
options_open = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
function click_outside(node: Node, cb: any): any {
|
||||||
|
const handle_click = (event: MouseEvent): void => {
|
||||||
|
if (
|
||||||
|
node &&
|
||||||
|
!node.contains(event.target as Node) &&
|
||||||
|
!event.defaultPrevented
|
||||||
|
) {
|
||||||
|
cb(event);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
document.addEventListener("click", handle_click, true);
|
||||||
|
|
||||||
|
return {
|
||||||
|
destroy() {
|
||||||
|
document.removeEventListener("click", handle_click, true);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const handle_device_change = async (event: InputEvent): Promise<void> => {
|
||||||
|
const target = event.target as HTMLInputElement;
|
||||||
|
const device_id = target.value;
|
||||||
|
|
||||||
|
stream = await navigator.mediaDevices.getUserMedia({ audio: {deviceId: { exact: device_id }, ...track_constraints }});
|
||||||
|
selected_device =
|
||||||
|
available_audio_devices.find(
|
||||||
|
(device) => device.deviceId === device_id
|
||||||
|
) || null;
|
||||||
|
options_open = false;
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -133,37 +208,83 @@
|
|||||||
on:ended={() => dispatch("stop")}
|
on:ended={() => dispatch("stop")}
|
||||||
on:play={() => dispatch("play")}
|
on:play={() => dispatch("play")}
|
||||||
/>
|
/>
|
||||||
<AudioWave audio_source={audio_player} {stream_state}/>
|
{#if !mic_accessed}
|
||||||
<StreamingBar time_limit={_time_limit} />
|
<div
|
||||||
<div class="button-wrap">
|
in:fade={{ delay: 100, duration: 200 }}
|
||||||
<button
|
title="grant webcam access"
|
||||||
on:click={start_stream}
|
style="height: 100%"
|
||||||
aria-label={"start stream"}
|
|
||||||
>
|
>
|
||||||
{#if stream_state === "waiting"}
|
<WebcamPermissions icon={Microphone} on:click={async () => access_mic()} />
|
||||||
<div class="icon-with-text" style="width:var(--size-24);">
|
</div>
|
||||||
<div class="icon color-primary" title="spinner">
|
{:else}
|
||||||
<Spinner />
|
<AudioWave {audio_source_callback} {stream_state}/>
|
||||||
|
<StreamingBar time_limit={_time_limit} />
|
||||||
|
<div class="button-wrap">
|
||||||
|
<button
|
||||||
|
on:click={start_stream}
|
||||||
|
aria-label={"start stream"}
|
||||||
|
>
|
||||||
|
{#if stream_state === "waiting"}
|
||||||
|
<div class="icon-with-text" style="width:var(--size-24);">
|
||||||
|
<div class="icon color-primary" title="spinner">
|
||||||
|
<Spinner />
|
||||||
|
</div>
|
||||||
|
{i18n("audio.waiting")}
|
||||||
</div>
|
</div>
|
||||||
{i18n("audio.waiting")}
|
{:else if stream_state === "open"}
|
||||||
</div>
|
<div class="icon-with-text">
|
||||||
{:else if stream_state === "open"}
|
<div class="icon color-primary" title="stop recording">
|
||||||
<div class="icon-with-text">
|
<Square />
|
||||||
<div class="icon color-primary" title="stop recording">
|
</div>
|
||||||
<Square />
|
{i18n("audio.stop")}
|
||||||
</div>
|
</div>
|
||||||
{i18n("audio.stop")}
|
{:else}
|
||||||
</div>
|
<div class="icon-with-text">
|
||||||
{:else}
|
<div class="icon color-primary" title="start recording">
|
||||||
<div class="icon-with-text">
|
<Circle />
|
||||||
<div class="icon color-primary" title="start recording">
|
</div>
|
||||||
<Circle />
|
{i18n("audio.record")}
|
||||||
</div>
|
</div>
|
||||||
{i18n("audio.record")}
|
{/if}
|
||||||
</div>
|
</button>
|
||||||
|
{#if stream_state === "closed"}
|
||||||
|
<button
|
||||||
|
class="icon"
|
||||||
|
on:click={() => (options_open = true)}
|
||||||
|
aria-label="select input source"
|
||||||
|
>
|
||||||
|
<DropdownArrow />
|
||||||
|
</button>
|
||||||
{/if}
|
{/if}
|
||||||
</button>
|
{#if options_open && selected_device}
|
||||||
</div>
|
<select
|
||||||
|
class="select-wrap"
|
||||||
|
aria-label="select source"
|
||||||
|
use:click_outside={handle_click_outside}
|
||||||
|
on:change={handle_device_change}
|
||||||
|
>
|
||||||
|
<button
|
||||||
|
class="inset-icon"
|
||||||
|
on:click|stopPropagation={() => (options_open = false)}
|
||||||
|
>
|
||||||
|
<DropdownArrow />
|
||||||
|
</button>
|
||||||
|
{#if available_audio_devices.length === 0}
|
||||||
|
<option value="">{i18n("common.no_devices")}</option>
|
||||||
|
{:else}
|
||||||
|
{#each available_audio_devices as device}
|
||||||
|
<option
|
||||||
|
value={device.deviceId}
|
||||||
|
selected={selected_device.deviceId === device.deviceId}
|
||||||
|
>
|
||||||
|
{device.label}
|
||||||
|
</option>
|
||||||
|
{/each}
|
||||||
|
{/if}
|
||||||
|
</select>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<style>
|
<style>
|
||||||
@@ -239,4 +360,44 @@
|
|||||||
stroke: var(--primary-600);
|
stroke: var(--primary-600);
|
||||||
color: var(--primary-600);
|
color: var(--primary-600);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.select-wrap {
|
||||||
|
-webkit-appearance: none;
|
||||||
|
-moz-appearance: none;
|
||||||
|
appearance: none;
|
||||||
|
color: var(--button-secondary-text-color);
|
||||||
|
background-color: transparent;
|
||||||
|
width: 95%;
|
||||||
|
font-size: var(--text-md);
|
||||||
|
position: absolute;
|
||||||
|
bottom: var(--size-2);
|
||||||
|
background-color: var(--block-background-fill);
|
||||||
|
box-shadow: var(--shadow-drop-lg);
|
||||||
|
border-radius: var(--radius-xl);
|
||||||
|
z-index: var(--layer-top);
|
||||||
|
border: 1px solid var(--border-color-primary);
|
||||||
|
text-align: left;
|
||||||
|
line-height: var(--size-4);
|
||||||
|
white-space: nowrap;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
left: 50%;
|
||||||
|
transform: translate(-50%, 0);
|
||||||
|
max-width: var(--size-52);
|
||||||
|
}
|
||||||
|
|
||||||
|
.select-wrap > option {
|
||||||
|
padding: 0.25rem 0.5rem;
|
||||||
|
border-bottom: 1px solid var(--border-color-accent);
|
||||||
|
padding-right: var(--size-8);
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
|
||||||
|
.select-wrap > option:hover {
|
||||||
|
background-color: var(--color-accent);
|
||||||
|
}
|
||||||
|
|
||||||
|
.select-wrap > option:last-child {
|
||||||
|
border: none;
|
||||||
|
}
|
||||||
</style>
|
</style>
|
||||||
@@ -21,7 +21,8 @@
|
|||||||
};
|
};
|
||||||
export let rtc_configuration: Object;
|
export let rtc_configuration: Object;
|
||||||
export let track_constraints: MediaTrackConstraints = {};
|
export let track_constraints: MediaTrackConstraints = {};
|
||||||
export let on_change_cb: () => void;
|
export let mode: "send" | "send-receive";
|
||||||
|
export let on_change_cb: (msg: "change" | "tick") => void;
|
||||||
|
|
||||||
const dispatch = createEventDispatcher<{
|
const dispatch = createEventDispatcher<{
|
||||||
change: FileData | null;
|
change: FileData | null;
|
||||||
@@ -51,6 +52,7 @@
|
|||||||
{include_audio}
|
{include_audio}
|
||||||
{time_limit}
|
{time_limit}
|
||||||
{track_constraints}
|
{track_constraints}
|
||||||
|
{mode}
|
||||||
{on_change_cb}
|
{on_change_cb}
|
||||||
on:error
|
on:error
|
||||||
on:start_recording
|
on:start_recording
|
||||||
|
|||||||
@@ -17,7 +17,7 @@
|
|||||||
export let show_label = true;
|
export let show_label = true;
|
||||||
export let rtc_configuration: Object | null = null;
|
export let rtc_configuration: Object | null = null;
|
||||||
export let i18n: I18nFormatter;
|
export let i18n: I18nFormatter;
|
||||||
export let on_change_cb: () => void;
|
export let on_change_cb: (msg: "change" | "tick") => void;
|
||||||
|
|
||||||
export let server: {
|
export let server: {
|
||||||
offer: (body: any) => Promise<any>;
|
offer: (body: any) => Promise<any>;
|
||||||
@@ -103,7 +103,7 @@
|
|||||||
/>
|
/>
|
||||||
{#if value !== "__webrtc_value__"}
|
{#if value !== "__webrtc_value__"}
|
||||||
<div class="audio-container">
|
<div class="audio-container">
|
||||||
<AudioWave audio_source={audio_player} {stream_state}/>
|
<AudioWave audio_source_callback={() => audio_player.srcObject} {stream_state}/>
|
||||||
</div>
|
</div>
|
||||||
{/if}
|
{/if}
|
||||||
{#if value === "__webrtc_value__"}
|
{#if value === "__webrtc_value__"}
|
||||||
|
|||||||
@@ -13,7 +13,7 @@
|
|||||||
export let label: string | undefined = undefined;
|
export let label: string | undefined = undefined;
|
||||||
export let show_label = true;
|
export let show_label = true;
|
||||||
export let rtc_configuration: Object | null = null;
|
export let rtc_configuration: Object | null = null;
|
||||||
export let on_change_cb: () => void;
|
export let on_change_cb: (msg: "change" | "tick") => void;
|
||||||
export let server: {
|
export let server: {
|
||||||
offer: (body: any) => Promise<any>;
|
offer: (body: any) => Promise<any>;
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -24,9 +24,12 @@
|
|||||||
let _time_limit: number | null = null;
|
let _time_limit: number | null = null;
|
||||||
export let time_limit: number | null = null;
|
export let time_limit: number | null = null;
|
||||||
let stream_state: "open" | "waiting" | "closed" = "closed";
|
let stream_state: "open" | "waiting" | "closed" = "closed";
|
||||||
export let on_change_cb: () => void;
|
export let on_change_cb: (msg: "tick" | "change") => void;
|
||||||
|
export let mode: "send-receive" | "send";
|
||||||
const _webrtc_id = Math.random().toString(36).substring(2);
|
const _webrtc_id = Math.random().toString(36).substring(2);
|
||||||
|
|
||||||
|
console.log("mode", mode);
|
||||||
|
|
||||||
export const modify_stream: (state: "open" | "closed" | "waiting") => void = (
|
export const modify_stream: (state: "open" | "closed" | "waiting") => void = (
|
||||||
state: "open" | "closed" | "waiting"
|
state: "open" | "closed" | "waiting"
|
||||||
) => {
|
) => {
|
||||||
@@ -131,6 +134,7 @@
|
|||||||
case "disconnected":
|
case "disconnected":
|
||||||
stream_state = "closed";
|
stream_state = "closed";
|
||||||
_time_limit = null;
|
_time_limit = null;
|
||||||
|
stop(pc);
|
||||||
await access_webcam();
|
await access_webcam();
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
@@ -140,7 +144,7 @@
|
|||||||
)
|
)
|
||||||
stream_state = "waiting"
|
stream_state = "waiting"
|
||||||
webrtc_id = Math.random().toString(36).substring(2);
|
webrtc_id = Math.random().toString(36).substring(2);
|
||||||
start(stream, pc, video_source, server.offer, webrtc_id, "video", on_change_cb).then((connection) => {
|
start(stream, pc, mode === "send" ? null: video_source, server.offer, webrtc_id, "video", on_change_cb).then((connection) => {
|
||||||
pc = connection;
|
pc = connection;
|
||||||
}).catch(() => {
|
}).catch(() => {
|
||||||
console.info("catching")
|
console.info("catching")
|
||||||
|
|||||||
@@ -2,6 +2,9 @@
|
|||||||
import { Webcam } from "@gradio/icons";
|
import { Webcam } from "@gradio/icons";
|
||||||
import { createEventDispatcher } from "svelte";
|
import { createEventDispatcher } from "svelte";
|
||||||
|
|
||||||
|
export let icon = Webcam;
|
||||||
|
$: text = icon === Webcam ? "Click to Access Webcam" : "Click to Access Microphone";
|
||||||
|
|
||||||
const dispatch = createEventDispatcher<{
|
const dispatch = createEventDispatcher<{
|
||||||
click: undefined;
|
click: undefined;
|
||||||
}>();
|
}>();
|
||||||
@@ -10,9 +13,9 @@
|
|||||||
<button style:height="100%" on:click={() => dispatch("click")}>
|
<button style:height="100%" on:click={() => dispatch("click")}>
|
||||||
<div class="wrap">
|
<div class="wrap">
|
||||||
<span class="icon-wrap">
|
<span class="icon-wrap">
|
||||||
<Webcam />
|
<svelte:component this={icon} />
|
||||||
</span>
|
</span>
|
||||||
{"Click to Access Webcam"}
|
{text}
|
||||||
</div>
|
</div>
|
||||||
</button>
|
</button>
|
||||||
|
|
||||||
|
|||||||
@@ -1,50 +1,53 @@
|
|||||||
export function get_devices(): Promise<MediaDeviceInfo[]> {
|
export function get_devices(): Promise<MediaDeviceInfo[]> {
|
||||||
return navigator.mediaDevices.enumerateDevices();
|
return navigator.mediaDevices.enumerateDevices();
|
||||||
}
|
}
|
||||||
|
|
||||||
export function handle_error(error: string): void {
|
export function handle_error(error: string): void {
|
||||||
throw new Error(error);
|
throw new Error(error);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function set_local_stream(
|
export function set_local_stream(
|
||||||
local_stream: MediaStream | null,
|
local_stream: MediaStream | null,
|
||||||
video_source: HTMLVideoElement
|
video_source: HTMLVideoElement,
|
||||||
): void {
|
): void {
|
||||||
video_source.srcObject = local_stream;
|
video_source.srcObject = local_stream;
|
||||||
video_source.muted = true;
|
video_source.muted = true;
|
||||||
video_source.play();
|
video_source.play();
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function get_video_stream(
|
export async function get_video_stream(
|
||||||
include_audio: boolean,
|
include_audio: boolean,
|
||||||
video_source: HTMLVideoElement,
|
video_source: HTMLVideoElement,
|
||||||
device_id?: string,
|
device_id?: string,
|
||||||
track_constraints?: MediaTrackConstraints,
|
track_constraints?: MediaTrackConstraints,
|
||||||
): Promise<MediaStream> {
|
): Promise<MediaStream> {
|
||||||
const fallback_constraints = track_constraints || {
|
const fallback_constraints = track_constraints || {
|
||||||
width: { ideal: 500 },
|
width: { ideal: 500 },
|
||||||
height: { ideal: 500 }
|
height: { ideal: 500 },
|
||||||
};
|
};
|
||||||
|
|
||||||
const constraints = {
|
const constraints = {
|
||||||
video: device_id ? { deviceId: { exact: device_id }, ...fallback_constraints } : fallback_constraints,
|
video: device_id
|
||||||
audio: include_audio
|
? { deviceId: { exact: device_id }, ...fallback_constraints }
|
||||||
};
|
: fallback_constraints,
|
||||||
|
audio: include_audio,
|
||||||
|
};
|
||||||
|
|
||||||
return navigator.mediaDevices
|
return navigator.mediaDevices
|
||||||
.getUserMedia(constraints)
|
.getUserMedia(constraints)
|
||||||
.then((local_stream: MediaStream) => {
|
.then((local_stream: MediaStream) => {
|
||||||
set_local_stream(local_stream, video_source);
|
set_local_stream(local_stream, video_source);
|
||||||
return local_stream;
|
return local_stream;
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export function set_available_devices(
|
export function set_available_devices(
|
||||||
devices: MediaDeviceInfo[]
|
devices: MediaDeviceInfo[],
|
||||||
|
kind: "videoinput" | "audioinput" = "videoinput",
|
||||||
): MediaDeviceInfo[] {
|
): MediaDeviceInfo[] {
|
||||||
const cameras = devices.filter(
|
const cameras = devices.filter(
|
||||||
(device: MediaDeviceInfo) => device.kind === "videoinput"
|
(device: MediaDeviceInfo) => device.kind === kind,
|
||||||
);
|
);
|
||||||
|
|
||||||
return cameras;
|
return cameras;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,144 +3,144 @@ import { FFmpeg } from "@ffmpeg/ffmpeg";
|
|||||||
import { lookup } from "mrmime";
|
import { lookup } from "mrmime";
|
||||||
|
|
||||||
export const prettyBytes = (bytes: number): string => {
|
export const prettyBytes = (bytes: number): string => {
|
||||||
let units = ["B", "KB", "MB", "GB", "PB"];
|
let units = ["B", "KB", "MB", "GB", "PB"];
|
||||||
let i = 0;
|
let i = 0;
|
||||||
while (bytes > 1024) {
|
while (bytes > 1024) {
|
||||||
bytes /= 1024;
|
bytes /= 1024;
|
||||||
i++;
|
i++;
|
||||||
}
|
}
|
||||||
let unit = units[i];
|
let unit = units[i];
|
||||||
return bytes.toFixed(1) + " " + unit;
|
return bytes.toFixed(1) + " " + unit;
|
||||||
};
|
};
|
||||||
|
|
||||||
export const playable = (): boolean => {
|
export const playable = (): boolean => {
|
||||||
// TODO: Fix this
|
// TODO: Fix this
|
||||||
// let video_element = document.createElement("video");
|
// let video_element = document.createElement("video");
|
||||||
// let mime_type = mime.lookup(filename);
|
// let mime_type = mime.lookup(filename);
|
||||||
// return video_element.canPlayType(mime_type) != "";
|
// return video_element.canPlayType(mime_type) != "";
|
||||||
return true; // FIX BEFORE COMMIT - mime import causing issues
|
return true; // FIX BEFORE COMMIT - mime import causing issues
|
||||||
};
|
};
|
||||||
|
|
||||||
export function loaded(
|
export function loaded(
|
||||||
node: HTMLVideoElement,
|
node: HTMLVideoElement,
|
||||||
{ autoplay }: { autoplay: boolean }
|
{ autoplay }: { autoplay: boolean },
|
||||||
): any {
|
): any {
|
||||||
async function handle_playback(): Promise<void> {
|
async function handle_playback(): Promise<void> {
|
||||||
if (!autoplay) return;
|
if (!autoplay) return;
|
||||||
await node.play();
|
await node.play();
|
||||||
}
|
}
|
||||||
|
|
||||||
node.addEventListener("loadeddata", handle_playback);
|
node.addEventListener("loadeddata", handle_playback);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
destroy(): void {
|
destroy(): void {
|
||||||
node.removeEventListener("loadeddata", handle_playback);
|
node.removeEventListener("loadeddata", handle_playback);
|
||||||
}
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
export default async function loadFfmpeg(): Promise<FFmpeg> {
|
export default async function loadFfmpeg(): Promise<FFmpeg> {
|
||||||
const ffmpeg = new FFmpeg();
|
const ffmpeg = new FFmpeg();
|
||||||
const baseURL = "https://unpkg.com/@ffmpeg/core@0.12.4/dist/esm";
|
const baseURL = "https://unpkg.com/@ffmpeg/core@0.12.4/dist/esm";
|
||||||
|
|
||||||
await ffmpeg.load({
|
await ffmpeg.load({
|
||||||
coreURL: await toBlobURL(`${baseURL}/ffmpeg-core.js`, "text/javascript"),
|
coreURL: await toBlobURL(`${baseURL}/ffmpeg-core.js`, "text/javascript"),
|
||||||
wasmURL: await toBlobURL(`${baseURL}/ffmpeg-core.wasm`, "application/wasm")
|
wasmURL: await toBlobURL(`${baseURL}/ffmpeg-core.wasm`, "application/wasm"),
|
||||||
});
|
});
|
||||||
|
|
||||||
return ffmpeg;
|
return ffmpeg;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function blob_to_data_url(blob: Blob): Promise<string> {
|
export function blob_to_data_url(blob: Blob): Promise<string> {
|
||||||
return new Promise((fulfill, reject) => {
|
return new Promise((fulfill, reject) => {
|
||||||
let reader = new FileReader();
|
let reader = new FileReader();
|
||||||
reader.onerror = reject;
|
reader.onerror = reject;
|
||||||
reader.onload = () => fulfill(reader.result as string);
|
reader.onload = () => fulfill(reader.result as string);
|
||||||
reader.readAsDataURL(blob);
|
reader.readAsDataURL(blob);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function trimVideo(
|
export async function trimVideo(
|
||||||
ffmpeg: FFmpeg,
|
ffmpeg: FFmpeg,
|
||||||
startTime: number,
|
startTime: number,
|
||||||
endTime: number,
|
endTime: number,
|
||||||
videoElement: HTMLVideoElement
|
videoElement: HTMLVideoElement,
|
||||||
): Promise<any> {
|
): Promise<any> {
|
||||||
const videoUrl = videoElement.src;
|
const videoUrl = videoElement.src;
|
||||||
const mimeType = lookup(videoElement.src) || "video/mp4";
|
const mimeType = lookup(videoElement.src) || "video/mp4";
|
||||||
const blobUrl = await toBlobURL(videoUrl, mimeType);
|
const blobUrl = await toBlobURL(videoUrl, mimeType);
|
||||||
const response = await fetch(blobUrl);
|
const response = await fetch(blobUrl);
|
||||||
const vidBlob = await response.blob();
|
const vidBlob = await response.blob();
|
||||||
const type = getVideoExtensionFromMimeType(mimeType) || "mp4";
|
const type = getVideoExtensionFromMimeType(mimeType) || "mp4";
|
||||||
const inputName = `input.${type}`;
|
const inputName = `input.${type}`;
|
||||||
const outputName = `output.${type}`;
|
const outputName = `output.${type}`;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
if (startTime === 0 && endTime === 0) {
|
if (startTime === 0 && endTime === 0) {
|
||||||
return vidBlob;
|
return vidBlob;
|
||||||
}
|
}
|
||||||
|
|
||||||
await ffmpeg.writeFile(
|
await ffmpeg.writeFile(
|
||||||
inputName,
|
inputName,
|
||||||
new Uint8Array(await vidBlob.arrayBuffer())
|
new Uint8Array(await vidBlob.arrayBuffer()),
|
||||||
);
|
);
|
||||||
|
|
||||||
let command = [
|
let command = [
|
||||||
"-i",
|
"-i",
|
||||||
inputName,
|
inputName,
|
||||||
...(startTime !== 0 ? ["-ss", startTime.toString()] : []),
|
...(startTime !== 0 ? ["-ss", startTime.toString()] : []),
|
||||||
...(endTime !== 0 ? ["-to", endTime.toString()] : []),
|
...(endTime !== 0 ? ["-to", endTime.toString()] : []),
|
||||||
"-c:a",
|
"-c:a",
|
||||||
"copy",
|
"copy",
|
||||||
outputName
|
outputName,
|
||||||
];
|
];
|
||||||
|
|
||||||
await ffmpeg.exec(command);
|
await ffmpeg.exec(command);
|
||||||
const outputData = await ffmpeg.readFile(outputName);
|
const outputData = await ffmpeg.readFile(outputName);
|
||||||
const outputBlob = new Blob([outputData], {
|
const outputBlob = new Blob([outputData], {
|
||||||
type: `video/${type}`
|
type: `video/${type}`,
|
||||||
});
|
});
|
||||||
|
|
||||||
return outputBlob;
|
return outputBlob;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("Error initializing FFmpeg:", error);
|
console.error("Error initializing FFmpeg:", error);
|
||||||
return vidBlob;
|
return vidBlob;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const getVideoExtensionFromMimeType = (mimeType: string): string | null => {
|
const getVideoExtensionFromMimeType = (mimeType: string): string | null => {
|
||||||
const videoMimeToExtensionMap: { [key: string]: string } = {
|
const videoMimeToExtensionMap: { [key: string]: string } = {
|
||||||
"video/mp4": "mp4",
|
"video/mp4": "mp4",
|
||||||
"video/webm": "webm",
|
"video/webm": "webm",
|
||||||
"video/ogg": "ogv",
|
"video/ogg": "ogv",
|
||||||
"video/quicktime": "mov",
|
"video/quicktime": "mov",
|
||||||
"video/x-msvideo": "avi",
|
"video/x-msvideo": "avi",
|
||||||
"video/x-matroska": "mkv",
|
"video/x-matroska": "mkv",
|
||||||
"video/mpeg": "mpeg",
|
"video/mpeg": "mpeg",
|
||||||
"video/3gpp": "3gp",
|
"video/3gpp": "3gp",
|
||||||
"video/3gpp2": "3g2",
|
"video/3gpp2": "3g2",
|
||||||
"video/h261": "h261",
|
"video/h261": "h261",
|
||||||
"video/h263": "h263",
|
"video/h263": "h263",
|
||||||
"video/h264": "h264",
|
"video/h264": "h264",
|
||||||
"video/jpeg": "jpgv",
|
"video/jpeg": "jpgv",
|
||||||
"video/jpm": "jpm",
|
"video/jpm": "jpm",
|
||||||
"video/mj2": "mj2",
|
"video/mj2": "mj2",
|
||||||
"video/mpv": "mpv",
|
"video/mpv": "mpv",
|
||||||
"video/vnd.ms-playready.media.pyv": "pyv",
|
"video/vnd.ms-playready.media.pyv": "pyv",
|
||||||
"video/vnd.uvvu.mp4": "uvu",
|
"video/vnd.uvvu.mp4": "uvu",
|
||||||
"video/vnd.vivo": "viv",
|
"video/vnd.vivo": "viv",
|
||||||
"video/x-f4v": "f4v",
|
"video/x-f4v": "f4v",
|
||||||
"video/x-fli": "fli",
|
"video/x-fli": "fli",
|
||||||
"video/x-flv": "flv",
|
"video/x-flv": "flv",
|
||||||
"video/x-m4v": "m4v",
|
"video/x-m4v": "m4v",
|
||||||
"video/x-ms-asf": "asf",
|
"video/x-ms-asf": "asf",
|
||||||
"video/x-ms-wm": "wm",
|
"video/x-ms-wm": "wm",
|
||||||
"video/x-ms-wmv": "wmv",
|
"video/x-ms-wmv": "wmv",
|
||||||
"video/x-ms-wmx": "wmx",
|
"video/x-ms-wmx": "wmx",
|
||||||
"video/x-ms-wvx": "wvx",
|
"video/x-ms-wvx": "wvx",
|
||||||
"video/x-sgi-movie": "movie",
|
"video/x-sgi-movie": "movie",
|
||||||
"video/x-smv": "smv"
|
"video/x-smv": "smv",
|
||||||
};
|
};
|
||||||
|
|
||||||
return videoMimeToExtensionMap[mimeType] || null;
|
return videoMimeToExtensionMap[mimeType] || null;
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,162 +1,166 @@
|
|||||||
export function createPeerConnection(pc, node) {
|
export function createPeerConnection(pc, node) {
|
||||||
// register some listeners to help debugging
|
// register some listeners to help debugging
|
||||||
pc.addEventListener(
|
pc.addEventListener(
|
||||||
"icegatheringstatechange",
|
"icegatheringstatechange",
|
||||||
() => {
|
() => {
|
||||||
console.debug(pc.iceGatheringState);
|
console.debug(pc.iceGatheringState);
|
||||||
},
|
},
|
||||||
false
|
false,
|
||||||
);
|
);
|
||||||
|
|
||||||
pc.addEventListener(
|
pc.addEventListener(
|
||||||
"iceconnectionstatechange",
|
"iceconnectionstatechange",
|
||||||
() => {
|
() => {
|
||||||
console.debug(pc.iceConnectionState);
|
console.debug(pc.iceConnectionState);
|
||||||
},
|
},
|
||||||
false
|
false,
|
||||||
);
|
);
|
||||||
|
|
||||||
pc.addEventListener(
|
pc.addEventListener(
|
||||||
"signalingstatechange",
|
"signalingstatechange",
|
||||||
() => {
|
() => {
|
||||||
console.debug(pc.signalingState);
|
console.debug(pc.signalingState);
|
||||||
},
|
},
|
||||||
false
|
false,
|
||||||
);
|
);
|
||||||
|
|
||||||
// connect audio / video from server to local
|
// connect audio / video from server to local
|
||||||
pc.addEventListener("track", (evt) => {
|
pc.addEventListener("track", (evt) => {
|
||||||
console.debug("track event listener");
|
console.debug("track event listener");
|
||||||
if (node.srcObject !== evt.streams[0]) {
|
if (node && node.srcObject !== evt.streams[0]) {
|
||||||
console.debug("streams", evt.streams);
|
console.debug("streams", evt.streams);
|
||||||
node.srcObject = evt.streams[0];
|
node.srcObject = evt.streams[0];
|
||||||
console.debug("node.srcOject", node.srcObject);
|
console.debug("node.srcOject", node.srcObject);
|
||||||
if (evt.track.kind === 'audio') {
|
if (evt.track.kind === "audio") {
|
||||||
node.volume = 1.0; // Ensure volume is up
|
node.volume = 1.0; // Ensure volume is up
|
||||||
node.muted = false;
|
node.muted = false;
|
||||||
node.autoplay = true;
|
node.autoplay = true;
|
||||||
// Attempt to play (needed for some browsers)
|
// Attempt to play (needed for some browsers)
|
||||||
node.play().catch(e => console.debug("Autoplay failed:", e));
|
node.play().catch((e) => console.debug("Autoplay failed:", e));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
return pc;
|
return pc;
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function start(stream, pc: RTCPeerConnection, node, server_fn, webrtc_id,
|
export async function start(
|
||||||
modality: "video" | "audio" = "video", on_change_cb: () => void = () => {}) {
|
stream,
|
||||||
pc = createPeerConnection(pc, node);
|
pc: RTCPeerConnection,
|
||||||
const data_channel = pc.createDataChannel("text");
|
node,
|
||||||
|
server_fn,
|
||||||
|
webrtc_id,
|
||||||
|
modality: "video" | "audio" = "video",
|
||||||
|
on_change_cb: (msg: "change" | "tick") => void = () => {},
|
||||||
|
) {
|
||||||
|
pc = createPeerConnection(pc, node);
|
||||||
|
const data_channel = pc.createDataChannel("text");
|
||||||
|
|
||||||
data_channel.onopen = () => {
|
data_channel.onopen = () => {
|
||||||
console.debug("Data channel is open");
|
console.debug("Data channel is open");
|
||||||
data_channel.send("handshake");
|
data_channel.send("handshake");
|
||||||
};
|
};
|
||||||
|
|
||||||
data_channel.onmessage = (event) => {
|
data_channel.onmessage = (event) => {
|
||||||
console.debug("Received message:", event.data);
|
console.debug("Received message:", event.data);
|
||||||
if (event.data === "change") {
|
if (event.data === "change" || event.data === "tick") {
|
||||||
console.debug("Change event received");
|
console.debug(`${event.data} event received`);
|
||||||
on_change_cb();
|
on_change_cb(event.data);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
if (stream) {
|
if (stream) {
|
||||||
stream.getTracks().forEach((track) => {
|
stream.getTracks().forEach((track) => {
|
||||||
console.debug("Track stream callback", track);
|
console.debug("Track stream callback", track);
|
||||||
pc.addTrack(track, stream);
|
pc.addTrack(track, stream);
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
console.debug("Creating transceiver!");
|
console.debug("Creating transceiver!");
|
||||||
pc.addTransceiver(modality, { direction: "recvonly" });
|
pc.addTransceiver(modality, { direction: "recvonly" });
|
||||||
}
|
}
|
||||||
|
|
||||||
await negotiate(pc, server_fn, webrtc_id);
|
await negotiate(pc, server_fn, webrtc_id);
|
||||||
return pc;
|
return pc;
|
||||||
}
|
}
|
||||||
|
|
||||||
function make_offer(server_fn: any, body): Promise<object> {
|
function make_offer(server_fn: any, body): Promise<object> {
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
server_fn(body).then((data) => {
|
server_fn(body).then((data) => {
|
||||||
console.debug("data", data)
|
console.debug("data", data);
|
||||||
if(data?.status === "failed") {
|
if (data?.status === "failed") {
|
||||||
console.debug("rejecting")
|
console.debug("rejecting");
|
||||||
reject("error")
|
reject("error");
|
||||||
}
|
}
|
||||||
resolve(data);
|
resolve(data);
|
||||||
})
|
});
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
async function negotiate(
|
async function negotiate(
|
||||||
pc: RTCPeerConnection,
|
pc: RTCPeerConnection,
|
||||||
server_fn: any,
|
server_fn: any,
|
||||||
webrtc_id: string,
|
webrtc_id: string,
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
return pc
|
return pc
|
||||||
.createOffer()
|
.createOffer()
|
||||||
.then((offer) => {
|
.then((offer) => {
|
||||||
return pc.setLocalDescription(offer);
|
return pc.setLocalDescription(offer);
|
||||||
})
|
})
|
||||||
.then(() => {
|
.then(() => {
|
||||||
// wait for ICE gathering to complete
|
// wait for ICE gathering to complete
|
||||||
return new Promise<void>((resolve) => {
|
return new Promise<void>((resolve) => {
|
||||||
console.debug("ice gathering state", pc.iceGatheringState);
|
console.debug("ice gathering state", pc.iceGatheringState);
|
||||||
if (pc.iceGatheringState === "complete") {
|
if (pc.iceGatheringState === "complete") {
|
||||||
resolve();
|
resolve();
|
||||||
} else {
|
} else {
|
||||||
const checkState = () => {
|
const checkState = () => {
|
||||||
if (pc.iceGatheringState === "complete") {
|
if (pc.iceGatheringState === "complete") {
|
||||||
console.debug("ice complete");
|
console.debug("ice complete");
|
||||||
pc.removeEventListener("icegatheringstatechange", checkState);
|
pc.removeEventListener("icegatheringstatechange", checkState);
|
||||||
resolve();
|
resolve();
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
pc.addEventListener("icegatheringstatechange", checkState);
|
pc.addEventListener("icegatheringstatechange", checkState);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
})
|
})
|
||||||
.then(() => {
|
.then(() => {
|
||||||
var offer = pc.localDescription;
|
var offer = pc.localDescription;
|
||||||
return make_offer(
|
return make_offer(server_fn, {
|
||||||
server_fn,
|
sdp: offer.sdp,
|
||||||
{
|
type: offer.type,
|
||||||
sdp: offer.sdp,
|
webrtc_id: webrtc_id,
|
||||||
type: offer.type,
|
});
|
||||||
webrtc_id: webrtc_id
|
})
|
||||||
},
|
.then((response) => {
|
||||||
);
|
return response;
|
||||||
})
|
})
|
||||||
.then((response) => {
|
.then((answer) => {
|
||||||
return response;
|
return pc.setRemoteDescription(answer);
|
||||||
})
|
});
|
||||||
.then((answer) => {
|
|
||||||
return pc.setRemoteDescription(answer);
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function stop(pc: RTCPeerConnection) {
|
export function stop(pc: RTCPeerConnection) {
|
||||||
console.debug("Stopping peer connection");
|
console.debug("Stopping peer connection");
|
||||||
// close transceivers
|
// close transceivers
|
||||||
if (pc.getTransceivers) {
|
if (pc.getTransceivers) {
|
||||||
pc.getTransceivers().forEach((transceiver) => {
|
pc.getTransceivers().forEach((transceiver) => {
|
||||||
if (transceiver.stop) {
|
if (transceiver.stop) {
|
||||||
transceiver.stop();
|
transceiver.stop();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// close local audio / video
|
// close local audio / video
|
||||||
if (pc.getSenders()) {
|
if (pc.getSenders()) {
|
||||||
pc.getSenders().forEach((sender) => {
|
pc.getSenders().forEach((sender) => {
|
||||||
console.log("sender", sender);
|
console.log("sender", sender);
|
||||||
if (sender.track && sender.track.stop) sender.track.stop();
|
if (sender.track && sender.track.stop) sender.track.stop();
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// close peer connection
|
// close peer connection
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
pc.close();
|
pc.close();
|
||||||
}, 500);
|
}, 500);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ build-backend = "hatchling.build"
|
|||||||
|
|
||||||
[project]
|
[project]
|
||||||
name = "gradio_webrtc"
|
name = "gradio_webrtc"
|
||||||
version = "0.0.10"
|
version = "0.0.11"
|
||||||
description = "Stream images in realtime with webrtc"
|
description = "Stream images in realtime with webrtc"
|
||||||
readme = "README.md"
|
readme = "README.md"
|
||||||
license = "apache-2.0"
|
license = "apache-2.0"
|
||||||
|
|||||||
Reference in New Issue
Block a user