Spaces:
Running
on
T4
Running
on
T4
fix
Browse files- app.py +233 -139
- llm_handler.py +26 -264
- retrieval.py +0 -579
- retrieval_handler.py +82 -0
- utils.py +4 -36
app.py
CHANGED
@@ -1,144 +1,238 @@
|
|
1 |
-
|
2 |
-
|
3 |
-
|
4 |
-
|
5 |
-
|
6 |
-
|
7 |
-
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
from
|
|
|
|
|
|
|
14 |
import faiss
|
|
|
15 |
from rank_bm25 import BM25Okapi
|
16 |
-
import
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
llm_model,
|
79 |
-
model_name=
|
80 |
-
max_seq_length=2048,
|
81 |
-
dtype=None, # Unsloth sẽ tự động chọn
|
82 |
-
load_in_4bit=True, # Sử dụng 4-bit quantization
|
83 |
)
|
84 |
-
FastLanguageModel.for_inference(llm_model)
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
|
99 |
-
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
|
120 |
-
|
121 |
-
|
122 |
-
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
|
129 |
-
|
130 |
-
|
131 |
-
|
132 |
-
|
133 |
-
|
134 |
-
|
135 |
-
|
136 |
-
|
137 |
-
|
138 |
-
|
139 |
-
|
140 |
-
|
141 |
-
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
142 |
|
143 |
if __name__ == "__main__":
|
144 |
-
demo.launch()
|
|
|
1 |
+
# app.py
|
2 |
+
# Phiên bản triển khai cuối cùng, tải các mô hình từ Hub và các tài sản dữ liệu đã xử lý trước.
|
3 |
+
|
4 |
+
import os
|
5 |
+
import sys
|
6 |
+
import json
|
7 |
+
import re
|
8 |
+
import pickle
|
9 |
+
from collections import defaultdict
|
10 |
+
|
11 |
+
# Core ML/DL và Unsloth
|
12 |
+
import torch
|
13 |
+
from unsloth import FastLanguageModel
|
14 |
+
from transformers import TextStreamer
|
15 |
+
|
16 |
+
# RAG - Retrieval
|
17 |
import faiss
|
18 |
+
from sentence_transformers import SentenceTransformer
|
19 |
from rank_bm25 import BM25Okapi
|
20 |
+
import numpy as np
|
21 |
+
|
22 |
+
# Deployment
|
23 |
+
import gradio as gr
|
24 |
+
|
25 |
+
print("✅ Import thư viện thành công.")
|
26 |
+
|
27 |
+
# --- PHẦN 1: CẤU HÌNH VÀ ĐƯỜNG DẪN ---
|
28 |
+
|
29 |
+
# Tên các mô hình sẽ được tải từ Hub
|
30 |
+
EMBEDDING_MODEL_NAME = "bkai-foundation-models/vietnamese-bi-encoder"
|
31 |
+
LLM_MODEL_NAME = "unsloth/Llama-3.2-3B-Instruct-bnb-4bit"
|
32 |
+
|
33 |
+
# Đường dẫn đến các file bạn sẽ upload lên Space
|
34 |
+
# Tạo một thư mục 'data' trong Space để chứa chúng cho gọn gàng
|
35 |
+
RAW_LAW_DATA_FILE = "data/luat_chi_tiet_output_openai_sdk_final_cleaned.json"
|
36 |
+
FAISS_INDEX_FILE = "data/my_law_faiss_flatip_normalized.index"
|
37 |
+
|
38 |
+
# Tên các file sẽ được tạo ra trong quá trình chạy (nếu chưa có)
|
39 |
+
PROCESSED_CHUNKS_FILE = "processed_chunks.json"
|
40 |
+
BM25_MODEL_FILE = "bm25_model.pkl"
|
41 |
+
|
42 |
+
# Biến toàn cục để lưu trữ tài nguyên
|
43 |
+
APP_RESOURCES = {}
|
44 |
+
|
45 |
+
# --- PHẦN 2: CÁC HÀM TIỆN ÍCH VÀ XỬ LÝ DỮ LIỆU ---
|
46 |
+
|
47 |
+
def process_law_data_to_chunks(structured_data):
|
48 |
+
"""Làm phẳng d��� liệu luật có cấu trúc thành danh sách các chunks."""
|
49 |
+
flat_list = []
|
50 |
+
articles = [structured_data] if isinstance(structured_data, dict) else structured_data
|
51 |
+
for article_data in articles:
|
52 |
+
if not isinstance(article_data, dict): continue
|
53 |
+
clauses = article_data.get("clauses", [])
|
54 |
+
for clause in clauses:
|
55 |
+
points = clause.get("points_in_clause", [])
|
56 |
+
if points:
|
57 |
+
for point in points:
|
58 |
+
text = point.get("point_text_original")
|
59 |
+
if text:
|
60 |
+
flat_list.append({"text": text, "metadata": {"article": article_data.get("article"), "clause": clause.get("clause_number"), "point": point.get("point_id")}})
|
61 |
+
else:
|
62 |
+
text = clause.get("clause_text_original")
|
63 |
+
if text:
|
64 |
+
flat_list.append({"text": text, "metadata": {"article": article_data.get("article"), "clause": clause.get("clause_number")}})
|
65 |
+
return flat_list
|
66 |
+
|
67 |
+
def tokenize_vi_simple(text):
|
68 |
+
"""Tokenize tiếng Việt đơn giản."""
|
69 |
+
text = text.lower()
|
70 |
+
text = re.sub(r'[^\w\s]', '', text)
|
71 |
+
return text.split()
|
72 |
+
|
73 |
+
# --- PHẦN 3: LOGIC CỐT LÕI CỦA ỨNG DỤNG ---
|
74 |
+
|
75 |
+
def load_app_resources():
|
76 |
+
"""Tải hoặc tạo tất cả các tài nguyên cần thiết cho ứng dụng."""
|
77 |
+
print("--- Bắt đầu quá trình tải tài nguyên ---")
|
78 |
+
|
79 |
+
# 1. Tải các mô hình AI từ Hub
|
80 |
+
print("1. Đang tải LLM và Embedding Model từ Hugging Face Hub...")
|
81 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
82 |
+
llm_model, tokenizer = FastLanguageModel.from_pretrained(
|
83 |
+
model_name=LLM_MODEL_NAME, max_seq_length=2048, dtype=None, load_in_4bit=True
|
|
|
|
|
|
|
84 |
)
|
85 |
+
FastLanguageModel.for_inference(llm_model)
|
86 |
+
embedding_model = SentenceTransformer(EMBEDDING_MODEL_NAME, device=device)
|
87 |
+
APP_RESOURCES['llm_model'] = llm_model
|
88 |
+
APP_RESOURCES['tokenizer'] = tokenizer
|
89 |
+
APP_RESOURCES['embedding_model'] = embedding_model
|
90 |
+
print("✅ Tải mô hình AI thành công.")
|
91 |
+
|
92 |
+
# 2. Tải và xử lý dữ liệu luật từ file JSON bạn cung cấp
|
93 |
+
print(f"2. Đang tải và xử lý dữ liệu từ '{RAW_LAW_DATA_FILE}'...")
|
94 |
+
if not os.path.exists(RAW_LAW_DATA_FILE):
|
95 |
+
raise FileNotFoundError(f"Không tìm thấy file dữ liệu luật: '{RAW_LAW_DATA_FILE}'. Vui lòng tạo thư mục 'data' và upload file này lên Space.")
|
96 |
+
with open(RAW_LAW_DATA_FILE, 'r', encoding='utf-8') as f:
|
97 |
+
raw_data = json.load(f)
|
98 |
+
chunks_data = process_law_data_to_chunks(raw_data)
|
99 |
+
APP_RESOURCES['chunks_data'] = chunks_data
|
100 |
+
print(f"✅ Đã xử lý thành {len(chunks_data)} chunks dữ liệu.")
|
101 |
+
|
102 |
+
# 3. Tải FAISS Index đã được tạo sẵn
|
103 |
+
print(f"3. Đang tải FAISS index từ '{FAISS_INDEX_FILE}'...")
|
104 |
+
if not os.path.exists(FAISS_INDEX_FILE):
|
105 |
+
raise FileNotFoundError(f"Không tìm thấy file FAISS index: '{FAISS_INDEX_FILE}'. Vui lòng upload file này.")
|
106 |
+
faiss_index = faiss.read_index(FAISS_INDEX_FILE)
|
107 |
+
APP_RESOURCES['faiss_index'] = faiss_index
|
108 |
+
print(f"✅ Đã tải FAISS Index với {faiss_index.ntotal} vectors.")
|
109 |
+
|
110 |
+
# 4. Tải hoặc tạo BM25 Model (bước này nhanh nên có thể tạo on-the-fly)
|
111 |
+
if os.path.exists(BM25_MODEL_FILE):
|
112 |
+
print(f"4. Đang tải BM25 model từ '{BM25_MODEL_FILE}'...")
|
113 |
+
with open(BM25_MODEL_FILE, 'rb') as f:
|
114 |
+
bm25_model = pickle.load(f)
|
115 |
+
else:
|
116 |
+
print("4. Không tìm thấy BM25 model. Đang tạo mới...")
|
117 |
+
tokenized_corpus = [tokenize_vi_simple(c['text']) for c in chunks_data]
|
118 |
+
bm25_model = BM25Okapi(tokenized_corpus)
|
119 |
+
with open(BM25_MODEL_FILE, 'wb') as f:
|
120 |
+
pickle.dump(bm25_model, f)
|
121 |
+
print(f"✅ Đã tạo và lưu BM25 model vào '{BM25_MODEL_FILE}'.")
|
122 |
+
APP_RESOURCES['bm25_model'] = bm25_model
|
123 |
+
|
124 |
+
print("\n--- Tải tài nguyên hoàn tất! Ứng dụng đã sẵn sàng. ---")
|
125 |
+
|
126 |
+
def search_relevant_laws(query_text, k=5):
|
127 |
+
"""Thực hiện Hybrid Search."""
|
128 |
+
# (Hàm này giữ nguyên như trước, không cần thay đổi)
|
129 |
+
rrf_k_constant = 60
|
130 |
+
embedding_model = APP_RESOURCES['embedding_model']
|
131 |
+
faiss_index = APP_RESOURCES['faiss_index']
|
132 |
+
chunks_data = APP_RESOURCES['chunks_data']
|
133 |
+
bm25_model = APP_RESOURCES['bm25_model']
|
134 |
+
|
135 |
+
query_embedding = embedding_model.encode([query_text], convert_to_tensor=True)
|
136 |
+
query_embedding_np = query_embedding.cpu().numpy().astype('float32')
|
137 |
+
faiss.normalize_L2(query_embedding_np)
|
138 |
+
num_candidates = min(k * 10, faiss_index.ntotal)
|
139 |
+
_, semantic_indices = faiss_index.search(query_embedding_np, num_candidates)
|
140 |
+
|
141 |
+
tokenized_query = tokenize_vi_simple(query_text)
|
142 |
+
bm25_scores = bm25_model.get_scores(tokenized_query)
|
143 |
+
bm25_results = sorted(enumerate(bm25_scores), key=lambda x: x[1], reverse=True)[:num_candidates]
|
144 |
+
|
145 |
+
rrf_scores = defaultdict(float)
|
146 |
+
if semantic_indices.size > 0:
|
147 |
+
for rank, doc_idx in enumerate(semantic_indices[0]):
|
148 |
+
if doc_idx != -1: rrf_scores[doc_idx] += 1.0 / (rrf_k_constant + rank)
|
149 |
+
for rank, (doc_idx, score) in enumerate(bm25_results):
|
150 |
+
if score > 0: rrf_scores[doc_idx] += 1.0 / (rrf_k_constant + rank)
|
151 |
+
|
152 |
+
fused_results = sorted(rrf_scores.items(), key=lambda x: x[1], reverse=True)
|
153 |
+
|
154 |
+
final_results = []
|
155 |
+
for doc_idx, score in fused_results[:k]:
|
156 |
+
result = chunks_data[doc_idx].copy()
|
157 |
+
result['retrieval_score'] = score
|
158 |
+
final_results.append(result)
|
159 |
+
|
160 |
+
return final_results
|
161 |
+
|
162 |
+
def generate_llm_response(query, context):
|
163 |
+
"""Sinh câu trả lời từ LLM."""
|
164 |
+
# (Hàm này giữ nguyên như trước, không cần thay đổi)
|
165 |
+
llm_model = APP_RESOURCES['llm_model']
|
166 |
+
tokenizer = APP_RESOURCES['tokenizer']
|
167 |
+
prompt = f"""Bạn là một trợ lý AI chuyên tư vấn về luật giao thông đường bộ Việt Nam. Dựa vào các thông tin luật được cung cấp dưới đây để trả lời câu hỏi của người dùng một cách chính xác và chi tiết.
|
168 |
+
|
169 |
+
### Thông tin luật được trích dẫn:
|
170 |
+
{context}
|
171 |
+
|
172 |
+
### Câu hỏi của người dùng:
|
173 |
+
{query}
|
174 |
+
|
175 |
+
### Trả lời của bạn:"""
|
176 |
+
inputs = tokenizer(prompt, return_tensors="pt").to(llm_model.device)
|
177 |
+
output_ids = llm_model.generate(**inputs, max_new_tokens=512, temperature=0.3, do_sample=True, pad_token_id=tokenizer.eos_token_id)
|
178 |
+
response_text = tokenizer.decode(output_ids[0][inputs.input_ids.shape[1]:], skip_special_tokens=True).strip()
|
179 |
+
return response_text
|
180 |
+
|
181 |
+
# --- PHẦN 4: CÁC HÀM GIAO TIẾP VỚI GRADIO ---
|
182 |
+
|
183 |
+
def retriever_interface(query):
|
184 |
+
"""Giao tiếp với Tab 1: Chỉ tìm kiếm."""
|
185 |
+
retrieved_results = search_relevant_laws(query)
|
186 |
+
if not retrieved_results: return "Không tìm thấy điều luật nào liên quan."
|
187 |
+
|
188 |
+
output_md = "### Các điều luật liên quan nhất:\n\n"
|
189 |
+
for i, res in enumerate(retrieved_results):
|
190 |
+
meta = res.get('metadata', {})
|
191 |
+
text = res.get('text', 'N/A')
|
192 |
+
output_md += f"**{i+1}. {meta.get('article', 'N/A')} | {meta.get('clause', 'N/A')} | {meta.get('point', 'N/A')}**\n"
|
193 |
+
output_md += f"> {text}\n\n---\n\n"
|
194 |
+
return output_md
|
195 |
+
|
196 |
+
def rag_interface(query, progress=gr.Progress()):
|
197 |
+
"""Giao tiếp với Tab 2: RAG hoàn chỉnh."""
|
198 |
+
progress(0.2, desc="Đang tìm kiếm ngữ cảnh...")
|
199 |
+
retrieved_results = search_relevant_laws(query)
|
200 |
+
|
201 |
+
if not retrieved_results:
|
202 |
+
context_for_llm = "Không tìm thấy thông tin luật liên quan."
|
203 |
+
context_for_display = "Không tìm thấy điều luật nào liên quan để tạo câu trả lời."
|
204 |
+
else:
|
205 |
+
context_for_llm = "\n\n---\n\n".join([r['text'] for r in retrieved_results])
|
206 |
+
context_for_display = retriever_interface(query)
|
207 |
+
|
208 |
+
progress(0.7, desc="Đang sinh câu trả lời...")
|
209 |
+
final_answer = generate_llm_response(query, context_for_llm)
|
210 |
+
progress(1, desc="Hoàn tất!")
|
211 |
+
return final_answer, context_for_display
|
212 |
+
|
213 |
+
# --- PHẦN 5: KHỞI CHẠY ỨNG DỤNG ---
|
214 |
+
|
215 |
+
# Tải tài nguyên một lần duy nhất
|
216 |
+
load_app_resources()
|
217 |
+
|
218 |
+
# Xây dựng giao diện
|
219 |
+
with gr.Blocks(theme=gr.themes.Soft(), title="Chatbot Luật GTĐB") as demo:
|
220 |
+
gr.Markdown("# ⚖️ Chatbot Luật Giao thông Đường bộ Việt Nam (RAG)")
|
221 |
+
with gr.Tabs():
|
222 |
+
with gr.TabItem("Tìm kiếm Điều luật (Retriever)"):
|
223 |
+
retriever_query = gr.Textbox(label="Nhập nội dung tìm kiếm", placeholder="Vd: Vượt đèn đỏ")
|
224 |
+
retriever_button = gr.Button("Tìm kiếm", variant="secondary")
|
225 |
+
retriever_output = gr.Markdown(label="Các điều luật liên quan")
|
226 |
+
|
227 |
+
with gr.TabItem("Hỏi-Đáp (RAG)"):
|
228 |
+
rag_query = gr.Textbox(label="Nhập câu hỏi", placeholder="Vd: Vượt đèn đỏ phạt bao nhiêu tiền?")
|
229 |
+
rag_button = gr.Button("Gửi", variant="primary")
|
230 |
+
rag_answer = gr.Textbox(label="Câu trả lời", interactive=False, lines=7)
|
231 |
+
with gr.Accordion("Xem ngữ cảnh đã sử dụng", open=False):
|
232 |
+
rag_context = gr.Markdown()
|
233 |
+
|
234 |
+
retriever_button.click(fn=retriever_interface, inputs=retriever_query, outputs=retriever_output)
|
235 |
+
rag_button.click(fn=rag_interface, inputs=rag_query, outputs=[rag_answer, rag_context])
|
236 |
|
237 |
if __name__ == "__main__":
|
238 |
+
demo.launch()
|
llm_handler.py
CHANGED
@@ -1,194 +1,28 @@
|
|
1 |
# llm_handler.py
|
|
|
2 |
|
3 |
import torch
|
4 |
-
import re
|
5 |
-
import json
|
6 |
from unsloth import FastLanguageModel
|
7 |
-
# from transformers import TextStreamer # Bỏ comment nếu bạn muốn dùng TextStreamer để stream token
|
8 |
|
9 |
-
#
|
10 |
-
|
11 |
-
# from retrieval import search_relevant_laws
|
12 |
-
# Hoặc nếu bạn muốn hàm này độc lập hơn, bạn có thể truyền retrieved_results vào generate_response
|
13 |
-
# thay vì truyền tất cả các thành phần của RAG.
|
14 |
-
# Tuy nhiên, dựa theo code gốc, generate_response gọi search_relevant_laws.
|
15 |
-
|
16 |
-
# --- HÀM TẢI MÔ HÌNH LLM VÀ TOKENIZER ---
|
17 |
-
def load_llm_model_and_tokenizer(
|
18 |
-
model_name_or_path: str,
|
19 |
-
max_seq_length: int = 2048,
|
20 |
-
load_in_4bit: bool = True,
|
21 |
-
device_map: str = "auto" # Cho phép Unsloth tự quyết định device map
|
22 |
-
):
|
23 |
-
"""
|
24 |
-
Tải mô hình ngôn ngữ lớn (LLM) đã được fine-tune bằng Unsloth và tokenizer tương ứng.
|
25 |
-
|
26 |
-
Args:
|
27 |
-
model_name_or_path (str): Tên hoặc đường dẫn đến mô hình đã fine-tune.
|
28 |
-
max_seq_length (int): Độ dài chuỗi tối đa mà mô hình hỗ trợ.
|
29 |
-
load_in_4bit (bool): Có tải mô hình ở dạng 4-bit quantization hay không.
|
30 |
-
device_map (str): Cách map model lên các device (ví dụ "auto", "cuda:0").
|
31 |
-
|
32 |
-
Returns:
|
33 |
-
tuple: (model, tokenizer) nếu thành công, (None, None) nếu có lỗi.
|
34 |
-
"""
|
35 |
-
print(f"Đang tải LLM model: {model_name_or_path}...")
|
36 |
-
try:
|
37 |
-
model, tokenizer = FastLanguageModel.from_pretrained(
|
38 |
-
model_name=model_name_or_path,
|
39 |
-
max_seq_length=max_seq_length,
|
40 |
-
dtype=None, # Unsloth sẽ tự động chọn dtype tối ưu
|
41 |
-
load_in_4bit=load_in_4bit,
|
42 |
-
device_map=device_map, # Thêm device_map
|
43 |
-
# token = "hf_YOUR_TOKEN_HERE" # Nếu model là private trên Hugging Face Hub
|
44 |
-
)
|
45 |
-
FastLanguageModel.for_inference(model) # Tối ưu hóa mô hình cho inference
|
46 |
-
print("Tải LLM model và tokenizer thành công.")
|
47 |
-
return model, tokenizer
|
48 |
-
except Exception as e:
|
49 |
-
print(f"Lỗi khi tải LLM model và tokenizer: {e}")
|
50 |
-
return None, None
|
51 |
-
|
52 |
-
# --- HÀM TẠO CÂU TRẢ LỜI TỪ LLM ---
|
53 |
-
def generate_response(
|
54 |
query: str,
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
# Các tham số cho search_relevant_laws
|
63 |
-
search_k: int = 5,
|
64 |
-
search_multiplier: int = 10, # initial_k_multiplier
|
65 |
-
rrf_k_constant: int = 60,
|
66 |
-
# Các tham số cho generation của LLM
|
67 |
-
max_new_tokens: int = 768, # Tăng lên một chút cho câu trả lời đầy đủ hơn
|
68 |
-
temperature: float = 0.4, # Giảm một chút để câu trả lời bớt ngẫu nhiên, tập trung hơn
|
69 |
-
top_p: float = 0.9, # Giữ nguyên hoặc giảm nhẹ
|
70 |
-
top_k: int = 40,
|
71 |
-
repetition_penalty: float = 1.15, # Tăng nhẹ để tránh lặp từ
|
72 |
-
# Tham số để import hàm search_relevant_laws
|
73 |
-
search_function # Đây là hàm search_relevant_laws được truyền vào
|
74 |
-
):
|
75 |
"""
|
76 |
-
|
77 |
-
và tạo câu trả lời từ LLM dựa trên ngữ cảnh đó.
|
78 |
-
|
79 |
-
Args:
|
80 |
-
query (str): Câu truy vấn của người dùng.
|
81 |
-
llama_model: Mô hình LLM đã tải.
|
82 |
-
tokenizer: Tokenizer tương ứng.
|
83 |
-
faiss_index: FAISS index đã tải.
|
84 |
-
embed_model: Mô hình embedding đã tải.
|
85 |
-
chunks_data_list (list): Danh sách các chunk dữ liệu luật.
|
86 |
-
bm25_model: Mô hình BM25 đã tạo.
|
87 |
-
search_k (int): Số lượng kết quả cuối cùng muốn lấy từ hàm search.
|
88 |
-
search_multiplier (int): Hệ số initial_k_multiplier cho hàm search.
|
89 |
-
rrf_k_constant (int): Hằng số k cho RRF trong hàm search.
|
90 |
-
max_new_tokens (int): Số token tối đa được tạo mới bởi LLM.
|
91 |
-
temperature (float): Nhiệt độ cho việc sinh văn bản.
|
92 |
-
top_p (float): Tham số top-p cho nucleus sampling.
|
93 |
-
top_k (int): Tham số top-k.
|
94 |
-
repetition_penalty (float): Phạt cho việc lặp từ.
|
95 |
-
search_function: Hàm thực hiện tìm kiếm (ví dụ: retrieval.search_relevant_laws).
|
96 |
-
|
97 |
-
Returns:
|
98 |
-
str: Câu trả lời được tạo ra bởi LLM.
|
99 |
"""
|
100 |
-
print(
|
101 |
-
|
102 |
-
#
|
103 |
-
print("--- [LLM Handler] Bước 1: Truy xuất ngữ cảnh (Hybrid Search)... ---")
|
104 |
-
try:
|
105 |
-
retrieved_results = search_function(
|
106 |
-
query_text=query,
|
107 |
-
embedding_model=embed_model,
|
108 |
-
faiss_index=faiss_index,
|
109 |
-
chunks_data=chunks_data_list,
|
110 |
-
bm25_model=bm25_model,
|
111 |
-
k=search_k,
|
112 |
-
initial_k_multiplier=search_multiplier,
|
113 |
-
rrf_k_constant=rrf_k_constant
|
114 |
-
# Các tham số boost có thể lấy giá trị mặc định trong search_function
|
115 |
-
# hoặc truyền vào đây nếu muốn tùy chỉnh sâu hơn từ app.py
|
116 |
-
)
|
117 |
-
print(f"--- [LLM Handler] Truy xuất xong, số kết quả: {len(retrieved_results)} ---")
|
118 |
-
if not retrieved_results:
|
119 |
-
print("--- [LLM Handler] Không tìm thấy ngữ cảnh nào. ---")
|
120 |
-
except Exception as e:
|
121 |
-
print(f"Lỗi trong quá trình truy xuất ngữ cảnh: {e}")
|
122 |
-
retrieved_results = [] # Xử lý lỗi bằng cách trả về danh sách rỗng
|
123 |
-
|
124 |
-
# === 2. Định dạng Context từ retrieved_results ===
|
125 |
-
print("--- [LLM Handler] Bước 2: Định dạng context cho LLM... ---")
|
126 |
-
context_parts = []
|
127 |
-
if not retrieved_results:
|
128 |
-
context = "Không tìm thấy thông tin luật liên quan trong cơ sở dữ liệu để trả lời câu hỏi này."
|
129 |
-
else:
|
130 |
-
for i, res in enumerate(retrieved_results):
|
131 |
-
metadata = res.get('metadata', {})
|
132 |
-
article_title = metadata.get('article_title', 'N/A') # Lấy tiêu đề Điều
|
133 |
-
article = metadata.get('article', 'N/A')
|
134 |
-
clause = metadata.get('clause_number', 'N/A') # Sửa key cho khớp với process_law_data_to_chunks
|
135 |
-
point = metadata.get('point_id', '')
|
136 |
-
source = metadata.get('source_document', 'N/A')
|
137 |
-
text_content = res.get('text', '*Nội dung không có*')
|
138 |
-
|
139 |
-
# Header rõ ràng cho mỗi nguồn
|
140 |
-
header_parts = [f"Trích dẫn {i+1}:"]
|
141 |
-
if source != 'N/A':
|
142 |
-
header_parts.append(f"(Nguồn: {source})")
|
143 |
-
if article != 'N/A':
|
144 |
-
header_parts.append(f"Điều {article}")
|
145 |
-
if article_title != 'N/A' and article_title != article: # Chỉ thêm tiêu đề nếu khác số điều
|
146 |
-
header_parts.append(f"({article_title})")
|
147 |
-
if clause != 'N/A':
|
148 |
-
header_parts.append(f", Khoản {clause}")
|
149 |
-
if point: # point_id có thể là None hoặc rỗng
|
150 |
-
header_parts.append(f", Điểm {point}")
|
151 |
-
|
152 |
-
header = " ".join(header_parts)
|
153 |
-
|
154 |
-
# Bổ sung thông tin phạt/điểm vào header nếu query có đề cập
|
155 |
-
# và metadata của chunk có thông tin đó (lấy từ logic boosting của search_relevant_laws)
|
156 |
-
query_analysis = metadata.get("query_analysis_for_boost", {}) # Giả sử search_relevant_laws có thể trả về
|
157 |
-
# Hoặc phân tích lại query ở đây (ít hiệu quả hơn)
|
158 |
-
mentions_fine_in_query = bool(re.search(r'tiền|phạt|bao nhiêu đồng|mức phạt', query.lower()))
|
159 |
-
mentions_points_in_query = bool(re.search(r'điểm|trừ điểm|bằng lái|gplx', query.lower()))
|
160 |
-
|
161 |
-
fine_info_text = []
|
162 |
-
if metadata.get("has_fine") and mentions_fine_in_query:
|
163 |
-
if metadata.get("individual_fine_min") is not None and metadata.get("individual_fine_max") is not None:
|
164 |
-
fine_info_text.append(f"Phạt tiền: {metadata.get('individual_fine_min'):,} - {metadata.get('individual_fine_max'):,} VND.")
|
165 |
-
elif metadata.get("overall_fine_note_for_clause_text"):
|
166 |
-
fine_info_text.append(f"Ghi chú phạt tiền: {metadata.get('overall_fine_note_for_clause_text')}")
|
167 |
-
|
168 |
-
points_info_text = []
|
169 |
-
if metadata.get("has_points_deduction") and mentions_points_in_query:
|
170 |
-
if metadata.get("points_deducted_values_str"):
|
171 |
-
points_info_text.append(f"Trừ điểm: {metadata.get('points_deducted_values_str')} điểm.")
|
172 |
-
elif metadata.get("overall_points_deduction_note_for_clause_text"):
|
173 |
-
points_info_text.append(f"Ghi chú trừ điểm: {metadata.get('overall_points_deduction_note_for_clause_text')}")
|
174 |
-
|
175 |
-
|
176 |
-
penalty_summary = ""
|
177 |
-
if fine_info_text or points_info_text:
|
178 |
-
penalty_summary = " (Liên quan: " + " ".join(fine_info_text + points_info_text) + ")"
|
179 |
-
|
180 |
-
context_parts.append(f"{header}{penalty_summary}\nNội dung: {text_content}")
|
181 |
-
|
182 |
-
context = "\n\n---\n\n".join(context_parts)
|
183 |
-
# print("\n--- [LLM Handler] Context đã định dạng ---\n", context[:1000] + "...") # Xem trước context
|
184 |
-
|
185 |
-
# === 3. Xây dựng Prompt ===
|
186 |
-
# Sử dụng định dạng prompt mà mô hình của bạn được fine-tune (ví dụ: Alpaca)
|
187 |
-
# Dưới đây là một ví dụ, bạn có thể cần điều chỉnh cho phù hợp với `lora_model_base`
|
188 |
prompt = f"""Bạn là một trợ lý AI chuyên tư vấn về luật giao thông đường bộ Việt Nam.
|
189 |
-
|
190 |
-
Nếu thông tin không
|
191 |
-
Tránh đưa ra ý kiến cá nhân hoặc thông tin không có trong ngữ cảnh. Hãy trích dẫn điều, khoản, điểm nếu có thể.
|
192 |
|
193 |
### Thông tin luật được trích dẫn:
|
194 |
{context}
|
@@ -198,99 +32,27 @@ Tránh đưa ra ý kiến cá nhân hoặc thông tin không có trong ngữ c
|
|
198 |
|
199 |
### Trả lời của bạn:"""
|
200 |
|
201 |
-
#
|
202 |
-
|
203 |
-
|
204 |
-
print("--- [LLM Handler] Bước 3: Tạo câu trả lời từ LLM... ---")
|
205 |
-
device = llama_model.device # Lấy device từ model đã tải
|
206 |
-
inputs = tokenizer(prompt, return_tensors="pt").to(device) # Chuyển inputs lên cùng device với model
|
207 |
|
|
|
208 |
generation_config = dict(
|
209 |
max_new_tokens=max_new_tokens,
|
210 |
temperature=temperature,
|
211 |
top_p=top_p,
|
212 |
-
|
213 |
-
|
214 |
-
do_sample=True if temperature > 0 else False, # Chỉ sample khi temperature > 0
|
215 |
-
pad_token_id=tokenizer.eos_token_id, # Quan trọng cho batch generation và padding
|
216 |
-
eos_token_id=tokenizer.eos_token_id,
|
217 |
)
|
218 |
|
219 |
try:
|
220 |
-
|
221 |
-
# text_streamer = TextStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True)
|
222 |
-
# output_ids = llama_model.generate(**inputs, streamer=text_streamer, **generation_config)
|
223 |
-
# response_text = "" # TextStreamer sẽ in ra, không cần decode lại nếu chỉ để hiển thị
|
224 |
-
|
225 |
-
# Generate bình thường để trả về chuỗi hoàn chỉnh
|
226 |
-
output_ids = llama_model.generate(**inputs, **generation_config)
|
227 |
-
|
228 |
-
# Lấy phần token được tạo mới (sau prompt)
|
229 |
input_length = inputs.input_ids.shape[1]
|
230 |
generated_ids = output_ids[0][input_length:]
|
231 |
response_text = tokenizer.decode(generated_ids, skip_special_tokens=True).strip()
|
232 |
-
|
233 |
-
print("--- [LLM Handler] Tạo câu trả lời hoàn tất. ---")
|
234 |
-
# print(f"--- [LLM Handler] Response text: {response_text[:300]}...")
|
235 |
return response_text
|
236 |
-
|
237 |
except Exception as e:
|
238 |
-
print(f"Lỗi
|
239 |
-
return "Xin lỗi, đã có lỗi xảy ra trong quá trình tạo câu trả lời
|
240 |
-
|
241 |
-
|
242 |
-
# --- (Tùy chọn) Hàm main để test nhanh file này ---
|
243 |
-
if __name__ == '__main__':
|
244 |
-
# Phần này chỉ để test, bạn cần mock các đối tượng hoặc tải thật
|
245 |
-
print("Chạy test cho llm_handler.py (chưa có mock dữ liệu)...")
|
246 |
|
247 |
-
# # Ví dụ cách mock (bạn cần dữ liệu thật hoặc mock phức tạp hơn để chạy)
|
248 |
-
# mock_llm_model, mock_tokenizer = load_llm_model_and_tokenizer(
|
249 |
-
# "unsloth/Phi-3-mini-4k-instruct-bnb-4bit", # Thay bằng model bạn dùng hoặc một model nhỏ để test
|
250 |
-
# # model_name_or_path="path/to/your/lora_model_base" # Nếu test với model đã tải
|
251 |
-
# )
|
252 |
-
#
|
253 |
-
# if mock_llm_model and mock_tokenizer:
|
254 |
-
# # Mock các thành phần RAG
|
255 |
-
# class MockFAISSIndex:
|
256 |
-
# def __init__(self): self.ntotal = 0
|
257 |
-
# def search(self, query, k): return ([], []) # Trả về không có gì
|
258 |
-
#
|
259 |
-
# class MockEmbeddingModel:
|
260 |
-
# def encode(self, text, convert_to_tensor, device): return torch.randn(1, 10) # Vector dummy
|
261 |
-
#
|
262 |
-
# class MockBM25Model:
|
263 |
-
# def get_scores(self, query_tokens): return []
|
264 |
-
#
|
265 |
-
# def mock_search_relevant_laws(**kwargs):
|
266 |
-
# print(f"Mock search_relevant_laws called with query: {kwargs.get('query_text')}")
|
267 |
-
# # Trả về một vài kết quả giả để test formatting
|
268 |
-
# return [
|
269 |
-
# {
|
270 |
-
# "text": "Người điều khiển xe máy không đội mũ bảo hiểm sẽ bị phạt tiền.",
|
271 |
-
# "metadata": {
|
272 |
-
# "source_document": "Nghị định 100/2019/NĐ-CP",
|
273 |
-
# "article": "6", "clause_number": "2", "point_id": "i",
|
274 |
-
# "article_title": "Xử phạt người điều khiển xe mô tô, xe gắn máy",
|
275 |
-
# "has_fine": True, "individual_fine_min": 200000, "individual_fine_max": 300000,
|
276 |
-
# }
|
277 |
-
# }
|
278 |
-
# ]
|
279 |
-
#
|
280 |
-
# test_query = "Không đội mũ bảo hiểm xe máy phạt bao nhiêu?"
|
281 |
-
# response = generate_response(
|
282 |
-
# query=test_query,
|
283 |
-
# llama_model=mock_llm_model,
|
284 |
-
# tokenizer=mock_tokenizer,
|
285 |
-
# faiss_index=MockFAISSIndex(),
|
286 |
-
# embed_model=MockEmbeddingModel(),
|
287 |
-
# chunks_data_list=[{"text": "dummy chunk", "metadata": {}}],
|
288 |
-
# bm25_model=MockBM25Model(),
|
289 |
-
# search_function=mock_search_relevant_laws, # Truyền hàm mock
|
290 |
-
# search_k=1
|
291 |
-
# )
|
292 |
-
# print("\n--- Câu trả lời Test ---")
|
293 |
-
# print(response)
|
294 |
-
# else:
|
295 |
-
# print("Không thể tải mock LLM model để test.")
|
296 |
-
pass # Bỏ qua phần test nếu không có mock
|
|
|
1 |
# llm_handler.py
|
2 |
+
# Chịu trách nhiệm cho mọi logic liên quan đến mô hình ngôn ngữ lớn (LLM).
|
3 |
|
4 |
import torch
|
|
|
|
|
5 |
from unsloth import FastLanguageModel
|
|
|
6 |
|
7 |
+
# --- HÀM TẠO CÂU TRẢ LỜI ---
|
8 |
+
def generate_llm_response(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
9 |
query: str,
|
10 |
+
context: str,
|
11 |
+
llm_model,
|
12 |
+
tokenizer,
|
13 |
+
max_new_tokens: int = 512,
|
14 |
+
temperature: float = 0.3,
|
15 |
+
top_p: float = 0.9,
|
16 |
+
) -> str:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
17 |
"""
|
18 |
+
Sinh câu trả lời từ LLM dựa trên câu hỏi và ngữ cảnh đã được truy xuất.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
19 |
"""
|
20 |
+
print("🧠 Bắt đầu sinh câu trả lời từ LLM...")
|
21 |
+
|
22 |
+
# Xây dựng prompt
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
23 |
prompt = f"""Bạn là một trợ lý AI chuyên tư vấn về luật giao thông đường bộ Việt Nam.
|
24 |
+
Dựa vào các thông tin luật được cung cấp dưới đây để trả lời câu hỏi của người dùng một cách chính xác và chi tiết.
|
25 |
+
Nếu thông tin không đủ, hãy trả lời rằng bạn không tìm thấy thông tin cụ thể trong tài liệu.
|
|
|
26 |
|
27 |
### Thông tin luật được trích dẫn:
|
28 |
{context}
|
|
|
32 |
|
33 |
### Trả lời của bạn:"""
|
34 |
|
35 |
+
# Tạo input cho model
|
36 |
+
device = llm_model.device
|
37 |
+
inputs = tokenizer(prompt, return_tensors="pt").to(device)
|
|
|
|
|
|
|
38 |
|
39 |
+
# Cấu hình cho việc sinh văn bản
|
40 |
generation_config = dict(
|
41 |
max_new_tokens=max_new_tokens,
|
42 |
temperature=temperature,
|
43 |
top_p=top_p,
|
44 |
+
do_sample=True,
|
45 |
+
pad_token_id=tokenizer.eos_token_id
|
|
|
|
|
|
|
46 |
)
|
47 |
|
48 |
try:
|
49 |
+
output_ids = llm_model.generate(**inputs, **generation_config)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
50 |
input_length = inputs.input_ids.shape[1]
|
51 |
generated_ids = output_ids[0][input_length:]
|
52 |
response_text = tokenizer.decode(generated_ids, skip_special_tokens=True).strip()
|
53 |
+
print("✅ Sinh câu trả lời hoàn tất.")
|
|
|
|
|
54 |
return response_text
|
|
|
55 |
except Exception as e:
|
56 |
+
print(f"❌ Lỗi khi sinh câu trả lời từ LLM: {e}")
|
57 |
+
return "Xin lỗi, đã có lỗi xảy ra trong quá trình tạo câu trả lời."
|
|
|
|
|
|
|
|
|
|
|
|
|
58 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
retrieval.py
DELETED
@@ -1,579 +0,0 @@
|
|
1 |
-
# retrieval.py
|
2 |
-
|
3 |
-
import json
|
4 |
-
import re
|
5 |
-
import numpy as np
|
6 |
-
import faiss # Thư viện này cần được cài đặt (faiss-cpu hoặc faiss-gpu)
|
7 |
-
from collections import defaultdict
|
8 |
-
from typing import List, Dict, Any, Tuple, Optional, Callable
|
9 |
-
|
10 |
-
# --- 1. CÁC HẰNG SỐ VÀ MAP CHO LOẠI PHƯƠNG TIỆN ---
|
11 |
-
VEHICLE_TYPE_MAP: Dict[str, List[str]] = {
|
12 |
-
"xe máy": ["xe máy", "xe mô tô", "xe gắn máy", "xe máy điện", "mô tô hai bánh", "mô tô ba bánh"],
|
13 |
-
"ô tô": ["xe ô tô", "ô tô con", "ô tô tải", "ô tô khách", "xe con", "xe tải", "xe khách", "ô tô điện"],
|
14 |
-
"xe cơ giới": ["xe cơ giới"], # Loại chung hơn
|
15 |
-
"xe thô sơ": ["xe thô sơ", "xe đạp", "xích lô", "xe đạp điện"], # Thêm xe đạp điện vào xe thô sơ
|
16 |
-
"người đi bộ": ["người đi bộ"],
|
17 |
-
# Thêm các loại khác nếu cần, ví dụ "xe chuyên dùng" nếu muốn tách riêng
|
18 |
-
}
|
19 |
-
|
20 |
-
# --- 2. HÀM TIỆN ÍCH ---
|
21 |
-
|
22 |
-
def get_standardized_vehicle_type(text_input: Optional[str]) -> Optional[str]:
|
23 |
-
"""
|
24 |
-
Suy luận và chuẩn hóa loại phương tiện từ một chuỗi text.
|
25 |
-
Ưu tiên các loại cụ thể trước, sau đó đến các loại chung hơn.
|
26 |
-
"""
|
27 |
-
if not text_input or not isinstance(text_input, str):
|
28 |
-
return None
|
29 |
-
|
30 |
-
text_lower = text_input.lower()
|
31 |
-
|
32 |
-
# Ưu tiên kiểm tra "xe máy" và các biến thể trước "xe cơ giới"
|
33 |
-
# Cẩn thận với "xe máy chuyên dùng"
|
34 |
-
is_moto = any(re.search(r'\b' + re.escape(kw) + r'\b', text_lower) for kw in VEHICLE_TYPE_MAP["xe máy"])
|
35 |
-
if is_moto:
|
36 |
-
# Tránh trường hợp "xe máy chuyên dùng" bị tính là "xe máy"
|
37 |
-
# nếu "xe máy chuyên dùng" là một category riêng hoặc cần xử lý đặc biệt.
|
38 |
-
# Hiện tại, nếu có "chuyên dùng" và "xe máy", nó vẫn sẽ là "xe máy" nếu không có category "xe máy chuyên dùng".
|
39 |
-
if "chuyên dùng" in text_lower and "xe máy chuyên dùng" not in text_lower: # Logic này có thể cần review tùy theo định nghĩa
|
40 |
-
# Nếu bạn có category "xe máy chuyên dùng" trong VEHICLE_TYPE_MAP, nó sẽ được xử lý ở vòng lặp sau.
|
41 |
-
# Nếu không, "xe máy chuyên dùng" vẫn có thể bị coi là "xe máy".
|
42 |
-
pass # Để nó rơi xuống các kiểm tra khác nếu cần
|
43 |
-
else:
|
44 |
-
return "xe máy"
|
45 |
-
|
46 |
-
# Kiểm tra "ô tô" và các biến thể
|
47 |
-
is_car = any(re.search(r'\b' + re.escape(kw) + r'\b', text_lower) for kw in VEHICLE_TYPE_MAP["ô tô"])
|
48 |
-
if is_car:
|
49 |
-
return "ô tô"
|
50 |
-
|
51 |
-
# Kiểm tra các loại chung hơn hoặc khác
|
52 |
-
# Thứ tự này quan trọng nếu có sự chồng chéo (ví dụ: "xe cơ giới" bao gồm "ô tô", "xe máy")
|
53 |
-
# Đã xử lý ô tô, xe máy ở trên nên thứ tự ở đây ít quan trọng hơn giữa các loại còn lại.
|
54 |
-
for standard_type, keywords in VEHICLE_TYPE_MAP.items():
|
55 |
-
if standard_type in ["xe máy", "ô tô"]: # Đã xử lý ở trên
|
56 |
-
continue
|
57 |
-
if any(re.search(r'\b' + re.escape(kw) + r'\b', text_lower) for kw in keywords):
|
58 |
-
return standard_type
|
59 |
-
|
60 |
-
return None # Trả về None nếu không khớp rõ ràng
|
61 |
-
|
62 |
-
def tokenize_vi_for_bm25_setup(text: str) -> List[str]:
|
63 |
-
"""
|
64 |
-
Tokenize tiếng Việt đơn giản cho BM25: lowercase, loại bỏ dấu câu, split theo khoảng trắng.
|
65 |
-
"""
|
66 |
-
text = text.lower()
|
67 |
-
text = re.sub(r'[^\w\s]', '', text) # Loại bỏ các ký tự không phải chữ, số, hoặc khoảng trắng
|
68 |
-
return text.split()
|
69 |
-
|
70 |
-
# --- 3. HÀM XỬ LÝ DỮ LIỆU LUẬT TỪ JSON SANG CHUNKS ---
|
71 |
-
def process_law_data_to_chunks(structured_data_input: Any) -> List[Dict[str, Any]]:
|
72 |
-
"""
|
73 |
-
Xử lý dữ liệu luật có cấu trúc (từ JSON) thành một danh sách phẳng các "chunks".
|
74 |
-
Mỗi chunk bao gồm "text" và "metadata".
|
75 |
-
"""
|
76 |
-
flat_list: List[Dict[str, Any]] = []
|
77 |
-
|
78 |
-
if isinstance(structured_data_input, dict) and "article" in structured_data_input:
|
79 |
-
articles_list: List[Dict[str, Any]] = [structured_data_input]
|
80 |
-
elif isinstance(structured_data_input, list):
|
81 |
-
articles_list = structured_data_input
|
82 |
-
else:
|
83 |
-
print("Lỗi: Dữ liệu đầu vào không phải là danh sách các Điều luật hoặc một đối tượng Điều luật.")
|
84 |
-
return flat_list
|
85 |
-
|
86 |
-
for article_data in articles_list:
|
87 |
-
if not isinstance(article_data, dict):
|
88 |
-
# print(f"Cảnh báo: Bỏ qua mục không phải dict trong articles_list: {article_data}")
|
89 |
-
continue
|
90 |
-
|
91 |
-
raw_article_title = article_data.get("article_title", "")
|
92 |
-
article_metadata_base = {
|
93 |
-
"source_document": article_data.get("source_document"),
|
94 |
-
"article": article_data.get("article"), # Số điều, ví dụ "Điều 5"
|
95 |
-
"article_title": raw_article_title # Tiêu đề của Điều, ví dụ "Xử phạt người điều khiển..."
|
96 |
-
}
|
97 |
-
|
98 |
-
article_level_vehicle_type = get_standardized_vehicle_type(raw_article_title) or "không xác định"
|
99 |
-
|
100 |
-
clauses = article_data.get("clauses", [])
|
101 |
-
if not isinstance(clauses, list):
|
102 |
-
# print(f"Cảnh báo: 'clauses' trong Điều {article_data.get('article')} không phải list.")
|
103 |
-
continue
|
104 |
-
|
105 |
-
for clause_data in clauses:
|
106 |
-
if not isinstance(clause_data, dict):
|
107 |
-
# print(f"Cảnh báo: Bỏ qua mục không phải dict trong 'clauses' của Điều {article_data.get('article')}")
|
108 |
-
continue
|
109 |
-
|
110 |
-
clause_metadata_base = article_metadata_base.copy()
|
111 |
-
clause_number = clause_data.get("clause_number") # Số khoản, ví dụ "1" hoặc "1a"
|
112 |
-
clause_metadata_base.update({"clause_number": clause_number})
|
113 |
-
|
114 |
-
clause_summary_data = clause_data.get("clause_metadata_summary")
|
115 |
-
if isinstance(clause_summary_data, dict):
|
116 |
-
clause_metadata_base["overall_fine_note_for_clause_text"] = clause_summary_data.get("overall_fine_note_for_clause")
|
117 |
-
clause_metadata_base["overall_points_deduction_note_for_clause_text"] = clause_summary_data.get("overall_points_deduction_note_for_clause")
|
118 |
-
|
119 |
-
points_in_clause = clause_data.get("points_in_clause", [])
|
120 |
-
if not isinstance(points_in_clause, list):
|
121 |
-
# print(f"Cảnh báo: 'points_in_clause' trong Khoản {clause_number} của Điều {article_data.get('article')} không phải list.")
|
122 |
-
continue
|
123 |
-
|
124 |
-
if points_in_clause: # Nếu có các Điểm trong Khoản
|
125 |
-
for point_data in points_in_clause:
|
126 |
-
if not isinstance(point_data, dict):
|
127 |
-
# print(f"Cảnh báo: Bỏ qua mục không phải dict trong 'points_in_clause'.")
|
128 |
-
continue
|
129 |
-
|
130 |
-
chunk_text = point_data.get("point_text_original")
|
131 |
-
if not chunk_text: chunk_text = point_data.get("violation_description_summary") # Fallback
|
132 |
-
if not chunk_text: continue # Bỏ qua nếu không có text
|
133 |
-
|
134 |
-
current_chunk_metadata = clause_metadata_base.copy()
|
135 |
-
current_chunk_metadata["point_id"] = point_data.get("point_id") # ID của điểm, ví dụ "a"
|
136 |
-
current_chunk_metadata["violation_description_summary"] = point_data.get("violation_description_summary")
|
137 |
-
|
138 |
-
# 1. Làm phẳng 'penalties_detail'
|
139 |
-
current_chunk_metadata.update({
|
140 |
-
'has_fine': False, 'has_points_deduction': False,
|
141 |
-
'has_license_suspension': False, 'has_confiscation': False
|
142 |
-
})
|
143 |
-
penalty_types_for_this_point: List[str] = []
|
144 |
-
points_values: List[Any] = []
|
145 |
-
s_min_months: List[float] = [] # Sửa thành float để chứa giá trị tháng lẻ
|
146 |
-
s_max_months: List[float] = []
|
147 |
-
confiscation_items_list: List[str] = []
|
148 |
-
|
149 |
-
penalties = point_data.get("penalties_detail", [])
|
150 |
-
if isinstance(penalties, list):
|
151 |
-
for p_item in penalties:
|
152 |
-
if not isinstance(p_item, dict): continue
|
153 |
-
p_type_original, p_details = p_item.get("penalty_type"), p_item.get("details", {})
|
154 |
-
if p_type_original: penalty_types_for_this_point.append(str(p_type_original))
|
155 |
-
if not isinstance(p_details, dict): continue
|
156 |
-
|
157 |
-
p_type_lower = str(p_type_original).lower()
|
158 |
-
if "phạt tiền" in p_type_lower:
|
159 |
-
current_chunk_metadata['has_fine'] = True
|
160 |
-
if p_details.get("individual_fine_min") is not None: current_chunk_metadata['individual_fine_min'] = p_details.get("individual_fine_min")
|
161 |
-
if p_details.get("individual_fine_max") is not None: current_chunk_metadata['individual_fine_max'] = p_details.get("individual_fine_max")
|
162 |
-
if "trừ điểm" in p_type_lower or "điểm giấy phép lái xe" in p_type_lower : # Mở rộng kiểm tra
|
163 |
-
current_chunk_metadata['has_points_deduction'] = True
|
164 |
-
if p_details.get("points_deducted") is not None: points_values.append(p_details.get("points_deducted"))
|
165 |
-
if "tước quyền sử dụng giấy phép lái xe" in p_type_lower or "tước bằng lái" in p_type_lower:
|
166 |
-
current_chunk_metadata['has_license_suspension'] = True
|
167 |
-
if p_details.get("suspension_duration_min_months") is not None: s_min_months.append(float(p_details.get("suspension_duration_min_months")))
|
168 |
-
if p_details.get("suspension_duration_max_months") is not None: s_max_months.append(float(p_details.get("suspension_duration_max_months")))
|
169 |
-
if "tịch thu" in p_type_lower:
|
170 |
-
current_chunk_metadata['has_confiscation'] = True
|
171 |
-
if p_details.get("confiscation_item"): confiscation_items_list.append(str(p_details.get("confiscation_item")))
|
172 |
-
|
173 |
-
if penalty_types_for_this_point: current_chunk_metadata['penalty_types_str'] = ", ".join(sorted(list(set(penalty_types_for_this_point))))
|
174 |
-
if points_values: current_chunk_metadata['points_deducted_values_str'] = ", ".join(map(str, sorted(list(set(points_values)))))
|
175 |
-
if s_min_months: current_chunk_metadata['suspension_min_months'] = min(s_min_months)
|
176 |
-
if s_max_months: current_chunk_metadata['suspension_max_months'] = max(s_max_months)
|
177 |
-
if confiscation_items_list: current_chunk_metadata['confiscation_items_str'] = ", ".join(sorted(list(set(confiscation_items_list))))
|
178 |
-
|
179 |
-
# 2. Thông tin tốc độ
|
180 |
-
if point_data.get("speed_limit") is not None: current_chunk_metadata['speed_limit_value'] = point_data.get("speed_limit")
|
181 |
-
if point_data.get("speed_limit_min") is not None: current_chunk_metadata['speed_limit_min_value'] = point_data.get("speed_limit_min")
|
182 |
-
if point_data.get("speed_type"): current_chunk_metadata['speed_category'] = point_data.get("speed_type")
|
183 |
-
|
184 |
-
# 3. Thông tin loại xe/đường cụ thể từ point_data
|
185 |
-
speed_limits_extra = point_data.get("speed_limits_by_vehicle_type_and_road_type", [])
|
186 |
-
point_specific_vehicle_types_raw: List[str] = []
|
187 |
-
point_specific_road_types: List[str] = []
|
188 |
-
if isinstance(speed_limits_extra, list):
|
189 |
-
for sl_item in speed_limits_extra:
|
190 |
-
if isinstance(sl_item, dict):
|
191 |
-
if sl_item.get("vehicle_type"): point_specific_vehicle_types_raw.append(str(sl_item.get("vehicle_type")).lower())
|
192 |
-
if sl_item.get("road_type"): point_specific_road_types.append(str(sl_item.get("road_type")).lower())
|
193 |
-
if point_specific_vehicle_types_raw: current_chunk_metadata['point_specific_vehicle_types_str'] = ", ".join(sorted(list(set(point_specific_vehicle_types_raw))))
|
194 |
-
if point_specific_road_types: current_chunk_metadata['point_specific_road_types_str'] = ", ".join(sorted(list(set(point_specific_road_types))))
|
195 |
-
|
196 |
-
# 4. Gán 'applicable_vehicle_type' chính
|
197 |
-
derived_vehicle_type_from_point = "không xác định"
|
198 |
-
if point_specific_vehicle_types_raw:
|
199 |
-
normalized_types_from_point_data = set()
|
200 |
-
for vt_raw in set(point_specific_vehicle_types_raw):
|
201 |
-
standard_type = get_standardized_vehicle_type(vt_raw)
|
202 |
-
if standard_type: normalized_types_from_point_data.add(standard_type)
|
203 |
-
|
204 |
-
if len(normalized_types_from_point_data) == 1:
|
205 |
-
derived_vehicle_type_from_point = list(normalized_types_from_point_data)[0]
|
206 |
-
elif len(normalized_types_from_point_data) > 1:
|
207 |
-
# Xử lý trường hợp có nhiều loại xe đã chuẩn hóa
|
208 |
-
if "ô tô" in normalized_types_from_point_data and "xe máy" in normalized_types_from_point_data:
|
209 |
-
derived_vehicle_type_from_point = "ô tô và xe máy"
|
210 |
-
# Có thể thêm các logic ưu tiên khác nếu cần (ví dụ: nếu có "xe cơ giới" và "ô tô" -> "ô tô")
|
211 |
-
elif "ô tô" in normalized_types_from_point_data: derived_vehicle_type_from_point = "ô tô"
|
212 |
-
elif "xe máy" in normalized_types_from_point_data: derived_vehicle_type_from_point = "xe máy"
|
213 |
-
else: # Nếu không có cặp ưu tiên rõ ràng
|
214 |
-
derived_vehicle_type_from_point = "nhiều loại cụ thể" # Hoặc join các loại: ", ".join(sorted(list(normalized_types_from_point_data)))
|
215 |
-
|
216 |
-
# Ưu tiên thông tin từ point, nếu không rõ ràng thì mới dùng từ article
|
217 |
-
# Các loại được coi là rõ ràng: "ô tô", "xe máy", "xe cơ giới", "xe thô sơ", "người đi bộ", "ô tô và xe máy"
|
218 |
-
clear_types = ["ô tô", "xe máy", "xe cơ giới", "xe thô sơ", "người đi bộ", "ô tô và xe máy"]
|
219 |
-
if derived_vehicle_type_from_point not in clear_types and derived_vehicle_type_from_point != "không xác định":
|
220 |
-
# Nếu là "nhiều loại cụ thể" mà không phải "ô tô và xe máy" hoặc các loại không rõ ràng khác
|
221 |
-
current_chunk_metadata['applicable_vehicle_type'] = article_level_vehicle_type
|
222 |
-
elif derived_vehicle_type_from_point == "không xác định":
|
223 |
-
current_chunk_metadata['applicable_vehicle_type'] = article_level_vehicle_type
|
224 |
-
else: # Các trường hợp còn lại (rõ ràng từ point)
|
225 |
-
current_chunk_metadata['applicable_vehicle_type'] = derived_vehicle_type_from_point
|
226 |
-
|
227 |
-
# 5. Các trường khác
|
228 |
-
if point_data.get("applies_to"): current_chunk_metadata['applies_to_context'] = point_data.get("applies_to")
|
229 |
-
if point_data.get("location"): current_chunk_metadata['specific_location_info'] = point_data.get("location")
|
230 |
-
|
231 |
-
final_metadata_cleaned = {k: v for k, v in current_chunk_metadata.items() if v is not None}
|
232 |
-
flat_list.append({ "text": chunk_text, "metadata": final_metadata_cleaned })
|
233 |
-
|
234 |
-
else: # Nếu Khoản không có Điểm nào, thì text của Khoản là một chunk
|
235 |
-
chunk_text = clause_data.get("clause_text_original")
|
236 |
-
if chunk_text: # Chỉ thêm nếu có text
|
237 |
-
current_clause_level_metadata = clause_metadata_base.copy()
|
238 |
-
# Với chunk cấp độ Khoản, loại xe sẽ lấy từ article_level_vehicle_type
|
239 |
-
current_clause_level_metadata['applicable_vehicle_type'] = article_level_vehicle_type
|
240 |
-
# Kiểm tra xem có thông tin phạt tiền tổng thể ở Khoản không
|
241 |
-
if current_clause_level_metadata.get("overall_fine_note_for_clause_text"):
|
242 |
-
current_clause_level_metadata['has_fine_clause_level'] = True # Dùng để boost nếu cần
|
243 |
-
|
244 |
-
final_metadata_cleaned = {k:v for k,v in current_clause_level_metadata.items() if v is not None}
|
245 |
-
flat_list.append({ "text": chunk_text, "metadata": final_metadata_cleaned })
|
246 |
-
return flat_list
|
247 |
-
|
248 |
-
# --- 4. HÀM PHÂN TÍCH QUERY ---
|
249 |
-
def analyze_query(query_text: str) -> Dict[str, Any]:
|
250 |
-
"""
|
251 |
-
Phân tích query để xác định ý định của người dùng (ví dụ: hỏi về phạt tiền, điểm, loại xe...).
|
252 |
-
"""
|
253 |
-
query_lower = query_text.lower()
|
254 |
-
analysis: Dict[str, Any] = {
|
255 |
-
"mentions_fine": bool(re.search(r'tiền|phạt|bao nhiêu đồng|bao nhiêu tiền|mức phạt|xử phạt hành chính|nộp phạt', query_lower)),
|
256 |
-
"mentions_points": bool(re.search(r'điểm|trừ điểm|mấy điểm|trừ bao nhiêu điểm|bằng lái|gplx|giấy phép lái xe', query_lower)),
|
257 |
-
"mentions_suspension": bool(re.search(r'tước bằng|tước giấy phép lái xe|giam bằng|treo bằng|thu bằng lái|tước quyền sử dụng', query_lower)),
|
258 |
-
"mentions_confiscation": bool(re.search(r'tịch thu|thu xe|thu phương tiện', query_lower)),
|
259 |
-
"mentions_max_speed": bool(re.search(r'tốc độ tối đa|giới hạn tốc độ|chạy quá tốc độ|vượt tốc độ', query_lower)),
|
260 |
-
"mentions_min_speed": bool(re.search(r'tốc độ tối thiểu|chạy chậm hơn', query_lower)),
|
261 |
-
"mentions_safe_distance": bool(re.search(r'khoảng cách an toàn|cự ly an toàn|cự ly tối thiểu|giữ khoảng cách', query_lower)),
|
262 |
-
"mentions_remedial_measures": bool(re.search(r'biện pháp khắc phục|khắc phục hậu quả', query_lower)),
|
263 |
-
"vehicle_type_query": None, # Sẽ được điền bằng loại xe chuẩn hóa nếu có
|
264 |
-
}
|
265 |
-
|
266 |
-
# Sử dụng lại VEHICLE_TYPE_MAP để chuẩn hóa loại xe trong query
|
267 |
-
# Ưu tiên loại cụ thể trước
|
268 |
-
queried_vehicle_standardized = get_standardized_vehicle_type(query_lower)
|
269 |
-
if queried_vehicle_standardized:
|
270 |
-
analysis["vehicle_type_query"] = queried_vehicle_standardized
|
271 |
-
|
272 |
-
return analysis
|
273 |
-
|
274 |
-
# --- 5. HÀM TÌM KIẾM KẾT HỢP (HYBRID SEARCH) ---
|
275 |
-
def search_relevant_laws(
|
276 |
-
query_text: str,
|
277 |
-
embedding_model, # Kiểu dữ liệu: SentenceTransformer model
|
278 |
-
faiss_index, # Kiểu dữ liệu: faiss.Index
|
279 |
-
chunks_data: List[Dict[str, Any]],
|
280 |
-
bm25_model, # Kiểu dữ liệu: BM25Okapi model
|
281 |
-
k: int = 5,
|
282 |
-
initial_k_multiplier: int = 10,
|
283 |
-
rrf_k_constant: int = 60,
|
284 |
-
# Trọng số cho các loại boost (có thể điều chỉnh)
|
285 |
-
boost_fine: float = 0.15,
|
286 |
-
boost_points: float = 0.15,
|
287 |
-
boost_both_fine_points: float = 0.10, # Boost thêm nếu khớp cả hai
|
288 |
-
boost_vehicle_type: float = 0.20,
|
289 |
-
boost_suspension: float = 0.18,
|
290 |
-
boost_confiscation: float = 0.18,
|
291 |
-
boost_max_speed: float = 0.15,
|
292 |
-
boost_min_speed: float = 0.15,
|
293 |
-
boost_safe_distance: float = 0.12,
|
294 |
-
boost_remedial_measures: float = 0.10
|
295 |
-
) -> List[Dict[str, Any]]:
|
296 |
-
"""
|
297 |
-
Thực hiện tìm kiếm kết hợp (semantic + keyword) với RRF và metadata re-ranking.
|
298 |
-
"""
|
299 |
-
if k <= 0:
|
300 |
-
print("Lỗi: k (số lượng kết quả) phải là số dương.")
|
301 |
-
return []
|
302 |
-
if not chunks_data:
|
303 |
-
print("Lỗi: chunks_data rỗng, không thể tìm kiếm.")
|
304 |
-
return []
|
305 |
-
|
306 |
-
print(f"\n🔎 Đang tìm kiếm (Hybrid) cho truy vấn: '{query_text}'")
|
307 |
-
|
308 |
-
# === 1. Phân tích Query ===
|
309 |
-
query_analysis = analyze_query(query_text)
|
310 |
-
# print(f" Phân tích query: {json.dumps(query_analysis, ensure_ascii=False, indent=2)}")
|
311 |
-
|
312 |
-
num_vectors_in_index = faiss_index.ntotal
|
313 |
-
if num_vectors_in_index == 0:
|
314 |
-
print("Lỗi: FAISS index rỗng.")
|
315 |
-
return []
|
316 |
-
|
317 |
-
# Số lượng ứng viên ban đầu từ mỗi retriever
|
318 |
-
num_candidates_each_retriever = max(min(k * initial_k_multiplier, num_vectors_in_index), min(k, num_vectors_in_index))
|
319 |
-
if num_candidates_each_retriever == 0:
|
320 |
-
print(f" Không thể lấy đủ số lượng ứng viên ban đầu (num_candidates = 0).")
|
321 |
-
return []
|
322 |
-
|
323 |
-
# === 2. Semantic Search (FAISS) ===
|
324 |
-
semantic_indices_raw: np.ndarray = np.array([[]], dtype=int) # Khởi tạo rỗng
|
325 |
-
try:
|
326 |
-
query_embedding_tensor = embedding_model.encode(
|
327 |
-
[query_text], convert_to_tensor=True, device=embedding_model.device
|
328 |
-
)
|
329 |
-
query_embedding_np = query_embedding_tensor.cpu().numpy().astype('float32')
|
330 |
-
faiss.normalize_L2(query_embedding_np) # Chuẩn hóa vector query
|
331 |
-
# print(f" Đã tạo và chuẩn hóa vector truy vấn shape: {query_embedding_np.shape}")
|
332 |
-
# print(f" Tìm kiếm {num_candidates_each_retriever} kết quả ngữ nghĩa (FAISS)...")
|
333 |
-
_, semantic_indices_raw = faiss_index.search(query_embedding_np, num_candidates_each_retriever)
|
334 |
-
# print(f" ✅ Tìm kiếm ngữ nghĩa (FAISS) hoàn tất.")
|
335 |
-
except Exception as e:
|
336 |
-
print(f"Lỗi khi tìm kiếm ngữ nghĩa (FAISS): {e}")
|
337 |
-
# semantic_indices_raw đã được khởi tạo là rỗng
|
338 |
-
|
339 |
-
# === 3. Keyword Search (BM25) ===
|
340 |
-
# print(f" Tìm kiếm {num_candidates_each_retriever} kết quả từ khóa (BM25)...")
|
341 |
-
tokenized_query_bm25 = tokenize_vi_for_bm25_setup(query_text)
|
342 |
-
top_bm25_results: List[Dict[str, Any]] = []
|
343 |
-
try:
|
344 |
-
if bm25_model and tokenized_query_bm25:
|
345 |
-
all_bm25_scores = bm25_model.get_scores(tokenized_query_bm25)
|
346 |
-
# Lấy chỉ số và score cho các document có score > 0
|
347 |
-
bm25_results_with_indices = [
|
348 |
-
{'index': i, 'score': score} for i, score in enumerate(all_bm25_scores) if score > 0
|
349 |
-
]
|
350 |
-
# Sắp xếp theo score giảm dần
|
351 |
-
bm25_results_with_indices.sort(key=lambda x: x['score'], reverse=True)
|
352 |
-
top_bm25_results = bm25_results_with_indices[:num_candidates_each_retriever]
|
353 |
-
# print(f" ✅ Tìm kiếm từ khóa (BM25) hoàn tất, tìm thấy {len(top_bm25_results)} ứng viên.")
|
354 |
-
else:
|
355 |
-
# print(" Cảnh báo: BM25 model hoặc tokenized query không hợp lệ, bỏ qua BM25.")
|
356 |
-
pass
|
357 |
-
except Exception as e:
|
358 |
-
print(f"Lỗi khi tìm kiếm từ khóa (BM25): {e}")
|
359 |
-
|
360 |
-
# === 4. Result Fusion (Reciprocal Rank Fusion - RRF) ===
|
361 |
-
# print(f" Kết hợp kết quả từ FAISS và BM25 bằng RRF (k_const={rrf_k_constant})...")
|
362 |
-
rrf_scores: Dict[int, float] = defaultdict(float)
|
363 |
-
all_retrieved_indices_set: set[int] = set()
|
364 |
-
|
365 |
-
if semantic_indices_raw.size > 0:
|
366 |
-
for rank, doc_idx_int in enumerate(semantic_indices_raw[0]):
|
367 |
-
doc_idx = int(doc_idx_int) # Đảm bảo là int
|
368 |
-
if 0 <= doc_idx < len(chunks_data): # Kiểm tra doc_idx hợp lệ với chunks_data
|
369 |
-
rrf_scores[doc_idx] += 1.0 / (rrf_k_constant + rank)
|
370 |
-
all_retrieved_indices_set.add(doc_idx)
|
371 |
-
|
372 |
-
for rank, item in enumerate(top_bm25_results):
|
373 |
-
doc_idx = item['index']
|
374 |
-
if 0 <= doc_idx < len(chunks_data):
|
375 |
-
rrf_scores[doc_idx] += 1.0 / (rrf_k_constant + rank)
|
376 |
-
all_retrieved_indices_set.add(doc_idx)
|
377 |
-
|
378 |
-
fused_initial_results: List[Dict[str, Any]] = []
|
379 |
-
for doc_idx in all_retrieved_indices_set:
|
380 |
-
fused_initial_results.append({
|
381 |
-
'index': doc_idx,
|
382 |
-
'fused_score': rrf_scores[doc_idx]
|
383 |
-
})
|
384 |
-
fused_initial_results.sort(key=lambda x: x['fused_score'], reverse=True)
|
385 |
-
# print(f" ✅ Kết hợp RRF hoàn tất, có {len(fused_initial_results)} ứng viên duy nhất.")
|
386 |
-
|
387 |
-
# === 5. Xử lý Metadata, Lọc và Tái xếp hạng cuối cùng ===
|
388 |
-
final_processed_results: List[Dict[str, Any]] = []
|
389 |
-
# Xử lý metadata cho số lượng ứng viên lớn hơn để có đủ lựa chọn sau khi lọc
|
390 |
-
num_to_process_metadata = min(len(fused_initial_results), num_candidates_each_retriever * 2 if num_candidates_each_retriever > 0 else k * 3)
|
391 |
-
|
392 |
-
# print(f" Xử lý metadata và tính điểm cuối cùng cho top {num_to_process_metadata} ứng viên lai ghép...")
|
393 |
-
for rank_idx, res_item in enumerate(fused_initial_results[:num_to_process_metadata]):
|
394 |
-
result_index = res_item['index']
|
395 |
-
base_score_from_fusion = res_item['fused_score']
|
396 |
-
metadata_boost_components: Dict[str, float] = defaultdict(float)
|
397 |
-
passes_all_strict_filters = True
|
398 |
-
|
399 |
-
try:
|
400 |
-
original_chunk = chunks_data[result_index]
|
401 |
-
chunk_metadata = original_chunk.get('metadata', {})
|
402 |
-
chunk_text_lower = original_chunk.get('text', '').lower()
|
403 |
-
|
404 |
-
# 5.1 & 5.2: Tiền phạt và Điểm phạt
|
405 |
-
has_fine_info_in_chunk = chunk_metadata.get("has_fine", False) or chunk_metadata.get("has_fine_clause_level", False)
|
406 |
-
has_points_info_in_chunk = chunk_metadata.get("has_points_deduction", False)
|
407 |
-
|
408 |
-
if query_analysis["mentions_fine"]:
|
409 |
-
if has_fine_info_in_chunk:
|
410 |
-
metadata_boost_components["fine"] += boost_fine
|
411 |
-
elif not query_analysis["mentions_points"]: # Chỉ hỏi tiền mà chunk không có -> lọc
|
412 |
-
passes_all_strict_filters = False
|
413 |
-
|
414 |
-
if query_analysis["mentions_points"]:
|
415 |
-
if has_points_info_in_chunk:
|
416 |
-
metadata_boost_components["points"] += boost_points
|
417 |
-
elif not query_analysis["mentions_fine"]: # Chỉ hỏi điểm mà chunk không có -> lọc
|
418 |
-
passes_all_strict_filters = False
|
419 |
-
|
420 |
-
if query_analysis["mentions_fine"] and query_analysis["mentions_points"]:
|
421 |
-
if not has_fine_info_in_chunk and not has_points_info_in_chunk: # Query hỏi cả hai mà chunk ko có cả hai
|
422 |
-
passes_all_strict_filters = False
|
423 |
-
elif has_fine_info_in_chunk and has_points_info_in_chunk:
|
424 |
-
metadata_boost_components["both_fine_points"] += boost_both_fine_points
|
425 |
-
|
426 |
-
# 5.3. Loại xe
|
427 |
-
queried_vehicle = query_analysis["vehicle_type_query"]
|
428 |
-
if queried_vehicle:
|
429 |
-
applicable_vehicle_meta = chunk_metadata.get("applicable_vehicle_type", "").lower()
|
430 |
-
point_specific_vehicles_meta = chunk_metadata.get("point_specific_vehicle_types_str", "").lower()
|
431 |
-
article_title_lower = chunk_metadata.get("article_title", "").lower()
|
432 |
-
|
433 |
-
match_vehicle = False
|
434 |
-
if queried_vehicle in applicable_vehicle_meta: match_vehicle = True
|
435 |
-
elif queried_vehicle in point_specific_vehicles_meta: match_vehicle = True
|
436 |
-
# Kiểm tra xem queried_vehicle (đã chuẩn hóa) có trong article_title không
|
437 |
-
elif queried_vehicle in article_title_lower: match_vehicle = True # Đơn giản hóa, có thể dùng regex nếu cần chính xác hơn
|
438 |
-
# Kiểm tra xem queried_vehicle (đã chuẩn hóa) có trong chunk_text không
|
439 |
-
elif queried_vehicle in chunk_text_lower: match_vehicle = True
|
440 |
-
|
441 |
-
|
442 |
-
if match_vehicle:
|
443 |
-
metadata_boost_components["vehicle_type"] += boost_vehicle_type
|
444 |
-
else:
|
445 |
-
# Logic lọc: nếu query có loại xe cụ thể, mà applicable_vehicle_type của chunk là một loại khác
|
446 |
-
# và không phải là "không xác định", "nhiều loại cụ thể", hoặc loại cha chung ("xe cơ giới" cho "ô tô")
|
447 |
-
if applicable_vehicle_meta and \
|
448 |
-
applicable_vehicle_meta not in ["không xác định", "nhiều loại cụ thể", "ô tô và xe máy"] and \
|
449 |
-
not (applicable_vehicle_meta == "xe cơ giới" and queried_vehicle in ["ô tô", "xe máy"]):
|
450 |
-
passes_all_strict_filters = False
|
451 |
-
|
452 |
-
# 5.4. Tước quyền sử dụng GPLX
|
453 |
-
if query_analysis["mentions_suspension"] and chunk_metadata.get("has_license_suspension"):
|
454 |
-
metadata_boost_components["suspension"] += boost_suspension
|
455 |
-
|
456 |
-
# 5.5. Tịch thu
|
457 |
-
if query_analysis["mentions_confiscation"] and chunk_metadata.get("has_confiscation"):
|
458 |
-
metadata_boost_components["confiscation"] += boost_confiscation
|
459 |
-
|
460 |
-
# 5.6. Tốc độ tối đa
|
461 |
-
if query_analysis["mentions_max_speed"]:
|
462 |
-
if chunk_metadata.get("speed_limit_value") is not None or \
|
463 |
-
"tốc độ tối đa" in chunk_metadata.get("speed_category","").lower() or \
|
464 |
-
any(kw in chunk_text_lower for kw in ["quá tốc độ", "tốc độ tối đa", "vượt tốc độ quy định"]):
|
465 |
-
metadata_boost_components["max_speed"] += boost_max_speed
|
466 |
-
|
467 |
-
# 5.7. Tốc độ tối thiểu
|
468 |
-
if query_analysis["mentions_min_speed"]:
|
469 |
-
if chunk_metadata.get("speed_limit_min_value") is not None or \
|
470 |
-
"tốc độ tối thiểu" in chunk_metadata.get("speed_category","").lower() or \
|
471 |
-
"tốc độ tối thiểu" in chunk_text_lower:
|
472 |
-
metadata_boost_components["min_speed"] += boost_min_speed
|
473 |
-
|
474 |
-
# 5.8. Khoảng cách an toàn
|
475 |
-
if query_analysis["mentions_safe_distance"]:
|
476 |
-
if any(kw in chunk_text_lower for kw in ["khoảng cách an toàn", "cự ly an toàn", "cự ly tối thiểu", "giữ khoảng cách"]):
|
477 |
-
metadata_boost_components["safe_distance"] += boost_safe_distance
|
478 |
-
|
479 |
-
# 5.9. Biện pháp khắc phục
|
480 |
-
if query_analysis["mentions_remedial_measures"]:
|
481 |
-
if any(kw in chunk_text_lower for kw in ["biện pháp khắc phục", "khắc phục hậu quả"]):
|
482 |
-
metadata_boost_components["remedial_measures"] += boost_remedial_measures
|
483 |
-
|
484 |
-
if not passes_all_strict_filters:
|
485 |
-
continue
|
486 |
-
|
487 |
-
total_metadata_boost = sum(metadata_boost_components.values())
|
488 |
-
final_score_calculated = base_score_from_fusion + total_metadata_boost
|
489 |
-
|
490 |
-
final_processed_results.append({
|
491 |
-
"rank_after_fusion": rank_idx + 1,
|
492 |
-
"index": int(result_index),
|
493 |
-
"base_score_rrf": float(base_score_from_fusion),
|
494 |
-
"metadata_boost_components": dict(metadata_boost_components), # Lưu lại để debug
|
495 |
-
"metadata_boost_total": float(total_metadata_boost),
|
496 |
-
"final_score": final_score_calculated,
|
497 |
-
"text": original_chunk.get('text', '*Không có text*'),
|
498 |
-
"metadata": chunk_metadata, # Giữ nguyên metadata gốc
|
499 |
-
"query_analysis_for_boost": query_analysis # (Tùy chọn) Lưu lại query analysis dùng cho boosting
|
500 |
-
})
|
501 |
-
|
502 |
-
except IndexError:
|
503 |
-
print(f"Lỗi Index: Chỉ số {result_index} nằm ngoài chunks_data (size: {len(chunks_data)}). Bỏ qua chunk này.")
|
504 |
-
except Exception as e:
|
505 |
-
print(f"Lỗi khi xử lý ứng viên lai ghép tại chỉ số {result_index}: {e}. Bỏ qua chunk này.")
|
506 |
-
|
507 |
-
final_processed_results.sort(key=lambda x: x["final_score"], reverse=True)
|
508 |
-
final_results_top_k = final_processed_results[:k]
|
509 |
-
|
510 |
-
print(f" ✅ Xử lý, kết hợp metadata boost và tái xếp hạng hoàn tất. Trả về {len(final_results_top_k)} kết quả.")
|
511 |
-
return final_results_top_k
|
512 |
-
|
513 |
-
|
514 |
-
# --- (Tùy chọn) Hàm main để test nhanh file này ---
|
515 |
-
if __name__ == '__main__':
|
516 |
-
print("Chạy test cho retrieval.py...")
|
517 |
-
|
518 |
-
# --- Test get_standardized_vehicle_type ---
|
519 |
-
print("\n--- Test get_standardized_vehicle_type ---")
|
520 |
-
test_vehicles = [
|
521 |
-
"người điều khiển xe ô tô con", "xe gắn máy", "xe cơ giới", "xe máy chuyên dùng",
|
522 |
-
"xe đạp điện", "người đi bộ", "ô tô tải và xe mô tô", None, ""
|
523 |
-
]
|
524 |
-
for tv in test_vehicles:
|
525 |
-
print(f"'{tv}' -> '{get_standardized_vehicle_type(tv)}'")
|
526 |
-
|
527 |
-
# --- Test analyze_query ---
|
528 |
-
print("\n--- Test analyze_query ---")
|
529 |
-
test_queries = [
|
530 |
-
"xe máy không gương phạt bao nhiêu tiền?",
|
531 |
-
"ô tô chạy quá tốc độ 20km bị trừ mấy điểm gplx",
|
532 |
-
"đi bộ ở đâu thì đúng luật",
|
533 |
-
"biện pháp khắc phục khi gây tai nạn là gì"
|
534 |
-
]
|
535 |
-
for tq in test_queries:
|
536 |
-
print(f"Query: '{tq}'\nAnalysis: {json.dumps(analyze_query(tq), indent=2, ensure_ascii=False)}")
|
537 |
-
|
538 |
-
# --- Test process_law_data_to_chunks (cần file JSON mẫu) ---
|
539 |
-
# Giả sử bạn có file JSON mẫu 'sample_law_data.json' cùng cấp
|
540 |
-
# sample_data = {
|
541 |
-
# "article": "Điều 5",
|
542 |
-
# "article_title": "Xử phạt người điều khiển xe ô tô và các loại xe tương tự xe ô tô vi phạm quy tắc giao thông đường bộ",
|
543 |
-
# "source_document": "Nghị định 100/2019/NĐ-CP",
|
544 |
-
# "clauses": [
|
545 |
-
# {
|
546 |
-
# "clause_number": "1",
|
547 |
-
# "clause_text_original": "Phạt tiền từ 200.000 đồng đến 400.000 đồng đối với người điều khiển xe thực hiện một trong các hành vi vi phạm sau đây:",
|
548 |
-
# "points_in_clause": [
|
549 |
-
# {
|
550 |
-
# "point_id": "a",
|
551 |
-
# "point_text_original": "Không chấp hành hiệu lệnh, chỉ dẫn của biển báo hiệu, vạch kẻ đường, trừ các hành vi vi phạm quy định tại điểm a khoản 2, điểm c khoản 3, điểm đ khoản 4, điểm g khoản 5, điểm b khoản 6, điểm b khoản 7, điểm d khoản 8 Điều này;",
|
552 |
-
# "penalties_detail": [
|
553 |
-
# {"penalty_type": "Phạt tiền", "details": {"individual_fine_min": 200000, "individual_fine_max": 400000}}
|
554 |
-
# ],
|
555 |
-
# "speed_limits_by_vehicle_type_and_road_type": [{"vehicle_type": "xe ô tô con"}]
|
556 |
-
# }
|
557 |
-
# ]
|
558 |
-
# },
|
559 |
-
# {
|
560 |
-
# "clause_number": "12", # Khoản không có điểm
|
561 |
-
# "clause_text_original": "Ngoài việc bị phạt tiền, người điều khiển xe thực hiện hành vi vi phạm còn bị áp dụng các hình thức xử phạt bổ sung sau đây: ...",
|
562 |
-
# "clause_metadata_summary": {"overall_fine_note_for_clause": "Áp dụng hình phạt bổ sung"}
|
563 |
-
# }
|
564 |
-
# ]
|
565 |
-
# }
|
566 |
-
#
|
567 |
-
# print("\n--- Test process_law_data_to_chunks ---")
|
568 |
-
# chunks = process_law_data_to_chunks(sample_data)
|
569 |
-
# print(f"Số chunks được tạo: {len(chunks)}")
|
570 |
-
# if chunks:
|
571 |
-
# print("Chunk đầu tiên:")
|
572 |
-
# print(json.dumps(chunks[0], indent=2, ensure_ascii=False))
|
573 |
-
# print("Chunk cuối cùng (nếu có nhiều hơn 1):")
|
574 |
-
# if len(chunks) > 1:
|
575 |
-
# print(json.dumps(chunks[-1], indent=2, ensure_ascii=False))
|
576 |
-
|
577 |
-
# Để test search_relevant_laws, bạn cần mock embedding_model, faiss_index, bm25_model
|
578 |
-
# và có chunks_data đã được xử lý.
|
579 |
-
print("\n--- Các test khác (ví dụ: search_relevant_laws) cần mock hoặc dữ liệu đầy đủ. ---")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
retrieval_handler.py
ADDED
@@ -0,0 +1,82 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# retrieval_handler.py
|
2 |
+
# Chịu trách nhiệm cho mọi logic liên quan đến việc truy xuất thông tin (Retrieval).
|
3 |
+
|
4 |
+
import json
|
5 |
+
import re
|
6 |
+
import numpy as np
|
7 |
+
import faiss
|
8 |
+
from collections import defaultdict
|
9 |
+
from typing import List, Dict, Any, Optional
|
10 |
+
from utils import tokenize_vi_simple # Import từ file utils.py
|
11 |
+
|
12 |
+
# --- HÀM XỬ LÝ DỮ LIỆU ---
|
13 |
+
def process_law_data_to_chunks(structured_data: Any) -> List[Dict]:
|
14 |
+
"""Làm phẳng dữ liệu luật có cấu trúc thành danh sách các chunks."""
|
15 |
+
flat_list = []
|
16 |
+
articles = [structured_data] if isinstance(structured_data, dict) else structured_data
|
17 |
+
for article_data in articles:
|
18 |
+
if not isinstance(article_data, dict): continue
|
19 |
+
# (Logic xử lý chi tiết của bạn ở đây... đã được rút gọn để dễ đọc)
|
20 |
+
# Giả sử logic này hoạt động đúng như bạn đã thiết kế
|
21 |
+
# và trả về một danh sách các chunk, mỗi chunk là một dict có "text" và "metadata".
|
22 |
+
# Để đảm bảo, tôi sẽ thêm một phiên bản đơn giản hóa ở đây.
|
23 |
+
clauses = article_data.get("clauses", [])
|
24 |
+
for clause in clauses:
|
25 |
+
points = clause.get("points_in_clause", [])
|
26 |
+
if points:
|
27 |
+
for point in points:
|
28 |
+
text = point.get("point_text_original")
|
29 |
+
if text:
|
30 |
+
flat_list.append({"text": text, "metadata": {"article": article_data.get("article"), "clause": clause.get("clause_number"), "point": point.get("point_id")}})
|
31 |
+
else:
|
32 |
+
text = clause.get("clause_text_original")
|
33 |
+
if text:
|
34 |
+
flat_list.append({"text": text, "metadata": {"article": article_data.get("article"), "clause": clause.get("clause_number")}})
|
35 |
+
return flat_list
|
36 |
+
|
37 |
+
|
38 |
+
# --- HÀM TÌM KIẾM ---
|
39 |
+
def search_relevant_laws(
|
40 |
+
query_text: str,
|
41 |
+
embedding_model,
|
42 |
+
faiss_index,
|
43 |
+
chunks_data: List[Dict],
|
44 |
+
bm25_model,
|
45 |
+
k: int = 5,
|
46 |
+
rrf_k_constant: int = 60
|
47 |
+
) -> List[Dict]:
|
48 |
+
"""
|
49 |
+
Thực hiện Hybrid Search (Semantic + Keyword) với RRF để tìm các chunk liên quan.
|
50 |
+
"""
|
51 |
+
print(f"🔎 Bắt đầu tìm kiếm cho: '{query_text}'")
|
52 |
+
# 1. Semantic Search (FAISS)
|
53 |
+
query_embedding = embedding_model.encode([query_text], convert_to_tensor=True)
|
54 |
+
query_embedding_np = query_embedding.cpu().numpy().astype('float32')
|
55 |
+
faiss.normalize_L2(query_embedding_np)
|
56 |
+
num_candidates = min(k * 10, faiss_index.ntotal)
|
57 |
+
_, semantic_indices = faiss_index.search(query_embedding_np, num_candidates)
|
58 |
+
|
59 |
+
# 2. Keyword Search (BM25)
|
60 |
+
tokenized_query = tokenize_vi_simple(query_text)
|
61 |
+
bm25_scores = bm25_model.get_scores(tokenized_query)
|
62 |
+
bm25_results = sorted(enumerate(bm25_scores), key=lambda x: x[1], reverse=True)[:num_candidates]
|
63 |
+
|
64 |
+
# 3. Reciprocal Rank Fusion (RRF)
|
65 |
+
rrf_scores = defaultdict(float)
|
66 |
+
if semantic_indices.size > 0:
|
67 |
+
for rank, doc_idx in enumerate(semantic_indices[0]):
|
68 |
+
if doc_idx != -1: rrf_scores[doc_idx] += 1.0 / (rrf_k_constant + rank)
|
69 |
+
for rank, (doc_idx, score) in enumerate(bm25_results):
|
70 |
+
if score > 0: rrf_scores[doc_idx] += 1.0 / (rrf_k_constant + rank)
|
71 |
+
|
72 |
+
fused_results = sorted(rrf_scores.items(), key=lambda x: x[1], reverse=True)
|
73 |
+
|
74 |
+
# 4. Trả về top K kết quả cuối cùng
|
75 |
+
final_results = []
|
76 |
+
for doc_idx, score in fused_results[:k]:
|
77 |
+
result = chunks_data[doc_idx].copy()
|
78 |
+
result['retrieval_score'] = score
|
79 |
+
final_results.append(result)
|
80 |
+
|
81 |
+
print(f"✅ Tìm kiếm hoàn tất, trả về {len(final_results)} kết quả.")
|
82 |
+
return final_results
|
utils.py
CHANGED
@@ -5,44 +5,12 @@ from typing import List
|
|
5 |
|
6 |
def tokenize_vi_simple(text: str) -> List[str]:
|
7 |
"""
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
Args:
|
12 |
-
text (str): The input Vietnamese text.
|
13 |
-
|
14 |
-
Returns:
|
15 |
-
List[str]: A list of tokens.
|
16 |
"""
|
17 |
if not isinstance(text, str):
|
18 |
-
# Or raise TypeError("Input must be a string")
|
19 |
return []
|
20 |
text = text.lower()
|
21 |
-
#
|
22 |
text = re.sub(r'[^\w\s]', '', text)
|
23 |
-
return text.split()
|
24 |
-
|
25 |
-
# You can add other general utility functions here as your project grows.
|
26 |
-
# For example:
|
27 |
-
# - Functions for logging
|
28 |
-
# - Functions for path manipulation if they are used across multiple modules
|
29 |
-
# - Simple data validation or cleaning routines not specific to law data or LLMs
|
30 |
-
|
31 |
-
if __name__ == '__main__':
|
32 |
-
print("Testing utils.py...")
|
33 |
-
|
34 |
-
# Test tokenize_vi_simple
|
35 |
-
print("\n--- Test tokenize_vi_simple ---")
|
36 |
-
test_phrases = [
|
37 |
-
"Luật Giao thông Đường bộ Việt Nam 2023!",
|
38 |
-
"Xe ô tô con và xe máy.",
|
39 |
-
" Phạt tiền từ 200.000đ đến 400.000đ. ",
|
40 |
-
"",
|
41 |
-
None, # Test with None
|
42 |
-
123 # Test with non-string
|
43 |
-
]
|
44 |
-
for phrase in test_phrases:
|
45 |
-
print(f"Input: '{phrase}' (type: {type(phrase).__name__})")
|
46 |
-
tokens = tokenize_vi_simple(phrase)
|
47 |
-
print(f"Tokens: {tokens}")
|
48 |
-
print("-" * 10)
|
|
|
5 |
|
6 |
def tokenize_vi_simple(text: str) -> List[str]:
|
7 |
"""
|
8 |
+
Tokenize tiếng Việt một cách đơn giản cho các tác vụ như BM25.
|
9 |
+
Chuyển thành chữ thường, loại bỏ dấu câu cơ bản và tách theo khoảng trắng.
|
|
|
|
|
|
|
|
|
|
|
|
|
10 |
"""
|
11 |
if not isinstance(text, str):
|
|
|
12 |
return []
|
13 |
text = text.lower()
|
14 |
+
# Loại bỏ các ký tự không phải chữ, số, hoặc khoảng trắng
|
15 |
text = re.sub(r'[^\w\s]', '', text)
|
16 |
+
return text.split()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|