deddoggo commited on
Commit
c69c2f9
·
1 Parent(s): 845a94d

update full version

Browse files
.gitattributes CHANGED
@@ -33,3 +33,5 @@ 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
+ *.index filter=lfs diff=lfs merge=lfs -text
app.py CHANGED
@@ -1,358 +1,144 @@
1
- # app.py
2
- # File triển khai hoàn chỉnh cho đồ án Chatbot Luật Giao thông
3
- # Tác giả: (Tên của bạn)
4
- # Ngày: (Ngày bạn tạo)
5
-
6
- # --- PHẦN 1: IMPORT CÁC THƯ VIỆN CẦN THIẾT ---
7
- print("Bắt đầu import các thư viện...")
8
- import os
9
- import sys
10
- import json
11
- import re
12
- import time
13
- from collections import defaultdict
14
-
15
- # Core ML/DL và Unsloth
16
- import torch
17
- from unsloth import FastLanguageModel
18
- from transformers import TextStreamer
19
-
20
- # RAG - Retrieval
21
- import faiss
22
  from sentence_transformers import SentenceTransformer
 
23
  from rank_bm25 import BM25Okapi
24
- import numpy as np
25
-
26
- # Deployment
27
- import gradio as gr
28
-
29
- print("✅ Import thư viện thành công.")
30
-
31
- # --- PHẦN 2: CẤU HÌNH TẢI TÀI NGUYÊN (MODELS & DATA) ---
32
- # Phần này sẽ chỉ chạy một lần khi ứng dụng khởi động.
33
-
34
- # Cấu hình hình
35
- MAX_SEQ_LENGTH = 2048
36
- DTYPE = None
37
- LOAD_IN_4BIT = True
38
- EMBEDDING_MODEL_NAME = "bkai-foundation-models/vietnamese-bi-encoder"
39
- LLM_MODEL_NAME = "unsloth/Llama-3.2-3B-Instruct-bnb-4bit"
40
- LAW_DATA_FILE = "luat_chi_tiet_output_openai_sdk_final_cleaned.json"
41
-
42
- # Biến toàn cục để lưu các tài nguyên đã tải
43
- # Điều này giúp tránh việc phải tải lại mô hình mỗi khi người dùng gửi yêu cầu.
44
- MODELS_AND_DATA = {
45
- "llm_model": None,
46
- "tokenizer": None,
47
- "embedding_model": None,
48
- "faiss_index": None,
49
- "bm25_model": None,
50
- "chunks_data": None,
51
- "tokenized_corpus_bm25": None,
52
- }
53
-
54
- # --- Các hàm xử lý dữ liệu (từ các notebook của bạn) ---
55
-
56
- def process_law_data_to_chunks(structured_data_input):
57
- """
58
- Hàm làm phẳng dữ liệu luật có cấu trúc chi tiết thành danh sách các chunks.
59
- Mỗi chunk chứa 'text' và 'metadata'.
60
- """
61
- flat_list = []
62
- articles_list = []
63
- if isinstance(structured_data_input, dict) and "article" in structured_data_input:
64
- articles_list = [structured_data_input]
65
- elif isinstance(structured_data_input, list):
66
- articles_list = structured_data_input
67
- else:
68
- print("Lỗi: Dữ liệu đầu vào không hợp lệ.")
69
- return flat_list
70
-
71
- for article_data in articles_list:
72
- if not isinstance(article_data, dict): continue
73
- article_metadata_base = {
74
- "source_document": article_data.get("source_document"),
75
- "article": article_data.get("article"),
76
- "article_title": article_data.get("article_title")
77
- }
78
- clauses = article_data.get("clauses", [])
79
- if not isinstance(clauses, list): continue
80
-
81
- for clause_data in clauses:
82
- if not isinstance(clause_data, dict): continue
83
- clause_metadata_base = article_metadata_base.copy()
84
- clause_metadata_base.update({
85
- "clause_number": clause_data.get("clause_number"),
86
- "clause_metadata_summary": clause_data.get("clause_metadata_summary")
87
- })
88
- points_in_clause = clause_data.get("points_in_clause", [])
89
- if not isinstance(points_in_clause, list): continue
90
-
91
- if points_in_clause:
92
- for point_data in points_in_clause:
93
- if not isinstance(point_data, dict): continue
94
- chunk_text = point_data.get("point_text_original") or point_data.get("violation_description_summary")
95
- if not chunk_text: continue
96
-
97
- current_point_metadata = clause_metadata_base.copy()
98
- point_specific_metadata = point_data.copy()
99
- if "point_text_original" in point_specific_metadata:
100
- del point_specific_metadata["point_text_original"]
101
- current_point_metadata.update(point_specific_metadata)
102
- final_metadata_cleaned = {k: v for k, v in current_point_metadata.items() if v is not None}
103
- flat_list.append({"text": chunk_text, "metadata": final_metadata_cleaned})
104
- else:
105
- chunk_text = clause_data.get("clause_text_original")
106
- if chunk_text:
107
- current_clause_metadata = clause_metadata_base.copy()
108
- additional_clause_info = {k: v for k, value in clause_data.items() if k not in ["clause_text_original", "points_in_clause", "clause_number", "clause_metadata_summary"]}
109
- if additional_clause_info:
110
- current_clause_metadata.update(additional_clause_info)
111
- final_metadata_cleaned = {k: v for k, v in current_clause_metadata.items() if v is not None}
112
- flat_list.append({"text": chunk_text, "metadata": final_metadata_cleaned})
113
- return flat_list
114
-
115
- def tokenize_vi_for_bm25(text):
116
- """Hàm tokenize tiếng Việt đơn giản cho BM25."""
117
- text = text.lower()
118
- text = re.sub(r'[^\w\s]', '', text)
119
- return text.split()
120
-
121
- def load_all_resources():
122
- """
123
- Hàm chính để tải tất cả mô hình và dữ liệu cần thiết.
124
- Chỉ chạy một lần khi ứng dụng khởi động.
125
- """
126
- print("--- Bắt đầu quá trình tải tài nguyên ---")
127
-
128
- # 1. Tải mô hình LLM và Tokenizer
129
- print(f"1. Đang tải LLM và Tokenizer: {LLM_MODEL_NAME}...")
130
- llm_model, tokenizer = FastLanguageModel.from_pretrained(
131
- model_name=LLM_MODEL_NAME,
132
- max_seq_length=MAX_SEQ_LENGTH,
133
- dtype=DTYPE,
134
- load_in_4bit=LOAD_IN_4BIT,
135
- )
136
- FastLanguageModel.for_inference(llm_model)
137
- MODELS_AND_DATA["llm_model"] = llm_model
138
- MODELS_AND_DATA["tokenizer"] = tokenizer
139
- print("✅ Tải LLM và Tokenizer thành công.")
140
-
141
- # 2. Tải mô hình Embedding
142
- print(f"2. Đang tải Embedding Model: {EMBEDDING_MODEL_NAME}...")
143
- embedding_model = SentenceTransformer(EMBEDDING_MODEL_NAME, device="cuda" if torch.cuda.is_available() else "cpu")
144
- MODELS_AND_DATA["embedding_model"] = embedding_model
145
- print("✅ Tải Embedding Model thành công.")
146
-
147
- # 3. Tải và xử lý dữ liệu luật
148
- print(f"3. Đang tải và xử lý dữ liệu từ: {LAW_DATA_FILE}...")
149
- if not os.path.exists(LAW_DATA_FILE):
150
- raise FileNotFoundError(f"Không tìm thấy file dữ liệu luật: {LAW_DATA_FILE}. Vui lòng upload file này lên Space.")
151
- with open(LAW_DATA_FILE, 'r', encoding='utf-8') as f:
152
  raw_data_from_file = json.load(f)
153
  chunks_data = process_law_data_to_chunks(raw_data_from_file)
