File size: 45,092 Bytes
2d5d005
 
 
 
 
 
 
 
 
 
 
 
 
2ac2b96
 
2d5d005
 
 
 
 
 
2ac2b96
2d5d005
 
 
2ac2b96
 
 
2d5d005
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b53c956
2d5d005
b53c956
 
 
 
 
 
 
 
 
 
2ac2b96
fbf0a2e
 
b53c956
 
 
 
 
 
 
 
 
 
 
 
 
 
2d5d005
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2ac2b96
2d5d005
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2ac2b96
 
 
2d5d005
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2ac2b96
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2d5d005
 
 
 
 
 
 
 
b53c956
 
 
 
 
 
 
 
 
2d5d005
b53c956
2d5d005
 
 
 
 
 
 
 
 
 
 
 
2ac2b96
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35addf4
2ac2b96
 
 
35addf4
2ac2b96
 
 
 
 
 
 
 
 
2d5d005
 
 
 
b53c956
2d5d005
 
 
 
 
 
 
 
 
 
b53c956
 
 
 
 
 
 
 
35addf4
 
b53c956
 
 
 
 
 
 
 
 
 
 
2d5d005
 
35addf4
 
2d5d005
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b53c956
2d5d005
b53c956
 
 
 
 
 
2d5d005
b53c956
 
 
 
 
2d5d005
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
#!/bin/bash

source /venv/main/bin/activate
COMFYUI_DIR=workspace/ComfyUI

# Packages are installed after nodes so we can fix them...

APT_PACKAGES=(
    #"package-1"
    #"package-2"
)

PIP_PACKAGES=(
    "google-genai"
    "xai-sdk"
)

NODES=(
    "https://github.com/city96/ComfyUI-GGUF"
    "https://github.com/kijai/ComfyUI-KJNodes"
    "https://github.com/Suzie1/ComfyUI_Comfyroll_CustomNodes"
    "https://github.com/pythongosssss/ComfyUI-Custom-Scripts"
)

WORKFLOWS=(
    "https://huggingface.co/nathanglm/sofia/resolve/main/ZIT%20v6.json"
    "https://huggingface.co/nathanglm/sofia/resolve/main/EXTRACTOR%20v1.json"
    "https://huggingface.co/nathanglm/sofia/resolve/main/NANO%20BANANA%20v1.json"
)

SAMS=(
    "https://huggingface.co/datasets/Gourieff/ReActor/resolve/main/models/sams/sam_vit_b_01ec64.pth"
)


CHECKPOINT_MODELS=(
    "https://civitai.com/api/download/models/2155386" # SDXL-Lustify
)

BBOX=(
    "https://huggingface.co/nathanglm/sofia/resolve/main/Eyes.pt"
    "https://huggingface.co/nathanglm/sofia/resolve/main/Face.pt"
    "https://huggingface.co/nathanglm/sofia/resolve/main/Foot.pt"
    "https://huggingface.co/nathanglm/sofia/resolve/main/Hands.pt"
    "https://huggingface.co/nathanglm/sofia/resolve/main/Nipples.pt"
    "https://huggingface.co/nathanglm/sofia/resolve/main/Pussy.pt"
    "https://huggingface.co/nathanglm/sofia/resolve/main/Pussy2.pt"
    "https://huggingface.co/nathanglm/sofia/resolve/main/Penis.pt"
)

UNET_MODELS=(
    "https://huggingface.co/jayn7/Z-Image-Turbo-GGUF/resolve/main/z_image_turbo-Q8_0.gguf"
)

# Format: "URL|filename.safetensors"
LORA_MODELS=(
    "https://huggingface.co/nathanglm/sofia/resolve/main/Sofia.safetensors|ZIT-Sofia.safetensors"
    "https://huggingface.co/Finesse365/Anya-Lora/resolve/main/ZIT-Anya.safetensors|ZIT-Anya.safetensors"
    "https://civitai.com/api/download/models/2483794?type=Model&format=SafeTensor&size=full&fp=fp16|ZIT-Asian-To-Caucasian.safetensors"
    "https://civitai.com/api/download/models/2534692?type=Model&format=SafeTensor&size=full&fp=fp16|ZIT-Hands-XL-v2.1.safetensors"
    "https://civitai.com/api/download/models/2536073?type=Model&format=SafeTensor&size=full&fp=fp16|ZIT-Feet-XL-v2.1.safetensors"
    "https://civitai.com/api/download/models/2581135?type=Model&format=SafeTensor&size=full&fp=fp16|ZIT-Mystic-v5.safetensors"
    "https://civitai.com/api/download/models/2452071?type=Model&format=SafeTensor&size=full&fp=fp16|ZIT-Lenovo-v1.safetensors"
    "https://civitai.com/api/download/models/2617751?type=Model&format=SafeTensor&size=full&fp=fp16|ZIT-Realistic-Snapshot-v5.safetensors"
    "https://civitai.com/api/download/models/2513043?type=Model&format=SafeTensor&size=full&fp=fp16|ZIT-Hip-Slider-v1.safetensors"
    "https://civitai.com/api/download/models/2510875?type=Model&format=SafeTensor&size=full&fp=fp16|ZIT-Breast-Slider-v1.safetensors"
    "https://civitai.com/api/download/models/2088956?type=Model&format=SafeTensor&size=full&fp=fp16|ZIT-Famegird-2nd-Gen-Spicy.safetensors"
    #"https://civitai.com/api/download/models/550216?type=Model&format=SafeTensor&size=full&fp=fp16|SDXL-Lady-Hands-v1.safetensors"
    #"https://civitai.com/api/download/models/139194?type=Model&format=SafeTensor&size=full&fp=fp16|SDXL-Real-Feet-v1.safetensors"
    "https://civitai.com/api/download/models/368603?type=Model&format=SafeTensor&size=full&fp=fp16|SDXL-Detailed-Nipples-v1.safetensors"
    "https://civitai.com/api/download/models/1604857?type=Model&format=SafeTensor&size=full&fp=fp16|SDXL-Real-Pussy-Peach.safetensors"
    "https://civitai.com/api/download/models/1511445?type=Model&format=SafeTensor&size=full&fp=fp16|SDXL-Real-Pussy-Spreading.safetensors"
    "https://civitai.com/api/download/models/1284103?type=Model&format=SafeTensor&size=full&fp=fp16|SDXL-Real-Pussy-Butterfly.safetensors"
    "https://civitai.com/api/download/models/802232?type=Model&format=SafeTensor&size=full&fp=fp16|SDXL-Real-Pussy-Cameltoe.safetensors"
    "https://civitai.com/api/download/models/712004?type=Model&format=SafeTensor&size=full&fp=fp16|SDXL-Real-Pussy-Lotte.safetensors"
    "https://civitai.com/api/download/models/262705?type=Model&format=SafeTensor&size=full&fp=fp16|SDXL-Real-Humans-v1.safetensors"
    "https://civitai.com/api/download/models/216946?type=Model&format=SafeTensor&size=full&fp=fp16|SDXL-Penis-XL-v1.safetensors"
    "https://civitai.com/api/download/models/707763?type=Model&format=SafeTensor&size=full&fp=fp16|SDXL-Realistic-Skin-Texture-v4.safetensors"
    "https://civitai.com/api/download/models/341068?type=Model&format=SafeTensor&size=full&fp=fp16|SDXL-NSFW-XL-v2.1.safetensors"
    "https://civitai.com/api/download/models/1506027?type=Model&format=SafeTensor&size=full&fp=fp16|SDXL-Add-Detail-Slider-v1.2.safetensors"
    "https://civitai.com/api/download/models/1934796?type=Model&format=SafeTensor&size=full&fp=fp16|SDXL-touch-of-Realism-v2.safetensors"
    "https://civitai.com/api/download/models/535064?type=Model&format=SafeTensor&size=full&fp=fp16|SDXL-Breast-Size-Slider-v1.safetensors"
    "https://civitai.com/api/download/models/1242203?type=Model&format=SafeTensor&size=full&fp=fp16|SDXL-Dramatic-Lighting-Slider-v1.safetensors"
)

