Fifafan1 commited on
Commit
d956057
·
verified ·
1 Parent(s): b2455ae

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py +64 -0
  2. requirements.txt +4 -0
app.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # app.py — FastAPI бекенд за Hugging Face Spaces
2
+ import os
3
+ import httpx
4
+ from fastapi import FastAPI, Request, UploadFile, File, Response
5
+ from fastapi.responses import JSONResponse
6
+ from fastapi.staticfiles import StaticFiles
7
+
8
+ HF_TOKEN = os.getenv("HF_TOKEN") or os.getenv("HUGGINGFACEHUB_API_TOKEN") or os.getenv("HUGGING_FACE_HUB_TOKEN")
9
+ HF_MODEL = os.getenv("HF_MODEL", "nateraw/food101")
10
+ HF_URL = f"https://api-inference.huggingface.co/models/{HF_MODEL}"
11
+
12
+ app = FastAPI()
13
+
14
+ @app.get("/health")
15
+ async def health():
16
+ ok = bool(HF_TOKEN)
17
+ return {"ok": ok, "model": HF_MODEL, "token_present": ok}
18
+
19
+ @app.post("/api/classify")
20
+ async def classify_raw(request: Request):
21
+ body = await request.body()
22
+ if not body:
23
+ return JSONResponse({"error": "No image body"}, status_code=400)
24
+ if not HF_TOKEN:
25
+ return JSONResponse({"error": "Missing HF_TOKEN in Space secrets"}, status_code=500)
26
+
27
+ headers = {
28
+ "Authorization": f"Bearer {HF_TOKEN}",
29
+ "Accept": "application/json",
30
+ "X-Wait-For-Model": "true",
31
+ }
32
+ async with httpx.AsyncClient(timeout=60) as client:
33
+ r = await client.post(HF_URL, headers=headers, content=body)
34
+
35
+ try:
36
+ data = r.json()
37
+ return JSONResponse(data, status_code=r.status_code)
38
+ except Exception:
39
+ return Response(content=r.text, status_code=r.status_code,
40
+ media_type=r.headers.get("content-type", "text/plain"))
41
+
42
+ @app.post("/api/classify-multipart")
43
+ async def classify_multipart(file: UploadFile = File(...)):
44
+ if not HF_TOKEN:
45
+ return JSONResponse({"error": "Missing HF_TOKEN in Space secrets"}, status_code=500)
46
+
47
+ headers = {
48
+ "Authorization": f"Bearer {HF_TOKEN}",
49
+ "Accept": "application/json",
50
+ "X-Wait-For-Model": "true",
51
+ }
52
+ files = {"file": (file.filename, await file.read(), file.content_type)}
53
+ async with httpx.AsyncClient(timeout=60) as client:
54
+ r = await client.post(HF_URL, headers=headers, files=files)
55
+
56
+ try:
57
+ data = r.json()
58
+ return JSONResponse(data, status_code=r.status_code)
59
+ except Exception:
60
+ return Response(content=r.text, status_code=r.status_code,
61
+ media_type=r.headers.get("content-type", "text/plain"))
62
+
63
+ if os.path.isdir("frontend"):
64
+ app.mount("/", StaticFiles(directory="frontend", html=True), name="static")
requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ fastapi==0.111.0
2
+ uvicorn==0.30.1
3
+ httpx==0.27.0
4
+ starlette==0.37.2