File size: 2,381 Bytes
d956057
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# 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")