Files changed (1) hide show
  1. app.py +161 -582
app.py CHANGED
@@ -7,7 +7,7 @@ from gradio_imageslider import ImageSlider
7
  from huggingface_hub import hf_hub_download
8
  from controlnet_union import ControlNetModel_Union
9
  from pipeline_fill_sd_xl import StableDiffusionXLFillPipeline
10
- from PIL import Image, ImageDraw
11
  import numpy as np
12
  # from gradio.sketch.run import create
13
 
@@ -19,6 +19,7 @@ MODELS = {
19
  "SatPony-Lightning": "John6666/satpony-lightning-v2-sdxl"
20
  }
21
 
 
22
  config_file = hf_hub_download(
23
  "xinsir/controlnet-union-sdxl-1.0",
24
  filename="config_promax.json",
@@ -49,6 +50,7 @@ pipe.to("cuda")
49
  print(pipe)
50
 
51
  def load_default_pipeline():
 
52
  global pipe
53
  pipe = StableDiffusionXLFillPipeline.from_pretrained(
54
  "SG161222/RealVisXL_V5.0_Lightning",
@@ -56,15 +58,39 @@ def load_default_pipeline():
56
  vae=vae,
57
  controlnet=model,
58
  ).to("cuda")
59
- return gr.update(value="Default pipeline loaded!")
 
60
 
61
  @spaces.GPU(duration=7)
62
  def fill_image(prompt, image, model_selection, paste_back):
 
 
 
 
63
  print(f"Received image: {image}")
64
  if image is None:
65
  yield None, None
66
  return
67
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68
  (
69
  prompt_embeds,
70
  negative_prompt_embeds,
@@ -72,298 +98,75 @@ def fill_image(prompt, image, model_selection, paste_back):
72
  negative_pooled_prompt_embeds,
73
  ) = pipe.encode_prompt(prompt, "cuda", True)
74
  source = image["background"]
 
75
  mask = image["layers"][0]
 
76
  alpha_channel = mask.split()[3]
77
- binary_mask = alpha_channel.point(lambda p: p > 0 and 255)
 
 
 
 
 
 
 
78
  cnet_image = source.copy()
 
79
  cnet_image.paste(0, (0, 0), binary_mask)
80
 
81
- for image in pipe(
 
82
  prompt_embeds=prompt_embeds,
83
  negative_prompt_embeds=negative_prompt_embeds,
84
  pooled_prompt_embeds=pooled_prompt_embeds,
85
  negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
86
  image=cnet_image,
 
 
 
 
87
  ):
88
- yield image, cnet_image
89
 
90
  print(f"{model_selection=}")
91
  print(f"{paste_back=}")
 
92
  if paste_back:
93
- image = image.convert("RGBA")
94
- cnet_image.paste(image, (0, 0), binary_mask)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95
  else:
96
- cnet_image = image
97
- yield source, cnet_image
98
 
99
  def clear_result():
100
  return gr.update(value=None)
101
 
102
- def can_expand(source_width, source_height, target_width, target_height, alignment):
103
- if alignment in ("Left", "Right") and source_width >= target_width:
104
- return False
105
- if alignment in ("Top", "Bottom") and source_height >= target_height:
106
- return False
107
- return True
108
-
109
- def prepare_image_and_mask(image, width, height, overlap_percentage, resize_option, custom_resize_percentage, alignment, overlap_left, overlap_right, overlap_top, overlap_bottom, x_offset=None, y_offset=None):
110
- target_size = (width, height)
111
- scale_factor = min(target_size[0] / image.width, target_size[1] / image.height)
112
- new_width = int(image.width * scale_factor)
113
- new_height = int(image.height * scale_factor)
114
-
115
- source = image.resize((new_width, new_height), Image.LANCZOS)
116
-
117
- if resize_option == "Full":
118
- resize_percentage = 100
119
- elif resize_option == "80%":
120
- resize_percentage = 80
121
- elif resize_option == "66%":
122
- resize_percentage = 66
123
- elif resize_option == "50%":
124
- resize_percentage = 50
125
- elif resize_option == "33%":
126
- resize_percentage = 33
127
- elif resize_option == "25%":
128
- resize_percentage = 25
129
- else: # Custom
130
- resize_percentage = custom_resize_percentage
131
- resize_factor = resize_percentage / 100
132
- new_width = int(source.width * resize_factor)
133
- new_height = int(source.height * resize_factor)
134
- new_width = max(new_width, 64)
135
- new_height = max(new_height, 64)
136
- source = source.resize((new_width, new_height), Image.LANCZOS)
137
-
138
- overlap_x = int(new_width * (overlap_percentage / 100))
139
- overlap_y = int(new_height * (overlap_percentage / 100))
140
- overlap_x = max(overlap_x, 1)
141
- overlap_y = max(overlap_y, 1)
142
-
143
- if alignment == "Middle":
144
- margin_x = (target_size[0] - new_width) // 2
145
- margin_y = (target_size[1] - new_height) // 2
146
- elif alignment == "Left":
147
- margin_x = 0
148
- margin_y = (target_size[1] - new_height) // 2
149
- elif alignment == "Right":
150
- margin_x = target_size[0] - new_width
151
- margin_y = (target_size[1] - new_height) // 2
152
- elif alignment == "Top":
153
- margin_x = (target_size[0] - new_width) // 2
154
- margin_y = 0
155
- elif alignment == "Bottom":
156
- margin_x = (target_size[0] - new_width) // 2
157
- margin_y = target_size[1] - new_height
158
-
159
- # Ensure x_offset and y_offset are not None
160
- x_offset = x_offset if x_offset is not None else 0
161
- y_offset = y_offset if y_offset is not None else 0
162
-
163
- margin_x = max(0, min(margin_x + x_offset, target_size[0] - new_width))
164
- margin_y = max(0, min(margin_y + y_offset, target_size[1] - new_height))
165
-
166
- if image.mode == "RGBA":
167
- background = Image.new("RGBA", target_size, (255, 255, 255, 255))
168
- else:
169
- background = Image.new("RGB", target_size, (255, 255, 255))
170
-
171
- background.paste(source, (margin_x, margin_y))
172
-
173
- # background = Image.new('RGB', target_size, (255, 255, 255))
174
- # Paste the source (resized image) onto the background
175
- # Paste the source image (resized) onto the background
176
- # If the source has alpha, it will be preserved in the background
177
-
178
-
179
- # Create the generated mask (L mode)
180
- mask = Image.new("L", target_size, 255)
181
- mask_draw = ImageDraw.Draw(mask)
182
- white_gaps_patch = 2
183
-
184
- left_overlap = margin_x + overlap_x if overlap_left else margin_x + white_gaps_patch
185
- right_overlap = margin_x + new_width - overlap_x if overlap_right else margin_x + new_width - white_gaps_patch
186
- top_overlap = margin_y + overlap_y if overlap_top else margin_y + white_gaps_patch
187
- bottom_overlap = margin_y + new_height - overlap_y if overlap_bottom else margin_y + new_height - white_gaps_patch
188
-
189
- mask_draw.rectangle([
190
- (left_overlap, top_overlap),
191
- (right_overlap, bottom_overlap)
192
- ], fill=0)
193
-
194
- return background, mask
195
-
196
- def preview_image_and_mask(image, width, height, overlap_percentage, resize_option, custom_resize_percentage, alignment, overlap_left, overlap_right, overlap_top, overlap_bottom, x_offset, y_offset):
197
- background, mask = prepare_image_and_mask(
198
- image,
199
- width,
200
- height,
201
- overlap_percentage,
202
- resize_option,
203
- custom_resize_percentage,
204
- alignment,
205
- overlap_left,
206
- overlap_right,
207
- overlap_top,
208
- overlap_bottom,
209
- x_offset,
210
- y_offset
211
- )
212
- preview = background.copy().convert('RGBA')
213
- red_overlay = Image.new('RGBA', background.size, (255, 0, 0, 64))
214
- red_mask = Image.new('RGBA', background.size, (0, 0, 0, 0))
215
- red_mask.paste(red_overlay, (0, 0), mask)
216
- preview = Image.alpha_composite(preview, red_mask)
217
- return preview
218
-
219
- @spaces.GPU(duration=12)
220
- def inpaint(prompt, image, inpaint_model, paste_back):
221
- global pipe
222
- if pipe.config.model_name != MODELS[model_name]:
223
- pipe = StableDiffusionXLFillPipeline.from_pretrained(
224
- MODELS[model_name],
225
- torch_dtype=torch.float16,
226
- vae=vae,
227
- controlnet=model,
228
- ).to("cuda")
229
- print(f"Loaded new SDXL model: {pipe.config.model_name}")
230
- mask = Image.fromarray(image["mask"]).convert("L")
231
- image = Image.fromarray(image["image"])
232
- inpaint_final_prompt = f"score_9, score_8_up, score_7_up, {prompt}"
233
- result = pipe(prompt=inpaint_final_prompt, image=image, mask_image=mask).images[0]
234
- if paste_back:
235
- result.paste(image, (0, 0), Image.fromarray(255 - np.array(mask)))
236
- return result
237
-
238
- @spaces.GPU(duration=7)
239
- def outpaint(image, width, height, overlap_percentage, num_inference_steps, resize_option, custom_resize_percentage, prompt_input, alignment, overlap_left, overlap_right, overlap_top, overlap_bottom, x_offset, y_offset):
240
- background, mask = prepare_image_and_mask(image, width, height, overlap_percentage, resize_option, custom_resize_percentage, alignment, overlap_left, overlap_right, overlap_top, overlap_bottom, x_offset, y_offset)
241
- if not can_expand(background.width, background.height, width, height, alignment):
242
- alignment = "Middle"
243
-
244
- # Original alpha is 0 where transparent (or 255 where opaque)
245
- original_alpha = background.split()[3] if background.mode == "RGBA" else Image.new("L", background.size, 255)
246
-
247
- # Generated mask is 0 where you want to paint (from image["layers"][0])
248
- # If "layers"[0] is not alpha, convert it to L-mode
249
- mask = mask.convert("L") if mask.mode != "L" else mask
250
-
251
- # Combine the two masks: 0 where either the original is transparent OR the generated mask is active
252
- combined_mask = ImageChops.logical_or(original_alpha, mask)
253
- # After generating the combined_mask
254
- if cnet_image.mode == "RGBA":
255
- # Create a new alpha channel based on the mask
256
- new_alpha = combined_mask.convert("L")
257
- cnet_image = Image.merge("RGBA", cnet_image.split()[:3] + (new_alpha,))
258
- else:
259
- # If no alpha, you can't use the mask — just use the background as is
260
- cnet_image = background.copy()
261
- # Use the combined_mask in the pipeline
262
- #cnet_image = background.copy()
263
- # cnet_image.paste(0, (0, 0), combined_mask) # Overlay black on combined_mask area
264
-
265
- final_prompt = f"score_9, score_8_up, score_7_up, {prompt_input} , high quality, 4k"
266
- print(f"Outpainting using SDXL model: {pipe.config.model_name}")
267
- (
268
- prompt_embeds,
269
- negative_prompt_embeds,
270
- pooled_prompt_embeds,
271
- negative_pooled_prompt_embeds,
272
- ) = pipe.encode_prompt(final_prompt, "cuda", True)
273
- for image in pipe(
274
- prompt_embeds=prompt_embeds,
275
- negative_prompt_embeds=negative_prompt_embeds,
276
- pooled_prompt_embeds=pooled_prompt_embeds,
277
- negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
278
- image=cnet_image,
279
- num_inference_steps=num_inference_steps
280
- ):
281
- yield cnet_image, image
282
- image = image.convert("RGBA")
283
- # If the pipeline uses alpha as the mask, invert it to get 255 where to paint
284
- filled_mask = combined_mask.point(lambda p: 255 - p)
285
- # Paste the result using the mask to preserve transparency
286
- cnet_image.paste(image, (0, 0), filled_mask) # Only modify areas where filled_mask is 255 (i.e., original transparent + generated mask area)
287
- yield background, cnet_image
288
-
289
- @spaces.GPU(duration=7)
290
- def infer(image, width, height, overlap_percentage, num_inference_steps, resize_option, custom_resize_percentage, prompt_input, alignment, overlap_left, overlap_right, overlap_top, overlap_bottom, x_offset, y_offset):
291
- background, mask = prepare_image_and_mask(image, width, height, overlap_percentage, resize_option, custom_resize_percentage, alignment, overlap_left, overlap_right, overlap_top, overlap_bottom, x_offset, y_offset)
292
- if not can_expand(background.width, background.height, width, height, alignment):
293
- alignment = "Middle"
294
- cnet_image = background.copy()
295
- cnet_image.paste(0, (0, 0), mask)
296
- final_prompt = f"{prompt_input} , high quality, 4k"
297
- (
298
- prompt_embeds,
299
- negative_prompt_embeds,
300
- pooled_prompt_embeds,
301
- negative_pooled_prompt_embeds,
302
- ) = pipe.encode_prompt(final_prompt, "cuda", True)
303
- for image in pipe(
304
- prompt_embeds=prompt_embeds,
305
- negative_prompt_embeds=negative_prompt_embeds,
306
- pooled_prompt_embeds=pooled_prompt_embeds,
307
- negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
308
- image=cnet_image,
309
- num_inference_steps=num_inference_steps
310
- ):
311
- yield cnet_image, image
312
- image = image.convert("RGBA")
313
- cnet_image.paste(image, (0, 0), mask)
314
- yield background, cnet_image
315
-
316
  def use_output_as_input(output_image):
317
- return gr.update(value=output_image[1])
318
-
319
- def preload_presets(target_ratio, ui_width, ui_height):
320
- if target_ratio == "9:16":
321
- changed_width = 768
322
- changed_height = 1280
323
- return changed_width, changed_height, gr.update()
324
- elif target_ratio == "2:3":
325
- changed_width = 1024
326
- changed_height = 1536
327
- return changed_width, changed_height, gr.update()
328
- elif target_ratio == "16:9":
329
- changed_width = 1280
330
- changed_height = 768
331
- return changed_width, changed_height, gr.update()
332
- elif target_ratio == "1:1":
333
- changed_width = 1024
334
- changed_height = 1024
335
- return changed_width, changed_height, gr.update()
336
- elif target_ratio == "Custom":
337
- return ui_width, ui_height, gr.update(open=True)
338
- else:
339
- return ui_width, ui_height, gr.update()
340
-
341
- def select_the_right_preset(user_width, user_height):
342
- if user_width == 720 and user_height == 1280:
343
- return "9:16"
344
- elif user_width == 1024 and user_height == 1536:
345
- return "2:3"
346
- elif user_width == 1280 and user_height == 720:
347
- return "16:9"
348
- elif user_width == 1024 and user_height == 1024:
349
- return "1:1"
350
- else:
351
- return "Custom"
352
-
353
- def toggle_custom_resize_slider(resize_option):
354
- return gr.update(visible=(resize_option == "Custom"))
355
-
356
- def update_history(new_image, history):
357
- if history is None:
358
- history = []
359
- history.insert(0, new_image)
360
- return history
361
-
362
- def clear_cache():
363
- global pipe
364
- pipe = None
365
- torch.cuda.empty_cache()
366
- return gr.update(value="Cache cleared!")
367
 
368
  css = """
369
  .nulgradio-container {
@@ -373,25 +176,22 @@ css = """
373
  overflow-y: scroll !important;
374
  padding: 10px 40px !important;
375
  }
