nathanglm commited on
Commit
79ba264
Β·
verified Β·
1 Parent(s): c905134

Update installer.sh

Browse files
Files changed (1) hide show
  1. installer.sh +113 -58
installer.sh CHANGED
@@ -200,6 +200,18 @@ function provisioning_create_nanobananapro() {
200
 
201
  # ── nano_banana_pro_node.py ────────────────────────────────────────────────
202
  cat > "${NBP_DIR}/nano_banana_pro_node.py" << 'ENDOFFILE'
 
 
 
 
 
 
 
 
 
 
 
 
203
  import torch, numpy as np, io, random
204
  from PIL import Image, ImageEnhance
205
 
@@ -237,25 +249,35 @@ def apply_color_grade(image, brightness, contrast, saturation, temperature, shar
237
  else:
238
  r_arr = np.clip(r_arr - strength * 0.5, 0, 255)
239
  b_arr = np.clip(b_arr + strength, 0, 255)
240
- img = Image.merge("RGB", (Image.fromarray(r_arr.astype(np.uint8)), g, Image.fromarray(b_arr.astype(np.uint8))))
 
 
 
 
241
  if sharpness != 1.0:
242
  img = ImageEnhance.Sharpness(img).enhance(sharpness)
243
  return img
244
 
 
245
  class NanaBananaProNode:
246
- MODELS = ["gemini-3-pro-image-preview", "gemini-2.5-flash-image"]
 
 
 
 
 
247
  SAFETY = ["OFF", "BLOCK_ONLY_HIGH", "BLOCK_MEDIUM_AND_ABOVE", "BLOCK_LOW_AND_ABOVE"]
248
- RATIOS = ["1:1", "2:3", "3:2", "16:9", "9:16", "4:3", "3:4", "21:9"]
249
- QUALITY = ["1K", "2K", "4K"]
250
- MEDIA_RES = ["HIGH", "MEDIUM", "LOW"]
251
  AFTER_GEN = ["randomize", "fixed", "increment"]
252
 
253
  @classmethod
254
  def INPUT_TYPES(cls):
255
  return {
256
  "required": {
257
- "prompt": ("STRING", {"default": "A stunning landscape, ultra detailed", "multiline": True}),
258
  "model": (cls.MODELS,),
 
259
  "aspect_ratio": (cls.RATIOS,),
260
  "quality": (cls.QUALITY,),
261
  "temperature": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 2.0, "step": 0.05}),
@@ -264,8 +286,6 @@ class NanaBananaProNode:
264
  "seed": ("INT", {"default": -1, "min": -1, "max": 2**31,"step": 1}),
265
  "control_after_generate": (cls.AFTER_GEN,),
266
  "safety_threshold": (cls.SAFETY,),
267
- "use_images": ("BOOLEAN", {"default": False}),
268
- "media_resolution": (cls.MEDIA_RES,),
269
  "api_key": ("STRING", {"default": "YOUR_GEMINI_API_KEY"}),
270
  "cg_brightness": ("FLOAT", {"default": 1.0, "min": 0.1, "max": 3.0, "step": 0.05}),
271
  "cg_contrast": ("FLOAT", {"default": 1.0, "min": 0.1, "max": 3.0, "step": 0.05}),
@@ -274,12 +294,14 @@ class NanaBananaProNode:
274
  "cg_sharpness": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 3.0, "step": 0.05}),
275
  },
276
  "optional": {
277
- "batch_images": ("IMAGE",),
278
- "image_1": ("IMAGE",),
279
- "image_2": ("IMAGE",),
280
- "image_3": ("IMAGE",),
281
- "image_4": ("IMAGE",),
282
- "image_5": ("IMAGE",),
 
 
283
  }
284
  }
285
 
@@ -288,66 +310,119 @@ class NanaBananaProNode:
288
  FUNCTION = "generate"
289
  CATEGORY = "🍌 Nano Banana Pro"
290
 
