MoburstAI commited on
Commit
13b1120
Β·
verified Β·
1 Parent(s): dc48354

Rewrite insights: data-driven analysis instead of generic templates

Browse files
Files changed (1) hide show
  1. app.py +193 -76
app.py CHANGED
@@ -212,108 +212,225 @@ def find_peak_region_seconds(region_activations, hrf_offset):
212
  return summary
213
 
214
 
215
- def generate_insights(engagement, region_activations, hrf_offset=5):
216
- """Generate actionable creative strategy insights from brain data."""
217
  insights = []
218
- if len(engagement) < 3:
 
219
  return insights
220
 
221
  mean_eng = float(np.mean(engagement))
222
- n = len(engagement)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
223
 
224
- # ── 1. Hook Analysis ──
225
- hook = float(np.mean(engagement[:3]))
226
- if hook < mean_eng * 0.85:
227
- drop = ((mean_eng - hook) / mean_eng * 100)
228
  insights.append({
229
  "type": "hook", "severity": "high",
230
- "title": "Weak Opening Hook",
231
- "message": f"The first 3 seconds generate {drop:.0f}% less brain engagement than the rest of the ad. In a feed environment, this means scroll-past risk is high.",
232
- "action": "Front-load impact: lead with a surprising visual, bold text, or audio spike in the first 1-2 seconds."
233
  })
234
- elif hook > mean_eng * 1.15:
235
- lift = ((hook - mean_eng) / mean_eng * 100)
 
 
 
 
 
 
 
 
 
 
236
  insights.append({
237
  "type": "hook", "severity": "positive",
238
- "title": "Strong Opening Hook",
239
- "message": f"The opening drives {lift:.0f}% higher engagement than average β€” this ad grabs attention immediately.",
240
- "action": "This hook pattern works. Replicate the opening structure (visual style, pacing, audio) across other creatives."
241
  })
242
 
243
- # ── 2. What's Driving Engagement (translate brain regions to creative language) ──
244
- region_means = {}
245
- for rname in ["visual_processing", "attention", "emotional_response", "language_processing", "motor_planning"]:
246
- if rname in region_activations:
247
- vals = region_activations[rname]
248
- search = vals[:-2] if len(vals) > 3 else vals
249
- region_means[rname] = float(np.mean(search))
250
-
251
- if region_means:
252
- sorted_regions = sorted(region_means.items(), key=lambda x: x[1], reverse=True)
253
- top = sorted_regions[0][0]
254
-
255
- driver_map = {
256
- "visual_processing": ("Visually-Led Creative", "The visual elements (colors, motion, composition) generate the strongest brain response. Viewers are engaged by what they see, not what they hear.", "Double down on visual storytelling. Test different visual treatments β€” the audience is responding to imagery over copy."),
257
- "attention": ("High Cognitive Engagement", "This ad demands active focus β€” viewers are thinking and processing, not passively watching.", "This is engaging but mentally demanding. Balance information-dense sections with breathing room to avoid fatigue."),
258
- "emotional_response": ("Emotionally Resonant", "Emotional processing dominates β€” this ad creates a feeling. Emotion-driven ads tend to build stronger brand recall.", "Lean into the emotional angle in your CTA. 'Feel' CTAs ('Join the movement', 'Don't miss out') outperform 'think' CTAs ('Learn more') for emotional creatives."),
259
- "language_processing": ("Copy & Audio Are Carrying", "Language processing is the dominant signal β€” voiceover, on-screen text, or dialogue are doing the heavy lifting.", "The words matter most. A/B test different copy, voiceover tones, or text overlay styles to find the strongest variant."),
260
- "motor_planning": ("Action-Oriented", "The brain is preparing to act β€” tap, swipe, click. This is the ideal response for performance ads.", "Capitalize on this impulse. Make the CTA large, immediate, and friction-free. This audience is ready to convert."),
261
- }
 
 
 
 
 
 
 
262
 
263
- if top in driver_map:
264
- title, msg, action = driver_map[top]
265
- insights.append({"type": "driver", "severity": "positive", "title": title, "message": msg, "action": action})
 
 
 
266
 
