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 
 
 
 
 
 
 
 
 
 
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
+
30
+ # Configurações de performance
31
+ export MAX_JOBS=32
32
+ export NVCC_APPEND_FLAGS="--threads 8"
33
+ export UV_SYSTEM_PYTHON=1
34
+ export PYTORCH_CUDA_ALLOC_CONF="expandable_segments:True"
35
+ export HF_HUB_ENABLE_HF_TRANSFER=1
36
+ export HF_TRANSFER_CONCURRENCY=16
37
+ export EXT_PARALLEL=4
38
+
39
+ # -----------------------------
40
+ # Lista de downloads
41
+ # -----------------------------
42
+ # Formato: "URL|TIPO|NOME_ARQUIVO_OPCIONAL"
43
+ readonly DOWNLOAD_FILES=(
44
+ # Wan 2.2 models
45
+ "hf://Comfy-Org/Wan_2.2_ComfyUI_Repackaged/split_files/diffusion_models/wan2.2_fun_control_low_noise_14B_fp8_scaled.safetensors|checkpoints|"
46
+ "hf://Comfy-Org/Wan_2.2_ComfyUI_Repackaged/split_files/diffusion_models/wan2.2_fun_control_high_noise_14B_fp8_scaled.safetensors|checkpoints|"
47
+ "hf://Comfy-Org/Wan_2.2_ComfyUI_Repackaged/split_files/loras/wan2.2_i2v_lightx2v_4steps_lora_v1_high_noise.safetensors|loras|"
48
+ "hf://Comfy-Org/Wan_2.2_ComfyUI_Repackaged/split_files/loras/wan2.2_i2v_lightx2v_4steps_lora_v1_low_noise.safetensors|loras|"
49
+ "hf://Comfy-Org/Wan_2.2_ComfyUI_Repackaged/split_files/vae/wan_2.1_vae.safetensors|vae|"
50
+ "hf://Comfy-Org/Wan_2.2_ComfyUI_Repackaged/split_files/text_encoders/umt5_xxl_fp16.safetensors|text_encoders|"
51
+ # Wan 2.1 clip vision
52
+ "hf://Comfy-Org/Wan_2.1_ComfyUI_repackaged/split_files/clip_vision/clip_vision_h.safetensors|clip_vision|"
53
+ # ControlNet
54
+ "hf://xinsir/controlnet-union-sdxl-1.0/diffusion_pytorch_model_promax.safetensors|controlnet|controlnet-union.safetensors"
55
+ # Civitai model
56
+ "https://civitai.com/api/download/models/2122278?type=Model&format=SafeTensor&size=pruned&fp=fp16|loras|"
57
+ )
58
+
59
+ # Custom nodes para instalar
60
+ readonly CUSTOM_NODES=(
61
+ "https://github.com/kijai/ComfyUI-Florence2"
62
+ "https://github.com/kijai/ComfyUI-WanVideoWrapper"
63
+ "https://github.com/Fannovel16/ComfyUI-Frame-Interpolation"
64
+ "https://github.com/kijai/ComfyUI-GIMM-VFI"
65
+ "https://github.com/Kosinkadink/ComfyUI-VideoHelperSuite"
66
+ "https://github.com/kijai/ComfyUI-KJNodes"
67
+ "https://github.com/Fannovel16/comfyui_controlnet_aux"
68
+ "https://github.com/Artificial-Sweetener/comfyui-WhiteRabbit"
69
+ "https://github.com/LucipherDev/ComfyUI-AniDoc"
70
+ "https://github.com/shiimizu/ComfyUI_smZNodes"
71
+ "https://github.com/yuvraj108c/ComfyUI-Dwpose-Tensorrt"
72
+ "https://github.com/grmchn/ComfyUI-ProportionChanger"
73
+ )
74
+
75
+ # -----------------------------
76
+ # Funções auxiliares
77
+ # -----------------------------
78
+ command_exists() {
79
+ command -v "$1" >/dev/null 2>&1
80
+ }
81
+
82
+ # Adicionar token do Civitai se necessário
83
+ add_civitai_token() {
84
+ local url="$1"
85
+ if [[ "$url" == *"civitai.com/api/download"* ]] && [[ "$url" != *"token="* ]]; then
86
+ echo "${url}&token=${CIVITAI_TOKEN}"
87
+ else
88
+ echo "$url"
89
+ fi
90
+ }
91
+
92
+ # Download HuggingFace usando novo comando hf
93
+ download_hf() {
94
+ local repo="$1"
95
+ local file_path="$2"
96
+ local target_dir="$3"
97
+ local filename="$4"
98
+
99
+ # Extrair nome do arquivo se não fornecido
100
+ if [ -z "$filename" ]; then
101
+ filename=$(basename "$file_path")
102
+ fi
103
+
104
+ local target_file="$target_dir/$filename"
105
+
106
+ # Se arquivo já existe e tem tamanho razoável, pular
107
+ if [ -f "$target_file" ] && [ $(stat -c%s "$target_file" 2>/dev/null || echo 0) -gt 1000000 ]; then
108
+ log_success "Arquivo já existe: $filename"
109
+ return 0
110
+ fi
111
+
112
+ log_info "Baixando de HF: $filename"
113
+
114
+ # Criar diretório temporário para download
115
+ local temp_dir=$(mktemp -d)
116
+
117
+ # Usar novo comando hf com HF Transfer habilitado
118
+ if HF_HUB_ENABLE_HF_TRANSFER=1 hf download "$repo" "$file_path" \
119
+ --local-dir "$temp_dir" \
120
+ --local-dir-use-symlinks False \
121
+ --resume-download 2>/dev/null; then
122
+
123
+ # Encontrar o arquivo baixado (pode estar em subdiretório)
124
+ local downloaded_file=$(find "$temp_dir" -name "$filename" -type f 2>/dev/null | head -1)
125
+
126
+ if [ -z "$downloaded_file" ]; then
127
+ # Tentar encontrar qualquer arquivo .safetensors
128
+ downloaded_file=$(find "$temp_dir" -name "*.safetensors" -type f 2>/dev/null | head -1)
129
+ fi
130
+
131
+ if [ -n "$downloaded_file" ]; then
132
+ mv "$downloaded_file" "$target_file"
133
+ rm -rf "$temp_dir"
134
+ log_success "Download concluído: $filename"
135
+ return 0
136
+ fi
137
+ fi
138
+
139
+ # Fallback para huggingface-cli se hf falhar
140
+ if huggingface-cli download "$repo" "$file_path" \
141
+ --local-dir "$temp_dir" \
142
+ --local-dir-use-symlinks False \
143
+ --resume-download 2>/dev/null; then
144
+
145
+ # Procurar arquivo baixado
146
+ local downloaded_file=$(find "$temp_dir" -name "$filename" -type f 2>/dev/null | head -1)
147
+
148
+ if [ -z "$downloaded_file" ]; then
149
+ downloaded_file=$(find "$temp_dir" -name "*.safetensors" -type f 2>/dev/null | head -1)
150
+ fi
151
+
152
+ if [ -n "$downloaded_file" ]; then
153
+ mv "$downloaded_file" "$target_file"
154
+ rm -rf "$temp_dir"
155
+ log_success "Download concluído (fallback): $filename"
156
+ return 0
157
+ fi
158
+ fi
159
+
160
+ rm -rf "$temp_dir"
161
+ log_error "Falha ao baixar: $filename"
162
+ return 1
163
+ }
164
+
165
+ # Download genérico com aria2c, wget ou curl
166
+ download_file() {
167
+ local url="$1"
168
+ local target_dir="$2"
169
+ local filename="$3"
170
+
171
+ # Adicionar token Civitai se necessário
172
+ url=$(add_civitai_token "$url")
173
+
174
+ # Se arquivo já existe e tem tamanho razoável, pular
175
+ if [ -n "$filename" ] && [ -f "$target_dir/$filename" ] && [ $(stat -c%s "$target_dir/$filename" 2>/dev/null || echo 0) -gt 1000000 ]; then
176
+ log_success "Arquivo já existe: $filename"
177
+ return 0
178
+ fi
179
+
180
+ log_info "Baixando: ${filename:-$(basename "$url" | cut -d'?' -f1)}"
181
+
182
+ # Tentar com aria2c primeiro (mais rápido)
183
+ if command_exists aria2c; then
184
+ local aria_opts="-c -s 16 -x 16 -k 1M --console-log-level=warn --summary-interval=10"
185
+ if [ -n "$filename" ]; then
186
+ aria2c $aria_opts --dir="$target_dir" --out="$filename" "$url" && return 0
187
+ else
188
+ aria2c $aria_opts --dir="$target_dir" "$url" && return 0
189
+ fi
190
+ fi
191
+
192
+ # Fallback para wget
193
+ if command_exists wget; then
194
+ if [ -n "$filename" ]; then
195
+ wget -q --show-progress -c -O "$target_dir/$filename" "$url" && return 0
196
+ else
197
+ wget -q --show-progress -c --content-disposition -P "$target_dir" "$url" && return 0
198
+ fi
199
+ fi
200
+
201
+ # Último recurso: curl
202
+ if command_exists curl; then
203
+ if [ -n "$filename" ]; then
204
+ curl -L -# -C - -o "$target_dir/$filename" "$url" && return 0
205
+ else
206
+ local headers=$(curl -sI -L "$url")
207
+ local detected_name=$(echo "$headers" | grep -i "content-disposition" | sed -n 's/.*filename="\([^"]*\)".*/\1/p' | tr -d '\r')
208
+ if [ -z "$detected_name" ]; then
209
+ detected_name="downloaded_$(date +%s).safetensors"
210
+ fi
211
+ curl -L -# -C - -o "$target_dir/$detected_name" "$url" && return 0
212
+ fi
213
+ fi
214
+
215
+ log_error "Falha ao baixar: $url"
216
+ return 1
217
+ }
218
+
219
+ # Processar lista de downloads
220
+ process_downloads() {
221
+ local failed_count=0
222
+
223
+ for entry in "${DOWNLOAD_FILES[@]}"; do
224
+ IFS='|' read -r url type filename <<< "$entry"
225
+
226
+ # Limpar espaços
227
+ url=$(echo "$url" | xargs)
228
+ type=$(echo "$type" | xargs)
229
+ filename=$(echo "$filename" | xargs)
230
+
231
+ # Determinar diretório de destino
232
+ local target_dir="$MODELS_DIR"
233
+ case "$type" in
234
+ checkpoints) target_dir="$MODELS_DIR/diffusion_models" ;;
235
+ loras) target_dir="$MODELS_DIR/loras" ;;
236
+ vae) target_dir="$MODELS_DIR/vae" ;;
237
+ text_encoders) target_dir="$MODELS_DIR/text_encoders" ;;
238
+ clip_vision) target_dir="$MODELS_DIR/clip_vision" ;;
239
+ controlnet) target_dir="$MODELS_DIR/controlnet" ;;
240
+ upscale_models) target_dir="$MODELS_DIR/upscale_models" ;;
241
+ *) target_dir="$MODELS_DIR/$type" ;;
242
+ esac
243
+
244
+ # Criar diretório se não existir
245
+ mkdir -p "$target_dir"
246
+
247
+ # Processar URL
248
+ if [[ "$url" == hf://* ]]; then
249
+ # HuggingFace download
250
+ url="${url#hf://}" # Remove prefixo hf://
251
+ repo=$(echo "$url" | cut -d'/' -f1-2)
252
+ file_path=$(echo "$url" | cut -d'/' -f3-)
253
+
254
+ download_hf "$repo" "$file_path" "$target_dir" "$filename" || ((failed_count++))
255
+ else
256
+ # Download normal (HTTP/HTTPS)
257
+ download_file "$url" "$target_dir" "$filename" || ((failed_count++))
258
+ fi
259
+ done
260
+
261
+ # Limpar arquivos órfãos em split_files (se existirem)
262
+ if [ -d "$MODELS_DIR/diffusion_models/split_files" ]; then
263
+ log_info "Movendo arquivos de split_files para diretórios corretos..."
264
+ find "$MODELS_DIR" -path "*/split_files/*" -name "*.safetensors" | while read -r file; do
265
+ local base_dir=$(dirname "$(dirname "$file")")
266
+ local target_name=$(basename "$file")
267
+ if [ ! -f "$base_dir/$target_name" ]; then
268
+ mv "$file" "$base_dir/" 2>/dev/null && log_success "Movido: $target_name"
269
+ fi
270
+ done
271
+ # Remover diretórios split_files vazios
272
+ find "$MODELS_DIR" -type d -name "split_files" -empty -delete 2>/dev/null
273
+ fi
274
+
275
+ return $failed_count
276
+ }
277
+
278
+ # Clonar ou atualizar repositório git
279
+ clone_or_update() {
280
+ local url="$1"
281
+ local dest="$2"
282
+
283
+ if [ -d "$dest/.git" ]; then
284
+ log_info "Atualizando $(basename "$dest")..."
285
+ git -C "$dest" pull --ff-only 2>/dev/null || true
286
+ else
287
+ log_info "Clonando $(basename "$dest")..."
288
+ git clone --recursive --depth 1 "$url" "$dest" 2>/dev/null || return 1
289
+ fi
290
+
291
+ # Instalar requirements se existir
292
+ if [ -f "$dest/requirements.txt" ]; then
293
+ python3 -m pip install --no-warn-script-location -q -r "$dest/requirements.txt" 2>/dev/null || true
294
+ fi
295
+ }
296
+
297
+ # -----------------------------
298
+ # Instalação principal
299
+ # -----------------------------
300
+ echo ""
301
+ log_info "========================================="
302
+ log_info " ComfyUI + Wan 2.2 Setup (Fixed)"
303
+ log_info "========================================="
304
+ echo ""
305
+
306
+ # [1] Verificar e instalar dependências
307
+ log_info "[1/7] Verificando e instalando dependências..."
308
+
309
+ # Instalar aria2c do sistema se não existir
310
+ if ! command_exists aria2c; then
311
+ log_info "Instalando aria2c do sistema..."
312
+ apt-get update -qq && apt-get install -y -qq aria2 2>/dev/null
313
+ fi
314
+
315
+ for cmd in python3 git wget curl; do
316
+ if ! command_exists "$cmd"; then
317
+ log_error "Dependência faltando: $cmd"
318
+ exit 1
319
+ fi
320
+ done
321
+ log_success "Dependências OK"
322
+
323
+ # [2] Atualizar pip e instalar ferramentas
324
+ log_info "[2/7] Preparando ferramentas Python..."
325
+ python3 -m pip install --upgrade pip wheel setuptools -q
326
+
327
+ # Instalar huggingface_hub com hf_transfer
328
+ python3 -m pip install --upgrade "huggingface_hub[hf_transfer]>=0.26.0" comfy-cli -q
329
+
330
+ # Verificar se hf está disponível
331
+ if ! command_exists hf; then
332
+ log_warn "Comando 'hf' não encontrado, usando huggingface-cli como fallback"
333
+ fi
334
+
335
+ log_success "Ferramentas instaladas"
336
+
337
+ # [3] Instalar ComfyUI
338
+ log_info "[3/7] Instalando ComfyUI..."
339
+ if [ -f "$COMFY_DIR/main.py" ]; then
340
+ log_warn "ComfyUI já existe, pulando instalação base"
341
+ else
342
+ comfy --skip-prompt install --fast-deps --nvidia
343
+
344
+ # Verificar instalação
345
+ if [ ! -f "$COMFY_DIR/main.py" ]; then
346
+ log_error "ComfyUI não foi instalado corretamente!"
347
+ exit 1
348
+ fi
349
+ fi
350
+ log_success "ComfyUI instalado em: $COMFY_DIR"
351
+
352
+ # [4] Instalar SageAttention (em background)
353
+ log_info "[4/7] Instalando SageAttention..."
354
+ (
355
+ if command_exists nvcc; then
356
+ python3 -m pip install "triton>=3.0.0" nvidia-ml-py -q
357
+ SAGE_DIR="/tmp/SageAttention"
358
+ rm -rf "$SAGE_DIR"
359
+ git clone --depth 1 https://github.com/thu-ml/SageAttention.git "$SAGE_DIR" 2>/dev/null
360
+ cd "$SAGE_DIR"
361
+ python3 setup.py install --quiet 2>/dev/null
362
+ log_success "SageAttention instalado"
363
+ else
364
+ log_warn "CUDA não detectado, pulando SageAttention"
365
+ fi
366
+ ) &
367
+ SAGE_PID=$!
368
+
369
+ # [5] Baixar modelos
370
+ log_info "[5/7] Baixando modelos..."
371
+ mkdir -p "$MODELS_DIR"/{diffusion_models,loras,vae,text_encoders,clip_vision,controlnet,upscale_models}
372
+
373
+ # Verificar ferramentas de download
374
+ if command_exists aria2c; then
375
+ log_success "Usando aria2c para downloads (rápido)"
376
+ else
377
+ log_warn "aria2c não encontrado, usando wget/curl (mais lento)"
378
+ fi
379
+
380
+ # Processar downloads
381
+ if process_downloads; then
382
+ log_success "Todos os modelos baixados com sucesso"
383
+ else
384
+ log_warn "Alguns downloads falharam, mas continuando..."
385
+ fi
386
+
387
+ # [6] Instalar custom nodes
388
+ log_info "[6/7] Instalando custom nodes..."
389
+ CN_DIR="$COMFY_DIR/custom_nodes"
390
+ mkdir -p "$CN_DIR"
391
+
392
+ for repo_url in "${CUSTOM_NODES[@]}"; do
393
+ node_name=$(basename "$repo_url")
394
+ clone_or_update "$repo_url" "$CN_DIR/$node_name" &
395
+ done
396
+ wait
397
+
398
+ log_success "Custom nodes instalados"
399
+
400
+ # Aguardar SageAttention
401
+ wait $SAGE_PID 2>/dev/null || true
402
+
403
+ # [7] Verificação final
404
+ echo ""
405
+ log_info "[7/7] Verificando instalação..."
406
+
407
+ # Verificar arquivos principais
408
+ check_critical_files() {
409
+ local files=(
410
+ "$COMFY_DIR/main.py"
411
+ "$MODELS_DIR/diffusion_models/wan2.2_fun_control_low_noise_14B_fp8_scaled.safetensors"
412
+ "$MODELS_DIR/diffusion_models/wan2.2_fun_control_high_noise_14B_fp8_scaled.safetensors"
413
+ "$MODELS_DIR/vae/wan_2.1_vae.safetensors"
414
+ "$MODELS_DIR/text_encoders/umt5_xxl_fp16.safetensors"
415
+ )
416
+
417
+ local missing=0
418
+ for file in "${files[@]}"; do
419
+ if [ -f "$file" ]; then
420
+ log_success "✓ $(basename "$file")"
421
+ else
422
+ log_error "✗ $(basename "$file") não encontrado"
423
+ ((missing++))
424
+ fi
425
+ done
426
+
427
+ return $missing
428
+ }
429
+
430
+ if check_critical_files; then
431
+ log_success "Instalação concluída com sucesso!"
432
+ echo ""
433
+ log_info "========================================="
434
+ log_info "Iniciando ComfyUI..."
435
+ log_info "URL: http://localhost:$COMFY_PORT"
436
+ log_info "========================================="
437
+
438
+ # Tentar usar SageAttention se disponível
439
+ SAGE_FLAG=""
440
+ if python3 -c "import sageattention" 2>/dev/null; then
441
+ SAGE_FLAG="--use-sage-attention"
442
+ log_info "SageAttention habilitado"
443
+ fi
444
+
445
+ cd "$COMFY_DIR"
446
+ exec comfy launch -- $SAGE_FLAG --listen "$COMFY_HOST" --port "$COMFY_PORT"
447
+ else
448
+ log_error "Arquivos críticos faltando. Verifique os erros acima."
449
+
450
+ # Mostrar onde os arquivos podem estar
451
+ log_info "Procurando arquivos mal posicionados..."
452
+ find "$MODELS_DIR" -name "*.safetensors" -type f | head -20
453
+
454
+ exit 1
455
+ fi