MarthaIA commited on
Commit
8f6b2a2
·
verified ·
1 Parent(s): dcb3f2c

Upload 2 files

Browse files
Files changed (2) hide show
  1. app_gradio.py +143 -0
  2. requirements.txt +3 -0
app_gradio.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ==============================
2
+ # app_gradio.py
3
+ # ==============================
4
+ # Analizador de sentimientos en español usando TextBlob + Google Translate
5
+ # Interfaz web creada con Gradio (sin Flask)
6
+ # ==============================
7
+
8
+ import re
9
+ import gradio as gr
10
+ from textblob import TextBlob
11
+ from googletrans import Translator
12
+
13
+ # Inicializar el traductor global
14
+ translator = Translator()
15
+
16
+ # ------------------------------------------------
17
+ # 1️⃣ Preprocesamiento del texto
18
+ # ------------------------------------------------
19
+ def preprocess_text(text: str) -> str:
20
+ """Limpia el texto eliminando caracteres innecesarios."""
21
+ text = re.sub(r'[^\w\sáéíóúñ¡!¿?]', '', text, flags=re.UNICODE)
22
+ return text.lower().strip()
23
+
24
+ # ------------------------------------------------
25
+ # 2️⃣ Traducción a inglés
26
+ # ------------------------------------------------
27
+ def translate_to_english(text: str) -> str:
28
+ """Traduce el texto a inglés. Si falla, devuelve el original."""
29
+ try:
30
+ return translator.translate(text, src='es', dest='en').text
31
+ except Exception as e:
32
+ print(f"⚠️ Error en traducción: {e}")
33
+ return text
34
+
35
+ # ------------------------------------------------
36
+ # 3️⃣ Análisis de sentimiento
37
+ # ------------------------------------------------
38
+ def analyze_spanish_sentiment(text: str):
39
+ """Analiza el sentimiento en español y en inglés, y combina ambos resultados."""
40
+ cleaned_text = preprocess_text(text)
41
+
42
+ # Análisis en español
43
+ blob_es = TextBlob(cleaned_text)
44
+ polarity_es = blob_es.sentiment.polarity
45
+ subjectivity_es = blob_es.sentiment.subjectivity
46
+
47
+ # Análisis en inglés (traducido)
48
+ try:
49
+ english_text = translate_to_english(text)
50
+ blob_en = TextBlob(english_text)
51
+ polarity_en = blob_en.sentiment.polarity
52
+ subjectivity_en = blob_en.sentiment.subjectivity
53
+ except:
54
+ english_text = text
55
+ polarity_en = polarity_es
56
+ subjectivity_en = subjectivity_es
57
+
58
+ # Combinamos resultados (70% inglés, 30% español)
59
+ final_polarity = (0.7 * polarity_en) + (0.3 * polarity_es)
60
+ final_subjectivity = (0.7 * subjectivity_en) + (0.3 * subjectivity_es)
61
+
62
+ return final_polarity, final_subjectivity, polarity_es, polarity_en, english_text
63
+
64
+ # ------------------------------------------------
65
+ # 4️⃣ Clasificación del sentimiento
66
+ # ------------------------------------------------
67
+ def classify_sentiment(polarity: float) -> str:
68
+ """Devuelve una etiqueta de sentimiento a partir de la polaridad."""
69
+ if polarity > 0.1:
70
+ return "POSITIVO 😊"
71
+ elif polarity < -0.1:
72
+ return "NEGATIVO 😡"
73
+ elif polarity > 0.02:
74
+ return "LEVEMENTE POSITIVO 🙂"
75
+ elif polarity < -0.02:
76
+ return "LEVEMENTE NEGATIVO 🙁"
77
+ else:
78
+ return "NEUTRO 😐"
79
+
80
+ # ------------------------------------------------
81
+ # 5️⃣ Función principal para Gradio
82
+ # ------------------------------------------------
83
+ def analyze_text(text: str):
84
+ """Función que conecta todo el pipeline para Gradio."""
85
+ if not text.strip():
86
+ return "⚠️ Por favor ingresa un texto.", "-", "-", "-", "-", "-", "-"
87
+
88
+ final_polarity, final_subjectivity, polarity_es, polarity_en, english_text = analyze_spanish_sentiment(text)
89
+ sentiment = classify_sentiment(final_polarity)
90
+ word_count = len(text.split())
91
+
92
+ return (
93
+ sentiment,
94
+ round(final_polarity, 4),
95
+ round(final_subjectivity, 4),
96
+ round(polarity_es, 4),
97
+ round(polarity_en, 4),
98
+ english_text,
99
+ word_count
100
+ )
101
+
102
+ # ------------------------------------------------
103
+ # 6️⃣ Interfaz con Gradio
104
+ # ------------------------------------------------
105
+ title = "🎯 Analizador de Sentimientos en Español"
106
+ description = """
107
+ Este analizador detecta el **sentimiento** de un texto en español usando:
108
+ - ✅ Preprocesamiento del texto
109
+ - ✅ Traducción automática al inglés
110
+ - ✅ Análisis bilingüe con TextBlob
111
+ - ✅ Clasificación (POSITIVO, NEGATIVO, NEUTRO, etc.)
112
+ """
113
+
114
+ interface = gr.Interface(
115
+ fn=analyze_text,
116
+ inputs=gr.Textbox(
117
+ label="📝 Escribe tu texto en español:",
118
+ placeholder="Ej: Me encanta este restaurante, la comida fue excelente."
119
+ ),
120
+ outputs=[
121
+ gr.Textbox(label="🔎 Clasificación del sentimiento"),
122
+ gr.Number(label="📊 Polaridad final (-1 a 1)"),
123
+ gr.Number(label="📈 Subjetividad final (0 a 1)"),
124
+ gr.Number(label="🇪🇸 Polaridad en español"),
125
+ gr.Number(label="🇬🇧 Polaridad en inglés (traducido)"),
126
+ gr.Textbox(label="🌍 Texto traducido al inglés"),
127
+ gr.Number(label="📚 Número de palabras")
128
+ ],
129
+ title=title,
130
+ description=description,
131
+ examples=[
132
+ ["Me encanta este lugar, la comida es deliciosa y la atención fue maravillosa."],
133
+ ["El producto no funciona bien, estoy muy decepcionado."],
134
+ ["Es un día normal, no pasó nada especial."]
135
+ ]
136
+ )
137
+
138
+ # ------------------------------------------------
139
+ # 7️⃣ Iniciar la app
140
+ # ------------------------------------------------
141
+ if __name__ == "__main__":
142
+ print("🚀 Iniciando analizador de sentimientos con Gradio...")
143
+ interface.launch(server_name="0.0.0.0", server_port=7860)
requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ spacy==3.7.2
2
+ https://github.com/explosion/spacy-models/releases/download/es_core_news_sm-3.7.0/es_core_news_sm-3.7.0-py3-none-any.whl
3
+ gradio==4.24.0