File size: 24,503 Bytes
8fb34af
c85b2d6
8fb34af
c85b2d6
 
 
 
 
8fb34af
c85b2d6
8fb34af
 
 
c85b2d6
 
8fb34af
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c85b2d6
8fb34af
 
 
 
 
 
c85b2d6
 
8fb34af
 
 
c85b2d6
8fb34af
 
 
 
 
 
c85b2d6
8fb34af
c85b2d6
063b0c2
 
 
 
c85b2d6
df141f2
 
 
8fb34af
 
 
 
 
 
90b8c4b
c85b2d6
8fb34af
c85b2d6
 
8fb34af
c85b2d6
 
90b8c4b
 
 
c85b2d6
90b8c4b
 
 
c85b2d6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90b8c4b
 
 
 
 
 
 
c85b2d6
 
 
 
 
8fb34af
c85b2d6
8fb34af
c85b2d6
 
bd3221e
c85b2d6
8fb34af
c85b2d6
 
 
8fb34af
c85b2d6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a791eeb
c85b2d6
 
90b8c4b
 
 
 
 
c85b2d6
 
 
 
 
 
 
 
 
 
adc3cea
c85b2d6
adc3cea
c85b2d6
 
 
 
 
 
 
 
adc3cea
c85b2d6
 
 
90b8c4b
 
 
 
 
c85b2d6
 
 
 
 
 
 
 
 
 
 
 
 
 
adc3cea
c85b2d6
adc3cea
c85b2d6
 
adc3cea
c85b2d6
 
adc3cea
c85b2d6
 
adc3cea
c85b2d6
adc3cea
c85b2d6
adc3cea
 
c85b2d6
 
 
adc3cea
c85b2d6
adc3cea
c85b2d6
 
adc3cea
c85b2d6
 
adc3cea
c85b2d6
 
 
 
 
adc3cea
c85b2d6
adc3cea
c85b2d6
 
 
 
 
 
adc3cea
c85b2d6
 
 
8fb34af
 
6ad8df9
a791eeb
c85b2d6
 
a791eeb
c85b2d6
 
 
 
8fb34af
 
c85b2d6
bd3221e
c85b2d6
 
bd3221e
c85b2d6
bd3221e
c85b2d6
 
 
 
 
 
 
 
bd3221e
c85b2d6
8fb34af
c85b2d6
90b8c4b
 
 
 
 
 
b09dcf7
 
 
 
 
 
 
 
 
 
 
 
 
 
c85b2d6
 
90b8c4b
c85b2d6
 
90b8c4b
8fb34af
c85b2d6
 
8fb34af
b09dcf7
1628dbf
c85b2d6
 
 
65a4b73
c85b2d6
 
65a4b73
8fb34af
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c85b2d6
 
8fb34af
 
 
c85b2d6
773b10f
 
 
 
 
c85b2d6
8fb34af
 
 
 
 
 
 
 
c85b2d6
 
8fb34af
 
c85b2d6
8fb34af
 
 
 
 
 
 
 
 
 
c85b2d6
 
 
8fb34af
 
 
c85b2d6
8fb34af
 
 
 
 
 
 
c85b2d6
8fb34af
c85b2d6
8fb34af
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c85b2d6
8fb34af
 
773b10f
8fb34af
 
 
 
c85b2d6
8fb34af
 
adc3cea
c85b2d6
 
65a4b73
8fb34af
 
c85b2d6
bd3221e
c85b2d6
 
65a4b73
c85b2d6
 
 
 
8fb34af
c85b2d6
 
 
 
bd3221e
c85b2d6
 
 
 
 
 
 
 
 
 
bd3221e
c85b2d6
 
 
bd3221e
c85b2d6
bd3221e
c85b2d6
bd3221e
c85b2d6
 
 
 
bd3221e
c85b2d6
 
 
 
 
 
bd3221e
c85b2d6
 
 
bd3221e
c85b2d6
 
 
 
 
bd3221e
c85b2d6
bd3221e
8fb34af
 
 
 
 
 
c85b2d6
8fb34af
 
 
 
 
c85b2d6
8fb34af
c85b2d6
 
 
 
 
 
 
 
 
 
8fb34af
 
c85b2d6
 
8fb34af
c85b2d6
 
