MarkdownとBullet Journal

いわゆるプログラマーのつぶやき

【備忘録】Stable Diffusionをcolabで動かすコード一覧

Google colabで生成した例

別記事で導入解説

詳細な説明と事例を加えた、未経験者でも簡単にGoogle colabでStable Diffusionを使うための解説記事はこちら。

programmingforever.hatenablog.com

自分のメモ用

こちらの記事は自分の備忘録としてまとめた。Stable Diffusion系列のAI画像生成をGoogle colabで使うための設定を自分用にまとめたもので、バージョン変更の都度修正する予定。具体的な導入方法の手順等は割愛しているので、詳細を知りたい方は前記リンクの記事を参照して欲しい。

①Stable Diffusion : txt2img

# ①Stable Diffusionパッケージをインストール
!pip install diffusers==0.3.0 transformers scipy ftfy

# ②Hugging Faceへのアクセストークンをトークン変数に格納
MyTOKEN="<HugginFace HubのサイトでコピーしたAccess Tokenをここに入れる>"

# ③StableDiffusionパイプラインを準備する
from diffusers import StableDiffusionPipeline

pipe = StableDiffusionPipeline.from_pretrained(
    "CompVis/stable-diffusion-v1-4", 
    use_auth_token=MyTOKEN
).to("cuda")

# ④プロンプトを与えて画像を生成する
ffrom torch import autocast

prompt = "japanese girl"
with autocast("cuda"):
    images = pipe(prompt, guidance_scale=7.5).images
images[0].save("output.png")

上記のモデルID(フォルダとモデル名)を変更するだけで、WaifuやTrinartなどStable Diffusion以外のモデルが使える。

それではブロック③で変更する箇所のみを以下に記載する

# モデル:Stable Diffusion 1.4を使用する場合

pipe = StableDiffusionPipeline.from_pretrained(
    "CompVis/stable-diffusion-v1-4",                   # 変更箇所はこの行のみ
    use_auth_token=MyTOKEN
).to("cuda")

# モデル:Waifu Diffusion を使用する場合

pipe = StableDiffusionPipeline.from_pretrained(
    "hakurei/waifu-diffusion",                        # 変更箇所はこの行のみ
    use_auth_token=MyTOKEN
).to("cuda")

# モデル:Trinart Diffusion V2 を使用する場合

pipe = StableDiffusionPipeline.from_pretrained(
    "ayan4m1/trinart_diffusers_v2”",                   # 変更箇所はこの行のみ
    use_auth_token=MyTOKEN
).to("cuda")

モデルはその他にも多数あり同様に使える。以下紹介記事。

programmingforever.hatenablog.com

またDreamboothで作られたコンセプトもモデル同様に扱える。Dreambooth Concepts Libraryに多数掲載されている各コンセプトを利用したい場合は、下記のdiffusersのパイプラインのモデルIDCompVis/stable-diffusion-v1-4の部分を、'sd-dreambooth-library/XXXX`に変更するだけでよい。以下にDreambooth Concepts LibraryサイトのURLを記載する。

sd-dreambooth-library (Stable Diffusion Dreambooth Concepts Library)

 

②Stable Diffusion : img2img

# ①Stable Diffusionパッケージをインストール
# img2img対応したバージョンをインストールするためにGitHubのリポジトリを指定
!pip install transformers scipy ftfy
!pip install git+https://github.com/huggingface/diffusers.git

# ②Hugging Faceへのアクセストークンをトークン変数に格納
MyTOKEN="<HugginFace HubのサイトでコピーしたAccess Tokenをここに入れる>"

# ③StableDiffusionパイプラインを準備する
import torch
from diffusers import StableDiffusionImg2ImgPipeline

pipe = StableDiffusionImg2ImgPipeline.from_pretrained(
    "CompVis/stable-diffusion-v1-4",
    revision="fp16", 
    torch_dtype=torch.float16,
    use_auth_token=MyTOKEN
).to("cuda")

# ④画像を与えて画像を生成する
from PIL import Image
from torch import autocast

# 与える画像は512x512サイズ限定
prompt = "Kitten surrounded by flowers in a poster style garden with mountains in the distance"
init_image = Image.open("<アップロードしたファイル名をここに入れる>").convert("RGB")
init_image = init_image.resize((512, 512))    # 512x512にリサイズ
with autocast("cuda"):
    images = pipe(
        prompt=prompt,
        init_image=init_image,
        strength=0.85
        )["sample"]

images[0].save("output.png")

③Waifu Diffusion : txt2img

# ①Stable Diffusionパッケージをインストール
!pip install diffusers==0.3.0 transformers scipy ftfy

# ②StableDiffusionパイプラインの準備
import torch
from torch import autocast
from diffusers import StableDiffusionPipeline, DDIMScheduler

pipe = StableDiffusionPipeline.from_pretrained(
    "hakurei/waifu-diffusion",               # ここでwaifu-diffusionを指定
    torch_dtype=torch.float16,
    revision="fp16",
    scheduler=DDIMScheduler(
        beta_start=0.00085,
        beta_end=0.012,
        beta_schedule="scaled_linear",
        clip_sample=False,
        set_alpha_to_one=False,
    ),
).to("cuda")

# ③プロンプトから画像を生成する
prompt = "cute cat ear maid"
with autocast("cuda"):
    images = pipe(prompt, guidance_scale=7.5).images  
images[0].save("output.png")

情報元

Pythonコードは下記リンクを参照した。

note.com

ysko909.github.io

④Stable Diffusion + Textual Inversion

解説記事

note.com

⑤Waifu Diffusion + Textual inversion

解説記事

birdmanikioishota.blog.fc2.com

⑥NSFW回避

別記事で説明したAUTOMATIC1111使えば、NSFWフィルターを設定でON/OFFできる。

programmingforever.hatenablog.com

本記事のノートブックでNSFWを外したい場合はGoogle colabの下記フォルダのファイルを書き換え保存してからランタイムを再起動する。なおリスクのある画像を生成するとGoogleの垢BANになる噂があるので要注意。

生成した画像内の肌の面積が多くてNSFWフィルターが発動してしまう時に使えば効果的。

# 対象フォルダとファイル
/usr/local/lib/python3.7/dist-packages/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion.py

# 修正箇所

# run safety checker
safety_cheker_input = self.feature_extractor(self.numpy_to_pil(image), return_tensors="pt").to(self.device)
image, has_nsfw_concept = self.safety_checker(images=image, clip_input=safety_cheker_input.pixel_values)

 ↓

# run safety checker
        safety_cheker_input = self.feature_extractor(self.numpy_to_pil(image), return_tensors="pt").to(self.device)
        image, has_nsfw_concept = [False]

# ファイル保存(CTRL+S)してからランタイム再起動