File size: 15,984 Bytes
d105a2f
7902a33
3834fa9
d105a2f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33a464d
 
82f4850
 
520f981
fed9c2d
 
 
 
 
 
 
 
f35c7d2
7902a33
d105a2f
 
 
 
3a8c553
 
b699636
3a8c553
b699636
8604d83
2039c18
 
 
43b4a40
fed9c2d
520f981
d105a2f
 
 
 
2039c18
 
 
d105a2f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43b4a40
 
5ea89f5
43b4a40
77ca625
8604d83
43b4a40
 
 
 
8993d74
7902a33
 
10bf136
8993d74
2039c18
8993d74
 
 
0981906
7902a33
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10bf136
 
7902a33
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3d97d62
7902a33
 
3d97d62
7902a33
 
 
 
 
2039c18
d105a2f
 
 
 
 
 
 
 
 
 
 
 
7902a33
2039c18
 
d105a2f
 
 
 
 
 
 
 
fed9c2d
7902a33
 
fed9c2d
 
b966219
 
 
 
 
 
 
fed9c2d
 
3d97d62
fed9c2d
 
6d09891
2039c18
3d97d62
fed9c2d
7902a33
2039c18
5ea89f5
 
520f981
5ea89f5
 
 
 
0981906
7902a33
 
520f981
7902a33
 
 
 
 
 
 
 
0981906
7902a33
 
 
 
 
 
 
fed9c2d
 
 
d105a2f
 
 
3a8c553
d105a2f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7902a33
d105a2f
 
 
 
 
 
 
 
 
 
7902a33
 
 
 
 
 
 
 
 
 
 
3d97d62
7902a33
 
 
 
 
 
 
 
 
 
d105a2f
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
# import spaces


# import os
# import sys
# import subprocess
# import importlib.util


# #Installazione silenziosa C++
# if importlib.util.find_spec("torch_cluster") is None:
#     print("Downloading precompiled torch-cluster...")
#     subprocess.check_call([
#         sys.executable, "-m", "pip", "install", "torch-cluster", 
#         "-f", "https://data.pyg.org/whl/torch-2.11.0+cu121.html",
#         "--no-build-isolation"
#     ])

# import os
# import torch
# import gradio as gr
# from PIL import Image
# from pathlib import Path
# from huggingface_hub import hf_hub_download
# import lightning as L

# OUTPUT_DIR = Path("outputs")
# OUTPUT_DIR.mkdir(exist_ok=True)

# weight_file = "epoch=47-step=37544.ckpt"
# if not os.path.exists(weight_file):
#     print(f"Downloading {weight_file} from cloud...")
#     hf_hub_download(
#         repo_id="FedericoGiulio/loomnet",
#         repo_type="model",
#         filename=weight_file, 
#         local_dir="."
#     )

# GLOBAL_MODEL = None

# @spaces.GPU(duration=120)  
# def run_demo(image_path, elevation, seed, without_loomnet):
#     global GLOBAL_MODEL
    
#     import hydra
#     from loomnet.utils import load_config
#     from inference import prepare_inputs

#     try: 
   
#         L.seed_everything(int(seed), workers=True)

#         if GLOBAL_MODEL is None:
#             print("Initializing model...")
#             cfg = load_config("configs/baseline.yaml", cli_args=[])

#             _original_load = torch.load
#             def _safe_load(*args, **kwargs):
#                 kwargs['map_location'] = 'cpu'
#                 kwargs['weights_only'] = False
#                 return _original_load(*args, **kwargs)

#             torch.load = _safe_load
#             try:
#                 GLOBAL_MODEL = hydra.utils.instantiate(cfg.system)
#                 GLOBAL_MODEL.load_weights(weight_file)
#             finally:
#                 torch.load = _original_load

#             GLOBAL_MODEL = GLOBAL_MODEL.to("cuda").eval()

#         # Bypass per immagini di esempio in Gradio
#         if "gradio" in image_path or "tmp" in image_path:
#             nome_file = os.path.basename(image_path)
#             percorso_reale = os.path.abspath(os.path.join("examples", nome_file))
#             if os.path.exists(percorso_reale):
#                 image_path = percorso_reale

#         data = prepare_inputs(image_path, elevation, "ele30")
#         for k, v in data.items():
#             data[k] = v.unsqueeze(0).to("cuda")
#             if k not in ["k_near_indices"]: data[k] = data[k].float()

#         GLOBAL_MODEL.mv_model.without_loomnet = without_loomnet

