ntphuc149 commited on
Commit
4076aec
·
verified ·
1 Parent(s): d345eca
Files changed (1) hide show
  1. app.py +134 -118
app.py CHANGED
@@ -5,7 +5,7 @@ import streamlit as st
5
  import os
6
  from urllib.parse import urlencode, urlparse, parse_qs
7
 
8
- st.set_page_config(page_title="ViBidLQA - Trợ lý AI hỗ trợ hỏi đáp luật Việt Nam", page_icon="./app/static/ai.jpg", layout="centered", initial_sidebar_state="collapsed")
9
 
10
  # ==== MÔI TRƯỜNG OAuth ====
11
  FB_APP_ID = os.getenv("FB_APP_ID")
@@ -28,6 +28,7 @@ url_api_introduce_system_model = f"{routing_response_module}/about_me"
28
  url_api_retrieval_model = f"{retrieval_module}/search"
29
  url_api_reranker_model = f"{reranker_module}/rerank"
30
  url_api_generation_model = f"{abs_QA_module}/answer"
 
31
 
32
  # ========== STREAMLIT UI ==========
33
 
@@ -117,17 +118,9 @@ def rerank_context(url_rerank_module, question, relevant_docs, top_k=5):
117
  else:
118
  return f"Lỗi tại Rerank module: {response.status_code} - {response.text}"
119
 
120
- def get_abstractive_answer(question):
121
- retrieved_context = retrieve_context(question=question)
122
- retrieved_context = [item['text'] for item in retrieved_context]
123
-
124
- reranked_context = rerank_context(url_rerank_module=url_api_reranker_model,
125
- question=question,
126
- relevant_docs=retrieved_context,
127
- top_k=5)[0]
128
-
129
  data = {
130
- "context": reranked_context,
131
  "question": question
132
  }
133
 
@@ -138,6 +131,20 @@ def get_abstractive_answer(question):
138
  else:
139
  return f"Lỗi: {response.status_code} - {response.text}"
140
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
141
  def generate_text_effect(answer):
142
  words = answer.split()
143
  for i in range(len(words)):
