markIA23 commited on
Commit
b52833f
·
verified ·
1 Parent(s): e7fde9f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +56 -126
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
- TITLE = '''
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
- # Load the tokenizer and model
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 inference function
72
- @spaces.GPU(duration=120)
73
- def chat_llama3_1_8b(message: str,
74
- history: list,
75
- temperature: float,
76
- max_new_tokens: int
77
- ) -> str:
78
- """
79
- Generate a streaming response using the llama3-8b model.
80
- Args:
81
- message (str): The input message.
82
- history (list): The conversation history used by ChatInterface.
83
- temperature (float): The temperature for generating the response.
84
- max_new_tokens (int): The maximum number of new tokens to generate.
85
- Returns:
86
- str: The generated response.
87
- """
88
- conversation = []
89
- for user, assistant in history:
90
- conversation.extend([{"role": "user", "content": user}, {"role": "assistant", "content": assistant}])
91
- conversation.append({"role": "user", "content": message})
 
 
 
 
 
 
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= input_ids,
103
  streamer=streamer,
104
- max_new_tokens=max_new_tokens,
105
- do_sample=temperature != 0, # This will enforce greedy generation (do_sample=False) when the temperature is passed 0, avoiding the crash.
106
- temperature=temperature,
107
- eos_token_id=terminators,
108
  )
109
 
 
110
  t = Thread(target=model.generate, kwargs=generate_kwargs)
111
  t.start()
112
 
113
- outputs = []
 
114
  for text in streamer:
115
- outputs.append(text)
116
- yield "".join(outputs)
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
- gr.Markdown(TITLE)
125
- gr.Markdown(DESCRIPTION)
126
- #gr.DuplicateButton(value="Duplicate Space for private use", elem_id="duplicate-button")
127
- gr.ChatInterface(
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
- gr.Markdown(LICENSE)
 
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()