sofia / qwen.sh
nathanglm's picture
Upload qwen.sh
9b38937 verified
Raw History Blame Contribute Delete
41.7 kB
#!/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/ltdrdata/ComfyUI-Manager"
"https://github.com/rgthree/rgthree-comfy"
"https://github.com/ltdrdata/ComfyUI-Impact-Pack"
"https://github.com/yolain/ComfyUI-Easy-Use"
"https://github.com/ssitu/ComfyUI_UltimateSDUpscale"
"https://github.com/sipherxyz/comfyui-art-venture"
"https://github.com/ltdrdata/ComfyUI-Impact-Subpack"
"https://github.com/moonwhaler/comfyui-moonpack"
"https://github.com/gseth/ControlAltAI-Nodes"
"https://github.com/vrgamegirl19/comfyui-vrgamedevgirl"
"https://github.com/numz/ComfyUI-SeedVR2_VideoUpscaler"
"https://github.com/robertvoy/ComfyUI-Flux-Continuum"
"https://github.com/ltdrdata/was-node-suite-comfyui"
"https://github.com/ChangeTheConstants/SeedVarianceEnhancer"
"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=(
)
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
"https://civitai.com/api/download/models/1621447" # Iniverse
"https://huggingface.co/Phr00t/Qwen-Image-Edit-Rapid-AIO/resolve/main/v23/Qwen-Rapid-AIO-NSFW-v23.safetensors"
)
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=(
)
# Format: "URL|filename.safetensors"
LORA_MODELS=(
)
VAE_MODELS=(
)
DIFFUSION_MODELS=(
)
TEXT_ENCODERS=(
)
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 "$CIVITAI_TOKEN" ]] || 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 $CIVITAI_TOKEN" \
-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 "$CIVITAI_TOKEN" ]]; then
curl -L -o "$output_file" --progress-bar -H "Authorization: Bearer $CIVITAI_TOKEN" "$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 "$CIVITAI_TOKEN" ]]; then
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')
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