Youtube-Analyzer-Pro / final_channal_analyzer.py
suil0109's picture
update
86a7494
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