-
Notifications
You must be signed in to change notification settings - Fork 4
/
webui.py
executable file
·1576 lines (1261 loc) · 55.5 KB
/
webui.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
#!/usr/bin/env python
# (c) 2024 Niels Provos
import argparse
import base64
import io
import os
from pathlib import Path
from PIL import Image
import numpy as np
import constants as C
from segmentation import (
generate_depth_map,
analyze_depth_histogram,
generate_image_slices,
create_slice_from_mask,
export_gltf,
blend_with_alpha,
remove_mask_from_alpha,
render_image_sequence
)
import components
from utils import (
find_pixel_from_event, postprocess_depth_map,
get_gltf_iframe, get_no_gltf_available,
to_data_url
)
from depth import DepthEstimationModel
from instance import SegmentationModel
from inpainting import InpaintingModel, create_inpainting_pipeline
from clientside import make_clientside_callbacks
from slice import ImageSlice
import dash
from dash import dcc, html, ctx, no_update
from dash.dependencies import Input, Output, State
from dash.dependencies import ALL, MATCH
from dash_extensions import EventListener
from dash.exceptions import PreventUpdate
from flask import send_file
from werkzeug import serving
from controller import AppState, CompositeMode
from camera import Camera
# Globals
EXPAND_MASK = 5
HIGHLIGHT_COLOR = 'color-is-selected-light'
# Progress tracking variables
current_progress = -1
total_progress = 100
def progress_callback(current, total):
global current_progress, total_progress
current_progress = (current / total) * 100
total_progress = 100
# call the ability to add external scripts
external_scripts = [
# add the tailwind cdn url hosting the files with the utility classes
{'src': 'https://kit.fontawesome.com/48f728cfc9.js'},
]
app = dash.Dash(__name__,
external_scripts=external_scripts)
# Create a Flask route for serving images
@app.server.route(f'/{AppState.SRV_DIR}/<path:filename>')
def serve_data(filename):
filename = Path(os.getcwd()) / filename
if filename.suffix == '.gltf':
mimetype = 'model/gltf+json'
else:
mimetype = f'image/{filename.suffix[1:]}'
return send_file(str(filename), mimetype=mimetype)
# JavaScript event(s) that we want to listen to and what properties to collect.
eventScroll = {"event": "scroll", "props": ["type", "scrollLeft", "scrollTop"]}
app.layout = html.Div([
EventListener(events=[eventScroll], logging=True, id="evScroll"),
# dcc.Store stores all application state
dcc.Store(id=C.STORE_APPSTATE_FILENAME),
dcc.Store(id=C.STORE_RESTORE_STATE), # trigger to restore state
# Store for rect coordinates from the clientside JS
dcc.Store(id=C.STORE_RECT_DATA),
# Store for bounding box coordinates from inpainting
dcc.Store(id=C.STORE_BOUNDING_BOX),
dcc.Store(id=C.LOGS_DATA, data=[]), # Store for logs
# Trigger for generating depth map
dcc.Store(id=C.STORE_TRIGGER_GEN_DEPTHMAP),
# Trigger for updating depth map
dcc.Store(id=C.STORE_TRIGGER_UPDATE_DEPTHMAP),
# Trigger for updating thresholds
dcc.Store(id=C.STORE_UPDATE_THRESHOLD_CONTAINER),
# Context for the help window
dcc.Store(id=C.STORE_CURRENT_TAB),
# App Layout
html.Header([
html.Div([
html.Button([
html.I(className='fas fa-moon', id=C.ICON_DARK_MODE)
], id=C.BTN_DARK_MODE,
n_clicks=0, className='dark-mode-toggle')
], className='header-left'),
html.H1("Parallax Maker", className='title-text'),
html.Div([], className='header-right')
], className='title-header'),
html.Main([
html.Div(
['Some helpful text to guide the user'],
id=C.CTR_HELP_WINDOW,
className='help-box hidden absolute w-64 p-2 z-40'),
components.make_tabs(
'viewer',
['2D', '3D'],
[
components.make_input_image_container(
upload_id=C.UPLOAD_IMAGE,
image_id=C.IMAGE, event_id='el',
canvas_id=C.CANVAS,
outer_class_name='w-full col-span-3'),
html.Div(
id=C.CTR_MODEL_VIEWER,
children=[
html.Iframe(
id=C.IFRAME_MODEL_VIEWER,
srcDoc=get_no_gltf_available(),
style={'height': '70vh'},
className='gltf-container'
)
]
),
],
outer_class_name='w-full col-span-3'
),
components.make_tabs(
'main',
['Mode', 'Segmentation', 'Inpainting', 'Export', 'Configuration'],
[
html.Div([
components.make_depth_map_container(
depth_map_id=C.CTR_DEPTH_MAP),
components.make_mode_selector(),
], className='w-full', id='depth-map-column'),
components.make_slice_generation_container(),
components.make_inpainting_container(),
html.Div([
components.make_3d_export_div(),
components.make_animation_export_div(),
],
className='w-full'
),
components.make_configuration_div()
],
outer_class_name='w-full col-span-2'
),
], className='grid grid-cols-5 gap-4 p-2'),
components.make_logs_container(logs_id='log'),
html.Footer('© 2024 Niels Provos', className='footer'),
],
id='app-container',
className='min-h-screen'
)
app.scripts.config.serve_locally = True
make_clientside_callbacks(app)
components.make_segmentation_callbacks(app)
components.make_canvas_callbacks(app)
components.make_navigation_callbacks(app)
components.make_inpainting_container_callbacks(app)
components.make_configuration_callbacks(app)
# Callbacks for collapsible sections
components.make_tabs_callback(app, 'viewer')
components.make_tabs_callback(app, 'main')
components.make_tools_callbacks(app)
@app.callback(
Output('app-container', 'className'),
Output(C.ICON_DARK_MODE, 'className'),
Input(C.BTN_DARK_MODE, 'n_clicks'),
State(C.STORE_APPSTATE_FILENAME, 'data'),
prevent_initial_call=True
)
def toggle_dark_mode(n_clicks, filename):
dark_mode = n_clicks % 2 == 1
if filename is not None:
state = AppState.from_cache(filename)
if state.dark_mode != dark_mode:
state.dark_mode = dark_mode
state.to_file(filename, save_image_slices=False,
save_depth_map=False, save_input_image=False)
if dark_mode:
return 'dark min-h-screen', 'fas fa-sun'
else:
return 'min-h-screen', 'fas fa-moon'
# Callback for the logs
@app.callback(Output('log', 'children'),
Input(C.LOGS_DATA, 'data'),
prevent_initial_call=True)
def update_logs(data):
structured_logs = [html.Div(log) for log in data[-3:]]
return structured_logs
# Callback to update progress bar
@app.callback(
Output(C.CTR_PROGRESS_BAR, 'children'),
Output(C.PROGRESS_INTERVAL, 'disabled', allow_duplicate=True),
Input(C.PROGRESS_INTERVAL, 'n_intervals'),
prevent_initial_call=True
)
def update_progress(n):
progress_bar = html.Div(className='progress-bar-fill',
style={'width': f'{max(0, current_progress)}%'})
interval_disabled = current_progress >= total_progress or current_progress == -1
return progress_bar, interval_disabled
@app.callback(
Output({'type': 'threshold-slider', 'index': ALL}, 'value'),
Output(C.IMAGE, 'src', allow_duplicate=True),
Input({'type': 'threshold-slider', 'index': ALL}, 'value'),
State(C.SLIDER_NUM_SLICES, 'value'),
State(C.STORE_APPSTATE_FILENAME, 'data'),
prevent_initial_call=True
)
def update_threshold_values(threshold_values, num_slices, filename):
if filename is None:
raise PreventUpdate()
state = AppState.from_cache(filename)
if state.imgThresholds[1:-1] == threshold_values:
print("Threshold values are the same; not erasing data.")
raise PreventUpdate()
# make sure that threshold values are monotonically increasing
if threshold_values[0] <= 0:
threshold_values[0] = 1
for i in range(1, num_slices-1):
if threshold_values[i] <= threshold_values[i-1]:
threshold_values[i] = threshold_values[i-1] + 1
# go through the list in reverse order to make sure that the thresholds are monotonically decreasing
if threshold_values[-1] >= 255:
threshold_values[-1] = 254
# num slices is the number of thresholds + 1, so the largest index is num_slices - 2
# and the second largest index is num_slices - 3
for i in range(num_slices-3, -1, -1):
if threshold_values[i] >= threshold_values[i+1]:
threshold_values[i] = threshold_values[i+1] - 1
state.imgThresholds[1:-1] = threshold_values
img_data = no_update
if state.slice_pixel:
state.slice_mask, _ = state.depth_slice_from_pixel(
state.slice_pixel[0], state.slice_pixel[1])
if state.slice_mask is not None:
result = state.apply_mask(state.imgData, state.slice_mask)
img_data = state.serve_main_image(result)
else:
img_data = state.serve_main_image(state.imgData)
return threshold_values, img_data
@app.callback(
Output(C.CTR_THRESHOLDS, 'children'),
Input(C.STORE_UPDATE_THRESHOLD_CONTAINER, 'data'),
State(C.STORE_APPSTATE_FILENAME, 'data'),
prevent_initial_call=True
)
def update_thresholds_html(value, filename):
if filename is None:
raise PreventUpdate()
state = AppState.from_cache(filename)
thresholds = []
for i in range(1, state.num_slices):
threshold = html.Div([
dcc.Slider(
id={'type': 'threshold-slider', 'index': i},
min=0,
max=255,
step=1,
value=state.imgThresholds[i],
marks=None,
tooltip={'always_visible': True, 'placement': 'right'},
)
], className='m-1 pl-1')
thresholds.append(threshold)
return thresholds
@app.callback(
Output(C.STORE_UPDATE_THRESHOLD_CONTAINER, 'data', allow_duplicate=True),
Output(C.LOGS_DATA, 'data', allow_duplicate=True),
# triggers regeneration of slices if we have them already
Input(C.CTR_DEPTH_MAP, 'children'),
Input(C.SLIDER_NUM_SLICES, 'value'),
State(C.STORE_APPSTATE_FILENAME, 'data'),
State(C.LOGS_DATA, 'data'),
prevent_initial_call=True
)
def update_thresholds(contents, num_slices, filename, logs_data):
if filename is None:
raise PreventUpdate()
state = AppState.from_cache(filename)
if (
state.num_slices == num_slices and
state.imgThresholds is not None and
len(state.imgThresholds) == num_slices + 1):
print("Number of slices is the same; not erasing data.")
raise PreventUpdate()
state.num_slices = num_slices
if state.depthMapData is None:
logs_data.append("No depth map data available")
state.imgThresholds = [0]
state.imgThresholds.extend([i * (255 // (num_slices - 1))
for i in range(1, num_slices)])
elif state.imgThresholds is None or len(state.imgThresholds) != num_slices:
state.imgThresholds = analyze_depth_histogram(
state.depthMapData, num_slices=num_slices)
logs_data.append(f"Thresholds: {state.imgThresholds}")
return True, logs_data
@app.callback(Output(C.STORE_APPSTATE_FILENAME, 'data', allow_duplicate=True),
Output(C.STORE_UPDATE_SLICE, 'data', allow_duplicate=True),
Output(C.STORE_TRIGGER_GEN_DEPTHMAP,
'data', allow_duplicate=True),
Output(C.IMAGE, 'src', allow_duplicate=True),
Output(C.CTR_DEPTH_MAP, 'children', allow_duplicate=True),
Output(C.PROGRESS_INTERVAL, 'disabled', allow_duplicate=True),
Input(C.UPLOAD_IMAGE, 'contents'),
State({'type': f'tab-content-main', 'index': ALL}, 'className'),
prevent_initial_call=True)
def update_input_image(contents, classnames):
if not contents:
raise PreventUpdate()
# allow an upload action only when the user is on the main tab
# or configuration tab
on_valid_tab = 'hidden' not in classnames[0] or 'hidden' not in classnames[-1]
if classnames is None or not on_valid_tab:
raise PreventUpdate()
state, filename = AppState.from_file_or_new(None)
content_type, content_string = contents.split(',')
# save the image data to the state
state.set_img_data(Image.open(
io.BytesIO(base64.b64decode(content_string))))
img_uri = state.serve_input_image()
return filename, True, True, img_uri, html.Img(
id='depthmap-image',
className='w-full p-0 object-scale-down'), False
@app.callback(Output(C.IMAGE, 'src', allow_duplicate=True),
Output(C.LOGS_DATA, 'data'),
Output(C.LOADING_UPLOAD, 'children', allow_duplicate=True),
Output(C.STORE_CLICKED_POINT, 'data'),
Input(C.SEG_MULTI_COMMIT, 'n_clicks'),
Input("el", "n_events"),
State("el", "event"),
State(C.STORE_RECT_DATA, 'data'),
State(C.DROPDOWN_MODE_SELECTOR, 'value'),
State(C.STORE_APPSTATE_FILENAME, 'data'),
State(C.LOGS_DATA, 'data'),
prevent_initial_call=True
)
def click_event(n_clicks, n_events, e, rect_data, mode, filename, logs_data):
if filename is None:
raise PreventUpdate()
state = AppState.from_cache(filename)
t_id = ctx.triggered_id
shiftClick = False
ctrlClick = False
if t_id == 'el':
if e is None or rect_data is None or state.imgData is None:
raise PreventUpdate()
pixel_x, pixel_y = find_pixel_from_event(state, e, rect_data)
# we need to find the depth even if we use instance segmentation
new_mask, depth = state.depth_slice_from_pixel(pixel_x, pixel_y)
state.slice_pixel = (pixel_x, pixel_y)
state.slice_pixel_depth = depth
logs_data.append(
f"Click event at pixel coordinates ({pixel_x}, {pixel_y}) at depth {depth}")
shiftClick = e["shiftKey"]
ctrlClick = e["ctrlKey"]
elif t_id != C.SEG_MULTI_COMMIT:
raise ValueError(f"Unexpected trigger {t_id}")
image = state.imgData
if mode == 'segment':
positive_points = []
negative_points = []
if state.multi_point_mode:
# if we are still selecting points, add them to the state
if t_id != C.SEG_MULTI_COMMIT:
state.points_selected.append(((pixel_x, pixel_y), ctrlClick))
return no_update, no_update, no_update, e
# if we are committing the points, add them to the positive and negative points
for point, ctrl_click in state.points_selected:
if ctrl_click:
negative_points.append(point)
else:
positive_points.append(point)
else:
assert t_id == 'el'
positive_points.append((pixel_x, pixel_y))
if state.segmentation_model == None:
state.segmentation_model = SegmentationModel()
# if we have a slice, take it and compose the background image over it
if state.selected_slice is not None:
image = state.slice_image_composed(
state.selected_slice, CompositeMode.NONE)
state.segmentation_model.segment_image(image)
# XXX - allow selection of the cheap vs the expensive alogrithm
new_mask = state.segmentation_model.mask_at_point_blended(
{
'positive_points': positive_points,
'negative_points': negative_points
})
logs_data.append(
f"Committed points {positive_points} and {negative_points} for Segment Anything")
# allow mask manipulation with add and subtract via shift and ctrl click
if state.slice_mask is None or not (shiftClick or ctrlClick):
state.slice_mask = new_mask
elif shiftClick:
state.slice_mask = np.maximum(state.slice_mask, new_mask)
elif ctrlClick:
state.slice_mask = np.minimum(state.slice_mask, 255 - new_mask)
if state.slice_mask is not None:
result = state.apply_mask(image, state.slice_mask)
img_data = state.serve_main_image(result)
else:
img_data = state.serve_main_image(state.imgData)
return img_data, logs_data, "", no_update
@app.callback(Output(C.STORE_TRIGGER_GEN_DEPTHMAP, 'data'),
Input(C.BTN_GENERATE_DEPTHMAP, 'n_clicks'),
State(C.STORE_APPSTATE_FILENAME, 'data'),
running=[
(Output(C.BTN_GENERATE_DEPTHMAP, 'disabled'), True, False)],
prevent_initial_call=True)
def generate_depth_map_from_button(n_clicks, filename):
if n_clicks is None or filename is None:
raise PreventUpdate()
return True
@app.callback(Output(C.STORE_TRIGGER_UPDATE_DEPTHMAP, 'data'),
Output(C.DEPTHMAP_OUTPUT, 'children'),
Input(C.STORE_TRIGGER_GEN_DEPTHMAP, 'data'),
State(C.STORE_APPSTATE_FILENAME, 'data'),
State(C.DROPDOWN_DEPTH_MODEL, 'value'),
prevent_initial_call=True)
def generate_depth_map_callback(ignored_data, filename, model):
if filename is None:
raise PreventUpdate()
print(f'Received a request to generate a depth map for state f{filename}')
state = AppState.from_cache(filename)
PIL_image = state.imgData
if PIL_image.mode == 'RGBA':
PIL_image = PIL_image.convert('RGB')
np_image = np.array(PIL_image)
depth_model = DepthEstimationModel(model=model)
if depth_model != state.depth_estimation_model:
state.depth_estimation_model = depth_model
state.depthMapData = generate_depth_map(
np_image, model=state.depth_estimation_model, progress_callback=progress_callback)
state.imgThresholds = None
state.to_file(filename, save_image_slices=False,
save_depth_map=True, save_input_image=False)
return True, ""
@app.callback(Output(C.CTR_DEPTH_MAP, 'children'),
Input(C.STORE_TRIGGER_UPDATE_DEPTHMAP, 'data'),
State(C.STORE_APPSTATE_FILENAME, 'data'),
prevent_initial_call=True)
def update_depth_map_callback(ignored_data, filename):
if filename is None:
raise PreventUpdate()
state = AppState.from_cache(filename)
depth_map_pil = Image.fromarray(state.depthMapData)
buffered = io.BytesIO()
depth_map_pil.save(buffered, format="PNG")
img_str = base64.b64encode(buffered.getvalue()).decode('utf-8')
return html.Img(
src='data:image/png;base64,{}'.format(img_str),
className='w-full h-full object-contain',
style={'height': '35vh'},
id='depthmap-image'), ""
@app.callback(Output(C.IMAGE, 'src', allow_duplicate=True),
Output(C.STORE_UPDATE_SLICE, 'data', allow_duplicate=True),
Output(C.LOGS_DATA, 'data', allow_duplicate=True),
Output(C.LOADING_UPLOAD, 'children', allow_duplicate=True),
Input(C.BTN_DELETE_SLICE, 'n_clicks'),
State(C.STORE_APPSTATE_FILENAME, 'data'),
State(C.LOGS_DATA, 'data'),
prevent_initial_call=True)
def delete_slice_request(n_clicks, filename, logs):
if n_clicks is None:
raise PreventUpdate()
if filename is None:
raise PreventUpdate()
state = AppState.from_cache(filename)
if state.selected_slice is None:
logs.append("No slice selected")
return no_update, no_update, logs, ""
logs.append(f"Deleted slice at index {state.selected_slice}")
state.delete_slice(state.selected_slice)
# sufficient to just change the json.
state.to_file(filename, save_image_slices=False,
save_depth_map=False, save_input_image=False)
return state.serve_main_image(state.imgData), True, logs, ""
@app.callback(Output(C.LOGS_DATA, 'data', allow_duplicate=True),
Input(C.BTN_COPY_SLICE, 'n_clicks'),
State(C.STORE_APPSTATE_FILENAME, 'data'),
State(C.LOGS_DATA, 'data'),
prevent_initial_call=True)
def copy_to_clipboard(n_clicks, filename, logs):
if n_clicks is None:
raise PreventUpdate()
if filename is None:
raise PreventUpdate()
state = AppState.from_cache(filename)
if state.slice_mask is None:
logs.append("No mask selected")
return logs
if state.selected_slice is not None:
image = state.slice_image_composed(
state.selected_slice, CompositeMode.NONE)
else:
image = state.imgData
image = np.array(image.convert('RGBA'))
image[:, :, 3] = state.slice_mask
state.clipboard_image = image
logs.append("Copied mask to clipboard")
return logs
@app.callback(Output(C.STORE_UPDATE_SLICE, 'data', allow_duplicate=True),
Output(C.LOGS_DATA, 'data', allow_duplicate=True),
Output(C.LOADING_UPLOAD, 'children', allow_duplicate=True),
Input(C.BTN_PASTE_SLICE, 'n_clicks'),
State(C.STORE_APPSTATE_FILENAME, 'data'),
State(C.LOGS_DATA, 'data'),
prevent_initial_call=True)
def paste_clipboard_request(n_clicks, filename, logs):
if n_clicks is None:
raise PreventUpdate()
if filename is None:
raise PreventUpdate()
state = AppState.from_cache(filename)
if state.clipboard_image is None:
logs.append("Nothing in the clipboard")
return no_update, logs, no_update
if state.selected_slice is None:
logs.append("No slice selected")
return no_update, logs, no_update
image = state.clipboard_image
# updates the image slice in place - dangerous
blend_with_alpha(state.image_slices[state.selected_slice].image, image)
state.image_slices[state.selected_slice].new_version()
state.to_file(filename, save_image_slices=False,
save_depth_map=False, save_input_image=False)
logs.append(f"Pasted clipboard to slice {state.selected_slice}")
return True, logs, ""
@app.callback(Output(C.STORE_UPDATE_SLICE, 'data', allow_duplicate=True),
Output(C.LOGS_DATA, 'data', allow_duplicate=True),
Output(C.LOADING_UPLOAD, 'children', allow_duplicate=True),
Input(C.BTN_REMOVE_SLICE, 'n_clicks'),
State(C.STORE_APPSTATE_FILENAME, 'data'),
State(C.LOGS_DATA, 'data'),
prevent_initial_call=True)
def remove_mask_slice_request(n_clicks, filename, logs):
if n_clicks is None:
raise PreventUpdate()
if filename is None:
raise PreventUpdate()
state = AppState.from_cache(filename)
if state.slice_mask is None:
logs.append("No mask selected")
return no_update, logs, no_update
if state.selected_slice is None:
logs.append("No slice selected")
return no_update, logs, no_update
final_mask = remove_mask_from_alpha(
state.image_slices[state.selected_slice].image, state.slice_mask)
state.image_slices[state.selected_slice].image[:, :, 3] = final_mask
state.image_slices[state.selected_slice].new_version()
state.to_file(filename, save_image_slices=False,
save_depth_map=False, save_input_image=False)
logs.append(f"Removed mask from slice {state.selected_slice}")
return True, logs, ""
@app.callback(Output(C.STORE_UPDATE_SLICE, 'data', allow_duplicate=True),
Output(C.LOGS_DATA, 'data', allow_duplicate=True),
Output(C.LOADING_UPLOAD, 'children', allow_duplicate=True),
Input(C.BTN_ADD_SLICE, 'n_clicks'),
State(C.STORE_APPSTATE_FILENAME, 'data'),
State(C.LOGS_DATA, 'data'),
running=[(Output(C.BTN_ADD_SLICE, 'disabled'), True, False)],
prevent_initial_call=True)
def add_mask_slice_request(n_clicks, filename, logs):
if n_clicks is None:
raise PreventUpdate()
if filename is None:
raise PreventUpdate()
state = AppState.from_cache(filename)
if state.slice_mask is None:
logs.append("No mask selected")
return no_update, logs, no_update
if state.selected_slice is None:
logs.append("No slice selected")
return no_update, logs, no_update
# XXX - should we create an option to copy from the composed image?
image = create_slice_from_mask(
state.imgData, state.slice_mask, num_expand=EXPAND_MASK)
# updates the image slice in place - dangerous
blend_with_alpha(state.image_slices[state.selected_slice].image, image)
state.image_slices[state.selected_slice].new_version()
state.to_file(filename, save_image_slices=False,
save_depth_map=False, save_input_image=False)
logs.append(f"Added mask to slice {state.selected_slice}")
return True, logs, ""
@app.callback(Input(C.TEXT_POSITIVE_PROMPT, 'value'),
Input(C.TEXT_NEGATIVE_PROMPT, 'value'),
State(C.STORE_APPSTATE_FILENAME, 'data'),
prevent_initial_call=True
)
def update_prompt_text(positive, negative, filename):
if filename is None:
raise PreventUpdate()
state = AppState.from_cache(filename)
if state.selected_slice is None:
raise PreventUpdate()
if (state.image_slices[state.selected_slice].positive_prompt == positive and
state.image_slices[state.selected_slice].negative_prompt == negative):
raise PreventUpdate()
state.image_slices[state.selected_slice].positive_prompt = positive
state.image_slices[state.selected_slice].negative_prompt = negative
state.to_file(filename, save_image_slices=False,
save_depth_map=False, save_input_image=False)
@app.callback(Output(C.STORE_UPDATE_SLICE, 'data', allow_duplicate=True),
Output(C.TEXT_POSITIVE_PROMPT, 'value', allow_duplicate=True),
Output(C.TEXT_NEGATIVE_PROMPT, 'value', allow_duplicate=True),
Output(C.LOGS_DATA, 'data', allow_duplicate=True),
Output(C.LOADING_UPLOAD, 'children', allow_duplicate=True),
Input(C.BTN_CREATE_SLICE, 'n_clicks'),
State(C.STORE_APPSTATE_FILENAME, 'data'),
State(C.LOGS_DATA, 'data'),
running=[(Output(C.BTN_CREATE_SLICE, 'disabled'), True, False)],
prevent_initial_call=True)
def create_single_slice_request(n_clicks, filename, logs):
if n_clicks is None:
raise PreventUpdate()
if filename is None:
raise PreventUpdate()
state = AppState.from_cache(filename)
if state.imgData is None:
logs.append("No image available")
return no_update, no_update, no_update, logs, no_update
depth = 127
if state.slice_mask is None:
# create an empty image that the user can inpaint if they want to
image = Image.new('RGBA', state.imgData.size, (0, 0, 0, 0))
else:
if state.slice_pixel is not None:
depth = state.slice_pixel_depth
image = create_slice_from_mask(
state.imgData, state.slice_mask, num_expand=EXPAND_MASK)
image = ImageSlice(image, depth)
state.selected_slice = state.add_slice(image)
image.save_image()
state.to_file(filename, save_image_slices=False,
save_depth_map=False, save_input_image=False)
logs.append("Created a slice from the mask")
return True, "", "", logs, ""
@app.callback(Output(C.STORE_UPDATE_SLICE, 'data', allow_duplicate=True),
Output(C.LOGS_DATA, 'data', allow_duplicate=True),
Input(C.BTN_BALANCE_SLICE, 'n_clicks'),
State(C.STORE_APPSTATE_FILENAME, 'data'),
State(C.LOGS_DATA, 'data'),
prevent_initial_call=True)
def balance_slices_request(n_clicks, filename, logs):
if n_clicks is None:
raise PreventUpdate()
if filename is None:
raise PreventUpdate()
state = AppState.from_cache(filename)
if len(state.image_depths) == 0:
raise PreventUpdate()
state.balance_slices_depths()
state.to_file(filename, save_image_slices=False,
save_depth_map=False, save_input_image=False)
logs.append("Balanced slice depths")
return True, logs
@app.callback(Output(C.STORE_GENERATE_SLICE, 'data'),
Input(C.BTN_GENERATE_SLICE, 'n_clicks'))
def generate_slices_request(n_clicks):
if n_clicks is None:
raise PreventUpdate()
return n_clicks
@app.callback(Output(C.CTR_SLICE_IMAGES, 'children'),
Output('gen-slice-output', 'children', allow_duplicate=True),
Output(C.IMAGE, 'src', allow_duplicate=True),
Input(C.STORE_UPDATE_SLICE, 'data'),
State(C.STORE_APPSTATE_FILENAME, 'data'),
prevent_initial_call=True)
def update_slices(ignored_data, filename):
if filename is None:
raise PreventUpdate()
state = AppState.from_cache(filename)
if len(state.image_slices) == 0:
# a user may have uploaded a new image and not generated slices yet
return [], "", no_update
if state.depthMapData is None:
raise PreventUpdate()
caret_color_enabled = "has-history-color"
caret_color_disabled = "no-history-color"
img_container = []
for i, image_slice in enumerate(state.image_slices):
img_data = state.serve_slice_image(i)
left_color = caret_color_enabled if image_slice.can_undo(
forward=False) else caret_color_disabled
left_disabled = True if left_color == caret_color_disabled else False
right_color = caret_color_enabled if image_slice.can_undo(
forward=True) else caret_color_disabled
right_disabled = True if right_color == caret_color_disabled else False
left_id = {'type': 'slice-undo-backwards', 'index': i}
right_id = {'type': 'slice-undo-forwards', 'index': i}
slice_name = html.Div([
html.Button(
title="Download image for manipuation in an external editor",
className="fa-solid fa-download pr-1",
id={'type': 'slice-info', 'index': i}),
html.Button(
title="Undo last change",
className=f"fa-solid fa-caret-left {left_color} pr-1",
id=left_id, disabled=left_disabled),
html.Button(
title="Redo last change",
className=f"fa-solid fa-caret-right {right_color} pr-1",
id=right_id, disabled=right_disabled),
Path(image_slice.filename).stem])
# slice creation with select a slice so we need to highlight it here
highlight_class = f'overlay' if state.selected_slice == i else 'hidden'
img_container.append(
dcc.Upload(
html.Div([
html.Div(
# The number to display
children=f"{int(image_slice.depth)}",
id={'type': C.ID_SLICE_DEPTH_DISPLAY, 'index': i},
className='depth-number-display'
),
html.Div(className=highlight_class,
id={'type': C.ID_SLICE_OVERLAY, 'index': i}),
dcc.Input(id={'type': C.INPUT_SLICE_DEPTH, 'index': i},
className='depth-number-input hidden',
type='number',
debounce=True,
inputMode='numeric',
maxLength=3,
value=f"{int(image_slice.depth)}"),
html.Img(
src=img_data,
className='image-border',
id={'type': 'slice', 'index': i},),
html.Div(children=slice_name,
className='text-center text-overlay p-1')
], style={'position': 'relative'}),
id={'type': C.UPLOAD_SLICE, 'index': i},
disable_click=True,
)
)
img_data = no_update
if state.selected_slice is not None:
assert state.selected_slice >= 0 and state.selected_slice < len(
state.image_slices)
mode = CompositeMode.CHECKERBOARD if state.use_checkerboard else CompositeMode.GRAYSCALE
img_data = state.serve_slice_image_composed(
state.selected_slice, mode=mode)
state.slice_pixel = None
state.slice_pixel_depth = None
state.slice_mask = None
return img_container, "", img_data
@app.callback(
Output({'type': C.INPUT_SLICE_DEPTH, 'index': MATCH}, 'className'),
Input({'type': C.ID_SLICE_DEPTH_DISPLAY, 'index': MATCH}, 'n_clicks'),
State({'type': C.INPUT_SLICE_DEPTH, 'index': MATCH}, 'className'),
prevent_initial_call=True
)
def display_depth_input(n_clicks, class_name):
if n_clicks is None:
raise PreventUpdate()
class_name = class_name.replace('hidden', '')
return class_name
@app.callback(
Output(C.STORE_UPDATE_SLICE, 'data', allow_duplicate=True),
Output(C.STORE_INPAINTING, 'data', allow_duplicate=True),
Input({'type': C.INPUT_SLICE_DEPTH, 'index': ALL}, 'value'),
Input({'type': C.INPUT_SLICE_DEPTH, 'index': ALL}, 'n_submit'),
State(C.STORE_APPSTATE_FILENAME, 'data'),
prevent_initial_call=True
)
def record_depth_input(values, n_submits, filename):
if filename is None or values is None or n_submits is None:
raise PreventUpdate()
index = ctx.triggered_id['index']
if n_submits[index] is None:
raise PreventUpdate()
value = int(values[index])
# need to re-order and validate the depth values
state = AppState.from_cache(filename)
new_index = state.change_slice_depth(index, value)
if index != new_index:
state.selected_slice = None
state.to_file(filename, save_image_slices=False,
save_depth_map=False, save_input_image=False)
return True, True
@app.callback(Output(C.STORE_UPDATE_SLICE, 'data', allow_duplicate=True),
Input({'type': 'slice-undo-backwards', 'index': ALL}, 'n_clicks'),
Input({'type': 'slice-undo-forwards', 'index': ALL}, 'n_clicks'),
State(C.STORE_APPSTATE_FILENAME, 'data'),
prevent_initial_call=True)
def undo_slice(n_clicks_backwards, n_clicks_forwards, filename):
if filename is None:
raise PreventUpdate()
state = AppState.from_cache(filename)
# don't need to use ctx.triggered_id since we are repaining the whole thing
index = None
forward = None
if any(n_clicks_backwards):
index = n_clicks_backwards.index(1)
forward = False
elif any(n_clicks_forwards):
index = n_clicks_forwards.index(1)
forward = True
else:
raise PreventUpdate()
if not state.image_slices[index].undo(forward=forward):
print(f"Cannot undo slice {index} with forward {forward}")
raise PreventUpdate()
# only save the json with the updated file mapping
state.to_file(filename, save_image_slices=False,
save_depth_map=False, save_input_image=False)
return True