-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathfunpack.py
More file actions
1689 lines (1416 loc) · 75.2 KB
/
funpack.py
File metadata and controls
1689 lines (1416 loc) · 75.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
import os
import torch
from transformers import LlamaConfig, LlamaForCausalLM, LlavaForConditionalGeneration, AutoModelForCausalLM, AutoTokenizer, AutoConfig
from huggingface_hub import hf_hub_download, snapshot_download
from safetensors.torch import load_file, save_file, safe_open
import glob
import comfy.model_management as mm
import comfy.sd as sd
import folder_paths
import nodes
import tempfile
import gc # Import garbage collector
import torch.nn as nn
import torch.nn.functional as F
from typing import List, Tuple, Optional
import numpy as np
from PIL import Image
import folder_paths
from comfy.utils import ProgressBar
import comfy.clip_vision
import math
import json
from comfy.utils import ProgressBar
import random
import re
# Constants from StoryMem
IMAGE_FACTOR = 28
VIDEO_MIN_PIXELS = 48 * IMAGE_FACTOR * IMAGE_FACTOR # 37,632
MIN_FRAME_SIMILARITY = 0.9
MAX_KEYFRAME_NUM = 3
ADAPTIVE_ALPHA = 0.01
HPSV3_QUALITY_THRESHOLD = 3.0
class FunPackAutoMontage:
"""
FunPack Auto Montage v2
- Dynamic 1-5 sequences (only connect what you need)
- CLIP (text) is optional — works with CLIP_VISION only
- Per-sequence prompt-based semantic filtering
- Adds transitions only between kept sequences
"""
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"clip_vision": ("CLIP_VISION",),
"images_1": ("IMAGE",),
"prompt_1": ("STRING", {"multiline": True, "default": "Describe the first scene here..."}),
"images_2": ("IMAGE",),
"prompt_2": ("STRING", {"multiline": True, "default": ""}),
"prompt_threshold": ("FLOAT", {
"default": 0.24, "min": 0.0, "max": 1.0, "step": 0.01,
"tooltip": "Lower = more permissive (keeps more frames)"
}),
"min_scene_frames": ("INT", {"default": 8, "min": 1}),
"transition_frames": ("INT", {"default": 12, "min": 0, "max": 60}),
"transition_mode": (["none", "fade", "dissolve", "slide_left", "slide_right"],),
},
"optional": {
"images_3": ("IMAGE",),
"prompt_3": ("STRING", {"multiline": True, "default": ""}),
"images_4": ("IMAGE",),
"prompt_4": ("STRING", {"multiline": True, "default": ""}),
"images_5": ("IMAGE",),
"prompt_5": ("STRING", {"multiline": True, "default": ""}),
"clip": ("CLIP",), # Optional — improves prompt scoring accuracy
"negative_prompt": ("STRING", {"multiline": True, "default": ""}),
}
}
RETURN_TYPES = ("IMAGE", "INT", "STRING")
RETURN_NAMES = ("montage_frames", "scene_count", "stats")
FUNCTION = "montage"
CATEGORY = "FunPack/Video"
def montage(self, clip_vision, images_1, prompt_1,
images_2=None, prompt_2="", images_3=None, prompt_3="",
images_4=None, prompt_4="", images_5=None, prompt_5="",
prompt_threshold=0.24, min_scene_frames=8,
transition_frames=12, transition_mode="fade",
clip=None, negative_prompt=""):
sequences = [
(images_1, prompt_1.strip()),
(images_2, prompt_2.strip()) if images_2 is not None else (None, ""),
(images_3, prompt_3.strip()) if images_3 is not None else (None, ""),
(images_4, prompt_4.strip()) if images_4 is not None else (None, ""),
(images_5, prompt_5.strip()) if images_5 is not None else (None, ""),
]
active_seqs: List[Tuple[torch.Tensor, str]] = [ (imgs, p) for imgs, p in sequences if imgs is not None and imgs.shape[0] > 0 and p ]
if not active_seqs:
raise ValueError("At least one sequence with images and a non-empty prompt is required.")
device = images_1.device
final_frames: List[torch.Tensor] = []
stats_lines = []
total_dropped = 0
scene_count = len(active_seqs)
# Use provided CLIP if available, else fallback
has_text_clip = clip is not None
for i, (batch, prompt) in enumerate(active_seqs):
orig_frames = batch.shape[0]
kept_frames = []
scores = []
dropped = 0
# Encode prompt (best path or fallback)
if has_text_clip:
tokens = clip.tokenizer.encode(prompt)
tokens = clip.tokenizer.pad_tokens(tokens)
text_embed = clip.encode_text(tokens).to(device)
text_embed = F.normalize(text_embed, dim=-1)
else:
# Fallback: simple prompt hash or zero-embed approximation (less accurate but works)
# In practice many users will connect CLIP, so this is rare
text_embed = torch.zeros((1, 768), device=device) # placeholder - will be improved if needed
# Note: Pure CLIP_VISION can't directly encode text well, so CLIP is strongly recommended for best results
neg_embed = None
if negative_prompt.strip() and has_text_clip:
tokens = clip.tokenizer.encode(negative_prompt)
tokens = clip.tokenizer.pad_tokens(tokens)
neg_embed = clip.encode_text(tokens).to(device)
neg_embed = F.normalize(neg_embed, dim=-1)
for j in range(orig_frames):
frame = batch[j:j+1]
# Encode image with CLIP_VISION (standard ComfyUI path)
vision_out = clip_vision.encode_image(frame)
if isinstance(vision_out, dict):
img_embed = vision_out.get("image_embeds") or vision_out.get("last_hidden_state")
else:
img_embed = vision_out
if img_embed is None:
img_embed = vision_out
img_embed = img_embed.to(device)
if img_embed.dim() > 2:
img_embed = img_embed.mean(dim=1)
img_embed = F.normalize(img_embed, dim=-1)
# Score
if has_text_clip and text_embed.shape[-1] == img_embed.shape[-1]:
sim = F.cosine_similarity(img_embed, text_embed, dim=-1).item()
if neg_embed is not None:
neg_sim = F.cosine_similarity(img_embed, neg_embed, dim=-1).item()
sim -= 0.3 * neg_sim
else:
sim = 0.5 # fallback when no text CLIP
scores.append(sim)
if sim >= prompt_threshold:
kept_frames.append(batch[j:j+1])
else:
dropped += 1
if not kept_frames:
# Keep best frame as fallback
best_idx = int(np.argmax(scores))
kept_frames = [batch[best_idx:best_idx+1]]
dropped = orig_frames - 1
cleaned = torch.cat(kept_frames, dim=0)
# Enforce min_scene_frames (simple repeat best frames if needed)
if cleaned.shape[0] < min_scene_frames and cleaned.shape[0] > 0:
repeat_count = min_scene_frames - cleaned.shape[0]
best_frame = cleaned[0:1]
cleaned = torch.cat([cleaned] + [best_frame] * repeat_count, dim=0)
final_frames.append(cleaned)
total_dropped += dropped
avg_score = float(np.mean(scores)) if scores else 0.0
stats_lines.append(f"Seq {i+1}: {orig_frames} → {cleaned.shape[0]} frames (dropped {dropped}, avg score {avg_score:.3f})")
# Build final montage with transitions
montage_list: List[torch.Tensor] = []
for idx, seq in enumerate(final_frames):
montage_list.append(seq)
if idx < len(final_frames) - 1 and transition_frames > 0:
A = seq[-1:]
B = final_frames[idx + 1][0:1]
trans = self._create_transition(A, B, transition_frames, transition_mode, device)
montage_list.append(trans)
final_batch = torch.cat(montage_list, dim=0) if montage_list else images_1[0:1]
stats = f"Scenes: {scene_count} | Total dropped: {total_dropped} | Final frames: {final_batch.shape[0]}\n" + "\n".join(stats_lines)
return (final_batch, scene_count, stats)
def _create_transition(self, A: torch.Tensor, B: torch.Tensor, n: int, mode: str, device):
if n <= 0 or mode == "none":
return torch.zeros((0, *A.shape[1:]), device=device, dtype=A.dtype)
frames = []
for i in range(n):
t = i / max(n - 1, 1)
if mode == "fade":
frame = (1 - t) * A + t * B
elif mode == "dissolve":
frame = (1 - t) * A + t * B
noise = torch.randn_like(frame) * 0.04 * (1 - t)
frame = torch.clamp(frame + noise, 0.0, 1.0)
elif mode in ("slide_left", "slide_right"):
# Simple horizontal slide
w = A.shape[2]
shift = int(w * t)
if mode == "slide_right":
shift = w - shift
left = A[:, :, :w-shift, :] if shift < w else A
right = B[:, :, shift:, :] if shift > 0 else B
frame = torch.cat([left, right], dim=2) if left.shape[2] + right.shape[2] == w else A
else:
frame = (1 - t) * A + t * B
frames.append(frame)
return torch.cat(frames, dim=0)
class FunPackPromptCombiner:
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"main_prompt": ("STRING", {
"multiline": True,
"default": "masterpiece, best quality, detailed background"
}),
},
"optional": {
"prompt1": ("STRING", {"default": "", "multiline": True}),
"prompt2": ("STRING", {"default": "", "multiline": True}),
"prompt3": ("STRING", {"default": "", "multiline": True}),
"prompt4": ("STRING", {"default": "", "multiline": True}),
"prompt5": ("STRING", {"default": "", "multiline": True}),
}
}
RETURN_TYPES = ("STRING", "STRING", "STRING", "STRING", "STRING")
RETURN_NAMES = ("out1", "out2", "out3", "out4", "out5")
FUNCTION = "combine"
CATEGORY = "FunPack"
OUTPUT_NODE = False
def combine(self, main_prompt,
prompt1="", prompt2="", prompt3="", prompt4="", prompt5=""):
main = main_prompt.strip()
def merge(base, addon):
addon = addon.strip()
if not addon:
return base
if not base:
return addon
# You can change separator style here
#return f"{base}, {addon}" # ← comma style (most common in SD)
return f"{base}\n{addon}" # ← new line style
# return f"{base} | {addon}" # ← pipe style, etc.
results = []
for p in (prompt1, prompt2, prompt3, prompt4, prompt5):
combined = merge(main, p)
results.append(combined)
# Always return exactly 5 strings (even if some are just the main prompt)
return tuple(results)
class FunPackLorebookEnhancer:
"""
Injects context from SillyTavern-style lorebook JSON files.
Always appends activated entries to the END of the prompt.
Supports multiple lorebooks, constants, selective filtering, probability, etc.
"""
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"prompt": ("STRING", {
"multiline": True,
"default": "The brave explorer enters an ancient forest temple at twilight, discovering glowing runes on the walls."
}),
},
"optional": {
"lorebook_1": ("STRING", {"default": "", "multiline": False}),
"lorebook_2": ("STRING", {"default": "", "multiline": False}),
"lorebook_3": ("STRING", {"default": "", "multiline": False}),
"lorebook_4": ("STRING", {"default": "", "multiline": False}),
"entry_delimiter": ("STRING", {"default": "", "multiline": True}),
"context_history": ("STRING", {"multiline": True, "default": ""}),
"scan_depth": ("INT", {
"default": 4,
"min": 1,
"max": 12,
"step": 1
}),
}
}
RETURN_TYPES = ("STRING", "STRING")
RETURN_NAMES = ("enhanced_prompt", "injected_content")
FUNCTION = "enhance"
CATEGORY = "FunPack"
OUTPUT_NODE = True
def _match_keys(self, keys, text):
if not keys:
return False
if isinstance(keys, str):
keys = [k.strip() for k in keys.split(",") if k.strip()]
text = text.lower()
for key in keys:
key = key.strip()
if not key:
continue
if key.startswith("/") and key.endswith("/"):
try:
pattern = re.compile(key[1:-1], re.IGNORECASE)
if pattern.search(text):
return True
except:
continue
elif key.lower() in text:
return True
return False
def _match_secondary(self, secs, text, logic):
if not secs:
return True
if isinstance(secs, str):
secs = [s.strip() for s in secs.split(",") if s.strip()]
matches = [self._match_keys([s], text) for s in secs]
if logic == 0: return any(matches)
elif logic == 1: return all(matches)
elif logic == 2: return not any(matches)
elif logic == 3: return not all(matches)
return True
def _process_lorebook(self, path, scan_text, activated):
if not path or not os.path.exists(path):
print(f"[Lorebook Enhancer] File not found: {path}")
return activated
try:
with open(path, 'r', encoding='utf-8') as f:
lorebook = json.load(f)
entries = lorebook.get("entries", [])
if isinstance(entries, dict):
entries = list(entries.values())
for entry in entries:
if not entry.get("enabled", True):
continue
is_constant = entry.get("constant", False)
is_constant = entry.get("constant", False)
if not is_constant:
keys = entry.get("keys", entry.get("key", [])) # Fixed: use "keys" (plural) first
if not self._match_keys(keys, scan_text):
continue
if entry.get("selective", False):
sec_keys = entry.get("keysecondary", []) or entry.get("secondary_keys", [])
logic = entry.get("selectiveLogic", 0)
if not self._match_secondary(sec_keys, scan_text, logic):
continue
if entry.get("selective", False):
sec_keys = entry.get("keysecondary", []) or entry.get("secondary_keys", [])
logic = entry.get("selectiveLogic", 0)
if not self._match_secondary(sec_keys, scan_text, logic):
continue
prob = entry.get("extensions", {}).get("probability", 100)
if random.randint(1, 100) > prob:
continue
activated.append(entry)
except json.JSONDecodeError as e:
print(f"[Lorebook Enhancer] JSON decode error in {path}: {str(e)}")
except Exception as e:
print(f"[Lorebook Enhancer] Failed to process {path}: {type(e).__name__}: {str(e)}")
return activated
def enhance(self, prompt,
lorebook_1="", lorebook_2="", lorebook_3="", lorebook_4="",
context_history="", scan_depth=4, entry_delimiter=""):
full_text = (context_history + "\n" + prompt).lower()
lines = full_text.splitlines()
scan_text = "\n".join(lines[-scan_depth:]) if scan_depth > 0 else full_text
activated = []
for path in [lorebook_1, lorebook_2, lorebook_3, lorebook_4]:
if path.strip():
activated = self._process_lorebook(path.strip(), scan_text, activated)
if not activated:
return (prompt, "No lorebook entries were triggered.")
activated.sort(key=lambda e: e.get("insertion_order", e.get("order", 0)))
injected = []
enhanced = prompt.strip() # clean up any trailing space
for entry in activated:
content = entry.get("content", "").strip()
if not content:
continue
# Always append to the end - this is the requested behavior
if enhanced:
enhanced += "\n" + content
else:
enhanced = content
source = entry.get("comment") or entry.get("name") or f"uid:{entry.get('uid','?')}" or "unnamed"
injected.append(f"[{source}] {content}")
injected_text = "\n\n".join(injected) if injected else "No content injected"
return (enhanced, injected_text)
class FunPackStoryMemJSONConverter:
"""
FunPack StoryMem LoRA JSON Converter - supports both manual input and Qwen-generated output.
Features:
- Lenient parsing: auto-adjusts mismatched lengths for cut/first_frame_prompt
- Handles 'cut' as single bool (replicates) or list
- NO forced first cut=True (user can control via prompt or manual input)
- Safe defaults on invalid data → no crashes
- Splits full Qwen story into up to 3 separate scene JSONs
When use_qwen_output=False → uses manual per-scene inputs with the same leniency.
"""
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"use_qwen_output": ("BOOLEAN", {
"default": False,
"label_on": "Use Qwen Output (ignores manual scenes below)",
"label_off": "Use Manual Scene Inputs",
"tooltip": "Toggle between Qwen-generated full story JSON or classic manual per-scene setup"
}),
"qwen_output": ("STRING", {
"multiline": True,
"default": "",
"tooltip": "Connect STRING output from Kijai's WanVideoPromptExtender / Qwen enhancer here.\nDrag wire onto the left side of this box to convert to input socket."
}),
"story_name": ("STRING", {
"default": "",
"tooltip": "Story title (used in all output JSONs)"
}),
"story_overview": ("STRING", {
"multiline": True,
"default": "",
"tooltip": "Overall story summary (shared across all scenes)"
}),
# Scene 1
"scene1_video_prompts": ("STRING", {
"multiline": True,
"default": "",
"tooltip": "One prompt per line (each = 5-sec clip)"
}),
"scene1_first_frame_prompts": ("STRING", {
"multiline": True,
"default": "",
"tooltip": "First frame description per prompt (will auto-adjust to match count)"
}),
"scene1_cut_values": ("STRING", {
"default": "",
"tooltip": "Comma-separated booleans: true,false,true,... (will auto-adjust to match prompt count)"
}),
# Scene 2
"scene2_video_prompts": ("STRING", {
"multiline": True,
"default": "",
"tooltip": "One prompt per line (each = 5-sec clip)"
}),
"scene2_first_frame_prompts": ("STRING", {
"multiline": True,
"default": "",
"tooltip": "First frame description per prompt (will auto-adjust to match count)"
}),
"scene2_cut_values": ("STRING", {
"default": "",
"tooltip": "Comma-separated booleans: true,false,true,... (will auto-adjust to match prompt count)"
}),
# Scene 3
"scene3_video_prompts": ("STRING", {
"multiline": True,
"default": "",
"tooltip": "One prompt per line (each = 5-sec clip)"
}),
"scene3_first_frame_prompts": ("STRING", {
"multiline": True,
"default": "",
"tooltip": "First frame description per prompt (will auto-adjust to match count)"
}),
"scene3_cut_values": ("STRING", {
"default": "",
"tooltip": "Comma-separated booleans: true,false,true,... (will auto-adjust to match prompt count)"
}),
},
"optional": {
"qwen_mode_notice": ("STRING", {
"multiline": True,
"default": "!!! QWEN MODE ACTIVE !!!\nAll manual inputs below are completely ignored\nConnect the Qwen JSON string above.",
"tooltip": "Reminder - only visible/meaningful when use_qwen_output = True"
})
}
}
RETURN_TYPES = ("STRING", "STRING", "STRING")
RETURN_NAMES = ("json_scene_1", "json_scene_2", "json_scene_3")
OUTPUT_NODE = True
FUNCTION = "convert"
CATEGORY = "FunPack"
def convert(self,
use_qwen_output,
qwen_output,
story_name, story_overview,
scene1_video_prompts, scene1_first_frame_prompts, scene1_cut_values,
scene2_video_prompts, scene2_first_frame_prompts, scene2_cut_values,
scene3_video_prompts, scene3_first_frame_prompts, scene3_cut_values,
qwen_mode_notice=""):
if use_qwen_output:
if not qwen_output.strip():
raise ValueError("Qwen mode enabled but 'qwen_output' is empty! Connect Kijai's prompt enhancer output.")
pbar = ProgressBar(2)
try:
full_data = json.loads(qwen_output)
except json.JSONDecodeError as e:
raise ValueError(f"Failed to parse Qwen output as JSON:\n{str(e)}\n\nMake sure system prompt instructs Qwen to return **only** valid JSON.")
story_name = full_data.get("story_name", "Generated Story")
story_overview = full_data.get("story_overview", "Generated overview")
scenes = full_data.get("scenes", [])
if not isinstance(scenes, list) or not scenes:
raise ValueError("Qwen JSON must contain non-empty 'scenes' list.")
outputs = ["", "", ""]
for i, scene in enumerate(scenes[:3]):
if not isinstance(scene, dict):
continue
scene_num = scene.get("scene_num", i+1)
video_prompts = scene.get("video_prompts", [])
first_frame_prompt = scene.get("first_frame_prompt", [])
cut = scene.get("cut", [])
if not video_prompts:
continue
num_prompts = len(video_prompts)
# Lenient: adjust first_frame_prompt
if len(first_frame_prompt) < num_prompts:
if first_frame_prompt:
first_frame_prompt += [first_frame_prompt[-1]] * (num_prompts - len(first_frame_prompt))
else:
first_frame_prompt = [""] * num_prompts
elif len(first_frame_prompt) > num_prompts:
first_frame_prompt = first_frame_prompt[:num_prompts]
# Lenient: handle cut (single bool or mismatched list)
if isinstance(cut, bool):
cut = [cut] * num_prompts
elif not isinstance(cut, list) or not all(isinstance(c, bool) for c in cut):
cut = [False] * num_prompts # Default to no cuts
else:
if len(cut) < num_prompts:
cut += [cut[-1] if cut else False] * (num_prompts - len(cut))
elif len(cut) > num_prompts:
cut = cut[:num_prompts]
# NO forced first cut=True anymore
single_scene_data = {
"scene_num": scene_num,
"video_prompts": video_prompts,
"first_frame_prompt": first_frame_prompt,
"cut": cut
}
json_data = {
"story_name": story_name,
"story_overview": story_overview,
"scenes": [single_scene_data]
}
outputs[i] = json.dumps(json_data, indent=2, ensure_ascii=False)
pbar.update(2)
return tuple(outputs)
else:
# Manual mode - same leniency
scenes_input = [
(scene1_video_prompts, scene1_first_frame_prompts, scene1_cut_values, 1),
(scene2_video_prompts, scene2_first_frame_prompts, scene2_cut_values, 2),
(scene3_video_prompts, scene3_first_frame_prompts, scene3_cut_values, 3),
]
outputs = ["", "", ""]
for i, (video_text, first_text, cuts_text, scene_num) in enumerate(scenes_input):
if not video_text.strip():
continue
video_prompts = [p.strip() for p in video_text.split("\n") if p.strip()]
if not video_prompts:
continue
num_prompts = len(video_prompts)
first_prompts = [f.strip() for f in first_text.split("\n") if f.strip()]
# Lenient adjust first_prompts
if len(first_prompts) < num_prompts:
if first_prompts:
first_prompts += [first_prompts[-1]] * (num_prompts - len(first_prompts))
else:
first_prompts = [""] * num_prompts
elif len(first_prompts) > num_prompts:
first_prompts = first_prompts[:num_prompts]
# Parse cuts leniently
if cuts_text.strip():
cuts_str = [c.strip().lower() for c in cuts_text.split(",") if c.strip()]
cuts = []
for c in cuts_str:
if c in ("true", "t", "1", "yes"):
cuts.append(True)
else:
cuts.append(False) # default for invalid or false
else:
cuts = [False] * num_prompts
# Lenient adjust cuts
if len(cuts) < num_prompts:
cuts += [cuts[-1] if cuts else False] * (num_prompts - len(cuts))
elif len(cuts) > num_prompts:
cuts = cuts[:num_prompts]
# NO forced first cut=True
scene = {
"scene_num": scene_num,
"video_prompts": video_prompts,
"first_frame_prompt": first_prompts,
"cut": cuts
}
full_json = {
"story_name": story_name.strip() or "Manual Story",
"story_overview": story_overview.strip() or "Manual overview",
"scenes": [scene]
}
outputs[i] = json.dumps(full_json, indent=2, ensure_ascii=False)
return tuple(outputs)
class FunPackImg2LatentInterpolation:
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"images": ("IMAGE",),
"frame_count": ("INT", {"default": 25, "min": 1, "max": 125, "step": 4}),
}
}
RETURN_TYPES = ("IMAGE", "IMAGE")
RETURN_NAMES = ("img_batch_for_encode", "img_for_start_image")
FUNCTION = "process"
CATEGORY = "FunPack"
def process(self, images, frame_count):
device = images.device
total_input_frames = images.shape[0]
# 1. Take the last frame as our starting point
last_frame = images[-1:]
# 2. Generate smooth transition from this frame
interpolated = []
# First frame is exact copy of last input frame (for perfect continuity)
interpolated.append(last_frame.clone())
# Generate remaining frames with increasing denoise
for i in range(1, frame_count):
# Calculate denoise strength (0 at start, 1 at end)
denoise_strength = i / (frame_count - 1)
# Apply denoising
noise = torch.randn_like(last_frame)
blended = (1 - denoise_strength) * last_frame + denoise_strength * noise
interpolated.append(blended)
# Convert to tensor
output = torch.cat(interpolated, dim=0)
# Preview is first frame (same as input's last frame)
preview = interpolated[0].clone()
return (output, preview)
class FunPackPromptEnhancer:
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"user_prompt": ("STRING", {"multiline": True, "default": "A photo of a [subject] in a [setting]. [action]."}),
"system_prompt": ("STRING", {
"multiline": True,
"default": "<You are a creative AI assistant tasked with describing videos.\n\nDescribe the video by detailing the following aspects:\n1. The main content and theme of the video.\n2. The color, shape, size, texture, quantity, text, and spatial relationships of the objects.\n3. Actions, events, behaviors temporal relationships, physical movement changes of the objects.\n4. background environment, light, style and atmosphere.\n5. camera angles, movements, and transitions used in the video:"
}),
"model_path_type": (["Local Safetensors", "HuggingFace Pretrained"],),
"model_path": ("STRING", {"multiline": False, "default": "mlabonne/NeuralLlama-3-8B-Instruct-abliterated"}),
"llm_safetensors_file": (folder_paths.get_filename_list('clip'),),
"top_p": ("FLOAT", {"min": 0.0, "max": 2.0, "step": 0.05, "default": 0.75}),
"top_k": ("INT", {"min": 0, "max": 1000, "step": 1, "default": 40}),
"temperature": ("FLOAT", {"min": 0.0, "max": 2.0, "step": 0.01, "default": 0.6}),
"max_new_tokens": ("INT", {"min": 64, "max": 4096, "step": 64, "default": 512}),
"repetition_penalty": ("FLOAT", {"min": 0.0, "max": 3.0, "step": 0.01, "default": 1.0}),
}
}
RETURN_TYPES = ("STRING",)
RETURN_NAMES = ("enhanced_prompt",)
FUNCTION = "enhance_prompt"
CATEGORY = "FunPack"
def enhance_prompt(self, user_prompt, system_prompt, model_path_type, model_path, llm_safetensors_file, top_p, top_k, temperature, max_new_tokens, repetition_penalty):
llm_model = None
llm_tokenizer = None
llm_model_device = "cuda" if torch.cuda.is_available() else "cpu"
print(f"[FunPackPromptEnhancer] Starting prompt enhancement...")
try:
if model_path_type == "HuggingFace Pretrained":
print(f"[FunPackPromptEnhancer] Loading LLM from HuggingFace pretrained: {model_path}")
llm_tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)
llm_model = AutoModelForCausalLM.from_pretrained(model_path, ignore_mismatched_sizes=True, trust_remote_code=True)
elif model_path_type == "Local Safetensors":
print(f"[FunPackPromptEnhancer] Loading LLM from local safetensors file: {llm_safetensors_file}")
full_safetensors_path = folder_paths.get_full_path('clip', llm_safetensors_file)
llm_tokenizer = AutoTokenizer.from_pretrained("xtuner/llava-llama-3-8b-v1_1-transformers", trust_remote_code=True)
config = AutoConfig.from_pretrained("xtuner/llava-llama-3-8b-v1_1-transformers", trust_remote_code=True)
model_base = AutoModelForCausalLM.from_config(config, trust_remote_code=True)
state_dict = load_file(full_safetensors_path, device="cpu")
model_base.load_state_dict(state_dict, strict=False)
llm_model = model_base
llm_model = llm_model.eval().to(torch.bfloat16 if llm_model_device == "cuda" else torch.float32).to(llm_model_device).requires_grad_(False)
print(f"[FunPackPromptEnhancer] LLM model loaded successfully to {llm_model_device}!")
# Model detection to apply correct chat template
llm_tokenizer.chat_template = """{% set loop_messages = messages %}{% for message in loop_messages %}{% set content = '<|start_header_id|>' + message['role'] + '<|end_header_id|>\n\n' + message['content'] | trim + '<|eot_id|>' %}{% if loop.first %}{{ '<|begin_of_text|>' + content }}{% else %}{{ content }}{% endif %}{% endfor %}{{ '<|start_header_id|>assistant<|end_header_id|>\n\n' if add_generation_prompt else '' }}"""
messages = [
{"role": "system", "content": system_prompt},
{"role": "user", "content": user_prompt}
]
if llm_tokenizer.pad_token_id is None:
llm_tokenizer.pad_token = llm_tokenizer.eos_token
llm_tokenizer.pad_token_id = llm_tokenizer.eos_token_id
llm_tokens = llm_tokenizer.apply_chat_template(
messages,
add_generation_prompt=True,
return_tensors="pt",
tokenize=True
).to(llm_model_device)
print("[FunPackPromptEnhancer] Generating enhanced prompt...")
with torch.no_grad():
generated_ids = llm_model.generate(
**llm_tokens,
do_sample=True,
top_p=top_p,
top_k=top_k,
temperature=temperature,
max_new_tokens=max_new_tokens,
repetition_penalty=repetition_penalty,
pad_token_id=llm_tokenizer.pad_token_id
)
output_text = llm_tokenizer.decode(generated_ids[0][llm_tokens['input_ids'].shape[1]:], skip_special_tokens=True)
print(f"[FunPackPromptEnhancer] Enhanced prompt generated: {output_text}")
return (output_text,)
except Exception as e:
print(f"[FunPackPromptEnhancer] Error during prompt enhancement: {e}")
raise
finally:
if llm_model is not None:
del llm_model
llm_model = None
if llm_tokenizer is not None:
del llm_tokenizer
llm_tokenizer = None
if torch.cuda.is_available():
torch.cuda.empty_cache()
gc.collect()
print("[FunPackPromptEnhancer] LLM model and tokenizer unloaded and memory cleared.")
class FunPackStoryWriter:
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"user_prompt": ("STRING", {"multiline": True, "default": "A photo of a [subject] in a [setting]. [action]."}),
"prompt1": ("STRING", {"multiline": False, "default": ""}),
"prompt2": ("STRING", {"multiline": False, "default": ""}),
"prompt3": ("STRING", {"multiline": False, "default": ""}),
"prompt4": ("STRING", {"multiline": False, "default": ""}),
"prompt5": ("STRING", {"multiline": False, "default": ""}),
"story_system_prompt": ("STRING", {
"multiline": True,
"default": ""
}),
"sequence_system_prompt": ("STRING", {
"multiline": True,
"default": ""
}),
"model_path_type": (["Local Safetensors", "HuggingFace Pretrained"],),
"model_path": ("STRING", {"multiline": False, "default": "mlabonne/NeuralLlama-3-8B-Instruct-abliterated"}),
"llm_safetensors_file": (folder_paths.get_filename_list('clip'),),
"prompt_count": ("INT", {"min": 1, "max": 5, "step": 1, "default": 3}),
"top_p": ("FLOAT", {"min": 0.0, "max": 2.0, "step": 0.05, "default": 0.75}),
"top_k": ("INT", {"min": 0, "max": 1000, "step": 1, "default": 40}),
"min_p": ("FLOAT", {"min": 0.0, "max": 1.0, "step": 0.01, "default": 0.1}),
"temperature": ("FLOAT", {"min": 0.0, "max": 2.0, "step": 0.01, "default": 0.6}),
"max_new_tokens": ("INT", {"min": 64, "max": 4096, "step": 64, "default": 512}),
"repetition_penalty": ("FLOAT", {"min": 0.0, "max": 3.0, "step": 0.01, "default": 1.0}),
"mode": (["Sequences from story", "Sequences from user prompt"],),
"vision_input": ("STRING", {"multiline": True, "default": "Put outputs of your VL model here to make the Story Writer aware of the starting image."}),
"sanity_check": ("BOOLEAN", {"default": True, "label": "Enable Sanity Check"}),
"sanity_check_system_prompt": ("STRING", {
"multiline": True,
"default": "Analyze the given sequence and perform a correction, if the sequence does not match the given requirements:\n1. The sequence is related to given user's prompt.\n2. The sequence contains only physically possible actions.\n3. The sequence contains information about characters, their appearances, positioning, actions, camera angle, focus and zoom.\n4. The sequence is fully describing the requested action.\n\nOutput ONLY corrected sequence, or return it unchanged if it matches the requirements. No additional text except for sequence is allowed."
}),
"disable_continuity": ("BOOLEAN", {"default": False, "label": "Enable/disable continuity - if enabled, does not provide the history of previously generated sequences when generating new one."}),
"provide_current_id": ("BOOLEAN", {"default": True, "label": "If true, provides current sequence ID to the model even if continuity is disabled."}),
}
}
RETURN_TYPES = ("STRING","STRING","STRING","STRING","STRING",)
RETURN_NAMES = ("prompt1","prompt2","prompt3","prompt4","prompt5",)
FUNCTION = "write_story"
CATEGORY = "FunPack"
def write_story(self, user_prompt, prompt1, prompt2, prompt3, prompt4, prompt5, story_system_prompt, sequence_system_prompt, model_path_type, model_path, llm_safetensors_file, prompt_count, top_p, top_k, min_p, temperature, max_new_tokens, repetition_penalty, mode, vision_input, sanity_check, sanity_check_system_prompt, disable_continuity, provide_current_id):
llm_model = None
llm_tokenizer = None
llm_model_device = "cuda" if torch.cuda.is_available() else "cpu"
print(f"[FunPackPromptEnhancer] Making initial story...")
try:
if model_path_type == "HuggingFace Pretrained":
print(f"[FunPackStoryWriter] Loading LLM from HuggingFace pretrained: {model_path}")
llm_tokenizer = AutoTokenizer.from_pretrained(model_path, ignore_mismatched_sizes=True, trust_remote_code=True)
llm_model = AutoModelForCausalLM.from_pretrained(model_path, ignore_mismatched_sizes=True, trust_remote_code=True)
elif model_path_type == "Local Safetensors":
print(f"[FunPackStoryWriter] Loading LLM from local safetensors file: {llm_safetensors_file}")
full_safetensors_path = folder_paths.get_full_path('clip', llm_safetensors_file)
llm_tokenizer = AutoTokenizer.from_pretrained("xtuner/llava-llama-3-8b-v1_1-transformers", ignore_mismatched_sizes=True, trust_remote_code=True)
config = AutoConfig.from_pretrained("xtuner/llava-llama-3-8b-v1_1-transformers", trust_remote_code=True)
model_base = AutoModelForCausalLM.from_config(config, trust_remote_code=True)
state_dict = load_file(full_safetensors_path, device="cpu")
model_base.load_state_dict(state_dict, strict=False)
llm_model = model_base
llm_model = llm_model.eval().to(torch.bfloat16 if llm_model_device == "cuda" else torch.float32).to(llm_model_device).requires_grad_(False)
print(f"[FunPackStoryWriter] LLM model loaded successfully to {llm_model_device}!")
# Applying correct chat template
llm_tokenizer.chat_template = """{% set loop_messages = messages %}{% for message in loop_messages %}{% set content = '<|start_header_id|>' + message['role'] + '<|end_header_id|>\n\n' + message['content'] | trim + '<|eot_id|>' %}{% if loop.first %}{{ '<|begin_of_text|>' + content }}{% else %}{{ content }}{% endif %}{% endfor %}{{ '<|start_header_id|>assistant<|end_header_id|>\n\n' if add_generation_prompt else '' }}"""
# Inside write_story method, after model loading and template/pad fix
outputs = [""] * 5
prompts = [""] * 5
prompts[0] = prompt1
prompts[1] = prompt2
prompts[2] = prompt3
prompts[3] = prompt4
prompts[4] = prompt5
recommended_loras = None
# ── Initialize messages ONCE, depending on mode ────────────────────────────
if mode == "Sequences from story":
messages = [
{"role": "system", "content": story_system_prompt},
{"role": "user", "content": user_prompt}
]
# Generate hidden story
llm_tokens = llm_tokenizer.apply_chat_template(
messages, add_generation_prompt=True, return_tensors="pt", tokenize=True
).to(llm_model_device)
print("[FunPackStoryWriter] Generating hidden story...")
with torch.no_grad():
generated_ids = llm_model.generate(
**llm_tokens,
do_sample=True,
top_p=top_p,
top_k=top_k,
min_p=min_p,
temperature=temperature,
max_new_tokens=max_new_tokens,
repetition_penalty=repetition_penalty,
pad_token_id=llm_tokenizer.pad_token_id,
eos_token_id=llm_tokenizer.eos_token_id,
)
story = llm_tokenizer.decode(generated_ids[0][llm_tokens['input_ids'].shape[1]:], skip_special_tokens=True).strip()
print(f"[FunPackStoryWriter] Hidden story: {story[:150]}...")
messages.append({"role": "assistant", "content": story})
else: # "Sequences from user prompt"
messages = [
{"role": "system", "content": sequence_system_prompt},
{"role": "user", "content": user_prompt}
]
# ── Now generate sequences — only add new instruction + append output ─────
for seq_idx in range(prompt_count):
# Add **only** the fresh sequence instruction each time
if disable_continuity == True and provide_current_id == False:
messages = [
{"role": "system", "content": sequence_system_prompt},
{"role": "user", "content": user_prompt}
]
if prompts[seq_idx]:
messages.append({"role": "user", "content": f"""User's request for current scene only: {prompts[seq_idx]}"""})
elif disable_continuity == True and provide_current_id == True:
messages = [
{"role": "system", "content": sequence_system_prompt},
{"role": "user", "content": f"""Current request ID: {seq_idx+1}\nUser's instruction for all requests: {user_prompt}"""}
]
if prompts[seq_idx]:
messages.append({"role": "user", "content": f"""User's request for current scene only: {prompts[seq_idx]}"""})
else:
messages = [
{"role": "system", "content": sequence_system_prompt},
{"role": "user", "content": f"""Total amount of requests in this batch: {prompt_count}\nCurrently generating request ID {seq_idx+1} out of {prompt_count}\nRequests left in queue: {prompt_count - seq_idx - 1}\nUser's instruction for all requests: {user_prompt}"""},
{"role": "assistant", "content": f"""History:{chr(10).join([f"ID {i}: {text}" for i, text in enumerate(outputs[:seq_idx])]) if seq_idx > 0 else "No history available."}"""}