EuuIia commited on
Commit
6f5bacf
·
verified ·
1 Parent(s): 20c6b9e

Update inference_cli.py

Browse files
Files changed (1) hide show
  1. inference_cli.py +40 -160
inference_cli.py CHANGED
@@ -1,7 +1,7 @@
1
  #!/usr/bin/env python3
2
  """
3
  Standalone SeedVR2 Video Upscaler CLI Script
4
- (MODIFICADO PARA SER IMPORTÁVEL E SUPORTAR CALLBACKS DE PROGRESSO EM MULTIPROCESSING)
5
  """
6
 
7
  import sys
@@ -9,27 +9,15 @@ import os
9
  import argparse
10
  import time
11
  import multiprocessing as mp
12
- import queue # Importa a classe de exceção para filas vazias
13
 
14
- # Garante o uso seguro de CUDA com multiprocessing, essencial para estabilidade.
15
  if mp.get_start_method(allow_none=True) != 'spawn':
16
  mp.set_start_method('spawn', force=True)
17
 
18
- # -------------------------------------------------------------
19
- # 1) Configuração de alocação de memória da VRAM
20
  os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "backend:cudaMallocAsync")
21
 
22
- # 2) Pré-análise dos argumentos para configurar a visibilidade dos dispositivos CUDA
23
- _pre_parser = argparse.ArgumentParser(add_help=False)
24
- _pre_parser.add_argument("--cuda_device", type=str, default=None)
25
- _pre_args, _ = _pre_parser.parse_known_args()
26
- if _pre_args.cuda_device is not None:
27
- device_list_env = [x.strip() for x in _pre_args.cuda_device.split(',') if x.strip()!='']
28
- if len(device_list_env) == 1:
29
- os.environ["CUDA_VISIBLE_DEVICES"] = device_list_env[0]
30
 
31
- # -------------------------------------------------------------
32
- # 3) Importações pesadas (torch, etc.) são feitas após a configuração do ambiente.
33
  import torch
34
  import cv2
35
  import numpy as np
@@ -37,62 +25,16 @@ from datetime import datetime
37
  from pathlib import Path
38
  from src.utils.downloads import download_weight
39
 
40
- # Adiciona o diretório raiz do projeto ao path do sistema para permitir importações de `src`
41
  script_dir = os.path.dirname(os.path.abspath(__file__))
42
  if script_dir not in sys.path:
43
  sys.path.insert(0, script_dir)
44
- root_dir = os.path.join(script_dir, '..', '..')
45
- if root_dir not in sys.path:
46
- sys.path.insert(0, root_dir)
47
 
48
- def extract_frames_from_video(video_path, debug=False, skip_first_frames=0, load_cap=None):
49
- """
50
- Extrai quadros de um vídeo e os converte para o formato de tensor.
51
- """
52
- if debug: print(f"🎬 Extracting frames from video: {video_path}")
53
- if not os.path.exists(video_path): raise FileNotFoundError(f"Video file not found: {video_path}")
54
- cap = cv2.VideoCapture(video_path)
55
- if not cap.isOpened(): raise ValueError(f"Cannot open video file: {video_path}")
56
- fps = cap.get(cv2.CAP_PROP_FPS)
57
- frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)); width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)); height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
58
- if debug: print(f"📊 Video info: {frame_count} frames, {width}x{height}, {fps:.2f} FPS")
59
- frames = []; frame_idx = 0; frames_loaded = 0
60
- while True:
61
- ret, frame = cap.read()
62
- if not ret: break
63
- if frame_idx < skip_first_frames: frame_idx += 1; continue
64
- if load_cap is not None and load_cap > 0 and frames_loaded >= load_cap: break
65
- frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
66
- frame = frame.astype(np.float32) / 255.0
67
- frames.append(frame); frame_idx += 1; frames_loaded += 1
68
- cap.release()
69
- if len(frames) == 0: raise ValueError(f"No frames extracted from video: {video_path}")
70
- if debug: print(f"✅ Extracted {len(frames)} frames")
71
- frames_tensor = torch.from_numpy(np.stack(frames)).to(torch.float16)
72
- if debug: print(f"📊 Frames tensor shape: {frames_tensor.shape}, dtype: {frames_tensor.dtype}")
73
- return frames_tensor, fps
74
-
75
- def save_frames_to_video(frames_tensor, output_path, fps=30.0, debug=False):
76
- """
77
- Salva um tensor de quadros em um arquivo de vídeo.
78
- """
79
- if debug: print(f"🎬 Saving {frames_tensor.shape[0]} frames to video: {output_path}")
80
- os.makedirs(os.path.dirname(output_path), exist_ok=True)
81
- frames_np = (frames_tensor.cpu().numpy() * 255.0).astype(np.uint8)
82
- T, H, W, C = frames_np.shape
83
- fourcc = cv2.VideoWriter_fourcc(*'mp4v')
84
- out = cv2.VideoWriter(output_path, fourcc, fps, (W, H))
85
- if not out.isOpened(): raise ValueError(f"Cannot create video writer for: {output_path}")
86
- for i, frame in enumerate(frames_np):
87
- frame_bgr = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
88
- out.write(frame_bgr)
89
- out.release()
90
- if debug: print(f"✅ Video saved successfully: {output_path}")
91
 
 
92
  def _worker_process(proc_idx, device_id, frames_np, shared_args, return_queue, progress_queue=None):
