### Initialize and Start Project with Makefile Source: https://github.com/deepgram-starters/flask-live-text-to-speech/blob/main/README.md Use this Makefile target to initialize the project, copy the sample environment file, and start the application. Ensure your DEEPGRAM_API_KEY is added to the .env file. ```bash make init cp sample.env .env # Add your DEEPGRAM_API_KEY make start ``` -------------------------------- ### Install Dependencies Source: https://github.com/deepgram-starters/flask-live-text-to-speech/blob/main/AGENTS.md Commands to install Python and Node.js dependencies. ```bash python3 -m venv venv && ./venv/bin/pip install -r requirements.txt ``` ```bash cd frontend && corepack pnpm install ``` -------------------------------- ### Initialize Project Environment Source: https://github.com/deepgram-starters/flask-live-text-to-speech/blob/main/AGENTS.md Commands to clone submodules, install dependencies, and prepare the environment. ```bash # Initialize (clone submodules + install deps) make init # Set up environment test -f .env || cp sample.env .env # then set DEEPGRAM_API_KEY # Start both servers make start # Backend: http://localhost:8081 # Frontend: http://localhost:8080 ``` -------------------------------- ### Clone and Set Up Project with Python and pnpm Source: https://github.com/deepgram-starters/flask-live-text-to-speech/blob/main/README.md Clone the repository, set up a Python virtual environment, install Python dependencies, and install frontend dependencies using pnpm. Copy the sample environment file and add your DEEPGRAM_API_KEY. ```bash git clone --recurse-submodules https://github.com/deepgram-starters/flask-live-text-to-speech.git cd flask-live-text-to-speech python3 -m venv venv ./venv/bin/pip install -r requirements.txt cd frontend && corepack pnpm install && cd .. ``` -------------------------------- ### Manage Project Lifecycle with Makefile Source: https://context7.com/deepgram-starters/flask-live-text-to-speech/llms.txt Use these commands to initialize the environment, start servers, and run tests. ```bash # Initialize project (clone submodules, create venv, install dependencies) make init # Create environment configuration cp sample.env .env # Edit .env and add your DEEPGRAM_API_KEY # Start both backend (port 8081) and frontend (port 8080) make start # Or start servers separately make start-backend # Backend on http://localhost:8081 make start-frontend # Frontend on http://localhost:8080 # Run conformance tests make test # Clean build artifacts make clean ``` -------------------------------- ### Start Backend and Frontend Servers Source: https://github.com/deepgram-starters/flask-live-text-to-speech/blob/main/README.md Instructions for starting the backend Flask server and the frontend development server in separate terminals. The backend runs on port 8081 and the frontend on port 8080. ```bash # Terminal 1 - Backend (port 8081) ./venv/bin/python app.py ``` ```bash # Terminal 2 - Frontend (port 8080) cd frontend && corepack pnpm run dev -- --port 8080 --no-open ``` -------------------------------- ### Start and Stop Application Servers Source: https://github.com/deepgram-starters/flask-live-text-to-speech/blob/main/AGENTS.md Commands for managing the lifecycle of the backend and frontend servers. ```bash make start ``` ```bash # Terminal 1 — Backend ./venv/bin/python app.py # Terminal 2 — Frontend cd frontend && corepack pnpm run dev -- --port 8080 --no-open ``` ```bash lsof -ti:8080,8081 | xargs kill -9 2>/dev/null ``` ```bash rm -rf venv frontend/node_modules frontend/.vite make init ``` -------------------------------- ### Conventional Commit Examples Source: https://github.com/deepgram-starters/flask-live-text-to-speech/blob/main/AGENTS.md Standardized commit message formats for project contributions. ```text feat(flask-live-text-to-speech): add diarization support fix(flask-live-text-to-speech): resolve WebSocket close handling refactor(flask-live-text-to-speech): simplify session endpoint chore(deps): update frontend submodule ``` -------------------------------- ### Configure Environment Variables Source: https://context7.com/deepgram-starters/flask-live-text-to-speech/llms.txt Define required API keys and server settings in the .env file. ```bash # .env file configuration # Required - Your Deepgram API key DEEPGRAM_API_KEY=your_deepgram_api_key_here # Optional - Backend server port (default: 8081) PORT=8081 # Optional - Server bind address (default: 0.0.0.0) HOST=0.0.0.0 # Optional - JWT signing secret for session tokens (auto-generated if not set) SESSION_SECRET=your_secure_random_secret_here ``` -------------------------------- ### Application Testing Commands Source: https://github.com/deepgram-starters/flask-live-text-to-speech/blob/main/AGENTS.md Commands for running conformance tests and verifying API endpoints. ```bash # Run conformance tests (requires app to be running) make test # Manual endpoint check curl -sf http://localhost:8081/api/metadata | python3 -m json.tool curl -sf http://localhost:8081/api/session | python3 -m json.tool ``` -------------------------------- ### Retrieve Application Metadata Source: https://context7.com/deepgram-starters/flask-live-text-to-speech/llms.txt Retrieves configuration metadata for the starter application from the deepgram.toml file. ```bash # Request application metadata curl -X GET http://localhost:8081/api/metadata # Response { "title": "Flask Live Text-to-Speech", "description": "Get started using Deepgram's Live Text-to-Speech with this Flask demo app", "author": "Deepgram DX Team (https://developers.deepgram.com)", "repository": "https://github.com/deepgram-starters/flask-live-text-to-speech", "useCase": "live-text-to-speech", "language": "python", "framework": "flask", "tags": ["live-text-to-speech", "live-tts", "streaming-tts", "real-time-tts", "streaming-text-to-speech", "python", "flask"] } ``` -------------------------------- ### Configure WebSocket Query Parameters Source: https://context7.com/deepgram-starters/flask-live-text-to-speech/llms.txt Sets TTS output format options such as model, encoding, sample rate, and container via URL query parameters. ```javascript // Available query parameters with defaults const params = new URLSearchParams({ model: 'aura-asteria-en', // Deepgram TTS voice model encoding: 'linear16', // Audio encoding: linear16, mp3, opus, mulaw, alaw sample_rate: '48000', // Sample rate: 8000-48000 Hz container: 'none' // Container format: none, wav, ogg }); const ws = new WebSocket( `ws://localhost:8081/api/live-text-to-speech?${params}`, [`access_token.${token}`] ); ``` -------------------------------- ### Send Text for Synthesis Source: https://context7.com/deepgram-starters/flask-live-text-to-speech/llms.txt Sends text messages to the WebSocket for synthesis. Multiple messages can be queued for continuous generation. ```javascript // Queue text for synthesis ws.send(JSON.stringify({ type: 'Speak', text: 'Hello, this is a test of Deepgram live text-to-speech.' })); // Queue additional text ws.send(JSON.stringify({ type: 'Speak', text: 'You can send multiple messages to create a continuous audio stream.' })); ``` -------------------------------- ### Establish WebSocket Connection Source: https://context7.com/deepgram-starters/flask-live-text-to-speech/llms.txt Connects to the live TTS endpoint using JWT authentication via the Sec-WebSocket-Protocol header. ```javascript // JavaScript WebSocket client example const token = await fetch('http://localhost:8081/api/session') .then(res => res.json()) .then(data => data.token); // Connect with authentication and TTS parameters const ws = new WebSocket( 'ws://localhost:8081/api/live-text-to-speech?model=aura-asteria-en&encoding=linear16&sample_rate=48000&container=none', [`access_token.${token}`] ); // Handle incoming binary audio data ws.onmessage = (event) => { if (event.data instanceof Blob) { // Binary audio chunk - process for playback event.data.arrayBuffer().then(buffer => { const int16Array = new Int16Array(buffer); // Convert to Float32 for Web Audio API const float32Array = new Float32Array(int16Array.length); for (let i = 0; i < int16Array.length; i++) { float32Array[i] = int16Array[i] / 32768.0; } // Queue for audio playback... }); } else { // JSON control message console.log('Control message:', JSON.parse(event.data)); } }; ws.onopen = () => { console.log('Connected to TTS'); }; ``` -------------------------------- ### Implement WebSocket Proxy in Flask Source: https://context7.com/deepgram-starters/flask-live-text-to-speech/llms.txt This backend route handles authentication and bidirectional message forwarding between the client and Deepgram. ```python # Core WebSocket proxy pattern from app.py import websocket from flask_sock import Sock from urllib.parse import urlencode @sock.route('/api/live-text-to-speech') def live_text_to_speech(ws): # Validate JWT from WebSocket subprotocol valid_proto = validate_ws_token() if not valid_proto: ws.close(4401, "Unauthorized") return # Get TTS parameters from query string model = request.args.get('model', 'aura-asteria-en') encoding = request.args.get('encoding', 'linear16') sample_rate = request.args.get('sample_rate', '48000') container = request.args.get('container', 'none') # Build Deepgram WebSocket URL deepgram_params = { 'model': model, 'encoding': encoding, 'sample_rate': sample_rate, 'container': container } deepgram_url = f"wss://api.deepgram.com/v1/speak?{urlencode(deepgram_params)}" # Create connection to Deepgram deepgram_ws = websocket.WebSocketApp( deepgram_url, header={'Authorization': f'Token {API_KEY}'}, on_message=lambda dg_ws, msg: ws.send(msg), # Forward to client on_error=lambda dg_ws, err: print(f"Error: {err}"), on_close=lambda dg_ws, code, msg: print(f"Closed: {code}") ) # Run Deepgram connection in background thread import threading dg_thread = threading.Thread(target=deepgram_ws.run_forever) dg_thread.daemon = True dg_thread.start() # Forward client messages to Deepgram while True: message = ws.receive(timeout=0.1) if message: if isinstance(message, bytes): deepgram_ws.send(message, opcode=websocket.ABNF.OPCODE_BINARY) else: deepgram_ws.send(message) ``` -------------------------------- ### Retrieve Session Token Source: https://context7.com/deepgram-starters/flask-live-text-to-speech/llms.txt Fetches a JWT session token required for authenticating WebSocket connections to the live TTS endpoint. ```bash # Request a new session token curl -X GET http://localhost:8081/api/session # Response { "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpYXQiOjE3MDk4NzY1NDIsImV4cCI6MTcwOTg4MDE0Mn0.abc123..." } ``` -------------------------------- ### Flush Audio Buffer Source: https://context7.com/deepgram-starters/flask-live-text-to-speech/llms.txt Signals the server to finish processing and flush all pending audio data. ```javascript // After sending all text, flush the buffer ws.send(JSON.stringify({ type: 'Flush' })); // Server will generate remaining audio and send it ``` -------------------------------- ### Close Connection Gracefully Source: https://context7.com/deepgram-starters/flask-live-text-to-speech/llms.txt Sends a close message to the server before closing the WebSocket connection. ```javascript // Graceful disconnect ws.send(JSON.stringify({ type: 'Close' })); // Then close the WebSocket ws.close(); ``` -------------------------------- ### Clear Pending Audio Source: https://context7.com/deepgram-starters/flask-live-text-to-speech/llms.txt Cancels any audio currently in the queue that has not yet been sent to the client. ```javascript // Cancel any pending audio generation ws.send(JSON.stringify({ type: 'Clear' })); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.