File size: 22,091 Bytes
1501522
 
 
 
 
 
 
071a77d
74acf19
 
 
 
 
1501522
 
 
 
74acf19
d4d07bc
1501522
 
 
 
 
 
 
071a77d
c0eb121
 
 
 
 
87c35c6
c0eb121
 
 
 
 
 
87c35c6
c0eb121
 
 
 
87c35c6
c0eb121
87c35c6
1501522
87c35c6
c0eb121
 
 
 
 
 
87c35c6
c0eb121
 
 
 
87c35c6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1501522
 
 
 
 
74acf19
1501522
 
 
74acf19
c0eb121
1501522
74acf19
c0eb121
 
74acf19
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c0eb121
 
74acf19
 
 
 
 
 
 
 
 
 
 
 
c0eb121
74acf19
1501522
c0eb121
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1501522
 
 
74acf19
071a77d
74acf19
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d4d07bc
 
 
74acf19
 
 
 
 
 
d4d07bc
 
74acf19
d4d07bc
 
74acf19
 
 
 
d4d07bc
 
 
 
 
74acf19
071a77d
 
d4d07bc
 
 
 
 
 
071a77d
d4d07bc
 
071a77d
 
 
74acf19
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1501522
 
 
 
 
 
 
 
74acf19
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1501522
 
 
 
 
 
 
87c35c6
1501522
 
 
 
87c35c6
 
1501522
87c35c6
1501522
87c35c6
 
 
 
 
 
 
 
 
 
c0eb121
 
 
 
87c35c6
 
1501522
 
 
 
c0eb121
74acf19
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1501522
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
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
<?php

namespace App\Services;

class SocialMediaStudioService
{
    public function __construct(
        private HuggingFaceImageService $huggingFaceImage,
        private HuggingFaceVideoService $huggingFaceVideo,
        private FreepikVideoService $freepikVideo,
        private FreepikAssetRemixService $freepikAssetRemix,
        private OpenAiVideoService $openAiVideo,
        private ReplicateImageService $replicateImage,
        private PollinationsImageService $pollinations,
        private PosterImageService $posterImage,
        private StoryImageNormalizerService $storyNormalizer,
        private MotionVideoService $motionVideo,
        private GeminiVideoService $geminiVideo,
        private ReplicateVideoService $replicateVideo,
    ) {
    }

    public function generateImage(string $prompt): array
    {
        $cleanPrompt = trim($prompt);

        return $this->generateImageFallback($cleanPrompt, []);
    }

    private function generateImageFallback(string $prompt, array $fallbackErrors): array
    {
        try {
            $urls = $this->huggingFaceImage->generate($prompt, 'portrait', 4);
            $variants = $this->storyNormalizer->normalizeMany($urls);

            return [
                'url' => $variants[0]['url'] ?? null,
                'thumbnail_url' => $variants[0]['thumbnail_url'] ?? null,
                'variants' => $variants,
                'provider' => 'huggingface',
                'aspect' => '9:16',
                'prompt' => $prompt,
                'width' => 1080,
                'height' => 1920,
                'notice' => 'Image story-size diproses lewat Hugging Face.',
            ];
        } catch (\Throwable $hfError) {
            try {
                $urls = $this->pollinations->generate($prompt, 'portrait', 4);
                $variants = $this->storyNormalizer->normalizeMany($urls);

                return [
                    'url' => $variants[0]['url'] ?? null,
                    'thumbnail_url' => $variants[0]['thumbnail_url'] ?? null,
                    'variants' => $variants,
                    'provider' => 'pollinations',
                    'aspect' => '9:16',
                    'prompt' => $prompt,
                    'width' => 1080,
                    'height' => 1920,
                    'notice' => 'Image story-size diproses lewat Pollinations.',
                ];
            } catch (\Throwable $pollinationsError) {
                $urls = $this->posterImage->generate($prompt, 'portrait', 4);
                $variants = $this->storyNormalizer->normalizeMany($urls);

                return [
                    'url' => $variants[0]['url'] ?? null,
                    'thumbnail_url' => $variants[0]['thumbnail_url'] ?? null,
                    'variants' => $variants,
                    'provider' => 'poster',
                    'aspect' => '9:16',
                    'prompt' => $prompt,
                    'width' => 1080,
                    'height' => 1920,
                    'notice' => 'Provider eksternal tidak tersedia, menggunakan poster story-size lokal.',
                    'fallback_errors' => array_merge($fallbackErrors, [
                        'huggingface' => $hfError->getMessage(),
                        'pollinations' => $pollinationsError->getMessage(),
                    ]),
                ];
            }
        }
    }

