Update app.py
Browse files
app.py
CHANGED
@@ -1,65 +1,69 @@
|
|
1 |
import torch
|
2 |
-
from transformers import AutoModelForCausalLM, AutoTokenizer
|
3 |
-
from threading import Thread
|
4 |
import gradio as gr
|
|
|
5 |
|
6 |
-
# 1. Configuración
|
7 |
-
MODEL_NAME = "
|
|
|
8 |
|
9 |
-
# 2. Carga
|
10 |
try:
|
11 |
-
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME
|
12 |
model = AutoModelForCausalLM.from_pretrained(
|
13 |
MODEL_NAME,
|
14 |
torch_dtype=torch.float16,
|
15 |
-
device_map="auto"
|
|
|
16 |
)
|
|
|
|
|
17 |
except Exception as e:
|
18 |
-
raise gr.Error(f"
|
19 |
|
20 |
-
# 3. Función de
|
21 |
-
def
|
22 |
try:
|
23 |
-
#
|
24 |
-
|
25 |
-
|
26 |
-
prompt += f"Usuario: {user_msg}\nGerardo: {bot_msg}\n"
|
27 |
-
prompt += f"Usuario: {message}\nGerardo:"
|
28 |
|
29 |
-
|
30 |
-
|
|
|
|
|
|
|
|
|
|
|
31 |
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
|
|
36 |
temperature=0.7,
|
|
|
37 |
pad_token_id=tokenizer.eos_token_id
|
38 |
)
|
39 |
|
40 |
-
|
41 |
-
|
|
|
42 |
|
43 |
-
partial_message = ""
|
44 |
-
for new_token in streamer:
|
45 |
-
partial_message += new_token
|
46 |
-
yield partial_message
|
47 |
-
|
48 |
-
except torch.cuda.OutOfMemoryError:
|
49 |
-
yield "⚠️ Error: Memoria de GPU agotada. Intenta con una consulta más corta."
|
50 |
except Exception as e:
|
51 |
-
|
|
|
52 |
|
53 |
-
# 4. Interfaz
|
54 |
-
with gr.Blocks(
|
55 |
-
gr.Markdown("## 🤖 Chatbot
|
56 |
-
gr.ChatInterface(
|
57 |
-
fn=
|
58 |
-
examples=["Hola
|
59 |
-
|
|
|
|
|
60 |
)
|
61 |
|
62 |
-
# 5. Lanzamiento específico para Hugging Face
|
63 |
if __name__ == "__main__":
|
64 |
-
demo.launch(server_name="0.0.0.0", server_port=7860)
|
65 |
-
|
|
|
1 |
import torch
|
2 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
|
|
3 |
import gradio as gr
|
4 |
+
import warnings
|
5 |
|
6 |
+
# 1. Configuración a prueba de errores
|
7 |
+
MODEL_NAME = "HuggingFaceH4/zephyr-7b-beta" # Modelo optimizado para Spaces
|
8 |
+
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
|
9 |
|
10 |
+
# 2. Carga segura del modelo
|
11 |
try:
|
12 |
+
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
|
13 |
model = AutoModelForCausalLM.from_pretrained(
|
14 |
MODEL_NAME,
|
15 |
torch_dtype=torch.float16,
|
16 |
+
device_map="auto",
|
17 |
+
low_cpu_mem_usage=True
|
18 |
)
|
19 |
+
if DEVICE == "cuda":
|
20 |
+
model = model.to(DEVICE)
|
21 |
except Exception as e:
|
22 |
+
raise gr.Error(f"Error inicialización: {str(e)}")
|
23 |
|
24 |
+
# 3. Función de chat mejorada
|
25 |
+
def generate_response(message, history):
|
26 |
try:
|
27 |
+
# Limpieza de memoria
|
28 |
+
if DEVICE == "cuda":
|
29 |
+
torch.cuda.empty_cache()
|
|
|
|
|
30 |
|
31 |
+
# Formateo del prompt
|
32 |
+
messages = [{"role": "user", "content": message}]
|
33 |
+
prompt = tokenizer.apply_chat_template(
|
34 |
+
messages,
|
35 |
+
tokenize=False,
|
36 |
+
add_generation_prompt=True
|
37 |
+
)
|
38 |
|
39 |
+
# Generación con parámetros seguros
|
40 |
+
inputs = tokenizer(prompt, return_tensors="pt").to(DEVICE)
|
41 |
+
outputs = model.generate(
|
42 |
+
**inputs,
|
43 |
+
max_new_tokens=256,
|
44 |
temperature=0.7,
|
45 |
+
do_sample=True,
|
46 |
pad_token_id=tokenizer.eos_token_id
|
47 |
)
|
48 |
|
49 |
+
# Decodificación segura
|
50 |
+
response = tokenizer.decode(outputs[0], skip_special_tokens=True)
|
51 |
+
return response.split("assistant\n")[-1].strip()
|
52 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
53 |
except Exception as e:
|
54 |
+
warnings.warn(str(e))
|
55 |
+
return f"Error: {str(e)}"
|
56 |
|
57 |
+
# 4. Interfaz a prueba de fallos
|
58 |
+
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
59 |
+
gr.Markdown("## 🤖 Chatbot Gerardo - Versión Estable")
|
60 |
+
chatbot = gr.ChatInterface(
|
61 |
+
fn=generate_response,
|
62 |
+
examples=["Hola", "¿Cómo estás?"],
|
63 |
+
title="Chatbot Personalizado",
|
64 |
+
description="Asistente IA creado por Gerardo",
|
65 |
+
cache_examples=False
|
66 |
)
|
67 |
|
|
|
68 |
if __name__ == "__main__":
|
69 |
+
demo.launch(server_name="0.0.0.0", server_port=7860)
|
|