-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
257 lines (213 loc) · 7.59 KB
/
app.py
File metadata and controls
257 lines (213 loc) · 7.59 KB
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
# coding: utf-8
# In[1]:
from flask import Flask,jsonify,json
from flask import request
from flask import render_template
import sys
import numpy
import nltk
import nltk.data
import collections
import json
#import yesno
from bs4 import BeautifulSoup
from pycorenlp import StanfordCoreNLP
import os
import sys
import nltk.data
import nltk
from nltk.stem.wordnet import WordNetLemmatizer
lemma = WordNetLemmatizer()
app = Flask(__name__)
sent_detector = nltk.data.load("tokenizers/punkt/english.pickle")
nlp = StanfordCoreNLP('http://localhost:9000')
# Hardcoded word lists
yesnowords = ["can", "could", "would", "is", "does", "has", "was", "were", "had", "have", "did", "are", "will", "wa"]
commonwords = ["the", "a", "an", "is", "are", "were", "."]
questionwords = ["who", "what", "where", "when", "why", "how", "whose", "which", "whom"]
# Process article file
article = open("beatles.txt", 'r')
article = BeautifulSoup(article, "lxml").get_text()
article = ''.join([i if ord(i) < 128 else ' ' for i in article])
article = article.replace("\n", " . ")
article = sent_detector.tokenize(article)
# Take in a tokenized question and return the question type and body
def processquestion(qwords):
# Find "question word" (what, who, where, etc.)
questionword = ""
qidx = -1
for (idx, word) in enumerate(qwords):
if word.lower() in questionwords:
questionword = word.lower()
qidx = idx
break
elif word.lower() in yesnowords:
return ("YESNO", qwords)
if qidx < 0:
return ("MISC", qwords)
if qidx > len(qwords) - 3:
target = qwords[:qidx]
else:
target = qwords[qidx+1:]
type = "MISC"
# Determine question type
if questionword in ["who", "whose", "whom"]:
type = "PERSON"
elif questionword == "where":
type = "PLACE"
elif questionword == "when":
type = "TIME"
elif questionword == "how":
if target[0] in ["few", "little", "much", "many"]:
type = "QUANTITY"
target = target[1:]
elif target[0] in ["young", "old", "long"]:
type = "TIME"
target = target[1:]
# Trim possible extra helper verb
if questionword == "which":
target = target[1:]
if target[0] in yesnowords:
target = target[1:]
# Return question data
return (type, target)
def answeryesno(article, question):
prev = "no"
questionstr = ' '.join(question)
questionstr = questionstr.lower()
question = nltk.pos_tag(question)
answer = "no"
keyword = ""
for (word,pos) in question:
if (pos == 'NN' or pos == 'NNS' or pos == 'NNP' or pos == 'NNPS'):
keyword = word.lower()
answer = "no"
for sentence in article:
# print sentence
if answer == "yes":
break
s = nltk.word_tokenize(sentence.lower())
if keyword in s:
#print sentence
answer = "yes"
for (word,pos) in question:
if answer == 'no':
break
if (pos != '.') and (word.lower() not in s) and (pos != 'DT') and (word != 'does') and (word != 'do'):
answer = 'no'
#print word, pos
if pos[0] == 'V':
tempword = nltk.stem.wordnet.WordNetLemmatizer().lemmatize(word,'v')
for (w,p) in nltk.pos_tag(s):
if p[0] == 'V':
tempword2 = nltk.stem.wordnet.WordNetLemmatizer().lemmatize(w,'v')
if tempword == tempword2:
answer = 'yes'
elif word in article[0]:
answer = "yes"
if prev == "yes":
if (word == "no" or word =="not"):
answer = "no"
if pos[0] == 'V':
prev = "yes"
else:
prev = "no"
#print questionstr,answer
return answer
@app.route('/')
def my_form():
return render_template("my-form.html")
@app.route('/', methods=['POST'])
def my_form_post():
question = request.form['text']
done = False
# Tokenize question
qwords = nltk.word_tokenize(question.lower().replace('?', ''))
questionPOS = nltk.pos_tag(qwords)
qwords = [lemma.lemmatize(q) for q in qwords]
# Process question
(type, target) = processquestion(qwords)
if type == "YESNO":
answer = answeryesno(article, qwords)
return answer
# Get sentence keywords
searchwords = set(target).difference(commonwords)
dict = collections.Counter()
# Find most relevant sentences
for (i, sent) in enumerate(article):
sentwords = nltk.word_tokenize(sent.lower())
sentwords = [lemma.lemmatize(s) for s in sentwords]
wordmatches = set(filter(set(searchwords).__contains__, sentwords))
dict[sent] = len(wordmatches)
answer = []
for (sentence, matches) in dict.most_common(5):
parse = nlp.annotate(sentence,
properties={
'annotators': 'ner',
'outputFormat': 'json',
'timeout': 1000,
})
sentencePOS = nltk.pos_tag(nltk.word_tokenize(sentence))
done = False
# Attempt to find matching substrings
searchstring = ' '.join(target)
if searchstring in sentence.lower():
# startidx = sentence.lower().index(target[0])
# endidx = sentence.lower().index(target[-1])
answer.append(sentence)
done = True
# Check if solution is found
if done:
continue
# Check by question type
# answer = ""
# for worddata in parse["sentences"][0]["words"]:
for worddata in parse["sentences"][0]["tokens"]:
# Mentioned in the question
# if worddata["word"] in searchwords:
# continue
if done == False:
if type == "PERSON":
if worddata["ner"] == "PERSON":
answer.append(sentence)
done = True
# elif done:
# break
# Check if solution is found
if done:
continue
if type == "PLACE":
if worddata["ner"] == "LOCATION":
answer.append(sentence)
done = True
# elif done:
# break
# Check if solution is found
if done:
continue
if type == "QUANTITY":
if worddata["ner"] == "NUMBER":
answer.append(sentence)
done = True
# elif done:
# break
# Check if solution is found
if done:
continue
if type == "TIME":
if worddata["ner"] == "NUMBER":
answer.append(sentence)
done = True
# elif done:
# answer = sentence
# break
if done:
# print(answer)
return jsonify({'matched phrases':answer})
if not done:
(answer, matches) = dict.most_common(1)[0]
return jsonify({'note': "couldn't find exact matches", 'some close matches':answer})
if __name__ == '__main__':
# app.debug = True
app.run()
# In[ ]: