【python】OpenAIのDALL・E 2を利用する

TODO

Pythonにて

  1. DALL-E 2を利用して画像を自動生成する
  2. 作成した画像をローカルにダウンロードする
  3. 複数の画像を作成&ダウンロード

Environmet

Pythonバージョンは3.7.1が必須
MSYS2 MinGWWindowsBash環境を整えるためのソフトウェア

Using Library

pip install openai
urllibはPythonに内蔵されているライブラリ

1. Write code creating a image with dall・E 2

import openai
openai.api_key = 'Your API Key'
def generate_image_with_dalle2(prompt):
    # Official API Reference: https://beta.openai.com/docs/api-reference/images
    response = openai.Image.create(
        prompt=prompt,
        n=1,
        size='{}x{}'.format(str(256), str(256))
    )
    image_url = response['data'][0]['url']
    return image_url

image_url = generate_image_with_dalle2('a white cat')
print(image_url)

openai.Image.create()でDALL・E 2のAPIを利用して画像を生成する。responseには画像URLがある。画像そのものはローカルには保存されないため注意。

パラメタについては下記の通り。

  • prompt: 画像の説明文
  • n: 生成する画像数
  • size: 画像サイズ(256x256, 512x512, 1024x1024)

生成する画像数と画像サイズにより、AIモデル利用料が変化するので注意。

そのほか、response_formaturlb64_jsonで取得するか選択可能。

2. Download a image with urllib.request

import openai
import urllib.request
openai.api_key = 'Your API Key'

def generate_image_with_dalle2(prompt):
    # Official API Reference: https://beta.openai.com/docs/api-reference/images
    response = openai.Image.create(
        prompt=prompt,
        n=1,
        size='{}x{}'.format(str(256), str(256))
    )
    image_url = response['data'][0]['url']
    return image_url

def download_dall2_image(image):
    with urllib.request.urlopen(image) as web_file:
        data = web_file.read()
        with open('./dall2.png', mode='wb') as local_file:
            local_file.write(data)

image = generate_image_with_dalle2('a white cat')
download_dall2_image(image)

DALL・E 2で作成した画像をローカルへDLするコード。urllibでWeb上の画像をopenできるので、openしたファイルをローカルファイルに書き込めばDLできる。

3. Create some images, and download.

import openai
import urllib.request
openai.api_key = 'Your API Key'

def generate_image_with_dalle2(prompt, n, size):
    size = str(size)
    response = openai.Image.create(
        prompt=prompt,
        n=n,
        size='{}x{}'.format(size, size)
    )
    datas = response['data']
    images = []
    for data in datas:
        print(data['url'])
        images.append(data['url'])
    return images

def download_dall2_image(image, n):
    with urllib.request.urlopen(image) as web_file:
        data = web_file.read()
        with open('./dall2_{}.png'.format(n), mode='wb') as local_file:
            local_file.write(data)

images = generate_image_with_dalle2('a white cat', 3, 256)
i = 0
for image in images:
    download_dall2_image(image, i)
    i = i + 1

一回の実行で複数の画像を生成するコード。ベースは#2のコード。generate_image_with_dalle2で生成した画像URLの配列を返し、download_dall2_imageで各画像URLをDLする。

以上。