VAE_MODELS=(
    "https://huggingface.co/Comfy-Org/z_image_turbo/resolve/main/split_files/vae/ae.safetensors"
)

DIFFUSION_MODELS=(
    "https://huggingface.co/Comfy-Org/z_image_turbo/resolve/main/split_files/diffusion_models/z_image_turbo_bf16.safetensors"
)

TEXT_ENCODERS=(
    "https://huggingface.co/Comfy-Org/z_image_turbo/resolve/main/split_files/text_encoders/qwen_3_4b.safetensors"
)

ESRGAN_MODELS=(
)

CONTROLNET_MODELS=(
)

### DO NOT EDIT BELOW HERE UNLESS YOU KNOW WHAT YOU ARE DOING ###

function provisioning_start() {
    provisioning_print_header
    provisioning_get_apt_packages
    provisioning_get_nodes
    provisioning_get_pip_packages
    provisioning_create_nanobananapro
    provisioning_get_files \
        "${COMFYUI_DIR}/models/sams" \
        "${SAMS[@]}"
    provisioning_get_files \
        "${COMFYUI_DIR}/models/checkpoints" \
        "${CHECKPOINT_MODELS[@]}"
    provisioning_get_files \
        "${COMFYUI_DIR}/models/ultralytics/bbox" \
        "${BBOX[@]}"
    provisioning_get_files \
        "${COMFYUI_DIR}/models/unet" \
        "${UNET_MODELS[@]}"
    provisioning_get_files \
        "${COMFYUI_DIR}/models/loras" \
        "${LORA_MODELS[@]}"
    provisioning_get_files \
        "${COMFYUI_DIR}/models/diffusion_models" \
        "${DIFFUSION_MODELS[@]}"
    provisioning_get_files \
        "${COMFYUI_DIR}/models/text_encoders" \
        "${TEXT_ENCODERS[@]}"
    provisioning_get_files \
        "${COMFYUI_DIR}/models/controlnet" \
        "${CONTROLNET_MODELS[@]}"
    provisioning_get_files \
        "${COMFYUI_DIR}/models/vae" \
        "${VAE_MODELS[@]}"
    provisioning_get_files \
        "${COMFYUI_DIR}/user/default/workflows" \
        "${WORKFLOWS[@]}"
    provisioning_get_files \
        "${COMFYUI_DIR}/models/esrgan" \
        "${ESRGAN_MODELS[@]}"
    provisioning_print_end
}

function provisioning_get_apt_packages() {
    if [[ -n $APT_PACKAGES ]]; then
            sudo $APT_INSTALL ${APT_PACKAGES[@]}
    fi
}

function provisioning_get_pip_packages() {
    if [[ -n $PIP_PACKAGES ]]; then
            pip install --no-cache-dir ${PIP_PACKAGES[@]}
    fi
}

function provisioning_get_nodes() {
    for repo in "${NODES[@]}"; do
        dir="${repo##*/}"
        path="${COMFYUI_DIR}/custom_nodes/${dir}"
        requirements="${path}/requirements.txt"
        if [[ -d $path ]]; then
            if [[ ${AUTO_UPDATE,,} != "false" ]]; then
                printf "Updating node: %s...\n" "${repo}"
                ( cd "$path" && git pull )
                if [[ -e $requirements ]]; then
                   pip install --no-cache-dir -r "$requirements"
                fi
            fi
        else
            printf "Downloading node: %s...\n" "${repo}"
            git clone "${repo}" "${path}" --recursive
            if [[ -e $requirements ]]; then
                pip install --no-cache-dir -r "${requirements}"
            fi
        fi
    done
}

