Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from diffusers import StableDiffusionPipeline
|
| 3 |
+
import gradio as gr
|
| 4 |
+
|
| 5 |
+
# Load the Stable Diffusion model
|
| 6 |
+
model_id = "runwayml/stable-diffusion-v1-5" # Replace with your model if different
|
| 7 |
+
pipe = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float32) # Use float32 for CPU
|
| 8 |
+
pipe = pipe.to("cpu") # Explicitly set to CPU
|
| 9 |
+
|
| 10 |
+
# Enable CPU offloading to save memory (optional but recommended)
|
| 11 |
+
pipe.enable_attention_slicing() # Reduces memory usage by slicing attention computation
|
| 12 |
+
|
| 13 |
+
# Define the generation function
|
| 14 |
+
def generate_image(prompt, seed=None):
|
| 15 |
+
# If no seed is provided, generate a random one
|
| 16 |
+
if seed is None or seed == "":
|
| 17 |
+
seed = torch.randint(0, 1000000, (1,)).item()
|
| 18 |
+
|
| 19 |
+
# Set up the generator with the seed for CPU
|
| 20 |
+
generator = torch.Generator(device="cpu").manual_seed(seed)
|
| 21 |
+
|
| 22 |
+
# Generate the image with fewer steps for faster CPU execution
|
| 23 |
+
image = pipe(prompt, generator=generator, num_inference_steps=20).images[0]
|
| 24 |
+
|
| 25 |
+
return image, seed # Return the image and the seed used
|
| 26 |
+
|
| 27 |
+
# Create Gradio interface
|
| 28 |
+
interface = gr.Interface(
|
| 29 |
+
fn=generate_image,
|
| 30 |
+
inputs=[
|
| 31 |
+
gr.Textbox(label="Prompt", placeholder="Enter your prompt here"),
|
| 32 |
+
gr.Textbox(label="Seed (optional)", placeholder="Leave blank for random")
|
| 33 |
+
],
|
| 34 |
+
outputs=[
|
| 35 |
+
gr.Image(label="Generated Image"),
|
| 36 |
+
gr.Textbox(label="Seed Used")
|
| 37 |
+
],
|
| 38 |
+
title="Stable Diffusion on CPU with Random Seed",
|
| 39 |
+
description="Generate images with Stable Diffusion on CPU. Leave seed blank for random output."
|
| 40 |
+
)
|
| 41 |
+
|
| 42 |
+
# Launch the interface
|
| 43 |
+
interface.launch()
|