NayabShakeel commited on
Commit
2a21347
·
verified ·
1 Parent(s): 24bb010

Update test_openai.py

Browse files
Files changed (1) hide show
  1. test_openai.py +27 -14
test_openai.py CHANGED
@@ -1,23 +1,30 @@
1
- import requests
2
- from PIL import Image
3
  import streamlit as st
 
 
 
4
 
5
- # Function to generate image from Hugging Face API (or other providers like DeepAI)
6
  def generate_image_from_text(text):
7
- response = requests.post(
8
- "https://api-inference.huggingface.co/models/dalle-mini",
9
- headers={"Authorization": f"Bearer {st.secrets['HF_API_KEY']}"},
10
- json={"inputs": text}
11
- )
12
- if response.status_code == 200:
13
- image_url = response.json()[0]['image']
 
14
  return image_url
15
- else:
 
16
  return None
17
 
18
- # Test Image Generation (on button click or any other trigger)
19
  if __name__ == "__main__":
20
- st.title("Test Image Generation API")
 
 
 
21
 
22
  user_input = st.text_input("Enter text for image generation:")
23
 
@@ -25,7 +32,13 @@ if __name__ == "__main__":
25
  if user_input:
26
  image_url = generate_image_from_text(user_input)
27
  if image_url:
28
- st.image(image_url, caption="Generated Image")
 
 
 
 
 
 
29
  else:
30
  st.error("Image generation failed.")
31
  else:
 
1
+ import openai
 
2
  import streamlit as st
3
+ from PIL import Image
4
+ import requests
5
+ from io import BytesIO
6
 
7
+ # Function to generate image from OpenAI API
8
  def generate_image_from_text(text):
9
+ try:
10
+ response = openai.Image.create(
11
+ prompt=text, # The text prompt for the image
12
+ n=1, # Number of images to generate
13
+ size="1024x1024" # Size of the image
14
+ )
15
+ # Extracting the image URL from the response
16
+ image_url = response['data'][0]['url']
17
  return image_url
18
+ except Exception as e:
19
+ st.error(f"Error generating image: {e}")
20
  return None
21
 
22
+ # Streamlit UI for Image Generation
23
  if __name__ == "__main__":
24
+ st.title("Test OpenAI Image Generation API")
25
+
26
+ # Load OpenAI API key securely
27
+ openai.api_key = st.secrets["OPENAI_API_KEY"]
28
 
29
  user_input = st.text_input("Enter text for image generation:")
30
 
 
32
  if user_input:
33
  image_url = generate_image_from_text(user_input)
34
  if image_url:
35
+ # Fetch the image from the URL and display it
36
+ response = requests.get(image_url)
37
+ if response.status_code == 200:
38
+ img = Image.open(BytesIO(response.content))
39
+ st.image(img, caption="Generated Image")
40
+ else:
41
+ st.error("Failed to fetch image.")
42
  else:
43
  st.error("Image generation failed.")
44
  else: