Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -495,12 +495,11 @@ class TextToSQLSystem:
|
|
| 495 |
return formatted.strip()
|
| 496 |
|
| 497 |
# 在 class TextToSQLSystem 內
|
| 498 |
-
|
| 499 |
def _validate_and_fix_sql(self, question: str, raw_response: str) -> Tuple[Optional[str], str]:
|
| 500 |
"""
|
| 501 |
-
(
|
| 502 |
-
|
| 503 |
-
如果無法匹配,則回退到解析和修正AI模型的輸出。
|
| 504 |
"""
|
| 505 |
q_lower = question.lower()
|
| 506 |
|
|
@@ -508,7 +507,7 @@ class TextToSQLSystem:
|
|
| 508 |
# 第零層:統一實體識別引擎 (Unified Entity Recognition Engine)
|
| 509 |
# ==============================================================================
|
| 510 |
entity_match_data = None
|
| 511 |
-
#
|
| 512 |
entity_patterns = [
|
| 513 |
# 模式1: 匹配 "类型 + ID" (e.g., "买家ID C0761N") - 最高优先级
|
| 514 |
{'pattern': r"(買家|买家|buyer)\s*(?:id|代號|代碼|代号|代码)\s*'\"?\b([A-Z]\d{4}[A-Z])\b'\"?", 'column': 'sd.BuyerID', 'type': '買家ID'},
|
|
@@ -554,7 +553,8 @@ class TextToSQLSystem:
|
|
| 554 |
|
| 555 |
# --- 運行一系列獨立的意圖偵測器 ---
|
| 556 |
|
| 557 |
-
# 偵測器 2.1: 核心動作意圖
|
|
|
|
| 558 |
if any(kw in q_lower for kw in ['幾份', '多少', '數量', '總數', 'how many', 'count']):
|
| 559 |
intents['action'] = 'count'
|
| 560 |
sql_components['select'].append("COUNT(DISTINCT jt.JobNo) AS report_count")
|
|
@@ -566,6 +566,7 @@ class TextToSQLSystem:
|
|
| 566 |
sql_components['log_parts'].append("報告列表")
|
| 567 |
|
| 568 |
# 偵測器 2.2: 時間意圖
|
|
|
|
| 569 |
year_match = re.search(r'(\d{4})\s*年?', question)
|
| 570 |
month_match = re.search(r'(\d{1,2})\s*月', question)
|
| 571 |
if year_match:
|
|
@@ -577,7 +578,8 @@ class TextToSQLSystem:
|
|
| 577 |
sql_components['where'].append(f"strftime('%m', jt.ReportAuthorization) = '{month}'")
|
| 578 |
sql_components['log_parts'].append(f"{month}月")
|
| 579 |
|
| 580 |
-
# 偵測器 2.3: 實體意圖
|
|
|
|
| 581 |
if entity_match_data:
|
| 582 |
if "TSR53SampleDescription" not in " ".join(sql_components['joins']):
|
| 583 |
sql_components['joins'].append("JOIN TSR53SampleDescription AS sd ON jt.JobNo = sd.JobNo")
|
|
@@ -589,7 +591,8 @@ class TextToSQLSystem:
|
|
| 589 |
if intents.get('action') == 'list':
|
| 590 |
sql_components['select'].append("sd.BuyerName")
|
| 591 |
|
| 592 |
-
# 偵測器 2.4: 評級意圖
|
|
|
|
| 593 |
if 'fail' in q_lower or '失敗' in q_lower:
|
| 594 |
if "TSR53SampleDescription" not in " ".join(sql_components['joins']):
|
| 595 |
sql_components['joins'].append("JOIN TSR53SampleDescription AS sd ON jt.JobNo = sd.JobNo")
|
|
@@ -601,16 +604,32 @@ class TextToSQLSystem:
|
|
| 601 |
sql_components['where'].append("sd.OverallRating = 'Pass'")
|
| 602 |
sql_components['log_parts'].append("Pass")
|
| 603 |
|
| 604 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 605 |
lab_group_match = re.search(r'([A-Z]{1,2})組', question, re.IGNORECASE)
|
| 606 |
if lab_group_match:
|
| 607 |
-
|
|
|
|
|
|
|
|
|
|
| 608 |
# 測試項目數量應從 JobItemsInProgress 計算
|
| 609 |
sql_components['joins'].append("JOIN JobItemsInProgress AS jip ON jt.JobNo = jip.JobNo")
|
| 610 |
-
sql_components['where'].append(f"jip.LabGroup = '{
|
| 611 |
-
sql_components['log_parts'].append(f"{
|
|
|
|
| 612 |
# 如果是計數,目標應該是測試項目而不是報告
|
| 613 |
-
if intents.get('action') == 'count':
|
| 614 |
sql_components['select'] = ["COUNT(jip.ItemCode) AS item_count"] # 覆蓋掉原有的 SELECT
|
| 615 |
sql_components['log_parts'][0] = "測試項目總數" # 更新日誌
|
| 616 |
|
|
@@ -618,7 +637,8 @@ class TextToSQLSystem:
|
|
| 618 |
if 'action' in intents:
|
| 619 |
# 動態決定主表和必要的預設條件
|
| 620 |
sql_components['from'] = "FROM JobTimeline AS jt"
|
| 621 |
-
|
|
|
|
| 622 |
|
| 623 |
# 組合所有SQL組件
|
| 624 |
select_clause = "SELECT " + ", ".join(sorted(list(set(sql_components['select']))))
|
|
@@ -638,6 +658,7 @@ class TextToSQLSystem:
|
|
| 638 |
# ==============================================================================
|
| 639 |
self._log("未觸發任何模板,嘗試解析並修正 AI 輸出...", "INFO")
|
| 640 |
|
|
|
|
| 641 |
parsed_sql = parse_sql_from_response(raw_response)
|
| 642 |
if not parsed_sql:
|
| 643 |
self._log(f"❌ 未能從模型回應中解析出任何 SQL。原始回應: {raw_response}", "ERROR")
|
|
|
|
| 495 |
return formatted.strip()
|
| 496 |
|
| 497 |
# 在 class TextToSQLSystem 內
|
| 498 |
+
|
| 499 |
def _validate_and_fix_sql(self, question: str, raw_response: str) -> Tuple[Optional[str], str]:
|
| 500 |
"""
|
| 501 |
+
(V28 / 實驗組別名映射版)
|
| 502 |
+
增加了實驗組別名到資料庫真實值的映射,以處理 "A組" -> "TA" 這類轉換。
|
|
|
|
| 503 |
"""
|
| 504 |
q_lower = question.lower()
|
| 505 |
|
|
|
|
| 507 |
# 第零層:統一實體識別引擎 (Unified Entity Recognition Engine)
|
| 508 |
# ==============================================================================
|
| 509 |
entity_match_data = None
|
| 510 |
+
# (您的 entity_patterns 邏輯保持不變,此處省略以保持簡潔)
|
| 511 |
entity_patterns = [
|
| 512 |
# 模式1: 匹配 "类型 + ID" (e.g., "买家ID C0761N") - 最高优先级
|
| 513 |
{'pattern': r"(買家|买家|buyer)\s*(?:id|代號|代碼|代号|代码)\s*'\"?\b([A-Z]\d{4}[A-Z])\b'\"?", 'column': 'sd.BuyerID', 'type': '買家ID'},
|
|
|
|
| 553 |
|
| 554 |
# --- 運行一系列獨立的意圖偵測器 ---
|
| 555 |
|
| 556 |
+
# 偵測器 2.1: 核心動作意圖
|
| 557 |
+
# (此處邏輯不變)
|
| 558 |
if any(kw in q_lower for kw in ['幾份', '多少', '數量', '總數', 'how many', 'count']):
|
| 559 |
intents['action'] = 'count'
|
| 560 |
sql_components['select'].append("COUNT(DISTINCT jt.JobNo) AS report_count")
|
|
|
|
| 566 |
sql_components['log_parts'].append("報告列表")
|
| 567 |
|
| 568 |
# 偵測器 2.2: 時間意圖
|
| 569 |
+
# (此處邏輯不變)
|
| 570 |
year_match = re.search(r'(\d{4})\s*年?', question)
|
| 571 |
month_match = re.search(r'(\d{1,2})\s*月', question)
|
| 572 |
if year_match:
|
|
|
|
| 578 |
sql_components['where'].append(f"strftime('%m', jt.ReportAuthorization) = '{month}'")
|
| 579 |
sql_components['log_parts'].append(f"{month}月")
|
| 580 |
|
| 581 |
+
# 偵測器 2.3: 實體意圖
|
| 582 |
+
# (此處邏輯不變)
|
| 583 |
if entity_match_data:
|
| 584 |
if "TSR53SampleDescription" not in " ".join(sql_components['joins']):
|
| 585 |
sql_components['joins'].append("JOIN TSR53SampleDescription AS sd ON jt.JobNo = sd.JobNo")
|
|
|
|
| 591 |
if intents.get('action') == 'list':
|
| 592 |
sql_components['select'].append("sd.BuyerName")
|
| 593 |
|
| 594 |
+
# 偵測器 2.4: 評級意圖
|
| 595 |
+
# (此處邏輯不變)
|
| 596 |
if 'fail' in q_lower or '失敗' in q_lower:
|
| 597 |
if "TSR53SampleDescription" not in " ".join(sql_components['joins']):
|
| 598 |
sql_components['joins'].append("JOIN TSR53SampleDescription AS sd ON jt.JobNo = sd.JobNo")
|
|
|
|
| 604 |
sql_components['where'].append("sd.OverallRating = 'Pass'")
|
| 605 |
sql_components['log_parts'].append("Pass")
|
| 606 |
|
| 607 |
+
# *** V28 修正 ***
|
| 608 |
+
# 偵測器 2.5: 實驗組 (LabGroup) 意圖 (帶有別名映射)
|
| 609 |
+
lab_group_mapping = {
|
| 610 |
+
'A': 'TA',
|
| 611 |
+
'B': 'TB',
|
| 612 |
+
'C': 'TC',
|
| 613 |
+
'D': 'TD',
|
| 614 |
+
'E': 'TE',
|
| 615 |
+
'Y': 'TY',
|
| 616 |
+
'GCI': 'GCI',
|
| 617 |
+
'GCO': 'GCO'
|
| 618 |
+
# ...可在此處繼續添加其他映射...
|
| 619 |
+
}
|
| 620 |
lab_group_match = re.search(r'([A-Z]{1,2})組', question, re.IGNORECASE)
|
| 621 |
if lab_group_match:
|
| 622 |
+
user_input_group = lab_group_match.group(1).upper()
|
| 623 |
+
# 從映射表中查找真實值,如果找不到,則使用用戶的原始輸入作為備用
|
| 624 |
+
db_lab_group = lab_group_mapping.get(user_input_group, user_input_group)
|
| 625 |
+
|
| 626 |
# 測試項目數量應從 JobItemsInProgress 計算
|
| 627 |
sql_components['joins'].append("JOIN JobItemsInProgress AS jip ON jt.JobNo = jip.JobNo")
|
| 628 |
+
sql_components['where'].append(f"jip.LabGroup = '{db_lab_group}'")
|
| 629 |
+
sql_components['log_parts'].append(f"{user_input_group}組(->{db_lab_group})")
|
| 630 |
+
|
| 631 |
# 如果是計數,目標應該是測試項目而不是報告
|
| 632 |
+
if intents.get('action') == 'count' and "測試項目" in question:
|
| 633 |
sql_components['select'] = ["COUNT(jip.ItemCode) AS item_count"] # 覆蓋掉原有的 SELECT
|
| 634 |
sql_components['log_parts'][0] = "測試項目總數" # 更新日誌
|
| 635 |
|
|
|
|
| 637 |
if 'action' in intents:
|
| 638 |
# 動態決定主表和必要的預設條件
|
| 639 |
sql_components['from'] = "FROM JobTimeline AS jt"
|
| 640 |
+
if year_match or month_match or entity_match_data or ('fail' in q_lower or '失敗' in q_lower) or ('pass' in q_lower or '通過' in q_lower):
|
| 641 |
+
sql_components['where'].insert(0, "jt.ReportAuthorization IS NOT NULL")
|
| 642 |
|
| 643 |
# 組合所有SQL組件
|
| 644 |
select_clause = "SELECT " + ", ".join(sorted(list(set(sql_components['select']))))
|
|
|
|
| 658 |
# ==============================================================================
|
| 659 |
self._log("未觸發任何模板,嘗試解析並修正 AI 輸出...", "INFO")
|
| 660 |
|
| 661 |
+
# (此處的 Fallback 邏輯保持不變)
|
| 662 |
parsed_sql = parse_sql_from_response(raw_response)
|
| 663 |
if not parsed_sql:
|
| 664 |
self._log(f"❌ 未能從模型回應中解析出任何 SQL。原始回應: {raw_response}", "ERROR")
|