#         with torch.no_grad():
#             images_pred = GLOBAL_MODEL._generate_images(data)

#         views_folder = str(OUTPUT_DIR / "views")
#         os.makedirs(views_folder, exist_ok=True)

#         image_list = []
#         for i, img in enumerate(images_pred[0]):
#             img_pil = Image.fromarray(img)
#             image_list.append(img_pil)
#             img_pil.save(os.path.join(views_folder, f"{i}.png"))

      
#         return image_list

#     except Exception as e_globale:
#         print(f"⚠️ ERRORE CRITICO INTERCETTATO NELLA FUNZIONE 2D: {e_globale}")
#         gr.Warning(f"Generazione fallita: {e_globale}")
#         return None

# def run_demo_safe(image_path, elevation, seed, without_loomnet_in):
#     """Wrapper per proteggere il flusso nel caso in cui fallisca l'allocazione GPU"""
#     try:
#         return run_demo(image_path, elevation, seed, without_loomnet_in)
#     except Exception as e:
#         print(f"⚠️ ERRORE CRITICO A LIVELLO GPU/SCHEDULER (2D): {e}")
#         gr.Warning(f"Generazione fallita: {e}")
#         return None


# with gr.Blocks() as demo:
#     with gr.Row():
#         with gr.Column():
#             img_in = gr.Image(type="filepath", label="Input Image", height=300)

#             # Blocco Esempi
#             examples_block = gr.Examples(
#                 examples=[
#                     "examples/1.png",
#                     "examples/2.jpg",
#                 ],
#                 inputs=img_in,
#                 label="Or choose a sample image:"
#             )

#             elevation_in = gr.Slider(-90, 90, value=12.0, label="Elevation of the input image")
#             seed_in = gr.Number(value=0, label="Seed")
#             without_loomnet_in = gr.Checkbox(label="Disable consistency mechanism (Useful for understanding LoomNet's contribution)", value=False)
#             btn = gr.Button("Generate", interactive=False)
            
#         with gr.Column():
#             out_gallery = gr.Gallery(
#                 label="Generated Views",
#                 columns=4,
#                 rows=4,
#                 object_fit="contain",
#                 height="auto"
#             )

  
#     LOCK_OUTPUTS = [btn, img_in, elevation_in, seed_in, examples_block.dataset]

#     def blocca_interfaccia():
#         return (
#             gr.update(interactive=False),  # btn
#             gr.update(interactive=False),  # img_in
#             gr.update(interactive=False),  # elevation_in
#             gr.update(interactive=False),  # seed_in
#             gr.update(visible=False),      # examples_block.dataset
#         )

#     def sblocca_dopo_immagini():
#         return (
#             gr.update(interactive=True),   # btn
#             gr.update(interactive=True),   # img_in
#             gr.update(interactive=True),   # elevation_in
#             gr.update(interactive=True),   # seed_in
#             gr.update(visible=True),       # examples_block.dataset
#         )


#     img_in.change(
#         fn=lambda x: gr.update(interactive=(x is not None)),
#         inputs=[img_in],
#         outputs=[btn]
#     )

   
#     btn.click(
#         fn=blocca_interfaccia,
#         inputs=[],
#         outputs=LOCK_OUTPUTS,
#         queue=False,
#         show_progress="hidden"
#     ).then(
#         fn=run_demo_safe, 
#         inputs=[img_in, elevation_in, seed_in, without_loomnet_in], 
#         outputs=[out_gallery] 
#     ).then(
#         fn=sblocca_dopo_immagini,
#         inputs=[],
#         outputs=LOCK_OUTPUTS,
#         queue=False,
#         show_progress="hidden"
#     )

# if __name__ == "__main__":
#     demo.launch(share=True)





import spaces
import sys
import subprocess
import importlib.util


#Installazione silenziosa C++
if importlib.util.find_spec("torch_cluster") is None:
    print("Downloading precompiled torch-cluster...")
    subprocess.check_call([
        sys.executable, "-m", "pip", "install", "torch-cluster", 
        "-f", "https://data.pyg.org/whl/torch-2.11.0+cu121.html",
        "--no-build-isolation"
    ])

import os


if importlib.util.find_spec("rembg") is None:
    print("Installazione di rembg...")
    subprocess.check_call([
        sys.executable, "-m", "pip", "install",
        "rembg", "onnxruntime-gpu"
    ])
    
