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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
"""Anima Reference add-on for the Krita "AI Image Diffusion" plugin.

What it does
    Krita's Reference control layers do nothing with Anima styles ("Not supported for Anima").
    This add-on makes three of them work, by putting one extra node into the workflows the AI
    plugin builds whenever such a layer is used together with an Anima style:

      Reference   a character                              Anima Ref Adapter v2, or SnapRef
      Style       a character and the picture's art style  SnapRef, mode "character and style"
      Face        one more picture of the same character   SnapRef, several references

    Nodes: "Anima Ref Adapter" (github.com/ArcAnima/ComfyUI-Anima-Ref-Adapter) and "SnapRef"
    (github.com/ArcAnima/SnapRef). Only one of the two is ever put into a workflow.

How it does it
    No file of the AI plugin is changed. When Krita starts, a handful of the AI plugin's
    functions are wrapped in memory. Disable this add-on in Krita's Python Plugin Manager and the
    AI plugin is exactly as it was.

    The wrapped functions (AI Image Diffusion 1.53.0):
      ComfyClient._refresh_models          notice the nodes on the server
      ControlLayer._update_is_supported    clearer message when a node is missing
      ControlLayer.to_api                  send the reference at full size instead of 224 x 224
      workflow.prepare                     check the request before it is queued
      workflow.create                      remember the reference(s) while one workflow is built
      workflow.apply_attention_mask        note the text encoder (SnapRef needs it)
      workflow.apply_regional_ip_adapter   insert the node

Things found by running the pieces together (ComfyUI 4da9e2d, tooling nodes ca01116, Anima Ref
Adapter f02d54d, SnapRef 1f7e606) and handled here:

  * Order (Anima Ref Adapter). The node goes after the plugin's region node (ETN_AttentionMask),
    not before it, where the plugin's own reference hook sits. While a reference is attached the
    adapter runs its own copy of the Anima forward pass; placed first it skips the region setup.

  * Regions and reference strength (Anima Ref Adapter). Above ref_guidance 1 the adapter makes one
    extra model call per step with the reference switched off. The region node misreads that call,
    which cancels most of the text guidance. With regions the node is run at ref_guidance 1.

  * Regions and SnapRef do not go together at all. Both replace the model's self-attention
    function: the region node for the length of one job, SnapRef once and for good. Used in one
    job, the region node pushes SnapRef's replacement out; that job, or every SnapRef job after
    it until the server restarts, then stops with "'NoneType' object is not subscriptable".
    SnapRef is therefore never put into a workflow that has regions. Plain Reference layers use
    the Anima Ref Adapter there; Style and Face layers are refused with a message.

  * Control layers. Anima control layers (LLLite) patch the model's projections and only apply
    to inputs that have exactly as many tokens as the picture being made. If a reference happens
    to have the same number of tokens, the control is applied to the reference too (both nodes).
    The reference size is nudged down by 5% steps until the counts differ.
"""

from __future__ import annotations

import inspect
import threading
import traceback

ADDON_VERSION = "1.1"
TESTED_VERSIONS = ("1.53.0",)

ADAPTER_NODE = "AnimaRefAdapter"
SNAPREF_NODE = "SnapRef"  # the original node pack's "SnapRef (Advanced)"
REGION_NODE = "ETN_AttentionMask"
ADAPTER_FILE = "anima_ref_adapter_v2"  # the v2 adapter; the older "pilot" file needs other nodes
SNAPREF_NEEDS = ("clip", "mode", "ref_megapixels", "image_2", "image_3", "use_batch", "weight_1", "weight_2", "weight_3")
MAX_REFERENCES = 2  # different characters: one, or two placed side by side
MAX_PICTURES = 5  # pictures of one character (SnapRef)
SNAPREF_SLOTS = 3  # image inputs of the SnapRef node; each takes a batch of same-size pictures
MAX_REFERENCE_PIXELS = 2 * 1024 * 1024  # larger layers are scaled down before upload
RECOMMENDED_GUIDANCE = 4.5  # the adapter author's setting for a normal (cfg 4.5) Anima style
REFERENCE_MEGAPIXELS = (1.0, 0.95, 0.9, 0.85, 0.8)  # first one whose token count is free; trained on 0.56-1 MP
SNAPREF_TOTAL_MEGAPIXELS = 2.0  # all pictures together; one picture is never read above 1 MP
MIN_WEIGHT = 0.05  # a picture below this strength is left out
MISSING_NODE_TEXT = "Anima Ref Adapter is missing on the server (run install.bat)"
MISSING_SNAPREF_TEXT = "SnapRef is missing on the server (run install.bat and answer Y to SnapRef)"
# The AI plugin adds its FaceID LoRA to every job that has a Face layer and stops with "LoRA 'face' for
# Anima not found" if there is none. It is given this name to find, and the entry is taken out of the
# job again before anything is built from it. Never a file.
FACE_LORA_PLACEHOLDER = "anima_reference_face_layer_placeholder"

CHARACTER, STYLE, EXTRA = "character", "style", "extra"

