artdwn commited on
Commit
894aa6d
·
1 Parent(s): 2e2b7ba

Upload launch.py

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