Repository navigation
Expand file tree
/
Copy pathvoice-server-https.py
More file actions
182 lines (154 loc) · 6.42 KB
/
Copy pathvoice-server-https.py
File metadata and controls
182 lines (154 loc) · 6.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
#!/usr/bin/env python3
"""
HTTPS Cloud TTS Server for Simba Voice Chat (ElevenLabs)
"""
import os
import sys
import http.client
import json
import ssl
from http.server import HTTPServer, BaseHTTPRequestHandler
PORT = 8443 # HTTPS port
ELEVENLABS_API_KEY = "sk_63d6d857580a365ef74774a4ad7b47ac1614da33c3214d9a"
DEFAULT_VOICE = "EXAVITQu4vr4xnSDxMaL"
class CloudTTSHandler(BaseHTTPRequestHandler):
def log_message(self, format, *args):
print(f"[{self.log_date_time_string()}] {format % args}")
def send_cors_headers(self):
self.send_header('Access-Control-Allow-Origin', '*')
self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
self.send_header('Access-Control-Allow-Headers', 'Content-Type, Authorization')
def do_OPTIONS(self):
self.send_response(200)
self.send_cors_headers()
self.end_headers()
def do_GET(self):
if self.path == '/health':
self.send_response(200)
self.send_cors_headers()
self.send_header('Content-Type', 'application/json')
self.end_headers()
self.wfile.write(json.dumps({"status": "ok", "tts": "elevenlabs-cloud"}).encode())
elif self.path == '/' or self.path == '/index.html':
self.serve_file('voice-chat-safari.html', 'text/html')
elif self.path.endswith('.html'):
self.serve_file(self.path[1:], 'text/html')
else:
self.send_response(404)
self.end_headers()
def serve_file(self, filename, content_type):
try:
filepath = os.path.join('/Users/shashank/.openclaw/workspace', filename)
with open(filepath, 'rb') as f:
content = f.read()
self.send_response(200)
self.send_cors_headers()
self.send_header('Content-Type', content_type)
self.send_header('Content-Length', len(content))
self.end_headers()
self.wfile.write(content)
except FileNotFoundError:
self.send_response(404)
self.end_headers()
except Exception as e:
print(f"Error serving file: {e}")
self.send_response(500)
self.end_headers()
def do_POST(self):
if self.path == '/v1/tts':
self.handle_tts()
elif self.path == '/v1/chat':
self.handle_chat()
else:
self.send_response(404)
self.end_headers()
def handle_tts(self):
try:
content_length = int(self.headers.get('Content-Length', 0))
body = json.loads(self.rfile.read(content_length).decode())
text = body.get('text', '')
voice_id = body.get('voice_id', DEFAULT_VOICE)
if not text:
self.send_response(400)
self.end_headers()
return
print(f"🎙️ Generating cloud TTS: {text[:50]}...")
conn = http.client.HTTPSConnection("api.elevenlabs.io")
headers = {
'xi-api-key': ELEVENLABS_API_KEY,
'Content-Type': 'application/json'
}
payload = json.dumps({
'text': text,
'model_id': 'eleven_multilingual_v2',
'voice_settings': {
'stability': 0.5,
'similarity_boost': 0.75
}
})
conn.request("POST", f"/v1/text-to-speech/{voice_id}", body=payload, headers=headers)
response = conn.getresponse()
if response.status != 200:
error = response.read().decode()
print(f"ElevenLabs error: {error}")
self.send_response(500)
self.end_headers()
return
audio_data = response.read()
conn.close()
self.send_response(200)
self.send_cors_headers()
self.send_header('Content-Type', 'audio/mpeg')
self.send_header('Content-Length', len(audio_data))
self.end_headers()
self.wfile.write(audio_data)
print(f"✅ Cloud TTS generated: {len(audio_data)} bytes")
except Exception as e:
print(f"TTS error: {e}")
self.send_response(500)
self.end_headers()
def handle_chat(self):
try:
content_length = int(self.headers.get('Content-Length', 0))
body = json.loads(self.rfile.read(content_length).decode())
if 'message' in body:
body = {
"model": "kimi-k2.5:cloud",
"messages": [{"role": "user", "content": body['message']}],
"stream": False
}
conn = http.client.HTTPConnection("127.0.0.1", 18789)
headers = {'Content-Type': 'application/json', 'Authorization': 'Bearer ollama'}
conn.request("POST", "/v1/chat/completions", body=json.dumps(body).encode(), headers=headers)
response = conn.getresponse()
self.send_response(response.status)
self.send_cors_headers()
self.send_header('Content-Type', 'application/json')
self.end_headers()
self.wfile.write(response.read())
conn.close()
except Exception as e:
print(f"Chat error: {e}")
self.send_response(503)
self.end_headers()
self.wfile.write(json.dumps({"error": "Gateway unavailable"}).encode())
def main():
print("🚀 Simba HTTPS Cloud Voice Chat Server")
print("=" * 40)
print(f"\n🔒 HTTPS Server: https://localhost:{PORT}")
print(f" TTS: ElevenLabs Cloud")
print(f" Voice: Sarah (warm, professional)")
print("\n⚠️ You'll see a security warning - click 'Visit Website'")
print("-" * 40)
# SSL context with self-signed cert
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
context.load_cert_chain('/tmp/cert.pem', '/tmp/key.pem')
server = HTTPServer(('127.0.0.1', PORT), CloudTTSHandler)
server.socket = context.wrap_socket(server.socket, server_side=True)
try:
server.serve_forever()
except KeyboardInterrupt:
print("\n\n👋 Server stopped")
server.shutdown()
if __name__ == '__main__':
main()