File size: 18,111 Bytes
c93d183 3a249bb 3d2120b 3a249bb c93d183 829d082 c93d183 b3dcea1 c93d183 829d082 56b85a5 829d082 56b85a5 5a741e8 56b85a5 5a741e8 56b85a5 5a741e8 56b85a5 5a741e8 56b85a5 5a741e8 56b85a5 5a741e8 56b85a5 5a741e8 4071ce6 56b85a5 d09d853 56b85a5 4071ce6 5a741e8 56b85a5 27e835e 3f08853 27e835e 804adf6 27e835e 5a741e8 bd6cebd c48887f 804adf6 5a741e8 c48887f 5a741e8 27e835e 5a741e8 804adf6 5a741e8 27e835e 65d8742 27e835e 804adf6 bd6cebd 5a741e8 27e835e 5a741e8 bd6cebd 5a741e8 27e835e 5a741e8 27e835e 804adf6 27e835e 5a741e8 27e835e 5a741e8 27e835e 3f08853 e403ca5 3f08853 aef26d4 ae4aef6 9634b65 c364051 9634b65 c364051 28143df d4c903e 28143df 6c11ebf a656f58 1dfe639 a656f58 815e99c 804adf6 bd6cebd |
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 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 |
'''import gradio as gr
from transformers import TFBertForSequenceClassification, BertTokenizer
import tensorflow as tf
# Load model and tokenizer from your HF model repo
model = TFBertForSequenceClassification.from_pretrained("shrish191/sentiment-bert")
tokenizer = BertTokenizer.from_pretrained("shrish191/sentiment-bert")
def classify_sentiment(text):
inputs = tokenizer(text, return_tensors="tf", padding=True, truncation=True)
predictions = model(inputs).logits
label = tf.argmax(predictions, axis=1).numpy()[0]
labels = {0: "Negative", 1: "Neutral", 2: "Positive"}
return labels[label]
demo = gr.Interface(fn=classify_sentiment,
inputs=gr.Textbox(placeholder="Enter a tweet..."),
outputs="text",
title="Tweet Sentiment Classifier",
description="Multilingual BERT-based Sentiment Analysis")
demo.launch()
'''
'''
import gradio as gr
from transformers import TFBertForSequenceClassification, BertTokenizer
import tensorflow as tf
# Load model and tokenizer from Hugging Face
model = TFBertForSequenceClassification.from_pretrained("shrish191/sentiment-bert")
tokenizer = BertTokenizer.from_pretrained("shrish191/sentiment-bert")
# Manually define the correct mapping
LABELS = {
0: "Neutral",
1: "Positive",
2: "Negative"
}
def classify_sentiment(text):
inputs = tokenizer(text, return_tensors="tf", truncation=True, padding=True)
outputs = model(inputs)
probs = tf.nn.softmax(outputs.logits, axis=1)
pred_label = tf.argmax(probs, axis=1).numpy()[0]
confidence = float(tf.reduce_max(probs).numpy())
return f"Prediction: {LABELS[pred_label]} (Confidence: {confidence:.2f})"
demo = gr.Interface(
fn=classify_sentiment,
inputs=gr.Textbox(placeholder="Type your tweet here..."),
outputs="text",
title="Sentiment Analysis on Tweets",
description="Multilingual BERT model fine-tuned for sentiment classification. Labels: Positive, Neutral, Negative."
)
demo.launch()
'''
'''
import gradio as gr
from transformers import TFBertForSequenceClassification, BertTokenizer
import tensorflow as tf
import snscrape.modules.twitter as sntwitter
import praw
import os
# Load model and tokenizer
model = TFBertForSequenceClassification.from_pretrained("shrish191/sentiment-bert")
tokenizer = BertTokenizer.from_pretrained("shrish191/sentiment-bert")
# Label Mapping
LABELS = {
0: "Neutral",
1: "Positive",
2: "Negative"
}
# Reddit API setup with environment variables
reddit = praw.Reddit(
client_id=os.getenv("REDDIT_CLIENT_ID"),
client_secret=os.getenv("REDDIT_CLIENT_SECRET"),
user_agent=os.getenv("REDDIT_USER_AGENT", "sentiment-classifier-script")
)
# Tweet text extractor
def fetch_tweet_text(tweet_url):
try:
tweet_id = tweet_url.split("/")[-1]
for tweet in sntwitter.TwitterTweetScraper(tweet_id).get_items():
return tweet.content
return "Unable to extract tweet content."
except Exception as e:
return f"Error fetching tweet: {str(e)}"
# Reddit post extractor
def fetch_reddit_text(reddit_url):
try:
submission = reddit.submission(url=reddit_url)
return f"{submission.title}\n\n{submission.selftext}"
except Exception as e:
return f"Error fetching Reddit post: {str(e)}"
# Sentiment classification logic
def classify_sentiment(text_input, tweet_url, reddit_url):
if reddit_url.strip():
text = fetch_reddit_text(reddit_url)
elif tweet_url.strip():
text = fetch_tweet_text(tweet_url)
elif text_input.strip():
text = text_input
else:
return "[!] Please enter text or a post URL."
if text.lower().startswith("error") or "Unable to extract" in text:
return f"[!] Error: {text}"
try:
inputs = tokenizer(text, return_tensors="tf", truncation=True, padding=True)
outputs = model(inputs)
probs = tf.nn.softmax(outputs.logits, axis=1)
pred_label = tf.argmax(probs, axis=1).numpy()[0]
confidence = float(tf.reduce_max(probs).numpy())
return f"Prediction: {LABELS[pred_label]} (Confidence: {confidence:.2f})"
except Exception as e:
return f"[!] Prediction error: {str(e)}"
# Gradio Interface
demo = gr.Interface(
fn=classify_sentiment,
inputs=[
gr.Textbox(label="Custom Text Input", placeholder="Type your tweet or message here..."),
gr.Textbox(label="Tweet URL", placeholder="Paste a tweet URL here (optional)"),
gr.Textbox(label="Reddit Post URL", placeholder="Paste a Reddit post URL here (optional)")
],
outputs="text",
title="Multilingual Sentiment Analysis",
description="Analyze sentiment of text, tweets, or Reddit posts. Supports multiple languages using BERT!"
)
demo.launch()
'''
'''
import gradio as gr
from transformers import TFBertForSequenceClassification, BertTokenizer
import tensorflow as tf
import praw
import os
from transformers import AutoTokenizer, AutoModelForSequenceClassification
import torch
from scipy.special import softmax
model = TFBertForSequenceClassification.from_pretrained("shrish191/sentiment-bert")
tokenizer = BertTokenizer.from_pretrained("shrish191/sentiment-bert")
LABELS = {
0: "Neutral",
1: "Positive",
2: "Negative"
}
fallback_model_name = "cardiffnlp/twitter-roberta-base-sentiment"
fallback_tokenizer = AutoTokenizer.from_pretrained(fallback_model_name)
fallback_model = AutoModelForSequenceClassification.from_pretrained(fallback_model_name)
# Reddit API
reddit = praw.Reddit(
client_id=os.getenv("REDDIT_CLIENT_ID"),
client_secret=os.getenv("REDDIT_CLIENT_SECRET"),
user_agent=os.getenv("REDDIT_USER_AGENT", "sentiment-classifier-ui")
)
def fetch_reddit_text(reddit_url):
try:
submission = reddit.submission(url=reddit_url)
return f"{submission.title}\n\n{submission.selftext}"
except Exception as e:
return f"Error fetching Reddit post: {str(e)}"
def fallback_classifier(text):
encoded_input = fallback_tokenizer(text, return_tensors='pt', truncation=True, padding=True)
with torch.no_grad():
output = fallback_model(**encoded_input)
scores = softmax(output.logits.numpy()[0])
labels = ['Negative', 'Neutral', 'Positive']
return f"Prediction: {labels[scores.argmax()]}"
def classify_sentiment(text_input, reddit_url):
if reddit_url.strip():
text = fetch_reddit_text(reddit_url)
elif text_input.strip():
text = text_input
else:
return "[!] Please enter some text or a Reddit post URL."
if text.lower().startswith("error") or "Unable to extract" in text:
return f"[!] {text}"
try:
inputs = tokenizer(text, return_tensors="tf", truncation=True, padding=True)
outputs = model(inputs)
probs = tf.nn.softmax(outputs.logits, axis=1)
confidence = float(tf.reduce_max(probs).numpy())
pred_label = tf.argmax(probs, axis=1).numpy()[0]
if confidence < 0.5:
return fallback_classifier(text)
return f"Prediction: {LABELS[pred_label]}"
except Exception as e:
return f"[!] Prediction error: {str(e)}"
# Gradio interface
demo = gr.Interface(
fn=classify_sentiment,
inputs=[
gr.Textbox(
label="Text Input (can be tweet or any content)",
placeholder="Paste tweet or type any content here...",
lines=4
),
gr.Textbox(
label="Reddit Post URL",
placeholder="Paste a Reddit post URL (optional)",
lines=1
),
],
outputs="text",
title="Sentiment Analyzer",
description="π Paste any text (including tweet content) OR a Reddit post URL to analyze sentiment.\n\nπ‘ Tweet URLs are not supported directly due to platform restrictions. Please paste tweet content manually."
)
demo.launch()
'''
'''
import gradio as gr
from transformers import TFBertForSequenceClassification, BertTokenizer
import tensorflow as tf
import praw
import os
import pytesseract
from PIL import Image
import cv2
import numpy as np
import re
from transformers import AutoTokenizer, AutoModelForSequenceClassification
import torch
from scipy.special import softmax
# Install tesseract OCR (only runs once in Hugging Face Spaces)
os.system("apt-get update && apt-get install -y tesseract-ocr")
# Load main model
model = TFBertForSequenceClassification.from_pretrained("shrish191/sentiment-bert")
tokenizer = BertTokenizer.from_pretrained("shrish191/sentiment-bert")
LABELS = {
0: "Neutral",
1: "Positive",
2: "Negative"
}
# Load fallback model
fallback_model_name = "cardiffnlp/twitter-roberta-base-sentiment"
fallback_tokenizer = AutoTokenizer.from_pretrained(fallback_model_name)
fallback_model = AutoModelForSequenceClassification.from_pretrained(fallback_model_name)
# Reddit API setup
reddit = praw.Reddit(
client_id=os.getenv("REDDIT_CLIENT_ID"),
client_secret=os.getenv("REDDIT_CLIENT_SECRET"),
user_agent=os.getenv("REDDIT_USER_AGENT", "sentiment-classifier-ui")
)
def fetch_reddit_text(reddit_url):
try:
submission = reddit.submission(url=reddit_url)
return f"{submission.title}\n\n{submission.selftext}"
except Exception as e:
return f"Error fetching Reddit post: {str(e)}"
def fallback_classifier(text):
encoded_input = fallback_tokenizer(text, return_tensors='pt', truncation=True, padding=True)
with torch.no_grad():
output = fallback_model(**encoded_input)
scores = softmax(output.logits.numpy()[0])
labels = ['Negative', 'Neutral', 'Positive']
return f"Prediction: {labels[scores.argmax()]}"
def clean_ocr_text(text):
text = text.strip()
text = re.sub(r'\s+', ' ', text) # Replace multiple spaces and newlines
text = re.sub(r'[^\x00-\x7F]+', '', text) # Remove non-ASCII characters
return text
def classify_sentiment(text_input, reddit_url, image):
if reddit_url.strip():
text = fetch_reddit_text(reddit_url)
elif image is not None:
try:
img_array = np.array(image)
gray = cv2.cvtColor(img_array, cv2.COLOR_RGB2GRAY)
_, thresh = cv2.threshold(gray, 150, 255, cv2.THRESH_BINARY)
text = pytesseract.image_to_string(thresh)
text = clean_ocr_text(text)
except Exception as e:
return f"[!] OCR failed: {str(e)}"
elif text_input.strip():
text = text_input
else:
return "[!] Please enter some text, upload an image, or provide a Reddit URL."
if text.lower().startswith("error") or "Unable to extract" in text:
return f"[!] {text}"
try:
inputs = tokenizer(text, return_tensors="tf", truncation=True, padding=True)
outputs = model(inputs)
probs = tf.nn.softmax(outputs.logits, axis=1)
confidence = float(tf.reduce_max(probs).numpy())
pred_label = tf.argmax(probs, axis=1).numpy()[0]
if confidence < 0.5:
return fallback_classifier(text)
return f"Prediction: {LABELS[pred_label]}"
except Exception as e:
return f"[!] Prediction error: {str(e)}"
# Gradio interface
demo = gr.Interface(
fn=classify_sentiment,
inputs=[
gr.Textbox(
label="Text Input (can be tweet or any content)",
placeholder="Paste tweet or type any content here...",
lines=4
),
gr.Textbox(
label="Reddit Post URL",
placeholder="Paste a Reddit post URL (optional)",
lines=1
),
gr.Image(
label="Upload Image (optional)",
type="pil"
)
],
outputs="text",
title="Sentiment Analyzer",
description="π Paste any text, Reddit post URL, or upload an image containing text to analyze sentiment.\n\nπ‘ Tweet URLs are not supported. Please paste tweet content or screenshot instead."
)
demo.launch()
'''
import gradio as gr
from transformers import TFBertForSequenceClassification, BertTokenizer
import tensorflow as tf
import praw
import os
import pytesseract
from PIL import Image
import cv2
import numpy as np
import re
from transformers import AutoTokenizer, AutoModelForSequenceClassification
import torch
from scipy.special import softmax
import matplotlib.pyplot as plt
import pandas as pd
# Install tesseract OCR (only runs once in Hugging Face Spaces)
os.system("apt-get update && apt-get install -y tesseract-ocr")
# Load main model
model = TFBertForSequenceClassification.from_pretrained("shrish191/sentiment-bert")
tokenizer = BertTokenizer.from_pretrained("shrish191/sentiment-bert")
LABELS = {0: "Neutral", 1: "Positive", 2: "Negative"}
# Load fallback model
fallback_model_name = "cardiffnlp/twitter-roberta-base-sentiment"
fallback_tokenizer = AutoTokenizer.from_pretrained(fallback_model_name)
fallback_model = AutoModelForSequenceClassification.from_pretrained(fallback_model_name)
# Reddit API setup
reddit = praw.Reddit(
client_id=os.getenv("REDDIT_CLIENT_ID"),
client_secret=os.getenv("REDDIT_CLIENT_SECRET"),
user_agent=os.getenv("REDDIT_USER_AGENT", "sentiment-classifier-ui")
)
def fetch_reddit_text(reddit_url):
try:
submission = reddit.submission(url=reddit_url)
return f"{submission.title}\n\n{submission.selftext}"
except Exception as e:
return f"Error fetching Reddit post: {str(e)}"
def fallback_classifier(text):
encoded_input = fallback_tokenizer(text, return_tensors='pt', truncation=True, padding=True)
with torch.no_grad():
output = fallback_model(**encoded_input)
scores = softmax(output.logits.numpy()[0])
labels = ['Negative', 'Neutral', 'Positive']
return f"Prediction: {labels[scores.argmax()]}"
def clean_ocr_text(text):
text = text.strip()
text = re.sub(r'\s+', ' ', text)
text = re.sub(r'[^\x00-\x7F]+', '', text)
return text
def classify_sentiment(text_input, reddit_url, image):
if reddit_url.strip():
text = fetch_reddit_text(reddit_url)
elif image is not None:
try:
img_array = np.array(image)
gray = cv2.cvtColor(img_array, cv2.COLOR_RGB2GRAY)
_, thresh = cv2.threshold(gray, 150, 255, cv2.THRESH_BINARY)
text = pytesseract.image_to_string(thresh)
text = clean_ocr_text(text)
except Exception as e:
return f"[!] OCR failed: {str(e)}"
elif text_input.strip():
text = text_input
else:
return "[!] Please enter some text, upload an image, or provide a Reddit URL."
if text.lower().startswith("error") or "Unable to extract" in text:
return f"[!] {text}"
try:
inputs = tokenizer(text, return_tensors="tf", truncation=True, padding=True)
outputs = model(inputs)
probs = tf.nn.softmax(outputs.logits, axis=1)
confidence = float(tf.reduce_max(probs).numpy())
pred_label = tf.argmax(probs, axis=1).numpy()[0]
if confidence < 0.5:
return fallback_classifier(text)
return f"Prediction: {LABELS[pred_label]}"
except Exception as e:
return f"[!] Prediction error: {str(e)}"
# Subreddit sentiment analysis function
def analyze_subreddit(subreddit_name):
try:
subreddit = reddit.subreddit(subreddit_name)
posts = list(subreddit.hot(limit=20))
sentiments = []
titles = []
for post in posts:
text = f"{post.title}\n{post.selftext}"
try:
inputs = tokenizer(text, return_tensors="tf", truncation=True, padding=True)
outputs = model(inputs)
probs = tf.nn.softmax(outputs.logits, axis=1)
confidence = float(tf.reduce_max(probs).numpy())
pred_label = tf.argmax(probs, axis=1).numpy()[0]
sentiment = LABELS[pred_label] if confidence >= 0.5 else fallback_classifier(text).split(": ")[-1]
except:
sentiment = "Error"
sentiments.append(sentiment)
titles.append(post.title)
df = pd.DataFrame({"Title": titles, "Sentiment": sentiments})
sentiment_counts = df["Sentiment"].value_counts()
# Plot bar chart
fig, ax = plt.subplots()
sentiment_counts.plot(kind="bar", color=["red", "green", "gray"], ax=ax)
ax.set_title(f"Sentiment Distribution in r/{subreddit_name}")
ax.set_xlabel("Sentiment")
ax.set_ylabel("Number of Posts")
return fig, df
except Exception as e:
return f"[!] Error: {str(e)}", pd.DataFrame()
# Gradio tab 1: Text/Image/Reddit Post Analysis
main_interface = gr.Interface(
fn=classify_sentiment,
inputs=[
gr.Textbox(
label="Text Input (can be tweet or any content)",
placeholder="Paste tweet or type any content here...",
lines=4
),
gr.Textbox(
label="Reddit Post URL",
placeholder="Paste a Reddit post URL (optional)",
lines=1
),
gr.Image(
label="Upload Image (optional)",
type="pil"
)
],
outputs="text",
title="Sentiment Analyzer",
description="π Paste any text, Reddit post URL, or upload an image containing text to analyze sentiment.\n\nπ‘ Tweet URLs are not supported. Please paste tweet content or screenshot instead."
)
# Gradio tab 2: Subreddit Analysis
subreddit_interface = gr.Interface(
fn=analyze_subreddit,
inputs=gr.Textbox(label="Subreddit Name", placeholder="e.g., AskReddit"),
outputs=[
gr.Plot(label="Sentiment Distribution"),
gr.Dataframe(label="Post Titles and Sentiments", wrap=True)
],
title="Subreddit Sentiment Analysis",
description="π Enter a subreddit to analyze sentiment of its top 20 hot posts."
)
# Tabs
demo = gr.TabbedInterface(
interface_list=[main_interface, subreddit_interface],
tab_names=["General Sentiment Analysis", "Subreddit Analysis"]
)
demo.launch()
|