launch_utils.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  1. # this scripts installs necessary requirements and launches main program in webui.py
  2. import logging
  3. import re
  4. import subprocess
  5. import os
  6. import shutil
  7. import sys
  8. import importlib.util
  9. import platform
  10. import json
  11. from functools import lru_cache
  12. from modules import cmd_args, errors
  13. from modules.paths_internal import script_path, extensions_dir
  14. from modules.timer import startup_timer
  15. from modules import logging_config
  16. args, _ = cmd_args.parser.parse_known_args()
  17. logging_config.setup_logging(args.loglevel)
  18. python = sys.executable
  19. git = os.environ.get('GIT', "git")
  20. index_url = os.environ.get('INDEX_URL', "")
  21. dir_repos = "repositories"
  22. # Whether to default to printing command output
  23. default_command_live = (os.environ.get('WEBUI_LAUNCH_LIVE_OUTPUT') == "1")
  24. if 'GRADIO_ANALYTICS_ENABLED' not in os.environ:
  25. os.environ['GRADIO_ANALYTICS_ENABLED'] = 'False'
  26. def check_python_version():
  27. is_windows = platform.system() == "Windows"
  28. major = sys.version_info.major
  29. minor = sys.version_info.minor
  30. micro = sys.version_info.micro
  31. if is_windows:
  32. supported_minors = [10]
  33. else:
  34. supported_minors = [7, 8, 9, 10, 11]
  35. if not (major == 3 and minor in supported_minors):
  36. import modules.errors
  37. modules.errors.print_error_explanation(f"""
  38. INCOMPATIBLE PYTHON VERSION
  39. This program is tested with 3.10.6 Python, but you have {major}.{minor}.{micro}.
  40. If you encounter an error with "RuntimeError: Couldn't install torch." message,
  41. or any other error regarding unsuccessful package (library) installation,
  42. please downgrade (or upgrade) to the latest version of 3.10 Python
  43. and delete current Python and "venv" folder in WebUI's directory.
  44. You can download 3.10 Python from here: https://www.python.org/downloads/release/python-3106/
  45. {"Alternatively, use a binary release of WebUI: https://github.com/AUTOMATIC1111/stable-diffusion-webui/releases" if is_windows else ""}
  46. Use --skip-python-version-check to suppress this warning.
  47. """)
  48. @lru_cache()
  49. def commit_hash():
  50. try:
  51. return subprocess.check_output([git, "rev-parse", "HEAD"], shell=False, encoding='utf8').strip()
  52. except Exception:
  53. return "<none>"
  54. @lru_cache()
  55. def git_tag():
  56. try:
  57. return subprocess.check_output([git, "describe", "--tags"], shell=False, encoding='utf8').strip()
  58. except Exception:
  59. try:
  60. changelog_md = os.path.join(os.path.dirname(os.path.dirname(__file__)), "CHANGELOG.md")
  61. with open(changelog_md, "r", encoding="utf-8") as file:
  62. line = next((line.strip() for line in file if line.strip()), "<none>")
  63. line = line.replace("## ", "")
  64. return line
  65. except Exception:
  66. return "<none>"
  67. def run(command, desc=None, errdesc=None, custom_env=None, live: bool = default_command_live) -> str:
  68. if desc is not None:
  69. print(desc)
  70. run_kwargs = {
  71. "args": command,
  72. "shell": True,
  73. "env": os.environ if custom_env is None else custom_env,
  74. "encoding": 'utf8',
  75. "errors": 'ignore',
  76. }
  77. if not live:
  78. run_kwargs["stdout"] = run_kwargs["stderr"] = subprocess.PIPE
  79. result = subprocess.run(**run_kwargs)
  80. if result.returncode != 0:
  81. error_bits = [
  82. f"{errdesc or 'Error running command'}.",
  83. f"Command: {command}",
  84. f"Error code: {result.returncode}",
  85. ]
  86. if result.stdout:
  87. error_bits.append(f"stdout: {result.stdout}")
  88. if result.stderr:
  89. error_bits.append(f"stderr: {result.stderr}")
  90. raise RuntimeError("\n".join(error_bits))
  91. return (result.stdout or "")
  92. def is_installed(package):
  93. try:
  94. spec = importlib.util.find_spec(package)
  95. except ModuleNotFoundError:
  96. return False
  97. return spec is not None
  98. def repo_dir(name):
  99. return os.path.join(script_path, dir_repos, name)
  100. def run_pip(command, desc=None, live=default_command_live):
  101. if args.skip_install:
  102. return
  103. index_url_line = f' --index-url {index_url}' if index_url != '' else ''
  104. return run(f'"{python}" -m pip {command} --prefer-binary{index_url_line}', desc=f"Installing {desc}", errdesc=f"Couldn't install {desc}", live=live)
  105. def check_run_python(code: str) -> bool:
  106. result = subprocess.run([python, "-c", code], capture_output=True, shell=False)
  107. return result.returncode == 0
  108. def git_fix_workspace(dir, name):
  109. run(f'"{git}" -C "{dir}" fetch --refetch --no-auto-gc', f"Fetching all contents for {name}", f"Couldn't fetch {name}", live=True)
  110. run(f'"{git}" -C "{dir}" gc --aggressive --prune=now', f"Pruning {name}", f"Couldn't prune {name}", live=True)
  111. return
  112. def run_git(dir, name, command, desc=None, errdesc=None, custom_env=None, live: bool = default_command_live, autofix=True):
  113. try:
  114. return run(f'"{git}" -C "{dir}" {command}', desc=desc, errdesc=errdesc, custom_env=custom_env, live=live)
  115. except RuntimeError:
  116. if not autofix:
  117. raise
  118. print(f"{errdesc}, attempting autofix...")
  119. git_fix_workspace(dir, name)
  120. return run(f'"{git}" -C "{dir}" {command}', desc=desc, errdesc=errdesc, custom_env=custom_env, live=live)
  121. def git_clone(url, dir, name, commithash=None):
  122. # TODO clone into temporary dir and move if successful
  123. if os.path.exists(dir):
  124. if commithash is None:
  125. return
  126. current_hash = run_git(dir, name, 'rev-parse HEAD', None, f"Couldn't determine {name}'s hash: {commithash}", live=False).strip()
  127. if current_hash == commithash:
  128. return
  129. if run_git(dir, name, 'config --get remote.origin.url', None, f"Couldn't determine {name}'s origin URL", live=False).strip() != url:
  130. run_git(dir, name, f'remote set-url origin "{url}"', None, f"Failed to set {name}'s origin URL", live=False)
  131. run_git(dir, name, 'fetch', f"Fetching updates for {name}...", f"Couldn't fetch {name}", autofix=False)
  132. run_git(dir, name, f'checkout {commithash}', f"Checking out commit for {name} with hash: {commithash}...", f"Couldn't checkout commit {commithash} for {name}", live=True)
  133. return
  134. try:
  135. run(f'"{git}" clone "{url}" "{dir}"', f"Cloning {name} into {dir}...", f"Couldn't clone {name}", live=True)
  136. except RuntimeError:
  137. shutil.rmtree(dir, ignore_errors=True)
  138. raise
  139. if commithash is not None:
  140. run(f'"{git}" -C "{dir}" checkout {commithash}', None, "Couldn't checkout {name}'s hash: {commithash}")
  141. def git_pull_recursive(dir):
  142. for subdir, _, _ in os.walk(dir):
  143. if os.path.exists(os.path.join(subdir, '.git')):
  144. try:
  145. output = subprocess.check_output([git, '-C', subdir, 'pull', '--autostash'])
  146. print(f"Pulled changes for repository in '{subdir}':\n{output.decode('utf-8').strip()}\n")
  147. except subprocess.CalledProcessError as e:
  148. print(f"Couldn't perform 'git pull' on repository in '{subdir}':\n{e.output.decode('utf-8').strip()}\n")
  149. def version_check(commit):
  150. try:
  151. import requests
  152. commits = requests.get('https://api.github.com/repos/AUTOMATIC1111/stable-diffusion-webui/branches/master').json()
  153. if commit != "<none>" and commits['commit']['sha'] != commit:
  154. print("--------------------------------------------------------")
  155. print("| You are not up to date with the most recent release. |")
  156. print("| Consider running `git pull` to update. |")
  157. print("--------------------------------------------------------")
  158. elif commits['commit']['sha'] == commit:
  159. print("You are up to date with the most recent release.")
  160. else:
  161. print("Not a git clone, can't perform version check.")
  162. except Exception as e:
  163. print("version check failed", e)
  164. def run_extension_installer(extension_dir):
  165. path_installer = os.path.join(extension_dir, "install.py")
  166. if not os.path.isfile(path_installer):
  167. return
  168. try:
  169. env = os.environ.copy()
  170. env['PYTHONPATH'] = f"{os.path.abspath('.')}{os.pathsep}{env.get('PYTHONPATH', '')}"
  171. print(run(f'"{python}" "{path_installer}"', errdesc=f"Error running install.py for extension {extension_dir}", custom_env=env))
  172. except Exception as e:
  173. errors.report(str(e))
  174. def list_extensions(settings_file):
  175. settings = {}
  176. try:
  177. if os.path.isfile(settings_file):
  178. with open(settings_file, "r", encoding="utf8") as file:
  179. settings = json.load(file)
  180. except Exception:
  181. errors.report("Could not load settings", exc_info=True)
  182. disabled_extensions = set(settings.get('disabled_extensions', []))
  183. disable_all_extensions = settings.get('disable_all_extensions', 'none')
  184. if disable_all_extensions != 'none' or args.disable_extra_extensions or args.disable_all_extensions or not os.path.isdir(extensions_dir):
  185. return []
  186. return [x for x in os.listdir(extensions_dir) if x not in disabled_extensions]
  187. def run_extensions_installers(settings_file):
  188. if not os.path.isdir(extensions_dir):
  189. return
  190. with startup_timer.subcategory("run extensions installers"):
  191. for dirname_extension in list_extensions(settings_file):
  192. logging.debug(f"Installing {dirname_extension}")
  193. path = os.path.join(extensions_dir, dirname_extension)
  194. if os.path.isdir(path):
  195. run_extension_installer(path)
  196. startup_timer.record(dirname_extension)
  197. re_requirement = re.compile(r"\s*([-_a-zA-Z0-9]+)\s*(?:==\s*([-+_.a-zA-Z0-9]+))?\s*")
  198. def requirements_met(requirements_file):
  199. """
  200. Does a simple parse of a requirements.txt file to determine if all rerqirements in it
  201. are already installed. Returns True if so, False if not installed or parsing fails.
  202. """
  203. import importlib.metadata
  204. import packaging.version
  205. with open(requirements_file, "r", encoding="utf8") as file:
  206. for line in file:
  207. if line.strip() == "":
  208. continue
  209. m = re.match(re_requirement, line)
  210. if m is None:
  211. return False
  212. package = m.group(1).strip()
  213. version_required = (m.group(2) or "").strip()
  214. if version_required == "":
  215. continue
  216. try:
  217. version_installed = importlib.metadata.version(package)
  218. except Exception:
  219. return False
  220. if packaging.version.parse(version_required) != packaging.version.parse(version_installed):
  221. return False
  222. return True
  223. def prepare_environment():
  224. torch_index_url = os.environ.get('TORCH_INDEX_URL', "https://download.pytorch.org/whl/cu118")
  225. torch_command = os.environ.get('TORCH_COMMAND', f"pip install torch==2.0.1 torchvision==0.15.2 --extra-index-url {torch_index_url}")
  226. requirements_file = os.environ.get('REQS_FILE', "requirements_versions.txt")
  227. xformers_package = os.environ.get('XFORMERS_PACKAGE', 'xformers==0.0.20')
  228. clip_package = os.environ.get('CLIP_PACKAGE', "https://github.com/openai/CLIP/archive/d50d76daa670286dd6cacf3bcd80b5e4823fc8e1.zip")
  229. openclip_package = os.environ.get('OPENCLIP_PACKAGE', "https://github.com/mlfoundations/open_clip/archive/bb6e834e9c70d9c27d0dc3ecedeebeaeb1ffad6b.zip")
  230. stable_diffusion_repo = os.environ.get('STABLE_DIFFUSION_REPO', "https://github.com/Stability-AI/stablediffusion.git")
  231. stable_diffusion_xl_repo = os.environ.get('STABLE_DIFFUSION_XL_REPO', "https://github.com/Stability-AI/generative-models.git")
  232. k_diffusion_repo = os.environ.get('K_DIFFUSION_REPO', 'https://github.com/crowsonkb/k-diffusion.git')
  233. codeformer_repo = os.environ.get('CODEFORMER_REPO', 'https://github.com/sczhou/CodeFormer.git')
  234. blip_repo = os.environ.get('BLIP_REPO', 'https://github.com/salesforce/BLIP.git')
  235. stable_diffusion_commit_hash = os.environ.get('STABLE_DIFFUSION_COMMIT_HASH', "cf1d67a6fd5ea1aa600c4df58e5b47da45f6bdbf")
  236. stable_diffusion_xl_commit_hash = os.environ.get('STABLE_DIFFUSION_XL_COMMIT_HASH', "45c443b316737a4ab6e40413d7794a7f5657c19f")
  237. k_diffusion_commit_hash = os.environ.get('K_DIFFUSION_COMMIT_HASH', "ab527a9a6d347f364e3d185ba6d714e22d80cb3c")
  238. codeformer_commit_hash = os.environ.get('CODEFORMER_COMMIT_HASH', "c5b4593074ba6214284d6acd5f1719b6c5d739af")
  239. blip_commit_hash = os.environ.get('BLIP_COMMIT_HASH', "48211a1594f1321b00f14c9f7a5b4813144b2fb9")
  240. try:
  241. # the existence of this file is a signal to webui.sh/bat that webui needs to be restarted when it stops execution
  242. os.remove(os.path.join(script_path, "tmp", "restart"))
  243. os.environ.setdefault('SD_WEBUI_RESTARTING', '1')
  244. except OSError:
  245. pass
  246. if not args.skip_python_version_check:
  247. check_python_version()
  248. startup_timer.record("checks")
  249. commit = commit_hash()
  250. tag = git_tag()
  251. startup_timer.record("git version info")
  252. print(f"Python {sys.version}")
  253. print(f"Version: {tag}")
  254. print(f"Commit hash: {commit}")
  255. if args.reinstall_torch or not is_installed("torch") or not is_installed("torchvision"):
  256. run(f'"{python}" -m {torch_command}', "Installing torch and torchvision", "Couldn't install torch", live=True)
  257. startup_timer.record("install torch")
  258. if not args.skip_torch_cuda_test and not check_run_python("import torch; assert torch.cuda.is_available()"):
  259. raise RuntimeError(
  260. 'Torch is not able to use GPU; '
  261. 'add --skip-torch-cuda-test to COMMANDLINE_ARGS variable to disable this check'
  262. )
  263. startup_timer.record("torch GPU test")
  264. if not is_installed("clip"):
  265. run_pip(f"install {clip_package}", "clip")
  266. startup_timer.record("install clip")
  267. if not is_installed("open_clip"):
  268. run_pip(f"install {openclip_package}", "open_clip")
  269. startup_timer.record("install open_clip")
  270. if (not is_installed("xformers") or args.reinstall_xformers) and args.xformers:
  271. run_pip(f"install -U -I --no-deps {xformers_package}", "xformers")
  272. startup_timer.record("install xformers")
  273. if not is_installed("ngrok") and args.ngrok:
  274. run_pip("install ngrok", "ngrok")
  275. startup_timer.record("install ngrok")
  276. os.makedirs(os.path.join(script_path, dir_repos), exist_ok=True)
  277. git_clone(stable_diffusion_repo, repo_dir('stable-diffusion-stability-ai'), "Stable Diffusion", stable_diffusion_commit_hash)
  278. git_clone(stable_diffusion_xl_repo, repo_dir('generative-models'), "Stable Diffusion XL", stable_diffusion_xl_commit_hash)
  279. git_clone(k_diffusion_repo, repo_dir('k-diffusion'), "K-diffusion", k_diffusion_commit_hash)
  280. git_clone(codeformer_repo, repo_dir('CodeFormer'), "CodeFormer", codeformer_commit_hash)
  281. git_clone(blip_repo, repo_dir('BLIP'), "BLIP", blip_commit_hash)
  282. startup_timer.record("clone repositores")
  283. if not is_installed("lpips"):
  284. run_pip(f"install -r \"{os.path.join(repo_dir('CodeFormer'), 'requirements.txt')}\"", "requirements for CodeFormer")
  285. startup_timer.record("install CodeFormer requirements")
  286. if not os.path.isfile(requirements_file):
  287. requirements_file = os.path.join(script_path, requirements_file)
  288. if not requirements_met(requirements_file):
  289. run_pip(f"install -r \"{requirements_file}\"", "requirements")
  290. startup_timer.record("install requirements")
  291. run_extensions_installers(settings_file=args.ui_settings_file)
  292. if args.update_check:
  293. version_check(commit)
  294. startup_timer.record("check version")
  295. if args.update_all_extensions:
  296. git_pull_recursive(extensions_dir)
  297. startup_timer.record("update extensions")
  298. if "--exit" in sys.argv:
  299. print("Exiting because of --exit argument")
  300. exit(0)
  301. def configure_for_tests():
  302. if "--api" not in sys.argv:
  303. sys.argv.append("--api")
  304. if "--ckpt" not in sys.argv:
  305. sys.argv.append("--ckpt")
  306. sys.argv.append(os.path.join(script_path, "test/test_files/empty.pt"))
  307. if "--skip-torch-cuda-test" not in sys.argv:
  308. sys.argv.append("--skip-torch-cuda-test")
  309. if "--disable-nan-check" not in sys.argv:
  310. sys.argv.append("--disable-nan-check")
  311. os.environ['COMMANDLINE_ARGS'] = ""
  312. def start():
  313. print(f"Launching {'API server' if '--nowebui' in sys.argv else 'Web UI'} with arguments: {' '.join(sys.argv[1:])}")
  314. import webui
  315. if '--nowebui' in sys.argv:
  316. webui.api_only()
  317. else:
  318. webui.webui()