File size: 2,152 Bytes
65cc444
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import streamlit as st
from PIL import Image as PILImage
import torch
from io import BytesIO
from diffusers import StableDiffusionImg2ImgPipeline

# Function to load the Stable Diffusion model
def load_model():
    model_id = "stabilityai/stable-diffusion-2-1"
    device = "mps" if torch.backends.mps.is_available() else "cpu"
    pipe = StableDiffusionImg2ImgPipeline.from_pretrained(
        model_id, torch_dtype=torch.float32, safety_checker=None
    ).to(device)
    return pipe, device

# Function to generate the transformed image
def generate_image(pipe, device, init_image, prompt, strength, guidance_scale):
    init_image = init_image.convert("RGB").resize((512, 512))
    generator = torch.manual_seed(42)
    output_image = pipe(
        prompt=prompt,
        image=init_image,
        strength=strength,
        guidance_scale=guidance_scale,
        generator=generator
    ).images[0]
    return output_image

# Streamlit App
def main():
    st.title("Stable Diffusion Image Transformer")

    # Load the model
    pipe, device = load_model()

    # Image Upload
    uploaded_file = st.file_uploader("Choose an image...", type=["png", "jpg", "jpeg"])
    if uploaded_file is not None:
        init_image = PILImage.open(uploaded_file)
        st.image(init_image, caption="Uploaded Image", use_column_width=True)

        # Prompt Input
        prompt = st.text_input("Enter transformation prompt:")

        # Sliders for Strength and Guidance Scale
        strength = st.slider("Select strength:", 0.1, 1.0, 0.5, 0.1)
        guidance_scale = st.slider("Select guidance scale:", 1.0, 10.0, 7.5, 0.5)

        # Generate Image Button
        if st.button("Generate Image"):
            if prompt:
                with st.spinner("Generating image..."):
                    transformed_image = generate_image(
                        pipe, device, init_image, prompt, strength, guidance_scale
                    )
                st.image(transformed_image, caption="Transformed Image", use_column_width=True)
            else:
                st.error("Please enter a transformation prompt.")

if __name__ == "__main__":
    main()