Paul720810 commited on
Commit
fcd6422
·
verified ·
1 Parent(s): 5df0985

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +69 -38
app.py CHANGED
@@ -1,6 +1,3 @@
1
- # 檔案名稱: app.py
2
- # 部署在 Hugging Face Spaces (已修正 KeyError)
3
-
4
  import gradio as gr
5
  import requests
6
  import json
@@ -19,25 +16,37 @@ SIMILARITY_THRESHOLD = 0.90
19
  print("--- [1/5] 開始初始化應用 ---")
20
 
21
  # --- 1. 載入知識庫 ---
 
 
22
  try:
23
  print(f"--- [2/5] 正在從 '{DATASET_REPO_ID}' 載入知識庫... ---")
24
- # 載入問答範例, 移除已過時的 trust_remote_code 參數
25
- dataset = load_dataset(DATASET_REPO_ID, token=HF_TOKEN)
26
- raw_qa_dataset = dataset['train']
27
-
28
- # *** 關鍵修正:解析被包裹在 'text' 欄位中的 JSON ***
29
- parsed_qa_data = []
30
- for item in raw_qa_dataset:
31
- try:
32
- # item 現在是 {'text': '{"question": "...", "sql": "..."}'}
33
- line_dict = json.loads(item['text'])
34
- parsed_qa_data.append(line_dict)
35
- except (json.JSONDecodeError, KeyError) as e:
36
- print(f"警告:跳過一行無法解析的數據: {item}, 錯誤: {e}")
37
-
38
- # 使用解析後的數據創建一個新的、格式正確的 Dataset 對象
39
- qa_dataset = Dataset.from_list(parsed_qa_data)
40
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41
  # 載入並解析 Schema JSON
42
  schema_file_path = "sqlite_schema_FULL.json"
43
  hf_hub_download(repo_id=DATASET_REPO_ID, filename=schema_file_path, repo_type='dataset', local_dir='.', token=HF_TOKEN)
@@ -45,15 +54,16 @@ try:
45
  with open(schema_file_path, 'r', encoding='utf-8') as f:
46
  schema_data = json.load(f)
47
 
48
- print(f"--- > 成功解析 {len(qa_dataset)} 條問答範例和 Schema。 ---")
 
49
  except Exception as e:
50
  print(f"!!! 致命錯誤: 無法載入或解析 Dataset '{DATASET_REPO_ID}'.")
51
  print(f"詳細錯誤: {e}")
52
  qa_dataset = Dataset.from_dict({"question": ["示例問題"], "sql": ["SELECT 'Dataset failed to load'"]})
53
- schema_data = {}
54
 
55
  # --- 2. 構建 DDL 和初始化檢索模型 ---
56
  def load_schema_as_ddl(schema_dict: dict) -> str:
 
57
  ddl_string = ""
58
  for table_name, columns in schema_dict.items():
59
  if not isinstance(columns, list): continue
@@ -67,33 +77,53 @@ SCHEMA_DDL = load_schema_as_ddl(schema_data)
67
  print("--- [3/5] 正在載入句向量模型 (all-MiniLM-L6-v2)... ---")
68
  embedder = SentenceTransformer('all-MiniLM-L6-v2', device='cpu')
69
 
70
- # *** 關鍵修正:現在 qa_dataset 的結構是正確的了 ***
71
  questions = [item['question'] for item in qa_dataset]
72
  sql_answers = [item['sql'] for item in qa_dataset]
73
 
74
- print(f"--- [4/5] 正在為 {len(questions)} 個問題計算向量 (這可能需要幾分鐘)... ---")
75
- question_embeddings = embedder.encode(questions, convert_to_tensor=True, show_progress_bar=True)
76
- print("--- > 向量計算完成! ---")
 
 
 
 
 
 
77
 
78
  # --- 3. 混合系統核心邏輯 ---
79
  def get_sql_query(user_question: str):
80
- # (此函式剩餘部分無需修改,保持原樣)
81
  if not user_question:
82
  return "請輸入您的問題。", "日誌:用戶未輸入問題。"
 
 
 
 
 
 
83
  question_embedding = embedder.encode(user_question, convert_to_tensor=True)
84
  hits = util.semantic_search(question_embedding, question_embeddings, top_k=5)
