svjack commited on
Commit
ef88f9e
·
1 Parent(s): a9ce25b

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +273 -0
app.py ADDED
@@ -0,0 +1,273 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+
4
+ import gradio as gr
5
+ import numpy as np
6
+ import shutil
7
+
8
+ import copy
9
+ import json
10
+ import gc
11
+ import random
12
+ from PIL import Image
13
+
14
+ '''
15
+ models
16
+ images
17
+ custom.css
18
+ sd_cfg.json
19
+ '''
20
+
21
+ if not os.path.exists("sd-ggml-cpp-dp"):
22
+ os.system("git clone https://huggingface.co/svjack/sd-ggml-cpp-dp")
23
+ else:
24
+ shutil.rmtree("sd-ggml-cpp-dp")
25
+ os.system("git clone https://huggingface.co/svjack/sd-ggml-cpp-dp")
26
+ assert os.path.exists("sd-ggml-cpp-dp")
27
+ os.chdir("sd-ggml-cpp-dp")
28
+ assert os.path.exists("stable-diffusion.cpp")
29
+ os.system("cmake stable-diffusion.cpp")
30
+ os.system("cmake --build . --config Release")
31
+ assert os.path.exists("bin")
32
+
33
+ def process(model_path ,prompt, num_samples, image_resolution, sample_steps, seed,):
34
+ from PIL import Image
35
+ from uuid import uuid1
36
+ output_path = "output_image_dir"
37
+ if not os.path.exists(output_path):
38
+ os.mkdir(output_path)
39
+ else:
40
+ shutil.rmtree(output_path)
41
+ os.mkdir(output_path)
42
+ assert os.path.exists(output_path)
43
+
44
+ run_format = './bin/sd -m {} --sampling-method "dpm++2mv2" -o "{}/{}.png" -p "{}" --steps {} -H {} -W {} -s {}'
45
+ images = []
46
+ for i in range(num_samples):
47
+ uid = str(uuid1())
48
+ run_cmd = run_format.format(model_path, output_path,
49
+ uid, prompt, sample_steps, image_resolution,
50
+ image_resolution, seed + i)
51
+ print("run cmd: {}".format(run_cmd))
52
+ os.system(run_cmd)
53
+ assert os.path.exists(os.path.join(output_path, "{}.png".format(uid)))
54
+ image = Image.open(os.path.join(output_path, "{}.png".format(uid)))
55
+ images.append(np.asarray(image))
56
+ results = images
57
+ return results
58
+
59
+ model_list = list(map(lambda x: os.path.join("models", x), os.listdir("models")))
60
+ assert model_list
61
+
62
+ sdxl_loras_raw = []
63
+ with open("sd_cfg.json", "r") as file:
64
+ data = json.load(file)
65
+ sdxl_loras_raw = [
66
+ {
67
+ "image": item["image"],
68
+ "title": item["title"],
69
+ "repo": item["repo"],
70
+ "trigger_word": item["trigger_word"],
71
+ "model_path": item["model_path"]
72
+ #"weights": item["weights"],
73
+ #"is_compatible": item["is_compatible"],
74
+ #"is_pivotal": item.get("is_pivotal", False),
75
+ #"text_embedding_weights": item.get("text_embedding_weights", None),
76
+ #"likes": item.get("likes", 0),
77
+ #"downloads": item.get("downloads", 0),
78
+ #"is_nc": item.get("is_nc", False)
79
+ }
80
+ for item in data
81
+ ]
82
+
83
+ sdxl_loras_raw = list(filter(lambda d: d["model_path"] in model_list, sdxl_loras_raw))
84
+ assert sdxl_loras_raw
85
+
86
+
87
+ def update_selection(selected_state: gr.SelectData, sdxl_loras):
88
+ lora_repo = sdxl_loras[selected_state.index]["repo"]
89
+ instance_prompt = sdxl_loras[selected_state.index]["trigger_word"]
90
+ new_placeholder = "Type a prompt. This applies for all prompts, no need for a trigger word" if instance_prompt == "" else "Type a prompt to use your selected LoRA"
91
+ #weight_name = sdxl_loras[selected_state.index]["weights"]
92
+ updated_text = f"### Selected: [{lora_repo}](https://huggingface.co/{lora_repo}) ✨ "
93
+ is_compatible = True
94
+ is_pivotal = True
95
+
96
+ use_with_diffusers = f'''
97
+ ## Using [`{lora_repo}`](https://huggingface.co/{lora_repo})
98
+
99
+ ## Use it with diffusers:
100
+ '''
101
+ use_with_uis = f'''
102
+ ## Use it with Comfy UI, Invoke AI, SD.Next, AUTO1111:
103
+
104
+ ### Download the `*.safetensors` weights of [here](https://huggingface.co/{lora_repo})
105
+
106
+ - [ComfyUI guide](https://comfyanonymous.github.io/ComfyUI_examples/lora/)
107
+ - [Invoke AI guide](https://invoke-ai.github.io/InvokeAI/features/CONCEPTS/?h=lora#using-loras)
108
+ - [SD.Next guide](https://github.com/vladmandic/automatic)
109
+ - [AUTOMATIC1111 guide](https://stable-diffusion-art.com/lora/)
110
+ '''
111
+ return (
112
+ updated_text,
113
+ instance_prompt,
114
+ gr.update(placeholder=new_placeholder),
115
+ selected_state,
116
+ use_with_diffusers,
117
+ use_with_uis,
118
+ )
119
+
120
+ def check_selected(selected_state):
121
+ if not selected_state:
122
+ raise gr.Error("You must select a Model")
123
+
124
+ def shuffle_gallery(sdxl_loras):
125
+ random.shuffle(sdxl_loras)
126
+ return [(item["image"], item["title"]) for item in sdxl_loras], sdxl_loras
127
+
128
+ def swap_gallery(order, sdxl_loras):
129
+ if(order == "random"):
130
+ return shuffle_gallery(sdxl_loras)
131
+ else:
132
+ #sorted_gallery = sorted(sdxl_loras, key=lambda x: x.get(order, 0), reverse=True)
133
+ sorted_gallery = sorted(sdxl_loras, key=lambda x: x["title"], reverse=False)
134
+ return [(item["image"], item["title"]) for item in sorted_gallery], sorted_gallery
135
+
136
+ '''
137
+ def run_lora(prompt, negative, lora_scale, selected_state, sdxl_loras,
138
+ progress=gr.Progress(track_tqdm=True)):
139
+ '''
140
+ def run_lora(prompt, selected_state, sdxl_loras,
141
+ image_resolution, sample_steps, seed,
142
+ progress=gr.Progress(track_tqdm=True)):
143
+ #global last_lora, last_merged, last_fused, pipe
144
+
145
+ '''
146
+ if negative == "":
147
+ negative = None
148
+ '''
149
+
150
+ if not selected_state:
151
+ raise gr.Error("You must select a Model")
152
+ repo_name = sdxl_loras[selected_state.index]["repo"]
153
+ model_path = sdxl_loras[selected_state.index]["model_path"]
154
+ #weight_name = sdxl_loras[selected_state.index]["weights"]
155
+
156
+ '''
157
+ image = pipe(
158
+ prompt=prompt,
159
+ negative_prompt=negative,
160
+ width=1024,
161
+ height=1024,
162
+ num_inference_steps=20,
163
+ guidance_scale=7.5,
164
+ ).images[0]
165
+ last_lora = repo_name
166
+ gc.collect()
167
+ '''
168
+ num_samples = 1
169
+ #### image_resolution : 512
170
+ #### sample_steps : 8
171
+ #### seed : 20
172
+ image = process(model_path ,prompt, num_samples, image_resolution, sample_steps, seed,)[0]
173
+ image = Image.fromarray(image.astype(np.uint8))
174
+ #return image, gr.update(visible=True)
175
+ return image
176
+
177
+ with gr.Blocks(css="custom.css") as demo:
178
+ #with gr.Blocks() as demo:
179
+ gr_sdxl_loras = gr.State(value=sdxl_loras_raw)
180
+ title = gr.HTML(
181
+ """<h1><img src="https://i.imgur.com/vT48NAO.png" alt="SD"> StableDiffusion GGML Explorer</h1>""",
182
+ elem_id="title",
183
+ )
184
+
185
+ selected_state = gr.State()
186
+ with gr.Row(elem_id="main_app"):
187
+ with gr.Box(elem_id="gallery_box"):
188
+ order_gallery = gr.Radio(choices=["random", "alphabetical"],
189
+ value="random", label="Order by", elem_id="order_radio")
190
+ gallery = gr.Gallery(
191
+ #value=[(item["image"], item["title"]) for item in sdxl_loras_raw],
192
+ label="SD Model Gallery",
193
+ allow_preview=True,
194
+ #rows = 1,
195
+ columns=2,
196
+ #scale = 3,
197
+ min_width = 256,
198
+ #object_fit = "scale-down",
199
+ elem_id="gallery",
200
+ show_share_button=False,
201
+ height=512
202
+ )
203
+ with gr.Column():
204
+ prompt_title = gr.Markdown(
205
+ value="### Click on a Model in the gallery to select it",
206
+ visible=True,
207
+ elem_id="selected_model",
208
+ )
209
+ with gr.Row():
210
+ prompt = gr.Textbox(label="Prompt", show_label=False, lines=1, max_lines=1,
211
+ placeholder="Type a prompt after selecting a Model", elem_id="prompt")
212
+ button = gr.Button("Run", elem_id="run_button")
213
+ '''
214
+ with gr.Group(elem_id="share-btn-container", visible=False) as share_group:
215
+ community_icon = gr.HTML(community_icon_html)
216
+ loading_icon = gr.HTML(loading_icon_html)
217
+ share_button = gr.Button("Share to community", elem_id="share-btn")
218
+ '''
219
+ result = gr.Image(
220
+ interactive=False, label="Generated Image", elem_id="result-image"
221
+ )
222
+ with gr.Accordion("Advanced options", open=False):
223
+ #negative = gr.Textbox(label="Negative Prompt")
224
+ #weight = gr.Slider(0, 10, value=0.8, step=0.1, label="LoRA weight")
225
+ #negative = ""
226
+ image_resolution = gr.Slider(label="Image Resolution", minimum=256, maximum=768, value=512, step=256)
227
+ sample_steps = gr.Slider(label="Steps", minimum=1, maximum=100, value=8, step=1)
228
+ seed = gr.Slider(label="Seed", minimum=-1, maximum=2147483647, step=1, randomize=True)
229
+
230
+ order_gallery.change(
231
+ fn=swap_gallery,
232
+ inputs=[order_gallery, gr_sdxl_loras],
233
+ outputs=[gallery, gr_sdxl_loras],
234
+ queue=False
235
+ )
236
+ gallery.select(
237
+ fn=update_selection,
238
+ inputs=[gr_sdxl_loras],
239
+ #outputs=[prompt_title, prompt, prompt, selected_state, use_diffusers, use_uis],
240
+ outputs=[prompt_title, prompt, prompt, selected_state,],
241
+ queue=False,
242
+ show_progress=False
243
+ )
244
+ prompt.submit(
245
+ fn=check_selected,
246
+ inputs=[selected_state],
247
+ queue=False,
248
+ show_progress=False
249
+ ).success(
250
+ fn=run_lora,
251
+ #inputs=[prompt, negative, weight, selected_state, gr_sdxl_loras],
252
+ inputs=[prompt, selected_state, gr_sdxl_loras, image_resolution, sample_steps, seed],
253
+ #outputs=[result, share_group],
254
+ #outputs=[result,],
255
+ outputs = result
256
+ )
257
+ button.click(
258
+ fn=check_selected,
259
+ inputs=[selected_state],
260
+ queue=False,
261
+ show_progress=False
262
+ ).success(
263
+ fn=run_lora,
264
+ #inputs=[prompt, negative, weight, selected_state, gr_sdxl_loras],
265
+ inputs=[prompt, selected_state, gr_sdxl_loras, image_resolution, sample_steps, seed],
266
+ #outputs=[result, share_group],
267
+ #outputs=[result,],
268
+ outputs = result
269
+ )
270
+ #share_button.click(None, [], [], _js=share_js)
271
+ demo.load(fn=shuffle_gallery, inputs=[gr_sdxl_loras], outputs=[gallery, gr_sdxl_loras], queue=False)
272
+ demo.queue(max_size=20)
273
+ demo.launch()