    public function generateVideo(string $prompt, array $options = []): array
    {
        $cleanPrompt = trim($prompt);

        return $this->generateVideoFallback($cleanPrompt, [], $options);
    }

    private function generateVideoFallback(string $prompt, array $fallbackErrors, array $options = []): array
    {
        try {
            $requestedProvider = $this->resolveRequestedVideoProvider($options);

            if ($requestedProvider === 'gemini') {
                if (! $this->geminiVideo->isAvailable()) {
                    throw new \RuntimeException('Provider Gemini belum siap karena GEMINI_API_KEY belum diset.');
                }

                $submission = $this->geminiVideo->submit(null, $prompt, $options);
                $appliedSettings = (array) ($submission['applied_settings'] ?? []);

                return [
                    'provider' => 'gemini-veo',
                    'prediction_id' => $submission['prediction_id'] ?? null,
                    'prompt' => $prompt,
                    'applied_settings' => $appliedSettings,
                    'notice' => 'Render Google Veo native aktif dengan '.$this->describeAppliedVideoSettings($appliedSettings).'.',
                    'async' => true,
                ];
            }

            if ($requestedProvider === 'huggingface') {
                return $this->huggingFaceVideo->generate(null, $prompt, $options);
            }

            if ($requestedProvider === 'runway') {
                try {
                    $duration = (int) preg_replace('/[^0-9]/', '', (string) ($options['video_duration'] ?? '4s'));
                    $video = $this->freepikVideo->generate($prompt, $duration);

                    return [
                        ...$video,
                        'prompt' => $prompt,
                        'notice' => 'Render Runway aktif lewat Freepik dengan output vertikal siap pakai.',
                        'async' => false,
                    ];
                } catch (\Throwable $runwayError) {
                    $fallbackErrors['runway'] = $runwayError->getMessage();

                    if ($this->replicateVideo->isAvailable()) {
                        $image = $this->generateSingleStoryImage($prompt);
                        $fallbackOptions = array_merge($options, ['video_provider' => 'replicate']);
                        $video = $this->generateVideoFromImageUrl((string) $image['url'], $prompt, $fallbackOptions);

                        return [
                            ...$video,
                            'source_image_provider' => $image['provider'] ?? 'huggingface',
                            'notice' => 'Runway tidak tersedia saat ini, otomatis dialihkan ke Replicate dari source frame story terbaru.',
                            'fallback_errors' => array_merge($fallbackErrors, (array) ($image['fallback_errors'] ?? [])),
                        ];
                    }
                }
            }

            if ($requestedProvider === 'openai') {
                return $this->openAiVideo->generate(null, $prompt, $options);
            }

            if ($requestedProvider === 'replicate') {
                if (! $this->replicateVideo->isAvailable()) {
                    throw new \RuntimeException('Provider Replicate belum siap karena REPLICATE_API_KEY belum diset.');
                }

                $image = $this->generateSingleStoryImage($prompt);
                $video = $this->generateVideoFromImageUrl((string) $image['url'], $prompt, $options);

                return [
                    ...$video,
                    'source_image_provider' => $image['provider'] ?? 'huggingface',
                    'notice' => 'Video diproses lewat Replicate dari source frame story terbaru.',
                    'fallback_errors' => array_merge($fallbackErrors, (array) ($image['fallback_errors'] ?? [])),
                ];
            }

            // Buat frame visual dulu
            $image = $this->generateSingleStoryImage($prompt);

            if ($this->replicateVideo->isAvailable()) {
                $video = $this->generateVideoFromImageUrl((string) $image['url'], $prompt, $options);

                return [
                    ...$video,
                    'source_image_provider' => $image['provider'] ?? 'huggingface',
                    'notice' => 'Video diproses lewat Replicate dari source frame story terbaru.',
                    'fallback_errors' => array_merge($fallbackErrors, (array) ($image['fallback_errors'] ?? [])),
                ];
            }

            // Render jadi motion video lokal via ffmpeg
            $video = $this->motionVideo->createFromImageUrl((string) $image['url'], $prompt, $options);

            return [
                'url' => $video['url'],
                'provider' => $video['provider'],
                'aspect' => '9:16',
                'prompt' => $prompt,
                'duration_seconds' => $video['duration_seconds'] ?? 6,
                'source_image_url' => $image['url'],
                'source_image_provider' => $image['provider'],
                'notice' => 'Video vertikal dirender lokal dari visual story terbaru.',
                'fallback_errors' => array_merge($fallbackErrors, (array) ($image['fallback_errors'] ?? [])),
            ];
        } catch (\Throwable $fallbackVideoError) {
            throw new \RuntimeException(
                'Gagal membuat video: ' . $fallbackVideoError->getMessage()
            );
        }
    }

