File size: 4,541 Bytes
b600651 7562ef2 b600651 1d05d78 b600651 1d05d78 b600651 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 | import torch
import gradio as gr
from transformers import AutoTokenizer, AutoModelForCausalLM
import spaces
# --------------------------------------------------------
# CONFIG
# --------------------------------------------------------
MODEL_ID = "benkemp/granite-excel-es-qlora" # CAMBIA ESTO
SYSTEM_PROMPT = (
"Eres un asistente que convierte instrucciones de negocio en "
"fórmulas de Excel en español. Respondes siempre SOLO con una "
"fórmula Excel válida usando funciones en español y ';' como separador."
)
CONTEXTOS = {
"Ventas": (
"Tabla de ventas: A = Fecha, B = Cliente, C = Producto, "
"D = Unidades vendidas, E = Importe, F = Región. Filas 2–500."
),
"RRHH": (
"Tabla HR: A = Empleado, B = Departamento, C = Salario, "
"D = Horas trabajadas, E = Fecha de ingreso, F = Bonificaciones. "
"Filas 2–400."
),
"Finanzas": (
"Tabla de finanzas: A = Categoría, B = Presupuesto, C = Gasto real, "
"D = Mes, E = Responsable. Filas 3–200."
),
"Inventario": (
"Tabla de inventario: A = Producto, B = Categoría, C = Stock actual, "
"D = Stock mínimo, E = Precio, F = Almacén. Filas 2–300."
),
"Marketing": (
"Tabla de marketing: A = Fecha, B = Campaña, C = Canal, "
"D = Impresiones, E = Clics, F = Conversiones, G = Coste."
),
}
# --------------------------------------------------------
# ZeroGPU MODEL LOADING (LAZY)
# --------------------------------------------------------
tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
if tokenizer.pad_token is None:
tokenizer.pad_token = tokenizer.eos_token
model = None # ← se carga solo cuando hace falta
@spaces.GPU
def load_model():
"""Carga el modelo SOLO cuando ZeroGPU lo activa."""
global model
if model is None:
model = AutoModelForCausalLM.from_pretrained(
MODEL_ID,
torch_dtype=torch.float16,
device_map="auto",
)
return model
# --------------------------------------------------------
# GENERACIÓN
# --------------------------------------------------------
def build_prompt(system_prompt: str, context: str, instruction: str) -> str:
return (
f"[SISTEMA]\n{system_prompt}\n\n"
f"[CONTEXTO]\n{context}\n\n"
f"[INSTRUCCIÓN]\n{instruction}\n\n"
f"[RESPUESTA]\n"
)
@spaces.GPU
def generar_formula(instruction: str, contexto_nombre: str, temperatura: float, max_tokens: int):
if not instruction.strip():
return "⚠️ Escribe una instrucción de negocio."
context = CONTEXTOS.get(contexto_nombre, "")
prompt = build_prompt(SYSTEM_PROMPT, context, instruction)
model_local = load_model() # ← ZeroGPU lo trae a GPU automáticamente
inputs = tokenizer(prompt, return_tensors="pt").to(model_local.device)
with torch.no_grad():
outputs = model_local.generate(
**inputs,
max_new_tokens=max_tokens,
do_sample=(temperatura > 0),
temperature=temperatura,
top_p=0.9,
pad_token_id=tokenizer.eos_token_id,
)
text = tokenizer.decode(outputs[0], skip_special_tokens=True)
# Extraer contenido después de [RESPUESTA]
if "[RESPUESTA]" in text:
result = text.split("[RESPUESTA]")[-1].strip()
else:
result = text.strip()
# Devolver solo la primera línea (limpieza)
return result.splitlines()[0].strip()
# --------------------------------------------------------
# GRADIO UI
# --------------------------------------------------------
with gr.Blocks(title="Granite Excel ES — ZeroGPU") as demo:
gr.Markdown(
"""
# 🧮 Granite Excel SLM (ES) — ZeroGPU Demo
Convierte **instrucciones de negocio en español** en **fórmulas Excel**.
"""
)
instruction = gr.Textbox(
label="Instrucción en español",
placeholder="Ej: Calcular el total de ventas del mes pasado",
lines=3,
)
contexto = gr.Dropdown(
choices=list(CONTEXTOS.keys()),
value="Ventas",
label="Contexto de negocio"
)
temperatura = gr.Slider(0, 1, value=0.0, step=0.1, label="Temperatura")
max_tokens = gr.Slider(16, 128, value=64, step=8, label="Máx. tokens")
output = gr.Textbox(label="Fórmula generada", lines=2)
boton = gr.Button("Generar fórmula")
boton.click(generar_formula, [instruction, contexto, temperatura, max_tokens], output)
demo.launch()
|