samuellimabraz commited on
Commit
30cb267
·
unverified ·
1 Parent(s): d0aa0b6

Add Twilio TURN server integration for WebRTC

Browse files

- Implemented get_ice_servers function to retrieve ICE server configurations, enhancing connectivity options for Streamlit Cloud deployment.
- Updated webrtc_streamer configuration to utilize the new ICE server settings, ensuring more reliable video streaming.

Files changed (1) hide show
  1. app.py +31 -1
app.py CHANGED
@@ -2,12 +2,41 @@ import av
2
  import cv2
3
  import numpy as np
4
  import streamlit as st
 
5
  from streamlit_webrtc import webrtc_streamer, WebRtcMode
6
- from src.opencv_utils import OpenCVUtils
 
7
 
8
  st.set_page_config(page_title="OpenCV Explorer", page_icon="🎨", layout="wide")
9
 
10
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
  @st.cache_resource
12
  def get_app():
13
  return OpenCVUtils()
@@ -122,6 +151,7 @@ def video_frame_callback(frame: av.VideoFrame) -> av.VideoFrame:
122
  webrtc_streamer(
123
  key="opencv-explorer",
124
  mode=WebRtcMode.SENDRECV,
 
125
  video_frame_callback=video_frame_callback,
126
  media_stream_constraints={"video": True, "audio": False},
127
  async_processing=True,
 
2
  import cv2
3
  import numpy as np
4
  import streamlit as st
5
+ import os
6
  from streamlit_webrtc import webrtc_streamer, WebRtcMode
7
+ from opencv_utils import OpenCVUtils
8
+ from twilio.rest import Client
9
 
10
  st.set_page_config(page_title="OpenCV Explorer", page_icon="🎨", layout="wide")
11
 
12
 
13
+ def get_ice_servers():
14
+ """
15
+ Get ICE servers configuration.
16
+ For Streamlit Cloud deployment, a TURN server is required in addition to STUN.
17
+ This function will try to use Twilio's TURN server service if credentials are available,
18
+ otherwise it falls back to a free STUN server from Google.
19
+ """
20
+ try:
21
+ # Try to get Twilio credentials from environment variables
22
+ account_sid = os.environ.get("TWILIO_ACCOUNT_SID")
23
+ auth_token = os.environ.get("TWILIO_AUTH_TOKEN")
24
+
25
+ if account_sid and auth_token:
26
+ client = Client(account_sid, auth_token)
27
+ token = client.tokens.create()
28
+ return token.ice_servers
29
+ else:
30
+ st.warning(
31
+ "Twilio credentials not found. Using free STUN server only, which may not work reliably on Streamlit Cloud."
32
+ )
33
+ except Exception as e:
34
+ st.error(f"Error setting up Twilio TURN servers: {e}")
35
+
36
+ # Fallback to Google's free STUN server
37
+ return [{"urls": ["stun:stun.l.google.com:19302"]}]
38
+
39
+
40
  @st.cache_resource
41
  def get_app():
42
  return OpenCVUtils()
 
151
  webrtc_streamer(
152
  key="opencv-explorer",
153
  mode=WebRtcMode.SENDRECV,
154
+ rtc_configuration={"iceServers": get_ice_servers()},
155
  video_frame_callback=video_frame_callback,
156
  media_stream_constraints={"video": True, "audio": False},
157
  async_processing=True,