    public function generateVideoFromImageUrl(string $imageUrl, string $prompt, array $options = []): array
    {
        $requestedProvider = $this->resolveRequestedVideoProvider($options);

        if ($requestedProvider === 'gemini') {
            if (! $this->geminiVideo->isAvailable()) {
                throw new \RuntimeException('Provider Gemini belum siap karena GEMINI_API_KEY belum diset.');
            }

            $submission = $this->geminiVideo->submit($imageUrl, trim($prompt), $options);
            $appliedSettings = (array) ($submission['applied_settings'] ?? []);

            return [
                'provider' => 'gemini-veo',
                'prediction_id' => $submission['prediction_id'] ?? null,
                'source_image_url' => $imageUrl,
                'prompt' => trim($prompt),
                'requested_quality' => $options['video_quality'] ?? '720p',
                'requested_duration' => $options['video_duration'] ?? '4s',
                'applied_settings' => $appliedSettings,
                'notice' => 'Render Google Veo native aktif dengan '.$this->describeAppliedVideoSettings($appliedSettings).'.',
                'async' => true,
            ];
        }

        if ($requestedProvider === 'huggingface') {
            return $this->huggingFaceVideo->generate($imageUrl, trim($prompt), $options);
        }

        if ($requestedProvider === 'runway') {
            try {
                $duration = (int) preg_replace('/[^0-9]/', '', (string) ($options['video_duration'] ?? '4s'));
                $result = $this->freepikAssetRemix->submitRemixVideo([
                    'type' => 'image',
                    'url' => $imageUrl,
                    'thumbnail_url' => $imageUrl,
                ], trim($prompt), 'image_to_video', $duration);

                return [
                    ...$result,
                    'source_image_url' => $imageUrl,
                    'prompt' => trim($prompt),
                    'notice' => 'Render Runway aktif dari start frame yang dipilih. Job diproses async lalu hasil final akan masuk ke gallery.',
                    'async' => true,
                ];
            } catch (\Throwable $runwayError) {
                if ($this->replicateVideo->isAvailable()) {
                    $fallbackOptions = array_merge($options, ['video_provider' => 'replicate']);
                    $fallbackVideo = $this->generateVideoFromImageUrl($imageUrl, trim($prompt), $fallbackOptions);

                    return [
                        ...$fallbackVideo,
                        'notice' => 'Runway tidak tersedia saat ini, otomatis dialihkan ke Replicate dari start frame yang dipilih.',
                    ];
                }
            }
        }

        if ($requestedProvider === 'openai') {
            return $this->openAiVideo->generate($imageUrl, trim($prompt), $options);
        }

        if ($requestedProvider === 'replicate' && ! $this->replicateVideo->isAvailable()) {
            throw new \RuntimeException('Provider Replicate belum siap karena REPLICATE_API_KEY belum diset.');
        }

        // If Replicate is available, submit async and return prediction_id immediately.
        // The controller redirects right away; browser polls /tools/video/poll for result.
        if ($this->replicateVideo->isAvailable()) {
            $submission = $this->replicateVideo->submit($imageUrl, trim($prompt), $options);
            $appliedSettings = (array) ($submission['applied_settings'] ?? []);
            $appliedModel = (string) ($appliedSettings['replicate_i2v_model'] ?? 'replicate-i2v');
            $appliedQuality = (string) ($appliedSettings['video_quality'] ?? ($options['video_quality'] ?? '720p'));
            $appliedDuration = (string) ($appliedSettings['video_duration'] ?? ($options['video_duration'] ?? '4s'));
            $appliedAudio = (string) ($appliedSettings['video_audio'] ?? ($options['video_audio'] ?? 'off'));
            return [
                'provider'         => 'replicate-i2v',
                'prediction_id'    => $submission['prediction_id'] ?? null,
                'source_image_url' => $imageUrl,
                'prompt'           => trim($prompt),
                'requested_quality' => $options['video_quality'] ?? '720p',
                'requested_duration' => $options['video_duration'] ?? '4s',
                'applied_settings' => $appliedSettings,
                'notice'           => 'Render Replicate aktif memakai '.$appliedModel.' dengan output '.$appliedQuality.', durasi '.$appliedDuration.', dan audio '.($appliedAudio === 'on' ? 'aktif' : 'nonaktif').'.',
                'async'            => true,
            ];
        }

        // Fallback: local FFmpeg Ken Burns zoompan (sync, fast enough on small res)
        $video = $this->motionVideo->createFromImageUrl($imageUrl, trim($prompt), $options);

        return [
            'url'                   => $video['url'],
            'provider'              => $video['provider'],
            'aspect'                => '9:16',
            'prompt'                => trim($prompt),
            'duration_seconds'      => $video['duration_seconds'] ?? 5,
            'source_image_url'      => $imageUrl,
            'source_image_provider' => 'upload',
            'notice'                => 'Video dirender dari gambar (FFmpeg zoompan).',
            'async'                 => false,
        ];
    }

