Fabrice-TIERCELIN commited on
Commit
42b0d88
·
verified ·
1 Parent(s): 61523b2

Upload 3 files

Browse files
Files changed (3) hide show
  1. README.md +18 -5
  2. app.py +880 -241
  3. requirements.txt +41 -8
README.md CHANGED
@@ -1,8 +1,21 @@
1
  ---
2
- title: Stable Video Diffusion Img2Vid
3
  sdk: gradio
4
- emoji: ✨🎥
5
- colorFrom: red
6
- colorTo: blue
7
- short_description: Animate Your Pictures With Stable VIdeo DIffusion
 
 
 
 
 
 
 
 
 
 
 
 
 
8
  ---
 
1
  ---
2
+ title: SUPIR Image Upscaler
3
  sdk: gradio
4
+ emoji: 📷
5
+ sdk_version: 4.38.1
6
+ app_file: app.py
7
+ license: mit
8
+ colorFrom: blue
9
+ colorTo: pink
10
+ tags:
11
+ - Upscaling
12
+ - Restoring
13
+ - Image-to-Image
14
+ - Image-2-Image
15
+ - Img-to-Img
16
+ - Img-2-Img
17
+ - language models
18
+ - LLMs
19
+ short_description: Restore blurred or small images with prompt
20
+ suggested_hardware: zero-a10g
21
  ---
app.py CHANGED
@@ -1,109 +1,421 @@
1
- # -*- coding: UTF-8 -*-
2
-
3
  import gradio as gr
 
 
4
  import torch
5
- import os
6
- import random
7
- import time
8
  import math
 
 
9
  import spaces
10
- from glob import glob
11
- from pathlib import Path
12
- from typing import Optional
13
 
14
- from diffusers import StableVideoDiffusionPipeline
15
- from diffusers.utils import export_to_video, export_to_gif
16
  from PIL import Image
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
 
18
- fps25Pipe = StableVideoDiffusionPipeline.from_pretrained(
19
- "vdo/stable-video-diffusion-img2vid-xt-1-1", torch_dtype=torch.float16, variant="fp16"
20
- )
21
- fps25Pipe.to("cuda")
22
-
23
- fps14Pipe = StableVideoDiffusionPipeline.from_pretrained(
24
- "stabilityai/stable-video-diffusion-img2vid", torch_dtype=torch.float16, variant="fp16"
25
- )
26
- fps14Pipe.to("cuda")
27
-
28
- max_64_bit_int = 2**63 - 1
29
-
30
- def animate_example(
31
- image: Image,
32
- seed: Optional[int] = 42,
33
- randomize_seed: bool = True,
34
- motion_bucket_id: int = 127,
35
- fps_id: int = 6,
36
- noise_aug_strength: float = 0.1,
37
- decoding_t: int = 3,
38
- video_format: str = "mp4",
39
- frame_format: str = "webp",
40
- version: str = "auto",
41
- output_folder: str = "outputs",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
  ):
43
- video2, gif_output2, download_button2, gallery2, seed2, information_msg2, reset_btn2 = animate(
44
- image,
45
- seed,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46
  randomize_seed,
47
- motion_bucket_id,
48
- fps_id,
49
- noise_aug_strength,
50
- decoding_t,
51
- video_format,
52
- frame_format,
53
- version,
54
- output_folder)
55
-
56
- return video2
57
-
58
- def animate(
59
- image: Image,
60
- seed: Optional[int] = 42,
61
- randomize_seed: bool = True,
62
- motion_bucket_id: int = 127,
63
- fps_id: int = 6,
64
- noise_aug_strength: float = 0.1,
65
- decoding_t: int = 3,
66
- video_format: str = "mp4",
67
- frame_format: str = "webp",
68
- version: str = "auto",
69
- output_folder: str = "outputs",
70
  ):
71
- start = time.time()
72
- if image.mode == "RGBA":
73
- image = image.convert("RGB")
74
-
75
- if randomize_seed:
76
- seed = random.randint(0, max_64_bit_int)
77
-
78
- if version == "auto":
79
- if 14 < fps_id:
80
- version = "svdxt"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81
  else:
82
- version = "svd"
 
83
 
84
- frames = animate_on_gpu(
85
- image,
86
- seed,
87
- motion_bucket_id,
88
- fps_id,
89
- noise_aug_strength,
90
- decoding_t,
91
- version
92
- )
93
-
94
- os.makedirs(output_folder, exist_ok=True)
95
- base_count = len(glob(os.path.join(output_folder, "*." + video_format)))
96
- result_path = os.path.join(output_folder, f"{base_count:06d}." + video_format)
97
-
98
- if video_format == "gif":
99
- video_path = None
100
- gif_path = result_path
101
- export_to_gif(image=frames, output_gif_path=gif_path, fps=fps_id)
102
  else:
103
- video_path = result_path
104
- gif_path = None
105
- export_to_video(frames, video_path, fps=fps_id)
106
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
107
  end = time.time()
108
  secondes = int(end - start)
109
  minutes = math.floor(secondes / 60)
