K00B404 commited on
Commit
3f4fb33
·
verified ·
1 Parent(s): 13a2260

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +96 -151
app.py CHANGED
@@ -1,152 +1,97 @@
 
 
 
 
 
1
  import gradio as gr
2
- from random import randint, sample
3
- from all_models import models
4
- import csv
5
- import os
6
-
7
- # Assuming you have a function to calculate ELO ratings
8
- def init_model_scores(file_path='model_scores.csv'):
9
- # Check if the CSV file exists, if not, create it with headers
10
- if not os.path.isfile(csv_file_path):
11
- with open(csv_file_path, 'w', newline='') as file:
12
- writer = csv.writer(file)
13
- writer.writerow(["Model Name", "Score"])
14
- for model in models:
15
- # make a entry for each model
16
- writer.writerow([model, 0])
17
-
18
- def update_elo_ratings(user_vote, csv_file_path='model_scores.csv'):
19
- # Logic to update ELO ratings based on user vote
20
-
21
- # Read the current scores from the CSV file
22
- scores = {}
23
- with open(csv_file_path, 'r') as file:
24
- reader = csv.reader(file)
25
- next(reader) # Skip the header row
26
- for row in reader:
27
- scores[row[0]] = int(row[1])
28
-
29
- # Update the score for the selected model
30
- if user_vote in scores:
31
- scores[user_vote] += 1 # Increment the score
32
- else:
33
- scores[user_vote] = 1 # Add the model with a score of 1
34
-
35
- # Write the updated scores back to the CSV file
36
- with open(csv_file_path, 'w', newline='') as file:
37
- writer = csv.writer(file)
38
- writer.writerow(["Model Name", "Score"]) # Write the header row
39
- for model, score in scores.items():
40
- writer.writerow([model, score])
41
-
42
-
43
- # Function to compare two models
44
- def compare_models(prompt):
45
- model1, model2 = sample(models, 2)
46
- image1, model_name1 = gen_fn(model1, prompt)
47
- image2, model_name2 = gen_fn(model2, prompt)
48
- return image1, model_name1, image2, model_name2
49
-
50
- # User voting logic
51
- def handle_vote(user_vote):
52
- init_model_scores()
53
- # Assuming user_vote is a string indicating the preferred model
54
- # Update ELO ratings based on user vote
55
- update_elo_ratings(user_vote)
56
-
57
- # Leaderboard display logic
58
- def display_leaderboard():
59
- # Logic to display leaderboard based on ELO ratings
60
- pass
61
-
62
- # Your existing Gradio setup code here...
63
- def load_fn(models):
64
- global models_load
65
- models_load = {}
66
-
67
- for model in models:
68
- if model not in models_load.keys():
69
- try:
70
- m = gr.load(f'models/{model}')
71
- except Exception as error:
72
- m = gr.Interface(lambda txt: None, ['text'], ['image'])
73
- models_load.update({model: m})
74
-
75
-
76
- load_fn(models)
77
-
78
-
79
- num_models = 6
80
- default_models = models[:num_models]
81
-
82
-
83
- def extend_choices(choices):
84
- return choices + (num_models - len(choices)) * ['NA']
85
-
86
-
87
- def update_imgbox(choices):
88
- choices_plus = extend_choices(choices)
89
- return [gr.Image(None, label = m, visible = (m != 'NA')) for m in choices_plus]
90
-
91
-
92
- def gen_fn(model_str, prompt):
93
- if model_str == 'NA':
94
- return None
95
- noise = str(randint(0, 99999999999))
96
- return models_load[model_str](f'{prompt} {noise}')
97
-
98
- # Modified gen_fn function to return model name
99
- def gen_fn(model_str, prompt):
100
- if model_str == 'NA':
101
- return None, None
102
- noise = str(randint(0, 99999999999))
103
- image = models_load[model_str](f'{prompt} {noise}')
104
- return image, model_str
105
-
106
-
107
- with gr.Blocks() as ImageGenarationArena:
108
- with gr.Column('model A', variant='panel', width=2, height=150) as col:
109
- #with gr.Tab('model B'):
110
- model_choice2 = gr.Dropdown(models, label = 'Choose model', value = models[0], filterable = False)
111
- txt_input2 = gr.Textbox(label = 'Prompt text')
112
-
113
- max_images = 6
114
- num_images = gr.Slider(1, max_images, value = max_images, step = 1, label = 'Number of images')
115
-
116
- gen_button2 = gr.Button('Generate')
117
- stop_button2 = gr.Button('Stop', variant = 'secondary', interactive = False)
118
- gen_button2.click(lambda s: gr.update(interactive = True), None, stop_button2)
119
-
120
- with gr.Row():
121
- output2 = [gr.Image(label = '') for _ in range(max_images)]
122
-
123
- for i, o in enumerate(output2):
124
- img_i = gr.Number(i, visible = False)
125
- num_images.change(lambda i, n: gr.update(visible = (i < n)), [img_i, num_images], o)
126
- gen_event2 = gen_button2.click(lambda i, n, m, t: gen_fn(m, t) if (i < n) else None, [img_i, num_images, model_choice2, txt_input2], o)
127
- stop_button2.click(lambda s: gr.update(interactive = False), None, stop_button2, cancels = [gen_event2])
128
-
129
- with gr.Column('model B', variant='panel', width=2, height=150) as col:
130
- #with gr.Tab('model A'):
131
- model_choice2 = gr.Dropdown(models, label = 'Choose model', value = models[0], filterable = False)
132
- txt_input2 = gr.Textbox(label = 'Prompt text')
133
-
134
- max_images = 6
135
- num_images = gr.Slider(1, max_images, value = max_images, step = 1, label = 'Number of images')
136
-
137
- gen_button2 = gr.Button('Generate')
138
- stop_button2 = gr.Button('Stop', variant = 'secondary', interactive = False)
139
- gen_button2.click(lambda s: gr.update(interactive = True), None, stop_button2)
140
-
141
- with gr.Row():
142
- output2 = [gr.Image(label = '') for _ in range(max_images)]
143
-
144
- for i, o in enumerate(output2):
145
- img_i = gr.Number(i, visible = False)
146
- num_images.change(lambda i, n: gr.update(visible = (i < n)), [img_i, num_images], o)
147
- gen_event2 = gen_button2.click(lambda i, n, m, t: gen_fn(m, t) if (i < n) else None, [img_i, num_images, model_choice2, txt_input2], o)
148
- stop_button2.click(lambda s: gr.update(interactive = False), None, stop_button2, cancels = [gen_event2])
149
-
150
-
151
- ImageGenarationArena.queue(concurrency_count = 36)
152
- ImageGenarationArena.launch()
 
