File size: 30,161 Bytes
e7251ed 86a7494 e7251ed |
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 |
from utils import *
from youtube_api_test import *
import traceback
import datetime
import json
import plotly.graph_objects as go
from plotly.subplots import make_subplots
def analyze_detailed_comments_sentiment(videos_data, content_type="videos", max_videos=5):
if not videos_data:
return {}
batch_content = f"Analyze {content_type} comments in detail with reasoning:\n\n"
for i, (video_id, title, likes, comments) in enumerate(videos_data[:max_videos]):
comment_data = []
for j, (comment, like_count) in enumerate(zip(comments[:30], likes[:30])):
comment_data.append(f"- \"{comment}\" ({like_count} likes)")
comments_text = '\n'.join(comment_data)[:2500]
batch_content += f"""
VIDEO {i}: "{title[:120]}"
COMMENTS WITH LIKES:
{comments_text}
---
"""
batch_prompt = f"""
{batch_content}
**Note: Advanced sentiment analysis required - consider sarcasm, slang, emojis, and context**
For each video, analyze the comments and extract multiple top comments by sentiment. Provide detailed analysis in this EXACT JSON format:
{{
"video_0": {{
"sentiment": "positive",
"score": 0.7,
"positive_ratio": 65,
"negative_ratio": 15,
"key_themes": ["collaboration", "creativity"],
"engagement_quality": "high",
"best_positives": [
{{"comment": "Amazing collaboration with small creators!", "likes": 150}},
{{"comment": "Love this authentic content!", "likes": 89}},
{{"comment": "Best video this year!", "likes": 67}}
],
"best_negatives": [
{{"comment": "Audio quality could be better", "likes": 45}},
{{"comment": "Too long, should be shorter", "likes": 23}},
{{"comment": "Boring content lately", "likes": 12}}
],
"best_neutrals": [
{{"comment": "Thanks for the content", "likes": 34}},
{{"comment": "First!", "likes": 89}},
{{"comment": "When is the next upload?", "likes": 56}}
],
"positive_reasons": [
"Viewers appreciate authentic collaborations and humble attitude",
"High production quality and engaging storytelling",
"Strong community connection and interaction"
],
"negative_reasons": [
"Technical issues mentioned by some viewers",
"Content length concerns from audience",
"Some want more variety in topics"
],
"trend_analysis": "Strong positive trend due to community focus and authentic content"
}},
"video_1": {{
"sentiment": "neutral",
"score": 0.5,
"positive_ratio": 45,
"negative_ratio": 25,
"key_themes": ["gaming", "entertainment"],
"engagement_quality": "medium",
"best_positives": [
{{"comment": "Good gameplay as always", "likes": 78}},
{{"comment": "Nice skills bro", "likes": 45}}
],
"best_negatives": [
{{"comment": "Not your best work", "likes": 34}},
{{"comment": "Too repetitive", "likes": 23}}
],
"best_neutrals": [
{{"comment": "Part 2 when?", "likes": 67}},
{{"comment": "Early squad", "likes": 89}}
],
"positive_reasons": [
"Consistent quality appreciated by fans",
"Good technical skills recognized"
],
"negative_reasons": [
"Some viewers want more innovation",
"Content feels repetitive to some"
],
"trend_analysis": "Steady engagement but needs fresh elements"
}}
}}
IMPORTANT REQUIREMENTS:
0. If comments are not in English. Translate it in English.
1. Extract 2-3 best comments for each sentiment category (positive, negative, neutral)
2. Include actual comment text and like counts from the data provided.
3. Ensure like counts match the data given
4. Provide 2-3 specific reasons for positive and negative sentiment patterns
5. Make sure positive_ratio + negative_ratio + neutral_ratio roughly equals 100
6. Return ONLY valid JSON without markdown formatting
7. Use actual quotes from the comments provided. Do not change the raw comments if it includes likes.
"""
try:
print(f"π§ Sending {len(videos_data)} videos to AI for multi-comment sentiment analysis...")
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": batch_prompt}],
max_tokens=3000,
temperature=0.5
)
response_text = response.choices[0].message.content.strip()
print(f"π₯ Received AI response: {len(response_text)} characters")
if "```json" in response_text:
response_text = response_text.split("```json")[1].split("```")[0].strip()
elif "```" in response_text:
response_text = response_text.split("```")[1].split("```")[0].strip()
response_text = response_text.strip()
if not response_text.startswith('{'):
start_idx = response_text.find('{')
end_idx = response_text.rfind('}') + 1
if start_idx != -1 and end_idx != 0:
response_text = response_text[start_idx:end_idx]
print(f"π§ Cleaned response for JSON parsing...")
batch_results = json.loads(response_text)
print(f"β
Successfully parsed AI analysis for {len(batch_results)} {content_type}")
return batch_results
except json.JSONDecodeError as e:
print(f"β JSON parsing error: {e}")
print(f"β Raw response: {response_text[:500]}...")
fallback_results = {}
for i in range(min(len(videos_data), max_videos)):
video_id, title, likes, comments = videos_data[i]
sample_positives = []
sample_negatives = []
sample_neutrals = []
for j, (comment, like_count) in enumerate(zip(comments[:10], likes[:10])):
if j < 3:
sample_positives.append({"comment": comment[:100], "likes": like_count})
elif j < 6:
sample_negatives.append({"comment": comment[:100], "likes": like_count})
else:
sample_neutrals.append({"comment": comment[:100], "likes": like_count})
fallback_results[f"video_{i}"] = {
"sentiment": "neutral",
"score": 0.5 + (i * 0.1),
"positive_ratio": 50 + (i * 5),
"negative_ratio": 20 + (i * 2),
"key_themes": ["content", "entertainment", "youtube"],
"engagement_quality": "medium",
"best_positives": sample_positives or [{"comment": "Great video!", "likes": 50}],
"best_negatives": sample_negatives or [{"comment": "Could improve", "likes": 20}],
"best_neutrals": sample_neutrals or [{"comment": "Thanks for content", "likes": 30}],
"positive_reasons": [
"General audience appreciation",
"Consistent content quality"
],
"negative_reasons": [
"Minor technical improvements needed",
"Some content preferences vary"
],
"trend_analysis": "Steady engagement with growth potential"
}
print(f"π Using enhanced fallback data for {len(fallback_results)} videos")
return fallback_results
except Exception as e:
print(f"β Sentiment analysis error: {e}")
print(f"β Full error: {traceback.format_exc()}")
basic_fallback = {}
for i in range(min(len(videos_data), max_videos)):
basic_fallback[f"video_{i}"] = {
"sentiment": "neutral", "score": 0.4, "positive_ratio": 40,
"negative_ratio": 30, "key_themes": ["general"], "engagement_quality": "medium",
"best_positives": [{"comment": "Good content", "likes": 25}],
"best_negatives": [{"comment": "Could improve", "likes": 15}],
"best_neutrals": [{"comment": "Thanks", "likes": 20}],
"positive_reasons": ["Basic appreciation"],
"negative_reasons": ["General feedback"],
"trend_analysis": "Stable engagement"
}
print(f"π Using basic fallback for {len(basic_fallback)} videos")
return basic_fallback
def create_content_dashboard(content_df, content_type="Videos"):
"""Create specialized dashboard for videos or shorts"""
if content_df.empty:
fig = go.Figure()
fig.add_annotation(text=f"No {content_type.lower()} found for analysis",
xref="paper", yref="paper", x=0.5, y=0.5, showarrow=False)
return fig
fig = make_subplots(
rows=2, cols=2,
subplot_titles=(
f'π {content_type} Sentiment Trend & Performance',
f'π {content_type} Sentiment Distribution',
f'π‘ Engagement Quality Breakdown',
f'π₯ Performance vs Sentiment Correlation'
),
specs=[
[{"secondary_y": True}, {"type": "pie"}],
[{"type": "bar"}, {"type": "scatter"}]
],
vertical_spacing=0.15,
horizontal_spacing=0.12
)
content_labels = [f"{content_type[:-1]} {i+1}" for i in range(len(content_df))]
colors = ['#2E86DE' if content_type == 'Videos' else '#FF6B35'] * len(content_df)
fig.add_trace(
go.Scatter(
x=content_labels,
y=content_df['sentiment_score'],
mode='lines+markers',
marker=dict(size=12, color=colors[0], line=dict(width=2, color='white')),
line=dict(width=4, color=colors[0]),
name=f'{content_type} Sentiment',
hovertemplate='<b>%{x}</b><br>Sentiment: %{y:.2f}<extra></extra>'
),
row=1, col=1
)
# Add views as bars
fig.add_trace(
go.Bar(
x=content_labels,
y=content_df['views']/1000,
name='Views (K)',
opacity=0.4,
marker_color=colors[0],
hovertemplate='<b>%{x}</b><br>Views: %{y:.0f}K<extra></extra>'
),
row=1, col=1, secondary_y=True
)
# Sentiment distribution pie
avg_positive = content_df['positive_ratio'].mean()
avg_negative = content_df['negative_ratio'].mean()
avg_neutral = 100 - avg_positive - avg_negative
fig.add_trace(
go.Pie(
labels=['π Positive', 'π Neutral', 'π Negative'],
values=[avg_positive, avg_neutral, avg_negative],
marker_colors=['#2ECC71', '#95A5A6', '#E74C3C'],
hole=0.4,
hovertemplate='<b>%{label}</b><br>%{value:.1f}%<extra></extra>',
textinfo='label+percent',
textfont=dict(size=12, color='white')
),
row=1, col=2
)
# Engagement quality breakdown
engagement_counts = content_df['engagement_quality'].value_counts()
quality_colors = {'high': '#27AE60', 'medium': '#F39C12', 'low': '#E74C3C'}
fig.add_trace(
go.Bar(
x=engagement_counts.index,
y=engagement_counts.values,
marker_color=[quality_colors.get(q, '#95A5A6') for q in engagement_counts.index],
hovertemplate='<b>%{x} Quality</b><br>Count: %{y}<extra></extra>',
text=engagement_counts.values,
textposition='auto',
textfont=dict(size=14, color='white')
),
row=2, col=1
)
# Performance vs Sentiment scatter
fig.add_trace(
go.Scatter(
x=content_df['sentiment_score'],
y=content_df['views'],
mode='markers',
marker=dict(
size=content_df['positive_ratio']/3,
color=content_df['sentiment_score'],
colorscale='RdYlGn',
showscale=True,
colorbar=dict(title="Sentiment Score"),
line=dict(width=2, color='white')
),
text=[f"{content_type[:-1]} {i+1}" for i in range(len(content_df))],
hovertemplate='<b>%{text}</b><br>Sentiment: %{x:.2f}<br>Views: %{y:,}<extra></extra>'
),
row=2, col=2
)
fig.update_layout(
height=800,
showlegend=False,
title_text=f"π― {content_type} Analytics Dashboard - AI-Powered Insights",
title_font=dict(size=20, color='#2C3E50'),
title_x=0.5,
plot_bgcolor='white',
paper_bgcolor='white'
)
# Update axes
fig.update_yaxes(title_text="Sentiment Score", row=1, col=1)
fig.update_yaxes(title_text="Views (K)", row=1, col=1, secondary_y=True)
fig.update_xaxes(title_text="Content Index", row=1, col=1, tickangle=45)
fig.update_xaxes(title_text="Sentiment Score", row=2, col=2)
fig.update_yaxes(title_text="Views", row=2, col=2)
return fig
def analyze_content_batch(channel_input, content_type="videos", max_videos=5):
"""Analyze either videos or shorts with detailed insights"""
try:
print(f"π Starting {content_type} analysis for: {channel_input} (Max: {max_videos})")
channel_id = get_channel_id_by_name(channel_input)
if not channel_id:
print(f"β Channel '{channel_input}' not found!")
return None
if content_type == "videos":
content_df = get_channel_videos(channel_id, limit=max_videos)
emoji = "πΉ"
else:
content_df = get_channel_shorts(channel_id, limit=max_videos)
emoji = "π¬"
if content_df.empty:
return f"## {emoji} No {content_type} found\n\nThis channel doesn't have any {content_type} to analyze.", go.Figure()
# Initialize columns
content_df['sentiment_score'] = 0.0
content_df['positive_ratio'] = 0.0
content_df['negative_ratio'] = 0.0
content_df['key_themes'] = None
content_df['engagement_quality'] = 'medium'
content_df['best_positive'] = ''
content_df['best_negative'] = ''
content_df['best_neutral'] = ''
content_df['positive_reason'] = ''
content_df['negative_reason'] = ''
content_df['trend_analysis'] = ''
content_df['best_positives'] = None
content_df['best_negatives'] = None
content_df['best_neutrals'] = None
content_df['positive_reasons'] = None
content_df['negative_reasons'] = None
print(f"π Collecting {content_type} comments...")
batch_data = []
for i, row in content_df.iterrows():
comments_df = get_youtube_comments(row['video_id'], limit=17, order='relevance')
if not comments_df.empty:
batch_data.append((row['video_id'], row['title'], comments_df['likes'].tolist(), comments_df['comment'].tolist()))
if batch_data:
print(f"π§ AI analyzing {len(batch_data)} {content_type}...")
results = analyze_detailed_comments_sentiment(batch_data, content_type, max_videos)
for i, (video_id, title, likes, comments) in enumerate(batch_data):
result_key = f"video_{i}"
if result_key in results:
result = results[result_key]
try:
idx = content_df[content_df['video_id'] == video_id].index[0]
# Apply basic metrics
content_df.at[idx, 'sentiment_score'] = result.get('score', 0)
content_df.at[idx, 'positive_ratio'] = result.get('positive_ratio', 0)
content_df.at[idx, 'negative_ratio'] = result.get('negative_ratio', 0)
content_df.at[idx, 'key_themes'] = result.get('key_themes', [])
content_df.at[idx, 'engagement_quality'] = result.get('engagement_quality', 'medium')
content_df.at[idx, 'trend_analysis'] = result.get('trend_analysis', '')
# Apply multiple comments and reasons
content_df.at[idx, 'best_positives'] = result.get('best_positives', [])
content_df.at[idx, 'best_negatives'] = result.get('best_negatives', [])
content_df.at[idx, 'best_neutrals'] = result.get('best_neutrals', [])
content_df.at[idx, 'positive_reasons'] = result.get('positive_reasons', [])
content_df.at[idx, 'negative_reasons'] = result.get('negative_reasons', [])
# Keep single comment fields for backward compatibility
best_pos = result.get('best_positives', [])
best_neg = result.get('best_negatives', [])
best_neu = result.get('best_neutrals', [])
content_df.at[idx, 'best_positive'] = best_pos[0]['comment'] if best_pos else ''
content_df.at[idx, 'best_negative'] = best_neg[0]['comment'] if best_neg else ''
content_df.at[idx, 'best_neutral'] = best_neu[0]['comment'] if best_neu else ''
pos_reasons = result.get('positive_reasons', [])
neg_reasons = result.get('negative_reasons', [])
content_df.at[idx, 'positive_reason'] = pos_reasons[0] if pos_reasons else ''
content_df.at[idx, 'negative_reason'] = neg_reasons[0] if neg_reasons else ''
print(f"β
Applied multi-comment analysis for: {title[:50]}...")
except Exception as e:
print(f"β Error applying results for {title[:50]}: {str(e)}")
# Generate insights
insights = generate_detailed_insights(content_df, content_type.capitalize())
# Create dashboard
dashboard = create_content_dashboard(content_df, content_type.capitalize())
print(f"β
{content_type.capitalize()} analysis completed!")
return insights, dashboard
except Exception as e:
print(f"β Error analyzing {content_type}: {str(e)}")
error_msg = f"## β {content_type.capitalize()} Analysis Error\n\n**Error:** {str(e)}"
empty_fig = go.Figure()
return error_msg, empty_fig
def generate_detailed_insights(content_df, content_type):
"""Generate AI-powered detailed insights with LLM analysis"""
if content_df.empty:
return f"## No {content_type.lower()} found for analysis"
analysis_data = {
"content_type": content_type,
"total_content": len(content_df),
"performance_metrics": {
"avg_views": content_df['views'].mean(),
"avg_sentiment": content_df['sentiment_score'].mean(),
"avg_positive": content_df['positive_ratio'].mean(),
"avg_negative": content_df['negative_ratio'].mean(),
"total_views": content_df['views'].sum()
},
"content_breakdown": []
}
for i, row in content_df.iterrows():
content_analysis = {
"index": i + 1,
"title": row['title'][:80],
"views": row['views'],
"sentiment_score": row['sentiment_score'],
"positive_ratio": row.get('positive_ratio', 0),
"negative_ratio": row.get('negative_ratio', 0),
"engagement_quality": row.get('engagement_quality', 'medium'),
"key_themes": row.get('key_themes', []),
"best_positives": row.get('best_positives', []),
"best_negatives": row.get('best_negatives', []),
"positive_reasons": row.get('positive_reasons', []),
"negative_reasons": row.get('negative_reasons', []),
"trend_analysis": row.get('trend_analysis', '')
}
analysis_data["content_breakdown"].append(content_analysis)
# Create LLM analysis prompt
llm_prompt = f"""
Analyze this YouTube {content_type.lower()} performance data and generate a comprehensive intelligence report.
PERFORMANCE DATA:
- Total {content_type}: {analysis_data['total_content']}
- Average Views: {analysis_data['performance_metrics']['avg_views']:,.0f}
- Average Sentiment: {analysis_data['performance_metrics']['avg_sentiment']:.2f}/1.0
- Positive Ratio: {analysis_data['performance_metrics']['avg_positive']:.1f}%
- Negative Ratio: {analysis_data['performance_metrics']['avg_negative']:.1f}%
INDIVIDUAL CONTENT ANALYSIS:
{chr(10).join([f"{item['index']}. '{item['title']}' - {item['views']:,} views, {item['sentiment_score']:.2f} sentiment, {item['positive_ratio']:.0f}% positive, Quality: {item['engagement_quality']}, Themes: {item['key_themes'][:3]}" for item in analysis_data['content_breakdown']])}
Generate a professional analysis report in the following structure:
# π {content_type} Performance Intelligence Report
## π Executive Summary
[2-3 sentences about overall performance and key findings]
## π― Performance Breakdown
### π Champion Content Analysis
[Identify top 2-3 performing videos with specific reasons for success]
### β οΈ Optimization Opportunities
[Identify bottom 2-3 performing videos with specific improvement recommendations]
## π‘ Strategic Insights
### π₯ Winning Formula
[3-4 key success patterns identified from top performers]
### π¬ Content DNA Analysis
[Analysis of themes, engagement patterns, and audience preferences]
### π Audience Sentiment Intelligence
[Deep dive into comment sentiment patterns and audience behavior]
## π Action Plan Recommendations
### Immediate Actions
[1-2 specific, actionable recommendations]
## π Competitive Advantage
[How this channel can differentiate and excel in their niche]
---
Requirements:
- Use emojis strategically for visual impact
- Include specific data points and percentages
- Make recommendations actionable and specific
- Write in professional but engaging tone
- Focus on growth and optimization strategies
- Keep analysis data-driven and insightful
"""
try:
# Generate LLM insights
print("π§ Generating AI-powered strategic insights...")
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": llm_prompt}],
max_tokens=3000,
temperature=0.3
)
llm_insights = response.choices[0].message.content.strip()
# Add individual content performance cards
detailed_breakdown = """
---
<details>
<summary style="font-size: 1.5em; font-weight: bold; cursor: pointer; margin: 16px 0 8px 0; color: inherit;">
Individual Content Performance Matrix<br> (Click to Expand!)
</summary>
## π Individual Content Performance Matrix
"""
for item in analysis_data["content_breakdown"]:
# Performance rating logic
performance_score = (
(item['sentiment_score'] * 40) +
(min(item['views'] / analysis_data['performance_metrics']['avg_views'], 2) * 30) +
(item['positive_ratio'] * 0.3)
)
if performance_score >= 80:
rating = "π CHAMPION"
status_color = "π"
elif performance_score >= 60:
rating = "π STRONG"
status_color = "π"
elif performance_score >= 40:
rating = "π STEADY"
status_color = "π "
else:
rating = "β οΈ NEEDS WORK"
status_color = "π"
detailed_breakdown += f"""
### {rating}: "{item['title']}"
| Metric | Value | Performance |
|--------|--------|-------------|
| π **Views** | {item['views']:,} | {status_color} {'Above Average' if item['views'] > analysis_data['performance_metrics']['avg_views'] else 'Below Average'} |
| π― **Sentiment Score** | {item['sentiment_score']:.2f}/1.0 | {'π₯ Excellent' if item['sentiment_score'] > 0.8 else 'π Good' if item['sentiment_score'] > 0.6 else 'β οΈ Needs Work'} |
| π **Positive Feedback** | {item['positive_ratio']:.0f}% | {'π Outstanding' if item['positive_ratio'] > 80 else 'π Strong' if item['positive_ratio'] > 60 else 'π§ Improve'} |
| πͺ **Engagement Quality** | {item['engagement_quality'].title()} | {'π₯ High Impact' if item['engagement_quality'] == 'high' else 'π Steady Growth' if item['engagement_quality'] == 'medium' else 'π‘ Potential'} |
**π¨ Content Themes**: {', '.join(item['key_themes'][:3]) if item['key_themes'] else 'General Content'}
"""
# Positive feedback section
if item.get('best_positives') or item.get('positive_reasons'):
detailed_breakdown += "| **π Top Comments** | **π Positive Reasons** |\n"
detailed_breakdown += "|---------------------|------------------------|\n"
max_len = max(len(item.get('best_positives', [])), len(item.get('positive_reasons', [])))
for i in range(max_len):
comment = item.get('best_positives', [])[i]['comment'][:100] + "..." if i < len(item.get('best_positives', [])) else ""
reason = item.get('positive_reasons', [])[i][:100] + "..." if i < len(item.get('positive_reasons', [])) else ""
detailed_breakdown += f"| {comment} | {reason} |\n"
detailed_breakdown += "\n"
# Negative feedback section
if item.get('best_negatives') or item.get('negative_reasons'):
detailed_breakdown += "| **π Critical Feedback** | **π Negative Reasons** |\n"
detailed_breakdown += "|--------------------------|------------------------|\n"
max_len = max(len(item.get('best_negatives', [])), len(item.get('negative_reasons', [])))
for i in range(max_len):
comment = item.get('best_negatives', [])[i]['comment'][:100] + "..." if i < len(item.get('best_negatives', [])) else ""
reason = item.get('negative_reasons', [])[i][:100] + "..." if i < len(item.get('negative_reasons', [])) else ""
detailed_breakdown += f"| {comment} | {reason} |\n"
detailed_breakdown += "\n"
detailed_breakdown += "---\n"
detailed_breakdown += "\n</details>\n"
# Combine LLM insights with detailed breakdown
final_report = llm_insights + detailed_breakdown
# Add footer with timestamp and hackathon branding
final_report += f"""
---
*π€ AI-Powered Strategic Intelligence | β° {datetime.datetime.now().strftime('%Y-%m-%d %H:%M UTC')} | π Next-Gen Analytics*
"""
print("β
Strategic intelligence report generated successfully!")
return final_report
except Exception as e:
print(f"β LLM Analysis Error: {str(e)}")
# Fallback to enhanced static analysis
best_video = content_df.loc[content_df['sentiment_score'].idxmax()]
worst_video = content_df.loc[content_df['sentiment_score'].idxmin()]
fallback_report = f"""
# π {content_type} Performance Intelligence Report
## π Executive Dashboard
| π― Key Metric | π Performance | π Status |
|---------------|----------------|-----------|
| **Portfolio Size** | {len(content_df)} {content_type.lower()} | {'π₯ Focused Strategy' if len(content_df) <= 10 else 'π Active Portfolio'} |
| **Average Performance** | {content_df['views'].mean():,.0f} views | {'π Viral Territory' if content_df['views'].mean() > 1000000 else 'π Strong Growth' if content_df['views'].mean() > 100000 else 'π Building Momentum'} |
| **Audience Sentiment** | {content_df['sentiment_score'].mean():.2f}/1.0 | {'π Exceptional' if content_df['sentiment_score'].mean() > 0.8 else 'π Positive' if content_df['sentiment_score'].mean() > 0.6 else 'β οΈ Optimization Needed'} |
| **Success Rate** | {content_df['positive_ratio'].mean():.0f}% positive | {'π Championship Level' if content_df['positive_ratio'].mean() > 80 else 'π Competitive' if content_df['positive_ratio'].mean() > 60 else 'π§ Growth Opportunity'} |
## π― Performance Analysis
### π TOP PERFORMER: "{best_video['title'][:60]}..."
- **π Metrics**: {best_video['views']:,} views | {best_video['sentiment_score']:.2f} sentiment | {best_video.get('positive_ratio', 0):.0f}% positive
- **β
Success DNA**: {best_video.get('positive_reason', 'Strong audience resonance and engaging content delivery')}
### β οΈ OPTIMIZATION TARGET: "{worst_video['title'][:60]}..."
- **π Metrics**: {worst_video['views']:,} views | {worst_video['sentiment_score']:.2f} sentiment | {worst_video.get('positive_ratio', 0):.0f}% positive
- **π§ Growth Areas**: {worst_video.get('negative_reason', 'Content optimization and audience alignment needed')}
## π Strategic Action Plan
### Immediate Wins (Next 30 Days)
1. **π¬ Replicate Success Formula**: Scale elements from "{best_video['title'][:30]}..." format
2. **π§ Optimize Underperformers**: Address feedback patterns from bottom performers
3. **π Engagement Boost**: Focus on {content_df['engagement_quality'].value_counts().index[0]} quality content
### Strategic Growth (Next 90 Days)
1. **π― Content Optimization**: Leverage top-performing themes and formats
2. **π₯ Audience Development**: Build on positive sentiment patterns
3. **π Performance Scaling**: Systematic improvement of bottom 20% content
---
*π€ Enhanced Analytics Engine | π MCP Server Hackathon | β° {datetime.datetime.now().strftime('%Y-%m-%d %H:%M')} | π Next-Gen Intelligence*
"""
return fallback_report |