modelloader.py 6.9 KB

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