Of course! Here is a comprehensive, production-ready example of a Python FastAPI application that handles real-time audio streaming from Twilio, transcribes it using Google Cloud Speech-to-Text, and prints the results to the console.
This example demonstrates the core concepts of handling WebSockets, bridging two separate real-time streams, and managing asynchronous tasks.
Key Technologies
- FastAPI: The web framework for creating the API endpoints.
- Twilio
<Stream>: A TwiML verb that instructs Twilio to open a WebSocket and stream the call's audio to your server.
- Google Cloud Speech-to-Text (STT): The service that will perform the real-time transcription. We'll use its streaming recognition API.
- WebSockets: The communication protocol used by Twilio to send audio data in real-time.
asyncio: Python's library for writing concurrent code, essential for handling both the incoming Twilio stream and the outgoing GCP STT stream simultaneously.
Project Structure
.
├── .env
├── main.py
└── requirements.txt
1. requirements.txt
First, define the necessary Python libraries.
fastapi
uvicorn[standard]
python-dotenv
twilio
google-cloud-speech
2. .env
Create this file to securely store the path to your Google Cloud credentials. Do not commit this file to version control.
# .env file
# Replace with the actual path to your GCP service account JSON key
GOOGLE_APPLICATION_CREDENTIALS="path/to/your/gcp-service-account-key.json"
3. main.py
This is the core of our application. It contains the FastAPI logic for handling both the initial HTTP request from Twilio and the subsequent WebSocket audio stream.
import base64
import json
import os
import asyncio
from dotenv import load_dotenv
from fastapi import FastAPI, Request, WebSocket, WebSocketDisconnect
from fastapi.responses import Response
from twilio.twiml.voice_response import VoiceResponse, Stream
from google.cloud import speech
# Load environment variables from .env file
load_dotenv()
# Set up Google Cloud credentials
# The GOOGLE_APPLICATION_CREDENTIALS environment variable is used automatically
# by the google-cloud-speech library. We load it here from the .env file.
# Make sure the path in your .env file is correct.
if not os.getenv("GOOGLE_APPLICATION_CREDENTIALS"):
raise Exception("GOOGLE_APPLICATION_CREDENTIALS environment variable not set.")
app = FastAPI()
# --- Google Cloud Speech-to-Text Configuration ---
# See https://cloud.google.com/speech-to-text/docs/reference/rest/v1/RecognitionConfig
# Twilio streams audio in 8000 Hz, 1-channel, mu-law format.
AUDIO_ENCODING = speech.RecognitionConfig.AudioEncoding.MULAW
SAMPLE_RATE_HERTZ = 8000
LANGUAGE_CODE = "en-US"
# In this example, we'll get interim results.
# This means we get transcripts as the user is speaking, not just at the end.
GCP_STREAMING_CONFIG = speech.StreamingRecognitionConfig(
config=speech.RecognitionConfig(
encoding=AUDIO_ENCODING,
sample_rate_hertz=SAMPLE_RATE_HERTZ,
language_code=LANGUAGE_CODE,
),
interim_results=True,
)
@app.post("/voice")
async def voice(request: Request):
"""
This endpoint is the entry point for a Twilio voice call.
It generates TwiML to instruct Twilio to open a WebSocket stream.
"""
host = request.url.hostname
port = request.url.port
# Use wss for secure WebSockets. Ngrok will handle the TLS termination.
websocket_url = f"wss://{host}/ws"
if port:
websocket_url = f"wss://{host}:{port}/ws"
print(f"Twilio connecting to WebSocket at: {websocket_url}")
response = VoiceResponse()
response.say(
"Hello! Please start speaking, I am listening.",
voice='alice',
language='en-US'
)
# The <Stream> verb is what opens the WebSocket from Twilio
stream = Stream(url=websocket_url)
response.append(stream)
response.pause(length=30) # Keep the call open for 30 seconds of silence
response.say(
"Thank you for your time. Goodbye.",
voice='alice',
language='en-US'
)
return Response(content=str(response), media_type="text/xml")
@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
"""
This WebSocket endpoint handles the real-time audio stream from Twilio.
It bridges the audio to Google Cloud Speech-to-Text and prints transcripts.
"""
await websocket.accept()
print("WebSocket connection established.")
audio_queue = asyncio.Queue()
gcp_task = None
try:
# This function will run in a separate task to process audio from the queue
async def gcp_request_generator():
# The first request must be the configuration
yield speech.StreamingRecognizeRequest(streaming_config=GCP_STREAMING_CONFIG)
# Now, yield audio data from the queue
while True:
chunk = await audio_queue.get()
if chunk is None:
break # Signal to end the stream
yield speech.StreamingRecognizeRequest(audio_content=chunk)
# This function processes the responses from GCP
async def process_gcp_responses():
client = speech.SpeechAsyncClient()
responses = await client.streaming_recognize(requests=gcp_request_generator())
async for response in responses:
if not response.results:
continue
result = response.results[0]
if not result.alternatives:
continue
transcript = result.alternatives[0].transcript
if result.is_final:
print(f"✅ Final Transcript: {transcript}")
else:
# Use carriage return to overwrite the line for a smooth real-time effect
print(f"🗣️ Interim Transcript: {transcript}\r", end="")
# Start the GCP processing task
gcp_task = asyncio.create_task(process_gcp_responses())
# Main loop to receive messages from Twilio's WebSocket
while True:
message_str = await websocket.receive_text()
message_json = json.loads(message_str)
event = message_json.get("event")
if event == "start":
print(f"Twilio stream started. Stream SID: {message_json['start']['streamSid']}")
elif event == "media":
# The 'payload' is base64 encoded audio data (mu-law)
payload = message_json["media"]["payload"]
audio_chunk = base64.b64decode(payload)
await audio_queue.put(audio_chunk)
elif event == "stop":
print("Twilio stream stopped.")
break
except WebSocketDisconnect:
print("WebSocket disconnected.")
except Exception as e:
print(f"An error occurred: {e}")
finally:
# Signal the GCP generator to finish
await audio_queue.put(None)
# Wait for the GCP task to complete
if gcp_task:
await gcp_task
print("Cleanup complete. Connection closed.")
How to Run the Application
Step 1: Prerequisites
- Python 3.8+: Ensure you have a modern version of Python installed.
- Google Cloud Account:
- Create a new project in the Google Cloud Console.
- Enable the Speech-to-Text API for your project.
- Create a Service Account, grant it the "Cloud Speech-to-Text API User" role (or a similar permission), and download the JSON key file.
- Twilio Account:
- ngrok: Twilio needs a publicly accessible URL to send requests to your local machine.
ngrok is the perfect tool for this. Download it here.
Step 2: Project Setup
- Clone or download the project files into a directory.
- Open your terminal in that directory.
- Create and activate a virtual environment:
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
- Install the required libraries:
pip install -r requirements.txt
- Edit the
.env file and set GOOGLE_APPLICATION_CREDENTIALS to the absolute path of the JSON key you downloaded from Google Cloud.
Step 3: Expose Your Local Server with ngrok
- In a new terminal window, start
ngrok to expose your local port 8000:
ngrok http 8000
ngrok will give you a public "Forwarding" URL (e.g., https://random-string.ngrok-free.app). Copy the https URL.
Step 4: Run the FastAPI Application
- Go back to your first terminal window (where your virtual environment is active).
- Start the Uvicorn server:
uvicorn main:app --reload
You will see logs indicating the server is running on http://127.0.0.1:8000.
Step 5: Configure Your Twilio Phone Number
- Go to the Twilio Console.
- Navigate to Phone Numbers > Manage > Active numbers.
- Click on the phone number you want to use.
- Scroll down to the "Voice & Fax" section.
- For "A CALL COMES IN", select "Webhook".
- Paste your ngrok
https URL into the text box and add /voice at the end. For example: https://random-string.ngrok-free.app/voice
- Ensure the method is set to
HTTP POST.
- Click Save.
Step 6: Test It!
- Call your Twilio phone number from any phone.
- You will hear the "Hello! Please start speaking..." prompt.
- Look at your FastAPI server's terminal window. As you speak, you will see the interim and final transcripts being printed in real-time!
# Example output in your FastAPI terminal:
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO: Started reloader process [23326] using StatReload
INFO: Started server process [23328]
INFO: Waiting for application startup.
INFO: Application startup complete.
Twilio connecting to WebSocket at: wss://random-string.ngrok-free.app/ws
INFO: 11.22.33.44:0 - "POST /voice HTTP/1.1" 200 OK
WebSocket connection established.
Twilio stream started. Stream SID: MZ...
🗣️ Interim Transcript: hello this is a test
🗣️ Interim Transcript: hello this is a test of the real-time
🗣️ Interim Transcript: hello this is a test of the real-time streaming
✅ Final Transcript: hello this is a test of the real-time streaming system
🗣️ Interim Transcript: I hope it is working
✅ Final Transcript: I hope it is working correctly.
Twilio stream stopped.
Cleanup complete. Connection closed.