File size: 20,373 Bytes
e423c4b
ff8eac8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25e7823
db1d80a
836d682
 
d88d679
836d682
 
 
 
 
17379cc
db1d80a
1791ffb
9f7b4e6
1791ffb
c4a3510
17379cc
00d5996
9f7b4e6
d04069e
 
 
 
 
 
 
 
 
 
9f7b4e6
 
d04069e
32e7681
9f7b4e6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94eb043
 
9f7b4e6
32e7681
17379cc
 
 
4e87d3f
17379cc
 
32e7681
17379cc
 
db1d80a
00d5996
 
 
47413cf
1791ffb
4e87d3f
1791ffb
d88d679
836d682
d88d679
4e87d3f
836d682
1791ffb
836d682
47413cf
079d316
 
836d682
079d316
 
 
 
 
 
 
836d682
079d316
 
 
 
 
 
836d682
079d316
836d682
 
 
 
 
d88d679
 
17379cc
d88d679
 
 
4e87d3f
d88d679
17379cc
d88d679
 
 
 
17379cc
 
d88d679
17379cc
 
 
 
 
836d682
47413cf
836d682
17379cc
836d682
d88d679
47413cf
25e7823
 
079d316
 
17379cc
079d316
d88d679
 
079d316
 
 
d04069e
 
 
0b5b20e
 
 
1b704ad
0b5b20e
d04069e
dda7776
d04069e
845979b
dda7776
 
d04069e
dda7776
00d5996
dda7776
 
 
00d5996
dda7776
c65196c
 
836d682
dda7776
836d682
 
 
dda7776
836d682
00d5996
836d682
00d5996
 
836d682
 
 
00d5996
dda7776
836d682
dda7776
c65196c
 
 
 
 
dda7776
 
 
 
 
836d682
 
 
 
 
 
 
dda7776
836d682
 
 
 
 
 
 
 
 
 
 
 
 
 
dda7776
c65196c
dda7776
 
 
 
00d5996
dda7776
 
c65196c
dda7776
 
d88d679
 
 
 
 
 
 
 
 
 
 
 
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

# import os
# from pathlib import Path
# import gc
# import torch
# from diffusers import StableDiffusionXLPipeline, StableDiffusionXLImg2ImgPipeline
# from huggingface_hub import hf_hub_download
# from typing import Dict, Any
# from PIL import Image
# from io import BytesIO
# import base64
# import tempfile

# # --------------------------------------------------------------
# # 🚨 ABSOLUTE FIX FOR PermissionError('/.cache') & '/root/.cache'
# # --------------------------------------------------------------
# HF_CACHE_DIR = Path("/tmp/hf_cache")
# HF_CACHE_DIR.mkdir(parents=True, exist_ok=True)

# # Set ALL key environment variables FIRST
# os.environ.update({
#     "HF_HOME": str(HF_CACHE_DIR),
#     "HF_HUB_CACHE": str(HF_CACHE_DIR),
#     "DIFFUSERS_CACHE": str(HF_CACHE_DIR),
#     "TRANSFORMERS_CACHE": str(HF_CACHE_DIR),
#     "XDG_CACHE_HOME": str(HF_CACHE_DIR),
#     "HF_DATASETS_CACHE": str(HF_CACHE_DIR),
#     "HF_MODULES_CACHE": str(HF_CACHE_DIR),
#     "TMPDIR": str(HF_CACHE_DIR),
#     "CACHE_DIR": str(HF_CACHE_DIR),
#     "TORCH_HOME": str(HF_CACHE_DIR),
#     "HOME": str(HF_CACHE_DIR)
# })

# # Patch expanduser BEFORE any library imports that might touch ~/.cache
# import os.path
# if not hasattr(os.path, "expanduser_original"):
#     os.path.expanduser_original = os.path.expanduser

# def safe_expanduser(path):
#     if (
#         path.startswith("~") or 
#         path.startswith("/.cache") or 
#         path.startswith("/root/.cache")
#     ):
#         print(f"[DEBUG] πŸ”„ Patched path expanduser call for: {path}")
#         return str(HF_CACHE_DIR)
#     return os.path.expanduser_original(path)

# os.path.expanduser = safe_expanduser

# tempfile.tempdir = str(HF_CACHE_DIR)

# print("[DEBUG] βœ… Hugging Face, Diffusers, Datasets and Torch cache fully redirected to:", HF_CACHE_DIR)

# # --------------------------------------------------------------
# # βœ… PERSISTENT STORAGE SETUP (for Hugging Face Spaces)
# # --------------------------------------------------------------
# MODEL_DIR = Path("/tmp/models/realvisxl_v4")
# SEED_DIR = Path("/tmp/seed_images")
# TMP_DIR = Path("/tmp/generated_images")

