Spaces:
Runtime error
Runtime error
Delete app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960import osimport requestsfrom fastapi import FastAPI, Requestfrom fastapi.responses import HTMLResponse, JSONResponse, FileResponsefrom fastapi.staticfiles import StaticFiles
app = FastAPI()app.mount("/static", StaticFiles(directory="static"), name="static")
HF_TOKEN = os.environ.get("HF_TOKEN") # tu token en Settings → SecretsMODEL = os.environ.get("MODEL_NAME", "google/flan-t5-small")API_URL = f"https://api-inference.huggingface.co/models/{MODEL}"HEADERS = {"Authorization": f"Bearer {HF_TOKEN}"} if HF_TOKEN else {}
SYSTEM_PROMPT = ( "Eres un asistente amable y conciso. Responde en el idioma del usuario. " "Si el usuario dice 'habla' o 'cuéntame', responde con frases claras y cortas.")
def build_prompt(user_text: str) -> str: return f"{SYSTEM_PROMPT}\nUsuario: {user_text}\nAsistente:"
@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)
try: # Llamada a la Inference API de Hugging Face resp = requests.post(API_URL, headers=HEADERS, json={"inputs": prompt}, timeout=60) resp.raise_for_status() out = resp.json()
if isinstance(out, list) and out and "generated_text" in out[0]: text = out[0]["generated_text"] elif isinstance(out, dict) and "generated_text" in out: text = out["generated_text"] else: text = str(out)
reply = text.split("Asistente:")[-1].strip() if "Asistente:" in text else text.strip() if not reply: reply = "Déjame pensar... ¿puedes repetirlo con otras palabras?" return JSONResponse({"reply": reply}) except Exception as e: return JSONResponse({"reply": f"Ocurrió un problema con el servicio: {e}"})
if __name__ == "__main__": import uvicorn uvicorn.run(app, host="0.0.0.0", port=7860)
app.pyDeleted-60