    private function shouldUseGeminiVeo(array $options): bool
    {
        return $this->resolveRequestedVideoProvider($options) === 'gemini'
            && (string) ($options['video_model'] ?? '') === 'veo';
    }

    private function resolveRequestedVideoProvider(array $options): string
    {
        $provider = trim((string) ($options['video_provider'] ?? 'replicate'));

        return match ($provider) {
            'runway', 'huggingface', 'openai', 'replicate' => $provider,
            default => 'gemini',
        };
    }

    private function describeAppliedVideoSettings(array $appliedSettings): string
    {
        $model = (string) ($appliedSettings['gemini_model'] ?? 'veo-3.1-fast-generate-preview');
        $quality = (string) ($appliedSettings['video_quality'] ?? '720p');
        $duration = (string) ($appliedSettings['video_duration'] ?? '4s');
        $audio = (string) ($appliedSettings['video_audio'] ?? 'on');

        return $model.' dengan output '.$quality.', durasi '.$duration.', dan audio '.($audio === 'on' ? 'aktif' : 'nonaktif');
    }

    public function remixFromAsset(array $source, string $prompt, string $mode, string $outputType): array
    {
        $cleanPrompt = trim($prompt);

        if ($cleanPrompt === '') {
            throw new \RuntimeException('Prompt remix tidak boleh kosong.');
        }

        $mode = trim($mode);
        $outputType = trim($outputType);
        $remixPrompt = $this->composeRemixPrompt($source, $cleanPrompt, $mode, $outputType);

        if ($outputType === 'video') {
            $sourceImageUrl = $this->resolveReferenceImageUrl($source);
            $video = $this->generateVideoFromImageUrl($sourceImageUrl, $remixPrompt);

            return [
                ...$video,
                'prompt' => $cleanPrompt,
                'source_image_url' => $sourceImageUrl,
                'notice' => 'AI Remix video diproses lewat jalur Hugging Face-compatible image-to-video.',
            ];
        }

        $image = $this->generateRemixImageFallback($remixPrompt, $mode);

        return [
            ...$image,
            'prompt' => $cleanPrompt,
            'notice' => $image['notice'] ?? 'AI Remix image diproses lewat Replicate/Hugging Face fallback. Hasil mengikuti prompt dan referensi secara aproksimatif.',
        ];
    }