# for d in [MODEL_DIR, SEED_DIR, TMP_DIR]:
#     d.mkdir(parents=True, exist_ok=True)

# print("[DEBUG] βœ… Using persistent Hugging Face cache at:", HF_CACHE_DIR)
# print("[DEBUG] βœ… Model directory:", MODEL_DIR)
# print("[DEBUG] βœ… Seed directory:", SEED_DIR)

# # --------------------------------------------------------------
# # MODEL CONFIG
# # --------------------------------------------------------------
# MODEL_REPO = "SG161222/RealVisXL_V4.0"
# MODEL_FILENAME = "RealVisXL_V4.0.safetensors"

# # ---------------- GLOBAL PIPELINE CACHE ----------------
# pipe: StableDiffusionXLPipeline | None = None
# img2img_pipe: StableDiffusionXLImg2ImgPipeline | None = None

# # --------------------------------------------------------------
# # MODEL DOWNLOAD
# # --------------------------------------------------------------
# def download_model() -> Path:
#     model_path = MODEL_DIR / MODEL_FILENAME
#     if not model_path.exists():
#         print("[ImageGen] Downloading RealVisXL V4.0 model...")
#         model_path = Path(
#             hf_hub_download(
#                 repo_id=MODEL_REPO,
#                 filename=MODEL_FILENAME,
#                 cache_dir=str(HF_CACHE_DIR),
#                 force_download=False,
#                 resume_download=True,
#             )
#         )
#         print(f"[ImageGen] βœ… Model downloaded to: {model_path}")
#     else:
#         print("[ImageGen] βœ… Model already exists at:", model_path)
#     return model_path

# # --------------------------------------------------------------
# # MEMORY-SAFE PIPELINE MANAGER
# # --------------------------------------------------------------
# def unload_pipelines(target="all"):
#     """Unload specific or all pipelines."""
#     global pipe, img2img_pipe
#     print("[ImageGen] 🧹 Clearing pipelines from memory...")

#     if target in ("pipe", "all"):
#         try:
#             del pipe
#         except:
#             pass
#         pipe = None

#     if target in ("img2img_pipe", "all"):
#         try:
#             del img2img_pipe
#         except:
#             pass
#         img2img_pipe = None

#     gc.collect()
#     if torch.cuda.is_available():
#         torch.cuda.empty_cache()
#     print("[ImageGen] βœ… Memory cleared.")

# def safe_load_pipeline(pipeline_class, model_path):
#     """Safely load a pipeline with retry logic and memory handling."""
#     try:
#         print(f"[ImageGen] πŸ”„ Loading {pipeline_class.__name__} from {model_path} ...")
#         pipe = pipeline_class.from_single_file(
#             model_path,
#             torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
#         )
#         print(f"[ImageGen] βœ… Successfully loaded {pipeline_class.__name__}.")
#         return pipe
#     except Exception as e:
#         print(f"[ImageGen] ❌ Failed to load {pipeline_class.__name__}: {e}")
#         unload_pipelines()
#         gc.collect()
#         if torch.cuda.is_available():
#             torch.cuda.empty_cache()
#         raise e

# def load_pipeline():
#     global pipe
#     unload_pipelines(target="pipe")
#     model_path = download_model()
#     print("[ImageGen] Loading main (txt2img) pipeline...")
#     pipe = safe_load_pipeline(StableDiffusionXLPipeline, model_path)
#     device = "cuda" if torch.cuda.is_available() else "cpu"
#     pipe.to(device)
#     pipe.safety_checker = None
#     pipe.enable_attention_slicing()
#     print("[ImageGen] βœ… Text-to-image pipeline ready.")
#     return pipe

# def load_img2img_pipeline():
#     global img2img_pipe
#     unload_pipelines(target="img2img_pipe")
#     model_path = download_model()
#     print("[ImageGen] Loading img2img pipeline...")
#     img2img_pipe = safe_load_pipeline(StableDiffusionXLImg2ImgPipeline, model_path)
#     device = "cuda" if torch.cuda.is_available() else "cpu"
#     img2img_pipe.to(device)
#     img2img_pipe.safety_checker = None
#     img2img_pipe.enable_attention_slicing()
#     print("[ImageGen] βœ… Img2Img pipeline ready.")
#     return img2img_pipe

# # --------------------------------------------------------------
# # UTILITY: PIL β†’ BASE64
# # --------------------------------------------------------------
# def pil_to_base64(img: Image.Image) -> str:
#     buffered = BytesIO()
#     img.save(buffered, format="PNG")
#     return f"data:image/png;base64,{base64.b64encode(buffered.getvalue()).decode()}"

