Path: blob/master/misc/direct/v1.3.2/launch_utils_org.py
3275 views
# this scripts installs necessary requirements and launches main program in webui.py1import subprocess2import os3import sys4import importlib.util5import platform6import json7from functools import lru_cache89from modules import cmd_args10from modules.paths_internal import script_path, extensions_dir1112args, _ = cmd_args.parser.parse_known_args()1314python = sys.executable15git = os.environ.get('GIT', "git")16index_url = os.environ.get('INDEX_URL', "")17dir_repos = "repositories"1819# Whether to default to printing command output20default_command_live = (os.environ.get('WEBUI_LAUNCH_LIVE_OUTPUT') == "1")2122if 'GRADIO_ANALYTICS_ENABLED' not in os.environ:23os.environ['GRADIO_ANALYTICS_ENABLED'] = 'False'242526def check_python_version():27is_windows = platform.system() == "Windows"28major = sys.version_info.major29minor = sys.version_info.minor30micro = sys.version_info.micro3132if is_windows:33supported_minors = [10]34else:35supported_minors = [7, 8, 9, 10, 11]3637if not (major == 3 and minor in supported_minors):38import modules.errors3940modules.errors.print_error_explanation(f"""41INCOMPATIBLE PYTHON VERSION4243This program is tested with 3.10.6 Python, but you have {major}.{minor}.{micro}.44If you encounter an error with "RuntimeError: Couldn't install torch." message,45or any other error regarding unsuccessful package (library) installation,46please downgrade (or upgrade) to the latest version of 3.10 Python47and delete current Python and "venv" folder in WebUI's directory.4849You can download 3.10 Python from here: https://www.python.org/downloads/release/python-3106/5051{"Alternatively, use a binary release of WebUI: https://github.com/AUTOMATIC1111/stable-diffusion-webui/releases" if is_windows else ""}5253Use --skip-python-version-check to suppress this warning.54""")555657@lru_cache()58def commit_hash():59try:60return subprocess.check_output([git, "rev-parse", "HEAD"], shell=False, encoding='utf8').strip()61except Exception:62return "<none>"636465@lru_cache()66def git_tag():67try:68return subprocess.check_output([git, "describe", "--tags"], shell=False, encoding='utf8').strip()69except Exception:70return "<none>"717273def run(command, desc=None, errdesc=None, custom_env=None, live: bool = default_command_live) -> str:74if desc is not None:75print(desc)7677run_kwargs = {78"args": command,79"shell": True,80"env": os.environ if custom_env is None else custom_env,81"encoding": 'utf8',82"errors": 'ignore',83}8485if not live:86run_kwargs["stdout"] = run_kwargs["stderr"] = subprocess.PIPE8788result = subprocess.run(**run_kwargs)8990if result.returncode != 0:91error_bits = [92f"{errdesc or 'Error running command'}.",93f"Command: {command}",94f"Error code: {result.returncode}",95]96if result.stdout:97error_bits.append(f"stdout: {result.stdout}")98if result.stderr:99error_bits.append(f"stderr: {result.stderr}")100raise RuntimeError("\n".join(error_bits))101102return (result.stdout or "")103104105def is_installed(package):106try:107spec = importlib.util.find_spec(package)108except ModuleNotFoundError:109return False110111return spec is not None112113114def repo_dir(name):115return os.path.join(script_path, dir_repos, name)116117118def run_pip(command, desc=None, live=default_command_live):119if args.skip_install:120return121122index_url_line = f' --index-url {index_url}' if index_url != '' else ''123return run(f'"{python}" -m pip {command} --prefer-binary{index_url_line}', desc=f"Installing {desc}", errdesc=f"Couldn't install {desc}", live=live)124125126def check_run_python(code: str) -> bool:127result = subprocess.run([python, "-c", code], capture_output=True, shell=False)128return result.returncode == 0129130131def git_clone(url, dir, name, commithash=None):132# TODO clone into temporary dir and move if successful133134if os.path.exists(dir):135if commithash is None:136return137138current_hash = run(f'"{git}" -C "{dir}" rev-parse HEAD', None, f"Couldn't determine {name}'s hash: {commithash}").strip()139if current_hash == commithash:140return141142run(f'"{git}" -C "{dir}" fetch', f"Fetching updates for {name}...", f"Couldn't fetch {name}")143run(f'"{git}" -C "{dir}" checkout {commithash}', f"Checking out commit for {name} with hash: {commithash}...", f"Couldn't checkout commit {commithash} for {name}")144return145146run(f'"{git}" clone "{url}" "{dir}"', f"Cloning {name} into {dir}...", f"Couldn't clone {name}")147148if commithash is not None:149run(f'"{git}" -C "{dir}" checkout {commithash}', None, "Couldn't checkout {name}'s hash: {commithash}")150151152def git_pull_recursive(dir):153for subdir, _, _ in os.walk(dir):154if os.path.exists(os.path.join(subdir, '.git')):155try:156output = subprocess.check_output([git, '-C', subdir, 'pull', '--autostash'])157print(f"Pulled changes for repository in '{subdir}':\n{output.decode('utf-8').strip()}\n")158except subprocess.CalledProcessError as e:159print(f"Couldn't perform 'git pull' on repository in '{subdir}':\n{e.output.decode('utf-8').strip()}\n")160161162def version_check(commit):163try:164import requests165commits = requests.get('https://api.github.com/repos/AUTOMATIC1111/stable-diffusion-webui/branches/master').json()166if commit != "<none>" and commits['commit']['sha'] != commit:167print("--------------------------------------------------------")168print("| You are not up to date with the most recent release. |")169print("| Consider running `git pull` to update. |")170print("--------------------------------------------------------")171elif commits['commit']['sha'] == commit:172print("You are up to date with the most recent release.")173else:174print("Not a git clone, can't perform version check.")175except Exception as e:176print("version check failed", e)177178179def run_extension_installer(extension_dir):180path_installer = os.path.join(extension_dir, "install.py")181if not os.path.isfile(path_installer):182return183184try:185env = os.environ.copy()186env['PYTHONPATH'] = os.path.abspath(".")187188print(run(f'"{python}" "{path_installer}"', errdesc=f"Error running install.py for extension {extension_dir}", custom_env=env))189except Exception as e:190print(e, file=sys.stderr)191192193def list_extensions(settings_file):194settings = {}195196try:197if os.path.isfile(settings_file):198with open(settings_file, "r", encoding="utf8") as file:199settings = json.load(file)200except Exception as e:201print(e, file=sys.stderr)202203disabled_extensions = set(settings.get('disabled_extensions', []))204disable_all_extensions = settings.get('disable_all_extensions', 'none')205206if disable_all_extensions != 'none':207return []208209return [x for x in os.listdir(extensions_dir) if x not in disabled_extensions]210211212def run_extensions_installers(settings_file):213if not os.path.isdir(extensions_dir):214return215216for dirname_extension in list_extensions(settings_file):217run_extension_installer(os.path.join(extensions_dir, dirname_extension))218219220def prepare_environment():221torch_index_url = os.environ.get('TORCH_INDEX_URL', "https://download.pytorch.org/whl/cu118")222torch_command = os.environ.get('TORCH_COMMAND', f"pip install torch==2.0.1 torchvision==0.15.2 --extra-index-url {torch_index_url}")223requirements_file = os.environ.get('REQS_FILE', "requirements_versions.txt")224225xformers_package = os.environ.get('XFORMERS_PACKAGE', 'xformers==0.0.17')226gfpgan_package = os.environ.get('GFPGAN_PACKAGE', "https://github.com/TencentARC/GFPGAN/archive/8d2447a2d918f8eba5a4a01463fd48e45126a379.zip")227clip_package = os.environ.get('CLIP_PACKAGE', "https://github.com/openai/CLIP/archive/d50d76daa670286dd6cacf3bcd80b5e4823fc8e1.zip")228openclip_package = os.environ.get('OPENCLIP_PACKAGE', "https://github.com/mlfoundations/open_clip/archive/bb6e834e9c70d9c27d0dc3ecedeebeaeb1ffad6b.zip")229230stable_diffusion_repo = os.environ.get('STABLE_DIFFUSION_REPO', "https://github.com/Stability-AI/stablediffusion.git")231taming_transformers_repo = os.environ.get('TAMING_TRANSFORMERS_REPO', "https://github.com/CompVis/taming-transformers.git")232k_diffusion_repo = os.environ.get('K_DIFFUSION_REPO', 'https://github.com/crowsonkb/k-diffusion.git')233codeformer_repo = os.environ.get('CODEFORMER_REPO', 'https://github.com/sczhou/CodeFormer.git')234blip_repo = os.environ.get('BLIP_REPO', 'https://github.com/salesforce/BLIP.git')235236stable_diffusion_commit_hash = os.environ.get('STABLE_DIFFUSION_COMMIT_HASH', "cf1d67a6fd5ea1aa600c4df58e5b47da45f6bdbf")237taming_transformers_commit_hash = os.environ.get('TAMING_TRANSFORMERS_COMMIT_HASH', "24268930bf1dce879235a7fddd0b2355b84d7ea6")238k_diffusion_commit_hash = os.environ.get('K_DIFFUSION_COMMIT_HASH', "c9fe758757e022f05ca5a53fa8fac28889e4f1cf")239codeformer_commit_hash = os.environ.get('CODEFORMER_COMMIT_HASH', "c5b4593074ba6214284d6acd5f1719b6c5d739af")240blip_commit_hash = os.environ.get('BLIP_COMMIT_HASH', "48211a1594f1321b00f14c9f7a5b4813144b2fb9")241242if not args.skip_python_version_check:243check_python_version()244245commit = commit_hash()246tag = git_tag()247248print(f"Python {sys.version}")249print(f"Version: {tag}")250print(f"Commit hash: {commit}")251252if args.reinstall_torch or not is_installed("torch") or not is_installed("torchvision"):253run(f'"{python}" -m {torch_command}', "Installing torch and torchvision", "Couldn't install torch", live=True)254255if not args.skip_torch_cuda_test and not check_run_python("import torch; assert torch.cuda.is_available()"):256raise RuntimeError(257'Torch is not able to use GPU; '258'add --skip-torch-cuda-test to COMMANDLINE_ARGS variable to disable this check'259)260261if not is_installed("gfpgan"):262run_pip(f"install {gfpgan_package}", "gfpgan")263264if not is_installed("clip"):265run_pip(f"install {clip_package}", "clip")266267if not is_installed("open_clip"):268run_pip(f"install {openclip_package}", "open_clip")269270if (not is_installed("xformers") or args.reinstall_xformers) and args.xformers:271if platform.system() == "Windows":272if platform.python_version().startswith("3.10"):273run_pip(f"install -U -I --no-deps {xformers_package}", "xformers", live=True)274else:275print("Installation of xformers is not supported in this version of Python.")276print("You can also check this and build manually: https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Xformers#building-xformers-on-windows-by-duckness")277if not is_installed("xformers"):278exit(0)279elif platform.system() == "Linux":280run_pip(f"install -U -I --no-deps {xformers_package}", "xformers")281282if not is_installed("ngrok") and args.ngrok:283run_pip("install ngrok", "ngrok")284285os.makedirs(os.path.join(script_path, dir_repos), exist_ok=True)286287git_clone(stable_diffusion_repo, repo_dir('stable-diffusion-stability-ai'), "Stable Diffusion", stable_diffusion_commit_hash)288git_clone(taming_transformers_repo, repo_dir('taming-transformers'), "Taming Transformers", taming_transformers_commit_hash)289git_clone(k_diffusion_repo, repo_dir('k-diffusion'), "K-diffusion", k_diffusion_commit_hash)290git_clone(codeformer_repo, repo_dir('CodeFormer'), "CodeFormer", codeformer_commit_hash)291git_clone(blip_repo, repo_dir('BLIP'), "BLIP", blip_commit_hash)292293if not is_installed("lpips"):294run_pip(f"install -r \"{os.path.join(repo_dir('CodeFormer'), 'requirements.txt')}\"", "requirements for CodeFormer")295296if not os.path.isfile(requirements_file):297requirements_file = os.path.join(script_path, requirements_file)298run_pip(f"install -r \"{requirements_file}\"", "requirements")299300run_extensions_installers(settings_file=args.ui_settings_file)301302if args.update_check:303version_check(commit)304305if args.update_all_extensions:306git_pull_recursive(extensions_dir)307308if "--exit" in sys.argv:309print("Exiting because of --exit argument")310exit(0)311312313def configure_for_tests():314if "--api" not in sys.argv:315sys.argv.append("--api")316if "--ckpt" not in sys.argv:317sys.argv.append("--ckpt")318sys.argv.append(os.path.join(script_path, "test/test_files/empty.pt"))319if "--skip-torch-cuda-test" not in sys.argv:320sys.argv.append("--skip-torch-cuda-test")321if "--disable-nan-check" not in sys.argv:322sys.argv.append("--disable-nan-check")323324os.environ['COMMANDLINE_ARGS'] = ""325326327def start():328print(f"Launching {'API server' if '--nowebui' in sys.argv else 'Web UI'} with arguments: {' '.join(sys.argv[1:])}")329import webui330if '--nowebui' in sys.argv:331webui.api_only()332else:333webui.webui()334335336