SoyTuTilin commited on
Commit
5fc4744
1 Parent(s): 63dcd97

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +67 -0
app.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import pandas as pd
3
+ from transformers import pipeline
4
+ import matplotlib.pyplot as plt
5
+
6
+ # Configurar el clasificador de sentimientos multilingüe
7
+ classifier = pipeline(task="zero-shot-classification", model="facebook/bart-large-mnli")
8
+
9
+ # Función para analizar los sentimientos de una lista de textos
10
+ def analyze_sentiments(texts):
11
+ if not texts:
12
+ return "0.0%", "0.0%", "0.0%", None # Manejar el caso donde no hay textos para analizar
13
+
14
+ positive, negative, neutral = 0, 0, 0
15
+ for text in texts:
16
+ results = classifier(text, ["positive", "negative", "neutral"], multi_label=True)
17
+ mx = max(results['scores'])
18
+ ind = results['scores'].index(mx)
19
+ result = results['labels'][ind]
20
+ if result == "positive":
21
+ positive += 1
22
+ elif result == "negative":
23
+ negative += 1
24
+ else:
25
+ neutral += 1
26
+ total = len(texts)
27
+ positive_percent = round((positive / total) * 100, 1)
28
+ negative_percent = round((negative / total) * 100, 1)
29
+ neutral_percent = round((neutral / total) * 100, 1)
30
+
31
+ # Crear el gráfico circular
32
+ fig, ax = plt.subplots()
33
+ ax.pie([positive_percent, negative_percent, neutral_percent], labels=["Positivo", "Negativo", "Neutro"], autopct='%1.1f%%', colors=['green', 'red', 'blue'])
34
+ plt.title("Distribución de Sentimientos")
35
+ plt.savefig("sentiment_pie_chart.png")
36
+ plt.close(fig)
37
+
38
+ return f"{positive_percent}%", f"{negative_percent}%", f"{neutral_percent}%", "sentiment_pie_chart.png"
39
+
40
+ # Función para cargar el archivo CSV y analizar los primeros 100 comentarios
41
+ def analyze_sentiment_from_csv(file):
42
+ try:
43
+ df = pd.read_csv(file.name)
44
+ if 'content' not in df.columns:
45
+ raise ValueError("El archivo CSV no contiene una columna 'content'")
46
+ texts = df['content'].head(100).tolist() # Tomar solo los primeros 100 comentarios
47
+ return analyze_sentiments(texts)
48
+ except pd.errors.ParserError as e:
49
+ return f"Error al analizar el archivo CSV: {e}", "", "", None
50
+ except Exception as e:
51
+ return f"Error inesperado: {e}", "", "", None
52
+
53
+ # Configurar la interfaz de Gradio
54
+ demo = gr.Interface(
55
+ fn=analyze_sentiment_from_csv,
56
+ inputs=gr.File(file_count="single", label="Sube tu archivo CSV"), # Permitir la carga del archivo CSV
57
+ outputs=[
58
+ gr.Textbox(label="Porcentaje Positivo"),
59
+ gr.Textbox(label="Porcentaje Negativo"),
60
+ gr.Textbox(label="Porcentaje Neutro"),
61
+ gr.Image(type="filepath", label="Gráfico de Sentimientos")
62
+ ],
63
+ title="Analizador de Sentimientos V.2",
64
+ description="Porcentaje de comentarios positivos, negativos y neutrales"
65
+ )
66
+
67
+ demo.launch(share=True)