File size: 1,498 Bytes
8c70434
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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)