File size: 2,096 Bytes
8ff9c1c
 
 
 
bf6f9b3
8ff9c1c
 
 
 
 
 
 
 
 
 
d5652b2
8ff9c1c
 
436c0bd
8ff9c1c
 
 
 
 
436c0bd
d5652b2
8ff9c1c
436c0bd
bf6f9b3
 
 
 
8ff9c1c
 
 
 
 
d5652b2
436c0bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import streamlit as st
from diffusers import DiffusionPipeline
import torch
from PIL import Image
import os

# Title and description of the app
st.title("🖼️ Stable Diffusion Image Generator")
st.write("Generate images from text using the Stable Diffusion v1.5 model!")

# Sidebar for user inputs
st.sidebar.title("Input Options")
prompt = st.sidebar.text_input("Enter your prompt", "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k")
generate_button = st.sidebar.button("Generate Image")

# Load the pipeline once at startup and cache it for future use
@st.cache_resource
def load_pipeline():
    # Load the diffusion model
    pipe = DiffusionPipeline.from_pretrained(
        "runwayml/stable-diffusion-v1-5", 
        torch_dtype=torch.float16
    )
    device = "cuda" if torch.cuda.is_available() else "cpu"
    pipe.to(device)
    return pipe

# Ensure the pipeline is loaded into the session state
if 'pipe' not in st.session_state:
    st.session_state.pipe = load_pipeline()

pipe = st.session_state.pipe

# Generate image when button is clicked
if generate_button:
    st.write(f"### Prompt: {prompt}")
    with st.spinner("Generating image... Please wait."):

        try:
            # Generate the image using fewer steps to speed up generation (you can adjust this)
            image = pipe(prompt, num_inference_steps=25).images[0]  # Reduce the steps for faster results
            
            # Display the generated image
            st.image(image, caption="Generated Image", use_column_width=True)
            
            # Save and allow the user to download the image
            img_path = "generated_image.png"
            image.save(img_path)
            
            with open(img_path, "rb") as img_file:
                st.download_button(
                    label="Download Image",
                    data=img_file,
                    file_name="generated_image.png",
                    mime="image/png"
                )
        except Exception as e:
            st.error(f"Error during image generation: {e}")
            st.stop()