forked from Fanghua-Yu/SUPIR
-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathgradio_demo.py
2975 lines (2566 loc) · 143 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 subprocess
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 pillow_avif # Import the AVIF plugin
from PIL import UnidentifiedImageError
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"
def get_recent_images(num_images=20):
"""
Get a list of recent image files from the outputs folder without scanning subfolders.
"""
try:
if not os.path.exists(args.outputs_folder):
os.makedirs(args.outputs_folder, exist_ok=True)
return []
# Get all image files from only the main outputs folder, not subfolders
image_files = []
# Instead of os.walk, just list files in the main directory
for file in os.listdir(args.outputs_folder):
file_path = os.path.join(args.outputs_folder, file)
# Only process files (not directories) with image extensions
if os.path.isfile(file_path) and file.lower().endswith(('.png', '.jpg', '.jpeg', '.webp', '.bmp', '.tiff', '.avif')):
# Get file modification time
mtime = os.path.getmtime(file_path)
image_files.append((file_path, mtime))
# Sort by modification time, most recent first
image_files.sort(key=lambda x: x[1], reverse=True)
# Extract just the paths for the most recent images
recent_paths = [item[0] for item in image_files[:num_images]]
return recent_paths
except Exception as e:
print(f"Error getting recent images: {str(e)}")
return []
def update_comparison_images(image1_path, image2_path):
"""
Update the image comparison slider with the selected images.
Resize smaller image to match the larger image's dimensions using nearest neighbor interpolation.
"""
if image1_path and image2_path:
try:
img1 = safe_open_image(image1_path)
img2 = safe_open_image(image2_path)
# Get dimensions of both images
width1, height1 = img1.size
width2, height2 = img2.size
# Determine which image is larger
if (width1 * height1) > (width2 * height2):
# img1 is larger, resize img2 to match img1's dimensions
img2 = img2.resize((width1, height1), Image.NEAREST)
elif (width2 * height2) > (width1 * height1):
# img2 is larger, resize img1 to match img2's dimensions
img1 = img1.resize((width2, height2), Image.NEAREST)
return gr.update(visible=True, value=(img1, img2)), gr.update(value=f"Comparing: {os.path.basename(image1_path)} and {os.path.basename(image2_path)}")
except Exception as e:
return gr.update(visible=False), gr.update(value=f"Error loading images: {str(e)}")
else:
return gr.update(visible=False), gr.update(value="Please select two images to compare")
def refresh_image_list():
"""
Refresh the list of recent images for the comparison tab.
"""
recent_images = get_recent_images(20)
return gr.update(value=recent_images)
# Global variables to keep track of selected images
selected_image1 = None
selected_image2 = None
def on_image_select_gallery1(evt: gr.SelectData, gallery_images):
"""Handle image selection from the first gallery."""
global selected_image1
if not gallery_images or evt.index >= len(gallery_images):
return gr.update(value="Invalid selection"), gr.update(), gr.update()
# Gallery images from get_recent_images should be paths, not tuples
selected_image1 = gallery_images[evt.index]
# Check if it's a tuple and extract the path if needed
if isinstance(selected_image1, tuple):
selected_image1 = selected_image1[0] if selected_image1 else None
if not selected_image1:
return gr.update(value="Invalid selection"), gr.update(), gr.update()
message = f"Selected image 1: {os.path.basename(selected_image1)}"
if selected_image2:
# Check if selected_image2 is a tuple and extract the path if needed
image2_path = selected_image2
if isinstance(selected_image2, tuple):
image2_path = selected_image2[0] if selected_image2 else None
if not image2_path:
return gr.update(value=message), gr.update(), gr.update(value=selected_image1)
message += f" and image 2: {os.path.basename(image2_path)}"
try:
img1 = safe_open_image(selected_image1)
img2 = safe_open_image(image2_path)
# Get dimensions of both images
width1, height1 = img1.size
width2, height2 = img2.size
# Determine which image is larger
if (width1 * height1) > (width2 * height2):
# img1 is larger, resize img2 to match img1's dimensions
img2 = img2.resize((width1, height1), Image.NEAREST)
elif (width2 * height2) > (width1 * height1):
# img2 is larger, resize img1 to match img2's dimensions
img1 = img1.resize((width2, height2), Image.NEAREST)
return gr.update(value=message), gr.update(visible=True, value=(img1, img2)), gr.update(value=selected_image1)
except Exception as e:
return gr.update(value=f"Error loading images: {str(e)}"), gr.update(visible=False), gr.update(value=selected_image1)
return gr.update(value=message), gr.update(), gr.update(value=selected_image1)
def on_image_select_gallery2(evt: gr.SelectData, gallery_images):
"""Handle image selection from the second gallery."""
global selected_image2
if not gallery_images or evt.index >= len(gallery_images):
return gr.update(value="Invalid selection"), gr.update(), gr.update()
# Gallery images from get_recent_images should be paths, not tuples
selected_image2 = gallery_images[evt.index]
# Check if it's a tuple and extract the path if needed
if isinstance(selected_image2, tuple):
selected_image2 = selected_image2[0] if selected_image2 else None
if not selected_image2:
return gr.update(value="Invalid selection"), gr.update(), gr.update()
message = f"Selected image 2: {os.path.basename(selected_image2)}"
if selected_image1:
# Check if selected_image1 is a tuple and extract the path if needed
image1_path = selected_image1
if isinstance(selected_image1, tuple):
image1_path = selected_image1[0] if selected_image1 else None
if not image1_path:
return gr.update(value=message), gr.update(), gr.update(value=selected_image2)
message = f"Selected image 1: {os.path.basename(image1_path)} and image 2: {os.path.basename(selected_image2)}"
try:
img1 = safe_open_image(image1_path)
img2 = safe_open_image(selected_image2)
# Get dimensions of both images
width1, height1 = img1.size
width2, height2 = img2.size
# Determine which image is larger
if (width1 * height1) > (width2 * height2):
# img1 is larger, resize img2 to match img1's dimensions
img2 = img2.resize((width1, height1), Image.NEAREST)
elif (width2 * height2) > (width1 * height1):
# img2 is larger, resize img1 to match img2's dimensions
img1 = img1.resize((width2, height2), Image.NEAREST)
return gr.update(value=message), gr.update(visible=True, value=(img1, img2)), gr.update(value=selected_image2)
except Exception as e:
return gr.update(value=f"Error loading images: {str(e)}"), gr.update(visible=False), gr.update(value=selected_image2)
return gr.update(value=message), gr.update(), gr.update(value=selected_image2)
def clear_selected_images():
"""Clear selected images and refresh the galleries."""
global selected_image1, selected_image2
selected_image1 = None
selected_image2 = None
recent_images = get_recent_images(20)
return gr.update(value=recent_images), gr.update(value=recent_images), gr.update(value="Select one image from each gallery below"), gr.update(visible=False), gr.update(value=""), gr.update(value="")
def compare_selected_images(image1_path, image2_path, uploaded_img1=None, uploaded_img2=None):
"""
Compare images from either the galleries or uploads.
Resize smaller image to match the larger image's dimensions using nearest neighbor interpolation.
"""
img1_path = image1_path if image1_path else uploaded_img1
img2_path = image2_path if image2_path else uploaded_img2
if not img1_path or not img2_path:
return gr.update(visible=False), gr.update(value="Please select two images to compare")
try:
img1 = safe_open_image(img1_path)
img2 = safe_open_image(img2_path)
# Get dimensions of both images
width1, height1 = img1.size
width2, height2 = img2.size
# Determine which image is larger
if (width1 * height1) > (width2 * height2):
# img1 is larger, resize img2 to match img1's dimensions
img2 = img2.resize((width1, height1), Image.NEAREST)
elif (width2 * height2) > (width1 * height1):
# img2 is larger, resize img1 to match img2's dimensions
img1 = img1.resize((width2, height2), Image.NEAREST)
message = f"Comparing: {os.path.basename(img1_path)} and {os.path.basename(img2_path)}"
return gr.update(visible=True, value=(img1, img2)), gr.update(value=message)
except Exception as e:
return gr.update(visible=False), gr.update(value=f"Error loading images: {str(e)}")
# Comment out toggle_compare_fullscreen function
"""
def toggle_compare_fullscreen():
# Toggle fullscreen for the comparison slider.
# Returns compare_result_col, fullscreen button, download button
return (
gr.update(elem_classes=["preview_col", "full_preview"]),
gr.update(elem_classes=["slider_button", "full"]),
gr.update(elem_classes=["slider_button", "full"])
)
"""
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
# Add this function after imports and before any other functions
def safe_open_image(image_path):
"""Safely open any image format including AVIF with fallback options."""
try:
# Try to open normally first
return Image.open(image_path)
except UnidentifiedImageError as e:
print(f"Error opening image with PIL: {str(e)}. Attempting to convert...")
try:
# Create a temporary file for the converted image
import tempfile
temp_output = tempfile.NamedTemporaryFile(delete=False, suffix='.png').name
# Try several methods to convert the image
converted = False
# 1. Try using pillow_avif directly
try:
with Image.open(image_path) as img:
img.save(temp_output, format='PNG')
converted = True
except Exception as conversion_error:
print(f"Direct conversion failed: {str(conversion_error)}")
# 2. Try using Wand (ImageMagick binding)
if not converted:
try:
from wand.image import Image as WandImage
with WandImage(filename=image_path) as wand_img:
wand_img.save(filename=temp_output)
converted = True
print(f"Converted image using Wand")
except Exception as wand_error:
print(f"Wand conversion failed: {str(wand_error)}")
# 3. Try using system commands
if not converted:
import subprocess
try:
if os.name == 'nt': # Windows
subprocess.run(['magick', 'convert', image_path, temp_output], check=True)
else: # Linux/Mac
subprocess.run(['convert', image_path, temp_output], check=True)
converted = True
print(f"Converted image using system commands")
except Exception as cmd_error:
print(f"System command conversion failed: {str(cmd_error)}")
if converted:
return Image.open(temp_output)
else:
raise Exception("All conversion methods failed")
except Exception as e:
print(f"Failed to convert image: {str(e)}")
raise
except Exception as e:
print(f"Error opening image: {str(e)}")
raise
def apply_metadata(image_path):
global elements_dict, extra_info_elements
if image_path is None:
return [gr.update(value="No image selected")] + [gr.update() for _ in range(len(elements_dict) + len(extra_info_elements))]
# Open the image and extract metadata
try:
with safe_open_image(image_path) as img:
metadata = img.info
# First update is for output_label
all_updates = [gr.update(value=f"Applied metadata from {os.path.basename(image_path)}")]
# Add default update for each UI element
for _ in elements_dict:
all_updates.append(gr.update())
for _ in extra_info_elements:
all_updates.append(gr.update())
# Map to track which elements have been updated
updated_elements = set()
# Special handling for the caption - look for it first
caption_value = None
for key in ["Used Final Prompt", "caption"]:
if key in metadata:
caption_value = metadata[key]
break
if caption_value and "main_prompt" in elements_dict:
# Get the index of main_prompt in the list (add 1 for output_label)
main_prompt_index = list(elements_dict.keys()).index("main_prompt") + 1
# Set the update for this element
all_updates[main_prompt_index] = gr.update(value=caption_value)
updated_elements.add("main_prompt")
# Process the rest of the metadata
for key, value in metadata.items():
try:
# Try to use the key directly or find a renamed key
renamed_key = rename_meta_key_reverse(key)
if renamed_key in elements_dict and renamed_key not in updated_elements:
# Get the index of the element in the list (add 1 for output_label)
index = list(elements_dict.keys()).index(renamed_key) + 1
# Convert string boolean values to actual booleans for checkboxes
element = elements_dict[renamed_key]
if isinstance(element, gr.Checkbox):
if isinstance(value, str):
if value.lower() == "true":
value = True
elif value.lower() == "false":
value = False
# Convert numeric strings to numbers for sliders and number inputs
elif isinstance(element, (gr.Slider, gr.Number)):
try:
if isinstance(value, str):
if '.' in value:
value = float(value)
else:
value = int(value)
except (ValueError, TypeError):
pass # Keep as string if conversion fails
# Set the update for this element
all_updates[index] = gr.update(value=value)
updated_elements.add(renamed_key)
elif renamed_key in extra_info_elements and renamed_key not in updated_elements:
# Get the index in the combined list (after elements_dict and add 1 for output_label)
index = 1 + len(elements_dict) + list(extra_info_elements.keys()).index(renamed_key)
# Convert string boolean values to actual booleans for checkboxes
element = extra_info_elements[renamed_key]
if isinstance(element, gr.Checkbox):
if isinstance(value, str):
if value.lower() == "true":
value = True
elif value.lower() == "false":
value = False
all_updates[index] = gr.update(value=value)
updated_elements.add(renamed_key)
except Exception as e:
print(f"Error processing metadata key '{key}': {str(e)}")
return all_updates
except Exception as e:
print(f"Error applying metadata: {str(e)}")
return [gr.update(value=f"Error applying metadata: {str(e)}")] + [gr.update() for _ in range(len(elements_dict) + len(extra_info_elements))]
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, max_megapixels, max_resolution, start_time):
global video_start
video_start = start_time
target_res_text = update_target_resolution(src_file, upscale_size, max_megapixels, max_resolution)
return gr.update(value=target_res_text, visible=True)
def update_end_time(src_file, upscale_size, max_megapixels, max_resolution, end_time):
global video_end
video_end = end_time
target_res_text = update_target_resolution(src_file, upscale_size, max_megapixels, max_resolution)
return gr.update(value=target_res_text, visible=True)
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() == "Darwin": # macOS
subprocess.run(["open", open_folder_path])
else: # Linux and other Unix-like
subprocess.run(["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, max_megapixels, max_resolution):
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, max_megapixels, max_resolution)
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, max_megapixels, max_resolution)
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, max_megapixels=0, max_resolution=0):
global last_input_path, last_video_params
# Convert inputs to proper types
try:
do_upscale = float(do_upscale)
max_megapixels = float(max_megapixels) if max_megapixels else 0
max_resolution = int(float(max_resolution)) if max_resolution else 0
except (ValueError, TypeError):
do_upscale = 1.0
max_megapixels = 0
max_resolution = 0
if img is None:
last_video_params = None
last_input_path = None
return ""
try:
if is_image(img):
last_input_path = img
last_video_params = None
try:
# Use the safe_open_image helper instead of direct Image.open
with safe_open_image(img) as img_obj:
width, height = img_obj.size
width_org, height_org = img_obj.size
except Exception as e:
print(f"Failed to open image: {str(e)}")
raise
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']
print(f"Video dimensions: {width}x{height}")
else:
last_input_path = None
last_video_params = None
print(f"Invalid media type: {type(img)}")
return ""
# Convert width and height to float for calculations
width = float(width)
height = float(height)
width_org = float(width_org)
height_org = float(height_org)
# Calculate aspect ratio for maintaining proportion
aspect_ratio = width / height
# Apply standard upscale factor first
width *= do_upscale
height *= do_upscale
#print(f"After upscale: {width}x{height}")
# Store dimensions before applying minimum constraints (for detection purposes)
width_before_min = width
height_before_min = height
# Default minimal resolution check
if min(width, height) < 1024:
do_upscale_factor = 1024 / min(width, height)
width *= do_upscale_factor
height *= do_upscale_factor
#print(f"After min size adjustment: {width}x{height}")
# Apply max megapixels limit if specified
if max_megapixels > 0:
current_megapixels = width * height / 1_000_000
#print(f"Current MP: {current_megapixels}, Max allowed: {max_megapixels}")
if current_megapixels > max_megapixels:
scale_factor = (max_megapixels * 1_000_000 / (width * height)) ** 0.5
width *= scale_factor
height *= scale_factor
#print(f"After max MP adjustment: {width}x{height}")
# Re-apply minimum resolution check after max megapixels constraint
if min(width, height) < 1024:
min_scale_factor = 1024 / min(width, height)
width *= min_scale_factor
height *= min_scale_factor
# Apply max resolution limit if specified
if max_resolution > 0:
#print(f"Max resolution: {max_resolution}, Current max dimension: {max(width, height)}")
if max(width, height) > max_resolution:
if width > height:
scale_factor = max_resolution / width
else:
scale_factor = max_resolution / height
width *= scale_factor
height *= scale_factor
#print(f"After max resolution adjustment: {width}x{height}")
# Re-apply minimum resolution check after max resolution constraint
if min(width, height) < 1024:
min_scale_factor = 1024 / min(width, height)
width *= min_scale_factor
height *= min_scale_factor
# Round dimensions to multiples of 32 to match upscale_image function
unit_resolution = 32
width = int(np.round(width / unit_resolution)) * unit_resolution
height = int(np.round(height / unit_resolution)) * unit_resolution
#print(f"After unit resolution adjustment: {width}x{height}")
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>",
]