launch_utils.py 20 KB

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