adbrasi commited on
Commit
453254f
·
verified ·
1 Parent(s): c6f85aa

Update image_Studio.sh

Browse files
Files changed (1) hide show
  1. image_Studio.sh +341 -709
image_Studio.sh CHANGED
@@ -1,761 +1,393 @@
1
  #!/usr/bin/env bash
2
- # setup_comfyui_custom_v2.sh
3
- # Script otimizado com suporte para RTX 5090, estado persistente e downloads do Mega
 
 
 
 
 
4
 
5
- set -euo pipefail
6
 
7
- # Detectar se está rodando via pipe (não-interativo)
8
- if [ ! -t 0 ] || [ ! -t 1 ]; then
9
- INTERACTIVE=false
10
- else
11
- INTERACTIVE=true
12
- fi
 
13
 
14
- # -----------------------------
15
- # Cores para output
16
- # -----------------------------
17
- RED='\033[0;31m'
18
- GREEN='\033[0;32m'
19
- YELLOW='\033[1;33m'
20
- BLUE='\033[0;34m'
21
- CYAN='\033[0;36m'
22
- NC='\033[0m'
23
 
24
- log_info() { echo -e "${BLUE}[INFO]${NC} $1"; }
25
- log_success() { echo -e "${GREEN}[✓]${NC} $1"; }
26
- log_warn() { echo -e "${YELLOW}[!]${NC} $1"; }
27
- log_error() { echo -e "${RED}[✗]${NC} $1"; }
28
- log_progress() { echo -e "${CYAN}[→]${NC} $1"; }
29
-
30
- # -----------------------------
31
- # Configuração
32
- # -----------------------------
33
- COMFY_DIR="/root/comfy/ComfyUI"
34
  MODELS_DIR="$COMFY_DIR/models"
35
- COMFY_HOST="${COMFY_HOST:-0.0.0.0}"
36
- COMFY_PORT="${COMFY_PORT:-8818}"
37
- CIVITAI_TOKEN="${CIVITAI_TOKEN:-4fcb2834969399006a736ee402b061e5}"
38
- HF_TOKEN="${HF_TOKEN:-}"
39
 
40
- # Diretório para salvar estado
41
- STATE_DIR="/root/.comfyui_setup_state"
42
- STATE_FILE="$STATE_DIR/installation_state.txt"
43
- COMPLETED_DOWNLOADS="$STATE_DIR/completed_downloads.txt"
44
- COMPLETED_NODES="$STATE_DIR/completed_nodes.txt"
 
 
 
45
 
46
- # Configurações de performance
47
- export MAX_JOBS=32
48
- export NVCC_APPEND_FLAGS="--threads 8"
49
- export UV_SYSTEM_PYTHON=1
50
- export PYTORCH_CUDA_ALLOC_CONF="expandable_segments:True"
51
- export HF_HUB_ENABLE_HF_TRANSFER=1
52
- export HF_TRANSFER_CONCURRENCY=16
53
- export EXT_PARALLEL=4
54
 
55
- # -----------------------------
56
- # Sistema de Estado Persistente
57
- # -----------------------------
58
- init_state() {
59
- mkdir -p "$STATE_DIR"
60
- touch "$STATE_FILE" "$COMPLETED_DOWNLOADS" "$COMPLETED_NODES"
61
- }
62
 