291
- def generate(self, prompt, model, aspect_ratio, quality, temperature, top_p, top_k,
292
- seed, control_after_generate, safety_threshold, use_images,
293
- media_resolution, api_key,
294
  cg_brightness, cg_contrast, cg_saturation, cg_temperature, cg_sharpness,
295
- batch_images=None, image_1=None, image_2=None, image_3=None,
296
- image_4=None, image_5=None):
297
  try:
298
  from google import genai
299
  from google.genai import types
300
  except ImportError:
301
  raise ImportError("Lance : pip install google-genai")
 
302
  if seed == -1 or control_after_generate == "randomize":
303
  actual_seed = random.randint(0, 2**31)
304
  elif control_after_generate == "increment":
305
  actual_seed = seed + 1
306
  else:
307
  actual_seed = seed
 
308
  client = genai.Client(api_key=api_key)
 
309
  safety_settings = []
310
  if safety_threshold != "OFF":
311
- harm_categories = ["HARM_CATEGORY_HARASSMENT","HARM_CATEGORY_HATE_SPEECH","HARM_CATEGORY_SEXUALLY_EXPLICIT","HARM_CATEGORY_DANGEROUS_CONTENT"]
 
 
 
 
 
312
  safety_settings = [types.SafetySetting(category=cat, threshold=safety_threshold) for cat in harm_categories]
 
313
  parts = []
314
- if use_images:
315
- for ref in [batch_images, image_1, image_2, image_3, image_4, image_5]:
316
- if ref is not None:
317
- if ref.shape[0] > 1:
318
- for i in range(ref.shape[0]):
319
- parts.append(types.Part.from_bytes(data=pil_to_bytes(tensor_to_pil(ref[i].unsqueeze(0))), mime_type="image/png"))
320
- else:
321
- parts.append(types.Part.from_bytes(data=pil_to_bytes(tensor_to_pil(ref)), mime_type="image/png"))
 
 
 
 
 
 
 
 
322
  parts.append(types.Part.from_text(text=prompt))
323
- 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))
324
- if top_k > 0: gen_config_kwargs["top_k"] = top_k
325
- if safety_settings: gen_config_kwargs["safety_settings"] = safety_settings
 
 
 
 
 
 
 
 
 
 
 
 
326
  gen_config = types.GenerateContentConfig(**gen_config_kwargs)
327
- print(f"[NanaBanana] -> {model} | safety: {safety_threshold}")
328
- response = client.models.generate_content(model=model, contents=parts, config=gen_config)
 
 
 
 
 
 
 
329
  if not response.candidates:
330
  raise RuntimeError(f"[NanaBanana] Aucun candidat: {response}")
 
331
  candidate = response.candidates[0]
332
  finish_reason = str(getattr(candidate, "finish_reason", ""))
333
  if "SAFETY" in finish_reason:
334
  raise RuntimeError("[NanaBanana] Bloque par IMAGE_SAFETY. Reformule le prompt.")
 
335
  content = getattr(candidate, "content", None)
336
  if content is None or not getattr(content, "parts", None):
337
  raise RuntimeError(f"[NanaBanana] Content vide. finish_reason: {finish_reason}")
 
338
  result_image, info_text = None, ""
339
  for part in content.parts:
340
  if hasattr(part, "text") and part.text:
341
  info_text += part.text + "\n"
342
  elif hasattr(part, "inline_data") and part.inline_data:
343
  result_image = Image.open(io.BytesIO(part.inline_data.data)).convert("RGB")
 
344
  if result_image is None:
345
- raise RuntimeError(f"[NanaBanana] Aucune image. Texte: {info_text or '(aucun)'}")
346
- result_image = apply_color_grade(result_image, cg_brightness, cg_contrast, cg_saturation, cg_temperature, cg_sharpness)
347
- metadata = f"model: {model}\nseed: {actual_seed}\ntemperature: {temperature} | top_p: {top_p} | top_k: {top_k}\naspect_ratio: {aspect_ratio} | quality: {quality}\nsafety: {safety_threshold}\n{info_text.strip()}"
348
- print("[NanaBanana] Succes !")
 
 
 
 
 
 
 
 
 
 
 
 
 
