Spaces:
Sleeping

File size: 9,492 Bytes
8ad4db9
 
 
 
 
 
 
 
 
3682bd7
8ad4db9
 
 
 
 
 
 
 
 
 
 
 
 
d29fc98
8ad4db9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3682bd7
 
 
 
 
d29fc98
3682bd7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d29fc98
8ad4db9
3682bd7
 
 
 
8ad4db9
 
 
 
3682bd7
 
 
 
 
8ad4db9
 
 
 
 
 
 
 
3682bd7
 
 
 
 
 
 
 
 
 
8ad4db9
 
 
 
 
 
 
 
 
 
3682bd7
 
 
8ad4db9
 
 
 
 
 
3682bd7
8ad4db9
 
 
3682bd7
 
 
 
 
 
5f8cb08
 
3682bd7
 
 
 
 
5f8cb08
 
8ad4db9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d29fc98
 
8ad4db9
9254159
d29fc98
6189034
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
import io
import os
import gc
import time
from typing import Any, Optional

# pyrefly: ignore [missing-import, untyped-import]
import onnxruntime as ort
# pyrefly: ignore [missing-import, untyped-import]
from scipy.ndimage import label
# pyrefly: ignore [missing-import, untyped-import]
from flask import Flask, request, jsonify, send_file
# pyrefly: ignore [missing-import, untyped-import]
from flask_cors import CORS
# pyrefly: ignore [missing-import, untyped-import]
from rembg import remove, new_session

# pyrefly: ignore [missing-import, untyped-import]
from PIL import Image, ImageFilter

# pyrefly: ignore [missing-import, untyped-import]
import numpy as np

# ONNX Runtime automatically manages threads to utilize all available CPU cores on local machines.

app = Flask(__name__, static_folder='.', static_url_path='')
CORS(app)

@app.route('/')
def index() -> Any:
    return send_file('index.html')

# ── LAZY-LOADED SESSION CACHE (MEMORY OPTIMIZED) ────────────────
active_session: Any = None
active_model_name: Optional[str] = None

def get_session(model_name: str) -> Any:
    """
    Load and cache the active ONNX session, freeing the old session's memory
    if the model changes to prevent Out Of Memory (OOM) errors.
    """
    global active_session, active_model_name
    if active_model_name != model_name:
        print(f"Clearing old session and loading model session for '{model_name}'...")
        active_session = None  # Dereference old session
        gc.collect()  # Force garbage collection to free RAM

        active_session = new_session(model_name)
        active_model_name = model_name
        print(f"Model '{model_name}' loaded successfully!")
    return active_session


MODEL_SIZES = {
    'silueta': 320,
    'u2netp': 320,
    'u2net': 320,
    'isnet-general-use': 1024,
    'birefnet-general-lite': 768,
    'birefnet-general': 1024,
}

def fill_small_holes(mask_np: np.ndarray, max_hole_size: int = 500) -> np.ndarray:
    """
    Fill only internal holes in the binary mask that are smaller than or equal to `max_hole_size` pixels.
    This preserves larger background gaps (e.g. between fingers or arm-body loops).
    """
    mask_bin = mask_np > 127
    background_mask = ~mask_bin
    labeled_bg, num_features = label(background_mask)
    if num_features == 0:
        return mask_np
        
    border_pixels = np.concatenate([
        labeled_bg[0, :],        # top border
        labeled_bg[-1, :],       # bottom border
        labeled_bg[:, 0],        # left border
        labeled_bg[:, -1]        # right border
    ])
    border_labels = set(border_pixels)
    
    for i in range(1, num_features + 1):
        if i not in border_labels:
            hole_area = np.sum(labeled_bg == i)
            if hole_area <= max_hole_size:
                mask_np[labeled_bg == i] = 255
                
    return mask_np