function provisioning_create_nanobananapro() {
    local NBP_DIR="${COMFYUI_DIR}/custom_nodes/NanoBananaPro"
    printf "Creating NanoBananaPro custom nodes...\n"
    mkdir -p "${NBP_DIR}"

    # ── nano_banana_pro_node.py ────────────────────────────────────────────────
    cat > "${NBP_DIR}/nano_banana_pro_node.py" << 'ENDOFFILE'
"""
🍌 Nano Banana Pro Node β€” ComfyUI
Supporte :
  - Nano Banana 2    = gemini-3.1-flash-image-preview  (NOUVEAU, recommandΓ©)
  - Nano Banana Pro  = gemini-3-pro-image-preview       (⚠️ déprécié le 9 mars 2026)
  - Nano Banana      = gemini-2.5-flash-image           (stable, rapide)
Modes :
  - generate : text-to-image pur
  - edit      : image editing (envoyer une image + prompt)
RΓ©solutions : 0.5K, 1K, 2K, 4K
"""

import torch, numpy as np, io, random
from PIL import Image, ImageEnhance

def pil_to_tensor(image):
    img = image.convert("RGB")
    arr = np.array(img).astype(np.float32) / 255.0
    return torch.from_numpy(arr).unsqueeze(0)

def tensor_to_pil(tensor):
    arr = tensor.squeeze(0).numpy()
    arr = (arr * 255).clip(0, 255).astype(np.uint8)
    return Image.fromarray(arr)

def pil_to_bytes(image):
    buf = io.BytesIO()
    image.save(buf, format="PNG")
    return buf.getvalue()

def apply_color_grade(image, brightness, contrast, saturation, temperature, sharpness):
    img = image.convert("RGB")
    if brightness != 1.0:
        img = ImageEnhance.Brightness(img).enhance(brightness)
    if contrast != 1.0:
        img = ImageEnhance.Contrast(img).enhance(contrast)
    if saturation != 1.0:
        img = ImageEnhance.Color(img).enhance(saturation)
    if temperature != 0.0:
        r, g, b = img.split()
        r_arr = np.array(r, dtype=np.float32)
        b_arr = np.array(b, dtype=np.float32)
        strength = abs(temperature) * 30
        if temperature > 0:
            r_arr = np.clip(r_arr + strength, 0, 255)
            b_arr = np.clip(b_arr - strength * 0.5, 0, 255)
        else:
            r_arr = np.clip(r_arr - strength * 0.5, 0, 255)
            b_arr = np.clip(b_arr + strength, 0, 255)
        img = Image.merge("RGB", (
            Image.fromarray(r_arr.astype(np.uint8)),
            g,
            Image.fromarray(b_arr.astype(np.uint8))
        ))
    if sharpness != 1.0:
        img = ImageEnhance.Sharpness(img).enhance(sharpness)
    return img


class NanaBananaProNode:
    MODELS = [
        "gemini-3.1-flash-image-preview",
        "gemini-2.5-flash-image",
        "gemini-3-pro-image-preview",
    ]
    MODES     = ["generate", "edit"]
    SAFETY    = ["OFF", "BLOCK_ONLY_HIGH", "BLOCK_MEDIUM_AND_ABOVE", "BLOCK_LOW_AND_ABOVE"]
    RATIOS    = ["1:1", "9:16", "16:9", "2:3", "3:2", "4:3", "3:4", "21:9", "1:4", "4:1"]
    QUALITY   = ["1K", "2K", "4K", "0.5K"]
    AFTER_GEN = ["randomize", "fixed", "increment"]

    @classmethod
    def INPUT_TYPES(cls):
        return {
            "required": {
                "prompt":                 ("STRING",  {"default": "A stunning photorealistic portrait, ultra detailed", "multiline": True}),
                "model":                  (cls.MODELS,),
                "mode":                   (cls.MODES,),
                "aspect_ratio":           (cls.RATIOS,),
                "quality":                (cls.QUALITY,),
                "temperature":            ("FLOAT",   {"default": 1.0,  "min": 0.0,  "max": 2.0,  "step": 0.05}),
                "top_p":                  ("FLOAT",   {"default": 0.95, "min": 0.0,  "max": 1.0,  "step": 0.01}),
                "top_k":                  ("INT",     {"default": 0,    "min": 0,    "max": 100,  "step": 1}),
                "seed":                   ("INT",     {"default": -1,   "min": -1,   "max": 2**31,"step": 1}),
                "control_after_generate": (cls.AFTER_GEN,),
                "safety_threshold":       (cls.SAFETY,),
                "api_key":                ("STRING",  {"default": "YOUR_GEMINI_API_KEY"}),
                "cg_brightness":          ("FLOAT",   {"default": 1.0, "min": 0.1, "max": 3.0, "step": 0.05}),
                "cg_contrast":            ("FLOAT",   {"default": 1.0, "min": 0.1, "max": 3.0, "step": 0.05}),
                "cg_saturation":          ("FLOAT",   {"default": 1.0, "min": 0.0, "max": 3.0, "step": 0.05}),
                "cg_temperature":         ("FLOAT",   {"default": 0.0, "min": -1.0,"max": 1.0, "step": 0.05}),
                "cg_sharpness":           ("FLOAT",   {"default": 1.0, "min": 0.0, "max": 3.0, "step": 0.05}),
            },
            "optional": {
                "edit_image":   ("IMAGE",),
                "ref_image_1":  ("IMAGE",),
                "ref_image_2":  ("IMAGE",),
                "ref_image_3":  ("IMAGE",),
                "ref_image_4":  ("IMAGE",),
                "ref_image_5":  ("IMAGE",),
                "ref_image_6":  ("IMAGE",),
                "ref_image_7":  ("IMAGE",),
            }
        }

    RETURN_TYPES = ("IMAGE", "STRING")
    RETURN_NAMES = ("image", "metadata")
    FUNCTION     = "generate"
    CATEGORY     = "🍌 Nano Banana Pro"

    def generate(self, prompt, model, mode, aspect_ratio, quality, temperature, top_p, top_k,
                 seed, control_after_generate, safety_threshold, api_key,
                 cg_brightness, cg_contrast, cg_saturation, cg_temperature, cg_sharpness,
                 edit_image=None, ref_image_1=None, ref_image_2=None, ref_image_3=None,
                 ref_image_4=None, ref_image_5=None, ref_image_6=None, ref_image_7=None):
        try:
            from google import genai
            from google.genai import types
        except ImportError:
            raise ImportError("Lance : pip install google-genai")

        if seed == -1 or control_after_generate == "randomize":
            actual_seed = random.randint(0, 2**31)
        elif control_after_generate == "increment":
            actual_seed = seed + 1
        else:
            actual_seed = seed

        client = genai.Client(api_key=api_key)

        safety_settings = []
        if safety_threshold != "OFF":
            harm_categories = [
                "HARM_CATEGORY_HARASSMENT",
                "HARM_CATEGORY_HATE_SPEECH",
                "HARM_CATEGORY_SEXUALLY_EXPLICIT",
                "HARM_CATEGORY_DANGEROUS_CONTENT"
            ]
            safety_settings = [types.SafetySetting(category=cat, threshold=safety_threshold) for cat in harm_categories]

        parts = []

        if mode == "edit" and edit_image is not None:
            parts.append(types.Part.from_bytes(
                data=pil_to_bytes(tensor_to_pil(edit_image)),
                mime_type="image/png"
            ))

        ref_images = [ref_image_1, ref_image_2, ref_image_3, ref_image_4,
                      ref_image_5, ref_image_6, ref_image_7]
        for ref in ref_images:
            if ref is not None:
                parts.append(types.Part.from_bytes(
                    data=pil_to_bytes(tensor_to_pil(ref)),
                    mime_type="image/png"
                ))

        parts.append(types.Part.from_text(text=prompt))

        gen_config_kwargs = dict(
            response_modalities=["TEXT", "IMAGE"],
            temperature=temperature,
            top_p=top_p,
            image_config=types.ImageConfig(
                aspect_ratio=aspect_ratio,
                image_size=quality
            ),
        )
        if top_k > 0:
            gen_config_kwargs["top_k"] = top_k
        if safety_settings:
            gen_config_kwargs["safety_settings"] = safety_settings

        gen_config = types.GenerateContentConfig(**gen_config_kwargs)

        print(f"[NanaBanana] -> {model} | mode:{mode} | quality:{quality} | safety:{safety_threshold}")

        response = client.models.generate_content(
            model=model,
            contents=parts,
            config=gen_config
        )

        if not response.candidates:
            raise RuntimeError(f"[NanaBanana] Aucun candidat: {response}")

        candidate = response.candidates[0]
        finish_reason = str(getattr(candidate, "finish_reason", ""))
        if "SAFETY" in finish_reason:
            raise RuntimeError("[NanaBanana] Bloque par IMAGE_SAFETY. Reformule le prompt.")

        content = getattr(candidate, "content", None)
        if content is None or not getattr(content, "parts", None):
            raise RuntimeError(f"[NanaBanana] Content vide. finish_reason: {finish_reason}")

        result_image, info_text = None, ""
        for part in content.parts:
            if hasattr(part, "text") and part.text:
                info_text += part.text + "\n"
            elif hasattr(part, "inline_data") and part.inline_data:
                result_image = Image.open(io.BytesIO(part.inline_data.data)).convert("RGB")

        if result_image is None:
            raise RuntimeError(f"[NanaBanana] Aucune image generee. Texte: {info_text or '(aucun)'}")

        result_image = apply_color_grade(
            result_image,
            cg_brightness, cg_contrast, cg_saturation, cg_temperature, cg_sharpness
        )

        metadata = (
            f"model: {model}\n"
            f"mode: {mode}\n"
            f"seed: {actual_seed}\n"
            f"temperature: {temperature} | top_p: {top_p} | top_k: {top_k}\n"
            f"aspect_ratio: {aspect_ratio} | quality: {quality}\n"
            f"safety: {safety_threshold}\n"
            f"{info_text.strip()}"
        )
        print(f"[NanaBanana] Succes ! ({quality})")
        return (pil_to_tensor(result_image), metadata)


NODE_CLASS_MAPPINGS = {"NanaBananaProNode": NanaBananaProNode}
NODE_DISPLAY_NAME_MAPPINGS = {"NanaBananaProNode": "🍌 Nano Banana Pro"}
ENDOFFILE

    # ── anya_prompt_extractor_node.py ──────────────────────────────────────────
    cat > "${NBP_DIR}/anya_prompt_extractor_node.py" << 'ENDOFFILE'
import torch, numpy as np, io, json
from PIL import Image

def tensor_to_pil(tensor):
    arr = tensor.squeeze(0).numpy()
    arr = (arr * 255).clip(0, 255).astype(np.uint8)
    return Image.fromarray(arr)

def pil_to_bytes(image):
    buf = io.BytesIO()
    image.save(buf, format="PNG")
    return buf.getvalue()

def build_system_prompt(anya_desc, include_anya, include_l3n0v0, breast_size, style_hint, use_ref_images, num_refs, ref_descs_list):
    breast_map = {"small": "small perky breasts", "medium": "medium-sized natural breasts, visible cleavage", "large": "large full breasts with natural weight", "huge": "very large breasts, voluptuous silhouette"}
    breast_desc = breast_map.get(breast_size, "medium-sized natural breasts")
    triggers = []
    if include_anya: triggers.append("Anya")
    if include_l3n0v0: triggers.append("l3n0v0")
    triggers_str = json.dumps(triggers)
    if include_anya:
        subject_block = f'  "subject": {{"name": "Anya", "ethnicity": "Asian", "hair": "...", "skin_tone": "...", "breast_size": "{breast_desc}", "body": "wide hips, prominent round BBL-style butt, thick thighs, hourglass figure", "face": "full lips, almond-shaped eyes, long lashes, natural makeup", "jewelry": "...", "pose": "...", "expression": "...", "gaze": "..."}}'
        subject_instruction = f"## ANYA FIXED CHARACTER\n{anya_desc}\nBreast size: {breast_desc}\nHips: wide hips, prominent round BBL-style butt, thick thighs\nInject into subject section, never modify physical traits."
    else:
        subject_block = '  "subject": {"description": "...", "pose": "...", "expression": "...", "gaze": "..."}'
        subject_instruction = "## SUBJECT\nDescribe the subject from the reference image exactly. Reproduce face, hair, skin tone, body proportions 1:1. No changes, no beautification."
    if use_ref_images and num_refs > 0:
        ref_labels = ["subject_identity"] + [f"reference_image_{i}" for i in range(2, num_refs+1)]
        ref_entries = []
        for i in range(num_refs):
            label = ref_labels[i] if i < len(ref_labels) else f"reference_image_{i+1}"
            desc = ref_descs_list[i] if i < len(ref_descs_list) and ref_descs_list[i].strip() else f"uploaded_reference_image_{i+1}"
            ref_entries.append(f'    "{label}": "{desc}"')
        ref_block = '  "reference_images": {\n' + ',\n'.join(ref_entries) + '\n  },'
        ref_instruction = f"## REFERENCE IMAGES\n{num_refs} reference image(s):\n" + "\n".join([f"- Image {i+1}: {ref_descs_list[i] if i < len(ref_descs_list) else 'reference'}" for i in range(num_refs)])
    else:
        ref_block = ""
        ref_instruction = "## REFERENCE IMAGES\nNo reference images."
    ref_section = f"\n{ref_block}" if ref_block else ""
    inject_note = "Inject the fixed Anya character description into subject." if include_anya else "Describe subject exactly as seen in the reference image, 1:1 accuracy."
    return f"""You are an expert AI image prompt engineer specializing in structured JSON prompts.
{subject_instruction}
{ref_instruction}
## OUTPUT RULES
- Return ONLY valid JSON, no markdown, no backticks, no explanation
- trigger_words must be exactly: {triggers_str}
{{
  "trigger_words": {triggers_str},{ref_section}
  "output_quality": {{"resolution": "4K", "definition": "ultra high resolution", "sharpness": "natural realistic detail, not overprocessed"}},
{subject_block},
  "outfit": {{"description": "...", "colors": [...], "fit": "...", "fabric": "..."}},
  "location": {{"setting": "...", "environment": [...], "time_of_day": "...", "lighting": "...", "atmosphere": "..."}},
  "image_type": {{"orientation": "...", "aspect_ratio": "...", "style": "{style_hint}", "camera_feel": "...", "color_grading": "..."}},
  "identity_preservation": {{"facial_identity": "...", "no_changes": ["bone_structure", "facial_proportions", "skin_tone", "hairline", "facial_features"], "no_beautification": true, "no_stylization": true}},
  "realism_constraints": {{"no_extra_limbs": true, "no_ai_symmetry_correction": true, "natural_skin_texture": true, "natural_light_behavior": true, "no_heavy_color_grading": true}},
  "image_feel": [...]
}}
Analyze the provided image(s): extract scene, lighting, pose, outfit, mood. {inject_note} Return ONLY the JSON."""

class AnyaPromptExtractor:
    MODELS       = ["gemini-2.5-flash-preview-05-20", "gemini-2.5-flash", "gemini-2.5-pro", "gemini-3-pro-image-preview"]
    BREAST_SIZES = ["small", "medium", "large", "huge"]
    NUM_REFS     = ["0", "1", "2", "3", "4", "5"]

    @classmethod
    def INPUT_TYPES(cls):
        return {
            "required": {
                "api_key":                ("STRING",  {"default": "YOUR_GEMINI_API_KEY"}),
                "model":                  (cls.MODELS,),
                "include_trigger_anya":   ("BOOLEAN", {"default": True}),
                "include_trigger_l3n0v0": ("BOOLEAN", {"default": True}),
                "breast_size_override":   (cls.BREAST_SIZES,),
                "anya_base_description":  ("STRING",  {"default": "Anya is an Asian woman with long straight black hair, medium-sized natural breasts, wide hips and a prominent BBL-style butt, thick thighs. She has full lips, almond-shaped eyes with long lashes, tan warm skin tone, and usually wears gold jewelry.", "multiline": True}),
                "style_hint":             ("STRING",  {"default": "natural high-end lifestyle, candid editorial"}),
                "json_indent":            ("INT",     {"default": 4, "min": 0, "max": 8, "step": 1}),
                "use_reference_images":   ("BOOLEAN", {"default": True}),
                "num_reference_images":   (cls.NUM_REFS,),
                "ref_1_description":      ("STRING",  {"default": "subject identity β€” main model reference"}),
                "ref_2_description":      ("STRING",  {"default": "outfit reference"}),
                "ref_3_description":      ("STRING",  {"default": "location or background reference"}),
                "ref_4_description":      ("STRING",  {"default": "style or mood reference"}),
                "ref_5_description":      ("STRING",  {"default": "additional reference"}),
            },
            "optional": {
                "scene_image":  ("IMAGE",),
                "ref_image_1":  ("IMAGE",),
                "ref_image_2":  ("IMAGE",),
                "ref_image_3":  ("IMAGE",),
                "ref_image_4":  ("IMAGE",),
                "ref_image_5":  ("IMAGE",),
            }
        }

    RETURN_TYPES = ("STRING", "IMAGE", "IMAGE", "IMAGE", "IMAGE", "IMAGE", "IMAGE")
    RETURN_NAMES = ("prompt_json", "scene_passthrough", "ref_1_passthrough", "ref_2_passthrough", "ref_3_passthrough", "ref_4_passthrough", "ref_5_passthrough")
    FUNCTION     = "extract"
    CATEGORY     = "🍌 Nano Banana Pro"
    OUTPUT_NODE  = True

    def extract(self, api_key, model, include_trigger_anya, include_trigger_l3n0v0,
                breast_size_override, anya_base_description, style_hint, json_indent,
                use_reference_images, num_reference_images,
                ref_1_description, ref_2_description, ref_3_description,
                ref_4_description, ref_5_description,
                scene_image=None, ref_image_1=None, ref_image_2=None,
                ref_image_3=None, ref_image_4=None, ref_image_5=None):
        try:
            from google import genai
            from google.genai import types
        except ImportError:
            raise ImportError("Lance : pip install google-genai")
        num_refs = int(num_reference_images)
        ref_descs_list = [ref_1_description, ref_2_description, ref_3_description, ref_4_description, ref_5_description]
        system_prompt = build_system_prompt(anya_base_description, include_trigger_anya, include_trigger_l3n0v0, breast_size_override, style_hint, use_reference_images, num_refs, ref_descs_list)
        client = genai.Client(api_key=api_key)
        parts = []
        if scene_image is not None:
            parts.append(types.Part.from_bytes(data=pil_to_bytes(tensor_to_pil(scene_image)), mime_type="image/png"))
        if use_reference_images and num_refs > 0:
            ref_images_list = [ref_image_1, ref_image_2, ref_image_3, ref_image_4, ref_image_5]
            for i in range(min(num_refs, 5)):
                ref = ref_images_list[i]
                if ref is not None:
                    desc = ref_descs_list[i] if ref_descs_list[i].strip() else f"reference image {i+1}"
                    parts.append(types.Part.from_text(text=f"[Reference image {i+1}: {desc}]"))
                    parts.append(types.Part.from_bytes(data=pil_to_bytes(tensor_to_pil(ref)), mime_type="image/png"))
        if not parts:
            parts.append(types.Part.from_text(text="No image provided. Generate a generic lifestyle JSON prompt. Return ONLY the JSON."))
        else:
            parts.append(types.Part.from_text(text="Analyze the provided image(s) and generate the structured JSON prompt. Return ONLY the JSON."))
        config = types.GenerateContentConfig(system_instruction=system_prompt, response_modalities=["TEXT"], temperature=0.4, top_p=0.9)
        print(f"[AnyaExtractor] -> {model} | Anya:{include_trigger_anya} | l3n0v0:{include_trigger_l3n0v0} | refs:{num_refs if use_reference_images else 0}")
        response = client.models.generate_content(model=model, contents=parts, config=config)
        raw_parts = response.parts or []
        raw_text = "".join(part.text for part in raw_parts if hasattr(part, "text") and part.text).strip()
        if not raw_text and hasattr(response, "candidates") and response.candidates:
            raw_text = "".join(part.text for part in (response.candidates[0].content.parts or []) if hasattr(part, "text") and part.text).strip()
        if not raw_text:
            raise RuntimeError(f"[AnyaExtractor] Reponse vide. Modele: {model} | Verifier la cle API ou changer de modele.")
        if raw_text.startswith("```"):
            lines = raw_text.split("\n")
            raw_text = "\n".join(lines[1:-1] if lines[-1].strip() == "```" else lines[1:]).strip()
        try:
            parsed = json.loads(raw_text)
            tw = parsed.get("trigger_words", [])
            if include_trigger_anya and "Anya" not in tw: tw.insert(0, "Anya")
            if not include_trigger_anya and "Anya" in tw: tw.remove("Anya")
            if include_trigger_l3n0v0 and "l3n0v0" not in tw: tw.append("l3n0v0")
            if not include_trigger_l3n0v0 and "l3n0v0" in tw: tw.remove("l3n0v0")
            parsed["trigger_words"] = tw
            output_json = json.dumps(parsed, indent=json_indent, ensure_ascii=False)
        except json.JSONDecodeError as e:
            print(f"[AnyaExtractor] JSON invalide: {e}")
            output_json = raw_text
        print(f"[AnyaExtractor] Succes ({len(output_json)} chars)")
        empty = torch.zeros(1, 64, 64, 3)
        return (output_json, scene_image if scene_image is not None else empty, ref_image_1 if ref_image_1 is not None else empty, ref_image_2 if ref_image_2 is not None else empty, ref_image_3 if ref_image_3 is not None else empty, ref_image_4 if ref_image_4 is not None else empty, ref_image_5 if ref_image_5 is not None else empty)

NODE_CLASS_MAPPINGS = {"AnyaPromptExtractor": AnyaPromptExtractor}
NODE_DISPLAY_NAME_MAPPINGS = {"AnyaPromptExtractor": "πŸ” Anya Prompt Extractor"}
ENDOFFILE

    # ── grok_prompt_extractor_node.py ──────────────────────────────────────────
    cat > "${NBP_DIR}/grok_prompt_extractor_node.py" << 'ENDOFFILE'
import torch, numpy as np, io, base64
from PIL import Image

def tensor_to_pil(tensor):
    arr = tensor.squeeze(0).numpy()
    arr = (arr * 255).clip(0, 255).astype(np.uint8)
    return Image.fromarray(arr)

def pil_to_bytes(image):
    buf = io.BytesIO()
    image.save(buf, format="PNG")
    return buf.getvalue()

def image_to_base64(image):
    return base64.b64encode(pil_to_bytes(image)).decode("utf-8")

def build_system_prompt(anya_desc, include_anya, include_l3n0v0, breast_size, style_hint, word_count):
    breast_map = {
        "small":  "small perky breasts",
        "medium": "medium-sized natural breasts with visible cleavage",
        "large":  "large full breasts with natural weight and deep cleavage",
        "huge":   "very large heavy breasts, extremely voluptuous silhouette"
    }
    breast_desc = breast_map.get(breast_size, "medium-sized natural breasts with visible cleavage")
    triggers = []
    if include_anya:   triggers.append("Anya")
    if include_l3n0v0: triggers.append("l3n0v0")
    trigger_line = ", ".join(triggers)
    if include_anya:
        char_instruction = f"""## ANYA β€” FIXED PHYSICAL CHARACTER
{anya_desc}
Breast size: {breast_desc}
Body: wide hips, prominent round BBL-style butt, thick thighs, hourglass figure, slim waist
Face: full pouty lips, almond-shaped eyes with long lashes, warm tan Asian skin, high cheekbones
Jewelry: gold hoop earrings, gold chain necklace, gold bracelets
## REPLACEMENT RULE
Anya replaces the person in the image EXACTLY.
- Same pose, same expression, same gaze, same position in frame
- Same outfit worn on Anya's body β€” describe how each garment fits her curves
- Same location, same lighting, same background, same props
- Only the physical identity changes to Anya"""
        subject_block = f"Anya, Asian woman, long straight black hair, warm tan skin, full pouty lips, almond eyes with long lashes, {breast_desc}, wide hips, round prominent BBL butt, thick thighs, hourglass figure, slim waist, gold jewelry"
    else:
        char_instruction = "## SUBJECT\nDescribe the subject exactly as seen. Be extremely precise about every physical detail."
        subject_block = "the person in the image"
    inject = f"Replace the subject with: {subject_block}" if include_anya else "Describe the subject exactly as visible."
    return f"""You are a professional text-to-image prompt writer specializing in photorealistic NSFW adult content generation. You write prompts for Stable Diffusion, Flux, and similar models.
{char_instruction}
## YOUR MISSION
Analyze the image with forensic precision. Write a single continuous text-to-image prompt of exactly {word_count} words.
The prompt must be so detailed that an AI image generator can reproduce the scene perfectly.
## TEXT-TO-IMAGE PROMPT RULES
- Write as comma-separated descriptive phrases, NOT sentences
- Start with trigger words, then subject, then body details, then outfit, then pose, then location, then lighting, then camera, then mood
- Use text-to-image vocabulary: "photorealistic, 8k uhd, RAW photo, sharp focus, f/1.8, 85mm lens, bokeh, cinematic lighting" etc
- Be EXTREMELY explicit about body proportions, clothing fit, skin exposure
- Describe exactly what is visible β€” if cleavage is showing, describe it precisely
- If outfit is tight/revealing, describe exactly how it fits on the body
- Never use euphemisms β€” describe body parts and clothing directly and explicitly
- No sentences, no paragraph structure β€” pure prompt style
## STRUCTURE TO FOLLOW
1. Trigger words: {trigger_line},
2. Subject physical description (face, hair, skin, eyes, lips, body)
3. Breast description and how visible/covered they are
4. Exact outfit β€” every garment, color, fabric, fit, how tight, what skin is exposed
5. Exact pose β€” body position, limb placement, weight, angles
6. Hands and arm positions
7. Expression and gaze direction
8. Location β€” exact setting, architecture, materials, colors
9. Background elements one by one
10. Lighting β€” source, direction, quality, color temperature, how it hits skin and clothing
11. Camera β€” shot type, angle, focal length, depth of field
12. Technical quality tags
13. Mood and atmosphere tags
## NSFW DESCRIPTION RULES
- Describe clothing tightness and fit on the body explicitly
- Describe visible skin areas precisely (neckline depth, leg exposure, midriff, back)
- Describe breast shape and how they appear in the outfit
- Describe butt shape and how outfit fits on it
- Use direct anatomical and fashion terminology
- If any body part is prominent or featured in the image, describe it in detail
## CRITICAL
- {word_count} words minimum
- Pure text-to-image prompt format β€” no prose, no sentences
- Every single visual detail from the image must be captured
- {inject}
- Return ONLY the prompt text, nothing else"""

class GrokPromptExtractor:
    MODELS = ["grok-2-vision-1212", "grok-2-vision"]
    BREAST_SIZES = ["small", "medium", "large", "huge"]

    @classmethod
    def INPUT_TYPES(cls):
        return {
            "required": {
                "api_key":                ("STRING",  {"default": "YOUR_XAI_API_KEY"}),
                "model":                  (cls.MODELS,),
                "include_trigger_anya":   ("BOOLEAN", {"default": True}),
                "include_trigger_l3n0v0": ("BOOLEAN", {"default": True}),
                "breast_size_override":   (cls.BREAST_SIZES,),
                "anya_base_description":  ("STRING",  {"default": "Anya is an Asian woman with long straight black hair, medium-sized natural breasts, wide hips and a prominent BBL-style butt, thick thighs. She has full lips, almond-shaped eyes with long lashes, tan warm skin tone, and usually wears gold jewelry.", "multiline": True}),
                "style_hint":             ("STRING",  {"default": "RAW photo, photorealistic, candid shot, natural lighting, 8k uhd"}),
                "word_count":             ("INT",     {"default": 450, "min": 200, "max": 800, "step": 50}),
            },
            "optional": {
                "image": ("IMAGE",),
            }
        }

    RETURN_TYPES = ("STRING", "IMAGE")
    RETURN_NAMES = ("prompt_text", "image_passthrough")
    FUNCTION     = "extract"
    CATEGORY     = "πŸ€– Grok xAI"
    OUTPUT_NODE  = True

    def extract(self, api_key, model, include_trigger_anya, include_trigger_l3n0v0,
                breast_size_override, anya_base_description, style_hint, word_count,
                image=None):
        try:
            from xai_sdk import Client
            from xai_sdk.chat import system, user, image as xai_image
        except ImportError:
            raise ImportError("Lance : pip install xai-sdk")
        system_prompt = build_system_prompt(anya_base_description, include_trigger_anya, include_trigger_l3n0v0, breast_size_override, style_hint, word_count)
        client = Client(api_key=api_key)
        chat   = client.chat.create(model=model)
        chat.append(system(system_prompt))
        if image is not None:
            b64      = image_to_base64(tensor_to_pil(image))
            data_url = f"data:image/png;base64,{b64}"
            chat.append(user(
                f"Analyze every detail of this image. Write a {word_count}-word text-to-image prompt. "
                f"Be extremely explicit about body proportions, outfit fit, skin exposure, clothing tightness. "
                f"Pure prompt format β€” comma-separated tags and descriptors, no sentences, no explanations. "
                f"Return ONLY the prompt.",
                xai_image(data_url)
            ))
        else:
            chat.append(user(f"Write a {word_count}-word text-to-image prompt for Anya in a high-end Miami lifestyle scene. Pure prompt format, comma-separated, extremely detailed. Return ONLY the prompt."))
        print(f"[GrokExtractor] -> {model} | Anya:{include_trigger_anya} | l3n0v0:{include_trigger_l3n0v0} | words:{word_count}")
        response = chat.sample()
        output_text = response.content.strip()
        print(f"[GrokExtractor] OK ({len(output_text.split())} words)")
        empty = torch.zeros(1, 64, 64, 3)
        return (output_text, image if image is not None else empty)

NODE_CLASS_MAPPINGS = {"GrokPromptExtractor": GrokPromptExtractor}
NODE_DISPLAY_NAME_MAPPINGS = {"GrokPromptExtractor": "πŸ€– Grok Prompt Extractor"}
ENDOFFILE

    # ── __init__.py ────────────────────────────────────────────────────────────
    cat > "${NBP_DIR}/__init__.py" << 'EOF'
from .nano_banana_pro_node import NODE_CLASS_MAPPINGS as _NM1, NODE_DISPLAY_NAME_MAPPINGS as _DN1
from .anya_prompt_extractor_node import NODE_CLASS_MAPPINGS as _NM2, NODE_DISPLAY_NAME_MAPPINGS as _DN2
from .grok_prompt_extractor_node import NODE_CLASS_MAPPINGS as _NM3, NODE_DISPLAY_NAME_MAPPINGS as _DN3

NODE_CLASS_MAPPINGS = {}
NODE_CLASS_MAPPINGS.update(_NM1)
NODE_CLASS_MAPPINGS.update(_NM2)
NODE_CLASS_MAPPINGS.update(_NM3)

NODE_DISPLAY_NAME_MAPPINGS = {}
NODE_DISPLAY_NAME_MAPPINGS.update(_DN1)
NODE_DISPLAY_NAME_MAPPINGS.update(_DN2)
NODE_DISPLAY_NAME_MAPPINGS.update(_DN3)

__all__ = ["NODE_CLASS_MAPPINGS", "NODE_DISPLAY_NAME_MAPPINGS"]
EOF

    printf "NanoBananaPro nodes created successfully.\n"
}