376
- div#component-17 {
377
  height: auto !important;
378
  }
379
 
380
-
381
  @media screen and (max-width: 600px) {
382
  .img-row{
383
  display: block !important;
384
  margin-bottom: 20px !important;
385
  }
386
- div#component-16 {
387
- display: block !important;
388
- }
389
  }
390
 
391
  """
392
 
393
- title = """<h1 align="center">Diffusers Image Outpaint</h1>
394
- <div align="center">Drop an image you would like to extend, pick your expected ratio and hit Generate.</div>
395
  <div style="display: flex; justify-content: center; align-items: center; text-align: center;">
396
  <p style="display: flex;gap: 6px;">
397
  <a href="https://huggingface.co/spaces/fffiloni/diffusers-image-outpout?duplicate=true">
@@ -401,310 +201,89 @@ title = """<h1 align="center">Diffusers Image Outpaint</h1>
401
  </div>
402
  """
403
 
404
- # with gr.Blocks() as sketchapp:
405
- # sketchapp = create("test.py", "test.py.json")
406
-
407
-
408
  with gr.Blocks(css=css, fill_height=True) as demo:
409
- gr.Markdown("# Diffusers Inpaint and Outpaint")
410
- with gr.Tabs():
411
- with gr.TabItem("Inpaint"):
 
 
412
  with gr.Column():