63
- save_state() {
64
- local step="$1"
65
- echo "$step" > "$STATE_FILE"
66
- log_info "Estado salvo: $step"
67
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68
 
69
- get_state() {
70
- if [ -f "$STATE_FILE" ]; then
71
- local state=$(cat "$STATE_FILE" 2>/dev/null)
72
- # Verificar se é um número válido
73
- if [[ "$state" =~ ^[0-9]+$ ]]; then
74
- echo "$state"
75
- else
76
- echo "0"
77
- fi
78
- else
79
- echo "0"
80
- fi
81
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82
 
83
- mark_download_complete() {
84
- local url="$1"
85
- echo "$url" >> "$COMPLETED_DOWNLOADS"
86
- }
 
87
 
88
- is_download_complete() {
89
- local url="$1"
90
- grep -Fxq "$url" "$COMPLETED_DOWNLOADS" 2>/dev/null
 
 
 
 
 
 
91
  }
92
 
93
- mark_node_complete() {
94
- local node="$1"
95
- echo "$node" >> "$COMPLETED_NODES"
 
 
 
 
 
 
 
 
 
 
 
 
96
  }
97
 
98
- is_node_complete() {
99
- local node="$1"
100
- grep -Fxq "$node" "$COMPLETED_NODES" 2>/dev/null
101
- }
 
 
102
 
103
- reset_state() {
104
- log_warn "Resetando estado da instalação..."
105
- rm -rf "$STATE_DIR"
106
- init_state
 
 
 
 
 
 
 
 
 
107
  }
108
 
109
- # -----------------------------
110
- # Lista de downloads (ATUALIZADA - sem ControlNet)
111
- # -----------------------------
112
- readonly DOWNLOAD_FILES=(
113
- # Checkpoint mantido
114
- "https://civitai.com/api/download/models/2122278?type=Model&format=SafeTensor&size=pruned&fp=fp16|checkpoints|raehoshiIllustXL_v60.safetensors"
115
-
116
- # LoRAs from Civitai
117
- "https://civitai.com/api/download/models/1268294?type=Model&format=SafeTensor|loras|"
118
- "https://civitai.com/api/download/models/1715330?type=Model&format=SafeTensor|loras|"
119
- "https://civitai.com/api/download/models/1499397?type=Model&format=SafeTensor|loras|"
120
- "https://civitai.com/api/download/models/1779002?type=Model&format=SafeTensor|loras|"
121
- "https://civitai.com/api/download/models/1114313?type=Model&format=SafeTensor|loras|"
122
- "https://civitai.com/api/download/models/1780244?type=Model&format=SafeTensor|loras|"
123
-
124
- # LoRA from Mega (nome automático pelo megadl)
125
- "mega://https://mega.nz/file/gIRTFQSQ#no6Ay3JLE9LVRi7ib9O-Jc0CW7XmG046kCgpCzDg1tY|loras|"
126
-
127
- # Upscale models - Coleção completa
128
- "https://huggingface.co/Kim2091/AnimeSharp/resolve/main/4x-AnimeSharp.pth|upscale_models|4x-AnimeSharp.pth"
129
- "https://huggingface.co/Kim2091/AnimeSharpV3/resolve/main/2x-AnimeSharpV3.pth|upscale_models|2x-AnimeSharpV3.pth"
130
- "https://huggingface.co/ABDALLALSWAITI/Upscalers/resolve/main/anime/2x-AnimeSharpV2_MoSR_Soft.pth|upscale_models|2x-AnimeSharpV2_MoSR_Soft.pth"
131
- "https://huggingface.co/Kim2091/UltraSharpV2/resolve/main/4x-UltraSharpV2.pth|upscale_models|4x-UltraSharpV2.pth"
132
- "https://huggingface.co/Kim2091/UltraSharpV2/resolve/main/4x-UltraSharpV2_Lite.pth|upscale_models|4x-UltraSharpV2_Lite.pth"
133
- "https://huggingface.co/Kim2091/UltraSharpV2/resolve/main/4x-UltraSharpV2_fp32_op17.onnx|upscale_models|4x-UltraSharpV2_fp32_op17.onnx"
134
-
135
- # Ultralytics model
136
- "https://huggingface.co/adbrasi/testedownload/resolve/main/99coins_anime_girl_face_m_seg.pt|ultralytics/bbox|99coins_anime_girl_face_m_seg.pt"
137
- )
138
-
139
- # Custom nodes para instalar (ATUALIZADA com novos nodes)
140
- readonly CUSTOM_NODES=(
141
- "https://github.com/adbrasi/huggpackreator"
142
- "https://github.com/adbrasi/packreator_processor"
143
- "https://github.com/adbrasi/Packreator_manager"
144
- "https://github.com/adbrasi/cezarsave34"
145
- "https://github.com/adbrasi/pageonetor"
146
- "https://github.com/adbrasi/pakreatorio"
147
- "https://github.com/adbrasi/WaterMark_bumbumzin"
148
- "https://github.com/adbrasi/marcadaguita"
149
- "https://github.com/adbrasi/randomico"
150
- "https://github.com/adbrasi/groqrouter"
151
- "https://github.com/adbrasi/find_charakito"
152
- "https://github.com/adbrasi/randomsizito"
153
- "https://github.com/adbrasi/importex"
154
- "https://github.com/adbrasi/storitadifusita"
155
- "https://github.com/adbrasi/attentionPPM"
156
- "https://github.com/ClownsharkBatwing/RES4LYF"
157
- "https://github.com/Suzie1/ComfyUI_Comfyroll_CustomNodes"
158
- "https://github.com/sipherxyz/comfyui-art-venture"
159
- "https://github.com/pamparamm/sd-perturbed-attention"
160
- "https://github.com/KoreTeknology/ComfyUI-Universal-Styler"
161
- "https://github.com/WASasquatch/was-node-suite-comfyui"
162
- "https://github.com/chflame163/ComfyUI_LayerStyle"
163
- "https://github.com/ltdrdata/ComfyUI-Impact-Pack"
164
- "https://github.com/pythongosssss/ComfyUI-Custom-Scripts"
165
- "https://github.com/rgthree/rgthree-comfy"
166
- "https://github.com/ssitu/ComfyUI_UltimateSDUpscale"
167
- "https://github.com/adbrasi/Importador"
168
- "https://github.com/adbrasi/GetFirstTag"
169
- "https://github.com/adbrasi/comfydodi"
170
- "https://github.com/omar92/ComfyUI-QualityOfLifeSuit_Omar92"
171
- "https://github.com/Cezarsaint/blacklisto"
172
- "https://github.com/TinyTerra/ComfyUI_tinyterraNodes"
173
- "https://github.com/ltdrdata/ComfyUI-Impact-Subpack"
174
- "https://github.com/Cezarsaint/rand0micoUploaderLoven"
175
- "https://github.com/adbrasi/pixivmosaic"
176
- "https://github.com/adbrasi/futfilter"
177
- "https://github.com/Artificial-Sweetener/comfyui-WhiteRabbit"
178
- "https://github.com/shiimizu/ComfyUI_smZNodes"
179
- "https://github.com/CoreyCorza/ComfyUI-CRZnodes"
180
- )
181
-
182
- # Custom nodes que precisam de instalação especial via comfy-cli
183
- readonly SPECIAL_NODES=(
184
- "Civicomfy"
185
- "ComfyUI-RMBG"
186
- )
187
-
188
- # -----------------------------
189
- # Funções auxiliares
190
- # -----------------------------
191
- command_exists() {
192
- command -v "$1" >/dev/null 2>&1
193
  }
194
 
195
- # Instalar megatools se necessário
196
- install_megatools() {
197
- if ! command_exists megadl; then
198
- log_info "Instalando megatools para downloads do Mega..."
199
- apt-get update -qq && apt-get install -y -qq megatools 2>/dev/null
200
- if command_exists megadl; then
201
- log_success "Megatools instalado com sucesso"
202
- else
203
- log_warn "Falha ao instalar megatools, downloads do Mega não estarão disponíveis"
204
- fi
205
  fi
 
 
206
  }
207
 
208
- # Download do Mega
209
- download_mega() {
210
- local url="$1"
211
- local target_dir="$2"
212
- local filename="$3"
213
-
214
- if ! command_exists megadl; then
215
- log_error "megatools não instalado, pulando download do Mega"
216
- return 1
217
- fi
218
-
219
- # Limpar URL - remover prefixo mega:// se houver
220
- url="${url#mega://}"
221
-
222
- log_info "Baixando do Mega..."
223
- log_info " URL: $url"
224
- log_info " Destino: $target_dir"
225
-
226
- # Criar diretório temporário para download
227
- local temp_dir=$(mktemp -d)
228
- cd "$temp_dir"
229
-
230
- # Baixar com megadl (ele salva com o nome correto automaticamente)
231
- if timeout 1800 megadl "$url" 2>/dev/null; then
232
- # Encontrar o arquivo baixado
233
- local downloaded_file=$(find . -type f -maxdepth 1 2>/dev/null | grep -v "^\.$" | head -1)
234
-
235
- if [ -n "$downloaded_file" ]; then
236
- local actual_filename=$(basename "$downloaded_file")
237
-
238
- # Se foi especificado um nome E não está vazio, renomear
239
- if [ -n "$filename" ] && [ "$filename" != "" ]; then
240
- mv "$downloaded_file" "$target_dir/$filename"
241
- log_success "Download concluído: $filename"
242
- else
243
- # Manter o nome original do Mega
244
- mv "$downloaded_file" "$target_dir/$actual_filename"
245
- log_success "Download concluído: $actual_filename"
246
- fi
247
- cd - >/dev/null
248
- rm -rf "$temp_dir"
249
- return 0
250
- else
251
- log_error "Arquivo baixado mas não encontrado no diretório temporário"
252
- fi
253
  else
254
- log_error "Falha ao baixar do Mega (timeout ou erro)"
255
  fi
256
-
257
- cd - >/dev/null
258
- rm -rf "$temp_dir"
259
- return 1
260
- }
261
-
262
- # Adicionar token do Civitai se necessário
263
- add_civitai_token() {
264
- local url="$1"
265
- if [[ "$url" == *"civitai.com/api/download"* ]] && [[ "$url" != *"token="* ]]; then
266
- echo "${url}&token=${CIVITAI_TOKEN}"
267
  else
268
- echo "$url"
269
  fi
 
 
 
 
 
 
 
 
 
 
 
 
270
  }
271
 
272
- # Download HuggingFace usando hf com hf_transfer
273
- download_hf() {
274
- local repo="$1"
275
- local file_path="$2"
276
- local target_dir="$3"
277
- local filename="$4"
278
-
279
- if [ -z "$filename" ]; then
280
- filename=$(basename "$file_path")
281
- fi
282
-
283
- local target_file="$target_dir/$filename"
284
-
285
- if [ -f "$target_file" ] && [ $(stat -c%s "$target_file" 2>/dev/null || echo 0) -gt 1000000 ]; then
286
- log_success "Arquivo já existe: $filename"
287
- return 0
288
- fi
289
-
290
- log_info "Baixando de HF: $filename"
291
-
292
- local temp_dir=$(mktemp -d)
293
- local download_success=false
294
-
295
- if command_exists hf; then
296
- if HF_HUB_ENABLE_HF_TRANSFER=1 hf download "$repo" "$file_path" \
297
- --local-dir "$temp_dir" \
298
- --local-dir-use-symlinks False 2>/dev/null; then
299
- download_success=true
300
- fi
301
  fi
302
-
303
- if [ "$download_success" = false ] && command_exists huggingface-cli; then
304
- log_warn "Tentando com huggingface-cli..."
305
- if HF_HUB_ENABLE_HF_TRANSFER=1 huggingface-cli download "$repo" "$file_path" \
306
- --local-dir "$temp_dir" \
307
- --local-dir-use-symlinks False 2>/dev/null; then
308
- download_success=true
309
- fi
310
- fi
311
-
312
- if [ "$download_success" = true ]; then
313
- local downloaded_file=$(find "$temp_dir" -type f \( -name "*.safetensors" -o -name "*.pth" -o -name "*.pt" -o -name "*.bin" -o -name "*.onnx" \) 2>/dev/null | head -1)
314
-
315
- if [ -n "$downloaded_file" ]; then
316
- mv "$downloaded_file" "$target_file"
317
- rm -rf "$temp_dir"
318
- log_success "Download concluído: $filename"
319
- return 0
320
- fi
321
- fi
322
-
323
- rm -rf "$temp_dir"
324
- log_error "Falha ao baixar: $filename"
325
- return 1
326
  }
327
 
328
- # Download genérico com aria2c, wget ou curl
329
- download_file() {
330
- local url="$1"
331
- local target_dir="$2"
332
- local filename="$3"
333
-
334
- url=$(add_civitai_token "$url")
335
-
336
- if [ -n "$filename" ] && [ -f "$target_dir/$filename" ] && [ $(stat -c%s "$target_dir/$filename" 2>/dev/null || echo 0) -gt 1000000 ]; then
337
- log_success "Arquivo existe: $filename"
338
- return 0
339
- fi
340
-
341
- log_info "Baixando: ${filename:-$(basename "$url" | cut -d'?' -f1)}"
342
-
343
- if command_exists aria2c; then
344
- local aria_opts="-c -s 16 -x 16 -k 1M --console-log-level=warn --summary-interval=10"
345
- if [ -n "$filename" ]; then
346
- aria2c $aria_opts --dir="$target_dir" --out="$filename" "$url" && return 0
347
- else
348
- aria2c $aria_opts --dir="$target_dir" "$url" && return 0
349
- fi
350
- fi
351
-
352
- if command_exists wget; then
353
- if [ -n "$filename" ]; then
354
- wget -q --show-progress -c -O "$target_dir/$filename" "$url" && return 0
355
- else
356
- wget -q --show-progress -c --content-disposition -P "$target_dir" "$url" && return 0
357
- fi
358
- fi
359
-
360
- if command_exists curl; then
361
- if [ -n "$filename" ]; then
362
- curl -L -# -C - -o "$target_dir/$filename" "$url" && return 0
363
- else
364
- local headers=$(curl -sI -L "$url")
365
- local detected_name=$(echo "$headers" | grep -i "content-disposition" | sed -n 's/.*filename="\([^"]*\)".*/\1/p' | tr -d '\r')
366
- if [ -z "$detected_name" ]; then
367
- detected_name="downloaded_$(date +%s).safetensors"
368
- fi
369
- curl -L -# -C - -o "$target_dir/$detected_name" "$url" && return 0
370
- fi
371
  fi
372
-
373
- log_error "Falha ao baixar: $url"
374
- return 1
 
375
  }
376
 
377
- # Processar lista de downloads (NÃO PARA EM FALHAS)
378
- process_downloads() {
379
- local total=${#DOWNLOAD_FILES[@]}
380
- local current=0
381
- local failed_count=0
382
- local skipped_count=0
383
-
384
- log_info "Total de downloads: $total"
385
-
386
- for entry in "${DOWNLOAD_FILES[@]}"; do
387
- ((current++))
388
- log_progress "[$current/$total] Processando download..."
389
-
390
- # Verificar se já foi baixado
391
- if is_download_complete "$entry"; then
392
- log_success "Download já completado anteriormente, pulando..."
393
- ((skipped_count++))
394
- continue
395
- fi
396
-
397
- IFS='|' read -r url type filename <<< "$entry"
398
-
399
- url=$(echo "$url" | xargs)
400
- type=$(echo "$type" | xargs)
401
- filename=$(echo "$filename" | xargs)
402
-
403
- local target_dir="$MODELS_DIR"
404
- case "$type" in
405
- checkpoints) target_dir="$MODELS_DIR/checkpoints" ;;
406
- diffusion_models) target_dir="$MODELS_DIR/diffusion_models" ;;
407
- loras) target_dir="$MODELS_DIR/loras" ;;
408
- vae) target_dir="$MODELS_DIR/vae" ;;
409
- vae_approx) target_dir="$MODELS_DIR/vae_approx" ;;
410
- text_encoders) target_dir="$MODELS_DIR/text_encoders" ;;
411
- clip_vision) target_dir="$MODELS_DIR/clip_vision" ;;
412
- upscale_models) target_dir="$MODELS_DIR/upscale_models" ;;
413
- ultralytics/bbox) target_dir="$MODELS_DIR/ultralytics/bbox" ;;
414
- *) target_dir="$MODELS_DIR/$type" ;;
415
- esac
416
-
417
- mkdir -p "$target_dir"
418
-
419
- # Determinar tipo de download e executar
420
- local download_result=1
421
-
422
- if [[ "$url" == mega://* ]]; then
423
- # Download do Mega
424
- download_mega "$url" "$target_dir" "$filename" && download_result=0
425
- elif [[ "$url" == hf://* ]]; then
426
- # HuggingFace download
427
- url="${url#hf://}"
428
- local repo=$(echo "$url" | cut -d'/' -f1-2)
429
- local file_path=$(echo "$url" | cut -d'/' -f3-)
430
- download_hf "$repo" "$file_path" "$target_dir" "$filename" && download_result=0
431
- else
432
- # Download normal
433
- download_file "$url" "$target_dir" "$filename" && download_result=0
434
- fi
435
-
436
- if [ $download_result -eq 0 ]; then
437
- mark_download_complete "$entry"
438
- else
439
- ((failed_count++))
440
- log_warn "Download falhou, mas continuando com o próximo..."
441
- fi
442
- done
443
-
444
- log_info "Downloads completados: $((total - failed_count - skipped_count)) novos, $skipped_count já existentes, $failed_count falharam"
445
- return 0 # Sempre retorna sucesso para não parar o script
446
  }
447
 
448
- # Clonar ou atualizar repositório git
449
- clone_or_update() {
450
- local url="$1"
451
- local dest="$2"
452
- local node_name=$(basename "$dest")
453
-
454
- if is_node_complete "$url"; then
455
- log_success "Node já instalado: $node_name"
456
- return 0
457
- fi
458
-
459
- if [ -d "$dest/.git" ]; then
460
- log_info "Atualizando $node_name..."
461
- timeout 60 git -C "$dest" pull --ff-only 2>/dev/null || {
462
- log_warn "Timeout ou erro ao atualizar $node_name"
463
- return 0
464
- }
465
  else
466
- log_info "Clonando $node_name..."
467
- timeout 60 git clone --recursive --depth 1 "$url" "$dest" 2>/dev/null || {
468
- log_warn "Falha ao clonar $node_name"
469
- return 0
470
- }
471
  fi
472
-
473
- if [ -f "$dest/requirements.txt" ]; then
474
- timeout 120 python3 -m pip install --no-warn-script-location -q -r "$dest/requirements.txt" 2>/dev/null || {
475
- log_warn "Falha ao instalar requirements para $node_name"
476
- }
477
- fi
478
-
479
- mark_node_complete "$url"
480
- return 0
481
  }
482
 
483
- # Detectar GPU e ajustar PyTorch se necessário
484
- detect_and_fix_gpu() {
485
- log_info "Detectando GPU..."
486
-
487
- # Verificar se é uma GPU Blackwell (RTX 5090, etc)
488
- local gpu_info=$(nvidia-smi --query-gpu=name --format=csv,noheader 2>/dev/null || echo "")
489
-
490
- if [[ "$gpu_info" == *"5090"* ]] || [[ "$gpu_info" == *"5080"* ]] || [[ "$gpu_info" == *"Blackwell"* ]]; then
491
- log_warn "GPU Blackwell detectada (${gpu_info})"
492
- log_info "Instalando PyTorch nightly para suporte completo..."
493
-
494
- # Instalar PyTorch nightly para Blackwell
495
- python3 -m pip install --pre --upgrade --no-cache-dir torch --extra-index-url https://download.pytorch.org/whl/nightly/cu128
496
- python3 -m pip install --pre --upgrade --no-cache-dir torchvision --extra-index-url https://download.pytorch.org/whl/nightly/cu128
497
- python3 -m pip install --pre --upgrade --no-cache-dir torchaudio --extra-index-url https://download.pytorch.org/whl/nightly/cu128
498
-
499
- log_success "PyTorch nightly instalado para Blackwell"
500
- else
501
- log_info "GPU padrão detectada: ${gpu_info:-Não detectada}"
502
- log_info "Usando PyTorch stable"
503
- fi
504
  }
505
 
506
- # -----------------------------
507
- # Menu de opções
508
- # -----------------------------
509
- show_menu() {
510
- echo ""
511
- log_info "========================================="
512
- log_info " ComfyUI Custom Setup v2.0"
513
- log_info "========================================="
514
- echo ""
515
-
516
- local current_state=$(get_state)
517
-
518
- # Verificar se o estado está vazio ou inválido
519
- if [ -z "$current_state" ] || ! [[ "$current_state" =~ ^[0-9]+$ ]]; then
520
- log_info "Iniciando nova instalação..."
521
- reset_state
522
- return 0
523
- fi
524
-
525
- # Se não for interativo, sempre continuar ou começar do zero
526
- if [ "$INTERACTIVE" = false ]; then
527
- if [ "$current_state" != "0" ] && [ "$current_state" -lt "8" ]; then
528
- log_info "Modo não-interativo: continuando instalação anterior (Step: $current_state)"
529
- else
530
- log_info "Modo não-interativo: iniciando nova instalação"
531
- fi
532
- return 0
533
- fi
534
-
535
- if [ "$current_state" != "0" ] && [ "$current_state" -lt "8" ]; then
536
- log_warn "Instalação anterior detectada (Step: $current_state)"
537
- echo ""
538
- echo "Opções:"
539
- echo " 1) Continuar instalação de onde parou"
540
- echo " 2) Reiniciar instalação do zero"
541
- echo " 3) Sair"
542
- echo ""
543
-
544
- # Timeout de 10 segundos, padrão é continuar
545
- read -t 10 -p "Escolha uma opção [1-3] (padrão: 1 em 10s): " choice || choice="1"
546
-
547
- case $choice in
548
- 1|"") return 0 ;;
549
- 2) reset_state; return 0 ;;
550
- 3) exit 0 ;;
551
- *) log_warn "Opção inválida, continuando..."; return 0 ;;
552
- esac
553
- fi
554
-
555
- return 0
556
  }
