File size: 3,006 Bytes
dc774cb
 
 
ef78c2c
 
 
dc774cb
 
 
 
 
 
 
ef78c2c
dc774cb
 
 
61fc924
dc774cb
 
 
 
 
 
 
 
 
 
18f6c17
 
 
ef78c2c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dc774cb
 
5605e98
dc774cb
5605e98
dc774cb
 
 
 
 
ef78c2c
dc774cb
ef78c2c
dc774cb
 
 
5605e98
 
 
 
 
ef78c2c
 
5605e98
502648f
ef78c2c
dc774cb
 
5605e98
18f6c17
ef78c2c
cadebbd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import gradio as gr
import pandas as pd
from transformers import pipeline
import matplotlib.pyplot as plt
import io
import base64

# Configurar el clasificador de sentimientos multilingüe
classifier = pipeline(task="zero-shot-classification", model="facebook/bart-large-mnli")

# Función para analizar los sentimientos de una lista de textos
def analyze_sentiments(texts):
    if not texts:
        return "0.0%", "0.0%", "0.0%", None  # Manejar el caso donde no hay textos para analizar

    positive, negative, neutral = 0, 0, 0
    for text in texts:
        results = classifier(text, candidate_labels=["positive", "negative", "neutral"], multi_label=True)
        mx = max(results['scores'])
        ind = results['scores'].index(mx)
        result = results['labels'][ind]
        if result == "positive":
            positive += 1
        elif result == "negative":
            negative += 1
        else:
            neutral += 1
    total = len(texts)
    positive_percent = round((positive / total) * 100, 1)
    negative_percent = round((negative / total) * 100, 1)
    neutral_percent = round((neutral / total) * 100, 1)

    # Crear el gráfico circular
    labels = 'Positivo', 'Negativo', 'Neutral'
    sizes = [positive_percent, negative_percent, neutral_percent]
    colors = ['#ff9999','#66b3ff','#99ff99']
    fig, ax = plt.subplots()
    ax.pie(sizes, labels=labels, colors=colors, autopct='%1.1f%%', startangle=90)
    ax.axis('equal')  # Para asegurar que el pie sea circular

    # Guardar el gráfico en un buffer de memoria
    buf = io.BytesIO()
    plt.savefig(buf, format='png')
    buf.seek(0)
    img_base64 = base64.b64encode(buf.read()).decode('utf-8')
    buf.close()

    return f"{positive_percent}%", f"{negative_percent}%", f"{neutral_percent}%", img_base64

# Función para cargar el archivo CSV y analizar los primeros 100 comentarios
def analyze_sentiment_from_csv(file):
    try:
        df = pd.read_csv(file.name)
        if 'content' not in df.columns:
            raise ValueError("El archivo CSV no contiene una columna 'content'")
        texts = df['content'].head(100).tolist()  # Tomar solo los primeros 100 comentarios
        return analyze_sentiments(texts)
    except pd.errors.ParserError as e:
        return f"Error al analizar el archivo CSV: {e}", "", "", None
    except Exception as e:
        return f"Error inesperado: {e}", "", "", None

# Configurar la interfaz de Gradio
demo = gr.Interface(
    fn=analyze_sentiment_from_csv,
    inputs=gr.File(file_count="single", label="Sube tu archivo CSV"),  # Permitir la carga del archivo CSV
    outputs=[
        gr.Textbox(label="Porcentaje Positivo"),
        gr.Textbox(label="Porcentaje Negativo"),
        gr.Textbox(label="Porcentaje Neutro"),
        gr.Image(label="Gráfico de Resultados")  # Añadir un output para el gráfico
    ],
    title="Analizador de Sentimientos V.2",
    description="Porcentaje de comentarios positivos, negativos y neutrales"
)

demo.launch(share=True)