function provisioning_get_files() {
    if [[ -z $2 ]]; then return 1; fi
    
    dir="$1"
    mkdir -p "$dir"
    shift
    arr=("$@")
    printf "Downloading %s model(s) to %s...\n" "${#arr[@]}" "$dir"
    for entry in "${arr[@]}"; do
        # Support "URL|filename" format for custom filenames
        if [[ "$entry" == *"|"* ]]; then
            url="${entry%%|*}"
            filename="${entry##*|}"
        else
            url="$entry"
            filename=""
        fi
        printf "Downloading: %s\n" "${url}"
        provisioning_download "${url}" "${dir}" "${filename}"
        printf "\n"
    done
}

function provisioning_print_header() {
    printf "\n##############################################\n#                                            #\n#          Provisioning container            #\n#                                            #\n#         This will take some time           #\n#                                            #\n# Your container will be ready on completion #\n#                                            #\n##############################################\n\n"
}

function provisioning_print_end() {
    printf "\nProvisioning complete:  Application will start now\n\n"
}

function provisioning_has_valid_hf_token() {
    [[ -n "$HF_TOKEN" ]] || return 1
    url="https://huggingface.co/api/whoami-v2"

    response=$(curl -o /dev/null -s -w "%{http_code}" -X GET "$url" \
        -H "Authorization: Bearer $HF_TOKEN" \
        -H "Content-Type: application/json")

    if [ "$response" -eq 200 ]; then
        return 0
    else
        return 1
    fi
}

