ローカルのパソコンでdiffusersを使って画像生成

インストール

https://github.com/huggingface/diffusers

 git clone https://github.com/huggingface/diffusers

pip install diffusers transformers accelerate safetensors   
pip install --upgrade diffusers[torch]

torchをインストールしてないならば

https://pytorch.org/get-started/locally

pip3 install torch torchvision --index-url https://download.pytorch.org/whl/cu128

モデルのダウンロード

https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-v1-5/blob/main/v1-5-pruned-emaonly.safetensors

プログラム

import torch
from diffusers import StableDiffusionPipeline
from pathlib import Path

# モデルと出力パスの指定
model_path = r"D:\WPy64-31241\content\stable-diffusion-webui\models\Stable-diffusion\v1-5-pruned-emaonly.safetensors"
output_dir = Path(r"E:\WPy64-31241\content\diffusers\outputs\txt2img-images")
output_dir.mkdir(parents=True, exist_ok=True)

# パイプラインの読み込み
pipe = StableDiffusionPipeline.from_single_file(
    model_path,
    torch_dtype=torch.float16,
    use_safetensors=True,
    variant="fp16"
).to("cuda")

# プロンプトの設定
prompt = "a futuristic cityscape at sunset, ultra detailed, 4k"

# 画像生成
image = pipe(prompt).images[0]

# 保存
output_path = output_dir / "generated_image.png"
image.save(output_path)

print(f"画像を保存しました: {output_path}")

仮想環境インストールおよび実行バッチファイル

@echo off
call %~dp0\scripts\env_for_icons.bat  %*
SET PATH=%PATH%;%WINPYDIRBASE%\PortableGit;%WINPYDIRBASE%\PortableGit\bin
SET PATH=%PATH%;%WINPYDIRBASE%\ffmpeg\bin
If not exist %WINPYDIRBASE%\content mkdir  %WINPYDIRBASE%\content 

set HF_HOME=E:\my_cache\hf_home
set TRANSFORMERS_CACHE=E:\my_cache\transformers
set DIFFUSERS_CACHE=E:\my_cache\diffusers
echo HF_HOME = %HF_HOME%
echo TRANSFORMERS_CACHE = %TRANSFORMERS_CACHE%
echo DIFFUSERS_CACHE = %DIFFUSERS_CACHE%

set APP_NAME=diffusers
set APP_DIR=%WINPYDIRBASE%\content\%APP_NAME%
echo %APP_DIR%
cd %WINPYDIRBASE%\content\

If not exist  %APP_DIR% git clone https://github.com/huggingface/diffusers


cd %APP_DIR%
timeout /t 5
if not defined VENV_DIR (set "VENV_DIR=%APP_DIR%\venv")
if EXIST %VENV_DIR% goto :activate_venv

::python.exe -m venv "%VENV_DIR%" 
python.exe -m venv "%VENV_DIR%" --system-site-packages 
if %ERRORLEVEL% == 0 goto :pip
echo Unable to create venv 
goto :skip_venv

:pip
call "%VENV_DIR%\Scripts\activate"

pip install -r requirements.txt
pip install diffusers transformers accelerate safetensors

pip install "huggingface_hub[cli]"

::huggingface-cli download stable-diffusion-v1-5/stable-diffusion-v1-5 --local-dir ./models
cmd.exe /k

:activate_venv
call "%VENV_DIR%\Scripts\activate"
 ::
python.exe .\modules\StableDiffusion.py

 ::cmd.exe /k
goto :skip_venv
:skip_cmd
::
:skip_venv
 :: ::cmd.exe /k

timeout /t 55