Light-Dav commited on
Commit
8a03f45
Β·
verified Β·
1 Parent(s): 313788c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +79 -81
app.py CHANGED
@@ -13,63 +13,71 @@ except Exception as e:
13
  sentiment_analyzer = None
14
  model_loaded_successfully = False
15
 
16
- # --- Custom CSS for a unique look ---
17
  custom_css = """
18
  body {
19
- background-color: #f0f2f5; /* Light grey background */
 
20
  }
21
  .gradio-container {
22
- box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
23
- border-radius: 15px;
24
  overflow: hidden;
25
- background-color: #ffffff; /* White card background */
 
 
26
  }
27
  h1, h2, h3 {
28
- color: #4CAF50; /* Green accents */
29
  text-align: center;
30
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
31
  animation: fadeIn 1s ease-in-out;
32
  }
33
  .gr-button.primary {
34
- background-color: #4CAF50 !important;
35
- color: white !important;
36
- border-radius: 8px;
37
  transition: background-color 0.3s ease;
 
38
  }
39
  .gr-button.primary:hover {
40
- background-color: #45a049 !important;
41
  }
42
  .gradio-output {
43
- border: 1px solid #e0e0e0;
44
- border-radius: 10px;
45
  padding: 15px;
46
- margin-top: 20px;
47
- background-color: #f9f9f9;
 
48
  }
49
  .sentiment-display {
50
  text-align: center;
51
  padding: 10px;
52
- border-radius: 8px;
53
- margin-top: 15px;
54
- font-size: 1.2em;
55
  font-weight: bold;
56
  }
57
  .sentiment-positive {
58
- background-color: #e6ffe6; /* Light green */
59
- color: #28a745; /* Darker green */
60
  }
61
  .sentiment-negative {
62
- background-color: #ffe6e6; /* Light red */
63
- color: #dc3545; /* Darker red */
64
  }
65
  .sentiment-neutral {
66
- background-color: #e6f7ff; /* Light blue */
67
- color: #007bff; /* Darker blue */
68
  }
69
  @keyframes fadeIn {
70
  from { opacity: 0; }
71
  to { opacity: 1; }
72
  }
 
 
 
73
  """
74
 
75
  # --- Helper Function for Sentiment Interpretation ---
@@ -78,18 +86,15 @@ def interpret_sentiment(label, score):
78
  description = ""
79
  color_class = ""
80
 
81
- # IMPORTANT: Adjust 'LABEL_0', 'LABEL_1', 'LABEL_2' to your model's actual output labels
82
- # Check your model's config.json on Hugging Face Hub under 'id2label' or 'label2id'
83
- # Example: "id2label": {"0": "negative", "1": "neutral", "2": "positive"}
84
- if label.lower() == "positive" or label.lower() == "label_2": # Assuming LABEL_2 is positive
85
  emoji = "😊"
86
  description = "This text expresses a **highly positive** sentiment." if score > 0.9 else "This text expresses a **positive** sentiment."
87
  color_class = "sentiment-positive"
88
- elif label.lower() == "negative" or label.lower() == "label_0": # Assuming LABEL_0 is negative
89
  emoji = "😠"
90
  description = "This text expresses a **highly negative** sentiment." if score > 0.9 else "This text expresses a **negative** sentiment."
91
  color_class = "sentiment-negative"
92
- elif label.lower() == "neutral" or label.lower() == "label_1": # Assuming LABEL_1 is neutral
93
  emoji = "😐"
94
  description = "This text expresses a **neutral** sentiment."
95
  color_class = "sentiment-neutral"
@@ -97,7 +102,7 @@ def interpret_sentiment(label, score):
97
  emoji = "❓"
98
  description = "Could not confidently determine sentiment. Unexpected label."
99
  color_class = ""
100
-
101
  return f"<div class='sentiment-display {color_class}'>{emoji} {label.upper()} ({score:.2f})</div>" + \
102
  f"<p>{description}</p>"
103
 
@@ -118,11 +123,11 @@ def analyze_sentiment(text):
118
  }
119
 
120
  try:
121
- results = sentiment_analyzer(text)[0]
122
 
123
  results_sorted = sorted(results, key=lambda x: x['score'], reverse=True)
124
 
125
- top_sentiment = results_sorted[0]
126
  label = top_sentiment['label']
127
  score = top_sentiment['score']
128
 
@@ -143,60 +148,53 @@ def analyze_sentiment(text):
143
  }
144
 
145
  # --- Gradio Interface ---
