Quotation_App / test_openai.py
NayabShakeel's picture
Update test_openai.py
2a21347 verified
raw
history blame contribute delete
1.54 kB
import openai
import streamlit as st
from PIL import Image
import requests
from io import BytesIO
# Function to generate image from OpenAI API
def generate_image_from_text(text):
try:
response = openai.Image.create(
prompt=text, # The text prompt for the image
n=1, # Number of images to generate
size="1024x1024" # Size of the image
)
# Extracting the image URL from the response
image_url = response['data'][0]['url']
return image_url
except Exception as e:
st.error(f"Error generating image: {e}")
return None
# Streamlit UI for Image Generation
if __name__ == "__main__":
st.title("Test OpenAI Image Generation API")
# Load OpenAI API key securely
openai.api_key = st.secrets["OPENAI_API_KEY"]
user_input = st.text_input("Enter text for image generation:")
if st.button("Generate Image"):
if user_input:
image_url = generate_image_from_text(user_input)
if image_url:
# Fetch the image from the URL and display it
response = requests.get(image_url)
if response.status_code == 200:
img = Image.open(BytesIO(response.content))
st.image(img, caption="Generated Image")
else:
st.error("Failed to fetch image.")
else:
st.error("Image generation failed.")
else:
st.error("Please enter text to generate an image.")