1
+ import openai
2
+ import os
3
+ import requests
4
+ from PIL import Image
5
+ import dotenv
6
+
7
+ # import dotenv
8
+ dotenv .load_dotenv ()
9
+
10
+ # Get endpoint and key from environment variables
11
+ openai .api_base = os .environ ['AZURE_OPENAI_ENDPOINT' ]
12
+ openai .api_key = os .environ ['AZURE_OPENAI_KEY' ]
13
+
14
+ # Assign the API version (DALL-E is currently supported for the 2023-06-01-preview API version only)
15
+ openai .api_version = '2023-06-01-preview'
16
+ openai .api_type = 'azure'
17
+
18
+
19
+ try :
20
+ # Create an image by using the image generation API
21
+ generation_response = openai .Image .create (
22
+ prompt = 'Bunny on horse, holding a lollipop, on a foggy meadow where it grows daffodils' , # Enter your prompt text here
23
+ size = '1024x1024' ,
24
+ n = 2 ,
25
+ temperature = 0 ,
26
+ )
27
+ # Set the directory for the stored image
28
+ image_dir = os .path .join (os .curdir , 'images' )
29
+
30
+ # If the directory doesn't exist, create it
31
+ if not os .path .isdir (image_dir ):
32
+ os .mkdir (image_dir )
33
+
34
+ # Initialize the image path (note the filetype should be png)
35
+ image_path = os .path .join (image_dir , 'generated_image.png' )
36
+
37
+ # Retrieve the generated image
38
+ image_url = generation_response ["data" ][0 ]["url" ] # extract image URL from response
39
+ generated_image = requests .get (image_url ).content # download the image
40
+ with open (image_path , "wb" ) as image_file :
41
+ image_file .write (generated_image )
42
+
43
+ # Display the image in the default image viewer
44
+ image = Image .open (image_path )
45
+ image .show ()
46
+
47
+ # catch exceptions
48
+ except openai .error .InvalidRequestError as err :
49
+ print (err )
50
+
51
+ # ---creating variation below---
52
+
53
+ response = openai .Image .create_variation (
54
+ image = open (image_path , "rb" ),
55
+ n = 1 ,
56
+ size = "1024x1024"
57
+ )
58
+
59
+ image_path = os .path .join (image_dir , 'generated_variation.png' )
60
+
61
+ image_url = response ['data' ][0 ]['url' ]
62
+
63
+ generated_image = requests .get (image_url ).content # download the image
64
+ with open (image_path , "wb" ) as image_file :
65
+ image_file .write (generated_image )
66
+
67
+ # Display the image in the default image viewer
68
+ image = Image .open (image_path )
69
+ image .show ()
0 commit comments