amongusrickroll68 commited on
Commit
f188890
1 Parent(s): e8e53be

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +48 -0
app.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import requests
2
+ import json
3
+ from io import BytesIO
4
+ from PIL import Image
5
+ import matplotlib.pyplot as plt
6
+
7
+ API_KEY = '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'
8
+ ENDPOINT = 'https://api.openai.com/v1/images/generations'
9
+
10
+ def generate_image(prompt):
11
+ headers = {
12
+ 'Content-Type': 'application/json',
13
+ 'Authorization': f'Bearer {API_KEY}'
14
+ }
15
+
16
+ data = {
17
+ 'model': 'image-alpha-001',
18
+ 'prompt': prompt,
19
+ 'num_images': 1,
20
+ 'size': '512x512',
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"
43
+ image = generate_image(prompt)
44
+ if image:
45
+ plt.imshow(image)
46
+ plt.show()
47
+ else:
48
+ print("Error generating image")