import torch
import gradio as gr
from PIL import Image
from pathlib import Path
from huggingface_hub import hf_hub_download
import lightning as L


from rembg import remove, new_session
import numpy as np

OUTPUT_DIR = Path("outputs")
OUTPUT_DIR.mkdir(exist_ok=True)

_REMBG_SESSION = None
def get_rembg_session():
    global _REMBG_SESSION
    if _REMBG_SESSION is None:
        _REMBG_SESSION = new_session("birefnet-general")
    return _REMBG_SESSION


def has_removed_background(image: Image.Image, threshold: float = 0.10) -> bool:
    """True se l'immagine ha già una porzione significativa di alpha trasparente."""
    if image.mode != "RGBA":
        return False
    alpha = np.array(image.split()[-1])
    return (alpha < 10).mean() > threshold


def pad_to_square(image: Image.Image, fill=(0, 0, 0, 0)) -> Image.Image:
    """Aggiunge padding trasparente per rendere l'immagine quadrata, centrando il contenuto."""
    width, height = image.size
    if width == height:
        return image
    side = max(width, height)
    squared = Image.new("RGBA", (side, side), fill)
    offset = ((side - width) // 2, (side - height) // 2)
    squared.paste(image, offset, image)
    return squared


def remove_background_if_needed(image_path):
    """Rimuove lo sfondo (se presente) e rende l'immagine quadrata con padding trasparente."""
    if not image_path:
        return image_path

    img = Image.open(image_path).convert("RGBA")
    already_clean = has_removed_background(img)
    already_square = (img.width == img.height)

    if already_clean and already_square:
        return image_path

    if not already_clean:
        img = remove(img, session=get_rembg_session())

    img = pad_to_square(img)

    out_path = str(OUTPUT_DIR / "input_no_bg.png")
    img.save(out_path)
    return out_path



weight_file = "epoch=47-step=37544.ckpt"
if not os.path.exists(weight_file):
    print(f"Downloading {weight_file} from cloud...")
    hf_hub_download(
        repo_id="FedericoGiulio/loomnet",
        repo_type="model",
        filename=weight_file, 
        local_dir="."
    )

GLOBAL_MODEL = None

@spaces.GPU(duration=120)  
def run_demo(image_path, elevation, seed, without_loomnet):
    global GLOBAL_MODEL
    
    import hydra
    from loomnet.utils import load_config
    from inference import prepare_inputs

    try: 
   
        L.seed_everything(int(seed), workers=True)

        if GLOBAL_MODEL is None:
            print("Initializing model...")
            cfg = load_config("configs/baseline.yaml", cli_args=[])

            _original_load = torch.load
            def _safe_load(*args, **kwargs):
                kwargs['map_location'] = 'cpu'
                kwargs['weights_only'] = False
                return _original_load(*args, **kwargs)

            torch.load = _safe_load
            try:
                GLOBAL_MODEL = hydra.utils.instantiate(cfg.system)
                GLOBAL_MODEL.load_weights(weight_file)
            finally:
                torch.load = _original_load

            GLOBAL_MODEL = GLOBAL_MODEL.to("cuda").eval()

        # Bypass per immagini di esempio in Gradio
        if "gradio" in image_path or "tmp" in image_path:
            nome_file = os.path.basename(image_path)
            percorso_reale = os.path.abspath(os.path.join("examples", nome_file))
            if os.path.exists(percorso_reale):
                image_path = percorso_reale

        data = prepare_inputs(image_path, elevation, "ele30")
        for k, v in data.items():
            data[k] = v.unsqueeze(0).to("cuda")
            if k not in ["k_near_indices"]: data[k] = data[k].float()

        GLOBAL_MODEL.mv_model.without_loomnet = without_loomnet

        with torch.no_grad():
            images_pred = GLOBAL_MODEL._generate_images(data)

        views_folder = str(OUTPUT_DIR / "views")
        os.makedirs(views_folder, exist_ok=True)

        image_list = []
        for i, img in enumerate(images_pred[0]):
            img_pil = Image.fromarray(img)
            image_list.append(img_pil)
            img_pil.save(os.path.join(views_folder, f"{i}.png"))

      
        return image_list

    except Exception as e_globale:
        print(f"⚠️ ERRORE CRITICO INTERCETTATO NELLA FUNZIONE 2D: {e_globale}")
        gr.Warning(f"Generazione fallita: {e_globale}")
        return None

def run_demo_safe(image_path, elevation, seed, without_loomnet_in):
    """Wrapper per proteggere il flusso nel caso in cui fallisca l'allocazione GPU"""
    try:
        return run_demo(image_path, elevation, seed, without_loomnet_in)
    except Exception as e:
        print(f"⚠️ ERRORE CRITICO A LIVELLO GPU/SCHEDULER (2D): {e}")
        gr.Warning(f"Generazione fallita: {e}")
        return None


custom_css = """
#img-in-box.processing img {
    opacity: 0.4;
    animation: pulse-processing 1.2s ease-in-out infinite;
}

@keyframes pulse-processing {
    0%, 100% { opacity: 0.4; }
    50% { opacity: 0.85; }
}
"""

with gr.Blocks() as demo:
    with gr.Row():
        with gr.Column():
            img_in = gr.Image(
                type="filepath",
                label="Input Image",
                height=300,
                elem_id="img-in-box",
                image_mode=None,   # RGBA inferito solo per i PNG, RGB per gli altri formati
                format="png"
            )

            # Blocco Esempi
            examples_block = gr.Examples(
                examples=[
                    "examples/1.png",
                    "examples/2.jpg", #elevation 12
                    "examples/3.png",
                    "examples/4.png",
                    "examples/6.webp",
                    "examples/7.webp",
                    "examples/8.jpg",
                    "examples/9.jpg",
                ],
                inputs=img_in,
                label="Or choose a sample image:"
            )

            elevation_in = gr.Slider(-90, 90, value=12.0, label="Elevation of the input image")
            seed_in = gr.Number(value=0, label="Seed")
            without_loomnet_in = gr.Checkbox(label="Disable consistency mechanism (Useful for understanding LoomNet's contribution)", value=False)
            btn = gr.Button("Generate", interactive=False)
            
        with gr.Column():
            out_gallery = gr.Gallery(
                label="Generated Views",
                columns=4,
                rows=4,
                object_fit="contain",
                height="auto"
            )

  
    LOCK_OUTPUTS = [btn, img_in, elevation_in, seed_in, examples_block.dataset]

    def blocca_interfaccia():
        return (
            gr.update(interactive=False),  # btn
            gr.update(interactive=False),  # img_in
            gr.update(interactive=False),  # elevation_in
            gr.update(interactive=False),  # seed_in
            gr.update(visible=False),      # examples_block.dataset
        )

    def sblocca_dopo_immagini():
        return (
            gr.update(interactive=True),   # btn
            gr.update(interactive=True),   # img_in
            gr.update(interactive=True),   # elevation_in
            gr.update(interactive=True),   # seed_in
            gr.update(visible=True),       # examples_block.dataset
        )


    img_in.upload(
        fn=lambda: (
            gr.update(interactive=False),
            gr.update(label="Removing background...", elem_classes=["processing"])
        ),
        inputs=[],
        outputs=[btn, img_in],
        queue=False
    ).then(
        fn=remove_background_if_needed,
        inputs=[img_in],
        outputs=[img_in],
        show_progress="hidden"
    ).then(
        fn=lambda p: (
            gr.update(interactive=(p is not None)),
            gr.update(label="Input Image", elem_classes=[])
        ),
        inputs=[img_in],
        outputs=[btn, img_in],
        queue=False
    )

    examples_block.load_input_event.then(
        fn=lambda: (
            gr.update(interactive=False),
            gr.update(label="Rimozione sfondo in corso...", elem_classes=["processing"])
        ),
        inputs=[],
        outputs=[btn, img_in],
        queue=False
    ).then(
        fn=remove_background_if_needed,
        inputs=[img_in],
        outputs=[img_in],
        show_progress="hidden"
    ).then(
        fn=lambda p: (
            gr.update(interactive=(p is not None)),
            gr.update(label="Input Image", elem_classes=[])
        ),
        inputs=[img_in],
        outputs=[btn, img_in],
        queue=False
    )

   
    btn.click(
        fn=blocca_interfaccia,
        inputs=[],
        outputs=LOCK_OUTPUTS,
        queue=False,
        show_progress="hidden"
    ).then(
        fn=run_demo_safe, 
        inputs=[img_in, elevation_in, seed_in, without_loomnet_in], 
        outputs=[out_gallery] 
    ).then(
        fn=sblocca_dopo_immagini,
        inputs=[],
        outputs=LOCK_OUTPUTS,
        queue=False,
        show_progress="hidden"
    )

if __name__ == "__main__":
    demo.launch(share=True, css=custom_css)