sameerbanchhor's picture
Upload folder using huggingface_hub
a55cbbf verified
from fastapi import APIRouter, UploadFile, File, Depends, HTTPException
from fastapi.responses import Response
from rembg import remove
from PIL import Image
import io
# Import the auth dependency from your existing system
from app.routers.auth.system import get_current_user
router = APIRouter(
prefix="/image",
tags=["Image Processing"]
)
# ==========================================
# πŸ” Auth Toggle
# ==========================================
AUTH_ENABLED = False # <<< set False to disable authentication
# Logic to conditionally apply authentication
# If True, the endpoint will require a valid token.
# If False, the dependency list is empty.
security_dependencies = [Depends(get_current_user)] if AUTH_ENABLED else []
@router.post("/remove-bg", dependencies=security_dependencies)
async def remove_background(file: UploadFile = File(...)):
"""
Upload an image and receive it back with the background removed (PNG).
"""
# 1. Validate file type
if not file.content_type.startswith("image/"):
raise HTTPException(status_code=400, detail="Invalid file type. Please upload an image.")
try:
# 2. Read image data
image_data = await file.read()
# 3. Process image using rembg
# We pass the raw bytes to remove() and it returns bytes (PNG)
output_data = remove(image_data)
# 4. Return the result as a raw image response
return Response(content=output_data, media_type="image/png")
except Exception as e:
raise HTTPException(status_code=500, detail=f"Image processing failed: {str(e)}")