tombetthauser commited on
Commit
5e22611
Β·
1 Parent(s): 4a237f8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +36 -278
app.py CHANGED
@@ -11,90 +11,19 @@ from huggingface_hub import HfApi
11
  from transformers import CLIPTextModel, CLIPTokenizer
12
  import html
13
 
14
- community_icon_html = """<svg id="share-btn-share-icon" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32">
15
- <path d="M20.6081 3C21.7684 3 22.8053 3.49196 23.5284 4.38415C23.9756 4.93678 24.4428 5.82749 24.4808 7.16133C24.9674 7.01707 25.4353 6.93643 25.8725 6.93643C26.9833 6.93643 27.9865 7.37587 28.696 8.17411C29.6075 9.19872 30.0124 10.4579 29.8361 11.7177C29.7523 12.3177 29.5581 12.8555 29.2678 13.3534C29.8798 13.8646 30.3306 14.5763 30.5485 15.4322C30.719 16.1032 30.8939 17.5006 29.9808 18.9403C30.0389 19.0342 30.0934 19.1319 30.1442 19.2318C30.6932 20.3074 30.7283 21.5229 30.2439 22.6548C29.5093 24.3704 27.6841 25.7219 24.1397 27.1727C21.9347 28.0753 19.9174 28.6523 19.8994 28.6575C16.9842 29.4379 14.3477 29.8345 12.0653 29.8345C7.87017 29.8345 4.8668 28.508 3.13831 25.8921C0.356375 21.6797 0.754104 17.8269 4.35369 14.1131C6.34591 12.058 7.67023 9.02782 7.94613 8.36275C8.50224 6.39343 9.97271 4.20438 12.4172 4.20438H12.4179C12.6236 4.20438 12.8314 4.2214 13.0364 4.25468C14.107 4.42854 15.0428 5.06476 15.7115 6.02205C16.4331 5.09583 17.134 4.359 17.7682 3.94323C18.7242 3.31737 19.6794 3 20.6081 3ZM20.6081 5.95917C20.2427 5.95917 19.7963 6.1197 19.3039 6.44225C17.7754 7.44319 14.8258 12.6772 13.7458 14.7131C13.3839 15.3952 12.7655 15.6837 12.2086 15.6837C11.1036 15.6837 10.2408 14.5497 12.1076 13.1085C14.9146 10.9402 13.9299 7.39584 12.5898 7.1776C12.5311 7.16799 12.4731 7.16355 12.4172 7.16355C11.1989 7.16355 10.6615 9.33114 10.6615 9.33114C10.6615 9.33114 9.0863 13.4148 6.38031 16.206C3.67434 18.998 3.5346 21.2388 5.50675 24.2246C6.85185 26.2606 9.42666 26.8753 12.0653 26.8753C14.8021 26.8753 17.6077 26.2139 19.1799 25.793C19.2574 25.7723 28.8193 22.984 27.6081 20.6107C27.4046 20.212 27.0693 20.0522 26.6471 20.0522C24.9416 20.0522 21.8393 22.6726 20.5057 22.6726C20.2076 22.6726 19.9976 22.5416 19.9116 22.222C19.3433 20.1173 28.552 19.2325 27.7758 16.1839C27.639 15.6445 27.2677 15.4256 26.746 15.4263C24.4923 15.4263 19.4358 19.5181 18.3759 19.5181C18.2949 19.5181 18.2368 19.4937 18.2053 19.4419C17.6743 18.557 17.9653 17.9394 21.7082 15.6009C25.4511 13.2617 28.0783 11.8545 26.5841 10.1752C26.4121 9.98141 26.1684 9.8956 25.8725 9.8956C23.6001 9.89634 18.2311 14.9403 18.2311 14.9403C18.2311 14.9403 16.7821 16.496 15.9057 16.496C15.7043 16.496 15.533 16.4139 15.4169 16.2112C14.7956 15.1296 21.1879 10.1286 21.5484 8.06535C21.7928 6.66715 21.3771 5.95917 20.6081 5.95917Z" fill="#FF9D00"></path>
16
- <path d="M5.50686 24.2246C3.53472 21.2387 3.67446 18.9979 6.38043 16.206C9.08641 13.4147 10.6615 9.33111 10.6615 9.33111C10.6615 9.33111 11.2499 6.95933 12.59 7.17757C13.93 7.39581 14.9139 10.9401 12.1069 13.1084C9.29997 15.276 12.6659 16.7489 13.7459 14.713C14.8258 12.6772 17.7747 7.44316 19.304 6.44221C20.8326 5.44128 21.9089 6.00204 21.5484 8.06532C21.188 10.1286 14.795 15.1295 15.4171 16.2118C16.0391 17.2934 18.2312 14.9402 18.2312 14.9402C18.2312 14.9402 25.0907 8.49588 26.5842 10.1752C28.0776 11.8545 25.4512 13.2616 21.7082 15.6008C17.9646 17.9393 17.6744 18.557 18.2054 19.4418C18.7372 20.3266 26.9998 13.1351 27.7759 16.1838C28.5513 19.2324 19.3434 20.1173 19.9117 22.2219C20.48 24.3274 26.3979 18.2382 27.6082 20.6107C28.8193 22.9839 19.2574 25.7722 19.18 25.7929C16.0914 26.62 8.24723 28.3726 5.50686 24.2246Z" fill="#FFD21E"></path>
17
- </svg>"""
18
 
