openAIとflaskで画像生成アプリを作成
タイトル画像は実際に、「cat」「japanese dog」「big bear」「small dog」と文字を与えて、アプリで作成したものになります。
openAIは画像生成APIも備えており、取得してすぐにアプリにすることができます。作成したソースも掲載中なので、最後まで見ていってくれれば幸いです。
※Flaskとopenaiライブラリが必要なのでインストールしてください。
Pythonでのプログラムになります。
openAIでAPIを取得
アカウントを作成してから
https://beta.openai.com/account/api-keys
https://beta.openai.com/docs/quickstart/build-your-application
こちらで、APIを有効化する環境変数を作成
https://beta.openai.com/docs/api-reference/authentication
ここに従った通りに画像生成モデルを投入。
https://platform.openai.com/docs/api-reference/images/create
この形をもとにアプリにしていきます。
Flaskを使う
Flaskをもとに組んでいきます。
openai.api_key"" に取得したAPIキーを挿入します。
app.py
from flask import render_template
from flask import Flask, render_template, request
import openai
openai.api_key = ""
# Webサイトのインスタンスを作成する
app = Flask(__name__)
@app.route("/", methods=["GET", "POST"])
def generate_image():
if request.method == "POST":
# フォームからプロンプトを取得する
prompt = request.form["prompt"]
# openAIのイメージ生成モデルを呼び出す
response = openai.Image.create(prompt=prompt, n=1, size="512x512")
image_url = response["data"][0]["url"]
else:
# プロンプトが指定されない場合はデフォルトの画像を表示する
image_url = "https://via.placeholder.com/512x512"
return render_template("index.html", image_url=image_url)
if __name__ == "__main__":
app.run()
imdex.html
<!doctype html>
<html>
<head>
<title>AI画像生成</title>
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
</head>
<body>
<div class="container mt-5 text-center">
<h1 class="display-4">AI画像生成</h1>
<form method="POST" class="form-inline justify-content-center mt-5">
<div class="form-group mx-sm-3">
<label for="prompt" class="sr-only">Prompt:</label>
<input type="text" id="prompt" name="prompt" class="form-control" placeholder="生成したいキーワード">
</div>
<button type="submit" class="btn btn-primary">生成する</button>
</form>
<br>
<img src="{{ image_url }}" alt="Generated Image" class="img-fluid rounded-lg shadow-lg">
</div>
</body>
</html>
コンソールコマンドで「flask run」で入力。
アプリが起動される。
cat walk in the cityと入力してみる
他にもいろんなことにopenAIのAPIが使えそうです。
この記事がいいと思ったらスキをお願いします☆
この記事が参加している募集
ご覧いただきありがとうございました。 サポートしていただいたお金は開発費にかけさせていただきます。