-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathprompt_expander_node_advanced.py
More file actions
1077 lines (960 loc) · 42.2 KB
/
prompt_expander_node_advanced.py
File metadata and controls
1077 lines (960 loc) · 42.2 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
"""
Advanced AI Video Prompt Expander Node with Granular Aesthetic Controls
Provides dropdown menus for all Wan 2.2 elements
"""
import os
import re
import random
from typing import Tuple
from .llm_backend import LLMBackend
from .expansion_engine import PromptExpander
from .utils import (
save_prompts_to_file,
parse_keywords,
format_breakdown,
validate_positive_keywords
)
class AIVideoPromptExpanderAdvanced:
"""
Advanced ComfyUI node with granular control over all Wan 2.2 aesthetic elements
"""
def __init__(self):
self.expander = PromptExpander()
self.type = "prompt_expansion_advanced"
self.output_dir = "output/video_prompts"
self._emphasis_store = [] # Store for emphasis syntax preservation
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
# Core inputs
"basic_prompt": ("STRING", {
"multiline": True,
"default": "A cat playing piano in a cozy room",
"tooltip": "Enter your prompt. Supports emphasis (keyword:1.5) and alternations {opt1|opt2}"
}),
# NEW: Operation mode
"operation_mode": ([
"expand_from_idea",
"refine_existing",
"modify_style",
"add_details"
], {
"default": "expand_from_idea",
"tooltip": (
"expand_from_idea: Take a short concept and expand it fully\n"
"refine_existing: Polish and improve an existing prompt\n"
"modify_style: Change the style/aesthetic of existing prompt\n"
"add_details: Add more descriptive details to existing prompt"
)
}),
"preset": ([
"custom",
"cinematic",
"surreal",
"action",
"stylized",
"noir",
"random"
], {
"default": "cinematic"
}),
"detail_level": ([
"concise", # ~150-200 words
"moderate", # ~250-350 words
"detailed", # ~400-500 words
"exhaustive" # ~600-1000 words
], {
"default": "detailed",
"tooltip": (
"concise: Brief, essential details only\n"
"moderate: Good balance of detail\n"
"detailed: Rich, comprehensive description\n"
"exhaustive: Maximum detail for cinematic quality"
)
}),
"creativity_mode": ([
"conservative",
"balanced",
"creative",
"highly_creative"
], {
"default": "balanced",
"tooltip": (
"Conservative: Focused, predictable (temp 0.5)\n"
"Balanced: Good variety (temp 0.7)\n"
"Creative: More experimental (temp 0.85)\n"
"Highly Creative: Maximum variety (temp 1.0)"
)
}),
# === REFERENCE IMAGE CONTROLS ===
"reference_mode": ([
"recreate_exact",
"subject_only",
"style_only",
"color_palette_only",
"action_only",
"character_remix",
"reimagine"
], {
"default": "recreate_exact",
"tooltip": (
"recreate_exact: Use image as exact reference for character, costume, and setting\n"
"subject_only: Keep character identity, ignore background and lighting\n"
"style_only: Match aesthetic and mood, create new subject\n"
"color_palette_only: Extract and apply color scheme only\n"
"action_only: Use the pose/action, change everything else\n"
"character_remix: Keep character, place in new scenario\n"
"reimagine: Loosely inspired by image, creative reinterpretation"
)
}),
# === SHOT STRUCTURE CONTROLS ===
"shot_structure": ([
"continuous_paragraph",
"2_shot_structure",
"3_shot_structure",
"4_shot_structure"
], {
"default": "3_shot_structure",
"tooltip": (
"continuous_paragraph: Single flowing description (no shot breaks)\n"
"2_shot_structure: Two distinct shots (Opening + Final Reveal)\n"
"3_shot_structure: Three shots (Setup, Development, Finale) [Recommended]\n"
"4_shot_structure: Four shots (Intro, Build, Climax, Resolution)"
)
}),
# === LIGHTING CONTROLS ===
"light_source": ([
"auto",
"none",
"sunny lighting",
"artificial lighting",
"moonlighting",
"practical lighting",
"firelighting",
"fluorescent lighting",
"overcast lighting",
"mixed lighting",
"ambient lighting",
"reflected lighting",
"softbox lighting",
"camera flash",
"neon lights",
"striplight",
"computer screen glow",
"flashlight",
"candlelight",
"spotlight"
], {
"default": "auto",
"tooltip": "Primary source of illumination in the scene"
}),
"lighting_quality": ([
"auto",
"none",
"soft lighting",
"hard lighting",
"top lighting",
"side lighting",
"edge lighting",
"rim lighting",
"underlighting",
"silhouette lighting",
"backlighting",
"low contrast lighting",
"high contrast lighting",
"spotlight effect",
"dappled lighting",
"cinematic lighting",
"diffused lighting",
"dramatic lighting"
], {
"default": "auto",
"tooltip": "Quality and style of lighting"
}),
"time_of_day": ([
"auto",
"none",
"sunrise time",
"dawn time",
"daylight",
"daytime",
"dusk time",
"sunset time",
"night time"
], {
"default": "auto"
}),
# === CAMERA/SHOT CONTROLS ===
"shot_size": ([
"auto",
"none",
"extreme close-up shot",
"close-up shot",
"medium close-up shot",
"medium shot",
"medium wide shot",
"wide shot",
"extreme wide shot",
"establishing shot"
], {
"default": "auto"
}),
"composition": ([
"auto",
"none",
"center composition",
"balanced composition",
"left-weighted composition",
"right-weighted composition",
"symmetrical composition",
"short-side composition",
"rule of thirds"
], {
"default": "auto"
}),
"lens": ([
"auto",
"none",
"wide-angle lens",
"medium lens",
"long-focus lens",
"telephoto lens",
"fisheye lens"
], {
"default": "auto"
}),
"camera_angle": ([
"auto",
"none",
"eye-level shot",
"high angle shot",
"low angle shot",
"dutch angle shot",
"aerial shot",
"bird's eye view",
"over-the-shoulder shot",
"top-down shot",
"first-person POV",
"profile close-up"
], {
"default": "auto"
}),
"camera_movement": ([
"auto",
"none",
"static shot",
"locked-off shot",
"camera pushes in",
"dolly in",
"camera pulls back",
"dolly out",
"camera pans right",
"camera pans left",
"camera tilts up",
"camera tilts down",
"tracking shot",
"arc shot",
"crane shot",
"camera cranes up",
"camera cranes down",
"handheld camera",
"steadicam",
"compound move",
"whip pan",
"camera orbits around subject",
"smooth glide",
"crash zoom in"
], {
"default": "auto",
"tooltip": "How the camera moves through the scene (Wan 2.2 optimized)"
}),
# === COLOR/STYLE CONTROLS ===
"color_tone": ([
"auto",
"none",
"warm colors",
"cool colors",
"saturated colors",
"desaturated colors",
"monochromatic",
"black and white"
], {
"default": "auto"
}),
"art_style": ([
"auto",
"none",
"Picasso style",
"Van Gogh style",
"Monet style",
"Salvador Dali style",
"Banksy style",
"Andy Warhol style",
"Rembrandt style",
"Caravaggio style",
"Studio Ghibli style",
"Tim Burton style",
"Wes Anderson style",
"Pixar style",
"Norman Rockwell style",
"Edward Hopper style",
"Renaissance style",
"Baroque style",
"Art Nouveau style",
"Expressionist style",
"Impressionist style",
"Surrealist style",
"Cubist style",
"Pop Art style"
], {
"default": "auto",
"tooltip": "Apply the distinctive style of famous artists or art movements"
}),
"scene_detail": ([
"auto",
"none",
"simple scene",
"clean scene",
"detailed scene",
"cluttered scene",
"intricate detail",
"minimalist",
"maximalist"
], {
"default": "auto",
"tooltip": "Level of detail and complexity in the scene composition"
}),
"visual_style": ([
"auto",
"none",
"photorealistic",
"cinematic",
"3D cartoon style",
"2D anime style",
"pixel art style",
"claymation style",
"puppet animation",
"felt style",
"watercolor painting",
"oil painting style",
"pencil sketch",
"comic book style",
"line drawing"
], {
"default": "auto"
}),
"visual_effect": ([
"auto",
"none",
"tilt-shift photography",
"time-lapse",
"slow motion",
"motion blur",
"depth of field",
"bokeh",
"lens flare",
"film grain",
"vignette"
], {
"default": "auto"
}),
# === MOTION/EMOTION CONTROLS ===
"character_emotion": ([
"auto",
"none",
"angry",
"fearful",
"happy",
"sad",
"surprised",
"confused",
"determined",
"thoughtful",
"pensive",
"excited",
"calm",
"anxious"
], {
"default": "auto"
}),
# LLM Configuration
"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 'local:A:\\path\\to\\model'"
)
}),
# Keywords
"positive_keywords": ("STRING", {
"default": "",
"multiline": True,
"placeholder": "lora_trigger, keyword1, keyword2"
}),
"negative_keywords": ("STRING", {
"default": "",
"multiline": True,
"placeholder": "unwanted_term1, unwanted_term2"
}),
# Output options
"num_variations": ("INT", {
"default": 1,
"min": 1,
"max": 3,
"step": 1
}),
"save_to_file": ("BOOLEAN", {
"default": False
}),
"filename_base": ("STRING", {
"default": "video_prompt_advanced",
"multiline": False
})
},
"optional": {
# Optional image/video reference for image-to-video workflows
"reference_image": ("IMAGE", {
"tooltip": "Optional: Provide an image to analyze and incorporate into the prompt using Qwen3-VL"
}),
}
}
RETURN_TYPES = ("STRING", "STRING", "STRING", "STRING", "STRING", "STRING", "STRING")
RETURN_NAMES = (
"positive_prompt_1",
"positive_prompt_2",
"positive_prompt_3",
"negative_prompt",
"breakdown",
"status",
"vision_caption"
)
FUNCTION = "expand_prompt"
CATEGORY = "Eric Prompt Enhancers"
OUTPUT_NODE = True
def expand_prompt(
self,
basic_prompt: str,
operation_mode: str,
preset: str,
detail_level: str,
creativity_mode: str,
reference_mode: str,
shot_structure: str,
light_source: str,
lighting_quality: str,
time_of_day: str,
shot_size: str,
composition: str,
lens: str,
camera_angle: str,
camera_movement: str,
color_tone: str,
art_style: str,
scene_detail: str,
visual_style: str,
visual_effect: str,
character_emotion: str,
llm_backend: str,
api_endpoint: str,
positive_keywords: str,
negative_keywords: str,
num_variations: int,
save_to_file: bool,
filename_base: str,
reference_image=None # Optional image input
) -> Tuple[str, str, str, str, str, str, str]:
"""
Main processing function with aesthetic controls
"""
try:
# Map creativity mode to temperature
temperature_map = {
"conservative": 0.5,
"balanced": 0.7,
"creative": 0.85,
"highly_creative": 1.0
}
temperature = temperature_map.get(creativity_mode, 0.7)
# Process alternations first (before LLM)
basic_prompt = self._process_alternations(basic_prompt)
# Preserve emphasis syntax before LLM processing
basic_prompt = self._preserve_emphasis_syntax(basic_prompt)
# === PASS 1: Vision Analysis (if image provided) ===
vision_caption = ""
mode = "text-to-video" # Default
if reference_image is not None:
try:
print(f"[Advanced Node] PASS 1: Analyzing reference image with Qwen3-VL...")
# Get comprehensive image caption (no mode filtering yet)
vision_caption = self._process_reference_image(reference_image)
if vision_caption:
mode = "image-to-video"
print(f"[Advanced Node] ✓ Vision analysis complete: {len(vision_caption)} chars")
print(f"[Advanced Node] Caption preview: {vision_caption[:200]}...")
else:
print(f"[Advanced Node] ⚠ Vision analysis returned empty - continuing without image context")
except Exception as e:
print(f"[Advanced Node] ⚠ Warning: Could not process image: {e}")
print(f"[Advanced Node] Continuing with text-only mode...")
# Continue without image context - graceful degradation
elif reference_mode != "recreate_exact":
# User set a reference_mode but didn't attach image - warn but continue
print(f"[Advanced Node] ⚠ Warning: reference_mode is '{reference_mode}' but no image attached")
print(f"[Advanced Node] Continuing in text-only mode...")
# Parse keywords
pos_kw_list = parse_keywords(positive_keywords)
neg_kw_list = parse_keywords(negative_keywords)
# Gather aesthetic controls
aesthetic_controls = self._gather_aesthetic_controls(
light_source, lighting_quality, time_of_day,
shot_size, composition, lens, camera_angle,
camera_movement, color_tone, art_style, scene_detail,
visual_style, visual_effect, character_emotion
)
# 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
)
# Test connection
conn_test = llm.test_connection()
if not conn_test["success"]:
error_msg = f"LLM Connection Failed: {conn_test['message']}"
return (
basic_prompt,
"",
"",
"",
f"ERROR: {error_msg}",
f"❌ {error_msg}",
vision_caption if vision_caption else "No image provided"
)
# === PASS 2: Smart LLM Expansion ===
print(f"[Advanced Node] PASS 2: Expanding prompt with LLM...")
# Generate variations
positive_prompts = []
breakdowns = []
for var_num in range(num_variations):
# Build expansion prompts with:
# - User's basic prompt
# - Vision caption (if available)
# - Reference mode instructions (how to apply vision caption)
# - Aesthetic controls
# - Creativity mode
# - Shot structure
system_prompt, user_prompt, breakdown_dict = self.expander.expand_prompt(
basic_prompt=basic_prompt,
preset=preset,
tier=detail_level, # Map detail_level to tier
mode=mode,
positive_keywords=pos_kw_list,
variation_seed=var_num if num_variations > 1 else None,
aesthetic_controls=aesthetic_controls,
shot_structure=shot_structure,
creativity_mode=creativity_mode,
vision_caption=vision_caption, # Pass 1 result
reference_mode=reference_mode # How to apply vision caption
)
# Call LLM with longer max_tokens for detailed output
response = llm.send_prompt(
system_prompt=system_prompt,
user_prompt=user_prompt,
max_tokens=3000 # Increased for more detail
)
if not response["success"]:
error_msg = response["error"]
print(f"[Advanced Node] LLM expansion failed: {error_msg}")
print(f"[Advanced Node] Full response: {response}")
return (
basic_prompt,
"",
"",
"",
f"ERROR: {error_msg}",
f"❌ {error_msg}",
vision_caption if vision_caption else "No image provided"
)
# Parse response
parsed = self.expander.parse_llm_response(response["response"])
enhanced_prompt = parsed["prompt"]
# Restore emphasis syntax after LLM processing
enhanced_prompt = self._restore_emphasis_syntax(enhanced_prompt)
# Ensure positive keywords are included
if pos_kw_list:
keywords_present, missing = validate_positive_keywords(pos_kw_list, enhanced_prompt)
if missing:
enhanced_prompt += f" {', '.join(missing)}"
positive_prompts.append(enhanced_prompt)
breakdowns.append(breakdown_dict)
# Pad to 3 variations
while len(positive_prompts) < 3:
positive_prompts.append("")
# Generate negative prompt with visual_style for Wan 2.2 optimization
negative_prompt = self.expander.generate_negative_prompt(
preset=preset,
custom_negatives=neg_kw_list,
mode=mode,
visual_style=visual_style
)
# Format breakdown
breakdown_text = self._format_advanced_breakdown(
breakdowns,
basic_prompt,
aesthetic_controls
)
# Save to file if requested
if save_to_file and positive_prompts[0]:
metadata = {
"preset": preset,
"detail_level": detail_level,
"operation_mode": operation_mode,
"mode": mode,
"backend": llm_backend,
"model": llm.model_name or "auto-detected",
"creativity_mode": creativity_mode,
"temperature": temperature,
"variation_num": num_variations,
"original_prompt": basic_prompt,
"aesthetic_controls": aesthetic_controls,
"had_image_reference": reference_image is not None
}
save_result = save_prompts_to_file(
positive_prompt=positive_prompts[0],
negative_prompt=negative_prompt,
breakdown=breakdown_text,
metadata=metadata,
filename_base=filename_base,
output_dir=self.output_dir
)
if save_result["success"]:
file_status = f"💾 Saved to: {save_result['filepath']}"
else:
file_status = f"⚠️ Save failed: {save_result['error']}"
else:
file_status = "Not saved"
# Build status with aesthetic controls summary
controls_summary = self._summarize_controls(aesthetic_controls)
mode_display = f"Mode: {mode}" + (" (with image)" if reference_image is not None else "")
vision_status = f" | Vision: {len(vision_caption)} chars" if vision_caption else ""
status = f"✅ Generated {num_variations} variation(s) | {operation_mode} | Detail: {detail_level} | Preset: {preset}\n{mode_display}{vision_status}\n{controls_summary}\n{file_status}"
return (
positive_prompts[0],
positive_prompts[1],
positive_prompts[2],
negative_prompt,
breakdown_text,
status,
vision_caption if vision_caption else "No image provided"
)
except Exception as e:
error_msg = f"Unexpected error: {str(e)}"
# Try to preserve vision_caption if it exists
caption_output = vision_caption if 'vision_caption' in locals() and vision_caption else "No image provided"
return (
basic_prompt if 'basic_prompt' in locals() else "",
"",
"",
"",
f"ERROR: {error_msg}",
f"❌ {error_msg}",
caption_output
)
def _gather_aesthetic_controls(
self,
light_source: str,
lighting_quality: str,
time_of_day: str,
shot_size: str,
composition: str,
lens: str,
camera_angle: str,
camera_movement: str,
color_tone: str,
art_style: str,
scene_detail: str,
visual_style: str,
visual_effect: str,
character_emotion: str
) -> dict:
"""Gather all non-auto/none aesthetic controls"""
controls = {}
if light_source not in ["auto", "none"]:
controls["light_source"] = light_source
if lighting_quality not in ["auto", "none"]:
controls["lighting_quality"] = lighting_quality
if time_of_day not in ["auto", "none"]:
controls["time_of_day"] = time_of_day
if shot_size not in ["auto", "none"]:
controls["shot_size"] = shot_size
if composition not in ["auto", "none"]:
controls["composition"] = composition
if lens not in ["auto", "none"]:
controls["lens"] = lens
if camera_angle not in ["auto", "none"]:
controls["camera_angle"] = camera_angle
if camera_movement not in ["auto", "none"]:
controls["camera_movement"] = camera_movement
if color_tone not in ["auto", "none"]:
controls["color_tone"] = color_tone
if art_style not in ["auto", "none"]:
controls["art_style"] = art_style
if scene_detail not in ["auto", "none"]:
controls["scene_detail"] = scene_detail
if visual_style not in ["auto", "none"]:
controls["visual_style"] = visual_style
if visual_effect not in ["auto", "none"]:
controls["visual_effect"] = visual_effect
if character_emotion not in ["auto", "none"]:
controls["character_emotion"] = character_emotion
return controls
def _summarize_controls(self, controls: dict) -> str:
"""Create summary of applied controls"""
if not controls:
return "Controls: All Auto"
summary_parts = []
for key, value in controls.items():
label = key.replace("_", " ").title()
summary_parts.append(f"{label}: {value}")
return "Controls: " + ", ".join(summary_parts)
def _format_advanced_breakdown(
self,
breakdowns: list,
original: str,
aesthetic_controls: dict
) -> str:
"""Format breakdown with aesthetic controls"""
if not breakdowns:
return "No breakdown available"
lines = [
"=" * 70,
"ADVANCED PROMPT EXPANSION BREAKDOWN",
"=" * 70,
f"\nOriginal Input:\n{original}\n",
f"\nDetected Tier: {breakdowns[0].get('detected_tier', 'N/A')}",
f"Applied Preset: {breakdowns[0].get('applied_preset', 'N/A')}",
f"Mode: {breakdowns[0].get('mode', 'N/A')}",
]
if breakdowns[0].get('positive_keywords'):
lines.append(f"Required Keywords: {', '.join(breakdowns[0]['positive_keywords'])}")
if aesthetic_controls:
lines.append("\nUser-Specified Aesthetic Controls:")
for key, value in aesthetic_controls.items():
label = key.replace("_", " ").title()
lines.append(f" - {label}: {value}")
lines.append("\n" + "=" * 70)
return "\n".join(lines)
def _process_alternations(self, text: str) -> str:
"""
Process alternation syntax {option1|option2|option3}
Replaces with randomly chosen option
"""
import re
import random
# Pattern to match {option1|option2|option3}
pattern = r'\{([^{}]+)\}'
def replace_alternation(match):
options = match.group(1).split('|')
# Strip whitespace from each option
options = [opt.strip() for opt in options]
return random.choice(options)
# Keep replacing until no more alternations found (handles nested cases)
max_iterations = 10 # Prevent infinite loops
iteration = 0
while '{' in text and '|' in text and iteration < max_iterations:
new_text = re.sub(pattern, replace_alternation, text)
if new_text == text: # No more changes
break
text = new_text
iteration += 1
return text
def _preserve_emphasis_syntax(self, text: str) -> str:
"""
Protect emphasis syntax (keyword:1.5) from being modified
Replaces temporarily with placeholders during LLM processing
"""
import re
# Pattern to match (text:number) emphasis syntax
# This matches things like (dark skin:1.5) or (hair:0.8)
pattern = r'\(([^():]+):(\d+\.?\d*)\)'
# Find all emphasis patterns
emphasis_patterns = re.findall(pattern, text)
# Store original patterns
self._emphasis_store = []
# Replace with placeholders
def replace_emphasis(match):
full_match = match.group(0)
placeholder = f"__EMPHASIS_{len(self._emphasis_store)}__"
self._emphasis_store.append(full_match)
return placeholder
text = re.sub(pattern, replace_emphasis, text)
return text
def _restore_emphasis_syntax(self, text: str) -> str:
"""
Restore emphasis syntax that was protected
"""
if not hasattr(self, '_emphasis_store'):
return text
# Restore placeholders with original emphasis syntax
for i, original in enumerate(self._emphasis_store):
placeholder = f"__EMPHASIS_{i}__"
text = text.replace(placeholder, original)
# Clear the store
self._emphasis_store = []
return text
def _apply_operation_mode(self, prompt: str, operation_mode: str, image_context: str = "") -> str:
"""
Apply operation mode to modify how the prompt is processed
"""
if operation_mode == "expand_from_idea":
# Default behavior - treat as short concept to expand
return prompt + image_context
elif operation_mode == "refine_existing":
# Polish and improve without major changes
instruction = "\n\n[INSTRUCTION: This is an existing prompt to refine. Keep the core content but improve clarity, flow, and descriptive quality. Don't dramatically change the concept or add major new elements.]"
return prompt + instruction + image_context
elif operation_mode == "modify_style":
# Change aesthetic/style while keeping subject
instruction = "\n\n[INSTRUCTION: This is an existing prompt. Keep the main subject and action, but modify the style, mood, cinematography, and aesthetic treatment according to the selected preset and controls.]"
return prompt + instruction + image_context
elif operation_mode == "add_details":
# Add more descriptive elements
instruction = "\n\n[INSTRUCTION: This is an existing prompt that needs more detail. Keep everything that's already there and add richer descriptions, atmospheric details, and sensory elements.]"
return prompt + instruction + image_context
return prompt + image_context
def _build_reference_mode_instruction(self, reference_mode: str) -> str:
"""
Build explicit instruction for how to use the reference image based on mode
Follows Wan 2.2 image-to-video best practices
"""
mode_instructions = {
"recreate_exact": (
"[REFERENCE MODE: RECREATE EXACT]\n"
"Use the provided image as the exact character and costume reference. "
"Keep the same face, hair, outfit, lighting, and overall aesthetic. "
"Animate this character/scene without changing identity or appearance. "
"Match the visual style, mood, and composition of the reference image."
),
"subject_only": (
"[REFERENCE MODE: SUBJECT ONLY]\n"
"Preserve ONLY the subject's face, body identity, and core appearance from the reference image. "
"Ignore the original background, lighting, and environment. "
"Place this character in the new scene described by the prompt with new lighting and atmosphere. "
"Keep character identity consistent but change everything else."
),
"style_only": (
"[REFERENCE MODE: STYLE TRANSFER]\n"
"Match the lighting, color palette, visual aesthetic, and cinematic mood of the reference image. "
"Create a completely new subject, character, and scene, but apply the same artistic style, "
"color grading, lighting quality, and atmospheric treatment seen in the reference."
),
"color_palette_only": (
"[REFERENCE MODE: COLOR PALETTE ONLY]\n"
"Extract and apply the dominant color scheme from the reference image. "
"Use the same hues, saturation levels, and color relationships. "
"Create an entirely new subject and scene, but maintain color harmony with the reference palette. "
"Ignore composition, lighting style, and subject matter from the reference."
),
"action_only": (
"[REFERENCE MODE: ACTION/POSE ONLY]\n"
"Recreate the pose, gesture, body language, and action/movement from the reference image. "
"Change the character identity, environment, lighting, costume, and visual style completely. "
"Keep only the physical positioning and motion dynamic from the reference."
),
"character_remix": (
"[REFERENCE MODE: CHARACTER REMIX]\n"
"Keep the character's core identity (face, build, personality traits) from the reference image. "
"Place them in a completely new scenario, environment, time period, or genre as described in the prompt. "
"Change their outfit, the lighting, the setting, and the mood, but maintain character recognition. "
"Adapt the character to fit the new context while preserving their essential identity."
),
"reimagine": (
"[REFERENCE MODE: REIMAGINE]\n"
"Use the reference image as loose inspiration for a creative reinterpretation. "
"Take the core concept, mood, or theme and reimagine it in a new way. "
"Feel free to change subject, style, setting, and execution while maintaining thematic connection. "
"This is the most creative mode - interpret the essence freely and combine with the prompt."
)
}
return mode_instructions.get(reference_mode, mode_instructions["recreate_exact"])
def _process_reference_image(self, image_tensor):
"""