Can you build me a python programme that allows me to enter a prompt and an image be…
- User
Can you build me a python programme that allows me to enter a prompt and an image be generated using a stable diffusion model
- Assistant
Certainly! Below is a Python program that allows you to enter a prompt and generates an image using a Stable Diffusion model. We'll use the
diffuserslibrary developed by Hugging Face, which provides an easy interface for working with diffusion models like Stable Diffusion.
Prerequisites
Before running the program, make sure you have the following packages installed:
- diffusers
- transformers
- accelerate
- torch
You can install them using
pip:bashpip install diffusers transformers accelerate torchNote: If you have a CUDA-compatible GPU and want to leverage GPU acceleration, ensure that you have the appropriate CUDA toolkit installed, and install PyTorch with CUDA support. You can find installation instructions here.
The Python Program
Save the following code in a file named
generate_image.py:pythonimport torch from diffusers import StableDiffusionPipeline def generate_image(prompt, steps=50, image_path='generated_image.png'): # Determine the device to use (GPU if available, else CPU) device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') print(f"Using device: {device}") # Specify the model you want to use model_id = "runwayml/stable-diffusion-v1-5" # Load the Stable Diffusion pipeline if device.type == 'cuda': # For GPU, use half precision for faster inference pipe = StableDiffusionPipeline.from_pretrained( model_id, torch_dtype=torch.float16, revision="fp16" # Use the fp16 precision weights ) pipe = pipe.to(device) else: # For CPU, use full precision pipe = StableDiffusionPipeline.from_pretrained(model_id) pipe = pipe.to(device) # Generate the image if device.type == 'cuda': # Use autocast for faster inference on GPU with torch.autocast("cuda"): image = pipe(prompt, num_inference_steps=steps).images[0] else: # No autocast on CPU image = pipe(prompt, num_inference_steps=steps).images[0] # Save the image image.save(image_path) print(f"Image saved to {image_path}") if __name__ == "__main__": prompt = input("Enter your prompt: ") generate_image(prompt)