Okay, here is an example demonstrating how to connect Twilio's <Stream> TwiML verb with Google Cloud Speech-to-Text (GCP STT) for real-time transcription using Python and Flask-Sock.
This example sets up a small web server that:
- Responds to a Twilio voice call with TwiML that instructs Twilio to stream the audio.
- Receives the audio stream from Twilio over a WebSocket connection.
- Forwards the audio chunks to the GCP STT streaming API.
- Prints the real-time transcription results (both interim and final) as they are received from GCP.
Prerequisites:
- Python 3.7+
- Google Cloud Project: Enabled the Speech-to-Text API.
- Google Cloud Credentials: Set up a service account key and make it available to your application (e.g., via the
GOOGLE_APPLICATION_CREDENTIALS environment variable). See Google Cloud Authentication docs.
- Twilio Account: A Twilio phone number configured to point to your server's webhook.
- Publicly Accessible Server: Your Flask application needs to be accessible from the internet so Twilio can send webhooks and connect to the WebSocket. For local testing,
ngrok is highly recommended.
Installation:
pip install Flask Flask-Sock google-cloud-speech twilio
Code (app.py):
import json
import os
import queue
import logging
from flask import Flask, request
from flask_sock import Sock
from twilio.twiml.voice_response import VoiceResponse, Connect
from google.cloud import speech
# Configure logging
logging.basicConfig(level=logging.INFO)
app = Flask(__name__)
# Optional: Recommended ping interval for Twilio streams
app.config['SOCK_SERVER_OPTIONS'] = {'ping_interval': 25}
sock = Sock(app)
# --- Google Cloud Speech-to-Text Configuration ---
# Ensure GOOGLE_APPLICATION_CREDENTIALS environment variable is set
# or provide explicit credentials path/config here.
# See https://cloud.google.com/docs/authentication/getting-started
# --- Twilio Webhook Endpoint ---
@app.route('/voice', methods=['POST'])
def voice():
"""Respond to incoming calls with a <Stream> TwiML verb."""
response = VoiceResponse()
connect = Connect()
# The websocket URL must be publicly accessible (wss://).
# Replace 'your-ngrok-url' with your actual ngrok or server URL.
# Make sure ngrok is running and forwarding to your Flask port (e.g., 5000).
connect.stream(url='wss://your-ngrok-url/stream') # <-- !!! IMPORTANT: Replace with your URL !!!
response.append(connect)
logging.info(f"TwiML response: {response}")
return str(response)
# --- WebSocket Endpoint for Audio Streaming ---
@sock.route('/stream')
def stream(ws):
"""Receive audio stream from Twilio and send to Google Cloud STT."""
logging.info('WebSocket connection opened')
# [1] Receive the initial metadata message from Twilio
# This message contains information about the stream, like sample rate and encoding.
message = ws.receive()
if message is None:
logging.error("Received empty message on WebSocket")
return
try:
data = json.loads(message)
if data['event'] == 'start':
start_payload = data['start']
sample_rate = start_payload['sampleRate']
encoding = start_payload['encoding'] # Twilio uses 'mulaw' or 'alaw'
logging.info(f"Stream started: Sample Rate={sample_rate}, Encoding={encoding}")
# Map Twilio encoding to GCP encoding enum
# Twilio streams use 8-bit Mu-law or A-law.
if encoding == 'mulaw':
gcp_encoding = speech.RecognitionConfig.AudioEncoding.MULAW
elif encoding == 'alaw':
gcp_encoding = speech.RecognitionConfig.AudioEncoding.ALAW
else:
logging.error(f"Unsupported Twilio encoding: {encoding}")
ws.close()
return
# [2] Configure Google Cloud STT
config = speech.RecognitionConfig(
encoding=gcp_encoding,
sample_rate_hertz=sample_rate,
language_code="en-US", # Or any desired language code (e.g., "es-ES", "fr-FR")
# Use a model suitable for phone calls or short utterances
model="latest_short", # or "phone_call" or "default"
use_enhanced=True, # Use enhanced models if available for selected language
)
streaming_config = speech.StreamingRecognitionConfig(
config=config,
interim_results=True, # Get interim results in real-time
)
# [3] Create a generator to send audio data to GCP
# This generator yields StreamingRecognizeRequest objects.
# The first request contains the config, subsequent contain audio.
def request_generator():
# Yield the initial configuration request first
yield speech.StreamingRecognizeRequest(streaming_config=streaming_config)
# Now, continuously receive audio from the Twilio WebSocket
# and yield requests containing the audio content.
while True:
# ws.receive() blocks until a message is received or the socket closes
message = ws.receive()
if message is None: # WebSocket closed by client (Twilio)
logging.info("WebSocket received None, breaking generator loop.")
break
if isinstance(message, bytes):
# This is the actual audio data chunk
yield speech.StreamingRecognizeRequest(audio_content=message)
# Ignore other message types Twilio might send after 'start', like 'media' event JSON
# [4] Start the Google Cloud STT streaming recognition
# The client will consume the requests from our generator function
# and simultaneously yield responses from the GCP API.
client = speech.SpeechClient()
logging.info("Starting GCP streaming recognition...")
# This call is blocking and processes requests/responses
responses = client.streaming_recognize(request_generator())
# [5] Process responses from Google Cloud STT
# This loop iterates over the responses yielded by the GCP client.
try:
for response in responses:
# Check for transcription errors returned by GCP
if response.error.code != 0:
logging.error(f"GCP Error: {response.error.message} (Code: {response.error.code})")
# Optionally break if a critical error occurs
# break
# Process results within the response
for result in response.results:
# Check if alternatives are available
if result.alternatives:
alternative = result.alternatives[0] # Get the most probable transcription
transcript = alternative.transcript
stability = result.stability # Indicates how stable the result is (0.0 to 1.0)
if result.is_final:
# This is a final, confirmed transcription chunk
logging.info(f"Final: {transcript} (Stability: {stability:.2f})")
# TODO: Do something useful with the final transcript (e.g., store it, process it)
else:
# This is an interim, potentially changing, transcription result
logging.info(f"Interim: {transcript} (Stability: {stability:.2f})")
# TODO: Do something useful with interim results (e.g., display it live to an agent)
except Exception as e:
# Catch exceptions during GCP response processing
logging.error(f"Error processing GCP responses: {e}", exc_info=True)
elif data['event'] == 'media':
# This handles subsequent 'media' events that contain audio data.
# However, our generator is already receiving the raw binary audio
# data directly via ws.receive(). So, we mostly just ignore
# the JSON metadata for 'media' events here.
pass
elif data['event'] == 'stop':
logging.info("Twilio stream stopped")
# When Twilio sends the 'stop' event, the WebSocket connection
# is closed, which will cause ws.receive() in the generator
# to return None, breaking the generator loop and ending the GCP stream.
else:
logging.warning(f"Received unhandled Twilio event: {data['event']}")
except json.JSONDecodeError:
logging.error("Failed to decode JSON from Twilio message")
except Exception as e:
# Catch any other errors during the initial setup or processing loop
logging.error(f"An error occurred in the stream handler: {e}", exc_info=True)
finally:
logging.info('WebSocket connection closed')
# The generator and GCP client should clean up naturally when the WS closes.
# --- Running the Flask App ---
if __name__ == '__main__':
# In a production environment, use a production-ready WSGI server like Gunicorn
# configured with WebSocket support (e.g., Gunicorn with gevent or eventlet workers).
# For local testing:
# 1. Make sure your Google Cloud credentials are set up.
# 2. Run this script: python app.py
# 3. In a separate terminal, start ngrok to expose your Flask app (default port 5000):
# ngrok http 5000
# 4. Copy the `https` URL from ngrok (e.g., https://abcdef123456.ngrok.io).
# 5. Update the `connect.stream(url='wss://your-ngrok-url/stream')` line in the `/voice` route, replacing 'your-ngrok-url' with the hostname from your ngrok URL. Use `wss` NOT `https`.
# 6. Configure your Twilio phone number's "A CALL COMES IN" webhook to point to your ngrok URL + '/voice' (e.g., `https://abcdef123456.ngrok.io/voice`). Use HTTPS for the webhook.
# 7. Make a call to your Twilio number.
# Note: debug=True should NOT be used in production.
logging.info("Starting Flask app on port 5000...")
app.run(host='0.0.0.0', port=5000, debug=True)
Explanation:
/voice Route: This is the webhook that Twilio hits when a call comes in. It returns TwiML containing the <Connect> verb with a nested <Stream>. The url attribute of <Stream> specifies the WebSocket endpoint on your server where Twilio should send the audio. Remember to replace your-ngrok-url with your actual public URL/ngrok URL.
/stream WebSocket Route: This endpoint is handled by flask_sock. When Twilio connects via WebSocket, the stream(ws) function is called. ws is the WebSocket connection object.
- Twilio Metadata: The first message Twilio sends over the WebSocket is a JSON object with event type
'start'. This contains crucial information like the sampleRate and encoding of the audio stream. We parse this to configure the GCP STT client correctly.
- GCP STT Configuration: We create a
google.cloud.speech.SpeechClient and define the RecognitionConfig and StreamingRecognitionConfig using the information from Twilio's metadata. interim_results=True is key for real-time results.
- Request Generator: The
request_generator() function is an essential part of the GCP streaming client. It's an iterator that the client.streaming_recognize() method consumes. It first yields a request containing the streaming_config, and then enters a loop that continuously receives binary audio messages from the Twilio WebSocket (ws.receive()) and yields StreamingRecognizeRequest objects containing that audio_content.
- Starting GCP Stream:
client.streaming_recognize(request_generator()) starts the actual streaming process with Google. This call is somewhat magical; it consumes the request_generator in one part of the client and yields responses from the GCP API in another part.
- Processing GCP Responses: The
for response in responses: loop iterates over the results that GCP sends back as they become available.
response.results contains the transcription results for a chunk of audio.
result.alternatives[0] usually holds the most likely transcription text.
result.is_final tells you if this transcription chunk is considered final by GCP (usually corresponds to a pause in speech).
How to Run:
- Save the code as
app.py.
- Set up Google Cloud Credentials: Make sure the
GOOGLE_APPLICATION_CREDENTIALS environment variable is pointing to your service account JSON key file.
- Run the Flask app:
python app.py
- Start ngrok: In a separate terminal, expose your Flask app to the internet.
ngrok http 5000
(Replace 5000 if your Flask app runs on a different port).
- Update URLs:
- Copy the
https URL provided by ngrok (e.g., https://abcdef123456.ngrok.io).
- In your Twilio number's voice configuration, set the "A CALL COMES IN" webhook to this ngrok URL +
/voice (e.g., https://abcdef123456.ngrok.io/voice). Make sure the method is HTTP POST.
- In the
app.py code, find the line connect.stream(url='wss://your-ngrok-url/stream'). Replace your-ngrok-url with the hostname from your ngrok URL (e.g., abcdef123456.ngrok.io). Crucially, use wss:// not https://.
- Restart the Flask app after updating the WSS URL.
- Call your Twilio phone number. Speak into the phone. You should see the real-time interim and final transcription results appear in the terminal where your Flask app is running.
This example provides a solid foundation. For production, you would need to consider:
- Using a production-ready WSGI server (like Gunicorn) with WebSocket support.
- More robust error handling and reconnection logic.
- Handling multiple concurrent calls and streams.
- What you actually do with the transcription results (store in a database, send to another service, display in a UI, etc.).