Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
AUTOMATIC1111
GitHub Repository: AUTOMATIC1111/stable-diffusion-webui
Path: blob/master/extensions-builtin/SwinIR/scripts/swinir_model.py
2448 views
1
import logging
2
import sys
3
4
import torch
5
from PIL import Image
6
7
from modules import devices, modelloader, script_callbacks, shared, upscaler_utils
8
from modules.upscaler import Upscaler, UpscalerData
9
10
SWINIR_MODEL_URL = "https://github.com/JingyunLiang/SwinIR/releases/download/v0.0/003_realSR_BSRGAN_DFOWMFC_s64w8_SwinIR-L_x4_GAN.pth"
11
12
logger = logging.getLogger(__name__)
13
14
15
class UpscalerSwinIR(Upscaler):
16
def __init__(self, dirname):
17
self._cached_model = None # keep the model when SWIN_torch_compile is on to prevent re-compile every runs
18
self._cached_model_config = None # to clear '_cached_model' when changing model (v1/v2) or settings
19
self.name = "SwinIR"
20
self.model_url = SWINIR_MODEL_URL
21
self.model_name = "SwinIR 4x"
22
self.user_path = dirname
23
super().__init__()
24
scalers = []
25
model_files = self.find_models(ext_filter=[".pt", ".pth"])
26
for model in model_files:
27
if model.startswith("http"):
28
name = self.model_name
29
else:
30
name = modelloader.friendly_name(model)
31
model_data = UpscalerData(name, model, self)
32
scalers.append(model_data)
33
self.scalers = scalers
34
35
def do_upscale(self, img: Image.Image, model_file: str) -> Image.Image:
36
current_config = (model_file, shared.opts.SWIN_tile)
37
38
if self._cached_model_config == current_config:
39
model = self._cached_model
40
else:
41
try:
42
model = self.load_model(model_file)
43
except Exception as e:
44
print(f"Failed loading SwinIR model {model_file}: {e}", file=sys.stderr)
45
return img
46
self._cached_model = model
47
self._cached_model_config = current_config
48
49
img = upscaler_utils.upscale_2(
50
img,
51
model,
52
tile_size=shared.opts.SWIN_tile,
53
tile_overlap=shared.opts.SWIN_tile_overlap,
54
scale=model.scale,
55
desc="SwinIR",
56
)
57
devices.torch_gc()
58
return img
59
60
def load_model(self, path, scale=4):
61
if path.startswith("http"):
62
filename = modelloader.load_file_from_url(
63
url=path,
64
model_dir=self.model_download_path,
65
file_name=f"{self.model_name.replace(' ', '_')}.pth",
66
)
67
else:
68
filename = path
69
70
model_descriptor = modelloader.load_spandrel_model(
71
filename,
72
device=self._get_device(),
73
prefer_half=(devices.dtype == torch.float16),
74
expected_architecture="SwinIR",
75
)
76
if getattr(shared.opts, 'SWIN_torch_compile', False):
77
try:
78
model_descriptor.model.compile()
79
except Exception:
80
logger.warning("Failed to compile SwinIR model, fallback to JIT", exc_info=True)
81
return model_descriptor
82
83
def _get_device(self):
84
return devices.get_device_for('swinir')
85
86
87
def on_ui_settings():
88
import gradio as gr
89
90
shared.opts.add_option("SWIN_tile", shared.OptionInfo(192, "Tile size for all SwinIR.", gr.Slider, {"minimum": 16, "maximum": 512, "step": 16}, section=('upscaling', "Upscaling")))
91
shared.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")))
92
shared.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"))
93
94
95
script_callbacks.on_ui_settings(on_ui_settings)
96
97