# # --------------------------------------------------------------
# # UNIFIED IMAGE GENERATION FUNCTION
# # --------------------------------------------------------------
# async def generate_images(prompt_or_json, seed: int | None = None, num_images: int = 3):
#     global pipe, img2img_pipe
#     device = "cuda" if torch.cuda.is_available() else "cpu"

#     # ----------------------------------------------------------
#     # CASE 1: STRUCTURED JSON (story mode)
#     # ----------------------------------------------------------
#     if isinstance(prompt_or_json, dict):
#         story_json = prompt_or_json
#         print("[ImageGen] Detected structured JSON input. Generating cinematic visuals...")

#         # Step 1: Load only txt2img for character generation
#         pipe = load_pipeline()
#         seed_to_char_image = {}
#         for char in story_json.get("characters", []):
#             char_name = char["name"]
#             char_seed = int(char.get("seed", 0))
#             char_desc = char.get("description", "")

#             seed_image_path = SEED_DIR / f"seed_{char_seed}.png"
#             if seed_image_path.exists():
#                 print(f"[ImageGen] πŸ” Reusing existing seed image for '{char_name}' (seed={char_seed})")
#                 image = Image.open(seed_image_path)
#             else:
#                 print(f"[ImageGen] 🎨 Generating new character '{char_name}' (seed={char_seed})")
#                 generator = torch.Generator(device).manual_seed(char_seed)
#                 image = pipe(f"{char_name}, {char_desc}", num_inference_steps=30, generator=generator).images[0]
#                 image.save(seed_image_path)

#             seed_to_char_image[char_seed] = image

#         # Free txt2img pipeline
#         unload_pipelines(target="pipe")

#         # Step 2: Load only img2img for keyframes
#         img2img_pipe = load_img2img_pipeline()
#         for key, scene_data in story_json.items():
#             if not key.startswith("scene"):
#                 continue

#             for frame in scene_data.get("keyframes", []):
#                 frame_seed = int(frame.get("seed", 0))
#                 if frame_seed not in seed_to_char_image:
#                     print(f"[WARN] Seed {frame_seed} not found in characters. Skipping keyframes...")
#                     continue

#                 init_image = seed_to_char_image[frame_seed]

#                 for kf_key, kf_prompt in frame.items():
#                     if kf_key.startswith("keyframe"):
#                         print(f"[ImageGen] 🎬 Generating {key} β†’ {kf_key} using seed {frame_seed}")
#                         generator = torch.Generator(device).manual_seed(frame_seed)
#                         img = img2img_pipe(
#                             prompt=kf_prompt,
#                             image=init_image,
#                             strength=0.55,
#                             num_inference_steps=30,
#                             generator=generator
#                         ).images[0]

#                         out_path = TMP_DIR / f"{key}_{kf_key}_seed{frame_seed}.png"
#                         img.save(out_path)
#                         frame[kf_key] = pil_to_base64(img)

#         unload_pipelines(target="all")  # unload both just in case
#         print("[ImageGen] βœ… Story JSON image generation complete.")
#         return story_json

#     # ----------------------------------------------------------
#     # CASE 2: NORMAL PROMPT
#     # ----------------------------------------------------------
#     print(f"[ImageGen] Generating {num_images} image(s) for prompt='{prompt_or_json}' seed={seed}")
#     pipe = load_pipeline()
#     images = []
#     for i in range(num_images):
#         gen = torch.Generator(device).manual_seed(seed + i) if seed is not None else None
#         try:
#             img = pipe(prompt_or_json, num_inference_steps=30, generator=gen).images[0]
#             img_path = TMP_DIR / f"prompt_{i}.png"
#             img.save(img_path)
#             images.append(pil_to_base64(img))
#         except Exception as e:
#             print(f"[ImageGen] ⚠️ Failed on image {i}: {e}")

#     unload_pipelines(target="pipe")
#     print(f"[ImageGen] βœ… Generated {len(images)} image(s) successfully.")
#     return images





import os
from pathlib import Path
import gc
import torch
from diffusers import StableDiffusionXLPipeline, StableDiffusionXLImg2ImgPipeline, AutoPipelineForText2Image
from huggingface_hub import hf_hub_download
from typing import Dict, Any
from PIL import Image
from io import BytesIO
import base64
import tempfile

# --------------------------------------------------------------
# 🚨 ABSOLUTE FIX FOR PermissionError('/.cache') & '/root/.cache'
# --------------------------------------------------------------
HF_CACHE_DIR = Path("/tmp/hf_cache")
HF_CACHE_DIR.mkdir(parents=True, exist_ok=True)

