Light-Dav commited on
Commit
810cb59
·
verified ·
1 Parent(s): 5cabd66

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +39 -25
app.py CHANGED
@@ -1,6 +1,7 @@
1
  import gradio as gr
2
  from transformers import pipeline
3
  import os
 
4
 
5
  # Añade esto para verificar la versión de Gradio en tiempo de ejecución
6
  print(f"Gradio version at runtime: {gr.__version__}")
@@ -86,7 +87,7 @@ p {
86
 
87
  /* BOTONES PRINCIPALES */
88
  .gr-button.primary {
89
- background-color: #00BFFF !important; /* Azul Brillante para el botón primario */
90
  color: #1E2B38 !important; /* Texto oscuro para el botón primario */
91
  border-radius: 5px;
92
  transition: background-color 0.3s ease;
@@ -204,40 +205,38 @@ def interpret_sentiment(label, score):
204
  description = ""
205
  color_class = ""
206
 
207
- # Asegúrate de que las etiquetas coincidan con las salidas reales de tu modelo
208
- # 'LABEL_0' es negativo, 'LABEL_1' es neutral, 'LABEL_2' es positivo
209
  if label.lower() == "positive" or label.lower() == "label_2":
210
  emoji = "😊"
211
- description = "Positive sentiment detected." # Mensaje más corto
212
  color_class = "sentiment-positive"
213
  elif label.lower() == "negative" or label.lower() == "label_0":
214
  emoji = "😠"
215
- description = "Negative sentiment detected." # Mensaje más corto
216
  color_class = "sentiment-negative"
217
  elif label.lower() == "neutral" or label.lower() == "label_1":
218
  emoji = "😐"
219
- description = "Neutral sentiment detected." # Mensaje más corto
220
  color_class = "sentiment-neutral"
221
  else:
222
  emoji = "❓"
223
- description = "Sentiment not determined." # Mensaje más corto
224
  color_class = ""
225
 
226
  return f"<div class='sentiment-display {color_class}'>{emoji} {label.upper()} ({score:.2f})</div>" + \
227
- f"<p style='color: #FFFFFF; font-size: 0.75em; margin-top: 3px; margin-bottom: 0;'>{description}</p>" # Asegurar que la descripción sea pequeña
228
 
229
  # --- Sentiment Analysis Function ---
230
  def analyze_sentiment(text):
231
  if not model_loaded_successfully:
232
  return (
233
- "<div class='sentiment-display'>⚠️ Model Error ⚠️</div><p style='color: #FFFFFF; font-size: 0.75em;'>Model not loaded.</p>", # Mensaje más corto
234
  {},
235
  {"error": "Model loading failed."}
236
  )
237
 
238
  if not text.strip():
239
  return (
240
- "<div class='sentiment-display'>✍️ Enter text ✍️</div><p style='color: #FFFFFF; font-size: 0.75em;'>Type text to analyze.</p>", # Mensaje más corto
241
  {},
242
  {"info": "No text entered."}
243
  )
@@ -259,15 +258,35 @@ def analyze_sentiment(text):
259
 
260
  except Exception as e:
261
  return (
262
- f"<div class='sentiment-display'>❌ Error ❌</div><p style='color: #FFFFFF; font-size: 0.75em;'>Analysis failed.</p>", # Mensaje más corto
263
  {},
264
  {"error_message": str(e)}
265
  )
266
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
267
  # --- Gradio Interface ---
268
  with gr.Blocks(css=custom_css, theme=None) as demo:
269
  gr.Markdown("<h1 style='color: #00BFFF;'>🌌 Sentiment Analyzer 🌌</h1>")
270
- gr.Markdown("<p style='color: #AAB7C4;'>Analyze the emotional tone of your English text.</p>") # Párrafo más corto
271
 
272
  with gr.Column(elem_classes="gradio-container"):
273
  text_input = gr.Textbox(
@@ -275,32 +294,27 @@ with gr.Blocks(css=custom_css, theme=None) as demo:
275
  placeholder="Type your English text here...",
276
  label="Your Text",
277
  interactive=True,
278
- value="This movie was absolutely brilliant! A masterpiece of storytelling and emotion."
 
279
  )
280
  analyze_btn = gr.Button("Analyze Sentiment", variant="primary")
281
 
282
  gr.Markdown("<hr>")
283
- gr.Markdown("<h3 style='color: #00BFFF;'>Try examples:</h3>") # Título de ejemplos más corto
284
 
285
  with gr.Row():
 
 
286
  examples = gr.Examples(
287
- examples=[
288
- ["Amazing product!"], # Ejemplos más cortos
289
- ["Very slow service."],
290
- ["Light rain tomorrow."],
291
- ["Fantastic experience!"],
292
- ["Frustrated with internet."],
293
- ["Meeting concluded."]
294
- ],
295
  inputs=text_input,
296
  fn=analyze_sentiment,
297
- outputs=[gr.HTML(label="Sentiment"), gr.Label(num_top_classes=3, label="Scores"), gr.JSON(label="Raw Output", visible=False)], # Labels de salida más cortos
298
  cache_examples=False,
299
- # ELIMINADO: elem_classes="example-buttons-row"
300
  )
301
 
302
  gr.Markdown("<hr>")
303
- gr.Markdown("<h2 style='color: #00BFFF;'>📊 Results</h2>") # Título de resultados más corto
304
 
305
  overall_sentiment_output = gr.HTML(label="Overall Sentiment")
306
  confidence_scores_output = gr.Label(num_top_classes=3, label="Confidence Scores")
 
1
  import gradio as gr
2
  from transformers import pipeline
3
  import os
4
+ import random # ¡Importamos random para la selección aleatoria!
5
 
6
  # Añade esto para verificar la versión de Gradio en tiempo de ejecución
7
  print(f"Gradio version at runtime: {gr.__version__}")
 
87
 
88
  /* BOTONES PRINCIPALES */
89
  .gr-button.primary {
90
+ background-color: #00BFFF !important; /* ¡CAMBIO AQUÍ! Azul Brillante para el botón primario (Acento) */
91
  color: #1E2B38 !important; /* Texto oscuro para el botón primario */
92
  border-radius: 5px;
93
  transition: background-color 0.3s ease;
 
205
  description = ""
206
  color_class = ""
207
 
 
 
208
  if label.lower() == "positive" or label.lower() == "label_2":
209
  emoji = "😊"
210
+ description = "Positive sentiment detected."
211
  color_class = "sentiment-positive"
212
  elif label.lower() == "negative" or label.lower() == "label_0":
213
  emoji = "😠"
214
+ description = "Negative sentiment detected."
215
  color_class = "sentiment-negative"
216
  elif label.lower() == "neutral" or label.lower() == "label_1":
217
  emoji = "😐"
218
+ description = "Neutral sentiment detected."
219
  color_class = "sentiment-neutral"
220
  else:
221
  emoji = "❓"
222
+ description = "Sentiment not determined."
223
  color_class = ""
224
 
225
  return f"<div class='sentiment-display {color_class}'>{emoji} {label.upper()} ({score:.2f})</div>" + \
226
+ f"<p style='color: #FFFFFF; font-size: 0.75em; margin-top: 3px; margin-bottom: 0;'>{description}</p>"
227
 
228
  # --- Sentiment Analysis Function ---
229
  def analyze_sentiment(text):
230
  if not model_loaded_successfully:
231
  return (
232
+ "<div class='sentiment-display'>⚠️ Model Error ⚠️</div><p style='color: #FFFFFF; font-size: 0.75em;'>Model not loaded.</p>",
233
  {},
234
  {"error": "Model loading failed."}
235
  )
236
 
237
  if not text.strip():
238
  return (
239
+ "<div class='sentiment-display'>✍️ Enter text ✍️</div><p style='color: #FFFFFF; font-size: 0.75em;'>Type text to analyze.</p>",
240
  {},
241
  {"info": "No text entered."}
242
  )
 
258
 
259
  except Exception as e:
260
  return (
261
+ f"<div class='sentiment-display'>❌ Error ❌</div><p style='color: #FFFFFF; font-size: 0.75em;'>Analysis failed.</p>",
262
  {},
263
  {"error_message": str(e)}
264
  )
265
 
266
+ # --- Lista completa de ejemplos para selección aleatoria ---
267
+ ALL_EXAMPLES = [
268
+ ["The product quality is absolutely outstanding and worth every penny!"],
269
+ ["I found the customer support unhelpful and quite rude, a terrible experience."],
270
+ ["The new software update introduced several bugs, making it very unstable."],
271
+ ["This book is a captivating read, I couldn't put it down!"],
272
+ ["The delivery was late, and the package arrived damaged."],
273
+ ["Despite the bad reviews, I thoroughly enjoyed the film and its unique plot."],
274
+ ["The instructions were unclear, leading to a lot of confusion during assembly."],
275
+ ["What a delicious meal! Every dish was prepared to perfection."],
276
+ ["I'm very disappointed with the recent policy changes; they are unfair."],
277
+ ["The new art exhibition is thought-provoking and visually stunning."],
278
+ ["Traffic was unexpectedly heavy, causing significant delays."],
279
+ ["Overall, a solid performance, though there's room for improvement."]
280
+ ]
281
+
282
+ # --- Función para obtener ejemplos aleatorios ---
283
+ def get_random_examples():
284
+ return random.sample(ALL_EXAMPLES, 3) # Selecciona 3 ejemplos al azar
285
+
286
  # --- Gradio Interface ---
287
  with gr.Blocks(css=custom_css, theme=None) as demo:
288
  gr.Markdown("<h1 style='color: #00BFFF;'>🌌 Sentiment Analyzer 🌌</h1>")
289
+ gr.Markdown("<p style='color: #AAB7C4;'>Analyze the emotional tone of your English text.</p>")
290
 
291
  with gr.Column(elem_classes="gradio-container"):
292
  text_input = gr.Textbox(
 
294
  placeholder="Type your English text here...",
295
  label="Your Text",
296
  interactive=True,
297
+ # Establece un ejemplo aleatorio inicial al cargar la interfaz
298
+ value=random.choice(ALL_EXAMPLES)[0]
299
  )
300
  analyze_btn = gr.Button("Analyze Sentiment", variant="primary")
301
 
302
  gr.Markdown("<hr>")
303
+ gr.Markdown("<h3 style='color: #00BFFF;'>Try examples:</h3>")
304
 
305
  with gr.Row():
306
+ # gr.Examples ahora usa la función get_random_examples para cargar los ejemplos
307
+ # y no tiene el argumento elem_classes para evitar el TypeError.
308
  examples = gr.Examples(
309
+ examples=get_random_examples(), # Carga ejemplos aleatorios
 
 
 
 
 
 
 
310
  inputs=text_input,
311
  fn=analyze_sentiment,
312
+ outputs=[gr.HTML(label="Sentiment"), gr.Label(num_top_classes=3, label="Scores"), gr.JSON(label="Raw Output", visible=False)],
313
  cache_examples=False,
 
314
  )
315
 
316
  gr.Markdown("<hr>")
317
+ gr.Markdown("<h2 style='color: #00BFFF;'>📊 Results</h2>")
318
 
319
  overall_sentiment_output = gr.HTML(label="Overall Sentiment")
320
  confidence_scores_output = gr.Label(num_top_classes=3, label="Confidence Scores")