-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathtext_to_image_node.py
More file actions
3712 lines (3245 loc) · 159 KB
/
text_to_image_node.py
File metadata and controls
3712 lines (3245 loc) · 159 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Text-to-Image Prompt Enhancer Node
Advanced multi-platform prompt enhancement for image generation
Supports: SDXL, Pony, Illustrious, Flux, Chroma, Qwen-Image, Qwen-Edit, Wan-Image
"""
import torch
import numpy as np
from PIL import Image
import io
import random
import re
from typing import Tuple, Optional, Dict, List, Any, Union
from .llm_backend import LLMBackend
from .qwen3_vl_backend import caption_with_qwen3_vl
from .platforms import get_platform_config, get_negative_prompt_for_platform
from .utils import save_prompts_to_file, parse_keywords
class TextToImagePromptEnhancer:
"""
Advanced text-to-image prompt enhancement with platform-specific optimization
Features:
- Multiple platform support with tailored prompting
- Optional image reference input (1-2 images)
- Advanced aesthetic controls (lighting, camera, time of day, etc.)
- Wildcard random options
- Platform-specific formatting and token optimization
"""
def __init__(self):
self.type = "text_to_image_enhancement"
self.output_dir = "output/txt2img_prompts"
# Wildcard options
self.camera_angles = [
"eye level", "low angle", "high angle", "dutch angle", "bird's eye view",
"worm's eye view", "over the shoulder", "point of view", "extreme close-up angle"
]
self.lighting_sources = [
"natural sunlight", "studio lighting", "golden hour sun", "moonlight",
"candlelight", "neon lights", "firelight", "spotlight", "ambient lighting",
"backlight", "rim lighting", "window light", "street lights"
]
self.lighting_quality = [
"soft diffused", "hard dramatic", "even balanced", "high contrast",
"low key", "high key", "chiaroscuro", "volumetric", "atmospheric"
]
self.times_of_day = [
"dawn", "early morning", "mid-morning", "noon", "afternoon",
"golden hour", "dusk", "twilight", "night", "midnight", "blue hour"
]
self.weather_conditions = [
"clear sky", "partly cloudy", "overcast", "misty", "foggy",
"rainy", "stormy", "snowy", "sunny", "hazy"
]
self.composition_styles = [
"rule of thirds", "centered", "symmetrical", "asymmetrical",
"golden ratio", "leading lines", "frame within frame", "negative space",
"balanced", "dynamic diagonal"
]
self.genre_styles = [
"surreal", "cinematic", "dramatic", "action", "humorous",
"indie", "horror", "scifi", "romantic", "artistic",
"documentary", "minimalist", "maximalist", "vintage", "modern",
"fantasy", "noir", "cyberpunk", "steampunk", "dieselpunk",
"mythic", "gothic", "art deco", "retro futurism"
]
self.historical_periods = [
"prehistoric era", "ancient civilizations", "classical antiquity",
"medieval era", "renaissance", "baroque period", "industrial revolution",
"victorian era", "edwardian era", "roaring twenties", "mid-century modern",
"1960s counterculture", "1980s neon wave", "1990s digital dawn",
"modern day", "near future", "far future", "cyberpunk future",
"post-apocalyptic era", "fantasy realm", "science fiction epoch"
]
self.subject_framings = [
"extreme close-up", "close-up", "medium close-up",
"medium shot", "medium wide", "wide shot",
"full body", "cowboy shot", "bust shot",
"head and shoulders", "three-quarter", "establishing shot",
"aerial overview", "profile view"
]
self.subject_poses = [
"standing", "sitting", "lying down", "kneeling", "crouching",
"action pose", "portrait pose", "dynamic", "static",
"asymmetric", "contrapposto", "relaxed", "tense",
"walking", "running", "jumping", "dancing", "floating"
]
self.creative_randomness_modes = {
"off": "Stay close to user wording with minimal embellishment.",
"subtle": "Add gentle flourishes that enhance mood without changing subject focus.",
"moderate": "Introduce fresh context, supporting details, or small narrative beats.",
"bold": "Transform the prompt into a vivid scene with new narrative hooks and world-building.",
"storyteller": "Invent an imaginative mini-story or scenario that surprises while honoring the subject.",
"chaotic": "Push boundaries with experimental, dreamlike, or surreal twists."
}
self.random_story_settings = [
"abandoned futuristic metropolis", "misty forest crossroads",
"luminous underwater research lab", "quiet suburban street at dawn",
"ancient floating temple", "deserted lunar colony", "ornate victorian ballroom",
"hidden speakeasy behind a bookstore", "glitching neon arcade",
"forgotten museum of impossible inventions", "bioluminescent cavern",
"storm-lashed airship deck", "sunset-drenched mountain pass",
"labyrinthine library of living books", "gravity-defying market square"
]
self.random_story_companions = [
"a time-traveling archivist", "an eccentric inventor", "a sentient automaton",
"a mysterious stranger in vintage attire", "a playful cosmic entity",
"a band of skyship pirates", "a chorus of bioluminescent sprites",
"a rival artist seeking inspiration", "a loyal cybernetic fox",
"an undercover interstellar diplomat"
]
self.random_story_conflicts = [
"searching for the last fragment of a lost melody",
"racing against an impending temporal storm",
"unlocking a doorway hidden inside a beam of light",
"negotiating peace between rival realities",
"decoding whispers carried by the rain",
"restoring color to a world frozen in monochrome",
"solving a puzzle etched into the constellations",
"protecting a fragile artifact of collective memories"
]
self.reference_usage_labels = {
"caption": "scene overview",
"style": "artistic style and texture",
"lighting": "lighting qualities and direction",
"genre": "genre or mood cues",
"time_period": "time period context",
"subject": "primary subject appearance",
"objects": "notable secondary objects",
"color": "color palette or grading",
"composition": "framing and spatial layout"
}
self.reference_directive_choices = [
"none",
"auto",
"recreate",
"reinterpret",
"subject only",
"style only",
"lighting only",
"composition",
"genre"
]
self._seed_state: Dict[str, Any] = {
"last_seed": None,
"last_mode": None,
"last_input": None
}
self.reference_directive_configs = {
"none": {
"display": "None",
"user_guidance": "Use this reference for broad inspiration using its full caption.",
"user_summary": "Incorporate helpful elements from the reference caption without enforcing a specific focus.",
"include_categories": ["caption"],
"exclude_categories": [],
"llm_instruction": (
"Absorb the entire reference caption as general inspiration. Keep the meaningful traits but avoid over-emphasizing any single element."
),
"analysis_focus": (
"Summarize the overall subject, setting, lighting, mood, and notable items so the prompt can mirror the scene holistically."
)
},
"auto": {
"display": "Auto",
"user_guidance": "Adapt helpful traits from the reference based on context.",
"user_summary": "Auto-balances useful cues from the reference.",
"include_categories": [
"caption",
"style",
"lighting",
"color",
"genre",
"composition",
"subject",
"objects",
"time_period"
],
"exclude_categories": [],
"llm_instruction": (
"Absorb the full caption from this reference to strengthen the user's brief. "
"Borrow cues that align with the goal and adjust anything that conflicts."
),
"analysis_focus": (
"Identify the most influential subject, style, lighting, composition, and supporting details from the"
" complete caption that will benefit the final prompt."
)
},
"recreate": {
"display": "Recreate",
"user_guidance": "Match the reference closely across subject, palette, lighting, and mood.",
"user_summary": "Recreate the reference look as faithfully as possible.",
"include_categories": "all",
"exclude_categories": [],
"llm_instruction": (
"Reproduce this reference almost verbatim. Maintain subject identity, palette, lighting, composition, "
"and supporting props unless the main prompt explicitly overrides them."
),
"analysis_focus": (
"List the critical traits that must be preserved exactly: subject identity, pose, palette, lighting,"
" composition, and key props or environment cues."
)
},
"reinterpret": {
"display": "Reinterpret",
"user_guidance": "Use the reference as inspiration; preserve core subject or mood, but embrace smart variations.",
"user_summary": "Keep the spirit of the reference while allowing tasteful changes.",
"include_categories": [
"caption",
"subject",
"objects",
"genre",
"style",
"lighting",
"color",
"composition",
"time_period"
],
"exclude_categories": [],
"llm_instruction": (
"Preserve the recognizable subject or atmosphere from this reference using the full caption as context, yet "
"refresh style, palette, or composition when it improves alignment with the user's prompt."
),
"analysis_focus": (
"Summarize the anchor traits (subject identity, mood, palette cues) drawn from the entire caption while"
" noting which aspects feel flexible for reinterpretation."
)
},
"subject_only": {
"display": "Subject Only",
"user_guidance": "Preserve the subject’s identity, pose, and defining traits; let other elements follow the prompt.",
"user_summary": "Keep subject fidelity; redesign other aspects.",
"include_categories": ["caption", "subject", "objects", "composition"],
"exclude_categories": ["style", "lighting", "color", "genre"],
"llm_instruction": (
"Carry over the subject's identity, pose, and silhouette from this reference using the full caption as context. "
"Invent fresh style, lighting, and background details to suit the user's prompt."
),
"analysis_focus": (
"Describe the subject's appearance, pose, silhouette, distinguishing features, and supportive forms as captured"
" in the caption so the identity remains unmistakable."
)
},
"style_only": {
"display": "Style Only",
"user_guidance": "Borrow the artistic style, texture, palette, and brushwork; ignore subject and composition cues.",
"user_summary": "Transfer the reference style while changing subject matter.",
"include_categories": ["caption", "style", "color", "genre", "lighting"],
"exclude_categories": ["subject", "objects", "composition"],
"llm_instruction": (
"Adopt the artistic style, texture, and palette suggested by this reference after studying the complete caption. "
"Replace its subject and layout with the user's requested scene."
),
"analysis_focus": (
"Detail the artistic medium, techniques, palette tendencies, brushwork, texture, and stylistic motifs present"
" in the caption so the style can be transferred accurately."
)
},
"lighting_only": {
"display": "Lighting Only",
"user_guidance": "Replicate lighting qualities like direction, intensity, and warmth; disregard subject or style cues.",
"user_summary": "Reuse lighting mood without copying subject matter.",
"include_categories": ["caption", "lighting", "color"],
"exclude_categories": ["subject", "objects", "style", "genre", "composition"],
"llm_instruction": (
"Match the lighting direction, intensity, and warmth suggested by this reference while treating the full caption as context. "
"Do not replicate its subject, style, or composition."
),
"analysis_focus": (
"Explain the lighting direction, intensity, quality, shadow behavior, and color temperature found in the caption"
" so the mood can be recreated without losing context."
)
},
"composition": {
"display": "Composition",
"user_guidance": "Adopt the camera angle, framing, and spatial layout; let subject and style come from the prompt.",
"user_summary": "Mirror the reference framing while refreshing other traits.",
"include_categories": ["composition", "caption", "objects"],
"exclude_categories": ["style", "lighting", "color", "genre"],
"llm_instruction": (
"Borrow the framing, camera angle, and spatial relationships implied by this reference using the caption as your map. "
"Populate that layout with the subjects and styling requested in the prompt."
),
"analysis_focus": (
"Describe the camera angle, focal length impression, framing, depth relationships, and placement of key elements"
" from the caption so the layout can be preserved."
)
},
"genre": {
"display": "Genre",
"user_guidance": "Match the genre or storytelling conventions; let other specifics follow the prompt unless genre demands otherwise.",
"user_summary": "Carry over the reference genre atmosphere.",
"include_categories": ["caption", "genre", "style", "color", "lighting"],
"exclude_categories": ["subject", "objects", "composition"],
"llm_instruction": (
"Preserve the genre tone and storytelling conventions from this reference by internalizing the whole caption. "
"Let the user's prompt determine subject matter and layout unless genre cues require tweaks."
),
"analysis_focus": (
"Summarize the genre-defining mood, atmosphere, storytelling motifs, and stylistic cues from the full caption"
" so the tone carries over cleanly."
)
}
}
self.default_reference_analysis_method = "sequential_refine"
self.reference_guardrail_text = (
"Blend reference guidance without repeating yourself. Do not mention source image dimensions, aspect ratios, "
"or pixel resolutions under any circumstance."
)
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
# Core inputs
"text_prompt": ("STRING", {
"multiline": True,
"default": "a beautiful woman in a garden",
"placeholder": "Describe the image you want to generate\n\n"
"Supports:\n"
"- Emphasis: (keyword:1.5) to increase weight\n"
"- De-emphasis: (keyword:0.5) to decrease weight\n"
"- Alternation: {apple|banana|orange} picks one randomly\n"
"- Nested: {red|blue|green} (dress:1.2) works too"
}),
"reference_directive_1": ([
"none",
"auto",
"recreate",
"reinterpret",
"subject only",
"style only",
"lighting only",
"composition",
"genre"
], {
"default": "none"
}),
"reference_directive_2": ([
"none",
"auto",
"recreate",
"reinterpret",
"subject only",
"style only",
"lighting only",
"composition",
"genre"
], {
"default": "none"
}),
"prompt_context": ([
"none",
"auto",
"expand_short_prompt",
"finish_opening_line",
"prompt_from_item_list",
"modify_reference_image",
"enhance_reference_image"
], {
"default": "none",
"tooltip": (
"none/auto: Standard prompt\n"
"expand_short_prompt: Expand shorthand into full description\n"
"finish_opening_line: Continue from your opening line\n"
"prompt_from_item_list: Transform comma-separated elements into scene\n"
"modify_reference_image: Alter specific parts of reference\n"
"enhance_reference_image: Enrich reference with new elements"
)
}),
"creative_randomness": ([
"auto", "none", "off", "subtle", "moderate", "bold", "storyteller", "chaotic"
], {
"default": "none",
"tooltip": (
"off/none: Minimal embellishment\n"
"subtle: Gentle mood enhancement\n"
"moderate: Add supporting details\n"
"bold: Vivid scene with narrative hooks\n"
"storyteller: Imaginative mini-story\n"
"chaotic: Experimental, surreal twists"
)
}),
# Platform selection
"target_platform": ([
"flux",
"flux_kontex",
"sd_xl",
"sd_1_5",
"pony",
"illustrious",
"chroma",
"pixart_sigma",
"aura_flow",
"noobai",
"kolors",
"qwen_image",
"qwen_image_edit",
"wan_image"
], {
"default": "flux"
}),
# LLM settings
"llm_backend": ([
"lm_studio",
"ollama",
"qwen3_vl"
], {
"default": "lm_studio",
"tooltip": (
"lm_studio: Uses currently loaded model in LM Studio\n"
"ollama: Uses currently loaded model in Ollama\n"
"qwen3_vl: Auto-detects local Qwen3-VL model (no API server needed)"
)
}),
"api_endpoint": ("STRING", {
"default": "http://localhost:1234/v1",
"multiline": False,
"tooltip": (
"lm_studio/ollama: API endpoint URL\n"
"qwen3_vl: Leave default, or specify custom model path like 'A:\\path\\to\\model'"
)
}),
"temperature": ("FLOAT", {
"default": 0.7,
"min": 0.1,
"max": 2.0,
"step": 0.1
}),
"vision_backend": ([
"auto",
"lm_studio",
"ollama",
"qwen3_vl",
"disable"
], {
"default": "auto",
"tooltip": "Vision captioning: auto=inherit from main LLM, qwen3_vl=local Qwen3-VL, lm_studio/ollama=separate vision model, disable=heuristics only"
}),
"vision_api_endpoint": ("STRING", {
"default": "http://localhost:1234/v1",
"multiline": False,
"tooltip": (
"Vision backend API endpoint (lm_studio/ollama) or custom model path (qwen3_vl)\n"
"For qwen3_vl: Leave default for auto-detect, or specify 'A:\\path\\to\\model'"
)
}),
# Camera & Composition
"camera_angle": ([
"auto", "random", "none",
"eye level", "low angle", "high angle", "dutch angle",
"bird's eye view", "worm's eye view", "over the shoulder",
"point of view", "extreme close-up angle"
], {
"default": "none"
}),
"composition": ([
"auto", "random", "none",
"rule of thirds", "centered", "symmetrical", "asymmetrical",
"golden ratio", "leading lines", "frame within frame",
"negative space", "balanced", "dynamic diagonal"
], {
"default": "none"
}),
# Lighting
"lighting_source": ([
"auto", "random", "none",
"natural sunlight", "studio lighting", "golden hour sun",
"moonlight", "candlelight", "neon lights", "firelight",
"spotlight", "ambient lighting", "backlight", "rim lighting",
"window light", "street lights"
], {
"default": "none"
}),
"lighting_quality": ([
"auto", "random", "none",
"soft diffused", "hard dramatic", "even balanced",
"high contrast", "low key", "high key", "chiaroscuro",
"volumetric", "atmospheric"
], {
"default": "none"
}),
# Time & Weather
"time_of_day": ([
"auto", "random", "none",
"dawn", "early morning", "mid-morning", "noon", "afternoon",
"golden hour", "dusk", "twilight", "night", "midnight", "blue hour"
], {
"default": "none"
}),
"historical_period": ([
"auto", "random", "none",
"prehistoric era", "ancient civilizations", "classical antiquity",
"medieval era", "renaissance", "baroque period", "industrial revolution",
"victorian era", "edwardian era", "roaring twenties", "mid-century modern",
"1960s counterculture", "1980s neon wave", "1990s digital dawn",
"modern day", "near future", "far future", "cyberpunk future",
"post-apocalyptic era", "fantasy realm", "science fiction epoch"
], {
"default": "none"
}),
"weather": ([
"auto", "random", "none",
"clear sky", "partly cloudy", "overcast", "misty", "foggy",
"rainy", "stormy", "snowy", "sunny", "hazy"
], {
"default": "none"
}),
# Style & Quality
"art_style": ([
"auto", "none",
"photorealistic", "digital art", "oil painting", "watercolor",
"anime", "manga", "sketch", "pencil drawing", "3D render",
"illustration", "concept art", "impressionist", "abstract",
"pixel art", "low poly", "papercraft", "isometric"
], {
"default": "none"
}),
"genre_style": ([
"auto", "random", "none",
"surreal", "cinematic", "dramatic", "action", "humorous",
"indie", "horror", "scifi", "romantic", "x-rated", "pg",
"artistic", "documentary", "minimalist", "maximalist",
"vintage", "modern", "fantasy", "noir", "cyberpunk",
"steampunk", "dieselpunk", "mythic", "gothic", "art deco", "retro futurism"
], {
"default": "none"
}),
"color_mood": ([
"auto", "random", "none",
"vibrant", "muted", "monochrome", "warm tones", "cool tones",
"pastel", "high contrast", "desaturated", "neon", "earth tones"
], {
"default": "none"
}),
# Subject Controls
"subject_framing": ([
"auto", "random", "none",
"extreme close-up", "close-up", "medium close-up",
"medium shot", "medium wide", "wide shot",
"full body", "cowboy shot", "bust shot",
"head and shoulders", "three-quarter", "establishing shot",
"aerial overview", "profile view"
], {
"default": "none"
}),
"subject_pose": ([
"auto", "random", "none",
"standing", "sitting", "lying down", "kneeling", "crouching",
"action pose", "portrait pose", "dynamic", "static",
"asymmetric", "contrapposto", "relaxed", "tense",
"walking", "running", "jumping", "dancing", "floating"
], {
"default": "none"
}),
# Keywords
"positive_keywords": ("STRING", {
"default": "",
"multiline": True,
"placeholder": "Additional keywords, LoRA triggers, specific details"
}),
"negative_keywords": ("STRING", {
"default": "ugly, blurry, duplicate, deformed, distorted, lowres, bad anatomy, disfigured, poorly drawn, mutation, mutated, extra limbs, cloned face, disfigured, gross proportions, malformed limbs, missing arms, missing legs, fused fingers, too many fingers, long neck",
"multiline": True,
"placeholder": "Things to avoid"
}),
"seed_mode": ([
"random",
"fixed",
"increment",
"decrement"
], {
"default": "random"
}),
"random_seed": ("INT", {
"default": -1,
"min": -1,
"max": 2_147_483_647,
"step": 1
}),
# Output
"save_to_file": ("BOOLEAN", {
"default": False
}),
"filename_base": ("STRING", {
"default": "txt2img_prompt",
"multiline": False
})
},
"optional": {
# Optional image references
"reference_image_1": ("IMAGE",),
"reference_image_2": ("IMAGE",),
"reference_caption_override_1": ("STRING", {
"default": "",
"multiline": True,
"placeholder": "Optional external caption for Reference 1"
}),
"reference_caption_override_2": ("STRING", {
"default": "",
"multiline": True,
"placeholder": "Optional external caption for Reference 2"
}),
}
}
RETURN_TYPES = ("STRING", "STRING", "STRING", "STRING", "STRING", "INT")
RETURN_NAMES = ("positive_prompt", "negative_prompt", "settings_used", "status", "vision_caption", "seed_used")
FUNCTION = "enhance_prompt"
CATEGORY = "Eric Prompt Enhancers"
OUTPUT_NODE = True
@classmethod
def IS_CHANGED(cls, random_seed: int, seed_mode: str, **kwargs):
"""Determine if the node should re-execute based on seed mode.
Returns a unique value for modes that need to re-run each time,
or the seed value for fixed mode (to use ComfyUI's caching).
"""
import time
mode = str(seed_mode).strip().lower()
# For random/increment/decrement, return unique value each time to force re-execution
if mode in {"random", "increment", "decrement"}:
# Return timestamp to guarantee uniqueness
return float(time.time())
# For fixed mode, return the seed value so ComfyUI can cache
try:
seed_value = int(random_seed)
if seed_value < 0:
# Negative seed means random even in fixed mode
return float(time.time())
return seed_value
except Exception:
return float(time.time())
def enhance_prompt(
self,
text_prompt: str,
reference_directive_1: str,
reference_directive_2: str,
prompt_context: str,
target_platform: str,
llm_backend: str,
api_endpoint: str,
temperature: float,
vision_backend: str,
vision_api_endpoint: str,
camera_angle: str,
composition: str,
lighting_source: str,
lighting_quality: str,
time_of_day: str,
historical_period: str,
weather: str,
art_style: str,
genre_style: str,
color_mood: str,
creative_randomness: str,
subject_framing: str,
subject_pose: str,
positive_keywords: str,
negative_keywords: str,
seed_mode: str,
random_seed: int,
save_to_file: bool,
filename_base: str,
reference_image_1: Optional[torch.Tensor] = None,
reference_image_2: Optional[torch.Tensor] = None,
reference_caption_override_1: str = "",
reference_caption_override_2: str = ""
) -> Tuple[str, str, str, str]:
"""Main processing function"""
try:
requested_seed = int(random_seed)
except Exception:
requested_seed = -1
seed_mode_normalized = str(seed_mode).strip().lower()
seed_value, resolved_seed_mode = self._resolve_seed_value(seed_mode_normalized, requested_seed)
python_random_state = random.getstate()
numpy_random_state = np.random.get_state()
random.seed(seed_value)
np.random.seed(seed_value % (2**32))
try:
# STEP 0: Process alternations first (before LLM)
text_prompt = self._process_alternations(text_prompt)
# STEP 0.5: Protect emphasis syntax
text_prompt = self._preserve_emphasis_syntax(text_prompt)
# STEP 1: Process reference images if provided
reference_images = []
directive_inputs = []
override_1 = (reference_caption_override_1 or "").strip()
override_2 = (reference_caption_override_2 or "").strip()
if reference_image_1 is not None:
reference_images.append({
"label": "Reference 1",
"tensor": reference_image_1,
"caption_override": override_1,
"override_source": "user" if override_1 else None
})
directive_inputs.append(("Reference 1", reference_directive_1))
elif override_1:
# Allow caption-only references when external descriptor provided
reference_images.append({
"label": "Reference 1",
"tensor": None,
"caption_override": override_1,
"override_source": "user"
})
directive_inputs.append(("Reference 1", reference_directive_1))
if reference_image_2 is not None:
reference_images.append({
"label": "Reference 2",
"tensor": reference_image_2,
"caption_override": override_2,
"override_source": "user" if override_2 else None
})
directive_inputs.append(("Reference 2", reference_directive_2))
elif override_2:
reference_images.append({
"label": "Reference 2",
"tensor": None,
"caption_override": override_2,
"override_source": "user"
})
directive_inputs.append(("Reference 2", reference_directive_2))
reference_plan = self._prepare_reference_plan(directive_inputs)
# Initialize LLM backend (model_name auto-detected)
llm = LLMBackend(
backend_type=llm_backend,
endpoint=api_endpoint,
model_name=None, # Auto-detect for all backends
temperature=temperature
)
vision_backend_selection = (vision_backend or "inherit").strip().lower()
if not vision_backend_selection:
vision_backend_selection = "auto"
# Vision backend now supports custom endpoint via vision_api_endpoint
vision_llm: Optional[LLMBackend] = None
vision_qwen_config: Optional[Dict[str, Any]] = None
vision_backend_mode = "disabled"
vision_caption_enabled = False
vision_model_used = ""
vision_init_warning: Optional[str] = None
if vision_backend_selection in {"", "auto", "inherit"}:
if llm.supports_images():
vision_llm = llm
vision_backend_mode = "inherit"
vision_caption_enabled = True
vision_model_used = getattr(llm, "model_name", "auto-detected")
else:
vision_backend_mode = "disabled"
elif vision_backend_selection == "disable":
vision_backend_mode = "disabled"
elif vision_backend_selection in {"lm_studio", "ollama"}:
# Use vision-specific endpoint
try:
vision_llm = LLMBackend(
backend_type=vision_backend_selection,
endpoint=vision_api_endpoint,
model_name=None, # Auto-detect
temperature=temperature
)
if vision_llm.supports_images():
vision_backend_mode = vision_backend_selection
vision_caption_enabled = True
vision_model_used = getattr(vision_llm, "model_name", "auto-detected")
else:
vision_backend_mode = "disabled"
vision_init_warning = (
f"Vision backend '{vision_backend_selection}' does not advertise image support."
)
except Exception as exc:
vision_backend_mode = "disabled"
vision_init_warning = (
f"Vision backend init failed ({vision_backend_selection}): {exc}"
)
print(f"[Text-to-Image] ⚠️ Vision backend '{vision_backend_selection}' initialization failed: {exc}")
print(f"[Text-to-Image] → Continuing with text expansion only (no vision captions)")
vision_llm = None
elif vision_backend_selection == "qwen3_vl":
# Use vision_api_endpoint for custom model path
vision_qwen_config = {
"model": None, # Auto-detect from vision_api_endpoint
"backend_hint": vision_api_endpoint if vision_api_endpoint != "http://localhost:1234/v1" else None,
}
vision_backend_mode = "qwen3_vl"
vision_caption_enabled = True
vision_model_used = "Qwen3-VL (auto-detected)"
else:
vision_backend_mode = "disabled"
if not vision_model_used:
vision_model_used = getattr(llm, "model_name", "auto-detected")
analysis_backend_label = vision_backend_mode
if analysis_backend_label == "inherit":
analysis_backend_label = f"inherit:{llm.backend_type}"
if not vision_caption_enabled:
vision_model_used = ""
reference_warnings: List[str] = []
if vision_init_warning:
reference_warnings.append(vision_init_warning)
if reference_images and not vision_caption_enabled:
reference_warnings.append(
"Vision captioning disabled; reference traits rely on heuristic estimates."
)
# Wrap vision processing in try/except to prevent vision failures from breaking text expansion
image_analyses = []
try:
for entry in reference_images:
label = entry.get("label", "Reference")
tensor = entry.get("tensor")
override_caption = entry.get("caption_override")
analysis = self._analyze_reference_image(
tensor,
label,
vision_llm=vision_llm if vision_caption_enabled and vision_llm is not None else None,
override_caption=override_caption,
qwen_config=vision_qwen_config if vision_backend_mode == "qwen3_vl" else None,
vision_temperature=temperature,
vision_backend=analysis_backend_label,
vision_model=vision_model_used
)
if override_caption:
existing_warnings = analysis.setdefault("warnings", [])
override_note = f"{label}: caption supplied by override."
if override_note not in existing_warnings:
existing_warnings.append(override_note)
warnings_from_analysis = analysis.get("warnings") or []
for warning in warnings_from_analysis:
if warning not in reference_warnings:
reference_warnings.append(warning)
image_analyses.append(analysis)
except Exception as vision_exc:
# Vision processing failed - log error but continue with text expansion
error_msg = f"Vision processing failed: {str(vision_exc)}"
print(f"[Text-to-Image] ⚠️ {error_msg}")
reference_warnings.append(error_msg)
# Create fallback analyses if we got partial results
if not image_analyses and reference_images:
for entry in reference_images:
label = entry.get("label", "Reference")
fallback = {
"label": label,
"summary": f"{label}: vision analysis failed, continuing with text expansion",
"details": ["Vision model unavailable"],
"warnings": [error_msg]
}
image_analyses.append(fallback)
# STEP 2: Resolve random/auto options
resolved_settings, setting_sources = self._resolve_settings(
camera_angle, composition, lighting_source, lighting_quality,
time_of_day, historical_period, weather, art_style, genre_style, color_mood,
creative_randomness,
subject_framing, subject_pose, prompt_context,
target_platform
)
# STEP 3: Build enhancement prompt
platform_config = get_platform_config(target_platform)
quality_emphasis = bool(platform_config.get("quality_emphasis", True))
resolved_settings["quality_emphasis"] = "enabled" if quality_emphasis else "disabled"
setting_sources["quality_emphasis"] = {"mode": "platform", "value": resolved_settings["quality_emphasis"]}
# Wrap reference guidance processing to prevent failures from blocking text expansion
reference_guidance = ""
reference_notes = []
reference_meta = {}
try:
directive_analyses, directive_meta = self._run_reference_directive_analysis(
image_analyses,
reference_plan,
llm
)
reference_guidance, reference_notes, guidance_meta = self._build_reference_guidance(
directive_analyses,
reference_plan,
llm,
prompt_context
)
reference_meta = self._merge_reference_metadata(reference_plan, directive_meta, guidance_meta)
except Exception as ref_exc:
# Reference guidance processing failed - log but continue
error_msg = f"Reference guidance generation failed: {str(ref_exc)}"
print(f"[Text-to-Image] ⚠️ {error_msg}")
reference_warnings.append(error_msg)
# Initialize empty reference data
reference_meta = {
"analysis_method": "failed",
"reference_count": len(image_analyses),
"llm_queries": 0,
"llm_successes": 0,
"warnings": [error_msg]
}
# Always update reference_meta with vision info (even if guidance failed)
reference_meta.update(
{
"vision_backend_requested": vision_backend_selection,
"vision_backend_resolved": vision_backend_mode,
"vision_caption_enabled": vision_caption_enabled,
"vision_model_used": vision_model_used,
}
)
if vision_qwen_config:
reference_meta["vision_backend_config"] = vision_qwen_config
if reference_warnings:
reference_meta["warnings"] = reference_warnings
backend_set = sorted(
{
str(analysis.get("vision_backend"))
for analysis in image_analyses
if analysis.get("vision_backend")
}
)
model_set = sorted(
{
str(analysis.get("vision_model"))
for analysis in image_analyses
if analysis.get("vision_model")
}
)
source_set = sorted(
{
str(analysis.get("vision_caption_source"))
for analysis in image_analyses
if analysis.get("vision_caption_source")