CoolFace
Apppublic

cymic/Waifu_Diffusion_Webui

sourceHugging Faceupdated 4y agoView on Hugging Face
1likes
bsrgan_model.py79 linesDownload Raw Back to modules
1import os.path2import sys3import traceback4 5import PIL.Image6import numpy as np7import torch8from basicsr.utils.download_util import load_file_from_url9 10import modules.upscaler11from modules import devices, modelloader12from modules.bsrgan_model_arch import RRDBNet13from modules.paths import models_path14 15 16class UpscalerBSRGAN(modules.upscaler.Upscaler):17    def __init__(self, dirname):18        self.name = "BSRGAN"19        self.model_path = os.path.join(models_path, self.name)20        self.model_name = "BSRGAN 4x"21        self.model_url = "https://github.com/cszn/KAIR/releases/download/v1.0/BSRGAN.pth"22        self.user_path = dirname23        super().__init__()24        model_paths = self.find_models(ext_filter=[".pt", ".pth"])25        scalers = []26        if len(model_paths) == 0:27            scaler_data = modules.upscaler.UpscalerData(self.model_name, self.model_url, self, 4)28            scalers.append(scaler_data)29        for file in model_paths:30            if "http" in file:31                name = self.model_name32            else:33                name = modelloader.friendly_name(file)34            try:35                scaler_data = modules.upscaler.UpscalerData(name, file, self, 4)36                scalers.append(scaler_data)37            except Exception:38                print(f"Error loading BSRGAN model: {file}", file=sys.stderr)39                print(traceback.format_exc(), file=sys.stderr)40        self.scalers = scalers41 42    def do_upscale(self, img: PIL.Image, selected_file):43        torch.cuda.empty_cache()44        model = self.load_model(selected_file)45        if model is None:46            return img47        model.to(devices.device_bsrgan)48        torch.cuda.empty_cache()49        img = np.array(img)50        img = img[:, :, ::-1]51        img = np.moveaxis(img, 2, 0) / 25552        img = torch.from_numpy(img).float()53        img = img.unsqueeze(0).to(devices.device_bsrgan)54        with torch.no_grad():55            output = model(img)56        output = output.squeeze().float().cpu().clamp_(0, 1).numpy()57        output = 255. * np.moveaxis(output, 0, 2)58        output = output.astype(np.uint8)59        output = output[:, :, ::-1]60        torch.cuda.empty_cache()61        return PIL.Image.fromarray(output, 'RGB')62 63    def load_model(self, path: str):64        if "http" in path:65            filename = load_file_from_url(url=self.model_url, model_dir=self.model_path, file_name="%s.pth" % self.name,66                                          progress=True)67        else:68            filename = path69        if not os.path.exists(filename) or filename is None:70            print(f"BSRGAN: Unable to load model from {filename}", file=sys.stderr)71            return None72        model = RRDBNet(in_nc=3, out_nc=3, nf=64, nb=23, gc=32, sf=4)  # define network73        model.load_state_dict(torch.load(filename), strict=True)74        model.eval()75        for k, v in model.named_parameters():76            v.requires_grad = False77        return model78 79