-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwebui.py
More file actions
5310 lines (4827 loc) · 347 KB
/
Copy pathwebui.py
File metadata and controls
5310 lines (4827 loc) · 347 KB
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
import gradio as gr
import random
import os
import json
import html as html_lib
import ast
import time
import re
import threading
from datetime import date, datetime, timedelta
import shared
import modules.config
import fooocus_version
import modules.html
import modules.async_worker as worker
import modules.constants as constants
import modules.flags as flags
import modules.gradio_hijack as grh
import modules.style_sorter as style_sorter
import modules.wildprompt_sorter as wildprompt_sorter
import modules.sdxl_styles
import modules.meta_parser
import modules.prompt_config
import modules.lora_notes
import modules.lora_training
import modules.history_db
import args_manager
import copy
import launch
from extras.inpaint_mask import SAMOptions
from modules.private_logger import get_current_html_path
from modules.ui_gradio_extensions import reload_javascript
from modules.auth import auth_enabled, check_auth
from modules.util import is_json
people_dir = os.path.abspath(os.path.join('input', 'people'))
legacy_people_dir = os.path.abspath('input')
history_debug_enabled = bool(
getattr(args_manager.args, 'history_debug', False)
or str(os.getenv('FOOOCUS_HISTORY_DEBUG') or '').strip().lower() in ['1', 'true', 'yes', 'on']
)
print(
'[HistoryDebug] status=',
'enabled' if history_debug_enabled else 'disabled',
'source=',
'arg' if getattr(args_manager.args, 'history_debug', False) else (
'env' if str(os.getenv('FOOOCUS_HISTORY_DEBUG') or '').strip().lower() in ['1', 'true', 'yes', 'on'] else 'off'
),
'tip=use --history-debug or FOOOCUS_HISTORY_DEBUG=1',
flush=True
)
def history_debug(*parts):
if not history_debug_enabled:
return
print('[HistoryDebug]', *parts, flush=True)
def sanitize_person_name(name):
name = re.sub(r'[<>:"/\\|?*\x00-\x1f]', '_', str(name or '').strip())
name = re.sub(r'\s+', ' ', name).strip(' .')
return name[:80]
def get_uploaded_file_path(file):
if file is None:
return None
if isinstance(file, str):
return file
if isinstance(file, dict):
return file.get('name') or file.get('path')
return getattr(file, 'name', None)
def flatten_person_likeness_files(files):
if files is None:
return []
if isinstance(files, str) and files.strip().startswith('['):
try:
files = json.loads(files)
except Exception:
files = [files]
if isinstance(files, (str, dict)) or hasattr(files, 'name'):
files = [files]
return [file for file in files if get_uploaded_file_path(file) is not None]
def parse_person_likeness_paths(paths_json):
try:
paths = json.loads(paths_json or '[]')
except Exception:
paths = []
return [
path for path in paths
if isinstance(path, str) and os.path.exists(path)
]
def encode_person_likeness_paths(paths):
deduped = []
seen = set()
for path in paths:
path = os.path.abspath(path)
key = os.path.normcase(path)
if os.path.exists(path) and key not in seen:
deduped.append(path)
seen.add(key)
return json.dumps(deduped)
def preview_person_likeness_paths(paths_json):
return parse_person_likeness_paths(paths_json)
def append_person_likeness_files(files, paths_json):
paths = parse_person_likeness_paths(paths_json)
paths += [get_uploaded_file_path(file) for file in flatten_person_likeness_files(files)]
encoded = encode_person_likeness_paths(paths)
return encoded, preview_person_likeness_paths(encoded), gr.update(value=None)
def clamp_float(value, default, minimum, maximum):
try:
value = float(value)
except Exception:
value = default
return max(minimum, min(maximum, value))
PERSON_LIKENESS_PRESETS = {
'Baseline': (1.00, 1.00, 0.30),
'ID+': (1.15, 1.00, 0.25),
'Face+': (1.00, 1.15, 0.25),
'Early Lock': (1.05, 1.05, 0.15),
'Strong Match': (1.20, 1.15, 0.15),
'Aggressive Match': (1.30, 1.25, 0.10),
'Flexible': (0.90, 0.90, 0.35),
'Dataset Candidate': (1.15, 1.10, 0.20),
}
def apply_person_likeness_preset(name):
return PERSON_LIKENESS_PRESETS.get(name, PERSON_LIKENESS_PRESETS['Baseline'])
def clear_person_likeness_settings():
strength, face_weight, face_start = apply_person_likeness_preset('Baseline')
return '', gr.update(value=None), False, 'person', strength, face_weight, face_start, 'Baseline', \
'[]', [], gr.update(value=None), 'Person likeness cleared and settings reset to Baseline.'
def list_saved_people():
saved_people = set()
for base_dir in [people_dir, legacy_people_dir]:
if not os.path.exists(base_dir):
continue
for name in os.listdir(base_dir):
person_dir = os.path.join(base_dir, name)
if os.path.isdir(person_dir) and os.path.exists(os.path.join(person_dir, 'person.json')):
saved_people.add(name)
return sorted(saved_people, key=lambda x: x.lower())
def resolve_saved_person_dir(person_name):
for base_dir in [people_dir, legacy_people_dir]:
person_dir = os.path.abspath(os.path.join(base_dir, person_name))
if os.path.exists(os.path.join(person_dir, 'person.json')) and os.path.commonpath([base_dir, person_dir]) == base_dir:
return person_dir, base_dir
return os.path.abspath(os.path.join(people_dir, person_name)), people_dir
def save_person_likeness(name, enabled, subject, strength, face_weight, face_start, files):
from PIL import Image
person_name = sanitize_person_name(name)
if person_name == '':
return gr.update(), 'Enter a name before saving.', gr.update(), gr.update()
valid_files = flatten_person_likeness_files(files)
if len(valid_files) == 0:
return gr.update(), 'Add at least one photo before saving.', gr.update(), gr.update()
os.makedirs(people_dir, exist_ok=True)
person_dir = os.path.abspath(os.path.join(people_dir, person_name))
if os.path.commonpath([people_dir, person_dir]) != people_dir:
return gr.update(), 'Invalid person name.', gr.update(), gr.update()
if os.path.exists(person_dir) and os.listdir(person_dir) and not os.path.exists(os.path.join(person_dir, 'person.json')):
return gr.update(), f'Cannot save: input folder already exists and is not a saved person: {person_name}', gr.update(), gr.update()
os.makedirs(person_dir, exist_ok=True)
saved_count = 0
image_files = []
save_stamp = time.strftime('%Y%m%d_%H%M%S')
for file in valid_files:
image_path = get_uploaded_file_path(file)
source_path = os.path.abspath(image_path)
if os.path.exists(source_path) and os.path.commonpath([person_dir, source_path]) == person_dir:
image_files.append(os.path.basename(source_path))
saved_count += 1
continue
try:
filename = f'{save_stamp}_{saved_count + 1:02d}.png'
Image.open(image_path).convert('RGB').save(os.path.join(person_dir, filename))
image_files.append(filename)
saved_count += 1
except Exception:
pass
if saved_count == 0:
return gr.update(), 'No valid image files were found.', gr.update(), gr.update()
person_config = {
'name': person_name,
'enabled': bool(enabled),
'subject': subject if subject in flags.person_likeness_classes else 'person',
'identity_strength': clamp_float(strength, 1.0, 0.0, modules.config.default_person_likeness_strength_max),
'face_weight': clamp_float(face_weight, modules.config.default_person_likeness_face_weight, 0.0,
modules.config.default_person_likeness_face_weight_max),
'face_weight_start': clamp_float(face_start, modules.config.default_person_likeness_face_start, 0.0, 1.0),
'image_count': saved_count,
'image_files': image_files
}
with open(os.path.join(person_dir, 'person.json'), 'w', encoding='utf-8') as f:
json.dump(person_config, f, indent=2)
image_file_set = set(image_files)
for filename in os.listdir(person_dir):
path = os.path.join(person_dir, filename)
if os.path.isfile(path) and filename not in image_file_set and os.path.splitext(filename)[1].lower() in ['.png', '.jpg', '.jpeg', '.webp']:
try:
os.remove(path)
except Exception:
pass
saved_paths = encode_person_likeness_paths([os.path.join(person_dir, filename) for filename in image_files])
choices = list_saved_people()
return gr.update(choices=choices, value=person_name), f'Saved {saved_count} photo(s) for {person_name}.', saved_paths, preview_person_likeness_paths(saved_paths)
def load_person_likeness(name):
person_name = sanitize_person_name(name)
if person_name == '':
return True, 'person', 1.0, modules.config.default_person_likeness_face_weight, \
modules.config.default_person_likeness_face_start, '[]', 'Choose a saved person to load.'
person_dir, base_dir = resolve_saved_person_dir(person_name)
if not os.path.exists(person_dir) or os.path.commonpath([base_dir, person_dir]) != base_dir:
return True, 'person', 1.0, modules.config.default_person_likeness_face_weight, \
modules.config.default_person_likeness_face_start, '[]', f'Could not find saved person: {person_name}'
metadata = {}
metadata_path = os.path.join(person_dir, 'person.json')
if os.path.exists(metadata_path):
try:
with open(metadata_path, 'r', encoding='utf-8') as f:
metadata = json.load(f)
except Exception:
metadata = {}
subject = metadata.get('subject', 'person')
if subject not in flags.person_likeness_classes:
subject = 'person'
enabled = bool(metadata.get('enabled', True))
strength = clamp_float(metadata.get('identity_strength', metadata.get('strength', 1.0)), 1.0, 0.0,
modules.config.default_person_likeness_strength_max)
face_weight = clamp_float(metadata.get('face_weight', modules.config.default_person_likeness_face_weight),
modules.config.default_person_likeness_face_weight, 0.0,
modules.config.default_person_likeness_face_weight_max)
face_start = clamp_float(metadata.get('face_weight_start', metadata.get('face_start',
modules.config.default_person_likeness_face_start)),
modules.config.default_person_likeness_face_start, 0.0, 1.0)
image_files = metadata.get('image_files')
if isinstance(image_files, list):
image_paths = [
os.path.join(person_dir, filename)
for filename in image_files
if isinstance(filename, str)
and os.path.exists(os.path.join(person_dir, filename))
and os.path.splitext(filename)[1].lower() in ['.png', '.jpg', '.jpeg', '.webp']
]
else:
image_paths = sorted([
os.path.join(person_dir, filename)
for filename in os.listdir(person_dir)
if os.path.splitext(filename)[1].lower() in ['.png', '.jpg', '.jpeg', '.webp']
])
return enabled, subject, strength, face_weight, face_start, encode_person_likeness_paths(image_paths), \
f'Loaded {len(image_paths)} photo(s) for {person_name}.'
def build_prompt_config(prompt, negative_prompt, style_selections, wildprompt_selections, wildprompt_generate_all,
wildprompt_test_separately, wildprompt_line_selections,
performance_selection, overwrite_step,
overwrite_switch, aspect_ratios_selection, overwrite_width, overwrite_height,
guidance_scale, sharpness, adm_scaler_positive, adm_scaler_negative, adm_scaler_end,
refiner_swap_method, adaptive_cfg, clip_skip, base_model, refiner_model, refiner_switch,
sampler_name, scheduler_name, vae_name, seed_random, image_seed, inpaint_engine,
inpaint_mode, person_likeness_enabled, person_likeness_class, person_likeness_strength,
person_likeness_face_weight, person_likeness_face_start, person_likeness_paths,
freeu_enabled, freeu_b1, freeu_b2, freeu_s1, freeu_s2, *lora_values):
lora_prompt_values = list(lora_values[-modules.config.default_max_lora_number:])
lora_values = lora_values[:-modules.config.default_max_lora_number]
resolution_numbers = re.findall(r'\d+', str(aspect_ratios_selection))
if len(resolution_numbers) >= 2:
resolution = (int(resolution_numbers[0]), int(resolution_numbers[1]))
elif int(overwrite_width) > 0 and int(overwrite_height) > 0:
resolution = (int(overwrite_width), int(overwrite_height))
else:
resolution = None
generate_all_files = modules.sdxl_styles.normalize_wildprompt_generate_all_files(
wildprompt_selections,
wildprompt_generate_all,
)
config_data = {
'prompt': prompt,
'negative_prompt': negative_prompt,
'styles': str(style_selections or []),
'wildprompts': str(wildprompt_selections or []),
'wildprompt_generate_all': len(generate_all_files) > 0,
'wildprompt_generate_all_files': str(generate_all_files),
'wildprompt_test_separately': bool(wildprompt_test_separately),
'wildprompt_line_selections': wildprompt_line_selections if isinstance(wildprompt_line_selections, str) else '{}',
'performance': performance_selection,
'steps': int(overwrite_step),
'overwrite_switch': overwrite_switch,
'guidance_scale': guidance_scale,
'sharpness': sharpness,
'adm_guidance': str((adm_scaler_positive, adm_scaler_negative, adm_scaler_end)),
'refiner_swap_method': refiner_swap_method,
'adaptive_cfg': adaptive_cfg,
'clip_skip': int(clip_skip),
'base_model': base_model,
'refiner_model': refiner_model,
'refiner_switch': refiner_switch,
'sampler': sampler_name,
'scheduler': scheduler_name,
'vae': vae_name,
'inpaint_engine_version': inpaint_engine,
'inpaint_method': inpaint_mode,
'person_likeness_enabled': bool(person_likeness_enabled),
'person_likeness_class': person_likeness_class,
'person_likeness_strength': person_likeness_strength,
'person_likeness_face_weight': person_likeness_face_weight,
'person_likeness_face_start': person_likeness_face_start,
'person_likeness_paths': person_likeness_paths if isinstance(person_likeness_paths, str) else '[]',
'saved_at': time.strftime('%Y-%m-%d %H:%M:%S'),
'version': 'Fooocus v' + fooocus_version.version
}
if resolution is not None:
config_data['resolution'] = str(resolution)
if not seed_random:
config_data['seed'] = str(image_seed)
if freeu_enabled:
config_data['freeu'] = str((freeu_b1, freeu_b2, freeu_s1, freeu_s2))
for index in range(0, len(lora_values), 3):
enabled, filename, weight = lora_values[index:index + 3]
if filename != 'None':
config_data[f'lora_combined_{index // 3 + 1}'] = f'{enabled} : {filename} : {weight}'
for index, lora_prompt in enumerate(lora_prompt_values):
lora_prompt = str(lora_prompt or '').strip()
if lora_prompt != '':
config_data[f'lora_prompt_{index + 1}'] = lora_prompt
return config_data
def append_lora_note_to_prompt(prompt, lora_note):
prompt = str(prompt or '').strip()
lora_note = str(lora_note or '').strip()
if lora_note == '':
return prompt
if prompt == '':
return lora_note
return f'{prompt}, {lora_note}'
def get_task(*args):
args = list(args)
args.pop(0)
return worker.AsyncTask(args=args)
def set_quick_preview_mode(enabled):
return bool(enabled)
def make_queue_panel_html():
snapshot = worker.get_queue_snapshot()
active = snapshot.get('active')
pending = snapshot.get('pending') or []
if active is None and len(pending) == 0:
return '<div class="queue-panel queue-panel-empty">Queue is empty.</div>'
rows = ['<div class="queue-panel">']
rows.append('<div class="queue-panel-header"><span>Queue</span><span>Images</span><span>Steps</span><span>Action</span></div>')
def row_html(task, status):
badges = []
if task.get('quick_preview'):
badges.append('<span class="queue-badge">Preview</span>')
prompt = html_lib.escape(task.get('prompt', '(empty prompt)'))
performance = html_lib.escape(str(task.get('performance') or ''))
steps = int(task.get("steps", 0) or 0)
total_steps = int(task.get("total_steps", 0) or 0)
badge_html = ''.join(badges)
if status == 'active':
action = (
'<div class="queue-action-group">'
'<button type="button" class="queue-skip-button">Skip</button>'
'<button type="button" class="queue-stop-button">Stop</button>'
'</div>'
)
else:
action = (
f'<button type="button" class="queue-remove-button" '
f'data-queue-id="{int(task.get("id", 0))}">Remove from Queue</button>'
)
return (
f'<div class="queue-row queue-row-{status}">'
f'<div><strong>{status.title()}</strong><span>{prompt}</span>{badge_html}</div>'
f'<div>{int(task.get("images", 0) or 0)}</div>'
f'<div>{total_steps}<small>{steps} per image</small><small>{performance}</small></div>'
f'<div>{action}</div>'
f'</div>'
)
if active is not None:
rows.append(row_html(active, 'active'))
for task in pending:
rows.append(row_html(task, 'pending'))
rows.append('</div>')
return ''.join(rows)
def get_generation_tracking_task(task):
active_task = worker.get_current_task()
if active_task is not None and not getattr(active_task, 'completed', False):
return active_task
return task
def get_active_generation_task(fallback_task=None):
active_task = worker.get_current_task()
if active_task is not None and not getattr(active_task, 'completed', False):
return active_task
if fallback_task is not None and not getattr(fallback_task, 'completed', False):
return fallback_task
return None
def enqueue_generate_task(*args):
task = get_task(*args)
should_monitor = False
tracking_task = task
if len(task.args) > 0:
pending_count = worker.append_async_task(task)
should_monitor = worker.begin_queue_monitor()
tracking_task = get_generation_tracking_task(task)
print(f'[Queue] Added generation task. Pending tasks: {pending_count}')
return tracking_task, should_monitor, \
gr.update(visible=False, interactive=False), \
gr.update(visible=False, interactive=False), \
gr.update(visible=True, interactive=True), \
gr.update(visible=True, interactive=True), \
gr.update(), \
gr.update(value=make_queue_panel_html()), \
True
def remove_queued_task(queue_id):
removed = worker.remove_pending_task(queue_id)
message = 'Removed queued item.' if removed else 'Queued item was already running or missing.'
return gr.update(value=make_queue_panel_html()), message
def prune_missing_gallery_paths(gallery_items):
pruned = []
changed = False
for item in list(gallery_items or []):
if isinstance(item, str) and not os.path.exists(item):
changed = True
continue
pruned.append(item)
return pruned, changed
def monitor_generate_queue(should_monitor, session_history):
session_history, session_history_pruned = prune_missing_gallery_paths(session_history)
if not should_monitor:
yield gr.update(), gr.update(), gr.update(), \
gr.update(value=session_history) if session_history_pruned else gr.update(), session_history, \
gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update()
return
def get_quick_preview_indices():
indices = []
for index, image_item in enumerate(session_history):
if isinstance(image_item, str):
config_data = worker.get_generated_image_config(image_item)
if bool(config_data.get('quick_preview', False)):
indices.append(index)
return json.dumps(indices)
observed_task = None
execution_start_time = None
def get_latest_display_image(image_items):
image_items = list(image_items or [])
for image_item in reversed(image_items):
if isinstance(image_item, str):
if os.path.exists(image_item):
return image_item
continue
return image_item
return None
def append_task_results_to_session_history(task, image_items=None):
if image_items is None:
image_items = getattr(task, 'results', []) or []
changed = False
for image_item in list(image_items):
if isinstance(image_item, str):
if not os.path.exists(image_item):
continue
if image_item not in session_history:
session_history.append(image_item)
changed = True
elif image_item not in session_history:
session_history.append(image_item)
changed = True
return changed
yield gr.update(visible=True, value=modules.html.make_progress_html(1, 'Waiting for task to start ...')), \
gr.update(visible=True, value=None), \
gr.update(visible=False, value=None), \
gr.update(visible=True), \
gr.update(), \
gr.update(visible=True, interactive=True), \
gr.update(visible=False, interactive=False), \
gr.update(visible=False, interactive=False), \
gr.update(value=make_queue_panel_html()), \
gr.update(value=get_quick_preview_indices()), \
True
try:
while True:
worker.heartbeat_queue_monitor()
active_task = worker.get_current_task()
if active_task is not None and observed_task is not active_task:
observed_task = active_task
execution_start_time = time.perf_counter()
if observed_task is None:
pending_count = worker.get_pending_task_count()
if pending_count == 0:
break
yield gr.update(
visible=True,
value=modules.html.make_progress_html(1, f'Waiting for queued task ... ({pending_count} pending)')
), gr.update(), gr.update(), gr.update(), \
gr.update(), \
gr.update(visible=True, interactive=True), \
gr.update(visible=False, interactive=False), \
gr.update(visible=False, interactive=False), \
gr.update(value=make_queue_panel_html()), \
gr.update(value=get_quick_preview_indices()), \
True
time.sleep(0.1)
continue
if worker.get_task_yield_count(observed_task) == 0:
time.sleep(0.01)
continue
event = worker.get_latest_display_yield(preferred_task=observed_task, same_task_only=True)
if event is None:
time.sleep(0.01)
continue
observed_task, flag, product = event
if flag == 'preview':
percentage, title, image = product
session_history_changed = append_task_results_to_session_history(observed_task)
yield gr.update(visible=True, value=modules.html.make_progress_html(percentage, title)), \
gr.update(visible=True, value=image) if image is not None else gr.update(), \
gr.update(), \
gr.update(visible=True, value=session_history) if session_history_changed else gr.update(visible=True), \
session_history, \
gr.update(visible=True, interactive=True), \
gr.update(visible=False, interactive=False), \
gr.update(visible=False, interactive=False), \
gr.update(value=make_queue_panel_html()), \
gr.update(value=get_quick_preview_indices()), \
True
if flag == 'results':
for image_item in product:
if isinstance(image_item, str):
if not os.path.exists(image_item):
continue
if image_item not in session_history:
session_history.append(image_item)
else:
session_history.append(image_item)
latest_image = get_latest_display_image(product)
yield gr.update(visible=True), \
gr.update(visible=True, value=latest_image) if latest_image is not None else gr.update(visible=True), \
gr.update(visible=False), \
gr.update(visible=True, value=session_history), \
session_history, \
gr.update(visible=True, interactive=True), \
gr.update(visible=False, interactive=False), \
gr.update(visible=False, interactive=False), \
gr.update(value=make_queue_panel_html()), \
gr.update(value=get_quick_preview_indices()), \
True
if flag == 'finish':
if not args_manager.args.disable_enhance_output_sorting:
product = sort_enhance_images(product, observed_task)
for image_item in product:
if isinstance(image_item, str):
if not os.path.exists(image_item):
continue
if image_item not in session_history:
session_history.append(image_item)
else:
session_history.append(image_item)
latest_image = get_latest_display_image(product)
yield gr.update(visible=False), \
gr.update(visible=True, value=latest_image) if latest_image is not None else gr.update(visible=True), \
gr.update(visible=False), \
gr.update(visible=True, value=session_history), \
session_history, \
gr.update(visible=True, interactive=True), \
gr.update(visible=False, interactive=False), \
gr.update(visible=False, interactive=False), \
gr.update(value=make_queue_panel_html()), \
gr.update(value=get_quick_preview_indices()), \
True
if execution_start_time is not None:
execution_time = time.perf_counter() - execution_start_time
print(f'Total time: {execution_time:.2f} seconds')
observed_task = None
execution_start_time = None
finally:
worker.end_queue_monitor()
yield gr.update(), gr.update(), gr.update(), gr.update(), \
gr.update(), \
gr.update(visible=True, interactive=True), \
gr.update(visible=False, interactive=False), \
gr.update(visible=False, interactive=False), \
gr.update(value=make_queue_panel_html()), \
gr.update(value=get_quick_preview_indices()), \
False
def poll_generate_queue(task, is_generating, session_history):
session_history, session_history_pruned = prune_missing_gallery_paths(session_history)
def get_quick_preview_indices():
indices = []
for index, image_item in enumerate(session_history):
if isinstance(image_item, str):
config_data = worker.get_generated_image_config(image_item)
if bool(config_data.get('quick_preview', False)):
indices.append(index)
return json.dumps(indices)
def get_latest_display_image(image_items):
image_items = list(image_items or [])
for image_item in reversed(image_items):
if isinstance(image_item, str):
if os.path.exists(image_item):
return image_item
continue
return image_item
return None
def append_task_results_to_session_history(task, image_items=None):
if image_items is None:
image_items = getattr(task, 'results', []) or []
changed = False
for image_item in list(image_items):
if isinstance(image_item, str):
if not os.path.exists(image_item):
continue
if image_item not in session_history:
session_history.append(image_item)
changed = True
elif image_item not in session_history:
session_history.append(image_item)
changed = True
return changed
def idle_updates():
return gr.update(), gr.update(), gr.update(), \
gr.update(value=session_history) if session_history_pruned else gr.update(), session_history, \
gr.update(visible=True, interactive=True), \
gr.update(visible=False, interactive=False), \
gr.update(visible=False, interactive=False), \
gr.update(value=make_queue_panel_html()), \
gr.update(value=get_quick_preview_indices()), \
False
active_task = worker.get_current_task()
pending_count = worker.get_pending_task_count()
task_yield_count = worker.get_task_yield_count(task)
if active_task is not None and active_task is not task and not getattr(active_task, 'completed', False) \
and (task_yield_count == 0 or getattr(task, 'completed', False)):
task = active_task
task_yield_count = worker.get_task_yield_count(task)
active_running = active_task is not None and not getattr(active_task, 'completed', False)
task_is_active = active_task is task
task_is_pending = (
task is not None and hasattr(task, 'yields') and
not task_is_active and pending_count > 0 and not getattr(task, 'completed', False)
)
if not is_generating and not active_running and not task_is_pending and pending_count == 0 \
and task_yield_count == 0:
return idle_updates()
worker.heartbeat_queue_monitor()
event = worker.get_latest_display_yield(preferred_task=task, same_task_only=True) \
if task_yield_count > 0 else None
if event is None:
active_task = worker.get_current_task()
pending_count = worker.get_pending_task_count()
active_running = active_task is not None and not getattr(active_task, 'completed', False)
if not active_running and pending_count == 0:
if task is not None and getattr(task, 'completed', False):
final_product = list(getattr(task, 'results', []) or [])
if not args_manager.args.disable_enhance_output_sorting:
final_product = sort_enhance_images(final_product, task)
append_task_results_to_session_history(task, final_product)
latest_image = get_latest_display_image(final_product)
return gr.update(visible=False), \
gr.update(visible=True, value=latest_image) if latest_image is not None else gr.update(visible=True), \
gr.update(), \
gr.update(visible=True, value=session_history) if final_product else gr.update(visible=True), \
session_history, \
gr.update(visible=True, interactive=True), \
gr.update(visible=False, interactive=False), \
gr.update(visible=False, interactive=False), \
gr.update(value=make_queue_panel_html()), \
gr.update(value=get_quick_preview_indices()), \
False
worker.end_queue_monitor()
return idle_updates()
if not active_running and pending_count > 0:
return gr.update(
visible=True,
value=modules.html.make_progress_html(1, f'Waiting for queued task ... ({pending_count} pending)')
), gr.update(), gr.update(), gr.update(), session_history, \
gr.update(visible=True, interactive=True), \
gr.update(visible=False, interactive=False), \
gr.update(visible=False, interactive=False), \
gr.update(value=make_queue_panel_html()), \
gr.update(value=get_quick_preview_indices()), \
True
running_task_id = getattr(active_task, 'queue_id', 0)
status_html = modules.html.make_progress_html(
1,
f'Generation running (task {running_task_id})...'
if running_task_id
else 'Generation running...'
)
latest_image = get_latest_display_image(session_history)
return status_html, \
gr.update(visible=True, value=latest_image) if latest_image is not None else gr.update(), \
gr.update(), \
gr.update(visible=True, value=session_history), \
session_history, \
gr.update(visible=True, interactive=True), \
gr.update(visible=False, interactive=False), \
gr.update(visible=False, interactive=False), \
gr.update(value=make_queue_panel_html()), \
gr.update(value=get_quick_preview_indices()), \
True
task, flag, product = event
if flag == 'preview':
percentage, title, image = product
session_history_changed = append_task_results_to_session_history(task)
return gr.update(visible=True, value=modules.html.make_progress_html(percentage, title)), \
gr.update(visible=True, value=image) if image is not None else gr.update(), \
gr.update(), \
gr.update(visible=True, value=session_history) if session_history_changed else gr.update(visible=True), \
session_history, \
gr.update(visible=True, interactive=True), \
gr.update(visible=False, interactive=False), \
gr.update(visible=False, interactive=False), \
gr.update(value=make_queue_panel_html()), \
gr.update(value=get_quick_preview_indices()), \
True
if flag in ['results', 'finish']:
if flag == 'finish' and not args_manager.args.disable_enhance_output_sorting:
product = sort_enhance_images(product, task)
if flag == 'results':
image_items = product
elif flag == 'finish':
image_items = list(product)
if not image_items:
image_items = list(getattr(task, 'results', []) or [])
if not args_manager.args.disable_enhance_output_sorting:
image_items = sort_enhance_images(image_items, task)
append_task_results_to_session_history(task, image_items)
latest_image = get_latest_display_image(image_items)
active_task = worker.get_current_task()
active_running = active_task is not None and not getattr(active_task, 'completed', False)
has_more_work = active_running or worker.get_pending_task_count() > 0
is_finished = flag == 'finish' and not has_more_work
if is_finished:
worker.end_queue_monitor()
return gr.update(visible=not is_finished), \
gr.update(visible=True, value=latest_image) if latest_image is not None else gr.update(visible=True), \
gr.update(visible=False), \
gr.update(visible=True, value=session_history), \
session_history, \
gr.update(visible=True, interactive=True), \
gr.update(visible=False, interactive=False), \
gr.update(visible=False, interactive=False), \
gr.update(value=make_queue_panel_html()), \
gr.update(value=get_quick_preview_indices()), \
has_more_work
return gr.update(), gr.update(), gr.update(), gr.update(), session_history, \
gr.update(visible=True, interactive=True), \
gr.update(visible=False, interactive=False), \
gr.update(visible=False, interactive=False), \
gr.update(value=make_queue_panel_html()), \
gr.update(value=get_quick_preview_indices()), \
True
def reconnect_generate_queue(session_history):
active_task = worker.get_current_task()
if active_task is None:
latest_event = worker.get_latest_display_yield()
if latest_event is not None and latest_event[1] in ['results', 'finish']:
task = latest_event[0]
print(f'[Queue] Reconnected to completed generation task {getattr(task, "queue_id", 0)}.')
return task, False, \
gr.update(visible=True, interactive=True), \
gr.update(visible=False, interactive=False), \
gr.update(visible=False, interactive=False), \
gr.update(visible=False, interactive=False), \
gr.update(value=make_queue_panel_html()), \
True
return worker.AsyncTask(args=[]), False, \
gr.update(visible=True, interactive=True), \
gr.update(visible=False, interactive=False), \
gr.update(visible=False, interactive=False), \
gr.update(visible=False, interactive=False), \
gr.update(value=make_queue_panel_html()), \
False
should_monitor = worker.begin_queue_monitor()
print(f'[Queue] Reconnected to active generation task {getattr(active_task, "queue_id", 0)}.')
return active_task, should_monitor, \
gr.update(visible=True, interactive=True), \
gr.update(visible=False, interactive=False), \
gr.update(visible=False, interactive=False), \
gr.update(visible=True, interactive=True), \
gr.update(value=make_queue_panel_html()), \
True
def sort_enhance_images(images, task):
if not task.should_enhance or len(images) <= task.images_to_enhance_count:
return images
sorted_images = []
walk_index = task.images_to_enhance_count
for index, enhanced_img in enumerate(images[:task.images_to_enhance_count]):
sorted_images.append(enhanced_img)
if index not in task.enhance_stats:
continue
target_index = walk_index + task.enhance_stats[index]
if walk_index < len(images) and target_index <= len(images):
sorted_images += images[walk_index:target_index]
walk_index += task.enhance_stats[index]
return sorted_images
def inpaint_mode_change(mode, inpaint_engine_version):
assert mode in modules.flags.inpaint_options
# inpaint_additional_prompt, outpaint_selections, example_inpaint_prompts,
# inpaint_disable_initial_latent, inpaint_engine,
# inpaint_strength, inpaint_respective_field
if mode == modules.flags.inpaint_option_detail:
return [
gr.update(visible=True), gr.update(visible=False, value=[]),
gr.Dataset.update(visible=True, samples=modules.config.example_inpaint_prompts),
False, 'None', 0.5, 0.0
]
if inpaint_engine_version == 'empty':
inpaint_engine_version = modules.config.default_inpaint_engine_version
if mode == modules.flags.inpaint_option_modify:
return [
gr.update(visible=True), gr.update(visible=False, value=[]),
gr.Dataset.update(visible=False, samples=modules.config.example_inpaint_prompts),
True, inpaint_engine_version, 1.0, 0.0
]
return [
gr.update(visible=False, value=''), gr.update(visible=True),
gr.Dataset.update(visible=False, samples=modules.config.example_inpaint_prompts),
False, inpaint_engine_version, 1.0, 0.618
]
reload_javascript()
title = f'Fooocus {fooocus_version.version}'
if isinstance(args_manager.args.preset, str):
title += ' ' + args_manager.args.preset
shared.gradio_root = gr.Blocks(title=title).queue()
with shared.gradio_root:
with gr.Tabs(elem_id='generation_mode_tabs', selected='image_generation_tab'):
with gr.Tab(label='History', id='history_tab'):
gr.HTML(elem_id='history_live_generation_status', elem_classes='progress-bar')
history_visible_image_ids = gr.State([])
history_selected_image_ids = gr.State([])
history_selection_mode = gr.Textbox(value='single', elem_id='history_selection_mode',
visible=False)
history_day_selection_mode = gr.Textbox(value='single', elem_id='history_day_selection_mode',
visible=False)
history_selected_image_ids_json = gr.Textbox(value='[]', elem_id='history_selected_image_ids_json',
visible=False)
history_select_thumbnail_image_id = gr.Textbox(value='', elem_id='history_select_thumbnail_image_id',
visible=False)
history_select_thumbnail_button = gr.Button(value='Select History Thumbnail',
elem_id='history_select_thumbnail_button',
visible=False)
history_selected_days = gr.State([])
history_remove_selected_image_id = gr.Textbox(value='', elem_id='history_remove_selected_image_id',
visible=False)
history_remove_selected_image_button = gr.Button(value='Remove Selected History Image',
elem_id='history_remove_selected_image_button',
visible=False)
history_delete_selected_image_id = gr.Textbox(value='', elem_id='history_delete_selected_image_id',
visible=False)
history_delete_selected_image_button = gr.Button(value='Delete Selected History Image',
elem_id='history_delete_selected_image_button',
visible=False)
history_apply_selected_image_id = gr.Textbox(value='', elem_id='history_apply_selected_image_id',
visible=False)
history_apply_selected_image_button = gr.Button(value='Apply Selected History Image Config',
elem_id='history_apply_selected_image_button',
visible=False)
history_quality_selected_image_id = gr.Textbox(value='', elem_id='history_quality_selected_image_id',
visible=False)
history_quality_selected_image_button = gr.Button(value='Generate History Preview at Quality',
elem_id='history_quality_selected_image_button',
visible=False)
history_toggle_favorite_image_id = gr.Textbox(value='', elem_id='history_toggle_favorite_image_id',
visible=False)
history_toggle_favorite_button = gr.Button(value='Toggle History Favorite',
elem_id='history_toggle_favorite_button',