FigmaPrompt
Add application file
1d05d78
Raw History Blame Contribute Delete
4.54 kB
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()