kltn20133118 commited on
Commit
20df729
·
verified ·
1 Parent(s): 7fb2e71

Update function/chatbot.py

Browse files
Files changed (1) hide show
  1. function/chatbot.py +725 -725
function/chatbot.py CHANGED
@@ -1,726 +1,726 @@
1
- from langchain.text_splitter import CharacterTextSplitter
2
- import json
3
- import os
4
- import random
5
- import re
6
- from concurrent.futures import ThreadPoolExecutor, as_completed
7
- import google.generativeai as genai
8
- import nltk
9
- import pandas as pd
10
- from groq import Groq
11
- from langchain.chains.summarize import load_summarize_chain
12
- from langchain.docstore.document import Document
13
- from langchain.prompts import PromptTemplate
14
- from langchain.retrievers import BM25Retriever, EnsembleRetriever
15
- from langchain.retrievers.contextual_compression import ContextualCompressionRetriever
16
- from langchain.text_splitter import CharacterTextSplitter
17
- from langchain.text_splitter import RecursiveCharacterTextSplitter
18
- from langchain_cohere import CohereRerank
19
- from langchain_community.document_loaders import Docx2txtLoader
20
- from langchain_community.document_loaders import TextLoader
21
- from langchain_community.document_loaders import UnstructuredCSVLoader
22
- from langchain_community.document_loaders import UnstructuredExcelLoader
23
- from langchain_community.document_loaders import UnstructuredHTMLLoader
24
- from langchain_community.document_loaders import UnstructuredMarkdownLoader
25
- from langchain_community.document_loaders import UnstructuredPDFLoader
26
- from langchain_community.document_loaders import UnstructuredPowerPointLoader
27
- from langchain_community.document_loaders import UnstructuredXMLLoader
28
- from langchain_community.document_loaders.csv_loader import CSVLoader
29
- from langchain_community.llms import Cohere
30
- from langchain_community.vectorstores import Chroma
31
- from langchain_core.output_parsers.openai_tools import PydanticToolsParser
32
- from langchain_core.prompts import ChatPromptTemplate
33
- from langchain_core.pydantic_v1 import BaseModel, Field
34
- from langchain_core.runnables import RunnablePassthrough
35
- from langchain_openai import ChatOpenAI
36
- from typing import List
37
- from nltk.corpus import stopwords
38
- from nltk.tokenize import word_tokenize
39
- nltk.download('punkt')
40
-
41
- def process_json_file(file_path):
42
- json_data = []
43
- with open(file_path, 'r') as file:
44
- for line in file:
45
- try:
46
- data = json.loads(line)
47
- json_data.append(data)
48
- except json.JSONDecodeError:
49
- try:
50
- data = json.loads(line[:-1])
51
- json_data.append(data)
52
- except json.JSONDecodeError as e:
53
- print(f"Error decoding JSON: {e}")
54
- return json_data
55
-
56
- from dotenv import load_dotenv
57
- import os
58
- load_dotenv()
59
- GROQ_API_KEY = os.getenv("GROQ_API_KEY")
60
- COHERE_API_KEY = os.getenv("COHERE_API_KEY")
61
- OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
62
- GOOGLE_API_KEY1= os.getenv("GOOGLE_API_KEY_1")
63
- GOOGLE_API_KEY= os.getenv("GOOGLE_API_KEY")
64
- os.environ["COHERE_API_KEY"] = COHERE_API_KEY
65
- os.environ["OPENAI_API_KEY"] = OPENAI_API_KEY
66
- client = Groq(
67
- api_key= GROQ_API_KEY,
68
- )
69
- genai.configure(api_key=GOOGLE_API_KEY1)
70
- os.environ["GOOGLE_API_KEY"] = GOOGLE_API_KEY
71
- from langchain_google_genai import GoogleGenerativeAIEmbeddings, ChatGoogleGenerativeAI
72
- embeddings = GoogleGenerativeAIEmbeddings(model="models/embedding-001", task_type="retrieval_document")
73
- llm = ChatGoogleGenerativeAI(model='gemini-pro',
74
- max_output_tokens=2048,
75
- temperature=0.2,
76
- convert_system_message_to_human=True)
77
- def extract_multi_metadata_content(texts, tests):
78
- extracted_content = []
79
- precomputed_metadata = [x.metadata['source'].lower() for x in texts]
80
- for idx, test in enumerate(tests):
81
- temp_content = []
82
- test_terms = set(test.lower().split())
83
- for metadata_lower, x in zip(precomputed_metadata, texts):
84
- if any(term in metadata_lower for term in test_terms):
85
- temp_content.append(x.page_content)
86
- if idx == 0:
87
- extracted_content.append(f"Dữ liệu của {test}:\n{''.join(temp_content)}")
88
- else:
89
- extracted_content.append(''.join(temp_content))
90
- return '\n'.join(extracted_content)
91
- import unicodedata
92
- def text_preprocessing(text):
93
- text = text.lower()
94
- emoji_pattern = re.compile("["
95
- u"\U0001F600-\U0001F64F" # emoticons
96
- u"\U0001F300-\U0001F5FF" # symbols & pictographs
97
- u"\U0001F680-\U0001F6FF" # transport & map symbols
98
- u"\U0001F1E0-\U0001F1FF" # flags (iOS)
99
- u"\U00002500-\U00002BEF" # chinese char
100
- u"\U00002702-\U000027B0"
101
- u"\U000024C2-\U0001F251"
102
- u"\U0001f926-\U0001f937"
103
- u"\U00010000-\U0010ffff"
104
- u"\u2640-\u2642"
105
- u"\u2600-\u2B55"
106
- u"\u200d"
107
- u"\u23cf"
108
- u"\u23e9"
109
- u"\u231a"
110
- u"\ufe0f" # dingbats
111
- u"\u3030"
112
- "]+", flags=re.UNICODE)
113
- text = emoji_pattern.sub(r'', text)
114
- text = unicodedata.normalize('NFC', text)
115
- words = text.split()
116
- text = ' '.join(words)
117
- return text
118
- def find_matching_files_in_docs_12_id(text, id):
119
- folder_path = f"./user_file/{id}"
120
- search_terms = []
121
- search_terms_old = []
122
- matching_index = []
123
- search_origin = re.findall(r'\b\w+\.\w+\b|\b\w+\b', text)
124
- search_terms_origin = []
125
- for word in search_origin:
126
- if '.' in word:
127
- search_terms_origin.append(word)
128
- else:
129
- search_terms_origin.extend(re.findall(r'\b\w+\b', word))
130
-
131
- file_names_with_extension = re.findall(r'\b\w+\.\w+\b|\b\w+\b', text.lower())
132
- file_names_with_extension_old = re.findall(r'\b(\w+\.\w+)\b', text)
133
- for file_name in search_terms_origin:
134
- if "." in file_name:
135
- search_terms_old.append(file_name)
136
- for file_name in file_names_with_extension_old:
137
- if "." in file_name:
138
- search_terms_old.append(file_name)
139
- for file_name in file_names_with_extension:
140
- search_terms.append(file_name)
141
- clean_text_old = text
142
- clean_text = text.lower()
143
- for term in search_terms_old:
144
- clean_text_old = clean_text_old.replace(term, '')
145
- for term in search_terms:
146
- clean_text = clean_text.replace(term, '')
147
- words_old = re.findall(r'\b\w+\b', clean_text_old)
148
- search_terms_old.extend(words_old)
149
- matching_files = set()
150
- for root, dirs, files in os.walk(folder_path):
151
- for file in files:
152
- for term in search_terms:
153
- if term.lower() in file.lower():
154
- term_position = search_terms.index(term)
155
- matching_files.add(file)
156
- matching_index.append(term_position)
157
- break
158
- matching_files_old1 = []
159
- matching_index.sort()
160
- for x in matching_index:
161
- matching_files_old1.append(search_terms_origin[x])
162
- return matching_files, matching_files_old1
163
-
164
- def convert_xlsx_to_csv(xlsx_file_path, csv_file_path):
165
- df = pd.read_excel(xlsx_file_path)
166
- df.to_csv(csv_file_path, index=False)
167
-
168
- def save_list_CSV_id(file_list, id):
169
- text = ""
170
- for x in file_list:
171
- if x.endswith('.xlsx'):
172
- old = f"./user_file/{id}/{x}"
173
- new = old.replace(".xlsx", ".csv")
174
- convert_xlsx_to_csv(old, new)
175
- x = x.replace(".xlsx", ".csv")
176
- loader1 = CSVLoader(f"./user_file/{id}/{x}")
177
- docs1 = loader1.load()
178
- text += f"Dữ liệu file {x}:\n"
179
- for z in docs1:
180
- text += z.page_content + "\n"
181
- return text
182
-
183
- def merge_files(file_set, file_list):
184
- """Hàm này ghép lại các tên file dựa trên điều kiện đã cho."""
185
- merged_files = {}
186
- for file_name in file_list:
187
- name = file_name.split('.')[0]
188
- for f in file_set:
189
- if name in f:
190
- merged_files[name] = f
191
- break
192
- return merged_files
193
-
194
- def replace_keys_with_values(original_dict, replacement_dict):
195
- new_dict = {}
196
- for key, value in original_dict.items():
197
- if key in replacement_dict:
198
- new_key = replacement_dict[key]
199
- new_dict[new_key] = value
200
- else:
201
- new_dict[key] = value
202
- return new_dict
203
-
204
- def aws1_csv_id(new_dict_csv, id):
205
- text = ""
206
- query_all = ""
207
- keyword = []
208
- for key, value in new_dict_csv.items():
209
- print(key, value)
210
- query_all += value
211
- keyword.append(key)
212
- test = save_list_CSV_id(keyword, id)
213
- text += test
214
- sources = ",".join(keyword)
215
- return text, query_all, sources
216
-
217
- def chat_llama3(prompt_query):
218
- try:
219
- chat_completion = client.chat.completions.create(
220
- messages=[
221
- {
222
- "role": "system",
223
- "content": "Bạn là một trợ lý trung thưc, trả lời dựa trên nội dung tài liệu được cung cấp. Chỉ trả lời liên quan đến câu hỏi một cách đầy đủ chính xác, không bỏ sót thông tin."
224
- },
225
- {
226
-
227
- "role": "user",
228
- "content": f"{prompt_query}",
229
- }
230
- ],
231
- model="llama3-70b-8192",
232
- temperature=0.0,
233
- max_tokens=9000,
234
- stop=None,
235
- stream=False,
236
- )
237
- return chat_completion.choices[0].message.content
238
- except Exception as error:
239
- return False
240
-
241
- def chat_gemini(prompt):
242
- generation_config = {
243
- "temperature": 0.0,
244
- "top_p": 0.0,
245
- "top_k": 0,
246
- "max_output_tokens": 8192,
247
- }
248
- safety_settings = [
249
- {
250
- "category": "HARM_CATEGORY_HARASSMENT",
251
- "threshold": "BLOCK_MEDIUM_AND_ABOVE"
252
- },
253
- {
254
- "category": "HARM_CATEGORY_HATE_SPEECH",
255
- "threshold": "BLOCK_MEDIUM_AND_ABOVE"
256
- },
257
- {
258
- "category": "HARM_CATEGORY_SEXUALLY_EXPLICIT",
259
- "threshold": "BLOCK_MEDIUM_AND_ABOVE"
260
- },
261
- {
262
- "category": "HARM_CATEGORY_DANGEROUS_CONTENT",
263
- "threshold": "BLOCK_MEDIUM_AND_ABOVE"
264
- },
265
- ]
266
- model = genai.GenerativeModel(model_name="gemini-1.5-pro-latest",
267
- generation_config=generation_config,
268
- safety_settings=safety_settings)
269
- convo = model.start_chat(history=[])
270
- convo.send_message(prompt)
271
- return convo.last.text
272
-
273
- def question_answer(question):
274
- completion = chat_llama3(question)
275
- if completion:
276
- return completion
277
- else:
278
- answer = chat_gemini(question)
279
- return answer
280
-
281
- def check_persist_directory(id, file_name):
282
- directory_path = f"./vector_database/{id}/{file_name}"
283
- return os.path.exists(directory_path)
284
-
285
- from langchain_community.vectorstores import FAISS
286
-
287
- def check_path_exists(path):
288
- return os.path.exists(path)
289
- def aws1_all_id(new_dict, text_alls, id, thread_id):
290
- answer = ""
291
- COHERE_API_KEY1 = os.getenv("COHERE_API_KEY_1")
292
- os.environ["COHERE_API_KEY"] = COHERE_API_KEY1
293
- answer_relevant = ""
294
- directory = ""
295
- for key, value in new_dict.items():
296
- query = value
297
- query = text_preprocessing(query)
298
- keyword, keyword2 = find_matching_files_in_docs_12_id(query, id)
299
- data = extract_multi_metadata_content(text_alls, keyword)
300
- if keyword:
301
- file_name = next(iter(keyword))
302
- text_splitter = CharacterTextSplitter(chunk_size=3200, chunk_overlap=1500)
303
- texts_data = text_splitter.split_text(data)
304
-
305
- if check_persist_directory(id, file_name):
306
- vectordb_query = Chroma(persist_directory=f"./vector_database/{id}/{file_name}", embedding_function=embeddings)
307
- else:
308
- vectordb_query = Chroma.from_texts(texts_data,
309
- embedding=embeddings,
310
- persist_directory=f"./vector_database/{id}/{file_name}")
311
-
312
- k_1 = len(texts_data)
313
- retriever = vectordb_query.as_retriever(search_kwargs={f"k": k_1})
314
- bm25_retriever = BM25Retriever.from_texts(texts_data)
315
- bm25_retriever.k = k_1
316
- ensemble_retriever = EnsembleRetriever(retrievers=[bm25_retriever, retriever],
317
- weights=[0.6, 0.4])
318
- docs = ensemble_retriever.get_relevant_documents(f"{query}")
319
-
320
- path = f"./vector_database/FAISS/{id}/{file_name}"
321
- if check_path_exists(path):
322
- docsearch = FAISS.load_local(path, embeddings, allow_dangerous_deserialization=True)
323
- else:
324
- docsearch = FAISS.from_documents(docs, embeddings)
325
- docsearch.save_local(f"./vector_database/FAISS/{id}/{file_name}")
326
- docsearch = FAISS.load_local(path, embeddings, allow_dangerous_deserialization=True)
327
-
328
- k_2 = len(docs)
329
- compressor = CohereRerank(top_n=3)
330
- retrieve3 = docsearch.as_retriever(search_kwargs={f"k": k_2})
331
- compression_retriever = ContextualCompressionRetriever(
332
- base_compressor=compressor, base_retriever=retrieve3
333
- )
334
- compressed_docs = compression_retriever.get_relevant_documents(f"{query}")
335
-
336
- if compressed_docs:
337
- data = compressed_docs[0].page_content
338
- text = ''.join(map(lambda x: x.page_content, compressed_docs))
339
- prompt_document = f"Dựa vào nội dung sau:{text}. Hãy trả lời câu hỏi sau đây: {query}. Mà không thay đổi nội dung mà mình đã cung cấp. Cuối cùng nếu câu hỏi sử dụng tiếng Việt thì phải trả lời bằng Vietnamese. Nếu câu hỏi sử dụng tiếng Anh phải trả lời bằng English"
340
- answer_for = question_answer(prompt_document)
341
- answer += answer_for + "\n"
342
- answer_relevant = data
343
- directory = file_name
344
-
345
- return answer, answer_relevant, directory
346
-
347
-
348
- def extract_content_between_keywords(query, keywords):
349
- contents = {}
350
- num_keywords = len(keywords)
351
- keyword_positions = []
352
- for i in range(num_keywords):
353
- keyword = keywords[i]
354
- keyword_position = query.find(keyword)
355
- keyword_positions.append(keyword_position)
356
- if keyword_position == -1:
357
- continue
358
- next_keyword_position = len(query)
359
- for j in range(i + 1, num_keywords):
360
- next_keyword = keywords[j]
361
- next_keyword_position = query.find(next_keyword)
362
- if next_keyword_position != -1:
363
- break
364
- if i == 0:
365
- content_before = query[:keyword_position].strip()
366
- else:
367
- content_before = query[keyword_positions[i - 1] + len(keywords[i - 1]):keyword_position].strip()
368
- if i == num_keywords - 1:
369
- content_after = query[keyword_position + len(keyword):].strip()
370
- else:
371
- content_after = query[keyword_position + len(keyword):next_keyword_position].strip()
372
- content = f"{content_before} {keyword} {content_after}"
373
- contents[keyword] = content
374
- return contents
375
-
376
- def generate_random_questions(filtered_ques_list):
377
- if len(filtered_ques_list) >= 2:
378
- random_questions = random.sample(filtered_ques_list, 2)
379
- else:
380
- random_questions = filtered_ques_list
381
- return random_questions
382
-
383
- def generate_question_main(loader, name_file):
384
- text_splitter = RecursiveCharacterTextSplitter(chunk_size=4500, chunk_overlap=2500)
385
- texts = text_splitter.split_documents(loader)
386
- question_gen = f"nội dung {name_file} : \n"
387
- question_gen += texts[0].page_content
388
- splitter_ques_gen = RecursiveCharacterTextSplitter(
389
- chunk_size=4500,
390
- chunk_overlap=2200
391
- )
392
- chunks_ques_gen = splitter_ques_gen.split_text(question_gen)
393
- document_ques_gen = [Document(page_content=t) for t in chunks_ques_gen]
394
- llm_ques_gen_pipeline = llm
395
- prompt_template_vn = """
396
- Bạn là một chuyên gia tạo câu hỏi dựa trên tài liệu và tài liệu hướng dẫn.
397
- Bạn làm điều này bằng cách đặt các câu hỏi về đoạn văn bản dưới đây:
398
-
399
- ------------
400
- {text}
401
- ------------
402
-
403
- Hãy tạo ra các câu hỏi từ đoạn văn bản này.Nếu đoạn văn là tiếng Việt hãy tạo câu hỏi tiếng Việt. Nếu đoạn văn là tiếng Anh hãy tạo câu hỏi tiếng Anh.
404
- Hãy chắc chắn không bỏ sót bất kỳ thông tin quan trọng nào. Và chỉ tạo với đoạn tài liệu đó tối đa 5 câu hỏi liên quan tới tài liệu cung cấp nhất.Nếu trong đoạn tài liệu có các tên liên quan đến file như demo1.pdf( nhiều file khác) thì phải kèm nó vào nội dung câu hỏi bạn tạo ra.
405
-
406
- CÁC CÂU HỎI:
407
- """
408
-
409
- PROMPT_QUESTIONS_VN = PromptTemplate(template=prompt_template_vn, input_variables=["text"])
410
- refine_template_vn = ("""
411
- Bạn là một chuyên gia tạo câu hỏi thực hành dựa trên tài liệu và tài liệu hướng dẫn.
412
- Mục tiêu của bạn là giúp người học chuẩn bị cho một kỳ thi.
413
- Chúng tôi đã nhận được một số câu hỏi thực hành ở mức độ nào đó: {existing_answer}.
414
- Chúng tôi có thể tinh chỉnh các câu hỏi hiện có hoặc thêm câu hỏi mới
415
- (chỉ khi cần thiết) với một số ngữ cảnh bổ sung dưới đây.
416
- ------------
417
- {text}
418
- ------------
419
-
420
- Dựa trên ngữ cảnh mới, hãy tinh chỉnh các câu hỏi bằng tiếng Việt nếu đoạn văn đó cung cấp tiếng Việt. Nếu không hãy tinh chỉnh câu hỏi bằng tiếng Anh nếu đoạn đó cung cấp tiếng Anh.
421
- Nếu ngữ cảnh không hữu ích, vui lòng cung cấp các câu hỏi gốc. Và chỉ tạo với đoạn tài liệu đó tối đa 5 câu hỏi liên quan tới tài liệu cung cấp nhất. Nếu trong đoạn tài liệu có các tên file thì phải kèm nó vào câu hỏi.
422
- CÁC CÂU HỎI:
423
- """
424
- )
425
-
426
- REFINE_PROMPT_QUESTIONS = PromptTemplate(
427
- input_variables=["existing_answer", "text"],
428
- template=refine_template_vn,
429
- )
430
- ques_gen_chain = load_summarize_chain(llm=llm_ques_gen_pipeline,
431
- chain_type="refine",
432
- verbose=True,
433
- question_prompt=PROMPT_QUESTIONS_VN,
434
- refine_prompt=REFINE_PROMPT_QUESTIONS)
435
- ques = ques_gen_chain.run(document_ques_gen)
436
- ques_list = ques.split("\n")
437
- filtered_ques_list = ["{}: {}".format(name_file, re.sub(r'^\d+\.\s*', '', element)) for element in ques_list if
438
- element.endswith('?') or element.endswith('.')]
439
- return generate_random_questions(filtered_ques_list)
440
-
441
- def load_file(loader):
442
- return loader.load()
443
-
444
- def extract_data2(id):
445
- documents = []
446
- directory_path = f"./user_file/{id}"
447
- if not os.path.exists(directory_path) or not any(
448
- os.path.isfile(os.path.join(directory_path, f)) for f in os.listdir(directory_path)):
449
- return False
450
- tasks = []
451
- with ThreadPoolExecutor() as executor:
452
- for file in os.listdir(directory_path):
453
- if file.endswith(".pdf"):
454
- pdf_path = os.path.join(directory_path, file)
455
- loader = UnstructuredPDFLoader(pdf_path)
456
- tasks.append(executor.submit(load_file, loader))
457
- elif file.endswith('.docx') or file.endswith('.doc'):
458
- doc_path = os.path.join(directory_path, file)
459
- loader = Docx2txtLoader(doc_path)
460
- tasks.append(executor.submit(load_file, loader))
461
- elif file.endswith('.txt'):
462
- txt_path = os.path.join(directory_path, file)
463
- loader = TextLoader(txt_path, encoding="utf8")
464
- tasks.append(executor.submit(load_file, loader))
465
- elif file.endswith('.pptx'):
466
- ppt_path = os.path.join(directory_path, file)
467
- loader = UnstructuredPowerPointLoader(ppt_path)
468
- tasks.append(executor.submit(load_file, loader))
469
- elif file.endswith('.csv'):
470
- csv_path = os.path.join(directory_path, file)
471
- loader = UnstructuredCSVLoader(csv_path)
472
- tasks.append(executor.submit(load_file, loader))
473
- elif file.endswith('.xlsx'):
474
- excel_path = os.path.join(directory_path, file)
475
- loader = UnstructuredExcelLoader(excel_path)
476
- tasks.append(executor.submit(load_file, loader))
477
- elif file.endswith('.json'):
478
- json_path = os.path.join(directory_path, file)
479
- loader = TextLoader(json_path)
480
- tasks.append(executor.submit(load_file, loader))
481
- elif file.endswith('.md'):
482
- md_path = os.path.join(directory_path, file)
483
- loader = UnstructuredMarkdownLoader(md_path)
484
- tasks.append(executor.submit(load_file, loader))
485
- for future in as_completed(tasks):
486
- result = future.result()
487
- documents.extend(result)
488
- text_splitter = CharacterTextSplitter(chunk_size=4500, chunk_overlap=2500
489
- )
490
- texts = text_splitter.split_documents(documents)
491
- Chroma.from_documents(documents=texts,
492
- embedding=embeddings,
493
- persist_directory=f"./vector_database/{id}")
494
- return texts
495
-
496
- def generate_question(id):
497
- directory_path = f"./user_file/{id}"
498
- if not os.path.exists(directory_path) or not any(
499
- os.path.isfile(os.path.join(directory_path, f)) for f in os.listdir(directory_path)):
500
- return False
501
- all_questions = []
502
- tasks = []
503
- with ThreadPoolExecutor() as executor:
504
- for file in os.listdir(directory_path):
505
- if file.endswith(".pdf"):
506
- pdf_path = os.path.join(directory_path, file)
507
- loader = UnstructuredPDFLoader(pdf_path).load()
508
- tasks.append(executor.submit(generate_question_main, loader, file))
509
- elif file.endswith('.docx') or file.endswith('.doc'):
510
- doc_path = os.path.join(directory_path, file)
511
- loader = Docx2txtLoader(doc_path).load()
512
- tasks.append(executor.submit(generate_question_main, loader, file))
513
- elif file.endswith('.txt'):
514
- txt_path = os.path.join(directory_path, file)
515
- loader = TextLoader(txt_path, encoding="utf8").load()
516
- tasks.append(executor.submit(generate_question_main, loader, file))
517
- elif file.endswith('.pptx'):
518
- ppt_path = os.path.join(directory_path, file)
519
- loader = UnstructuredPowerPointLoader(ppt_path).load()
520
- tasks.append(executor.submit(generate_question_main, loader, file))
521
- elif file.endswith('.json'):
522
- json_path = os.path.join(directory_path, file)
523
- loader = TextLoader(json_path, encoding="utf8").load()
524
- tasks.append(executor.submit(generate_question_main, loader, file))
525
- elif file.endswith('.md'):
526
- md_path = os.path.join(directory_path, file)
527
- loader = UnstructuredMarkdownLoader(md_path).load()
528
- tasks.append(executor.submit(generate_question_main, loader, file))
529
- for future in as_completed(tasks):
530
- result = future.result()
531
- all_questions.extend(result)
532
- return all_questions
533
-
534
- class Search(BaseModel):
535
- queries: List[str] = Field(
536
- ...,
537
- description="Truy vấn riêng biệt để tìm kiếm, giữ nguyên ý chính câu hỏi riêng biệt",
538
- )
539
-
540
- def query_analyzer(query):
541
- output_parser = PydanticToolsParser(tools=[Search])
542
- system = """Bạn có khả năng đưa ra các truy vấn tìm kiếm chính xác để lấy thông tin giúp trả lời các yêu cầu của người dùng. Các truy vấn của bạn phải chính xác, không được bỏ ngắn rút gọn.
543
- Nếu bạn cần tra cứu hai hoặc nhiều thông tin riêng biệt, bạn có thể làm điều đó!. Trả lời câu hỏi bằng tiếng Việt(Vietnamese), không được dùng ngôn ngữ khác"""
544
- prompt = ChatPromptTemplate.from_messages(
545
- [
546
- ("system", system),
547
- ("human", "{question}"),
548
- ]
549
- )
550
- llm = ChatOpenAI(model="gpt-3.5-turbo-0125", temperature=0.0)
551
- structured_llm = llm.with_structured_output(Search)
552
- query_analyzer = {"question": RunnablePassthrough()} | prompt | structured_llm
553
- text = query_analyzer.invoke(query)
554
- return text
555
-
556
- def handle_query(question, text_all, compression_retriever, id, thread_id):
557
- COHERE_API_KEY_3 = os.environ["COHERE_API_KEY_3"]
558
- os.environ["COHERE_API_KEY"] = COHERE_API_KEY_3
559
- query = question
560
- x = query
561
- keyword, key_words_old = find_matching_files_in_docs_12_id(query, id)
562
- # if keyword == set() or key_words_old == list():
563
- # return "Not found file"
564
- file_list = keyword
565
-
566
- if file_list:
567
- list_keywords2 = list(key_words_old)
568
- contents1 = extract_content_between_keywords(query, list_keywords2)
569
- merged_result = merge_files(keyword, list_keywords2)
570
- original_dict = contents1
571
- replacement_dict = merged_result
572
- new_dict = replace_keys_with_values(original_dict, replacement_dict)
573
- files_to_remove = [filename for filename in new_dict.keys() if
574
- filename.endswith('.xlsx') or filename.endswith('.csv')]
575
- removed_files = {}
576
- for filename in files_to_remove:
577
- removed_files[filename] = new_dict[filename]
578
- for filename in files_to_remove:
579
- new_dict.pop(filename)
580
- test_csv = ""
581
- text_csv, query_csv, source = aws1_csv_id(removed_files, id)
582
- prompt_csv = ""
583
- answer_csv = ""
584
- if test_csv:
585
- prompt_csv = f"Dựa vào nội dung sau: {text_csv}. Hãy trả lời câu hỏi sau đây: {query_csv}.Bằng tiếng Việt"
586
- answer_csv = question_answer(prompt_csv)
587
- answer_document, data_relevant, source = aws1_all_id(new_dict, text_all, id, thread_id)
588
- answer_all1 = answer_document + answer_csv
589
- return answer_all1, data_relevant, source
590
- else:
591
- compressed_docs = compression_retriever.get_relevant_documents(f"{query}")
592
- relevance_score_float = float(compressed_docs[0].metadata['relevance_score'])
593
- print(relevance_score_float)
594
- if relevance_score_float <= 0.12:
595
- documents1 = []
596
- for file in os.listdir(f"./user_file/{id}"):
597
- if file.endswith('.csv'):
598
- csv_path = f"./user_file/{id}/" + file
599
- loader = UnstructuredCSVLoader(csv_path)
600
- documents1.extend(loader.load())
601
- elif file.endswith('.xlsx'):
602
- excel_path = f"./user_file/{id}/" + file
603
- loader = UnstructuredExcelLoader(excel_path)
604
- documents1.extend(loader.load())
605
- text_splitter_csv = CharacterTextSplitter.from_tiktoken_encoder(chunk_size=2200, chunk_overlap=1500)
606
- texts_csv = text_splitter_csv.split_documents(documents1)
607
- vectordb_csv = Chroma.from_documents(documents=texts_csv,
608
- embedding=embeddings, persist_directory=f'./vector_database/csv/{thread_id}')
609
- k = len(texts_csv)
610
- retriever_csv = vectordb_csv.as_retriever(search_kwargs={"k": k})
611
- llm = Cohere(temperature=0)
612
- compressor_csv = CohereRerank(top_n=3, model="rerank-english-v2.0")
613
- compression_retriever_csv = ContextualCompressionRetriever(
614
- base_compressor=compressor_csv, base_retriever=retriever_csv
615
- )
616
- compressed_docs_csv = compression_retriever_csv.get_relevant_documents(f"{query}")
617
- file_path = compressed_docs_csv[0].metadata['source']
618
- print(file_path)
619
- if file_path.endswith('.xlsx'):
620
- new = file_path.replace(".xlsx", ".csv")
621
- convert_xlsx_to_csv(file_path, new)
622
- loader1 = CSVLoader(new)
623
- else:
624
- loader1 = CSVLoader(file_path)
625
- docs1 = loader1.load()
626
- text = " "
627
- for z in docs1:
628
- text += z.page_content + "\n"
629
- prompt_csv = f"Dựa vào nội dung sau: {text}. Hãy trả lời câu hỏi sau đây: {query}. Bằng tiếng Việt"
630
- answer_csv = question_answer(prompt_csv)
631
- return answer_csv
632
- else:
633
- file_path = compressed_docs[0].metadata['source']
634
- file_path = file_path.replace('\\', '/')
635
- print(file_path)
636
- if file_path.endswith(".pdf"):
637
- loader = UnstructuredPDFLoader(file_path)
638
- elif file_path.endswith('.docx') or file_path.endswith('doc'):
639
- loader = Docx2txtLoader(file_path)
640
- elif file_path.endswith('.txt'):
641
- loader = TextLoader(file_path, encoding="utf8")
642
- elif file_path.endswith('.pptx'):
643
- loader = UnstructuredPowerPointLoader(file_path)
644
- elif file_path.endswith('.xml'):
645
- loader = UnstructuredXMLLoader(file_path)
646
- elif file_path.endswith('.html'):
647
- loader = UnstructuredHTMLLoader(file_path)
648
- elif file_path.endswith('.json'):
649
- loader = TextLoader(file_path)
650
- elif file_path.endswith('.md'):
651
- loader = UnstructuredMarkdownLoader(file_path)
652
- elif file_path.endswith('.xlsx'):
653
- file_path_new = file_path.replace(".xlsx", ".csv")
654
- convert_xlsx_to_csv(file_path, file_path_new)
655
- loader = CSVLoader(file_path_new)
656
- elif file_path.endswith('.csv'):
657
- loader = CSVLoader(file_path)
658
- text_splitter = CharacterTextSplitter(chunk_size=3200, chunk_overlap=1500)
659
- texts = text_splitter.split_documents(loader.load())
660
- k_1 = len(texts)
661
- file_name = os.path.basename(file_path)
662
- if check_persist_directory(id, file_name):
663
- vectordb_file = Chroma(persist_directory=f"./vector_database/{id}/{file_name}",
664
- embedding_function=embeddings)
665
- else:
666
- vectordb_file = Chroma.from_documents(texts,
667
- embedding=embeddings,
668
- persist_directory=f"./vector_database/{id}/{file_name}")
669
- retriever_file = vectordb_file.as_retriever(search_kwargs={f"k": k_1})
670
- bm25_retriever = BM25Retriever.from_documents(texts)
671
- bm25_retriever.k = k_1
672
- ensemble_retriever = EnsembleRetriever(retrievers=[bm25_retriever, retriever_file],
673
- weights=[0.6, 0.4])
674
- docs = ensemble_retriever.get_relevant_documents(f"{query}")
675
-
676
- path = f"./vector_database/FAISS/{id}/{file_name}"
677
- if check_path_exists(path):
678
- docsearch = FAISS.load_local(path, embeddings, allow_dangerous_deserialization=True)
679
- else:
680
- docsearch = FAISS.from_documents(docs, embeddings)
681
- docsearch.save_local(f"./vector_database/FAISS/{id}/{file_name}")
682
- docsearch = FAISS.load_local(path, embeddings, allow_dangerous_deserialization=True)
683
- k_2 = len(docs)
684
- retrieve3 = docsearch.as_retriever(search_kwargs={f"k": k_2})
685
- compressor_file = CohereRerank(top_n=3, model="rerank-english-v2.0")
686
- compression_retriever_file = ContextualCompressionRetriever(
687
- base_compressor=compressor_file, base_retriever=retrieve3
688
- )
689
- compressed_docs_file = compression_retriever_file.get_relevant_documents(f"{x}")
690
- query = question
691
- text = ''.join(map(lambda x: x.page_content, compressed_docs_file))
692
- prompt = f"Dựa vào nội dung sau:{text}. Hãy trả lời câu hỏi sau đây: {query}. Mà không thay đổi, chỉnh sửa nội dung mà mình đã cung cấp"
693
- answer = question_answer(prompt)
694
- list_relevant = compressed_docs_file[0].page_content
695
- source = file_name
696
- return answer, list_relevant, source
697
- import concurrent.futures
698
- def handle_query_upgrade_keyword_old(query_all, text_all, id,chat_history):
699
- COHERE_API_KEY_2 = os.environ["COHERE_API_KEY_2"]
700
- os.environ["COHERE_API_KEY"] = COHERE_API_KEY_2
701
- test = query_analyzer(query_all)
702
- test_string = str(test)
703
- matches = re.findall(r"'([^']*)'", test_string)
704
- vectordb = Chroma(persist_directory=f"./vector_database/{id}", embedding_function=embeddings)
705
- k = len(text_all)
706
- retriever = vectordb.as_retriever(search_kwargs={"k": k})
707
- compressor = CohereRerank(top_n=5, model="rerank-english-v2.0")
708
- compression_retriever = ContextualCompressionRetriever(base_compressor=compressor, base_retriever= retriever)
709
- with concurrent.futures.ThreadPoolExecutor() as executor:
710
- futures = {executor.submit(handle_query, query, text_all, compression_retriever, id, i): query for i, query in
711
- enumerate(matches)}
712
- results = []
713
- data_relevant = []
714
- sources = []
715
- for future in as_completed(futures):
716
- try:
717
- result, list_data, list_source = future.result()
718
- results.append(result)
719
- data_relevant.append(list_data)
720
- sources.append(list_source)
721
- except Exception as e:
722
- print(f'An error occurred: {e}')
723
- answer_all = ''.join(results)
724
- prompt1 = f"Dựa vào nội dung sau: {answer_all}. Hãy trả lời câu hỏi sau đây: {query_all}. Lưu ý rằng ngữ cảnh của cuộc trò chuyện này trước đây là: {chat_history}. Vui lòng trả lời câu hỏi mà không thay đổi, chỉnh sửa nội dung mà mình đã cung cấp."
725
- answer1 = question_answer(prompt1)
726
  return answer1, data_relevant, sources
 