557
 
558
- # -----------------------------
559
- # Instalação principal
560
- # -----------------------------
561
- main() {
562
- # Inicializar sistema de estado
563
- init_state
564
-
565
- # Mostrar menu
566
- show_menu
567
-
568
- local current_state=$(get_state)
569
-
570
- # [STEP 1] Verificar e instalar dependências
571
- if [ "$current_state" -lt "1" ]; then
572
- log_info "[1/8] Verificando e instalando dependências..."
573
-
574
- # Instalar aria2c e megatools
575
- if ! command_exists aria2c; then
576
- log_info "Instalando aria2c..."
577
- apt-get update -qq && apt-get install -y -qq aria2 2>/dev/null
578
- fi
579
-
580
- install_megatools
581
-
582
- for cmd in python3 git wget curl; do
583
- if ! command_exists "$cmd"; then
584
- log_error "Dependência faltando: $cmd"
585
- exit 1
586
- fi
587
- done
588
-
589
- log_success "Dependências OK"
590
- save_state "1"
591
- fi
592
-
593
- # [STEP 2] Atualizar pip e instalar ferramentas
594
- if [ "$current_state" -lt "2" ]; then
595
- log_info "[2/8] Preparando ferramentas Python..."
596
- python3 -m pip install --upgrade pip wheel setuptools -q
597
- python3 -m pip install --upgrade "huggingface_hub[cli,hf_transfer]>=0.26.0" comfy-cli -q
598
-
599
- if [ -n "$HF_TOKEN" ]; then
600
- huggingface-cli login --token "$HF_TOKEN" 2>/dev/null || log_warn "Login HF falhou"
601
- fi
602
-
603
- log_success "Ferramentas instaladas"
604
- save_state "2"
605
- fi
606
-
607
- # [STEP 3] Instalar PyTorch inicial
608
- if [ "$current_state" -lt "3" ]; then
609
- log_info "[3/8] Instalando PyTorch com CUDA 12.8..."
610
- python3 -m pip install --upgrade torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu128
611
- log_success "PyTorch instalado"
612
- save_state "3"
613
- fi
614
-
615
- # [STEP 4] Instalar ComfyUI
616
- if [ "$current_state" -lt "4" ]; then
617
- log_info "[4/8] Instalando ComfyUI..."
618
- if [ -f "$COMFY_DIR/main.py" ]; then
619
- log_warn "ComfyUI já existe"
620
- else
621
- comfy --skip-prompt install --fast-deps --nvidia
622
-
623
- if [ ! -f "$COMFY_DIR/main.py" ]; then
624
- log_error "ComfyUI não foi instalado corretamente!"
625
- exit 1
626
- fi
627
- fi
628
- log_success "ComfyUI instalado"
629
- save_state "4"
630
- fi
631
-
632
- # [STEP 5] Detectar e corrigir para GPU Blackwell se necessário
633
- if [ "$current_state" -lt "5" ]; then
634
- log_info "[5/8] Verificando compatibilidade de GPU..."
635
- detect_and_fix_gpu
636
- save_state "5"
637
- fi
638
-
639
- # [STEP 6] Baixar modelos
640
- if [ "$current_state" -lt "6" ]; then
641
- log_info "[6/8] Baixando modelos..."
642
- mkdir -p "$MODELS_DIR"/{diffusion_models,loras,vae,vae_approx,text_encoders,clip_vision,upscale_models,checkpoints,ultralytics/bbox}
643
-
644
- process_downloads # Não falha mesmo se alguns downloads falharem
645
-
646
- log_success "Processo de download concluído"
647
- save_state "6"
648
- fi
649
-
650
- # [STEP 7] Instalar custom nodes
651
- if [ "$current_state" -lt "7" ]; then
652
- log_info "[7/8] Instalando custom nodes..."
653
- CN_DIR="$COMFY_DIR/custom_nodes"
654
- mkdir -p "$CN_DIR"
655
-
656
- local total_nodes=${#CUSTOM_NODES[@]}
657
- local current_node=0
658
-
659
- for repo_url in "${CUSTOM_NODES[@]}"; do
660
- ((current_node++))
661
- node_name=$(basename "$repo_url")
662
- log_progress "[$current_node/$total_nodes] Instalando: $node_name"
663
- clone_or_update "$repo_url" "$CN_DIR/$node_name"
664
- done
665
-
666
- for node_name in "${SPECIAL_NODES[@]}"; do
667
- if ! is_node_complete "special:$node_name"; then
668
- log_info "Instalando $node_name via comfy-cli..."
669
- comfy node install "$node_name" 2>/dev/null && mark_node_complete "special:$node_name" || log_warn "Falha: $node_name"
670
- fi
671
- done
672
-
673
- log_success "Custom nodes instalados"
674
- save_state "7"
675
- fi
676
-
677
- # [STEP 8] Verificação final
678
- log_info "[8/8] Verificando instalação..."
679
-
680
- echo ""
681
- log_info "Estatísticas da instalação:"
682
-
683
- # Verificar ComfyUI
684
- if [ -f "$COMFY_DIR/main.py" ]; then
685
- log_success "✓ ComfyUI instalado"
686
- else
687
- log_error "✗ ComfyUI não encontrado"
688
- fi
689
-
690
- # Contar modelos
691
- echo ""
692
- log_info "Modelos instalados:"
693
- for dir in checkpoints loras vae vae_approx text_encoders clip_vision upscale_models ultralytics; do
694
- if [ -d "$MODELS_DIR/$dir" ]; then
695
- local count=$(find "$MODELS_DIR/$dir" -type f \( -name "*.safetensors" -o -name "*.pth" -o -name "*.pt" -o -name "*.ckpt" -o -name "*.onnx" \) 2>/dev/null | wc -l)
696
- if [ $count -gt 0 ]; then
697
- log_success " $dir: $count arquivo(s)"
698
- fi
699
- fi
700
- done
701
-
702
- # Contar nodes
703
- echo ""
704
- local node_count=$(find "$CN_DIR" -maxdepth 1 -type d 2>/dev/null | wc -l)
705
- log_success "Custom nodes: $((node_count - 1)) instalados"
706
-
707
- # Verificar GPU
708
- echo ""
709
- local gpu_info=$(nvidia-smi --query-gpu=name --format=csv,noheader 2>/dev/null || echo "Não detectada")
710
- log_info "GPU: $gpu_info"
711
-
712
- # Marcar instalação como completa
713
- save_state "8"
714
-
715
- echo ""
716
- log_success "========================================="
717
- log_success " Instalação concluída!"
718
- log_success "========================================="
719
-
720
- # Se não for interativo ou se for via argumento, iniciar direto
721
- if [ "$INTERACTIVE" = false ] || [ "${1:-}" = "--start" ]; then
722
- log_info "Iniciando ComfyUI automaticamente..."
723
- log_info "URL: http://localhost:$COMFY_PORT"
724
- cd "$COMFY_DIR"
725
- exec comfy launch -- --listen "$COMFY_HOST" --port "$COMFY_PORT"
726
- fi
727
-
728
- echo ""
729
  echo "Opções:"
730
  echo " 1) Iniciar ComfyUI agora"
731
- echo " 2) Resetar estado da instalação"
732
- echo " 3) Sair"
733
- echo ""
734
-
735
- # Timeout de 10 segundos, padrão é iniciar
736
- read -t 10 -p "Escolha uma opção [1-3] (padrão: 1 em 10s): " final_choice || final_choice="1"
737
-
738
- case $final_choice in
739
- 1|"")
740
- log_info "Iniciando ComfyUI..."
741
- log_info "URL: http://localhost:$COMFY_PORT"
742
- cd "$COMFY_DIR"
743
- exec comfy launch -- --listen "$COMFY_HOST" --port "$COMFY_PORT"
744
- ;;
745
- 2)
746
- reset_state
747
- log_success "Estado resetado. Execute o script novamente para reinstalar."
748
- ;;
749
- 3)
750
- log_info "Saindo..."
751
- ;;
752
- *)
753
- log_info "Iniciando ComfyUI (opção padrão)..."
754
- cd "$COMFY_DIR"
755
- exec comfy launch -- --listen "$COMFY_HOST" --port "$COMFY_PORT"
756
- ;;
757
  esac
 
