-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
305 lines (243 loc) · 9.88 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
from typing import Optional
from pydantic import BaseModel
from fastapi import FastAPI, Body, Request, Form
import requests
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates
from bson.objectid import ObjectId
import numbering
import pymongo
import uuid
from fastapi.staticfiles import StaticFiles
from dotenv import load_dotenv
import os
import datetime
from bs4 import BeautifulSoup
import urllib.request
from BERT import answeringQA
import ggapi
load_dotenv()
myclient = pymongo.MongoClient(os.environ.get("DB_URL"))
mydb = myclient["NLPdataBase"]
collection = mydb["database"]
class ANS(BaseModel):
text : str
answer_start : int
class QAS(BaseModel) :
question : str
id : str
answer : ANS
class data(BaseModel) :
content : str
qas: list
class NEWS(BaseModel):
content : str
qas : list
app = FastAPI()
app.mount("/static", StaticFiles(directory="static"), name="static")
templates = Jinja2Templates(directory="templates")
@app.get("/", response_class=HTMLResponse)
async def form_delete(request: Request):
colname = mydb.list_collection_names()
print(colname)
return templates.TemplateResponse("index.html", {"request": request, "CollectionName":colname})
@app.post('/')
async def createCollection(request: Request, colname: str = Form(...), ip: str = Form(...)):
print(colname)
time = datetime.datetime.now()
collection = mydb[colname]
create_time = {"name": colname, "time create": time, "ip": ip}
x = collection.insert_one(create_time)
colname = mydb.list_collection_names()
return templates.TemplateResponse("index.html", {"request": request,
"CollectionName":colname})
@app.post("/display", response_class=HTMLResponse)
def loadData(request: Request, nameCollection:str = Form(...) ):
colname = mydb.list_collection_names()
collection = mydb[nameCollection]
li = list(collection.find())
size = len(li)
print(colname)
tieude = "Xem tất cả data đã nhập từ collection "+ nameCollection
return templates.TemplateResponse("displayData.html", {
"request": request,
"size" : size,
"jsonData" : li,
"tieude" : tieude,
"CollectionName":colname,
"nameCollection":nameCollection,
})
@app.get("/home", response_class=HTMLResponse)
def write_home(request: Request ):
colname = mydb.list_collection_names()
user_name = "MTA NLP TEAM"
return templates.TemplateResponse("home.html", {"request": request,
"username": user_name,
"CollectionName":colname,
})
def MainProcess(collection, content, listQuestion , listAnswer):# tạo data và thêm vào db
listContent = numbering.contentToList(content)
listQAS = list()
for i in range(len(listAnswer)):
answer = listAnswer[i]
question = listQuestion[i]
start = numbering.findSentence(answer,listContent)
objAnswer = ANS(
text = answer,
answer_start = start
)
id = (uuid.uuid4().hex)
objQuestionAndAnswer = QAS(
question = question,
id = id,
answer = objAnswer
)
listQAS.append(objQuestionAndAnswer.dict())
print(len(listQAS))
newData = data(
content = content,
qas = listQAS
)
print(collection)
collection.insert_one(newData.dict())
return (newData.dict())
@app.post('/home')
async def handle_form(content : str = Form(...), qas : list = Form(...), nameCollection:str = Form(...)):
collection = mydb[nameCollection]
listQuestion = numbering.createListQuestion(qas)
listAnswer = numbering.createListAnswer(qas)
return MainProcess(collection, content, listQuestion, listAnswer)
@app.get("/display-data", response_class=HTMLResponse)
def loadGetAllData(request: Request):
colname = mydb.list_collection_names()
tieude = "Xem tất cả data đã nhập"
return templates.TemplateResponse("displayData.html", {
"request": request,
"tieude" : tieude,
"CollectionName":colname,
})
@app.get("/delete/{id}/{nameCollection}")
async def form_delete(request: Request, id : str, nameCollection : str):
collection = mydb[nameCollection]
myquery = {"_id": ObjectId(id)}
li = collection.find_one(myquery)
content = li['content']
qas = li['qas']
tieude = "Xem lại data đã xóa"
collection.delete_one(myquery)
return templates.TemplateResponse("delete.html", {"request": request,
"tieude": tieude,
"content": content,
"qas" : qas})
@app.get("/editData/{id}/{nameCollection}", response_class=HTMLResponse)
def editData(request: Request, id : str, nameCollection: str):
collection = mydb[nameCollection]
myquery = {"_id": ObjectId(id)}
obj = collection.find_one(myquery)
content = obj['content']
qas = obj['qas']
return templates.TemplateResponse("editData.html", {
"request": request,
"content" : content,
"qas" : qas,
"id": id,
"nameCollection":nameCollection,
})
def UpdateProcess(collection, idObj, content, listQuestion , listAnswer):# update một bảng ghi trong db
listContent = numbering.contentToList(content)
listQAS = list()
for i in range(len(listAnswer)):
answer = listAnswer[i]
question = listQuestion[i]
start = numbering.findSentence(answer,listContent)
objAnswer = ANS(
text = answer,
answer_start = start
)
id = (uuid.uuid4().hex)
objQuestionAndAnswer = QAS(
question = question,
id = id,
answer = objAnswer
)
listQAS.append(objQuestionAndAnswer.dict())
print(len(listQAS))
newData = data(
content = content,
qas = listQAS
)
myquery = {"_id": ObjectId(idObj)}
newvalues = { "$set": newData.dict()}
collection.update(myquery, newvalues)
return (newData.dict())
@app.post('/update-data')
async def updateData(content : str = Form(...), qas : list = Form(...), id = Form(...), nameCollection: str = Form(...)):
print(id)
collection = mydb[nameCollection]
listQuestion = numbering.createListQuestion(qas)
listAnswer = numbering.createListAnswer(qas)
return UpdateProcess(collection, id, content, listQuestion, listAnswer)
@app.get("/guide", response_class=HTMLResponse)
def write_home(request: Request):
return templates.TemplateResponse("guide.html", {"request": request})
# ========================================= CRAWL DATA ===========================================================
@app.get("/crawl", response_class=HTMLResponse)
async def form_delete(request: Request):
colname = mydb.list_collection_names()
print(colname)
return templates.TemplateResponse("crawl.html", {"request": request, "CollectionName":colname})
@app.post('/crawl')
async def createCollection(request: Request,nameCollection: str = Form(...), url: str = Form(...)):
diclist = crawlData(url)
collection = mydb[nameCollection]
for li in diclist:
content = li['content']
qas = li['qas']
listQuestion = numbering.createListQuestion(qas)
listAnswer = numbering.createListAnswer(qas)
MainProcess(collection, content, listQuestion, listAnswer)
return templates.TemplateResponse("success.html",{"request": request})
def crawlData(url):
dictList = []
page = urllib.request.urlopen(url)
soup = BeautifulSoup(page, 'html.parser')
news = soup.find_all('div', attrs={'class' : 'para-wrap'})
for i in range(len(news)):
content = (news[i].find('pre').text)
qaswrap = news[i].find_all('div', class_='qa-wrap')
li = []
for j in range(len(qaswrap)):
question = qaswrap[j].find_all('strong',class_='question')
answer = qaswrap[j].find_all('span',class_='answer')
if(not len(answer)):
answer = qaswrap[j].find_all('span',class_='no-answer')
if(len(question)):
li.append(question[0].text)
li.append(answer[0].text)
temp = NEWS(
content = content,
qas = li
).dict()
dictList.append(temp)
return dictList
#================== GG Search ========================
@app.get("/searchGG", response_class=HTMLResponse)
async def Find_Ans(request: Request):
ListAns = []
ListLink = []
leng = 0
question = ""
PredictAnswer = [{
"answer":"",
"score_start": 0
}]
ListRecent = ggapi.recentQuestion()
return templates.TemplateResponse("SearchGG.html", {"request": request,"PredictAnswer":PredictAnswer, "ListAns":ListAns, "ListLink":ListLink , "leng":leng , "question" : question, "ListRecent" :ListRecent})
@app.post('/searchGG')
async def Find_Ans(request: Request,question: str = Form(...)):
(PredictAnswer,ListLink,listcontext) = answeringQA(question)
leng = (len(listcontext))
print("Số kết quả tìm được ===========> ",leng)
print(PredictAnswer)
ListRecent = ggapi.recentQuestion()
return templates.TemplateResponse("SearchGG.html",{"request": request,"PredictAnswer":PredictAnswer,"ListAns":listcontext, "ListLink":ListLink, "leng":leng, "question" : question , "ListRecent" :ListRecent})