-
Notifications
You must be signed in to change notification settings - Fork 1
/
webhook.py
204 lines (169 loc) · 7.89 KB
/
webhook.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
import os
import re
from google.cloud import dialogflow_v2beta1 as dialogflow
from google.protobuf.json_format import MessageToDict
from KnowledgeBase import create_knowledge_base, HEADER_LIST
from chatbot import search_knowledge_base_by_intent, add_disliked_item
from common_functions import *
from IntentParsing import *
from flask import Flask, request
app = Flask(__name__)
filename = None
country = None
current_kbid = None
current_kbid_doc_mapping = None
is_first_request = True
flag = False
last_country = None
session = None
user_dict = {"name": "", "countries": [], "interests": {}, "dislikes": []}
@app.route('/webhook', methods=["POST"])
def webhook():
response = {'fulfillmentText': ""}
global filename
global country
global current_kbid
global current_kbid_doc_mapping
global user_dict
global is_first_request
global flag
global last_country
global session
global session_id
# get request
payload = request.json
# set up session
session_client = dialogflow.SessionsClient()
user_input = payload["queryResult"]["queryText"]
parameters_dict = payload["queryResult"]['parameters']
fulfill = ''
is_existing_country_intent = False
# person detected
if 'person' in parameters_dict and 'name' in parameters_dict['person']:
user_name = parameters_dict['person']['name']
print("Log - Detected name: " + user_name)
filename = f"{user_name}.json"
if not os.path.exists(filename):
user_dict["name"] = user_name
save_user_data(filename, user_dict)
response["fulfillmentText"] = f"Nice to meet you {user_name}, what country are you interested in visiting?"
else:
user_dict = load_user_data(filename)
# user has previous countries in their JSON
if len(user_dict["countries"]) > 0:
last_country = user_dict["countries"][-1]
response["fulfillmentText"] = f"Welcome back {user_name}, let's continue researching your trip to {last_country}!"
is_existing_country_intent = True
session = session_client.session_path(PROJECT_ID, user_name)
# avoid showing the response from this extra request to the user
parameters_dict['geo-country'] = last_country
# existing user has never indicated interest in a country
else:
response["fulfillmentText"] = f"Welcome back {user_name}, please let me know the name of a country you are interested in."
session = session_client.session_path(PROJECT_ID, user_name)
# only update user info at start of conversation
is_first_request = False
# new country detected, so you should switch context
if 'geo-country' in parameters_dict and parameters_dict['geo-country'] != '':
country = parameters_dict['geo-country']
print("LOG - Detected country: " + country)
if country in CURRENT_COUNTRIES:
current_kbid = get_kb_name_of_country(country)
print("KBID Detected: " + current_kbid)
else:
# build a knowledge base for that country if it does not already exist
current_kbid = create_knowledge_base(country)
print("KBID Created: " + current_kbid)
CURRENT_COUNTRIES.append(country)
response["fulfillmentText"] += "Warning: populating the knowledge base may take a few minutes"
current_kbid_doc_mapping = map_doc_name_to_id(current_kbid)
if country in user_dict["countries"]:
user_dict["countries"].remove(country)
user_dict["countries"].append(country)
if filename:
save_user_data(filename, user_dict)
# extract what information the user would like to know
query_result = payload["queryResult"]
if "fulfillmentText" in query_result:
fulfill = query_result["fulfillmentText"]
if 'intent' in payload["queryResult"]:
print("DEBUG LOG - IN INTENT")
intent_name = query_result['intent']['displayName']
print("LOG - Detected user intent: " + intent_name)
# dislike
if intent_name == "Dislike":
add_disliked_item(parameters_dict['Disliked'], user_dict)
response["fulfillmentText"] = fulfill
return response
# close
elif intent_name == "Close":
response["fulfillmentText"] = fulfill
return response
elif is_existing_country_intent:
return response
elif intent_name == "Welcome Intent":
response["fulfillmentText"] = "What country are you interested in visiting?"
return response
# default
elif intent_name == "Default Fallback":
print("EXPERIMENTAL DEFAULT FALLBACK")
response2 = make_dialogflow_request(session, session_client, user_input, current_kbid)
answers = response2.query_result.knowledge_answers.answers
if len(answers) > 0:
answer = answers[0].answer
x = 0
found_result = False
while x < len(nltk.sent_tokenize(answer)) and not found_result:
sentence = nltk.sent_tokenize(answer)[x]
has_word_in_common = False
for word in nltk.word_tokenize(user_input):
if len(word) > 4 and sentence.lower().find(word.lower()) != -1:
has_word_in_common = True
if len(sentence.split()) < 100 and has_word_in_common:
response["fulfillmentText"] = f"Here's what I found about that on the web: {sentence}"
return response
x += 1
response["fulfillmentText"] = f"Sorry, can you rephrase your question?"
return response
else:
response["fulfillmentText"] = f"Sorry, I didn't get that."
return response
# other
else:
# check if we should reference the knowledge base of a certain header
if intent_name in HEADER_LIST and country:
if "fulfillmentText" in query_result:
fulfill = query_result["fulfillmentText"]
else:
fulfill = ""
if intent_name in user_dict["interests"]:
user_dict["interests"][intent_name] += 1
else:
user_dict["interests"][intent_name] = 1
if filename:
save_user_data(filename, user_dict)
print("DEBUG LOG - HERE 1")
current_kbid_doc_mapping = map_doc_name_to_id(current_kbid)
kb_response = search_knowledge_base_by_intent(session, session_client, user_input, current_kbid,
intent_name, current_kbid_doc_mapping)
if kb_response is None:
print("DEBUG LOG - HERE 2")
kb_response = ''
content = kb_intent_response(kb_response, intent_name, country, user_dict, current_kbid_doc_mapping)
if content is None:
content = " "
response["fulfillmentText"] = f"{fulfill} {content}"
return response
else:
print("DEBUG LOG - HERE 3")
content = kb_intent_response(kb_response, intent_name, country, user_dict, current_kbid_doc_mapping)
response["fulfillmentText"] = f"{fulfill} {content}"
return response
else:
response["fulfillmentText"] = fulfill
return response
else:
response["fulfillmentText"] = fulfill
return response
if __name__ == '__main__':
app.run(port=5002)