Spaces:
Running on Zero
Running on Zero
Upload 5 files
Browse files- README.md +10 -7
- app.py +155 -0
- logreg.pkl +3 -0
- requirements.txt +6 -0
- tfidf_vectorizer.pkl +3 -0
README.md
CHANGED
|
@@ -1,14 +1,17 @@
|
|
| 1 |
---
|
| 2 |
-
title:
|
| 3 |
-
emoji:
|
| 4 |
-
colorFrom:
|
| 5 |
-
colorTo:
|
| 6 |
sdk: gradio
|
| 7 |
-
sdk_version:
|
| 8 |
-
python_version: '3.12'
|
| 9 |
app_file: app.py
|
| 10 |
pinned: false
|
| 11 |
license: cc-by-nc-sa-4.0
|
| 12 |
---
|
| 13 |
|
| 14 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
+
title: CrisisBench Classifier
|
| 3 |
+
emoji: 🚨
|
| 4 |
+
colorFrom: red
|
| 5 |
+
colorTo: yellow
|
| 6 |
sdk: gradio
|
| 7 |
+
sdk_version: 4.44.0
|
|
|
|
| 8 |
app_file: app.py
|
| 9 |
pinned: false
|
| 10 |
license: cc-by-nc-sa-4.0
|
| 11 |
---
|
| 12 |
|
| 13 |
+
# CrisisBench Classifier
|
| 14 |
+
|
| 15 |
+
Clasificador de mensajes en emergencias. Compara XLM-RoBERTa fine-tuned con Regresion Logistica.
|
| 16 |
+
|
| 17 |
+
Proyecto final de Tecnicas de Aprendizaje de Maquina - Pontificia Universidad Javeriana 2026-2.
|
app.py
ADDED
|
@@ -0,0 +1,155 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Clasificador de mensajes en emergencias - CrisisBench
|
| 2 |
+
# Proyecto final Tecnicas de Aprendizaje de Maquina - PUJ 2026-2
|
| 3 |
+
|
| 4 |
+
import re
|
| 5 |
+
import html
|
| 6 |
+
import ftfy
|
| 7 |
+
import pickle
|
| 8 |
+
import torch
|
| 9 |
+
import gradio as gr
|
| 10 |
+
from transformers import AutoTokenizer, AutoModelForSequenceClassification
|
| 11 |
+
|
| 12 |
+
# ============================================================
|
| 13 |
+
# 1. PREPROCESAMIENTO (EXACTO del cuaderno, seccion 5.1)
|
| 14 |
+
# ============================================================
|
| 15 |
+
RT_RE = re.compile(r'^(rt\s+@\w+:?\s*)+')
|
| 16 |
+
URL_RE = re.compile(r'https?://\S+|www\.\S+')
|
| 17 |
+
USER_RE = re.compile(r'@\w+')
|
| 18 |
+
HASH_RE = re.compile(r'#(\w+)')
|
| 19 |
+
WS_RE = re.compile(r'\s+')
|
| 20 |
+
|
| 21 |
+
def limpiar(t: str) -> str:
|
| 22 |
+
t = ftfy.fix_text(t)
|
| 23 |
+
t = html.unescape(t)
|
| 24 |
+
t = RT_RE.sub("", t)
|
| 25 |
+
t = URL_RE.sub(" <URL> ", t)
|
| 26 |
+
t = USER_RE.sub(" <USER> ", t)
|
| 27 |
+
t = HASH_RE.sub(lambda m: " " + re.sub(r"(?<=[a-z])(?=[A-Z])", " ", m.group(1)) + " ", t)
|
| 28 |
+
return WS_RE.sub(" ", t).strip()
|
| 29 |
+
|
| 30 |
+
# ============================================================
|
| 31 |
+
# 2. CARGAR MODELOS (se carga una vez al iniciar)
|
| 32 |
+
# ============================================================
|
| 33 |
+
print("Cargando XLM-R...")
|
| 34 |
+
XLM_PATH = "xlm_r_finetuned"
|
| 35 |
+
tok = AutoTokenizer.from_pretrained(XLM_PATH)
|
| 36 |
+
model_xlm = AutoModelForSequenceClassification.from_pretrained(XLM_PATH)
|
| 37 |
+
model_xlm.eval()
|
| 38 |
+
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
|
| 39 |
+
model_xlm.to(DEVICE)
|
| 40 |
+
print(f"XLM-R cargado en {DEVICE}")
|
| 41 |
+
|
| 42 |
+
print("Cargando LogReg + TF-IDF...")
|
| 43 |
+
with open("logreg.pkl", "rb") as f:
|
| 44 |
+
logreg = pickle.load(f)
|
| 45 |
+
with open("tfidf_vectorizer.pkl", "rb") as f:
|
| 46 |
+
vec = pickle.load(f)
|
| 47 |
+
print("LogReg listo")
|
| 48 |
+
|
| 49 |
+
MAX_LEN = 64
|
| 50 |
+
|
| 51 |
+
# ============================================================
|
| 52 |
+
# 3. FUNCION DE INFERENCIA
|
| 53 |
+
# ============================================================
|
| 54 |
+
def clasificar(mensaje: str):
|
| 55 |
+
if not mensaje or not mensaje.strip():
|
| 56 |
+
return "Escribe un mensaje para clasificar.", "", "", ""
|
| 57 |
+
|
| 58 |
+
# Preprocesar
|
| 59 |
+
texto_limpio = limpiar(mensaje)
|
| 60 |
+
|
| 61 |
+
# XLM-R
|
| 62 |
+
with torch.no_grad():
|
| 63 |
+
enc = tok(texto_limpio, padding="max_length", truncation=True,
|
| 64 |
+
max_length=MAX_LEN, return_tensors="pt").to(DEVICE)
|
| 65 |
+
logits = model_xlm(**enc).logits
|
| 66 |
+
probs_xlm = torch.softmax(logits, dim=-1).cpu().numpy()[0]
|
| 67 |
+
p_inf_xlm = float(probs_xlm[1])
|
| 68 |
+
pred_xlm = "INFORMATIVO" if p_inf_xlm >= 0.5 else "NO INFORMATIVO"
|
| 69 |
+
|
| 70 |
+
# LogReg
|
| 71 |
+
X = vec.transform([texto_limpio])
|
| 72 |
+
p_inf_lr = float(logreg.predict_proba(X)[0, 1])
|
| 73 |
+
pred_lr = "INFORMATIVO" if p_inf_lr >= 0.5 else "NO INFORMATIVO"
|
| 74 |
+
|
| 75 |
+
# Marca si hay desacuerdo
|
| 76 |
+
acuerdo = "Los dos modelos coinciden" if pred_xlm == pred_lr else "DESACUERDO: los modelos discrepan"
|
| 77 |
+
|
| 78 |
+
resultado_xlm = f"**{pred_xlm}** ({p_inf_xlm*100:.1f}% probabilidad de ser informativo)"
|
| 79 |
+
resultado_lr = f"**{pred_lr}** ({p_inf_lr*100:.1f}% probabilidad de ser informativo)"
|
| 80 |
+
|
| 81 |
+
return texto_limpio, resultado_xlm, resultado_lr, acuerdo
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
# ============================================================
|
| 85 |
+
# 4. INTERFAZ GRADIO
|
| 86 |
+
# ============================================================
|
| 87 |
+
DESCRIPCION = """
|
| 88 |
+
# Filtro de mensajes utiles en emergencias
|
| 89 |
+
|
| 90 |
+
Esta aplicacion clasifica mensajes de redes sociales durante desastres (terremotos, huracanes, inundaciones, etc.) en dos categorias:
|
| 91 |
+
- **INFORMATIVO**: aporta datos operativos para equipos de emergencias (danos, victimas, ubicaciones, servicios caidos, instrucciones oficiales).
|
| 92 |
+
- **NO INFORMATIVO**: opiniones, chistes, condolencias genericas, publicidad, contenido fuera de tema.
|
| 93 |
+
|
| 94 |
+
Compara dos modelos:
|
| 95 |
+
- **XLM-RoBERTa** (fine-tuned): Transformer multilingue preentrenado. Mejor en global y en eventos nuevos.
|
| 96 |
+
- **Regresion Logistica + TF-IDF**: Modelo clasico rapido. Puede ser mejor en espanol conocido.
|
| 97 |
+
|
| 98 |
+
**Idiomas soportados**: ingles, espanol y otros 92 (XLM-R) / ingles y espanol principalmente (LogReg).
|
| 99 |
+
|
| 100 |
+
Proyecto final de Tecnicas de Aprendizaje de Maquina - Pontificia Universidad Javeriana 2026-2.
|
| 101 |
+
Dataset: [timhigins/crisisbench](https://huggingface.co/datasets/timhigins/crisisbench).
|
| 102 |
+
"""
|
| 103 |
+
|
| 104 |
+
EJEMPLOS = [
|
| 105 |
+
["BREAKING: 7.2 magnitude earthquake hits coastal region, buildings collapsed in downtown area"],
|
| 106 |
+
["Our thoughts and prayers go out to everyone affected by the hurricane"],
|
| 107 |
+
["Alerta sanitaria oficial en Iquique tras sismo: no consumir agua de la red"],
|
| 108 |
+
["Que tristeza lo que pasa en Venezuela. #FuerzaVenezuela"],
|
| 109 |
+
["Rescue teams working to free 20 people trapped in collapsed hotel in downtown Port-au-Prince"],
|
| 110 |
+
["Peanut butter jelly sandwiches are the best"],
|
| 111 |
+
["RT @24HorasTVN: Imagen del conductor del tren accidentado en Espana da la vuelta al mundo"],
|
| 112 |
+
["Happy birthday bro @Hurricane_Dolce"],
|
| 113 |
+
]
|
| 114 |
+
|
| 115 |
+
with gr.Blocks(theme=gr.themes.Soft(primary_hue="orange", secondary_hue="gray"),
|
| 116 |
+
title="CrisisBench Classifier") as app:
|
| 117 |
+
gr.Markdown(DESCRIPCION)
|
| 118 |
+
|
| 119 |
+
with gr.Row():
|
| 120 |
+
with gr.Column(scale=2):
|
| 121 |
+
entrada = gr.Textbox(
|
| 122 |
+
label="Mensaje a clasificar",
|
| 123 |
+
placeholder="Pega aqui un tuit, un mensaje de Facebook o Whatsapp...",
|
| 124 |
+
lines=4,
|
| 125 |
+
)
|
| 126 |
+
boton = gr.Button("Clasificar", variant="primary", size="lg")
|
| 127 |
+
gr.Examples(examples=EJEMPLOS, inputs=entrada, label="Prueba con estos ejemplos:")
|
| 128 |
+
|
| 129 |
+
with gr.Column(scale=3):
|
| 130 |
+
texto_limpio = gr.Textbox(label="Texto despues de preprocesamiento", interactive=False)
|
| 131 |
+
|
| 132 |
+
with gr.Row():
|
| 133 |
+
with gr.Column():
|
| 134 |
+
gr.Markdown("### XLM-RoBERTa (fine-tuned)")
|
| 135 |
+
out_xlm = gr.Markdown("...")
|
| 136 |
+
with gr.Column():
|
| 137 |
+
gr.Markdown("### Regresion Logistica + TF-IDF")
|
| 138 |
+
out_lr = gr.Markdown("...")
|
| 139 |
+
|
| 140 |
+
acuerdo = gr.Markdown("")
|
| 141 |
+
|
| 142 |
+
gr.Markdown("""
|
| 143 |
+
---
|
| 144 |
+
### Limitaciones del sistema
|
| 145 |
+
- **Sobre la calidad de las etiquetas**: una revision manual de 100 mensajes mostro 18% de desacuerdo con la etiqueta oficial del dataset. Los modelos aprenden ese ruido.
|
| 146 |
+
- **Espanol**: tiene menos datos (3% del corpus) y las etiquetas son mas ruidosas (32% desacuerdo en la clase "informativo"). La precision en espanol es menor.
|
| 147 |
+
- **Eventos nuevos**: XLM-R generaliza mejor que LogReg a desastres nunca vistos (caida de solo 9 puntos vs 22 puntos de LogReg en evento Chile dejado fuera).
|
| 148 |
+
- **No reemplaza a un humano**: el sistema es un filtro de primer paso para reducir el volumen a revisar, no un clasificador definitivo.
|
| 149 |
+
""")
|
| 150 |
+
|
| 151 |
+
boton.click(clasificar, inputs=entrada,
|
| 152 |
+
outputs=[texto_limpio, out_xlm, out_lr, acuerdo])
|
| 153 |
+
|
| 154 |
+
if __name__ == "__main__":
|
| 155 |
+
app.launch()
|
logreg.pkl
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:a5ecc24bee204a92b007dd466ad517c41ac8da58d1823d3658f0928f7632ca75
|
| 3 |
+
size 240726
|
requirements.txt
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
gradio==4.44.0
|
| 2 |
+
transformers==4.44.2
|
| 3 |
+
torch==2.4.0
|
| 4 |
+
scikit-learn==1.5.1
|
| 5 |
+
ftfy==6.2.3
|
| 6 |
+
numpy<2.0
|
tfidf_vectorizer.pkl
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:9043bc36acd105393ac544d00eda0736326c97b0b69f4e2b6877042175810602
|
| 3 |
+
size 1156850
|