Sign In

🖼️ WebUI Image Generator on Google Colab!

20

🖼️ WebUI Image Generator on Google Colab!

Hello ~

So... I ran out of BUZZ to generate images and had to look for alternatives.

I found several, but there were so many steps that it was overwhelming. My solution was to refine it, and since I see it works, I'm sharing it with you.

By the way, I recommend only activating the first and last cells, since thanks to the Civitai key, you can download the LORAS and checkpoints from the Gradio interface. The images are hosted on Hub, but you should download them every time you generate them, since Google Collab sometimes pauses.

PS: This notebook is based on Segsmaker_COLAB's notebook, I simply adapted it to my tastes.

Open In Colab

🎨✨ Get your notebook ready with Civitai! 🔑

To get started with this notebook, you must activate T4 GPU. You'll also need your Civitai API key to download loras from the Gradio interface. If you don't have it yet, don't worry, here are the steps to obtain it.

🚀 How to get your Civitai API key:

1️⃣ Log in to Civitai with your account.

2️⃣ Click on your avatar (profile) in the top right corner.

3️⃣ Select "Settings" from the drop-down menu.

4️⃣ In the left panel, go to the "API" section.

5️⃣ Press the "Generate API Key" button.

6️⃣ Done! Copy your API key and store it in a safe place.

⚠️ Important: Your API key is personal and private. Do not share it with anyone, as it grants access to Civitai resources.

🚀🔥 SELECT YOUR WEB UI AND START THE SYSTEM 🔥🚀

# =====================================================
#@markdown ##### 🚀🔥 **SELECCIONA TU INTERFAZ WEBUI Y ARRANCA EL SISTEMA** 🔥🚀
# =====================================================

# 🎭 Selecciona la interfaz WebUI
webui = "A1111"  # @param ["ReForge", "ComfyUI", "A1111"]

# 🖼️ Elige la versión de Stable Diffusion
sd = "xl"  # @param ["1.5", "xl"]

# 🔑 Introduce tu API Key de Civitai
civitai_key = "Your_Api_key"  # @param {type:"string"}

# 🔐 Token de HuggingFace **(Opcional)**
hf_read_token = ""  # @param {type:"string"}

BGM = 'eqajIuKwVu4' # @param {type:"string", placeholder:"youtube video id, default to eqajIuKwVu4"}

# 📥 Descargando archivos de configuración...
!curl -sLo /content/setup.py https://github.com/gutris1/segsmaker/raw/main/script/KC/setup.py

# 🚀 Ejecutando configuración inicial...
%run /content/setup.py --webui="$webui" --sd="$sd" --civitai_key="$civitai_key" --hf_read_token="$hf_read_token"

print("✅ Configuración completada con éxito. ¡Listo para crear arte! 🎨✨")

📥✨ DOWNLOAD VAE, LORAS, CHECKPOINTS, EXTENSIONS, EMBEDDINGS AND UPSCALERS ✨📥

# ==========================================
#@markdown ### 📥✨ **DESCARGA DE VAE, EMBEDDINGS Y UPSCALERS** ✨📥
# ==========================================

# 🎨 **Links para VAE:**
vae_links = "https://civitai.com/api/download/models/290640?type=VAE&format=SafeTensor"  #@param {type:"string"}

# 🧠 **Links para Embeddings:**
embeddings_links = ""  #@param {type:"string"}

# 🔎 **Links para Upscalers:**
upscalers_links = ""  #@param {type:"string"}

#@markdown ### ⬇️ **Descarga de Modelos y LoRAs**


# 🎭 **Links para Checkpoint:**
checkpoint_links = "https://civitai.com/api/download/models/1490781?type=Model&format=SafeTensor&size=pruned&fp=fp16"  #@param {type:"string"}

# 🖌️ **Links para LoRA:**
lora_links = "https://civitai.com/api/download/models/1558670?type=Model&format=SafeTensor"  #@param {type:"string"}

import os

def download_links(link_string, output_path):
    """
 #@markdown #####   📡 Descarga archivos desde una lista de links separados por comas: (Url_1, Url_2, etc...)
    Args:
        link_string (str): Links separados por comas.
        output_path (str): Directorio donde guardar los archivos.
    """
    links = [link.strip() for link in link_string.split(",") if link.strip()]
    os.makedirs(output_path, exist_ok=True)  # ✅ Asegura que el directorio exista

    for link in links:
        print(f"⬇️ Descargando: {link} a {output_path}...")
        try:
            get_ipython().run_line_magic('download', link)
            print(f"✅ Descargado con éxito: {link}")
        except Exception as e:
            print(f"❌ Error al descargar {link}: {str(e)}")

