Drocho's picture
Update app.py
6364247 verified
Raw History Blame Contribute Delete
4.01 kB
# -*- coding: utf-8 -*-
"""
Demo interactiva — Análisis de Sentimientos Multidominio
Modelo: Drocho/distilbert-sentiment
Curso: Deep Learning (1INF52) — PUCP 2026-1
"""
import gradio as gr
from transformers import pipeline
# Cargar modelo desde Hugging Face
clasificador = pipeline(
"text-classification",
model="Drocho/distilbert-sentiment",
truncation=True,
max_length=512,
)
LABEL_MAP = {
"NEGATIVE": ("Negativo 😞", "#e74c3c"),
"POSITIVE": ("Positivo 😊", "#2ecc71"),
}
EJEMPLOS = [
["This movie was absolutely fantastic! The acting was superb and the story kept me hooked the entire time."],
["Terrible experience. The product broke after one day and customer service was completely useless."],
["I can't believe how good this restaurant is. Best meal I've had in years, will definitely come back!"],
["Waste of money. The film was boring, predictable, and way too long. Don't bother watching it."],
["The book was okay. Some parts were interesting but overall it felt a bit slow and repetitive."],
["Amazing service! The staff went above and beyond to make sure we had a great experience."],
]
def analizar(texto: str):
if not texto or not texto.strip():
return "⚠️ Por favor ingresa un texto.", "", ""
resultado = clasificador(texto)[0]
label_raw = resultado["label"]
score = resultado["score"]
etiqueta, color = LABEL_MAP.get(label_raw, ("Desconocido", "#95a5a6"))
confianza = f"{score * 100:.1f}%"
barra = "█" * int(score * 20) + "░" * (20 - int(score * 20))
detalle = f"{barra} {confianza}"
return etiqueta, detalle, color
def wrapper(texto):
etiqueta, detalle, color = analizar(texto)
return etiqueta, detalle
# Interfaz
with gr.Blocks(
title="Análisis de Sentimientos — DistilBERT",
theme=gr.themes.Soft(),
) as demo:
gr.Markdown(
"""
# 🎭 Análisis de Sentimientos Multidominio
### Modelo DistilBERT fine-tuneado — PUCP Deep Learning 2026-1
Clasifica reseñas de películas, productos, restaurantes y más como **positivas** o **negativas**.
> **Modelo:** [`Drocho/distilbert-sentiment`](https://huggingface.co/Drocho/distilbert-sentiment)
> **Dataset:** IMDb · Amazon Polarity · Yelp · SST-2 — 36,496 muestras
> **Accuracy:** 92.85% · **F1-score:** 92.63%
"""
)
with gr.Row():
with gr.Column(scale=2):
texto_input = gr.Textbox(
label="Texto a analizar",
placeholder="Escribe o pega aquí una reseña en inglés...",
lines=5,
max_lines=10,
)
btn = gr.Button("Analizar sentimiento 🔍", variant="primary")
with gr.Column(scale=1):
sentimiento_output = gr.Textbox(
label="Sentimiento detectado",
interactive=False,
lines=2,
)
confianza_output = gr.Textbox(
label="Confianza del modelo",
interactive=False,
lines=2,
)
gr.Markdown("### 📝 Ejemplos")
gr.Examples(
examples=EJEMPLOS,
inputs=texto_input,
outputs=[sentimiento_output, confianza_output],
fn=wrapper,
cache_examples=True,
label="Haz clic en un ejemplo para probarlo",
)
btn.click(
fn=wrapper,
inputs=texto_input,
outputs=[sentimiento_output, confianza_output],
)
texto_input.submit(
fn=wrapper,
inputs=texto_input,
outputs=[sentimiento_output, confianza_output],
)
gr.Markdown(
"""
---
**Integrantes:** Cáceres Lecaros F. · Ching Sato D. · Condori Chocce Z. · Serpa Paredes C. · Chavez Gonzalez P.
**Limitaciones:** El modelo fue entrenado en inglés. Puede tener dificultades con sarcasmo,
ironía o reseñas con sentimientos mixtos.
"""
)
demo.launch()