-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathvideo-analyzer.js
More file actions
1573 lines (1359 loc) · 61.3 KB
/
Copy pathvideo-analyzer.js
File metadata and controls
1573 lines (1359 loc) · 61.3 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
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Advanced Video Analyzer Module
* Comprehensive video analysis: watch, listen, scan, read
* Provides detailed creative diagnostics, strategy, and insights
* Version: 2.4.0 - January 18, 2026
*
* v2.4.0 MAJOR UPDATE - Real Frame Extraction:
* - Uses VideoFrameExtractor to download/capture actual video frames
* - Sends frame images (not just URLs) to AI for real visual analysis
* - Handles social media platform restrictions with clear messaging
* - Prompts for file upload when URL extraction fails
* - Stores analysis screenshots in Cloudinary
*
* This module now integrates with the Advanced Video Creative Intelligence System v2.0
* for comprehensive paid media analysis including:
* - Hook & Attention Mechanics (0-3 second analysis)
* - Retention Curve Prediction
* - Skip-Ad Likelihood (YouTube)
* - Sound-Off Effectiveness
* - Funnel Position Classification
* - Audience Intelligence
* - Platform Performance Prediction
* - CTA Analysis
* - Narrative Architecture
* - Emotional Journey Mapping
* - Compliance & Accessibility
* - Strategic Recommendations
*/
(function() {
'use strict';
const VERSION = '2.4.0';
// ============================================
// VIDEO ANALYZER CLASS
// ============================================
class VideoAnalyzer {
constructor() {
this.analysisHistory = [];
this.selectedModel = null; // User can select model before analysis
this.loadHistory();
console.log(`[VideoAnalyzer] Module loaded v${VERSION}`);
}
// Set the AI model to use for analysis
setModel(modelId) {
this.selectedModel = modelId;
console.log(`[VideoAnalyzer] Model set to: ${modelId}`);
}
// Get the currently selected model
getModel() {
return this.selectedModel || window.AIModelSelector?.selectedModel || 'gemini-3-flash-preview';
}
loadHistory() {
try {
this.analysisHistory = JSON.parse(localStorage.getItem('cav_video_analyses') || '[]');
} catch (e) {
this.analysisHistory = [];
}
}
saveHistory() {
localStorage.setItem('cav_video_analyses', JSON.stringify(this.analysisHistory.slice(0, 50)));
}
// ============================================
// MAIN ANALYSIS FUNCTION
// ============================================
async analyzeVideo(videoSource, options = {}) {
const isFile = videoSource instanceof File;
const videoUrl = isFile ? `file://${videoSource.name}` : videoSource;
console.log('[VideoAnalyzer] Starting comprehensive analysis:', isFile ? videoSource.name : videoUrl);
console.log('[VideoAnalyzer] Options:', options);
// Use AdvancedVideoAnalyzer v2 if available (comprehensive paid media intelligence)
if (window.AdvancedVideoAnalyzer && window.AdvancedVideoAnalyzer !== this) {
console.log('[VideoAnalyzer] Delegating to AdvancedVideoAnalyzer v2.0');
if (this.selectedModel) {
window.AdvancedVideoAnalyzer.setModel(this.selectedModel);
}
const result = await window.AdvancedVideoAnalyzer.analyzeVideo(videoSource, options);
this.analysisHistory = window.AdvancedVideoAnalyzer.analysisHistory;
return result;
}
// Validate input
if (!isFile && (!videoUrl || !videoUrl.startsWith('http'))) {
throw new Error('Please enter a valid video URL starting with http:// or https://');
}
// Check for API key upfront
const apiKey = this.getAPIKey();
if (!apiKey) {
throw new Error('No Gemini API key configured. Please go to Settings > API Keys and add your Gemini API key to use video analysis.');
}
const analysisId = crypto.randomUUID();
const analysis = {
id: analysisId,
url: videoUrl,
timestamp: new Date().toISOString(),
status: 'analyzing',
platform: isFile ? 'upload' : this.detectPlatform(videoUrl),
frames: [],
frameExtraction: null,
metadata: {},
visualAnalysis: {},
audioAnalysis: {},
contentAnalysis: {},
sentimentAnalysis: {},
experienceAnalysis: {},
strategicInsights: {},
creativeScore: {},
recommendations: []
};
console.log('[VideoAnalyzer] Detected platform:', analysis.platform);
try {
// Step 0: Extract frames from video (NEW - critical step)
this.updateProgress('Extracting video frames...', 5);
if (window.VideoFrameExtractor) {
const frameResult = await window.VideoFrameExtractor.extractFrames(
isFile ? videoSource : videoUrl,
{
maxFrames: 8,
progressCallback: (msg, pct) => this.updateProgress(msg, 5 + (pct * 0.15))
}
);
analysis.frameExtraction = frameResult;
if (frameResult.success) {
analysis.frames = frameResult.frames;
analysis.metadata = {
...analysis.metadata,
...(frameResult.metadata || {}),
...(frameResult.metadata?.raw || {})
};
console.log(`[VideoAnalyzer] Extracted ${frameResult.frames.length} frames`);
} else {
console.warn('[VideoAnalyzer] Frame extraction limited:', frameResult.message);
// Check if we should prompt for upload
if (frameResult.suggestUpload) {
analysis.uploadPrompt = {
show: true,
reason: frameResult.message || `${this.getPlatformName(analysis.platform)} restricts automated video access.`,
tip: 'Download the video and upload it directly for complete frame-by-frame analysis.'
};
}
// Use partial data if available
if (frameResult.partial && frameResult.frames?.length > 0) {
analysis.frames = frameResult.frames;
}
}
} else {
console.warn('[VideoAnalyzer] VideoFrameExtractor not available');
}
// Step 1: Extract video metadata
this.updateProgress('Extracting video metadata...', 20);
const additionalMetadata = await this.extractMetadata(videoUrl);
analysis.metadata = { ...analysis.metadata, ...additionalMetadata };
console.log('[VideoAnalyzer] Metadata extracted:', analysis.metadata);
// Step 2: Visual frame analysis (now with actual frames!)
this.updateProgress('Analyzing visual elements & composition...', 30);
analysis.visualAnalysis = await this.analyzeVisuals(videoUrl, analysis.metadata, analysis.frames);
console.log('[VideoAnalyzer] Visual analysis complete');
// Step 3: Audio/transcript analysis
this.updateProgress('Analyzing audio, music & voiceover...', 40);
analysis.audioAnalysis = await this.analyzeAudio(videoUrl, analysis.metadata);
console.log('[VideoAnalyzer] Audio analysis complete');
// Step 4: Content and messaging analysis
this.updateProgress('Analyzing messaging & value proposition...', 55);
analysis.contentAnalysis = await this.analyzeContent(analysis);
console.log('[VideoAnalyzer] Content analysis complete');
// Step 5: Sentiment analysis
this.updateProgress('Evaluating emotional impact & sentiment...', 70);
analysis.sentimentAnalysis = await this.analyzeSentiment(analysis);
console.log('[VideoAnalyzer] Sentiment analysis complete');
// Step 6: Experience/UX analysis
this.updateProgress('Assessing viewer experience & flow...', 80);
analysis.experienceAnalysis = await this.analyzeExperience(analysis);
console.log('[VideoAnalyzer] Experience analysis complete');
// Step 7: Strategic insights
this.updateProgress('Generating strategic recommendations...', 90);
analysis.strategicInsights = await this.generateStrategicInsights(analysis);
console.log('[VideoAnalyzer] Strategic insights complete');
// Step 8: Final scoring and recommendations
this.updateProgress('Calculating scores & finalizing...', 95);
analysis.creativeScore = this.calculateCreativeScore(analysis);
analysis.recommendations = this.generateRecommendations(analysis);
console.log('[VideoAnalyzer] Scoring complete:', analysis.creativeScore);
analysis.status = 'complete';
this.updateProgress('Analysis complete!', 100);
// Save to history
this.analysisHistory.unshift(analysis);
this.saveHistory();
console.log('[VideoAnalyzer] Saved to history');
// Sync to Supabase
if (window.CAVSupabase?.saveUrlAnalysis) {
try {
await window.CAVSupabase.saveUrlAnalysis({
uuid: analysis.id,
url: videoUrl,
analysis_type: 'video',
results: analysis
});
console.log('[VideoAnalyzer] Synced to Supabase');
} catch (e) {
console.warn('[VideoAnalyzer] Supabase sync failed:', e);
}
}
return analysis;
} catch (error) {
console.error('[VideoAnalyzer] Analysis failed:', error);
analysis.status = 'error';
analysis.error = error.message || 'Unknown error occurred';
// Still save failed analysis for debugging
this.analysisHistory.unshift(analysis);
this.saveHistory();
return analysis;
}
}
// ============================================
// PLATFORM DETECTION
// ============================================
detectPlatform(url) {
const platforms = {
youtube: /youtube\.com|youtu\.be/i,
vimeo: /vimeo\.com/i,
tiktok: /tiktok\.com/i,
instagram: /instagram\.com/i,
facebook: /facebook\.com|fb\.watch/i,
twitter: /twitter\.com|x\.com/i,
linkedin: /linkedin\.com/i,
loom: /loom\.com/i,
wistia: /wistia\.com/i,
veed: /veed\.io/i,
direct: /\.(mp4|webm|mov|avi)$/i
};
for (const [platform, regex] of Object.entries(platforms)) {
if (regex.test(url)) return platform;
}
return 'unknown';
}
// ============================================
// METADATA EXTRACTION
// ============================================
async extractMetadata(url) {
const platform = this.detectPlatform(url);
// Try to get metadata via API or scraping
let metadata = {
title: '',
description: '',
duration: 0,
thumbnail: '',
creator: '',
uploadDate: '',
views: 0,
likes: 0,
comments: 0,
platform: platform
};
// For YouTube, extract video ID and fetch metadata
if (platform === 'youtube') {
const videoId = this.extractYouTubeId(url);
if (videoId) {
metadata.videoId = videoId;
metadata.embedUrl = `https://www.youtube.com/embed/${videoId}`;
metadata.thumbnail = `https://img.youtube.com/vi/${videoId}/maxresdefault.jpg`;
}
}
return metadata;
}
extractYouTubeId(url) {
const patterns = [
/(?:youtube\.com\/watch\?v=|youtu\.be\/|youtube\.com\/embed\/)([^&\?\/]+)/,
/youtube\.com\/shorts\/([^&\?\/]+)/
];
for (const pattern of patterns) {
const match = url.match(pattern);
if (match) return match[1];
}
return null;
}
getPlatformName(platform) {
const names = {
youtube: 'YouTube',
instagram: 'Instagram',
tiktok: 'TikTok',
facebook: 'Facebook',
twitter: 'X (Twitter)',
vimeo: 'Vimeo',
linkedin: 'LinkedIn',
upload: 'Uploaded Video',
direct: 'Direct Video'
};
return names[platform] || platform;
}
// ============================================
// VISUAL ANALYSIS (using AI with actual frames)
// ============================================
async analyzeVisuals(url, metadata, frames = []) {
const apiKey = this.getAPIKey();
if (!apiKey) {
return this.getPlaceholderVisualAnalysis();
}
// Build frame context for AI
const frameContext = frames.length > 0
? `\n\nI have extracted ${frames.length} key frames from this video at these timestamps: ${frames.map(f => f.label || `${f.timestamp}s`).join(', ')}.`
: '';
// If we have frames with data URLs, we'll send them as images
const hasRealFrames = frames.some(f => f.dataUrl || f.url);
const prompt = `You are an expert video creative analyst. Analyze this video for visual creative effectiveness.
Video URL: ${url}
Platform: ${metadata.platform}
${metadata.title ? `Title: ${metadata.title}` : ''}
${metadata.thumbnail ? `Thumbnail: ${metadata.thumbnail}` : ''}
${frameContext}
${hasRealFrames ? 'I am providing actual video frames for analysis. Analyze the ACTUAL visual content you can see.' : 'Note: I could not extract video frames due to platform restrictions. Provide analysis based on available metadata and typical patterns for this platform.'}
Provide a comprehensive VISUAL analysis including:
1. **Opening Hook** (first 3 seconds):
- Visual impact score (0-100)
- What grabs attention
- Brand visibility
- Thumb-stop potential
2. **Visual Storytelling**:
- Story arc clarity (0-100)
- Scene transitions quality
- Visual hierarchy
- Pacing effectiveness
3. **Brand Elements**:
- Logo placement and visibility
- Brand colors usage
- Typography consistency
- Brand recognition score (0-100)
4. **Production Quality**:
- Video resolution/quality
- Lighting assessment
- Color grading
- Professional polish score (0-100)
5. **Composition**:
- Rule of thirds usage
- Subject framing
- Background effectiveness
- Visual clutter assessment
6. **Text/Graphics**:
- Text readability
- Graphics quality
- Animation smoothness
- Mobile optimization
7. **Platform Optimization**:
- Aspect ratio appropriateness
- Duration appropriateness
- Platform-specific features used
- Optimization score (0-100)
Return ONLY valid JSON:
{
"openingHook": {
"impactScore": 75,
"attentionGrabber": "Description of what grabs attention",
"brandVisibility": "How visible is the brand",
"thumbStopPotential": 80
},
"visualStorytelling": {
"storyArcClarity": 70,
"transitions": "Quality assessment",
"visualHierarchy": "Assessment",
"pacingScore": 75
},
"brandElements": {
"logoPlacement": "Assessment",
"colorUsage": "Assessment",
"typographyConsistency": "Assessment",
"brandRecognitionScore": 65
},
"productionQuality": {
"resolution": "HD/4K/etc",
"lighting": "Assessment",
"colorGrading": "Assessment",
"polishScore": 80
},
"composition": {
"ruleOfThirds": "Assessment",
"subjectFraming": "Assessment",
"backgroundEffectiveness": "Assessment",
"visualClutter": "Low/Medium/High"
},
"textGraphics": {
"textReadability": "Assessment",
"graphicsQuality": "Assessment",
"animationSmoothness": "Assessment",
"mobileOptimized": true
},
"platformOptimization": {
"aspectRatio": "16:9/9:16/1:1",
"durationAppropriate": true,
"platformFeaturesUsed": ["Feature 1", "Feature 2"],
"optimizationScore": 70
},
"overallVisualScore": 75,
"topVisualStrengths": ["Strength 1", "Strength 2", "Strength 3"],
"visualWeaknesses": ["Weakness 1", "Weakness 2"]
}`;
return await this.callAI(prompt);
}
// ============================================
// AUDIO ANALYSIS
// ============================================
async analyzeAudio(url, metadata) {
const apiKey = this.getAPIKey();
if (!apiKey) {
return this.getPlaceholderAudioAnalysis();
}
const prompt = `You are an expert audio/video analyst. Analyze the audio elements of this video creative.
Video URL: ${url}
Platform: ${metadata.platform}
Provide a comprehensive AUDIO analysis including:
1. **Voice/Narration**:
- Voice presence (yes/no)
- Voice quality assessment
- Tone and delivery style
- Clarity and intelligibility (0-100)
- Emotional resonance (0-100)
2. **Music/Sound Design**:
- Music presence and style
- Music-mood alignment
- Sound effects usage
- Audio branding elements
- Music licensing concern level
3. **Audio Technical Quality**:
- Overall audio quality
- Volume consistency
- Background noise level
- Professional mixing score (0-100)
4. **Messaging Through Audio**:
- Key messages delivered via audio
- Call-to-action clarity in audio
- Brand mention frequency
- Script effectiveness (0-100)
5. **Emotional Audio Journey**:
- Opening audio hook
- Emotional arc through audio
- Closing audio impact
- Memorability score (0-100)
6. **Accessibility**:
- Caption/subtitle readiness
- Audio-only comprehension
- Multi-language potential
Return ONLY valid JSON:
{
"voiceNarration": {
"present": true,
"quality": "Professional/Amateur/None",
"tone": "Energetic/Calm/Professional/Casual",
"clarity": 85,
"emotionalResonance": 70
},
"musicSoundDesign": {
"musicPresent": true,
"musicStyle": "Upbeat pop/Corporate/Cinematic/etc",
"moodAlignment": "Strong/Moderate/Weak",
"soundEffects": "Effective/Minimal/Overused",
"audioBranding": "Present/Absent",
"licensingRisk": "Low/Medium/High"
},
"technicalQuality": {
"overallQuality": "Excellent/Good/Average/Poor",
"volumeConsistency": "Consistent/Variable",
"backgroundNoise": "None/Minimal/Noticeable",
"mixingScore": 80
},
"messaging": {
"keyMessages": ["Message 1", "Message 2"],
"ctaClarity": 75,
"brandMentions": 2,
"scriptEffectiveness": 70
},
"emotionalJourney": {
"openingHook": "Description",
"emotionalArc": "Building/Flat/Declining",
"closingImpact": "Strong/Moderate/Weak",
"memorabilityScore": 65
},
"accessibility": {
"captionReady": true,
"audioOnlyComprehension": 60,
"multiLanguagePotential": "High/Medium/Low"
},
"overallAudioScore": 75,
"topAudioStrengths": ["Strength 1", "Strength 2"],
"audioWeaknesses": ["Weakness 1", "Weakness 2"]
}`;
return await this.callAI(prompt);
}
// ============================================
// CONTENT ANALYSIS
// ============================================
async analyzeContent(analysis) {
const apiKey = this.getAPIKey();
if (!apiKey) {
return this.getPlaceholderContentAnalysis();
}
const prompt = `You are an expert content strategist. Analyze the content and messaging of this video.
Video URL: ${analysis.url}
Platform: ${analysis.platform}
Visual Analysis Summary: ${JSON.stringify(analysis.visualAnalysis?.overallVisualScore || 'N/A')}
Audio Analysis Summary: ${JSON.stringify(analysis.audioAnalysis?.overallAudioScore || 'N/A')}
Provide comprehensive CONTENT analysis:
1. **Message Architecture**:
- Primary message/value proposition
- Supporting messages
- Proof points/evidence
- Message clarity score (0-100)
2. **Target Audience**:
- Primary audience identification
- Demographics implied
- Psychographics implied
- Audience relevance score (0-100)
3. **Value Proposition**:
- Core benefit communicated
- Differentiation from competitors
- Urgency/scarcity elements
- Compelling factor score (0-100)
4. **Storytelling Structure**:
- Story type (Problem-Solution/Testimonial/Demo/etc)
- Narrative arc
- Emotional triggers used
- Story effectiveness (0-100)
5. **Call-to-Action**:
- CTA presence and clarity
- CTA type (Click/Buy/Learn/Sign up)
- CTA timing
- CTA effectiveness (0-100)
6. **Content Funnel Position**:
- Awareness/Consideration/Decision
- Content goal identification
- Funnel alignment score (0-100)
Return ONLY valid JSON:
{
"messageArchitecture": {
"primaryMessage": "Main value proposition",
"supportingMessages": ["Message 1", "Message 2"],
"proofPoints": ["Proof 1", "Proof 2"],
"clarityScore": 75
},
"targetAudience": {
"primaryAudience": "Description",
"demographics": "Age, gender, location indicators",
"psychographics": "Interests, values, lifestyle",
"relevanceScore": 80
},
"valueProposition": {
"coreBenefit": "Main benefit",
"differentiation": "What sets it apart",
"urgencyElements": "Scarcity/time elements if any",
"compellingScore": 70
},
"storytelling": {
"storyType": "Problem-Solution/Testimonial/Demo/Lifestyle",
"narrativeArc": "Beginning-Middle-End assessment",
"emotionalTriggers": ["Trigger 1", "Trigger 2"],
"effectivenessScore": 75
},
"callToAction": {
"present": true,
"ctaText": "The actual CTA",
"ctaType": "Click/Buy/Learn/Sign up/etc",
"timing": "When in video",
"effectivenessScore": 65
},
"funnelPosition": {
"stage": "Awareness/Consideration/Decision",
"contentGoal": "Primary goal",
"alignmentScore": 70
},
"overallContentScore": 75,
"contentStrengths": ["Strength 1", "Strength 2"],
"contentWeaknesses": ["Weakness 1", "Weakness 2"]
}`;
return await this.callAI(prompt);
}
// ============================================
// SENTIMENT ANALYSIS
// ============================================
async analyzeSentiment(analysis) {
const apiKey = this.getAPIKey();
if (!apiKey) {
return this.getPlaceholderSentimentAnalysis();
}
const prompt = `You are an expert in emotional and sentiment analysis. Analyze the emotional impact of this video.
Video URL: ${analysis.url}
Platform: ${analysis.platform}
Content Summary: ${analysis.contentAnalysis?.messageArchitecture?.primaryMessage || 'N/A'}
Provide comprehensive SENTIMENT and EMOTIONAL analysis:
1. **Overall Sentiment**:
- Dominant sentiment (Positive/Negative/Neutral)
- Sentiment intensity (0-100)
- Sentiment consistency throughout
2. **Emotional Mapping**:
- Primary emotions evoked
- Emotional journey timeline
- Peak emotional moments
- Emotional authenticity score (0-100)
3. **Trust Signals**:
- Credibility indicators
- Authenticity perception
- Trust-building elements
- Trust score (0-100)
4. **Engagement Triggers**:
- Curiosity triggers
- FOMO elements
- Social proof usage
- Engagement potential (0-100)
5. **Brand Sentiment**:
- Brand perception created
- Brand personality traits conveyed
- Brand affinity potential (0-100)
6. **Viewer Response Prediction**:
- Likely positive reactions
- Potential negative reactions
- Viral potential (0-100)
- Share likelihood (0-100)
Return ONLY valid JSON:
{
"overallSentiment": {
"dominant": "Positive/Negative/Neutral",
"intensity": 75,
"consistency": "Consistent/Variable/Contradictory"
},
"emotionalMapping": {
"primaryEmotions": ["Excitement", "Trust", "Curiosity"],
"emotionalJourney": "Description of emotional arc",
"peakMoments": ["Moment 1 description", "Moment 2 description"],
"authenticityScore": 70
},
"trustSignals": {
"credibilityIndicators": ["Indicator 1", "Indicator 2"],
"authenticityPerception": "High/Medium/Low",
"trustElements": ["Element 1", "Element 2"],
"trustScore": 75
},
"engagementTriggers": {
"curiosityTriggers": ["Trigger 1", "Trigger 2"],
"fomoElements": "Present/Absent",
"socialProof": "Strong/Moderate/Weak/None",
"engagementPotential": 70
},
"brandSentiment": {
"perception": "Premium/Friendly/Professional/Innovative/etc",
"personalityTraits": ["Trait 1", "Trait 2", "Trait 3"],
"affinityPotential": 65
},
"viewerResponse": {
"positiveReactions": ["Likely reaction 1", "Likely reaction 2"],
"negativeReactions": ["Potential issue 1", "Potential issue 2"],
"viralPotential": 50,
"shareLikelihood": 55
},
"overallSentimentScore": 72
}`;
return await this.callAI(prompt);
}
// ============================================
// EXPERIENCE ANALYSIS
// ============================================
async analyzeExperience(analysis) {
const apiKey = this.getAPIKey();
if (!apiKey) {
return this.getPlaceholderExperienceAnalysis();
}
const prompt = `You are a UX expert specializing in video content. Analyze the viewer experience of this video.
Video URL: ${analysis.url}
Platform: ${analysis.platform}
Duration: ${analysis.metadata?.duration || 'Unknown'}
Provide comprehensive VIEWER EXPERIENCE analysis:
1. **First Impression** (0-3 seconds):
- Hook effectiveness
- Clarity of purpose
- Brand recognition
- First impression score (0-100)
2. **Viewing Flow**:
- Pacing assessment
- Information density
- Cognitive load
- Flow score (0-100)
3. **Retention Factors**:
- Drop-off risk points
- Re-engagement hooks
- Pattern interrupt usage
- Retention prediction (0-100)
4. **Accessibility**:
- Readability of text
- Color contrast
- Audio dependency
- Accessibility score (0-100)
5. **Platform Experience**:
- Mobile viewing experience
- Sound-off comprehension
- Autoplay effectiveness
- Platform fit score (0-100)
6. **Post-View Impact**:
- Memorability assessment
- Action likelihood
- Repeat view potential
- Impact score (0-100)
7. **Pain Points**:
- Confusion points
- Friction elements
- Improvement opportunities
Return ONLY valid JSON:
{
"firstImpression": {
"hookEffectiveness": 75,
"purposeClarity": "Clear/Unclear/Mixed",
"brandRecognition": "Immediate/Delayed/Absent",
"score": 70
},
"viewingFlow": {
"pacing": "Too fast/Just right/Too slow",
"informationDensity": "Heavy/Balanced/Light",
"cognitiveLoad": "High/Medium/Low",
"flowScore": 75
},
"retentionFactors": {
"dropOffRisks": ["Risk point 1", "Risk point 2"],
"reEngagementHooks": ["Hook 1", "Hook 2"],
"patternInterrupts": "Used effectively/Minimal/Overused",
"retentionPrediction": 65
},
"accessibility": {
"textReadability": "Good/Fair/Poor",
"colorContrast": "Sufficient/Insufficient",
"audioDependency": "High/Medium/Low",
"accessibilityScore": 70
},
"platformExperience": {
"mobileViewing": "Optimized/Acceptable/Poor",
"soundOffComprehension": 60,
"autoplayEffectiveness": "Engaging/Neutral/Disengaging",
"platformFitScore": 75
},
"postViewImpact": {
"memorability": "High/Medium/Low",
"actionLikelihood": 65,
"repeatViewPotential": 40,
"impactScore": 70
},
"painPoints": {
"confusionPoints": ["Point 1", "Point 2"],
"frictionElements": ["Element 1", "Element 2"],
"improvements": ["Improvement 1", "Improvement 2", "Improvement 3"]
},
"overallExperienceScore": 72
}`;
return await this.callAI(prompt);
}
// ============================================
// STRATEGIC INSIGHTS
// ============================================
async generateStrategicInsights(analysis) {
const apiKey = this.getAPIKey();
if (!apiKey) {
return this.getPlaceholderStrategicInsights();
}
const prompt = `You are a senior creative strategist. Based on this comprehensive video analysis, provide strategic insights and recommendations.
Video URL: ${analysis.url}
Platform: ${analysis.platform}
Visual Score: ${analysis.visualAnalysis?.overallVisualScore || 'N/A'}
Audio Score: ${analysis.audioAnalysis?.overallAudioScore || 'N/A'}
Content Score: ${analysis.contentAnalysis?.overallContentScore || 'N/A'}
Sentiment Score: ${analysis.sentimentAnalysis?.overallSentimentScore || 'N/A'}
Experience Score: ${analysis.experienceAnalysis?.overallExperienceScore || 'N/A'}
Provide STRATEGIC INSIGHTS:
1. **Performance Prediction**:
- Expected CTR range
- Expected view-through rate
- Expected engagement rate
- Conversion potential
2. **Competitive Position**:
- Industry benchmark comparison
- Unique differentiators
- Competitive gaps
- Market positioning
3. **Optimization Opportunities**:
- Quick wins (easy fixes)
- Medium effort improvements
- Major overhaul suggestions
- Priority ranking
4. **A/B Testing Recommendations**:
- Elements to test
- Test hypotheses
- Expected impact
5. **Platform Strategy**:
- Best platforms for this content
- Platforms to avoid
- Platform-specific adaptations needed
6. **Audience Expansion**:
- Additional audiences to target
- Audience segments to avoid
- Lookalike potential
7. **Creative Iterations**:
- Variation ideas
- Format adaptations
- Seasonal/timely opportunities
Return ONLY valid JSON:
{
"performancePrediction": {
"expectedCTR": "1.5-2.5%",
"viewThroughRate": "25-35%",
"engagementRate": "3-5%",
"conversionPotential": "Medium/High/Low"
},
"competitivePosition": {
"benchmarkComparison": "Above/At/Below average",
"differentiators": ["Unique element 1", "Unique element 2"],
"gaps": ["Gap 1", "Gap 2"],
"positioning": "Market position assessment"
},
"optimizationOpportunities": {
"quickWins": [
{"fix": "Fix description", "impact": "High/Medium/Low", "effort": "Low"}
],
"mediumEffort": [
{"improvement": "Improvement description", "impact": "High/Medium/Low", "effort": "Medium"}
],
"majorOverhaul": [
{"suggestion": "Suggestion description", "impact": "High", "effort": "High"}
]
},
"abTestingRecommendations": [
{
"element": "Element to test",
"hypothesis": "Testing hypothesis",
"expectedImpact": "+10-20% on metric"
}
],
"platformStrategy": {
"bestPlatforms": ["Platform 1", "Platform 2"],
"avoid": ["Platform to avoid"],
"adaptations": {
"platform1": "Adaptation needed",
"platform2": "Adaptation needed"
}
},
"audienceExpansion": {
"additionalAudiences": ["Audience 1", "Audience 2"],
"avoid": ["Audience to avoid"],
"lookalikePotential": "High/Medium/Low"
},
"creativeIterations": {
"variations": ["Variation idea 1", "Variation idea 2"],
"formatAdaptations": ["Short form version", "Story format", "etc"],
"seasonalOpportunities": ["Opportunity 1", "Opportunity 2"]
}
}`;
return await this.callAI(prompt);
}
// ============================================
// SCORING
// ============================================
calculateCreativeScore(analysis) {
const weights = {
visual: 0.25,
audio: 0.20,
content: 0.25,
sentiment: 0.15,
experience: 0.15
};
const scores = {
visual: analysis.visualAnalysis?.overallVisualScore || 50,
audio: analysis.audioAnalysis?.overallAudioScore || 50,
content: analysis.contentAnalysis?.overallContentScore || 50,
sentiment: analysis.sentimentAnalysis?.overallSentimentScore || 50,
experience: analysis.experienceAnalysis?.overallExperienceScore || 50
};
const overallScore = Math.round(
scores.visual * weights.visual +