Gemini 2.0 Flashの画像生成を試す
上の記事はGemini APIの方の記事で。VertexAIでも使えるのかな?と思ったけど、2025/03/14 2025/03/26時点のドキュメント見る限りは、Private Previewなので、まだ使えなさそう。
2025/03/29追記
VertexAIでも使えるようになった様子。Vertex AI Studioにリストされてた。よく見るとgemini-2.5-pro-expもある!
一番下でColaboratoryからGenAI SDKで試した。
ノートブックがいくつか公開されている。
とりあえずざっと試してみる。
Colaboratoryで。
パッケージインストール。そういえばVertexAIもGemini APIもGoogle Gen AI SDKに統一されてるね。v1.5.0以上である必要がある。あとランタイムの再起動が必要だった。
!pip install -U google-genai
!pip freeze | grep -i genai
google-genai==1.5.0
普通のテキストだけの場合はこんな感じ
from google import genai
from google.colab import userdata
client = genai.Client(
api_key=userdata.get('GEMINI_API_KEY')
)
model_id = "gemini-2.0-flash-exp"
response = client.models.generate_content(
model=model_id,
contents="こんにちは!今日はいいお天気だね。",
)
print(response.text)
こんにちは!本当にいいお天気ですね!何かお出かけの予定はありますか?
画像生成させてみる。画像生成させる場合はレスポンスのモダリティに画像を追加する設定をGenerateContentConfig
で渡して生成させる。
from google.genai.types import GenerateContentConfig
import json
config = GenerateContentConfig(response_modalities=['Text', 'Image'])
response = client.models.generate_content(
model=model_id,
contents="走っている競走馬の画像を生成して、競馬の魅力を伝えるような1文のキャッチコピーを作成して。",
config=config,
)
レスポンスの中身
print(json.dumps(json.loads(response.model_dump_json()), indent=2, ensure_ascii=False))
{
"candidates": [
{
"content": {
"parts": [
{
"video_metadata": null,
"thought": null,
"code_execution_result": null,
"executable_code": null,
"file_data": null,
"function_call": null,
"function_response": null,
"inline_data": {
"data": "iVBORw0KGgoAAAANSU(...snip...)LYDwAAAABJRU5ErkJggg=="",
"mime_type": "image/png"
},
"text": null
},
{
"video_metadata": null,
"thought": null,
"code_execution_result": null,
"executable_code": null,
"file_data": null,
"function_call": null,
"function_response": null,
"inline_data": null,
"text": "\n\n**一瞬の爆発力、心揺さぶる感動、競馬は生きるエネルギー。**"
}
],
"role": "model"
},
"citation_metadata": null,
"finish_message": null,
"token_count": null,
"avg_logprobs": null,
"finish_reason": "STOP",
"grounding_metadata": null,
"index": 0,
"logprobs_result": null,
"safety_ratings": null
}
],
"create_time": null,
"response_id": null,
"model_version": "gemini-2.0-flash-exp",
"prompt_feedback": null,
"usage_metadata": {
"cached_content_token_count": null,
"candidates_token_count": 22,
"prompt_token_count": 25,
"total_token_count": 47
},
"automatic_function_calling_history": [],
"parsed": null
}
画像とテキストは response.candidates[0].content.parts
の配列で返されるので、それぞれを取り出してnotebookで表示するには以下のようにすればよい。
from IPython.display import Image, display, Markdown
from PIL import Image as PILImage
import io
def display_image(data):
"""画像を表示する"""
display(Image(data=data))
def save_image(data, filename):
"""画像を保存する"""
image = PILImage.open(io.BytesIO(data))
image.save(filename)
for part in response.candidates[0].content.parts:
if part.inline_data:
# 画像の場合
display_image(part.inline_data.data)
save_image(part.inline_data.data, f"output.png")
else:
# それ以外(テキスト)の場合
display(Markdown(part.text))
この画像をさらに入力に使う。
response = client.models.generate_content(
model=model_id,
contents=[
"先頭の競走馬の騎手の服を赤にして。",
PILImage.open("output.png")
],
config=config
)
for part in response.candidates[0].content.parts:
if part.inline_data:
display_image(part.inline_data.data)
save_image(part.inline_data.data, f"output2.png")
else:
display(Markdown(part.text))
部分的な修正ができるのは良いね。こんなのも。
response = client.models.generate_content(
model=model_id,
contents=[
"先頭の競走馬の毛色を白毛にして。",
PILImage.open("output.png")
],
config=config
)
for part in response.candidates[0].content.parts:
if part.inline_data:
display_image(part.inline_data.data)
save_image(part.inline_data.data, f"output2.png")
else:
display(Markdown(part.text))
複数のイメージとテキストを一度に生成させることもできる。
response = client.models.generate_content(
model=model_id,
contents=[
"競馬の魅力を5つリストアップして。画像付きで。",
],
config=config
)
for part in response.candidates[0].content.parts:
if part.inline_data:
display_image(part.inline_data.data)
save_image(part.inline_data.data, f"output2.png")
else:
display(Markdown(part.text))
こんな感じでまとめて生成される。
コンテンツとか資料作成とかこれでできちゃうなぁ。
マルチターンのチャット。
def display_image(data, width=500):
"""画像を指定した横幅で表示"""
display(Image(data=data, width=width))
chat = client.chats.create(
model=model_id,
config=config,
)
while True:
user_input = input("USER: ")
if user_input.lower() == 'quit':
print("チャットを終了します。さようなら。")
break
response = chat.send_message(user_input)
print("Assistant: ")
for part in response.candidates[0].content.parts:
if part.inline_data:
display_image(part.inline_data.data)
save_image(part.inline_data.data, f"output.png")
else:
display(Markdown(part.text))
いい感じにコンテキストを引き継いでくれる。
これすごいなー。Vertex AIにも早く来て欲しい。
Vertex AIの方のドキュメントを見てると、Speech Generationも予定されてるんだね・・・・
サンプルのnotebookに少し書いてあるけど、画像生成のプロンプトはImagenのプロンプトも参考になるみたい。
Imagen触ったことないしやってみるかな。
Vertex AIの場合
!pip install -U google-genai
!pip freeze | grep -i genai
google-genai==1.8.0
認証
import sys
if "google.colab" in sys.modules:
from google.colab import auth
auth.authenticate_user()
チャット
from google import genai
from google.colab import userdata
client = genai.Client(
vertexai=True,
project='<プロジェクトID>',
location='us-central1', # 多分試験運用版はus-central1だけだと思う
)
model_id = "gemini-2.0-flash-exp"
response = client.models.generate_content(
model=model_id,
contents="こんにちは!今日はいいお天気だね。",
)
print(response.text)
こんにちは!本当にいいお天気ですね。どこかお出かけしたくなりますね。何かご予定はありますか?
画像生成
from google.genai.types import GenerateContentConfig
import json
config = GenerateContentConfig(response_modalities=['Text', 'Image'])
response = client.models.generate_content(
model=model_id,
contents="走っている競走馬の画像を生成して、競馬の魅力を伝えるような1文のキャッチコピーを作成して。",
config=config,
)
from IPython.display import Image, display, Markdown
from PIL import Image as PILImage
import io
def display_image(data):
"""画像を表示する"""
display(Image(data=data))
def save_image(data, filename):
"""画像を保存する"""
image = PILImage.open(io.BytesIO(data))
image.save(filename)
for part in response.candidates[0].content.parts:
if part.inline_data:
display_image(part.inline_data.data)
save_image(part.inline_data.data, f"output.png")
else:
display(Markdown(part.text))