askbyte commited on
Commit
3fb5e57
·
verified ·
1 Parent(s): d5afe56

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +18 -76
app.py CHANGED
@@ -1,92 +1,34 @@
1
  import gradio as gr
2
- from transformers import AutoModelForCausalLM, AutoTokenizer
3
  import torch
4
- import os
5
- import gc
6
 
7
- model = None
8
- tokenizer = None
 
 
9
 
10
  def get_system_prompt():
11
  with open("prompt.txt", "r", encoding="utf-8") as f:
12
  return f.read().strip()
13
 
14
- def load_model_if_needed():
15
- global model, tokenizer
 
16
 
17
- if model is None:
18
- print("🔁 Cargando modelo Falcon-7B-Instruct...")
19
 
20
- model_name = "tiiuae/falcon-7b-instruct"
21
-
22
- tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
23
- model = AutoModelForCausalLM.from_pretrained(
24
- model_name,
25
- torch_dtype=torch.float32,
26
- trust_remote_code=True,
27
- low_cpu_mem_usage=True
28
- )
29
-
30
- model = model.to("cpu")
31
-
32
- gc.collect()
33
- torch.cuda.empty_cache() if torch.cuda.is_available() else None
34
-
35
- print("✅ Modelo Falcon-7B cargado en CPU")
36
-
37
- def generate_response(user_message):
38
- try:
39
- load_model_if_needed()
40
-
41
- if not user_message.strip():
42
- return "Por favor, escribe una pregunta para que pueda ayudarte."
43
-
44
- system_prompt = get_system_prompt()
45
-
46
- prompt = f"{system_prompt}\n\nUsuario: {user_message}\nBITER:"
47
-
48
- inputs = tokenizer(prompt, return_tensors="pt")
49
-
50
- generation_config = {
51
- "max_new_tokens": 400,
52
- "temperature": 0.7,
53
- "top_p": 0.9,
54
- "do_sample": True,
55
- "pad_token_id": tokenizer.eos_token_id,
56
- "num_return_sequences": 1
57
- }
58
-
59
- with torch.no_grad():
60
- outputs = model.generate(**inputs, **generation_config)
61
-
62
- response = tokenizer.decode(outputs[0], skip_special_tokens=True)
63
- answer = response.replace(prompt, "").strip()
64
-
65
- gc.collect()
66
- torch.cuda.empty_cache() if torch.cuda.is_available() else None
67
-
68
- return answer
69
-
70
- except Exception as e:
71
- print(f"Error: {str(e)}")
72
- return f"❌ Lo siento, ha ocurrido un error: {str(e)}"
73
 
 
74
  demo = gr.Interface(
75
  fn=generate_response,
76
- inputs=gr.Textbox(
77
- placeholder="Escribe tu pregunta sobre emprendimiento aquí...",
78
- label="Tu pregunta"
79
- ),
80
- outputs=gr.Textbox(label="Respuesta de BITER"),
81
- title="BITER - Tu Mentor en Tiempo Real para Decisiones de Negocio",
82
- description="BITER es un asistente de IA que responde dudas de emprendedores como si fuera un CEO experimentado.",
83
- examples=[
84
- ["¿Cómo puedo validar mi idea de negocio con poco presupuesto?"],
85
- ["¿Cuál es la mejor estrategia para conseguir mis primeros clientes?"],
86
- ["¿Debería invertir en publicidad en redes sociales o en SEO?"]
87
- ],
88
- allow_flagging="never"
89
  )
90
 
91
  if __name__ == "__main__":
92
- demo.queue(max_size=1).launch(share=False, debug=False)
 
1
  import gradio as gr
2
+ from transformers import T5Tokenizer, T5ForConditionalGeneration
3
  import torch
 
 
4
 
5
+ # Cargar modelo y tokenizer
6
+ model_name = "google/flan-t5-base"
7
+ tokenizer = T5Tokenizer.from_pretrained(model_name)
8
+ model = T5ForConditionalGeneration.from_pretrained(model_name)
9
 
10
  def get_system_prompt():
11
  with open("prompt.txt", "r", encoding="utf-8") as f:
12
  return f.read().strip()
13
 
14
+ def generate_response(user_input):
15
+ system_prompt = get_system_prompt()
16
+ full_prompt = f"{system_prompt}\n\nUsuario: {user_input}\nBITER:"
17
 
18
+ inputs = tokenizer(full_prompt, return_tensors="pt")
19
+ output = model.generate(**inputs, max_new_tokens=200)
20
 
21
+ decoded_output = tokenizer.decode(output[0], skip_special_tokens=True)
22
+ return decoded_output.strip()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
 
24
+ # Interfaz Gradio para probar el modelo directamente en Hugging Face
25
  demo = gr.Interface(
26
  fn=generate_response,
27
+ inputs=gr.Textbox(lines=2, placeholder="Escribe tu pregunta..."),
28
+ outputs=gr.Textbox(),
29
+ title="BITER - Mentor IA para Emprendedores",
30
+ description="Respuestas rápidas, estratégicas y en español. Como un CEO que te asesora al instante.",
 
 
 
 
 
 
 
 
 
31
  )
32
 
33
  if __name__ == "__main__":
34
+ demo.launch()