Update app.py
Browse files
app.py
CHANGED
@@ -12,152 +12,82 @@ if hf_token:
|
|
12 |
else:
|
13 |
raise ValueError("Hugging Face token no encontrado. Asegúrate de que la variable de entorno HF_TOKEN esté configurada.")
|
14 |
|
15 |
-
|
16 |
-
<h1 style="text-align: center;">Meta Llama3.1 8B <a href="https://huggingface.co/spaces/ysharma/Chat_with_Meta_llama3_1_8b?duplicate=true" id="duplicate-button"><button style="color:white">Duplicate this Space</button></a></h1>
|
17 |
-
'''
|
18 |
-
|
19 |
-
DESCRIPTION = '''
|
20 |
-
<div>
|
21 |
-
<p>This Space demonstrates the instruction-tuned model <a href="https://huggingface.co/meta-llama/Meta-Llama-3.1-8B-Instruct"><b>Meta Llama3.1 8b Chat</b></a>. Feel free to play with this demo, or duplicate to run privately!</p>
|
22 |
-
<p>🔨 Interested in trying out more powerful Instruct versions of Llama3.1? Check out the <a href="https://huggingface.co/chat/"><b>Hugging Chat</b></a> integration for 🐘 Meta Llama 3.1 70b, and 🦕 Meta Llama 3.1 405b</p>
|
23 |
-
<p>🔎 For more details about the Llama3.1 release and how to use the model with <code>transformers</code>, take a look <a href="https://huggingface.co/blog/llama31">at our blog post</a>.</p>
|
24 |
-
</div>
|
25 |
-
'''
|
26 |
-
|
27 |
-
LICENSE = """
|
28 |
-
<p/>
|
29 |
-
---
|
30 |
-
Built with Llama
|
31 |
-
"""
|
32 |
-
|
33 |
-
PLACEHOLDER = """
|
34 |
-
<div style="padding: 30px; text-align: center; display: flex; flex-direction: column; align-items: center;">
|
35 |
-
<img src="https://ysharma-dummy-chat-app.hf.space/file=/tmp/gradio/c21ff9c8e7ecb2f7d957a72f2ef03c610ac7bbc4/Meta_lockup_positive%20primary_RGB_small.jpg" style="width: 80%; max-width: 550px; height: auto; opacity: 0.55; ">
|
36 |
-
<h1 style="font-size: 28px; margin-bottom: 2px; opacity: 0.55;">Meta llama3.1</h1>
|
37 |
-
<p style="font-size: 18px; margin-bottom: 2px; opacity: 0.65;">Ask me anything...</p>
|
38 |
-
</div>
|
39 |
-
"""
|
40 |
-
|
41 |
-
css = """
|
42 |
-
h1 {
|
43 |
-
text-align: center;
|
44 |
-
display: block;
|
45 |
-
display: flex;
|
46 |
-
align-items: center;
|
47 |
-
justify-content: center;
|
48 |
-
}
|
49 |
-
#duplicate-button {
|
50 |
-
margin-left: 10px;
|
51 |
-
color: white;
|
52 |
-
background: #1565c0;
|
53 |
-
border-radius: 100vh;
|
54 |
-
font-size: 1rem;
|
55 |
-
padding: 3px 5px;
|
56 |
-
}
|
57 |
-
"""
|
58 |
-
|
59 |
model_id = "meta-llama/Meta-Llama-3.1-8B-Instruct"
|
60 |
|
61 |
-
#
|
62 |
tokenizer = AutoTokenizer.from_pretrained(model_id)
|
63 |
model = AutoModelForCausalLM.from_pretrained(model_id, device_map="auto")
|
64 |
-
terminators = [
|
65 |
-
tokenizer.eos_token_id,
|
66 |
-
tokenizer.convert_tokens_to_ids("")
|
67 |
-
]
|
68 |
-
|
69 |
-
MAX_INPUT_TOKEN_LENGTH = 4096
|
70 |
|
71 |
-
# Gradio
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
"""
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
92 |
|
|
|
93 |
input_ids = tokenizer.apply_chat_template(conversation, return_tensors="pt")
|
94 |
-
if input_ids.shape[1] > MAX_INPUT_TOKEN_LENGTH:
|
95 |
-
input_ids = input_ids[:, -MAX_INPUT_TOKEN_LENGTH:]
|
96 |
-
gr.Warning(f"Trimmed input from conversation as it was longer than {MAX_INPUT_TOKEN_LENGTH} tokens.")
|
97 |
input_ids = input_ids.to(model.device)
|
98 |
|
|
|
99 |
streamer = TextIteratorStreamer(tokenizer, timeout=10.0, skip_prompt=True, skip_special_tokens=True)
|
100 |
|
|
|
101 |
generate_kwargs = dict(
|
102 |
-
input_ids=
|
103 |
streamer=streamer,
|
104 |
-
max_new_tokens=
|
105 |
-
do_sample=
|
106 |
-
temperature=
|
107 |
-
eos_token_id=terminators,
|
108 |
)
|
109 |
|
|
|
110 |
t = Thread(target=model.generate, kwargs=generate_kwargs)
|
111 |
t.start()
|
112 |
|
113 |
-
|
|
|
114 |
for text in streamer:
|
115 |
-
|
116 |
-
yield
|
117 |
-
|
118 |
-
|
119 |
-
# Gradio block
|
120 |
-
chatbot=gr.Chatbot(height=450, placeholder=PLACEHOLDER, label='Gradio ChatInterface')
|
121 |
-
|
122 |
-
with gr.Blocks(fill_height=True, css=css) as demo:
|
123 |
|
124 |
-
|
125 |
-
|
126 |
-
#
|
127 |
-
gr.
|
128 |
-
fn=chat_llama3_1_8b,
|
129 |
-
chatbot=chatbot,
|
130 |
-
fill_height=True,
|
131 |
-
examples_per_page=3,
|
132 |
-
additional_inputs_accordion=gr.Accordion(label="⚙️ Parameters", open=False, render=False),
|
133 |
-
additional_inputs=[
|
134 |
-
gr.Slider(minimum=0,
|
135 |
-
maximum=1,
|
136 |
-
step=0.1,
|
137 |
-
value=0.95,
|
138 |
-
label="Temperature",
|
139 |
-
render=False),
|
140 |
-
gr.Slider(minimum=128,
|
141 |
-
maximum=4096,
|
142 |
-
step=1,
|
143 |
-
value=512,
|
144 |
-
label="Max new tokens",
|
145 |
-
render=False ),
|
146 |
-
],
|
147 |
-
examples=[
|
148 |
-
["There's a llama in my garden 😱 What should I do?"],
|
149 |
-
["What is the best way to open a can of worms?"],
|
150 |
-
["The odd numbers in this group add up to an even number: 15, 32, 5, 13, 82, 7, 1. "],
|
151 |
-
['How to setup a human base on Mars? Give short answer.'],
|
152 |
-
['Explain theory of relativity to me like I’m 8 years old.'],
|
153 |
-
['What is 9,000 * 9,000?'],
|
154 |
-
['Write a pun-filled happy birthday message to my friend Alex.'],
|
155 |
-
['Justify why a penguin might make a good king of the jungle.']
|
156 |
-
],
|
157 |
-
cache_examples=False,
|
158 |
-
)
|
159 |
|
160 |
-
|
|
|
161 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
162 |
if __name__ == "__main__":
|
163 |
-
demo.launch()
|
|
|
12 |
else:
|
13 |
raise ValueError("Hugging Face token no encontrado. Asegúrate de que la variable de entorno HF_TOKEN esté configurada.")
|
14 |
|
15 |
+
# Definimos el ID del modelo Meta Llama 3.1 8B Instruct
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
16 |
model_id = "meta-llama/Meta-Llama-3.1-8B-Instruct"
|
17 |
|
18 |
+
# Cargamos el tokenizador y el modelo desde Hugging Face
|
19 |
tokenizer = AutoTokenizer.from_pretrained(model_id)
|
20 |
model = AutoModelForCausalLM.from_pretrained(model_id, device_map="auto")
|
|
|
|
|
|
|
|
|
|
|
|
|
21 |
|
22 |
+
# Si Gradio está en modo de no recargar (NO_RELOAD), creamos un cliente de inferencia
|
23 |
+
if gr.NO_RELOAD:
|
24 |
+
client = InferenceClient()
|
25 |
+
|
26 |
+
# Definimos un mensaje inicial que simula un rol del sistema y contiene instrucciones sobre cómo responder, adaptado al español
|
27 |
+
system_message = {
|
28 |
+
"role": "system",
|
29 |
+
"content": """
|
30 |
+
Eres un asistente útil.
|
31 |
+
Recibirás una pregunta y un conjunto de respuestas junto con una puntuación de confianza entre 0 y 1 para cada respuesta.
|
32 |
+
Tu trabajo es convertir esta información en una respuesta corta y coherente.
|
33 |
+
Por ejemplo:
|
34 |
+
Pregunta: "¿A quién se le está facturando?", respuesta: {"answer": "John Doe", "confidence": 0.98}
|
35 |
+
Deberías responder algo como:
|
36 |
+
Con un alto grado de confianza, puedo decir que se le está facturando a John Doe.
|
37 |
+
Pregunta: "¿Cuál es el total de la factura?", respuesta: [{"answer": "154.08", "confidence": 0.75}, {"answer": "155", "confidence": 0.25}]
|
38 |
+
Deberías responder algo como:
|
39 |
+
Creo que el total de la factura es de $154.08 aunque también podría ser $155.
|
40 |
+
"""}
|
41 |
+
|
42 |
+
# Definimos la función de inferencia utilizando el modelo Meta Llama 3.1 8B Instruct
|
43 |
+
def chat_fn(multimodal_message):
|
44 |
+
# Extraemos el texto de la pregunta del mensaje proporcionado por el usuario
|
45 |
+
question = multimodal_message["text"]
|
46 |
+
|
47 |
+
# Construimos el mensaje para el modelo
|
48 |
+
conversation = [{"role": "user", "content": question}]
|
49 |
|
50 |
+
# Generamos los IDs de entrada utilizando el tokenizador del modelo
|
51 |
input_ids = tokenizer.apply_chat_template(conversation, return_tensors="pt")
|
|
|
|
|
|
|
52 |
input_ids = input_ids.to(model.device)
|
53 |
|
54 |
+
# Configuramos el streamer para la generación progresiva de texto
|
55 |
streamer = TextIteratorStreamer(tokenizer, timeout=10.0, skip_prompt=True, skip_special_tokens=True)
|
56 |
|
57 |
+
# Configuramos los argumentos de generación
|
58 |
generate_kwargs = dict(
|
59 |
+
input_ids=input_ids,
|
60 |
streamer=streamer,
|
61 |
+
max_new_tokens=500, # Ajusta esto según tus necesidades
|
62 |
+
do_sample=True,
|
63 |
+
temperature=0.7, # Ajusta la temperatura según tus necesidades
|
|
|
64 |
)
|
65 |
|
66 |
+
# Iniciamos la generación de texto en un hilo separado
|
67 |
t = Thread(target=model.generate, kwargs=generate_kwargs)
|
68 |
t.start()
|
69 |
|
70 |
+
# Iteramos sobre los tokens generados y construimos la respuesta
|
71 |
+
message = ""
|
72 |
for text in streamer:
|
73 |
+
message += text
|
74 |
+
yield message
|
|
|
|
|
|
|
|
|
|
|
|
|
75 |
|
76 |
+
# Usamos la clase 'Blocks' de Gradio para definir la interfaz de usuario
|
77 |
+
with gr.Blocks() as demo:
|
78 |
+
# Título de la aplicación en español
|
79 |
+
gr.Markdown("# 🔍 Chatbot Analizador de Documentos")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
80 |
|
81 |
+
# Cuadro de texto para mostrar la respuesta generada, etiquetado en español
|
82 |
+
response = gr.Textbox(lines=5, label="Respuesta")
|
83 |
|
84 |
+
# Campo de texto multimodal para que el usuario suba un archivo e ingrese una pregunta, en español
|
85 |
+
chat = gr.MultimodalTextbox(file_types=["image"], interactive=True,
|
86 |
+
show_label=False, placeholder="Sube una imagen del documento haciendo clic en '+' y haz una pregunta.")
|
87 |
+
|
88 |
+
# Se asigna la función chat_fn para que se ejecute cuando el usuario envíe un mensaje en chat
|
89 |
+
chat.submit(chat_fn, inputs=chat, outputs=response)
|
90 |
+
|
91 |
+
# Lanza la aplicación si este archivo es ejecutado directamente
|
92 |
if __name__ == "__main__":
|
93 |
+
demo.launch()
|