Spaces:
Sleeping
Sleeping
Create image_processor.py
Browse files- image_processor.py +33 -0
image_processor.py
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# image_processor.py
|
| 2 |
+
import google.generativeai as genai
|
| 3 |
+
from PIL import Image
|
| 4 |
+
import config
|
| 5 |
+
import os
|
| 6 |
+
|
| 7 |
+
# 初始化 Gemini API
|
| 8 |
+
if config.GEMINI_KEY:
|
| 9 |
+
genai.configure(api_key=config.GEMINI_KEY)
|
| 10 |
+
|
| 11 |
+
def extract_text(image_path):
|
| 12 |
+
"""
|
| 13 |
+
眼睛模組:讀取圖片並擷取所有文字 (OCR)
|
| 14 |
+
"""
|
| 15 |
+
if not config.GEMINI_KEY:
|
| 16 |
+
print("⚠️ 未設定 GEMINI_KEY,無法啟用視覺功能")
|
| 17 |
+
return None
|
| 18 |
+
|
| 19 |
+
try:
|
| 20 |
+
# 呼叫 Gemini 1.5 Flash 模型 (速度最快,適合 OCR)
|
| 21 |
+
model = genai.GenerativeModel('gemini-1.5-flash')
|
| 22 |
+
|
| 23 |
+
# 開啟圖片
|
| 24 |
+
img = Image.open(image_path)
|
| 25 |
+
|
| 26 |
+
# 給 Gemini 的指令:只要抓字,不要自己亂加戲或翻譯
|
| 27 |
+
prompt = "請幫我辨識這張圖片中的所有文字(包含中文、英文字母或族語羅馬拼音)。請直接回覆原文,保持原本的換行格式,不要自行翻譯、解釋或推測。"
|
| 28 |
+
|
| 29 |
+
response = model.generate_content([prompt, img])
|
| 30 |
+
return response.text.strip()
|
| 31 |
+
except Exception as e:
|
| 32 |
+
print(f"圖片辨識失敗: {e}")
|
| 33 |
+
return None
|