PHP code example of droath / edenai

1. Go to this page and download the library: Download droath/edenai library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

droath / edenai example snippets




declare(strict_types=1);

use Droath\Edenai\Http\ApiClient;
use Droath\Edenai\Resources\AudioResource;

// Client auto-discovers HTTP client and loads config from environment
$client = new ApiClient();

// Use a resource to make API calls
$audioResource = new AudioResource($client);



declare(strict_types=1);

use GuzzleHttp\Client as GuzzleClient;
use Droath\Edenai\Http\ApiClient;

$httpClient = new GuzzleClient();

$client = new ApiClient(
    httpClient: $httpClient,
    baseUrl: 'https://api.edenai.run',
    apiKey: 'your-api-key-here',
);



declare(strict_types=1);

use Droath\Edenai\Http\ApiClient;
use Droath\Edenai\Resources\AudioResource;
use Droath\Edenai\DTOs\Audio\SpeechToTextAsyncRequest;
use Droath\Edenai\Enums\ServiceProviderEnum;

$client = new ApiClient();
$audioResource = new AudioResource($client);

// Create request with file upload
$request = new SpeechToTextAsyncRequest(
    file: '/path/to/audio.mp3',
    providers: [ServiceProviderEnum::GOOGLE, ServiceProviderEnum::DEEPGRAM],
    language: 'en',
);

// Upload file and get job ID for tracking
$response = $audioResource->speechToTextAsync($request);

echo "Job ID: {$response->jobId}";
echo "Providers: " . implode(', ', $response->providers);
echo "Created: {$response->submittedAt->format('Y-m-d H:i:s')}";



declare(strict_types=1);

use Droath\Edenai\Http\ApiClient;
use Droath\Edenai\Resources\AudioResource;
use Droath\Edenai\DTOs\Audio\TextToSpeechRequest;
use Droath\Edenai\Enums\ServiceProviderEnum;

$client = new ApiClient();
$audioResource = new AudioResource($client);

// Create request with optional parameters
$request = new TextToSpeechRequest(
    text: 'Hello world',
    providers: [ServiceProviderEnum::AMAZON],
    language: 'en',
    option: 'FEMALE',
    audioFormat: 'mp3',
    rate: 1,
    pitch: 0,
    volume: 1,
);

// Get generated audio immediately
$response = $audioResource->textToSpeech($request);

// Save audio to file (already decoded from Base64)
// Response contains results from all providers
foreach ($response->results as $result) {
    file_put_contents("output_{$result->provider}.mp3", $result->audioData);
    echo "Provider: {$result->provider}, Voice type: {$result->voiceType}\n";
}



declare(strict_types=1);

use Droath\Edenai\Http\ApiClient;
use Droath\Edenai\Resources\AudioResource;
use Droath\Edenai\DTOs\Audio\TextToSpeechAsyncRequest;
use Droath\Edenai\Enums\ServiceProviderEnum;

$client = new ApiClient();
$audioResource = new AudioResource($client);

// Create async request
$request = new TextToSpeechAsyncRequest(
    text: 'This is a longer text that will be processed asynchronously',
    providers: [ServiceProviderEnum::MICROSOFT, ServiceProviderEnum::AZURE],
    language: 'en-US',
    option: 'MALE',
    audioFormat: 'wav',
);

// Get job ID for polling
$response = $audioResource->textToSpeechAsync($request);

echo "Job ID: {$response->jobId}";
echo "Created: {$response->submittedAt->format('Y-m-d H:i:s')}";



declare(strict_types=1);

use Droath\Edenai\Enums\ServiceProviderEnum;

// Available providers:
ServiceProviderEnum::GOOGLE      // Google Cloud
ServiceProviderEnum::AMAZON      // Amazon AWS
ServiceProviderEnum::MICROSOFT   // Microsoft Azure
ServiceProviderEnum::OPENAI      // OpenAI
ServiceProviderEnum::DEEPGRAM    // Deepgram
ServiceProviderEnum::ASSEMBLY_AI // AssemblyAI
ServiceProviderEnum::REV_AI      // Rev.ai
ServiceProviderEnum::SPEECHMATICS // Speechmatics
ServiceProviderEnum::IBMWATSON   // IBM Watson
ServiceProviderEnum::AZURE       // Azure Cognitive Services



declare(strict_types=1);

use Droath\Edenai\Http\ApiClient;
use Droath\Edenai\Resources\AudioResource;
use Droath\Edenai\DTOs\Audio\SpeechToTextAsyncRequest;
use Droath\Edenai\Enums\ServiceProviderEnum;
use Droath\Edenai\Exceptions\FileUploadException;
use Droath\Edenai\Exceptions\ValidationException;
use InvalidArgumentException;

$client = new ApiClient();
$audioResource = new AudioResource($client);

