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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import re
3
+ import tempfile
4
+ import time
5
+ from glob import iglob
6
+ from io import BytesIO
7
+
8
+ import numpy as np
9
+ import streamlit as st
10
+ import torch
11
+ from einops import rearrange
12
+ from fire import Fire
13
+ from PIL import ExifTags, Image
14
+ from st_keyup import st_keyup
15
+ from streamlit_drawable_canvas import st_canvas
16
+ from transformers import pipeline
17
+
18
+ from flux.sampling import denoise, get_noise, get_schedule, prepare_fill, unpack
19
+ from flux.util import (
20
+ embed_watermark,
21
+ load_ae,
22
+ load_clip,
23
+ load_flow_model,
24
+ load_t5,
25
+ track_usage_via_api,
26
+ )
27
+
28
+ NSFW_THRESHOLD = 0.85
29
+
30
+
31
+ def add_border_and_mask(image, zoom_all=1.0, zoom_left=0, zoom_right=0, zoom_up=0, zoom_down=0, overlap=0):
32
+ """Adds a black border around the image with individual side control and mask overlap"""
33
+ orig_width, orig_height = image.size
34
+
35
+ # Calculate padding for each side (in pixels)
36
+ left_pad = int(orig_width * zoom_left)
37
+ right_pad = int(orig_width * zoom_right)
38
+ top_pad = int(orig_height * zoom_up)
39
+ bottom_pad = int(orig_height * zoom_down)
40
+
41
+ # Calculate overlap in pixels
42
+ overlap_left = int(orig_width * overlap)
43
+ overlap_right = int(orig_width * overlap)
44
+ overlap_top = int(orig_height * overlap)
45
+ overlap_bottom = int(orig_height * overlap)
46
+
47
+ # If using the all-sides zoom, add it to each side
48
+ if zoom_all > 1.0:
49
+ extra_each_side = (zoom_all - 1.0) / 2
50
+ left_pad += int(orig_width * extra_each_side)
51
+ right_pad += int(orig_width * extra_each_side)
52
+ top_pad += int(orig_height * extra_each_side)
53
+ bottom_pad += int(orig_height * extra_each_side)
54
+
55
+ # Calculate new dimensions (ensure they're multiples of 32)
56
+ new_width = 32 * round((orig_width + left_pad + right_pad) / 32)
57
+ new_height = 32 * round((orig_height + top_pad + bottom_pad) / 32)
58
+
59
+ # Create new image with black border
60
+ bordered_image = Image.new("RGB", (new_width, new_height), (0, 0, 0))
61
+ # Paste original image in position
62
+ paste_x = left_pad
63
+ paste_y = top_pad
64
+ bordered_image.paste(image, (paste_x, paste_y))
65
+
66
+ # Create mask (white where the border is, black where the original image was)
67
+ mask = Image.new("L", (new_width, new_height), 255) # White background
68
+ # Paste black rectangle with overlap adjustment
69
+ mask.paste(
70
+ 0,
71
+ (
72
+ paste_x + overlap_left, # Left edge moves right
73
+ paste_y + overlap_top, # Top edge moves down
74
+ paste_x + orig_width - overlap_right, # Right edge moves left
75
+ paste_y + orig_height - overlap_bottom, # Bottom edge moves up
76
+ ),
77
+ )
78
+
79
+ return bordered_image, mask
80
+
81
+
82
+ @st.cache_resource()
83
+ def get_models(name: str, device: torch.device, offload: bool):
84
+ t5 = load_t5(device, max_length=128)
85
+ clip = load_clip(device)
86
+ model = load_flow_model(name, device="cpu" if offload else device)
87
+ ae = load_ae(name, device="cpu" if offload else device)
88
+ nsfw_classifier = pipeline("image-classification", model="Falconsai/nsfw_image_detection", device=device)
89
+ return model, ae, t5, clip, nsfw_classifier
90
+
91
+
92
+ def resize(img: Image.Image, min_mp: float = 0.5, max_mp: float = 2.0) -> Image.Image:
93
+ width, height = img.size
94
+ mp = (width * height) / 1_000_000 # Current megapixels
95
+
96
+ if min_mp <= mp <= max_mp:
97
+ # Even if MP is in range, ensure dimensions are multiples of 32
98
+ new_width = int(32 * round(width / 32))
99
+ new_height = int(32 * round(height / 32))
100
+ if new_width != width or new_height != height:
101
+ return img.resize((new_width, new_height), Image.Resampling.LANCZOS)
102
+ return img
103
+
104
+ # Calculate scaling factor
105
+ if mp < min_mp:
106
+ scale = (min_mp / mp) ** 0.5
107
+ else: # mp > max_mp
108
+ scale = (max_mp / mp) ** 0.5
109
+
110
+ new_width = int(32 * round(width * scale / 32))
111
+ new_height = int(32 * round(height * scale / 32))
112
+
113
+ return img.resize((new_width, new_height), Image.Resampling.LANCZOS)
114
+
115
+
116
+ def clear_canvas_state():
117
+ """Clear all canvas-related state"""
118
+ keys_to_clear = ["canvas", "last_image_dims"]
119
+ for key in keys_to_clear:
120
+ if key in st.session_state:
121
+ del st.session_state[key]
122
+
123
+
124
+ def set_new_image(img: Image.Image):
125
+ """Safely set a new image and clear relevant state"""
126
+ st.session_state["current_image"] = img
127
+ clear_canvas_state()
128
+ st.rerun()
129
+
130
+
131
+ def downscale_image(img: Image.Image, scale_factor: float) -> Image.Image:
132
+ """Downscale image by a given factor while maintaining 32-pixel multiple dimensions"""
133
+ if scale_factor >= 1.0:
134
+ return img
135
+
136
+ width, height = img.size
137
+ new_width = int(32 * round(width * scale_factor / 32))
138
+ new_height = int(32 * round(height * scale_factor / 32))
139
+
140
+ # Ensure minimum dimensions
141
+ new_width = max(64, new_width) # minimum 64 pixels
142
+ new_height = max(64, new_height) # minimum 64 pixels
143
+
144
+ return img.resize((new_width, new_height), Image.Resampling.LANCZOS)
145
+
146
+
147
+ @torch.inference_mode()
148
+ def main(
149
+ device: str = "cuda" if torch.cuda.is_available() else "cpu",
150
+ offload: bool = False,
151
+ output_dir: str = "output",
152
+ track_usage: bool = False,
153
+ ):
154
+ torch_device = torch.device(device)
155
+ st.title("Flux Fill: Inpainting & Outpainting")
156
+
157
+ # Model selection and loading
158
+ name = "flux-dev-fill"
159
+ if not st.checkbox("Load model", False):
160
+ return
161
+
162
+ try:
163
+ model, ae, t5, clip, nsfw_classifier = get_models(
164
+ name,
165
+ device=torch_device,
166
+ offload=offload,
167
+ )
168
+ except Exception as e:
169
+ st.error(f"Error loading models: {e}")
170
+ return
171
+
172
+ # Mode selection
173
+ mode = st.radio("Select Mode", ["Inpainting", "Outpainting"])
174
+
175
+ # Image handling - either from previous generation or new upload
176
+ if "input_image" in st.session_state:
177
+ image = st.session_state["input_image"]
178
+ del st.session_state["input_image"]
179
+ set_new_image(image)
180
+ st.write("Continuing from previous result")
181
+ else:
182
+ uploaded_image = st.file_uploader("Upload image", type=["jpg", "jpeg", "png"])
183
+ if uploaded_image is None:
184
+ st.warning("Please upload an image")
185
+ return
186
+
187
+ if (
188
+ "current_image_name" not in st.session_state
189
+ or st.session_state["current_image_name"] != uploaded_image.name
190
+ ):
191
+ try:
192
+ image = Image.open(uploaded_image).convert("RGB")
193
+ st.session_state["current_image_name"] = uploaded_image.name
194
+ set_new_image(image)
195
+ except Exception as e:
196
+ st.error(f"Error loading image: {e}")
197
+ return
198
+ else:
199
+ image = st.session_state.get("current_image")
200
+ if image is None:
201
+ st.error("Error: Image state is invalid. Please reupload the image.")
202
+ clear_canvas_state()
203
+ return
204
+
205
+ # Add downscale control
206
+ with st.expander("Image Size Control"):
207
+ current_mp = (image.size[0] * image.size[1]) / 1_000_000
208
+ st.write(f"Current image size: {image.size[0]}x{image.size[1]} ({current_mp:.1f}MP)")
209
+
210
+ scale_factor = st.slider(
211
+ "Downscale Factor",
212
+ min_value=0.1,
213
+ max_value=1.0,
214
+ value=1.0,
215
+ step=0.1,
216
+ help="1.0 = original size, 0.5 = half size, etc.",
217
+ )
218
+
219
+ if scale_factor < 1.0 and st.button("Apply Downscaling"):
220
+ image = downscale_image(image, scale_factor)
221
+ set_new_image(image)
222
+ st.rerun()
223
+
224
+ # Resize image with validation
225
+ try:
226
+ original_mp = (image.size[0] * image.size[1]) / 1_000_000
227
+ image = resize(image)
228
+ width, height = image.size
229
+ current_mp = (width * height) / 1_000_000
230
+
231
+ if width % 32 != 0 or height % 32 != 0:
232
+ st.error("Error: Image dimensions must be multiples of 32")
233
+ return
234
+
235
+ st.write(f"Image dimensions: {width}x{height} pixels")
236
+ if original_mp != current_mp:
237
+ st.write(
238
+ f"Image has been resized from {original_mp:.1f}MP to {current_mp:.1f}MP to stay within bounds (0.5MP - 2MP)"
239
+ )
240
+ except Exception as e:
241
+ st.error(f"Error processing image: {e}")
242
+ return
243
+
244
+ if mode == "Outpainting":
245
+ # Outpainting controls
246
+ zoom_all = st.slider("Zoom Out Amount (All Sides)", min_value=1.0, max_value=3.0, value=1.0, step=0.1)
247
+
248
+ with st.expander("Advanced Zoom Controls"):
249
+ st.info("These controls add additional zoom to specific sides")
250
+ col1, col2 = st.columns(2)
251
+ with col1:
252
+ zoom_left = st.slider("Left", min_value=0.0, max_value=1.0, value=0.0, step=0.1)
253
+ zoom_right = st.slider("Right", min_value=0.0, max_value=1.0, value=0.0, step=0.1)
254
+ with col2:
255
+ zoom_up = st.slider("Up", min_value=0.0, max_value=1.0, value=0.0, step=0.1)
256
+ zoom_down = st.slider("Down", min_value=0.0, max_value=1.0, value=0.0, step=0.1)
257
+
258
+ overlap = st.slider("Overlap", min_value=0.01, max_value=0.25, value=0.01, step=0.01)
259
+
260
+ # Generate bordered image and mask
261
+ image_for_generation, mask = add_border_and_mask(
262
+ image,
263
+ zoom_all=zoom_all,
264
+ zoom_left=zoom_left,
265
+ zoom_right=zoom_right,
266
+ zoom_up=zoom_up,
267
+ zoom_down=zoom_down,
268
+ overlap=overlap,
269
+ )
270
+ width, height = image_for_generation.size
271
+
272
+ # Show preview
273
+ col1, col2 = st.columns(2)
274
+ with col1:
275
+ st.image(image_for_generation, caption="Image with Border")
276
+ with col2:
277
+ st.image(mask, caption="Mask (white areas will be generated)")
278
+
279
+ else: # Inpainting mode
280
+ # Canvas setup with dimension tracking
281
+ canvas_key = f"canvas_{width}_{height}"
282
+ if "last_image_dims" not in st.session_state:
283
+ st.session_state.last_image_dims = (width, height)
284
+ elif st.session_state.last_image_dims != (width, height):
285
+ clear_canvas_state()
286
+ st.session_state.last_image_dims = (width, height)
287
+ st.rerun()
288
+
289
+ try:
290
+ canvas_result = st_canvas(
291
+ fill_color="rgba(255, 255, 255, 0.0)",
292
+ stroke_width=st.slider("Brush size", 1, 500, 50),
293
+ stroke_color="#fff",
294
+ background_image=image,
295
+ height=height,
296
+ width=width,
297
+ drawing_mode="freedraw",
298
+ key=canvas_key,
299
+ display_toolbar=True,
300
+ )
301
+ except Exception as e:
302
+ st.error(f"Error creating canvas: {e}")
303
+ clear_canvas_state()
304
+ st.rerun()
305
+ return
306
+
307
+ # Sampling parameters
308
+ num_steps = int(st.number_input("Number of steps", min_value=1, value=50))
309
+ guidance = float(st.number_input("Guidance", min_value=1.0, value=30.0))
310
+ seed_str = st.text_input("Seed")
311
+ if seed_str.isdecimal():
312
+ seed = int(seed_str)
313
+ else:
314
+ st.info("No seed set, using random seed")
315
+ seed = None
316
+
317
+ save_samples = st.checkbox("Save samples?", True)
318
+ add_sampling_metadata = st.checkbox("Add sampling parameters to metadata?", True)
319
+
320
+ # Prompt input
321
+ prompt = st_keyup("Enter a prompt", value="", debounce=300, key="interactive_text")
322
+
323
+ # Setup output path
324
+ output_name = os.path.join(output_dir, "img_{idx}.jpg")
325
+ if not os.path.exists(output_dir):
326
+ os.makedirs(output_dir)
327
+ idx = 0
328
+ else:
329
+ fns = [fn for fn in iglob(output_name.format(idx="*")) if re.search(r"img_[0-9]+\.jpg$", fn)]
330
+ idx = len(fns)
331
+
332
+ if st.button("Generate"):
333
+ valid_input = False
334
+
335
+ if mode == "Inpainting" and canvas_result.image_data is not None:
336
+ valid_input = True
337
+ # Create mask from canvas
338
+ try:
339
+ mask = Image.fromarray(canvas_result.image_data)
340
+ mask = mask.getchannel("A") # Get alpha channel
341
+ mask_array = np.array(mask)
342
+ mask_array = (mask_array > 0).astype(np.uint8) * 255
343
+ mask = Image.fromarray(mask_array)
344
+ image_for_generation = image
345
+ except Exception as e:
346
+ st.error(f"Error creating mask: {e}")
347
+ return
348
+
349
+ elif mode == "Outpainting":
350
+ valid_input = True
351
+ # image_for_generation and mask are already set above
352
+
353
+ if not valid_input:
354
+ st.error("Please draw a mask or configure outpainting settings")
355
+ return
356
+
357
+ # Create temporary files
358
+ with (
359
+ tempfile.NamedTemporaryFile(suffix=".png", delete=False) as tmp_img,
360
+ tempfile.NamedTemporaryFile(suffix=".png", delete=False) as tmp_mask,
361
+ ):
362
+ try:
363
+ image_for_generation.save(tmp_img.name)
364
+ mask.save(tmp_mask.name)
365
+ except Exception as e:
366
+ st.error(f"Error saving temporary files: {e}")
367
+ return
368
+
369
+ try:
370
+ # Generate inpainting/outpainting
371
+ rng = torch.Generator(device="cpu")
372
+ if seed is None:
373
+ seed = rng.seed()
374
+
375
+ print(f"Generating with seed {seed}:\n{prompt}")
376
+ t0 = time.perf_counter()
377
+
378
+ x = get_noise(
379
+ 1,
380
+ height,
381
+ width,
382
+ device=torch_device,
383
+ dtype=torch.bfloat16,
384
+ seed=seed,
385
+ )
386
+
387
+ if offload:
388
+ t5, clip, ae = t5.to(torch_device), clip.to(torch_device), ae.to(torch_device)
389
+
390
+ inp = prepare_fill(
391
+ t5,
392
+ clip,
393
+ x,
394
+ prompt=prompt,
395
+ ae=ae,
396
+ img_cond_path=tmp_img.name,
397
+ mask_path=tmp_mask.name,
398
+ )
399
+
400
+ timesteps = get_schedule(num_steps, inp["img"].shape[1], shift=True)
401
+
402
+ if offload:
403
+ t5, clip, ae = t5.cpu(), clip.cpu(), ae.cpu()
404
+ torch.cuda.empty_cache()
405
+ model = model.to(torch_device)
406
+
407
+ x = denoise(model, **inp, timesteps=timesteps, guidance=guidance)
408
+
409
+ if offload:
410
+ model.cpu()
411
+ torch.cuda.empty_cache()
412
+ ae.decoder.to(x.device)
413
+
414
+ x = unpack(x.float(), height, width)
415
+ with torch.autocast(device_type=torch_device.type, dtype=torch.bfloat16):
416
+ x = ae.decode(x)
417
+
418
+ t1 = time.perf_counter()
419
+ print(f"Done in {t1 - t0:.1f}s")
420
+
421
+ # Process and display result
422
+ x = x.clamp(-1, 1)
423
+ x = embed_watermark(x.float())
424
+ x = rearrange(x[0], "c h w -> h w c")
425
+ img = Image.fromarray((127.5 * (x + 1.0)).cpu().byte().numpy())
426
+
427
+ nsfw_score = [x["score"] for x in nsfw_classifier(img) if x["label"] == "nsfw"][0]
428
+
429
+ if nsfw_score < NSFW_THRESHOLD:
430
+ buffer = BytesIO()
431
+ exif_data = Image.Exif()
432
+ exif_data[ExifTags.Base.Software] = "AI generated;inpainting;flux"
433
+ exif_data[ExifTags.Base.Make] = "Black Forest Labs"
434
+ exif_data[ExifTags.Base.Model] = name
435
+ if add_sampling_metadata:
436
+ exif_data[ExifTags.Base.ImageDescription] = prompt
437
+ img.save(buffer, format="jpeg", exif=exif_data, quality=95, subsampling=0)
438
+
439
+ img_bytes = buffer.getvalue()
440
+ if save_samples:
441
+ fn = output_name.format(idx=idx)
442
+ print(f"Saving {fn}")
443
+ with open(fn, "wb") as file:
444
+ file.write(img_bytes)
445
+
446
+ if track_usage:
447
+ track_usage_via_api(name, 1)
448
+
449
+ st.session_state["samples"] = {
450
+ "prompt": prompt,
451
+ "img": img,
452
+ "seed": seed,
453
+ "bytes": img_bytes,
454
+ }
455
+ else:
456
+ st.warning("Your generated image may contain NSFW content.")
457
+ st.session_state["samples"] = None
458
+
459
+ except Exception as e:
460
+ st.error(f"Error during generation: {e}")
461
+ return
462
+ finally:
463
+ # Clean up temporary files
464
+ try:
465
+ os.unlink(tmp_img.name)
466
+ os.unlink(tmp_mask.name)
467
+ except Exception as e:
468
+ print(f"Error cleaning up temporary files: {e}")
469
+
470
+ # Display results
471
+ samples = st.session_state.get("samples", None)
472
+ if samples is not None:
473
+ st.image(samples["img"], caption=samples["prompt"])
474
+ col1, col2 = st.columns(2)
475
+ with col1:
476
+ st.download_button(
477
+ "Download full-resolution",
478
+ samples["bytes"],
479
+ file_name="generated.jpg",
480
+ mime="image/jpg",
481
+ )
482
+ with col2:
483
+ if st.button("Continue from this image"):
484
+ # Store the generated image
485
+ new_image = samples["img"]
486
+ # Clear ALL canvas state
487
+ clear_canvas_state()
488
+ if "samples" in st.session_state:
489
+ del st.session_state["samples"]
490
+ # Set as current image
491
+ st.session_state["current_image"] = new_image
492
+ st.rerun()
493
+
494
+ st.write(f"Seed: {samples['seed']}")
495
+
496
+
497
+ def app():
498
+ Fire(main)
499
+
500
+
501
+ if __name__ == "__main__":
502
+ st.set_page_config(layout="wide")
503
+ app()