-
Notifications
You must be signed in to change notification settings - Fork 81
/
__init__.py
5893 lines (5118 loc) · 242 KB
/
__init__.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
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTIBILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
bl_info = {
"name": "Pallaidium - Generative AI",
"author": "tintwotin",
"version": (2, 0),
"blender": (3, 4, 0),
"location": "Video Sequence Editor > Sidebar > Generative AI",
"description": "AI Generate media in the VSE",
"category": "Sequencer",
}
# TO DO: Move prints.
import bpy
import ctypes
import random
import site
import platform
import json
import subprocess
import sys
import os
import aud
import re
import glob
import string
from os.path import dirname, realpath, isdir, join, basename
import shutil
from datetime import date
import pathlib
import gc
import time
from bpy_extras.io_utils import ImportHelper
from bpy.types import Operator, Panel, AddonPreferences, UIList, PropertyGroup
from bpy.props import (
StringProperty,
BoolProperty,
EnumProperty,
IntProperty,
FloatProperty,
)
import sys
os.environ['TF_ENABLE_ONEDNN_OPTS'] = '0'
print("Python: " + sys.version)
# if os_platform == "Windows":
# # Temporarily modify pathlib.PosixPath for Windows compatibility
# temp = pathlib.PosixPath
# pathlib.PosixPath = pathlib.WindowsPath
try:
exec("import torch")
if torch.cuda.is_available():
gfx_device = "cuda"
elif torch.backends.mps.is_available():
gfx_device = "mps"
else:
gfx_device = "cpu"
except:
print("Pallaidium dependencies needs to be installed and Blender needs to be restarted.")
os_platform = platform.system() # 'Linux', 'Darwin', 'Java', 'Windows'
if os_platform == "Windows":
pathlib.PosixPath = pathlib.WindowsPath
def show_system_console(show):
if os_platform == "Windows":
# https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-showwindow
SW_HIDE = 0
SW_SHOW = 5
ctypes.windll.user32.ShowWindow(ctypes.windll.kernel32.GetConsoleWindow(), SW_SHOW) # if show else SW_HIDE
def set_system_console_topmost(top):
if os_platform == "Windows":
# https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-setwindowpos
HWND_NOTOPMOST = -2
HWND_TOPMOST = -1
HWND_TOP = 0
SWP_NOMOVE = 0x0002
SWP_NOSIZE = 0x0001
SWP_NOZORDER = 0x0004
ctypes.windll.user32.SetWindowPos(
ctypes.windll.kernel32.GetConsoleWindow(),
HWND_TOP if top else HWND_NOTOPMOST,
0,
0,
0,
0,
SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER,
)
# normalize text, remove redundant whitespace and convert non-ascii quotes to ascii
def format_time(milliseconds):
seconds, milliseconds = divmod(milliseconds, 1000)
minutes, seconds = divmod(seconds, 60)
hours, minutes = divmod(minutes, 60)
return f"{int(hours):02d}:{int(minutes):02d}:{int(seconds):02d}:{int(milliseconds):03d}"
def timer():
start_time = time.time()
return start_time
def print_elapsed_time(start_time):
elapsed_time = time.time() - start_time
formatted_time = format_time(elapsed_time * 1000) # Convert to milliseconds
print(f"Total time: {formatted_time}\n\n")
def split_and_recombine_text(text, desired_length=200, max_length=300):
"""Split text it into chunks of a desired length trying to keep sentences intact."""
text = re.sub(r"\n\n+", "\n", text)
text = re.sub(r"\s+", " ", text)
text = re.sub(r"[“[“”]”]", '"', text)
rv = []
in_quote = False
current = ""
split_pos = []
pos = -1
end_pos = len(text) - 1
def seek(delta):
nonlocal pos, in_quote, current
is_neg = delta < 0
for _ in range(abs(delta)):
if is_neg:
pos -= 1
current = current[:-1]
else:
pos += 1
current += text[pos]
if text[pos] == '"':
in_quote = not in_quote
return text[pos]
def peek(delta):
p = pos + delta
return text[p] if p < end_pos and p >= 0 else ""
def commit():
nonlocal rv, current, split_pos
rv.append(current)
current = ""
split_pos = []
while pos < end_pos:
c = seek(1)
# do we need to force a split?
if len(current) >= max_length:
if len(split_pos) > 0 and len(current) > (desired_length / 2):
# we have at least one sentence and we are over half the desired length, seek back to the last split
d = pos - split_pos[-1]
seek(-d)
else:
# no full sentences, seek back until we are not in the middle of a word and split there
while c not in "!?.,\n " and pos > 0 and len(current) > desired_length:
c = seek(-1)
commit()
# check for sentence boundaries
elif not in_quote and (c in "!?\n" or (c == "." and peek(1) in "\n ")):
# seek forward if we have consecutive boundary markers but still within the max length
while pos < len(text) - 1 and len(current) < max_length and peek(1) in "!?.,":
c = seek(1)
split_pos.append(pos)
if len(current) >= desired_length:
commit()
# treat end of quote as a boundary if its followed by a space or newline
elif in_quote and peek(1) == '"' and peek(2) in "\n ":
seek(2)
split_pos.append(pos)
rv.append(current)
# clean up, remove lines with only whitespace or punctuation
rv = [s.strip() for s in rv]
rv = [s for s in rv if len(s) > 0 and not re.match(r"^[\s\.,;:!?]*$", s)]
return rv
def extract_numbers(input_string):
numbers = re.findall(r"\d+", input_string)
if numbers:
return int(numbers[0])
else:
return None
def load_styles(json_filename):
styles_array = []
try:
with open(json_filename, "r") as json_file:
data = json.load(json_file)
except FileNotFoundError:
print(f"JSON file '{json_filename}' not found.")
data = []
for item in data:
name = item["name"]
prompt = item["prompt"]
negative_prompt = item["negative_prompt"]
styles_array.append((negative_prompt.lower().replace(" ", "_"), name.title(), prompt))
return styles_array
def style_prompt(prompt):
selected_entry_key = bpy.context.scene.generatorai_styles
return_array = []
if selected_entry_key:
styles_array = load_styles(os.path.dirname(os.path.abspath(__file__)) + "/styles.json")
if styles_array:
selected_entry = next((item for item in styles_array if item[0] == selected_entry_key), None)
if selected_entry:
selected_entry_list = list(selected_entry)
return_array.append(selected_entry_list[2].replace("{prompt}", prompt))
return_array.append(bpy.context.scene.generate_movie_negative_prompt + ", " + selected_entry_list[0].replace("_", " "))
return return_array
return_array.append(prompt)
return_array.append(bpy.context.scene.generate_movie_negative_prompt)
return return_array
def closest_divisible_16(num):
# Determine the remainder when num is divided by 64
remainder = num % 16
# If the remainder is less than or equal to 16, return num - remainder,
# but ensure the result is not less than 192
if remainder <= 8:
result = num - remainder
return max(result, 192)
# Otherwise, return num + (32 - remainder)
else:
return max(num + (16 - remainder), 192)
def closest_divisible_128(num):
# Determine the remainder when num is divided by 128
remainder = num % 128
# If the remainder is less than or equal to 64, return num - remainder,
# but ensure the result is not less than 256
if remainder <= 64:
result = num - remainder
return max(result, 256)
# Otherwise, return num + (32 - remainder)
else:
return max(num + (64 - remainder), 256)
def find_first_empty_channel(start_frame, end_frame):
for ch in range(1, len(bpy.context.scene.sequence_editor.sequences_all) + 1):
for seq in bpy.context.scene.sequence_editor.sequences_all:
if seq.channel == ch and seq.frame_final_start < end_frame and (seq.frame_final_start + seq.frame_final_duration) > start_frame:
break
else:
return ch
return 1
def clean_filename(filename):
filename = filename[:50]
valid_chars = "-_,.() %s%s" % (string.ascii_letters, string.digits)
clean_filename = "".join(c if c in valid_chars else "_" for c in filename)
clean_filename = clean_filename.replace("\n", " ")
clean_filename = clean_filename.replace("\r", " ")
clean_filename = clean_filename.replace(" ", "_")
return clean_filename.strip()
def create_folder(folderpath):
try:
os.makedirs(folderpath)
return True
except FileExistsError:
# directory already exists
pass
return False
def solve_path(full_path):
preferences = bpy.context.preferences
addon_prefs = preferences.addons[__name__].preferences
name, ext = os.path.splitext(full_path)
dir_path, filename = os.path.split(name)
dir_path = os.path.join(addon_prefs.generator_ai, str(date.today()))
create_folder(dir_path)
cleaned_filename = clean_filename(filename)
new_filename = cleaned_filename + ext
i = 1
while os.path.exists(os.path.join(dir_path, new_filename)):
name, ext = os.path.splitext(new_filename)
new_filename = f"{name.rsplit('(', 1)[0]}({i}){ext}"
i += 1
return os.path.join(dir_path, new_filename)
def limit_string(my_string):
if len(my_string) > 77:
print(
"Warning: String is longer than 77 characters. Excessive string:",
my_string[77:],
)
return my_string[:77]
else:
return my_string
def delete_strip(input_strip):
if input_strip is None:
return
original_selection = [strip for strip in bpy.context.scene.sequence_editor.sequences_all if strip.select]
bpy.ops.sequencer.select_all(action="DESELECT")
input_strip.select = True
bpy.ops.sequencer.delete()
for strip in original_selection:
strip.select = True
def load_video_as_np_array(video_path):
import cv2
import numpy as np
cap = cv2.VideoCapture(video_path)
if not cap.isOpened():
raise IOError("Error opening video file")
frames = []
while True:
ret, frame = cap.read()
if not ret:
break
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
frames.append(frame)
cap.release()
return np.array(frames)
def load_first_frame(file_path):
import cv2, PIL, os
from diffusers.utils import load_image
extension = os.path.splitext(file_path)[-1].lower() # Convert to lowercase for case-insensitive comparison
valid_image_extensions = {
".sgi",
".rgb",
".bw",
".cin",
".dpx",
".png",
".jpg",
".jpeg",
".jp2",
".jp2",
".j2c",
".tga",
".exr",
".hdr",
".tif",
".tiff",
".webp",
}
valid_video_extensions = {
".avi",
".flc",
".mov",
".movie",
".mp4",
".m4v",
".m2v",
".m2t",
".m2ts",
".mts",
".ts",
".mv",
".avs",
".wmv",
".ogv",
".ogg",
".r3d",
".dv",
".mpeg",
".mpg",
".mpg2",
".vob",
".mkv",
".flv",
".divx",
".xvid",
".mxf",
".webm",
}
if extension in valid_image_extensions:
image = cv2.imread(file_path)
# if image is not None:
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
return PIL.Image.fromarray(image)
if extension in valid_video_extensions:
# Try to open the file as a video
cap = cv2.VideoCapture(file_path)
# Check if the file was successfully opened as a video
if cap.isOpened():
# Read the first frame from the video
ret, frame = cap.read()
cap.release() # Release the video capture object
if ret:
# If the first frame was successfully read, it's a video
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
return PIL.Image.fromarray(frame)
# If neither video nor image worked, return None
return None
def process_frames(frame_folder_path, target_width):
from PIL import Image
Image.MAX_IMAGE_PIXELS = None
import cv2
processed_frames = []
# List all image files in the folder
image_files = sorted([f for f in os.listdir(frame_folder_path) if f.endswith(".png")])
for image_file in image_files:
image_path = os.path.join(frame_folder_path, image_file)
img = Image.open(image_path)
# Process the image (resize and convert to RGB)
frame_width, frame_height = img.size
# Calculate the target height to maintain the original aspect ratio
target_height = int((target_width / frame_width) * frame_height)
# Ensure width and height are divisible by 64
target_width = closest_divisible_16(target_width)
target_height = closest_divisible_16(target_height)
img = img.resize((target_width, target_height), Image.Resampling.LANCZOS)
img = img.convert("RGB")
processed_frames.append(img)
return processed_frames
def process_video(input_video_path, output_video_path):
from PIL import Image
Image.MAX_IMAGE_PIXELS = None
import cv2
import shutil
scene = bpy.context.scene
movie_x = scene.generate_movie_x
# Create a temporary folder for storing frames
temp_image_folder = solve_path("temp_images")
if not os.path.exists(temp_image_folder):
os.makedirs(temp_image_folder)
# Open the video file using OpenCV
cap = cv2.VideoCapture(input_video_path)
frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
fps = int(cap.get(cv2.CAP_PROP_FPS))
# Save each loaded frame as an image in the temp folder
for i in range(frame_count):
ret, frame = cap.read()
if not ret:
break
# Save the frame as an image in the temp folder
temp_image_path = os.path.join(temp_image_folder, f"frame_{i:04d}.png")
cv2.imwrite(temp_image_path, frame)
cap.release()
# Process frames using the separate function
processed_frames = process_frames(temp_image_folder, movie_x)
# Clean up: Delete the temporary image folder
shutil.rmtree(temp_image_folder)
return processed_frames
# Define the function for zooming effect
def zoomPan(img, zoom=1, angle=0, coord=None):
import cv2
cy, cx = [i / 2 for i in img.shape[:-1]] if coord is None else coord[::-1]
rot = cv2.getRotationMatrix2D((cx, cy), angle, zoom)
res = cv2.warpAffine(img, rot, img.shape[1::-1], flags=cv2.INTER_LINEAR)
return res
def process_image(image_path, frames_nr):
from PIL import Image
Image.MAX_IMAGE_PIXELS = None
import cv2, shutil
scene = bpy.context.scene
movie_x = scene.generate_movie_x
img = cv2.imread(image_path)
height, width, layers = img.shape
# Create a temporary folder for storing frames
temp_image_folder = solve_path("/temp_images")
if not os.path.exists(temp_image_folder):
os.makedirs(temp_image_folder)
max_zoom = 2.0 # Maximum Zoom level (should be > 1.0)
max_rot = 30 # Maximum rotation in degrees, set '0' for no rotation
# Make the loop for Zooming-in
i = 1
while i < frames_nr:
zLvl = 1.0 + ((i / (1 / (max_zoom - 1)) / frames_nr) * 0.005)
angle = 0 # i * max_rot / frames_nr
zoomedImg = zoomPan(img, zLvl, angle, coord=None)
output_path = os.path.join(temp_image_folder, f"frame_{i:04d}.png")
cv2.imwrite(output_path, zoomedImg)
i = i + 1
# Process frames using the separate function
processed_frames = process_frames(temp_image_folder, movie_x)
# Clean up: Delete the temporary image folder
shutil.rmtree(temp_image_folder)
return processed_frames
def low_vram():
try:
if gfx_device == "mps":
return True
exec("import torch")
total_vram = 0
for i in range(torch.cuda.device_count()):
properties = torch.cuda.get_device_properties(i)
total_vram += properties.total_memory
return (total_vram / (1024**3)) <= 16 # Y/N under 16 GB?
except:
print("Torch not found!")
return True
def clear_cuda_cache():
gc.collect()
if torch.cuda.is_available():
torch.cuda.empty_cache()
#def isWindows():
# return os.name == "nt"
#def isMacOS():
# return os.name == "posix" and platform.system() == "Darwin"
#def isLinux():
# return os.name == "posix" and platform.system() == "Linux"
#def python_exec():
# import sys
# if isWindows():
# return os.path.join(sys.prefix, "bin", "python.exe")
# elif isMacOS():
# try:
# # 2.92 and older
# path = bpy.app.binary_path_python
# except AttributeError:
# # 2.93 and later
# import sys
# path = sys.executable
# return os.path.abspath(path)
# elif isLinux():
# return os.path.join(sys.prefix, "bin", "python")
# else:
# print("sorry, still not implemented for ", os.name, " - ", platform.system)
def python_exec():
return sys.executable
def find_strip_by_name(scene, name):
for sequence in scene.sequence_editor.sequences:
if sequence.name == name:
return sequence
return None
def get_strip_path(strip):
if strip.type == "IMAGE":
strip_dirname = os.path.dirname(strip.directory)
image_path = bpy.path.abspath(os.path.join(strip_dirname, strip.elements[0].filename))
return image_path
if strip.type == "MOVIE":
movie_path = bpy.path.abspath(strip.filepath)
return movie_path
return None
def clamp_value(value, min_value, max_value):
# Ensure value is within the specified range
return max(min(value, max_value), min_value)
def find_overlapping_frame(strip, current_frame):
# Calculate the end frame of the strip
strip_end_frame = strip.frame_final_start + strip.frame_duration
# Check if the strip's frame range overlaps with the current frame
if strip.frame_final_start <= current_frame <= strip_end_frame:
# Calculate the overlapped frame by subtracting strip.frame_start from the current frame
return current_frame - strip.frame_start
else:
return None # Return None if there is no overlap
def ensure_unique_filename(file_name):
if os.path.exists(file_name):
base_name, extension = os.path.splitext(file_name)
index = 1
while True:
unique_file_name = f"{base_name}_{index}{extension}"
if not os.path.exists(unique_file_name):
return unique_file_name
index += 1
else:
return file_name
def import_module(self, module, install_module):
show_system_console(True)
set_system_console_topmost(True)
module = str(module)
python_exe = python_exec()
# try:
# #exec("import " + module)
# subprocess.call([python_exe, "import ", module])
# except:
self.report({"INFO"}, "Installing: " + module + " module.")
print("\nInstalling: " + module + " module")
subprocess.call([python_exe, "-m", "pip", "install", "--disable-pip-version-check", "--use-deprecated=legacy-resolver", install_module, "--no-warn-script-location", "--upgrade"])
# try:
# exec("import " + module)
# except ModuleNotFoundError:
# print("Module not found: " + module)
# return False
return True
def parse_python_version(version_info):
major, minor = version_info[:2]
return f"{major}.{minor}"
def install_modules(self):
os_platform = platform.system()
app_path = site.USER_SITE
pybin = python_exec()
print("Ensuring: pip")
try:
subprocess.call([pybin, "-m", "ensurepip"])
except ImportError:
subprocess.call([pybin, "-m", "pip", "install", "--upgrade", "pip"])
pass
# import_module(self, "diffusers", "diffusers")
import_module(self, "diffusers", "git+https://github.com/huggingface/diffusers.git")
import_module(self, "huggingface_hub", "huggingface_hub")
import_module(self, "protobuf", "protobuf")
import_module(self, "pydub", "pydub")
if os_platform == "Windows":
import_module(self, "deepspeed", "https://github.com/daswer123/deepspeed-windows/releases/download/13.1/deepspeed-0.13.1+cu121-cp311-cp311-win_amd64.whl")
# resemble-enhance:
subprocess.call(
[pybin, "-m", "pip", "install", "--disable-pip-version-check", "--use-deprecated=legacy-resolver", "git+https://github.com/tin2tin/resemble-enhance-windows.git", "--upgrade"] #"--no-dependencies",
)
#deep_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "deepspeed/deepspeed-0.12.4+unknown-py3-none-any.whl")
else:
import_module(self, "deepspeed", "deepspeed==0.14.4")
import_module(self, "resemble_enhance", "resemble-enhance")
subprocess.check_call([pybin, "-m", "pip", "install", "--disable-pip-version-check","--use-deprecated=legacy-resolver", "tensorflow", "--upgrade"])
import_module(self, "sentencepiece", "sentencepiece")
import_module(self, "safetensors", "safetensors")
import_module(self, "cv2", "opencv_python")
import_module(self, "PIL", "pillow")
import_module(self, "scipy", "scipy")
import_module(self, "IPython", "IPython")
import_module(self, "omegaconf", "omegaconf")
#import_module(self, "hidiffusion", "hidiffusion")
import_module(self, "aura_sr", "aura-sr")
import_module(self, "stable_audio_tools", "stable-audio-tools")
if os_platform == "Windows":
pass
import_module(self, "flash_attn", "https://github.com/oobabooga/flash-attention/releases/download/v2.6.3/flash_attn-2.6.3+cu122torch2.3.1cxx11abiFALSE-cp311-cp311-win_amd64.whl")
else:
import_module(self, "flash_attn", "flash-attn")
subprocess.call([pybin, "-m", "pip", "install", "--disable-pip-version-check", "--use-deprecated=legacy-resolver", "controlnet-aux", "--upgrade"])
import_module(self, "beautifulsoup4", "beautifulsoup4")
import_module(self, "ftfy", "ftfy")
python_version_info = sys.version_info
python_version_str = parse_python_version(python_version_info)
import_module(self, "imageio", "imageio[ffmpeg]==2.4.1")
import_module(self, "imageio", "imageio-ffmpeg")
import_module(self, "imWatermark", "imWatermark")
import_module(self, "parler_tts", "git+https://github.com/huggingface/parler-tts.git")
if os_platform == "Windows":
subprocess.call([pybin, "-m", "pip", "install", "--disable-pip-version-check", "--use-deprecated=legacy-resolver", "--disable-pip-version-check", "https://hf-mirror.com/LightningJay/triton-2.1.0-python3.11-win_amd64-wheel/resolve/main/triton-2.1.0-cp311-cp311-win_amd64.whl", "--upgrade", '--user'])
else:
try:
exec("import triton")
except ModuleNotFoundError:
import_module(self, "triton", "triton")
import_module(self, "mediapipe", "mediapipe")
subprocess.call([pybin, "-m", "pip", "install", "--disable-pip-version-check", "--use-deprecated=legacy-resolver", "ultralytics", "--upgrade"])
subprocess.call([pybin, "-m", "pip", "install", "--disable-pip-version-check", "--use-deprecated=legacy-resolver", "git+https://github.com/theblackhatmagician/adetailer_sdxl.git"])
subprocess.call([pybin, "-m", "pip", "install", "--disable-pip-version-check", "--use-deprecated=legacy-resolver", "lmdb", "--upgrade"])
subprocess.call([pybin, "-m", "pip", "install", "--disable-pip-version-check", "--use-deprecated=legacy-resolver", "git+https://github.com/huggingface/accelerate.git", "--upgrade"])
#import_module(self, "accelerate", "git+https://github.com/huggingface/accelerate.git")
#import_module(self, "accelerate", "accelerate")
import_module(self, "controlnet_aux", "controlnet-aux")
self.report({"INFO"}, "Installing: torch module.")
print("\nInstalling: torch module")
if os_platform == "Windows":
subprocess.call([pybin, "-m", "pip", "uninstall", "-y", "torch"])
subprocess.call([pybin, "-m", "pip", "uninstall", "-y", "torchvision"])
subprocess.call([pybin, "-m", "pip", "uninstall", "-y", "torchaudio"])
subprocess.call([pybin, "-m", "pip", "uninstall", "-y", "xformers"])
subprocess.check_call(
[
pybin,
"-m",
"pip",
"install",
"torch==2.3.1+cu121",
"xformers",
"torchvision",
"--index-url",
"https://download.pytorch.org/whl/cu121",
"--no-warn-script-location",
#"--user",
"--upgrade",
]
)
subprocess.check_call(
[
pybin,
"-m",
"pip",
"install",
"torchaudio==2.3.1+cu121",
"--index-url",
"https://download.pytorch.org/whl/cu121",
"--no-warn-script-location",
#"--user",
"--upgrade",
]
)
else:
import_module(self, "torch", "torch")
import_module(self, "torchvision", "torchvision")
import_module(self, "torchaudio", "torchaudio")
import_module(self, "xformers", "xformers")
import_module(self, "torchao", "torchao")
if os_platform != "Linux":
subprocess.call([pybin, "-m", "pip", "install", "--disable-pip-version-check", "--use-deprecated=legacy-resolver", "git+https://github.com/suno-ai/bark.git", "--upgrade"])
import_module(self, "whisperspeech", "WhisperSpeech==0.8")
import_module(self, "jaxlib", "jaxlib>=0.4.33")
subprocess.check_call([pybin, "-m", "pip", "install", "peft", "--upgrade"])
import_module(self, "transformers", "transformers==4.43.0")
print("Dir: " + str(subprocess.check_call([pybin, "-m", "pip", "cache", "purge"])))
def get_module_dependencies(module_name):
"""
Get the list of dependencies for a given module.
"""
pybin = python_exec()
result = subprocess.run([pybin, "-m", "pip", "show", module_name], capture_output=True, text=True)
dependencies = []
if result.stdout:
output = result.stdout.strip()
else:
return dependencies
for line in output.split("\n"):
if line.startswith("Requires:"):
dependencies = line.split(":")[1].strip().split(", ")
break
return dependencies
def uninstall_module_with_dependencies(module_name):
"""
Uninstall a module and its dependencies.
"""
show_system_console(True)
set_system_console_topmost(True)
pybin = python_exec()
dependencies = get_module_dependencies(module_name)
subprocess.run([pybin, "-m", "pip", "uninstall", "-y", module_name])
for dependency in dependencies:
if (len(dependency) > 5 and str(dependency[5].lower) != "numpy") and not dependency.find("requests"):
subprocess.run([pybin, "-m", "pip", "uninstall", "-y", dependency])
class GENERATOR_OT_install(Operator):
"""Install all dependencies"""
bl_idname = "sequencer.install_generator"
bl_label = "Install Dependencies"
bl_options = {"REGISTER", "UNDO"}
def execute(self, context):
preferences = context.preferences
addon_prefs = preferences.addons[__name__].preferences
install_modules(self)
self.report(
{"INFO"},
"Installation of dependencies is finished.",
)
return {"FINISHED"}
class GENERATOR_OT_uninstall(Operator):
"""Uninstall all dependencies"""
bl_idname = "sequencer.uninstall_generator"
bl_label = "Uninstall Dependencies"
bl_options = {"REGISTER", "UNDO"}
def execute(self, context):
pybin = python_exec()
preferences = context.preferences
addon_prefs = preferences.addons[__name__].preferences
uninstall_module_with_dependencies("torch")
uninstall_module_with_dependencies("torchvision")
uninstall_module_with_dependencies("torchaudio")
uninstall_module_with_dependencies("diffusers")
uninstall_module_with_dependencies("transformers")
uninstall_module_with_dependencies("sentencepiece")
uninstall_module_with_dependencies("safetensors")
uninstall_module_with_dependencies("opencv_python")
uninstall_module_with_dependencies("scipy")
uninstall_module_with_dependencies("IPython")
uninstall_module_with_dependencies("bark")
uninstall_module_with_dependencies("xformers")
uninstall_module_with_dependencies("imageio")
uninstall_module_with_dependencies("imWatermark")
uninstall_module_with_dependencies("pillow")
uninstall_module_with_dependencies("libtorrent")
uninstall_module_with_dependencies("accelerate")
uninstall_module_with_dependencies("triton")
uninstall_module_with_dependencies("cv2")
uninstall_module_with_dependencies("protobuf")
uninstall_module_with_dependencies("resemble-enhance")
uninstall_module_with_dependencies("mediapipe")
uninstall_module_with_dependencies("flash_attn")
uninstall_module_with_dependencies("controlnet-aux")
uninstall_module_with_dependencies("stable-audio-tools")
uninstall_module_with_dependencies("beautifulsoup4")
uninstall_module_with_dependencies("ftfy")
uninstall_module_with_dependencies("albumentations")
uninstall_module_with_dependencies("datasets")
uninstall_module_with_dependencies("deepspeed")
uninstall_module_with_dependencies("gradio-client")
uninstall_module_with_dependencies("insightface")
uninstall_module_with_dependencies("suno-bark")
uninstall_module_with_dependencies("aura-sr")
uninstall_module_with_dependencies("peft")
uninstall_module_with_dependencies("ultralytics")
uninstall_module_with_dependencies("aura-sr")
uninstall_module_with_dependencies("parler-tts")
# "resemble-enhance":
uninstall_module_with_dependencies("celluloid")
uninstall_module_with_dependencies("omegaconf")
uninstall_module_with_dependencies("pandas")
uninstall_module_with_dependencies("ptflops")
uninstall_module_with_dependencies("rich")
uninstall_module_with_dependencies("resampy")
uninstall_module_with_dependencies("tabulate")
uninstall_module_with_dependencies("gradio")
# WhisperSpeech
uninstall_module_with_dependencies("ruamel.yaml.clib")
uninstall_module_with_dependencies("fastprogress")
uninstall_module_with_dependencies("fastcore")
uninstall_module_with_dependencies("ruamel.yaml")
uninstall_module_with_dependencies("hyperpyyaml")
uninstall_module_with_dependencies("speechbrain")
uninstall_module_with_dependencies("vocos")
uninstall_module_with_dependencies("WhisperSpeech")
uninstall_module_with_dependencies("pydub")
subprocess.check_call([pybin, "-m", "pip", "cache", "purge"])
self.report(
{"INFO"},
"\nRemove AI Models manually: \nLinux and macOS: ~/.cache/huggingface/hub\nWindows: %userprofile%\\.cache\\huggingface\\hub",
)
return {"FINISHED"}
def lcm_updated(self, context):
scene = context.scene
if scene.use_lcm:
scene.movie_num_guidance = 0
def filter_updated(self, context):
scene = context.scene
if (scene.aurasr or scene.adetailer) and scene.movie_num_batch > 1 :
scene.movie_num_batch = 1
print("INFO: Aura SR and ADetailer will only allow for 1 batch for memory reasons.")
def input_strips_updated(self, context):
preferences = context.preferences
addon_prefs = preferences.addons[__name__].preferences
movie_model_card = addon_prefs.movie_model_card
image_model_card = addon_prefs.image_model_card
scene = context.scene
type = scene.generatorai_typeselect
input = scene.input_strips
if movie_model_card == "stabilityai/stable-diffusion-xl-base-1.0" and type == "movie":
scene.input_strips = "input_strips"
if type == "movie" or type == "audio" or image_model_card == "xinsir/controlnet-scribble-sdxl-1.0":
scene.inpaint_selected_strip = ""
if (
type == "image"
and scene.input_strips != "input_strips"
and (
image_model_card == "diffusers/controlnet-canny-sdxl-1.0-small"
or image_model_card == "xinsir/controlnet-openpose-sdxl-1.0"
or image_model_card == "xinsir/controlnet-scribble-sdxl-1.0"
or image_model_card == "Salesforce/blipdiffusion"
)
):
scene.input_strips = "input_strips"
if context.scene.lora_folder:
bpy.ops.lora.refresh_files()
if type == "text":
scene.input_strips = "input_strips"
if (type == "movie" and movie_model_card == "stabilityai/stable-video-diffusion-img2vid") or (
type == "movie" and movie_model_card == "stabilityai/stable-video-diffusion-img2vid-xt"
):
scene.input_strips = "input_strips"
if scene.input_strips == "input_prompt":
bpy.types.Scene.movie_path = ""
bpy.types.Scene.image_path = ""
if (movie_model_card == "THUDM/CogVideoX-5b" or movie_model_card == "THUDM/CogVideoX-2b") and type == "movie":
scene.generate_movie_x = 720
scene.generate_movie_y = 480
scene.generate_movie_frames = 48
scene.movie_num_inference_steps = 50
scene.movie_num_guidance = 6
if (image_model_card == "dataautogpt3/OpenDalleV1.1") and type == "image":
bpy.context.scene.use_lcm = False
if (image_model_card == "Kwai-Kolors/Kolors-diffusers") and type == "image":
bpy.context.scene.use_lcm = False
if (image_model_card == "Tencent-Hunyuan/HunyuanDiT-v1.2-Diffusers") and type == "image":