um41r commited on
Commit
7c62166
·
verified ·
1 Parent(s): 9325bd2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +33 -19
app.py CHANGED
@@ -1,12 +1,11 @@
1
- # app.py - FastAPI BiRefNet Background Remover API
2
  import torch
3
  import numpy as np
4
  from PIL import Image
5
  from safetensors.torch import load_file
6
  import io
7
- from typing import Optional
8
 
9
- from fastapi import FastAPI, File, UploadFile, HTTPException
10
  from fastapi.middleware.cors import CORSMiddleware
11
  from fastapi.responses import StreamingResponse
12
  import uvicorn
@@ -14,7 +13,7 @@ import uvicorn
14
  from birefnet import BiRefNet
15
  from BiRefNet_config import BiRefNetConfig
16
 
17
- # Global model (loaded once)
18
  device = "cpu"
19
  config = BiRefNetConfig()
20
  model = BiRefNet(config)
@@ -44,10 +43,10 @@ def remove_bg(image: Image.Image) -> Image.Image:
44
 
45
  app = FastAPI(title="BiRefNet Background Remover API")
46
 
47
- # CORS for NextJS/Vercel
48
  app.add_middleware(
49
  CORSMiddleware,
50
- allow_origins=["*"], # Update with your domain in production
51
  allow_credentials=True,
52
  allow_methods=["*"],
53
  allow_headers=["*"],
@@ -55,32 +54,47 @@ app.add_middleware(
55
 
56
  @app.get("/")
57
  async def root():
58
- return {"message": "BiRefNet Background Remover API", "status": "ready"}
59
 
 
60
  @app.post("/remove-bg")
61
- async def remove_background(
62
- file: UploadFile = File(..., description="Image file (PNG/JPG)")
63
- ):
64
- if not file.content_type.startswith("image/"):
65
- raise HTTPException(400, detail="File must be an image")
66
-
67
  try:
68
- # Read and process image
69
- contents = await file.read()
70
- image = Image.open(io.BytesIO(contents))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
71
  result = remove_bg(image)
72
 
73
- # Save to bytes
74
  img_byte_arr = io.BytesIO()
75
  result.save(img_byte_arr, format="PNG")
76
  img_byte_arr.seek(0)
77
 
78
  return StreamingResponse(
79
- img_byte_arr,
80
  media_type="image/png",
81
- headers={"Content-Disposition": "inline; filename=removed-bg.png"}
 
 
 
82
  )
83
  except Exception as e:
 
84
  raise HTTPException(500, detail=f"Processing failed: {str(e)}")
85
 
86
  if __name__ == "__main__":
 
1
+ # app.py - Fixed FastAPI for HF Spaces
2
  import torch
3
  import numpy as np
4
  from PIL import Image
5
  from safetensors.torch import load_file
6
  import io
 
7
 
8
+ from fastapi import FastAPI, File, UploadFile, Form, HTTPException, Request
9
  from fastapi.middleware.cors import CORSMiddleware
10
  from fastapi.responses import StreamingResponse
11
  import uvicorn
 
13
  from birefnet import BiRefNet
14
  from BiRefNet_config import BiRefNetConfig
15
 
16
+ # Global model
17
  device = "cpu"
18
  config = BiRefNetConfig()
19
  model = BiRefNet(config)
 
43
 
44
  app = FastAPI(title="BiRefNet Background Remover API")
45
 
46
+ # CORS - allow all for testing (restrict in production)
47
  app.add_middleware(
48
  CORSMiddleware,
49
+ allow_origins=["*"],
50
  allow_credentials=True,
51
  allow_methods=["*"],
52
  allow_headers=["*"],
 
54
 
55
  @app.get("/")
56
  async def root():
57
+ return {"message": "BiRefNet Background Remover API", "endpoints": ["/remove-bg"]}
58
 
59
+ # FIXED: Accept both UploadFile and raw bytes
60
  @app.post("/remove-bg")
61
+ async def remove_background(request: Request, file: UploadFile = File(None)):
 
 
 
 
 
62
  try:
63
+ # Handle different content types
64
+ if file is None:
65
+ # Fallback: read raw body if no file param
66
+ body = await request.body()
67
+ if not body:
68
+ raise HTTPException(400, detail="No image data received")
69
+ image = Image.open(io.BytesIO(body))
70
+ else:
71
+ contents = await file.read()
72
+ if not contents:
73
+ raise HTTPException(400, detail="Empty file")
74
+ image = Image.open(io.BytesIO(contents))
75
+
76
+ # Validate image
77
+ if not image.format or image.format not in ["JPEG", "PNG", "JPG"]:
78
+ raise HTTPException(400, detail="Invalid image format")
79
+
80
+ # Process
81
  result = remove_bg(image)
82
 
83
+ # Return PNG
84
  img_byte_arr = io.BytesIO()
85
  result.save(img_byte_arr, format="PNG")
86
  img_byte_arr.seek(0)
87
 
88
  return StreamingResponse(
89
+ img_byte_arr,
90
  media_type="image/png",
91
+ headers={
92
+ "Content-Disposition": "inline; filename=removed-bg.png",
93
+ "Cache-Control": "public, max-age=3600"
94
+ }
95
  )
96
  except Exception as e:
97
+ print(f"❌ Error: {str(e)}")
98
  raise HTTPException(500, detail=f"Processing failed: {str(e)}")
99
 
100
  if __name__ == "__main__":