154
- MODELS_AND_DATA["chunks_data"] = chunks_data
155
- print(f"✅ Đã xử lý thành {len(chunks_data)} chunks.")
156
-
157
- # 4. Tạo BM25 Model
158
- print("4. Đang tạo BM25 Model...")
159
- corpus_texts = [chunk.get('text', '') for chunk in chunks_data]
160
- tokenized_corpus = [tokenize_vi_for_bm25(text) for text in corpus_texts]
161
- bm25_model = BM25Okapi(tokenized_corpus)
162
- MODELS_AND_DATA["bm25_model"] = bm25_model
163
- MODELS_AND_DATA["tokenized_corpus_bm25"] = tokenized_corpus
164
- print("✅ Tạo BM25 Model thành công.")
165
-
166
- # 5. Tạo FAISS Index
167
- print("5. Đang tạo FAISS Index...")
168
- texts_to_encode = [chunk.get('text', '') for chunk in chunks_data]
169
- chunk_embeddings = embedding_model.encode(texts_to_encode, convert_to_tensor=True, device=embedding_model.device)
170
- chunk_embeddings_np = chunk_embeddings.cpu().numpy().astype('float32')
171
- faiss.normalize_L2(chunk_embeddings_np)
172
- dimension = chunk_embeddings_np.shape[1]
173
- index = faiss.IndexFlatIP(dimension)
174
- index.add(chunk_embeddings_np)
175
- MODELS_AND_DATA["faiss_index"] = index
176
- print(f"✅ Tạo FAISS Index thành công với {index.ntotal} vectors.")
177
-
178
- print("\n--- Tải tài nguyên hoàn tất! Ứng dụng đã sẵn sàng. ---")
179
-
180
- # --- PHẦN 3: CÁC HÀM LÕI CHO RAG ---
181
-
182
- def search_relevant_laws(query_text, k=5, initial_k_multiplier=10, rrf_k_constant=60):
183
- """
184
- Hàm thực hiện Hybrid Search để tìm các đoạn luật liên quan.
185
- """
186
- # Lấy các tài nguyên đã tải
187
- embedding_model = MODELS_AND_DATA["embedding_model"]
188
- faiss_index = MODELS_AND_DATA["faiss_index"]
189
- chunks_data = MODELS_AND_DATA["chunks_data"]
190
- bm25_model = MODELS_AND_DATA["bm25_model"]
191
-
192
- if not all([embedding_model, faiss_index, chunks_data, bm25_model]):
193
- return "Lỗi: Tài nguyên chưa được tải xong. Vui lòng chờ."
194
-
195
- # 1. Semantic Search (FAISS)
196
- query_embedding = embedding_model.encode([query_text], convert_to_tensor=True, device=embedding_model.device)
197
- query_embedding_np = query_embedding.cpu().numpy().astype('float32')
198
- faiss.normalize_L2(query_embedding_np)
199
- num_candidates = min(k * initial_k_multiplier, faiss_index.ntotal)
200
- semantic_scores, semantic_indices = faiss_index.search(query_embedding_np, num_candidates)
201
-
202
- # 2. Keyword Search (BM25)
203
- tokenized_query = tokenize_vi_for_bm25(query_text)
204
- bm25_scores = bm25_model.get_scores(tokenized_query)
205
- bm25_results = sorted(enumerate(bm25_scores), key=lambda x: x[1], reverse=True)[:num_candidates]
206
-
207
- # 3. Reciprocal Rank Fusion (RRF)
208
- rrf_scores = defaultdict(float)
209
- if semantic_indices.size > 0:
210
- for rank, doc_idx in enumerate(semantic_indices[0]):
211
- if doc_idx != -1: rrf_scores[doc_idx] += 1.0 / (rrf_k_constant + rank)
212
- for rank, (doc_idx, score) in enumerate(bm25_results):
213
- if score > 0: rrf_scores[doc_idx] += 1.0 / (rrf_k_constant + rank)
214
-
215
- fused_results = sorted(rrf_scores.items(), key=lambda x: x[1], reverse=True)
216
-
217
- # 4. Lấy kết quả cuối cùng
218
- final_results = []
219
- for doc_idx, score in fused_results[:k]:
220
- result = chunks_data[doc_idx].copy()
221
- result['score'] = score
222
- final_results.append(result)
223
-
224
- return final_results
225
-
226
- def generate_llm_response(query, context):
227
- """
228
- Hàm sinh câu trả lời từ LLM dựa trên query và context.
229
- """
230
- llm_model = MODELS_AND_DATA["llm_model"]
231
- tokenizer = MODELS_AND_DATA["tokenizer"]
232
-
233
- prompt = f"""Dưới đây là một số thông tin trích dẫn từ văn bản luật giao thông đường bộ Việt Nam.
234
- Hãy SỬ DỤNG CÁC THÔNG TIN NÀY để trả lời câu hỏi một cách chính xác và đầy đủ.
235
- Nếu câu hỏi đưa ra nhiều đáp án thì chọn 1 đáp án đúng nhất.
236
-
237
- ### Thông tin luật:
238
- {context}
239
-
240
- ### Câu hỏi:
241
- {query}
242
-
243
- ### Trả lời:"""
244
-
245
- inputs = tokenizer(prompt, return_tensors="pt").to("cuda")
246
- generation_config = dict(
247
- max_new_tokens=300,
248
- temperature=0.2,
249
- top_p=0.7,
250
- do_sample=True,
251
- pad_token_id=tokenizer.eos_token_id,
252
- eos_token_id=tokenizer.eos_token_id
253
- )
254
- output_ids = llm_model.generate(**inputs, **generation_config)
255
- input_length = inputs.input_ids.shape[1]
256
- generated_ids = output_ids[0][input_length:]
257
- response_text = tokenizer.decode(generated_ids, skip_special_tokens=True)
258
- return response_text
259
-
260
- # --- PHẦN 4: CÁC HÀM XỬ LÝ CHO GRADIO INTERFACE ---
261
-
262
- def run_retriever_only(query):
263
- """
264
- Chức năng 1: Chỉ tìm kiếm và trả về các điều luật liên quan.
265
- """
266
- print(f"Chạy chức năng Retriever cho query: '{query}'")
267
- retrieved_results = search_relevant_laws(query)
268
-
269
- if isinstance(retrieved_results, str): # Xử lý trường hợp lỗi
270
- return retrieved_results
271
-
272
- if not retrieved_results:
273
- return "Không tìm thấy điều luật nào liên quan."
274
-
275
- # Định dạng output cho Gradio Markdown
276
- formatted_output = f"### Các điều luật liên quan nhất đến truy vấn của bạn:\n\n"
277
- for i, res in enumerate(retrieved_results):
278
- metadata = res.get('metadata', {})
279
- article = metadata.get('article', 'N/A')
280
- clause = metadata.get('clause_number', 'N/A')
281
- source = metadata.get('source_document', 'N/A')
282
- text = res.get('text', 'N/A')
283
-
284
- formatted_output += f"**{i+1}. Nguồn: {source} | Điều {article} | Khoản {clause}**\n"
285
- formatted_output += f"> {text}\n\n---\n\n"
286
-
287
- return formatted_output
288
-
289
- def run_full_rag(query, progress=gr.Progress()):
290
- """
291
- Chức năng 2: Thực hiện toàn bộ pipeline RAG.
292
- """
293
- progress(0, desc="Bắt đầu...")
294
-
295
- # Bước 1: Truy xuất ngữ cảnh
296
- progress(0.2, desc="Đang tìm kiếm các điều luật liên quan (Hybrid Search)...")
297
- print(f"Chạy chức năng RAG cho query: '{query}'")
298
- retrieved_results = search_relevant_laws(query)
299
-
300
- if isinstance(retrieved_results, str) or not retrieved_results:
301
- context_for_llm = "Không tìm thấy thông tin luật liên quan."
302
- context_for_display = context_for_llm
303
- else:
304
- # Định dạng context cho LLM
305
- context_parts = []
306
- for res in retrieved_results:
307
- text = res.get('text', '')
308
- context_parts.append(text)
309
- context_for_llm = "\n\n---\n\n".join(context_parts)
310
-
311
- # Định dạng context để hiển thị cho người dùng
312
- context_for_display = run_retriever_only(query) # Tái sử dụng hàm retriever
313
-
314
- # Bước 2: Sinh câu trả lời
315
- progress(0.7, desc="Đã có ngữ cảnh, đang yêu cầu LLM tạo câu trả lời...")
316
- final_answer = generate_llm_response(query, context_for_llm)
317
-
318
- progress(1, desc="Hoàn tất!")
319
-
320
- return final_answer, context_for_display
321
-
322
-
323
- # --- PHẦN 5: KHỞI CHẠY ỨNG DỤNG GRADIO ---
324
-
325
- # Tải tài nguyên ngay khi script được chạy
326
- load_all_resources()
327
-
328
- with gr.Blocks(theme=gr.themes.Soft(), title="Chatbot Luật Giao thông") as demo:
329
- gr.Markdown(
330
- """
331
- # ⚖️ Chatbot Luật Giao thông Việt Nam
332
- Ứng dụng này sử dụng mô hình RAG (Retrieval-Augmented Generation) để trả lời các câu hỏi về luật giao thông.
333
- """
334
  )
335
-
336
- with gr.Tabs():
337
- # Tab 1: Chỉ tìm kiếm
338
- with gr.TabItem("Tìm kiếm Điều luật (Retriever)"):
339
- with gr.Row():
340
- retriever_query = gr.Textbox(label="Nhập nội dung cần tìm kiếm", placeholder="Ví dụ: Vượt đèn đỏ bị phạt bao nhiêu tiền?", scale=4)
341
- retriever_button = gr.Button("Tìm kiếm", variant="secondary", scale=1)
342
- retriever_output = gr.Markdown(label="Các điều luật liên quan")
343
-
344
- # Tab 2: Hỏi-đáp RAG đầy đủ
345
- with gr.TabItem("Hỏi-Đáp (RAG)"):
346
- with gr.Row():
347
- rag_query = gr.Textbox(label="Nhập câu hỏi của bạn", placeholder="Ví dụ: Phương tiện giao thông đường bộ gồm những loại nào?", scale=4)
348
- rag_button = gr.Button("Gửi câu hỏi", variant="primary", scale=1)
349
- rag_answer = gr.Textbox(label="Câu trả lời của Chatbot", lines=5)
350
- with gr.Accordion("Xem ngữ cảnh đã sử dụng để tạo câu trả lời", open=False):
351
- rag_context = gr.Markdown(label="Ngữ cảnh")
352
-
353
- # Xử sự kiện click
354
- retriever_button.click(fn=run_retriever_only, inputs=retriever_query, outputs=retriever_output)
355
- rag_button.click(fn=run_full_rag, inputs=rag_query, outputs=[rag_answer, rag_context])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
356
 
357
  if __name__ == "__main__":
358
- demo.launch(share=True) # share=True để tạo link public nếu chạy trên Colab/local
 
