on1onmangoes commited on
Commit
43325c0
·
verified ·
1 Parent(s): 0c88c1c

Upload utils/turn_server.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. utils/turn_server.py +124 -0
utils/turn_server.py ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from typing import Literal, Optional, Dict, Any
3
+ import requests
4
+
5
+ from fastrtc import get_hf_turn_credentials, get_twilio_turn_credentials
6
+
7
+
8
+ def get_rtc_credentials(
9
+ provider: Literal["hf", "twilio", "cloudflare"] = "hf",
10
+ **kwargs
11
+ ) -> Dict[str, Any]:
12
+ """
13
+ Get RTC configuration for different TURN server providers.
14
+
15
+ Args:
16
+ provider: The TURN server provider to use ('hf', 'twilio', or 'cloudflare')
17
+ **kwargs: Additional arguments passed to the specific provider's function
18
+
19
+ Returns:
20
+ Dictionary containing the RTC configuration
21
+ """
22
+ try:
23
+ if provider == "hf":
24
+ return get_hf_credentials(**kwargs)
25
+ elif provider == "twilio":
26
+ return get_twilio_credentials(**kwargs)
27
+ elif provider == "cloudflare":
28
+ return get_cloudflare_credentials(**kwargs)
29
+ except Exception as e:
30
+ raise Exception(f"Failed to get RTC credentials ({provider}): {str(e)}")
31
+
32
+
33
+ def get_hf_credentials(token: Optional[str] = None) -> Dict[str, Any]:
34
+ """
35
+ Get credentials for Hugging Face's community TURN server.
36
+
37
+ Required setup:
38
+ 1. Create a Hugging Face account at huggingface.co
39
+ 2. Visit: https://huggingface.co/spaces/fastrtc/turn-server-login
40
+ 3. Set HF_TOKEN environment variable or pass token directly
41
+ """
42
+ token = token or os.environ.get("HF_TOKEN")
43
+ if not token:
44
+ raise ValueError("HF_TOKEN environment variable not set")
45
+
46
+ try:
47
+ return get_hf_turn_credentials(token=token)
48
+ except Exception as e:
49
+ raise Exception(f"Failed to get HF TURN credentials: {str(e)}")
50
+
51
+
52
+ def get_twilio_credentials(
53
+ account_sid: Optional[str] = None,
54
+ auth_token: Optional[str] = None
55
+ ) -> Dict[str, Any]:
56
+ """
57
+ Get credentials for Twilio's TURN server.
58
+
59
+ Required setup:
60
+ 1. Create a free Twilio account at: https://login.twilio.com/u/signup
61
+ 2. Get your Account SID and Auth Token from the Twilio Console
62
+ 3. Set environment variables:
63
+ - TWILIO_ACCOUNT_SID (or pass directly)
64
+ - TWILIO_AUTH_TOKEN (or pass directly)
65
+ """
66
+ account_sid = account_sid or os.environ.get("TWILIO_ACCOUNT_SID")
67
+ auth_token = auth_token or os.environ.get("TWILIO_AUTH_TOKEN")
68
+
69
+ if not account_sid or not auth_token:
70
+ raise ValueError("Twilio credentials not found. Set TWILIO_ACCOUNT_SID and TWILIO_AUTH_TOKEN env vars")
71
+
72
+ try:
73
+ return get_twilio_turn_credentials(account_sid=account_sid, auth_token=auth_token)
74
+ except Exception as e:
75
+ raise Exception(f"Failed to get Twilio TURN credentials: {str(e)}")
76
+
77
+
78
+ def get_cloudflare_credentials(
79
+ key_id: Optional[str] = None,
80
+ api_token: Optional[str] = None,
81
+ ttl: int = 86400
82
+ ) -> Dict[str, Any]:
83
+ """
84
+ Get credentials for Cloudflare's TURN server.
85
+
86
+ Required setup:
87
+ 1. Create a free Cloudflare account
88
+ 2. Go to Cloudflare dashboard -> Calls section
89
+ 3. Create a TURN App and get the Turn Token ID and API Token
90
+ 4. Set environment variables:
91
+ - TURN_KEY_ID
92
+ - TURN_KEY_API_TOKEN
93
+
94
+ Args:
95
+ key_id: Cloudflare Turn Token ID (optional, will use env var if not provided)
96
+ api_token: Cloudflare API Token (optional, will use env var if not provided)
97
+ ttl: Time-to-live for credentials in seconds (default: 24 hours)
98
+ """
99
+ key_id = key_id or os.environ.get("TURN_KEY_ID")
100
+ api_token = api_token or os.environ.get("TURN_KEY_API_TOKEN")
101
+
102
+ if not key_id or not api_token:
103
+ raise ValueError("Cloudflare credentials not found. Set TURN_KEY_ID and TURN_KEY_API_TOKEN env vars")
104
+
105
+ response = requests.post(
106
+ f"https://rtc.live.cloudflare.com/v1/turn/keys/{key_id}/credentials/generate",
107
+ headers={
108
+ "Authorization": f"Bearer {api_token}",
109
+ "Content-Type": "application/json",
110
+ },
111
+ json={"ttl": ttl},
112
+ )
113
+
114
+ if response.ok:
115
+ return {"iceServers": [response.json()["iceServers"]]}
116
+ else:
117
+ raise Exception(
118
+ f"Failed to get Cloudflare TURN credentials: {response.status_code} {response.text}"
119
+ )
120
+
121
+
122
+ if __name__ == "__main__":
123
+ # Test
124
+ print(get_rtc_credentials(provider="hf"))