multimodalart HF Staff commited on
Commit
b0751aa
·
verified ·
1 Parent(s): 850d0d4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +42 -90
app.py CHANGED
@@ -1,22 +1,23 @@
1
  import os
2
  import subprocess
3
  import sys
 
 
 
 
4
  import io
5
  import gradio as gr
6
  import numpy as np
7
  import random
8
  import spaces
9
  import torch
10
- from diffusers import Flux2Pipeline, Flux2Transformer2DModel
11
- from diffusers import BitsAndBytesConfig as DiffBitsAndBytesConfig
12
  import requests
13
  from PIL import Image
14
  import json
15
  import base64
16
  from huggingface_hub import InferenceClient
17
 
18
- subprocess.check_call([sys.executable, "-m", "pip", "install", "spaces==0.43.0"])
19
-
20
  dtype = torch.bfloat16
21
  device = "cuda" if torch.cuda.is_available() else "cpu"
22
 
@@ -50,38 +51,13 @@ Rules:
50
 
51
  Output only the final instruction in plain text and nothing else."""
52
 
53
- def remote_text_encoder(prompts):
54
- from gradio_client import Client
55
-
56
- client = Client("multimodalart/mistral-text-encoder")
57
- result = client.predict(
58
- prompt=prompts,
59
- api_name="/encode_text"
60
- )
61
-
62
- # Load returns a tensor, usually on CPU by default
63
- prompt_embeds = torch.load(result[0])
64
- return prompt_embeds
65
-
66
- # Load model
67
- repo_id = "black-forest-labs/FLUX.2-dev"
68
 
69
- dit = Flux2Transformer2DModel.from_pretrained(
70
- repo_id,
71
- subfolder="transformer",
72
- torch_dtype=torch.bfloat16
73
- )
74
-
75
- pipe = Flux2Pipeline.from_pretrained(
76
- repo_id,
77
- text_encoder=None,
78
- transformer=dit,
79
- torch_dtype=torch.bfloat16
80
- )
81
- pipe.to(device)
82
 
83
- # Pull pre-compiled Flux2 Transformer blocks from HF hub
84
- spaces.aoti_blocks_load(pipe.transformer, "zerogpu-aoti/FLUX.2", variant="fa3")
85
 
86
  def image_to_data_uri(img):
87
  buffered = io.BytesIO()
@@ -89,6 +65,7 @@ def image_to_data_uri(img):
89
  img_str = base64.b64encode(buffered.getvalue()).decode("utf-8")
90
  return f"data:image/png;base64,{img_str}"
91
 
 
92
  def upsample_prompt_logic(prompt, image_list):
93
  try:
94
  if image_list and len(image_list) > 0:
@@ -128,6 +105,7 @@ def upsample_prompt_logic(prompt, image_list):
128
  print(f"Upsampling failed: {e}")
129
  return prompt
130
 
 
131
  def update_dimensions_from_image(image_list):
132
  """Update width/height sliders based on uploaded image aspect ratio.
