-
Notifications
You must be signed in to change notification settings - Fork 4
/
components.py
1576 lines (1385 loc) · 61.8 KB
/
components.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# (c) 2024 Niels Provos
# Standard library imports
import io
import base64
from pathlib import Path
from PIL import Image
import cv2
# Related third party imports
import numpy as np
from dash import dcc, html, ctx, no_update
from dash_extensions import EventListener
from dash.dependencies import Input, Output, State, ALL, ClientsideFunction
from dash.exceptions import PreventUpdate
# Local application/library specific imports
import constants as C
from automatic1111 import make_models_request
from comfyui import get_history, patch_inpainting_workflow
from controller import AppState, CompositeMode
from utils import to_image_url, find_square_bounding_box
from inpainting import patch_image, create_inpainting_pipeline
from segmentation import render_view, remove_mask_from_alpha
from stabilityai import StabilityAI
def get_canvas_paint_events():
props = ["type", "clientX", "clientY", "offsetX", "offsetY",
"button", "altKey", "ctrlKey", "shiftKey"]
events = []
for event in ["mousedown", "mouseup", "mouseout", "mouseenter"]:
events.append({"event": event, "props": props})
return events
def get_image_click_event():
return {"event": "click", "props": [
"type", "clientX", "clientY", "offsetX", "offsetY", "ctrlKey", "shiftKey"]}
def make_input_image_container(
upload_id: str = C.UPLOAD_IMAGE,
image_id: str = C.IMAGE,
event_id: str = 'el',
canvas_id: str = C.CANVAS,
preview_canvas_id: str = C.PREVIEW_CANVAS,
outer_class_name: str = 'w-full col-span-2'):
return html.Div([
html.Label('Input Image', className='font-bold mb-2 ml-3'),
dcc.Store(id=C.STORE_IGNORE), # we don't read this data
dcc.Store(id=C.STORE_CLICKED_POINT),
dcc.Store(id=C.STORE_CLEAR_PREVIEW),
dcc.Upload(
id=upload_id,
disabled=False,
children=html.Div(
[
dcc.Loading(
id=C.LOADING_UPLOAD,
children=[],
fullscreen=False, # Ensure not to use fullscreen
# Center in the Upload container
className='absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 z-20',
style={'color': 'blue'},
),
EventListener(
html.Img(
id=image_id,
className='absolute top-0 left-0 w-full h-full object-contain object-left-top z-0'),
events=[get_image_click_event()], logging=True, id=event_id
),
EventListener(
html.Canvas(
id=canvas_id,
className='absolute top-0 left-0 w-full h-full object-contain object-left-top opacity-50 z-10'
),
id=C.CANVAS_PAINT, events=get_canvas_paint_events(), logging=False
),
html.Canvas(
id=preview_canvas_id,
className='absolute top-0 left-0 w-full h-full object-contain object-left-top opacity-50 z-20'
),
],
className='general-container relative flex h-full overflow-hidden',
style={'height': '67vh'},
),
style={'height': '67vh'},
className='w-full',
disable_click=True,
multiple=False
),
make_segmentation_tools_container(),
make_inpainting_tools_container(),
], className=outer_class_name,
id=C.CTR_INPUT_IMAGE
)
def make_inpainting_tools_container():
return html.Div([
# Div for existing canvas tools
html.Div([
dcc.Store(id=C.CANVAS_DATA), # saves to disk
dcc.Store(id=C.CANVAS_MASK_DATA),
# keeps track of the selected slice for Javascript
dcc.Store(id=C.STORE_SELECTED_SLICE),
html.Div([
html.Button('Clear', id=C.BTN_CLEAR_CANVAS,
className='general-element mr-1'),
html.Button('Erase', id=C.BTN_ERASE_MODE,
className='general-element mr-1'),
html.Button('Load', id=C.BTN_LOAD_CANVAS,
className='general-element'),
], className='tools-container')
], className='tools-backdrop items-center'),
# Div for navigation buttons arranged just in a single row
html.Div([
html.Div([
html.Button(html.I(className="fa fa-magnifying-glass-minus"), id=C.NAV_ZOOM_OUT,
className='nav-button mr-1'),
html.Button(html.I(className="fa fa-arrow-up"), id=C.NAV_UP,
className='nav-button mr-1'),
html.Button(html.I(className="fa fa-arrow-left"), id=C.NAV_LEFT,
className='nav-button mr-1'),
html.Button(html.I(className="fa fa-circle"), id=C.NAV_RESET,
className='nav-button mr-1'),
html.Button(html.I(className="fa fa-arrow-right"), id=C.NAV_RIGHT,
className='nav-button mr-1'),
html.Button(html.I(className="fa fa-arrow-down"), id=C.NAV_DOWN,
className='nav-button mr-1'),
html.Button(html.I(className="fa fa-magnifying-glass-plus"), id=C.NAV_ZOOM_IN,
className='nav-button'),
], className='tools-container'),
], className='tools-backdrop items-centergap-1'),
], id=C.CTR_CANVAS_BUTTONS, className='flex gap-2')
def make_segmentation_tools_container():
return html.Div([
html.Div([
html.Div([
html.Button([html.I(className="fa fa-clone")], id=C.SEG_TOGGLE_CHECKERBOARD,
title='Toggle checkerboard background',
className='general-element color-not-selected mr-1'),
html.Button(["Invert ", html.I(className="fa fa-adjust")], id=C.SEG_INVERT_MASK,
title='Invert the current mask',
className='general-element mr-1'),
html.Button(["Feather ", html.I(className="fa fa-wind")], id=C.SEG_FEATHER_MASK,
title='Feather the current mask',
className='general-element mr-1'),
html.Button(["Multi ", html.I(className="fa fa-wand-magic-sparkles")], id=C.SEG_MULTI_POINT,
className='general-element color-not-selected mr-1'),
html.Button(["Commit ", html.I(className="fa fa-person-running")], id=C.SEG_MULTI_COMMIT,
className='general-element mr-1'),
], className='flex justify-between')
], className='tools-backdrop items-center')
],
id=C.CTR_SEG_BUTTONS,
className='inline-block')
def make_tools_callbacks(app):
@app.callback(
Output(C.CANVAS, 'className'),
Output(C.IMAGE, 'className'),
Output(C.CTR_CANVAS_BUTTONS, 'className'),
Output(C.CTR_SEG_BUTTONS, 'className'),
Input({'type': 'tab-content-main', 'index': ALL}, 'className'),
State(C.CANVAS, 'className'),
State(C.IMAGE, 'className'),
State(C.CTR_CANVAS_BUTTONS, 'className'),
State(C.CTR_SEG_BUTTONS, 'className'),
)
def update_events(tab_class_names, canvas_class_name, image_class_name,
inpaint_btns_class, segment_btns_class):
if tab_class_names is None:
raise PreventUpdate()
canvas_class_name = canvas_class_name.replace(
' z-10', '').replace(' z-0', '')
image_class_name = image_class_name.replace(
' z-10', '').replace(' z-0', '')
inpaint_btns_class = inpaint_btns_class.replace(' hidden', '')
segment_btns_class = segment_btns_class.replace(' hidden', '')
# tabs[1] == Segmentation tab
# tabs[2] == Inpainting tab
# we paint on the canvas only if the Inpainting tab is active
if 'hidden' not in tab_class_names[2]:
canvas_class_name += ' z-10'
image_class_name += ' z-0'
else:
canvas_class_name += ' z-0'
image_class_name += ' z-10'
inpaint_btns_class += ' hidden'
# we will show the segmentation tools only if the Segmentation tab is active
if 'hidden' in tab_class_names[1]:
segment_btns_class += ' hidden'
return canvas_class_name, image_class_name, inpaint_btns_class, segment_btns_class
def make_depth_map_container(depth_map_id: str = C.CTR_DEPTH_MAP):
return html.Div([
html.Label('Depth Map', className='font-bold mb-2 ml-3'),
html.Div(id=depth_map_id,
className='general-container min-h-60',
),
dcc.Loading(
id=C.LOADING_DEPTHMAP,
type='default',
children=html.Div(id=C.DEPTHMAP_OUTPUT)
),
html.Div([
html.Div([
html.Label('Depth Module Algorithm'),
dcc.Dropdown(
id=C.DROPDOWN_DEPTH_MODEL,
options=[
{'label': 'MiDaS', 'value': 'midas'},
{'label': 'ZoeDepth', 'value': 'zoedepth'},
{'label': 'DINOv2', 'value': 'dinov2'}
],
value='zoedepth',
className='general-dropdown mt-2 mb-2',
)
], className='w-full'),
html.Button(
html.Div([
html.Label('Regenerate Depth Map'),
html.I(className='fa-solid fa-image pl-1')]),
id=C.BTN_GENERATE_DEPTHMAP,
className='general-element mt-2 mb-2'
),
], className='w-full grid grid-cols-2 gap-2 p-2 items-end'),
html.Div([
dcc.Interval(id=C.PROGRESS_INTERVAL, interval=500, n_intervals=0),
html.Div(id=C.CTR_PROGRESS_BAR,
className='progress-bar'),
], className='p-2'),
], className='w-full')
def make_thresholds_container(thresholds_id: str = C.CTR_THRESHOLDS):
return html.Div([
html.Label('Thresholds', className='font-bold mb-2 ml-3'),
html.Div(id=thresholds_id,
className='general-border min-h-8 w-full flex-auto grow'),
], className='w-full mb-2')
def make_slice_generation_container():
return html.Div([
dcc.Store(id=C.STORE_GENERATE_SLICE),
dcc.Store(id=C.STORE_UPDATE_SLICE),
dcc.Download(id=C.DOWNLOAD_IMAGE),
html.Div([
html.Div([
make_thresholds_container(
thresholds_id=C.CTR_THRESHOLDS),
],
className='w-full col-span-3',
),
html.Div([
html.Label(
'Actions', className='font-bold mb-1 ml-3'),
html.Div([
html.Button(
html.Div([
html.Label('Generate'),
html.I(className='fa-solid fa-images pl-1')]),
id=C.BTN_GENERATE_SLICE,
title='Generate image slices from the input image using the depth map',
className='w-full general-element mb-1 mr-2'
),
html.Button(
html.Div([
html.Label('Balance'),
html.I(className='fa-solid fa-arrows-left-right pl-1')]),
id=C.BTN_BALANCE_SLICE,
title='Rebalances the depths of the image slices evenly',
className='w-full general-element mb-1'
),
html.Button(
html.Div([
html.Label('Create'),
html.I(className='fa-solid fa-square-plus pl-1')]),
id=C.BTN_CREATE_SLICE,
title='Creates a slice from the current mask',
className='w-full general-element mb-1'
),
html.Button(
html.Div([
html.Label('Delete'),
html.I(className='fa-solid fa-trash-can pl-1')]),
id=C.BTN_DELETE_SLICE,
title='Deletes the currently selected slice',
className='w-full general-element mb-1'
),
html.Button(
html.Div([
html.Label('Add'),
html.I(className='fa-solid fa-brush pl-1')]),
id=C.BTN_ADD_SLICE,
title='Adds the current mask to the selected slice',
className='w-full general-element mb-1'
),
html.Button(
html.Div([
html.Label('Remove'),
html.I(className='fa-solid fa-eraser pl-1')]),
id=C.BTN_REMOVE_SLICE,
title='Removes the current mask from the selected slice',
className='w-full general-element mb-1'
),
html.Button(
html.Div([
html.Label('Copy'),
html.I(className='fa-solid fa-brush pl-1')]),
id=C.BTN_COPY_SLICE,
title='Copies the current mask to the clipboard',
className='w-full general-element mb-1'
),
html.Button(
html.Div([
html.Label('Paste'),
html.I(className='fa-solid fa-eraser pl-1')]),
id=C.BTN_PASTE_SLICE,
title='Copies the clipboard to the selected slice',
className='w-full general-element mb-1'
),
],
className='grid grid-cols-2 gap-2 gap-2 p-2'
),
], className='w-full h-full col-span-2',
)
],
className='grid grid-cols-5 gap-4 p-2'
),
dcc.Loading(id=C.LOADING_GENERATE_SLICE,
children=html.Div(id="gen-slice-output")),
html.Div(id=C.CTR_SLICE_IMAGES,
className='general-border min-h-8 w-full grid grid-cols-3 gap-1 overflow-auto'),
],
className='w-full overflow-auto',
style={'height': '69vh'},
)
def make_inpainting_container():
return html.Div([
dcc.Store(id=C.STORE_INPAINTING),
html.Div([
html.Label('Positive Prompt'),
dcc.Textarea(
id=C.TEXT_POSITIVE_PROMPT,
placeholder='Enter a positive generative AI prompt...',
className='w-full light-border',
style={'height': '100px'}
)
]),
html.Div([
html.Label('Negative Prompt'),
dcc.Textarea(
id=C.TEXT_NEGATIVE_PROMPT,
placeholder='Enter a negative prompt...',
className='w-full light-border',
)
]),
html.Div([
html.Div([
html.Label('Strength'),
dcc.Slider(
id=C.SLIDER_INPAINT_STRENGTH,
min=0,
max=1,
step=0.01,
value=0.8,
marks=None,
tooltip={"placement": "bottom", "always_visible": True}
),
], className='w-full p-2'),
html.Div([
html.Label('Guidance Scale'),
dcc.Slider(
id=C.SLIDER_INPAINT_GUIDANCE,
min=1,
max=15,
step=0.25,
value=7.5,
marks=None,
tooltip={"placement": "bottom", "always_visible": True}
),
], className='w-full p-2'),
], className='flex w-full'),
dcc.Checklist(
id=C.CHECKLIST_REGION_OF_INTEREST,
options=[{"label": html.Span("Crop to region of interest",
className="p-2"),
"value": "crop"}],
value=["crop"],
className='p-2',
),
html.Button(
html.Div([
html.Label('Generate'),
html.I(className='fa-solid fa-paint-brush pl-1')
]),
id=C.BTN_GENERATE_INPAINTING,
title='Inpaint the areas of the selected image based on the painted mask',
className='general-element mb-2 mt-3 mr-2'
),
html.Button(
html.Div([
html.Label('Fill'),
html.I(className='fa-solid fa-fill pl-1')
]),
id=C.BTN_FILL_INPAINTING,
title='Fill all empty areas of the selected image via inpainting',
className='general-element mb-2 mt-3 mr-2'
),
html.Button(
html.Div([
html.Label('Enhance'),
html.I(className='fa-solid fa-wand-magic-sparkles pl-1')
]),
id=C.BTN_ENHANCE,
title='Use inpainting to enhance the selected image via up and downscaling',
className='general-element mb-2 mt-3 mr-2'
),
html.Button(
html.Div([
html.Label('Erase'),
html.I(className='fa-solid fa-trash-can pl-1')
]),
id=C.BTN_ERASE_INPAINTING,
className='general-element mb-2 mt-3',
title='Clear the painted areas from the selected image',
),
dcc.Loading(
id=C.LOADING_GENERATE_INPAINTING,
children=html.Div(id=C.CTR_INPAINTING_OUTPUT)
),
html.Div(
id=C.CTR_INPAINTING_IMAGES,
children=[
html.Div(
id=C.CTR_INPAINTING_DISPLAY,
className='grid grid-cols-3 gap-2'
),
],
className='general-border w-full min-h-8'
),
html.Button(
'Apply Selected Image',
id=C.BTN_APPLY_INPAINTING,
className='color-is-selected p-2 rounded-md mt-2',
disabled=True
)
], className='w-full', id=C.CTR_INPAINTING_COLUNM)
def make_inpainting_container_callbacks(app):
@app.callback(
Output(C.BTN_APPLY_INPAINTING, 'disabled'),
Input(C.CTR_INPAINTING_DISPLAY, 'children')
)
def enable_apply_inpainting_button(children):
return False if children else True
@app.callback(
Output(C.STORE_UPDATE_SLICE, 'data', allow_duplicate=True),
Output(C.LOGS_DATA, 'data', allow_duplicate=True),
Input(C.BTN_ERASE_INPAINTING, 'n_clicks'),
State(C.STORE_APPSTATE_FILENAME, 'data'),
State(C.LOGS_DATA, 'data'),
running=[(Output(C.BTN_ERASE_INPAINTING, 'disabled'), True, False)],
prevent_initial_call=True)
def erase_inpainting(n_clicks, filename, logs):
if n_clicks is None or filename is None:
raise PreventUpdate()
state = AppState.from_cache(filename)
if state.selected_slice is None:
logs.append('No slice selected')
return no_update, logs
index = state.selected_slice
mask_filename = state.mask_filename(index)
if not Path(mask_filename).exists():
logs.append(f'No mask found for slice {index}')
return no_update, logs
mask = Image.open(mask_filename).convert('L')
mask = np.array(mask)
final_mask = remove_mask_from_alpha(
state.image_slices[index].image, mask)
state.image_slices[index].image[:, :, 3] = final_mask
state.image_slices[index].new_version()
state.to_file(state.filename, save_image_slices=False,
save_depth_map=False, save_input_image=False)
logs.append(f'Inpainting erased for slice {index}')
logs.append(f'Inpainting erased for slice {index}')
return True, logs
@app.callback(
Output(C.CTR_INPAINTING_DISPLAY, 'children'),
Output(C.LOADING_GENERATE_INPAINTING, 'children'),
Input(C.BTN_GENERATE_INPAINTING, 'n_clicks'),
Input(C.BTN_FILL_INPAINTING, 'n_clicks'),
Input(C.BTN_ENHANCE, 'n_clicks'),
State(C.STORE_APPSTATE_FILENAME, 'data'),
State(C.DROPDOWN_INPAINT_MODEL, 'value'),
State(C.UPLOAD_COMFYUI_WORKFLOW, 'contents'),
State(C.TEXT_POSITIVE_PROMPT, 'value'),
State(C.TEXT_NEGATIVE_PROMPT, 'value'),
State(C.SLIDER_INPAINT_STRENGTH, 'value'),
State(C.SLIDER_INPAINT_GUIDANCE, 'value'),
State(C.SLIDER_MASK_PADDING, 'value'),
State(C.SLIDER_MASK_BLUR, 'value'),
running=[(Output(C.BTN_GENERATE_INPAINTING, 'disabled'), True, False),
(Output(C.BTN_FILL_INPAINTING, 'disabled'), True, False),
(Output(C.BTN_ENHANCE, 'disabled'), True, False)],
prevent_initial_call=True
)
def update_inpainting_image_display(
n_clicks_one, n_clicks_two, n_clicks_three, filename, model,
workflow,
positive_prompt, negative_prompt,
strength, guidance_scale,
padding, blur):
if n_clicks_one is None and n_clicks_two is None and n_clicks_three is None:
raise PreventUpdate()
if filename is None:
raise PreventUpdate()
state = AppState.from_cache(filename)
if state.selected_slice is None:
raise PreventUpdate() # XXX - write controller logic to clear this on image changes
index = state.selected_slice
# An empty prompt is OK.
if positive_prompt is None:
positive_prompt = ''
if negative_prompt is None:
negative_prompt = ''
state.image_slices[state.selected_slice].positive_prompt = positive_prompt
state.image_slices[state.selected_slice].negative_prompt = negative_prompt
state.to_file(state.filename, save_image_slices=False,
save_depth_map=False, save_input_image=False)
tid = ctx.triggered_id
image = state.image_slices[index].image
pipeline = create_inpainting_pipeline(
model, workflow, state)
if tid == C.BTN_GENERATE_INPAINTING or tid == C.BTN_FILL_INPAINTING:
if tid == C.BTN_GENERATE_INPAINTING:
mask_filename = state.mask_filename(index)
if not Path(mask_filename).exists():
raise PreventUpdate()
mask = Image.open(mask_filename).convert('L')
mask = np.array(mask)
else:
# we'll fill everything that does not have an alpha
mask = 255 - image[:, :, 3]
def execute(input_image): return pipeline.inpaint(
positive_prompt, negative_prompt, input_image, mask,
strength=strength, guidance_scale=guidance_scale,
blur_radius=blur, padding=padding,
crop=True)
# patch the image
image = patch_image(image, mask)
num_images = 3
else:
assert tid == C.BTN_ENHANCE
def upscale_image(input_image):
upscaled_image = state.upscale_image(
input_image, prompt=positive_prompt, negative_prompt=negative_prompt)
upscaled_image = upscaled_image.resize(
(input_image.shape[1], input_image.shape[0]), Image.LANCZOS)
upscaled_image = np.array(upscaled_image)
upscaled_image[:, :, 3] = input_image[:, :, 3]
return upscaled_image
def execute(input_image): return upscale_image(input_image)
num_images = 2
images = []
for i in range(num_images):
new_image = execute(image)
images.append(new_image)
children = []
for i, new_image in enumerate(images):
children.append(
html.Img(src=to_image_url(new_image),
className='w-full h-full object-contain',
id={'type': C.ID_INPAINTING_IMAGE, 'index': i})
)
return children, []
@app.callback(
Output(C.IMAGE, 'src', allow_duplicate=True),
Output({'type': C.ID_INPAINTING_IMAGE, 'index': ALL}, 'className'),
Output(C.LOADING_UPLOAD, 'children', allow_duplicate=True),
Input({'type': C.ID_INPAINTING_IMAGE, 'index': ALL}, 'n_clicks'),
State(C.STORE_APPSTATE_FILENAME, 'data'),
State({'type': C.ID_INPAINTING_IMAGE, 'index': ALL}, 'src'),
State({'type': C.ID_INPAINTING_IMAGE, 'index': ALL}, 'className'),
prevent_initial_call=True)
def select_inpainting_image(n_clicks, filename, images, classnames):
if n_clicks is None or filename is None:
raise PreventUpdate()
index = ctx.triggered_id['index']
if n_clicks[index] is None:
raise PreventUpdate()
state = AppState.from_cache(filename)
if state.selected_slice is None:
raise PreventUpdate()
state.selected_inpainting = index
print(f'Applying inpainting image {index}')
# give a visual highlight on the selected children
return_image = no_update
new_classnames = []
selected_background = ' color-is-selected-light'
for i, classname in enumerate(classnames):
already_selected = selected_background in classname
classname = classname.replace(selected_background, '')
if i == index:
if not already_selected:
classname += selected_background
return_image = images[i]
else:
mode = CompositeMode.CHECKERBOARD if state.use_checkerboard else CompositeMode.GRAYSCALE
return_image = state.serve_slice_image_composed(
state.selected_slice, mode)
new_classnames.append(classname)
return return_image, new_classnames, ""
@app.callback(
Output(C.STORE_INPAINTING, 'data'),
Output(C.LOGS_DATA, 'data', allow_duplicate=True),
Output(C.STORE_UPDATE_SLICE, 'data', allow_duplicate=True),
Input(C.BTN_APPLY_INPAINTING, 'n_clicks'),
State(C.STORE_APPSTATE_FILENAME, 'data'),
State({'type': C.ID_INPAINTING_IMAGE, 'index': ALL}, 'src'),
State(C.LOGS_DATA, 'data'),
running=[(Output(C.BTN_APPLY_INPAINTING, 'disabled'), True, False)],
prevent_initial_call=True)
def apply_inpainting(n_clicks, filename, inpainted_images, logs):
if n_clicks is None or filename is None:
raise PreventUpdate()
state = AppState.from_cache(filename)
if state.selected_inpainting is None:
raise PreventUpdate()
index = state.selected_slice
new_image_data = inpainted_images[state.selected_inpainting]
new_image = Image.open(io.BytesIO(
base64.b64decode(new_image_data.split(',')[1])))
image_filename = state.image_slices[index].new_version(
np.array(new_image))
state.to_file(state.filename, save_image_slices=False,
save_depth_map=False, save_input_image=False)
logs.append(
f'Inpainting applied to slice {index} with new image {image_filename}')
return True, logs, True
# this is called when the selected slice changes
@app.callback(Output(C.TEXT_POSITIVE_PROMPT, 'disabled'),
Output(C.TEXT_NEGATIVE_PROMPT, 'disabled'),
Output(C.BTN_GENERATE_INPAINTING, 'disabled'),
Output(C.BTN_FILL_INPAINTING, 'disabled'),
Output(C.BTN_ENHANCE, 'disabled'),
Output(C.BTN_ERASE_INPAINTING, 'disabled'),
Output(C.STORE_SELECTED_SLICE, 'data'),
Input(C.STORE_INPAINTING, 'data'),
State(C.STORE_APPSTATE_FILENAME, 'data'),
prevent_initial_call=True)
def react_selected_slice_change(ignore, filename):
if filename is None:
return True, True, True, True, True, True, None
state = AppState.from_cache(filename)
if state.selected_slice is None:
return True, True, True, True, True, True, None
return False, False, False, False, False, False, state.selected_slice
return update_inpainting_image_display
def make_configuration_callbacks(app):
success_class = ' color-is-selected-light'
failure_class = ' failure-color'
@app.callback(
Output(C.UPLOAD_COMFYUI_WORKFLOW, 'contents'),
Output(C.UPLOAD_COMFYUI_WORKFLOW, 'children'),
Output(C.LOGS_DATA, 'data', allow_duplicate=True),
Input(C.UPLOAD_COMFYUI_WORKFLOW, 'contents'),
State(C.UPLOAD_COMFYUI_WORKFLOW, 'filename'),
State(C.STORE_APPSTATE_FILENAME, 'data'),
State(C.LOGS_DATA, 'data'),
prevent_initial_call=True)
def validate_workflow(contents, upload_name, filename, logs):
if contents is None:
raise PreventUpdate()
# remove the data URL prefix
contents = contents.split(',')[1]
contents = base64.b64decode(contents)
try:
patch_inpainting_workflow(
contents, C.IMAGE, 'mask', 'positive', 'negative')
logs.append('ComfyUI workflow validated')
except Exception as e:
logs.append(f'ComfyUI workflow validation failed: {str(e)}')
return "", ['Drag and Drop or ', html.I(
className='fa-solid fa-upload'), ' to upload'], logs
if filename is not None:
state = AppState.from_cache(filename)
workflow_path = state.workflow_path()
if not workflow_path.exists() or workflow_path.read_bytes() != contents:
with open(workflow_path, 'wb') as f:
f.write(contents)
state.to_file(state.filename, save_image_slices=False,
save_depth_map=False, save_input_image=False)
return no_update, upload_name, logs
# Stability AI API for inpainting does not support mask blurring
@app.callback(
Output(C.SLIDER_INPAINT_GUIDANCE, 'disabled'),
Input(C.DROPDOWN_INPAINT_MODEL, 'value'),
prevent_initial_call=True)
def toggle_blur_slider(value):
if value == 'stabilityai':
return True
return False
@app.callback(
Output(C.CTR_AUTOMATIC_CONFIG, 'className'),
Output(C.CTR_COMFYUI_WORKFLOW, 'className'),
Input(C.DROPDOWN_INPAINT_MODEL, 'value'),
State(C.CTR_AUTOMATIC_CONFIG, 'className'),
State(C.CTR_COMFYUI_WORKFLOW, 'className'),
)
def toggle_automatic_config(value, class_name_server, class_name_workflow):
class_name_server = class_name_server.replace(' hidden', '')
if value != 'automatic1111' and value != 'comfyui':
class_name_server += ' hidden'
class_name_workflow = class_name_workflow.replace(' hidden', '')
if value != 'comfyui':
class_name_workflow += ' hidden'
return class_name_server, class_name_workflow
@app.callback(
Output(C.INPUT_EXTERNAL_SERVER, 'className', allow_duplicate=True),
Input(C.INPUT_EXTERNAL_SERVER, 'value'),
State(C.INPUT_EXTERNAL_SERVER, 'className'),
State(C.STORE_APPSTATE_FILENAME, 'data'),
prevent_initial_call=True)
def reset_external_server_address(value, class_name, filename):
if filename is not None:
state = AppState.from_cache(filename)
if state.server_address == value:
raise PreventUpdate()
state.server_address = value
state.to_file(state.filename,
save_image_slices=False,
save_depth_map=False, save_input_image=False)
return class_name.replace(success_class, '').replace(failure_class, '')
@app.callback(
Output(C.LOGS_DATA, 'data', allow_duplicate=True),
Output(C.INPUT_EXTERNAL_SERVER, 'className'),
Input(C.BTN_EXTERNAL_TEST_CONNECTION, 'n_clicks'),
State(C.INPUT_EXTERNAL_SERVER, 'value'),
State(C.INPUT_EXTERNAL_SERVER, 'className'),
State(C.DROPDOWN_INPAINT_MODEL, 'value'),
State(C.LOGS_DATA, 'data'),
prevent_initial_call=True)
def test_external_connection(n_clicks, server_address, class_name, model, logs):
if n_clicks is None:
raise PreventUpdate()
class_name = class_name.replace(
success_class, '').replace(failure_class, '')
success = False
try:
if model == 'automatic1111':
data = make_models_request(server_address)
else:
data = get_history(server_address, 'test')
if data is not None:
logs.append(f'Connection to {model} successful: {data}')
success = True
else:
logs.append(f'Connection to {model} failed')
except Exception as e:
logs.append(f'Connection to {model} failed: {str(e)}')
class_name += success_class if success else failure_class
return logs, class_name
# Stability AI related callbacks
@app.callback(
Output(C.CTR_API_KEY, 'className'),
Input(C.DROPDOWN_INPAINT_MODEL, 'value'),
State(C.CTR_API_KEY, 'className'),
)
def toggle_stabilityai_config(value, class_name):
class_name = class_name.replace(' hidden', '')
if value != 'stabilityai':
class_name += ' hidden'
return class_name
@app.callback(
Output(C.INPUT_API_KEY, 'className', allow_duplicate=True),
Input(C.INPUT_API_KEY, 'value'),
State(C.INPUT_API_KEY, 'className'),
State(C.STORE_APPSTATE_FILENAME, 'data'),
prevent_initial_call=True)
def reset_external_api_key(value, class_name, filename):
if filename is not None:
state = AppState.from_cache(filename)
if state.api_key == value:
raise PreventUpdate()
state.api_key = value
state.to_file(state.filename,
save_image_slices=False,
save_depth_map=False, save_input_image=False)
return class_name.replace(success_class, '').replace(failure_class, '')
@app.callback(
Output(C.LOGS_DATA, 'data', allow_duplicate=True),
Output(C.INPUT_API_KEY, 'className'),
Input(C.BTN_VALIDATE_API_KEY, 'n_clicks'),
State(C.INPUT_API_KEY, 'value'),
State(C.INPUT_API_KEY, 'className'),
State(C.DROPDOWN_INPAINT_MODEL, 'value'),
State(C.LOGS_DATA, 'data'),
prevent_initial_call=True)
def test_api_key(n_clicks, api_key, class_name, model, logs):
if n_clicks is None:
raise PreventUpdate()
class_name = class_name.replace(
success_class, '').replace(failure_class, '')
success = False
if api_key.startswith('sk-') and len(api_key) > 12:
try:
inpaint_model = StabilityAI(api_key)
success, credits = inpaint_model.validate_key()
if success:
logs.append(
f'Connection to {model} successful: you have {credits:0.2f} remaining credits')
success = True
else:
logs.append(f'Connection to {model} failed')
except Exception as e:
logs.append(f'Connection to {model} failed: {str(e)}')
else:
logs.append(f'Invalid API key format')
class_name += success_class if success else failure_class
return logs, class_name
def make_configuration_container():
return make_label_container(
'Configuration',
make_configuration_div())
def make_configuration_div():
return html.Div([
html.Div([
html.Label('Number of Slices'),
dcc.Slider(
id=C.SLIDER_NUM_SLICES,
min=2,
max=10,
step=1,
value=3,
marks={i: str(i) for i in range(2, 11)}
),
], className='w-full'),
html.Div([
html.Label('Inpainting Model'),
dcc.Dropdown(
id=C.DROPDOWN_INPAINT_MODEL,
options=[
{'label': 'Kadinksy',
'value': 'kandinsky-community/kandinsky-2-2-decoder-inpaint'},
{'label': 'SD 1.5', 'value': 'unwayml/stable-diffusion-v1-5'},
{'label': 'SD XL 1.0',
'value': 'diffusers/stable-diffusion-xl-1.0-inpainting-0.1'},
{'label': 'StableDiffusion3',
'value': 'stabilityai/stable-diffusion-3-medium-diffusers'},
{'label': 'Automatic1111', 'value': 'automatic1111'},
{'label': 'ComfyUI', 'value': 'comfyui'},
{'label': 'StabilityAI', 'value': 'stabilityai'},
],
value='diffusers/stable-diffusion-xl-1.0-inpainting-0.1',
className='general-dropdown',
)
], className='w-full'),
html.Div([
html.Label('A1111/ComfyUI Server Address'),
html.Div([
dcc.Input(
id=C.INPUT_EXTERNAL_SERVER,
value='localhost:7860',
type='text',
debounce=True,
className='light-border flex-grow'
),
html.Button(
html.Div([
html.Label('Test Connection'),
html.I(className='fa-solid fa-network-wired pl-1')
]),
id=C.BTN_EXTERNAL_TEST_CONNECTION,
className='general-element mb-2 ml-2'
),
],
# Set the container to display flex for a row layout
className='flex flex-row items-center w-full'),
html.Div([
html.Label('ComfyUI Workflow'),
dcc.Upload(
children=['Drag and Drop or ', html.I(
className='fa-solid fa-upload'), ' to upload'],
className='light-border flex-grow',
id=C.UPLOAD_COMFYUI_WORKFLOW,
),
],
id=C.CTR_COMFYUI_WORKFLOW,
className='w-full'
),
],
id=C.CTR_AUTOMATIC_CONFIG,
className='w-full'),
html.Div([
html.Label('StabilityAI API Key'),
html.Div([
dcc.Input(
id=C.INPUT_API_KEY,
value='',
type='password',
debounce=True,
className='light-border flex-grow'
),
html.Button(
html.Div([
html.Label('Test API Key'),
html.I(className='fa-solid fa-network-wired pl-1')
]),