Spaces:
Runtime error
Runtime error
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,108 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
2 |
+
from peft import PeftModel
|
3 |
+
import gradio as gr
|
4 |
+
import os
|
5 |
+
import torch
|
6 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
7 |
+
print(device)
|
8 |
+
# Asegúrate de que tu token de Hugging Face está cargado como una variable de entorno
|
9 |
+
hf_token = os.environ.get("token")
|
10 |
+
if hf_token is not None:
|
11 |
+
from huggingface_hub import HfFolder
|
12 |
+
HfFolder.save_token(hf_token)
|
13 |
+
else:
|
14 |
+
print("No se encontró el token de Hugging Face. Asegúrate de que la variable de entorno HF_TOKEN esté configurada.")
|
15 |
+
|
16 |
+
# Configuración inicial
|
17 |
+
tokenizer = AutoTokenizer.from_pretrained("Juliofc/chaterapia_model")
|
18 |
+
model_base = AutoModelForCausalLM.from_pretrained("google/gemma-2b-it").to(device)
|
19 |
+
model_base.resize_token_embeddings(len(tokenizer))
|
20 |
+
model_with_adapter = PeftModel.from_pretrained(model_base, "Juliofc/chaterapia_model").to(device)
|
21 |
+
|
22 |
+
CHAT_TEMPLATE= """{% for message in messages %}
|
23 |
+
{% if message['role'] == 'user' %}
|
24 |
+
{{'<user> ' + message['content'].strip() + ' </user>' }}
|
25 |
+
{% elif message['role'] == 'system' %}
|
26 |
+
{{'<system>\\n' + message['content'].strip() + '\\n</system>\\n\\n' }}
|
27 |
+
{% elif message['role'] == 'assistant' %}
|
28 |
+
{{ message['content'].strip() + ' </assistant>' + eos_token }}
|
29 |
+
{% elif message['role'] == 'input' %}
|
30 |
+
{{'<input> ' + message['content'] + ' </input>' }}
|
31 |
+
{% endif %}
|
32 |
+
{% endfor %}""" # Asegúrate de usar tu CHAT_TEMPLATE aquí
|
33 |
+
tokenizer.chat_template = CHAT_TEMPLATE
|
34 |
+
|
35 |
+
# Función para generar respuestas del modelo
|
36 |
+
import gradio as gr
|
37 |
+
|
38 |
+
# Asume que todas tus importaciones previas y configuraciones del modelo están aquí
|
39 |
+
|
40 |
+
# Aquí deberías tener definida la función `generate_response` tal como la compartiste
|
41 |
+
# Función para generar respuestas del modelo
|
42 |
+
def generate_response(user_input, chat_history):
|
43 |
+
# Preparar el input agregando el historial de chat
|
44 |
+
chat_history.append({"content": user_input, "role": "user"})
|
45 |
+
print(chat_history)
|
46 |
+
user_input = tokenizer.apply_chat_template(chat_history, tokenize=False)
|
47 |
+
|
48 |
+
input_tokens = tokenizer(user_input, return_tensors='pt', padding=True, truncation=True, max_length=1024).to(device)
|
49 |
+
|
50 |
+
# Generar la respuesta
|
51 |
+
output_tokens = model_with_adapter.generate(**input_tokens, max_length=1024, pad_token_id=tokenizer.eos_token_id, top_k=50, top_p=0.95, temperature=0.7)
|
52 |
+
generated_text = tokenizer.decode(output_tokens[0], skip_special_tokens=True)
|
53 |
+
|
54 |
+
last_us = generated_text.rfind("</user>") + len("</user>")
|
55 |
+
last_as = generated_text.rfind("</assistant>")
|
56 |
+
generated_text = generated_text[last_us:last_as].strip()
|
57 |
+
chat_history.append({"content": generated_text, "role": "assistant"})
|
58 |
+
return generated_text, chat_history
|
59 |
+
|
60 |
+
History = List[Tuple[str, str]]
|
61 |
+
|
62 |
+
def clear_session() -> History:
|
63 |
+
return '', []
|
64 |
+
|
65 |
+
def modify_system_session(system: str) -> str:
|
66 |
+
if system is None or len(system) == 0:
|
67 |
+
system = default_system
|
68 |
+
return system, system, []
|
69 |
+
|
70 |
+
def model_chat(query: Optional[str], history: Optional[History], system: str
|
71 |
+
) -> Tuple[str, str, History]:
|
72 |
+
if query is None:
|
73 |
+
query = ''
|
74 |
+
if history is None:
|
75 |
+
history = []
|
76 |
+
if not history or history[-1][0] != query: # Asegurar que no se repita la última pregunta
|
77 |
+
history.append((query, ''))
|
78 |
+
response, history = generate_response(query, history) # Tu función de modelo
|
79 |
+
return '', response, history
|
80 |
+
|
81 |
+
placeholder = "This is a simulated conversation with your model."
|
82 |
+
|
83 |
+
with gr.Blocks() as demo:
|
84 |
+
gr.Markdown("<center><font size=6>Chatbot with Your Model</center>")
|
85 |
+
|
86 |
+
with gr.Row():
|
87 |
+
system_input = gr.Textbox(value=default_system, lines=1, label='System')
|
88 |
+
modify_system = gr.Button("🛠️ Set system prompt and clear the history")
|
89 |
+
system_state = gr.Textbox(value=default_system, visible=False)
|
90 |
+
|
91 |
+
chatbot = gr.Chatbot(label='Chat with Your Model', placeholder=placeholder)
|
92 |
+
textbox = gr.Textbox(lines=2, label='Input')
|
93 |
+
|
94 |
+
with gr.Row():
|
95 |
+
clear_history = gr.Button("🧹 Clear history")
|
96 |
+
submit = gr.Button("🚀 Send")
|
97 |
+
|
98 |
+
submit.click(model_chat,
|
99 |
+
inputs=[textbox, chatbot, system_state],
|
100 |
+
outputs=[textbox, chatbot, system_input])
|
101 |
+
clear_history.click(fn=clear_session,
|
102 |
+
inputs=[],
|
103 |
+
outputs=[textbox, chatbot])
|
104 |
+
modify_system.click(fn=modify_system_session,
|
105 |
+
inputs=[system_input],
|
106 |
+
outputs=[system_state, system_input, chatbot])
|
107 |
+
|
108 |
+
demo.launch()
|