# 🚀 **Iniciando descargas...**
print("\n🔵 Descargando **VAE**...")
%cd -q $VAE
download_links(vae_links, "./VAE")

print("\n🟢 Descargando **Embeddings**...")
%cd -q $Embeddings
download_links(embeddings_links, "./Embeddings")

print("\n🟠 Descargando **Upscalers**...")
%cd -q $Upscalers
download_links(upscalers_links, "./Upscalers")

print("\n🎉 ¡Descargas completadas! 🔥")

# 🚀 **Iniciando descargas...**
print("''' Checkpoint '''")
download_links(checkpoint_links, "./CKPT")

print("''' LoRA '''")
download_links(lora_links, "./LORA")

print("\n✅ Descarga completada. ¡Listo para usar los modelos en Stable Diffusion! 🚀")

# ========================================
#@markdown ##### 🔌✨ **DESCARGA Otras EXTENSIONES (Github Repositories)** ✨🔌
# ========================================

# 📥 **Links para Extensiones (Git Repositories)** 🔗
# (Separar por comas y un espacio si son múltiples)
extensions_links = "https://github.com/yankooliveira/sd-webui-photopea-embed"  #@param {type:"string"}

import os

def git_clone_links(link_string, output_path):
    """
#@markdown #####    🔄 Clona repositorios Git desde una lista de links separados por comas.
    Args:
        link_string (str): Links separados por comas.
        output_path (str): Directorio donde clonar los repositorios.
    """
    links = [link.strip() for link in link_string.split(",") if link.strip()]
    os.makedirs(output_path, exist_ok=True)  # ✅ Asegura que el directorio exista

    for link in links:
        print(f"🚀 Clonando: {link} a {output_path}...")
        try:
            os.system(f"git -C {output_path} clone {link}")
            print(f"✅ Clonación completada: {link}")
        except Exception as e:
            print(f"❌ Error al clonar {link}: {str(e)}")

# 📂 **Descargando extensiones...**
print("''' 🔧 Extensiones '''")
%cd -q $Extensions
git_clone_links(extensions_links, "./")

print("🎉 ¡Extensiones instaladas con éxito! 🔥")

🚀🔥 SELECT YOUR WEB UI INTERFACE and Start the cell: Now you're ready to create art! 🎨✨

from IPython.display import Audio
import time

# URL de una música épica libre de derechos
epic_music_url = "https://opengameart.org/sites/default/files/audio_preview/This%20World%20is%20Sh%23t.ogg.mp3"

# Reproducir el audio en Google Colab
audio = Audio(epic_music_url, autoplay=True)
display(audio)

# =====================================================
#@markdown #### 🚀🔥 SELECCIONA TU INTERFAZ WEB UI y Arranca la celda: ¡Ahora estás listo para crear arte! 🎨✨
# =====================================================

# 🎨 **Selecciona la interfaz WebUI:**
webui = "A1111"  #@param ["ReForge", "ComfyUI", "A1111"]

# Fix disconnect Ram
import os

# ==========================
# ⚙️ OPTIMIZACIÓN DE RAM 🔧
# ==========================

print("\n🔄 Verificando y optimizando memoria RAM...")

# 📌 Verificar y descargar libtcmalloc si no existe
if not os.path.exists("/content/libtcmalloc_minimal.so.4"):
    print("⬇️ Descargando libtcmalloc...")
    !wget https://github.com/camenduru/gperftools/releases/download/v1.0/libtcmalloc_minimal.so.4 -O /content/libtcmalloc_minimal.so.4
    print("✅ libtcmalloc instalado correctamente.")

# 🏗️ Establecer la variable de entorno para optimización: LD_PRELOAD
os.environ["LD_PRELOAD"] = "/content/libtcmalloc_minimal.so.4"
print("🚀 Optimización de RAM completada.\n")

# ==========================
# 🖥️ ARGUMENTOS PARA CADA WEBUI
# ==========================
arguments = {
    "A1111": "--xformers",
    "ComfyUI": "--dont-print-server --preview-method auto --use-pytorch-cross-attention",
    "ReForge": "--xformers --cuda-stream --pin-shared-memory"
}

# 📌 Obtener los argumentos correspondientes
selected_argument = arguments[webui]

# ==========================
# 🚀 EJECUCIÓN DE WEBUI
# ==========================

print(f"🛠️ Preparando ejecución de **{webui}**...")

# 📂 Cambiar al directorio correspondiente
%cd -q $WebUI

# 🎯 Ejecutar el script con los argumentos adecuados
print(f"🚀 Iniciando **{webui}** con argumentos: `{selected_argument}`")
%run segsmaker.py {selected_argument}

print("\n🎉 **WebUI en marcha!** 🚀🔥")

20