Fabrice TIERCELIN commited on
Commit ·
734e4e5
1
Parent(s): 68231ac
Reuse ref space of SUPIR
Browse filesFiles changed (10)
- CKPT_PTH.pyAdded+4
- Examples/Example1.pngDeleted
- LICENSEAdded+18
- README.md+154-20
- app.pyDeleted-328
- gradio_demo.pyAdded+314
- gradio_demo_face.pyAdded+411
- gradio_demo_tiled.pyAdded+339
- requirements.txt+42-8
- test.pyAdded+106
1234LLAVA_CLIP_PATH = '/opt/data/private/AIGC_pretrain/LLaVA1.5/clip-vit-large-patch14-336'LLAVA_MODEL_PATH = '/opt/data/private/AIGC_pretrain/LLaVA1.5/llava-v1.5-13b'SDXL_CLIP1_PATH = '/opt/data/private/AIGC_pretrain/clip-vit-large-patch14'SDXL_CLIP2_CKPT_PTH = '/opt/data/private/AIGC_pretrain/CLIP-ViT-bigG-14-laion2B-39B-b160k/open_clip_pytorch_model.bin'123456789101112131415161718License
Copyright (c) 2024 XPixel Group, Especially the author team of SUPIR.
The SUPIR ("Software") is made available for use, reproduction, and distribution strictly for non-commercial purposes. For the purposes of this declaration, "non-commercial" is defined as not primarily intended for or directed towards commercial advantage or monetary compensation.
By using, reproducing, or distributing the Software, you agree to abide by this restriction and not to use the Software for any commercial purposes without obtaining prior written permission from Dr. Jinjin Gu.
This declaration does not in any way limit the rights under any open source license that may apply to the Software; it solely adds a condition that the Software shall not be used for commercial purposes.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
For inquiries or to obtain permission for commercial use, please contact Dr. Jinjin Gu (jinjin.gu@suppixel.ai).
1234567891011121314151617181920212223---title: Image Upscaleremoji: ↕️colorFrom: bluecolorTo: greentags:- Image-to-Image- Image-2-Image- Img-to-Img- Img-2-Img- SDXL- Stable Diffusion- language models- LLMssdk: gradiosdk_version: 4.22.0app_file: app.pypinned: falselicense: mitshort_description: Increases the image resolution, freely, no watermark---Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157## (CVPR2024) Scaling Up to Excellence: Practicing Model Scaling for Photo-Realistic Image Restoration In the Wild> [[Paper](https://arxiv.org/abs/2401.13627)]   [[Project Page](http://supir.xpixel.group/)]   [Online Demo (Coming soon)] <br>> Fanghua, Yu, [Jinjin Gu](https://www.jasongt.com/), Zheyuan Li, Jinfan Hu, Xiangtao Kong, [Xintao Wang](https://xinntao.github.io/), [Jingwen He](https://scholar.google.com.hk/citations?user=GUxrycUAAAAJ), [Yu Qiao](https://scholar.google.com.hk/citations?user=gFtI-8QAAAAJ), [Chao Dong](https://scholar.google.com.hk/citations?user=OSDCB0UAAAAJ) <br>> Shenzhen Institute of Advanced Technology; Shanghai AI Laboratory; University of Sydney; The Hong Kong Polytechnic University; ARC Lab, Tencent PCG; The Chinese University of Hong Kong <br><p align="center"><img src="assets/teaser.png"></p>---#### ⚠ Due to the large RAM (60G) and VRAM (30G x2) costs of SUPIR, we are working on the online demo releasing.---## 🔧 Dependencies and Installation1. Clone repo```bashgit clone https://github.com/Fanghua-Yu/SUPIR.gitcd SUPIR```2. Install dependent packages```bashconda create -n SUPIR python=3.8 -yconda activate SUPIRpip install --upgrade pippip install -r requirements.txt```3. Download CheckpointsFor users who can connect to huggingface, please setting `LLAVA_CLIP_PATH, SDXL_CLIP1_PATH, SDXL_CLIP2_CKPT_PTH` in `CKPT_PTH.py` as `None`. These CLIPs will be downloaded automatically.#### Dependent Models* [SDXL CLIP Encoder-1](https://huggingface.co/openai/clip-vit-large-patch14)* [SDXL CLIP Encoder-2](https://huggingface.co/laion/CLIP-ViT-bigG-14-laion2B-39B-b160k)* [SDXL base 1.0_0.9vae](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0/blob/main/sd_xl_base_1.0_0.9vae.safetensors)* [LLaVA CLIP](https://huggingface.co/openai/clip-vit-large-patch14-336)* [LLaVA v1.5 13B](https://huggingface.co/liuhaotian/llava-v1.5-13b)* (optional) [Juggernaut-XL_v9_RunDiffusionPhoto_v2](https://huggingface.co/RunDiffusion/Juggernaut-XL-v9/blob/main/Juggernaut-XL_v9_RunDiffusionPhoto_v2.safetensors)* Replacement of `SDXL base 1.0_0.9vae` for Photo Realistic* (optional) [Juggernaut_RunDiffusionPhoto2_Lightning_4Steps](https://huggingface.co/RunDiffusion/Juggernaut-XL-Lightning/blob/main/Juggernaut_RunDiffusionPhoto2_Lightning_4Steps.safetensors)* Distilling model used in `SUPIR_v0_Juggernautv9_lightning.yaml`#### Models we provided:* `SUPIR-v0Q`: [Baidu Netdisk](https://pan.baidu.com/s/1lnefCZhBTeDWijqbj1jIyw?pwd=pjq6), [Google Drive](https://drive.google.com/drive/folders/1yELzm5SvAi9e7kPcO_jPp2XkTs4vK6aR?usp=sharing)Default training settings with paper. High generalization and high image quality in most cases.* `SUPIR-v0F`: [Baidu Netdisk](https://pan.baidu.com/s/1AECN8NjiVuE3hvO8o-Ua6A?pwd=k2uz), [Google Drive](https://drive.google.com/drive/folders/1yELzm5SvAi9e7kPcO_jPp2XkTs4vK6aR?usp=sharing)Training with light degradation settings. Stage1 encoder of `SUPIR-v0F` remains more details when facing light degradations.4. Edit Custom Path for Checkpoints```* [CKPT_PTH.py] --> LLAVA_CLIP_PATH, LLAVA_MODEL_PATH, SDXL_CLIP1_PATH, SDXL_CLIP2_CACHE_DIR* [options/SUPIR_v0.yaml] --> SDXL_CKPT, SUPIR_CKPT_Q, SUPIR_CKPT_F```---## ⚡ Quick Inference### Val DatasetRealPhoto60: [Baidu Netdisk](https://pan.baidu.com/s/1CJKsPGtyfs8QEVCQ97voBA?pwd=aocg), [Google Drive](https://drive.google.com/drive/folders/1yELzm5SvAi9e7kPcO_jPp2XkTs4vK6aR?usp=sharing)### Usage of SUPIR```ShellUsage:-- python test.py [options]-- python gradio_demo.py [interactive options]--img_dir Input folder.--save_dir Output folder.--upscale Upsampling ratio of given inputs. Default: 1--SUPIR_sign Model selection. Default: 'Q'; Options: ['F', 'Q']--seed Random seed. Default: 1234--min_size Minimum resolution of output images. Default: 1024--edm_steps Numb of steps for EDM Sampling Scheduler. Default: 50--s_stage1 Control Strength of Stage1. Default: -1 (negative means invalid)--s_churn Original hy-param of EDM. Default: 5--s_noise Original hy-param of EDM. Default: 1.003--s_cfg Classifier-free guidance scale for prompts. Default: 7.5--s_stage2 Control Strength of Stage2. Default: 1.0--num_samples Number of samples for each input. Default: 1--a_prompt Additive positive prompt for all inputs.Default: 'Cinematic, High Contrast, highly detailed, taken using a Canon EOS R camera,hyper detailed photo - realistic maximum detail, 32k, Color Grading, ultra HD, extrememeticulous detailing, skin pore detailing, hyper sharpness, perfect without deformations.'--n_prompt Fixed negative prompt for all inputs.Default: 'painting, oil painting, illustration, drawing, art, sketch, oil painting,cartoon, CG Style, 3D render, unreal engine, blurring, dirty, messy, worst quality,low quality, frames, watermark, signature, jpeg artifacts, deformed, lowres, over-smooth'--color_fix_type Color Fixing Type. Default: 'Wavelet'; Options: ['None', 'AdaIn', 'Wavelet']--linear_CFG Linearly (with sigma) increase CFG from 'spt_linear_CFG' to s_cfg. Default: False--linear_s_stage2 Linearly (with sigma) increase s_stage2 from 'spt_linear_s_stage2' to s_stage2. Default: False--spt_linear_CFG Start point of linearly increasing CFG. Default: 1.0--spt_linear_s_stage2 Start point of linearly increasing s_stage2. Default: 0.0--ae_dtype Inference data type of AutoEncoder. Default: 'bf16'; Options: ['fp32', 'bf16']--diff_dtype Inference data type of Diffusion. Default: 'fp16'; Options: ['fp32', 'fp16', 'bf16']```### Python Script```Shell# Seek for best quality for most casesCUDA_VISIBLE_DEVICES=0,1 python test.py --img_dir '/opt/data/private/LV_Dataset/DiffGLV-Test-All/RealPhoto60/LQ' --save_dir ./results-Q --SUPIR_sign Q --upscale 2# for light degradation and high fidelityCUDA_VISIBLE_DEVICES=0,1 python test.py --img_dir '/opt/data/private/LV_Dataset/DiffGLV-Test-All/RealPhoto60/LQ' --save_dir ./results-F --SUPIR_sign F --upscale 2 --s_cfg 4.0 --linear_CFG```### Gradio Demo```ShellCUDA_VISIBLE_DEVICES=0,1 python gradio_demo.py --ip 0.0.0.0 --port 6688 --use_image_slider --log_history# Juggernaut_RunDiffusionPhoto2_Lightning_4Steps and DPM++ M2 SDE Karras for fast samplingCUDA_VISIBLE_DEVICES=0,1 python gradio_demo.py --ip 0.0.0.0 --port 6688 --use_image_slider --log_history --opt options/SUPIR_v0_Juggernautv9_lightning.yaml# less VRAM & slower (12G for Diffusion, 16G for LLaVA)CUDA_VISIBLE_DEVICES=0,1 python gradio_demo.py --ip 0.0.0.0 --port 6688 --use_image_slider --log_history --loading_half_params --use_tile_vae --load_8bit_llava```<p align="center"><img src="assets/DemoGuide.png"></p>### Online Demo (Coming Soon)---## BibTeX@misc{yu2024scaling,title={Scaling Up to Excellence: Practicing Model Scaling for Photo-Realistic Image Restoration In the Wild},author={Fanghua Yu and Jinjin Gu and Zheyuan Li and Jinfan Hu and Xiangtao Kong and Xintao Wang and Jingwen He and Yu Qiao and Chao Dong},year={2024},eprint={2401.13627},archivePrefix={arXiv},primaryClass={cs.CV}}---## 📧 ContactIf you have any question, please email `fanghuayu96@gmail.com`.---## Non-Commercial Use Only DeclarationThe SUPIR ("Software") is made available for use, reproduction, and distribution strictly for non-commercial purposes. For the purposes of this declaration, "non-commercial" is defined as not primarily intended for or directed towards commercial advantage or monetary compensation.By using, reproducing, or distributing the Software, you agree to abide by this restriction and not to use the Software for any commercial purposes without obtaining prior written permission from Dr. Jinjin Gu.This declaration does not in any way limit the rights under any open source license that may apply to the Software; it solely adds a condition that the Software shall not be used for commercial purposes.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.For inquiries or to obtain permission for commercial use, please contact Dr. Jinjin Gu (hellojasongt@gmail.com).
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328import gradio as grimport numpy as npimport timeimport mathimport randomimport imageioimport torch
from diffusers import DiffusionPipelinefrom PIL import Image, ImageFilter
max_64_bit_int = 2**63 - 1
device = "cuda" if torch.cuda.is_available() else "cpu"floatType = torch.float16 if torch.cuda.is_available() else torch.float32variant = "fp16" if torch.cuda.is_available() else None
pipe = DiffusionPipeline.from_pretrained("yushan777/SUPIR", trust_remote_code = True)pipe = pipe.to(device)
def update_seed(is_randomize_seed, seed): if is_randomize_seed: return random.randint(0, max_64_bit_int) return seed
def toggle_debug(is_debug_mode): if is_debug_mode: return [gr.update(visible = True)] return [gr.update(visible = False)]
def check( source_img, prompt, negative_prompt, num_inference_steps, guidance_scale, image_guidance_scale, strength, denoising_steps, seed, debug_mode, progress = gr.Progress()): if source_img is None: raise gr.Error("Please provide an image.")
if prompt is None or prompt == "": raise gr.Error("Please provide a prompt input.")
def redraw( source_img, prompt, negative_prompt, num_inference_steps, guidance_scale, image_guidance_scale, strength, denoising_steps, seed, debug_mode, progress = gr.Progress()): check( source_img, prompt, negative_prompt, num_inference_steps, guidance_scale, image_guidance_scale, strength, denoising_steps, seed, debug_mode ) start = time.time() progress(0, desc = "Preparing data...")
if negative_prompt is None: negative_prompt = ""
if num_inference_steps is None: num_inference_steps = 25
if guidance_scale is None: guidance_scale = 7
if image_guidance_scale is None: image_guidance_scale = 1.1
if strength is None: strength = 0.5
if denoising_steps is None: denoising_steps = 1000
if seed is None: seed = random.randint(0, max_64_bit_int)
random.seed(seed) torch.manual_seed(seed)
input_image = source_img.convert("RGB")
original_height, original_width, original_channel = np.array(input_image).shape output_width = original_width output_height = original_height
# Limited to 1 million pixels if 1024 * 1024 < output_width * output_height: factor = ((1024 * 1024) / (output_width * output_height))**0.5 process_width = math.floor(output_width * factor) process_height = math.floor(output_height * factor)
limitation = " Due to technical limitation, the image have been downscaled and then upscaled."; else: process_width = output_width process_height = output_height
limitation = "";
# Width and height must be multiple of 8 if (process_width % 8) != 0 or (process_height % 8) != 0: if ((process_width - (process_width % 8) + 8) * (process_height - (process_height % 8) + 8)) <= (1024 * 1024): process_width = process_width - (process_width % 8) + 8 process_height = process_height - (process_height % 8) + 8 elif (process_height % 8) <= (process_width % 8) and ((process_width - (process_width % 8) + 8) * process_height) <= (1024 * 1024): process_width = process_width - (process_width % 8) + 8 process_height = process_height - (process_height % 8) elif (process_width % 8) <= (process_height % 8) and (process_width * (process_height - (process_height % 8) + 8)) <= (1024 * 1024): process_width = process_width - (process_width % 8) process_height = process_height - (process_height % 8) + 8 else: process_width = process_width - (process_width % 8) process_height = process_height - (process_height % 8)
process_width = 1024 process_height = 1024
output_width = 1024 output_height = 1024
progress(None, desc = "Processing...") output_image = pipe( seeds = [seed], width = process_width, height = process_height, prompt = prompt, negative_prompt = negative_prompt, image = input_image, num_inference_steps = num_inference_steps, guidance_scale = guidance_scale, image_guidance_scale = image_guidance_scale, strength = strength, denoising_steps = denoising_steps, show_progress_bar = True ).images[0]
if limitation != "": output_image = output_image.resize((output_width, output_height))
if debug_mode == False: input_image = None
end = time.time() secondes = int(end - start) minutes = secondes // 60 secondes = secondes - (minutes * 60) hours = minutes // 60 minutes = minutes - (hours * 60) return [ output_image, "Start again to get a different result. The new image is " + str(output_width) + " pixels large and " + str(output_height) + " pixels high, so an image of " + f'{output_width * output_height:,}' + " pixels. The image have been generated in " + str(hours) + " h, " + str(minutes) + " min, " + str(secondes) + " sec." + limitation, input_image ]
with gr.Blocks() as interface: gr.Markdown( """ <p style="text-align: center;"><b><big><big><big>Image-to-Image</big></big></big></b></p> <p style="text-align: center;">Modifies the global render of your image, at any resolution, freely, without account, without watermark, without installation, which can be downloaded</p> <br/> <br/> 🚀 Powered by <i>SDXL Turbo</i> artificial intellingence. For illustration purpose, not information purpose. The new content is not based on real information but imagination. <br/> <ul> <li>To change the <b>view angle</b> of your image, I recommend to use <i>Zero123</i>,</li> <li>To <b>upscale</b> your image, I recommend to use <i>Ilaria Upscaler</i>,</li> <li>To change one <b>detail</b> on your image, I recommend to use <i>Inpaint SDXL</i>,</li> <li>If you need to enlarge the <b>viewpoint</b> of your image, I recommend you to use <i>Uncrop</i>,</li> <li>To remove the <b>background</b> of your image, I recommend to use <i>BRIA</i>,</li> <li>To make a <b>tile</b> of your image, I recommend to use <i>Make My Image Tile</i>,</li> <li>To modify <b>anything else</b> on your image, I recommend to use <i>Instruct Pix2Pix</i>.</li> </ul> <br/> 🐌 Slow process... ~2 hours. Your computer must not enter into standby mode.<br/>You can duplicate this space on a free account, it works on CPU and should also run on CUDA.<br/> <a href='https://huggingface.co/spaces/Fabrice-TIERCELIN/Image-to-Image?duplicate=true'><img src='https://img.shields.io/badge/-Duplicate%20Space-blue?labelColor=white&style=flat&logo=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAP5JREFUOE+lk7FqAkEURY+ltunEgFXS2sZGIbXfEPdLlnxJyDdYB62sbbUKpLbVNhyYFzbrrA74YJlh9r079973psed0cvUD4A+4HoCjsA85X0Dfn/RBLBgBDxnQPfAEJgBY+A9gALA4tcbamSzS4xq4FOQAJgCDwV2CPKV8tZAJcAjMMkUe1vX+U+SMhfAJEHasQIWmXNN3abzDwHUrgcRGmYcgKe0bxrblHEB4E/pndMazNpSZGcsZdBlYJcEL9Afo75molJyM2FxmPgmgPqlWNLGfwZGG6UiyEvLzHYDmoPkDDiNm9JR9uboiONcBXrpY1qmgs21x1QwyZcpvxt9NS09PlsPAAAAAElFTkSuQmCC&logoWidth=14'></a> <br/> ⚖️ You can use, modify and share the generated images but not for commercial uses.
""" ) with gr.Column(): source_img = gr.Image(label = "Your image", sources = ["upload", "webcam", "clipboard"], type = "pil") prompt = gr.Textbox(label = "Prompt", info = "Describe the subject, the background and the style of image; 77 token limit", placeholder = "Describe what you want to see in the entire image") strength = gr.Slider(value = 0.5, minimum = 0.01, maximum = 1.0, step = 0.01, label = "Strength", info = "lower=follow the original image, higher=follow the prompt") with gr.Accordion("Advanced options", open = False): negative_prompt = gr.Textbox(label = "Negative prompt", placeholder = "Describe what you do NOT want to see in the entire image", value = "Ugly, malformed, noise, blur, watermark") num_inference_steps = gr.Slider(minimum = 10, maximum = 100, value = 25, step = 1, label = "Number of inference steps", info = "lower=faster, higher=image quality") guidance_scale = gr.Slider(minimum = 1, maximum = 13, value = 7, step = 0.1, label = "Classifier-Free Guidance Scale", info = "lower=image quality, higher=follow the prompt") image_guidance_scale = gr.Slider(minimum = 1, value = 1.1, step = 0.1, label = "Image Guidance Scale", info = "lower=image quality, higher=follow the image") denoising_steps = gr.Slider(minimum = 0, maximum = 1000, value = 1000, step = 1, label = "Denoising", info = "lower=irrelevant result, higher=relevant result") randomize_seed = gr.Checkbox(label = "\U0001F3B2 Randomize seed", value = True, info = "If checked, result is always different") seed = gr.Slider(minimum = 0, maximum = max_64_bit_int, step = 1, randomize = True, label = "Seed") debug_mode = gr.Checkbox(label = "Debug mode", value = False, info = "Show intermediate results")
submit = gr.Button("Redraw", variant = "primary")
redrawn_image = gr.Image(label = "Redrawn image") information = gr.Label(label = "Information") original_image = gr.Image(label = "Original image", visible = False)
submit.click(update_seed, inputs = [ randomize_seed, seed ], outputs = [ seed ], queue = False, show_progress = False).then(toggle_debug, debug_mode, [ original_image ], queue = False, show_progress = False).then(check, inputs = [ source_img, prompt, negative_prompt, num_inference_steps, guidance_scale, image_guidance_scale, strength, denoising_steps, seed, debug_mode ], outputs = [], queue = False, show_progress = False).success(redraw, inputs = [ source_img, prompt, negative_prompt, num_inference_steps, guidance_scale, image_guidance_scale, strength, denoising_steps, seed, debug_mode ], outputs = [ redrawn_image, information, original_image ], scroll_to_output = True)
gr.Examples( fn = redraw, inputs = [ source_img, prompt, negative_prompt, num_inference_steps, guidance_scale, image_guidance_scale, strength, denoising_steps, seed, debug_mode ], outputs = [ redrawn_image, information, original_image ], examples = [ [ "./Examples/Example1.png", "Drawn image, line art, illustration, picture", "3d, photo, realistic, noise, blur, watermark", 25, 7, 1.1, 0.6, 1000, 42, False ], ], cache_examples = False, ) gr.Markdown( """ ## How to prompt your image
To easily read your prompt, start with the subject, then describ the pose or action, then secondary elements, then the background, then the graphical style, then the image quality: ``` A Vietnamese woman, red clothes, walking, smilling, in the street, a car on the left, in a modern city, photorealistic, 8k ```
You can use round brackets to increase the importance of a part: ``` A Vietnamese woman, (red clothes), walking, smilling, in the street, a car on the left, in a modern city, photorealistic, 8k ```
You can use several levels of round brackets to even more increase the importance of a part: ``` A Vietnamese woman, ((red clothes)), (walking), smilling, in the street, a car on the left, in a modern city, photorealistic, 8k ```
You can use number instead of several round brackets: ``` A Vietnamese woman, (red clothes:1.5), (walking), smilling, in the street, a car on the left, in a modern city, photorealistic, 8k ```
You can do the same thing with square brackets to decrease the importance of a part: ``` A [Vietnamese] woman, (red clothes:1.5), (walking), smilling, in the street, a car on the left, in a modern city, photorealistic, 8k ```
To easily read your negative prompt, organize it the same way as your prompt (not important for the AI): ``` man, boy, hat, running, tree, bicycle, forest, drawing, painting, cartoon, 3d, monochrome, blurry, noisy, bokeh ``` """ )
interface.queue().launch()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314import os
import gradio as grfrom gradio_imageslider import ImageSliderimport argparsefrom SUPIR.util import HWC3, upscale_image, fix_resize, convert_dtypeimport numpy as npimport torchfrom SUPIR.util import create_SUPIR_model, load_QF_ckptfrom PIL import Imagefrom llava.llava_agent import LLavaAgentfrom CKPT_PTH import LLAVA_MODEL_PATHimport einopsimport copyimport time
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=False)parser.add_argument("--use_image_slider", action='store_true', default=False)parser.add_argument("--log_history", action='store_true', default=False)parser.add_argument("--loading_half_params", action='store_true', default=False)parser.add_argument("--use_tile_vae", action='store_true', default=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()server_ip = args.ipserver_port = args.portuse_llava = not args.no_llava
if torch.cuda.device_count() >= 2: SUPIR_device = 'cuda:0' LLaVA_device = 'cuda:1'elif torch.cuda.device_count() == 1: SUPIR_device = 'cuda:0' LLaVA_device = 'cuda:0'else: raise ValueError('Currently support CUDA only.')
# load SUPIRmodel, 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)
# load LLaVAif use_llava: llava_agent = LLavaAgent(LLAVA_MODEL_PATH, device=LLaVA_device, load_8bit=args.load_8bit_llava, load_4bit=False)else: llava_agent = None
def stage1_process(input_image, gamma_correction): torch.cuda.set_device(SUPIR_device) LQ = HWC3(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, :, :] 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) return LQ
def llave_process(input_image, temperature, top_p, qs=None): torch.cuda.set_device(LLaVA_device) if use_llava: LQ = HWC3(input_image) LQ = Image.fromarray(LQ.astype('uint8')) captions = llava_agent.gen_image_caption([LQ], temperature=temperature, top_p=top_p, qs=qs) else: captions = ['LLaVA is not available. Please add text manually.'] return captions[0]
def stage2_process(input_image, prompt, a_prompt, n_prompt, num_samples, upscale, edm_steps, s_stage1, s_stage2, s_cfg, 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): torch.cuda.set_device(SUPIR_device) event_id = str(time.time_ns()) event_dict = {'event_id': event_id, 'localtime': time.ctime(), 'prompt': prompt, 'a_prompt': a_prompt, 'n_prompt': n_prompt, 'num_samples': num_samples, 'upscale': upscale, 'edm_steps': edm_steps, 's_stage1': s_stage1, 's_stage2': s_stage2, 's_cfg': s_cfg, 'seed': seed, 's_churn': s_churn, 's_noise': s_noise, 'color_fix_type': color_fix_type, 'diff_dtype': diff_dtype, 'ae_dtype': ae_dtype, 'gamma_correction': gamma_correction, 'linear_CFG': linear_CFG, 'linear_s_stage2': linear_s_stage2, 'spt_linear_CFG': spt_linear_CFG, 'spt_linear_s_stage2': spt_linear_s_stage2, 'model_select': model_select}
if model_select != model.current_model: if model_select == 'v0-Q': print('load v0-Q') model.load_state_dict(ckpt_Q, strict=False) model.current_model = 'v0-Q' elif model_select == 'v0-F': print('load v0-F') model.load_state_dict(ckpt_F, strict=False) model.current_model = 'v0-F' input_image = HWC3(input_image) input_image = upscale_image(input_image, upscale, unit_resolution=32, min_size=1024)
LQ = np.array(input_image) / 255.0 LQ = np.power(LQ, gamma_correction) LQ *= 255.0 LQ = LQ.round().clip(0, 255).astype(np.uint8) LQ = LQ / 255 * 2 - 1 LQ = torch.tensor(LQ, dtype=torch.float32).permute(2, 0, 1).unsqueeze(0).to(SUPIR_device)[:, :3, :, :] if use_llava: captions = [prompt] else: captions = ['']
model.ae_dtype = convert_dtype(ae_dtype) model.model.dtype = convert_dtype(diff_dtype)
samples = model.batchify_sample(LQ, captions, num_steps=edm_steps, restoration_scale=s_stage1, s_churn=s_churn, s_noise=s_noise, cfg_scale=s_cfg, control_scale=s_stage2, seed=seed, num_samples=num_samples, p_p=a_prompt, n_p=n_prompt, color_fix_type=color_fix_type, use_linear_CFG=linear_CFG, use_linear_control_scale=linear_s_stage2, cfg_scale_start=spt_linear_CFG, control_scale_start=spt_linear_s_stage2)
x_samples = (einops.rearrange(samples, 'b c h w -> b h w c') * 127.5 + 127.5).cpu().numpy().round().clip( 0, 255).astype(np.uint8) results = [x_samples[i] for i in range(num_samples)]
if args.log_history: os.makedirs(f'./history/{event_id[:5]}/{event_id[5:]}', exist_ok=True) with open(f'./history/{event_id[:5]}/{event_id[5:]}/logs.txt', 'w') as f: f.write(str(event_dict)) f.close() Image.fromarray(input_image).save(f'./history/{event_id[:5]}/{event_id[5:]}/LQ.png') for i, result in enumerate(results): Image.fromarray(result).save(f'./history/{event_id[:5]}/{event_id[5:]}/HQ_{i}.png') return [input_image] + results, event_id, 3, ''
def load_and_reset(param_setting): edm_steps = default_setting.edm_steps s_stage2 = 1.0 s_stage1 = -1.0 s_churn = 5 s_noise = 1.003 a_prompt = '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.' n_prompt = 'painting, oil painting, illustration, drawing, art, sketch, oil painting, cartoon, CG Style, ' \ '3D render, unreal engine, blurring, dirty, messy, worst quality, low quality, frames, watermark, ' \ 'signature, jpeg artifacts, deformed, lowres, over-smooth' color_fix_type = 'Wavelet' spt_linear_s_stage2 = 0.0 linear_s_stage2 = False linear_CFG = True if param_setting == "Quality": s_cfg = default_setting.s_cfg_Quality spt_linear_CFG = default_setting.spt_linear_CFG_Quality elif param_setting == "Fidelity": s_cfg = default_setting.s_cfg_Fidelity spt_linear_CFG = default_setting.spt_linear_CFG_Fidelity else: raise NotImplementedError return 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
def submit_feedback(event_id, fb_score, fb_text): if args.log_history: with open(f'./history/{event_id[:5]}/{event_id[5:]}/logs.txt', 'r') as f: event_dict = eval(f.read()) f.close() event_dict['feedback'] = {'score': fb_score, 'text': fb_text} with open(f'./history/{event_id[:5]}/{event_id[5:]}/logs.txt', 'w') as f: f.write(str(event_dict)) f.close() return 'Submit successfully, thank you for your comments!' else: return 'Submit failed, the server is not set to log history.'
title_md = """# **SUPIR: Practicing Model Scaling for Photo-Realistic Image Restoration**
⚠️SUPIR is still a research project under tested and is not yet a stable commercial product.
[[Paper](https://arxiv.org/abs/2401.13627)]   [[Project Page](http://supir.xpixel.group/)]   [[How to play](https://github.com/Fanghua-Yu/SUPIR/blob/master/assets/DemoGuide.png)]"""
claim_md = """## **Terms of use**
By using this service, users are required to agree to the following terms: The service is a research preview intended for non-commercial use only. It only provides limited safety measures and may generate offensive content. It must not be used for any illegal, harmful, violent, racist, or sexual purposes. The service may collect user dialogue data for future research. Please submit a feedback to us if you get any inappropriate answer! We will collect those to keep improving our models. For an optimal experience, please use desktop computers for this demo, as mobile devices may compromise its quality.
## **License**
The service is a research preview intended for non-commercial use only, subject to the model [License](https://github.com/Fanghua-Yu/SUPIR) of SUPIR."""
block = gr.Blocks(title='SUPIR').queue()with block: with gr.Row(): gr.Markdown(title_md) with gr.Row(): with gr.Column(): with gr.Row(equal_height=True): with gr.Column(): gr.Markdown("<center>Input</center>") input_image = gr.Image(type="numpy", elem_id="image-input", height=400, width=400) with gr.Column(): gr.Markdown("<center>Stage1 Output</center>") denoise_image = gr.Image(type="numpy", elem_id="image-s1", height=400, width=400) prompt = gr.Textbox(label="Prompt", value="") with gr.Accordion("Stage1 options", open=False): gamma_correction = gr.Slider(label="Gamma Correction", minimum=0.1, maximum=2.0, value=1.0, step=0.1) with gr.Accordion("LLaVA options", open=False): temperature = gr.Slider(label="Temperature", minimum=0., maximum=1.0, value=0.2, step=0.1) top_p = gr.Slider(label="Top P", minimum=0., maximum=1.0, value=0.7, step=0.1) qs = gr.Textbox(label="Question", value="Describe this image and its style in a very detailed manner. " "The image is a realistic photography, not an art painting.") with gr.Accordion("Stage2 options", open=False): num_samples = gr.Slider(label="Num Samples", minimum=1, maximum=4 if not args.use_image_slider else 1 , value=1, step=1) upscale = gr.Slider(label="Upscale", minimum=1, maximum=8, value=1, step=1) edm_steps = gr.Slider(label="Steps", minimum=1, maximum=200, value=default_setting.edm_steps, step=1) s_cfg = gr.Slider(label="Text Guidance Scale", minimum=1.0, maximum=15.0, value=default_setting.s_cfg_Quality, step=0.1) s_stage2 = gr.Slider(label="Stage2 Guidance Strength", minimum=0., maximum=1., value=1., step=0.05) s_stage1 = gr.Slider(label="Stage1 Guidance Strength", minimum=-1.0, maximum=6.0, value=-1.0, step=1.0) seed = gr.Slider(label="Seed", minimum=-1, maximum=2147483647, step=1, randomize=True) 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) a_prompt = gr.Textbox(label="Default Positive Prompt", 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.') n_prompt = gr.Textbox(label="Default Negative Prompt", value='painting, oil painting, illustration, drawing, art, sketch, oil painting, ' 'cartoon, CG Style, 3D render, unreal engine, blurring, dirty, messy, ' 'worst quality, low quality, frames, watermark, signature, jpeg artifacts, ' 'deformed, lowres, over-smooth') 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, step=0.5) with gr.Column(): linear_s_stage2 = gr.Checkbox(label="Linear Stage2 Guidance", value=False) spt_linear_s_stage2 = gr.Slider(label="Guidance Start", minimum=0., maximum=1., value=0., step=0.05) with gr.Row(): with gr.Column(): diff_dtype = gr.Radio(['fp32', 'fp16', 'bf16'], label="Diffusion Data Type", value="fp16", interactive=True) with gr.Column(): ae_dtype = gr.Radio(['fp32', 'bf16'], label="Auto-Encoder Data Type", value="bf16", interactive=True) with gr.Column(): color_fix_type = gr.Radio(["None", "AdaIn", "Wavelet"], label="Color-Fix Type", value="Wavelet", interactive=True) with gr.Column(): model_select = gr.Radio(["v0-Q", "v0-F"], label="Model Selection", value="v0-Q", interactive=True)
with gr.Column(): gr.Markdown("<center>Stage2 Output</center>") if not args.use_image_slider: result_gallery = gr.Gallery(label='Output', show_label=False, elem_id="gallery1") else: result_gallery = ImageSlider(label='Output', show_label=False, elem_id="gallery1") with gr.Row(): with gr.Column(): denoise_button = gr.Button(value="Stage1 Run") with gr.Column(): llave_button = gr.Button(value="LlaVa Run") with gr.Column(): diffusion_button = gr.Button(value="Stage2 Run") with gr.Row(): with gr.Column(): param_setting = gr.Dropdown(["Quality", "Fidelity"], interactive=True, label="Param Setting", value="Quality") with gr.Column(): restart_button = gr.Button(value="Reset Param", scale=2) with gr.Accordion("Feedback", open=True): fb_score = gr.Slider(label="Feedback Score", minimum=1, maximum=5, value=3, step=1, interactive=True) fb_text = gr.Textbox(label="Feedback Text", value="", placeholder='Please enter your feedback here.') submit_button = gr.Button(value="Submit Feedback") with gr.Row(): gr.Markdown(claim_md) event_id = gr.Textbox(label="Event ID", value="", visible=False)
llave_button.click(fn=llave_process, inputs=[denoise_image, temperature, top_p, qs], outputs=[prompt]) denoise_button.click(fn=stage1_process, inputs=[input_image, gamma_correction], outputs=[denoise_image]) stage2_ips = [input_image, prompt, a_prompt, n_prompt, num_samples, upscale, edm_steps, s_stage1, s_stage2, s_cfg, 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] diffusion_button.click(fn=stage2_process, inputs=stage2_ips, outputs=[result_gallery, event_id, fb_score, fb_text]) 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]) submit_button.click(fn=submit_feedback, inputs=[event_id, fb_score, fb_text], outputs=[fb_text])block.launch(server_name=server_ip, server_port=server_port)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411import os
import gradio as grfrom gradio_imageslider import ImageSliderimport argparsefrom SUPIR.util import HWC3, upscale_image, fix_resize, convert_dtypeimport numpy as npimport torchfrom SUPIR.util import create_SUPIR_model, load_QF_ckptfrom PIL import Imagefrom llava.llava_agent import LLavaAgentfrom CKPT_PTH import LLAVA_MODEL_PATHimport einopsimport copyimport timefrom omegaconf import OmegaConffrom SUPIR.utils.face_restoration_helper import FaceRestoreHelper
parser = argparse.ArgumentParser()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=False)parser.add_argument("--use_image_slider", action='store_true', default=False)parser.add_argument("--log_history", action='store_true', default=False)parser.add_argument("--loading_half_params", action='store_true', default=False)parser.add_argument("--use_tile_vae", action='store_true', default=False)parser.add_argument("--load_8bit_llava", action='store_true', default=False)parser.add_argument("--local_prompt", action='store_true', default=False)args = parser.parse_args()server_ip = args.ipserver_port = args.portuse_llava = not args.no_llava
if torch.cuda.device_count() >= 2: SUPIR_device = 'cuda:0' LLaVA_device = 'cuda:1'elif torch.cuda.device_count() == 1: SUPIR_device = 'cuda:0' LLaVA_device = 'cuda:0'else: raise ValueError('Currently support CUDA only.')
# load SUPIRconfig_path = 'options/SUPIR_v0.yaml'config = OmegaConf.load(config_path)model = create_SUPIR_model(config_path, SUPIR_sign='Q')if args.loading_half_params: model = model.half()if args.use_tile_vae: model.init_tile_vae(encoder_tile_size=512, decoder_tile_size=64)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('options/SUPIR_v0.yaml')
# load LLaVAif use_llava: llava_agent = LLavaAgent(LLAVA_MODEL_PATH, device=LLaVA_device, load_8bit=args.load_8bit_llava, load_4bit=False)else: llava_agent = None
# load face helperface_helper = FaceRestoreHelper( device=SUPIR_device, upscale_factor=1, face_size=1024, use_parse=True, det_model='retinaface_resnet50' )
# only exhibit the overall quality of the stage1 outputdef stage1_process(input_image, gamma_correction): torch.cuda.set_device(SUPIR_device) LQ = HWC3(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, :, :] 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) return LQ
def llave_process(input_image, upscale, temperature, top_p, qs=None): torch.cuda.set_device(SUPIR_device) input_image = HWC3(input_image) input_image = upscale_image(input_image, upscale, unit_resolution=32, min_size=1024) LQ = np.array(input_image) / 255 * 2 - 1 LQ = torch.tensor(LQ, dtype=torch.float32).permute(2, 0, 1).unsqueeze(0).to(SUPIR_device)[:, :3, :, :] 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) LQs = [Image.fromarray(LQ)]
face_helper.clean_all() face_helper.read_image(LQ) # get face landmarks for each face face_helper.get_face_landmarks_5(only_center_face=False, resize=640, eye_dist_threshold=5) face_helper.align_warp_face()
for face in face_helper.cropped_faces: LQs.append(Image.fromarray(face))
captions = [] torch.cuda.set_device(LLaVA_device) if use_llava: for LQ in LQs: captions += llava_agent.gen_image_caption([LQ], temperature=temperature, top_p=top_p, qs=qs) else: captions = ['LLaVA is not available. Please add text manually.'] del LQs[0] return str(captions), [np.array(face) for face in LQs]
def stage2_process(input_image, prompt, a_prompt, n_prompt, num_samples, upscale, edm_steps, s_stage1, s_stage2, s_cfg, 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, face_resolution, apply_bg, apply_face): torch.cuda.set_device(SUPIR_device) event_id = str(time.time_ns()) event_dict = {'event_id': event_id, 'localtime': time.ctime(), 'prompt': prompt, 'a_prompt': a_prompt, 'n_prompt': n_prompt, 'num_samples': num_samples, 'upscale': upscale, 'edm_steps': edm_steps, 's_stage1': s_stage1, 's_stage2': s_stage2, 's_cfg': s_cfg, 'seed': seed, 's_churn': s_churn, 's_noise': s_noise, 'color_fix_type': color_fix_type, 'diff_dtype': diff_dtype, 'ae_dtype': ae_dtype, 'gamma_correction': gamma_correction, 'linear_CFG': linear_CFG, 'linear_s_stage2': linear_s_stage2, 'spt_linear_CFG': spt_linear_CFG, 'spt_linear_s_stage2': spt_linear_s_stage2, 'model_select': model_select}
if model_select != model.current_model: if model_select == 'v0-Q': print('load v0-Q') model.load_state_dict(ckpt_Q, strict=False) model.current_model = 'v0-Q' elif model_select == 'v0-F': print('load v0-F') model.load_state_dict(ckpt_F, strict=False) model.current_model = 'v0-F' input_image = HWC3(input_image) input_image = upscale_image(input_image, upscale, unit_resolution=32, min_size=1024)
LQ = np.array(input_image) face_helper.clean_all() face_helper.read_image(LQ) # get face landmarks for each face face_helper.get_face_landmarks_5(only_center_face=False, resize=640, eye_dist_threshold=5) face_helper.align_warp_face()
LQ = LQ / 255 * 2 - 1 LQ = torch.tensor(LQ, dtype=torch.float32).permute(2, 0, 1).unsqueeze(0).to(SUPIR_device)[:, :3, :, :]
if use_llava and prompt != '': captions = eval(prompt) else: captions = [''] * (1 + len(face_helper.cropped_faces))
bg_caption, face_captions = captions[0], captions[1:]
model.ae_dtype = convert_dtype(ae_dtype) model.model.dtype = convert_dtype(diff_dtype)
_faces = [] if apply_face: faces = [] for face in face_helper.cropped_faces: _faces.append(face) face = np.array(face) / 255 * 2 - 1 face = torch.tensor(face, dtype=torch.float32).permute(2, 0, 1).unsqueeze(0).to(SUPIR_device)[:, :3, :, :] faces.append(face)
for face, caption in zip(faces, face_captions): caption = [caption]
from torch.nn.functional import interpolate face = interpolate(face, size=face_resolution, mode='bilinear', align_corners=False) if face_resolution < 1024: face = torch.nn.functional.pad(face, (512-face_resolution//2, 512-face_resolution//2, 512-face_resolution//2, 512-face_resolution//2), 'constant', 0)
samples = model.batchify_sample(face, caption, num_steps=edm_steps, restoration_scale=s_stage1, s_churn=s_churn, s_noise=s_noise, cfg_scale=s_cfg, control_scale=s_stage2, seed=seed, num_samples=num_samples, p_p=a_prompt, n_p=n_prompt, color_fix_type=color_fix_type, use_linear_CFG=linear_CFG, use_linear_control_scale=linear_s_stage2, cfg_scale_start=spt_linear_CFG, control_scale_start=spt_linear_s_stage2) if face_resolution < 1024: samples = samples[:, :, 512-face_resolution//2:512+face_resolution//2, 512-face_resolution//2:512+face_resolution//2] samples = interpolate(samples, size=face_helper.face_size, mode='bilinear', align_corners=False) x_samples = (einops.rearrange(samples, 'b c h w -> b h w c') * 127.5 + 127.5).cpu().numpy().round().clip( 0, 255).astype(np.uint8)
face_helper.add_restored_face(x_samples[0]) _faces.append(x_samples[0])
if apply_bg: caption = [bg_caption] samples = model.batchify_sample(LQ, caption, num_steps=edm_steps, restoration_scale=s_stage1, s_churn=s_churn, s_noise=s_noise, cfg_scale=s_cfg, control_scale=s_stage2, seed=seed, num_samples=num_samples, p_p=a_prompt, n_p=n_prompt, color_fix_type=color_fix_type, use_linear_CFG=linear_CFG, use_linear_control_scale=linear_s_stage2, cfg_scale_start=spt_linear_CFG, control_scale_start=spt_linear_s_stage2) else: samples = LQ _bg = (einops.rearrange(samples, 'b c h w -> b h w c') * 127.5 + 127.5).cpu().numpy().round().clip( 0, 255).astype(np.uint8) face_helper.get_inverse_affine(None) results = [face_helper.paste_faces_to_input_image(upsample_img=_bg[0])] else: caption = [bg_caption] samples = model.batchify_sample(LQ, caption, num_steps=edm_steps, restoration_scale=s_stage1, s_churn=s_churn, s_noise=s_noise, cfg_scale=s_cfg, control_scale=s_stage2, seed=seed, num_samples=num_samples, p_p=a_prompt, n_p=n_prompt, color_fix_type=color_fix_type, use_linear_CFG=linear_CFG, use_linear_control_scale=linear_s_stage2, cfg_scale_start=spt_linear_CFG, control_scale_start=spt_linear_s_stage2) x_samples = (einops.rearrange(samples, 'b c h w -> b h w c') * 127.5 + 127.5).cpu().numpy().round().clip( 0, 255).astype(np.uint8) results = [x_samples[0]]
if args.log_history: os.makedirs(f'./history/{event_id[:5]}/{event_id[5:]}', exist_ok=True) with open(f'./history/{event_id[:5]}/{event_id[5:]}/logs.txt', 'w') as f: f.write(str(event_dict)) f.close() Image.fromarray(input_image).save(f'./history/{event_id[:5]}/{event_id[5:]}/LQ.png') for i, result in enumerate(results): Image.fromarray(result).save(f'./history/{event_id[:5]}/{event_id[5:]}/HQ_{i}.png') return [input_image] + results, event_id, 3, '', _faces
def load_and_reset(param_setting): edm_steps = 50 s_stage2 = 1.0 s_stage1 = -1.0 s_churn = 5 s_noise = 1.003 a_prompt = '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.' n_prompt = 'painting, oil painting, illustration, drawing, art, sketch, oil painting, cartoon, CG Style, ' \ '3D render, unreal engine, blurring, dirty, messy, worst quality, low quality, frames, watermark, ' \ 'signature, jpeg artifacts, deformed, lowres, over-smooth' color_fix_type = 'Wavelet' spt_linear_s_stage2 = 0.0 linear_s_stage2 = False linear_CFG = True if param_setting == "Quality": s_cfg = 7.5 spt_linear_CFG = 4.0 elif param_setting == "Fidelity": s_cfg = 4.0 spt_linear_CFG = 1.0 else: raise NotImplementedError return 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
def submit_feedback(event_id, fb_score, fb_text): if args.log_history: with open(f'./history/{event_id[:5]}/{event_id[5:]}/logs.txt', 'r') as f: event_dict = eval(f.read()) f.close() event_dict['feedback'] = {'score': fb_score, 'text': fb_text} with open(f'./history/{event_id[:5]}/{event_id[5:]}/logs.txt', 'w') as f: f.write(str(event_dict)) f.close() return 'Submit successfully, thank you for your comments!' else: return 'Submit failed, the server is not set to log history.'
title_md = """# **SUPIR: Practicing Model Scaling for Photo-Realistic Image Restoration**
⚠️SUPIR is still a research project under tested and is not yet a stable commercial product.
[[Paper](https://arxiv.org/abs/2401.13627)]   [[Project Page](http://supir.xpixel.group/)]   [[How to play](https://github.com/Fanghua-Yu/SUPIR/blob/master/assets/DemoGuide.png)]"""
claim_md = """## **Terms of use**
By using this service, users are required to agree to the following terms: The service is a research preview intended for non-commercial use only. It only provides limited safety measures and may generate offensive content. It must not be used for any illegal, harmful, violent, racist, or sexual purposes. The service may collect user dialogue data for future research. Please submit a feedback to us if you get any inappropriate answer! We will collect those to keep improving our models. For an optimal experience, please use desktop computers for this demo, as mobile devices may compromise its quality.
## **License**
The service is a research preview intended for non-commercial use only, subject to the model [License](https://github.com/Fanghua-Yu/SUPIR) of SUPIR."""
block = gr.Blocks(title='SUPIR').queue()with block: with gr.Row(): gr.Markdown(title_md) with gr.Row(): with gr.Column(): with gr.Row(equal_height=True): with gr.Column(): gr.Markdown("<center>Input</center>") input_image = gr.Image(type="numpy", elem_id="image-input", height=400, width=400) with gr.Column(): gr.Markdown("<center>Stage1 Output</center>") denoise_image = gr.Image(type="numpy", elem_id="image-s1", height=400, width=400) prompt = gr.Textbox(label="Prompt", value="") with gr.Accordion("Stage1 options", open=False): gamma_correction = gr.Slider(label="Gamma Correction", minimum=0.1, maximum=2.0, value=1.0, step=0.1) with gr.Accordion("LLaVA options", open=False): temperature = gr.Slider(label="Temperature", minimum=0., maximum=1.0, value=0.2, step=0.1) top_p = gr.Slider(label="Top P", minimum=0., maximum=1.0, value=0.7, step=0.1) qs = gr.Textbox(label="Question", value="Describe this image and its style in a very detailed manner. " "The image is a realistic photography, not an art painting.") with gr.Accordion("Stage2 options", open=False): num_samples = gr.Slider(label="Num Samples", minimum=1, maximum=4 if not args.use_image_slider else 1 , value=1, step=1) upscale = gr.Slider(label="Upscale", minimum=1, maximum=8, value=1, step=1) edm_steps = gr.Slider(label="Steps", minimum=20, maximum=200, value=50, step=1) s_cfg = gr.Slider(label="Text Guidance Scale", minimum=1.0, maximum=15.0, value=7.5, step=0.1) s_stage2 = gr.Slider(label="Stage2 Guidance Strength", minimum=0., maximum=1., value=1., step=0.05) s_stage1 = gr.Slider(label="Stage1 Guidance Strength", minimum=-1.0, maximum=6.0, value=-1.0, step=1.0) seed = gr.Slider(label="Seed", minimum=-1, maximum=2147483647, step=1, randomize=True) 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) a_prompt = gr.Textbox(label="Default Positive Prompt", 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.') n_prompt = gr.Textbox(label="Default Negative Prompt", value='painting, oil painting, illustration, drawing, art, sketch, oil painting, ' 'cartoon, CG Style, 3D render, unreal engine, blurring, dirty, messy, ' 'worst quality, low quality, frames, watermark, signature, jpeg artifacts, ' 'deformed, lowres, over-smooth') 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=4.0, step=0.5) with gr.Column(): linear_s_stage2 = gr.Checkbox(label="Linear Stage2 Guidance", value=False) spt_linear_s_stage2 = gr.Slider(label="Guidance Start", minimum=0., maximum=1., value=0., step=0.05) with gr.Row(): with gr.Column(): diff_dtype = gr.Radio(['fp32', 'fp16', 'bf16'], label="Diffusion Data Type", value="fp16", interactive=True) with gr.Column(): ae_dtype = gr.Radio(['fp32', 'bf16'], label="Auto-Encoder Data Type", value="bf16", interactive=True) with gr.Column(): color_fix_type = gr.Radio(["None", "AdaIn", "Wavelet"], label="Color-Fix Type", value="Wavelet", interactive=True) with gr.Column(): model_select = gr.Radio(["v0-Q", "v0-F"], label="Model Selection", value="v0-Q", interactive=True)
with gr.Column(): gr.Markdown("<center>Stage2 Output</center>") if not args.use_image_slider: result_gallery = gr.Gallery(label='Output', show_label=False, elem_id="gallery1") else: result_gallery = ImageSlider(label='Output', show_label=False, elem_id="gallery1") with gr.Row(): with gr.Column(): denoise_button = gr.Button(value="Stage1 Run") with gr.Column(): llave_button = gr.Button(value="LlaVa Run") with gr.Column(): diffusion_button = gr.Button(value="Stage2 Run") with gr.Row(): with gr.Column(): param_setting = gr.Dropdown(["Quality", "Fidelity"], interactive=True, label="Param Setting", value="Quality") with gr.Column(): restart_button = gr.Button(value="Reset Param", scale=2) with gr.Accordion("Face Options", open=True): face_resolution = gr.Slider(label="Text Guidance Scale", minimum=256, maximum=2048, value=1024, step=32) with gr.Row(): with gr.Column(): apply_bg = gr.Checkbox(label="BG restoration", value=True) with gr.Column(): apply_face = gr.Checkbox(label="Face restoration", value=True) with gr.Accordion("Feedback", open=False): fb_score = gr.Slider(label="Feedback Score", minimum=1, maximum=5, value=3, step=1, interactive=True) fb_text = gr.Textbox(label="Feedback Text", value="", placeholder='Please enter your feedback here.') submit_button = gr.Button(value="Submit Feedback") face_gallery = gr.Gallery(label='Faces', show_label=False, elem_id="gallery2") with gr.Row(): gr.Markdown(claim_md) event_id = gr.Textbox(label="Event ID", value="", visible=False)
llave_button.click(fn=llave_process, inputs=[input_image, upscale, temperature, top_p, qs], outputs=[prompt, face_gallery]) denoise_button.click(fn=stage1_process, inputs=[input_image, gamma_correction], outputs=[denoise_image]) stage2_ips = [input_image, prompt, a_prompt, n_prompt, num_samples, upscale, edm_steps, s_stage1, s_stage2, s_cfg, 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, face_resolution, apply_bg, apply_face] diffusion_button.click(fn=stage2_process, inputs=stage2_ips, outputs=[result_gallery, event_id, fb_score, fb_text, face_gallery]) 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]) submit_button.click(fn=submit_feedback, inputs=[event_id, fb_score, fb_text], outputs=[fb_text])block.launch(server_name=server_ip, server_port=server_port)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339import os
import gradio as grfrom gradio_imageslider import ImageSliderimport argparsefrom SUPIR.util import HWC3, upscale_image, fix_resize, convert_dtypeimport numpy as npimport torchfrom SUPIR.util import create_SUPIR_model, load_QF_ckptfrom PIL import Imagefrom llava.llava_agent import LLavaAgentfrom CKPT_PTH import LLAVA_MODEL_PATHimport einopsimport copyimport timefrom omegaconf import OmegaConffrom sgm.modules.diffusionmodules.sampling import _sliding_windows
parser = argparse.ArgumentParser()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=False)parser.add_argument("--use_image_slider", action='store_true', default=False)parser.add_argument("--log_history", action='store_true', default=False)parser.add_argument("--loading_half_params", action='store_true', default=False)parser.add_argument("--use_tile_vae", action='store_true', default=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)parser.add_argument("--local_prompt", action='store_true', default=False)args = parser.parse_args()server_ip = args.ipserver_port = args.portuse_llava = not args.no_llava
if torch.cuda.device_count() >= 2: SUPIR_device = 'cuda:0' LLaVA_device = 'cuda:1'elif torch.cuda.device_count() == 1: SUPIR_device = 'cuda:0' LLaVA_device = 'cuda:0'else: raise ValueError('Currently support CUDA only.')
# load SUPIRconfig_path = 'options/SUPIR_v0_tiled.yaml'config = OmegaConf.load(config_path)model = create_SUPIR_model(config_path, SUPIR_sign='Q')if args.loading_half_params: model = model.half()if args.use_tile_vae: model.init_tile_vae(encoder_tile_size=512, decoder_tile_size=64)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('options/SUPIR_v0.yaml')
tile_size = config.model.params.sampler_config.params.tile_size * 8tile_stride = config.model.params.sampler_config.params.tile_stride * 8
# load LLaVAif use_llava: llava_agent = LLavaAgent(LLAVA_MODEL_PATH, device=LLaVA_device, load_8bit=args.load_8bit_llava, load_4bit=False)else: llava_agent = None
# only exhibit the overall quality of the stage1 outputdef stage1_process(input_image, gamma_correction): torch.cuda.set_device(SUPIR_device) LQ = HWC3(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, :, :] 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) return LQ
def llave_process(input_image, upscale, temperature, top_p, qs=None): torch.cuda.set_device(SUPIR_device) input_image = HWC3(input_image) input_image = upscale_image(input_image, upscale, unit_resolution=32, min_size=1024) LQ = np.array(input_image) / 255.0 LQ *= 255.0 LQ = LQ.round().clip(0, 255).astype(np.uint8) LQ = LQ / 255 * 2 - 1 LQ = torch.tensor(LQ, dtype=torch.float32).permute(2, 0, 1).unsqueeze(0).to(SUPIR_device)[:, :3, :, :] LQ = model.batchify_denoise(LQ, is_stage1=True)
_, _, h, w = LQ.shape tiles_iterator = _sliding_windows(h, w, tile_size, tile_stride) LQ_tiles = [] for hi, hi_end, wi, wi_end in tiles_iterator: _LQ = LQ[:, :, hi:hi_end, wi:wi_end] _LQ = (_LQ[0].permute(1, 2, 0) * 127.5 + 127.5).cpu().numpy().round().clip(0, 255).astype(np.uint8) LQ_tiles.append(Image.fromarray(_LQ))
captions = [] torch.cuda.set_device(LLaVA_device) if use_llava: for LQ_tile in LQ_tiles: captions += llava_agent.gen_image_caption([LQ_tile], temperature=temperature, top_p=top_p, qs=qs) else: captions = 'LLaVA is not available. Please add text manually.' return str(captions)
def stage2_process(input_image, prompt, a_prompt, n_prompt, num_samples, upscale, edm_steps, s_stage1, s_stage2, s_cfg, 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): torch.cuda.set_device(SUPIR_device) event_id = str(time.time_ns()) event_dict = {'event_id': event_id, 'localtime': time.ctime(), 'prompt': prompt, 'a_prompt': a_prompt, 'n_prompt': n_prompt, 'num_samples': num_samples, 'upscale': upscale, 'edm_steps': edm_steps, 's_stage1': s_stage1, 's_stage2': s_stage2, 's_cfg': s_cfg, 'seed': seed, 's_churn': s_churn, 's_noise': s_noise, 'color_fix_type': color_fix_type, 'diff_dtype': diff_dtype, 'ae_dtype': ae_dtype, 'gamma_correction': gamma_correction, 'linear_CFG': linear_CFG, 'linear_s_stage2': linear_s_stage2, 'spt_linear_CFG': spt_linear_CFG, 'spt_linear_s_stage2': spt_linear_s_stage2, 'model_select': model_select}
if model_select != model.current_model: if model_select == 'v0-Q': print('load v0-Q') model.load_state_dict(ckpt_Q, strict=False) model.current_model = 'v0-Q' elif model_select == 'v0-F': print('load v0-F') model.load_state_dict(ckpt_F, strict=False) model.current_model = 'v0-F' input_image = HWC3(input_image) input_image = upscale_image(input_image, upscale, unit_resolution=32, min_size=1024)
LQ = np.array(input_image) / 255.0 LQ = np.power(LQ, gamma_correction) LQ *= 255.0 LQ = LQ.round().clip(0, 255).astype(np.uint8) LQ = LQ / 255 * 2 - 1 LQ = torch.tensor(LQ, dtype=torch.float32).permute(2, 0, 1).unsqueeze(0).to(SUPIR_device)[:, :3, :, :] if use_llava: captions = [eval(prompt)] else: captions = ['']
model.ae_dtype = convert_dtype(ae_dtype) model.model.dtype = convert_dtype(diff_dtype)
samples = model.batchify_sample(LQ, captions, num_steps=edm_steps, restoration_scale=s_stage1, s_churn=s_churn, s_noise=s_noise, cfg_scale=s_cfg, control_scale=s_stage2, seed=seed, num_samples=num_samples, p_p=a_prompt, n_p=n_prompt, color_fix_type=color_fix_type, use_linear_CFG=linear_CFG, use_linear_control_scale=linear_s_stage2, cfg_scale_start=spt_linear_CFG, control_scale_start=spt_linear_s_stage2)
x_samples = (einops.rearrange(samples, 'b c h w -> b h w c') * 127.5 + 127.5).cpu().numpy().round().clip( 0, 255).astype(np.uint8) results = [x_samples[i] for i in range(num_samples)]
if args.log_history: os.makedirs(f'./history/{event_id[:5]}/{event_id[5:]}', exist_ok=True) with open(f'./history/{event_id[:5]}/{event_id[5:]}/logs.txt', 'w') as f: f.write(str(event_dict)) f.close() Image.fromarray(input_image).save(f'./history/{event_id[:5]}/{event_id[5:]}/LQ.png') for i, result in enumerate(results): Image.fromarray(result).save(f'./history/{event_id[:5]}/{event_id[5:]}/HQ_{i}.png') return [input_image] + results, event_id, 3, ''
def load_and_reset(param_setting): edm_steps = 50 s_stage2 = 1.0 s_stage1 = -1.0 s_churn = 5 s_noise = 1.003 a_prompt = '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.' n_prompt = 'painting, oil painting, illustration, drawing, art, sketch, oil painting, cartoon, CG Style, ' \ '3D render, unreal engine, blurring, dirty, messy, worst quality, low quality, frames, watermark, ' \ 'signature, jpeg artifacts, deformed, lowres, over-smooth' color_fix_type = 'Wavelet' spt_linear_s_stage2 = 0.0 linear_s_stage2 = False linear_CFG = True if param_setting == "Quality": s_cfg = 7.5 spt_linear_CFG = 4.0 elif param_setting == "Fidelity": s_cfg = 4.0 spt_linear_CFG = 1.0 else: raise NotImplementedError return 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
def submit_feedback(event_id, fb_score, fb_text): if args.log_history: with open(f'./history/{event_id[:5]}/{event_id[5:]}/logs.txt', 'r') as f: event_dict = eval(f.read()) f.close() event_dict['feedback'] = {'score': fb_score, 'text': fb_text} with open(f'./history/{event_id[:5]}/{event_id[5:]}/logs.txt', 'w') as f: f.write(str(event_dict)) f.close() return 'Submit successfully, thank you for your comments!' else: return 'Submit failed, the server is not set to log history.'
title_md = """# **SUPIR: Practicing Model Scaling for Photo-Realistic Image Restoration**
⚠️SUPIR is still a research project under tested and is not yet a stable commercial product.
[[Paper](https://arxiv.org/abs/2401.13627)]   [[Project Page](http://supir.xpixel.group/)]   [[How to play](https://github.com/Fanghua-Yu/SUPIR/blob/master/assets/DemoGuide.png)]"""
claim_md = """## **Terms of use**
By using this service, users are required to agree to the following terms: The service is a research preview intended for non-commercial use only. It only provides limited safety measures and may generate offensive content. It must not be used for any illegal, harmful, violent, racist, or sexual purposes. The service may collect user dialogue data for future research. Please submit a feedback to us if you get any inappropriate answer! We will collect those to keep improving our models. For an optimal experience, please use desktop computers for this demo, as mobile devices may compromise its quality.
## **License**
The service is a research preview intended for non-commercial use only, subject to the model [License](https://github.com/Fanghua-Yu/SUPIR) of SUPIR."""
block = gr.Blocks(title='SUPIR').queue()with block: with gr.Row(): gr.Markdown(title_md) with gr.Row(): with gr.Column(): with gr.Row(equal_height=True): with gr.Column(): gr.Markdown("<center>Input</center>") input_image = gr.Image(type="numpy", elem_id="image-input", height=400, width=400) with gr.Column(): gr.Markdown("<center>Stage1 Output</center>") denoise_image = gr.Image(type="numpy", elem_id="image-s1", height=400, width=400) prompt = gr.Textbox(label="Prompt", value="") with gr.Accordion("Stage1 options", open=False): gamma_correction = gr.Slider(label="Gamma Correction", minimum=0.1, maximum=2.0, value=1.0, step=0.1) with gr.Accordion("LLaVA options", open=False): temperature = gr.Slider(label="Temperature", minimum=0., maximum=1.0, value=0.2, step=0.1) top_p = gr.Slider(label="Top P", minimum=0., maximum=1.0, value=0.7, step=0.1) qs = gr.Textbox(label="Question", value="Describe this image and its style in a very detailed manner. " "The image is a realistic photography, not an art painting.") with gr.Accordion("Stage2 options", open=False): num_samples = gr.Slider(label="Num Samples", minimum=1, maximum=4 if not args.use_image_slider else 1 , value=1, step=1) upscale = gr.Slider(label="Upscale", minimum=1, maximum=8, value=1, step=1) edm_steps = gr.Slider(label="Steps", minimum=20, maximum=200, value=50, step=1) s_cfg = gr.Slider(label="Text Guidance Scale", minimum=1.0, maximum=15.0, value=7.5, step=0.1) s_stage2 = gr.Slider(label="Stage2 Guidance Strength", minimum=0., maximum=1., value=1., step=0.05) s_stage1 = gr.Slider(label="Stage1 Guidance Strength", minimum=-1.0, maximum=6.0, value=-1.0, step=1.0) seed = gr.Slider(label="Seed", minimum=-1, maximum=2147483647, step=1, randomize=True) 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) a_prompt = gr.Textbox(label="Default Positive Prompt", 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.') n_prompt = gr.Textbox(label="Default Negative Prompt", value='painting, oil painting, illustration, drawing, art, sketch, oil painting, ' 'cartoon, CG Style, 3D render, unreal engine, blurring, dirty, messy, ' 'worst quality, low quality, frames, watermark, signature, jpeg artifacts, ' 'deformed, lowres, over-smooth') 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=4.0, step=0.5) with gr.Column(): linear_s_stage2 = gr.Checkbox(label="Linear Stage2 Guidance", value=False) spt_linear_s_stage2 = gr.Slider(label="Guidance Start", minimum=0., maximum=1., value=0., step=0.05) with gr.Row(): with gr.Column(): diff_dtype = gr.Radio(['fp32', 'fp16', 'bf16'], label="Diffusion Data Type", value="fp16", interactive=True) with gr.Column(): ae_dtype = gr.Radio(['fp32', 'bf16'], label="Auto-Encoder Data Type", value="bf16", interactive=True) with gr.Column(): color_fix_type = gr.Radio(["None", "AdaIn", "Wavelet"], label="Color-Fix Type", value="Wavelet", interactive=True) with gr.Column(): model_select = gr.Radio(["v0-Q", "v0-F"], label="Model Selection", value="v0-Q", interactive=True)
with gr.Column(): gr.Markdown("<center>Stage2 Output</center>") if not args.use_image_slider: result_gallery = gr.Gallery(label='Output', show_label=False, elem_id="gallery1") else: result_gallery = ImageSlider(label='Output', show_label=False, elem_id="gallery1") with gr.Row(): with gr.Column(): denoise_button = gr.Button(value="Stage1 Run") with gr.Column(): llave_button = gr.Button(value="LlaVa Run") with gr.Column(): diffusion_button = gr.Button(value="Stage2 Run") with gr.Row(): with gr.Column(): param_setting = gr.Dropdown(["Quality", "Fidelity"], interactive=True, label="Param Setting", value="Quality") with gr.Column(): restart_button = gr.Button(value="Reset Param", scale=2) with gr.Accordion("Feedback", open=True): fb_score = gr.Slider(label="Feedback Score", minimum=1, maximum=5, value=3, step=1, interactive=True) fb_text = gr.Textbox(label="Feedback Text", value="", placeholder='Please enter your feedback here.') submit_button = gr.Button(value="Submit Feedback") with gr.Row(): gr.Markdown(claim_md) event_id = gr.Textbox(label="Event ID", value="", visible=False)
llave_button.click(fn=llave_process, inputs=[input_image, upscale, temperature, top_p, qs], outputs=[prompt]) denoise_button.click(fn=stage1_process, inputs=[input_image, gamma_correction], outputs=[denoise_image]) stage2_ips = [input_image, prompt, a_prompt, n_prompt, num_samples, upscale, edm_steps, s_stage1, s_stage2, s_cfg, 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] diffusion_button.click(fn=stage2_process, inputs=stage2_ips, outputs=[result_gallery, event_id, fb_score, fb_text]) 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]) submit_button.click(fn=submit_feedback, inputs=[event_id, fb_score, fb_text], outputs=[fb_text])block.launch(server_name=server_ip, server_port=server_port)12345678torchvisiondiffuserstransformersaccelerateftfyscipyimageioinvisible_watermark123456789101112131415161718192021222324252627282930313233343536373839404142fastapi==0.95.1gradio==4.16.0gradio_imageslider==0.0.17gradio_client==0.8.1Markdown==3.4.1numpy==1.24.2requests==2.28.2sentencepiece==0.1.98tokenizers==0.13.3torch>=2.1.0torchvision>=0.16.0uvicorn==0.21.1wandb==0.14.0httpx==0.24.0transformers==4.28.1accelerate==0.18.0scikit-learn==1.2.2sentencepiece==0.1.98einops==0.7.0einops-exts==0.0.4timm==0.9.8openai-clip==1.0.1fsspec==2023.4.0kornia==0.6.9matplotlib==3.7.1ninja==1.11.1omegaconf==2.3.0open-clip-torch==2.17.1opencv-python==4.7.0.72pandas==2.0.1Pillow==9.4.0pytorch-lightning==2.1.2PyYAML==6.0scipy==1.9.1tqdm==4.65.0triton==2.1.0urllib3==1.26.15webdataset==0.2.48xformers>=0.0.20facexlib==0.3.0k-diffusion==0.1.1.post1diffusers==0.16.1
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106import torch.cudaimport argparsefrom SUPIR.util import create_SUPIR_model, PIL2Tensor, Tensor2PIL, convert_dtypefrom PIL import Imagefrom llava.llava_agent import LLavaAgentfrom CKPT_PTH import LLAVA_MODEL_PATHimport osfrom torch.nn.functional import interpolate
if torch.cuda.device_count() >= 2: SUPIR_device = 'cuda:0' LLaVA_device = 'cuda:1'elif torch.cuda.device_count() == 1: SUPIR_device = 'cuda:0' LLaVA_device = 'cuda:0'else: raise ValueError('Currently support CUDA only.')
# hyparams hereparser = argparse.ArgumentParser()parser.add_argument("--img_dir", type=str)parser.add_argument("--save_dir", type=str)parser.add_argument("--upscale", type=int, default=1)parser.add_argument("--SUPIR_sign", type=str, default='Q', choices=['F', 'Q'])parser.add_argument("--seed", type=int, default=1234)parser.add_argument("--min_size", type=int, default=1024)parser.add_argument("--edm_steps", type=int, default=50)parser.add_argument("--s_stage1", type=int, default=-1)parser.add_argument("--s_churn", type=int, default=5)parser.add_argument("--s_noise", type=float, default=1.003)parser.add_argument("--s_cfg", type=float, default=7.5)parser.add_argument("--s_stage2", type=float, default=1.)parser.add_argument("--num_samples", type=int, default=1)parser.add_argument("--a_prompt", type=str, default='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.')parser.add_argument("--n_prompt", type=str, default='painting, oil painting, illustration, drawing, art, sketch, oil painting, ' 'cartoon, CG Style, 3D render, unreal engine, blurring, dirty, messy, ' 'worst quality, low quality, frames, watermark, signature, jpeg artifacts, ' 'deformed, lowres, over-smooth')parser.add_argument("--color_fix_type", type=str, default='Wavelet', choices=["None", "AdaIn", "Wavelet"])parser.add_argument("--linear_CFG", action='store_true', default=True)parser.add_argument("--linear_s_stage2", action='store_true', default=False)parser.add_argument("--spt_linear_CFG", type=float, default=4.0)parser.add_argument("--spt_linear_s_stage2", type=float, default=0.)parser.add_argument("--ae_dtype", type=str, default="bf16", choices=['fp32', 'bf16'])parser.add_argument("--diff_dtype", type=str, default="fp16", choices=['fp32', 'fp16', 'bf16'])parser.add_argument("--no_llava", action='store_true', default=False)parser.add_argument("--loading_half_params", action='store_true', default=False)parser.add_argument("--use_tile_vae", action='store_true', default=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()print(args)use_llava = not args.no_llava
# load SUPIRmodel = create_SUPIR_model('options/SUPIR_v0.yaml', SUPIR_sign=args.SUPIR_sign)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.ae_dtype = convert_dtype(args.ae_dtype)model.model.dtype = convert_dtype(args.diff_dtype)model = model.to(SUPIR_device)# load LLaVAif use_llava: llava_agent = LLavaAgent(LLAVA_MODEL_PATH, device=LLaVA_device, load_8bit=args.load_8bit_llava, load_4bit=False)else: llava_agent = None
os.makedirs(args.save_dir, exist_ok=True)for img_pth in os.listdir(args.img_dir): img_name = os.path.splitext(img_pth)[0]
LQ_ips = Image.open(os.path.join(args.img_dir, img_pth)) LQ_img, h0, w0 = PIL2Tensor(LQ_ips, upsacle=args.upscale, min_size=args.min_size) LQ_img = LQ_img.unsqueeze(0).to(SUPIR_device)[:, :3, :, :]
# step 1: Pre-denoise for LLaVA, resize to 512 LQ_img_512, h1, w1 = PIL2Tensor(LQ_ips, upsacle=args.upscale, min_size=args.min_size, fix_resize=512) LQ_img_512 = LQ_img_512.unsqueeze(0).to(SUPIR_device)[:, :3, :, :] clean_imgs = model.batchify_denoise(LQ_img_512) clean_PIL_img = Tensor2PIL(clean_imgs[0], h1, w1)
# step 2: LLaVA if use_llava: captions = llava_agent.gen_image_caption([clean_PIL_img]) else: captions = [''] print(captions)
# # step 3: Diffusion Process samples = model.batchify_sample(LQ_img, captions, num_steps=args.edm_steps, restoration_scale=args.s_stage1, s_churn=args.s_churn, s_noise=args.s_noise, cfg_scale=args.s_cfg, control_scale=args.s_stage2, seed=args.seed, num_samples=args.num_samples, p_p=args.a_prompt, n_p=args.n_prompt, color_fix_type=args.color_fix_type, use_linear_CFG=args.linear_CFG, use_linear_control_scale=args.linear_s_stage2, cfg_scale_start=args.spt_linear_CFG, control_scale_start=args.spt_linear_s_stage2) # save for _i, sample in enumerate(samples): Tensor2PIL(sample, h0, w0).save(f'{args.save_dir}/{img_name}_{_i}.png')
CKPT_PTH.pyAdded+4
Examples/Example1.pngDeleted

Large File Pointer Details
- SHA256: 6d2b232ceb3e21af983307151c5e5b8ce5ea2e24b689feff544cfcc1019d0c91
- Pointer size: 132 Bytes
- Size of remote file: 1.24 MB
LICENSEAdded+18
README.md+154-20
app.pyDeleted-328
gradio_demo.pyAdded+314
gradio_demo_face.pyAdded+411
gradio_demo_tiled.pyAdded+339
requirements.txt+42-8
test.pyAdded+106