Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -36,24 +36,42 @@ def extract_text(file):
|
|
| 36 |
|
| 37 |
# 3. 定義主預測邏輯
|
| 38 |
def predict(file, manual_context, question):
|
| 39 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 40 |
if file is not None:
|
|
|
|
| 41 |
context = extract_text(file)
|
| 42 |
-
|
|
|
|
|
|
|
| 43 |
context = manual_context
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
#
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 57 |
|
| 58 |
# 4. 建立 Gradio 網頁介面
|
| 59 |
with gr.Blocks(title="Case Study: AI Document QA") as demo:
|
|
|
|
| 36 |
|
| 37 |
# 3. 定義主預測邏輯
|
| 38 |
def predict(file, manual_context, question):
|
| 39 |
+
# 1. 檢查問題是否為空
|
| 40 |
+
if not question.strip():
|
| 41 |
+
return "⚠️ 請輸入您想提問的問題。"
|
| 42 |
+
|
| 43 |
+
# 2. 判斷資料來源優先級
|
| 44 |
+
source_info = ""
|
| 45 |
if file is not None:
|
| 46 |
+
# 如果有上傳檔案,優先讀取檔案
|
| 47 |
context = extract_text(file)
|
| 48 |
+
source_info = f"📝 來源:已偵測到上傳檔案 ({file.name.split('/')[-1]})"
|
| 49 |
+
elif manual_context.strip():
|
| 50 |
+
# 如果沒有檔案但有貼上文字
|
| 51 |
context = manual_context
|
| 52 |
+
source_info = "📝 來源:手動輸入的文本"
|
| 53 |
+
else:
|
| 54 |
+
# 兩者皆無
|
| 55 |
+
return "⚠️ 請先提供文件內容(上傳檔案或是在文字框貼上內容)。"
|
| 56 |
|
| 57 |
+
# 3. 檢查 Context 是否成功提取文字
|
| 58 |
+
if not context.strip():
|
| 59 |
+
return "⚠️ 無法從提供的來源中提取有效文字,請檢查檔案格式。"
|
| 60 |
+
|
| 61 |
+
# 4. 執行模型推理
|
| 62 |
+
try:
|
| 63 |
+
result = qa_model(question=question, context=context)
|
| 64 |
+
|
| 65 |
+
# SQuAD 2.0 門檻檢查
|
| 66 |
+
if result['score'] < 0.01:
|
| 67 |
+
return f"{source_info}\n\n❌ 抱歉,在提供的內容中找不到相關答案。"
|
| 68 |
+
|
| 69 |
+
return (f"{source_info}\n"
|
| 70 |
+
f"🎯 模型回答:{result['answer']}\n"
|
| 71 |
+
f"📊 信心分數:{round(result['score'] * 100, 2)}%")
|
| 72 |
+
|
| 73 |
+
except Exception as e:
|
| 74 |
+
return f"❌ 發生錯誤:{str(e)}"
|
| 75 |
|
| 76 |
# 4. 建立 Gradio 網頁介面
|
| 77 |
with gr.Blocks(title="Case Study: AI Document QA") as demo:
|