File size: 6,744 Bytes
d4d07bc 74acf19 d4d07bc 74acf19 d4d07bc 74acf19 d4d07bc 74acf19 d4d07bc | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 | <?php
namespace App\Services;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use RuntimeException;
/**
* Text-to-image generation via Replicate free-tier models.
*
* Supported models (Try-for-Free):
* - google/imagen-4 (high quality, ~10-25s)
* - black-forest-labs/flux-1.1-pro (fast & sharp, ~5-15s)
* - ideogram-ai/ideogram-v3-quality (highest-quality Ideogram v3 output)
*
* All use sync polling β predictions settle in <30s so we block within the
* HTTP request rather than adding an async flow.
*/
class ReplicateImageService
{
private string $apiKey;
private string $baseUrl;
// Replicate model slug β aspect_ratio key name (some models differ)
private const MODELS = [
'replicate-imagen4' => 'google/imagen-4',
'replicate-flux' => 'black-forest-labs/flux-1.1-pro',
'replicate-ideogram' => 'ideogram-ai/ideogram-v3-quality',
'replicate-flux-flex' => 'black-forest-labs/flux-2-flex',
];
public function __construct()
{
$this->apiKey = (string) config('services.replicate.api_key', '');
$this->baseUrl = (string) config('services.replicate.base_url', 'https://api.replicate.com/v1');
}
public function isAvailable(): bool
{
return $this->apiKey !== '';
}
public static function providerToModel(string $provider): string
{
return self::MODELS[$provider] ?? 'google/imagen-4';
}
/**
* Generate image(s) β submits N predictions serially then polls all.
*
* @param string $prompt
* @param string $aspect 'landscape'|'square'|'portrait'
* @param int $count 1β4
* @param string $provider e.g. 'replicate-imagen4'
* @return array<string> Image URLs
*/
public function generate(
string $prompt,
string $aspect = 'landscape',
int $count = 1,
string $provider = 'replicate-imagen4',
array $referenceImages = []
): array
{
if (! $this->isAvailable()) {
throw new RuntimeException('REPLICATE_API_KEY belum diset.');
}
$model = self::providerToModel($provider);
$count = max(1, min(4, $count));
$aspectRatio = match ($aspect) {
'portrait' => '9:16',
'square' => '1:1',
default => '16:9',
};
$input = ['prompt' => $prompt, 'aspect_ratio' => $aspectRatio];
if ($provider === 'replicate-flux-flex') {
$input = [
'prompt' => $prompt,
'aspect_ratio' => $referenceImages !== [] ? 'match_input_image' : $aspectRatio,
'resolution' => $referenceImages !== [] ? 'match_input_image' : '1 MP',
'output_format' => 'png',
'input_images' => array_values(array_filter(array_map(
static fn ($url) => filled($url) ? trim((string) $url) : null,
$referenceImages
))),
];
}
// Ideogram uses aspect_ratio directly and can take extra style inputs later.
// Flux supports safety_tolerance; keep defaults
$predictionIds = [];
$endpoint = rtrim($this->baseUrl, '/') . '/models/' . $model . '/predictions';
for ($i = 0; $i < $count; $i++) {
// Delay between submissions to respect burst=1 on low-credit accounts
if ($i > 0) {
sleep(2);
}
$response = $this->post($endpoint, ['input' => $input]);
$id = $response->json('id');
if (blank($id)) {
throw new RuntimeException('Replicate: prediction ID tidak ada di response.');
}
$predictionIds[] = $id;
}
return $this->pollUntilDone($predictionIds, model: $model);
}
// βββ Internal ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
private function post(string $endpoint, array $payload)
{
$response = Http::withToken($this->apiKey)->timeout(30)->post($endpoint, $payload);
if ($response->status() === 429) {
Log::info('ReplicateImageService: rate-limited, retrying in 3sβ¦');
sleep(3);
$response = Http::withToken($this->apiKey)->timeout(30)->post($endpoint, $payload);
}
if ($response->failed()) {
$status = $response->status();
$detail = $response->json('detail') ?? $response->body();
if ($status === 429) {
throw new RuntimeException('Replicate sedang sibuk (rate limit). Tunggu beberapa detik lalu coba lagi.');
}
throw new RuntimeException('Replicate image gagal: ' . Str::limit((string) $detail, 200));
}
return $response;
}
private function pollUntilDone(array $ids, string $model = ''): array
{
$maxWait = 90; // seconds
$interval = 3;
$elapsed = 0;
$urls = [];
$pending = array_flip($ids); // id => index
while (! empty($pending) && $elapsed < $maxWait) {
sleep($interval);
$elapsed += $interval;
foreach (array_keys($pending) as $id) {
$r = Http::withToken($this->apiKey)
->timeout(15)
->get(rtrim($this->baseUrl, '/') . '/predictions/' . $id);
if ($r->failed()) {
continue;
}
$status = $r->json('status');
if ($status === 'succeeded') {
$output = $r->json('output');
if (is_array($output)) {
foreach ($output as $url) {
if (filled($url)) {
$urls[] = (string) $url;
}
}
} elseif (filled($output)) {
$urls[] = (string) $output;
}
unset($pending[$id]);
} elseif (in_array($status, ['failed', 'canceled'], true)) {
$err = $r->json('error') ?? 'Unknown error';
Log::warning('ReplicateImageService: prediction failed', ['id' => $id, 'model' => $model, 'error' => $err]);
unset($pending[$id]);
}
}
}
if (empty($urls)) {
throw new RuntimeException('Replicate: Gagal menghasilkan gambar. Coba lagi dalam beberapa detik.');
}
return $urls;
}
}
|