50 lines
1.7 KiB
PHP
50 lines
1.7 KiB
PHP
<?php
|
|||
|
|
|
||
|
|
namespace App\Support\AiProviders;
|
||
|
|
|
||
|
|
use App\Models\AiProvider;
|
||
|
|
use Illuminate\Http\Client\ConnectionException;
|
||
|
|
use Illuminate\Support\Facades\Http;
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Image generation via StabilityAI's Stable Image Core API. Used for
|
||
|
|
* storyboard frames, thumbnails, and scene visuals.
|
||
|
|
*/
|
||
|
|
class StabilityAiDriver implements AiProviderDriver
|
||
|
|
{
|
||
|
|
public function generate(AiProvider $provider, string $prompt, array $options = []): AiGenerationResult
|
||
|
|
{
|
||
|
|
$outputFormat = $options['output_format'] ?? $provider->config['output_format'] ?? 'png';
|
||
|
|
|
||
|
|
try {
|
||
|
|
$response = Http::withToken($provider->api_key)
|
||
|
|
->accept('application/json')
|
||
|
|
->asMultipart()
|
||
|
|
->attach('prompt', $prompt)
|
||
|
|
->attach('output_format', $outputFormat)
|
||
|
|
->post('https://api.stability.ai/v2beta/stable-image/generate/core');
|
||
|
|
} catch (ConnectionException $e) {
|
||
|
|
throw new AiGenerationException("could not connect to StabilityAI: {$e->getMessage()}");
|
||
|
|
}
|
||
|
|
|
||
|
|
if ($response->failed()) {
|
||
|
|
$error = $response->json('errors.0') ?? $response->json('message') ?? 'unexpected response from StabilityAI';
|
||
|
|
|
||
|
|
throw new AiGenerationException($error);
|
||
|
|
}
|
||
|
|
|
||
|
|
$base64 = $response->json('image');
|
||
|
|
|
||
|
|
if (! $base64) {
|
||
|
|
throw new AiGenerationException('unexpected response from StabilityAI: missing image data');
|
||
|
|
}
|
||
|
|
|
||
|
|
$bytes = base64_decode($base64);
|
||
|
|
|
||
|
|
return new AiGenerationResult($bytes, "image/{$outputFormat}", [
|
||
|
|
'seed' => $response->json('seed'),
|
||
|
|
'finish_reason' => $response->json('finish_reason'),
|
||
|
|
]);
|
||
|
|
}
|
||
|
|
}
|