multimodalart HF staff commited on
Commit
9d731d3
1 Parent(s): 2d475e1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +8 -153
app.py CHANGED
@@ -7,17 +7,9 @@ import numpy as np
7
  import cv2
8
  from PIL import Image
9
  from diffusers.utils import load_image
10
- from diffusers.pipelines.flux.pipeline_flux_controlnet import FluxControlNetPipeline
11
- from diffusers.models.controlnet_flux import FluxControlNetModel
12
  from diffusers.utils import export_to_gif
13
  import random
14
 
15
- def process_controlnet_img(image):
16
- controlnet_img = np.array(image)
17
- controlnet_img = cv2.Canny(controlnet_img, 100, 200)
18
- controlnet_img = HWC3(controlnet_img)
19
- controlnet_img = Image.fromarray(controlnet_img)
20
-
21
  # load pipelines
22
  base_model = "black-forest-labs/FLUX.1-schnell"
23
 
@@ -32,11 +24,6 @@ pipe.transformer.to(memory_format=torch.channels_last)
32
  clip_slider = CLIPSliderFlux(pipe, device=torch.device("cuda"))
33
 
34
 
35
- # controlnet_model = 'InstantX/FLUX.1-dev-Controlnet-Canny-alpha'
36
- # controlnet = FluxControlNetModel.from_pretrained(controlnet_model, torch_dtype=torch.bfloat16)
37
- # pipe_controlnet = FluxControlNetPipeline.from_pretrained(base_model, controlnet=controlnet, torch_dtype=torch.bfloat16)
38
- # t5_slider_controlnet = T5SliderFlux(sd_pipe=pipe_controlnet,device=torch.device("cuda"))
39
-
40
  MAX_SEED = 2**32-1
41
 
42
  def convert_to_centered_scale(num):
@@ -56,8 +43,6 @@ def convert_to_centered_scale(num):
56
  def generate(concept_1, concept_2, scale, prompt, randomize_seed=True, seed=42, recalc_directions=True, iterations=200, steps=4, interm_steps=9, guidance_scale=3.5,
57
  x_concept_1="", x_concept_2="",
58
  avg_diff_x=None,
59
- img2img_type = None, img = None,
60
- controlnet_scale= None, ip_adapter_scale=None,
61
  total_images=[],
62
  progress=gr.Progress(track_tqdm=True)
63
  ):
