Light-Dav commited on
Commit
fbfc3a2
·
verified ·
1 Parent(s): 9d5b24b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +17 -7
app.py CHANGED
@@ -9,12 +9,16 @@ print(f"Gradio version at runtime: {gr.__version__}")
9
  MODEL_ID = "Light-Dav/sentiment-analysis-full-project"
10
 
11
  try:
 
 
12
  sentiment_analyzer = pipeline("sentiment-analysis", model=MODEL_ID, top_k=None)
13
  model_loaded_successfully = True
 
14
  except Exception as e:
15
  print(f"Error loading model: {e}")
16
  sentiment_analyzer = None
17
  model_loaded_successfully = False
 
18
 
19
  # --- Custom CSS for a dark look inspired by the website ---
20
  # Este CSS define todo el aspecto visual sin depender de un tema de Gradio
@@ -132,16 +136,21 @@ def analyze_sentiment(text):
132
  }
133
 
134
  try:
135
- results = sentiment_analyzer(text)[0] # Obtener la primera (y única) lista de resultados
 
136
 
 
137
  results_sorted = sorted(results, key=lambda x: x['score'], reverse=True)
138
 
139
- top_sentiment = results_sorted[0] # <--- CORRECCIÓN IMPORTANTE AQUÍ (era results_sorted(0))
 
140
  label = top_sentiment['label']
141
  score = top_sentiment['score']
142
 
 
143
  confidence_scores_output = {item['label']: item['score'] for item in results}
144
 
 
145
  overall_sentiment_display = interpret_sentiment(label, score)
146
 
147
  return {
@@ -150,6 +159,7 @@ def analyze_sentiment(text):
150
  "Raw Output": str(results)
151
  }
152
  except Exception as e:
 
