bg-proxy / app.py
Mystyc's picture
Create app.py
8c70434
raw
history blame
1.5 kB
import os
from fastapi import FastAPI, UploadFile, File, Response
import httpx
# Endpoint Space tujuan (bisa dioverride via Space variable TARGET_URL)
TARGET_URL = os.getenv(
"TARGET_URL",
"https://not-lain-background-removal.hf.space/image"
)
app = FastAPI(title="Background Removal Proxy")
@app.get("/")
async def root():
return {
"ok": True,
"message": "POST /removebg with multipart field 'image' β†’ returns image/png",
"target": TARGET_URL,
}
@app.get("/healthz")
async def health():
return {"ok": True}
@app.post("/removebg")
async def removebg(image: UploadFile = File(...)):
timeout = httpx.Timeout(60.0, connect=20.0)
async with httpx.AsyncClient(timeout=timeout, follow_redirects=True) as client:
files = {
# Space target menerima field bernama 'image'
"image": (image.filename, await image.read(), image.content_type or "image/jpeg")
}
# retry ringan untuk cold start/gateway
for attempt in range(2):
r = await client.post(TARGET_URL, files=files)
if r.status_code == 200:
return Response(content=r.content, media_type="image/png")
if r.status_code in (502, 503, 504) and attempt == 0:
continue
return Response(content=r.text, media_type="application/json", status_code=r.status_code)
return Response(content='{"detail":"unknown error"}', media_type="application/json", status_code=500)