-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathanalyze-module.js
More file actions
2573 lines (2257 loc) · 132 KB
/
Copy pathanalyze-module.js
File metadata and controls
2573 lines (2257 loc) · 132 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
/**
* Analyze Module - Creative Asset Validator v3.0.7
* Creative Intelligence Module with Hook Analysis, CTA Audit, Brand Compliance,
* Audio Strategy, Thumb-Stop Scoring, and Performance Prediction
*
* v3.0.7 FIXES:
* - Persist analysis results to localStorage
* - Save analysis history that persists across sessions
* - Link analysis to CRM companies
* - Fix blank image/screenshot issue
* - Auto-detect brand and create CRM entry
*/
(function() {
'use strict';
const ANALYZE_VERSION = '4.0.0'; // January 17, 2026 - Multi-service AI integration
// User-specific storage key prefix - ROBUST multi-source check
function getAnalyzeStoragePrefix() {
try {
// Try multiple session sources
let email = null;
// 1. Check window.cavUserSession
if (window.cavUserSession?.email) {
email = window.cavUserSession.email;
}
// 2. Check CAVSecurity SecureSessionManager
if (!email) {
const secureSession = window.CAVSecurity?.SecureSessionManager?.getSession?.();
if (secureSession?.email) email = secureSession.email;
}
// 3. Check localStorage cav_user_session
if (!email) {
try {
const session = JSON.parse(localStorage.getItem('cav_user_session') || 'null');
if (session?.email) email = session.email;
} catch (e) {}
}
// 4. Check localStorage cav_secure_session_v3
if (!email) {
try {
const secureV3 = JSON.parse(localStorage.getItem('cav_secure_session_v3') || 'null');
if (secureV3?.email) email = secureV3.email;
} catch (e) {}
}
// 5. Check localStorage cav_last_user_email
if (!email) {
const lastEmail = localStorage.getItem('cav_last_user_email');
if (lastEmail && lastEmail !== 'anonymous') email = lastEmail;
}
if (email) {
const userKey = email.toLowerCase().replace(/[^a-z0-9]/g, '_');
return `cav_analyze_${userKey}_`;
}
} catch (e) {
console.warn('[Analyze] Error getting user prefix:', e);
}
return 'cav_analyze_anonymous_';
}
// Dynamic storage keys - user-specific
const STORAGE_KEYS = {
get ANALYSIS_HISTORY() { return `${getAnalyzeStoragePrefix()}history`; },
get CURRENT_ANALYSIS() { return `${getAnalyzeStoragePrefix()}current`; },
get ANALYSIS_CACHE() { return `${getAnalyzeStoragePrefix()}cache`; },
};
// ============================================
// ANALYZE MODULE CLASS
// ============================================
class AnalyzeModule {
constructor() {
this.currentAsset = null;
this.currentAnalysis = this.loadCurrentAnalysis();
this.analysisHistory = this.loadAnalysisHistory();
console.log(`[Analyze] Initialized v${ANALYZE_VERSION} - ${this.analysisHistory.length} analyses in history`);
}
// Load current analysis from storage
loadCurrentAnalysis() {
try {
return JSON.parse(localStorage.getItem(STORAGE_KEYS.CURRENT_ANALYSIS) || 'null');
} catch {
return null;
}
}
// Save current analysis to storage
saveCurrentAnalysis(analysis) {
try {
localStorage.setItem(STORAGE_KEYS.CURRENT_ANALYSIS, JSON.stringify(analysis));
} catch (e) {
console.warn('[Analyze] Failed to save current analysis:', e);
}
}
// Load analysis history from storage
loadAnalysisHistory() {
try {
return JSON.parse(localStorage.getItem(STORAGE_KEYS.ANALYSIS_HISTORY) || '[]');
} catch {
return [];
}
}
// Save analysis to history
saveAnalysisToHistory(analysis) {
// Remove any existing analysis for this asset
this.analysisHistory = this.analysisHistory.filter(a => a.assetId !== analysis.assetId);
// Add new analysis at the beginning
this.analysisHistory.unshift(analysis);
// Keep last 100 analyses
if (this.analysisHistory.length > 100) {
this.analysisHistory = this.analysisHistory.slice(0, 100);
}
// Save to localStorage
try {
localStorage.setItem(STORAGE_KEYS.ANALYSIS_HISTORY, JSON.stringify(this.analysisHistory));
// Also save to unified storage for cross-device sync
if (window.UnifiedStorage) {
window.UnifiedStorage.saveCreativeAnalysis({
...analysis,
id: analysis.id || analysis.assetId || `analysis_${Date.now()}`
}).catch(e => console.warn('[Analyze] Unified storage save failed:', e));
}
} catch (e) {
console.warn('[Analyze] Failed to save analysis history:', e);
}
}
// Get analysis for an asset from cache
getAnalysisForAsset(assetId) {
return this.analysisHistory.find(a => a.assetId === assetId);
}
// Clear analysis history
clearAnalysisHistory() {
this.analysisHistory = [];
localStorage.removeItem(STORAGE_KEYS.ANALYSIS_HISTORY);
}
// ============================================
// HOOK ANALYSIS ENGINE
// ============================================
async analyzeHook(asset, imageBase64) {
const prompt = `Analyze this creative asset for its "hook" or scroll-stopping potential in paid media advertising.
Evaluate and score (0-100) each dimension:
1. **Visual Disruption** (weight 35%): Pattern interrupt elements, unexpected visuals, contrast with typical feed content
2. **Motion Quality** (weight 20%): For images, assess implied motion. First frame composition and energy.
3. **Emotional Trigger** (weight 25%): Curiosity, urgency, surprise, relatability, fear of missing out
4. **Text Hook** (weight 10%): First visible text impact, headline strength, font prominence
5. **Audio Hook** (weight 10%): For video, assess opening sound. For images, mark as N/A.
Also identify:
- Face detected: Is there a human face in the first view? (yes/no)
- Eye contact: Does the face make eye contact with viewer? (yes/no)
- First frame elements: List 3-5 key visual elements
- Improvement suggestions: 3 specific ways to improve the hook
Return ONLY valid JSON in this exact format:
{
"overallScore": 75,
"visualDisruptionScore": 80,
"motionQualityScore": 70,
"emotionalTriggerScore": 75,
"textHookScore": 65,
"audioHookScore": null,
"faceDetected": true,
"eyeContact": false,
"firstFrameElements": ["product shot", "bold headline", "vibrant colors"],
"improvementSuggestions": ["Add human face for emotional connection", "Increase text contrast", "Add motion blur for energy"],
"confidenceLevel": "high"
}`;
try {
const orchestrator = window.AIOrchestrator;
if (!orchestrator) throw new Error('AI Orchestrator not available');
let result;
if (orchestrator.isProviderAvailable('openai')) {
result = await orchestrator.callOpenAI(prompt, { image: imageBase64 });
} else if (orchestrator.isProviderAvailable('gemini')) {
result = await orchestrator.callGemini(prompt, { image: imageBase64 });
} else {
throw new Error('No vision-capable AI provider available');
}
const analysis = this.parseJSON(result.content);
return window.CAVDataModels.HookAnalysis.create({
assetId: asset.id,
...analysis
});
} catch (error) {
console.error('[Analyze] Hook analysis error:', error);
return window.CAVDataModels.HookAnalysis.create({
assetId: asset.id,
confidenceLevel: 'low',
improvementSuggestions: ['Analysis failed - please try again']
});
}
}
// ============================================
// CTA AUDIT SYSTEM
// ============================================
async analyzeCTA(asset, imageBase64) {
const prompt = `Analyze this creative asset's Call-to-Action (CTA) effectiveness for paid advertising.
Evaluate:
1. **CTA Presence** (25%): Is there a clear CTA? Is it visible without scrolling?
2. **CTA Clarity** (30%): Does it use action verbs? Single clear action? No ambiguity?
3. **CTA Placement** (20%): Location in frame, prominence, visual hierarchy
4. **CTA Urgency** (15%): Time-limited language? Scarcity indicators? Motivation?
5. **Platform Alignment** (10%): Does format match platform best practices?
Classify CTA type:
- "hard": Buy Now, Sign Up, Get Started, Shop Now
- "soft": Learn More, See How, Discover
- "engagement": Comment, Share, Follow, Tag a Friend
- "none": No clear CTA detected
Check platform alignment for: Meta, TikTok, YouTube, LinkedIn, Google Ads
Return ONLY valid JSON:
{
"ctaDetected": true,
"ctaText": "Shop Now",
"ctaType": "hard",
"presenceScore": 85,
"clarityScore": 90,
"placementScore": 75,
"urgencyScore": 60,
"platformAlignmentScore": 80,
"overallEffectiveness": 80,
"platformAlignment": [
{"platform": "Meta", "aligned": true},
{"platform": "TikTok", "aligned": false},
{"platform": "YouTube", "aligned": true},
{"platform": "LinkedIn", "aligned": true},
{"platform": "Google Ads", "aligned": true}
],
"recommendations": ["Add urgency with limited-time offer", "Make CTA button larger", "Use contrasting color for CTA"]
}`;
try {
const orchestrator = window.AIOrchestrator;
if (!orchestrator) throw new Error('AI Orchestrator not available');
let result;
if (orchestrator.isProviderAvailable('openai')) {
result = await orchestrator.callOpenAI(prompt, { image: imageBase64 });
} else if (orchestrator.isProviderAvailable('gemini')) {
result = await orchestrator.callGemini(prompt, { image: imageBase64 });
} else {
throw new Error('No vision-capable AI provider available');
}
const analysis = this.parseJSON(result.content);
return window.CAVDataModels.CTAAnalysis.create({
assetId: asset.id,
...analysis
});
} catch (error) {
console.error('[Analyze] CTA analysis error:', error);
return window.CAVDataModels.CTAAnalysis.create({
assetId: asset.id,
ctaDetected: false,
recommendations: ['Analysis failed - please try again']
});
}
}
// ============================================
// BRAND COMPLIANCE SCANNER
// ============================================
async analyzeBrandCompliance(asset, imageBase64, brandProfile = null) {
// Get default brand profile if not provided
if (!brandProfile && window.CAVSettings) {
brandProfile = window.CAVSettings.manager.getDefaultBrandProfile();
}
const brandContext = brandProfile ? `
Brand Guidelines to Check Against:
- Brand Name: ${brandProfile.name}
- Primary Color: ${brandProfile.colors?.primary || 'Not specified'}
- Secondary Color: ${brandProfile.colors?.secondary || 'Not specified'}
- Accent Color: ${brandProfile.colors?.accent || 'Not specified'}
- Fonts: ${brandProfile.fonts?.join(', ') || 'Not specified'}
- Voice Keywords: ${brandProfile.voiceKeywords?.join(', ') || 'Not specified'}
` : 'No brand profile configured - do general brand analysis.';
const prompt = `Analyze this creative asset for brand compliance and consistency.
${brandContext}
Evaluate:
1. **Logo Presence**: Is a logo visible? Is it the correct version? Proper placement and clear space?
2. **Color Match**: Do the dominant colors match the brand palette? Detect actual hex codes.
3. **Typography**: What fonts are visible? Do they match brand guidelines?
4. **Tone of Voice**: Does any text match the brand voice keywords?
5. **Visual Style**: Is the overall aesthetic consistent with brand identity?
Score each dimension 0-100 and calculate overall compliance.
Return ONLY valid JSON:
{
"overallCompliance": 75,
"logoPresent": true,
"logoCorrectVersion": true,
"logoPlacementValid": true,
"logoScore": 85,
"colorMatch": {
"primary": {"detected": "#FF5733", "expected": "${brandProfile?.colors?.primary || '#000000'}", "match": false},
"secondary": {"detected": "#FFFFFF", "expected": "${brandProfile?.colors?.secondary || '#FFFFFF'}", "match": true},
"accent": {"detected": "#3498DB", "expected": "${brandProfile?.colors?.accent || '#0066CC'}", "match": false}
},
"colorScore": 60,
"fontsDetected": ["Helvetica", "Arial"],
"fontMatch": false,
"fontScore": 40,
"toneOfVoice": {
"detected": "casual, friendly",
"expected": "${brandProfile?.voiceKeywords?.join(', ') || 'professional'}",
"match": true
},
"toneScore": 80,
"visualStyleMatch": true,
"visualStyleScore": 75,
"issues": ["Primary color doesn't match brand guidelines", "Non-brand font detected"],
"recommendations": ["Update primary color to brand color", "Use approved brand fonts"]
}`;
try {
const orchestrator = window.AIOrchestrator;
if (!orchestrator) throw new Error('AI Orchestrator not available');
let result;
if (orchestrator.isProviderAvailable('openai')) {
result = await orchestrator.callOpenAI(prompt, { image: imageBase64 });
} else if (orchestrator.isProviderAvailable('gemini')) {
result = await orchestrator.callGemini(prompt, { image: imageBase64 });
} else {
throw new Error('No vision-capable AI provider available');
}
const analysis = this.parseJSON(result.content);
return window.CAVDataModels.BrandComplianceResult.create({
assetId: asset.id,
brandProfileId: brandProfile?.id || null,
...analysis
});
} catch (error) {
console.error('[Analyze] Brand compliance error:', error);
return window.CAVDataModels.BrandComplianceResult.create({
assetId: asset.id,
issues: ['Analysis failed - please try again']
});
}
}
// ============================================
// AUDIO STRATEGY ANALYZER (Video Only)
// ============================================
async analyzeAudioStrategy(asset, videoBase64OrUrl = null) {
if (asset.type !== 'video' && !asset.duration) {
return window.CAVDataModels.AudioStrategyResult.create({
assetId: asset.id,
hasAudio: false,
recommendations: ['This analysis is for video assets only']
});
}
const prompt = `Analyze this video's audio strategy for paid media advertising.
Consider that 85% of Facebook video is watched without sound, and different platforms have different audio expectations.
Evaluate:
1. **Sound-Off Viability**: Can the message be understood without audio? Are text overlays sufficient?
2. **Caption Quality**: Are captions present? Readable? Properly timed? Full coverage?
3. **Music Selection**: Is there background music? Does it match the mood? Is it a trending sound?
4. **Voice Over**: Is there voice over? Is it clear? Good pacing? Professional quality?
5. **Sound Effects**: Are there sound effects? Do they enhance or distract?
Provide platform-specific recommendations for:
- TikTok (sound-on critical, trending sounds important)
- Instagram Reels (music integration, voice + music balance)
- Facebook Feed (sound-off optimization mandatory)
- YouTube (full audio experience expected)
- LinkedIn (professional audio, minimal music)
Return ONLY valid JSON:
{
"hasAudio": true,
"soundOffViable": true,
"soundOffScore": 75,
"captionsPresent": true,
"captionQuality": 80,
"captionCoverage": 95,
"musicPresent": true,
"musicMoodMatch": "energetic, upbeat - matches content well",
"isTrendingSound": false,
"voiceOverPresent": true,
"voiceOverClarity": 85,
"soundEffects": ["swoosh transition", "click sound"],
"platformRecommendations": {
"tiktok": "Consider using trending sound for better reach",
"instagram_reels": "Good balance of voice and music",
"facebook_feed": "Sound-off optimization is good with captions",
"youtube": "Audio quality is appropriate",
"linkedin": "May be too energetic for LinkedIn audience"
},
"overallScore": 78,
"recommendations": ["Add trending TikTok sound variant", "Increase caption size", "Add sound wave animation for sound-on engagement"]
}`;
try {
const orchestrator = window.AIOrchestrator;
if (!orchestrator) throw new Error('AI Orchestrator not available');
// For video, we'd ideally extract frames and audio
// For now, use Claude for text-based analysis if we have metadata
let result;
if (orchestrator.isProviderAvailable('claude')) {
const contextPrompt = `Based on a video asset with the following characteristics:
- Duration: ${asset.duration || 'unknown'} seconds
- Has audio track: assumed yes
- Type: promotional video
${prompt}`;
result = await orchestrator.callClaude(contextPrompt);
} else {
throw new Error('Claude not available for audio strategy analysis');
}
const analysis = this.parseJSON(result.content);
return window.CAVDataModels.AudioStrategyResult.create({
assetId: asset.id,
...analysis
});
} catch (error) {
console.error('[Analyze] Audio strategy error:', error);
return window.CAVDataModels.AudioStrategyResult.create({
assetId: asset.id,
recommendations: ['Analysis failed - please try again']
});
}
}
// ============================================
// THUMB-STOP SCORING
// ============================================
async analyzeThumbStop(asset, imageBase64) {
const prompt = `Analyze this creative's "thumb-stop" potential - the likelihood a user will stop scrolling to engage with this content in a social media feed.
Score each factor (0-100):
1. **Visual Salience** (weight 35%):
- Color contrast with typical feed content
- Visual complexity (not too busy, not too simple)
- Focal point clarity
2. **Pattern Interrupt** (weight 25%):
- Deviation from feed norms
- Unexpected elements
- Novelty factor
3. **Emotional Hook** (weight 25%):
- Facial expressions (if faces present)
- Body language cues
- Emotional content triggers
4. **Relevance Signal** (weight 15%):
- Product visibility
- Audience targeting cues
- Context match indicators
Calculate overall thumb-stop score using the weighted formula.
Return ONLY valid JSON:
{
"overallScore": 72,
"visualSalience": 80,
"patternInterrupt": 65,
"emotionalHook": 75,
"relevanceSignal": 60,
"colorContrast": 85,
"visualComplexity": 70,
"focalPointClarity": 78,
"noveltyFactor": 62,
"facialExpressions": "confident smile, engaging",
"bodyLanguage": "open, welcoming posture",
"productVisibility": 75,
"targetingCues": ["young professionals", "tech-savvy", "urban lifestyle"]
}`;
try {
const orchestrator = window.AIOrchestrator;
if (!orchestrator) throw new Error('AI Orchestrator not available');
let result;
if (orchestrator.isProviderAvailable('openai')) {
result = await orchestrator.callOpenAI(prompt, { image: imageBase64 });
} else if (orchestrator.isProviderAvailable('gemini')) {
result = await orchestrator.callGemini(prompt, { image: imageBase64 });
} else {
throw new Error('No vision-capable AI provider available');
}
const analysis = this.parseJSON(result.content);
// Calculate weighted score if not provided
if (!analysis.overallScore && analysis.visualSalience) {
analysis.overallScore = Math.round(
(analysis.visualSalience * 0.35) +
(analysis.patternInterrupt * 0.25) +
(analysis.emotionalHook * 0.25) +
(analysis.relevanceSignal * 0.15)
);
}
return window.CAVDataModels.ThumbStopScore.create({
assetId: asset.id,
...analysis
});
} catch (error) {
console.error('[Analyze] Thumb-stop analysis error:', error);
return window.CAVDataModels.ThumbStopScore.create({
assetId: asset.id
});
}
}
// ============================================
// PERFORMANCE PREDICTION MODEL
// ============================================
async predictPerformance(asset, analysisResults) {
const context = {
asset: {
type: asset.type || 'image',
width: asset.width,
height: asset.height,
aspectRatio: asset.width && asset.height ? (asset.width / asset.height).toFixed(2) : null,
duration: asset.duration
},
hookScore: analysisResults.hookAnalysis?.overallScore || null,
ctaScore: analysisResults.ctaAnalysis?.overallEffectiveness || null,
thumbStopScore: analysisResults.thumbStopScore?.overallScore || null,
brandCompliance: analysisResults.brandCompliance?.overallCompliance || null
};
const prompt = `Based on this creative asset analysis, predict expected performance metrics for paid media campaigns.
Asset Context:
${JSON.stringify(context, null, 2)}
Predict ranges for:
1. **CTR (Click-Through Rate)**: low/expected/high percentages
2. **CPM (Cost Per Mille)**: low/expected/high in USD
3. **Engagement Rate**: low/expected/high percentages
4. **View-Through Rate**: for video, completion rate ranges
5. **Conversion Potential**: high/medium/low relative assessment
Also provide:
- Confidence level: high/medium/low based on data quality
- Key factors influencing predictions
- Calibration notes for user's specific account (if any historical data)
Return ONLY valid JSON:
{
"ctr": {
"low": 0.8,
"expected": 1.2,
"high": 1.8
},
"cpm": {
"low": 5.00,
"expected": 8.50,
"high": 14.00
},
"engagementRate": {
"low": 2.0,
"expected": 3.5,
"high": 5.5
},
"viewThroughRate": null,
"conversionPotential": "medium",
"confidenceFactors": [
"Strong hook score indicates good initial engagement",
"CTA clarity suggests decent click intent",
"Brand compliance may affect quality score"
],
"calibrationData": null
}`;
try {
const orchestrator = window.AIOrchestrator;
if (!orchestrator) throw new Error('AI Orchestrator not available');
let result;
if (orchestrator.isProviderAvailable('claude')) {
result = await orchestrator.callClaude(prompt, { temperature: 0.3 });
} else if (orchestrator.isProviderAvailable('openai')) {
result = await orchestrator.callOpenAI(prompt, { temperature: 0.3 });
} else {
throw new Error('No reasoning AI provider available');
}
const prediction = this.parseJSON(result.content);
return window.CAVDataModels.PerformancePrediction.create({
assetId: asset.id,
...prediction
});
} catch (error) {
console.error('[Analyze] Performance prediction error:', error);
return window.CAVDataModels.PerformancePrediction.create({
assetId: asset.id
});
}
}
// ============================================
// FULL COMPREHENSIVE ANALYSIS
// ============================================
async analyzeComprehensive(asset, imageBase64) {
const startTime = Date.now();
const results = {
assetId: asset.id,
assetFilename: asset.filename,
assetType: asset.type || 'image',
assetDimensions: { width: asset.width, height: asset.height },
analyzedAt: new Date().toISOString(),
hookAnalysis: null,
ctaAnalysis: null,
brandCompliance: null,
audioStrategy: null,
thumbStopScore: null,
performancePrediction: null,
confidence: 'low',
processingTime: 0,
// NEW: CRM linking
detectedBrand: null,
linkedCompanyId: null,
linkedProjectId: null
};
try {
// Run ENHANCED multi-service analysis if available (Google Vision, Cloudinary AI, etc.)
let enhancedData = null;
if (window.EnhancedCreativeAnalysis?.analyze) {
console.log('[Analyze] Running enhanced multi-service analysis...');
try {
enhancedData = await window.EnhancedCreativeAnalysis.analyze(asset, imageBase64);
results.enhancedAnalysis = enhancedData;
console.log('[Analyze] Enhanced analysis complete:', enhancedData?.sources);
} catch (e) {
console.warn('[Analyze] Enhanced analysis unavailable:', e.message);
}
}
// Run visual analyses in parallel
const [hookAnalysis, ctaAnalysis, brandCompliance, thumbStopScore] = await Promise.allSettled([
this.analyzeHook(asset, imageBase64),
this.analyzeCTA(asset, imageBase64),
this.analyzeBrandCompliance(asset, imageBase64, enhancedData),
this.analyzeThumbStop(asset, imageBase64, enhancedData)
]);
results.hookAnalysis = hookAnalysis.status === 'fulfilled' ? hookAnalysis.value : null;
results.ctaAnalysis = ctaAnalysis.status === 'fulfilled' ? ctaAnalysis.value : null;
results.brandCompliance = brandCompliance.status === 'fulfilled' ? brandCompliance.value : null;
results.thumbStopScore = thumbStopScore.status === 'fulfilled' ? thumbStopScore.value : null;
// Merge enhanced data into results if available
if (enhancedData) {
// Add detected objects and labels
results.detectedObjects = enhancedData.objects || [];
results.detectedLabels = enhancedData.labels || [];
results.extractedText = enhancedData.detectedText || '';
results.colorPalette = enhancedData.colorPalette || [];
results.detectedLogos = enhancedData.logos || [];
results.faceData = enhancedData.faceAnalysis || null;
results.tags = enhancedData.tags || [];
// Enhanced scores
if (enhancedData.scores) {
results.enhancedScores = enhancedData.scores;
}
}
// Audio strategy for videos
if (asset.type === 'video' || asset.duration) {
results.audioStrategy = await this.analyzeAudioStrategy(asset);
}
// Performance prediction based on other analyses
results.performancePrediction = await this.predictPerformance(asset, results);
// Calculate confidence
const successCount = [results.hookAnalysis, results.ctaAnalysis, results.thumbStopScore]
.filter(r => r && r.overallScore !== undefined).length;
results.confidence = successCount >= 3 ? 'high' : successCount >= 2 ? 'medium' : 'low';
// AUTO-DETECT BRAND from the creative
const brandInfo = await this.detectBrandFromCreative(asset, imageBase64);
if (brandInfo && brandInfo.brandName && brandInfo.brandName !== 'unknown') {
results.detectedBrand = brandInfo;
// Auto-create/link CRM entry
const crmLink = await this.linkAnalysisToCRM(brandInfo, asset, results);
results.linkedCompanyId = crmLink?.companyId;
results.linkedProjectId = crmLink?.projectId;
}
} catch (error) {
console.error('[Analyze] Comprehensive analysis error:', error);
}
results.processingTime = Date.now() - startTime;
// Store current analysis
this.currentAnalysis = results;
// PERSIST: Save to localStorage and history
this.saveCurrentAnalysis(results);
this.saveAnalysisToHistory(results);
// Also save via data models if available
if (window.CAVDataModels?.Storage) {
window.CAVDataModels.Storage.saveAnalysis(results);
}
console.log(`[Analyze] Analysis complete for ${asset.filename}, confidence: ${results.confidence}`);
if (results.detectedBrand) {
console.log(`[Analyze] Brand detected: ${results.detectedBrand.brandName}`);
}
return results;
}
// Detect brand from creative using AI vision
async detectBrandFromCreative(asset, imageBase64) {
try {
const apiKey = localStorage.getItem('cav_gemini_api_key');
if (!apiKey || !imageBase64) return null;
const cleanBase64 = imageBase64.replace(/^data:image\/[a-z]+;base64,/, '');
const mimeType = imageBase64.match(/^data:(image\/[a-z]+);base64,/)?.[1] || 'image/jpeg';
const prompt = `Analyze this creative asset and identify any brand information.
Identify:
1. **Brand Name**: What company, product, or organization is featured? If it's a sports team, school, or organization, identify that.
2. **Brand Type**: company, product, sports_team, school, organization, personal_brand, or unknown
3. **Industry**: What industry or sector?
4. **Website**: What is the likely official website? (e.g., "nordvpn.com")
5. **Logo Visible**: Is there a visible logo? (yes/no)
6. **Brand Confidence**: How confident are you? (high/medium/low)
Return ONLY valid JSON:
{
"brandName": "NordVPN",
"brandType": "company",
"industry": "Cybersecurity/VPN",
"website": "nordvpn.com",
"logoVisible": true,
"confidence": "high",
"brandDescription": "VPN and cybersecurity service"
}
If no brand is detectable, return:
{"brandName": "unknown", "confidence": "low"}`;
const response = await fetch(
`https://generativelanguage.googleapis.com/v1beta/models/gemini-3-flash-preview:generateContent?key=${apiKey}`,
{
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
contents: [{
parts: [
{ text: prompt },
{ inlineData: { mimeType, data: cleanBase64 } }
]
}],
generationConfig: { temperature: 0.2, maxOutputTokens: 500 }
})
}
);
const data = await response.json();
const text = data.candidates?.[0]?.content?.parts?.[0]?.text || '';
const jsonMatch = text.match(/\{[\s\S]*\}/);
if (jsonMatch) {
return JSON.parse(jsonMatch[0]);
}
} catch (e) {
console.warn('[Analyze] Brand detection error:', e);
}
return null;
}
// Link analysis to CRM
async linkAnalysisToCRM(brandInfo, asset, analysis) {
if (!window.cavCRM || !brandInfo.brandName) return null;
try {
// Check if company exists
let company = window.cavCRM.getAllCompanies({ search: brandInfo.brandName })[0];
// If not, create it
if (!company) {
company = window.cavCRM.createCompany({
name: brandInfo.brandName,
industry: brandInfo.industry || 'Unknown',
website: brandInfo.website ? `https://${brandInfo.website}` : '',
type: 'client',
description: brandInfo.brandDescription || `Auto-detected from creative: ${asset.filename}`,
tags: ['auto-detected', 'from-analysis'],
source: 'creative_analysis'
});
console.log(`[Analyze] Created CRM company: ${brandInfo.brandName}`);
}
// Link asset to company
if (company && !company.linkedAssets?.includes(asset.id)) {
const linkedAssets = company.linkedAssets || [];
linkedAssets.push(asset.id);
window.cavCRM.updateCompany(company.id, { linkedAssets });
}
// Check for or create a project
let project = window.cavCRM.getAllProjects({ client: company.id })[0];
if (!project) {
project = window.cavCRM.createProject({
name: `${brandInfo.brandName} Creative Analysis`,
client: company.id,
clientName: company.name,
type: 'campaign',
status: 'active',
description: `Auto-created project for creative assets from ${brandInfo.brandName}`,
tags: ['auto-created', 'creative-analysis']
});
console.log(`[Analyze] Created CRM project for ${brandInfo.brandName}`);
}
// Link asset to project
if (project) {
window.cavCRM.linkAssetToProject(project.id, asset.id);
}
// Log activity
window.cavCRM.logActivity('creative_analyzed', {
assetId: asset.id,
assetFilename: asset.filename,
companyId: company.id,
companyName: company.name,
hookScore: analysis.hookAnalysis?.overallScore,
ctaScore: analysis.ctaAnalysis?.overallEffectiveness,
confidence: analysis.confidence
});
return {
companyId: company.id,
projectId: project?.id
};
} catch (e) {
console.warn('[Analyze] CRM linking error:', e);
return null;
}
}
// ============================================
// UI RENDERING
// ============================================
render(container, asset = null) {
this.container = container;
container.innerHTML = `
<div class="cav-analyze-page">
<div class="cav-analyze-header">
<h1 class="cav-analyze-title">
<svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="var(--cav-primary)" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align: middle; margin-right: 8px;">
<line x1="18" y1="20" x2="18" y2="10"></line>
<line x1="12" y1="20" x2="12" y2="4"></line>
<line x1="6" y1="20" x2="6" y2="14"></line>
</svg>
Analyze
</h1>
<p class="cav-analyze-subtitle">AI-powered creative intelligence analysis</p>
</div>
${!asset ? this.renderAssetSelector() : ''}
<div class="cav-analyze-content">
${asset ? this.renderAnalysisView(asset) : this.renderEmptyState()}
</div>
</div>
`;
this.attachEventHandlers(container);
if (asset) {
this.currentAsset = asset;
}
}
renderEmptyState() {
const history = this.analysisHistory || [];
return `
<div class="cav-analyze-empty">
<div class="cav-empty-icon">
<svg width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="var(--cav-primary)" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
<circle cx="12" cy="12" r="10"></circle>
<circle cx="12" cy="12" r="4" fill="var(--cav-primary-soft)"></circle>
<line x1="12" y1="2" x2="12" y2="6"></line>
<line x1="12" y1="18" x2="12" y2="22"></line>
<line x1="2" y1="12" x2="6" y2="12"></line>
<line x1="18" y1="12" x2="22" y2="12"></line>
</svg>
</div>
<h2>Select an Asset to Analyze</h2>
<p>Choose an asset from your library or upload a new one to get AI-powered creative insights.</p>
<div class="cav-analyze-actions">
<button class="cav-btn cav-btn-primary" id="select-from-library">
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align: middle; margin-right: 6px;">
<path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"></path>
</svg>
Select from Library
</button>
<button class="cav-btn cav-btn-secondary" id="upload-for-analysis">
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align: middle; margin-right: 6px;">
<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path>
<polyline points="17 8 12 3 7 8"></polyline>
<line x1="12" y1="3" x2="12" y2="15"></line>
</svg>
Upload New Asset
</button>
</div>
<!-- Analysis History Section -->
${history.length > 0 ? `
<div class="cav-analysis-history-section">
<h3>
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="var(--cav-primary)" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align: middle; margin-right: 6px;">
<line x1="18" y1="20" x2="18" y2="10"></line>
<line x1="12" y1="20" x2="12" y2="4"></line>
<line x1="6" y1="20" x2="6" y2="14"></line>
</svg>
Recent Analyses (${history.length})
</h3>
<p class="cav-section-hint">Your analysis history is saved and persists across sessions</p>
<div class="cav-history-list">
${history.slice(0, 8).map(a => `
<div class="cav-history-item" data-asset-id="${a.assetId}">
<div class="cav-history-info">
<span class="cav-history-filename">${a.assetFilename || 'Unknown'}</span>
<span class="cav-history-date">${new Date(a.analyzedAt).toLocaleString()}</span>
</div>
<div class="cav-history-scores">
${a.hookAnalysis?.overallScore ? `<span class="cav-score-badge">🎣 ${a.hookAnalysis.overallScore}</span>` : ''}
${a.ctaAnalysis?.overallEffectiveness ? `<span class="cav-score-badge">📢 ${a.ctaAnalysis.overallEffectiveness}</span>` : ''}
${a.thumbStopScore?.overallScore ? `<span class="cav-score-badge">👆 ${a.thumbStopScore.overallScore}</span>` : ''}
</div>
<div class="cav-history-meta">
<span class="cav-confidence-badge cav-confidence-${a.confidence}">${a.confidence}</span>
${a.detectedBrand?.brandName && a.detectedBrand.brandName !== 'unknown' ?
`<span class="cav-brand-mini">${a.detectedBrand.brandName}</span>` : ''}
</div>