349
  return (pil_to_tensor(result_image), metadata)
350
 
 
351
  NODE_CLASS_MAPPINGS = {"NanaBananaProNode": NanaBananaProNode}
352
  NODE_DISPLAY_NAME_MAPPINGS = {"NanaBananaProNode": "🍌 Nano Banana Pro"}
353
  ENDOFFILE
@@ -681,7 +756,7 @@ NODE_CLASS_MAPPINGS = {"GrokPromptExtractor": GrokPromptExtractor}
681
  NODE_DISPLAY_NAME_MAPPINGS = {"GrokPromptExtractor": "πŸ€– Grok Prompt Extractor"}
682
  ENDOFFILE
683
 
684
- # ── __init__.py (version complΓ¨te avec nano_banana_pro_node) ───────────────
685
  cat > "${NBP_DIR}/__init__.py" << 'EOF'
686
  from .nano_banana_pro_node import NODE_CLASS_MAPPINGS as _NM1, NODE_DISPLAY_NAME_MAPPINGS as _DN1
687
  from .anya_prompt_extractor_node import NODE_CLASS_MAPPINGS as _NM2, NODE_DISPLAY_NAME_MAPPINGS as _DN2
@@ -742,7 +817,6 @@ function provisioning_has_valid_hf_token() {
742
  -H "Authorization: Bearer $HF_TOKEN" \
743
  -H "Content-Type: application/json")
744
 
745
- # Check if the token is valid
746
  if [ "$response" -eq 200 ]; then
747
  return 0
748
  else
@@ -758,7 +832,6 @@ function provisioning_has_valid_civitai_token() {
758
  -H "Authorization: Bearer $CIVITAI_TOKEN" \
759
  -H "Content-Type: application/json")
760
 
761
- # Check if the token is valid
762
  if [ "$response" -eq 200 ]; then
763
  return 0
764
  else