146
- with gr.Blocks(css=custom_css, theme=gr.themes.Soft()) as demo:
147
- gr.Markdown("# ✨ Sentiment Spark ��")
148
- gr.Markdown("---")
149
- gr.Markdown("### Uncover the emotional tone of your English text instantly!")
150
-
151
- with gr.Row():
152
- with gr.Column(scale=2):
153
- text_input = gr.Textbox(
154
- lines=7,
155
- placeholder="Type your English text here...",
156
- label="Your Text",
157
- interactive=True,
158
- value="This movie was absolutely brilliant! A masterpiece of storytelling and emotion."
159
- )
160
- analyze_btn = gr.Button("Analyze Sentiment", variant="primary")
161
-
162
- # --- Define outputs BEFORE gr.Examples ---
163
- # These variables need to exist before they are referenced in gr.Examples
164
- gr.Markdown("## πŸ“ˆ Analysis Results πŸ“‰")
165
- overall_sentiment_output = gr.HTML(label="Overall Sentiment")
166
- confidence_scores_output = gr.Label(num_top_classes=3, label="Confidence Scores")
167
- raw_output = gr.JSON(label="Raw Model Output", visible=False)
168
- # ----------------------------------------
169
-
170
- gr.Markdown("---")
171
- gr.Markdown("### Try some examples:")
172
- gr.Examples(
173
- examples=[
174
- ["This product exceeded my expectations, truly amazing!"],
175
- ["I found the customer service to be quite disappointing and slow."],
176
- ["The weather forecast predicts light rain for tomorrow morning."],
177
- ["What a fantastic experience! Highly recommend it."],
178
- ["I'm so frustrated with this slow internet connection."],
179
- ["The meeting concluded without any major decisions."]
180
- ],
181
- inputs=text_input,
182
- fn=analyze_sentiment, # Function to run for examples
183
- outputs=[overall_sentiment_output, confidence_scores_output, raw_output], # Outputs for examples
184
- cache_examples=True # Caching examples for faster loading
185
- )
186
-
187
-
188
- # --- Event Listeners ---
189
- text_input.change(
190
  fn=analyze_sentiment,
191
  inputs=text_input,
192
- outputs=[overall_sentiment_output, confidence_scores_output, raw_output],
193
- # live=True
194
  )
195
- analyze_btn.click(
196
  fn=analyze_sentiment,
197
  inputs=text_input,
198
- outputs=[overall_sentiment_output, confidence_scores_output, raw_output]
 
199
  )
200
 
201
- # Launch the Gradio application
202
  demo.launch()
 
13
  sentiment_analyzer = None
14
  model_loaded_successfully = False
15
 
16
+ # --- Custom CSS for a dark look inspired by the website ---
17
  custom_css = """
18
  body {
19
+ background-color: #121212; /* Dark background */
20
+ color: #f8f8f2; /* Light text */
21
  }
22
  .gradio-container {
23
+ box-shadow: 0 4px 8px rgba(255, 255, 255, 0.1);
24
+ border-radius: 10px;
25
  overflow: hidden;
26
+ background-color: #1e1e1e; /* Darker card background */
27
+ padding: 20px;
28
+ margin-bottom: 20px;
29
  }
30
  h1, h2, h3 {
31
+ color: #80cbc4; /* Teal/Cyan accents */
32
  text-align: center;
33
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
34
  animation: fadeIn 1s ease-in-out;
35
  }
36
  .gr-button.primary {
37
+ background-color: #80cbc4 !important;
38
+ color: #1e1e1e !important;
39
+ border-radius: 6px;
40
  transition: background-color 0.3s ease;
41
+ padding: 10px 20px;
42
  }
43
  .gr-button.primary:hover {
44
+ background-color: #26a69a !important;
45
  }
46
  .gradio-output {
47
+ border: 1px solid #424242;
48
+ border-radius: 8px;
49
  padding: 15px;
50
+ margin-top: 15px;
51
+ background-color: #212121;
52
+ color: #f8f8f2;
53
  }
54
  .sentiment-display {
55
  text-align: center;
56
  padding: 10px;
57
+ border-radius: 6px;
58
+ margin-top: 10px;
59
+ font-size: 1.1em;
60
  font-weight: bold;
61
  }
62
  .sentiment-positive {
63
+ background-color: #388e3c; /* Darker green */
64
+ color: #e8f5e9; /* Light green */
65
  }
66
  .sentiment-negative {
67
+ background-color: #d32f2f; /* Darker red */
68
+ color: #ffebee; /* Light red */
69
  }
70
  .sentiment-neutral {
71
+ background-color: #1976d2; /* Darker blue */
72
+ color: #e3f2fd; /* Light blue */
73
  }
74
  @keyframes fadeIn {
75
  from { opacity: 0; }
76
  to { opacity: 1; }
77
  }
78
+ gr-textbox > label {
79
+ color: #80cbc4;
80
+ }
81
  """