133
  Keeps one side at 1024 and scales the other proportionally, with both sides as multiples of 8."""
@@ -157,37 +135,9 @@ def update_dimensions_from_image(image_list):
157
 
158
  return new_width, new_height
159
 
160
- # Updated duration function to match generate_image arguments (including progress)
161
- def get_duration(prompt_embeds, image_list, width, height, num_inference_steps, guidance_scale, seed, progress=gr.Progress(track_tqdm=True)):
162
- num_images = 0 if image_list is None else len(image_list)
163
- step_duration = 1 + 0.8 * num_images
164
- return max(65, num_inference_steps * step_duration + 10)
165
-
166
- @spaces.GPU(duration=get_duration)
167
- def generate_image(prompt_embeds, image_list, width, height, num_inference_steps, guidance_scale, seed, progress=gr.Progress(track_tqdm=True)):
168
- # Move embeddings to GPU only when inside the GPU decorated function
169
- prompt_embeds = prompt_embeds.to(device)
170
-
171
- generator = torch.Generator(device=device).manual_seed(seed)
172
-
173
- pipe_kwargs = {
174
- "prompt_embeds": prompt_embeds,
175
- "image": image_list,
176
- "num_inference_steps": num_inference_steps,
177
- "guidance_scale": guidance_scale,
178
- "generator": generator,
179
- "width": width,
180
- "height": height,
181
- }
182
-
183
- # Progress bar for the actual generation steps
184
- if progress:
185
- progress(0, desc="Starting generation...")
186
-
187
- image = pipe(**pipe_kwargs).images[0]
188
- return image
189
 
190
- def infer(prompt, input_images=None, seed=42, randomize_seed=False, width=1024, height=1024, num_inference_steps=50, guidance_scale=2.5, prompt_upsampling=False, progress=gr.Progress(track_tqdm=True)):
 
191
 
192
  if randomize_seed:
193
  seed = random.randint(0, MAX_SEED)
@@ -199,34 +149,37 @@ def infer(prompt, input_images=None, seed=42, randomize_seed=False, width=1024,
199
  for item in input_images:
200
  image_list.append(item[0])
201
 
202
- # 1. Upsampling (Network bound - No GPU needed)
203
  final_prompt = prompt
204
  if prompt_upsampling:
205
- progress(0.05, desc="Upsampling prompt...")
206
  final_prompt = upsample_prompt_logic(prompt, image_list)
207
  print(f"Original Prompt: {prompt}")
208
  print(f"Upsampled Prompt: {final_prompt}")
209
 
210
- # 2. Text Encoding (Network bound - No GPU needed)
211
- progress(0.1, desc="Encoding prompt...")
212
- # This returns CPU tensors
213
- prompt_embeds = remote_text_encoder(final_prompt)
214
 
215
- # 3. Image Generation (GPU bound)
216
- progress(0.3, desc="Waiting for GPU...")
217
- image = generate_image(
218
- prompt_embeds,
219
- image_list,
220
- width,
221
- height,
222
- num_inference_steps,
223
- guidance_scale,
224
- seed,
225
- progress
226
- )
 
 
 
 
227
 
228
  return image, seed
229
 
 
230
  examples = [
231
  ["Create a vase on a table in living room, the color of the vase is a gradient of color, starting with #02eb3c color and finishing with #edfa3c. The flowers inside the vase have the color #ff0088"],
232
  ["Photorealistic infographic showing the complete Berlin TV Tower (Fernsehturm) from ground base to antenna tip, full vertical view with entire structure visible including concrete shaft, metallic sphere, and antenna spire. Slight upward perspective angle looking up toward the iconic sphere, perfectly centered on clean white background. Left side labels with thin horizontal connector lines: the text '368m' in extra large bold dark grey numerals (#2D3748) positioned at exactly the antenna tip with 'TOTAL HEIGHT' in small caps below. The text '207m' in extra large bold with 'TELECAFÉ' in small caps below, with connector line touching the sphere precisely at the window level. Right side label with horizontal connector line touching the sphere's equator: the text '32m' in extra large bold dark grey numerals with 'SPHERE DIAMETER' in small caps below. Bottom section arranged in three balanced columns: Left - Large text '986' in extra bold dark grey with 'STEPS' in caps below. Center - 'BERLIN TV TOWER' in bold caps with 'FERNSEHTURM' in lighter weight below. Right - 'INAUGURATED' in bold caps with 'OCTOBER 3, 1969' below. All typography in modern sans-serif font (such as Inter or Helvetica), color #2D3748, clean minimal technical diagram style. Horizontal connector lines are thin, precise, and clearly visible, touching the tower structure at exact corresponding measurement points. Professional architectural elevation drawing aesthetic with dynamic low angle perspective creating sense of height and grandeur, poster-ready infographic design with perfect visual hierarchy."],
@@ -235,11 +188,10 @@ examples = [
235
  ]
236
 
237
  examples_images = [
238
- # ["Replace the top of the person from image 1 with the one from image 2", ["person1.webp", "woman2.webp"]],
239
  ["The person from image 1 is petting the cat from image 2, the bird from image 3 is next to them", ["woman1.webp", "cat_window.webp", "bird.webp"]]
240
  ]
241
 
242
- css="""
243
  #col-container {
