### Initialize and Start Project with Makefile Source: https://context7.com/deepgram-starters/flask-live-transcription/llms.txt Automates project initialization, dependency installation, and server startup. ```bash # Check prerequisites (git, python3, pip) make check-prereqs # Initialize project (submodules + dependencies) make init # Configure environment cp sample.env .env # Edit .env and set DEEPGRAM_API_KEY # Start both backend (port 8081) and frontend (port 8080) make start ``` -------------------------------- ### Manual environment setup Source: https://github.com/deepgram-starters/flask-live-transcription/blob/main/README.md Commands to clone the repository, create a virtual environment, and install dependencies for both backend and frontend. ```bash git clone --recurse-submodules https://github.com/deepgram-starters/flask-live-transcription.git cd flask-live-transcription python3 -m venv venv ./venv/bin/pip install -r requirements.txt cd frontend && corepack pnpm install && cd .. cp sample.env .env # Add your DEEPGRAM_API_KEY ``` -------------------------------- ### Initialize project with Makefile Source: https://github.com/deepgram-starters/flask-live-transcription/blob/main/README.md Use the provided Makefile to set up the environment and start the application. ```bash make init cp sample.env .env # Add your DEEPGRAM_API_KEY make start ``` -------------------------------- ### Install Frontend Dependencies Source: https://github.com/deepgram-starters/flask-live-transcription/blob/main/AGENTS.md Install frontend dependencies using pnpm within the `frontend` directory. ```bash cd frontend && corepack pnpm install ``` -------------------------------- ### Install Backend Dependencies Source: https://github.com/deepgram-starters/flask-live-transcription/blob/main/AGENTS.md Set up a Python virtual environment and install the necessary backend packages listed in `requirements.txt`. ```bash python3 -m venv venv && ./venv/bin/pip install -r requirements.txt ``` -------------------------------- ### Initialize and Run Flask App Source: https://github.com/deepgram-starters/flask-live-transcription/blob/main/AGENTS.md Use these commands to set up the project dependencies, configure environment variables, and start both the backend and frontend servers. ```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 ``` -------------------------------- ### Start Flask Backend Separately Source: https://github.com/deepgram-starters/flask-live-transcription/blob/main/AGENTS.md Manually start the Flask backend server in its own terminal. Ensure the Python virtual environment is activated. ```bash # Terminal 1 — Backend ./venv/bin/python app.py ``` -------------------------------- ### Start Frontend Development Server Source: https://github.com/deepgram-starters/flask-live-transcription/blob/main/AGENTS.md Manually start the frontend development server using Vite. This command specifies the port and disables automatic browser opening. ```bash # Terminal 2 — Frontend cd frontend && corepack pnpm run dev -- --port 8080 --no-open ``` -------------------------------- ### Conventional Commits Examples Source: https://github.com/deepgram-starters/flask-live-transcription/blob/main/AGENTS.md Examples of commit messages following the conventional commits format. Ensure all commits adhere to this standard. ```bash feat(flask-live-transcription): add diarization support ``` ```bash fix(flask-live-transcription): resolve WebSocket close handling ``` ```bash refactor(flask-live-transcription): simplify session endpoint ``` ```bash chore(deps): update frontend submodule ``` -------------------------------- ### Start backend and frontend servers Source: https://github.com/deepgram-starters/flask-live-transcription/blob/main/README.md Commands to run the Flask backend and the frontend development server in separate terminal sessions. ```bash # Terminal 1 - Backend (port 8081) ./venv/bin/python app.py # Terminal 2 - Frontend (port 8080) cd frontend && corepack pnpm run dev -- --port 8080 --no-open ``` -------------------------------- ### GET /api/metadata - Retrieve Application Metadata Source: https://context7.com/deepgram-starters/flask-live-transcription/llms.txt This endpoint retrieves metadata about the Flask Live Transcription starter application. The information, sourced from the `deepgram.toml` configuration file, includes details such as the use case, framework, language, and relevant tags, aiding in standardization across Deepgram starter projects. ```APIDOC ## GET /api/metadata - Retrieve Application Metadata ### Description Returns metadata about the starter application from the `deepgram.toml` configuration file, including use case, framework, language, and tags. This endpoint is used for standardization compliance across Deepgram starter applications. ### Method GET ### Endpoint /api/metadata ### Response #### Success Response (200) - **title** (string) - The title of the application. - **description** (string) - A brief description of the application. - **author** (string) - Information about the author or team. - **repository** (string) - URL to the application's repository. - **useCase** (string) - The primary use case of the application. - **language** (string) - The programming language used. - **framework** (string) - The web framework used. - **sdk** (string) - The SDK used (if any). - **tags** (array of strings) - Tags associated with the application. ### Request Example ```bash curl -s http://localhost:8081/api/metadata | python3 -m json.tool ``` ### Response Example ```json { "title": "Flask Live Transcription", "description": "Get started using Deepgram's Live Transcription with this Flask demo app", "author": "Deepgram DX Team (https://developers.deepgram.com)", "repository": "https://github.com/deepgram-starters/flask-live-transcription", "useCase": "live-transcription", "language": "python", "framework": "flask", "sdk": "N/A", "tags": ["live-transcription", "live-stt", "real-time-transcription"] } ``` ``` -------------------------------- ### GET /api/session - Issue JWT Session Token Source: https://context7.com/deepgram-starters/flask-live-transcription/llms.txt This endpoint issues a JSON Web Token (JWT) that is required for authenticating WebSocket connections to the Deepgram Live STT API. The token is valid for one hour and must be included in the `Sec-WebSocket-Protocol` header when establishing the WebSocket connection. ```APIDOC ## GET /api/session - Issue JWT Session Token ### Description Issues a JWT token for authenticating WebSocket connections. The token is valid for 1 hour and must be passed via the `Sec-WebSocket-Protocol` header when connecting to the live transcription WebSocket endpoint. ### Method GET ### Endpoint /api/session ### Response #### Success Response (200) - **token** (string) - The JWT session token. ### Request Example ```bash curl -s http://localhost:8081/api/session | python3 -m json.tool ``` ### Response Example ```json { "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpYXQiOjE3MDk1..." } ``` ``` -------------------------------- ### Deploy with Docker Source: https://context7.com/deepgram-starters/flask-live-transcription/llms.txt Build and run the application using Docker, which includes a Caddy reverse proxy for production-ready features like rate limiting. ```bash # Build the Docker image docker build -f deploy/Dockerfile -t flask-live-transcription . # Run the container docker run -d \ -p 8080:8080 \ -e DEEPGRAM_API_KEY=your_api_key_here \ -e SESSION_SECRET=your_production_secret \ flask-live-transcription # Container exposes single port 8080 with Caddy handling: # - Static frontend serving # - API reverse proxy to backend # - Rate limiting: 5 req/min for /api/session, 120 req/min for other API endpoints # - WebSocket proxying for live transcription # Verify deployment curl -s http://localhost:8080/api/metadata | python3 -m json.tool ``` -------------------------------- ### Manage Local Development Source: https://context7.com/deepgram-starters/flask-live-transcription/llms.txt Use these Makefile commands to control the backend and frontend services, update dependencies, and run tests. ```makefile make start-backend # Backend only on http://localhost:8081 make start-frontend # Frontend only on http://localhost:8080 # Other useful commands make update # Update submodules to latest make clean # Remove venv, node_modules, build artifacts make status # Show git and submodule status make test # Run contract conformance tests (requires app running) ``` -------------------------------- ### Configure Environment Variables Source: https://context7.com/deepgram-starters/flask-live-transcription/llms.txt Sets required API keys and server configuration in the .env file. ```bash # Required: Deepgram API key (get from https://console.deepgram.com) DEEPGRAM_API_KEY=your_api_key_here # Optional: Backend server configuration PORT=8081 # Backend API server port (default: 8081) HOST=0.0.0.0 # Server bind address (default: 0.0.0.0) # Optional: Production security SESSION_SECRET=your_random_secret_here # JWT signing secret (auto-generated if not set) # Create .env file from template cp sample.env .env # Edit .env and add your DEEPGRAM_API_KEY ``` -------------------------------- ### Run Conformance Tests Source: https://github.com/deepgram-starters/flask-live-transcription/blob/main/AGENTS.md Execute conformance tests for the application. This requires the backend application to be running. ```bash make test ``` -------------------------------- ### Clean Rebuild Project Source: https://github.com/deepgram-starters/flask-live-transcription/blob/main/AGENTS.md Remove build artifacts, virtual environments, and node modules to perform a clean re-initialization of the project. ```bash rm -rf venv frontend/node_modules frontend/.vite make init ``` -------------------------------- ### Fetch Application Metadata with cURL Source: https://context7.com/deepgram-starters/flask-live-transcription/llms.txt Fetch application metadata from the /api/metadata endpoint using cURL. This endpoint provides details about the starter application, such as its use case, framework, and language, for standardization compliance. ```bash # Fetch application metadata curl -s http://localhost:8081/api/metadata | python3 -m json.tool ``` ```bash # Response: # { # "title": "Flask Live Transcription", # "description": "Get started using Deepgram's Live Transcription with this Flask demo app", # "author": "Deepgram DX Team (https://developers.deepgram.com)", # "repository": "https://github.com/deepgram-starters/flask-live-transcription", # "useCase": "live-transcription", # "language": "python", # "framework": "flask", # "sdk": "N/A", # "tags": ["live-transcription", "live-stt", "real-time-transcription", ...] # } ``` ```bash # Check specific metadata fields curl -s http://localhost:8081/api/metadata | python3 -c "import sys,json; d=json.load(sys.stdin); print(f'Use Case: {d["useCase"]}, Framework: {d["framework"]}')" ``` -------------------------------- ### Connect via Python Client Source: https://context7.com/deepgram-starters/flask-live-transcription/llms.txt Establish a WebSocket connection to the transcription service using JWT authentication and the websocket-client library. ```python import json import requests import websocket import threading # Configuration BASE_URL = "http://localhost:8081" # Step 1: Get session token session_response = requests.get(f"{BASE_URL}/api/session") token = session_response.json()["token"] print(f"Session token obtained: {token[:20]}...") # Step 2: Build WebSocket URL params = { "model": "nova-3", "language": "en", "encoding": "linear16", "sample_rate": "16000", "channels": "1" } query_string = "&".join(f"{k}={v}" for k, v in params.items()) ws_url = f"ws://localhost:8081/api/live-transcription?{query_string}" # Step 3: WebSocket callbacks def on_message(ws, message): data = json.loads(message) if data.get("type") == "Results": transcript = data.get("channel", {}).get("alternatives", [{}])[0].get("transcript", "") if transcript: is_final = data.get("is_final", False) print(f"{'[FINAL]' if is_final else '[INTERIM]'} {transcript}") def on_error(ws, error): print(f"Error: {error}") def on_close(ws, close_status_code, close_msg): print(f"Connection closed: {close_status_code} - {close_msg}") def on_open(ws): print("Connected to live transcription") # Start sending audio data here # Example: ws.send(audio_bytes, opcode=websocket.ABNF.OPCODE_BINARY) # Step 4: Connect with JWT authentication subprotocol ws = websocket.WebSocketApp( ws_url, subprotocols=[f"access_token.{token}"], on_open=on_open, on_message=on_message, on_error=on_error, on_close=on_close ) ``` -------------------------------- ### Configure WebSocket Query Parameters Source: https://context7.com/deepgram-starters/flask-live-transcription/llms.txt Defines optional transcription settings passed as query parameters to the WebSocket URL. ```javascript // Full parameter configuration example const params = new URLSearchParams({ // Core settings model: 'nova-3', // STT model: nova-3, nova-2, base language: 'en', // BCP-47 language code smart_format: 'true', // Intelligent punctuation and formatting // Audio settings encoding: 'linear16', // Audio format: linear16, opus, flac sample_rate: '16000', // Hz: 8000, 16000, 44100, 48000 channels: '1', // 1 (mono) or 2 (stereo) // Additional Deepgram features (passed through to API) interim_results: 'true', // Show partial transcripts while speaking endpointing: '300', // Silence duration (ms) before finalization utterance_end_ms: '1000', // Detect end of utterance vad_events: 'true', // Voice activity detection events diarize: 'true', // Speaker identification punctuate: 'true', // Auto-punctuation no_delay: 'true' // Minimize latency (may reduce accuracy) }); const wsUrl = `ws://localhost:8081/api/live-transcription?${params}`; ``` -------------------------------- ### Verify API Endpoints Source: https://context7.com/deepgram-starters/flask-live-transcription/llms.txt Use curl to verify that the backend API is responding correctly to metadata and session requests. ```bash curl -s http://localhost:8081/api/metadata | python3 -m json.tool curl -s http://localhost:8081/api/session | python3 -m json.tool ``` -------------------------------- ### Manual Endpoint Checks Source: https://github.com/deepgram-starters/flask-live-transcription/blob/main/AGENTS.md Perform manual checks on the API endpoints for metadata and session. The output is formatted using `json_tool` for readability. ```bash curl -sf http://localhost:8081/api/metadata | python3 -m json.tool ``` ```bash curl -sf http://localhost:8081/api/session | python3 -m json.tool ``` -------------------------------- ### Connect to Live Transcription WebSocket Source: https://context7.com/deepgram-starters/flask-live-transcription/llms.txt Establishes a WebSocket connection to the transcription endpoint using a JWT subprotocol and streams browser audio data. ```javascript // JavaScript WebSocket client example async function startTranscription() { // Step 1: Get session token const sessionRes = await fetch('http://localhost:8081/api/session'); const { token } = await sessionRes.json(); // Step 2: Build WebSocket URL with transcription parameters const params = new URLSearchParams({ model: 'nova-3', // Deepgram model (nova-3, nova-2, base) language: 'en', // Language code (BCP-47) smart_format: 'true', // Enable smart formatting encoding: 'linear16', // Audio encoding sample_rate: '16000', // Sample rate in Hz channels: '1' // Mono audio }); const wsUrl = `ws://localhost:8081/api/live-transcription?${params}`; // Step 3: Connect with JWT subprotocol authentication const ws = new WebSocket(wsUrl, [`access_token.${token}`]); ws.onopen = () => { console.log('Connected to live transcription'); startAudioCapture(ws); }; ws.onmessage = (event) => { const data = JSON.parse(event.data); if (data.channel?.alternatives?.[0]?.transcript) { console.log('Transcript:', data.channel.alternatives[0].transcript); } }; ws.onerror = (error) => console.error('WebSocket error:', error); ws.onclose = (event) => console.log('Disconnected:', event.code, event.reason); } // Audio capture and streaming function startAudioCapture(ws) { navigator.mediaDevices.getUserMedia({ audio: true }).then(stream => { const audioContext = new AudioContext({ sampleRate: 16000 }); const source = audioContext.createMediaStreamSource(stream); const processor = audioContext.createScriptProcessor(4096, 1, 1); processor.onaudioprocess = (e) => { if (ws.readyState === WebSocket.OPEN) { const float32 = e.inputBuffer.getChannelData(0); // Convert Float32 to Int16 PCM const int16 = new Int16Array(float32.length); for (let i = 0; i < float32.length; i++) { int16[i] = Math.max(-32768, Math.min(32767, float32[i] * 32768)); } ws.send(int16.buffer); } }; source.connect(processor); processor.connect(audioContext.destination); }); } startTranscription(); ``` -------------------------------- ### Stop Running Servers Source: https://github.com/deepgram-starters/flask-live-transcription/blob/main/AGENTS.md This command finds and terminates processes listening on ports 8080 and 8081, effectively stopping both the backend and frontend servers. ```bash lsof -ti:8080,8081 | xargs kill -9 2>/dev/null ``` -------------------------------- ### Handle WebSocket Transcription Responses Source: https://context7.com/deepgram-starters/flask-live-transcription/llms.txt Process incoming WebSocket messages to extract transcripts, metadata, and event signals like utterance ends or speech detection. ```javascript // Handle incoming transcription messages ws.onmessage = (event) => { const response = JSON.parse(event.data); // Check for transcription results if (response.type === 'Results') { const alternative = response.channel?.alternatives?.[0]; if (alternative) { const transcript = alternative.transcript; const confidence = alternative.confidence; const isFinal = response.is_final; const speechFinal = response.speech_final; if (transcript) { if (isFinal) { console.log(`[FINAL] ${transcript} (confidence: ${confidence})`); // Append to final transcript display } else { console.log(`[INTERIM] ${transcript}`); // Update interim transcript display } } } } // Handle metadata messages if (response.type === 'Metadata') { console.log('Request ID:', response.request_id); console.log('Model:', response.model_info?.name); } // Handle utterance end events (if utterance_end_ms is set) if (response.type === 'UtteranceEnd') { console.log('Utterance ended at:', response.last_word_end); } // Handle speech started events (if vad_events is true) if (response.type === 'SpeechStarted') { console.log('Speech detected at:', response.timestamp); } }; ``` -------------------------------- ### Request JWT Session Token with cURL Source: https://context7.com/deepgram-starters/flask-live-transcription/llms.txt Use cURL to request a JWT session token from the /api/session endpoint. This token is required for authenticating WebSocket connections to the Deepgram service. The token is valid for 1 hour. ```bash # Request a session token curl -s http://localhost:8081/api/session | python3 -m json.tool ``` ```bash # Response: # { # "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpYXQiOjE3MDk1..." # } ``` ```bash # Store token for WebSocket authentication TOKEN=$(curl -s http://localhost:8081/api/session | python3 -c "import sys,json; print(json.load(sys.stdin)['token'])") echo "Session token: $TOKEN" ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.