whitphx HF staff commited on
Commit
5073206
1 Parent(s): ad524c9

Use Twilio STUN/TURN servers

Browse files
Files changed (2) hide show
  1. requirements.txt +1 -0
  2. turn.py +21 -13
requirements.txt CHANGED
@@ -1 +1,2 @@
1
  streamlit-webrtc
 
1
  streamlit-webrtc
2
+ twilio
turn.py CHANGED
@@ -1,26 +1,34 @@
 
1
  import logging
2
  import os
3
 
4
- import requests
5
  import streamlit as st
 
6
 
7
  logger = logging.getLogger(__name__)
8
 
9
 
10
- OPEN_RELAY_API_HOST = os.environ.get("OPEN_RELAY_API_HOST")
11
- OPEN_RELAY_API_KEY = os.environ.get("OPEN_RELAY_API_KEY")
12
-
13
-
14
- @st.cache_data
15
  def get_ice_servers():
16
- if not OPEN_RELAY_API_HOST or not OPEN_RELAY_API_KEY:
 
 
 
 
 
 
 
 
 
 
 
17
  logger.warning(
18
- "Open Relay API host or key is not set. Fallback to a free STUN server from Google." # noqa: E501
19
  )
20
  return [{"urls": ["stun:stun.l.google.com:19302"]}]
21
 
22
- # Get response from Open Relay API
23
- response = requests.get(
24
- f"https://{OPEN_RELAY_API_HOST}/api/v1/turn/credentials?apiKey={OPEN_RELAY_API_KEY}" # noqa: E501
25
- )
26
- return response.json()
1
+ # Copied from streamlit-webrtc/sample_utils/turn.py
2
  import logging
3
  import os
4
 
 
5
  import streamlit as st
6
+ from twilio.rest import Client
7
 
8
  logger = logging.getLogger(__name__)
9
 
10
 
11
+ @st.cache_data # type: ignore
 
 
 
 
12
  def get_ice_servers():
13
+ """Use Twilio's TURN server because Streamlit Community Cloud has changed
14
+ its infrastructure and WebRTC connection cannot be established without TURN server now. # noqa: E501
15
+ We considered Open Relay Project (https://www.metered.ca/tools/openrelay/) too,
16
+ but it is not stable and hardly works as some people reported like https://github.com/aiortc/aiortc/issues/832#issuecomment-1482420656 # noqa: E501
17
+ See https://github.com/whitphx/streamlit-webrtc/issues/1213
18
+ """
19
+
20
+ # Ref: https://www.twilio.com/docs/stun-turn/api
21
+ try:
22
+ account_sid = os.environ["TWILIO_ACCOUNT_SID"]
23
+ auth_token = os.environ["TWILIO_AUTH_TOKEN"]
24
+ except KeyError:
25
  logger.warning(
26
+ "Twilio credentials are not set. Fallback to a free STUN server from Google." # noqa: E501
27
  )
28
  return [{"urls": ["stun:stun.l.google.com:19302"]}]
29
 
30
+ client = Client(account_sid, auth_token)
31
+
32
+ token = client.tokens.create()
33
+
34
+ return token.ice_servers