244
  margin: 0 auto;
245
  max-width: 1200px;
@@ -249,11 +201,11 @@ css="""
249
  }
250
  """
251
 
252
- with gr.Blocks() as demo:
253
 
254
  with gr.Column(elem_id="col-container"):
255
- gr.Markdown(f"""# FLUX.2 [dev]
256
- FLUX.2 [dev] is a 32B model rectified flow capable of generating, editing and combining images based on text instructions model [[model](https://huggingface.co/black-forest-labs/FLUX.2-dev)], [[blog](https://bfl.ai/blog/flux-2)]
257
  """)
258
  with gr.Row():
259
  with gr.Column():
@@ -319,7 +271,7 @@ FLUX.2 [dev] is a 32B model rectified flow capable of generating, editing and co
319
  minimum=1,
320
  maximum=100,
321
  step=1,
322
- value=30,
323
  )
324
 
325
  guidance_scale = gr.Slider(
@@ -327,7 +279,7 @@ FLUX.2 [dev] is a 32B model rectified flow capable of generating, editing and co
327
  minimum=0.0,
328
  maximum=10.0,
329
  step=0.1,
330
- value=4,
331
  )
332
 
333
 
@@ -367,4 +319,4 @@ FLUX.2 [dev] is a 32B model rectified flow capable of generating, editing and co
367
  outputs=[result, seed]
368
  )
369
 
370
- demo.launch(css=css)
 
1
  import os
2
  import subprocess
3
  import sys
4
+
5
+ subprocess.check_call(["unzip", "-o", "diffusers.zip", "-d", "diffusers_local"])
6
+ subprocess.check_call([sys.executable, "-m", "pip", "install", "-e", "diffusers_local/diffusers"])
7
+
8
  import io
9
  import gradio as gr
10
  import numpy as np
11
  import random
12
  import spaces
13
  import torch
14
+ from diffusers import Flux2KleinPipeline
 
15
  import requests
16
  from PIL import Image
17
  import json
18
  import base64
19
  from huggingface_hub import InferenceClient
20
 
 
 
21
  dtype = torch.bfloat16
22
  device = "cuda" if torch.cuda.is_available() else "cpu"
23
 
 
51
 
52
  Output only the final instruction in plain text and nothing else."""
53
 
54
+ # Load model - using Flux2KleinPipeline with built-in text encoder
55
+ repo_id = "diffusers-internal-dev/dummy-1015-4b" # 4b model
56
+ # repo_id = "diffusers-internal-dev/dummy-1015-9b" # 9b model (alternative)
 
 
 
 
 
 
 
 
 
 
 
 
57
 
58
+ pipe = Flux2KleinPipeline.from_pretrained(repo_id, torch_dtype=dtype)
59
+ pipe.enable_model_cpu_offload()
 
 
 
 
 
 
 
 
 
 
 
60
 
 
 
61
 
62
  def image_to_data_uri(img):
63
  buffered = io.BytesIO()
 
65
  img_str = base64.b64encode(buffered.getvalue()).decode("utf-8")
66
  return f"data:image/png;base64,{img_str}"
67
 
68
+
69
  def upsample_prompt_logic(prompt, image_list):
70
  try:
71
  if image_list and len(image_list) > 0:
 
105
  print(f"Upsampling failed: {e}")
106
  return prompt
107
 
108
+
109
  def update_dimensions_from_image(image_list):
110
  """Update width/height sliders based on uploaded image aspect ratio.
