File size: 6,963 Bytes
ee9a865
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e9cc72
ee9a865
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e9cc72
ee9a865
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e9cc72
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
"""Parallax Cine · gerador de mapas de profundidade (Hugging Face Spaces · ZeroGPU)

Modelos:
  • Depth Anything V2 Large  – estável, rápido, muito bom em pintura/arte gerada por IA
  • Depth Pro (Apple)        – bordas mais nítidas, bom para parallax; mais lento
Saída: ZIP (sem compressão) com  <nome>_depth.png  (branco = perto, preto = longe).
"""
import os, re, zipfile, tempfile
import numpy as np
import cv2
import torch
import gradio as gr
from PIL import Image, ImageOps
from transformers import AutoImageProcessor, AutoModelForDepthEstimation

# ---------- ZeroGPU (e fallback local) ----------
try:
    import spaces
    gpu = spaces.GPU
except Exception:                                   # rodando fora do Spaces
    def gpu(*a, **k):
        if len(a) == 1 and callable(a[0]) and not k:
            return a[0]
        return lambda f: f

DEVICE = "cuda" if torch.cuda.is_available() else "cpu"   # no ZeroGPU o CUDA é emulado na inicialização


@gpu
def _dummy_gpu():
    """Função GPU 'dummy': o ZeroGPU exige ao menos uma função @spaces.GPU registrada na inicialização."""
    return 0


MODELS = {
    "Depth Anything V2 Large (padrão)": ("depth-anything/Depth-Anything-V2-Large-hf", "dav2"),
    "Depth Pro (bordas mais nítidas, mais lento)": ("apple/DepthPro-hf", "pro"),
}
DEFAULT = "Depth Anything V2 Large (padrão)"
_cache = {}


def load(name):
    if name in _cache:
        return _cache[name]
    rid, kind = MODELS[name]
    proc = AutoImageProcessor.from_pretrained(rid)
    dtype = torch.float16 if (kind == "dav2" and DEVICE == "cuda") else torch.float32
    model = AutoModelForDepthEstimation.from_pretrained(rid, dtype=dtype).to(DEVICE).eval()
    _cache[name] = (proc, model, kind)
    return _cache[name]


load(DEFAULT)   # pré-carrega o modelo padrão no início (o ZeroGPU move para a GPU só durante a chamada)


# ---------- utilidades ----------
def norm01(d, lo=1.0, hi=99.0):
    a, b = np.percentile(d, [lo, hi])
    return np.clip((d - a) / max(1e-6, b - a), 0, 1).astype(np.float32)


def guided_filter(I, p, r, eps):
    """Filtro guiado: suaviza a profundidade respeitando as bordas da própria imagem (menos 'esticão' no parallax)."""
    k = (2 * r + 1, 2 * r + 1)
    m = lambda x: cv2.boxFilter(x, -1, k, normalize=True)
    mI, mp = m(I), m(p)
    a = (m(I * p) - mI * mp) / (m(I * I) - mI * mI + eps)
    b = mp - a * mI
    return m(a) * I + m(b)


@torch.inference_mode()
def predict(img, name, res, tta):
    proc, model, kind = load(name)
    w, h = img.size

    def run(im):
        kw = {"size": {"height": res, "width": res}} if kind == "dav2" else {}
        inp = proc(images=im, return_tensors="pt", **kw)
        inp = {k: v.to(model.device) for k, v in inp.items()}
        if kind == "dav2":
            inp["pixel_values"] = inp["pixel_values"].to(model.dtype)
        out = model(**inp)
        if kind == "pro":                                      # profundidade métrica → inversa (perto = grande)
            d = proc.post_process_depth_estimation(out, target_sizes=[(h, w)])[0]["predicted_depth"].float()
            d = 1.0 / d.clamp(min=1e-3)
        else:
            d = out.predicted_depth.unsqueeze(1).float()
            d = torch.nn.functional.interpolate(d, size=(h, w), mode="bicubic", align_corners=False)[0, 0]
        return norm01(d.cpu().numpy())

    d = run(img)
    if tta:                                                    # média com a imagem espelhada
        d = 0.5 * (d + run(ImageOps.mirror(img))[:, ::-1])
    return d


