launch.py 14 KB

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