-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathnlp.py
64 lines (53 loc) · 1.74 KB
/
nlp.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
import re
import nltk
import string
from words import greeting_inputs, definition_inputs, vqa_filter
nltk.download("punkt")
nltk.download("wordnet")
class NLP:
def __init__(self):
self.wnlemmatizer = nltk.stem.WordNetLemmatizer()
self.punctuation_removal = dict(
(ord(punctuation), None) for punctuation in string.punctuation
)
def perform_lemmatization(self, tokens):
return [self.wnlemmatizer.lemmatize(token) for token in tokens]
def get_processed_text(self, document):
return self.perform_lemmatization(
nltk.word_tokenize(document.lower().translate(self.punctuation_removal))
)
def is_greeting(self, words, query):
if query in greeting_inputs:
return True
for word in words:
if word in greeting_inputs:
return True
return False
def is_definition(self, words, query):
for sep in definition_inputs:
if sep in query:
return query.split(sep)[1]
return None
def is_vqa_safe(self, words, query):
for word in words:
if word in vqa_filter:
return True
return False
def ask(self, query):
words = self.get_processed_text(query)
query = " ".join(words)
if self.is_greeting(words, query):
return {"type": "greeting"}
define = self.is_definition(words, query)
if define:
return {
"type": "wiki",
"data": "".join(self.get_processed_text(define)),
}
if self.is_vqa_safe(words, query):
return {
"type": "vqa",
}
return {
"type": "invalid",
}