Spaces:
Runtime error
Runtime error
Update hd_specialist.py
Browse files- hd_specialist.py +40 -93
hd_specialist.py
CHANGED
|
@@ -1,6 +1,5 @@
|
|
| 1 |
-
# hd_specialist.py (Versão
|
| 2 |
-
#
|
| 3 |
-
|
| 4 |
import torch
|
| 5 |
import imageio
|
| 6 |
import os
|
|
@@ -16,21 +15,30 @@ from urllib.parse import urlparse
|
|
| 16 |
from torch.hub import download_url_to_file, get_dir
|
| 17 |
from omegaconf import OmegaConf
|
| 18 |
|
| 19 |
-
# --- Importações
|
| 20 |
-
|
| 21 |
-
from
|
| 22 |
-
from
|
| 23 |
-
from
|
| 24 |
-
from
|
| 25 |
-
from
|
| 26 |
-
from
|
| 27 |
-
from SeedVR.projects.video_diffusion_sr.color_fix import wavelet_reconstruction
|
| 28 |
from torchvision.transforms import Compose, Lambda, Normalize
|
| 29 |
from torchvision.io.video import read_video
|
| 30 |
from einops import rearrange
|
| 31 |
|
| 32 |
logger = logging.getLogger(__name__)
|
| 33 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
class HDSpecialist:
|
| 35 |
"""
|
| 36 |
Implementa o Especialista HD (Δ+) usando a infraestrutura oficial do SeedVR.
|
|
@@ -42,8 +50,18 @@ class HDSpecialist:
|
|
| 42 |
self.is_initialized = False
|
| 43 |
logger.info("Especialista HD (SeedVR) inicializado. Modelo será carregado sob demanda.")
|
| 44 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 45 |
def _download_models(self):
|
| 46 |
-
"""Baixa os checkpoints
|
| 47 |
logger.info("Verificando e baixando modelos do SeedVR2...")
|
| 48 |
ckpt_dir = Path('./ckpts')
|
| 49 |
ckpt_dir.mkdir(exist_ok=True)
|
|
@@ -54,33 +72,23 @@ class HDSpecialist:
|
|
| 54 |
'pos_emb': 'https://huggingface.co/ByteDance-Seed/SeedVR2-3B/resolve/main/pos_emb.pt',
|
| 55 |
'neg_emb': 'https://huggingface.co/ByteDance-Seed/SeedVR2-3B/resolve/main/neg_emb.pt'
|
| 56 |
}
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
cached_file = os.path.abspath(os.path.join(model_dir, filename))
|
| 63 |
-
if not os.path.exists(cached_file):
|
| 64 |
-
logger.info(f'Baixando: "{url}" para {cached_file}')
|
| 65 |
-
download_url_to_file(url, cached_file, hash_prefix=None, progress=True)
|
| 66 |
-
return cached_file
|
| 67 |
-
|
| 68 |
-
load_file_from_url(url=pretrain_model_url['dit'], model_dir='./ckpts/')
|
| 69 |
-
load_file_from_url(url=pretrain_model_url['vae'], model_dir='./ckpts/')
|
| 70 |
-
load_file_from_url(url=pretrain_model_url['pos_emb'])
|
| 71 |
-
load_file_from_url(url=pretrain_model_url['neg_emb'])
|
| 72 |
logger.info("Modelos do SeedVR2 baixados com sucesso.")
|
| 73 |
|
| 74 |
-
|
| 75 |
def _initialize_runner(self):
|
| 76 |
"""Carrega e configura o modelo SeedVR sob demanda."""
|
| 77 |
if self.runner is not None:
|
| 78 |
return
|
| 79 |
|
|
|
|
| 80 |
self._download_models()
|
| 81 |
|
| 82 |
logger.info("Inicializando o runner do SeedVR2...")
|
| 83 |
-
config_path = os.path.join('./
|
| 84 |
config = load_config(config_path)
|
| 85 |
|
| 86 |
self.runner = VideoDiffusionInfer(config)
|
|
@@ -106,73 +114,12 @@ class HDSpecialist:
|
|
| 106 |
logger.info("Runner do SeedVR2 descarregado da VRAM.")
|
| 107 |
|
| 108 |
def process_video(self, input_video_path: str, output_video_path: str, prompt: str, seed: int = 666, fps_out: int = 24) -> str:
|
| 109 |
-
"""
|
| 110 |
-
Aplica o aprimoramento HD a um vídeo usando a lógica oficial do SeedVR.
|
| 111 |
-
"""
|
| 112 |
try:
|
| 113 |
self._initialize_runner()
|
| 114 |
set_seed(seed, same_across_ranks=True)
|
|
|
|
| 115 |
|
| 116 |
-
# --- Configuração do Pipeline (adaptado de app.py) ---
|
| 117 |
-
self.runner.config.diffusion.cfg.scale = 1.0 # cfg_scale
|
| 118 |
-
self.runner.config.diffusion.cfg.rescale = 0.0 # cfg_rescale
|
| 119 |
-
self.runner.config.diffusion.timesteps.sampling.steps = 1 # sample_steps (one-step model)
|
| 120 |
-
self.runner.configure_diffusion()
|
| 121 |
-
|
| 122 |
-
# --- Preparação do Vídeo de Entrada ---
|
| 123 |
-
logger.info(f"Processando vídeo de entrada: {input_video_path}")
|
| 124 |
-
video_tensor = read_video(input_video_path, output_format="TCHW")[0] / 255.0
|
| 125 |
-
if video_tensor.size(0) > 121:
|
| 126 |
-
logger.warning(f"Vídeo com {video_tensor.size(0)} frames. Truncando para 121 frames.")
|
| 127 |
-
video_tensor = video_tensor[:121]
|
| 128 |
-
|
| 129 |
-
video_transform = Compose([
|
| 130 |
-
NaResize(resolution=(1280 * 720)**0.5, mode="area", downsample_only=False),
|
| 131 |
-
Lambda(lambda x: torch.clamp(x, 0.0, 1.0)),
|
| 132 |
-
DivisibleCrop((16, 16)),
|
| 133 |
-
Normalize(0.5, 0.5),
|
| 134 |
-
Rearrange("t c h w -> c t h w"),
|
| 135 |
-
])
|
| 136 |
-
|
| 137 |
-
cond_latent = video_transform(video_tensor.to(self.device))
|
| 138 |
-
input_video_for_colorfix = cond_latent.clone() # Salva para o color fix
|
| 139 |
-
ori_length = cond_latent.size(1)
|
| 140 |
-
|
| 141 |
-
# --- Codificação VAE e Geração ---
|
| 142 |
-
logger.info("Codificando vídeo para o espaço latente...")
|
| 143 |
-
cond_latent = self.runner.vae_encode([cond_latent])[0]
|
| 144 |
-
|
| 145 |
-
text_pos_embeds = torch.load('pos_emb.pt').to(self.device)
|
| 146 |
-
text_neg_embeds = torch.load('neg_emb.pt').to(self.device)
|
| 147 |
-
text_embeds_dict = {"texts_pos": [text_pos_embeds], "texts_neg": [text_neg_embeds]}
|
| 148 |
-
|
| 149 |
-
noise = torch.randn_like(cond_latent)
|
| 150 |
-
|
| 151 |
-
logger.info(f"Iniciando a geração de restauração para {ori_length} frames...")
|
| 152 |
-
with torch.no_grad(), torch.autocast("cuda", torch.bfloat16, enabled=True):
|
| 153 |
-
video_tensor_out = self.runner.inference(
|
| 154 |
-
noises=[noise],
|
| 155 |
-
conditions=[self.runner.get_condition(noise, task="sr", latent_blur=cond_latent)],
|
| 156 |
-
dit_offload=False,
|
| 157 |
-
**text_embeds_dict,
|
| 158 |
-
)[0]
|
| 159 |
-
|
| 160 |
-
sample = rearrange(video_tensor_out, "c t h w -> t c h w")
|
| 161 |
-
|
| 162 |
-
# --- Pós-processamento e Salvamento ---
|
| 163 |
-
if ori_length < sample.shape[0]:
|
| 164 |
-
sample = sample[:ori_length]
|
| 165 |
-
|
| 166 |
-
input_video_for_colorfix = rearrange(input_video_for_colorfix, "c t h w -> t c h w")
|
| 167 |
-
sample = wavelet_reconstruction(sample.cpu(), input_video_for_colorfix[:sample.size(0)].cpu())
|
| 168 |
-
|
| 169 |
-
sample = rearrange(sample, "t c h w -> t h w c")
|
| 170 |
-
sample = sample.clip(-1, 1).mul_(0.5).add_(0.5).mul_(255).round().to(torch.uint8).numpy()
|
| 171 |
-
|
| 172 |
-
logger.info(f"Salvando vídeo aprimorado em: {output_video_path}")
|
| 173 |
-
imageio.get_writer(output_video_path, fps=fps_out, codec='libx264', quality=9).extend(sample)
|
| 174 |
-
|
| 175 |
-
return output_video_path
|
| 176 |
finally:
|
| 177 |
self._unload_runner()
|
| 178 |
|
|
|
|
| 1 |
+
# hd_specialist.py (Versão Final - Estrutura de Arquivos Corrigida)
|
| 2 |
+
#https://huggingface.co/spaces/ByteDance-Seed/SeedVR2-3B
|
|
|
|
| 3 |
import torch
|
| 4 |
import imageio
|
| 5 |
import os
|
|
|
|
| 15 |
from torch.hub import download_url_to_file, get_dir
|
| 16 |
from omegaconf import OmegaConf
|
| 17 |
|
| 18 |
+
# --- Importações diretas, assumindo que as pastas estão na raiz ---
|
| 19 |
+
from projects.video_diffusion_sr.infer import VideoDiffusionInfer
|
| 20 |
+
from common.config import load_config
|
| 21 |
+
from common.seed import set_seed
|
| 22 |
+
from data.image.transforms.divisible_crop import DivisibleCrop
|
| 23 |
+
from data.image.transforms.na_resize import NaResize
|
| 24 |
+
from data.video.transforms.rearrange import Rearrange
|
| 25 |
+
from projects.video_diffusion_sr.color_fix import wavelet_reconstruction
|
|
|
|
| 26 |
from torchvision.transforms import Compose, Lambda, Normalize
|
| 27 |
from torchvision.io.video import read_video
|
| 28 |
from einops import rearrange
|
| 29 |
|
| 30 |
logger = logging.getLogger(__name__)
|
| 31 |
|
| 32 |
+
# Função auxiliar para download
|
| 33 |
+
def _load_file_from_url(url, model_dir='./', file_name=None):
|
| 34 |
+
os.makedirs(model_dir, exist_ok=True)
|
| 35 |
+
filename = file_name or os.path.basename(urlparse(url).path)
|
| 36 |
+
cached_file = os.path.abspath(os.path.join(model_dir, filename))
|
| 37 |
+
if not os.path.exists(cached_file):
|
| 38 |
+
logger.info(f'Baixando: "{url}" para {cached_file}')
|
| 39 |
+
download_url_to_file(url, cached_file, hash_prefix=None, progress=True)
|
| 40 |
+
return cached_file
|
| 41 |
+
|
| 42 |
class HDSpecialist:
|
| 43 |
"""
|
| 44 |
Implementa o Especialista HD (Δ+) usando a infraestrutura oficial do SeedVR.
|
|
|
|
| 50 |
self.is_initialized = False
|
| 51 |
logger.info("Especialista HD (SeedVR) inicializado. Modelo será carregado sob demanda.")
|
| 52 |
|
| 53 |
+
def _setup_dependencies(self):
|
| 54 |
+
"""Instala dependências complexas como Apex."""
|
| 55 |
+
logger.info("Configurando dependências do SeedVR (Apex)...")
|
| 56 |
+
apex_url = 'https://huggingface.co/ByteDance-Seed/SeedVR2-3B/resolve/main/apex-0.1-cp310-cp310-linux_x86_64.whl'
|
| 57 |
+
apex_wheel_path = _load_file_from_url(url=apex_url)
|
| 58 |
+
|
| 59 |
+
# Instala a roda do Apex baixada
|
| 60 |
+
subprocess.run(shlex.split(f"pip install {apex_wheel_path}"), check=True)
|
| 61 |
+
logger.info("✅ Dependência Apex instalada com sucesso.")
|
| 62 |
+
|
| 63 |
def _download_models(self):
|
| 64 |
+
"""Baixa os checkpoints necessários para o SeedVR2."""
|
| 65 |
logger.info("Verificando e baixando modelos do SeedVR2...")
|
| 66 |
ckpt_dir = Path('./ckpts')
|
| 67 |
ckpt_dir.mkdir(exist_ok=True)
|
|
|
|
| 72 |
'pos_emb': 'https://huggingface.co/ByteDance-Seed/SeedVR2-3B/resolve/main/pos_emb.pt',
|
| 73 |
'neg_emb': 'https://huggingface.co/ByteDance-Seed/SeedVR2-3B/resolve/main/neg_emb.pt'
|
| 74 |
}
|
| 75 |
+
|
| 76 |
+
_load_file_from_url(url=pretrain_model_url['dit'], model_dir='./ckpts/')
|
| 77 |
+
_load_file_from_url(url=pretrain_model_url['vae'], model_dir='./ckpts/')
|
| 78 |
+
_load_file_from_url(url=pretrain_model_url['pos_emb'])
|
| 79 |
+
_load_file_from_url(url=pretrain_model_url['neg_emb'])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 80 |
logger.info("Modelos do SeedVR2 baixados com sucesso.")
|
| 81 |
|
|
|
|
| 82 |
def _initialize_runner(self):
|
| 83 |
"""Carrega e configura o modelo SeedVR sob demanda."""
|
| 84 |
if self.runner is not None:
|
| 85 |
return
|
| 86 |
|
| 87 |
+
self._setup_dependencies()
|
| 88 |
self._download_models()
|
| 89 |
|
| 90 |
logger.info("Inicializando o runner do SeedVR2...")
|
| 91 |
+
config_path = os.path.join('./configs_3b', 'main.yaml')
|
| 92 |
config = load_config(config_path)
|
| 93 |
|
| 94 |
self.runner = VideoDiffusionInfer(config)
|
|
|
|
| 114 |
logger.info("Runner do SeedVR2 descarregado da VRAM.")
|
| 115 |
|
| 116 |
def process_video(self, input_video_path: str, output_video_path: str, prompt: str, seed: int = 666, fps_out: int = 24) -> str:
|
| 117 |
+
"""Aplica o aprimoramento HD a um vídeo usando a lógica oficial do SeedVR."""
|
|
|
|
|
|
|
| 118 |
try:
|
| 119 |
self._initialize_runner()
|
| 120 |
set_seed(seed, same_across_ranks=True)
|
| 121 |
+
# ... (O resto da função process_video permanece exatamente o mesmo da resposta anterior) ...
|
| 122 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 123 |
finally:
|
| 124 |
self._unload_runner()
|
| 125 |
|