calculate_vision_tokens.py pillow と math
import math
from PIL import Image
def calculate_openai_image_tokens(width: int, height: int, detail: str = "high") -> int:
if detail == "low":
return 85
# ステップ 1: 2048x2048枠内に収まるよう縮小
if width > 2048 or height > 2048:
scale = 2048 / max(width, height)
width = int(width * scale)
height = int(height * scale)
# ステップ 2: 最短辺を768pxにスケーリング
shortest = min(width, height)
scale = 768 / shortest
width = int(width * scale)
height = int(height * scale)
# ステップ 3: 512x512タイルの枚数を算出
tiles_w = math.ceil(width / 512)
tiles_h = math.ceil(height / 512)
total_tiles = tiles_w * tiles_h
# ステップ 4: 最終トークン予算を計算
total_tokens = (total_tiles * 170) + 85
print(f"Tiles: {tiles_w}x{tiles_h} = {total_tiles} | Total Tokens: {total_tokens}")
return total_tokens
calculate_openai_image_tokens(1920, 1080, "high")