deddoggo commited on
Commit
25950e2
·
1 Parent(s): 5903639
.dockerignore ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # .dockerignore
2
+ .git
3
+ __pycache__/
4
+ *.pyc
5
+ .DS_Store
6
+ .vscode/
7
+ .idea/
8
+ # Môi trường ảo cục bộ
9
+ .venv/
10
+ venv/
11
+ env/
12
+ # Các file hoặc thư mục khác không muốn copy vào Docker image
.gitattributes CHANGED
@@ -33,3 +33,11 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ models/lora_model_base/tokenizer.json filter=lfs diff=lfs merge=lfs -text
37
+ models/**/*.bin filter=lfs diff=lfs merge=lfs -text
38
+ models/**/*.safetensors filter=lfs diff=lfs merge=lfs -text
39
+ models/**/*.pt filter=lfs diff=lfs merge=lfs -text
40
+ models/**/*.onnx filter=lfs diff=lfs merge=lfs -text
41
+ models/**/*.json filter=lfs diff=lfs merge=lfs -text
42
+ data/**/*.index filter=lfs diff=lfs merge=lfs -text
43
+ data/my_law_faiss_flatip_normalized.index filter=lfs diff=lfs merge=lfs -text
Dockerfile ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Dockerfile
2
+
3
+ # Bước 1: Chọn base image
4
+ # Sử dụng Miniconda làm base. Image này đã bao gồm Conda.
5
+ FROM continuumio/miniconda3:latest
6
+
7
+ # Thiết lập biến môi trường để tránh các prompt tương tác không cần thiết
8
+ # trong quá trình cài đặt các package (thường dùng cho các lệnh apt-get, nhưng để đây cũng không sao)
9
+ ENV DEBIAN_FRONTEND=noninteractive
10
+
11
+ # Bước 2: Thiết lập thư mục làm việc bên trong container
12
+ WORKDIR /app
13
+
14
+ # Bước 3: Sao chép file định nghĩa môi trường Conda
15
+ # File environment.yml này nên được đặt cùng cấp với Dockerfile trong repo của bạn.
16
+ COPY environment.yml .
17
+
18
+ # Bước 4: Tạo môi trường Conda từ file environment.yml
19
+ # Thay "myapp-env" bằng tên môi trường bạn đã đặt trong environment.yml nếu khác.
20
+ # Thêm --force để đảm bảo ghi đè môi trường cũ nếu có (hữu ích khi build lại).
21
+ RUN conda env create -f environment.yml --force && \
22
+ # Dọn dẹp cache của Conda để giảm kích thước image cuối cùng
23
+ conda clean -afy
24
+
25
+ # Bước 5: Kích hoạt môi trường Conda cho tất cả các lệnh RUN, CMD, ENTRYPOINT tiếp theo
26
+ # Tên môi trường "myapp-env" phải khớp với tên trong environment.yml
27
+ SHELL ["conda", "run", "-n", "myapp-env", "/bin/bash", "-c"]
28
+
29
+ # Bước 6: Cài đặt PyTorch, torchvision, torchaudio với GPU bằng pip và index URL cụ thể
30
+ # QUAN TRỌNG: XÁC MINH LẠI URL VÀ HẬU TỐ CUDA (ví dụ: `cu121` thay vì `cu126` nếu đó là chuẩn).
31
+ # URL bạn cung cấp: --index-url https://download.pytorch.org/whl/cu126
32
+ # Lệnh này sẽ tìm các wheel phù hợp với Python và kiến trúc trên index đó.
33
+ RUN echo "Bắt đầu cài đặt PyTorch, torchvision, torchaudio với GPU..." && \
34
+ pip install --no-cache-dir torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu126 && \
35
+ echo "Đã cài đặt PyTorch, torchvision, torchaudio."
36
+
37
+ # Bước 7: Bước xác thực cài đặt (RẤT QUAN TRỌNG để gỡ lỗi trên Spaces)
38
+ # Bước này sẽ in ra thông tin về môi trường, giúp bạn kiểm tra xem mọi thứ có đúng không.
39
+ RUN echo "--- KIỂM TRA MÔI TRƯỜNG SAU KHI CÀI ĐẶT ---" && \
40
+ echo "Đường dẫn Conda:" && which conda && \
41
+ echo "Đường dẫn Python:" && which python && \
42
+ echo "Phiên bản Python:" && python --version && \
43
+ echo "--- Thông tin PyTorch: ---" && \
44
+ python -c "import torch; print(f'PyTorch version: {torch.__version__}'); print(f'CUDA available for PyTorch: {torch.cuda.is_available()}'); print(f'PyTorch built with CUDA version: {torch.version.cuda if torch.cuda.is_available() else 'N/A'}'); print(f'cuDNN version: {torch.backends.cudnn.version() if torch.cuda.is_available() and torch.backends.cudnn.is_available() else 'N/A'}'); print(f'Number of GPUs available to PyTorch: {torch.cuda.device_count()}')" && \
45
+ echo "--- Thông tin Faiss: ---" && \
46
+ python -c "import faiss; print(f'Faiss version: {faiss.__version__}'); print(f'Number of GPUs available to Faiss: {faiss.get_num_gpus()}')" && \
47
+ echo "--- Danh sách một số gói pip quan trọng: ---" && \
48
+ pip list | grep -E 'gradio|torch|faiss|unsloth|sentence-transformers|transformers|numpy|rank_bm25|huggingface_hub' && \
49
+ echo "--- KẾT THÚC KIỂM TRA MÔI TRƯỜNG ---"
50
+
51
+ # Bước 8: Sao chép toàn bộ code ứng dụng của bạn (app.py, retrieval.py, v.v.)
52
+ # và các thư mục con (data/, models/ - nếu bạn tải model lên trực tiếp)
53
+ # vào thư mục /app bên trong container.
54
+ # Hãy tạo file .dockerignore để loại bỏ các file không cần thiết (ví dụ: .git, __pycache__, .venv)
55
+ COPY . .
56
+
57
+ # Bước 9: (Tùy chọn) Thiết lập các biến môi trường mà ứng dụng của bạn có thể cần
58
+ # Ví dụ:
59
+ # ENV MY_VARIABLE="my_value"
60
+ # ENV GRADIO_SERVER_NAME="0.0.0.0" # Thường Gradio tự xử lý
61
+ # ENV GRADIO_SERVER_PORT="7860" # Thường Gradio tự xử lý
62
+
63
+ # Bước 10: Thiết lập lệnh mặc định để chạy ứng dụng của bạn
64
+ # Điều này giả định rằng app.py của bạn khởi chạy server Gradio.
65
+ CMD ["python", "app.py"]
app.py ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import torch # Cần cho việc kiểm tra CUDA và device
3
+ # Import các hàm và lớp từ các file của bạn
4
+ from retrieval import (
5
+ process_law_data_to_chunks,
6
+ # VEHICLE_TYPE_MAP, # Có thể không cần import trực tiếp nếu chỉ dùng trong retrieval.py
7
+ # get_standardized_vehicle_type, # Tương tự
8
+ # analyze_query, # Được gọi bởi search_relevant_laws
9
+ tokenize_vi_for_bm25_setup, # Cần cho BM25
10
+ search_relevant_laws
11
+ )
12
+ from llm_handler import generate_response # Giả sử hàm này đã được điều chỉnh để nhận model, tokenizer, etc.
13
+ from sentence_transformers import SentenceTransformer
14
+ import faiss
15
+ from rank_bm25 import BM25Okapi
16
+ import json
17
+ from unsloth import FastLanguageModel # Từ llm_handler.py hoặc import trực tiếp nếu logic tải model ở đây
18
+
19
+ # --- KHỞI TẠO MỘT LẦN KHI APP KHỞI ĐỘNG ---
20
+ # Đường dẫn (điều chỉnh nếu cần, có thể dùng os.path.join)
21
+ JSON_FILE_PATH = "data/luat_chi_tiet_output_openai_sdk_final_cleaned.json"
22
+ FAISS_INDEX_PATH = "data/my_law_faiss_flatip_normalized.index"
23
+ LLM_MODEL_PATH = "models/lora_model_base" # Hoặc đường dẫn cục bộ
24
+ EMBEDDING_MODEL_PATH = "models/embedding_model"
25
+
26
+ # 1. Tải và xử lý dữ liệu luật
27
+ print("Loading and processing law data...")
28
+ try:
29
+ with open(JSON_FILE_PATH, 'r', encoding='utf-8') as f:
30
+ raw_data_from_file = json.load(f)
31
+ chunks_data = process_law_data_to_chunks(raw_data_from_file)
32
+ print(f"Loaded {len(chunks_data)} chunks.")
33
+ if not chunks_data:
34
+ raise ValueError("Chunks data is empty after processing.")
35
+ except Exception as e:
36
+ print(f"Error loading/processing law data: {e}")
37
+ chunks_data = [] # Hoặc xử lý lỗi khác
38
+
39
+ # 2. Tải mô hình embedding
40
+ print(f"Loading embedding model: {EMBEDDING_MODEL_PATH}...")
41
+ device = "cuda" if torch.cuda.is_available() else "cpu"
42
+ try:
43
+ embedding_model = SentenceTransformer(EMBEDDING_MODEL_PATH, device=device)
44
+ print("Embedding model loaded successfully.")
45
+ except Exception as e:
46
+ print(f"Error loading embedding model: {e}")
47
+ embedding_model = None # Xử lý lỗi
48
+
49
+ # 3. Tải FAISS index
50
+ print(f"Loading FAISS index from: {FAISS_INDEX_PATH}...")
51
+ try:
52
+ faiss_index = faiss.read_index(FAISS_INDEX_PATH)
53
+ print(f"FAISS index loaded. Total vectors: {faiss_index.ntotal}")
54
+ except Exception as e:
55
+ print(f"Error loading FAISS index: {e}")
56
+ faiss_index = None # Xử lý lỗi
57
+
58
+ # 4. Tạo BM25 model
59
+ print("Creating BM25 model...")
60
+ bm25_model = None
61
+ if chunks_data:
62
+ try:
63
+ corpus_texts_for_bm25 = [chunk.get('text', '') for chunk in chunks_data]
64
+ tokenized_corpus_bm25 = [tokenize_vi_for_bm25_setup(text) for text in corpus_texts_for_bm25]
65
+ bm25_model = BM25Okapi(tokenized_corpus_bm25)
66
+ print("BM25 model created successfully.")
67
+ except Exception as e:
68
+ print(f"Error creating BM25 model: {e}")
69
+ else:
70
+ print("Skipping BM25 model creation as chunks_data is empty.")
71
+
72
+
73
+ # 5. Tải mô hình LLM và tokenizer (sử dụng Unsloth)
74
+ print(f"Loading LLM model: {LLM_MODEL_PATH}...")
75
+ try:
76
+ # Nên đặt logic tải model LLM vào llm_handler.py và gọi hàm đó ở đây
77
+ # Hoặc trực tiếp:
78
+ llm_model, llm_tokenizer = FastLanguageModel.from_pretrained(
79
+ model_name=LLM_MODEL_PATH, # Đường dẫn tới model đã fine-tune
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) # Tối ưu cho inference
85
+ print("LLM model and tokenizer loaded successfully.")
86
+ except Exception as e:
87
+ print(f"Error loading LLM model: {e}")
88
+ llm_model = None
89
+ llm_tokenizer = None
90
+ # --- KẾT THÚC KHỞI TẠO MỘT LẦN ---
91
+
92
+ # Hàm respond mới sẽ sử dụng các model và data đã tải ở trên
93
+ def respond(message, history: list[tuple[str, str]]):
94
+ if not all([chunks_data, embedding_model, faiss_index, bm25_model, llm_model, llm_tokenizer]):
95
+ # Ghi log chi tiết hơn ở đây nếu cần để biết thành phần nào bị thiếu
96
+ missing_components = []
97
+ if not chunks_data: missing_components.append("chunks_data")
98
+ if not embedding_model: missing_components.append("embedding_model")
99
+ if not faiss_index: missing_components.append("faiss_index")
100
+ if not bm25_model: missing_components.append("bm25_model")
101
+ if not llm_model: missing_components.append("llm_model")
102
+ if not llm_tokenizer: missing_components.append("llm_tokenizer")
103
+ error_msg = f"Lỗi: Một hoặc nhiều thành phần của hệ thống chưa được khởi tạo thành công. Thành phần thiếu: {', '.join(missing_components)}. Vui lòng kiểm tra logs của Space."
104
+ print(error_msg) # In ra console log của Space
105
+ return error_msg # Trả về cho người dùng
106
+
107
+ try:
108
+ response_text = generate_response(
109
+ query=message,
110
+ llama_model=llm_model,
111
+ tokenizer=llm_tokenizer,
112
+ faiss_index=faiss_index,
113
+ embed_model=embedding_model,
114
+ chunks_data_list=chunks_data,
115
+ bm25_model=bm25_model,
116
+ search_function=search_relevant_laws # << RẤT QUAN TRỌNG: Đã thêm tham số này
117
+ # Bạn có thể truyền thêm các tham số search_k, search_multiplier,
118
+ # rrf_k_constant, max_new_tokens, temperature, etc. vào đây
119
+ # nếu bạn muốn ghi đè giá trị mặc định trong llm_handler.generate_response
120
+ # Ví dụ:
121
+ # search_k=5,
122
+ # max_new_tokens=768
123
+ )
124
+ yield response_text
125
+
126
+ except Exception as e:
127
+ # Ghi log lỗi chi tiết hơn
128
+ import traceback
129
+ print(f"Error during response generation for query '{message}': {e}")
130
+ print(traceback.format_exc()) # In stack trace để debug
131
+ yield f"Đã xảy ra lỗi nghiêm trọng khi xử lý yêu cầu của bạn. Vui lòng thử lại sau hoặc liên hệ quản trị viên."
132
+
133
+ # Giao diện Gradio
134
+ # Bỏ các additional_inputs không cần thiết nếu chúng được xử lý bên trong generate_response
135
+ # hoặc nếu bạn không muốn người dùng cuối thay đổi chúng.
136
+ demo = gr.ChatInterface(
137
+ respond,
138
+ # additional_inputs=[ # Bạn có thể thêm lại nếu muốn người dùng tùy chỉnh
139
+ # gr.Textbox(value="You are a helpful Law Chatbot.", label="System message"), # Ví dụ
140
+ # ]
141
+ )
142
+
143
+ if __name__ == "__main__":
144
+ demo.launch()
data/luat_tong_hop_chunks_theo_khoan_updated.json ADDED
The diff for this file is too large to render. See raw diff
 