93
- """
94
- Processo filho (worker) que executa o upscaling em uma GPU dedicada.
95
- """
96
  os.environ["CUDA_VISIBLE_DEVICES"] = str(device_id)
97
  os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "backend:cudaMallocAsync")
98
 
@@ -105,6 +47,7 @@ def _worker_process(proc_idx, device_id, frames_np, shared_args, return_queue, p
105
  local_progress_callback = None
106
  if progress_queue:
107
  def callback_wrapper(batch_idx, total_batches, current_frames, message):
 
108
  progress_queue.put((proc_idx, batch_idx, total_batches, message))
109
  local_progress_callback = callback_wrapper
110
 
@@ -122,10 +65,10 @@ def _worker_process(proc_idx, device_id, frames_np, shared_args, return_queue, p
122
  import traceback
123
  error_msg = f"ERROR in worker {proc_idx}: {e}\n{traceback.format_exc()}"
124
  print(error_msg)
125
- if progress_queue:
126
- progress_queue.put((proc_idx, -1, -1, error_msg))
127
  return_queue.put((proc_idx, error_msg))
128
 
 
129
  def _gpu_processing(frames_tensor, device_list, args, progress_callback=None):
130
  """
131
  Divide os quadros, gerencia os workers e monitora o progresso de forma robusta.
@@ -150,124 +93,61 @@ def _gpu_processing(frames_tensor, device_list, args, progress_callback=None):
150
  workers.append(p)
151
 
152
  results_np = [None] * num_devices
153
- finished_workers = [False] * num_devices
154
  worker_progress = [0.0] * num_devices
155
 
156
- while not all(finished_workers):
 
157
  if progress_queue:
158
  while not progress_queue.empty():
159
  try:
160
  proc_idx, batch_idx, total_batches, message = progress_queue.get_nowait()
161
- if batch_idx == -1: # Mensagem de erro do worker
162
- raise RuntimeError(f"Worker {proc_idx} encontrou um erro: {message}")
163
-
164
- if total_batches > 0:
165
- worker_progress[proc_idx] = batch_idx / total_batches
166
 
167
  total_progress = sum(worker_progress) / num_devices
168
  progress_callback(total_progress, desc=f"GPU {proc_idx+1}/{num_devices}: {message}")
169
  except queue.Empty:
170
  break
171
 
172
- while not return_queue.empty():
173
- try:
174
- proc_idx, result = return_queue.get_nowait()
175
- if isinstance(result, str) and result.startswith("ERROR"):
176
- raise RuntimeError(f"Worker {proc_idx} falhou: {result}")
177
-
178
- results_np[proc_idx] = result
179
- worker_progress[proc_idx] = 1.0 # Marca como 100% concluído
180
- finished_workers[proc_idx] = True
181
-
182
  total_progress = sum(worker_progress) / num_devices
183
- if progress_callback:
184
- progress_callback(total_progress, desc=f"GPU {proc_idx+1}/{num_devices}: Concluído!")
185
- except queue.Empty:
186
- break
187
-
188
- time.sleep(0.2)
189
 
190
  for p in workers: p.join()
191
 
192
- # Verifica se algum resultado está faltando, indicando um erro não capturado
193
  if any(r is None for r in results_np):
194
- raise RuntimeError("Um ou mais workers falharam em retornar um resultado.")
195
 
196
  return torch.from_numpy(np.concatenate(results_np, axis=0)).to(torch.float16)
197
 
198
- def parse_arguments():
199
- """Analisa os argumentos da linha de comando."""
200
- parser = argparse.ArgumentParser(description="SeedVR2 Video Upscaler CLI")
201
- parser.add_argument("--video_path", type=str, required=True, help="Path to input video file")
202
- parser.add_argument("--seed", type=int, default=100, help="Random seed for generation (default: 100)")
203
- parser.add_argument("--resolution", type=int, default=1072, help="Target resolution of the short side (default: 1072)")
204
- parser.add_argument("--batch_size", type=int, default=5, help="Number of frames per batch (default: 5)")
205
- parser.add_argument("--model", type=str, default="seedvr2_ema_3b_fp16.safetensors",
206
- choices=["seedvr2_ema_3b_fp16.safetensors", "seedvr2_ema_3b_fp8_e4m3fn.safetensors",
207
- "seedvr2_ema_7b_fp16.safetensors", "seedvr2_ema_7b_fp8_e4m3fn.safetensors"],
208
- help="Model to use")
209
- parser.add_argument("--model_dir", type=str, default=None, help="Directory containing the model files")
210
- parser.add_argument("--skip_first_frames", type=int, default=0, help="Skip the first frames during processing")
211
- parser.add_argument("--load_cap", type=int, default=0, help="Maximum number of frames to load from video (default: load all)")
212
- parser.add_argument("--output", type=str, default=None, help="Output path")
213
- parser.add_argument("--output_format", type=str, default="video", choices=["video", "png"], help="Output format: 'video' (mp4) or 'png' images")
214
- parser.add_argument("--preserve_vram", action="store_true", help="Enable VRAM preservation mode")
215
- parser.add_argument("--debug", action="store_true", help="Enable debug logging")
216
- parser.add_argument("--cuda_device", type=str, default=None, help="CUDA device id(s). e.g., '0' or '0,1' for multi-GPU")
217
-
218
- return parser.parse_args()
219
 
 
220
  def run_inference_logic(args, progress_callback=None):
221
- """
222
- Função principal que executa o pipeline de upscaling. Pode ser importada e chamada por outros scripts.
223
- """
224
- if args.debug:
225
- print(f"📋 Argumentos da Lógica de Inferência: {vars(args)}")
226
-
227
- if progress_callback: progress_callback(0.05, "Extracting frames...")
228
- print("🎬 Extraindo frames do vídeo...")
229
- start_time = time.time()
230
- frames_tensor, original_fps = extract_frames_from_video(
231
- args.video_path, args.debug, args.skip_first_frames, args.load_cap
232
- )
233
- if args.debug:
234
- print(f"🔄 Tempo de extração de frames: {time.time() - start_time:.2f}s")
235
-
236
- device_list = [d.strip() for d in str(args.cuda_device).split(',') if d.strip()] if args.cuda_device else ["0"]
237
- if args.debug:
238
- print(f"🚀 Usando dispositivos: {device_list}")
239
-
240
- if progress_callback: progress_callback(0.1, "Starting generation...")
241
- processing_start = time.time()
242
- download_weight(args.model, args.model_dir)
243
-
244
  result_tensor = _gpu_processing(frames_tensor, device_list, args, progress_callback)
245
-
246
- generation_time = time.time() - processing_start
247
- if args.debug:
248
- print(f"🔄 Tempo de Geração: {generation_time:.2f}s")
249
- print(f"📊 Resultado: {result_tensor.shape}, dtype: {result_tensor.dtype}")
250
-
251
  return result_tensor, original_fps, generation_time, len(frames_tensor)
252
 
 
253
  def main():
254
- """
255
- Função principal para execução via linha de comando (CLI).
256
- """
257
- print(f"🚀 SeedVR2 Video Upscaler CLI iniciado às {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
258
- args = parse_arguments()
259
- try:
260
- result_tensor, original_fps, _, _ = run_inference_logic(args)
261
-
262
- print(f"💾 Salvando vídeo em: {args.output}")
263
- save_frames_to_video(result_tensor, args.output, original_fps, args.debug)
264
- print("✅ Upscaling via CLI concluído com sucesso!")
265
-
266
- except Exception as e:
267
- print(f"❌ Erro durante o processamento via CLI: {e}")
268
- import traceback
269
- traceback.print_exc()
270
- sys.exit(1)
271
 
272
  if __name__ == "__main__":
273
- main()
 
 
 
 
 
1
  #!/usr/bin/env python3
2
  """
3
  Standalone SeedVR2 Video Upscaler CLI Script
4
+ (MODIFICADO PARA SUPORTE ROBUSTO A CALLBACKS EM MULTIPROCESSING)
5
  """
6
 
7
  import sys
 
9
  import argparse
10
  import time
11
  import multiprocessing as mp
12
+ import queue # Necessário para a exceção queue.Empty
13
 
 
14
  if mp.get_start_method(allow_none=True) != 'spawn':
15
  mp.set_start_method('spawn', force=True)
16
 
 
 
17
  os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "backend:cudaMallocAsync")
18
 
19
+ # ... (código de pré-parse e imports pesados permanece o mesmo) ...
 
 
 
 
 
 
 
20
 
 
 
21
  import torch
22
  import cv2
23
  import numpy as np
 
25
  from pathlib import Path
26
  from src.utils.downloads import download_weight
27
 
 
28
  script_dir = os.path.dirname(os.path.abspath(__file__))
29
  if script_dir not in sys.path:
30
  sys.path.insert(0, script_dir)
 
 
 
31
 
32
+ # --- FUNÇÕES AUXILIARES (extract_frames_..., save_frames_... - sem alterações) ---
33
+ # ... (mantenha suas funções originais aqui) ...
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
 
35
+ # --- LÓGICA DO WORKER (com a fila de progresso) ---
36
  def _worker_process(proc_idx, device_id, frames_np, shared_args, return_queue, progress_queue=None):
37
+ """Worker que executa o upscaling em uma GPU dedicada."""
 
 
38
  os.environ["CUDA_VISIBLE_DEVICES"] = str(device_id)
39
  os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "backend:cudaMallocAsync")
40
 
 
47
  local_progress_callback = None
48
  if progress_queue:
49
  def callback_wrapper(batch_idx, total_batches, current_frames, message):
50
+ # Envia uma tupla com informações de progresso para a fila
51
  progress_queue.put((proc_idx, batch_idx, total_batches, message))
52
  local_progress_callback = callback_wrapper
53
 
 
65
  import traceback
66
  error_msg = f"ERROR in worker {proc_idx}: {e}\n{traceback.format_exc()}"
67
  print(error_msg)
68
+ if progress_queue: progress_queue.put((proc_idx, -1, -1, error_msg))
 
69
  return_queue.put((proc_idx, error_msg))
70
 
71
+ # --- PROCESSAMENTO PRINCIPAL (COM MONITORAMENTO ROBUSTO) ---
72
  def _gpu_processing(frames_tensor, device_list, args, progress_callback=None):
73
  """
74
  Divide os quadros, gerencia os workers e monitora o progresso de forma robusta.
 
93
  workers.append(p)
94
 
95
  results_np = [None] * num_devices
96
+ finished_workers_count = 0
97
  worker_progress = [0.0] * num_devices
98
 
99
+ while finished_workers_count < num_devices:
100
+ # 1. Processa todas as mensagens de progresso na fila
101
  if progress_queue:
102
  while not progress_queue.empty():
103
  try:
104
  proc_idx, batch_idx, total_batches, message = progress_queue.get_nowait()
105
+ if batch_idx == -1: raise RuntimeError(f"Worker {proc_idx} error: {message}")
106
+ if total_batches > 0: worker_progress[proc_idx] = batch_idx / total_batches
 
 
 
107
 
108
  total_progress = sum(worker_progress) / num_devices
109
  progress_callback(total_progress, desc=f"GPU {proc_idx+1}/{num_devices}: {message}")
110
  except queue.Empty:
111
  break
112
 
113
+ # 2. Verifica se algum worker terminou
114
+ try:
115
+ proc_idx, result = return_queue.get(timeout=0.1) # Usa um timeout curto
116
+ if isinstance(result, str) and result.startswith("ERROR"):
117
+ raise RuntimeError(f"Worker {proc_idx} failed: {result}")
118
+ results_np[proc_idx] = result
119
+ worker_progress[proc_idx] = 1.0 # Marca como 100%
120
+ finished_workers_count += 1
121
+ if progress_callback:
 
122
  total_progress = sum(worker_progress) / num_devices
123
+ progress_callback(total_progress, desc=f"GPU {proc_idx+1}/{num_devices}: Completed!")
124
+ except queue.Empty:
125
+ pass # Continua o loop se não houver resultados ainda
 
 
 
126
 
127
  for p in workers: p.join()
128
 
 
129
  if any(r is None for r in results_np):
130
+ raise RuntimeError("One or more workers failed to return a result.")
131
 
132
  return torch.from_numpy(np.concatenate(results_np, axis=0)).to(torch.float16)
133
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
134
 
135
+ # --- FUNÇÃO DE LÓGICA E MAIN (sem alterações) ---
136
  def run_inference_logic(args, progress_callback=None):
137
+ # ... (código completo, já está correto para passar o callback)
138
+ # ...
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
139
  result_tensor = _gpu_processing(frames_tensor, device_list, args, progress_callback)
140
+ # ...
 
 
 
 
 
141
  return result_tensor, original_fps, generation_time, len(frames_tensor)
142
 
143
+
144
  def main():
145
+ # ... (código completo, sem alterações)
146
+ # ...
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
147
 
148
  if __name__ == "__main__":
149
+ main()
150
+
151
+ # Adicione aqui o código completo das funções omitidas para garantir que nada se perca
152
+ # (extract_frames_from_video, save_frames_to_video, parse_arguments, run_inference_logic, main)
153
+ # Omiti por brevidade, mas você deve tê-los no seu arquivo.