File size: 49,362 Bytes
2891de7
4ac877f
2891de7
 
 
 
 
 
8362ace
 
 
 
 
 
 
 
 
99beccb
8362ace
 
 
 
5e7dd18
 
ac23084
 
 
 
a6e974e
ac23084
a6e974e
ac23084
 
 
1797675
ac23084
 
bd507dd
 
33de423
5e7dd18
 
ac23084
2891de7
4eef400
 
4ac877f
1797675
cb3f487
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2891de7
cb3f487
 
 
 
 
 
 
 
9b10e93
cb3f487
 
 
 
 
 
9b10e93
cb3f487
 
 
 
 
 
4ac877f
cb3f487
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ac23084
 
 
5e7dd18
ac23084
 
5e7dd18
ac23084
5e7dd18
ac23084
5e7dd18
ac23084
 
8362ace
 
 
 
 
 
 
 
 
eb62b92
ac23084
 
5e7dd18
ac23084
 
 
5e7dd18
ac23084
5e7dd18
 
ac23084
 
 
1797675
8362ace
1797675
ac23084
 
1797675
 
 
5e7dd18
1797675
5e7dd18
 
1797675
 
 
5e7dd18
 
 
 
1797675
 
 
ac23084
 
5e7dd18
 
 
 
ac23084
5e7dd18
1797675
5e7dd18
bd507dd
9b10e93
33de423
1797675
5e7dd18
 
 
1797675
 
 
33de423
 
5e7dd18
33de423
2891de7
 
 
 
 
 
 
 
1797675
 
 
5e7dd18
 
bd507dd
 
 
 
 
 
 
 
 
 
 
9b10e93
5e7dd18
 
bd507dd
5e7dd18
bd507dd
 
 
 
31d7902
5e7dd18
9b10e93
31d7902
 
5e7dd18
9b10e93
31d7902
 
5e7dd18
9b10e93
5e7dd18
31d7902
 
 
9b10e93
5e7dd18
 
31d7902
 
5e7dd18
31d7902
 
 
9b10e93
5e7dd18
 
31d7902
 
5e7dd18
31d7902
 
 
 
 
 
 
 
5e7dd18
 
31d7902
 
5e7dd18
 
bd507dd
ac23084
33de423
 
c9e392e
33de423
bda9780
33de423
 
 
5e7dd18
33de423
 
0f11d75
5e7dd18
 
ac23084
 
1797675
5e7dd18
ac23084
9b10e93
bd507dd
 
 
 
 
 
 
1797675
5e7dd18
bd507dd
9b10e93
bd507dd
 
 
 
 
 
 
1797675
5e7dd18
bd507dd
5e7dd18
bd507dd
 
 
 
 
 
 
 
 
 
5e7dd18
bd507dd
1797675
 
5e7dd18
1797675
5e7dd18
 
8ce4529
bd507dd
33de423
c825b23
5e7dd18
c825b23
33de423
 
5e7dd18
33de423
5e7dd18
33de423
 
 
 
9b10e93
33de423
 
 
 
 
9b10e93
33de423
 
5e7dd18
bda9780
33de423
 
 
5e7dd18
33de423
 
c825b23
5e7dd18
c825b23
 
 
5e7dd18
 
c825b23
 
 
5e7dd18
 
33de423
 
 
 
 
 
bda9780
1797675
5e7dd18
1797675
 
5e7dd18
 
 
1797675
cf601a2
2d8b03b
cf601a2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e46b077
cf601a2
 
 
 
 
 
 
 
e46b077
cf601a2
 
 
 
79febce
 
 
 
c8c0470
79febce
 
 
c8c0470
79febce
 
 
 
 
c8c0470
79febce
c8c0470
cccc7f5
35d232d
 
 
 
 
 
cf11167
35d232d
c2ee5af
35d232d
 
 
cf11167
35d232d
 
cf11167
c2ee5af
35d232d
c2ee5af
35d232d
 
 
 
 
 
85f06ad
bd507dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4ac877f
5e7dd18
bd507dd
5e7dd18
 
1797675
9b10e93
1797675
 
 
 
 
 
 
 
9b10e93
1797675
c9e392e
1797675
 
 
5e7dd18
bd507dd
1797675
 
 
5e7dd18
bd507dd
1797675
 
bd507dd
1797675
 
 
 
 
 
 
 
 
 
 
5e7dd18
1797675
9b10e93
1797675
bd507dd
 
 
 
 
 
 
9b10e93
bd507dd
1797675
bd507dd
 
 
0f11d75
bd507dd
 
1797675
bd507dd
 
c7230e1
1797675
9b10e93
1797675
 
5e7dd18
bd507dd
 
 
 
 
 
5e7dd18
 
1797675
2e1e83b
85f06ad
5e7dd18
85f06ad
 
5e7dd18
 
 
6077505
29c78f7
6077505
 
3a06c45
6077505
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2acde31
6077505
29c78f7
bb90730
29c78f7
6077505
 
 
 
 
29c78f7
6077505
 
 
 
 
 
 
 
 
29c78f7
6077505
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85f06ad
 
 
 
 
 
 
 
 
 
 
 
 
 
29c78f7
85f06ad
 
 
29c78f7
6077505
 
 
 
 
29c78f7
6077505
85f06ad
2e1e83b
85f06ad
5e7dd18
 
 
 
 
 
 
 
 
 
9b10e93
5e7dd18
9b10e93
5e7dd18
 
 
 
 
 
 
 
85f06ad
 
9b10e93
1797675
85f06ad
1259f38
 
85f06ad
 
 
 
 
 
1259f38
8b8ae24
 
 
a600797
8b8ae24
1259f38
9b10e93
 
bd507dd
1259f38
 
 
85f06ad
 
1259f38
 
 
 
 
85f06ad
1259f38
 
 
 
85f06ad
1259f38
 
 
 
 
 
 
cf48f76
1259f38
33ef6a8
 
1259f38
 
 
 
 
415e712
d178c3a
 
bd507dd
cf601a2
1259f38
f70421a
 
 
 
53be96b
 
f70421a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53be96b
f70421a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53be96b
 
 
 
f70421a
53be96b
 
f70421a
 
53be96b
f70421a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0d469b1
f70421a
 
 
 
 
 
 
 
 
 
53be96b
f70421a
53be96b
f70421a
 
 
53be96b
 
f70421a
53be96b
f70421a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53be96b
f70421a
 
 
53be96b
 
f70421a
53be96b
f70421a
53be96b
 
 
 
 
f70421a
53be96b
f70421a
 
 
 
 
 
 
 
 
 
53be96b
f70421a
53be96b
 
 
 
 
 
 
f70421a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53be96b
 
 
 
 
 
 
 
 
f70421a
53be96b
 
 
 
f70421a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5e7dd18
 
 
 
bd507dd
53be96b
 
 
 
 
 
c344381
bd507dd
85f06ad
 
