diff --git a/README.md b/README.md index f6a58ad..d21679f 100644 --- a/README.md +++ b/README.md @@ -54,6 +54,7 @@ else: def detection(image, conf_threshold=0.3): + print("running detection") image = cv2.resize(image, (model.input_width, model.input_height)) new_image = model.detect_objects(image, conf_threshold) return cv2.resize(new_image, (500, 500)) diff --git a/backend/gradio_webrtc/utils.py b/backend/gradio_webrtc/utils.py index dedd014..1712b32 100644 --- a/backend/gradio_webrtc/utils.py +++ b/backend/gradio_webrtc/utils.py @@ -1,10 +1,15 @@ -import time -import fractions -import av import asyncio +import fractions import threading +import time from typing import Callable +import av +import logging + +logger = logging.getLogger(__name__) + + AUDIO_PTIME = 0.020 @@ -39,7 +44,7 @@ def player_worker_decode( frame = next(generator) except Exception as exc: if isinstance(exc, StopIteration): - print("Not iterating") + logger.debug("Stopping audio stream") asyncio.run_coroutine_threadsafe(queue.put(None), loop) thread_quit.set() break diff --git a/backend/gradio_webrtc/webrtc.py b/backend/gradio_webrtc/webrtc.py index c5a3a13..9139409 100644 --- a/backend/gradio_webrtc/webrtc.py +++ b/backend/gradio_webrtc/webrtc.py @@ -1,31 +1,33 @@ -"""gr.Video() component.""" +"""gr.WebRTC() component.""" from __future__ import annotations -from abc import ABC, abstractmethod import asyncio -from collections.abc import Callable, Sequence -from typing import TYPE_CHECKING, Any, Literal, cast, Generator -import fractions +import logging import threading import time -from gradio_webrtc.utils import player_worker_decode +import traceback +from collections.abc import Callable +from typing import TYPE_CHECKING, Any, Literal, Generator, Sequence, cast -from aiortc import RTCPeerConnection, RTCSessionDescription -from aiortc.contrib.media import MediaRelay -from aiortc import VideoStreamTrack, AudioStreamTrack -from aiortc.mediastreams import MediaStreamError -from aiortc.contrib.media import AudioFrame, VideoFrame # type: ignore -from gradio_client import handle_file import numpy as np - - +from aiortc import ( + AudioStreamTrack, + RTCPeerConnection, + RTCSessionDescription, + VideoStreamTrack, +) +from aiortc.contrib.media import AudioFrame, MediaRelay, VideoFrame # type: ignore +from aiortc.mediastreams import MediaStreamError from gradio import wasm_utils from gradio.components.base import Component, server +from gradio_client import handle_file + +from gradio_webrtc.utils import player_worker_decode if TYPE_CHECKING: - from gradio.components import Timer from gradio.blocks import Block + from gradio.components import Timer from gradio.events import Dependency @@ -33,6 +35,9 @@ if wasm_utils.IS_WASM: raise ValueError("Not supported in gradio-lite!") +logger = logging.getLogger(__name__) + + class VideoCallback(VideoStreamTrack): """ This works for streaming input and output @@ -90,10 +95,9 @@ class VideoCallback(VideoStreamTrack): return new_frame except Exception as e: - print(e) - import traceback - - traceback.print_exc() + logger.debug(e) + exec = traceback.format_exc() + logger.debug(exec) class ServerToClientVideo(VideoStreamTrack): @@ -150,10 +154,9 @@ class ServerToClientVideo(VideoStreamTrack): next_frame.time_base = time_base return next_frame except Exception as e: - print(e) - import traceback - - traceback.print_exc() + logger.debug(e) + exec = traceback.format_exc() + logger.debug(exec) class ServerToClientAudio(AudioStreamTrack): @@ -173,26 +176,6 @@ class ServerToClientAudio(AudioStreamTrack): self._start: float | None = None super().__init__() - def array_to_frame(self, array: tuple[int, np.ndarray]) -> AudioFrame: - frame = AudioFrame.from_ndarray(array[1], format="s16", layout="mono") - frame.sample_rate = array[0] - frame.time_base = fractions.Fraction(1, array[0]) - self.current_timestamp += array[1].shape[1] - frame.pts = self.current_timestamp - return frame - - async def empty_frame(self) -> AudioFrame: - sample_rate = 22050 - samples = 100 - frame = AudioFrame(format="s16", layout="mono", samples=samples) - for p in frame.planes: - p.update(bytes(p.buffer_size)) - frame.sample_rate = sample_rate - frame.time_base = fractions.Fraction(1, sample_rate) - self.current_timestamp += samples - frame.pts = self.current_timestamp - return frame - def start(self): if self.__thread is None: self.__thread = threading.Thread( @@ -232,10 +215,9 @@ class ServerToClientAudio(AudioStreamTrack): return data except Exception as e: - print(e) - import traceback - - traceback.print_exc() + logger.debug(e) + exec = traceback.format_exc() + logger.debug(exec) def stop(self): self.thread_quit.set() @@ -244,39 +226,6 @@ class ServerToClientAudio(AudioStreamTrack): self.__thread = None super().stop() - # next_frame = await super().recv() - # print("next frame", next_frame) - # return next_frame - # try: - # if self.latest_args == "not_set": - # frame = await self.empty_frame() - - # # await self.modify_frame(frame) - # await asyncio.sleep(100 / 22050) - # print("next_frame not set", frame) - # return frame - # if self.generator is None: - # self.generator = cast( - # Generator[Any, None, Any], self.event_handler(*self.latest_args) - # ) - - # try: - # next_array = next(self.generator) - # print("iteration") - # except StopIteration: - # print("exception") - # self.stop() # type: ignore - # return - # next_frame = self.array_to_frame(next_array) - # # await self.modify_frame(next_frame) - # print("next frame", next_frame) - # return next_frame - # except Exception as e: - # print(e) - # import traceback - - # traceback.print_exc() - class WebRTC(Component): """ @@ -485,7 +434,8 @@ class WebRTC(Component): @server async def offer(self, body): - print("starting") + logger.debug("Starting to handle offer") + logger.debug("Offer body", body) if len(self.connections) >= cast(int, self.concurrency_limit): return {"status": "failed"} @@ -496,7 +446,7 @@ class WebRTC(Component): @pc.on("iceconnectionstatechange") async def on_iceconnectionstatechange(): - print(pc.iceConnectionState) + logger.debug("ICE connection state change", pc.iceConnectionState) if pc.iceConnectionState == "failed": await pc.close() self.connections.pop(body["webrtc_id"], None) @@ -519,32 +469,27 @@ class WebRTC(Component): event_handler=cast(Callable, self.event_handler), ) self.connections[body["webrtc_id"]] = cb + logger.debug("Adding track to peer connection", cb) pc.addTrack(cb) - if self.mode == "receive" and self.modality == "video": - cb = ServerToClientVideo(cast(Callable, self.event_handler)) - pc.addTrack(cb) - self.connections[body["webrtc_id"]] = cb - cb.on("ended", lambda: self.connections.pop(body["webrtc_id"], None)) - if self.mode == "receive" and self.modality == "audio": - print("adding") - cb = ServerToClientAudio(cast(Callable, self.event_handler)) - print("cb.recv", cb.recv) - # from aiortc.contrib.media import MediaPlayer - # player = MediaPlayer("/Users/freddy/sources/gradio/demo/audio_debugger/cantina.wav") - # pc.addTrack(player.audio) + if self.mode == "receive": + if self.modality == "video": + cb = ServerToClientVideo(cast(Callable, self.event_handler)) + elif self.modality == "audio": + cb = ServerToClientAudio(cast(Callable, self.event_handler)) + + logger.debug("Adding track to peer connection", cb) pc.addTrack(cb) self.connections[body["webrtc_id"]] = cb cb.on("ended", lambda: self.connections.pop(body["webrtc_id"], None)) - print("here") # handle offer await pc.setRemoteDescription(offer) # send answer answer = await pc.createAnswer() await pc.setLocalDescription(answer) # type: ignore - print("done") + logger.debug("done handling offer about to return") return { "sdp": pc.localDescription.sdp, diff --git a/demo/audio_out.py b/demo/audio_out.py index 716c1ab..a66d41c 100644 --- a/demo/audio_out.py +++ b/demo/audio_out.py @@ -22,18 +22,20 @@ if account_sid and auth_token: else: rtc_configuration = None +import time 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)) + time.sleep(3.5) 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: +with gr.Blocks() as demo: gr.HTML( """

diff --git a/demo/space.py b/demo/space.py index 8b477fa..794d05e 100644 --- a/demo/space.py +++ b/demo/space.py @@ -3,7 +3,7 @@ import gradio as gr from app import demo as app import os -_docs = {'WebRTC': {'description': 'Creates a video component that can be used to upload/record videos (as an input) or display videos (as an output).\nFor the video to be playable in the browser it must have a compatible container and codec combination. Allowed\ncombinations are .mp4 with h264 codec, .ogg with theora codec, and .webm with vp9 codec. If the component detects\nthat the output video would not be playable in the browser it will attempt to convert it to a playable mp4 video.\nIf the conversion fails, the original video is returned.\n', 'members': {'__init__': {'value': {'type': 'None', 'default': 'None', 'description': 'path or URL for the default value that WebRTC component is going to take. Can also be a tuple consisting of (video filepath, subtitle filepath). If a subtitle file is provided, it should be of type .srt or .vtt. Or can be callable, in which case the function will be called whenever the app loads to set the initial value of the component.'}, '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.'}, 'every': {'type': 'Timer | float | None', 'default': 'None', 'description': 'continously calls `value` to recalculate it if `value` is a function (has no effect otherwise). Can provide a Timer whose tick resets `value`, or a float that provides the regular interval for the reset Timer.'}, 'inputs': {'type': 'Component | Sequence[Component] | set[Component] | None', 'default': 'None', 'description': 'components that are used as inputs to calculate `value` if `value` is a function (has no effect otherwise). `value` is recalculated any time the inputs change.'}, 'show_label': {'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.'}, 'rtc_configuration': {'type': 'dict[str, Any] | None', 'default': 'None', 'description': None}, 'time_limit': {'type': 'float | None', 'default': 'None', 'description': None}}, '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': []}}} +_docs = {'WebRTC': {'description': 'Creates a video component that can be used to upload/record videos (as an input) or display videos (as an output).\nFor the video to be playable in the browser it must have a compatible container and codec combination. Allowed\ncombinations are .mp4 with h264 codec, .ogg with theora codec, and .webm with vp9 codec. If the component detects\nthat the output video would not be playable in the browser it will attempt to convert it to a playable mp4 video.\nIf the conversion fails, the original video is returned.\n', 'members': {'__init__': {'value': {'type': 'None', 'default': 'None', 'description': 'path or URL for the default value that WebRTC component is going to take. Can also be a tuple consisting of (video filepath, subtitle filepath). If a subtitle file is provided, it should be of type .srt or .vtt. Or can be callable, in which case the function will be called whenever the app loads to set the initial value of the component.'}, '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.'}, 'every': {'type': 'Timer | float | None', 'default': 'None', 'description': 'continously calls `value` to recalculate it if `value` is a function (has no effect otherwise). Can provide a Timer whose tick resets `value`, or a float that provides the regular interval for the reset Timer.'}, 'inputs': {'type': 'Component | Sequence[Component] | set[Component] | None', 'default': 'None', 'description': 'components that are used as inputs to calculate `value` if `value` is a function (has no effect otherwise). `value` is recalculated any time the inputs change.'}, 'show_label': {'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.'}, 'rtc_configuration': {'type': 'dict[str, Any] | None', 'default': 'None', 'description': None}, 'time_limit': {'type': 'float | None', 'default': 'None', 'description': None}, 'mode': {'type': 'Literal["send-receive", "receive"]', 'default': '"send-receive"', 'description': None}, 'modality': {'type': 'Literal["video", "audio"]', 'default': '"video"', 'description': None}}, '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': []}}} abs_path = os.path.join(os.path.dirname(__file__), "css.css") @@ -21,7 +21,7 @@ with gr.Blocks( # `gradio_webrtc`
-Static Badge +PyPI - Version
Stream images in realtime with webrtc @@ -69,6 +69,7 @@ else: def detection(image, conf_threshold=0.3): + print("running detection") image = cv2.resize(image, (model.input_width, model.input_height)) new_image = model.detect_objects(image, conf_threshold) return cv2.resize(new_image, (500, 500)) diff --git a/demo/video_out.py b/demo/video_out.py index 696d3fe..082e193 100644 --- a/demo/video_out.py +++ b/demo/video_out.py @@ -48,7 +48,7 @@ with gr.Blocks() as demo: input_video = gr.Video(sources="upload") with gr.Column(): output_video = WebRTC(label="Video Stream", rtc_configuration=rtc_configuration, - mode="receive", modality="video") + mode="receive", modality="video") output_video.stream( fn=generation, inputs=[input_video], outputs=[output_video], trigger=input_video.upload diff --git a/frontend/Index.svelte b/frontend/Index.svelte index 5f022fc..4d14ea8 100644 --- a/frontend/Index.svelte +++ b/frontend/Index.svelte @@ -35,10 +35,73 @@ let dragging = false; $: console.log("value", value); - - + gradio.dispatch("clear_status", loading_status)} + /> + + gradio.dispatch("tick")} + on:error={({ detail }) => gradio.dispatch("error", detail)} + /> + + +{:else if mode == "receive" && modality === "audio"} + + gradio.dispatch("clear_status", loading_status)} + /> + gradio.dispatch("tick")} + on:error={({ detail }) => gradio.dispatch("error", detail)} + /> + +{:else if mode === "send-receive" && modality === "video"} + - + gradio.dispatch("clear_status", loading_status)} /> - - {#if mode === "receive" && modality === "video"} - gradio.dispatch("tick")} - on:error={({ detail }) => gradio.dispatch("error", detail)} - /> - {:else if mode == "receive" && modality === "audio"} - gradio.dispatch("tick")} - on:error={({ detail }) => gradio.dispatch("error", detail)} - /> - {:else if mode === "send-receive" && modality === "video"} - {/if} - + +{/if} diff --git a/frontend/shared/InteractiveVideo.svelte b/frontend/shared/InteractiveVideo.svelte index 46dde79..d74480b 100644 --- a/frontend/shared/InteractiveVideo.svelte +++ b/frontend/shared/InteractiveVideo.svelte @@ -38,7 +38,8 @@ let dragging = false; $: dispatch("drag", dragging); - $: console.log("interactive value", value); + $: console.log("value", value) + diff --git a/frontend/shared/StaticAudio.svelte b/frontend/shared/StaticAudio.svelte index 31c6c76..6e9a146 100644 --- a/frontend/shared/StaticAudio.svelte +++ b/frontend/shared/StaticAudio.svelte @@ -49,34 +49,27 @@ $: if( value === "start_webrtc_stream") { stream_state = "connecting"; value = _webrtc_id; - const fallback_config = { - iceServers: [ - { - urls: 'stun:stun.l.google.com:19302' - } - ] - }; - pc = new RTCPeerConnection(rtc_configuration); - pc.addEventListener("connectionstatechange", - async (event) => { - switch(pc.connectionState) { - case "connected": - console.log("connected"); - stream_state = "open"; - break; - case "disconnected": - console.log("closed"); - stop(pc); - break; - default: - break; - } + pc = new RTCPeerConnection(rtc_configuration); + pc.addEventListener("connectionstatechange", + async (event) => { + switch(pc.connectionState) { + case "connected": + console.info("connected"); + stream_state = "open"; + break; + case "disconnected": + console.info("closed"); + stop(pc); + break; + default: + break; } - ) + } + ) start(null, pc, audio_player, server.offer, _webrtc_id, "audio").then((connection) => { pc = connection; }).catch(() => { - console.log("catching") + console.info("catching") dispatch("error", "Too many concurrent users. Come back later!"); }); } @@ -91,7 +84,6 @@ float={false} label={label || i18n("audio.audio")} /> -