758
  }
759
 
760
- # Executar instalação
761
- main "$@"
 
1
  #!/usr/bin/env bash
2
+ # setup_comfyui_simplificado.sh
3
+ # Objetivo: script simples, previsível e resiliente para instalar/atualizar ComfyUI
4
+ # - Ambiente isolado em venv (sem poluir Python do sistema)
5
+ # - Torch/Torchvision/Torchaudio sempre compatíveis (um único passo)
6
+ # - Estado persistente com retomada de steps, downloads e nodes
7
+ # - Downloads com retry/timeout e suporte Mega/HF/HTTP(s)
8
+ # - Layout e variáveis fáceis de editar (manifesto inline)
9
 
10
+ set -Eeuo pipefail
11
 
12
+ # ====== Configuração básica ======
13
+ COMFY_DIR=${COMFY_DIR:-"/root/comfy/ComfyUI"}
14
+ VENV_DIR=${VENV_DIR:-"$COMFY_DIR/.venv"}
15
+ PYTHON="$VENV_DIR/bin/python"
16
+ PIP="$VENV_DIR/bin/pip"
17
+ COMFY_HOST=${COMFY_HOST:-"0.0.0.0"}
18
+ COMFY_PORT=${COMFY_PORT:-"8818"}
19
 
20
+ # Tokens opcionais
21
+ CIVITAI_TOKEN=${CIVITAI_TOKEN:-""} # NUNCA hardcode aqui. Passe por env.
22
+ HF_TOKEN=${HF_TOKEN:-""}
 
 
 
 
 
 
23
 
