### Initialize and Start Project with Makefile Source: https://github.com/deepgram-starters/fastapi-text-to-speech/blob/main/README.md Use the Makefile for a streamlined local development setup. 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 ``` -------------------------------- ### Initialize and Start the Application Source: https://github.com/deepgram-starters/fastapi-text-to-speech/blob/main/AGENTS.md Commands to initialize the project environment and start 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/fastapi-text-to-speech/blob/main/AGENTS.md Commands to install backend Python requirements and frontend Node.js dependencies. ```bash python3 -m venv venv && ./venv/bin/pip install -r requirements.txt Frontend: cd frontend && corepack pnpm install ``` -------------------------------- ### Clone and Set Up Project with Python and pnpm Source: https://github.com/deepgram-starters/fastapi-text-to-speech/blob/main/README.md Clone the repository, set up a Python virtual environment, install backend requirements, and install frontend dependencies using pnpm. Remember to add your DEEPGRAM_API_KEY to the .env file. ```bash git clone --recurse-submodules https://github.com/deepgram-starters/fastapi-text-to-speech.git cd fastapi-text-to-speech 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 ``` -------------------------------- ### Manage Application Lifecycle Source: https://github.com/deepgram-starters/fastapi-text-to-speech/blob/main/AGENTS.md Commands for starting, stopping, and rebuilding the application services. ```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 ``` -------------------------------- ### Initialize and Run Application Source: https://context7.com/deepgram-starters/fastapi-text-to-speech/llms.txt Use Make commands to clone the repository, set up the environment, and start the backend and frontend services. ```bash # Clone the repository with submodules git clone --recurse-submodules https://github.com/deepgram-starters/fastapi-text-to-speech.git cd fastapi-text-to-speech # Initialize the project (creates venv, installs dependencies) make init # Configure environment cp sample.env .env # Edit .env and add your DEEPGRAM_API_KEY # Start both backend and frontend make start # Backend: http://localhost:8081 # Frontend: http://localhost:8080 ``` -------------------------------- ### Start Backend Server Source: https://github.com/deepgram-starters/fastapi-text-to-speech/blob/main/README.md Run the FastAPI backend server in a separate terminal. This server will handle Text-to-Speech requests. ```bash # Terminal 1 - Backend (port 8081) ./venv/bin/python app.py ``` -------------------------------- ### Conventional Commit Examples Source: https://github.com/deepgram-starters/fastapi-text-to-speech/blob/main/AGENTS.md Standardized commit message formats for project contributions. ```text feat(fastapi-text-to-speech): add diarization support fix(fastapi-text-to-speech): resolve WebSocket close handling refactor(fastapi-text-to-speech): simplify session endpoint chore(deps): update frontend submodule ``` -------------------------------- ### Start Frontend Server Source: https://github.com/deepgram-starters/fastapi-text-to-speech/blob/main/README.md Run the frontend development server in a separate terminal. This server is typically served on port 8080. ```bash # Terminal 2 - Frontend (port 8080) cd frontend && corepack pnpm run dev -- --port 8080 --no-open ``` -------------------------------- ### GET /api/metadata Source: https://context7.com/deepgram-starters/fastapi-text-to-speech/llms.txt Returns application metadata including use case, framework, and language information. ```APIDOC ## GET /api/metadata ### Description Returns application metadata including use case, framework, and language information. This endpoint does not require authentication. ### Method GET ### Endpoint /api/metadata ### Response #### Success Response (200) - **title** (string) - Application title - **description** (string) - Application description - **author** (string) - Author information - **repository** (string) - GitHub repository URL - **useCase** (string) - Primary use case - **language** (string) - Programming language - **framework** (string) - Web framework - **sdk** (string) - SDK version - **tags** (array) - List of relevant tags #### Response Example { "title": "FastAPI Text-to-Speech", "description": "Get started using Deepgram's Text-to-Speech with this FastAPI demo app", "author": "Deepgram DX Team ", "repository": "https://github.com/deepgram-starters/fastapi-text-to-speech", "useCase": "text-to-speech", "language": "python", "framework": "fastapi", "sdk": "6.0.0-rc.1", "tags": ["text-to-speech", "tts", "speech-synthesis", "python", "fastapi"] } ``` -------------------------------- ### GET /api/session Source: https://context7.com/deepgram-starters/fastapi-text-to-speech/llms.txt Issues a JWT session token for authenticating subsequent API requests. The token expires after 1 hour. ```APIDOC ## GET /api/session ### Description Issues a JWT session token for authenticating subsequent API requests. The token expires after 1 hour and must be included in the Authorization header as a Bearer token for protected endpoints. ### Method GET ### Endpoint /api/session ### Response #### Success Response (200) - **token** (string) - JWT session token #### Response Example { "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." } ``` -------------------------------- ### Deploy Application with Docker Source: https://context7.com/deepgram-starters/fastapi-text-to-speech/llms.txt Commands to build the Docker image and run the container with environment variables. ```dockerfile # Build the Docker image docker build -f deploy/Dockerfile -t fastapi-tts . # Run the container docker run -d \ -p 8080:8080 \ -e DEEPGRAM_API_KEY=your_api_key_here \ -e SESSION_SECRET=your_production_secret \ --name fastapi-tts \ fastapi-tts # Test the containerized application curl -s http://localhost:8080/api/metadata | jq . # The Caddy server provides: # - Rate limiting: 5 req/min for /api/session, 120 req/min for other API endpoints # - Static file serving for the frontend # - Reverse proxy to the FastAPI backend ``` -------------------------------- ### Execute Development Tasks with Makefile Source: https://context7.com/deepgram-starters/fastapi-text-to-speech/llms.txt Common development commands for managing dependencies, servers, and testing. ```bash # Check prerequisites (git, python3, pip3) make check-prereqs # Initialize project with all dependencies make init # Start both backend and frontend servers make start # Start servers separately make start-backend # Backend on port 8081 make start-frontend # Frontend on port 8080 # Run contract conformance tests (requires running app) make test # Update git submodules to latest make update # Clean build artifacts (venv, node_modules, cache) make clean # Show repository and submodule status make status # Eject frontend submodule for standalone development make eject-frontend ``` -------------------------------- ### Retrieve Application Metadata Source: https://context7.com/deepgram-starters/fastapi-text-to-speech/llms.txt Fetch public application information including framework, language, and repository details. ```bash # Get application metadata curl -s http://localhost:8081/api/metadata | python3 -m json.tool # Response { "title": "FastAPI Text-to-Speech", "description": "Get started using Deepgram's Text-to-Speech with this FastAPI demo app", "author": "Deepgram DX Team (https://developers.deepgram.com)", "repository": "https://github.com/deepgram-starters/fastapi-text-to-speech", "useCase": "text-to-speech", "language": "python", "framework": "fastapi", "sdk": "6.0.0-rc.1", "tags": ["text-to-speech", "tts", "speech-synthesis", "python", "fastapi"] } ``` -------------------------------- ### Testing and Endpoint Verification Source: https://github.com/deepgram-starters/fastapi-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 ``` -------------------------------- ### Configure Environment Variables Source: https://context7.com/deepgram-starters/fastapi-text-to-speech/llms.txt Define required and optional settings in the .env file, including the Deepgram API key and server configuration. ```bash # .env file configuration # Required - Your Deepgram API key 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_secret_here ``` -------------------------------- ### Synthesize Speech with Deepgram Python SDK Source: https://context7.com/deepgram-starters/fastapi-text-to-speech/llms.txt Initializes the Deepgram client and generates audio from text using the speak.v1.audio.generate method. ```python import os from deepgram import DeepgramClient # Initialize client with API key api_key = os.environ.get("DEEPGRAM_API_KEY") deepgram = DeepgramClient(api_key=api_key) # Generate speech from text text = "Hello, this is a demonstration of Deepgram's text-to-speech capabilities." model = "aura-2-thalia-en" # or "aura-asteria-en" for legacy voice # Using the speak.v1.audio.generate method audio_generator = deepgram.speak.v1.audio.generate( text=text, model=model ) # Collect audio data from generator audio_data = b"".join(audio_generator) # Save to file with open("output.mp3", "wb") as f: f.write(audio_data) print(f"Audio saved: {len(audio_data)} bytes") ``` -------------------------------- ### Convert Text to Speech Source: https://context7.com/deepgram-starters/fastapi-text-to-speech/llms.txt Send text to the API to generate MP3 audio. Requires a valid Bearer token and supports optional voice model selection. ```bash # Get session token first TOKEN=$(curl -s http://localhost:8081/api/session | jq -r '.token') # Convert text to speech (default voice: aura-asteria-en) curl -X POST http://localhost:8081/api/text-to-speech \ -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/json" \ -d '{"text": "Hello, this is a text to speech demo using Deepgram."}' \ --output speech.mp3 # Use a specific Aura 2 voice model curl -X POST "http://localhost:8081/api/text-to-speech?model=aura-2-thalia-en" \ -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/json" \ -d '{"text": "Welcome to Deepgram Text-to-Speech!"}' \ --output speech-thalia.mp3 # Available Aura 2 voices: aura-2-thalia-en, aura-2-andromeda-en, aura-2-arcas-en, # aura-2-atlas-en, aura-2-luna-en, aura-2-orion-en, aura-2-stella-en, aura-2-zeus-en # Error handling - missing token returns 401 curl -X POST http://localhost:8081/api/text-to-speech \ -H "Content-Type: application/json" \ -d '{"text": "Hello"}' -w "\nHTTP Status: %{http_code}\n" # Response: {"error":{"type":"AuthenticationError","code":"MISSING_TOKEN","message":"Authorization header with Bearer token is required"}} # HTTP Status: 401 # Error handling - empty text returns 400 curl -X POST http://localhost:8081/api/text-to-speech \ -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/json" \ -d '{"text": ""}' -w "\nHTTP Status: %{http_code}\n" # Response: {"error":{"type":"SynthesisError","code":"SYNTHESIS_FAILED","message":"Text required"}} # HTTP Status: 400 ``` -------------------------------- ### Integrate TTS with JavaScript Frontend Source: https://context7.com/deepgram-starters/fastapi-text-to-speech/llms.txt A client class for authenticating and synthesizing speech via the FastAPI backend. ```javascript // Frontend JavaScript example (frontend/main.js pattern) class TTSClient { constructor(baseUrl = 'http://localhost:8081') { this.baseUrl = baseUrl; this.token = null; } // Get session token async authenticate() { const response = await fetch(`${this.baseUrl}/api/session`); const data = await response.json(); this.token = data.token; return this.token; } // Convert text to speech async synthesize(text, model = 'aura-asteria-en') { if (!this.token) { await this.authenticate(); } const url = new URL(`${this.baseUrl}/api/text-to-speech`); url.searchParams.set('model', model); const response = await fetch(url, { method: 'POST', headers: { 'Authorization': `Bearer ${this.token}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ text }) }); if (!response.ok) { const error = await response.json(); throw new Error(error.error?.message || 'TTS synthesis failed'); } return response.blob(); } // Play audio in browser async playText(text, model) { const audioBlob = await this.synthesize(text, model); const audioUrl = URL.createObjectURL(audioBlob); const audio = new Audio(audioUrl); await audio.play(); return audio; } } // Usage const tts = new TTSClient(); await tts.playText('Hello from the browser!', 'aura-2-luna-en'); ``` -------------------------------- ### POST /api/text-to-speech Source: https://context7.com/deepgram-starters/fastapi-text-to-speech/llms.txt Converts text to speech audio using Deepgram's Text-to-Speech API. Requires JWT authentication. ```APIDOC ## POST /api/text-to-speech ### Description Converts text to speech audio using Deepgram's Text-to-Speech API. Returns binary audio data in MP3 format. ### Method POST ### Endpoint /api/text-to-speech ### Parameters #### Query Parameters - **model** (string) - Optional - The Aura voice model to use (e.g., aura-2-thalia-en) #### Request Body - **text** (string) - Required - The text to convert to speech ### Request Example { "text": "Hello, this is a text to speech demo using Deepgram." } ### Response #### Success Response (200) - **binary** (audio/mpeg) - MP3 audio data ``` -------------------------------- ### Handle API Error Responses Source: https://context7.com/deepgram-starters/fastapi-text-to-speech/llms.txt Standardized JSON error formats for authentication, validation, and synthesis failures. ```json // Authentication error (401) { "error": { "type": "AuthenticationError", "code": "MISSING_TOKEN", "message": "Authorization header with Bearer token is required" } } // Expired token error (401) { "error": { "type": "AuthenticationError", "code": "INVALID_TOKEN", "message": "Session expired, please refresh the page" } } // Validation error (400) { "error": { "type": "ValidationError", "code": "INVALID_INPUT", "message": "Invalid request" } } // Text too long error (400) { "error": { "type": "ValidationError", "code": "TEXT_TOO_LONG", "message": "Text exceeds maximum allowed length" } } // Synthesis error (500) { "error": { "type": "SynthesisError", "code": "SYNTHESIS_FAILED", "message": "TTS synthesis failed" } } ``` -------------------------------- ### Request Session Token Source: https://context7.com/deepgram-starters/fastapi-text-to-speech/llms.txt Retrieve a JWT session token required for authenticating requests to protected API endpoints. ```bash # Request a new session token curl -X GET http://localhost:8081/api/session # Response { "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpYXQiOjE3MDk4MjQwMDAsImV4cCI6MTcwOTgyNzYwMH0.signature" } # Using the token in subsequent requests export TOKEN=$(curl -s http://localhost:8081/api/session | jq -r '.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.