Spaces:
Sleeping
Sleeping
File size: 12,218 Bytes
9ff5c45 0bb81de | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 | from transformers import pipeline
from keybert import KeyBERT
from sentence_transformers import SentenceTransformer
import torch
import re
from collections import Counter
import numpy as np
import os
# Set cache directories
os.environ['TRANSFORMERS_CACHE'] = '/app/cache'
os.environ['HF_HOME'] = '/app/cache'
# Check if GPU is available
device = 0 if torch.cuda.is_available() else -1
print(f"Using device: {'GPU' if torch.cuda.is_available() else 'CPU'}")
# Load sentence transformer model FIRST (needed for KeyBERT)
print("Loading sentence transformer model...")
try:
sentence_model = SentenceTransformer('all-MiniLM-L6-v2', device='cpu')
print("Sentence transformer loaded successfully!")
except Exception as e:
print(f"Error loading sentence transformer: {e}")
# Fallback to a smaller model
sentence_model = SentenceTransformer('paraphrase-MiniLM-L3-v2', device='cpu')
# Load sentiment analysis model
print("Loading sentiment analysis model...")
try:
sentiment_model = pipeline(
"sentiment-analysis",
model="cardiffnlp/twitter-roberta-base-sentiment-latest",
device=device,
truncation=True,
max_length=512
)
print("Sentiment model loaded!")
except Exception as e:
print(f"Error loading sentiment model: {e}")
sentiment_model = None
# Load sarcasm detection model
print("Loading sarcasm detection model...")
try:
sarcasm_model = pipeline(
"text-classification",
model="cardiffnlp/twitter-roberta-base-irony",
device=device,
truncation=True,
max_length=512
)
print("Sarcasm model loaded!")
except Exception as e:
print(f"Error loading sarcasm model: {e}")
sarcasm_model = None
# Load emotion detection model
print("Loading emotion detection model...")
try:
emotion_model = pipeline(
"text-classification",
model="j-hartmann/emotion-english-distilroberta-base",
device=device,
truncation=True,
max_length=512
)
print("Emotion model loaded!")
except Exception as e:
print(f"Error loading emotion model: {e}")
emotion_model = None
# Load summarizer (optional - use smaller model for faster loading)
print("Loading summarizer model...")
try:
summarizer = pipeline(
"summarization",
model="facebook/bart-large-cnn",
device=device,
truncation=True,
max_length=1024
)
print("Summarizer loaded!")
except Exception as e:
print(f"Error loading summarizer: {e}")
# Fallback to smaller model
try:
summarizer = pipeline(
"summarization",
model="t5-small",
device=device
)
print("Fallback summarizer loaded!")
except:
summarizer = None
# Load keyword extractor with the sentence model
print("Loading keyword extractor...")
try:
kw_model = KeyBERT(model=sentence_model)
print("KeyBERT loaded successfully!")
except Exception as e:
print(f"Error loading KeyBERT: {e}")
kw_model = None
print("All models loaded successfully!")
# Positive and negative word lists for fallback
POSITIVE_WORDS = {
'love', 'β€οΈ', 'π', 'π', 'π', 'π', 'π', 'π',
'great', 'amazing', 'awesome', 'fantastic', 'wonderful',
'beautiful', 'perfect', 'excellent', 'brilliant',
'fan', 'favorite', 'favourite', 'best', 'good', 'nice',
'like', 'enjoy', 'appreciate', 'thank', 'thanks', 'legend'
}
NEGATIVE_WORDS = {
'hate', 'bad', 'terrible', 'awful', 'horrible', 'sucks',
'dislike', 'worst', 'poor', 'disappointing', 'waste',
'boring', 'useless', 'trash', 'garbage', 'cringe',
'overrated', 'hated', 'annoying', 'stupid', 'dumb'
}
def safe_truncate(text, max_length=512):
"""Safely truncate text to max_length characters"""
if not text:
return ""
if len(text) > max_length:
return text[:max_length]
return text
def clean_text(text: str) -> tuple:
"""Clean and normalize text"""
if not text:
return "", ""
text = ' '.join(text.split())
text_lower = text.lower()
return text, text_lower
def predict_sentiment(text: str) -> str:
"""
Sentiment prediction with fallback
"""
try:
if not text or len(text.strip()) < 2:
return "NEUTRAL"
# Clean and truncate
text = safe_truncate(text, 512)
text, text_lower = clean_text(text)
# Try model prediction first
if sentiment_model:
try:
result = sentiment_model(text)[0]
model_label = result['label']
model_score = result['score']
# Map model labels to our categories
if model_label == "LABEL_0":
return "NEGATIVE"
elif model_label == "LABEL_2":
return "POSITIVE"
elif model_label == "LABEL_1" and model_score > 0.7:
return "NEUTRAL"
except Exception as model_err:
print(f"Model error: {model_err}")
# Keyword-based analysis (fallback)
pos_count = sum(1 for word in POSITIVE_WORDS if word in text_lower)
neg_count = sum(1 for word in NEGATIVE_WORDS if word in text_lower)
if pos_count > neg_count and pos_count > 0:
return "POSITIVE"
elif neg_count > pos_count and neg_count > 0:
return "NEGATIVE"
return "NEUTRAL"
except Exception as e:
print(f"Error in sentiment analysis: {e}")
return "NEUTRAL"
def detect_sarcasm(text: str) -> str:
"""Detect sarcasm in comment"""
try:
if not text or not sarcasm_model:
return "NO"
text = safe_truncate(text, 512)
if len(text.strip()) < 3:
return "NO"
result = sarcasm_model(text)[0]
return "YES" if result['label'] == "LABEL_1" and result['score'] > 0.55 else "NO"
except Exception as e:
return "NO"
def detect_emotion(text: str) -> str:
"""Detect emotion in comment"""
try:
if not text:
return "neutral"
# Emoji-based fast detection
if 'π' in text or 'π’' in text:
return "sadness"
elif 'π' in text or 'π' in text or 'π₯°' in text:
return "joy"
elif 'π' in text or 'π€£' in text:
return "amusement"
elif 'β€οΈ' in text or 'π' in text:
return "love"
elif 'π' in text or 'π' in text:
return "excitement"
elif 'π ' in text or 'π€¬' in text:
return "anger"
elif 'π¨' in text or 'π±' in text:
return "fear"
# Model-based detection
if emotion_model:
text = safe_truncate(text, 512)
if len(text.strip()) > 2:
result = emotion_model(text)[0]
return result['label']
return "neutral"
except Exception as e:
return "neutral"
def generate_summary(texts: list) -> str:
"""Generate summary of all comments"""
try:
if not texts or not summarizer:
return "No comments to summarize"
sample_size = min(50, len(texts))
combined = " ".join(texts[:sample_size])
combined = safe_truncate(combined, 800)
if len(combined) < 50:
return "Not enough comments to generate summary"
summary = summarizer(combined, max_length=100, min_length=30, do_sample=False)
return summary[0]['summary_text']
except Exception as e:
print(f"Error in summary generation: {e}")
return "Comments analysis completed"
def extract_keywords(texts: list, top_n=15):
"""Extract keywords from comments"""
try:
if not texts:
return []
sample_size = min(150, len(texts))
combined = " ".join(texts[:sample_size])
combined = safe_truncate(combined, 1500)
if len(combined) < 20:
return []
# Use KeyBERT if available
if kw_model:
keywords = kw_model.extract_keywords(
combined,
keyphrase_ngram_range=(1, 2),
stop_words='english',
top_n=top_n
)
return [kw[0] for kw in keywords if kw and kw[0]]
# Fallback: simple word frequency
words = combined.lower().split()
stop_words = {'the', 'a', 'an', 'and', 'or', 'but', 'is', 'are', 'was', 'were',
'to', 'for', 'of', 'in', 'on', 'at', 'by', 'with', 'without', 'i',
'you', 'he', 'she', 'it', 'we', 'they', 'this', 'that', 'these', 'those'}
word_freq = {}
for word in words:
word = word.strip('.,!?;:()[]{}"\'')
if len(word) > 2 and word not in stop_words and not word.isdigit():
word_freq[word] = word_freq.get(word, 0) + 1
sorted_words = sorted(word_freq.items(), key=lambda x: x[1], reverse=True)[:top_n]
return [word for word, count in sorted_words]
except Exception as e:
print(f"Error in keyword extraction: {e}")
return []
def process_comments_in_batches(comments, batch_size=50):
"""Process comments in batches"""
total = len(comments)
if total == 0:
return
print(f"Processing {total} comments in batches of {batch_size}...")
for i in range(0, total, batch_size):
batch = comments[i:i+batch_size]
batch_results = []
for comment in batch:
try:
if not comment or len(comment.strip()) < 2:
batch_results.append({
"text": comment if comment else "",
"sentiment": "NEUTRAL",
"sarcasm": "NO",
"emotion": "neutral"
})
continue
sentiment = predict_sentiment(comment)
sarcasm = detect_sarcasm(comment)
emotion = detect_emotion(comment)
batch_results.append({
"text": comment,
"sentiment": sentiment,
"sarcasm": sarcasm,
"emotion": emotion
})
except Exception as e:
batch_results.append({
"text": comment if comment else "",
"sentiment": "NEUTRAL",
"sarcasm": "NO",
"emotion": "unknown"
})
yield batch_results
if (i // batch_size + 1) % 10 == 0 or (i + batch_size) >= total:
processed = min(i + batch_size, total)
print(f" Processed batch {i//batch_size + 1}/{(total + batch_size - 1)//batch_size} ({processed}/{total} comments)")
def get_batch_stats(results_batches):
"""Aggregate statistics from batch results"""
stats = {"positive": 0, "neutral": 0, "negative": 0}
all_results = []
for batch in results_batches:
for item in batch:
all_results.append(item)
if item["sentiment"] == "POSITIVE":
stats["positive"] += 1
elif item["sentiment"] == "NEGATIVE":
stats["negative"] += 1
else:
stats["neutral"] += 1
return stats, all_results
def get_sentiment_score(stats):
"""Calculate overall sentiment score"""
total = stats["positive"] + stats["neutral"] + stats["negative"]
if total == 0:
return 0
return ((stats["positive"] - stats["negative"]) / total) * 100 |