import os import re from fastapi import FastAPI, Request from fastapi.responses import HTMLResponse, JSONResponse, FileResponse from fastapi.staticfiles import StaticFiles from transformers import pipeline # ========================= # Config # ========================= # Modelo por defecto (mejor calidad que t5-small) MODEL_NAME = os.environ.get("MODEL_NAME", "google/flan-t5-small") # Prompt base: instructivo general (T5 funciona mejor con instrucciones en inglés) SYSTEM_PROMPT = ( "You are a smart, helpful assistant. " "Default to Spanish unless the user asks for another language. " "Be concise, clear, and avoid repeating the user's input. " "If asked to translate, just return the translation without extra text. " ) # ========================= # App # ========================= app = FastAPI() app.mount("/static", StaticFiles(directory="static"), name="static") # Cargamos el pipeline una sola vez generator = pipeline( task="text2text-generation", model=MODEL_NAME, ) def build_prompt(user_text: str) -> str: """ Construye un prompt robusto para casos generales. Detecta algunos patrones (traducción/resumen/listas) pero sirve para TODO. """ txt = (user_text or "").strip() # Traducción ES->EN (ej: "traduce X al inglés") m = re.search(r"(?i)\btraduce\s+(.+?)\s+(?:al|a)\s+ingl[eé]s\b", txt) if m: phrase = m.group(1).strip() return f"{SYSTEM_PROMPT}\nTranslate this to English:\n\"\"\"{phrase}\"\"\"" # Traducción EN->ES (ej: "translate X to Spanish") m = re.search(r"(?i)\btranslate\s+(.+?)\s+to\s+spanish\b", txt) if m: phrase = m.group(1).strip() return f"{SYSTEM_PROMPT}\nTranslate this to Spanish:\n\"\"\"{phrase}\"\"\"" # Resumen rápido (si el usuario dice 'resume:' o 'resumen de') if re.search(r"(?i)\b(resume|resumen de)\b", txt): return f"{SYSTEM_PROMPT}\nSummarize in Spanish in 1-3 sentences:\n\"\"\"{txt}\"\"\"" # Por defecto: responder en español con claridad return ( f"{SYSTEM_PROMPT}\n" f"User question (answer in Spanish):\n" f"\"\"\"{txt}\"\"\"\n\n" f"Assistant:" ) def postprocess(prompt: str, output_text: str, user_text: str) -> str: """Limpia eco del prompt y salidas vacías.""" if not output_text: return "No tengo una respuesta ahora mismo, ¿puedes reformular?" # Quita el prompt si el modelo lo repitió reply = output_text.replace(prompt, "").strip() # Si todavía quedó prácticamente igual a lo que escribió el usuario, forzamos algo diferente if reply.lower() == (user_text or "").strip().lower(): reply = reply + "." # Sanitiza espacios repetidos reply = re.sub(r"\n{3,}", "\n\n", reply).strip() return reply or "Déjame pensar... ¿puedes decirlo de otra forma?" @app.get("/", response_class=HTMLResponse) async def root(): return FileResponse("static/index.html") @app.post("/api/chat") async def chat(req: Request): data = await req.json() user_text = (data.get("message") or "").strip() if not user_text: return JSONResponse({"reply": "¿Qué te gustaría preguntar?"}) prompt = build_prompt(user_text) # Generación con muestreo y penalización para reducir eco out = generator( prompt, max_new_tokens=128, do_sample=True, top_p=0.92, temperature=0.8, repetition_penalty=1.25, )[0]["generated_text"] reply = postprocess(prompt, out, user_text) return JSONResponse({"reply": reply}) # Ejecuta uvicorn cuando corre como script (Spaces escucha en 7860) if __name__ == "__main__": import uvicorn uvicorn.run(app, host="0.0.0.0", port=7860)