24
+ # Diretórios de modelo
 
 
 
 
 
 
 
 
 
25
  MODELS_DIR="$COMFY_DIR/models"
 
 
 
 
26
 
27
+ # Estado
28
+ STATE_DIR=${STATE_DIR:-"/root/.comfyui_setup_state"}
29
+ STATE_FILE="$STATE_DIR/step.txt"
30
+ DONE_DL="$STATE_DIR/completed_downloads.txt"
31
+ DONE_NODE="$STATE_DIR/completed_nodes.txt"
32
+ mkdir -p "$STATE_DIR"
33
+ : > "$DONE_DL" 2>/dev/null || true
34
+ : > "$DONE_NODE" 2>/dev/null || true
35
 
36
+ # Tempo & rede
37
+ RETRIES=${RETRIES:-3}
38
+ CONNECT_TIMEOUT=${CONNECT_TIMEOUT:-30} # seg
39
+ DL_TIMEOUT=${DL_TIMEOUT:-3600} # seg
 
 
 
 
40
 
41
+ # UI
42
+ BLUE='\033[0;34m'; GREEN='\033[0;32m'; YELLOW='\033[1;33m'; RED='\033[0;31m'; CYAN='\033[0;36m'; NC='\033[0m'
43
+ log_info(){ echo -e "${BLUE}[INFO]${NC} $*"; }
44
+ log_ok(){ echo -e "${GREEN}[✓]${NC} $*"; }
45
+ log_warn(){ echo -e "${YELLOW}[!]${NC} $*"; }
46
+ log_err(){ echo -e "${RED}[✗]${NC} $*"; }
47
+ log_step(){ echo -e "${CYAN}[→]${NC} $*"; }
48
 