1
+ from langchain.text_splitter import CharacterTextSplitter
2
+ import json
3
+ import os
4
+ import random
5
+ import re
6
+ from concurrent.futures import ThreadPoolExecutor, as_completed
7
+ import google.generativeai as genai
8
+ import nltk
9
+ import pandas as pd
10
+ from groq import Groq
11
+ from langchain.chains.summarize import load_summarize_chain
12
+ from langchain.docstore.document import Document
13
+ from langchain.prompts import PromptTemplate
14
+ from langchain.retrievers import BM25Retriever, EnsembleRetriever
15
+ from langchain.retrievers.contextual_compression import ContextualCompressionRetriever
16
+ from langchain.text_splitter import CharacterTextSplitter
17
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
18
+ from langchain_cohere import CohereRerank
19
+ from langchain_community.document_loaders import Docx2txtLoader
20
+ from langchain_community.document_loaders import TextLoader
21
+ from langchain_community.document_loaders import UnstructuredCSVLoader
22
+ from langchain_community.document_loaders import UnstructuredExcelLoader
23
+ from langchain_community.document_loaders import UnstructuredHTMLLoader
24
+ from langchain_community.document_loaders import UnstructuredMarkdownLoader
25
+ from langchain_community.document_loaders import UnstructuredPDFLoader
26
+ from langchain_community.document_loaders import UnstructuredPowerPointLoader
27
+ from langchain_community.document_loaders import UnstructuredXMLLoader
28
+ from langchain_community.document_loaders.csv_loader import CSVLoader
29
+ from langchain_community.llms import Cohere
30
+ from langchain_community.vectorstores import Chroma
31
+ from langchain_core.output_parsers.openai_tools import PydanticToolsParser
32
+ from langchain_core.prompts import ChatPromptTemplate
33
+ from langchain_core.pydantic_v1 import BaseModel, Field
34
+ from langchain_core.runnables import RunnablePassthrough
35
+ from langchain_openai import ChatOpenAI
36
+ from typing import List
37
+ from nltk.corpus import stopwords
38
+ from nltk.tokenize import word_tokenize
39
+ nltk.download('punkt')
40
+
41
+ def process_json_file(file_path):
42
+ json_data = []
43
+ with open(file_path, 'r') as file:
44
+ for line in file:
45
+ try:
46
+ data = json.loads(line)
47
+ json_data.append(data)
48
+ except json.JSONDecodeError:
49
+ try:
50
+ data = json.loads(line[:-1])
51
+ json_data.append(data)
52
+ except json.JSONDecodeError as e:
53
+ print(f"Error decoding JSON: {e}")
54
+ return json_data
55
+
56
+ from dotenv import load_dotenv
57
+ import os
58
+ load_dotenv()
59
+ GROQ_API_KEY = os.getenv("GROQ_API_KEY")
60
+ COHERE_API_KEY = os.getenv("COHERE_API_KEY")
61
+ OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
62
+ GOOGLE_API_KEY1= os.getenv("GOOGLE_API_KEY_1")
63
+ GOOGLE_API_KEY= os.getenv("GOOGLE_API_KEY")
64
+ os.environ["COHERE_API_KEY"] = COHERE_API_KEY
65
+ os.environ["OPENAI_API_KEY"] = OPENAI_API_KEY
66
+ client = Groq(
67
+ api_key= GROQ_API_KEY,
68
+ )
69
+ genai.configure(api_key=GOOGLE_API_KEY1)
70
+ os.environ["GOOGLE_API_KEY"] = GOOGLE_API_KEY
71
+ from langchain_google_genai import GoogleGenerativeAIEmbeddings, ChatGoogleGenerativeAI
72
+ embeddings = GoogleGenerativeAIEmbeddings(model="models/embedding-001", task_type="retrieval_document")
73
+ llm = ChatGoogleGenerativeAI(model='gemini-pro',
74
+ max_output_tokens=2048,
75
+ temperature=0.2,
76
+ convert_system_message_to_human=True)
77
+ def extract_multi_metadata_content(texts, tests):
78
+ extracted_content = []
79
+ precomputed_metadata = [x.metadata['source'].lower() for x in texts]
80
+ for idx, test in enumerate(tests):
81
+ temp_content = []
82
+ test_terms = set(test.lower().split())
83
+ for metadata_lower, x in zip(precomputed_metadata, texts):
84
+ if any(term in metadata_lower for term in test_terms):
85
+ temp_content.append(x.page_content)
86
+ if idx == 0:
87
+ extracted_content.append(f"Dữ liệu của {test}:\n{''.join(temp_content)}")
88
+ else:
89
+ extracted_content.append(''.join(temp_content))
90
+ return '\n'.join(extracted_content)
91
+ import unicodedata
92
+ def text_preprocessing(text):
93
+ text = text.lower()
94
+ emoji_pattern = re.compile("["
95
+ u"\U0001F600-\U0001F64F" # emoticons
96
+ u"\U0001F300-\U0001F5FF" # symbols & pictographs
97
+ u"\U0001F680-\U0001F6FF" # transport & map symbols
98
+ u"\U0001F1E0-\U0001F1FF" # flags (iOS)
99
+ u"\U00002500-\U00002BEF" # chinese char
100
+ u"\U00002702-\U000027B0"
101
+ u"\U000024C2-\U0001F251"
102
+ u"\U0001f926-\U0001f937"
103
+ u"\U00010000-\U0010ffff"
104
+ u"\u2640-\u2642"
105
+ u"\u2600-\u2B55"
106
+ u"\u200d"
107
+ u"\u23cf"
108
+ u"\u23e9"
109
+ u"\u231a"
110
+ u"\ufe0f" # dingbats
111
+ u"\u3030"
112
+ "]+", flags=re.UNICODE)
113
+ text = emoji_pattern.sub(r'', text)
114
+ text = unicodedata.normalize('NFC', text)
115
+ words = text.split()
116
+ text = ' '.join(words)
117
+ return text
118
+ def find_matching_files_in_docs_12_id(text, id):
119
+ folder_path = f"./user_file/{id}"
120
+ search_terms = []
121
+ search_terms_old = []
122
+ matching_index = []
123
+ search_origin = re.findall(r'\b\w+\.\w+\b|\b\w+\b', text)
124
+ search_terms_origin = []
125
+ for word in search_origin:
126
+ if '.' in word:
127
+ search_terms_origin.append(word)
128
+ else:
129
+ search_terms_origin.extend(re.findall(r'\b\w+\b', word))
130
+
131
+ file_names_with_extension = re.findall(r'\b\w+\.\w+\b|\b\w+\b', text.lower())
132
+ file_names_with_extension_old = re.findall(r'\b(\w+\.\w+)\b', text)
133
+ for file_name in search_terms_origin:
134
+ if "." in file_name:
135
+ search_terms_old.append(file_name)
136
+ for file_name in file_names_with_extension_old:
137
+ if "." in file_name:
138
+ search_terms_old.append(file_name)
139
+ for file_name in file_names_with_extension:
140
+ search_terms.append(file_name)
141
+ clean_text_old = text
142
+ clean_text = text.lower()
143
+ for term in search_terms_old:
144
+ clean_text_old = clean_text_old.replace(term, '')
145
+ for term in search_terms:
146
+ clean_text = clean_text.replace(term, '')
147
+ words_old = re.findall(r'\b\w+\b', clean_text_old)
148
+ search_terms_old.extend(words_old)
149
+ matching_files = set()
150
+ for root, dirs, files in os.walk(folder_path):
151
+ for file in files:
152
+ for term in search_terms:
153
+ if term.lower() in file.lower():
154
+ term_position = search_terms.index(term)
155
+ matching_files.add(file)
156
+ matching_index.append(term_position)
157
+ break
158
+ matching_files_old1 = []
159
+ matching_index.sort()
160
+ for x in matching_index:
161
+ matching_files_old1.append(search_terms_origin[x])
162
+ return matching_files, matching_files_old1
163
+
164
+ def convert_xlsx_to_csv(xlsx_file_path, csv_file_path):
165
+ df = pd.read_excel(xlsx_file_path)
166
+ df.to_csv(csv_file_path, index=False)
167
+
168
+ def save_list_CSV_id(file_list, id):
169
+ text = ""
170
+ for x in file_list:
171
+ if x.endswith('.xlsx'):
172
+ old = f"./user_file/{id}/{x}"
173
+ new = old.replace(".xlsx", ".csv")
174
+ convert_xlsx_to_csv(old, new)
175
+ x = x.replace(".xlsx", ".csv")
176
+ loader1 = CSVLoader(f"./user_file/{id}/{x}")
177
+ docs1 = loader1.load()
178
+ text += f"Dữ liệu file {x}:\n"
179
+ for z in docs1:
180
+ text += z.page_content + "\n"
181
+ return text
182
+
183
+ def merge_files(file_set, file_list):
184
+ """Hàm này ghép lại các tên file dựa trên điều kiện đã cho."""
185
+ merged_files = {}
186
+ for file_name in file_list:
187
+ name = file_name.split('.')[0]
188
+ for f in file_set:
189
+ if name in f:
190
+ merged_files[name] = f
191
+ break
192
+ return merged_files
193
+
194
+ def replace_keys_with_values(original_dict, replacement_dict):
195
+ new_dict = {}
196
+ for key, value in original_dict.items():
197
+ if key in replacement_dict:
198
+ new_key = replacement_dict[key]
199
+ new_dict[new_key] = value
200
+ else:
201
+ new_dict[key] = value
202
+ return new_dict
203
+
204
+ def aws1_csv_id(new_dict_csv, id):
205
+ text = ""
206
+ query_all = ""
207
+ keyword = []
208
+ for key, value in new_dict_csv.items():
209
+ print(key, value)
210
+ query_all += value
211
+ keyword.append(key)
212
+ test = save_list_CSV_id(keyword, id)
213
+ text += test
214
+ sources = ",".join(keyword)
215
+ return text, query_all, sources
216
+
217
+ def chat_llama3(prompt_query):
218
+ try:
219
+ chat_completion = client.chat.completions.create(
220
+ messages=[
221
+ {
222
+ "role": "system",
223
+ "content": "Bạn là một trợ lý trung thưc, trả lời dựa trên nội dung tài liệu được cung cấp. Chỉ trả lời liên quan đến câu hỏi một cách đầy đủ chính xác, không bỏ sót thông tin."
224
+ },
225
+ {
226
+
227
+ "role": "user",
228
+ "content": f"{prompt_query}",
229
+ }
230
+ ],
231
+ model="llama3-70b-8192",
232
+ temperature=0.0,
233
+ max_tokens=9000,
234
+ stop=None,
235
+ stream=False,
236
+ )
237
+ return chat_completion.choices[0].message.content
238
+ except Exception as error:
239
+ return False
240
+
241
+ def chat_gemini(prompt):
242
+ generation_config = {
243
+ "temperature": 0.0,
244
+ "top_p": 0.0,
245
+ "top_k": 0,
246
+ "max_output_tokens": 8192,
247
+ }
248
+ safety_settings = [
249
+ {
250
+ "category": "HARM_CATEGORY_HARASSMENT",
251
+ "threshold": "BLOCK_MEDIUM_AND_ABOVE"
252
+ },
253
+ {
254
+ "category": "HARM_CATEGORY_HATE_SPEECH",
255
+ "threshold": "BLOCK_MEDIUM_AND_ABOVE"
256
+ },
257
+ {
258
+ "category": "HARM_CATEGORY_SEXUALLY_EXPLICIT",
259
+ "threshold": "BLOCK_MEDIUM_AND_ABOVE"
260
+ },
261
+ {
262
+ "category": "HARM_CATEGORY_DANGEROUS_CONTENT",
263
+ "threshold": "BLOCK_MEDIUM_AND_ABOVE"
264
+ },
265
+ ]
266
+ model = genai.GenerativeModel(model_name="gemini-1.5-pro-latest",
267
+ generation_config=generation_config,
268
+ safety_settings=safety_settings)
269
+ convo = model.start_chat(history=[])
270
+ convo.send_message(prompt)
271
+ return convo.last.text
272
+
273
+ def question_answer(question):
274
+ completion = chat_llama3(question)
275
+ if completion:
276
+ return completion
277
+ else:
278
+ answer = chat_gemini(question)
279
+ return answer
280
+
281
+ def check_persist_directory(id, file_name):
282
+ directory_path = f"./vector_database/{id}/{file_name}"
283
+ return os.path.exists(directory_path)
284
+
285
+ from langchain_community.vectorstores import FAISS
286
+
287
+ def check_path_exists(path):
288
+ return os.path.exists(path)
289
+ def aws1_all_id(new_dict, text_alls, id, thread_id):
290
+ answer = ""
291
+ COHERE_API_KEY1 = os.getenv("COHERE_API_KEY_1")
292
+ os.environ["COHERE_API_KEY"] = COHERE_API_KEY1
293
+ answer_relevant = ""
294
+ directory = ""
295
+ for key, value in new_dict.items():
296
+ query = value
297
+ query = text_preprocessing(query)
298
+ keyword, keyword2 = find_matching_files_in_docs_12_id(query, id)
299
+ data = extract_multi_metadata_content(text_alls, keyword)
300
+ if keyword:
301
+ file_name = next(iter(keyword))
302
+ text_splitter = CharacterTextSplitter(chunk_size=3200, chunk_overlap=1500)
303
+ texts_data = text_splitter.split_text(data)
304
+
305
+ if check_persist_directory(id, file_name):
306
+ vectordb_query = Chroma(persist_directory=f"./vector_database/{id}/{file_name}", embedding_function=embeddings)
307
+ else:
308
+ vectordb_query = Chroma.from_texts(texts_data,
309
+ embedding=embeddings,
310
+ persist_directory=f"./vector_database/{id}/{file_name}")
311
+
312
+ k_1 = len(texts_data)
313
+ retriever = vectordb_query.as_retriever(search_kwargs={f"k": k_1})
314
+ bm25_retriever = BM25Retriever.from_texts(texts_data)
315
+ bm25_retriever.k = k_1
316
+ ensemble_retriever = EnsembleRetriever(retrievers=[bm25_retriever, retriever],
317
+ weights=[0.6, 0.4])
318
+ docs = ensemble_retriever.get_relevant_documents(f"{query}")
319
+
320
+ path = f"./vector_database/FAISS/{id}/{file_name}"
321
+ if check_path_exists(path):
322
+ docsearch = FAISS.load_local(path, embeddings, allow_dangerous_deserialization=True)
323
+ else:
324
+ docsearch = FAISS.from_documents(docs, embeddings)
325
+ docsearch.save_local(f"./vector_database/FAISS/{id}/{file_name}")
326
+ docsearch = FAISS.load_local(path, embeddings, allow_dangerous_deserialization=True)
327
+
328
+ k_2 = len(docs)
329
+ compressor = CohereRerank(top_n=3)
330
+ retrieve3 = docsearch.as_retriever(search_kwargs={f"k": k_2})
331
+ compression_retriever = ContextualCompressionRetriever(
332
+ base_compressor=compressor, base_retriever=retrieve3
333
+ )
334
+ compressed_docs = compression_retriever.get_relevant_documents(f"{query}")
335
+
336
+ if compressed_docs:
337
+ data = compressed_docs[0].page_content
338
+ text = ''.join(map(lambda x: x.page_content, compressed_docs))
339
+ prompt_document = f"Dựa vào nội dung sau:{text}. Hãy trả lời câu hỏi sau đây: {query}. Mà không thay đổi nội dung mà mình đã cung cấp. Cuối cùng nếu câu hỏi sử dụng tiếng Việt thì phải trả lời bằng Vietnamese. Nếu câu hỏi sử dụng tiếng Anh phải trả lời bằng English"
340
+ answer_for = question_answer(prompt_document)
341
+ answer += answer_for + "\n"
342
+ answer_relevant = data
343
+ directory = file_name
344
+
345
+ return answer, answer_relevant, directory
346
+
347
+
348
+ def extract_content_between_keywords(query, keywords):
349
+ contents = {}
350
+ num_keywords = len(keywords)
351
+ keyword_positions = []
352
+ for i in range(num_keywords):
353
+ keyword = keywords[i]
354
+ keyword_position = query.find(keyword)
355
+ keyword_positions.append(keyword_position)
356
+ if keyword_position == -1:
357
+ continue
358
+ next_keyword_position = len(query)
359
+ for j in range(i + 1, num_keywords):
360
+ next_keyword = keywords[j]
361
+ next_keyword_position = query.find(next_keyword)
362
+ if next_keyword_position != -1:
363
+ break
364
+ if i == 0:
365
+ content_before = query[:keyword_position].strip()
366
+ else:
367
+ content_before = query[keyword_positions[i - 1] + len(keywords[i - 1]):keyword_position].strip()
368
+ if i == num_keywords - 1:
369
+ content_after = query[keyword_position + len(keyword):].strip()
370
+ else:
371
+ content_after = query[keyword_position + len(keyword):next_keyword_position].strip()
372
+ content = f"{content_before} {keyword} {content_after}"
373
+ contents[keyword] = content
374
+ return contents
375
+
376
+ def generate_random_questions(filtered_ques_list):
377
+ if len(filtered_ques_list) >= 2:
378
+ random_questions = random.sample(filtered_ques_list, 2)
379
+ else:
380
+ random_questions = filtered_ques_list
381
+ return random_questions
382
+
383
+ def generate_question_main(loader, name_file):
384
+ text_splitter = RecursiveCharacterTextSplitter(chunk_size=4500, chunk_overlap=2500)
385
+ texts = text_splitter.split_documents(loader)
386
+ question_gen = f"nội dung {name_file} : \n"
387
+ question_gen += texts[0].page_content
388
+ splitter_ques_gen = RecursiveCharacterTextSplitter(
389
+ chunk_size=4500,
390
+ chunk_overlap=2200
391
+ )
392
+ chunks_ques_gen = splitter_ques_gen.split_text(question_gen)
393
+ document_ques_gen = [Document(page_content=t) for t in chunks_ques_gen]
394
+ llm_ques_gen_pipeline = llm
395
+ prompt_template_vn = """
396
+ Bạn là một chuyên gia tạo câu hỏi dựa trên tài liệu và tài liệu hướng dẫn.
397
+ Bạn làm điều này bằng cách đặt các câu hỏi về đoạn văn bản dưới đây:
398
+
399
+ ------------
400
+ {text}
401
+ ------------
402
+
403
+ Hãy tạo ra các câu hỏi từ đoạn văn bản này.Nếu đoạn văn là tiếng Việt hãy tạo câu hỏi tiếng Việt. Nếu đoạn văn là tiếng Anh hãy tạo câu hỏi tiếng Anh.
404
+ Hãy chắc chắn không bỏ sót bất kỳ thông tin quan trọng nào. Và chỉ tạo với đoạn tài liệu đó tối đa 5 câu hỏi liên quan tới tài liệu cung cấp nhất.Nếu trong đoạn tài liệu có các tên liên quan đến file như demo1.pdf( nhiều file khác) thì phải kèm nó vào nội dung câu hỏi bạn tạo ra.
405
+
406
+ CÁC CÂU HỎI:
407
+ """
408
+
409
+ PROMPT_QUESTIONS_VN = PromptTemplate(template=prompt_template_vn, input_variables=["text"])
410
+ refine_template_vn = ("""
411
+ Bạn là một chuyên gia tạo câu hỏi thực hành dựa trên tài liệu và tài liệu hướng dẫn.
412
+ Mục tiêu của bạn là giúp người học chuẩn bị cho một kỳ thi.
413
+ Chúng tôi đã nhận được một số câu hỏi thực hành ở mức độ nào đó: {existing_answer}.
414
+ Chúng tôi có thể tinh chỉnh các câu hỏi hiện có hoặc thêm câu hỏi mới
415
+ (chỉ khi cần thiết) với một số ngữ cảnh bổ sung dưới đây.
416
+ ------------
417
+ {text}
418
+ ------------
419
+
420
+ Dựa trên ngữ cảnh mới, hãy tinh chỉnh các câu hỏi bằng tiếng Việt nếu đoạn văn đó cung cấp tiếng Việt. Nếu không hãy tinh chỉnh câu hỏi bằng tiếng Anh nếu đoạn đó cung cấp tiếng Anh.
421
+ Nếu ngữ cảnh không hữu ích, vui lòng cung cấp các câu hỏi gốc. Và chỉ tạo với đoạn tài liệu đó tối đa 5 câu hỏi liên quan tới tài liệu cung cấp nhất. Nếu trong đoạn tài liệu có các tên file thì phải kèm nó vào câu hỏi.
422
+ CÁC CÂU HỎI:
423
+ """
424
+ )
425
+
426
+ REFINE_PROMPT_QUESTIONS = PromptTemplate(
427
+ input_variables=["existing_answer", "text"],
428
+ template=refine_template_vn,
429
+ )
430
+ ques_gen_chain = load_summarize_chain(llm=llm_ques_gen_pipeline,
431
+ chain_type="refine",
432
+ verbose=True,
433
+ question_prompt=PROMPT_QUESTIONS_VN,
434
+ refine_prompt=REFINE_PROMPT_QUESTIONS)
435
+ ques = ques_gen_chain.run(document_ques_gen)
436
+ ques_list = ques.split("\n")
437
+ filtered_ques_list = ["{}: {}".format(name_file, re.sub(r'^\d+\.\s*', '', element)) for element in ques_list if
438
+ element.endswith('?') or element.endswith('.')]
439
+ return generate_random_questions(filtered_ques_list)
440
+
441
+ def load_file(loader):
442
+ return loader.load()
443
+
444
+ def extract_data2(id):
445
+ documents = []
446
+ directory_path = f" ./code/user_file/{id}"
447
+ if not os.path.exists(directory_path) or not any(
448
+ os.path.isfile(os.path.join(directory_path, f)) for f in os.listdir(directory_path)):
449
+ return False
450
+ tasks = []
451
+ with ThreadPoolExecutor() as executor:
452
+ for file in os.listdir(directory_path):
453
+ if file.endswith(".pdf"):
454
+ pdf_path = os.path.join(directory_path, file)
455
+ loader = UnstructuredPDFLoader(pdf_path)
456
+ tasks.append(executor.submit(load_file, loader))
457
+ elif file.endswith('.docx') or file.endswith('.doc'):
458
+ doc_path = os.path.join(directory_path, file)
459
+ loader = Docx2txtLoader(doc_path)
460
+ tasks.append(executor.submit(load_file, loader))
461
+ elif file.endswith('.txt'):
462
+ txt_path = os.path.join(directory_path, file)
463
+ loader = TextLoader(txt_path, encoding="utf8")
464
+ tasks.append(executor.submit(load_file, loader))
465
+ elif file.endswith('.pptx'):
466
+ ppt_path = os.path.join(directory_path, file)
467
+ loader = UnstructuredPowerPointLoader(ppt_path)
468
+ tasks.append(executor.submit(load_file, loader))
469
+ elif file.endswith('.csv'):
470
+ csv_path = os.path.join(directory_path, file)
471
+ loader = UnstructuredCSVLoader(csv_path)
472
+ tasks.append(executor.submit(load_file, loader))
473
+ elif file.endswith('.xlsx'):
474
+ excel_path = os.path.join(directory_path, file)
475
+ loader = UnstructuredExcelLoader(excel_path)
476
+ tasks.append(executor.submit(load_file, loader))
477
+ elif file.endswith('.json'):
478
+ json_path = os.path.join(directory_path, file)
479
+ loader = TextLoader(json_path)
480
+ tasks.append(executor.submit(load_file, loader))
481
+ elif file.endswith('.md'):
482
+ md_path = os.path.join(directory_path, file)
483
+ loader = UnstructuredMarkdownLoader(md_path)
484
+ tasks.append(executor.submit(load_file, loader))
485
+ for future in as_completed(tasks):
486
+ result = future.result()
487
+ documents.extend(result)
488
+ text_splitter = CharacterTextSplitter(chunk_size=4500, chunk_overlap=2500
489
+ )
490
+ texts = text_splitter.split_documents(documents)
491
+ Chroma.from_documents(documents=texts,
492
+ embedding=embeddings,
493
+ persist_directory=f"./vector_database/{id}")
494
+ return texts
495
+
496
+ def generate_question(id):
497
+ directory_path = f"./code/user_file/{id}"
498
+ if not os.path.exists(directory_path) or not any(
499
+ os.path.isfile(os.path.join(directory_path, f)) for f in os.listdir(directory_path)):
500
+ return False
501
+ all_questions = []
502
+ tasks = []
503
+ with ThreadPoolExecutor() as executor:
504
+ for file in os.listdir(directory_path):
505
+ if file.endswith(".pdf"):
506
+ pdf_path = os.path.join(directory_path, file)
507
+ loader = UnstructuredPDFLoader(pdf_path).load()
508
+ tasks.append(executor.submit(generate_question_main, loader, file))
509
+ elif file.endswith('.docx') or file.endswith('.doc'):
510
+ doc_path = os.path.join(directory_path, file)
511
+ loader = Docx2txtLoader(doc_path).load()
512
+ tasks.append(executor.submit(generate_question_main, loader, file))
513
+ elif file.endswith('.txt'):
514
+ txt_path = os.path.join(directory_path, file)
515
+ loader = TextLoader(txt_path, encoding="utf8").load()
516
+ tasks.append(executor.submit(generate_question_main, loader, file))
517
+ elif file.endswith('.pptx'):
518
+ ppt_path = os.path.join(directory_path, file)
519
+ loader = UnstructuredPowerPointLoader(ppt_path).load()
520
+ tasks.append(executor.submit(generate_question_main, loader, file))
521
+ elif file.endswith('.json'):
522
+ json_path = os.path.join(directory_path, file)
523
+ loader = TextLoader(json_path, encoding="utf8").load()
524
+ tasks.append(executor.submit(generate_question_main, loader, file))
525
+ elif file.endswith('.md'):
526
+ md_path = os.path.join(directory_path, file)
527
+ loader = UnstructuredMarkdownLoader(md_path).load()
528
+ tasks.append(executor.submit(generate_question_main, loader, file))
529
+ for future in as_completed(tasks):
530
+ result = future.result()
531
+ all_questions.extend(result)
532
+ return all_questions
533
+
534
+ class Search(BaseModel):
535
+ queries: List[str] = Field(
536
+ ...,
537
+ description="Truy vấn riêng biệt để tìm kiếm, giữ nguyên ý chính câu hỏi riêng biệt",
538
+ )
539
+
540
+ def query_analyzer(query):
541
+ output_parser = PydanticToolsParser(tools=[Search])
542
+ system = """Bạn có khả năng đưa ra các truy vấn tìm kiếm chính xác để lấy thông tin giúp trả lời các yêu cầu của người dùng. Các truy vấn của bạn phải chính xác, không được bỏ ngắn rút gọn.
543
+ Nếu bạn cần tra cứu hai hoặc nhiều thông tin riêng biệt, bạn có thể làm điều đó!. Trả lời câu hỏi bằng tiếng Việt(Vietnamese), không được dùng ngôn ngữ khác"""
544
+ prompt = ChatPromptTemplate.from_messages(
545
+ [
546
+ ("system", system),
547
+ ("human", "{question}"),
548
+ ]
549
+ )
550
+ llm = ChatOpenAI(model="gpt-3.5-turbo-0125", temperature=0.0)
551
+ structured_llm = llm.with_structured_output(Search)
552
+ query_analyzer = {"question": RunnablePassthrough()} | prompt | structured_llm
553
+ text = query_analyzer.invoke(query)
554
+ return text
555
+
556
+ def handle_query(question, text_all, compression_retriever, id, thread_id):
557
+ COHERE_API_KEY_3 = os.environ["COHERE_API_KEY_3"]
558
+ os.environ["COHERE_API_KEY"] = COHERE_API_KEY_3
559
+ query = question
560
+ x = query
561
+ keyword, key_words_old = find_matching_files_in_docs_12_id(query, id)
562
+ # if keyword == set() or key_words_old == list():
563
+ # return "Not found file"
564
+ file_list = keyword
565
+
566
+ if file_list:
567
+ list_keywords2 = list(key_words_old)
568
+ contents1 = extract_content_between_keywords(query, list_keywords2)
569
+ merged_result = merge_files(keyword, list_keywords2)
570
+ original_dict = contents1
571
+ replacement_dict = merged_result
572
+ new_dict = replace_keys_with_values(original_dict, replacement_dict)
573
+ files_to_remove = [filename for filename in new_dict.keys() if
574
+ filename.endswith('.xlsx') or filename.endswith('.csv')]
575
+ removed_files = {}
576
+ for filename in files_to_remove:
577
+ removed_files[filename] = new_dict[filename]
578
+ for filename in files_to_remove:
579
+ new_dict.pop(filename)
580
+ test_csv = ""
581
+ text_csv, query_csv, source = aws1_csv_id(removed_files, id)
582
+ prompt_csv = ""
583
+ answer_csv = ""
584
+ if test_csv:
585
+ prompt_csv = f"Dựa vào nội dung sau: {text_csv}. Hãy trả lời câu hỏi sau đây: {query_csv}.Bằng tiếng Việt"
586
+ answer_csv = question_answer(prompt_csv)
587
+ answer_document, data_relevant, source = aws1_all_id(new_dict, text_all, id, thread_id)
588
+ answer_all1 = answer_document + answer_csv
589
+ return answer_all1, data_relevant, source
590
+ else:
591
+ compressed_docs = compression_retriever.get_relevant_documents(f"{query}")
592
+ relevance_score_float = float(compressed_docs[0].metadata['relevance_score'])
593
+ print(relevance_score_float)
594
+ if relevance_score_float <= 0.12:
595
+ documents1 = []
596
+ for file in os.listdir(f"./code/user_file/{id}"):
597
+ if file.endswith('.csv'):
598
+ csv_path = f"./code/user_file/{id}/" + file
599
+ loader = UnstructuredCSVLoader(csv_path)
600
+ documents1.extend(loader.load())
601
+ elif file.endswith('.xlsx'):
602
+ excel_path = f"./code/user_file/{id}/" + file
603
+ loader = UnstructuredExcelLoader(excel_path)
604
+ documents1.extend(loader.load())
605
+ text_splitter_csv = CharacterTextSplitter.from_tiktoken_encoder(chunk_size=2200, chunk_overlap=1500)
606
+ texts_csv = text_splitter_csv.split_documents(documents1)
607
+ vectordb_csv = Chroma.from_documents(documents=texts_csv,
608
+ embedding=embeddings, persist_directory=f'./code/vector_database/csv/{thread_id}')
609
+ k = len(texts_csv)
610
+ retriever_csv = vectordb_csv.as_retriever(search_kwargs={"k": k})
611
+ llm = Cohere(temperature=0)
612
+ compressor_csv = CohereRerank(top_n=3, model="rerank-english-v2.0")
613
+ compression_retriever_csv = ContextualCompressionRetriever(
614
+ base_compressor=compressor_csv, base_retriever=retriever_csv
615
+ )
616
+ compressed_docs_csv = compression_retriever_csv.get_relevant_documents(f"{query}")
617
+ file_path = compressed_docs_csv[0].metadata['source']
618
+ print(file_path)
619
+ if file_path.endswith('.xlsx'):
620
+ new = file_path.replace(".xlsx", ".csv")
621
+ convert_xlsx_to_csv(file_path, new)
622
+ loader1 = CSVLoader(new)
623
+ else:
624
+ loader1 = CSVLoader(file_path)
625
+ docs1 = loader1.load()
626
+ text = " "
627
+ for z in docs1:
628
+ text += z.page_content + "\n"
629
+ prompt_csv = f"Dựa vào nội dung sau: {text}. Hãy trả lời câu hỏi sau đây: {query}. Bằng tiếng Việt"
630
+ answer_csv = question_answer(prompt_csv)
631
+ return answer_csv
632
+ else:
633
+ file_path = compressed_docs[0].metadata['source']
634
+ file_path = file_path.replace('\\', '/')
635
+ print(file_path)
636
+ if file_path.endswith(".pdf"):
637
+ loader = UnstructuredPDFLoader(file_path)
638
+ elif file_path.endswith('.docx') or file_path.endswith('doc'):
639
+ loader = Docx2txtLoader(file_path)
640
+ elif file_path.endswith('.txt'):
641
+ loader = TextLoader(file_path, encoding="utf8")
642
+ elif file_path.endswith('.pptx'):
643
+ loader = UnstructuredPowerPointLoader(file_path)
644
+ elif file_path.endswith('.xml'):
645
+ loader = UnstructuredXMLLoader(file_path)
646
+ elif file_path.endswith('.html'):
647
+ loader = UnstructuredHTMLLoader(file_path)
648
+ elif file_path.endswith('.json'):
649
+ loader = TextLoader(file_path)
650
+ elif file_path.endswith('.md'):
651
+ loader = UnstructuredMarkdownLoader(file_path)
652
+ elif file_path.endswith('.xlsx'):
653
+ file_path_new = file_path.replace(".xlsx", ".csv")
654
+ convert_xlsx_to_csv(file_path, file_path_new)
655
+ loader = CSVLoader(file_path_new)
656
+ elif file_path.endswith('.csv'):
657
+ loader = CSVLoader(file_path)
658
+ text_splitter = CharacterTextSplitter(chunk_size=3200, chunk_overlap=1500)
659
+ texts = text_splitter.split_documents(loader.load())
660
+ k_1 = len(texts)
661
+ file_name = os.path.basename(file_path)
662
+ if check_persist_directory(id, file_name):
663
+ vectordb_file = Chroma(persist_directory=f"./code/vector_database/{id}/{file_name}",
664
+ embedding_function=embeddings)
665
+ else:
666
+ vectordb_file = Chroma.from_documents(texts,
667
+ embedding=embeddings,
668
+ persist_directory=f"./code/vector_database/{id}/{file_name}")
669
+ retriever_file = vectordb_file.as_retriever(search_kwargs={f"k": k_1})
670
+ bm25_retriever = BM25Retriever.from_documents(texts)
671
+ bm25_retriever.k = k_1
672
+ ensemble_retriever = EnsembleRetriever(retrievers=[bm25_retriever, retriever_file],
673
+ weights=[0.6, 0.4])
674
+ docs = ensemble_retriever.get_relevant_documents(f"{query}")
675
+
676
+ path = f"./code/vector_database/FAISS/{id}/{file_name}"
677
+ if check_path_exists(path):
678
+ docsearch = FAISS.load_local(path, embeddings, allow_dangerous_deserialization=True)
679
+ else:
680
+ docsearch = FAISS.from_documents(docs, embeddings)
681
+ docsearch.save_local(f"./code/vector_database/FAISS/{id}/{file_name}")
682
+ docsearch = FAISS.load_local(path, embeddings, allow_dangerous_deserialization=True)
683
+ k_2 = len(docs)
684
+ retrieve3 = docsearch.as_retriever(search_kwargs={f"k": k_2})
685
+ compressor_file = CohereRerank(top_n=3, model="rerank-english-v2.0")
686
+ compression_retriever_file = ContextualCompressionRetriever(
687
+ base_compressor=compressor_file, base_retriever=retrieve3
688
+ )
689
+ compressed_docs_file = compression_retriever_file.get_relevant_documents(f"{x}")
690
+ query = question
691
+ text = ''.join(map(lambda x: x.page_content, compressed_docs_file))
692
+ prompt = f"Dựa vào nội dung sau:{text}. Hãy trả lời câu hỏi sau đây: {query}. Mà không thay đổi, chỉnh sửa nội dung mà mình đã cung cấp"
693
+ answer = question_answer(prompt)
694
+ list_relevant = compressed_docs_file[0].page_content
695
+ source = file_name
696
+ return answer, list_relevant, source
697
+ import concurrent.futures
698
+ def handle_query_upgrade_keyword_old(query_all, text_all, id,chat_history):
699
+ COHERE_API_KEY_2 = os.environ["COHERE_API_KEY_2"]
700
+ os.environ["COHERE_API_KEY"] = COHERE_API_KEY_2
701
+ test = query_analyzer(query_all)
702
+ test_string = str(test)
703
+ matches = re.findall(r"'([^']*)'", test_string)
704
+ vectordb = Chroma(persist_directory=f"./code/vector_database/{id}", embedding_function=embeddings)
705
+ k = len(text_all)
706
+ retriever = vectordb.as_retriever(search_kwargs={"k": k})
707
+ compressor = CohereRerank(top_n=5, model="rerank-english-v2.0")
708
+ compression_retriever = ContextualCompressionRetriever(base_compressor=compressor, base_retriever= retriever)
709
+ with concurrent.futures.ThreadPoolExecutor() as executor:
710
+ futures = {executor.submit(handle_query, query, text_all, compression_retriever, id, i): query for i, query in
711
+ enumerate(matches)}
712
+ results = []
713
+ data_relevant = []
714
+ sources = []
715
+ for future in as_completed(futures):
716
+ try:
717
+ result, list_data, list_source = future.result()
718
+ results.append(result)
719
+ data_relevant.append(list_data)
720
+ sources.append(list_source)
721
+ except Exception as e:
722
+ print(f'An error occurred: {e}')
723
+ answer_all = ''.join(results)
724
+ prompt1 = f"Dựa vào nội dung sau: {answer_all}. Hãy trả lời câu hỏi sau đây: {query_all}. Lưu ý rằng ngữ cảnh của cuộc trò chuyện này trước đây là: {chat_history}. Vui lòng trả lời câu hỏi mà không thay đổi, chỉnh sửa nội dung mà mình đã cung cấp."
725
+ answer1 = question_answer(prompt1)
726
  return answer1, data_relevant, sources