Skip to content

Commit 5a40c03

Browse files
committed
Last large refactoring movement, now it's polish and getting things working...
1 parent f1d311a commit 5a40c03

83 files changed

Lines changed: 2181 additions & 2478 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

core/cmdargs.py

Lines changed: 52 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -4,53 +4,57 @@
44
from core.paths import *
55
# TODO do not use cargs
66

7+
# The parsed args (global)
8+
cargs = None
9+
710
parser = argparse.ArgumentParser()
8-
parser.add_argument("--gfpgan-dir", type=str, help="GFPGAN directory", default=('./src/gfpgan' if os.path.exists('./src/gfpgan') else './GFPGAN'))
9-
parser.add_argument("--gfpgan-model", type=str, help="GFPGAN model file name", default=None)
10-
parser.add_argument("--no-half", action='store_true', help="do not switch the model to 16-bit floats")
11-
parser.add_argument("--no-half-vae", action='store_true', help="do not switch the VAE model to 16-bit floats")
12-
parser.add_argument("--no-progressbar-hiding", action='store_true', help="do not hide progressbar in gradio UI (we hide it because it slows down ML if you have hardware acceleration in browser)")
13-
parser.add_argument("--max-batch-count", type=int, default=16, help="maximum batch count value for the UI")
14-
parser.add_argument("--embeddings-dir", type=str, default=rootdir / 'embeddings', help="embeddings directory for textual inversion (default: embeddings)")
15-
parser.add_argument("--hypernetwork-dir", type=str, default=modeldir / 'modules/hypernetworks', help="hypernetwork directory")
16-
parser.add_argument("--allow-code", action='store_true', help="allow custom script execution from webui")
17-
parser.add_argument("--medvram", action='store_true', help="enable stable diffusion model optimizations for sacrificing a little speed for low VRM usage")
18-
parser.add_argument("--lowvram", action='store_true', help="enable stable diffusion model optimizations for sacrificing a lot of speed for very low VRM usage")
19-
parser.add_argument("--always-batch-cond-uncond", action='store_true', help="disables cond/uncond batching that is enabled to save memory with --medvram or --lowvram")
20-
parser.add_argument("--unload-gfpgan", action='store_true', help="does not do anything.")
21-
parser.add_argument("--precision", type=str, help="evaluate at this precision", choices=["full", "autocast"], default="autocast")
22-
parser.add_argument("--share", action='store_true', help="use share=True for gradio and make the UI accessible through their site (doesn't work for me but you might have better luck)")
23-
parser.add_argument("--ngrok", type=str, help="ngrok authtoken, alternative to gradio --share", default=None)
24-
parser.add_argument("--codeformer-models-path", type=str, help="Path to directory with codeformer model file(s).", default=modeldir / 'Codeformer')
25-
parser.add_argument("--gfpgan-models-path", type=str, help="Path to directory with GFPGAN model file(s).", default=(modeldir / 'GFPGAN').as_posix())
26-
parser.add_argument("--esrgan-models-path", type=str, help="Path to directory with ESRGAN model file(s).", default=(modeldir / 'ESRGAN').as_posix())
27-
parser.add_argument("--bsrgan-models-path", type=str, help="Path to directory with BSRGAN model file(s).", default=(modeldir / 'BSRGAN').as_posix())
28-
parser.add_argument("--realesrgan-models-path", type=str, help="Path to directory with RealESRGAN model file(s).", default=(modeldir / 'RealESRGAN').as_posix())
29-
parser.add_argument("--scunet-models-path", type=str, help="Path to directory with ScuNET model file(s).", default=(modeldir / 'ScuNET').as_posix())
30-
parser.add_argument("--swinir-models-path", type=str, help="Path to directory with SwinIR model file(s).", default=modeldir / 'SwinIR')
31-
parser.add_argument("--ldsr-models-path", type=str, help="Path to directory with LDSR model file(s).", default=modeldir / 'LDSR')
32-
parser.add_argument("--xformers", action='store_true', help="enable xformers for cross attention layers")
33-
parser.add_argument("--force-enable-xformers", action='store_true', help="enable xformers for cross attention layers regardless of whether the checking code thinks you can run it; do not make bug reports if this fails to work")
34-
parser.add_argument("--opt-split-attention", action='store_true', help="force-enables Doggettx's cross-attention layer optimization. By default, it's on for torch cuda.")
35-
parser.add_argument("--opt-split-attention-invokeai", action='store_true', help="force-enables InvokeAI's cross-attention layer optimization. By default, it's on when cuda is unavailable.")
36-
parser.add_argument("--opt-split-attention-v1", action='store_true', help="enable older version of split attention optimization that does not consume all the VRAM it can find")
37-
parser.add_argument("--disable-opt-split-attention", action='store_true', help="force-disables cross-attention layer optimization")
38-
parser.add_argument("--use-cpu", nargs='+', choices=['StableDiffusion', 'GFPGAN', 'BSRGAN', 'ESRGAN', 'SCUNet', 'CodeFormer'], help="use CPU as torch device for specified modules", default=[])
39-
parser.add_argument("--listen", action='store_true', help="launch gradio with 0.0.0.0 as server name, allowing to respond to network requests")
40-
parser.add_argument("--port", type=int, help="launch gradio with given server port, you need root/admin rights for ports < 1024, defaults to 7860 if available", default=None)
41-
parser.add_argument("--show-negative-prompt", action='store_true', help="does not do anything", default=False)
42-
parser.add_argument("--ui-config-file", type=str, help="filename to use for ui configuration", default=rootdir / 'ui-config.json')
43-
parser.add_argument("--hide-ui-dir-config", action='store_true', help="hide directory configuration from webui", default=False)
44-
parser.add_argument("--ui-settings-file", type=str, help="filename to use for ui settings", default=rootdir / 'config.json')
45-
parser.add_argument("--gradio-debug", action='store_true', help="launch gradio with --debug option")
46-
parser.add_argument("--gradio-auth", type=str, help='set gradio authentication like "username:password"; or comma-delimit multiple like "u1:p1,u2:p2,u3:p3"', default=None)
47-
parser.add_argument("--gradio-img2img-tool", type=str, help='gradio image uploader tool: can be either editor for ctopping, or color-sketch for drawing', choices=["color-sketch", "editor"], default="editor")
48-
parser.add_argument("--opt-channelslast", action='store_true', help="change memory type for stable diffusion to channels last")
49-
parser.add_argument("--styles-file", type=str, help="filename to use for styles", default=rootdir / 'styles.csv')
50-
parser.add_argument("--autolaunch", action='store_true', help="open the webui URL in the system's default browser upon launch", default=False)
51-
parser.add_argument("--use-textbox-seed", action='store_true', help="use textbox for seeds in UI (no up/down, but possible to input long seeds)", default=False)
52-
parser.add_argument("--disable-console-progressbars", action='store_true', help="do not output progressbars to console", default=False)
53-
parser.add_argument('--vae-path', type=str, help='Path to Variational Autoencoders model', default=None)
54-
parser.add_argument("--disable-safe-unpickle", action='store_true', help="disable checking pytorch models for malicious code", default=False)
11+
parser.add_argument("--dry", type=str, help="Only install and test the core, do not launch server.")
12+
13+
# parser.add_argument("--gfpgan-dir", type=str, help="GFPGAN directory", default=('./src/gfpgan' if os.path.exists('./src/gfpgan') else './GFPGAN'))
14+
# parser.add_argument("--gfpgan-model", type=str, help="GFPGAN model file name", default=None)
15+
# parser.add_argument("--no-half", action='store_true', help="do not switch the model to 16-bit floats")
16+
# parser.add_argument("--no-half-vae", action='store_true', help="do not switch the VAE model to 16-bit floats")
17+
# parser.add_argument("--no-progressbar-hiding", action='store_true', help="do not hide progressbar in gradio UI (we hide it because it slows down ML if you have hardware acceleration in browser)")
18+
# parser.add_argument("--max-batch-count", type=int, default=16, help="maximum batch count value for the UI")
19+
# parser.add_argument("--embeddings-dir", type=str, default=rootdir / 'embeddings', help="embeddings directory for textual inversion (default: embeddings)")
20+
# parser.add_argument("--hypernetwork-dir", type=str, default=modeldir / 'modules/hypernetworks', help="hypernetwork directory")
21+
# parser.add_argument("--allow-code", action='store_true', help="allow custom script execution from webui")
22+
# parser.add_argument("--medvram", action='store_true', help="enable stable diffusion model optimizations for sacrificing a little speed for low VRM usage")
23+
# parser.add_argument("--lowvram", action='store_true', help="enable stable diffusion model optimizations for sacrificing a lot of speed for very low VRM usage")
24+
# parser.add_argument("--always-batch-cond-uncond", action='store_true', help="disables cond/uncond batching that is enabled to save memory with --medvram or --lowvram")
25+
# parser.add_argument("--unload-gfpgan", action='store_true', help="does not do anything.")
26+
# parser.add_argument("--precision", type=str, help="evaluate at this precision", choices=["full", "autocast"], default="autocast")
27+
# parser.add_argument("--share", action='store_true', help="use share=True for gradio and make the UI accessible through their site (doesn't work for me but you might have better luck)")
28+
# parser.add_argument("--ngrok", type=str, help="ngrok authtoken, alternative to gradio --share", default=None)
29+
# parser.add_argument("--codeformer-models-path", type=str, help="Path to directory with codeformer model file(s).", default=modeldir / 'Codeformer')
30+
# parser.add_argument("--gfpgan-models-path", type=str, help="Path to directory with GFPGAN model file(s).", default=(modeldir / 'GFPGAN').as_posix())
31+
# parser.add_argument("--esrgan-models-path", type=str, help="Path to directory with ESRGAN model file(s).", default=(modeldir / 'ESRGAN').as_posix())
32+
# parser.add_argument("--bsrgan-models-path", type=str, help="Path to directory with BSRGAN model file(s).", default=(modeldir / 'BSRGAN').as_posix())
33+
# parser.add_argument("--realesrgan-models-path", type=str, help="Path to directory with RealESRGAN model file(s).", default=(modeldir / 'RealESRGAN').as_posix())
34+
# parser.add_argument("--scunet-models-path", type=str, help="Path to directory with ScuNET model file(s).", default=(modeldir / 'ScuNET').as_posix())
35+
# parser.add_argument("--swinir-models-path", type=str, help="Path to directory with SwinIR model file(s).", default=modeldir / 'SwinIR')
36+
# parser.add_argument("--ldsr-models-path", type=str, help="Path to directory with LDSR model file(s).", default=modeldir / 'LDSR')
37+
# parser.add_argument("--xformers", action='store_true', help="enable xformers for cross attention layers")
38+
# parser.add_argument("--force-enable-xformers", action='store_true', help="enable xformers for cross attention layers regardless of whether the checking code thinks you can run it; do not make bug reports if this fails to work")
39+
# parser.add_argument("--opt-split-attention", action='store_true', help="force-enables Doggettx's cross-attention layer optimization. By default, it's on for torch cuda.")
40+
# parser.add_argument("--opt-split-attention-invokeai", action='store_true', help="force-enables InvokeAI's cross-attention layer optimization. By default, it's on when cuda is unavailable.")
41+
# parser.add_argument("--opt-split-attention-v1", action='store_true', help="enable older version of split attention optimization that does not consume all the VRAM it can find")
42+
# parser.add_argument("--disable-opt-split-attention", action='store_true', help="force-disables cross-attention layer optimization")
43+
# parser.add_argument("--use-cpu", nargs='+', choices=['stable_diffusion', 'GFPGAN', 'BSRGAN', 'ESRGAN', 'SCUNet', 'CodeFormer'], help="use CPU as torch device for specified modules", default=[])
44+
# parser.add_argument("--listen", action='store_true', help="launch gradio with 0.0.0.0 as server name, allowing to respond to network requests")
45+
# parser.add_argument("--port", type=int, help="launch gradio with given server port, you need root/admin rights for ports < 1024, defaults to 7860 if available", default=None)
46+
# parser.add_argument("--show-negative-prompt", action='store_true', help="does not do anything", default=False)
47+
# parser.add_argument("--ui-config-file", type=str, help="filename to use for ui configuration", default=rootdir / 'ui-config.json')
48+
# parser.add_argument("--hide-ui-dir-config", action='store_true', help="hide directory configuration from webui", default=False)
49+
# parser.add_argument("--ui-settings-file", type=str, help="filename to use for ui settings", default=rootdir / 'config.json')
50+
# parser.add_argument("--gradio-debug", action='store_true', help="launch gradio with --debug option")
51+
# parser.add_argument("--gradio-auth", type=str, help='set gradio authentication like "username:password"; or comma-delimit multiple like "u1:p1,u2:p2,u3:p3"', default=None)
52+
# parser.add_argument("--gradio-img2img-tool", type=str, help='gradio image uploader tool: can be either editor for ctopping, or color-sketch for drawing', choices=["color-sketch", "editor"], default="editor")
53+
# parser.add_argument("--opt-channelslast", action='store_true', help="change memory type for stable diffusion to channels last")
54+
# parser.add_argument("--styles-file", type=str, help="filename to use for styles", default=rootdir / 'styles.csv')
55+
# parser.add_argument("--autolaunch", action='store_true', help="open the webui URL in the system's default browser upon launch", default=False)
56+
# parser.add_argument("--use-textbox-seed", action='store_true', help="use textbox for seeds in UI (no up/down, but possible to input long seeds)", default=False)
57+
# parser.add_argument("--disable-console-progressbars", action='store_true', help="do not output progressbars to console", default=False)
58+
# parser.add_argument('--vae-path', type=str, help='Path to Variational Autoencoders model', default=None)
59+
# parser.add_argument("--disable-safe-unpickle", action='store_true', help="disable checking pytorch models for malicious code", default=False)
5560

