repd79 commited on
Commit
9d138e8
verified
1 Parent(s): 3385516

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +24 -75
app.py CHANGED
@@ -1,86 +1,35 @@
1
- import gradio as gr
2
- import os
3
- import logging
4
- from huggingface_hub import InferenceClient
5
 
6
- # Configurar logging para depuraci贸n
7
- logging.basicConfig(
8
- level=logging.INFO,
9
- format="%(asctime)s - %(levelname)s - %(message)s"
10
- )
11
 
12
- # Obtener el token de Hugging Face de variables de entorno (secret)
13
- hf_token = os.getenv("HF_TOKEN2")
14
 
15
- if not hf_token:
16
- logging.error("El token de Hugging Face no est谩 configurado. Agrega 'HF_TOKEN' como variable de entorno.")
17
- raise ValueError("El token de Hugging Face no est谩 configurado. Agrega 'HF_TOKEN' como variable de entorno.")
18
 
19
- logging.info("Token de Hugging Face encontrado correctamente.")
 
20
 
21
- # Inicializar el cliente de inferencia con autenticaci贸n segura
22
- try:
23
- client = InferenceClient("BSC-LT/ALIA-40b", token=hf_token)
24
- logging.info("Cliente de Hugging Face inicializado correctamente.")
25
- except Exception as e:
26
- logging.error(f"Error al inicializar el cliente de Hugging Face: {e}")
27
- raise
28
 
29
- def respond(
30
- message,
31
- history: list[tuple[str, str]],
32
- system_message,
33
- max_tokens,
34
- temperature,
35
- top_p,
36
- ):
37
- logging.info("Generando respuesta para el mensaje del usuario.")
38
 
39
- prompt = f"{system_message}\n"
40
-
41
- for user_input, bot_response in history:
42
- prompt += f"User: {user_input}\nAssistant: {bot_response}\n"
43
-
44
- prompt += f"User: {message}\nAssistant:"
45
-
46
- response = ""
47
-
48
- try:
49
- for message in client.text_generation(
50
- prompt=prompt,
51
- max_new_tokens=max_tokens,
52
- temperature=temperature,
53
- top_p=top_p,
54
- stream=True
55
- ):
56
- response += message
57
- yield response
58
-
59
- logging.info("Respuesta generada correctamente.")
60
-
61
- except Exception as e:
62
- logging.error(f"Error durante la generaci贸n de texto: {e}", exc_info=True)
63
- yield f"Error: {str(e)}. Por favor, int茅ntalo nuevamente."
64
-
65
- """
66
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
67
- """
68
- demo = gr.Interface(
69
- fn=respond,
70
- inputs=[
71
- gr.Textbox(value="Eres un chatbot muy amigable.", label="Mensaje del sistema"),
72
- gr.Chatbot(type="messages"),
73
- gr.Slider(minimum=1, maximum=1024, value=512, step=1, label="Max new tokens"),
74
- gr.Slider(minimum=0.1, maximum=1.0, value=0.7, step=0.1, label="Temperature"),
75
- gr.Slider(minimum=0.1, maximum=1.0, value=0.9, step=0.05, label="Top-p"),
76
- gr.Textbox(value="", label="Mensaje del usuario"), # Asegurar los inputs correctos
77
- ],
78
  outputs="text",
79
- title="ALIA-40b Generador de Texto",
80
- description="Introduce un texto y deja que el modelo ALIA-40b complete la respuesta.",
81
  )
82
 
83
  if __name__ == "__main__":
84
- logging.info("Lanzando la aplicaci贸n con Gradio...")
85
- demo.launch(share=True)
86
-
 
 
 
 
 
1
 
 
 
 
 
 
2
 
 
 
3
 
4
+ import gradio as gr
5
+ from transformers import AutoTokenizer, AutoModelForCausalLM
 
6
 
7
+ # Especifica el nombre del modelo
8
+ model_name = "BSC-LT/ALIA-40b"
9
 
10
+ # Cargar el tokenizador y el modelo
11
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
12
+ model = AutoModelForCausalLM.from_pretrained(model_name)
 
 
 
 
13
 
14
+ def generar_texto(entrada):
15
+ # Tokenizar la entrada
16
+ input_ids = tokenizer.encode(entrada, return_tensors="pt")
 
 
 
 
 
 
17
 
18
+ # Generar texto con el modelo
19
+ output = model.generate(input_ids, max_length=100, num_return_sequences=1)
20
+
21
+ # Decodificar y retornar el texto generado
22
+ texto_generado = tokenizer.decode(output[0], skip_special_tokens=True)
23
+ return texto_generado
24
+
25
+ # Crear la interfaz de Gradio
26
+ interfaz = gr.Interface(
27
+ fn=generar_texto,
28
+ inputs=gr.inputs.Textbox(lines=2, placeholder="Escribe tu prompt aqu铆..."),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
  outputs="text",
30
+ title="Generador de Texto con ALIA-40b",
31
+ description="Este modelo genera texto utilizando ALIA-40b, un modelo LLM entrenado por BSC-LT."
32
  )
33
 
34
  if __name__ == "__main__":
35
+ interfaz.launch()