Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -2,9 +2,10 @@ 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="
|
8 |
|
9 |
# Función para analizar los sentimientos de una lista de textos
|
10 |
def analyze_sentiments(texts):
|
@@ -12,7 +13,10 @@ def analyze_sentiments(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 |
-
|
|
|
|
|
|
|
16 |
results = classifier(text, ["positive", "negative", "neutral"], multi_label=True)
|
17 |
mx = max(results['scores'])
|
18 |
ind = results['scores'].index(mx)
|
@@ -23,11 +27,16 @@ def analyze_sentiments(texts):
|
|
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'])
|
@@ -37,13 +46,13 @@ def analyze_sentiments(texts):
|
|
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
|
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(
|
47 |
return analyze_sentiments(texts)
|
48 |
except pd.errors.ParserError as e:
|
49 |
return f"Error al analizar el archivo CSV: {e}", "", "", None
|
@@ -60,9 +69,10 @@ demo = gr.Interface(
|
|
60 |
gr.Textbox(label="Porcentaje Neutro"),
|
61 |
gr.Image(type="filepath", label="Gráfico de Sentimientos")
|
62 |
],
|
63 |
-
title="Analizador de Sentimientos V.
|
64 |
-
description="Porcentaje de comentarios positivos, negativos y neutrales
|
65 |
)
|
66 |
|
67 |
demo.launch(share=True)
|
68 |
|
|
|
|
2 |
import pandas as pd
|
3 |
from transformers import pipeline
|
4 |
import matplotlib.pyplot as plt
|
5 |
+
from concurrent.futures import ThreadPoolExecutor
|
6 |
|
7 |
+
# Configurar el clasificador de sentimientos multilingüe con un modelo más pequeño
|
8 |
+
classifier = pipeline(task="zero-shot-classification", model="typeform/distilbert-base-uncased-mnli")
|
9 |
|
10 |
# Función para analizar los sentimientos de una lista de textos
|
11 |
def analyze_sentiments(texts):
|
|
|
13 |
return "0.0%", "0.0%", "0.0%", None # Manejar el caso donde no hay textos para analizar
|
14 |
|
15 |
positive, negative, neutral = 0, 0, 0
|
16 |
+
|
17 |
+
# Función para procesar un texto individualmente
|
18 |
+
def process_text(text):
|
19 |
+
nonlocal positive, negative, neutral
|
20 |
results = classifier(text, ["positive", "negative", "neutral"], multi_label=True)
|
21 |
mx = max(results['scores'])
|
22 |
ind = results['scores'].index(mx)
|
|
|
27 |
negative += 1
|
28 |
else:
|
29 |
neutral += 1
|
30 |
+
|
31 |
+
# Usar ThreadPoolExecutor para procesar textos en paralelo
|
32 |
+
with ThreadPoolExecutor() as executor:
|
33 |
+
executor.map(process_text, texts)
|
34 |
+
|
35 |
total = len(texts)
|
36 |
positive_percent = round((positive / total) * 100, 1)
|
37 |
negative_percent = round((negative / total) * 100, 1)
|
38 |
neutral_percent = round((neutral / total) * 100, 1)
|
39 |
+
|
40 |
# Crear el gráfico circular
|
41 |
fig, ax = plt.subplots()
|
42 |
ax.pie([positive_percent, negative_percent, neutral_percent], labels=["Positivo", "Negativo", "Neutro"], autopct='%1.1f%%', colors=['green', 'red', 'blue'])
|
|
|
46 |
|
47 |
return f"{positive_percent}%", f"{negative_percent}%", f"{neutral_percent}%", "sentiment_pie_chart.png"
|
48 |
|
49 |
+
# Función para cargar el archivo CSV y analizar los primeros 50 comentarios
|
50 |
def analyze_sentiment_from_csv(file):
|
51 |
try:
|
52 |
df = pd.read_csv(file.name)
|
53 |
if 'content' not in df.columns:
|
54 |
raise ValueError("El archivo CSV no contiene una columna 'content'")
|
55 |
+
texts = df['content'].head(50).tolist() # Tomar solo los primeros 50 comentarios
|
56 |
return analyze_sentiments(texts)
|
57 |
except pd.errors.ParserError as e:
|
58 |
return f"Error al analizar el archivo CSV: {e}", "", "", None
|
|
|
69 |
gr.Textbox(label="Porcentaje Neutro"),
|
70 |
gr.Image(type="filepath", label="Gráfico de Sentimientos")
|
71 |
],
|
72 |
+
title="Analizador de Sentimientos V.2",
|
73 |
+
description="Porcentaje de comentarios positivos, negativos y neutrales"
|
74 |
)
|
75 |
|
76 |
demo.launch(share=True)
|
77 |
|
78 |
+
|