pythonintermediate

Stable Diffusion Text-to-Image in Python

Generate images from text prompts locally using HuggingFace Diffusers and Stable Diffusion XL.

python
from diffusers import StableDiffusionXLPipeline
import torch
from pathlib import Path

pipe = StableDiffusionXLPipeline.from_pretrained(
    'stabilityai/stable-diffusion-xl-base-1.0',
    torch_dtype=torch.float16,
    use_safetensors=True,
    variant='fp16',
)
pipe = pipe.to('cuda')  # use 'mps' for Apple Silicon
pipe.enable_model_cpu_offload()

result = pipe(
    prompt='A photorealistic image of a robot data scientist analysing charts, cinematic lighting',
    negative_prompt='blurry, ugly, watermark, distorted',
    num_inference_steps=30,
    guidance_scale=7.5,
    width=1024,
    height=1024,
)

result.images[0].save('output.png')
print('Image saved to output.png')

Use Cases

  • local image generation
  • creative AI
  • content creation

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.