owiedotch commited on
Commit
6381c79
1 Parent(s): ad27324

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +79 -0
app.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import torch
3
+ import gradio as gr
4
+ import spaces
5
+ from PIL import Image
6
+ import numpy as np
7
+ from omegaconf import OmegaConf
8
+ import requests
9
+ from tqdm import tqdm
10
+
11
+ def download_file(url, filename):
12
+ response = requests.get(url, stream=True)
13
+ total_size = int(response.headers.get('content-length', 0))
14
+ block_size = 1024
15
+ with open(filename, 'wb') as file, tqdm(
16
+ desc=filename,
17
+ total=total_size,
18
+ unit='iB',
19
+ unit_scale=True,
20
+ unit_divisor=1024,
21
+ ) as progress_bar:
22
+ for data in response.iter_content(block_size):
23
+ size = file.write(data)
24
+ progress_bar.update(size)
25
+
26
+ def setup_environment():
27
+ os.makedirs("weights", exist_ok=True)
28
+ if not os.path.exists("weights/real-world_ccsr.ckpt"):
29
+ print("Downloading model checkpoint...")
30
+ download_file(
31
+ "https://huggingface.co/camenduru/CCSR/resolve/main/real-world_ccsr.ckpt",
32
+ "weights/real-world_ccsr.ckpt"
33
+ )
34
+ else:
35
+ print("Model checkpoint already exists. Skipping download.")
36
+
37
+ setup_environment()
38
+
39
+ from ccsr.models.ccsr import CCSR
40
+ from ccsr.utils.util import instantiate_from_config
41
+
42
+ config = OmegaConf.load("configs/model/ccsr_stage2.yaml")
43
+ model = instantiate_from_config(config.model)
44
+ ckpt = torch.load("weights/real-world_ccsr.ckpt", map_location="cpu")
45
+ model.load_state_dict(ckpt["state_dict"], strict=False)
46
+ model.cuda().eval()
47
+
48
+ @spaces.GPU
49
+ @torch.inference_mode()
50
+ def infer(image, sr_scale, t_max, t_min, color_fix_type):
51
+ image = Image.open(image).convert("RGB").resize((256, 256), Image.LANCZOS)
52
+ image = torch.from_numpy(np.array(image)).float().cuda() / 127.5 - 1
53
+ image = image.permute(2, 0, 1).unsqueeze(0)
54
+
55
+ output = model.super_resolution(
56
+ image,
57
+ sr_scale=sr_scale,
58
+ t_max=t_max,
59
+ t_min=t_min,
60
+ color_fix_type=color_fix_type
61
+ )
62
+
63
+ output = ((output.squeeze().permute(1, 2, 0).cpu().numpy() + 1) * 127.5).clip(0, 255).astype(np.uint8)
64
+ return Image.fromarray(output)
65
+
66
+ interface = gr.Interface(
67
+ fn=infer,
68
+ inputs=[
69
+ gr.Image(type="filepath"),
70
+ gr.Slider(minimum=1, maximum=8, step=1, value=4),
71
+ gr.Slider(minimum=0, maximum=1, step=0.0001, value=0.6667),
72
+ gr.Slider(minimum=0, maximum=1, step=0.0001, value=0.3333),
73
+ gr.Dropdown(choices=["adain", "wavelet", "none"], value="adain"),
74
+ ],
75
+ outputs=gr.Image(type="pil"),
76
+ title="CCSR: Continuous Contrastive Super-Resolution",
77
+ )
78
+
79
+ interface.launch()