launch_utils.py 17 KB

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