markIA23 commited on
Commit
48616d7
verified
1 Parent(s): 62ce61c

Update app.py

Browse files

Est谩 la versi贸n que sustituye al formato que proporciona HG

Files changed (1) hide show
  1. app.py +72 -57
app.py CHANGED
@@ -1,63 +1,78 @@
 
 
 
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
3
-
4
- """
5
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
6
- """
7
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
8
-
9
-
10
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
17
- ):
18
- messages = [{"role": "system", "content": system_message}]
19
-
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
25
-
26
- messages.append({"role": "user", "content": message})
27
-
28
- response = ""
29
-
30
- for message in client.chat_completion(
31
- messages,
32
- max_tokens=max_tokens,
33
- stream=True,
34
- temperature=temperature,
35
- top_p=top_p,
36
- ):
37
- token = message.choices[0].delta.content
38
-
39
- response += token
40
- yield response
41
-
42
- """
43
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
44
- """
45
- demo = gr.ChatInterface(
46
- respond,
47
- additional_inputs=[
48
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
49
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
50
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
51
- gr.Slider(
52
- minimum=0.1,
53
- maximum=1.0,
54
- value=0.95,
55
- step=0.05,
56
- label="Top-p (nucleus sampling)",
57
- ),
58
- ],
59
  )
60
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61
 
 
62
  if __name__ == "__main__":
63
  demo.launch()
 
1
+ import os
2
+ from huggingface_hub import login
3
+ from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
4
  import gradio as gr
5
+
6
+ # Obt茅n el token desde la variable de entorno
7
+ hf_token = os.getenv("LLAMA31")
8
+
9
+ if hf_token:
10
+ # Autenticaci贸n en Hugging Face utilizando el token
11
+ login(token=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
+ # Configuraci贸n para cargar el modelo en 4 bits utilizando bitsandbytes
16
+ bnb_config = BitsAndBytesConfig(load_in_4bit=True)
17
+
18
+ # Cargar el modelo y tokenizador
19
+ model_id = "meta-llama/Meta-Llama-3.1-8B-Instruct"
20
+ tokenizer = AutoTokenizer.from_pretrained(model_id)
21
+ model = AutoModelForCausalLM.from_pretrained(
22
+ model_id,
23
+ device_map="auto",
24
+ quantization_config=bnb_config # Aplicar cuantizaci贸n en 4 bits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
  )
26
 
27
+ # Definir la funci贸n de inferencia del chatbot
28
+ def chat_fn(multimodal_message):
29
+ # Extraer el texto de la pregunta proporcionada por el usuario
30
+ question = multimodal_message["text"]
31
+
32
+ # Construir la conversaci贸n inicial con el mensaje del usuario
33
+ conversation = [{"role": "user", "content": question}]
34
+
35
+ # Generar los IDs de entrada utilizando el tokenizador del modelo
36
+ input_ids = tokenizer.apply_chat_template(conversation, return_tensors="pt")
37
+ input_ids = input_ids.to(model.device)
38
+
39
+ # Configurar el streamer para la generaci贸n progresiva de texto
40
+ streamer = TextIteratorStreamer(tokenizer, timeout=10.0, skip_prompt=True, skip_special_tokens=True)
41
+
42
+ # Configurar los argumentos de generaci贸n
43
+ generate_kwargs = dict(
44
+ input_ids=input_ids,
45
+ streamer=streamer,
46
+ max_new_tokens=500, # Ajusta esto seg煤n tus necesidades
47
+ do_sample=True,
48
+ temperature=0.7, # Ajusta la temperatura seg煤n tus necesidades
49
+ )
50
+
51
+ # Iniciar la generaci贸n de texto en un hilo separado
52
+ t = Thread(target=model.generate, kwargs=generate_kwargs)
53
+ t.start()
54
+
55
+ # Iterar sobre los tokens generados y construir la respuesta
56
+ message = ""
57
+ for text in streamer:
58
+ message += text
59
+ yield message
60
+
61
+ # Crear la interfaz de usuario utilizando Gradio
62
+ with gr.Blocks() as demo:
63
+ # T铆tulo de la aplicaci贸n en espa帽ol
64
+ gr.Markdown("# 馃攳 Chatbot Analizador de Documentos")
65
+
66
+ # Cuadro de texto para mostrar la respuesta generada, etiquetado en espa帽ol
67
+ response = gr.Textbox(lines=5, label="Respuesta")
68
+
69
+ # Campo de texto multimodal para que el usuario suba un archivo e ingrese una pregunta, en espa帽ol
70
+ chat = gr.MultimodalTextbox(file_types=["image"], interactive=True,
71
+ show_label=False, placeholder="Sube una imagen del documento haciendo clic en '+' y haz una pregunta.")
72
+
73
+ # Asignar la funci贸n chat_fn para que se ejecute cuando el usuario env铆e un mensaje en el chat
74
+ chat.submit(chat_fn, inputs=chat, outputs=response)
75
 
76
+ # Lanzar la aplicaci贸n si este archivo es ejecutado directamente
77
  if __name__ == "__main__":
78
  demo.launch()