@@ -65,12 +50,10 @@ def generate(concept_1, concept_2, scale, prompt, randomize_seed=True, seed=42,
65
  # check if avg diff for directions need to be re-calculated
66
  print("slider_x", slider_x)
67
  print("x_concept_1", x_concept_1, "x_concept_2", x_concept_2)
68
- #torch.manual_seed(seed)
69
  if randomize_seed:
70
  seed = random.randint(0, MAX_SEED)
71
 
72
  if not sorted(slider_x) == sorted([x_concept_1, x_concept_2]) or recalc_directions:
73
- #avg_diff = clip_slider.find_latent_direction(slider_x[0], slider_x[1], num_iterations=iterations).to(torch.float16)
74
  avg_diff = clip_slider.find_latent_direction(slider_x[0], slider_x[1], num_iterations=iterations)
75
  x_concept_1, x_concept_2 = slider_x[0], slider_x[1]
76
 
@@ -82,7 +65,7 @@ def generate(concept_1, concept_2, scale, prompt, randomize_seed=True, seed=42,
82
  image = clip_slider.generate(prompt,
83
  width=768,
84
  height=768,
85
- #guidance_scale=guidance_scale,
86
  scale=cur_scale, seed=seed, num_inference_steps=steps, avg_diff=avg_diff)
87
  images.append(image)
88
  canvas = Image.new('RGB', (256*interm_steps, 256))
@@ -100,46 +83,6 @@ def generate(concept_1, concept_2, scale, prompt, randomize_seed=True, seed=42,
100
 
101
  return x_concept_1,x_concept_2, avg_diff_x, export_to_gif(images, "clip.gif", fps=5), canvas, images, images[scale_middle], post_generation_slider_update, seed
102
 
103
- @spaces.GPU
104
- def update_scales(x,prompt,seed, steps, interm_steps, guidance_scale,
105
- avg_diff_x,
106
- img2img_type = None, img = None,
107
- controlnet_scale= None, ip_adapter_scale=None, total_images=[], progress=gr.Progress(track_tqdm=True)):
108
- print("Hola", x)
109
- avg_diff = avg_diff_x.cuda()
110
-
111
- # for spectrum generation
112
- images = []
113
-
114
- high_scale = x
115
- low_scale = -1 * x
116
-
117
- if img2img_type=="controlnet canny" and img is not None:
118
- control_img = process_controlnet_img(img)
119
- image = t5_slider_controlnet.generate(prompt, guidance_scale=guidance_scale, image=control_img, controlnet_conditioning_scale =controlnet_scale, scale=x, seed=seed, num_inference_steps=steps, avg_diff=avg_diff)
120
- elif img2img_type=="ip adapter" and img is not None:
121
- image = clip_slider.generate(prompt, guidance_scale=guidance_scale, ip_adapter_image=img, scale=x,seed=seed, num_inference_steps=steps, avg_diff=avg_diff)
122
- else:
123
- for i in range(interm_steps):
124
- cur_scale = low_scale + (high_scale - low_scale) * i / (steps - 1)
125
- image = clip_slider.generate(prompt,
126
- width=768,
127
- height=768,
128
- #guidance_scale=guidance_scale,
129
- scale=cur_scale, seed=seed, num_inference_steps=steps, avg_diff=avg_diff)
130
- images.append(image)
131
- canvas = Image.new('RGB', (256*interm_steps, 256))
132
- for i, im in enumerate(images):
133
- canvas.paste(im.resize((256,256)), (256 * i, 0))
134
-
135
- scale_total = convert_to_centered_scale(interm_steps)
136
- scale_min = scale_total[0]
137
- scale_max = scale_total[-1]
138
- scale_middle = scale_total.index(0)
139
- post_generation_slider_update = gr.update(minimum=scale_min, maximum=scale_max, visible=True)
140
-
141
- return export_to_gif(images, "clip.gif", fps=5), canvas, images, images[scale_middle], post_generation_slider_update
142
-
143
  def update_pre_generated_images(slider_value, total_images):
144
  number_images = len(total_images)
145
  if(number_images > 0):
@@ -151,39 +94,11 @@ def update_pre_generated_images(slider_value, total_images):
151
  def reset_recalc_directions():
152
  return True
153
 
154
- css_old = '''
155
- #group {
156
- position: relative;
157
- width: 600px; /* Increased width */
158
- height: 600px; /* Increased height */
159
- margin-bottom: 20px;
160
- background-color: white;
161
- }
162
- #x {
163
- position: absolute;
164
- bottom: 20px; /* Moved further down */
165
- left: 30px; /* Adjusted left margin */
166
- width: 540px; /* Increased width to match the new container size */
167
- }
168
- #y {
169
- position: absolute;
170
- bottom: 200px; /* Increased bottom margin to ensure proper spacing from #x */
171
- left: 20px; /* Adjusted left margin */
172
- width: 540px; /* Increased width to match the new container size */
173
- transform: rotate(-90deg);
174
- transform-origin: left bottom;
175
- }
176
- #image_out {
177
- position: absolute;
178
- width: 80%; /* Adjust width as needed */
179
- right: 10px;
180
- top: 10px; /* Increased top margin to clear space occupied by #x */
181
- }
182
- '''
183
  intro = """
184
  <div style="display: flex;align-items: center;justify-content: center">
185
- <img src="https://huggingface.co/spaces/LatentNavigation/latentnavigation-flux/resolve/main/Group 4-16.png" width="100" style="display: inline-block">
186
- <h1 style="margin-left: 12px;text-align: center;margin-bottom: 7px;display: inline-block">Latent Navigation</h1>
187
  </div>
188
  <div style="display: flex;align-items: center;justify-content: center">
189
  <h3 style="display: inline-block;margin-left: 10px;margin-top: 6px;font-weight: 500">Exploring CLIP text space with FLUX.1 schnell 🪐</h3>
@@ -205,6 +120,8 @@ image_seq = gr.Image(label="Strip", elem_id="strip")
205
  output_image = gr.Image(label="Gif", elem_id="gif")
206
  post_generation_image = gr.Image(label="Generated Images")
207
  post_generation_slider = gr.Slider(minimum=-2, maximum=2, value=0, step=1, interactive=False)
 
 
208
  with gr.Blocks(css=css) as demo:
209
 
210
  gr.HTML(intro)
@@ -212,22 +129,16 @@ with gr.Blocks(css=css) as demo:
212
  x_concept_1 = gr.State("")
213
  x_concept_2 = gr.State("")
214
  total_images = gr.State([])
215
- # y_concept_1 = gr.State("")
216
- # y_concept_2 = gr.State("")
217
 
218
  avg_diff_x = gr.State()
219
- #avg_diff_y = gr.State()
220
 
221
  recalc_directions = gr.State(False)
222
 
223
- #with gr.Tab("text2image"):
224
  with gr.Row():
225
  with gr.Column():
226
  with gr.Row():
227
  concept_1 = gr.Textbox(label="1st direction to steer", placeholder="winter")
228
  concept_2 = gr.Textbox(label="2nd direction to steer", placeholder="summer")
229
- #slider_x = gr.Dropdown(label="Slider concept range", allow_custom_value=True, multiselect=True, max_choices=2)
230
- #slider_y = gr.Dropdown(label="Slider Y concept range", allow_custom_value=True, multiselect=True, max_choices=2)
231
  prompt = gr.Textbox(label="Prompt", info="Describe what you to be steered by the directions", placeholder="A dog in the park")
232
  x = gr.Slider(minimum=0, value=1.5, step=0.1, maximum=4.0, label="Strength", info="maximum strength on each direction (unstable beyond 2.5)")
233
  submit = gr.Button("Generate directions")
@@ -242,15 +153,12 @@ with gr.Blocks(css=css) as demo:
242
  with gr.Group(elem_id="group"):
243
  post_generation_image.render()
244
  post_generation_slider.render()
245
- #y = gr.Slider(minimum=-10, value=0, maximum=10, elem_id="y", interactive=False)
246
  with gr.Row():
247
  with gr.Column(scale=4, min_width=50):
248
  image_seq.render()
249
 
250
  with gr.Column(scale=2, min_width=50):
251
  output_image.render()
252
- # with gr.Row():
253
- # generate_butt = gr.Button("generate")
254
 
255
  with gr.Accordion(label="advanced options", open=False):
256
  iterations = gr.Slider(label = "num iterations for clip directions", minimum=0, value=200, maximum=500, step=1)
@@ -264,67 +172,14 @@ with gr.Blocks(css=css) as demo:
264
  value=3.5,
265
  )
266
  randomize_seed = gr.Checkbox(True, label="Randomize seed")
267
- seed = gr.Slider(minimum=0, maximum=MAX_SEED, step=1, label="Seed", interactive=True, randomize=True)
268
-
269
-
270
- # with gr.Tab(label="image2image"):
271
- # with gr.Row():
272
- # with gr.Column():
273
- # image = gr.ImageEditor(type="pil", image_mode="L", crop_size=(512, 512))
274
- # slider_x_a = gr.Dropdown(label="Slider X concept range", allow_custom_value=True, multiselect=True, max_choices=2)
275
- # slider_y_a = gr.Dropdown(label="Slider X concept range", allow_custom_value=True, multiselect=True, max_choices=2)
276
- # img2img_type = gr.Radio(["controlnet canny", "ip adapter"], label="", info="", visible=False, value="controlnet canny")
277
- # prompt_a = gr.Textbox(label="Prompt")
278
- # submit_a = gr.Button("Submit")
279
- # with gr.Column():
280
- # with gr.Group(elem_id="group"):
281
- # x_a = gr.Slider(minimum=-10, value=0, maximum=10, elem_id="x", interactive=False)
282
- # y_a = gr.Slider(minimum=-10, value=0, maximum=10, elem_id="y", interactive=False)
283
- # output_image_a = gr.Image(elem_id="image_out")
284
- # with gr.Row():
285
- # generate_butt_a = gr.Button("generate")
286
-
287
- # with gr.Accordion(label="advanced options", open=False):
288
- # iterations_a = gr.Slider(label = "num iterations", minimum=0, value=200, maximum=300)
289
- # steps_a = gr.Slider(label = "num inference steps", minimum=1, value=8, maximum=30)
290
- # guidance_scale_a = gr.Slider(
291
- # label="Guidance scale",
292
- # minimum=0.1,
293
- # maximum=10.0,
294
- # step=0.1,
295
- # value=5,
296
- # )
297
- # controlnet_conditioning_scale = gr.Slider(
298
- # label="controlnet conditioning scale",
299
- # minimum=0.5,
300
- # maximum=5.0,
301
- # step=0.1,
302
- # value=0.7,
303
- # )
304
- # ip_adapter_scale = gr.Slider(
305
- # label="ip adapter scale",
306
- # minimum=0.5,
307
- # maximum=5.0,
308
- # step=0.1,
309
- # value=0.8,
310
- # visible=False
311
- # )
312
- # seed_a = gr.Slider(minimum=0, maximum=np.iinfo(np.int32).max, label="Seed", interactive=True, randomize=True)
313
-
314
- # submit.click(fn=generate,
315
- # inputs=[slider_x, slider_y, prompt, seed, iterations, steps, guidance_scale, x_concept_1, x_concept_2, y_concept_1, y_concept_2, avg_diff_x, avg_diff_y],
316
- # outputs=[x, y, x_concept_1, x_concept_2, y_concept_1, y_concept_2, avg_diff_x, avg_diff_y, output_image])
317
  submit.click(fn=generate,
318
  inputs=[concept_1, concept_2, x, prompt, randomize_seed, seed, recalc_directions, iterations, steps, interm_steps, guidance_scale, x_concept_1, x_concept_2, avg_diff_x, total_images],
319
  outputs=[x_concept_1, x_concept_2, avg_diff_x, output_image, image_seq, total_images, post_generation_image, post_generation_slider, seed])
320
 
321
  iterations.change(fn=reset_recalc_directions, outputs=[recalc_directions])
322
  seed.change(fn=reset_recalc_directions, outputs=[recalc_directions])
323
- #x.release(fn=update_scales, inputs=[x, prompt, seed, steps, interm_steps, guidance_scale, avg_diff_x, total_images], outputs=[output_image, image_seq, total_images, post_generation_image, post_generation_slider], trigger_mode='always_last')
324
- # generate_butt_a.click(fn=update_scales, inputs=[x_a,y_a, prompt_a, seed_a, steps_a, guidance_scale_a, avg_diff_x, avg_diff_y, img2img_type, image, controlnet_conditioning_scale, ip_adapter_scale], outputs=[output_image_a])
325
- # submit_a.click(fn=generate,
326
- # inputs=[slider_x_a, slider_y_a, prompt_a, seed_a, iterations_a, steps_a, guidance_scale_a, x_concept_1, x_concept_2, y_concept_1, y_concept_2, avg_diff_x, avg_diff_y, img2img_type, image, controlnet_conditioning_scale, ip_adapter_scale],
327
- # outputs=[x_a, y_a, x_concept_1, x_concept_2, y_concept_1, y_concept_2, avg_diff_x, avg_diff_y, output_image_a])
328
  post_generation_slider.change(fn=update_pre_generated_images, inputs=[post_generation_slider, total_images], outputs=[post_generation_image], queue=False, show_progress="hidden", concurrency_limit=None)
329
 
330
  if __name__ == "__main__":
 
7
  import cv2
8
  from PIL import Image
9
  from diffusers.utils import load_image
 
 
10
  from diffusers.utils import export_to_gif
11
  import random
12
 
 
 
 
 
 
 
13
  # load pipelines
14
  base_model = "black-forest-labs/FLUX.1-schnell"
15
 
 
24
  clip_slider = CLIPSliderFlux(pipe, device=torch.device("cuda"))
25
 
26
 
 
 
 
 
 
27
  MAX_SEED = 2**32-1
28
 
29
  def convert_to_centered_scale(num):
 
43
  def generate(concept_1, concept_2, scale, prompt, randomize_seed=True, seed=42, recalc_directions=True, iterations=200, steps=4, interm_steps=9, guidance_scale=3.5,
44
  x_concept_1="", x_concept_2="",
45
  avg_diff_x=None,
 
 
46
  total_images=[],
47
  progress=gr.Progress(track_tqdm=True)
48
  ):
 
50
  # check if avg diff for directions need to be re-calculated
51
  print("slider_x", slider_x)
52
  print("x_concept_1", x_concept_1, "x_concept_2", x_concept_2)
 
53
  if randomize_seed:
54
  seed = random.randint(0, MAX_SEED)
55
 
56
  if not sorted(slider_x) == sorted([x_concept_1, x_concept_2]) or recalc_directions:
 
57
  avg_diff = clip_slider.find_latent_direction(slider_x[0], slider_x[1], num_iterations=iterations)
58
  x_concept_1, x_concept_2 = slider_x[0], slider_x[1]
59
 
 
65
  image = clip_slider.generate(prompt,
66
  width=768,
67
  height=768,
68
+ guidance_scale=guidance_scale,
69
  scale=cur_scale, seed=seed, num_inference_steps=steps, avg_diff=avg_diff)
70
  images.append(image)
71
  canvas = Image.new('RGB', (256*interm_steps, 256))
 
83
 
84
  return x_concept_1,x_concept_2, avg_diff_x, export_to_gif(images, "clip.gif", fps=5), canvas, images, images[scale_middle], post_generation_slider_update, seed
85
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86
  def update_pre_generated_images(slider_value, total_images):
87
  number_images = len(total_images)
88
  if(number_images > 0):
 
94
  def reset_recalc_directions():
95
  return True
96
 
97
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98
  intro = """
99
  <div style="display: flex;align-items: center;justify-content: center">
100
+ <img src="https://huggingface.co/spaces/LatentNavigation/latentnavigation-flux/resolve/main/Group 4-16.png" width="120" style="display: inline-block">
101
+ <h1 style="margin-left: 12px;text-align: center;margin-bottom: 7px;display: inline-block;font-size:1.1em">Latent Navigation</h1>
102
  </div>
103
  <div style="display: flex;align-items: center;justify-content: center">
104
  <h3 style="display: inline-block;margin-left: 10px;margin-top: 6px;font-weight: 500">Exploring CLIP text space with FLUX.1 schnell 🪐</h3>
 
120
  output_image = gr.Image(label="Gif", elem_id="gif")
121
  post_generation_image = gr.Image(label="Generated Images")
122
  post_generation_slider = gr.Slider(minimum=-2, maximum=2, value=0, step=1, interactive=False)
123
+ seed = gr.Slider(minimum=0, maximum=MAX_SEED, step=1, label="Seed", interactive=True, randomize=True)
124
+
125
  with gr.Blocks(css=css) as demo:
126
 
127
  gr.HTML(intro)
 
129
  x_concept_1 = gr.State("")
130
  x_concept_2 = gr.State("")
131
  total_images = gr.State([])
 
 
132
 
133
  avg_diff_x = gr.State()
 
134
 
135
  recalc_directions = gr.State(False)
136
 
 
137
  with gr.Row():
138
  with gr.Column():
139
  with gr.Row():
140
  concept_1 = gr.Textbox(label="1st direction to steer", placeholder="winter")
141
  concept_2 = gr.Textbox(label="2nd direction to steer", placeholder="summer")
 
 
142
  prompt = gr.Textbox(label="Prompt", info="Describe what you to be steered by the directions", placeholder="A dog in the park")
143
  x = gr.Slider(minimum=0, value=1.5, step=0.1, maximum=4.0, label="Strength", info="maximum strength on each direction (unstable beyond 2.5)")
144
  submit = gr.Button("Generate directions")
 
153
  with gr.Group(elem_id="group"):
154
  post_generation_image.render()
155
  post_generation_slider.render()
 
156
  with gr.Row():
157
  with gr.Column(scale=4, min_width=50):
158
  image_seq.render()
159
 
160
  with gr.Column(scale=2, min_width=50):
161
  output_image.render()
 
 
162
 
163
  with gr.Accordion(label="advanced options", open=False):
164
  iterations = gr.Slider(label = "num iterations for clip directions", minimum=0, value=200, maximum=500, step=1)
 
172
  value=3.5,
173
  )
174
  randomize_seed = gr.Checkbox(True, label="Randomize seed")
175
+ seed.render()
176
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
177
  submit.click(fn=generate,
178
  inputs=[concept_1, concept_2, x, prompt, randomize_seed, seed, recalc_directions, iterations, steps, interm_steps, guidance_scale, x_concept_1, x_concept_2, avg_diff_x, total_images],
179
  outputs=[x_concept_1, x_concept_2, avg_diff_x, output_image, image_seq, total_images, post_generation_image, post_generation_slider, seed])
180
 
181
  iterations.change(fn=reset_recalc_directions, outputs=[recalc_directions])
182
  seed.change(fn=reset_recalc_directions, outputs=[recalc_directions])
 
 
 
 
 
183
  post_generation_slider.change(fn=update_pre_generated_images, inputs=[post_generation_slider, total_images], outputs=[post_generation_image], queue=False, show_progress="hidden", concurrency_limit=None)
184
 
185
  if __name__ == "__main__":