Spaces:
Sleeping
Sleeping
正確寫法
Browse files- text2image.py +8 -34
text2image.py
CHANGED
|
@@ -1,10 +1,8 @@
|
|
| 1 |
import os
|
| 2 |
import logging
|
| 3 |
-
from io import BytesIO
|
| 4 |
from PIL import Image
|
| 5 |
import gradio as gr
|
| 6 |
-
|
| 7 |
-
from google.genai import types
|
| 8 |
|
| 9 |
# 設定 logging
|
| 10 |
logging.basicConfig(
|
|
@@ -15,41 +13,17 @@ logging.basicConfig(
|
|
| 15 |
|
| 16 |
# 初始化 Gemini API
|
| 17 |
GEMINI_API_KEY = os.environ.get("GEMINI_API_KEY")
|
| 18 |
-
|
|
|
|
| 19 |
|
| 20 |
# 定義「圖解釋文」功能
|
| 21 |
def explain_image(image: Image.Image):
|
| 22 |
-
#
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
image_bytes = buffered.getvalue()
|
| 26 |
-
|
| 27 |
-
# 直接建立 types.Content
|
| 28 |
-
contents = [
|
| 29 |
-
types.Content(
|
| 30 |
-
parts=[
|
| 31 |
-
types.Part(
|
| 32 |
-
inline_data=types.Blob(
|
| 33 |
-
mime_type="image/png",
|
| 34 |
-
data=image_bytes
|
| 35 |
-
)
|
| 36 |
-
),
|
| 37 |
-
types.Part(
|
| 38 |
-
text="請用繁體中文詳細說明這張圖片的內容。"
|
| 39 |
-
)
|
| 40 |
-
]
|
| 41 |
-
)
|
| 42 |
-
]
|
| 43 |
-
|
| 44 |
-
# 呼叫 Gemini 模型
|
| 45 |
-
response = client.generate_content(
|
| 46 |
-
model="gemini-1.5-flash",
|
| 47 |
-
contents=contents,
|
| 48 |
-
generation_config=types.GenerationConfig(response_mime_type="text/plain")
|
| 49 |
)
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
explanation = response.candidates[0].content.parts[0].text
|
| 53 |
logging.info("圖片說明成功取得。")
|
| 54 |
return explanation
|
| 55 |
|
|
|
|
| 1 |
import os
|
| 2 |
import logging
|
|
|
|
| 3 |
from PIL import Image
|
| 4 |
import gradio as gr
|
| 5 |
+
import google.generativeai as genai
|
|
|
|
| 6 |
|
| 7 |
# 設定 logging
|
| 8 |
logging.basicConfig(
|
|
|
|
| 13 |
|
| 14 |
# 初始化 Gemini API
|
| 15 |
GEMINI_API_KEY = os.environ.get("GEMINI_API_KEY")
|
| 16 |
+
genai.configure(api_key=GEMINI_API_KEY)
|
| 17 |
+
google_client = genai.GenerativeModel(model_name="gemini-2.0-flash")
|
| 18 |
|
| 19 |
# 定義「圖解釋文」功能
|
| 20 |
def explain_image(image: Image.Image):
|
| 21 |
+
# 直接把 PIL image 傳進去
|
| 22 |
+
response = google_client.generate_content(
|
| 23 |
+
contents=[image, "請用繁體中文描述這張圖片"]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
)
|
| 25 |
+
# 取出回答
|
| 26 |
+
explanation = response.text
|
|
|
|
| 27 |
logging.info("圖片說明成功取得。")
|
| 28 |
return explanation
|
| 29 |
|