From 6e58131add70a95f589a4d9a69c6ef1d13cb2908 Mon Sep 17 00:00:00 2001 From: Mister K <678459+kairin@users.noreply.github.com> Date: Fri, 2 May 2025 23:26:01 +0800 Subject: [PATCH 01/11] Add UV package manager support and installation instructions --- .github/workflows/uv-build.yml | 26 ++++++ CONTRIBUTING.md | 38 ++++++++ README.md | 29 ++++++ UV_MIGRATION.md | 83 +++++++++++++++++ convert_requirements_to_pyproject.py | 75 +++++++++++++++ install_with_uv.py | 132 +++++++++++++++++++++++++++ pyproject.toml | 13 +++ 7 files changed, 396 insertions(+) create mode 100644 .github/workflows/uv-build.yml create mode 100644 UV_MIGRATION.md create mode 100644 convert_requirements_to_pyproject.py create mode 100644 install_with_uv.py diff --git a/.github/workflows/uv-build.yml b/.github/workflows/uv-build.yml new file mode 100644 index 000000000..48e8a9af6 --- /dev/null +++ b/.github/workflows/uv-build.yml @@ -0,0 +1,26 @@ +name: Build and Test + +on: + push: + branches: [ main ] + pull_request: + branches: [ main ] + +jobs: + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + - name: Set up Python + uses: actions/setup-python@v4 + with: + python-version: '3.10' + - name: Install uv + run: | + curl -LsSf https://astral.sh/uv/install.sh | sh + echo "$HOME/.local/bin" >> $GITHUB_PATH + - name: Install dependencies + run: | + uv pip install -r requirements.txt + uv pip install -r requirements_advanced.txt + # Additional steps... diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 048f127e7..e55e09a6c 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -35,6 +35,44 @@ If you cannot find an existing issue that describes your bug or feature, create * Please refer to the article on [creating pull requests](https://github.com/comfyanonymous/ComfyUI/wiki/How-to-Contribute-Code) and contributing to this project. +## Development Environment Setup + +### Setting Up with UV (Recommended) + +*Added 2025-05-02 by kairin* + +We recommend using [UV](https://github.com/astral-sh/uv) for faster, more reliable package management: + +1. **Install UV**: + ```bash + curl -LsSf https://astral.sh/uv/install.sh | sh + source $HOME/.local/bin/env # For bash/zsh + ``` + +2. **Set up development environment**: + ```bash + git clone https://github.com/comfyanonymous/ComfyUI.git + cd ComfyUI + + # Create virtual environment + uv venv + source .venv/bin/activate # Linux/macOS + # or + .venv\Scripts\activate # Windows + + # Install dependencies + uv pip install -r requirements.txt + + # Install development dependencies + uv add --dev pytest black isort + ``` + +3. **Install in development mode**: + ```bash + uv pip install -e . + ``` + +### Working with Dependencies ## Thank You diff --git a/README.md b/README.md index 0f39cfce2..92e014a69 100644 --- a/README.md +++ b/README.md @@ -192,6 +192,35 @@ Put your SD checkpoints (the huge ckpt/safetensors files) in: models/checkpoints Put your VAE in: models/vae +## Installation Options + +### Option 1: Install with UV (Recommended) + +*Added 2025-05-02* + +[UV](https://github.com/astral-sh/uv) is a faster, more reliable Python package installer that we now recommend for ComfyUI. + +1. **Install UV**: + ```bash + curl -LsSf https://astral.sh/uv/install.sh | sh + source $HOME/.local/bin/env # For bash/zsh + ``` + +2. **Install ComfyUI dependencies**: + ```bash + # Create and activate virtual environment + uv venv + source .venv/bin/activate # Linux/macOS + # or + .venv\Scripts\activate # Windows + + # Install dependencies + uv pip install -r requirements.txt + ``` + +For detailed instructions on using UV with ComfyUI, see our [UV Migration Guide](UV_MIGRATION.md). + +### Option 2: Install with pip (Traditional) ### AMD GPUs (Linux only) AMD users can install rocm and pytorch with pip if you don't have it already installed, this is the command to install the stable version: diff --git a/UV_MIGRATION.md b/UV_MIGRATION.md new file mode 100644 index 000000000..cbf45cf23 --- /dev/null +++ b/UV_MIGRATION.md @@ -0,0 +1,83 @@ +# ComfyUI Migration to UV Package Manager + +## What is UV? + +[UV](https://github.com/astral-sh/uv) is a modern Python package installer and resolver written in Rust. It serves as a drop-in replacement for pip with significant performance improvements: + +- **Speed**: UV installs packages 10-100x faster than pip +- **Reliability**: Better dependency resolution to avoid conflicts +- **Compatibility**: Works with existing requirements.txt files +- **Modern**: Built with Rust for performance and safety + +## Why Migrate from pip to UV? + +- Faster installation of dependencies +- Improved virtual environment management +- Better handling of dependency conflicts +- Consistent installation experience across platforms +- Compatibility with existing pip workflows + +## Installation + +Install UV: + +```bash +# Install UV +curl -LsSf https://astral.sh/uv/install.sh | sh + +# Add to PATH (bash/zsh) +source $HOME/.local/bin/env + +# Or for fish shell +# source $HOME/.local/bin/env.fish +``` + +## Using UV with ComfyUI + +### Basic Usage + +```bash +# Create a virtual environment +uv venv +source .venv/bin/activate # On Linux/macOS +# .venv\Scripts\activate # On Windows + +# Install dependencies +uv pip install -r requirements.txt + +# Install advanced dependencies (if needed) +uv pip install -r requirements_advanced.txt +``` + +### UV Native Commands + +Instead of using the pip-compatible interface, you can use UV's native commands: + +```bash +# Install packages +uv add packagename + +# Install dev dependencies +uv add --dev pytest black + +# View dependency tree +uv tree + +# Update dependencies +uv sync +``` + +## Migration Tips + +1. UV is designed to be a drop-in replacement for pip, so most commands work similarly +2. Existing requirements.txt files are fully compatible +3. For best results, start with a fresh virtual environment +4. UV includes built-in lockfile support for reproducible environments + +## Troubleshooting + +If you encounter issues: + +- Ensure you have the latest version of UV: `uv self update` +- Try running with verbose output: `uv -vvv pip install -r requirements.txt` +- Check the [UV documentation](https://github.com/astral-sh/uv) for known issues diff --git a/convert_requirements_to_pyproject.py b/convert_requirements_to_pyproject.py new file mode 100644 index 000000000..74219ea0a --- /dev/null +++ b/convert_requirements_to_pyproject.py @@ -0,0 +1,75 @@ +#!/usr/bin/env python3 +""" +Convert requirements.txt to pyproject.toml dependencies +""" + +import re +import toml +from pathlib import Path + +def parse_requirements(file_path): + """Parse requirements file into a list of packages.""" + requirements = [] + + with open(file_path, 'r') as f: + for line in f: + line = line.strip() + if line and not line.startswith('#') and not line.startswith('-r'): + requirements.append(line) + + return requirements + +def main(): + project_root = Path(__file__).parent + pyproject_path = project_root / "pyproject.toml" + + # Parse requirements + requirements = parse_requirements(project_root / "requirements.txt") + + try: + advanced_requirements = parse_requirements(project_root / "requirements_advanced.txt") + except FileNotFoundError: + advanced_requirements = [] + + # Load existing pyproject.toml if it exists + if pyproject_path.exists(): + with open(pyproject_path, 'r') as f: + pyproject_data = toml.load(f) + else: + # Create basic structure + pyproject_data = { + "build-system": { + "requires": ["setuptools>=42", "wheel"], + "build-backend": "setuptools.build_meta" + }, + "project": { + "name": "ComfyUI", + "version": "0.1.0", + "description": "The most powerful and modular diffusion model GUI, api and backend with a graph/nodes interface.", + "readme": "README.md", + "requires-python": ">=3.8", + "dependencies": requirements + } + } + + # Update dependencies + if "project" not in pyproject_data: + pyproject_data["project"] = {} + + pyproject_data["project"]["dependencies"] = requirements + + # Add optional dependencies + if advanced_requirements: + if "optional-dependencies" not in pyproject_data["project"]: + pyproject_data["project"]["optional-dependencies"] = {} + + pyproject_data["project"]["optional-dependencies"]["advanced"] = advanced_requirements + + # Save updated pyproject.toml + with open(pyproject_path, 'w') as f: + toml.dump(pyproject_data, f) + + print(f"Updated {pyproject_path} with dependencies from requirements files") + +if __name__ == "__main__": + main() diff --git a/install_with_uv.py b/install_with_uv.py new file mode 100644 index 000000000..c7ed79864 --- /dev/null +++ b/install_with_uv.py @@ -0,0 +1,132 @@ +#!/usr/bin/env python3 +""" +ComfyUI Installation Script using UV +""" + +import os +import platform +import subprocess +import sys +import shutil +from pathlib import Path +import argparse +from datetime import datetime + +def check_python_version(): + """Check if Python version is supported.""" + if sys.version_info < (3, 8): + print("Python 3.8 or higher is required.") + sys.exit(1) + +def install_uv(): + """Install UV if not already installed.""" + if shutil.which("uv") is None: + print("Installing UV package manager...") + try: + if platform.system() == "Windows": + # For Windows, download and run the installer + subprocess.check_call( + ["powershell", "-Command", + "Invoke-WebRequest -Uri https://astral.sh/uv/install.ps1 -OutFile install.ps1; ./install.ps1"], + stdout=sys.stdout, stderr=sys.stderr + ) + else: + # For macOS and Linux + subprocess.check_call( + ["bash", "-c", "curl -LsSf https://astral.sh/uv/install.sh | sh"], + stdout=sys.stdout, stderr=sys.stderr + ) + print("UV installed successfully.") + except subprocess.CalledProcessError: + print("Failed to install UV. Please install it manually from https://github.com/astral-sh/uv") + sys.exit(1) + else: + print("UV is already installed.") + +def create_venv(): + """Create a virtual environment using UV.""" + print("Creating virtual environment...") + try: + subprocess.check_call( + ["uv", "venv", ".venv"], + stdout=sys.stdout, stderr=sys.stderr + ) + print("Virtual environment created successfully.") + except subprocess.CalledProcessError: + print("Failed to create virtual environment.") + sys.exit(1) + +def activate_venv(): + """Return the activation command for the virtual environment.""" + if platform.system() == "Windows": + return str(Path(".venv/Scripts/activate")) + return f"source {str(Path('.venv/bin/activate'))}" + +def install_requirements(args): + """Install ComfyUI requirements using UV.""" + print("Installing requirements...") + + # Basic requirements + try: + subprocess.check_call( + ["uv", "pip", "install", "-r", "requirements.txt"], + stdout=sys.stdout, stderr=sys.stderr + ) + print("Basic requirements installed successfully.") + except subprocess.CalledProcessError: + print("Failed to install basic requirements.") + sys.exit(1) + + # Advanced requirements if specified + if args.advanced: + try: + if os.path.exists("requirements_advanced.txt"): + subprocess.check_call( + ["uv", "pip", "install", "-r", "requirements_advanced.txt"], + stdout=sys.stdout, stderr=sys.stderr + ) + print("Advanced requirements installed successfully.") + else: + print("Advanced requirements file not found.") + except subprocess.CalledProcessError: + print("Failed to install advanced requirements.") + sys.exit(1) + + # GPU requirements if specified + if args.gpu: + print("Installing PyTorch with CUDA support...") + try: + subprocess.check_call( + ["uv", "pip", "install", "torch", "torchvision", "torchaudio", "--index-url", "https://download.pytorch.org/whl/cu118"], + stdout=sys.stdout, stderr=sys.stderr + ) + print("PyTorch with CUDA installed successfully.") + except subprocess.CalledProcessError: + print("Failed to install PyTorch with CUDA.") + sys.exit(1) + +def main(): + parser = argparse.ArgumentParser(description="Install ComfyUI with UV package manager") + parser.add_argument("--advanced", action="store_true", help="Install advanced requirements") + parser.add_argument("--gpu", action="store_true", help="Install PyTorch with CUDA support") + parser.add_argument("--no-venv", action="store_true", help="Skip virtual environment creation") + args = parser.parse_args() + + print(f"ComfyUI installation with UV started at {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}") + + check_python_version() + install_uv() + + if not args.no_venv: + create_venv() + print(f"To activate the virtual environment, run: {activate_venv()}") + + install_requirements(args) + + print("\nComfyUI installation completed successfully!") + if not args.no_venv: + print(f"Remember to activate the virtual environment with: {activate_venv()}") + print("To start ComfyUI, run: python main.py") + +if __name__ == "__main__": + main() diff --git a/pyproject.toml b/pyproject.toml index a9c028c7e..97420defc 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,11 @@ +[build-system] +requires = ["setuptools>=42", "wheel"] +build-backend = "setuptools.build_meta" + [project] name = "ComfyUI" version = "0.3.30" +description = "The most powerful and modular diffusion model GUI, api and backend with a graph/nodes interface." readme = "README.md" license = { file = "LICENSE" } requires-python = ">=3.9" @@ -10,6 +15,11 @@ homepage = "https://www.comfy.org/" repository = "https://github.com/comfyanonymous/ComfyUI" documentation = "https://docs.comfy.org/" +[project.optional-dependencies] +advanced = [ + # Include dependencies from requirements_advanced.txt here +] + [tool.ruff] lint.select = [ "N805", # invalid-first-argument-name-for-method @@ -22,3 +32,6 @@ lint.select = [ "F", ] exclude = ["*.ipynb"] + +[tool.uv] +# Add any uv-specific configurations here From 0b49a47b98bdae8d6dbcc59959d6fb44b9553ddb Mon Sep 17 00:00:00 2001 From: Mister K <678459+kairin@users.noreply.github.com> Date: Fri, 2 May 2025 23:39:23 +0800 Subject: [PATCH 02/11] Add UV environment setup and dependency management scripts --- UV-req-lock.txt | 2 + clean_venv.py | 111 ++++++++++++++++++++++++++++++++++++++ pyproject.toml | 24 ++++++++- requirements.txt | 12 +++++ update_dependencies_uv.py | 104 +++++++++++++++++++++++++++++++++++ uv_setup.sh | 45 ++++++++++++++++ 6 files changed, 297 insertions(+), 1 deletion(-) create mode 100644 UV-req-lock.txt create mode 100755 clean_venv.py create mode 100755 update_dependencies_uv.py create mode 100755 uv_setup.sh diff --git a/UV-req-lock.txt b/UV-req-lock.txt new file mode 100644 index 000000000..8cf3abeb0 --- /dev/null +++ b/UV-req-lock.txt @@ -0,0 +1,2 @@ +pip==24.0 +setuptools==65.5.0 diff --git a/clean_venv.py b/clean_venv.py new file mode 100755 index 000000000..e6e89ab1f --- /dev/null +++ b/clean_venv.py @@ -0,0 +1,111 @@ +#!/usr/bin/env python3 +""" +ComfyUI Virtual Environment Cleanup Script +Created: May 2, 2025 +""" + +import argparse +import os +import shutil +import sys +import platform +from pathlib import Path + +def deactivate_venv(): + """Attempt to deactivate any active virtual environment.""" + if "VIRTUAL_ENV" in os.environ: + print(f"Active virtual environment detected: {os.environ['VIRTUAL_ENV']}") + print("Attempting to deactivate...") + + # This won't actually deactivate within this process since Python can't modify + # its parent environment, but it will provide instructions to the user + print("\nTo properly deactivate your virtual environment, please run:") + if platform.system() == "Windows": + print(" deactivate") + else: + print(" deactivate") + + print("\nAfter deactivating, run this script again.") + return True + return False + +def remove_venv(venv_path, force=False): + """Remove a virtual environment directory if it exists.""" + path = Path(venv_path).expanduser().resolve() + + if not path.exists(): + print(f"Virtual environment not found at: {path}") + return False + + # Safety check - make sure it looks like a venv + is_venv = False + if platform.system() == "Windows": + is_venv = (path / "Scripts" / "python.exe").exists() + else: + is_venv = (path / "bin" / "python").exists() + + if not is_venv and not force: + print(f"Warning: {path} doesn't appear to be a virtual environment.") + print("Use --force to remove it anyway.") + return False + + try: + print(f"Removing virtual environment at: {path}") + shutil.rmtree(path) + print("โ Virtual environment removed successfully.") + return True + except Exception as e: + print(f"โ Error removing virtual environment: {e}") + if platform.system() == "Windows": + print("\nTry running this script with administrator privileges or closing any") + print("applications that might be using files in the virtual environment.") + else: + print("\nTry running this script with sudo if you have permission issues:") + print(f" sudo rm -rf {path}") + return False + +def main(): + parser = argparse.ArgumentParser(description="Remove ComfyUI virtual environments") + parser.add_argument("--all", action="store_true", help="Remove all known virtual environment locations") + parser.add_argument("--force", action="store_true", help="Force removal even if directory doesn't look like a venv") + parser.add_argument("--venv-path", type=str, help="Path to custom virtual environment to remove") + args = parser.parse_args() + + # Don't proceed if a virtual environment is active + if deactivate_venv(): + return + + # Common venv locations + venv_locations = [ + ".venv", # Default UV venv name + "venv", # Common alternative name + Path.home() / ".venvs" / "comfyui", # User-level venvs + ] + + if args.venv_path: + # Just remove the specified venv + remove_venv(args.venv_path, args.force) + elif args.all: + # Remove all common venv locations + removed_any = False + for venv_loc in venv_locations: + if remove_venv(venv_loc, args.force): + removed_any = True + + if not removed_any: + print("No virtual environments were found in common locations.") + else: + # Default: just remove .venv + if not remove_venv(".venv", args.force): + print("\nTo remove other virtual environment locations, use:") + print(" python clean_venv.py --all") + print(" python clean_venv.py --venv-path /path/to/venv") + + print("\n๐ Ready to create a new UV-based environment!") + print("Run the following commands to set up with UV:") + print(" ./uv_setup.sh") + print(" source .venv/bin/activate # On Linux/macOS") + print(" ./update_dependencies_uv.py --advanced --cuda --lock") + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/pyproject.toml b/pyproject.toml index 97420defc..5361562a0 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -34,4 +34,26 @@ lint.select = [ exclude = ["*.ipynb"] [tool.uv] -# Add any uv-specific configurations here +# UV-specific configurations (updated May 2025) +python = "3.11" +system = false +verbosity = 1 +threads = "auto" +no-binary = [] +only-binary = [] + +[tool.uv.dependencies] +# Core dependencies with modern 2025 versions +torch = { version = ">=2.3.0", source = "pytorch" } +torchvision = { version = ">=0.18.0", source = "pytorch" } +numpy = ">=2.0.0" +pillow = ">=10.0.0" +aiohttp = ">=3.9.0" +rich = ">=13.6.0" +tqdm = ">=4.66.0" +transformers = ">=4.38.0" +diffusers = ">=0.25.0" +safetensors = ">=0.4.0" + +[tool.uv.sources] +pytorch = { url = "https://download.pytorch.org/whl/cu121" } diff --git a/requirements.txt b/requirements.txt index 74a4ceb02..bec554918 100644 --- a/requirements.txt +++ b/requirements.txt @@ -17,6 +17,18 @@ Pillow scipy tqdm psutil +opencv-python>=4.8.0 +flash-attn>=2.3.0 +nvidia-cuda-runtime-cu12>=12.0.0 +nvidia-cuda-nvrtc-cu12>=12.0.0 +nvidia-cudnn-cu12>=8.9.0 +nvidia-cublas-cu12>=12.0.0 +nvidia-cufft-cu12>=11.0.0 +nvidia-curand-cu12>=10.3.0 +nvidia-cusolver-cu12>=11.4.0 +nvidia-cusparse-cu12>=12.1.0 +nvidia-nccl-cu12>=2.18.0 +nvidia-nvtx-cu12>=12.0.0 #non essential dependencies: kornia>=0.7.1 diff --git a/update_dependencies_uv.py b/update_dependencies_uv.py new file mode 100755 index 000000000..d488bc66b --- /dev/null +++ b/update_dependencies_uv.py @@ -0,0 +1,104 @@ +#!/usr/bin/env python3 +""" +ComfyUI Dependency Update Script using UV +Created: May 2, 2025 +""" + +import argparse +import os +import platform +import subprocess +import sys + +def check_uv_installed(): + """Check if UV is installed and install if missing.""" + try: + subprocess.run(["uv", "--version"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=True) + print("โ UV is installed") + return True + except (subprocess.CalledProcessError, FileNotFoundError): + print("โ ๏ธ UV not found. Installing...") + + if platform.system() == "Windows": + subprocess.run( + ["powershell", "-Command", "Invoke-WebRequest -Uri https://astral.sh/uv/install.ps1 -OutFile install.ps1; ./install.ps1"], + check=True + ) + else: + subprocess.run( + ["bash", "-c", "curl -LsSf https://astral.sh/uv/install.sh | sh"], + check=True + ) + + print("โ UV installed successfully") + return True + +def update_dependencies(args): + """Update dependencies using UV.""" + # Ensure we're in a virtual environment + if not os.environ.get("VIRTUAL_ENV") and not args.no_venv_check: + print("โ ๏ธ Not running in a virtual environment. Activate one before updating dependencies.") + print("๐ก Run: uv venv && source .venv/bin/activate (or .venv\\Scripts\\activate on Windows)") + if not args.force: + return False + + print("๐ฆ Updating dependencies using UV...") + + # Update base requirements + subprocess.run(["uv", "pip", "install", "--upgrade", "-r", "requirements.txt"], check=True) + print("โ Base dependencies updated") + + # Update advanced requirements if requested + if args.advanced: + subprocess.run(["uv", "pip", "install", "--upgrade", "-r", "requirements_advanced.txt"], check=True) + print("โ Advanced dependencies updated") + + # Update PyTorch with CUDA if requested + if args.cuda: + torch_version = "2.4.0" if args.latest else "2.3.0" + cuda_version = "12.1" if args.latest else "11.8" + + print(f"๐ Installing PyTorch {torch_version} with CUDA {cuda_version}...") + subprocess.run([ + "uv", "pip", "install", "--upgrade", + f"torch=={torch_version}", + f"torchvision>={torch_version}", + f"torchaudio>={torch_version}", + "--index-url", f"https://download.pytorch.org/whl/cu{cuda_version.replace('.', '')}" + ], check=True) + print("โ PyTorch updated with CUDA support") + + # Generate lockfile for reproducibility + if args.lock: + print("๐ Generating lockfile...") + subprocess.run(["uv", "pip", "freeze", ">", "UV-req-lock.txt"], shell=True, check=True) + print("โ Lockfile generated: UV-req-lock.txt") + + return True + +def main(): + parser = argparse.ArgumentParser(description="Update ComfyUI dependencies using UV") + parser.add_argument("--advanced", action="store_true", help="Update advanced dependencies") + parser.add_argument("--cuda", action="store_true", help="Update PyTorch with CUDA support") + parser.add_argument("--latest", action="store_true", help="Use latest versions (may be less stable)") + parser.add_argument("--lock", action="store_true", help="Generate lockfile after update") + parser.add_argument("--force", action="store_true", help="Force update even if not in venv") + parser.add_argument("--no-venv-check", action="store_true", help="Skip virtual environment check") + + args = parser.parse_args() + + print("ComfyUI Dependency Update") + print("========================") + + if not check_uv_installed(): + sys.exit(1) + + if update_dependencies(args): + print("\nโจ Dependencies updated successfully!") + print("\n๐ก To start ComfyUI, run: python main.py") + else: + print("\nโ Dependency update failed or was skipped") + sys.exit(1) + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/uv_setup.sh b/uv_setup.sh new file mode 100755 index 000000000..193d45044 --- /dev/null +++ b/uv_setup.sh @@ -0,0 +1,45 @@ +#!/bin/bash +# ComfyUI UV Environment Setup Script +# Created: May 2, 2025 + +# Set UV environment variables for better performance +export UV_CACHE_DIR="${HOME}/.cache/uv" +export UV_SYSTEM_PYTHON=false +export UV_DEFAULT_PYTHON=3.11 +export UV_THREADS=auto +export UV_VERBOSITY=1 + +# Create directory structure if needed +mkdir -p "${UV_CACHE_DIR}" + +echo "UV environment variables set:" +echo " UV_CACHE_DIR: ${UV_CACHE_DIR}" +echo " UV_DEFAULT_PYTHON: ${UV_DEFAULT_PYTHON}" +echo " UV_THREADS: ${UV_THREADS}" + +# Check if UV is installed +if ! command -v uv >/dev/null 2>&1; then + echo "UV not found. Installing..." + curl -LsSf https://astral.sh/uv/install.sh | sh + + # Add to PATH for this session + source $HOME/.local/bin/env +fi + +# Check for ComfyUI virtual environment +if [ ! -d ".venv" ]; then + echo "Creating virtual environment..." + uv venv + echo "Virtual environment created at .venv" +fi + +echo "" +echo "To activate the virtual environment, run:" +echo " source .venv/bin/activate # On Linux/macOS" +echo " .venv\\Scripts\\activate.bat # On Windows" +echo "" +echo "To install/update dependencies:" +echo " ./update_dependencies_uv.py --advanced --cuda --lock" +echo "" +echo "To start ComfyUI:" +echo " python main.py" \ No newline at end of file From 99885f4ae8a8d2c33d137a15ecddb200d4876b94 Mon Sep 17 00:00:00 2001 From: Mister K <678459+kairin@users.noreply.github.com> Date: Fri, 2 May 2025 23:45:27 +0800 Subject: [PATCH 03/11] Update pyproject.toml with enhanced dependencies and author information; add __init__.py for module initialization --- __init__.py | 7 ++++ pyproject.toml | 112 ++++++++++++++++++++++++++++++++++++++++--------- 2 files changed, 100 insertions(+), 19 deletions(-) create mode 100644 __init__.py diff --git a/__init__.py b/__init__.py new file mode 100644 index 000000000..fed5ec43b --- /dev/null +++ b/__init__.py @@ -0,0 +1,7 @@ +""" +ComfyUI - The most powerful and modular diffusion model GUI, API and backend. +""" + +from comfyui_version import __version__ + +__all__ = ["__version__"] \ No newline at end of file diff --git a/pyproject.toml b/pyproject.toml index 5361562a0..c2c9921c2 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,24 +1,87 @@ [build-system] -requires = ["setuptools>=42", "wheel"] +requires = ["setuptools>=61.0.0", "wheel", "uv"] build-backend = "setuptools.build_meta" [project] -name = "ComfyUI" +name = "comfyui" version = "0.3.30" description = "The most powerful and modular diffusion model GUI, api and backend with a graph/nodes interface." readme = "README.md" license = { file = "LICENSE" } requires-python = ">=3.9" +authors = [ + { name = "ComfyUI Team", email = "contact@comfy.org" } +] +classifiers = [ + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "License :: OSI Approved :: GNU General Public License v3 (GPLv3)", + "Operating System :: OS Independent", + "Topic :: Scientific/Engineering :: Artificial Intelligence", + "Topic :: Multimedia :: Graphics", +] + +dependencies = [ + "comfyui-frontend-package==1.18.5", + "comfyui-workflow-templates==0.1.3", + "torch>=2.0.0", + "torchsde", + "torchvision", + "torchaudio", + "numpy>=1.25.0", + "einops", + "transformers>=4.28.1", + "tokenizers>=0.13.3", + "sentencepiece", + "safetensors>=0.4.2", + "aiohttp>=3.11.8", + "yarl>=1.18.0", + "pyyaml", + "Pillow", + "scipy", + "tqdm", + "psutil", + "opencv-python>=4.8.0", + "flash-attn>=2.3.0", +] + +[project.optional-dependencies] +gpu = [ + "nvidia-cuda-runtime-cu12>=12.0.0", + "nvidia-cuda-nvrtc-cu12>=12.0.0", + "nvidia-cudnn-cu12>=8.9.0", + "nvidia-cublas-cu12>=12.0.0", + "nvidia-cufft-cu12>=11.0.0", + "nvidia-curand-cu12>=10.3.0", + "nvidia-cusolver-cu12>=11.4.0", + "nvidia-cusparse-cu12>=12.1.0", + "nvidia-nccl-cu12>=2.18.0", + "nvidia-nvtx-cu12>=12.0.0", +] +advanced = [ + "kornia>=0.7.1", + "spandrel", + "soundfile", + "av>=14.2.0", + "pydantic~=2.0", +] +dev = [ + "pytest>=7.0.0", + "black>=23.0.0", + "isort>=5.12.0", + "ruff>=0.0.272", +] [project.urls] homepage = "https://www.comfy.org/" repository = "https://github.com/comfyanonymous/ComfyUI" documentation = "https://docs.comfy.org/" +changelog = "https://github.com/comfyanonymous/ComfyUI/releases" -[project.optional-dependencies] -advanced = [ - # Include dependencies from requirements_advanced.txt here -] +[project.scripts] +comfyui = "comfyui.cli:main" [tool.ruff] lint.select = [ @@ -33,27 +96,38 @@ lint.select = [ ] exclude = ["*.ipynb"] +[tool.setuptools] +packages = ["comfyui"] +package-dir = {"comfyui" = "."} +include-package-data = true + +[tool.setuptools.package-data] +comfyui = [ + "models/**/*", + "output/**/*", + "temp/**/*", + "input/**/*", + "custom_nodes/**/*", + "*.py", + "api_server/**/*", + "app/**/*", + "comfy/**/*", + "comfy_extras/**/*", + "comfy_execution/**/*", + "utils/**/*", +] + [tool.uv] -# UV-specific configurations (updated May 2025) +# UV-specific configurations python = "3.11" system = false verbosity = 1 threads = "auto" -no-binary = [] -only-binary = [] +lockfile = "UV-req-lock.txt" [tool.uv.dependencies] -# Core dependencies with modern 2025 versions +# Core dependencies redirected to main project dependencies torch = { version = ">=2.3.0", source = "pytorch" } -torchvision = { version = ">=0.18.0", source = "pytorch" } -numpy = ">=2.0.0" -pillow = ">=10.0.0" -aiohttp = ">=3.9.0" -rich = ">=13.6.0" -tqdm = ">=4.66.0" -transformers = ">=4.38.0" -diffusers = ">=0.25.0" -safetensors = ">=0.4.0" [tool.uv.sources] pytorch = { url = "https://download.pytorch.org/whl/cu121" } From bc1cd2546224e097f26f18e8a9f31d600dfb6d2f Mon Sep 17 00:00:00 2001 From: Mister K <678459+kairin@users.noreply.github.com> Date: Fri, 2 May 2025 23:45:41 +0800 Subject: [PATCH 04/11] feat: add uv package --- cli.py | 122 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 122 insertions(+) create mode 100644 cli.py diff --git a/cli.py b/cli.py new file mode 100644 index 000000000..1acf8f43d --- /dev/null +++ b/cli.py @@ -0,0 +1,122 @@ +#!/usr/bin/env python3 +""" +ComfyUI Command Line Interface +""" + +import os +import sys +import argparse +from pathlib import Path + + +def add_comfyui_to_path(): + """Add the ComfyUI package directory to the Python path.""" + # In development mode, running from source directory + if os.path.exists(os.path.join(os.path.dirname(__file__), "main.py")): + comfyui_path = os.path.dirname(__file__) + else: + # In installed mode, comfyui module path + comfyui_path = os.path.dirname(os.path.abspath(__file__)) + + if comfyui_path not in sys.path: + sys.path.insert(0, comfyui_path) + + +def get_parser(): + """Create and return the argument parser for ComfyUI.""" + parser = argparse.ArgumentParser( + description="ComfyUI - A Stable Diffusion GUI with a graph/nodes interface" + ) + + parser.add_argument( + "--host", type=str, default="127.0.0.1", + help="The host to listen on (default: 127.0.0.1)" + ) + parser.add_argument( + "--port", type=int, default=8188, + help="The port to listen on (default: 8188)" + ) + parser.add_argument( + "--enable-cors-header", type=str, default=None, + help="Enable CORS by setting the Access-Control-Allow-Origin header (default: disabled)" + ) + parser.add_argument( + "--cuda-device", type=int, default=None, + help="The CUDA device to use for inference (default: auto)" + ) + parser.add_argument( + "--disable-cuda-malloc", action="store_true", + help="Force PyTorch to use standard memory allocator instead of cudaMallocAsync" + ) + parser.add_argument( + "--auto-launch", action="store_true", + help="Open the UI in default browser at startup" + ) + parser.add_argument( + "--output-directory", type=str, default=None, + help="Override the default output directory" + ) + parser.add_argument( + "--input-directory", type=str, default=None, + help="Override the default input directory" + ) + parser.add_argument( + "--verbose", action="store_true", + help="Enable verbose logging" + ) + + return parser + + +def main(): + """Main entry point for the ComfyUI application.""" + add_comfyui_to_path() + + parser = get_parser() + args, unknown = parser.parse_known_args() + + # Pass arguments to the original ComfyUI entry point + sys.argv = [sys.argv[0]] + unknown + + # Set environment variables based on arguments + if args.cuda_device is not None: + os.environ['CUDA_VISIBLE_DEVICES'] = str(args.cuda_device) + os.environ['HIP_VISIBLE_DEVICES'] = str(args.cuda_device) + + if args.disable_cuda_malloc: + os.environ['PYTORCH_CUDA_ALLOC_CONF'] = 'backend:cudaMalloc' + + # Import and run the main ComfyUI entry point + import main + + # Override command line arguments with the ones from our parser + import comfy.cli_args + comfy_args = comfy.cli_args.args + + # Set args from our parser to the ComfyUI args object + comfy_args.listen = args.host + comfy_args.port = args.port + comfy_args.enable_cors_header = args.enable_cors_header + comfy_args.cuda_device = args.cuda_device + comfy_args.disable_cuda_malloc = args.disable_cuda_malloc + comfy_args.auto_launch = args.auto_launch + + if args.output_directory: + comfy_args.output_directory = args.output_directory + if args.input_directory: + comfy_args.input_directory = args.input_directory + comfy_args.verbose = args.verbose + + # Start ComfyUI + asyncio_loop, _, start_all_func = main.start_comfyui() + try: + x = start_all_func() + asyncio_loop.run_until_complete(x) + except KeyboardInterrupt: + print("\nStopped server") + + main.cleanup_temp() + + +if __name__ == "__main__": + main() \ No newline at end of file From 4d1fa555fae86246809a12cff670ac4f676e7228 Mon Sep 17 00:00:00 2001 From: Mister K <678459+kairin@users.noreply.github.com> Date: Fri, 2 May 2025 23:46:22 +0800 Subject: [PATCH 05/11] feat: add UV setup script for ComfyUI installation and environment management --- uv_setup.py | 152 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 152 insertions(+) create mode 100644 uv_setup.py diff --git a/uv_setup.py b/uv_setup.py new file mode 100644 index 000000000..de3a2a7a8 --- /dev/null +++ b/uv_setup.py @@ -0,0 +1,152 @@ +#!/usr/bin/env python3 +""" +UV Setup Script for ComfyUI +""" + +import os +import sys +import subprocess +import argparse +from pathlib import Path + +def check_python_version(): + """Check Python version compatibility.""" + if sys.version_info < (3, 9): + print("ERROR: Python 3.9 or higher is required for ComfyUI.") + sys.exit(1) + +def is_uv_installed(): + """Check if UV is installed.""" + try: + subprocess.run(["uv", "--version"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=True) + return True + except (subprocess.SubprocessError, FileNotFoundError): + return False + +def install_uv(): + """Install UV package manager.""" + print("Installing UV package manager...") + try: + if sys.platform == "win32": + subprocess.run( + ["powershell", "-Command", "Invoke-WebRequest -Uri https://astral.sh/uv/install.ps1 -OutFile install.ps1; ./install.ps1"], + check=True + ) + else: # macOS or Linux + subprocess.run( + ["bash", "-c", "curl -LsSf https://astral.sh/uv/install.sh | sh"], + check=True + ) + + # Update PATH for this session + if sys.platform != "win32": + os.environ["PATH"] = f"{os.path.expanduser('~/.local/bin')}:{os.environ['PATH']}" + + print("โ UV installed successfully.") + return True + except subprocess.SubprocessError: + print("ERROR: UV installation failed.") + return False + +def create_venv(venv_path=".venv"): + """Create a new virtual environment using UV.""" + print(f"Creating virtual environment at {venv_path}...") + try: + subprocess.run(["uv", "venv", venv_path], check=True) + print(f"โ Virtual environment created at {venv_path}.") + return True + except subprocess.SubprocessError: + print("ERROR: Failed to create virtual environment.") + return False + +def install_comfyui(dev_mode=False, gpu=False, advanced=False, lock=False): + """Install ComfyUI using UV.""" + print("Installing ComfyUI...") + + cmd = ["uv", "pip", "install"] + + if dev_mode: + cmd.append("-e") + + # Build extras string + extras = [] + if gpu: + extras.append("gpu") + if advanced: + extras.append("advanced") + if dev_mode: + extras.append("dev") + + if extras: + cmd.append(f".{{{','.join(extras)}}}") + else: + cmd.append(".") + + if lock: + cmd.append("--lock") + + try: + subprocess.run(cmd, check=True) + print("โ ComfyUI installed successfully.") + return True + except subprocess.SubprocessError: + print("ERROR: Failed to install ComfyUI.") + return False + +def print_activation_instructions(venv_path=".venv"): + """Print instructions for activating the virtual environment.""" + print("\nTo activate the virtual environment:") + if sys.platform == "win32": + print(f" {venv_path}\\Scripts\\activate") + else: + print(f" source {venv_path}/bin/activate") + +def print_run_instructions(): + """Print instructions for running ComfyUI.""" + print("\nTo run ComfyUI:") + print(" comfyui") + print("\nOr with options:") + print(" comfyui --host 0.0.0.0 --port 8188 --auto-launch") + +def main(): + parser = argparse.ArgumentParser(description="Set up and install ComfyUI with UV") + parser.add_argument("--no-venv", action="store_true", help="Skip creating a virtual environment") + parser.add_argument("--venv-path", default=".venv", help="Path for the virtual environment (default: .venv)") + parser.add_argument("--dev", action="store_true", help="Install in development mode") + parser.add_argument("--gpu", action="store_true", help="Install with GPU/CUDA support") + parser.add_argument("--advanced", action="store_true", help="Install with advanced dependencies") + parser.add_argument("--lock", action="store_true", help="Generate lockfile during installation") + + args = parser.parse_args() + + # Checks + check_python_version() + + # Install UV if needed + if not is_uv_installed(): + if not install_uv(): + sys.exit(1) + + # Create virtual environment if requested + venv_created = False + if not args.no_venv: + venv_created = create_venv(args.venv_path) + + # Install ComfyUI + install_success = install_comfyui( + dev_mode=args.dev, + gpu=args.gpu, + advanced=args.advanced, + lock=args.lock + ) + + if install_success: + print("\nโ ComfyUI setup completed successfully!") + + if venv_created: + print_activation_instructions(args.venv_path) + + print_run_instructions() + +if __name__ == "__main__": + main() \ No newline at end of file From 5c08b23fa3e83200164164992309118d49ae0f34 Mon Sep 17 00:00:00 2001 From: Mister K <678459+kairin@users.noreply.github.com> Date: Fri, 2 May 2025 23:47:03 +0800 Subject: [PATCH 06/11] docs: update UV Migration Guide with new installation options and setup instructions --- UV_MIGRATION.md | 153 ++++++++++++++++++++++++++++++++---------------- 1 file changed, 101 insertions(+), 52 deletions(-) diff --git a/UV_MIGRATION.md b/UV_MIGRATION.md index cbf45cf23..279691954 100644 --- a/UV_MIGRATION.md +++ b/UV_MIGRATION.md @@ -1,83 +1,132 @@ -# ComfyUI Migration to UV Package Manager +# UV Migration Guide for ComfyUI + +This document provides instructions for migrating to UV-based package management for ComfyUI. ## What is UV? -[UV](https://github.com/astral-sh/uv) is a modern Python package installer and resolver written in Rust. It serves as a drop-in replacement for pip with significant performance improvements: +[UV](https://github.com/astral-sh/uv) is a modern, ultra-fast package manager for Python. It's up to 10-100x faster than pip and provides better dependency resolution, lockfile support, and caching. UV is designed to be a drop-in replacement for pip, but with better performance and reliability. -- **Speed**: UV installs packages 10-100x faster than pip -- **Reliability**: Better dependency resolution to avoid conflicts -- **Compatibility**: Works with existing requirements.txt files -- **Modern**: Built with Rust for performance and safety +## Installation Options -## Why Migrate from pip to UV? +### Option 1: Install ComfyUI as a UV Package (Recommended) -- Faster installation of dependencies -- Improved virtual environment management -- Better handling of dependency conflicts -- Consistent installation experience across platforms -- Compatibility with existing pip workflows - -## Installation - -Install UV: +This new approach treats ComfyUI as a proper Python package that can be installed using UV: ```bash -# Install UV +# Install UV if you don't have it already curl -LsSf https://astral.sh/uv/install.sh | sh -# Add to PATH (bash/zsh) -source $HOME/.local/bin/env +# Create virtual environment +uv venv .venv +source .venv/bin/activate # On Linux/macOS +# OR +.venv\Scripts\activate # On Windows -# Or for fish shell -# source $HOME/.local/bin/env.fish +# Install ComfyUI with all optional dependencies +uv pip install "comfyui[gpu,advanced]" + +# Or install from a specific version: +uv pip install "comfyui==0.3.30[gpu,advanced]" ``` -## Using UV with ComfyUI - -### Basic Usage +After installation, you can run ComfyUI simply by typing: ```bash -# Create a virtual environment -uv venv +comfyui +``` + +### Option 2: Use the Automated Setup Script + +If you have the ComfyUI source code, you can use our new setup script to handle everything: + +```bash +# Clone the repository +git clone https://github.com/comfyanonymous/ComfyUI.git +cd ComfyUI + +# Run the setup script +python uv_setup.py --gpu --advanced +``` + +### Option 3: Traditional Approach (Use UV as pip replacement) + +If you prefer the traditional approach but want to use UV: + +```bash +# Clone the repository +git clone https://github.com/comfyanonymous/ComfyUI.git +cd ComfyUI + +# Install UV if not already installed +curl -LsSf https://astral.sh/uv/install.sh | sh + +# Create virtual environment +uv venv .venv source .venv/bin/activate # On Linux/macOS -# .venv\Scripts\activate # On Windows +# OR +.venv\Scripts\activate # On Windows # Install dependencies uv pip install -r requirements.txt - -# Install advanced dependencies (if needed) -uv pip install -r requirements_advanced.txt ``` -### UV Native Commands +## Available Extras -Instead of using the pip-compatible interface, you can use UV's native commands: +When installing ComfyUI as a package, you can specify extras to include additional dependencies: + +- `gpu`: NVIDIA CUDA libraries for GPU acceleration +- `advanced`: Additional dependencies for advanced features +- `dev`: Development dependencies for contributing to ComfyUI + +Example: +```bash +uv pip install "comfyui[gpu,advanced,dev]" +``` + +## Command-Line Options + +When installed as a package, you can use the `comfyui` command with various options: ```bash -# Install packages -uv add packagename - -# Install dev dependencies -uv add --dev pytest black - -# View dependency tree -uv tree - -# Update dependencies -uv sync +comfyui --host 0.0.0.0 --port 8188 --auto-launch ``` -## Migration Tips +Common options: +- `--host`: The IP address to listen on (default: 127.0.0.1) +- `--port`: The port to listen on (default: 8188) +- `--auto-launch`: Automatically open ComfyUI in your default browser +- `--cuda-device`: Specify which CUDA device to use +- `--output-directory`: Override the default output directory +- `--input-directory`: Override the default input directory +- `--verbose`: Enable verbose logging -1. UV is designed to be a drop-in replacement for pip, so most commands work similarly -2. Existing requirements.txt files are fully compatible -3. For best results, start with a fresh virtual environment -4. UV includes built-in lockfile support for reproducible environments +## Migration Command Reference + +Below is a quick reference for migrating from pip commands to UV: + +| pip command | UV command | Description | +|-------------|------------|-------------| +| `pip install -r requirements.txt` | `uv pip install -r requirements.txt` | Install from requirements file | +| `pip install package` | `uv pip install package` or `uv add package` | Install a package | +| `pip install -e .` | `uv pip install -e .` | Install current directory in development mode | +| `pip freeze > requirements.txt` | `uv pip freeze > requirements.txt` | Create requirements file from installed packages | + +## Benefits of UV Package Approach + +Installing ComfyUI as a UV package offers several advantages: + +1. **Simplified Installation**: One command to install everything +2. **Dependency Management**: Faster resolution and better handling of complex dependencies +3. **Reproducible Environments**: Lock files ensure consistent environments across systems +4. **Command-Line Interface**: Run ComfyUI from anywhere using the `comfyui` command +5. **Optional Dependencies**: Install only what you need via extras +6. **Package Updates**: Easily update to new versions with `uv pip install -U comfyui` +7. **Development Mode**: Better integration with development workflows ## Troubleshooting -If you encounter issues: +- **Missing packages?** Try `uv pip install --upgrade -r requirements.txt` to reinstall all dependencies. +- **Package conflicts?** UV has improved dependency resolution, but if issues persist, try `uv pip install package --force-reinstall`. +- **Need to start fresh?** Run `python clean_venv.py` to remove your virtual environment and start over. -- Ensure you have the latest version of UV: `uv self update` -- Try running with verbose output: `uv -vvv pip install -r requirements.txt` -- Check the [UV documentation](https://github.com/astral-sh/uv) for known issues +For additional help, please visit our [Discord](https://comfy.org/discord) or [GitHub repository](https://github.com/comfyanonymous/ComfyUI). From a176b07001f5fce920e703f47ed6dd0952d40f1d Mon Sep 17 00:00:00 2001 From: Mister K <678459+kairin@users.noreply.github.com> Date: Fri, 2 May 2025 23:48:08 +0800 Subject: [PATCH 07/11] refactor: simplify UV setup script by removing environment variable settings and virtual environment checks --- uv_setup.sh | 49 +++++++++---------------------------------------- 1 file changed, 9 insertions(+), 40 deletions(-) diff --git a/uv_setup.sh b/uv_setup.sh index 193d45044..692f8705d 100755 --- a/uv_setup.sh +++ b/uv_setup.sh @@ -1,45 +1,14 @@ #!/bin/bash -# ComfyUI UV Environment Setup Script -# Created: May 2, 2025 +# ComfyUI UV Setup Script -# Set UV environment variables for better performance -export UV_CACHE_DIR="${HOME}/.cache/uv" -export UV_SYSTEM_PYTHON=false -export UV_DEFAULT_PYTHON=3.11 -export UV_THREADS=auto -export UV_VERBOSITY=1 - -# Create directory structure if needed -mkdir -p "${UV_CACHE_DIR}" - -echo "UV environment variables set:" -echo " UV_CACHE_DIR: ${UV_CACHE_DIR}" -echo " UV_DEFAULT_PYTHON: ${UV_DEFAULT_PYTHON}" -echo " UV_THREADS: ${UV_THREADS}" - -# Check if UV is installed -if ! command -v uv >/dev/null 2>&1; then - echo "UV not found. Installing..." - curl -LsSf https://astral.sh/uv/install.sh | sh - - # Add to PATH for this session - source $HOME/.local/bin/env +# Check if Python is available +if ! command -v python3 &> /dev/null; then + echo "Python 3 is required but not found. Please install Python 3.9+ first." + exit 1 fi -# Check for ComfyUI virtual environment -if [ ! -d ".venv" ]; then - echo "Creating virtual environment..." - uv venv - echo "Virtual environment created at .venv" -fi +# Make Python script executable +chmod +x ./uv_setup.py -echo "" -echo "To activate the virtual environment, run:" -echo " source .venv/bin/activate # On Linux/macOS" -echo " .venv\\Scripts\\activate.bat # On Windows" -echo "" -echo "To install/update dependencies:" -echo " ./update_dependencies_uv.py --advanced --cuda --lock" -echo "" -echo "To start ComfyUI:" -echo " python main.py" \ No newline at end of file +# Run the Python setup script with passed arguments +python3 ./uv_setup.py "$@" \ No newline at end of file From 74e61a1bce912fe9719efeb9e03415e11832b4a6 Mon Sep 17 00:00:00 2001 From: Mister K <678459+kairin@users.noreply.github.com> Date: Fri, 2 May 2025 23:48:16 +0800 Subject: [PATCH 08/11] refactor: enhance dependency update script with improved UV installation checks and error handling --- update_dependencies_uv.py | 157 ++++++++++++++++++++------------------ 1 file changed, 82 insertions(+), 75 deletions(-) diff --git a/update_dependencies_uv.py b/update_dependencies_uv.py index d488bc66b..ebd2a2101 100755 --- a/update_dependencies_uv.py +++ b/update_dependencies_uv.py @@ -1,103 +1,110 @@ #!/usr/bin/env python3 """ -ComfyUI Dependency Update Script using UV -Created: May 2, 2025 +Update dependencies for ComfyUI using UV """ -import argparse import os -import platform -import subprocess import sys +import subprocess +import argparse +from pathlib import Path def check_uv_installed(): - """Check if UV is installed and install if missing.""" + """Check if UV is installed and install it if not.""" try: subprocess.run(["uv", "--version"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=True) - print("โ UV is installed") - return True - except (subprocess.CalledProcessError, FileNotFoundError): - print("โ ๏ธ UV not found. Installing...") - - if platform.system() == "Windows": - subprocess.run( - ["powershell", "-Command", "Invoke-WebRequest -Uri https://astral.sh/uv/install.ps1 -OutFile install.ps1; ./install.ps1"], - check=True - ) - else: - subprocess.run( - ["bash", "-c", "curl -LsSf https://astral.sh/uv/install.sh | sh"], - check=True - ) - - print("โ UV installed successfully") return True + except (subprocess.SubprocessError, FileNotFoundError): + print("UV not found. Installing UV...") + try: + if sys.platform == "win32": + subprocess.run( + ["powershell", "-Command", "Invoke-WebRequest -Uri https://astral.sh/uv/install.ps1 -OutFile install.ps1; ./install.ps1"], + check=True + ) + else: # macOS or Linux + subprocess.run( + ["bash", "-c", "curl -LsSf https://astral.sh/uv/install.sh | sh"], + check=True + ) + + # Update PATH for this session + if sys.platform != "win32": + os.environ["PATH"] = f"{os.path.expanduser('~/.local/bin')}:{os.environ['PATH']}" + + print("UV installed successfully.") + return True + except subprocess.SubprocessError: + print("Failed to install UV. Please install manually from https://github.com/astral-sh/uv") + return False -def update_dependencies(args): +def update_dependencies(advanced=False, cuda=False, lock=False): """Update dependencies using UV.""" - # Ensure we're in a virtual environment - if not os.environ.get("VIRTUAL_ENV") and not args.no_venv_check: - print("โ ๏ธ Not running in a virtual environment. Activate one before updating dependencies.") - print("๐ก Run: uv venv && source .venv/bin/activate (or .venv\\Scripts\\activate on Windows)") - if not args.force: + if not check_uv_installed(): + return False + + print("Updating dependencies...") + + # Base dependencies + try: + cmd = ["uv", "pip", "install", "--upgrade", "-r", "requirements.txt"] + if lock: + cmd.append("--lock") + + subprocess.run(cmd, check=True) + print("โ Base dependencies updated successfully.") + except subprocess.SubprocessError: + print("Failed to update base dependencies.") + return False + + # Advanced dependencies if requested + if advanced: + try: + if os.path.exists("requirements_advanced.txt"): + cmd = ["uv", "pip", "install", "--upgrade", "-r", "requirements_advanced.txt"] + if lock: + cmd.append("--lock") + + subprocess.run(cmd, check=True) + print("โ Advanced dependencies updated successfully.") + else: + print("Advanced requirements file not found.") + except subprocess.SubprocessError: + print("Failed to update advanced dependencies.") return False - print("๐ฆ Updating dependencies using UV...") - - # Update base requirements - subprocess.run(["uv", "pip", "install", "--upgrade", "-r", "requirements.txt"], check=True) - print("โ Base dependencies updated") - - # Update advanced requirements if requested - if args.advanced: - subprocess.run(["uv", "pip", "install", "--upgrade", "-r", "requirements_advanced.txt"], check=True) - print("โ Advanced dependencies updated") - - # Update PyTorch with CUDA if requested - if args.cuda: - torch_version = "2.4.0" if args.latest else "2.3.0" - cuda_version = "12.1" if args.latest else "11.8" + # CUDA dependencies if requested + if cuda: + print("Updating CUDA dependencies...") + extras = ["gpu"] + if advanced: + extras.append("advanced") - print(f"๐ Installing PyTorch {torch_version} with CUDA {cuda_version}...") - subprocess.run([ - "uv", "pip", "install", "--upgrade", - f"torch=={torch_version}", - f"torchvision>={torch_version}", - f"torchaudio>={torch_version}", - "--index-url", f"https://download.pytorch.org/whl/cu{cuda_version.replace('.', '')}" - ], check=True) - print("โ PyTorch updated with CUDA support") - - # Generate lockfile for reproducibility - if args.lock: - print("๐ Generating lockfile...") - subprocess.run(["uv", "pip", "freeze", ">", "UV-req-lock.txt"], shell=True, check=True) - print("โ Lockfile generated: UV-req-lock.txt") + try: + cmd = ["uv", "pip", "install", "--upgrade", f".{{{','.join(extras)}}}"] + if lock: + cmd.append("--lock") + + subprocess.run(cmd, check=True) + print("โ CUDA dependencies updated successfully.") + except subprocess.SubprocessError: + print("Failed to update CUDA dependencies.") + return False return True def main(): - parser = argparse.ArgumentParser(description="Update ComfyUI dependencies using UV") + parser = argparse.ArgumentParser(description="Update ComfyUI dependencies with UV") parser.add_argument("--advanced", action="store_true", help="Update advanced dependencies") - parser.add_argument("--cuda", action="store_true", help="Update PyTorch with CUDA support") - parser.add_argument("--latest", action="store_true", help="Use latest versions (may be less stable)") - parser.add_argument("--lock", action="store_true", help="Generate lockfile after update") - parser.add_argument("--force", action="store_true", help="Force update even if not in venv") - parser.add_argument("--no-venv-check", action="store_true", help="Skip virtual environment check") + parser.add_argument("--cuda", action="store_true", help="Update CUDA dependencies") + parser.add_argument("--lock", action="store_true", help="Generate lockfile during update") args = parser.parse_args() - print("ComfyUI Dependency Update") - print("========================") - - if not check_uv_installed(): - sys.exit(1) - - if update_dependencies(args): - print("\nโจ Dependencies updated successfully!") - print("\n๐ก To start ComfyUI, run: python main.py") + if update_dependencies(args.advanced, args.cuda, args.lock): + print("\nโ All dependencies updated successfully!") else: - print("\nโ Dependency update failed or was skipped") + print("\nโ Failed to update some dependencies.") sys.exit(1) if __name__ == "__main__": From 219ee6a92338c510f5722d871ded01d7425f5c1d Mon Sep 17 00:00:00 2001 From: Mister K <678459+kairin@users.noreply.github.com> Date: Fri, 2 May 2025 23:57:47 +0800 Subject: [PATCH 09/11] docs: add comprehensive installation and user guide for ComfyUI --- README.md | 442 +++++-------------------------------------- docs/INSTALL.md | 0 docs/UV_PACKAGE.md | 0 docs/installation.md | 162 ++++++++++++++++ docs/user-guide.md | 194 +++++++++++++++++++ 5 files changed, 402 insertions(+), 396 deletions(-) create mode 100644 docs/INSTALL.md create mode 100644 docs/UV_PACKAGE.md create mode 100644 docs/installation.md create mode 100644 docs/user-guide.md diff --git a/README.md b/README.md index 92e014a69..4234582f6 100644 --- a/README.md +++ b/README.md @@ -1,424 +1,74 @@