""" LeapScholar Enhanced Brand Perception Monitor ========================================== A comprehensive brand monitoring tool with advanced analytics, competitive analysis, sentiment tracking, influence scoring, and actionable business insights. """ import gradio as gr import pandas as pd import numpy as np from datetime import datetime, timedelta import matplotlib.pyplot as plt import seaborn as sns import plotly.express as px import plotly.graph_objects as go from plotly.subplots import make_subplots from collections import Counter, defaultdict import re import json from typing import Dict, List, Tuple, Optional import time import warnings import hashlib from dataclasses import dataclass warnings.filterwarnings('ignore') # Data collection libraries - with fallbacks for compatibility try: from textblob import TextBlob TEXTBLOB_AVAILABLE = True except ImportError: TEXTBLOB_AVAILABLE = False print("TextBlob not available - using enhanced sentiment analysis") # Optional libraries - graceful fallbacks if not available try: import requests from bs4 import BeautifulSoup WEB_SCRAPING_AVAILABLE = True except ImportError: WEB_SCRAPING_AVAILABLE = False print("Web scraping libraries not available - using sample data only") # Simple word cloud fallback try: from wordcloud import WordCloud WORDCLOUD_AVAILABLE = True except ImportError: WORDCLOUD_AVAILABLE = False print("WordCloud not available - skipping word cloud generation") @dataclass class MentionAlert: """Data class for mention alerts""" id: str content: str platform: str author: str sentiment: str urgency: str # high, medium, low timestamp: datetime engagement: int url: str class EnhancedBrandPerceptionMonitor: def extract_keywords(self, texts: List[str], top_k=10) -> List[Tuple[str, float]]: """Enhanced keyword extraction with domain-specific logic""" if not texts: return [ ("university", 0.8), ("admission", 0.6), ("counseling", 0.5), ("application", 0.4), ("student", 0.3), ("guidance", 0.25), ("study", 0.2), ("abroad", 0.18), ("visa", 0.15), ("scholarship", 0.12) ] # Enhanced stopwords for education domain stopwords = { 'the', 'and', 'for', 'are', 'with', 'this', 'that', 'was', 'were', 'been', 'have', 'has', 'had', 'will', 'would', 'could', 'should', 'can', 'may', 'might', 'must', 'shall', 'leapscholar', 'leap', 'scholar', 'from', 'they', 'them', 'their', 'there', 'where', 'when', 'what', 'who', 'how', 'why', 'which', 'than', 'then', 'more', 'most', 'some', 'any', 'all', 'each', 'every', 'many', 'much', 'few', 'little', 'big', 'small', 'large', 'good', 'bad', 'very', 'really', 'just', 'like', 'get', 'got', 'going', 'go' } all_words = [] for text in texts: # Extract meaningful phrases and words words = re.findall(r'\b[a-zA-Z]{3,}\b', text.lower()) meaningful_words = [w for w in words if w not in stopwords and len(w) > 3] all_words.extend(meaningful_words) if not all_words: return [("university", 0.8), ("admission", 0.6), ("counseling", 0.5)] word_freq = Counter(all_words) total_words = len(all_words) # Calculate relative frequency keywords = [(word, count/total_words) for word, count in word_freq.most_common(top_k)] return keywords if keywords else [("university", 0.8), ("admission", 0.6)] def __init__(self): """Initialize the Enhanced Brand Perception Monitor""" self.brand_name = "LeapScholar" self.competitors = ["IDP", "Yocket", "Leverage Edu", "Collegedunia", "Shiksha"] self.setup_models() self.data_cache = {} self.alerts_cache = [] self.sentiment_history = [] def setup_models(self): """Initialize sentiment analysis and other components""" print("🤖 Setting up enhanced analytics engine...") # Enhanced sentiment lexicon self.sentiment_patterns = { 'positive_strong': ['amazing', 'excellent', 'outstanding', 'fantastic', 'brilliant', 'phenomenal', 'exceptional', 'superb'], 'positive_mild': ['good', 'nice', 'helpful', 'decent', 'okay', 'fine', 'satisfactory'], 'negative_strong': ['terrible', 'awful', 'horrible', 'worst', 'disgusting', 'pathetic', 'useless'], 'negative_mild': ['bad', 'poor', 'disappointing', 'slow', 'expensive', 'confusing'], 'educational_terms': ['university', 'college', 'admission', 'application', 'scholarship', 'visa', 'study abroad'], 'service_terms': ['counseling', 'guidance', 'support', 'help', 'service', 'consultant', 'advisor'] } # Influence scoring factors self.influence_weights = { 'Twitter': {'follower_multiplier': 0.001, 'engagement_weight': 0.3}, 'Reddit': {'karma_multiplier': 0.0001, 'engagement_weight': 0.4}, 'News': {'domain_authority': 0.5, 'engagement_weight': 0.2}, 'LinkedIn': {'connection_multiplier': 0.0005, 'engagement_weight': 0.35} } print("✅ Enhanced analytics engine ready!") print("✅ Competitive analysis module loaded!") print("✅ Alert system initialized!") print("🎯 Advanced setup complete!") def calculate_influence_score(self, mention: Dict) -> float: """Calculate influence score for a mention""" base_score = 1.0 platform = mention.get('platform', 'Unknown') engagement = mention.get('engagement', 0) # Platform-specific scoring if platform == 'Twitter': followers = mention.get('author_followers', 100) base_score = (followers * 0.001) + (engagement * 0.3) elif platform == 'Reddit': karma = mention.get('author_karma', 100) base_score = (karma * 0.0001) + (engagement * 0.4) elif platform == 'News': domain_authority = mention.get('domain_authority', 50) base_score = (domain_authority * 0.5) + (engagement * 0.2) elif platform == 'LinkedIn': connections = mention.get('author_connections', 500) base_score = (connections * 0.0005) + (engagement * 0.35) # Sentiment multiplier sentiment = mention.get('sentiment', 'neutral') if sentiment == 'positive': base_score *= 1.2 elif sentiment == 'negative': base_score *= 1.5 # Negative mentions have higher impact return min(100.0, max(0.1, base_score)) def analyze_sentiment_advanced(self, text: str) -> Dict: """Enhanced sentiment analysis with emotion detection""" try: text_lower = text.lower() # Emotion detection emotions = { 'joy': ['happy', 'excited', 'thrilled', 'delighted', 'pleased'], 'trust': ['reliable', 'trustworthy', 'professional', 'credible'], 'fear': ['worried', 'concerned', 'anxious', 'scared'], 'anger': ['frustrated', 'annoyed', 'angry', 'furious'], 'sadness': ['disappointed', 'sad', 'upset', 'depressed'], 'surprise': ['shocked', 'amazed', 'surprised', 'unexpected'] } detected_emotions = {} for emotion, words in emotions.items(): score = sum(1 for word in words if word in text_lower) / len(words) detected_emotions[emotion] = score if TEXTBLOB_AVAILABLE: blob = TextBlob(text) polarity = blob.sentiment.polarity subjectivity = blob.sentiment.subjectivity if polarity > 0.3: dominant = 'positive' confidence = min(0.95, 0.6 + abs(polarity)) elif polarity < -0.3: dominant = 'negative' confidence = min(0.95, 0.6 + abs(polarity)) else: dominant = 'neutral' confidence = min(0.85, 0.5 + (1 - abs(polarity)) * 0.4) scores = { 'positive': max(0, polarity) if polarity > 0 else 0.1, 'negative': max(0, -polarity) if polarity < 0 else 0.1, 'neutral': max(0.1, 1 - abs(polarity)) } else: # Enhanced pattern-based analysis pos_strong = sum(1 for word in self.sentiment_patterns['positive_strong'] if word in text_lower) pos_mild = sum(1 for word in self.sentiment_patterns['positive_mild'] if word in text_lower) neg_strong = sum(1 for word in self.sentiment_patterns['negative_strong'] if word in text_lower) neg_mild = sum(1 for word in self.sentiment_patterns['negative_mild'] if word in text_lower) pos_score = (pos_strong * 2) + pos_mild neg_score = (neg_strong * 2) + neg_mild if pos_score > neg_score and pos_score > 0: dominant = 'positive' confidence = min(0.9, 0.6 + (pos_score * 0.1)) scores = {'positive': 0.7, 'negative': 0.1, 'neutral': 0.2} elif neg_score > pos_score and neg_score > 0: dominant = 'negative' confidence = min(0.9, 0.6 + (neg_score * 0.1)) scores = {'negative': 0.7, 'positive': 0.1, 'neutral': 0.2} else: dominant = 'neutral' confidence = 0.6 scores = {'neutral': 0.6, 'positive': 0.2, 'negative': 0.2} subjectivity = 0.5 # Default subjectivity # Normalize scores total = sum(scores.values()) scores = {k: v/total for k, v in scores.items()} return { 'sentiment': dominant, 'confidence': confidence, 'scores': scores, 'subjectivity': subjectivity, 'emotions': detected_emotions, 'intensity': 'high' if confidence > 0.8 else 'medium' if confidence > 0.6 else 'low' } except Exception as e: print(f"Enhanced sentiment analysis error: {e}") return { 'sentiment': 'neutral', 'confidence': 0.5, 'scores': {'positive': 0.33, 'negative': 0.33, 'neutral': 0.34}, 'subjectivity': 0.5, 'emotions': {}, 'intensity': 'low' } def extract_themes_and_topics(self, texts: List[str]) -> Dict: """Extract themes, topics, and contextual insights""" try: # Topic categories for education domain topic_keywords = { 'admission_process': ['admission', 'application', 'apply', 'acceptance', 'selection'], 'counseling_quality': ['counselor', 'guidance', 'advice', 'support', 'help'], 'university_selection': ['university', 'college', 'school', 'institution', 'program'], 'documentation': ['documents', 'transcript', 'certificate', 'visa', 'passport'], 'pricing_value': ['price', 'cost', 'fee', 'expensive', 'value', 'worth'], 'timeline_efficiency': ['time', 'fast', 'slow', 'delay', 'quick', 'response'], 'success_outcomes': ['accepted', 'rejected', 'admit', 'scholarship', 'success'], 'platform_experience': ['website', 'app', 'platform', 'interface', 'user experience'] } topic_scores = defaultdict(int) total_mentions = 0 for text in texts: text_lower = text.lower() for topic, keywords in topic_keywords.items(): score = sum(1 for keyword in keywords if keyword in text_lower) topic_scores[topic] += score total_mentions += score # Calculate percentages topic_percentages = {} for topic, score in topic_scores.items(): topic_percentages[topic] = (score / max(1, total_mentions)) * 100 # Sort by relevance sorted_topics = sorted(topic_percentages.items(), key=lambda x: x[1], reverse=True) return { 'topic_distribution': dict(sorted_topics), 'primary_themes': [topic for topic, score in sorted_topics[:3] if score > 5], 'total_topic_mentions': total_mentions } except Exception as e: print(f"Theme extraction error: {e}") return { 'topic_distribution': {}, 'primary_themes': [], 'total_topic_mentions': 0 } def generate_competitive_analysis(self, df: pd.DataFrame) -> Dict: """Generate competitive landscape insights""" competitive_mentions = {} for competitor in self.competitors: mentions = df[df['content'].str.contains(competitor, case=False, na=False)] if len(mentions) > 0: sentiment_dist = mentions['sentiment'].value_counts().to_dict() competitive_mentions[competitor] = { 'total_mentions': len(mentions), 'sentiment_distribution': sentiment_dist, 'average_engagement': mentions['engagement'].mean(), 'recent_trend': 'stable' # Could be enhanced with time series analysis } return competitive_mentions def detect_trending_topics(self, df: pd.DataFrame) -> List[Dict]: """Detect trending topics and emerging discussions""" # Group by time periods and analyze keyword frequency changes df['hour'] = pd.to_datetime(df['timestamp']).dt.hour recent_hours = df[df['hour'] >= (datetime.now().hour - 6)] if len(recent_hours) == 0: return [] # Extract trending keywords from recent mentions recent_content = recent_hours['content'].tolist() recent_keywords = self.extract_keywords(recent_content, top_k=15) trending_topics = [] for keyword, score in recent_keywords[:5]: # Calculate sentiment for this keyword keyword_mentions = df[df['content'].str.contains(keyword, case=False, na=False)] if len(keyword_mentions) > 0: keyword_sentiment = keyword_mentions['sentiment'].value_counts().to_dict() trending_topics.append({ 'keyword': keyword, 'score': score, 'mentions': len(keyword_mentions), 'sentiment_breakdown': keyword_sentiment, 'trend_direction': 'rising' # Could be enhanced with historical comparison }) return trending_topics def generate_alerts(self, df: pd.DataFrame) -> List[MentionAlert]: """Generate alerts for mentions requiring immediate attention""" alerts = [] # High-priority negative mentions high_impact_negative = df[ (df['sentiment'] == 'negative') & (df['sentiment_confidence'] > 0.7) & (df['engagement'] > df['engagement'].quantile(0.8)) ] for _, mention in high_impact_negative.iterrows(): alert = MentionAlert( id=hashlib.md5(mention['content'].encode()).hexdigest()[:8], content=mention['content'], platform=mention['platform'], author=mention['author'], sentiment=mention['sentiment'], urgency='high', timestamp=mention['timestamp'], engagement=mention['engagement'], url=mention['url'] ) alerts.append(alert) # Medium-priority: Competitor mentions competitor_mentions = df[df['content'].str.contains('|'.join(self.competitors), case=False, na=False)] for _, mention in competitor_mentions.head(3).iterrows(): alert = MentionAlert( id=hashlib.md5(mention['content'].encode()).hexdigest()[:8], content=mention['content'], platform=mention['platform'], author=mention['author'], sentiment=mention.get('sentiment', 'neutral'), urgency='medium', timestamp=mention['timestamp'], engagement=mention['engagement'], url=mention['url'] ) alerts.append(alert) return alerts[:10] # Limit to top 10 alerts def generate_enhanced_sample_data(self) -> List[Dict]: """Generate comprehensive sample data with enhanced metrics""" sample_data = [] # Enhanced Twitter samples with more realistic data twitter_samples = [ { "content": "Just got accepted to Stanford! 🎉 LeapScholar's counseling was incredible - they helped me craft the perfect SOP and prepared me for interviews. Worth every rupee! #StudyAbroad #Stanford", "sentiment_type": "positive", "author_followers": 1200, "engagement_rate": 0.08 }, { "content": "LeapScholar vs IDP - which is better for MS applications? Need honest reviews from people who've used both services. Planning for Fall 2025 intake.", "sentiment_type": "neutral", "author_followers": 450, "engagement_rate": 0.12 }, { "content": "Had a terrible experience with LeapScholar. Counselor was unprepared, gave outdated info about visa requirements. Wasted 3 months and ₹50k. Looking for alternatives now.", "sentiment_type": "negative", "author_followers": 800, "engagement_rate": 0.15 }, { "content": "LeapScholar's mock interview sessions are game-changers! Went from nervous wreck to confident applicant. Got into 4/6 universities I applied to! 🚀", "sentiment_type": "positive", "author_followers": 2300, "engagement_rate": 0.06 }, { "content": "Comparing study abroad consultants: LeapScholar ₹45k, IDP ₹30k, Yocket ₹25k. Price vs quality - what's your experience?", "sentiment_type": "neutral", "author_followers": 650, "engagement_rate": 0.18 } ] # Enhanced Reddit samples reddit_samples = [ { "content": "Detailed LeapScholar Review: Used them for MS in CS applications. Got into CMU, UT Austin, and UCSD. Their essay editing is top-notch, but pricing is on the higher side. Overall rating: 8/10", "sentiment_type": "positive", "author_karma": 15000, "engagement_rate": 0.25 }, { "content": "AVOID LeapScholar! They provided incorrect GRE score requirements for my target universities. Had to scramble and retake GRE. Cost me an entire application cycle.", "sentiment_type": "negative", "author_karma": 8500, "engagement_rate": 0.35 }, { "content": "LeapScholar counselor helped me pivot from ECE to Data Science programs. Identified perfect-fit universities I never knew existed. Now at Georgia Tech!", "sentiment_type": "positive", "author_karma": 12000, "engagement_rate": 0.20 } ] # Enhanced News samples with domain authority news_samples = [ { "content": "LeapScholar raises $50M Series C to expand AI-powered university matching platform across Southeast Asia", "sentiment_type": "positive", "domain_authority": 85, "engagement_rate": 0.05 }, { "content": "Indian EdTech sector consolidation: LeapScholar acquires smaller competitor to strengthen market position", "sentiment_type": "positive", "domain_authority": 78, "engagement_rate": 0.03 } ] # LinkedIn samples linkedin_samples = [ { "content": "Grateful to LeapScholar for their exceptional guidance. Just started my MBA at Wharton! Their industry connections and alumni network made all the difference.", "sentiment_type": "positive", "author_connections": 5000, "engagement_rate": 0.12 } ] platforms_data = [ ("Twitter", twitter_samples), ("Reddit", reddit_samples), ("News", news_samples), ("LinkedIn", linkedin_samples) ] for platform_name, samples in platforms_data: for i, sample in enumerate(samples): engagement_base = { 'Twitter': (50, 800), 'Reddit': (20, 500), 'News': (100, 2000), 'LinkedIn': (30, 400) } engagement = np.random.randint(*engagement_base.get(platform_name, (10, 100))) sample_data.append({ 'platform': platform_name, 'content': sample['content'], 'author': f"{platform_name.lower()}_user_{i+1}" if platform_name != "News" else f"NewsOutlet_{i+1}", 'timestamp': datetime.now() - timedelta( days=np.random.randint(0, 7), hours=np.random.randint(0, 24), minutes=np.random.randint(0, 60) ), 'url': f"https://{platform_name.lower()}.com/post_{i+1}", 'engagement': engagement, 'expected_sentiment': sample['sentiment_type'], 'author_followers': sample.get('author_followers', np.random.randint(100, 1000)), 'author_karma': sample.get('author_karma', np.random.randint(500, 10000)), 'author_connections': sample.get('author_connections', np.random.randint(200, 3000)), 'domain_authority': sample.get('domain_authority', np.random.randint(40, 90)), 'engagement_rate': sample.get('engagement_rate', np.random.uniform(0.02, 0.15)), 'reach_estimate': engagement * np.random.randint(10, 50) }) return sample_data def collect_all_data(self) -> pd.DataFrame: """Collect and process data from all platforms""" print("🔍 Collecting comprehensive data from all platforms...") # Use enhanced sample data all_data = self.generate_enhanced_sample_data() # Convert to DataFrame df = pd.DataFrame(all_data) # Enhanced sentiment analysis print("🤖 Performing advanced sentiment analysis...") sentiment_results = [self.analyze_sentiment_advanced(content) for content in df['content']] df['sentiment'] = [r['sentiment'] for r in sentiment_results] df['sentiment_confidence'] = [r['confidence'] for r in sentiment_results] df['sentiment_scores'] = [r['scores'] for r in sentiment_results] df['subjectivity'] = [r['subjectivity'] for r in sentiment_results] df['sentiment_intensity'] = [r['intensity'] for r in sentiment_results] df['emotions'] = [r['emotions'] for r in sentiment_results] # Calculate influence scores print("📈 Calculating influence scores...") df['influence_score'] = df.apply(lambda row: self.calculate_influence_score(row.to_dict()), axis=1) return df def generate_comprehensive_insights(self, df: pd.DataFrame) -> Dict: """Generate comprehensive insights with advanced analytics""" print("📊 Generating comprehensive insights...") insights = {} # Basic metrics (enhanced) insights['total_mentions'] = len(df) insights['platforms'] = df['platform'].value_counts().to_dict() insights['total_reach'] = df['reach_estimate'].sum() insights['average_engagement_rate'] = df['engagement_rate'].mean() insights['total_influence_score'] = df['influence_score'].sum() # Sentiment analysis (enhanced) sentiment_dist = df['sentiment'].value_counts() insights['sentiment_distribution'] = sentiment_dist.to_dict() insights['sentiment_percentages'] = (sentiment_dist / len(df) * 100).round(1).to_dict() insights['weighted_sentiment'] = ( df.groupby('sentiment')['influence_score'].sum() / df['influence_score'].sum() * 100 ).round(1).to_dict() # Sentiment intensity distribution intensity_dist = df['sentiment_intensity'].value_counts() insights['sentiment_intensity'] = intensity_dist.to_dict() # Platform analytics platform_metrics = df.groupby('platform').agg({ 'engagement': ['mean', 'sum'], 'influence_score': ['mean', 'sum'], 'sentiment_confidence': 'mean', 'reach_estimate': 'sum' }).round(2) insights['platform_analytics'] = platform_metrics.to_dict() # Time-based insights df['hour'] = pd.to_datetime(df['timestamp']).dt.hour df['day_of_week'] = pd.to_datetime(df['timestamp']).dt.day_name() hourly_activity = df.groupby('hour').size().to_dict() insights['hourly_activity'] = hourly_activity insights['peak_activity_hour'] = max(hourly_activity.items(), key=lambda x: x[1])[0] daily_activity = df.groupby('day_of_week').size().to_dict() insights['daily_activity'] = daily_activity # Content insights all_content = df['content'].tolist() keywords = self.extract_keywords(all_content, top_k=15) insights['top_keywords'] = keywords # Theme analysis theme_analysis = self.extract_themes_and_topics(all_content) insights.update(theme_analysis) # Trending topics insights['trending_topics'] = self.detect_trending_topics(df) # Competitive analysis insights['competitive_landscape'] = self.generate_competitive_analysis(df) # High-impact mentions high_impact = df.nlargest(5, 'influence_score')[ ['content', 'platform', 'engagement', 'sentiment', 'influence_score', 'author'] ].to_dict('records') insights['high_impact_mentions'] = high_impact # Negative sentiment deep dive negative_mentions = df[df['sentiment'] == 'negative'].sort_values('influence_score', ascending=False) insights['critical_negative_mentions'] = negative_mentions.head(3)[ ['content', 'platform', 'author', 'url', 'timestamp', 'influence_score'] ].to_dict('records') # Performance benchmarks insights['performance_benchmarks'] = { 'sentiment_health_score': ( insights['sentiment_percentages'].get('positive', 0) * 1.0 + insights['sentiment_percentages'].get('neutral', 0) * 0.5 + insights['sentiment_percentages'].get('negative', 0) * -1.0 ), 'engagement_health': 'high' if insights['average_engagement_rate'] > 0.1 else 'medium' if insights['average_engagement_rate'] > 0.05 else 'low', 'brand_momentum': 'positive' if insights['sentiment_percentages'].get('positive', 0) > 60 else 'stable' if insights['sentiment_percentages'].get('positive', 0) > 40 else 'needs_attention' } # Generate alerts insights['alerts'] = self.generate_alerts(df) return insights def create_advanced_visualizations(self, df: pd.DataFrame, insights: Dict) -> Tuple: """Create comprehensive visualization suite""" colors = { 'positive': '#2E8B57', 'negative': '#DC143C', 'neutral': '#4682B4', 'brand': '#FF6B35', 'competitor': '#845EC2' } # 1. Enhanced Sentiment Distribution with Influence Weighting fig_sentiment = make_subplots( rows=1, cols=2, specs=[[{"type": "pie"}, {"type": "pie"}]], subplot_titles=("Volume-based Sentiment", "Influence-weighted Sentiment") ) # Volume-based pie sentiment_labels = list(insights['sentiment_percentages'].keys()) sentiment_values = list(insights['sentiment_percentages'].values()) fig_sentiment.add_trace( go.Pie( labels=sentiment_labels, values=sentiment_values, marker_colors=[colors.get(label, '#808080') for label in sentiment_labels], textinfo='label+percent', name="Volume" ), row=1, col=1 ) # Influence-weighted pie weighted_labels = list(insights['weighted_sentiment'].keys()) weighted_values = list(insights['weighted_sentiment'].values()) fig_sentiment.add_trace( go.Pie( labels=weighted_labels, values=weighted_values, marker_colors=[colors.get(label, '#808080') for label in weighted_labels], textinfo='label+percent', name="Weighted" ), row=1, col=2 ) fig_sentiment.update_layout(height=400, showlegend=True, title_text="Sentiment Analysis Comparison") # 2. Platform Performance Dashboard platforms = list(insights['platforms'].keys()) platform_data = insights['platform_analytics'] fig_platforms = make_subplots( rows=2, cols=2, subplot_titles=("Mentions by Platform", "Average Engagement", "Total Influence", "Reach by Platform"), specs=[[{"type": "bar"}, {"type": "bar"}], [{"type": "bar"}, {"type": "bar"}]] ) # Mentions fig_platforms.add_trace( go.Bar(x=platforms, y=list(insights['platforms'].values()), marker_color=colors['brand'], name="Mentions"), row=1, col=1 ) # Average engagement (if data available) if 'engagement' in platform_data and 'mean' in platform_data['engagement']: avg_engagement = [platform_data['engagement']['mean'].get(p, 0) for p in platforms] fig_platforms.add_trace( go.Bar(x=platforms, y=avg_engagement, marker_color=colors['competitor'], name="Avg Engagement"), row=1, col=2 ) # Total influence if 'influence_score' in platform_data and 'sum' in platform_data['influence_score']: total_influence = [platform_data['influence_score']['sum'].get(p, 0) for p in platforms] fig_platforms.add_trace( go.Bar(x=platforms, y=total_influence, marker_color=colors['positive'], name="Total Influence"), row=2, col=1 ) # Reach if 'reach_estimate' in platform_data and 'sum' in platform_data['reach_estimate']: total_reach = [platform_data['reach_estimate']['sum'].get(p, 0) for p in platforms] fig_platforms.add_trace( go.Bar(x=platforms, y=total_reach, marker_color=colors['neutral'], name="Total Reach"), row=2, col=2 ) fig_platforms.update_layout(height=500, showlegend=False, title_text="Platform Performance Analytics") # 3. Sentiment Timeline with Moving Average df['date'] = pd.to_datetime(df['timestamp']).dt.date daily_sentiment = df.groupby(['date', 'sentiment']).size().unstack(fill_value=0) fig_timeline = go.Figure() for sentiment in ['positive', 'negative', 'neutral']: if sentiment in daily_sentiment.columns: fig_timeline.add_trace(go.Scatter( x=daily_sentiment.index, y=daily_sentiment[sentiment], mode='lines+markers', name=sentiment.title(), line=dict(color=colors.get(sentiment, '#808080'), width=3), marker=dict(size=8) )) # Add overall trend line daily_total = daily_sentiment.sum(axis=1) fig_timeline.add_trace(go.Scatter( x=daily_sentiment.index, y=daily_total, mode='lines', name='Total Mentions', line=dict(color='black', width=2, dash='dash'), yaxis='y2' )) fig_timeline.update_layout( title="Sentiment Timeline with Trend Analysis", xaxis_title="Date", yaxis_title="Sentiment Mentions", yaxis2=dict(title="Total Mentions", overlaying='y', side='right'), height=400, hovermode='x unified' ) # 4. Topic Distribution Radar Chart topic_data = insights.get('topic_distribution', {}) if topic_data: fig_topics = go.Figure() topics = list(topic_data.keys())[:8] # Top 8 topics values = [topic_data.get(topic, 0) for topic in topics] fig_topics.add_trace(go.Scatterpolar( r=values, theta=topics, fill='toself', marker=dict(color=colors['brand']), line=dict(color=colors['brand']), name='Topic Distribution' )) fig_topics.update_layout( polar=dict( radialaxis=dict(visible=True, range=[0, max(values) * 1.1]) ), title="Topic Distribution Analysis", height=400 ) else: fig_topics = go.Figure().add_annotation(text="No topic data available", showarrow=False) # 5. Competitive Landscape competitive_data = insights.get('competitive_landscape', {}) if competitive_data: competitors = list(competitive_data.keys()) competitor_mentions = [competitive_data[comp]['total_mentions'] for comp in competitors] competitor_sentiment = [ competitive_data[comp]['sentiment_distribution'].get('positive', 0) / max(1, competitive_data[comp]['total_mentions']) * 100 for comp in competitors ] fig_competitive = go.Figure() fig_competitive.add_trace(go.Scatter( x=competitor_mentions, y=competitor_sentiment, mode='markers+text', text=competitors, textposition="top center", marker=dict( size=[competitive_data[comp]['average_engagement']/10 for comp in competitors], color=colors['competitor'], opacity=0.7, line=dict(width=2, color='white') ), name='Competitors' )) fig_competitive.update_layout( title="Competitive Landscape Analysis", xaxis_title="Total Mentions", yaxis_title="Positive Sentiment %", height=400, showlegend=False ) else: fig_competitive = go.Figure().add_annotation(text="No competitive data available", showarrow=False) # 6. Influence vs Engagement Scatter fig_influence = px.scatter( df, x='engagement', y='influence_score', color='sentiment', size='reach_estimate', hover_data=['platform', 'author'], color_discrete_map=colors, title="Influence vs Engagement Analysis" ) fig_influence.update_layout(height=400) return fig_sentiment, fig_platforms, fig_timeline, fig_topics, fig_competitive, fig_influence def create_enhanced_dashboard(): """Create the comprehensive Gradio dashboard""" monitor = EnhancedBrandPerceptionMonitor() def analyze_brand_perception(): """Main analysis function with comprehensive reporting""" # Collect and analyze data df = monitor.collect_all_data() insights = monitor.generate_comprehensive_insights(df) # Create visualizations viz_results = monitor.create_advanced_visualizations(df, insights) (fig_sentiment, fig_platforms, fig_timeline, fig_topics, fig_competitive, fig_influence) = viz_results # Generate executive summary total_mentions = insights['total_mentions'] total_reach = insights['total_reach'] health_score = insights['performance_benchmarks']['sentiment_health_score'] brand_momentum = insights['performance_benchmarks']['brand_momentum'] # Health score interpretation if health_score > 30: health_status = "🟢 Excellent" health_emoji = "🟢" elif health_score > 10: health_status = "🟡 Good" health_emoji = "🟡" elif health_score > -10: health_status = "🟠 Fair" health_emoji = "🟠" else: health_status = "🔴 Needs Attention" health_emoji = "🔴" # Brand momentum emoji momentum_emoji = "📈" if brand_momentum == "positive" else "📊" if brand_momentum == "stable" else "📉" # Sentiment summary with influence weighting sentiment_summary = "" for sentiment, percentage in insights['sentiment_percentages'].items(): weighted_pct = insights['weighted_sentiment'].get(sentiment, 0) emoji = "🟢" if sentiment == "positive" else "🔴" if sentiment == "negative" else "🟡" sentiment_summary += f"{emoji} **{sentiment.title()}:** {percentage:.1f}% (weighted: {weighted_pct:.1f}%)\n" # Generate executive report executive_summary = f""" # 📊 LeapScholar Enhanced Brand Perception Report **Generated:** {datetime.now().strftime('%Y-%m-%d %H:%M:%S')} | **Health Score:** {health_status} ({health_score:.1f}) ## 🎯 Executive Summary - **Total Mentions:** {total_mentions:,} | **Total Reach:** {total_reach:,} - **Brand Momentum:** {momentum_emoji} {brand_momentum.replace('_', ' ').title()} - **Avg Engagement Rate:** {insights['average_engagement_rate']:.1%} - **Total Influence Score:** {insights['total_influence_score']:.1f} ## 📈 Sentiment Analysis {sentiment_summary} ## 🔥 Key Themes & Topics """ # Add primary themes primary_themes = insights.get('primary_themes', []) if primary_themes: for theme in primary_themes[:3]: theme_score = insights['topic_distribution'].get(theme, 0) executive_summary += f"• **{theme.replace('_', ' ').title()}** ({theme_score:.1f}% of discussions)\n" else: executive_summary += "• No dominant themes identified\n" # Trending topics section trending_section = "\n## 🚀 Trending Topics\n" trending_topics = insights.get('trending_topics', []) if trending_topics: for i, topic in enumerate(trending_topics[:3], 1): trending_section += f"{i}. **{topic['keyword'].title()}** - {topic['mentions']} mentions (trending {topic['trend_direction']})\n" else: trending_section += "• No trending topics detected in recent activity\n" # Competitive landscape competitive_section = "\n## 🏆 Competitive Landscape\n" competitive_data = insights.get('competitive_landscape', {}) if competitive_data: for competitor, data in list(competitive_data.items())[:3]: pos_sentiment = data['sentiment_distribution'].get('positive', 0) total_comp_mentions = data['total_mentions'] pos_pct = (pos_sentiment / max(1, total_comp_mentions)) * 100 competitive_section += f"• **{competitor}:** {total_comp_mentions} mentions, {pos_pct:.1f}% positive\n" else: competitive_section += "• Limited competitive mention data available\n" # High-impact mentions impact_section = "\n## 🎯 High-Impact Mentions\n" high_impact = insights.get('high_impact_mentions', []) for i, mention in enumerate(high_impact[:3], 1): emoji = "🟢" if mention['sentiment'] == "positive" else "🔴" if mention['sentiment'] == "negative" else "🟡" impact_section += f""" **{i}. {mention['platform']} {emoji} (Influence: {mention['influence_score']:.1f})** > "{mention['content'][:120]}..." *by @{mention['author']} | {mention['engagement']} engagements* """ # Alerts and action items alerts_section = "\n## 🚨 Priority Alerts\n" alerts = insights.get('alerts', []) if alerts: high_priority = [a for a in alerts if a.urgency == 'high'] if high_priority: alerts_section += "### High Priority 🔴\n" for alert in high_priority[:2]: alerts_section += f""" **{alert.platform} - @{alert.author}** > "{alert.content[:150]}..." 📅 {alert.timestamp.strftime('%Y-%m-%d %H:%M')} | 🔗 [View Post]({alert.url}) """ medium_priority = [a for a in alerts if a.urgency == 'medium'] if medium_priority: alerts_section += "\n### Medium Priority 🟡\n" for alert in medium_priority[:2]: alerts_section += f"• {alert.platform}: {alert.content[:80]}...\n" else: alerts_section += "✅ **No critical alerts** - Brand sentiment is healthy!\n" # Action recommendations recommendations_section = "\n## 💡 Strategic Recommendations\n" if health_score < 0: recommendations_section += "🔴 **Immediate Action Required:**\n" recommendations_section += "• Address negative sentiment drivers identified in alerts\n" recommendations_section += "• Implement proactive customer outreach program\n" recommendations_section += "• Review and improve service delivery processes\n\n" if insights['sentiment_percentages'].get('positive', 0) > 70: recommendations_section += "🟢 **Leverage Positive Momentum:**\n" recommendations_section += "• Amplify positive testimonials and success stories\n" recommendations_section += "• Encourage satisfied customers to share experiences\n" recommendations_section += "• Consider case study development from top mentions\n\n" # Always include growth recommendations recommendations_section += "📈 **Growth Opportunities:**\n" peak_hour = insights.get('peak_activity_hour', 12) recommendations_section += f"• Optimize posting schedule around peak activity ({peak_hour}:00)\n" recommendations_section += "• Engage with high-influence mentions for partnership opportunities\n" recommendations_section += "• Monitor competitive mentions for market intelligence\n" # Platform insights platform_section = "\n## 📱 Platform Performance\n" for platform, count in insights['platforms'].items(): percentage = (count / total_mentions * 100) if total_mentions > 0 else 0 platform_section += f"• **{platform}:** {count} mentions ({percentage:.1f}%)\n" # Combine all sections full_report = (executive_summary + trending_section + competitive_section + impact_section + platform_section + alerts_section + recommendations_section) # Generate alerts summary for separate display alerts_summary = f"**{len(alerts)} Total Alerts** | High: {len([a for a in alerts if a.urgency == 'high'])} | Medium: {len([a for a in alerts if a.urgency == 'medium'])}" return ( full_report, fig_sentiment, fig_platforms, fig_timeline, fig_topics, fig_competitive, fig_influence, alerts_summary, f"Last updated: {datetime.now().strftime('%H:%M:%S')}" ) def export_report(): """Export comprehensive report""" timestamp = datetime.now().strftime('%Y%m%d_%H%M%S') return f"Report exported as LeapScholar_Brand_Report_{timestamp}.pdf (Feature coming soon!)" def refresh_data(): """Refresh all dashboard data""" return analyze_brand_perception() # Create the enhanced Gradio interface with gr.Blocks( title="LeapScholar Enhanced Brand Perception Monitor", theme=gr.themes.Soft() # Use a built-in theme instead ) as demo: gr.Markdown(""" # 🎯 LeapScholar Enhanced Brand Perception Monitor ### Comprehensive brand monitoring with advanced analytics, competitive intelligence, and actionable insights """) # Control panel with gr.Row(): with gr.Column(scale=2): refresh_btn = gr.Button("🔄 Refresh Data", variant="primary", size="lg") export_btn = gr.Button("📊 Export Report", variant="secondary", size="lg") with gr.Column(scale=2): alerts_display = gr.Textbox(label="🚨 Alert Summary", interactive=False) with gr.Column(scale=1): last_updated = gr.Textbox(label="⏰ Last Updated", interactive=False) # Main content area with gr.Row(): with gr.Column(scale=3): report = gr.Markdown(label="📋 Executive Dashboard", height=600) with gr.Column(scale=2): sentiment_chart = gr.Plot(label="📊 Sentiment Analysis") # Analytics grid with gr.Row(): with gr.Column(): platform_chart = gr.Plot(label="📱 Platform Analytics") with gr.Column(): timeline_chart = gr.Plot(label="📈 Sentiment Timeline") with gr.Row(): with gr.Column(): topics_chart = gr.Plot(label="🏷️ Topic Distribution") with gr.Column(): competitive_chart = gr.Plot(label="🏆 Competitive Analysis") with gr.Row(): influence_chart = gr.Plot(label="🎯 Influence vs Engagement Analysis") # Footer with additional info gr.Markdown(""" --- **Enhanced Features:** Sentiment intensity analysis, competitive monitoring, influence scoring, trending topic detection, automated alerts, and strategic recommendations. *Powered by advanced NLP and social media analytics* """) def safe_analyze_brand_perception(): """Safe wrapper for analysis function""" try: return analyze_brand_perception() except Exception as e: error_msg = f"Error loading data: {str(e)}" empty_fig = go.Figure().add_annotation(text="No data", showarrow=False) return ( error_msg, # report empty_fig, # sentiment_chart empty_fig, # platform_chart empty_fig, # timeline_chart empty_fig, # topics_chart empty_fig, # competitive_chart empty_fig, # influence_chart "No alerts", # alerts_display "Error" # last_updated ) # Use the safe version (optional): demo.load( fn=safe_analyze_brand_perception, outputs=[ report, sentiment_chart, platform_chart, timeline_chart, topics_chart, competitive_chart, influence_chart, alerts_display, last_updated ] ) return demo # Additional utility functions def extract_keywords(texts: List[str], top_k=10) -> List[Tuple[str, float]]: """Enhanced keyword extraction with domain-specific logic""" if not texts: return [ ("university", 0.8), ("admission", 0.6), ("counseling", 0.5), ("application", 0.4), ("student", 0.3), ("guidance", 0.25), ("study", 0.2), ("abroad", 0.18), ("visa", 0.15), ("scholarship", 0.12) ] # Enhanced stopwords for education domain stopwords = { 'the', 'and', 'for', 'are', 'with', 'this', 'that', 'was', 'were', 'been', 'have', 'has', 'had', 'will', 'would', 'could', 'should', 'can', 'may', 'might', 'must', 'shall', 'leapscholar', 'leap', 'scholar', 'from', 'they', 'them', 'their', 'there', 'where', 'when', 'what', 'who', 'how', 'why', 'which', 'than', 'then', 'more', 'most', 'some', 'any', 'all', 'each', 'every', 'many', 'much', 'few', 'little', 'big', 'small', 'large', 'good', 'bad', 'very', 'really', 'just', 'like', 'get', 'got', 'going', 'go' } all_words = [] for text in texts: # Extract meaningful phrases and words words = re.findall(r'\b[a-zA-Z]{3,}\b', text.lower()) meaningful_words = [w for w in words if w not in stopwords and len(w) > 3] all_words.extend(meaningful_words) if not all_words: return [("university", 0.8), ("admission", 0.6), ("counseling", 0.5)] word_freq = Counter(all_words) total_words = len(all_words) # Calculate relative frequency keywords = [(word, count/total_words) for word, count in word_freq.most_common(top_k)] return keywords if keywords else [("university", 0.8), ("admission", 0.6)] if __name__ == "__main__": print("🚀 Starting Enhanced LeapScholar Brand Perception Monitor...") print("✨ New Features: Advanced sentiment analysis, competitive monitoring, influence scoring") print("📊 Enhanced Analytics: Topic modeling, trending detection, strategic recommendations") dashboard = create_enhanced_dashboard() dashboard.launch( server_name="0.0.0.0", server_port=7860, share=True, debug=False )