Update setup.py
Browse files
setup.py
CHANGED
|
@@ -1,135 +1,181 @@
|
|
| 1 |
# setup.py
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
|
| 3 |
import os
|
| 4 |
import subprocess
|
| 5 |
import sys
|
| 6 |
from pathlib import Path
|
| 7 |
import yaml
|
| 8 |
-
|
| 9 |
-
# Adiciona a importação do hf_hub_download
|
| 10 |
from huggingface_hub import hf_hub_download
|
| 11 |
|
| 12 |
-
# --- Configuração ---
|
| 13 |
DEPS_DIR = Path("/data")
|
| 14 |
-
MODELS_ROOT = DEPS_DIR / "ltx_models" # Diretório centralizado para modelos
|
| 15 |
|
| 16 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
REPOS_TO_CLONE = {
|
| 18 |
"LTX-Video": "https://huggingface.co/spaces/Lightricks/ltx-video-distilled",
|
| 19 |
-
"
|
| 20 |
"MMAudio": "https://github.com/hkchengrex/MMAudio.git"
|
| 21 |
}
|
| 22 |
|
| 23 |
-
def run_command(command, cwd=None
|
| 24 |
-
"""Executa um comando no terminal e
|
| 25 |
-
if is_pip:
|
| 26 |
-
command = [sys.executable, "-m", "pip"] + command
|
| 27 |
-
|
| 28 |
print(f"Executando: {' '.join(command)}")
|
| 29 |
try:
|
| 30 |
-
|
| 31 |
-
command,
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
return_code = process.wait()
|
| 38 |
-
if return_code != 0:
|
| 39 |
-
raise subprocess.CalledProcessError(return_code, command)
|
| 40 |
except subprocess.CalledProcessError as e:
|
| 41 |
-
print(f"ERRO: O comando falhou com o código de saída {e.returncode}")
|
| 42 |
sys.exit(1)
|
| 43 |
except FileNotFoundError:
|
| 44 |
-
print(f"ERRO: O comando '{command[0]}' não foi encontrado.")
|
| 45 |
-
sys.exit(1)
|
| 46 |
-
|
| 47 |
-
def clone_repos():
|
| 48 |
-
"""ETAPA 1: Garante que todos os repositórios de código necessários existam."""
|
| 49 |
-
print("--- ETAPA 1: Verificando e clonando repositórios de código ---")
|
| 50 |
-
for repo_name, repo_url in REPOS_TO_CLONE.items():
|
| 51 |
-
repo_path = DEPS_DIR / repo_name
|
| 52 |
-
if repo_path.exists() and (repo_path / ".git").exists():
|
| 53 |
-
print(f"Repositório '{repo_name}' já existe. Pulando.")
|
| 54 |
-
else:
|
| 55 |
-
print(f"Clonando '{repo_name}' de {repo_url}...")
|
| 56 |
-
run_command(["git", "clone", "--depth", "1", "-q", repo_url, str(repo_path)])
|
| 57 |
-
print(f"'{repo_name}' clonado com sucesso.")
|
| 58 |
-
|
| 59 |
-
def install_ltx_dependencies():
|
| 60 |
-
"""ETAPA 2: Instala as dependências Python do LTX-Video."""
|
| 61 |
-
print("\n--- ETAPA 2: Instalando dependências Python do LTX-Video ---")
|
| 62 |
-
ltx_repo_path = DEPS_DIR / "LTX-Video"
|
| 63 |
-
if ltx_repo_path.exists():
|
| 64 |
-
run_command(["install", "-e", ".[inference]"], cwd=str(ltx_repo_path), is_pip=True)
|
| 65 |
-
print("Dependências do LTX-Video instaladas com sucesso.")
|
| 66 |
-
else:
|
| 67 |
-
print("ERRO CRÍTICO: Diretório LTX-Video não encontrado. Não foi possível instalar dependências.")
|
| 68 |
sys.exit(1)
|
| 69 |
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
""
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 80 |
|
| 81 |
-
|
| 82 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 83 |
sys.exit(1)
|
| 84 |
|
| 85 |
-
|
| 86 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 87 |
try:
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
required_model_files.add(config["spatial_upscaler_model_path"])
|
| 94 |
except Exception as e:
|
| 95 |
-
print(f"
|
|
|
|
| 96 |
|
| 97 |
-
if not required_model_files:
|
| 98 |
-
print("AVISO: Nenhum arquivo de modelo foi encontrado nos arquivos de configuração. Verifique os configs.")
|
| 99 |
-
return
|
| 100 |
|
| 101 |
-
|
| 102 |
-
|
|
|
|
|
|
|
| 103 |
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 110 |
try:
|
| 111 |
hf_hub_download(
|
| 112 |
-
repo_id=
|
| 113 |
-
filename=
|
| 114 |
-
local_dir=str(
|
| 115 |
cache_dir=os.getenv("HF_HOME_CACHE"),
|
| 116 |
token=os.getenv("HF_TOKEN"),
|
|
|
|
| 117 |
)
|
| 118 |
-
print(f"'{
|
| 119 |
except Exception as e:
|
| 120 |
-
print(f"ERRO
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 121 |
|
| 122 |
def main():
|
| 123 |
-
print("--- Iniciando Setup
|
| 124 |
DEPS_DIR.mkdir(exist_ok=True)
|
| 125 |
|
| 126 |
-
#
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 130 |
|
| 131 |
-
print("\n---
|
| 132 |
-
print("Todos os repositórios
|
|
|
|
| 133 |
|
| 134 |
if __name__ == "__main__":
|
| 135 |
main()
|
|
|
|
| 1 |
# setup.py
|
| 2 |
+
#
|
| 3 |
+
# Copyright (C) August 4, 2025 Carlos Rodrigues dos Santos
|
| 4 |
+
#
|
| 5 |
+
# Versão 2.3.0 (Setup Robusto e Idempotente)
|
| 6 |
+
# - Verifica a existência de repositórios e arquivos de modelo antes de baixar.
|
| 7 |
+
# - Pula downloads se os artefatos já existirem, sem gerar erros.
|
| 8 |
+
# - Unifica o download de todas as dependências (Git, LTX Models, SeedVR Models).
|
| 9 |
|
| 10 |
import os
|
| 11 |
import subprocess
|
| 12 |
import sys
|
| 13 |
from pathlib import Path
|
| 14 |
import yaml
|
|
|
|
|
|
|
| 15 |
from huggingface_hub import hf_hub_download
|
| 16 |
|
| 17 |
+
# --- Configuração Geral ---
|
| 18 |
DEPS_DIR = Path("/data")
|
|
|
|
| 19 |
|
| 20 |
+
# --- Configuração Específica LTX-Video ---
|
| 21 |
+
LTX_VIDEO_REPO_DIR = DEPS_DIR / "LTX-Video"
|
| 22 |
+
|
| 23 |
+
# --- Configuração Específica SeedVR ---
|
| 24 |
+
SEEDVR_MODELS_DIR = DEPS_DIR / "SeedVR"
|
| 25 |
+
|
| 26 |
+
# --- Repositórios para Clonar ---
|
| 27 |
REPOS_TO_CLONE = {
|
| 28 |
"LTX-Video": "https://huggingface.co/spaces/Lightricks/ltx-video-distilled",
|
| 29 |
+
"SeedVR": "https://huggingface.co/spaces/ByteDance-Seed/SeedVR2-3B",
|
| 30 |
"MMAudio": "https://github.com/hkchengrex/MMAudio.git"
|
| 31 |
}
|
| 32 |
|
| 33 |
+
def run_command(command, cwd=None):
|
| 34 |
+
"""Executa um comando no terminal e lida com erros."""
|
|
|
|
|
|
|
|
|
|
| 35 |
print(f"Executando: {' '.join(command)}")
|
| 36 |
try:
|
| 37 |
+
subprocess.run(
|
| 38 |
+
command,
|
| 39 |
+
check=True,
|
| 40 |
+
cwd=cwd,
|
| 41 |
+
stdin=subprocess.DEVNULL,
|
| 42 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
except subprocess.CalledProcessError as e:
|
| 44 |
+
print(f"ERRO: O comando falhou com o código de saída {e.returncode}\nStderr: {e.stderr}")
|
| 45 |
sys.exit(1)
|
| 46 |
except FileNotFoundError:
|
| 47 |
+
print(f"ERRO: O comando '{command[0]}' não foi encontrado. Certifique-se de que o git está instalado e no seu PATH.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
sys.exit(1)
|
| 49 |
|
| 50 |
+
# --- Funções de Download (LTX-Video) ---
|
| 51 |
+
|
| 52 |
+
def _load_ltx_config():
|
| 53 |
+
"""Carrega o arquivo de configuração YAML do LTX-Video."""
|
| 54 |
+
print("--- Carregando Configuração do LTX-Video ---")
|
| 55 |
+
base = LTX_VIDEO_REPO_DIR / "configs"
|
| 56 |
+
candidates = [
|
| 57 |
+
base / "ltxv-13b-0.9.8-dev-fp8.yaml",
|
| 58 |
+
base / "ltxv-13b-0.9.8-distilled-fp8.yaml",
|
| 59 |
+
base / "ltxv-13b-0.9.8-distilled.yaml",
|
| 60 |
+
]
|
| 61 |
+
for cfg_path in candidates:
|
| 62 |
+
if cfg_path.exists():
|
| 63 |
+
print(f"Configuração encontrada: {cfg_path}")
|
| 64 |
+
with open(cfg_path, "r") as file:
|
| 65 |
+
return yaml.safe_load(file)
|
| 66 |
+
|
| 67 |
+
fallback_path = base / "ltxv-13b-0.9.8-distilled-fp8.yaml"
|
| 68 |
+
print(f"AVISO: Nenhuma configuração preferencial encontrada. Usando fallback: {fallback_path}")
|
| 69 |
+
if not fallback_path.exists():
|
| 70 |
+
print(f"ERRO: Arquivo de configuração fallback '{fallback_path}' não encontrado.")
|
| 71 |
+
return None
|
| 72 |
+
|
| 73 |
+
with open(fallback_path, "r") as file:
|
| 74 |
+
return yaml.safe_load(file)
|
| 75 |
|
| 76 |
+
def _download_ltx_models(config):
|
| 77 |
+
"""Baixa os modelos principais do LTX-Video, pulando os que já existem."""
|
| 78 |
+
print("\n--- Verificando Modelos do LTX-Video ---")
|
| 79 |
+
LTX_REPO = "Lightricks/LTX-Video"
|
| 80 |
+
|
| 81 |
+
if "checkpoint_path" not in config or "spatial_upscaler_model_path" not in config:
|
| 82 |
+
print("ERRO: Chaves de modelo não encontradas no arquivo de configuração do LTX.")
|
| 83 |
sys.exit(1)
|
| 84 |
|
| 85 |
+
models_to_download = {
|
| 86 |
+
config["checkpoint_path"]: "checkpoint principal",
|
| 87 |
+
config["spatial_upscaler_model_path"]: "upscaler espacial"
|
| 88 |
+
}
|
| 89 |
+
|
| 90 |
+
# O hf_hub_download já verifica o cache, mas vamos verificar o diretório final para clareza
|
| 91 |
+
# e para garantir que a lógica seja explícita.
|
| 92 |
+
for filename, description in models_to_download.items():
|
| 93 |
+
# A biblioteca huggingface_hub gerencia o local exato, então confiamos nela.
|
| 94 |
+
# A verificação aqui é para garantir que o download seja tentado.
|
| 95 |
+
print(f"Garantindo a existência do {description}: {filename}...")
|
| 96 |
try:
|
| 97 |
+
hf_hub_download(
|
| 98 |
+
repo_id=LTX_REPO, filename=filename,
|
| 99 |
+
local_dir=os.getenv("HF_HOME"), cache_dir=os.getenv("HF_HOME_CACHE"), token=os.getenv("HF_TOKEN")
|
| 100 |
+
)
|
| 101 |
+
print(f"{description.capitalize()} está disponível.")
|
|
|
|
| 102 |
except Exception as e:
|
| 103 |
+
print(f"ERRO ao baixar o {description}: {e}")
|
| 104 |
+
sys.exit(1)
|
| 105 |
|
|
|
|
|
|
|
|
|
|
| 106 |
|
| 107 |
+
def _download_seedvr_models():
|
| 108 |
+
"""Baixa os modelos do SeedVR, pulando os que já existem."""
|
| 109 |
+
print(f"\n--- Verificando Checkpoints do SeedVR em {SEEDVR_MODELS_DIR} ---")
|
| 110 |
+
SEEDVR_MODELS_DIR.mkdir(exist_ok=True)
|
| 111 |
|
| 112 |
+
model_files = {
|
| 113 |
+
"seedvr2_ema_7b_fp16.safetensors": "MonsterMMORPG/SeedVR2_SECourses",
|
| 114 |
+
"seedvr2_ema_7b_sharp_fp16.safetensors": "MonsterMMORPG/SeedVR2_SECourses",
|
| 115 |
+
"seedvr2_ema_3b_fp16.safetensors": "MonsterMMORPG/SeedVR2_SECourses",
|
| 116 |
+
"ema_vae_fp16.safetensors": "MonsterMMORPG/SeedVR2_SECourses",
|
| 117 |
+
"pos_emb.pt": "ByteDance-Seed/SeedVR2-3B",
|
| 118 |
+
"neg_emb.pt": "ByteDance-Seed/SeedVR2-3B"
|
| 119 |
+
}
|
| 120 |
+
|
| 121 |
+
for filename, repo_id in model_files.items():
|
| 122 |
+
local_path = SEEDVR_MODELS_DIR / filename
|
| 123 |
+
if not local_path.is_file(): # Verifica se é um arquivo
|
| 124 |
+
print(f"Baixando {filename} de {repo_id}...")
|
| 125 |
try:
|
| 126 |
hf_hub_download(
|
| 127 |
+
repo_id=repo_id,
|
| 128 |
+
filename=filename,
|
| 129 |
+
local_dir=str(SEEDVR_MODELS_DIR),
|
| 130 |
cache_dir=os.getenv("HF_HOME_CACHE"),
|
| 131 |
token=os.getenv("HF_TOKEN"),
|
| 132 |
+
local_dir_use_symlinks=False
|
| 133 |
)
|
| 134 |
+
print(f"'{filename}' baixado com sucesso.")
|
| 135 |
except Exception as e:
|
| 136 |
+
print(f"ERRO ao baixar o modelo SeedVR '{filename}': {e}")
|
| 137 |
+
sys.exit(1)
|
| 138 |
+
else:
|
| 139 |
+
print(f"Arquivo '{filename}' já existe. Pulando.")
|
| 140 |
+
print("Checkpoints do SeedVR estão no local correto.")
|
| 141 |
+
|
| 142 |
+
# --- Função Principal ---
|
| 143 |
|
| 144 |
def main():
|
| 145 |
+
print("--- Iniciando Setup do Ambiente ADUC-SDR (Versão Robusta) ---")
|
| 146 |
DEPS_DIR.mkdir(exist_ok=True)
|
| 147 |
|
| 148 |
+
# --- ETAPA 1: Clonar Repositórios ---
|
| 149 |
+
print("\n--- ETAPA 1: Clonando Repositórios Git ---")
|
| 150 |
+
for repo_name, repo_url in REPOS_TO_CLONE.items():
|
| 151 |
+
repo_path = DEPS_DIR / repo_name
|
| 152 |
+
if repo_path.is_dir(): # Verifica se é um diretório
|
| 153 |
+
print(f"Repositório '{repo_name}' já existe. Pulando.")
|
| 154 |
+
else:
|
| 155 |
+
print(f"Clonando '{repo_name}' de {repo_url}...")
|
| 156 |
+
run_command(["git", "clone", "--depth", "1", repo_url, str(repo_path)])
|
| 157 |
+
print(f"'{repo_name}' clonado com sucesso.")
|
| 158 |
+
|
| 159 |
+
# --- ETAPA 2: Baixar Modelos do LTX-Video ---
|
| 160 |
+
print("\n--- ETAPA 2: Preparando Modelos LTX-Video ---")
|
| 161 |
+
if not LTX_VIDEO_REPO_DIR.is_dir():
|
| 162 |
+
print(f"ERRO: Diretório '{LTX_VIDEO_REPO_DIR}' não encontrado. Execute a clonagem primeiro.")
|
| 163 |
+
sys.exit(1)
|
| 164 |
+
|
| 165 |
+
ltx_config = _load_ltx_config()
|
| 166 |
+
if ltx_config:
|
| 167 |
+
_download_ltx_models(ltx_config)
|
| 168 |
+
else:
|
| 169 |
+
print("ERRO: Não foi possível carregar a configuração do LTX-Video. Abortando.")
|
| 170 |
+
sys.exit(1)
|
| 171 |
+
|
| 172 |
+
# --- ETAPA 3: Baixar Modelos do SeedVR ---
|
| 173 |
+
print("\n--- ETAPA 3: Preparando Modelos SeedVR ---")
|
| 174 |
+
_download_seedvr_models()
|
| 175 |
|
| 176 |
+
print("\n\n--- Setup do Ambiente Concluído com Sucesso! ---")
|
| 177 |
+
print("Todos os repositórios e modelos necessários foram verificados e estão prontos.")
|
| 178 |
+
print("Você agora pode iniciar a aplicação principal.")
|
| 179 |
|
| 180 |
if __name__ == "__main__":
|
| 181 |
main()
|