modelloader.py 6.2 KB

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