adbrasi commited on
Commit
0f4d02a
Β·
verified Β·
1 Parent(s): c0d6478

Upload comfyui_setup_script.sh

Browse files
Files changed (1) hide show
  1. comfyui_setup_script.sh +386 -315
comfyui_setup_script.sh CHANGED
@@ -1,402 +1,473 @@
1
  #!/bin/bash
2
 
3
- # =============================================================================
4
- # ComfyUI Professional Setup Script
5
- # =============================================================================
6
- # Autor: Setup automatizado para RunPod/VastAI
7
- # VersΓ£o: 1.0
8
- # DescriΓ§Γ£o: Instala e configura ComfyUI com todas as dependΓͺncias necessΓ‘rias
9
- # =============================================================================
10
-
11
- set -euo pipefail # Exit on error, undefined vars, pipe failures
12
-
13
- # Cores para output
14
- readonly RED='\033[0;31m'
15
- readonly GREEN='\033[0;32m'
16
- readonly YELLOW='\033[1;33m'
17
- readonly BLUE='\033[0;34m'
18
- readonly MAGENTA='\033[0;35m'
19
- readonly CYAN='\033[0;36m'
20
- readonly WHITE='\033[1;37m'
21
- readonly NC='\033[0m' # No Color
22
-
23
- # ConfiguraΓ§Γ΅es
24
- readonly SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
25
- readonly LOG_FILE="${SCRIPT_DIR}/setup.log"
26
- readonly COMFY_DIR="/root/comfy"
27
- readonly TOKEN="0b698de03658fb8df2eeef90bad3ab9a"
28
- readonly LISTEN_PORT="8818"
29
-
30
- # URLs dos arquivos
31
- declare -A DOWNLOADS=(
32
- ["checkpoint"]="https://civitai.com/api/download/models/1761560?type=Model&format=SafeTensor&size=pruned&fp=fp16&token=${TOKEN}"
33
- ["lora1"]="https://civitai.com/api/download/models/1426079?type=Model&format=SafeTensor&token=${TOKEN}"
34
- ["lora2"]="https://civitai.com/api/download/models/1193082?type=Model&format=SafeTensor&token=${TOKEN}"
35
- ["snapshot"]="https://huggingface.co/adbrasi/testedownload/resolve/main/snapshotBRABEX.json"
36
  )
37
 
38
- declare -A DOWNLOAD_PATHS=(
39
- ["checkpoint"]="${COMFY_DIR}/ComfyUI/models/checkpoints"
40
- ["lora1"]="${COMFY_DIR}/ComfyUI/models/loras"
41
- ["lora2"]="${COMFY_DIR}/ComfyUI/models/loras"
42
- ["snapshot"]="${COMFY_DIR}/"
 
 
 
 
43
  )
44
 
45
- # =============================================================================
46
- # FUNÇÕES UTILITÁRIAS
47
- # =============================================================================
48
-
49
- log() {
50
- local level="$1"
51
- shift
52
- local message="$*"
53
- local timestamp=$(date '+%Y-%m-%d %H:%M:%S')
54
-
55
- case "$level" in
56
- "INFO") echo -e "${CYAN}[INFO]${NC} ${message}" | tee -a "$LOG_FILE" ;;
57
- "WARN") echo -e "${YELLOW}[WARN]${NC} ${message}" | tee -a "$LOG_FILE" ;;
58
- "ERROR") echo -e "${RED}[ERROR]${NC} ${message}" | tee -a "$LOG_FILE" ;;
59
- "SUCCESS") echo -e "${GREEN}[SUCCESS]${NC} ${message}" | tee -a "$LOG_FILE" ;;
60
- "STEP") echo -e "${MAGENTA}[STEP]${NC} ${WHITE}${message}${NC}" | tee -a "$LOG_FILE" ;;
61
- esac
62
-
63
- echo "[$timestamp] [$level] $message" >> "$LOG_FILE"
 
 
 
64
  }
65
 
66
- print_banner() {
67
- echo -e "${CYAN}"
68
- cat << 'EOF'
69
- ╔══════════════════════════════════════════════════════════════╗
70
- β•‘ ComfyUI Setup Script β•‘
71
- β•‘ Professional Installation β•‘
72
- β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•
73
- EOF
74
- echo -e "${NC}"
75
  }
76
 
