Repository navigation
Expand file tree
/
Copy pathapp.js
More file actions
714 lines (595 loc) · 22.4 KB
/
Copy pathapp.js
File metadata and controls
714 lines (595 loc) · 22.4 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
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
/**
* UGC Video Generator - Main Application Logic
* Handles UI interactions, state management, and orchestrates the video generation pipeline
*/
class UGCVideoGenerator {
constructor() {
// Application state
this.state = {
productImage: null,
personImage: null,
contentStyle: '',
setting: '',
generatedVideo: null,
generatedVideoObjectUrl: null,
isGenerating: false,
currentStep: 0
};
// Initialize API manager
this.apiManager = null;
// DOM elements cache
this.elements = {};
// Initialize the application
this.init();
}
/**
* Initialize the application
*/
init() {
// Wait for DOM to be ready
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', () => this.onDOMReady());
} else {
this.onDOMReady();
}
}
/**
* Called when DOM is ready
*/
onDOMReady() {
// Cache DOM elements
this.cacheElements();
// Initialize API manager
this.initializeAPI();
// Setup event listeners
this.setupEventListeners();
// Initialize UI state
this.updateGenerateButtonState();
if (CONFIG.DEBUG) {
console.log('✅ Application initialized');
}
}
/**
* Cache frequently used DOM elements
*/
cacheElements() {
// Upload elements
this.elements.productUpload = document.getElementById('productUpload');
this.elements.personUpload = document.getElementById('personUpload');
this.elements.productUploadZone = document.getElementById('productUploadZone');
this.elements.personUploadZone = document.getElementById('personUploadZone');
this.elements.productUploadContent = document.getElementById('productUploadContent');
this.elements.personUploadContent = document.getElementById('personUploadContent');
this.elements.productPreview = document.getElementById('productPreview');
this.elements.personPreview = document.getElementById('personPreview');
this.elements.productError = document.getElementById('productError');
this.elements.personError = document.getElementById('personError');
// Selection elements
this.elements.contentStyle = document.getElementById('contentStyle');
this.elements.setting = document.getElementById('setting');
// Action elements
this.elements.apiKeyInput = document.getElementById('apiKeyInput');
this.elements.saveApiKeyBtn = document.getElementById('saveApiKeyBtn');
this.elements.generateBtn = document.getElementById('generateBtn');
// Progress elements
this.elements.progressSection = document.getElementById('progressSection');
this.elements.progressBar = document.getElementById('progressBar');
this.elements.step1 = document.getElementById('step1');
this.elements.step2 = document.getElementById('step2');
this.elements.step3 = document.getElementById('step3');
this.elements.step4 = document.getElementById('step4');
// Video elements
this.elements.videoSection = document.getElementById('videoSection');
this.elements.videoPlayer = document.getElementById('videoPlayer');
this.elements.downloadBtn = document.getElementById('downloadBtn');
this.elements.regenerateBtn = document.getElementById('regenerateBtn');
// Error elements
this.elements.globalErrorSection = document.getElementById('globalErrorSection');
this.elements.globalErrorMessage = document.getElementById('globalErrorMessage');
this.elements.retryBtn = document.getElementById('retryBtn');
// Toast container
this.elements.toastContainer = document.getElementById('toastContainer');
}
/**
* Initialize API manager
*/
initializeAPI() {
// Check for API key in environment or prompt user
let apiKey = CONFIG.API.GEMINI_API_KEY;
// In production, you might load from localStorage or prompt user
if (!apiKey && typeof localStorage !== 'undefined') {
try {
apiKey = localStorage.getItem('gemini_api_key');
} catch (error) {
console.warn('Local API key storage is unavailable in this browser.', error);
}
}
if (!apiKey) {
console.warn('⚠️ No API key found. Please configure GEMINI_API_KEY.');
// You might want to show a modal or prompt here
// For now, we'll initialize anyway and show error when user tries to generate
}
this.apiManager = new GeminiAPIManager(apiKey);
this.elements.apiKeyInput.value = apiKey;
if (CONFIG.DEBUG) {
console.log('🔑 API Manager initialized');
}
}
/**
* Setup all event listeners
*/
setupEventListeners() {
// Product image upload
this.setupFileUpload(
this.elements.productUpload,
this.elements.productUploadZone,
this.elements.productPreview,
this.elements.productUploadContent,
this.elements.productError,
'product'
);
// Person image upload
this.setupFileUpload(
this.elements.personUpload,
this.elements.personUploadZone,
this.elements.personPreview,
this.elements.personUploadContent,
this.elements.personError,
'person'
);
// Selection changes
this.elements.contentStyle.addEventListener('change', () => {
this.state.contentStyle = this.elements.contentStyle.value;
this.updateGenerateButtonState();
});
this.elements.setting.addEventListener('change', () => {
this.state.setting = this.elements.setting.value;
this.updateGenerateButtonState();
});
// Generate button
this.elements.saveApiKeyBtn.addEventListener('click', () => this.saveApiKey());
this.elements.apiKeyInput.addEventListener('keydown', (event) => {
if (event.key === 'Enter') {
this.saveApiKey();
}
});
this.elements.generateBtn.addEventListener('click', () => this.handleGenerate());
// Video actions
this.elements.downloadBtn.addEventListener('click', () => this.handleDownload());
this.elements.regenerateBtn.addEventListener('click', () => this.handleRegenerate());
// Retry button
this.elements.retryBtn.addEventListener('click', () => this.handleRetry());
// Remove image buttons
document.querySelectorAll('.remove-image-btn').forEach(btn => {
btn.addEventListener('click', (e) => {
e.stopPropagation();
const type = btn.dataset.removeType;
this.removeImage(type);
});
});
}
/**
* Setup file upload functionality
*/
setupFileUpload(inputElement, zoneElement, previewElement, contentElement, errorElement, type) {
// Click to upload
zoneElement.addEventListener('click', () => {
if (!previewElement.classList.contains('hidden')) return;
inputElement.click();
});
// Keyboard accessibility
zoneElement.addEventListener('keydown', (e) => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
if (!previewElement.classList.contains('hidden')) return;
inputElement.click();
}
});
// File input change
inputElement.addEventListener('change', (e) => {
const file = e.target.files[0];
if (file) {
this.handleFileUpload(file, type, previewElement, contentElement, errorElement, zoneElement);
}
});
// Drag and drop
zoneElement.addEventListener('dragover', (e) => {
e.preventDefault();
zoneElement.classList.add('drag-over');
});
zoneElement.addEventListener('dragleave', () => {
zoneElement.classList.remove('drag-over');
});
zoneElement.addEventListener('drop', (e) => {
e.preventDefault();
zoneElement.classList.remove('drag-over');
if (previewElement.classList.contains('hidden')) {
const file = e.dataTransfer.files[0];
if (file) {
this.handleFileUpload(file, type, previewElement, contentElement, errorElement, zoneElement);
}
}
});
}
/**
* Handle file upload
*/
async handleFileUpload(file, type, previewElement, contentElement, errorElement, zoneElement) {
// Hide previous error
errorElement.classList.add('hidden');
// Validate file type
if (!CONFIG.UPLOAD.ALLOWED_TYPES.includes(file.type)) {
this.showError(errorElement, CONFIG.ERRORS.UPLOAD.INVALID_FORMAT);
return;
}
// Validate file size
if (file.size > CONFIG.UPLOAD.MAX_FILE_SIZE) {
this.showError(errorElement, CONFIG.ERRORS.UPLOAD.FILE_TOO_LARGE);
return;
}
try {
// Read file as data URL for preview
const reader = new FileReader();
reader.onload = (e) => {
// Update preview
const img = previewElement.querySelector('.preview-image');
img.src = e.target.result;
// Show preview, hide upload content
contentElement.classList.add('hidden');
previewElement.classList.remove('hidden');
// Update state
if (type === 'product') {
this.state.productImage = file;
} else {
this.state.personImage = file;
}
// Update button state
this.updateGenerateButtonState();
// Show success toast
this.showToast(CONFIG.SUCCESS.UPLOAD_COMPLETE, 'success');
// Track analytics
this.trackEvent(CONFIG.ANALYTICS.EVENTS.IMAGE_UPLOADED, { type });
// Add fade-in animation
previewElement.style.animation = 'fadeIn 0.3s ease-in-out';
};
reader.onerror = () => {
this.showError(errorElement, CONFIG.ERRORS.UPLOAD.UPLOAD_FAILED);
};
reader.readAsDataURL(file);
} catch (error) {
console.error('File upload error:', error);
this.showError(errorElement, CONFIG.ERRORS.UPLOAD.UPLOAD_FAILED);
}
}
/**
* Remove uploaded image
*/
removeImage(type) {
const previewElement = type === 'product' ? this.elements.productPreview : this.elements.personPreview;
const contentElement = type === 'product' ? this.elements.productUploadContent : this.elements.personUploadContent;
const inputElement = type === 'product' ? this.elements.productUpload : this.elements.personUpload;
// Reset state
if (type === 'product') {
this.state.productImage = null;
} else {
this.state.personImage = null;
}
// Reset UI
previewElement.classList.add('hidden');
contentElement.classList.remove('hidden');
inputElement.value = '';
// Update button state
this.updateGenerateButtonState();
}
/**
* Update generate button state
*/
updateGenerateButtonState() {
const hasImages = this.state.productImage && this.state.personImage;
const hasSelections = this.state.contentStyle && this.state.setting;
const hasApiKey = Boolean(this.apiManager?.apiKey);
const canGenerate = hasApiKey && hasImages && hasSelections && !this.state.isGenerating;
this.elements.generateBtn.disabled = !canGenerate;
}
/**
* Store the local API key and update the active API client.
*/
saveApiKey() {
const apiKey = this.elements.apiKeyInput.value.trim();
if (!apiKey) {
try {
localStorage.removeItem('gemini_api_key');
} catch (error) {
console.warn('Local API key storage is unavailable in this browser.', error);
}
setApiKey('');
this.apiManager.apiKey = '';
this.updateGenerateButtonState();
this.showToast(CONFIG.ERRORS.API.API_KEY_MISSING, 'error');
return;
}
try {
localStorage.setItem('gemini_api_key', apiKey);
} catch (error) {
console.warn('Local API key storage is unavailable in this browser.', error);
}
setApiKey(apiKey);
this.apiManager.apiKey = apiKey;
this.updateGenerateButtonState();
this.showToast(CONFIG.SUCCESS.API_KEY_SAVED, 'success');
}
/**
* Handle video generation
*/
async handleGenerate() {
// Validate inputs
if (!this.validateInputs()) {
return;
}
// Check API key
if (!this.apiManager.apiKey) {
this.showGlobalError(CONFIG.ERRORS.API.API_KEY_MISSING);
return;
}
// Update state
this.state.isGenerating = true;
this.updateGenerateButtonState();
// Show progress
this.showProgress();
// Hide previous video or error
this.elements.videoSection.classList.add('hidden');
this.elements.globalErrorSection.classList.add('hidden');
try {
// Step 1: Analyze product
this.updateProgressStep(1);
const productDescription = await this.apiManager.analyzeProduct(this.state.productImage);
// Step 2: Generate script
this.updateProgressStep(2);
const script = await this.apiManager.generateScript(productDescription, this.state.contentStyle);
// Step 3: Compose scene
this.updateProgressStep(3);
const composedImage = await this.apiManager.composeScene(
this.state.productImage,
this.state.personImage,
this.state.setting
);
// Step 4: Generate video
this.updateProgressStep(4);
let videoData = await this.apiManager.generateVideo(
composedImage,
script,
this.state.setting
);
// Add subtitles if enabled
if (CONFIG.SUBTITLES.ENABLED) {
videoData = await this.apiManager.addSubtitles(videoData, script);
}
// Store generated video
this.state.generatedVideo = videoData;
// Show success
this.showVideo(videoData);
this.showToast(CONFIG.SUCCESS.VIDEO_GENERATED, 'success');
// Track analytics
this.trackEvent(CONFIG.ANALYTICS.EVENTS.VIDEO_GENERATED, {
style: this.state.contentStyle,
setting: this.state.setting
});
} catch (error) {
console.error('Video generation error:', error);
// Show error
const errorMessage = error.userMessage || CONFIG.ERRORS.API.GENERATION_FAILED;
this.showGlobalError(errorMessage);
// Track analytics
this.trackEvent(CONFIG.ANALYTICS.EVENTS.GENERATION_FAILED, {
error: error.message
});
} finally {
// Reset state
this.state.isGenerating = false;
this.state.currentStep = 0;
this.updateGenerateButtonState();
// Hide progress
this.hideProgress();
}
}
/**
* Validate inputs before generation
*/
validateInputs() {
if (!this.state.productImage || !this.state.personImage) {
this.showToast(CONFIG.ERRORS.VALIDATION.MISSING_IMAGES, 'error');
return false;
}
if (!this.state.contentStyle) {
this.showToast(CONFIG.ERRORS.VALIDATION.MISSING_STYLE, 'error');
return false;
}
if (!this.state.setting) {
this.showToast(CONFIG.ERRORS.VALIDATION.MISSING_SETTING, 'error');
return false;
}
return true;
}
/**
* Show progress section
*/
showProgress() {
this.elements.progressSection.classList.remove('hidden');
this.elements.generateBtn.classList.add('loading');
// Reset progress bar and steps
this.elements.progressBar.style.width = '0%';
[this.elements.step1, this.elements.step2, this.elements.step3, this.elements.step4].forEach(step => {
step.classList.remove('active', 'completed');
});
}
/**
* Hide progress section
*/
hideProgress() {
this.elements.progressSection.classList.add('hidden');
this.elements.generateBtn.classList.remove('loading');
}
/**
* Update progress step
*/
updateProgressStep(stepNumber) {
const steps = [this.elements.step1, this.elements.step2, this.elements.step3, this.elements.step4];
const progressConfig = CONFIG.PROGRESS_STEPS[stepNumber - 1];
// Mark previous steps as completed
for (let i = 0; i < stepNumber - 1; i++) {
steps[i].classList.remove('active');
steps[i].classList.add('completed');
}
// Mark current step as active
steps[stepNumber - 1].classList.add('active');
steps[stepNumber - 1].classList.remove('completed');
// Update progress bar
this.elements.progressBar.style.width = `${progressConfig.progressPercentage}%`;
this.state.currentStep = stepNumber;
if (CONFIG.DEBUG) {
console.log(`📊 Progress: Step ${stepNumber}/4 (${progressConfig.progressPercentage}%)`);
}
}
/**
* Show generated video
*/
showVideo(videoData) {
// Hide progress
this.hideProgress();
if (this.state.generatedVideoObjectUrl) {
URL.revokeObjectURL(this.state.generatedVideoObjectUrl);
this.state.generatedVideoObjectUrl = null;
}
if (videoData.startsWith('blob:')) {
this.state.generatedVideoObjectUrl = videoData;
}
// Set video source
const videoSource = this.elements.videoPlayer.querySelector('source');
videoSource.src = videoData;
this.elements.videoPlayer.load();
// Show video section
this.elements.videoSection.classList.remove('hidden');
// Scroll to video
this.elements.videoSection.scrollIntoView({ behavior: 'smooth', block: 'center' });
// Auto-play video (with user gesture requirement in mind)
setTimeout(() => {
this.elements.videoPlayer.play().catch(err => {
if (CONFIG.DEBUG) {
console.log('Autoplay prevented:', err);
}
});
}, 300);
}
/**
* Handle video download
*/
async handleDownload() {
if (!this.state.generatedVideo) {
return;
}
try {
this.showToast(CONFIG.SUCCESS.DOWNLOAD_STARTED, 'success');
// Create download link
const link = document.createElement('a');
link.href = this.state.generatedVideo;
link.download = `ugc-video-${Date.now()}.mp4`;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
// Track analytics
this.trackEvent(CONFIG.ANALYTICS.EVENTS.VIDEO_DOWNLOADED);
} catch (error) {
console.error('Download error:', error);
this.showToast(CONFIG.ERRORS.GENERAL.PROCESSING_ERROR, 'error');
}
}
/**
* Handle regenerate
*/
handleRegenerate() {
// Hide video section
this.elements.videoSection.classList.add('hidden');
// Scroll back to top
window.scrollTo({ top: 0, behavior: 'smooth' });
// Clear cache to force regeneration
if (this.apiManager) {
this.apiManager.clearCache();
}
}
/**
* Handle retry after error
*/
handleRetry() {
this.elements.globalErrorSection.classList.add('hidden');
this.handleGenerate();
}
/**
* Show global error
*/
showGlobalError(message) {
this.hideProgress();
this.elements.globalErrorMessage.textContent = message;
this.elements.globalErrorSection.classList.remove('hidden');
this.elements.globalErrorSection.scrollIntoView({ behavior: 'smooth', block: 'center' });
}
/**
* Show field error
*/
showError(errorElement, message) {
errorElement.textContent = message;
errorElement.classList.remove('hidden');
}
/**
* Show toast notification
*/
showToast(message, type = 'success') {
const toast = document.createElement('div');
toast.className = `toast ${type}`;
const icon = type === 'success' ? '✅' : type === 'error' ? '❌' : '⚠️';
toast.innerHTML = `
<span class="toast-icon">${icon}</span>
<span class="toast-message">${message}</span>
`;
this.elements.toastContainer.appendChild(toast);
// Auto-remove after 5 seconds
setTimeout(() => {
toast.style.opacity = '0';
setTimeout(() => {
toast.remove();
}, 300);
}, 5000);
}
/**
* Track analytics event
*/
trackEvent(eventName, data = {}) {
if (!CONFIG.ANALYTICS.ENABLED) {
return;
}
// Placeholder for analytics tracking
// Integrate with Google Analytics, Mixpanel, etc.
if (CONFIG.DEBUG) {
console.log('📊 Analytics Event:', eventName, data);
}
// Example: Google Analytics
if (typeof gtag !== 'undefined') {
gtag('event', eventName, data);
}
}
}
// Initialize the application
let app;
function exposeAppForDebug() {
if (CONFIG.DEBUG) {
window.ugcApp = app;
}
}
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', () => {
app = new UGCVideoGenerator();
exposeAppForDebug();
});
} else {
app = new UGCVideoGenerator();
exposeAppForDebug();
}