To create a real-time streaming speech-to-text (STT) application using Twilio and Google Cloud Speech-to-Text (GCP STT) with FastAPI, you will need to follow several steps. This involves setting up a FastAPI application that can handle WebSocket connections for real-time audio streaming from Twilio, and then using GCP's Speech-to-Text API for transcription.
First, ensure you have the necessary dependencies installed:
pip install fastapi uvicorn twilio google-cloud-speech
Here's a step-by-step guide and example code to achieve this:
Step 1: Setup GCP Speech-to-Text
- Create a GCP project and enable the Speech-to-Text API.
- Create credentials (OAuth client ID) for your project. Download the JSON key file.
Step 2: Configure Twilio
- Create a Twilio account and purchase a phone number.
- Configure the phone number to send incoming call audio to your FastAPI application's WebSocket endpoint.
Step 3: FastAPI Application
Below is an example FastAPI application that demonstrates how to handle Twilio's WebSocket connections and stream audio to GCP STT for real-time transcription.
from fastapi import FastAPI, WebSocket
from google.cloud import speech
from twilio.twiml.voice_response import VoiceResponse, Connect, Stream
from pydub import AudioSegment
from pydub.playback import play
import logging
import io
import os
# Set up logging
logging.basicConfig(level=logging.INFO)
# Initialize FastAPI app
app = FastAPI()
# Set up GCP STT client
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = 'path/to/your/gcp-credentials.json'
client = speech.SpeechClient()
@app.get("/twiml")
async def twiml():
"""Returns TwiML to stream audio to the WebSocket endpoint."""
response = VoiceResponse()
connect = Connect()
stream = Stream(url=f"wss://your-fastapi-app.com/ws")
connect.append(stream)
response.append(connect)
return response
@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
"""Handles WebSocket connection for real-time audio streaming."""
await websocket.accept()
logging.info("WebSocket connection established")
# Configure GCP STT streaming
config = speech.RecognitionConfig(
encoding=speech.RecognitionConfig.AudioEncoding.MULAW,
sample_rate_hertz=8000,
language_code="en-US",
)
streaming_config = speech.StreamingRecognitionConfig(config=config, interim_results=True)
# Create a generator that yields audio data from the WebSocket
async def audio_stream(websocket):
while True:
try:
data = await websocket.receive_bytes()
# Twilio sends a 'start' message, followed by 'media' messages with audio
if data.startswith(b'{"event":"start"}'):
logging.info("Received start event")
elif data.startswith(b'{"event":"media"}'):
# Extract the audio data (mulaw encoded) from the 'media' message
import json
msg = json.loads(data.decode('utf-8'))
audio_data = bytes.fromhex(msg['media']['payload'])
yield speech.StreamingRecognizeRequest(audio_content=audio_data)
except Exception as e:
logging.error(f"Error in audio stream: {e}")
break
# Create a GCP STT streaming request
requests = (speech.StreamingRecognizeRequest(streaming_config=streaming_config),
*(audio_stream(websocket)))
responses = client.streaming_recognize(requests)
# Process the responses from GCP STT
for response in responses:
for result in response.results:
for alternative in result.alternatives:
transcript = alternative.transcript
logging.info(f"Transcript: {transcript}")
# You can send the transcript back to the client or handle it as needed
await websocket.send_text(transcript)
logging.info("WebSocket connection closed")
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)
Notes
- Replace placeholders: Make sure to replace
'path/to/your/gcp-credentials.json' with the actual path to your GCP credentials JSON file and https://your-fastapi-app.com/ws with your actual FastAPI WebSocket endpoint URL.
- Twilio Configuration: You need to configure your Twilio phone number to send the call audio to your FastAPI app's
/twiml endpoint, which will then instruct Twilio to stream the audio to the /ws WebSocket endpoint.
- GCP STT Configuration: The example assumes you're using the
MULAW encoding and a sample rate of 8000 Hz, which is typical for telephony applications. Adjust the RecognitionConfig as necessary for your specific use case.
This example provides a basic framework. Depending on your requirements, you might need to adjust the error handling, add additional logging, or modify the GCP STT configuration.