ThuyNT03 commited on
Commit
6aad9b3
1 Parent(s): 1e8e971

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +261 -0
app.py ADDED
@@ -0,0 +1,261 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import random
3
+ import time
4
+ from rank_bm25 import BM25Okapi, BM25Plus
5
+ import re
6
+ import numpy as np
7
+ from underthesea import text_normalize
8
+ import pandas as pd
9
+ from pyvi import ViTokenizer
10
+ import heapq
11
+ import torch
12
+ from transformers import AutoModel, AutoTokenizer
13
+ from pyvi.ViTokenizer import tokenize
14
+ from sklearn.metrics.pairwise import cosine_similarity
15
+ from sentence_transformers import CrossEncoder
16
+ import heapq
17
+ from sklearn.metrics.pairwise import cosine_similarity
18
+ from sentence_transformers import SentenceTransformer, CrossEncoder
19
+ from sentence_transformers import SentenceTransformer
20
+ from pyvi.ViTokenizer import tokenize
21
+ from Levenshtein import ratio as lev
22
+ from Levenshtein import ratio as lev
23
+ from openai import OpenAI
24
+ import re
25
+ import numpy as np
26
+ from underthesea import text_normalize
27
+
28
+ def chuan_hoa_unicode_go_dau(text):
29
+ return text_normalize(text)
30
+
31
+ def viet_thuong(text):
32
+ return text.lower()
33
+
34
+ def chuan_hoa_dau_cau(text):
35
+ text = re.sub(r'[^\s\wáàảãạăắằẳẵặâấầẩẫậéèẻẽẹêếềểễệóòỏõọôốồổỗộơớờởỡợíìỉĩịúùủũụưứừửữựýỳỷỹỵđ_]',' ',text)
36
+ text = re.sub(r'\s+', ' ', text).strip()
37
+ return text
38
+
39
+ def chuan_hoa_cau(doc):
40
+ pattern = r'(\w)([^\s\w])'
41
+ result1 = re.sub(pattern, r'\1 \2', doc)
42
+
43
+ pattern = r'([^\s\w])(\w)'
44
+ result2 = re.sub(pattern, r'\1 \2', result1)
45
+
46
+ pattern = r'\s+'
47
+ # Loại bỏ khoảng trắng thừa
48
+ result = re.sub(pattern, ' ', result2)
49
+ return result
50
+
51
+ def my_pre_processing(doc):
52
+ doc = chuan_hoa_unicode_go_dau(doc)
53
+ doc = chuan_hoa_dau_cau(doc)
54
+ doc = chuan_hoa_cau(doc)
55
+ doc = viet_thuong(doc)
56
+ return doc
57
+
58
+
59
+ def levenshtein_similarity(sentence1, sentence2):
60
+ return lev(sentence1, sentence2)
61
+
62
+ def jaccard_similarity(sentence1, sentence2):
63
+ # Tokenize sentences into words
64
+ words1 = set(sentence1.lower().split())
65
+ words2 = set(sentence2.lower().split())
66
+
67
+ # Calculate intersection and union of the sets
68
+ intersection = len(words1.intersection(words2))
69
+ union = len(words1.union(words2))
70
+
71
+ # Calculate Jaccard Similarity
72
+ jaccard_similarity = intersection / union
73
+
74
+ # Define min and max Jaccard similarity scores (0 and 1.0 in this case)
75
+ min_score = 0.0
76
+ max_score = 1.0
77
+
78
+ # Normalize Jaccard Similarity to range from 0 to 1.0
79
+ normalized_similarity = (jaccard_similarity - min_score) / (max_score - min_score)
80
+
81
+ return normalized_similarity
82
+
83
+ def filter_similarity(sentence1, sentence2, debug = False):
84
+ score_leve = levenshtein_similarity(sentence1, sentence2)
85
+ score_jac = jaccard_similarity(sentence1, sentence2)
86
+
87
+ if debug:
88
+ print(sentence2)
89
+ print("Levenshtein similarity", score_leve)
90
+ print("Jaccard similarity", score_jac)
91
+
92
+ return (score_leve + score_jac) / 2
93
+
94
+ def top_n_indexes(lst, n):
95
+ top_items = heapq.nlargest(n, enumerate(lst), key=lambda x: x[1])
96
+ return [i for i, s in top_items]
97
+
98
+ def BM25_retrieval(query, seg_question_corpus, top_BM25):
99
+ query = my_pre_processing(query)
100
+ word_tokenized_query = ViTokenizer.tokenize(query).split(" ")
101
+ # xử lý ở level word với question
102
+ tokenized_word_question_corpus = [doc.split(" ") for doc in seg_question_corpus]
103
+ bm25_word_question = BM25Plus(tokenized_word_question_corpus)
104
+ word_score_question = bm25_word_question.get_scores(word_tokenized_query)
105
+ BM25_result = top_n_indexes(word_score_question, n=top_BM25)
106
+ return BM25_result
107
+
108
+ def SimCSE_retrieval(query, SimCSE_set, top_Sim):
109
+ from sentence_transformers import CrossEncoder
110
+ query = my_pre_processing(query)
111
+ # Sim_CSE_model_question = SentenceTransformer('VoVanPhuc/sup-SimCSE-VietNamese-phobert-base')
112
+ # Sim_CSE_word_ques_embeddings = torch.load('/content/drive/MyDrive/Study/Năm 3/CS336-IR/model/word_ques_embeddings.pth')
113
+ Sim_CSE_model_question = SimCSE_set[0]
114
+ Sim_CSE_word_ques_embeddings = SimCSE_set[1]
115
+
116
+ seg_query = ViTokenizer.tokenize(query)
117
+ query_vector = Sim_CSE_model_question.encode(seg_query)
118
+ SimCSE_word_scores = list(cosine_similarity([query_vector], Sim_CSE_word_ques_embeddings)[0])
119
+ SimCSE_result = top_n_indexes(SimCSE_word_scores, n=top_Sim)
120
+ return SimCSE_result
121
+
122
+ def Para_retriveval(query, para_set, top_para):
123
+ query = my_pre_processing(query)
124
+ from sentence_transformers import SentenceTransformer, CrossEncoder
125
+ import torch
126
+ # retri_model = SentenceTransformer('sentence-transformers/paraphrase-multilingual-mpnet-base-v2')
127
+ # para_question_embeddings = torch.load('/content/drive/MyDrive/Study/Năm 3/CS336-IR/model/para_embeddings.pth')
128
+ retri_model = para_set[0]
129
+ para_question_embeddings = para_set[1]
130
+
131
+ query_embed = retri_model.encode([query], device = device)
132
+ para_score = cosine_similarity(query_embed, para_question_embeddings)[0]
133
+ Para_result = top_n_indexes(para_score, n = top_para)
134
+ return Para_result
135
+
136
+ def Rerank(query, retrieval_result, question_corpus, reranker, top_n):
137
+ #rerank_model_name = 'unicamp-dl/mMiniLM-L6-v2-mmarco-v2'
138
+ query = my_pre_processing(query)
139
+ #reranker = CrossEncoder(rerank_model_name)
140
+ scores = reranker.predict([(query, question_corpus[i]) for i in retrieval_result])
141
+ id_score = list(zip(retrieval_result, scores))
142
+ sorted_id_score = sorted(id_score, key=lambda x: x[1], reverse=True)[:(min(len(retrieval_result), top_n))]
143
+ return sorted_id_score
144
+
145
+ def retrieval(query, question_corpus, seg_question_corpus, models, top_n = 15, thread_hold = 0.2, rerank = True):
146
+ BM25_result = BM25_retrieval(query, seg_question_corpus, top_n)
147
+ SimCSE_result = SimCSE_retrieval(query, models['Sim_CSE'], top_n)
148
+ Para_result = Para_retriveval(query, models['para'], top_n)
149
+ retrieval_result = list(set(BM25_result + SimCSE_result + Para_result))
150
+ #sents_retri = [question_corpus[i] for i in retrieval_result]
151
+
152
+ scores_filter = []
153
+ while len(scores_filter) == 0 and thread_hold >= 0:
154
+ scores_filter = []
155
+ for id in retrieval_result:
156
+ score = filter_similarity(my_pre_processing(query), question_corpus[id])
157
+ if score >= thread_hold:
158
+ scores_filter.append((score, id))
159
+ thread_hold -= 0.1
160
+ scores_filter = sorted(scores_filter, key = lambda x : x[0], reverse=True)
161
+ sent_filter = [i[1] for i in scores_filter]
162
+
163
+ if rerank == False:
164
+ return retrieval_result
165
+ rerank_result = Rerank(query, sent_filter, question_corpus, models['rerank'], top_n)
166
+ sent_rerank = [i[0] for i in rerank_result]
167
+ sent_rerank.append(-1)
168
+
169
+ score_rerank = [i[1] for i in rerank_result]
170
+ score_rerank = [(i - min(score_rerank))/(max(score_rerank) - min(score_rerank)) for i in score_rerank]
171
+ data_rerank = {}
172
+ for i in sent_rerank:
173
+ data_rerank[i] = []
174
+
175
+ for idx, id in enumerate(sent_rerank):
176
+ for j in range(idx + 1, len(sent_rerank)):
177
+ if id == -1:
178
+ sent1 = my_pre_processing(query)
179
+ else:
180
+ sent1 = question_corpus[id]
181
+
182
+ if sent_rerank[j] == -1:
183
+ sent2 = my_pre_processing(query)
184
+ else:
185
+ sent2 = question_corpus[sent_rerank[j]]
186
+
187
+ score = filter_similarity(sent1, sent2) * score_rerank[idx]
188
+ data_rerank[id].append(score)
189
+ data_rerank[sent_rerank[j]].append(score)
190
+
191
+ del data_rerank[-1]
192
+ data_rerank = {key: sum(data)/len(data) for key, data in data_rerank.items()}
193
+ scores_rerank = [{'corpus_id': key, 'score': score} for key, score in sorted(data_rerank.items(), key = lambda x: x[1], reverse = True)]
194
+
195
+ return scores_rerank
196
+
197
+
198
+
199
+ client = OpenAI(
200
+ # defaults to os.environ.get("OPENAI_API_KEY")
201
+ api_key="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",
202
+ )
203
+
204
+ def chat_gpt(prompt):
205
+ response = client.chat.completions.create(
206
+ model="gpt-3.5-turbo",
207
+ messages=[{"role": "user", "content": prompt}]
208
+ )
209
+ return response.choices[0].message.content.strip()
210
+
211
+ if torch.cuda.is_available():
212
+ device = 'cuda'
213
+ else:
214
+ device = 'cpu'
215
+
216
+ df = pd.read_csv('.\source\corpus.csv')
217
+ question_corpus = list(df['question_corpus'])
218
+ seg_question_corpus = list(df['seg_question_corpus'])
219
+ Sim_CSE_model = SentenceTransformer('VoVanPhuc/sup-SimCSE-VietNamese-phobert-base')
220
+ Sim_CSE_word_ques_embeddings = torch.load('.\source\word_ques_embeddings.pth')
221
+
222
+ para_model = SentenceTransformer('sentence-transformers/paraphrase-multilingual-mpnet-base-v2')
223
+ para_question_embeddings = torch.load('.\source\para_embeddings.pth')
224
+
225
+ rerank_model = CrossEncoder('unicamp-dl/mMiniLM-L6-v2-mmarco-v2')
226
+
227
+ models = {'rerank': rerank_model, 'para': [para_model, para_question_embeddings], 'Sim_CSE': [Sim_CSE_model, Sim_CSE_word_ques_embeddings]}
228
+ source_corpus = pd.read_csv("./source/new_tthc.csv")
229
+
230
+ def RAG(query):
231
+ answer = {'query': query}
232
+ retri_result = retrieval(query, question_corpus, seg_question_corpus, models, top_n = 25, rerank = True)
233
+ if len(retri_result) == 0:
234
+ answer['answer'] = "Không tìm thấy thủ tục hành chính phù hợp"
235
+ return answer
236
+ corpus_id = retri_result[0]['corpus_id']
237
+ info = source_corpus.loc[corpus_id]
238
+ answer['tthc'] = info['PROCEDURE_NAME']
239
+ prompt = f"Chỉ dựa vào thông tin ngữ cảnh tôi cung cấp để trả lời câu hỏi. Chú ý giản cách dòng hợp lý: \n Câu hỏi: {answer['query']} \n Ngữ cảnh: {info['IMPL_ORDER']}"
240
+ #print("RAG function Propmt", prompt)
241
+ answer['answer'] = chat_gpt(prompt)
242
+ answer['reference'] = f"https://dichvucong.gov.vn/p/home/dvc-tthc-thu-tuc-hanh-chinh-chi-tiet.html?ma_thu_tuc={info['ID']}"
243
+ return answer
244
+
245
+ #print(RAG("tôi muốn biết cách làm biển sổ xe lần lần đầu"))
246
+ with gr.Blocks() as demo:
247
+ chatbot = gr.Chatbot()
248
+ msg = gr.Textbox()
249
+ clear = gr.ClearButton([msg, chatbot])
250
+
251
+ def respond(message, chat_history):
252
+ answer = RAG(message)
253
+ bot_message = f"Tên thủ tục hành chính: {answer['tthc']}\nCâu trả lời:\n{answer['answer']}\nNguồn: {answer['reference']}"
254
+ chat_history.append((message, bot_message))
255
+ time.sleep(2)
256
+ return "", chat_history
257
+
258
+ msg.submit(respond, [msg, chatbot], [msg, chatbot])
259
+
260
+ if __name__ == "__main__":
261
+ demo.launch(inline = False)