Update app_seedvr.py
Browse files- app_seedvr.py +249 -224
app_seedvr.py
CHANGED
|
@@ -1,248 +1,273 @@
|
|
| 1 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
|
| 3 |
-
import os
|
| 4 |
import sys
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
import
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
import cv2
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
|
| 10 |
-
#
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
raise
|
| 18 |
-
|
| 19 |
-
# --- INICIALIZAÇÃO ---
|
| 20 |
-
# Cria uma instância única e persistente do servidor.
|
| 21 |
-
# A inicialização (clonar repo, baixar modelos) acontece apenas uma vez, no início.
|
| 22 |
-
server = SeedVRServer()
|
| 23 |
-
|
| 24 |
-
# --- FUNÇÕES AUXILIARES ---
|
| 25 |
-
|
| 26 |
-
def _is_video(path: str) -> bool:
|
| 27 |
-
"""Verifica se um caminho de arquivo corresponde a um tipo de vídeo."""
|
| 28 |
-
if not path: return False
|
| 29 |
-
import mimetypes
|
| 30 |
-
mime, _ = mimetypes.guess_type(path)
|
| 31 |
-
return (mime or "").startswith("video")
|
| 32 |
-
|
| 33 |
-
def _extract_first_frame(video_path: str) -> Optional[str]:
|
| 34 |
-
"""Extrai o primeiro frame de um vídeo e o salva como uma imagem JPG."""
|
| 35 |
-
if not video_path or not os.path.exists(video_path): return None
|
| 36 |
-
try:
|
| 37 |
-
vid_cap = cv2.VideoCapture(video_path)
|
| 38 |
-
if not vid_cap.isOpened():
|
| 39 |
-
print(f"Erro: Não foi possível abrir o vídeo em {video_path}")
|
| 40 |
-
return None
|
| 41 |
-
success, image = vid_cap.read()
|
| 42 |
-
vid_cap.release()
|
| 43 |
-
if not success:
|
| 44 |
-
print(f"Erro: Não foi possível ler o primeiro frame de {video_path}")
|
| 45 |
-
return None
|
| 46 |
-
|
| 47 |
-
# Salva o frame no mesmo diretório do vídeo, com extensão .jpg
|
| 48 |
-
image_path = Path(video_path).with_suffix(".jpg")
|
| 49 |
-
cv2.imwrite(str(image_path), image)
|
| 50 |
-
return str(image_path)
|
| 51 |
-
except Exception as e:
|
| 52 |
-
print(f"Erro ao extrair o primeiro frame: {e}")
|
| 53 |
-
return None
|
| 54 |
|
| 55 |
-
def
|
| 56 |
"""
|
| 57 |
-
|
| 58 |
-
Verifica se o arquivo é um vídeo e sugere um `sp_size` apropriado.
|
| 59 |
"""
|
| 60 |
-
if
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 80 |
"""
|
| 81 |
-
|
| 82 |
-
para permitir atualizações da UI em tempo real durante a tarefa de longa duração.
|
| 83 |
"""
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
|
|
|
|
|
|
|
|
|
| 93 |
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
|
|
|
| 99 |
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 103 |
|
| 104 |
try:
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
last_log_message = desc
|
| 113 |
-
# Atualiza o objeto de progresso do Gradio
|
| 114 |
-
progress(step, desc=desc)
|
| 115 |
-
|
| 116 |
-
# 2. Executa a Inferência
|
| 117 |
-
# Chama o método direto do servidor, passando o nosso callback.
|
| 118 |
-
video_result_path = server.run_inference_direct(
|
| 119 |
-
file_path=input_file_path,
|
| 120 |
-
seed=42, # Semente fixa conforme solicitado
|
| 121 |
-
res_h=int(resolution),
|
| 122 |
-
res_w=int(resolution), # Largura igual à altura
|
| 123 |
-
sp_size=int(sp_size),
|
| 124 |
-
fps=float(fps) if fps and fps > 0 else None,
|
| 125 |
-
progress=progress_callback_wrapper, # Passa nossa função de callback
|
| 126 |
-
)
|
| 127 |
-
|
| 128 |
-
progress(1.0, desc="Complete!")
|
| 129 |
-
log_buffer.append("✅ Inference complete! Processing final output...\n")
|
| 130 |
-
|
| 131 |
-
# 3. Processa e Exibe os Resultados
|
| 132 |
-
final_image, final_video = None, None
|
| 133 |
-
if was_input_video:
|
| 134 |
-
final_video = video_result_path
|
| 135 |
-
log_buffer.append("✅ Video result is ready.\n")
|
| 136 |
-
else: # Se a entrada foi uma imagem
|
| 137 |
-
final_image = _extract_first_frame(video_result_path)
|
| 138 |
-
final_video = video_result_path # Também disponibiliza o vídeo de 1 frame
|
| 139 |
-
log_buffer.append("✅ Image result extracted from video.\n")
|
| 140 |
-
|
| 141 |
-
# Yield final para mostrar os resultados e reabilitar o botão
|
| 142 |
-
yield (
|
| 143 |
-
gr.update(interactive=True, value="Restore Media"),
|
| 144 |
-
gr.update(value=final_image, visible=final_image is not None),
|
| 145 |
-
gr.update(value=final_video, visible=final_video is not None),
|
| 146 |
-
gr.update(value=video_result_path, visible=video_result_path is not None),
|
| 147 |
-
''.join(log_buffer)
|
| 148 |
)
|
| 149 |
-
|
| 150 |
except Exception as e:
|
| 151 |
-
error_message = f"❌ Inference failed: {e}"
|
| 152 |
-
gr.Error(error_message)
|
| 153 |
-
log_buffer.append(f"\n{error_message}")
|
| 154 |
import traceback
|
| 155 |
-
traceback.
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
None, None, None,
|
| 161 |
-
gr.update(value=''.join(log_buffer), visible=True)
|
| 162 |
-
)
|
| 163 |
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
<div style='text-align: center; margin-bottom: 20px;'>
|
| 171 |
-
<h1>📸 SeedVR - Image & Video Restoration 🚀</h1>
|
| 172 |
-
<p>High-quality media upscaling powered by SeedVR-3B. Upload your file and see the magic.</p>
|
| 173 |
-
</div>
|
| 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 |
-
fps_out = gr.Number(label="Output FPS (for Videos)", value=24, precision=0, info="Set to 0 to use the original FPS.")
|
| 199 |
-
|
| 200 |
-
run_button = gr.Button("Restore Media", variant="primary", icon="✨")
|
| 201 |
-
|
| 202 |
-
# --- Coluna da Direita: Resultados ---
|
| 203 |
-
with gr.Column(scale=2):
|
| 204 |
-
gr.Markdown("### 3. Results")
|
| 205 |
-
|
| 206 |
-
# Janela de Log
|
| 207 |
-
log_window = gr.Textbox(
|
| 208 |
-
label="Inference Log 📝",
|
| 209 |
-
lines=8, max_lines=15,
|
| 210 |
-
interactive=False, visible=False, autoscroll=True
|
| 211 |
-
)
|
| 212 |
-
|
| 213 |
-
# Componentes de saída (começam invisíveis)
|
| 214 |
-
output_image = gr.Image(label="Image Result", show_download_button=True, type="filepath", visible=False)
|
| 215 |
-
output_video = gr.Video(label="Video Result", visible=False)
|
| 216 |
-
output_download = gr.File(label="Download Full Result (Video)", visible=False)
|
| 217 |
-
|
| 218 |
-
# --- Rodapé ---
|
| 219 |
-
gr.Markdown(
|
| 220 |
-
"""
|
| 221 |
-
---
|
| 222 |
-
*Space and Docker were developed by Carlex.*
|
| 223 |
-
*Contact: Email: Carlex22@gmail.com | GitHub: [carlex22](https://github.com/carlex22)*
|
| 224 |
-
"""
|
| 225 |
-
)
|
| 226 |
|
| 227 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 228 |
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 234 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 235 |
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 242 |
|
| 243 |
if __name__ == "__main__":
|
| 244 |
-
|
| 245 |
-
server_name=os.getenv("GRADIO_SERVER_NAME", "0.0.0.0"),
|
| 246 |
-
server_port=int(os.getenv("GRADIO_SERVER_PORT", "7860")),
|
| 247 |
-
show_error=True
|
| 248 |
-
)
|
|
|
|
| 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
|
| 8 |
+
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
|
| 36 |
+
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 |
|
| 99 |
+
import torch
|
| 100 |
+
from src.core.model_manager import configure_runner
|
| 101 |
+
from src.core.generation import generation_loop
|
| 102 |
+
|
| 103 |
+
frames_tensor = torch.from_numpy(frames_np).to(torch.float16)
|
| 104 |
+
|
| 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 |
|
| 111 |
try:
|
| 112 |
+
runner = configure_runner(shared_args["model"], shared_args["model_dir"], shared_args["preserve_vram"], shared_args["debug"])
|
| 113 |
+
result_tensor = generation_loop(
|
| 114 |
+
runner=runner, images=frames_tensor, cfg_scale=shared_args["cfg_scale"],
|
| 115 |
+
seed=shared_args["seed"], res_w=shared_args["res_w"], batch_size=shared_args["batch_size"],
|
| 116 |
+
preserve_vram=shared_args["preserve_vram"], temporal_overlap=shared_args["temporal_overlap"],
|
| 117 |
+
debug=shared_args["debug"],
|
| 118 |
+
progress_callback=local_progress_callback
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 119 |
)
|
| 120 |
+
return_queue.put((proc_idx, result_tensor.cpu().numpy()))
|
| 121 |
except Exception as e:
|
|
|
|
|
|
|
|
|
|
| 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.
|
| 132 |
+
"""
|
| 133 |
+
num_devices = len(device_list)
|
| 134 |
+
chunks = torch.chunk(frames_tensor, num_devices, dim=0)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 135 |
|
| 136 |
+
manager = mp.Manager()
|
| 137 |
+
return_queue = manager.Queue()
|
| 138 |
+
progress_queue = manager.Queue() if progress_callback else None
|
| 139 |
+
workers = []
|
| 140 |
+
|
| 141 |
+
shared_args = {
|
| 142 |
+
"model": args.model, "model_dir": args.model_dir or "./models/SEEDVR2",
|
| 143 |
+
"preserve_vram": args.preserve_vram, "debug": args.debug, "cfg_scale": 1.0,
|
| 144 |
+
"seed": args.seed, "res_w": args.resolution, "batch_size": args.batch_size, "temporal_overlap": 0,
|
| 145 |
+
}
|
| 146 |
+
|
| 147 |
+
for idx, (device_id, chunk_tensor) in enumerate(zip(device_list, chunks)):
|
| 148 |
+
p = mp.Process(target=_worker_process, args=(idx, device_id, chunk_tensor.cpu().numpy(), shared_args, return_queue, progress_queue))
|
| 149 |
+
p.start()
|
| 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()
|
|
|
|
|
|
|
|
|
|
|
|