File size: 11,138 Bytes
79327b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
import os
import sys
import subprocess
import zipfile
from huggingface_hub import hf_hub_download
from huggingface_hub.utils import (
    RepositoryNotFoundError,
    EntryNotFoundError,
    HfHubHTTPError,
    LocalEntryNotFoundError
)

def run_command(command):
    """Run a shell command and print its output"""
    process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True)
    for line in process.stdout:
        print(line, end='')
    process.wait()
    return process.returncode

def install_comfyui():
    """First-time installation of ComfyUI and models to Google Drive"""
    # Mount Google Drive
    print("Mounting Google Drive...")
    from google.colab import drive
    drive.mount('/content/drive')
    
    # Create ComfyUI directory in Google Drive
    COMFYUI_DRIVE_PATH = "/content/drive/MyDrive/ComfyUI"
    os.makedirs(COMFYUI_DRIVE_PATH, exist_ok=True)
    
    # Clone ComfyUI repository
    print("\nCloning ComfyUI repository...")
    run_command("git clone https://github.com/comfyanonymous/ComfyUI /content/ComfyUI")
    
    # Create and activate virtual environment
    print("\nSetting up virtual environment...")
    run_command("cd /content/ComfyUI && python -m venv venv")
    run_command("source /content/ComfyUI/venv/bin/activate && pip install --upgrade pip")
    
    # Install PyTorch and dependencies
    print("\nInstalling PyTorch and dependencies...")
    run_command("source /content/ComfyUI/venv/bin/activate && pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu121")
    
    # Install additional packages
    print("\nInstalling additional packages...")
    packages = [
        "insightface", "onnxruntime-gpu", "wheel", "setuptools", "packaging", "ninja",
        "accelerate", "diffusers", "transformers", "mediapipe>=0.10.8", "huggingface-hub",
        "omegaconf", "einops", "opencv-python", "face-alignment", "decord",
        "ffmpeg-python>=0.2.0", "safetensors", "soundfile", "pytorch-lightning",
        "deepspeed", "flash-attn", "triton==3.2.0"
    ]
    
    for package in packages:
        run_command(f"source /content/ComfyUI/venv/bin/activate && pip install {package}")
    
    # Install requirements.txt
    run_command("source /content/ComfyUI/venv/bin/activate && pip install -r /content/ComfyUI/requirements.txt")
    
    # Install SageAttention
    print("\nInstalling SageAttention...")
    run_command("cd /content && git clone https://github.com/thu-ml/SageAttention")
    run_command("cd /content/SageAttention && export MAX_JOBS=4 && python setup.py install")
    
    # Create model directories
    print("\nCreating model directories...")
    model_dirs = ["checkpoints", "controlnet", "clip", "vae", "loras"]
    for dir_name in model_dirs:
        os.makedirs(os.path.join(COMFYUI_DRIVE_PATH, "models", dir_name), exist_ok=True)
    
    # Download models
    print("\nDownloading models...")
    BASE_DOWNLOAD_DIR = os.path.join(COMFYUI_DRIVE_PATH, "models")
    
    def download_and_process_item(repo_id, local_dir, filename, extract_and_delete=False, repo_type=None):
        try:
            print(f"Downloading {filename}...")
            file_path = hf_hub_download(
                repo_id=repo_id,
                filename=filename,
                repo_type=repo_type,
                local_dir=local_dir
            )
            
            if extract_and_delete and filename.endswith('.zip'):
                print(f"Extracting {filename}...")
                with zipfile.ZipFile(file_path, 'r') as zip_ref:
                    zip_ref.extractall(local_dir)
                os.remove(file_path)
                print(f"Extracted and removed {filename}")
            
            return True
        except Exception as e:
            print(f"Error downloading {filename}: {str(e)}")
            return False
    
    # Download tasks
    flux_dev_tasks = [
        # ControlNet models
        {"repo_id": "simwalo/FluxDevFP8", "repo_type": "dataset", "filename": "Flux-Union-Pro2.safetensors", "local_dir": os.path.join(BASE_DOWNLOAD_DIR, "controlnet")},
        {"repo_id": "simwalo/FluxDevFP8", "repo_type": "dataset", "filename": "Flux1-controlnet-upscaler-Jasperai-fp8.safetensors", "local_dir": os.path.join(BASE_DOWNLOAD_DIR, "controlnet")},
        # CLIP models
        {"repo_id": "simwalo/FluxDevFP8", "repo_type": "dataset", "filename": "clip_l.safetensors", "local_dir": os.path.join(BASE_DOWNLOAD_DIR, "clip")},
        {"repo_id": "simwalo/FluxDevFP8", "repo_type": "dataset", "filename": "ViT-L-14-TEXT-detail-improved-hiT-GmP-TE-only-HF.safetensors", "local_dir": os.path.join(BASE_DOWNLOAD_DIR, "clip")},
        # VAE models
        {"repo_id": "simwalo/FluxDevFP8", "repo_type": "dataset", "filename": "ae.safetensors", "local_dir": os.path.join(BASE_DOWNLOAD_DIR, "vae")},
        # LoRA models
        {"repo_id": "simwalo/FluxDevFP8", "repo_type": "dataset", "filename": "comfyui_portrait_lora64.safetensors", "local_dir": os.path.join(BASE_DOWNLOAD_DIR, "loras")},
        {"repo_id": "simwalo/FluxDevFP8", "repo_type": "dataset", "filename": "Maya_Lora_v1_000002500.safetensors", "local_dir": os.path.join(BASE_DOWNLOAD_DIR, "loras")},
        {"repo_id": "simwalo/FluxDevFP8", "repo_type": "dataset", "filename": "more_details.safetensors", "local_dir": os.path.join(BASE_DOWNLOAD_DIR, "loras")},
        {"repo_id": "simwalo/FluxDevFP8", "repo_type": "dataset", "filename": "FameGrid_Bold_SDXL_V1.safetensors", "local_dir": os.path.join(BASE_DOWNLOAD_DIR, "loras")},
        # Checkpoints
        {"repo_id": "simwalo/FluxDevFP8", "repo_type": "dataset", "filename": "epicrealism_naturalSinRC1VAE.safetensors", "local_dir": os.path.join(BASE_DOWNLOAD_DIR, "checkpoints")},
        {"repo_id": "simwalo/FluxDevFP8", "repo_type": "dataset", "filename": "epicrealism_pureEvolutionV3.safetensors", "local_dir": os.path.join(BASE_DOWNLOAD_DIR, "checkpoints")},
        {"repo_id": "simwalo/FluxDevFP8", "repo_type": "dataset", "filename": "epicrealismXL_vxviLastfameRealism.safetensors", "local_dir": os.path.join(BASE_DOWNLOAD_DIR, "checkpoints")}
    ]
    
    wanskyreels_tasks = [
        {"repo_id": "simwalo/WanSkyReelsFP8", "repo_type": "dataset", "filename": "wan2.1-fp8.safetensors", "local_dir": os.path.join(BASE_DOWNLOAD_DIR, "checkpoints")}
    ]
    
    custom_nodes_tasks = [
        {"repo_id": "simwalo/custom_nodes", "repo_type": "dataset", "filename": "PersonMaskUltraV2.zip", "local_dir": os.path.join(COMFYUI_DRIVE_PATH, "custom_nodes"), "extract_and_delete": True},
        {"repo_id": "simwalo/custom_nodes", "repo_type": "dataset", "filename": "insightface.zip", "local_dir": os.path.join(COMFYUI_DRIVE_PATH, "custom_nodes"), "extract_and_delete": True},
        {"repo_id": "simwalo/custom_nodes", "repo_type": "dataset", "filename": "liveportrait.zip", "local_dir": os.path.join(COMFYUI_DRIVE_PATH, "custom_nodes"), "extract_and_delete": True},
        {"repo_id": "simwalo/custom_nodes", "repo_type": "dataset", "filename": "rembg.zip", "local_dir": os.path.join(COMFYUI_DRIVE_PATH, "custom_nodes"), "extract_and_delete": True},
        {"repo_id": "simwalo/custom_nodes", "repo_type": "dataset", "filename": "LLM.zip", "local_dir": os.path.join(COMFYUI_DRIVE_PATH, "custom_nodes"), "extract_and_delete": True},
        {"repo_id": "simwalo/custom_nodes", "repo_type": "dataset", "filename": "sams.zip", "local_dir": os.path.join(COMFYUI_DRIVE_PATH, "custom_nodes"), "extract_and_delete": True},
        {"repo_id": "simwalo/custom_nodes", "repo_type": "dataset", "filename": "ComfyUI-LatentSyncWrapper.zip", "local_dir": os.path.join(COMFYUI_DRIVE_PATH, "custom_nodes"), "extract_and_delete": True}
    ]
    
    # Download all models
    for task in flux_dev_tasks + wanskyreels_tasks + custom_nodes_tasks:
        download_and_process_item(**task)
    
    # Copy ComfyUI to Google Drive
    print("\nCopying ComfyUI to Google Drive...")
    run_command(f"cp -r /content/ComfyUI/* {COMFYUI_DRIVE_PATH}/")
    
    print("\nInstallation complete! You can now use the startup function to run ComfyUI.")

