nmarafo commited on
Commit
2076d66
·
verified ·
1 Parent(s): 305707d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +34 -41
app.py CHANGED
@@ -1,8 +1,9 @@
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,8 +32,8 @@ model = AutoModelForCausalLM.from_pretrained(
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,9 +46,8 @@ def generar_prompt(message, tipo_clasificacion, idioma):
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,37 +61,29 @@ 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
- # 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
70
  viola las políticas de seguridad definidas.
71
-
72
  <inicio_turno>
73
  Pregunta del usuario: {message.strip()}
74
  <fin_turno>
75
-
76
  Nuestro principio de seguridad se define a continuación:
77
-
78
  {politica_seguridad.strip()}
79
-
80
  ¿La pregunta del usuario viola el principio anterior? Tu respuesta debe comenzar con
81
  'Sí' o 'No'. Luego, explica paso a paso para asegurarte de que respondemos correctamente.
82
  """
83
  else: # Default to English
84
  prompt = f"""You are a policy expert trying to help determine whether a user prompt is in
85
  violation of the defined safety policies.
86
-
87
  <start_of_turn>
88
  Human Question: {message.strip()}
89
  <end_of_turn>
90
-
91
  Our safety principle is defined below:
92
-
93
  {politica_seguridad.strip()}
94
-
95
  Does the human question violate the above principle? Your answer must start with
96
  'Yes' or 'No'. Then walk through step by step to be sure we answer correctly.
97
  """
@@ -102,31 +94,32 @@ def generar_prompt(message, tipo_clasificacion, idioma):
102
  # Función para procesar la respuesta y clasificar según las políticas de seguridad
103
  def respond(message, history: list[tuple[str, str]], system_message, max_tokens, temperature, top_p, language, harm_type):
104
  prompt = generar_prompt(message, harm_type, language)
 
 
 
105
 
106
- inputs = tokenizer(prompt, return_tensors="pt").to("cuda")
107
-
108
- with torch.no_grad():
109
- logits = model(**inputs).logits
110
-
111
- # Extraer los logits para los tokens 'Yes'/'No' en inglés o 'Sí'/'No' en español
112
- vocab = tokenizer.get_vocab()
113
- if language == "Español":
114
- selected_logits = logits[0, -1, [vocab['Sí'], vocab['No']]]
115
- else:
116
- selected_logits = logits[0, -1, [vocab['Yes'], vocab['No']]]
117
-
118
- # Convertir los logits en una probabilidad con softmax
119
- probabilities = softmax(selected_logits, dim=0)
120
-
121
- # Devolver la probabilidad de 'Sí'/'Yes' y la respuesta generada
122
- score_yes = probabilities[0].item()
123
-
124
- if language == "Español":
125
- response = f"Puntuación para 'Sí' (violación): {score_yes:.4f}"
126
- else:
127
- response = f"Score for 'Yes' (violation): {score_yes:.4f}"
128
 
129
- return response
 
 
 
130
 
131
  # Crear la interfaz de Gradio con selección de idioma y tipo de contenido
132
  demo = gr.ChatInterface(
@@ -134,7 +127,7 @@ demo = gr.ChatInterface(
134
  additional_inputs=[
135
  gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
136
  gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
137
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
138
  gr.Slider(minimum=0.1, maximum=1.0, value=0.95, step=0.05, label="Top-p (nucleus sampling)"),
139
  gr.Dropdown(choices=["English", "Español"], value="English", label="Idioma/Language"),
140
  gr.Dropdown(choices=["Dangerous Content", "Harassment", "Hate Speech", "Sexually Explicit Information"], value="Harassment", label="Harm Type")
 
1
  import gradio as gr
2
+ from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig, TextIteratorStreamer
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
 
33
  # Función para generar el prompt dependiendo del idioma seleccionado
34
  def generar_prompt(message, tipo_clasificacion, idioma):
35
+ politicas = {
36
+ "Español": {
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
  "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
+ "English": {
 
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
+
66
+ politica_seguridad = politicas.get(idioma, {}).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
70
  viola las políticas de seguridad definidas.
 
71
  <inicio_turno>
72
  Pregunta del usuario: {message.strip()}
73
  <fin_turno>
 
74
  Nuestro principio de seguridad se define a continuación:
 
75
  {politica_seguridad.strip()}
 
76
  ¿La pregunta del usuario viola el principio anterior? Tu respuesta debe comenzar con
77
  'Sí' o 'No'. Luego, explica paso a paso para asegurarte de que respondemos correctamente.
78
  """
79
  else: # Default to English
80
  prompt = f"""You are a policy expert trying to help determine whether a user prompt is in
81
  violation of the defined safety policies.
 
82
  <start_of_turn>
83
  Human Question: {message.strip()}
84
  <end_of_turn>
 
85
  Our safety principle is defined below:
 
86
  {politica_seguridad.strip()}
 
87
  Does the human question violate the above principle? Your answer must start with
88
  'Yes' or 'No'. Then walk through step by step to be sure we answer correctly.
89
  """
 
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
+ # Streamer para salida progresiva
102
+ streamer = TextIteratorStreamer(
103
+ tokenizer, timeout=10.0, skip_prompt=True, skip_special_tokens=True
104
+ )
105
+
106
+ generate_kwargs = dict(
107
+ input_ids=input_ids['input_ids'],
108
+ streamer=streamer,
109
+ max_new_tokens=max_tokens,
110
+ do_sample=True,
111
+ top_p=top_p,
112
+ temperature=temperature,
113
+ )
114
+
115
+ # Utilizar un thread para manejar la generación en paralelo
116
+ t = Thread(target=model.generate, kwargs=generate_kwargs)
117
+ t.start()
 
 
 
 
 
118
 
119
+ outputs = []
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
  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 4.0, value=0.7, step=0.1, label="Temperature"),
131
  gr.Slider(minimum=0.1, maximum=1.0, value=0.95, step=0.05, label="Top-p (nucleus sampling)"),
132
  gr.Dropdown(choices=["English", "Español"], value="English", label="Idioma/Language"),
133
  gr.Dropdown(choices=["Dangerous Content", "Harassment", "Hate Speech", "Sexually Explicit Information"], value="Harassment", label="Harm Type")