# Strength presets for the control layer's slider (5 positions, interpolated between these).
PRESETS = [
    {"strength": 0.4, "start": 0.0, "end": 0.6},
    {"strength": 1.0, "start": 0.0, "end": 1.0},
    {"strength": 1.4, "start": 0.0, "end": 1.0},
]

# Set from the add-on's dialog (Tools > Scripts) and kept in Krita's settings by __init__.py.
options = {"prefer_snapref": False}


class _State:
    def __init__(self):
        self.installed = False
        self.plugin_version = ""
        self.tested = False
        self.error = ""
        self.originals = []  # (owner, attribute name, original value)
        self.presets_added = []  # control mode names
        self.resource_id = ""  # Reference + Anima
        self.resource_ids = {}  # role -> resource id, and "face_lora"
        self.snapref_inputs = ()  # input names of the SnapRef node on the server
        self.last_job = ""  # what the last workflow used, for the status dialog


state = _State()
_local = threading.local()
# Qt keeps only a weak hold on a function connected as a slot (bound method). The wrappers below
# end up connected to the plugin's signals, so they must never be freed, also not after uninstall().
_keep_alive = []


class _Context:
    """What the node needs while one workflow is being built."""

    def __init__(self, engine, vae_name, megapixels, description):
        self.engine = engine  # "v2" or "snapref"
        self.vae_name = vae_name
        self.ref_megapixels = megapixels
        self.description = description
        # Anima Ref Adapter
        self.images = []
        self.ref_guidance = 1.0
        self.ref_end = 1.0
        self.lora_name = ""
        # SnapRef
        self.adapter = ""
        self.mode = "char"
        self.groups = []  # [(pictures of one node input, weight)]
        self.stitch = False  # the first group holds two characters to be placed side by side


def _logger():
    try:
        from ai_diffusion.util import client_logger

        return client_logger
    except Exception:
        import logging

        return logging.getLogger("anima_reference")


def ref_guidance_for(strength: float, cfg: float) -> float:
    """Control layer strength (0 .. 1.5, 1.0 = default) -> the Anima Ref Adapter's ref_guidance.

    The adapter's author pairs ref_guidance with the text guidance: 4.5 for a normal style
    (cfg 4.5) and 1 for a turbo setup (cfg 1). Strength 1.0 gives that recommended value,
    lower strengths go down to 1 (no extra push), higher strengths add up to +1.75.
    """
    recommended = min(RECOMMENDED_GUIDANCE, max(1.0, float(cfg)))
    strength = max(0.0, float(strength))
    if strength <= 1.0:
        value = 1.0 + (recommended - 1.0) * strength
    else:
        value = recommended + (strength - 1.0) * 3.5
    return round(min(20.0, max(1.0, value)), 2)


def snapref_weight(strength: float) -> float:
    """Control layer strength -> SnapRef's weight of one picture (1 = as trained, 2 = the node's maximum)."""
    return round(min(2.0, max(0.0, float(strength))), 2)


def _filename(option):
    return str(option).replace("\\", "/").rsplit("/", 1)[-1].lower()


def pick_adapter(options):
    """The Anima Ref Adapter file to use from the node's list of LoRA files, or None."""
    candidates = [o for o in options if ADAPTER_FILE in _filename(o)]
    if not candidates:
        return None
    # The node always lists its own download name, even before the file exists. An entry inside a
    # sub-folder can only come from a file that is really there, so prefer that one.
    in_folder = [o for o in candidates if "/" in str(o) or "\\" in str(o)]
    return (in_folder or candidates)[0]


def pick_snapref(options):
    """The SnapRef weights to use from the node's list of LoRA files, or None. The node lists every
    LoRA when it finds no SnapRef file, so the name is checked here. Order: v2a stable, the original
    (bf16) file before its FP8 copy, then newer names first."""
    candidates = [o for o in options if "snapref" in _filename(o)]

    def rank(option):
        name = _filename(option).replace("snapref", "")  # ("snapref" itself contains "pre")
        stable = "v2a" in name and "pre" not in name
        return (0 if stable else 1, 1 if "fp8" in name else 0, [-ord(c) for c in name])

    return sorted(candidates, key=rank)[0] if candidates else None


def is_v2_file(name):
    return bool(name) and ADAPTER_FILE in _filename(name)


def reference_size(images):
    """Width and height of two pictures placed side by side: the second is scaled to the height of
    the first (ComfyUI's Image Stitch with match_image_size). One picture: its own size."""
    width, height = images[0].width, images[0].height
    for other in images[1:]:
        width += int(height * (other.width / other.height))
    return width, height


