amongusrickroll68 commited on
Commit
c745175
1 Parent(s): 13559ad

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +15 -9
app.py CHANGED
@@ -3,9 +3,8 @@ import json
3
  from io import BytesIO
4
  from PIL import Image
5
  import matplotlib.pyplot as plt
6
- pip install requests json Pillow matplotlib
7
- # Replace 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 with your OpenAI API key
8
- API_KEY = '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'
9
  ENDPOINT = 'https://api.openai.com/v1/images/generations'
10
 
11
  def generate_image(prompt):
@@ -22,14 +21,22 @@ def generate_image(prompt):
22
  'response_format': 'url'
23
  }
24
 
25
- response = requests.post(url=ENDPOINT, headers=headers, data=json.dumps(data))
26
- if response.status_code == 200:
 
27
  result_url = response.json()['data'][0]['url']
28
  image_bytes = requests.get(result_url).content
29
  image = Image.open(BytesIO(image_bytes))
30
  return image
31
- else:
32
- return None
 
 
 
 
 
 
 
33
 
34
  # Example usage
35
  prompt = "a cat sitting on a windowsill looking outside"
@@ -37,5 +44,4 @@ image = generate_image(prompt)
37
  if image:
38
  plt.imshow(image)
39
  plt.show()
40
- else:
41
- print("Error generating image")
 
3
  from io import BytesIO
4
  from PIL import Image
5
  import matplotlib.pyplot as plt
6
+
7
+ API_KEY = 'YOUR_API_KEY'
 
8
  ENDPOINT = 'https://api.openai.com/v1/images/generations'
9
 
10
  def generate_image(prompt):
 
21
  'response_format': 'url'
22
  }
23
 
24
+ try:
25
+ response = requests.post(url=ENDPOINT, headers=headers, data=json.dumps(data))
26
+ response.raise_for_status()
27
  result_url = response.json()['data'][0]['url']
28
  image_bytes = requests.get(result_url).content
29
  image = Image.open(BytesIO(image_bytes))
30
  return image
31
+ except requests.exceptions.HTTPError as e:
32
+ print(f"HTTP error {e.response.status_code}: {e.response.reason}")
33
+ print(f"Error details: {e.response.text}")
34
+ except requests.exceptions.RequestException as e:
35
+ print(f"Request error: {e}")
36
+ except Exception as e:
37
+ print(f"Unexpected error: {e}")
38
+
39
+ return None
40
 
41
  # Example usage
42
  prompt = "a cat sitting on a windowsill looking outside"
 
44
  if image:
45
  plt.imshow(image)
46
  plt.show()
47
+