Python:如何串接Gemini API?如何傳遞圖片給API?如何將回應的base64 str轉回圖片?

加入好友
加入社群
Python:如何串接Gemini API?如何傳遞圖片給API?如何將回應的base64 str轉回圖片? - 儲蓄保險王

API key 請到 AI Studio申請

官網說明:

Python:如何串接Gemini API?如何傳遞圖片給API?如何將回應的base64 str轉回圖片? - 儲蓄保險王

官網示範code:

from google import genai
from google.genai import types
from PIL import Image
from io import BytesIO

client = genai.Client()

prompt = (
    "Create a picture of a nano banana dish in a fancy restaurant with a Gemini theme"
)

response = client.models.generate_content(
    model="gemini-2.5-flash-image-preview",
    contents=[prompt],
)

for part in response.candidates[0].content.parts:
    if part.text is not None:
        print(part.text)
    elif part.inline_data is not None:
        image = Image.open(BytesIO(part.inline_data.data))
        image.save("generated_image.png")

實作

import os
import json
from google import genai
import base64
import time

dir_api = r"D:\Python code\api_key"
basename_api = "api_key.json"
path_api = os.path.join(dir_api, basename_api)

dir_img = r"D:\Python code\vision"
basename_img = "leone-africano-2.jpg"
path_img = os.path.join(dir_img, basename_img)
main_fname = basename_img.split(".")[0] 
#"leone-africano-2"

with open(path_api, "r", encoding="utf-8") as f:
    api_key = json.load(f)["Gemini"]["api_key"]
#'AIzaSyD...'

with open(path_img, "rb") as img_f:
    img_bytes = img_f.read()
    base64_str = base64.b64encode(img_bytes).decode('utf-8')

model = "gemini-2.5-flash-image-preview" #"gemini-2.5-flash"
client = genai.Client(api_key=api_key)
prompt = """製作圖片中角色的1/7比例商業化模型手辦
以寫實風格呈現置於真實環境中的電腦桌上
模型底座為 圓形透明壓克力材質且上面不含任何文字
電腦螢幕畫面顯示該模型在 ZBrush建模的製作過程
電腦螢幕旁擺放一個 圓角設計正面帶透明視窗的包裝盒盒內模型清晰可見
請回傳一張圖片不要只描述輸出需為 inline_data 形式的 base64 編碼圖片數據
"""
#prompt = "Google Gemini 是什麼請用繁體中文簡要回答"

image_part = {
    "inline_data": {
        "mime_type": "image/jpeg",
        "data": img_bytes #base64_str
    }
}

response = client.models.generate_content(
    model=model,
    contents=[
        {"role": "user", 
         "parts": [{"text": prompt}, image_part]}
    ]
)
print(response.text)

b64_str = response.candidates[0].content.parts[1].inline_data.data
mime = response.candidates[0].content.parts[1].inline_data.mime_type   
# 這是 API 回報的檔案格式 #'image/png'
ext = mime.split("/")[1]  # 'png'

# base64 -> bytes
img_bytes = base64.b64decode(b64_str)
#b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x05\x80'

# 存檔
strftime = time.strftime("%Y%m%d_%H%M%S")
path_ex = os.path.join(dir_img, f"{main_fname}_output_{strftime}.{ext}")
with open(path_ex, "wb") as f:
    f.write(img_bytes)

print(f"圖片已存為:\n {path_ex}")

輸出結果:

Python:如何串接Gemini API?如何傳遞圖片給API?如何將回應的base64 str轉回圖片? - 儲蓄保險王

做幾張圖而已就會用盡tokens,
並非程式錯誤:

errors.APIError.raise_for_response(response)
File "C:\Python311\Lib\site-packages\google\genai\errors.py", line 105, in raise_for_response
raise ClientError(status_code, response_json, response)
google.genai.errors.ClientError: 429 RESOURCE_EXHAUSTED. {'error': {'code': 429, 'message': 'Resource has been exhausted (e.g. check quota).', 'status': 'RESOURCE_EXHAUSTED'}}

看消耗的tokens
response.usage_metadata

Python:如何串接Gemini API?如何傳遞圖片給API?如何將回應的base64 str轉回圖片? - 儲蓄保險王

推薦hahow線上學習python: https://igrape.net/30afN

加入好友
加入社群
Python:如何串接Gemini API?如何傳遞圖片給API?如何將回應的base64 str轉回圖片? - 儲蓄保險王

儲蓄保險王

儲蓄險是板主最喜愛的儲蓄工具,最喜愛的投資理財工具則是ETF,最喜愛的省錢工具則是信用卡

You may also like...

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *