Martin Rodrigo Morales commited on
Commit
a8e77be
·
1 Parent(s): e73dd4a

Fix: Improve probability plots with labels and better error handling

Browse files
Files changed (1) hide show
  1. app.py +59 -14
app.py CHANGED
@@ -93,10 +93,11 @@ class SentimentAnalyzer:
93
  # Initialize analyzer
94
  analyzer = SentimentAnalyzer()
95
 
96
- def analyze_sentiment(text: str) -> Tuple[str, float, dict]:
97
  """Main analysis function for Gradio"""
98
  result = analyzer.analyze_single(text)
99
 
 
100
  if result["probabilities"]:
101
  df = pd.DataFrame([
102
  {"Sentiment": "Negative", "Probability": result["probabilities"]["Negative"]},
@@ -109,27 +110,56 @@ def analyze_sentiment(text: str) -> Tuple[str, float, dict]:
109
  y="Probability",
110
  color="Sentiment",
111
  color_discrete_map={"Negative": "#ff4444", "Positive": "#44ff44"},
112
- title="Sentiment Probability Distribution"
 
113
  )
114
- fig.update_layout(showlegend=False, height=300)
 
 
 
 
 
 
 
 
 
115
 
116
- return (
117
- f"**{result['sentiment']}** (Confidence: {result['confidence']:.1%})",
118
- result['confidence'],
119
- fig
 
 
 
120
  )
 
 
121
 
122
- return result['sentiment'], result['confidence'], None
123
 
124
- def analyze_batch_texts(text_input: str) -> Tuple[str, dict]:
125
  """Analyze multiple texts separated by newlines"""
126
  if not text_input.strip():
127
- return "Please enter some texts (one per line)", None
 
 
 
 
 
 
 
128
 
129
  texts = [line.strip() for line in text_input.split('\n') if line.strip()]
130
 
131
  if not texts:
132
- return "No valid texts found", None
 
 
 
 
 
 
 
133
 
134
  results = analyzer.analyze_batch(texts)
135
 
@@ -149,6 +179,7 @@ def analyze_batch_texts(text_input: str) -> Tuple[str, dict]:
149
 
150
  summary = "\n".join(summary_lines)
151
 
 
152
  if plot_data:
153
  df = pd.DataFrame(plot_data)
154
  fig = px.bar(
@@ -157,12 +188,26 @@ def analyze_batch_texts(text_input: str) -> Tuple[str, dict]:
157
  y="Confidence",
158
  color="Sentiment",
159
  color_discrete_map={"NEGATIVE": "#ff4444", "POSITIVE": "#44ff44"},
160
- title="Batch Analysis Results"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
161
  )
162
  fig.update_layout(height=400)
163
-
164
- return summary, fig
165
 
 
166
  return summary, None
167
 
168
  # Demo examples
 
93
  # Initialize analyzer
94
  analyzer = SentimentAnalyzer()
95
 
96
+ def analyze_sentiment(text: str) -> Tuple[str, float, go.Figure]:
97
  """Main analysis function for Gradio"""
98
  result = analyzer.analyze_single(text)
99
 
100
+ # Create figure even if no text to avoid None errors
101
  if result["probabilities"]:
102
  df = pd.DataFrame([
103
  {"Sentiment": "Negative", "Probability": result["probabilities"]["Negative"]},
 
110
  y="Probability",
111
  color="Sentiment",
112
  color_discrete_map={"Negative": "#ff4444", "Positive": "#44ff44"},
113
+ title="Sentiment Probability Distribution",
114
+ text="Probability"
115
  )
116
+ fig.update_traces(texttemplate='%{text:.2%}', textposition='outside')
117
+ fig.update_layout(
118
+ showlegend=False,
119
+ height=300,
120
+ yaxis_range=[0, 1],
121
+ yaxis_title="Probability",
122
+ xaxis_title="Sentiment"
123
+ )
124
+
125
+ output_text = f"**{result['sentiment']}** (Confidence: {result['confidence']:.1%})"
126
 
127
+ else:
128
+ # Create empty figure for error cases
129
+ fig = go.Figure()
130
+ fig.add_annotation(
131
+ text="No data to display",
132
+ xref="paper", yref="paper",
133
+ x=0.5, y=0.5, showarrow=False
134
  )
135
+ fig.update_layout(height=300)
136
+ output_text = result['sentiment']
137
 
138
+ return output_text, result['confidence'], fig
139
 
140
+ def analyze_batch_texts(text_input: str) -> Tuple[str, go.Figure]:
141
  """Analyze multiple texts separated by newlines"""
142
  if not text_input.strip():
143
+ empty_fig = go.Figure()
144
+ empty_fig.add_annotation(
145
+ text="Please enter texts to analyze",
146
+ xref="paper", yref="paper",
147
+ x=0.5, y=0.5, showarrow=False
148
+ )
149
+ empty_fig.update_layout(height=400)
150
+ return "Please enter some texts (one per line)", empty_fig
151
 
152
  texts = [line.strip() for line in text_input.split('\n') if line.strip()]
153
 
154
  if not texts:
155
+ empty_fig = go.Figure()
156
+ empty_fig.add_annotation(
157
+ text="No valid texts found",
158
+ xref="paper", yref="paper",
159
+ x=0.5, y=0.5, showarrow=False
160
+ )
161
+ empty_fig.update_layout(height=400)
162
+ return "No valid texts found", empty_fig
163
 
164
  results = analyzer.analyze_batch(texts)
165
 
 
179
 
180
  summary = "\n".join(summary_lines)
181
 
182
+ # Always create a figure
183
  if plot_data:
184
  df = pd.DataFrame(plot_data)
185
  fig = px.bar(
 
188
  y="Confidence",
189
  color="Sentiment",
190
  color_discrete_map={"NEGATIVE": "#ff4444", "POSITIVE": "#44ff44"},
191
+ title="Batch Analysis Results",
192
+ text="Confidence"
193
+ )
194
+ fig.update_traces(texttemplate='%{text:.1%}', textposition='outside')
195
+ fig.update_layout(
196
+ height=400,
197
+ yaxis_range=[0, 1.1],
198
+ yaxis_title="Confidence",
199
+ xaxis_title="Text Number"
200
+ )
201
+ else:
202
+ fig = go.Figure()
203
+ fig.add_annotation(
204
+ text="No results to display",
205
+ xref="paper", yref="paper",
206
+ x=0.5, y=0.5, showarrow=False
207
  )
208
  fig.update_layout(height=400)
 
 
209
 
210
+ return summary, fig
211
  return summary, None
212
 
213
  # Demo examples