Update aduc_framework/managers/seedvr_manager.py
Browse files
aduc_framework/managers/seedvr_manager.py
CHANGED
|
@@ -1,4 +1,4 @@
|
|
| 1 |
-
# hd_specialist.py (Versão Final -
|
| 2 |
# https://huggingface.co/spaces/ByteDance-Seed/SeedVR2-3B
|
| 3 |
|
| 4 |
import torch
|
|
@@ -13,49 +13,53 @@ import shlex
|
|
| 13 |
import subprocess
|
| 14 |
from pathlib import Path
|
| 15 |
from urllib.parse import urlparse
|
| 16 |
-
from torch.hub import download_url_to_file
|
| 17 |
from omegaconf import OmegaConf
|
| 18 |
import sys
|
| 19 |
|
| 20 |
-
|
| 21 |
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
| 22 |
logger = logging.getLogger(__name__)
|
| 23 |
|
| 24 |
-
|
| 25 |
-
|
|
|
|
|
|
|
| 26 |
SEEDVR_SPACE_DIR = DEPS_DIR / "SeedVR_Space"
|
| 27 |
SEEDVR_SPACE_URL = "https://huggingface.co/spaces/ByteDance-Seed/SeedVR2-3B"
|
| 28 |
|
| 29 |
-
|
| 30 |
-
def setup_dependencies():
|
| 31 |
"""
|
| 32 |
-
|
| 33 |
-
|
| 34 |
"""
|
| 35 |
-
if not SEEDVR_SPACE_DIR.
|
| 36 |
-
logger.info(f"
|
| 37 |
try:
|
|
|
|
| 38 |
DEPS_DIR.mkdir(exist_ok=True)
|
|
|
|
| 39 |
subprocess.run(
|
| 40 |
["git", "clone", "--depth", "1", SEEDVR_SPACE_URL, str(SEEDVR_SPACE_DIR)],
|
| 41 |
check=True, capture_output=True, text=True
|
| 42 |
)
|
| 43 |
-
logger.info("
|
| 44 |
except subprocess.CalledProcessError as e:
|
| 45 |
-
logger.error(f"
|
| 46 |
-
raise RuntimeError("
|
| 47 |
else:
|
| 48 |
-
logger.info("
|
| 49 |
-
|
| 50 |
-
if str(SEEDVR_SPACE_DIR.resolve()) not in sys.path:
|
| 51 |
-
sys.path.insert(0, str(SEEDVR_SPACE_DIR.resolve()))
|
| 52 |
-
logger.info(f"Added '{SEEDVR_SPACE_DIR.resolve()}' to sys.path.")
|
| 53 |
-
|
| 54 |
-
setup_dependencies()
|
| 55 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 56 |
|
|
|
|
|
|
|
| 57 |
|
| 58 |
-
# Função auxiliar
|
| 59 |
def _load_file_from_url(url, model_dir='./', file_name=None):
|
| 60 |
os.makedirs(model_dir, exist_ok=True)
|
| 61 |
filename = file_name or os.path.basename(urlparse(url).path)
|
|
@@ -65,9 +69,8 @@ def _load_file_from_url(url, model_dir='./', file_name=None):
|
|
| 65 |
download_url_to_file(url, cached_file, hash_prefix=None, progress=True)
|
| 66 |
return cached_file
|
| 67 |
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
# --- Importações diretas, assumindo que as pastas estão na raiz ---
|
| 71 |
from projects.video_diffusion_sr.infer import VideoDiffusionInfer
|
| 72 |
from common.config import load_config
|
| 73 |
from common.seed import set_seed
|
|
@@ -79,8 +82,6 @@ from torchvision.transforms import Compose, Lambda, Normalize
|
|
| 79 |
from torchvision.io.video import read_video
|
| 80 |
from einops import rearrange
|
| 81 |
|
| 82 |
-
|
| 83 |
-
|
| 84 |
class SeedVrManager:
|
| 85 |
"""
|
| 86 |
Implementa o Especialista HD (Δ+) usando a infraestrutura oficial do SeedVR.
|
|
@@ -88,27 +89,25 @@ class SeedVrManager:
|
|
| 88 |
def __init__(self, workspace_dir="deformes_workspace"):
|
| 89 |
self.device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
| 90 |
self.runner = None
|
| 91 |
-
self.workspace_dir = workspace_dir
|
| 92 |
self.is_initialized = False
|
| 93 |
logger.info("Especialista HD (SeedVR) inicializado. Modelo será carregado sob demanda.")
|
| 94 |
|
| 95 |
def _setup_dependencies(self):
|
| 96 |
-
|
| 97 |
"""Instala dependências complexas como Apex."""
|
| 98 |
logger.info("Configurando dependências do SeedVR (Apex)...")
|
| 99 |
apex_url = 'https://huggingface.co/ByteDance-Seed/SeedVR2-3B/resolve/main/apex-0.1-cp310-cp310-linux_x86_64.whl'
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
# Instala a roda do Apex baixada
|
| 103 |
subprocess.run(shlex.split(f"pip install {apex_wheel_path}"), check=True)
|
| 104 |
logger.info("✅ Dependência Apex instalada com sucesso.")
|
| 105 |
|
| 106 |
def _download_models(self):
|
| 107 |
-
"""Baixa os checkpoints necessários para o SeedVR2."""
|
| 108 |
logger.info("Verificando e baixando modelos do SeedVR2...")
|
| 109 |
-
|
| 110 |
-
ckpt_dir
|
| 111 |
-
|
| 112 |
pretrain_model_url = {
|
| 113 |
'vae': 'https://huggingface.co/ByteDance-Seed/SeedVR2-3B/resolve/main/ema_vae.pth',
|
| 114 |
'dit': 'https://huggingface.co/ByteDance-Seed/SeedVR2-3B/resolve/main/seedvr2_ema_3b.pth',
|
|
@@ -116,11 +115,12 @@ class SeedVrManager:
|
|
| 116 |
'neg_emb': 'https://huggingface.co/ByteDance-Seed/SeedVR2-3B/resolve/main/neg_emb.pt'
|
| 117 |
}
|
| 118 |
|
| 119 |
-
|
| 120 |
-
_load_file_from_url(url=pretrain_model_url['
|
| 121 |
-
_load_file_from_url(url=pretrain_model_url['
|
| 122 |
-
_load_file_from_url(url=pretrain_model_url['
|
| 123 |
-
|
|
|
|
| 124 |
|
| 125 |
def _initialize_runner(self):
|
| 126 |
"""Carrega e configura o modelo SeedVR sob demanda."""
|
|
@@ -132,66 +132,49 @@ class SeedVrManager:
|
|
| 132 |
|
| 133 |
logger.info("Inicializando o runner do SeedVR2...")
|
| 134 |
|
| 135 |
-
#
|
| 136 |
-
|
| 137 |
-
config_path = config_dir / 'main.yaml'
|
| 138 |
-
config_url = "https://huggingface.co/spaces/ByteDance-Seed/SeedVR2-3B/resolve/main/configs_3b/main.yaml"
|
| 139 |
|
| 140 |
if not config_path.is_file():
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
try:
|
| 144 |
-
# Reutiliza a função de download existente
|
| 145 |
-
_load_file_from_url(url=config_url, model_dir=str(config_dir), file_name='main.yaml')
|
| 146 |
-
logger.info(f"✅ Arquivo de configuração baixado com sucesso para '{config_path}'")
|
| 147 |
-
except Exception as e:
|
| 148 |
-
logger.error(f"Falha ao baixar o arquivo de configuração. Por favor, baixe-o manualmente de {config_url} e coloque-o em {config_dir}. Erro: {e}")
|
| 149 |
-
raise
|
| 150 |
-
else:
|
| 151 |
-
logger.info(f"Arquivo de configuração encontrado em '{config_path}'.")
|
| 152 |
-
# --- FIM DA MODIFICAÇÃO ---
|
| 153 |
|
|
|
|
| 154 |
config = load_config(str(config_path))
|
| 155 |
|
| 156 |
self.runner = VideoDiffusionInfer(config)
|
| 157 |
OmegaConf.set_readonly(self.runner.config, False)
|
| 158 |
|
| 159 |
-
|
|
|
|
|
|
|
| 160 |
self.runner.configure_vae_model()
|
| 161 |
|
| 162 |
if hasattr(self.runner.vae, "set_memory_limit"):
|
| 163 |
self.runner.vae.set_memory_limit(**self.runner.config.vae.memory_limit)
|
| 164 |
|
| 165 |
self.is_initialized = True
|
| 166 |
-
logger.info("Runner do SeedVR2 inicializado e pronto.")
|
| 167 |
|
| 168 |
def _unload_runner(self):
|
| 169 |
"""Remove o runner da VRAM para liberar recursos."""
|
| 170 |
if self.runner is not None:
|
| 171 |
-
del self.runner
|
| 172 |
-
|
| 173 |
-
gc.collect()
|
| 174 |
-
torch.cuda.empty_cache()
|
| 175 |
self.is_initialized = False
|
| 176 |
logger.info("Runner do SeedVR2 descarregado da VRAM.")
|
| 177 |
|
| 178 |
-
|
| 179 |
-
|
| 180 |
def process_video(self, input_video_path: str, output_video_path: str, prompt: str) -> str:
|
| 181 |
-
"""
|
| 182 |
-
Aplica o aprimoramento HD a um vídeo usando a lógica oficial do SeedVR.
|
| 183 |
-
"""
|
| 184 |
try:
|
| 185 |
self._initialize_runner()
|
| 186 |
set_seed(seed, same_across_ranks=True)
|
| 187 |
|
| 188 |
-
|
| 189 |
-
self.runner.config.diffusion.cfg.
|
| 190 |
-
self.runner.config.diffusion.
|
| 191 |
-
self.runner.config.diffusion.timesteps.sampling.steps = 1 # sample_steps (one-step model)
|
| 192 |
self.runner.configure_diffusion()
|
| 193 |
|
| 194 |
-
# --- Preparação do Vídeo de Entrada ---
|
| 195 |
logger.info(f"Processando vídeo de entrada: {input_video_path}")
|
| 196 |
video_tensor = read_video(input_video_path, output_format="TCHW")[0] / 255.0
|
| 197 |
if video_tensor.size(0) > 121:
|
|
@@ -200,22 +183,22 @@ class SeedVrManager:
|
|
| 200 |
|
| 201 |
video_transform = Compose([
|
| 202 |
NaResize(resolution=(1280 * 720)**0.5, mode="area", downsample_only=False),
|
| 203 |
-
Lambda(lambda x: torch.clamp(x, 0.0, 1.0)),
|
| 204 |
-
|
| 205 |
-
Normalize(0.5, 0.5),
|
| 206 |
-
Rearrange("t c h w -> c t h w"),
|
| 207 |
])
|
| 208 |
|
| 209 |
cond_latent = video_transform(video_tensor.to(self.device))
|
| 210 |
-
input_video_for_colorfix = cond_latent.clone()
|
| 211 |
ori_length = cond_latent.size(1)
|
| 212 |
|
| 213 |
-
# --- Codificação VAE e Geração ---
|
| 214 |
logger.info("Codificando vídeo para o espaço latente...")
|
| 215 |
cond_latent = self.runner.vae_encode([cond_latent])[0]
|
| 216 |
|
| 217 |
-
|
| 218 |
-
|
|
|
|
|
|
|
|
|
|
| 219 |
text_embeds_dict = {"texts_pos": [text_pos_embeds], "texts_neg": [text_neg_embeds]}
|
| 220 |
|
| 221 |
noise = torch.randn_like(cond_latent)
|
|
@@ -225,28 +208,25 @@ class SeedVrManager:
|
|
| 225 |
video_tensor_out = self.runner.inference(
|
| 226 |
noises=[noise],
|
| 227 |
conditions=[self.runner.get_condition(noise, task="sr", latent_blur=cond_latent)],
|
| 228 |
-
dit_offload=False,
|
| 229 |
-
**text_embeds_dict,
|
| 230 |
)[0]
|
| 231 |
|
| 232 |
sample = rearrange(video_tensor_out, "c t h w -> t c h w")
|
| 233 |
-
|
| 234 |
-
# --- Pós-processamento e Salvamento ---
|
| 235 |
if ori_length < sample.shape[0]:
|
| 236 |
sample = sample[:ori_length]
|
| 237 |
|
| 238 |
input_video_for_colorfix = rearrange(input_video_for_colorfix, "c t h w -> t c h w")
|
| 239 |
sample = wavelet_reconstruction(sample.cpu(), input_video_for_colorfix[:sample.size(0)].cpu())
|
| 240 |
-
|
| 241 |
sample = rearrange(sample, "t c h w -> t h w c")
|
| 242 |
sample = sample.clip(-1, 1).mul_(0.5).add_(0.5).mul_(255).round().to(torch.uint8).numpy()
|
| 243 |
|
| 244 |
logger.info(f"Salvando vídeo aprimorado em: {output_video_path}")
|
|
|
|
| 245 |
imageio.get_writer(output_video_path, fps=fps_out, codec='libx264', quality=9).extend(sample)
|
| 246 |
|
| 247 |
return output_video_path
|
| 248 |
finally:
|
| 249 |
-
self._unload_runner()
|
| 250 |
|
| 251 |
-
# Instância Singleton
|
| 252 |
seedvr_manager_singleton = SeedVrManager()
|
|
|
|
| 1 |
+
# hd_specialist.py (Versão Final - Gerenciando o Repositório Completo)
|
| 2 |
# https://huggingface.co/spaces/ByteDance-Seed/SeedVR2-3B
|
| 3 |
|
| 4 |
import torch
|
|
|
|
| 13 |
import subprocess
|
| 14 |
from pathlib import Path
|
| 15 |
from urllib.parse import urlparse
|
| 16 |
+
from torch.hub import download_url_to_file
|
| 17 |
from omegaconf import OmegaConf
|
| 18 |
import sys
|
| 19 |
|
| 20 |
+
# --- Configuração do Logging ---
|
| 21 |
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
| 22 |
logger = logging.getLogger(__name__)
|
| 23 |
|
| 24 |
+
# --- Constantes de Caminho ---
|
| 25 |
+
# Define a raiz do projeto (onde este script está) e cria um diretório para dependências
|
| 26 |
+
PROJECT_ROOT = Path(__file__).resolve().parent
|
| 27 |
+
DEPS_DIR = PROJECT_ROOT / "deps"
|
| 28 |
SEEDVR_SPACE_DIR = DEPS_DIR / "SeedVR_Space"
|
| 29 |
SEEDVR_SPACE_URL = "https://huggingface.co/spaces/ByteDance-Seed/SeedVR2-3B"
|
| 30 |
|
| 31 |
+
def setup_environment():
|
|
|
|
| 32 |
"""
|
| 33 |
+
Clona o repositório SeedVR se não existir e o adiciona ao sys.path
|
| 34 |
+
para que seus módulos (common, projects, etc.) possam ser importados.
|
| 35 |
"""
|
| 36 |
+
if not SEEDVR_SPACE_DIR.is_dir():
|
| 37 |
+
logger.info(f"Repositório SeedVR não encontrado. Clonando de '{SEEDVR_SPACE_URL}'...")
|
| 38 |
try:
|
| 39 |
+
# Garante que o diretório de dependências exista
|
| 40 |
DEPS_DIR.mkdir(exist_ok=True)
|
| 41 |
+
# Clona o repositório. '--depth 1' baixa apenas a versão mais recente.
|
| 42 |
subprocess.run(
|
| 43 |
["git", "clone", "--depth", "1", SEEDVR_SPACE_URL, str(SEEDVR_SPACE_DIR)],
|
| 44 |
check=True, capture_output=True, text=True
|
| 45 |
)
|
| 46 |
+
logger.info(f"✅ Repositório clonado com sucesso em '{SEEDVR_SPACE_DIR}'")
|
| 47 |
except subprocess.CalledProcessError as e:
|
| 48 |
+
logger.error(f"❌ Falha ao clonar o repositório. Erro do Git: {e.stderr}")
|
| 49 |
+
raise RuntimeError("Não foi possível clonar a dependência SeedVR do Hugging Face.")
|
| 50 |
else:
|
| 51 |
+
logger.info(f"Repositório SeedVR já existe em '{SEEDVR_SPACE_DIR}'.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
|
| 53 |
+
# Adiciona a raiz do repositório clonado ao path do Python
|
| 54 |
+
resolved_path = str(SEEDVR_SPACE_DIR.resolve())
|
| 55 |
+
if resolved_path not in sys.path:
|
| 56 |
+
sys.path.insert(0, resolved_path)
|
| 57 |
+
logger.info(f"Adicionado '{resolved_path}' ao sys.path.")
|
| 58 |
|
| 59 |
+
# Executa a configuração do ambiente assim que o módulo é carregado
|
| 60 |
+
setup_environment()
|
| 61 |
|
| 62 |
+
# Função auxiliar de download (permanece a mesma)
|
| 63 |
def _load_file_from_url(url, model_dir='./', file_name=None):
|
| 64 |
os.makedirs(model_dir, exist_ok=True)
|
| 65 |
filename = file_name or os.path.basename(urlparse(url).path)
|
|
|
|
| 69 |
download_url_to_file(url, cached_file, hash_prefix=None, progress=True)
|
| 70 |
return cached_file
|
| 71 |
|
| 72 |
+
# --- Importações do Repositório Clonado ---
|
| 73 |
+
# Agora estas importações funcionam porque `setup_environment` adicionou o repositório ao sys.path
|
|
|
|
| 74 |
from projects.video_diffusion_sr.infer import VideoDiffusionInfer
|
| 75 |
from common.config import load_config
|
| 76 |
from common.seed import set_seed
|
|
|
|
| 82 |
from torchvision.io.video import read_video
|
| 83 |
from einops import rearrange
|
| 84 |
|
|
|
|
|
|
|
| 85 |
class SeedVrManager:
|
| 86 |
"""
|
| 87 |
Implementa o Especialista HD (Δ+) usando a infraestrutura oficial do SeedVR.
|
|
|
|
| 89 |
def __init__(self, workspace_dir="deformes_workspace"):
|
| 90 |
self.device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
| 91 |
self.runner = None
|
| 92 |
+
self.workspace_dir = Path(workspace_dir)
|
| 93 |
self.is_initialized = False
|
| 94 |
logger.info("Especialista HD (SeedVR) inicializado. Modelo será carregado sob demanda.")
|
| 95 |
|
| 96 |
def _setup_dependencies(self):
|
|
|
|
| 97 |
"""Instala dependências complexas como Apex."""
|
| 98 |
logger.info("Configurando dependências do SeedVR (Apex)...")
|
| 99 |
apex_url = 'https://huggingface.co/ByteDance-Seed/SeedVR2-3B/resolve/main/apex-0.1-cp310-cp310-linux_x86_64.whl'
|
| 100 |
+
# Baixa para um diretório temporário ou de dependências
|
| 101 |
+
apex_wheel_path = _load_file_from_url(url=apex_url, model_dir=str(DEPS_DIR))
|
|
|
|
| 102 |
subprocess.run(shlex.split(f"pip install {apex_wheel_path}"), check=True)
|
| 103 |
logger.info("✅ Dependência Apex instalada com sucesso.")
|
| 104 |
|
| 105 |
def _download_models(self):
|
| 106 |
+
"""Baixa os checkpoints necessários para o SeedVR2 DENTRO do repositório clonado."""
|
| 107 |
logger.info("Verificando e baixando modelos do SeedVR2...")
|
| 108 |
+
# O diretório de checkpoints agora é DENTRO do repositório clonado
|
| 109 |
+
ckpt_dir = SEEDVR_SPACE_DIR / 'ckpts'
|
| 110 |
+
|
| 111 |
pretrain_model_url = {
|
| 112 |
'vae': 'https://huggingface.co/ByteDance-Seed/SeedVR2-3B/resolve/main/ema_vae.pth',
|
| 113 |
'dit': 'https://huggingface.co/ByteDance-Seed/SeedVR2-3B/resolve/main/seedvr2_ema_3b.pth',
|
|
|
|
| 115 |
'neg_emb': 'https://huggingface.co/ByteDance-Seed/SeedVR2-3B/resolve/main/neg_emb.pt'
|
| 116 |
}
|
| 117 |
|
| 118 |
+
# Salva os modelos nos locais corretos que o código espera
|
| 119 |
+
_load_file_from_url(url=pretrain_model_url['dit'], model_dir=str(ckpt_dir))
|
| 120 |
+
_load_file_from_url(url=pretrain_model_url['vae'], model_dir=str(ckpt_dir))
|
| 121 |
+
_load_file_from_url(url=pretrain_model_url['pos_emb'], model_dir=str(SEEDVR_SPACE_DIR))
|
| 122 |
+
_load_file_from_url(url=pretrain_model_url['neg_emb'], model_dir=str(SEEDVR_SPACE_DIR))
|
| 123 |
+
logger.info("✅ Modelos do SeedVR2 baixados com sucesso.")
|
| 124 |
|
| 125 |
def _initialize_runner(self):
|
| 126 |
"""Carrega e configura o modelo SeedVR sob demanda."""
|
|
|
|
| 132 |
|
| 133 |
logger.info("Inicializando o runner do SeedVR2...")
|
| 134 |
|
| 135 |
+
# CORREÇÃO: O caminho para o config agora é relativo ao repositório clonado.
|
| 136 |
+
config_path = SEEDVR_SPACE_DIR / 'configs_3b' / 'main.yaml'
|
|
|
|
|
|
|
| 137 |
|
| 138 |
if not config_path.is_file():
|
| 139 |
+
# Esta verificação agora é uma salvaguarda, pois o git clone já deve ter baixado o arquivo.
|
| 140 |
+
raise FileNotFoundError(f"Arquivo de configuração principal não encontrado em {config_path}. O clone do repositório pode ter falhado.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 141 |
|
| 142 |
+
# `load_config` agora encontrará os arquivos herdados pois estamos no contexto do repo clonado.
|
| 143 |
config = load_config(str(config_path))
|
| 144 |
|
| 145 |
self.runner = VideoDiffusionInfer(config)
|
| 146 |
OmegaConf.set_readonly(self.runner.config, False)
|
| 147 |
|
| 148 |
+
# CORREÇÃO: Os caminhos para os checkpoints também são relativos ao repositório clonado.
|
| 149 |
+
dit_checkpoint_path = SEEDVR_SPACE_DIR / 'ckpts' / 'seedvr2_ema_3b.pth'
|
| 150 |
+
self.runner.configure_dit_model(device=self.device, checkpoint=str(dit_checkpoint_path))
|
| 151 |
self.runner.configure_vae_model()
|
| 152 |
|
| 153 |
if hasattr(self.runner.vae, "set_memory_limit"):
|
| 154 |
self.runner.vae.set_memory_limit(**self.runner.config.vae.memory_limit)
|
| 155 |
|
| 156 |
self.is_initialized = True
|
| 157 |
+
logger.info("✅ Runner do SeedVR2 inicializado e pronto.")
|
| 158 |
|
| 159 |
def _unload_runner(self):
|
| 160 |
"""Remove o runner da VRAM para liberar recursos."""
|
| 161 |
if self.runner is not None:
|
| 162 |
+
del self.runner; self.runner = None
|
| 163 |
+
gc.collect(); torch.cuda.empty_cache()
|
|
|
|
|
|
|
| 164 |
self.is_initialized = False
|
| 165 |
logger.info("Runner do SeedVR2 descarregado da VRAM.")
|
| 166 |
|
|
|
|
|
|
|
| 167 |
def process_video(self, input_video_path: str, output_video_path: str, prompt: str) -> str:
|
| 168 |
+
"""Aplica o aprimoramento HD a um vídeo usando a lógica oficial do SeedVR."""
|
|
|
|
|
|
|
| 169 |
try:
|
| 170 |
self._initialize_runner()
|
| 171 |
set_seed(seed, same_across_ranks=True)
|
| 172 |
|
| 173 |
+
self.runner.config.diffusion.cfg.scale = 1.0
|
| 174 |
+
self.runner.config.diffusion.cfg.rescale = 0.0
|
| 175 |
+
self.runner.config.diffusion.timesteps.sampling.steps = 1
|
|
|
|
| 176 |
self.runner.configure_diffusion()
|
| 177 |
|
|
|
|
| 178 |
logger.info(f"Processando vídeo de entrada: {input_video_path}")
|
| 179 |
video_tensor = read_video(input_video_path, output_format="TCHW")[0] / 255.0
|
| 180 |
if video_tensor.size(0) > 121:
|
|
|
|
| 183 |
|
| 184 |
video_transform = Compose([
|
| 185 |
NaResize(resolution=(1280 * 720)**0.5, mode="area", downsample_only=False),
|
| 186 |
+
Lambda(lambda x: torch.clamp(x, 0.0, 1.0)), DivisibleCrop((16, 16)),
|
| 187 |
+
Normalize(0.5, 0.5), Rearrange("t c h w -> c t h w"),
|
|
|
|
|
|
|
| 188 |
])
|
| 189 |
|
| 190 |
cond_latent = video_transform(video_tensor.to(self.device))
|
| 191 |
+
input_video_for_colorfix = cond_latent.clone()
|
| 192 |
ori_length = cond_latent.size(1)
|
| 193 |
|
|
|
|
| 194 |
logger.info("Codificando vídeo para o espaço latente...")
|
| 195 |
cond_latent = self.runner.vae_encode([cond_latent])[0]
|
| 196 |
|
| 197 |
+
# CORREÇÃO: Carrega os embeddings a partir do repositório clonado
|
| 198 |
+
pos_emb_path = SEEDVR_SPACE_DIR / 'pos_emb.pt'
|
| 199 |
+
neg_emb_path = SEEDVR_SPACE_DIR / 'neg_emb.pt'
|
| 200 |
+
text_pos_embeds = torch.load(pos_emb_path).to(self.device)
|
| 201 |
+
text_neg_embeds = torch.load(neg_emb_path).to(self.device)
|
| 202 |
text_embeds_dict = {"texts_pos": [text_pos_embeds], "texts_neg": [text_neg_embeds]}
|
| 203 |
|
| 204 |
noise = torch.randn_like(cond_latent)
|
|
|
|
| 208 |
video_tensor_out = self.runner.inference(
|
| 209 |
noises=[noise],
|
| 210 |
conditions=[self.runner.get_condition(noise, task="sr", latent_blur=cond_latent)],
|
| 211 |
+
dit_offload=False, **text_embeds_dict,
|
|
|
|
| 212 |
)[0]
|
| 213 |
|
| 214 |
sample = rearrange(video_tensor_out, "c t h w -> t c h w")
|
|
|
|
|
|
|
| 215 |
if ori_length < sample.shape[0]:
|
| 216 |
sample = sample[:ori_length]
|
| 217 |
|
| 218 |
input_video_for_colorfix = rearrange(input_video_for_colorfix, "c t h w -> t c h w")
|
| 219 |
sample = wavelet_reconstruction(sample.cpu(), input_video_for_colorfix[:sample.size(0)].cpu())
|
|
|
|
| 220 |
sample = rearrange(sample, "t c h w -> t h w c")
|
| 221 |
sample = sample.clip(-1, 1).mul_(0.5).add_(0.5).mul_(255).round().to(torch.uint8).numpy()
|
| 222 |
|
| 223 |
logger.info(f"Salvando vídeo aprimorado em: {output_video_path}")
|
| 224 |
+
self.workspace_dir.mkdir(parents=True, exist_ok=True)
|
| 225 |
imageio.get_writer(output_video_path, fps=fps_out, codec='libx264', quality=9).extend(sample)
|
| 226 |
|
| 227 |
return output_video_path
|
| 228 |
finally:
|
| 229 |
+
self._unload_runner()
|
| 230 |
|
| 231 |
+
# Instância Singleton
|
| 232 |
seedvr_manager_singleton = SeedVrManager()
|