Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
@@ -1,9 +1,8 @@
|
|
1 |
import gradio as gr
|
2 |
-
from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
|
3 |
import torch
|
4 |
from threading import Thread
|
5 |
import os
|
6 |
-
from torch.nn.functional import softmax
|
7 |
|
8 |
# Cargar el token de Hugging Face desde los secretos
|
9 |
token = os.environ.get("HF_TOKEN")
|
@@ -32,8 +31,8 @@ model = AutoModelForCausalLM.from_pretrained(
|
|
32 |
|
33 |
# Función para generar el prompt dependiendo del idioma seleccionado
|
34 |
def generar_prompt(message, tipo_clasificacion, idioma):
|
35 |
-
|
36 |
-
|
37 |
"Contenido Peligroso": """
|
38 |
* "No al contenido peligroso": El mensaje no debe contener ni buscar la generación de contenido que cause daño a uno mismo o a otros (por ejemplo, acceder o fabricar armas de fuego o explosivos, promoción del terrorismo, instrucciones para el suicidio).
|
39 |
""",
|
@@ -46,8 +45,9 @@ def generar_prompt(message, tipo_clasificacion, idioma):
|
|
46 |
"Contenido Sexual": """
|
47 |
* "No al contenido sexual explícito": El mensaje no debe contener ni buscar la generación de contenido que haga referencia a actos sexuales u otro contenido lascivo (por ejemplo, descripciones gráficas sexuales, contenido destinado a causar excitación). Los términos médicos o científicos relacionados con la anatomía humana o la educación sexual están permitidos.
|
48 |
"""
|
49 |
-
}
|
50 |
-
|
|
|
51 |
"Dangerous Content": """
|
52 |
* "No Dangerous Content": The prompt shall not contain or seek generation of content that harms oneself and/or others (e.g., accessing or building firearms and explosive devices, promotion of terrorism, instructions for suicide).
|
53 |
""",
|
@@ -61,9 +61,9 @@ def generar_prompt(message, tipo_clasificacion, idioma):
|
|
61 |
* "No Sexually Explicit Information": The prompt shall not contain or seek generation of content that contains references to sexual acts or other lewd content (e.g., sexually graphic descriptions, content aimed at causing arousal). Medical or scientific terms related to human anatomy or sex education are permitted.
|
62 |
"""
|
63 |
}
|
64 |
-
|
65 |
-
|
66 |
-
politica_seguridad = politicas.get(
|
67 |
|
68 |
if idioma == "Español":
|
69 |
prompt = f"""Eres un experto en políticas tratando de determinar si un mensaje del usuario
|
@@ -94,32 +94,31 @@ def generar_prompt(message, tipo_clasificacion, idioma):
|
|
94 |
# Función para procesar la respuesta y clasificar según las políticas de seguridad
|
95 |
def respond(message, history: list[tuple[str, str]], system_message, max_tokens, temperature, top_p, language, harm_type):
|
96 |
prompt = generar_prompt(message, harm_type, language)
|
97 |
-
|
98 |
-
# Tokenizar el prompt
|
99 |
-
input_ids = tokenizer(prompt, return_tensors="pt").to("cuda")
|
100 |
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
|
|
|
|
|
|
|
|
|
|
118 |
|
119 |
-
|
120 |
-
for text in streamer:
|
121 |
-
outputs.append(text)
|
122 |
-
yield "".join(outputs)
|
123 |
|
124 |
# Crear la interfaz de Gradio con selección de idioma y tipo de contenido
|
125 |
demo = gr.ChatInterface(
|
@@ -127,6 +126,7 @@ demo = gr.ChatInterface(
|
|
127 |
additional_inputs=[
|
128 |
gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
|
129 |
gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
|
|
|
130 |
gr.Slider(minimum=0.1, maximum=1.0, value=0.95, step=0.05, label="Top-p (nucleus sampling)"),
|
131 |
gr.Dropdown(choices=["English", "Español"], value="English", label="Idioma/Language"),
|
132 |
gr.Dropdown(choices=["Dangerous Content", "Harassment", "Hate Speech", "Sexually Explicit Information"], value="Harassment", label="Harm Type")
|
@@ -134,4 +134,4 @@ demo = gr.ChatInterface(
|
|
134 |
)
|
135 |
|
136 |
if __name__ == "__main__":
|
137 |
-
demo.launch()
|
|
|
1 |
import gradio as gr
|
2 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
|
3 |
import torch
|
4 |
from threading import Thread
|
5 |
import os
|
|
|
6 |
|
7 |
# Cargar el token de Hugging Face desde los secretos
|
8 |
token = os.environ.get("HF_TOKEN")
|
|
|
31 |
|
32 |
# Función para generar el prompt dependiendo del idioma seleccionado
|
33 |
def generar_prompt(message, tipo_clasificacion, idioma):
|
34 |
+
if idioma == "Español":
|
35 |
+
politicas = {
|
36 |
"Contenido Peligroso": """
|
37 |
* "No al contenido peligroso": El mensaje no debe contener ni buscar la generación de contenido que cause daño a uno mismo o a otros (por ejemplo, acceder o fabricar armas de fuego o explosivos, promoción del terrorismo, instrucciones para el suicidio).
|
38 |
""",
|
|
|
45 |
"Contenido Sexual": """
|
46 |
* "No al contenido sexual explícito": El mensaje no debe contener ni buscar la generación de contenido que haga referencia a actos sexuales u otro contenido lascivo (por ejemplo, descripciones gráficas sexuales, contenido destinado a causar excitación). Los términos médicos o científicos relacionados con la anatomía humana o la educación sexual están permitidos.
|
47 |
"""
|
48 |
+
}
|
49 |
+
else: # English
|
50 |
+
politicas = {
|
51 |
"Dangerous Content": """
|
52 |
* "No Dangerous Content": The prompt shall not contain or seek generation of content that harms oneself and/or others (e.g., accessing or building firearms and explosive devices, promotion of terrorism, instructions for suicide).
|
53 |
""",
|
|
|
61 |
* "No Sexually Explicit Information": The prompt shall not contain or seek generation of content that contains references to sexual acts or other lewd content (e.g., sexually graphic descriptions, content aimed at causing arousal). Medical or scientific terms related to human anatomy or sex education are permitted.
|
62 |
"""
|
63 |
}
|
64 |
+
|
65 |
+
# Formatear el prompt según el tipo de clasificación seleccionado
|
66 |
+
politica_seguridad = politicas.get(tipo_clasificacion, "")
|
67 |
|
68 |
if idioma == "Español":
|
69 |
prompt = f"""Eres un experto en políticas tratando de determinar si un mensaje del usuario
|
|
|
94 |
# Función para procesar la respuesta y clasificar según las políticas de seguridad
|
95 |
def respond(message, history: list[tuple[str, str]], system_message, max_tokens, temperature, top_p, language, harm_type):
|
96 |
prompt = generar_prompt(message, harm_type, language)
|
|
|
|
|
|
|
97 |
|
98 |
+
inputs = tokenizer(prompt, return_tensors="pt").to("cuda")
|
99 |
+
|
100 |
+
with torch.no_grad():
|
101 |
+
logits = model(**inputs).logits
|
102 |
+
|
103 |
+
# Extraer los logits para los tokens 'Yes'/'No' en inglés o 'Sí'/'No' en español
|
104 |
+
vocab = tokenizer.get_vocab()
|
105 |
+
if language == "Español":
|
106 |
+
selected_logits = logits[0, -1, [vocab['Sí'], vocab['No']]]
|
107 |
+
else:
|
108 |
+
selected_logits = logits[0, -1, [vocab['Yes'], vocab['No']]]
|
109 |
+
|
110 |
+
# Convertir los logits en una probabilidad con softmax
|
111 |
+
probabilities = softmax(selected_logits, dim=0)
|
112 |
+
|
113 |
+
# Devolver la probabilidad de 'Sí'/'Yes' y la respuesta generada
|
114 |
+
score_yes = probabilities[0].item()
|
115 |
+
|
116 |
+
if language == "Español":
|
117 |
+
response = f"Puntuación para 'Sí' (violación): {score_yes:.4f}"
|
118 |
+
else:
|
119 |
+
response = f"Score for 'Yes' (violation): {score_yes:.4f}"
|
120 |
|
121 |
+
return response
|
|
|
|
|
|
|
122 |
|
123 |
# Crear la interfaz de Gradio con selección de idioma y tipo de contenido
|
124 |
demo = gr.ChatInterface(
|
|
|
126 |
additional_inputs=[
|
127 |
gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
|
128 |
gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
|
129 |
+
gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
|
130 |
gr.Slider(minimum=0.1, maximum=1.0, value=0.95, step=0.05, label="Top-p (nucleus sampling)"),
|
131 |
gr.Dropdown(choices=["English", "Español"], value="English", label="Idioma/Language"),
|
132 |
gr.Dropdown(choices=["Dangerous Content", "Harassment", "Hate Speech", "Sexually Explicit Information"], value="Harassment", label="Harm Type")
|
|
|
134 |
)
|
135 |
|
136 |
if __name__ == "__main__":
|
137 |
+
demo.launch()
|