def start_comfyui():
    """Start ComfyUI using the installation from Google Drive"""
    # Mount Google Drive
    print("Mounting Google Drive...")
    from google.colab import drive
    drive.mount('/content/drive')
    
    # Set paths
    COMFYUI_DRIVE_PATH = "/content/drive/MyDrive/ComfyUI"
    COMFYUI_LOCAL_PATH = "/content/ComfyUI"
    
    # Create local directory
    os.makedirs(COMFYUI_LOCAL_PATH, exist_ok=True)
    
    # Copy ComfyUI from Drive to local
    print("\nCopying ComfyUI from Google Drive...")
    run_command(f"cp -r {COMFYUI_DRIVE_PATH}/* {COMFYUI_LOCAL_PATH}/")
    
    # Create and activate virtual environment
    print("\nSetting up virtual environment...")
    run_command(f"cd {COMFYUI_LOCAL_PATH} && python -m venv venv")
    run_command(f"source {COMFYUI_LOCAL_PATH}/venv/bin/activate && pip install --upgrade pip")
    
    # Install PyTorch and dependencies
    print("\nInstalling PyTorch and dependencies...")
    run_command(f"source {COMFYUI_LOCAL_PATH}/venv/bin/activate && pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu121")
    
    # Install additional packages
    print("\nInstalling additional packages...")
    packages = [
        "insightface", "onnxruntime-gpu", "wheel", "setuptools", "packaging", "ninja",
        "accelerate", "diffusers", "transformers", "mediapipe>=0.10.8", "huggingface-hub",
        "omegaconf", "einops", "opencv-python", "face-alignment", "decord",
        "ffmpeg-python>=0.2.0", "safetensors", "soundfile", "pytorch-lightning",
        "deepspeed", "flash-attn", "triton==3.2.0"
    ]
    
    for package in packages:
        run_command(f"source {COMFYUI_LOCAL_PATH}/venv/bin/activate && pip install {package}")
    
    # Install requirements.txt
    run_command(f"source {COMFYUI_LOCAL_PATH}/venv/bin/activate && pip install -r {COMFYUI_LOCAL_PATH}/requirements.txt")
    
    # Install SageAttention
    print("\nInstalling SageAttention...")
    run_command("cd /content && git clone https://github.com/thu-ml/SageAttention")
    run_command("cd /content/SageAttention && export MAX_JOBS=4 && python setup.py install")
    
    # Start ComfyUI
    print("\nStarting ComfyUI...")
    run_command(f"cd {COMFYUI_LOCAL_PATH} && source venv/bin/activate && python main.py --fast --use-pytorch-cross-attention --listen")

if __name__ == "__main__":
    print("ComfyUI Google Colab Helper")
    print("1. First-time installation (saves to Google Drive)")
    print("2. Quick startup (uses existing installation from Google Drive)")
    
    choice = input("Enter your choice (1 or 2): ")
    
    if choice == "1":
        install_comfyui()
    elif choice == "2":
        start_comfyui()
    else:
        print("Invalid choice. Please enter 1 or 2.")