quoc-khanh commited on
Commit
4993b07
·
verified ·
1 Parent(s): 24c98f4

Create helpers.py

Browse files
Files changed (1) hide show
  1. helpers.py +255 -0
helpers.py ADDED
@@ -0,0 +1,255 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from docx import Document
2
+ import json
3
+ import datetime
4
+ import tempfile
5
+ from pathlib import Path
6
+ from unidecode import unidecode
7
+ from langchain.document_loaders import JSONLoader, UnstructuredWordDocumentLoader, WebBaseLoader
8
+ from langchain_text_splitters import RecursiveCharacterTextSplitter, RecursiveJsonSplitter
9
+ from langchain_community.vectorstores import FAISS
10
+ from langchain_google_genai import GoogleGenerativeAIEmbeddings, ChatGoogleGenerativeAI
11
+ import google.generativeai as genai
12
+ from tqdm import tqdm
13
+ from pathlib import Path
14
+ import shutil
15
+ import requests
16
+ from bs4 import BeautifulSoup
17
+
18
+ async def get_urls_splits(url='https://nct.neu.edu.vn/', char='https://nct.neu.edu.vn/'):
19
+ reqs = requests.get(url)
20
+ soup = BeautifulSoup(reqs.text, 'html.parser')
21
+
22
+ urls = []
23
+ for link in soup.find_all('a', href=True): # Chỉ lấy thẻ có 'href'
24
+ href = link.get('href')
25
+ if href.startswith(char):
26
+ urls.append(href)
27
+ return urls
28
+ # docs = []
29
+ # for page_url in url:
30
+ # loader = WebBaseLoader(web_paths=[page_url])
31
+ # async for doc in loader.alazy_load():
32
+ # docs.append(doc)
33
+
34
+ # assert len(docs) == 1
35
+ # # doc = docs[0]
36
+
37
+ # return docs
38
+
39
+ # Ví dụ sử dụng
40
+ # nct_urls = get_nct_urls('https://nct.neu.edu.vn/')
41
+ # print(nct_urls)
42
+
43
+ def log_message(messages, filename="chat_log.txt"):
44
+ """Ghi lịch sử tin nhắn vào file log"""
45
+ with open(filename, "a", encoding="utf-8") as f:
46
+ log_entry = {
47
+ "timestamp": datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
48
+ "conversation": messages
49
+ }
50
+ f.write(json.dumps(log_entry, ensure_ascii=False) + "\n")
51
+
52
+ def remove_tables_from_docx(file_path):
53
+ """Tạo bản sao của file DOCX nhưng loại bỏ tất cả bảng bên trong."""
54
+ doc = Document(file_path)
55
+ new_doc = Document()
56
+
57
+ for para in doc.paragraphs:
58
+ new_doc.add_paragraph(para.text)
59
+
60
+ # 📌 Lưu vào file tạm, đảm bảo đóng đúng cách
61
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".docx") as temp_file:
62
+ temp_path = temp_file.name
63
+ new_doc.save(temp_path)
64
+
65
+ return temp_path # ✅ Trả về đường dẫn file mới, không làm hỏng file gốc
66
+
67
+ def load_text_data(file_path):
68
+ """Tải nội dung văn bản từ file DOCX (đã loại bảng)."""
69
+ cleaned_file = remove_tables_from_docx(file_path)
70
+ return UnstructuredWordDocumentLoader(cleaned_file).load()
71
+
72
+
73
+ def extract_tables_from_docx(file_path):
74
+ doc = Document(file_path)
75
+ tables = []
76
+ all_paragraphs = [p.text.strip() for p in doc.paragraphs if p.text.strip()] # Lấy tất cả đoạn văn bản không rỗng
77
+
78
+ table_index = 0
79
+ para_index = 0
80
+ table_positions = []
81
+
82
+ # Xác định vị trí của bảng trong tài liệu
83
+ for element in doc.element.body:
84
+ if element.tag.endswith("tbl"):
85
+ table_positions.append((table_index, para_index))
86
+ table_index += 1
87
+ elif element.tag.endswith("p"):
88
+ para_index += 1
89
+
90
+ for idx, (table_idx, para_idx) in enumerate(table_positions):
91
+ data = []
92
+ for row in doc.tables[table_idx].rows:
93
+ data.append([cell.text.strip() for cell in row.cells])
94
+
95
+ if len(data) > 1: # Chỉ lấy bảng có dữ liệu
96
+ # Lấy 5 dòng trước và sau bảng
97
+ related_start = max(0, para_idx - 5)
98
+ related_end = min(len(all_paragraphs), para_idx + 5)
99
+ related_text = all_paragraphs[related_start:related_end]
100
+ tables.append({"table": idx + 1, "content": data, "related": related_text})
101
+ return tables
102
+
103
+ def convert_to_json(tables):
104
+ structured_data = {}
105
+
106
+ for table in tables:
107
+ headers = [unidecode(h) for h in table["content"][0]] # Bỏ dấu ở headers
108
+ rows = [[unidecode(cell) for cell in row] for row in table["content"][1:]] # Bỏ dấu ở dữ liệu
109
+ json_table = [dict(zip(headers, row)) for row in rows if len(row) == len(headers)]
110
+
111
+ related_text = [unidecode(text) for text in table["related"]] # Bỏ dấu ở văn bản liên quan
112
+
113
+ structured_data[table["table"]] = {
114
+ "content": json_table,
115
+ "related": related_text
116
+ }
117
+
118
+ return json.dumps(structured_data, indent=4, ensure_ascii=False)
119
+
120
+
121
+ def save_json_to_file(json_data, output_path):
122
+ with open(output_path, 'w', encoding='utf-8') as f:
123
+ json.dump(json.loads(json_data), f, ensure_ascii=False, indent=4)
124
+
125
+ # def load_json_with_langchain(json_path):
126
+ # loader = JSONLoader(file_path=json_path, jq_schema='.. | .content?', text_content=False)
127
+ # data = loader.load()
128
+
129
+ # # # Kiểm tra xem dữ liệu có bị lỗi không
130
+ # # print("Sample Data:", data[:2]) # In thử 2 dòng đầu
131
+ # return data
132
+
133
+ def load_json_manually(json_path):
134
+ with open(json_path, 'r', encoding='utf-8') as f:
135
+ data = json.load(f)
136
+ return data
137
+
138
+ def load_table_data(filepath, output_json_path):
139
+ tables = extract_tables_from_docx(file_path)
140
+ json_output = convert_to_json(tables)
141
+ save_json_to_file(json_output, output_json_path)
142
+
143
+ table_data = load_json_manually(output_json_path)
144
+ return table_data
145
+
146
+ def get_splits(file_path, output_json_path):
147
+ table_data = load_table_data(file_path, output_json_path)
148
+ text_data = load_text_data(file_path)
149
+
150
+ # Chia nhỏ văn bản
151
+ json_splitter = RecursiveJsonSplitter(max_chunk_size = 1000)
152
+ text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=250)
153
+
154
+ table_splits = json_splitter.create_documents(texts=[table_data])
155
+ text_splits = text_splitter.split_documents(text_data)
156
+ all_splits = table_splits + text_splits
157
+ return all_splits
158
+
159
+ def get_json_splits_only(file_path):
160
+ table_data = load_json_manually(file_path)
161
+
162
+ def remove_accents(obj): #xoa dau tieng viet
163
+ if isinstance(obj, str):
164
+ return unidecode(obj)
165
+ elif isinstance(obj, list):
166
+ return [remove_accents(item) for item in obj]
167
+ elif isinstance(obj, dict):
168
+ return {remove_accents(k): remove_accents(v) for k, v in obj.items()}
169
+ return obj
170
+
171
+ cleaned_data = remove_accents(table_data)
172
+ wrapped_data = {"data": cleaned_data} if isinstance(cleaned_data, list) else cleaned_data
173
+
174
+ json_splitter = RecursiveJsonSplitter(max_chunk_size = 512)
175
+ text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=250)
176
+
177
+ table_splits = json_splitter.create_documents(texts=[wrapped_data])
178
+ table_splits = text_splitter.split_documents(table_splits)
179
+
180
+ return table_splits
181
+
182
+ def list_docx_files(folder_path):
183
+ return [str(file) for file in Path(folder_path).rglob("*.docx")]
184
+
185
+ def prompt_order(queries):
186
+ text = 'IMPORTANT: Here is the questions of user in order, use that and the context above to know the best answer:\n'
187
+ i = 0
188
+ for q in queries:
189
+ i += 1
190
+ text += f'Question {i}: {str(q)}\n'
191
+ return text
192
+
193
+ # Define the augment_prompt function
194
+ def augment_prompt(query: str, k: int = 10):
195
+ queries = []
196
+ queries.append(query)
197
+
198
+ retriever = vectorstore.as_retriever(search_kwargs={"k": k})
199
+ results = retriever.invoke(query)
200
+
201
+ if results:
202
+ source_knowledge = "\n\n".join([doc.page_content for doc in results])
203
+ return f"""Using the contexts below, answer the query.
204
+
205
+ Contexts:
206
+ {source_knowledge}
207
+
208
+ """
209
+ else:
210
+ return f"No relevant context found.\n."
211
+
212
+ def get_answer(query, queries_list=None):
213
+ if queries_list is None:
214
+ queries_list = []
215
+
216
+ messages = [
217
+ {"role": "user", "parts": [{"text": "IMPORTANT: You are a super energetic, helpful, polite, Vietnamese-speaking assistant. If you can not see the answer in contexts, try to search it up online by yourself but remember to give the source."}]},
218
+ {"role": "user", "parts": [{"text": augment_prompt(query)}]}
219
+ ]
220
+ # bonus = '''
221
+ # Bạn tham kháo thêm các nguồn thông tin tại:
222
+ # Trang thông tin điện tử: https://neu.edu.vn ; https://daotao.neu.edu.vn
223
+ # Trang mạng xã hội có thông tin tuyển sinh: https://www.facebook.com/ktqdNEU ; https://www.facebook.com/tvtsneu ;
224
+ # Email tuyển sinh: [email protected]
225
+ # Số điện thoại tuyển sinh: 0888.128.558
226
+ # '''
227
+
228
+ queries_list.append(query)
229
+ queries = {"role": "user", "parts": [{"text": prompt_order(queries_list)}]}
230
+ messages_with_queries = messages.copy()
231
+ messages_with_queries.append(queries)
232
+ # messages_with_queries.insert(0, queries)
233
+
234
+ # Configure API key
235
+ genai.configure(api_key=key)
236
+
237
+ # Initialize the Gemini model
238
+ model = genai.GenerativeModel("gemini-2.0-flash")
239
+
240
+ response = model.generate_content(contents=messages_with_queries, stream=True)
241
+ response_text = ""
242
+
243
+ for chunk in response:
244
+ response_text += chunk.text
245
+ yield response_text
246
+
247
+ messages.append({"role": "model", "parts": [{"text": response_text}]})
248
+
249
+ # user_feedback = yield "\nNhập phản hồi của bạn (hoặc nhập 'q' để thoát): "
250
+ # if user_feedback.lower() == "q":
251
+ # break
252
+
253
+ # messages.append({"role": "user", "parts": [{"text": query}]})
254
+
255
+ log_message(messages)