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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """app.ipynb
3
+
4
+ Automatically generated by Colab.
5
+
6
+ Original file is located at
7
+ https://colab.research.google.com/drive/1d0w1AQ1zJrRThcbqlHqZWeJl36xmI4Hy
8
+ """
9
+
10
+
11
+
12
+ !pip install transformers keybert pandas numpy gradio plotly wordcloud matplotlib youtube-comment-downloader
13
+
14
+
15
+
16
+
17
+
18
+ import pandas as pd
19
+ import numpy as np
20
+ import matplotlib.pyplot as plt
21
+ import plotly.express as px
22
+ import plotly.graph_objects as go
23
+ from plotly.subplots import make_subplots
24
+ import io
25
+ import base64
26
+ import random
27
+ from datetime import datetime, timedelta
28
+ from collections import Counter
29
+ import gradio as gr
30
+ from wordcloud import WordCloud
31
+ import os
32
+
33
+ from transformers import pipeline
34
+ from keybert import KeyBERT
35
+
36
+ from transformers import pipeline
37
+ from keybert import KeyBERT
38
+ from youtube_comment_downloader import YoutubeCommentDownloader
39
+ from datetime import datetime, timedelta
40
+ import re
41
+ import pandas as pd
42
+
43
+
44
+
45
+ # Initialize models globally
46
+ classifier = pipeline("sentiment-analysis", model="cardiffnlp/twitter-roberta-base-sentiment-latest")
47
+ kw_model = KeyBERT()
48
+
49
+ # Label mapping - handling different model outputs
50
+ sentiment_map = {
51
+ "LABEL_0": "Negative", "LABEL_1": "Neutral", "LABEL_2": "Positive", # RoBERTa format
52
+ "negative": "Negative", "neutral": "Neutral", "positive": "Positive", # Standard format
53
+ "NEGATIVE": "Negative", "NEUTRAL": "Neutral", "POSITIVE": "Positive" # Uppercase format
54
+ }
55
+ color_map = {"Positive": "#2E8B57", "Neutral": "#4682B4", "Negative": "#CD5C5C"}
56
+
57
+
58
+
59
+ # Default comments for when no file is uploaded
60
+ comments = [
61
+ "This new distance fare is really fair. I pay less for short trips!",
62
+ "It's confusing, I don't know how much I'll pay now.",
63
+ "RURA should have informed us better about this change.",
64
+ "Good step towards fairness and modernization.",
65
+ "Too expensive now! I hate this new system.",
66
+ "The distance-based system makes so much more sense than flat rates.",
67
+ "Why should I pay the same for 1km as I would for 10km? This is better.",
68
+ "Finally a fair system — short-distance commuters benefit the most!",
69
+ "I'm still unsure how the new rates are calculated. Needs clarity.",
70
+ "A detailed public awareness campaign would have helped a lot.",
71
+ "Smart move toward a fairer system, but more awareness is needed.",
72
+ "I'm paying more now and it feels unjust.",
73
+ "Flat rates were easier to understand, but this is more logical.",
74
+ "Paying based on distance is reasonable, but it needs fine-tuning.",
75
+ "App crashes when I try to calculate my fare. Fix it!",
76
+ "Drivers are confused about the new system too.",
77
+ "Great initiative but poor implementation.",
78
+ "Now I know exactly what I'm paying for. Transparent and fair.",
79
+ "The fare calculator is very helpful.",
80
+ "Bus company profits will increase, but what about us passengers?",
81
+ "I've noticed faster service since the new system launched.",
82
+ "Rural areas are being charged too much now.",
83
+ "The new system is making my daily commute more expensive.",
84
+ "Distance-based fares are the future of transportation.",
85
+ "I appreciate the transparency but the app needs work.",
86
+ "This discriminates against people living in rural areas!",
87
+ "My transportation costs have decreased by 30%!",
88
+ "We should go back to the old system immediately.",
89
+ "Kids going to school are now paying more, this is unfair.",
90
+ "The government did a good job explaining the benefits.",
91
+ "I've waited years for a fair pricing system like this.",
92
+ "Very impressed with the new fare calculation technology.",
93
+ "The app is too complicated for elderly passengers.",
94
+ "The transition period should have been longer.",
95
+ "I find the new fare calculator very intuitive.",
96
+ "This is just another way to extract more money from us.",
97
+ "Love how I can now predict exactly what my trip will cost.",
98
+ "The implementation was rushed without proper testing.",
99
+ "Prices vary too much depending on traffic congestion.",
100
+ "Works well in urban areas but rural commuters are suffering.",
101
+ "I've downloaded the fare calculator app - it's brilliant!",
102
+ "Taxi drivers are confused about calculating fares correctly."
103
+ ]
104
+
105
+ # Global variable to hold the current dataframe
106
+ global_df = None
107
+
108
+ # Function to generate default dataset from predefined comments
109
+
110
+ def generate_default_df():
111
+ global global_df
112
+ default_data = []
113
+ start_time = datetime.now() - timedelta(hours=24)
114
+
115
+ for i, comment in enumerate(comments):
116
+ timestamp = start_time + timedelta(hours=random.uniform(0, 24))
117
+
118
+ # Analyze sentiment
119
+ result = classifier(comment)[0]
120
+ sentiment = sentiment_map[result["label"]]
121
+ score = round(result["score"], 3)
122
+
123
+ # Extract keywords
124
+ try:
125
+ keywords = kw_model.extract_keywords(comment, top_n=3)
126
+ keyword_str = ", ".join([kw[0] for kw in keywords]) if keywords else "N/A"
127
+ except:
128
+ keyword_str = "N/A"
129
+
130
+ default_data.append({
131
+ "Datetime": timestamp,
132
+ "Text": comment,
133
+ "Sentiment": sentiment,
134
+ "Score": score,
135
+ "Keywords": keyword_str
136
+ })
137
+
138
+ default_df = pd.DataFrame(default_data)
139
+ default_df["Datetime"] = pd.to_datetime(default_df["Datetime"])
140
+ default_df["Datetime"] = default_df["Datetime"].dt.floor("1H")
141
+ global_df = default_df.sort_values("Datetime").reset_index(drop=True)
142
+ return global_df
143
+
144
+
145
+
146
+ import re
147
+ from datetime import datetime, timedelta
148
+
149
+ def convert_relative_time(relative):
150
+ now = datetime.now()
151
+ try:
152
+ match = re.match(r'(\d+)\s+(second|minute|hour|day|week|month|year)s?\s+ago', relative.lower())
153
+ if not match:
154
+ return now # fallback to now for unknown formats
155
+
156
+ value, unit = int(match.group(1)), match.group(2)
157
+
158
+ if unit == 'second':
159
+ dt = now - timedelta(seconds=value)
160
+ elif unit == 'minute':
161
+ dt = now - timedelta(minutes=value)
162
+ elif unit == 'hour':
163
+ dt = now - timedelta(hours=value)
164
+ elif unit == 'day':
165
+ dt = now - timedelta(days=value)
166
+ elif unit == 'week':
167
+ dt = now - timedelta(weeks=value)
168
+ elif unit == 'month':
169
+ dt = now - timedelta(days=value * 30)
170
+ elif unit == 'year':
171
+ dt = now - timedelta(days=value * 365)
172
+ else:
173
+ dt = now
174
+ except Exception as e:
175
+ print(f"Failed to parse relative time '{relative}': {e}")
176
+ dt = now
177
+ return dt
178
+
179
+ def generate_df(comments):
180
+ global global_df
181
+ default_data = []
182
+
183
+ for comment in comments:
184
+ text = comment.get('text', '')
185
+ timestamp = convert_relative_time(comment.get('time', '0 seconds ago'))
186
+
187
+ # Truncate long text for model input (e.g. 512 tokens)
188
+ truncated_text = text[:512]
189
+
190
+ # Sentiment analysis
191
+ try:
192
+ result = classifier(truncated_text)[0]
193
+ sentiment = sentiment_map.get(result["label"], "Unknown")
194
+ score = round(result["score"], 3)
195
+ except Exception as e:
196
+ print(f"Sentiment classification failed: {e}")
197
+ sentiment = "Unknown"
198
+ score = 0.0
199
+
200
+ # Keyword extraction
201
+ try:
202
+ keywords = kw_model.extract_keywords(truncated_text, top_n=3)
203
+ keyword_str = ", ".join([kw[0] for kw in keywords]) if keywords else "N/A"
204
+ except Exception as e:
205
+ print(f"Keyword extraction failed: {e}")
206
+ keyword_str = "N/A"
207
+
208
+ default_data.append({
209
+ "Datetime": timestamp,
210
+ "Text": text,
211
+ "Sentiment": sentiment,
212
+ "Score": score,
213
+ "Keywords": keyword_str
214
+ })
215
+
216
+ default_df = pd.DataFrame(default_data)
217
+ default_df["Datetime"] = pd.to_datetime(default_df["Datetime"])
218
+ default_df["Datetime"] = default_df["Datetime"].dt.floor("1H")
219
+ global_df = default_df.sort_values("Datetime").reset_index(drop=True)
220
+ return global_df
221
+
222
+
223
+
224
+
225
+
226
+ # Function to process uploaded CSV or Excel file and analyze sentiment
227
+
228
+ def process_uploaded_file(file):
229
+ global global_df
230
+
231
+ if file is None:
232
+ global_df = generate_default_df()
233
+ return global_df
234
+
235
+ try:
236
+ # Read the uploaded file
237
+ if file.name.endswith('.csv'):
238
+ user_df = pd.read_csv(file.name)
239
+ elif file.name.endswith('.xlsx'):
240
+ user_df = pd.read_excel(file.name)
241
+ else:
242
+ raise ValueError("Unsupported file type. Please upload CSV or Excel files only.")
243
+
244
+ # Check required columns
245
+ if 'Text' not in user_df.columns:
246
+ raise ValueError("File must contain a 'Text' column with comments.")
247
+
248
+ # Handle datetime - create if not exists
249
+ if 'Datetime' not in user_df.columns:
250
+ # Generate timestamps for uploaded data
251
+ start_time = datetime.now() - timedelta(hours=len(user_df))
252
+ user_df['Datetime'] = [start_time + timedelta(hours=i) for i in range(len(user_df))]
253
+
254
+ # Clean and prepare data
255
+ user_df = user_df[['Datetime', 'Text']].copy()
256
+ user_df["Datetime"] = pd.to_datetime(user_df["Datetime"])
257
+ user_df["Datetime"] = user_df["Datetime"].dt.floor("1H")
258
+ user_df = user_df.dropna(subset=['Text'])
259
+
260
+ # Analyze sentiment and extract keywords for each comment
261
+ sentiments = []
262
+ scores = []
263
+ keywords_list = []
264
+
265
+ for text in user_df["Text"]:
266
+ try:
267
+ # Sentiment analysis
268
+ result = classifier(str(text))[0]
269
+ sentiment = sentiment_map[result['label']]
270
+ score = round(result['score'], 3)
271
+
272
+ # Keyword extraction
273
+ keywords = kw_model.extract_keywords(str(text), top_n=3)
274
+ keyword_str = ", ".join([kw[0] for kw in keywords]) if keywords else "N/A"
275
+
276
+ sentiments.append(sentiment)
277
+ scores.append(score)
278
+ keywords_list.append(keyword_str)
279
+ except Exception as e:
280
+ print(f"Error processing text: {e}")
281
+ sentiments.append("Neutral")
282
+ scores.append(0.5)
283
+ keywords_list.append("N/A")
284
+
285
+ user_df["Sentiment"] = sentiments
286
+ user_df["Score"] = scores
287
+ user_df["Keywords"] = keywords_list
288
+
289
+ global_df = user_df.sort_values("Datetime").reset_index(drop=True)
290
+ return global_df
291
+
292
+ except Exception as e:
293
+ print(f"Error processing file: {str(e)}")
294
+ global_df = generate_default_df()
295
+ return global_df
296
+
297
+ # Function to wrapper function for file analysis to update dataframe display
298
+
299
+ def get_analysis_dataframe(file):
300
+ return process_uploaded_file(file)
301
+
302
+ # Function to analyze a single comment and return sentiment and keywords
303
+
304
+ def analyze_text(comment):
305
+ if not comment or not comment.strip():
306
+ return "N/A", 0, "N/A"
307
+
308
+ try:
309
+ result = classifier(comment)[0]
310
+ sentiment = sentiment_map.get(result["label"], result["label"])
311
+ score = result["score"]
312
+
313
+ keywords = kw_model.extract_keywords(comment, top_n=3, keyphrase_ngram_range=(1, 2))
314
+ keywords_str = ", ".join([kw[0] for kw in keywords]) if keywords else "N/A"
315
+
316
+ return sentiment, score, keywords_str
317
+ except Exception as e:
318
+ print(f"Error analyzing text: {e}")
319
+ return "Error", 0, "Error processing text"
320
+
321
+ # Function to add analyzed comment to global dataframe
322
+
323
+ def add_to_dataframe(comment, sentiment, score, keywords):
324
+
325
+ global global_df
326
+ timestamp = datetime.now().replace(microsecond=0)
327
+
328
+ new_row = pd.DataFrame([{
329
+ "Datetime": timestamp,
330
+ "Text": comment,
331
+ "Sentiment": sentiment,
332
+ "Score": score,
333
+ "Keywords": keywords
334
+ }])
335
+
336
+ global_df = pd.concat([global_df, new_row], ignore_index=True)
337
+ return global_df
338
+
339
+ # Function to generate and display a simple word cloud based on sentiment filter
340
+
341
+ def create_wordcloud_simple(df, sentiment_filter=None):
342
+ if df is None or df.empty:
343
+ return None
344
+
345
+ # Filter by sentiment if provided
346
+ if sentiment_filter and sentiment_filter != "All":
347
+ filtered_df = df[df["Sentiment"] == sentiment_filter]
348
+ else:
349
+ filtered_df = df
350
+
351
+ if filtered_df.empty:
352
+ print("No data available for the selected sentiment.")
353
+ return None
354
+
355
+ # Combine keywords into a single string
356
+ keyword_text = filtered_df["Keywords"].fillna("").str.replace("N/A", "").str.replace(",", " ")
357
+ all_keywords = " ".join(keyword_text)
358
+
359
+ if not all_keywords.strip():
360
+ print("No valid keywords to display in word cloud.")
361
+ return None
362
+
363
+ # Select colormap based on sentiment
364
+ colormap = "viridis"
365
+ if sentiment_filter == "Positive":
366
+ colormap = "Greens"
367
+ elif sentiment_filter == "Neutral":
368
+ colormap = "Blues"
369
+ elif sentiment_filter == "Negative":
370
+ colormap = "Reds"
371
+
372
+ # Create the word cloud
373
+ wordcloud = WordCloud(
374
+ background_color='white',
375
+ colormap=colormap,
376
+ max_words=50,
377
+ height=500,
378
+ ).generate(all_keywords)
379
+
380
+ # Convert to image for Gradio
381
+ return wordcloud.to_image()
382
+
383
+
384
+
385
+ # Function to create a scatter plot showing comment volume by sentiment over time
386
+ def plot_sentiment_timeline(df):
387
+ if df is None or df.empty:
388
+ return go.Figure().update_layout(title="No data available", height=400)
389
+
390
+ try:
391
+ df_copy = df.copy()
392
+ df_copy["Datetime"] = pd.to_datetime(df_copy["Datetime"])
393
+ df_copy["Time_Bin"] = df_copy["Datetime"].dt.floor("1H")
394
+
395
+ # Grouping comments by time and sentiment
396
+ grouped = (
397
+ df_copy.groupby(["Time_Bin", "Sentiment"])
398
+ .agg(
399
+ Count=("Text", "count"),
400
+ Score=("Score", "mean"),
401
+ Keywords=("Keywords", lambda x: ", ".join(set(", ".join(x).split(", "))) if len(x) > 0 else "")
402
+ )
403
+ .reset_index()
404
+ )
405
+
406
+ fig = go.Figure()
407
+
408
+ for sentiment, color in color_map.items():
409
+ sentiment_df = grouped[grouped["Sentiment"] == sentiment]
410
+ if sentiment_df.empty:
411
+ continue
412
+
413
+ fig.add_trace(
414
+ go.Scatter(
415
+ x=sentiment_df["Time_Bin"],
416
+ y=sentiment_df["Count"],
417
+ mode='markers',
418
+ name=sentiment,
419
+ marker=dict(size=10, color=color, opacity=0.9, line=dict(width=1, color='DarkSlateGrey')),
420
+ text=sentiment_df["Keywords"],
421
+ hovertemplate='<b>%{y} comments</b><br>%{x}<br><b>Keywords:</b> %{text}<extra></extra>'
422
+ )
423
+ )
424
+
425
+ fig.update_layout(
426
+ title="Sentiment Distribution Over Time (1-Hour Bins)",
427
+ height=500,
428
+ xaxis=dict(
429
+ title="Time",
430
+ type="date",
431
+ rangeslider=dict(visible=False),
432
+ rangeselector=dict(
433
+ buttons=list([
434
+ dict(count=1, label="1d", step="day", stepmode="backward"),
435
+ dict(count=7, label="1w", step="day", stepmode="backward"),
436
+ dict(count=1, label="1m", step="month", stepmode="backward"),
437
+ dict(count=6, label="6m", step="month", stepmode="backward"),
438
+ dict(count=1, label="1y", step="year", stepmode="backward"),
439
+ dict(step="all", label="All")
440
+ ])
441
+ )
442
+ ),
443
+ yaxis=dict(title="Number of Comments"),
444
+ template="plotly_white"
445
+ )
446
+
447
+ return fig
448
+
449
+ except Exception as e:
450
+ print(f"Error in timeline plot: {e}")
451
+ return go.Figure().update_layout(
452
+ title="Error creating timeline visualization",
453
+ height=400
454
+ )
455
+
456
+
457
+
458
+ # Function to create a dual-view visualization of sentiment distribution
459
+
460
+ def plot_sentiment_distribution(df):
461
+ if df is None or df.empty:
462
+ return go.Figure().update_layout(title="No data available", height=400)
463
+
464
+ try:
465
+ # Group sentiment counts
466
+ sentiment_counts = df["Sentiment"].value_counts().reset_index()
467
+ sentiment_counts.columns = ["Sentiment", "Count"]
468
+ sentiment_counts["Percentage"] = sentiment_counts["Count"] / sentiment_counts["Count"].sum() * 100
469
+
470
+ # Create subplots
471
+ fig = make_subplots(
472
+ rows=1, cols=2,
473
+ specs=[[{"type": "domain"}, {"type": "xy"}]],
474
+ subplot_titles=("Sentiment Distribution", "Sentiment Counts"),
475
+ column_widths=[0.5, 0.5]
476
+ )
477
+
478
+ # Pie Chart
479
+ fig.add_trace(
480
+ go.Pie(
481
+ labels=sentiment_counts["Sentiment"],
482
+ values=sentiment_counts["Count"],
483
+ textinfo="percent+label",
484
+ marker=dict(colors=[color_map.get(s, "#999999") for s in sentiment_counts["Sentiment"]]),
485
+ hole=0.4
486
+ ),
487
+ row=1, col=1
488
+ )
489
+
490
+ # Bar Chart
491
+ fig.add_trace(
492
+ go.Bar(
493
+ x=sentiment_counts["Sentiment"],
494
+ y=sentiment_counts["Count"],
495
+ text=sentiment_counts["Count"],
496
+ textposition="auto",
497
+ marker_color=[color_map.get(s, "#999999") for s in sentiment_counts["Sentiment"]]
498
+ ),
499
+ row=1, col=2
500
+ )
501
+
502
+ # Update layout
503
+ fig.update_layout(
504
+ title="Sentiment Distribution Overview",
505
+ height=500,
506
+ autosize=True,
507
+ width=None ,
508
+ template="plotly_white",
509
+ showlegend=False
510
+ )
511
+
512
+ return fig
513
+
514
+ except Exception as e:
515
+ print(f"Error in distribution plot: {e}")
516
+ return go.Figure().update_layout(
517
+ title="Error creating distribution visualization",
518
+ height=500,
519
+ autosize=True,
520
+ width=None
521
+ )
522
+
523
+ # Function to create a grouped bar chart visualization of the top keywords across sentiments
524
+
525
+ def plot_keyword_analysis(df):
526
+ if df is None or df.empty:
527
+ return go.Figure().update_layout(title="No data available", height=400)
528
+
529
+ try:
530
+ all_keywords = []
531
+
532
+ # Process each sentiment
533
+ for sentiment in ["Positive", "Neutral", "Negative"]:
534
+ sentiment_df = df[df["Sentiment"] == sentiment]
535
+ if sentiment_df.empty:
536
+ continue
537
+
538
+ # Extract and flatten keyword lists
539
+ for keywords_str in sentiment_df["Keywords"].dropna():
540
+ if keywords_str and keywords_str.upper() != "N/A":
541
+ keywords = [kw.strip() for kw in keywords_str.split(",") if kw.strip()]
542
+ for kw in keywords:
543
+ all_keywords.append((kw, sentiment))
544
+
545
+ if not all_keywords:
546
+ return go.Figure().update_layout(
547
+ title="No keyword data available",
548
+ height=500,
549
+ autosize=True,
550
+ width=None
551
+ )
552
+
553
+ # Create DataFrame and aggregate keyword counts
554
+ keywords_df = pd.DataFrame(all_keywords, columns=["Keyword", "Sentiment"])
555
+ keyword_counts = (
556
+ keywords_df.groupby(["Keyword", "Sentiment"])
557
+ .size()
558
+ .reset_index(name="Count")
559
+ )
560
+
561
+ # Filter top 15 keywords by overall frequency
562
+ top_keywords = keywords_df["Keyword"].value_counts().nlargest(15).index
563
+ keyword_counts = keyword_counts[keyword_counts["Keyword"].isin(top_keywords)]
564
+
565
+ # Plot grouped bar chart
566
+ fig = px.bar(
567
+ keyword_counts,
568
+ x="Keyword",
569
+ y="Count",
570
+ color="Sentiment",
571
+ color_discrete_map=color_map,
572
+ text="Count",
573
+ barmode="group",
574
+ labels={"Count": "Frequency", "Keyword": ""},
575
+ title="🔍 Top Keywords by Sentiment"
576
+ )
577
+
578
+ fig.update_layout(
579
+ legend_title="Sentiment",
580
+ xaxis=dict(categoryorder="total descending"),
581
+ yaxis=dict(title="Frequency"),
582
+ height=500,
583
+ autosize=True,
584
+ width=None ,
585
+ template="plotly_white"
586
+ )
587
+
588
+ return fig
589
+
590
+ except Exception as e:
591
+ print(f"Error in keyword analysis: {e}")
592
+ return go.Figure().update_layout(
593
+ title="Error creating keyword visualization",
594
+ height=500,
595
+ autosize=True,
596
+ width=None
597
+ )
598
+
599
+ # Function to generate summary sentiment metrics for dashboard visualization
600
+
601
+ def create_summary_metrics(df):
602
+ if df is None or df.empty:
603
+ return {
604
+ "total": 0, "positive": 0, "neutral": 0, "negative": 0,
605
+ "positive_pct": 0.0, "neutral_pct": 0.0, "negative_pct": 0.0,
606
+ "sentiment_ratio": 0.0, "trend": "No data"
607
+ }
608
+
609
+ try:
610
+ total_comments = len(df)
611
+
612
+ # Count sentiments
613
+ sentiment_counts = df["Sentiment"].value_counts().to_dict()
614
+ positive = sentiment_counts.get("Positive", 0)
615
+ neutral = sentiment_counts.get("Neutral", 0)
616
+ negative = sentiment_counts.get("Negative", 0)
617
+
618
+ # Calculate percentages safely
619
+ def pct(count):
620
+ return round((count / total_comments) * 100, 1) if total_comments else 0.0
621
+
622
+ positive_pct = pct(positive)
623
+ neutral_pct = pct(neutral)
624
+ negative_pct = pct(negative)
625
+
626
+ # Sentiment ratio (Positive : Negative)
627
+ sentiment_ratio = round(positive / negative, 2) if negative > 0 else float('inf')
628
+
629
+ # Trend detection based on time-series sentiment evolution
630
+ trend = "Insufficient data"
631
+ if total_comments >= 5 and "Datetime" in df.columns:
632
+ sorted_df = df.sort_values("Datetime")
633
+ mid = total_comments // 2
634
+ first_half = sorted_df.iloc[:mid]
635
+ second_half = sorted_df.iloc[mid:]
636
+
637
+ # Compute positive sentiment proportion in both halves
638
+ first_pos_pct = (first_half["Sentiment"] == "Positive").mean()
639
+ second_pos_pct = (second_half["Sentiment"] == "Positive").mean()
640
+
641
+ delta = second_pos_pct - first_pos_pct
642
+ if delta > 0.05:
643
+ trend = "Improving"
644
+ elif delta < -0.05:
645
+ trend = "Declining"
646
+ else:
647
+ trend = "Stable"
648
+
649
+ return {
650
+ "total": total_comments,
651
+ "positive": positive,
652
+ "neutral": neutral,
653
+ "negative": negative,
654
+ "positive_pct": positive_pct,
655
+ "neutral_pct": neutral_pct,
656
+ "negative_pct": negative_pct,
657
+ "sentiment_ratio": sentiment_ratio,
658
+ "trend": trend,
659
+ }
660
+
661
+ except Exception as e:
662
+ print(f"Error in summary metrics: {e}")
663
+ return {
664
+ "total": 0, "positive": 0, "neutral": 0, "negative": 0,
665
+ "positive_pct": 0.0, "neutral_pct": 0.0, "negative_pct": 0.0,
666
+ "sentiment_ratio": 0.0, "trend": "Error calculating"
667
+ }
668
+
669
+ # Function to analyze a single comment for the Quick Analyzer tab
670
+
671
+ def gradio_analyze_comment(comment):
672
+
673
+ try:
674
+ if not comment or not comment.strip():
675
+ return "N/A", "0.0%", "N/A"
676
+
677
+ sentiment, score, keywords = analyze_text(comment)
678
+ score_str = f"{score * 100:.1f}%"
679
+
680
+ return sentiment, score_str, keywords
681
+
682
+ except Exception as e:
683
+ print(f"Error in gradio_analyze_comment: {e}")
684
+ return "Error", "0.0%", "Error processing comment"
685
+
686
+ # Function to add a comment to the dashboard
687
+
688
+ def gradio_add_comment(comment):
689
+ global global_df
690
+
691
+ if not comment or not comment.strip():
692
+ return global_df, "Please enter a comment", "", plot_sentiment_timeline(global_df), plot_sentiment_distribution(global_df), plot_keyword_analysis(global_df)
693
+
694
+ sentiment, score, keywords = analyze_text(comment)
695
+ updated_df = add_to_dataframe(comment, sentiment, score, keywords)
696
+
697
+ # Generate feedback message
698
+ feedback = f"✓ Added: {sentiment} comment (Confidence: {score*100:.1f}%)"
699
+
700
+
701
+ # Update all visualizations
702
+ timeline_plot = plot_sentiment_timeline(updated_df)
703
+ distribution_plot = plot_sentiment_distribution(updated_df)
704
+ keyword_plot = plot_keyword_analysis(updated_df)
705
+
706
+ return updated_df, feedback, "", timeline_plot, distribution_plot, keyword_plot
707
+
708
+ # Function to generate a word cloud image from the DataFrame
709
+
710
+ def gradio_generate_wordcloud(sentiment_filter):
711
+ try:
712
+ filter_value = sentiment_filter if sentiment_filter != "All" else None
713
+ return create_wordcloud_simple(global_df, filter_value)
714
+ except Exception as e:
715
+ print(f"Error generating word cloud: {e}")
716
+ return None
717
+
718
+
719
+
720
+ # Function to export the current dataframe to CSV for download
721
+
722
+ def export_data_to_csv(df_component):
723
+ global global_df
724
+ try:
725
+ if global_df is not None and not global_df.empty:
726
+ csv_buffer = io.StringIO()
727
+ global_df.to_csv(csv_buffer, index=False)
728
+ csv_content = csv_buffer.getvalue()
729
+
730
+ # Save to a temporary file
731
+ filename = f"sentiment_analysis_{datetime.now().strftime('%Y%m%d_%H%M%S')}.csv"
732
+ with open(filename, 'w', encoding='utf-8') as f:
733
+ f.write(csv_content)
734
+
735
+ return filename
736
+ else:
737
+ return None
738
+ except Exception as e:
739
+ print(f"Error exporting data: {e}")
740
+ return None
741
+
742
+
743
+
744
+ def analyze_youtube_comments(video_url):
745
+ from youtube_comment_downloader import YoutubeCommentDownloader
746
+ import re
747
+
748
+ # Simple YouTube video URL validation
749
+ youtube_pattern = r"(https?://)?(www\.)?(youtube\.com/watch\?v=|youtu\.be/)[\w-]{11}"
750
+ if not re.match(youtube_pattern, video_url):
751
+ raise gr.Error("🚫 Please provide a valid YouTube video link.")
752
+
753
+ try:
754
+ downloader = YoutubeCommentDownloader()
755
+ comments = downloader.get_comments_from_url(video_url)
756
+ if not comments:
757
+ raise gr.Error("⚠️ No comments found for this video.")
758
+ return generate_df(comments)
759
+ except Exception as e:
760
+ raise gr.Error(f"❌ Failed to retrieve comments: {str(e)}")
761
+
762
+ # Global default data initialization
763
+ global_df = generate_default_df()
764
+
765
+
766
+ # Function: Load either a file or a video URL, return dashboard-ready components
767
+ def load_and_update_all_components(file, video_url):
768
+ global global_df
769
+
770
+ # Determine which input to process
771
+ if file is not None:
772
+ updated_df = get_analysis_dataframe(file)
773
+ elif video_url:
774
+ updated_df = analyze_youtube_comments(video_url)
775
+ else:
776
+ updated_df = global_df # fallback to default data if nothing provided
777
+
778
+ # Generate updated metrics and visuals
779
+ metrics = create_summary_metrics(updated_df)
780
+ global_df = updated_df # Update global state
781
+
782
+ return (
783
+ updated_df,
784
+ metrics["total"], metrics["positive_pct"], metrics["neutral_pct"],
785
+ metrics["negative_pct"], metrics["sentiment_ratio"], metrics["trend"],
786
+ plot_sentiment_timeline(updated_df),
787
+ plot_sentiment_distribution(updated_df),
788
+ plot_keyword_analysis(updated_df),
789
+ updated_df
790
+ )
791
+
792
+ # Create the Gradio interface and dashboard
793
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
794
+ gr.Markdown(
795
+ """
796
+ # A Smart Dashboard for Analyzing Public Sentiment and Perception
797
+ #### This interactive dashboard enables users to analyze public sentiment and perception by processing YouTube video comments or customized datasets uploaded as CSV or Excel files. Using advanced natural language processing techniques, the dashboard provides sentiment classification, keyword trends, and visual insights to support data-driven decision-making.
798
+ """
799
+ )
800
+
801
+ # Data Input Section
802
+ with gr.Tabs() as input_tabs:
803
+
804
+ with gr.Tab("🎬 YouTube Video Analysis"):
805
+ with gr.Row():
806
+ video_url = gr.Textbox(label="YouTube Video URL", placeholder="https://www.youtube.com/watch?v=...")
807
+ url_load_btn = gr.Button("🎬 Analyze Comments", variant="primary")
808
+
809
+ with gr.Tab("📁 File Upload Analysis"):
810
+ with gr.Row():
811
+ file_input = gr.File(label="Upload CSV or Excel File", file_types=[".csv", ".xlsx"])
812
+ file_load_btn = gr.Button("📊 Load & Analyze File", variant="primary")
813
+
814
+ # Hidden state component
815
+ comments_df = gr.DataFrame(value=global_df if global_df is not None else generate_default_df(),
816
+ label="Loaded Comment Data", interactive=False, visible=False)
817
+
818
+ # Dashboard Tabs
819
+ with gr.Tabs():
820
+ # Tab 1: Main Analytics Dashboard
821
+ with gr.Tab("Analytics Dashboard"):
822
+ # Summary metrics
823
+ metrics = create_summary_metrics(global_df if global_df is not None else generate_default_df())
824
+
825
+ with gr.Row():
826
+ with gr.Column(scale=1):
827
+ total_comments = gr.Number(value=metrics["total"], label="Total Comments", interactive=False)
828
+ with gr.Column(scale=1):
829
+ positive_count = gr.Number(value=metrics["positive_pct"], label="Positive %", interactive=False)
830
+ with gr.Column(scale=1):
831
+ neutral_count = gr.Number(value=metrics["neutral_pct"], label="Neutral %", interactive=False)
832
+ with gr.Column(scale=1):
833
+ negative_count = gr.Number(value=metrics["negative_pct"], label="Negative %", interactive=False)
834
+
835
+ with gr.Row():
836
+ with gr.Column(scale=1):
837
+ pos_neg_ratio = gr.Number(value=metrics["sentiment_ratio"], label="Positive/Negative Ratio", interactive=False)
838
+ with gr.Column(scale=1):
839
+ sentiment_trend = gr.Textbox(value=metrics["trend"], label="Sentiment Trend", interactive=False)
840
+
841
+
842
+ # Visualizations
843
+ gr.Markdown("### 📊 Sentiment Visualizations")
844
+
845
+ with gr.Tabs():
846
+ with gr.Tab("Timeline Analysis"):
847
+ timeline_plot = gr.Plot(value=plot_sentiment_timeline(global_df if global_df is not None else generate_default_df()))
848
+
849
+ with gr.Tab("Sentiment Distribution"):
850
+ distribution_plot = gr.Plot(value=plot_sentiment_distribution(global_df if global_df is not None else generate_default_df()))
851
+
852
+ with gr.Tab("Keyword Analysis"):
853
+ keyword_plot = gr.Plot(value=plot_keyword_analysis(global_df if global_df is not None else generate_default_df()))
854
+
855
+ gr.Markdown("### Word Clouds of keyword")
856
+
857
+ with gr.Tab("Word Clouds"):
858
+ with gr.Row():
859
+ sentiment_filter = gr.Dropdown(
860
+ choices=["All", "Positive", "Neutral", "Negative"],
861
+ value="All",
862
+ label="Sentiment Filter"
863
+ )
864
+ generate_button = gr.Button("Generate Word Cloud")
865
+
866
+ wordcloud_output = gr.Image(label="Word Cloud")
867
+
868
+ gr.Markdown("### Data Extracted")
869
+ with gr.Row():
870
+ comments_display = gr.DataFrame(
871
+ value=global_df if global_df is not None else generate_default_df(),
872
+ interactive=False
873
+ )
874
+
875
+ with gr.Row():
876
+ export_btn = gr.Button("💾 Export & Download CSV", variant="secondary")
877
+ with gr.Row():
878
+ download_component = gr.File(label="Download", visible=True)
879
+
880
+ # Tab 2: Quick Analysis
881
+ with gr.Tab("Quick Sentiment Analyzer"):
882
+ gr.Markdown("""
883
+ ### Quick Sentiment Analysis Tool
884
+ Quickly analyze the sentiment of any comment you enter.
885
+ """)
886
+
887
+ with gr.Row():
888
+ quick_comment = gr.Textbox(
889
+ placeholder="Type your comment here...",
890
+ label="Comment for Analysis",
891
+ lines=3
892
+ )
893
+
894
+ with gr.Row():
895
+ analyze_btn = gr.Button("Analyze Sentiment", variant="primary")
896
+
897
+ with gr.Row():
898
+ with gr.Column():
899
+ sentiment_result = gr.Textbox(label="Sentiment")
900
+ with gr.Column():
901
+ confidence_result = gr.Textbox(label="Confidence")
902
+ with gr.Column():
903
+ keyword_result = gr.Textbox(label="Key Topics")
904
+
905
+ # Tab 3: About & Help
906
+ with gr.Tab("About This Dashboard"):
907
+ gr.Markdown("""
908
+ ## About This Dashboard
909
+
910
+ This dashboard allows you to analyze public sentiment from YouTube video comments or uploaded CSV/Excel files.
911
+ It uses natural language processing to detect sentiment, highlight key topics, and reveal emerging trends.
912
+ Whether you are tracking opinions or exploring concerns, the dashboard delivers clear, data-driven insights.
913
+
914
+ ### Features:
915
+
916
+ - **Multiple Data Sources**: Upload CSV/Excel files or analyze YouTube video comments
917
+ - **Sentiment Analysis**: Automatically classifies comments as Positive, Neutral, or Negative
918
+ - **Keyword Extraction**: Identifies the most important topics in each comment
919
+ - **Time Series Analysis**: Tracks sentiment trends over time
920
+ - **Word Cloud Visualization**: Visual representation of the most common terms
921
+ - **Data Export**: Download collected data for further analysis
922
+
923
+ ### How to Use:
924
+
925
+ 1. Upload a dataset file via the File Upload tab or enter a YouTube URL
926
+ 2. View overall sentiment metrics and trends in the Analytics Dashboard
927
+ 3. Add new comments using the comment input box
928
+ 4. Use the Quick Analyzer for testing sentiment on individual comments
929
+ 5. Export data in CSV format for external analysis
930
+
931
+ ### File Upload Requirements:
932
+
933
+ - CSV or Excel files (.csv, .xlsx)
934
+ - Must contain a 'Text' column with comments
935
+ - Optional 'Datetime' column (will be auto-generated if missing)
936
+
937
+ This dashboard is developed by [**Anaclet UKURIKIYEYEZU**](https://portofolio-pi-lac.vercel.app/)
938
+ Feel free to reach out with any questions or feedback!
939
+
940
+ ### Contact Information:
941
+ - [**WhatsApp**](https://wa.me/250786698014): +250 786 698 014
942
+ - [**Email**](mailto:anaclet.ukurikiyeyezu@aims.ac.rw): anaclet.ukurikiyeyezu@aims.ac.rw
943
+
944
+ """
945
+ )
946
+
947
+ # Connect events to functions
948
+
949
+ # File upload event
950
+ file_load_btn.click(
951
+ fn=lambda file: load_and_update_all_components(file, None),
952
+ inputs=[file_input],
953
+ outputs=[
954
+ comments_df, # Hidden state component
955
+ total_comments, positive_count, neutral_count, negative_count, # Metric displays
956
+ pos_neg_ratio, sentiment_trend, # Additional metrics
957
+ timeline_plot, distribution_plot, keyword_plot, # Visualizations
958
+ comments_display # Comments table
959
+ ]
960
+ )
961
+
962
+ # YouTube analysis event
963
+ url_load_btn.click(
964
+ fn=lambda url: load_and_update_all_components(None, url),
965
+ inputs=[video_url],
966
+ outputs=[
967
+ comments_df, # Hidden state component
968
+ total_comments, positive_count, neutral_count, negative_count, # Metric displays
969
+ pos_neg_ratio, sentiment_trend, # Additional metrics
970
+ timeline_plot, distribution_plot, keyword_plot, # Visualizations
971
+ comments_display # Comments table
972
+ ]
973
+ )
974
+
975
+ # Word cloud generation event
976
+ generate_button.click(
977
+ fn=gradio_generate_wordcloud,
978
+ inputs=[sentiment_filter],
979
+ outputs=[wordcloud_output]
980
+ )
981
+
982
+ # Comment analysis event
983
+ analyze_btn.click(
984
+ fn=gradio_analyze_comment,
985
+ inputs=[quick_comment],
986
+ outputs=[sentiment_result, confidence_result, keyword_result]
987
+ )
988
+
989
+ # Add comment event
990
+ def add_comment_and_update(comment):
991
+ global global_df
992
+ updated_df, feedback, _ = gradio_add_comment(comment)
993
+
994
+ # Update metrics based on the new dataframe
995
+ metrics = create_summary_metrics(updated_df)
996
+
997
+ # Return all updated components
998
+ return (
999
+ updated_df, # Update hidden state
1000
+ feedback, "", # Feedback message and clear input
1001
+ metrics["total"], metrics["positive_pct"], metrics["neutral_pct"], # Update metrics
1002
+ metrics["negative_pct"], metrics["sentiment_ratio"], metrics["trend"],
1003
+ plot_sentiment_timeline(updated_df), # Update plots
1004
+ plot_sentiment_distribution(updated_df),
1005
+ plot_keyword_analysis(updated_df),
1006
+ updated_df # Update display table
1007
+ )
1008
+
1009
+ # Export to CSV event
1010
+ export_btn.click(
1011
+ fn=export_data_to_csv,
1012
+ inputs=[comments_display],
1013
+ outputs=[download_component]
1014
+ )
1015
+
1016
+ # Launch the app
1017
+ if __name__ == "__main__":
1018
+ demo.launch(share=True)
1019
+
1020
+
1021
+
1022
+
1023
+
1024
+
1025
+
1026
+
1027
+
1028
+
1029
+
requirements.txt ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ transformers>=4.30.0
2
+ keybert>=0.7.0
3
+ pandas>=1.5.0
4
+ numpy>=1.24.0
5
+ gradio>=4.0.0
6
+ plotly>=5.15.0
7
+ wordcloud>=1.9.0
8
+ matplotlib>=3.7.0
9
+ youtube-comment-downloader>=0.1.0
10
+ torch>=2.0.0
11
+ scikit-learn>=1.3.0
12
+ sentence-transformers>=2.2.0
13
+ Pillow>=9.0.0
14
+ openpyxl>=3.1.0