Ksjsjjdj commited on
Commit
f29521b
verified
1 Parent(s): 4186f9e

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +67 -0
app.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from transformers import pipeline, login
3
+ import torch
4
+ from dotenv import load_dotenv
5
+ import os
6
+ import spaces # Importar la librer铆a de spaces
7
+
8
+ # Cargar variables de entorno desde el archivo .env
9
+ load_dotenv()
10
+
11
+ # Obtener el token de Hugging Face desde las variables de entorno
12
+ huggingface_token = os.getenv("HUGGINGFACE_TOKEN")
13
+
14
+ # Verificar si el token fue cargado correctamente
15
+ if not huggingface_token:
16
+ raise ValueError("Token de Hugging Face no encontrado en las variables de entorno")
17
+
18
+ # Iniciar sesi贸n con tu token de Hugging Face
19
+ login(token=huggingface_token) # Inicia sesi贸n con el token
20
+
21
+ # Funci贸n para cargar el modelo en GPU (si est谩 disponible) o en CPU si hay un error
22
+ def load_model():
23
+ model_id = "facebook/MobileLLM-R1.5-950M"
24
+ try:
25
+ # Intentar cargar el modelo en GPU
26
+ print("Intentando cargar el modelo en la GPU...")
27
+ return pipeline(
28
+ "text-generation",
29
+ model=model_id,
30
+ torch_dtype="auto",
31
+ device_map="auto", # Esto autom谩ticamente usa la GPU si est谩 disponible
32
+ )
33
+ except Exception as e:
34
+ # Si hay un error (por ejemplo, no hay GPU disponible), usar CPU
35
+ print("Error en GPU, cambiando a CPU. Error:", e)
36
+ return pipeline(
37
+ "text-generation",
38
+ model=model_id,
39
+ torch_dtype="auto",
40
+ device=0, # Usar CPU en caso de error
41
+ )
42
+
43
+ # Cargar el modelo con el fallback a CPU
44
+ pipe = load_model()
45
+
46
+ # Decorador para garantizar que el c贸digo se ejecute en GPU si est谩 disponible
47
+ @spaces.GPU
48
+ def chat_with_model(system_message, user_message):
49
+ messages = [
50
+ {"role": "system", "content": system_message},
51
+ {"role": "user", "content": user_message},
52
+ ]
53
+
54
+ # Generar la respuesta usando el modelo
55
+ outputs = pipe(messages, max_new_tokens=8192)
56
+ return outputs[0]["generated_text"][-1]
57
+
58
+ # Crear la interfaz de Gradio
59
+ gr.Interface(
60
+ fn=chat_with_model,
61
+ inputs=[
62
+ gr.Textbox(label="System Message", placeholder="Escribe el mensaje del sistema..."),
63
+ gr.Textbox(label="User Message", placeholder="Escribe tu mensaje aqu铆..."),
64
+ ],
65
+ outputs="text",
66
+ live=True,
67
+ ).launch()