quoc-khanh commited on
Commit
1d07d89
·
verified ·
1 Parent(s): d44a5bf

Update helpers.py

Browse files
Files changed (1) hide show
  1. helpers.py +1 -99
helpers.py CHANGED
@@ -21,32 +21,6 @@ if "GOOGLE_API_KEY" not in os.environ:
21
  os.environ["GOOGLE_API_KEY"] = "AIzaSyDJ4vIKuIBIPNHATLxnoHlagXWbsAz-vRs"
22
  key = "AIzaSyDJ4vIKuIBIPNHATLxnoHlagXWbsAz-vRs"
23
 
24
- ###
25
-
26
- def get_vectorstore():
27
- ### Xử lý tất cả các tài liệu và nhét vào database
28
- folder_path = "syllabus_nct_word_format/"
29
- docx_files = list_docx_files(folder_path)
30
-
31
- all_splits = [] # Khởi tạo danh sách lưu kết quả
32
- for i, file_path in enumerate(tqdm(docx_files, desc="Đang xử lý", unit="file")):
33
- output_json_path = f"output_{i}.json"
34
- splits = get_splits(file_path, output_json_path)
35
- all_splits += splits
36
-
37
- # Xử lý FAQ
38
- FAQ_path = "syllabus_nct_word_format/FAQ.json"
39
- FAQ_splits = get_json_splits_only(FAQ_path)
40
- all_splits += FAQ_splits
41
-
42
- # Lưu vào vectorstore với nhúng từ Google GenAI
43
- embedding = GoogleGenerativeAIEmbeddings(model="models/text-embedding-004")
44
- vectorstore = FAISS.from_documents(documents=all_splits, embedding=embedding)
45
-
46
- return vectorstore
47
-
48
- ###
49
-
50
  async def get_urls_splits(url='https://nct.neu.edu.vn/', char='https://nct.neu.edu.vn/'):
51
  reqs = requests.get(url)
52
  soup = BeautifulSoup(reqs.text, 'html.parser')
@@ -220,76 +194,4 @@ def prompt_order(queries):
220
  for q in queries:
221
  i += 1
222
  text += f'Question {i}: {str(q)}\n'
223
- return text
224
-
225
- # Define the augment_prompt function
226
- def augment_prompt(query: str, k: int = 10):
227
- queries = []
228
- queries.append(query)
229
-
230
- if "vectorstore" not in globals():
231
- print("Không tìm thấy vectorstore. Đang tạo mới...")
232
- vectorstore = get_vectorstore()
233
- print("✅ Vectorstore đã được tạo thành công!")
234
- else:
235
- print("✅ Vectorstore đã tồn tại, không cần tạo lại.")
236
-
237
-
238
- retriever = vectorstore.as_retriever(search_kwargs={"k": k})
239
- results = retriever.invoke(query)
240
-
241
- if results:
242
- source_knowledge = "\n\n".join([doc.page_content for doc in results])
243
- return f"""Using the contexts below, answer the query.
244
-
245
- Contexts:
246
- {source_knowledge}
247
-
248
- """
249
- else:
250
- return f"No relevant context found.\n."
251
-
252
- def get_answer(query, queries_list=None):
253
- if queries_list is None:
254
- queries_list = []
255
-
256
- messages = [
257
- {"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."}]},
258
- {"role": "user", "parts": [{"text": augment_prompt(query)}]}
259
- ]
260
- # bonus = '''
261
- # Bạn tham kháo thêm các nguồn thông tin tại:
262
- # Trang thông tin điện tử: https://neu.edu.vn ; https://daotao.neu.edu.vn
263
- # Trang mạng xã hội có thông tin tuyển sinh: https://www.facebook.com/ktqdNEU ; https://www.facebook.com/tvtsneu ;
264
- # Email tuyển sinh: [email protected]
265
- # Số điện thoại tuyển sinh: 0888.128.558
266
- # '''
267
-
268
- queries_list.append(query)
269
- queries = {"role": "user", "parts": [{"text": prompt_order(queries_list)}]}
270
- messages_with_queries = messages.copy()
271
- messages_with_queries.append(queries)
272
- # messages_with_queries.insert(0, queries)
273
-
274
- # Configure API key
275
- genai.configure(api_key=key)
276
-
277
- # Initialize the Gemini model
278
- model = genai.GenerativeModel("gemini-2.0-flash")
279
-
280
- response = model.generate_content(contents=messages_with_queries, stream=True)
281
- response_text = ""
282
-
283
- for chunk in response:
284
- response_text += chunk.text
285
- yield response_text
286
-
287
- messages.append({"role": "model", "parts": [{"text": response_text}]})
288
-
289
- # user_feedback = yield "\nNhập phản hồi của bạn (hoặc nhập 'q' để thoát): "
290
- # if user_feedback.lower() == "q":
291
- # break
292
-
293
- # messages.append({"role": "user", "parts": [{"text": query}]})
294
-
295
- log_message(messages)
 
21
  os.environ["GOOGLE_API_KEY"] = "AIzaSyDJ4vIKuIBIPNHATLxnoHlagXWbsAz-vRs"
22
  key = "AIzaSyDJ4vIKuIBIPNHATLxnoHlagXWbsAz-vRs"
23
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
  async def get_urls_splits(url='https://nct.neu.edu.vn/', char='https://nct.neu.edu.vn/'):
25
  reqs = requests.get(url)
26
  soup = BeautifulSoup(reqs.text, 'html.parser')
 
194
  for q in queries:
195
  i += 1
196
  text += f'Question {i}: {str(q)}\n'
197
+ return text