413
- with gr.Row():
414
- with gr.Column():
415
- prompt = gr.Textbox(
416
- label="Prompt",
417
- info="Describe what to inpaint the mask with",
418
- lines=3,
419
- )
420
- with gr.Column():
421
- model_selection = gr.Dropdown(
422
- choices=list(MODELS.keys()),
423
- value="RealVisXL V5.0 Lightning",
424
- label="Model",
425
- )
426
- with gr.Row():
427
- run_button = gr.Button("Generate")
428
- paste_back = gr.Checkbox(True, label="Paste back original")
429
- with gr.Row(equal_height=False):
430
- input_image = gr.ImageMask(
431
- type="pil", label="Input Image", layers=True, elem_classes="img-row"
432
- )
433
- result = ImageSlider(
434
- interactive=False,
435
- label="Generated Image",
436
- elem_classes="img-row"
437
- )
438
- use_as_input_button = gr.Button("Use as Input Image", visible=False)
439
- use_as_input_button.click(
440
- fn=use_output_as_input, inputs=[result], outputs=[input_image]
441
- )
442
- run_button.click(
443
- fn=clear_result,
444
- inputs=None,
445
- outputs=result,
446
- ).then(
447
- fn=lambda: gr.update(visible=False),
448
- inputs=None,
449
- outputs=use_as_input_button,
450
- ).then(
451
- fn=fill_image,
452
- inputs=[prompt, input_image, model_selection, paste_back],
453
- outputs=[result],
454
- ).then(
455
- fn=lambda: gr.update(visible=True),
456
- inputs=None,
457
- outputs=use_as_input_button,
458
- )
459
- prompt.submit(
460
- fn=clear_result,
461
- inputs=None,
462
- outputs=result,
463
- ).then(
464
- fn=lambda: gr.update(visible=False),
465
- inputs=None,
466
- outputs=use_as_input_button,
467
- ).then(
468
- fn=fill_image,
469
- inputs=[prompt, input_image, model_selection, paste_back],
470
- outputs=[result],
471
- ).then(
472
- fn=lambda: gr.update(visible=True),
473
- inputs=None,
474
- outputs=use_as_input_button,
475
  )
