modelloader.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147
  1. import glob
  2. import os
  3. import shutil
  4. import importlib
  5. from urllib.parse import urlparse
  6. from basicsr.utils.download_util import load_file_from_url
  7. from modules import shared
  8. from modules.upscaler import Upscaler
  9. from modules.paths import script_path, models_path
  10. def load_models(model_path: str, model_url: str = None, command_path: str = None, ext_filter=None, download_name=None) -> list:
  11. """
  12. A one-and done loader to try finding the desired models in specified directories.
  13. @param download_name: Specify to download from model_url immediately.
  14. @param model_url: If no other models are found, this will be downloaded on upscale.
  15. @param model_path: The location to store/find models in.
  16. @param command_path: A command-line argument to search for models in first.
  17. @param ext_filter: An optional list of filename extensions to filter by
  18. @return: A list of paths containing the desired model(s)
  19. """
  20. output = []
  21. if ext_filter is None:
  22. ext_filter = []
  23. try:
  24. places = []
  25. if command_path is not None and command_path != model_path:
  26. pretrained_path = os.path.join(command_path, 'experiments/pretrained_models')
  27. if os.path.exists(pretrained_path):
  28. print(f"Appending path: {pretrained_path}")
  29. places.append(pretrained_path)
  30. elif os.path.exists(command_path):
  31. places.append(command_path)
  32. places.append(model_path)
  33. for place in places:
  34. if os.path.exists(place):
  35. for file in glob.iglob(place + '**/**', recursive=True):
  36. full_path = file
  37. if os.path.isdir(full_path):
  38. continue
  39. if len(ext_filter) != 0:
  40. model_name, extension = os.path.splitext(file)
  41. if extension not in ext_filter:
  42. continue
  43. if file 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. dl = load_file_from_url(model_url, model_path, True, download_name)
  48. output.append(dl)
  49. else:
  50. output.append(model_url)
  51. except Exception:
  52. pass
  53. return output
  54. def friendly_name(file: str):
  55. if "http" in file:
  56. file = urlparse(file).path
  57. file = os.path.basename(file)
  58. model_name, extension = os.path.splitext(file)
  59. return model_name
  60. def cleanup_models():
  61. # This code could probably be more efficient if we used a tuple list or something to store the src/destinations
  62. # and then enumerate that, but this works for now. In the future, it'd be nice to just have every "model" scaler
  63. # somehow auto-register and just do these things...
  64. root_path = script_path
  65. src_path = models_path
  66. dest_path = os.path.join(models_path, "Stable-diffusion")
  67. move_files(src_path, dest_path, ".ckpt")
  68. move_files(src_path, dest_path, ".safetensors")
  69. src_path = os.path.join(root_path, "ESRGAN")
  70. dest_path = os.path.join(models_path, "ESRGAN")
  71. move_files(src_path, dest_path)
  72. src_path = os.path.join(models_path, "BSRGAN")
  73. dest_path = os.path.join(models_path, "ESRGAN")
  74. move_files(src_path, dest_path, ".pth")
  75. src_path = os.path.join(root_path, "gfpgan")
  76. dest_path = os.path.join(models_path, "GFPGAN")
  77. move_files(src_path, dest_path)
  78. src_path = os.path.join(root_path, "SwinIR")
  79. dest_path = os.path.join(models_path, "SwinIR")
  80. move_files(src_path, dest_path)
  81. src_path = os.path.join(root_path, "repositories/latent-diffusion/experiments/pretrained_models/")
  82. dest_path = os.path.join(models_path, "LDSR")
  83. move_files(src_path, dest_path)
  84. def move_files(src_path: str, dest_path: str, ext_filter: str = None):
  85. try:
  86. if not os.path.exists(dest_path):
  87. os.makedirs(dest_path)
  88. if os.path.exists(src_path):
  89. for file in os.listdir(src_path):
  90. fullpath = os.path.join(src_path, file)
  91. if os.path.isfile(fullpath):
  92. if ext_filter is not None:
  93. if ext_filter not in file:
  94. continue
  95. print(f"Moving {file} from {src_path} to {dest_path}.")
  96. try:
  97. shutil.move(fullpath, dest_path)
  98. except:
  99. pass
  100. if len(os.listdir(src_path)) == 0:
  101. print(f"Removing empty folder: {src_path}")
  102. shutil.rmtree(src_path, True)
  103. except:
  104. pass
  105. def load_upscalers():
  106. # We can only do this 'magic' method to dynamically load upscalers if they are referenced,
  107. # so we'll try to import any _model.py files before looking in __subclasses__
  108. modules_dir = os.path.join(shared.script_path, "modules")
  109. for file in os.listdir(modules_dir):
  110. if "_model.py" in file:
  111. model_name = file.replace("_model.py", "")
  112. full_model = f"modules.{model_name}_model"
  113. try:
  114. importlib.import_module(full_model)
  115. except:
  116. pass
  117. datas = []
  118. commandline_options = vars(shared.cmd_opts)
  119. for cls in Upscaler.__subclasses__():
  120. name = cls.__name__
  121. cmd_name = f"{name.lower().replace('upscaler', '')}_models_path"
  122. scaler = cls(commandline_options.get(cmd_name, None))
  123. datas += scaler.scalers
  124. shared.sd_upscalers = datas