nathanglm commited on
Commit
9b38937
Β·
verified Β·
1 Parent(s): f90cbc4

Upload qwen.sh

Browse files
Files changed (1) hide show
  1. qwen.sh +922 -0
qwen.sh ADDED
@@ -0,0 +1,922 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ source /venv/main/bin/activate
4
+ COMFYUI_DIR=${WORKSPACE}/ComfyUI
5
+
6
+ # Packages are installed after nodes so we can fix them...
7
+
8
+ APT_PACKAGES=(
9
+ #"package-1"
10
+ #"package-2"
11
+ )
12
+
13
+ PIP_PACKAGES=(
14
+ "google-genai"
15
+ "xai-sdk"
16
+ )
17
+
18
+ NODES=(
19
+ "https://github.com/ltdrdata/ComfyUI-Manager"
20
+ "https://github.com/rgthree/rgthree-comfy"
21
+ "https://github.com/ltdrdata/ComfyUI-Impact-Pack"
22
+ "https://github.com/yolain/ComfyUI-Easy-Use"
23
+ "https://github.com/ssitu/ComfyUI_UltimateSDUpscale"
24
+ "https://github.com/sipherxyz/comfyui-art-venture"
25
+ "https://github.com/ltdrdata/ComfyUI-Impact-Subpack"
26
+ "https://github.com/moonwhaler/comfyui-moonpack"
27
+ "https://github.com/gseth/ControlAltAI-Nodes"
28
+ "https://github.com/vrgamegirl19/comfyui-vrgamedevgirl"
29
+ "https://github.com/numz/ComfyUI-SeedVR2_VideoUpscaler"
30
+ "https://github.com/robertvoy/ComfyUI-Flux-Continuum"
31
+ "https://github.com/ltdrdata/was-node-suite-comfyui"
32
+ "https://github.com/ChangeTheConstants/SeedVarianceEnhancer"
33
+ "https://github.com/city96/ComfyUI-GGUF"
34
+ "https://github.com/kijai/ComfyUI-KJNodes"
35
+ "https://github.com/Suzie1/ComfyUI_Comfyroll_CustomNodes"
36
+ "https://github.com/pythongosssss/ComfyUI-Custom-Scripts"
37
+ )
38
+
39
+ WORKFLOWS=(
40
+ )
41
+
42
+ SAMS=(
43
+ "https://huggingface.co/datasets/Gourieff/ReActor/resolve/main/models/sams/sam_vit_b_01ec64.pth"
44
+ )
45
+
46
+
47
+ CHECKPOINT_MODELS=(
48
+ "https://civitai.com/api/download/models/2155386" # SDXL-Lustify
49
+ "https://civitai.com/api/download/models/1621447" # Iniverse
50
+ "https://huggingface.co/Phr00t/Qwen-Image-Edit-Rapid-AIO/resolve/main/v23/Qwen-Rapid-AIO-NSFW-v23.safetensors"
51
+ )
52
+
53
+ BBOX=(
54
+ "https://huggingface.co/nathanglm/sofia/resolve/main/Eyes.pt"
55
+ "https://huggingface.co/nathanglm/sofia/resolve/main/Face.pt"
56
+ "https://huggingface.co/nathanglm/sofia/resolve/main/Foot.pt"
57
+ "https://huggingface.co/nathanglm/sofia/resolve/main/Hands.pt"
58
+ "https://huggingface.co/nathanglm/sofia/resolve/main/Nipples.pt"
59
+ "https://huggingface.co/nathanglm/sofia/resolve/main/Pussy.pt"
60
+ "https://huggingface.co/nathanglm/sofia/resolve/main/Pussy2.pt"
61
+ "https://huggingface.co/nathanglm/sofia/resolve/main/Penis.pt"
62
+ )
63
+
64
+ UNET_MODELS=(
65
+ )
66
+
67
+ # Format: "URL|filename.safetensors"
68
+ LORA_MODELS=(
69
+ )
70
+
71
+ VAE_MODELS=(
72
+ )
73
+
74
+ DIFFUSION_MODELS=(
75
+ )
76
+
77
+ TEXT_ENCODERS=(
78
+ )
79
+
80
+ ESRGAN_MODELS=(
81
+ )
82
+
83
+ CONTROLNET_MODELS=(
84
+ )
85
+
86
+ ### DO NOT EDIT BELOW HERE UNLESS YOU KNOW WHAT YOU ARE DOING ###
87
+
88
+ function provisioning_start() {
89
+ provisioning_print_header
90
+ provisioning_get_apt_packages
91
+ provisioning_get_nodes
92
+ provisioning_get_pip_packages
93
+ provisioning_create_nanobananapro
94
+ provisioning_get_files \
95
+ "${COMFYUI_DIR}/models/sams" \
96
+ "${SAMS[@]}"
97
+ provisioning_get_files \
98
+ "${COMFYUI_DIR}/models/checkpoints" \
99
+ "${CHECKPOINT_MODELS[@]}"
100
+ provisioning_get_files \
101
+ "${COMFYUI_DIR}/models/ultralytics/bbox" \
102
+ "${BBOX[@]}"
103
+ provisioning_get_files \
104
+ "${COMFYUI_DIR}/models/unet" \
105
+ "${UNET_MODELS[@]}"
106
+ provisioning_get_files \
107
+ "${COMFYUI_DIR}/models/loras" \
108
+ "${LORA_MODELS[@]}"
109
+ provisioning_get_files \
110
+ "${COMFYUI_DIR}/models/diffusion_models" \
111
+ "${DIFFUSION_MODELS[@]}"
112
+ provisioning_get_files \
113
+ "${COMFYUI_DIR}/models/text_encoders" \
114
+ "${TEXT_ENCODERS[@]}"
115
+ provisioning_get_files \
116
+ "${COMFYUI_DIR}/models/controlnet" \
117
+ "${CONTROLNET_MODELS[@]}"
118
+ provisioning_get_files \
119
+ "${COMFYUI_DIR}/models/vae" \
120
+ "${VAE_MODELS[@]}"
121
+ provisioning_get_files \
122
+ "${COMFYUI_DIR}/user/default/workflows" \
123
+ "${WORKFLOWS[@]}"
124
+ provisioning_get_files \
125
+ "${COMFYUI_DIR}/models/esrgan" \
126
+ "${ESRGAN_MODELS[@]}"
127
+ provisioning_print_end
128
+ }
129
+
130
+ function provisioning_get_apt_packages() {
131
+ if [[ -n $APT_PACKAGES ]]; then
132
+ sudo $APT_INSTALL ${APT_PACKAGES[@]}
133
+ fi
134
+ }
135
+
136
+ function provisioning_get_pip_packages() {
137
+ if [[ -n $PIP_PACKAGES ]]; then
138
+ pip install --no-cache-dir ${PIP_PACKAGES[@]}
139
+ fi
140
+ }
141
+
142
+ function provisioning_get_nodes() {
143
+ for repo in "${NODES[@]}"; do
144
+ dir="${repo##*/}"
145
+ path="${COMFYUI_DIR}/custom_nodes/${dir}"
146
+ requirements="${path}/requirements.txt"
147
+ if [[ -d $path ]]; then
148
+ if [[ ${AUTO_UPDATE,,} != "false" ]]; then
149
+ printf "Updating node: %s...\n" "${repo}"
150
+ ( cd "$path" && git pull )
151
+ if [[ -e $requirements ]]; then
152
+ pip install --no-cache-dir -r "$requirements"
153
+ fi
154
+ fi
155
+ else
156
+ printf "Downloading node: %s...\n" "${repo}"
157
+ git clone "${repo}" "${path}" --recursive
158
+ if [[ -e $requirements ]]; then
159
+ pip install --no-cache-dir -r "${requirements}"
160
+ fi
161
+ fi
162
+ done
163
+ }
164
+
165
+ function provisioning_create_nanobananapro() {
166
+ local NBP_DIR="${COMFYUI_DIR}/custom_nodes/NanoBananaPro"
167
+ printf "Creating NanoBananaPro custom nodes...\n"
168
+ mkdir -p "${NBP_DIR}"
169
+
170
+ # ── nano_banana_pro_node.py ────────────────────────────────────────────────
171
+ cat > "${NBP_DIR}/nano_banana_pro_node.py" << 'ENDOFFILE'
172
+ """
173
+ 🍌 Nano Banana Pro Node β€” ComfyUI
174
+ Supporte :
175
+ - Nano Banana 2 = gemini-3.1-flash-image-preview (NOUVEAU, recommandΓ©)
176
+ - Nano Banana Pro = gemini-3-pro-image-preview (⚠️ déprécié le 9 mars 2026)
177
+ - Nano Banana = gemini-2.5-flash-image (stable, rapide)
178
+ Modes :
179
+ - generate : text-to-image pur
180
+ - edit : image editing (envoyer une image + prompt)
181
+ RΓ©solutions : 0.5K, 1K, 2K, 4K
182
+ """
183
+
184
+ import torch, numpy as np, io, random
185
+ from PIL import Image, ImageEnhance
186
+
187
+ def pil_to_tensor(image):
188
+ img = image.convert("RGB")
189
+ arr = np.array(img).astype(np.float32) / 255.0
190
+ return torch.from_numpy(arr).unsqueeze(0)
191
+
192
+ def tensor_to_pil(tensor):
193
+ arr = tensor.squeeze(0).numpy()
194
+ arr = (arr * 255).clip(0, 255).astype(np.uint8)
195
+ return Image.fromarray(arr)
196
+
197
+ def pil_to_bytes(image):
198
+ buf = io.BytesIO()
199
+ image.save(buf, format="PNG")
200
+ return buf.getvalue()
201
+
202
+ def apply_color_grade(image, brightness, contrast, saturation, temperature, sharpness):
203
+ img = image.convert("RGB")
204
+ if brightness != 1.0:
205
+ img = ImageEnhance.Brightness(img).enhance(brightness)
206
+ if contrast != 1.0:
207
+ img = ImageEnhance.Contrast(img).enhance(contrast)
208
+ if saturation != 1.0:
209
+ img = ImageEnhance.Color(img).enhance(saturation)
210
+ if temperature != 0.0:
211
+ r, g, b = img.split()
212
+ r_arr = np.array(r, dtype=np.float32)
213
+ b_arr = np.array(b, dtype=np.float32)
214
+ strength = abs(temperature) * 30
215
+ if temperature > 0:
216
+ r_arr = np.clip(r_arr + strength, 0, 255)
217
+ b_arr = np.clip(b_arr - strength * 0.5, 0, 255)
218
+ else:
219
+ r_arr = np.clip(r_arr - strength * 0.5, 0, 255)
220
+ b_arr = np.clip(b_arr + strength, 0, 255)
221
+ img = Image.merge("RGB", (
222
+ Image.fromarray(r_arr.astype(np.uint8)),
223
+ g,
224
+ Image.fromarray(b_arr.astype(np.uint8))
225
+ ))
226
+ if sharpness != 1.0:
227
+ img = ImageEnhance.Sharpness(img).enhance(sharpness)
228
+ return img
229
+
230
+
231
+ class NanaBananaProNode:
232
+ MODELS = [
233
+ "gemini-3.1-flash-image-preview",
234
+ "gemini-2.5-flash-image",
235
+ "gemini-3-pro-image-preview",
236
+ ]
237
+ MODES = ["generate", "edit"]
238
+ SAFETY = ["OFF", "BLOCK_ONLY_HIGH", "BLOCK_MEDIUM_AND_ABOVE", "BLOCK_LOW_AND_ABOVE"]
239
+ RATIOS = ["1:1", "9:16", "16:9", "2:3", "3:2", "4:3", "3:4", "21:9", "1:4", "4:1"]
240
+ QUALITY = ["1K", "2K", "4K", "0.5K"]
241
+ AFTER_GEN = ["randomize", "fixed", "increment"]
242
+
243
+ @classmethod
244
+ def INPUT_TYPES(cls):
245
+ return {
246
+ "required": {
247
+ "prompt": ("STRING", {"default": "A stunning photorealistic portrait, ultra detailed", "multiline": True}),
248
+ "model": (cls.MODELS,),
249
+ "mode": (cls.MODES,),
250
+ "aspect_ratio": (cls.RATIOS,),
251
+ "quality": (cls.QUALITY,),
252
+ "temperature": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 2.0, "step": 0.05}),
253
+ "top_p": ("FLOAT", {"default": 0.95, "min": 0.0, "max": 1.0, "step": 0.01}),
254
+ "top_k": ("INT", {"default": 0, "min": 0, "max": 100, "step": 1}),
255
+ "seed": ("INT", {"default": -1, "min": -1, "max": 2**31,"step": 1}),
256
+ "control_after_generate": (cls.AFTER_GEN,),
257
+ "safety_threshold": (cls.SAFETY,),
258
+ "api_key": ("STRING", {"default": "YOUR_GEMINI_API_KEY"}),
259
+ "cg_brightness": ("FLOAT", {"default": 1.0, "min": 0.1, "max": 3.0, "step": 0.05}),
260
+ "cg_contrast": ("FLOAT", {"default": 1.0, "min": 0.1, "max": 3.0, "step": 0.05}),
261
+ "cg_saturation": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 3.0, "step": 0.05}),
262
+ "cg_temperature": ("FLOAT", {"default": 0.0, "min": -1.0,"max": 1.0, "step": 0.05}),
263
+ "cg_sharpness": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 3.0, "step": 0.05}),
264
+ },
265
+ "optional": {
266
+ "edit_image": ("IMAGE",),
267
+ "ref_image_1": ("IMAGE",),
268
+ "ref_image_2": ("IMAGE",),
269
+ "ref_image_3": ("IMAGE",),
270
+ "ref_image_4": ("IMAGE",),
271
+ "ref_image_5": ("IMAGE",),
272
+ "ref_image_6": ("IMAGE",),
273
+ "ref_image_7": ("IMAGE",),
274
+ }
275
+ }
276
+
277
+ RETURN_TYPES = ("IMAGE", "STRING")
278
+ RETURN_NAMES = ("image", "metadata")
279
+ FUNCTION = "generate"
280
+ CATEGORY = "🍌 Nano Banana Pro"
281
+
282
+ def generate(self, prompt, model, mode, aspect_ratio, quality, temperature, top_p, top_k,
283
+ seed, control_after_generate, safety_threshold, api_key,
284
+ cg_brightness, cg_contrast, cg_saturation, cg_temperature, cg_sharpness,
285
+ edit_image=None, ref_image_1=None, ref_image_2=None, ref_image_3=None,
286
+ ref_image_4=None, ref_image_5=None, ref_image_6=None, ref_image_7=None):
287
+ try:
288
+ from google import genai
289
+ from google.genai import types
290
+ except ImportError:
291
+ raise ImportError("Lance : pip install google-genai")
292
+
293
+ if seed == -1 or control_after_generate == "randomize":
294
+ actual_seed = random.randint(0, 2**31)
295
+ elif control_after_generate == "increment":
296
+ actual_seed = seed + 1
297
+ else:
298
+ actual_seed = seed
299
+
300
+ client = genai.Client(api_key=api_key)
301
+
302
+ safety_settings = []
303
+ if safety_threshold != "OFF":
304
+ harm_categories = [
305
+ "HARM_CATEGORY_HARASSMENT",
306
+ "HARM_CATEGORY_HATE_SPEECH",
307
+ "HARM_CATEGORY_SEXUALLY_EXPLICIT",
308
+ "HARM_CATEGORY_DANGEROUS_CONTENT"
309
+ ]
310
+ safety_settings = [types.SafetySetting(category=cat, threshold=safety_threshold) for cat in harm_categories]
311
+
312
+ parts = []
313
+
314
+ if mode == "edit" and edit_image is not None:
315
+ parts.append(types.Part.from_bytes(
316
+ data=pil_to_bytes(tensor_to_pil(edit_image)),
317
+ mime_type="image/png"
318
+ ))
319
+
320
+ ref_images = [ref_image_1, ref_image_2, ref_image_3, ref_image_4,
321
+ ref_image_5, ref_image_6, ref_image_7]
322
+ for ref in ref_images:
323
+ if ref is not None:
324
+ parts.append(types.Part.from_bytes(
325
+ data=pil_to_bytes(tensor_to_pil(ref)),
326
+ mime_type="image/png"
327
+ ))
328
+
329
+ parts.append(types.Part.from_text(text=prompt))
330
+
331
+ gen_config_kwargs = dict(
332
+ response_modalities=["TEXT", "IMAGE"],
333
+ temperature=temperature,
334
+ top_p=top_p,
335
+ image_config=types.ImageConfig(
336
+ aspect_ratio=aspect_ratio,
337
+ image_size=quality
338
+ ),
339
+ )
340
+ if top_k > 0:
341
+ gen_config_kwargs["top_k"] = top_k
342
+ if safety_settings:
343
+ gen_config_kwargs["safety_settings"] = safety_settings
344
+
345
+ gen_config = types.GenerateContentConfig(**gen_config_kwargs)
346
+
347
+ print(f"[NanaBanana] -> {model} | mode:{mode} | quality:{quality} | safety:{safety_threshold}")
348
+
349
+ response = client.models.generate_content(
350
+ model=model,
351
+ contents=parts,
352
+ config=gen_config
353
+ )
354
+
355
+ if not response.candidates:
356
+ raise RuntimeError(f"[NanaBanana] Aucun candidat: {response}")
357
+
358
+ candidate = response.candidates[0]
359
+ finish_reason = str(getattr(candidate, "finish_reason", ""))
360
+ if "SAFETY" in finish_reason:
361
+ raise RuntimeError("[NanaBanana] Bloque par IMAGE_SAFETY. Reformule le prompt.")
362
+
363
+ content = getattr(candidate, "content", None)
364
+ if content is None or not getattr(content, "parts", None):
365
+ raise RuntimeError(f"[NanaBanana] Content vide. finish_reason: {finish_reason}")
366
+
367
+ result_image, info_text = None, ""
368
+ for part in content.parts:
369
+ if hasattr(part, "text") and part.text:
370
+ info_text += part.text + "\n"
371
+ elif hasattr(part, "inline_data") and part.inline_data:
372
+ result_image = Image.open(io.BytesIO(part.inline_data.data)).convert("RGB")
373
+
374
+ if result_image is None:
375
+ raise RuntimeError(f"[NanaBanana] Aucune image generee. Texte: {info_text or '(aucun)'}")
376
+
377
+ result_image = apply_color_grade(
378
+ result_image,
379
+ cg_brightness, cg_contrast, cg_saturation, cg_temperature, cg_sharpness
380
+ )
381
+
382
+ metadata = (
383
+ f"model: {model}\n"
384
+ f"mode: {mode}\n"
385
+ f"seed: {actual_seed}\n"
386
+ f"temperature: {temperature} | top_p: {top_p} | top_k: {top_k}\n"
387
+ f"aspect_ratio: {aspect_ratio} | quality: {quality}\n"
388
+ f"safety: {safety_threshold}\n"
389
+ f"{info_text.strip()}"
390
+ )
391
+ print(f"[NanaBanana] Succes ! ({quality})")
392
+ return (pil_to_tensor(result_image), metadata)
393
+
394
+
395
+ NODE_CLASS_MAPPINGS = {"NanaBananaProNode": NanaBananaProNode}
396
+ NODE_DISPLAY_NAME_MAPPINGS = {"NanaBananaProNode": "🍌 Nano Banana Pro"}
397
+ ENDOFFILE
398
+
399
+ # ── anya_prompt_extractor_node.py ──────────────────────────────────────────
400
+ cat > "${NBP_DIR}/anya_prompt_extractor_node.py" << 'ENDOFFILE'
401
+ import torch, numpy as np, io, json
402
+ from PIL import Image
403
+
404
+ def tensor_to_pil(tensor):
405
+ arr = tensor.squeeze(0).numpy()
406
+ arr = (arr * 255).clip(0, 255).astype(np.uint8)
407
+ return Image.fromarray(arr)
408
+
409
+ def pil_to_bytes(image):
410
+ buf = io.BytesIO()
411
+ image.save(buf, format="PNG")
412
+ return buf.getvalue()
413
+
414
+ def build_system_prompt(anya_desc, include_anya, include_l3n0v0, breast_size, style_hint, use_ref_images, num_refs, ref_descs_list):
415
+ 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"}
416
+ breast_desc = breast_map.get(breast_size, "medium-sized natural breasts")
417
+ triggers = []
418
+ if include_anya: triggers.append("Anya")
419
+ if include_l3n0v0: triggers.append("l3n0v0")
420
+ triggers_str = json.dumps(triggers)
421
+ if include_anya:
422
+ 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": "..."}}'
423
+ 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."
424
+ else:
425
+ subject_block = ' "subject": {"description": "...", "pose": "...", "expression": "...", "gaze": "..."}'
426
+ subject_instruction = "## SUBJECT\nDescribe the subject from the reference image exactly. Reproduce face, hair, skin tone, body proportions 1:1. No changes, no beautification."
427
+ if use_ref_images and num_refs > 0:
428
+ ref_labels = ["subject_identity"] + [f"reference_image_{i}" for i in range(2, num_refs+1)]
429
+ ref_entries = []
430
+ for i in range(num_refs):
431
+ label = ref_labels[i] if i < len(ref_labels) else f"reference_image_{i+1}"
432
+ desc = ref_descs_list[i] if i < len(ref_descs_list) and ref_descs_list[i].strip() else f"uploaded_reference_image_{i+1}"
433
+ ref_entries.append(f' "{label}": "{desc}"')
434
+ ref_block = ' "reference_images": {\n' + ',\n'.join(ref_entries) + '\n },'
435
+ 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)])
436
+ else:
437
+ ref_block = ""
438
+ ref_instruction = "## REFERENCE IMAGES\nNo reference images."
439
+ ref_section = f"\n{ref_block}" if ref_block else ""
440
+ 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."
441
+ return f"""You are an expert AI image prompt engineer specializing in structured JSON prompts.
442
+
443
+ {subject_instruction}
444
+ {ref_instruction}
445
+
446
+ ## OUTPUT RULES
447
+ - Return ONLY valid JSON, no markdown, no backticks, no explanation
448
+ - trigger_words must be exactly: {triggers_str}
449
+
450
+ {{
451
+ "trigger_words": {triggers_str},{ref_section}
452
+ "output_quality": {{"resolution": "4K", "definition": "ultra high resolution", "sharpness": "natural realistic detail, not overprocessed"}},
453
+ {subject_block},
454
+ "outfit": {{"description": "...", "colors": [...], "fit": "...", "fabric": "..."}},
455
+ "location": {{"setting": "...", "environment": [...], "time_of_day": "...", "lighting": "...", "atmosphere": "..."}},
456
+ "image_type": {{"orientation": "...", "aspect_ratio": "...", "style": "{style_hint}", "camera_feel": "...", "color_grading": "..."}},
457
+ "identity_preservation": {{"facial_identity": "...", "no_changes": ["bone_structure", "facial_proportions", "skin_tone", "hairline", "facial_features"], "no_beautification": true, "no_stylization": true}},
458
+ "realism_constraints": {{"no_extra_limbs": true, "no_ai_symmetry_correction": true, "natural_skin_texture": true, "natural_light_behavior": true, "no_heavy_color_grading": true}},
459
+ "image_feel": [...]
460
+ }}
461
+
462
+ Analyze the provided image(s): extract scene, lighting, pose, outfit, mood. {inject_note} Return ONLY the JSON."""
463
+
464
+ class AnyaPromptExtractor:
465
+ MODELS = ["gemini-2.5-flash-preview-05-20", "gemini-2.5-flash", "gemini-2.5-pro", "gemini-3-pro-image-preview"]
466
+ BREAST_SIZES = ["small", "medium", "large", "huge"]
467
+ NUM_REFS = ["0", "1", "2", "3", "4", "5"]
468
+
469
+ @classmethod
470
+ def INPUT_TYPES(cls):
471
+ return {
472
+ "required": {
473
+ "api_key": ("STRING", {"default": "YOUR_GEMINI_API_KEY"}),
474
+ "model": (cls.MODELS,),
475
+ "include_trigger_anya": ("BOOLEAN", {"default": True}),
476
+ "include_trigger_l3n0v0": ("BOOLEAN", {"default": True}),
477
+ "breast_size_override": (cls.BREAST_SIZES,),
478
+ "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}),
479
+ "style_hint": ("STRING", {"default": "natural high-end lifestyle, candid editorial"}),
480
+ "json_indent": ("INT", {"default": 4, "min": 0, "max": 8, "step": 1}),
481
+ "use_reference_images": ("BOOLEAN", {"default": True}),
482
+ "num_reference_images": (cls.NUM_REFS,),
483
+ "ref_1_description": ("STRING", {"default": "subject identity β€” main model reference"}),
484
+ "ref_2_description": ("STRING", {"default": "outfit reference"}),
485
+ "ref_3_description": ("STRING", {"default": "location or background reference"}),
486
+ "ref_4_description": ("STRING", {"default": "style or mood reference"}),
487
+ "ref_5_description": ("STRING", {"default": "additional reference"}),
488
+ },
489
+ "optional": {
490
+ "scene_image": ("IMAGE",),
491
+ "ref_image_1": ("IMAGE",),
492
+ "ref_image_2": ("IMAGE",),
493
+ "ref_image_3": ("IMAGE",),
494
+ "ref_image_4": ("IMAGE",),
495
+ "ref_image_5": ("IMAGE",),
496
+ }
497
+ }
498
+
499
+ RETURN_TYPES = ("STRING", "IMAGE", "IMAGE", "IMAGE", "IMAGE", "IMAGE", "IMAGE")
500
+ RETURN_NAMES = ("prompt_json", "scene_passthrough", "ref_1_passthrough", "ref_2_passthrough", "ref_3_passthrough", "ref_4_passthrough", "ref_5_passthrough")
501
+ FUNCTION = "extract"
502
+ CATEGORY = "🍌 Nano Banana Pro"
503
+ OUTPUT_NODE = True
504
+
505
+ def extract(self, api_key, model, include_trigger_anya, include_trigger_l3n0v0,
506
+ breast_size_override, anya_base_description, style_hint, json_indent,
507
+ use_reference_images, num_reference_images,
508
+ ref_1_description, ref_2_description, ref_3_description,
509
+ ref_4_description, ref_5_description,
510
+ scene_image=None, ref_image_1=None, ref_image_2=None,
511
+ ref_image_3=None, ref_image_4=None, ref_image_5=None):
512
+ try:
513
+ from google import genai
514
+ from google.genai import types
515
+ except ImportError:
516
+ raise ImportError("Lance : pip install google-genai")
517
+ num_refs = int(num_reference_images)
518
+ ref_descs_list = [ref_1_description, ref_2_description, ref_3_description, ref_4_description, ref_5_description]
519
+ 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)
520
+ client = genai.Client(api_key=api_key)
521
+ parts = []
522
+ if scene_image is not None:
523
+ parts.append(types.Part.from_bytes(data=pil_to_bytes(tensor_to_pil(scene_image)), mime_type="image/png"))
524
+ if use_reference_images and num_refs > 0:
525
+ ref_images_list = [ref_image_1, ref_image_2, ref_image_3, ref_image_4, ref_image_5]
526
+ for i in range(min(num_refs, 5)):
527
+ ref = ref_images_list[i]
528
+ if ref is not None:
529
+ desc = ref_descs_list[i] if ref_descs_list[i].strip() else f"reference image {i+1}"
530
+ parts.append(types.Part.from_text(text=f"[Reference image {i+1}: {desc}]"))
531
+ parts.append(types.Part.from_bytes(data=pil_to_bytes(tensor_to_pil(ref)), mime_type="image/png"))
532
+ if not parts:
533
+ parts.append(types.Part.from_text(text="No image provided. Generate a generic lifestyle JSON prompt. Return ONLY the JSON."))
534
+ else:
535
+ parts.append(types.Part.from_text(text="Analyze the provided image(s) and generate the structured JSON prompt. Return ONLY the JSON."))
536
+ config = types.GenerateContentConfig(system_instruction=system_prompt, response_modalities=["TEXT"], temperature=0.4, top_p=0.9)
537
+ print(f"[AnyaExtractor] -> {model} | Anya:{include_trigger_anya} | l3n0v0:{include_trigger_l3n0v0} | refs:{num_refs if use_reference_images else 0}")
538
+ response = client.models.generate_content(model=model, contents=parts, config=config)
539
+ raw_parts = response.parts or []
540
+ raw_text = "".join(part.text for part in raw_parts if hasattr(part, "text") and part.text).strip()
541
+ if not raw_text and hasattr(response, "candidates") and response.candidates:
542
+ raw_text = "".join(part.text for part in (response.candidates[0].content.parts or []) if hasattr(part, "text") and part.text).strip()
543
+ if not raw_text:
544
+ raise RuntimeError(f"[AnyaExtractor] Reponse vide. Modele: {model} | Verifier la cle API ou changer de modele.")
545
+ if raw_text.startswith("```"):
546
+ lines = raw_text.split("\n")
547
+ raw_text = "\n".join(lines[1:-1] if lines[-1].strip() == "```" else lines[1:]).strip()
548
+ try:
549
+ parsed = json.loads(raw_text)
550
+ tw = parsed.get("trigger_words", [])
551
+ if include_trigger_anya and "Anya" not in tw: tw.insert(0, "Anya")
552
+ if not include_trigger_anya and "Anya" in tw: tw.remove("Anya")
553
+ if include_trigger_l3n0v0 and "l3n0v0" not in tw: tw.append("l3n0v0")
554
+ if not include_trigger_l3n0v0 and "l3n0v0" in tw: tw.remove("l3n0v0")
555
+ parsed["trigger_words"] = tw
556
+ output_json = json.dumps(parsed, indent=json_indent, ensure_ascii=False)
557
+ except json.JSONDecodeError as e:
558
+ print(f"[AnyaExtractor] JSON invalide: {e}")
559
+ output_json = raw_text
560
+ print(f"[AnyaExtractor] Succes ({len(output_json)} chars)")
561
+ empty = torch.zeros(1, 64, 64, 3)
562
+ 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)
563
+
564
+ NODE_CLASS_MAPPINGS = {"AnyaPromptExtractor": AnyaPromptExtractor}
565
+ NODE_DISPLAY_NAME_MAPPINGS = {"AnyaPromptExtractor": "πŸ” Anya Prompt Extractor"}
566
+ ENDOFFILE
567
+
568
+ # ── grok_prompt_extractor_node.py ──────────────────────────────────────────
569
+ cat > "${NBP_DIR}/grok_prompt_extractor_node.py" << 'ENDOFFILE'
570
+ import torch, numpy as np, io, base64
571
+ from PIL import Image
572
+
573
+ def tensor_to_pil(tensor):
574
+ arr = tensor.squeeze(0).numpy()
575
+ arr = (arr * 255).clip(0, 255).astype(np.uint8)
576
+ return Image.fromarray(arr)
577
+
578
+ def pil_to_bytes(image):
579
+ buf = io.BytesIO()
580
+ image.save(buf, format="PNG")
581
+ return buf.getvalue()
582
+
583
+ def image_to_base64(image):
584
+ return base64.b64encode(pil_to_bytes(image)).decode("utf-8")
585
+
586
+ def build_system_prompt(anya_desc, include_anya, include_l3n0v0, breast_size, style_hint, word_count):
587
+ breast_map = {
588
+ "small": "small perky breasts",
589
+ "medium": "medium-sized natural breasts with visible cleavage",
590
+ "large": "large full breasts with natural weight and deep cleavage",
591
+ "huge": "very large heavy breasts, extremely voluptuous silhouette"
592
+ }
593
+ breast_desc = breast_map.get(breast_size, "medium-sized natural breasts with visible cleavage")
594
+ triggers = []
595
+ if include_anya: triggers.append("Anya")
596
+ if include_l3n0v0: triggers.append("l3n0v0")
597
+ trigger_line = ", ".join(triggers)
598
+ if include_anya:
599
+ char_instruction = f"""## ANYA β€” FIXED PHYSICAL CHARACTER
600
+ {anya_desc}
601
+ Breast size: {breast_desc}
602
+ Body: wide hips, prominent round BBL-style butt, thick thighs, hourglass figure, slim waist
603
+ Face: full pouty lips, almond-shaped eyes with long lashes, warm tan Asian skin, high cheekbones
604
+ Jewelry: gold hoop earrings, gold chain necklace, gold bracelets
605
+
606
+ ## REPLACEMENT RULE
607
+ Anya replaces the person in the image EXACTLY.
608
+ - Same pose, same expression, same gaze, same position in frame
609
+ - Same outfit worn on Anya's body β€” describe how each garment fits her curves
610
+ - Same location, same lighting, same background, same props
611
+ - Only the physical identity changes to Anya"""
612
+ 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"
613
+ else:
614
+ char_instruction = "## SUBJECT\nDescribe the subject exactly as seen. Be extremely precise about every physical detail."
615
+ subject_block = "the person in the image"
616
+ inject = f"Replace the subject with: {subject_block}" if include_anya else "Describe the subject exactly as visible."
617
+ 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.
618
+
619
+ {char_instruction}
620
+
621
+ ## YOUR MISSION
622
+ Analyze the image with forensic precision. Write a single continuous text-to-image prompt of exactly {word_count} words.
623
+ The prompt must be so detailed that an AI image generator can reproduce the scene perfectly.
624
+
625
+ ## TEXT-TO-IMAGE PROMPT RULES
626
+ - Write as comma-separated descriptive phrases, NOT sentences
627
+ - Start with trigger words, then subject, then body details, then outfit, then pose, then location, then lighting, then camera, then mood
628
+ - Use text-to-image vocabulary: "photorealistic, 8k uhd, RAW photo, sharp focus, f/1.8, 85mm lens, bokeh, cinematic lighting" etc
629
+ - Be EXTREMELY explicit about body proportions, clothing fit, skin exposure
630
+ - Describe exactly what is visible β€” if cleavage is showing, describe it precisely
631
+ - If outfit is tight/revealing, describe exactly how it fits on the body
632
+ - Never use euphemisms β€” describe body parts and clothing directly and explicitly
633
+ - No sentences, no paragraph structure β€” pure prompt style
634
+
635
+ ## STRUCTURE TO FOLLOW
636
+ 1. Trigger words: {trigger_line},
637
+ 2. Subject physical description (face, hair, skin, eyes, lips, body)
638
+ 3. Breast description and how visible/covered they are
639
+ 4. Exact outfit β€” every garment, color, fabric, fit, how tight, what skin is exposed
640
+ 5. Exact pose β€” body position, limb placement, weight, angles
641
+ 6. Hands and arm positions
642
+ 7. Expression and gaze direction
643
+ 8. Location β€” exact setting, architecture, materials, colors
644
+ 9. Background elements one by one
645
+ 10. Lighting β€” source, direction, quality, color temperature, how it hits skin and clothing
646
+ 11. Camera β€” shot type, angle, focal length, depth of field
647
+ 12. Technical quality tags
648
+ 13. Mood and atmosphere tags
649
+
650
+ ## NSFW DESCRIPTION RULES
651
+ - Describe clothing tightness and fit on the body explicitly
652
+ - Describe visible skin areas precisely (neckline depth, leg exposure, midriff, back)
653
+ - Describe breast shape and how they appear in the outfit
654
+ - Describe butt shape and how outfit fits on it
655
+ - Use direct anatomical and fashion terminology
656
+ - If any body part is prominent or featured in the image, describe it in detail
657
+
658
+ ## CRITICAL
659
+ - {word_count} words minimum
660
+ - Pure text-to-image prompt format β€” no prose, no sentences
661
+ - Every single visual detail from the image must be captured
662
+ - {inject}
663
+ - Return ONLY the prompt text, nothing else"""
664
+
665
+ class GrokPromptExtractor:
666
+ MODELS = ["grok-2-vision-1212", "grok-2-vision"]
667
+ BREAST_SIZES = ["small", "medium", "large", "huge"]
668
+
669
+ @classmethod
670
+ def INPUT_TYPES(cls):
671
+ return {
672
+ "required": {
673
+ "api_key": ("STRING", {"default": "YOUR_XAI_API_KEY"}),
674
+ "model": (cls.MODELS,),
675
+ "include_trigger_anya": ("BOOLEAN", {"default": True}),
676
+ "include_trigger_l3n0v0": ("BOOLEAN", {"default": True}),
677
+ "breast_size_override": (cls.BREAST_SIZES,),
678
+ "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}),
679
+ "style_hint": ("STRING", {"default": "RAW photo, photorealistic, candid shot, natural lighting, 8k uhd"}),
680
+ "word_count": ("INT", {"default": 450, "min": 200, "max": 800, "step": 50}),
681
+ },
682
+ "optional": {
683
+ "image": ("IMAGE",),
684
+ }
685
+ }
686
+
687
+ RETURN_TYPES = ("STRING", "IMAGE")
688
+ RETURN_NAMES = ("prompt_text", "image_passthrough")
689
+ FUNCTION = "extract"
690
+ CATEGORY = "πŸ€– Grok xAI"
691
+ OUTPUT_NODE = True
692
+
693
+ def extract(self, api_key, model, include_trigger_anya, include_trigger_l3n0v0,
694
+ breast_size_override, anya_base_description, style_hint, word_count,
695
+ image=None):
696
+ try:
697
+ from xai_sdk import Client
698
+ from xai_sdk.chat import system, user, image as xai_image
699
+ except ImportError:
700
+ raise ImportError("Lance : pip install xai-sdk")
701
+ system_prompt = build_system_prompt(anya_base_description, include_trigger_anya, include_trigger_l3n0v0, breast_size_override, style_hint, word_count)
702
+ client = Client(api_key=api_key)
703
+ chat = client.chat.create(model=model)
704
+ chat.append(system(system_prompt))
705
+ if image is not None:
706
+ b64 = image_to_base64(tensor_to_pil(image))
707
+ data_url = f"data:image/png;base64,{b64}"
708
+ chat.append(user(
709
+ f"Analyze every detail of this image. Write a {word_count}-word text-to-image prompt. "
710
+ f"Be extremely explicit about body proportions, outfit fit, skin exposure, clothing tightness. "
711
+ f"Pure prompt format β€” comma-separated tags and descriptors, no sentences, no explanations. "
712
+ f"Return ONLY the prompt.",
713
+ xai_image(data_url)
714
+ ))
715
+ else:
716
+ 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."))
717
+ print(f"[GrokExtractor] -> {model} | Anya:{include_trigger_anya} | l3n0v0:{include_trigger_l3n0v0} | words:{word_count}")
718
+ response = chat.sample()
719
+ output_text = response.content.strip()
720
+ print(f"[GrokExtractor] OK ({len(output_text.split())} words)")
721
+ empty = torch.zeros(1, 64, 64, 3)
722
+ return (output_text, image if image is not None else empty)
723
+
724
+ NODE_CLASS_MAPPINGS = {"GrokPromptExtractor": GrokPromptExtractor}
725
+ NODE_DISPLAY_NAME_MAPPINGS = {"GrokPromptExtractor": "πŸ€– Grok Prompt Extractor"}
726
+ ENDOFFILE
727
+
728
+ # ── __init__.py ────────────────────────────────────────────────────────────
729
+ cat > "${NBP_DIR}/__init__.py" << 'EOF'
730
+ from .nano_banana_pro_node import NODE_CLASS_MAPPINGS as _NM1, NODE_DISPLAY_NAME_MAPPINGS as _DN1
731
+ from .anya_prompt_extractor_node import NODE_CLASS_MAPPINGS as _NM2, NODE_DISPLAY_NAME_MAPPINGS as _DN2
732
+ from .grok_prompt_extractor_node import NODE_CLASS_MAPPINGS as _NM3, NODE_DISPLAY_NAME_MAPPINGS as _DN3
733
+
734
+ NODE_CLASS_MAPPINGS = {}
735
+ NODE_CLASS_MAPPINGS.update(_NM1)
736
+ NODE_CLASS_MAPPINGS.update(_NM2)
737
+ NODE_CLASS_MAPPINGS.update(_NM3)
738
+
739
+ NODE_DISPLAY_NAME_MAPPINGS = {}
740
+ NODE_DISPLAY_NAME_MAPPINGS.update(_DN1)
741
+ NODE_DISPLAY_NAME_MAPPINGS.update(_DN2)
742
+ NODE_DISPLAY_NAME_MAPPINGS.update(_DN3)
743
+
744
+ __all__ = ["NODE_CLASS_MAPPINGS", "NODE_DISPLAY_NAME_MAPPINGS"]
745
+ EOF
746
+
747
+ printf "NanoBananaPro nodes created successfully.\n"
748
+ }
749
+
750
+ function provisioning_get_files() {
751
+ if [[ -z $2 ]]; then return 1; fi
752
+
753
+ dir="$1"
754
+ mkdir -p "$dir"
755
+ shift
756
+ arr=("$@")
757
+ printf "Downloading %s model(s) to %s...\n" "${#arr[@]}" "$dir"
758
+ for entry in "${arr[@]}"; do
759
+ # Support "URL|filename" format for custom filenames
760
+ if [[ "$entry" == *"|"* ]]; then
761
+ url="${entry%%|*}"
762
+ filename="${entry##*|}"
763
+ else
764
+ url="$entry"
765
+ filename=""
766
+ fi
767
+ printf "Downloading: %s\n" "${url}"
768
+ provisioning_download "${url}" "${dir}" "${filename}"
769
+ printf "\n"
770
+ done
771
+ }
772
+
773
+ function provisioning_print_header() {
774
+ 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"
775
+ }
776
+
777
+ function provisioning_print_end() {
778
+ printf "\nProvisioning complete: Application will start now\n\n"
779
+ }
780
+
781
+ function provisioning_has_valid_hf_token() {
782
+ [[ -n "$HF_TOKEN" ]] || return 1
783
+ url="https://huggingface.co/api/whoami-v2"
784
+
785
+ response=$(curl -o /dev/null -s -w "%{http_code}" -X GET "$url" \
786
+ -H "Authorization: Bearer $HF_TOKEN" \
787
+ -H "Content-Type: application/json")
788
+
789
+ if [ "$response" -eq 200 ]; then
790
+ return 0
791
+ else
792
+ return 1
793
+ fi
794
+ }
795
+
796
+ function provisioning_has_valid_civitai_token() {
797
+ [[ -n "$CIVITAI_TOKEN" ]] || return 1
798
+ url="https://civitai.com/api/v1/models?hidden=1&limit=1"
799
+
800
+ response=$(curl -o /dev/null -s -w "%{http_code}" -X GET "$url" \
801
+ -H "Authorization: Bearer $CIVITAI_TOKEN" \
802
+ -H "Content-Type: application/json")
803
+
804
+ if [ "$response" -eq 200 ]; then
805
+ return 0
806
+ else
807
+ return 1
808
+ fi
809
+ }
810
+
811
+ # Download CivitAI models with curl (pure bash)
812
+ function download_civitai_bash() {
813
+ local url="$1"
814
+ local output_dir="$2"
815
+ local forced_filename="$3"
816
+ local model_id=""
817
+
818
+ if [[ $url =~ /models/([0-9]+) ]]; then
819
+ model_id="${BASH_REMATCH[1]}"
820
+ else
821
+ printf "ERROR: Could not extract model ID from URL\n"
822
+ return 1
823
+ fi
824
+
825
+ printf "Downloading CivitAI model %s...\n" "$model_id"
826
+
827
+ if [[ -n "$forced_filename" ]]; then
828
+ local output_file="${output_dir}/${forced_filename}"
829
+ if [[ -f "$output_file" ]]; then
830
+ printf "File already exists: %s\n" "$forced_filename"
831
+ return 0
832
+ fi
833
+ printf "Downloading to: %s\n" "$forced_filename"
834
+ if [[ -n "$CIVITAI_TOKEN" ]]; then
835
+ curl -L -o "$output_file" --progress-bar -H "Authorization: Bearer $CIVITAI_TOKEN" "$url"
836
+ else
837
+ curl -L -o "$output_file" --progress-bar "$url"
838
+ fi
839
+ if [[ $? -eq 0 ]]; then
840
+ printf "Download completed: %s\n" "$forced_filename"
841
+ return 0
842
+ else
843
+ printf "ERROR: Download failed for model %s\n" "$model_id"
844
+ return 1
845
+ fi
846
+ fi
847
+
848
+ local redirect_url=""
849
+ if [[ -n "$CIVITAI_TOKEN" ]]; then
850
+ redirect_url=$(curl -s -I -L -H "Authorization: Bearer $CIVITAI_TOKEN" "$url" | grep -i "^location:" | tail -1 | sed 's/location: //i' | tr -d '\r\n')
851
+ else
852
+ redirect_url=$(curl -s -I -L "$url" | grep -i "^location:" | tail -1 | sed 's/location: //i' | tr -d '\r\n')
853
+ fi
854
+
855
+ if [[ -z "$redirect_url" ]]; then
856
+ printf "ERROR: Could not get redirect URL for model %s\n" "$model_id"
857
+ return 1
858
+ fi
859
+
860
+ local filename=""
861
+
862
+ if [[ $redirect_url =~ response-content-disposition=attachment.*filename%3D%22([^%\"]+) ]]; then
863
+ filename="${BASH_REMATCH[1]}"
864
+ filename=$(echo "$filename" | sed 's/%20/ /g; s/%2D/-/g; s/%2E/./g; s/%5F/_/g')
865
+ elif [[ $redirect_url =~ filename=\"([^\"]+)\" ]]; then
866
+ filename="${BASH_REMATCH[1]}"
867
+ elif [[ $redirect_url =~ filename=([^&]+) ]]; then
868
+ filename="${BASH_REMATCH[1]}"
869
+ else
870
+ local path_part=$(echo "$redirect_url" | sed 's/?.*//')
871
+ filename=$(basename "$path_part")
872
+ if [[ ! "$filename" =~ \.(safetensors|pt|pth|ckpt|bin)$ ]]; then
873
+ filename="${filename}.safetensors"
874
+ fi
875
+ fi
876
+
877
+ filename=$(printf '%b' "${filename//%/\\x}")
878
+
879
+ if [[ -z "$filename" ]] || [[ "$filename" == "." ]] || [[ "$filename" == ".safetensors" ]]; then
880
+ filename="civitai_${model_id}.safetensors"
881
+ fi
882
+
883
+ local output_file="${output_dir}/${filename}"
884
+
885
+ if [[ -f "$output_file" ]]; then
886
+ printf "File already exists: %s\n" "$filename"
887
+ return 0
888
+ fi
889
+
890
+ printf "Downloading to: %s\n" "$filename"
891
+ curl -L -o "$output_file" --progress-bar "$redirect_url"
892
+
893
+ if [[ $? -eq 0 ]]; then
894
+ printf "Download completed: %s\n" "$filename"
895
+ return 0
896
+ else
897
+ printf "ERROR: Download failed for model %s\n" "$model_id"
898
+ return 1
899
+ fi
900
+ }
901
+
902
+ # Download from $1 URL to $2 file path, with optional $3 forced filename
903
+ function provisioning_download() {
904
+ local url="$1"
905
+ local dir="$2"
906
+ local forced_filename="$3"
907
+
908
+ if [[ $url =~ ^https://civitai\.com/api/download/models/([0-9]+) ]]; then
909
+ download_civitai_bash "$url" "$dir" "$forced_filename"
910
+ else
911
+ if [[ -n "$forced_filename" ]]; then
912
+ wget -qnc --show-progress -e dotbytes="${4:-4M}" -O "${dir}/${forced_filename}" "$url"
913
+ else
914
+ wget -qnc --content-disposition --show-progress -e dotbytes="${4:-4M}" -P "$dir" "$url"
915
+ fi
916
+ fi
917
+ }
918
+
919
+ # Allow user to disable provisioning if they started with a script they didn't want
920
+ if [[ ! -f /.noprovisioning ]]; then
921
+ provisioning_start
922
+ fi