### Initialize and Start the Application Source: https://github.com/deepgram-starters/rust-live-transcription/blob/main/AGENTS.md Commands to initialize submodules, install dependencies, and launch 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 ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/deepgram-starters/rust-live-transcription/blob/main/AGENTS.md Commands to install backend and frontend dependencies. ```bash Install: `cargo build` Frontend: `cd frontend && corepack pnpm install` ``` -------------------------------- ### Project Initialization Commands Source: https://context7.com/deepgram-starters/rust-live-transcription/llms.txt Makefile commands for setting up the development environment and starting the services. ```bash # Check prerequisites (git, cargo, pnpm) make check-prereqs # Initialize project: clone submodules and install all dependencies make init # Set up environment cp sample.env .env # Edit .env and add your DEEPGRAM_API_KEY # Start both backend (8081) and frontend (8080) servers make start ``` -------------------------------- ### Conventional Commit Examples Source: https://github.com/deepgram-starters/rust-live-transcription/blob/main/AGENTS.md Standardized commit message formats for the project. ```text feat(rust-live-transcription): add diarization support fix(rust-live-transcription): resolve WebSocket close handling refactor(rust-live-transcription): simplify session endpoint chore(deps): update frontend submodule ``` -------------------------------- ### Manage Application Lifecycle Source: https://github.com/deepgram-starters/rust-live-transcription/blob/main/AGENTS.md Commands for starting, stopping, and rebuilding the application environment. ```bash make start ``` ```bash # Terminal 1 — Backend cargo run # 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 target frontend/node_modules frontend/.vite make init ``` -------------------------------- ### Initialize and Run the Rust Project Source: https://github.com/deepgram-starters/rust-live-transcription/blob/main/README.md Use the Makefile to initialize the environment, configure the API key, and start the application. ```bash make init cp sample.env .env # Add your DEEPGRAM_API_KEY make start ``` -------------------------------- ### GET /api/metadata Source: https://github.com/deepgram-starters/rust-live-transcription/blob/main/AGENTS.md Retrieves application metadata including use case, framework, and language. ```APIDOC ## GET /api/metadata ### Description Returns app metadata such as the use case, framework, and programming language. ### Method GET ### Endpoint /api/metadata ``` -------------------------------- ### Get Project Metadata Source: https://context7.com/deepgram-starters/rust-live-transcription/llms.txt Retrieve project information from deepgram.toml for frontend display. ```bash # Request project metadata curl -s http://localhost:8081/api/metadata | python3 -m json.tool # Response: { "title": "Rust Live Transcription", "description": "Get started using Deepgram's Live Transcription with this Rust demo app", "author": "Deepgram DX Team (https://developers.deepgram.com)", "repository": "https://github.com/deepgram-starters/rust-live-transcription", "useCase": "live-transcription", "language": "Rust", "framework": "Axum", "sdk": "N/A", "tags": ["live-transcription", "live-stt", "real-time-transcription", "real-time-asr", "streaming-transcription", "live-speech-to-text", "rust", "axum"] } ``` -------------------------------- ### Rust Axum Router Setup Source: https://context7.com/deepgram-starters/rust-live-transcription/llms.txt Configures the Axum router with API endpoints for session, metadata, live transcription, and health checks. Includes CORS layer for cross-origin requests. ```rust // Router setup with CORS let app = Router::new() .route("/api/session", get(handle_session)) .route("/api/metadata", get(handle_metadata)) .route("/api/live-transcription", get(handle_live_transcription)) .route("/health", get(handle_health)) .layer(CorsLayer::new().allow_origin(Any).allow_methods(Any).allow_headers(Any)) .with_state(state); ``` -------------------------------- ### GET /api/metadata - Get Project Metadata Source: https://context7.com/deepgram-starters/rust-live-transcription/llms.txt Returns the `[meta]` section from `deepgram.toml`, providing project information including title, description, use case, framework, and tags. Useful for frontend display and project identification. ```APIDOC ## GET /api/metadata - Get Project Metadata ### Description Returns the `[meta]` section from `deepgram.toml`, providing project information including title, description, use case, framework, and tags. Useful for frontend display and project identification. ### Method GET ### Endpoint /api/metadata ### Parameters ### Request Example ```bash curl -s http://localhost:8081/api/metadata | python3 -m json.tool ``` ### Response #### Success Response (200) - **title** (string) - The title of the project. - **description** (string) - A brief description of the project. - **author** (string) - The author(s) of the project. - **repository** (string) - The URL of the project's repository. - **useCase** (string) - The primary use case of the project. - **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 project. #### Response Example ```json { "title": "Rust Live Transcription", "description": "Get started using Deepgram's Live Transcription with this Rust demo app", "author": "Deepgram DX Team (https://developers.deepgram.com)", "repository": "https://github.com/deepgram-starters/rust-live-transcription", "useCase": "live-transcription", "language": "Rust", "framework": "Axum", "sdk": "N/A", "tags": ["live-transcription", "live-stt", "real-time-transcription", "real-time-asr", "streaming-transcription", "live-speech-to-text", "rust", "axum"] } ``` ``` -------------------------------- ### GET /api/session Source: https://github.com/deepgram-starters/rust-live-transcription/blob/main/AGENTS.md Issues a JWT session token for authentication. ```APIDOC ## GET /api/session ### Description Issues a JWT session token used for authenticating WebSocket connections. ### Method GET ### Endpoint /api/session ``` -------------------------------- ### GET /health - Health Check Source: https://context7.com/deepgram-starters/rust-live-transcription/llms.txt Returns a simple health check response to verify the server is running. Useful for container orchestration, load balancers, and monitoring systems. ```APIDOC ## GET /health - Health Check ### Description Returns a simple health check response to verify the server is running. Useful for container orchestration, load balancers, and monitoring systems. ### Method GET ### Endpoint /health ### Parameters ### Request Example ```bash curl -s http://localhost:8081/health | python3 -m json.tool ``` ### Response #### Success Response (200) - **status** (string) - The status of the server (e.g., "ok"). #### Response Example ```json { "status": "ok" } ``` ``` -------------------------------- ### GET /api/session - Issue JWT Session Token Source: https://context7.com/deepgram-starters/rust-live-transcription/llms.txt Issues a signed JWT session token with a 1-hour expiry for authenticating WebSocket connections. The token is required before establishing a live transcription WebSocket connection and must be passed via the `access_token.` subprotocol. ```APIDOC ## GET /api/session - Issue JWT Session Token ### Description Issues a signed JWT session token with a 1-hour expiry for authenticating WebSocket connections. The token is required before establishing a live transcription WebSocket connection and must be passed via the `access_token.` subprotocol. ### Method GET ### Endpoint /api/session ### Parameters ### Request Example ```bash curl -s http://localhost:8081/api/session | python3 -m json.tool ``` ### Response #### Success Response (200) - **token** (string) - A signed JWT session token. #### Response Example ```json { "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpYXQiOjE3MDk4MjQ0MDAsImV4cCI6MTcwOTgyODAwMH0.abc123..." } ``` #### Error Response - **error** (string) - An error code (e.g., "INTERNAL_SERVER_ERROR"). - **message** (string) - A descriptive error message. #### Error Response Example ```json { "error": "INTERNAL_SERVER_ERROR", "message": "Failed to issue session token" } ``` ``` -------------------------------- ### Rust Axum Server Initialization Source: https://context7.com/deepgram-starters/rust-live-transcription/llms.txt Initializes and runs the Axum server, setting up graceful shutdown handling to ensure all requests are processed before the server stops. ```rust // Server with graceful shutdown axum::serve(listener, app) .with_graceful_shutdown(shutdown_signal(state)) .await?; ``` -------------------------------- ### Run Project Tests and Endpoint Checks Source: https://github.com/deepgram-starters/rust-live-transcription/blob/main/AGENTS.md Commands to execute the test suite and verify API endpoints via curl. ```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 ``` -------------------------------- ### Environment Variable Configuration Source: https://context7.com/deepgram-starters/rust-live-transcription/llms.txt Defines the required and optional environment variables for the backend server. ```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 production (auto-generated if not set) SESSION_SECRET=your_secure_random_secret_here ``` -------------------------------- ### Check Server Health Source: https://context7.com/deepgram-starters/rust-live-transcription/llms.txt Verify the server status for monitoring and orchestration purposes. ```bash # Check server health curl -s http://localhost:8081/health | python3 -m json.tool # Response: { "status": "ok" } ``` -------------------------------- ### Rust Backend Core Dependencies Source: https://context7.com/deepgram-starters/rust-live-transcription/llms.txt Essential dependencies for the Rust backend, including Axum for web handling, Tokio for async runtime, and libraries for WebSocket and JWT. ```toml # Core dependencies (Cargo.toml) # axum = { version = "0.8", features = ["ws"] } # tokio = { version = "1", features = ["full"] } # tokio-tungstenite = { version = "0.24", features = ["native-tls"] } # jsonwebtoken = "9" # serde_json = "1" ``` -------------------------------- ### Rust Configuration Structure Source: https://context7.com/deepgram-starters/rust-live-transcription/llms.txt Defines the configuration parameters for the backend, including Deepgram API credentials, server host and port, and JWT session secret. ```rust // Configuration structure struct Config { deepgram_api_key: String, deepgram_stt_url: String, // wss://api.deepgram.com/v1/listen port: u16, // Default: 8081 host: String, // Default: 0.0.0.0 session_secret: Vec, // For JWT signing } ``` -------------------------------- ### WebSocket Query Parameters Configuration Source: https://context7.com/deepgram-starters/rust-live-transcription/llms.txt Lists supported query parameters for customizing Deepgram STT behavior via the WebSocket URL. ```bash # Default parameters (applied if not specified): # model=nova-3, language=en, smart_format=true, punctuate=true, # diarize=false, filler_words=false, encoding=linear16, sample_rate=16000, channels=1 # Additional Deepgram features can be enabled via query params: # 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 # keywords=deepgram:2 - Boost keyword with weight # no_delay=true - Minimize latency (may reduce accuracy) # Example WebSocket URL with custom params: ws://localhost:8081/api/live-transcription?model=nova-3&language=en&diarize=true&interim_results=true&smart_format=true ``` -------------------------------- ### WS /api/live-transcription Source: https://github.com/deepgram-starters/rust-live-transcription/blob/main/AGENTS.md Establishes a WebSocket connection to stream microphone audio to Deepgram for real-time transcription. ```APIDOC ## WS /api/live-transcription ### Description Streams microphone audio to Deepgram for real-time transcription. Requires a JWT session token in the subprotocol (access_token.). ### Method WS ### Endpoint /api/live-transcription ``` -------------------------------- ### Update Frontend Submodule Source: https://github.com/deepgram-starters/rust-live-transcription/blob/main/AGENTS.md Commands to commit and push changes made within the frontend submodule directory. ```bash cd frontend && git add . && git commit -m "feat: description" ``` ```bash cd frontend && git push origin main ``` ```bash cd .. && git add frontend && git commit -m "chore(deps): update frontend submodule" ``` -------------------------------- ### Fetch API Metadata Source: https://context7.com/deepgram-starters/rust-live-transcription/llms.txt Retrieve metadata from the backend API using curl. This can be useful for understanding available API features. ```bash curl -sf http://localhost:8081/api/metadata | python3 -m json.tool ``` -------------------------------- ### Request Session Token Source: https://context7.com/deepgram-starters/rust-live-transcription/llms.txt Obtain a session token from the backend API, which is required for establishing a WebSocket connection for live transcription. ```bash curl -sf http://localhost:8081/api/session | python3 -m json.tool ``` -------------------------------- ### Verify Backend Health Endpoint Source: https://context7.com/deepgram-starters/rust-live-transcription/llms.txt Use curl to check the health status of the backend API. Ensure the backend is running before executing. ```bash curl -sf http://localhost:8081/health | python3 -m json.tool ``` -------------------------------- ### Browser JavaScript Live Transcription Flow Source: https://context7.com/deepgram-starters/rust-live-transcription/llms.txt Implements the full lifecycle of a live transcription session, including token retrieval, WebSocket connection, audio capture, and result handling. ```javascript // Browser JavaScript: Complete live transcription flow // Step 1: Get session token const sessionRes = await fetch('http://localhost:8081/api/session'); const { token } = await sessionRes.json(); // Step 2: Connect WebSocket with auth token as subprotocol const params = new URLSearchParams({ model: 'nova-3', language: 'en', smart_format: 'true', punctuate: 'true', diarize: 'false', encoding: 'linear16', sample_rate: '16000', channels: '1' }); const ws = new WebSocket( `ws://localhost:8081/api/live-transcription?${params}`, [`access_token.${token}`] ); ws.onopen = () => { console.log('WebSocket connected, starting audio capture...'); startAudioCapture(); }; ws.onmessage = (event) => { const result = JSON.parse(event.data); // Deepgram transcription result format: // { // "type": "Results", // "channel_index": [0, 1], // "duration": 1.5, // "start": 0.0, // "is_final": true, // "channel": { // "alternatives": [{ // "transcript": "Hello world", // "confidence": 0.98, // "words": [...] // }] // } // } if (result.channel?.alternatives?.[0]?.transcript) { console.log('Transcript:', result.channel.alternatives[0].transcript); } }; ws.onerror = (error) => console.error('WebSocket error:', error); ws.onclose = (event) => console.log('WebSocket closed:', event.code, event.reason); // Step 3: Capture and send audio async function startAudioCapture() { const stream = await navigator.mediaDevices.getUserMedia({ audio: true }); 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 float32Data = e.inputBuffer.getChannelData(0); // Convert Float32 to Int16 PCM const int16Data = new Int16Array(float32Data.length); for (let i = 0; i < float32Data.length; i++) { int16Data[i] = Math.max(-32768, Math.min(32767, float32Data[i] * 32768)); } ws.send(int16Data.buffer); } }; source.connect(processor); processor.connect(audioContext.destination); } // Step 4: Close connection when done function stopTranscription() { ws.close(1000, 'User stopped'); } ``` -------------------------------- ### Rust JWT Claims Structure Source: https://context7.com/deepgram-starters/rust-live-transcription/llms.txt Defines the structure for JWT claims, including issued at and expiry timestamps, used for authentication. ```rust // JWT Claims with 1-hour expiry #[derive(Debug, Serialize, Deserialize)] struct Claims { iat: i64, // Issued at timestamp exp: i64, // Expiry timestamp (iat + 3600) } ``` -------------------------------- ### Issue JWT Session Token Source: https://context7.com/deepgram-starters/rust-live-transcription/llms.txt Request a signed JWT session token required for authenticating WebSocket connections. ```bash # Request a new session token curl -s http://localhost:8081/api/session | python3 -m json.tool # Response: { "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpYXQiOjE3MDk4MjQ0MDAsImV4cCI6MTcwOTgyODAwMH0.abc123..." } # Error response (internal server error): { "error": "INTERNAL_SERVER_ERROR", "message": "Failed to issue session token" } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.