# Set ALL key environment variables FIRST
os.environ.update({
    "HF_HOME": str(HF_CACHE_DIR),
    "HF_HUB_CACHE": str(HF_CACHE_DIR),
    "DIFFUSERS_CACHE": str(HF_CACHE_DIR),
    "TRANSFORMERS_CACHE": str(HF_CACHE_DIR),
    "XDG_CACHE_HOME": str(HF_CACHE_DIR),
    "HF_DATASETS_CACHE": str(HF_CACHE_DIR),
    "HF_MODULES_CACHE": str(HF_CACHE_DIR),
    "TMPDIR": str(HF_CACHE_DIR),
    "CACHE_DIR": str(HF_CACHE_DIR),
    "TORCH_HOME": str(HF_CACHE_DIR),
    "HOME": str(HF_CACHE_DIR)
})

# Patch expanduser BEFORE any library imports that might touch ~/.cache
import os.path
if not hasattr(os.path, "expanduser_original"):
    os.path.expanduser_original = os.path.expanduser

def safe_expanduser(path):
    if (
        path.startswith("~") or 
        path.startswith("/.cache") or 
        path.startswith("/root/.cache")
    ):
        print(f"[DEBUG] πŸ”„ Patched path expanduser call for: {path}")
        return str(HF_CACHE_DIR)
    return os.path.expanduser_original(path)

os.path.expanduser = safe_expanduser
tempfile.tempdir = str(HF_CACHE_DIR)

print("[DEBUG] βœ… Hugging Face, Diffusers, Datasets and Torch cache fully redirected to:", HF_CACHE_DIR)

# --------------------------------------------------------------
# βœ… PERSISTENT STORAGE SETUP (for Hugging Face Spaces)
# --------------------------------------------------------------
MODEL_DIR = Path("/tmp/models/dreamshaper_sd15")
SEED_DIR = Path("/tmp/seed_images")
TMP_DIR = Path("/tmp/generated_images")

for d in [MODEL_DIR, SEED_DIR, TMP_DIR]:
    d.mkdir(parents=True, exist_ok=True)

print("[DEBUG] βœ… Using persistent Hugging Face cache at:", HF_CACHE_DIR)
print("[DEBUG] βœ… Model directory:", MODEL_DIR)
print("[DEBUG] βœ… Seed directory:", SEED_DIR)

# --------------------------------------------------------------
# MODEL CONFIG
# --------------------------------------------------------------
MODEL_REPO = "lykon/dreamshaper-8"  # Use Hugging Face repo
# ---------------- GLOBAL PIPELINE CACHE ----------------
pipe: StableDiffusionXLPipeline | AutoPipelineForText2Image | None = None
img2img_pipe: StableDiffusionXLImg2ImgPipeline | None = None

# --------------------------------------------------------------
# MEMORY-SAFE PIPELINE MANAGER
# --------------------------------------------------------------
def unload_pipelines(target="all"):
    """Unload specific or all pipelines."""
    global pipe, img2img_pipe
    print("[ImageGen] 🧹 Clearing pipelines from memory...")

    if target in ("pipe", "all"):
        try:
            del pipe
        except:
            pass
        pipe = None

    if target in ("img2img_pipe", "all"):
        try:
            del img2img_pipe
        except:
            pass
        img2img_pipe = None

    gc.collect()
    if torch.cuda.is_available():
        torch.cuda.empty_cache()
    print("[ImageGen] βœ… Memory cleared.")

def safe_load_pipeline(pretrained_model_name):
    """Load DreamShaper SD1.5 safely via from_pretrained."""
    try:
        print(f"[ImageGen] πŸ”„ Loading model {pretrained_model_name} ...")
        pipe = AutoPipelineForText2Image.from_pretrained(
            pretrained_model_name,
            torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
            variant="fp16"  # use fp16 if possible
        )
        device = "cuda" if torch.cuda.is_available() else "cpu"
        pipe = pipe.to(device)
        pipe.enable_attention_slicing()
        print(f"[ImageGen] βœ… Successfully loaded {pretrained_model_name}.")
        return pipe
    except Exception as e:
        print(f"[ImageGen] ❌ Failed to load {pretrained_model_name}: {e}")
        unload_pipelines()
        gc.collect()
        if torch.cuda.is_available():
            torch.cuda.empty_cache()
        raise e