56-
cargs = None

core/devicelib.py

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@
33
import torch
44

55
from core import printing
6-
from core.cmdargs import cargs
76

87

98
def get_optimal_device():
@@ -50,12 +49,9 @@ def randn_without_seed(shape):
5049
return torch.randn(shape, device=device)
5150

5251

53-
def autocast(disable=False):
54-
if disable:
55-
return contextlib.nullcontext()
56-
57-
if dtype == torch.float32 or cargs.precision == "full":
58-
return contextlib.nullcontext()
52+
def autocast(enable=True):
53+
if not enable: return contextlib.nullcontext()
54+
if dtype == torch.float32: return contextlib.nullcontext() # or cargs.precision == "full"
5955

6056
return torch.autocast("cuda")
6157

@@ -79,7 +75,7 @@ def autocast(disable=False):
7975
# device_codeformer = \
8076
# (cpu if x in cargs.use_cpu else get_optimal_device()
8177
# for x
82-
# in ['StableDiffusion', 'GFPGAN', 'BSRGAN', 'ESRGAN', 'SCUNet', 'CodeFormer'])
78+
# in ['stable_diffusion', 'GFPGAN', 'BSRGAN', 'ESRGAN', 'SCUNet', 'CodeFormer'])
8379

8480
# device = device
8581

