File size: 11,614 Bytes
dde8ccd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
ComfyUI custom node for running the WithAnyone pipeline.

Copy or symlink this file into your ComfyUI `custom_nodes` directory and ensure
the WithAnyone project plus its dependencies are available in the Python path.
"""

from __future__ import annotations

import json
import random
from typing import Dict, Iterable, List, Optional, Sequence, Tuple

import numpy as np
import torch
from PIL import Image

try:
    from comfy import model_management
    from comfy.utils import ProgressBar
except ImportError:  # pragma: no cover - only executed outside ComfyUI
    model_management = None  # type: ignore
    ProgressBar = None  # type: ignore

from withanyone.flux.pipeline import WithAnyonePipeline
from util import FaceExtractor


DEFAULT_SINGLE_BBOXES: List[List[int]] = [
    [150, 100, 250, 200],
    [100, 100, 200, 200],
    [200, 100, 300, 200],
    [250, 100, 350, 200],
    [300, 100, 400, 200],
]

DEFAULT_DOUBLE_BBOXES: List[List[List[int]]] = [
    [[100, 100, 200, 200], [300, 100, 400, 200]],
    [[150, 100, 250, 200], [300, 100, 400, 200]],
]

PIPELINE_CACHE: Dict[Tuple, WithAnyonePipeline] = {}
FACE_EXTRACTOR: Optional[FaceExtractor] = None


def _get_device() -> torch.device:
    if model_management is not None:
        return model_management.get_torch_device()
    return torch.device("cuda" if torch.cuda.is_available() else "cpu")


def _get_face_extractor() -> FaceExtractor:
    global FACE_EXTRACTOR
    if FACE_EXTRACTOR is None:
        FACE_EXTRACTOR = FaceExtractor()
    return FACE_EXTRACTOR


def _select_default_bboxes(identity_count: int) -> List[List[int]]:
    if identity_count >= 2:
        return [*random.choice(DEFAULT_DOUBLE_BBOXES)]
    return [*DEFAULT_SINGLE_BBOXES[random.randrange(len(DEFAULT_SINGLE_BBOXES))]]


def _parse_manual_bboxes(spec: str) -> Optional[List[List[int]]]:
    if not spec or not spec.strip():
        return None

    spec = spec.strip()
    try:
        parsed = json.loads(spec)
    except json.JSONDecodeError:
        parsed = []
        for chunk in spec.split(";"):
            chunk = chunk.strip()
            if not chunk:
                continue
            values = [float(value.strip()) for value in chunk.split(",")]
            if len(values) != 4:
                raise ValueError(f"Expected 4 values per bbox, got {len(values)}: {chunk}")
            parsed.append(values)

    if isinstance(parsed, dict) and "bboxes" in parsed:
        parsed = parsed["bboxes"]

    if not isinstance(parsed, Sequence):
        raise ValueError("Bounding box specification must be a list or dictionary with 'bboxes'.")

    cleaned: List[List[int]] = []
    for entry in parsed:
        if isinstance(entry, str):
            coords = [float(value.strip()) for value in entry.split(",")]
        elif isinstance(entry, Iterable):
            coords = [float(value) for value in entry]
        else:
            raise ValueError(f"Unsupported bbox entry type: {type(entry)}")

        if len(coords) != 4:
            raise ValueError(f"Each bbox needs four coordinates, received {coords}")

        cleaned.append([int(round(coord)) for coord in coords])

    return cleaned


def _scale_bboxes(bboxes: List[List[int]], width: int, height: int, reference: int = 512) -> List[List[int]]:
    if width == reference and height == reference:
        return bboxes

    sx = width / float(reference)
    sy = height / float(reference)
    scaled = []
    for x1, y1, x2, y2 in bboxes:
        scaled.append(
            [
                int(round(x1 * sx)),
                int(round(y1 * sy)),
                int(round(x2 * sx)),
                int(round(y2 * sy)),
            ]
        )
    return scaled


def _comfy_to_pil_batch(images: torch.Tensor) -> List[Image.Image]:
    if images.ndim == 3:
        images = images.unsqueeze(0)
    pil_images: List[Image.Image] = []
    for image in images:
        array = image.detach().cpu().numpy()
        if array.dtype != np.float32 and array.dtype != np.float64:
            array = array.astype(np.float32)
        array = np.clip(array, 0.0, 1.0)
        array = (array * 255.0).astype(np.uint8)
        if array.shape[-1] == 4:
            array = array[..., :3]
        pil_images.append(Image.fromarray(array))
    return pil_images


def _pil_to_comfy_image(image: Image.Image) -> torch.Tensor:
    array = np.asarray(image.convert("RGB"), dtype=np.float32) / 255.0
    tensor = torch.from_numpy(array)
    tensor = tensor.unsqueeze(0)  # batch dimension
    return tensor


def _prepare_references(
    images: torch.Tensor,
    device: torch.device,
) -> Tuple[List[Image.Image], torch.Tensor]:
    face_extractor = _get_face_extractor()
    ref_pil: List[Image.Image] = []
    arc_embeddings: List[torch.Tensor] = []

    for pil_image in _comfy_to_pil_batch(images):
        ref_img, embedding = face_extractor.extract(pil_image)
        if ref_img is None or embedding is None:
            raise RuntimeError("Failed to extract a face embedding from the provided reference image.")
        ref_pil.append(ref_img)
        arc_embeddings.append(torch.tensor(embedding, dtype=torch.float32, device=device))

    arcface_tensor = torch.stack(arc_embeddings, dim=0)
    return ref_pil, arcface_tensor


def _get_pipeline(
    model_type: str,
    ipa_path: str,
    clip_path: str,
    t5_path: str,
    flux_path: str,
    siglip_path: str,
    only_lora: bool,
    offload: bool,
    lora_rank: int,
    lora_weight: float,
    additional_lora: Optional[str],
) -> WithAnyonePipeline:
    device = _get_device()
    cache_key = (
        model_type,
        ipa_path,
        clip_path,
        t5_path,
        flux_path,
        siglip_path,
        only_lora,
        offload,
        lora_rank,
        lora_weight,
        additional_lora,
        device.type,
    )

    pipeline = PIPELINE_CACHE.get(cache_key)
    if pipeline is None:
        face_extractor = _get_face_extractor()
        pipeline = WithAnyonePipeline(
            model_type=model_type,
            ipa_path=ipa_path,
            device=device,
            offload=offload,
            only_lora=only_lora,
            lora_rank=lora_rank,
            face_extractor=face_extractor,
            additional_lora_ckpt=additional_lora,
            lora_weight=lora_weight,
            clip_path=clip_path,
            t5_path=t5_path,
            flux_path=flux_path,
            siglip_path=siglip_path,
        )
        PIPELINE_CACHE[cache_key] = pipeline
    else:
        pipeline.device = device

    return pipeline


class WithAnyoneNode:
    """
    ComfyUI node that wraps the WithAnyone inference pipeline.
    """

    @classmethod
    def INPUT_TYPES(cls):  # noqa: N802 - ComfyUI API
        return {
            "required": {
                "prompt": ("STRING", {"multiline": True, "default": ""}),
                "ref_images": ("IMAGE",),
            },
            "optional": {
                "manual_bboxes": ("STRING", {"default": ""}),
                "width": ("INT", {"default": 512, "min": 256, "max": 1024, "step": 16}),
                "height": ("INT", {"default": 512, "min": 256, "max": 1024, "step": 16}),
                "num_steps": ("INT", {"default": 25, "min": 5, "max": 100, "step": 1}),
                "guidance": ("FLOAT", {"default": 4.0, "min": 0.0, "max": 25.0, "step": 0.1}),
                "seed": ("INT", {"default": 1234, "min": 0, "max": 2**32 - 1}),
                "model_type": (["flux-dev", "flux-dev-fp8", "flux-schnell"], {"default": "flux-dev"}),
                "id_weight": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 5.0, "step": 0.05}),
                "siglip_weight": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 5.0, "step": 0.05}),
                "only_lora": ("BOOLEAN", {"default": True}),
                "offload": ("BOOLEAN", {"default": False}),
                "lora_rank": ("INT", {"default": 64, "min": 1, "max": 128, "step": 1}),
                "lora_weight": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 2.0, "step": 0.05}),
                "additional_lora": ("STRING", {"default": ""}),
                "ipa_path": ("STRING", {"default": "WithAnyone/WithAnyone"}),
                "clip_path": ("STRING", {"default": "openai/clip-vit-large-patch14"}),
                "t5_path": ("STRING", {"default": "xlabs-ai/xflux_text_encoders"}),
                "flux_path": ("STRING", {"default": "black-forest-labs/FLUX.1-dev"}),
                "siglip_path": ("STRING", {"default": "google/siglip-base-patch16-256-i18n"}),
            },
        }

    RETURN_TYPES = ("IMAGE", "DICT")
    RETURN_NAMES = ("image", "info")
    FUNCTION = "generate"
    CATEGORY = "withanyone"

    def _create_progress_bar(self, steps: int):
        if ProgressBar is None:
            return None
        return ProgressBar(steps)

    def generate(  # noqa: C901 - ComfyUI entry points are typically long
        self,
        prompt: str,
        ref_images: torch.Tensor,
        manual_bboxes: str = "",
        width: int = 512,
        height: int = 512,
        num_steps: int = 25,
        guidance: float = 4.0,
        seed: int = 1234,
        model_type: str = "flux-dev",
        id_weight: float = 1.0,
        siglip_weight: float = 1.0,
        only_lora: bool = True,
        offload: bool = False,
        lora_rank: int = 64,
        lora_weight: float = 1.0,
        additional_lora: str = "",
        ipa_path: str = "WithAnyone/WithAnyone",
        clip_path: str = "openai/clip-vit-large-patch14",
        t5_path: str = "xlabs-ai/xflux_text_encoders",
        flux_path: str = "black-forest-labs/FLUX.1-dev",
        siglip_path: str = "google/siglip-base-patch16-256-i18n",
    ):
        additional_lora_ckpt = additional_lora if additional_lora.strip() else None
        device = _get_device()
        progress = self._create_progress_bar(num_steps)

        pipeline = _get_pipeline(
            model_type=model_type,
            ipa_path=ipa_path,
            clip_path=clip_path,
            t5_path=t5_path,
            flux_path=flux_path,
            siglip_path=siglip_path,
            only_lora=only_lora,
            offload=offload,
            lora_rank=lora_rank,
            lora_weight=lora_weight,
            additional_lora=additional_lora_ckpt,
        )

        ref_imgs_pil, arcface_embeddings = _prepare_references(ref_images, device=device)

        parsed_bboxes = _parse_manual_bboxes(manual_bboxes)
        if parsed_bboxes is None:
            parsed_bboxes = _select_default_bboxes(len(ref_imgs_pil))
        parsed_bboxes = _scale_bboxes(parsed_bboxes, width, height)

        result_image = pipeline(
            prompt=prompt,
            width=width,
            height=height,
            guidance=guidance,
            num_steps=num_steps,
            seed=seed,
            ref_imgs=ref_imgs_pil,
            arcface_embeddings=arcface_embeddings,
            bboxes=[parsed_bboxes],
            id_weight=id_weight,
            siglip_weight=siglip_weight,
        )

        if progress is not None:
            progress.update_absolute(num_steps, num_steps)

        output_tensor = _pil_to_comfy_image(result_image)
        info = {
            "seed": seed,
            "width": width,
            "height": height,
            "guidance": guidance,
            "num_steps": num_steps,
            "bboxes": parsed_bboxes,
            "model_type": model_type,
        }

        return output_tensor, info


NODE_CLASS_MAPPINGS = {
    "WithAnyoneGenerate": WithAnyoneNode,
}

NODE_DISPLAY_NAME_MAPPINGS = {
    "WithAnyoneGenerate": "WithAnyone (Flux)",
}