stable-diffusion-webui
169 строк · 6.0 Кб
1from __future__ import annotations2
3import importlib4import logging5import os6from typing import TYPE_CHECKING7from urllib.parse import urlparse8
9import torch10
11from modules import shared12from modules.upscaler import Upscaler, UpscalerLanczos, UpscalerNearest, UpscalerNone13
14if TYPE_CHECKING:15import spandrel16
17logger = logging.getLogger(__name__)18
19
20def load_file_from_url(21url: str,22*,23model_dir: str,24progress: bool = True,25file_name: str | None = None,26) -> str:27"""Download a file from `url` into `model_dir`, using the file present if possible.28
29Returns the path to the downloaded file.
30"""
31os.makedirs(model_dir, exist_ok=True)32if not file_name:33parts = urlparse(url)34file_name = os.path.basename(parts.path)35cached_file = os.path.abspath(os.path.join(model_dir, file_name))36if not os.path.exists(cached_file):37print(f'Downloading: "{url}" to {cached_file}\n')38from torch.hub import download_url_to_file39download_url_to_file(url, cached_file, progress=progress)40return cached_file41
42
43def load_models(model_path: str, model_url: str = None, command_path: str = None, ext_filter=None, download_name=None, ext_blacklist=None) -> list:44"""45A one-and done loader to try finding the desired models in specified directories.
46
47@param download_name: Specify to download from model_url immediately.
48@param model_url: If no other models are found, this will be downloaded on upscale.
49@param model_path: The location to store/find models in.
50@param command_path: A command-line argument to search for models in first.
51@param ext_filter: An optional list of filename extensions to filter by
52@return: A list of paths containing the desired model(s)
53"""
54output = []55
56try:57places = []58
59if command_path is not None and command_path != model_path:60pretrained_path = os.path.join(command_path, 'experiments/pretrained_models')61if os.path.exists(pretrained_path):62print(f"Appending path: {pretrained_path}")63places.append(pretrained_path)64elif os.path.exists(command_path):65places.append(command_path)66
67places.append(model_path)68
69for place in places:70for full_path in shared.walk_files(place, allowed_extensions=ext_filter):71if os.path.islink(full_path) and not os.path.exists(full_path):72print(f"Skipping broken symlink: {full_path}")73continue74if ext_blacklist is not None and any(full_path.endswith(x) for x in ext_blacklist):75continue76if full_path not in output:77output.append(full_path)78
79if model_url is not None and len(output) == 0:80if download_name is not None:81output.append(load_file_from_url(model_url, model_dir=places[0], file_name=download_name))82else:83output.append(model_url)84
85except Exception:86pass87
88return output89
90
91def friendly_name(file: str):92if file.startswith("http"):93file = urlparse(file).path94
95file = os.path.basename(file)96model_name, extension = os.path.splitext(file)97return model_name98
99
100def load_upscalers():101# We can only do this 'magic' method to dynamically load upscalers if they are referenced,102# so we'll try to import any _model.py files before looking in __subclasses__103modules_dir = os.path.join(shared.script_path, "modules")104for file in os.listdir(modules_dir):105if "_model.py" in file:106model_name = file.replace("_model.py", "")107full_model = f"modules.{model_name}_model"108try:109importlib.import_module(full_model)110except Exception:111pass112
113datas = []114commandline_options = vars(shared.cmd_opts)115
116# some of upscaler classes will not go away after reloading their modules, and we'll end117# up with two copies of those classes. The newest copy will always be the last in the list,118# so we go from end to beginning and ignore duplicates119used_classes = {}120for cls in reversed(Upscaler.__subclasses__()):121classname = str(cls)122if classname not in used_classes:123used_classes[classname] = cls124
125for cls in reversed(used_classes.values()):126name = cls.__name__127cmd_name = f"{name.lower().replace('upscaler', '')}_models_path"128commandline_model_path = commandline_options.get(cmd_name, None)129scaler = cls(commandline_model_path)130scaler.user_path = commandline_model_path131scaler.model_download_path = commandline_model_path or scaler.model_path132datas += scaler.scalers133
134shared.sd_upscalers = sorted(135datas,136# Special case for UpscalerNone keeps it at the beginning of the list.137key=lambda x: x.name.lower() if not isinstance(x.scaler, (UpscalerNone, UpscalerLanczos, UpscalerNearest)) else ""138)139
140
141def load_spandrel_model(142path: str | os.PathLike,143*,144device: str | torch.device | None,145prefer_half: bool = False,146dtype: str | torch.dtype | None = None,147expected_architecture: str | None = None,148) -> spandrel.ModelDescriptor:149import spandrel150model_descriptor = spandrel.ModelLoader(device=device).load_from_file(str(path))151if expected_architecture and model_descriptor.architecture != expected_architecture:152logger.warning(153f"Model {path!r} is not a {expected_architecture!r} model (got {model_descriptor.architecture!r})",154)155half = False156if prefer_half:157if model_descriptor.supports_half:158model_descriptor.model.half()159half = True160else:161logger.info("Model %s does not support half precision, ignoring --half", path)162if dtype:163model_descriptor.model.to(dtype=dtype)164model_descriptor.model.eval()165logger.debug(166"Loaded %s from %s (device=%s, half=%s, dtype=%s)",167model_descriptor, path, device, half, dtype,168)169return model_descriptor170