JacobPerera commited on
Commit
6a6b894
·
1 Parent(s): d2bb9f9

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -345
app.py DELETED
@@ -1,345 +0,0 @@
1
- # import gradio as gr
2
-
3
- # def greet(name):
4
- # return "Hello " + name + "!!"
5
-
6
- # iface = gr.Interface(fn=greet, inputs="text", outputs="text")
7
- # iface.launch()
8
-
9
- import os
10
- import sys
11
- import time
12
- import importlib
13
- import signal
14
- import re
15
- from fastapi import FastAPI
16
- from fastapi.middleware.cors import CORSMiddleware
17
- from fastapi.middleware.gzip import GZipMiddleware
18
- from packaging import version
19
-
20
- import logging
21
- logging.getLogger("xformers").addFilter(lambda record: 'A matching Triton is not available' not in record.getMessage())
22
-
23
- from modules import paths, timer, import_hook, errors
24
-
25
- startup_timer = timer.Timer()
26
-
27
- import torch
28
- startup_timer.record("import torch")
29
-
30
- import gradio
31
- startup_timer.record("import gradio")
32
-
33
- import ldm.modules.encoders.modules
34
- startup_timer.record("import ldm")
35
-
36
- from modules import extra_networks, ui_extra_networks_checkpoints
37
- from modules import extra_networks_hypernet, ui_extra_networks_hypernets, ui_extra_networks_textual_inversion
38
- from modules.call_queue import wrap_queued_call, queue_lock, wrap_gradio_gpu_call
39
-
40
- # Truncate version number of nightly/local build of PyTorch to not cause exceptions with CodeFormer or Safetensors
41
- if ".dev" in torch.__version__ or "+git" in torch.__version__:
42
- torch.__long_version__ = torch.__version__
43
- torch.__version__ = re.search(r'[\d.]+[\d]', torch.__version__).group(0)
44
-
45
- from modules import shared, devices, sd_samplers, upscaler, extensions, localization, ui_tempdir, ui_extra_networks
46
- import modules.codeformer_model as codeformer
47
- import modules.face_restoration
48
- import modules.gfpgan_model as gfpgan
49
- import modules.img2img
50
-
51
- import modules.lowvram
52
- import modules.scripts
53
- import modules.sd_hijack
54
- import modules.sd_models
55
- import modules.sd_vae
56
- import modules.txt2img
57
- import modules.script_callbacks
58
- import modules.textual_inversion.textual_inversion
59
- import modules.progress
60
-
61
- import modules.ui
62
- from modules import modelloader
63
- from modules.shared import cmd_opts
64
- import modules.hypernetworks.hypernetwork
65
-
66
- startup_timer.record("other imports")
67
-
68
-
69
- if cmd_opts.server_name:
70
- server_name = cmd_opts.server_name
71
- else:
72
- server_name = "0.0.0.0" if cmd_opts.listen else None
73
-
74
-
75
- def check_versions():
76
- if shared.cmd_opts.skip_version_check:
77
- return
78
-
79
- expected_torch_version = "1.13.1"
80
-
81
- if version.parse(torch.__version__) < version.parse(expected_torch_version):
82
- errors.print_error_explanation(f"""
83
- You are running torch {torch.__version__}.
84
- The program is tested to work with torch {expected_torch_version}.
85
- To reinstall the desired version, run with commandline flag --reinstall-torch.
86
- Beware that this will cause a lot of large files to be downloaded, as well as
87
- there are reports of issues with training tab on the latest version.
88
-
89
- Use --skip-version-check commandline argument to disable this check.
90
- """.strip())
91
-
92
- expected_xformers_version = "0.0.16rc425"
93
- if shared.xformers_available:
94
- import xformers
95
-
96
- if version.parse(xformers.__version__) < version.parse(expected_xformers_version):
97
- errors.print_error_explanation(f"""
98
- You are running xformers {xformers.__version__}.
99
- The program is tested to work with xformers {expected_xformers_version}.
100
- To reinstall the desired version, run with commandline flag --reinstall-xformers.
101
-
102
- Use --skip-version-check commandline argument to disable this check.
103
- """.strip())
104
-
105
-
106
- def initialize():
107
- check_versions()
108
-
109
- extensions.list_extensions()
110
- localization.list_localizations(cmd_opts.localizations_dir)
111
- startup_timer.record("list extensions")
112
-
113
- if cmd_opts.ui_debug_mode:
114
- shared.sd_upscalers = upscaler.UpscalerLanczos().scalers
115
- modules.scripts.load_scripts()
116
- return
117
-
118
- modelloader.cleanup_models()
119
- modules.sd_models.setup_model()
120
- startup_timer.record("list SD models")
121
-
122
- codeformer.setup_model(cmd_opts.codeformer_models_path)
123
- startup_timer.record("setup codeformer")
124
-
125
- gfpgan.setup_model(cmd_opts.gfpgan_models_path)
126
- startup_timer.record("setup gfpgan")
127
-
128
- modelloader.list_builtin_upscalers()
129
- startup_timer.record("list builtin upscalers")
130
-
131
- modules.scripts.load_scripts()
132
- startup_timer.record("load scripts")
133
-
134
- modelloader.load_upscalers()
135
- startup_timer.record("load upscalers")
136
-
137
- modules.sd_vae.refresh_vae_list()
138
- startup_timer.record("refresh VAE")
139
-
140
- modules.textual_inversion.textual_inversion.list_textual_inversion_templates()
141
- startup_timer.record("refresh textual inversion templates")
142
-
143
- try:
144
- modules.sd_models.load_model()
145
- except Exception as e:
146
- errors.display(e, "loading stable diffusion model")
147
- print("", file=sys.stderr)
148
- print("Stable diffusion model failed to load, exiting", file=sys.stderr)
149
- exit(1)
150
- startup_timer.record("load SD checkpoint")
151
-
152
- shared.opts.data["sd_model_checkpoint"] = shared.sd_model.sd_checkpoint_info.title
153
-
154
- shared.opts.onchange("sd_model_checkpoint", wrap_queued_call(lambda: modules.sd_models.reload_model_weights()))
155
- shared.opts.onchange("sd_vae", wrap_queued_call(lambda: modules.sd_vae.reload_vae_weights()), call=False)
156
- shared.opts.onchange("sd_vae_as_default", wrap_queued_call(lambda: modules.sd_vae.reload_vae_weights()), call=False)
157
- shared.opts.onchange("temp_dir", ui_tempdir.on_tmpdir_changed)
158
- startup_timer.record("opts onchange")
159
-
160
- shared.reload_hypernetworks()
161
- startup_timer.record("reload hypernets")
162
-
163
- ui_extra_networks.intialize()
164
- ui_extra_networks.register_page(ui_extra_networks_textual_inversion.ExtraNetworksPageTextualInversion())
165
- ui_extra_networks.register_page(ui_extra_networks_hypernets.ExtraNetworksPageHypernetworks())
166
- ui_extra_networks.register_page(ui_extra_networks_checkpoints.ExtraNetworksPageCheckpoints())
167
-
168
- extra_networks.initialize()
169
- extra_networks.register_extra_network(extra_networks_hypernet.ExtraNetworkHypernet())
170
- startup_timer.record("extra networks")
171
-
172
- if cmd_opts.tls_keyfile is not None and cmd_opts.tls_keyfile is not None:
173
-
174
- try:
175
- if not os.path.exists(cmd_opts.tls_keyfile):
176
- print("Invalid path to TLS keyfile given")
177
- if not os.path.exists(cmd_opts.tls_certfile):
178
- print(f"Invalid path to TLS certfile: '{cmd_opts.tls_certfile}'")
179
- except TypeError:
180
- cmd_opts.tls_keyfile = cmd_opts.tls_certfile = None
181
- print("TLS setup invalid, running webui without TLS")
182
- else:
183
- print("Running with TLS")
184
- startup_timer.record("TLS")
185
-
186
- # make the program just exit at ctrl+c without waiting for anything
187
- def sigint_handler(sig, frame):
188
- print(f'Interrupted with signal {sig} in {frame}')
189
- os._exit(0)
190
-
191
- signal.signal(signal.SIGINT, sigint_handler)
192
-
193
-
194
- def setup_middleware(app):
195
- app.middleware_stack = None # reset current middleware to allow modifying user provided list
196
- app.add_middleware(GZipMiddleware, minimum_size=1000)
197
- if cmd_opts.cors_allow_origins and cmd_opts.cors_allow_origins_regex:
198
- app.add_middleware(CORSMiddleware, allow_origins=cmd_opts.cors_allow_origins.split(','), allow_origin_regex=cmd_opts.cors_allow_origins_regex, allow_methods=['*'], allow_credentials=True, allow_headers=['*'])
199
- elif cmd_opts.cors_allow_origins:
200
- app.add_middleware(CORSMiddleware, allow_origins=cmd_opts.cors_allow_origins.split(','), allow_methods=['*'], allow_credentials=True, allow_headers=['*'])
201
- elif cmd_opts.cors_allow_origins_regex:
202
- app.add_middleware(CORSMiddleware, allow_origin_regex=cmd_opts.cors_allow_origins_regex, allow_methods=['*'], allow_credentials=True, allow_headers=['*'])
203
- app.build_middleware_stack() # rebuild middleware stack on-the-fly
204
-
205
-
206
- def create_api(app):
207
- from modules.api.api import Api
208
- api = Api(app, queue_lock)
209
- return api
210
-
211
-
212
- def wait_on_server(demo=None):
213
- while 1:
214
- time.sleep(0.5)
215
- if shared.state.need_restart:
216
- shared.state.need_restart = False
217
- time.sleep(0.5)
218
- demo.close()
219
- time.sleep(0.5)
220
- break
221
-
222
-
223
- def api_only():
224
- initialize()
225
-
226
- app = FastAPI()
227
- setup_middleware(app)
228
- api = create_api(app)
229
-
230
- modules.script_callbacks.app_started_callback(None, app)
231
-
232
- print(f"Startup time: {startup_timer.summary()}.")
233
- api.launch(server_name="0.0.0.0" if cmd_opts.listen else "127.0.0.1", port=cmd_opts.port if cmd_opts.port else 7861)
234
-
235
-
236
- def webui():
237
- launch_api = cmd_opts.api
238
- initialize()
239
-
240
- while 1:
241
- if shared.opts.clean_temp_dir_at_start:
242
- ui_tempdir.cleanup_tmpdr()
243
- startup_timer.record("cleanup temp dir")
244
-
245
- modules.script_callbacks.before_ui_callback()
246
- startup_timer.record("scripts before_ui_callback")
247
-
248
- shared.demo = modules.ui.create_ui()
249
- startup_timer.record("create ui")
250
-
251
- if cmd_opts.gradio_queue:
252
- shared.demo.queue(64)
253
-
254
- gradio_auth_creds = []
255
- if cmd_opts.gradio_auth:
256
- gradio_auth_creds += [x.strip() for x in cmd_opts.gradio_auth.strip('"').replace('\n', '').split(',') if x.strip()]
257
- if cmd_opts.gradio_auth_path:
258
- with open(cmd_opts.gradio_auth_path, 'r', encoding="utf8") as file:
259
- for line in file.readlines():
260
- gradio_auth_creds += [x.strip() for x in line.split(',') if x.strip()]
261
-
262
- app, local_url, share_url = shared.demo.launch(
263
- share=cmd_opts.share,
264
- server_name=server_name,
265
- server_port=cmd_opts.port,
266
- ssl_keyfile=cmd_opts.tls_keyfile,
267
- ssl_certfile=cmd_opts.tls_certfile,
268
- debug=cmd_opts.gradio_debug,
269
- auth=[tuple(cred.split(':')) for cred in gradio_auth_creds] if gradio_auth_creds else None,
270
- inbrowser=cmd_opts.autolaunch,
271
- prevent_thread_lock=True
272
- )
273
- # after initial launch, disable --autolaunch for subsequent restarts
274
- cmd_opts.autolaunch = False
275
-
276
- startup_timer.record("gradio launch")
277
-
278
- # gradio uses a very open CORS policy via app.user_middleware, which makes it possible for
279
- # an attacker to trick the user into opening a malicious HTML page, which makes a request to the
280
- # running web ui and do whatever the attacker wants, including installing an extension and
281
- # running its code. We disable this here. Suggested by RyotaK.
282
- app.user_middleware = [x for x in app.user_middleware if x.cls.__name__ != 'CORSMiddleware']
283
-
284
- setup_middleware(app)
285
-
286
- modules.progress.setup_progress_api(app)
287
-
288
- if launch_api:
289
- create_api(app)
290
-
291
- ui_extra_networks.add_pages_to_demo(app)
292
-
293
- modules.script_callbacks.app_started_callback(shared.demo, app)
294
- startup_timer.record("scripts app_started_callback")
295
-
296
- print(f"Startup time: {startup_timer.summary()}.")
297
-
298
- wait_on_server(shared.demo)
299
- print('Restarting UI...')
300
-
301
- startup_timer.reset()
302
-
303
- sd_samplers.set_samplers()
304
-
305
- modules.script_callbacks.script_unloaded_callback()
306
- extensions.list_extensions()
307
- startup_timer.record("list extensions")
308
-
309
- localization.list_localizations(cmd_opts.localizations_dir)
310
-
311
- modelloader.forbid_loaded_nonbuiltin_upscalers()
312
- modules.scripts.reload_scripts()
313
- startup_timer.record("load scripts")
314
-
315
- modules.script_callbacks.model_loaded_callback(shared.sd_model)
316
- startup_timer.record("model loaded callback")
317
-
318
- modelloader.load_upscalers()
319
- startup_timer.record("load upscalers")
320
-
321
- for module in [module for name, module in sys.modules.items() if name.startswith("modules.ui")]:
322
- importlib.reload(module)
323
- startup_timer.record("reload script modules")
324
-
325
- modules.sd_models.list_models()
326
- startup_timer.record("list SD models")
327
-
328
- shared.reload_hypernetworks()
329
- startup_timer.record("reload hypernetworks")
330
-
331
- ui_extra_networks.intialize()
332
- ui_extra_networks.register_page(ui_extra_networks_textual_inversion.ExtraNetworksPageTextualInversion())
333
- ui_extra_networks.register_page(ui_extra_networks_hypernets.ExtraNetworksPageHypernetworks())
334
- ui_extra_networks.register_page(ui_extra_networks_checkpoints.ExtraNetworksPageCheckpoints())
335
-
336
- extra_networks.initialize()
337
- extra_networks.register_extra_network(extra_networks_hypernet.ExtraNetworkHypernet())
338
- startup_timer.record("initialize extra networks")
339
-
340
-
341
- if __name__ == "__main__":
342
- if cmd_opts.nowebui:
343
- api_only()
344
- else:
345
- webui()