adbrasi commited on
Commit
5a91244
·
verified ·
1 Parent(s): 2f1a159

Upload wanFullForTest.sh

Browse files
Files changed (1) hide show
  1. wanFullForTest.sh +592 -0
wanFullForTest.sh ADDED
@@ -0,0 +1,592 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # setup_comfyui_wan22_fixed.sh
3
+ # Script corrigido para instalação do ComfyUI com Wan 2.2
4
+
5
+ set -euo pipefail
6
+
7
+ # -----------------------------
8
+ # Cores para output
9
+ # -----------------------------
10
+ RED='\033[0;31m'
11
+ GREEN='\033[0;32m'
12
+ YELLOW='\033[1;33m'
13
+ BLUE='\033[0;34m'
14
+ NC='\033[0m'
15
+
16
+ log_info() { echo -e "${BLUE}[INFO]${NC} $1"; }
17
+ log_success() { echo -e "${GREEN}[✓]${NC} $1"; }
18
+ log_warn() { echo -e "${YELLOW}[!]${NC} $1"; }
19
+ log_error() { echo -e "${RED}[✗]${NC} $1"; }
20
+
21
+ # -----------------------------
22
+ # Configuração
23
+ # -----------------------------
24
+ COMFY_DIR="/root/comfy/ComfyUI"
25
+ MODELS_DIR="$COMFY_DIR/models"
26
+ COMFY_HOST="${COMFY_HOST:-0.0.0.0}"
27
+ COMFY_PORT="${COMFY_PORT:-8818}"
28
+ CIVITAI_TOKEN="${CIVITAI_TOKEN:-4fcb2834969399006a736ee402b061e5}"
29
+ HF_TOKEN="${HF_TOKEN:-}" # Token opcional do HuggingFace para login
30
+
31
+ # Configurações de performance
32
+ export MAX_JOBS=32
33
+ export NVCC_APPEND_FLAGS="--threads 8"
34
+ export UV_SYSTEM_PYTHON=1
35
+ export PYTORCH_CUDA_ALLOC_CONF="expandable_segments:True"
36
+ export HF_HUB_ENABLE_HF_TRANSFER=1
37
+ export HF_TRANSFER_CONCURRENCY=16
38
+ export EXT_PARALLEL=4
39
+
40
+ # -----------------------------
41
+ # Lista de downloads
42
+ # -----------------------------
43
+ # Formato: "URL|TIPO|NOME_ARQUIVO_OPCIONAL"
44
+ readonly DOWNLOAD_FILES=(
45
+ # Wan 2.2 models
46
+ "hf://Kijai/WanVideo_comfy/Wan22-Lightning/Wan2.2-Lightning_T2V-v1.1-A14B-4steps-lora_HIGH_fp16.safetensors|loras|Wan2.2-Lightning_T2V-v1.1-A14B-4steps-lora_HIGH_fp16.safetensors"
47
+ "hf://Kijai/WanVideo_comfy/Wan22-Lightning/Wan2.2-Lightning_T2V-v1.1-A14B-4steps-lora_LOW_fp16.safetensors|loras|Wan2.2-Lightning_T2V-v1.1-A14B-4steps-lora_LOW_fp16.safetensors"
48
+ "hf://Kijai/WanVideo_comfy_fp8_scaled/I2V/Wan2_2-I2V-A14B-HIGH_fp8_e5m2_scaled_KJ.safetensors|diffusion_models|Wan2_2-I2V-A14B-HIGH_fp8_e5m2_scaled_KJ.safetensors"
49
+ "hf://Kijai/WanVideo_comfy_fp8_scaled/I2V/Wan2_2-I2V-A14B-LOW_fp8_e5m2_scaled_KJ.safetensors|diffusion_models|Wan2_2-I2V-A14B-LOW_fp8_e5m2_scaled_KJ.safetensors"
50
+ "hf://Kijai/WanVideo_comfy/Wan22-Lightning/Wan2.2-Lightning_I2V-A14B-4steps-lora_HIGH_fp16.safetensors|loras|Wan2.2-Lightning_I2V-A14B-4steps-lora_HIGH_fp16.safetensors"
51
+ "hf://Kijai/WanVideo_comfy/Wan22-Lightning/Wan2.2-Lightning_I2V-A14B-4steps-lora_LOW_fp16.safetensors|loras|Wan2.2-Lightning_I2V-A14B-4steps-lora_LOW_fp16.safetensors"
52
+ "hf://Kijai/WanVideo_comfy/Wan2_1_VAE_fp32.safetensors|vae|Wan2_1_VAE_fp32.safetensors"
53
+ "hf://Kijai/WanVideo_comfy/umt5-xxl-enc-bf16.safetensors|text_encoders|umt5-xxl-enc-bf16.safetensors"
54
+ # Wan 2.1 models
55
+ "hf://Kijai/WanVideo_comfy/Wan2_1-I2V-14B-720P_fp8_e4m3fn.safetensors|diffusion_models|Wan2_1-I2V-14B-720P_fp8_e4m3fn.safetensors"
56
+ "hf://Kijai/WanVideo_comfy/Lightx2v/lightx2v_I2V_14B_480p_cfg_step_distill_rank256_bf16.safetensors|loras|lightx2v_I2V_14B_480p_cfg_step_distill_rank256_bf16.safetensors"
57
+ "hf://Comfy-Org/Wan_2.2_ComfyUI_Repackaged/split_files/vae/wan_2.1_vae.safetensors|vae|wan_2.1_vae.safetensors"
58
+ "hf://Comfy-Org/Wan_2.2_ComfyUI_Repackaged/split_files/text_encoders/umt5_xxl_fp16.safetensors|text_encoders|umt5_xxl_fp16.safetensors"
59
+ # Wan 2.1 clip vision
60
+ "hf://Kijai/WanVideo_comfy/open-clip-xlm-roberta-large-vit-huge-14_visual_fp32.safetensors|clip_vision|open-clip-xlm-roberta-large-vit-huge-14_visual_fp32.safetensors"
61
+ "hf://Comfy-Org/Wan_2.1_ComfyUI_repackaged/split_files/clip_vision/clip_vision_h.safetensors|clip_vision|clip_vision_h.safetensors"
62
+ # ControlNet e outros modelos
63
+ "https://huggingface.co/Kijai/WanVideo_comfy/resolve/main/taew2_1.safetensors|vae_approx|taew2_1.safetensors"
64
+ "https://huggingface.co/Kijai/WanVideo_comfy/resolve/main/UniAnimate-Wan2.1-14B-Lora-12000-fp16.safetensors|loras|UniAnimate-Wan2.1-14B-Lora-12000-fp16.safetensors"
65
+ "https://huggingface.co/ABDALLALSWAITI/Upscalers/resolve/main/anime/2x-AnimeSharpV2_MoSR_Soft.pth|upscale_models|2x-AnimeSharpV2_MoSR_Soft.pth"
66
+ )
67
+
68
+ # RIFE ONNX models for TensorRT
69
+ readonly RIFE_MODELS=(
70
+ "https://huggingface.co/yuvraj108c/rife-onnx/resolve/main/rife49_ensemble_True_scale_1_sim.onnx"
71
+ "https://huggingface.co/yuvraj108c/rife-onnx/resolve/main/rife48_ensemble_True_scale_1_sim.onnx"
72
+ "https://huggingface.co/yuvraj108c/rife-onnx/resolve/main/rife47_ensemble_True_scale_1_sim.onnx"
73
+ )
74
+
75
+ # Mega.nz LoRA models
76
+ readonly MEGA_LORAS=(
77
+ "https://mega.nz/file/QFxREJpZ#0dge8TyRgb52lMFKdsk-Ac-rwcoG49hvBHvaqNsZkuk"
78
+ "https://mega.nz/file/lIhQETjT#nKlQ01Euw6fUxo8P5bfwlQrxAkWEedXQQOqHv5u4yrM"
79
+ "https://mega.nz/file/UIAESACY#Qlei1Pj5Nwno3Sz-wsTekvD-YgCkN1A5QbFKoRHXG9E"
80
+ "https://mega.nz/file/cdAg1Q7D#tQVrer2sB-M7XdYiKAqr7kRRfJw4pXCdliOg2aPJUGE"
81
+ "https://mega.nz/file/5RQFiAAJ#QCWrHkuJjXlFufR18g5R9YXJGqJ1pQp7xbqNRgSYUjc"
82
+ "https://mega.nz/file/tABgxLTS#NNlPV8NPc7R52MIjABMFUb41EOFDxFoszBxOrPMN13Q"
83
+ "https://mega.nz/file/4MxBgJ5Y#R8OSby0u-t-QFBnpnOtdjN3xuiVRvHa4_OEzTwWoGKQ"
84
+ "https://mega.nz/file/dJJxiSRR#o3XsYfSvb04xg7gNVdfHb3XTVHgvx0ZyXe9N8VQ9Lfw"
85
+ "https://mega.nz/file/wcAFhRJZ#ifZcckts0wPq1FG693tYLkpFrvjXvab1ZQeL6DuL1T8"
86
+ )
87
+
88
+ # Custom nodes para instalar
89
+ readonly CUSTOM_NODES=(
90
+ "https://github.com/kijai/ComfyUI-Florence2"
91
+ "https://github.com/adbrasi/groqrouter"
92
+ "https://github.com/yuvraj108c/ComfyUI-Rife-Tensorrt"
93
+ "https://github.com/yuvraj108c/ComfyUI-Dwpose-Tensorrt"
94
+ "https://github.com/kijai/ComfyUI-WanVideoWrapper"
95
+ "https://github.com/Fannovel16/ComfyUI-Frame-Interpolation"
96
+ "https://github.com/kijai/ComfyUI-GIMM-VFI"
97
+ "https://github.com/Kosinkadink/ComfyUI-VideoHelperSuite"
98
+ "https://github.com/kijai/ComfyUI-KJNodes"
99
+ "https://github.com/Fannovel16/comfyui_controlnet_aux"
100
+ "https://github.com/Artificial-Sweetener/comfyui-WhiteRabbit"
101
+ "https://github.com/shiimizu/ComfyUI_smZNodes"
102
+ "https://github.com/CoreyCorza/ComfyUI-CRZnodes"
103
+ "https://github.com/yuvraj108c/ComfyUI-Dwpose-Tensorrt"
104
+ "https://github.com/WASasquatch/was-node-suite-comfyui"
105
+ "https://github.com/justUmen/Bjornulf_custom_nodes"
106
+ "https://github.com/mingsky-ai/ComfyUI-MingNodes"
107
+ "https://github.com/numz/ComfyUI-SeedVR2_VideoUpscaler"
108
+ "https://github.com/1038lab/ComfyUI-RMBG"
109
+ "https://github.com/wallish77/wlsh_nodes"
110
+ "https://github.com/yuvraj108c/ComfyUI-Upscaler-Tensorrt"
111
+ "https://github.com/raindrop313/ComfyUI-WanVideoStartEndFrames"
112
+ "https://github.com/MushroomFleet/DJZ-Nodes"
113
+ "https://github.com/Suzie1/ComfyUI_Comfyroll_CustomNodes"
114
+ "https://github.com/grmchn/ComfyUI-ProportionChanger"
115
+ )
116
+
117
+ # -----------------------------
118
+ # Funções auxiliares
119
+ # -----------------------------
120
+ command_exists() {
121
+ command -v "$1" >/dev/null 2>&1
122
+ }
123
+
124
+ # Adicionar token do Civitai se necessário
125
+ add_civitai_token() {
126
+ local url="$1"
127
+ if [[ "$url" == *"civitai.com/api/download"* ]] && [[ "$url" != *"token="* ]]; then
128
+ echo "${url}&token=${CIVITAI_TOKEN}"
129
+ else
130
+ echo "$url"
131
+ fi
132
+ }
133
+
134
+ # Download HuggingFace usando hf com hf_transfer
135
+ download_hf() {
136
+ local repo="$1"
137
+ local file_path="$2"
138
+ local target_dir="$3"
139
+ local filename="$4"
140
+
141
+ # Se filename não foi fornecido, extrair do caminho
142
+ if [ -z "$filename" ]; then
143
+ filename=$(basename "$file_path")
144
+ fi
145
+
146
+ local target_file="$target_dir/$filename"
147
+
148
+ # Se arquivo já existe e tem tamanho razoável, pular
149
+ if [ -f "$target_file" ] && [ $(stat -c%s "$target_file" 2>/dev/null || echo 0) -gt 1000000 ]; then
150
+ log_success "Arquivo já existe: $filename"
151
+ return 0
152
+ fi
153
+
154
+ log_info "Baixando de HF: $filename"
155
+ log_info " Repo: $repo"
156
+ log_info " Path: $file_path"
157
+
158
+ # Criar diretório temporário para download
159
+ local temp_dir=$(mktemp -d)
160
+
161
+ # Tentar primeiro com 'hf download' (novo comando)
162
+ local download_success=false
163
+
164
+ if command_exists hf; then
165
+ if HF_HUB_ENABLE_HF_TRANSFER=1 hf download "$repo" "$file_path" \
166
+ --local-dir "$temp_dir" \
167
+ --local-dir-use-symlinks False 2>/dev/null; then
168
+ download_success=true
169
+ fi
170
+ fi
171
+
172
+ # Se 'hf' não funcionou, tentar com huggingface-cli
173
+ if [ "$download_success" = false ] && command_exists huggingface-cli; then
174
+ log_warn "Tentando com huggingface-cli..."
175
+ if HF_HUB_ENABLE_HF_TRANSFER=1 huggingface-cli download "$repo" "$file_path" \
176
+ --local-dir "$temp_dir" \
177
+ --local-dir-use-symlinks False 2>/dev/null; then
178
+ download_success=true
179
+ fi
180
+ fi
181
+
182
+ if [ "$download_success" = true ]; then
183
+ # Procurar o arquivo baixado (pode estar em subdiretórios)
184
+ local downloaded_file=$(find "$temp_dir" -type f \( -name "*.safetensors" -o -name "*.pth" -o -name "*.pt" -o -name "*.bin" \) 2>/dev/null | head -1)
185
+
186
+ if [ -n "$downloaded_file" ]; then
187
+ # Mover para o destino correto com o nome correto
188
+ mv "$downloaded_file" "$target_file"
189
+ rm -rf "$temp_dir"
190
+ log_success "Download concluído: $filename"
191
+ return 0
192
+ else
193
+ log_error "Arquivo baixado mas não encontrado em $temp_dir"
194
+ fi
195
+ fi
196
+
197
+ rm -rf "$temp_dir"
198
+ log_error "Falha ao baixar: $filename"
199
+ return 1
200
+ }
201
+
202
+ # Download genérico com aria2c, wget ou curl
203
+ download_file() {
204
+ local url="$1"
205
+ local target_dir="$2"
206
+ local filename="$3"
207
+
208
+ # Adicionar token Civitai se necessário
209
+ url=$(add_civitai_token "$url")
210
+
211
+ # Se arquivo já existe e tem tamanho razoável, pular
212
+ if [ -n "$filename" ] && [ -f "$target_dir/$filename" ] && [ $(stat -c%s "$target_dir/$filename" 2>/dev/null || echo 0) -gt 1000000 ]; then
213
+ log_success "Arquivo já existe: $filename"
214
+ return 0
215
+ fi
216
+
217
+ log_info "Baixando: ${filename:-$(basename "$url" | cut -d'?' -f1)}"
218
+
219
+ # Tentar com aria2c primeiro (mais rápido)
220
+ if command_exists aria2c; then
221
+ local aria_opts="-c -s 16 -x 16 -k 1M --console-log-level=warn --summary-interval=10"
222
+ if [ -n "$filename" ]; then
223
+ aria2c $aria_opts --dir="$target_dir" --out="$filename" "$url" && return 0
224
+ else
225
+ aria2c $aria_opts --dir="$target_dir" "$url" && return 0
226
+ fi
227
+ fi
228
+
229
+ # Fallback para wget
230
+ if command_exists wget; then
231
+ if [ -n "$filename" ]; then
232
+ wget -q --show-progress -c -O "$target_dir/$filename" "$url" && return 0
233
+ else
234
+ wget -q --show-progress -c --content-disposition -P "$target_dir" "$url" && return 0
235
+ fi
236
+ fi
237
+
238
+ # Último recurso: curl
239
+ if command_exists curl; then
240
+ if [ -n "$filename" ]; then
241
+ curl -L -# -C - -o "$target_dir/$filename" "$url" && return 0
242
+ else
243
+ local headers=$(curl -sI -L "$url")
244
+ local detected_name=$(echo "$headers" | grep -i "content-disposition" | sed -n 's/.*filename="\([^"]*\)".*/\1/p' | tr -d '\r')
245
+ if [ -z "$detected_name" ]; then
246
+ detected_name="downloaded_$(date +%s).safetensors"
247
+ fi
248
+ curl -L -# -C - -o "$target_dir/$detected_name" "$url" && return 0
249
+ fi
250
+ fi
251
+
252
+ log_error "Falha ao baixar: $url"
253
+ return 1
254
+ }
255
+
256
+ # Download from Mega.nz using megadl
257
+ download_mega() {
258
+ local url="$1"
259
+ local target_dir="$2"
260
+
261
+ if ! command_exists megadl; then
262
+ log_error "megadl não está instalado. Instalando megatools..."
263
+ apt-get update -qq && apt-get install -y -qq megatools 2>/dev/null
264
+ if ! command_exists megadl; then
265
+ log_error "Falha ao instalar megatools"
266
+ return 1
267
+ fi
268
+ fi
269
+
270
+ log_info "Baixando de Mega.nz: $url"
271
+
272
+ # megadl já baixa com o nome correto do arquivo
273
+ cd "$target_dir"
274
+ if megadl "$url" 2>/dev/null; then
275
+ log_success "Download Mega.nz concluído"
276
+ cd - > /dev/null
277
+ return 0
278
+ else
279
+ log_error "Falha ao baixar de Mega.nz: $url"
280
+ cd - > /dev/null
281
+ return 1
282
+ fi
283
+ }
284
+
285
+ # Processar lista de downloads
286
+ process_downloads() {
287
+ local failed_count=0
288
+
289
+ for entry in "${DOWNLOAD_FILES[@]}"; do
290
+ IFS='|' read -r url type filename <<< "$entry"
291
+
292
+ # Limpar espaços
293
+ url=$(echo "$url" | xargs)
294
+ type=$(echo "$type" | xargs)
295
+ filename=$(echo "$filename" | xargs)
296
+
297
+ # Determinar diretório de destino
298
+ local target_dir="$MODELS_DIR"
299
+ case "$type" in
300
+ checkpoints) target_dir="$MODELS_DIR/checkpoints" ;;
301
+ diffusion_models) target_dir="$MODELS_DIR/diffusion_models" ;;
302
+ loras) target_dir="$MODELS_DIR/loras" ;;
303
+ vae) target_dir="$MODELS_DIR/vae" ;;
304
+ vae_approx) target_dir="$MODELS_DIR/vae_approx" ;;
305
+ text_encoders) target_dir="$MODELS_DIR/text_encoders" ;;
306
+ clip_vision) target_dir="$MODELS_DIR/clip_vision" ;;
307
+ controlnet) target_dir="$MODELS_DIR/controlnet" ;;
308
+ upscale_models) target_dir="$MODELS_DIR/upscale_models" ;;
309
+ *) target_dir="$MODELS_DIR/$type" ;;
310
+ esac
311
+
312
+ # Criar diretório se não existir
313
+ mkdir -p "$target_dir"
314
+
315
+ # Processar URL
316
+ if [[ "$url" == hf://* ]]; then
317
+ # HuggingFace download
318
+ url="${url#hf://}" # Remove prefixo hf://
319
+
320
+ # Separar repo e caminho do arquivo
321
+ local repo=$(echo "$url" | cut -d'/' -f1-2)
322
+ local file_path=$(echo "$url" | cut -d'/' -f3-)
323
+
324
+ download_hf "$repo" "$file_path" "$target_dir" "$filename" || ((failed_count++))
325
+ else
326
+ # Download normal (HTTP/HTTPS)
327
+ download_file "$url" "$target_dir" "$filename" || ((failed_count++))
328
+ fi
329
+ done
330
+
331
+ return $failed_count
332
+ }
333
+
334
+ # Clonar ou atualizar repositório git
335
+ clone_or_update() {
336
+ local url="$1"
337
+ local dest="$2"
338
+ local node_name=$(basename "$dest")
339
+
340
+ # Timeout de 60 segundos para operações git
341
+ if [ -d "$dest/.git" ]; then
342
+ log_info "Atualizando $node_name..."
343
+ timeout 60 git -C "$dest" pull --ff-only 2>/dev/null || {
344
+ log_warn "Timeout ou erro ao atualizar $node_name"
345
+ return 0 # Não falhar, apenas avisar
346
+ }
347
+ else
348
+ log_info "Clonando $node_name..."
349
+ timeout 60 git clone --recursive --depth 1 "$url" "$dest" 2>/dev/null || {
350
+ log_warn "Falha ao clonar $node_name"
351
+ return 0 # Não falhar, apenas avisar
352
+ }
353
+ fi
354
+
355
+ # Instalar requirements se existir (com timeout)
356
+ if [ -f "$dest/requirements.txt" ]; then
357
+ timeout 120 python3 -m pip install --no-warn-script-location -q -r "$dest/requirements.txt" 2>/dev/null || {
358
+ log_warn "Falha ao instalar requirements para $node_name"
359
+ }
360
+ fi
361
+
362
+ return 0
363
+ }
364
+
365
+ # -----------------------------
366
+ # Instalação principal
367
+ # -----------------------------
368
+ echo ""
369
+ log_info "========================================="
370
+ log_info " ComfyUI + Wan 2.2 Setup (Fixed v2)"
371
+ log_info "========================================="
372
+ echo ""
373
+
374
+ # [1] Verificar e instalar dependências
375
+ log_info "[1/10] Verificando e instalando dependências..."
376
+
377
+ # Instalar aria2c e megatools se não existirem
378
+ if ! command_exists aria2c || ! command_exists megadl; then
379
+ log_info "Instalando ferramentas de download..."
380
+ apt-get update -qq 2>/dev/null
381
+
382
+ if ! command_exists aria2c; then
383
+ apt-get install -y -qq aria2 2>/dev/null
384
+ log_success "aria2c instalado"
385
+ fi
386
+
387
+ if ! command_exists megadl; then
388
+ apt-get install -y -qq megatools 2>/dev/null
389
+ log_success "megatools instalado"
390
+ fi
391
+ fi
392
+
393
+ for cmd in python3 git wget curl; do
394
+ if ! command_exists "$cmd"; then
395
+ log_error "Dependência faltando: $cmd"
396
+ exit 1
397
+ fi
398
+ done
399
+ log_success "Dependências OK"
400
+
401
+ # [2] Atualizar pip e instalar ferramentas
402
+ log_info "[2/10] Preparando ferramentas Python..."
403
+ python3 -m pip install --upgrade pip wheel setuptools -q
404
+
405
+ # Instalar huggingface_hub com CLI e hf_transfer para velocidade máxima
406
+ python3 -m pip install --upgrade "huggingface_hub[cli,hf_transfer]>=0.26.0" comfy-cli -q
407
+
408
+ # Configurar token HF se disponível (opcional)
409
+ HF_TOKEN="${HF_TOKEN:-}"
410
+ if [ -n "$HF_TOKEN" ]; then
411
+ if huggingface-cli login --token "$HF_TOKEN" 2>/dev/null; then
412
+ log_success "Login HF configurado"
413
+ else
414
+ log_warn "Falha ao configurar login HF, continuando sem autenticação"
415
+ fi
416
+ fi
417
+
418
+ # Verificar comandos disponíveis
419
+ if command_exists hf; then
420
+ log_success "Comando 'hf' disponível (recomendado)"
421
+ elif command_exists huggingface-cli; then
422
+ log_warn "Usando 'huggingface-cli' (deprecated, mas funcional)"
423
+ else
424
+ log_error "Nenhum comando HF disponível!"
425
+ fi
426
+
427
+ log_success "Ferramentas instaladas"
428
+
429
+ # [3] Instalar PyTorch com CUDA 12.8
430
+ log_info "[3/10] Instalando PyTorch com CUDA 12.8..."
431
+ python3 -m pip install --upgrade torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu128
432
+ log_success "PyTorch com CUDA 12.8 instalado"
433
+
434
+ # [4] Instalar ComfyUI
435
+ log_info "[4/10] Instalando ComfyUI..."
436
+ if [ -f "$COMFY_DIR/main.py" ]; then
437
+ log_warn "ComfyUI já existe, pulando instalação base"
438
+ else
439
+ comfy --skip-prompt install --fast-deps --nvidia
440
+
441
+ # Verificar instalação
442
+ if [ ! -f "$COMFY_DIR/main.py" ]; then
443
+ log_error "ComfyUI não foi instalado corretamente!"
444
+ exit 1
445
+ fi
446
+ fi
447
+ log_success "ComfyUI instalado em: $COMFY_DIR"
448
+
449
+ # [5] Instalar SageAttention (wheel pré-compilada)
450
+ log_info "[5/10] Instalando SageAttention..."
451
+ if command_exists nvcc || python3 -c "import torch; print(torch.cuda.is_available())" 2>/dev/null | grep -q "True"; then
452
+ log_info "Instalando SageAttention pré-compilada..."
453
+ python3 -m pip install "https://huggingface.co/adbrasi/comfywheel/resolve/main/sageattention-2.2.0-cp311-cp311-linux_x86_64.whl" -q
454
+
455
+ # Verificar instalação
456
+ if python3 -c "import sageattention" 2>/dev/null; then
457
+ log_success "SageAttention instalado com sucesso"
458
+ else
459
+ log_warn "SageAttention instalado mas não pôde ser importado"
460
+ fi
461
+ else
462
+ log_warn "CUDA não detectado, pulando SageAttention"
463
+ fi
464
+
465
+ # [6] Baixar modelos principais
466
+ log_info "[6/10] Baixando modelos principais..."
467
+ mkdir -p "$MODELS_DIR"/{diffusion_models,loras,vae,vae_approx,text_encoders,clip_vision,controlnet,upscale_models,checkpoints}
468
+
469
+ # Verificar ferramentas de download
470
+ if command_exists aria2c; then
471
+ log_success "Usando aria2c para downloads (rápido)"
472
+ else
473
+ log_warn "aria2c não encontrado, usando wget/curl (mais lento)"
474
+ fi
475
+
476
+ # Processar downloads
477
+ if process_downloads; then
478
+ log_success "Todos os modelos baixados com sucesso"
479
+ else
480
+ log_warn "Alguns downloads falharam, mas continuando..."
481
+ fi
482
+
483
+ # [7] Baixar modelos RIFE para TensorRT
484
+ log_info "[7/10] Baixando modelos RIFE..."
485
+ RIFE_DIR="$MODELS_DIR/tensorrt/rife"
486
+ mkdir -p "$RIFE_DIR"
487
+
488
+ for url in "${RIFE_MODELS[@]}"; do
489
+ filename=$(basename "$url")
490
+ if [ -f "$RIFE_DIR/$filename" ] && [ $(stat -c%s "$RIFE_DIR/$filename" 2>/dev/null || echo 0) -gt 100000 ]; then
491
+ log_success "RIFE modelo já existe: $filename"
492
+ else
493
+ log_info "Baixando RIFE: $filename"
494
+ download_file "$url" "$RIFE_DIR" "$filename"
495
+ fi
496
+ done
497
+ log_success "Modelos RIFE instalados"
498
+
499
+ # [8] Baixar modelos Mega.nz LoRAs
500
+ log_info "[8/10] Baixando LoRAs do Mega.nz..."
501
+ LORA_DIR="$MODELS_DIR/loras"
502
+ mkdir -p "$LORA_DIR"
503
+
504
+ if command_exists megadl; then
505
+ for mega_url in "${MEGA_LORAS[@]}"; do
506
+ log_info "Processando: $mega_url"
507
+ download_mega "$mega_url" "$LORA_DIR" || log_warn "Falha ao baixar: $mega_url"
508
+ done
509
+ log_success "Downloads Mega.nz concluídos"
510
+ else
511
+ log_warn "megatools não disponível, pulando downloads do Mega.nz"
512
+ fi
513
+
514
+ # TODO: Adicionar download da pasta Mega para upscale_models
515
+ # https://mega.nz/folder/rdpkjZzC#eUXPed_vntJKLrB0wpeJ-w
516
+ # Nota: megadl não suporta pastas diretamente, requer links individuais
517
+
518
+ # [9] Instalar custom nodes
519
+ log_info "[9/10] Instalando custom nodes..."
520
+ CN_DIR="$COMFY_DIR/custom_nodes"
521
+ mkdir -p "$CN_DIR"
522
+
523
+ # Instalar nodes sequencialmente para evitar travamentos
524
+ for repo_url in "${CUSTOM_NODES[@]}"; do
525
+ node_name=$(basename "$repo_url")
526
+ clone_or_update "$repo_url" "$CN_DIR/$node_name"
527
+ done
528
+
529
+ log_success "Custom nodes instalados"
530
+
531
+ # [10] Verificação final
532
+ echo ""
533
+ log_info "[10/10] Verificando instalação..."
534
+
535
+ # Verificar arquivos principais (ajustado para os modelos que você está baixando)
536
+ check_critical_files() {
537
+ local files=(
538
+ "$COMFY_DIR/main.py"
539
+ "$MODELS_DIR/diffusion_models/Wan2_1-I2V-14B-720P_fp8_e4m3fn.safetensors"
540
+ "$MODELS_DIR/vae/wan_2.1_vae.safetensors"
541
+ "$MODELS_DIR/text_encoders/umt5_xxl_fp16.safetensors"
542
+ "$MODELS_DIR/clip_vision/clip_vision_h.safetensors"
543
+ )
544
+
545
+ local missing=0
546
+ for file in "${files[@]}"; do
547
+ if [ -f "$file" ]; then
548
+ log_success "✓ $(basename "$file")"
549
+ else
550
+ log_warn "✗ $(basename "$file") não encontrado (opcional)"
551
+ fi
552
+ done
553
+
554
+ # Listar modelos baixados
555
+ echo ""
556
+ log_info "Modelos disponíveis:"
557
+ for dir in diffusion_models loras vae vae_approx text_encoders clip_vision controlnet upscale_models checkpoints; do
558
+ if [ -d "$MODELS_DIR/$dir" ]; then
559
+ local count=$(find "$MODELS_DIR/$dir" -type f \( -name "*.safetensors" -o -name "*.pth" -o -name "*.pt" \) 2>/dev/null | wc -l)
560
+ if [ $count -gt 0 ]; then
561
+ log_success " $dir: $count arquivo(s)"
562
+ fi
563
+ fi
564
+ done
565
+
566
+ return 0
567
+ }
568
+
569
+ if check_critical_files; then
570
+ log_success "Instalação concluída com sucesso!"
571
+ echo ""
572
+ log_info "========================================="
573
+ log_info "Iniciando ComfyUI..."
574
+ log_info "URL: http://localhost:$COMFY_PORT"
575
+ log_info "========================================="
576
+
577
+ # Tentar usar SageAttention se disponível
578
+ SAGE_FLAG=""
579
+ if python3 -c "import sageattention" 2>/dev/null; then
580
+ SAGE_FLAG="--use-sage-attention"
581
+ log_info "SageAttention habilitado"
582
+ fi
583
+
584
+ cd "$COMFY_DIR"
585
+ exec comfy launch -- $SAGE_FLAG --listen "$COMFY_HOST" --port "$COMFY_PORT"
586
+ else
587
+ log_error "Alguns arquivos não foram encontrados, mas a instalação pode funcionar."
588
+ log_info "Iniciando ComfyUI mesmo assim..."
589
+
590
+ cd "$COMFY_DIR"
591
+ exec comfy launch -- --listen "$COMFY_HOST" --port "$COMFY_PORT"
592
+ fi