def reference_tokens(size, megapixels):
    """Number of tokens the Anima Ref Adapter turns a reference of this size into (its resize rule)."""
    width, height = size
    scale = (megapixels * 1024 * 1024 / (width * height)) ** 0.5
    width, height = (max(16, round(d * scale / 16) * 16) for d in (width, height))
    return (width // 16) * (height // 16)


def snapref_tokens(size, megapixels):
    """The same for SnapRef: it only ever shrinks, and rounds the sides down to a multiple of 16."""
    width, height = size
    scale = min(1.0, (megapixels * 1024 * 1024 / (width * height)) ** 0.5)
    width = max(16, int(width * scale) // 16 * 16)
    height = max(16, int(height * scale) // 16 * 16)
    return (width // 16) * (height // 16)


def target_tokens(width, height):
    """Number of tokens of a picture generated at this size (8x VAE, 2x2 patches, padded)."""
    return ((width // 8 + 1) // 2) * ((height // 8 + 1) // 2)


def pick_megapixels(size, taken):
    for megapixels in REFERENCE_MEGAPIXELS:
        if reference_tokens(size, megapixels) not in taken:
            return megapixels
    return REFERENCE_MEGAPIXELS[0]


def snapref_budget(count):
    """Megapixels one picture is read at when there are `count` of them."""
    return min(1.0, SNAPREF_TOTAL_MEGAPIXELS / max(1, count))


def pick_snapref_megapixels(sizes, count, taken):
    """The node's ref_megapixels for pictures of these sizes: the budget, nudged down until no
    picture has as many tokens as the picture being generated."""
    base = snapref_budget(count)
    for step in REFERENCE_MEGAPIXELS:
        megapixels = round(base * step, 3)
        if all(snapref_tokens(size, megapixels) not in taken for size in sizes):
            return megapixels
    return round(base, 3)


def _partitions(count, limit):
    """Every way to split the numbers 0 .. count-1 into at most `limit` groups."""

    def extend(index, groups):
        if index == count:
            yield [list(g) for g in groups]
            return
        for group in groups:
            group.append(index)
            yield from extend(index + 1, groups)
            group.pop()
        if len(groups) < limit:
            groups.append([index])
            yield from extend(index + 1, groups)
            groups.pop()

    yield from extend(0, [])


def _group_cost(members):
    """How bad it is to put these (width, height, weight) pictures into one node input: they get one
    weight, and one canvas size (the unused part is filled with white)."""
    if len(members) < 2:
        return 0.0
    weights = [m[2] for m in members]
    # at the same area, a picture of aspect a measures sqrt(a) x 1/sqrt(a)
    widths = [(m[0] / m[1]) ** 0.5 for m in members]
    heights = [(m[1] / m[0]) ** 0.5 for m in members]
    unused = len(members) * (1.0 - 1.0 / (max(widths) * max(heights)))
    return 10.0 * (max(weights) - min(weights)) + unused


def group_pictures(pictures, limit=SNAPREF_SLOTS):
    """pictures: [(width, height, weight)]. Returns groups of indices, at most `limit` groups: each
    group goes into one image input of the SnapRef node. Up to `limit` pictures get an input each.
    With more, the pictures that share an input are the ones closest in weight and shape."""
    count = len(pictures)
    if count <= limit:
        return [[i] for i in range(count)]
    best = None
    for groups in _partitions(count, limit):
        cost = sum(_group_cost([pictures[i] for i in group]) for group in groups)
        key = (round(cost, 6), groups)
        if best is None or key < best:
            best = key
    return best[1]


def set_engines(models, v2, snap):
    """Enter what the server has into the AI plugin's own resource list (kept per connection).
    v2 / snap: the Anima Ref Adapter and SnapRef file names, or None."""
    ids = state.resource_ids
    models.resources[ids[CHARACTER]] = v2 or snap  # Reference works with either node
    models.resources[ids[STYLE]] = snap
    models.resources[ids[EXTRA]] = snap
    models.resources[ids["face_lora"]] = FACE_LORA_PLACEHOLDER if snap else None


def _need(condition, what):
    if not condition:
        raise RuntimeError("AI Image Diffusion looks different than expected: " + what)


def _set(owner, name, value):
    original = getattr(owner, name)
    _keep_alive.extend((original, value))
    state.originals.append((owner, name, original))
    setattr(owner, name, value)


def _restore():
    while state.originals:
        owner, name, original = state.originals.pop()
        try:
            setattr(owner, name, original)
        except Exception:
            pass


def install():
    """Wrap the AI plugin's functions. Safe to call more than once. Never raises."""
    if state.installed:
        return state
    try:
        _install()
        state.installed = True
        state.error = ""
        note = "" if state.tested else " (this version is untested, the checks passed)"
        _logger().info(
            "Anima Reference add-on " + ADDON_VERSION + ": active for AI Image Diffusion "
            + state.plugin_version + note
        )
    except Exception as e:
        _restore()
        state.installed = False
        state.error = type(e).__name__ + ": " + str(e)
        _logger().error("Anima Reference add-on could not start:\n" + traceback.format_exc())
    return state


def uninstall():
    """Undo install(). Used by tests; in Krita, disabling the add-on does the same on restart."""
    _restore()
    try:
        from ai_diffusion.backend.resources import Arch
        from ai_diffusion.model.control import ControlPresets

        presets = ControlPresets.instance()._presets
        for mode_name in state.presets_added:
            presets.get(mode_name, {}).pop(Arch.anima.name, None)
    except Exception:
        pass
    state.presets_added = []
    try:
        from ai_diffusion.model.root import root

        client = root.connection.client_if_connected
        if client is not None:
            for resource in state.resource_ids.values():
                client.models.resources.pop(resource, None)
    except Exception:
        pass
    state.installed = False


def _install():
    import ai_diffusion
    import ai_diffusion.model.model  # noqa: F401  (must be loaded before model.control, they import each other)
    from ai_diffusion.backend import api, comfy_client, resources, workflow
    from ai_diffusion.backend import client as client_module
    from ai_diffusion.backend.comfy_workflow import ComfyWorkflow, Output
    from ai_diffusion.image import Extent, Image
    from ai_diffusion.model import control as control_module
    from ai_diffusion.style import StyleSettings
    from ai_diffusion.util import PluginError
    try:  # Krita 5
        from PyQt5.QtCore import Qt
    except ImportError:  # Krita 6
        from PyQt6.QtCore import Qt

    state.plugin_version = str(getattr(ai_diffusion, "__version__", "unknown"))
    state.tested = state.plugin_version in TESTED_VERSIONS

    Arch = resources.Arch
    ControlMode = resources.ControlMode
    ResourceKind = resources.ResourceKind
    WorkflowKind = api.WorkflowKind
    ControlInput = api.ControlInput
    ControlLayer = control_module.ControlLayer
    ComfyClient = comfy_client.ComfyClient

    # ---- Checks first: nothing is changed unless all of them pass ------------------------------

    def params(function):
        return list(inspect.signature(function).parameters)

    _need(hasattr(Arch, "anima"), "no Anima support")
    for name in ("reference", "style", "face"):
        _need(hasattr(ControlMode, name), "ControlMode." + name)
    _need(params(workflow.create)[:2] == ["i", "models"], "workflow.create")
    _need(comfy_client.create_workflow is workflow.create, "comfy_client.create_workflow")
    _need(
        params(workflow.apply_regional_ip_adapter) == ["w", "model", "regions", "shape", "models"],
        "workflow.apply_regional_ip_adapter",
    )
    _need(params(workflow.apply_attention_mask)[:4] == ["w", "model", "cond", "clip"], "workflow.apply_attention_mask")
    _need("models" in params(workflow.prepare), "workflow.prepare")
    _need(params(ComfyClient._refresh_models)[:2] == ["self", "nodes"], "ComfyClient._refresh_models")
    _need(params(ControlLayer.to_api) == ["self", "bounds", "time"], "ControlLayer.to_api")
    _need(params(ControlLayer._update_is_supported) == ["self"], "ControlLayer._update_is_supported")
    _need(hasattr(ControlLayer, "strength_multiplier"), "ControlLayer.strength_multiplier")
    for name in ("add", "add_cached", "load_image", "load_vae", "batch_image"):
        _need(hasattr(ComfyWorkflow, name), "ComfyWorkflow." + name)
    for name in ("create", "scale", "draw_image"):
        _need(hasattr(Image, name), "Image." + name)
    _need(hasattr(client_module.ModelDict, "vae"), "ModelDict.vae")
    for name in ("generate", "inpaint", "refine", "refine_region", "upscale_tiled"):
        _need(hasattr(WorkflowKind, name), "WorkflowKind." + name)

    roles = {ControlMode.reference: CHARACTER, ControlMode.style: STYLE, ControlMode.face: EXTRA}
    resource_of = {
        role: resources.resource_id(ResourceKind.ip_adapter, Arch.anima, mode) for mode, role in roles.items()
    }
    state.resource_ids = dict(resource_of)
    state.resource_ids["face_lora"] = resources.resource_id(ResourceKind.lora, Arch.anima, ControlMode.face)
    state.resource_id = resource_of[CHARACTER]
    default_vae = StyleSettings.vae.default
    kinds = (
        WorkflowKind.generate,
        WorkflowKind.inpaint,
        WorkflowKind.refine,
        WorkflowKind.refine_region,
        WorkflowKind.upscale_tiled,
    )

    original_refresh = ComfyClient._refresh_models
    original_supported = ControlLayer._update_is_supported
    original_to_api = ControlLayer.to_api
    original_prepare = workflow.prepare
    original_create = workflow.create
    original_attention = workflow.apply_attention_mask
    original_regional = workflow.apply_regional_ip_adapter
    prepare_signature = inspect.signature(original_prepare)

    # ---- 1. Notice the nodes when the plugin lists what the server has ------------------------

    def register_engines(models, nodes):
        v2, snap, inputs = None, None, ()
        if nodes and ADAPTER_NODE in nodes:
            v2 = pick_adapter(nodes.options(ADAPTER_NODE, "lora_name"))
        if nodes and SNAPREF_NODE in nodes:
            inputs = tuple((nodes.inputs(SNAPREF_NODE) or {}).keys())
            if all(name in inputs for name in SNAPREF_NEEDS):
                snap = pick_snapref(nodes.options(SNAPREF_NODE, "adapter"))
            else:
                _logger().warning("Anima Reference add-on: the SnapRef node on the server is too old (run install.bat)")
        state.snapref_inputs = inputs
        set_engines(models, v2, snap)
        _logger().info(
            "Anima Reference add-on: Anima Ref Adapter " + (str(v2) if v2 else "not found")
            + ", SnapRef " + (str(snap) if snap else "not found")
        )

    def engines(models):
        """(Anima Ref Adapter file, SnapRef file) on this server; None where one is missing."""
        reference = models.resources.get(resource_of[CHARACTER])
        return (reference if is_v2_file(reference) else None), (models.resources.get(resource_of[STYLE]) or None)

    def _refresh_models(self, nodes, *args, **kwargs):
        result = original_refresh(self, nodes, *args, **kwargs)
        try:
            register_engines(self.models, nodes)
        except Exception:
            _logger().error("Anima Reference add-on:\n" + traceback.format_exc())
        return result

    # ---- 2. Control layer: is it usable, and what image is sent -------------------------------

    def role_of(control):
        """character / style / extra for a Reference / Style / Face layer in an Anima document."""
        try:
            if control._model.arch is Arch.anima:
                return roles.get(control.mode)
        except Exception:
            pass
        return None

    def _update_is_supported(self):
        original_supported(self)
        try:
            role = role_of(self)
            if self.is_supported or role is None:
                return
            from ai_diffusion.model.root import root

            client = root.connection.client_if_connected
            if client is not None and not client.models.resources.get(resource_of[role]):
                self.error_text = MISSING_NODE_TEXT if role == CHARACTER else MISSING_SNAPREF_TEXT
        except Exception:
            pass

    def to_api(self, bounds=None, time=None):
        if role_of(self) is None:
            return original_to_api(self, bounds, time)

        layer = self.layer
        if not self.is_supported:
            raise PluginError("Can't use '" + layer.name + "' as control layer: " + self.error_text)
        if layer.bounds.is_zero:
            raise PluginError(
                "Reference layer '" + layer.name + "' is empty (or entirely outside the canvas). "
                "Pick the layer that holds the reference picture in the control layer's dropdown."
            )
        # The whole layer content, like the plugin does for every reference. The IP-Adapter path
        # then shrinks it to 224 x 224 for CLIP vision; these nodes read the picture itself.
        image = layer.get_pixels(None, time)
        image.make_opaque(background=Qt.GlobalColor.white)
        image = shrink(image, MAX_REFERENCE_PIXELS)
        strength = self.strength / self.strength_multiplier
        return ControlInput(self.mode, image, strength, (self.start, self.end))

    def shrink(image, pixels):
        """The picture scaled down to at most this many pixels (never up)."""
        area = image.width * image.height
        if area <= pixels:
            return image
        factor = (pixels / area) ** 0.5
        return Image.scale(image, Extent(max(1, round(image.width * factor)), max(1, round(image.height * factor))))

    def same_size(pictures, megapixels):
        """Pictures that share one input of the SnapRef node travel as a batch, so they need one
        size: each is brought to the same area, then centred on a white canvas that fits them all."""
        if len(pictures) < 2 or not all(hasattr(p, "_qimage") for p in pictures):
            return pictures
        area = min(megapixels * 1024 * 1024, max(p.width * p.height for p in pictures))
        scaled = []
        for picture in pictures:
            factor = (area / (picture.width * picture.height)) ** 0.5
            extent = Extent(max(1, round(picture.width * factor)), max(1, round(picture.height * factor)))
            scaled.append(Image.scale(picture, extent))
        width, height = max(p.width for p in scaled), max(p.height for p in scaled)
        canvases = []
        for picture in scaled:
            canvas = Image.create(Extent(width, height), fill=Qt.GlobalColor.white)
            canvas.draw_image(picture, ((width - picture.width) // 2, (height - picture.height) // 2))
            canvases.append(canvas)
        return canvases

    # ---- 3. Workflow: which references, which node, and where it goes -------------------------

    def collect_references(cond):
        """(role, control) for every Reference / Style / Face layer: the ones on the root prompt in
        list order, then the ones attached to regions ordered by where the region sits (left first)."""
        found = [(roles.get(c.mode), c) for c in cond.control]
        regional = []
        for region in cond.regions:
            for c in region.control:
                regional.append((region.bounds.x + region.bounds.width / 2, len(regional), (roles.get(c.mode), c)))
        regional.sort(key=lambda entry: entry[:2])
        found += [entry[2] for entry in regional]
        return [(role, c) for role, c in found if role is not None and c.image is not None]

    def plan(i, models):
        """Context for this job, or None if it has no Anima reference. Raises PluginError with a
        message meant for the user when the request cannot work."""
        checkpoint, cond = i.models, i.conditioning
        if checkpoint is None or cond is None or i.kind not in kinds:
            return None
        if checkpoint.version is not Arch.anima:
            return None
        rows = collect_references(cond)
        if not rows:
            return None
        characters = [(role, c) for role, c in rows if role != EXTRA]
        extras = [c for role, c in rows if role == EXTRA]
        if not characters:  # only Face layers: the first one is the character
            characters, extras = [(CHARACTER, extras[0])], extras[1:]
        want_style = any(role == STYLE for role, _ in characters)
        v2, snap = engines(models)

        if len(characters) > MAX_REFERENCES:
            raise PluginError(
                "Anima can show two different characters at most, and there are " + str(len(characters))
                + " Reference/Style layers. For more pictures of the same character, set the extra layers to Face."
            )
        if extras and len(characters) > 1:
            raise PluginError(
                "Face layers (more pictures of one character) only work with a single Reference or Style layer. "
                "With two characters, use one picture each."
            )
        if len(characters) + len(extras) > MAX_PICTURES:
            raise PluginError(
                "Anima takes up to " + str(MAX_PICTURES) + " reference pictures of one character (found "
                + str(len(characters) + len(extras)) + ")."
            )

        needs_snapref = want_style or bool(extras)
        if len(cond.regions) > 1:  # the plugin adds its region node; SnapRef must stay out
            if needs_snapref:
                raise PluginError(
                    "Style and Face layers can't be combined with Regions on Anima (SnapRef and Krita's region "
                    "node don't work in one job). Use Reference layers with Regions, or generate without regions."
                )
            if not v2:
                raise PluginError(
                    "Reference together with Regions needs the Anima Ref Adapter on the server. "
                    "Run install.bat from the Anima Reference package, then restart Krita."
                )
            engine = "v2"
        elif needs_snapref:
            if not snap:
                raise PluginError(
                    "Style and Face layers with an Anima style need SnapRef on the server. Run install.bat from "
                    "the Anima Reference package and answer Y at the SnapRef step, then restart Krita."
                )
            engine = "snapref"
        elif snap and (options.get("prefer_snapref") or not v2):
            engine = "snapref"
        elif v2:
            engine = "v2"
        else:
            raise PluginError(
                "Reference with an Anima style needs the Anima Ref Adapter on the server. "
                "Run install.bat from the Anima Reference package, then restart Krita."
            )

        vae_name = checkpoint.vae if checkpoint.vae and checkpoint.vae != default_vae else None
        taken = generation_tokens(i)
        if engine == "v2":
            references = [c for _, c in characters]
            cfg = i.sampling.cfg_scale if i.sampling is not None else RECOMMENDED_GUIDANCE
            strength = sum(c.strength for c in references) / len(references)
            end = max(c.range[1] for c in references)
            images = [c.image for c in references]
            who = "1 character" if len(images) == 1 else "2 characters side by side"
            context = _Context("v2", vae_name, pick_megapixels(reference_size(images), taken), "")
            context.images = images
            context.ref_guidance = ref_guidance_for(strength, cfg)
            context.ref_end = round(min(1.0, max(0.0, float(end))), 2)
            context.lora_name = v2
            context.description = "Anima Ref Adapter: " + who + ", ref_guidance " + str(context.ref_guidance)
            return context
        return plan_snapref(characters, extras, want_style, snap, vae_name, taken)

    def plan_snapref(characters, extras, want_style, adapter, vae_name, taken):
        what = "character and style" if want_style else "character"
        if len(characters) == 2:  # two characters: one reference picture, left and right
            pair = [c for _, c in characters]
            weight = snapref_weight(sum(c.strength for c in pair) / len(pair))
            if weight < MIN_WEIGHT:
                return None
            images = [c.image for c in pair]
            megapixels = pick_snapref_megapixels([reference_size(images)], 1, taken)
            groups, stitch = [(images, weight)], True
            who = "2 characters side by side, weight " + str(weight)
        else:
            pictures = [(c.image, snapref_weight(c.strength)) for c in [characters[0][1]] + extras]
            pictures = [(image, weight) for image, weight in pictures if weight >= MIN_WEIGHT]
            if not pictures:
                return None
            budget = snapref_budget(len(pictures))
            pictures = [(shrink(image, int(budget * 1024 * 1024)), weight) for image, weight in pictures]
            groups, stitch = [], False
            for indices in group_pictures([(image.width, image.height, weight) for image, weight in pictures]):
                weight = round(sum(pictures[n][1] for n in indices) / len(indices), 2)
                groups.append((same_size([pictures[n][0] for n in indices], budget), weight))
            sizes = [(members[0].width, members[0].height) for members, _ in groups]
            megapixels = pick_snapref_megapixels(sizes, len(pictures), taken)
            count = str(len(pictures)) + (" picture" if len(pictures) == 1 else " pictures of one character")
            who = count + ", weight " + " / ".join(str(weight) for _, weight in pictures)
        context = _Context("snapref", vae_name, megapixels, "SnapRef (" + what + "): " + who)
        context.adapter = adapter
        context.mode = "cs" if want_style else "char"
        context.groups = groups
        context.stitch = stitch
        return context

    def generation_tokens(i):
        """Token counts of every size this job generates at (first pass, hi-res pass)."""
        taken = set()
        try:
            extents = [i.images.extent.initial, i.images.extent.desired] if i.images is not None else []
            if i.crop_upscale_extent is not None:
                extents.append(i.crop_upscale_extent)
            for extent in extents:
                taken.add(target_tokens(extent.width, extent.height))
        except Exception:
            pass
        return taken

    def chain_has(w, model, class_type):
        """True if the chain of nodes that produced this MODEL output contains the node type."""
        node_id = str(model.node)
        for _ in range(200):
            node = w.root.get(node_id)
            if node is None:
                return False
            if node["class_type"] == class_type:
                return True
            source = node["inputs"].get("model")
            if not (isinstance(source, (list, tuple)) and len(source) == 2):
                return False
            node_id = str(source[0])
        return False

    def is_anima_job(i):
        return i is not None and i.models is not None and i.models.version is Arch.anima

    def without_placeholder(i):
        """Take out the FaceID LoRA entry the plugin adds for Face layers (see FACE_LORA_PLACEHOLDER)."""
        loras = getattr(i.models, "loras", None)
        if loras and any(lora.name == FACE_LORA_PLACEHOLDER for lora in loras):
            i.models.loras = [lora for lora in loras if lora.name != FACE_LORA_PLACEHOLDER]

    def prepare(*args, **kwargs):
        i = original_prepare(*args, **kwargs)
        if not is_anima_job(i):
            return i
        without_placeholder(i)
        # Inpainting with an empty prompt normally feeds the surrounding picture to the reference
        # model as a mild hint. These nodes copy characters, so that would paste the people
        # around the hole into it. Only layers the user marked as Reference / Style / Face are used.
        if i.inpaint is not None and getattr(i.inpaint, "use_reference", False):
            i.inpaint.use_reference = False
        models = prepare_signature.bind(*args, **kwargs).arguments["models"]
        plan(i, models)  # raises here, before the job is queued, if it cannot work
        return i

    def create(i, models, *args, **kwargs):
        context = None
        if is_anima_job(i):
            without_placeholder(i)
            if i.inpaint is not None and getattr(i.inpaint, "use_reference", False):
                i.inpaint.use_reference = False
            context = plan(i, models)
            if context is not None:
                state.last_job = context.description
        previous = getattr(_local, "context", None), getattr(_local, "clip", None)
        _local.context, _local.clip = context, None
        try:
            return original_create(i, models, *args, **kwargs)
        finally:
            _local.context, _local.clip = previous

    def apply_attention_mask(w, model, cond, clip, *args, **kwargs):
        # Called right before apply_regional_ip_adapter everywhere: the text encoder for SnapRef.
        _local.clip = getattr(clip, "model", None)
        return original_attention(w, model, cond, clip, *args, **kwargs)

    def find_text_encoder(w):
        for node_id, node in w.root.items():
            if node.get("class_type") in ("CLIPLoader", "CLIPLoaderGGUF"):
                return Output(int(node_id), 0)
        return None

    def apply_adapter(w, model, models, context):
        reference = w.__dict__.get("_anima_reference_image")
        if reference is None:
            loaded = [w.load_image(image) for image in context.images]
            reference = side_by_side(w, loaded)
            w.__dict__["_anima_reference_image"] = reference
        vae = w.load_vae(context.vae_name or models.vae)
        # With regions the adapter's extra reference-off call is misread by the region node
        # (see the notes at the top), so no extra call there: ref_guidance 1.
        ref_guidance = 1.0 if chain_has(w, model, REGION_NODE) else context.ref_guidance
        return w.add_cached(
            ADAPTER_NODE,
            1,
            model=model,
            vae=vae,
            image=reference,
            lora_name=context.lora_name,
            ref_guidance=ref_guidance,
            correction="apg",
            strength=1.0,
            ref_end=context.ref_end,
            ref_megapixels=context.ref_megapixels,
        )

    def side_by_side(w, loaded):
        reference = loaded[0]
        for other in loaded[1:]:  # as in both nodes' two-character workflows
            reference = w.add(
                "ImageStitch",
                1,
                image1=reference,
                image2=other,
                direction="right",
                match_image_size=True,
                spacing_width=0,
                spacing_color="white",
            )
        return reference

    def apply_snapref(w, model, models, context):
        if chain_has(w, model, REGION_NODE):  # plan() refuses this already; never let it through
            raise PluginError("Style and Face layers can't be combined with Regions on Anima.")
        clip = getattr(_local, "clip", None) or find_text_encoder(w)
        if clip is None:
            raise PluginError("Anima Reference add-on: the workflow has no text encoder node for SnapRef.")
        inputs = w.__dict__.get("_anima_snapref_inputs")
        if inputs is None:
            inputs = []
            for pictures, weight in context.groups:
                loaded = [w.load_image(picture) for picture in pictures]
                if context.stitch:
                    image = side_by_side(w, loaded)
                else:
                    image = loaded[0]
                    for other in loaded[1:]:
                        image = w.batch_image(image, other)
                inputs.append((image, weight))
            w.__dict__["_anima_snapref_inputs"] = inputs
        vae = w.load_vae(context.vae_name or models.vae)
        values = dict(
            model=model,
            clip=clip,
            vae=vae,
            image=inputs[0][0],
            adapter=context.adapter,
            mode=context.mode,
            ref_in_uncond=False,
            ref_megapixels=context.ref_megapixels,
            strength=0.0,
            ref_caption="",
            ref_guidance_on=False,
            use_batch=not context.stitch and any(len(pictures) > 1 for pictures, _ in context.groups),
            multi_layout="separate",
            fidelity=1.0,
        )
        for index, (image, weight) in enumerate(inputs, start=1):
            values["weight_" + str(index)] = weight
            if index > 1:
                values["image_" + str(index)] = image
        if state.snapref_inputs:  # only what this server's node knows
            values = {name: value for name, value in values.items() if name in state.snapref_inputs}
        return w.add_cached(SNAPREF_NODE, 1, **values)

    def apply_regional_ip_adapter(w, model, regions, shape, models):
        model = original_regional(w, model, regions, shape, models)
        context = getattr(_local, "context", None)
        if context is None or models.arch is not Arch.anima:
            return model
        if context.engine == "snapref":
            return apply_snapref(w, model, models, context)
        return apply_adapter(w, model, models, context)

    # ---- Install ------------------------------------------------------------------------------

    _set(ComfyClient, "_refresh_models", _refresh_models)
    _set(ControlLayer, "_update_is_supported", _update_is_supported)
    _set(ControlLayer, "to_api", to_api)
    _set(workflow, "prepare", prepare)
    _set(workflow, "create", create)
    _set(comfy_client, "create_workflow", create)
    _set(workflow, "apply_attention_mask", apply_attention_mask)
    _set(workflow, "apply_regional_ip_adapter", apply_regional_ip_adapter)

    # Strength presets for Reference / Style / Face + Anima, unless the user defined their own.
    try:
        presets = control_module.ControlPresets.instance()._presets
        for mode in roles:
            by_arch = presets.setdefault(mode.name, {})
            if Arch.anima.name not in by_arch:
                by_arch[Arch.anima.name] = [dict(p) for p in PRESETS]
                state.presets_added.append(mode.name)
    except Exception:
        _logger().warning("Anima Reference add-on: could not add strength presets")

    # If Krita is already connected (add-on started late), look at the server right away.
    try:
        from ai_diffusion.model.root import root

        client = root.connection.client_if_connected
        if isinstance(client, ComfyClient):
            register_engines(client.models, client.models.node_inputs)
    except Exception:
        pass


def status_text() -> str:
    """Plain-language status, shown by Tools > Scripts > Anima Reference."""
    lines = ["Anima Reference add-on " + ADDON_VERSION, ""]
    if not state.installed:
        if state.error:
            lines.append("NOT ACTIVE.")
            lines.append("")
            lines.append("This add-on was made for AI Image Diffusion " + ", ".join(TESTED_VERSIONS) + ".")
            lines.append("The installed version is " + (state.plugin_version or "unknown") + " and works differently inside:")
            lines.append(state.error)
            lines.append("")
            lines.append("Nothing was changed. Reference with Anima styles stays off until the add-on")
            lines.append("is updated; everything else in the AI plugin works as before.")
        else:
            lines.append("NOT ACTIVE: the AI Image Diffusion plugin is not loaded.")
            lines.append("Check that it is ticked in Settings > Configure Krita > Python Plugin Manager.")
        return "\n".join(lines)

    tested = "tested version" if state.tested else "untested version, checks passed"
    lines.append("AI Image Diffusion " + state.plugin_version + " (" + tested + ")")
    lines.append("Add-on: active")
    try:
        from ai_diffusion.model.root import root

        client = root.connection.client_if_connected
    except Exception:
        client = None
    if client is None:
        lines.append("Server: not connected yet - check again once the AI docker shows Connected")
        return "\n".join(lines)

    reference = client.models.resources.get(state.resource_ids.get(CHARACTER, state.resource_id))
    snap = client.models.resources.get(state.resource_ids.get(STYLE, "")) or None
    v2 = reference if is_v2_file(reference) else None
    lines.append("Server: connected")
    lines.append("Anima Ref Adapter: " + ("found (" + str(v2) + ")" if v2 else "NOT FOUND on the server"))
    lines.append("SnapRef: " + ("found (" + str(snap) + ")" if snap else "not found on the server"))
    lines.append("")
    if not v2 and not snap:
        lines.append("Close Krita, run install.bat from the Anima Reference package, start Krita again.")
        return "\n".join(lines)
    lines.append("Ready. Control layers that work with an Anima style:")
    use_snap = bool(snap) and (options.get("prefer_snapref") or not v2)
    lines.append("  Reference - a character; two layers = left and right character   ["
                 + ("SnapRef" if use_snap else "Anima Ref Adapter") + "]")
    if snap:
        lines.append("  Style - like Reference, and the picture's art style is taken too   [SnapRef]")
        lines.append("  Face - one more picture of the same character, up to " + str(MAX_PICTURES) + " in total   [SnapRef]")
    else:
        lines.append("  Style and Face need SnapRef: run install.bat again and answer Y at the SnapRef step.")
    if state.last_job:
        lines.append("")
        lines.append("Last job: " + state.last_job)
    return "\n".join(lines)