@@ -773,7 +846,6 @@ function download_civitai_bash() {
773
  local forced_filename="$3"
774
  local model_id=""
775
 
776
- # Extract model ID from URL
777
  if [[ $url =~ /models/([0-9]+) ]]; then
778
  model_id="${BASH_REMATCH[1]}"
779
  else
@@ -783,7 +855,6 @@ function download_civitai_bash() {
783
 
784
  printf "Downloading CivitAI model %s...\n" "$model_id"
785
 
786
- # If a forced filename was provided, use it directly
787
  if [[ -n "$forced_filename" ]]; then
788
  local output_file="${output_dir}/${forced_filename}"
789
  if [[ -f "$output_file" ]]; then
@@ -805,7 +876,6 @@ function download_civitai_bash() {
805
  fi
806
  fi
807
 
808
- # Get redirect location with curl
809
  local redirect_url=""
810
  if [[ -n "$CIVITAI_TOKEN" ]]; then
811
  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')
@@ -818,49 +888,36 @@ function download_civitai_bash() {
818
  return 1
819
  fi
820
 
821
- # Extract filename from redirect URL - improved method
822
  local filename=""
823
 
824
- # Method 1: Try to extract from response-content-disposition parameter (URL encoded)
825
  if [[ $redirect_url =~ response-content-disposition=attachment.*filename%3D%22([^%\"]+) ]]; then
826
  filename="${BASH_REMATCH[1]}"
827
- # URL decode %20 to space, %2D to -, etc.
828
  filename=$(echo "$filename" | sed 's/%20/ /g; s/%2D/-/g; s/%2E/./g; s/%5F/_/g')
829
- # Method 2: Try filename=" pattern
830
  elif [[ $redirect_url =~ filename=\"([^\"]+)\" ]]; then
831
  filename="${BASH_REMATCH[1]}"
832
- # Method 3: Try filename= without quotes
833
  elif [[ $redirect_url =~ filename=([^&]+) ]]; then
834
  filename="${BASH_REMATCH[1]}"
835
- # Method 4: Extract from URL path before query string
836
  else
837
- # Remove query string and get the last part of the path
838
  local path_part=$(echo "$redirect_url" | sed 's/?.*//')
839
  filename=$(basename "$path_part")
840
-
841
- # If filename doesn't have an extension, add .safetensors
842
  if [[ ! "$filename" =~ \.(safetensors|pt|pth|ckpt|bin)$ ]]; then
843
  filename="${filename}.safetensors"
844
  fi
845
  fi
846
 
847
- # Clean up the filename - remove any remaining % encodings
848
  filename=$(printf '%b' "${filename//%/\\x}")
849
 
850
- # If still no valid filename, use fallback
851
  if [[ -z "$filename" ]] || [[ "$filename" == "." ]] || [[ "$filename" == ".safetensors" ]]; then
852
  filename="civitai_${model_id}.safetensors"
853
  fi
854
 
855
  local output_file="${output_dir}/${filename}"
856
 
857
- # Check if file already exists
858
  if [[ -f "$output_file" ]]; then
859
  printf "File already exists: %s\n" "$filename"
860
  return 0
861
  fi
862
 
863
- # Download with curl
864
  printf "Downloading to: %s\n" "$filename"
865
  curl -L -o "$output_file" --progress-bar "$redirect_url"
866
 
@@ -879,10 +936,8 @@ function provisioning_download() {
879
  local dir="$2"
880
  local forced_filename="$3"
881
 
882
- # Check if it's a CivitAI URL
883
  if [[ $url =~ ^https://civitai\.com/api/download/models/([0-9]+) ]]; then
884
  download_civitai_bash "$url" "$dir" "$forced_filename"
885
- # HuggingFace or other URLs
886
  else
887
  if [[ -n "$forced_filename" ]]; then
888
  wget -qnc --show-progress -e dotbytes="${4:-4M}" -O "${dir}/${forced_filename}" "$url"
 
200
 
201
  # ── nano_banana_pro_node.py ────────────────────────────────────────────────
202
  cat > "${NBP_DIR}/nano_banana_pro_node.py" << 'ENDOFFILE'
203
+ """
204
+ 🍌 Nano Banana Pro Node β€” ComfyUI
205
+ Supporte :
206
+ - Nano Banana 2 = gemini-3.1-flash-image-preview (NOUVEAU, recommandΓ©)
207
+ - Nano Banana Pro = gemini-3-pro-image-preview (⚠️ déprécié le 9 mars 2026)
208
+ - Nano Banana = gemini-2.5-flash-image (stable, rapide)
209
+ Modes :
210
+ - generate : text-to-image pur
211
+ - edit : image editing (envoyer une image + prompt)
212
+ RΓ©solutions : 0.5K, 1K, 2K, 4K
213
+ """
214
+
215
  import torch, numpy as np, io, random
216
  from PIL import Image, ImageEnhance
217
 
 
249
  else:
250
  r_arr = np.clip(r_arr - strength * 0.5, 0, 255)
251
  b_arr = np.clip(b_arr + strength, 0, 255)
252
+ img = Image.merge("RGB", (
253
+ Image.fromarray(r_arr.astype(np.uint8)),
254
+ g,
255
+ Image.fromarray(b_arr.astype(np.uint8))
256
+ ))
257
  if sharpness != 1.0:
258
  img = ImageEnhance.Sharpness(img).enhance(sharpness)
259
  return img
260
 
261
+
262
  class NanaBananaProNode:
263
+ MODELS = [
264
+ "gemini-3.1-flash-image-preview",
265
+ "gemini-2.5-flash-image",
266
+ "gemini-3-pro-image-preview",
267
+ ]
268
+ MODES = ["generate", "edit"]
269
  SAFETY = ["OFF", "BLOCK_ONLY_HIGH", "BLOCK_MEDIUM_AND_ABOVE", "BLOCK_LOW_AND_ABOVE"]
270
+ RATIOS = ["1:1", "9:16", "16:9", "2:3", "3:2", "4:3", "3:4", "21:9", "1:4", "4:1"]
271
+ QUALITY = ["1K", "2K", "4K", "0.5K"]
 
272
  AFTER_GEN = ["randomize", "fixed", "increment"]
273
 
274
  @classmethod
275
  def INPUT_TYPES(cls):
276
  return {
277
  "required": {
278
+ "prompt": ("STRING", {"default": "A stunning photorealistic portrait, ultra detailed", "multiline": True}),
279
  "model": (cls.MODELS,),
280
+ "mode": (cls.MODES,),
281
  "aspect_ratio": (cls.RATIOS,),
282
  "quality": (cls.QUALITY,),
283
  "temperature": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 2.0, "step": 0.05}),
 
286
  "seed": ("INT", {"default": -1, "min": -1, "max": 2**31,"step": 1}),
287
  "control_after_generate": (cls.AFTER_GEN,),
288
  "safety_threshold": (cls.SAFETY,),
 
 
289
  "api_key": ("STRING", {"default": "YOUR_GEMINI_API_KEY"}),
290
  "cg_brightness": ("FLOAT", {"default": 1.0, "min": 0.1, "max": 3.0, "step": 0.05}),
291
  "cg_contrast": ("FLOAT", {"default": 1.0, "min": 0.1, "max": 3.0, "step": 0.05}),
 
294
  "cg_sharpness": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 3.0, "step": 0.05}),
295
  },
296
  "optional": {
297
+ "edit_image": ("IMAGE",),
298
+ "ref_image_1": ("IMAGE",),
299
+ "ref_image_2": ("IMAGE",),
300
+ "ref_image_3": ("IMAGE",),
301
+ "ref_image_4": ("IMAGE",),
302
+ "ref_image_5": ("IMAGE",),
303
+ "ref_image_6": ("IMAGE",),
304
+ "ref_image_7": ("IMAGE",),
305
  }
306
  }
307
 
 
310
  FUNCTION = "generate"
311
  CATEGORY = "🍌 Nano Banana Pro"
312
 
313
+ def generate(self, prompt, model, mode, aspect_ratio, quality, temperature, top_p, top_k,
314
+ seed, control_after_generate, safety_threshold, api_key,
 
315
  cg_brightness, cg_contrast, cg_saturation, cg_temperature, cg_sharpness,
316
+ edit_image=None, ref_image_1=None, ref_image_2=None, ref_image_3=None,
317
+ ref_image_4=None, ref_image_5=None, ref_image_6=None, ref_image_7=None):
318
  try:
319
  from google import genai
320
  from google.genai import types
321
  except ImportError:
322
  raise ImportError("Lance : pip install google-genai")
323
+
324
  if seed == -1 or control_after_generate == "randomize":
325
  actual_seed = random.randint(0, 2**31)
326
  elif control_after_generate == "increment":
327
  actual_seed = seed + 1
328
  else:
329
  actual_seed = seed
330
+
331
  client = genai.Client(api_key=api_key)
332
+
333
  safety_settings = []
334
  if safety_threshold != "OFF":
335
+ harm_categories = [
336
+ "HARM_CATEGORY_HARASSMENT",
337
+ "HARM_CATEGORY_HATE_SPEECH",
338
+ "HARM_CATEGORY_SEXUALLY_EXPLICIT",
339
+ "HARM_CATEGORY_DANGEROUS_CONTENT"
340
+ ]
341
  safety_settings = [types.SafetySetting(category=cat, threshold=safety_threshold) for cat in harm_categories]
342
+
343
  parts = []
344
+
345
+ if mode == "edit" and edit_image is not None:
346
+ parts.append(types.Part.from_bytes(
347
+ data=pil_to_bytes(tensor_to_pil(edit_image)),
348
+ mime_type="image/png"
349
+ ))
350
+
351
+ ref_images = [ref_image_1, ref_image_2, ref_image_3, ref_image_4,
352
+ ref_image_5, ref_image_6, ref_image_7]
353
+ for ref in ref_images:
354
+ if ref is not None:
355
+ parts.append(types.Part.from_bytes(
356
+ data=pil_to_bytes(tensor_to_pil(ref)),
357
+ mime_type="image/png"
358
+ ))
359
+
360
  parts.append(types.Part.from_text(text=prompt))
361
+
362
+ gen_config_kwargs = dict(
363
+ response_modalities=["TEXT", "IMAGE"],
364
+ temperature=temperature,
365
+ top_p=top_p,
366
+ image_config=types.ImageConfig(
367
+ aspect_ratio=aspect_ratio,
368
+ image_size=quality
369
+ ),
370
+ )
371
+ if top_k > 0:
372
+ gen_config_kwargs["top_k"] = top_k
373
+ if safety_settings:
374
+ gen_config_kwargs["safety_settings"] = safety_settings
375
+
376
  gen_config = types.GenerateContentConfig(**gen_config_kwargs)
377
+
378
+ print(f"[NanaBanana] -> {model} | mode:{mode} | quality:{quality} | safety:{safety_threshold}")
379
+
380
+ response = client.models.generate_content(
381
+ model=model,
382
+ contents=parts,
383
+ config=gen_config
384
+ )
385
+
386
  if not response.candidates:
387
  raise RuntimeError(f"[NanaBanana] Aucun candidat: {response}")
388
+
389
  candidate = response.candidates[0]
390
  finish_reason = str(getattr(candidate, "finish_reason", ""))
391
  if "SAFETY" in finish_reason:
392
  raise RuntimeError("[NanaBanana] Bloque par IMAGE_SAFETY. Reformule le prompt.")
393
+
394
  content = getattr(candidate, "content", None)
395
  if content is None or not getattr(content, "parts", None):
396
  raise RuntimeError(f"[NanaBanana] Content vide. finish_reason: {finish_reason}")
397
+
398
  result_image, info_text = None, ""
399
  for part in content.parts:
400
  if hasattr(part, "text") and part.text:
401
  info_text += part.text + "\n"
402
  elif hasattr(part, "inline_data") and part.inline_data:
403
  result_image = Image.open(io.BytesIO(part.inline_data.data)).convert("RGB")
404
+
405
  if result_image is None:
406
+ raise RuntimeError(f"[NanaBanana] Aucune image generee. Texte: {info_text or '(aucun)'}")
407
+
408
+ result_image = apply_color_grade(
409
+ result_image,
410
+ cg_brightness, cg_contrast, cg_saturation, cg_temperature, cg_sharpness
411
+ )
412
+
413
+ metadata = (
414
+ f"model: {model}\n"
415
+ f"mode: {mode}\n"
416
+ f"seed: {actual_seed}\n"
417
+ f"temperature: {temperature} | top_p: {top_p} | top_k: {top_k}\n"
418
+ f"aspect_ratio: {aspect_ratio} | quality: {quality}\n"
419
+ f"safety: {safety_threshold}\n"
420
+ f"{info_text.strip()}"
421
+ )
422
+ print(f"[NanaBanana] Succes ! ({quality})")
423
  return (pil_to_tensor(result_image), metadata)
424
 
425
+
426
  NODE_CLASS_MAPPINGS = {"NanaBananaProNode": NanaBananaProNode}
427
  NODE_DISPLAY_NAME_MAPPINGS = {"NanaBananaProNode": "🍌 Nano Banana Pro"}
428
  ENDOFFILE
 
756
  NODE_DISPLAY_NAME_MAPPINGS = {"GrokPromptExtractor": "πŸ€– Grok Prompt Extractor"}
757
  ENDOFFILE
758
 
759
+ # ── __init__.py ────────────────────────────────────────────────────────────
760
  cat > "${NBP_DIR}/__init__.py" << 'EOF'
761
  from .nano_banana_pro_node import NODE_CLASS_MAPPINGS as _NM1, NODE_DISPLAY_NAME_MAPPINGS as _DN1
762
  from .anya_prompt_extractor_node import NODE_CLASS_MAPPINGS as _NM2, NODE_DISPLAY_NAME_MAPPINGS as _DN2
 
817
  -H "Authorization: Bearer $HF_TOKEN" \
818
  -H "Content-Type: application/json")
819
 
 
820
  if [ "$response" -eq 200 ]; then
821
  return 0
822
  else
 
832
  -H "Authorization: Bearer $CIVITAI_TOKEN" \
833
  -H "Content-Type: application/json")
834
 
 
835
  if [ "$response" -eq 200 ]; then
836
  return 0
837
  else
 
846
  local forced_filename="$3"
847
  local model_id=""
848
 
 
849
  if [[ $url =~ /models/([0-9]+) ]]; then
850
  model_id="${BASH_REMATCH[1]}"
851
  else
 
855
 
856
  printf "Downloading CivitAI model %s...\n" "$model_id"
857
 
 
858
  if [[ -n "$forced_filename" ]]; then
859
  local output_file="${output_dir}/${forced_filename}"
860
  if [[ -f "$output_file" ]]; then
 
876
  fi
877
  fi
878
 
 
879
  local redirect_url=""
880
  if [[ -n "$CIVITAI_TOKEN" ]]; then
881
  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')
 
888
  return 1
889
  fi
890
 
 
891
  local filename=""
892
 
 
893
  if [[ $redirect_url =~ response-content-disposition=attachment.*filename%3D%22([^%\"]+) ]]; then
894
  filename="${BASH_REMATCH[1]}"
 
895
  filename=$(echo "$filename" | sed 's/%20/ /g; s/%2D/-/g; s/%2E/./g; s/%5F/_/g')
 
896
  elif [[ $redirect_url =~ filename=\"([^\"]+)\" ]]; then
897
  filename="${BASH_REMATCH[1]}"
 
898
  elif [[ $redirect_url =~ filename=([^&]+) ]]; then
899
  filename="${BASH_REMATCH[1]}"
 
900
  else
 
901
  local path_part=$(echo "$redirect_url" | sed 's/?.*//')
902
  filename=$(basename "$path_part")
 
 
903
  if [[ ! "$filename" =~ \.(safetensors|pt|pth|ckpt|bin)$ ]]; then
904
  filename="${filename}.safetensors"
905
  fi
906
  fi
907
 
 
908
  filename=$(printf '%b' "${filename//%/\\x}")
909
 
 
910
  if [[ -z "$filename" ]] || [[ "$filename" == "." ]] || [[ "$filename" == ".safetensors" ]]; then
911
  filename="civitai_${model_id}.safetensors"
912
  fi
913
 
914
  local output_file="${output_dir}/${filename}"
915
 
 
916
  if [[ -f "$output_file" ]]; then
917
  printf "File already exists: %s\n" "$filename"
918
  return 0
919
  fi
920
 
 
921
  printf "Downloading to: %s\n" "$filename"
922
  curl -L -o "$output_file" --progress-bar "$redirect_url"
923
 
 
936
  local dir="$2"
937
  local forced_filename="$3"
938
 
 
939
  if [[ $url =~ ^https://civitai\.com/api/download/models/([0-9]+) ]]; then
940
  download_civitai_bash "$url" "$dir" "$forced_filename"
 
941
  else
942
  if [[ -n "$forced_filename" ]]; then
943
  wget -qnc --show-progress -e dotbytes="${4:-4M}" -O "${dir}/${forced_filename}" "$url"