""" PixelAI Backend — Servidor Flask (API + Static Files) Funciona em: PC local (testes) e VPS Windows/Linux (produção) Arquitetura: - Cloudflare Pages → Frontend público (produção) - Este servidor → API de remoção de fundo + Frontend local (testes) - Supabase → Auth, banco de dados, storage """ from flask import Flask, request, jsonify, send_file, send_from_directory from flask_cors import CORS from rembg import remove from PIL import Image, ImageFilter from collections import deque import io import traceback import os import socket import threading import time import requests as http_requests import numpy as np # ══════════════════════════════════════════════════════ # CONFIGURAÇÃO DO APP # ══════════════════════════════════════════════════════ BASE_DIR = os.path.dirname(os.path.abspath(__file__)) PUBLIC_DIR = os.path.join(BASE_DIR, 'public') app = Flask(__name__, static_folder=PUBLIC_DIR, static_url_path='') # CORS aberto — permite chamadas do Cloudflare, localhost, qualquer domínio CORS(app, resources={r"/*": {"origins": "*"}}, allow_private_network=True) @app.after_request def allow_private_network_requests(response): origin = request.headers.get("Origin") if origin: response.headers["Access-Control-Allow-Origin"] = origin response.headers["Vary"] = "Origin" if request.headers.get("Access-Control-Request-Private-Network") == "true": response.headers["Access-Control-Allow-Private-Network"] = "true" allow_headers = request.headers.get("Access-Control-Request-Headers") if allow_headers: response.headers["Access-Control-Allow-Headers"] = allow_headers if request.method == "OPTIONS": response.headers["Access-Control-Allow-Methods"] = "DELETE, GET, HEAD, OPTIONS, PATCH, POST, PUT" return response # ── SUPABASE ADMIN (para criar usuários da Phantom sem confirmação de email) ── SUPABASE_URL = os.environ.get('SUPABASE_URL', 'https://hgtozyyrbcnnsjswwrbe.supabase.co') SUPABASE_SERVICE_ROLE_KEY = os.environ.get('SUPABASE_SERVICE_ROLE_KEY', '') # ══════════════════════════════════════════════════════ # MODELO DE IA (carregado uma vez, reutilizado sempre) # ══════════════════════════════════════════════════════ _sessions = {} _sessions_lock = threading.Lock() _warmup_started = False def get_model(model_name="bria-rmbg"): global _sessions if model_name in _sessions: return _sessions[model_name] with _sessions_lock: if model_name in _sessions: return _sessions[model_name] print(f"\n[+] Baixando modelo de IA '{model_name}' (~300MB, so na primeira vez)...") print(" Aguarde 1-2 minutos...\n") from rembg import new_session for attempt in range(3): try: _sessions[model_name] = new_session(model_name) print(f"[OK] Modelo '{model_name}' carregado! Pronto para processar imagens.\n") break except Exception as exc: error_text = str(exc).lower() transient = ( "broken pipe" in error_text or "connection broken" in error_text or "connection aborted" in error_text or "connection reset" in error_text or "timed out" in error_text ) if attempt < 2 and transient: wait_sec = 2 * (attempt + 1) print(f"[WARN] Falha de rede ao carregar '{model_name}'. Tentando novamente em {wait_sec}s...") time.sleep(wait_sec) continue raise return _sessions[model_name] def start_background_model_warmup(): global _warmup_started if _warmup_started: return _warmup_started = True def _warm(): try: get_model("bria-rmbg") except Exception as exc: print(f"[WARN] Warmup bria-rmbg falhou: {exc}") try: get_model("birefnet-general") except Exception as exc: print(f"[WARN] Warmup birefnet-general falhou: {exc}") threading.Thread(target=_warm, name="model-warmup", daemon=True).start() def resize_for_logo_model(img, min_size=1100, max_size=1600): w, h = img.size max_dim = max(w, h) scale = 1.0 if max_dim > max_size: scale = max_size / max_dim elif max_dim < min_size: scale = min(2.5, min_size / max_dim) if abs(scale - 1.0) < 0.01: return img new_size = ( max(1, int(round(w * scale))), max(1, int(round(h * scale))), ) return img.resize(new_size, Image.Resampling.LANCZOS) def build_border_contrast_mask(img): rgba = img.convert("RGBA") arr = np.asarray(rgba, dtype=np.uint8) h, w, _ = arr.shape border = max(1, min(h, w) // 25) border_pixels = np.concatenate([ arr[:border, :, :3].reshape(-1, 3), arr[-border:, :, :3].reshape(-1, 3), arr[:, :border, :3].reshape(-1, 3), arr[:, -border:, :3].reshape(-1, 3), ], axis=0).astype(np.float32) bg_rgb = np.median(border_pixels, axis=0) border_dist = np.linalg.norm(border_pixels - bg_rgb, axis=1) border_spread = float(np.mean(np.std(border_pixels, axis=0))) threshold = float(np.clip(np.percentile(border_dist, 95) + 12, 18, 72)) rgb = arr[:, :, :3].astype(np.float32) dist = np.linalg.norm(rgb - bg_rgb, axis=2) mask = np.where(dist > threshold, 255, 0).astype(np.uint8) alpha_channel = arr[:, :, 3] if np.any(alpha_channel < 250): mask = np.maximum(mask, alpha_channel) uniform_background = border_spread < 18 and np.percentile(border_dist, 95) < 16 return Image.fromarray(mask, mode="L"), uniform_background def get_edge_pixels(arr, border): return np.concatenate([ arr[:border, :, :3].reshape(-1, 3), arr[-border:, :, :3].reshape(-1, 3), arr[:, :border, :3].reshape(-1, 3), arr[:, -border:, :3].reshape(-1, 3), ], axis=0) def detect_checkerboard_colors(border_pixels): if border_pixels.size == 0: return None quantized = ((border_pixels.astype(np.uint16) + 4) // 8) * 8 unique_colors, counts = np.unique(quantized.astype(np.uint8), axis=0, return_counts=True) if len(unique_colors) < 2: return None total = counts.sum() ranked = np.argsort(counts)[::-1][:6] candidates = [] for idx in ranked: color = unique_colors[idx].astype(np.float32) share = counts[idx] / total channel_spread = float(color.max() - color.min()) brightness = float(color.mean()) if share < 0.06: continue if channel_spread > 28: continue if brightness < 40 or brightness > 250: continue candidates.append((color, share)) best_pair = None best_share = 0.0 for i in range(len(candidates)): for j in range(i + 1, len(candidates)): color_a, share_a = candidates[i] color_b, share_b = candidates[j] brightness_diff = abs(float(color_a.mean() - color_b.mean())) color_distance = float(np.linalg.norm(color_a - color_b)) combined_share = share_a + share_b if brightness_diff < 8 or brightness_diff > 70: continue if color_distance < 12: continue if combined_share < 0.34: continue if combined_share > best_share: best_share = combined_share best_pair = (color_a, color_b) return best_pair def flood_fill_candidate_mask(candidate_mask): h, w = candidate_mask.shape visited = np.zeros((h, w), dtype=bool) queue = deque() def add_seed(y, x): if candidate_mask[y, x] and not visited[y, x]: visited[y, x] = True queue.append((y, x)) for x in range(w): add_seed(0, x) add_seed(h - 1, x) for y in range(h): add_seed(y, 0) add_seed(y, w - 1) while queue: y, x = queue.popleft() if y > 0: add_seed(y - 1, x) if y + 1 < h: add_seed(y + 1, x) if x > 0: add_seed(y, x - 1) if x + 1 < w: add_seed(y, x + 1) return visited def rgb_to_hsv_channels(rgb_float): r = rgb_float[:, :, 0] g = rgb_float[:, :, 1] b = rgb_float[:, :, 2] cmax = np.max(rgb_float, axis=2) cmin = np.min(rgb_float, axis=2) delta = cmax - cmin hue = np.zeros_like(cmax) nz = delta > 1e-6 r_is_max = (cmax == r) & nz g_is_max = (cmax == g) & nz b_is_max = (cmax == b) & nz hue[r_is_max] = ((g[r_is_max] - b[r_is_max]) / delta[r_is_max]) % 6.0 hue[g_is_max] = ((b[g_is_max] - r[g_is_max]) / delta[g_is_max]) + 2.0 hue[b_is_max] = ((r[b_is_max] - g[b_is_max]) / delta[b_is_max]) + 4.0 hue *= 60.0 sat = np.zeros_like(cmax) has_value = cmax > 1e-6 sat[has_value] = delta[has_value] / cmax[has_value] val = cmax return hue, sat, val def build_checkerboard_foreground_mask(img): rgba = img.convert("RGBA") arr = np.asarray(rgba, dtype=np.uint8) h, w, _ = arr.shape border = max(1, min(h, w) // 20) border_pixels = get_edge_pixels(arr, border) checker_colors = detect_checkerboard_colors(border_pixels) if checker_colors is None: return None, False, None color_a, color_b = checker_colors rgb = arr[:, :, :3].astype(np.float32) dist_a = np.linalg.norm(rgb - color_a, axis=2) dist_b = np.linalg.norm(rgb - color_b, axis=2) bg_color_distance = float(np.linalg.norm(color_a - color_b)) tolerance = float(np.clip(bg_color_distance * 0.35, 9, 18)) candidate_mask = (dist_a <= tolerance) | (dist_b <= tolerance) connected_background = flood_fill_candidate_mask(candidate_mask) background_mask = candidate_mask | connected_background foreground_ratio = float(1.0 - (np.count_nonzero(background_mask) / background_mask.size)) if foreground_ratio < 0.01 or foreground_ratio > 0.95: return None, False, None mask = Image.fromarray(np.where(background_mask, 255, 0).astype(np.uint8), mode="L") mask = mask.filter(ImageFilter.GaussianBlur(0.6)) return mask, True, (color_a, color_b) def build_neutral_cleanup_mask(rgba_img, checker_colors): rgb_u8 = np.asarray(rgba_img.convert("RGB"), dtype=np.uint8) rgb = rgb_u8.astype(np.float32) / 255.0 hue, sat, val = rgb_to_hsv_channels(rgb) if checker_colors is None: neutral_like = (sat < 0.14) & (val > 0.42) else: color_a, color_b = checker_colors rgb_255 = rgb_u8.astype(np.float32) dist_a = np.linalg.norm(rgb_255 - color_a, axis=2) dist_b = np.linalg.norm(rgb_255 - color_b, axis=2) bg_distance = float(np.linalg.norm(color_a - color_b)) tol = float(np.clip(bg_distance * 0.42, 10, 26)) neutral_like = ((sat < 0.17) & ((dist_a <= tol) | (dist_b <= tol))) | ((sat < 0.10) & (val > 0.84)) gold_like = (hue >= 20.0) & (hue <= 80.0) & (sat > 0.14) & (val > 0.12) colored_like = sat > 0.26 preserve_seed = gold_like | colored_like preserve_img = Image.fromarray(np.where(preserve_seed, 255, 0).astype(np.uint8), mode="L") preserve_mask = np.asarray(preserve_img.filter(ImageFilter.MaxFilter(5)), dtype=np.uint8) > 0 cleanup = neutral_like & (~preserve_mask) cleanup_img = Image.fromarray(np.where(cleanup, 255, 0).astype(np.uint8), mode="L") cleanup_img = cleanup_img.filter(ImageFilter.GaussianBlur(0.8)) return cleanup_img def find_compact_neutral_blobs(cleanup_arr, preserve_arr): candidate = (cleanup_arr > 170) & (~preserve_arr) h, w = candidate.shape visited = np.zeros((h, w), dtype=bool) remove_mask = np.zeros((h, w), dtype=bool) min_area = max(140, int(candidate.size * 0.0016)) def maybe_enqueue(ny, nx, queue): if ny < 0 or ny >= h or nx < 0 or nx >= w: return if visited[ny, nx] or not candidate[ny, nx]: return visited[ny, nx] = True queue.append((ny, nx)) for y in range(h): for x in range(w): if visited[y, x] or not candidate[y, x]: continue queue = deque([(y, x)]) visited[y, x] = True component = [] area = 0 min_y, max_y = y, y min_x, max_x = x, x touches_border = False while queue: cy, cx = queue.popleft() component.append((cy, cx)) area += 1 if cy == 0 or cy == h - 1 or cx == 0 or cx == w - 1: touches_border = True if cy < min_y: min_y = cy if cy > max_y: max_y = cy if cx < min_x: min_x = cx if cx > max_x: max_x = cx maybe_enqueue(cy - 1, cx, queue) maybe_enqueue(cy + 1, cx, queue) maybe_enqueue(cy, cx - 1, queue) maybe_enqueue(cy, cx + 1, queue) bbox_h = max_y - min_y + 1 bbox_w = max_x - min_x + 1 bbox_area = max(1, bbox_h * bbox_w) fill_ratio = area / bbox_area aspect_ratio = bbox_w / max(1, bbox_h) compact_shape = 0.65 <= aspect_ratio <= 1.6 is_large_compact = area >= min_area and fill_ratio >= 0.42 and compact_shape if touches_border or is_large_compact: for py, px in component: remove_mask[py, px] = True return remove_mask def build_white_halo_mask(rgba_img, alpha_arr): rgb = np.asarray(rgba_img.convert("RGB"), dtype=np.uint8).astype(np.float32) / 255.0 hue, sat, val = rgb_to_hsv_channels(rgb) white_like = (sat < 0.24) & (val > 0.55) bright_white = (sat < 0.16) & (val > 0.72) yellow_like = (hue >= 18.0) & (hue <= 90.0) & (sat > 0.20) & (val > 0.16) dark_like = val < 0.26 # Only attack currently-opaque pixels that look like white spill. foreground_alpha = alpha_arr > 28 seed = foreground_alpha & (bright_white | (white_like & (~yellow_like) & (~dark_like))) seed_img = Image.fromarray(np.where(seed, 255, 0).astype(np.uint8), mode="L") seed_img = seed_img.filter(ImageFilter.MaxFilter(5)).filter(ImageFilter.GaussianBlur(1.1)) return np.array(seed_img, dtype=np.uint8) def build_logo_specialist_result(img, session): rgba = img.convert("RGBA") model_input = resize_for_logo_model(rgba) ai_mask = remove( model_input, session=session, only_mask=True, alpha_matting=False, post_process_mask=False, ).convert("L") if ai_mask.size != rgba.size: ai_mask = ai_mask.resize(rgba.size, Image.Resampling.LANCZOS) ai_mask = ai_mask.filter(ImageFilter.MaxFilter(3)) checker_mask, checker_detected, checker_colors = build_checkerboard_foreground_mask(model_input) if checker_detected and checker_mask.size != rgba.size: checker_mask = checker_mask.resize(rgba.size, Image.Resampling.LANCZOS) contrast_mask, uniform_background = build_border_contrast_mask(rgba) combined = np.array(ai_mask, dtype=np.uint8) if checker_detected and checker_mask is not None: checker_background = np.array(checker_mask, dtype=np.uint8) combined[checker_background > 140] = 0 print("[LOGO] Fundo quadriculado detectado e removido.") elif uniform_background: combined = np.maximum(combined, np.array(contrast_mask, dtype=np.uint8)) cleanup_mask = build_neutral_cleanup_mask(rgba, checker_colors if checker_detected else None) cleanup_arr = np.array(cleanup_mask, dtype=np.uint8) cleanup_large_arr = np.array( cleanup_mask.filter(ImageFilter.GaussianBlur(2.2)), dtype=np.uint8 ) rgb = np.asarray(rgba.convert("RGB"), dtype=np.uint8).astype(np.float32) / 255.0 hue, sat, val = rgb_to_hsv_channels(rgb) gold_like = (hue >= 18.0) & (hue <= 90.0) & (sat > 0.10) & (val > 0.08) colored_like = sat > 0.24 mask_edge_img = Image.fromarray(combined, mode="L").filter(ImageFilter.FIND_EDGES).filter(ImageFilter.MaxFilter(5)) edge_preserve = np.array(mask_edge_img, dtype=np.uint8) > 10 preserve_seed = gold_like | colored_like | edge_preserve preserve_img = Image.fromarray(np.where(preserve_seed, 255, 0).astype(np.uint8), mode="L") preserve_arr = np.array(preserve_img.filter(ImageFilter.MaxFilter(5)), dtype=np.uint8) > 0 compact_neutral_blobs = find_compact_neutral_blobs(cleanup_arr, preserve_arr) if checker_detected: cleanup_pixels = (((cleanup_arr > 148) | (cleanup_large_arr > 160)) & (~preserve_arr)) | compact_neutral_blobs combined[cleanup_pixels] = 0 print("[LOGO] Limpeza de fundo neutro aplicada para logos/textos.") elif uniform_background: cleanup_pixels = (((cleanup_arr > 220) | (cleanup_large_arr > 236)) & (~preserve_arr) & (combined < 195)) | compact_neutral_blobs combined[cleanup_pixels] = 0 else: cleanup_pixels = (((cleanup_arr > 190) | (cleanup_large_arr > 205)) & (~preserve_arr) & (combined < 225)) | compact_neutral_blobs combined[cleanup_pixels] = 0 halo_mask = build_white_halo_mask(rgba, combined) strong_halo = halo_mask > (118 if checker_detected else 168) combined[strong_halo] = 0 soft_halo = (halo_mask > 92) & (combined > 0) & (combined < 240) combined[soft_halo] = np.minimum(combined[soft_halo], 28) original_alpha = np.array(rgba.getchannel("A"), dtype=np.uint8) if np.any(original_alpha < 250): combined = np.minimum(combined, original_alpha) combined_mask = Image.fromarray(combined, mode="L") if checker_detected or uniform_background: combined_mask = combined_mask.filter(ImageFilter.MaxFilter(3)) combined_mask = combined_mask.filter(ImageFilter.GaussianBlur(0.6)) result = rgba.copy() result.putalpha(combined_mask) return result # ══════════════════════════════════════════════════════ # ROTAS — API (backend) # ══════════════════════════════════════════════════════ @app.route('/api/health', methods=['GET']) def health(): """Health check — útil para monitorar se o servidor está online""" return jsonify({"status": "online", "service": "pixelai-rembg"}), 200 @app.route('/api/remove-background', methods=['POST', 'OPTIONS']) def remove_background(): """Remove o fundo de uma imagem usando IA (rembg)""" if request.method == 'OPTIONS': return '', 204 try: # Validação de input if 'image_file' not in request.files: return jsonify({"error": "Campo 'image_file' obrigatório"}), 400 file = request.files['image_file'] if not file or file.filename == '': return jsonify({"error": "Arquivo vazio"}), 400 # Abre e valida a imagem img = Image.open(file.stream).convert("RGBA") w, h = img.size if w < 10 or h < 10: return jsonify({"error": "Imagem muito pequena (mín 10x10px)"}), 400 if w * h > 50_000_000: return jsonify({"error": "Imagem muito grande (máx 50MP)"}), 400 print(f"[IMG] Processando: {file.filename} ({w}x{h}px)") # Processa com IA req_model = request.form.get('model', 'birefnet-general') if req_model == 'birefnet-general': model_name = 'birefnet-general' use_advanced_matting = False elif req_model == 'logo-specialist': model_name = 'birefnet-general' use_advanced_matting = True elif req_model == 'bria-rmbg': model_name = 'bria-rmbg' use_advanced_matting = False else: model_name = 'isnet-general-use' use_advanced_matting = False session = get_model(model_name) if use_advanced_matting: result = build_logo_specialist_result(img, session) else: result = remove(img, session=session, alpha_matting=False, post_process_mask=True) if False: # Algoritmo especial para Logos: Alpha Matting seguro com redimensionamento orig_w, orig_h = img.size MAX_SIZE = 1200 # Tamanho seguro para PyMatting não dar erro 500 (OOM) if orig_w > MAX_SIZE or orig_h > MAX_SIZE: ratio = min(MAX_SIZE/orig_w, MAX_SIZE/orig_h) new_w, new_h = int(orig_w * ratio), int(orig_h * ratio) small_img = img.resize((new_w, new_h), Image.Resampling.LANCZOS) mask = remove(small_img, session=session, only_mask=True, alpha_matting=True, alpha_matting_foreground_threshold=240, alpha_matting_background_threshold=10, alpha_matting_erode_size=5) mask = mask.resize((orig_w, orig_h), Image.Resampling.LANCZOS) else: mask = remove(img, session=session, only_mask=True, alpha_matting=True, alpha_matting_foreground_threshold=240, alpha_matting_background_threshold=10, alpha_matting_erode_size=5) result = img.convert("RGBA") result.putalpha(mask) # Retorna PNG sem fundo buf = io.BytesIO() result.save(buf, format='PNG') buf.seek(0) print(f"[OK] Concluido: {file.filename}") return send_file(buf, mimetype='image/png', as_attachment=True, download_name='sem-fundo.png') except Exception as e: print(f"[ERRO] {e}") traceback.print_exc() return jsonify({"error": str(e)}), 500 # Mantém compatibilidade com o endpoint antigo (sem /api/) @app.route('/remove-background', methods=['POST', 'OPTIONS']) def remove_background_legacy(): return remove_background() # ══════════════════════════════════════════════════════ # ROTA — PHANTOM WALLET AUTH (cria usuário sem confirmação de email) # ══════════════════════════════════════════════════════ @app.route('/api/phantom-auth', methods=['POST', 'OPTIONS']) def phantom_auth(): """Cria/autentica um usuário Phantom Wallet via Supabase Admin API""" if request.method == 'OPTIONS': return '', 204 try: if not SUPABASE_SERVICE_ROLE_KEY: return jsonify({"error": "SUPABASE_SERVICE_ROLE_KEY nao configurada no backend."}), 500 data = request.get_json() if not data or 'wallet_address' not in data: return jsonify({"error": "wallet_address obrigatório"}), 400 wallet = data['wallet_address'] email = f"{wallet.lower()}@phantom.pixelai" password = f"pk_{wallet}" headers = { 'apikey': SUPABASE_SERVICE_ROLE_KEY, 'Authorization': f'Bearer {SUPABASE_SERVICE_ROLE_KEY}', 'Content-Type': 'application/json' } # 1) Tenta buscar o usuário existente por email list_resp = http_requests.get( f"{SUPABASE_URL}/auth/v1/admin/users", headers=headers, timeout=10 ) existing_user = None if list_resp.ok: users_data = list_resp.json() users_list = users_data.get('users', users_data) if isinstance(users_data, dict) else users_data if isinstance(users_list, list): for u in users_list: if u.get('email') == email: existing_user = u break if not existing_user: # 2) Cria novo usuário com email já confirmado create_resp = http_requests.post( f"{SUPABASE_URL}/auth/v1/admin/users", headers=headers, json={ "email": email, "password": password, "email_confirm": True, "user_metadata": {"wallet": wallet, "provider": "phantom"} }, timeout=10 ) if not create_resp.ok: err = create_resp.json() if create_resp.headers.get("content-type", "").startswith("application/json") else {"raw": create_resp.text} err_text = str(err).lower() already_exists = create_resp.status_code in (409, 422) and ( "already" in err_text or "exists" in err_text or "registered" in err_text or "duplicate" in err_text ) # Se já existe (409), tudo ok if not already_exists: return jsonify({"error": f"Erro ao criar usuário: {err}"}), 500 else: # 2.5) Garante que usuários antigos que ficaram travados sem confirmação sejam confirmados if not existing_user.get('email_confirmed_at'): user_id = existing_user.get('id') http_requests.put( f"{SUPABASE_URL}/auth/v1/admin/users/{user_id}", headers=headers, json={"email_confirm": True}, timeout=10 ) # 3) Retorna as credenciais para o frontend fazer signInWithPassword return jsonify({ "email": email, "password": password, "status": "ok" }), 200 except Exception as e: print(f"[ERRO] Phantom auth error: {e}") traceback.print_exc() return jsonify({"error": str(e)}), 500 # ══════════════════════════════════════════════════════ # INICIALIZAÇÃO # ══════════════════════════════════════════════════════ def _get_local_ip(): try: s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(("8.8.8.8", 80)) ip = s.getsockname()[0] s.close() return ip except Exception: return "127.0.0.1" # ══════════════════════════════════════════════════════ # ROTAS — FRONTEND (serve o site localmente) # ══════════════════════════════════════════════════════ @app.route('/') def serve_index(): response = send_from_directory(PUBLIC_DIR, 'index.html', max_age=0) response.headers['Cache-Control'] = 'no-store, no-cache, must-revalidate, max-age=0' response.headers['Pragma'] = 'no-cache' response.headers['Expires'] = '0' return response @app.route('/') def serve_static(path): response = send_from_directory(PUBLIC_DIR, path, max_age=0) if path.endswith(('.html', '.js', '.css', '.json')): response.headers['Cache-Control'] = 'no-store, no-cache, must-revalidate, max-age=0' response.headers['Pragma'] = 'no-cache' response.headers['Expires'] = '0' return response # Warmup assíncrono também em runtime do Gunicorn (import de módulo). if os.environ.get("PIXELAI_WARMUP_MODELS", "1") == "1": start_background_model_warmup() if __name__ == '__main__': port = int(os.environ.get('PORT', 5000)) ip = _get_local_ip() print() print("=" * 55) print(" PixelAI Studio - Servidor Completo") print("=" * 55) print() print(f" Local: http://localhost:{port}") print(f" Rede/VPS: http://{ip}:{port}") print(f" Health: GET /api/health") print(f" Remover BG: POST /api/remove-background") print(f" Phantom: POST /api/phantom-auth") print() print(" O site do Netlify chama este servidor.") print(" Na VPS, libere a porta 5000 no firewall.") print(" Ctrl+C para parar.") print() print("=" * 55) # Pre-carrega o modelo principal ao iniciar get_model('bria-rmbg') app.run(host='0.0.0.0', port=port, debug=False, threaded=True)