-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutil.py
284 lines (263 loc) · 8.97 KB
/
util.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
import sqlite3
import hashlib
import oauth2
import argparse
import json
import urllib
import urllib2
import datetime
import operator
import random
#SQLITE STUFF
type_dist = {
"Chinese":[
"chinese", "hot pot", "shanghainese", "dim sum"
],
"Japanese":[
"sushi", "live/raw food", "teppanyaki", "japanese", "sushi bars"
],
"Diner":[
"sandwiches", "american", "diner", "deli", "hotdogs", "burgers", "southern", "breakfast", "fast food"
],
"Middle Eastern":[
"falafel", "egyptian", "afghan", "persian/iranian", "middle eastern"
],
"Indian":[
"bangladeshi", "pakistani", "indian"
],
"Steakhouse":[
"steakhouse"
],
"Buffet":[
"buffet"
],
"Vegan":[
"vegetarian", "vegan", "gluten free"
],
"Mexican":[
"mexican", "texmex"
],
"Pizza":[
"pizza","italian"
]
}
def create():
conn = sqlite3.connect("database.db")
c = conn.cursor()
createlogin = "CREATE TABLE IF NOT EXISTS login (username text, password text)"
c.execute(createlogin)
createinfo = "CREATE TABLE IF NOT EXISTS info (username text, restaurant text, location text, rating real, day text, category text)"
c.execute(createinfo)
conn.commit()
def newUser(username, password):
conn = sqlite3.connect("database.db")
c = conn.cursor()
c.execute("SELECT username FROM login WHERE username=:uname LIMIT 1", {"uname":username})
data = c.fetchone()
if data is None :
m = hashlib.sha224(password)
query = "INSERT INTO login VALUES (\"%(username)s\", \"%(password)s\")" % ({"username":username, "password":m.hexdigest()})
c.execute(query)
conn.commit()
return True
return False
def authenticate(username, password):
conn = sqlite3.connect("database.db")
c = conn.cursor()
m = hashlib.sha224(password).hexdigest()
query = "SELECT password FROM login WHERE username=\"%s\"" % (username)
c.execute(query)
userdata = c.fetchone()
if userdata == None:
return "Cannot find Username"
userdata = userdata[0]
if m == userdata:
userstore = username
return ""
return "Incorrect Password"
def setrating(uname, rating, location, restaurant, category):
conn = sqlite3.connect("database.db")
c = conn.cursor()
query = "INSERT INTO info VALUES (\"%(username)s\", \"%(restaurant)s\", \"%(location)s\", \"%(rating)f\", \"%(day)s\", \"%(category)s\")"%({
"username":uname,"restaurant":restaurant,"location":location, "rating":rating,"day":datetime.date.today(), "category":category})
c.execute(query)
conn.commit()
def getrating(location):
conn = sqlite3.connect("database.db")
c = conn.cursor()
query = "SELECT rating FROM info WHERE location=:loc"
data = c.execute(query, { "loc":location}).fetchall()
data = [f[0] for f in data]
conn.commit()
return data
def getUserCategories(uname):
conn = sqlite3.connect("database.db")
c = conn.cursor()
query = "SELECT category FROM info WHERE username=:uname"
data = c.execute(query, {"uname":uname}).fetchall()
cats = {}
for d in [d[0] for d in data]:
cats[d] += 1
conn.commit()
return data
#def record_restaurant():
#API STUFF
YELP_HOST = 'api.yelp.com'
DEFAULT_TERM = 'dinner'
DEFAULT_LOCATION = 'San Francisco, CA'
SEARCH_LIMIT = 3
YELP_SEARCH_PATH = '/v2/search/'
#BUSINESS_PATH = '/v2/business/'
# OAuth credential placeholders that must be filled in by users.
CONSUMER_KEY = "LsCXQQuggKugyyJCt4DkDw"
CONSUMER_SECRET = "TG8tyKlYvMTG3zSfn-YBNCOuuSk"
TOKEN = "B2wxvqBxgXYZ8tZWMBn4QU5Sm01MVeUN"
TOKEN_SECRET = "RL8NahsPX5xNXCE3aHM-y9iqYj4"
def request(url_params=None,host=YELP_HOST, path=YELP_SEARCH_PATH):
"""Prepares OAuth authentication and sends the request to the API.
Args:
host (str): The domain host of the API.
path (str): The path of the API after the domain.
url_params (dict): An optional set of query parameters in the request.
Returns:
dict: The JSON response from the request.
Raises:
urllib2.HTTPError: An error occurs from the HTTP request.
"""
# if api == "google":
# CONSUMER_KEY = ""
# CONSUMER_SECRET ="NYHPtFCnNVhup9oVo9nDki9a"
url_params = url_params or {}
url = 'https://{0}{1}?'.format(host, urllib.quote(path.encode('utf8')))
consumer = oauth2.Consumer(CONSUMER_KEY, CONSUMER_SECRET)
oauth_request = oauth2.Request(method="GET", url=url, parameters=url_params)
oauth_request.update(
{
'oauth_nonce': oauth2.generate_nonce(),
'oauth_timestamp': oauth2.generate_timestamp(),
'oauth_token': TOKEN,
'oauth_consumer_key': CONSUMER_KEY
}
)
token = oauth2.Token(TOKEN, TOKEN_SECRET)
oauth_request.sign_request(oauth2.SignatureMethod_HMAC_SHA1(), consumer, token)
signed_url = oauth_request.to_url()
print u'Querying {0} ...'.format(url)
conn = urllib2.urlopen(signed_url, None)
try:
response = json.loads(conn.read())
finally:
conn.close()
return response
def getTypes(addr,rad=8000):
url_params = {
'term':'restaurants',
'location':addr.replace(' ','+'),
'radius':rad
}
raw = request(url_params)
types = []
for business in raw['businesses']:
for category in business['categories']:
added = 0
for dist in type_dist:
if category[0].lower() in type_dist[dist]:
if dist not in types:
types += [dist]
added = 1
if category[0] not in types and added != 1:
types += [category[0]]
return types
def filter(addr, rad=8000, types=[] , rating=0):
addr = addr.strip()
url_params = {
'term':'restaurants',
'location':addr.replace(' ','+'),
'radius':rad
}
raw = request(url_params)
restaurants = []
for business in raw['businesses']:
categories = []
for category in business['categories']:
added = 0
for dist in type_dist:
if category[0].lower() in type_dist[dist]:
if dist not in categories:
categories += [dist]
added = 1
if category[0] not in categories and added != 1:
categories += [category[0]]
if 'distance' in business:
restaurants += [{
'name':business['name'],
'location':business['location']['display_address'],
'category':categories,
'rating':business['rating'],
'distance':str(int((business['distance'] / 1609) * 100) / 100.) + 'mi',
'link':business['url']
}]
else:
restaurants += [{
'name':business['name'],
'location':business['location']['display_address'],
'category':categories,
'rating':business['rating'],
#'distance':str(int((business['distance'] / 1609) * 100) / 100.) + 'mi',
'link':business['url']
}]
final =[]
for restaurant in restaurants:
b = False
if float(restaurant['rating']) < float(rating):
b = True
else:
#restaurant['category'] = [c[0] for c in restaurant['category']]
for category in restaurant['category']:
category = category.strip()
if category in types:
b = True
break
if not b:
final += [restaurant]
return final
# def suggest(uname, restaurants):
# conn = sqlite3.connect("database.db")
# c = conn.cursor()
# query = "SELECT category FROM info WHERE username=:uname"
# data = c.execute(query, {"uname":uname}).fetchall()
# cats = {}
# for d in [d[0] for d in data]:
# for s in d.split(','):
# if s not in cats:
# cats[s] = 1
# else:
# cats[s] += 1
# fav = "helpme"
# most_visit = -1
# for k,v in cats.iteritems():
# if v > most_visit:
# fav = k
# a = random.randrange(99)
# choices = []
# if fav == "helpme":
# choices = [f['name'] for f in restaurants]
# return choices[random.randrange(len(choices))]
# elif a >= 0 and a < 30:
# for restaurant in restaurants:
# for c in restaurant["category"]:
# if c == fav:
# choices += [restaurant["name"]]
# break
# return choices[random.randrange(len(choices))]
# elif a >= 30 and a < 85:
# for restaurant in restaurants:
# for c in restaurant["category"]:
# if c != fav:
# choices += [restaurant["name"]]
# break
# return choices[random.randrange(len(choices))]
# else:
# for restaurant in restaurants:
# choices += [restaurant["name"]]
# return choices[random.randrange(len(choices))]