try {
    $request = new SpeechToTextAsyncRequest(
        file: '/path/to/audio.mp3',
        providers: [ServiceProviderEnum::GOOGLE],
        language: 'en',
    );
    $response = $audioResource->speechToTextAsync($request);
} catch (InvalidArgumentException $e) {
    // Request DTO validation failed (e.g., empty text)
    echo 'Invalid request: ' . $e->getMessage();
} catch (FileUploadException $e) {
    // File not found or not readable
    echo 'File upload error: ' . $e->getMessage();
} catch (ValidationException $e) {
    // Unsupported audio format or API validation error
    echo 'Validation error: ' . $e->getMessage();
    print_r($e->getErrors());
}



declare(strict_types=1);

use Droath\Edenai\Http\ApiClient;
use Droath\Edenai\Middleware\MiddlewareInterface;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;

final class LoggingMiddleware implements MiddlewareInterface
{
    public function handle(RequestInterface $request, callable $next): ResponseInterface
    {
        // Log before request
        error_log('Request: ' . $request->getMethod() . ' ' . $request->getUri());

        // Execute next middleware
        $response = $next($request);

        // Log after response
        error_log('Response: ' . $response->getStatusCode());

        return $response;
    }
}

// Custom middleware is prepended before default middleware
$client = new ApiClient(
    middleware: [new LoggingMiddleware()],
);



declare(strict_types=1);

use Droath\Edenai\Http\ApiClient;
use Droath\Edenai\Resources\AudioResource;
use Droath\Edenai\DTOs\Audio\TextToSpeechRequest;
use Droath\Edenai\Enums\ServiceProviderEnum;
use Droath\Edenai\Exceptions\AuthenticationException;
use Droath\Edenai\Exceptions\ValidationException;
use Droath\Edenai\Exceptions\RateLimitException;
use Droath\Edenai\Exceptions\ServerException;
use Droath\Edenai\Exceptions\NetworkException;

$client = new ApiClient();
$audioResource = new AudioResource($client);

try {
    $request = new TextToSpeechRequest(
        text: 'Hello world',
        providers: [ServiceProviderEnum::GOOGLE],
    );
    $response = $audioResource->textToSpeech($request);
} catch (AuthenticationException $e) {
    // 401 - Invalid or missing API credentials
    echo 'Authentication failed: ' . $e->getMessage();
    echo 'Status: ' . $e->getStatusCode();
} catch (ValidationException $e) {
    // 422 - Request validation failed
    echo 'Validation errors: ';
    print_r($e->getErrors());
} catch (RateLimitException $e) {
    // 429 - Rate limit exceeded
    echo 'Rate limited. Retry after: ' . $e->getRetryAfter();
} catch (ServerException $e) {
    // 500+ - Server error
    echo 'Server error: ' . $e->getMessage();
} catch (NetworkException $e) {
    // Network/connection error
    echo 'Network error: ' . $e->getMessage();
}



declare(strict_types=1);

use Droath\Edenai\DTOs\Audio\TextToSpeechRequest;
use Droath\Edenai\Enums\ServiceProviderEnum;
use InvalidArgumentException;

// Valid request
$request = new TextToSpeechRequest(
    text: 'Hello world',
    providers: [ServiceProviderEnum::GOOGLE, ServiceProviderEnum::AMAZON],
    language: 'en',
);

// Serialize to array for HTTP request
$payload = $request->toArray();

// Invalid requests throw exceptions at construction time
try {
    $invalid = new TextToSpeechRequest(
        text: '', // Empty text
        providers: [ServiceProviderEnum::GOOGLE],
    );
} catch (InvalidArgumentException $e) {
    echo 'Validation error: ' . $e->getMessage();
    // Output: "Text cannot be empty"
}



declare(strict_types=1);

use Droath\Edenai\DTOs\Audio\SpeechToTextAsyncResponse;

// Parse API response
$data = [
    'job_id' => 'job-abc123',
    'providers' => ['google', 'deepgram'],
    'submitted_at' => '2024-11-09 15:30:00',
    'unknown_field' => 'ignored', // Unknown fields are ignored
];

$response = SpeechToTextAsyncResponse::fromResponse($data);

// Access typed properties
echo $response->jobId; // string: "job-abc123"
print_r($response->providers); // array: ['google', 'deepgram']
echo $response->submittedAt->format('Y-m-d'); // DateTimeImmutable: "2024-11-09"

// Properties are readonly and immutable
$response->jobId = 'xyz'; // Error: Cannot modify readonly property



declare(strict_types=1);

use Droath\Edenai\DTOs\ResponseMetadata;
use Psr\Http\Message\ResponseInterface;

/** @var ResponseInterface $psrResponse */
$metadata = ResponseMetadata::fromResponse($psrResponse);

// Access rate limit information
echo 'Requests remaining: ' . $metadata->getRateLimitRemaining();
echo 'Rate limit resets at: ' . date('Y-m-d H:i:s', $metadata->getRateLimitReset());

// Access request ID for debugging
echo 'Request ID: ' . $metadata->getRequestId();

// Access all headers
$headers = $metadata->getHeaders();