476
- with gr.TabItem("Outpaint"):
477
  with gr.Column():
478
- with gr.Row():
479
- with gr.Column():
480
- input_image_outpaint = gr.Image(
481
- type="pil",
482
- label="Input Image"
483
- )
484
- with gr.Row():
485
- with gr.Column(scale=2):
486
- prompt_input = gr.Textbox(label="Prompt (Optional)")
487
- with gr.Column(scale=1):
488
- runout_button = gr.Button("Generate")
489
- with gr.Row():
490
- target_ratio = gr.Radio(
491
- label="Expected Ratio",
492
- choices=["2:3", "9:16", "16:9", "1:1", "Custom"],
493
- value="1:1",
494
- scale=2
495
- )
496
- alignment_dropdown = gr.Dropdown(
497
- choices=["Middle", "Left", "Right", "Top", "Bottom"],
498
- value="Middle",
499
- label="Alignment"
500
- )
501
- with gr.Accordion(label="Advanced settings", open=False) as settings_panel:
502
- with gr.Column():
503
- with gr.Row():
504
- width_slider = gr.Slider(
505
- label="Target Width",
506
- minimum=720,
507
- maximum=1536,
508
- step=8,
509
- value=1024,
510
- )
511
- height_slider = gr.Slider(
512
- label="Target Height",
513
- minimum=720,
514
- maximum=1536,
515
- step=8,
516
- value=1024,
517
- )
518
- num_inference_steps = gr.Slider(label="Steps", minimum=4, maximum=12, step=1, value=8)
519
- with gr.Group():
520
- overlap_percentage = gr.Slider(
521
- label="Mask overlap (%)",
522
- minimum=1,
523
- maximum=80,
524
- value=10,
525
- step=1
526
- )
527
- with gr.Row():
528
- overlap_top = gr.Checkbox(label="Overlap Top", value=True)
529
- overlap_right = gr.Checkbox(label="Overlap Right", value=True)
530
- with gr.Row():
531
- overlap_left = gr.Checkbox(label="Overlap Left", value=True)
532
- overlap_bottom = gr.Checkbox(label="Overlap Bottom", value=True)
533
- with gr.Row():
534
- x_offset_slider = gr.Slider(
535
- label="X Offset",
536
- minimum=-100,
537
- maximum=100,
538
- value=0,
539
- step=1
540
- )
541
- y_offset_slider = gr.Slider(
542
- label="Y Offset",
543
- minimum=-100,
544
- maximum=100,
545
- value=0,
546
- step=1
547
- )
548
- with gr.Row():
549
- resize_option = gr.Radio(
550
- label="Resize input image",
551
- choices=["Full", "80%", "66%", "50%", "33%", "25%", "Custom"],
552
- value="Full"
553
- )
554
- custom_resize_percentage = gr.Slider(
555
- label="Custom resize (%)",
556
- minimum=1,
557
- maximum=100,
558
- step=1,
559
- value=50,
560
- visible=False
561
- )
562
- with gr.Column():
563
- preview_button = gr.Button("Preview alignment and mask")
564
- # gr.Examples(
565
- # examples=[
566
- # ["./examples/example_1.webp", 1280, 720, "Middle"],
567
- # ["./examples/example_2.jpg", 1440, 810, "Left"],
568
- # ["./examples/example_3.jpg", 1024, 1024, "Top"],
569
- # ["./examples/example_3.jpg", 1024, 1024, "Bottom"],
570
- # ],
571
- # inputs=[input_image_outpaint, width_slider, height_slider, alignment_dropdown],
572
- # )
573
- with gr.Column():
574
- result_outpaint = ImageSlider(
575
- interactive=False,
576
- label="Generated Image",
577
- )
578
- use_as_input_button_outpaint = gr.Button("Use as Input Image", visible=False)
579
- history_gallery = gr.Gallery(label="History", columns=6, object_fit="contain", interactive=False)
580
- preview_image = gr.Image(label="Preview")
581
- with gr.TabItem("Misc"):
582
- with gr.Column():
583
- clear_cache_button = gr.Button("Clear CUDA Cache")
584
- clear_cache_message = gr.Markdown("")
585
- clear_cache_button.click(
586
- fn=clear_cache,
587
- inputs=None,
588
- outputs=clear_cache_message,
589
- )
590
- load_default_button = gr.Button("Load Default Pipeline")
591
- load_default_message = gr.Markdown("")
592
- load_default_button.click(
593
- fn=load_default_pipeline,
594
- inputs=None,
595
- outputs=load_default_message,
596
  )
