File size: 1,702 Bytes
2ccc1a1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
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
        }