Spaces:
Runtime error
Runtime error
Commit
Β·
880a175
1
Parent(s):
3fdce8f
Overhaul update from working version to new attempt
Browse files
app.py
CHANGED
@@ -1,449 +1,270 @@
|
|
1 |
-
|
2 |
-
|
3 |
-
import requests
|
4 |
import os
|
5 |
-
import gradio as gr
|
6 |
-
import wget
|
7 |
import torch
|
8 |
-
|
|
|
|
|
|
|
9 |
from diffusers import StableDiffusionPipeline
|
10 |
-
from
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
${htmlImgsMd}
|
73 |
-
</div>`;
|
74 |
-
const params = new URLSearchParams({
|
75 |
-
title: promptTxt,
|
76 |
-
description: descriptionMd,
|
77 |
-
});
|
78 |
-
const paramsStr = params.toString();
|
79 |
-
window.open(`https://huggingface.co/spaces/sd-concepts-library/stable-diffusion-conceptualizer/discussions/new?${paramsStr}`, '_blank');
|
80 |
-
shareBtnEl.style.removeProperty('pointer-events');
|
81 |
-
shareIconEl.style.removeProperty('display');
|
82 |
-
loadingIconEl.style.display = 'none';
|
83 |
-
}"""
|
84 |
-
|
85 |
-
api = HfApi()
|
86 |
-
models_list = api.list_models(author="sd-concepts-library", sort="likes", direction=-1)
|
87 |
-
models = []
|
88 |
-
|
89 |
-
# NEW LOGIN ATTEMPT {{{
|
90 |
-
api_key = os.environ['api_key']
|
91 |
-
my_token = api_key
|
92 |
-
|
93 |
-
pipe = StableDiffusionPipeline.from_pretrained("CompVis/stable-diffusion-v1-4", revision="fp16", torch_dtype=torch.float16, use_auth_token=my_token).to("cuda")
|
94 |
-
# }}}
|
95 |
-
|
96 |
-
# pipe = StableDiffusionPipeline.from_pretrained("CompVis/stable-diffusion-v1-4", use_auth_token=True, revision="fp16", torch_dtype=torch.float16).to("cuda")
|
97 |
-
|
98 |
-
def load_learned_embed_in_clip(learned_embeds_path, text_encoder, tokenizer, token=None):
|
99 |
-
loaded_learned_embeds = torch.load(learned_embeds_path, map_location="cpu")
|
100 |
-
|
101 |
-
_old_token = token
|
102 |
-
# separate token and the embeds
|
103 |
-
trained_token = list(loaded_learned_embeds.keys())[0]
|
104 |
-
embeds = loaded_learned_embeds[trained_token]
|
105 |
-
|
106 |
-
# cast to dtype of text_encoder
|
107 |
-
dtype = text_encoder.get_input_embeddings().weight.dtype
|
108 |
-
|
109 |
-
# add the token in tokenizer
|
110 |
-
token = token if token is not None else trained_token
|
111 |
-
num_added_tokens = tokenizer.add_tokens(token)
|
112 |
-
i = 1
|
113 |
-
print("start while loop **************")
|
114 |
-
while(num_added_tokens == 0):
|
115 |
-
token = f"{token[:-1]}-{i}>"
|
116 |
-
num_added_tokens = tokenizer.add_tokens(token)
|
117 |
-
print("i --> ", i)
|
118 |
-
print("token --> ", token)
|
119 |
-
print("num_added_tokens --> ", num_added_tokens)
|
120 |
-
i+=1
|
121 |
-
print("end while loop **************")
|
122 |
-
|
123 |
-
# resize the token embeddings
|
124 |
-
text_encoder.resize_token_embeddings(len(tokenizer))
|
125 |
-
|
126 |
-
# get the id for the token and assign the embeds
|
127 |
-
token_id = tokenizer.convert_tokens_to_ids(token)
|
128 |
-
print("&&&&&&&&&&&&&&&&")
|
129 |
-
print("learned_embeds_path --> ", learned_embeds_path)
|
130 |
-
print("text_encoder --> ", text_encoder)
|
131 |
-
print("tokenizer --> ", tokenizer)
|
132 |
-
print("_old_token --> ", _old_token)
|
133 |
-
print("token --> ", token)
|
134 |
-
print("trained_token --> ", trained_token)
|
135 |
-
print("dtype --> ", dtype)
|
136 |
-
print("num_added_tokens --> ", num_added_tokens)
|
137 |
-
print("text_encoder --> ", text_encoder)
|
138 |
-
print("token_id --> ", token_id)
|
139 |
-
print("embeds --> ", embeds)
|
140 |
-
print("&&&&&&&&&&&&&&&&")
|
141 |
-
text_encoder.get_input_embeddings().weight.data[token_id] = embeds # <------ POINT OF FAILURE
|
142 |
-
return token
|
143 |
-
|
144 |
-
|
145 |
-
ahx_model_list = [model for model in models_list if "ahx" in model.modelId]
|
146 |
-
|
147 |
-
|
148 |
-
|
149 |
-
# UNDER CONSTRUCTION ---------------------------------------------------------------
|
150 |
-
from time import sleep
|
151 |
-
|
152 |
-
print("--------------------------------------------------")
|
153 |
-
print("--------------------------------------------------")
|
154 |
-
print("Setting up the public library........")
|
155 |
-
print("--------------------------------------------------")
|
156 |
-
for model in ahx_model_list:
|
157 |
-
model_content = {}
|
158 |
-
model_id = model.modelId
|
159 |
-
model_content["id"] = model_id
|
160 |
-
embeds_url = f"https://huggingface.co/{model_id}/resolve/main/learned_embeds.bin"
|
161 |
-
os.makedirs(model_id,exist_ok = True)
|
162 |
-
if not os.path.exists(f"{model_id}/learned_embeds.bin"):
|
163 |
-
try:
|
164 |
-
wget.download(embeds_url, out=model_id)
|
165 |
-
except:
|
166 |
-
# print("FAILURE: <-------------------------------------------------------------------")
|
167 |
-
# print("model -->", model)
|
168 |
-
# print("model_id -->", model_id)
|
169 |
-
# print("CONTINUING - MODEL NOT LOADING")
|
170 |
-
continue
|
171 |
-
|
172 |
-
token_identifier = f"https://huggingface.co/{model_id}/raw/main/token_identifier.txt"
|
173 |
-
response = requests.get(token_identifier)
|
174 |
-
token_name = response.text
|
175 |
-
|
176 |
-
concept_type = f"https://huggingface.co/{model_id}/raw/main/type_of_concept.txt"
|
177 |
-
response = requests.get(concept_type)
|
178 |
-
concept_name = response.text
|
179 |
-
model_content["concept_type"] = concept_name
|
180 |
-
images = []
|
181 |
-
for i in range(4):
|
182 |
-
url = f"https://huggingface.co/{model_id}/resolve/main/concept_images/{i}.jpeg"
|
183 |
-
image_download = requests.get(url)
|
184 |
-
url_code = image_download.status_code
|
185 |
-
if(url_code == 200):
|
186 |
-
file = open(f"{model_id}/{i}.jpeg", "wb") ## Creates the file for image
|
187 |
-
file.write(image_download.content) ## Saves file content
|
188 |
-
file.close()
|
189 |
-
images.append(f"{model_id}/{i}.jpeg")
|
190 |
-
model_content["images"] = images
|
191 |
-
#if token cannot be loaded, skip it
|
192 |
-
try:
|
193 |
-
learned_token = load_learned_embed_in_clip(f"{model_id}/learned_embeds.bin", pipe.text_encoder, pipe.tokenizer, token_name)
|
194 |
-
print("success / model loaded:")
|
195 |
-
print("model -->", model)
|
196 |
-
print("model_id -->", model_id)
|
197 |
-
except:
|
198 |
-
print("FAILURE: <- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -")
|
199 |
-
print("model -->", model)
|
200 |
-
print("model_id -->", model_id)
|
201 |
-
print("CONTINUING - MODEL NOT LOADING")
|
202 |
-
continue
|
203 |
-
model_content["token"] = learned_token
|
204 |
-
models.append(model_content)
|
205 |
-
models.append(model_content)
|
206 |
-
print("--------------------------------------------------")
|
207 |
-
sleep(5)
|
208 |
-
|
209 |
-
|
210 |
-
print("--------------------------------------------------")
|
211 |
-
print("--------------------------------------------------")
|
212 |
-
print("--------------------------------------------------")
|
213 |
-
sleep(60)
|
214 |
-
|
215 |
-
#@title Run the app to navigate around [the Library](https://huggingface.co/sd-concepts-library)
|
216 |
-
#@markdown Click the `Running on public URL:` result to run the Gradio app
|
217 |
-
|
218 |
-
SELECT_LABEL = "Select concept"
|
219 |
-
def assembleHTML(model):
|
220 |
-
html_gallery = ''
|
221 |
-
html_gallery = html_gallery+'''
|
222 |
-
<div class="flex gr-gap gr-form-gap row gap-4 w-full flex-wrap" id="main_row">
|
223 |
-
'''
|
224 |
-
cap = 0
|
225 |
-
for model in models:
|
226 |
-
html_gallery = html_gallery+f'''
|
227 |
-
<div class="gr-block gr-box relative w-full overflow-hidden border-solid border border-gray-200 gr-panel">
|
228 |
-
<div class="output-markdown gr-prose" style="max-width: 100%;">
|
229 |
-
<h3>
|
230 |
-
<a href="https://huggingface.co/{model["id"]}" target="_blank">
|
231 |
-
<code>{html.escape(model["token"])}</code>
|
232 |
-
</a>
|
233 |
-
</h3>
|
234 |
-
</div>
|
235 |
-
<div id="gallery" class="gr-block gr-box relative w-full overflow-hidden border-solid border border-gray-200">
|
236 |
-
<div class="wrap svelte-17ttdjv opacity-0"></div>
|
237 |
-
<div class="absolute left-0 top-0 py-1 px-2 rounded-br-lg shadow-sm text-xs text-gray-500 flex items-center pointer-events-none bg-white z-20 border-b border-r border-gray-100 dark:bg-gray-900">
|
238 |
-
<span class="mr-2 h-[12px] w-[12px] opacity-80">
|
239 |
-
<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" class="feather feather-image">
|
240 |
-
<rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect>
|
241 |
-
<circle cx="8.5" cy="8.5" r="1.5"></circle>
|
242 |
-
<polyline points="21 15 16 10 5 21"></polyline>
|
243 |
-
</svg>
|
244 |
-
</span> {model["concept_type"]}
|
245 |
-
</div>
|
246 |
-
<div class="overflow-y-auto h-full p-2" style="position: relative;">
|
247 |
-
<div class="grid gap-2 grid-cols-2 sm:grid-cols-2 md:grid-cols-2 lg:grid-cols-2 xl:grid-cols-2 2xl:grid-cols-2 svelte-1g9btlg pt-6">
|
248 |
-
'''
|
249 |
-
for image in model["images"]:
|
250 |
-
html_gallery = html_gallery + f'''
|
251 |
-
<button class="gallery-item svelte-1g9btlg">
|
252 |
-
<img alt="" loading="lazy" class="h-full w-full overflow-hidden object-contain" src="file/{image}">
|
253 |
-
</button>
|
254 |
-
'''
|
255 |
-
html_gallery = html_gallery+'''
|
256 |
-
</div>
|
257 |
-
<iframe style="display: block; position: absolute; top: 0; left: 0; width: 100%; height: 100%; overflow: hidden; border: 0; opacity: 0; pointer-events: none; z-index: -1;" aria-hidden="true" tabindex="-1" src="about:blank"></iframe>
|
258 |
-
</div>
|
259 |
-
</div>
|
260 |
-
</div>
|
261 |
-
'''
|
262 |
-
cap += 1
|
263 |
-
if(cap == 99):
|
264 |
-
break
|
265 |
-
html_gallery = html_gallery+'''
|
266 |
-
</div>
|
267 |
-
'''
|
268 |
-
return html_gallery
|
269 |
-
|
270 |
-
def title_block(title, id):
|
271 |
-
return gr.Markdown(f"### [`{title}`](https://huggingface.co/{id})")
|
272 |
-
|
273 |
-
def image_block(image_list, concept_type):
|
274 |
-
return gr.Gallery(
|
275 |
-
label=concept_type, value=image_list, elem_id="gallery"
|
276 |
-
).style(grid=[2], height="auto")
|
277 |
-
|
278 |
-
def checkbox_block():
|
279 |
-
checkbox = gr.Checkbox(label=SELECT_LABEL).style(container=False)
|
280 |
-
return checkbox
|
281 |
-
|
282 |
-
def infer(text):
|
283 |
-
#with autocast("cuda"):
|
284 |
-
images_list = pipe(
|
285 |
-
[text],
|
286 |
-
num_inference_steps=50,
|
287 |
-
guidance_scale=7.5
|
288 |
)
|
289 |
-
|
290 |
-
|
291 |
-
# output_images.append(image)
|
292 |
-
return images_list.images, gr.update(visible=True), gr.update(visible=True), gr.update(visible=True)
|
293 |
-
|
294 |
-
# idetnical to `infer` function without gradio state updates for share btn
|
295 |
-
def infer_examples(text):
|
296 |
-
#with autocast("cuda"):
|
297 |
-
images_list = pipe(
|
298 |
-
[text],
|
299 |
-
num_inference_steps=50,
|
300 |
-
guidance_scale=7.5
|
301 |
)
|
302 |
-
|
303 |
-
|
304 |
-
|
305 |
-
|
306 |
-
|
307 |
-
|
308 |
-
|
309 |
-
#
|
310 |
-
|
311 |
-
|
312 |
-
|
313 |
-
#
|
314 |
-
|
315 |
-
.
|
316 |
-
|
317 |
-
|
318 |
-
|
319 |
-
|
320 |
-
|
321 |
-
.
|
322 |
-
|
323 |
-
|
324 |
-
|
325 |
-
|
326 |
-
|
327 |
-
|
328 |
-
|
329 |
-
|
330 |
-
|
331 |
-
|
332 |
-
|
333 |
-
#
|
334 |
-
.
|
335 |
-
|
336 |
-
|
337 |
-
|
338 |
-
|
339 |
-
|
340 |
-
|
341 |
-
|
342 |
-
|
343 |
-
|
344 |
-
|
345 |
-
|
346 |
-
|
347 |
-
|
348 |
-
#
|
349 |
-
|
350 |
-
|
351 |
-
#
|
352 |
-
|
353 |
-
|
354 |
-
|
355 |
-
#
|
356 |
-
|
357 |
-
|
358 |
-
|
359 |
-
|
360 |
-
|
361 |
-
|
362 |
-
|
363 |
-
|
364 |
-
|
365 |
-
|
366 |
-
|
367 |
-
|
368 |
-
|
369 |
-
|
370 |
-
|
371 |
-
|
372 |
-
|
373 |
-
|
374 |
-
|
375 |
-
|
376 |
-
|
377 |
-
|
378 |
-
|
379 |
-
|
380 |
-
|
381 |
-
|
382 |
-
|
383 |
-
|
384 |
-
|
385 |
-
|
386 |
-
|
387 |
-
|
388 |
-
|
389 |
-
|
390 |
-
|
391 |
-
|
392 |
-
|
393 |
-
|
394 |
-
|
395 |
-
|
396 |
-
|
397 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
398 |
with gr.Row():
|
399 |
-
|
400 |
-
|
401 |
-
|
402 |
-
|
403 |
-
|
404 |
-
|
405 |
-
|
406 |
-
|
407 |
-
|
408 |
-
|
409 |
-
|
410 |
-
|
411 |
-
|
412 |
-
|
413 |
-
|
414 |
-
|
415 |
-
|
416 |
-
|
417 |
-
|
418 |
-
|
419 |
-
|
420 |
-
rounded=(False, True, True, False),
|
421 |
-
)
|
422 |
-
with gr.Row().style():
|
423 |
-
infer_outputs = gr.Gallery(show_label=False, elem_id="generated-gallery").style(grid=[2], height="512px")
|
424 |
-
with gr.Row():
|
425 |
-
gr.HTML("<p></p>")
|
426 |
-
with gr.Row():
|
427 |
-
gr.Examples(examples=examples, fn=infer_examples, inputs=[text], outputs=infer_outputs, cache_examples=True)
|
428 |
-
with gr.Group(elem_id="share-btn-container"):
|
429 |
-
community_icon = gr.HTML(community_icon_html, visible=False)
|
430 |
-
loading_icon = gr.HTML(loading_icon_html, visible=False)
|
431 |
-
checkbox_states = {}
|
432 |
-
inputs = [text]
|
433 |
-
btn.click(
|
434 |
-
infer,
|
435 |
-
inputs=inputs,
|
436 |
-
outputs=[infer_outputs, community_icon, loading_icon]
|
437 |
-
)
|
438 |
-
# after loading_icon on line 392.5
|
439 |
-
# share_button = gr.Button("", elem_id="share-btn", visible=False)
|
440 |
-
# and update outputs=[...] on line 398 to match this
|
441 |
-
# outputs=[infer_outputs, community_icon, loading_icon, share_button]
|
442 |
-
# then this has to be added after line 399
|
443 |
-
# share_button.click(
|
444 |
-
# None,
|
445 |
-
# [],
|
446 |
-
# [],
|
447 |
-
# _js=share_js,
|
448 |
-
# )
|
449 |
-
demo.queue(max_size=20).launch()
|
|
|
1 |
+
# !pip install -qq diffusers==0.11.1 transformers ftfy accelerate
|
2 |
+
#@title Import required libraries
|
|
|
3 |
import os
|
|
|
|
|
4 |
import torch
|
5 |
+
|
6 |
+
import PIL
|
7 |
+
from PIL import Image
|
8 |
+
|
9 |
from diffusers import StableDiffusionPipeline
|
10 |
+
from transformers import CLIPFeatureExtractor, CLIPTextModel, CLIPTokenizer
|
11 |
+
|
12 |
+
|
13 |
+
#@title Login to the Hugging Face Hub
|
14 |
+
from huggingface_hub import notebook_login
|
15 |
+
# hf_token_write = "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" # π€«
|
16 |
+
hf_token_write = os.environ['api_key']
|
17 |
+
|
18 |
+
# notebook_login()
|
19 |
+
|
20 |
+
def image_grid(imgs, rows, cols):
|
21 |
+
assert len(imgs) == rows*cols
|
22 |
+
|
23 |
+
w, h = imgs[0].size
|
24 |
+
grid = Image.new('RGB', size=(cols*w, rows*h))
|
25 |
+
grid_w, grid_h = grid.size
|
26 |
+
|
27 |
+
for i, img in enumerate(imgs):
|
28 |
+
grid.paste(img, box=(i%cols*w, i//cols*h))
|
29 |
+
return grid
|
30 |
+
|
31 |
+
## Run Stable Diffusion with pre-trained Learned Concepts
|
32 |
+
|
33 |
+
pretrained_model_name_or_path = "stabilityai/stable-diffusion-2"
|
34 |
+
|
35 |
+
|
36 |
+
|
37 |
+
from IPython.display import Markdown
|
38 |
+
from huggingface_hub import hf_hub_download
|
39 |
+
|
40 |
+
#@title Concept Pipe Function
|
41 |
+
|
42 |
+
def create_concept_pipe(model_name):
|
43 |
+
# 1. Load Concept
|
44 |
+
repo_id_embeds = f"sd-concepts-library/{model_name}" # <-------- CONCEPT NAME
|
45 |
+
|
46 |
+
embeds_url = "" #Add the URL or path to a learned_embeds.bin file in case you have one
|
47 |
+
placeholder_token_string = "" #Add what is the token string in case you are uploading your own embed
|
48 |
+
|
49 |
+
downloaded_embedding_folder = "./downloaded_embedding"
|
50 |
+
if not os.path.exists(downloaded_embedding_folder):
|
51 |
+
os.mkdir(downloaded_embedding_folder)
|
52 |
+
if(not embeds_url):
|
53 |
+
embeds_path = hf_hub_download(repo_id=repo_id_embeds, filename="learned_embeds.bin")
|
54 |
+
token_path = hf_hub_download(repo_id=repo_id_embeds, filename="token_identifier.txt")
|
55 |
+
!cp $embeds_path $downloaded_embedding_folder
|
56 |
+
!cp $token_path $downloaded_embedding_folder
|
57 |
+
with open(f'{downloaded_embedding_folder}/token_identifier.txt', 'r') as file:
|
58 |
+
placeholder_token_string = file.read()
|
59 |
+
else:
|
60 |
+
!wget -q -O $downloaded_embedding_folder/learned_embeds.bin $embeds_url
|
61 |
+
|
62 |
+
learned_embeds_path = f"{downloaded_embedding_folder}/learned_embeds.bin"
|
63 |
+
|
64 |
+
# display (Markdown("## The placeholder token for your concept is `%s`"%(placeholder_token_string)))
|
65 |
+
|
66 |
+
|
67 |
+
|
68 |
+
# 2. Set up the Tokenizer and the Text Encoder
|
69 |
+
tokenizer = CLIPTokenizer.from_pretrained(
|
70 |
+
pretrained_model_name_or_path,
|
71 |
+
subfolder="tokenizer",
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
72 |
)
|
73 |
+
text_encoder = CLIPTextModel.from_pretrained(
|
74 |
+
pretrained_model_name_or_path, subfolder="text_encoder", torch_dtype=torch.float16
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
75 |
)
|
76 |
+
|
77 |
+
|
78 |
+
|
79 |
+
# 3. Load the newly learned embeddings into CLIP
|
80 |
+
def load_learned_embed_in_clip(learned_embeds_path, text_encoder, tokenizer, token=None):
|
81 |
+
loaded_learned_embeds = torch.load(learned_embeds_path, map_location="cpu")
|
82 |
+
|
83 |
+
# separate token and the embeds
|
84 |
+
trained_token = list(loaded_learned_embeds.keys())[0]
|
85 |
+
embeds = loaded_learned_embeds[trained_token]
|
86 |
+
|
87 |
+
# cast to dtype of text_encoder
|
88 |
+
dtype = text_encoder.get_input_embeddings().weight.dtype
|
89 |
+
embeds.to(dtype)
|
90 |
+
|
91 |
+
# add the token in tokenizer
|
92 |
+
token = token if token is not None else trained_token
|
93 |
+
num_added_tokens = tokenizer.add_tokens(token)
|
94 |
+
if num_added_tokens == 0:
|
95 |
+
raise ValueError(f"The tokenizer already contains the token {token}. Please pass a different `token` that is not already in the tokenizer.")
|
96 |
+
|
97 |
+
# resize the token embeddings
|
98 |
+
text_encoder.resize_token_embeddings(len(tokenizer))
|
99 |
+
|
100 |
+
# get the id for the token and assign the embeds
|
101 |
+
token_id = tokenizer.convert_tokens_to_ids(token)
|
102 |
+
text_encoder.get_input_embeddings().weight.data[token_id] = embeds
|
103 |
+
load_learned_embed_in_clip(learned_embeds_path, text_encoder, tokenizer)
|
104 |
+
|
105 |
+
|
106 |
+
|
107 |
+
# 4. Load the Stable Diffusion pipeline
|
108 |
+
pipe = StableDiffusionPipeline.from_pretrained(
|
109 |
+
pretrained_model_name_or_path,
|
110 |
+
torch_dtype=torch.float16,
|
111 |
+
text_encoder=text_encoder,
|
112 |
+
tokenizer=tokenizer,
|
113 |
+
).to("cuda")
|
114 |
+
|
115 |
+
return pipe
|
116 |
+
|
117 |
+
# Load All Concept Pipes
|
118 |
+
|
119 |
+
models_to_load = [
|
120 |
+
# "ahx-model-3",
|
121 |
+
# "ahx-model-5",
|
122 |
+
# "ahx-model-6",
|
123 |
+
# "ahx-model-7",
|
124 |
+
# "ahx-model-8",
|
125 |
+
# "ahx-model-9",
|
126 |
+
# "ahx-model-10",
|
127 |
+
"ahx-model-11",
|
128 |
+
"ahx-model-12",
|
129 |
+
# "ahx-model-13",
|
130 |
+
# "ahx-model-14",
|
131 |
+
]
|
132 |
+
|
133 |
+
completed_concept_pipes = {}
|
134 |
+
|
135 |
+
for model in models_to_load:
|
136 |
+
completed_concept_pipes[model] = create_concept_pipe(model)
|
137 |
+
|
138 |
+
# Test Concept Pipes
|
139 |
+
|
140 |
+
#@title Create Image Function
|
141 |
+
|
142 |
+
import random
|
143 |
+
|
144 |
+
def random_seed():
|
145 |
+
return random.randint(0, 18446744073709551615)
|
146 |
+
|
147 |
+
def create_image(concept="", prompt="", height=768, width=768, steps=30, guidance=7.5, seed=None):
|
148 |
+
complete_prompt = f"{prompt} in the style of \u003C{concept}>"
|
149 |
+
|
150 |
+
if seed is None:
|
151 |
+
seed = random_seed()
|
152 |
+
|
153 |
+
num_samples = 1
|
154 |
+
num_rows = 1
|
155 |
+
|
156 |
+
all_images = []
|
157 |
+
for _ in range(num_rows):
|
158 |
+
pipe = completed_concept_pipes[concept]
|
159 |
+
|
160 |
+
generator = torch.Generator(device="cuda").manual_seed(seed)
|
161 |
+
|
162 |
+
images = pipe(complete_prompt, num_images_per_prompt=num_samples, num_inference_steps=steps, guidance_scale=guidance, height=int((height // 8) * 8), width=int((width // 8) * 8), generator=generator).images
|
163 |
+
|
164 |
+
# images = pipe(complete_prompt, num_images_per_prompt=num_samples, height=height, width=width, num_inference_steps=30, guidance_scale=7.5).images
|
165 |
+
all_images.extend(images)
|
166 |
+
|
167 |
+
grid = image_grid(all_images, num_samples, num_rows)
|
168 |
+
|
169 |
+
return {
|
170 |
+
"complete_prompt": complete_prompt,
|
171 |
+
"seed": seed,
|
172 |
+
"guidance": guidance,
|
173 |
+
"inf_steps": steps,
|
174 |
+
"grid": grid,
|
175 |
+
}
|
176 |
+
|
177 |
+
#@title Test Text-to-Image Functionality
|
178 |
+
|
179 |
+
concept = "ahx-model-11" #@param {type:"string"}
|
180 |
+
prompt = "forgotten" #@param {type:"string"}
|
181 |
+
|
182 |
+
height = 525 #@param {type:"integer"}
|
183 |
+
width = 1700 #@param {type:"integer"}
|
184 |
+
# max square --> 983 x 983 --> 966,289 px^2
|
185 |
+
# default good square --> 768 x 768
|
186 |
+
|
187 |
+
guidance = 7.5 #@param {type:"number"}
|
188 |
+
steps = 30 #@param {type:"integer"}
|
189 |
+
seed = None #@param {type:"integer"}
|
190 |
+
|
191 |
+
image_obj = create_image(concept, prompt, steps=steps, guidance=guidance, height=height, width=width, seed=seed)
|
192 |
+
|
193 |
+
print(image_obj)
|
194 |
+
image_obj["grid"]
|
195 |
+
|
196 |
+
# Create Gradio Interface
|
197 |
+
|
198 |
+
# !pip install gradio
|
199 |
+
import gradio as gr
|
200 |
+
|
201 |
+
#@title Gradio Concept Loader
|
202 |
+
DROPDOWNS = {}
|
203 |
+
|
204 |
+
# images = pipe(complete_prompt, num_images_per_prompt=num_samples, num_inference_steps=steps, guidance_scale=guidance, height=int((height // 8) * 8), width=int((width // 8) * 8), generator=generator).images
|
205 |
+
|
206 |
+
for model in models_to_load:
|
207 |
+
# token = model.split("/")[1]
|
208 |
+
DROPDOWNS[model] = f" in the style of <{model}>"
|
209 |
+
|
210 |
+
if "sd-concepts-library/ahx-model-5" in DROPDOWNS:
|
211 |
+
DROPDOWNS["sd-concepts-library/ahx-model-5"] = f"{prompt} in the style of <ahx-model-4>"
|
212 |
+
|
213 |
+
def image_prompt(prompt, dropdown, guidance, steps, seed, height, width):
|
214 |
+
# def image_prompt(prompt, dropdown, seed):
|
215 |
+
prompt = prompt + DROPDOWNS[dropdown]
|
216 |
+
pipe = completed_concept_pipes[dropdown]
|
217 |
+
generator = torch.Generator(device="cuda").manual_seed(int(seed))
|
218 |
+
return (
|
219 |
+
pipe(prompt=prompt, guidance_scale=guidance, num_inference_steps=steps, generator=generator, height=int((height // 8) * 8), width=int((width // 8) * 8)).images[0],
|
220 |
+
f"prompt = '{prompt}'\nseed = {int(seed)}\nguidance_scale = {guidance}\ninference steps = {steps}\nheight = {int((height // 8) * 8)}\nwidth = {int((width // 8) * 8)}"
|
221 |
+
)
|
222 |
+
# images = pipe(complete_prompt, num_images_per_prompt=num_samples, num_inference_steps=steps, guidance_scale=guidance, height=int((height // 8) * 8), width=int((width // 8) * 8), generator=generator).images
|
223 |
+
# return pipe(prompt=prompt, height=768, width=768, generator=generator).images[0]
|
224 |
+
|
225 |
+
|
226 |
+
def default_guidance():
|
227 |
+
return 7.5
|
228 |
+
|
229 |
+
def default_steps():
|
230 |
+
return 30
|
231 |
+
|
232 |
+
def default_pixel():
|
233 |
+
return 768
|
234 |
+
|
235 |
+
def random_seed():
|
236 |
+
return random.randint(0, 99999999999999) # <-- this is a random gradio limit, the seed range seems to actually be 0-18446744073709551615
|
237 |
+
|
238 |
+
# with gr.Blocks(css=gradio_css) as demo:
|
239 |
+
with gr.Blocks(css=".gradio-container {max-width: 650px}") as demo:
|
240 |
+
dropdown = gr.Dropdown(list(DROPDOWNS), label="choose style...")
|
241 |
+
gr.Markdown("<u>styles</u>: check out examples of these at https://www.astronaut.horse/collaborations")
|
242 |
+
prompt = gr.Textbox(label="image prompt...", elem_id="input-text")
|
243 |
+
seed = gr.Slider(0, 99999999999999, label="seed", dtype=int, value=random_seed, interactive=True, step=1)
|
244 |
+
with gr.Row():
|
245 |
+
with gr.Column():
|
246 |
+
guidance = gr.Slider(0, 10, label="guidance", dtype=float, value=default_guidance, step=0.1, interactive=True)
|
247 |
+
with gr.Column():
|
248 |
+
steps = gr.Slider(1, 100, label="inference steps", dtype=int, value=default_steps, step=1, interactive=True)
|
249 |
with gr.Row():
|
250 |
+
with gr.Column():
|
251 |
+
height = gr.Slider(50, 3500, label="height", dtype=int, value=default_pixel, step=1, interactive=True)
|
252 |
+
with gr.Column():
|
253 |
+
width = gr.Slider(50, 3500, label="width", dtype=int, value=default_pixel, step=1, interactive=True)
|
254 |
+
gr.Markdown("<u>heads-up</u>: height multiplied by width should not exceed about 195,000 or an error will occur so don't go too nuts")
|
255 |
+
|
256 |
+
# seed = gr.Slider(0, 18446744073709551615, label="seed", dtype=int, value=random_seed, interactive=True, step=1)
|
257 |
+
# seed = gr.Slider(0, 18446744073709550591, label="seed", dtype=int, value=random_seed, interactive=True, step=1)
|
258 |
+
# seed = gr.Slider(0, 18446744073709550, label="seed", dtype=int, value=random_seed, interactive=True, step=1)
|
259 |
+
# seed = gr.Slider(0, 85835103557872, label="seed", dtype=int, value=random_seed, interactive=True, step=1)
|
260 |
+
|
261 |
+
output = gr.Image(elem_id="output-image")
|
262 |
+
output_text = gr.Text(elem_id="output-text")
|
263 |
+
go_button = gr.Button("draw it!", elem_id="go-button")
|
264 |
+
go_button.click(fn=image_prompt, inputs=[prompt, dropdown, guidance, steps, seed, height, width], outputs=[output, output_text])
|
265 |
+
# go_button.click(fn=image_prompt, inputs=[prompt, dropdown, seed], outputs=output)
|
266 |
+
|
267 |
+
#@title Create Gradio Tab Interface
|
268 |
+
|
269 |
+
tabbed_interface = gr.TabbedInterface([demo], ["Concept Loader"])
|
270 |
+
tabbed_interface.launch(share=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|