597
- # with gr.TabItem("Sketch"):
598
- # sketchapp.render()
599
-
600
- target_ratio.change(
601
- fn=preload_presets,
602
- inputs=[target_ratio, width_slider, height_slider],
603
- outputs=[width_slider, height_slider, settings_panel],
604
- queue=False
605
- )
606
-
607
- width_slider.change(
608
- fn=select_the_right_preset,
609
- inputs=[width_slider, height_slider],
610
- outputs=[target_ratio],
611
- queue=False
612
- )
613
-
614
- height_slider.change(
615
- fn=select_the_right_preset,
616
- inputs=[width_slider, height_slider],
617
- outputs=[target_ratio],
618
- queue=False
619
- )
620
-
621
- resize_option.change(
622
- fn=toggle_custom_resize_slider,
623
- inputs=[resize_option],
624
- outputs=[custom_resize_percentage],
625
- queue=False
626
- )
627
-
628
- use_as_input_button_outpaint.click(
629
- fn=use_output_as_input,
630
- inputs=[result_outpaint],
631
- outputs=[input_image_outpaint]
632
- )
633
- runout_button.click(
634
- fn=clear_result,
635
- inputs=None,
636
- outputs=result_outpaint,
637
- ).then(
638
- fn=infer,
639
- inputs=[
640
- input_image_outpaint,
641
- width_slider,
642
- height_slider,
643
- overlap_percentage,
644
- num_inference_steps,
645
- resize_option,
646
- custom_resize_percentage,
647
- prompt_input,
648
- alignment_dropdown,
649
- overlap_left,
650
- overlap_right,
651
- overlap_top,
652
- overlap_bottom,
653
- x_offset_slider,
654
- y_offset_slider
655
- ],
656
- outputs=[result_outpaint],
657
- ).then(
658
- fn=lambda x, history: update_history(x[1], history),
659
- inputs=[result_outpaint, history_gallery],
660
- outputs=history_gallery,
661
- ).then(
662
- fn=lambda: gr.update(visible=True),
663
- inputs=None,
664
- outputs=[use_as_input_button_outpaint],
665
- )
666
-
667
- prompt_input.submit(
668
- fn=clear_result,
669
- inputs=None,
670
- outputs=result_outpaint,
671
- ).then(
672
- fn=infer,
673
- inputs=[
674
- input_image_outpaint,
675
- width_slider,
676
- height_slider,
677
- overlap_percentage,
678
- num_inference_steps,
679
- resize_option,
680
- custom_resize_percentage,
681
- prompt_input,
682
- alignment_dropdown,
683
- overlap_left,
684
- overlap_right,
685
- overlap_top,
686
- overlap_bottom,
687
- x_offset_slider,
688
- y_offset_slider
689
- ],
690
- outputs=[result_outpaint],
691
- ).then(
692
- fn=lambda x, history: update_history(x[1], history),
693
- inputs=[result_outpaint, history_gallery],
694
- outputs=history_gallery,
695
- ).then(
696
- fn=lambda: gr.update(visible=True),
697
- inputs=None,
698
- outputs=[use_as_input_button_outpaint],
699
- )
700
-
701
-
702
- preview_button.click(
703
- fn=preview_image_and_mask,
704
- inputs=[input_image_outpaint, width_slider, height_slider, overlap_percentage, resize_option, custom_resize_percentage, alignment_dropdown,
705
- overlap_left, overlap_right, overlap_top, overlap_bottom, x_offset_slider, y_offset_slider],
706
- outputs=[preview_image],
707
- queue=False
708
- )
709
-
710
- demo.queue(max_size=10).launch(show_error=True)
 
