File size: 29,405 Bytes
e2ca502
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
"""
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('/<path:path>')
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)