alvdansen commited on
Commit
85b3dcf
Β·
verified Β·
1 Parent(s): 6d9c61b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +66 -190
app.py CHANGED
@@ -1,5 +1,8 @@
1
  import json
2
  import random
 
 
 
3
 
4
  import gradio as gr
5
  import numpy as np
@@ -7,11 +10,45 @@ import spaces
7
  import torch
8
  from diffusers import DiffusionPipeline, LCMScheduler
9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
  with open("sdxl_lora.json", "r") as file:
11
  data = json.load(file)
12
  sdxl_loras_raw = [
13
  {
14
- "image": item["image"],
15
  "title": item["title"],
16
  "repo": item["repo"],
17
  "trigger_word": item["trigger_word"],
@@ -23,7 +60,6 @@ with open("sdxl_lora.json", "r") as file:
23
  for item in data
24
  ]
25
 
26
- # Sort the loras by likes
27
  sdxl_loras_raw = sorted(sdxl_loras_raw, key=lambda x: x["likes"], reverse=True)
28
 
29
  DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
@@ -55,202 +91,42 @@ def infer(
55
  user_lora_weight,
56
  progress=gr.Progress(track_tqdm=True),
57
  ):
58
- flash_sdxl_id = "jasperai/flash-sdxl"
59
-
60
- new_adapter_id = user_lora_selector.replace("/", "_")
61
- loaded_adapters = pipe.get_list_adapters()
62
-
63
- if new_adapter_id not in loaded_adapters["unet"]:
64
- gr.Info("Loading new LoRA")
65
- pipe.unload_lora_weights()
66
- pipe.load_lora_weights(flash_sdxl_id, adapter_name="flash_lora")
67
- pipe.load_lora_weights(user_lora_selector, adapter_name=new_adapter_id)
68
-
69
- pipe.set_adapters(["flash_lora", new_adapter_id], adapter_weights=[1.0, user_lora_weight])
70
- gr.Info("LoRA setup complete")
71
-
72
- if randomize_seed:
73
- seed = random.randint(0, MAX_SEED)
74
-
75
- generator = torch.Generator().manual_seed(seed)
76
-
77
- if pre_prompt != "":
78
- prompt = f"{pre_prompt} {prompt}"
79
-
80
- image = pipe(
81
- prompt=prompt,
82
- negative_prompt=negative_prompt,
83
- guidance_scale=guidance_scale,
84
- num_inference_steps=num_inference_steps,
85
- generator=generator,
86
- ).images[0]
87
-
88
- return image
89
-
90
- css = """
91
- h1 {
92
- text-align: center;
93
- display:block;
94
- }
95
- p {
96
- text-align: justify;
97
- display:block;
98
- }
99
- """
100
-
101
- if torch.cuda.is_available():
102
- power_device = "GPU"
103
- else:
104
- power_device = "CPU"
105
-
106
- with gr.Blocks(css=css) as demo:
107
- gr.Markdown(
108
- f"""
109
- # ⚑ FlashDiffusion: FlashLoRA ⚑
110
- This is an interactive demo of [Flash Diffusion](https://gojasper.github.io/flash-diffusion-project/) **on top of** existing LoRAs.
111
-
112
- The distillation method proposed in [Flash Diffusion: Accelerating Any Conditional Diffusion Model for Few Steps Image Generation](http://arxiv.org/abs/2406.02347) *by ClΓ©ment Chadebec, Onur Tasar, Eyal Benaroche and Benjamin Aubin* from Jasper Research.
113
- The LoRAs can be added **without** any retraining for similar results in most cases. Feel free to tweak the parameters and use your own LoRAs by giving a look at the [Github Repo](https://github.com/gojasper/flash-diffusion)
114
- """
115
- )
116
- gr.Markdown(
117
- "If you enjoy the space, please also promote *open-source* by giving a ⭐ to our repo [![GitHub Stars](https://img.shields.io/github/stars/gojasper/flash-diffusion?style=social)](https://github.com/gojasper/flash-diffusion)"
118
- )
119
-
120
- gr_sdxl_loras = gr.State(value=sdxl_loras_raw)
121
- gr_lora_id = gr.State(value="")
122
-
123
- with gr.Row():
124
- with gr.Blocks():
125
- with gr.Column():
126
- user_lora_selector = gr.Textbox(
127
- label="Current Selected LoRA",
128
- max_lines=1,
129
- interactive=False,
130
- )
131
-
132
- user_lora_weight = gr.Slider(
133
- label="Selected LoRA Weight",
134
- minimum=0.5,
135
- maximum=3,
136
- step=0.1,
137
- value=1,
138
- )
139
-
140
- gallery = gr.Gallery(
141
- value=[(item["image"], item["title"]) for item in sdxl_loras_raw],
142
- label="SDXL LoRA Gallery",
143
- allow_preview=False,
144
- columns=3,
145
- elem_id="gallery",
146
- show_share_button=False,
147
- )
148
-
149
- with gr.Column():
150
- with gr.Row():
151
- prompt = gr.Text(
152
- label="Prompt",
153
- show_label=False,
154
- max_lines=1,
155
- placeholder="Enter your prompt",
156
- container=False,
157
- scale=5,
158
- )
159
-
160
- run_button = gr.Button("Run", scale=1)
161
-
162
- result = gr.Image(label="Result", show_label=False)
163
-
164
- with gr.Accordion("Advanced Settings", open=False):
165
- pre_prompt = gr.Text(
166
- label="Pre-Prompt",
167
- show_label=True,
168
- max_lines=1,
169
- placeholder="Pre Prompt from the LoRA config",
170
- container=True,
171
- scale=5,
172
- )
173
 
174
- seed = gr.Slider(
175
- label="Seed",
176
- minimum=0,
177
- maximum=MAX_SEED,
178
- step=1,
179
- value=0,
180
- )
181
 
182
- randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
 
 
 
 
183
 
184
- with gr.Row():
185
- num_inference_steps = gr.Slider(
186
- label="Number of inference steps",
187
- minimum=4,
188
- maximum=8,
189
- step=1,
190
- value=4,
191
- )
192
 
193
- with gr.Row():
194
- guidance_scale = gr.Slider(
195
- label="Guidance Scale",
196
- minimum=1,
197
- maximum=6,
198
- step=0.5,
199
- value=1,
200
- )
201
 
202
- hint_negative = gr.Markdown(
203
- """πŸ’‘ _Hint : Negative Prompt will only work with Guidance > 1 but the model was
204
- trained to be used with guidance = 1 (ie. without guidance).
205
- Can degrade the results, use cautiously._"""
206
- )
207
 
208
- negative_prompt = gr.Text(
209
- label="Negative Prompt",
210
- show_label=False,
211
- max_lines=1,
212
- placeholder="Enter a negative Prompt",
213
- container=False,
214
- )
215
 
216
- gr.on(
217
- [
218
- run_button.click,
219
- seed.change,
220
- randomize_seed.change,
221
- prompt.submit,
222
- negative_prompt.change,
223
- negative_prompt.submit,
224
- guidance_scale.change,
225
- ],
226
- fn=infer,
227
- inputs=[
228
- pre_prompt,
229
- prompt,
230
- seed,
231
- randomize_seed,
232
- num_inference_steps,
233
- negative_prompt,
234
- guidance_scale,
235
- user_lora_selector,
236
- user_lora_weight,
237
- ],
238
- outputs=[result],
239
- )
240
 
241
- gallery.select(
242
- fn=update_selection,
243
- inputs=[gr_sdxl_loras],
244
- outputs=[
245
- user_lora_selector,
246
- pre_prompt,
247
- ],
248
- show_progress="hidden",
249
- )
250
 
251
- gr.Markdown("**Disclaimer:**")
252
- gr.Markdown(
253
- "This demo is only for research purpose. Users are solely responsible for any content they create, and it is their obligation to ensure that it adheres to appropriate and ethical standards."
254
- )
255
 
256
  demo.queue().launch()
 
1
  import json
2
  import random
3
+ import requests
4
+ import os
5
+ from PIL import Image
6
 
7
  import gradio as gr
8
  import numpy as np
 
10
  import torch
11
  from diffusers import DiffusionPipeline, LCMScheduler
12
 
13
+ def get_image(image_data):
14
+ if isinstance(image_data, str):
15
+ return image_data
16
+
17
+ if isinstance(image_data, dict):
18
+ local_path = image_data.get('local_path')
19
+ hf_url = image_data.get('hf_url')
20
+ else:
21
+ print(f"Unexpected image_data format: {type(image_data)}")
22
+ return None
23
+
24
+ if local_path and os.path.exists(local_path):
25
+ try:
26
+ Image.open(local_path).verify()
27
+ return local_path
28
+ except Exception as e:
29
+ print(f"Error loading local image {local_path}: {e}")
30
+
31
+ if hf_url:
32
+ try:
33
+ response = requests.get(hf_url)
34
+ if response.status_code == 200:
35
+ img = Image.open(requests.get(hf_url, stream=True).raw)
36
+ img.verify()
37
+ img.save(local_path)
38
+ return local_path
39
+ else:
40
+ print(f"Failed to fetch image from URL {hf_url}. Status code: {response.status_code}")
41
+ except Exception as e:
42
+ print(f"Error loading image from URL {hf_url}: {e}")
43
+
44
+ print(f"Failed to load image for {image_data}")
45
+ return None
46
+
47
  with open("sdxl_lora.json", "r") as file:
48
  data = json.load(file)
49
  sdxl_loras_raw = [
50
  {
51
+ "image": get_image(item["image"]),
52
  "title": item["title"],
53
  "repo": item["repo"],
54
  "trigger_word": item["trigger_word"],
 
60
  for item in data
61
  ]
62
 
 
63
  sdxl_loras_raw = sorted(sdxl_loras_raw, key=lambda x: x["likes"], reverse=True)
64
 
65
  DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
 
91
  user_lora_weight,
92
  progress=gr.Progress(track_tqdm=True),
93
  ):
94
+ try:
95
+ flash_sdxl_id = "jasperai/flash-sdxl"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96
 
97
+ new_adapter_id = user_lora_selector.replace("/", "_")
98
+ loaded_adapters = pipe.get_list_adapters()
 
 
 
 
 
99
 
100
+ if "flash_lora" not in loaded_adapters["unet"] or new_adapter_id not in loaded_adapters["unet"]:
101
+ gr.Info("Loading LoRAs")
102
+ pipe.unload_lora_weights()
103
+ pipe.load_lora_weights(flash_sdxl_id, adapter_name="flash_lora")
104
+ pipe.load_lora_weights(user_lora_selector, adapter_name=new_adapter_id)
105
 
106
+ pipe.set_adapters(["flash_lora", new_adapter_id], adapter_weights=[1.0, user_lora_weight])
107
+ gr.Info("LoRA setup complete")
 
 
 
 
 
 
108
 
109
+ if randomize_seed:
110
+ seed = random.randint(0, MAX_SEED)
 
 
 
 
 
 
111
 
112
+ generator = torch.Generator().manual_seed(seed)
 
 
 
 
113
 
114
+ if pre_prompt != "":
115
+ prompt = f"{pre_prompt} {prompt}"
 
 
 
 
 
116
 
117
+ image = pipe(
118
+ prompt=prompt,
119
+ negative_prompt=negative_prompt,
120
+ guidance_scale=guidance_scale,
121
+ num_inference_steps=num_inference_steps,
122
+ generator=generator,
123
+ ).images[0]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
124
 
125
+ return image
126
+ except Exception as e:
127
+ gr.Error(f"An error occurred: {str(e)}")
128
+ return None
 
 
 
 
 
129
 
130
+ # ... (rest of the Gradio interface code remains the same)
 
 
 
131
 
132
  demo.queue().launch()