### Initialize and Start the Application Source: https://github.com/deepgram-starters/ruby-live-text-to-speech/blob/main/AGENTS.md Run these commands to initialize the project, set up 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 ``` -------------------------------- ### Install Frontend Dependencies Source: https://github.com/deepgram-starters/ruby-live-text-to-speech/blob/main/AGENTS.md Install the frontend dependencies using pnpm. ```bash cd frontend && corepack pnpm install ``` -------------------------------- ### Initialize and Start the Application Source: https://github.com/deepgram-starters/ruby-live-text-to-speech/blob/main/README.md Use these commands to initialize the project, configure environment variables, and launch the local development server. ```bash make init cp sample.env .env # Add your DEEPGRAM_API_KEY make start ``` -------------------------------- ### Install Backend Dependencies Source: https://github.com/deepgram-starters/ruby-live-text-to-speech/blob/main/AGENTS.md Install the Ruby backend dependencies using Bundler. ```bash bundle install ``` -------------------------------- ### Configure Environment Variables Source: https://context7.com/deepgram-starters/ruby-live-text-to-speech/llms.txt Sets up the required API keys and server configuration. Ensure the .env file is populated before starting the application. ```bash # Create .env file from template cp sample.env .env # Required: Your Deepgram API key (get one at https://console.deepgram.com) DEEPGRAM_API_KEY=your_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 # Verify configuration bundle exec ruby -e "require 'dotenv'; Dotenv.load; puts ENV['DEEPGRAM_API_KEY'] ? 'API key configured' : 'Missing API key'" ``` -------------------------------- ### Start Application Servers Separately Source: https://github.com/deepgram-starters/ruby-live-text-to-speech/blob/main/AGENTS.md Use these commands to start the backend and frontend servers in separate terminals if needed. ```bash # Terminal 1 — Backend bundle exec ruby app.rb ``` ```bash # Terminal 2 — Frontend cd frontend && corepack pnpm run dev -- --port 8080 --no-open ``` -------------------------------- ### Manage Project with Makefile Source: https://context7.com/deepgram-starters/ruby-live-text-to-speech/llms.txt Standardized commands for initializing, running, and testing the application. Use these to handle dependencies and server lifecycles. ```bash # Check prerequisites (git, ruby, bundle) 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 (port 8081) and frontend (port 8080) make start # Or start servers separately: make start-backend # Backend only on http://localhost:8081 make start-frontend # Frontend only on http://localhost:8080 # Run contract conformance tests (requires app to be running) make test # Update git submodules to latest versions make update # Clean build artifacts (vendor/, node_modules/, etc.) make clean # Show git and submodule status make status # Eject frontend submodule for standalone development make eject-frontend ``` -------------------------------- ### Project Testing Commands Source: https://github.com/deepgram-starters/ruby-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 ``` -------------------------------- ### Clean Rebuild Project Source: https://github.com/deepgram-starters/ruby-live-text-to-speech/blob/main/AGENTS.md Perform a clean rebuild by removing vendor directories and node modules, then re-initializing the project. ```bash rm -rf vendor frontend/node_modules frontend/.vite make init ``` -------------------------------- ### Update Frontend Submodule Source: https://github.com/deepgram-starters/ruby-live-text-to-speech/blob/main/AGENTS.md Steps to modify the frontend, commit changes within the submodule, push to its repository, and then update the main project's submodule reference. ```bash cd frontend && git add . && git commit -m "feat: description" cd .. && git add frontend && git commit -m "chore(deps): update frontend submodule" ``` -------------------------------- ### Configure Rack Middleware Source: https://context7.com/deepgram-starters/ruby-live-text-to-speech/llms.txt Entry point for the Ruby application using Rack middleware to intercept WebSocket requests. The WebSocketProxy handles the upgrade and authentication logic. ```ruby # config.ru - Application entry point require_relative "app" # Wrap Sinatra app with WebSocket proxy middleware use WebSocketProxy run App # Start with: bundle exec rackup config.ru -p 8081 -o 0.0.0.0 # The WebSocketProxy middleware: # - Intercepts WebSocket upgrades to /api/live-text-to-speech # - Validates JWT from Sec-WebSocket-Protocol header ``` -------------------------------- ### Retrieve Application Metadata Source: https://context7.com/deepgram-starters/ruby-live-text-to-speech/llms.txt Fetches configuration details from the deepgram.toml file, providing information about the application's capabilities and identity. ```bash # Request application metadata curl -s http://localhost:8081/api/metadata | python3 -m json.tool # Response: # { # "title": "Ruby Live Text-to-Speech", # "description": "Get started using Deepgram's Live Text-to-Speech with this Ruby demo app", # "author": "Deepgram DX Team (https://developers.deepgram.com)", # "repository": "https://github.com/deepgram-starters/ruby-live-text-to-speech", # "useCase": "live-text-to-speech", # "language": "ruby", # "framework": "sinatra", # "tags": ["live-text-to-speech", "live-tts", "streaming-tts", "real-time-tts", "ruby", "sinatra"] # } ``` -------------------------------- ### Application Metadata Endpoint Source: https://context7.com/deepgram-starters/ruby-live-text-to-speech/llms.txt Returns metadata about the application from the `deepgram.toml` configuration file, including the title, description, use case, language, and framework information. Useful for client applications to discover app capabilities. ```APIDOC ## GET /api/metadata - Application Metadata Endpoint ### Description Returns metadata about the application from the `deepgram.toml` configuration file, including the title, description, use case, language, and framework information. Useful for client applications to discover app capabilities. ### Method GET ### Endpoint /api/metadata ### Parameters None ### Request Example None ### 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 framework used. - **tags** (array of strings) - Keywords or tags associated with the application. #### Response Example ```json { "title": "Ruby Live Text-to-Speech", "description": "Get started using Deepgram's Live Text-to-Speech with this Ruby demo app", "author": "Deepgram DX Team (https://developers.deepgram.com)", "repository": "https://github.com/deepgram-starters/ruby-live-text-to-speech", "useCase": "live-text-to-speech", "language": "ruby", "framework": "sinatra", "tags": ["live-text-to-speech", "live-tts", "streaming-tts", "real-time-tts", "ruby", "sinatra"] } ``` ``` -------------------------------- ### Request JWT Session Token Source: https://context7.com/deepgram-starters/ruby-live-text-to-speech/llms.txt Retrieves a JWT session token for WebSocket authentication and demonstrates how to initialize a connection using the token as a subprotocol. ```bash # Request a session token curl -s http://localhost:8081/api/session | python3 -m json.tool # Response: # { # "token": "eyJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE3MDk4MzI0MDAsImV4cCI6MTcwOTgzNjAwMH0.abc123..." # } # Using the token in JavaScript WebSocket connection: # const response = await fetch('http://localhost:8081/api/session'); # const { token } = await response.json(); # const ws = new WebSocket( # 'ws://localhost:8081/live-text-to-speech', # [`access_token.${token}`] # ); ``` -------------------------------- ### Stop Application Servers Source: https://github.com/deepgram-starters/ruby-live-text-to-speech/blob/main/AGENTS.md This command stops any running backend or frontend processes listening on ports 8080 and 8081. ```bash lsof -ti:8080,8081 | xargs kill -9 2>/dev/null ``` -------------------------------- ### WebSocket Message Protocol - Speak Source: https://github.com/deepgram-starters/ruby-live-text-to-speech/blob/main/AGENTS.md Send this JSON message to the WebSocket to queue text for speech synthesis. ```json { "type": "Speak", "text": "Hello world" } ``` -------------------------------- ### Construct Deepgram TTS WebSocket URL Source: https://context7.com/deepgram-starters/ruby-live-text-to-speech/llms.txt Builds the WebSocket URL with required query parameters for model selection and audio encoding. ```ruby DEEPGRAM_TTS_URL = "wss://api.deepgram.com/v1/speak" deepgram_params = URI.encode_www_form( model: "aura-asteria-en", encoding: "linear16", sample_rate: "24000", container: "none" ) deepgram_url = "#{DEEPGRAM_TTS_URL}?#{deepgram_params}" ``` -------------------------------- ### Stream Text-to-Speech via WebSocket Source: https://context7.com/deepgram-starters/ruby-live-text-to-speech/llms.txt Connects to the TTS service using a JWT subprotocol and streams text for synthesis. Requires an active AudioContext for playback and handles binary audio chunks. ```javascript // Complete WebSocket client example with authentication and audio playback async function streamTextToSpeech(text) { // Step 1: Get session token const sessionResponse = await fetch('http://localhost:8081/api/session'); const { token } = await sessionResponse.json(); // Step 2: Connect to WebSocket with authentication and TTS parameters const params = new URLSearchParams({ model: 'aura-asteria-en', // Voice model (default) encoding: 'linear16', // Audio encoding: linear16, mp3, opus, mulaw, alaw sample_rate: '24000', // Sample rate: 8000-48000 container: 'none' // Container format: none, wav, ogg }); const ws = new WebSocket( `ws://localhost:8081/api/live-text-to-speech?${params}`, [`access_token.${token}`] // JWT passed as subprotocol ); // Step 3: Handle connection and messages ws.onopen = () => { console.log('Connected to TTS service'); // Send text for synthesis ws.send(JSON.stringify({ type: 'Speak', text: 'Hello, world!' })); // Send more text ws.send(JSON.stringify({ type: 'Speak', text: 'This is streaming TTS.' })); // Signal end of text input ws.send(JSON.stringify({ type: 'Flush' })); }; // Step 4: Receive and play audio chunks const audioContext = new AudioContext({ sampleRate: 24000 }); const audioChunks = []; ws.onmessage = (event) => { if (event.data instanceof Blob) { // Binary audio data - accumulate chunks event.data.arrayBuffer().then(buffer => { audioChunks.push(new Int16Array(buffer)); }); } else { // JSON control message from Deepgram console.log('Deepgram response:', JSON.parse(event.data)); } }; ws.onclose = () => { console.log('Connection closed'); // Play accumulated audio playAudio(audioContext, audioChunks); }; ws.onerror = (error) => { console.error('WebSocket error:', error); }; } // WebSocket Message Protocol: // { "type": "Speak", "text": "Hello world" } - Queue text for synthesis // { "type": "Flush" } - Signal end of text, flush buffer // { "type": "Clear" } - Cancel pending audio // { "type": "Close" } - Graceful disconnect ``` -------------------------------- ### Conventional Commits Format Source: https://github.com/deepgram-starters/ruby-live-text-to-speech/blob/main/AGENTS.md Standardized commit message format required for project contributions. ```text feat(ruby-live-text-to-speech): add diarization support fix(ruby-live-text-to-speech): resolve WebSocket close handling refactor(ruby-live-text-to-speech): simplify session endpoint chore(deps): update frontend submodule ``` -------------------------------- ### WebSocket Message Protocol - Flush Source: https://github.com/deepgram-starters/ruby-live-text-to-speech/blob/main/AGENTS.md Send this JSON message to the WebSocket to signal the end of text input and flush any pending audio. ```json { "type": "Flush" } ``` -------------------------------- ### Check Service Health Source: https://context7.com/deepgram-starters/ruby-live-text-to-speech/llms.txt Verifies the operational status of the service, suitable for load balancer probes or automated monitoring scripts. ```bash # Check service health curl -s http://localhost:8081/health # Response: # {"status":"ok"} # Using in a health check script: if curl -sf http://localhost:8081/health > /dev/null; then echo "Service is healthy" else echo "Service is down" exit 1 fi ``` -------------------------------- ### Health Check Endpoint Source: https://context7.com/deepgram-starters/ruby-live-text-to-speech/llms.txt Simple health check endpoint for monitoring and load balancer health probes. Returns a JSON status object indicating the service is operational. ```APIDOC ## GET /health - Health Check Endpoint ### Description Simple health check endpoint for monitoring and load balancer health probes. Returns a JSON status object indicating the service is operational. ### Method GET ### Endpoint /health ### Parameters None ### Request Example None ### Response #### Success Response (200) - **status** (string) - Indicates the operational status of the service (e.g., "ok"). #### Response Example ```json {"status":"ok"} ``` ``` -------------------------------- ### WebSocket Message Protocol - Close Source: https://github.com/deepgram-starters/ruby-live-text-to-speech/blob/main/AGENTS.md Send this JSON message to the WebSocket for a graceful disconnection. ```json { "type": "Close" } ``` -------------------------------- ### WebSocket Message Protocol - Clear Source: https://github.com/deepgram-starters/ruby-live-text-to-speech/blob/main/AGENTS.md Send this JSON message to the WebSocket to cancel any currently queued or playing audio. ```json { "type": "Clear" } ``` -------------------------------- ### JWT Session Token Endpoint Source: https://context7.com/deepgram-starters/ruby-live-text-to-speech/llms.txt Issues a JWT session token for authenticating WebSocket connections. The token is valid for 1 hour and must be passed as a WebSocket subprotocol in the format `access_token.` when connecting to the TTS endpoint. ```APIDOC ## GET /api/session - JWT Session Token Endpoint ### Description Issues a JWT session token for authenticating WebSocket connections. The token is valid for 1 hour and must be passed as a WebSocket subprotocol in the format `access_token.` when connecting to the TTS endpoint. ### Method GET ### Endpoint /api/session ### Parameters None ### Request Example None ### Response #### Success Response (200) - **token** (string) - The JWT session token. #### Response Example ```json { "token": "eyJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE3MDk4MzI0MDAsImV4cCI6MTcwOTgzNjAwMH0.abc123..." } ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.