Spaces:
Sleeping

clearcut-api / app.py
BhavyaPatel07's picture
Update app.py
6189034 verified
Raw History Blame Contribute Delete
9.49 kB
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)