1
+ from share import *
2
+ import config
3
+
4
+ import cv2
5
+ import einops
6
  import gradio as gr
7
+ import numpy as np
8
+ import torch
9
+ import random
10
+
11
+ from pytorch_lightning import seed_everything
12
+ from annotator.util import resize_image, HWC3
13
+ from annotator.uniformer import UniformerDetector
14
+ from cldm.model import create_model, load_state_dict
15
+ from cldm.ddim_hacked import DDIMSampler
16
+
17
+
18
+ apply_uniformer = UniformerDetector()
19
+
20
+ model = create_model('./models/cldm_v15.yaml').cpu()
21
+ model.load_state_dict(load_state_dict('./models/control_sd15_seg.pth', location='cuda'))
22
+ model = model.cuda()
23
+ ddim_sampler = DDIMSampler(model)
24
+
25
+
26
+ def process(input_image, prompt, a_prompt, n_prompt, num_samples, image_resolution, detect_resolution, ddim_steps, guess_mode, strength, scale, seed, eta):
27
+ with torch.no_grad():
28
+ input_image = HWC3(input_image)
29
+ detected_map = apply_uniformer(resize_image(input_image, detect_resolution))
30
+ img = resize_image(input_image, image_resolution)
31
+ H, W, C = img.shape
32
+
33
+ detected_map = cv2.resize(detected_map, (W, H), interpolation=cv2.INTER_NEAREST)
34
+
35
+ control = torch.from_numpy(detected_map.copy()).float().cuda() / 255.0
36
+ control = torch.stack([control for _ in range(num_samples)], dim=0)
37
+ control = einops.rearrange(control, 'b h w c -> b c h w').clone()
38
+
39
+ if seed == -1:
40
+ seed = random.randint(0, 65535)
41
+ seed_everything(seed)
42
+
43
+ if config.save_memory:
44
+ model.low_vram_shift(is_diffusing=False)
45
+
46
+ cond = {"c_concat": [control], "c_crossattn": [model.get_learned_conditioning([prompt + ', ' + a_prompt] * num_samples)]}
47
+ un_cond = {"c_concat": None if guess_mode else [control], "c_crossattn": [model.get_learned_conditioning([n_prompt] * num_samples)]}
48
+ shape = (4, H // 8, W // 8)
49
+
50
+ if config.save_memory:
51
+ model.low_vram_shift(is_diffusing=True)
52
+
53
+ model.control_scales = [strength * (0.825 ** float(12 - i)) for i in range(13)] if guess_mode else ([strength] * 13) # Magic number. IDK why. Perhaps because 0.825**12<0.01 but 0.826**12>0.01
54
+ samples, intermediates = ddim_sampler.sample(ddim_steps, num_samples,
55
+ shape, cond, verbose=False, eta=eta,
56
+ unconditional_guidance_scale=scale,
57
+ unconditional_conditioning=un_cond)
58
+
59
+ if config.save_memory:
60
+ model.low_vram_shift(is_diffusing=False)
61
+
62
+ x_samples = model.decode_first_stage(samples)
63
+ x_samples = (einops.rearrange(x_samples, 'b c h w -> b h w c') * 127.5 + 127.5).cpu().numpy().clip(0, 255).astype(np.uint8)
64
+
65
+ results = [x_samples[i] for i in range(num_samples)]
66
+ return [detected_map] + results
67
+
68
+
69
+ block = gr.Blocks().queue()
70
+ with block:
71
+ with gr.Row():
72
+ gr.Markdown("## Control Stable Diffusion with Segmentation Maps")
73
+ with gr.Row():
74
+ with gr.Column():
75
+ input_image = gr.Image(source='upload', type="numpy")
76
+ prompt = gr.Textbox(label="Prompt")
77
+ run_button = gr.Button(label="Run")
78
+ with gr.Accordion("Advanced options", open=False):
79
+ num_samples = gr.Slider(label="Images", minimum=1, maximum=12, value=1, step=1)
80
+ image_resolution = gr.Slider(label="Image Resolution", minimum=256, maximum=768, value=512, step=64)
81
+ strength = gr.Slider(label="Control Strength", minimum=0.0, maximum=2.0, value=1.0, step=0.01)
82
+ guess_mode = gr.Checkbox(label='Guess Mode', value=False)
83
+ detect_resolution = gr.Slider(label="Segmentation Resolution", minimum=128, maximum=1024, value=512, step=1)
84
+ ddim_steps = gr.Slider(label="Steps", minimum=1, maximum=100, value=20, step=1)
85
+ scale = gr.Slider(label="Guidance Scale", minimum=0.1, maximum=30.0, value=9.0, step=0.1)
86
+ seed = gr.Slider(label="Seed", minimum=-1, maximum=2147483647, step=1, randomize=True)
87
+ eta = gr.Number(label="eta (DDIM)", value=0.0)
88
+ a_prompt = gr.Textbox(label="Added Prompt", value='best quality, extremely detailed')
89
+ n_prompt = gr.Textbox(label="Negative Prompt",
90
+ value='longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality')
91
+ with gr.Column():
92
+ result_gallery = gr.Gallery(label='Output', show_label=False, elem_id="gallery").style(grid=2, height='auto')
93
+ ips = [input_image, prompt, a_prompt, n_prompt, num_samples, image_resolution, detect_resolution, ddim_steps, guess_mode, strength, scale, seed, eta]
94
+ run_button.click(fn=process, inputs=ips, outputs=[result_gallery])
95
+
96
+
97
+ block.launch(server_name='0.0.0.0')