BBrother commited on
Commit
a5e0237
1 Parent(s): 041a571

Update launch.py

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