From 841d78420666622e73ea9ea23af01825e313a493 Mon Sep 17 00:00:00 2001 From: freddyaboulton Date: Mon, 14 Oct 2024 12:57:06 -0700 Subject: [PATCH] Add code --- README.md | 478 ++++++++++++-------------------------------------- demo/css.css | 4 + demo/space.py | 257 ++++++++++++++++----------- 3 files changed, 275 insertions(+), 464 deletions(-) diff --git a/README.md b/README.md index f6a58ad..2dab0d6 100644 --- a/README.md +++ b/README.md @@ -9,10 +9,15 @@ pinned: false app_file: space.py --- -# `gradio_webrtc` -PyPI - Version +

Gradio WebRTC ⚡️

-Stream images in realtime with webrtc +
+Static Badge +
+ +

+Stream video and audio in real time with Gradio using WebRTC. +

## Installation @@ -20,397 +25,146 @@ Stream images in realtime with webrtc 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) 🗣️ + ## Usage +The WebRTC component supports the following three use cases: +1. Streaming video from the user webcam to the server and back +2. Streaming Video from the server to the client +3. Streaming Audio from the server to the client + +Streaming Audio from client to the server and back (conversational AI) is not supported yet. + + +## Streaming Video from the User Webcam to the Server and Back + ```python import gradio as gr -import cv2 -from huggingface_hub import hf_hub_download from gradio_webrtc import WebRTC -from twilio.rest import Client -import os -from inference import YOLOv10 - -model_file = hf_hub_download( - repo_id="onnx-community/yolov10n", filename="onnx/model.onnx" -) - -model = YOLOv10(model_file) - -account_sid = os.environ.get("TWILIO_ACCOUNT_SID") -auth_token = os.environ.get("TWILIO_AUTH_TOKEN") - -if account_sid and auth_token: - client = Client(account_sid, auth_token) - - token = client.tokens.create() - - rtc_configuration = { - "iceServers": token.ice_servers, - "iceTransportPolicy": "relay", - } -else: - rtc_configuration = None def detection(image, conf_threshold=0.3): - image = cv2.resize(image, (model.input_width, model.input_height)) - new_image = model.detect_objects(image, conf_threshold) - return cv2.resize(new_image, (500, 500)) + ... your detection code here ... -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( - """ -

- YOLOv10 Webcam Stream (Powered by WebRTC ⚡️) -

- """ +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, ) - gr.HTML( - """ -

- arXiv | github -

- """ + image.stream( + fn=detection, + inputs=[image, conf_threshold], + outputs=[image], time_limit=10 ) - 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, - ) - - 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. -## `WebRTC` - -### Initialization - - - - - - - - - - - - - - - - - +* 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. - - - - - - +* 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. - - - - - - +account_sid = os.environ.get("TWILIO_ACCOUNT_SID") +auth_token = os.environ.get("TWILIO_AUTH_TOKEN") - - - - - - +rtc_configuration = { + "iceServers": token.ice_servers, + "iceTransportPolicy": "relay", +} - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
nametypedefaultdescription
value +## Streaming Video from the User Webcam to the Server and Back ```python -None +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() ``` -Nonepath 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 +## Streaming Audio from the Server to the Client ```python -int | str | None +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 + ) ``` -NoneThe 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 +## 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 -int | str | None -``` +from twilio.rest import Client +import os -NoneThe 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 +client = Client(account_sid, auth_token) -```python -str | None -``` +token = client.tokens.create() -Nonethe 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 - -```python -Timer | float | None -``` - -Nonecontinously 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 - -```python -Component | Sequence[Component] | set[Component] | None -``` - -Nonecomponents 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 - -```python -bool | None -``` - -Noneif True, will display label.
container - -```python -bool -``` - -Trueif True, will place the component in a container - providing some extra padding around the border.
scale - -```python -int | None -``` - -Nonerelative 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 - -```python -int -``` - -160minimum 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 - -```python -bool | None -``` - -Noneif 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 - -```python -bool -``` - -Trueif False, component will be hidden.
elem_id - -```python -str | None -``` - -Nonean optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles.
elem_classes - -```python -list[str] | str | None -``` - -Nonean 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 - -```python -bool -``` - -Trueif 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 - -```python -int | str | None -``` - -Noneif 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 - -```python -bool -``` - -Trueif True webcam will be mirrored. Default is True.
rtc_configuration - -```python -dict[str, Any] | None -``` - -NoneNone
time_limit - -```python -float | None -``` - -NoneNone
mode - -```python -Literal["send-receive", "receive"] -``` - -"send-receive"None
modality - -```python -Literal["video", "audio"] -``` - -"video"None
- - -### Events - -| name | description | -|:-----|:------------| -| `tick` | | - - - -### User function - -The impact on the users predict function varies depending on whether the component is used as an input or output for an event (or both). - -- When used as an Input, the component only impacts the input signature of the user function. -- When used as an output, the component only impacts the return signature of the user function. - -The code snippet below is accurate in cases where the component is used as both an input and an output. - -- **As output:** Is passed, passes the uploaded video as a `str` filepath or URL whose extension can be modified by `format`. -- **As input:** Should return, 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. - - ```python - def predict( - value: str - ) -> typing.Any: - return value - ``` - +with gr.Blocks() as demo: + ... + rtc = WebRTC(rtc_configuration=rtc_configuration, ...) + ... +``` \ No newline at end of file diff --git a/demo/css.css b/demo/css.css index f7256be..486edd8 100644 --- a/demo/css.css +++ b/demo/css.css @@ -155,3 +155,7 @@ h2 + h3 { .gap { gap: 0; } + +.md-custom { + overflow: hidden; +} diff --git a/demo/space.py b/demo/space.py index 98813c8..ef039ab 100644 --- a/demo/space.py +++ b/demo/space.py @@ -1,14 +1,33 @@ 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}, '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': []}}} +_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=abs_path, + css_paths=abs_path, theme=gr.themes.Default( font_mono=[ gr.themes.GoogleFont("Inconsolata"), @@ -18,15 +37,16 @@ with gr.Blocks( ) as demo: gr.Markdown( """ -# `gradio_webrtc` +

