Merlimhhs commited on
Commit
cf63ce6
·
verified ·
1 Parent(s): 18ab8dc

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +89 -62
app.py CHANGED
@@ -2,89 +2,116 @@ import gradio as gr
2
  import torch
3
  import numpy as np
4
  import cv2
5
- from PIL import Image, ImageFilter, ImageOps
6
  from transformers import pipeline
7
  from pathlib import Path
8
  import zipfile
9
  import shutil
10
- import rembg
11
- import os
12
 
13
- print(" ALVORE TURBO-INPAINT ENGINE STARTING...")
14
 
15
- device = "cpu" # HF Grátis = CPU
16
 
17
- # 1. Depth Anything V2 (Mantido o modelo que você quer para máxima qualidade)
18
- print("Carregando Depth-Anything-V2-Base...")
19
- depth_pipe = pipeline(
20
  task="depth-estimation",
21
  model="depth-anything/Depth-Anything-V2-Base-hf",
22
- device=-1
23
  )
24
 
25
- # 2. Sessão Rembg (Alta Qualidade)
26
- session = rembg.new_session(model_name="u2net")
27
-
28
  def normalize_depth(depth):
29
  d = np.array(depth).astype(np.float32)
30
  d = (d - d.min()) / (d.max() - d.min() + 1e-6)
31
  return d
32
 
33
- def process_batch(files):
34
- if not files: return None
35
- out_dir = Path("alvore_turbo_out")
36
- if out_dir.exists(): shutil.rmtree(out_dir)
37
- out_dir.mkdir()
38
- zip_path = "LOTE_ALVORE_TURBO.zip"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
 
40
  with zipfile.ZipFile(zip_path, 'w') as zipf:
41
- for i, file in enumerate(files):
42
- name = Path(file.name).stem
43
- print(f"📦 [{i+1}/{len(files)}] {name}")
44
-
45
- # Carregar Imagem
46
- img_orig = Image.open(file.name).convert("RGB")
47
- img_cv = cv2.cvtColor(np.array(img_orig), cv2.COLOR_RGB2BGR)
48
-
49
- # 1. FG - REMBG (Qualidade Máxima)
50
- fg_rgba = rembg.remove(img_orig, session=session)
51
- fg_path = out_dir / f"{name}_FG.png"
52
- fg_rgba.save(fg_path)
53
- zipf.write(fg_path, fg_path.name)
54
-
55
- # 2. BG - INPAINT MATEMÁTICO (Instantâneo)
56
- # Extrair máscara do FG e dilatar
57
- mask_alpha = np.array(fg_rgba.getchannel('A'))
58
- kernel = np.ones((15,15), np.uint8)
59
- mask_cv = cv2.dilate(mask_alpha, kernel, iterations=1)
60
-
61
- # O "Mágica": Inpaint via OpenCV (Método Telea)
62
- # Leva milisegundos e limpa o personagem para o fundo
63
- bg_cv = cv2.inpaint(img_cv, mask_cv, 3, cv2.INPAINT_TELEA)
64
- bg_res = Image.fromarray(cv2.cvtColor(bg_cv, cv2.COLOR_BGR2RGB))
65
-
66
- bg_path = out_dir / f"{name}_BG.png"
67
- bg_res.save(bg_path)
68
- zipf.write(bg_path, bg_path.name)
69
-
70
- # 3. DEPTH (Qualidade Máxima no Fundo Limpo)
71
- depth_raw = depth_pipe(bg_res)["depth"]
72
- d_np = normalize_depth(depth_raw)
73
- depth_map = Image.fromarray((d_np * 255).astype(np.uint8))
74
- depth_map = depth_map.filter(ImageFilter.GaussianBlur(0.6))
75
-
76
- depth_path = out_dir / f"{name}_DEPTH.png"
77
- depth_map.save(depth_path)
78
  zipf.write(depth_path, depth_path.name)
79
 
 
80
  return zip_path
81
 
82
- with gr.Blocks(theme=gr.themes.Soft()) as demo:
83
- gr.Markdown("# ⚡ ALVORE TURBO-BATCH (No-Wait Inpaint)")
84
- gr.Markdown("Rembg e Depth em Alta Qualidade + Inpaint Matemático Instantâneo.")
85
- inp = gr.File(file_count="multiple")
 
 
 
 
 
86
  out = gr.File()
87
- btn = gr.Button("🚀 GERAR LOTE TURBO", variant="primary")
88
- btn.click(fn=process_batch, inputs=inp, outputs=out)
89
 
90
- demo.launch()
 
 
 
 
2
  import torch
