import os
from openai import OpenAI
from PIL import Image
from io import BytesIO
import base64
client = OpenAI(
api_key="sk-***", # あなたのAiHubMixで生成したキーに置き換えてください
base_url="https://aihubmix.com/v1",
)
project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
image_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "resources", "filled.jpg")
if not os.path.exists(image_path):
raise FileNotFoundError(f"画像 {image_path} が存在しません")
def encode_image(image_path):
with open(image_path, "rb") as image_file:
return base64.b64encode(image_file.read()).decode("utf-8")
base64_image = encode_image(image_path)
response = client.chat.completions.create(
model="gemini-2.0-flash-preview-image-generation",
messages=[
{
"role": "user",
"content": [
{
"type": "text",
"text": "describe the image with a concise and engaging paragraph, then fill color as children's crayon style",
},
{
"type": "image_url",
"image_url": {"url": f"data:image/jpeg;base64,{base64_image}"},
},
],
},
],
modalities=["text", "image"],
temperature=0.7,
)
try:
# base64データなしで基本的な応答情報を出力
print(f"作成時間: {response.created}")
print(f"トークン使用量: {response.usage.total_tokens}")
# multi_mod_contentフィールドが存在するかどうかを確認
if (
hasattr(response.choices[0].message, "multi_mod_content")
and response.choices[0].message.multi_mod_content is not None
):
print("\n応答コンテンツ:")
for part in response.choices[0].message.multi_mod_content:
if "text" in part and part["text"] is not None:
print(part["text"])
# 画像コンテンツを処理
elif "inline_data" in part and part["inline_data"] is not None:
print("\n🖼️ [画像コンテンツを受信しました]")
image_data = base64.b64decode(part["inline_data"]["data"])
mime_type = part["inline_data"].get("mime_type", "image/png")
print(f"画像タイプ: {mime_type}")
image = Image.open(BytesIO(image_data))
image.show()
# 画像を保存
output_dir = os.path.join(os.path.dirname(image_path), "output")
os.makedirs(output_dir, exist_ok=True)
output_path = os.path.join(output_dir, "edited_image.jpg")
image.save(output_path)
print(f"✅ 画像は以下に保存されました: {output_path}")
else:
print("有効なマルチモーダル応答が受信されませんでした。応答構造を確認してください")
except Exception as e:
print(f"応答の処理中にエラーが発生しました: {str(e)}")