8fb34af
c85b2d6
8fb34af
c85b2d6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8fb34af
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c85b2d6
8fb34af
 
 
 
 
 
 
 
 
 
 
 
 
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
"""

Custom Handler for FLUX.1-dev with PuLID using Diffusers Pipeline



This handler uses the standard HuggingFace Diffusers FluxPipeline as the base,

with PuLID integration for character consistency. This approach provides:

1. Proper memory management via diffusers' enable_model_cpu_offload()

2. Standard diffusers API compatibility

3. More stable operation compared to the original PuLID sampling code



Based on: https://github.com/KBRASK/PuLID-FLUX-diffusers



API Modes:

- register: Register character face -> extract embedding -> cache

- generate_with_ids: Generate with cached character embeddings

- generate: Normal image generation (no PuLID)

- check_cache: Check which character IDs are cached

- clear_cache: Clear character embedding cache

"""

from typing import Dict, List, Any, Union, Optional
import torch
import torch.nn as nn
from io import BytesIO
import base64
import time
import os
import sys
import uuid
import gc
import numpy as np
from PIL import Image
from types import MethodType

# Environment configuration
NUM_INFERENCE_STEPS = int(os.environ.get("NUM_INFERENCE_STEPS", "28"))
PULID_VERSION = os.environ.get("PULID_VERSION", "v0.9.1")


def setup_pulid_for_embeddings():
    """Clone PuLID repository for ID embedding extraction only."""
    pulid_dir = "/tmp/PuLID"

    if not os.path.exists(pulid_dir):
        print("[FLUX-Diffusers] Cloning PuLID repository for ID extraction...")
        import subprocess
        subprocess.run([
            "git", "clone", "--depth", "1",
            "https://github.com/ToTheBeginning/PuLID.git",
            pulid_dir
        ], check=True)
        print("[FLUX-Diffusers] PuLID cloned successfully")

        # Patch app_flux.py to remove gradio import
        app_flux_path = os.path.join(pulid_dir, "app_flux.py")
        if os.path.exists(app_flux_path):
            with open(app_flux_path, "r") as f:
                content = f.read()
            content = content.replace("import gradio as gr", "# import gradio as gr")
            with open(app_flux_path, "w") as f:
                f.write(content)

    if pulid_dir not in sys.path:
        sys.path.insert(0, pulid_dir)

    return pulid_dir


