Spaces:
Running
Running
import os | |
import io | |
import PIL.Image | |
import tempfile | |
from google import genai | |
from google.genai import types | |
from datetime import datetime | |
# 使用 Gemini 生成圖片 | |
client = genai.Client(api_key=os.environ["GOOGLE_API_KEY"]) | |
def generate_image_with_gemini(prompt): | |
response = client.models.generate_content( | |
model="gemini-2.0-flash-exp-image-generation", | |
contents=prompt, | |
config=types.GenerateContentConfig(response_modalities=['Text', 'Image']) | |
) | |
for part in response.candidates[0].content.parts: | |
if part.text is not None: | |
print(part.text) | |
elif part.inline_data is not None: | |
return part.inline_data.data | |
return | |
def upload_image_to_imgur(client, image_binary, album=None, name="gemini-image", title="gemini Generated Image"): | |
# 將 binary 資料轉為 PIL Image | |
image = PIL.Image.open(io.BytesIO(image_binary)) | |
# 建立暫存檔案來上傳 (因為 ImgurClient 需要檔案路徑) | |
with tempfile.NamedTemporaryFile(suffix=".png", delete=True) as tmp: | |
image.save(tmp.name, format='PNG') | |
# 準備上傳資訊 | |
config = { | |
'album': album, | |
'name': name, | |
'title': title, | |
'description': f'Generated by gemini - {datetime.now()}' | |
} | |
# 使用 client 進行圖片上傳 | |
uploaded_image = client.upload_from_path(tmp.name, config=config, anon=False) | |
# 回傳圖片網址 | |
return uploaded_image['link'] | |