Spaces:
Sleeping
Sleeping
Upload app.py
Browse filesfix api error fix
app.py
CHANGED
|
@@ -1,18 +1,14 @@
|
|
| 1 |
"""
|
| 2 |
Background Removal API using rembg
|
| 3 |
Optimized for Hugging Face Spaces with GPU support
|
| 4 |
-
|
| 5 |
-
Provides both Gradio UI and FastAPI endpoint for direct HTTP access
|
| 6 |
"""
|
| 7 |
|
| 8 |
import gradio as gr
|
| 9 |
-
from fastapi import FastAPI, File, UploadFile, HTTPException
|
| 10 |
-
from fastapi.responses import Response
|
| 11 |
from rembg import remove, new_session
|
| 12 |
from PIL import Image
|
| 13 |
import io
|
| 14 |
import time
|
| 15 |
-
import uvicorn
|
| 16 |
|
| 17 |
def create_rembg_session():
|
| 18 |
"""Create rembg session with GPU fallback to CPU if CUDA libraries are missing."""
|
|
@@ -21,17 +17,20 @@ def create_rembg_session():
|
|
| 21 |
try:
|
| 22 |
session = new_session(model_name="u2net")
|
| 23 |
load_time = time.time() - start_time
|
| 24 |
-
print(f"✅ rembg model loaded in {load_time:.2f}s (
|
| 25 |
return session
|
| 26 |
except Exception as e:
|
| 27 |
print(f"⚠️ GPU session failed, falling back to CPU: {e}")
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
|
|
|
|
|
|
|
|
|
| 35 |
rembg_session = create_rembg_session()
|
| 36 |
|
| 37 |
def remove_background(image):
|
|
@@ -44,6 +43,9 @@ def remove_background(image):
|
|
| 44 |
Returns:
|
| 45 |
PIL Image with transparent background
|
| 46 |
"""
|
|
|
|
|
|
|
|
|
|
| 47 |
print(f"📥 Received image: {image.size}, mode: {image.mode}")
|
| 48 |
|
| 49 |
try:
|
|
@@ -68,7 +70,7 @@ def remove_background(image):
|
|
| 68 |
|
| 69 |
except Exception as e:
|
| 70 |
print(f"❌ Error: {e}")
|
| 71 |
-
raise e
|
| 72 |
|
| 73 |
# Create Gradio Interface
|
| 74 |
demo = gr.Interface(
|
|
@@ -80,77 +82,25 @@ demo = gr.Interface(
|
|
| 80 |
Fast background removal using rembg (u2net model).
|
| 81 |
|
| 82 |
**Features:**
|
| 83 |
-
- GPU-accelerated processing (
|
| 84 |
- Session reuse for faster processing
|
| 85 |
-
-
|
| 86 |
|
| 87 |
-
**API Usage:**
|
| 88 |
-
```
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
|
|
|
| 92 |
```
|
| 93 |
""",
|
| 94 |
examples=[],
|
| 95 |
-
|
| 96 |
-
api_visibility="public",
|
| 97 |
-
api_name="remove_background"
|
| 98 |
-
)
|
| 99 |
-
|
| 100 |
-
# Mount Gradio app to FastAPI
|
| 101 |
-
fastapi_app = FastAPI()
|
| 102 |
-
app = gr.mount_gradio_app(
|
| 103 |
-
fastapi_app,
|
| 104 |
-
demo,
|
| 105 |
-
path="/",
|
| 106 |
-
footer_links=["api", "gradio", "settings"]
|
| 107 |
)
|
| 108 |
|
| 109 |
-
# Add custom FastAPI endpoint for direct HTTP access
|
| 110 |
-
@app.post("/remove-bg")
|
| 111 |
-
async def remove_bg_endpoint(file: UploadFile = File(...)):
|
| 112 |
-
"""
|
| 113 |
-
Direct HTTP endpoint for background removal
|
| 114 |
-
Returns PNG image with transparent background
|
| 115 |
-
"""
|
| 116 |
-
try:
|
| 117 |
-
# Read uploaded file
|
| 118 |
-
contents = await file.read()
|
| 119 |
-
input_image = Image.open(io.BytesIO(contents))
|
| 120 |
-
|
| 121 |
-
# Process with rembg
|
| 122 |
-
output_image = remove_background(input_image)
|
| 123 |
-
|
| 124 |
-
# Convert to bytes
|
| 125 |
-
img_byte_arr = io.BytesIO()
|
| 126 |
-
output_image.save(img_byte_arr, format='PNG')
|
| 127 |
-
img_byte_arr.seek(0)
|
| 128 |
-
|
| 129 |
-
# Return as PNG
|
| 130 |
-
return Response(
|
| 131 |
-
content=img_byte_arr.getvalue(),
|
| 132 |
-
media_type="image/png",
|
| 133 |
-
headers={
|
| 134 |
-
"Content-Disposition": f"attachment; filename=removed_bg.png"
|
| 135 |
-
}
|
| 136 |
-
)
|
| 137 |
-
|
| 138 |
-
except Exception as e:
|
| 139 |
-
raise HTTPException(status_code=500, detail=str(e))
|
| 140 |
-
|
| 141 |
-
@app.get("/health")
|
| 142 |
-
async def health_check():
|
| 143 |
-
"""Health check endpoint"""
|
| 144 |
-
return {
|
| 145 |
-
"status": "healthy",
|
| 146 |
-
"model": "rembg u2net",
|
| 147 |
-
"session_loaded": rembg_session is not None
|
| 148 |
-
}
|
| 149 |
-
|
| 150 |
if __name__ == "__main__":
|
| 151 |
-
# Launch Gradio with custom app
|
| 152 |
demo.launch(
|
| 153 |
server_name="0.0.0.0",
|
| 154 |
server_port=7860,
|
| 155 |
-
|
| 156 |
)
|
|
|
|
| 1 |
"""
|
| 2 |
Background Removal API using rembg
|
| 3 |
Optimized for Hugging Face Spaces with GPU support
|
| 4 |
+
Simple Gradio-only implementation
|
|
|
|
| 5 |
"""
|
| 6 |
|
| 7 |
import gradio as gr
|
|
|
|
|
|
|
| 8 |
from rembg import remove, new_session
|
| 9 |
from PIL import Image
|
| 10 |
import io
|
| 11 |
import time
|
|
|
|
| 12 |
|
| 13 |
def create_rembg_session():
|
| 14 |
"""Create rembg session with GPU fallback to CPU if CUDA libraries are missing."""
|
|
|
|
| 17 |
try:
|
| 18 |
session = new_session(model_name="u2net")
|
| 19 |
load_time = time.time() - start_time
|
| 20 |
+
print(f"✅ rembg model loaded in {load_time:.2f}s (GPU)")
|
| 21 |
return session
|
| 22 |
except Exception as e:
|
| 23 |
print(f"⚠️ GPU session failed, falling back to CPU: {e}")
|
| 24 |
+
try:
|
| 25 |
+
session = new_session(model_name="u2net", providers=["CPUExecutionProvider"])
|
| 26 |
+
load_time = time.time() - start_time
|
| 27 |
+
print(f"✅ rembg model loaded in {load_time:.2f}s (CPU)")
|
| 28 |
+
return session
|
| 29 |
+
except Exception as e2:
|
| 30 |
+
print(f"❌ Failed to load rembg: {e2}")
|
| 31 |
+
raise
|
| 32 |
+
|
| 33 |
+
# Global session for model reuse
|
| 34 |
rembg_session = create_rembg_session()
|
| 35 |
|
| 36 |
def remove_background(image):
|
|
|
|
| 43 |
Returns:
|
| 44 |
PIL Image with transparent background
|
| 45 |
"""
|
| 46 |
+
if image is None:
|
| 47 |
+
return None
|
| 48 |
+
|
| 49 |
print(f"📥 Received image: {image.size}, mode: {image.mode}")
|
| 50 |
|
| 51 |
try:
|
|
|
|
| 70 |
|
| 71 |
except Exception as e:
|
| 72 |
print(f"❌ Error: {e}")
|
| 73 |
+
raise gr.Error(f"Background removal failed: {str(e)}")
|
| 74 |
|
| 75 |
# Create Gradio Interface
|
| 76 |
demo = gr.Interface(
|
|
|
|
| 82 |
Fast background removal using rembg (u2net model).
|
| 83 |
|
| 84 |
**Features:**
|
| 85 |
+
- GPU-accelerated processing (when available)
|
| 86 |
- Session reuse for faster processing
|
| 87 |
+
- API access via gradio_client
|
| 88 |
|
| 89 |
+
**Python API Usage:**
|
| 90 |
+
```python
|
| 91 |
+
from gradio_client import Client
|
| 92 |
+
|
| 93 |
+
client = Client("https://tigger13-background-removal.hf.space")
|
| 94 |
+
result = client.predict("/path/to/image.png")
|
| 95 |
```
|
| 96 |
""",
|
| 97 |
examples=[],
|
| 98 |
+
allow_flagging="never"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 99 |
)
|
| 100 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 101 |
if __name__ == "__main__":
|
|
|
|
| 102 |
demo.launch(
|
| 103 |
server_name="0.0.0.0",
|
| 104 |
server_port=7860,
|
| 105 |
+
show_error=True # Enable error reporting
|
| 106 |
)
|