Spaces:
Runtime error
Runtime error
| import gradio as gr | |
| import pandas as pd | |
| from transformers import pipeline | |
| import matplotlib.pyplot as plt | |
| from concurrent.futures import ThreadPoolExecutor | |
| # Configurar el clasificador de sentimientos multiling眉e con un modelo m谩s peque帽o | |
| classifier = pipeline(task="zero-shot-classification", model="typeform/distilbert-base-uncased-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 | |
| # Funci贸n para procesar un texto individualmente | |
| def process_text(text): | |
| nonlocal positive, negative, neutral | |
| results = classifier(text, ["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 | |
| # Usar ThreadPoolExecutor para procesar textos en paralelo | |
| with ThreadPoolExecutor() as executor: | |
| executor.map(process_text, texts) | |
| 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 | |
| fig, ax = plt.subplots() | |
| ax.pie([positive_percent, negative_percent, neutral_percent], labels=["Positivo", "Negativo", "Neutro"], autopct='%1.1f%%', colors=['green', 'red', 'blue']) | |
| plt.title("Distribuci贸n de Sentimientos") | |
| plt.savefig("sentiment_pie_chart.png") | |
| plt.close(fig) | |
| return f"{positive_percent}%", f"{negative_percent}%", f"{neutral_percent}%", "sentiment_pie_chart.png" | |
| # Funci贸n para cargar el archivo CSV y analizar los primeros 50 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(50).tolist() # Tomar solo los primeros 50 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(type="filepath", label="Gr谩fico de Sentimientos") | |
| ], | |
| title="Analizador de Sentimientos V.2", | |
| description="Porcentaje de comentarios positivos, negativos y neutrales" | |
| ) | |
| demo.launch(share=True) | |