3
  import numpy as np
4
  import cv2
5
+ from PIL import Image
6
  from transformers import pipeline
7
  from pathlib import Path
8
  import zipfile
9
  import shutil
 
 
10
 
11
+ print("AAA INPAINT + DEPTH ENGINE")
12
 
13
+ device = "cuda" if torch.cuda.is_available() else "cpu"
14
 
15
+ pipe = pipeline(
 
 
16
  task="depth-estimation",
17
  model="depth-anything/Depth-Anything-V2-Base-hf",
18
+ device=device
19
  )
20
 
21
+ # =========================
22
+ # NORMALIZAÇÃO DEPTH
23
+ # =========================
24
  def normalize_depth(depth):
25
  d = np.array(depth).astype(np.float32)
26
  d = (d - d.min()) / (d.max() - d.min() + 1e-6)
27
  return d
28
 
29
+ # =========================
30
+ # INPAINT PROFISSIONAL
31
+ # =========================
32
+ def inpaint_pro(image_pil, mask_pil):
33
+ img = np.array(image_pil)
34
+ mask = np.array(mask_pil.convert("L"))
35
+
36
+ # binariza máscara
37
+ mask = (mask > 128).astype(np.uint8) * 255
38
+
39
+ # 🔥 suaviza borda do buraco
40
+ kernel = np.ones((5,5), np.uint8)
41
+ mask = cv2.dilate(mask, kernel, iterations=1)
42
+
43
+ img_cv = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
44
+
45
+ # 🔥 TELEA (detalhe)
46
+ telea = cv2.inpaint(img_cv, mask, 3, cv2.INPAINT_TELEA)
47
+
48
+ # 🔥 NAVIER (consistência)
49
+ ns = cv2.inpaint(img_cv, mask, 3, cv2.INPAINT_NS)
50
+
51
+ # 🔥 mistura inteligente
52
+ blended = cv2.addWeighted(telea, 0.6, ns, 0.4, 0)
53
+
54
+ # 🔥 refino leve (anti artefato)
55
+ blended = cv2.bilateralFilter(blended, 5, 50, 50)
56
+
57
+ return Image.fromarray(cv2.cvtColor(blended, cv2.COLOR_BGR2RGB))
58
+
59
+ # =========================
60
+ # PROCESS
61
+ # =========================
62
+ def process(images, masks):
63
+ if not images or not masks:
64
+ return None
65
+
66
+ out = Path("AAA_output")
67
+ if out.exists():
68
+ shutil.rmtree(out)
69
+ out.mkdir()
70
+
71
+ zip_path = "AAA_RESULT.zip"
72
 
73
  with zipfile.ZipFile(zip_path, 'w') as zipf:
74
+ for img_file, mask_file in zip(images, masks):
75
+
76
+ name = Path(img_file.name).stem
77
+
78
+ img = Image.open(img_file.name).convert("RGB")
79
+ mask = Image.open(mask_file.name)
80
+
81
+ # 💥 INPAINT REAL (SEM IA)
82
+ clean = inpaint_pro(img, mask)
83
+
84
+ # 💥 DEPTH
85
+ depth_raw = pipe(clean)["depth"]
86
+ depth_np = normalize_depth(depth_raw)
87
+
88
+ depth_img = Image.fromarray((depth_np * 255).astype(np.uint8))
89
+
90
+ # salvar
91
+ img_path = out / f"clean_{name}.png"
92
+ depth_path = out / f"depth_{name}.png"
93
+
94
+ clean.save(img_path)
95
+ depth_img.save(depth_path)
96
+
97
+ zipf.write(img_path, img_path.name)
 
 
 
 
 
 
 
 
 
 
 
 
 
98
  zipf.write(depth_path, depth_path.name)
99
 
100
+ print("✅ PIPELINE COMPLETO FINALIZADO")
101
  return zip_path
102
 
103
+ # =========================
104
+ # UI
105
+ # =========================
106
+ with gr.Blocks() as demo:
107
+ gr.Markdown("# 🧠 AAA INPAINT + DEPTH (NO FAKE AI)")
108
+
109
+ inp_img = gr.File(file_count="multiple", label="IMAGENS (BG com buraco)")
110
+ inp_mask = gr.File(file_count="multiple", label="MÁSCARAS (buraco branco)")
111
+
112
  out = gr.File()
 
 
113
 
114
+ btn = gr.Button("PROCESSAR AAA")
115
+ btn.click(fn=process, inputs=[inp_img, inp_mask], outputs=out)
116
+
117
+ demo.launch()