-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
executable file
·332 lines (254 loc) · 10.4 KB
/
app.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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
#!/usr/bin/env python3
from flask import Flask
from flask import request, jsonify
from datetime import datetime
import pickle, copy, random
import argparse
from mashup import *
from ont2nl import *
from ont2confirm import *
import matplotlib.pyplot as plt
import networkx as nx
app = Flask(__name__)
mashups = []
graph_mashups = []
cursor = None
paused = False
# Count of added commands from last current mashup check
feedback_given = 0
last_length = 0
# Undo check
undo_used = False
@app.route('/', methods=['POST'])
def main():
global mashups
global graph_mashups
global cursor
global paused
global feedback_given
global last_length
global undo_used
data = request.get_json()
ret = {}
# check user intent
intent = data['queryResult']['intent']['displayName']
if intent == 'new_mashup':
if paused:
ret = {
"fulfillmentText": "It seems you haven't finished making a mashup, please resume it."
}
outputContexts = data['queryResult']['outputContexts']
# Reset contexts
for context in outputContexts:
context['lifespanCount'] = 0
ret['outputContexts'] = outputContexts
now = int(datetime.now().timestamp())
print('[INFO] New mashup session initiated at ' + str(now))
mashups.append([])
cursor = mashups[-1]
confirm_init()
feedback_given = 0
last_length = 0
undo_used = False
if intent == 'add_command':
now = int(datetime.now().timestamp())
print('[INFO] Command added at ' + str(now))
cursor.append(data['queryResult']['parameters'])
try:
m = Mashup()
m.init_list(copy.deepcopy(mashups[-1]))
feedback_given += m.graph.number_of_nodes() - last_length
last_length = m.graph.number_of_nodes()
ret['fulfillmentText'] = speak_add_command(m, False if feedback_given > 4 else True)
if feedback_given > 4:
now = int(datetime.now().timestamp())
print('[INFO] Feedback suggested at ' + str(now))
ret["outputContexts"] = [
{"name": "{}/contexts/add_command-followup".format(data['session']),
"lifespanCount": 2}
]
ret["fulfillmentText"] += "Great. Before moving on to the next step, would you like to check the current progress of your mashup?"
feedback_given = 0
except Exception as e:
print('[Error] Failed to instantiate the mashup - ' + str(e))
cursor.pop()
ret = {
"fulfillmentText": "Oops, I failed to process your input. Could you rephrase it?",
}
return jsonify(ret)
if intent == 'undo_command':
now = int(datetime.now().timestamp())
print('[INFO] Command undone at ' + str(now))
feedback_given += 1
last_length -= 1
try:
cursor.pop()
except IndexError as e:
print('[Error] Failed to pop a command - ' + str(e))
ret['fulfillmentText'] = 'Sorry, you cannot undo when you did not add any commands.'
return jsonify(ret)
if not undo_used:
undo_used = True
ret['fulfillmentText'] = 'Sure, the last command has been undone. Please tell me commands you want to add.'
else:
ret_str = [
'Removing the last action.',
'Undoing the last action.'
]
ret['fulfillmentText'] = random.choice(ret_str)
if intent == 'pause_add_command':
now = int(datetime.now().timestamp())
print('[INFO] Paused at ' + str(now) + ' - ' + str(cursor))
outputContexts = data['queryResult']['outputContexts']
for context in outputContexts:
context['lifespanCount'] = 0
ret['outputContexts'] = outputContexts
paused = True
if intent == 'resume_add_command':
now = int(datetime.now().timestamp())
print('[INFO] Resumed at ' + str(now) + ' - ' + str(cursor))
paused = False
if intent == 'finish_add_command':
# Check if the mashup is empty
if len(cursor) == 0:
ret = {
"fulfillmentText": "Umm... Nothing has been added.",
"payload": {
'google': {'expectUserResponse': False}
}
}
return jsonify(ret)
if feedback_given > 2:
now = int(datetime.now().timestamp())
print('[INFO] Feedback suggested at ' + str(now))
outputContexts = data['queryResult']['outputContexts']
for context in outputContexts:
if 'finish_add_command-followup' not in context['name']:
context['lifespanCount'] = 0
ret['outputContexts'] = outputContexts
ret["fulfillmentText"] = "Okay, it's almost ready. Before I deploy your mashup, do you want to check it out?"
return jsonify(ret)
else:
ret['payload'] = {
'google': {'expectUserResponse': False}
}
now = int(datetime.now().timestamp())
f = open('dump/multi-' + str(now) + '.bin', 'wb+')
pickle.dump(cursor, f)
print('[INFO] New mashup created at ' + str(now) + ' - ' + str(cursor))
f.close()
cursor = None
# Build a mashup from dump file
try:
m = Mashup()
m.init_list(copy.deepcopy(mashups[-1]))
nx.draw_networkx(m.graph)
plt.savefig('dump/multi-' + str(now) + '.png')
plt.close('all')
# If not redundant
graph_mashups.append(m)
except Exception as e:
print('[Error] Failed to instantiate the mashup - ' + str(e))
ret = {
"fulfillmentText": "Sorry, something strange has occurred while processing your input.",
"payload": {
'google': {'expectUserResponse': False}
}
}
return jsonify(ret)
# Resetting contexts
outputContexts = data['queryResult']['outputContexts']
for context in outputContexts:
context['lifespanCount'] = 0
ret['outputContexts'] = outputContexts
if intent == 'finish_add_command - no' or intent == 'finish_add_command - yes - yes':
now = int(datetime.now().timestamp())
f = open('dump/multi-' + str(now) + '.bin', 'wb+')
pickle.dump(cursor, f)
print('[INFO] New mashup created at ' + str(now) + ' - ' + str(cursor))
f.close()
cursor = None
# Build a mashup from dump file
try:
m = Mashup()
m.init_list(copy.deepcopy(mashups[-1]))
nx.draw_networkx(m.graph)
plt.savefig('dump/multi-' + str(now) + '.png')
plt.close('all')
graph_mashups.append(m)
except Exception as e:
print('[Error] Failed to instantiate the mashup - ' + str(e))
ret = {
"fulfillmentText": "Sorry, something strange has occurred while processing your input.",
"payload": {
'google': {'expectUserResponse': False}
}
}
return jsonify(ret)
# Resetting contexts
outputContexts = data['queryResult']['outputContexts']
for context in outputContexts:
context['lifespanCount'] = 0
ret['outputContexts'] = outputContexts
if intent == 'finish_add_command - yes':
now = int(datetime.now().timestamp())
print('[INFO] Final feedback is provided at ' + str(now))
f = open('dump/multi-' + str(now) + '-cur' + '.bin', 'wb+')
pickle.dump(cursor, f)
f.close()
# Build a mashup from dump file
try:
m = Mashup()
m.init_list(copy.deepcopy(cursor))
ret = {
"outputContexts": [
{"name": "{}/contexts/finish_add_command-yes-followup".format(data['session']),
"lifespanCount": 2}
],
}
fulfillmentText = speak_mashup(m) + 'Do you want to deploy your mashup?</speak>'
ret['fulfillmentText'] = fulfillmentText
feedback_given = 0
except:
print('[Error] Failed to instantiate the mashup - ' + str(e))
ret = {
"fulfillmentText": "Sorry. I got an error while checking the mashup command.",
"payload": {
'google': {'expectUserResponse': False}
}
}
return jsonify(ret)
if intent == 'current_mashup' or intent == 'add_command - yes':
now = int(datetime.now().timestamp())
print('[INFO] Current feedback is provided at ' + str(now))
now = int(datetime.now().timestamp())
f = open('dump/multi-' + str(now) + '-cur' + '.bin', 'wb+')
pickle.dump(cursor, f)
f.close()
# Build a mashup from dump file
try:
m = Mashup()
m.init_list(copy.deepcopy(cursor))
fulfillmentText = speak_mashup(m) + " Tell me if you have more to add, or just say I'm done.</speak>"
ret['fulfillmentText'] = fulfillmentText
feedback_given = 0
except Exception as e:
print('[Error] Failed to instantiate the mashup - ' + str(e))
ret = {
"fulfillmentText": "Sorry. I got an error while checking the mashup command.",
"payload": {
'google': {'expectUserResponse': False}
}
}
return jsonify(ret)
return jsonify(ret)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Chatbot server')
parser.add_argument('--protocol', default='https', help='protocol ("http" or "https")')
args = parser.parse_args()
if args.protocol == 'https':
app.run(host='0.0.0.0', port=443, ssl_context=('server.crt', 'server.key'))
elif args.protocol == 'http':
app.run(host='127.0.0.1', port=9000)
else:
raise RuntimeError("unexpected protocol {}".format(args.protocol))