mirror of
https://github.com/HumanAIGC-Engineering/gradio-webrtc.git
synced 2026-02-05 01:49:23 +08:00
[feat] update some feature
sync code of fastrtc, add text support through datachannel, fix safari connect problem support chat without camera or mic
This commit is contained in:
461
docs/userguide/api.md
Normal file
461
docs/userguide/api.md
Normal file
@@ -0,0 +1,461 @@
|
||||
# Connecting via API
|
||||
|
||||
Before continuing, select the `modality`, `mode` of your `Stream` and whether you're using `WebRTC` or `WebSocket`s.
|
||||
|
||||
<div class="config-selector">
|
||||
<div class="select-group">
|
||||
<label for="connection">Connection</label>
|
||||
<select id="connection" onchange="updateDocs()">
|
||||
<option value="webrtc">WebRTC</option>
|
||||
<option value="websocket">WebSocket</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="select-group">
|
||||
<label for="modality">Modality</label>
|
||||
<select id="modality" onchange="updateDocs()">
|
||||
<option value="audio">Audio</option>
|
||||
<option value="video">Video</option>
|
||||
<option value="audio-video">Audio-Video</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="select-group">
|
||||
<label for="mode">Mode</label>
|
||||
<select id="mode" onchange="updateDocs()">
|
||||
<option value="send-receive">Send-Receive</option>
|
||||
<option value="receive">Receive</option>
|
||||
<option value="send">Send</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
### Sample Code
|
||||
<div id="docs"></div>
|
||||
|
||||
### Message Format
|
||||
|
||||
Over both WebRTC and WebSocket, the server can send messages of the following format:
|
||||
|
||||
```json
|
||||
{
|
||||
"type": `send_input` | `fetch_output` | `stopword` | `error` | `warning` | `log`,
|
||||
"data": string | object
|
||||
}
|
||||
```
|
||||
|
||||
- `send_input`: Send any input data for the handler to the server. See [`Additional Inputs`](#additional-inputs) for more details.
|
||||
- `fetch_output`: An instance of [`AdditionalOutputs`](#additional-outputs) is sent to the server.
|
||||
- `stopword`: The stopword has been detected. See [`ReplyOnStopWords`](../audio/#reply-on-stopwords) for more details.
|
||||
- `error`: An error occurred. The `data` will be a string containing the error message.
|
||||
- `warning`: A warning occurred. The `data` will be a string containing the warning message.
|
||||
- `log`: A log message. The `data` will be a string containing the log message.
|
||||
|
||||
The `ReplyOnPause` handler can also send the following `log` messages.
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "log",
|
||||
"data": "pause_detected" | "response_starting"
|
||||
}
|
||||
```
|
||||
|
||||
!!! tip
|
||||
When using WebRTC, the messages will be encoded as strings, so parse as JSON before using.
|
||||
|
||||
### Additional Inputs
|
||||
|
||||
When the `send_input` message is received, update the inputs of your handler however you like by using the `set_input` method of the `Stream` object.
|
||||
|
||||
A common pattern is to use a `POST` request to send the updated data. The first argument to the `set_input` method is the `webrtc_id` of the handler.
|
||||
|
||||
```python
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
class InputData(BaseModel):
|
||||
webrtc_id: str
|
||||
conf_threshold: float = Field(ge=0, le=1)
|
||||
|
||||
|
||||
@app.post("/input_hook")
|
||||
async def _(data: InputData):
|
||||
stream.set_input(data.webrtc_id, data.conf_threshold)
|
||||
```
|
||||
|
||||
The updated data will be passed to the handler on the **next** call.
|
||||
|
||||
### Additional Outputs
|
||||
|
||||
The `fetch_output` message is sent to the client whenever an instance of [`AdditionalOutputs`](../streams/#additional-outputs) is available. You can access the latest output data by calling the `fetch_latest_output` method of the `Stream` object.
|
||||
|
||||
However, rather than fetching each output manually, a common pattern is to fetch the entire stream of output data by calling the `output_stream` method.
|
||||
|
||||
Here is an example:
|
||||
```python
|
||||
from fastapi.responses import StreamingResponse
|
||||
|
||||
@app.get("/updates")
|
||||
async def stream_updates(webrtc_id: str):
|
||||
async def output_stream():
|
||||
async for output in stream.output_stream(webrtc_id):
|
||||
# Output is the AdditionalOutputs instance
|
||||
# Be sure to serialize it however you would like
|
||||
yield f"data: {output.args[0]}\n\n"
|
||||
|
||||
return StreamingResponse(
|
||||
output_stream(),
|
||||
media_type="text/event-stream"
|
||||
)
|
||||
```
|
||||
|
||||
### Handling Errors
|
||||
|
||||
When connecting via `WebRTC`, the server will respond to the `/webrtc/offer` route with a JSON response. If there are too many connections, the server will respond with a 200 error.
|
||||
|
||||
```json
|
||||
{
|
||||
"status": "failed",
|
||||
"meta": {
|
||||
"error": "concurrency_limit_reached",
|
||||
"limit": 10
|
||||
}
|
||||
```
|
||||
|
||||
Over `WebSocket`, the server will send the same message before closing the connection.
|
||||
|
||||
!!! tip
|
||||
The server will sends a 200 status code because otherwise the gradio client will not be able to process the json response and display the error.
|
||||
|
||||
<style>
|
||||
.config-selector {
|
||||
margin: 1em 0;
|
||||
display: flex;
|
||||
gap: 2em;
|
||||
}
|
||||
|
||||
.select-group {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.5em;
|
||||
}
|
||||
|
||||
.select-group label {
|
||||
font-size: 0.8em;
|
||||
font-weight: 600;
|
||||
color: var(--md-default-fg-color--light);
|
||||
}
|
||||
|
||||
.select-group select {
|
||||
padding: 0.5em;
|
||||
border: 1px solid var(--md-default-fg-color--lighter);
|
||||
border-radius: 4px;
|
||||
background-color: var(--md-code-bg-color);
|
||||
color: var(--md-code-fg-color);
|
||||
width: 150px;
|
||||
font-size: 0.9em;
|
||||
}
|
||||
|
||||
/* Style code blocks to match site theme */
|
||||
.rendered-content pre {
|
||||
background-color: var(--md-code-bg-color) !important;
|
||||
color: var(--md-code-fg-color) !important;
|
||||
padding: 1em;
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
.rendered-content code {
|
||||
font-family: var(--md-code-font-family);
|
||||
background-color: var(--md-code-bg-color) !important;
|
||||
color: var(--md-code-fg-color) !important;
|
||||
}
|
||||
</style>
|
||||
|
||||
<script>
|
||||
|
||||
// doT.js
|
||||
// 2011-2014, Laura Doktorova, https://github.com/olado/doT
|
||||
// Licensed under the MIT license.
|
||||
|
||||
|
||||
var doT = {
|
||||
name: "doT",
|
||||
version: "1.1.1",
|
||||
templateSettings: {
|
||||
evaluate: /\{\{([\s\S]+?(\}?)+)\}\}/g,
|
||||
interpolate: /\{\{=([\s\S]+?)\}\}/g,
|
||||
encode: /\{\{!([\s\S]+?)\}\}/g,
|
||||
use: /\{\{#([\s\S]+?)\}\}/g,
|
||||
useParams: /(^|[^\w$])def(?:\.|\[[\'\"])([\w$\.]+)(?:[\'\"]\])?\s*\:\s*([\w$\.]+|\"[^\"]+\"|\'[^\']+\'|\{[^\}]+\})/g,
|
||||
define: /\{\{##\s*([\w\.$]+)\s*(\:|=)([\s\S]+?)#\}\}/g,
|
||||
defineParams: /^\s*([\w$]+):([\s\S]+)/,
|
||||
conditional: /\{\{\?(\?)?\s*([\s\S]*?)\s*\}\}/g,
|
||||
iterate: /\{\{~\s*(?:\}\}|([\s\S]+?)\s*\:\s*([\w$]+)\s*(?:\:\s*([\w$]+))?\s*\}\})/g,
|
||||
varname: "it",
|
||||
strip: false,
|
||||
append: true,
|
||||
selfcontained: false,
|
||||
doNotSkipEncoded: false
|
||||
},
|
||||
template: undefined, //fn, compile template
|
||||
compile: undefined, //fn, for express
|
||||
log: true
|
||||
}, _globals;
|
||||
|
||||
doT.encodeHTMLSource = function (doNotSkipEncoded) {
|
||||
var encodeHTMLRules = { "&": "&", "<": "<", ">": ">", '"': """, "'": "'", "/": "/" },
|
||||
matchHTML = doNotSkipEncoded ? /[&<>"'\/]/g : /&(?!#?\w+;)|<|>|"|'|\//g;
|
||||
return function (code) {
|
||||
return code ? code.toString().replace(matchHTML, function (m) { return encodeHTMLRules[m] || m; }) : "";
|
||||
};
|
||||
};
|
||||
|
||||
_globals = (function () { return this || (0, eval)("this"); }());
|
||||
|
||||
/* istanbul ignore else */
|
||||
if (typeof module !== "undefined" && module.exports) {
|
||||
module.exports = doT;
|
||||
} else if (typeof define === "function" && define.amd) {
|
||||
define(function () { return doT; });
|
||||
} else {
|
||||
_globals.doT = doT;
|
||||
}
|
||||
|
||||
var startend = {
|
||||
append: { start: "'+(", end: ")+'", startencode: "'+encodeHTML(" },
|
||||
split: { start: "';out+=(", end: ");out+='", startencode: "';out+=encodeHTML(" }
|
||||
}, skip = /$^/;
|
||||
|
||||
function resolveDefs(c, block, def) {
|
||||
return ((typeof block === "string") ? block : block.toString())
|
||||
.replace(c.define || skip, function (m, code, assign, value) {
|
||||
if (code.indexOf("def.") === 0) {
|
||||
code = code.substring(4);
|
||||
}
|
||||
if (!(code in def)) {
|
||||
if (assign === ":") {
|
||||
if (c.defineParams) value.replace(c.defineParams, function (m, param, v) {
|
||||
def[code] = { arg: param, text: v };
|
||||
});
|
||||
if (!(code in def)) def[code] = value;
|
||||
} else {
|
||||
new Function("def", "def['" + code + "']=" + value)(def);
|
||||
}
|
||||
}
|
||||
return "";
|
||||
})
|
||||
.replace(c.use || skip, function (m, code) {
|
||||
if (c.useParams) code = code.replace(c.useParams, function (m, s, d, param) {
|
||||
if (def[d] && def[d].arg && param) {
|
||||
var rw = (d + ":" + param).replace(/'|\\/g, "_");
|
||||
def.__exp = def.__exp || {};
|
||||
def.__exp[rw] = def[d].text.replace(new RegExp("(^|[^\\w$])" + def[d].arg + "([^\\w$])", "g"), "$1" + param + "$2");
|
||||
return s + "def.__exp['" + rw + "']";
|
||||
}
|
||||
});
|
||||
var v = new Function("def", "return " + code)(def);
|
||||
return v ? resolveDefs(c, v, def) : v;
|
||||
});
|
||||
}
|
||||
|
||||
function unescape(code) {
|
||||
return code.replace(/\\('|\\)/g, "$1").replace(/[\r\t\n]/g, " ");
|
||||
}
|
||||
|
||||
doT.template = function (tmpl, c, def) {
|
||||
c = c || doT.templateSettings;
|
||||
var cse = c.append ? startend.append : startend.split, needhtmlencode, sid = 0, indv,
|
||||
str = (c.use || c.define) ? resolveDefs(c, tmpl, def || {}) : tmpl;
|
||||
|
||||
str = ("var out='" + (c.strip ? str.replace(/(^|\r|\n)\t* +| +\t*(\r|\n|$)/g, " ")
|
||||
.replace(/\r|\n|\t|\/\*[\s\S]*?\*\//g, "") : str)
|
||||
.replace(/'|\\/g, "\\$&")
|
||||
.replace(c.interpolate || skip, function (m, code) {
|
||||
return cse.start + unescape(code) + cse.end;
|
||||
})
|
||||
.replace(c.encode || skip, function (m, code) {
|
||||
needhtmlencode = true;
|
||||
return cse.startencode + unescape(code) + cse.end;
|
||||
})
|
||||
.replace(c.conditional || skip, function (m, elsecase, code) {
|
||||
return elsecase ?
|
||||
(code ? "';}else if(" + unescape(code) + "){out+='" : "';}else{out+='") :
|
||||
(code ? "';if(" + unescape(code) + "){out+='" : "';}out+='");
|
||||
})
|
||||
.replace(c.iterate || skip, function (m, iterate, vname, iname) {
|
||||
if (!iterate) return "';} } out+='";
|
||||
sid += 1; indv = iname || "i" + sid; iterate = unescape(iterate);
|
||||
return "';var arr" + sid + "=" + iterate + ";if(arr" + sid + "){var " + vname + "," + indv + "=-1,l" + sid + "=arr" + sid + ".length-1;while(" + indv + "<l" + sid + "){"
|
||||
+ vname + "=arr" + sid + "[" + indv + "+=1];out+='";
|
||||
})
|
||||
.replace(c.evaluate || skip, function (m, code) {
|
||||
return "';" + unescape(code) + "out+='";
|
||||
})
|
||||
+ "';return out;")
|
||||
.replace(/\n/g, "\\n").replace(/\t/g, '\\t').replace(/\r/g, "\\r")
|
||||
.replace(/(\s|;|\}|^|\{)out\+='';/g, '$1').replace(/\+''/g, "");
|
||||
//.replace(/(\s|;|\}|^|\{)out\+=''\+/g,'$1out+=');
|
||||
|
||||
if (needhtmlencode) {
|
||||
if (!c.selfcontained && _globals && !_globals._encodeHTML) _globals._encodeHTML = doT.encodeHTMLSource(c.doNotSkipEncoded);
|
||||
str = "var encodeHTML = typeof _encodeHTML !== 'undefined' ? _encodeHTML : ("
|
||||
+ doT.encodeHTMLSource.toString() + "(" + (c.doNotSkipEncoded || '') + "));"
|
||||
+ str;
|
||||
}
|
||||
try {
|
||||
return new Function(c.varname, str);
|
||||
} catch (e) {
|
||||
/* istanbul ignore else */
|
||||
if (typeof console !== "undefined") console.log("Could not create a template function: " + str);
|
||||
throw e;
|
||||
}
|
||||
};
|
||||
|
||||
doT.compile = function (tmpl, def) {
|
||||
return doT.template(tmpl, null, def);
|
||||
};
|
||||
|
||||
// WebRTC template
|
||||
|
||||
const webrtcTemplate = doT.template(`
|
||||
To connect to the server, you need to create a new RTCPeerConnection object and call the \`setupWebRTC\` function below.
|
||||
{{? it.mode === "send-receive" || it.mode === "receive" }}
|
||||
This code snippet assumes there is an html element with an id of \`{{=it.modality}}_output_component_id\` where the output will be displayed. It should be {{? it.modality === "audio"}}a \`<audio>\`{{??}}an \`<video>\`{{?}} element.
|
||||
{{?}}
|
||||
|
||||
\`\`\`javascript
|
||||
// pass any rtc_configuration params here
|
||||
const pc = new RTCPeerConnection();
|
||||
{{? it.mode === "send-receive" || it.mode === "receive" }}
|
||||
const {{=it.modality}}_output_component = document.getElementById("{{=it.modality}}_output_component_id");
|
||||
{{?}}
|
||||
async function setupWebRTC(peerConnection) {
|
||||
{{? it.mode === "send-receive" || it.mode === "send" }}
|
||||
// Get {{=it.modality}} stream from webcam
|
||||
const stream = await navigator.mediaDevices.getUserMedia({
|
||||
{{=it.modality}}: true,
|
||||
})
|
||||
{{?}}
|
||||
{{? it.mode === "send-receive" }}
|
||||
// Send {{=it.modality}} stream to server
|
||||
stream.getTracks().forEach(async (track) => {
|
||||
const sender = pc.addTrack(track, stream);
|
||||
})
|
||||
{{?? it.mode === "send" }}
|
||||
// Receive {{=it.modality}} stream from server
|
||||
pc.addTransceiver({{=it.modality}}, { direction: "recvonly" })
|
||||
{{?}}
|
||||
{{? it.mode === "send-receive" || it.mode === "receive" }}
|
||||
peerConnection.addEventListener("track", (evt) => {
|
||||
if ({{=it.modality}}_output_component &&
|
||||
{{=it.modality}}_output_component.srcObject !== evt.streams[0]) {
|
||||
{{=it.modality}}_output_component.srcObject = evt.streams[0];
|
||||
}
|
||||
});
|
||||
{{?}}
|
||||
// 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);
|
||||
}
|
||||
\`\`\`
|
||||
`);
|
||||
|
||||
// WebSocket template
|
||||
const wsTemplate = doT.template(`
|
||||
{{? it.modality !== "audio" || it.mode !== "send-receive" }}
|
||||
WebSocket connections are currently only supported for audio in send-receive mode.
|
||||
{{??}}
|
||||
|
||||
To connect to the server via WebSocket, you'll need to establish a WebSocket connection and handle audio processing. The code below assumes there is an HTML audio element for output playback.
|
||||
|
||||
\`\`\`javascript
|
||||
// Setup audio context and stream
|
||||
const audioContext = new AudioContext();
|
||||
const stream = await navigator.mediaDevices.getUserMedia({
|
||||
audio: true
|
||||
});
|
||||
|
||||
// Create WebSocket connection
|
||||
const ws = new WebSocket(\`\${window.location.protocol === 'https:' ? 'wss:' : 'ws:'}//$\{window.location.host}/websocket/offer\`);
|
||||
|
||||
ws.onopen = () => {
|
||||
// Send initial start message with unique ID
|
||||
ws.send(JSON.stringify({
|
||||
event: "start",
|
||||
websocket_id: generateId() // Implement your own ID generator
|
||||
}));
|
||||
|
||||
// Setup audio processing
|
||||
const source = audioContext.createMediaStreamSource(stream);
|
||||
const processor = audioContext.createScriptProcessor(2048, 1, 1);
|
||||
source.connect(processor);
|
||||
processor.connect(audioContext.destination);
|
||||
|
||||
processor.onaudioprocess = (e) => {
|
||||
const inputData = e.inputBuffer.getChannelData(0);
|
||||
const mulawData = convertToMulaw(inputData, audioContext.sampleRate);
|
||||
const base64Audio = btoa(String.fromCharCode.apply(null, mulawData));
|
||||
|
||||
if (ws.readyState === WebSocket.OPEN) {
|
||||
ws.send(JSON.stringify({
|
||||
event: "media",
|
||||
media: {
|
||||
payload: base64Audio
|
||||
}
|
||||
}));
|
||||
}
|
||||
};
|
||||
};
|
||||
\`\`\`
|
||||
{{?}}
|
||||
`);
|
||||
|
||||
function updateDocs() {
|
||||
// Get selected values
|
||||
const modality = document.getElementById('modality').value;
|
||||
const mode = document.getElementById('mode').value;
|
||||
const connection = document.getElementById('connection').value;
|
||||
|
||||
// Context for templates
|
||||
const context = {
|
||||
modality: modality,
|
||||
mode: mode,
|
||||
additional_inputs: true,
|
||||
additional_outputs: true
|
||||
};
|
||||
|
||||
// Choose template based on connection type
|
||||
const template = connection === 'webrtc' ? webrtcTemplate : wsTemplate;
|
||||
|
||||
// Render docs with syntax highlighting
|
||||
const html = template(context);
|
||||
const docsDiv = document.getElementById('docs');
|
||||
docsDiv.innerHTML = marked.parse(html);
|
||||
docsDiv.className = 'rendered-content';
|
||||
|
||||
// Initialize any code blocks that were just added
|
||||
document.querySelectorAll('pre code').forEach((block) => {
|
||||
hljs.highlightElement(block);
|
||||
});
|
||||
}
|
||||
|
||||
// Initial render
|
||||
document.addEventListener('DOMContentLoaded', updateDocs);
|
||||
</script>
|
||||
|
||||
27
docs/userguide/audio-video.md
Normal file
27
docs/userguide/audio-video.md
Normal file
@@ -0,0 +1,27 @@
|
||||
# Audio-Video Streaming
|
||||
|
||||
You can simultaneously stream audio and video using `AudioVideoStreamHandler` or `AsyncAudioVideoStreamHandler`.
|
||||
They are identical to the audio `StreamHandlers` with the addition of `video_receive` and `video_emit` methods which take and return a `numpy` array, respectively.
|
||||
|
||||
Here is an example of the video handling functions for connecting with the Gemini multimodal API. In this case, we simply reflect the webcam feed back to the user but every second we'll send the latest webcam frame (and an additional image component) to the Gemini server.
|
||||
|
||||
Please see the "Gemini Audio Video Chat" example in the [cookbook](../../cookbook) for the complete code.
|
||||
|
||||
``` python title="Async Gemini Video Handling"
|
||||
|
||||
async def video_receive(self, frame: np.ndarray):
|
||||
"""Send video frames to the server"""
|
||||
if self.session:
|
||||
# send image every 1 second
|
||||
# otherwise we flood the API
|
||||
if time.time() - self.last_frame_time > 1:
|
||||
self.last_frame_time = time.time()
|
||||
await self.session.send(encode_image(frame))
|
||||
if self.latest_args[2] is not None:
|
||||
await self.session.send(encode_image(self.latest_args[2]))
|
||||
self.video_queue.put_nowait(frame)
|
||||
|
||||
async def video_emit(self) -> VideoEmitType:
|
||||
"""Return video frames to the client"""
|
||||
return await self.video_queue.get()
|
||||
```
|
||||
388
docs/userguide/audio.md
Normal file
388
docs/userguide/audio.md
Normal file
@@ -0,0 +1,388 @@
|
||||
|
||||
## Reply On Pause
|
||||
|
||||
Typically, you want to run a python function whenever a user has stopped speaking. This can be done by wrapping a python generator with the `ReplyOnPause` class and passing it to the `handler` argument of the `Stream` object. The `ReplyOnPause` class will handle the voice detection and turn taking logic automatically!
|
||||
|
||||
|
||||
=== "Code"
|
||||
```python
|
||||
from fastrtc import ReplyOnPause, Stream
|
||||
|
||||
def response(audio: tuple[int, np.ndarray]): # (1)
|
||||
sample_rate, audio_array = audio
|
||||
# Generate response
|
||||
for audio_chunk in generate_response(sample_rate, audio_array):
|
||||
yield (sample_rate, audio_chunk) # (2)
|
||||
|
||||
stream = Stream(
|
||||
handler=ReplyOnPause(response),
|
||||
modality="audio",
|
||||
mode="send-receive"
|
||||
)
|
||||
```
|
||||
|
||||
1. The python generator will receive the **entire** audio up until the user stopped. It will be a tuple of the form (sampling_rate, numpy array of audio). The array will have a shape of (1, num_samples). You can also pass in additional input components.
|
||||
|
||||
2. The generator must yield audio chunks as a tuple of (sampling_rate, numpy audio array). Each numpy audio array must have a shape of (1, num_samples).
|
||||
|
||||
=== "Notes"
|
||||
1. The python generator will receive the **entire** audio up until the user stopped. It will be a tuple of the form (sampling_rate, numpy array of audio). The array will have a shape of (1, num_samples). You can also pass in additional input components.
|
||||
|
||||
2. The generator must yield audio chunks as a tuple of (sampling_rate, numpy audio array). Each numpy audio array must have a shape of (1, num_samples).
|
||||
|
||||
!!! tip "Asynchronous"
|
||||
You can also use an async generator with `ReplyOnPause`.
|
||||
|
||||
!!! tip "Parameters"
|
||||
You can customize the voice detection parameters by passing in `algo_options` and `model_options` to the `ReplyOnPause` class.
|
||||
```python
|
||||
from fastrtc import AlgoOptions, SileroVadOptions
|
||||
|
||||
stream = Stream(
|
||||
handler=ReplyOnPause(
|
||||
response,
|
||||
algo_options=AlgoOptions(
|
||||
audio_chunk_duration=0.6,
|
||||
started_talking_threshold=0.2,
|
||||
speech_threshold=0.1
|
||||
),
|
||||
model_options=SileroVadOptions(
|
||||
threshold=0.5,
|
||||
min_speech_duration_ms=250,
|
||||
min_silence_duration_ms=100
|
||||
)
|
||||
)
|
||||
)
|
||||
```
|
||||
|
||||
### Interruptions
|
||||
|
||||
By default, the `ReplyOnPause` handler will allow you to interrupt the response at any time by speaking again. If you do not want to allow interruption, you can set the `can_interrupt` parameter to `False`.
|
||||
|
||||
```python
|
||||
from fastrtc import Stream, ReplyOnPause
|
||||
|
||||
stream = Stream(
|
||||
handler=ReplyOnPause(
|
||||
response,
|
||||
can_interrupt=True,
|
||||
)
|
||||
)
|
||||
```
|
||||
|
||||
<video width=98% src="https://github.com/user-attachments/assets/dba68dd7-7444-439b-b948-59171067e850" controls style="text-align: center"></video>
|
||||
|
||||
|
||||
!!! tip "Muting Response Audio"
|
||||
You can directly talk over the output audio and the interruption will still work. However, in these cases, the audio transcription may be incorrect. To prevent this, it's best practice to mute the output audio before talking over it.
|
||||
|
||||
### Startup Function
|
||||
|
||||
You can pass in a `startup_fn` to the `ReplyOnPause` class. This function will be called when the connection is first established. It is helpful for generating intial responses.
|
||||
|
||||
```python
|
||||
from fastrtc import get_tts_model, Stream, ReplyOnPause
|
||||
|
||||
tts_client = get_tts_model()
|
||||
|
||||
|
||||
def detection(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(detection, startup_fn=startup),
|
||||
modality="audio",
|
||||
mode="send-receive",
|
||||
ui_args={"title": "Echo Audio"},
|
||||
)
|
||||
```
|
||||
|
||||
<video width=98% src="https://github.com/user-attachments/assets/c6b1cb51-5790-4522-80c3-e24e58ef9f11" controls style="text-align: center"></video>
|
||||
|
||||
## Reply On Stopwords
|
||||
|
||||
You can configure your AI model to run whenever a set of "stop words" are detected, like "Hey Siri" or "computer", with the `ReplyOnStopWords` class.
|
||||
|
||||
The API is similar to `ReplyOnPause` with the addition of a `stop_words` parameter.
|
||||
|
||||
=== "Code"
|
||||
``` py
|
||||
from fastrtc import Stream, ReplyOnStopWords
|
||||
|
||||
def response(audio: tuple[int, np.ndarray]):
|
||||
"""This function must yield audio frames"""
|
||||
...
|
||||
for numpy_array in generated_audio:
|
||||
yield (sampling_rate, numpy_array, "mono")
|
||||
|
||||
stream = Stream(
|
||||
handler=ReplyOnStopWords(generate,
|
||||
input_sample_rate=16000,
|
||||
stop_words=["computer"]), # (1)
|
||||
modality="audio",
|
||||
mode="send-receive"
|
||||
)
|
||||
```
|
||||
|
||||
1. The `stop_words` can be single words or pairs of words. Be sure to include common misspellings of your word for more robust detection, e.g. "llama", "lamma". In my experience, it's best to use two very distinct words like "ok computer" or "hello iris".
|
||||
|
||||
=== "Notes"
|
||||
1. The `stop_words` can be single words or pairs of words. Be sure to include common misspellings of your word for more robust detection, e.g. "llama", "lamma". In my experience, it's best to use two very distinct words like "ok computer" or "hello iris".
|
||||
|
||||
!!! tip "Extra Dependencies"
|
||||
The `ReplyOnStopWords` class requires the the `stopword` extra. Run `pip install fastrtc[stopword]` to install it.
|
||||
|
||||
!!! warning "English Only"
|
||||
The `ReplyOnStopWords` class is currently only supported for English.
|
||||
|
||||
## Stream Handler
|
||||
|
||||
`ReplyOnPause` and `ReplyOnStopWords` are implementations of a `StreamHandler`. The `StreamHandler` is a low-level abstraction that gives you arbitrary control over how the input audio stream and output audio stream are created. The following example echos back the user audio.
|
||||
|
||||
=== "Code"
|
||||
``` py
|
||||
import gradio as gr
|
||||
from gradio_webrtc import WebRTC, StreamHandler
|
||||
from queue import Queue
|
||||
|
||||
class EchoHandler(StreamHandler):
|
||||
def __init__(self) -> None:
|
||||
super().__init__()
|
||||
self.queue = Queue()
|
||||
|
||||
def receive(self, frame: tuple[int, np.ndarray]) -> None: # (1)
|
||||
self.queue.put(frame)
|
||||
|
||||
def emit(self) -> None: # (2)
|
||||
return self.queue.get()
|
||||
|
||||
def copy(self) -> StreamHandler:
|
||||
return EchoHandler()
|
||||
|
||||
def shutdown(self) -> None: # (3)
|
||||
pass
|
||||
|
||||
def start_up(self) -> None: # (4)
|
||||
pass
|
||||
|
||||
stream = Stream(
|
||||
handler=EchoHandler(),
|
||||
modality="audio",
|
||||
mode="send-receive"
|
||||
)
|
||||
```
|
||||
|
||||
1. The `StreamHandler` class implements three methods: `receive`, `emit` and `copy`. 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. The `copy` method is called at the beginning of the stream to ensure each user has a unique stream handler.
|
||||
2. The `emit` method SHOULD NOT block. If a frame is not ready to be sent, the method should return `None`. If you need to wait for a frame, use [`wait_for_item`](../../utils#wait_for_item) from the `utils` module.
|
||||
3. The `shutdown` method is called when the stream is closed. It should be used to clean up any resources.
|
||||
4. The `start_up` method is called when the stream is first created. It should be used to initialize any resources. See [Talk To OpenAI](https://huggingface.co/spaces/fastrtc/talk-to-openai-gradio) or [Talk To Gemini](https://huggingface.co/spaces/fastrtc/talk-to-gemini-gradio) for an example of a `StreamHandler` that uses the `start_up` method to connect to an API.
|
||||
=== "Notes"
|
||||
1. The `StreamHandler` class implements three methods: `receive`, `emit` and `copy`. 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. The `copy` method is called at the beginning of the stream to ensure each user has a unique stream handler.
|
||||
2. The `emit` method SHOULD NOT block. If a frame is not ready to be sent, the method should return `None`. If you need to wait for a frame, use [`wait_for_item`](../../utils#wait_for_item) from the `utils` module.
|
||||
3. The `shutdown` method is called when the stream is closed. It should be used to clean up any resources.
|
||||
4. The `start_up` method is called when the stream is first created. It should be used to initialize any resources. See [Talk To OpenAI](https://huggingface.co/spaces/fastrtc/talk-to-openai-gradio) or [Talk To Gemini](https://huggingface.co/spaces/fastrtc/talk-to-gemini-gradio) for an example of a `StreamHandler` that uses the `start_up` method to connect to an API.
|
||||
|
||||
!!! tip
|
||||
See this [Talk To Gemini](https://huggingface.co/spaces/fastrtc/talk-to-gemini-gradio) for a complete example of a more complex stream handler.
|
||||
|
||||
!!! warning
|
||||
The `emit` method should not block. If you need to wait for a frame, use [`wait_for_item`](../../utils#wait_for_item) from the `utils` module.
|
||||
|
||||
## Async Stream Handlers
|
||||
|
||||
It is also possible to create asynchronous stream handlers. This is very convenient for accessing async APIs from major LLM developers, like Google and OpenAI. The main difference is that `receive`, `emit`, and `start_up` are now defined with `async def`.
|
||||
|
||||
Here is aa simple example of using `AsyncStreamHandler`:
|
||||
|
||||
=== "Code"
|
||||
``` py
|
||||
from fastrtc import AsyncStreamHandler, wait_for_item, Stream
|
||||
import asyncio
|
||||
import numpy as np
|
||||
|
||||
class AsyncEchoHandler(AsyncStreamHandler):
|
||||
"""Simple Async Echo Handler"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
super().__init__(input_sample_rate=24000)
|
||||
self.queue = asyncio.Queue()
|
||||
|
||||
async def receive(self, frame: tuple[int, np.ndarray]) -> None:
|
||||
await self.queue.put(frame)
|
||||
|
||||
async def emit(self) -> None:
|
||||
return await wait_for_item(self.queue)
|
||||
|
||||
def copy(self):
|
||||
return AsyncEchoHandler()
|
||||
|
||||
async def shutdown(self):
|
||||
pass
|
||||
|
||||
async def start_up(self) -> None:
|
||||
pass
|
||||
```
|
||||
|
||||
!!! tip
|
||||
See [Talk To Gemini](https://huggingface.co/spaces/fastrtc/talk-to-gemini), [Talk To Openai](https://huggingface.co/spaces/fastrtc/talk-to-openai) for complete examples of `AsyncStreamHandler`s.
|
||||
|
||||
|
||||
## Text To Speech
|
||||
|
||||
You can use an on-device text to speech model if you have the `tts` extra installed.
|
||||
Import the `get_tts_model` function and call it with the model name you want to use.
|
||||
At the moment, the only model supported is `kokoro`.
|
||||
|
||||
The `get_tts_model` function returns an object with three methods:
|
||||
|
||||
- `tts`: Synchronous text to speech.
|
||||
- `stream_tts_sync`: Synchronous text to speech streaming.
|
||||
- `stream_tts`: Asynchronous text to speech streaming.
|
||||
|
||||
```python
|
||||
from fastrtc import get_tts_model
|
||||
|
||||
model = get_tts_model(model="kokoro")
|
||||
|
||||
for audio in model.stream_tts_sync("Hello, world!"):
|
||||
yield audio
|
||||
|
||||
async for audio in model.stream_tts("Hello, world!"):
|
||||
yield audio
|
||||
|
||||
audio = model.tts("Hello, world!")
|
||||
```
|
||||
|
||||
!!! tip
|
||||
You can customize the audio by passing in an instace of `KokoroTTSOptions` to the method.
|
||||
See [here](https://huggingface.co/hexgrad/Kokoro-82M/blob/main/VOICES.md) for a list of available voices.
|
||||
```python
|
||||
from fastrtc import KokoroTTSOptions, get_tts_model
|
||||
|
||||
model = get_tts_model(model="kokoro")
|
||||
|
||||
options = KokoroTTSOptions(
|
||||
voice="af_heart",
|
||||
speed=1.0,
|
||||
lang="en-us"
|
||||
)
|
||||
|
||||
audio = model.tts("Hello, world!", options=options)
|
||||
```
|
||||
|
||||
## Speech To Text
|
||||
|
||||
You can use an on-device speech to text model if you have the `stt` or `stopword` extra installed.
|
||||
Import the `get_stt_model` function and call it with the model name you want to use.
|
||||
At the moment, the only models supported are `moonshine/base` and `moonshine/tiny`.
|
||||
|
||||
The `get_stt_model` function returns an object with the following method:
|
||||
|
||||
- `stt`: Synchronous speech to text.
|
||||
|
||||
```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)
|
||||
```
|
||||
|
||||
!!! tip "Example"
|
||||
See [LLM Voice Chat](https://huggingface.co/spaces/fastrtc/llm-voice-chat) for an example of using the `stt` method in a `ReplyOnPause` handler.
|
||||
|
||||
!!! warning "English Only"
|
||||
The `stt` model is currently only supported for English.
|
||||
|
||||
## Requesting Inputs
|
||||
|
||||
In `ReplyOnPause` and `ReplyOnStopWords`, any additional input data is automatically passed to your generator. For `StreamHandler`s, you must manually request the input data from the client.
|
||||
|
||||
You can do this by calling `await self.wait_for_args()` (for `AsyncStreamHandler`s) in either the `emit` or `receive` methods. For a `StreamHandler`, you can call `self.wait_for_args_sync()`.
|
||||
|
||||
|
||||
We can access the value of this component via the `latest_args` property of the `StreamHandler`. The `latest_args` is a list storing each of the values. The 0th index is the dummy string `__webrtc_value__`.
|
||||
|
||||
## Considerations for Telephone Use
|
||||
|
||||
In order for your handler to work over the phone, you must make sure that your handler is not expecting any additional input data besides the audio.
|
||||
|
||||
If you call `await self.wait_for_args()` your stream will wait forever for the additional input data.
|
||||
|
||||
The stream handlers have a `phone_mode` property that is set to `True` if the stream is running over the phone. You can use this property to determine if you should wait for additional input data.
|
||||
|
||||
```python
|
||||
def emit(self):
|
||||
if self.phone_mode:
|
||||
self.latest_args = [None]
|
||||
else:
|
||||
await self.wait_for_args()
|
||||
```
|
||||
|
||||
### `ReplyOnPause` and telephone use
|
||||
|
||||
The generator you pass to `ReplyOnPause` must have default arguments for all arguments except audio.
|
||||
|
||||
If you yield `AdditionalOutputs`, they will be passed in as the input arguments to the generator the next time it is called.
|
||||
|
||||
!!! tip
|
||||
See [Talk To Claude](https://huggingface.co/spaces/fastrtc/talk-to-claude) for an example of a `ReplyOnPause` handler that is compatible with telephone usage. Notice how the input chatbot history is yielded as an `AdditionalOutput` on each invocation.
|
||||
|
||||
## Telephone Integration
|
||||
|
||||
You can integrate a `Stream` with a SIP provider like Twilio to set up your own phone number for your application.
|
||||
|
||||
### Setup Process
|
||||
|
||||
1. **Create a Twilio Account**: Sign up for a [Twilio](https://login.twilio.com/u/signup) account and purchase a phone number with voice capabilities. With a trial account, only the phone number you used during registration will be able to connect to your `Stream`.
|
||||
|
||||
2. **Mount Your Stream**: Add your `Stream` to a FastAPI app using `stream.mount(app)` and run the server.
|
||||
|
||||
3. **Configure Twilio Webhook**: Point your Twilio phone number to your webhook URL.
|
||||
|
||||
### Configuring Twilio
|
||||
|
||||
To configure your Twilio phone number:
|
||||
|
||||
1. In your Twilio dashboard, navigate to `Manage` → `TwiML Apps` in the left sidebar
|
||||
2. Click `Create TwiML App`
|
||||
3. Set the `Voice URL` to your FastAPI app's URL with `/telephone/incoming` appended (e.g., `https://your-app-url.com/telephone/incoming`)
|
||||
|
||||

|
||||

|
||||
|
||||
!!! tip "Local Development with Ngrok"
|
||||
For local development, use [ngrok](https://ngrok.com/) to expose your local server:
|
||||
```bash
|
||||
ngrok http <port>
|
||||
```
|
||||
Then set your Twilio Voice URL to `https://your-ngrok-subdomain.ngrok.io/telephone/incoming-call`
|
||||
|
||||
### Code Example
|
||||
|
||||
Here's a simple example of setting up a Twilio endpoint:
|
||||
|
||||
|
||||
```py
|
||||
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`
|
||||
```
|
||||
96
docs/userguide/gradio.md
Normal file
96
docs/userguide/gradio.md
Normal file
@@ -0,0 +1,96 @@
|
||||
# Gradio Component
|
||||
|
||||
The automatic gradio UI is a great way to test your stream. However, you may want to customize the UI to your liking or simply build a standalone Gradio application.
|
||||
|
||||
## The WebRTC Component
|
||||
|
||||
To build a standalone Gradio application, you can use the `WebRTC` component and implement the `stream` event.
|
||||
Similarly to the `Stream` object, you must set the `mode` and `modality` arguments and pass in a `handler`.
|
||||
|
||||
In the `stream` event, you pass in your handler as well as the input and output components.
|
||||
|
||||
``` py
|
||||
import gradio as gr
|
||||
from fastrtc import WebRTC, ReplyOnPause
|
||||
|
||||
def response(audio: tuple[int, np.ndarray]):
|
||||
"""This function must yield audio frames"""
|
||||
...
|
||||
yield audio
|
||||
|
||||
|
||||
with gr.Blocks() as demo:
|
||||
gr.HTML(
|
||||
"""
|
||||
<h1 style='text-align: center'>
|
||||
Chat (Powered by WebRTC ⚡️)
|
||||
</h1>
|
||||
"""
|
||||
)
|
||||
with gr.Column():
|
||||
with gr.Group():
|
||||
audio = WebRTC(
|
||||
mode="send-receive",
|
||||
modality="audio",
|
||||
)
|
||||
audio.stream(fn=ReplyOnPause(response),
|
||||
inputs=[audio], outputs=[audio],
|
||||
time_limit=60)
|
||||
demo.launch()
|
||||
```
|
||||
|
||||
## Additional Outputs
|
||||
|
||||
In order to modify other components from within the WebRTC stream, you must yield an instance of `AdditionalOutputs` and add an `on_additional_outputs` event to the `WebRTC` component.
|
||||
|
||||
This is common for displaying a multimodal text/audio conversation in a Chatbot UI.
|
||||
|
||||
=== "Code"
|
||||
|
||||
``` py title="Additional Outputs"
|
||||
from fastrtc import AdditionalOutputs, WebRTC
|
||||
|
||||
def transcribe(audio: tuple[int, np.ndarray],
|
||||
transformers_convo: list[dict],
|
||||
gradio_convo: list[dict]):
|
||||
response = model.generate(**inputs, max_length=256)
|
||||
transformers_convo.append({"role": "assistant", "content": response})
|
||||
gradio_convo.append({"role": "assistant", "content": response})
|
||||
yield AdditionalOutputs(transformers_convo, gradio_convo) # (1)
|
||||
|
||||
|
||||
with gr.Blocks() as demo:
|
||||
gr.HTML(
|
||||
"""
|
||||
<h1 style='text-align: center'>
|
||||
Talk to Qwen2Audio (Powered by WebRTC ⚡️)
|
||||
</h1>
|
||||
"""
|
||||
)
|
||||
transformers_convo = gr.State(value=[])
|
||||
with gr.Row():
|
||||
with gr.Column():
|
||||
audio = WebRTC(
|
||||
label="Stream",
|
||||
mode="send", # (2)
|
||||
modality="audio",
|
||||
)
|
||||
with gr.Column():
|
||||
transcript = gr.Chatbot(label="transcript", type="messages")
|
||||
|
||||
audio.stream(ReplyOnPause(transcribe),
|
||||
inputs=[audio, transformers_convo, transcript],
|
||||
outputs=[audio], time_limit=90)
|
||||
audio.on_additional_outputs(lambda s,a: (s,a), # (3)
|
||||
outputs=[transformers_convo, transcript],
|
||||
queue=False, show_progress="hidden")
|
||||
demo.launch()
|
||||
```
|
||||
|
||||
1. Pass your data to `AdditionalOutputs` and yield it.
|
||||
2. In this case, no audio is being returned, so we set `mode="send"`. However, if we set `mode="send-receive"`, we could also yield generated audio and `AdditionalOutputs`.
|
||||
3. The `on_additional_outputs` event does not take `inputs`. It's common practice to not run this event on the queue since it is just a quick UI update.
|
||||
=== "Notes"
|
||||
1. Pass your data to `AdditionalOutputs` and yield it.
|
||||
2. In this case, no audio is being returned, so we set `mode="send"`. However, if we set `mode="send-receive"`, we could also yield generated audio and `AdditionalOutputs`.
|
||||
3. The `on_additional_outputs` event does not take `inputs`. It's common practice to not run this event on the queue since it is just a quick UI update.
|
||||
236
docs/userguide/streams.md
Normal file
236
docs/userguide/streams.md
Normal file
@@ -0,0 +1,236 @@
|
||||
# Core Concepts
|
||||
|
||||
|
||||
The core of FastRTC is the `Stream` object. It can be used to stream audio, video, or both.
|
||||
|
||||
Here's a simple example of creating a video stream that flips the video vertically. We'll use it to explain the core concepts of the `Stream` object. Click on the plus icons to get a link to the relevant section.
|
||||
|
||||
```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, # (1)
|
||||
modality="video", # (2)
|
||||
mode="send-receive", # (3)
|
||||
additional_inputs=[
|
||||
gr.Slider(minimum=0, maximum=1, step=0.01, value=0.3) # (4)
|
||||
],
|
||||
additional_outputs=None, # (5)
|
||||
additional_outputs_handler=None # (6)
|
||||
)
|
||||
```
|
||||
|
||||
1. See [Handlers](#handlers) for more information.
|
||||
2. See [Modalities](#modalities) for more information.
|
||||
3. See [Stream Modes](#stream-modes) for more information.
|
||||
4. See [Additional Inputs](#additional-inputs) for more information.
|
||||
5. See [Additional Outputs](#additional-outputs) for more information.
|
||||
6. See [Additional Outputs Handler](#additional-outputs) for more information.
|
||||
7. Mount the `Stream` on a `FastAPI` app with `stream.mount(app)` and you can add custom routes to it. See [Custom Routes and Frontend Integration](#custom-routes-and-frontend-integration) for more information.
|
||||
8. See [Built-in Routes](#built-in-routes) for more information.
|
||||
|
||||
Run:
|
||||
=== "UI"
|
||||
|
||||
```py
|
||||
stream.ui.launch()
|
||||
```
|
||||
=== "FastAPI"
|
||||
|
||||
```py
|
||||
app = FastAPI()
|
||||
stream.mount(app)
|
||||
|
||||
# uvicorn app:app --host 0.0.0.0 --port 8000
|
||||
```
|
||||
|
||||
### Stream Modes
|
||||
|
||||
FastRTC supports three streaming modes:
|
||||
|
||||
- `send-receive`: Bidirectional streaming (default)
|
||||
- `send`: Client-to-server only
|
||||
- `receive`: Server-to-client only
|
||||
|
||||
### Modalities
|
||||
|
||||
FastRTC supports three modalities:
|
||||
|
||||
- `video`: Video streaming
|
||||
- `audio`: Audio streaming
|
||||
- `audio-video`: Combined audio and video streaming
|
||||
|
||||
### Handlers
|
||||
|
||||
The `handler` argument is the main argument of the `Stream` object. A handler should be a function or a class that inherits from `StreamHandler` or `AsyncStreamHandler` depending on the modality and mode.
|
||||
|
||||
|
||||
| Modality | send-receive | send | receive |
|
||||
|----------|--------------|------|----------|
|
||||
| video | Function that takes a video frame and returns a new video frame | Function that takes a video frame and returns a new frame | Function that takes a video frame and returns a new frame |
|
||||
| audio | `StreamHandler` or `AsyncStreamHandler` subclass | `StreamHandler` or `AsyncStreamHandler` subclass | Generator yielding audio frames |
|
||||
| audio-video | `AudioVideoStreamHandler` or `AsyncAudioVideoStreamHandler` subclass | Not Supported Yet | Not Supported Yet |
|
||||
|
||||
|
||||
## Methods
|
||||
|
||||
The `Stream` has three main methods:
|
||||
|
||||
- `.ui.launch()`: Launch a built-in UI for easily testing and sharing your stream. Built with [Gradio](https://www.gradio.app/). You can change the UI by setting the `ui` property of the `Stream` object. Also see the [Gradio guide](../gradio.md) for building Gradio apss with fastrtc.
|
||||
- `.fastphone()`: Get a free temporary phone number to call into your stream. Hugging Face token required.
|
||||
- `.mount(app)`: Mount the stream on a [FastAPI](https://fastapi.tiangolo.com/) app. Perfect for integrating with your already existing production system or for building a custom UI.
|
||||
|
||||
!!! warning
|
||||
Websocket docs are only available for audio streams. Telephone docs are only available for audio streams in `send-receive` mode.
|
||||
|
||||
## Additional Inputs
|
||||
|
||||
You can add additional inputs to your stream using the `additional_inputs` argument. These inputs will be displayed in the generated Gradio UI and they will be passed to the handler as additional arguments.
|
||||
|
||||
!!! tip
|
||||
For audio `StreamHandlers`, please read the special [note](../audio#requesting-inputs) on requesting inputs.
|
||||
|
||||
In the automatic gradio UI, these inputs will be the same python type corresponding to the Gradio component. In our case, we used a `gr.Slider` as the additional input, so it will be passed as a float. See the [Gradio documentation](https://www.gradio.app/docs/gradio) for a complete list of components and their corresponding types.
|
||||
|
||||
### Input Hooks
|
||||
|
||||
Outside of the gradio UI, you are free to update the inputs however you like by using the `set_input` method of the `Stream` object.
|
||||
|
||||
A common pattern is to use a `POST` request to send the updated data.
|
||||
|
||||
```python
|
||||
from pydantic import BaseModel, Field
|
||||
from fastapi import FastAPI
|
||||
|
||||
class InputData(BaseModel):
|
||||
webrtc_id: str
|
||||
conf_threshold: float = Field(ge=0, le=1)
|
||||
|
||||
app = FastAPI()
|
||||
stream.mount(app)
|
||||
|
||||
@app.post("/input_hook")
|
||||
async def _(data: InputData):
|
||||
stream.set_input(data.webrtc_id, data.conf_threshold)
|
||||
```
|
||||
|
||||
The updated data will be passed to the handler on the **next** call.
|
||||
|
||||
|
||||
## Additional Outputs
|
||||
|
||||
You can return additional output from the handler by returning an instance of `AdditionalOutputs` from the handler.
|
||||
Let's modify our previous example to also return the number of detections in the frame.
|
||||
|
||||
```python
|
||||
from fastrtc import Stream, AdditionalOutputs
|
||||
import gradio as gr
|
||||
|
||||
def detection(image, conf_threshold=0.3):
|
||||
processed_frame, n_objects = process_frame(image, conf_threshold)
|
||||
return processed_frame, AdditionalOutputs(n_objects)
|
||||
|
||||
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=[gr.Number()], # (5)
|
||||
additional_outputs_handler=lambda component, n_objects: n_objects
|
||||
)
|
||||
```
|
||||
|
||||
We added a `gr.Number()` to the additional outputs and we provided an `additional_outputs_handler`.
|
||||
|
||||
The `additional_outputs_handler` is **only** needed for the gradio UI. It is a function that takes the current state of the `component` and the instance of `AdditionalOutputs` and returns the updated state of the `component`. In our case, we want to update the `gr.Number()` with the number of detections.
|
||||
|
||||
!!! tip
|
||||
Since the webRTC is very low latency, you probably don't want to return an additional output on each frame.
|
||||
|
||||
### Output Hooks
|
||||
|
||||
Outside of the gradio UI, you are free to access the output data however you like by calling the `output_stream` method of the `Stream` object.
|
||||
|
||||
A common pattern is to use a `GET` request to get a stream of the output data.
|
||||
|
||||
```python
|
||||
from fastapi.responses import StreamingResponse
|
||||
|
||||
@app.get("/updates")
|
||||
async def stream_updates(webrtc_id: str):
|
||||
async def output_stream():
|
||||
async for output in stream.output_stream(webrtc_id):
|
||||
# Output is the AdditionalOutputs instance
|
||||
# Be sure to serialize it however you would like
|
||||
yield f"data: {output.args[0]}\n\n"
|
||||
|
||||
return StreamingResponse(
|
||||
output_stream(),
|
||||
media_type="text/event-stream"
|
||||
)
|
||||
```
|
||||
|
||||
## Custom Routes and Frontend Integration
|
||||
|
||||
You can add custom routes for serving your own frontend or handling additional functionality once you have mounted the stream on a FastAPI app.
|
||||
|
||||
```python
|
||||
from fastapi.responses import HTMLResponse
|
||||
from fastapi import FastAPI
|
||||
from fastrtc import Stream
|
||||
|
||||
stream = Stream(...)
|
||||
|
||||
app = FastAPI()
|
||||
stream.mount(app)
|
||||
|
||||
# Serve a custom frontend
|
||||
@app.get("/")
|
||||
async def serve_frontend():
|
||||
return HTMLResponse(content=open("index.html").read())
|
||||
|
||||
```
|
||||
|
||||
## Telephone Integration
|
||||
|
||||
FastRTC provides built-in telephone support through the `fastphone()` method:
|
||||
|
||||
```python
|
||||
# Launch with a temporary phone number
|
||||
stream.fastphone(
|
||||
# Optional: If None, will use the default token in your machine or read from the HF_TOKEN environment variable
|
||||
token="your_hf_token",
|
||||
host="127.0.0.1",
|
||||
port=8000
|
||||
)
|
||||
```
|
||||
|
||||
This will print out a phone number along with your temporary code you can use to connect to the stream. You are limited to **10 minutes** of calls per calendar month.
|
||||
|
||||
!!! warning
|
||||
|
||||
See this [section](../audio#telephone-integration) on making sure your stream handler is compatible for telephone usage.
|
||||
|
||||
!!! tip
|
||||
|
||||
If you don't have a HF token, you can get one [here](https://huggingface.co/settings/tokens).
|
||||
|
||||
## Concurrency
|
||||
|
||||
1. You can limit the number of concurrent connections by setting the `concurrency_limit` argument.
|
||||
2. You can limit the amount of time (in seconds) a connection can stay open by setting the `time_limit` argument.
|
||||
|
||||
```python
|
||||
stream = Stream(
|
||||
handler=handler,
|
||||
concurrency_limit=10,
|
||||
time_limit=3600
|
||||
)
|
||||
```
|
||||
57
docs/userguide/video.md
Normal file
57
docs/userguide/video.md
Normal file
@@ -0,0 +1,57 @@
|
||||
# Video Streaming
|
||||
|
||||
## Input/Output Streaming
|
||||
|
||||
We already saw this example in the [Quickstart](../../#quickstart) and the [Core Concepts](../streams) section.
|
||||
|
||||
=== "Code"
|
||||
|
||||
``` py title="Input/Output Streaming"
|
||||
from fastrtc import Stream
|
||||
import gradio as gr
|
||||
|
||||
def detection(image, conf_threshold=0.3): # (1)
|
||||
processed_frame = process_frame(image, conf_threshold)
|
||||
return processed_frame # (2)
|
||||
|
||||
stream = Stream(
|
||||
handler=detection,
|
||||
modality="video",
|
||||
mode="send-receive", # (3)
|
||||
additional_inputs=[
|
||||
gr.Slider(minimum=0, maximum=1, step=0.01, value=0.3)
|
||||
],
|
||||
)
|
||||
```
|
||||
|
||||
1. The webcam frame will be represented as a numpy array of shape (height, width, RGB).
|
||||
2. The function must return a numpy array. It can take arbitrary values from other components.
|
||||
3. Set the `modality="video"` and `mode="send-receive"`
|
||||
=== "Notes"
|
||||
1. The webcam frame will be represented as a numpy array of shape (height, width, RGB).
|
||||
2. The function must return a numpy array. It can take arbitrary values from other components.
|
||||
3. Set the `modality="video"` and `mode="send-receive"`
|
||||
|
||||
## Server-to-Client Only
|
||||
|
||||
In this case, we stream from the server to the client so we will write a generator function that yields the next frame from the video (as a numpy array)
|
||||
and set the `mode="receive"` in the `WebRTC` component.
|
||||
|
||||
=== "Code"
|
||||
``` py title="Server-To-Client"
|
||||
from fastrtc import Stream
|
||||
|
||||
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
|
||||
|
||||
stream = Stream(
|
||||
handler=generation,
|
||||
modality="video",
|
||||
mode="receive"
|
||||
)
|
||||
```
|
||||
160
docs/userguide/webrtc_docs.md
Normal file
160
docs/userguide/webrtc_docs.md
Normal file
@@ -0,0 +1,160 @@
|
||||
# FastRTC Docs
|
||||
|
||||
## Connecting
|
||||
|
||||
To connect to the server, you need to create a new RTCPeerConnection object and call the `setupWebRTC` function below.
|
||||
{% if mode in ["send-receive", "receive"] %}
|
||||
This code snippet assumes there is an html element with an id of `{{ modality }}_output_component_id` where the output will be displayed. It should be {{ "a `<audio>`" if modality == "audio" else "an `<video>`"}} element.
|
||||
{% endif %}
|
||||
|
||||
```js
|
||||
// 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);
|
||||
}
|
||||
```
|
||||
|
||||
{%if additional_inputs %}
|
||||
## Sending Input Data
|
||||
|
||||
Your python handler can request additional data from the frontend by calling the `fetch_args()` method (see [here](#add docs)).
|
||||
|
||||
This will send a `send_input` message over the WebRTC data channel.
|
||||
Upon receiving this message, you should trigger the `set_input` hook of your stream.
|
||||
A simple way to do this is with a `POST` request.
|
||||
|
||||
```python
|
||||
@stream.post("/input_hook")
|
||||
def _(data: PydanticBody):
|
||||
stream.set_inputs(data.webrtc_id, data.inputs)
|
||||
```
|
||||
|
||||
And then in your client code:
|
||||
|
||||
```js
|
||||
const data_channel = peerConnection.createDataChannel("text");
|
||||
|
||||
data_channel.onmessage = (event) => {
|
||||
event_json = JSON.parse(event.data);
|
||||
if (event_json.type === "send_input") {
|
||||
fetch('/input_hook', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: inputs
|
||||
}
|
||||
)
|
||||
};
|
||||
};
|
||||
```
|
||||
|
||||
|
||||
The `set_inputs` hook will set the `latest_args` property of your stream to whatever the second argument is.
|
||||
|
||||
NOTE: It is completely up to you how you want to call the `set_inputs` hook.
|
||||
Here we use a `POST` request but you can use a websocket or any other protocol.
|
||||
|
||||
{% endif %}
|
||||
|
||||
{% if additional_outputs %}
|
||||
## Fetching Output Data
|
||||
Your python handler can send additional data to the front end by returning or yielding `AdditionalOutputs(...)`. See the [docs](https://freddyaboulton.github.io/gradio-webrtc/user-guide/#additional-outputs).
|
||||
|
||||
Your front end can fetch these outputs by calling the `get_outputs` hook of the `Stream`.
|
||||
Here is an example using `server-sent-events`:
|
||||
|
||||
```python
|
||||
@stream.get("/outputs")
|
||||
def _(webrtc_id: str)
|
||||
async def get_outputs():
|
||||
while True:
|
||||
for output in stream.get_output(webrtc_id):
|
||||
# Serialize to a string prior to this step
|
||||
yield f"data: {output}\n\n"
|
||||
await
|
||||
return StreamingResponse(get_outputs(), media_type="text/event-stream")
|
||||
```
|
||||
|
||||
NOTE: It is completely up to you how you want to call the `get_output` hook.
|
||||
Here we use a `server-sent-events` but you can use whatever protocol you want!
|
||||
|
||||
{% endif %}
|
||||
|
||||
|
||||
## Stopping
|
||||
|
||||
You can stop the stream by calling the following function:
|
||||
|
||||
```js
|
||||
function stop(pc) {
|
||||
// close transceivers
|
||||
if (pc.getTransceivers) {
|
||||
pc.getTransceivers().forEach((transceiver) => {
|
||||
if (transceiver.stop) {
|
||||
transceiver.stop();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// close local audio / video
|
||||
if (pc.getSenders()) {
|
||||
pc.getSenders().forEach((sender) => {
|
||||
if (sender.track && sender.track.stop) sender.track.stop();
|
||||
});
|
||||
}
|
||||
|
||||
// close peer connection
|
||||
setTimeout(() => {
|
||||
pc.close();
|
||||
}, 500);
|
||||
}
|
||||
```
|
||||
151
docs/userguide/websocket_docs.md
Normal file
151
docs/userguide/websocket_docs.md
Normal file
@@ -0,0 +1,151 @@
|
||||
# FastRTC WebSocket Docs
|
||||
|
||||
{% if modality != "audio" or mode != "send-receive" %}
|
||||
WebSocket connections are currently only supported for audio in send-receive mode.
|
||||
{% else %}
|
||||
|
||||
## Connecting
|
||||
|
||||
To connect to the server via WebSocket, you'll need to establish a WebSocket connection and handle audio processing. The code below assumes there is an HTML audio element for output playback.
|
||||
|
||||
```js
|
||||
// Setup audio context and stream
|
||||
const audioContext = new AudioContext();
|
||||
const stream = await navigator.mediaDevices.getUserMedia({
|
||||
audio: true
|
||||
});
|
||||
|
||||
// Create WebSocket connection
|
||||
const ws = new WebSocket(`${window.location.protocol === 'https:' ? 'wss:' : 'ws:'}//${window.location.host}/websocket/offer`);
|
||||
|
||||
ws.onopen = () => {
|
||||
// Send initial start message with unique ID
|
||||
ws.send(JSON.stringify({
|
||||
event: "start",
|
||||
websocket_id: generateId() // Implement your own ID generator
|
||||
}));
|
||||
|
||||
// Setup audio processing
|
||||
const source = audioContext.createMediaStreamSource(stream);
|
||||
const processor = audioContext.createScriptProcessor(2048, 1, 1);
|
||||
source.connect(processor);
|
||||
processor.connect(audioContext.destination);
|
||||
|
||||
processor.onaudioprocess = (e) => {
|
||||
const inputData = e.inputBuffer.getChannelData(0);
|
||||
const mulawData = convertToMulaw(inputData, audioContext.sampleRate);
|
||||
const base64Audio = btoa(String.fromCharCode.apply(null, mulawData));
|
||||
|
||||
if (ws.readyState === WebSocket.OPEN) {
|
||||
ws.send(JSON.stringify({
|
||||
event: "media",
|
||||
media: {
|
||||
payload: base64Audio
|
||||
}
|
||||
}));
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
// Handle incoming audio
|
||||
const outputContext = new AudioContext({ sampleRate: 24000 });
|
||||
let audioQueue = [];
|
||||
let isPlaying = false;
|
||||
|
||||
ws.onmessage = (event) => {
|
||||
const data = JSON.parse(event.data);
|
||||
if (data.event === "media") {
|
||||
// Process received audio
|
||||
const audioData = atob(data.media.payload);
|
||||
const mulawData = new Uint8Array(audioData.length);
|
||||
for (let i = 0; i < audioData.length; i++) {
|
||||
mulawData[i] = audioData.charCodeAt(i);
|
||||
}
|
||||
|
||||
// Convert mu-law to linear PCM
|
||||
const linearData = alawmulaw.mulaw.decode(mulawData);
|
||||
const audioBuffer = outputContext.createBuffer(1, linearData.length, 24000);
|
||||
const channelData = audioBuffer.getChannelData(0);
|
||||
|
||||
for (let i = 0; i < linearData.length; i++) {
|
||||
channelData[i] = linearData[i] / 32768.0;
|
||||
}
|
||||
|
||||
audioQueue.push(audioBuffer);
|
||||
if (!isPlaying) {
|
||||
playNextBuffer();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
function playNextBuffer() {
|
||||
if (audioQueue.length === 0) {
|
||||
isPlaying = false;
|
||||
return;
|
||||
}
|
||||
|
||||
isPlaying = true;
|
||||
const bufferSource = outputContext.createBufferSource();
|
||||
bufferSource.buffer = audioQueue.shift();
|
||||
bufferSource.connect(outputContext.destination);
|
||||
bufferSource.onended = playNextBuffer;
|
||||
bufferSource.start();
|
||||
}
|
||||
```
|
||||
|
||||
Note: This implementation requires the `alawmulaw` library for audio encoding/decoding:
|
||||
```html
|
||||
<script src="https://cdn.jsdelivr.net/npm/alawmulaw"></script>
|
||||
```
|
||||
|
||||
## Handling Input Requests
|
||||
|
||||
When the server requests additional input data, it will send a `send_input` message over the WebSocket. You should handle this by sending the data to your input hook:
|
||||
|
||||
```js
|
||||
ws.onmessage = (event) => {
|
||||
const data = JSON.parse(event.data);
|
||||
// Handle send_input messages
|
||||
if (data?.type === "send_input") {
|
||||
fetch('/input_hook', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
webrtc_id: websocket_id, // Use the same ID from connection
|
||||
inputs: your_input_data
|
||||
})
|
||||
});
|
||||
}
|
||||
// ... existing audio handling code ...
|
||||
};
|
||||
```
|
||||
|
||||
## Receiving Additional Outputs
|
||||
|
||||
To receive additional outputs from the server, you can use Server-Sent Events (SSE):
|
||||
|
||||
```js
|
||||
const eventSource = new EventSource('/outputs?webrtc_id=' + websocket_id);
|
||||
eventSource.addEventListener("output", (event) => {
|
||||
const eventJson = JSON.parse(event.data);
|
||||
// Handle the output data here
|
||||
console.log("Received output:", eventJson);
|
||||
});
|
||||
```
|
||||
|
||||
## Stopping
|
||||
|
||||
To stop the WebSocket connection:
|
||||
|
||||
```js
|
||||
function stop(ws) {
|
||||
if (ws) {
|
||||
ws.send(JSON.stringify({
|
||||
event: "stop"
|
||||
}));
|
||||
ws.close();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
{% endif %}
|
||||
Reference in New Issue
Block a user