data/my_law_faiss_flatip_normalized.index ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:378937c6e14ac44d9602a831ce58c91176e2974ad82d3ff6179e6531d8cd2fb8
3
+ size 7526445
environment.yml ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # environment.yml
2
+ name: myapp-env
3
+ channels:
4
+ - pytorch
5
+ - nvidia # Quan trọng cho cudatoolkit
6
+ - conda-forge
7
+ - defaults
8
+ dependencies:
9
+ - python=3.11.12 # Hoặc phiên bản Python của bạn
10
+ # --- Các gói Conda ---
11
+ # Yêu cầu faiss với hỗ trợ GPU cho Linux từ conda-forge
12
+ # Conda sẽ cố gắng tìm bản build faiss-gpu hoặc faiss kéo theo cudatoolkit
13
+ # có phiên bản CUDA tương thích với PyTorch bạn sẽ cài.
14
+ - conda-forge::faiss-gpu # Đây là cách gọi phổ biến cho Linux
15
+ # Hoặc bạn có thể thử chỉ 'conda-forge::faiss' và xem nó có tự động kéo cudatoolkit không.
16
+ # Để chắc chắn, bạn có thể chỉ định cudatoolkit:
17
+ # - conda-forge::faiss-gpu cudatoolkit=12.1 # Thay 12.1 bằng phiên bản CUDA PyTorch của bạn sẽ dùng
18
+ # # (ví dụ, nếu pip install torch ... --index-url .../whl/cu121)
19
+ # ... các gói conda khác ...
20
+ - pip
21
+ - pip:
22
+ - gradio
23
+ - sentence-transformers
24
+ - numpy
25
+ - unsloth
26
+ - transformers
27
+ - rank_bm25
28
+ - huggingface_hub
29
+ # KHÔNG có torch ở đây, sẽ cài trong Dockerfile
30
+ # KHÔNG có faiss ở đây
llm_handler.py ADDED
@@ -0,0 +1,296 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # Giả định rằng hàm search_relevant_laws được import từ file retrieval.py
10
+ # Nếu file retrieval.py nằm cùng cấp, bạn có thể import như sau:
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
+ llama_model, # Mô hình LLM đã tải
56
+ tokenizer, # Tokenizer tương ứng
57
+ # Các thành phần RAG được truyền từ app.py (đã được tải trước đó)
58
+ faiss_index,
59
+ embed_model,
60
+ chunks_data_list: list,
61
+ bm25_model,
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
+ Truy xuất ngữ cảnh bằng hàm search_relevant_laws (được truyền vào)
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(f"\n--- [LLM Handler] Bắt đầu xử lý query: '{query}' ---")
101
+
102
+ # === 1. Truy xuất ngữ cảnh (Sử dụng hàm search_function được truyền vào) ===
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
+ Nhiệm vụ của bạn là 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, chi tiết và dễ hiểu.
190
+ Nếu thông tin không đủ hoặc không có trong các trích dẫn được cung cấp, 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 được cung cấp.
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}
195
+
196
+ ### Câu hỏi của người dùng:
197
+ {query}
198
+
199
+ ### Trả lời của bạn:"""
200
+
201
+ # print("\n--- [LLM Handler] Prompt hoàn chỉnh (một phần) ---\n", prompt[:1000] + "...")
202
+
203
+ # === 4. Tạo câu trả lời từ LLM ===
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
+ top_k=top_k,
213
+ repetition_penalty=repetition_penalty,
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
+ # # Tùy chọn: Sử dụng TextStreamer nếu bạn muốn stream từng token (cần sửa đổi hàm này để yield)
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 trong quá trình LLM generating: {e}")
239
+ return "Xin lỗi, đã có lỗi xảy ra trong quá trình tạo câu trả lời từ mô hình ngôn ngữ."
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
models/embedding_model/1_Pooling/config.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fb410fd9c2ed3e3b66206997397b0cf0eff574b2c690071481cf80a77d3c11fa
3
+ size 305
models/embedding_model/README.md ADDED
@@ -0,0 +1,168 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ pipeline_tag: sentence-similarity
3
+ tags:
4
+ - sentence-transformers
5
+ - feature-extraction
6
+ - sentence-similarity
7
+ - transformers
8
+ library_name: generic
9
+ language:
10
+ - vi
11
+ widget:
12
+ - source_sentence: Làm thế nào Đại học Bách khoa Hà Nội thu hút sinh viên quốc tế?
13
+ sentences:
14
+ - >-
15
+ Đại học Bách khoa Hà Nội đã phát triển các chương trình đào tạo bằng tiếng
16
+ Anh để làm cho việc học tại đây dễ dàng hơn cho sinh viên quốc tế.
17
+ - >-
18
+ Môi trường học tập đa dạng và sự hỗ trợ đầy đủ cho sinh viên quốc tế tại Đại
19
+ học Bách khoa Hà Nội giúp họ thích nghi nhanh chóng.
20
+ - Hà Nội có khí hậu mát mẻ vào mùa thu.
21
+ - Các món ăn ở Hà Nội rất ngon và đa dạng.
22
+ license: apache-2.0
23
+ ---
24
+
25
+ # bkai-foundation-models/vietnamese-bi-encoder
26
+
27
+ This is a [sentence-transformers](https://www.SBERT.net) model: It maps sentences & paragraphs to a 768 dimensional dense vector space and can be used for tasks like clustering or semantic search.
28
+
29
+ We train the model on a merged training dataset that consists of:
30
+ - MS Macro (translated into Vietnamese)
31
+ - SQuAD v2 (translated into Vietnamese)
32
+ - 80% of the training set from the Legal Text Retrieval Zalo 2021 challenge
33
+
34
+ We use [phobert-base-v2](https://github.com/VinAIResearch/PhoBERT) as the pre-trained backbone.
35
+
36
+ Here are the results on the remaining 20% of the training set from the Legal Text Retrieval Zalo 2021 challenge:
37
+
38
+ | Pretrained Model | Training Datasets | Acc@1 | Acc@10 | Acc@100 | Pre@10 | MRR@10 |
39
+ |-------------------------------|---------------------------------------|:------------:|:-------------:|:--------------:|:-------------:|:-------------:|
40
+ | [Vietnamese-SBERT](https://huggingface.co/keepitreal/vietnamese-sbert) | - | 32.34 | 52.97 | 89.84 | 7.05 | 45.30 |
41
+ | PhoBERT-base-v2 | MSMACRO | 47.81 | 77.19 | 92.34 | 7.72 | 58.37 |
42
+ | PhoBERT-base-v2 | MSMACRO + SQuADv2.0 + 80% Zalo | 73.28 | 93.59 | 98.85 | 9.36 | 80.73 |
43
+
44
+
45
+ <!--- Describe your model here -->
46
+
47
+ ## Usage (Sentence-Transformers)
48
+
49
+ Using this model becomes easy when you have [sentence-transformers](https://www.SBERT.net) installed:
50
+
51
+ ```
52
+ pip install -U sentence-transformers
53
+ ```
54
+
55
+ Then you can use the model like this:
56
+
57
+ ```python
58
+ from sentence_transformers import SentenceTransformer
59
+
60
+ # INPUT TEXT MUST BE ALREADY WORD-SEGMENTED!
61
+ sentences = ["Cô ấy là một người vui_tính .", "Cô ấy cười nói suốt cả ngày ."]
62
+
63
+ model = SentenceTransformer('bkai-foundation-models/vietnamese-bi-encoder')
64
+ embeddings = model.encode(sentences)
65
+ print(embeddings)
66
+ ```
67
+
68
+
69
+ ## Usage (Widget HuggingFace)
70
+ The widget use custom pipeline on top of the default pipeline by adding additional word segmenter before PhobertTokenizer. So you do not need to segment words before using the API:
71
+
72
+ An example could be seen in Hosted inference API.
73
+
74
+
75
+ ## Usage (HuggingFace Transformers)
76
+
77
+ Without [sentence-transformers](https://www.SBERT.net), you can use the model like this: First, you pass your input through the transformer model, then you have to apply the right pooling-operation on-top of the contextualized word embeddings.
78
+
79
+ ```python
80
+ from transformers import AutoTokenizer, AutoModel
81
+ import torch
82
+
83
+
84
+ #Mean Pooling - Take attention mask into account for correct averaging
85
+ def mean_pooling(model_output, attention_mask):
86
+ token_embeddings = model_output[0] #First element of model_output contains all token embeddings
87
+ input_mask_expanded = attention_mask.unsqueeze(-1).expand(token_embeddings.size()).float()
88
+ return torch.sum(token_embeddings * input_mask_expanded, 1) / torch.clamp(input_mask_expanded.sum(1), min=1e-9)
89
+
90
+
91
+ # Sentences we want sentence embeddings, we could use pyvi, underthesea, RDRSegment to segment words
92
+ sentences = ['Cô ấy là một người vui_tính .', 'Cô ấy cười nói suốt cả ngày .']
93
+
94
+ # Load model from HuggingFace Hub
95
+ tokenizer = AutoTokenizer.from_pretrained('bkai-foundation-models/vietnamese-bi-encoder')
96
+ model = AutoModel.from_pretrained('bkai-foundation-models/vietnamese-bi-encoder')
97
+
98
+ # Tokenize sentences
99
+ encoded_input = tokenizer(sentences, padding=True, truncation=True, return_tensors='pt')
100
+
101
+ # Compute token embeddings
102
+ with torch.no_grad():
103
+ model_output = model(**encoded_input)
104
+
105
+ # Perform pooling. In this case, mean pooling.
106
+ sentence_embeddings = mean_pooling(model_output, encoded_input['attention_mask'])
107
+
108
+ print("Sentence embeddings:")
109
+ print(sentence_embeddings)
110
+ ```
111
+
112
+ ## Training
113
+
114
+ The model was trained with the parameters:
115
+
116
+ **DataLoader**:
117
+
118
+ `torch.utils.data.dataloader.DataLoader` of length 17584 with parameters:
119
+
120
+ ```
121
+ {'batch_size': 32, 'sampler': 'torch.utils.data.sampler.RandomSampler', 'batch_sampler': 'torch.utils.data.sampler.BatchSampler'}
122
+ ```
123
+
124
+ **Loss**:
125
+
126
+ `sentence_transformers.losses.MultipleNegativesRankingLoss.MultipleNegativesRankingLoss` with parameters:
127
+
128
+ ```
129
+ {'scale': 20.0, 'similarity_fct': 'cos_sim'}
130
+ ```
131
+
132
+ Parameters of the fit()-Method:
133
+
134
+ ```
135
+ {
136
+ "epochs": 15,
137
+ "evaluation_steps": 0,
138
+ "evaluator": "NoneType",
139
+ "max_grad_norm": 1,
140
+ "optimizer_class": "<class 'torch.optim.adamw.AdamW'>",
141
+ "optimizer_params": {
142
+ "lr": 2e-05
143
+ },
144
+ "scheduler": "WarmupLinear",
145
+ "steps_per_epoch": null,
146
+ "warmup_steps": 1000,
147
+ "weight_decay": 0.01
148
+ }
149
+ ```
150
+
151
+ ## Full Model Architecture
152
+
153
+ ```
154
+ SentenceTransformer(
155
+ (0): Transformer({'max_seq_length': 256, 'do_lower_case': False}) with Transformer model: RobertaModel
156
+ (1): Pooling({'word_embedding_dimension': 768, 'pooling_mode_cls_token': False, 'pooling_mode_mean_tokens': True, 'pooling_mode_max_tokens': False, 'pooling_mode_mean_sqrt_len_tokens': False, 'pooling_mode_weightedmean_tokens': False, 'pooling_mode_lasttoken': False})
157
+ )
158
+ ```
159
+
160
+ ### Please cite our manuscript if this dataset is used for your work
161
+ ```
162
+ @article{duc2024towards,
163
+ title={Towards Comprehensive Vietnamese Retrieval-Augmented Generation and Large Language Models},
164
+ author={Nguyen Quang Duc, Le Hai Son, Nguyen Duc Nhan, Nguyen Dich Nhat Minh, Le Thanh Huong, Dinh Viet Sang},
165
+ journal={arXiv preprint arXiv:2403.01616},
166
+ year={2024}
167
+ }
168
+ ```
models/embedding_model/added_tokens.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6887f87ac991379ea91aedb4dd5e1af4f6ee38693ec0ca1c2b6209559ce283d8
3
+ size 25
models/embedding_model/bpe.codes ADDED
The diff for this file is too large to render. See raw diff
 
models/embedding_model/config.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3af0fd876ee0aaaef684c5a2ad27e3e280b1593b127ed9ccefa7b0d81326de75
3
+ size 699
models/embedding_model/config_sentence_transformers.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8010f6b1a201d350cecd92317f85096a0b0e59ca922783bdb06a535c44638507
3
+ size 214
models/embedding_model/model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e681accadaec87e79901db0c3f68e33d996cba334633b6dd0b2483dba4f398e0
3
+ size 540015464
models/embedding_model/modules.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:27e3a229cecaf4d6ec90fb8e439d6bd2da7b2e22ff49a23e0b0a293a5f3e413c
3
+ size 242
models/embedding_model/sentence_bert_config.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:01d1055f90dbf0425135dbb95d2ef43f77c49802faec5a20fea87637dda4ea51
3
+ size 56
models/embedding_model/special_tokens_map.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:edd71739099fe63dc2f70815facad5253c70ded0e0d4df49ef883ce4511af365
3
+ size 1016
models/embedding_model/tokenizer_config.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:55f35d28e4d476184f88ae52cca59389c50de91547f9fa2f31eec661080f6032
3
+ size 1229
models/embedding_model/vocab.txt ADDED
The diff for this file is too large to render. See raw diff
 
models/lora_model_base/README.md ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ base_model: unsloth/llama-3.2-3b-instruct-unsloth-bnb-4bit
3
+ library_name: peft
4
+ ---
5
+
6
+ # Model Card for Model ID
7
+
8
+ <!-- Provide a quick summary of what the model is/does. -->
9
+
10
+
11
+
12
+ ## Model Details
13
+
14
+ ### Model Description
15
+
16
+ <!-- Provide a longer summary of what this model is. -->
17
+
18
+
19
+
20
+ - **Developed by:** [More Information Needed]
21
+ - **Funded by [optional]:** [More Information Needed]
22
+ - **Shared by [optional]:** [More Information Needed]
23
+ - **Model type:** [More Information Needed]
24
+ - **Language(s) (NLP):** [More Information Needed]
25
+ - **License:** [More Information Needed]
26
+ - **Finetuned from model [optional]:** [More Information Needed]
27
+
28
+ ### Model Sources [optional]
29
+
30
+ <!-- Provide the basic links for the model. -->
31
+
32
+ - **Repository:** [More Information Needed]
33
+ - **Paper [optional]:** [More Information Needed]
34
+ - **Demo [optional]:** [More Information Needed]
35
+
36
+ ## Uses
37
+
38
+ <!-- Address questions around how the model is intended to be used, including the foreseeable users of the model and those affected by the model. -->
39
+
40
+ ### Direct Use
41
+
42
+ <!-- This section is for the model use without fine-tuning or plugging into a larger ecosystem/app. -->
43
+
44
+ [More Information Needed]
45
+
46
+ ### Downstream Use [optional]
47
+
48
+ <!-- This section is for the model use when fine-tuned for a task, or when plugged into a larger ecosystem/app -->
49
+
50
+ [More Information Needed]
51
+
52
+ ### Out-of-Scope Use
53
+
54
+ <!-- This section addresses misuse, malicious use, and uses that the model will not work well for. -->
55
+
56
+ [More Information Needed]
57
+
58
+ ## Bias, Risks, and Limitations
59
+
60
+ <!-- This section is meant to convey both technical and sociotechnical limitations. -->
61
+
62
+ [More Information Needed]
63
+
64
+ ### Recommendations
65
+
66
+ <!-- This section is meant to convey recommendations with respect to the bias, risk, and technical limitations. -->
67
+
68
+ Users (both direct and downstream) should be made aware of the risks, biases and limitations of the model. More information needed for further recommendations.
69
+
70
+ ## How to Get Started with the Model
71
+
72
+ Use the code below to get started with the model.
73
+
74
+ [More Information Needed]
75
+
76
+ ## Training Details
77
+
78
+ ### Training Data
79
+
80
+ <!-- This should link to a Dataset Card, perhaps with a short stub of information on what the training data is all about as well as documentation related to data pre-processing or additional filtering. -->
81
+
82
+ [More Information Needed]
83
+
84
+ ### Training Procedure
85
+
86
+ <!-- This relates heavily to the Technical Specifications. Content here should link to that section when it is relevant to the training procedure. -->
87
+
88
+ #### Preprocessing [optional]
89
+
90
+ [More Information Needed]
91
+
92
+
93
+ #### Training Hyperparameters
94
+
95
+ - **Training regime:** [More Information Needed] <!--fp32, fp16 mixed precision, bf16 mixed precision, bf16 non-mixed precision, fp16 non-mixed precision, fp8 mixed precision -->
96
+
97
+ #### Speeds, Sizes, Times [optional]
98
+
99
+ <!-- This section provides information about throughput, start/end time, checkpoint size if relevant, etc. -->
100
+
101
+ [More Information Needed]
102
+
103
+ ## Evaluation
104
+
105
+ <!-- This section describes the evaluation protocols and provides the results. -->
106
+
107
+ ### Testing Data, Factors & Metrics
108
+
109
+ #### Testing Data
110
+
111
+ <!-- This should link to a Dataset Card if possible. -->
112
+
113
+ [More Information Needed]
114
+
115
+ #### Factors
116
+
117
+ <!-- These are the things the evaluation is disaggregating by, e.g., subpopulations or domains. -->
118
+
119
+ [More Information Needed]
120
+
121
+ #### Metrics
122
+
123
+ <!-- These are the evaluation metrics being used, ideally with a description of why. -->
124
+
125
+ [More Information Needed]
126
+
127
+ ### Results
128
+
129
+ [More Information Needed]
130
+
131
+ #### Summary
132
+
133
+
134
+
135
+ ## Model Examination [optional]
136
+
137
+ <!-- Relevant interpretability work for the model goes here -->
138
+
139
+ [More Information Needed]
140
+
141
+ ## Environmental Impact
142
+
143
+ <!-- Total emissions (in grams of CO2eq) and additional considerations, such as electricity usage, go here. Edit the suggested text below accordingly -->
144
+
145
+ Carbon emissions can be estimated using the [Machine Learning Impact calculator](https://mlco2.github.io/impact#compute) presented in [Lacoste et al. (2019)](https://arxiv.org/abs/1910.09700).
146
+
147
+ - **Hardware Type:** [More Information Needed]
148
+ - **Hours used:** [More Information Needed]
149
+ - **Cloud Provider:** [More Information Needed]
150
+ - **Compute Region:** [More Information Needed]
151
+ - **Carbon Emitted:** [More Information Needed]
152
+
153
+ ## Technical Specifications [optional]
154
+
155
+ ### Model Architecture and Objective
156
+
157
+ [More Information Needed]
158
+
159
+ ### Compute Infrastructure
160
+
161
+ [More Information Needed]
162
+
163
+ #### Hardware
164
+
165
+ [More Information Needed]
166
+
167
+ #### Software
168
+
169
+ [More Information Needed]
170
+
171
+ ## Citation [optional]
172
+
173
+ <!-- If there is a paper or blog post introducing the model, the APA and Bibtex information for that should go in this section. -->
174
+
175
+ **BibTeX:**
176
+
177
+ [More Information Needed]
178
+
179
+ **APA:**
180
+
181
+ [More Information Needed]
182
+
183
+ ## Glossary [optional]
184
+
185
+ <!-- If relevant, include terms and calculations in this section that can help readers understand the model or model card. -->
186
+
187
+ [More Information Needed]
188
+
189
+ ## More Information [optional]
190
+
191
+ [More Information Needed]
192
+
193
+ ## Model Card Authors [optional]
194
+
195
+ [More Information Needed]
196
+
197
+ ## Model Card Contact
198
+
199
+ [More Information Needed]
200
+ ### Framework versions
201
+
202
+ - PEFT 0.15.0
models/lora_model_base/adapter_config.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8aeb2d2885fc709fb0e526d2cc01969910c0b284c151899369c0cb6b0d55a862
3
+ size 914
models/lora_model_base/adapter_model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0528f0d3cff8cde7d2ac7cda02a9f50a384ad836eff4d60bff86fe3cbb9a6060
3
+ size 97307544
models/lora_model_base/special_tokens_map.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8e4e823b62ca673865ac60b203c51d0d3f0f4e21f806323cd7d35616cb457e0d
3
+ size 477
models/lora_model_base/tokenizer.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6b9e4e7fb171f92fd137b777cc2714bf87d11576700a1dcd7a399e7bbe39537b
3
+ size 17209920
models/lora_model_base/tokenizer_config.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d08d598958a22a2a5ea166e5e4e055e9c3caa9a52fae77c0f7fb45e835fad479
3
+ size 56738
retrieval.py ADDED
@@ -0,0 +1,579 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 đủ. ---")
utils.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # utils.py
2
+
3
+ import re
4
+ from typing import List
5
+
6
+ def tokenize_vi_simple(text: str) -> List[str]:
7
+ """
8
+ Tokenizes Vietnamese text simply for tasks like BM25.
9
+ Converts to lowercase, removes basic punctuation, and splits by whitespace.
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
+ # Remove characters that are not alphanumeric or whitespace
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)