Gemini899 commited on
Commit
7ae6a53
·
verified ·
1 Parent(s): 98dcf6a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +105 -20
app.py CHANGED
@@ -18,18 +18,98 @@ MAX_SEED = np.iinfo(np.int32).max
18
  MAX_IMAGE_SIZE = 1024
19
 
20
  # Initialize text encoder client ONCE at module level to avoid thread exhaustion
21
- text_encoder_client = client = Client("Gemini899/mistral-text-encoder")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
 
23
  def remote_text_encoder(prompts):
 
 
 
 
 
 
 
 
 
 
 
 
24
  result = text_encoder_client.predict(
25
  prompt=prompts,
26
  api_name="/encode_text"
27
  )
28
-
29
  prompt_embeds = torch.load(result[0])
30
  return prompt_embeds
31
 
32
- # Load model
 
 
 
 
 
 
33
  repo_id = "black-forest-labs/FLUX.2-dev"
34
 
35
  dit = Flux2Transformer2DModel.from_pretrained(
@@ -46,8 +126,9 @@ pipe = Flux2Pipeline.from_pretrained(
46
  )
47
  pipe.to(device)
48
 
49
- # AOTI blocks temporarily disabled - HuggingFace needs to recompile for new ZeroGPU environment
50
- # spaces.aoti_blocks_load(pipe.transformer, "zerogpu-aoti/FLUX.2", variant="fa3")
 
51
 
52
  def update_dimensions_from_image(image_list):
53
  """Update width/height sliders based on uploaded image aspect ratio."""
@@ -97,7 +178,7 @@ def generate_image(prompt_embeds, image_list, width, height, num_inference_steps
97
 
98
  if progress:
99
  progress(0, desc="Starting generation...")
100
-
101
  image = pipe(**pipe_kwargs).images[0]
102
  return image
103
 
@@ -111,26 +192,30 @@ def infer(prompt, input_images=None, seed=42, randomize_seed=False, width=1024,
111
  image_list = []
112
  for item in input_images:
113
  image_list.append(item[0])
114
-
115
- # Text Encoding
116
  progress(0.1, desc="Encoding prompt...")
117
  prompt_embeds = remote_text_encoder(prompt)
118
 
119
  # Image Generation
120
  progress(0.3, desc="Waiting for GPU...")
121
  image = generate_image(
122
- prompt_embeds,
123
- image_list,
124
- width,
125
- height,
126
- num_inference_steps,
127
- guidance_scale,
128
- seed,
129
  progress
130
  )
131
 
132
  return image, seed
133
 
 
 
 
 
134
  examples = [
135
  ["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"],
136
  ["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."],
@@ -157,7 +242,7 @@ with gr.Blocks() as demo:
157
  with gr.Column(elem_id="col-container"):
158
  gr.Markdown(f"""# FLUX.2 [dev]
159
  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)]
160
- """)
161
  with gr.Row():
162
  with gr.Column():
163
  with gr.Row():
@@ -171,7 +256,7 @@ FLUX.2 [dev] is a 32B model rectified flow capable of generating, editing and co
171
  )
172
 
173
  run_button = gr.Button("Run", scale=1)
174
-
175
  with gr.Accordion("Input image(s) (optional)", open=True):
176
  input_images = gr.Gallery(
177
  label="Input Image(s)",
@@ -236,7 +321,7 @@ FLUX.2 [dev] is a 32B model rectified flow capable of generating, editing and co
236
  cache_examples=True,
237
  cache_mode="lazy"
238
  )
239
-
240
  gr.Examples(
241
  examples=examples_images,
242
  fn=infer,
@@ -245,13 +330,13 @@ FLUX.2 [dev] is a 32B model rectified flow capable of generating, editing and co
245
  cache_examples=True,
246
  cache_mode="lazy"
247
  )
248
-
249
  input_images.upload(
250
  fn=update_dimensions_from_image,
251
  inputs=[input_images],
252
  outputs=[width, height]
253
  )
254
-
255
  gr.on(
256
  triggers=[run_button.click, prompt.submit],
257
  fn=infer,
 
18
  MAX_IMAGE_SIZE = 1024
19
 
20
  # Initialize text encoder client ONCE at module level to avoid thread exhaustion
21
+ text_encoder_client = Client("Gemini899/mistral-text-encoder")
22
+
23
+ # ============================================================================
24
+ # HARDCODED PROMPTS - Exact match only
25
+ # ============================================================================
26
+
27
+ HARDCODED_PROMPTS = {
28
+ "relief": "Clay bas-relief sculpture. PRESERVE exact facial features and proportions. Uniform matte gray material, NO black areas, NO dark shadows, NO outlines. Soft smooth depth only. Light gray to white tones. Like carved marble or clay relief.",
29
+
30
+ "details": "Enhance this depth map by adding surface micro-details (skin pores, fabric texture, hair strands, stone grain, wrinkles, fingernails, knuckles) using ONLY tonal variations within ±10% of local gray values. Keep EXACT same outline, silhouette, and overall tonal range. NO shadows, NO reflections, NO new light sources, NO dark areas under nose/eyes/lips. Output must overlay perfectly on original as bump map detail layer."
31
+ }
32
+
33
+ # Pre-load embeddings at startup
34
+ _cached_embeddings = {}
35
+
36
+ def load_cached_embeddings():
37
+ """Load pre-generated embeddings at startup."""
38
+ global _cached_embeddings
39
+
40
+ embedding_files = {
41
+ "relief": "relief.pt",
42
+ "details": "details.pt"
43
+ }
44
+
45
+ for key, filename in embedding_files.items():
46
+ # Try multiple possible paths
47
+ possible_paths = [
48
+ filename, # Current directory
49
+ f"/home/user/app/{filename}", # HF Spaces app directory
50
+ os.path.join(os.path.dirname(__file__), filename), # Same dir as script
51
+ ]
52
+
53
+ for path in possible_paths:
54
+ if os.path.exists(path):
55
+ try:
56
+ _cached_embeddings[key] = torch.load(path, map_location='cpu')
57
+ print(f"✓ Loaded cached embedding: {key} from {path}")
58
+ break
59
+ except Exception as e:
60
+ print(f"✗ Error loading {path}: {e}")
61
+ else:
62
+ print(f"⚠ Warning: {filename} not found - will use API for '{key}' prompt")
63
+
64
+ def normalize_prompt(prompt: str) -> str:
65
+ """Normalize prompt by stripping whitespace for comparison."""
66
+ return prompt.strip()
67
+
68
+ def get_cached_embedding(prompt: str) -> torch.Tensor | None:
69
+ """
70
+ Check if prompt EXACTLY matches a hardcoded prompt.
71
+ Returns cached embedding if exact match, None otherwise.
72
+ """
73
+ normalized_input = normalize_prompt(prompt)
74
+
75
+ for key, hardcoded_prompt in HARDCODED_PROMPTS.items():
76
+ if normalized_input == normalize_prompt(hardcoded_prompt):
77
+ if key in _cached_embeddings:
78
+ print(f"⚡ Exact match found: using cached '{key}' embedding (no API call)")
79
+ return _cached_embeddings[key]
80
+ else:
81
+ print(f"⚠ Exact match for '{key}' but no cached embedding - using API")
82
+ return None
83
+
84
+ return None
85
 
86
  def remote_text_encoder(prompts):
87
+ """
88
+ Encode text prompts to embeddings.
89
+ Uses cached embeddings for exact hardcoded prompt matches.
90
+ Falls back to Mistral API for all other prompts.
91
+ """
92
+ # Check for exact match with hardcoded prompts
93
+ cached = get_cached_embedding(prompts)
94
+ if cached is not None:
95
+ return cached
96
+
97
+ # Not an exact match - use API
98
+ print(f"🌐 Calling Mistral API for prompt encoding...")
99
  result = text_encoder_client.predict(
100
  prompt=prompts,
101
  api_name="/encode_text"
102
  )
 
103
  prompt_embeds = torch.load(result[0])
104
  return prompt_embeds
105
 
106
+ # Load cached embeddings at startup
107
+ load_cached_embeddings()
108
+
109
+ # ============================================================================
110
+ # Model Loading
111
+ # ============================================================================
112
+
113
  repo_id = "black-forest-labs/FLUX.2-dev"
114
 
115
  dit = Flux2Transformer2DModel.from_pretrained(
 
126
  )
127
  pipe.to(device)
128
 
129
+ # ============================================================================
130
+ # Image Generation Functions
131
+ # ============================================================================
132
 
133
  def update_dimensions_from_image(image_list):
134
  """Update width/height sliders based on uploaded image aspect ratio."""
 
178
 
179
  if progress:
180
  progress(0, desc="Starting generation...")
181
+
182
  image = pipe(**pipe_kwargs).images[0]
183
  return image
184
 
 
192
  image_list = []
193
  for item in input_images:
194
  image_list.append(item[0])
195
+
196
+ # Text Encoding (checks for cached embeddings first)
197
  progress(0.1, desc="Encoding prompt...")
198
  prompt_embeds = remote_text_encoder(prompt)
199
 
200
  # Image Generation
201
  progress(0.3, desc="Waiting for GPU...")
202
  image = generate_image(
203
+ prompt_embeds,
204
+ image_list,
205
+ width,
206
+ height,
207
+ num_inference_steps,
208
+ guidance_scale,
209
+ seed,
210
  progress
211
  )
212
 
213
  return image, seed
214
 
215
+ # ============================================================================
216
+ # Gradio UI
217
+ # ============================================================================
218
+
219
  examples = [
220
  ["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"],
221
  ["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."],
 
242
  with gr.Column(elem_id="col-container"):
243
  gr.Markdown(f"""# FLUX.2 [dev]
244
  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)]
245
+ """)
246
  with gr.Row():
247
  with gr.Column():
248
  with gr.Row():
 
256
  )
257
 
258
  run_button = gr.Button("Run", scale=1)
259
+
260
  with gr.Accordion("Input image(s) (optional)", open=True):
261
  input_images = gr.Gallery(
262
  label="Input Image(s)",
 
321
  cache_examples=True,
322
  cache_mode="lazy"
323
  )
324
+
325
  gr.Examples(
326
  examples=examples_images,
327
  fn=infer,
 
330
  cache_examples=True,
331
  cache_mode="lazy"
332
  )
333
+
334
  input_images.upload(
335
  fn=update_dimensions_from_image,
336
  inputs=[input_images],
337
  outputs=[width, height]
338
  )
339
+
340
  gr.on(
341
  triggers=[run_button.click, prompt.submit],
342
  fn=infer,