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
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """Deployment.ipynb
3
+
4
+ Automatically generated by Colaboratory.
5
+
6
+ Original file is located at
7
+ https://colab.research.google.com/drive/1RtXMnveLECPLSum0IJcSGtQTk1pGRjNE
8
+
9
+ # Proof of Concept:
10
+
11
+ Breakdown:
12
+
13
+ 1. One must first load the dataset that our group created on Mockaroo based on the guidelines given to us by the client. This dataset models a food delivery business that has 4 tables: Driver, Customer, Orders and Customer support. Each table has various types of data spanning from strings, ints to unique ids. Tables are linked by ids as well.
14
+
15
+ 2. Using the textblob library, we run spell checking on the user input in order to avoid any query generation issues due to misspelt words.
16
+
17
+ 3. We use spacy in order to run named entity recognition; these entities will be used in step 4.
18
+
19
+ 4. Using the named entities and a list of unique values from the dataset, we use tensorflow embeddings and cosine similarity to find the column value most likely being referenced in the user's query. For instance, an input of San Francisco Jail would have a strong cosine similarity with the actual value from the client's column: San Francisco Penitentiary. After the correct name has been found we use regex to substitute the corrected name in place of the user input.
20
+
21
+ 5. Finally, we do the actual query translation from plain text. We first input the formatted query and send it to openai that has already been fed the schema for the query. We then receive the SQL query and call our own hand-crafted SQL-to-MongoDB method that converts into a final MongoDB query.
22
+
23
+ ### User Instructions
24
+
25
+ For the code to function, you need to load the four datasets (driver_data, cust_data, order_data, cust_service_data) from the github repo into your google drive as outlined in the following cells.
26
+
27
+ Our main method first asks the user for their openai key. Then we have some test cases that may contain noun spelling issues, name spelling issues, etc.
28
+ """
29
+
30
+ pip install openai
31
+
32
+ pip install gradio
33
+
34
+ #imports
35
+ import pandas as pd
36
+ from google.colab import drive
37
+ from textblob import TextBlob
38
+ import spacy
39
+ import tensorflow_hub as hub
40
+ from scipy.spatial import distance
41
+ from numpy.core.fromnumeric import argmax
42
+ import os
43
+ import openai
44
+ import re
45
+ import gradio as gr
46
+
47
+ """# Loading Mockaroo dataset from drive"""
48
+
49
+ drive.mount('/content/drive')
50
+
51
+ """### **Attention**: Upload all four datasets into your MyDrive directory in google drive"""
52
+
53
+ driver = pd.read_csv('/content/drive/MyDrive/driver_data.csv')
54
+ customer = pd.read_csv('/content/drive/MyDrive/customer_data.csv')
55
+ order = pd.read_csv('/content/drive/MyDrive/order_data.csv')
56
+ service = pd.read_csv('/content/drive/MyDrive/cust_service_data.csv')
57
+
58
+ """# Spelling correction"""
59
+
60
+ def correctSpelling(sentence):
61
+ return str(TextBlob(sentence).correct())
62
+
63
+ """# Entity Extraction"""
64
+
65
+ # extract entities, label, label definition from natural language questions and append to dataframe
66
+ nlp = spacy.load("en_core_web_sm")
67
+ def EntityExtraction(text:str):
68
+ # print(text)
69
+ entities = []
70
+ entities_label = []
71
+ label_explanation = {}
72
+ doc = nlp(text)
73
+ for entity in doc.ents:
74
+ entities.append(entity.text)
75
+ entities_label.append(entity.label_)
76
+ label_explanation[entity.label_] = spacy.explain(entity.label_)
77
+ return entities, entities_label
78
+
79
+ """# Column Cosine Similarity"""
80
+
81
+ #creating a dictionary of unique values in the dataset
82
+ #Used for cosine similarity
83
+ unique_values = {}
84
+
85
+ for column in driver:
86
+ unique_values[column] = driver[column].unique()
87
+
88
+ for column in customer:
89
+ unique_values[column] = customer[column].unique()
90
+
91
+ for column in order:
92
+ if column in ['cust_id', 'driver_id']:
93
+ unique_values[column] = order[column].unique()
94
+
95
+ unique_values['sales_id'] = service['sales_id'].unique()
96
+
97
+ embed = hub.load("https://tfhub.dev/google/universal-sentence-encoder/4")
98
+
99
+ # Uses TF word embeddings to find the word/phrase in words[1:] most related
100
+ # to words[0]
101
+ def ClosestSimilarity(words):
102
+ embeddings = embed(words)
103
+
104
+ similarities = [1 - distance.cosine(embeddings[0],x) for x in embeddings[1:]]
105
+
106
+ return max(similarities), argmax(similarities)
107
+
108
+ def find_column(item, array = unique_values):
109
+
110
+ best_similarity = 0
111
+ best_item = None
112
+ best_key = None
113
+
114
+ for key in array:
115
+ values = [str(x) for x in unique_values[key]]
116
+ values = [item] + values
117
+ max_similarity, item_similar = ClosestSimilarity(values)
118
+ if not best_similarity or max_similarity > best_similarity:
119
+
120
+ best_similarity = max_similarity
121
+ best_item = unique_values[key][item_similar]
122
+ best_key = key
123
+
124
+ if best_similarity < 0.2:
125
+
126
+ return best_key, item
127
+ return best_key, best_item
128
+
129
+ """# Query to SQL to MongoDB"""
130
+
131
+ def query_to_SQL_to_MongoDB(query, key, organization):
132
+
133
+
134
+ openai.api_key = key # put in the unique key
135
+ openai.organization = organization # sets the specific parameters of the openai var
136
+
137
+ response = openai.Completion.create( # use the appropriate SQL model and set the parameters accordingly
138
+ model="text-davinci-003",
139
+ prompt="### Postgres SQL tables, with their properties:\n#\n# Customer_Support(sales_id, order_id, date)\n# Driver(driver_id, driver_name, driver_address, driver_experience)\n# Customer(cust_id, cust_name, cust_address)\n# Orders(order_id, cust_id, driver_id, date, amount)\n#\n### A query to " + query + ".\nSELECT",
140
+ temperature=0,
141
+ max_tokens=150,
142
+ top_p=1.0,
143
+ frequency_penalty=0.0,
144
+ presence_penalty=0.0,
145
+ stop=["#", ";"]
146
+ )
147
+
148
+ SQL = response['choices'][0]['text'] # extract the outputted SQL Query
149
+ return complex_SQL_to_MongoDB(SQL)
150
+
151
+ #Example:
152
+
153
+ '''
154
+ db.Customer.aggregate(
155
+
156
+ {
157
+
158
+ $lookup:
159
+
160
+ {
161
+
162
+ from: "Orders",
163
+ localField: "cust_id",
164
+ foreignField: "cust_id",
165
+ as: "Customer"
166
+
167
+ }
168
+
169
+ },
170
+
171
+ {
172
+
173
+ $group:
174
+
175
+ {
176
+
177
+ _id: "cust_name",
178
+ count: {$count : {}}
179
+
180
+ }
181
+
182
+ },
183
+
184
+ {
185
+
186
+ $sort:{count : -1}
187
+
188
+ },
189
+
190
+ {
191
+
192
+ $limit: 1
193
+
194
+ }
195
+
196
+ )
197
+
198
+
199
+ '''
200
+
201
+ '''
202
+ db.Customer.aggregate(
203
+ {
204
+ $lookup:
205
+ {
206
+ from : "Orders",
207
+ localField: "cust_id",
208
+ foreignField: "cust_id",
209
+ as: "Customer"
210
+
211
+ }
212
+ },
213
+ {
214
+ $lookup:
215
+ {
216
+ from : "Driver",
217
+ localField: "driver_id",
218
+ foreignField: "driver_id",
219
+ as: "Customer"
220
+ }
221
+ },
222
+
223
+ {
224
+ $match:
225
+ {
226
+
227
+ $group:
228
+ {
229
+ _id: "c.cust_name",
230
+ count: {$count: {order_id}
231
+ }
232
+ }
233
+
234
+ },
235
+ {
236
+ $sort: {count : -1}
237
+ },
238
+ { $limit : 1 }
239
+
240
+ )
241
+ '''
242
+
243
+ keywords = {'INNER', 'FROM', 'WHERE', 'GROUP', 'BY', 'ON', 'SELECT', 'BETWEEN', 'LIMIT', 'AND', 'ORDER'}
244
+
245
+ mapper = {} # maps SQL symbols to MongoDB functions
246
+
247
+ mapper['<'] = '$lt'
248
+ mapper['>'] = '$gt'
249
+ mapper['!='] = '$ne'
250
+
251
+ def complex_SQL_to_MongoDB(query):
252
+
253
+ query = re.split(r' |\n', query) # split the query on spaces and turn in to array
254
+ query = [ x for x in query if len(x) > 0]
255
+
256
+ if len(query[0]) > 3 and (query[0][:3] == 'MAX' or query[0][:3] == 'MIN'):
257
+
258
+ query += ['ORDER', 'BY', query[0][4:-1], 'DESC' if query[0][:3] == 'MAX' else 'ASC', 'LIMIT', '1']
259
+
260
+ count_str = ''
261
+
262
+ if len(query[0]) > 5 and query[0][:5] == 'COUNT':
263
+
264
+ count_str += ' {$count : '
265
+ if query[0][6] == '*':
266
+
267
+ count_str += '{} }'
268
+
269
+ else:
270
+
271
+ count_str += query[0][6:-1] + ' }'
272
+
273
+ print(query)
274
+ fields = ''
275
+ i = 0
276
+ while query[i] != 'FROM':
277
+
278
+ fields += ' ' + query[i] + ' : 1,'
279
+ i += 1
280
+
281
+ fields = fields[:-1]
282
+ i = i +1
283
+ collection = query[i]
284
+ i = i + 1
285
+ if i < len(query) and query[i] not in keywords:
286
+
287
+ i += 1
288
+ answer = 'db.' + collection + ".aggregate( " # MongoDB function for aggregation
289
+
290
+ while i < len(query) and query[i] == 'INNER':
291
+
292
+ i = i + 2
293
+ lookup = '{$lookup: { from : "'
294
+ lookup += query[i] + '", localField: "'
295
+ if query[i+1] not in keywords:
296
+ i += 1
297
+ i = i + 2
298
+ lookup += query[i].split('.')[1] + '", foreignField: "'
299
+ i = i+2
300
+ lookup += query[i].split('.')[1] + '", as: "' + collection + '"} },'
301
+ i = i + 1
302
+ answer += lookup
303
+
304
+
305
+ if i < len(query) and query[i] == 'WHERE':
306
+
307
+ where = '{$match:'
308
+ count = 0
309
+
310
+ while i < len(query) and (query[i] == 'WHERE' or query[i] == 'AND'):
311
+
312
+ count += 1
313
+ i = i+1
314
+ conditions = ''
315
+ print(query[i])
316
+ conditions = '{' + (query[i].split('.')[1] if len(query[i].split('.')) > 1 else query[i] ) + " : "
317
+ if query[i+1] == '=':
318
+
319
+ conditions += query[i+2]
320
+ i = i + 3
321
+
322
+ elif query[i+1] == 'BETWEEN':
323
+
324
+ conditions += '{$gt: ISODate(' + query[i+2] + '), $lt: ISODate(' + query[i+4] + ')}'
325
+ i+= 5
326
+
327
+ else:
328
+
329
+ conditions += '{ ' + mapper[query[i+1]] + ' : ' + query[i+2] + ' }'
330
+ i = i+3
331
+
332
+ conditions += '},'
333
+
334
+ if count > 1:
335
+
336
+ where += '{ $and: [' + conditions[:-1] + ']}}'
337
+
338
+ else:
339
+
340
+ where += conditions[:-1] + '}, '
341
+
342
+ answer += where
343
+
344
+
345
+ if i < len(query) and (query[i] == 'GROUP' or query[i] == 'ORDER'):
346
+
347
+ i = i + 2
348
+ group = '{$group: { _id: "' + query[i] + '"'
349
+ i += 1
350
+ i -= 3 if query[i -3 ] == 'ORDER' else 0
351
+ if query[i] == 'ORDER' and len(query[i+2]) > 5 and query[i+2][0:5] == 'COUNT':
352
+
353
+ group += ', count: {$count: ' + ('{}' if query[i+2].split('(')[1][:-1] == '*' else ('{' + query[i+2].split('(')[1][:-1].split('.')[1] + '}') ) + '} }}, { $sort: {count : ' + ('1' if query[i+3] == 'ASC' else '-1') + '}}, '
354
+
355
+ else:
356
+
357
+ group += '} }, { $sort: {' + query[i+2] + ' : ' + ('1' if query[i+3] == 'ASC' else '-1') + '}},'
358
+
359
+ i += 4
360
+
361
+ answer += group
362
+
363
+ if i < len(query) and query[i] == 'LIMIT':
364
+
365
+ answer += '{ $limit : ' + query[i+1] + ' }, '
366
+
367
+ answer += count_str
368
+ answer += ')'
369
+
370
+ return answer
371
+
372
+
373
+ def simple_SQL_to_MongoDB(query): #ignore function as it is replaced by new complex version
374
+
375
+ query = query.split(' ') # split the query on spaces and turn in to array
376
+ query = query[1:] # remove the initial space
377
+ answer = 'db.collection.find' # MongoDB function for selection
378
+ fields = ''
379
+ i = 0
380
+ while query[i] != 'FROM':
381
+
382
+ fields += ' ' + query[i] + ' : 1,'
383
+ i += 1
384
+
385
+ fields = fields[:-1]
386
+ while query[i] != 'WHERE':
387
+
388
+ i += 1
389
+
390
+ i += 1
391
+ conditions = ''
392
+ while i+2 < len(query):
393
+
394
+ print(i)
395
+
396
+ conditions += ' ' + query[i] + ' : '
397
+ if query[i+1] == '=':
398
+
399
+ conditions += query[i+2]
400
+
401
+ elif query[i+1] == 'BETWEEN':
402
+
403
+ conditions += '{$gt: ISODate(' + query[i+2] + '), $lt: ISODate(' + query[i+4] + ')}'
404
+ i+= 6
405
+ conditions += ','
406
+ continue
407
+
408
+ else:
409
+
410
+ conditions += '{ ' + mapper[query[i+1]] + ' : ' + query[i+2] + ' }'
411
+
412
+ conditions += ','
413
+
414
+ i+= 4
415
+
416
+
417
+
418
+
419
+
420
+ conditions = conditions[:-1]
421
+
422
+
423
+ answer += '({' + conditions + '}, {' + fields + '})'
424
+
425
+ return answer
426
+
427
+ """# Main method"""
428
+
429
+ def query_creator(key, organization, plain_query):
430
+ # find named entities in text, e.g. names, addresses, etc.
431
+ plain_query = correctSpelling(plain_query)
432
+ entities, entities_label = EntityExtraction(plain_query)
433
+ modified_query = plain_query
434
+
435
+ #print(entities)
436
+ #print(entities_label)
437
+ #For each named entity in the query
438
+ for i in range(len(entities)):
439
+
440
+ if entities_label[i] in ['ORDINAL', 'CARDINAL']:
441
+ continue
442
+ #Use cosine similarity on each entity to find closest matching string from tables.
443
+ col, best_match = find_column(entities[i])
444
+ #substitute table string in place of partial match found in previous step
445
+ modified_query = re.sub(entities[i],best_match,modified_query)
446
+
447
+ print("Modified input: ", modified_query)
448
+ #Convert adjusted plain text query to SQL, then MongoDB
449
+ MongoDB_query = query_to_SQL_to_MongoDB(modified_query, key, organization)
450
+ return MongoDB_query
451
+
452
+ """#Testers of query creator"""
453
+
454
+ tests = ["giv me number of orders from the driver elizbeth", "name of driver with maximum ordres", "first two orders with the highest order amount", "address of customer with lowest ordr amount",\
455
+ "id of customer with most complints", "date of customer support with sales id 21695-828", "number of drivers with order amount 20", "numbser of orders by customer martha", "order amount of most recent customer support",\
456
+ "amount of the highest order by customber Federica"]
457
+
458
+ #for test in tests:
459
+
460
+ # print(query_creator(api_key, org_key, test)) # put in your api and org keys to use the tester
461
+
462
+ """# UI"""
463
+
464
+ iface = gr.Interface(fn=query_creator, inputs= [gr.Textbox(label = "API Key"), gr.Textbox(label = "Organization Key"), gr.Textbox(label = "Plain Text Query")], outputs=gr.Textbox(label = "MongoDB Query"), )
465
+ iface.launch(share = True, debug = True)
466
+