77
- check_dependencies() {
78
- log "STEP" "Verificando dependΓͺncias do sistema..."
79
-
80
- local deps=("curl" "wget" "python3" "pip")
81
- local missing_deps=()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82
 
83
- for dep in "${deps[@]}"; do
84
- if ! command -v "$dep" &> /dev/null; then
85
- missing_deps+=("$dep")
86
- fi
87
- done
88
 
89
- if [[ ${#missing_deps[@]} -ne 0 ]]; then
90
- log "ERROR" "DependΓͺncias faltando: ${missing_deps[*]}"
91
- return 1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92
  fi
93
-
94
- log "SUCCESS" "Todas as dependΓͺncias bΓ‘sicas estΓ£o disponΓ­veis"
95
  }
96
 
97
- install_system_packages() {
98
- log "STEP" "Instalando pacotes do sistema..."
 
 
 
 
99
 
100
- if command -v apt-get &> /dev/null; then
101
- apt-get update -qq
102
- apt-get install -y -qq aria2 wget curl
103
- log "SUCCESS" "Pacotes do sistema instalados com sucesso"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
104
  else
105
- log "WARN" "apt-get nΓ£o encontrado, pulando instalaΓ§Γ£o de pacotes do sistema"
 
 
 
 
 
106
  fi
107
  }
108
 
 
 
 
 
109
  install_comfy_cli() {
110
- log "STEP" "Instalando comfy-cli..."
111
 
112
- pip install --quiet --upgrade pip
113
- pip install --quiet comfy-cli
 
 
114
 
115
- if ! command -v comfy &> /dev/null; then
116
- log "ERROR" "Falha na instalaΓ§Γ£o do comfy-cli"
117
- return 1
 
 
 
 
 
 
 
 
118
  fi
119
 
120
- log "SUCCESS" "comfy-cli instalado com sucesso"
121
  }
122
 
123
- install_comfyui() {
124
- log "STEP" "Instalando ComfyUI com suporte NVIDIA..."
125
-
126
- comfy --skip-prompt install --nvidia
 
 
127
 
128
- if [[ ! -d "$COMFY_DIR" ]]; then
129
- log "ERROR" "DiretΓ³rio do ComfyUI nΓ£o foi criado"
130
- return 1
131
- fi
132
 
133
- log "SUCCESS" "ComfyUI instalado com sucesso"
134
  }
135
 
136
- install_custom_nodes() {
137
- log "STEP" "Instalando nΓ³s customizados..."
138
-
139
- local nodes=(
140
- "https://github.com/Cezarsaint/custom_prompt_manager"
141
- "https://github.com/adbrasi/pakreatorio"
142
- )
143
 
144
- for node in "${nodes[@]}"; do
145
- log "INFO" "Instalando nΓ³: $(basename "$node")"
146
- if comfy node install "$node"; then
147
- log "SUCCESS" "NΓ³ $(basename "$node") instalado com sucesso"
148
- else
149
- log "WARN" "Falha ao instalar nΓ³: $(basename "$node")"
150
- fi
151
  done
 
 
 
152
  }
153
 
154
- create_directories() {
155
- log "STEP" "Criando estrutura de diretΓ³rios..."
156
-
157
- local dirs=(
158
- "${COMFY_DIR}/ComfyUI/models/checkpoints"
159
- "${COMFY_DIR}/ComfyUI/models/loras"
160
- )
161
 
162
- for dir in "${dirs[@]}"; do
163
- mkdir -p "$dir"
164
- log "INFO" "DiretΓ³rio criado: $dir"
 
 
165
  done
166
  }
167
 
168
- download_files() {
169
- log "STEP" "Iniciando downloads paralelos dos modelos..."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
170
 
171
- local pids=()
172
- local download_success=true
173
 
174
- # FunΓ§Γ£o para download individual
175
- download_file() {
176
- local name="$1"
177
- local url="$2"
178
- local path="$3"
 
179
 
180
- log "INFO" "Baixando $name..."
 
 
 
 
181
 
182
- if [[ "$name" == "snapshot" ]]; then
183
- # Usar wget para o snapshot
184
- if wget --quiet --show-progress --progress=bar:force:noscroll \
185
- --timeout=30 --tries=3 \
186
- "$url" -P "$path"; then
187
- log "SUCCESS" "Download concluΓ­do: $name"
188
- return 0
189
- else
190
- log "ERROR" "Falha no download: $name"
191
- return 1
192
- fi
193
  else
194
- # Usar aria2c para modelos grandes
195
- if aria2c --console-log-level=warn \
196
- --summary-interval=10 \
197
- --download-result=hide \
198
- -c -s 16 -x 16 -k 1M \
199
- --timeout=60 --retry-wait=5 --max-tries=3 \
200
- -d "$path" "$url"; then
201
- log "SUCCESS" "Download concluΓ­do: $name"
202
- return 0
 
 
 
 
 
 
 
 
 
 
203
  else
204
- log "ERROR" "Falha no download: $name"
205
- return 1
 
 
 
206
  fi
207
  fi
208
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
209
 
210
- # Iniciar downloads em paralelo
211
- for name in "${!DOWNLOADS[@]}"; do
212
- download_file "$name" "${DOWNLOADS[$name]}" "${DOWNLOAD_PATHS[$name]}" &
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
213
  pids+=($!)
214
  done
215
 
216
- # Aguardar conclusΓ£o de todos os downloads
217
- for pid in "${pids[@]}"; do
218
- if ! wait "$pid"; then
219
- download_success=false
 
 
 
 
 
 
 
 
 
 
 
 
 
220
  fi
221
  done
222
 
223
- if [[ "$download_success" == true ]]; then
224
- log "SUCCESS" "Todos os downloads concluΓ­dos com sucesso"
225
  else
226
- log "WARN" "Alguns downloads falharam, mas continuando..."
227
  fi
228
  }
229
 
 
 
 
 
230
  restore_snapshot() {
231
- log "STEP" "Restaurando snapshot..."
232
 
233
- local snapshot_file="${COMFY_DIR}/snapshotBRABEX.json"
234
 
235
- if [[ -f "$snapshot_file" ]]; then
236
- if comfy node restore-snapshot "$snapshot_file"; then
237
- log "SUCCESS" "Snapshot restaurado com sucesso"
238
  else
239
- log "WARN" "Falha ao restaurar snapshot"
240
  fi
241
  else
242
- log "WARN" "Arquivo de snapshot nΓ£o encontrado"
243
  fi
244
  }
245
 
246
- create_launch_script() {
247
- log "STEP" "Criando script de inicializaΓ§Γ£o..."
248
-
249
- local launch_script="${SCRIPT_DIR}/launch-comfyui.sh"
250
-
251
- cat > "$launch_script" << EOF
252
- #!/bin/bash
253
- # Script de inicializaΓ§Γ£o do ComfyUI
254
- # Gerado automaticamente em $(date)
255
 
256
- cd "$COMFY_DIR" || exit 1
257
-
258
- echo "Iniciando ComfyUI..."
259
- echo "Acesse: http://localhost:${LISTEN_PORT}"
260
- echo "Ou use o endereΓ§o pΓΊblico do seu RunPod/VastAI na porta ${LISTEN_PORT}"
261
- echo ""
262
-
263
- comfy launch -- --fast --listen 0.0.0.0 --port ${LISTEN_PORT}
264
- EOF
265
-
266
- chmod +x "$launch_script"
267
- log "SUCCESS" "Script de inicializaΓ§Γ£o criado: $launch_script"
268
- }
269
-
270
- cleanup() {
271
- log "INFO" "Limpando arquivos temporΓ‘rios..."
272
-
273
- # Limpar cache do pip
274
- pip cache purge 2>/dev/null || true
275
-
276
- # Limpar logs antigos (manter apenas os ΓΊltimos 5)
277
- find "$SCRIPT_DIR" -name "setup.log.*" -type f | head -n -5 | xargs rm -f 2>/dev/null || true
278
 
279
- log "SUCCESS" "Limpeza concluΓ­da"
 
280
  }
281
 
282
- show_summary() {
283
- echo -e "\n${GREEN}╔══════════════════════════════════════════════════════════════╗${NC}"
284
- echo -e "${GREEN}β•‘ INSTALAÇÃO CONCLUÍDA β•‘${NC}"
285
- echo -e "${GREEN}β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•${NC}"
286
- echo -e "\n${CYAN}Logs da instalaΓ§Γ£o:${NC}"
287
- echo -e "${WHITE} $LOG_FILE${NC}"
288
- echo -e "\n${YELLOW}Acesse ComfyUI em:${NC}"
289
- echo -e "${WHITE} http://localhost:$LISTEN_PORT${NC}"
290
- echo -e "${WHITE} ou use o endereΓ§o pΓΊblico do seu RunPod/VastAI na porta $LISTEN_PORT${NC}\n"
291
- }
292
 
293
- launch_comfyui() {
294
- log "STEP" "Iniciando ComfyUI automaticamente..."
 
295
 
296
- cd "$COMFY_DIR" || {
297
- log "ERROR" "NΓ£o foi possΓ­vel acessar o diretΓ³rio do ComfyUI"
298
- return 1
299
- }
300
 
301
- echo -e "\n${GREEN}╔══════════════════════════════════════════════════════════════╗${NC}"
302
- echo -e "${GREEN}β•‘ INICIANDO COMFYUI β•‘${NC}"
303
- echo -e "${GREEN}β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•${NC}"
304
- echo -e "\n${CYAN}πŸš€ ComfyUI estΓ‘ iniciando...${NC}"
305
- echo -e "${YELLOW}πŸ“± Acesse: http://localhost:${LISTEN_PORT}${NC}"
306
- echo -e "${YELLOW}🌐 Ou use o endereço público do seu RunPod/VastAI na porta ${LISTEN_PORT}${NC}"
307
- echo -e "\n${WHITE}Para parar o ComfyUI, pressione Ctrl+C${NC}\n"
308
 
309
- # Pequena pausa para o usuΓ‘rio ler as informaΓ§Γ΅es
310
- sleep 3
311
 
312
- log "INFO" "Executando: comfy launch -- --fast --listen 0.0.0.0 --port $LISTEN_PORT"
 
313
 
314
- # Executar ComfyUI
315
- exec comfy launch -- --fast --listen 0.0.0.0 --port "$LISTEN_PORT"
316
- }
317
-
318
- # =============================================================================
319
- # FUNÇÃO PRINCIPAL
320
- # =============================================================================
321
-
322
- main() {
323
- local start_time=$(date +%s)
324
-
325
- # Configurar arquivo de log
326
- exec > >(tee -a "$LOG_FILE")
327
- exec 2>&1
328
-
329
- print_banner
330
- log "INFO" "Iniciando instalaΓ§Γ£o do ComfyUI..."
331
- log "INFO" "Log da instalaΓ§Γ£o: $LOG_FILE"
332
-
333
- # Verificar se jΓ‘ existe uma instalaΓ§Γ£o
334
- if [[ -d "$COMFY_DIR" ]] && [[ -f "${COMFY_DIR}/ComfyUI/main.py" ]]; then
335
- log "WARN" "ComfyUI jΓ‘ parece estar instalado em $COMFY_DIR"
336
- read -p "Deseja continuar mesmo assim? (y/N): " -n 1 -r
337
- echo
338
- if [[ ! $REPLY =~ ^[Yy]$ ]]; then
339
- log "INFO" "InstalaΓ§Γ£o cancelada pelo usuΓ‘rio"
340
- exit 0
341
- fi
342
- fi
343
 
344
- # Executar etapas da instalaΓ§Γ£o
345
- local steps=(
346
- "check_dependencies"
347
- "install_system_packages"
348
- "install_comfy_cli"
349
- "install_comfyui"
350
- "create_directories"
351
- "install_custom_nodes"
352
- "download_files"
353
- "restore_snapshot"
354
- "create_launch_script"
355
- "cleanup"
356
- )
357
-
358
- local current_step=1
359
- local total_steps=${#steps[@]}
360
-
361
- for step in "${steps[@]}"; do
362
- echo -e "\n${BLUE}[$current_step/$total_steps]${NC} Executando: $step"
363
-
364
- if $step; then
365
- log "SUCCESS" "Etapa concluΓ­da: $step"
366
- else
367
- log "ERROR" "Falha na etapa: $step"
368
- log "ERROR" "InstalaΓ§Γ£o interrompida"
369
- exit 1
370
- fi
371
-
372
- ((current_step++))
373
- done
374
 
375
- local end_time=$(date +%s)
376
- local duration=$((end_time - start_time))
377
 
378
- log "SUCCESS" "InstalaΓ§Γ£o concluΓ­da em ${duration}s"
379
- show_summary
380
 
381
- # Iniciar ComfyUI automaticamente
 
 
 
382
  launch_comfyui
383
  }
384
 
385
- # =============================================================================
386
- # TRATAMENTO DE SINAIS
387
- # =============================================================================
388
-
389
- trap 'log "ERROR" "Script interrompido pelo usuΓ‘rio"; exit 1' INT TERM
390
-
391
- # =============================================================================
392
- # EXECUÇÃO
393
- # =============================================================================
394
 
395
- # Verificar se estΓ‘ sendo executado como root (recomendado para RunPod/VastAI)
396
- if [[ $EUID -ne 0 ]]; then
397
- log "WARN" "Script nΓ£o estΓ‘ sendo executado como root"
398
- log "WARN" "Algumas operaΓ§Γ΅es podem falhar"
399
- fi
400
 
401
- # Executar funΓ§Γ£o principal
402
  main "$@"
 
1
  #!/bin/bash
2
 
3
+ # ComfyUI Automated Setup Script
4
+ # Supports LightningAI, RunPod, VastAI, and generic Linux environments
5
+ # Author: Generated for automated ComfyUI deployment
6
+
7
+ set -e
8
+ set -o pipefail
9
+
10
+ # ============================================================================
11
+ # GLOBAL CONFIGURATIONS
12
+ # ============================================================================
13
+
14
+ # Civitai API Token
15
+ readonly CIVITAI_TOKEN="0b698de03658fb8df2eeef90bad3ab9a"
16
+
17
+ # Custom Nodes to Install
18
+ readonly CUSTOM_NODES=(
19
+ "https://github.com/Cezarsaint/custom_prompt_manager"
20
+ "https://github.com/adbrasi/pakreatorio"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
  )
22
 
23
+ # Files to Download - Format: "URL|target_subdir|filename"
24
+ # If filename is empty, let aria2c/wget determine from Content-Disposition
25
+ readonly DOWNLOAD_FILES=(
26
+ "https://civitai.com/api/download/models/1761560?type=Model&format=SafeTensor&size=pruned&fp=fp16|checkpoints|"
27
+ "https://civitai.com/api/download/models/1426079?type=Model&format=SafeTensor|loras|"
28
+ "https://civitai.com/api/download/models/1193082?type=Model&format=SafeTensor|loras|"
29
+ "https://huggingface.co/Kim2091/AnimeSharpV3/resolve/main/2x-AnimeSharpV3.pth|upscale_models|2x-AnimeSharpV3.pth"
30
+ "https://huggingface.co/adbrasi/testedownload/resolve/main/99coins_anime_girl_face_m_seg.pt|ultralytics/bbox|99coins_anime_girl_face_m_seg.pt"
31
+ "https://huggingface.co/adbrasi/testedownload/resolve/main/snapshotBRABEX.json|INSTALL_DIR|snapshotBRABEX.json"
32
  )
33
 
34
+ # Model directories to create
35
+ readonly MODEL_DIRS=(
36
+ "checkpoints"
37
+ "loras"
38
+ "upscale_models"
39
+ "ultralytics/bbox"
40
+ )
41
+
42
+ # Global variables
43
+ BASE_DIR=""
44
+ COMFY_INSTALL_DIR=""
45
+ MODELS_DIR=""
46
+ SUDO_PREFIX=""
47
+ ARIA2C_AVAILABLE=false
48
+ ENV_NAME=""
49
+
50
+ # ============================================================================
51
+ # UTILITY FUNCTIONS
52
+ # ============================================================================
53
+
54
+ log_info() {
55
+ echo "INFO: $1" >&2
56
  }
57
 
58
+ log_warning() {
59
+ echo "WARNING: $1" >&2
 
 
 
 
 
 
 
60
  }
61
 
62
+ log_error() {
63
+ echo "ERROR: $1" >&2
64
+ }
65
+
66
+ command_exists() {
67
+ command -v "$1" >/dev/null 2>&1
68
+ }
69
+
70
+ is_root() {
71
+ [ "$(id -u)" -eq 0 ]
72
+ }
73
+
74
+ # ============================================================================
75
+ # ENVIRONMENT DETECTION
76
+ # ============================================================================
77
+
78
+ detect_environment() {
79
+ log_info "Detecting environment..."
80
+
81
+ if [ -d "/teamspace/studios/this_studio" ]; then
82
+ BASE_DIR="/teamspace/studios/this_studio"
83
+ ENV_NAME="lightning"
84
+ elif [ -d "/workspace" ] && [ ! -d "/teamspace/studios/this_studio" ]; then
85
+ BASE_DIR="/workspace"
86
+ ENV_NAME="runpod"
87
+ elif is_root && [ ! -d "/teamspace/studios/this_studio" ] && [ ! -d "/workspace" ]; then
88
+ BASE_DIR="/root"
89
+ ENV_NAME="vastai"
90
+ else
91
+ BASE_DIR="$HOME"
92
+ ENV_NAME="generic"
93
+ fi
94
 
95
+ COMFY_INSTALL_DIR="${BASE_DIR}/my_comfy_setup"
96
+ MODELS_DIR="${COMFY_INSTALL_DIR}/models"
 
 
 
97
 
98
+ log_info "Environment detected: $ENV_NAME"
99
+ log_info "Base directory: $BASE_DIR"
100
+ log_info "ComfyUI install directory: $COMFY_INSTALL_DIR"
101
+ log_info "Models directory: $MODELS_DIR"
102
+ }
103
+
104
+ # ============================================================================
105
+ # PERMISSION MANAGEMENT
106
+ # ============================================================================
107
+
108
+ setup_permissions() {
109
+ log_info "Setting up permissions..."
110
+
111
+ if is_root; then
112
+ SUDO_PREFIX=""
113
+ log_info "Running as root, no sudo needed"
114
+ elif command_exists sudo; then
115
+ SUDO_PREFIX="sudo "
116
+ log_info "Non-root user with sudo available"
117
+ else
118
+ SUDO_PREFIX=""
119
+ log_warning "Non-root user without sudo, some system operations may fail"
120
  fi
 
 
121
  }
122
 
123
+ # ============================================================================
124
+ # SYSTEM DEPENDENCIES
125
+ # ============================================================================
126
+
127
+ install_system_dependencies() {
128
+ log_info "Installing system dependencies..."
129
 
130
+ # Update package list
131
+ if command_exists apt-get; then
132
+ ${SUDO_PREFIX}apt-get update -qq || log_warning "Failed to update package list"
133
+
134
+ # Install basic dependencies
135
+ ${SUDO_PREFIX}apt-get install -y -qq python3 python3-pip git || {
136
+ log_error "Failed to install basic dependencies (python3, pip, git)"
137
+ exit 1
138
+ }
139
+
140
+ # Try to install aria2c
141
+ if ${SUDO_PREFIX}apt-get install -y -qq aria2 >/dev/null 2>&1; then
142
+ ARIA2C_AVAILABLE=true
143
+ log_info "aria2c installed successfully"
144
+ else
145
+ ARIA2C_AVAILABLE=false
146
+ log_info "aria2c installation failed, will use wget/curl as fallback"
147
+ fi
148
  else
149
+ log_warning "apt-get not available, skipping system package installation"
150
+ # Check if aria2c is already available
151
+ if command_exists aria2c; then
152
+ ARIA2C_AVAILABLE=true
153
+ log_info "aria2c already available"
154
+ fi
155
  fi
156
  }
157
 
158
+ # ============================================================================
159
+ # COMFY-CLI INSTALLATION
160
+ # ============================================================================
161
+
162
  install_comfy_cli() {
163
+ log_info "Installing comfy-cli..."
164
 
165
+ python3 -m pip install --upgrade comfy-cli || {
166
+ log_error "Failed to install comfy-cli"
167
+ exit 1
168
+ }
169
 
170
+ # Check if comfy is in PATH
171
+ if ! command_exists comfy; then
172
+ if [ -d "$HOME/.local/bin" ]; then
173
+ export PATH="$HOME/.local/bin:$PATH"
174
+ log_info "Added $HOME/.local/bin to PATH"
175
+ fi
176
+
177
+ if ! command_exists comfy; then
178
+ log_error "comfy command not found in PATH after installation"
179
+ exit 1
180
+ fi
181
  fi
182
 
183
+ log_info "comfy-cli version: $(comfy --version 2>/dev/null || echo 'unknown')"
184
  }
185
 
186
+ # ============================================================================
187
+ # COMFYUI CORE INSTALLATION
188
+ # ============================================================================
189
+
190
+ install_comfyui_core() {
191
+ log_info "Installing ComfyUI core..."
192
 
193
+ comfy --workspace "$COMFY_INSTALL_DIR" --skip-prompt install --nvidia || {
194
+ log_error "Failed to install ComfyUI core"
195
+ exit 1
196
+ }
197
 
198
+ log_info "ComfyUI core installed successfully"
199
  }
200
 
201
+ # ============================================================================
202
+ # DIRECTORY STRUCTURE
203
+ # ============================================================================
204
+
205
+ create_model_directories() {
206
+ log_info "Creating model directories..."
 
207
 
208
+ # Create model directories
209
+ for dir in "${MODEL_DIRS[@]}"; do
210
+ mkdir -p "$MODELS_DIR/$dir"
211
+ log_info "Created directory: $MODELS_DIR/$dir"
 
 
 
212
  done
213
+
214
+ # Ensure install directory exists for snapshot
215
+ mkdir -p "$COMFY_INSTALL_DIR"
216
  }
217
 
218
+ # ============================================================================
219
+ # CUSTOM NODES INSTALLATION
220
+ # ============================================================================
221
+
222
+ install_custom_nodes() {
223
+ log_info "Installing custom nodes..."
 
224
 
225
+ for node_url in "${CUSTOM_NODES[@]}"; do
226
+ log_info "Installing custom node: $node_url"
227
+ comfy --workspace "$COMFY_INSTALL_DIR" node install "$node_url" || {
228
+ log_warning "Failed to install custom node: $node_url"
229
+ }
230
  done
231
  }
232
 
233
+ # ============================================================================
234
+ # DOWNLOAD FUNCTIONS
235
+ # ============================================================================
236
+
237
+ add_civitai_token() {
238
+ local url="$1"
239
+ if [[ "$url" == *"civitai.com/api/download"* ]] && [[ "$url" != *"token="* ]]; then
240
+ echo "${url}&token=${CIVITAI_TOKEN}"
241
+ else
242
+ echo "$url"
243
+ fi
244
+ }
245
+
246
+ download_file() {
247
+ local url="$1"
248
+ local target_dir="$2"
249
+ local filename="$3"
250
 
251
+ # Add Civitai token if needed
252
+ url=$(add_civitai_token "$url")
253
 
254
+ local download_cmd=""
255
+ local success=false
256
+
257
+ # Try aria2c first
258
+ if $ARIA2C_AVAILABLE && command_exists aria2c; then
259
+ local aria_opts="-c -s 16 -x 16 -k 1M --console-log-level=warn --summary-interval=0"
260
 
261
+ if [ -n "$filename" ]; then
262
+ download_cmd="aria2c $aria_opts --dir=\"$target_dir\" --out=\"$filename\" \"$url\""
263
+ else
264
+ download_cmd="aria2c $aria_opts --dir=\"$target_dir\" --content-disposition=true \"$url\""
265
+ fi
266
 
267
+ if eval "$download_cmd" >/dev/null 2>&1; then
268
+ success=true
269
+ fi
270
+ fi
271
+
272
+ # Try wget if aria2c failed or unavailable
273
+ if ! $success && command_exists wget; then
274
+ local wget_opts="-q --show-progress -c"
275
+
276
+ if [ -n "$filename" ]; then
277
+ download_cmd="wget $wget_opts -O \"$target_dir/$filename\" \"$url\""
278
  else
279
+ download_cmd="wget $wget_opts --content-disposition -P \"$target_dir\" \"$url\""
280
+ fi
281
+
282
+ if eval "$download_cmd"; then
283
+ success=true
284
+ fi
285
+ fi
286
+
287
+ # Try curl as last resort
288
+ if ! $success && command_exists curl; then
289
+ log_warning "Using curl fallback for $url - filename handling may be less robust"
290
+
291
+ if [ -n "$filename" ]; then
292
+ download_cmd="curl -L -C - -o \"$target_dir/$filename\" \"$url\""
293
+ else
294
+ # For curl with content-disposition, it's more complex
295
+ # Try -J -O with --output-dir (if available) or fallback to simpler approach
296
+ if curl --help 2>/dev/null | grep -q "output-dir"; then
297
+ download_cmd="curl -L -J -O --output-dir \"$target_dir\" \"$url\""
298
  else
299
+ # Fallback: extract filename from URL or use generic name
300
+ local fallback_name
301
+ fallback_name=$(basename "$url" | cut -d'?' -f1)
302
+ [ -z "$fallback_name" ] && fallback_name="downloaded_file"
303
+ download_cmd="curl -L -C - -o \"$target_dir/$fallback_name\" \"$url\""
304
  fi
305
  fi
306
+
307
+ if eval "$download_cmd"; then
308
+ success=true
309
+ fi
310
+ fi
311
+
312
+ if ! $success; then
313
+ log_error "Failed to download: $url"
314
+ return 1
315
+ fi
316
+
317
+ return 0
318
+ }
319
+
320
+ # ============================================================================
321
+ # PARALLEL DOWNLOADS
322
+ # ============================================================================
323
+
324
+ download_all_files() {
325
+ log_info "Starting parallel downloads..."
326
 
327
+ local pids=()
328
+ local download_logs=()
329
+
330
+ for file_spec in "${DOWNLOAD_FILES[@]}"; do
331
+ IFS='|' read -r url target_subdir filename <<< "$file_spec"
332
+
333
+ local target_dir
334
+ if [ "$target_subdir" = "INSTALL_DIR" ]; then
335
+ target_dir="$COMFY_INSTALL_DIR"
336
+ else
337
+ target_dir="$MODELS_DIR/$target_subdir"
338
+ fi
339
+
340
+ # Note: Directory creation is handled by download tools automatically
341
+ # No need to mkdir -p here as it can cause issues
342
+
343
+ local display_name="${filename:-$(basename "$url" | cut -d'?' -f1)}"
344
+ log_info "Starting download: $display_name -> $target_dir"
345
+
346
+ # Create a temporary log file for this download
347
+ local log_file
348
+ log_file=$(mktemp)
349
+ download_logs+=("$log_file")
350
+
351
+ # Start download in background
352
+ (
353
+ if download_file "$url" "$target_dir" "$filename" >"$log_file" 2>&1; then
354
+ echo "SUCCESS: Downloaded $display_name" >> "$log_file"
355
+ else
356
+ echo "FAILED: Failed to download $display_name" >> "$log_file"
357
+ exit 1
358
+ fi
359
+ ) &
360
+
361
  pids+=($!)
362
  done
363
 
364
+ # Wait for all downloads to complete
365
+ local failed_count=0
366
+ for i in "${!pids[@]}"; do
367
+ local pid=${pids[$i]}
368
+ local log_file=${download_logs[$i]}
369
+
370
+ if wait "$pid"; then
371
+ log_info "Download completed successfully"
372
+ else
373
+ failed_count=$((failed_count + 1))
374
+ log_warning "Download failed - check logs"
375
+ fi
376
+
377
+ # Show download log
378
+ if [ -f "$log_file" ]; then
379
+ cat "$log_file" >&2
380
+ rm -f "$log_file"
381
  fi
382
  done
383
 
384
+ if [ $failed_count -gt 0 ]; then
385
+ log_warning "$failed_count downloads failed, but continuing..."
386
  else
387
+ log_info "All downloads completed successfully"
388
  fi
389
  }
390
 
391
+ # ============================================================================
392
+ # SNAPSHOT RESTORATION
393
+ # ============================================================================
394
+
395
  restore_snapshot() {
396
+ log_info "Restoring snapshot..."
397
 
398
+ local snapshot_file="$COMFY_INSTALL_DIR/snapshotBRABEX.json"
399
 
400
+ if [ -f "$snapshot_file" ]; then
401
+ if comfy --workspace "$COMFY_INSTALL_DIR" node restore-snapshot "$snapshot_file"; then
402
+ log_info "Snapshot restored successfully"
403
  else
404
+ log_warning "Failed to restore snapshot, ComfyUI will start without it"
405
  fi
406
  else
407
+ log_warning "Snapshot file not found: $snapshot_file"
408
  fi
409
  }
410
 
411
+ # ============================================================================
412
+ # COMFYUI LAUNCH
413
+ # ============================================================================
 
 
 
 
 
 
414
 
415
+ launch_comfyui() {
416
+ log_info "Launching ComfyUI on port 8818..."
417
+ log_info "ComfyUI will be accessible at: http://0.0.0.0:8818"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
418
 
419
+ # Launch ComfyUI
420
+ exec comfy --workspace "$COMFY_INSTALL_DIR" launch -- --fast --listen 0.0.0.0 --port 8818
421
  }
422
 
423
+ # ============================================================================
424
+ # MAIN EXECUTION
425
+ # ============================================================================
 
 
 
 
 
 
 
426
 
427
+ main() {
428
+ log_info "Starting ComfyUI automated setup..."
429
+ log_info "========================================"
430
 
431
+ # Step 1: Environment Detection
432
+ detect_environment
 
 
433
 
434
+ # Step 2: Permission Setup
435
+ setup_permissions
 
 
 
 
 
436
 
437
+ # Step 3: System Dependencies
438
+ install_system_dependencies
439
 
440
+ # Step 4: Install comfy-cli
441
+ install_comfy_cli
442
 
443
+ # Step 5: Install ComfyUI Core
444
+ install_comfyui_core
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
445
 
446
+ # Step 6: Create Directory Structure
447
+ create_model_directories
448
+
449
+ # Step 7: Install Custom Nodes
450
+ install_custom_nodes
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
451
 
452
+ # Step 8: Download Files in Parallel
453
+ download_all_files
454
 
455
+ # Step 9: Restore Snapshot
456
+ restore_snapshot
457
 
458
+ # Step 10: Launch ComfyUI
459
+ log_info "========================================"
460
+ log_info "Setup completed successfully!"
461
+ log_info "========================================"
462
  launch_comfyui
463
  }
464
 
465
+ # ============================================================================
466
+ # SCRIPT EXECUTION
467
+ # ============================================================================
 
 
 
 
 
 
468
 
469
+ # Trap to handle script interruption
470
+ trap 'log_error "Script interrupted"; exit 1' INT TERM
 
 
 
471
 
472
+ # Run main function
473
  main "$@"