49
+ # ====== Manifestos (edite à vontade) ======
50
+ # Formato: "URL|subpasta_em_models|nome_arquivo(opcional)"
51
+ # Use mega:// para links do Mega. Para HF você pode usar hf://<repo>/<path>
52
+ read -r -d '' DOWNLOADS << 'EOF'
53
+ https://civitai.com/api/download/models/2122278?type=Model&format=SafeTensor&size=pruned&fp=fp16|checkpoints|raehoshiIllustXL_v60.safetensors
54
+ https://civitai.com/api/download/models/1268294?type=Model&format=SafeTensor|loras|
55
+ https://civitai.com/api/download/models/1715330?type=Model&format=SafeTensor|loras|
56
+ https://civitai.com/api/download/models/1499397?type=Model&format=SafeTensor|loras|
57
+ https://civitai.com/api/download/models/1779002?type=Model&format=SafeTensor|loras|
58
+ https://civitai.com/api/download/models/1114313?type=Model&format=SafeTensor|loras|
59
+ https://civitai.com/api/download/models/1780244?type=Model&format=SafeTensor|loras|
60
+ mega://https://mega.nz/file/gIRTFQSQ#no6Ay3JLE9LVRi7ib9O-Jc0CW7XmG046kCgpCzDg1tY|loras|
61
+ https://huggingface.co/Kim2091/AnimeSharp/resolve/main/4x-AnimeSharp.pth|upscale_models|4x-AnimeSharp.pth
62
+ https://huggingface.co/Kim2091/AnimeSharpV3/resolve/main/2x-AnimeSharpV3.pth|upscale_models|2x-AnimeSharpV3.pth
63
+ https://huggingface.co/ABDALLALSWAITI/Upscalers/resolve/main/anime/2x-AnimeSharpV2_MoSR_Soft.pth|upscale_models|2x-AnimeSharpV2_MoSR_Soft.pth
64
+ https://huggingface.co/Kim2091/UltraSharpV2/resolve/main/4x-UltraSharpV2.pth|upscale_models|4x-UltraSharpV2.pth
65
+ https://huggingface.co/Kim2091/UltraSharpV2/resolve/main/4x-UltraSharpV2_Lite.pth|upscale_models|4x-UltraSharpV2_Lite.pth
66
+ https://huggingface.co/Kim2091/UltraSharpV2/resolve/main/4x-UltraSharpV2_fp32_op17.onnx|upscale_models|4x-UltraSharpV2_fp32_op17.onnx
67
+ https://huggingface.co/adbrasi/testedownload/resolve/main/99coins_anime_girl_face_m_seg.pt|ultralytics/bbox|99coins_anime_girl_face_m_seg.pt
68
+ EOF
69
 
70
+ # Lista de nodes (clones git). Edite à vontade.
71
+ CUSTOM_NODES=(
72
+ https://github.com/adbrasi/huggpackreator
73
+ https://github.com/adbrasi/packreator_processor
74
+ https://github.com/adbrasi/Packreator_manager
75
+ https://github.com/adbrasi/cezarsave34
76
+ https://github.com/adbrasi/pageonetor
77
+ https://github.com/adbrasi/pakreatorio
78
+ https://github.com/adbrasi/WaterMark_bumbumzin
79
+ https://github.com/adbrasi/marcadaguita
80
+ https://github.com/adbrasi/randomico
81
+ https://github.com/adbrasi/groqrouter
82
+ https://github.com/adbrasi/find_charakito
83
+ https://github.com/adbrasi/randomsizito
84
+ https://github.com/adbrasi/importex
85
+ https://github.com/adbrasi/storitadifusita
86
+ https://github.com/adbrasi/attentionPPM
87
+ https://github.com/ClownsharkBatwing/RES4LYF
88
+ https://github.com/Suzie1/ComfyUI_Comfyroll_CustomNodes
89
+ https://github.com/sipherxyz/comfyui-art-venture
90
+ https://github.com/pamparamm/sd-perturbed-attention
91
+ https://github.com/KoreTeknology/ComfyUI-Universal-Styler
92
+ https://github.com/WASasquatch/was-node-suite-comfyui
93
+ https://github.com/chflame163/ComfyUI_LayerStyle
94
+ https://github.com/ltdrdata/ComfyUI-Impact-Pack
95
+ https://github.com/pythongosssss/ComfyUI-Custom-Scripts
96
+ https://github.com/rgthree/rgthree-comfy
97
+ https://github.com/ssitu/ComfyUI_UltimateSDUpscale
98
+ https://github.com/adbrasi/Importador
99
+ https://github.com/adbrasi/GetFirstTag
100
+ https://github.com/adbrasi/comfydodi
101
+ https://github.com/omar92/ComfyUI-QualityOfLifeSuit_Omar92
102
+ https://github.com/Cezarsaint/blacklisto
103
+ https://github.com/TinyTerra/ComfyUI_tinyterraNodes
104
+ https://github.com/ltdrdata/ComfyUI-Impact-Subpack
105
+ https://github.com/Cezarsaint/rand0micoUploaderLoven
106
+ https://github.com/adbrasi/pixivmosaic
107
+ https://github.com/adbrasi/futfilter
108
+ https://github.com/Artificial-Sweetener/comfyui-WhiteRabbit
109
+ https://github.com/shiimizu/ComfyUI_smZNodes
110
+ https://github.com/CoreyCorza/ComfyUI-CRZnodes
111
+ )
112
 
113
+ # ====== Estado ======
114
+ get_state(){ [[ -s "$STATE_FILE" ]] && cat "$STATE_FILE" || echo 0; }
115
+ save_state(){ printf '%s\n' "$1" >"$STATE_FILE.tmp" && mv -f "$STATE_FILE.tmp" "$STATE_FILE"; log_info "Estado salvo: $1"; }
116
+ mark_done(){ local f="$1"; shift; local key="$*"; grep -Fxq "$key" "$f" 2>/dev/null || echo "$key" >> "$f"; }
117
+ was_done(){ local f="$1"; shift; local key="$*"; grep -Fxq "$key" "$f" 2>/dev/null; }
118
 
119
+ # ====== Dependências base ======
120
+ need(){ command -v "$1" >/dev/null 2>&1; }
121
+ ensure_base(){
122
+ log_step "[1/7] Instalando dependências do SO (git, curl, wget, aria2, megatools, python3-venv)…"
123
+ export DEBIAN_FRONTEND=noninteractive
124
+ apt-get update -qq
125
+ apt-get install -y -qq git curl wget aria2 megatools python3 python3-venv ca-certificates
126
+ log_ok "Dependências do SO OK"
127
+ save_state 1
128
  }
129
 