bd507dd
85f06ad
 
 
31d7902
bd507dd
5e7dd18
 
 
ac23084
53be96b
1797675
85f06ad
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
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
# ltx_server.py — VideoService (beta 1.1)
# Sempre output_type="latent"; no final: VAE (bloco inteiro) → pixels → MP4.
# Ignora UserWarning/FutureWarning e injeta VAE no manager com dtype/device corretos.

# --- 0. WARNINGS E AMBIENTE ---
import warnings
warnings.filterwarnings("ignore", category=UserWarning)
warnings.filterwarnings("ignore", category=FutureWarning)
warnings.filterwarnings("ignore", message=".*")

from huggingface_hub import logging

logging.set_verbosity_error()
logging.set_verbosity_warning()
logging.set_verbosity_info()
logging.set_verbosity_debug()


LTXV_DEBUG=1
LTXV_FRAME_LOG_EVERY=8



# --- 1. IMPORTAÇÕES ---
import torch
import numpy as np
import random
import os
import shlex
import yaml
from typing import List, Dict
from pathlib import Path
import imageio
import tempfile
from huggingface_hub import hf_hub_download
import sys
import subprocess
import gc
import shutil
import contextlib
import time
import traceback

# Singletons (versões simples)
from managers.vae_manager import vae_manager_singleton
from tools.video_encode_tool import video_encode_tool_singleton

