File size: 17,183 Bytes
d4d07bc 74acf19 d4d07bc 74acf19 d4d07bc 74acf19 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 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 | <?php
namespace App\Services;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use RuntimeException;
/**
* Image-to-Video via Replicate API β ASYNC design.
*
* Step A (fast, <2s): submit() β POST /predictions β returns prediction_id
* Step B (poll): checkStatus() β GET /predictions/{id} β called by AJAX endpoint
*/
class ReplicateVideoService
{
private const WAVESPEED_WAN_MODEL = 'wavespeedai/wan-2.1-i2v-480p';
private string $apiKey;
private string $baseUrl;
private string $i2vModel;
public function __construct(private ?HuggingFaceMediaStorageService $hfMediaStorage = null)
{
$this->apiKey = (string) config('services.replicate.api_key', '');
$this->baseUrl = (string) config('services.replicate.base_url', 'https://api.replicate.com/v1');
$this->i2vModel = (string) config('services.replicate.i2v_model', self::WAVESPEED_WAN_MODEL);
}
public function isAvailable(): bool
{
return $this->apiKey !== '';
}
/**
* STEP A β submit prediction job, returns prediction_id immediately (<2s).
*
* @throws RuntimeException
*/
public function submit(string $imageUrl, string $prompt, array $options = []): array
{
if (! $this->isAvailable()) {
throw new RuntimeException('REPLICATE_API_KEY belum diset.');
}
// Replicate requires a fully-qualified https:// URI β convert relative paths.
if (! str_starts_with($imageUrl, 'http://') && ! str_starts_with($imageUrl, 'https://')) {
$imageUrl = rtrim((string) config('app.url', ''), '/') . '/' . ltrim($imageUrl, '/');
}
$endpoint = rtrim($this->baseUrl, '/') . '/models/' . $this->i2vModel . '/predictions';
$payload = $this->buildImageToVideoPayload($imageUrl, $prompt, $options);
$requestBody = [
'input' => $payload['input'] ?? [],
];
$response = Http::withToken($this->apiKey)->timeout(30)->post($endpoint, $requestBody);
// Retry once after 3s on rate-limit (burst=1 on low-credit accounts)
if ($response->status() === 429) {
Log::info('ReplicateVideoService: rate-limited, retrying in 3sβ¦');
sleep(3);
$response = Http::withToken($this->apiKey)->timeout(30)->post($endpoint, $requestBody);
}
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 submit gagal: ' . Str::limit((string) $detail, 200));
}
$id = $response->json('id');
if (blank($id)) {
throw new RuntimeException('Replicate: prediction ID tidak ada di response.');
}
Log::info('ReplicateVideoService: submitted', ['id' => $id]);
return [
'prediction_id' => (string) $id,
'applied_settings' => $payload['applied_settings'],
];
}
private function buildImageToVideoPayload(string $imageUrl, string $prompt, array $options): array
{
$model = $this->resolveRequestedModel($options);
$aspectRatio = $this->normalizeAspectRatio((string) ($options['aspect_ratio'] ?? '16:9'));
$audioEnabled = ((string) ($options['video_audio'] ?? 'off')) === 'on';
$negativePrompt = trim((string) ($options['video_negative_prompt'] ?? ''));
if ($model === self::WAVESPEED_WAN_MODEL) {
[$numFrames, $fps, $durationLabel] = $this->resolveWanFrameSettings((string) ($options['video_duration'] ?? '4s'));
$input = [
'prompt' => $prompt,
'image' => $imageUrl,
'aspect_ratio' => $aspectRatio,
'frames_per_second' => $fps,
'num_frames' => $numFrames,
];
if ($negativePrompt !== '') {
$input['negative_prompt'] = $negativePrompt;
}
return [
'input' => $input,
'applied_settings' => [
'aspect_ratio' => $aspectRatio,
'video_duration' => $durationLabel,
'video_quality' => '480p',
'video_audio' => 'off',
'veo_variant' => 'wan-2.1-i2v-480p',
'replicate_i2v_model' => $model,
],
];
}
if ($model === 'google/veo-3-fast' || $model === 'google/veo-3') {
$duration = $this->normalizeVeoDuration((string) ($options['video_duration'] ?? '4s'));
$resolution = ((string) ($options['video_quality'] ?? '1080p')) === '720p' ? '720p' : '1080p';
$input = [
'prompt' => $prompt,
'image' => $imageUrl,
'duration' => $duration,
'resolution' => $resolution,
'aspect_ratio' => $aspectRatio,
'generate_audio' => $audioEnabled,
];
if ($negativePrompt !== '') {
$input['negative_prompt'] = $negativePrompt;
}
return [
'input' => $input,
'applied_settings' => [
'aspect_ratio' => $aspectRatio,
'video_duration' => $duration.'s',
'video_quality' => $resolution,
'video_audio' => $audioEnabled ? 'on' : 'off',
'veo_variant' => $model === 'google/veo-3' ? 'veo-3' : 'veo-3-fast',
'replicate_i2v_model' => $model,
],
];
}
if ($model === 'google/veo-2') {
$duration = ((string) ($options['video_duration'] ?? '8s')) === '5s' ? 5 : 8;
return [
'input' => [
'prompt' => $prompt,
'image' => $imageUrl,
'duration' => $duration,
'aspect_ratio' => $aspectRatio,
],
'applied_settings' => [
'aspect_ratio' => $aspectRatio,
'video_duration' => $duration.'s',
'video_quality' => '720p',
'video_audio' => 'off',
'veo_variant' => 'veo-2',
'replicate_i2v_model' => $model,
],
];
}
if ($model === 'luma/ray-2-720p') {
$duration = ((string) ($options['video_duration'] ?? '8s')) === '5s' ? 5 : 9;
return [
'input' => [
'prompt' => $prompt,
'start_image' => $imageUrl,
'duration' => $duration,
'aspect_ratio' => $aspectRatio,
],
'applied_settings' => [
'aspect_ratio' => $aspectRatio,
'video_duration' => $duration.'s',
'video_quality' => '720p',
'video_audio' => 'off',
'veo_variant' => 'luma-ray-2',
'replicate_i2v_model' => $model,
],
];
}
if ($model === 'kwaivgi/kling-v1.6-pro') {
$duration = ((string) ($options['video_duration'] ?? '8s')) === '5s' ? 5 : 10;
return [
'input' => [
'prompt' => $prompt,
'start_image' => $imageUrl,
'duration' => $duration,
'aspect_ratio' => $aspectRatio,
],
'applied_settings' => [
'aspect_ratio' => $aspectRatio,
'video_duration' => $duration.'s',
'video_quality' => '1080p',
'video_audio' => 'off',
'veo_variant' => 'kling-v1.6-pro',
'replicate_i2v_model' => $model,
],
];
}
return [
'input' => [
'prompt' => $prompt,
'first_frame_image' => $imageUrl,
'prompt_optimizer' => true,
],
'applied_settings' => [
'aspect_ratio' => $aspectRatio,
'video_duration' => '6s',
'video_quality' => '720p',
'video_audio' => 'off',
'veo_variant' => 'legacy-replicate',
'replicate_i2v_model' => $model,
],
];
}
private function resolveRequestedModel(array $options): string
{
$requestedProvider = trim((string) ($options['video_provider'] ?? ''));
$requestedModel = trim((string) ($options['replicate_i2v_model'] ?? ''));
if ($requestedProvider === 'replicate') {
return $requestedModel !== '' ? $requestedModel : trim($this->i2vModel);
}
$requestedVariant = trim((string) ($options['veo_variant'] ?? ''));
return match ($requestedVariant) {
'veo-3' => 'google/veo-3',
'veo-3-fast' => 'google/veo-3-fast',
default => trim($this->i2vModel),
};
}
private function normalizeAspectRatio(string $aspectRatio): string
{
return match (trim($aspectRatio)) {
'9:16', '16:9' => trim($aspectRatio),
default => '16:9',
};
}
private function normalizeVeoDuration(string $duration): int
{
return match (trim($duration)) {
'4s', '5s' => 4,
'6s' => 6,
default => 8,
};
}
private function resolveWanFrameSettings(string $duration): array
{
return match (trim($duration)) {
'6s' => [72, 12, '6s'],
'8s' => [96, 12, '8s'],
default => [48, 12, '4s'],
};
}
/**
* STEP B β called from polling AJAX endpoint every ~5s.
* Returns status array. When succeeded, downloads and stores the video.
*
* @return array{status: string, url?: string, error?: string}
*/
public function checkStatus(string $predictionId): array
{
$endpoint = rtrim($this->baseUrl, '/') . '/predictions/' . $predictionId;
$response = Http::withToken($this->apiKey)
->timeout(15)
->get($endpoint);
if ($response->failed()) {
return ['status' => 'failed', 'error' => 'Gagal mengambil status dari Replicate.'];
}
$status = (string) $response->json('status');
if ($status === 'succeeded') {
$output = $response->json('output');
$remoteUrl = is_array($output) ? ($output[0] ?? null) : $output;
if (blank($remoteUrl)) {
return ['status' => 'failed', 'error' => 'Output URL kosong.'];
}
try {
$localUrl = $this->downloadVideo((string) $remoteUrl);
return ['status' => 'succeeded', 'url' => $localUrl, 'remote_url' => (string) $remoteUrl];
} catch (\Throwable $e) {
return ['status' => 'failed', 'error' => $e->getMessage()];
}
}
if ($status === 'failed' || $status === 'canceled') {
$error = $response->json('error') ?? $status;
return ['status' => 'failed', 'error' => Str::limit((string) $error, 200)];
}
// starting | processing
return ['status' => $status];
}
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
/**
* Submit a luma/reframe-video prediction.
* Reframes (reaspects) an existing video to the target aspect ratio.
*
* @param string $videoUrl Absolute URL to the source video
* @param string $aspectRatio Target ratio: "9:16" | "16:9" | "1:1" | "4:5"
* @return string prediction_id
*/
public function submitReframe(string $videoUrl, string $aspectRatio = '9:16'): string
{
if (! $this->isAvailable()) {
throw new RuntimeException('REPLICATE_API_KEY belum diset.');
}
if (! str_starts_with($videoUrl, 'http')) {
$videoUrl = rtrim((string) config('app.url', ''), '/') . '/' . ltrim($videoUrl, '/');
}
$endpoint = rtrim($this->baseUrl, '/') . '/models/luma/reframe-video/predictions';
$payload = [
'input' => [
'video_url' => $videoUrl,
'aspect_ratio' => $aspectRatio,
],
];
$response = Http::withToken($this->apiKey)->timeout(30)->post($endpoint, $payload);
if ($response->status() === 429) {
sleep(3);
$response = Http::withToken($this->apiKey)->timeout(30)->post($endpoint, $payload);
}
if ($response->failed()) {
$detail = $response->json('detail') ?? $response->body();
if ($response->status() === 429) {
throw new RuntimeException('Replicate sibuk (rate limit). Coba beberapa detik lagi.');
}
throw new RuntimeException('Luma reframe submit gagal: ' . Str::limit((string) $detail, 200));
}
$id = $response->json('id');
if (blank($id)) {
throw new RuntimeException('Replicate: prediction ID tidak ada di response.');
}
Log::info('ReplicateVideoService(luma/reframe): submitted', ['id' => $id]);
return (string) $id;
}
/**
* Submit a topazlabs/video-upscale prediction.
* Enhances and upscales a low-resolution video.
*
* @param string $videoUrl Absolute URL to the source video
* @return string prediction_id
*/
public function submitVideoUpscale(string $videoUrl): string
{
if (! $this->isAvailable()) {
throw new RuntimeException('REPLICATE_API_KEY belum diset.');
}
if (! str_starts_with($videoUrl, 'http')) {
$videoUrl = rtrim((string) config('app.url', ''), '/') . '/' . ltrim($videoUrl, '/');
}
$endpoint = rtrim($this->baseUrl, '/') . '/models/topazlabs/video-upscale/predictions';
$payload = [
'input' => [
'video' => $videoUrl,
],
];
$response = Http::withToken($this->apiKey)->timeout(30)->post($endpoint, $payload);
if ($response->status() === 429) {
sleep(3);
$response = Http::withToken($this->apiKey)->timeout(30)->post($endpoint, $payload);
}
if ($response->failed()) {
$detail = $response->json('detail') ?? $response->body();
if ($response->status() === 429) {
throw new RuntimeException('Replicate sibuk (rate limit). Coba beberapa detik lagi.');
}
throw new RuntimeException('Topaz video-upscale submit gagal: ' . Str::limit((string) $detail, 200));
}
$id = $response->json('id');
if (blank($id)) {
throw new RuntimeException('Replicate: prediction ID tidak ada di response.');
}
Log::info('ReplicateVideoService(topaz/video-upscale): submitted', ['id' => $id]);
return (string) $id;
}
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
private function downloadVideo(string $remoteUrl): string
{
$response = Http::withOptions(['stream' => false])
->timeout(60)
->get($remoteUrl);
if ($response->failed()) {
throw new RuntimeException('Gagal download video dari Replicate: ' . $remoteUrl);
}
$relPath = 'videos/replicate_' . now()->format('Ymd_His') . '_' . Str::lower(Str::random(8)) . '.mp4';
$absPath = Storage::disk('public')->path($relPath);
$outputDir = dirname($absPath);
if (! is_dir($outputDir) && ! @mkdir($outputDir, 0775, true) && ! is_dir($outputDir)) {
throw new RuntimeException('Gagal menyiapkan folder output video Replicate.');
}
file_put_contents($absPath, $response->body());
if (! is_file($absPath) || filesize($absPath) < 1024) {
throw new RuntimeException('File video Replicate kosong atau rusak setelah download.');
}
if ($this->hfMediaStorage !== null) {
try {
return $this->hfMediaStorage->offloadPublicRelativePath($relPath);
} catch (\Throwable $e) {
Log::warning('ReplicateVideoService: HF offload failed', ['error' => $e->getMessage()]);
}
}
return Storage::disk('public')->url($relPath);
}
}
|