def load_pipeline():
    global pipe
    unload_pipelines(target="pipe")
    print("[ImageGen] Loading main (txt2img) pipeline...")
    pipe = safe_load_pipeline(MODEL_REPO)
    print("[ImageGen] βœ… Text-to-image pipeline ready.")
    return pipe

def load_img2img_pipeline():
    global img2img_pipe
    unload_pipelines(target="img2img_pipe")
    print("[ImageGen] Loading img2img pipeline...")
    # For DreamShaper, img2img uses the same pipeline
    img2img_pipe = safe_load_pipeline(MODEL_REPO)
    print("[ImageGen] βœ… Img2Img pipeline ready.")
    return img2img_pipe

# --------------------------------------------------------------
# UTILITY: PIL β†’ BASE64
# --------------------------------------------------------------
def pil_to_base64(img: Image.Image) -> str:
    buffered = BytesIO()
    img.save(buffered, format="PNG")
    return f"data:image/png;base64,{base64.b64encode(buffered.getvalue()).decode()}"

# --------------------------------------------------------------
# UNIFIED IMAGE GENERATION FUNCTION
# --------------------------------------------------------------
async def generate_images(prompt_or_json, seed: int | None = None, num_images: int = 3):
    global pipe, img2img_pipe
    device = "cuda" if torch.cuda.is_available() else "cpu"

    # ----------------------------------------------------------
    # CASE 1: STRUCTURED JSON (story mode)
    # ----------------------------------------------------------
    if isinstance(prompt_or_json, dict):
        story_json = prompt_or_json
        print("[ImageGen] Detected structured JSON input. Generating cinematic visuals...")

        # Step 1: Load only txt2img for character generation
        pipe = load_pipeline()
        seed_to_char_image = {}
        for char in story_json.get("characters", []):
            char_name = char["name"]
            char_seed = int(char.get("seed", 0))
            char_desc = char.get("description", "")

            seed_image_path = SEED_DIR / f"seed_{char_seed}.png"
            if seed_image_path.exists():
                print(f"[ImageGen] πŸ” Reusing existing seed image for '{char_name}' (seed={char_seed})")
                image = Image.open(seed_image_path)
            else:
                print(f"[ImageGen] 🎨 Generating new character '{char_name}' (seed={char_seed})")
                generator = torch.Generator(device).manual_seed(char_seed)
                image = pipe(f"{char_name}, {char_desc}", num_inference_steps=30, generator=generator).images[0]
                image.save(seed_image_path)

            seed_to_char_image[char_seed] = image

        # Free txt2img pipeline
        unload_pipelines(target="pipe")

        # Step 2: Load only img2img for keyframes
        img2img_pipe = load_img2img_pipeline()
        for key, scene_data in story_json.items():
            if not key.startswith("scene"):
                continue

            for frame in scene_data.get("keyframes", []):
                frame_seed = int(frame.get("seed", 0))
                if frame_seed not in seed_to_char_image:
                    print(f"[WARN] Seed {frame_seed} not found in characters. Skipping keyframes...")
                    continue

                init_image = seed_to_char_image[frame_seed]

                for kf_key, kf_prompt in frame.items():
                    if kf_key.startswith("keyframe"):
                        print(f"[ImageGen] 🎬 Generating {key} β†’ {kf_key} using seed {frame_seed}")
                        generator = torch.Generator(device).manual_seed(frame_seed)
                        img = img2img_pipe(
                            prompt=kf_prompt,
                            image=init_image,
                            strength=0.55,
                            num_inference_steps=30,
                            generator=generator
                        ).images[0]

                        out_path = TMP_DIR / f"{key}_{kf_key}_seed{frame_seed}.png"
                        img.save(out_path)
                        frame[kf_key] = pil_to_base64(img)

        unload_pipelines(target="all")  # unload both just in case
        print("[ImageGen] βœ… Story JSON image generation complete.")
        return story_json

    # ----------------------------------------------------------
    # CASE 2: NORMAL PROMPT
    # ----------------------------------------------------------
    print(f"[ImageGen] Generating {num_images} image(s) for prompt='{prompt_or_json}' seed={seed}")
    pipe = load_pipeline()
    images = []
    for i in range(num_images):
        gen = torch.Generator(device).manual_seed(seed + i) if seed is not None else None
        try:
            img = pipe(prompt_or_json, num_inference_steps=30, generator=gen).images[0]
            img_path = TMP_DIR / f"prompt_{i}.png"
            img.save(img_path)
            images.append(pil_to_base64(img))
        except Exception as e:
            print(f"[ImageGen] ⚠️ Failed on image {i}: {e}")

    unload_pipelines(target="pipe")
    print(f"[ImageGen] βœ… Generated {len(images)} image(s) successfully.")
    return images