function provisioning_has_valid_civitai_token() {
    [[ -n "a881da881b7c01e808f1fb7843092a11" ]] || return 1
    url="https://civitai.com/api/v1/models?hidden=1&limit=1"

    response=$(curl -o /dev/null -s -w "%{http_code}" -X GET "$url" \
        -H "Authorization: Bearer a881da881b7c01e808f1fb7843092a11" \
        -H "Content-Type: application/json")

    if [ "$response" -eq 200 ]; then
        return 0
        else
        return 1
    fi
}

# Download CivitAI models with curl (pure bash)
function download_civitai_bash() {
    local url="$1"
    local output_dir="$2"
    local forced_filename="$3"
    local model_id=""
    
    if [[ $url =~ /models/([0-9]+) ]]; then
        model_id="${BASH_REMATCH[1]}"
    else
        printf "ERROR: Could not extract model ID from URL\n"
        return 1
    fi
    
    printf "Downloading CivitAI model %s...\n" "$model_id"

    if [[ -n "$forced_filename" ]]; then
        local output_file="${output_dir}/${forced_filename}"
        if [[ -f "$output_file" ]]; then
            printf "File already exists: %s\n" "$forced_filename"
            return 0
        fi
        printf "Downloading to: %s\n" "$forced_filename"
        if [[ -n "a881da881b7c01e808f1fb7843092a11" ]]; then
            curl -L -o "$output_file" --progress-bar -H "Authorization: Bearer a881da881b7c01e808f1fb7843092a11" "$url"
        else
            curl -L -o "$output_file" --progress-bar "$url"
        fi
        if [[ $? -eq 0 ]]; then
            printf "Download completed: %s\n" "$forced_filename"
            return 0
        else
            printf "ERROR: Download failed for model %s\n" "$model_id"
            return 1
        fi
    fi
    
    local redirect_url=""
    if [[ -n "a881da881b7c01e808f1fb7843092a11" ]]; then
        redirect_url=$(curl -s -I -L -H "Authorization: Bearer a881da881b7c01e808f1fb7843092a11" "$url" | grep -i "^location:" | tail -1 | sed 's/location: //i' | tr -d '\r\n')
    else
        redirect_url=$(curl -s -I -L "$url" | grep -i "^location:" | tail -1 | sed 's/location: //i' | tr -d '\r\n')
    fi
    
    if [[ -z "$redirect_url" ]]; then
        printf "ERROR: Could not get redirect URL for model %s\n" "$model_id"
        return 1
    fi
    
    local filename=""
    
    if [[ $redirect_url =~ response-content-disposition=attachment.*filename%3D%22([^%\"]+) ]]; then
        filename="${BASH_REMATCH[1]}"
        filename=$(echo "$filename" | sed 's/%20/ /g; s/%2D/-/g; s/%2E/./g; s/%5F/_/g')
    elif [[ $redirect_url =~ filename=\"([^\"]+)\" ]]; then
        filename="${BASH_REMATCH[1]}"
    elif [[ $redirect_url =~ filename=([^&]+) ]]; then
        filename="${BASH_REMATCH[1]}"
    else
        local path_part=$(echo "$redirect_url" | sed 's/?.*//')
        filename=$(basename "$path_part")
        if [[ ! "$filename" =~ \.(safetensors|pt|pth|ckpt|bin)$ ]]; then
            filename="${filename}.safetensors"
        fi
    fi
    
    filename=$(printf '%b' "${filename//%/\\x}")
    
    if [[ -z "$filename" ]] || [[ "$filename" == "." ]] || [[ "$filename" == ".safetensors" ]]; then
        filename="civitai_${model_id}.safetensors"
    fi
    
    local output_file="${output_dir}/${filename}"
    
    if [[ -f "$output_file" ]]; then
        printf "File already exists: %s\n" "$filename"
        return 0
    fi
    
    printf "Downloading to: %s\n" "$filename"
    curl -L -o "$output_file" --progress-bar "$redirect_url"
    
    if [[ $? -eq 0 ]]; then
        printf "Download completed: %s\n" "$filename"
        return 0
    else
        printf "ERROR: Download failed for model %s\n" "$model_id"
        return 1
    fi
}

# Download from $1 URL to $2 file path, with optional $3 forced filename
function provisioning_download() {
    local url="$1"
    local dir="$2"
    local forced_filename="$3"

    if [[ $url =~ ^https://civitai\.com/api/download/models/([0-9]+) ]]; then
        download_civitai_bash "$url" "$dir" "$forced_filename"
    else
        if [[ -n "$forced_filename" ]]; then
            wget -qnc --show-progress -e dotbytes="${4:-4M}" -O "${dir}/${forced_filename}" "$url"
        else
            wget -qnc --content-disposition --show-progress -e dotbytes="${4:-4M}" -P "$dir" "$url"
        fi
    fi
}

# Allow user to disable provisioning if they started with a script they didn't want
if [[ ! -f /.noprovisioning ]]; then
    provisioning_start
fi