Spaces:
Sleeping
Sleeping
import requests | |
from typing import Optional, Dict, Any | |
import os | |
import rembg | |
async def remove_background_from_url( | |
image_url: str, | |
output_path: str, | |
model_name: str = "u2net" | |
) -> Dict[str, Any]: | |
""" | |
Remove background from an image downloaded from a URL. | |
Args: | |
image_url: URL of the image to process | |
output_path: Path where to save the processed image | |
model_name: Background removal model to use | |
Returns: | |
Dictionary with result information | |
""" | |
try: | |
# Download image from URL | |
response = requests.get(image_url, timeout=30) | |
response.raise_for_status() | |
# Remove background | |
session = rembg.new_session(model_name=model_name) | |
output_data = rembg.remove(response.content, session=session) | |
# Save the result | |
with open(output_path, 'wb') as output_file: | |
output_file.write(output_data) | |
output_size = os.path.getsize(output_path) | |
return { | |
"success": True, | |
"message": f"Background removed from URL image using {model_name} model", | |
"source_url": image_url, | |
"output_path": output_path, | |
"output_size_bytes": output_size, | |
"model_used": model_name | |
} | |
except requests.RequestException as e: | |
return { | |
"success": False, | |
"error": f"Failed to download image: {str(e)}", | |
"output_path": None | |
} | |
except Exception as e: | |
return { | |
"success": False, | |
"error": f"Failed to process image: {str(e)}", | |
"output_path": None | |
} |