LoginSignup
0
1

More than 1 year has passed since last update.

chatGPTでコマンドラインから画像を作成(いまさら)

Last updated at Posted at 2023-04-19

chatGPT 有料会員のメリットを探す

chatGPT で有料会員になって久しいものの
ブラウザで画面操作するより command prompt から問合せする機会が多く
まだwish list に登録されていないため、GPT-4 が使えない点が悲しみ。

そうだ。openAIの他機能も利用してみよう。今はやりのAIの自動画像w

python 環境を準備すること

流行最先端といえば Stable Diffusion?みたいな感じではありますが
なにせ私は端末が非力なのでインストールなどできません。

そうすると選択肢はpythonでコマンドラインのみですw

必要なライブラリをインポート。

pip install requests

OPENAI_API_KEY はセキュリティの観点から環境変数に設定してください。
ソースはこちら(いきなり全量w

# Import necessary packages/libraries.
import datetime
import json
import os
import requests
import sys
import time
import urllib.parse


def create_image(prompt, model, api_key, save_dir):
    """
    Function that generates images using OpenAI API and saves them in the specified directory.
    """

    # The endpoint to which the request will be made.
    url = 'https://api.openai.com/v1/images/generations'

    # Request headers.
    headers = {
        'Content-Type': 'application/json',
        'Authorization': f'Bearer {api_key}'
    }

    # The data to be sent in the request.
    data = {
        'model': model,
        'prompt': urllib.parse.quote(prompt),
        'num_images': 1,
        'size': '512x512',
        'response_format': 'url'
    }

    # Send the request.
    response = requests.post(url, headers=headers, data=json.dumps(data))
    response.raise_for_status()

    # Get the URL of the generated image.
    image_url = response.json()['data'][0]['url']

    # Set the name and path for saving the image.
    image_name = f"{datetime.datetime.now():%Y%m%d%H%M%S}.png"
    save_path = os.path.join(save_dir, image_name)

    # Download the image and save it in the specified directory.
    response = requests.get(image_url)
    response.raise_for_status()

    with open(save_path, "wb") as f:
        f.write(response.content)

    with open('imageprompt.log', 'a') as log:
        log.write(f"prompt: {prompt}\nfile: {save_path}\ntimestamp: {datetime.datetime.now():%Y/%m/%d %H:%M:%S}\n\n")
        
    print(f"File saved at {save_path}")


def main():
    """
    Function that prompts the user to enter a message for generating an image and saves the generated image.
    """

    # Initialize.
    #api_key = "Set your API key here"
    api_key = os.environ.get('OPENAI_API_KEY')
    if not api_key:
        print(f"OPENAI_API_KEY environment variable doesn't exist, please restart again.")
        sys.exit(1)

    model = "image-alpha-001"
    save_dir = "./images/"

    if not os.path.exists(save_dir):
        os.makedirs(save_dir)

    while True:
        prompt = input('Enter a message: ')

        create_image(prompt, model, api_key, save_dir)

        yn = input('Do you want to try again? (y/n): ')

        if yn.lower() == 'n':
            break


if __name__ == '__main__':
    main()

openAI のAPIを利用しています。
https://platform.openai.com/docs/api-reference/images/create

画像を作成してみる

% python image.py
Enter a message: A digital Illustration of the Babel tower, 4k, detailed, trending in artstation, fantasy vivid colors, 8k
File saved at ./images/20230419091258.png
Do you want to try again? (y/n): y
Enter a message: A young girl with bright blue hair stands in a bustling futuristic metropolis. She is surrounded by sky-scraping buildings of various shapes and sizes, all illuminated in a brilliant orange light. The streets are lined with neon signs. Indistinct shapes whiz by in the sky, and the girl looks up in amazement. In the background there are people walking and cars zooming, and the sky is a mix of blues, pinks, and purples. Art style: animation.
File saved at ./images/20230419091416.png
Do you want to try again? (y/n): n

こんな感じでメッセージをいれると images 配下にファイルが生成されます。

  1. かわいいパンダさん。
    image.png

  2. 成果物
    image.png
    結構いい感じ。

  3. あらいぐま
    image.png

何故。プロンプトに利用する文章は英語にしないと駄目ぽいです。
URLEncode間違いかしら。

一応 Windows exe を作成しておく

python環境がないあなたのためにexeを作成しておきます

pyinstaller --onefile image.py

するとdist/ 配下に image.exe が生成されるので
コマンドプロンプトから実行
※コンソールから質問されるのでダブルクリックは嫌。

C:\tools\dist>image.exe
Enter a message: chatgpt fruite cute apple green
File saved at ./images/20230420074654.png
Do you want to try again? (y/n): n

chatGPT かわいい緑のフルーツ
image.png
なんか周りの銀紙っぽいのがchatGPTなのかしらw

一応ダブルクリックしても小窓が出てきて入力できました。
今日は念願のAWSサミット当日。AWSで12冠した記念品を。

prompt: 2023 AWS ALL Certifications Engineers keepsake in high quality. A product that the members who receive it will be pleased with.
2023 AWS ALL Certifications Engineersの記念品を高品質で受領したメンバが喜ぶ商品を

image.png
かなり違うし違和感しかないw

これからの進め方

ともあれ日本語で入力した内容をchatGPTで英語に変換すればそのまま使えるし
プロンプトはgoogle先生から取得したものをそのまま転用すればいけそうかも。

何より非力なPCでも画像 1個作成するのに数秒って素敵。
こういうのが欲しかったのよね。

是非お仲間募集中です。

openAI による別API(Create image variation)

先日落選した 2023 AWS Top Engineers にもし合格していたらと思い
記念品を作成してみました。
image.png
恐怖しかない。

元画像を入力として他のを作成することができるみたい。
ひとまず手打ちでcurlで頑張る。ヘイ、Mr. カール。

curl https://api.openai.com/v1/images/variations \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -F image="@aws_top_engineers.png" \
  -F n=4 \
  -F size="256x256"

image.png
image.png
image.png
image.png

もう悪夢。

GUIアプリケーションにしてみました。

ダブルクリックするとWindowsアプリケーションが立ち上がり
メッセージを入力して実行すると画像が表示されます(誰得w

image.png

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