### Install FastAPI with Standard Optional Dependencies Source: https://fastapi.tiangolo.com/ Demonstrates how to install FastAPI along with its 'standard' group of optional dependencies, which includes packages like email-validator, httpx, jinja2, python-multipart, uvicorn, and fastapi-cli[standard] for a comprehensive setup. ```Python pip install "fastapi[standard]" ``` -------------------------------- ### Setting Up a Basic FastRTC Stream with FastAPI Source: https://context7_llms This Python example demonstrates how to initialize a FastRTC Stream with a simple echo function and mount it onto a FastAPI application. This setup forms the fundamental building block for handling incoming audio streams, such as those originating from Twilio. It requires the `fastrtc` and `fastapi` libraries. ```python from fastrtc import Stream, ReplyOnPause from fastapi import FastAPI def echo(audio): yield audio app = FastAPI() stream = Stream(ReplyOnPause(echo), modality="audio", mode="send-receive") stream.mount(app) # run with `uvicorn main:app` ``` -------------------------------- ### Example: Saving Audio to File Source: https://context7_llms Demonstrates how to use the `audio_to_file` function. It shows the creation of an example audio tuple and its subsequent saving to a file, printing the resulting file path. ```python sample_rate = 44100 audio_data = np.array([0.1, -0.2, 0.3]) # Example audio samples audio_tuple = (sample_rate, audio_data) file_path = audio_to_file(audio_tuple) print(f"Audio saved to: {file_path}") ``` -------------------------------- ### Install FastAPI with Standard Dependencies Source: https://fastapi.tiangolo.com/ This command installs the FastAPI framework along with its standard dependencies, including Uvicorn for serving the application. Ensure to quote "fastapi[standard]" for cross-terminal compatibility. ```Shell pip install "fastapi[standard]" ``` -------------------------------- ### Install FastAPI Without Standard Optional Dependencies Source: https://fastapi.tiangolo.com/ Shows the command to install FastAPI without any of its optional 'standard' dependencies, providing a minimal installation for users who prefer to manage dependencies manually or only need core functionality. ```Python pip install fastapi ``` -------------------------------- ### Install Gradio Python Library Source: https://www.gradio.app/ This command utilizes pip, the Python package installer, to download and install the Gradio library. Gradio is widely used for creating user-friendly web interfaces for machine learning models, simplifying the process of demonstrating and deploying models. ```bash $ pip install gradio ``` -------------------------------- ### Install FastRTC Core Library Source: https://context7_llms Installs the core FastRTC library using pip, providing basic real-time communication functionalities. ```bash pip install fastrtc ``` -------------------------------- ### Example JSON Output for TURN Server Public Details Source: https://github.com/freddyaboulton/turn-server-deploy This JSON snippet demonstrates the expected format and content of the 'server-info.json' file generated by the `describe-stacks` command. It includes the 'PublicIP' and 'PublicDNS' of the deployed TURN server, along with descriptive keys. ```JSON [ { "OutputKey": "PublicIP", "OutputValue": "35.173.254.80", "Description": "Public IP address of the TURN server" }, { "OutputKey": "PublicDNS", "OutputValue": "ec2-35-173-254-80.compute-1.amazonaws.com", "Description": "Public DNS name of the TURN server" } ] ``` -------------------------------- ### FastRTC Python Library Installation Source: https://huggingface.co/fastrtc These commands demonstrate how to install the FastRTC Python library using pip. The first command installs the base library, while the second command includes optional 'vad' (Voice Activity Detection) and 'tts' (Text-to-Speech) extras for advanced audio processing features, enabling functionalities like 'ReplyOnPause' and 'Text To Speech'. ```Python pip install fastrtc ``` ```Python pip install fastrtc[vad, tts] ``` -------------------------------- ### Example: Waiting for Item from Asyncio Queue Source: https://context7_llms Shows how to use the `wait_for_item` function. It demonstrates putting an item into an `asyncio.Queue` and then asynchronously waiting for and retrieving that item. ```python queue = asyncio.Queue() queue.put_nowait(1) item = await wait_for_item(queue) print(item) ``` -------------------------------- ### Example Usage of get_cloudflare_turn_credentials Source: https://context7_llms Illustrates how to call `get_cloudflare_turn_credentials` asynchronously and integrate its output with a `Stream` class for WebRTC configuration. ```python >>> from fastrtc import get_cloudflare_turn_crendials_async, Stream >>> credentials = await get_cloudflare_turn_credentials_async() >>> print(credentials) >>> # Can pass directly to stream class >>> stream = Stream(..., rtc_configuration=get_turn_credentials_async) ``` -------------------------------- ### Install Gradio Python Library via Pip Source: https://www.gradio.app/ This command installs the Gradio library, a powerful tool for building interactive web UIs for machine learning models. It is highly recommended for quickly deploying computer vision and other ML models, enabling easy sharing and interaction. ```Shell $ pip install gradio ``` -------------------------------- ### SvelteKit Client-Side Application Initialization Source: https://huggingface.co/docs/hub/en/security-tokens This JavaScript snippet initializes a SvelteKit client-side application. It sets up environment variables, identifies the parent element for hydration, and dynamically imports the necessary SvelteKit runtime and application modules to start the client-side rendering process, ensuring the application is interactive. ```JavaScript { __sveltekit_12zdie6 = { assets: "/docs/hub/main/en", base: "/docs/hub/main/en", env: {} }; const element = document.currentScript.parentElement; const data = [null,null]; Promise.all([ import("/docs/hub/main/en/_app/immutable/entry/start.7cc01974.js"), import("/docs/hub/main/en/_app/immutable/entry/app.9494bad3.js") ]).then(([kit, app]) => { kit.start(app, element, { node_ids: [0, 135], data, form: null, error: null }); }); } ``` -------------------------------- ### Example: Asynchronously Aggregating Bytes to 16-bit Audio Source: https://context7_llms Demonstrates the usage of the `async_aggregate_bytes_to_16bit` function. It shows how to process byte chunks asynchronously into 16-bit audio samples. ```python chunks_iterator = [b'\x00\x01', b'\x02\x03', b'\x04\x05'] for chunk in async_aggregate_bytes_to_16bit(chunks_iterator): print(chunk) ``` -------------------------------- ### Use Speech-to-Text (STT) Models Source: https://context7_llms This Python example demonstrates how to initialize a Speech-to-Text (STT) model using `get_stt_model` and then use its `stt` method to transcribe audio into text. It shows how to prepare a dummy audio input for transcription. ```python from fastrtc import get_stt_model model = get_stt_model(model="moonshine/base") audio = (16000, np.random.randint(-32768, 32768, size=(1, 16000))) text = model.stt(audio) ``` -------------------------------- ### Create a Basic Asynchronous FastAPI Application Source: https://fastapi.tiangolo.com/ This Python code demonstrates an asynchronous FastAPI application using async def for its endpoint functions. It provides the same functionality as the synchronous example but leverages Python's async/await syntax for potentially higher concurrency and non-blocking I/O operations. ```Python from typing import Union from fastapi import FastAPI app = FastAPI() @app.get("/") async def read_root(): return {"Hello": "World"} @app.get("/items/{item_id}") async def read_item(item_id: int, q: Union[str, None] = None): return {"item_id": item_id, "q": q} ``` -------------------------------- ### SvelteKit Client-Side Application Bootstrap Source: https://www.gradio.app/ This JavaScript snippet demonstrates the typical client-side bootstrapping process for a SvelteKit application. It utilizes `Promise.all` to asynchronously import the necessary SvelteKit start and application modules, then proceeds to initialize the application using `kit.start` with configuration parameters such as node IDs and initial data. ```javascript Promise.all([ import("/_app/immutable/entry/start.D58pouxN.js"), import("/_app/immutable/entry/app.CYMPB2o4.js") ]).then(([kit, app]) => { kit.start(app, element, { node_ids: [0, 3], data, form: null, error: null }); }); ``` -------------------------------- ### Change WebRTC Component Button Labels Source: https://context7_llms This example shows how to customize the text displayed on the `Start`, `Stop`, and `Waiting` buttons of the `WebRTC` component. It uses the `button_labels` dictionary to provide custom text for these UI elements. ```python webrtc = WebRTC( label="Video Chat", modality="audio-video", mode="send-receive", button_labels={"start": "Start Talking to Gemini"} ) ``` -------------------------------- ### Raise WebRTCError for Custom UI Messages in Gradio Source: https://context7_llms This Python example illustrates how to use `WebRTCError` within a Gradio application to display custom error messages directly in the user interface. It includes a `generation` function that simulates an audio processing task and raises `WebRTCError` after a delay, along with a Gradio `Blocks` setup featuring a `WebRTC` component, a slider, and a button to trigger the generation process. ```python 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) raise WebRTCError("This is a test error") 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 ) demo.launch() ``` -------------------------------- ### Install FastAPI with Standard Dependencies Excluding fastapi-cloud-cli Source: https://fastapi.tiangolo.com/ Provides the specific 'pip' command to install FastAPI with most of its 'standard' optional dependencies, but explicitly excluding 'fastapi-cloud-cli', offering a customized installation for specific deployment needs. ```Python pip install "fastapi[standard-no-fastapi-cloud-cli]" ``` -------------------------------- ### Create a simple 'Hello World' Gradio interface in Python Source: https://www.gradio.app/ This Python code demonstrates how to create a basic 'Hello World' web interface using the Gradio library. It defines a Python function `greet` that takes a name and returns a personalized greeting, then wraps this function in a `gr.Interface` and launches the interactive demo. ```Python import gradio as gr def greet(name): return "Hello " + name + "!" demo = gr.Interface(fn=greet, inputs="text", outputs="text") demo.launch() ``` -------------------------------- ### Deploying AWS CloudFormation Stack for TURN Server Source: https://github.com/freddyaboulton/turn-server-deploy This shell command initiates the creation of an AWS CloudFormation stack named 'turn-server'. It uses a local 'deployment.yml' template and 'parameters.json' for configuration, requiring IAM capabilities for resource provisioning. Ensure 'parameters.json' is correctly populated with `KeyName`, `TurnUserName`, `TurnPassword`, and `InstanceType`. ```Shell aws cloudformation create-stack \ --stack-name turn-server \ --template-body file://deployment.yml \ --parameters file://parameters.json \ --capabilities CAPABILITY_IAM ``` -------------------------------- ### Create a Basic Synchronous FastAPI Application Source: https://fastapi.tiangolo.com/ This Python code defines a simple FastAPI application with two GET endpoints. The root endpoint returns a 'Hello World' message, and the /items/{item_id} endpoint demonstrates handling path parameters (item_id) and optional query parameters (q) using standard Python def functions. ```Python from typing import Union from fastapi import FastAPI app = FastAPI() @app.get("/") def read_root(): return {"Hello": "World"} @app.get("/items/{item_id}") def read_item(item_id: int, q: Union[str, None] = None): return {"item_id": item_id, "q": q} ``` -------------------------------- ### Configure Gradio WebRTC with TURN Server Credentials Source: https://github.com/freddyaboulton/turn-server-deploy This Python code demonstrates how to initialize the `gradio_webrtc` component with `rtc_configuration` that includes TURN server details. It sets up `iceServers` with the TURN server URL, username, and credential, enabling WebRTC connections through the specified server. ```Python import gradio as gr from gradio_webrtc import WebRTC rtc_configuration = { "iceServers": [ { "urls": "turn:35.173.254.80:80", "username": "", "credential": "" } ] } with gr.Blocks() as demo: webrtc = WebRTC(rtc_configuration=rtc_configuration) ``` -------------------------------- ### Monitor CloudFormation Stack Creation Completion Source: https://github.com/freddyaboulton/turn-server-deploy This command blocks execution until the specified CloudFormation stack, named 'turn-server', has successfully completed its creation process. It ensures that all resources are provisioned before proceeding with subsequent steps. ```Bash aws cloudformation wait stack-create-complete \ --stack-name turn-server ``` -------------------------------- ### Install FastRTC with Audio Processing Extras Source: https://context7_llms Installs FastRTC along with optional dependencies for voice activity detection (VAD), speech-to-text (STT), and text-to-speech (TTS) capabilities, enabling advanced audio processing features. ```bash pip install "fastrtc[vad, stt, tts]" ``` -------------------------------- ### Execute Initial Audio Responses with ReplyOnPause Startup Function Source: https://context7_llms This code demonstrates how to use the `startup_fn` parameter in `ReplyOnPause` to play an initial audio message when the connection is established. This is useful for providing greetings or introductory information before the main interaction begins, ensuring a smooth user experience. ```python from fastrtc import get_tts_model, Stream, ReplyOnPause tts_client = get_tts_model() def echo(audio: tuple[int, np.ndarray]): # Implement any iterator that yields audio # See "LLM Voice Chat" for a more complete example yield audio def startup(): for chunk in tts_client.stream_tts_sync("Welcome to the echo audio demo!"): yield chunk stream = Stream( handler=ReplyOnPause(echo, startup_fn=startup), modality="audio", mode="send-receive", ui_args={"title": "Echo Audio"}, ) ``` -------------------------------- ### Deploy AWS CloudFormation Stack for TURN Server Source: https://github.com/freddyaboulton/turn-server-deploy This multi-line command initiates the deployment of the TURN server infrastructure on AWS using a CloudFormation template (`deployment.yml`) and a parameters file (`parameters.json`). The `CAPABILITY_IAM` flag is necessary as the stack creates IAM roles. ```Bash aws cloudformation create-stack \ --stack-name turn-server \ --template-body file://deployment.yml \ --parameters file://parameters.json \ --capabilities CAPABILITY_IAM ``` -------------------------------- ### WebRTC API Guides and Core Concepts Source: https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/RTCPeerConnection This section provides links to essential guides and conceptual overviews for understanding and implementing WebRTC. Topics range from fundamental protocols and connectivity to advanced negotiation patterns, session management, and specialized features like data channels and encoded transforms. ```APIDOC WebRTC API Guides and Concepts: - Introduction to WebRTC protocols: Overview of protocols used in WebRTC. - Introduction to the Real-time Transport Protocol (RTP): Details on the RTP protocol. - WebRTC connectivity: Explains how WebRTC establishes connections. - Establishing a connection: The WebRTC perfect negotiation pattern: Guide to perfect negotiation. - Lifetime of a WebRTC session: Describes the lifecycle of a WebRTC session. - Signaling and video calling: Concepts of signaling for video calls. - Using WebRTC data channels: How to use data channels for arbitrary data. - Using DTMF with WebRTC: How to implement DTMF tones. - Using WebRTC Encoded Transforms: Guide to using encoded transforms. ``` -------------------------------- ### Define FastAPI Endpoints with Pydantic Models for Request Body Source: https://fastapi.tiangolo.com/ This Python code defines a FastAPI application with multiple API endpoints. It demonstrates how to use Pydantic's `BaseModel` to define a request body schema (`Item`) for a `PUT` request, allowing for structured data validation and automatic documentation generation. It includes a root GET endpoint, an item GET endpoint with an optional query parameter, and an item PUT endpoint that accepts an `Item` object. ```Python from typing import Union from fastapi import FastAPI from pydantic import BaseModel app = FastAPI() class Item(BaseModel): name: str price: float is_offer: Union[bool, None] = None @app.get("/") def read_root(): return {"Hello": "World"} @app.get("/items/{item_id}") def read_item(item_id: int, q: Union[str, None] = None): return {"item_id": item_id, "q": q} @app.put("/items/{item_id}") def update_item(item_id: int, item: Item): return {"item_name": item.name, "item_id": item_id} ``` -------------------------------- ### Initialize WebRTC Peer Connection and Media Streams in JavaScript Source: https://context7_llms This JavaScript function `setupWebRTC` establishes an `RTCPeerConnection` for real-time communication. It handles obtaining user media (audio/video), adding tracks to the peer connection, setting up event listeners for incoming streams, creating a data channel, and performing the SDP offer/answer exchange with a backend server. ```javascript // pass any rtc_configuration params here const pc = new RTCPeerConnection(); {% if mode in ["send-receive", "receive"] %} const {{modality}}_output_component = document.getElementById("{{modality}}_output_component_id"); {% endif %} async function setupWebRTC(peerConnection) { {%- if mode in ["send-receive", "send"] -%} // Get {{modality}} stream from webcam const stream = await navigator.mediaDevices.getUserMedia({ {{modality}}: true, }) {%- endif -%} {% if mode == "send-receive" %} // Send {{ self.modality }} stream to server stream.getTracks().forEach(async (track) => { const sender = pc.addTrack(track, stream); }) {% elif mode == "send" %} // Receive {self.modality} stream from server pc.addTransceiver({{modality}}, { direction: "recvonly" }) {%- endif -%} {% if mode in ["send-receive", "receive"] %} peerConnection.addEventListener("track", (evt) => { if ({{modality}}_output_component && {{modality}}_output_component.srcObject !== evt.streams[0]) { {{modality}}_output_component.srcObject = evt.streams[0]; } }); {% endif %} // Create data channel (needed!) const dataChannel = peerConnection.createDataChannel("text"); // Create and send offer const offer = await peerConnection.createOffer(); await peerConnection.setLocalDescription(offer); // Send offer to server const response = await fetch('/webrtc/offer', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ sdp: offer.sdp, type: offer.type, webrtc_id: Math.random().toString(36).substring(7) }) }); // Handle server response const serverResponse = await response.json(); await peerConnection.setRemoteDescription(serverResponse); } ``` -------------------------------- ### Client-Side JavaScript Application Initialization Source: https://huggingface.co/fastrtc This JavaScript snippet handles the initial setup of a web application. It imports a main application bundle, sets a global variable for a build identifier, and conditionally loads the Stripe V3 library based on the current hostname, ensuring it's only loaded on specific production domains. ```JavaScript import("\\/front\\/build\\/kube-9d797e5\\/index.js"); window.moonSha = "kube-9d797e5\\/"; window.__hf_deferred = {}; if (["hf.co", "huggingface.co"].includes(window.location.hostname)) { const script = document.createElement("script"); script.src = "https://js.stripe.com/v3/"; script.async = true; document.head.appendChild(script); } ``` -------------------------------- ### Example: Aggregating Bytes to 16-bit Audio Source: https://context7_llms Illustrates how to use the `aggregate_bytes_to_16bit` function. It shows processing a list of byte chunks and iterating over the resulting 16-bit audio samples. ```python chunks_iterator = [b'\x00\x01', b'\x02\x03', b'\x04\x05'] for chunk in aggregate_bytes_to_16bit(chunks_iterator): print(chunk) ``` -------------------------------- ### fastrtc ReplyOnPause Class and Configuration Options Source: https://context7_llms Documentation for the `ReplyOnPause` class, its constructor parameters, and related configuration classes like `AlgoOptions` and `SileroVadOptions`. This covers how to initialize `ReplyOnPause` with a response handler, set voice detection parameters, manage interruptions, and define startup functions for initial audio output. ```APIDOC ReplyOnPause(handler, algo_options=None, model_options=None, can_interrupt=True, startup_fn=None) - Description: A class to wrap a Python generator for voice detection and turn-taking logic. - Parameters: - handler: (callable) A Python generator function that receives audio (sampling_rate, numpy array) and yields audio chunks (sampling_rate, numpy array). - algo_options: (AlgoOptions, optional) Options for voice activity detection algorithm. - model_options: (SileroVadOptions, optional) Options for the Silero VAD model. - can_interrupt: (bool, optional) If True, allows interruption of response by user speech. Defaults to True. - startup_fn: (callable, optional) A function called when the connection is first established, for initial audio output. Stream(handler, modality, mode, ui_args=None) - Description: Initializes a streaming connection for real-time communication. - Parameters: - handler: (object) The handler for processing stream data (e.g., ReplyOnPause instance). - modality: (str) The type of data being streamed (e.g., "audio"). - mode: (str) The communication mode (e.g., "send-receive"). - ui_args: (dict, optional) Arguments for UI configuration. AlgoOptions(audio_chunk_duration, started_talking_threshold, speech_threshold) - Description: Configuration options for the voice activity detection algorithm. - Parameters: - audio_chunk_duration: (float) Duration of audio chunks in seconds. - started_talking_threshold: (float) Threshold for detecting when a user starts talking. - speech_threshold: (float) General speech detection threshold. SileroVadOptions(threshold, min_speech_duration_ms, min_silence_duration_ms) - Description: Configuration options for the Silero VAD model. - Parameters: - threshold: (float) VAD threshold. - min_speech_duration_ms: (int) Minimum duration of speech in milliseconds. - min_silence_duration_ms: (int) Minimum duration of silence in milliseconds. ``` -------------------------------- ### Get Temporary Phone Number for FastRTC Stream Source: https://context7_llms Obtains a free temporary phone number that can be used to call into the FastRTC stream, requiring a Hugging Face token for access. ```python stream.fastphone() ``` -------------------------------- ### Hugging Face Frontend Initialization and Stripe Integration Source: https://huggingface.co/ This JavaScript snippet handles the initial loading of core frontend build scripts, sets a unique build identifier (moonSha), initializes a deferred object, and conditionally loads the Stripe.js library if the current hostname is 'hf.co' or 'huggingface.co'. This ensures payment processing capabilities are only enabled on official domains. ```JavaScript import("\/front\/build\/kube-9d797e5\/index.js"); window.moonSha = "kube-9d797e5\/"; window.__hf_deferred = {}; if (["hf.co", "huggingface.co"].includes(window.location.hostname)) { const script = document.createElement("script"); script.src = "https://js.stripe.com/v3/"; script.async = true; document.head.appendChild(script); } ``` -------------------------------- ### Set Input Audio Sampling Rate for Stream Handlers Source: https://context7_llms This example demonstrates how to specify the `input_sampling_rate` for a `ReplyOnPause` instance within a FastRTC `Stream`. It allows controlling the sampling rate of audio passed to the stream handler. ```python from fastrtc import ReplyOnPause, Stream stream = Stream( handler=ReplyOnPause(..., input_sampling_rate=24000), modality="audio", mode="send-receive" ) ``` -------------------------------- ### Core UI Component and Tooltip Styles Source: https://github.com/freddyaboulton/turn-server-deploy This CSS defines foundational styles for various UI components, including flexbox layouts for element arrangement, text truncation, and detailed tooltip styling. It covers tooltip appearance, positioning (south, south-east, south-west, north, north-east, north-west, west, east), and animation effects for a consistent user experience. ```CSS .gMOVLe\[data-size="medium"\]{display:-webkit-box;display:-webkit-flex;display:-ms-flexbox;display:flex;min-width:0;}/\*!sc\*/ .gMOVLe\[data-size="medium"\] svg{color:var(--fgColor-muted,var(--color-fg-muted,#656d76));}/\*!sc\*/ .gMOVLe\[data-size="medium"\] > span{width:inherit;}/\*!sc\*/ .gUkoLg{-webkit-box-pack:center;-webkit-justify-content:center;-ms-flex-pack:center;justify-content:center;}/\*!sc\*/ .bZBlpz{display:-webkit-box;display:-webkit-flex;display:-ms-flexbox;display:flex;width:100%;}/\*!sc\*/ .lhTYNA{margin-right:4px;color:var(--fgColor-muted,var(--color-fg-muted,#656d76));}/\*!sc\*/ .ffLUq{font-size:14px;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}/\*!sc\*/ .bmcJak{min-width:0;}/\*!sc\*/ .hUCRAk{display:-webkit-box;display:-webkit-flex;display:-ms-flexbox;display:flex;-webkit-flex-direction:column;-ms-flex-direction:column;flex-direction:column;-webkit-align-items:center;-webkit-box-align:center;-ms-flex-align:center;align-items:center;}/\*!sc\*/ data-styled.g1\[id="Box-sc-g0xbh4-0"\]{content:"gMOVLe,gUkoLg,bZBlpz,lhTYNA,ffLUq,bmcJak,hUCRAk,"}/\*!sc\*/ .brGdpi{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;-webkit-clip:rect(0,0,0,0);clip:rect(0,0,0,0);white-space:nowrap;border-width:0;}/\*!sc\*/ data-styled.g3\[id="_VisuallyHidden__VisuallyHidden-sc-11jhm7a-0"\]{content:"brGdpi,"}/\*!sc\*/ .hWlpPn{position:relative;display:inline-block;}/\*!sc\*/ .hWlpPn::after{position:absolute;z-index:1000000;display:none;padding:0.5em 0.75em;font:normal normal 11px/1.5 -apple-system,BlinkMacSystemFont,"Segoe UI","Noto Sans",Helvetica,Arial,sans-serif,"Apple Color Emoji","Segoe UI Emoji";-webkit-font-smoothing:subpixel-antialiased;color:var(--tooltip-fgColor,var(--fgColor-onEmphasis,var(--color-fg-on-emphasis,#ffffff)));text-align:center;-webkit-text-decoration:none;text-decoration:none;text-shadow:none;text-transform:none;-webkit-letter-spacing:normal;-moz-letter-spacing:normal;-ms-letter-spacing:normal;letter-spacing:normal;word-wrap:break-word;white-space:pre;pointer-events:none;content:attr(aria-label);background:var(--tooltip-bgColor,var(--bgColor-emphasis,var(--color-neutral-emphasis-plus,#24292f)));border-radius:6px;opacity:0;}/\*!sc\*/ @-webkit-keyframes tooltip-appear{from{opacity:0;}to{opacity:1;}}/\*!sc\*/ @keyframes tooltip-appear{from{opacity:0;}to{opacity:1;}}/\*!sc\*/ .hWlpPn:hover::after,.hWlpPn:active::after,.hWlpPn:focus::after,.hWlpPn:focus-within::after{display:inline-block;-webkit-text-decoration:none;text-decoration:none;-webkit-animation-name:tooltip-appear;animation-name:tooltip-appear;-webkit-animation-duration:0.1s;animation-duration:0.1s;-webkit-animation-fill-mode:forwards;animation-fill-mode:forwards;-webkit-animation-timing-function:ease-in;animation-timing-function:ease-in;-webkit-animation-delay:0s;animation-delay:0s;}/\*!sc\*/ .hWlpPn.tooltipped-no-delay:hover::after,.hWlpPn.tooltipped-no-delay:active::after,.hWlpPn.tooltipped-no-delay:focus::after,.hWlpPn.tooltipped-no-delay:focus-within::after{-webkit-animation-delay:0s;animation-delay:0s;}/\*!sc\*/ .hWlpPn.tooltipped-multiline:hover::after,.hWlpPn.tooltipped-multiline:active::after,.hWlpPn.tooltipped-multiline:focus::after,.hWlpPn.tooltipped-multiline:focus-within::after{display:table-cell;}/\*!sc\*/ .hWlpPn.tooltipped-s::after,.hWlpPn.tooltipped-se::after,.hWlpPn.tooltipped-sw::after{top:100%;right:50%;margin-top:6px;}/\*!sc\*/ .hWlpPn.tooltipped-se::after{right:auto;left:50%;margin-left:-16px;}/\*!sc\*/ .hWlpPn.tooltipped-sw::after{margin-right:-16px;}/\*!sc\*/ .hWlpPn.tooltipped-n::after,.hWlpPn.tooltipped-ne::after,.hWlpPn.tooltipped-nw::after{right:50%;bottom:100%;margin-bottom:6px;}/\*!sc\*/ .hWlpPn.tooltipped-ne::after{right:auto;left:50%;margin-left:-16px;}/\*!sc\*/ .hWlpPn.tooltipped-nw::after{margin-right:-16px;}/\*!sc\*/ .hWlpPn.tooltipped-s::after,.hWlpPn.tooltipped-n::after{-webkit-transform:translateX(50%);-ms-transform:translateX(50%);transform:translateX(50%);}/\*!sc\*/ .hWlpPn.tooltipped-w::after{right:100%;bottom:50%;margin-right:6px;-webkit-transform:translateY(50%);-ms-transform:translateY(50%);transform:translateY(50%);}/\*!sc\*/ .hWlpPn.tooltipped-e::after{bottom:50%;left:100%;margin-left:6px;-webkit-transform:translateY(50%);-ms-transform:translateY(50%);transform:translateY(50%);}/\*!sc\*/ .hWlpPn.tooltipped-multiline::after{width:-webkit-max-content;width:-moz-max-content;width:max-content;max-width:250px;word-wrap:break-word;white-space:pre-line;border-collapse:separate;}/\*!sc\*/ .hWlpPn.tooltipped-multiline.tooltipped-s::after,.hWlpPn.tooltipped-multiline.tooltipped-n::after{right:auto;left:50%;-webkit-transform:translateX(-50%);-ms-transform:translateX(-50%);transform:translateX(-50%);}/\*!sc\*/ .hWlpPn.tooltipped-multiline.tooltipped-w::after,.hWlpPn.tooltipped-multiline.tooltipped-e::after{right:100%;}/\*!sc\*/ .hWlpPn.tooltipped-align-right-2::after{right:0;margin-right:0;}/\*!sc\*/ .hWlpPn.tooltipped-align-left-2::after{left:0;ma ``` -------------------------------- ### Initializing FastRTC Stream Object Source: https://context7_llms This example demonstrates the basic initialization of a `Stream` object in FastRTC. It defines a handler function for processing data, specifies the modality (e.g., video), and sets the streaming mode (e.g., send-receive). ```python from fastrtc import Stream import gradio as gr import numpy as np def detection(image, slider): return np.flip(image, axis=0) stream = Stream( handler=detection, modality="video", mode="send-receive", additional_inputs=[ gr.Slider(minimum=0, maximum=1, step=0.01, value=0.3) ], additional_outputs=None, additional_outputs_handler=None ) ``` -------------------------------- ### Hugging Face Hub Configuration Object Source: https://huggingface.co/spaces/fastrtc/llm-voice-chat This JavaScript object defines global configuration settings for the Hugging Face platform. It includes URLs for various services like Git, Moon, dataset viewer, and API endpoints, along with API keys for services like Captcha, Stripe, DocSearch, and Logo.dev. It also specifies environment and user agent details, crucial for platform functionality. ```javascript window.hubConfig = { "features": { "signupDisabled": false }, "sshGitUrl": "git@hf.co", "moonHttpUrl": "https:\\/\\/huggingface.co", "captchaApiKey": "bd5f2066-93dc-4bdd-a64b-a24646ca3859", "captchaDisabledOnSignup": true, "datasetViewerPublicUrl": "https:\\/\\/datasets-server.huggingface.co", "stripePublicKey": "pk_live_x2tdjFXBCvXo2FFmMybezpeM00J6gPCAAc", "environment": "production", "userAgent": "HuggingFace (production)", "spacesIframeDomain": "hf.space", "spacesApiUrl": "https:\\/\\/api.hf.space", "docSearchKey": "ece5e02e57300e17d152c08056145326e90c4bff3dd07d7d1ae40cf1c8d39cb6", "logoDev": { "apiUrl": "https:\\/\\/img.logo.dev\\/", "apiKey": "pk_UHS2HZOeRnaSOdDp7jbd5w" } }; ``` -------------------------------- ### Customize WebRTC Component Audio Icon Source: https://context7_llms This example demonstrates how to display a custom icon for the `WebRTC` component in FastRTC. It shows how to pass a local path or URL to the `icon` parameter, replacing the default wave animation for audio streaming. ```python audio = WebRTC( label="Stream", rtc_configuration=rtc_configuration, mode="receive", modality="audio", icon="phone-solid.svg", ) ``` -------------------------------- ### Mounting FastRTC Stream on FastAPI Application Source: https://context7_llms This example illustrates how to integrate a FastRTC `Stream` object into a FastAPI application. Mounting the stream allows it to serve custom routes and handle real-time communication within a larger web service. ```python app = FastAPI() stream.mount(app) # uvicorn app:app --host 0.0.0.0 --port 8000 ```