forked from Fanghua-Yu/SUPIR
-
Notifications
You must be signed in to change notification settings - Fork 13
/
gradio_demo.py
1954 lines (1690 loc) · 91.7 KB
/
gradio_demo.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
import argparse
import datetime
import gc
import os
import shutil
import tempfile
import threading
import time
import traceback
import json
from datetime import datetime
from typing import Tuple, List, Any, Dict
import einops
import gradio as gr
import numpy as np
import requests
import torch
from PIL import Image
from PIL import PngImagePlugin
from gradio_imageslider import ImageSlider
import ui_helpers
from SUPIR.models.SUPIR_model import SUPIRModel
from SUPIR.util import HWC3, upscale_image, convert_dtype
from SUPIR.util import create_SUPIR_model
from SUPIR.utils import shared
from SUPIR.utils.compare import create_comparison_video
from SUPIR.utils.face_restoration_helper import FaceRestoreHelper
from SUPIR.utils.model_fetch import get_model
from SUPIR.utils.rename_meta import rename_meta_key, rename_meta_key_reverse
from SUPIR.utils.ckpt_downloader import download_checkpoint_handler, download_checkpoint
from SUPIR.utils.status_container import StatusContainer, MediaData
from llava.llava_agent import LLavaAgent
from ui_helpers import is_video, extract_video, compile_video, is_image, get_video_params, printt
SUPIR_REVISION = "v52"
parser = argparse.ArgumentParser()
parser.add_argument("--ip", type=str, default='127.0.0.1', help="IP address for the server to listen on.")
parser.add_argument("--share", type=str, default=False, help="Set to True to share the app publicly.")
parser.add_argument("--port", type=int, help="Port number for the server to listen on.")
parser.add_argument("--log_history", action='store_true', default=False, help="Enable logging of request history.")
parser.add_argument("--loading_half_params", action='store_true', default=False,
help="Enable loading model parameters in half precision to reduce memory usage.")
parser.add_argument("--fp8", action='store_true', default=False,
help="Enable loading model parameters in FP8 precision to reduce memory usage.")
parser.add_argument("--autotune", action='store_true', default=False, help="Automatically set precision parameters based on the amount of VRAM available.")
parser.add_argument("--fast_load_sd", action='store_true', default=False,
help="Enable fast loading of model state dict and to prevents unnecessary memory allocation.")
parser.add_argument("--use_tile_vae", action='store_true', default=False,
help="Enable tiling for the VAE to handle larger images with limited memory.")
parser.add_argument("--outputs_folder_button",action='store_true', default=False, help="Outputs Folder Button Will Be Enabled")
parser.add_argument("--use_fast_tile", action='store_true', default=False,
help="Use a faster tile encoding/decoding, may impact quality.")
parser.add_argument("--encoder_tile_size", type=int, default=512,
help="Tile size for the encoder. Larger sizes may improve quality but require more memory.")
parser.add_argument("--decoder_tile_size", type=int, default=64,
help="Tile size for the decoder. Larger sizes may improve quality but require more memory.")
parser.add_argument("--load_8bit_llava", action='store_true', default=False,
help="Load the LLAMA model in 8-bit precision to save memory.")
parser.add_argument("--load_4bit_llava", action='store_true', default=True,
help="Load the LLAMA model in 4-bit precision to significantly reduce memory usage.")
parser.add_argument("--ckpt", type=str, default='Juggernaut-XL_v9_RunDiffusionPhoto_v2.safetensors',
help="Path to the checkpoint file for the model.")
parser.add_argument("--ckpt_browser", action='store_true', default=True, help="Enable a checkpoint selection dropdown.")
parser.add_argument("--ckpt_dir", type=str, default='models/checkpoints',
help="Directory where model checkpoints are stored.")
parser.add_argument("--theme", type=str, default='default',
help="Theme for the UI. Use 'default' or specify a custom theme.")
parser.add_argument("--open_browser", action='store_true', default=True,
help="Automatically open the web browser when the server starts.")
parser.add_argument("--outputs_folder", type=str, default='outputs', help="Folder where output files will be saved.")
parser.add_argument("--debug", action='store_true', default=False,
help="Enable debug mode, disables open_browser, and adds ui buttons for testing elements.")
parser.add_argument("--dont_move_cpu", action='store_true', default=False,
help="Disables moving models to the CPU after completed. If you have sufficient VRAM enable this.")
args = parser.parse_args()
ui_helpers.ui_args = args
current_video_fps = 0
total_video_frames = 0
video_start = 0
video_end = 0
last_input_path = None
last_video_params = None
meta_upload = False
bf16_supported = torch.cuda.is_bf16_supported()
total_vram = 100000
auto_unload = False
if torch.cuda.is_available() and args.autotune:
# Get total GPU memory
total_vram = torch.cuda.get_device_properties(0).total_memory / 1024 ** 3
print("Autotune enabled, Total VRAM: ", total_vram, "GB")
if not args.fp8:
args.fp8 = total_vram <= 8
auto_unload = total_vram <= 12
if total_vram <= 24:
if not args.loading_half_params:
args.loading_half_params = True
if not args.use_tile_vae:
args.use_tile_vae = True
print("Auto Unload: ", auto_unload)
print("Half Params: ", args.loading_half_params)
print("FP8: ", args.fp8)
print("Tile VAE: ", args.use_tile_vae)
shared.opts.half_mode = args.loading_half_params
shared.opts.fast_load_sd = args.fast_load_sd
def apply_metadata(image_path):
if image_path is None:
return
# Open the image and extract metadata
with Image.open(image_path) as img:
metadata = img.info
global elements_dict, extra_info_elements
updates = []
for key, value in metadata.items():
# Check if the key is in the dictionary of UI elements
if key in elements_dict:
if key == "src_file":
# Skip updating the "src_file" element
updates.append(gr.update())
else:
# Update the value of the element if it exists and is not "src_file"
elements_dict[key].value = value
updates.append(gr.update(value=elements_dict[key].value))
else:
# If the key is not found in elements_dict, try to find a matching key using rename_meta_key
renamed_key = rename_meta_key(key)
if renamed_key in elements_dict:
elements_dict[renamed_key].value = value
updates.append(gr.update(value=elements_dict[renamed_key].value))
elif renamed_key in extra_info_elements:
# Update the value of the element in extra_info_elements if it exists
extra_info_elements[renamed_key].value = value
updates.append(gr.update(value=value))
else:
# Append an update with no changes if the key is not recognized
updates.append(gr.update())
return updates
if args.fp8:
shared.opts.half_mode = args.fp8
shared.opts.fp8_storage = args.fp8
server_ip = args.ip
if args.debug:
args.open_browser = False
if args.ckpt_dir == "models/checkpoints":
args.ckpt_dir = os.path.join(os.path.dirname(__file__), args.ckpt_dir)
if not os.path.exists(args.ckpt_dir):
os.makedirs(args.ckpt_dir, exist_ok=True)
if torch.cuda.device_count() >= 2:
SUPIR_device = 'cuda:0'
LLaVA_device = 'cuda:1'
elif torch.cuda.device_count() == 1:
SUPIR_device = 'cuda:0'
LLaVA_device = 'cuda:0'
else:
SUPIR_device = 'cpu'
LLaVA_device = 'cpu'
face_helper = None
model: SUPIRModel = None
llava_agent = None
models_loaded = False
unique_counter = 0
status_container = StatusContainer()
# Store this globally so we can update variables more easily
elements_dict = {}
extra_info_elements = {}
single_process = False
is_processing = False
last_used_checkpoint = None
slider_html = """
<div id="keyframeSlider" class="keyframe-slider">
<div id="frameSlider"></div>
<!-- Labels for start and end times -->
<div class="labels">
<span id="startTimeLabel">0:00:00</span>
<span id="nowTimeLabel">0:00:30</span>
<span id="endTimeLabel">0:01:00</span>
</div>
</div>
"""
def refresh_models_click():
new_model_list = list_models()
return gr.update(choices=new_model_list)
def refresh_styles_click():
new_style_list = list_styles()
style_list = list(new_style_list.keys())
return gr.update(choices=style_list)
def update_start_time(src_file, upscale_size, start_time):
global video_start
video_start = start_time
target_res_text = update_target_resolution(src_file, upscale_size)
return gr.update(value=target_res_text, visible=target_res_text != "")
def update_end_time(src_file, upscale_size, end_time):
global video_end
video_end = end_time
target_res_text = update_target_resolution(src_file, upscale_size)
return gr.update(value=target_res_text, visible=target_res_text != "")
def select_style(style_name, current_prompt=None, values=False):
style_list = list_styles()
if style_name in style_list.keys():
style_pos, style_neg, style_llava = style_list[style_name]
if values:
return style_pos, style_neg, style_llava
return gr.update(value=style_pos), gr.update(value=style_neg), gr.update(value=style_llava)
if values:
return "", "", ""
return gr.update(value=""), gr.update(value=""), gr.update(value="")
import platform
def open_folder():
open_folder_path = os.path.abspath(args.outputs_folder)
if platform.system() == "Windows":
os.startfile(open_folder_path)
elif platform.system() == "Linux":
os.system(f'xdg-open "{open_folder_path}"')
def set_info_attributes(elements_to_set: Dict[str, Any]):
output = {}
for key, value in elements_to_set.items():
if not getattr(value, 'elem_id', None):
setattr(value, 'elem_id', key)
classes = getattr(value, 'elem_classes', None)
if isinstance(classes, list):
if "info-btn" not in classes:
classes.append("info-button")
setattr(value, 'elem_classes', classes)
output[key] = value
return output
def list_models():
model_dir = args.ckpt_dir
output = []
if os.path.exists(model_dir):
output = [os.path.join(model_dir, f) for f in os.listdir(model_dir) if
f.endswith('.safetensors') or f.endswith('.ckpt')]
else:
local_model_dir = os.path.join(os.path.dirname(__file__), args.ckpt_dir)
if os.path.exists(local_model_dir):
output = [os.path.join(local_model_dir, f) for f in os.listdir(local_model_dir) if
f.endswith('.safetensors') or f.endswith('.ckpt')]
if os.path.exists(args.ckpt) and args.ckpt not in output:
output.append(args.ckpt)
else:
if os.path.exists(os.path.join(os.path.dirname(__file__), args.ckpt)):
output.append(os.path.join(os.path.dirname(__file__), args.ckpt))
# Sort the models
output = [os.path.basename(f) for f in output]
# Ensure the values are unique
output = list(set(output))
output.sort()
return output
def get_ckpt_path(ckpt_path):
if os.path.exists(ckpt_path):
return ckpt_path
else:
if os.path.exists(args.ckpt_dir):
return os.path.join(args.ckpt_dir, ckpt_path)
local_model_dir = os.path.join(os.path.dirname(__file__), args.ckpt_dir)
if os.path.exists(local_model_dir):
return os.path.join(local_model_dir, ckpt_path)
return None
def list_styles():
styles_path = os.path.join(os.path.dirname(__file__), 'styles')
output = {}
style_files = []
llava_prompt = default_llava_prompt
for root, dirs, files in os.walk(styles_path):
for file in files:
if file.endswith('.csv'):
style_files.append(os.path.join(root, file))
for style_file in style_files:
with open(style_file, 'r') as f:
lines = f.readlines()
# Parse lines, skipping the first line
for line in lines[1:]:
line = line.strip()
if len(line) > 0:
name = line.split(',')[0]
cap_line = line.replace(name + ',', '')
captions = cap_line.split('","')
if len(captions) >= 2:
positive_prompt = captions[0].replace('"', '')
negative_prompt = captions[1].replace('"', '')
if "{prompt}" in positive_prompt:
positive_prompt = positive_prompt.replace("{prompt}", "")
if "{prompt}" in negative_prompt:
negative_prompt = negative_prompt.replace("{prompt}", "")
if len(captions) == 3:
llava_prompt = captions[2].replace('"', "")
output[name] = (positive_prompt, negative_prompt, llava_prompt)
return output
def selected_model():
models = list_models()
target_model = args.ckpt
if os.path.basename(target_model) in models:
return target_model
else:
if len(models) > 0:
return models[0]
return None
def load_face_helper():
global face_helper
if face_helper is None:
face_helper = FaceRestoreHelper(
device='cpu',
upscale_factor=1,
face_size=1024,
use_parse=True,
det_model='retinaface_resnet50'
)
def load_model(selected_model, selected_checkpoint, weight_dtype, sampler='DPMPP2M', device='cpu', progress=gr.Progress()):
global model, last_used_checkpoint
# Determine the need for model loading or updating
need_to_load_model = last_used_checkpoint is None or last_used_checkpoint != selected_checkpoint
need_to_update_model = selected_model != (model.current_model if model else None)
if need_to_update_model:
del model
model = None
# Resolve checkpoint path
checkpoint_paths = [
selected_checkpoint,
os.path.join(args.ckpt_dir, selected_checkpoint),
os.path.join(os.path.dirname(__file__), args.ckpt_dir, selected_checkpoint)
]
checkpoint_use = next((path for path in checkpoint_paths if os.path.exists(path)), None)
if checkpoint_use is None:
raise FileNotFoundError(f"Checkpoint {selected_checkpoint} not found.")
# Check if we need to load a new model
if need_to_load_model or model is None:
torch.cuda.empty_cache()
last_used_checkpoint = checkpoint_use
model_cfg = "options/SUPIR_v0_tiled.yaml" if args.use_tile_vae else "options/SUPIR_v0.yaml"
weight_dtype = 'fp16' if not bf16_supported else weight_dtype
model = create_SUPIR_model(model_cfg, weight_dtype, supir_sign=selected_model[-1], device=device, ckpt=checkpoint_use,
sampler=sampler)
model.current_model = selected_model
if args.use_tile_vae:
model.init_tile_vae(encoder_tile_size=512, decoder_tile_size=64, use_fast=args.use_fast_tile)
if progress is not None:
progress(1, desc="SUPIR loaded.")
def load_llava():
global llava_agent
if llava_agent is None:
llava_path = get_model('liuhaotian/llava-v1.5-7b')
llava_agent = LLavaAgent(llava_path, device=LLaVA_device, load_8bit=args.load_8bit_llava,
load_4bit=args.load_4bit_llava)
def unload_llava():
global llava_agent
if args.load_4bit_llava or args.load_8bit_llava:
printt("Clearing LLaVA.")
clear_llava()
printt("LLaVA cleared.")
else:
printt("Unloading LLaVA.")
llava_agent = llava_agent.to('cpu')
gc.collect()
torch.cuda.empty_cache()
printt("LLaVA unloaded.")
def clear_llava():
global llava_agent
del llava_agent
llava_agent = None
gc.collect()
torch.cuda.empty_cache()
def all_to_cpu_background():
if args.dont_move_cpu:
return
global face_helper, model, llava_agent, auto_unload
printt("Moving all to CPU")
if face_helper is not None:
face_helper = face_helper.to('cpu')
printt("Face helper moved to CPU")
if model is not None:
model = model.to('cpu')
model.move_to('cpu')
printt("Model moved to CPU")
if llava_agent is not None:
if auto_unload:
unload_llava()
gc.collect()
torch.cuda.empty_cache()
printt("All moved to CPU")
def all_to_cpu():
if args.dont_move_cpu:
return
cpu_thread = threading.Thread(target=all_to_cpu_background)
cpu_thread.start()
def to_gpu(elem_to_load, device):
if elem_to_load is not None:
elem_to_load = elem_to_load.to(device)
if getattr(elem_to_load, 'move_to', None):
elem_to_load.move_to(device)
torch.cuda.set_device(device)
return elem_to_load
def update_model_settings(model_type, param_setting):
"""
Returns a series of gr.updates with settings based on the model type.
If 'model_type' contains 'lightning', it uses the settings for a 'lightning' SDXL model.
Otherwise, it uses the settings for a normal SDXL model.
s_cfg_Quality, spt_linear_CFG_Quality, s_cfg_Fidelity, spt_linear_CFG_Fidelity, edm_steps
"""
# Default settings for a "lightning" SDXL model
lightning_settings = {
's_cfg_Quality': 2.0,
'spt_linear_CFG_Quality': 2.0,
's_cfg_Fidelity': 1.5,
'spt_linear_CFG_Fidelity': 1.5,
'edm_steps': 10
}
# Default settings for a normal SDXL model
normal_settings = {
's_cfg_Quality': 7.5,
'spt_linear_CFG_Quality': 4.0,
's_cfg_Fidelity': 4.0,
'spt_linear_CFG_Fidelity': 1.0,
'edm_steps': 50
}
# Choose the settings based on the model type
settings = lightning_settings if 'Lightning' in model_type else normal_settings
if param_setting == "Quality":
s_cfg = settings['s_cfg_Quality']
spt_linear_CFG = settings['spt_linear_CFG_Quality']
else:
s_cfg = settings['s_cfg_Fidelity']
spt_linear_CFG = settings['spt_linear_CFG_Fidelity']
return gr.update(value=s_cfg), gr.update(value=spt_linear_CFG), gr.update(value=settings['edm_steps'])
def update_inputs(input_file, upscale_amount):
global current_video_fps, total_video_frames, video_start, video_end
file_input = gr.update(visible=True)
image_input = gr.update(visible=False, sources=[])
video_slider = gr.update(visible=False)
video_start_time = gr.update(value=0)
video_end_time = gr.update(value=0)
video_current_time = gr.update(value=0)
video_fps = gr.update(value=0)
video_total_frames = gr.update(value=0)
current_video_fps = 0
total_video_frames = 0
video_start = 0
video_end = 0
res_output = gr.update(value="")
if is_image(input_file):
image_input = gr.update(visible=True, value=input_file, sources=[], label="Input Image")
file_input = gr.update(visible=False)
target_res = update_target_resolution(input_file, upscale_amount)
res_output = gr.update(value=target_res, visible=target_res != "")
elif is_video(input_file):
video_attributes = ui_helpers.get_video_params(input_file)
video_start = 0
end_time = video_attributes['frames']
video_end = end_time
mid_time = int(end_time / 2)
current_video_fps = video_attributes['framerate']
total_video_frames = end_time
video_end_time = gr.update(value=end_time)
video_total_frames = gr.update(value=end_time)
video_current_time = gr.update(value=mid_time)
video_frame = ui_helpers.get_video_frame(input_file, mid_time)
video_slider = gr.update(visible=True)
image_input = gr.update(visible=True, value=video_frame, sources=[], label="Input Video")
file_input = gr.update(visible=False)
video_fps = gr.update(value=current_video_fps)
target_res = update_target_resolution(input_file, upscale_amount)
res_output = gr.update(value=target_res, visible=target_res != "")
elif input_file is None:
file_input = gr.update(visible=True, value=None)
return file_input, image_input, video_slider, res_output, video_start_time, video_end_time, video_current_time, video_fps, video_total_frames
def update_target_resolution(img, do_upscale):
global last_input_path, last_video_params
if img is None:
last_video_params = None
last_input_path = None
return ""
if is_image(img):
last_input_path = img
last_video_params = None
with Image.open(img) as img:
width, height = img.size
width_org, height_org = img.size
elif is_video(img):
if img == last_input_path:
params = last_video_params
else:
last_input_path = img
params = get_video_params(img)
last_video_params = params
width, height = params['width'], params['height']
width_org, height_org = params['width'], params['height']
else:
last_input_path = None
last_video_params = None
return ""
width *= do_upscale
height *= do_upscale
if min(width, height) < 1024:
do_upscale_factor = 1024 / min(width, height)
width *= do_upscale_factor
height *= do_upscale_factor
output_lines = [
f"<td style='padding: 8px; border-bottom: 1px solid #ddd;'>Input: {int(width_org)}x{int(height_org)} px, {width_org * height_org / 1e6:.2f} Megapixels</td>",
f"<td style='padding: 8px; border-bottom: 1px solid #ddd;'>Estimated Output Resolution: {int(width)}x{int(height)} px, {width * height / 1e6:.2f} Megapixels</td>",
]
if total_video_frames > 0 and is_video(img):
selected_video_frames = video_end - video_start
total_video_time = int(selected_video_frames / current_video_fps)
output_lines += [
f"<td style='padding: 8px; border-bottom: 1px solid #ddd;'>Selected video frames: {selected_video_frames}</td>",
f"<td style='padding: 8px; border-bottom: 1px solid #ddd;'>Total video time: {total_video_time} seconds</td>"
]
output = '<table style="width:100%;"><tr>'
# Fix here: Convert each pair of <td> elements into a single string before joining
output += ''.join(''.join(output_lines[i:i + 2]) for i in range(0, len(output_lines), 2))
output += '</tr></table>'
return output
def read_image_metadata(image_path):
if image_path is None:
return
# Check if the file exists
if not os.path.exists(image_path):
return "File does not exist."
# Get the last modified date and format it
last_modified_timestamp = os.path.getmtime(image_path)
last_modified_date = datetime.fromtimestamp(last_modified_timestamp).strftime('%d %B %Y, %H:%M %p - UTC')
# Open the image and extract metadata
with Image.open(image_path) as img:
width, height = img.size
megapixels = (width * height) / 1e6
metadata_str = f"Last Modified Date: {last_modified_date}\nMegapixels: {megapixels:.2f}\n"
# Extract metadata based on image format
if img.format == 'JPEG':
exif_data = img._getexif()
if exif_data:
for tag, value in exif_data.items():
tag_name = Image.ExifTags.TAGS.get(tag, tag)
metadata_str += f"{tag_name}: {value}\n"
else:
metadata = img.info
if metadata:
for key, value in metadata.items():
metadata_str += f"{key}: {value}\n"
else:
metadata_str += "No additional metadata found."
return metadata_str
def update_elements(status_label):
prompt_el = gr.update()
result_gallery_el = gr.update(height=400)
result_slider_el = gr.update(height=400)
result_video_el = gr.update(height=400)
comparison_video_el = gr.update(height=400, visible=False)
seed = None
face_gallery_items = []
evt_id = ""
if not is_processing:
output_data = status_container.image_data
if len(output_data) == 1:
image_data = output_data[0]
caption = image_data.caption
prompt_el = gr.update(value=caption)
if len(image_data.outputs) > 0:
outputs = image_data.outputs
params = image_data.metadata_list
if len(params) != len(outputs):
params = [status_container.process_params] * len(outputs)
first_output = outputs[0]
first_params = params[0]
seed = first_params.get('seed', "")
face_gallery_items = first_params.get('face_gallery', [])
evt_id = first_params.get('event_id', "")
if image_data.media_type == "image":
if image_data.comparison_video:
comparison_video_el = gr.update(value=image_data.comparison_video, visible=True)
result_slider_el = gr.update(value=[image_data.media_path, first_output], visible=True)
result_gallery_el = gr.update(value=None, visible=False)
result_video_el = gr.update(value=None, visible=False)
elif image_data.media_type == "video":
prompt_el = gr.update(value="")
result_video_el = gr.update(value=first_output, visible=True)
result_gallery_el = gr.update(value=None, visible=False)
result_slider_el = gr.update(value=None, visible=False)
elif len(output_data) > 1:
first_output_data = output_data[0]
if len(first_output_data.outputs):
first_params = first_output_data.metadata_list[
0] if first_output_data.metadata_list else status_container.process_params
seed = first_params.get('seed', "")
face_gallery_items = first_params.get('face_gallery', [])
evt_id = first_params.get('event_id', "")
all_outputs = []
for output_data in output_data:
all_outputs.extend(output_data.outputs)
result_gallery_el = gr.update(value=all_outputs, visible=True)
result_slider_el = gr.update(value=None, visible=False)
result_video_el = gr.update(value=None, visible=False)
seed_el = gr.update(value=seed)
event_id_el = gr.update(value=evt_id)
face_gallery_el = gr.update(value=face_gallery_items)
return prompt_el, result_gallery_el, result_slider_el, result_video_el, comparison_video_el, event_id_el, seed_el, face_gallery_el
def populate_slider_single():
# Fetch the image at http://www.marketingtool.online/en/face-generator/img/faces/avatar-1151ce9f4b2043de0d2e3b7826127998.jpg
# and use it as the input image
temp_path = tempfile.NamedTemporaryFile(delete=False, suffix='.jpg')
temp_path.write(requests.get(
"http://www.marketingtool.online/en/face-generator/img/faces/avatar-1151ce9f4b2043de0d2e3b7826127998.jpg").content)
temp_path.close()
lowres_path = temp_path.name.replace('.jpg', '_lowres.jpg')
with Image.open(temp_path.name) as img:
current_dims = (img.size[0] // 2, img.size[1] // 2)
resized_dims = (img.size[0] // 4, img.size[1] // 4)
img = img.resize(current_dims)
img.save(temp_path.name)
img = img.resize(resized_dims)
img.save(lowres_path)
return (gr.update(value=[lowres_path, temp_path.name], visible=True,
elem_classes=["active", "preview_slider", "preview_box"]),
gr.update(visible=False, value=None, elem_classes=["preview_box"]))
def populate_gallery():
temp_path = tempfile.NamedTemporaryFile(delete=False, suffix='.jpg')
temp_path.write(requests.get(
"http://www.marketingtool.online/en/face-generator/img/faces/avatar-1151ce9f4b2043de0d2e3b7826127998.jpg").content)
temp_path.close()
lowres_path = temp_path.name.replace('.jpg', '_lowres.jpg')
with Image.open(temp_path.name) as img:
current_dims = (img.size[0] // 2, img.size[1] // 2)
resized_dims = (img.size[0] // 4, img.size[1] // 4)
img = img.resize(current_dims)
img.save(temp_path.name)
img = img.resize(resized_dims)
img.save(lowres_path)
return gr.update(value=[lowres_path, temp_path.name], visible=True,
elem_classes=["preview_box", "active"]), gr.update(visible=False, value=None,
elem_classes=["preview_slider", "preview_box"])
def start_single_process(*element_values):
global status_container, is_processing
status_container = StatusContainer()
status_container.is_batch = False
values_dict = zip(elements_dict.keys(), element_values)
values_dict = dict(values_dict)
main_prompt = values_dict['main_prompt']
# Delete input_image, prompt, batch_process_folder, outputs_folder from values_dict
input_image = values_dict['src_file']
if input_image is None:
return "No input image provided."
image_files = [input_image]
# Make a dictionary to store the image data and path
img_data = []
if is_video(input_image):
# Store the original video path for later
status_container.source_video_path = input_image
status_container.is_video = True
extracted_folder = os.path.join(args.outputs_folder, "extracted_frames")
if os.path.exists(extracted_folder):
shutil.rmtree(extracted_folder)
os.makedirs(extracted_folder, exist_ok=True)
start = values_dict.get('video_start', None)
end = values_dict.get('video_end', None)
extract_success, video_params = extract_video(input_image, extracted_folder, video_start=start, video_end=end)
if extract_success:
status_container.video_params = video_params
for file in os.listdir(extracted_folder):
full_path = os.path.join(extracted_folder, file)
media_data = MediaData(media_path=full_path)
media_data.caption = main_prompt
img_data.append(media_data)
else:
for file in image_files:
try:
media_data = MediaData(media_path=file)
img = Image.open(file)
media_data.media_data = np.array(img)
media_data.caption = main_prompt
img_data.append(media_data)
except:
pass
result = "An exception occurred. Please try again."
# auto_unload_llava, batch_process_folder, main_prompt, output_video_format, output_video_quality, outputs_folder,video_duration, video_fps, video_height, video_width
keys_to_pop = ['batch_process_folder', 'main_prompt', 'output_video_format',
'output_video_quality', 'outputs_folder', 'video_duration', 'video_end', 'video_fps',
'video_height', 'video_start', 'video_width', 'src_file']
values_dict['outputs_folder'] = args.outputs_folder
status_container.process_params = values_dict
values_dict = {k: v for k, v in values_dict.items() if k not in keys_to_pop}
try:
_, result = batch_process(img_data, **values_dict)
except Exception as e:
print(f"An exception occurred: {e} at {traceback.format_exc()}")
is_processing = False
return result
def start_batch_process(*element_values):
global status_container, is_processing
status_container = StatusContainer()
status_container.is_batch = True
values_dict = zip(elements_dict.keys(), element_values)
values_dict = dict(values_dict)
batch_process_folder = values_dict['batch_process_folder']
outputs_folder = values_dict['outputs_folder']
main_prompt = values_dict['main_prompt']
if not batch_process_folder:
return "No input folder provided."
if not os.path.exists(batch_process_folder):
return "The input folder does not exist."
if len(outputs_folder) < 2:
outputs_folder = args.outputs_folder
image_files = [file for file in os.listdir(batch_process_folder) if
is_image(os.path.join(batch_process_folder, file))]
# Make a dictionary to store the image data and path
img_data = []
for file in image_files:
media_data = MediaData(media_path=os.path.join(batch_process_folder, file))
img = Image.open(os.path.join(batch_process_folder, file))
media_data.media_data = np.array(img)
media_data.caption = main_prompt
img_data.append(media_data)
# Store it globally
status_container.image_data = img_data
result = "An exception occurred. Please try again."
try:
keys_to_pop = ['batch_process_folder', 'main_prompt', 'output_video_format',
'output_video_quality', 'outputs_folder', 'video_duration', 'video_end', 'video_fps',
'video_height', 'video_start', 'video_width', 'src_file']
status_container.outputs_folder = outputs_folder
values_dict['outputs_folder'] = outputs_folder
status_container.process_params = values_dict
values_dict = {k: v for k, v in values_dict.items() if k not in keys_to_pop}
result, _ = batch_process(img_data, **values_dict)
except Exception as e:
print(f"An exception occurred: {e} at {traceback.format_exc()}")
is_processing = False
return result
def llava_process(inputs: List[MediaData], temp, p, question=None, save_captions=False, progress=gr.Progress()):
global llava_agent, status_container
outputs = []
total_steps = len(inputs) + 1
step = 0
progress(step / total_steps, desc="Loading LLaVA...")
load_llava()
step += 1
printt("Moving LLaVA to GPU.")
llava_agent = to_gpu(llava_agent, LLaVA_device)
printt("LLaVA moved to GPU.")
progress(step / total_steps, desc="LLaVA loaded, captioning images...")
for md in inputs:
img = md.media_data
img_path = md.media_path
progress(step / total_steps, desc=f"Processing image {step}/{len(inputs)} with LLaVA...")
if img is None: ## this is for llava and video
img = Image.open(img_path)
img = np.array(img)
lq = HWC3(img)
lq = Image.fromarray(lq.astype('uint8'))
caption = llava_agent.gen_image_caption([lq], temperature=temp, top_p=p, qs=question)
caption = caption[0]
md.caption = caption
outputs.append(md)
if save_captions:
cap_path = os.path.splitext(img_path)[0] + ".txt"
with open(cap_path, 'w') as cf:
cf.write(caption)
if not is_processing: # Check if batch processing has been stopped
break
step += 1
progress(step / total_steps, desc="LLaVA processing completed.")
status_container.image_data = outputs
return f"LLaVA Processing Completed: {len(inputs)} images processed at {time.ctime()}."
# video_start_time_number, video_current_time_number, video_end_time_number,
# video_fps_number, video_total_frames_number, src_input_file, upscale_slider
def update_video_slider(start_time, current_time, end_time, fps, total_frames, src_file, upscale_size):
print(f"Updating video slider: {start_time}, {current_time}, {end_time}, {fps}, {src_file}")
global video_start, video_end
video_start = start_time
video_end = end_time
video_frame = ui_helpers.get_video_frame(src_file, current_time)
target_res_text = update_target_resolution(src_file, upscale_size)
return gr.update(value=video_frame), gr.update(value=target_res_text, visible=target_res_text != "")
def supir_process(inputs: List[MediaData], a_prompt, n_prompt, num_samples,
upscale, edm_steps,
s_stage1, s_stage2, s_cfg, seed, sampler, s_churn, s_noise, color_fix_type, diff_dtype, ae_dtype,
linear_cfg, linear_s_stage2, spt_linear_cfg, spt_linear_s_stage2, model_select,
ckpt_select, num_images, random_seed, apply_llava, face_resolution, apply_bg, apply_face,
face_prompt, dont_update_progress=False, unload=True,
progress=gr.Progress()):
global model, status_container, event_id
main_begin_time = time.time()
total_images = len(inputs) * num_images
total_progress = total_images + 1
if unload:
total_progress += 1
counter = 0
progress(counter / total_progress, desc="Loading SUPIR Model...")
load_model(model_select, ckpt_select, diff_dtype, sampler, progress=progress)
to_gpu(model, SUPIR_device)
counter += 1
progress(counter / total_progress, desc="Model Loaded, Processing Images...")
model.ae_dtype = convert_dtype('fp32' if bf16_supported == False else ae_dtype)
model.model.dtype = convert_dtype('fp16' if bf16_supported == False else diff_dtype)
idx = 0
output_data = []
processed_images = 0
params = status_container.process_params
for image_data in inputs:
gen_params_list = []
img_params = params.copy()
img = image_data.media_data
image_path = image_data.media_path
progress(counter / total_progress, desc=f"Processing image {counter}/{total_images}...")
if img is None:
printt(f"Image {counter}/{total_images} is None, loading from disk.")
with Image.open(image_path) as img:
img = np.array(img)
printt(f"Processing image {counter}/{total_images}...")
# Prompt is stored directly in the image data
img_prompt = image_data.caption
idx = idx + 1
# See if there is a caption file
if not apply_llava:
cap_path = os.path.join(os.path.splitext(image_path)[0] + ".txt")
if os.path.exists(cap_path):
printt(f"Loading caption from {cap_path}...")
with open(cap_path, 'r') as cf:
img_prompt = cf.read()
img = HWC3(img)
printt("Upscaling image (pre)...")
img = upscale_image(img, upscale, unit_resolution=32, min_size=1024)
lq = np.array(img)
lq = lq / 255 * 2 - 1
lq = torch.tensor(lq, dtype=torch.float32).permute(2, 0, 1).unsqueeze(0).to(SUPIR_device)[:, :3, :, :]
_faces = []
if not dont_update_progress and progress is not None:
progress(counter / total_images, desc=f"Upscaling Images {counter}/{total_images}")
face_captions = [img_prompt]
if apply_face:
lq = np.array(img)
load_face_helper()
if face_helper is None or not isinstance(face_helper, FaceRestoreHelper):
raise ValueError('Face helper not loaded')
face_helper.clean_all()
face_helper.read_image(lq)
# get face landmarks for each face
face_helper.get_face_landmarks_5(only_center_face=False, resize=640, eye_dist_threshold=5)
face_helper.align_warp_face()
lq = lq / 255 * 2 - 1
lq = torch.tensor(lq, dtype=torch.float32).permute(2, 0, 1).unsqueeze(0).to(SUPIR_device)[:, :3, :, :]
if len(face_prompt) > 1:
face_captions = [face_prompt]
to_gpu(face_helper, SUPIR_device)
results = []
for _ in range(num_images):
gen_params = img_params.copy()
gen_params['evt_id'] = event_id
result = None
if random_seed or num_images > 1:
seed = np.random.randint(0, 2147483647)
gen_params['seed'] = seed
start_time = time.time() # Track the start time
def process_sample(model, input_data, caption, face_resolution=None, is_face=False):
samples = model.batchify_sample(input_data, caption, num_steps=edm_steps, restoration_scale=s_stage1,
s_churn=s_churn, s_noise=s_noise, cfg_scale=s_cfg,
control_scale=s_stage2, seed=seed,
num_samples=num_samples, p_p=a_prompt, n_p=n_prompt,
color_fix_type=color_fix_type,
use_linear_cfg=linear_cfg, use_linear_control_scale=linear_s_stage2,
cfg_scale_start=spt_linear_cfg, control_scale_start=spt_linear_s_stage2, sampler_cls=sampler)
if is_face and face_resolution < 1024:
samples = samples[:, :, 512 - face_resolution // 2:512 + face_resolution // 2,
512 - face_resolution // 2:512 + face_resolution // 2]
return samples
if apply_face:
faces = []
restored_faces = []