shrish191 commited on
Commit
829d082
·
verified ·
1 Parent(s): b3dcea1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +83 -0
app.py CHANGED
@@ -21,6 +21,7 @@ demo = gr.Interface(fn=classify_sentiment,
21
 
22
  demo.launch()
23
  '''
 
24
  import gradio as gr
25
  from transformers import TFBertForSequenceClassification, BertTokenizer
26
  import tensorflow as tf
@@ -53,5 +54,87 @@ demo = gr.Interface(
53
  )
54
 
55
  demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56
 
57
 
 
21
 
22
  demo.launch()
23
  '''
24
+ '''
25
  import gradio as gr
26
  from transformers import TFBertForSequenceClassification, BertTokenizer
27
  import tensorflow as tf
 
54
  )
55
 
56
  demo.launch()
57
+ '''
58
+ import gradio as gr
59
+ from transformers import TFBertForSequenceClassification, BertTokenizer
60
+ import tensorflow as tf
61
+ import snscrape.modules.twitter as sntwitter
62
+ import praw
63
+ import os
64
+
65
+ # Load model and tokenizer
66
+ model = TFBertForSequenceClassification.from_pretrained("shrish191/sentiment-bert")
67
+ tokenizer = BertTokenizer.from_pretrained("shrish191/sentiment-bert")
68
+
69
+ # Label Mapping
70
+ LABELS = {
71
+ 0: "Neutral",
72
+ 1: "Positive",
73
+ 2: "Negative"
74
+ }
75
+
76
+ # Reddit API setup with environment variables
77
+ reddit = praw.Reddit(
78
+ client_id=os.getenv("REDDIT_CLIENT_ID"),
79
+ client_secret=os.getenv("REDDIT_CLIENT_SECRET"),
80
+ user_agent=os.getenv("REDDIT_USER_AGENT", "sentiment-classifier-script")
81
+ )
82
+
83
+ # Tweet text extractor
84
+ def fetch_tweet_text(tweet_url):
85
+ try:
86
+ tweet_id = tweet_url.split("/")[-1]
87
+ for tweet in sntwitter.TwitterTweetScraper(tweet_id).get_items():
88
+ return tweet.content
89
+ return "Unable to extract tweet content."
90
+ except Exception as e:
91
+ return f"Error fetching tweet: {str(e)}"
92
+
93
+ # Reddit post extractor
94
+ def fetch_reddit_text(reddit_url):
95
+ try:
96
+ submission = reddit.submission(url=reddit_url)
97
+ return f"{submission.title}\n\n{submission.selftext}"
98
+ except Exception as e:
99
+ return f"Error fetching Reddit post: {str(e)}"
100
+
101
+ # Sentiment classification logic
102
+ def classify_sentiment(text_input, tweet_url, reddit_url):
103
+ if reddit_url.strip():
104
+ text = fetch_reddit_text(reddit_url)
105
+ elif tweet_url.strip():
106
+ text = fetch_tweet_text(tweet_url)
107
+ elif text_input.strip():
108
+ text = text_input
109
+ else:
110
+ return "[!] Please enter text or a post URL."
111
+
112
+ if text.lower().startswith("error") or "Unable to extract" in text:
113
+ return f"[!] Error: {text}"
114
+
115
+ try:
116
+ inputs = tokenizer(text, return_tensors="tf", truncation=True, padding=True)
117
+ outputs = model(inputs)
118
+ probs = tf.nn.softmax(outputs.logits, axis=1)
119
+ pred_label = tf.argmax(probs, axis=1).numpy()[0]
120
+ confidence = float(tf.reduce_max(probs).numpy())
121
+ return f"Prediction: {LABELS[pred_label]} (Confidence: {confidence:.2f})"
122
+ except Exception as e:
123
+ return f"[!] Prediction error: {str(e)}"
124
+
125
+ # Gradio Interface
126
+ demo = gr.Interface(
127
+ fn=classify_sentiment,
128
+ inputs=[
129
+ gr.Textbox(label="Custom Text Input", placeholder="Type your tweet or message here..."),
130
+ gr.Textbox(label="Tweet URL", placeholder="Paste a tweet URL here (optional)"),
131
+ gr.Textbox(label="Reddit Post URL", placeholder="Paste a Reddit post URL here (optional)")
132
+ ],
133
+ outputs="text",
134
+ title="Multilingual Sentiment Analysis",
135
+ description="Analyze sentiment of text, tweets, or Reddit posts. Supports multiple languages using BERT!"
136
+ )
137
+
138
+ demo.launch()
139
 
140