19
- loading_icon_html = """<svg id="share-btn-loading-icon" style="display:none;" class="animate-spin"
20
- style="color: #ffffff;
21
- "
22
- xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" fill="none" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 24 24"><circle style="opacity: 0.25;" cx="12" cy="12" r="10" stroke="white" stroke-width="4"></circle><path style="opacity: 0.75;" fill="white" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path></svg>"""
23
-
24
- share_js = """async () => {
25
- async function uploadFile(file){
26
- const UPLOAD_URL = 'https://huggingface.co/uploads';
27
- const response = await fetch(UPLOAD_URL, {
28
- method: 'POST',
29
- headers: {
30
- 'Content-Type': file.type,
31
- 'X-Requested-With': 'XMLHttpRequest',
32
- },
33
- body: file, /// <- File inherits from Blob
34
- });
35
- const url = await response.text();
36
- return url;
37
- }
38
- const gradioEl = document.querySelector('body > gradio-app');
39
- const imgEls = gradioEl.querySelectorAll('#generated-gallery img');
40
- const promptTxt = gradioEl.querySelector('#prompt_input input').value;
41
- const shareBtnEl = gradioEl.querySelector('#share-btn');
42
- const shareIconEl = gradioEl.querySelector('#share-btn-share-icon');
43
- const loadingIconEl = gradioEl.querySelector('#share-btn-loading-icon');
44
- if(!imgEls.length){
45
- return;
46
- };
47
- shareBtnEl.style.pointerEvents = 'none';
48
- shareIconEl.style.display = 'none';
49
- loadingIconEl.style.removeProperty('display');
50
- const files = await Promise.all(
51
- [...imgEls].map(async (imgEl) => {
52
- const res = await fetch(imgEl.src);
53
- const blob = await res.blob();
54
- const imgId = Date.now() % 200;
55
- const fileName = `diffuse-the-rest-${{imgId}}.png`;
56
- return new File([blob], fileName, { type: 'image/png' });
57
- })
58
- );
59
- const REGEX_CONCEPT = /<(((?!<.+>).)+)>/gm;
60
- const matches = [...promptTxt.matchAll(REGEX_CONCEPT)];
61
- const concepts = matches.map(m => m[1]);
62
- const conceptLibraryMd = concepts.map(c => `<a href='https://huggingface.co/sd-concepts-library/${c}' target='_blank'>${c}</a>`).join(`, `);
63
- const urls = await Promise.all(files.map((f) => uploadFile(f)));
64
- const htmlImgs = urls.map(url => `<img src='${url}' width='400' height='400'>`);
65
- const htmlImgsMd = htmlImgs.join(`\n`);
66
- const descriptionMd = `#### Prompt:
67
- ${promptTxt.replace(/</g, '\\\<').replace(/>/g, '\\\>')}
68
- #### Concepts Used:
69
- ${conceptLibraryMd}
70
- #### Generations:
71
- <div style='display: flex; flex-wrap: wrap; column-gap: 0.75rem;'>
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("stabilityai/stable-diffusion-2", revision="fp16", torch_dtype=torch.float16, use_auth_token=my_token).to("cuda")
94
- # pipe = StableDiffusionPipeline.from_pretrained("CompVis/stable-diffusion-v1-4", revision="fp16", torch_dtype=torch.float16, use_auth_token=my_token).to("cuda")
95
- # }}}
96
-
97
- # pipe = StableDiffusionPipeline.from_pretrained("CompVis/stable-diffusion-v1-4", use_auth_token=True, revision="fp16", torch_dtype=torch.float16).to("cuda")
98
 
99
  def load_learned_embed_in_clip(learned_embeds_path, text_encoder, tokenizer, token=None):
100
  loaded_learned_embeds = torch.load(learned_embeds_path, map_location="cpu")
@@ -111,49 +40,23 @@ def load_learned_embed_in_clip(learned_embeds_path, text_encoder, tokenizer, tok
111
  token = token if token is not None else trained_token
112
  num_added_tokens = tokenizer.add_tokens(token)
113
  i = 1
114
- print("start while loop **************")
115
  while(num_added_tokens == 0):
116
  token = f"{token[:-1]}-{i}>"
117
  num_added_tokens = tokenizer.add_tokens(token)
118
- print("i --> ", i)
119
- print("token --> ", token)
120
- print("num_added_tokens --> ", num_added_tokens)
121
  i+=1
122
- print("end while loop **************")
123
 
124
  # resize the token embeddings
125
  text_encoder.resize_token_embeddings(len(tokenizer))
126
 
127
  # get the id for the token and assign the embeds
128
  token_id = tokenizer.convert_tokens_to_ids(token)
129
- print("&&&&&&&&&&&&&&&&")
130
- print("learned_embeds_path --> ", learned_embeds_path)
131
- print("text_encoder --> ", text_encoder)
132
- print("tokenizer --> ", tokenizer)
133
- print("_old_token --> ", _old_token)
134
- print("token --> ", token)
135
- print("trained_token --> ", trained_token)
136
- print("dtype --> ", dtype)
137
- print("num_added_tokens --> ", num_added_tokens)
138
- print("text_encoder --> ", text_encoder)
139
- print("token_id --> ", token_id)
140
- print("embeds --> ", embeds)
141
- print("&&&&&&&&&&&&&&&&")
142
- text_encoder.get_input_embeddings().weight.data[token_id] = embeds # <------ POINT OF FAILURE
143
  return token
144
 
145
 
146
  ahx_model_list = [model for model in models_list if "ahx" in model.modelId]
147
 
148
 
149
-
150
- # UNDER CONSTRUCTION ---------------------------------------------------------------
151
- from time import sleep
152
-
153
- print("--------------------------------------------------")
154
- print("--------------------------------------------------")
155
- print("Setting up the public library........")
156
- print("--------------------------------------------------")
157
  for model in ahx_model_list:
158
  model_content = {}
159
  model_id = model.modelId
@@ -164,10 +67,6 @@ for model in ahx_model_list:
164
  try:
165
  wget.download(embeds_url, out=model_id)
166
  except:
167
- # print("FAILURE: <-------------------------------------------------------------------")
168
- # print("model -->", model)
169
- # print("model_id -->", model_id)
170
- # print("CONTINUING - MODEL NOT LOADING")
171
  continue
172
 
173
  token_identifier = f"https://huggingface.co/{model_id}/raw/main/token_identifier.txt"
@@ -192,81 +91,20 @@ for model in ahx_model_list:
192
  #if token cannot be loaded, skip it
193
  try:
194
  learned_token = load_learned_embed_in_clip(f"{model_id}/learned_embeds.bin", pipe.text_encoder, pipe.tokenizer, token_name)
195
- print("success / model loaded:")
196
- print("model -->", model)
197
- print("model_id -->", model_id)
198
  except:
199
- print("FAILURE: <- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -")
200
- print("model -->", model)
201
- print("model_id -->", model_id)
202
- print("CONTINUING - MODEL NOT LOADING")
203
  continue
204
  model_content["token"] = learned_token
205
  models.append(model_content)
206
  models.append(model_content)
207
- print("--------------------------------------------------")
208
- sleep(5)
209
 
210
 
211
- print("--------------------------------------------------")
212
- print("--------------------------------------------------")
213
- print("--------------------------------------------------")
214
- sleep(60)
215
-
216
- #@title Run the app to navigate around [the Library](https://huggingface.co/sd-concepts-library)
217
- #@markdown Click the `Running on public URL:` result to run the Gradio app
218
 
219
  SELECT_LABEL = "Select concept"
220
  def assembleHTML(model):
221
- html_gallery = ''
222
- html_gallery = html_gallery+'''
223
- <div class="flex gr-gap gr-form-gap row gap-4 w-full flex-wrap" id="main_row">
224
- '''
225
- cap = 0
226
- for model in models:
227
- html_gallery = html_gallery+f'''
228
- <div class="gr-block gr-box relative w-full overflow-hidden border-solid border border-gray-200 gr-panel">
229
- <div class="output-markdown gr-prose" style="max-width: 100%;">
230
- <h3>
231
- <a href="https://huggingface.co/{model["id"]}" target="_blank">
232
- <code>{html.escape(model["token"])}</code>
233
- </a>
234
- </h3>
235
- </div>
236
- <div id="gallery" class="gr-block gr-box relative w-full overflow-hidden border-solid border border-gray-200">
237
- <div class="wrap svelte-17ttdjv opacity-0"></div>
238
- <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">
239
- <span class="mr-2 h-[12px] w-[12px] opacity-80">
240
- <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">
241
- <rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect>
242
- <circle cx="8.5" cy="8.5" r="1.5"></circle>
243
- <polyline points="21 15 16 10 5 21"></polyline>
244
- </svg>
245
- </span> {model["concept_type"]}
246
- </div>
247
- <div class="overflow-y-auto h-full p-2" style="position: relative;">
248
- <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">
249
- '''
250
- for image in model["images"]:
251
- html_gallery = html_gallery + f'''
252
- <button class="gallery-item svelte-1g9btlg">
253
- <img alt="" loading="lazy" class="h-full w-full overflow-hidden object-contain" src="file/{image}">
254
- </button>
255
- '''
256
- html_gallery = html_gallery+'''
257
- </div>
258
- <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>
259
- </div>
260
- </div>
261
- </div>
262
- '''
263
- cap += 1
264
- if(cap == 99):
265
- break
266
- html_gallery = html_gallery+'''
267
- </div>
268
- '''
269
- return html_gallery
270
 
271
  def title_block(title, id):
272
  return gr.Markdown(f"### [`{title}`](https://huggingface.co/{id})")
@@ -281,79 +119,22 @@ def checkbox_block():
281
  return checkbox
282
 
283
  def infer(text):
284
- #with autocast("cuda"):
285
  images_list = pipe(
286
  [text],
287
  num_inference_steps=50,
288
  guidance_scale=7.5
289
  )
290
- #output_images = []
291
- #for i, image in enumerate(images_list.images):
292
- # output_images.append(image)
293
  return images_list.images, gr.update(visible=True), gr.update(visible=True), gr.update(visible=True)
294
 
295
- # idetnical to `infer` function without gradio state updates for share btn
296
  def infer_examples(text):
297
- #with autocast("cuda"):
298
  images_list = pipe(
299
  [text],
300
  num_inference_steps=50,
301
  guidance_scale=7.5
302
  )
303
- #output_images = []
304
- #for i, image in enumerate(images_list["sample"]):
305
- # output_images.append(image)
306
  return images_list.images
307
 
308
- css = '''
309
- .gradio-container {font-family: 'IBM Plex Sans', sans-serif}
310
- #top_title{margin-bottom: .5em}
311
- #top_title h2{margin-bottom: 0; text-align: center}
312
- /*#main_row{flex-wrap: wrap; gap: 1em; max-height: 550px; overflow-y: scroll; flex-direction: row}*/
313
- #component-3{height: 760px; overflow: auto}
314
- #component-9{position: sticky;top: 0;align-self: flex-start;}
315
- @media (min-width: 768px){#main_row > div{flex: 1 1 32%; margin-left: 0 !important}}
316
- .gr-prose code::before, .gr-prose code::after {content: "" !important}
317
- ::-webkit-scrollbar {width: 10px}
318
- ::-webkit-scrollbar-track {background: #f1f1f1}
319
- ::-webkit-scrollbar-thumb {background: #888}
320
- ::-webkit-scrollbar-thumb:hover {background: #555}
321
- .gr-button {white-space: nowrap}
322
- .gr-button:focus {
323
- border-color: rgb(147 197 253 / var(--tw-border-opacity));
324
- outline: none;
325
- box-shadow: var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow, 0 0 #0000);
326
- --tw-border-opacity: 1;
327
- --tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);
328
- --tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(3px var(--tw-ring-offset-width)) var(--tw-ring-color);
329
- --tw-ring-color: rgb(191 219 254 / var(--tw-ring-opacity));
330
- --tw-ring-opacity: .5;
331
- }
332
- #prompt_input{flex: 1 3 auto; width: auto !important;}
333
- #prompt_area{margin-bottom: .75em}
334
- #prompt_area > div:first-child{flex: 1 3 auto}
335
- .animate-spin {
336
- animation: spin 1s linear infinite;
337
- }
338
- @keyframes spin {
339
- from {
340
- transform: rotate(0deg);
341
- }
342
- to {
343
- transform: rotate(360deg);
344
- }
345
- }
346
- #share-btn-container {
347
- display: flex; padding-left: 0.5rem !important; padding-right: 0.5rem !important; background-color: #000000; justify-content: center; align-items: center; border-radius: 9999px !important; width: 13rem;
348
- }
349
- #share-btn {
350
- all: initial; color: #ffffff;font-weight: 600; cursor:pointer; font-family: 'IBM Plex Sans', sans-serif; margin-left: 0.5rem !important; padding-top: 0.25rem !important; padding-bottom: 0.25rem !important;
351
- }
352
- #share-btn * {
353
- all: unset;
354
- }
355
- '''
356
- # examples = ["a <cat-toy> in <madhubani-art> style", "a <line-art> style mecha robot", "a piano being played by <bonzi>", "Candid photo of <cheburashka>, high resolution photo, trending on artstation, interior design"]
357
  examples = []
358
 
359
  with gr.Blocks(css=css) as demo:
@@ -369,43 +150,14 @@ with gr.Blocks(css=css) as demo:
369
  else:
370
  state[i] = True
371
  checkbox_states[i] = True
372
- gr.HTML('''
373
- <div style="text-align: left; max-width: 720px; margin: 0 auto;">
374
- <br>
375
- <h1 style="font-weight: 900; margin-bottom: 7px;">
376
- πŸ§‘β€πŸš€ Astronaut Horse Concept Loader
377
- </h1>
378
- <br>
379
- <p _style="margin-bottom: 10px; font-size: 94%">
380
- Run your own text prompts into fine-tuned artist concepts, see the example below. Currently only loading two artist concepts while testing. Soon will automatically be able to add all concepts from astronaut horse artist collaborations. There's some buggy stuff here that'll be cleared up next week but I wanted to at least get this usable for the weekend!
381
- </p>
382
- <br>
383
- <a style="text-decoration:underline;" href="http://www.astronaut.horse">http://www.astronaut.horse</a>
384
- <br>
385
- <br>
386
- <h2 style="font-weight:500;">Prompt Examples Using Artist Token:</h2>
387
- <ul>
388
- <li>"a photograph of pink crystals in the style of &lt;artist&gt;"</li>
389
- <li>"a painting of a horse in the style of &lt;ivan-stripes&gt;"</li>
390
- </ul>
391
- <br>
392
- <h2 style="font-weight:500;">Currently-Usable Concept Tokens:</h2>
393
- <ul>
394
- <li>&lt;artist&gt;</li>
395
- <li>&lt;ivan-stripes&gt;</li>
396
- </ul>
397
- </div>
398
  ''')
399
  with gr.Row():
400
- # with gr.Column():
401
- # gr.Markdown(f"")
402
- # with gr.Row():
403
- # image_blocks = []
404
- # #for i, model in enumerate(models):
405
- # with gr.Box().style(border=None):
406
- # gr.HTML(assembleHTML(models))
407
- # #title_block(model["token"], model["id"])
408
- # #image_blocks.append(image_block(model["images"], model["concept_type"]))
409
  with gr.Column():
410
  with gr.Box():
411
  with gr.Row(elem_id="prompt_area").style(mobile_collapse=False, equal_height=True):
@@ -420,8 +172,8 @@ with gr.Blocks(css=css) as demo:
420
  margin=False,
421
  rounded=(False, True, True, False),
422
  )
423
- with gr.Row().style():
424
- infer_outputs = gr.Gallery(show_label=False, elem_id="generated-gallery").style(grid=[2], height="512px")
425
  with gr.Row():
426
  gr.HTML("<p></p>")
427
  with gr.Row():
@@ -436,15 +188,21 @@ with gr.Blocks(css=css) as demo:
436
  inputs=inputs,
437
  outputs=[infer_outputs, community_icon, loading_icon]
438
  )
439
- # after loading_icon on line 392.5
440
- # share_button = gr.Button("", elem_id="share-btn", visible=False)
441
- # and update outputs=[...] on line 398 to match this
442
- # outputs=[infer_outputs, community_icon, loading_icon, share_button]
443
- # then this has to be added after line 399
444
- # share_button.click(
445
- # None,
446
- # [],
447
- # [],
448
- # _js=share_js,
449
- # )
 
 
 
 
 
 
450
  demo.queue(max_size=20).launch()
 
11
  from transformers import CLIPTextModel, CLIPTokenizer
12
  import html
13
 
14
+ community_icon_html = ""
 
 
 
15
 
16
+ loading_icon_html = ""
17
+ share_js = ""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18
 
19
  api = HfApi()
20
  models_list = api.list_models(author="sd-concepts-library", sort="likes", direction=-1)
21
  models = []
22
 
23
+ my_token = os.environ['api_key']
24
+ # my_token = "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" # 🀫
 
25
 
26
  pipe = StableDiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-2", revision="fp16", torch_dtype=torch.float16, use_auth_token=my_token).to("cuda")
 
 
 
 
27
 
28
  def load_learned_embed_in_clip(learned_embeds_path, text_encoder, tokenizer, token=None):
29
  loaded_learned_embeds = torch.load(learned_embeds_path, map_location="cpu")
 
40
  token = token if token is not None else trained_token
41
  num_added_tokens = tokenizer.add_tokens(token)
42
  i = 1
 
43
  while(num_added_tokens == 0):
44
  token = f"{token[:-1]}-{i}>"
45
  num_added_tokens = tokenizer.add_tokens(token)
 
 
 
46
  i+=1
 
47
 
48
  # resize the token embeddings
49
  text_encoder.resize_token_embeddings(len(tokenizer))
50
 
51
  # get the id for the token and assign the embeds
52
  token_id = tokenizer.convert_tokens_to_ids(token)
53
+ text_encoder.get_input_embeddings().weight.data[token_id] = embeds
 
 
 
 
 
 
 
 
 
 
 
 
 
54
  return token
55
 
56
 
57
  ahx_model_list = [model for model in models_list if "ahx" in model.modelId]
58
 
59
 
 
 
 
 
 
 
 
 
60
  for model in ahx_model_list:
61
  model_content = {}
62
  model_id = model.modelId
 
67
  try:
68
  wget.download(embeds_url, out=model_id)
69
  except:
 
 
 
 
70
  continue
71
 
72
  token_identifier = f"https://huggingface.co/{model_id}/raw/main/token_identifier.txt"
 
91
  #if token cannot be loaded, skip it
92
  try:
93
  learned_token = load_learned_embed_in_clip(f"{model_id}/learned_embeds.bin", pipe.text_encoder, pipe.tokenizer, token_name)
 
 
 
94
  except:
 
 
 
 
95
  continue
96
  model_content["token"] = learned_token
97
  models.append(model_content)
98
  models.append(model_content)
 
 
99
 
100
 
101
+
102
+
103
+ #@title Prepare the Concepts Library to be used
 
 
 
 
104
 
105
  SELECT_LABEL = "Select concept"
106
  def assembleHTML(model):
107
+ return ''
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
108
 
109
  def title_block(title, id):
110
  return gr.Markdown(f"### [`{title}`](https://huggingface.co/{id})")
 
119
  return checkbox
120
 
121
  def infer(text):
 
122
  images_list = pipe(
123
  [text],
124
  num_inference_steps=50,
125
  guidance_scale=7.5
126
  )
 
 
 
127
  return images_list.images, gr.update(visible=True), gr.update(visible=True), gr.update(visible=True)
128
 
 
129
  def infer_examples(text):
 
130
  images_list = pipe(
131
  [text],
132
  num_inference_steps=50,
133
  guidance_scale=7.5
134
  )
 
 
 
135
  return images_list.images
136
 
137
+ css = ""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
138
  examples = []
139
 
140
  with gr.Blocks(css=css) as demo:
 
150
  else:
151
  state[i] = True
152
  checkbox_states[i] = True
153
+ gr.Markdown('''
154
+ # πŸ§‘β€πŸš€ Astronaut Horse Concept Loader
155
+
156
+ Run your own text prompts into fine-tuned artist concepts, see the example below. Currently only loading two artist concepts while testing. Soon will automatically be able to add all concepts from astronaut horse artist collaborations. There's some buggy stuff here that'll be cleared up next week but I wanted to at least get this usable for the weekend!
157
+
158
+ http://www.astronaut.horse
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
159
  ''')
160
  with gr.Row():
 
 
 
 
 
 
 
 
 
161
  with gr.Column():
162
  with gr.Box():
163
  with gr.Row(elem_id="prompt_area").style(mobile_collapse=False, equal_height=True):
 
172
  margin=False,
173
  rounded=(False, True, True, False),
174
  )
175
+ # with gr.Row().style():
176
+ infer_outputs = gr.Gallery(show_label=False, elem_id="generated-gallery").style(grid=[1], height="512px")
177
  with gr.Row():
178
  gr.HTML("<p></p>")
179
  with gr.Row():
 
188
  inputs=inputs,
189
  outputs=[infer_outputs, community_icon, loading_icon]
190
  )
191
+ gr.Markdown('''
192
+ ## Prompt Examples Using Artist Token:
193
+ * "a painting in the style of \<ahx-model-11>"
194
+ * "an alien in the style of \<ahx-model-12>"
195
+
196
+ ## Valid Artist Tokens:
197
+ * \<afx-model-3>
198
+ * \<afx-model-4>
199
+ * \<afx-model-6>
200
+ * \<afx-model-7>
201
+ * \<afx-model-9>
202
+ * \<afx-model-10>
203
+ * \<afx-model-11>
204
+ * \<afx-model-12>
205
+ * \<afx-model-13>
206
+ * \<afx-model-14>
207
+ ''')
208
  demo.queue(max_size=20).launch()