import torch


def realesrgan(bg_tile):
    from basicsr.archs.rrdbnet_arch import RRDBNet
    from realesrgan import RealESRGANer

    cuda_is_available = torch.cuda.is_available()
    half = True if cuda_is_available else False
    model = RRDBNet(
        num_in_ch=3,
        num_out_ch=3,
        num_feat=64,
        num_block=23,
        num_grow_ch=32,
        scale=2,
    )
    upsampler = RealESRGANer(
        scale=2,
        model_path="https://github.com/sczhou/CodeFormer/releases/download/v0.1.0/RealESRGAN_x2plus.pth",
        model=model,
        tile=bg_tile,
        tile_pad=40,
        pre_pad=0,
        half=half,  # need to set False in CPU mode
    )

    if not cuda_is_available:  # CPU
        import warnings

        warnings.warn(
            "Running on CPU now! Make sure your PyTorch version matches your CUDA."
            "The unoptimized RealESRGAN is slow on CPU. "
            "If you want to disable it, please remove `--bg_upsampler` and `--face_upsample` in command.",
            category=RuntimeWarning,
        )
    return upsampler
