launch_utils.py 16 KB

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