Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
automatic1111
GitHub Repository: automatic1111/stable-diffusion-webui
Path: blob/master/modules/modelloader.py
3055 views
1
from __future__ import annotations
2
3
import importlib
4
import logging
5
import os
6
from typing import TYPE_CHECKING
7
from urllib.parse import urlparse
8
9
import torch
10
11
from modules import shared
12
from modules.upscaler import Upscaler, UpscalerLanczos, UpscalerNearest, UpscalerNone
13
14
if TYPE_CHECKING:
15
import spandrel
16
17
logger = logging.getLogger(__name__)
18
19
20
def load_file_from_url(
21
url: str,
22
*,
23
model_dir: str,
24
progress: bool = True,
25
file_name: str | None = None,
26
hash_prefix: str | None = None,
27
) -> str:
28
"""Download a file from `url` into `model_dir`, using the file present if possible.
29
30
Returns the path to the downloaded file.
31
"""
32
os.makedirs(model_dir, exist_ok=True)
33
if not file_name:
34
parts = urlparse(url)
35
file_name = os.path.basename(parts.path)
36
cached_file = os.path.abspath(os.path.join(model_dir, file_name))
37
if not os.path.exists(cached_file):
38
print(f'Downloading: "{url}" to {cached_file}\n')
39
from torch.hub import download_url_to_file
40
download_url_to_file(url, cached_file, progress=progress, hash_prefix=hash_prefix)
41
return cached_file
42
43
44
def load_models(model_path: str, model_url: str = None, command_path: str = None, ext_filter=None, download_name=None, ext_blacklist=None, hash_prefix=None) -> list:
45
"""
46
A one-and done loader to try finding the desired models in specified directories.
47
48
@param download_name: Specify to download from model_url immediately.
49
@param model_url: If no other models are found, this will be downloaded on upscale.
50
@param model_path: The location to store/find models in.
51
@param command_path: A command-line argument to search for models in first.
52
@param ext_filter: An optional list of filename extensions to filter by
53
@param hash_prefix: the expected sha256 of the model_url
54
@return: A list of paths containing the desired model(s)
55
"""
56
output = []
57
58
try:
59
places = []
60
61
if command_path is not None and command_path != model_path:
62
pretrained_path = os.path.join(command_path, 'experiments/pretrained_models')
63
if os.path.exists(pretrained_path):
64
print(f"Appending path: {pretrained_path}")
65
places.append(pretrained_path)
66
elif os.path.exists(command_path):
67
places.append(command_path)
68
69
places.append(model_path)
70
71
for place in places:
72
for full_path in shared.walk_files(place, allowed_extensions=ext_filter):
73
if os.path.islink(full_path) and not os.path.exists(full_path):
74
print(f"Skipping broken symlink: {full_path}")
75
continue
76
if ext_blacklist is not None and any(full_path.endswith(x) for x in ext_blacklist):
77
continue
78
if full_path not in output:
79
output.append(full_path)
80
81
if model_url is not None and len(output) == 0:
82
if download_name is not None:
83
output.append(load_file_from_url(model_url, model_dir=places[0], file_name=download_name, hash_prefix=hash_prefix))
84
else:
85
output.append(model_url)
86
87
except Exception:
88
pass
89
90
return output
91
92
93
def friendly_name(file: str):
94
if file.startswith("http"):
95
file = urlparse(file).path
96
97
file = os.path.basename(file)
98
model_name, extension = os.path.splitext(file)
99
return model_name
100
101
102
def load_upscalers():
103
# We can only do this 'magic' method to dynamically load upscalers if they are referenced,
104
# so we'll try to import any _model.py files before looking in __subclasses__
105
modules_dir = os.path.join(shared.script_path, "modules")
106
for file in os.listdir(modules_dir):
107
if "_model.py" in file:
108
model_name = file.replace("_model.py", "")
109
full_model = f"modules.{model_name}_model"
110
try:
111
importlib.import_module(full_model)
112
except Exception:
113
pass
114
115
data = []
116
commandline_options = vars(shared.cmd_opts)
117
118
# some of upscaler classes will not go away after reloading their modules, and we'll end
119
# up with two copies of those classes. The newest copy will always be the last in the list,
120
# so we go from end to beginning and ignore duplicates
121
used_classes = {}
122
for cls in reversed(Upscaler.__subclasses__()):
123
classname = str(cls)
124
if classname not in used_classes:
125
used_classes[classname] = cls
126
127
for cls in reversed(used_classes.values()):
128
name = cls.__name__
129
cmd_name = f"{name.lower().replace('upscaler', '')}_models_path"
130
commandline_model_path = commandline_options.get(cmd_name, None)
131
scaler = cls(commandline_model_path)
132
scaler.user_path = commandline_model_path
133
scaler.model_download_path = commandline_model_path or scaler.model_path
134
data += scaler.scalers
135
136
shared.sd_upscalers = sorted(
137
data,
138
# Special case for UpscalerNone keeps it at the beginning of the list.
139
key=lambda x: x.name.lower() if not isinstance(x.scaler, (UpscalerNone, UpscalerLanczos, UpscalerNearest)) else ""
140
)
141
142
# None: not loaded, False: failed to load, True: loaded
143
_spandrel_extra_init_state = None
144
145
146
def _init_spandrel_extra_archs() -> None:
147
"""
148
Try to initialize `spandrel_extra_archs` (exactly once).
149
"""
150
global _spandrel_extra_init_state
151
if _spandrel_extra_init_state is not None:
152
return
153
154
try:
155
import spandrel
156
import spandrel_extra_arches
157
spandrel.MAIN_REGISTRY.add(*spandrel_extra_arches.EXTRA_REGISTRY)
158
_spandrel_extra_init_state = True
159
except Exception:
160
logger.warning("Failed to load spandrel_extra_arches", exc_info=True)
161
_spandrel_extra_init_state = False
162
163
164
def load_spandrel_model(
165
path: str | os.PathLike,
166
*,
167
device: str | torch.device | None,
168
prefer_half: bool = False,
169
dtype: str | torch.dtype | None = None,
170
expected_architecture: str | None = None,
171
) -> spandrel.ModelDescriptor:
172
global _spandrel_extra_init_state
173
174
import spandrel
175
_init_spandrel_extra_archs()
176
177
model_descriptor = spandrel.ModelLoader(device=device).load_from_file(str(path))
178
arch = model_descriptor.architecture
179
if expected_architecture and arch.name != expected_architecture:
180
logger.warning(
181
f"Model {path!r} is not a {expected_architecture!r} model (got {arch.name!r})",
182
)
183
half = False
184
if prefer_half:
185
if model_descriptor.supports_half:
186
model_descriptor.model.half()
187
half = True
188
else:
189
logger.info("Model %s does not support half precision, ignoring --half", path)
190
if dtype:
191
model_descriptor.model.to(dtype=dtype)
192
model_descriptor.model.eval()
193
logger.debug(
194
"Loaded %s from %s (device=%s, half=%s, dtype=%s)",
195
arch, path, device, half, dtype,
196
)
197
return model_descriptor
198
199