-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathFantail.py
386 lines (340 loc) · 12.9 KB
/
Fantail.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
376
377
378
379
380
381
382
383
384
385
386
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import googlemaps
import json
import argparse
import sys
import pyodbc
import time
import datetime
import colorama
colorama.init()
import decimal
decimal.getcontext().prec = 4
# Here we organize the choices command line aruments
parser = argparse.ArgumentParser()
parser.add_argument('--country', dest='country', type=str, help="Input a country code (like \"US\" or \"FR\" or \"NZ\"), or \"ALL\" for all countries", metavar='') # Option: --country
parser.add_argument('--city', dest='city', type=str, help= "Enter a city name (like \"New York\" or \"Paris\" or \"Auckland\")", metavar='') # Option: --city
parser.add_argument('--category', dest='category', default='movie_theater', type=str, help="Enter a business category", metavar='') # Option: --category
parser.add_argument('--radius', dest='radius', default='10000', type=int, help="Enter a radius between 0 and 50000 (default is 10000)", metavar='') # Option: --radius
parser.add_argument('--verbose', dest='verbose',help='Print more data',action='store_true') # Option: --verbose
parser.add_argument('--rownumber', dest='rownumber', type=int, help="Input a specific row number", metavar='') # Option: --rownumber
args = parser.parse_args()
# If user directory nothing print help
#if len(sys.argv) < 2:
# parser.print_help()
# sys.exit(1)
# Argparse ends here
# Terminal color definitions
class fg:
BLACK = '\033[30m'
RED = '\033[31m'
GREEN = '\033[32m'
YELLOW = '\033[33m'
BLUE = '\033[34m'
MAGENTA = '\033[35m'
CYAN = '\033[36m'
WHITE = '\033[37m'
RESET = '\033[39m'
class bg:
BLACK = '\033[40m'
RED = '\033[41m'
GREEN = '\033[42m'
YELLOW = '\033[43m'
BLUE = '\033[44m'
MAGENTA = '\033[45m'
CYAN = '\033[46m'
WHITE = '\033[47m'
RESET = '\033[49m'
class style:
BRIGHT = '\033[1m'
DIM = '\033[2m'
NORMAL = '\033[22m'
RESET_ALL = '\033[0m'
#############################################################################
# Enter here your Google Places API key #
gmaps = googlemaps.Client(key='MyBeautifulAPIKey') #
#
# Enter here your database credentials #
Connection_Details = ('DRIVER={SQL Server};' #
'SERVER=ASPIRES3;' #
'DATABASE=ip2location;' #
'UID=sqlninja;' #
'PWD=sqlninja') #
#############################################################################
long_field = {}
short_field = {}
element_count = 0
element_saved = 0
Total_cost = decimal.Decimal(0.000)
def Search_URL(countdown_order,latitude, longitude,city_name,region_name,country_code):
global search_location
global params
global Total_cost
params = {'location': '%s,%s' % (latitude,longitude),
'radius': '%s' % (args.radius),
'type': '%s' % (args.category)
}
search_location = gmaps.places_nearby(**params)
Total_cost += decimal.Decimal(0.032)
if search_location['status'] == 'OK': # Check if the API is 'OK'
nearby_search(search_location)
elif search_location['status'] == 'ZERO_RESULTS':
pass
#print_totals(countdown_order,city_name,region_name,country_code)
else:
print ('API query returned:',search_location)
def nearby_search(search_location):
global element_count
global Place_ID
global ID
global Name
global Latitude
global Longitude
global Rating
global Types
global Vicinity
global Total_cost
for element in search_location['results']:
Place_ID = element.get('place_id',None)
ID = element.get('id',None)
Name = element.get('name',None)
Latitude = element['geometry']['location'].get('lat',None)
Longitude = element['geometry']['location'].get('lng',None)
Rating = element.get('rating',None)
Types = json.dumps(element.get('types',None)) # Genius!
Vicinity = element.get('vicinity',None)
if 'next_page_token' in search_location.keys():
time.sleep(5)
params.update({"page_token": search_location['next_page_token']})
search_location = gmaps.places_nearby(**params)
Total_cost += decimal.Decimal(0.032)
nearby_search(search_location)
Search_if_Place_ID_exists(Place_ID,ID,Name,Latitude,Longitude,Rating,Types,Vicinity)
element_count += 1
#return element
def Search_if_Place_ID_exists(Place_ID,ID,Name,Latitude,Longitude,Rating,Types,Vicinity):
global element_saved
cnxn = pyodbc.connect(Connection_Details)
CursorSearch = cnxn.cursor()
sqlSearchPlace_ID = """
select Place_ID
from GoogleNearbySearch
where Place_ID = '%s'
""" % (Place_ID)
CursorSearch.execute(sqlSearchPlace_ID)
row = CursorSearch.fetchone()
if row == None:
element_saved += 1
save_to_mssql(Place_ID,ID,Name,Latitude,Longitude,Rating,Types,Vicinity)
Search_For_Place_ID(Place_ID)
if args.verbose:
print (fg.GREEN,style.BRIGHT,Name,style.RESET_ALL,":",Vicinity)
else:
if args.verbose:
print (fg.YELLOW,style.BRIGHT,Name,style.RESET_ALL,":",Vicinity)
pass
return element_saved
def save_to_mssql(Place_ID,ID,Name,Latitude,Longitude,Rating,Types,Vicinity):
cnxn_nearby_search = pyodbc.connect(Connection_Details)
CursorSearch = cnxn_nearby_search.cursor()
SQLCommand = """
INSERT INTO GoogleNearbySearch (
Place_ID,
ID,
Name,
Latitude,
Longitude,
Rating,
Types,
Vicinity
)
values (?,?,?,?,?,?,?,?)
"""
Values = [Place_ID,ID,Name,Latitude,Longitude,Rating,Types,Vicinity]
CursorSearch.execute(SQLCommand, Values)
cnxn_nearby_search.commit()
def Search_For_Place_ID(Place_ID):
global Total_cost
params = {'place_id': Place_ID}
search_detials = gmaps.place(**params)
Total_cost += decimal.Decimal(0.017)
if search_detials['status'] == 'OK': # Check if the API is 'OK'
Search_Details(search_detials)
else:
print ('API *details* query returned:',search_detials)
def Search_Details(search_detials):
Googleplace_id = search_detials['result'].get("place_id", None)
Googleid = search_detials['result'].get("id", None)
GoogleName = search_detials['result'].get("name", None)
for e in search_detials['result']['address_components']:
for t in e['types']:
long_field[t] = e['long_name']
short_field[t] = e['short_name']
GoogleStreet_Number = long_field.get("street_number", None)
GoogleStreet = long_field.get("route", None)
GooglePostal_Code = long_field.get("postal_code", None)
GoogleCity = long_field.get("locality", None)
GoogleArea1 = long_field.get("administrative_area_level_1", None)
GoogleArea2 = long_field.get("administrative_area_level_2", None)
GoogleCountry = long_field.get("country", None)
GoogleCountryCode = short_field.get("country", None)
GooglePhone = search_detials['result'].get("international_phone_number", None)
GoogleLatitude = search_detials['result']['geometry']['location'].get("lat", None)
GoogleLongitude = search_detials['result']['geometry']['location'].get("lng", None)
GoogleRating = search_detials['result'].get("rating", None)
GoogleTypes = json.dumps(search_detials['result']['types']) # genius!
GoogleURL = search_detials['result'].get("url", None)
GoogleWebsite = search_detials['result'].get("website", None)
Save_Place_Details(Googleplace_id,Googleid,GoogleName,GoogleStreet_Number,GoogleStreet,GooglePostal_Code,GoogleCity,GoogleArea1,GoogleArea2,GoogleCountry,GoogleCountryCode,GooglePhone,GoogleLatitude,GoogleLongitude,GoogleTypes,GoogleRating,GoogleURL,GoogleWebsite)
def Save_Place_Details(Googleplace_id,Googleid,GoogleName,GoogleStreet_Number,GoogleStreet,GooglePostal_Code,GoogleCity,GoogleArea1,GoogleArea2,GoogleCountry,GoogleCountryCode,GooglePhone,GoogleLatitude,GoogleLongitude,GoogleTypes,GoogleRating,GoogleURL,GoogleWebsite):
# We connect to SQL Server Management Studio
connection_details = pyodbc.connect(Connection_Details)
#cursor = connection.cursor()
CursorSaveDetails = connection_details.cursor()
SQL_Save_Details = """
INSERT INTO GoogleDetails ( Place_ID,
ID,
Name,
Street_Number,
Street,
Postal_Code,
City,
Area1,
Area2,
Country,
CountryCode,
Phone,
Latitude,
Longitude,
Types,
Rating,
GoogleURL,
Website
)
values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
"""
CursorSaveDetails.execute(SQL_Save_Details, \
Googleplace_id, \
Googleid, \
GoogleName, \
GoogleStreet_Number, \
GoogleStreet, \
GooglePostal_Code, \
GoogleCity, \
GoogleArea1, \
GoogleArea2, \
GoogleCountry, \
GoogleCountryCode, \
GooglePhone, \
GoogleLatitude, \
GoogleLongitude, \
GoogleTypes, \
GoogleRating, \
GoogleURL, \
GoogleWebsite)
connection_details.commit()
def print_totals(countdown_order, city_name,region_name,country_code):
global element_count
global element_saved
The_Phrase = "{0}) Total places found: {1}, saved {2} in {3}, {4}, {5} - ${6} ({7})".format(countdown_order, element_count, element_saved,city_name,region_name,country_code,Total_cost,datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
if element_count == 0:
print (fg.RED,style.BRIGHT,The_Phrase,style.RESET_ALL)
else:
if element_count != 0 and element_count == element_saved:
print (fg.GREEN,style.BRIGHT,The_Phrase,style.RESET_ALL,sep="")
elif element_count > element_saved:
print (fg.YELLOW,style.BRIGHT,The_Phrase,style.RESET_ALL)
element_count = 0
element_saved = 0
def SQLQuery():
global latitude
global longitude
# We connect to SQL Server Management Studio
connection = pyodbc.connect(Connection_Details)
#cursor = connection.cursor()
CursorSearchLatLon = connection.cursor()
if args.country:
sqlStatement = """
SELECT
ROW_NUMBER() OVER (ORDER BY country_code desc,city_name desc) as countdown_order,
AVG(latitude) AS latitude,
AVG(longitude) AS longitude,
city_name,
region_name,
country_code
FROM ip2location_db11
where country_code = '%s'
GROUP BY country_code, region_name, city_name
ORDER BY country_code, city_name
""" % (args.country)
if args.country == "ALL":
sqlStatement = """
SELECT
ROW_NUMBER() OVER (ORDER BY country_code desc,city_name desc) as countdown_order,
AVG(latitude) AS latitude,
AVG(longitude) AS longitude,
city_name,
region_name,
country_code
FROM ip2location_db11
GROUP BY country_code, region_name, city_name
ORDER BY country_code, city_name
"""
if args.city:
sqlStatement = """
SELECT
ROW_NUMBER() OVER (ORDER BY country_code desc,city_name desc) as countdown_order,
AVG(latitude) AS latitude,
AVG(longitude) AS longitude,
city_name,
region_name,
country_code
FROM ip2location_db11
where city_name = '%s'
GROUP BY country_code, region_name, city_name
ORDER BY country_code, city_name
""" % (args.city)
if args.country and args.rownumber:
sqlStatement = """
SELECT *
FROM
( SELECT
ROW_NUMBER() OVER (ORDER BY country_code desc,
city_name desc) as countdown_order,
AVG(latitude) AS latitude,
AVG(longitude) AS longitude,
city_name,
region_name,
country_code
FROM ip2location_db11
where country_code = '%s'
GROUP BY country_code, region_name, city_name
) as D
where countdown_order < %s
ORDER BY country_code, city_name
""" % (args.country,args.rownumber)
if args.country and args.city:
sqlStatement = """
SELECT
ROW_NUMBER() OVER (ORDER BY country_code desc,city_name desc) as countdown_order,
AVG(latitude) AS latitude,
AVG(longitude) AS longitude,
city_name,
region_name,
country_code
FROM ip2location_db11
where country_code = '%s'
and city_name = '%s'
GROUP BY country_code, region_name, city_name
ORDER BY country_code, city_name
""" % (args.country,args.city)
try:
CursorSearchLatLon.execute(sqlStatement)
for countdown_order, latitude, longitude,city_name,region_name,country_code in CursorSearchLatLon:
Search_URL(countdown_order,latitude, longitude,city_name,region_name,country_code)
print_totals(countdown_order, city_name,region_name,country_code)
finally:
CursorSearchLatLon.close()
connection.close()
SQLQuery()