-
Notifications
You must be signed in to change notification settings - Fork 1
/
parse_helper.py
executable file
·375 lines (297 loc) · 11.7 KB
/
parse_helper.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
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
#!flask/bin/python
import re, json
from flask import jsonify
import nltk
from nltk.stem.snowball import SnowballStemmer
from nltk.corpus import stopwords
from persistent_helpers import get_recipe_info
stemmer = SnowballStemmer("english")
stop = stopwords.words('english')
def route_command(text, recipe_id):
"""Decide if command is:
a. Generic:
- what is step <X>?
- how much of <X> is required?
b. Hardware related
- what's the temperature of the oven?
- is the oven ready?
Route command accordingly
@type recipe_id: number
@type text: Request as String
@return: Respose as String
"""
text = text.lower()
recipe_id = int(recipe_id)
tokens = map(lambda x: x.strip(), text.split())
tokens = set(tokens)
hardware_kw = set(['temperature', 'oven', 'owen'])
if len(tokens & hardware_kw) > 0:
response = exec_hardware_command(text)
else:
response = exec_generic_command(recipe_id, text)
if response is None:
# TODO Handle elegantly
return None
return response
def exec_generic_command(recipe_id, text):
"""Execute generic command:
A. what is step <X>?
B. how much of <X> is required?
C. where do i use <X>?
D. how many calories does this contain?
E. how long do i <X>?
@type recipe_id: number
@type text: Request as String
@return: Respose as String
"""
# Keywords for A
step_kw = ['step']
# Keywords for B
ing_qty_kw = ['how much', 'required', 'needed', 'need', 'how many']
# Keywords for C
step_use_kw = ['where', 'do i use']
# Keywords for D
cal_kw = ['calories']
# Keywords for E
duration_kw = ['how long do i']
# Check what kind of a question it is
step_match = sum([kw in text for kw in step_kw])
ing_quantity_match = sum([kw in text for kw in ing_qty_kw])
step_use_match = sum([kw in text for kw in step_use_kw])
cal_match = sum([kw in text for kw in cal_kw])
duration_match = sum([kw in text for kw in duration_kw])
if cal_match > 0:
return respond_to_cal(text, recipe_id)
elif duration_match > 0:
return respond_to_duration(text, recipe_id)
elif step_use_match > 0:
return respond_to_step_use(text, recipe_id)
elif step_match > 0 :
return respond_to_step(text, recipe_id)
elif ing_quantity_match > 0:
return respond_to_ing_qty(text, recipe_id)
else:
print 'All routes failed'
return None
def exec_hardware_command(text):
"""Execute hardware-related command
A. what is the temperature of the oven?
B. is the oven ready?
@type text: Request as String
@return: Respose as String
"""
# Keywords for A and B
temp_kw = ['temperature', ]
ready_kw = ['ready', ]
# Check what kind of a question it is
temp_match = sum([kw in text for kw in temp_kw])
ready_match = sum([kw in text for kw in ready_kw])
if temp_match == 0 and ready_kw == 0:
return None
elif temp_match > 0 :
return respond_to_step(text)
elif ing_quantity_match > 0:
return ready_match(text)
else:
return None
def respond_to_step(text, recipe_id):
"""Respond to:
'what is step <X>?'
"""
# Which step is required?
match = re.search('step[s]?\s+(number\s+)?(?P<step_num>\w+)', text)
step_str = match.group('step_num')
try:
step_num = int(step_str)
except ValueError:
step_num = text2int(step_str)
# What are the steps in the recipe?
recipe_info_str = json.loads(get_recipe_info(recipe_id))
recipe_info = recipe_info_str['response']
raw_instructions = recipe_info["Instructions"].replace('\r', '').replace('\n', '')
instructions = raw_instructions.split('. ')
num_instructions = len(instructions)
# Construct response
if step_num > num_instructions:
response = "Step %d does not exist. There are just %d steps." % (step_num, num_instructions)
else:
response = instructions[step_num-1]
return json.dumps({'response' : response})
def respond_to_ing_qty(text, recipe_id):
"""Respond to:
'how much <X> is required?'
"""
# What is the ingredient?
# Detect by simple pattern matching
match = re.search('how (much|many) (?P<ing>[\w -]+)', text)
query_ingredient = match.group('ing')
# What are the ingredients in this recipe?
recipe_info_str = json.loads(get_recipe_info(recipe_id))
recipe_info = recipe_info_str['response']
# List of 'ingredient' dicts
ingredients = recipe_info["Ingredients"]
# Create a dict {ingredient_name -> quantity}
ing_dct = {}
for ing in ingredients:
name = ing['Name'].lower()
quantity = ing['Quantity']
units = ing.get('Unit', '')
ing_dct[name] = (quantity, units)
# What's the quantity required?
# Clean up recipe tokens
# a. tokenize the ingredients
recipe_tokens = nltk.word_tokenize(query_ingredient)
# b. stem the tokens
recipe_tokens = set([stemmer.stem(token) for token in recipe_tokens])
candidates = []
for dct_ing in ing_dct:
query_tokens = nltk.word_tokenize(dct_ing)
query_tokens = set([stemmer.stem(token) for token in query_tokens])
num_matches = len(recipe_tokens & query_tokens)
if num_matches > 0:
candidates += [(dct_ing, num_matches)]
candidates = sorted(candidates, key=lambda x:-x[1])
if len(candidates) == 0:
response = "For this recipe %s is not necessary." % query_ingredient
#elif len(candidates) == 1:
else:
response = "You will need %s %s of %s." % (ing_dct[candidates[0][0]][0], ing_dct[candidates[0][0]][1], candidates[0][0])
#else:
# response = "Did you mean %s? %s %s required" % (candidates[0][0], ing_dct[candidates[0][0]][0], ing_dct[candidates[0][0]][1])
return json.dumps({'response' : response})
def respond_to_duration(text, recipe_id):
"""Respond to
how long do i <X>
<X> can be "bake the cake", or whatever
"""
# Detect <X> by simple pattern matching
match = re.search('how long do i (?P<action>[\w\s -]+)', text)
query_action = match.group('action')
# Get tokens
action_tokens = recipe_tokens = nltk.word_tokenize(query_action)
action_tokens = set([stemmer.stem(token) for token in action_tokens])
action_tokens = set([token for token in action_tokens if token not in stop])
# Iterate over steps, find relevant steps, add with a score
# What are the steps in the recipe?
recipe_info_str = json.loads(get_recipe_info(recipe_id))
recipe_info = recipe_info_str['response']
raw_instructions = recipe_info["Instructions"].replace('\r', '').replace('\n', '')
instructions = raw_instructions.split('.')
num_instructions = len(instructions)
# Compare each instruction with a 'duration' keyword
dur_kw = set(['minutes', 'minut', 'minute', 'mins', 'min',
'seconds', 'second', 'secs', 'sec'])
candidates = []
for idx, instruc in enumerate(instructions):
instruc_tokens = nltk.word_tokenize(instruc)
instruc_tokens = [stemmer.stem(token) for token in instruc_tokens]
instruc_tokens = set([token for token in instruc_tokens if token not in stop])
is_duration_instruc = len(instruc_tokens & dur_kw) > 0
if is_duration_instruc:
# Calculate score
num_matches = len(instruc_tokens & action_tokens)
candidates += [(instruc, num_matches), ]
candidates = sorted(candidates, key=lambda x: -x[1])
if len(candidates) == 0:
response = 'error'
else:
most_relev_instruc = candidates[0][0]
response = most_relev_instruc
return json.dumps({'response' : response})
def respond_to_step_use(text, recipe_id):
"""Respond to
where do i use <X>?
"""
# What is the ingredient?
# Detect by simple pattern matching
match = re.search('where do i use (?P<ing>[\w -]+)', text)
query_ingredient = match.group('ing')
# Clean up recipe tokens
# a. tokenize the ingredients
recipe_tokens = nltk.word_tokenize(query_ingredient)
# b. stem the tokens
recipe_tokens = set([stemmer.stem(token) for token in recipe_tokens])
# c. remove stop words
recipe_tokens = set([token for token in recipe_tokens if token not in stop])
# Iterate over steps, find relevant steps, add with a score
# What are the steps in the recipe?
recipe_info_str = json.loads(get_recipe_info(recipe_id))
recipe_info = recipe_info_str['response']
raw_instructions = recipe_info["Instructions"].replace('\r', '').replace('\n', '')
instructions = raw_instructions.split('. ')
num_instructions = len(instructions)
candidates = []
for idx, instruc in enumerate(instructions):
instruc_tokens = nltk.word_tokenize(instruc)
instruc_tokens = [stemmer.stem(token) for token in instruc_tokens]
instruc_tokens = set([token for token in instruc_tokens if token not in stop])
num_matches = len(instruc_tokens & recipe_tokens)
step_num = idx + 1
if num_matches > 0:
candidates += [(instruc, step_num, num_matches), ]
candidates = sorted(candidates, key=lambda x:x[1])
if len(candidates) == 0:
response = '%s not used in any step.' % query_ingredient
elif len(candidates) == 1:
instruc, step_num, num_matches = candidates[0]
response = "You'll need %s in step %d. %s" % (query_ingredient, step_num, instruc)
else:
# Get list of steps where its used
steps_used = [str(cand[1]) for cand in candidates]
response = 'In steps ' + ', '.join(steps_used) + ' . '
for instruc, step_num, num_matches in candidates:
response += 'In step %d. %s. ' % (step_num, instruc)
return json.dumps({'response' : response})
def respond_to_cal(text, recipe_id):
"""Respond to
how many calories does this contain
"""
# Get Recipe
recipe_info = json.loads(get_recipe_info(recipe_id))['response']
calories = recipe_info.get("Calories", None)
if calories is None:
response = "Sorry, I don't know many calories this dish contains."
else:
response = "This dish contains %s kilocalories. Yay." % calories
return json.dumps({'response' : response})
def respond_to_temp(text):
# What is the temperature?
# Construct response
pass
def respond_to_ready(text):
# What is the state?
# Construct response
pass
def text2int(textnum, numwords={}):
if not numwords:
units = [
"zero", "one", "two", "three", "four", "five", "six", "seven", "eight",
"nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen",
"sixteen", "seventeen", "eighteen", "nineteen",
]
tens = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"]
scales = ["hundred", "thousand", "million", "billion", "trillion"]
numwords["and"] = (1, 0)
for idx, word in enumerate(units): numwords[word] = (1, idx)
for idx, word in enumerate(tens): numwords[word] = (1, idx * 10)
for idx, word in enumerate(scales): numwords[word] = (10 ** (idx * 3 or 2), 0)
current = result = 0
for word in textnum.split():
if word not in numwords:
raise Exception("Illegal word: " + word)
scale, increment = numwords[word]
current = current * scale + increment
if scale > 100:
result += current
current = 0
return result + current
def main():
recipe_id = 466840
# text = "what is step two"
# print respond_to_ing_qty(text, recipe_id)
# text = "what is step three"
# text = "how long do i parboil the red potatoes"
text = "where do i use pepper"
print route_command(text, recipe_id)
if __name__ == '__main__':
main()