core/installing.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,8 @@ def git_clone(url, dir, name, commithash=None):
8282
if commithash is not None:
8383
run(f'"{git}" -C {dir} checkout {commithash}', None, "Couldn't checkout {name}'s hash: {commithash}")
8484

85+
sys.path.append(dir)
86+
8587

8688
def move_files(src_path: str, dest_path: str, ext_filter: str = None):
8789
try:

core/jobs.py

Lines changed: 34 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import uuid
2+
from abc import abstractmethod
23
from datetime import datetime
34

45
from tqdm import tqdm
@@ -14,9 +15,16 @@ class JobParams:
1415
def __init__(self, **kwargs):
1516
self.__dict__.update(kwargs)
1617

18+
@abstractmethod
19+
def get_plugin_impl(self):
20+
pass
21+
1722
def plugin(self):
1823
return self.job.plugin()
1924

25+
def on_start(self, job):
26+
pass
27+
2028

2129
class Job:
2230
def __init__(self, plugin_id: str, plugin_func: str, parameters: JobParams):
@@ -88,6 +96,8 @@ def process(self, job):
8896
self.queued.remove(job)
8997
self.processing.append(job)
9098

99+
job.p.on_start(job)
100+
91101
webui.emit('started_job', job.job_id)
92102

93103
def cancel(self, job):
@@ -168,15 +178,22 @@ def clear(self):
168178
self.tqdm = None
169179

