© Haodong Li

First, install openai, requests, pillow python package (Wanna to try ChatGPT?).


You: How to install openai python package using pip or conda?

ChatGPT: To install openai python package using pip, follow these steps:

  1. Open your command prompt or terminal.
  2. Type pip install openai and hit enter.
  3. Wait for the installation process to complete.

To install openai python package using conda, follow these steps:

  1. Open your command prompt or terminal.
  2. Type conda install -c conda-forge openai and hit enter.
  3. Wait for the installation process to complete.

Note: If you’re using Anaconda distribution, prefer installing openai with conda.


Second, export OPENAI_API_KEY=YOUR_KEY in your environment.

Third, code using docs from https://github.com/openai/openai-python, here we use image-alpha-001.

# Written by ChatGPT on 03/20/2023
import openai
import requests
from PIL import Image

# Define the text prompt for the image
text = input('You: ')

# Call the OpenAI DALL-E2 API to generate the image
response = openai.Image.create(
    prompt=text,
    size='512x512',
    model='image-alpha-001'
)

# Get the image data from the API response
url = response['data'][0]['url']
image_data = requests.get(url).content

# Save the image to a file
image_path = './' + text.replace(' ', '_') + '.png'
print('Generated image was saved at ->', image_path)
with open(image_path, 'wb') as f:
    f.write(image_data)

# Load the image to a PIL Image object and display it
image = Image.open(image_path)
image.show()

Finally, enjoy!

You: Two dogs eating pizza, in realistic style

Generated image was saved at -> ./Two_dogs_eating_pizza,_in_realistic_style.png

png