130
+ # ====== Ambiente Python isolado ======
131
+ ensure_venv(){
132
+ log_step "[2/7] Preparando venv…"
133
+ if [[ ! -x "$PYTHON" ]]; then
134
+ mkdir -p "$COMFY_DIR"
135
+ python3 -m venv "$VENV_DIR"
136
+ fi
137
+ "$PIP" install -q --upgrade pip wheel setuptools
138
+ # Login opcional no HF
139
+ if [[ -n "$HF_TOKEN" ]]; then
140
+ "$PYTHON" -m pip install -q huggingface_hub[cli,hf_transfer]
141
+ "$VENV_DIR/bin/hf" auth login --token "$HF_TOKEN" || log_warn "HF auth falhou (seguindo sem login)"
142
+ fi
143
+ log_ok "Venv OK"
144
+ save_state 2
145
  }
146
 
147
+ # ====== Torch consistente (1 passo) ======
148
+ install_torch(){
149
+ log_step "[3/7] Instalando PyTorch/Torchvision/Torchaudio…"
150
+ local gpu_name="$(nvidia-smi --query-gpu=name --format=csv,noheader 2>/dev/null || true)"
151
+ local use_nightly=0
152
+ if echo "$gpu_name" | grep -Eqi "5090|5080|blackwell"; then use_nightly=1; fi
153
 
154
+ if (( use_nightly )); then
155
+ log_warn "GPU Blackwell detectada ($gpu_name). Usando *nightly cu128* compatível."
156
+ "$PIP" install --pre -q \
157
+ --extra-index-url https://download.pytorch.org/whl/nightly/cu128 \
158
+ torch torchvision torchaudio
159
+ else
160
+ log_info "GPU: ${gpu_name:-Não detectada}. Usando *estável cu128*."
161
+ "$PIP" install -q \
162
+ --index-url https://download.pytorch.org/whl/cu128 \
163
+ torch torchvision torchaudio
164
+ fi
165
+ log_ok "Torch stack OK"
166
+ save_state 3
167
  }
168
 
169
+ # ====== ComfyUI ======
170
+ install_comfy(){
171
+ log_step "[4/7] Instalando/Atualizando ComfyUI…"
172
+ if [[ -d "$COMFY_DIR/.git" ]]; then
173
+ git -C "$COMFY_DIR" pull --ff-only || log_warn "git pull falhou (mantendo versão atual)"
174
+ else
175
+ git clone --recursive https://github.com/comfyanonymous/ComfyUI "$COMFY_DIR"
176
+ fi
177
+ "$PIP" install -q -r "$COMFY_DIR/requirements.txt"
178
+ # Manager (útil p/ gerir nodes)
179
+ local mdir="$COMFY_DIR/custom_nodes/ComfyUI-Manager"
180
+ if [[ -d "$mdir/.git" ]]; then
181
+ git -C "$mdir" pull --ff-only || true
182
+ else
183
+ git clone --depth 1 https://github.com/ltdrdata/ComfyUI-Manager "$mdir"
184
+ fi
185
+ log_ok "ComfyUI OK"
186
+ save_state 4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
187
  }
188
 
189
+ # ====== Downloads ======
190
+ add_civitai_token(){
191
+ local url="$1"
192
+ if [[ "$url" == *"civitai.com/api/download"* && "$url" != *"token="* ]]; then
193
+ if [[ -n "$CIVITAI_TOKEN" ]]; then
194
+ printf '%s&token=%s' "$url" "$CIVITAI_TOKEN"
195
+ return 0
196
+ else
197
+ log_warn "Civitai sem token: pulando $url"
198
+ return 1
199
  fi
200
+ fi
201
+ printf '%s' "$url"
202
  }
203
 
204
+ http_download(){ # url dir [filename]
205
+ local url="$1"; local dir="$2"; local name="${3:-}"
206
+ mkdir -p "$dir"
207
+ local final_url
208
+ if ! final_url=$(add_civitai_token "$url"); then return 1; fi
209
+ if need aria2c; then
210
+ local args=("-c" "-x16" "-s16" "-k1M" "--max-tries=$RETRIES" "--retry-wait=5" "--timeout=$CONNECT_TIMEOUT" "--console-log-level=warn" "--summary-interval=10")
211
+ if [[ -n "$name" ]]; then
212
+ aria2c "${args[@]}" --dir="$dir" --out="$name" "$final_url" && return 0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
213
  else
214
+ aria2c "${args[@]}" --dir="$dir" "$final_url" && return 0
215
  fi
216
+ fi
217
+ if need wget; then
218
+ local wargs=("-c" "--tries=$RETRIES" "--timeout=$CONNECT_TIMEOUT" "--read-timeout=$DL_TIMEOUT")
219
+ if [[ -n "$name" ]]; then
220
+ wget -q "${wargs[@]}" -O "$dir/$name" "$final_url" && return 0
 
 
 
 
 
 
221
  else
222
+ wget -q "${wargs[@]}" --content-disposition -P "$dir" "$final_url" && return 0
223
  fi
224
+ fi
225
+ # curl fallback
226
+ local cargs=("-L" "--retry" "$RETRIES" "--connect-timeout" "$CONNECT_TIMEOUT" "--max-time" "$DL_TIMEOUT" "-C" "-")
227
+ if [[ -n "$name" ]]; then
228
+ curl -sS "${cargs[@]}" -o "$dir/$name" "$final_url" && return 0
229
+ else
230
+ # tentar extrair nome do header
231
+ local detected=$(curl -sI -L "$final_url" | sed -n 's/.*filename="\([^"]\+\)".*/\1/p' | tr -d '\r' | head -1)
232
+ [[ -z "$detected" ]] && detected="download_$(date +%s)"
233
+ curl -sS "${cargs[@]}" -o "$dir/$detected" "$final_url" && return 0
234
+ fi
235
+ return 1
236
  }
237
 
238
+ mega_download(){ # mega_url dir [filename]
239
+ local url="$1"; local dir="$2"; local name="${3:-}"
240
+ mkdir -p "$dir"
241
+ url="${url#mega://}"
242
+ if ! need megadl; then log_err "megadl não encontrado"; return 1; fi
243
+ log_info "megadl -> $url"
244
+ if timeout "$DL_TIMEOUT" megadl --path "$dir" "$url"; then
245
+ if [[ -n "$name" ]]; then
246
+ # renomeia para nome fixo, mantendo o arquivo único baixado
247
+ local got=$(find "$dir" -maxdepth 1 -type f -printf '%f\n' | tail -n 1)
248
+ [[ -n "$got" ]] && mv -f "$dir/$got" "$dir/$name"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
249
  fi
250
+ return 0
251
+ fi
252
+ return 1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
253
  }
254
 
255
+ hf_download(){ # hf://repo/path/to/file dir [filename]
256
+ local spec="$1"; local dir="$2"; local name="${3:-}"
257
+ mkdir -p "$dir"
258
+ spec="${spec#hf://}"
259
+ local repo="${spec%%/*/*}"
260
+ local path="${spec#*/ */}"
261
+ # Uso simples: se tiver a CLI, usa; senão cai no http_download se passar uma URL de 'resolve/main'
262
+ if "$VENV_DIR/bin/hf" --version >/dev/null 2>&1; then
263
+ "$VENV_DIR/bin/hf" download "$repo" "$path" --local-dir "$dir" --local-dir-use-symlinks False
264
+ if [[ -n "$name" ]]; then
265
+ local got=$(find "$dir" -type f \( -name "*.safetensors" -o -name "*.pth" -o -name "*.pt" -o -name "*.onnx" -o -name "*.bin" \) | head -1)
266
+ [[ -n "$got" ]] && mv -f "$got" "$dir/$name"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
267
  fi
268
+ return 0
269
+ fi
270
+ log_warn "hf CLI não disponível; tente fornecer URL de resolve/main"
271
+ return 1
272
  }