85
- hits = hits[0]
86
- most_similar_hit = hits[0]
87
- similarity_score = most_similar_hit['score']
88
- log_message = f"檢索到最相似問題: '{questions[most_similar_hit['corpus_id']]}' (相似度: {similarity_score:.4f})"
89
- if similarity_score > SIMILARITY_THRESHOLD:
90
- sql_result = sql_answers[most_similar_hit['corpus_id']]
91
- log_message += f"\n相似度 > {SIMILARITY_THRESHOLD},[模式: 直接返回]。"
92
- return sql_result, log_message
93
- log_message += f"\n相似度 < {SIMILARITY_THRESHOLD},[模式: LLM生成]。正在構建 Prompt..."
 
 
 
 
 
 
 
94
  examples_context = ""
95
- for hit in hits[:3]:
96
- examples_context += f"### A user asks: {questions[hit['corpus_id']]}\n{sql_answers[hit['corpus_id']]}\n\n"
 
 
97
  prompt = f"""### Task
98
  Generate a SQLite SQL query that answers the following user question.
99
  Your response must contain ONLY the SQL query. Do not add any explanation.
@@ -130,8 +160,9 @@ Your response must contain ONLY the SQL query. Do not add any explanation.
130
  # --- 4. 創建 Gradio Web 界面 ---
131
  print("--- [5/5] 正在創建 Gradio Web 界面... ---")
132
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
133
- # (此部分無需修改,保持原樣)
134
  gr.Markdown("# 智能 Text-to-SQL 系統 (混合模式)")
 
135
  gr.Markdown("輸入您的自然語言問題,系統將首先嘗試從知識庫中快速檢索答案。如果問題較新穎,則會調用雲端大語言模型生成SQL。")
136
  with gr.Row():
137
  question_input = gr.Textbox(label="輸入您的問題", placeholder="例如:去年Nike的總業績是多少?", scale=4)
 
 
 
 
1
  import gradio as gr
2
  import requests
3
  import json
 
16
  print("--- [1/5] 開始初始化應用 ---")
17
 
18
  # --- 1. 載入知識庫 ---
19
+ qa_dataset = None
20
+ schema_data = {}
21
  try:
22
  print(f"--- [2/5] 正在從 '{DATASET_REPO_ID}' 載入知識庫... ---")
23
+ raw_dataset = load_dataset(DATASET_REPO_ID, token=HF_TOKEN)['train']
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
 
25
+ # *** 關鍵修正:智能解析 Dataset ***
26
+ # 檢查第一條數據的結構來判斷格式
27
+ if raw_dataset and len(raw_dataset) > 0:
28
+ first_item = raw_dataset[0]
29
+ if 'text' in first_item and 'question' not in first_item:
30
+ # 這是舊的 {'text': '...'} 格式,需要解析
31
+ print("--- > 檢測到 'text' 格式,正在解析JSON...")
32
+ parsed_qa_data = []
33
+ for item in raw_dataset:
34
+ try:
35
+ line_dict = json.loads(item['text'])
36
+ parsed_qa_data.append(line_dict)
37
+ except (json.JSONDecodeError, KeyError):
38
+ continue # 跳過錯誤行
39
+ qa_dataset = Dataset.from_list(parsed_qa_data)
40
+ elif 'question' in first_item and 'sql' in first_item:
41
+ # 這已經是正確的 {'question': ..., 'sql': ...} 格式
42
+ print("--- > 檢測到已解析的 'question'/'sql' 格式,直接使用。")
43
+ qa_dataset = raw_dataset
44
+ else:
45
+ raise ValueError(f"未知的Dataset格式: {first_item}")
46
+ else:
47
+ # 數據集為空
48
+ raise ValueError("載入的Dataset為空。")
49
+
50
  # 載入並解析 Schema JSON
51
  schema_file_path = "sqlite_schema_FULL.json"
52
  hf_hub_download(repo_id=DATASET_REPO_ID, filename=schema_file_path, repo_type='dataset', local_dir='.', token=HF_TOKEN)
 
54
  with open(schema_file_path, 'r', encoding='utf-8') as f:
55
  schema_data = json.load(f)
56
 
57
+ print(f"--- > 成功載入 {len(qa_dataset)} 條問答範例和 Schema。 ---")
58
+
59
  except Exception as e:
60
  print(f"!!! 致命錯誤: 無法載入或解析 Dataset '{DATASET_REPO_ID}'.")
61
  print(f"詳細錯誤: {e}")
62
  qa_dataset = Dataset.from_dict({"question": ["示例問題"], "sql": ["SELECT 'Dataset failed to load'"]})
 
63
 
64
  # --- 2. 構建 DDL 和初始化檢索模型 ---
65
  def load_schema_as_ddl(schema_dict: dict) -> str:
66
+ # (此函式無需修改)
67
  ddl_string = ""
68
  for table_name, columns in schema_dict.items():
69
  if not isinstance(columns, list): continue
 
77
  print("--- [3/5] 正在載入句向量模型 (all-MiniLM-L6-v2)... ---")
78
  embedder = SentenceTransformer('all-MiniLM-L6-v2', device='cpu')
79
 
 
80
  questions = [item['question'] for item in qa_dataset]
81
  sql_answers = [item['sql'] for item in qa_dataset]
82
 
83
+ # 只有在 questions 列表不為空時才進行計算
84
+ if questions:
85
+ print(f"--- [4/5] 正在為 {len(questions)} 個問題計算向量... ---")
86
+ question_embeddings = embedder.encode(questions, convert_to_tensor=True, show_progress_bar=True)
87
+ print("--- > 向量計算完成! ---")
88
+ else:
89
+ print("--- [4/5] 警告:沒有可用的問題來計算向量。檢索功能將不可用。---")
90
+ question_embeddings = torch.Tensor([])
91
+
92
 
93
  # --- 3. 混合系統核心邏輯 ---
94
  def get_sql_query(user_question: str):
95
+ # (此函式剩餘部分幾乎無需修改)
96
  if not user_question:
97
  return "請輸入您的問題。", "日誌:用戶未輸入問題。"
98
+
99
+ # 增加一個檢查,確保知識庫不是空的
100
+ if len(questions) == 0:
101
+ log_message = "錯誤:知識庫為空,無法進行檢索。"
102
+ return "系統錯誤:知識庫未成功載入。", log_message
103
+
104
  question_embedding = embedder.encode(user_question, convert_to_tensor=True)
105
  hits = util.semantic_search(question_embedding, question_embeddings, top_k=5)
106
+
107
+ if not hits or not hits[0]:
108
+ log_message = "檢索失敗:找不到任何相似的問題。"
109
+ # 即使檢索失敗,也應該嘗試調用 LLM
110
+ else:
111
+ hits = hits[0]
112
+ most_similar_hit = hits[0]
113
+ similarity_score = most_similar_hit['score']
114
+ log_message = f"檢索到最相似問題: '{questions[most_similar_hit['corpus_id']]}' (相似度: {similarity_score:.4f})"
115
+
116
+ if similarity_score > SIMILARITY_THRESHOLD:
117
+ sql_result = sql_answers[most_similar_hit['corpus_id']]
118
+ log_message += f"\n相似度 > {SIMILARITY_THRESHOLD},[模式: 直接返回]。"
119
+ return sql_result, log_message
120
+
121
+ log_message += f"\n相似度低於閾值或檢索失敗,[模式: LLM生成]。正在構建 Prompt..."
122
  examples_context = ""
123
+ if hits: # 只有在檢索到結果時才添加範例
124
+ for hit in hits[:3]:
125
+ examples_context += f"### A user asks: {questions[hit['corpus_id']]}\n{sql_answers[hit['corpus_id']]}\n\n"
126
+
127
  prompt = f"""### Task
128
  Generate a SQLite SQL query that answers the following user question.
129
  Your response must contain ONLY the SQL query. Do not add any explanation.
 
160
  # --- 4. 創建 Gradio Web 界面 ---
161
  print("--- [5/5] 正在創建 Gradio Web 界面... ---")
162
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
163
+ # (此部分無需修改)
164
  gr.Markdown("# 智能 Text-to-SQL 系統 (混合模式)")
165
+ # ... (Gradio界面代碼與之前相同)
166
  gr.Markdown("輸入您的自然語言問題,系統將首先嘗試從知識庫中快速檢索答案。如果問題較新穎,則會調用雲端大語言模型生成SQL。")
167
  with gr.Row():
168
  question_input = gr.Textbox(label="輸入您的問題", placeholder="例如:去年Nike的總業績是多少?", scale=4)