Spaces:
Sleeping
Sleeping
fix: 修復圖片輸入處理 (支援 URL/Path/Bytes 多種格式)
Browse files
app.py
CHANGED
|
@@ -534,14 +534,39 @@ def process_image(
|
|
| 534 |
if image is None:
|
| 535 |
return json.dumps({"error": "❌ 請上傳圖片"}, ensure_ascii=False, indent=2)
|
| 536 |
|
| 537 |
-
# 讀取圖片數據
|
| 538 |
-
file_path =
|
|
|
|
| 539 |
|
|
|
|
| 540 |
if isinstance(image, str):
|
| 541 |
-
|
| 542 |
-
|
| 543 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 544 |
file_bytes = image
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 545 |
|
| 546 |
# ============================================
|
| 547 |
# 🛡️ 檔案驗證
|
|
|
|
| 534 |
if image is None:
|
| 535 |
return json.dumps({"error": "❌ 請上傳圖片"}, ensure_ascii=False, indent=2)
|
| 536 |
|
| 537 |
+
# 讀取圖片數據 (支援多種輸入格式)
|
| 538 |
+
file_path = "uploaded_image"
|
| 539 |
+
file_bytes = None
|
| 540 |
|
| 541 |
+
# Gradio 5.x 可能傳入字符串路徑或 bytes
|
| 542 |
if isinstance(image, str):
|
| 543 |
+
# 檢查是否為 URL
|
| 544 |
+
if image.startswith(('http://', 'https://')):
|
| 545 |
+
import urllib.request
|
| 546 |
+
try:
|
| 547 |
+
with urllib.request.urlopen(image, timeout=30) as resp:
|
| 548 |
+
file_bytes = resp.read()
|
| 549 |
+
file_path = image.split('/')[-1] or "url_image"
|
| 550 |
+
except Exception as e:
|
| 551 |
+
return json.dumps({"error": f"❌ 無法下載圖片: {e}"}, ensure_ascii=False, indent=2)
|
| 552 |
+
else:
|
| 553 |
+
# 本地檔案路徑
|
| 554 |
+
try:
|
| 555 |
+
with open(image, 'rb') as f:
|
| 556 |
+
file_bytes = f.read()
|
| 557 |
+
file_path = image
|
| 558 |
+
except Exception as e:
|
| 559 |
+
return json.dumps({"error": f"❌ 無法讀取圖片: {e}"}, ensure_ascii=False, indent=2)
|
| 560 |
+
elif isinstance(image, bytes):
|
| 561 |
file_bytes = image
|
| 562 |
+
elif hasattr(image, 'read'):
|
| 563 |
+
# File-like object
|
| 564 |
+
file_bytes = image.read()
|
| 565 |
+
else:
|
| 566 |
+
return json.dumps({"error": f"❌ 不支援的圖片格式: {type(image)}"}, ensure_ascii=False, indent=2)
|
| 567 |
+
|
| 568 |
+
if file_bytes is None:
|
| 569 |
+
return json.dumps({"error": "❌ 無法讀取圖片數據"}, ensure_ascii=False, indent=2)
|
| 570 |
|
| 571 |
# ============================================
|
| 572 |
# 🛡️ 檔案驗證
|