### Initialize and Start the Application Source: https://context7.com/deepgram-starters/php-transcription/llms.txt Use make commands to check prerequisites, install dependencies, and launch the backend server. ```bash # Check prerequisites (git, php, composer, pnpm) make check-prereqs # Initialize submodules and install all dependencies make init # Copy environment file and add your Deepgram API key cp sample.env .env # Edit .env and set DEEPGRAM_API_KEY=your_api_key_here # Start the application (backend on 8081, frontend on 8080) make start # Or start backend only make start-backend ``` -------------------------------- ### Install Backend Dependencies Source: https://github.com/deepgram-starters/php-transcription/blob/main/AGENTS.md Installs PHP dependencies using Composer, as defined in the `composer.json` file. ```bash composer install ``` -------------------------------- ### Start PHP Backend Separately Source: https://github.com/deepgram-starters/php-transcription/blob/main/AGENTS.md To start only the PHP backend server, navigate to the project directory and run the `server.php` script using the PHP built-in server. ```bash # Terminal 1 — Backend php server.php ``` -------------------------------- ### Install Frontend Dependencies Source: https://github.com/deepgram-starters/php-transcription/blob/main/AGENTS.md Installs frontend dependencies using pnpm within the `frontend` directory. ```bash cd frontend && corepack pnpm install ``` -------------------------------- ### Initialize and Start the PHP App Source: https://github.com/deepgram-starters/php-transcription/blob/main/AGENTS.md Use these make commands to initialize dependencies, set up the environment by copying a sample .env file, 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 ``` -------------------------------- ### Initialize and Start PHP Transcription App Source: https://github.com/deepgram-starters/php-transcription/blob/main/README.md Use this Makefile command to initialize the project, set up your API key, and start the local development server. 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 ``` -------------------------------- ### Start Frontend Separately Source: https://github.com/deepgram-starters/php-transcription/blob/main/AGENTS.md To start only the frontend development server using Vite, navigate to the `frontend` directory and run the `dev` script with specified port and options. ```bash # Terminal 2 — Frontend cd frontend && corepack pnpm run dev -- --port 8080 --no-open ``` -------------------------------- ### Conventional Commits Examples Source: https://github.com/deepgram-starters/php-transcription/blob/main/AGENTS.md Examples of commit messages following the conventional commits format. Ensure all commits adhere to this standard. ```bash feat(php-transcription): add diarization support ``` ```bash fix(php-transcription): resolve WebSocket close handling ``` ```bash refactor(php-transcription): simplify session endpoint ``` ```bash chore(deps): update frontend submodule ``` -------------------------------- ### Request Application Metadata Source: https://context7.com/deepgram-starters/php-transcription/llms.txt Retrieve the application metadata via a GET request. ```bash curl -X GET http://localhost:8081/api/metadata ``` -------------------------------- ### GET /api/metadata Source: https://context7.com/deepgram-starters/php-transcription/llms.txt Returns metadata about the starter application from the deepgram.toml configuration file. ```APIDOC ## GET /api/metadata ### Description Returns metadata about the starter application from the deepgram.toml configuration file. Used for standardization compliance. ### Method GET ### Endpoint /api/metadata ``` -------------------------------- ### PHP Transcription Functions Source: https://context7.com/deepgram-starters/php-transcription/llms.txt Examples of using the provided PHP functions for transcription. ```APIDOC ## PHP Integration - Using the Transcription Functions ### Description The server provides modular PHP functions that can be reused in your own projects for validating input and calling the Deepgram API. ### Usage Examples #### Option 1: Transcribe from a URL ```php 'url', 'url' => 'https://example.com/audio.mp3']; $model = 'nova-3'; $result = callDeepgramTranscription($dgRequest, $model, $apiKey); if ($result['success']) { $response = formatTranscriptionResponse($result['data'], $model); echo "Transcript: " . $response['transcript'] . "\n"; echo "Duration: " . $response['duration'] . " seconds\n"; } else { echo "Error: " . $result['error'] . "\n"; } ?> ``` #### Option 2: Transcribe from uploaded file ```php 'file', 'tmp_name' => '/tmp/uploaded_audio.wav', 'mimetype' => 'audio/wav' ]; $result = callDeepgramTranscription($dgRequest, 'nova-3', $apiKey); // Handle result as in Option 1 ?> ``` #### Option 3: Validate input from form submission ```php ``` ### Functions - **callDeepgramTranscription(array $request, string $model, string $apiKey): array** Transcribes audio using the Deepgram API. Returns an array with 'success' and 'data' or 'error'. - **formatTranscriptionResponse(array $data, string $model): array** Formats the Deepgram transcription response. - **validateTranscriptionInput(?array $file, ?string $url): ?array** Validates input for transcription, ensuring either a file or URL is provided. Returns a request array or null if input is invalid. ``` -------------------------------- ### GET /api/metadata Source: https://context7.com/deepgram-starters/php-transcription/llms.txt Retrieves metadata about the PHP Transcription application. ```APIDOC ## GET /api/metadata ### Description Retrieves metadata about the PHP Transcription application, including its title, description, author, repository, use case, language, framework, SDK, and tags. ### 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. - **repository** (string) - URL to the project repository. - **useCase** (string) - The primary use case of the application. - **language** (string) - The programming language used. - **framework** (string) - The framework used. - **sdk** (string) - The SDK used (N/A if not applicable). - **tags** (array) - An array of relevant tags. ### Response Example { "title": "PHP Transcription", "description": "Get started using Deepgram's speech-to-text with this PHP demo app", "author": "Deepgram DX Team (https://developers.deepgram.com)", "repository": "https://github.com/deepgram-starters/php-transcription", "useCase": "transcription", "language": "php", "framework": "php", "sdk": "N/A", "tags": ["transcription", "stt", "speech-to-text", "asr", "pre-recorded", "php"] } ``` -------------------------------- ### GET /health Source: https://context7.com/deepgram-starters/php-transcription/llms.txt Performs a health check on the server. ```APIDOC ## GET /health ### Description Returns a simple health check response to verify the server is running. ### Method GET ### Endpoint /health ### Response #### Success Response (200) - **status** (string) - Indicates the health status of the server (e.g., "ok"). ### Response Example { "status": "ok" } ``` -------------------------------- ### Add Deepgram Transcription Features Source: https://github.com/deepgram-starters/php-transcription/blob/main/AGENTS.md Demonstrates how to add various features to the Deepgram transcription API call by modifying the options object. Examples include language, diarization, punctuation, smart formatting, paragraph detection, utterance splitting, keyword boosting, redaction, summarization, topic detection, and sentiment analysis. ```json { "language": "es", "diarize": true, "punctuate": true, "smart_format": true, "paragraphs": true, "utterances": true, "keywords": ["deepgram"], "redact": ["pci", "ssn"], "summarize": "v2", "topics": true, "detect_topics": true } ``` -------------------------------- ### GET /api/session Source: https://context7.com/deepgram-starters/php-transcription/llms.txt Issues a signed JWT token for session authentication, which must be included as a Bearer token in subsequent API requests. ```APIDOC ## GET /api/session ### Description Issues a signed JWT token for session authentication. This token must be included as a Bearer token in subsequent API requests. ### Method GET ### Endpoint /api/session ### Response #### Success Response (200) - **token** (string) - The JWT authentication token. #### Response Example { "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9..." } ``` -------------------------------- ### Deploy Application with Docker and Fly.io Source: https://context7.com/deepgram-starters/php-transcription/llms.txt Commands for building and running the application container or deploying to the Fly.io platform. ```dockerfile # deploy/Dockerfile structure # Uses PHP with Caddy as reverse proxy # Build and run with Docker docker build -f deploy/Dockerfile -t php-transcription . docker run -p 8080:8080 -e DEEPGRAM_API_KEY=your_key php-transcription # Or deploy to Fly.io using provided fly.toml fly launch fly secrets set DEEPGRAM_API_KEY=your_deepgram_api_key fly deploy ``` -------------------------------- ### Run Conformance Tests Source: https://github.com/deepgram-starters/php-transcription/blob/main/AGENTS.md Execute conformance tests for the application. This command requires the application to be running. ```bash make test ``` -------------------------------- ### Clean Rebuild Project Source: https://github.com/deepgram-starters/php-transcription/blob/main/AGENTS.md Removes vendor and node_modules directories, clears Vite cache, and then re-initializes the project dependencies. ```bash rm -rf vendor frontend/node_modules frontend/.vite make init ``` -------------------------------- ### Configure Environment Variables Source: https://context7.com/deepgram-starters/php-transcription/llms.txt Define required and optional settings in the .env file, including the Deepgram API key and server port. ```bash # .env file configuration # Required - Get your API key at https://console.deepgram.com DEEPGRAM_API_KEY=your_deepgram_api_key_here # Optional - Backend API server port (default: 8081) PORT=8081 # Optional - Server host (default: 0.0.0.0) HOST=0.0.0.0 # Optional - Session secret for JWT signing (recommended for production) # If not set, a random secret is generated on each server start SESSION_SECRET=your_secure_random_string_here ``` -------------------------------- ### Transcribe Audio via URL Source: https://context7.com/deepgram-starters/php-transcription/llms.txt Submit a remote audio URL for transcription using a POST request. ```bash # Transcribe audio from a URL curl -X POST http://localhost:8081/api/transcription \ -H "Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9..." \ -F "url=https://example.com/audio/sample.mp3" \ -F "model=nova-2" # Response (200 OK) { "transcript": "Welcome to the demonstration of Deepgram's transcription service.", "words": [ { "word": "welcome", "start": 0.0, "end": 0.4, "confidence": 0.97 } ], "metadata": { "model_uuid": "model-uuid-here", "request_id": "request-id-here", "model_name": "nova-2" }, "duration": 5.2 } # Available models: "nova-3", "nova-2", "nova", "enhanced", "base" # Default model is "nova-3" if not specified ``` -------------------------------- ### Integrate Transcription Functions Source: https://context7.com/deepgram-starters/php-transcription/llms.txt Use modular PHP functions to transcribe audio from URLs or files and validate user input. ```php 'url', 'url' => 'https://example.com/audio.mp3']; $model = 'nova-3'; $result = callDeepgramTranscription($dgRequest, $model, $apiKey); if ($result['success']) { $response = formatTranscriptionResponse($result['data'], $model); echo "Transcript: " . $response['transcript'] . "\n"; echo "Duration: " . $response['duration'] . " seconds\n"; } else { echo "Error: " . $result['error'] . "\n"; } // Option 2: Transcribe from uploaded file $dgRequest = [ 'type' => 'file', 'tmp_name' => '/tmp/uploaded_audio.wav', 'mimetype' => 'audio/wav' ]; $result = callDeepgramTranscription($dgRequest, 'nova-3', $apiKey); // Option 3: Validate input from form submission $file = $_FILES['file'] ?? null; $url = $_POST['url'] ?? null; $dgRequest = validateTranscriptionInput($file, $url); if ($dgRequest === null) { $error = formatErrorResponse('Either file or url must be provided', 400, 'MISSING_INPUT'); http_response_code($error['statusCode']); echo json_encode($error['body']); exit; } ``` -------------------------------- ### Transcribe Audio via File Upload Source: https://context7.com/deepgram-starters/php-transcription/llms.txt Submit an audio file for transcription using a POST request with a valid Bearer token. ```bash # Transcribe an audio file with Bearer token authentication curl -X POST http://localhost:8081/api/transcription \ -H "Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9..." \ -F "file=@/path/to/audio.wav" \ -F "model=nova-3" # Response (200 OK) { "transcript": "Hello, this is a test of the transcription service.", "words": [ { "word": "hello", "start": 0.0, "end": 0.5, "confidence": 0.99 }, { "word": "this", "start": 0.6, "end": 0.8, "confidence": 0.98 } ], "metadata": { "model_uuid": "abc123-def456", "request_id": "req-789xyz", "model_name": "nova-3" }, "duration": 3.5 } # Error response (401 Unauthorized - missing or invalid token) { "error": { "type": "AuthenticationError", "code": "MISSING_TOKEN", "message": "Authorization header with Bearer token is required" } } # Error response (400 Bad Request - no file or URL provided) { "error": { "type": "ValidationError", "code": "MISSING_INPUT", "message": "Either file or url must be provided", "details": { "originalError": "Either file or url must be provided" } } } ``` -------------------------------- ### Check Server Health Source: https://context7.com/deepgram-starters/php-transcription/llms.txt Verify the server status using the health check endpoint. ```bash curl -X GET http://localhost:8081/health ``` -------------------------------- ### Stop All Running Servers Source: https://github.com/deepgram-starters/php-transcription/blob/main/AGENTS.md This command finds processes listening on ports 8080 and 8081 and terminates them forcefully. It redirects errors to `/dev/null` to suppress messages for non-existent processes. ```bash lsof -ti:8080,8081 | xargs kill -9 2>/dev/null ``` -------------------------------- ### JWT Session Authentication Source: https://context7.com/deepgram-starters/php-transcription/llms.txt Details on how to generate and validate JWT tokens for session authentication. ```APIDOC ## JWT Session Authentication ### Description The server uses JWT tokens for session authentication with configurable expiry and secret key. ### Configuration - **JWT_EXPIRY**: Constant defining the token expiry time in seconds (e.g., 3600 for 1 hour). - **SESSION_SECRET**: Environment variable or generated random string used as the secret key for JWT signing. It's recommended to set this in production. ### Creating a Session Token (GET /api/session implementation) #### Method POST (implied, typically used for session creation) #### Endpoint /api/session (example endpoint) #### Request Body (Example) (No explicit request body defined, typically relies on server-side logic or authentication context) #### Response (Example) ```json { "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9..." } ``` #### Code Example (PHP) ```php $now, 'exp' => $now + JWT_EXPIRY, ]; $token = JWT::encode($payload, $sessionSecret, 'HS256'); // The generated token is then typically returned in a JSON response. ?> ``` ### Validating a Session Token (requireSession function) #### Method (Typically used in middleware or before accessing protected resources) #### Endpoint (Applies to any endpoint requiring authentication) #### Request Headers - **Authorization** (string) - `Bearer ` #### Response #### Success Response (200) (Indicates successful validation, request proceeds) #### Error Response (401) - **MISSING_TOKEN**: If the Authorization header is missing or malformed. - **INVALID_TOKEN**: If the token is expired or invalid. #### Code Example (PHP) ```php 'MISSING_TOKEN']); exit; } $token = substr($authHeader, 7); try { $decoded = JWT::decode($token, new Key($sessionSecret, 'HS256')); // Token valid, proceed with request } catch (ExpiredException $e) { // Return 401 error: INVALID_TOKEN - Session expired // Example: http_response_code(401); echo json_encode(['error' => 'INVALID_TOKEN', 'message' => 'Session expired']); exit; } catch (\Exception $e) { // Return 401 error: INVALID_TOKEN - Invalid session token // Example: http_response_code(401); echo json_encode(['error' => 'INVALID_TOKEN', 'message' => 'Invalid session token']); exit; } ?> ``` ``` -------------------------------- ### Implement JWT Session Authentication Source: https://context7.com/deepgram-starters/php-transcription/llms.txt Configure, create, and validate JWT tokens for session management using the Firebase JWT library. ```php $now, // Issued at 'exp' => $now + JWT_EXPIRY, // Expiration ]; $token = JWT::encode($payload, $sessionSecret, 'HS256'); // Return: {"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9..."} // Validating a session token (requireSession function) use Firebase\\JWT\\Key; $authHeader = $_SERVER['HTTP_AUTHORIZATION'] ?? ''; if (empty($authHeader) || !str_starts_with($authHeader, 'Bearer ')) { // Return 401 error: MISSING_TOKEN } $token = substr($authHeader, 7); try { $decoded = JWT::decode($token, new Key($sessionSecret, 'HS256')); // Token valid, proceed with request } catch (\\Firebase\\JWT\\ExpiredException $e) { // Return 401 error: INVALID_TOKEN - Session expired } catch (\\Exception $e) { // Return 401 error: INVALID_TOKEN - Invalid session token } ``` -------------------------------- ### Obtain JWT Authentication Token Source: https://context7.com/deepgram-starters/php-transcription/llms.txt Request a session token via the /api/session endpoint to use in the Authorization header for protected requests. ```bash # Request a session token curl -X GET http://localhost:8081/api/session # Response (200 OK) { "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE3MDk4MjQ0MDAsImV4cCI6MTcwOTgyODAwMH0.abc123..." } # Token expires in 1 hour (3600 seconds) # Use this token in Authorization header for protected endpoints: # Authorization: Bearer ``` -------------------------------- ### Integrate Deepgram Transcription Client in JavaScript Source: https://context7.com/deepgram-starters/php-transcription/llms.txt A client-side class for handling authentication and transcription requests via file upload or URL. ```javascript // JavaScript client example for browser or Node.js class DeepgramTranscriptionClient { constructor(baseUrl = 'http://localhost:8081') { this.baseUrl = baseUrl; this.token = null; } // Step 1: 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; } // Step 2: Transcribe audio file async transcribeFile(file, model = 'nova-3') { if (!this.token) await this.authenticate(); const formData = new FormData(); formData.append('file', file); formData.append('model', model); const response = await fetch(`${this.baseUrl}/api/transcription`, { method: 'POST', headers: { 'Authorization': `Bearer ${this.token}` }, body: formData }); if (!response.ok) { const error = await response.json(); throw new Error(error.error?.message || 'Transcription failed'); } return response.json(); } // Step 3: Transcribe from URL async transcribeUrl(audioUrl, model = 'nova-3') { if (!this.token) await this.authenticate(); const formData = new FormData(); formData.append('url', audioUrl); formData.append('model', model); const response = await fetch(`${this.baseUrl}/api/transcription`, { method: 'POST', headers: { 'Authorization': `Bearer ${this.token}` }, body: formData }); return response.json(); } } // Usage const client = new DeepgramTranscriptionClient(); const result = await client.transcribeUrl('https://example.com/audio.mp3'); console.log('Transcript:', result.transcript); console.log('Words:', result.words.length); console.log('Duration:', result.duration, 'seconds'); ``` -------------------------------- ### POST /api/transcription Source: https://context7.com/deepgram-starters/php-transcription/llms.txt Transcribes audio from either an uploaded file or a remote URL using Deepgram's speech-to-text API. ```APIDOC ## POST /api/transcription ### Description Transcribes audio from an uploaded file or a remote URL using Deepgram's speech-to-text API. Requires JWT authentication. ### Method POST ### Endpoint /api/transcription ### Parameters #### Request Body - **file** (binary) - Optional - The audio file to upload. - **url** (string) - Optional - The URL of the audio file to transcribe. - **model** (string) - Optional - The Deepgram model to use (e.g., "nova-3", "nova-2"). ### Request Example { "file": "@/path/to/audio.wav", "model": "nova-3" } ### Response #### Success Response (200) - **transcript** (string) - The transcribed text. - **words** (array) - Detailed word-level transcription data. - **metadata** (object) - Request and model metadata. - **duration** (float) - Duration of the audio in seconds. #### Response Example { "transcript": "Hello, this is a test.", "words": [], "metadata": {}, "duration": 3.5 } ``` -------------------------------- ### Manual Endpoint Checks Source: https://github.com/deepgram-starters/php-transcription/blob/main/AGENTS.md Perform manual checks on the API endpoints using curl. The output is formatted using Python's 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 ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.