Update app.py
Browse filesPrueba TheBloke/mistral-ft-optimized-1227-GGUF
app.py
CHANGED
@@ -1,94 +1,25 @@
|
|
1 |
import gradio as gr
|
2 |
-
import
|
3 |
-
|
4 |
-
|
5 |
-
|
6 |
-
|
7 |
-
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
)
|
26 |
-
|
27 |
-
# Definimos un mensaje inicial que simula un rol del sistema y contiene instrucciones sobre cómo responder, adaptado al español
|
28 |
-
system_message = {
|
29 |
-
"role": "system",
|
30 |
-
"content": """
|
31 |
-
Eres un asistente útil.
|
32 |
-
Recibirás una pregunta y un conjunto de respuestas junto con una puntuación de confianza entre 0 y 1 para cada respuesta.
|
33 |
-
Tu trabajo es convertir esta información en una respuesta corta y coherente.
|
34 |
-
Por ejemplo:
|
35 |
-
Pregunta: "¿A quién se le está facturando?", respuesta: {"answer": "John Doe", "confidence": 0.98}
|
36 |
-
Deberías responder algo como:
|
37 |
-
Con un alto grado de confianza, puedo decir que se le está facturando a John Doe.
|
38 |
-
Pregunta: "¿Cuál es el total de la factura?", respuesta: [{"answer": "154.08", "confidence": 0.75}, {"answer": "155", "confidence": 0.25}]
|
39 |
-
Deberías responder algo como:
|
40 |
-
Creo que el total de la factura es de $154.08 aunque también podría ser $155.
|
41 |
-
"""}
|
42 |
-
|
43 |
-
# Definimos la función de inferencia utilizando el modelo Meta Llama 3.1 8B Instruct
|
44 |
-
def chat_fn(multimodal_message):
|
45 |
-
# Extraemos el texto de la pregunta del mensaje proporcionado por el usuario
|
46 |
-
question = multimodal_message["text"]
|
47 |
-
|
48 |
-
# Construimos el mensaje para el modelo
|
49 |
-
conversation = [{"role": "user", "content": question}]
|
50 |
-
|
51 |
-
# Generamos los IDs de entrada utilizando el tokenizador del modelo
|
52 |
-
input_ids = tokenizer.apply_chat_template(conversation, return_tensors="pt")
|
53 |
-
input_ids = input_ids.to(model.device)
|
54 |
-
|
55 |
-
# Configuramos el streamer para la generación progresiva de texto
|
56 |
-
streamer = TextIteratorStreamer(tokenizer, timeout=10.0, skip_prompt=True, skip_special_tokens=True)
|
57 |
-
|
58 |
-
# Configuramos los argumentos de generación
|
59 |
-
generate_kwargs = dict(
|
60 |
-
input_ids=input_ids,
|
61 |
-
streamer=streamer,
|
62 |
-
max_new_tokens=500, # Ajusta esto según tus necesidades
|
63 |
-
do_sample=True,
|
64 |
-
temperature=0.7, # Ajusta la temperatura según tus necesidades
|
65 |
-
)
|
66 |
-
|
67 |
-
# Iniciamos la generación de texto en un hilo separado
|
68 |
-
t = Thread(target=model.generate, kwargs=generate_kwargs)
|
69 |
-
t.start()
|
70 |
-
|
71 |
-
# Iteramos sobre los tokens generados y construimos la respuesta
|
72 |
-
message = ""
|
73 |
-
for text in streamer:
|
74 |
-
message += text
|
75 |
-
yield message
|
76 |
-
|
77 |
-
# Usamos la clase 'Blocks' de Gradio para definir la interfaz de usuario
|
78 |
-
with gr.Blocks() as demo:
|
79 |
-
# Título de la aplicación en español
|
80 |
-
gr.Markdown("# 🔍 Chatbot Analizador de Documentos")
|
81 |
-
|
82 |
-
# Cuadro de texto para mostrar la respuesta generada, etiquetado en español
|
83 |
-
response = gr.Textbox(lines=5, label="Respuesta")
|
84 |
-
|
85 |
-
# Campo de texto multimodal para que el usuario suba un archivo e ingrese una pregunta, en español
|
86 |
-
chat = gr.MultimodalTextbox(file_types=["image"], interactive=True,
|
87 |
-
show_label=False, placeholder="Sube una imagen del documento haciendo clic en '+' y haz una pregunta.")
|
88 |
-
|
89 |
-
# Se asigna la función chat_fn para que se ejecute cuando el usuario envíe un mensaje en chat
|
90 |
-
chat.submit(chat_fn, inputs=chat, outputs=response)
|
91 |
-
|
92 |
-
# Lanza la aplicación si este archivo es ejecutado directamente
|
93 |
-
if __name__ == "__main__":
|
94 |
-
demo.launch()
|
|
|
1 |
import gradio as gr
|
2 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
3 |
+
|
4 |
+
# Cargar el modelo y el tokenizador desde Hugging Face
|
5 |
+
model_name = "TheBloke/mistral-ft-optimized-1227-GGUF"
|
6 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
7 |
+
model = AutoModelForCausalLM.from_pretrained(model_name)
|
8 |
+
|
9 |
+
# Función para generar respuestas del chatbot
|
10 |
+
def chat_with_model(input_text):
|
11 |
+
inputs = tokenizer(input_text, return_tensors="pt")
|
12 |
+
outputs = model.generate(inputs["input_ids"], max_length=100, num_return_sequences=1, pad_token_id=tokenizer.eos_token_id)
|
13 |
+
response = tokenizer.decode(outputs[0], skip_special_tokens=True)
|
14 |
+
return response
|
15 |
+
|
16 |
+
# Crear la interfaz con Gradio
|
17 |
+
interface = gr.Interface(fn=chat_with_model,
|
18 |
+
inputs="text",
|
19 |
+
outputs="text",
|
20 |
+
title="Chatbot con Mistral FT Optimized",
|
21 |
+
description="Un chatbot básico utilizando el modelo Mistral FT Optimized 1227 en Hugging Face.",
|
22 |
+
examples=["Hola, ¿cómo estás?", "Cuéntame un chiste."])
|
23 |
+
|
24 |
+
# Lanzar la aplicación
|
25 |
+
interface.launch()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|