Update managers/seedvr_manager.py
Browse files- managers/seedvr_manager.py +19 -43
managers/seedvr_manager.py
CHANGED
|
@@ -2,11 +2,11 @@
|
|
| 2 |
#
|
| 3 |
# Copyright (C) 2025 Carlos Rodrigues dos Santos
|
| 4 |
#
|
| 5 |
-
# Version: 2.3.
|
| 6 |
#
|
| 7 |
-
# Esta versão
|
| 8 |
-
#
|
| 9 |
-
#
|
| 10 |
|
| 11 |
import torch
|
| 12 |
import os
|
|
@@ -21,7 +21,6 @@ import gradio as gr
|
|
| 21 |
import mediapy
|
| 22 |
from einops import rearrange
|
| 23 |
|
| 24 |
-
# Utilitário internalizado para correção de cor, garantindo estabilidade.
|
| 25 |
from tools.tensor_utils import wavelet_reconstruction
|
| 26 |
|
| 27 |
logger = logging.getLogger(__name__)
|
|
@@ -30,22 +29,15 @@ logger = logging.getLogger(__name__)
|
|
| 30 |
DEPS_DIR = Path("./deps")
|
| 31 |
SEEDVR_REPO_DIR = DEPS_DIR / "SeedVR"
|
| 32 |
SEEDVR_REPO_URL = "https://github.com/ByteDance-Seed/SeedVR.git"
|
| 33 |
-
# URL direto para o arquivo de configuração do VAE que pode estar faltando
|
| 34 |
VAE_CONFIG_URL = "https://raw.githubusercontent.com/ByteDance-Seed/SeedVR/main/models/video_vae_v3/s8_c16_t4_inflation_sd3.yaml"
|
| 35 |
|
| 36 |
def setup_seedvr_dependencies():
|
| 37 |
-
"""
|
| 38 |
-
Garante que o repositório do SeedVR seja clonado e esteja disponível no sys.path.
|
| 39 |
-
Esta função é executada uma vez quando o módulo é importado pela primeira vez.
|
| 40 |
-
"""
|
| 41 |
if not SEEDVR_REPO_DIR.exists():
|
| 42 |
logger.info(f"Repositório SeedVR não encontrado em '{SEEDVR_REPO_DIR}'. Clonando do GitHub...")
|
| 43 |
try:
|
| 44 |
DEPS_DIR.mkdir(exist_ok=True)
|
| 45 |
-
subprocess.run(
|
| 46 |
-
["git", "clone", "--depth", "1", SEEDVR_REPO_URL, str(SEEDVR_REPO_DIR)],
|
| 47 |
-
check=True, capture_output=True, text=True
|
| 48 |
-
)
|
| 49 |
logger.info("Repositório SeedVR clonado com sucesso.")
|
| 50 |
except subprocess.CalledProcessError as e:
|
| 51 |
logger.error(f"Falha ao clonar o repositório SeedVR. Git stderr: {e.stderr}")
|
|
@@ -57,10 +49,8 @@ def setup_seedvr_dependencies():
|
|
| 57 |
sys.path.insert(0, str(SEEDVR_REPO_DIR.resolve()))
|
| 58 |
logger.info(f"Adicionado '{SEEDVR_REPO_DIR.resolve()}' ao sys.path.")
|
| 59 |
|
| 60 |
-
# --- Executa a configuração da dependência imediatamente na importação do módulo ---
|
| 61 |
setup_seedvr_dependencies()
|
| 62 |
|
| 63 |
-
# --- Agora que o caminho está configurado, podemos importar com segurança do repositório clonado ---
|
| 64 |
from projects.video_diffusion_sr.infer import VideoDiffusionInfer
|
| 65 |
from common.config import load_config
|
| 66 |
from common.seed import set_seed
|
|
@@ -71,9 +61,7 @@ from torchvision.transforms import Compose, Lambda, Normalize
|
|
| 71 |
from torchvision.io.video import read_video
|
| 72 |
from omegaconf import OmegaConf
|
| 73 |
|
| 74 |
-
|
| 75 |
def _load_file_from_url(url, model_dir='./', file_name=None):
|
| 76 |
-
"""Função auxiliar para baixar arquivos de uma URL para um diretório local."""
|
| 77 |
os.makedirs(model_dir, exist_ok=True)
|
| 78 |
filename = file_name or os.path.basename(urlparse(url).path)
|
| 79 |
cached_file = os.path.abspath(os.path.join(model_dir, filename))
|
|
@@ -83,9 +71,7 @@ def _load_file_from_url(url, model_dir='./', file_name=None):
|
|
| 83 |
return cached_file
|
| 84 |
|
| 85 |
class SeedVrManager:
|
| 86 |
-
"""
|
| 87 |
-
Gerencia o modelo SeedVR para tarefas de Masterização HD.
|
| 88 |
-
"""
|
| 89 |
def __init__(self, workspace_dir="deformes_workspace"):
|
| 90 |
self.device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
| 91 |
self.runner = None
|
|
@@ -94,18 +80,13 @@ class SeedVrManager:
|
|
| 94 |
logger.info("SeedVrManager inicializado. O modelo será carregado sob demanda.")
|
| 95 |
|
| 96 |
def _download_models_and_configs(self):
|
| 97 |
-
"""
|
| 98 |
-
Baixa os checkpoints necessários E o arquivo de configuração do VAE que pode estar faltando.
|
| 99 |
-
"""
|
| 100 |
logger.info("Verificando e baixando modelos e configurações do SeedVR2...")
|
| 101 |
ckpt_dir = SEEDVR_REPO_DIR / 'ckpts'
|
| 102 |
config_dir = SEEDVR_REPO_DIR / 'configs' / 'vae'
|
| 103 |
ckpt_dir.mkdir(exist_ok=True)
|
| 104 |
config_dir.mkdir(parents=True, exist_ok=True)
|
| 105 |
-
|
| 106 |
-
# Baixa a configuração do VAE para garantir que ela exista
|
| 107 |
_load_file_from_url(url=VAE_CONFIG_URL, model_dir=str(config_dir))
|
| 108 |
-
|
| 109 |
pretrain_model_urls = {
|
| 110 |
'vae_ckpt': 'https://huggingface.co/ByteDance-Seed/SeedVR2-3B/resolve/main/ema_vae.pth',
|
| 111 |
'dit_3b': 'https://huggingface.co/ByteDance-Seed/SeedVR2-3B/resolve/main/seedvr2_ema_3b.pth',
|
|
@@ -113,18 +94,14 @@ class SeedVrManager:
|
|
| 113 |
'pos_emb': 'https://huggingface.co/ByteDance-Seed/SeedVR2-3B/resolve/main/pos_emb.pt',
|
| 114 |
'neg_emb': 'https://huggingface.co/ByteDance-Seed/SeedVR2-3B/resolve/main/neg_emb.pt'
|
| 115 |
}
|
| 116 |
-
|
| 117 |
for key, url in pretrain_model_urls.items():
|
| 118 |
_load_file_from_url(url=url, model_dir=str(ckpt_dir))
|
| 119 |
-
|
| 120 |
logger.info("Modelos e configurações do SeedVR2 baixados com sucesso.")
|
| 121 |
|
| 122 |
def _initialize_runner(self, model_version: str):
|
| 123 |
-
"""Carrega e configura o modelo SeedVR
|
| 124 |
if self.runner is not None: return
|
| 125 |
-
|
| 126 |
self._download_models_and_configs()
|
| 127 |
-
|
| 128 |
logger.info(f"Inicializando o executor do SeedVR2 {model_version}...")
|
| 129 |
if model_version == '3B':
|
| 130 |
config_path = SEEDVR_REPO_DIR / 'configs_3b' / 'main.yaml'
|
|
@@ -135,23 +112,22 @@ class SeedVrManager:
|
|
| 135 |
else:
|
| 136 |
raise ValueError(f"Versão do modelo SeedVR não suportada: {model_version}")
|
| 137 |
|
| 138 |
-
|
| 139 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 140 |
self.runner = VideoDiffusionInfer(config)
|
| 141 |
OmegaConf.set_readonly(self.runner.config, False)
|
| 142 |
-
|
| 143 |
self.runner.configure_dit_model(device=self.device, checkpoint=str(checkpoint_path))
|
| 144 |
-
|
| 145 |
-
# --- CORREÇÃO APLICADA AQUI ---
|
| 146 |
-
correct_vae_config_path = SEEDVR_REPO_DIR / 'configs' / 'vae' / 's8_c16_t4_inflation_sd3.yaml'
|
| 147 |
-
logger.info(f"Corrigindo o caminho da configuração do VAE para: {correct_vae_config_path}")
|
| 148 |
-
self.runner.config.vae.config = str(correct_vae_config_path)
|
| 149 |
-
|
| 150 |
self.runner.configure_vae_model()
|
| 151 |
-
|
| 152 |
if hasattr(self.runner.vae, "set_memory_limit"):
|
| 153 |
self.runner.vae.set_memory_limit(**self.runner.config.vae.memory_limit)
|
| 154 |
-
|
| 155 |
self.is_initialized = True
|
| 156 |
logger.info(f"Executor para SeedVR2 {model_version} inicializado e pronto.")
|
| 157 |
|
|
|
|
| 2 |
#
|
| 3 |
# Copyright (C) 2025 Carlos Rodrigues dos Santos
|
| 4 |
#
|
| 5 |
+
# Version: 2.3.2
|
| 6 |
#
|
| 7 |
+
# Esta versão implementa uma correção robusta para o FileNotFoundError da configuração do VAE,
|
| 8 |
+
# antecipando a falha, carregando as configurações manualmente e fundindo-as para
|
| 9 |
+
# contornar o caminho fixo problemático na biblioteca externa.
|
| 10 |
|
| 11 |
import torch
|
| 12 |
import os
|
|
|
|
| 21 |
import mediapy
|
| 22 |
from einops import rearrange
|
| 23 |
|
|
|
|
| 24 |
from tools.tensor_utils import wavelet_reconstruction
|
| 25 |
|
| 26 |
logger = logging.getLogger(__name__)
|
|
|
|
| 29 |
DEPS_DIR = Path("./deps")
|
| 30 |
SEEDVR_REPO_DIR = DEPS_DIR / "SeedVR"
|
| 31 |
SEEDVR_REPO_URL = "https://github.com/ByteDance-Seed/SeedVR.git"
|
|
|
|
| 32 |
VAE_CONFIG_URL = "https://raw.githubusercontent.com/ByteDance-Seed/SeedVR/main/models/video_vae_v3/s8_c16_t4_inflation_sd3.yaml"
|
| 33 |
|
| 34 |
def setup_seedvr_dependencies():
|
| 35 |
+
"""Garante que o repositório do SeedVR seja clonado e esteja disponível no sys.path."""
|
|
|
|
|
|
|
|
|
|
| 36 |
if not SEEDVR_REPO_DIR.exists():
|
| 37 |
logger.info(f"Repositório SeedVR não encontrado em '{SEEDVR_REPO_DIR}'. Clonando do GitHub...")
|
| 38 |
try:
|
| 39 |
DEPS_DIR.mkdir(exist_ok=True)
|
| 40 |
+
subprocess.run(["git", "clone", "--depth", "1", SEEDVR_REPO_URL, str(SEEDVR_REPO_DIR)], check=True, capture_output=True, text=True)
|
|
|
|
|
|
|
|
|
|
| 41 |
logger.info("Repositório SeedVR clonado com sucesso.")
|
| 42 |
except subprocess.CalledProcessError as e:
|
| 43 |
logger.error(f"Falha ao clonar o repositório SeedVR. Git stderr: {e.stderr}")
|
|
|
|
| 49 |
sys.path.insert(0, str(SEEDVR_REPO_DIR.resolve()))
|
| 50 |
logger.info(f"Adicionado '{SEEDVR_REPO_DIR.resolve()}' ao sys.path.")
|
| 51 |
|
|
|
|
| 52 |
setup_seedvr_dependencies()
|
| 53 |
|
|
|
|
| 54 |
from projects.video_diffusion_sr.infer import VideoDiffusionInfer
|
| 55 |
from common.config import load_config
|
| 56 |
from common.seed import set_seed
|
|
|
|
| 61 |
from torchvision.io.video import read_video
|
| 62 |
from omegaconf import OmegaConf
|
| 63 |
|
|
|
|
| 64 |
def _load_file_from_url(url, model_dir='./', file_name=None):
|
|
|
|
| 65 |
os.makedirs(model_dir, exist_ok=True)
|
| 66 |
filename = file_name or os.path.basename(urlparse(url).path)
|
| 67 |
cached_file = os.path.abspath(os.path.join(model_dir, filename))
|
|
|
|
| 71 |
return cached_file
|
| 72 |
|
| 73 |
class SeedVrManager:
|
| 74 |
+
"""Gerencia o modelo SeedVR para tarefas de Masterização HD."""
|
|
|
|
|
|
|
| 75 |
def __init__(self, workspace_dir="deformes_workspace"):
|
| 76 |
self.device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
| 77 |
self.runner = None
|
|
|
|
| 80 |
logger.info("SeedVrManager inicializado. O modelo será carregado sob demanda.")
|
| 81 |
|
| 82 |
def _download_models_and_configs(self):
|
| 83 |
+
"""Baixa os checkpoints necessários E o arquivo de configuração do VAE que pode estar faltando."""
|
|
|
|
|
|
|
| 84 |
logger.info("Verificando e baixando modelos e configurações do SeedVR2...")
|
| 85 |
ckpt_dir = SEEDVR_REPO_DIR / 'ckpts'
|
| 86 |
config_dir = SEEDVR_REPO_DIR / 'configs' / 'vae'
|
| 87 |
ckpt_dir.mkdir(exist_ok=True)
|
| 88 |
config_dir.mkdir(parents=True, exist_ok=True)
|
|
|
|
|
|
|
| 89 |
_load_file_from_url(url=VAE_CONFIG_URL, model_dir=str(config_dir))
|
|
|
|
| 90 |
pretrain_model_urls = {
|
| 91 |
'vae_ckpt': 'https://huggingface.co/ByteDance-Seed/SeedVR2-3B/resolve/main/ema_vae.pth',
|
| 92 |
'dit_3b': 'https://huggingface.co/ByteDance-Seed/SeedVR2-3B/resolve/main/seedvr2_ema_3b.pth',
|
|
|
|
| 94 |
'pos_emb': 'https://huggingface.co/ByteDance-Seed/SeedVR2-3B/resolve/main/pos_emb.pt',
|
| 95 |
'neg_emb': 'https://huggingface.co/ByteDance-Seed/SeedVR2-3B/resolve/main/neg_emb.pt'
|
| 96 |
}
|
|
|
|
| 97 |
for key, url in pretrain_model_urls.items():
|
| 98 |
_load_file_from_url(url=url, model_dir=str(ckpt_dir))
|
|
|
|
| 99 |
logger.info("Modelos e configurações do SeedVR2 baixados com sucesso.")
|
| 100 |
|
| 101 |
def _initialize_runner(self, model_version: str):
|
| 102 |
+
"""Carrega e configura o modelo SeedVR, com uma correção robusta para o caminho da config do VAE."""
|
| 103 |
if self.runner is not None: return
|
|
|
|
| 104 |
self._download_models_and_configs()
|
|
|
|
| 105 |
logger.info(f"Inicializando o executor do SeedVR2 {model_version}...")
|
| 106 |
if model_version == '3B':
|
| 107 |
config_path = SEEDVR_REPO_DIR / 'configs_3b' / 'main.yaml'
|
|
|
|
| 112 |
else:
|
| 113 |
raise ValueError(f"Versão do modelo SeedVR não suportada: {model_version}")
|
| 114 |
|
| 115 |
+
try:
|
| 116 |
+
config = load_config(str(config_path))
|
| 117 |
+
except FileNotFoundError:
|
| 118 |
+
logger.warning("FileNotFoundError esperado capturado. Carregando config manualmente.")
|
| 119 |
+
config = OmegaConf.load(str(config_path))
|
| 120 |
+
correct_vae_config_path = SEEDVR_REPO_DIR / 'configs' / 'vae' / 's8_c16_t4_inflation_sd3.yaml'
|
| 121 |
+
vae_config = OmegaConf.load(str(correct_vae_config_path))
|
| 122 |
+
config.vae = vae_config
|
| 123 |
+
logger.info("Configuração carregada e corrigida manualmente com sucesso.")
|
| 124 |
+
|
| 125 |
self.runner = VideoDiffusionInfer(config)
|
| 126 |
OmegaConf.set_readonly(self.runner.config, False)
|
|
|
|
| 127 |
self.runner.configure_dit_model(device=self.device, checkpoint=str(checkpoint_path))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 128 |
self.runner.configure_vae_model()
|
|
|
|
| 129 |
if hasattr(self.runner.vae, "set_memory_limit"):
|
| 130 |
self.runner.vae.set_memory_limit(**self.runner.config.vae.memory_limit)
|
|
|
|
| 131 |
self.is_initialized = True
|
| 132 |
logger.info(f"Executor para SeedVR2 {model_version} inicializado e pronto.")
|
| 133 |
|