File size: 5,993 Bytes
8652b04 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 | #!/usr/bin/env python3
"""Generate images with the locally downloaded Lustify SDXL model."""
from __future__ import annotations
import argparse
import os
from pathlib import Path
os.environ.setdefault("TOKENIZERS_PARALLELISM", "false")
import torch
from diffusers import DPMSolverMultistepScheduler, StableDiffusionXLPipeline
DEFAULT_MODEL = Path(__file__).resolve().parent / "models" / "Lustify-SDXL-GGWP-v7"
DEFAULT_NEGATIVE_PROMPT = (
"low quality, worst quality, blurry, deformed, distorted, bad anatomy, "
"bad hands, extra fingers, missing fingers, watermark, text, logo"
)
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description="Generate an image with Lustify SDXL GGWP v7")
prompt_group = parser.add_mutually_exclusive_group(required=True)
prompt_group.add_argument("--prompt", help="Text prompt")
prompt_group.add_argument(
"--prompt-file",
type=Path,
help="Read the text prompt from a UTF-8 file",
)
negative_group = parser.add_mutually_exclusive_group()
negative_group.add_argument(
"--negative-prompt",
default=DEFAULT_NEGATIVE_PROMPT,
help="Negative prompt",
)
negative_group.add_argument(
"--negative-prompt-file",
type=Path,
help="Read the negative prompt from a UTF-8 file",
)
parser.add_argument("--output", default="outputs/lustify.png", help="Output image path")
parser.add_argument("--model", type=Path, default=DEFAULT_MODEL, help="Local model directory")
parser.add_argument(
"--device",
default=None,
help="Torch device, for example cuda:0 or cpu (default: cuda:0 when available)",
)
parser.add_argument(
"--offload",
choices=("none", "model", "sequential"),
default="none",
help="CPU offload mode (default: none)",
)
parser.add_argument(
"--scheduler",
choices=("dpmpp-2m-sde-karras", "euler-a"),
default="dpmpp-2m-sde-karras",
)
parser.add_argument("--width", type=int, default=1024)
parser.add_argument("--height", type=int, default=1024)
parser.add_argument("--steps", type=int, default=30)
parser.add_argument("--guidance-scale", type=float, default=5.5)
parser.add_argument("--seed", type=int, default=None)
parser.add_argument("--num-images", type=int, default=1)
return parser.parse_args()
def validate_args(args: argparse.Namespace) -> None:
if not args.model.is_dir():
raise SystemExit(f"Model directory does not exist: {args.model}")
for label, path in (
("Prompt", args.prompt_file),
("Negative prompt", args.negative_prompt_file),
):
if path is not None and not path.is_file():
raise SystemExit(f"{label} file does not exist: {path}")
if args.width <= 0 or args.height <= 0 or args.width % 8 or args.height % 8:
raise SystemExit("--width and --height must be positive multiples of 8")
if args.steps <= 0:
raise SystemExit("--steps must be greater than 0")
if args.num_images <= 0:
raise SystemExit("--num-images must be greater than 0")
def read_text(direct: str | None, path: Path | None, label: str) -> str:
text = direct
if path is not None:
text = path.read_text(encoding="utf-8").strip()
if not text:
raise SystemExit(f"{label} is empty")
return text
def configure_device(pipe: StableDiffusionXLPipeline, device: str, offload: str) -> None:
torch_device = torch.device(device)
if torch_device.type != "cuda":
pipe.to(torch_device)
return
gpu_id = torch_device.index
if gpu_id is None:
gpu_id = torch.cuda.current_device()
if offload == "model":
pipe.enable_model_cpu_offload(gpu_id=gpu_id)
elif offload == "sequential":
pipe.enable_sequential_cpu_offload(gpu_id=gpu_id)
else:
pipe.to(torch_device)
def save_images(images: list, output: Path) -> None:
output.parent.mkdir(parents=True, exist_ok=True)
if len(images) == 1:
images[0].save(output)
print(f"Saved: {output.resolve()}")
return
stem, suffix = output.stem, output.suffix or ".png"
for index, image in enumerate(images, start=1):
path = output.with_name(f"{stem}_{index:02d}{suffix}")
image.save(path)
print(f"Saved: {path.resolve()}")
def main() -> None:
args = parse_args()
validate_args(args)
prompt = read_text(args.prompt, args.prompt_file, "Prompt")
negative_prompt = read_text(
args.negative_prompt,
args.negative_prompt_file,
"Negative prompt",
)
device = args.device or ("cuda:0" if torch.cuda.is_available() else "cpu")
dtype = torch.float16 if device.startswith("cuda") else torch.float32
print(f"Loading model from {args.model}")
print(f"Device: {device} ({dtype}), offload: {args.offload}")
pipe = StableDiffusionXLPipeline.from_pretrained(
args.model,
torch_dtype=dtype,
use_safetensors=True,
local_files_only=True,
)
if args.scheduler == "dpmpp-2m-sde-karras":
pipe.scheduler = DPMSolverMultistepScheduler.from_config(
pipe.scheduler.config,
algorithm_type="sde-dpmsolver++",
use_karras_sigmas=True,
)
configure_device(pipe, device, args.offload)
pipe.vae.enable_slicing()
pipe.set_progress_bar_config(disable=False)
generator = None
if args.seed is not None:
generator = torch.Generator(device="cpu").manual_seed(args.seed)
result = pipe(
prompt=prompt,
negative_prompt=negative_prompt,
width=args.width,
height=args.height,
num_inference_steps=args.steps,
guidance_scale=args.guidance_scale,
num_images_per_prompt=args.num_images,
generator=generator,
)
save_images(result.images, Path(args.output))
if __name__ == "__main__":
main()
|