Spaces:
Sleeping
Sleeping
| import uuid | |
| import json | |
| import streamlit as st | |
| from PIL import Image | |
| from diffusers import StableDiffusionPipeline | |
| import torch | |
| model_id = "runwayml/stable-diffusion-v1-5" | |
| pipe = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float32) | |
| # pipe = pipe.to("cuda") | |
| st.title("Convert Text To Image :sunglasses:") | |
| def load_metadata(): | |
| metadata = [] | |
| try: | |
| with open("metadata.json", "r") as f: | |
| metadata = json.load(f) | |
| except: | |
| print("json file doesn't exist") | |
| return metadata | |
| def update_metadata(data): | |
| metadata = [] | |
| try: | |
| with open("metadata.json", "r") as f: | |
| metadata = json.load(f) | |
| except: | |
| print("json file doesn't exist") | |
| metadata.append(data) | |
| with open("metadata.json", "w") as json_file: | |
| json.dump(metadata, json_file) | |
| def render_metadata(data): | |
| st.write("Previous prompt results (common for all)") | |
| for d in data: | |
| st.write("Prompt: ", d["prompt"]) | |
| st.image(Image.open(d["file_name"])) | |
| metadata = load_metadata() | |
| with st.form("tti_form"): | |
| prompt = st.text_input("Enter Prompt") | |
| # Every form must have a submit button. | |
| submitted = st.form_submit_button("Submit") | |
| if submitted: | |
| with st.spinner("Processing..."): | |
| image_name = uuid.uuid4().hex + ".png" | |
| st.write("prompt", prompt) | |
| image = pipe(prompt).images[0] | |
| # test mode - comment above and uncomment following | |
| # image = Image.open("abcd.png") | |
| pil_image = Image.fromarray(image) | |
| st.image(image) | |
| # save image | |
| data = {"file_name": image_name, "prompt": prompt} | |
| pil_image.save(image_name) | |
| # with open(image_name, 'wb') as f: | |
| # f.write(image) | |
| update_metadata(data) | |
| st.success("Image generated!") | |
| render_metadata(metadata) | |