    private function generateSingleStoryImage(string $prompt): array
    {
        $cleanPrompt = trim($prompt);

        try {
            $urls = $this->huggingFaceImage->generate($cleanPrompt, 'portrait', 1);
            $variant = $this->storyNormalizer->normalizeMany($urls)[0];

            return [
                ...$variant,
                'provider' => 'huggingface',
                'notice' => 'Source frame diproses lewat Hugging Face.',
            ];
        } catch (\Throwable $hfError) {
            try {
                $urls = $this->pollinations->generate($cleanPrompt, 'portrait', 1);
                $variant = $this->storyNormalizer->normalizeMany($urls)[0];

                return [
                    ...$variant,
                    'provider' => 'pollinations',
                    'notice' => 'Source frame diproses lewat Pollinations.',
                ];
            } catch (\Throwable $fallbackError) {
                $urls = $this->posterImage->generate($cleanPrompt, 'portrait', 1);
                $variant = $this->storyNormalizer->normalizeMany($urls)[0];

                return [
                    ...$variant,
                    'provider' => 'poster',
                    'notice' => 'Menggunakan poster story-size lokal.',
                ];
            }
        }
    }

    private function composeRemixPrompt(array $source, string $prompt, string $mode, string $outputType): string
    {
        $sourcePrompt = trim((string) ($source['prompt'] ?? ''));
        $modeInstruction = match ($mode) {
            'mockup' => 'Transform the reference into a polished premium mockup while preserving the main subject and overall composition cues.',
            'face_swap', 'strict_face_swap' => 'Preserve the primary identity, facial structure, and key likeness cues from the reference as much as possible while following the new styling request.',
            'restyle' => 'Restyle the reference into a fresh variation while keeping the same subject, framing intent, and recognizable visual anchors.',
            default => 'Create a refined variation based on the reference asset while preserving the main subject and core composition cues.',
        };

        $typeInstruction = ($source['type'] ?? 'image') === 'video'
            ? 'The reference comes from a video thumbnail, so preserve the hero subject and cinematic framing from that source frame.'
            : 'The reference comes from a still image, so preserve the hero subject and key visual balance from that image.';

        $outputInstruction = $outputType === 'video'
            ? 'Write the prompt as a motion-ready direction with clear cinematic movement and continuity from the reference.'
            : 'Write the prompt as an image-generation direction for a single strong keyframe.';

        $sourceInstruction = $sourcePrompt !== ''
            ? 'Reference description: '.$sourcePrompt.'.'
            : 'Reference description: preserve the selected source image subject, identity cues, and overall framing.';

        return trim($modeInstruction.' '.$typeInstruction.' '.$sourceInstruction.' '.$outputInstruction.' User request: '.$prompt);
    }

    private function resolveReferenceImageUrl(array $source): string
    {
        $sourceType = (string) ($source['type'] ?? 'image');

        if ($sourceType === 'video') {
            $thumbnailUrl = trim((string) ($source['thumbnail_url'] ?? ''));

            if ($thumbnailUrl === '') {
                throw new \RuntimeException('Source video belum punya thumbnail/reference image untuk diproses jadi video baru.');
            }

            return $thumbnailUrl;
        }

        $imageUrl = trim((string) ($source['url'] ?? ''));

        if ($imageUrl === '') {
            throw new \RuntimeException('Source image tidak punya URL referensi yang bisa dipakai untuk AI Remix.');
        }

        return $imageUrl;
    }

    private function generateRemixImageFallback(string $prompt, string $mode): array
    {
        $fallbackErrors = [];

        if ($this->replicateImage->isAvailable()) {
            try {
                $provider = $this->replicateProviderForRemixMode($mode);
                $urls = $this->replicateImage->generate($prompt, 'portrait', 1, $provider);
                $variants = $this->storyNormalizer->normalizeMany($urls);

                return [
                    'url' => $variants[0]['url'] ?? null,
                    'thumbnail_url' => $variants[0]['thumbnail_url'] ?? null,
                    'variants' => $variants,
                    'provider' => $provider,
                    'aspect' => '9:16',
                    'prompt' => $prompt,
                    'width' => 1080,
                    'height' => 1920,
                    'notice' => 'AI Remix image diproses lewat Replicate.',
                ];
            } catch (\Throwable $replicateError) {
                $fallbackErrors['replicate'] = $replicateError->getMessage();
            }
        }

        return $this->generateImageFallback($prompt, $fallbackErrors);
    }

    private function replicateProviderForRemixMode(string $mode): string
    {
        return match ($mode) {
            'mockup' => 'replicate-ideogram',
            'restyle', 'face_swap', 'strict_face_swap' => 'replicate-flux',
            default => 'replicate-imagen4',
        };
    }

}