olivercareyncl commited on
Commit
4e7df43
Β·
verified Β·
1 Parent(s): 2562763

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +58 -43
app.py CHANGED
@@ -1,63 +1,78 @@
1
- from transformers import AutoModelForSequenceClassification, AutoTokenizer
2
- import torch
3
  import gradio as gr
 
4
  import matplotlib.pyplot as plt
 
 
 
5
 
6
- # Use a better model for sentiment analysis (Supports Neutral)
7
- MODEL_NAME = "cardiffnlp/twitter-roberta-base-sentiment"
8
 
9
- # Load tokenizer and model
10
- tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
11
- model = AutoModelForSequenceClassification.from_pretrained(MODEL_NAME)
12
 
13
- # Labels for classification
14
- LABELS_MAP = {0: "Negative", 1: "Neutral", 2: "Positive"}
 
15
 
16
- # Function to analyze sentiment
 
 
 
 
 
 
17
  def analyze_sentiment(text):
18
- inputs = tokenizer(text, return_tensors="pt")
19
- outputs = model(**inputs)
 
 
 
20
 
21
- scores = torch.nn.functional.softmax(outputs.logits, dim=-1)
22
- predicted_label = torch.argmax(scores).item()
23
- sentiment = LABELS_MAP[predicted_label]
24
- confidence = scores[0, predicted_label].item()
25
-
26
- # Sentiment mapping for UI
27
  sentiment_map = {
28
- "Positive": ("🟒 Positive 😊", "green"),
29
- "Negative": ("πŸ”΄ Negative 😠", "red"),
30
- "Neutral": ("🟑 Neutral 😐", "orange")
31
  }
32
 
33
- sentiment_label, color = sentiment_map[sentiment]
34
-
35
- # Generate Confidence Score Bar Chart
36
- fig, ax = plt.subplots(figsize=(4, 2))
37
- ax.bar(sentiment, confidence, color=color)
38
- ax.set_ylim([0, 1])
39
- ax.set_ylabel("Confidence Score")
40
- ax.set_title("Sentiment Confidence")
41
-
42
- return sentiment_label, f"Confidence: {confidence:.2f}", fig
 
43
 
44
- # Gradio UI
45
  with gr.Blocks(theme=gr.themes.Soft()) as iface:
46
- gr.Markdown("# πŸ“’ Text Sentiment Analyzer")
47
- gr.Markdown("Analyze the sentiment of your text input and visualize the confidence score.")
48
-
49
  with gr.Row():
50
- text_input = gr.Textbox(lines=2, placeholder="Enter text here...", label="Your Input")
51
-
 
 
 
52
  analyze_button = gr.Button("Analyze Sentiment ✨")
53
-
 
54
  with gr.Row():
55
- sentiment_output = gr.Textbox(label="Sentiment Result", interactive=False)
56
- confidence_output = gr.Textbox(label="Confidence Score", interactive=False)
57
 
58
- chart_output = gr.Plot(label="Confidence Score Chart")
59
-
60
- analyze_button.click(analyze_sentiment, inputs=text_input, outputs=[sentiment_output, confidence_output, chart_output])
 
 
 
 
 
61
 
62
  # Launch the app
63
  if __name__ == "__main__":
 
 
 
1
  import gradio as gr
2
+ from transformers import pipeline
3
  import matplotlib.pyplot as plt
4
+ from wordcloud import WordCloud
5
+ import json
6
+ import os
7
 
8
+ # Load sentiment analysis model
9
+ sentiment_pipeline = pipeline("sentiment-analysis")
10
 
11
+ # Store last input/output using localStorage
12
+ STATE_FILE = "state.json"
 
13
 
14
+ def save_state(text, sentiment, confidence):
15
+ with open(STATE_FILE, "w") as f:
16
+ json.dump({"text": text, "sentiment": sentiment, "confidence": confidence}, f)
17
 
18
+ def load_state():
19
+ if os.path.exists(STATE_FILE):
20
+ with open(STATE_FILE, "r") as f:
21
+ return json.load(f)
22
+ return {"text": "", "sentiment": "", "confidence": ""}
23
+
24
+ # Function to analyze sentiment in real-time
25
  def analyze_sentiment(text):
26
+ if not text.strip():
27
+ return "Enter text to analyze.", "", None, ""
28
+
29
+ result = sentiment_pipeline(text)[0]
30
+ sentiment, confidence = result['label'], result['score']
31
 
 
 
 
 
 
 
32
  sentiment_map = {
33
+ "POSITIVE": ("🟒 Positive 😊", "green"),
34
+ "NEGATIVE": ("πŸ”΄ Negative 😠", "red"),
35
+ "NEUTRAL": ("🟑 Neutral 😐", "orange")
36
  }
37
 
38
+ sentiment_label, color = sentiment_map.get(sentiment.upper(), ("βšͺ Unknown ❓", "gray"))
39
+
40
+ # Generate Word Cloud
41
+ wordcloud = WordCloud(width=400, height=200, background_color="white").generate(text)
42
+ fig, ax = plt.subplots()
43
+ ax.imshow(wordcloud, interpolation='bilinear')
44
+ ax.axis("off")
45
+
46
+ save_state(text, sentiment_label, confidence)
47
+
48
+ return sentiment_label, f"Confidence: {confidence:.2%}", fig, text
49
 
50
+ # UI Layout
51
  with gr.Blocks(theme=gr.themes.Soft()) as iface:
52
+ gr.Markdown("# 🎭 AI Sentiment Analyzer")
53
+ gr.Markdown("Analyze sentiment in real-time with enhanced visualization.")
54
+
55
  with gr.Row():
56
+ dark_mode = gr.Checkbox(label="πŸŒ™ Dark Mode")
57
+
58
+ with gr.Row():
59
+ text_input = gr.Textbox(lines=3, placeholder="Type your text here...", label="Your Input", live=True)
60
+
61
  analyze_button = gr.Button("Analyze Sentiment ✨")
62
+ reset_button = gr.Button("πŸ”„ Reset")
63
+
64
  with gr.Row():
65
+ sentiment_output = gr.Label(label="Sentiment Result")
66
+ confidence_output = gr.Label(label="Confidence Score")
67
 
68
+ wordcloud_output = gr.Plot(label="Word Cloud Visualization")
69
+
70
+ # Load previous session state
71
+ state = load_state()
72
+ text_input.value, sentiment_output.value, confidence_output.value = state['text'], state['sentiment'], state['confidence']
73
+
74
+ analyze_button.click(analyze_sentiment, inputs=text_input, outputs=[sentiment_output, confidence_output, wordcloud_output, text_input])
75
+ reset_button.click(lambda: ("", "", None, ""), inputs=[], outputs=[sentiment_output, confidence_output, wordcloud_output, text_input])
76
 
77
  # Launch the app
78
  if __name__ == "__main__":