def process_remove(input_image: Image.Image, model_name: str = 'birefnet-general-lite', fill_holes: bool = False, alpha_matting: bool = False) -> Image.Image:
    """
    High-accuracy background removal.
    - Optimized resolution downscaling matches the model's native input size for fast CPU inference.
    - Connected-component-based hole-filling preserves hand/arm gaps while clearing noise.
    - Smoothing is applied to the small mask to optimize speed.
    """
    t_start = time.perf_counter()
    original_size = input_image.size
    rembg_model = model_name
    
    # ── 1. DOWNSCALE FOR FAST INFERENCE (TO MODEL NATIVE RESOLUTION) ──
    target_size = MODEL_SIZES.get(rembg_model, 1024)
    max_dim = max(original_size)
    
    if input_image.mode == 'RGBA':
        processing_image = Image.new('RGB', input_image.size, (255, 255, 255))
        processing_image.paste(input_image, mask=input_image.split()[3])
    elif input_image.mode != 'RGB':
        processing_image = input_image.convert('RGB')
    else:
        processing_image = input_image

    if max_dim > target_size:
        scale_factor = target_size / max_dim
        new_size = (int(original_size[0] * scale_factor), int(original_size[1] * scale_factor))
        processing_image = processing_image.resize(new_size, Image.Resampling.BILINEAR)

    # ── 2. BACKGROUND REMOVAL (GET MASK) ────────────────────────────
    t_model_start = time.perf_counter()
    print(f"[process_remove] Using model='{rembg_model}', processing size={processing_image.size}, original={original_size}")
    session = get_session(rembg_model)
    
    if alpha_matting:
        output = remove(
            processing_image,
            session=session,
            post_process_mask=False,
            alpha_matting=True,
            alpha_matting_foreground_threshold=240,
            alpha_matting_background_threshold=10,
            alpha_matting_erode_size=10
        )
        if output.size != original_size:
            output = output.resize(original_size, Image.Resampling.BILINEAR)
        print(f"[timing] Total processing (alpha_matting): {time.perf_counter() - t_start:.2f}s")
        return output

    result_img = remove(processing_image, session=session, post_process_mask=False)
    mask = result_img.split()[-1]
    print(f"[timing] Model inference: {time.perf_counter() - t_model_start:.2f}s")

    # ── 3. CLEAN UP MASK EDGES (ON SMALL MASK FOR SPEED) ────────────
    mask_np = np.array(mask)
    mask_np[mask_np < 10] = 0
    mask_np[mask_np > 245] = 255

    # ── 4. SMART HOLE FILLING (ON SMALL MASK) ────────────────────────
    if fill_holes:
        max_hole_size = 500 if target_size >= 1024 else 50
        mask_np = fill_small_holes(mask_np, max_hole_size=max_hole_size)

    mask = Image.fromarray(mask_np)

    # ── 5. GENTLE EDGE SMOOTHING (ON SMALL MASK FOR SPEED) ──────────
    blur_radius = 1.0 if target_size >= 1024 else 0.5
    mask = mask.filter(ImageFilter.GaussianBlur(radius=blur_radius))

    # ── 6. RESIZE MASK TO ORIGINAL RESOLUTION ──────────────────────
    if mask.size != original_size:
        mask = mask.resize(original_size, Image.Resampling.BILINEAR)

    # ── 7. APPLY MASK TO ORIGINAL IMAGE ─────────────────────────────
    output = input_image.convert('RGBA') if input_image.mode != 'RGBA' else input_image.copy()
    output.putalpha(mask)

    print(f"[timing] Total processing: {time.perf_counter() - t_start:.2f}s")
    return output


@app.route('/remove-bg', methods=['POST'])
def remove_background() -> Any:
    if 'image_file' not in request.files:
        return jsonify({'error': 'No image file provided.'}), 400

    file = request.files['image_file']
    if file.filename == '':
        return jsonify({'error': 'No file selected.'}), 400

    try:
        # ── 1. LOAD & PREPROCESS ──────────────────────────────────
        input_image = Image.open(io.BytesIO(file.read()))

        # Normalize to RGB or RGBA
        if input_image.mode not in ('RGB', 'RGBA'):
            input_image = input_image.convert('RGB')

        # ── 2. BACKGROUND REMOVAL ──────────────────────────────────
        model_name = request.form.get('model', 'birefnet-general-lite')
        fill_holes_val = request.form.get('fill_holes', 'false').lower() in ('true', '1', 'yes')
        alpha_matting_val = request.form.get('alpha_matting', 'false').lower() in ('true', '1', 'yes')
        output_image = process_remove(input_image, model_name, fill_holes=fill_holes_val, alpha_matting=alpha_matting_val)

        # ── 3. ENCODE & RESPOND ───────────────────────────────────
        t_enc = time.perf_counter()
        output_buffer = io.BytesIO()
        # compress_level=1: fastest PNG encoding, identical pixel output
        output_image.save(output_buffer, format='PNG', compress_level=1)
        output_buffer.seek(0)
        print(f"[timing] PNG encode: {time.perf_counter() - t_enc:.2f}s")

        return send_file(output_buffer, mimetype='image/png', as_attachment=False)

    except Exception as e:
        app.logger.error(f"Background removal failed: {str(e)}")
        return jsonify({'error': f'Processing failed: {str(e)}'}), 500


if __name__ == '__main__':
    import socket
    def get_local_ip() -> str:
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        try:
            # doesn't need to be reachable
            s.connect(('10.255.255.255', 1))
            IP = s.getsockname()[0]
        except Exception:
            IP = '127.0.0.1'
        finally:
            s.close()
        return IP

    print("\n" + "="*50)
    print("ClearCut AI Background Remover Local Server")
    print("="*50)
    local_ip = get_local_ip()
    print(f"Local URL (this PC):  http://localhost:5000")
    print(f"Mobile URL (phone):   http://{local_ip}:5000")
    print("(Note: Both devices must be on the same Wi-Fi network)")
    print("="*50)
    print("Pre-loading BiRefNet model for faster first request...")
    get_session('birefnet-general-lite')
    print("Ready!\n")
    
    app.run(host='0.0.0.0', port=5000, debug=False, threaded=True)