multimodalart HF staff commited on
Commit
7389e23
1 Parent(s): 2804630

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +53 -27
app.py CHANGED
@@ -6,14 +6,13 @@ from safetensors.torch import load_file
6
  from share_btn import community_icon_html, loading_icon_html, share_js
7
  from cog_sdxl_dataset_and_utils import TokenEmbeddingsHandler
8
  import lora
9
- from time import sleep
10
  import copy
11
  import json
12
  import gc
13
-
14
  with open("sdxl_loras.json", "r") as file:
15
  data = json.load(file)
16
- sdxl_loras = [
17
  {
18
  "image": item["image"],
19
  "title": item["title"],
@@ -23,6 +22,8 @@ with open("sdxl_loras.json", "r") as file:
23
  "is_compatible": item["is_compatible"],
24
  "is_pivotal": item.get("is_pivotal", False),
25
  "text_embedding_weights": item.get("text_embedding_weights", None),
 
 
26
  "is_nc": item.get("is_nc", False)
27
  }
28
  for item in data
@@ -30,16 +31,20 @@ with open("sdxl_loras.json", "r") as file:
30
 
31
  device = "cuda"
32
 
33
- for item in sdxl_loras:
 
 
34
  saved_name = hf_hub_download(item["repo"], item["weights"])
35
 
36
  if not saved_name.endswith('.safetensors'):
37
  state_dict = torch.load(saved_name)
38
  else:
39
  state_dict = load_file(saved_name)
40
-
41
- item["saved_name"] = saved_name
42
- item["state_dict"] = state_dict #{k: v.to(device=device, dtype=torch.float16) for k, v in state_dict.items() if torch.is_tensor(v)}
 
 
43
 
44
  vae = AutoencoderKL.from_pretrained(
45
  "madebyollin/sdxl-vae-fp16-fix", torch_dtype=torch.float16
@@ -55,7 +60,7 @@ pipe.to(device)
55
  last_lora = ""
56
  last_merged = False
57
  last_fused = False
58
- def update_selection(selected_state: gr.SelectData):
59
  lora_repo = sdxl_loras[selected_state.index]["repo"]
60
  instance_prompt = sdxl_loras[selected_state.index]["trigger_word"]
61
  new_placeholder = "Type a prompt. This LoRA applies for all prompts, no need for a trigger word" if instance_prompt == "" else "Type a prompt to use your selected LoRA"
@@ -135,7 +140,7 @@ def merge_incompatible_lora(full_path_lora, lora_scale):
135
  del lora_model
136
  gc.collect()
137
 
138
- def run_lora(prompt, negative, lora_scale, selected_state, progress=gr.Progress(track_tqdm=True)):
139
  global last_lora, last_merged, last_fused, pipe
140
 
141
  if negative == "":
@@ -145,8 +150,9 @@ def run_lora(prompt, negative, lora_scale, selected_state, progress=gr.Progress(
145
  raise gr.Error("You must select a LoRA")
146
  repo_name = sdxl_loras[selected_state.index]["repo"]
147
  weight_name = sdxl_loras[selected_state.index]["weights"]
148
- full_path_lora = sdxl_loras[selected_state.index]["saved_name"]
149
- loaded_state_dict = sdxl_loras[selected_state.index]["state_dict"]
 
150
  cross_attention_kwargs = None
151
  if last_lora != repo_name:
152
  if last_merged:
@@ -186,8 +192,8 @@ def run_lora(prompt, negative, lora_scale, selected_state, progress=gr.Progress(
186
  image = pipe(
187
  prompt=prompt,
188
  negative_prompt=negative,
189
- width=768,
190
- height=768,
191
  num_inference_steps=20,
192
  guidance_scale=7.5,
193
  ).images[0]
@@ -195,22 +201,36 @@ def run_lora(prompt, negative, lora_scale, selected_state, progress=gr.Progress(
195
  gc.collect()
196
  return image, gr.update(visible=True)
197
 
 
 
 
 
 
 
 
 
 
 
 
198
 
199
  with gr.Blocks(css="custom.css") as demo:
 
200
  title = gr.HTML(
201
  """<h1><img src="https://i.imgur.com/vT48NAO.png" alt="LoRA"> LoRA the Explorer</h1>""",
202
  elem_id="title",
203
  )
204
  selected_state = gr.State()
205
  with gr.Row():
206
- gallery = gr.Gallery(
207
- value=[(item["image"], item["title"]) for item in sdxl_loras],
208
- label="SDXL LoRA Gallery",
209
- allow_preview=False,
210
- columns=3,
211
- elem_id="gallery",
212
- show_share_button=False
213
- )
 
 
214
  with gr.Column():
215
  prompt_title = gr.Markdown(
216
  value="### Click on a LoRA in the gallery to select it",
@@ -268,12 +288,18 @@ with gr.Blocks(css="custom.css") as demo:
268
  submit_disclaimer = gr.Markdown(
269
  "This is a curated gallery by me, [apolinário (multimodal.art)](https://twitter.com/multimodalart). I'll try to include as many cool LoRAs as they are submitted! You can [duplicate this Space](https://huggingface.co/spaces/multimodalart/LoraTheExplorer?duplicate=true) to use it privately, and add your own LoRAs by editing `sdxl_loras.json` in the Files tab of your private space."
270
  )
271
-
 
 
 
 
 
272
  gallery.select(
273
- update_selection,
 
274
  outputs=[prompt_title, prompt, prompt, selected_state, use_diffusers, use_uis],
275
  queue=False,
276
- show_progress=False,
277
  )
278
  prompt.submit(
279
  fn=check_selected,
@@ -282,7 +308,7 @@ with gr.Blocks(css="custom.css") as demo:
282
  show_progress=False
283
  ).success(
284
  fn=run_lora,
285
- inputs=[prompt, negative, weight, selected_state],
286
  outputs=[result, share_group],
287
  )
288
  button.click(
@@ -292,10 +318,10 @@ with gr.Blocks(css="custom.css") as demo:
292
  show_progress=False
293
  ).success(
294
  fn=run_lora,
295
- inputs=[prompt, negative, weight, selected_state],
296
  outputs=[result, share_group],
297
  )
298
  share_button.click(None, [], [], _js=share_js)
299
-
300
  demo.queue(max_size=20)
301
  demo.launch()
 
6
  from share_btn import community_icon_html, loading_icon_html, share_js
7
  from cog_sdxl_dataset_and_utils import TokenEmbeddingsHandler
8
  import lora
 
9
  import copy
10
  import json
11
  import gc
12
+ import random
13
  with open("sdxl_loras.json", "r") as file:
14
  data = json.load(file)
15
+ sdxl_loras_raw = [
16
  {
17
  "image": item["image"],
18
  "title": item["title"],
 
22
  "is_compatible": item["is_compatible"],
23
  "is_pivotal": item.get("is_pivotal", False),
24
  "text_embedding_weights": item.get("text_embedding_weights", None),
25
+ "likes": item.get("likes", 0),
26
+ "downloads": item.get("downloads", 0),
27
  "is_nc": item.get("is_nc", False)
28
  }
29
  for item in data
 
31
 
32
  device = "cuda"
33
 
34
+ state_dicts = {}
35
+
36
+ for item in sdxl_loras_raw:
37
  saved_name = hf_hub_download(item["repo"], item["weights"])
38
 
39
  if not saved_name.endswith('.safetensors'):
40
  state_dict = torch.load(saved_name)
41
  else:
42
  state_dict = load_file(saved_name)
43
+
44
+ state_dicts[item["repo"]] = {
45
+ "saved_name": saved_name,
46
+ "state_dict": state_dict
47
+ }
48
 
49
  vae = AutoencoderKL.from_pretrained(
50
  "madebyollin/sdxl-vae-fp16-fix", torch_dtype=torch.float16
 
60
  last_lora = ""
61
  last_merged = False
62
  last_fused = False
63
+ def update_selection(selected_state: gr.SelectData, sdxl_loras):
64
  lora_repo = sdxl_loras[selected_state.index]["repo"]
65
  instance_prompt = sdxl_loras[selected_state.index]["trigger_word"]
66
  new_placeholder = "Type a prompt. This LoRA applies for all prompts, no need for a trigger word" if instance_prompt == "" else "Type a prompt to use your selected LoRA"
 
140
  del lora_model
141
  gc.collect()
142
 
143
+ def run_lora(prompt, negative, lora_scale, selected_state, sdxl_loras, progress=gr.Progress(track_tqdm=True)):
144
  global last_lora, last_merged, last_fused, pipe
145
 
146
  if negative == "":
 
150
  raise gr.Error("You must select a LoRA")
151
  repo_name = sdxl_loras[selected_state.index]["repo"]
152
  weight_name = sdxl_loras[selected_state.index]["weights"]
153
+
154
+ full_path_lora = state_dicts[repo_name]["saved_name"]
155
+ loaded_state_dict = state_dicts[repo_name]["state_dict"]
156
  cross_attention_kwargs = None
157
  if last_lora != repo_name:
158
  if last_merged:
 
192
  image = pipe(
193
  prompt=prompt,
194
  negative_prompt=negative,
195
+ width=1024,
196
+ height=1024,
197
  num_inference_steps=20,
198
  guidance_scale=7.5,
199
  ).images[0]
 
201
  gc.collect()
202
  return image, gr.update(visible=True)
203
 
204
+ def shuffle_gallery(sdxl_loras):
205
+ random.shuffle(sdxl_loras)
206
+ return [(item["image"], item["title"]) for item in sdxl_loras], sdxl_loras
207
+
208
+ def swap_gallery(order, sdxl_loras):
209
+ if(order == "random"):
210
+ return shuffle_gallery(sdxl_loras)
211
+ else:
212
+ sorted_gallery = sorted(sdxl_loras, key=lambda x: x.get(order, 0), reverse=True)
213
+ return [(item["image"], item["title"]) for item in sorted_gallery], sorted_gallery
214
+
215
 
216
  with gr.Blocks(css="custom.css") as demo:
217
+ gr_sdxl_loras = gr.State(value=sdxl_loras_raw)
218
  title = gr.HTML(
219
  """<h1><img src="https://i.imgur.com/vT48NAO.png" alt="LoRA"> LoRA the Explorer</h1>""",
220
  elem_id="title",
221
  )
222
  selected_state = gr.State()
223
  with gr.Row():
224
+ with gr.Box(elem_id="gallery_box"):
225
+ order_gallery = gr.Radio(choices=["random", "likes"], value="random", label="Order by", elem_id="order_radio")
226
+ gallery = gr.Gallery(
227
+ #value=[(item["image"], item["title"]) for item in sdxl_loras],
228
+ label="SDXL LoRA Gallery",
229
+ allow_preview=False,
230
+ columns=3,
231
+ elem_id="gallery",
232
+ show_share_button=False
233
+ )
234
  with gr.Column():
235
  prompt_title = gr.Markdown(
236
  value="### Click on a LoRA in the gallery to select it",
 
288
  submit_disclaimer = gr.Markdown(
289
  "This is a curated gallery by me, [apolinário (multimodal.art)](https://twitter.com/multimodalart). I'll try to include as many cool LoRAs as they are submitted! You can [duplicate this Space](https://huggingface.co/spaces/multimodalart/LoraTheExplorer?duplicate=true) to use it privately, and add your own LoRAs by editing `sdxl_loras.json` in the Files tab of your private space."
290
  )
291
+ order_gallery.change(
292
+ fn=swap_gallery,
293
+ inputs=[order_gallery, gr_sdxl_loras],
294
+ outputs=[gallery, gr_sdxl_loras],
295
+ queue=False
296
+ )
297
  gallery.select(
298
+ fn=update_selection,
299
+ inputs=[gr_sdxl_loras],
300
  outputs=[prompt_title, prompt, prompt, selected_state, use_diffusers, use_uis],
301
  queue=False,
302
+ show_progress=False
303
  )
304
  prompt.submit(
305
  fn=check_selected,
 
308
  show_progress=False
309
  ).success(
310
  fn=run_lora,
311
+ inputs=[prompt, negative, weight, selected_state, gr_sdxl_loras],
312
  outputs=[result, share_group],
313
  )
314
  button.click(
 
318
  show_progress=False
319
  ).success(
320
  fn=run_lora,
321
+ inputs=[prompt, negative, weight, selected_state, gr_sdxl_loras],
322
  outputs=[result, share_group],
323
  )
324
  share_button.click(None, [], [], _js=share_js)
325
+ demo.load(fn=shuffle_gallery, inputs=[gr_sdxl_loras], outputs=[gallery, gr_sdxl_loras], queue=False)
326
  demo.queue(max_size=20)
327
  demo.launch()