# --- 2. GERENCIAMENTO DE DEPENDÊNCIAS E SETUP ---
def _query_gpu_processes_via_nvml(device_index: int) -> List[Dict]:
    try:
        import psutil
        import pynvml as nvml
        nvml.nvmlInit()
        handle = nvml.nvmlDeviceGetHandleByIndex(device_index)
        try:
            procs = nvml.nvmlDeviceGetComputeRunningProcesses_v3(handle)
        except Exception:
            procs = nvml.nvmlDeviceGetComputeRunningProcesses(handle)
        results = []
        for p in procs:
            pid = int(p.pid)
            used_mb = None
            try:
                if getattr(p, "usedGpuMemory", None) is not None and p.usedGpuMemory not in (0,):
                    used_mb = max(0, int(p.usedGpuMemory) // (1024 * 1024))
            except Exception:
                used_mb = None
            name = "unknown"
            user = "unknown"
            try:
                import psutil
                pr = psutil.Process(pid)
                name = pr.name()
                user = pr.username()
            except Exception:
                pass
            results.append({"pid": pid, "name": name, "user": user, "used_mb": used_mb})
        nvml.nvmlShutdown()
        return results
    except Exception:
        return []

def _query_gpu_processes_via_nvidiasmi(device_index: int) -> List[Dict]:
    cmd = f"nvidia-smi -i {device_index} --query-compute-apps=pid,process_name,used_memory --format=csv,noheader,nounits"
    try:
        out = subprocess.check_output(shlex.split(cmd), stderr=subprocess.STDOUT, text=True, timeout=2.0)
    except Exception:
        return []
    results = []
    for line in out.strip().splitlines():
        parts = [p.strip() for p in line.split(",")]
        if len(parts) >= 3:
            try:
                pid = int(parts[0]); name = parts[1]; used_mb = int(parts[2])
                user = "unknown"
                try:
                    import psutil
                    pr = psutil.Process(pid)
                    user = pr.username()
                except Exception:
                    pass
                results.append({"pid": pid, "name": name, "user": user, "used_mb": used_mb})
            except Exception:
                continue
    return results

def _gpu_process_table(processes: List[Dict], current_pid: int) -> str:
    if not processes:
        return "  - Processos ativos: (nenhum)\n"
    processes = sorted(processes, key=lambda x: (x.get("used_mb") or 0), reverse=True)
    lines = ["  - Processos ativos (PID | USER | NAME | VRAM MB):"]
    for p in processes:
        star = "*" if p["pid"] == current_pid else " "
        used_str = str(p["used_mb"]) if p.get("used_mb") is not None else "N/A"
        lines.append(f"    {star} {p['pid']} | {p['user']} | {p['name']} | {used_str}")
    return "\n".join(lines) + "\n"

def run_setup():
    setup_script_path = "setup.py"
    if not os.path.exists(setup_script_path):
        print("[DEBUG] 'setup.py' não encontrado. Pulando clonagem de dependências.")
        return
    try:
        print("[DEBUG] Executando setup.py para dependências...")
        subprocess.run([sys.executable, setup_script_path], check=True)
        print("[DEBUG] Setup concluído com sucesso.")
    except subprocess.CalledProcessError as e:
        print(f"[DEBUG] ERRO no setup.py (code {e.returncode}). Abortando.")
        sys.exit(1)

from api.ltx.inference import (
    create_ltx_video_pipeline,
    create_latent_upsampler,
    load_image_to_tensor_with_resize_and_crop,
    seed_everething,
    calculate_padding,
    load_media_file,
)

DEPS_DIR = Path("/data")
LTX_VIDEO_REPO_DIR = DEPS_DIR / "LTX-Video"
if not LTX_VIDEO_REPO_DIR.exists():
    print(f"[DEBUG] Repositório não encontrado em {LTX_VIDEO_REPO_DIR}. Rodando setup...")
    run_setup()

def add_deps_to_path():
    repo_path = str(LTX_VIDEO_REPO_DIR.resolve())
    if str(LTX_VIDEO_REPO_DIR.resolve()) not in sys.path:
        sys.path.insert(0, repo_path)
        print(f"[DEBUG] Repo adicionado ao sys.path: {repo_path}")

add_deps_to_path()

# --- 3. IMPORTAÇÕES ESPECÍFICAS DO MODELO ---

from ltx_video.pipelines.pipeline_ltx_video import ConditioningItem, LTXMultiScalePipeline
from ltx_video.utils.skip_layer_strategy import SkipLayerStrategy

# --- 4. FUNÇÕES HELPER DE LOG ---
def log_tensor_info(tensor, name="Tensor"):
    if not isinstance(tensor, torch.Tensor):
        print(f"\n[INFO] '{name}' não é tensor.")
        return
    print(f"\n--- Tensor: {name} ---")
    print(f"  - Shape: {tuple(tensor.shape)}")
    print(f"  - Dtype: {tensor.dtype}")
    print(f"  - Device: {tensor.device}")
    if tensor.numel() > 0:
        try:
            print(f"  - Min: {tensor.min().item():.4f}  Max: {tensor.max().item():.4f}  Mean: {tensor.mean().item():.4f}")
        except Exception:
            pass
    print("------------------------------------------\n")

# --- 5. CLASSE PRINCIPAL DO SERVIÇO ---
class VideoService:
    def __init__(self):
        t0 = time.perf_counter()
        print("[DEBUG] Inicializando VideoService...")
        self.debug = os.getenv("LTXV_DEBUG", "1") == "1"
        self.frame_log_every = int(os.getenv("LTXV_FRAME_LOG_EVERY", "8"))
        self.config = self._load_config()
        print(f"[DEBUG] Config carregada (precision={self.config.get('precision')}, sampler={self.config.get('sampler')})")
        self.device = "cuda" if torch.cuda.is_available() else "cpu"
        print(f"[DEBUG] Device selecionado: {self.device}")
        self.last_memory_reserved_mb = 0.0
        self._tmp_dirs = set(); self._tmp_files = set(); self._last_outputs = []

        self.pipeline, self.latent_upsampler = self._load_models()
        print(f"[DEBUG] Pipeline e Upsampler carregados. Upsampler ativo? {bool(self.latent_upsampler)}")

        print(f"[DEBUG] Movendo modelos para {self.device}...")
        self.pipeline.to(self.device)
        if self.latent_upsampler:
            self.latent_upsampler.to(self.device)

        self._apply_precision_policy()
        print(f"[DEBUG] runtime_autocast_dtype = {getattr(self, 'runtime_autocast_dtype', None)}")

        # Injeta pipeline/vae no manager (impede vae=None)
        vae_manager_singleton.attach_pipeline(
            self.pipeline,
            device=self.device,
            autocast_dtype=self.runtime_autocast_dtype
        )
        print(f"[DEBUG] VAE manager conectado: has_vae={hasattr(self.pipeline, 'vae')} device={self.device}")

        if self.device == "cuda":
            torch.cuda.empty_cache()
            self._log_gpu_memory("Após carregar modelos")

        print(f"[DEBUG] VideoService pronto. boot_time={time.perf_counter()-t0:.3f}s")

    def _log_gpu_memory(self, stage_name: str):
        if self.device != "cuda":
            return
        device_index = torch.cuda.current_device() if torch.cuda.is_available() else 0
        current_reserved_b = torch.cuda.memory_reserved(device_index)
        current_reserved_mb = current_reserved_b / (1024 ** 2)
        total_memory_b = torch.cuda.get_device_properties(device_index).total_memory
        total_memory_mb = total_memory_b / (1024 ** 2)
        peak_reserved_mb = torch.cuda.max_memory_reserved(device_index) / (1024 ** 2)
        delta_mb = current_reserved_mb - getattr(self, "last_memory_reserved_mb", 0.0)
        processes = _query_gpu_processes_via_nvml(device_index) or _query_gpu_processes_via_nvidiasmi(device_index)
        print(f"\n--- [LOG GPU] {stage_name} (cuda:{device_index}) ---")
        print(f"  - Reservado: {current_reserved_mb:.2f} MB / {total_memory_mb:.2f} MB  (Δ={delta_mb:+.2f} MB)")
        if peak_reserved_mb > getattr(self, "last_memory_reserved_mb", 0.0):
            print(f"  - Pico reservado (nesta fase): {peak_reserved_mb:.2f} MB")
        print(_gpu_process_table(processes, os.getpid()), end="")
        print("--------------------------------------------------\n")
        self.last_memory_reserved_mb = current_reserved_mb

    def _register_tmp_dir(self, d: str):
        if d and os.path.isdir(d):
            self._tmp_dirs.add(d); print(f"[DEBUG] Registrado tmp dir: {d}")

    def _register_tmp_file(self, f: str):
        if f and os.path.exists(f):
            self._tmp_files.add(f); print(f"[DEBUG] Registrado tmp file: {f}")

    def finalize(self, keep_paths=None, extra_paths=None, clear_gpu=True):
        print("[DEBUG] Finalize: iniciando limpeza...")
        keep = set(keep_paths or []); extras = set(extra_paths or [])
        removed_files = 0
        for f in list(self._tmp_files | extras):
            try:
                if f not in keep and os.path.isfile(f):
                    os.remove(f); removed_files += 1; print(f"[DEBUG] Removido arquivo tmp: {f}")
            except Exception as e:
                print(f"[DEBUG] Falha removendo arquivo {f}: {e}")
            finally:
                self._tmp_files.discard(f)
        removed_dirs = 0
        for d in list(self._tmp_dirs):
            try:
                if d not in keep and os.path.isdir(d):
                    shutil.rmtree(d, ignore_errors=True); removed_dirs += 1; print(f"[DEBUG] Removido diretório tmp: {d}")
            except Exception as e:
                print(f"[DEBUG] Falha removendo diretório {d}: {e}")
            finally:
                self._tmp_dirs.discard(d)
        print(f"[DEBUG] Finalize: arquivos removidos={removed_files}, dirs removidos={removed_dirs}")
        gc.collect()
        try:
            if clear_gpu and torch.cuda.is_available():
                torch.cuda.empty_cache()
                try:
                    torch.cuda.ipc_collect()
                except Exception:
                    pass
        except Exception as e:
            print(f"[DEBUG] Finalize: limpeza GPU falhou: {e}")
        try:
            self._log_gpu_memory("Após finalize")
        except Exception as e:
            print(f"[DEBUG] Log GPU pós-finalize falhou: {e}")

    def _load_config(self):
        base = LTX_VIDEO_REPO_DIR / "configs"
        candidates = [
            base / "ltxv-13b-0.9.8-dev-fp8.yaml",
            base / "ltxv-13b-0.9.8-distilled-fp8.yaml",
            base / "ltxv-13b-0.9.8-distilled.yaml",
        ]
        for cfg in candidates:
            if cfg.exists():
                print(f"[DEBUG] Config selecionada: {cfg}")
                with open(cfg, "r") as file:
                    return yaml.safe_load(file)
        cfg = base / "ltxv-13b-0.9.8-distilled-fp8.yaml"
        print(f"[DEBUG] Config fallback: {cfg}")
        with open(cfg, "r") as file:
            return yaml.safe_load(file)

    def _load_models(self):
        t0 = time.perf_counter()
        LTX_REPO = "Lightricks/LTX-Video"
        print("[DEBUG] Baixando checkpoint principal...")
        distilled_model_path = hf_hub_download(
            repo_id=LTX_REPO,
            filename=self.config["checkpoint_path"],
            local_dir=os.getenv("HF_HOME"),
            cache_dir=os.getenv("HF_HOME_CACHE"),
            token=os.getenv("HF_TOKEN"),
        )
        self.config["checkpoint_path"] = distilled_model_path
        print(f"[DEBUG] Checkpoint em: {distilled_model_path}")

        print("[DEBUG] Baixando upscaler espacial...")
        spatial_upscaler_path = hf_hub_download(
            repo_id=LTX_REPO,
            filename=self.config["spatial_upscaler_model_path"],
            local_dir=os.getenv("HF_HOME"),
            cache_dir=os.getenv("HF_HOME_CACHE"),
            token=os.getenv("HF_TOKEN"),
        )
        self.config["spatial_upscaler_model_path"] = spatial_upscaler_path
        print(f"[DEBUG] Upscaler em: {spatial_upscaler_path}")

        print("[DEBUG] Construindo pipeline...")
        pipeline = create_ltx_video_pipeline(
            ckpt_path=self.config["checkpoint_path"],
            precision=self.config["precision"],
            text_encoder_model_name_or_path=self.config["text_encoder_model_name_or_path"],
            sampler=self.config["sampler"],
            device="cpu",
            enhance_prompt=False,
            prompt_enhancer_image_caption_model_name_or_path=self.config["prompt_enhancer_image_caption_model_name_or_path"],
            prompt_enhancer_llm_model_name_or_path=self.config["prompt_enhancer_llm_model_name_or_path"],
        )
        print("[DEBUG] Pipeline pronto.")

        latent_upsampler = None
        if self.config.get("spatial_upscaler_model_path"):
            print("[DEBUG] Construindo latent_upsampler...")
            latent_upsampler = create_latent_upsampler(self.config["spatial_upscaler_model_path"], device="cpu")
            print("[DEBUG] Upsampler pronto.")
        print(f"[DEBUG] _load_models() tempo total={time.perf_counter()-t0:.3f}s")
        return pipeline, latent_upsampler

    def _promote_fp8_weights_to_bf16(self, module):
        if not isinstance(module, torch.nn.Module):
            print("[DEBUG] Promoção FP8→BF16 ignorada: alvo não é nn.Module.")
            return
        f8 = getattr(torch, "float8_e4m3fn", None)
        if f8 is None:
            print("[DEBUG] torch.float8_e4m3fn indisponível.")
            return
        p_cnt = b_cnt = 0
        for _, p in module.named_parameters(recurse=True):
            try:
                if p.dtype == f8:
                    with torch.no_grad():
                        p.data = p.data.to(torch.bfloat16); p_cnt += 1
            except Exception:
                pass
        for _, b in module.named_buffers(recurse=True):
            try:
                if hasattr(b, "dtype") and b.dtype == f8:
                    b.data = b.data.to(torch.bfloat16); b_cnt += 1
            except Exception:
                pass
        print(f"[DEBUG] FP8→BF16: params_promoted={p_cnt}, buffers_promoted={b_cnt}")

    def _apply_precision_policy(self):
        prec = str(self.config.get("precision", "")).lower()
        self.runtime_autocast_dtype = torch.float32
        print(f"[DEBUG] Aplicando política de precisão: {prec}")
        if prec == "float8_e4m3fn":
            self.runtime_autocast_dtype = torch.bfloat16
            force_promote = os.getenv("LTXV_FORCE_BF16_ON_FP8", "0") == "1"
            print(f"[DEBUG] FP8 detectado. force_promote={force_promote}")
            if force_promote and hasattr(torch, "float8_e4m3fn"):
                try:
                    self._promote_fp8_weights_to_bf16(self.pipeline)
                except Exception as e:
                    print(f"[DEBUG] Promoção FP8→BF16 na pipeline falhou: {e}")
                try:
                    if self.latent_upsampler:
                        self._promote_fp8_weights_to_bf16(self.latent_upsampler)
                except Exception as e:
                    print(f"[DEBUG] Promoção FP8→BF16 no upsampler falhou: {e}")
        elif prec == "bfloat16":
            self.runtime_autocast_dtype = torch.bfloat16
        elif prec == "mixed_precision":
            self.runtime_autocast_dtype = torch.float16
        else:
            self.runtime_autocast_dtype = torch.float32

    def _prepare_conditioning_tensor(self, filepath, height, width, padding_values):
        print(f"[DEBUG] Carregando condicionamento: {filepath}")
        tensor = load_image_to_tensor_with_resize_and_crop(filepath, height, width)
        tensor = torch.nn.functional.pad(tensor, padding_values)
        out = tensor.to(self.device, dtype=self.runtime_autocast_dtype) if self.device == "cuda" else tensor.to(self.device)
        print(f"[DEBUG] Cond shape={tuple(out.shape)} dtype={out.dtype} device={out.device}")
        return out


    def _dividir_latentes_em_partes(self, latents_brutos, quantidade: int):
        """
        Divide um tensor de latentes em `quantidade` partes e retorna uma lista de clones.
        
        Args:
            latents_brutos: tensor [B, C, T, H, W]
            quantidade: número de partes que queremos dividir
        
        Returns:
            List[Tensor]: lista de `quantidade` partes, cada uma cloneada
        """
        total = latents_brutos.shape[2]  # dimensão temporal
        partes = []
    
        if quantidade <= 1 or quantidade > total:
            return [latents_brutos.clone()]
    
        # calcular tamanho aproximado de cada parte
        step = total // quantidade
        overlap = 0  # sobreposição mínima de 1 frame entre partes
    
        for i in range(quantidade):
            start = i * step
            end = start + step
            if i == quantidade - 1:
                end = total  # última parte vai até o final
            else:
                end += overlap  # sobreposição
            parte = latents_brutos[:, :, start-1:end+1, :, :].clone()
            partes.append(parte)
    
        return partes


    def dividir_latentes(latents_brutos):
        total = latents_brutos.shape[2]  # dimensão temporal (latentes)
    
        if total % 2 == 1:  # ÍMPAR
           cut = total // 2
           primeira = latents_brutos[:, :, :cut+1, :, :].clone()
           segunda  = latents_brutos[:, :, cut:, :, :].clone()
        else:  # PAR
           cut = total // 2
           # primeira parte até o meio, mas o último frame deve ser ajustado
           primeira = latents_brutos[:, :, :cut+1, :, :].clone()
           segunda  = latents_brutos[:, :, cut:, :, :].clone()

        return primeira, segunda
    
        
    def _concat_mp4s_no_reencode(self, mp4_list: List[str], out_path: str):
        """
        Concatena múltiplos MP4s sem reencode usando o demuxer do ffmpeg.
        ATENÇÃO: todos os arquivos precisam ter mesmo codec, fps, resolução etc.
        """
        if not mp4_list or len(mp4_list) < 2:
            raise ValueError("Forneça pelo menos dois arquivos MP4 para concatenar.")
    
        # Cria lista temporária para o ffmpeg
        with tempfile.NamedTemporaryFile("w", delete=False, suffix=".txt") as f:
            for mp4 in mp4_list:
                f.write(f"file '{os.path.abspath(mp4)}'\n")
            list_path = f.name
    
        cmd = f"ffmpeg -y -f concat -safe 0 -i {list_path} -c copy {out_path}"
        print(f"[DEBUG] Concat: {cmd}")
    
        try:
            subprocess.check_call(shlex.split(cmd))
        finally:
            try:
                os.remove(list_path)
            except Exception:
                pass  

                

    def generate(
        self,
        prompt,
        negative_prompt,
        mode="text-to-video",
        start_image_filepath=None,
        middle_image_filepath=None,
        middle_frame_number=None,
        middle_image_weight=1.0,
        end_image_filepath=None,
        end_image_weight=1.0,
        input_video_filepath=None,
        height=512,
        width=704,
        duration=2.0,
        frames_to_use=9,
        seed=42,
        randomize_seed=True,
        guidance_scale=3.0,
        improve_texture=True,
        progress_callback=None,
        # Sempre latent → VAE → MP4 (simples)
        external_decode=True,
    ):
        t_all = time.perf_counter()
        print(f"[DEBUG] generate() begin mode={mode} external_decode={external_decode} improve_texture={improve_texture}")
        if self.device == "cuda":
            torch.cuda.empty_cache(); torch.cuda.reset_peak_memory_stats()
        self._log_gpu_memory("Início da Geração")

        if mode == "image-to-video" and not start_image_filepath:
            raise ValueError("A imagem de início é obrigatória para o modo image-to-video")
        if mode == "video-to-video" and not input_video_filepath:
            raise ValueError("O vídeo de entrada é obrigatório para o modo video-to-video")

        used_seed = random.randint(0, 2**32 - 1) if randomize_seed else int(seed)
        seed_everething(used_seed); print(f"[DEBUG] Seed usado: {used_seed}")

        FPS = 24.0; MAX_NUM_FRAMES = 2570
        target_frames_rounded = round(duration * FPS)
        n_val = round((float(target_frames_rounded) - 1.0) / 8.0)
        actual_num_frames = max(9, min(MAX_NUM_FRAMES, int(n_val * 8 + 1)))
        print(f"[DEBUG] Frames alvo: {actual_num_frames} (dur={duration}s @ {FPS}fps)")

        height_padded = ((height - 1) // 32 + 1) * 32
        width_padded = ((width - 1) // 32 + 1) * 32
        padding_values = calculate_padding(height, width, height_padded, width_padded)
        print(f"[DEBUG] Dimensões: ({height},{width}) -> pad ({height_padded},{width_padded}); padding={padding_values}")

        generator = torch.Generator(device=self.device).manual_seed(used_seed)
        conditioning_items = []

        if mode == "image-to-video":
            start_tensor = self._prepare_conditioning_tensor(start_image_filepath, height, width, padding_values)
            conditioning_items.append(ConditioningItem(start_tensor, 0, 1.0))
            if middle_image_filepath and middle_frame_number is not None:
                middle_tensor = self._prepare_conditioning_tensor(middle_image_filepath, height, width, padding_values)
                safe_middle_frame = max(0, min(int(middle_frame_number), actual_num_frames - 1))
                conditioning_items.append(ConditioningItem(middle_tensor, safe_middle_frame, float(middle_image_weight)))
            if end_image_filepath:
                end_tensor = self._prepare_conditioning_tensor(end_image_filepath, height, width, padding_values)
                last_frame_index = actual_num_frames - 1
                conditioning_items.append(ConditioningItem(end_tensor, last_frame_index, float(end_image_weight)))
            print(f"[DEBUG] Conditioning items: {len(conditioning_items)}")

        # Sempre pedimos latentes (simples)
        call_kwargs = {
            "prompt": prompt,
            "negative_prompt": negative_prompt,
            "height": height_padded,
            "width": width_padded,
            "num_frames": actual_num_frames,
            "frame_rate": int(FPS),
            "generator": generator,
            "output_type": "latent",
            "conditioning_items": conditioning_items if conditioning_items else None,
            "media_items": None,
            "decode_timestep": self.config["decode_timestep"],
            "decode_noise_scale": self.config["decode_noise_scale"],
            "stochastic_sampling": self.config["stochastic_sampling"],
            "image_cond_noise_scale": 0.01,
            "is_video": True,
            "vae_per_channel_normalize": True,
            "mixed_precision": (self.config["precision"] == "mixed_precision"),
            "offload_to_cpu": False,
            "enhance_prompt": False,
            "skip_layer_strategy": SkipLayerStrategy.AttentionValues,
        }
        print(f"[DEBUG] output_type={call_kwargs['output_type']} skip_layer_strategy={call_kwargs['skip_layer_strategy']}")

        if mode == "video-to-video":
            media = load_media_file(
                media_path=input_video_filepath,
                height=height,
                width=width,
                max_frames=int(frames_to_use),
                padding=padding_values,
            ).to(self.device)
            call_kwargs["media_items"] = media
            print(f"[DEBUG] media_items shape={tuple(media.shape)}")

        latents = None
        
        try:
            ctx = torch.autocast(device_type="cuda", dtype=self.runtime_autocast_dtype) if self.device == "cuda" else contextlib.nullcontext()

            if improve_texture:
                if not self.latent_upsampler:
                    raise ValueError("Upscaler espacial não carregado.")
                
                # --- PASSO 1: GERAÇÃO DE LATENTES EM BAIXA RESOLUÇÃO ---
                print("[DEBUG] Multi-escala: Iniciando Passo 1 (geração de latentes base).")
                
                first_pass_args = self.config.get("first_pass", {}).copy()
                first_pass_kwargs = call_kwargs.copy()
                first_pass_kwargs.update({
                    "guidance_scale": float(guidance_scale),
                    "stg_scale": first_pass_args.get("stg_scale"),
                    "rescaling_scale": first_pass_args.get("rescaling_scale"),
                    "skip_block_list": first_pass_args.get("skip_block_list"),
                })
                schedule = first_pass_args.get("timesteps") or first_pass_args.get("guidance_timesteps")
                if schedule:
                    first_pass_kwargs["timesteps"] = schedule
                    first_pass_kwargs["guidance_timesteps"] = schedule
                
                downscale_factor = self.config.get("downscale_factor", 2)
                original_height = first_pass_kwargs["height"]
                original_width = first_pass_kwargs["width"]
                divisor = 24

                target_height_p1 = original_height // downscale_factor
                height_p1 = round(target_height_p1 / divisor) * divisor
                if height_p1 == 0: height_p1 = divisor
                first_pass_kwargs["height"] = height_p1

                target_width_p1 = original_width // downscale_factor
                width_p1 = round(target_width_p1 / divisor) * divisor
                if width_p1 == 0: width_p1 = divisor
                first_pass_kwargs["width"] = width_p1
                
                print(f"[DEBUG] Passo 1: Dimensões reduzidas e ajustadas para {height_p1}x{width_p1}")
                
                with ctx:
                    first_pass_result = self.pipeline(**first_pass_kwargs)
                    
                latents_low_res = first_pass_result.images
                log_tensor_info(latents_low_res, "Latentes (Passo 1)")
                
                del first_pass_result
                gc.collect()
                if self.device == "cuda": torch.cuda.empty_cache()

                # --- PASSO INTERMEDIÁRIO: UPSCALE DOS LATENTES ---
                print("[DEBUG] Multi-escala: Fazendo upscale dos latentes com latent_upsampler.")
                with ctx:
                    latents_high_res = self.latent_upsampler(latents_low_res)
                
                log_tensor_info(latents_high_res, "Latentes (Pós-Upscale)")
                del latents_low_res
                gc.collect()
                if self.device == "cuda": torch.cuda.empty_cache()
                
                # --- PASSO 2: REFINAMENTO EM ALTA RESOLUÇÃO ---
                print("[DEBUG] Multi-escala: Iniciando Passo 2 (refinamento em alta resolução).")
                second_pass_args = self.config.get("second_pass", {}).copy()
                second_pass_kwargs = call_kwargs.copy()

                height_p2 = height_p1 * 2
                width_p2 = width_p1 * 2
                second_pass_kwargs["height"] = height_p2
                second_pass_kwargs["width"] = width_p2
                print(f"[DEBUG] Passo 2: Dimensões definidas para {height_p2}x{width_p2} para corresponder ao upscale.")

                second_pass_kwargs.update({
                    "guidance_scale": float(guidance_scale),
                    "stg_scale": second_pass_args.get("stg_scale"),
                    "rescaling_scale": second_pass_args.get("rescaling_scale"),
                    "skip_block_list": second_pass_args.get("skip_block_list"),
                })
                
                schedule_p2 = second_pass_args.get("timesteps") or second_pass_args.get("guidance_timesteps")
                if schedule_p2:
                    timesteps_para_refinamento = schedule_p2
                    print(f"[DEBUG] Passo 2: Usando {len(timesteps_para_refinamento)} timesteps pré-definidos do config para refinamento.")
                else:
                    strength_p2 = second_pass_args.get("strength", second_pass_args.get("denoising_strength", 0.4))
                    num_steps_passo2_total = second_pass_args.get("num_inference_steps", 20)
                    
                    self.pipeline.scheduler.set_timesteps(num_steps_passo2_total, device=self.device)
                    todos_os_timesteps_p2 = self.pipeline.scheduler.timesteps
                    
                    ponto_de_corte = int(len(todos_os_timesteps_p2) * (1.0 - strength_p2))
                    timesteps_para_refinamento = todos_os_timesteps_p2[ponto_de_corte:]
                    print(f"[DEBUG] Passo 2: Calculando {len(timesteps_para_refinamento)} timesteps manuais (strength ≈ {strength_p2})")

                second_pass_kwargs["timesteps"] = timesteps_para_refinamento
                
                if "strength" in second_pass_kwargs: del second_pass_kwargs["strength"]

                second_pass_kwargs["latents"] = latents_high_res
                
                with ctx:
                    second_pass_result = self.pipeline(**second_pass_kwargs)
                    
                latents = second_pass_result.images
                log_tensor_info(latents, "Latentes Finais (Passo 2)")

            else:
                # --- PASSO ÚNICO (SINGLE-PASS) ---
                single_pass_kwargs = call_kwargs.copy()
                first_pass_config = self.config.get("first_pass", {})
                single_pass_kwargs.update(
                    {
                        "guidance_scale": float(guidance_scale),
                        "stg_scale": first_pass_config.get("stg_scale"),
                        "rescaling_scale": first_pass_config.get("rescaling_scale"),
                        "skip_block_list": first_pass_config.get("skip_block_list"),
                    }
                )
                schedule = first_pass_config.get("timesteps") or first_pass_config.get("guidance_timesteps")
                if mode == "video-to-video":
                    schedule = [0.7]; print("[INFO] Modo video-to-video (etapa única): timesteps=[0.7]")
                if isinstance(schedule, (list, tuple)) and len(schedule) > 0:
                    single_pass_kwargs["timesteps"] = schedule
                    single_pass_kwargs["guidance_timesteps"] = schedule
                print(f"[DEBUG] Single-pass: timesteps_len={len(schedule) if schedule else 0}")

                print("\n[INFO] Executando pipeline de etapa única...")
                with ctx:
                    result = self.pipeline(**single_pass_kwargs)
                
                latents = result.images
                print(f"[DEBUG] Latentes (single-pass): shape={tuple(latents.shape)}")

            # --- DECODIFICAÇÃO E CODIFICAÇÃO DE VÍDEO FINAL ---
            
            latents_cpu = latents.detach().to("cpu", non_blocking=True)
            if self.device == "cuda":
                torch.cuda.empty_cache()
                try:
                    torch.cuda.ipc_collect()
                except Exception:
                    pass
                
            lat_a, lat_b = self._dividir_latentes(latents_cpu)
            lat_a1, lat_a2 = self._dividir_latentes(lat_a)
            lat_b1, lat_b2 = self._dividir_latentes(lat_b)
            
            latents_parts = [lat_a1, lat_a2, lat_b1, lat_b2]
            
            temp_dir = tempfile.mkdtemp(prefix="ltxv_"); self._register_tmp_dir(temp_dir)
            results_dir = "/app/output"; os.makedirs(results_dir, exist_ok=True)

            partes_mp4 = []
            par = 0
            
            for part in latents_parts:
                print(f"[DEBUG] Partição {par}: {tuple(part.shape)}")
                par = par + 1
                output_video_path = os.path.join(temp_dir, f"output_{used_seed}_{par}.mp4")
    
                print("[DEBUG] Decodificando bloco de latentes com VAE → tensor de pixels...")
                pixel_tensor = vae_manager_singleton.decode(
                    part.to(self.device, non_blocking=True),
                    decode_timestep=float(self.config.get("decode_timestep", 0.05))
                )
                log_tensor_info(pixel_tensor, "Pixel tensor (VAE saída)")
    
                print("[DEBUG] Codificando MP4 a partir do tensor de pixels...")
                video_encode_tool_singleton.save_video_from_tensor(
                    pixel_tensor,
                    output_video_path,
                    fps=call_kwargs["frame_rate"],
                    progress_callback=progress_callback
                )
    
                candidate = os.path.join(results_dir, f"output_par_{par}.mp4")
                try:
                    shutil.move(output_video_path, candidate)
                    final_output_path = candidate
                    print(f"[DEBUG] MP4 parte {par} movido para {final_output_path}")
                    partes_mp4.append(final_output_path)
                except Exception as e:
                    print(f"[DEBUG] Falha no move; usando tmp como final: {e}")

            final_concat = os.path.join(results_dir, f"concat_fim_{used_seed}.mp4")
            self._concat_mp4s_no_reencode(partes_mp4, final_concat)

            self._log_gpu_memory("Fim da Geração")
            return final_concat, used_seed
            
        except Exception as e:
            print("[DEBUG] EXCEÇÃO NA GERAÇÃO:")
            print("".join(traceback.format_exception(type(e), e, e.__traceback__)))
            raise


# ltx_server.py

    def generate(
        self,
        prompt,
        negative_prompt,
        mode="text-to-video",
        start_image_filepath=None,
        middle_image_filepath=None,
        middle_frame_number=None,
        middle_image_weight=1.0,
        end_image_filepath=None,
        end_image_weight=1.0,
        input_video_filepath=None,
        height=512,
        width=704,
        duration=2.0,
        frames_to_use=9,
        seed=42,
        randomize_seed=True,
        guidance_scale=3.0, # Valor de referência/fallback
        improve_texture=True,
        progress_callback=None,
        external_decode=True,
    ):
        t_all = time.perf_counter()
        print(f"[DEBUG] generate() begin mode={mode} external_decode={external_decode} improve_texture={improve_texture}")
        if self.device == "cuda":
            torch.cuda.empty_cache(); torch.cuda.reset_peak_memory_stats()
        self._log_gpu_memory("Início da Geração")

        if mode == "image-to-video" and not start_image_filepath:
            raise ValueError("A imagem de início é obrigatória para o modo image-to-video")
        if mode == "video-to-video" and not input_video_filepath:
            raise ValueError("O vídeo de entrada é obrigatório para o modo video-to-video")

        used_seed = random.randint(0, 2**32 - 1) if randomize_seed else int(seed)
        seed_everething(used_seed); print(f"[DEBUG] Seed usado: {used_seed}")

        FPS = 24.0; MAX_NUM_FRAMES = 2570
        target_frames_rounded = round(duration * FPS)
        n_val = round((float(target_frames_rounded) - 1.0) / 8.0)
        actual_num_frames = max(9, min(MAX_NUM_FRAMES, int(n_val * 8 + 1)))
        print(f"[DEBUG] Frames alvo: {actual_num_frames} (dur={duration}s @ {FPS}fps)")

        height_padded = ((height - 1) // 32 + 1) * 32
        width_padded = ((width - 1) // 32 + 1) * 32
        padding_values = calculate_padding(height, width, height_padded, width_padded)
        print(f"[DEBUG] Dimensões: ({height},{width}) -> pad ({height_padded},{width_padded}); padding={padding_values}")

        generator = torch.Generator(device=self.device).manual_seed(used_seed)
        conditioning_items = []

        if mode == "image-to-video":
            start_tensor = self._prepare_conditioning_tensor(start_image_filepath, height, width, padding_values)
            conditioning_items.append(ConditioningItem(start_tensor, 0, 1.0))
            if middle_image_filepath and middle_frame_number is not None:
                middle_tensor = self._prepare_conditioning_tensor(middle_image_filepath, height, width, padding_values)
                safe_middle_frame = max(0, min(int(middle_frame_number), actual_num_frames - 1))
                conditioning_items.append(ConditioningItem(middle_tensor, safe_middle_frame, float(middle_image_weight)))
            if end_image_filepath:
                end_tensor = self._prepare_conditioning_tensor(end_image_filepath, height, width, padding_values)
                last_frame_index = actual_num_frames - 1
                conditioning_items.append(ConditioningItem(end_tensor, last_frame_index, float(end_image_weight)))
            print(f"[DEBUG] Conditioning items: {len(conditioning_items)}")

        call_kwargs = {
            "prompt": prompt,
            "negative_prompt": negative_prompt,
            "height": height_padded,
            "width": width_padded,
            "num_frames": actual_num_frames,
            "frame_rate": int(FPS),
            "generator": generator,
            "output_type": "latent",
            "conditioning_items": conditioning_items if conditioning_items else None,
            "media_items": None,
            "decode_timestep": self.config.get("decode_timestep"),
            "decode_noise_scale": self.config.get("decode_noise_scale"),
            "stochastic_sampling": self.config.get("stochastic_sampling"),
            "image_cond_noise_scale": self.config.get("image_cond_noise_scale", 0.01),
            "is_video": True,
            "vae_per_channel_normalize": self.config.get("vae_per_channel_normalize", True),
            "mixed_precision": (self.config.get("precision") == "mixed_precision"),
            "offload_to_cpu": False,
            "enhance_prompt": False,
            "skip_layer_strategy": SkipLayerStrategy[self.config.get("stg_mode", "AttentionValues")],
        }
        print(f"[DEBUG] output_type={call_kwargs['output_type']} skip_layer_strategy={call_kwargs['skip_layer_strategy']}")

        if mode == "video-to-video":
            media = load_media_file(
                media_path=input_video_filepath,
                height=height,
                width=width,
                max_frames=int(frames_to_use),
                padding=padding_values,
            ).to(self.device)
            call_kwargs["media_items"] = media
            print(f"[DEBUG] media_items shape={tuple(media.shape)}")

        latents = None
        
        try:
            ctx = torch.autocast(device_type="cuda", dtype=self.runtime_autocast_dtype) if self.device == "cuda" else contextlib.nullcontext()

            if improve_texture:
                if not self.latent_upsampler:
                    raise ValueError("Upscaler espacial não carregado.")
                
                # --- PASSO 1: GERAÇÃO DE LATENTES EM BAIXA RESOLUÇÃO ---
                print("[DEBUG] Multi-escala: Iniciando Passo 1 (geração de latentes base).")
                
                first_pass_args = self.config.get("first_pass", {}).copy()
                first_pass_kwargs = call_kwargs.copy()

                first_pass_kwargs.update({
                    "guidance_scale": first_pass_args.get("guidance_scale", guidance_scale),
                    "stg_scale": first_pass_args.get("stg_scale"),
                    "rescaling_scale": first_pass_args.get("rescaling_scale"),
                    "skip_block_list": first_pass_args.get("skip_block_list"),
                    "guidance_timesteps": first_pass_args.get("guidance_timesteps"),
                    "timesteps": first_pass_args.get("timesteps")
                })
                print(f"[DEBUG] Passo 1: Parâmetros do config carregados: guidance_scale={first_pass_kwargs['guidance_scale']}, stg_scale={first_pass_kwargs['stg_scale']}")
                
                downscale_factor = self.config.get("downscale_factor", 2)
                original_height = first_pass_kwargs["height"]
                original_width = first_pass_kwargs["width"]
                divisor = 24
                target_height_p1 = original_height // downscale_factor
                height_p1 = round(target_height_p1 / divisor) * divisor
                if height_p1 == 0: height_p1 = divisor
                first_pass_kwargs["height"] = height_p1
                target_width_p1 = original_width // downscale_factor
                width_p1 = round(target_width_p1 / divisor) * divisor
                if width_p1 == 0: width_p1 = divisor
                first_pass_kwargs["width"] = width_p1
                print(f"[DEBUG] Passo 1: Dimensões reduzidas e ajustadas para {height_p1}x{width_p1}")
                
                with ctx:
                    first_pass_result = self.pipeline(**first_pass_kwargs)
                    
                latents_low_res = first_pass_result.images
                log_tensor_info(latents_low_res, "Latentes (Passo 1)")
                
                del first_pass_result
                gc.collect()
                if self.device == "cuda": torch.cuda.empty_cache()

                # --- PASSO INTERMEDIÁRIO: UPSCALE DOS LATENTES ---
                print("[DEBUG] Multi-escala: Fazendo upscale dos latentes com latent_upsampler.")
                with ctx:
                    latents_high_res = self.latent_upsampler(latents_low_res)
                
                log_tensor_info(latents_high_res, "Latentes (Pós-Upscale)")
                del latents_low_res
                gc.collect()
                if self.device == "cuda": torch.cuda.empty_cache()
                
                # --- PASSO 2: REFINAMENTO EM ALTA RESOLUÇÃO ---
                print("[DEBUG] Multi-escala: Iniciando Passo 2 (refinamento em alta resolução).")
                second_pass_args = self.config.get("second_pass", {}).copy()
                second_pass_kwargs = call_kwargs.copy()

                second_pass_kwargs.update({
                    "guidance_scale": second_pass_args.get("guidance_scale", guidance_scale),
                    "stg_scale": second_pass_args.get("stg_scale"),
                    "rescaling_scale": second_pass_args.get("rescaling_scale"),
                    "skip_block_list": second_pass_args.get("skip_block_list"),
                    "guidance_timesteps": second_pass_args.get("guidance_timesteps"),
                    "timesteps": second_pass_args.get("timesteps")
                })
                print(f"[DEBUG] Passo 2: Parâmetros do config carregados: guidance_scale={second_pass_kwargs['guidance_scale']}, stg_scale={second_pass_kwargs['stg_scale']}")
                
                height_p2 = height_p1 * 2
                width_p2 = width_p1 * 2
                second_pass_kwargs["height"] = height_p2
                second_pass_kwargs["width"] = width_p2
                print(f"[DEBUG] Passo 2: Dimensões definidas para {height_p2}x{width_p2}")
                
                second_pass_kwargs["latents"] = latents_high_res

                with ctx:
                    second_pass_result = self.pipeline(**second_pass_kwargs)
                    
                latents = second_pass_result.images
                log_tensor_info(latents, "Latentes Finais (Passo 2)")

            else:
                # --- PASSO ÚNICO (SINGLE-PASS) ---
                single_pass_kwargs = call_kwargs.copy()
                
                single_pass_kwargs.update({
                    "guidance_scale": self.config.get("guidance_scale", guidance_scale),
                    "stg_scale": self.config.get("stg_scale"),
                    "rescaling_scale": self.config.get("rescaling_scale"),
                    "skip_block_list": self.config.get("skip_block_list"),
                    "guidance_timesteps": self.config.get("guidance_timesteps"),
                    "timesteps": self.config.get("timesteps"),
                    "num_inference_steps": self.config.get("num_inference_steps", 20)
                })

                print("\n[INFO] Executando pipeline de etapa única...")
                with ctx:
                    result = self.pipeline(**single_pass_kwargs)
                
                latents = result.images
                print(f"[DEBUG] Latentes (single-pass): shape={tuple(latents.shape)}")

            # --- DECODIFICAÇÃO E CODIFICAÇÃO DE VÍDEO FINAL ---
            latents_cpu = latents.detach().to("cpu", non_blocking=True)
            if self.device == "cuda":
                torch.cuda.empty_cache()
                try: torch.cuda.ipc_collect()
                except Exception: pass
            
            lat_a, lat_b = self._dividir_latentes(latents_cpu)
            if lat_a is not None:
                lat_a1, lat_a2 = self._dividir_latentes(lat_a)
            else:
                lat_a1, lat_a2 = None, None
            if lat_b is not None:
                lat_b1, lat_b2 = self._dividir_latentes(lat_b)
            else:
                lat_b1, lat_b2 = None, None
            
            latents_parts = [p for p in [lat_a1, lat_a2, lat_b1, lat_b2] if p is not None]
            if not latents_parts:
                latents_parts = [latents_cpu]

            temp_dir = tempfile.mkdtemp(prefix="ltxv_"); self._register_tmp_dir(temp_dir)
            results_dir = "/app/output"; os.makedirs(results_dir, exist_ok=True)
            partes_mp4 = []
            par = 0
            
            for part in latents_parts:
                par += 1
                print(f"[DEBUG] Partição {par}: {tuple(part.shape)}")
                output_video_path = os.path.join(temp_dir, f"output_{used_seed}_{par}.mp4")
    
                print("[DEBUG] Decodificando bloco de latentes com VAE → tensor de pixels...")
                pixel_tensor = vae_manager_singleton.decode(
                    part.to(self.device, non_blocking=True),
                    decode_timestep=float(self.config.get("decode_timestep", 0.05))
                )
                log_tensor_info(pixel_tensor, "Pixel tensor (VAE saída)")
    
                print("[DEBUG] Codificando MP4 a partir do tensor de pixels...")
                video_encode_tool_singleton.save_video_from_tensor(
                    pixel_tensor,
                    output_video_path,
                    fps=call_kwargs["frame_rate"],
                    progress_callback=progress_callback
                )
    
                candidate = os.path.join(results_dir, f"output_par_{par}.mp4")
                try:
                    shutil.move(output_video_path, candidate)
                    print(f"[DEBUG] MP4 parte {par} movido para {candidate}")
                    partes_mp4.append(candidate)
                except Exception as e:
                    print(f"[DEBUG] Falha no move; usando tmp como final: {e}")
                    partes_mp4.append(output_video_path)

            final_concat = os.path.join(results_dir, f"concat_fim_{used_seed}.mp4")
            if partes_mp4:
                if len(partes_mp4) == 1:
                    shutil.move(partes_mp4[0], final_concat)
                    print(f"[DEBUG] Apenas uma parte, movida para {final_concat}")
                else:
                    self._concat_mp4s_no_reencode(partes_mp4, final_concat)
            else:
                print("[WARN] Nenhuma parte de vídeo foi gerada para concatenar.")
                return None, used_seed

            self._log_gpu_memory("Fim da Geração")
            return final_concat, used_seed
            
        except Exception as e:
            print("[DEBUG] EXCEÇÃO NA GERAÇÃO:")
            print("".join(traceback.format_exception(type(e), e, e.__traceback__)))
            raise
        finally:
            try:
                del latents, latents_low_res, latents_high_res, second_pass_result, first_pass_result, result
            except NameError:
                pass
            except Exception as e:
                print(f"[DEBUG] Erro na limpeza de variáveis: {e}")

            gc.collect()
            if self.device == "cuda":
                try:
                    torch.cuda.empty_cache()
                    torch.cuda.ipc_collect()
                except Exception as e:
                    print(f"[DEBUG] Limpeza GPU no finally falhou: {e}")

            try:
                self.finalize(keep_paths=[])
            except Exception as e:
                print(f"[DEBUG] finalize() no finally falhou: {e}")


print("Criando instância do VideoService. O carregamento do modelo começará agora...")
video_generation_service = VideoService()