File size: 2,763 Bytes
bdddd6f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import streamlit as st
import torch
from diffusers import StableDiffusionPipeline
from PIL import Image
import os

# Set up the Streamlit page
st.set_page_config(
    page_title="Text-to-Image with Hugging Face",
    page_icon="🎨",
    layout="wide"
)

# --- App Title and Description ---
st.title("🎨 AI Image Generator")
st.markdown(
    "Enter a text prompt below and watch as the AI brings your words to life! "
    "This app uses the **Stable Diffusion** model from Hugging Face."
)
st.markdown("---")

# --- Model Loading ---
@st.cache_resource
def load_model():
    """
    Loads the Stable Diffusion model.
    Using st.cache_resource to cache the model so it doesn't reload on every interaction.
    """
    # Define the model ID. You can change this to other models on the Hugging Face Hub.
    model_id = "runwayml/stable-diffusion-v1-5"
    
    # Load the pipeline
    pipe = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float16)
    
    # Check for GPU and move model if available
    if torch.cuda.is_available():
        pipe = pipe.to("cuda")
    return pipe

pipeline = load_model()

# --- User Input and Generation ---
col1, col2 = st.columns([2, 1])

with col1:
    prompt = st.text_input(
        "Enter your prompt:",
        placeholder="e.g., A photo of an astronaut riding a horse on Mars, high resolution, detailed"
    )
    generate_button = st.button("Generate Image")

with col2:
    st.markdown("### Settings")
    negative_prompt = st.text_area(
        "Negative prompt:",
        placeholder="e.g., blurry, bad quality, low resolution"
    )

st.markdown("---")

# --- Image Display and Generation Logic ---
if generate_button:
    if not prompt:
        st.warning("Please enter a prompt to generate an image.")
    else:
        with st.spinner("Generating your image... This may take a moment."):
            try:
                # Generate the image
                image = pipeline(
                    prompt=prompt,
                    negative_prompt=negative_prompt
                ).images[0]
                
                # Display the generated image
                st.success("Image generated successfully!")
                st.image(image, caption=prompt, use_column_width=True)
                
                # Option to download the image
                buf = BytesIO()
                image.save(buf, format="PNG")
                byte_im = buf.getvalue()
                st.download_button(
                    label="Download Image",
                    data=byte_im,
                    file_name=f"{prompt.replace(' ', '_')}.png",
                    mime="image/png"
                )
            except Exception as e:
                st.error(f"An error occurred: {e}")