153
  return {
154
  "Overall Sentiment": f"<div class='sentiment-display'>❌ Error ❌</div><p>An error occurred during analysis: {e}</p>",
155
  "Confidence Scores": {},
@@ -159,7 +169,7 @@ def analyze_sentiment(text):
159
  # --- Gradio Interface ---
160
  # Al establecer theme=None, Gradio no aplicará ningún tema predefinido.
161
  # Todo el estilo visual vendrá de nuestro `custom_css`.
162
- with gr.Blocks(css=custom_css, theme=None) as demo: # <--- CAMBIO CLAVE AQUÍ: theme=None
163
  gr.Markdown("<h1 style='color: #80cbc4; text-align: center;'>🌌 Sentiment Analyzer 🌌</h1>")
164
  gr.Markdown("<p style='color: #f8f8f2; text-align: center;'>Uncover the emotional tone of your English text instantly.</p>")
165
 
@@ -175,8 +185,8 @@ with gr.Blocks(css=custom_css, theme=None) as demo: # <--- CAMBIO CLAVE AQUÍ: t
175
 
176
  gr.Markdown("<hr style='border-top: 1px solid #424242;'>")
177
  gr.Markdown("<h3 style='color: #80cbc4; text-align: center;'>Try some examples:</h3>")
178
- # Aquí definimos los outputs directamente al crear el gr.Examples,
179
- # esto es una forma robusta de manejarlo.
180
  examples = gr.Examples(
181
  examples=[
182
  ["This product exceeded my expectations, truly amazing!"],
@@ -189,12 +199,12 @@ with gr.Blocks(css=custom_css, theme=None) as demo: # <--- CAMBIO CLAVE AQUÍ: t
189
  inputs=text_input,
190
  fn=analyze_sentiment,
191
  outputs=[gr.HTML(label="Overall Sentiment"), gr.Label(num_top_classes=3, label="Confidence Scores"), gr.JSON(label="Raw Model Output", visible=False)],
192
- cache_examples=True
193
  )
194
 
195
  gr.Markdown("<hr style='border-top: 1px solid #424242;'>")
196
  gr.Markdown("<h2 style='color: #80cbc4;'>📊 Analysis Results</h2>")
197
- # Asegúrate de que las variables de salida estén definidas aquí para los listeners
198
  overall_sentiment_output = gr.HTML(label="Overall Sentiment")
199
  confidence_scores_output = gr.Label(num_top_classes=3, label="Confidence Scores")
200
  raw_output = gr.JSON(label="Raw Model Output", visible=False)
 
9
  MODEL_ID = "Light-Dav/sentiment-analysis-full-project"
10
 
11
  try:
12
+ # Esto carga tu modelo pre-entrenado desde Hugging Face Hub
13
+ # top_k=None asegura que se devuelvan las puntuaciones de todas las clases (positivo, negativo, neutral)
14
  sentiment_analyzer = pipeline("sentiment-analysis", model=MODEL_ID, top_k=None)
15
  model_loaded_successfully = True
16
+ print("Sentiment analysis model loaded successfully.")
17
  except Exception as e:
18
  print(f"Error loading model: {e}")
19
  sentiment_analyzer = None
20
  model_loaded_successfully = False
21
+ print("Sentiment analysis model failed to load. Please check MODEL_ID and network connection.")
22
 
23
  # --- Custom CSS for a dark look inspired by the website ---
24
  # Este CSS define todo el aspecto visual sin depender de un tema de Gradio
 
136
  }
137
 
138
  try:
139
+ # Asegúrate de que la salida del pipeline es una lista de listas, y toma la primera.
140
+ results = sentiment_analyzer(text)[0]
141
 
142
+ # Ordenar los resultados por puntuación de confianza de mayor a menor
143
  results_sorted = sorted(results, key=lambda x: x['score'], reverse=True)
144
 
145
+ # Tomar el primer elemento (el de mayor confianza)
146
+ top_sentiment = results_sorted[0]
147
  label = top_sentiment['label']
148
  score = top_sentiment['score']
149
 
150
+ # Crear un diccionario de puntuaciones de confianza para la salida de la etiqueta
151
  confidence_scores_output = {item['label']: item['score'] for item in results}
152
 
153
+ # Generar el HTML para mostrar el sentimiento general
154
  overall_sentiment_display = interpret_sentiment(label, score)
155
 
156
  return {
 
159
  "Raw Output": str(results)
160
  }
161
  except Exception as e:
162
+ # En caso de cualquier error durante el análisis
163
  return {
164
  "Overall Sentiment": f"<div class='sentiment-display'>❌ Error ❌</div><p>An error occurred during analysis: {e}</p>",
165
  "Confidence Scores": {},
 
169
  # --- Gradio Interface ---
170
  # Al establecer theme=None, Gradio no aplicará ningún tema predefinido.
171
  # Todo el estilo visual vendrá de nuestro `custom_css`.
172
+ with gr.Blocks(css=custom_css, theme=None) as demo:
173
  gr.Markdown("<h1 style='color: #80cbc4; text-align: center;'>🌌 Sentiment Analyzer 🌌</h1>")
174
  gr.Markdown("<p style='color: #f8f8f2; text-align: center;'>Uncover the emotional tone of your English text instantly.</p>")
175
 
 
185
 
186
  gr.Markdown("<hr style='border-top: 1px solid #424242;'>")
187
  gr.Markdown("<h3 style='color: #80cbc4; text-align: center;'>Try some examples:</h3>")
188
+
189
+ # IMPORTANTE: Desactivamos cache_examples para evitar el FileNotFoundError
190
  examples = gr.Examples(
191
  examples=[
192
  ["This product exceeded my expectations, truly amazing!"],
 
199
  inputs=text_input,
200
  fn=analyze_sentiment,
201
  outputs=[gr.HTML(label="Overall Sentiment"), gr.Label(num_top_classes=3, label="Confidence Scores"), gr.JSON(label="Raw Model Output", visible=False)],
202
+ cache_examples=False # <--- ESTE ES EL CAMBIO CLAVE PARA ELIMINAR EL FileNotFoundError
203
  )
204
 
205
  gr.Markdown("<hr style='border-top: 1px solid #424242;'>")
206
  gr.Markdown("<h2 style='color: #80cbc4;'>📊 Analysis Results</h2>")
207
+
208
  overall_sentiment_output = gr.HTML(label="Overall Sentiment")
209
  confidence_scores_output = gr.Label(num_top_classes=3, label="Confidence Scores")
210
  raw_output = gr.JSON(label="Raw Model Output", visible=False)