273
 
274
+ subdir_for(){
275
+ case "$1" in
276
+ checkpoints|diffusion_models|loras|vae|vae_approx|text_encoders|clip_vision|upscale_models) echo "$MODELS_DIR/$1" ;;
277
+ ultralytics/bbox) echo "$MODELS_DIR/ultralytics/bbox" ;;
278
+ *) echo "$MODELS_DIR/$1" ;;
279
+ esac
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
280
  }
281
 
282
+ process_downloads(){
283
+ log_step "[5/7] Baixando modelos (com retry/timeout)…"
284
+ mkdir -p "$MODELS_DIR"/{diffusion_models,loras,vae,vae_approx,text_encoders,clip_vision,upscale_models,checkpoints,ultralytics/bbox}
285
+ local IFS=$'\n'
286
+ local i=0; local ok=0; local fail=0; local skip=0
287
+ for line in $DOWNLOADS; do
288
+ [[ -z "$line" || "$line" =~ ^# ]] && continue
289
+ ((i++))
290
+ IFS='|' read -r url kind name <<<"$line"
291
+ url="$(echo "$url" | xargs)"; kind="$(echo "$kind" | xargs)"; name="$(echo "${name:-}" | xargs)"
292
+ local dst=$(subdir_for "$kind")
293
+ if was_done "$DONE_DL" "$line"; then log_ok "[$i] já baixado: ${name:-$(basename "$url")}"; ((skip++)); continue; fi
294
+ log_step "[$i] ${name:-$(basename "$url")} → $kind"
295
+ if [[ "$url" == mega://* ]]; then
296
+ if mega_download "$url" "$dst" "$name"; then mark_done "$DONE_DL" "$line"; ((ok++)); else ((fail++)); log_warn "Falha Mega, seguindo"; fi
297
+ elif [[ "$url" == hf://* ]]; then
298
+ if hf_download "$url" "$dst" "$name"; then mark_done "$DONE_DL" "$line"; ((ok++)); else ((fail++)); fi
299
  else
300
+ if http_download "$url" "$dst" "$name"; then mark_done "$DONE_DL" "$line"; ((ok++)); else ((fail++)); fi
 
 
 
 
301
  fi
302
+ done
303
+ log_info "Downloads: novos=$ok, pulados=$skip, falhas=$fail"
304
+ save_state 5
 
 
 
 
 
 
305
  }
306
 
307
+ # ====== Custom Nodes ======
308
+ clone_or_update(){ # url dest
309
+ local url="$1"; local dest="$2"; local key="node:$url"
310
+ if was_done "$DONE_NODE" "$key" && [[ -d "$dest" ]]; then log_ok "Node OK: $(basename "$dest")"; return 0; fi
311
+ if [[ -d "$dest/.git" ]]; then
312
+ git -C "$dest" pull --ff-only || log_warn "pull falhou: $(basename "$dest")"
313
+ else
314
+ git clone --depth 1 "$url" "$dest" || { log_warn "clone falhou: $url"; return 0; }
315
+ fi
316
+ # requirements do node (best-effort)
317
+ if [[ -f "$dest/requirements.txt" ]]; then
318
+ "$PIP" install -q -r "$dest/requirements.txt" || log_warn "pip req falhou em $(basename "$dest")"
319
+ fi
320
+ mark_done "$DONE_NODE" "$key"
 
 
 
 
 
 
 
321
  }
322
 
323
+ install_nodes(){
324
+ log_step "[6/7] Instalando/Atualizando custom nodes…"
325
+ local CN_DIR="$COMFY_DIR/custom_nodes"
326
+ mkdir -p "$CN_DIR"
327
+ local total=${#CUSTOM_NODES[@]}
328
+ local idx=0
329
+ for repo in "${CUSTOM_NODES[@]}"; do
330
+ ((idx++))
331
+ log_step "[$idx/$total] $(basename "$repo")"
332
+ clone_or_update "$repo" "$CN_DIR/$(basename "$repo")"
333
+ done
334
+ log_ok "Nodes OK"
335
+ save_state 6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
336
  }
337
 
338
+ # ====== Verificação final & execução ======
339
+ final_check(){
340
+ log_step "[7/7] Verificação final…"
341
+ [[ -f "$COMFY_DIR/main.py" ]] && log_ok "ComfyUI presente" || { log_err "ComfyUI ausente"; exit 1; }
342
+ # contagens
343
+ for d in checkpoints loras vae vae_approx text_encoders clip_vision upscale_models ultralytics; do
344
+ local p="$MODELS_DIR/$d"; [[ -d "$p" ]] || continue
345
+ local c=$(find "$p" -type f \( -name "*.safetensors" -o -name "*.pth" -o -name "*.pt" -o -name "*.ckpt" -o -name "*.onnx" \) 2>/dev/null | wc -l || echo 0)
346
+ (( c > 0 )) && log_ok "$d: $c arquivo(s)"
347
+ done
348
+ local gpu="$(nvidia-smi --query-gpu=name --format=csv,noheader 2>/dev/null || echo "Não detectada")"
349
+ log_info "GPU: $gpu"
350
+ save_state 7
351
+ }
352
+
353
+ launch(){
354
+ log_info "Iniciando ComfyUI em http://$COMFY_HOST:$COMFY_PORT"
355
+ cd "$COMFY_DIR"
356
+ exec "$PYTHON" main.py --listen "$COMFY_HOST" --port "$COMFY_PORT"
357
+ }
358
+
359
+ # ====== Fluxo principal ======
360
+ main(){
361
+ log_info "==============================="
362
+ log_info " ComfyUI Setup (Simplificado)"
363
+ log_info "==============================="
364
+
365
+ local st=$(get_state)
366
+ log_info "Step atual: $st"
367
+
368
+ (( st < 1 )) && ensure_base
369
+ (( $(get_state) < 2 )) && ensure_venv
370
+ (( $(get_state) < 3 )) && install_torch
371
+ (( $(get_state) < 4 )) && install_comfy
372
+ (( $(get_state) < 5 )) && process_downloads
373
+ (( $(get_state) < 6 )) && install_nodes
374
+ final_check
375
+
376
+ # Auto-start se não-interativo (pipe) ou se passar --start
377
+ if [[ ! -t 0 || ! -t 1 || "${1:-}" == "--start" ]]; then
378
+ launch
379
+ else
380
+ echo
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
381
  echo "Opções:"
382
  echo " 1) Iniciar ComfyUI agora"
383
+ echo " 2) Sair"
384
+ read -r -t 10 -p "Escolha [1-2] (padrão 1 em 10s): " ch || ch=1
385
+ case "$ch" in
386
+ 1|"") launch;;
387
+ 2) log_info "Saindo…";;
388
+ *) launch;;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
389
  esac
390
+ fi
391
  }
392
 
393
+ main "$@"