# app.py — FastAPI бекенд за Hugging Face Spaces import os import httpx from fastapi import FastAPI, Request, UploadFile, File, Response from fastapi.responses import JSONResponse from fastapi.staticfiles import StaticFiles HF_TOKEN = os.getenv("HF_TOKEN") or os.getenv("HUGGINGFACEHUB_API_TOKEN") or os.getenv("HUGGING_FACE_HUB_TOKEN") HF_MODEL = os.getenv("HF_MODEL", "nateraw/food101") HF_URL = f"https://api-inference.huggingface.co/models/{HF_MODEL}" app = FastAPI() @app.get("/health") async def health(): ok = bool(HF_TOKEN) return {"ok": ok, "model": HF_MODEL, "token_present": ok} @app.post("/api/classify") async def classify_raw(request: Request): body = await request.body() if not body: return JSONResponse({"error": "No image body"}, status_code=400) if not HF_TOKEN: return JSONResponse({"error": "Missing HF_TOKEN in Space secrets"}, status_code=500) headers = { "Authorization": f"Bearer {HF_TOKEN}", "Accept": "application/json", "X-Wait-For-Model": "true", } async with httpx.AsyncClient(timeout=60) as client: r = await client.post(HF_URL, headers=headers, content=body) try: data = r.json() return JSONResponse(data, status_code=r.status_code) except Exception: return Response(content=r.text, status_code=r.status_code, media_type=r.headers.get("content-type", "text/plain")) @app.post("/api/classify-multipart") async def classify_multipart(file: UploadFile = File(...)): if not HF_TOKEN: return JSONResponse({"error": "Missing HF_TOKEN in Space secrets"}, status_code=500) headers = { "Authorization": f"Bearer {HF_TOKEN}", "Accept": "application/json", "X-Wait-For-Model": "true", } files = {"file": (file.filename, await file.read(), file.content_type)} async with httpx.AsyncClient(timeout=60) as client: r = await client.post(HF_URL, headers=headers, files=files) try: data = r.json() return JSONResponse(data, status_code=r.status_code) except Exception: return Response(content=r.text, status_code=r.status_code, media_type=r.headers.get("content-type", "text/plain")) if os.path.isdir("frontend"): app.mount("/", StaticFiles(directory="frontend", html=True), name="static")