7
  from huggingface_hub import hf_hub_download
8
  from controlnet_union import ControlNetModel_Union
9
  from pipeline_fill_sd_xl import StableDiffusionXLFillPipeline
10
+ from PIL import Image, ImageFilter
11
  import numpy as np
12
  # from gradio.sketch.run import create
13
 
 
19
  "SatPony-Lightning": "John6666/satpony-lightning-v2-sdxl"
20
  }
21
 
22
+ # --- ControlNet and Pipeline Setup (Retained) ---
23
  config_file = hf_hub_download(
24
  "xinsir/controlnet-union-sdxl-1.0",
25
  filename="config_promax.json",
 
50
  print(pipe)
51
 
52
  def load_default_pipeline():
53
+ """仅保留,但当前 Inpaint 逻辑未直接使用,可以删除,但保留以防将来扩展。"""
54
  global pipe
55
  pipe = StableDiffusionXLFillPipeline.from_pretrained(
56
  "SG161222/RealVisXL_V5.0_Lightning",
 
58
  vae=vae,
59
  controlnet=model,
60
  ).to("cuda")
61
+ # 此函数原用于 Misc 选项卡,现在无需返回 gr.update
62
+ print("Default pipeline loaded!")
63
 
64
  @spaces.GPU(duration=7)
65
  def fill_image(prompt, image, model_selection, paste_back):
66
+ """
67
+ 处理 ImageMask(gr.ImageMask)输入的 fill/repair 流程。
68
+ 在这里对用户绘制的 mask 做默认 5% 膨胀。
69
+ """
70
  print(f"Received image: {image}")
71
  if image is None:
72
  yield None, None
73
  return
74
 
75
+ # 如果用户选择了不同的模型 key,则加载对应预训练仓库
76
+ # 注意:此逻辑原 Outpaint 中有,Inpaint 中缺失,现在补充以支持模型切换
77
+ global pipe
78
+ if model_selection in MODELS and pipe.config.model_name != MODELS[model_selection]:
79
+ # 释放旧模型显存
80
+ del pipe
81
+ torch.cuda.empty_cache()
82
+ pipe = StableDiffusionXLFillPipeline.from_pretrained(
83
+ MODELS[model_selection],
84
+ torch_dtype=torch.float16,
85
+ vae=vae,
86
+ controlnet=model,
87
+ variant="fp16", # 保持 variant 设置
88
+ )
89
+ pipe.scheduler = TCDScheduler.from_config(pipe.scheduler.config)
90
+ pipe.to("cuda")
91
+ print(f"Loaded new SDXL model: {pipe.config.model_name}")
92
+
93
+
94
  (
95
  prompt_embeds,
96
  negative_prompt_embeds,
 
98
  negative_pooled_prompt_embeds,
99
  ) = pipe.encode_prompt(prompt, "cuda", True)
100
  source = image["background"]
101
+ # 用户绘制的 mask layer(通常是 RGBA)
102
  mask = image["layers"][0]
103
+ # 取 alpha 通道并转为二值 mask(255 表示 mask 区域)
104
  alpha_channel = mask.split()[3]
105
+ binary_mask = alpha_channel.point(lambda p: 255 if p > 0 else 0).convert("L")
106
+
107
+ # ==== 扩大 5%(针对 fill_image 的二值 mask) ====
108
+ expand_px = max(1, int(min(binary_mask.width, binary_mask.height) * 0.05))
109
+ kernel_size = expand_px * 2 + 1
110
+ binary_mask = binary_mask.filter(ImageFilter.MaxFilter(kernel_size))
111
+ # ==== END 扩大 ====
112
+
113
  cnet_image = source.copy()
114
+ # 在控制网络输入图上把 mask 区域填黑(以便 ControlNet/pipe 根据此区域生成)
115
  cnet_image.paste(0, (0, 0), binary_mask)
116
 
117
+ # 调用管线(通常是生成若干中间结果,这里按原逻辑 yield)
118
+ for image_out in pipe(
119
  prompt_embeds=prompt_embeds,
120
  negative_prompt_embeds=negative_prompt_embeds,
121
  pooled_prompt_embeds=pooled_prompt_embeds,
122
  negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
123
  image=cnet_image,
124
+ # Inpaint 流程使用 image=cnet_image(原图 masked with black),
125
+ # 管道内部应该处理了 mask,但如果 StableDiffusionXLFillPipeline
126
+ # 需要显式 mask,这里可能需要调整。根据原代码的命名和逻辑,
127
+ # 假定 pipe(image=cnet_image) 适用于此填充流程。
128
  ):
129
+ yield image_out, cnet_image # 这里的 yield 是为了流式输出
130
 
131
  print(f"{model_selection=}")
132
  print(f"{paste_back=}")
133
+ # 最后 paste 回原图(如用户选择)
134
  if paste_back:
135
+ # image_out 是生成的修复部分
136
+ # cnet_image 在循环中已被用作 ControlNet 输入图(黑块版)
137
+ # 这里的 cnet_image 应该更新为 source.copy() 以避免和输入混淆,
138
+ # 但遵循原代码逻辑,使用 image_out + source/binary_mask
139
+
140
+ # 最终结果是 image_out(修复结果),我们将其粘贴回原图 source
141
+ # 的非 mask 区域(即只替换 mask 区域)
142
+ final_output = source.copy()
143
+ image_out_rgba = image_out.convert("RGBA")
144
+ # 使用二值 mask 的反转作为 paste 的 mask
145
+ inverted_mask = binary_mask.point(lambda p: 255 if p == 0 else 0).convert("L")
146
+
147
+ # 将 image_out 粘贴到 final_output 中,仅在 binary_mask 为 255 的区域(即修复区域)
148
+ final_output.paste(image_out_rgba, (0, 0), binary_mask)
149
+
150
+ yield final_output, cnet_image
151
  else:
152
+ # 如果不 paste back,只返回生成的修复图像
153
+ yield image_out, cnet_image
154
 
155
  def clear_result():
156
  return gr.update(value=None)
157
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
158
  def use_output_as_input(output_image):
159
+ """
160
+ 接收 ImageSlider 的输出 (image_out, cnet_image)
161
+ 返回 cnet_image 作为新的输入。
162
+ """
163
+ # ImageSlider 的 value 是一个 tuple (image1, image2)
164
+ # 这里的 image2 (即 cnet_image) 是包含修复结果的图像 (如果 paste_back 为 True)
165
+ # 或者只是 ControlNet 输入(如果 fill_image 逻辑有变)
166
+ # 假设我们想要将修复后的结果图作为新的输入图像(新的 source)
167
+ # 在 fill_image 中,最终 yield 的是 (final_output, cnet_image)
168
+ # 我们应该使用 final_output 作为新的背景图。
169
+ return gr.update(value=output_image[0]) # output_image[0] 是最终修复图像
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
170
 
171
  css = """
172
  .nulgradio-container {
 
176
  overflow-y: scroll !important;
177
  padding: 10px 40px !important;
178
  }
179
+ div#component-17 { /* 这是一个动态 ID,可能需要调整或移除 */
180
  height: auto !important;
181
  }
182
 
 
183
  @media screen and (max-width: 600px) {
184
  .img-row{
185
  display: block !important;
186
  margin-bottom: 20px !important;
187
  }
188
+ /* 移除掉 component-16 的引用,因为它是动态的 */
 
 
189
  }
190
 
191
  """
192
 
193
+ title = """<h1 align="center">Diffusers Image Inpaint</h1>
194
+ <div align="center">Upload an image, draw a mask, and enter a prompt to repair/inpaint the masked area.</div>
195
  <div style="display: flex; justify-content: center; align-items: center; text-align: center;">
196
  <p style="display: flex;gap: 6px;">
197
  <a href="https://huggingface.co/spaces/fffiloni/diffusers-image-outpout?duplicate=true">
 
201
  </div>
202
  """
203
 
 
 
 
 
204
  with gr.Blocks(css=css, fill_height=True) as demo:
205
+ gr.Markdown(title) # 使用更简洁的 Markdown 标题
206
+
207
+ # 只保留 Inpaint 选项卡的内容,移除 Tabs 结构,让 Inpaint 成为主界面
208
+ with gr.Column():
209
+ with gr.Row():
210
  with gr.Column():
211
+ prompt = gr.Textbox(
212
+ label="Prompt",
213
+ info="Describe what to inpaint the mask with",
214
+ lines=3,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
215
  )
 
216
  with gr.Column():
217
+ model_selection = gr.Dropdown(
218
+ choices=list(MODELS.keys()),
219
+ value="RealVisXL V5.0 Lightning",
220
+ label="Model",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
221
  )
222
+ with gr.Row():
223
+ run_button = gr.Button("Generate")
224
+ paste_back = gr.Checkbox(True, label="Paste back original")
225
+ with gr.Row(equal_height=False):
226
+ input_image = gr.ImageMask(
227
+ type="pil", label="Input Image", layers=True, elem_classes="img-row"
228
+ )
229
+ result = ImageSlider(
230
+ interactive=False,
231
+ label="Generated Image",
232
+ elem_classes="img-row"
233
+ )
234
+ use_as_input_button = gr.Button("Use as Input Image", visible=False)
235
+
236
+ # --- Event Handlers for Inpaint ---
237
+ use_as_input_button.click(
238
+ fn=use_output_as_input,
239
+ inputs=[result],
240
+ outputs=[input_image],
241
+ queue=False # 这是一个快速操作
242
+ )
243
+
244
+ # Generates image on button click
245
+ run_button.click(
246
+ fn=clear_result,
247
+ inputs=None,
248
+ outputs=result,
249
+ queue=False,
250
+ ).then(
251
+ fn=lambda: gr.update(visible=False),
252
+ inputs=None,
253
+ outputs=use_as_input_button,
254
+ queue=False,
255
+ ).then(
256
+ fn=fill_image,
257
+ inputs=[prompt, input_image, model_selection, paste_back],
258
+ outputs=[result],
259
+ ).then(
260
+ fn=lambda: gr.update(visible=True),
261
+ inputs=None,
262
+ outputs=use_as_input_button,
263
+ queue=False,
264
+ )
265
+
266
+ # Generates image on prompt submit
267
+ prompt.submit(
268
+ fn=clear_result,
269
+ inputs=None,
270
+ outputs=result,
271
+ queue=False,
272
+ ).then(
273
+ fn=lambda: gr.update(visible=False),
274
+ inputs=None,
275
+ outputs=use_as_input_button,
276
+ queue=False,
277
+ ).then(
278
+ fn=fill_image,
279
+ inputs=[prompt, input_image, model_selection, paste_back],
280
+ outputs=[result],
281
+ ).then(
282
+ fn=lambda: gr.update(visible=True),
283
+ inputs=None,
284
+ outputs=use_as_input_button,
285
+ queue=False,
286
+ )
287
+
288
+ # 将 queue 和 launch 保持不变
289
+ demo.queue(max_size=10).launch(show_error=True)