Nithish310 commited on
Commit
3cc83d8
·
verified ·
1 Parent(s): 75c215b

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +55 -0
app.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from PIL import Image
3
+ from io import BytesIO
4
+ import base64
5
+ from transformers import StableDiffusionPipeline
6
+ import requests
7
+
8
+ # Initialize the Stable Diffusion model
9
+ model_id = "stabilityai/stable-diffusion-3-medium-diffusers"
10
+ pipe = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float32)
11
+ pipe.to("cpu")
12
+
13
+ def generate_image(prompt, negative_prompt=None, temperature=1.0, steps=50, image_size=(512, 512)):
14
+ # Generate an image using the Stable Diffusion pipeline
15
+ image = pipe(prompt, negative_prompt=negative_prompt, num_inference_steps=steps, guidance_scale=temperature).images[0]
16
+ # Resize image
17
+ image = image.resize(image_size)
18
+
19
+ # Convert image to base64
20
+ buffered = BytesIO()
21
+ image.save(buffered, format="PNG")
22
+ img_str = base64.b64encode(buffered.getvalue()).decode('utf-8')
23
+ return img_str
24
+
25
+ def main():
26
+ st.title("Stable Diffusion Image Generation API")
27
+ st.write("Generate images using Stable Diffusion and get them in base64 format.")
28
+
29
+ # Get parameters from URL
30
+ query_params = st.experimental_get_query_params()
31
+ prompt = query_params.get("prompt", [""])[0]
32
+ negative_prompt = query_params.get("negative_prompt", [None])[0]
33
+ temperature = float(query_params.get("temperature", [1.0])[0])
34
+ steps = int(query_params.get("steps", [50])[0])
35
+ image_size = tuple(map(int, query_params.get("image_size", ["512,512"])[0].split(",")))
36
+
37
+ if prompt:
38
+ st.write("Generating image with parameters:")
39
+ st.write(f"Prompt: {prompt}")
40
+ st.write(f"Negative Prompt: {negative_prompt}")
41
+ st.write(f"Temperature: {temperature}")
42
+ st.write(f"Steps: {steps}")
43
+ st.write(f"Image Size: {image_size}")
44
+
45
+ # Generate the image
46
+ img_base64 = generate_image(prompt, negative_prompt, temperature, steps, image_size)
47
+
48
+ # Display the image
49
+ st.image(f"data:image/png;base64,{img_base64}", caption="Generated Image")
50
+
51
+ # Provide the base64 image string
52
+ st.text_area("Base64 Image String", value=img_base64, height=200)
53
+
54
+ if __name__ == "__main__":
55
+ main()