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")