File size: 1,390 Bytes
f188890
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import requests
import json
from io import BytesIO
from PIL import Image
import matplotlib.pyplot as plt

API_KEY = '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'
ENDPOINT = 'https://api.openai.com/v1/images/generations'

def generate_image(prompt):
    headers = {
        'Content-Type': 'application/json',
        'Authorization': f'Bearer {API_KEY}'
    }

    data = {
        'model': 'image-alpha-001',
        'prompt': prompt,
        'num_images': 1,
        'size': '512x512',
        'response_format': 'url'
    }

    try:
        response = requests.post(url=ENDPOINT, headers=headers, data=json.dumps(data))
        response.raise_for_status()
        result_url = response.json()['data'][0]['url']
        image_bytes = requests.get(result_url).content
        image = Image.open(BytesIO(image_bytes))
        return image
    except requests.exceptions.HTTPError as e:
        print(f"HTTP error {e.response.status_code}: {e.response.reason}")
        print(f"Error details: {e.response.text}")
    except requests.exceptions.RequestException as e:
        print(f"Request error: {e}")
    except Exception as e:
        print(f"Unexpected error: {e}")

    return None

# Example usage
prompt = "a cat sitting on a windowsill looking outside"
image = generate_image(prompt)
if image:
    plt.imshow(image)
    plt.show()
else:
    print("Error generating image")