|
import gradio as gr |
|
import pandas as pd |
|
from transformers import pipeline |
|
from collections import Counter |
|
import re |
|
|
|
|
|
classifier = pipeline(task="zero-shot-classification", model="facebook/bart-large-mnli") |
|
|
|
|
|
def analyze_sentiments(texts): |
|
if not texts: |
|
return "0.0%", "0.0%", "0.0%", [] |
|
|
|
positive, negative, neutral = 0, 0, 0 |
|
all_words = [] |
|
for text in texts: |
|
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 |
|
|
|
|
|
words = re.findall(r'\w+', text.lower()) |
|
all_words.extend(words) |
|
|
|
total = len(texts) |
|
positive_percent = round((positive / total) * 100, 1) |
|
negative_percent = round((negative / total) * 100, 1) |
|
neutral_percent = round((neutral / total) * 100, 1) |
|
|
|
|
|
word_counts = Counter(all_words) |
|
most_common_words = word_counts.most_common(10) |
|
|
|
return f"{positive_percent}%", f"{negative_percent}%", f"{neutral_percent}%", most_common_words |
|
|
|
|
|
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() |
|
return analyze_sentiments(texts) |
|
except pd.errors.ParserError as e: |
|
return f"Error al analizar el archivo CSV: {e}", "", "", [] |
|
except Exception as e: |
|
return f"Error inesperado: {e}", "", "", [] |
|
|
|
|
|
demo = gr.Interface( |
|
fn=analyze_sentiment_from_csv, |
|
inputs=gr.File(file_count="single", label="Sube tu archivo CSV"), |
|
outputs=[ |
|
gr.Textbox(label="Porcentaje Positivo"), |
|
gr.Textbox(label="Porcentaje Negativo"), |
|
gr.Textbox(label="Porcentaje Neutro"), |
|
gr.Textbox(label="Palabras Más Usadas") |
|
], |
|
title="Analizador de Sentimientos V.2", |
|
description="Porcentaje de comentarios positivos, negativos y neutrales, y palabras más usadas" |
|
) |
|
|
|
demo.launch(share=True) |
|
|
|
|
|
|
|
|