@@ -171,120 +178,129 @@ if prompt := st.chat_input(placeholder='Tôi có thể giúp được gì cho b
171
  message_placeholder = st.empty()
172
 
173
  full_response = ""
174
- try:
175
- classify_result = classify_question(question=prompt).json()
176
 
177
- print(f"The type of user query: {classify_result}")
178
-
179
- if classify_result == "BIDDING_RELATED":
180
- abs_answer = get_abstractive_answer(question=prompt)
181
-
182
- if isinstance(abs_answer, str):
183
- full_response = abs_answer
184
- message_placeholder.markdown(f"""
185
- <div class="assistant-message">
186
- <img src="./app/static/ai.jpg" class="assistant-avatar" />
187
- <div class="stMarkdown">{full_response}</div>
188
- </div>
189
- """, unsafe_allow_html=True)
190
- else:
191
- full_response = ""
192
- for line in abs_answer.iter_lines():
193
- if line:
194
- line = line.decode('utf-8')
195
- if line.startswith('data: '):
196
- data_str = line[6:]
197
- if data_str == '[DONE]':
198
- break
 
 
 
 
 
 
 
 
 
 
 
 
199
 
200
- try:
201
- data = json.loads(data_str)
202
- token = data.get('token', '')
203
- full_response += token
204
-
205
- message_placeholder.markdown(f"""
206
- <div class="assistant-message">
207
- <img src="./app/static/ai.jpg" class="assistant-avatar" />
208
- <div class="stMarkdown">{full_response}●</div>
209
- </div>
210
- """, unsafe_allow_html=True)
211
-
212
- except json.JSONDecodeError:
213
- pass
214
-
215
- elif classify_result == "ABOUT_CHATBOT":
216
- answer = introduce_system(question=prompt)
217
-
218
- if isinstance(answer, str):
219
- full_response = answer
220
- message_placeholder.markdown(f"""
221
- <div class="assistant-message">
222
- <img src="./app/static/ai.jpg" class="assistant-avatar" />
223
- <div class="stMarkdown">{full_response}</div>
224
- </div>
225
- """, unsafe_allow_html=True)
226
- else:
227
- full_response = ""
228
- for line in answer.iter_lines():
229
- if line:
230
- line = line.decode('utf-8')
231
- if line.startswith('data: '):
232
- data_str = line[6:]
233
- if data_str == '[DONE]':
234
- break
235
 
236
- try:
237
- data = json.loads(data_str)
238
- token = data.get('token', '')
239
- full_response += token
240
-
241
- message_placeholder.markdown(f"""
242
- <div class="assistant-message">
243
- <img src="./app/static/ai.jpg" class="assistant-avatar" />
244
- <div class="stMarkdown">{full_response}●</div>
245
- </div>
246
- """, unsafe_allow_html=True)
247
-
248
- except json.JSONDecodeError:
249
- pass
250
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
251
  else:
252
- answer = response_unrelated_question(question=prompt)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
253
 
254
- if isinstance(answer, str):
255
- full_response = answer
256
- message_placeholder.markdown(f"""
257
- <div class="assistant-message">
258
- <img src="./app/static/ai.jpg" class="assistant-avatar" />
259
- <div class="stMarkdown">{full_response}</div>
260
- </div>
261
- """, unsafe_allow_html=True)
262
- else:
263
- full_response = ""
264
- for line in answer.iter_lines():
265
- if line:
266
- line = line.decode('utf-8')
267
- if line.startswith('data: '):
268
- data_str = line[6:]
269
- if data_str == '[DONE]':
270
- break
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
271
 
272
- try:
273
- data = json.loads(data_str)
274
- token = data.get('token', '')
275
- full_response += token
276
-
277
- message_placeholder.markdown(f"""
278
- <div class="assistant-message">
279
- <img src="./app/static/ai.jpg" class="assistant-avatar" />
280
- <div class="stMarkdown">{full_response}●</div>
281
- </div>
282
- """, unsafe_allow_html=True)
283
-
284
- except json.JSONDecodeError:
285
- pass
286
- except Exception as e:
287
- full_response = "Hiện tại trợ lý AI đang nghỉ xíu để sạc pin 🔌. Bạn hãy quay lại sau nhé!"
288
 
289
  message_placeholder.markdown(f"""
290
  <div class="assistant-message">
 
5
  import os
6
  from urllib.parse import urlencode, urlparse, parse_qs
7
 
8
+ st.set_page_config(page_title="ViBidLQA - Trợ lý AI văn bản pháp luật Việt Nam", page_icon="./app/static/ai.jpg", layout="centered", initial_sidebar_state="collapsed")
9
 
10
  # ==== MÔI TRƯỜNG OAuth ====
11
  FB_APP_ID = os.getenv("FB_APP_ID")
 
28
  url_api_retrieval_model = f"{retrieval_module}/search"
29
  url_api_reranker_model = f"{reranker_module}/rerank"
30
  url_api_generation_model = f"{abs_QA_module}/answer"
31
+ url_api_extract_reference_model = f"{routing_response_module}/extract_references_unstream"
32
 
33
  # ========== STREAMLIT UI ==========
34
 
 
118
  else:
119
  return f"Lỗi tại Rerank module: {response.status_code} - {response.text}"
120
 
121
+ def get_abstractive_answer(context, question):
 
 
 
 
 
 
 
 
122
  data = {
123
+ "context": context,
124
  "question": question
125
  }
126
 
 
131
  else:
132
  return f"Lỗi: {response.status_code} - {response.text}"
133
 
134
+ def get_references(context, question, answer):
135
+ data = {
136
+ "context": context,
137
+ "question": question,
138
+ "answer": answer
139
+ }
140
+
141
+ response = requests.post(url_api_extract_reference_model, json=data)
142
+
143
+ if response.status_code == 200:
144
+ return response.json()["refs"]
145
+ else:
146
+ return f"Lỗi tại module Reference Extractor: {response.status_code} - {response.text}"
147
+
148
  def generate_text_effect(answer):
149
  words = answer.split()
150
  for i in range(len(words)):
 
178
  message_placeholder = st.empty()
179
 
180
  full_response = ""
181
+ classify_result = classify_question(question=prompt).json()
 
182
 
183
+ print(f"The type of user query: {classify_result}")
184
+
185
+ if classify_result == "BIDDING_RELATED":
186
+ retrieved_context = retrieve_context(question=prompt, top_k=10)
187
+ retrieved_context = [item['text'] for item in retrieved_context]
188
+ reranked_context = rerank_context(url_rerank_module=url_api_reranker_model,
189
+ question=prompt,
190
+ relevant_docs=retrieved_context,
191
+ top_k=5)[0]
192
+
193
+ abs_answer = get_abstractive_answer(context=reranked_context, question=prompt)
194
+
195
+ if isinstance(abs_answer, str):
196
+ full_response = abs_answer
197
+ message_placeholder.markdown(f"""
198
+ <div class="assistant-message">
199
+ <img src="./app/static/ai.jpg" class="assistant-avatar" />
200
+ <div class="stMarkdown">{full_response}</div>
201
+ </div>
202
+ """, unsafe_allow_html=True)
203
+ else:
204
+ full_response = ""
205
+ for line in abs_answer.iter_lines():
206
+ if line:
207
+ line = line.decode('utf-8')
208
+ if line.startswith('data: '):
209
+ data_str = line[6:]
210
+ if data_str == '[DONE]':
211
+ break
212
+
213
+ try:
214
+ data = json.loads(data_str)
215
+ token = data.get('token', '')
216
+ full_response += token
217
 
218
+ message_placeholder.markdown(f"""
219
+ <div class="assistant-message">
220
+ <img src="./app/static/ai.jpg" class="assistant-avatar" />
221
+ <div class="stMarkdown">{full_response}●</div>
222
+ </div>
223
+ """, unsafe_allow_html=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
224
 
225
+ except json.JSONDecodeError:
226
+ pass
 
 
 
 
 
 
 
 
 
 
 
 
227
 
228
+ refs = st.expander("Tài liệu tham khảo", expanded=False)
229
+ refs_list = get_references(context=reranked_context, question=prompt, answer=full_response)
230
+ print(refs_list)
231
+ refs.write(f"{refs_list}")
232
+
233
+ elif classify_result == "ABOUT_CHATBOT":
234
+ answer = introduce_system(question=prompt)
235
+
236
+ if isinstance(answer, str):
237
+ full_response = answer
238
+ message_placeholder.markdown(f"""
239
+ <div class="assistant-message">
240
+ <img src="./app/static/ai.jpg" class="assistant-avatar" />
241
+ <div class="stMarkdown">{full_response}</div>
242
+ </div>
243
+ """, unsafe_allow_html=True)
244
  else:
245
+ full_response = ""
246
+ for line in answer.iter_lines():
247
+ if line:
248
+ line = line.decode('utf-8')
249
+ if line.startswith('data: '):
250
+ data_str = line[6:]
251
+ if data_str == '[DONE]':
252
+ break
253
+
254
+ try:
255
+ data = json.loads(data_str)
256
+ token = data.get('token', '')
257
+ full_response += token
258
+
259
+ message_placeholder.markdown(f"""
260
+ <div class="assistant-message">
261
+ <img src="./app/static/ai.jpg" class="assistant-avatar" />
262
+ <div class="stMarkdown">{full_response}●</div>
263
+ </div>
264
+ """, unsafe_allow_html=True)
265
+
266
+ except json.JSONDecodeError:
267
+ pass
268
 
269
+ else:
270
+ answer = response_unrelated_question(question=prompt)
271
+
272
+ if isinstance(answer, str):
273
+ full_response = answer
274
+ message_placeholder.markdown(f"""
275
+ <div class="assistant-message">
276
+ <img src="./app/static/ai.jpg" class="assistant-avatar" />
277
+ <div class="stMarkdown">{full_response}</div>
278
+ </div>
279
+ """, unsafe_allow_html=True)
280
+ else:
281
+ full_response = ""
282
+ for line in answer.iter_lines():
283
+ if line:
284
+ line = line.decode('utf-8')
285
+ if line.startswith('data: '):
286
+ data_str = line[6:]
287
+ if data_str == '[DONE]':
288
+ break
289
+
290
+ try:
291
+ data = json.loads(data_str)
292
+ token = data.get('token', '')
293
+ full_response += token
294
+
295
+ message_placeholder.markdown(f"""
296
+ <div class="assistant-message">
297
+ <img src="./app/static/ai.jpg" class="assistant-avatar" />
298
+ <div class="stMarkdown">{full_response}●</div>
299
+ </div>
300
+ """, unsafe_allow_html=True)
301
 
302
+ except json.JSONDecodeError:
303
+ pass
 
 
 
 
 
 
 
 
 
 
 
 
 
 
304
 
305
  message_placeholder.markdown(f"""
306
  <div class="assistant-message">