Spaces:
Paused
Paused
Antonio Toro Jaén
commited on
Commit
·
5be1c50
1
Parent(s):
ea5ef1f
Update app.py
Browse files
app.py
CHANGED
@@ -5,6 +5,13 @@ import os
|
|
5 |
import csv
|
6 |
from transformers import AutoModelForCausalLM, AutoTokenizer
|
7 |
from huggingface_hub import login
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
8 |
login(os.environ["HF_TOKEN"])
|
9 |
|
10 |
model_name = "atorojaen/DeepSeekMisogyny"
|
@@ -16,26 +23,22 @@ model = AutoModelForCausalLM.from_pretrained(
|
|
16 |
device_map="auto"
|
17 |
)
|
18 |
|
|
|
|
|
19 |
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
20 |
model.eval()
|
21 |
|
22 |
-
|
23 |
FLAG_FILE = "flags_data/flags.csv"
|
24 |
os.makedirs(os.path.dirname(FLAG_FILE), exist_ok=True)
|
25 |
|
26 |
def clean_lyrics(text):
|
27 |
-
# Elimina caracteres no alfabéticos (excepto espacios y letras acentuadas comunes en español)
|
28 |
text = re.sub(r"[^a-zA-ZáéíóúñüÁÉÍÓÚÑÜ ]+", " ", text)
|
29 |
-
# Convierte a minúsculas
|
30 |
text = text.lower()
|
31 |
-
# Reduce espacios múltiples
|
32 |
text = re.sub(r"\s+", " ", text).strip()
|
33 |
return text
|
34 |
|
35 |
-
# Función de predicción
|
36 |
def detect_misogyny(text):
|
37 |
cleaned_text = clean_lyrics(text)
|
38 |
-
# Construir el prompt de entrada
|
39 |
prompt = """
|
40 |
### Instruccion
|
41 |
Analiza la siguiente letra de canción y determina si contiene contenido misógino. Evalúa si incluye lenguaje, actitudes o mensajes que:
|
@@ -51,7 +54,6 @@ def detect_misogyny(text):
|
|
51 |
|
52 |
### Respuesta:
|
53 |
<think>"""
|
54 |
-
|
55 |
prompt = prompt.format(lyrics=text)
|
56 |
|
57 |
inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
|
@@ -64,20 +66,15 @@ def detect_misogyny(text):
|
|
64 |
)
|
65 |
response = tokenizer.decode(outputs[0], skip_special_tokens=True)
|
66 |
|
67 |
-
# Extraer explicación entre <think>...</think>
|
68 |
explanation_match = re.search(r"<think>(.*?)</think>", response, re.DOTALL)
|
69 |
explanation = explanation_match.group(1).strip() if explanation_match else ""
|
70 |
|
71 |
-
# Extraer "1" o "0" después de </think>
|
72 |
label_match = re.search(r"</think>\s*(\d)", response)
|
73 |
label = label_match.group(1) if label_match else ""
|
74 |
|
75 |
-
# Combinar resultado final
|
76 |
return f"{explanation}\n\nRespuesta final: {label}" if explanation and label else response.strip()
|
77 |
|
78 |
-
|
79 |
def save_flag(user_text, response, flag_type):
|
80 |
-
# Guarda la entrada, salida y si fue correcta o incorrecta en CSV
|
81 |
with open(FLAG_FILE, mode="a", newline="", encoding="utf-8") as f:
|
82 |
writer = csv.writer(f)
|
83 |
writer.writerow([user_text, response, flag_type])
|
@@ -86,13 +83,12 @@ def save_flag(user_text, response, flag_type):
|
|
86 |
with gr.Blocks() as demo:
|
87 |
user_input = gr.Textbox(label="Letra de canción", lines=10)
|
88 |
result = gr.Textbox(label="Respuesta del modelo", lines=10)
|
89 |
-
|
90 |
btn_analizar = gr.Button("Analizar")
|
91 |
btn_correcto = gr.Button("Respuesta correcta")
|
92 |
btn_incorrecto = gr.Button("Respuesta incorrecta")
|
93 |
-
|
94 |
btn_analizar.click(fn=detect_misogyny, inputs=user_input, outputs=result)
|
95 |
-
|
96 |
btn_correcto.click(fn=save_flag, inputs=[user_input, result, gr.State("correcto")], outputs=result)
|
97 |
btn_incorrecto.click(fn=save_flag, inputs=[user_input, result, gr.State("incorrecto")], outputs=result)
|
98 |
|
|
|
5 |
import csv
|
6 |
from transformers import AutoModelForCausalLM, AutoTokenizer
|
7 |
from huggingface_hub import login
|
8 |
+
import spaces
|
9 |
+
|
10 |
+
@spaces.GPU
|
11 |
+
def confirm_gpu():
|
12 |
+
import torch
|
13 |
+
return torch.cuda.is_available()
|
14 |
+
|
15 |
login(os.environ["HF_TOKEN"])
|
16 |
|
17 |
model_name = "atorojaen/DeepSeekMisogyny"
|
|
|
23 |
device_map="auto"
|
24 |
)
|
25 |
|
26 |
+
assert torch.cuda.is_available(), "CUDA no está disponible"
|
27 |
+
|
28 |
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
29 |
model.eval()
|
30 |
|
|
|
31 |
FLAG_FILE = "flags_data/flags.csv"
|
32 |
os.makedirs(os.path.dirname(FLAG_FILE), exist_ok=True)
|
33 |
|
34 |
def clean_lyrics(text):
|
|
|
35 |
text = re.sub(r"[^a-zA-ZáéíóúñüÁÉÍÓÚÑÜ ]+", " ", text)
|
|
|
36 |
text = text.lower()
|
|
|
37 |
text = re.sub(r"\s+", " ", text).strip()
|
38 |
return text
|
39 |
|
|
|
40 |
def detect_misogyny(text):
|
41 |
cleaned_text = clean_lyrics(text)
|
|
|
42 |
prompt = """
|
43 |
### Instruccion
|
44 |
Analiza la siguiente letra de canción y determina si contiene contenido misógino. Evalúa si incluye lenguaje, actitudes o mensajes que:
|
|
|
54 |
|
55 |
### Respuesta:
|
56 |
<think>"""
|
|
|
57 |
prompt = prompt.format(lyrics=text)
|
58 |
|
59 |
inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
|
|
|
66 |
)
|
67 |
response = tokenizer.decode(outputs[0], skip_special_tokens=True)
|
68 |
|
|
|
69 |
explanation_match = re.search(r"<think>(.*?)</think>", response, re.DOTALL)
|
70 |
explanation = explanation_match.group(1).strip() if explanation_match else ""
|
71 |
|
|
|
72 |
label_match = re.search(r"</think>\s*(\d)", response)
|
73 |
label = label_match.group(1) if label_match else ""
|
74 |
|
|
|
75 |
return f"{explanation}\n\nRespuesta final: {label}" if explanation and label else response.strip()
|
76 |
|
|
|
77 |
def save_flag(user_text, response, flag_type):
|
|
|
78 |
with open(FLAG_FILE, mode="a", newline="", encoding="utf-8") as f:
|
79 |
writer = csv.writer(f)
|
80 |
writer.writerow([user_text, response, flag_type])
|
|
|
83 |
with gr.Blocks() as demo:
|
84 |
user_input = gr.Textbox(label="Letra de canción", lines=10)
|
85 |
result = gr.Textbox(label="Respuesta del modelo", lines=10)
|
86 |
+
|
87 |
btn_analizar = gr.Button("Analizar")
|
88 |
btn_correcto = gr.Button("Respuesta correcta")
|
89 |
btn_incorrecto = gr.Button("Respuesta incorrecta")
|
90 |
+
|
91 |
btn_analizar.click(fn=detect_misogyny, inputs=user_input, outputs=result)
|
|
|
92 |
btn_correcto.click(fn=save_flag, inputs=[user_input, result, gr.State("correcto")], outputs=result)
|
93 |
btn_incorrecto.click(fn=save_flag, inputs=[user_input, result, gr.State("incorrecto")], outputs=result)
|
94 |
|