Spaces:
Sleeping
Sleeping
Create Image_generation.py
Browse files- Image_generation.py +46 -0
Image_generation.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import io
|
| 3 |
+
import PIL.Image
|
| 4 |
+
from google import genai
|
| 5 |
+
from google.genai import types
|
| 6 |
+
from datetime import datetime
|
| 7 |
+
|
| 8 |
+
# 使用 Gemini 生成圖片
|
| 9 |
+
client = genai.Client(api_key=os.environ["GOOGLE_API_KEY"])
|
| 10 |
+
|
| 11 |
+
def generate_image_with_gemini(prompt):
|
| 12 |
+
response = client.models.generate_content(
|
| 13 |
+
model="gemini-2.0-flash-exp-image-generation",
|
| 14 |
+
contents=prompt,
|
| 15 |
+
config=types.GenerateContentConfig(response_modalities=['Text', 'Image'])
|
| 16 |
+
)
|
| 17 |
+
|
| 18 |
+
for part in response.candidates[0].content.parts:
|
| 19 |
+
if part.text is not None:
|
| 20 |
+
print(part.text)
|
| 21 |
+
elif part.inline_data is not None:
|
| 22 |
+
return part.inline_data.data
|
| 23 |
+
|
| 24 |
+
return
|
| 25 |
+
|
| 26 |
+
def upload_image_to_imgur(client, image_binary, album=None, name="gemini-image", title="gemini Generated Image"):
|
| 27 |
+
# 將 binary 資料轉為 PIL Image
|
| 28 |
+
image = PIL.Image.open(io.BytesIO(image_binary))
|
| 29 |
+
|
| 30 |
+
# 建立暫存檔案來上傳 (因為 ImgurClient 需要檔案路徑)
|
| 31 |
+
with tempfile.NamedTemporaryFile(suffix=".png", delete=True) as tmp:
|
| 32 |
+
image.save(tmp.name, format='PNG')
|
| 33 |
+
|
| 34 |
+
# 準備上傳資訊
|
| 35 |
+
config = {
|
| 36 |
+
'album': album,
|
| 37 |
+
'name': name,
|
| 38 |
+
'title': title,
|
| 39 |
+
'description': f'Generated by gemini - {datetime.now()}'
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
+
# 使用 client 進行圖片上傳
|
| 43 |
+
uploaded_image = client.upload_from_path(tmp.name, config=config, anon=False)
|
| 44 |
+
|
| 45 |
+
# 回傳圖片網址
|
| 46 |
+
return uploaded_image['link']
|