2023-05-29 14:34:26 +08:00
|
|
|
from __future__ import annotations
|
|
|
|
|
2023-12-31 06:04:47 +08:00
|
|
|
import importlib
|
2023-12-25 20:43:51 +08:00
|
|
|
import logging
|
2022-09-26 22:29:50 +08:00
|
|
|
import os
|
2023-12-31 06:04:47 +08:00
|
|
|
from typing import TYPE_CHECKING
|
2022-09-26 22:29:50 +08:00
|
|
|
from urllib.parse import urlparse
|
|
|
|
|
2023-12-30 22:37:03 +08:00
|
|
|
import torch
|
|
|
|
|
2022-09-30 06:46:23 +08:00
|
|
|
from modules import shared
|
2023-03-07 02:18:35 +08:00
|
|
|
from modules.upscaler import Upscaler, UpscalerLanczos, UpscalerNearest, UpscalerNone
|
2022-09-26 23:27:18 +08:00
|
|
|
|
2023-12-31 06:04:47 +08:00
|
|
|
if TYPE_CHECKING:
|
|
|
|
import spandrel
|
2022-09-26 22:29:50 +08:00
|
|
|
|
2023-12-25 20:43:51 +08:00
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
|
|
|
2023-05-29 14:34:26 +08:00
|
|
|
def load_file_from_url(
|
|
|
|
url: str,
|
|
|
|
*,
|
|
|
|
model_dir: str,
|
|
|
|
progress: bool = True,
|
|
|
|
file_name: str | None = None,
|
2024-04-23 02:08:09 +08:00
|
|
|
hash_prefix: str | None = None,
|
2023-05-29 14:34:26 +08:00
|
|
|
) -> str:
|
|
|
|
"""Download a file from `url` into `model_dir`, using the file present if possible.
|
|
|
|
|
|
|
|
Returns the path to the downloaded file.
|
|
|
|
"""
|
|
|
|
os.makedirs(model_dir, exist_ok=True)
|
|
|
|
if not file_name:
|
|
|
|
parts = urlparse(url)
|
|
|
|
file_name = os.path.basename(parts.path)
|
|
|
|
cached_file = os.path.abspath(os.path.join(model_dir, file_name))
|
|
|
|
if not os.path.exists(cached_file):
|
|
|
|
print(f'Downloading: "{url}" to {cached_file}\n')
|
|
|
|
from torch.hub import download_url_to_file
|
2024-04-23 02:08:09 +08:00
|
|
|
download_url_to_file(url, cached_file, progress=progress, hash_prefix=hash_prefix)
|
2023-05-29 14:34:26 +08:00
|
|
|
return cached_file
|
|
|
|
|
|
|
|
|
2024-04-23 02:08:09 +08:00
|
|
|
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:
|
2022-09-26 22:29:50 +08:00
|
|
|
"""
|
|
|
|
A one-and done loader to try finding the desired models in specified directories.
|
|
|
|
|
2022-09-30 06:46:23 +08:00
|
|
|
@param download_name: Specify to download from model_url immediately.
|
|
|
|
@param model_url: If no other models are found, this will be downloaded on upscale.
|
2022-09-26 22:29:50 +08:00
|
|
|
@param model_path: The location to store/find models in.
|
|
|
|
@param command_path: A command-line argument to search for models in first.
|
|
|
|
@param ext_filter: An optional list of filename extensions to filter by
|
2024-04-23 02:08:09 +08:00
|
|
|
@param hash_prefix: the expected sha256 of the model_url
|
2022-09-26 22:29:50 +08:00
|
|
|
@return: A list of paths containing the desired model(s)
|
|
|
|
"""
|
2022-09-30 06:46:23 +08:00
|
|
|
output = []
|
|
|
|
|
2022-09-26 22:29:50 +08:00
|
|
|
try:
|
|
|
|
places = []
|
2022-09-30 16:42:40 +08:00
|
|
|
|
2022-09-26 22:29:50 +08:00
|
|
|
if command_path is not None and command_path != model_path:
|
|
|
|
pretrained_path = os.path.join(command_path, 'experiments/pretrained_models')
|
|
|
|
if os.path.exists(pretrained_path):
|
2022-09-30 06:46:23 +08:00
|
|
|
print(f"Appending path: {pretrained_path}")
|
2022-09-26 22:29:50 +08:00
|
|
|
places.append(pretrained_path)
|
|
|
|
elif os.path.exists(command_path):
|
|
|
|
places.append(command_path)
|
2022-09-30 16:42:40 +08:00
|
|
|
|
2022-09-26 22:29:50 +08:00
|
|
|
places.append(model_path)
|
2022-09-30 16:42:40 +08:00
|
|
|
|
2022-09-26 22:29:50 +08:00
|
|
|
for place in places:
|
2023-05-08 16:33:45 +08:00
|
|
|
for full_path in shared.walk_files(place, allowed_extensions=ext_filter):
|
|
|
|
if os.path.islink(full_path) and not os.path.exists(full_path):
|
|
|
|
print(f"Skipping broken symlink: {full_path}")
|
|
|
|
continue
|
2023-05-10 16:05:02 +08:00
|
|
|
if ext_blacklist is not None and any(full_path.endswith(x) for x in ext_blacklist):
|
2023-05-08 16:33:45 +08:00
|
|
|
continue
|
|
|
|
if full_path not in output:
|
|
|
|
output.append(full_path)
|
2022-09-30 16:42:40 +08:00
|
|
|
|
2022-09-30 06:46:23 +08:00
|
|
|
if model_url is not None and len(output) == 0:
|
|
|
|
if download_name is not None:
|
2024-04-23 02:08:09 +08:00
|
|
|
output.append(load_file_from_url(model_url, model_dir=places[0], file_name=download_name, hash_prefix=hash_prefix))
|
2022-09-26 22:29:50 +08:00
|
|
|
else:
|
2022-09-30 06:46:23 +08:00
|
|
|
output.append(model_url)
|
2022-09-30 16:42:40 +08:00
|
|
|
|
|
|
|
except Exception:
|
2022-09-26 22:29:50 +08:00
|
|
|
pass
|
2022-09-30 16:42:40 +08:00
|
|
|
|
2022-09-30 06:46:23 +08:00
|
|
|
return output
|
2022-09-26 22:29:50 +08:00
|
|
|
|
|
|
|
|
|
|
|
def friendly_name(file: str):
|
2023-05-29 14:41:36 +08:00
|
|
|
if file.startswith("http"):
|
2022-09-26 22:29:50 +08:00
|
|
|
file = urlparse(file).path
|
|
|
|
|
|
|
|
file = os.path.basename(file)
|
|
|
|
model_name, extension = os.path.splitext(file)
|
|
|
|
return model_name
|
2022-09-26 23:27:18 +08:00
|
|
|
|
|
|
|
|
2022-09-30 06:46:23 +08:00
|
|
|
def load_upscalers():
|
2022-10-01 04:26:18 +08:00
|
|
|
# We can only do this 'magic' method to dynamically load upscalers if they are referenced,
|
|
|
|
# so we'll try to import any _model.py files before looking in __subclasses__
|
2022-12-03 23:06:33 +08:00
|
|
|
modules_dir = os.path.join(shared.script_path, "modules")
|
2022-10-01 04:26:18 +08:00
|
|
|
for file in os.listdir(modules_dir):
|
|
|
|
if "_model.py" in file:
|
|
|
|
model_name = file.replace("_model.py", "")
|
|
|
|
full_model = f"modules.{model_name}_model"
|
|
|
|
try:
|
|
|
|
importlib.import_module(full_model)
|
2023-05-10 13:25:25 +08:00
|
|
|
except Exception:
|
2022-10-01 04:26:18 +08:00
|
|
|
pass
|
2022-12-03 23:06:33 +08:00
|
|
|
|
2024-03-04 14:37:23 +08:00
|
|
|
data = []
|
2022-12-03 23:06:33 +08:00
|
|
|
commandline_options = vars(shared.cmd_opts)
|
2023-01-03 23:38:21 +08:00
|
|
|
|
2023-05-11 04:41:08 +08:00
|
|
|
# some of upscaler classes will not go away after reloading their modules, and we'll end
|
|
|
|
# up with two copies of those classes. The newest copy will always be the last in the list,
|
|
|
|
# so we go from end to beginning and ignore duplicates
|
|
|
|
used_classes = {}
|
|
|
|
for cls in reversed(Upscaler.__subclasses__()):
|
|
|
|
classname = str(cls)
|
|
|
|
if classname not in used_classes:
|
|
|
|
used_classes[classname] = cls
|
|
|
|
|
|
|
|
for cls in reversed(used_classes.values()):
|
2022-09-30 06:46:23 +08:00
|
|
|
name = cls.__name__
|
2022-10-01 04:26:18 +08:00
|
|
|
cmd_name = f"{name.lower().replace('upscaler', '')}_models_path"
|
2023-05-19 14:09:00 +08:00
|
|
|
commandline_model_path = commandline_options.get(cmd_name, None)
|
|
|
|
scaler = cls(commandline_model_path)
|
|
|
|
scaler.user_path = commandline_model_path
|
|
|
|
scaler.model_download_path = commandline_model_path or scaler.model_path
|
2024-03-04 14:37:23 +08:00
|
|
|
data += scaler.scalers
|
2022-09-30 06:46:23 +08:00
|
|
|
|
2023-02-25 03:22:58 +08:00
|
|
|
shared.sd_upscalers = sorted(
|
2024-03-04 14:37:23 +08:00
|
|
|
data,
|
2023-02-25 03:22:58 +08:00
|
|
|
# Special case for UpscalerNone keeps it at the beginning of the list.
|
2023-03-07 02:18:35 +08:00
|
|
|
key=lambda x: x.name.lower() if not isinstance(x.scaler, (UpscalerNone, UpscalerLanczos, UpscalerNearest)) else ""
|
2023-02-25 03:22:58 +08:00
|
|
|
)
|
2023-12-25 20:43:51 +08:00
|
|
|
|
2024-07-04 13:43:48 +08:00
|
|
|
# None: not loaded, False: failed to load, True: loaded
|
|
|
|
_spandrel_extra_init_state = None
|
|
|
|
|
|
|
|
|
|
|
|
def _init_spandrel_extra_archs() -> None:
|
|
|
|
"""
|
|
|
|
Try to initialize `spandrel_extra_archs` (exactly once).
|
|
|
|
"""
|
|
|
|
global _spandrel_extra_init_state
|
|
|
|
if _spandrel_extra_init_state is not None:
|
|
|
|
return
|
|
|
|
|
|
|
|
try:
|
|
|
|
import spandrel
|
|
|
|
import spandrel_extra_arches
|
|
|
|
spandrel.MAIN_REGISTRY.add(*spandrel_extra_arches.EXTRA_REGISTRY)
|
|
|
|
_spandrel_extra_init_state = True
|
|
|
|
except Exception:
|
|
|
|
logger.warning("Failed to load spandrel_extra_arches", exc_info=True)
|
|
|
|
_spandrel_extra_init_state = False
|
|
|
|
|
2023-12-25 20:43:51 +08:00
|
|
|
|
2023-12-30 22:37:03 +08:00
|
|
|
def load_spandrel_model(
|
2024-01-01 01:52:32 +08:00
|
|
|
path: str | os.PathLike,
|
2023-12-30 22:37:03 +08:00
|
|
|
*,
|
|
|
|
device: str | torch.device | None,
|
2024-01-01 01:52:32 +08:00
|
|
|
prefer_half: bool = False,
|
2023-12-31 06:09:51 +08:00
|
|
|
dtype: str | torch.dtype | None = None,
|
2023-12-30 22:37:03 +08:00
|
|
|
expected_architecture: str | None = None,
|
2023-12-31 06:04:47 +08:00
|
|
|
) -> spandrel.ModelDescriptor:
|
2024-07-04 13:43:48 +08:00
|
|
|
global _spandrel_extra_init_state
|
|
|
|
|
2023-12-25 20:43:51 +08:00
|
|
|
import spandrel
|
2024-07-04 13:43:48 +08:00
|
|
|
_init_spandrel_extra_archs()
|
|
|
|
|
2024-01-01 01:52:32 +08:00
|
|
|
model_descriptor = spandrel.ModelLoader(device=device).load_from_file(str(path))
|
2024-07-04 13:43:48 +08:00
|
|
|
arch = model_descriptor.architecture
|
|
|
|
if expected_architecture and arch.name != expected_architecture:
|
2023-12-31 03:05:59 +08:00
|
|
|
logger.warning(
|
2024-07-04 13:43:48 +08:00
|
|
|
f"Model {path!r} is not a {expected_architecture!r} model (got {arch.name!r})",
|
2023-12-31 03:05:59 +08:00
|
|
|
)
|
2024-01-01 01:52:32 +08:00
|
|
|
half = False
|
|
|
|
if prefer_half:
|
|
|
|
if model_descriptor.supports_half:
|
|
|
|
model_descriptor.model.half()
|
|
|
|
half = True
|
|
|
|
else:
|
|
|
|
logger.info("Model %s does not support half precision, ignoring --half", path)
|
2023-12-25 20:43:51 +08:00
|
|
|
if dtype:
|
2023-12-31 06:04:47 +08:00
|
|
|
model_descriptor.model.to(dtype=dtype)
|
|
|
|
model_descriptor.model.eval()
|
2024-01-01 01:52:32 +08:00
|
|
|
logger.debug(
|
|
|
|
"Loaded %s from %s (device=%s, half=%s, dtype=%s)",
|
2024-07-04 13:43:48 +08:00
|
|
|
arch, path, device, half, dtype,
|
2024-01-01 01:52:32 +08:00
|
|
|
)
|
2023-12-31 06:04:47 +08:00
|
|
|
return model_descriptor
|