Delete app.py
Browse files
app.py
DELETED
|
@@ -1,601 +0,0 @@
|
|
| 1 |
-
import os
|
| 2 |
-
import re
|
| 3 |
-
import tempfile
|
| 4 |
-
import threading
|
| 5 |
-
import zipfile
|
| 6 |
-
from pathlib import Path
|
| 7 |
-
|
| 8 |
-
# O runtime ZeroGPU exige uma função marcada com @spaces.GPU no arquivo.
|
| 9 |
-
# Este marcador não é chamado e não participa da geração; o app continua
|
| 10 |
-
# deliberadamente CPU-only. O import vem antes de OpenCV e Torch para evitar
|
| 11 |
-
# inicialização prematura do CUDA.
|
| 12 |
-
import spaces
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
@spaces.GPU
|
| 16 |
-
def zerogpu_startup_dummy():
|
| 17 |
-
"""Marcador de startup exigido pelo ZeroGPU; não executa processamento."""
|
| 18 |
-
return None
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
import cv2
|
| 22 |
-
import gradio as gr
|
| 23 |
-
import numpy as np
|
| 24 |
-
import torch
|
| 25 |
-
from PIL import Image
|
| 26 |
-
from scipy.ndimage import median_filter
|
| 27 |
-
from transformers import AutoImageProcessor, AutoModelForDepthEstimation
|
| 28 |
-
|
| 29 |
-
# -----------------------------------------------------------------------------
|
| 30 |
-
# Configuração de qualidade
|
| 31 |
-
# -----------------------------------------------------------------------------
|
| 32 |
-
MODEL_ID = "depth-anything/Depth-Anything-V2-Large-hf"
|
| 33 |
-
MODEL_LABEL = "Depth Anything V2 Large"
|
| 34 |
-
# CPU-only por escolha explícita do app.
|
| 35 |
-
DEVICE = torch.device("cpu")
|
| 36 |
-
MODEL_DTYPE = torch.float32
|
| 37 |
-
DEFAULT_INFERENCE_SIZE = 1024
|
| 38 |
-
MAX_LARGE_INFERENCE_SIZE = 1024
|
| 39 |
-
SAMPLE_MULTIPLE = 14
|
| 40 |
-
|
| 41 |
-
MODEL_LOCK = threading.Lock()
|
| 42 |
-
PROCESSOR = None
|
| 43 |
-
MODEL = None
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
def _configure_runtime() -> None:
|
| 47 |
-
"""Mantém o processamento CPU previsível."""
|
| 48 |
-
if DEVICE.type == "cpu":
|
| 49 |
-
try:
|
| 50 |
-
torch.set_num_threads(max(1, min(4, os.cpu_count() or 1)))
|
| 51 |
-
except RuntimeError:
|
| 52 |
-
pass
|
| 53 |
-
try:
|
| 54 |
-
torch.set_num_interop_threads(1)
|
| 55 |
-
except RuntimeError:
|
| 56 |
-
pass
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
def load_model_once():
|
| 60 |
-
"""Carrega o processador e o Large uma única vez no dispositivo disponível."""
|
| 61 |
-
global PROCESSOR, MODEL
|
| 62 |
-
if MODEL is not None:
|
| 63 |
-
return PROCESSOR, MODEL
|
| 64 |
-
|
| 65 |
-
with MODEL_LOCK:
|
| 66 |
-
if MODEL is None:
|
| 67 |
-
_configure_runtime()
|
| 68 |
-
PROCESSOR = AutoImageProcessor.from_pretrained(MODEL_ID)
|
| 69 |
-
MODEL = AutoModelForDepthEstimation.from_pretrained(
|
| 70 |
-
MODEL_ID,
|
| 71 |
-
torch_dtype=MODEL_DTYPE,
|
| 72 |
-
).to(DEVICE).eval()
|
| 73 |
-
return PROCESSOR, MODEL
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
# -----------------------------------------------------------------------------
|
| 77 |
-
# Operações de imagem equivalentes ao HTML v4.3
|
| 78 |
-
# -----------------------------------------------------------------------------
|
| 79 |
-
def _box_filter(data: np.ndarray, radius: int) -> np.ndarray:
|
| 80 |
-
if radius <= 0:
|
| 81 |
-
return data.astype(np.float32, copy=True)
|
| 82 |
-
kernel = (2 * int(radius) + 1, 2 * int(radius) + 1)
|
| 83 |
-
return cv2.boxFilter(
|
| 84 |
-
data.astype(np.float32, copy=False),
|
| 85 |
-
ddepth=-1,
|
| 86 |
-
ksize=kernel,
|
| 87 |
-
normalize=True,
|
| 88 |
-
borderType=cv2.BORDER_REPLICATE,
|
| 89 |
-
)
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
def _edge_aware_smooth(depth: np.ndarray, radius: int, strength: float) -> np.ndarray:
|
| 93 |
-
"""Suaviza degraus sem copiar a textura RGB para o depth."""
|
| 94 |
-
if strength <= 0:
|
| 95 |
-
return depth.astype(np.float32, copy=True)
|
| 96 |
-
radius = max(1, int(radius))
|
| 97 |
-
diameter = max(3, 2 * radius + 1)
|
| 98 |
-
filtered = cv2.bilateralFilter(
|
| 99 |
-
depth.astype(np.float32, copy=False),
|
| 100 |
-
d=diameter,
|
| 101 |
-
sigmaColor=0.06,
|
| 102 |
-
sigmaSpace=float(radius),
|
| 103 |
-
)
|
| 104 |
-
return (
|
| 105 |
-
depth * (1.0 - float(strength)) + filtered * float(strength)
|
| 106 |
-
).astype(np.float32)
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
def _guided_filter(gray_guide: np.ndarray, depth: np.ndarray, radius: int, eps: float) -> np.ndarray:
|
| 110 |
-
gray_guide = gray_guide.astype(np.float32, copy=False)
|
| 111 |
-
depth = depth.astype(np.float32, copy=False)
|
| 112 |
-
mean_i = _box_filter(gray_guide, radius)
|
| 113 |
-
mean_p = _box_filter(depth, radius)
|
| 114 |
-
corr_ip = _box_filter(gray_guide * depth, radius)
|
| 115 |
-
corr_ii = _box_filter(gray_guide * gray_guide, radius)
|
| 116 |
-
var_i = corr_ii - mean_i * mean_i
|
| 117 |
-
cov_ip = corr_ip - mean_i * mean_p
|
| 118 |
-
a = cov_ip / (var_i + float(eps))
|
| 119 |
-
b = mean_p - a * mean_i
|
| 120 |
-
mean_a = _box_filter(a, radius)
|
| 121 |
-
mean_b = _box_filter(b, radius)
|
| 122 |
-
return (mean_a * gray_guide + mean_b).astype(np.float32, copy=False)
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
def _sobel_gradient(data: np.ndarray) -> np.ndarray:
|
| 126 |
-
gx = cv2.Sobel(data.astype(np.float32), cv2.CV_32F, 1, 0, ksize=3)
|
| 127 |
-
gy = cv2.Sobel(data.astype(np.float32), cv2.CV_32F, 0, 1, ksize=3)
|
| 128 |
-
return cv2.magnitude(gx, gy)
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
def _edge_median_refine(depth: np.ndarray, radius: int, strength: float) -> np.ndarray:
|
| 132 |
-
if strength <= 0:
|
| 133 |
-
return depth.astype(np.float32, copy=True)
|
| 134 |
-
radius = max(1, int(radius))
|
| 135 |
-
# O median é calculado uma vez para evitar o custo extremo de ordenar uma
|
| 136 |
-
# janela para cada pixel, mantendo a mesma lógica de mistura nas bordas.
|
| 137 |
-
median = median_filter(
|
| 138 |
-
depth.astype(np.float32, copy=False),
|
| 139 |
-
size=2 * radius + 1,
|
| 140 |
-
mode="nearest",
|
| 141 |
-
).astype(np.float32, copy=False)
|
| 142 |
-
grad = _sobel_gradient(depth)
|
| 143 |
-
gmax = float(grad.max())
|
| 144 |
-
if gmax <= 0:
|
| 145 |
-
return depth.astype(np.float32, copy=True)
|
| 146 |
-
local_t = np.minimum(1.0, grad / gmax) * float(strength)
|
| 147 |
-
return (depth * (1.0 - local_t) + median * local_t).astype(np.float32)
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
def _matte_edge_snap(
|
| 151 |
-
depth: np.ndarray,
|
| 152 |
-
matte: np.ndarray,
|
| 153 |
-
radius: int = 4,
|
| 154 |
-
eps: float = 0.0002,
|
| 155 |
-
strength: float = 1.0,
|
| 156 |
-
) -> np.ndarray:
|
| 157 |
-
guided = _guided_filter(matte, depth, radius, eps)
|
| 158 |
-
guide_grad = _sobel_gradient(matte)
|
| 159 |
-
gmax = float(guide_grad.max())
|
| 160 |
-
if gmax <= 0:
|
| 161 |
-
return depth
|
| 162 |
-
edge_weight = np.minimum(1.0, guide_grad / gmax) * float(strength)
|
| 163 |
-
return (depth * (1.0 - edge_weight) + guided * edge_weight).astype(np.float32)
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
def _shadow_bias_correct(
|
| 167 |
-
depth: np.ndarray,
|
| 168 |
-
guide_gray: np.ndarray,
|
| 169 |
-
radius: int,
|
| 170 |
-
strength: float,
|
| 171 |
-
) -> np.ndarray:
|
| 172 |
-
guide_low = _box_filter(guide_gray, radius)
|
| 173 |
-
correction = (0.5 - guide_low) * float(strength)
|
| 174 |
-
correction = np.where(depth < 0.15, correction * 0.3, correction)
|
| 175 |
-
return np.clip(depth + correction, 0.0, 1.0).astype(np.float32)
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
def _stabilize_border_halo(
|
| 179 |
-
depth: np.ndarray,
|
| 180 |
-
fraction: float = 0.02,
|
| 181 |
-
strength: float = 0.90,
|
| 182 |
-
) -> np.ndarray:
|
| 183 |
-
"""Espelha suavemente apenas a faixa externa de 2%, como no HTML."""
|
| 184 |
-
h, w = depth.shape
|
| 185 |
-
bx = max(2, round(w * fraction))
|
| 186 |
-
by = max(2, round(h * fraction))
|
| 187 |
-
yy, xx = np.indices((h, w), dtype=np.int32)
|
| 188 |
-
edge_x = np.minimum(xx, w - 1 - xx)
|
| 189 |
-
edge_y = np.minimum(yy, h - 1 - yy)
|
| 190 |
-
mask = (edge_x < bx) | (edge_y < by)
|
| 191 |
-
sx = np.where(xx < bx, np.minimum(w - 1, 2 * bx - xx), xx)
|
| 192 |
-
sx = np.where(xx >= w - bx, np.maximum(0, 2 * (w - 1 - bx) - xx), sx)
|
| 193 |
-
sy = np.where(yy < by, np.minimum(h - 1, 2 * by - yy), yy)
|
| 194 |
-
sy = np.where(yy >= h - by, np.maximum(0, 2 * (h - 1 - by) - yy), sy)
|
| 195 |
-
edge_dist = np.minimum(
|
| 196 |
-
edge_x / max(1, bx),
|
| 197 |
-
edge_y / max(1, by),
|
| 198 |
-
)
|
| 199 |
-
blend = np.clip(strength * (1.0 - edge_dist) ** 2, 0.0, 1.0).astype(np.float32)
|
| 200 |
-
out = depth.copy()
|
| 201 |
-
reflected = depth[sy, sx]
|
| 202 |
-
out[mask] = depth[mask] * (1.0 - blend[mask]) + reflected[mask] * blend[mask]
|
| 203 |
-
return out.astype(np.float32)
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
def _extract_number(name: str):
|
| 207 |
-
matches = re.findall(r"(\d+)", Path(name).stem)
|
| 208 |
-
return int(matches[-1]) if matches else None
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
def _as_paths(value):
|
| 212 |
-
if value is None:
|
| 213 |
-
return []
|
| 214 |
-
if isinstance(value, (str, Path)):
|
| 215 |
-
return [str(value)]
|
| 216 |
-
paths = []
|
| 217 |
-
for item in value:
|
| 218 |
-
if isinstance(item, (str, Path)):
|
| 219 |
-
paths.append(str(item))
|
| 220 |
-
elif isinstance(item, dict) and item.get("name"):
|
| 221 |
-
paths.append(str(item["name"]))
|
| 222 |
-
return paths
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
def _load_matte(path: str, size: tuple[int, int]) -> np.ndarray:
|
| 226 |
-
image = Image.open(path).convert("RGBA")
|
| 227 |
-
image = image.resize(size, Image.Resampling.LANCZOS)
|
| 228 |
-
rgba = np.asarray(image).astype(np.float32) / 255.0
|
| 229 |
-
alpha = rgba[..., 3]
|
| 230 |
-
if np.any(alpha < 250.0 / 255.0):
|
| 231 |
-
return alpha.astype(np.float32)
|
| 232 |
-
rgb = rgba[..., :3]
|
| 233 |
-
return (0.299 * rgb[..., 0] + 0.587 * rgb[..., 1] + 0.114 * rgb[..., 2]).astype(np.float32)
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
def _normalise_depth(depth: np.ndarray, use_percentile: bool) -> np.ndarray:
|
| 237 |
-
depth = depth.astype(np.float32, copy=False)
|
| 238 |
-
if use_percentile:
|
| 239 |
-
low, high = np.percentile(depth, [0.5, 99.5])
|
| 240 |
-
else:
|
| 241 |
-
low, high = float(depth.min()), float(depth.max())
|
| 242 |
-
span = float(high - low) or 1.0
|
| 243 |
-
return np.clip((depth - low) / span, 0.0, 1.0).astype(np.float32)
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
def _save_16bit_png(depth: np.ndarray, path: str) -> None:
|
| 247 |
-
values = np.clip(depth * 65535.0 + 0.5, 0, 65535).astype(np.uint16)
|
| 248 |
-
Image.fromarray(values, mode="I;16").save(path, format="PNG", optimize=False)
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
def _save_8bit_png(depth: np.ndarray, path: str) -> None:
|
| 252 |
-
values = np.clip(depth * 255.0 + 0.5, 0, 255).astype(np.uint8)
|
| 253 |
-
Image.fromarray(values, mode="L").save(path, format="PNG", optimize=False)
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
def _resize_for_inference(image: Image.Image, target_size: int) -> Image.Image:
|
| 257 |
-
original_w, original_h = image.size
|
| 258 |
-
scale = float(target_size) / max(original_w, original_h)
|
| 259 |
-
width = max(SAMPLE_MULTIPLE, round(original_w * scale / SAMPLE_MULTIPLE) * SAMPLE_MULTIPLE)
|
| 260 |
-
height = max(SAMPLE_MULTIPLE, round(original_h * scale / SAMPLE_MULTIPLE) * SAMPLE_MULTIPLE)
|
| 261 |
-
return image.resize((width, height), Image.Resampling.LANCZOS)
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
def _infer_depth(image: Image.Image, inference_size: int, pre_blur: float):
|
| 265 |
-
processor, model = load_model_once()
|
| 266 |
-
resized = _resize_for_inference(image, inference_size)
|
| 267 |
-
infer_w, infer_h = resized.size
|
| 268 |
-
guide = np.asarray(resized.convert("RGB"), dtype=np.float32) / 255.0
|
| 269 |
-
guide_gray = (
|
| 270 |
-
0.299 * guide[..., 0]
|
| 271 |
-
+ 0.587 * guide[..., 1]
|
| 272 |
-
+ 0.114 * guide[..., 2]
|
| 273 |
-
).astype(np.float32)
|
| 274 |
-
|
| 275 |
-
model_image = resized
|
| 276 |
-
if pre_blur > 0:
|
| 277 |
-
rgb_u8 = np.asarray(resized.convert("RGB"))
|
| 278 |
-
ksize = max(3, 2 * int(round(3.0 * pre_blur)) + 1)
|
| 279 |
-
model_image = Image.fromarray(
|
| 280 |
-
cv2.GaussianBlur(rgb_u8, (ksize, ksize), sigmaX=float(pre_blur)),
|
| 281 |
-
mode="RGB",
|
| 282 |
-
)
|
| 283 |
-
|
| 284 |
-
inputs = processor(
|
| 285 |
-
images=model_image,
|
| 286 |
-
return_tensors="pt",
|
| 287 |
-
size={"height": infer_h, "width": infer_w},
|
| 288 |
-
keep_aspect_ratio=True,
|
| 289 |
-
ensure_multiple_of=SAMPLE_MULTIPLE,
|
| 290 |
-
)
|
| 291 |
-
inputs = {
|
| 292 |
-
key: (
|
| 293 |
-
value.to(DEVICE) if hasattr(value, "to") else value
|
| 294 |
-
)
|
| 295 |
-
for key, value in inputs.items()
|
| 296 |
-
}
|
| 297 |
-
with torch.inference_mode():
|
| 298 |
-
outputs = model(**inputs)
|
| 299 |
-
post = processor.post_process_depth_estimation(
|
| 300 |
-
outputs,
|
| 301 |
-
target_sizes=[(infer_h, infer_w)],
|
| 302 |
-
)
|
| 303 |
-
depth = post[0]["predicted_depth"].detach().float().cpu().numpy()
|
| 304 |
-
return depth.astype(np.float32), guide_gray, (infer_w, infer_h)
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
def generate_depth_maps(
|
| 308 |
-
image_files,
|
| 309 |
-
matte_files,
|
| 310 |
-
inference_size,
|
| 311 |
-
guided,
|
| 312 |
-
detail,
|
| 313 |
-
percentile,
|
| 314 |
-
white_near,
|
| 315 |
-
debug_raw,
|
| 316 |
-
guided_radius,
|
| 317 |
-
guided_eps,
|
| 318 |
-
detail_strength,
|
| 319 |
-
contrast,
|
| 320 |
-
pre_blur,
|
| 321 |
-
chiaroscuro,
|
| 322 |
-
chiaroscuro_gamma,
|
| 323 |
-
band_smoothing,
|
| 324 |
-
band_strength,
|
| 325 |
-
band_radius,
|
| 326 |
-
shadow_fix,
|
| 327 |
-
shadow_strength,
|
| 328 |
-
shadow_radius,
|
| 329 |
-
edge_refine_strength,
|
| 330 |
-
edge_refine_radius,
|
| 331 |
-
output_16bit,
|
| 332 |
-
progress=gr.Progress(track_tqdm=False),
|
| 333 |
-
):
|
| 334 |
-
image_paths = _as_paths(image_files)
|
| 335 |
-
matte_paths = _as_paths(matte_files)
|
| 336 |
-
if not image_paths:
|
| 337 |
-
raise gr.Error("Selecione pelo menos uma imagem.")
|
| 338 |
-
|
| 339 |
-
# O Large no HTML já era limitado a 1024 para evitar OOM; mantemos essa
|
| 340 |
-
# proteção no Space CPU para preservar estabilidade.
|
| 341 |
-
requested_size = int(inference_size)
|
| 342 |
-
inference_size = min(requested_size, MAX_LARGE_INFERENCE_SIZE)
|
| 343 |
-
if inference_size != requested_size:
|
| 344 |
-
size_note = f"Large limitado a {inference_size}px para estabilidade"
|
| 345 |
-
else:
|
| 346 |
-
size_note = f"inferência em {inference_size}px"
|
| 347 |
-
|
| 348 |
-
matte_map = {}
|
| 349 |
-
for matte_path in matte_paths:
|
| 350 |
-
number = _extract_number(matte_path)
|
| 351 |
-
if number is not None:
|
| 352 |
-
matte_map[number] = matte_path
|
| 353 |
-
|
| 354 |
-
out_dir = tempfile.mkdtemp(prefix="depthforge_")
|
| 355 |
-
output_paths = []
|
| 356 |
-
gallery = []
|
| 357 |
-
started = len(image_paths)
|
| 358 |
-
|
| 359 |
-
progress(0, desc=f"Carregando {MODEL_LABEL}…")
|
| 360 |
-
load_model_once()
|
| 361 |
-
|
| 362 |
-
try:
|
| 363 |
-
for index, image_path in enumerate(image_paths, start=1):
|
| 364 |
-
name = Path(image_path).name
|
| 365 |
-
progress((index - 1) / started, desc=f"Processando {index}/{started}: {name}")
|
| 366 |
-
image = Image.open(image_path).convert("RGB")
|
| 367 |
-
original_size = image.size
|
| 368 |
-
|
| 369 |
-
raw_depth, guide_gray, (infer_w, infer_h) = _infer_depth(
|
| 370 |
-
image,
|
| 371 |
-
inference_size,
|
| 372 |
-
float(pre_blur) if bool(pre_blur) else 0.0,
|
| 373 |
-
)
|
| 374 |
-
depth = _normalise_depth(raw_depth, bool(percentile))
|
| 375 |
-
# Depth Anything V2 relativo entrega inverse-depth: valores maiores
|
| 376 |
-
# representam superfícies mais próximas. Para paralaxe, o padrão é
|
| 377 |
-
# branco=perto e preto=longe; permite-se inverter para outros apps.
|
| 378 |
-
if not bool(white_near):
|
| 379 |
-
depth = 1.0 - depth
|
| 380 |
-
if abs(float(contrast) - 1.0) > 1e-6:
|
| 381 |
-
depth = np.power(np.clip(depth, 0.0, 1.0), float(contrast)).astype(np.float32)
|
| 382 |
-
|
| 383 |
-
if not bool(debug_raw):
|
| 384 |
-
if bool(shadow_fix) and float(shadow_strength) > 0:
|
| 385 |
-
progress((index - 0.75) / started, desc=f"Correção de sombra: {name}")
|
| 386 |
-
depth = _shadow_bias_correct(
|
| 387 |
-
depth, guide_gray, int(shadow_radius), float(shadow_strength)
|
| 388 |
-
)
|
| 389 |
-
if bool(band_smoothing) and float(band_strength) > 0:
|
| 390 |
-
depth = _edge_aware_smooth(
|
| 391 |
-
depth,
|
| 392 |
-
int(band_radius),
|
| 393 |
-
float(band_strength),
|
| 394 |
-
)
|
| 395 |
-
if bool(chiaroscuro):
|
| 396 |
-
guide_for_filter = np.power(
|
| 397 |
-
np.clip(guide_gray, 0.0, 1.0), float(chiaroscuro_gamma)
|
| 398 |
-
).astype(np.float32)
|
| 399 |
-
else:
|
| 400 |
-
guide_for_filter = guide_gray
|
| 401 |
-
if bool(guided):
|
| 402 |
-
progress((index - 0.65) / started, desc=f"Guided Filter: {name}")
|
| 403 |
-
depth = _guided_filter(
|
| 404 |
-
guide_for_filter,
|
| 405 |
-
depth,
|
| 406 |
-
int(guided_radius),
|
| 407 |
-
float(guided_eps),
|
| 408 |
-
)
|
| 409 |
-
if bool(detail) and float(detail_strength) > 0:
|
| 410 |
-
blurred = _box_filter(depth, 3)
|
| 411 |
-
depth = np.clip(
|
| 412 |
-
depth + (depth - blurred) * float(detail_strength),
|
| 413 |
-
0.0,
|
| 414 |
-
1.0,
|
| 415 |
-
).astype(np.float32)
|
| 416 |
-
if float(edge_refine_strength) > 0:
|
| 417 |
-
depth = _edge_median_refine(
|
| 418 |
-
depth,
|
| 419 |
-
int(edge_refine_radius),
|
| 420 |
-
float(edge_refine_strength),
|
| 421 |
-
)
|
| 422 |
-
|
| 423 |
-
number = _extract_number(image_path)
|
| 424 |
-
if number is not None and number in matte_map:
|
| 425 |
-
try:
|
| 426 |
-
matte = _load_matte(matte_map[number], (infer_w, infer_h))
|
| 427 |
-
depth = _matte_edge_snap(depth, matte, radius=4, eps=0.0002, strength=1.0)
|
| 428 |
-
except Exception:
|
| 429 |
-
# Um matte inválido não deve impedir o depth principal.
|
| 430 |
-
pass
|
| 431 |
-
|
| 432 |
-
if not bool(debug_raw):
|
| 433 |
-
depth = _stabilize_border_halo(depth, fraction=0.02, strength=0.90)
|
| 434 |
-
|
| 435 |
-
depth = np.clip(depth, 0.0, 1.0).astype(np.float32)
|
| 436 |
-
# O processamento é feito na resolução de inferência; a saída é
|
| 437 |
-
# reamostrada à resolução original com Lanczos, como o HTML fazia
|
| 438 |
-
# com imageSmoothingQuality='high'.
|
| 439 |
-
depth_image = Image.fromarray(
|
| 440 |
-
np.clip(depth * 65535.0 + 0.5, 0, 65535).astype(np.uint16),
|
| 441 |
-
mode="I;16",
|
| 442 |
-
).resize(original_size, Image.Resampling.LANCZOS)
|
| 443 |
-
depth_original = np.asarray(depth_image, dtype=np.uint16).astype(np.float32) / 65535.0
|
| 444 |
-
|
| 445 |
-
# A numeração é deliberadamente baseada na posição recebida pelo
|
| 446 |
-
# Gradio, não em números encontrados no nome do arquivo. Como
|
| 447 |
-
# output_paths é preenchido no mesmo loop, PNGs, galeria e ZIP
|
| 448 |
-
# permanecem na ordem original dos inputs.
|
| 449 |
-
output_name = f"depth_{index:03d}.png"
|
| 450 |
-
output_path = os.path.join(out_dir, output_name)
|
| 451 |
-
if bool(output_16bit):
|
| 452 |
-
_save_16bit_png(depth_original, output_path)
|
| 453 |
-
else:
|
| 454 |
-
_save_8bit_png(depth_original, output_path)
|
| 455 |
-
output_paths.append(output_path)
|
| 456 |
-
|
| 457 |
-
preview = Image.fromarray(
|
| 458 |
-
np.clip(depth_original * 255.0 + 0.5, 0, 255).astype(np.uint8),
|
| 459 |
-
mode="L",
|
| 460 |
-
)
|
| 461 |
-
gallery.append((preview, f"{index:03d} • {name} → {output_name}"))
|
| 462 |
-
progress(index / started, desc=f"Concluído {index}/{started}: {name}")
|
| 463 |
-
|
| 464 |
-
zip_path = os.path.join(out_dir, "depthforge_pintura_maps.zip")
|
| 465 |
-
with zipfile.ZipFile(zip_path, "w", compression=zipfile.ZIP_STORED) as archive:
|
| 466 |
-
for output_path in output_paths:
|
| 467 |
-
archive.write(output_path, arcname=os.path.basename(output_path))
|
| 468 |
-
|
| 469 |
-
bit_depth = "16-bit" if bool(output_16bit) else "8-bit"
|
| 470 |
-
status = (
|
| 471 |
-
f"✅ {len(output_paths)} mapa(s) concluído(s) • {MODEL_LABEL} • {size_note}\n"
|
| 472 |
-
f"Saída: PNG {bit_depth}, resolução original, sem quantização intermediária.\n"
|
| 473 |
-
"Preset PINTURA para paralaxe: bandas bilaterais leves, Detail OFF, "
|
| 474 |
-
"pré-blur 0.6, Edge Refine suave e proteção de halo.\n"
|
| 475 |
-
"Convenção padrão: branco=perto / preto=longe. ZIP e PNGs seguem exatamente a ordem dos inputs."
|
| 476 |
-
)
|
| 477 |
-
return gallery, output_paths, zip_path, status
|
| 478 |
-
except RuntimeError as error:
|
| 479 |
-
if "out of memory" in str(error).lower():
|
| 480 |
-
raise gr.Error(
|
| 481 |
-
"O Large ficou sem memória nesta resolução. Tente 768 ou 512; "
|
| 482 |
-
"o preset e a qualidade do modelo permanecem os mesmos."
|
| 483 |
-
) from error
|
| 484 |
-
raise
|
| 485 |
-
|
| 486 |
-
|
| 487 |
-
with gr.Blocks(title="DepthForge PINTURA — Depth Anything V2 Large") as demo:
|
| 488 |
-
gr.Markdown(
|
| 489 |
-
"""
|
| 490 |
-
# DepthForge PINTURA v4.3
|
| 491 |
-
Gere mapas de profundidade para pintura com **Depth Anything V2 Large**.
|
| 492 |
-
O pipeline mantém o depth bruto em ponto flutuante até a exportação,
|
| 493 |
-
aplica os filtros suaves do HTML e grava PNG de 16 bits por padrão.
|
| 494 |
-
"""
|
| 495 |
-
)
|
| 496 |
-
gr.Markdown(
|
| 497 |
-
"**Modelo:** Depth Anything V2 Large · **Execução:** CPU-only · "
|
| 498 |
-
"**Resolução Large padrão:** 1024 px · **Saída:** PNG 16-bit + ZIP"
|
| 499 |
-
)
|
| 500 |
-
|
| 501 |
-
with gr.Row():
|
| 502 |
-
with gr.Column(scale=1):
|
| 503 |
-
image_files = gr.File(
|
| 504 |
-
label="Imagens de entrada",
|
| 505 |
-
file_count="multiple",
|
| 506 |
-
file_types=["image"],
|
| 507 |
-
type="filepath",
|
| 508 |
-
)
|
| 509 |
-
matte_files = gr.File(
|
| 510 |
-
label="Mattes PNG alpha opcionais",
|
| 511 |
-
file_count="multiple",
|
| 512 |
-
file_types=["image"],
|
| 513 |
-
type="filepath",
|
| 514 |
-
)
|
| 515 |
-
inference_size = gr.Dropdown(
|
| 516 |
-
choices=[512, 768, 1024],
|
| 517 |
-
value=DEFAULT_INFERENCE_SIZE,
|
| 518 |
-
label="Resolução de inferência do Large",
|
| 519 |
-
)
|
| 520 |
-
output_16bit = gr.Checkbox(
|
| 521 |
-
value=True,
|
| 522 |
-
label="PNG 16-bit — recomendado para pintura",
|
| 523 |
-
)
|
| 524 |
-
generate = gr.Button("⚡ GERAR DEPTH MAPS", variant="primary")
|
| 525 |
-
|
| 526 |
-
with gr.Column(scale=2):
|
| 527 |
-
with gr.Accordion("PINTURA v4.3 — parâmetros avançados", open=True):
|
| 528 |
-
with gr.Row():
|
| 529 |
-
with gr.Column():
|
| 530 |
-
guided = gr.Checkbox(value=False, label="Guided Filter")
|
| 531 |
-
detail = gr.Checkbox(value=False, label="Detail Boost — opcional")
|
| 532 |
-
percentile = gr.Checkbox(value=True, label="Normalização por percentil 0,5–99,5%")
|
| 533 |
-
white_near = gr.Checkbox(
|
| 534 |
-
value=True,
|
| 535 |
-
label="Branco = perto / preto = longe (paralaxe)",
|
| 536 |
-
)
|
| 537 |
-
debug_raw = gr.Checkbox(value=False, label="🔬 Modo cru")
|
| 538 |
-
with gr.Column():
|
| 539 |
-
pre_blur = gr.Slider(0.0, 3.0, value=0.6, step=0.1, label="Pré-blur anti-textura (0,6 recomendado)")
|
| 540 |
-
detail_strength = gr.Slider(0.0, 1.0, value=0.04, step=0.01, label="Detail strength")
|
| 541 |
-
contrast = gr.Slider(0.8, 2.0, value=1.0, step=0.05, label="Contraste")
|
| 542 |
-
edge_refine_strength = gr.Slider(0.0, 1.0, value=0.10, step=0.05, label="Edge Refine suave")
|
| 543 |
-
edge_refine_radius = gr.Dropdown([1, 2, 3], value=1, label="Edge radius")
|
| 544 |
-
with gr.Row():
|
| 545 |
-
with gr.Column():
|
| 546 |
-
guided_radius = gr.Slider(2, 24, value=8, step=1, label="Guided radius")
|
| 547 |
-
guided_eps = gr.Slider(0.0001, 0.02, value=0.004, step=0.0001, label="Guided epsilon")
|
| 548 |
-
chiaroscuro = gr.Checkbox(value=False, label="Chiaroscuro")
|
| 549 |
-
chiaroscuro_gamma = gr.Slider(0.0, 2.0, value=1.0, step=0.05, label="Chiaroscuro gamma")
|
| 550 |
-
with gr.Column():
|
| 551 |
-
band_smoothing = gr.Checkbox(value=True, label="Suavização de bandas")
|
| 552 |
-
band_strength = gr.Slider(0.0, 1.0, value=0.08, step=0.01, label="Band strength")
|
| 553 |
-
band_radius = gr.Slider(4, 24, value=6, step=1, label="Band radius")
|
| 554 |
-
shadow_fix = gr.Checkbox(value=False, label="Correção de sombra — experimental")
|
| 555 |
-
shadow_strength = gr.Slider(0.0, 1.0, value=0.20, step=0.05, label="Shadow strength")
|
| 556 |
-
shadow_radius = gr.Slider(8, 48, value=28, step=1, label="Shadow radius")
|
| 557 |
-
|
| 558 |
-
status = gr.Markdown(
|
| 559 |
-
"Pronto. O modelo Large será baixado na primeira geração. "
|
| 560 |
-
"Padrão para paralaxe: branco=perto, preto=longe; filtros conservadores para pintura."
|
| 561 |
-
)
|
| 562 |
-
gallery = gr.Gallery(label="Prévia dos mapas", columns=3, height="auto")
|
| 563 |
-
output_files = gr.Files(label="Baixar PNGs individuais", file_types=[".png"])
|
| 564 |
-
output_zip = gr.File(label="Baixar todos em ZIP", file_types=[".zip"])
|
| 565 |
-
|
| 566 |
-
generate.click(
|
| 567 |
-
fn=generate_depth_maps,
|
| 568 |
-
inputs=[
|
| 569 |
-
image_files,
|
| 570 |
-
matte_files,
|
| 571 |
-
inference_size,
|
| 572 |
-
guided,
|
| 573 |
-
detail,
|
| 574 |
-
percentile,
|
| 575 |
-
white_near,
|
| 576 |
-
debug_raw,
|
| 577 |
-
guided_radius,
|
| 578 |
-
guided_eps,
|
| 579 |
-
detail_strength,
|
| 580 |
-
contrast,
|
| 581 |
-
pre_blur,
|
| 582 |
-
chiaroscuro,
|
| 583 |
-
chiaroscuro_gamma,
|
| 584 |
-
band_smoothing,
|
| 585 |
-
band_strength,
|
| 586 |
-
band_radius,
|
| 587 |
-
shadow_fix,
|
| 588 |
-
shadow_strength,
|
| 589 |
-
shadow_radius,
|
| 590 |
-
edge_refine_strength,
|
| 591 |
-
edge_refine_radius,
|
| 592 |
-
output_16bit,
|
| 593 |
-
],
|
| 594 |
-
outputs=[gallery, output_files, output_zip, status],
|
| 595 |
-
concurrency_limit=1,
|
| 596 |
-
show_progress="full",
|
| 597 |
-
)
|
| 598 |
-
|
| 599 |
-
|
| 600 |
-
if __name__ == "__main__":
|
| 601 |
-
demo.queue(max_size=4).launch()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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