Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from fastapi import FastAPI, UploadFile, File, Response
|
| 3 |
+
import httpx
|
| 4 |
+
|
| 5 |
+
# Endpoint Space tujuan (bisa dioverride via Space variable TARGET_URL)
|
| 6 |
+
TARGET_URL = os.getenv(
|
| 7 |
+
"TARGET_URL",
|
| 8 |
+
"https://not-lain-background-removal.hf.space/image"
|
| 9 |
+
)
|
| 10 |
+
|
| 11 |
+
app = FastAPI(title="Background Removal Proxy")
|
| 12 |
+
|
| 13 |
+
@app.get("/")
|
| 14 |
+
async def root():
|
| 15 |
+
return {
|
| 16 |
+
"ok": True,
|
| 17 |
+
"message": "POST /removebg with multipart field 'image' → returns image/png",
|
| 18 |
+
"target": TARGET_URL,
|
| 19 |
+
}
|
| 20 |
+
|
| 21 |
+
@app.get("/healthz")
|
| 22 |
+
async def health():
|
| 23 |
+
return {"ok": True}
|
| 24 |
+
|
| 25 |
+
@app.post("/removebg")
|
| 26 |
+
async def removebg(image: UploadFile = File(...)):
|
| 27 |
+
timeout = httpx.Timeout(60.0, connect=20.0)
|
| 28 |
+
async with httpx.AsyncClient(timeout=timeout, follow_redirects=True) as client:
|
| 29 |
+
files = {
|
| 30 |
+
# Space target menerima field bernama 'image'
|
| 31 |
+
"image": (image.filename, await image.read(), image.content_type or "image/jpeg")
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
# retry ringan untuk cold start/gateway
|
| 35 |
+
for attempt in range(2):
|
| 36 |
+
r = await client.post(TARGET_URL, files=files)
|
| 37 |
+
if r.status_code == 200:
|
| 38 |
+
return Response(content=r.content, media_type="image/png")
|
| 39 |
+
if r.status_code in (502, 503, 504) and attempt == 0:
|
| 40 |
+
continue
|
| 41 |
+
return Response(content=r.text, media_type="application/json", status_code=r.status_code)
|
| 42 |
+
|
| 43 |
+
return Response(content='{"detail":"unknown error"}', media_type="application/json", status_code=500)
|