@@ -111,160 +423,487 @@ def animate(
111
  hours = math.floor(minutes / 60)
112
  minutes = minutes - (hours * 60)
113
  information = ("Start the process again if you want a different result. " if randomize_seed else "") + \
114
- "Wait 2 min before a new run to avoid quota penalty or use another computer. " + \
115
- "The video has been generated in " + \
 
116
  ((str(hours) + " h, ") if hours != 0 else "") + \
117
  ((str(minutes) + " min, ") if hours != 0 or minutes != 0 else "") + \
118
- str(secondes) + " sec."
119
-
120
- return gr.update(value=video_path, format=video_format if video_format != "gif" else None, visible=video_format != "gif"), gr.update(value=gif_path, visible=video_format == "gif"), gr.update(value=result_path, visible=True), gr.update(label="Generated frames in *." + frame_format + " format", format = frame_format, value = frames, visible=True), seed, gr.update(value = information, visible = True), gr.update(visible=True)
121
-
122
- @spaces.GPU(duration=120)
123
- def animate_on_gpu(
124
- image: Image,
125
- seed: Optional[int] = 42,
126
- motion_bucket_id: int = 127,
127
- fps_id: int = 6,
128
- noise_aug_strength: float = 0.1,
129
- decoding_t: int = 3,
130
- version: str = "svdxt"
131
- ):
132
- generator = torch.manual_seed(seed)
133
 
134
- if version == "svdxt":
135
- return fps25Pipe(image, decode_chunk_size=decoding_t, generator=generator, motion_bucket_id=motion_bucket_id, noise_aug_strength=noise_aug_strength, num_frames=25).frames[0]
136
- else:
137
- return fps14Pipe(image, decode_chunk_size=decoding_t, generator=generator, motion_bucket_id=motion_bucket_id, noise_aug_strength=noise_aug_strength, num_frames=25).frames[0]
138
-
139
-
140
- def resize_image(image, output_size=(1024, 576)):
141
- # Calculate aspect ratios
142
- target_aspect = output_size[0] / output_size[1] # Aspect ratio of the desired size
143
- image_aspect = image.width / image.height # Aspect ratio of the original image
144
-
145
- # Do not touch the image if the size is good
146
- if image.width == output_size[0] and image.height == output_size[1]:
147
- return image
148
-
149
- # Resize if the original image is larger
150
- if image_aspect > target_aspect:
151
- # Resize the image to match the target height, maintaining aspect ratio
152
- new_height = output_size[1]
153
- new_width = int(new_height * image_aspect)
154
- resized_image = image.resize((new_width, new_height), Image.LANCZOS)
155
- # Calculate coordinates for cropping
156
- left = (new_width - output_size[0]) / 2
157
- top = 0
158
- right = (new_width + output_size[0]) / 2
159
- bottom = output_size[1]
 
 
 
 
 
160
  else:
161
- # Resize the image to match the target width, maintaining aspect ratio
162
- new_width = output_size[0]
163
- new_height = int(new_width / image_aspect)
164
- resized_image = image.resize((new_width, new_height), Image.LANCZOS)
165
- # Calculate coordinates for cropping
166
- left = 0
167
- top = (new_height - output_size[1]) / 2
168
- right = output_size[0]
169
- bottom = (new_height + output_size[1]) / 2
170
-
171
- # Crop the image
172
- return resized_image.crop((left, top, right, bottom))
173
 
174
- def reset():
175
- return [
176
- None,
177
- random.randint(0, max_64_bit_int),
178
- True,
179
- 127,
180
- 6,
181
- 0.1,
182
- 3,
183
- "mp4",
184
- "webp",
185
- "auto"
186
- ]
187
 
188
- with gr.Blocks() as demo:
189
- gr.HTML("""
190
- <h1><center>Image-to-Video</center></h1>
191
- <big><center>Animate your images into 25 frames of 1024x576 pixels freely, without account, without watermark and download the video</center></big>
192
- <br/>
 
 
 
 
 
 
 
 
193
 
194
- <p>
195
- This demo is based on <i>Stable Video Diffusion</i> artificial intelligence.
196
- No prompt or camera control is handled here. To control motions, rather use <i><a href="https://huggingface.co/spaces/TencentARC/MotionCtrl_SVD">MotionCtrl SVD</a></i>.
197
- </p>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
198
  """)
199
- with gr.Row():
200
- with gr.Column():
201
- image = gr.Image(label="Upload your image", type="pil")
202
- with gr.Accordion("Advanced options", open=False):
203
- fps_id = gr.Slider(label="Frames per second", info="The length of your video in seconds will be 25/fps", value=6, minimum=5, maximum=30)
204
- motion_bucket_id = gr.Slider(label="Motion bucket id", info="Controls how much motion to add/remove from the image", value=127, minimum=1, maximum=255)
205
- noise_aug_strength = gr.Slider(label="Noise strength", info="The noise to add", value=0.1, minimum=0, maximum=1, step=0.1)
206
- decoding_t = gr.Slider(label="Decoding", info="Number of frames decoded at a time; this eats more VRAM; reduce if necessary", value=3, minimum=1, maximum=5, step=1)
207
- video_format = gr.Radio([["*.mp4", "mp4"], ["*.gif", "gif"]], label="Video format for result", info="File extention", value="mp4", interactive=True)
208
- frame_format = gr.Radio([["*.webp", "webp"], ["*.png", "png"], ["*.jpeg", "jpeg"], ["*.gif (unanimated)", "gif"], ["*.bmp", "bmp"]], label="Image format for frames", info="File extention", value="webp", interactive=True)
209
- version = gr.Radio([["Auto", "auto"], ["🏃🏻‍♀️ SVD (trained on 14 f/s)", "svd"], ["🏃🏻‍♀️💨 SVD-XT (trained on 25 f/s)", "svdxt"]], label="Model", info="Trained model", value="auto", interactive=True)
210
- seed = gr.Slider(label="Seed", value=42, randomize=True, minimum=0, maximum=max_64_bit_int, step=1)
211
- randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
212
-
213
- generate_btn = gr.Button(value="🚀 Animate", variant="primary")
214
- reset_btn = gr.Button(value="🧹 Reinit page", variant="stop", elem_id="reset_button", visible = False)
215
-
216
- with gr.Column():
217
- video_output = gr.Video(label="Generated video", autoplay=True)
218
- gif_output = gr.Image(label="Generated video", format="gif", visible=False)
219
- download_button = gr.DownloadButton(label="💾 Download video", visible=False)
220
- information_msg = gr.HTML(visible=False)
221
- gallery = gr.Gallery(label="Generated frames", visible=False)
222
-
223
- image.upload(fn=resize_image, inputs=image, outputs=image, queue=False)
224
- generate_btn.click(fn=animate, inputs=[
225
- image,
226
- seed,
227
- randomize_seed,
228
- motion_bucket_id,
229
- fps_id,
230
- noise_aug_strength,
231
- decoding_t,
232
- video_format,
233
- frame_format,
234
- version
235
- ], outputs=[
236
- video_output,
237
- gif_output,
238
- download_button,
239
- gallery,
240
- seed,
241
- information_msg,
242
- reset_btn
243
- ], api_name="video")
244
-
245
- reset_btn.click(fn = reset, inputs = [], outputs = [
246
- image,
247
- seed,
248
- randomize_seed,
249
- motion_bucket_id,
250
- fps_id,
251
- noise_aug_strength,
252
- decoding_t,
253
- video_format,
254
- frame_format,
255
- version
256
- ], queue = False, show_progress = False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
257
 
258
- gr.Examples(
259
- examples=[
260
- ["Example.png", 42, True, 3, 30, 0.1, 3, "mp4", "png", "svdxt"]
261
- ],
262
- inputs=[image, seed, randomize_seed, motion_bucket_id, fps_id, noise_aug_strength, decoding_t, video_format, frame_format, version],
263
- outputs=[video_output],
264
- fn=animate_example,
265
- run_on_click=True,
266
- cache_examples=True,
267
- )
268
-
269
- if __name__ == "__main__":
270
- demo.launch(share=True, show_api=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
 
2
  import gradio as gr
3
+ import argparse
4
+ import numpy as np
5
  import torch
6
+ import einops
7
+ import copy
 
8
  import math
9
+ import time
10
+ import random
11
  import spaces
12
+ import re
13
+ import uuid
 
14
 
15
+ from gradio_imageslider import ImageSlider
 
16
  from PIL import Image
17
+ from SUPIR.util import HWC3, upscale_image, fix_resize, convert_dtype, create_SUPIR_model, load_QF_ckpt
18
+ from huggingface_hub import hf_hub_download
19
+ from pillow_heif import register_heif_opener
20
+
21
+ register_heif_opener()
22
+
23
+ max_64_bit_int = np.iinfo(np.int32).max
24
+
25
+ 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")
26
+ hf_hub_download(repo_id="camenduru/SUPIR", filename="sd_xl_base_1.0_0.9vae.safetensors", local_dir="yushan777_SUPIR")
27
+ hf_hub_download(repo_id="camenduru/SUPIR", filename="SUPIR-v0F.ckpt", local_dir="yushan777_SUPIR")
28
+ hf_hub_download(repo_id="camenduru/SUPIR", filename="SUPIR-v0Q.ckpt", local_dir="yushan777_SUPIR")
29
+ hf_hub_download(repo_id="RunDiffusion/Juggernaut-XL-Lightning", filename="Juggernaut_RunDiffusionPhoto2_Lightning_4Steps.safetensors", local_dir="RunDiffusion_Juggernaut-XL-Lightning")
30
+
31
+ parser = argparse.ArgumentParser()
32
+ parser.add_argument("--opt", type=str, default='options/SUPIR_v0.yaml')
33
+ parser.add_argument("--ip", type=str, default='127.0.0.1')
34
+ parser.add_argument("--port", type=int, default='6688')
35
+ parser.add_argument("--no_llava", action='store_true', default=True)#False
36
+ parser.add_argument("--use_image_slider", action='store_true', default=False)#False
37
+ parser.add_argument("--log_history", action='store_true', default=False)
38
+ parser.add_argument("--loading_half_params", action='store_true', default=False)#False
39
+ parser.add_argument("--use_tile_vae", action='store_true', default=True)#False
40
+ parser.add_argument("--encoder_tile_size", type=int, default=512)
41
+ parser.add_argument("--decoder_tile_size", type=int, default=64)
42
+ parser.add_argument("--load_8bit_llava", action='store_true', default=False)
43
+ args = parser.parse_args()
44
+
45
+ if torch.cuda.device_count() > 0:
46
+ SUPIR_device = 'cuda:0'
47
+
48
+ # Load SUPIR
49
+ model, default_setting = create_SUPIR_model(args.opt, SUPIR_sign='Q', load_default_setting=True)
50
+ if args.loading_half_params:
51
+ model = model.half()
52
+ if args.use_tile_vae:
53
+ model.init_tile_vae(encoder_tile_size=args.encoder_tile_size, decoder_tile_size=args.decoder_tile_size)
54
+ model = model.to(SUPIR_device)
55
+ model.first_stage_model.denoise_encoder_s1 = copy.deepcopy(model.first_stage_model.denoise_encoder)
56
+ model.current_model = 'v0-Q'
57
+ ckpt_Q, ckpt_F = load_QF_ckpt(args.opt)
58
+
59
+ def check_upload(input_image):
60
+ if input_image is None:
61
+ raise gr.Error("Please provide an image to restore.")
62
+ return gr.update(visible = True)
63
 
64
+ def update_seed(is_randomize_seed, seed):
65
+ if is_randomize_seed:
66
+ return random.randint(0, max_64_bit_int)
67
+ return seed
68
+
69
+ def reset():
70
+ return [
71
+ None,
72
+ 0,
73
+ None,
74
+ None,
75
+ "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.",
76
+ "painting, oil painting, illustration, drawing, art, sketch, anime, cartoon, CG Style, 3D render, unreal engine, blurring, aliasing, pixel, unsharp, weird textures, ugly, dirty, messy, worst quality, low quality, frames, watermark, signature, jpeg artifacts, deformed, lowres, over-smooth",
77
+ 1,
78
+ 1024,
79
+ 1,
80
+ 2,
81
+ 50,
82
+ -1.0,
83
+ 1.,
84
+ default_setting.s_cfg_Quality if torch.cuda.device_count() > 0 else 1.0,
85
+ True,
86
+ random.randint(0, max_64_bit_int),
87
+ 5,
88
+ 1.003,
89
+ "Wavelet",
90
+ "fp32",
91
+ "fp32",
92
+ 1.0,
93
+ True,
94
+ False,
95
+ default_setting.spt_linear_CFG_Quality if torch.cuda.device_count() > 0 else 1.0,
96
+ 0.,
97
+ "v0-Q",
98
+ "input",
99
+ 6
100
+ ]
101
+
102
+ def check_and_update(input_image):
103
+ if input_image is None:
104
+ raise gr.Error("Please provide an image to restore.")
105
+ return gr.update(visible = True)
106
+
107
+ @spaces.GPU(duration=420)
108
+ def stage1_process(
109
+ input_image,
110
+ gamma_correction,
111
+ diff_dtype,
112
+ ae_dtype
113
  ):
114
+ print('stage1_process ==>>')
115
+ if torch.cuda.device_count() == 0:
116
+ gr.Warning('Set this space to GPU config to make it work.')
117
+ return None, None
118
+ torch.cuda.set_device(SUPIR_device)
119
+ LQ = HWC3(np.array(Image.open(input_image)))
120
+ LQ = fix_resize(LQ, 512)
121
+ # stage1
122
+ LQ = np.array(LQ) / 255 * 2 - 1
123
+ LQ = torch.tensor(LQ, dtype=torch.float32).permute(2, 0, 1).unsqueeze(0).to(SUPIR_device)[:, :3, :, :]
124
+
125
+ model.ae_dtype = convert_dtype(ae_dtype)
126
+ model.model.dtype = convert_dtype(diff_dtype)
127
+
128
+ LQ = model.batchify_denoise(LQ, is_stage1=True)
129
+ LQ = (LQ[0].permute(1, 2, 0) * 127.5 + 127.5).cpu().numpy().round().clip(0, 255).astype(np.uint8)
130
+ # gamma correction
131
+ LQ = LQ / 255.0
132
+ LQ = np.power(LQ, gamma_correction)
133
+ LQ *= 255.0
134
+ LQ = LQ.round().clip(0, 255).astype(np.uint8)
135
+ print('<<== stage1_process')
136
+ return LQ, gr.update(visible = True)
137
+
138
+ def stage2_process(*args, **kwargs):
139
+ try:
140
+ return restore_in_Xmin(*args, **kwargs)
141
+ except Exception as e:
142
+ # NO_GPU_MESSAGE_INQUEUE
143
+ print("gradio.exceptions.Error 'No GPU is currently available for you after 60s'")
144
+ print('str(type(e)): ' + str(type(e))) # <class 'gradio.exceptions.Error'>
145
+ print('str(e): ' + str(e)) # You have exceeded your GPU quota...
146
+ try:
147
+ print('e.message: ' + e.message) # No GPU is currently available for you after 60s
148
+ except Exception as e2:
149
+ print('Failure')
150
+ if str(e).startswith("No GPU is currently available for you after 60s"):
151
+ print('Exception identified!!!')
152
+ #if str(type(e)) == "<class 'gradio.exceptions.Error'>":
153
+ #print('Exception of name ' + type(e).__name__)
154
+ raise e
155
+
156
+ def restore_in_Xmin(
157
+ noisy_image,
158
+ rotation,
159
+ denoise_image,
160
+ prompt,
161
+ a_prompt,
162
+ n_prompt,
163
+ num_samples,
164
+ min_size,
165
+ downscale,
166
+ upscale,
167
+ edm_steps,
168
+ s_stage1,
169
+ s_stage2,
170
+ s_cfg,
171
  randomize_seed,
172
+ seed,
173
+ s_churn,
174
+ s_noise,
175
+ color_fix_type,
176
+ diff_dtype,
177
+ ae_dtype,
178
+ gamma_correction,
179
+ linear_CFG,
180
+ linear_s_stage2,
181
+ spt_linear_CFG,
182
+ spt_linear_s_stage2,
183
+ model_select,
184
+ output_format,
185
+ allocation
 
 
 
 
 
 
 
 
 
186
  ):
187
+ print("noisy_image:\n" + str(noisy_image))
188
+ print("denoise_image:\n" + str(denoise_image))
189
+ print("rotation: " + str(rotation))
190
+ print("prompt: " + str(prompt))
191
+ print("a_prompt: " + str(a_prompt))
192
+ print("n_prompt: " + str(n_prompt))
193
+ print("num_samples: " + str(num_samples))
194
+ print("min_size: " + str(min_size))
195
+ print("downscale: " + str(downscale))
196
+ print("upscale: " + str(upscale))
197
+ print("edm_steps: " + str(edm_steps))
198
+ print("s_stage1: " + str(s_stage1))
199
+ print("s_stage2: " + str(s_stage2))
200
+ print("s_cfg: " + str(s_cfg))
201
+ print("randomize_seed: " + str(randomize_seed))
202
+ print("seed: " + str(seed))
203
+ print("s_churn: " + str(s_churn))
204
+ print("s_noise: " + str(s_noise))
205
+ print("color_fix_type: " + str(color_fix_type))
206
+ print("diff_dtype: " + str(diff_dtype))
207
+ print("ae_dtype: " + str(ae_dtype))
208
+ print("gamma_correction: " + str(gamma_correction))
209
+ print("linear_CFG: " + str(linear_CFG))
210
+ print("linear_s_stage2: " + str(linear_s_stage2))
211
+ print("spt_linear_CFG: " + str(spt_linear_CFG))
212
+ print("spt_linear_s_stage2: " + str(spt_linear_s_stage2))
213
+ print("model_select: " + str(model_select))
214
+ print("GPU time allocation: " + str(allocation) + " min")
215
+ print("output_format: " + str(output_format))
216
+
217
+ input_format = re.sub(r"^.*\.([^\.]+)$", r"\1", noisy_image)
218
+
219
+ if input_format not in ['png', 'webp', 'jpg', 'jpeg', 'gif', 'bmp', 'heic']:
220
+ gr.Warning('Invalid image format. Please first convert into *.png, *.webp, *.jpg, *.jpeg, *.gif, *.bmp or *.heic.')
221
+ return None, None, None, None
222
+
223
+ if output_format == "input":
224
+ if noisy_image is None:
225
+ output_format = "png"
226
  else:
227
+ output_format = input_format
228
+ print("final output_format: " + str(output_format))
229
 
230
+ if prompt is None:
231
+ prompt = ""
232
+
233
+ if a_prompt is None:
234
+ a_prompt = ""
235
+
236
+ if n_prompt is None:
237
+ n_prompt = ""
238
+
239
+ if prompt != "" and a_prompt != "":
240
+ a_prompt = prompt + ", " + a_prompt
 
 
 
 
 
 
 
241
  else:
242
+ a_prompt = prompt + a_prompt
243
+ print("Final prompt: " + str(a_prompt))
244
+
245
+ denoise_image = np.array(Image.open(noisy_image if denoise_image is None else denoise_image))
246
+
247
+ if rotation == 90:
248
+ denoise_image = np.array(list(zip(*denoise_image[::-1])))
249
+ elif rotation == 180:
250
+ denoise_image = np.array(list(zip(*denoise_image[::-1])))
251
+ denoise_image = np.array(list(zip(*denoise_image[::-1])))
252
+ elif rotation == -90:
253
+ denoise_image = np.array(list(zip(*denoise_image))[::-1])
254
+
255
+ if 1 < downscale:
256
+ input_height, input_width, input_channel = denoise_image.shape
257
+ denoise_image = np.array(Image.fromarray(denoise_image).resize((input_width // downscale, input_height // downscale), Image.LANCZOS))
258
+
259
+ denoise_image = HWC3(denoise_image)
260
+
261
+ if torch.cuda.device_count() == 0:
262
+ gr.Warning('Set this space to GPU config to make it work.')
263
+ return [noisy_image, denoise_image], gr.update(label="Downloadable results in *." + output_format + " format", format = output_format, value = [denoise_image]), None, gr.update(visible=True)
264
+
265
+ if model_select != model.current_model:
266
+ print('load ' + model_select)
267
+ if model_select == 'v0-Q':
268
+ model.load_state_dict(ckpt_Q, strict=False)
269
+ elif model_select == 'v0-F':
270
+ model.load_state_dict(ckpt_F, strict=False)
271
+ model.current_model = model_select
272
+
273
+ model.ae_dtype = convert_dtype(ae_dtype)
274
+ model.model.dtype = convert_dtype(diff_dtype)
275
+
276
+ # Allocation
277
+ if allocation == 1:
278
+ return restore_in_1min(
279
+ noisy_image, 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
280
+ )
281
+ if allocation == 2:
282
+ return restore_in_2min(
283
+ noisy_image, 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
284
+ )
285
+ if allocation == 3:
286
+ return restore_in_3min(
287
+ noisy_image, 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
288
+ )
289
+ if allocation == 4:
290
+ return restore_in_4min(
291
+ noisy_image, 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
292
+ )
293
+ if allocation == 5:
294
+ return restore_in_5min(
295
+ noisy_image, 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
296
+ )
297
+ if allocation == 7:
298
+ return restore_in_7min(
299
+ noisy_image, 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
300
+ )
301
+ if allocation == 8:
302
+ return restore_in_8min(
303
+ noisy_image, 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
304
+ )
305
+ if allocation == 9:
306
+ return restore_in_9min(
307
+ noisy_image, 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
308
+ )
309
+ if allocation == 10:
310
+ return restore_in_10min(
311
+ noisy_image, 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
312
+ )
313
+ else:
314
+ return restore_in_6min(
315
+ noisy_image, 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
316
+ )
317
+
318
+ @spaces.GPU(duration=59)
319
+ def restore_in_1min(*args, **kwargs):
320
+ return restore_on_gpu(*args, **kwargs)
321
+
322
+ @spaces.GPU(duration=119)
323
+ def restore_in_2min(*args, **kwargs):
324
+ return restore_on_gpu(*args, **kwargs)
325
+
326
+ @spaces.GPU(duration=179)
327
+ def restore_in_3min(*args, **kwargs):
328
+ return restore_on_gpu(*args, **kwargs)
329
+
330
+ @spaces.GPU(duration=239)
331
+ def restore_in_4min(*args, **kwargs):
332
+ return restore_on_gpu(*args, **kwargs)
333
+
334
+ @spaces.GPU(duration=299)
335
+ def restore_in_5min(*args, **kwargs):
336
+ return restore_on_gpu(*args, **kwargs)
337
+
338
+ @spaces.GPU(duration=359)
339
+ def restore_in_6min(*args, **kwargs):
340
+ return restore_on_gpu(*args, **kwargs)
341
+
342
+ @spaces.GPU(duration=419)
343
+ def restore_in_7min(*args, **kwargs):
344
+ return restore_on_gpu(*args, **kwargs)
345
+
346
+ @spaces.GPU(duration=479)
347
+ def restore_in_8min(*args, **kwargs):
348
+ return restore_on_gpu(*args, **kwargs)
349
+
350
+ @spaces.GPU(duration=539)
351
+ def restore_in_9min(*args, **kwargs):
352
+ return restore_on_gpu(*args, **kwargs)
353
+
354
+ @spaces.GPU(duration=599)
355
+ def restore_in_10min(*args, **kwargs):
356
+ return restore_on_gpu(*args, **kwargs)
357
+
358
+ def restore_on_gpu(
359
+ noisy_image,
360
+ input_image,
361
+ prompt,
362
+ a_prompt,
363
+ n_prompt,
364
+ num_samples,
365
+ min_size,
366
+ downscale,
367
+ upscale,
368
+ edm_steps,
369
+ s_stage1,
370
+ s_stage2,
371
+ s_cfg,
372
+ randomize_seed,
373
+ seed,
374
+ s_churn,
375
+ s_noise,
376
+ color_fix_type,
377
+ diff_dtype,
378
+ ae_dtype,
379
+ gamma_correction,
380
+ linear_CFG,
381
+ linear_s_stage2,
382
+ spt_linear_CFG,
383
+ spt_linear_s_stage2,
384
+ model_select,
385
+ output_format,
386
+ allocation
387
+ ):
388
+ start = time.time()
389
+ print('restore ==>>')
390
+
391
+ torch.cuda.set_device(SUPIR_device)
392
+
393
+ with torch.no_grad():
394
+ input_image = upscale_image(input_image, upscale, unit_resolution=32, min_size=min_size)
395
+ LQ = np.array(input_image) / 255.0
396
+ LQ = np.power(LQ, gamma_correction)
397
+ LQ *= 255.0
398
+ LQ = LQ.round().clip(0, 255).astype(np.uint8)
399
+ LQ = LQ / 255 * 2 - 1
400
+ LQ = torch.tensor(LQ, dtype=torch.float32).permute(2, 0, 1).unsqueeze(0).to(SUPIR_device)[:, :3, :, :]
401
+ captions = ['']
402
+
403
+ samples = model.batchify_sample(LQ, captions, num_steps=edm_steps, restoration_scale=s_stage1, s_churn=s_churn,
404
+ s_noise=s_noise, cfg_scale=s_cfg, control_scale=s_stage2, seed=seed,
405
+ num_samples=num_samples, p_p=a_prompt, n_p=n_prompt, color_fix_type=color_fix_type,
406
+ use_linear_CFG=linear_CFG, use_linear_control_scale=linear_s_stage2,
407
+ cfg_scale_start=spt_linear_CFG, control_scale_start=spt_linear_s_stage2)
408
+
409
+ x_samples = (einops.rearrange(samples, 'b c h w -> b h w c') * 127.5 + 127.5).cpu().numpy().round().clip(
410
+ 0, 255).astype(np.uint8)
411
+ results = [x_samples[i] for i in range(num_samples)]
412
+ torch.cuda.empty_cache()
413
+
414
+ # All the results have the same size
415
+ input_height, input_width, input_channel = np.array(input_image).shape
416
+ result_height, result_width, result_channel = np.array(results[0]).shape
417
+
418
+ print('<<== restore')
419
  end = time.time()
420
  secondes = int(end - start)
421
  minutes = math.floor(secondes / 60)
 
423
  hours = math.floor(minutes / 60)
424
  minutes = minutes - (hours * 60)
425
  information = ("Start the process again if you want a different result. " if randomize_seed else "") + \
426
+ "If you don't get the image you wanted, add more details in the « Image description ». " + \
427
+ "Wait " + str(allocation) + " min before a new run to avoid quota penalty or use another computer. " + \
428
+ "The image" + (" has" if len(results) == 1 else "s have") + " been generated in " + \
429
  ((str(hours) + " h, ") if hours != 0 else "") + \
430
  ((str(minutes) + " min, ") if hours != 0 or minutes != 0 else "") + \
431
+ str(secondes) + " sec. " + \
432
+ "The new image resolution is " + str(result_width) + \
433
+ " pixels large and " + str(result_height) + \
434
+ " pixels high, so a resolution of " + f'{result_width * result_height:,}' + " pixels."
435
+ print(information)
436
+ try:
437
+ print("Initial resolution: " + f'{input_width * input_height:,}')
438
+ print("Final resolution: " + f'{result_width * result_height:,}')
439
+ print("edm_steps: " + str(edm_steps))
440
+ print("num_samples: " + str(num_samples))
441
+ print("downscale: " + str(downscale))
442
+ print("Estimated minutes: " + f'{(((result_width * result_height**(1/1.75)) * input_width * input_height * (edm_steps**(1/2)) * (num_samples**(1/2.5)))**(1/2.5)) / 25000:,}')
443
+ except Exception as e:
444
+ print('Exception of Estimation')
 
445
 
446
+ # Only one image can be shown in the slider
447
+ return [noisy_image] + [results[0]], gr.update(label="Downloadable results in *." + output_format + " format", format = output_format, value = results), gr.update(value = information, visible = True), gr.update(visible=True)
448
+
449
+ def load_and_reset(param_setting):
450
+ print('load_and_reset ==>>')
451
+ if torch.cuda.device_count() == 0:
452
+ gr.Warning('Set this space to GPU config to make it work.')
453
+ return None, None, None, None, None, None, None, None, None, None, None, None, None, None
454
+ edm_steps = default_setting.edm_steps
455
+ s_stage2 = 1.0
456
+ s_stage1 = -1.0
457
+ s_churn = 5
458
+ s_noise = 1.003
459
+ a_prompt = 'Cinematic, High Contrast, highly detailed, taken using a Canon EOS R camera, hyper detailed photo - ' \
460
+ 'realistic maximum detail, 32k, Color Grading, ultra HD, extreme meticulous detailing, skin pore ' \
461
+ 'detailing, hyper sharpness, perfect without deformations.'
462
+ n_prompt = 'painting, oil painting, illustration, drawing, art, sketch, anime, cartoon, CG Style, ' \
463
+ '3D render, unreal engine, blurring, dirty, messy, worst quality, low quality, frames, watermark, ' \
464
+ 'signature, jpeg artifacts, deformed, lowres, over-smooth'
465
+ color_fix_type = 'Wavelet'
466
+ spt_linear_s_stage2 = 0.0
467
+ linear_s_stage2 = False
468
+ linear_CFG = True
469
+ if param_setting == "Quality":
470
+ s_cfg = default_setting.s_cfg_Quality
471
+ spt_linear_CFG = default_setting.spt_linear_CFG_Quality
472
+ model_select = "v0-Q"
473
+ elif param_setting == "Fidelity":
474
+ s_cfg = default_setting.s_cfg_Fidelity
475
+ spt_linear_CFG = default_setting.spt_linear_CFG_Fidelity
476
+ model_select = "v0-F"
477
  else:
478
+ raise NotImplementedError
479
+ gr.Info('The parameters are reset.')
480
+ print('<<== load_and_reset')
481
+ return edm_steps, s_cfg, s_stage2, s_stage1, s_churn, s_noise, a_prompt, n_prompt, color_fix_type, linear_CFG, \
482
+ linear_s_stage2, spt_linear_CFG, spt_linear_s_stage2, model_select
 
 
 
 
 
 
 
483
 
484
+ def log_information(result_gallery):
485
+ print('log_information')
486
+ if result_gallery is not None:
487
+ for i, result in enumerate(result_gallery):
488
+ print(result[0])
489
+
490
+ def on_select_result(result_slider, result_gallery, evt: gr.SelectData):
491
+ print('on_select_result')
492
+ if result_gallery is not None:
493
+ for i, result in enumerate(result_gallery):
494
+ print(result[0])
495
+ return [result_slider[0], result_gallery[evt.index][0]]
 
496
 
497
+ title_html = """
498
+ <h1><center>SUPIR</center></h1>
499
+ <big><center>Upscale your images up to x10 freely, without account, without watermark and download it</center></big>
500
+ <center><big><big>🤸<big><big><big><big><big><big>🤸</big></big></big></big></big></big></big></big></center>
501
+
502
+ <p>This is an online demo of SUPIR, a practicing model scaling for photo-realistic image restoration.
503
+ The content added by SUPIR is <b><u>imagination, not real-world information</u></b>.
504
+ SUPIR is for beauty and illustration only.
505
+ Most of the processes last few minutes.
506
+ If you want to upscale AI-generated images, be noticed that <i>PixArt Sigma</i> space can directly generate 5984x5984 images.
507
+ Due to Gradio issues, the generated image is slightly less satured than the original.
508
+ Please leave a <a href="https://huggingface.co/spaces/Fabrice-TIERCELIN/SUPIR/discussions/new">message in discussion</a> if you encounter issues.
509
+ You can also use <a href="https://huggingface.co/spaces/gokaygokay/AuraSR">AuraSR</a> to upscale x4.
510
 
511
+ <p><center><a href="https://arxiv.org/abs/2401.13627">Paper</a> &emsp; <a href="http://supir.xpixel.group/">Project Page</a> &emsp; <a href="https://huggingface.co/blog/MonsterMMORPG/supir-sota-image-upscale-better-than-magnific-ai">Local Install Guide</a></center></p>
512
+ <p><center><a style="display:inline-block" href='https://github.com/Fanghua-Yu/SUPIR'><img alt="GitHub Repo stars" src="https://img.shields.io/github/stars/Fanghua-Yu/SUPIR?style=social"></a></center></p>
513
+ """
514
+
515
+
516
+ claim_md = """
517
+ ## **Piracy**
518
+ The images are not stored but the logs are saved during a month.
519
+ ## **How to get SUPIR**
520
+ You can get SUPIR on HuggingFace by [duplicating this space](https://huggingface.co/spaces/Fabrice-TIERCELIN/SUPIR?duplicate=true) and set GPU.
521
+ You can also install SUPIR on your computer following [this tutorial](https://huggingface.co/blog/MonsterMMORPG/supir-sota-image-upscale-better-than-magnific-ai).
522
+ You can install _Pinokio_ on your computer and then install _SUPIR_ into it. It should be quite easy if you have an Nvidia GPU.
523
+ ## **Terms of use**
524
+ 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.
525
+ ## **License**
526
+ 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.
527
+ """
528
+
529
+ # Gradio interface
530
+ with gr.Blocks() as interface:
531
+ if torch.cuda.device_count() == 0:
532
+ with gr.Row():
533
+ gr.HTML("""
534
+ <p style="background-color: red;"><big><big><big><b>⚠️To use SUPIR, <a href="https://huggingface.co/spaces/Fabrice-TIERCELIN/SUPIR?duplicate=true">duplicate this space</a> and set a GPU with 30 GB VRAM.</b>
535
+
536
+ You can't use SUPIR directly here because this space runs on a CPU, which is not enough for SUPIR. Please provide <a href="https://huggingface.co/spaces/Fabrice-TIERCELIN/SUPIR/discussions/new">feedback</a> if you have issues.
537
+ </big></big></big></p>
538
  """)
539
+ gr.HTML(title_html)
540
+
541
+ input_image = gr.Image(label="Input (*.png, *.webp, *.jpeg, *.jpg, *.gif, *.bmp, *.heic)", show_label=True, type="filepath", height=600, elem_id="image-input")
542
+ 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)
543
+ with gr.Group():
544
+ 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)
545
+ prompt_hint = gr.HTML("You can use a <a href='"'https://huggingface.co/spaces/badayvedat/LLaVA'"'>LlaVa space</a> to auto-generate the description of your image.")
546
+ 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)
547
+ 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)
548
+ allocation = gr.Radio([["1 min", 1], ["2 min", 2], ["3 min", 3], ["4 min", 4], ["5 min", 5]], label="GPU allocation time", info="lower=May abort run, higher=Quota penalty for next runs", value=3, interactive=True)
549
+
550
+ with gr.Accordion("Pre-denoising (optional)", open=False):
551
+ gamma_correction = gr.Slider(label="Gamma Correction", info = "lower=lighter, higher=darker", minimum=0.1, maximum=2.0, value=1.0, step=0.1)
552
+ denoise_button = gr.Button(value="Pre-denoise")
553
+ denoise_image = gr.Image(label="Denoised image", show_label=True, type="filepath", sources=[], interactive = False, height=600, elem_id="image-s1")
554
+ denoise_information = gr.HTML(value="If present, the denoised image will be used for the restoration instead of the input image.", visible=False)
555
+
556
+ with gr.Accordion("Advanced options", open=False):
557
+ a_prompt = gr.Textbox(label="Additional image description",
558
+ info="Completes the main image description",
559
+ value='Cinematic, High Contrast, highly detailed, taken using a Canon EOS R '
560
+ 'camera, hyper detailed photo - realistic maximum detail, 32k, Color '
561
+ 'Grading, ultra HD, extreme meticulous detailing, skin pore detailing, clothing fabric detailing, '
562
+ 'hyper sharpness, perfect without deformations.',
563
+ lines=3)
564
+ n_prompt = gr.Textbox(label="Negative image description",
565
+ info="Disambiguate by listing what the image does NOT represent",
566
+ value='painting, oil painting, illustration, drawing, art, sketch, anime, '
567
+ 'cartoon, CG Style, 3D render, unreal engine, blurring, aliasing, pixel, unsharp, weird textures, ugly, dirty, messy, '
568
+ 'worst quality, low quality, frames, watermark, signature, jpeg artifacts, '
569
+ 'deformed, lowres, over-smooth',
570
+ lines=3)
571
+ edm_steps = gr.Slider(label="Steps", info="lower=faster, higher=more details; too many steps create a checker effect", minimum=1, maximum=200, value=default_setting.edm_steps if torch.cuda.device_count() > 0 else 1, step=1)
572
+ num_samples = gr.Slider(label="Num Samples", info="Number of generated results", minimum=1, maximum=4 if not args.use_image_slider else 1
573
+ , value=1, step=1)
574
+ min_size = gr.Slider(label="Minimum size", info="Minimum height, minimum width of the result", minimum=32, maximum=4096, value=1024, step=32)
575
+ 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)
576
+ with gr.Row():
577
+ with gr.Column():
578
+ model_select = gr.Radio([["💃 Quality (v0-Q)", "v0-Q"], ["🎯 Fidelity (v0-F)", "v0-F"]], label="Model Selection", info="Pretrained model", value="v0-Q",
579
+ interactive=True)
580
+ with gr.Column():
581
+ color_fix_type = gr.Radio([["None", "None"], ["AdaIn (improve as a photo)", "AdaIn"], ["Wavelet (for JPEG artifacts)", "Wavelet"]], label="Color-Fix Type", info="AdaIn=Improve following a style, Wavelet=For JPEG artifacts", value="AdaIn",
582
+ interactive=True)
583
+ s_cfg = gr.Slider(label="Text Guidance Scale", info="lower=follow the image, higher=follow the prompt", minimum=1.0, maximum=15.0,
584
+ value=default_setting.s_cfg_Quality if torch.cuda.device_count() > 0 else 1.0, step=0.1)
585
+ s_stage2 = gr.Slider(label="Restoring Guidance Strength", minimum=0., maximum=1., value=1., step=0.05)
586
+ s_stage1 = gr.Slider(label="Pre-denoising Guidance Strength", minimum=-1.0, maximum=6.0, value=-1.0, step=1.0)
587
+ s_churn = gr.Slider(label="S-Churn", minimum=0, maximum=40, value=5, step=1)
588
+ s_noise = gr.Slider(label="S-Noise", minimum=1.0, maximum=1.1, value=1.003, step=0.001)
589
+ with gr.Row():
590
+ with gr.Column():
591
+ linear_CFG = gr.Checkbox(label="Linear CFG", value=True)
592
+ spt_linear_CFG = gr.Slider(label="CFG Start", minimum=1.0,
593
+ maximum=9.0, value=default_setting.spt_linear_CFG_Quality if torch.cuda.device_count() > 0 else 1.0, step=0.5)
594
+ with gr.Column():
595
+ linear_s_stage2 = gr.Checkbox(label="Linear Restoring Guidance", value=False)
596
+ spt_linear_s_stage2 = gr.Slider(label="Guidance Start", minimum=0.,
597
+ maximum=1., value=0., step=0.05)
598
+ with gr.Column():
599
+ diff_dtype = gr.Radio([["fp32 (precision)", "fp32"], ["fp16 (medium)", "fp16"], ["bf16 (speed)", "bf16"]], label="Diffusion Data Type", value="fp32",
600
+ interactive=True)
601
+ with gr.Column():
602
+ ae_dtype = gr.Radio([["fp32 (precision)", "fp32"], ["bf16 (speed)", "bf16"]], label="Auto-Encoder Data Type", value="fp32",
603
+ interactive=True)
604
+ randomize_seed = gr.Checkbox(label = "\U0001F3B2 Randomize seed", value = True, info = "If checked, result is always different")
605
+ seed = gr.Slider(label="Seed", minimum=0, maximum=max_64_bit_int, step=1, randomize=True)
606
+ with gr.Group():
607
+ param_setting = gr.Radio(["Quality", "Fidelity"], interactive=True, label="Presetting", value = "Quality")
608
+ restart_button = gr.Button(value="Apply presetting")
609
+
610
+ with gr.Column():
611
+ diffusion_button = gr.Button(value="🚀 Upscale/Restore", variant = "primary", elem_id = "process_button")
612
+ reset_btn = gr.Button(value="🧹 Reinit page", variant="stop", elem_id="reset_button", visible = False)
613
+
614
+ warning = gr.HTML(value = "<center><big>Your computer must <u>not</u> enter into standby mode.</big><br/>On Chrome, you can force to keep a tab alive in <code>chrome://discards/</code></center>", visible = False)
615
+ restore_information = gr.HTML(value = "Restart the process to get another result.", visible = False)
616
+ result_slider = ImageSlider(label = 'Comparator', show_label = False, interactive = False, elem_id = "slider1", show_download_button = False)
617
+ result_gallery = gr.Gallery(label = 'Downloadable results', show_label = True, interactive = False, elem_id = "gallery1")
618
+
619
+ gr.Examples(
620
+ examples = [
621
+ [
622
+ "./Examples/Example1.png",
623
+ 0,
624
+ None,
625
+ "Group of people, walking, happy, in the street, photorealistic, 8k, extremely detailled",
626
+ "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.",
627
+ "painting, oil painting, illustration, drawing, art, sketch, anime, cartoon, CG Style, 3D render, unreal engine, blurring, aliasing, pixel, unsharp, weird textures, ugly, dirty, messy, worst quality, low quality, frames, watermark, signature, jpeg artifacts, deformed, lowres, over-smooth",
628
+ 2,
629
+ 1024,
630
+ 1,
631
+ 8,
632
+ 100,
633
+ -1,
634
+ 1,
635
+ 7.5,
636
+ False,
637
+ 42,
638
+ 5,
639
+ 1.003,
640
+ "AdaIn",
641
+ "fp16",
642
+ "bf16",
643
+ 1.0,
644
+ True,
645
+ 4,
646
+ False,
647
+ 0.,
648
+ "v0-Q",
649
+ "input",
650
+ 3
651
+ ],
652
+ [
653
+ "./Examples/Example2.jpeg",
654
+ 0,
655
+ None,
656
+ "La cabeza de un gato atigrado, en una casa, fotorrealista, 8k, extremadamente detallada",
657
+ "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.",
658
+ "painting, oil painting, illustration, drawing, art, sketch, anime, cartoon, CG Style, 3D render, unreal engine, blurring, aliasing, pixel, unsharp, weird textures, ugly, dirty, messy, worst quality, low quality, frames, watermark, signature, jpeg artifacts, deformed, lowres, over-smooth",
659
+ 1,
660
+ 1024,
661
+ 1,
662
+ 1,
663
+ 200,
664
+ -1,
665
+ 1,
666
+ 7.5,
667
+ False,
668
+ 42,
669
+ 5,
670
+ 1.003,
671
+ "Wavelet",
672
+ "fp16",
673
+ "bf16",
674
+ 1.0,
675
+ True,
676
+ 4,
677
+ False,
678
+ 0.,
679
+ "v0-Q",
680
+ "input",
681
+ 3
682
+ ],
683
+ [
684
+ "./Examples/Example3.webp",
685
+ 0,
686
+ None,
687
+ "A red apple",
688
+ "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.",
689
+ "painting, oil painting, illustration, drawing, art, sketch, anime, cartoon, CG Style, 3D render, unreal engine, blurring, aliasing, pixel, unsharp, weird textures, ugly, dirty, messy, worst quality, low quality, frames, watermark, signature, jpeg artifacts, deformed, lowres, over-smooth",
690
+ 1,
691
+ 1024,
692
+ 1,
693
+ 1,
694
+ 200,
695
+ -1,
696
+ 1,
697
+ 7.5,
698
+ False,
699
+ 42,
700
+ 5,
701
+ 1.003,
702
+ "Wavelet",
703
+ "fp16",
704
+ "bf16",
705
+ 1.0,
706
+ True,
707
+ 4,
708
+ False,
709
+ 0.,
710
+ "v0-Q",
711
+ "input",
712
+ 3
713
+ ],
714
+ [
715
+ "./Examples/Example3.webp",
716
+ 0,
717
+ None,
718
+ "A red marble",
719
+ "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.",
720
+ "painting, oil painting, illustration, drawing, art, sketch, anime, cartoon, CG Style, 3D render, unreal engine, blurring, aliasing, pixel, unsharp, weird textures, ugly, dirty, messy, worst quality, low quality, frames, watermark, signature, jpeg artifacts, deformed, lowres, over-smooth",
721
+ 1,
722
+ 1024,
723
+ 1,
724
+ 1,
725
+ 200,
726
+ -1,
727
+ 1,
728
+ 7.5,
729
+ False,
730
+ 42,
731
+ 5,
732
+ 1.003,
733
+ "Wavelet",
734
+ "fp16",
735
+ "bf16",
736
+ 1.0,
737
+ True,
738
+ 4,
739
+ False,
740
+ 0.,
741
+ "v0-Q",
742
+ "input",
743
+ 3
744
+ ],
745
+ ],
746
+ run_on_click = True,
747
+ fn = stage2_process,
748
+ inputs = [
749
+ input_image,
750
+ rotation,
751
+ denoise_image,
752
+ prompt,
753
+ a_prompt,
754
+ n_prompt,
755
+ num_samples,
756
+ min_size,
757
+ downscale,
758
+ upscale,
759
+ edm_steps,
760
+ s_stage1,
761
+ s_stage2,
762
+ s_cfg,
763
+ randomize_seed,
764
+ seed,
765
+ s_churn,
766
+ s_noise,
767
+ color_fix_type,
768
+ diff_dtype,
769
+ ae_dtype,
770
+ gamma_correction,
771
+ linear_CFG,
772
+ linear_s_stage2,
773
+ spt_linear_CFG,
774
+ spt_linear_s_stage2,
775
+ model_select,
776
+ output_format,
777
+ allocation
778
+ ],
779
+ outputs = [
780
+ result_slider,
781
+ result_gallery,
782
+ restore_information,
783
+ reset_btn
784
+ ],
785
+ cache_examples = False,
786
+ )
787
+
788
+ with gr.Row():
789
+ gr.Markdown(claim_md)
790
 
791
+ input_image.upload(fn = check_upload, inputs = [
792
+ input_image
793
+ ], outputs = [
794
+ rotation
795
+ ], queue = False, show_progress = False)
796
+
797
+ denoise_button.click(fn = check_and_update, inputs = [
798
+ input_image
799
+ ], outputs = [warning], queue = False, show_progress = False).success(fn = stage1_process, inputs = [
800
+ input_image,
801
+ gamma_correction,
802
+ diff_dtype,
803
+ ae_dtype
804
+ ], outputs=[
805
+ denoise_image,
806
+ denoise_information
807
+ ])
808
+
809
+ diffusion_button.click(fn = update_seed, inputs = [
810
+ randomize_seed,
811
+ seed
812
+ ], outputs = [
813
+ seed
814
+ ], queue = False, show_progress = False).then(fn = check_and_update, inputs = [
815
+ input_image
816
+ ], outputs = [warning], queue = False, show_progress = False).success(fn=stage2_process, inputs = [
817
+ input_image,
818
+ rotation,
819
+ denoise_image,
820
+ prompt,
821
+ a_prompt,
822
+ n_prompt,
823
+ num_samples,
824
+ min_size,
825
+ downscale,
826
+ upscale,
827
+ edm_steps,
828
+ s_stage1,
829
+ s_stage2,
830
+ s_cfg,
831
+ randomize_seed,
832
+ seed,
833
+ s_churn,
834
+ s_noise,
835
+ color_fix_type,
836
+ diff_dtype,
837
+ ae_dtype,
838
+ gamma_correction,
839
+ linear_CFG,
840
+ linear_s_stage2,
841
+ spt_linear_CFG,
842
+ spt_linear_s_stage2,
843
+ model_select,
844
+ output_format,
845
+ allocation
846
+ ], outputs = [
847
+ result_slider,
848
+ result_gallery,
849
+ restore_information,
850
+ reset_btn
851
+ ]).success(fn = log_information, inputs = [
852
+ result_gallery
853
+ ], outputs = [], queue = False, show_progress = False)
854
+
855
+ result_gallery.change(on_select_result, [result_slider, result_gallery], result_slider)
856
+ result_gallery.select(on_select_result, [result_slider, result_gallery], result_slider)
857
+
858
+ restart_button.click(fn = load_and_reset, inputs = [
859
+ param_setting
860
+ ], outputs = [
861
+ edm_steps,
862
+ s_cfg,
863
+ s_stage2,
864
+ s_stage1,
865
+ s_churn,
866
+ s_noise,
867
+ a_prompt,
868
+ n_prompt,
869
+ color_fix_type,
870
+ linear_CFG,
871
+ linear_s_stage2,
872
+ spt_linear_CFG,
873
+ spt_linear_s_stage2,
874
+ model_select
875
+ ])
876
+
877
+ reset_btn.click(fn = reset, inputs = [], outputs = [
878
+ input_image,
879
+ rotation,
880
+ denoise_image,
881
+ prompt,
882
+ a_prompt,
883
+ n_prompt,
884
+ num_samples,
885
+ min_size,
886
+ downscale,
887
+ upscale,
888
+ edm_steps,
889
+ s_stage1,
890
+ s_stage2,
891
+ s_cfg,
892
+ randomize_seed,
893
+ seed,
894
+ s_churn,
895
+ s_noise,
896
+ color_fix_type,
897
+ diff_dtype,
898
+ ae_dtype,
899
+ gamma_correction,
900
+ linear_CFG,
901
+ linear_s_stage2,
902
+ spt_linear_CFG,
903
+ spt_linear_s_stage2,
904
+ model_select,
905
+ output_format,
906
+ allocation
907
+ ], queue = False, show_progress = False)
908
+
909
+ interface.queue(10).launch()
requirements.txt CHANGED
@@ -1,8 +1,41 @@
1
- https://gradio-builds.s3.amazonaws.com/756e3431d65172df986a7e335dce8136206a293a/gradio-4.7.1-py3-none-any.whl
2
- git+https://github.com/huggingface/diffusers.git
3
- transformers
4
- accelerate
5
- safetensors
6
- opencv-python
7
- uuid
8
- torch
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ pydantic==2.10.6
2
+ fastapi==0.115.8
3
+ gradio_imageslider==0.0.20
4
+ gradio_client==1.7.0
5
+ numpy==1.26.4
6
+ requests==2.32.3
7
+ sentencepiece==0.2.0
8
+ tokenizers==0.19.1
9
+ torchvision==0.18.1
10
+ uvicorn==0.30.1
11
+ wandb==0.17.4
12
+ httpx==0.27.0
13
+ transformers==4.42.4
14
+ accelerate==0.32.1
15
+ scikit-learn==1.5.1
16
+ einops==0.8.0
17
+ einops-exts==0.0.4
18
+ timm==1.0.7
19
+ openai-clip==1.0.1
20
+ fsspec==2024.6.1
21
+ kornia==0.7.3
22
+ matplotlib==3.9.1
23
+ ninja==1.11.1.1
24
+ omegaconf==2.3.0
25
+ opencv-python==4.10.0.84
26
+ pandas==2.2.2
27
+ pillow==10.4.0
28
+ pytorch-lightning==2.3.3
29
+ PyYAML==6.0.1
30
+ scipy==1.14.0
31
+ tqdm==4.66.4
32
+ triton==2.3.1
33
+ urllib3==2.2.2
34
+ webdataset==0.2.86
35
+ xformers==0.0.27
36
+ facexlib==0.3.0
37
+ k-diffusion==0.1.1.post1
38
+ diffusers==0.29.2
39
+ pillow-heif==0.18.0
40
+
41
+ open-clip-torch==2.24.0