DeepCoreB4 commited on
Commit
5123800
1 Parent(s): 0412b8a

Upload app.py

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