pysunny commited on
Commit
5e25eda
·
1 Parent(s): f130543

Upload app.py

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