Path: blob/master/extensions-builtin/SwinIR/scripts/swinir_model.py
2448 views
import logging1import sys23import torch4from PIL import Image56from modules import devices, modelloader, script_callbacks, shared, upscaler_utils7from modules.upscaler import Upscaler, UpscalerData89SWINIR_MODEL_URL = "https://github.com/JingyunLiang/SwinIR/releases/download/v0.0/003_realSR_BSRGAN_DFOWMFC_s64w8_SwinIR-L_x4_GAN.pth"1011logger = logging.getLogger(__name__)121314class UpscalerSwinIR(Upscaler):15def __init__(self, dirname):16self._cached_model = None # keep the model when SWIN_torch_compile is on to prevent re-compile every runs17self._cached_model_config = None # to clear '_cached_model' when changing model (v1/v2) or settings18self.name = "SwinIR"19self.model_url = SWINIR_MODEL_URL20self.model_name = "SwinIR 4x"21self.user_path = dirname22super().__init__()23scalers = []24model_files = self.find_models(ext_filter=[".pt", ".pth"])25for model in model_files:26if model.startswith("http"):27name = self.model_name28else:29name = modelloader.friendly_name(model)30model_data = UpscalerData(name, model, self)31scalers.append(model_data)32self.scalers = scalers3334def do_upscale(self, img: Image.Image, model_file: str) -> Image.Image:35current_config = (model_file, shared.opts.SWIN_tile)3637if self._cached_model_config == current_config:38model = self._cached_model39else:40try:41model = self.load_model(model_file)42except Exception as e:43print(f"Failed loading SwinIR model {model_file}: {e}", file=sys.stderr)44return img45self._cached_model = model46self._cached_model_config = current_config4748img = upscaler_utils.upscale_2(49img,50model,51tile_size=shared.opts.SWIN_tile,52tile_overlap=shared.opts.SWIN_tile_overlap,53scale=model.scale,54desc="SwinIR",55)56devices.torch_gc()57return img5859def load_model(self, path, scale=4):60if path.startswith("http"):61filename = modelloader.load_file_from_url(62url=path,63model_dir=self.model_download_path,64file_name=f"{self.model_name.replace(' ', '_')}.pth",65)66else:67filename = path6869model_descriptor = modelloader.load_spandrel_model(70filename,71device=self._get_device(),72prefer_half=(devices.dtype == torch.float16),73expected_architecture="SwinIR",74)75if getattr(shared.opts, 'SWIN_torch_compile', False):76try:77model_descriptor.model.compile()78except Exception:79logger.warning("Failed to compile SwinIR model, fallback to JIT", exc_info=True)80return model_descriptor8182def _get_device(self):83return devices.get_device_for('swinir')848586def on_ui_settings():87import gradio as gr8889shared.opts.add_option("SWIN_tile", shared.OptionInfo(192, "Tile size for all SwinIR.", gr.Slider, {"minimum": 16, "maximum": 512, "step": 16}, section=('upscaling', "Upscaling")))90shared.opts.add_option("SWIN_tile_overlap", shared.OptionInfo(8, "Tile overlap, in pixels for SwinIR. Low values = visible seam.", gr.Slider, {"minimum": 0, "maximum": 48, "step": 1}, section=('upscaling', "Upscaling")))91shared.opts.add_option("SWIN_torch_compile", shared.OptionInfo(False, "Use torch.compile to accelerate SwinIR.", gr.Checkbox, {"interactive": True}, section=('upscaling', "Upscaling")).info("Takes longer on first run"))929394script_callbacks.on_ui_settings(on_ui_settings)959697