Repository navigation
Expand file tree
/
Copy pathapi.js
More file actions
673 lines (565 loc) · 22.8 KB
/
Copy pathapi.js
File metadata and controls
673 lines (565 loc) · 22.8 KB
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
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
/**
* Gemini API Integration Module
* Handles all API calls to Google Gemini services
*/
/**
* API Manager Class
* Manages all interactions with Google Gemini API
*/
class GeminiAPIManager {
constructor(apiKey) {
this.apiKey = apiKey || CONFIG.API.GEMINI_API_KEY;
this.baseUrl = CONFIG.API.ENDPOINTS.GEMINI_BASE;
this.cache = new Map();
}
/**
* Makes a generic API request with retry logic
* @param {string} endpoint - API endpoint
* @param {Object} payload - Request payload
* @param {number} timeout - Request timeout in ms
* @returns {Promise<Object>} API response
*/
async makeRequest(endpoint, payload, timeout = 30000) {
const url = `${this.baseUrl}/${endpoint}`;
let lastError = null;
const maxRetries = CONFIG.API.RATE_LIMITS.MAX_RETRIES;
for (let attempt = 0; attempt < maxRetries; attempt++) {
try {
if (CONFIG.DEBUG) {
console.log(`🔄 API Request (Attempt ${attempt + 1}/${maxRetries}):`, endpoint);
}
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), timeout);
let response;
try {
response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-goog-api-key': this.apiKey
},
body: JSON.stringify(payload),
signal: controller.signal
});
} finally {
clearTimeout(timeoutId);
}
if (!response.ok) {
const errorData = await response.json().catch(() => ({}));
// Handle rate limiting
if (response.status === 429) {
throw new Error('RATE_LIMIT');
}
// Handle authentication errors
if (response.status === 401 || response.status === 403) {
throw new Error('AUTHENTICATION_FAILED');
}
const requestError = new Error(errorData.error?.message || `HTTP ${response.status}`);
requestError.isRetryable = response.status >= 500;
throw requestError;
}
const data = await response.json();
if (CONFIG.DEBUG) {
console.log('✅ API Response received');
}
return data;
} catch (error) {
lastError = error;
if (error.name === 'AbortError') {
console.error('❌ API request timeout');
lastError = new Error('TIMEOUT');
}
// Don't retry on authentication errors
if (error.message === 'AUTHENTICATION_FAILED') {
throw error;
}
if (error.isRetryable === false) {
throw error;
}
// Wait before retrying (exponential backoff)
if (attempt < maxRetries - 1) {
const delay = CONFIG.API.RATE_LIMITS.RETRY_DELAY * Math.pow(CONFIG.API.RATE_LIMITS.BACKOFF_MULTIPLIER, attempt);
await this.sleep(delay);
}
}
}
throw lastError || new Error('GENERATION_FAILED');
}
/**
* Step 1: Generate script using Gemini Flash
* @param {string} productDescription - Description of the product
* @param {string} contentStyle - Selected content style
* @returns {Promise<string>} Generated script
*/
async generateScript(productDescription, contentStyle) {
const cacheKey = `script_${productDescription}_${contentStyle}`;
// Check cache if enabled
if (CONFIG.FEATURES.ENABLE_CACHE && this.cache.has(cacheKey)) {
if (CONFIG.DEBUG) {
console.log('📦 Using cached script');
}
return this.cache.get(cacheKey);
}
const styleConfig = CONFIG.CONTENT_STYLES[contentStyle];
const systemPrompt = `You are an expert UGC copywriter specializing in TikTok and Instagram content. Generate an 8-second script in conversational, natural, and emotional French for ${styleConfig.label} content about ${productDescription}.
Requirements:
- Maximum 20 spoken words
- Attention-grabbing hook
- One key benefit with emotional appeal
- Short call-to-action
- Tone: ${styleConfig.tone}
- Use casual French expressions and natural speech patterns as if speaking to a friend
- NOT overly commercial or salesy
Output format: Plain text only, with no timing markers, labels, or quotation marks.`;
const payload = {
contents: [{
parts: [{
text: systemPrompt
}]
}],
generationConfig: {
temperature: 0.8,
maxOutputTokens: 200,
topP: 0.95,
topK: 40
}
};
try {
const response = await this.makeRequest(
CONFIG.API.ENDPOINTS.GEMINI_FLASH,
payload,
CONFIG.API.TIMEOUTS.SCRIPT_GENERATION
);
const script = this.extractTextFromResponse(response);
if (!script) {
throw new Error('INVALID_RESPONSE');
}
// Cache the result
if (CONFIG.FEATURES.ENABLE_CACHE) {
this.cache.set(cacheKey, script);
}
if (CONFIG.DEBUG) {
console.log('📝 Generated Script:', script);
}
return script;
} catch (error) {
console.error('❌ Script generation failed:', error);
throw this.mapError(error);
}
}
/**
* Step 2: Compose scene using Gemini image generation
* @param {File} productImage - Product image file
* @param {File} personImage - Person image file
* @param {string} setting - Selected setting
* @returns {Promise<string>} Base64 encoded composed image
*/
async composeScene(productImage, personImage, setting) {
const cacheKey = `scene_${productImage.name}_${personImage.name}_${setting}`;
if (CONFIG.FEATURES.ENABLE_CACHE && this.cache.has(cacheKey)) {
if (CONFIG.DEBUG) {
console.log('📦 Using cached scene composition');
}
return this.cache.get(cacheKey);
}
const settingConfig = CONFIG.SETTINGS[setting];
const prompt = `Create a photorealistic composite image showing the person holding or actively using the product in a ${settingConfig.label}.
Requirements:
- Person looking directly at camera with an engaging, natural expression
- Natural lighting: ${settingConfig.lighting}
- Authentic UGC style (not polished advertising aesthetic)
- Composition: Medium chest-up shot, slightly off-center for intimacy
- Seamless integration of person and product
- Background matches the selected setting with appropriate depth of field
- Color grading: Natural, slightly warm tones
Output: High-resolution image (1080x1920) suitable for video generation.`;
try {
// Convert images to base64
const productBase64 = await this.fileToBase64(productImage);
const personBase64 = await this.fileToBase64(personImage);
const payload = {
contents: [{
parts: [
{ text: prompt },
{
inlineData: {
mimeType: productImage.type,
data: productBase64
}
},
{
inlineData: {
mimeType: personImage.type,
data: personBase64
}
}
]
}],
generationConfig: {
temperature: 0.7,
responseModalities: ['TEXT', 'IMAGE'],
responseFormat: {
image: {
aspectRatio: CONFIG.VIDEO.ASPECT_RATIO
}
}
}
};
const response = await this.makeRequest(
CONFIG.API.ENDPOINTS.GEMINI_IMAGE,
payload,
CONFIG.API.TIMEOUTS.IMAGE_COMPOSITION
);
// Extract image from response
const composedImage = this.extractImageFromResponse(response);
if (!composedImage) {
throw new Error('INVALID_RESPONSE');
}
// Cache the result
if (CONFIG.FEATURES.ENABLE_CACHE) {
this.cache.set(cacheKey, composedImage);
}
if (CONFIG.DEBUG) {
console.log('🎨 Scene composed successfully');
}
return composedImage;
} catch (error) {
console.error('❌ Scene composition failed:', error);
throw this.mapError(error);
}
}
/**
* Step 3: Generate video using Veo 3.1
* @param {string} composedImageBase64 - Base64 encoded composed image
* @param {string} script - Generated script
* @param {string} setting - Selected setting
* @returns {Promise<string>} Video URL or base64
*/
async generateVideo(composedImageBase64, script, setting) {
const settingConfig = CONFIG.SETTINGS[setting];
const imageData = typeof composedImageBase64 === 'string'
? { data: composedImageBase64, mimeType: 'image/png' }
: composedImageBase64;
const prompt = `Generate an 8-second 1080p vertical video (9:16 aspect ratio) of this person speaking naturally to camera.
Motion requirements:
- Natural facial micro-expressions synchronized with speech
- Subtle hand gestures (2-3 throughout video)
- Slight head tilts and movements for authenticity
- Realistic eye contact with camera
The person should appear to speak the following French text:
"${script}"
Audio requirements:
- Native audio track with ambient sounds matching ${settingConfig.label}
- Ambient sounds: ${settingConfig.ambiance}
- Automatic lip-sync with the script
Style: Organic UGC aesthetic - NOT overproduced. Should look like an authentic Instagram Story or TikTok video shot on a smartphone. Natural imperfections are acceptable and preferred.
Technical specs:
- Resolution: 1080x1920 (vertical)
- Frame rate: 24fps
- Duration: 8 seconds
- First frame: Use the provided composed image`;
try {
const payload = {
instances: [{
prompt,
image: {
inlineData: {
mimeType: imageData.mimeType || 'image/png',
data: imageData.data
}
}
}],
parameters: {
aspectRatio: CONFIG.VIDEO.ASPECT_RATIO,
durationSeconds: CONFIG.VIDEO.DURATION,
resolution: '1080p',
personGeneration: 'allow_adult'
}
};
const response = await this.makeRequest(
CONFIG.API.ENDPOINTS.VEO,
payload,
CONFIG.API.TIMEOUTS.VIDEO_GENERATION
);
// For long-running video generation, may need to poll for status
const videoData = await this.pollVideoStatus(response);
if (!videoData) {
throw new Error('INVALID_RESPONSE');
}
if (CONFIG.DEBUG) {
console.log('🎬 Video generated successfully');
}
return videoData;
} catch (error) {
console.error('❌ Video generation failed:', error);
throw this.mapError(error);
}
}
/**
* Polls for video generation status if needed
* @param {Object} initialResponse - Initial API response
* @returns {Promise<string>} Final video data
*/
async pollVideoStatus(initialResponse) {
// Check if video is immediately available
const videoUrl = this.extractVideoFromResponse(initialResponse);
if (videoUrl) {
return this.prepareVideoForBrowser(videoUrl);
}
// If operation is pending, poll for completion
const operationName = initialResponse.name;
if (!operationName) {
throw new Error('INVALID_RESPONSE');
}
const maxPolls = Math.ceil((6 * 60 * 1000) / CONFIG.API.TIMEOUTS.POLLING_INTERVAL);
let pollCount = 0;
while (pollCount < maxPolls) {
await this.sleep(CONFIG.API.TIMEOUTS.POLLING_INTERVAL);
pollCount++;
try {
const statusUrl = operationName.startsWith('operations/')
? `${this.baseUrl}/${operationName}`
: `${this.baseUrl}/operations/${operationName}`;
const response = await fetch(statusUrl, {
headers: {
'x-goog-api-key': this.apiKey
}
});
if (!response.ok) {
throw new Error(`Status check failed: ${response.status}`);
}
const status = await response.json();
if (status.done) {
if (status.error) {
const operationError = new Error(status.error.message || 'GENERATION_FAILED');
operationError.isTerminal = true;
throw operationError;
}
const video = this.extractVideoFromResponse(status.response);
if (video) {
return this.prepareVideoForBrowser(video);
}
throw new Error('INVALID_RESPONSE');
}
if (CONFIG.DEBUG) {
console.log(`⏳ Video generation in progress... (${pollCount}/${maxPolls})`);
}
} catch (error) {
if (error.isTerminal || pollCount >= maxPolls - 1) {
throw error;
}
}
}
throw new Error('TIMEOUT');
}
/**
* Process and add subtitles to video
* @param {string} videoData - Video data (URL or base64)
* @param {string} script - Script text for subtitles
* @returns {Promise<string>} Video with subtitles
*/
async addSubtitles(videoData, script) {
// Note: Subtitle generation would typically be done server-side
// or using a video processing library. This is a placeholder.
if (CONFIG.DEBUG) {
console.log('📝 Adding subtitles to video');
}
// In a production environment, you would:
// 1. Use a service like AWS MediaConvert or FFmpeg
// 2. Generate WebVTT or SRT subtitle files
// 3. Burn subtitles into the video or serve them separately
// For now, return the video data as-is
// The Gemini API may support subtitle overlay in future versions
return videoData;
}
/**
* Analyzes product from image
* @param {File} productImage - Product image file
* @returns {Promise<string>} Product description
*/
async analyzeProduct(productImage) {
try {
const productBase64 = await this.fileToBase64(productImage);
const payload = {
contents: [{
parts: [
{ text: 'Describe this product in 2-3 words in French (e.g., "crème hydratante", "smartphone élégant", "chaussures de sport"). Be concise and focus on the product category.' },
{
inlineData: {
mimeType: productImage.type,
data: productBase64
}
}
]
}],
generationConfig: {
temperature: 0.3,
maxOutputTokens: 50
}
};
const response = await this.makeRequest(
CONFIG.API.ENDPOINTS.GEMINI_FLASH,
payload,
CONFIG.API.TIMEOUTS.SCRIPT_GENERATION
);
const description = this.extractTextFromResponse(response);
if (CONFIG.DEBUG) {
console.log('🔍 Product detected:', description);
}
return description || 'ce produit';
} catch (error) {
console.error('⚠️ Product analysis failed, using generic description');
return 'ce produit';
}
}
/**
* Converts File to base64
* @param {File} file - File to convert
* @returns {Promise<string>} Base64 string (without data URI prefix)
*/
async fileToBase64(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => {
// Remove the data URI prefix (e.g., "data:image/jpeg;base64,")
const base64 = reader.result.split(',')[1];
resolve(base64);
};
reader.onerror = reject;
reader.readAsDataURL(file);
});
}
/**
* Extracts text from Gemini API response
* @param {Object} response - API response
* @returns {string} Extracted text
*/
extractTextFromResponse(response) {
try {
const parts = response?.candidates?.[0]?.content?.parts || response?.parts || [];
return parts.find(part => typeof part.text === 'string')?.text || '';
} catch (error) {
console.error('Failed to extract text from response:', error);
return '';
}
}
/**
* Extracts image from Gemini API response
* @param {Object} response - API response
* @returns {string} Base64 encoded image
*/
extractImageFromResponse(response) {
try {
const parts = response?.candidates?.[0]?.content?.parts || response?.parts || [];
const imagePart = parts.find(part => part.inline_data?.data || part.inlineData?.data);
const inlineData = imagePart?.inline_data || imagePart?.inlineData;
if (!inlineData?.data) {
return '';
}
return {
data: inlineData.data,
mimeType: inlineData.mime_type || inlineData.mimeType || 'image/png'
};
} catch (error) {
console.error('Failed to extract image from response:', error);
return '';
}
}
/**
* Extracts video URL/data from API response
* @param {Object} response - API response
* @returns {string} Video URL or base64
*/
extractVideoFromResponse(response) {
try {
const generatedSample = response?.generateVideoResponse?.generatedSamples?.[0]?.video;
if (generatedSample?.uri) return generatedSample.uri;
if (generatedSample?.videoBytes) return `data:video/mp4;base64,${generatedSample.videoBytes}`;
const generatedVideo = response?.generatedVideos?.[0]?.video;
if (generatedVideo?.uri) return generatedVideo.uri;
if (generatedVideo?.videoBytes) return `data:video/mp4;base64,${generatedVideo.videoBytes}`;
// Check for video URL
const videoUrl = response?.candidates?.[0]?.content?.parts?.[0]?.fileData?.fileUri;
if (videoUrl) return videoUrl;
// Check for inline video data
const videoData = response?.candidates?.[0]?.content?.parts?.[0]?.inline_data?.data;
if (videoData) return `data:video/mp4;base64,${videoData}`;
return '';
} catch (error) {
console.error('Failed to extract video from response:', error);
return '';
}
}
/**
* Converts generated video URIs into browser-playable object URLs.
* @param {string} videoData - Video URI, data URL, or base64 data
* @returns {Promise<string>} Browser-playable video URL
*/
async prepareVideoForBrowser(videoData) {
if (!videoData || videoData.startsWith('data:') || videoData.startsWith('blob:')) {
return videoData;
}
const response = await fetch(videoData, {
headers: {
'x-goog-api-key': this.apiKey
}
});
if (!response.ok) {
throw new Error(`VIDEO_DOWNLOAD_FAILED_${response.status}`);
}
const blob = await response.blob();
return URL.createObjectURL(blob);
}
/**
* Maps API errors to user-friendly error codes
* @param {Error} error - Original error
* @returns {Error} Mapped error
*/
mapError(error) {
const errorMessage = error.message || error.toString();
if (errorMessage.includes('RATE_LIMIT') || errorMessage.includes('429')) {
const mappedError = new Error('RATE_LIMIT');
mappedError.userMessage = CONFIG.ERRORS.API.RATE_LIMIT;
return mappedError;
}
if (errorMessage.includes('TIMEOUT') || errorMessage.includes('AbortError')) {
const mappedError = new Error('TIMEOUT');
mappedError.userMessage = CONFIG.ERRORS.API.TIMEOUT;
return mappedError;
}
if (errorMessage.includes('AUTHENTICATION_FAILED')) {
const mappedError = new Error('AUTHENTICATION_FAILED');
mappedError.userMessage = CONFIG.ERRORS.API.AUTHENTICATION_FAILED;
return mappedError;
}
if (errorMessage.includes('INVALID_RESPONSE')) {
const mappedError = new Error('INVALID_RESPONSE');
mappedError.userMessage = CONFIG.ERRORS.API.INVALID_RESPONSE;
return mappedError;
}
const mappedError = new Error('GENERATION_FAILED');
mappedError.userMessage = CONFIG.ERRORS.API.GENERATION_FAILED;
return mappedError;
}
/**
* Utility function to sleep/wait
* @param {number} ms - Milliseconds to wait
* @returns {Promise<void>}
*/
sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
/**
* Clears the cache
*/
clearCache() {
this.cache.clear();
if (CONFIG.DEBUG) {
console.log('🗑️ Cache cleared');
}
}
}
// Export the API manager
if (typeof module !== 'undefined' && module.exports) {
module.exports = { GeminiAPIManager };
}