def create_pulid_forward(pulid_ca, double_interval=2, single_interval=4):
    """Create a patched forward function that injects PuLID ID embeddings.



    This function wraps the original FluxTransformer2DModel.forward() to inject

    ID embeddings at regular intervals during the transformer blocks.



    ID embeddings are read from self._pulid_id_embeddings and self._pulid_id_weight

    which should be set before calling the pipeline.



    IMPORTANT: pulid_ca is captured in the closure since it's a nn.ModuleList

    that needs to be preserved even after enable_model_cpu_offload().

    """
    # Log closure capture for debugging
    print(f"[PuLID Forward] Creating patched forward with pulid_ca: {type(pulid_ca)}, len={len(pulid_ca) if pulid_ca else 0}")

    def forward_with_pulid(

        self,

        hidden_states: torch.Tensor,

        encoder_hidden_states: torch.Tensor = None,

        pooled_projections: torch.Tensor = None,

        timestep: torch.LongTensor = None,

        img_ids: torch.Tensor = None,

        txt_ids: torch.Tensor = None,

        guidance: torch.Tensor = None,

        joint_attention_kwargs: Optional[Dict[str, Any]] = None,

        controlnet_block_samples=None,

        controlnet_single_block_samples=None,

        return_dict: bool = True,

        controlnet_blocks_repeat: bool = False,

    ):
        """Forward with PuLID ID injection."""
        from diffusers.utils import USE_PEFT_BACKEND, is_torch_version, scale_lora_layers, unscale_lora_layers
        from diffusers.models.modeling_outputs import Transformer2DModelOutput

        # Get PuLID parameters from instance attributes (set before pipeline call)
        id_embeddings = getattr(self, '_pulid_id_embeddings', None)
        id_weight = getattr(self, '_pulid_id_weight', 1.0)

        # Debug: Log PuLID status on first step
        if not hasattr(self, '_pulid_logged'):
            self._pulid_logged = True
            print(f"[PuLID Forward] id_embeddings: {type(id_embeddings)}, shape={id_embeddings.shape if id_embeddings is not None else None}")
            print(f"[PuLID Forward] id_weight: {id_weight}")
            print(f"[PuLID Forward] pulid_ca available: {pulid_ca is not None}")

        ca_idx = 0

        if joint_attention_kwargs is not None:
            joint_attention_kwargs = joint_attention_kwargs.copy()
            lora_scale = joint_attention_kwargs.pop("scale", 1.0)
        else:
            lora_scale = 1.0

        if USE_PEFT_BACKEND:
            scale_lora_layers(self, lora_scale)

        hidden_states = self.x_embedder(hidden_states)

        timestep = timestep.to(hidden_states.dtype) * 1000
        if guidance is not None:
            guidance = guidance.to(hidden_states.dtype) * 1000

        temb = (
            self.time_text_embed(timestep, pooled_projections)
            if guidance is None
            else self.time_text_embed(timestep, guidance, pooled_projections)
        )
        encoder_hidden_states = self.context_embedder(encoder_hidden_states)

        if txt_ids.ndim == 3:
            txt_ids = txt_ids[0]
        if img_ids.ndim == 3:
            img_ids = img_ids[0]

        ids = torch.cat((txt_ids, img_ids), dim=0)
        image_rotary_emb = self.pos_embed(ids)

        # Handle IP adapter if present
        if joint_attention_kwargs is not None and "ip_adapter_image_embeds" in joint_attention_kwargs:
            ip_adapter_image_embeds = joint_attention_kwargs.pop("ip_adapter_image_embeds")
            ip_hidden_states = self.encoder_hid_proj(ip_adapter_image_embeds)
            joint_attention_kwargs.update({"ip_hidden_states": ip_hidden_states})

        # Double transformer blocks
        for index_block, block in enumerate(self.transformer_blocks):
            encoder_hidden_states, hidden_states = block(
                hidden_states=hidden_states,
                encoder_hidden_states=encoder_hidden_states,
                temb=temb,
                image_rotary_emb=image_rotary_emb,
                joint_attention_kwargs=joint_attention_kwargs,
            )

            # PuLID ID injection for double blocks
            if pulid_ca is not None and id_embeddings is not None and index_block % double_interval == 0:
                # Move pulid_ca module to same device as hidden_states if needed
                ca_module = pulid_ca[ca_idx]
                if next(ca_module.parameters()).device != hidden_states.device:
                    ca_module = ca_module.to(hidden_states.device)
                hidden_states = hidden_states + id_weight * ca_module(id_embeddings.to(hidden_states.device), hidden_states)
                ca_idx += 1

            # ControlNet residual
            if controlnet_block_samples is not None:
                interval_control = len(self.transformer_blocks) / len(controlnet_block_samples)
                interval_control = int(np.ceil(interval_control))
                if controlnet_blocks_repeat:
                    hidden_states = hidden_states + controlnet_block_samples[index_block % len(controlnet_block_samples)]
                else:
                    hidden_states = hidden_states + controlnet_block_samples[index_block // interval_control]

        hidden_states = torch.cat([encoder_hidden_states, hidden_states], dim=1)

        # Single transformer blocks
        for index_block, block in enumerate(self.single_transformer_blocks):
            hidden_states = block(
                hidden_states=hidden_states,
                temb=temb,
                image_rotary_emb=image_rotary_emb,
                joint_attention_kwargs=joint_attention_kwargs,
            )

            # PuLID ID injection for single blocks
            if pulid_ca is not None and id_embeddings is not None and index_block % single_interval == 0:
                real_img = hidden_states[:, encoder_hidden_states.shape[1]:, ...]
                # Move pulid_ca module to same device as hidden_states if needed
                ca_module = pulid_ca[ca_idx]
                if next(ca_module.parameters()).device != hidden_states.device:
                    ca_module = ca_module.to(hidden_states.device)
                real_img = real_img + id_weight * ca_module(id_embeddings.to(hidden_states.device), real_img)
                hidden_states = torch.cat([
                    hidden_states[:, :encoder_hidden_states.shape[1], ...],
                    real_img
                ], dim=1)
                ca_idx += 1

            # ControlNet residual
            if controlnet_single_block_samples is not None:
                interval_control = len(self.single_transformer_blocks) / len(controlnet_single_block_samples)
                interval_control = int(np.ceil(interval_control))
                hidden_states[:, encoder_hidden_states.shape[1]:, ...] = (
                    hidden_states[:, encoder_hidden_states.shape[1]:, ...]
                    + controlnet_single_block_samples[index_block // interval_control]
                )

        hidden_states = hidden_states[:, encoder_hidden_states.shape[1]:, ...]

        hidden_states = self.norm_out(hidden_states, temb)
        output = self.proj_out(hidden_states)

        if USE_PEFT_BACKEND:
            unscale_lora_layers(self, lora_scale)

        if not return_dict:
            return (output,)

        return Transformer2DModelOutput(sample=output)

    return forward_with_pulid


class EndpointHandler:
    def __init__(self, path: str = ""):
        """Initialize FLUX.1-dev pipeline with PuLID support using Diffusers."""
        if not torch.cuda.is_available():
            raise RuntimeError("GPU is required for FLUX.1-dev inference")

        self.device = torch.device("cuda")
        self._pulid_loaded = False

        # Character embedding cache
        self.embedding_cache: Dict[str, Dict[str, Any]] = {}

        # Log GPU info
        gpu_props = torch.cuda.get_device_properties(0)
        self.gpu_memory_gb = gpu_props.total_memory / 1e9
        print(f"[FLUX-Diffusers] GPU: {gpu_props.name}")
        print(f"[FLUX-Diffusers] GPU Memory: {self.gpu_memory_gb:.1f} GB")

        self._setup_pipeline()

    def _log_gpu_memory(self, stage: str):
        """Log GPU memory usage."""
        if torch.cuda.is_available():
            allocated = torch.cuda.memory_allocated() / 1e9
            reserved = torch.cuda.memory_reserved() / 1e9
            print(f"[FLUX-Diffusers] GPU Memory @ {stage}: allocated={allocated:.2f}GB, reserved={reserved:.2f}GB")

    def _setup_pipeline(self):
        """Setup diffusers FluxPipeline with PuLID integration."""
        print("[FLUX-Diffusers] Setting up pipeline...")
        load_start = time.time()

        self._log_gpu_memory("before_setup")

        # 1. Load base FluxPipeline
        from diffusers import FluxPipeline

        print("[FLUX-Diffusers] Loading FluxPipeline...")
        self.pipe = FluxPipeline.from_pretrained(
            "black-forest-labs/FLUX.1-dev",
            torch_dtype=torch.bfloat16,
        )

        self._log_gpu_memory("after_flux_load")

        # 2. Setup PuLID for ID embedding extraction
        setup_pulid_for_embeddings()

        from pulid.pipeline_flux import PuLIDPipeline

        print("[FLUX-Diffusers] Initializing PuLID for ID extraction...")
        self.pulid_model = PuLIDPipeline(
            dit=self.pipe.transformer,  # Pass transformer to inject pulid_ca
            device=self.device,
            weight_dtype=torch.bfloat16,
            onnx_provider="cpu",  # Use CPU for InsightFace to save GPU memory
        )
        self.pulid_model.load_pretrain()

        self._log_gpu_memory("after_pulid_load")

        # 3. Store pulid_ca for forward injection
        # PuLIDPipeline attaches pulid_ca directly to the transformer
        self.pulid_ca = getattr(self.pipe.transformer, 'pulid_ca', None)
        print(f"[FLUX-Diffusers] pulid_ca found: {self.pulid_ca is not None}")
        if self.pulid_ca is not None:
            print(f"[FLUX-Diffusers] pulid_ca type: {type(self.pulid_ca)}, len: {len(self.pulid_ca)}")

        # 4. Determine whether to use CPU offload based on GPU memory
        # H200 (150GB) doesn't need offload, and offload breaks our patched forward
        use_offload = self.gpu_memory_gb < 80  # Only use offload for smaller GPUs

        if use_offload:
            print("[FLUX-Diffusers] GPU < 80GB, enabling CPU offload...")
            self.pipe.enable_model_cpu_offload()
        else:
            print(f"[FLUX-Diffusers] GPU >= 80GB ({self.gpu_memory_gb:.1f}GB), using full GPU mode...")
            self.pipe.to(self.device)

        self._log_gpu_memory("after_device_setup")

        # 5. Patch transformer forward to support ID injection
        if self.pulid_ca is not None:
            print("[FLUX-Diffusers] Patching transformer forward for PuLID...")
            patched_forward = create_pulid_forward(self.pulid_ca)
            self.pipe.transformer.forward = MethodType(patched_forward, self.pipe.transformer)
            self._pulid_loaded = True
            print("[FLUX-Diffusers] PuLID forward patch applied successfully")
        else:
            print("[FLUX-Diffusers] Warning: pulid_ca not found, PuLID disabled")
            self._pulid_loaded = False

        self._log_gpu_memory("after_patch")

        # Clean up
        gc.collect()
        torch.cuda.empty_cache()

        print(f"[FLUX-Diffusers] Pipeline ready in {time.time() - load_start:.1f}s")
        self._log_gpu_memory("final")

    def _register_character(self, data: Dict) -> Dict:
        """Register a character face and cache its embedding."""
        if not self._pulid_loaded:
            return {"error": "PuLID not loaded", "success": False}

        params = data.get("parameters", {})
        face_b64 = params.get("face_image", "")
        char_name = params.get("character_name", "Unknown")

        if not face_b64:
            return {"error": "face_image required", "success": False}

        try:
            # Decode base64 image
            if face_b64.startswith("data:"):
                face_b64 = face_b64.split(",")[1]

            img_bytes = base64.b64decode(face_b64)
            img = Image.open(BytesIO(img_bytes)).convert("RGB")
            img_array = np.array(img)

            # Resize if needed
            from pulid.utils import resize_numpy_image_long
            img_array = resize_numpy_image_long(img_array, 1024)

            # Extract ID embedding
            id_embedding, uncond_embedding = self.pulid_model.get_id_embedding(
                img_array, cal_uncond=True
            )

            # Ensure embeddings are on GPU
            if id_embedding is not None:
                id_embedding = id_embedding.to(self.device)
            if uncond_embedding is not None:
                uncond_embedding = uncond_embedding.to(self.device)

            # Generate unique ID and cache
            char_id = str(uuid.uuid4())
            self.embedding_cache[char_id] = {
                "name": char_name,
                "id_embedding": id_embedding,
                "uncond_embedding": uncond_embedding,
                "created_at": time.time(),
            }

            # Check face detection
            debug_images = self.pulid_model.debug_img_list
            face_detected = len(debug_images) > 0

            print(f"[FLUX-Diffusers] Registered character '{char_name}' with ID {char_id}")

            return {
                "success": True,
                "character_id": char_id,
                "character_name": char_name,
                "embedding_cached": True,
                "face_detected": face_detected,
            }

        except Exception as e:
            print(f"[FLUX-Diffusers] Registration error: {e}")
            import traceback
            traceback.print_exc()
            return {"error": str(e), "success": False}

    def _generate_with_consistency(self, data: Dict) -> Union[Dict, List[Dict]]:
        """Generate image(s) with character consistency using cached embeddings."""
        if not self._pulid_loaded:
            return {"error": "PuLID not loaded", "success": False}

        inputs = data.get("inputs", "")
        params = data.get("parameters", {})
        char_ids = params.get("character_ids", [])

        # Handle single vs batch inputs
        single_input = isinstance(inputs, str)
        prompts = [inputs] if single_input else inputs

        if not prompts:
            return {"error": "No prompts provided", "success": False}

        # Validate character IDs
        missing_ids = [cid for cid in char_ids if cid not in self.embedding_cache]
        if missing_ids:
            return {
                "error": f"Characters not in cache: {missing_ids}",
                "success": False,
                "missing_ids": missing_ids,
            }

        if len(char_ids) == 0:
            return {"error": "At least one character_id required", "success": False}

        # Get first character's embedding
        char_data = self.embedding_cache[char_ids[0]]
        id_embedding = char_data["id_embedding"]

        # Extract parameters
        width = params.get("width", 896)
        height = params.get("height", 1152)
        num_steps = params.get("num_inference_steps", NUM_INFERENCE_STEPS)
        guidance = params.get("guidance_scale", 3.5)
        id_weight = params.get("id_weight", 1.0)
        seed = params.get("seed", -1)

        print(f"[FLUX-Diffusers] Generating {len(prompts)} image(s) with character '{char_data['name']}'")
        print(f"[FLUX-Diffusers] Settings: id_weight={id_weight}, steps={num_steps}, size={width}x{height}")

        results = []

        for i, prompt in enumerate(prompts):
            try:
                print(f"[FLUX-Diffusers] Generating image {i + 1}/{len(prompts)}")
                self._log_gpu_memory("before_generation")

                # Set seed
                generator = None
                if seed != -1:
                    generator = torch.Generator(device="cpu").manual_seed(seed + i)

                # Set PuLID parameters on transformer before generation
                # The patched forward will read these attributes
                self.pipe.transformer._pulid_id_embeddings = id_embedding
                self.pipe.transformer._pulid_id_weight = id_weight

                # Generate with PuLID
                with torch.inference_mode():
                    output = self.pipe(
                        prompt=prompt,
                        height=height,
                        width=width,
                        num_inference_steps=num_steps,
                        guidance_scale=guidance,
                        generator=generator,
                    )

                # Clear PuLID parameters after generation
                self.pipe.transformer._pulid_id_embeddings = None
                self.pipe.transformer._pulid_id_weight = 1.0

                image = output.images[0]

                self._log_gpu_memory("after_generation")

                # Encode to base64
                buffered = BytesIO()
                image.save(buffered, format="PNG")
                b64_image = base64.b64encode(buffered.getvalue()).decode("utf-8")

                results.append({
                    "success": True,
                    "image": f"data:image/png;base64,{b64_image}",
                    "characters_used": [char_ids[0]],
                    "character_name": char_data["name"],
                })

                # Clean up
                gc.collect()
                torch.cuda.empty_cache()

            except Exception as e:
                print(f"[FLUX-Diffusers] Generation error: {e}")
                import traceback
                traceback.print_exc()
                results.append({"error": str(e), "success": False})

        return results[0] if single_input else results

    def _generate_normal(self, data: Dict) -> Union[Dict, List[Dict]]:
        """Normal image generation without character consistency."""
        inputs = data.get("inputs", data)
        params = data.get("parameters", {})

        single_input = isinstance(inputs, str)
        prompts = [inputs] if single_input else inputs

        # Extract parameters
        width = params.get("width", 896)
        height = params.get("height", 1152)
        num_steps = params.get("num_inference_steps", NUM_INFERENCE_STEPS)
        guidance = params.get("guidance_scale", 3.5)
        seed = params.get("seed", -1)

        print(f"[FLUX-Diffusers] Generating {len(prompts)} image(s) (no PuLID)")

        results = []

        for i, prompt in enumerate(prompts):
            try:
                generator = None
                if seed != -1:
                    generator = torch.Generator(device="cpu").manual_seed(seed + i)

                with torch.inference_mode():
                    output = self.pipe(
                        prompt=prompt,
                        height=height,
                        width=width,
                        num_inference_steps=num_steps,
                        guidance_scale=guidance,
                        generator=generator,
                    )

                image = output.images[0]

                buffered = BytesIO()
                image.save(buffered, format="PNG")
                b64_image = base64.b64encode(buffered.getvalue()).decode("utf-8")

                results.append({
                    "image": f"data:image/png;base64,{b64_image}"
                })

                gc.collect()
                torch.cuda.empty_cache()

            except Exception as e:
                print(f"[FLUX-Diffusers] Generation error: {e}")
                results.append({"error": str(e), "success": False})

        return results[0] if single_input else results

    def _check_cache(self, char_ids: List[str]) -> Dict:
        """Check which character IDs are cached."""
        status = {}
        for cid in char_ids:
            if cid in self.embedding_cache:
                status[cid] = {
                    "cached": True,
                    "name": self.embedding_cache[cid]["name"],
                    "created_at": self.embedding_cache[cid]["created_at"],
                }
            else:
                status[cid] = {"cached": False}

        return {
            "cache_status": status,
            "total_cached": len(self.embedding_cache),
        }

    def _clear_cache(self, char_ids: Optional[List[str]] = None) -> Dict:
        """Clear character embedding cache."""
        if char_ids:
            cleared = []
            for cid in char_ids:
                if cid in self.embedding_cache:
                    del self.embedding_cache[cid]
                    cleared.append(cid)
            return {"cleared": cleared, "remaining": len(self.embedding_cache)}
        else:
            count = len(self.embedding_cache)
            self.embedding_cache.clear()
            gc.collect()
            torch.cuda.empty_cache()
            return {"cleared_all": True, "count": count}

    def __call__(self, data: Dict[str, Any]) -> Union[Dict, List[Dict]]:
        """Process image generation request."""
        params = data.get("parameters", {})
        mode = params.get("mode", "generate")

        if mode == "register":
            return self._register_character(data)
        elif mode == "generate_with_ids":
            return self._generate_with_consistency(data)
        elif mode == "check_cache":
            return self._check_cache(params.get("character_ids", []))
        elif mode == "clear_cache":
            return self._clear_cache(params.get("character_ids"))
        else:
            return self._generate_normal(data)