launch_utils.py 15 KB

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