267
- # ── 3. Peak Moment ──
268
- peak_idx = int(np.argmax(engagement))
269
  peak_s = peak_idx + hrf_offset
 
 
 
 
 
 
 
 
 
 
 
270
  insights.append({
271
  "type": "peak", "severity": "positive",
272
- "title": f"Strongest Moment at {peak_s}s",
273
- "message": f"Peak brain engagement occurs at second {peak_s}. Whatever happens here β€” a visual reveal, scene transition, or key message β€” is the most impactful element.",
274
- "action": f"Build your ad's narrative arc around the {peak_s}-second mark. Consider placing your product reveal or key value proposition here."
275
  })
276
 
277
- # ── 4. Mid-Section Drop ──
278
- if n >= 8:
279
- mid_s = n // 3
280
- mid_e = 2 * n // 3
281
- mid_eng = float(np.mean(engagement[mid_s:mid_e]))
282
- if mid_eng < mean_eng * 0.8:
283
- insights.append({
284
- "type": "mid_drop", "severity": "medium",
285
- "title": "Middle Section Loses Attention",
286
- "message": f"Engagement drops between seconds {mid_s+hrf_offset}-{mid_e+hrf_offset}. Without new stimulus, viewers disengage here.",
287
- "action": "Add a pattern interrupt: scene change, new speaker, text overlay, music shift, or tempo change. The brain needs novelty every 3-5 seconds."
288
- })
289
-
290
- # ── 5. Ending / CTA Readiness ──
291
  if n >= 5:
292
- last_3s = float(np.mean(engagement[-3:]))
293
- if last_3s < mean_eng * 0.8:
 
294
  insights.append({
295
- "type": "ending", "severity": "high",
296
- "title": "CTA Lands on Low Engagement",
297
- "message": "Brain engagement is low when the CTA appears. Viewers' attention has drifted β€” they're less likely to act.",
298
- "action": "Either move the CTA to the peak moment, or create a second attention spike at the end (urgency text, bold visual, or a direct question to re-engage)."
299
  })
300
- elif last_3s > mean_eng * 1.1:
301
  insights.append({
302
- "type": "ending", "severity": "positive",
303
  "title": "Strong CTA Window",
304
- "message": "Engagement is high at the end β€” viewers are attentive when the CTA appears, maximizing click-through potential.",
305
- "action": "Ensure the CTA is visually prominent and uses action language. This audience is primed to convert."
306
  })
307
 
308
- # ── 6. Overall Dynamics ──
309
- std_eng = float(np.std(engagement))
310
- if std_eng < 0.05:
311
- insights.append({
312
- "type": "dynamics", "severity": "medium",
313
- "title": "Flat Response β€” Low Memorability",
314
- "message": "Brain activation is uniform throughout β€” no emotional peaks or valleys. Flat response correlates with lower ad recall.",
315
- "action": "Create contrast: a quiet moment followed by a bold one, humor, an unexpected visual, or a change in pace. Memorable ads have peaks."
316
- })
 
 
 
 
 
 
 
 
 
 
 
 
 
317
 
318
  return insights
319
 
 
212
  return summary
213
 
214
 
215
+ def generate_insights(engagement, region_activations, hrf_offset=0):
216
+ """Generate data-specific creative insights from brain activation patterns."""
217
  insights = []
218
+ n = len(engagement)
219
+ if n < 3:
220
  return insights
221
 
222
  mean_eng = float(np.mean(engagement))
