runshouse multimodalart HF staff commited on
Commit
862693b
0 Parent(s):

Duplicate from sd-concepts-library/stable-diffusion-conceptualizer

Browse files

Co-authored-by: Multimodal AI art <multimodalart@users.noreply.huggingface.co>

Files changed (5) hide show
  1. .gitattributes +31 -0
  2. README.md +14 -0
  3. app.py +344 -0
  4. requirements.txt +9 -0
  5. share_btn.py +82 -0
.gitattributes ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ftz filter=lfs diff=lfs merge=lfs -text
6
+ *.gz filter=lfs diff=lfs merge=lfs -text
7
+ *.h5 filter=lfs diff=lfs merge=lfs -text
8
+ *.joblib filter=lfs diff=lfs merge=lfs -text
9
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
10
+ *.model filter=lfs diff=lfs merge=lfs -text
11
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
12
+ *.npy filter=lfs diff=lfs merge=lfs -text
13
+ *.npz filter=lfs diff=lfs merge=lfs -text
14
+ *.onnx filter=lfs diff=lfs merge=lfs -text
15
+ *.ot filter=lfs diff=lfs merge=lfs -text
16
+ *.parquet filter=lfs diff=lfs merge=lfs -text
17
+ *.pickle filter=lfs diff=lfs merge=lfs -text
18
+ *.pkl filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pt filter=lfs diff=lfs merge=lfs -text
21
+ *.pth filter=lfs diff=lfs merge=lfs -text
22
+ *.rar filter=lfs diff=lfs merge=lfs -text
23
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
24
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
25
+ *.tflite filter=lfs diff=lfs merge=lfs -text
26
+ *.tgz filter=lfs diff=lfs merge=lfs -text
27
+ *.wasm filter=lfs diff=lfs merge=lfs -text
28
+ *.xz filter=lfs diff=lfs merge=lfs -text
29
+ *.zip filter=lfs diff=lfs merge=lfs -text
30
+ *.zst filter=lfs diff=lfs merge=lfs -text
31
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Stable Diffusion Conceptualizer
3
+ emoji: 📖
4
+ colorFrom: gray
5
+ colorTo: green
6
+ sdk: gradio
7
+ sdk_version: 3.4.0
8
+ app_file: app.py
9
+ pinned: false
10
+ license: mit
11
+ duplicated_from: sd-concepts-library/stable-diffusion-conceptualizer
12
+ ---
13
+
14
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
app.py ADDED
@@ -0,0 +1,344 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #@title Prepare the Concepts Library to be used
2
+ import requests
3
+ import os
4
+ import gradio as gr
5
+ import wget
6
+ import torch
7
+ from torch import autocast
8
+ from diffusers import StableDiffusionPipeline
9
+ from huggingface_hub import HfApi
10
+ from transformers import CLIPTextModel, CLIPTokenizer
11
+ import html
12
+
13
+ from share_btn import community_icon_html, loading_icon_html, share_js
14
+
15
+ api = HfApi()
16
+ models_list = api.list_models(author="sd-concepts-library", sort="likes", direction=-1)
17
+ models = []
18
+
19
+ pipe = StableDiffusionPipeline.from_pretrained("CompVis/stable-diffusion-v1-4", use_auth_token=True, revision="fp16", torch_dtype=torch.float16).to("cuda")
20
+
21
+ def load_learned_embed_in_clip(learned_embeds_path, text_encoder, tokenizer, token=None):
22
+ loaded_learned_embeds = torch.load(learned_embeds_path, map_location="cpu")
23
+
24
+ # separate token and the embeds
25
+ trained_token = list(loaded_learned_embeds.keys())[0]
26
+ embeds = loaded_learned_embeds[trained_token]
27
+
28
+ # cast to dtype of text_encoder
29
+ dtype = text_encoder.get_input_embeddings().weight.dtype
30
+
31
+ # add the token in tokenizer
32
+ token = token if token is not None else trained_token
33
+ num_added_tokens = tokenizer.add_tokens(token)
34
+ i = 1
35
+ while(num_added_tokens == 0):
36
+ print(f"The tokenizer already contains the token {token}.")
37
+ token = f"{token[:-1]}-{i}>"
38
+ print(f"Attempting to add the token {token}.")
39
+ num_added_tokens = tokenizer.add_tokens(token)
40
+ i+=1
41
+
42
+ # resize the token embeddings
43
+ text_encoder.resize_token_embeddings(len(tokenizer))
44
+
45
+ # get the id for the token and assign the embeds
46
+ token_id = tokenizer.convert_tokens_to_ids(token)
47
+ text_encoder.get_input_embeddings().weight.data[token_id] = embeds
48
+ return token
49
+
50
+ print("Setting up the public library")
51
+ for model in models_list:
52
+ model_content = {}
53
+ model_id = model.modelId
54
+ model_content["id"] = model_id
55
+ embeds_url = f"https://huggingface.co/{model_id}/resolve/main/learned_embeds.bin"
56
+ os.makedirs(model_id,exist_ok = True)
57
+ if not os.path.exists(f"{model_id}/learned_embeds.bin"):
58
+ try:
59
+ wget.download(embeds_url, out=model_id)
60
+ except:
61
+ continue
62
+ token_identifier = f"https://huggingface.co/{model_id}/raw/main/token_identifier.txt"
63
+ response = requests.get(token_identifier)
64
+ token_name = response.text
65
+
66
+ concept_type = f"https://huggingface.co/{model_id}/raw/main/type_of_concept.txt"
67
+ response = requests.get(concept_type)
68
+ concept_name = response.text
69
+ model_content["concept_type"] = concept_name
70
+ images = []
71
+ for i in range(4):
72
+ url = f"https://huggingface.co/{model_id}/resolve/main/concept_images/{i}.jpeg"
73
+ image_download = requests.get(url)
74
+ url_code = image_download.status_code
75
+ if(url_code == 200):
76
+ file = open(f"{model_id}/{i}.jpeg", "wb") ## Creates the file for image
77
+ file.write(image_download.content) ## Saves file content
78
+ file.close()
79
+ images.append(f"{model_id}/{i}.jpeg")
80
+ model_content["images"] = images
81
+ #if token cannot be loaded, skip it
82
+ try:
83
+ learned_token = load_learned_embed_in_clip(f"{model_id}/learned_embeds.bin", pipe.text_encoder, pipe.tokenizer, token_name)
84
+ except:
85
+ continue
86
+ model_content["token"] = learned_token
87
+ models.append(model_content)
88
+
89
+ #@title Run the app to navigate around [the Library](https://huggingface.co/sd-concepts-library)
90
+ #@markdown Click the `Running on public URL:` result to run the Gradio app
91
+
92
+ SELECT_LABEL = "Select concept"
93
+ def assembleHTML(model):
94
+ html_gallery = ''
95
+ html_gallery = html_gallery+'''
96
+ <div class="flex gr-gap gr-form-gap row gap-4 w-full flex-wrap" id="main_row">
97
+ '''
98
+ cap = 0
99
+ for model in models:
100
+ html_gallery = html_gallery+f'''
101
+ <div class="gr-block gr-box relative w-full overflow-hidden border-solid border border-gray-200 gr-panel">
102
+ <div class="output-markdown gr-prose" style="max-width: 100%;">
103
+ <h3>
104
+ <a href="https://huggingface.co/{model["id"]}" target="_blank">
105
+ <code>{html.escape(model["token"])}</code>
106
+ </a>
107
+ </h3>
108
+ </div>
109
+ <div id="gallery" class="gr-block gr-box relative w-full overflow-hidden border-solid border border-gray-200">
110
+ <div class="wrap svelte-17ttdjv opacity-0"></div>
111
+ <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">
112
+ <span class="mr-2 h-[12px] w-[12px] opacity-80">
113
+ <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">
114
+ <rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect>
115
+ <circle cx="8.5" cy="8.5" r="1.5"></circle>
116
+ <polyline points="21 15 16 10 5 21"></polyline>
117
+ </svg>
118
+ </span> {model["concept_type"]}
119
+ </div>
120
+ <div class="overflow-y-auto h-full p-2" style="position: relative;">
121
+ <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">
122
+ '''
123
+ for image in model["images"]:
124
+ html_gallery = html_gallery + f'''
125
+ <button class="gallery-item svelte-1g9btlg">
126
+ <img alt="" loading="lazy" class="h-full w-full overflow-hidden object-contain" src="file/{image}">
127
+ </button>
128
+ '''
129
+ html_gallery = html_gallery+'''
130
+ </div>
131
+ <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>
132
+ </div>
133
+ </div>
134
+ </div>
135
+ '''
136
+ cap += 1
137
+ if(cap == 99):
138
+ break
139
+ html_gallery = html_gallery+'''
140
+ </div>
141
+ '''
142
+ return html_gallery
143
+
144
+ def title_block(title, id):
145
+ return gr.Markdown(f"### [`{title}`](https://huggingface.co/{id})")
146
+
147
+ def image_block(image_list, concept_type):
148
+ return gr.Gallery(
149
+ label=concept_type, value=image_list, elem_id="gallery"
150
+ ).style(grid=[2], height="auto")
151
+
152
+ def checkbox_block():
153
+ checkbox = gr.Checkbox(label=SELECT_LABEL).style(container=False)
154
+ return checkbox
155
+
156
+ def infer(text):
157
+ #with autocast("cuda"):
158
+ images_list = pipe(
159
+ [text]*2,
160
+ num_inference_steps=50,
161
+ guidance_scale=7.5
162
+ )
163
+ #output_images = []
164
+ #for i, image in enumerate(images_list.images):
165
+ # output_images.append(image)
166
+ return images_list.images, gr.update(visible=True), gr.update(visible=True), gr.update(visible=True)
167
+
168
+ # idetnical to `infer` function without gradio state updates for share btn
169
+ def infer_examples(text):
170
+ #with autocast("cuda"):
171
+ images_list = pipe(
172
+ [text]*2,
173
+ num_inference_steps=50,
174
+ guidance_scale=7.5
175
+ )
176
+ #output_images = []
177
+ #for i, image in enumerate(images_list["sample"]):
178
+ # output_images.append(image)
179
+ return images_list.images
180
+
181
+ css = '''
182
+ .gradio-container {font-family: 'IBM Plex Sans', sans-serif}
183
+ #top_title{margin-bottom: .5em}
184
+ #top_title h2{margin-bottom: 0; text-align: center}
185
+ /*#main_row{flex-wrap: wrap; gap: 1em; max-height: 550px; overflow-y: scroll; flex-direction: row}*/
186
+ #component-3{height: 760px; overflow: auto}
187
+ #component-9{position: sticky;top: 0;align-self: flex-start;}
188
+ @media (min-width: 768px){#main_row > div{flex: 1 1 32%; margin-left: 0 !important}}
189
+ .gr-prose code::before, .gr-prose code::after {content: "" !important}
190
+ ::-webkit-scrollbar {width: 10px}
191
+ ::-webkit-scrollbar-track {background: #f1f1f1}
192
+ ::-webkit-scrollbar-thumb {background: #888}
193
+ ::-webkit-scrollbar-thumb:hover {background: #555}
194
+ .gr-button {white-space: nowrap}
195
+ .gr-button:focus {
196
+ border-color: rgb(147 197 253 / var(--tw-border-opacity));
197
+ outline: none;
198
+ box-shadow: var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow, 0 0 #0000);
199
+ --tw-border-opacity: 1;
200
+ --tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);
201
+ --tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(3px var(--tw-ring-offset-width)) var(--tw-ring-color);
202
+ --tw-ring-color: rgb(191 219 254 / var(--tw-ring-opacity));
203
+ --tw-ring-opacity: .5;
204
+ }
205
+ #prompt_input{flex: 1 3 auto; width: auto !important;}
206
+ #prompt_area{margin-bottom: .75em}
207
+ #prompt_area > div:first-child{flex: 1 3 auto}
208
+ .animate-spin {
209
+ animation: spin 1s linear infinite;
210
+ }
211
+ @keyframes spin {
212
+ from {
213
+ transform: rotate(0deg);
214
+ }
215
+ to {
216
+ transform: rotate(360deg);
217
+ }
218
+ }
219
+ #share-btn-container {
220
+ 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;
221
+ }
222
+ #share-btn {
223
+ 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;
224
+ }
225
+ #share-btn * {
226
+ all: unset;
227
+ }
228
+ '''
229
+ 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"]
230
+
231
+ with gr.Blocks(css=css) as demo:
232
+ state = gr.Variable({
233
+ 'selected': -1
234
+ })
235
+ state = {}
236
+ def update_state(i):
237
+ global checkbox_states
238
+ if(checkbox_states[i]):
239
+ checkbox_states[i] = False
240
+ state[i] = False
241
+ else:
242
+ state[i] = True
243
+ checkbox_states[i] = True
244
+ gr.HTML('''
245
+ <div style="text-align: center; max-width: 720px; margin: 0 auto;">
246
+ <div
247
+ style="
248
+ display: inline-flex;
249
+ align-items: center;
250
+ gap: 0.8rem;
251
+ font-size: 1.75rem;
252
+ "
253
+ >
254
+ <svg
255
+ width="0.65em"
256
+ height="0.65em"
257
+ viewBox="0 0 115 115"
258
+ fill="none"
259
+ xmlns="http://www.w3.org/2000/svg"
260
+ >
261
+ <rect width="23" height="23" fill="white"></rect>
262
+ <rect y="69" width="23" height="23" fill="white"></rect>
263
+ <rect x="23" width="23" height="23" fill="#AEAEAE"></rect>
264
+ <rect x="23" y="69" width="23" height="23" fill="#AEAEAE"></rect>
265
+ <rect x="46" width="23" height="23" fill="white"></rect>
266
+ <rect x="46" y="69" width="23" height="23" fill="white"></rect>
267
+ <rect x="69" width="23" height="23" fill="black"></rect>
268
+ <rect x="69" y="69" width="23" height="23" fill="black"></rect>
269
+ <rect x="92" width="23" height="23" fill="#D9D9D9"></rect>
270
+ <rect x="92" y="69" width="23" height="23" fill="#AEAEAE"></rect>
271
+ <rect x="115" y="46" width="23" height="23" fill="white"></rect>
272
+ <rect x="115" y="115" width="23" height="23" fill="white"></rect>
273
+ <rect x="115" y="69" width="23" height="23" fill="#D9D9D9"></rect>
274
+ <rect x="92" y="46" width="23" height="23" fill="#AEAEAE"></rect>
275
+ <rect x="92" y="115" width="23" height="23" fill="#AEAEAE"></rect>
276
+ <rect x="92" y="69" width="23" height="23" fill="white"></rect>
277
+ <rect x="69" y="46" width="23" height="23" fill="white"></rect>
278
+ <rect x="69" y="115" width="23" height="23" fill="white"></rect>
279
+ <rect x="69" y="69" width="23" height="23" fill="#D9D9D9"></rect>
280
+ <rect x="46" y="46" width="23" height="23" fill="black"></rect>
281
+ <rect x="46" y="115" width="23" height="23" fill="black"></rect>
282
+ <rect x="46" y="69" width="23" height="23" fill="black"></rect>
283
+ <rect x="23" y="46" width="23" height="23" fill="#D9D9D9"></rect>
284
+ <rect x="23" y="115" width="23" height="23" fill="#AEAEAE"></rect>
285
+ <rect x="23" y="69" width="23" height="23" fill="black"></rect>
286
+ </svg>
287
+ <h1 style="font-weight: 900; margin-bottom: 7px;">
288
+ Stable Diffusion Conceptualizer
289
+ </h1>
290
+ </div>
291
+ <p style="margin-bottom: 10px; font-size: 94%">
292
+ Navigate through community created concepts and styles via Stable Diffusion Textual Inversion and pick yours for inference.
293
+ To train your own concepts and contribute to the library <a style="text-decoration: underline" href="https://colab.research.google.com/github/huggingface/notebooks/blob/main/diffusers/sd_textual_inversion_training.ipynb">check out this notebook</a>.
294
+ </p>
295
+ </div>
296
+ ''')
297
+ with gr.Row():
298
+ with gr.Column():
299
+ gr.Markdown(f"### Navigate the top 100 Textual-Inversion community trained concepts. Use 600+ from [The Library](https://huggingface.co/sd-concepts-library)")
300
+ with gr.Row():
301
+ image_blocks = []
302
+ #for i, model in enumerate(models):
303
+ with gr.Box().style(border=None):
304
+ gr.HTML(assembleHTML(models))
305
+ #title_block(model["token"], model["id"])
306
+ #image_blocks.append(image_block(model["images"], model["concept_type"]))
307
+ with gr.Column():
308
+ with gr.Box():
309
+ with gr.Row(elem_id="prompt_area").style(mobile_collapse=False, equal_height=True):
310
+ text = gr.Textbox(
311
+ label="Enter your prompt", placeholder="Enter your prompt", show_label=False, max_lines=1, elem_id="prompt_input"
312
+ ).style(
313
+ border=(True, False, True, True),
314
+ rounded=(True, False, False, True),
315
+ container=False,
316
+ )
317
+ btn = gr.Button("Run",elem_id="run_btn").style(
318
+ margin=False,
319
+ rounded=(False, True, True, False),
320
+ )
321
+ with gr.Row().style():
322
+ infer_outputs = gr.Gallery(show_label=False, elem_id="generated-gallery").style(grid=[2], height="512px")
323
+ with gr.Row():
324
+ gr.HTML("<p style=\"font-size: 95%;margin-top: .75em\">Prompting may not work as you are used to. <code>objects</code> may need the concept added at the end, <code>styles</code> may work better at the beginning. You can navigate on <a href='https://lexica.art'>lexica.art</a> to get inspired on prompts</p>")
325
+ with gr.Row():
326
+ gr.Examples(examples=examples, fn=infer_examples, inputs=[text], outputs=infer_outputs, cache_examples=True)
327
+ with gr.Group(elem_id="share-btn-container"):
328
+ community_icon = gr.HTML(community_icon_html, visible=False)
329
+ loading_icon = gr.HTML(loading_icon_html, visible=False)
330
+ share_button = gr.Button("Share to community", elem_id="share-btn", visible=False)
331
+ checkbox_states = {}
332
+ inputs = [text]
333
+ btn.click(
334
+ infer,
335
+ inputs=inputs,
336
+ outputs=[infer_outputs, community_icon, loading_icon, share_button]
337
+ )
338
+ share_button.click(
339
+ None,
340
+ [],
341
+ [],
342
+ _js=share_js,
343
+ )
344
+ demo.queue(max_size=20).launch()
requirements.txt ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ diffusers
2
+ transformers
3
+ accelerate
4
+ nvidia-ml-py3
5
+ ftfy
6
+ wget
7
+ huggingface_hub
8
+ --extra-index-url https://download.pytorch.org/whl/cu113
9
+ torch
share_btn.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 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">
2
+ <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>
3
+ <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>
4
+ </svg>"""
5
+
6
+ loading_icon_html = """<svg id="share-btn-loading-icon" style="display:none;" class="animate-spin"
7
+ style="color: #ffffff;
8
+ "
9
+ 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>"""
10
+
11
+ share_js = """async () => {
12
+ async function uploadFile(file){
13
+ const UPLOAD_URL = 'https://huggingface.co/uploads';
14
+ const response = await fetch(UPLOAD_URL, {
15
+ method: 'POST',
16
+ headers: {
17
+ 'Content-Type': file.type,
18
+ 'X-Requested-With': 'XMLHttpRequest',
19
+ },
20
+ body: file, /// <- File inherits from Blob
21
+ });
22
+ const url = await response.text();
23
+ return url;
24
+ }
25
+
26
+ const gradioEl = document.querySelector('body > gradio-app');
27
+ const imgEls = gradioEl.querySelectorAll('#generated-gallery img');
28
+ const promptTxt = gradioEl.querySelector('#prompt_input input').value;
29
+ const shareBtnEl = gradioEl.querySelector('#share-btn');
30
+ const shareIconEl = gradioEl.querySelector('#share-btn-share-icon');
31
+ const loadingIconEl = gradioEl.querySelector('#share-btn-loading-icon');
32
+
33
+ if(!imgEls.length){
34
+ return;
35
+ };
36
+
37
+ shareBtnEl.style.pointerEvents = 'none';
38
+ shareIconEl.style.display = 'none';
39
+ loadingIconEl.style.removeProperty('display');
40
+
41
+ const files = await Promise.all(
42
+ [...imgEls].map(async (imgEl) => {
43
+ const res = await fetch(imgEl.src);
44
+ const blob = await res.blob();
45
+ const imgId = Date.now() % 200;
46
+ const fileName = `diffuse-the-rest-${{imgId}}.png`;
47
+ return new File([blob], fileName, { type: 'image/png' });
48
+ })
49
+ );
50
+
51
+ const REGEX_CONCEPT = /<(((?!<.+>).)+)>/gm;
52
+ const matches = [...promptTxt.matchAll(REGEX_CONCEPT)];
53
+ const concepts = matches.map(m => m[1]);
54
+ const conceptLibraryMd = concepts.map(c => `<a href='https://huggingface.co/sd-concepts-library/${c}' target='_blank'>${c}</a>`).join(`, `);
55
+
56
+ const urls = await Promise.all(files.map((f) => uploadFile(f)));
57
+ const htmlImgs = urls.map(url => `<img src='${url}' width='400' height='400'>`);
58
+ const htmlImgsMd = htmlImgs.join(`\n`);
59
+
60
+ const descriptionMd = `#### Prompt:
61
+ ${promptTxt.replace(/</g, '\\\<').replace(/>/g, '\\\>')}
62
+
63
+ #### Concepts Used:
64
+ ${conceptLibraryMd}
65
+
66
+ #### Generations:
67
+ <div style='display: flex; flex-wrap: wrap; column-gap: 0.75rem;'>
68
+ ${htmlImgsMd}
69
+ </div>`;
70
+
71
+ const params = new URLSearchParams({
72
+ title: promptTxt,
73
+ description: descriptionMd,
74
+ });
75
+
76
+ const paramsStr = params.toString();
77
+ window.open(`https://huggingface.co/spaces/sd-concepts-library/stable-diffusion-conceptualizer/discussions/new?${paramsStr}`, '_blank');
78
+
79
+ shareBtnEl.style.removeProperty('pointer-events');
80
+ shareIconEl.style.removeProperty('display');
81
+ loadingIconEl.style.display = 'none';
82
+ }"""