pythonintermediate
Stable Diffusion Text-to-Image in Python
Generate images from text prompts locally using HuggingFace Diffusers and Stable Diffusion XL.
pythonPress β/Ctrl + Shift + C to copy
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.
typescriptbeginner
DALLΒ·E 3 Image Generation
Generate images from a text prompt using the OpenAI DALLΒ·E 3 API and return a URL.
Best for: AI art generation
#openai#dall-e
pythonbeginner
Sentence Transformers Local Embeddings
Generate high-quality text embeddings locally using Sentence Transformers without API calls.
Best for: semantic search
#sentence-transformers#embeddings
pythonbeginner
OpenAI DALL-E Image Generation
Generate and save images using the DALL-E 3 API with quality and style control.
Best for: AI image creation
#openai#dall-e
pythonintermediate
HuggingFace Text Generation with Streaming
Run local text generation with HuggingFace models and stream output token-by-token to the console.
Best for: local LLM
#huggingface#text-generation