223
+ std_eng = float(np.std(engagement))
224
+ peak_idx = int(np.argmax(engagement))
225
+ low_idx = int(np.argmin(engagement))
226
+ peak_val = float(engagement[peak_idx])
227
+ low_val = float(engagement[low_idx])
228
+
229
+ # ── Compute per-region stats ──
230
+ region_stats = {}
231
+ for rname in ["visual_processing", "attention", "emotional_response", "language_processing", "motor_planning"]:
232
+ if rname in region_activations:
233
+ vals = region_activations[rname]
234
+ safe = vals[:-2] if len(vals) > 3 else vals
235
+ region_stats[rname] = {
236
+ "mean": float(np.mean(safe)),
237
+ "std": float(np.std(safe)),
238
+ "peak_idx": int(np.argmax(safe)),
239
+ "peak_val": float(np.max(safe)),
240
+ }
241
+
242
+ sorted_regions = sorted(region_stats.items(), key=lambda x: x[1]["mean"], reverse=True) if region_stats else []
243
+ top_region = sorted_regions[0][0] if sorted_regions else None
244
+ bottom_region = sorted_regions[-1][0] if sorted_regions else None
245
+
246
+ # ── 1. Engagement Shape Analysis ──
247
+ # Split into thirds and identify the shape
248
+ third = max(1, n // 3)
249
+ start_eng = float(np.mean(engagement[:third]))
250
+ mid_eng = float(np.mean(engagement[third:2*third]))
251
+ end_eng = float(np.mean(engagement[2*third:]))
252
+
253
+ if start_eng > mid_eng and start_eng > end_eng:
254
+ shape = "front-loaded"
255
+ elif end_eng > mid_eng and end_eng > start_eng:
256
+ shape = "back-loaded"
257
+ elif mid_eng < start_eng and mid_eng < end_eng:
258
+ shape = "u-shape"
259
+ elif mid_eng > start_eng and mid_eng > end_eng:
260
+ shape = "peak-middle"
261
+ else:
262
+ shape = "flat"
263
+
264
+ shape_insights = {
265
+ "front-loaded": {
266
+ "title": "Front-Loaded Engagement",
267
+ "severity": "medium",
268
+ "message": f"Brain engagement is strongest in the first {third}s, then declines. Viewers get hooked early but lose interest before the CTA.",
269
+ "action": "Move your key message or CTA earlier β€” viewers are most receptive in the opening seconds. Or add a second hook in the final third to re-engage."
270
+ },
271
+ "back-loaded": {
272
+ "title": "Slow Build β€” Late Peak",
273
+ "severity": "medium",
274
+ "message": f"Engagement builds toward the end, peaking after {2*third}s. The opening is the weakest section β€” viewers in a feed may not stick around long enough to see the payoff.",
275
+ "action": "Tease the ending upfront: show a flash of the climax in the first 2 seconds to buy time. Or restructure to reveal the hook immediately."
276
+ },
277
+ "u-shape": {
278
+ "title": "Mid-Section Drop",
279
+ "severity": "medium",
280
+ "message": f"Strong opening and closing, but engagement dips in the middle ({third}s-{2*third}s). The ad loses attention between the hook and the CTA.",
281
+ "action": f"Add a pattern interrupt between {third}s-{2*third}s: scene change, new speaker, text overlay, or tempo shift. Bridge the gap between hook and close."
282
+ },
283
+ "peak-middle": {
284
+ "title": "Center-Weighted Engagement",
285
+ "severity": "positive",
286
+ "message": f"The core message (around {third}s-{2*third}s) drives the strongest response. The middle of the ad is doing the heavy lifting.",
287
+ "action": "The structure works β€” strong narrative arc. Ensure the CTA appears during or immediately after this engagement peak, not after it fades."
288
+ },
289
+ "flat": {
290
+ "title": "Flat Response β€” Low Contrast",
291
+ "severity": "medium",
292
+ "message": "Brain engagement is relatively uniform throughout β€” no strong peaks or valleys. Flat response correlates with lower ad recall and weaker brand lift.",
293
+ "action": "Create contrast: add a surprising moment, an emotional beat, a visual disruption, or a change in pacing. Memorable ads need at least one peak."
294
+ },
295
+ }
296
+ insights.append({"type": "shape", **shape_insights[shape]})
297
+
298
+ # ── 2. Hook Verdict ──
299
+ hook_3s = float(np.mean(engagement[:min(3, n)]))
300
+ hook_vs_avg = (hook_3s - mean_eng) / (mean_eng + 1e-8) * 100
301
+
302
+ if hook_vs_avg < -15:
303
+ # Find what's WEAK in the hook
304
+ hook_regions = {r: float(np.mean(region_activations[r][:min(3, n)])) for r in region_stats}
305
+ weakest_hook_region = min(hook_regions, key=hook_regions.get) if hook_regions else None
306
+ weakness_label = {
307
+ "visual_processing": "visuals aren't grabbing attention",
308
+ "attention": "nothing demands focus",
309
+ "emotional_response": "no emotional hook",
310
+ "language_processing": "the copy/audio doesn't land immediately",
311
+ "motor_planning": "no impulse to engage",
312
+ }.get(weakest_hook_region, "the opening lacks stimulus")
313
 
 
 
 
 
314
  insights.append({
315
  "type": "hook", "severity": "high",
316
+ "title": f"Weak Hook β€” {abs(hook_vs_avg):.0f}% Below Average",
317
+ "message": f"The first 3 seconds underperform the rest of the ad. Specifically, {weakness_label} in the opening.",
318
+ "action": "Restructure the first 2 seconds: lead with motion, a face, bold text, or a sound that demands attention. The hook determines 80% of view-through rate."
319
  })
320
+ elif hook_vs_avg > 15:
321
+ # Find what's STRONG in the hook
322
+ hook_regions = {r: float(np.mean(region_activations[r][:min(3, n)])) for r in region_stats}
323
+ strongest_hook_region = max(hook_regions, key=hook_regions.get) if hook_regions else None
324
+ strength_label = {
325
+ "visual_processing": "strong visual opening",
326
+ "attention": "immediately grabs focus",
327
+ "emotional_response": "emotional hook",
328
+ "language_processing": "compelling opening line/audio",
329
+ "motor_planning": "action-triggering opener",
330
+ }.get(strongest_hook_region, "effective opening")
331
+
332
  insights.append({
333
  "type": "hook", "severity": "positive",
334
+ "title": f"Strong Hook β€” {hook_vs_avg:.0f}% Above Average",
335
+ "message": f"The opening outperforms the rest of the ad, driven by {strength_label}. This hook pattern is worth replicating.",
336
+ "action": "Document this hook structure β€” it works. Test variations of the same opening pattern across other creatives."
337
  })
338
 
339
+ # ── 3. Engagement Drops β€” find the worst dip ──
340
+ if n >= 6:
341
+ # Find the biggest drop (3-second rolling window)
342
+ window = 3
343
+ rolling = [float(np.mean(engagement[max(0,i-1):i+window-1])) for i in range(n - window + 1)]
344
+ worst_window_idx = int(np.argmin(rolling))
345
+ worst_window_val = rolling[worst_window_idx]
346
+ drop_pct = (mean_eng - worst_window_val) / (mean_eng + 1e-8) * 100
347
+
348
+ if drop_pct > 15:
349
+ drop_start = worst_window_idx + hrf_offset
350
+ drop_end = worst_window_idx + window + hrf_offset
351
+ # What region drops the most here?
352
+ drop_regions = {}
353
+ for rname in region_stats:
354
+ region_at_drop = float(np.mean(region_activations[rname][worst_window_idx:worst_window_idx+window]))
355
+ region_overall = region_stats[rname]["mean"]
356
+ drop_regions[rname] = (region_overall - region_at_drop) / (region_overall + 1e-8)
357
+ biggest_drop_region = max(drop_regions, key=drop_regions.get) if drop_regions else None
358
+ drop_label = {
359
+ "visual_processing": "visual interest drops β€” the scene may be static or repetitive",
360
+ "attention": "cognitive focus fades β€” nothing new to process",
361
+ "emotional_response": "emotional connection weakens",
362
+ "language_processing": "the message loses clarity or relevance",
363
+ "motor_planning": "action intent drops β€” the ad feels passive",
364
+ }.get(biggest_drop_region, "engagement drops")
365
 
366
+ insights.append({
367
+ "type": "drop", "severity": "high",
368
+ "title": f"Attention Drop at {drop_start}s-{drop_end}s ({drop_pct:.0f}% below avg)",
369
+ "message": f"The weakest moment in the ad. Specifically, {drop_label} during this window.",
370
+ "action": f"Review what happens at {drop_start}s-{drop_end}s in the video. Add a scene change, new audio cue, or text overlay to re-engage."
371
+ })
372
 
373
+ # ── 4. Peak Moment β€” what makes it work ──
 
374
  peak_s = peak_idx + hrf_offset
375
+ # Find what region is strongest at the peak
376
+ peak_regions = {r: float(region_activations[r][peak_idx]) for r in region_stats}
377
+ peak_driver = max(peak_regions, key=peak_regions.get) if peak_regions else None
378
+ peak_label = {
379
+ "visual_processing": "a strong visual moment",
380
+ "attention": "high cognitive focus",
381
+ "emotional_response": "an emotional beat",
382
+ "language_processing": "a compelling message or audio cue",
383
+ "motor_planning": "an action trigger",
384
+ }.get(peak_driver, "a peak in brain activity")
385
+
386
  insights.append({
387
  "type": "peak", "severity": "positive",
388
+ "title": f"Peak at {peak_s}s β€” Driven by {peak_label.title()}",
389
+ "message": f"The strongest brain response occurs at {peak_s}s, primarily driven by {peak_label}. This is the most impactful moment in the ad.",
390
+ "action": f"Align your key message or product reveal with this moment. If the CTA isn't near {peak_s}s, consider moving it closer."
391
  })
392
 
393
+ # ── 5. CTA Window ──
 
 
 
 
 
 
 
 
 
 
 
 
 
394
  if n >= 5:
395
+ last_3 = float(np.mean(engagement[-3:]))
396
+ cta_vs_avg = (last_3 - mean_eng) / (mean_eng + 1e-8) * 100
397
+ if cta_vs_avg < -15:
398
  insights.append({
399
+ "type": "cta", "severity": "high",
400
+ "title": f"CTA Lands on Low Engagement ({cta_vs_avg:.0f}%)",
401
+ "message": f"The final 3 seconds are {abs(cta_vs_avg):.0f}% below average. Viewers' attention has faded when the CTA appears.",
402
+ "action": f"Option A: Move the CTA to the peak moment ({peak_s}s). Option B: Add a re-engagement spike before the CTA β€” a bold visual, urgency text, or direct question."
403
  })
404
+ elif cta_vs_avg > 10:
405
  insights.append({
406
+ "type": "cta", "severity": "positive",
407
  "title": "Strong CTA Window",
408
+ "message": f"Engagement is {cta_vs_avg:.0f}% above average at the end. Viewers are attentive when the CTA appears.",
409
+ "action": "Make sure the CTA is visually prominent and uses action language. This audience is primed to act."
410
  })
411
 
412
+ # ── 6. Region Dominance (only if there's a clear leader) ──
413
+ if len(sorted_regions) >= 2:
414
+ top_name, top_stats = sorted_regions[0]
415
+ second_name, second_stats = sorted_regions[1]
416
+ dominance = (top_stats["mean"] - second_stats["mean"]) / (second_stats["mean"] + 1e-8) * 100
417
+
418
+ if dominance > 10:
419
+ labels = {
420
+ "visual_processing": ("Visually-Driven", "imagery and motion", "Test different visual treatments β€” color, pacing, composition β€” since the audience responds primarily to what they see."),
421
+ "attention": ("Cognitively Demanding", "focused thinking", "Balance information density with breathing room. Too much cognitive load causes fatigue and drop-off."),
422
+ "emotional_response": ("Emotion-Led", "feelings over logic", "Use emotion-aligned CTAs ('Don't miss out', 'Join the movement') β€” they outperform rational CTAs for this type of creative."),
423
+ "language_processing": ("Copy-Driven", "words and audio", "The copy is doing the heavy lifting. A/B test different scripts, voiceover styles, or text overlays."),
424
+ "motor_planning": ("Action-Primed", "impulse to act", "This is ideal for performance ads. Place the CTA at the moment of highest motor activation for maximum conversion."),
425
+ }
426
+ if top_name in labels:
427
+ label, driver, action = labels[top_name]
428
+ insights.append({
429
+ "type": "dominance", "severity": "positive",
430
+ "title": f"{label} Creative ({dominance:.0f}% stronger than #{2})",
431
+ "message": f"This ad's engagement is primarily driven by {driver}. The {labels.get(top_name, ('','',''))[0].lower()} signal is {dominance:.0f}% stronger than the next closest region.",
432
+ "action": action,
433
+ })
434
 
435
  return insights
436