@gpu(duration=120)
def processar(arquivos, modelo, res, tta, refinar, gamma, invertir, progress=gr.Progress()):
    if not arquivos:
        raise gr.Error("Envie ao menos uma imagem.")
    arquivos = arquivos[:24]
    proc, model, kind = load(modelo)
    model.to(DEVICE)
    tmp = tempfile.mkdtemp()
    zpath = os.path.join(tmp, "profundidade.zip")
    thumbs, usados = [], {}
    with zipfile.ZipFile(zpath, "w", zipfile.ZIP_STORED) as z:       # sem compressão: o HTML lê direto
        for i, f in enumerate(progress.tqdm(arquivos, desc="Calculando profundidade")):
            path = f if isinstance(f, str) else f.name
            img = ImageOps.exif_transpose(Image.open(path)).convert("RGB")
            if max(img.size) > 4096:
                img.thumbnail((4096, 4096), Image.LANCZOS)
            d = predict(img, modelo, int(res), bool(tta))
            if refinar:
                g = cv2.cvtColor(np.asarray(img), cv2.COLOR_RGB2GRAY).astype(np.float32) / 255.0
                r = max(4, int(max(img.size) * 0.006))
                d = np.clip(guided_filter(g, d, r, 1e-4), 0, 1)
                d = norm01(d, 0.5, 99.5)
            d = d ** float(gamma)
            if invertir:
                d = 1.0 - d
            d8 = (d * 255 + 0.5).astype(np.uint8)
            stem = re.sub(r"[^\w\-]+", "_", os.path.splitext(os.path.basename(path))[0])
            usados[stem] = usados.get(stem, 0) + 1
            if usados[stem] > 1:
                stem += f"_{usados[stem]}"
            out = os.path.join(tmp, f"{stem}_depth.png")
            Image.fromarray(d8, "L").save(out)
            z.write(out, f"{stem}_depth.png")
            th = Image.fromarray(d8, "L"); th.thumbnail((512, 512))
            thumbs.append((th, stem))
    return thumbs, zpath, f"✔ {len(arquivos)} mapa(s) · {modelo} · entrada {int(res)} px"


# ---------- interface ----------
with gr.Blocks(title="Parallax Cine · Profundidade") as demo:
    gr.Markdown("## 🎞️ Parallax Cine · mapas de profundidade em lote\n"
                "Envie as imagens do episódio → baixe o ZIP → solte o ZIP junto com as imagens no `parallax_cine.html`. "
                "**Branco = perto, preto = longe.**")
    with gr.Row():
        with gr.Column():
            arq = gr.File(label="Imagens (até 24)", file_count="multiple", file_types=["image"], type="filepath")
            modelo = gr.Dropdown(list(MODELS), value=DEFAULT, label="Modelo")
            res = gr.Slider(518, 1022, value=756, step=14, label="Resolução de entrada (Depth Anything) — mais alto = mais detalhe, mais lento")
            with gr.Row():
                tta = gr.Checkbox(True, label="TTA (média com espelho)")
                refinar = gr.Checkbox(True, label="Refinar bordas com a imagem")
                invertir = gr.Checkbox(False, label="Inverter (se o mapa sair ao contrário)")
            gamma = gr.Slider(0.6, 1.6, value=1.0, step=0.05, label="Contraste da profundidade (gama)")
            ir = gr.Button("Gerar profundidade", variant="primary")
        with gr.Column():
            gal = gr.Gallery(label="Mapas", columns=3, height=420)
            zipo = gr.File(label="ZIP para o parallax_cine.html")
            msg = gr.Textbox(label="Status", interactive=False)
    ir.click(processar, [arq, modelo, res, tta, refinar, gamma, invertir], [gal, zipo, msg])

demo.queue(max_size=8).launch(theme=gr.themes.Soft())