Update video_service.py
Browse files- video_service.py +64 -0
video_service.py
CHANGED
|
@@ -71,6 +71,8 @@ def log_tensor_info(tensor, name="Tensor"):
|
|
| 71 |
print(" - O tensor está vazio, sem estatísticas.")
|
| 72 |
print("------------------------------------------\n")
|
| 73 |
|
|
|
|
|
|
|
| 74 |
# --- 5. CLASSE PRINCIPAL DO SERVIÇO ---
|
| 75 |
class VideoService:
|
| 76 |
def __init__(self):
|
|
@@ -78,6 +80,9 @@ class VideoService:
|
|
| 78 |
self.config = self._load_config()
|
| 79 |
self.device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 80 |
self.last_memory_reserved_mb = 0
|
|
|
|
|
|
|
|
|
|
| 81 |
self.pipeline, self.latent_upsampler = self._load_models()
|
| 82 |
print(f"Movendo modelos para o dispositivo de inferência: {self.device}")
|
| 83 |
self.pipeline.to(self.device)
|
|
@@ -88,6 +93,63 @@ class VideoService:
|
|
| 88 |
self._log_gpu_memory("Após carregar modelos")
|
| 89 |
print("VideoService pronto para uso.")
|
| 90 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 91 |
def _query_gpu_processes_via_nvml(device_index: int) -> List[Dict]:
|
| 92 |
try:
|
| 93 |
import psutil
|
|
@@ -328,6 +390,8 @@ class VideoService:
|
|
| 328 |
progress_callback(i + 1, total_frames)
|
| 329 |
|
| 330 |
self._log_gpu_memory("Fim da Geração")
|
|
|
|
|
|
|
| 331 |
return output_video_path, used_seed
|
| 332 |
|
| 333 |
print("Criando instância do VideoService. O carregamento do modelo começará agora...")
|
|
|
|
| 71 |
print(" - O tensor está vazio, sem estatísticas.")
|
| 72 |
print("------------------------------------------\n")
|
| 73 |
|
| 74 |
+
|
| 75 |
+
|
| 76 |
# --- 5. CLASSE PRINCIPAL DO SERVIÇO ---
|
| 77 |
class VideoService:
|
| 78 |
def __init__(self):
|
|
|
|
| 80 |
self.config = self._load_config()
|
| 81 |
self.device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 82 |
self.last_memory_reserved_mb = 0
|
| 83 |
+
self._tmp_dirs = set()
|
| 84 |
+
self._tmp_files = set()
|
| 85 |
+
self._last_outputs = []
|
| 86 |
self.pipeline, self.latent_upsampler = self._load_models()
|
| 87 |
print(f"Movendo modelos para o dispositivo de inferência: {self.device}")
|
| 88 |
self.pipeline.to(self.device)
|
|
|
|
| 93 |
self._log_gpu_memory("Após carregar modelos")
|
| 94 |
print("VideoService pronto para uso.")
|
| 95 |
|
| 96 |
+
def _register_tmp_dir(self, d: str):
|
| 97 |
+
if d and os.path.isdir(d):
|
| 98 |
+
self._tmp_dirs.add(d)
|
| 99 |
+
|
| 100 |
+
def _register_tmp_file(self, f: str):
|
| 101 |
+
if f and os.path.isfile(f):
|
| 102 |
+
self._tmp_files.add(f)
|
| 103 |
+
|
| 104 |
+
def finalize(self, keep_paths=None, extra_paths=None, clear_gpu=True):
|
| 105 |
+
"""
|
| 106 |
+
Remove temporários e coleta memória.
|
| 107 |
+
keep_paths: caminhos que não devem ser removidos (ex.: vídeo final).
|
| 108 |
+
extra_paths: caminhos adicionais para tentar remover (opcional).
|
| 109 |
+
"""
|
| 110 |
+
keep = set(keep_paths or [])
|
| 111 |
+
extras = set(extra_paths or [])
|
| 112 |
+
|
| 113 |
+
# Remoção de arquivos
|
| 114 |
+
for f in list(self._tmp_files | extras):
|
| 115 |
+
try:
|
| 116 |
+
if f not in keep and os.path.isfile(f):
|
| 117 |
+
os.remove(f)
|
| 118 |
+
except Exception:
|
| 119 |
+
pass
|
| 120 |
+
finally:
|
| 121 |
+
self._tmp_files.discard(f)
|
| 122 |
+
|
| 123 |
+
# Remoção de diretórios
|
| 124 |
+
for d in list(self._tmp_dirs):
|
| 125 |
+
try:
|
| 126 |
+
if d not in keep and os.path.isdir(d):
|
| 127 |
+
shutil.rmtree(d, ignore_errors=True)
|
| 128 |
+
except Exception:
|
| 129 |
+
pass
|
| 130 |
+
finally:
|
| 131 |
+
self._tmp_dirs.discard(d)
|
| 132 |
+
|
| 133 |
+
# Coleta de GC e limpeza de VRAM
|
| 134 |
+
gc.collect()
|
| 135 |
+
try:
|
| 136 |
+
import torch
|
| 137 |
+
if clear_gpu and torch.cuda.is_available():
|
| 138 |
+
torch.cuda.empty_cache()
|
| 139 |
+
# Limpa buffers de IPC quando aplicável
|
| 140 |
+
try:
|
| 141 |
+
torch.cuda.ipc_collect()
|
| 142 |
+
except Exception:
|
| 143 |
+
pass
|
| 144 |
+
except Exception:
|
| 145 |
+
pass
|
| 146 |
+
|
| 147 |
+
# Log opcional pós-limpeza
|
| 148 |
+
try:
|
| 149 |
+
self._log_gpu_memory("Após finalize")
|
| 150 |
+
except Exception:
|
| 151 |
+
pass
|
| 152 |
+
|
| 153 |
def _query_gpu_processes_via_nvml(device_index: int) -> List[Dict]:
|
| 154 |
try:
|
| 155 |
import psutil
|
|
|
|
| 390 |
progress_callback(i + 1, total_frames)
|
| 391 |
|
| 392 |
self._log_gpu_memory("Fim da Geração")
|
| 393 |
+
|
| 394 |
+
finalize()
|
| 395 |
return output_video_path, used_seed
|
| 396 |
|
| 397 |
print("Criando instância do VideoService. O carregamento do modelo começará agora...")
|