import os import json import re import base64 from pathlib import Path from openai import OpenAI from PIL import Image import numpy as np import torch from google import genai try: from colorama import Fore, Style, init except Exception: # colorama is optional (cosmetic terminal colors) class _NoColor: def __getattr__(self, _): return "" Fore = Style = _NoColor() def init(*a, **k): return None from time import sleep # === Config === client = genai.Client(api_key=os.environ.get("GEMINI_API_KEY") or os.environ.get("GOOGLE_API_KEY") or "EMPTY") def encode_image_base64(image_path: str) -> str: with open(image_path, "rb") as f: return base64.b64encode(f.read()).decode("utf-8") def transform_data_format(list:list) -> str: input = [] for item in list: dict = {} if 'image' in item and isinstance(item['image'], str): image = encode_image_base64(item['image']) dict['inline_data'] = {"mime_type": "image/png", "data": image} print(f"{Fore.YELLOW} Encoded image from path {Style.RESET_ALL} {item['image']}") elif 'image_base64' in item: image = item['image_base64'] dict['inline_data'] = {"mime_type": "image/png", "data": image} elif 'text' in item: dict['text'] = item['text'] print(f"{Fore.YELLOW} Added text {Style.RESET_ALL} {item['text']}") input.append(dict) return input # the input is a list: # [{'image': 'path'}, {'text': 'text'}] def generate_content(model_name, content): input_data = transform_data_format(content) for attempt in range(5): # 最多重试 5 次 try: response = client.models.generate_content( model=model_name, contents={ "role": "user", "parts": input_data } ) print(f"{Fore.YELLOW} The response from the model is: {Style.RESET_ALL}", response.text) sleep(1) # 等待一秒钟,避免过载 return response.text except: print(f"{Fore.RED}503 服务端过载,等待重试(第 {attempt+1} 次)...{Style.RESET_ALL}") sleep(2 ** attempt) # 指数退避等待 continue # 再试一次 print(f"{Fore.RED}重试次数已用完,仍然 503 过载{Style.RESET_ALL}") return "error"