111
  Keeps one side at 1024 and scales the other proportionally, with both sides as multiples of 8."""
 
135
 
136
  return new_width, new_height
137
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
138
 
139
+ @spaces.GPU
140
+ def infer(prompt, input_images=None, seed=42, randomize_seed=False, width=1024, height=1024, num_inference_steps=50, guidance_scale=4.0, prompt_upsampling=False, progress=gr.Progress(track_tqdm=True)):
141
 
142
  if randomize_seed:
143
  seed = random.randint(0, MAX_SEED)
 
149
  for item in input_images:
150
  image_list.append(item[0])
151
 
152
+ # 1. Upsampling (Network bound)
153
  final_prompt = prompt
154
  if prompt_upsampling:
155
+ progress(0.1, desc="Upsampling prompt...")
156
  final_prompt = upsample_prompt_logic(prompt, image_list)
157
  print(f"Original Prompt: {prompt}")
158
  print(f"Upsampled Prompt: {final_prompt}")
159
 
160
+ # 2. Image Generation
161
+ progress(0.2, desc="Generating image...")
 
 
162
 
163
+ generator = torch.Generator(device=device).manual_seed(seed)
164
+
165
+ pipe_kwargs = {
166
+ "prompt": final_prompt,
167
+ "height": height,
168
+ "width": width,
169
+ "num_inference_steps": num_inference_steps,
170
+ "guidance_scale": guidance_scale,
171
+ "generator": generator,
172
+ }
173
+
174
+ # Add images if provided
175
+ if image_list is not None:
176
+ pipe_kwargs["image"] = image_list
177
+
178
+ image = pipe(**pipe_kwargs).images[0]
179
 
180
  return image, seed
181
 
182
+
183
  examples = [
184
  ["Create a vase on a table in living room, the color of the vase is a gradient of color, starting with #02eb3c color and finishing with #edfa3c. The flowers inside the vase have the color #ff0088"],
185
  ["Photorealistic infographic showing the complete Berlin TV Tower (Fernsehturm) from ground base to antenna tip, full vertical view with entire structure visible including concrete shaft, metallic sphere, and antenna spire. Slight upward perspective angle looking up toward the iconic sphere, perfectly centered on clean white background. Left side labels with thin horizontal connector lines: the text '368m' in extra large bold dark grey numerals (#2D3748) positioned at exactly the antenna tip with 'TOTAL HEIGHT' in small caps below. The text '207m' in extra large bold with 'TELECAFÉ' in small caps below, with connector line touching the sphere precisely at the window level. Right side label with horizontal connector line touching the sphere's equator: the text '32m' in extra large bold dark grey numerals with 'SPHERE DIAMETER' in small caps below. Bottom section arranged in three balanced columns: Left - Large text '986' in extra bold dark grey with 'STEPS' in caps below. Center - 'BERLIN TV TOWER' in bold caps with 'FERNSEHTURM' in lighter weight below. Right - 'INAUGURATED' in bold caps with 'OCTOBER 3, 1969' below. All typography in modern sans-serif font (such as Inter or Helvetica), color #2D3748, clean minimal technical diagram style. Horizontal connector lines are thin, precise, and clearly visible, touching the tower structure at exact corresponding measurement points. Professional architectural elevation drawing aesthetic with dynamic low angle perspective creating sense of height and grandeur, poster-ready infographic design with perfect visual hierarchy."],
 
188
  ]
189
 
190
  examples_images = [
 
191
  ["The person from image 1 is petting the cat from image 2, the bird from image 3 is next to them", ["woman1.webp", "cat_window.webp", "bird.webp"]]
192
  ]
193
 
194
+ css = """
195
  #col-container {
196
  margin: 0 auto;
197
  max-width: 1200px;
 
201
  }
202
  """
203
 
204
+ with gr.Blocks(css=css) as demo:
205
 
206
  with gr.Column(elem_id="col-container"):
207
+ gr.Markdown(f"""# FLUX.2 Klein [dev]
208
+ FLUX.2 Klein [dev] is a distilled model capable of generating, editing and combining images based on text instructions [[model](https://huggingface.co/black-forest-labs/FLUX.2-dev)], [[blog](https://bfl.ai/blog/flux-2)]
209
  """)
210
  with gr.Row():
211
  with gr.Column():
 
271
  minimum=1,
272
  maximum=100,
273
  step=1,
274
+ value=50,
275
  )
276
 
277
  guidance_scale = gr.Slider(
 
279
  minimum=0.0,
280
  maximum=10.0,
281
  step=0.1,
282
+ value=4.0,
283
  )
284
 
285
 
 
319
  outputs=[result, seed]
320
  )
321
 
322
+ demo.launch()