1. はじめに
最終更新日: 2023 年 10 月 12 日
Imagegen 画像生成
Google Imagen は、テキスト記述からリアルでクリエイティブな画像を生成できる、Google の強力な大規模言語モデルです。Vertex AI の Imagen を使用すると、ユーザーの想像力を高画質のビジュアル アセットに変換する次世代の AI プロダクトを数秒で構築できます。テキストからの画像生成に加えて、テキスト プロンプトによる画像編集、画像キャプション、ビジュアル Q&A、被写体とスタイルに基づく画像モデルのチューニングもサポートしています。
プロンプトの生成
Imagen を使用して画像を生成するには、プロンプトと呼ばれる画像のテキスト記述を指定する必要があります。このプロンプトを使用して画像が生成されます。ただし、高画質で写実的な画像を生成するには、プロンプトの専門知識が必要です。小売業や製造業など、特定のビジネス ドメインに関連する画像を生成する場合は、ドメインに依存する可能性もあります。プロンプトを設計する簡単な方法は、Text Bison モデルにキーワードのセットを指定することです。
全体的なアプローチは次のとおりです。

Gradio UI
Gradio は、カスタマイズに対応した使いやすい UI コンポーネントをすばやく作成できるオープンソースの Python ライブラリです。ML モデルや API 用の UI はもちろん、数行のコーディングで任意の Python 関数を追加することも可能です。Gradio GUI を Jupyter ノートブックに直接統合することも、リンクとして他のユーザーと共有することもできます。Gradio は、テキスト、画像、動画、音声など、さまざまなメディアタイプをサポートしています。また、入力フィールド、ボタン、スライダー、プルダウン メニューなど、多くの事前構築済み UI コンポーネントも提供しています。
作成するアプリの概要
この Codelab では、次の機能を持つ Gradio アプリをデプロイします。
- キーワードまたはフレーズを使用してテキスト プロンプトを生成します。生成されたプロンプトは手動で編集することもできます。
- UI で生成されたプロンプトから画像を生成します。
学習内容
- text-bison モデルでゼロショット学習と少数ショット学習をプログラムで使用して、画像生成用の Imagen 固有のプロンプトを生成する方法。
- API とプロンプトを使用して Imagen モデルで画像を生成する方法。
- Vertex AI Workbench ノートブックから Gradio アプリケーションをビルド、デプロイ、テストする方法。
必要なもの
- GCP プロジェクト(例: ‘Cloud-llm-preview4')へのアクセス権
- Vertex AI Workbench を作成するためのアクセス権
- Vertex AI API が有効になっていること。
- Gradio のネットワーキング要件: ノートブック インスタンスの公開 URL にアクセスできること
2. 設定方法
ノートブックを作成する
- プロジェクトにログインします。
- 左側のナビゲーション メニューから [ワークベンチ] に移動します。
- Under [**ユーザー管理のノートブック**] で、デフォルトのオプションを使用して新しいノートブックを作成します。
- インスタンスがプロビジョニングされたら、[OPEN JUPYTERLAB] をクリックします。
注: ノートブックが停止状態の場合、ノートブックの起動に数分かかることがあります。
コードを取得する
コードファイルはこちらにあります。このノートブックは、環境にインポートしてそのまま実行できます(プロジェクトの詳細を変更する場合を除く)。
3. コードの実行
必要な依存関係とライブラリをインストールまたはインポートする
- Gradio アプリをインストールします。
- Text-Bison と画像生成用の Vertex AI API をインポートします。
- その他必要なライブラリをすべてインポートします。
Text-Bison を使用したプロンプトの生成
キーワードやフレーズを含むユーザー入力を使用します。これは、生成する必要な画像を説明する文の作成に使用できるキーワードまたはフレーズのカンマ区切りリストです。
例: ペルソナ、被写体、背景、照明、その他の説明。
プロンプトを生成する関数は次のとおりです。
def prompt_generation(persona,signal,theme, lighting, quality, extra_desc):
model = TextGenerationModel.from_pretrained("text-bison")
response_few_shot = model.predict([
few_shot_prompt,
**parameters
)
response_single_shot = model.predict(
prompt,
**parameters
)
少数ショット プロンプトとゼロショット プロンプト
ゼロショット プロンプトは、モデルにテキストを生成するためのコンテキストや例を与えないテキスト生成手法です。モデルは独自の知識に基づいて、一貫性のある有益なテキストを生成する必要があるため、難しい場合があります。
ただし、ゼロショット プロンプトは、モデルが既存の例に制約されないため、非常にクリエイティブなものにすることもできます。
少数ショット プロンプトは、モデルにテキストを生成するための少数の例を与えるテキスト生成手法です。モデルは生成する内容に関するガイダンスがあるため、ゼロショット プロンプトよりも簡単です。ただし、少数ショット プロンプトは、モデルが与えられた例に似たテキストしか生成できないため、制限されることもあります。
少数ショット プロンプトとゼロショット プロンプトのサンプルコードを次に示します。
**# コードで使用される少数ショット プロンプト**
few_shot_prompt = f"""You are an expert in writing prompts for Image Generation Models. Using the provided phrases and keywords, concatenate them and add on some realistic details to generate logical and Meaningful prompt that can be used for image generation.
input: people, gardening, house garden, colorful plants, Real, HD image, Photo.
output: A Photo of people gardening in a house garden landscape with few coloured flowering plants. Realistic FULL HD Images, Elegant and natural facial and eye features taken by professional photographer
input: plumber, faucet, kitchen, high quality, natural lighting, Photo
output: A Photo of a plumber fixing a faucet in the kitchen. High quality image with natural indoor lighting.
input: house and garden, halloween, warm lighting, high quality image, Sketch
output: A Sketch of Beautiful House and Garden with Halloween Decorations. Warm lighting, High Quality, 4K photograph taken by professional photographer from front.
input: nice living room, warm lighting,Professional Photographer from far, Photo
output: A photo of a Well designed Living Room. Warm lighting, High Quality, 4K photograph taken by Professional Photographer from far
input: {params_list_str}
output:
"""
# コードで使用されるゼロショット プロンプト
prompt = f"""You are an expert in writing prompts for Image Generation Models. 画像生成モデル向けの、意味のあるプロンプトのリストを文書作成サポートします。リストには次の単語を必ず含めます:「{params_list_str}」。Remember to include these words in the prompt and make the prompt meaningful."""
Imagen を使用した画像生成
ユーザー入力プロンプトとネガティブ プロンプト(省略可)を使用し、モデル(imagegeneration@002)にフィードします。
def image_generation_completion(input, negative_prompt):
input_prompt = input
model = ImageGenerationModel.from_pretrained("imagegeneration@002")
response = model.generate_images(
prompt=input_prompt,
number_of_images=4, #kept to static value of 4
negative_prompt=negative_prompt
)
次のコードは、ユーザー入力プロンプトとネガティブ プロンプトから画像を生成するために含まれています。最終的なコードでは、text-bison モデルによって生成されたプロンプトを使用します。
from vertexai.preview.vision_models import ImageGenerationModel
def image_generation(input, negative_prompt):
input_prompt = input
model = ImageGenerationModel.from_pretrained("imagegeneration@002")
response = model.generate_images(
prompt=input_prompt,
number_of_images=4, #kept to static value of 4.. can be a max value of 8
negative_prompt=negative_prompt
)
images = response.images
return images
user_prompt = "Prompt: A Young Woman Showcasing and selling an undecorated Fresh Christmas Tree from A bunch of trees. Cold Lighting, High Quality and detailed Image Taken By Professional Photographer from far."
negative_prompt = "Distorted and unattractive faces"
generated_images_list = image_generation(user_prompt,negative_prompt)
#show one of the generated image
generated_images_list[0].show()
出力 -

4. Gradio アプリをデプロイする
Gradio は、ユーザーがキーワードを入力して構造化されたプロンプトを生成できるフロントエンドに使用されます。これらのプロンプトは直接使用することも、ユーザーがさらに編集して Imagen にフィードし、入力に応じて画像を生成することもできます。Gradio は、機械学習モデルのユーザー インターフェースを作成するために使用できる Python ライブラリです。このアプリケーションでは、Blocks を使用して柔軟性と複雑なデータフローをアプリケーションに追加します。Blocks は、行と列を使用してアプリケーション レイアウトを管理します。
with gr.Blocks() as demo:
#Prompt Generation Part
with gr.Row():
with gr.Column(scale=1):
Persona = gr.Textbox(label="Persona", info = "Customer segment such as Plumber, Electrician etc.")
with gr.Column(scale=1):
Signals = gr.Textbox(label="Signals", info = "Main content of banner such as Faucet, Lamp etc.")
with gr.Column(scale=1):
Theme = gr.Textbox(label="Theme", info = "Context of the banner such as Halloween, Kitchen etc.")
with gr.Row():
with gr.Column(scale=1):
photo_modifiers = gr.Textbox(label="Photography Modifiers", info = "Photography specific modifiers and parameters such as Lighting(Dramatic/Natural/Warm/Cold), Camera Proximity etc.")
with gr.Column(scale=1):
quality_modifiers = gr.Textbox(label="Image Quality Modifier", info = "Quality Modifiers like high-quality, beautiful, stylized. 4K, HDR, By a professional etc")
with gr.Column(scale=1):
other_desc = gr.Textbox(label="Any Other Description", info = "Other Descriptions for Image such as Style (Painting/Photo/Sketch), Bakground/Foreground Context")
with gr.Row():
btn = gr.Button("Submit")
with gr.Row():
returned_prompts = gr.Textbox(label="Result Prompts", interactive = True)
btn.click(fn=prompt_generation, inputs=[Persona, Signals,Theme, photo_modifiers, quality_modifiers, other_desc], outputs = returned_prompts)
ユーザーの入力と出力を処理するために、Gradio には、画像、動画、スライダー、プルダウン、テキスト ボックス、ラジオなどの複数のコンポーネントが用意されています。これらのコンポーネントにより、デベロッパーはユーザーからの入力を受け取り、Test-bison、Imagen、その他の ML モデルにフィードする方法を柔軟に制御できます。
このプロジェクトでは、Blocks を使用してアプリケーションを作成し、柔軟性と複雑さを追加します。
アプリケーションへのデータフロー。Blocks に加えて、複数の Gradio コンポーネントが
次のように使用されます。
入力プロンプトとネガティブ プロンプトから画像を生成するために使用されるコード スニペットを次に示します。
#Image Generation part
with gr.Row():
with gr.Column(scale=1):
image_prompt = gr.Textbox(label="Image Generation Prompt")
with gr.Accordion("Advanced options", open=False): #Let's hide the advanced options!
with gr.Row():
negative_prompt = gr.Textbox(label="Negative prompt", info = "Specify What not to Include in Image ex. Bad Quality Image")
with gr.Row():
with gr.Column(scale=1):
img_btn = gr.Button("Generate Images")
with gr.Row():
with gr.Column():
output_image_1 = gr.Image(label = "Result Image 1", visible = False)
with gr.Column():
output_image_2 = gr.Image(label = "Result Image 2", visible = False)
with gr.Row():
with gr.Column():
output_image_3 = gr.Image(label = "Result Image 3", visible = False)
with gr.Column():
output_image_4 = gr.Image(label = "Result Image 4", visible = False)
returned_prompts.select(populate_image_prompt, inputs = [returned_prompts], outputs = image_prompt)
img_btn.click(fn=image_generation_completion, inputs=[image_prompt,negative_prompt], outputs = [output_image_1,output_image_2,output_image_3,output_image_4])
Gradio アプリケーションを実行してテストするには、テキスト プロンプトを入力して [Generate] ボタンをクリックします。Imagen は、プロンプトに基づいて画像を生成します。さまざまなプロンプトを試して、Imagen で生成できる画像の種類の確認できます。
Gradio アプリでのプロンプト生成のスクリーンショットを次に示します。

Gradio アプリでの画像生成のスクリーンショットを次に示します。

例 -
例 1 -
[左の画像] プロンプト(シンプルなキーワードをプロンプトとして使用): A couple of friends boating.
[右の画像] プロンプト(Text-Bison で生成されたプロンプトを使用): A photo of 2 young men fishing on a boat surrounded by dark trees in the woods. Men are wearing a shirt and are standing on a boat. Natural Lighting, High Quality, 4K Photo photographed by Professional Photographer.

例 2 -
[左の画像] プロンプト(シンプルなキーワードをプロンプトとして使用): A Christmas tree
[右の画像] プロンプト(Text-Bison で生成されたプロンプトを使用): A Christmas tree in a room with a lamp and furniture. The tree is decorated with lights and ornaments. It is placed near a window, and there is a wall visible in the background. Warm Lighting, High Quality, HDR Photo photographed by Professional Photographer taken from far.

5. クリーンアップ
リソースをクリーンアップするには、
- Gradio アプリを停止します。
- Workbench ノートブックを停止または削除します。
6. 完了
お疲れさまでした。Google Text-Bison API と Imagen API を使用してプロンプトと画像を作成するための Gradio アプリケーションをデプロイできました。