170180

171-
def get_job(job_id):
181+
def get(job_id):
182+
"""
183+
Get a job by id.
184+
The job must be queued or processing.
185+
"""
186+
if isinstance(job_id, Job):
187+
return job_id
188+
172189
for job in queue.all:
173190
if job.job_id == job_id:
174191
return job
175192
raise Exception("Job not found")
176193

177194

178195
def finish(job_id):
179-
job = get_job(job_id)
196+
job = get(job_id)
180197

181198
job.update(1)
182199
queue.finish(job)
@@ -201,10 +218,10 @@ def enqueue(job):
201218
queue.enqueue(job)
202219

203220

204-
def new_job(plugid, jobname, parameters):
221+
def new_job(plugid, name, jobparams):
205222
global total_created
206223
total_created += 1
207-
j = Job(plugid, jobname, parameters)
224+
j = Job(plugid, name, jobparams)
208225
enqueue(j)
209226

210227
return j
@@ -214,3 +231,16 @@ def new_job(plugid, jobname, parameters):
214231
queue = JobQueue()
215232
total_created = 0
216233
tqdm_total = JobTQDM()
234+
235+
236+
def is_processing(id):
237+
"""
238+
Check if a job is processing (by ID)
239+
"""
240+
j = get(id)
241+
if j is not None:
242+
return j in queue.processing
243+
244+
245+
def is_any_processing():
246+
return len(queue.processing) > 0

