Spaces:
Paused
Paused
File size: 7,627 Bytes
ac23084 4fe2b05 f912feb ac23084 edb8974 f912feb ac23084 f912feb 34480b6 f912feb ac23084 f912feb 4fe2b05 f912feb 4fe2b05 f912feb ac23084 b049923 f912feb ac23084 4fe2b05 f912feb ac23084 f912feb 4fe2b05 f912feb 4fe2b05 ac23084 f912feb ac23084 f912feb edb8974 4fe2b05 f912feb 4fe2b05 f912feb 4fe2b05 f912feb 4fe2b05 a07fd79 f912feb edb8974 4fe2b05 f912feb 4fe2b05 f912feb edb8974 f912feb 4fe2b05 edb8974 f912feb edb8974 f912feb edb8974 4fe2b05 f912feb 4fe2b05 f912feb 4fe2b05 f912feb 4fe2b05 f912feb 4fe2b05 f912feb 4fe2b05 f912feb 4fe2b05 f912feb edb8974 f912feb ac23084 edb8974 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 |
# setup.py
#
# Copyright (C) August 4, 2025 Carlos Rodrigues dos Santos
#
# Versão 3.0.0 (Setup Unificado com LTX, SeedVR e VINCIE)
# - Orquestra a instalação de todos os repositórios e modelos para a suíte ADUC-SDR.
# - Garante que todos os downloads usem um cache persistente para inicializações rápidas.
import os
import subprocess
import sys
from pathlib import Path
import yaml
from huggingface_hub import hf_hub_download, snapshot_download
# --- Configuração de Paths e Cache ---
# Assume-se que /data é um volume persistente montado no contêiner.
DEPS_DIR = Path("/data")
CACHE_DIR = DEPS_DIR / ".cache" / "huggingface"
# --- Configuração dos Módulos da Aplicação ---
LTX_VIDEO_REPO_DIR = DEPS_DIR / "LTX-Video"
SEEDVR_MODELS_DIR = DEPS_DIR / "models" / "SeedVR"
VINCIE_REPO_DIR = DEPS_DIR / "VINCIE"
VINCIE_CKPT_DIR = DEPS_DIR / "ckpt" / "VINCIE-3B"
# --- Repositórios Git para Clonar ---
REPOS_TO_CLONE = {
"LTX-Video": "https://huggingface.co/spaces/Lightricks/ltx-video-distilled",
"SeedVR": "https://github.com/numz/ComfyUI-SeedVR2_VideoUpscaler",
"VINCIE": "https://github.com/ByteDance-Seed/VINCIE",
}
def run_command(command, cwd=None):
"""Executa um comando no terminal de forma segura e com logs claros."""
print(f"Executando: {' '.join(command)}")
try:
# Usamos check=True para lançar uma exceção se o comando falhar.
subprocess.run(
command,
check=True,
cwd=cwd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
)
except subprocess.CalledProcessError as e:
print(f"ERRO: O comando falhou com o código {e.returncode}")
print(f"Stderr:\n{e.stderr.strip()}")
sys.exit(1)
except FileNotFoundError:
print(f"ERRO: Comando '{command[0]}' não encontrado. Verifique se o git está instalado no contêiner.")
sys.exit(1)
def _load_ltx_config():
"""Carrega o arquivo de configuração YAML do LTX-Video."""
print("--- Carregando Configuração do LTX-Video ---")
config_file = LTX_VIDEO_REPO_DIR / "configs" / "ltxv-13b-0.9.8-distilled-fp8.yaml"
if not config_file.exists():
print(f"ERRO: Arquivo de configuração do LTX não encontrado em '{config_file}'")
return None
print(f"Configuração LTX encontrada: {config_file}")
with open(config_file, "r") as file:
return yaml.safe_load(file)
def _download_models_from_hub(repo_id, filenames, cache_dir, local_dir=None):
"""Função auxiliar genérica para baixar arquivos do Hugging Face Hub."""
for filename in filenames:
if not filename: continue
print(f"Verificando/Baixando '{filename}' de '{repo_id}'...")
try:
hf_hub_download(
repo_id=repo_id,
filename=filename,
cache_dir=str(cache_dir),
local_dir=str(local_dir) if local_dir else None,
local_dir_use_symlinks=False, # Salva o arquivo real, não um link simbólico
token=os.getenv("HF_TOKEN"),
)
print(f"-> '{filename}' está disponível.")
except Exception as e:
if "404" in str(e) or "Not Found" in str(e):
print(f"AVISO: Arquivo '{filename}' não encontrado em '{repo_id}'. Isso pode ser normal se for um ponteiro para um diretório (como em Text Encoders). Continuando.")
else:
print(f"ERRO CRÍTICO ao baixar '{filename}': {e}")
sys.exit(1)
def main():
"""Função principal que orquestra todo o processo de setup."""
print("--- Iniciando Setup do Ambiente ADUC-SDR (LTX + SeedVR + VINCIE) ---")
DEPS_DIR.mkdir(exist_ok=True)
CACHE_DIR.mkdir(parents=True, exist_ok=True)
# --- ETAPA 1: Clonar Repositórios ---
print("\n--- ETAPA 1: Verificando Repositórios Git ---")
for repo_name, repo_url in REPOS_TO_CLONE.items():
repo_path = DEPS_DIR / repo_name
if repo_path.is_dir():
print(f"Repositório '{repo_name}' já existe em '{repo_path}'. Pulando.")
else:
print(f"Clonando '{repo_name}' de {repo_url}...")
run_command(["git", "clone", "--depth", "1", repo_url, str(repo_path)])
print(f"-> '{repo_name}' clonado com sucesso.")
# --- ETAPA 2: Baixar Modelos do LTX-Video e suas Dependências ---
print("\n--- ETAPA 2: Verificando Modelos LTX-Video e Dependências ---")
ltx_config = _load_ltx_config()
if not ltx_config:
print("ERRO: Não foi possível carregar a configuração do LTX-Video. Abortando.")
sys.exit(1)
_download_models_from_hub(
repo_id="Lightricks/LTX-Video",
filenames=[ltx_config.get("checkpoint_path"), ltx_config.get("spatial_upscaler_model_path")],
cache_dir=CACHE_DIR
)
dependency_repos = [
ltx_config.get("text_encoder_model_name_or_path"),
ltx_config.get("prompt_enhancer_image_caption_model_name_or_path"),
ltx_config.get("prompt_enhancer_llm_model_name_or_path"),
]
for repo_id in filter(None, dependency_repos):
_download_models_from_hub(repo_id=repo_id, filenames=["config.json"], cache_dir=CACHE_DIR)
# --- ETAPA 3: Baixar Modelos do SeedVR ---
print("\n--- ETAPA 3: Verificando Modelos SeedVR ---")
SEEDVR_MODELS_DIR.mkdir(parents=True, exist_ok=True)
seedvr_files = {
"seedvr2_ema_7b_fp16.safetensors": "MonsterMMORPG/SeedVR2_SECourses",
"seedvr2_ema_7b_sharp_fp16.safetensors": "MonsterMMORPG/SeedVR2_SECourses",
"ema_vae_fp16.safetensors": "MonsterMMORPG/SeedVR2_SECourses",
}
for filename, repo_id in seedvr_files.items():
if not (SEEDVR_MODELS_DIR / filename).is_file():
_download_models_from_hub(repo_id=repo_id, filenames=[filename], cache_dir=CACHE_DIR, local_dir=SEEDVR_MODELS_DIR)
else:
print(f"Arquivo SeedVR '{filename}' já existe. Pulando.")
# --- ETAPA 4: Baixar Modelos VINCIE ---
print("\n--- ETAPA 4: Verificando Modelos VINCIE ---")
VINCIE_CKPT_DIR.mkdir(parents=True, exist_ok=True)
try:
print(f"Verificando snapshot do VINCIE em '{VINCIE_CKPT_DIR}'...")
# snapshot_download é ideal para baixar um repositório inteiro.
snapshot_download(
repo_id="ByteDance-Seed/VINCIE-3B",
local_dir=str(VINCIE_CKPT_DIR),
cache_dir=str(CACHE_DIR),
force_download=False, # Não baixa novamente se o diretório já estiver completo
token=os.getenv("HF_TOKEN")
)
print("-> Modelos VINCIE estão disponíveis.")
# Cria o symlink de compatibilidade, se necessário, para que o código do VINCIE encontre os modelos
repo_ckpt_dir = VINCIE_REPO_DIR / "ckpt"
repo_ckpt_dir.mkdir(parents=True, exist_ok=True)
link = repo_ckpt_dir / "VINCIE-3B"
if not link.exists():
link.symlink_to(VINCIE_CKPT_DIR.resolve(), target_is_directory=True)
print(f"-> Symlink de compatibilidade VINCIE criado: '{link}' -> '{VINCIE_CKPT_DIR.resolve()}'")
else:
print(f"-> Symlink de compatibilidade VINCIE já existe.")
except Exception as e:
print(f"ERRO CRÍTICO ao baixar modelos VINCIE: {e}")
sys.exit(1)
print("\n\n--- ✅ Setup Completo do Ambiente ADUC-SDR Concluído com Sucesso! ---")
print("Todos os repositórios e modelos foram verificados e estão prontos para uso.")
if __name__ == "__main__":
main() |