【要約】 AUTOMATIC1111は、PythonとPyTorchを使用したテキストから画像を生成するWebUIを提供。Windows上で動作し、GitHubからダウンロードできる。インストール後は http://127.0.0.1:7860 でアクセスし、学習済みモデルを選択して利用可能。また、SDXL(画像生成モデル)も提供されている。AUTOMATIC1111 の公式ページからのSDXLのダウンロード、インストール、img2txt と img2img の方法を説明している。いずれも,作成したい画像について英語のテキストで記述し,「Generate」をクリックして結果を確認できる。さらに一括画像生成のPythonプログラムも紹介している。複数の画像を1回の操作で生成することができ便利である。
画像生成 (txt2img),画像変換 (img2img)
複数の画像を一度に画像生成
【目次】
Stable Diffusion XL (SDXL) は,Stability AIによって開発されたDiffusionベースの image-to-text の画像生成モデルである. SDXLはStable Diffusion with Larger UNet Backboneの略称である.
SDXLは,以前のStable Diffusionモデルと比較して,UNetバックボーンのサイズが3倍に増加している.この増加は,アテンションブロック数の増加とクロスアテンションコンテキストの拡大によるものである.また,SDXLはリファインメントモデルを導入している.このリファインメントモデルは,SDXLによって生成された画像の視覚的な精度を向上させるために使用される.
【文献】
D ustin Podell, Zion English, Kyle Lacey, Andreas Blattmann, Tim Dockhorn, Jonas Müller, Joe Penna, Robin Rombach: SDXL: Improving Latent Diffusion Models for High-Resolution Image Synthesis. CoRR abs/2307.01952, 2023.
https://arxiv.org/pdf/2307.01952v1.pdf
【サイト内の関連ページ】
【関連する外部ページ】
Gitは,バージョン管理システム.ソースコードの管理や複数人での共同に役立つ.
【サイト内の関連ページ】
Windows での Git のインストール: 別ページ »で説明している.
【関連する外部ページ】
Git の公式ページ: https://git-scm.com/
【サイト内の関連ページ】
【関連する外部ページ】
Python の公式ページ: https://www.python.org/
【サイト内の関連ページ】
NVIDIA グラフィックスボードを搭載しているパソコンの場合には, NVIDIA ドライバ, NVIDIA CUDA ツールキット, NVIDIA cuDNN のインストールを行う.
【関連する外部ページ】
コマンドプロンプトを管理者として実行: 別ページ »で説明
PyTorch のページ: https://pytorch.org/index.html
次のコマンドを実行することにより, PyTorch 2.3 (NVIDIA CUDA 11.8 用)がインストールされる. 但し,Anaconda3を使いたい場合には別手順になる.
事前に NVIDIA CUDA のバージョンを確認しておくこと(ここでは,NVIDIA CUDA ツールキット 11.8 が前もってインストール済みであるとする).
PyTorch で,GPU が動作している場合には,「torch.cuda.is_available()」により,True が表示される.
python -m pip install -U --ignore-installed pip python -m pip uninstall -y torch torchvision torchaudio python -m pip install -U torch torchvision torchaudio numpy --index-url https://download.pytorch.org/whl/cu118 python -c "import torch; print(torch.__version__, torch.cuda.is_available())"
Anaconda3を使いたい場合には, Anaconda プロンプト (Anaconda Prompt) を管理者として実行し, 次のコマンドを実行する. (PyTorch と NVIDIA CUDA との連携がうまくいかない可能性があるため,Anaconda3を使わないことも検討して欲しい).
conda install -y pytorch torchvision torchaudio pytorch-cuda=11.8 cudnn -c pytorch -c nvidia py -c "import torch; print(torch.__version__, torch.cuda.is_available())"
【サイト内の関連ページ】
【関連する外部ページ】
AUTOMATIC1111 の stable-diffusion-webui の GitHUb のページ: https://github.com/AUTOMATIC1111/stable-diffusion-webui
コマンドプロンプトを管理者として実行: 別ページ »で説明
cd %HOMEPATH% rmdir /s /q stable-diffusion-webui git clone https://github.com/AUTOMATIC1111/stable-diffusion-webui
「--update-all-extensions」を付けて実行することで,拡張機能(extension) の更新を行っている.
このとき, WebUI のバージョンが表示されるので確認.
エラーメッセージが出ていないことを確認.
cd %HOMEPATH% cd stable-diffusion-webui webui.bat --update-all-extensions
このとき,次のような「Couldn't launch python exit code: 9009 stderr: Python Launch unsuccessful. Exiting 」という表示が出た場合は, Python のインストールを行ってから,上の操作をやり直す.
右上のメニューでは,学習済みモデルを選ぶことができる. 2023年6月時点では,インストール直後に,V1-5-pruned-emaonly,safetensorsを選ぶことができる.
解像度は1920 x 1024 にしている.
プロンプトとして次を入れている.
(master piece:1,1) (best quality:1,1), cinematic lighting, 4k, 8k, Standing on a sandy beach by the sea, the vast ocean reflects sunlight. A forest trees, while in the distance, mountains with snow-capped peaks appear. The clear blue sky and warm sunlight create a perfect setting. Today is meant for playing on the beach, inspired by the beautiful scenery.
画像をクリックすると拡大表示できる.
コマンドプロンプトを管理者として実行: 別ページ »で説明
cd %HOMEPATH% cd stable-diffusion-webui cd venv cd scripts .\python -m pip install -U xformers
https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Features#stable-diffusion-20
ダウンロードしたファイルはあとで使用する.
https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Features#stable-diffusion-20
ダウンロードしたファイルはあとで使用する.
コマンドプロンプトを管理者として実行: 別ページ »で説明
cd %HOMEPATH% cd stable-diffusion-webui webui-user.bat
少ないビデオメモリで動かすために,公式ページでは「--lowvram」,「--medvram 」が案内されている.
webui-user.bat --lowvram
webui-user.bat --medvram
ここでは,sd_xl_base_1.0_0.9vae_safetensorsを選択
解像度は1920 x 1024 にしている.
プロンプトとして次を入れている.
(master piece:1,1) (best quality:1,1), cinematic lighting, 4k, 8k, Standing on a sandy beach by the sea, the vast ocean reflects sunlight. A forest trees, while in the distance, mountains with snow-capped peaks appear. The clear blue sky and warm sunlight create a perfect setting. Today is meant for playing on the beach, inspired by the beautiful scenery.
「Generate」をクリック.
画像合成で得られた画像をimg2img を用いて画像改善する
得られた画像
得られた画像
得られた画像
得られた画像
【関連する外部ページ】
AUTOMATIC1111 の API の公式ページ: https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/API
コマンドプロンプトを管理者として実行: 別ページ »で説明
前準備として「webui.bat --api --allow-code」で起動.(--allow-code はプロンプト中にコードを含めることを可能にするもの.今回はこの機能は使っていない)
cd %HOMEPATH% cd stable-diffusion-webui webui.bat --api --allow-code
cd %HOMEPATH% cd stable-diffusion-webui notepad txt2img.py
このプログラムは, AUTOMATIC1111 の API の公式ページ: https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/API で公開されていたものを変更して使用している.
import json import requests import io import base64 from PIL import Image, PngImagePlugin import os import tkinter as tk def get_file_extension(filename): # ファイル名と拡張子を取得 _, extension = os.path.splitext(filename) # 拡張子の先頭のピリオドを取り除く return extension[1:] def remove_file_extension(filename): # ファイル名と拡張子を取得 filename_without_extension, _ = os.path.splitext(filename) return filename_without_extension def get_response(url, payload): response = requests.post(url=url, json=payload) return response.json() def save_image(image_data, fname): image = Image.open(io.BytesIO(base64.b64decode(image_data.split(",", 1)[0]))) png_payload = { "image": "data:image/png;base64," + image_data } response2 = requests.post(url=f'{url}/sdapi/v1/png-info', json=png_payload) pnginfo = PngImagePlugin.PngInfo() pnginfo.add_text("parameters", response2.json().get("info")) print(fname) image.save(fname, pnginfo=pnginfo) def generate_images(): global url_entry url = url_entry.get() output_filename = output_filename_entry.get() number_of_files = int(number_of_files_entry.get()) model = model_entry.get() prompt = prompt_entry.get("1.0", tk.END) width = int(width_entry.get()) height = int(height_entry.get()) steps = int(steps_entry.get()) cfg_scale = int(cfg_scale_entry.get()) negative_prompt = negative_prompt_entry.get("1.0", tk.END) payload = { "sd_model_checkpoint": model, } response = get_response(f'{url}/sdapi/v1/options', payload) strings = [f"{i:02}" for i in range(number_of_files)] for i in strings: payload = { "prompt": prompt, "width": width, "height": height, "steps": steps, "cfg_scale": cfg_scale, "negative_prompt": negative_prompt, } response = get_response(f'{url}/sdapi/v1/txt2img', payload) for j in response['images']: save_image(j, remove_file_extension(output_filename) + i + '.' + get_file_extension(output_filename)) url_entry = None; output_filename_entry = None; number_of_files_entry = None; model_entry = None; prompt_entry = None; width_entry = None; height_entry = None; steps_entry = None; cfg_scale_entry = None; negative_prompt_entry = None; def main(): global url_entry, output_filename_entry, number_of_files_entry, model_entry, prompt_entry, width_entry, height_entry, steps_entry, cfg_scale_entry, negative_prompt_entry # Tkinter GUI setup root = tk.Tk() root.title("Image Generation Configurator") tk.Label(root, text="URL:").grid(row=0, column=0, padx=5, pady=5) url_entry = tk.Entry(root, width=50) url_entry.grid(row=0, column=1, columnspan=3, padx=5, pady=5) url_entry.insert(tk.END, "http://127.0.0.1:7860") tk.Label(root, text="Output Filename:").grid(row=1, column=0, padx=5, pady=5) output_filename_entry = tk.Entry(root, width=50) output_filename_entry.grid(row=1, column=1, columnspan=3, padx=5, pady=5) output_filename_entry.insert(tk.END, "output.png") tk.Label(root, text="Number of Files:").grid(row=2, column=0, padx=5, pady=5) number_of_files_entry = tk.Entry(root, width=50) number_of_files_entry.grid(row=2, column=1, columnspan=3, padx=5, pady=5) number_of_files_entry.insert(tk.END, "20") tk.Label(root, text="model:").grid(row=3, column=0, padx=5, pady=5) model_entry = tk.Entry(root, width=50) model_entry.grid(row=3, column=1, columnspan=3, padx=5, pady=5) model_entry.insert(tk.END, "sd_xl_base_1.0_0.9vae.safetensors [e6bb9ea85b]") tk.Label(root, text="Prompt:").grid(row=4, column=0, padx=5, pady=5) prompt_entry = tk.Text(root, width=50, height=6) prompt_entry.grid(row=4, column=1, columnspan=3, padx=5, pady=5) prompt_entry.insert(tk.END, "person, (master piece:1,1) (best quality:1,1), 4k, 8k") tk.Label(root, text="Width:").grid(row=5, column=0, padx=5, pady=5) width_entry = tk.Entry(root, width=50) width_entry.grid(row=5, column=1, columnspan=3, padx=5, pady=5) width_entry.insert(tk.END, "1024") tk.Label(root, text="Height:").grid(row=6, column=0, padx=5, pady=5) height_entry = tk.Entry(root, width=50) height_entry.grid(row=6, column=1, columnspan=3, padx=5, pady=5) height_entry.insert(tk.END, "1024") tk.Label(root, text="Steps:").grid(row=7, column=0, padx=5, pady=5) steps_entry = tk.Entry(root, width=50) steps_entry.grid(row=7, column=1, columnspan=3, padx=5, pady=5) steps_entry.insert(tk.END, "20") tk.Label(root, text="Cfg Scale:").grid(row=8, column=0, padx=5, pady=5) cfg_scale_entry = tk.Entry(root, width=50) cfg_scale_entry.grid(row=8, column=1, columnspan=3, padx=5, pady=5) cfg_scale_entry.insert(tk.END, "7") tk.Label(root, text="Negative Prompt:").grid(row=9, column=0, padx=5, pady=5) negative_prompt_entry = tk.Text(root, width=50, height=10) negative_prompt_entry.grid(row=9, column=1, columnspan=3, padx=5, pady=5) negative_prompt_entry.insert(tk.END, "(((deformed))), blurry, bad anatomy, disfigured, poorly drawn face, mutation, mutated, (extra_limb), (ugly), (poorly drawn hands), fused fingers, messy drawing, broken legs censor, censored, censor_bar, multiple breasts, (mutated hands and fingers:1.5), (long body :1.3), (mutation, poorly drawn :1.2), black-white, bad anatomy, liquid body, liquidtongue, disfigured, malformed, mutated, anatomical nonsense, text font ui, error, malformed hands, long neck, blurred, lowers, low res, bad anatomy, bad proportions, bad shadow, uncoordinated body, unnatural body, fused breasts, bad breasts, huge breasts, poorly drawn breasts, extra breasts, liquid breasts, heavy breasts, missingbreasts, huge haunch, huge thighs, huge calf, bad hands, fused hand, missing hand, disappearing arms, disappearing thigh, disappearing calf, disappearing legs, fusedears, bad ears, poorly drawn ears, extra ears, liquid ears, heavy ears, missing ears, fused animal ears, bad animal ears, poorly drawn animal ears, extra animal ears, liquidanimal ears, heavy animal ears, missing animal ears, text, ui, error, missing fingers, missing limb, fused fingers, one hand with more than 5 fingers, one hand with less than5 fingers, one hand with more than 5 digit, one hand with less than 5 digit, extra digit, fewer digits, fused digit, missing digit, bad digit, liquid digit, colorful tongue, blacktongue, cropped, watermark, username, blurry, JPEG artifacts, signature, malformed feet, extra feet, bad feet, poorly drawnfeet, fused feet, missing feet, extra shoes, bad shoes, fused shoes, more than two shoes, poorly drawn shoes, bad gloves, poorly drawn gloves, fused gloves, bad cum, poorly drawn cum, fused cum, bad hairs, poorly drawn hairs, fused hairs, big muscles, ugly, bad face, fused face, poorly drawn face, cloned face, big face, long face, badeyes, fused eyes poorly drawn eyes, extra eyes, malformed limbs, more than 2 nipples, missing nipples, different nipples, fused nipples, bad nipples, poorly drawnnipples, black nipples, colorful nipples, gross proportions. short arm, (((missing arms))), missing thighs, missing calf, missing legs, mutation, duplicate, morbid, mutilated, poorly drawn hands, more than 1 left hand, more than 1 right hand, deformed, (blurry), disfigured, missing legs, extra arms, extra thighs, more than 2 thighs, extra calf,fused calf, extra legs, bad knee, extra knee, more than 2 legs, bad tails, bad mouth, fused mouth, poorly drawn mouth, bad tongue, tongue within mouth, too longtongue, black tongue, big mouth, cracked mouth, bad mouth, dirty face, dirty teeth, dirty pantie, fused pantie, poorly drawn pantie, fused cloth, poorly drawn cloth, badpantie, yellow teeth, thick lips, bad camel toe, colorful camel toe, bad asshole, poorly drawn asshole, fused asshole, missing asshole, bad anus, bad pussy, bad crotch, badcrotch seam, fused anus, fused pussy, fused anus, fused crotch, poorly drawn crotch, fused seam, poorly drawn anus, poorly drawn pussy, poorly drawn crotch, poorlydrawn crotch seam, bad thigh gap, missing thigh gap, fused thigh gap, liquid thigh gap, poorly drawn thigh gap, poorly drawn anus, bad collarbone, fused collarbone, missing collarbone, liquid collarbone, strong girl, obesity, worst quality, low quality, normal quality, liquid tentacles, bad tentacles, poorly drawn tentacles, split tentacles, fused tentacles, missing clit, bad clit, fused clit, colorful clit, black clit, liquid clit, QR code, bar code, censored, safety panties, safety knickers, beard, furry, pony, pubic hair, mosaic, futa, testis, (((deformed))), blurry, bad anatomy, disfigured, poorly drawn face, mutation, mutated, (extra_limb), (ugly), (poorly drawn hands), fused fingers, messy drawing, broken legs censor, censored, censor_bar, multiple breasts, (mutated hands and fingers:1.5), (long body :1.3), (mutation, poorly drawn :1.2), black-white, bad anatomy, liquid body, liquidtongue, disfigured, malformed, mutated, anatomical nonsense, text font ui, error, malformed hands, long neck, blurred, lowers, low res, bad anatomy, bad proportions, bad shadow, uncoordinated body, unnatural body, fused breasts, bad breasts, huge breasts, poorly drawn breasts, extra breasts, liquid breasts, heavy breasts, missingbreasts, huge haunch, huge thighs, huge calf, bad hands, fused hand, missing hand, disappearing arms, disappearing thigh, disappearing calf, disappearing legs, fusedears, bad ears, poorly drawn ears, extra ears, liquid ears, heavy ears, missing ears, fused animal ears, bad animal ears, poorly drawn animal ears, extra animal ears, liquidanimal ears, heavy animal ears, missing animal ears, text, ui, error, missing fingers, missing limb, fused fingers, one hand with more than 5 fingers, one hand with less than5 fingers, one hand with more than 5 digit, one hand with less than 5 digit, extra digit, fewer digits, fused digit, missing digit, bad digit, liquid digit, colorful tongue, blacktongue, cropped, watermark, username, blurry, JPEG artifacts, signature, 3D, 3D game, 3D game scene, 3D character, malformed feet, extra feet, bad feet, poorly drawnfeet, fused feet, missing feet, extra shoes, bad shoes, fused shoes, more than two shoes, poorly drawn shoes, bad gloves, poorly drawn gloves, fused gloves, bad cum, poorly drawn cum, fused cum, bad hairs, poorly drawn hairs, fused hairs, big muscles, ugly, bad face, fused face, poorly drawn face, cloned face, big face, long face, badeyes, fused eyes poorly drawn eyes, extra eyes, malformed limbs, more than 2 nipples, missing nipples, different nipples, fused nipples, bad nipples, poorly drawnnipples, black nipples, colorful nipples, gross proportions. short arm, (((missing arms))), missing thighs, missing calf, missing legs, mutation, duplicate, morbid, mutilated, poorly drawn hands, more than 1 left hand, more than 1 right hand, deformed, (blurry), disfigured, missing legs, extra arms, extra thighs, more than 2 thighs, extra calf,fused calf, extra legs, bad knee, extra knee, more than 2 legs, bad tails, bad mouth, fused mouth, poorly drawn mouth, bad tongue, tongue within mouth, too longtongue, black tongue, big mouth, cracked mouth, bad mouth, dirty face, dirty teeth, dirty pantie, fused pantie, poorly drawn pantie, fused cloth, poorly drawn cloth, badpantie, yellow teeth, thick lips, bad camel toe, colorful camel toe, bad asshole, poorly drawn asshole, fused asshole, missing asshole, bad anus, bad pussy, bad crotch, badcrotch seam, fused anus, fused pussy, fused anus, fused crotch, poorly drawn crotch, fused seam, poorly drawn anus, poorly drawn pussy, poorly drawn crotch, poorlydrawn crotch seam, bad thigh gap, missing thigh gap, fused thigh gap, liquid thigh gap, poorly drawn thigh gap, poorly drawn anus, bad collarbone, fused collarbone, missing collarbone, liquid collarbone, strong girl, obesity, worst quality, low quality, normal quality, liquid tentacles, bad tentacles, poorly drawn tentacles, split tentacles, fused tentacles, missing clit, bad clit, fused clit, colorful clit, black clit, liquid clit, QR code, bar code, censored, safety panties, safety knickers, beard, furry, pony, pubic hair, mosaic, futa, testis") generate_button = tk.Button(root, text="Generate Images", command=generate_images) generate_button.grid(row=10, column=0, columnspan=4, padx=5, pady=10) root.mainloop() if __name__ == "__main__": main()
Python プログラムの実行
Python 開発環境(Jupyter Qt Console, Jupyter ノートブック (Jupyter Notebook), Jupyter Lab, Nteract, Spyder, PyCharm, PyScripterなど)も便利である.
Python のまとめ: 別ページ »にまとめ
プログラムを txt2img.pyのようなファイル名で保存したので, 「python txt2img.py」のようなコマンドで行う.
python txt2img.py
モデルの既定値(デフォルト値)は,sd_xl_base_1.0_0.9vae.safetensors [e6bb9ea85b]」にしている.
Output Filename で「output.png」と設定すると,生成される画像ファイル名はoutput00.png, output01.png ... のようなファイル名になる.
その他の設定
下のプログラムでは,https://huggingface.co/Deltaadams/HentaiDiffusion/resolve/main/Universal%20Negative%20Prompt%20Text.txtで公開されているものから「3D」についての記載を取り除いたものを既定値(デフォルト値)としている.
複数の画像を1回の操作で生成している.
下は,prompt に 「"Johannes Vermeer, fine art, master work, oil painting, (master piece:1,1) (best quality:1,1), 4k, 8k"」を設定して実行したときの結果
https://github.com/ahgsql/StyleSelectorXL