Skip to content

Commit

Permalink
fix: Handle ruff
Browse files Browse the repository at this point in the history
  • Loading branch information
devman0129 committed May 14, 2024
1 parent 7a700d5 commit ae0a034
Showing 1 changed file with 59 additions and 44 deletions.
103 changes: 59 additions & 44 deletions examples/twilio/call/python/app.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import os
import base64
import json
from io import BytesIO
from flask import Flask, make_response
from flask_socketio import SocketIO, emit
from elevenlabs.client import ElevenLabs
from twilio.twiml.voice_response import VoiceResponse
import os

from dotenv import load_dotenv
from elevenlabs.client import ElevenLabs
from flask import Flask
from flask_sockets import Sockets
from twilio.twiml.voice_response import Connect, VoiceResponse

load_dotenv()

Expand All @@ -24,7 +24,7 @@
)

app = Flask(__name__)
socketio = SocketIO(app)
sockets = Sockets(app)
PORT = int(os.getenv("PORT", 5000))

voice_id = "21m00Tcm4TlvDq8ikWAM"
Expand All @@ -34,48 +34,63 @@

@app.route("/call/incoming", methods=["POST"])
def handle_incoming_call():
print("Incoming call ...")
twiml = VoiceResponse()
twiml.connect().stream(url=f"wss://{SERVER_DOMAIN}/call/connection")

response = make_response(twiml.to_xml())
response.headers["Content-Type"] = "text/xml"
return response


@socketio.on("message", namespace="/call/connection")
def handle_message(data):
message = json.loads(data)
if message["event"] == "start" and "start" in message:
stream_sid = message["start"]["streamSid"]

response = client.text_to_speech.convert(
voice_id=voice_id,
output_format=output_format,
model_id="eleven_turbo_v2",
text=text,
)

audio_array_buffer = stream_to_array_buffer(response)

emit(
"media",
{
"streamSid": stream_sid,
"event": "media",
"media": {"payload": audio_array_buffer},
},
)
connect = Connect()
connect.stream(url=f"wss://{SERVER_DOMAIN}/call/connection")
twiml.append(connect)
twiml.say("The stream has started.")
return str(twiml)


@sockets.route("/call/connection")
def handle_connection(ws):
try:
while not ws.closed:
message = ws.receive()
if message is not None:
try:
data = json.loads(message)
if data["event"] == "start":
stream_sid = data.get("start", {}).get("streamSid")

response = client.text_to_speech.convert(
voice_id=voice_id,
output_format=output_format,
text=text,
model_id="eleven_turbo_v2",
)

audio_array_buffer = stream_to_array_buffer(response)
payload = base64.b64encode(audio_array_buffer).decode("utf-8")
ws.send(
json.dumps(
{
"streamSid": stream_sid,
"event": "media",
"media": {"payload": payload},
}
)
)
except json.JSONDecodeError as e:
print("Error parsing JSON:", e)
except Exception as e:
print(
"Error:", e
) # Log any other errors that occur while processing WebSocket messages


def stream_to_array_buffer(readable_stream):
audio_stream = BytesIO()
chunks = []
for chunk in readable_stream:
if chunk:
audio_stream.write(chunk)
audio_stream.seek(0)

return audio_stream
chunks.append(chunk)
return b"".join(chunks)


if __name__ == "__main__":
socketio.run(app, host="0.0.0.0", port=PORT)
from gevent import pywsgi
from geventwebsocket.handler import WebSocketHandler

server = pywsgi.WSGIServer(("", PORT), app, handler_class=WebSocketHandler)
print("Server listening on: http://localhost:" + str(PORT))
server.serve_forever()

0 comments on commit ae0a034

Please sign in to comment.