Path: blob/master/modules/modelloader.py
3055 views
from __future__ import annotations12import importlib3import logging4import os5from typing import TYPE_CHECKING6from urllib.parse import urlparse78import torch910from modules import shared11from modules.upscaler import Upscaler, UpscalerLanczos, UpscalerNearest, UpscalerNone1213if TYPE_CHECKING:14import spandrel1516logger = logging.getLogger(__name__)171819def load_file_from_url(20url: str,21*,22model_dir: str,23progress: bool = True,24file_name: str | None = None,25hash_prefix: str | None = None,26) -> str:27"""Download a file from `url` into `model_dir`, using the file present if possible.2829Returns 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, hash_prefix=hash_prefix)40return cached_file414243def 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:44"""45A one-and done loader to try finding the desired models in specified directories.4647@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 by52@param hash_prefix: the expected sha256 of the model_url53@return: A list of paths containing the desired model(s)54"""55output = []5657try:58places = []5960if command_path is not None and command_path != model_path:61pretrained_path = os.path.join(command_path, 'experiments/pretrained_models')62if os.path.exists(pretrained_path):63print(f"Appending path: {pretrained_path}")64places.append(pretrained_path)65elif os.path.exists(command_path):66places.append(command_path)6768places.append(model_path)6970for place in places:71for full_path in shared.walk_files(place, allowed_extensions=ext_filter):72if os.path.islink(full_path) and not os.path.exists(full_path):73print(f"Skipping broken symlink: {full_path}")74continue75if ext_blacklist is not None and any(full_path.endswith(x) for x in ext_blacklist):76continue77if full_path not in output:78output.append(full_path)7980if model_url is not None and len(output) == 0:81if download_name is not None:82output.append(load_file_from_url(model_url, model_dir=places[0], file_name=download_name, hash_prefix=hash_prefix))83else:84output.append(model_url)8586except Exception:87pass8889return output909192def friendly_name(file: str):93if file.startswith("http"):94file = urlparse(file).path9596file = os.path.basename(file)97model_name, extension = os.path.splitext(file)98return model_name99100101def load_upscalers():102# We can only do this 'magic' method to dynamically load upscalers if they are referenced,103# so we'll try to import any _model.py files before looking in __subclasses__104modules_dir = os.path.join(shared.script_path, "modules")105for file in os.listdir(modules_dir):106if "_model.py" in file:107model_name = file.replace("_model.py", "")108full_model = f"modules.{model_name}_model"109try:110importlib.import_module(full_model)111except Exception:112pass113114data = []115commandline_options = vars(shared.cmd_opts)116117# some of upscaler classes will not go away after reloading their modules, and we'll end118# up with two copies of those classes. The newest copy will always be the last in the list,119# so we go from end to beginning and ignore duplicates120used_classes = {}121for cls in reversed(Upscaler.__subclasses__()):122classname = str(cls)123if classname not in used_classes:124used_classes[classname] = cls125126for cls in reversed(used_classes.values()):127name = cls.__name__128cmd_name = f"{name.lower().replace('upscaler', '')}_models_path"129commandline_model_path = commandline_options.get(cmd_name, None)130scaler = cls(commandline_model_path)131scaler.user_path = commandline_model_path132scaler.model_download_path = commandline_model_path or scaler.model_path133data += scaler.scalers134135shared.sd_upscalers = sorted(136data,137# Special case for UpscalerNone keeps it at the beginning of the list.138key=lambda x: x.name.lower() if not isinstance(x.scaler, (UpscalerNone, UpscalerLanczos, UpscalerNearest)) else ""139)140141# None: not loaded, False: failed to load, True: loaded142_spandrel_extra_init_state = None143144145def _init_spandrel_extra_archs() -> None:146"""147Try to initialize `spandrel_extra_archs` (exactly once).148"""149global _spandrel_extra_init_state150if _spandrel_extra_init_state is not None:151return152153try:154import spandrel155import spandrel_extra_arches156spandrel.MAIN_REGISTRY.add(*spandrel_extra_arches.EXTRA_REGISTRY)157_spandrel_extra_init_state = True158except Exception:159logger.warning("Failed to load spandrel_extra_arches", exc_info=True)160_spandrel_extra_init_state = False161162163def load_spandrel_model(164path: str | os.PathLike,165*,166device: str | torch.device | None,167prefer_half: bool = False,168dtype: str | torch.dtype | None = None,169expected_architecture: str | None = None,170) -> spandrel.ModelDescriptor:171global _spandrel_extra_init_state172173import spandrel174_init_spandrel_extra_archs()175176model_descriptor = spandrel.ModelLoader(device=device).load_from_file(str(path))177arch = model_descriptor.architecture178if expected_architecture and arch.name != expected_architecture:179logger.warning(180f"Model {path!r} is not a {expected_architecture!r} model (got {arch.name!r})",181)182half = False183if prefer_half:184if model_descriptor.supports_half:185model_descriptor.model.half()186half = True187else:188logger.info("Model %s does not support half precision, ignoring --half", path)189if dtype:190model_descriptor.model.to(dtype=dtype)191model_descriptor.model.eval()192logger.debug(193"Loaded %s from %s (device=%s, half=%s, dtype=%s)",194arch, path, device, half, dtype,195)196return model_descriptor197198199