File size: 7,568 Bytes
ac23084
4fe2b05
 
 
1d458ad
 
 
ac23084
 
 
 
 
edb8974
1d458ad
ac23084
1d458ad
 
 
 
34480b6
1d458ad
ac23084
1d458ad
4fe2b05
1d458ad
 
 
4fe2b05
1d458ad
ac23084
 
b049923
1d458ad
ac23084
 
1d458ad
 
 
 
4fe2b05
1d458ad
ac23084
 
4fe2b05
1d458ad
 
4fe2b05
ac23084
1d458ad
ac23084
 
1d458ad
edb8974
 
4fe2b05
 
 
1d458ad
 
 
4fe2b05
1d458ad
 
4fe2b05
a07fd79
1d458ad
 
 
4fe2b05
1d458ad
 
 
 
 
edb8974
1d458ad
 
 
a07fd79
edb8974
1d458ad
 
 
 
 
 
 
 
 
 
 
4fe2b05
1d458ad
 
 
edb8974
 
1d458ad
 
edb8974
1d458ad
edb8974
4fe2b05
1d458ad
4fe2b05
 
1d458ad
 
4fe2b05
 
 
1d458ad
4fe2b05
1d458ad
 
4fe2b05
1d458ad
4fe2b05
 
1d458ad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4fe2b05
1d458ad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
edb8974
1d458ad
 
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
# setup.py
#
# Copyright (C) August 4, 2025  Carlos Rodrigues dos Santos
#
# Versão 3.1.0 (Setup Unificado com LTX, SeedVR e VINCIE com Cache Robusto)
# - Orquestra a instalação de todos os repositórios e modelos para a suíte ADUC-SDR.
# - Usa snapshot_download para baixar dependências de forma eficiente e correta.

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 que /data é um volume persistente montado no contêiner.
DEPS_DIR = Path("/data")
CACHE_DIR = DEPS_DIR / ".cache" / "huggingface"

# --- Paths 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",
}

# ==============================================================================
# --- FUNÇÕES AUXILIARES ---
# ==============================================================================

def run_command(command, cwd=None):
    """Executa um comando no terminal de forma segura e com logs claros."""
    print(f"Executando: {' '.join(command)}")
    try:
        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}\nStderr:\n{e.stderr.strip()}")
        sys.exit(1)
    except FileNotFoundError:
        print(f"ERRO: Comando '{command[0]}' não encontrado. Verifique se o git está instalado.")
        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 _ensure_hf_model(repo_id, filenames=None, allow_patterns=None, local_dir=None):
    """Função genérica para baixar um ou mais arquivos (hf_hub_download) ou um snapshot (snapshot_download)."""
    if not repo_id: return
    
    print(f"Verificando/Baixando modelo do repositório: '{repo_id}'...")
    try:
        if filenames: # Baixa arquivos específicos
            for filename in filenames:
                if not filename: continue
                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, 
                    token=os.getenv("HF_TOKEN"),
                )
        else: # Baixa um snapshot (partes de um repositório)
            snapshot_download(
                repo_id=repo_id, cache_dir=str(CACHE_DIR), 
                local_dir=str(local_dir) if local_dir else None,
                allow_patterns=allow_patterns, 
                token=os.getenv("HF_TOKEN"),
            )
        print(f"-> Modelo '{repo_id}' está disponível.")
    except Exception as e:
        print(f"ERRO CRÍTICO ao baixar o modelo '{repo_id}': {e}")
        sys.exit(1)

# ==============================================================================
# --- FUNÇÃO PRINCIPAL DE SETUP ---
# ==============================================================================

def main():
    """Orquestra todo o processo de setup do ambiente."""
    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 LTX-Video e 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)
        
    _ensure_hf_model(
        repo_id="Lightricks/LTX-Video",
        filenames=[
            ltx_config.get("checkpoint_path"), 
            ltx_config.get("spatial_upscaler_model_path") # <-- Adicione esta linha
        ]
    )
    
    _ensure_hf_model(
        repo_id=ltx_config.get("text_encoder_model_name_or_path"),
        allow_patterns=["*.json", "*.safetensors"]
    )
    
    enhancer_repos = [
        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, enhancer_repos):
         _ensure_hf_model(repo_id=repo_id, allow_patterns=["*.json", "*.safetensors", "*.bin"])

    # --- ETAPA 3: Baixar Modelos 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():
             _ensure_hf_model(repo_id=repo_id, filenames=[filename], 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)
    _ensure_hf_model(repo_id="ByteDance-Seed/VINCIE-3B", local_dir=VINCIE_CKPT_DIR)
    
    # Cria o symlink de compatibilidade, se necessário
    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.")

    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()