0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

OpenAIの画像生成AI:DALL·Eをpythonから呼ぶアプリを作る

Posted at

はじめに

最近はAIの進化が著しく、画像生成に特化したStable DiffusionなどのAIが登場しています
chatGPTで話題になっているOpenAI社についても画像生成AIであるDALL·Eというモデルがあるのでこちらを用いて今回はpythonでコマンドから入力されたテキストから画像を生成してみます
APIについての導入については下記で紹介しています

goやflutterでも呼んでみる記事も下記で書いてます

pythonでのOpenAIの利用

pythonでOpen AIを利用する場合はopenaiパッケージが公式から提供されているため、こちらを利用するととても簡単です
参照)
getting start
https://platform.openai.com/docs/api-reference/images/create

簡単に下記では画像の生成をしてみます

openai.organization="your Organization ID"
openai.api_key="your Api key"
response = openai.Image.create(
  prompt=text,
  n=1,
  size="1024x1024"
)
image_url = response['data'][0]['url']

apiキーとorganization idを入力し、promptに任意の文字列を入力することで画像を生成し、できた画像のURLがレスポンスとして帰ってきます

実際に作ってみる

ソースコード

import openai
import webbrowser

print("Please enter some text. When you're done, press Enter twice.")
input_text = []
while True:
    line = input()
    if line:
        input_text.append(line)
    else:
        break
text = '\n'.join(input_text)
print("Here's what you entered:")
print(text)

openai.organization="your Organization ID"
openai.api_key="your Api key"
response = openai.Image.create(
  prompt=text,
  n=1,
  size="1024x1024"
)
image_url = response['data'][0]['url']
print(image_url)

webbrowser.open(image_url)

上記コードでは、コマンドから入力されたテキストをOpenAIのパッケージから画像を生成してもらうようにしています。
その後、標準パッケージのwebbrowserを利用して自動的にブラウザでその画像を開くようにしています
プロンプトから入力する際は改行を可能にするため、空の文字列の行でEnterが押下された場合のみ次の処理に行くようにしています

ソースコードの実行

対象のpythonファイルを実行してみます

python main.py

実行すると下記のような表示になり、自動的に既定のブラウザが開き生成された画像が表示されます
2行目でwhite catと入力し、その画像を生成してもらっています

Please enter some text. When you're done, press Enter twice.
white cat

Here's what you entered:
white cat
{生成された画像のURL}

できた画像が下記になります(まさにwhite catです。。。)
スクリーンショット 2023-06-08 8.13.53.png

まとめ

今回はpythonからOpneAIのDOLL・Eで画像生成してみました
前回、flutterやgoからchatGPTを呼んでみましたが、pythonだとパッケージが存在することにより非常に簡単にOpenAIのモデルが使用可能です
これを利用することで、chatGPT→DOLL・Eという自動的に画像生成してくれるようにできそうです

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?