|
|
import os |
|
|
from fastapi import FastAPI, UploadFile, File, Response |
|
|
import httpx |
|
|
|
|
|
|
|
|
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 = { |
|
|
|
|
|
"image": (image.filename, await image.read(), image.content_type or "image/jpeg") |
|
|
} |
|
|
|
|
|
|
|
|
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) |
|
|
|