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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import pandas as pd
|
| 3 |
+
from nltk.sentiment import SentimentIntensityAnalyzer
|
| 4 |
+
from transformers import AutoTokenizer, AutoModelForSequenceClassification
|
| 5 |
+
import torch
|
| 6 |
+
import requests
|
| 7 |
+
import re
|
| 8 |
+
import sentence_transformers
|
| 9 |
+
from sentence_transformers import SentenceTransformer
|
| 10 |
+
from sklearn.feature_extraction.text import TfidfVectorizer
|
| 11 |
+
import matplotlib.pyplot as plt
|
| 12 |
+
import seaborn as sns
|
| 13 |
+
import nltk
|
| 14 |
+
from nltk.tokenize import word_tokenize
|
| 15 |
+
from nltk import pos_tag, ne_chunk
|
| 16 |
+
from nltk.tree import Tree
|
| 17 |
+
from googleapiclient.discovery import build
|
| 18 |
+
import emoji
|
| 19 |
+
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
|
| 20 |
+
from google.colab import drive
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
nltk.download('vader_lexicon')
|
| 25 |
+
nltk.download('punkt')
|
| 26 |
+
nltk.download('averaged_perceptron_tagger')
|
| 27 |
+
nltk.download('maxent_ne_chunker')
|
| 28 |
+
nltk.download('words')
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
# Mount Google Drive
|
| 32 |
+
drive.mount('/content/drive')
|
| 33 |
+
|
| 34 |
+
# Initialize the SentimentIntensityAnalyzer
|
| 35 |
+
sia = SentimentIntensityAnalyzer()
|
| 36 |
+
|
| 37 |
+
# Load the Sarcasm Detection model
|
| 38 |
+
sarcasm_tokenizer = AutoTokenizer.from_pretrained("jkhan447/sarcasm-detection-Bert-base-uncased")
|
| 39 |
+
sarcasm_model = AutoModelForSequenceClassification.from_pretrained("jkhan447/sarcasm-detection-Bert-base-uncased")
|
| 40 |
+
|
| 41 |
+
# Move model to GPU if available
|
| 42 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 43 |
+
sarcasm_model.to(device)
|
| 44 |
+
|
| 45 |
+
# Load SentenceTransformer model
|
| 46 |
+
sentence_transformer_model = SentenceTransformer('sentence-transformers/all-MiniLM-L6-v2')
|
| 47 |
+
|
| 48 |
+
api_key = "AIzaSyDOw_v-T58ATLOmQjF00k5Mjha6VPQ-TAk"
|
| 49 |
+
|
| 50 |
+
def extract_video_id(url):
|
| 51 |
+
match = re.search(r"v=([a-zA-Z0-9_-]{11})", url)
|
| 52 |
+
return match.group(1) if match else None
|
| 53 |
+
|
| 54 |
+
def get_video_details(video_id):
|
| 55 |
+
url = f"https://www.googleapis.com/youtube/v3/videos?part=snippet&id={video_id}&key={api_key}"
|
| 56 |
+
response = requests.get(url).json()
|
| 57 |
+
if response["items"]:
|
| 58 |
+
snippet = response["items"][0]["snippet"]
|
| 59 |
+
return snippet["title"], snippet["categoryId"]
|
| 60 |
+
return None, None
|
| 61 |
+
|
| 62 |
+
def get_comments(video_id):
|
| 63 |
+
comments = []
|
| 64 |
+
url = f"https://www.googleapis.com/youtube/v3/commentThreads?part=snippet&videoId={video_id}&key={api_key}&maxResults=100&order=relevance"
|
| 65 |
+
response = requests.get(url).json()
|
| 66 |
+
for item in response["items"]:
|
| 67 |
+
comment = item["snippet"]["topLevelComment"]["snippet"]["textOriginal"]
|
| 68 |
+
comments.append(comment)
|
| 69 |
+
return comments
|
| 70 |
+
|
| 71 |
+
def sentiment_scores(comment_text):
|
| 72 |
+
sentiment_dict = sia.polarity_scores(comment_text)
|
| 73 |
+
return sentiment_dict['compound']
|
| 74 |
+
|
| 75 |
+
def detect_sarcasm_batch(comments):
|
| 76 |
+
inputs = sarcasm_tokenizer(comments, return_tensors="pt", truncation=True, padding=True).to(device)
|
| 77 |
+
with torch.no_grad():
|
| 78 |
+
outputs = sarcasm_model(**inputs)
|
| 79 |
+
probs = torch.nn.functional.softmax(outputs.logits, dim=-1)
|
| 80 |
+
sarcasm_scores = probs[:, 1].tolist()
|
| 81 |
+
return sarcasm_scores
|
| 82 |
+
|
| 83 |
+
def get_sentiment_label(row):
|
| 84 |
+
polarity = row['polarity']
|
| 85 |
+
sarcasm_score = row['sarcasm_score']
|
| 86 |
+
category = row['category']
|
| 87 |
+
|
| 88 |
+
if sarcasm_score > 0.5:
|
| 89 |
+
return "Sarcastic"
|
| 90 |
+
|
| 91 |
+
if category == "Comedy":
|
| 92 |
+
if polarity > 0.05:
|
| 93 |
+
return "Funny/Enjoyable"
|
| 94 |
+
elif polarity < -0.05:
|
| 95 |
+
return "Unfunny/Criticism"
|
| 96 |
+
else:
|
| 97 |
+
return "Neutral"
|
| 98 |
+
|
| 99 |
+
elif category == "Education":
|
| 100 |
+
if polarity > 0.05:
|
| 101 |
+
return "Helpful/Informative"
|
| 102 |
+
elif polarity < -0.05:
|
| 103 |
+
return "Confusing/Criticism"
|
| 104 |
+
else:
|
| 105 |
+
return "Neutral"
|
| 106 |
+
|
| 107 |
+
elif category == "Music":
|
| 108 |
+
if polarity > 0.05:
|
| 109 |
+
return "Enjoyed"
|
| 110 |
+
elif polarity < -0.05:
|
| 111 |
+
return "Criticism/Disliked"
|
| 112 |
+
else:
|
| 113 |
+
return "Neutral"
|
| 114 |
+
|
| 115 |
+
elif category == "Entertainment":
|
| 116 |
+
if polarity > 0.05:
|
| 117 |
+
return "Entertained"
|
| 118 |
+
elif polarity < -0.05:
|
| 119 |
+
return "Bored/Criticism"
|
| 120 |
+
else:
|
| 121 |
+
return "Neutral"
|
| 122 |
+
|
| 123 |
+
else:
|
| 124 |
+
if polarity > 0.05:
|
| 125 |
+
return "Positive"
|
| 126 |
+
elif polarity < -0.05:
|
| 127 |
+
return "Negative"
|
| 128 |
+
else:
|
| 129 |
+
return "Neutral"
|
| 130 |
+
|
| 131 |
+
def extract_keywords(comments_for_video_df):
|
| 132 |
+
comment_embeddings = sentence_transformer_model.encode(comments_for_video_df['comment_text'].tolist())
|
| 133 |
+
tfidf = TfidfVectorizer(stop_words='english', max_features=20)
|
| 134 |
+
tfidf.fit(comments_for_video_df['comment_text'])
|
| 135 |
+
keywords = tfidf.get_feature_names_out()
|
| 136 |
+
keyword_importance = tfidf.idf_
|
| 137 |
+
keyword_importance_df = pd.DataFrame({'keyword': keywords, 'importance': keyword_importance})
|
| 138 |
+
|
| 139 |
+
plt.figure(figsize=(10, 6))
|
| 140 |
+
sns.barplot(y='keyword', x='importance', data=keyword_importance_df, palette='pastel')
|
| 141 |
+
plt.title('Top Keywords in Comments')
|
| 142 |
+
plt.xlabel('TF-IDF Importance')
|
| 143 |
+
plt.ylabel('Keyword')
|
| 144 |
+
plt.tight_layout()
|
| 145 |
+
|
| 146 |
+
return plt.gcf()
|
| 147 |
+
|
| 148 |
+
def analyze_video_sentiment(video_url):
|
| 149 |
+
video_id = extract_video_id(video_url)
|
| 150 |
+
if video_id:
|
| 151 |
+
video_title, category_id = get_video_details(video_id)
|
| 152 |
+
|
| 153 |
+
categories = {
|
| 154 |
+
"1": "Film & Animation", "2": "Autos & Vehicles", "10": "Music", "15": "Pets & Animals",
|
| 155 |
+
"17": "Sports", "18": "Short Movies", "19": "Travel & Events", "20": "Gaming",
|
| 156 |
+
"21": "Videoblogging", "22": "People & Blogs", "23": "Comedy", "24": "Entertainment",
|
| 157 |
+
"25": "News & Politics", "26": "Howto & Style", "27": "Education", "28": "Science & Technology",
|
| 158 |
+
"29": "Nonprofits & Activism", "30": "Movies", "31": "Anime/Animation", "32": "Action/Adventure",
|
| 159 |
+
"33": "Classics", "34": "Comedy", "35": "Documentary", "36": "Drama", "37": "Family",
|
| 160 |
+
"38": "Foreign", "39": "Horror", "40": "Sci-Fi/Fantasy", "41": "Thriller", "42": "Shorts",
|
| 161 |
+
"43": "Shows", "44": "Trailers"
|
| 162 |
+
}
|
| 163 |
+
category = categories.get(category_id, "Unknown Category")
|
| 164 |
+
|
| 165 |
+
comments = get_comments(video_id)
|
| 166 |
+
if comments:
|
| 167 |
+
comments_for_video_df = pd.DataFrame(comments, columns=["comment_text"])
|
| 168 |
+
comments_for_video_df['polarity'] = comments_for_video_df['comment_text'].apply(sentiment_scores)
|
| 169 |
+
|
| 170 |
+
batch_size = 32
|
| 171 |
+
sarcasm_scores = []
|
| 172 |
+
for i in range(0, len(comments_for_video_df), batch_size):
|
| 173 |
+
batch_comments = comments_for_video_df['comment_text'][i:i+batch_size].tolist()
|
| 174 |
+
batch_scores = detect_sarcasm_batch(batch_comments)
|
| 175 |
+
sarcasm_scores.extend(batch_scores)
|
| 176 |
+
|
| 177 |
+
comments_for_video_df['sarcasm_score'] = sarcasm_scores
|
| 178 |
+
comments_for_video_df['category'] = category # Assign the correct category to each comment
|
| 179 |
+
|
| 180 |
+
comments_for_video_df['Prominent sentiment'] = comments_for_video_df.apply(get_sentiment_label, axis=1)
|
| 181 |
+
|
| 182 |
+
keyword_plot = extract_keywords(comments_for_video_df)
|
| 183 |
+
|
| 184 |
+
# Analyze all comments but display only the top 10 comments based on relevance
|
| 185 |
+
top_10_comments = comments_for_video_df[['comment_text', 'Prominent sentiment']].head(10)
|
| 186 |
+
|
| 187 |
+
return comments_for_video_df, top_10_comments, video_title, category, keyword_plot
|
| 188 |
+
else:
|
| 189 |
+
return pd.DataFrame({"Error": ["No comments found."]}), None, None, None, None
|
| 190 |
+
else:
|
| 191 |
+
return pd.DataFrame({"Error": ["Invalid YouTube URL."]}), None, None, None, None
|
| 192 |
+
|
| 193 |
+
def plot_sentiment_distribution(df):
|
| 194 |
+
if 'Prominent sentiment' in df.columns:
|
| 195 |
+
sentiment_counts = df['Prominent sentiment'].value_counts().reset_index()
|
| 196 |
+
sentiment_counts.columns = ['Sentiment', 'Comment Count']
|
| 197 |
+
|
| 198 |
+
plt.figure(figsize=(10, 6))
|
| 199 |
+
sns.barplot(x='Sentiment', y='Comment Count', hue='Sentiment', data=sentiment_counts, palette="pastel", legend=False)
|
| 200 |
+
plt.title('Number of Comments by Sentiment', fontsize=14)
|
| 201 |
+
plt.xlabel('Sentiment', fontsize=12)
|
| 202 |
+
plt.ylabel('Number of Comments', fontsize=12)
|
| 203 |
+
plt.xticks(rotation=45)
|
| 204 |
+
plt.tight_layout()
|
| 205 |
+
|
| 206 |
+
return plt.gcf()
|
| 207 |
+
else:
|
| 208 |
+
return None
|
| 209 |
+
|
| 210 |
+
def plot_sarcasm_vs_polarity(df):
|
| 211 |
+
if 'polarity' in df.columns and 'sarcasm_score' in df.columns:
|
| 212 |
+
plt.figure(figsize=(10, 6))
|
| 213 |
+
sns.scatterplot(x='polarity', y='sarcasm_score', hue='Prominent sentiment', data=df, palette="pastel")
|
| 214 |
+
plt.title('Polarity vs. Sarcasm Score', fontsize=14)
|
| 215 |
+
plt.xlabel('Polarity Score', fontsize=12)
|
| 216 |
+
plt.ylabel('Sarcasm Score', fontsize=12)
|
| 217 |
+
plt.tight_layout()
|
| 218 |
+
|
| 219 |
+
return plt.gcf()
|
| 220 |
+
else:
|
| 221 |
+
return None
|
| 222 |
+
|
| 223 |
+
def gradio_interface(video_url):
|
| 224 |
+
full_df, df, video_title, category, keyword_plot = analyze_video_sentiment(video_url)
|
| 225 |
+
|
| 226 |
+
if category:
|
| 227 |
+
sentiment_plot = plot_sentiment_distribution(full_df)
|
| 228 |
+
sarcasm_plot = plot_sarcasm_vs_polarity(full_df)
|
| 229 |
+
|
| 230 |
+
insights = f"**Title:** {video_title}\n\n**Category:** {category}"
|
| 231 |
+
|
| 232 |
+
return df, sentiment_plot, sarcasm_plot, keyword_plot, insights, insights
|
| 233 |
+
else:
|
| 234 |
+
return df, None, None, None, "No insights available.", None
|
| 235 |
+
|
| 236 |
+
with gr.Blocks(theme=gr.themes.Monochrome()) as demo: # Dark theme applied
|
| 237 |
+
gr.Markdown(
|
| 238 |
+
"""
|
| 239 |
+
# 🎥 YouTube Sentiment Analysis
|
| 240 |
+
Enter a YouTube video URL below to analyze the comments for sentiment and sarcasm
|
| 241 |
+
"""
|
| 242 |
+
)
|
| 243 |
+
with gr.Row():
|
| 244 |
+
video_input = gr.Textbox(label="YouTube Video URL", placeholder="Enter a YouTube video URL here...")
|
| 245 |
+
analyze_button = gr.Button("Analyze", variant="primary", elem_id="analyze-btn")
|
| 246 |
+
|
| 247 |
+
video_details = gr.Markdown(label="Video Details", elem_id="video-details-box")
|
| 248 |
+
|
| 249 |
+
with gr.Accordion("Top 10 Comments", open=False):
|
| 250 |
+
comment_text = gr.Dataframe(label="Top 10 Comments", interactive=False)
|
| 251 |
+
|
| 252 |
+
sentiment_graph = gr.Plot(label="Sentiment Distribution")
|
| 253 |
+
sarcasm_graph = gr.Plot(label="Sarcasm vs Polarity")
|
| 254 |
+
keyword_graph = gr.Plot(label="Top Keywords")
|
| 255 |
+
insights_box = gr.Markdown(label="Insights", elem_id="insights-box")
|
| 256 |
+
|
| 257 |
+
analyze_button.click(gradio_interface,
|
| 258 |
+
inputs=video_input,
|
| 259 |
+
outputs=[comment_text, sentiment_graph, sarcasm_graph, keyword_graph, insights_box, video_details])
|
| 260 |
+
|
| 261 |
+
# Custom CSS for improved styling
|
| 262 |
+
gr.HTML(
|
| 263 |
+
"""
|
| 264 |
+
<style>
|
| 265 |
+
#analyze-btn {
|
| 266 |
+
background-color: #4CAF50; /* Green */
|
| 267 |
+
color: white;
|
| 268 |
+
border: none;
|
| 269 |
+
padding: 10px 24px;
|
| 270 |
+
text-align: center;
|
| 271 |
+
text-decoration: none;
|
| 272 |
+
display: inline-block;
|
| 273 |
+
font-size: 16px;
|
| 274 |
+
border-radius: 8px;
|
| 275 |
+
cursor: pointer;
|
| 276 |
+
}
|
| 277 |
+
#insights-box {
|
| 278 |
+
color: #FFD700;
|
| 279 |
+
font-weight: bold;
|
| 280 |
+
}
|
| 281 |
+
#video-details-box {
|
| 282 |
+
color: #1E90FF;
|
| 283 |
+
font-weight: bold;
|
| 284 |
+
}
|
| 285 |
+
body {
|
| 286 |
+
background-color: #1f1f1f;
|
| 287 |
+
color: #e0e0e0;
|
| 288 |
+
}
|
| 289 |
+
</style>
|
| 290 |
+
"""
|
| 291 |
+
)
|
| 292 |
+
|
| 293 |
+
demo.launch(debug=True)
|