core/modellib.py

Lines changed: 34 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,9 @@
33
from pathlib import Path
44
from urllib.parse import urlparse
55

6-
from basicsr.utils.download_util import load_file_from_url
7-
86
import torch
7+
from torch.hub import download_url_to_file, get_dir
8+
99
from core.devicelib import get_optimal_device
1010

1111
import pickle
@@ -114,6 +114,36 @@ def load_models(model_path: Path, model_url: Path = None, command_path: Path = N
114114

115115
return output
116116

117+
def load_file_from_url(url, model_dir=None, progress=True, file_name=None):
118+
"""Load file form http url, will download models if necessary.
119+
120+
Ref:https://github.com/1adrianb/face-alignment/blob/master/face_alignment/utils.py
121+
122+
Args:
123+
url (str): URL to be downloaded.
124+
model_dir (str): The path to save the downloaded model. Should be a full path. If None, use pytorch hub_dir.
125+
Default: None.
126+
progress (bool): Whether to show the download progress. Default: True.
127+
file_name (str): The downloaded file name. If None, use the file name in the url. Default: None.
128+
129+
Returns:
130+
str: The path to the downloaded file.
131+
"""
132+
if model_dir is None: # use the pytorch hub_dir
133+
hub_dir = get_dir()
134+
model_dir = os.path.join(hub_dir, 'checkpoints')
135+
136+
os.makedirs(model_dir, exist_ok=True)
137+
138+
parts = urlparse(url)
139+
filename = os.path.basename(parts.path)
140+
if file_name is not None:
141+
filename = file_name
142+
cached_file = os.path.abspath(os.path.join(model_dir, filename))
143+
if not os.path.exists(cached_file):
144+
print(f'Downloading: "{url}" to {cached_file}\n')
145+
download_url_to_file(url, cached_file, hash_prefix=None, progress=progress)
146+
return cached_file
117147

118148
# def load_upscalers():
119149
# sd = shared.script_path
@@ -217,11 +247,9 @@ def check_pt(filename):
217247

218248

219249
def load(filename, *args, **kwargs):
220-
import shared
221-
222250
try:
223-
if not shared.cmd_opts.disable_safe_unpickle:
224-
check_pt(filename)
251+
# if not shared.cmd_opts.disable_safe_unpickle:
252+
check_pt(filename)
225253

226254
except Exception:
227255
print(f"Error verifying pickled file from {filename}:", file=sys.stderr)

0 commit comments

Comments
 (0)