-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathsdxl_utility.py
3080 lines (2647 loc) · 120 KB
/
sdxl_utility.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
# Converting the prompt generation script into a ComfyUI plugin structure
import random
import json
import requests
import comfy.sd
import comfy.model_management
import nodes
import torch
import os
import google.generativeai as genai
import base64
from io import BytesIO
from openai import OpenAI
import torch
import numpy as np
from datetime import datetime
import codecs
from PIL import Image
import chardet
import io
import folder_paths
from transformers import AutoModelForCausalLM
from transformers import AutoProcessor
def tensor2pil(t_image: torch.Tensor) -> Image:
return Image.fromarray(np.clip(255.0 * t_image.cpu().numpy().squeeze(), 0, 255).astype(np.uint8))
models_file = os.path.join(os.path.dirname(__file__), "data", "gemini_models.json")
with open(models_file, 'r') as f:
models_data = json.load(f)
gemini_models = models_data.get('models', [])
# Function to load data from a JSON file
def load_json_file(file_name):
# Construct the absolute path to the data file
file_path = os.path.join(os.path.dirname(__file__), "data", file_name)
with open(file_path, "r") as file:
return json.load(file)
def load_all_json_files(base_path):
data = {}
for root, dirs, files in os.walk(base_path):
for file in files:
if file.endswith(".json"):
file_path = os.path.join(root, file)
relative_path = os.path.relpath(file_path, base_path)
key = os.path.splitext(relative_path)[0].replace(os.path.sep, "_")
try:
with codecs.open(file_path, "r", "utf-8") as f:
data[key] = json.load(f)
except UnicodeDecodeError:
print(
f"Warning: Unable to decode file {file_path} with UTF-8 encoding. Skipping this file."
)
except json.JSONDecodeError:
print(
f"Warning: Invalid JSON in file {file_path}. Skipping this file."
)
return data
# Assuming your script is in the same directory as the 'data' folder
base_dir = os.path.dirname(__file__)
next_dir = os.path.join(base_dir, "data", "next")
prompt_dir = os.path.join(base_dir, "data", "custom_prompts")
# custom_dir = os.path.join(base_dir, "data", "custom")
# Load all JSON files
all_data = load_all_json_files(next_dir)
# Now you can access the data using keys like:
# all_data['brands']
# all_data['architecture_architect']
# all_data['art_painting']
# etc.
# print(all_data.keys())
# To access a specific file's data:
# if 'brands' in all_data:
# print(all_data['brands'])
# if 'architecture_architect' in all_data:
# print(all_data['architecture_architect'])
# import nodes
import re
ARTFORM = load_json_file("artform.json")
PHOTO_FRAMING = load_json_file("photo_framing.json")
PHOTO_TYPE = load_json_file("photo_type.json")
DEFAULT_TAGS = load_json_file("default_tags.json")
ROLES = load_json_file("roles.json")
HAIRSTYLES = load_json_file("hairstyles.json")
ADDITIONAL_DETAILS = load_json_file("additional_details.json")
PHOTOGRAPHY_STYLES = load_json_file("photography_styles.json")
DEVICE = load_json_file("device.json")
PHOTOGRAPHER = load_json_file("photographer.json")
ARTIST = load_json_file("artist.json")
DIGITAL_ARTFORM = load_json_file("digital_artform.json")
PLACE = load_json_file("place.json")
LIGHTING = load_json_file("lighting.json")
CLOTHING = load_json_file("clothing.json")
COMPOSITION = load_json_file("composition.json")
POSE = load_json_file("pose.json")
BACKGROUND = load_json_file("background.json")
BODY_TYPES = load_json_file("body_types.json")
CUSTOM_CATEGORY = "comfyui_dagthomas"
class DynamicStringCombinerNode:
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"num_inputs": (["1", "2", "3", "4", "5"],),
"user_text": ("STRING", {"multiline": True}),
},
"optional": {
"string1": ("STRING", {"multiline": False}),
"string2": ("STRING", {"multiline": False}),
"string3": ("STRING", {"multiline": False}),
"string4": ("STRING", {"multiline": False}),
"string5": ("STRING", {"multiline": False}),
},
}
RETURN_TYPES = ("STRING",)
FUNCTION = "combine_strings"
CATEGORY = CUSTOM_CATEGORY
def combine_strings(
self,
num_inputs,
user_text,
string1="",
string2="",
string3="",
string4="",
string5="",
):
# Convert num_inputs to integer
n = int(num_inputs)
# Get the specified number of input strings
input_strings = [string1, string2, string3, string4, string5][:n]
# Combine the input strings
combined = ", ".join(s for s in input_strings if s.strip())
# Append the user_text to the result
result = f"{combined}\nUser Input: {user_text}"
return (result,)
@classmethod
def IS_CHANGED(
s, num_inputs, user_text, string1, string2, string3, string4, string5
):
return float(num_inputs)
class SentenceMixerNode:
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"input1": ("STRING", {"multiline": True}),
},
"optional": {
"input2": ("STRING", {"multiline": True}),
"input3": ("STRING", {"multiline": True}),
"input4": ("STRING", {"multiline": True}),
},
}
RETURN_TYPES = ("STRING",)
FUNCTION = "mix_sentences"
CATEGORY = CUSTOM_CATEGORY
def mix_sentences(self, input1, input2="", input3="", input4=""):
def process_input(input_data):
if isinstance(input_data, list):
return " ".join(input_data)
return input_data
all_text = " ".join(
filter(
bool,
[process_input(input) for input in [input1, input2, input3, input4]],
)
)
sentences = []
current_sentence = ""
for char in all_text:
current_sentence += char
if char in [".", ","]:
sentences.append(current_sentence.strip())
current_sentence = ""
if current_sentence:
sentences.append(current_sentence.strip())
random.shuffle(sentences)
result = " ".join(sentences)
return (result,)
# This line is needed to register the node in ComfyUI
NODE_CLASS_MAPPINGS = {"SentenceMixerNode": SentenceMixerNode}
class RandomIntegerNode:
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"min_value": (
"INT",
{"default": 0, "min": -1000000000, "max": 1000000000, "step": 1},
),
"max_value": (
"INT",
{"default": 10, "min": -1000000000, "max": 1000000000, "step": 1},
),
}
}
RETURN_TYPES = ("INT",)
FUNCTION = "generate_random_int"
CATEGORY = CUSTOM_CATEGORY # Replace with your actual category
def generate_random_int(self, min_value, max_value):
if min_value > max_value:
min_value, max_value = max_value, min_value
result = random.randint(min_value, max_value)
# print(f"Generating random int between {min_value} and {max_value}: {result}")
return (result,)
class FlexibleStringMergerNode:
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"string1": ("STRING", {"default": ""}),
},
"optional": {
"string2": ("STRING", {"default": ""}),
"string3": ("STRING", {"default": ""}),
"string4": ("STRING", {"default": ""}),
},
}
RETURN_TYPES = ("STRING",)
FUNCTION = "merge_strings"
CATEGORY = CUSTOM_CATEGORY
def merge_strings(self, string1, string2="", string3="", string4=""):
def process_input(s):
if isinstance(s, list):
return ", ".join(str(item) for item in s)
return str(s).strip()
strings = [
process_input(s)
for s in [string1, string2, string3, string4]
if process_input(s)
]
if not strings:
return "" # Return an empty string if no non-empty inputs
return (" AND ".join(strings),)
class StringMergerNode:
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"string1": ("STRING", {"default": "", "forceInput": True}),
"string2": ("STRING", {"default": "", "forceInput": True}),
"use_and": ("BOOLEAN", {"default": False}),
}
}
RETURN_TYPES = ("STRING",)
FUNCTION = "merge_strings"
CATEGORY = CUSTOM_CATEGORY
def merge_strings(self, string1, string2, use_and):
def process_input(s):
if isinstance(s, list):
return ",".join(str(item).strip() for item in s)
return str(s).strip()
processed_string1 = process_input(string1)
processed_string2 = process_input(string2)
separator = " AND " if use_and else ","
merged = f"{processed_string1}{separator}{processed_string2}"
# Remove double commas and clean spaces around commas
merged = merged.replace(",,", ",").replace(" ,", ",").replace(", ", ",")
# Clean leading and trailing spaces
merged = merged.strip()
return (merged,)
class PGSD3LatentGenerator:
def __init__(self):
self.device = comfy.model_management.intermediate_device()
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"width": (
"INT",
{"default": 1024, "min": 0, "max": nodes.MAX_RESOLUTION, "step": 8},
),
"height": (
"INT",
{"default": 1024, "min": 0, "max": nodes.MAX_RESOLUTION, "step": 8},
),
"batch_size": ("INT", {"default": 1, "min": 1, "max": 4096}),
}
}
RETURN_TYPES = ("LATENT",)
FUNCTION = "generate"
CATEGORY = CUSTOM_CATEGORY
def generate(self, width=1024, height=1024, batch_size=1):
def adjust_dimensions(width, height):
megapixel = 1_000_000
multiples = 64
if width == 0 and height != 0:
height = int(height)
width = megapixel // height
if width % multiples != 0:
width += multiples - (width % multiples)
if width * height > megapixel:
width -= multiples
elif height == 0 and width != 0:
width = int(width)
height = megapixel // width
if height % multiples != 0:
height += multiples - (height % multiples)
if width * height > megapixel:
height -= multiples
elif width == 0 and height == 0:
width = 1024
height = 1024
return width, height
width, height = adjust_dimensions(width, height)
latent = (
torch.ones([batch_size, 16, height // 8, width // 8], device=self.device)
* 0.0609
)
return ({"samples": latent},)
class APNLatent:
def __init__(self):
self.device = comfy.model_management.intermediate_device()
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"width": (
"INT",
{"default": 1024, "min": 0, "max": nodes.MAX_RESOLUTION, "step": 8},
),
"height": (
"INT",
{"default": 1024, "min": 0, "max": nodes.MAX_RESOLUTION, "step": 8},
),
"batch_size": ("INT", {"default": 1, "min": 1, "max": 4096}),
"megapixel_scale": (
"FLOAT",
{"default": 1.0, "min": 0.1, "max": 2.0, "step": 0.1},
),
"aspect_ratio": (
["1:1", "3:2", "4:3", "16:9", "21:9"],
{"default": "1:1"},
),
"is_portrait": ("BOOLEAN", {"default": False}),
}
}
RETURN_TYPES = ("LATENT", "INT", "INT")
RETURN_NAMES = ("LATENT", "width", "height")
FUNCTION = "generate"
CATEGORY = CUSTOM_CATEGORY
def generate(
self,
width=1024,
height=1024,
batch_size=1,
megapixel_scale=1.0,
aspect_ratio="1:1",
is_portrait=False,
):
def adjust_dimensions(megapixels, aspect_ratio, is_portrait):
aspect_ratios = {
"1:1": (1, 1),
"3:2": (3, 2),
"4:3": (4, 3),
"16:9": (16, 9),
"21:9": (21, 9),
}
ar_width, ar_height = aspect_ratios[aspect_ratio]
if is_portrait:
ar_width, ar_height = ar_height, ar_width
total_pixels = int(megapixels * 1_000_000)
width = int((total_pixels * ar_width / ar_height) ** 0.5)
height = int(total_pixels / width)
# Round to nearest multiple of 64
width = (width + 32) // 64 * 64
height = (height + 32) // 64 * 64
return width, height
if width == 0 or height == 0:
width, height = adjust_dimensions(
megapixel_scale, aspect_ratio, is_portrait
)
else:
# If width and height are provided, adjust them to fit within the megapixel scale
current_mp = (width * height) / 1_000_000
if current_mp > megapixel_scale:
scale_factor = (megapixel_scale / current_mp) ** 0.5
width = int((width * scale_factor + 32) // 64 * 64)
height = int((height * scale_factor + 32) // 64 * 64)
# Swap width and height if portrait is selected and current orientation doesn't match
if is_portrait and width > height:
width, height = height, width
elif not is_portrait and height > width:
width, height = height, width
latent = (
torch.ones([batch_size, 16, height // 8, width // 8], device=self.device)
* 0.0609
)
return ({"samples": latent}, width, height)
class GPT4VisionNode:
def __init__(self):
self.client = OpenAI(api_key=os.environ.get("OPENAI_API_KEY"))
self.prompts_dir = "./custom_nodes/comfyui_dagthomas/prompts"
os.makedirs(self.prompts_dir, exist_ok=True)
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"images": ("IMAGE",),
"happy_talk": ("BOOLEAN", {"default": True}),
"compress": ("BOOLEAN", {"default": False}),
"compression_level": (["soft", "medium", "hard"],),
"poster": ("BOOLEAN", {"default": False}),
},
"optional": {
"custom_base_prompt": ("STRING", {"multiline": True, "default": ""}),
"custom_title": ("STRING", {"default": ""}),
"override": (
"STRING",
{"multiline": True, "default": ""},
), # New override field
},
}
RETURN_TYPES = ("STRING",)
FUNCTION = "analyze_images"
CATEGORY = CUSTOM_CATEGORY
def encode_image(self, image):
buffered = BytesIO()
image.save(buffered, format="PNG")
return base64.b64encode(buffered.getvalue()).decode("utf-8")
def tensor_to_pil(self, img_tensor):
i = 255.0 * img_tensor.cpu().numpy()
img_array = np.clip(i, 0, 255).astype(np.uint8)
return Image.fromarray(img_array)
def save_prompt(self, prompt):
filename_text = "vision_" + prompt.split(",")[0].strip()
filename_text = re.sub(r"[^\w\-_\. ]", "_", filename_text)
filename_text = filename_text[:30]
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
base_filename = f"{filename_text}_{timestamp}.txt"
filename = os.path.join(self.prompts_dir, base_filename)
with open(filename, "w") as file:
file.write(prompt)
print(f"Prompt saved to {filename}")
def analyze_images(
self,
images,
happy_talk,
compress,
compression_level,
poster,
custom_base_prompt="",
custom_title="",
override="",
):
try:
default_happy_prompt = """Analyze the provided images and create a detailed visually descriptive caption that combines elements from all images into a single cohesive composition.Imagine all images being movie stills from real movies. This caption will be used as a prompt for a text-to-image AI system. Focus on:
1. Detailed visual descriptions of characters, including ethnicity, skin tone, expressions, etc.
2. Overall scene and background details.
3. Image style, photographic techniques, direction of photo taken.
4. Cinematography aspects with technical details.
5. If multiple characters are present, describe an interesting interaction between two primary characters.
6. Incorporate a specific movie director's visual style (e.g., Wes Anderson, Christopher Nolan, Quentin Tarantino).
7. Describe the lighting setup in detail, including type, color, and placement of light sources.
If you want to add text, state the font, style and where it should be placed, a sign, a poster, etc. The text should be captioned like this " ".
Always describn how characters look at each other, their expressions, and the overall mood of the scene.
Examples of prompts to generate:
1. Ethereal cyborg woman, bioluminescent jellyfish headdress. Steampunk goggles blend with translucent tentacles. Cracked porcelain skin meets iridescent scales. Mechanical implants and delicate tendrils intertwine. Human features with otherworldly glow. Dreamy aquatic hues contrast weathered metal. Reflective eyes capture unseen worlds. Soft bioluminescence meets harsh desert backdrop. Fusion of organic and synthetic, ancient and futuristic. Hyper-detailed textures, surreal atmosphere.
2. Photo of a broken ruined cyborg girl in a landfill, robot, body is broken with scares and holes,half the face is android,laying on the ground, creating a hyperpunk scene with desaturated dark red and blue details, colorful polaroid with vibrant colors, (vacations, high resolution:1.3), (small, selective focus, european film:1.2)
3. Horror-themed (extreme close shot of eyes :1.3) of nordic woman, (war face paint:1.2), mohawk blonde haircut wit thin braids, runes tattoos, sweat, (detailed dirty skin:1.3) shiny, (epic battleground backgroun :1.2), . analog, haze, ( lens blur :1.3) , hard light, sharp focus on eyes, low saturation
ALWAYS remember to out that it is a cinematic movie still and describe the film grain, color grading, and any artifacts or characteristics specific to film photography.
ALWAYS create the output as one scene, never transition between scenes.
"""
default_simple_prompt = """Analyze the provided images and create a brief, straightforward caption that combines key elements from all images. Focus on the main subjects, overall scene, and atmosphere. Provide a clear and concise description in one or two sentences, suitable for a text-to-image AI system."""
poster_prompt = f"""Analyze the provided images and extract key information to create a cinamtic movie poster style description. Format the output as follows:
Title: {"Use the title '" + custom_title + "'" if poster and custom_title else "A catchy, intriguing title that captures the essence of the scene"}, place the title in "".
Main character: Give a description of the main character.
Background: Describe the background in detail.
Supporting characters: Describe the supporting characters
Branding type: Describe the branding type
Tagline: Include a tagline that captures the essence of the movie.
Visual style: Ensure that the visual style fits the branding type and tagline.
You are allowed to make up film and branding names, and do them like 80's, 90's or modern movie posters.
Here is an example of a prompt:
Title: Display the title "Verdant Spirits" in elegant and ethereal text, placed centrally at the top of the poster.
Main Character: Depict a serene and enchantingly beautiful woman with an aura of nature, her face partly adorned and encased with vibrant green foliage and delicate floral arrangements. She exudes an ethereal and mystical presence.
Background: The background should feature a dreamlike enchanted forest with lush greenery, vibrant flowers, and an ethereal glow emanating from the foliage. The scene should feel magical and otherworldly, suggesting a hidden world within nature.
Supporting Characters: Add an enigmatic skeletal figure entwined with glowing, bioluminescent leaves and plants, subtly blending with the dark, verdant background. This figure should evoke a sense of ancient wisdom and mysterious energy.
Studio Ghibli Branding: Incorporate the Studio Ghibli logo at the bottom center of the poster to establish it as an official Ghibli film.
Tagline: Include a tagline that reads: "Where Nature's Secrets Come to Life" prominently on the poster.
Visual Style: Ensure the overall visual style is consistent with Studio Ghibli s signature look rich, detailed backgrounds, and characters imbued with a touch of whimsy and mystery. The colors should be lush and inviting, with an emphasis on the enchanting and mystical aspects of nature."""
if poster:
base_prompt = poster_prompt
elif custom_base_prompt.strip():
base_prompt = custom_base_prompt
else:
base_prompt = (
default_happy_prompt if happy_talk else default_simple_prompt
)
if compress and not poster:
compression_chars = {
"soft": 600 if happy_talk else 300,
"medium": 400 if happy_talk else 200,
"hard": 200 if happy_talk else 100,
}
char_limit = compression_chars[compression_level]
base_prompt += f" Compress the output to be concise while retaining key visual details. MAX OUTPUT SIZE no more than {char_limit} characters."
# Add the override at the beginning of the prompt
final_prompt = f"{override}\n\n{base_prompt}" if override else base_prompt
messages = [
{"role": "user", "content": [{"type": "text", "text": final_prompt}]}
]
# Process each image in the batch
for img_tensor in images:
pil_image = self.tensor_to_pil(img_tensor)
base64_image = self.encode_image(pil_image)
messages[0]["content"].append(
{
"type": "image_url",
"image_url": {"url": f"data:image/png;base64,{base64_image}"},
}
)
response = self.client.chat.completions.create(
model="gpt-4o", messages=messages
)
self.save_prompt(response.choices[0].message.content)
return (response.choices[0].message.content,)
except Exception as e:
print(f"An error occurred: {e}")
print(f"Images tensor shape: {images.shape}")
print(f"Images tensor type: {images.dtype}")
return (f"Error occurred while processing the request: {str(e)}",)
class GeminiTextOnly:
def __init__(self):
self.gemini_api_key = os.environ.get("GEMINI_API_KEY")
if not self.gemini_api_key:
raise ValueError("GEMINI_API_KEY environment variable is not set")
genai.configure(api_key=self.gemini_api_key)
self.prompts_dir = "./custom_nodes/comfyui_dagthomas/prompts"
os.makedirs(self.prompts_dir, exist_ok=True)
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"custom_prompt": ("STRING", {"multiline": True, "default": ""}),
"additive_prompt": ("STRING", {"multiline": True, "default": ""}),
"dynamic_prompt": ("BOOLEAN", {"default": False}),
"tag": ("STRING", {"default": "ohwx man"}),
"sex": ("STRING", {"default": "male"}),
"words": ("STRING", {"default": "100"}),
"pronouns": ("STRING", {"default": "him, his"}),
"gemini_model": (gemini_models,),
}
}
RETURN_TYPES = ("STRING", "STRING")
RETURN_NAMES = ("output", "clip_l")
FUNCTION = "process_text"
CATEGORY = "dagthomas"
def extract_first_two_sentences(self, text):
sentences = re.split(r"(?<=[.!?])\s+", text)
return " ".join(sentences[:2])
def save_prompt(self, prompt):
filename_text = "gemini_text_only_" + "".join(
c if c.isalnum() or c in "-_" else "_" for c in prompt[:30]
)
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
base_filename = f"{filename_text}_{timestamp}.txt"
filename = os.path.join(self.prompts_dir, base_filename)
try:
with open(filename, "w", encoding="utf-8") as file:
file.write(prompt)
print(f"Prompt saved to {filename}")
except Exception as e:
print(f"Error saving prompt: {e}")
def process_text(
self,
custom_prompt="",
additive_prompt="",
tag="ohwx man",
sex="male",
pronouns="him, his",
dynamic_prompt=False,
words="100",
gemini_model="gemini-2.0-flash-exp",
):
try:
if not dynamic_prompt:
full_prompt = custom_prompt if custom_prompt else "Generate a response."
else:
custom_prompt = custom_prompt.replace("##TAG##", tag.lower())
custom_prompt = custom_prompt.replace("##SEX##", sex)
custom_prompt = custom_prompt.replace("##PRONOUNS##", pronouns)
custom_prompt = custom_prompt.replace("##WORDS##", words)
full_prompt = f"{additive_prompt} {custom_prompt}".strip() if additive_prompt else custom_prompt
safety_settings = [
{
"category": "HARM_CATEGORY_HARASSMENT",
"threshold": "BLOCK_NONE",
},
{
"category": "HARM_CATEGORY_HATE_SPEECH",
"threshold": "BLOCK_NONE",
},
{
"category": "HARM_CATEGORY_SEXUALLY_EXPLICIT",
"threshold": "BLOCK_NONE",
},
{
"category": "HARM_CATEGORY_DANGEROUS_CONTENT",
"threshold": "BLOCK_NONE",
},
]
model = genai.GenerativeModel(gemini_model, safety_settings=safety_settings)
response = model.generate_content(full_prompt)
result = response.text
self.save_prompt(result)
return (
result,
self.extract_first_two_sentences(result),
)
except Exception as e:
print(f"An error occurred: {e}")
error_message = f"Error occurred while processing the request: {str(e)}"
return (error_message, error_message[:100])
class Gpt4VisionCloner:
def __init__(self):
self.client = OpenAI(api_key=os.environ.get("OPENAI_API_KEY"))
self.prompts_dir = "./custom_nodes/comfyui_dagthomas/prompts"
os.makedirs(self.prompts_dir, exist_ok=True)
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"images": ("IMAGE",),
"fade_percentage": (
"FLOAT",
{"default": 15.0, "min": 0.1, "max": 50.0, "step": 0.1},
),
},
"optional": {
"custom_prompt": ("STRING", {"multiline": True, "default": ""})
},
}
RETURN_TYPES = (
"STRING",
"STRING",
"IMAGE",
)
RETURN_NAMES = (
"formatted_output",
"raw_json",
"faded_image",
)
FUNCTION = "analyze_images"
CATEGORY = CUSTOM_CATEGORY
@staticmethod
def tensor2pil(image):
return Image.fromarray(
np.clip(255.0 * image.cpu().numpy().squeeze(), 0, 255).astype(np.uint8)
)
@staticmethod
def pil2tensor(image):
return torch.from_numpy(np.array(image).astype(np.float32) / 255.0).unsqueeze(0)
def fade_images(self, images, fade_percentage=15.0):
if len(images) < 2:
return images[0] if images else None
# Determine orientation based on aspect ratio
aspect_ratio = images[0].width / images[0].height
vertical_stack = aspect_ratio > 1
if vertical_stack:
# Vertical stacking for wider images
fade_height = int(images[0].height * (fade_percentage / 100))
total_height = sum(img.height for img in images) - fade_height * (
len(images) - 1
)
max_width = max(img.width for img in images)
combined_image = Image.new("RGB", (max_width, total_height))
y_offset = 0
for i, img in enumerate(images):
if i == 0:
combined_image.paste(img, (0, 0))
y_offset = img.height - fade_height
else:
for y in range(fade_height):
factor = y / fade_height
for x in range(max_width):
if x < images[i - 1].width and x < img.width:
pixel1 = images[i - 1].getpixel(
(x, images[i - 1].height - fade_height + y)
)
pixel2 = img.getpixel((x, y))
blended_pixel = tuple(
int(pixel1[c] * (1 - factor) + pixel2[c] * factor)
for c in range(3)
)
combined_image.putpixel(
(x, y_offset + y), blended_pixel
)
combined_image.paste(
img.crop((0, fade_height, img.width, img.height)),
(0, y_offset + fade_height),
)
y_offset += img.height - fade_height
else:
# Horizontal stacking for taller images
fade_width = int(images[0].width * (fade_percentage / 100))
total_width = sum(img.width for img in images) - fade_width * (
len(images) - 1
)
max_height = max(img.height for img in images)
combined_image = Image.new("RGB", (total_width, max_height))
x_offset = 0
for i, img in enumerate(images):
if i == 0:
combined_image.paste(img, (0, 0))
x_offset = img.width - fade_width
else:
for x in range(fade_width):
factor = x / fade_width
for y in range(max_height):
if y < images[i - 1].height and y < img.height:
pixel1 = images[i - 1].getpixel(
(images[i - 1].width - fade_width + x, y)
)
pixel2 = img.getpixel((x, y))
blended_pixel = tuple(
int(pixel1[c] * (1 - factor) + pixel2[c] * factor)
for c in range(3)
)
combined_image.putpixel(
(x_offset + x, y), blended_pixel
)
combined_image.paste(
img.crop((fade_width, 0, img.width, img.height)),
(x_offset + fade_width, 0),
)
x_offset += img.width - fade_width
return combined_image
def encode_image(self, image):
buffered = io.BytesIO()
image.save(buffered, format="PNG")
return base64.b64encode(buffered.getvalue()).decode("utf-8")
def save_prompt(self, prompt):
filename_text = "vision_json_" + "".join(
c if c.isalnum() or c in "-_" else "_" for c in prompt[:30]
)
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
base_filename = f"{filename_text}_{timestamp}.txt"
filename = os.path.join(self.prompts_dir, base_filename)
try:
with open(filename, "w", encoding="utf-8") as file:
file.write(prompt)
print(f"Prompt saved to {filename}")
except Exception as e:
print(f"Error saving prompt: {e}")
def format_element(self, element):
element_type = element.get("Type", "")
description = element.get("Description", "").lower()
attributes = element.get("Attributes", {})
if element_type.lower() == "object":
formatted = description
else:
formatted = f"{element_type} {description}"
attr_details = []
for key, value in attributes.items():
if value and value.lower() not in ["n/a", "none", "None"]:
attr_details.append(f"{key.lower()}: {value.lower()}")
if attr_details:
formatted += f" ({', '.join(attr_details)})"
return formatted
def extract_data(self, data):
extracted = []
extracted.append(data.get("Title", ""))
extracted.append(data.get("Artistic Style", ""))
color_scheme = data.get("Color Scheme", [])
if color_scheme:
extracted.append(
f"palette ({', '.join(color.lower() for color in color_scheme)})"
)
for element in data.get("Elements", []):
extracted.append(self.format_element(element))
overall_scene = data.get("Overall Scene", {})
extracted.append(overall_scene.get("Theme", ""))
extracted.append(overall_scene.get("Setting", ""))
extracted.append(overall_scene.get("Lighting", ""))
return ", ".join(item for item in extracted if item)
def analyze_images(self, images, fade_percentage=15.0, custom_prompt=""):
try:
default_prompt = """Analyze the provided image and generate a JSON object with the following structure:
{
"title": [A descriptive title for the image],
"color_scheme": [Array of dominant colors, including notes on significant contrasts or mood-setting choices],
"elements": [
{
"type": [Either "character" or "object"],
"description": [Brief description of the element],
"attributes": {
[Relevant attributes like clothing, accessories, position, location, category, etc.]
}
},
... [Additional elements]
],
"overall_scene": {
"theme": [Overall theme of the image],
"setting": [Where the scene takes place and how it contributes to the narrative],
"lighting": {
"type": [Type of lighting, e.g. natural, artificial, magical],
"direction": [Direction of the main light source],
"quality": [Quality of light, e.g. soft, harsh, diffused],
"effects": [Any special lighting effects or atmosphere created]
},
"mood": [The emotional tone or atmosphere conveyed],
"camera_angle": {
"perspective": [e.g. eye-level, low angle, high angle, bird's eye view],
"focus": [What the camera is focused on],
"depth_of_field": [Describe if all elements are in focus or if there's a specific focal point]
}
},
"artistic_choices": [Array of notable artistic decisions that contribute to the image's impact],
"text_elements": [
{
"content": [The text content],
"placement": [Description of where the text is placed in the image],
"style": [Description of the text style, font, color, etc.],
"purpose": [The role or purpose of the text in the overall composition]
},
... [Additional text elements]
]
}
ALWAYS blend concepts into one concept if there are multiple images. Ensure that all aspects of the image are thoroughly analyzed and accurately represented in the JSON output, including the camera angle, lighting details, and any significant distant objects or background elements. Provide the JSON output without any additional explanation or commentary."""
final_prompt = custom_prompt if custom_prompt.strip() else default_prompt
messages = [
{"role": "user", "content": [{"type": "text", "text": final_prompt}]}
]
# Handle single image or multiple images
if len(images.shape) == 3: # Single image
pil_images = [self.tensor2pil(images)]
else: # Multiple images
pil_images = [self.tensor2pil(img) for img in images]
combined_image = self.fade_images(pil_images, fade_percentage)
base64_image = self.encode_image(combined_image)
messages[0]["content"].append(
{
"type": "image_url",
"image_url": {"url": f"data:image/png;base64,{base64_image}"},
}
)
response = self.client.chat.completions.create(
model="gpt-4o", messages=messages
)
content = response.choices[0].message.content
# print(content)