danielramos commited on
Commit ·
fbf955a
1
Parent(s): bf59288
fix: switch to unlimited 24/7 CPU Basic engine
Browse files
app.py
CHANGED
|
@@ -1,122 +1,43 @@
|
|
| 1 |
-
import os
|
| 2 |
-
import threading
|
| 3 |
import gradio as gr
|
| 4 |
-
from typing import List, Dict, Any
|
| 5 |
-
|
| 6 |
-
# Importar configuración y lógica existente de main.py
|
| 7 |
from main import (
|
| 8 |
-
app as fastapi_app,
|
| 9 |
graph_app,
|
| 10 |
HumanMessage,
|
| 11 |
AIMessage,
|
| 12 |
SystemMessage,
|
| 13 |
-
DEFAULT_SYSTEM_PROMPT
|
|
|
|
| 14 |
)
|
| 15 |
|
| 16 |
-
# Detección del motor GPU (Hugging Face ZeroGPU)
|
| 17 |
-
USE_CUDA_ENGINE = False
|
| 18 |
-
|
| 19 |
-
try:
|
| 20 |
-
import spaces
|
| 21 |
-
import torch
|
| 22 |
-
from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
|
| 23 |
-
|
| 24 |
-
# En Hugging Face ZeroGPU siempre está disponible torch y spaces
|
| 25 |
-
MODEL_ID = "Qwen/Qwen2.5-0.5B-Instruct"
|
| 26 |
-
print(f"[INFO] Inicializando motor Transformers en GPU para {MODEL_ID}...")
|
| 27 |
-
tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
|
| 28 |
-
model = AutoModelForCausalLM.from_pretrained(
|
| 29 |
-
MODEL_ID,
|
| 30 |
-
torch_dtype="auto",
|
| 31 |
-
device_map="auto"
|
| 32 |
-
)
|
| 33 |
-
USE_CUDA_ENGINE = True
|
| 34 |
-
print("[INFO] Motor Transformers GPU cargado exitosamente en tarjeta gráfica.")
|
| 35 |
-
except Exception as e:
|
| 36 |
-
print(f"[INFO] Modo local/CPU detectado ({e}). Utilizando motor local LangGraph / llama-cpp-python.")
|
| 37 |
-
USE_CUDA_ENGINE = False
|
| 38 |
-
|
| 39 |
-
# Stub para spaces.GPU en desarrollo local
|
| 40 |
-
try:
|
| 41 |
-
import spaces
|
| 42 |
-
except ImportError:
|
| 43 |
-
class spaces:
|
| 44 |
-
@staticmethod
|
| 45 |
-
def GPU(func=None, duration=None):
|
| 46 |
-
if func is not None:
|
| 47 |
-
return func
|
| 48 |
-
def decorator(f):
|
| 49 |
-
return f
|
| 50 |
-
return decorator
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
# Función de generación con soporte de Streaming y aceleración por GPU
|
| 54 |
-
@spaces.GPU
|
| 55 |
def chat_fn(message, history):
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
max_new_tokens=120,
|
| 78 |
-
temperature=0.3,
|
| 79 |
-
repetition_penalty=1.15
|
| 80 |
-
)
|
| 81 |
-
t = threading.Thread(target=model.generate, kwargs=generate_kwargs)
|
| 82 |
-
t.start()
|
| 83 |
-
|
| 84 |
-
partial_text = ""
|
| 85 |
-
for new_token in streamer:
|
| 86 |
-
partial_text += new_token
|
| 87 |
-
yield partial_text
|
| 88 |
-
else:
|
| 89 |
-
# 2. Modo Local (LangGraph + llama-cpp-python)
|
| 90 |
-
messages = [SystemMessage(content=DEFAULT_SYSTEM_PROMPT)]
|
| 91 |
-
if history:
|
| 92 |
-
for turn in history:
|
| 93 |
-
if isinstance(turn, dict):
|
| 94 |
-
role = turn.get("role", "user")
|
| 95 |
-
content = turn.get("content", "")
|
| 96 |
-
if role == "assistant":
|
| 97 |
-
messages.append(AIMessage(content=content))
|
| 98 |
-
else:
|
| 99 |
-
messages.append(HumanMessage(content=content))
|
| 100 |
-
elif isinstance(turn, (list, tuple)) and len(turn) == 2:
|
| 101 |
-
if turn[0]:
|
| 102 |
-
messages.append(HumanMessage(content=str(turn[0])))
|
| 103 |
-
if turn[1]:
|
| 104 |
-
messages.append(AIMessage(content=str(turn[1])))
|
| 105 |
-
|
| 106 |
-
messages.append(HumanMessage(content=message))
|
| 107 |
-
output = graph_app.invoke({"messages": messages})
|
| 108 |
-
yield output["messages"][-1].content
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
# Interfaz Gradio con Streaming en tiempo real
|
| 112 |
demo = gr.ChatInterface(
|
| 113 |
fn=chat_fn,
|
| 114 |
title="⚡ Qwen 2.5 (0.5B) • Intelecto Conciso",
|
| 115 |
-
description="Chatbot superinteligente, hiperpreciso y conciso en español.
|
| 116 |
examples=["¿Qué es la entropía?", "¿Por qué el cielo es azul?", "¿Qué es la vida?"],
|
| 117 |
)
|
| 118 |
|
| 119 |
-
# Integrar las rutas de FastAPI (/chat, /healthz, /docs) en la misma
|
| 120 |
demo.app.include_router(fastapi_app.router)
|
| 121 |
|
| 122 |
if __name__ == "__main__":
|
|
|
|
|
|
|
|
|
|
| 1 |
import gradio as gr
|
|
|
|
|
|
|
|
|
|
| 2 |
from main import (
|
|
|
|
| 3 |
graph_app,
|
| 4 |
HumanMessage,
|
| 5 |
AIMessage,
|
| 6 |
SystemMessage,
|
| 7 |
+
DEFAULT_SYSTEM_PROMPT,
|
| 8 |
+
app as fastapi_app
|
| 9 |
)
|
| 10 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
def chat_fn(message, history):
|
| 12 |
+
messages = [SystemMessage(content=DEFAULT_SYSTEM_PROMPT)]
|
| 13 |
+
if history:
|
| 14 |
+
for turn in history:
|
| 15 |
+
if isinstance(turn, dict):
|
| 16 |
+
role = turn.get("role", "user")
|
| 17 |
+
content = turn.get("content", "")
|
| 18 |
+
if role == "assistant":
|
| 19 |
+
messages.append(AIMessage(content=content))
|
| 20 |
+
else:
|
| 21 |
+
messages.append(HumanMessage(content=content))
|
| 22 |
+
elif isinstance(turn, (list, tuple)) and len(turn) == 2:
|
| 23 |
+
if turn[0]:
|
| 24 |
+
messages.append(HumanMessage(content=str(turn[0])))
|
| 25 |
+
if turn[1]:
|
| 26 |
+
messages.append(AIMessage(content=str(turn[1])))
|
| 27 |
+
|
| 28 |
+
messages.append(HumanMessage(content=message))
|
| 29 |
+
output = graph_app.invoke({"messages": messages})
|
| 30 |
+
return output["messages"][-1].content
|
| 31 |
+
|
| 32 |
+
# Interfaz interactiva de Chat de Gradio (Modo Ilimitado 24/7 en CPU Basic)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
demo = gr.ChatInterface(
|
| 34 |
fn=chat_fn,
|
| 35 |
title="⚡ Qwen 2.5 (0.5B) • Intelecto Conciso",
|
| 36 |
+
description="Chatbot superinteligente, hiperpreciso y conciso en español. Ilimitado 24/7 con LangGraph y llama-cpp-python en Hugging Face Spaces (16 GB RAM).",
|
| 37 |
examples=["¿Qué es la entropía?", "¿Por qué el cielo es azul?", "¿Qué es la vida?"],
|
| 38 |
)
|
| 39 |
|
| 40 |
+
# Integrar las rutas de FastAPI (/chat, /healthz, /docs) en la misma app
|
| 41 |
demo.app.include_router(fastapi_app.router)
|
| 42 |
|
| 43 |
if __name__ == "__main__":
|