import os
import gradio as gr
import argparse
import numpy as np
import torch
import einops
import copy
import math
import time
import random
import spaces
import re
from gradio_imageslider import ImageSlider
from PIL import Image
from SUPIR.util import HWC3, upscale_image, fix_resize, convert_dtype, create_SUPIR_model, load_QF_ckpt
from huggingface_hub import hf_hub_download
hf_hub_download(repo_id="laion/CLIP-ViT-bigG-14-laion2B-39B-b160k", filename="open_clip_pytorch_model.bin", local_dir="laion_CLIP-ViT-bigG-14-laion2B-39B-b160k")
hf_hub_download(repo_id="camenduru/SUPIR", filename="sd_xl_base_1.0_0.9vae.safetensors", local_dir="yushan777_SUPIR")
hf_hub_download(repo_id="camenduru/SUPIR", filename="SUPIR-v0F.ckpt", local_dir="yushan777_SUPIR")
hf_hub_download(repo_id="camenduru/SUPIR", filename="SUPIR-v0Q.ckpt", local_dir="yushan777_SUPIR")
hf_hub_download(repo_id="RunDiffusion/Juggernaut-XL-Lightning", filename="Juggernaut_RunDiffusionPhoto2_Lightning_4Steps.safetensors", local_dir="RunDiffusion_Juggernaut-XL-Lightning")
parser = argparse.ArgumentParser()
parser.add_argument("--opt", type=str, default='options/SUPIR_v0.yaml')
parser.add_argument("--ip", type=str, default='127.0.0.1')
parser.add_argument("--port", type=int, default='6688')
parser.add_argument("--no_llava", action='store_true', default=True)#False
parser.add_argument("--use_image_slider", action='store_true', default=False)#False
parser.add_argument("--log_history", action='store_true', default=False)
parser.add_argument("--loading_half_params", action='store_true', default=False)#False
parser.add_argument("--use_tile_vae", action='store_true', default=True)#False
parser.add_argument("--encoder_tile_size", type=int, default=512)
parser.add_argument("--decoder_tile_size", type=int, default=64)
parser.add_argument("--load_8bit_llava", action='store_true', default=False)
args = parser.parse_args()
if torch.cuda.device_count() > 0:
SUPIR_device = 'cuda:0'
# Load SUPIR
model, default_setting = create_SUPIR_model(args.opt, SUPIR_sign='Q', load_default_setting=True)
if args.loading_half_params:
model = model.half()
if args.use_tile_vae:
model.init_tile_vae(encoder_tile_size=args.encoder_tile_size, decoder_tile_size=args.decoder_tile_size)
model = model.to(SUPIR_device)
model.first_stage_model.denoise_encoder_s1 = copy.deepcopy(model.first_stage_model.denoise_encoder)
model.current_model = 'v0-Q'
ckpt_Q, ckpt_F = load_QF_ckpt(args.opt)
def check_upload(input_image):
if input_image is None:
raise gr.Error("Please provide an image to restore.")
return gr.update(visible = True)
def update_seed(is_randomize_seed, seed):
if is_randomize_seed:
return random.randint(0, 2147483647)
return seed
def check(input_image):
if input_image is None:
raise gr.Error("Please provide an image to restore.")
@spaces.GPU(duration=420)
def stage1_process(
input_image,
gamma_correction,
diff_dtype,
ae_dtype
):
print('stage1_process ==>>')
if torch.cuda.device_count() == 0:
gr.Warning('Set this space to GPU config to make it work.')
return None, None
torch.cuda.set_device(SUPIR_device)
LQ = HWC3(np.array(Image.open(input_image)))
LQ = fix_resize(LQ, 512)
# stage1
LQ = np.array(LQ) / 255 * 2 - 1
LQ = torch.tensor(LQ, dtype=torch.float32).permute(2, 0, 1).unsqueeze(0).to(SUPIR_device)[:, :3, :, :]
model.ae_dtype = convert_dtype(ae_dtype)
model.model.dtype = convert_dtype(diff_dtype)
LQ = model.batchify_denoise(LQ, is_stage1=True)
LQ = (LQ[0].permute(1, 2, 0) * 127.5 + 127.5).cpu().numpy().round().clip(0, 255).astype(np.uint8)
# gamma correction
LQ = LQ / 255.0
LQ = np.power(LQ, gamma_correction)
LQ *= 255.0
LQ = LQ.round().clip(0, 255).astype(np.uint8)
print('<<== stage1_process')
return LQ, gr.update(visible = True)
def stage2_process(*args, **kwargs):
try:
return restore_in_Xmin(*args, **kwargs)
except Exception as e:
print('Exception of type ' + str(type(e)))
if type(e).__name__ == " This is an online demo of SUPIR, a practicing model scaling for photo-realistic image restoration.
It is still a research project under tested and is not yet a stable commercial product.
The content added by SUPIR is imagination, not real-world information.
SUPIR is for beauty and illustration only.
Most of the processes only last few minutes.
This demo can handle huge images but the process will be aborted if it lasts more than 10 min.
If you want to upscale AI-generated images, be noticed that Stable Diffusion Medium spaces can directly generate 1536x1536 images.
Please leave a message in discussion if you encounter issues.
⚠️To use SUPIR, duplicate this space and set a GPU with 30 GB VRAM. You can't use SUPIR directly here because this space runs on a CPU, which is not enough for SUPIR. Please provide feedback if you have issues.
""") gr.HTML(title_html) input_image = gr.Image(label="Input (*.png, *.webp, *.jpeg, *.gif, *.bmp)", show_label=True, type="filepath", height=600, elem_id="image-input") rotation = gr.Radio([["No rotation", 0], ["⤵ Rotate +90°", 90], ["↩ Return 180°", 180], ["⤴ Rotate -90°", -90]], label="Orientation correction", info="Will apply the following rotation before restoring the image; the AI needs a good orientation to understand the content", value=0, interactive=True, visible=False) with gr.Group(): prompt = gr.Textbox(label="Image description", info="Help the AI understand what the image represents; describe as much as possible, especially the details we can't see on the original image; you can write in any language", value="", placeholder="A 33 years old man, walking, in the street, Santiago, morning, Summer, photorealistic", lines=3) prompt_hint = gr.HTML("You can use a LlaVa space to auto-generate the description of your image.") upscale = gr.Radio([["x1", 1], ["x2", 2], ["x3", 3], ["x4", 4], ["x5", 5], ["x6", 6], ["x7", 7], ["x8", 8], ["x9", 9], ["x10", 10]], label="Upscale factor", info="Resolution x1 to x10", value=2, interactive=True) allocation = gr.Radio([["1 min", 1], ["2 min", 2], ["3 min", 3], ["4 min", 4], ["5 min", 5], ["6 min", 6], ["7 min", 7], ["8 min", 8], ["9 min (discouraged)", 9], ["10 min (discouraged)", 10]], label="GPU allocation time", info="lower=May abort run, higher=Quota penalty for next runs", value=6, interactive=True) output_format = gr.Radio([["As input", "input"], ["*.png", "png"], ["*.webp", "webp"], ["*.jpeg", "jpeg"], ["*.gif", "gif"], ["*.bmp", "bmp"]], label="Image format for result", info="File extention", value="input", interactive=True) with gr.Accordion("Pre-denoising (optional)", open=False): gamma_correction = gr.Slider(label="Gamma Correction", info = "lower=lighter, higher=darker", minimum=0.1, maximum=2.0, value=1.0, step=0.1) denoise_button = gr.Button(value="Pre-denoise") denoise_image = gr.Image(label="Denoised image", show_label=True, type="filepath", sources=[], height=600, elem_id="image-s1") denoise_information = gr.HTML(value="If present, the denoised image will be used for the restoration instead of the input image.", visible=False) with gr.Accordion("Advanced options", open=False): a_prompt = gr.Textbox(label="Additional image description", info="Completes the main image description", value='Cinematic, High Contrast, highly detailed, taken using a Canon EOS R ' 'camera, hyper detailed photo - realistic maximum detail, 32k, Color ' 'Grading, ultra HD, extreme meticulous detailing, skin pore detailing, ' 'hyper sharpness, perfect without deformations.', lines=3) n_prompt = gr.Textbox(label="Negative image description", info="Disambiguate by listing what the image does NOT represent", value='painting, oil painting, illustration, drawing, art, sketch, anime, ' 'cartoon, CG Style, 3D render, unreal engine, blurring, aliasing, bokeh, ugly, dirty, messy, ' 'worst quality, low quality, frames, watermark, signature, jpeg artifacts, ' 'deformed, lowres, over-smooth', lines=3) edm_steps = gr.Slider(label="Steps", info="lower=faster, higher=more details", minimum=1, maximum=200, value=default_setting.edm_steps if torch.cuda.device_count() > 0 else 1, step=1) num_samples = gr.Slider(label="Num Samples", info="Number of generated results", minimum=1, maximum=4 if not args.use_image_slider else 1 , value=1, step=1) min_size = gr.Slider(label="Minimum size", info="Minimum height, minimum width of the result", minimum=32, maximum=4096, value=1024, step=32) downscale = gr.Radio([["/1", 1], ["/2", 2], ["/3", 3], ["/4", 4], ["/5", 5], ["/6", 6], ["/7", 7], ["/8", 8], ["/9", 9], ["/10", 10]], label="Pre-downscale factor", info="Reducing blurred image reduce the process time", value=1, interactive=True) with gr.Row(): with gr.Column(): model_select = gr.Radio([["💃 Quality (v0-Q)", "v0-Q"], ["🎯 Fidelity (v0-F)", "v0-F"]], label="Model Selection", info="Pretrained model", value="v0-Q", interactive=True) with gr.Column(): color_fix_type = gr.Radio(["None", "AdaIn", "Wavelet"], label="Color-Fix Type", info="AdaIn=Improve following a style, Wavelet=For JPEG artifacts", value="Wavelet", interactive=True) s_cfg = gr.Slider(label="Text Guidance Scale", info="lower=follow the image, higher=follow the prompt", minimum=1.0, maximum=15.0, value=default_setting.s_cfg_Quality if torch.cuda.device_count() > 0 else 1.0, step=0.1) s_stage2 = gr.Slider(label="Restoring Guidance Strength", minimum=0., maximum=1., value=1., step=0.05) s_stage1 = gr.Slider(label="Pre-denoising Guidance Strength", minimum=-1.0, maximum=6.0, value=-1.0, step=1.0) s_churn = gr.Slider(label="S-Churn", minimum=0, maximum=40, value=5, step=1) s_noise = gr.Slider(label="S-Noise", minimum=1.0, maximum=1.1, value=1.003, step=0.001) with gr.Row(): with gr.Column(): linear_CFG = gr.Checkbox(label="Linear CFG", value=True) spt_linear_CFG = gr.Slider(label="CFG Start", minimum=1.0, maximum=9.0, value=default_setting.spt_linear_CFG_Quality if torch.cuda.device_count() > 0 else 1.0, step=0.5) with gr.Column(): linear_s_stage2 = gr.Checkbox(label="Linear Restoring Guidance", value=False) spt_linear_s_stage2 = gr.Slider(label="Guidance Start", minimum=0., maximum=1., value=0., step=0.05) with gr.Column(): diff_dtype = gr.Radio([["fp32 (precision)", "fp32"], ["fp16 (medium)", "fp16"], ["bf16 (speed)", "bf16"]], label="Diffusion Data Type", value="fp16", interactive=True) with gr.Column(): ae_dtype = gr.Radio([["fp32 (precision)", "fp32"], ["bf16 (speed)", "bf16"]], label="Auto-Encoder Data Type", value="fp32", interactive=True) randomize_seed = gr.Checkbox(label = "\U0001F3B2 Randomize seed", value = True, info = "If checked, result is always different") seed = gr.Slider(label="Seed", minimum=0, maximum=2**63 - 1, step=1, randomize=True) with gr.Group(): param_setting = gr.Radio(["Quality", "Fidelity"], interactive=True, label="Presetting", value="Quality") restart_button = gr.Button(value="Apply presetting") with gr.Group(): diffusion_button = gr.Button(value="🚀 Upscale/Restore", variant = "primary", elem_id="process_button") restore_information = gr.HTML(value="Restart the process to get another result.", visible = False) result_slider = ImageSlider(label='Comparator', show_label=False, elem_id="slider1", show_download_button = False) result_gallery = gr.Gallery(label='Downloadable results', show_label=True, elem_id="gallery1") gr.Examples( run_on_click = True, fn = stage2_process, inputs = [ input_image, rotation, denoise_image, prompt, a_prompt, n_prompt, num_samples, min_size, downscale, upscale, edm_steps, s_stage1, s_stage2, s_cfg, randomize_seed, seed, s_churn, s_noise, color_fix_type, diff_dtype, ae_dtype, gamma_correction, linear_CFG, linear_s_stage2, spt_linear_CFG, spt_linear_s_stage2, model_select, output_format, allocation ], outputs = [ result_slider, result_gallery, restore_information ], examples = [ [ "./Examples/Example1.png", 0, None, "Group of people, walking, happy, in the street, photorealistic, 8k, extremely detailled", "Cinematic, High Contrast, highly detailed, taken using a Canon EOS R camera, hyper detailed photo - realistic maximum detail, 32k, Color Grading, ultra HD, extreme meticulous detailing, skin pore detailing, hyper sharpness, perfect without deformations.", "painting, oil painting, illustration, drawing, art, sketch, anime, cartoon, CG Style, 3D render, unreal engine, blurring, aliasing, bokeh, ugly, dirty, messy, worst quality, low quality, frames, watermark, signature, jpeg artifacts, deformed, lowres, over-smooth", 2, 1024, 1, 8, 200, -1, 1, 7.5, False, 42, 5, 1.003, "AdaIn", "fp16", "bf16", 1.0, True, 4, False, 0., "v0-Q", "input", 5 ], [ "./Examples/Example2.jpeg", 0, None, "La cabeza de un gato atigrado, en una casa, fotorrealista, 8k, extremadamente detallada", "Cinematic, High Contrast, highly detailed, taken using a Canon EOS R camera, hyper detailed photo - realistic maximum detail, 32k, Color Grading, ultra HD, extreme meticulous detailing, skin pore detailing, hyper sharpness, perfect without deformations.", "painting, oil painting, illustration, drawing, art, sketch, anime, cartoon, CG Style, 3D render, unreal engine, blurring, aliasing, bokeh, ugly, dirty, messy, worst quality, low quality, frames, watermark, signature, jpeg artifacts, deformed, lowres, over-smooth", 1, 1024, 1, 1, 200, -1, 1, 7.5, False, 42, 5, 1.003, "Wavelet", "fp16", "bf16", 1.0, True, 4, False, 0., "v0-Q", "input", 4 ], [ "./Examples/Example3.webp", 0, None, "A red apple", "Cinematic, High Contrast, highly detailed, taken using a Canon EOS R camera, hyper detailed photo - realistic maximum detail, 32k, Color Grading, ultra HD, extreme meticulous detailing, skin pore detailing, hyper sharpness, perfect without deformations.", "painting, oil painting, illustration, drawing, art, sketch, anime, cartoon, CG Style, 3D render, unreal engine, blurring, aliasing, bokeh, ugly, dirty, messy, worst quality, low quality, frames, watermark, signature, jpeg artifacts, deformed, lowres, over-smooth", 1, 1024, 1, 1, 200, -1, 1, 7.5, False, 42, 5, 1.003, "Wavelet", "fp16", "bf16", 1.0, True, 4, False, 0., "v0-Q", "input", 4 ], [ "./Examples/Example3.webp", 0, None, "A red marble", "Cinematic, High Contrast, highly detailed, taken using a Canon EOS R camera, hyper detailed photo - realistic maximum detail, 32k, Color Grading, ultra HD, extreme meticulous detailing, skin pore detailing, hyper sharpness, perfect without deformations.", "painting, oil painting, illustration, drawing, art, sketch, anime, cartoon, CG Style, 3D render, unreal engine, blurring, aliasing, bokeh, ugly, dirty, messy, worst quality, low quality, frames, watermark, signature, jpeg artifacts, deformed, lowres, over-smooth", 1, 1024, 1, 1, 200, -1, 1, 7.5, False, 42, 5, 1.003, "Wavelet", "fp16", "bf16", 1.0, True, 4, False, 0., "v0-Q", "input", 4 ], ], cache_examples = False, ) with gr.Row(): gr.Markdown(claim_md) input_image.upload(fn = check_upload, inputs = [ input_image ], outputs = [ rotation ], queue = False, show_progress = False) denoise_button.click(fn = check, inputs = [ input_image ], outputs = [], queue = False, show_progress = False).success(fn = stage1_process, inputs = [ input_image, gamma_correction, diff_dtype, ae_dtype ], outputs=[ denoise_image, denoise_information ]) diffusion_button.click(fn = update_seed, inputs = [ randomize_seed, seed ], outputs = [ seed ], queue = False, show_progress = False).then(fn = check, inputs = [ input_image ], outputs = [], queue = False, show_progress = False).success(fn=stage2_process, inputs = [ input_image, rotation, denoise_image, prompt, a_prompt, n_prompt, num_samples, min_size, downscale, upscale, edm_steps, s_stage1, s_stage2, s_cfg, randomize_seed, seed, s_churn, s_noise, color_fix_type, diff_dtype, ae_dtype, gamma_correction, linear_CFG, linear_s_stage2, spt_linear_CFG, spt_linear_s_stage2, model_select, output_format, allocation ], outputs = [ result_slider, result_gallery, restore_information ]).success(fn = log_information, inputs = [ result_gallery ], outputs = [], queue = False, show_progress = False) result_gallery.select(on_select_result, [result_slider, result_gallery], result_slider) restart_button.click(fn = load_and_reset, inputs = [ param_setting ], outputs = [ edm_steps, s_cfg, s_stage2, s_stage1, s_churn, s_noise, a_prompt, n_prompt, color_fix_type, linear_CFG, linear_s_stage2, spt_linear_CFG, spt_linear_s_stage2, model_select ]) interface.queue(10).launch()