82
 
83
  # --- Helper Function for Sentiment Interpretation ---
 
86
  description = ""
87
  color_class = ""
88
 
89
+ if label.lower() == "positive" or label.lower() == "label_2":
 
 
 
90
  emoji = "😊"
91
  description = "This text expresses a **highly positive** sentiment." if score > 0.9 else "This text expresses a **positive** sentiment."
92
  color_class = "sentiment-positive"
93
+ elif label.lower() == "negative" or label.lower() == "label_0":
94
  emoji = "😠"
95
  description = "This text expresses a **highly negative** sentiment." if score > 0.9 else "This text expresses a **negative** sentiment."
96
  color_class = "sentiment-negative"
97
+ elif label.lower() == "neutral" or label.lower() == "label_1":
98
  emoji = "😐"
99
  description = "This text expresses a **neutral** sentiment."
100
  color_class = "sentiment-neutral"
 
102
  emoji = "❓"
103
  description = "Could not confidently determine sentiment. Unexpected label."
104
  color_class = ""
105
+
106
  return f"<div class='sentiment-display {color_class}'>{emoji} {label.upper()} ({score:.2f})</div>" + \
107
  f"<p>{description}</p>"
108
 
 
123
  }
124
 
125
  try:
126
+ results = sentiment_analyzer(text)[0]
127
 
128
  results_sorted = sorted(results, key=lambda x: x['score'], reverse=True)
129
 
130
+ top_sentiment = results_sorted(0)
131
  label = top_sentiment['label']
132
  score = top_sentiment['score']
133
 
 
148
  }
149
 
150
  # --- Gradio Interface ---
151
+ with gr.Blocks(css=custom_css, theme=gr.themes.BaseDark()) as demo:
152
+ gr.Markdown("<h1 style='color: #80cbc4; text-align: center;'>🌌 Sentiment Analyzer 🌌</h1>")
153
+ gr.Markdown("<p style='color: #f8f8f2; text-align: center;'>Uncover the emotional tone of your English text instantly.</p>")
154
+
155
+ with gr.Column(elem_classes="gradio-container"):
156
+ text_input = gr.Textbox(
157
+ lines=7,
158
+ placeholder="Type your English text here...",
159
+ label="Your Text",
160
+ interactive=True,
161
+ value="This movie was absolutely brilliant! A masterpiece of storytelling and emotion."
162
+ )
163
+ analyze_btn = gr.Button("Analyze Sentiment", variant="primary")
164
+
165
+ gr.Markdown("<hr style='border-top: 1px solid #424242;'>")
166
+ gr.Markdown("<h3 style='color: #80cbc4; text-align: center;'>Try some examples:</h3>")
167
+ examples = gr.Examples(
168
+ examples=[
169
+ ["This product exceeded my expectations, truly amazing!"],
170
+ ["I found the customer service to be quite disappointing and slow."],
171
+ ["The weather forecast predicts light rain for tomorrow morning."],
172
+ ["What a fantastic experience! Highly recommend it."],
173
+ ["I'm so frustrated with this slow internet connection."],
174
+ ["The meeting concluded without any major decisions."]
175
+ ],
176
+ inputs=text_input,
177
+ fn=analyze_sentiment,
178
+ outputs=[gr.HTML(label="Overall Sentiment"), gr.Label(num_top_classes=3, label="Confidence Scores"), gr.JSON(label="Raw Model Output", visible=False)],
179
+ cache_examples=True
180
+ )
181
+
182
+ gr.Markdown("<hr style='border-top: 1px solid #424242;'>")
183
+ gr.Markdown("<h2 style='color: #80cbc4;'>πŸ“Š Analysis Results</h2>")
184
+ overall_sentiment_output = gr.HTML(label="Overall Sentiment")
185
+ confidence_scores_output = gr.Label(num_top_classes=3, label="Confidence Scores")
186
+ raw_output = gr.JSON(label="Raw Model Output", visible=False)
187
+
188
+ analyze_btn.click(
 
 
 
 
 
 
189
  fn=analyze_sentiment,
190
  inputs=text_input,
191
+ outputs=[overall_sentiment_output, confidence_scores_output, raw_output]
 
192
  )
193
+ text_input.change(
194
  fn=analyze_sentiment,
195
  inputs=text_input,
196
+ outputs=[overall_sentiment_output, confidence_scores_output, raw_output],
197
+ # live=True # Puedes descomentar si quieres actualizaciones en vivo (consume mΓ‘s recursos)
198
  )
199
 
 
200
  demo.launch()