Gradio WebRTC ⚡️

-
-PyPI - Version +
+Static Badge
-Stream images in realtime with webrtc +

+Stream video and audio in real time with Gradio using WebRTC. +

""", elem_classes=["md-custom"], header_links=True) - app.render() gr.Markdown( """ ## Installation @@ -35,126 +55,159 @@ Stream images in realtime with webrtc 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) 🗣️ + ## Usage +The WebRTC component supports the following three use cases: +1. Streaming video from the user webcam to the server and back +2. Streaming Video from the server to the client +3. Streaming Audio from the server to the client + +Streaming Audio from client to the server and back (conversational AI) is not supported yet. + + +## Streaming Video from the User Webcam to the Server and Back + ```python import gradio as gr -import cv2 -from huggingface_hub import hf_hub_download from gradio_webrtc import WebRTC -from twilio.rest import Client -import os -from inference import YOLOv10 - -model_file = hf_hub_download( - repo_id="onnx-community/yolov10n", filename="onnx/model.onnx" -) - -model = YOLOv10(model_file) - -account_sid = os.environ.get("TWILIO_ACCOUNT_SID") -auth_token = os.environ.get("TWILIO_AUTH_TOKEN") - -if account_sid and auth_token: - client = Client(account_sid, auth_token) - - token = client.tokens.create() - - rtc_configuration = { - "iceServers": token.ice_servers, - "iceTransportPolicy": "relay", - } -else: - rtc_configuration = None def detection(image, conf_threshold=0.3): - image = cv2.resize(image, (model.input_width, model.input_height)) - new_image = model.detect_objects(image, conf_threshold) - return cv2.resize(new_image, (500, 500)) + ... your detection code here ... -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( - \"\"\" -

- YOLOv10 Webcam Stream (Powered by WebRTC ⚡️) -

- \"\"\" +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, ) - gr.HTML( - \"\"\" -

- arXiv | github -

- \"\"\" + image.stream( + fn=detection, + inputs=[image, conf_threshold], + outputs=[image], time_limit=10 ) - 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, - ) - - 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 User Webcam to the Server and Back + +```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. + +## 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(""" -## `WebRTC` - -### Initialization +## """, elem_classes=["md-custom"], header_links=True) gr.ParamViewer(value=_docs["WebRTC"]["members"]["__init__"], linkify=[]) - gr.Markdown("### Events") - gr.ParamViewer(value=_docs["WebRTC"]["events"], linkify=['Event']) - - - - - gr.Markdown(""" - -### User function - -The impact on the users predict function varies depending on whether the component is used as an input or output for an event (or both). - -- When used as an Input, the component only impacts the input signature of the user function. -- When used as an output, the component only impacts the return signature of the user function. - -The code snippet below is accurate in cases where the component is used as both an input and an output. - -- **As input:** Is passed, passes the uploaded video as a `str` filepath or URL whose extension can be modified by `format`. -- **As output:** Should return, 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. - - ```python -def predict( - value: str -) -> typing.Any: - return value -``` -""", elem_classes=["md-custom", "WebRTC-user-fn"], header_links=True) - - - - demo.load(None, js=r"""function() { const refs = {}; const user_fn_refs = {