1
+ import gradio as gr
2
+ import torch # Cần cho việc kiểm tra CUDA 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, # 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 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ỗ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ỗ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 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_chi_tiet_output_openai_sdk_final_cleaned.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
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,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "word_embedding_dimension": 768,
3
+ "pooling_mode_cls_token": false,
4
+ "pooling_mode_mean_tokens": true,
5
+ "pooling_mode_max_tokens": false,
6
+ "pooling_mode_mean_sqrt_len_tokens": false,
7
+ "pooling_mode_weightedmean_tokens": false,
8
+ "pooling_mode_lasttoken": false,
9
+ "include_prompt": true
10
+ }
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
+ {
2
+ "<mask>": 64000
3
+ }
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,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "RobertaModel"
4
+ ],
5
+ "attention_probs_dropout_prob": 0.1,
6
+ "bos_token_id": 0,
7
+ "classifier_dropout": null,
8
+ "eos_token_id": 2,
9
+ "hidden_act": "gelu",
10
+ "hidden_dropout_prob": 0.1,
11
+ "hidden_size": 768,
12
+ "initializer_range": 0.02,
13
+ "intermediate_size": 3072,
14
+ "layer_norm_eps": 1e-05,
15
+ "max_position_embeddings": 258,
16
+ "model_type": "roberta",
17
+ "num_attention_heads": 12,
18
+ "num_hidden_layers": 12,
19
+ "pad_token_id": 1,
20
+ "position_embedding_type": "absolute",
21
+ "tokenizer_class": "PhobertTokenizer",
22
+ "torch_dtype": "float32",
23
+ "transformers_version": "4.51.3",
24
+ "type_vocab_size": 1,
25
+ "use_cache": true,
26
+ "vocab_size": 64001
27
+ }
models/embedding_model/config_sentence_transformers.json ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "__version__": {
3
+ "sentence_transformers": "4.1.0",
4
+ "transformers": "4.51.3",
5
+ "pytorch": "2.7.0+cu126"
6
+ },
7
+ "prompts": {},
8
+ "default_prompt_name": null,
9
+ "similarity_fn_name": "cosine"
10
+ }
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,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [
2
+ {
3
+ "idx": 0,
4
+ "name": "0",
5
+ "path": "",
6
+ "type": "sentence_transformers.models.Transformer"
7
+ },
8
+ {
9
+ "idx": 1,
10
+ "name": "1",
11
+ "path": "1_Pooling",
12
+ "type": "sentence_transformers.models.Pooling"
13
+ }
14
+ ]
models/embedding_model/sentence_bert_config.json ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ {
2
+ "max_seq_length": 256,
3
+ "do_lower_case": false
4
+ }
models/embedding_model/special_tokens_map.json ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": {
3
+ "content": "<s>",
4
+ "lstrip": false,
5
+ "normalized": false,
6
+ "rstrip": false,
7
+ "single_word": false
8
+ },
9
+ "cls_token": {
10
+ "content": "<s>",
11
+ "lstrip": false,
12
+ "normalized": false,
13
+ "rstrip": false,
14
+ "single_word": false
15
+ },
16
+ "eos_token": {
17
+ "content": "</s>",
18
+ "lstrip": false,
19
+ "normalized": false,
20
+ "rstrip": false,
21
+ "single_word": false
22
+ },
23
+ "mask_token": {
24
+ "content": "<mask>",
25
+ "lstrip": false,
26
+ "normalized": false,
27
+ "rstrip": false,
28
+ "single_word": false
29
+ },
30
+ "pad_token": {
31
+ "content": "<pad>",
32
+ "lstrip": false,
33
+ "normalized": false,
34
+ "rstrip": false,
35
+ "single_word": false
36
+ },
37
+ "sep_token": {
38
+ "content": "</s>",
39
+ "lstrip": false,
40
+ "normalized": false,
41
+ "rstrip": false,
42
+ "single_word": false
43
+ },
44
+ "unk_token": {
45
+ "content": "<unk>",
46
+ "lstrip": false,
47
+ "normalized": false,
48
+ "rstrip": false,
49
+ "single_word": false
50
+ }
51
+ }
models/embedding_model/tokenizer_config.json ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "added_tokens_decoder": {
3
+ "0": {
4
+ "content": "<s>",
5
+ "lstrip": false,
6
+ "normalized": false,
7
+ "rstrip": false,
8
+ "single_word": false,
9
+ "special": true
10
+ },
11
+ "1": {
12
+ "content": "<pad>",
13
+ "lstrip": false,
14
+ "normalized": false,
15
+ "rstrip": false,
16
+ "single_word": false,
17
+ "special": true
18
+ },
19
+ "2": {
20
+ "content": "</s>",
21
+ "lstrip": false,
22
+ "normalized": false,
23
+ "rstrip": false,
24
+ "single_word": false,
25
+ "special": true
26
+ },
27
+ "3": {
28
+ "content": "<unk>",
29
+ "lstrip": false,
30
+ "normalized": false,
31
+ "rstrip": false,
32
+ "single_word": false,
33
+ "special": true
34
+ },
35
+ "64000": {
36
+ "content": "<mask>",
37
+ "lstrip": false,
38
+ "normalized": false,
39
+ "rstrip": false,
40
+ "single_word": false,
41
+ "special": true
42
+ }
43
+ },
44
+ "bos_token": "<s>",
45
+ "clean_up_tokenization_spaces": true,
46
+ "cls_token": "<s>",
47
+ "eos_token": "</s>",
48
+ "extra_special_tokens": {},
49
+ "mask_token": "<mask>",
50
+ "model_max_length": 256,
51
+ "pad_token": "<pad>",
52
+ "sep_token": "</s>",
53
+ "tokenizer_class": "PhobertTokenizer",
54
+ "unk_token": "<unk>"
55
+ }
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,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "alpha_pattern": {},
3
+ "auto_mapping": null,
4
+ "base_model_name_or_path": "unsloth/llama-3.2-3b-instruct-unsloth-bnb-4bit",
5
+ "bias": "none",
6
+ "corda_config": null,
7
+ "eva_config": null,
8
+ "exclude_modules": null,
9
+ "fan_in_fan_out": false,
10
+ "inference_mode": true,
11
+ "init_lora_weights": true,
12
+ "layer_replication": null,
13
+ "layers_pattern": null,
14
+ "layers_to_transform": null,
15
+ "loftq_config": {},
16
+ "lora_alpha": 16,
17
+ "lora_bias": false,
18
+ "lora_dropout": 0,
19
+ "megatron_config": null,
20
+ "megatron_core": "megatron.core",
21
+ "modules_to_save": null,
22
+ "peft_type": "LORA",
23
+ "r": 16,
24
+ "rank_pattern": {},
25
+ "revision": null,
26
+ "target_modules": [
27
+ "q_proj",
28
+ "gate_proj",
29
+ "down_proj",
30
+ "o_proj",
31
+ "k_proj",
32
+ "v_proj",
33
+ "up_proj"
34
+ ],
35
+ "task_type": "CAUSAL_LM",
36
+ "trainable_token_indices": null,
37
+ "use_dora": false,
38
+ "use_rslora": false
39
+ }
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,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": {
3
+ "content": "<|begin_of_text|>",
4
+ "lstrip": false,
5
+ "normalized": false,
6
+ "rstrip": false,
7
+ "single_word": false
8
+ },
9
+ "eos_token": {
10
+ "content": "<|eot_id|>",
11
+ "lstrip": false,
12
+ "normalized": false,
13
+ "rstrip": false,
14
+ "single_word": false
15
+ },
16
+ "pad_token": {
17
+ "content": "<|finetune_right_pad_id|>",
18
+ "lstrip": false,
19
+ "normalized": false,
20
+ "rstrip": false,
21
+ "single_word": false
22
+ }
23
+ }
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,2067 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": true,
3
+ "added_tokens_decoder": {
4
+ "128000": {
5
+ "content": "<|begin_of_text|>",
6
+ "lstrip": false,
7
+ "normalized": false,
8
+ "rstrip": false,
9
+ "single_word": false,
10
+ "special": true
11
+ },
12
+ "128001": {
13
+ "content": "<|end_of_text|>",
14
+ "lstrip": false,
15
+ "normalized": false,
16
+ "rstrip": false,
17
+ "single_word": false,
18
+ "special": true
19
+ },
20
+ "128002": {
21
+ "content": "<|reserved_special_token_0|>",
22
+ "lstrip": false,
23
+ "normalized": false,
24
+ "rstrip": false,
25
+ "single_word": false,
26
+ "special": true
27
+ },
28
+ "128003": {
29
+ "content": "<|reserved_special_token_1|>",
30
+ "lstrip": false,
31
+ "normalized": false,
32
+ "rstrip": false,
33
+ "single_word": false,
34
+ "special": true
35
+ },
36
+ "128004": {
37
+ "content": "<|finetune_right_pad_id|>",
38
+ "lstrip": false,
39
+ "normalized": false,
40
+ "rstrip": false,
41
+ "single_word": false,
42
+ "special": true
43
+ },
44
+ "128005": {
45
+ "content": "<|reserved_special_token_2|>",
46
+ "lstrip": false,
47
+ "normalized": false,
48
+ "rstrip": false,
49
+ "single_word": false,
50
+ "special": true
51
+ },
52
+ "128006": {
53
+ "content": "<|start_header_id|>",
54
+ "lstrip": false,
55
+ "normalized": false,
56
+ "rstrip": false,
57
+ "single_word": false,
58
+ "special": true
59
+ },
60
+ "128007": {
61
+ "content": "<|end_header_id|>",
62
+ "lstrip": false,
63
+ "normalized": false,
64
+ "rstrip": false,
65
+ "single_word": false,
66
+ "special": true
67
+ },
68
+ "128008": {
69
+ "content": "<|eom_id|>",
70
+ "lstrip": false,
71
+ "normalized": false,
72
+ "rstrip": false,
73
+ "single_word": false,
74
+ "special": true
75
+ },
76
+ "128009": {
77
+ "content": "<|eot_id|>",
78
+ "lstrip": false,
79
+ "normalized": false,
80
+ "rstrip": false,
81
+ "single_word": false,
82
+ "special": true
83
+ },
84
+ "128010": {
85
+ "content": "<|python_tag|>",
86
+ "lstrip": false,
87
+ "normalized": false,
88
+ "rstrip": false,
89
+ "single_word": false,
90
+ "special": true
91
+ },
92
+ "128011": {
93
+ "content": "<|reserved_special_token_3|>",
94
+ "lstrip": false,
95
+ "normalized": false,
96
+ "rstrip": false,
97
+ "single_word": false,
98
+ "special": true
99
+ },
100
+ "128012": {
101
+ "content": "<|reserved_special_token_4|>",
102
+ "lstrip": false,
103
+ "normalized": false,
104
+ "rstrip": false,
105
+ "single_word": false,
106
+ "special": true
107
+ },
108
+ "128013": {
109
+ "content": "<|reserved_special_token_5|>",
110
+ "lstrip": false,
111
+ "normalized": false,
112
+ "rstrip": false,
113
+ "single_word": false,
114
+ "special": true
115
+ },
116
+ "128014": {
117
+ "content": "<|reserved_special_token_6|>",
118
+ "lstrip": false,
119
+ "normalized": false,
120
+ "rstrip": false,
121
+ "single_word": false,
122
+ "special": true
123
+ },
124
+ "128015": {
125
+ "content": "<|reserved_special_token_7|>",
126
+ "lstrip": false,
127
+ "normalized": false,
128
+ "rstrip": false,
129
+ "single_word": false,
130
+ "special": true
131
+ },
132
+ "128016": {
133
+ "content": "<|reserved_special_token_8|>",
134
+ "lstrip": false,
135
+ "normalized": false,
136
+ "rstrip": false,
137
+ "single_word": false,
138
+ "special": true
139
+ },
140
+ "128017": {
141
+ "content": "<|reserved_special_token_9|>",
142
+ "lstrip": false,
143
+ "normalized": false,
144
+ "rstrip": false,
145
+ "single_word": false,
146
+ "special": true
147
+ },
148
+ "128018": {
149
+ "content": "<|reserved_special_token_10|>",
150
+ "lstrip": false,
151
+ "normalized": false,
152
+ "rstrip": false,
153
+ "single_word": false,
154
+ "special": true
155
+ },
156
+ "128019": {
157
+ "content": "<|reserved_special_token_11|>",
158
+ "lstrip": false,
159
+ "normalized": false,
160
+ "rstrip": false,
161
+ "single_word": false,
162
+ "special": true
163
+ },
164
+ "128020": {
165
+ "content": "<|reserved_special_token_12|>",
166
+ "lstrip": false,
167
+ "normalized": false,
168
+ "rstrip": false,
169
+ "single_word": false,
170
+ "special": true
171
+ },
172
+ "128021": {
173
+ "content": "<|reserved_special_token_13|>",
174
+ "lstrip": false,
175
+ "normalized": false,
176
+ "rstrip": false,
177
+ "single_word": false,
178
+ "special": true
179
+ },
180
+ "128022": {
181
+ "content": "<|reserved_special_token_14|>",
182
+ "lstrip": false,
183
+ "normalized": false,
184
+ "rstrip": false,
185
+ "single_word": false,
186
+ "special": true
187
+ },
188
+ "128023": {
189
+ "content": "<|reserved_special_token_15|>",
190
+ "lstrip": false,
191
+ "normalized": false,
192
+ "rstrip": false,
193
+ "single_word": false,
194
+ "special": true
195
+ },
196
+ "128024": {
197
+ "content": "<|reserved_special_token_16|>",
198
+ "lstrip": false,
199
+ "normalized": false,
200
+ "rstrip": false,
201
+ "single_word": false,
202
+ "special": true
203
+ },
204
+ "128025": {
205
+ "content": "<|reserved_special_token_17|>",
206
+ "lstrip": false,
207
+ "normalized": false,
208
+ "rstrip": false,
209
+ "single_word": false,
210
+ "special": true
211
+ },
212
+ "128026": {
213
+ "content": "<|reserved_special_token_18|>",
214
+ "lstrip": false,
215
+ "normalized": false,
216
+ "rstrip": false,
217
+ "single_word": false,
218
+ "special": true
219
+ },
220
+ "128027": {
221
+ "content": "<|reserved_special_token_19|>",
222
+ "lstrip": false,
223
+ "normalized": false,
224
+ "rstrip": false,
225
+ "single_word": false,
226
+ "special": true
227
+ },
228
+ "128028": {
229
+ "content": "<|reserved_special_token_20|>",
230
+ "lstrip": false,
231
+ "normalized": false,
232
+ "rstrip": false,
233
+ "single_word": false,
234
+ "special": true
235
+ },
236
+ "128029": {
237
+ "content": "<|reserved_special_token_21|>",
238
+ "lstrip": false,
239
+ "normalized": false,
240
+ "rstrip": false,
241
+ "single_word": false,
242
+ "special": true
243
+ },
244
+ "128030": {
245
+ "content": "<|reserved_special_token_22|>",
246
+ "lstrip": false,
247
+ "normalized": false,
248
+ "rstrip": false,
249
+ "single_word": false,
250
+ "special": true
251
+ },
252
+ "128031": {
253
+ "content": "<|reserved_special_token_23|>",
254
+ "lstrip": false,
255
+ "normalized": false,
256
+ "rstrip": false,
257
+ "single_word": false,
258
+ "special": true
259
+ },
260
+ "128032": {
261
+ "content": "<|reserved_special_token_24|>",
262
+ "lstrip": false,
263
+ "normalized": false,
264
+ "rstrip": false,
265
+ "single_word": false,
266
+ "special": true
267
+ },
268
+ "128033": {
269
+ "content": "<|reserved_special_token_25|>",
270
+ "lstrip": false,
271
+ "normalized": false,
272
+ "rstrip": false,
273
+ "single_word": false,
274
+ "special": true
275
+ },
276
+ "128034": {
277
+ "content": "<|reserved_special_token_26|>",
278
+ "lstrip": false,
279
+ "normalized": false,
280
+ "rstrip": false,
281
+ "single_word": false,
282
+ "special": true
283
+ },
284
+ "128035": {
285
+ "content": "<|reserved_special_token_27|>",
286
+ "lstrip": false,
287
+ "normalized": false,
288
+ "rstrip": false,
289
+ "single_word": false,
290
+ "special": true
291
+ },
292
+ "128036": {
293
+ "content": "<|reserved_special_token_28|>",
294
+ "lstrip": false,
295
+ "normalized": false,
296
+ "rstrip": false,
297
+ "single_word": false,
298
+ "special": true
299
+ },
300
+ "128037": {
301
+ "content": "<|reserved_special_token_29|>",
302
+ "lstrip": false,
303
+ "normalized": false,
304
+ "rstrip": false,
305
+ "single_word": false,
306
+ "special": true
307
+ },
308
+ "128038": {
309
+ "content": "<|reserved_special_token_30|>",
310
+ "lstrip": false,
311
+ "normalized": false,
312
+ "rstrip": false,
313
+ "single_word": false,
314
+ "special": true
315
+ },
316
+ "128039": {
317
+ "content": "<|reserved_special_token_31|>",
318
+ "lstrip": false,
319
+ "normalized": false,
320
+ "rstrip": false,
321
+ "single_word": false,
322
+ "special": true
323
+ },
324
+ "128040": {
325
+ "content": "<|reserved_special_token_32|>",
326
+ "lstrip": false,
327
+ "normalized": false,
328
+ "rstrip": false,
329
+ "single_word": false,
330
+ "special": true
331
+ },
332
+ "128041": {
333
+ "content": "<|reserved_special_token_33|>",
334
+ "lstrip": false,
335
+ "normalized": false,
336
+ "rstrip": false,
337
+ "single_word": false,
338
+ "special": true
339
+ },
340
+ "128042": {
341
+ "content": "<|reserved_special_token_34|>",
342
+ "lstrip": false,
343
+ "normalized": false,
344
+ "rstrip": false,
345
+ "single_word": false,
346
+ "special": true
347
+ },
348
+ "128043": {
349
+ "content": "<|reserved_special_token_35|>",
350
+ "lstrip": false,
351
+ "normalized": false,
352
+ "rstrip": false,
353
+ "single_word": false,
354
+ "special": true
355
+ },
356
+ "128044": {
357
+ "content": "<|reserved_special_token_36|>",
358
+ "lstrip": false,
359
+ "normalized": false,
360
+ "rstrip": false,
361
+ "single_word": false,
362
+ "special": true
363
+ },
364
+ "128045": {
365
+ "content": "<|reserved_special_token_37|>",
366
+ "lstrip": false,
367
+ "normalized": false,
368
+ "rstrip": false,
369
+ "single_word": false,
370
+ "special": true
371
+ },
372
+ "128046": {
373
+ "content": "<|reserved_special_token_38|>",
374
+ "lstrip": false,
375
+ "normalized": false,
376
+ "rstrip": false,
377
+ "single_word": false,
378
+ "special": true
379
+ },
380
+ "128047": {
381
+ "content": "<|reserved_special_token_39|>",
382
+ "lstrip": false,
383
+ "normalized": false,
384
+ "rstrip": false,
385
+ "single_word": false,
386
+ "special": true
387
+ },
388
+ "128048": {
389
+ "content": "<|reserved_special_token_40|>",
390
+ "lstrip": false,
391
+ "normalized": false,
392
+ "rstrip": false,
393
+ "single_word": false,
394
+ "special": true
395
+ },
396
+ "128049": {
397
+ "content": "<|reserved_special_token_41|>",
398
+ "lstrip": false,
399
+ "normalized": false,
400
+ "rstrip": false,
401
+ "single_word": false,
402
+ "special": true
403
+ },
404
+ "128050": {
405
+ "content": "<|reserved_special_token_42|>",
406
+ "lstrip": false,
407
+ "normalized": false,
408
+ "rstrip": false,
409
+ "single_word": false,
410
+ "special": true
411
+ },
412
+ "128051": {
413
+ "content": "<|reserved_special_token_43|>",
414
+ "lstrip": false,
415
+ "normalized": false,
416
+ "rstrip": false,
417
+ "single_word": false,
418
+ "special": true
419
+ },
420
+ "128052": {
421
+ "content": "<|reserved_special_token_44|>",
422
+ "lstrip": false,
423
+ "normalized": false,
424
+ "rstrip": false,
425
+ "single_word": false,
426
+ "special": true
427
+ },
428
+ "128053": {
429
+ "content": "<|reserved_special_token_45|>",
430
+ "lstrip": false,
431
+ "normalized": false,
432
+ "rstrip": false,
433
+ "single_word": false,
434
+ "special": true
435
+ },
436
+ "128054": {
437
+ "content": "<|reserved_special_token_46|>",
438
+ "lstrip": false,
439
+ "normalized": false,
440
+ "rstrip": false,
441
+ "single_word": false,
442
+ "special": true
443
+ },
444
+ "128055": {
445
+ "content": "<|reserved_special_token_47|>",
446
+ "lstrip": false,
447
+ "normalized": false,
448
+ "rstrip": false,
449
+ "single_word": false,
450
+ "special": true
451
+ },
452
+ "128056": {
453
+ "content": "<|reserved_special_token_48|>",
454
+ "lstrip": false,
455
+ "normalized": false,
456
+ "rstrip": false,
457
+ "single_word": false,
458
+ "special": true
459
+ },
460
+ "128057": {
461
+ "content": "<|reserved_special_token_49|>",
462
+ "lstrip": false,
463
+ "normalized": false,
464
+ "rstrip": false,
465
+ "single_word": false,
466
+ "special": true
467
+ },
468
+ "128058": {
469
+ "content": "<|reserved_special_token_50|>",
470
+ "lstrip": false,
471
+ "normalized": false,
472
+ "rstrip": false,
473
+ "single_word": false,
474
+ "special": true
475
+ },
476
+ "128059": {
477
+ "content": "<|reserved_special_token_51|>",
478
+ "lstrip": false,
479
+ "normalized": false,
480
+ "rstrip": false,
481
+ "single_word": false,
482
+ "special": true
483
+ },
484
+ "128060": {
485
+ "content": "<|reserved_special_token_52|>",
486
+ "lstrip": false,
487
+ "normalized": false,
488
+ "rstrip": false,
489
+ "single_word": false,
490
+ "special": true
491
+ },
492
+ "128061": {
493
+ "content": "<|reserved_special_token_53|>",
494
+ "lstrip": false,
495
+ "normalized": false,
496
+ "rstrip": false,
497
+ "single_word": false,
498
+ "special": true
499
+ },
500
+ "128062": {
501
+ "content": "<|reserved_special_token_54|>",
502
+ "lstrip": false,
503
+ "normalized": false,
504
+ "rstrip": false,
505
+ "single_word": false,
506
+ "special": true
507
+ },
508
+ "128063": {
509
+ "content": "<|reserved_special_token_55|>",
510
+ "lstrip": false,
511
+ "normalized": false,
512
+ "rstrip": false,
513
+ "single_word": false,
514
+ "special": true
515
+ },
516
+ "128064": {
517
+ "content": "<|reserved_special_token_56|>",
518
+ "lstrip": false,
519
+ "normalized": false,
520
+ "rstrip": false,
521
+ "single_word": false,
522
+ "special": true
523
+ },
524
+ "128065": {
525
+ "content": "<|reserved_special_token_57|>",
526
+ "lstrip": false,
527
+ "normalized": false,
528
+ "rstrip": false,
529
+ "single_word": false,
530
+ "special": true
531
+ },
532
+ "128066": {
533
+ "content": "<|reserved_special_token_58|>",
534
+ "lstrip": false,
535
+ "normalized": false,
536
+ "rstrip": false,
537
+ "single_word": false,
538
+ "special": true
539
+ },
540
+ "128067": {
541
+ "content": "<|reserved_special_token_59|>",
542
+ "lstrip": false,
543
+ "normalized": false,
544
+ "rstrip": false,
545
+ "single_word": false,
546
+ "special": true
547
+ },
548
+ "128068": {
549
+ "content": "<|reserved_special_token_60|>",
550
+ "lstrip": false,
551
+ "normalized": false,
552
+ "rstrip": false,
553
+ "single_word": false,
554
+ "special": true
555
+ },
556
+ "128069": {
557
+ "content": "<|reserved_special_token_61|>",
558
+ "lstrip": false,
559
+ "normalized": false,
560
+ "rstrip": false,
561
+ "single_word": false,
562
+ "special": true
563
+ },
564
+ "128070": {
565
+ "content": "<|reserved_special_token_62|>",
566
+ "lstrip": false,
567
+ "normalized": false,
568
+ "rstrip": false,
569
+ "single_word": false,
570
+ "special": true
571
+ },
572
+ "128071": {
573
+ "content": "<|reserved_special_token_63|>",
574
+ "lstrip": false,
575
+ "normalized": false,
576
+ "rstrip": false,
577
+ "single_word": false,
578
+ "special": true
579
+ },
580
+ "128072": {
581
+ "content": "<|reserved_special_token_64|>",
582
+ "lstrip": false,
583
+ "normalized": false,
584
+ "rstrip": false,
585
+ "single_word": false,
586
+ "special": true
587
+ },
588
+ "128073": {
589
+ "content": "<|reserved_special_token_65|>",
590
+ "lstrip": false,
591
+ "normalized": false,
592
+ "rstrip": false,
593
+ "single_word": false,
594
+ "special": true
595
+ },
596
+ "128074": {
597
+ "content": "<|reserved_special_token_66|>",
598
+ "lstrip": false,
599
+ "normalized": false,
600
+ "rstrip": false,
601
+ "single_word": false,
602
+ "special": true
603
+ },
604
+ "128075": {
605
+ "content": "<|reserved_special_token_67|>",
606
+ "lstrip": false,
607
+ "normalized": false,
608
+ "rstrip": false,
609
+ "single_word": false,
610
+ "special": true
611
+ },
612
+ "128076": {
613
+ "content": "<|reserved_special_token_68|>",
614
+ "lstrip": false,
615
+ "normalized": false,
616
+ "rstrip": false,
617
+ "single_word": false,
618
+ "special": true
619
+ },
620
+ "128077": {
621
+ "content": "<|reserved_special_token_69|>",
622
+ "lstrip": false,
623
+ "normalized": false,
624
+ "rstrip": false,
625
+ "single_word": false,
626
+ "special": true
627
+ },
628
+ "128078": {
629
+ "content": "<|reserved_special_token_70|>",
630
+ "lstrip": false,
631
+ "normalized": false,
632
+ "rstrip": false,
633
+ "single_word": false,
634
+ "special": true
635
+ },
636
+ "128079": {
637
+ "content": "<|reserved_special_token_71|>",
638
+ "lstrip": false,
639
+ "normalized": false,
640
+ "rstrip": false,
641
+ "single_word": false,
642
+ "special": true
643
+ },
644
+ "128080": {
645
+ "content": "<|reserved_special_token_72|>",
646
+ "lstrip": false,
647
+ "normalized": false,
648
+ "rstrip": false,
649
+ "single_word": false,
650
+ "special": true
651
+ },
652
+ "128081": {
653
+ "content": "<|reserved_special_token_73|>",
654
+ "lstrip": false,
655
+ "normalized": false,
656
+ "rstrip": false,
657
+ "single_word": false,
658
+ "special": true
659
+ },
660
+ "128082": {
661
+ "content": "<|reserved_special_token_74|>",
662
+ "lstrip": false,
663
+ "normalized": false,
664
+ "rstrip": false,
665
+ "single_word": false,
666
+ "special": true
667
+ },
668
+ "128083": {
669
+ "content": "<|reserved_special_token_75|>",
670
+ "lstrip": false,
671
+ "normalized": false,
672
+ "rstrip": false,
673
+ "single_word": false,
674
+ "special": true
675
+ },
676
+ "128084": {
677
+ "content": "<|reserved_special_token_76|>",
678
+ "lstrip": false,
679
+ "normalized": false,
680
+ "rstrip": false,
681
+ "single_word": false,
682
+ "special": true
683
+ },
684
+ "128085": {
685
+ "content": "<|reserved_special_token_77|>",
686
+ "lstrip": false,
687
+ "normalized": false,
688
+ "rstrip": false,
689
+ "single_word": false,
690
+ "special": true
691
+ },
692
+ "128086": {
693
+ "content": "<|reserved_special_token_78|>",
694
+ "lstrip": false,
695
+ "normalized": false,
696
+ "rstrip": false,
697
+ "single_word": false,
698
+ "special": true
699
+ },
700
+ "128087": {
701
+ "content": "<|reserved_special_token_79|>",
702
+ "lstrip": false,
703
+ "normalized": false,
704
+ "rstrip": false,
705
+ "single_word": false,
706
+ "special": true
707
+ },
708
+ "128088": {
709
+ "content": "<|reserved_special_token_80|>",
710
+ "lstrip": false,
711
+ "normalized": false,
712
+ "rstrip": false,
713
+ "single_word": false,
714
+ "special": true
715
+ },
716
+ "128089": {
717
+ "content": "<|reserved_special_token_81|>",
718
+ "lstrip": false,
719
+ "normalized": false,
720
+ "rstrip": false,
721
+ "single_word": false,
722
+ "special": true
723
+ },
724
+ "128090": {
725
+ "content": "<|reserved_special_token_82|>",
726
+ "lstrip": false,
727
+ "normalized": false,
728
+ "rstrip": false,
729
+ "single_word": false,
730
+ "special": true
731
+ },
732
+ "128091": {
733
+ "content": "<|reserved_special_token_83|>",
734
+ "lstrip": false,
735
+ "normalized": false,
736
+ "rstrip": false,
737
+ "single_word": false,
738
+ "special": true
739
+ },
740
+ "128092": {
741
+ "content": "<|reserved_special_token_84|>",
742
+ "lstrip": false,
743
+ "normalized": false,
744
+ "rstrip": false,
745
+ "single_word": false,
746
+ "special": true
747
+ },
748
+ "128093": {
749
+ "content": "<|reserved_special_token_85|>",
750
+ "lstrip": false,
751
+ "normalized": false,
752
+ "rstrip": false,
753
+ "single_word": false,
754
+ "special": true
755
+ },
756
+ "128094": {
757
+ "content": "<|reserved_special_token_86|>",
758
+ "lstrip": false,
759
+ "normalized": false,
760
+ "rstrip": false,
761
+ "single_word": false,
762
+ "special": true
763
+ },
764
+ "128095": {
765
+ "content": "<|reserved_special_token_87|>",
766
+ "lstrip": false,
767
+ "normalized": false,
768
+ "rstrip": false,
769
+ "single_word": false,
770
+ "special": true
771
+ },
772
+ "128096": {
773
+ "content": "<|reserved_special_token_88|>",
774
+ "lstrip": false,
775
+ "normalized": false,
776
+ "rstrip": false,
777
+ "single_word": false,
778
+ "special": true
779
+ },
780
+ "128097": {
781
+ "content": "<|reserved_special_token_89|>",
782
+ "lstrip": false,
783
+ "normalized": false,
784
+ "rstrip": false,
785
+ "single_word": false,
786
+ "special": true
787
+ },
788
+ "128098": {
789
+ "content": "<|reserved_special_token_90|>",
790
+ "lstrip": false,
791
+ "normalized": false,
792
+ "rstrip": false,
793
+ "single_word": false,
794
+ "special": true
795
+ },
796
+ "128099": {
797
+ "content": "<|reserved_special_token_91|>",
798
+ "lstrip": false,
799
+ "normalized": false,
800
+ "rstrip": false,
801
+ "single_word": false,
802
+ "special": true
803
+ },
804
+ "128100": {
805
+ "content": "<|reserved_special_token_92|>",
806
+ "lstrip": false,
807
+ "normalized": false,
808
+ "rstrip": false,
809
+ "single_word": false,
810
+ "special": true
811
+ },
812
+ "128101": {
813
+ "content": "<|reserved_special_token_93|>",
814
+ "lstrip": false,
815
+ "normalized": false,
816
+ "rstrip": false,
817
+ "single_word": false,
818
+ "special": true
819
+ },
820
+ "128102": {
821
+ "content": "<|reserved_special_token_94|>",
822
+ "lstrip": false,
823
+ "normalized": false,
824
+ "rstrip": false,
825
+ "single_word": false,
826
+ "special": true
827
+ },
828
+ "128103": {
829
+ "content": "<|reserved_special_token_95|>",
830
+ "lstrip": false,
831
+ "normalized": false,
832
+ "rstrip": false,
833
+ "single_word": false,
834
+ "special": true
835
+ },
836
+ "128104": {
837
+ "content": "<|reserved_special_token_96|>",
838
+ "lstrip": false,
839
+ "normalized": false,
840
+ "rstrip": false,
841
+ "single_word": false,
842
+ "special": true
843
+ },
844
+ "128105": {
845
+ "content": "<|reserved_special_token_97|>",
846
+ "lstrip": false,
847
+ "normalized": false,
848
+ "rstrip": false,
849
+ "single_word": false,
850
+ "special": true
851
+ },
852
+ "128106": {
853
+ "content": "<|reserved_special_token_98|>",
854
+ "lstrip": false,
855
+ "normalized": false,
856
+ "rstrip": false,
857
+ "single_word": false,
858
+ "special": true
859
+ },
860
+ "128107": {
861
+ "content": "<|reserved_special_token_99|>",
862
+ "lstrip": false,
863
+ "normalized": false,
864
+ "rstrip": false,
865
+ "single_word": false,
866
+ "special": true
867
+ },
868
+ "128108": {
869
+ "content": "<|reserved_special_token_100|>",
870
+ "lstrip": false,
871
+ "normalized": false,
872
+ "rstrip": false,
873
+ "single_word": false,
874
+ "special": true
875
+ },
876
+ "128109": {
877
+ "content": "<|reserved_special_token_101|>",
878
+ "lstrip": false,
879
+ "normalized": false,
880
+ "rstrip": false,
881
+ "single_word": false,
882
+ "special": true
883
+ },
884
+ "128110": {
885
+ "content": "<|reserved_special_token_102|>",
886
+ "lstrip": false,
887
+ "normalized": false,
888
+ "rstrip": false,
889
+ "single_word": false,
890
+ "special": true
891
+ },
892
+ "128111": {
893
+ "content": "<|reserved_special_token_103|>",
894
+ "lstrip": false,
895
+ "normalized": false,
896
+ "rstrip": false,
897
+ "single_word": false,
898
+ "special": true
899
+ },
900
+ "128112": {
901
+ "content": "<|reserved_special_token_104|>",
902
+ "lstrip": false,
903
+ "normalized": false,
904
+ "rstrip": false,
905
+ "single_word": false,
906
+ "special": true
907
+ },
908
+ "128113": {
909
+ "content": "<|reserved_special_token_105|>",
910
+ "lstrip": false,
911
+ "normalized": false,
912
+ "rstrip": false,
913
+ "single_word": false,
914
+ "special": true
915
+ },
916
+ "128114": {
917
+ "content": "<|reserved_special_token_106|>",
918
+ "lstrip": false,
919
+ "normalized": false,
920
+ "rstrip": false,
921
+ "single_word": false,
922
+ "special": true
923
+ },
924
+ "128115": {
925
+ "content": "<|reserved_special_token_107|>",
926
+ "lstrip": false,
927
+ "normalized": false,
928
+ "rstrip": false,
929
+ "single_word": false,
930
+ "special": true
931
+ },
932
+ "128116": {
933
+ "content": "<|reserved_special_token_108|>",
934
+ "lstrip": false,
935
+ "normalized": false,
936
+ "rstrip": false,
937
+ "single_word": false,
938
+ "special": true
939
+ },
940
+ "128117": {
941
+ "content": "<|reserved_special_token_109|>",
942
+ "lstrip": false,
943
+ "normalized": false,
944
+ "rstrip": false,
945
+ "single_word": false,
946
+ "special": true
947
+ },
948
+ "128118": {
949
+ "content": "<|reserved_special_token_110|>",
950
+ "lstrip": false,
951
+ "normalized": false,
952
+ "rstrip": false,
953
+ "single_word": false,
954
+ "special": true
955
+ },
956
+ "128119": {
957
+ "content": "<|reserved_special_token_111|>",
958
+ "lstrip": false,
959
+ "normalized": false,
960
+ "rstrip": false,
961
+ "single_word": false,
962
+ "special": true
963
+ },
964
+ "128120": {
965
+ "content": "<|reserved_special_token_112|>",
966
+ "lstrip": false,
967
+ "normalized": false,
968
+ "rstrip": false,
969
+ "single_word": false,
970
+ "special": true
971
+ },
972
+ "128121": {
973
+ "content": "<|reserved_special_token_113|>",
974
+ "lstrip": false,
975
+ "normalized": false,
976
+ "rstrip": false,
977
+ "single_word": false,
978
+ "special": true
979
+ },
980
+ "128122": {
981
+ "content": "<|reserved_special_token_114|>",
982
+ "lstrip": false,
983
+ "normalized": false,
984
+ "rstrip": false,
985
+ "single_word": false,
986
+ "special": true
987
+ },
988
+ "128123": {
989
+ "content": "<|reserved_special_token_115|>",
990
+ "lstrip": false,
991
+ "normalized": false,
992
+ "rstrip": false,
993
+ "single_word": false,
994
+ "special": true
995
+ },
996
+ "128124": {
997
+ "content": "<|reserved_special_token_116|>",
998
+ "lstrip": false,
999
+ "normalized": false,
1000
+ "rstrip": false,
1001
+ "single_word": false,
1002
+ "special": true
1003
+ },
1004
+ "128125": {
1005
+ "content": "<|reserved_special_token_117|>",
1006
+ "lstrip": false,
1007
+ "normalized": false,
1008
+ "rstrip": false,
1009
+ "single_word": false,
1010
+ "special": true
1011
+ },
1012
+ "128126": {
1013
+ "content": "<|reserved_special_token_118|>",
1014
+ "lstrip": false,
1015
+ "normalized": false,
1016
+ "rstrip": false,
1017
+ "single_word": false,
1018
+ "special": true
1019
+ },
1020
+ "128127": {
1021
+ "content": "<|reserved_special_token_119|>",
1022
+ "lstrip": false,
1023
+ "normalized": false,
1024
+ "rstrip": false,
1025
+ "single_word": false,
1026
+ "special": true
1027
+ },
1028
+ "128128": {
1029
+ "content": "<|reserved_special_token_120|>",
1030
+ "lstrip": false,
1031
+ "normalized": false,
1032
+ "rstrip": false,
1033
+ "single_word": false,
1034
+ "special": true
1035
+ },
1036
+ "128129": {
1037
+ "content": "<|reserved_special_token_121|>",
1038
+ "lstrip": false,
1039
+ "normalized": false,
1040
+ "rstrip": false,
1041
+ "single_word": false,
1042
+ "special": true
1043
+ },
1044
+ "128130": {
1045
+ "content": "<|reserved_special_token_122|>",
1046
+ "lstrip": false,
1047
+ "normalized": false,
1048
+ "rstrip": false,
1049
+ "single_word": false,
1050
+ "special": true
1051
+ },
1052
+ "128131": {
1053
+ "content": "<|reserved_special_token_123|>",
1054
+ "lstrip": false,
1055
+ "normalized": false,
1056
+ "rstrip": false,
1057
+ "single_word": false,
1058
+ "special": true
1059
+ },
1060
+ "128132": {
1061
+ "content": "<|reserved_special_token_124|>",
1062
+ "lstrip": false,
1063
+ "normalized": false,
1064
+ "rstrip": false,
1065
+ "single_word": false,
1066
+ "special": true
1067
+ },
1068
+ "128133": {
1069
+ "content": "<|reserved_special_token_125|>",
1070
+ "lstrip": false,
1071
+ "normalized": false,
1072
+ "rstrip": false,
1073
+ "single_word": false,
1074
+ "special": true
1075
+ },
1076
+ "128134": {
1077
+ "content": "<|reserved_special_token_126|>",
1078
+ "lstrip": false,
1079
+ "normalized": false,
1080
+ "rstrip": false,
1081
+ "single_word": false,
1082
+ "special": true
1083
+ },
1084
+ "128135": {
1085
+ "content": "<|reserved_special_token_127|>",
1086
+ "lstrip": false,
1087
+ "normalized": false,
1088
+ "rstrip": false,
1089
+ "single_word": false,
1090
+ "special": true
1091
+ },
1092
+ "128136": {
1093
+ "content": "<|reserved_special_token_128|>",
1094
+ "lstrip": false,
1095
+ "normalized": false,
1096
+ "rstrip": false,
1097
+ "single_word": false,
1098
+ "special": true
1099
+ },
1100
+ "128137": {
1101
+ "content": "<|reserved_special_token_129|>",
1102
+ "lstrip": false,
1103
+ "normalized": false,
1104
+ "rstrip": false,
1105
+ "single_word": false,
1106
+ "special": true
1107
+ },
1108
+ "128138": {
1109
+ "content": "<|reserved_special_token_130|>",
1110
+ "lstrip": false,
1111
+ "normalized": false,
1112
+ "rstrip": false,
1113
+ "single_word": false,
1114
+ "special": true
1115
+ },
1116
+ "128139": {
1117
+ "content": "<|reserved_special_token_131|>",
1118
+ "lstrip": false,
1119
+ "normalized": false,
1120
+ "rstrip": false,
1121
+ "single_word": false,
1122
+ "special": true
1123
+ },
1124
+ "128140": {
1125
+ "content": "<|reserved_special_token_132|>",
1126
+ "lstrip": false,
1127
+ "normalized": false,
1128
+ "rstrip": false,
1129
+ "single_word": false,
1130
+ "special": true
1131
+ },
1132
+ "128141": {
1133
+ "content": "<|reserved_special_token_133|>",
1134
+ "lstrip": false,
1135
+ "normalized": false,
1136
+ "rstrip": false,
1137
+ "single_word": false,
1138
+ "special": true
1139
+ },
1140
+ "128142": {
1141
+ "content": "<|reserved_special_token_134|>",
1142
+ "lstrip": false,
1143
+ "normalized": false,
1144
+ "rstrip": false,
1145
+ "single_word": false,
1146
+ "special": true
1147
+ },
1148
+ "128143": {
1149
+ "content": "<|reserved_special_token_135|>",
1150
+ "lstrip": false,
1151
+ "normalized": false,
1152
+ "rstrip": false,
1153
+ "single_word": false,
1154
+ "special": true
1155
+ },
1156
+ "128144": {
1157
+ "content": "<|reserved_special_token_136|>",
1158
+ "lstrip": false,
1159
+ "normalized": false,
1160
+ "rstrip": false,
1161
+ "single_word": false,
1162
+ "special": true
1163
+ },
1164
+ "128145": {
1165
+ "content": "<|reserved_special_token_137|>",
1166
+ "lstrip": false,
1167
+ "normalized": false,
1168
+ "rstrip": false,
1169
+ "single_word": false,
1170
+ "special": true
1171
+ },
1172
+ "128146": {
1173
+ "content": "<|reserved_special_token_138|>",
1174
+ "lstrip": false,
1175
+ "normalized": false,
1176
+ "rstrip": false,
1177
+ "single_word": false,
1178
+ "special": true
1179
+ },
1180
+ "128147": {
1181
+ "content": "<|reserved_special_token_139|>",
1182
+ "lstrip": false,
1183
+ "normalized": false,
1184
+ "rstrip": false,
1185
+ "single_word": false,
1186
+ "special": true
1187
+ },
1188
+ "128148": {
1189
+ "content": "<|reserved_special_token_140|>",
1190
+ "lstrip": false,
1191
+ "normalized": false,
1192
+ "rstrip": false,
1193
+ "single_word": false,
1194
+ "special": true
1195
+ },
1196
+ "128149": {
1197
+ "content": "<|reserved_special_token_141|>",
1198
+ "lstrip": false,
1199
+ "normalized": false,
1200
+ "rstrip": false,
1201
+ "single_word": false,
1202
+ "special": true
1203
+ },
1204
+ "128150": {
1205
+ "content": "<|reserved_special_token_142|>",
1206
+ "lstrip": false,
1207
+ "normalized": false,
1208
+ "rstrip": false,
1209
+ "single_word": false,
1210
+ "special": true
1211
+ },
1212
+ "128151": {
1213
+ "content": "<|reserved_special_token_143|>",
1214
+ "lstrip": false,
1215
+ "normalized": false,
1216
+ "rstrip": false,
1217
+ "single_word": false,
1218
+ "special": true
1219
+ },
1220
+ "128152": {
1221
+ "content": "<|reserved_special_token_144|>",
1222
+ "lstrip": false,
1223
+ "normalized": false,
1224
+ "rstrip": false,
1225
+ "single_word": false,
1226
+ "special": true
1227
+ },
1228
+ "128153": {
1229
+ "content": "<|reserved_special_token_145|>",
1230
+ "lstrip": false,
1231
+ "normalized": false,
1232
+ "rstrip": false,
1233
+ "single_word": false,
1234
+ "special": true
1235
+ },
1236
+ "128154": {
1237
+ "content": "<|reserved_special_token_146|>",
1238
+ "lstrip": false,
1239
+ "normalized": false,
1240
+ "rstrip": false,
1241
+ "single_word": false,
1242
+ "special": true
1243
+ },
1244
+ "128155": {
1245
+ "content": "<|reserved_special_token_147|>",
1246
+ "lstrip": false,
1247
+ "normalized": false,
1248
+ "rstrip": false,
1249
+ "single_word": false,
1250
+ "special": true
1251
+ },
1252
+ "128156": {
1253
+ "content": "<|reserved_special_token_148|>",
1254
+ "lstrip": false,
1255
+ "normalized": false,
1256
+ "rstrip": false,
1257
+ "single_word": false,
1258
+ "special": true
1259
+ },
1260
+ "128157": {
1261
+ "content": "<|reserved_special_token_149|>",
1262
+ "lstrip": false,
1263
+ "normalized": false,
1264
+ "rstrip": false,
1265
+ "single_word": false,
1266
+ "special": true
1267
+ },
1268
+ "128158": {
1269
+ "content": "<|reserved_special_token_150|>",
1270
+ "lstrip": false,
1271
+ "normalized": false,
1272
+ "rstrip": false,
1273
+ "single_word": false,
1274
+ "special": true
1275
+ },
1276
+ "128159": {
1277
+ "content": "<|reserved_special_token_151|>",
1278
+ "lstrip": false,
1279
+ "normalized": false,
1280
+ "rstrip": false,
1281
+ "single_word": false,
1282
+ "special": true
1283
+ },
1284
+ "128160": {
1285
+ "content": "<|reserved_special_token_152|>",
1286
+ "lstrip": false,
1287
+ "normalized": false,
1288
+ "rstrip": false,
1289
+ "single_word": false,
1290
+ "special": true
1291
+ },
1292
+ "128161": {
1293
+ "content": "<|reserved_special_token_153|>",
1294
+ "lstrip": false,
1295
+ "normalized": false,
1296
+ "rstrip": false,
1297
+ "single_word": false,
1298
+ "special": true
1299
+ },
1300
+ "128162": {
1301
+ "content": "<|reserved_special_token_154|>",
1302
+ "lstrip": false,
1303
+ "normalized": false,
1304
+ "rstrip": false,
1305
+ "single_word": false,
1306
+ "special": true
1307
+ },
1308
+ "128163": {
1309
+ "content": "<|reserved_special_token_155|>",
1310
+ "lstrip": false,
1311
+ "normalized": false,
1312
+ "rstrip": false,
1313
+ "single_word": false,
1314
+ "special": true
1315
+ },
1316
+ "128164": {
1317
+ "content": "<|reserved_special_token_156|>",
1318
+ "lstrip": false,
1319
+ "normalized": false,
1320
+ "rstrip": false,
1321
+ "single_word": false,
1322
+ "special": true
1323
+ },
1324
+ "128165": {
1325
+ "content": "<|reserved_special_token_157|>",
1326
+ "lstrip": false,
1327
+ "normalized": false,
1328
+ "rstrip": false,
1329
+ "single_word": false,
1330
+ "special": true
1331
+ },
1332
+ "128166": {
1333
+ "content": "<|reserved_special_token_158|>",
1334
+ "lstrip": false,
1335
+ "normalized": false,
1336
+ "rstrip": false,
1337
+ "single_word": false,
1338
+ "special": true
1339
+ },
1340
+ "128167": {
1341
+ "content": "<|reserved_special_token_159|>",
1342
+ "lstrip": false,
1343
+ "normalized": false,
1344
+ "rstrip": false,
1345
+ "single_word": false,
1346
+ "special": true
1347
+ },
1348
+ "128168": {
1349
+ "content": "<|reserved_special_token_160|>",
1350
+ "lstrip": false,
1351
+ "normalized": false,
1352
+ "rstrip": false,
1353
+ "single_word": false,
1354
+ "special": true
1355
+ },
1356
+ "128169": {
1357
+ "content": "<|reserved_special_token_161|>",
1358
+ "lstrip": false,
1359
+ "normalized": false,
1360
+ "rstrip": false,
1361
+ "single_word": false,
1362
+ "special": true
1363
+ },
1364
+ "128170": {
1365
+ "content": "<|reserved_special_token_162|>",
1366
+ "lstrip": false,
1367
+ "normalized": false,
1368
+ "rstrip": false,
1369
+ "single_word": false,
1370
+ "special": true
1371
+ },
1372
+ "128171": {
1373
+ "content": "<|reserved_special_token_163|>",
1374
+ "lstrip": false,
1375
+ "normalized": false,
1376
+ "rstrip": false,
1377
+ "single_word": false,
1378
+ "special": true
1379
+ },
1380
+ "128172": {
1381
+ "content": "<|reserved_special_token_164|>",
1382
+ "lstrip": false,
1383
+ "normalized": false,
1384
+ "rstrip": false,
1385
+ "single_word": false,
1386
+ "special": true
1387
+ },
1388
+ "128173": {
1389
+ "content": "<|reserved_special_token_165|>",
1390
+ "lstrip": false,
1391
+ "normalized": false,
1392
+ "rstrip": false,
1393
+ "single_word": false,
1394
+ "special": true
1395
+ },
1396
+ "128174": {
1397
+ "content": "<|reserved_special_token_166|>",
1398
+ "lstrip": false,
1399
+ "normalized": false,
1400
+ "rstrip": false,
1401
+ "single_word": false,
1402
+ "special": true
1403
+ },
1404
+ "128175": {
1405
+ "content": "<|reserved_special_token_167|>",
1406
+ "lstrip": false,
1407
+ "normalized": false,
1408
+ "rstrip": false,
1409
+ "single_word": false,
1410
+ "special": true
1411
+ },
1412
+ "128176": {
1413
+ "content": "<|reserved_special_token_168|>",
1414
+ "lstrip": false,
1415
+ "normalized": false,
1416
+ "rstrip": false,
1417
+ "single_word": false,
1418
+ "special": true
1419
+ },
1420
+ "128177": {
1421
+ "content": "<|reserved_special_token_169|>",
1422
+ "lstrip": false,
1423
+ "normalized": false,
1424
+ "rstrip": false,
1425
+ "single_word": false,
1426
+ "special": true
1427
+ },
1428
+ "128178": {
1429
+ "content": "<|reserved_special_token_170|>",
1430
+ "lstrip": false,
1431
+ "normalized": false,
1432
+ "rstrip": false,
1433
+ "single_word": false,
1434
+ "special": true
1435
+ },
1436
+ "128179": {
1437
+ "content": "<|reserved_special_token_171|>",
1438
+ "lstrip": false,
1439
+ "normalized": false,
1440
+ "rstrip": false,
1441
+ "single_word": false,
1442
+ "special": true
1443
+ },
1444
+ "128180": {
1445
+ "content": "<|reserved_special_token_172|>",
1446
+ "lstrip": false,
1447
+ "normalized": false,
1448
+ "rstrip": false,
1449
+ "single_word": false,
1450
+ "special": true
1451
+ },
1452
+ "128181": {
1453
+ "content": "<|reserved_special_token_173|>",
1454
+ "lstrip": false,
1455
+ "normalized": false,
1456
+ "rstrip": false,
1457
+ "single_word": false,
1458
+ "special": true
1459
+ },
1460
+ "128182": {
1461
+ "content": "<|reserved_special_token_174|>",
1462
+ "lstrip": false,
1463
+ "normalized": false,
1464
+ "rstrip": false,
1465
+ "single_word": false,
1466
+ "special": true
1467
+ },
1468
+ "128183": {
1469
+ "content": "<|reserved_special_token_175|>",
1470
+ "lstrip": false,
1471
+ "normalized": false,
1472
+ "rstrip": false,
1473
+ "single_word": false,
1474
+ "special": true
1475
+ },
1476
+ "128184": {
1477
+ "content": "<|reserved_special_token_176|>",
1478
+ "lstrip": false,
1479
+ "normalized": false,
1480
+ "rstrip": false,
1481
+ "single_word": false,
1482
+ "special": true
1483
+ },
1484
+ "128185": {
1485
+ "content": "<|reserved_special_token_177|>",
1486
+ "lstrip": false,
1487
+ "normalized": false,
1488
+ "rstrip": false,
1489
+ "single_word": false,
1490
+ "special": true
1491
+ },
1492
+ "128186": {
1493
+ "content": "<|reserved_special_token_178|>",
1494
+ "lstrip": false,
1495
+ "normalized": false,
1496
+ "rstrip": false,
1497
+ "single_word": false,
1498
+ "special": true
1499
+ },
1500
+ "128187": {
1501
+ "content": "<|reserved_special_token_179|>",
1502
+ "lstrip": false,
1503
+ "normalized": false,
1504
+ "rstrip": false,
1505
+ "single_word": false,
1506
+ "special": true
1507
+ },
1508
+ "128188": {
1509
+ "content": "<|reserved_special_token_180|>",
1510
+ "lstrip": false,
1511
+ "normalized": false,
1512
+ "rstrip": false,
1513
+ "single_word": false,
1514
+ "special": true
1515
+ },
1516
+ "128189": {
1517
+ "content": "<|reserved_special_token_181|>",
1518
+ "lstrip": false,
1519
+ "normalized": false,
1520
+ "rstrip": false,
1521
+ "single_word": false,
1522
+ "special": true
1523
+ },
1524
+ "128190": {
1525
+ "content": "<|reserved_special_token_182|>",
1526
+ "lstrip": false,
1527
+ "normalized": false,
1528
+ "rstrip": false,
1529
+ "single_word": false,
1530
+ "special": true
1531
+ },
1532
+ "128191": {
1533
+ "content": "<|reserved_special_token_183|>",
1534
+ "lstrip": false,
1535
+ "normalized": false,
1536
+ "rstrip": false,
1537
+ "single_word": false,
1538
+ "special": true
1539
+ },
1540
+ "128192": {
1541
+ "content": "<|reserved_special_token_184|>",
1542
+ "lstrip": false,
1543
+ "normalized": false,
1544
+ "rstrip": false,
1545
+ "single_word": false,
1546
+ "special": true
1547
+ },
1548
+ "128193": {
1549
+ "content": "<|reserved_special_token_185|>",
1550
+ "lstrip": false,
1551
+ "normalized": false,
1552
+ "rstrip": false,
1553
+ "single_word": false,
1554
+ "special": true
1555
+ },
1556
+ "128194": {
1557
+ "content": "<|reserved_special_token_186|>",
1558
+ "lstrip": false,
1559
+ "normalized": false,
1560
+ "rstrip": false,
1561
+ "single_word": false,
1562
+ "special": true
1563
+ },
1564
+ "128195": {
1565
+ "content": "<|reserved_special_token_187|>",
1566
+ "lstrip": false,
1567
+ "normalized": false,
1568
+ "rstrip": false,
1569
+ "single_word": false,
1570
+ "special": true
1571
+ },
1572
+ "128196": {
1573
+ "content": "<|reserved_special_token_188|>",
1574
+ "lstrip": false,
1575
+ "normalized": false,
1576
+ "rstrip": false,
1577
+ "single_word": false,
1578
+ "special": true
1579
+ },
1580
+ "128197": {
1581
+ "content": "<|reserved_special_token_189|>",
1582
+ "lstrip": false,
1583
+ "normalized": false,
1584
+ "rstrip": false,
1585
+ "single_word": false,
1586
+ "special": true
1587
+ },
1588
+ "128198": {
1589
+ "content": "<|reserved_special_token_190|>",
1590
+ "lstrip": false,
1591
+ "normalized": false,
1592
+ "rstrip": false,
1593
+ "single_word": false,
1594
+ "special": true
1595
+ },
1596
+ "128199": {
1597
+ "content": "<|reserved_special_token_191|>",
1598
+ "lstrip": false,
1599
+ "normalized": false,
1600
+ "rstrip": false,
1601
+ "single_word": false,
1602
+ "special": true
1603
+ },
1604
+ "128200": {
1605
+ "content": "<|reserved_special_token_192|>",
1606
+ "lstrip": false,
1607
+ "normalized": false,
1608
+ "rstrip": false,
1609
+ "single_word": false,
1610
+ "special": true
1611
+ },
1612
+ "128201": {
1613
+ "content": "<|reserved_special_token_193|>",
1614
+ "lstrip": false,
1615
+ "normalized": false,
1616
+ "rstrip": false,
1617
+ "single_word": false,
1618
+ "special": true
1619
+ },
1620
+ "128202": {
1621
+ "content": "<|reserved_special_token_194|>",
1622
+ "lstrip": false,
1623
+ "normalized": false,
1624
+ "rstrip": false,
1625
+ "single_word": false,
1626
+ "special": true
1627
+ },
1628
+ "128203": {
1629
+ "content": "<|reserved_special_token_195|>",
1630
+ "lstrip": false,
1631
+ "normalized": false,
1632
+ "rstrip": false,
1633
+ "single_word": false,
1634
+ "special": true
1635
+ },
1636
+ "128204": {
1637
+ "content": "<|reserved_special_token_196|>",
1638
+ "lstrip": false,
1639
+ "normalized": false,
1640
+ "rstrip": false,
1641
+ "single_word": false,
1642
+ "special": true
1643
+ },
1644
+ "128205": {
1645
+ "content": "<|reserved_special_token_197|>",
1646
+ "lstrip": false,
1647
+ "normalized": false,
1648
+ "rstrip": false,
1649
+ "single_word": false,
1650
+ "special": true
1651
+ },
1652
+ "128206": {
1653
+ "content": "<|reserved_special_token_198|>",
1654
+ "lstrip": false,
1655
+ "normalized": false,
1656
+ "rstrip": false,
1657
+ "single_word": false,
1658
+ "special": true
1659
+ },
1660
+ "128207": {
1661
+ "content": "<|reserved_special_token_199|>",
1662
+ "lstrip": false,
1663
+ "normalized": false,
1664
+ "rstrip": false,
1665
+ "single_word": false,
1666
+ "special": true
1667
+ },
1668
+ "128208": {
1669
+ "content": "<|reserved_special_token_200|>",
1670
+ "lstrip": false,
1671
+ "normalized": false,
1672
+ "rstrip": false,
1673
+ "single_word": false,
1674
+ "special": true
1675
+ },
1676
+ "128209": {
1677
+ "content": "<|reserved_special_token_201|>",
1678
+ "lstrip": false,
1679
+ "normalized": false,
1680
+ "rstrip": false,
1681
+ "single_word": false,
1682
+ "special": true
1683
+ },
1684
+ "128210": {
1685
+ "content": "<|reserved_special_token_202|>",
1686
+ "lstrip": false,
1687
+ "normalized": false,
1688
+ "rstrip": false,
1689
+ "single_word": false,
1690
+ "special": true
1691
+ },
1692
+ "128211": {
1693
+ "content": "<|reserved_special_token_203|>",
1694
+ "lstrip": false,
1695
+ "normalized": false,
1696
+ "rstrip": false,
1697
+ "single_word": false,
1698
+ "special": true
1699
+ },
1700
+ "128212": {
1701
+ "content": "<|reserved_special_token_204|>",
1702
+ "lstrip": false,
1703
+ "normalized": false,
1704
+ "rstrip": false,
1705
+ "single_word": false,
1706
+ "special": true
1707
+ },
1708
+ "128213": {
1709
+ "content": "<|reserved_special_token_205|>",
1710
+ "lstrip": false,
1711
+ "normalized": false,
1712
+ "rstrip": false,
1713
+ "single_word": false,
1714
+ "special": true
1715
+ },
1716
+ "128214": {
1717
+ "content": "<|reserved_special_token_206|>",
1718
+ "lstrip": false,
1719
+ "normalized": false,
1720
+ "rstrip": false,
1721
+ "single_word": false,
1722
+ "special": true
1723
+ },
1724
+ "128215": {
1725
+ "content": "<|reserved_special_token_207|>",
1726
+ "lstrip": false,
1727
+ "normalized": false,
1728
+ "rstrip": false,
1729
+ "single_word": false,
1730
+ "special": true
1731
+ },
1732
+ "128216": {
1733
+ "content": "<|reserved_special_token_208|>",
1734
+ "lstrip": false,
1735
+ "normalized": false,
1736
+ "rstrip": false,
1737
+ "single_word": false,
1738
+ "special": true
1739
+ },
1740
+ "128217": {
1741
+ "content": "<|reserved_special_token_209|>",
1742
+ "lstrip": false,
1743
+ "normalized": false,
1744
+ "rstrip": false,
1745
+ "single_word": false,
1746
+ "special": true
1747
+ },
1748
+ "128218": {
1749
+ "content": "<|reserved_special_token_210|>",
1750
+ "lstrip": false,
1751
+ "normalized": false,
1752
+ "rstrip": false,
1753
+ "single_word": false,
1754
+ "special": true
1755
+ },
1756
+ "128219": {
1757
+ "content": "<|reserved_special_token_211|>",
1758
+ "lstrip": false,
1759
+ "normalized": false,
1760
+ "rstrip": false,
1761
+ "single_word": false,
1762
+ "special": true
1763
+ },
1764
+ "128220": {
1765
+ "content": "<|reserved_special_token_212|>",
1766
+ "lstrip": false,
1767
+ "normalized": false,
1768
+ "rstrip": false,
1769
+ "single_word": false,
1770
+ "special": true
1771
+ },
1772
+ "128221": {
1773
+ "content": "<|reserved_special_token_213|>",
1774
+ "lstrip": false,
1775
+ "normalized": false,
1776
+ "rstrip": false,
1777
+ "single_word": false,
1778
+ "special": true
1779
+ },
1780
+ "128222": {
1781
+ "content": "<|reserved_special_token_214|>",
1782
+ "lstrip": false,
1783
+ "normalized": false,
1784
+ "rstrip": false,
1785
+ "single_word": false,
1786
+ "special": true
1787
+ },
1788
+ "128223": {
1789
+ "content": "<|reserved_special_token_215|>",
1790
+ "lstrip": false,
1791
+ "normalized": false,
1792
+ "rstrip": false,
1793
+ "single_word": false,
1794
+ "special": true
1795
+ },
1796
+ "128224": {
1797
+ "content": "<|reserved_special_token_216|>",
1798
+ "lstrip": false,
1799
+ "normalized": false,
1800
+ "rstrip": false,
1801
+ "single_word": false,
1802
+ "special": true
1803
+ },
1804
+ "128225": {
1805
+ "content": "<|reserved_special_token_217|>",
1806
+ "lstrip": false,
1807
+ "normalized": false,
1808
+ "rstrip": false,
1809
+ "single_word": false,
1810
+ "special": true
1811
+ },
1812
+ "128226": {
1813
+ "content": "<|reserved_special_token_218|>",
1814
+ "lstrip": false,
1815
+ "normalized": false,
1816
+ "rstrip": false,
1817
+ "single_word": false,
1818
+ "special": true
1819
+ },
1820
+ "128227": {
1821
+ "content": "<|reserved_special_token_219|>",
1822
+ "lstrip": false,
1823
+ "normalized": false,
1824
+ "rstrip": false,
1825
+ "single_word": false,
1826
+ "special": true
1827
+ },
1828
+ "128228": {
1829
+ "content": "<|reserved_special_token_220|>",
1830
+ "lstrip": false,
1831
+ "normalized": false,
1832
+ "rstrip": false,
1833
+ "single_word": false,
1834
+ "special": true
1835
+ },
1836
+ "128229": {
1837
+ "content": "<|reserved_special_token_221|>",
1838
+ "lstrip": false,
1839
+ "normalized": false,
1840
+ "rstrip": false,
1841
+ "single_word": false,
1842
+ "special": true
1843
+ },
1844
+ "128230": {
1845
+ "content": "<|reserved_special_token_222|>",
1846
+ "lstrip": false,
1847
+ "normalized": false,
1848
+ "rstrip": false,
1849
+ "single_word": false,
1850
+ "special": true
1851
+ },
1852
+ "128231": {
1853
+ "content": "<|reserved_special_token_223|>",
1854
+ "lstrip": false,
1855
+ "normalized": false,
1856
+ "rstrip": false,
1857
+ "single_word": false,
1858
+ "special": true
1859
+ },
1860
+ "128232": {
1861
+ "content": "<|reserved_special_token_224|>",
1862
+ "lstrip": false,
1863
+ "normalized": false,
1864
+ "rstrip": false,
1865
+ "single_word": false,
1866
+ "special": true
1867
+ },
1868
+ "128233": {
1869
+ "content": "<|reserved_special_token_225|>",
1870
+ "lstrip": false,
1871
+ "normalized": false,
1872
+ "rstrip": false,
1873
+ "single_word": false,
1874
+ "special": true
1875
+ },
1876
+ "128234": {
1877
+ "content": "<|reserved_special_token_226|>",
1878
+ "lstrip": false,
1879
+ "normalized": false,
1880
+ "rstrip": false,
1881
+ "single_word": false,
1882
+ "special": true
1883
+ },
1884
+ "128235": {
1885
+ "content": "<|reserved_special_token_227|>",
1886
+ "lstrip": false,
1887
+ "normalized": false,
1888
+ "rstrip": false,
1889
+ "single_word": false,
1890
+ "special": true
1891
+ },
1892
+ "128236": {
1893
+ "content": "<|reserved_special_token_228|>",
1894
+ "lstrip": false,
1895
+ "normalized": false,
1896
+ "rstrip": false,
1897
+ "single_word": false,
1898
+ "special": true
1899
+ },
1900
+ "128237": {
1901
+ "content": "<|reserved_special_token_229|>",
1902
+ "lstrip": false,
1903
+ "normalized": false,
1904
+ "rstrip": false,
1905
+ "single_word": false,
1906
+ "special": true
1907
+ },
1908
+ "128238": {
1909
+ "content": "<|reserved_special_token_230|>",
1910
+ "lstrip": false,
1911
+ "normalized": false,
1912
+ "rstrip": false,
1913
+ "single_word": false,
1914
+ "special": true
1915
+ },
1916
+ "128239": {
1917
+ "content": "<|reserved_special_token_231|>",
1918
+ "lstrip": false,
1919
+ "normalized": false,
1920
+ "rstrip": false,
1921
+ "single_word": false,
1922
+ "special": true
1923
+ },
1924
+ "128240": {
1925
+ "content": "<|reserved_special_token_232|>",
1926
+ "lstrip": false,
1927
+ "normalized": false,
1928
+ "rstrip": false,
1929
+ "single_word": false,
1930
+ "special": true
1931
+ },
1932
+ "128241": {
1933
+ "content": "<|reserved_special_token_233|>",
1934
+ "lstrip": false,
1935
+ "normalized": false,
1936
+ "rstrip": false,
1937
+ "single_word": false,
1938
+ "special": true
1939
+ },
1940
+ "128242": {
1941
+ "content": "<|reserved_special_token_234|>",
1942
+ "lstrip": false,
1943
+ "normalized": false,
1944
+ "rstrip": false,
1945
+ "single_word": false,
1946
+ "special": true
1947
+ },
1948
+ "128243": {
1949
+ "content": "<|reserved_special_token_235|>",
1950
+ "lstrip": false,
1951
+ "normalized": false,
1952
+ "rstrip": false,
1953
+ "single_word": false,
1954
+ "special": true
1955
+ },
1956
+ "128244": {
1957
+ "content": "<|reserved_special_token_236|>",
1958
+ "lstrip": false,
1959
+ "normalized": false,
1960
+ "rstrip": false,
1961
+ "single_word": false,
1962
+ "special": true
1963
+ },
1964
+ "128245": {
1965
+ "content": "<|reserved_special_token_237|>",
1966
+ "lstrip": false,
1967
+ "normalized": false,
1968
+ "rstrip": false,
1969
+ "single_word": false,
1970
+ "special": true
1971
+ },
1972
+ "128246": {
1973
+ "content": "<|reserved_special_token_238|>",
1974
+ "lstrip": false,
1975
+ "normalized": false,
1976
+ "rstrip": false,
1977
+ "single_word": false,
1978
+ "special": true
1979
+ },
1980
+ "128247": {
1981
+ "content": "<|reserved_special_token_239|>",
1982
+ "lstrip": false,
1983
+ "normalized": false,
1984
+ "rstrip": false,
1985
+ "single_word": false,
1986
+ "special": true
1987
+ },
1988
+ "128248": {
1989
+ "content": "<|reserved_special_token_240|>",
1990
+ "lstrip": false,
1991
+ "normalized": false,
1992
+ "rstrip": false,
1993
+ "single_word": false,
1994
+ "special": true
1995
+ },
1996
+ "128249": {
1997
+ "content": "<|reserved_special_token_241|>",
1998
+ "lstrip": false,
1999
+ "normalized": false,
2000
+ "rstrip": false,
2001
+ "single_word": false,
2002
+ "special": true
2003
+ },
2004
+ "128250": {
2005
+ "content": "<|reserved_special_token_242|>",
2006
+ "lstrip": false,
2007
+ "normalized": false,
2008
+ "rstrip": false,
2009
+ "single_word": false,
2010
+ "special": true
2011
+ },
2012
+ "128251": {
2013
+ "content": "<|reserved_special_token_243|>",
2014
+ "lstrip": false,
2015
+ "normalized": false,
2016
+ "rstrip": false,
2017
+ "single_word": false,
2018
+ "special": true
2019
+ },
2020
+ "128252": {
2021
+ "content": "<|reserved_special_token_244|>",
2022
+ "lstrip": false,
2023
+ "normalized": false,
2024
+ "rstrip": false,
2025
+ "single_word": false,
2026
+ "special": true
2027
+ },
2028
+ "128253": {
2029
+ "content": "<|reserved_special_token_245|>",
2030
+ "lstrip": false,
2031
+ "normalized": false,
2032
+ "rstrip": false,
2033
+ "single_word": false,
2034
+ "special": true
2035
+ },
2036
+ "128254": {
2037
+ "content": "<|reserved_special_token_246|>",
2038
+ "lstrip": false,
2039
+ "normalized": false,
2040
+ "rstrip": false,
2041
+ "single_word": false,
2042
+ "special": true
2043
+ },
2044
+ "128255": {
2045
+ "content": "<|reserved_special_token_247|>",
2046
+ "lstrip": false,
2047
+ "normalized": false,
2048
+ "rstrip": false,
2049
+ "single_word": false,
2050
+ "special": true
2051
+ }
2052
+ },
2053
+ "bos_token": "<|begin_of_text|>",
2054
+ "chat_template": "{{- bos_token }}\n{%- if custom_tools is defined %}\n {%- set tools = custom_tools %}\n{%- endif %}\n{%- if not tools_in_user_message is defined %}\n {%- set tools_in_user_message = true %}\n{%- endif %}\n{%- if not date_string is defined %}\n {%- if strftime_now is defined %}\n {%- set date_string = strftime_now(\"%d %b %Y\") %}\n {%- else %}\n {%- set date_string = \"26 Jul 2024\" %}\n {%- endif %}\n{%- endif %}\n{%- if not tools is defined %}\n {%- set tools = none %}\n{%- endif %}\n\n{#- This block extracts the system message, so we can slot it into the right place. #}\n{%- if messages[0]['role'] == 'system' %}\n {%- set system_message = messages[0]['content']|trim %}\n {%- set messages = messages[1:] %}\n{%- else %}\n {%- set system_message = \"\" %}\n{%- endif %}\n\n{#- System message #}\n{{- \"<|start_header_id|>system<|end_header_id|>\\n\\n\" }}\n{%- if tools is not none %}\n {{- \"Environment: ipython\\n\" }}\n{%- endif %}\n{{- \"Cutting Knowledge Date: December 2023\\n\" }}\n{{- \"Today Date: \" + date_string + \"\\n\\n\" }}\n{%- if tools is not none and not tools_in_user_message %}\n {{- \"You have access to the following functions. To call a function, please respond with JSON for a function call.\" }}\n {{- 'Respond in the format {\"name\": function name, \"parameters\": dictionary of argument name and its value}.' }}\n {{- \"Do not use variables.\\n\\n\" }}\n {%- for t in tools %}\n {{- t | tojson(indent=4) }}\n {{- \"\\n\\n\" }}\n {%- endfor %}\n{%- endif %}\n{{- system_message }}\n{{- \"<|eot_id|>\" }}\n\n{#- Custom tools are passed in a user message with some extra guidance #}\n{%- if tools_in_user_message and not tools is none %}\n {#- Extract the first user message so we can plug it in here #}\n {%- if messages | length != 0 %}\n {%- set first_user_message = messages[0]['content']|trim %}\n {%- set messages = messages[1:] %}\n {%- else %}\n {{- raise_exception(\"Cannot put tools in the first user message when there's no first user message!\") }}\n{%- endif %}\n {{- '<|start_header_id|>user<|end_header_id|>\\n\\n' -}}\n {{- \"Given the following functions, please respond with a JSON for a function call \" }}\n {{- \"with its proper arguments that best answers the given prompt.\\n\\n\" }}\n {{- 'Respond in the format {\"name\": function name, \"parameters\": dictionary of argument name and its value}.' }}\n {{- \"Do not use variables.\\n\\n\" }}\n {%- for t in tools %}\n {{- t | tojson(indent=4) }}\n {{- \"\\n\\n\" }}\n {%- endfor %}\n {{- first_user_message + \"<|eot_id|>\"}}\n{%- endif %}\n\n{%- for message in messages %}\n {%- if not (message.role == 'ipython' or message.role == 'tool' or 'tool_calls' in message) %}\n {{- '<|start_header_id|>' + message['role'] + '<|end_header_id|>\\n\\n'+ message['content'] | trim + '<|eot_id|>' }}\n {%- elif 'tool_calls' in message %}\n {%- if not message.tool_calls|length == 1 %}\n {{- raise_exception(\"This model only supports single tool-calls at once!\") }}\n {%- endif %}\n {%- set tool_call = message.tool_calls[0].function %}\n {{- '<|start_header_id|>assistant<|end_header_id|>\\n\\n' -}}\n {{- '{\"name\": \"' + tool_call.name + '\", ' }}\n {{- '\"parameters\": ' }}\n {{- tool_call.arguments | tojson }}\n {{- \"}\" }}\n {{- \"<|eot_id|>\" }}\n {%- elif message.role == \"tool\" or message.role == \"ipython\" %}\n {{- \"<|start_header_id|>ipython<|end_header_id|>\\n\\n\" }}\n {%- if message.content is mapping or message.content is iterable %}\n {{- message.content | tojson }}\n {%- else %}\n {{- message.content }}\n {%- endif %}\n {{- \"<|eot_id|>\" }}\n {%- endif %}\n{%- endfor %}\n{%- if add_generation_prompt %}\n {{- '<|start_header_id|>assistant<|end_header_id|>\\n\\n' }}\n{%- endif %}\n",
2055
+ "clean_up_tokenization_spaces": true,
2056
+ "eos_token": "<|eot_id|>",
2057
+ "extra_special_tokens": {},
2058
+ "model_input_names": [
2059
+ "input_ids",
2060
+ "attention_mask"
2061
+ ],
2062
+ "model_max_length": 131072,
2063
+ "pad_token": "<|finetune_right_pad_id|>",
2064
+ "padding_side": "right",
2065
+ "tokenizer_class": "PreTrainedTokenizer",
2066
+ "unk_token": null
2067
+ }
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)