-
Notifications
You must be signed in to change notification settings - Fork 0
/
POI.py
1940 lines (1846 loc) · 76.5 KB
/
POI.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
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import requests
import urllib.request
import json
import html
import re
from haversine import haversine, haversine_vector
import heapq
import pandas as pd
from dateutil import parser
import pytz
from datetime import datetime
#DISABLE WARNINGS FOR CARREFOUR API (may be unsafe)
import urllib3
import warnings
limit = 1
radius = 6 #in km
# lat = 52.635875 #uk - norfolk
# lng = 1.301 #uk - norfolk
# lat = 52.50003299 #germany - berlin
# lng = 13.3913285 #germany - berlin
# lat = 45.455390 #milan
# lng = 9.403006
# lat = 48.805439 #paris
# lng = 2.311690
# lat = 36.283993 # spain
# lng = -6.08953
# lat = 51.012676 #belgium
# lng = 4.114648
lat = -33.821880 #sydney - australia
lng = 150.790379
#Section for functions to set up local databases:
def set_up_rewe_database():
API_URL = "https://www.rewe.de/market/content/marketsearch"
headers = { "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.98 Safari/537.36",
"accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
"accept-language": "en-US,en;q=0.9",
"sec-fetch-dest": "document",
"sec-fetch-mode": "navigate",
"sec-fetch-site": "none",
"sec-fetch-user": "?1",
"upgrade-insecure-requests": "1"
}
pageStoreCount = 1
page = 0
reweArray = []
intermediaryDayKeys = { 'MONDAY' : 0, 'TUESDAY' : 1, 'WEDNESDAY' : 2, 'THURSDAY' : 3, 'FRIDAY' : 4, 'SATURDAY' : 5, 'SUNDAY' : 6, None : None}
dayKeys = { 0 : 'Monday', 1 : 'Tuesday', 2 : 'Wednesday', 3 : 'Thursday', 4 : 'Friday', 5 : 'Saturday', 6 : 'Sunday'}
while pageStoreCount > 0:
params = { 'searchString' : "REWE",
'pageSize' : 500,
'page' : page}
try:
req_url = API_URL + '?' + '&'.join(k + '=' + str(v) for k, v in params.items())
rq = urllib.request.urlopen(urllib.request.Request(url=req_url, data=None, headers=headers))
if rq.status != 200:
return False
data = rq.read().decode('utf-8')
res = json.loads(data)
if res["total"] == 0:
return False
res = res["markets"]
pageStoreCount = len(res)
except:
return False
# print(res[347]["openingHours"]["dayAndTimeRanges"])
for index in range(len(res)):
dayDoneSet = set()
daysHeap = []
openingHours = res[index]["openingHours"]["dayAndTimeRanges"]
for dayRange in range(len(openingHours)):
startDay = intermediaryDayKeys[openingHours[dayRange]["startDay"]]
endDay = intermediaryDayKeys[openingHours[dayRange]["endDay"]]
opens = openingHours[dayRange]["opens"]
closes = openingHours[dayRange]["closes"]
actualHours = [{'open' : opens, 'close' : closes}]
#deal with 1 day ranges
if endDay == None:
endDay = startDay
#deal with wrap around windows e.g. sunday to tuesday
if startDay > endDay:
startDay += -7
for day in range(startDay, endDay+1):
if day < 0:
day += 7
#if statement to deal with incorrect responses where multiple ranges cover the same day (implemnted due to a bug in their system)
if day not in dayDoneSet:
dayDoneSet.add(day)
keyHours = {'day' : dayKeys[day],
'open' : True,
'hours' : actualHours
}
heapq.heappush(daysHeap, [day,keyHours])
# simple heap method to check for any missing days (method which could be deployed to all other API functions quite easily)
for missingDay in set(dayKeys.keys()).difference(dayDoneSet):
closedDayHours = {
"day": dayKeys[missingDay],
"open": False
}
heapq.heappush(daysHeap, [missingDay, closedDayHours])
if len(daysHeap) != 7:
return False
hoursArray = [i[1] for i in heapq.nsmallest(7, daysHeap)]
coords = res[index]["geoLocation"]
reweArray.append([(float(coords["latitude"]),float(coords["longitude"])), hoursArray])
page += 1
reweDB = pd.DataFrame(reweArray, columns=['Coordinates', 'OpeningHours'])
reweDB.to_csv("REWE.csv")
return True
def set_up_netto_database():
API_URL = "https://netto.de/umbraco/api/StoresData/StoresV2"
nettoArray = []
dayKeys = { 0 : 'Monday', 1 : 'Tuesday', 2 : 'Wednesday', 3 : 'Thursday', 4 : 'Friday', 5 : 'Saturday', 6 : 'Sunday'}
try:
rq = requests.get("https://netto.de/umbraco/api/StoresData/StoresV2")
res = rq.json()
if len(res) == 0:
return False
except:
return False
for index in range(len(res)):
dayDoneSet = set()
daysHeap = []
openingHours = res[index]["hours"]
for dayIndex in range(len(openingHours)):
#potential weakness if a bugged date is retrieved and the datetime parser raises an exception?
day = parser.parse(openingHours[dayIndex]["date"]).weekday()
if day not in dayDoneSet:
try:
dayDoneSet.add(day)
#keyHours processing code
if openingHours[dayIndex]["closed"] == False:
opens = parser.parse(openingHours[dayIndex]["open"]).strftime("%H:%M")
closes = parser.parse(openingHours[dayIndex]["close"]).strftime("%H:%M")
actualHours = {'open' : opens,
'close' : closes}
keyHours = {'day' : dayKeys[day],
'open' : True,
'hours' : [actualHours]
}
heapq.heappush(daysHeap, [day,keyHours])
else:
closedDayHours = { 'day' : dayKeys[day],
'open' : False }
heapq.heappush(daysHeap, [day, closedDayHours])
except:
closedDayHours = { 'day' : dayKeys[day],
'open' : False }
heapq.heappush(daysHeap, [day, closedDayHours])
#Check for any missing days and ensure all days are in order for insertion into our database
for missingDay in set(dayKeys.keys()).difference(dayDoneSet):
closedDayHours = {
"day": dayKeys[missingDay],
"open": False
}
heapq.heappush(daysHeap, [missingDay, closedDayHours])
if len(daysHeap) != 7:
return False
hoursArray = [i[1] for i in heapq.nsmallest(7, daysHeap)]
coords = res[index]["coordinates"]
nettoArray.append([(float(coords[1]),float(coords[0])), hoursArray])
nettoDB = pd.DataFrame(nettoArray, columns=['Coordinates', 'OpeningHours'])
nettoDB.to_csv("Netto.csv")
return True
def set_up_mercadona_database():
API_URL = "https://www.mercadona.com/estaticos/cargas/data.js"
mercadonaArray = []
dayKeys = {
0: "Monday",
1: "Tuesday",
2: "Wednesday",
3: "Thursday",
4: "Friday",
5: "Saturday",
6: "Sunday",
}
intermediaryDayKeys = {
"Monday": 0,
"Tuesday": 1,
"Wednesday": 2,
"Thursday": 3,
"Friday": 4,
"Saturday": 5,
"Sunday": 6,
None: None,
}
try:
rq = requests.get(API_URL)
obj = rq.text[rq.text.find("{") : -5] + "]}"
res = json.loads(obj)
if len(res) == 0:
return False
except:
return False
for index in range(len(res["tiendasFull"])):
dayDoneSet = set()
daysHeap = []
daysArray = []
closingDayArray = res["tiendasFull"][index]["fi"].split("#")
openingDayArray = res["tiendasFull"][index]["in"].split("#")
# finding current day in Spain(madrid)
timeZoneEurope = pytz.timezone("Europe/Madrid")
datetimeEurope = datetime.now(timeZoneEurope)
currentday = datetimeEurope.strftime("%A")
dayCounter = intermediaryDayKeys[currentday]
# implemented because time string returned accordni to the current day in Spain(eg : "##C#C###")
for val in range(7):
daysArray.append(dayCounter)
dayCounter += 1
if dayCounter == 7:
dayCounter = 0
openingHours = daysArray
for dayIndex in range(len(openingHours)):
day = daysArray[dayIndex]
# if statement to deal with days being included twice (implemnted due to a bug in rewe system)
if day not in dayDoneSet:
try:
dayDoneSet.add(day)
# keyHours processing code
opens = openingDayArray[dayIndex]
closes = closingDayArray[dayIndex]
if opens == closes != "":
closedDayHours = {
"day": dayKeys[daysArray[dayIndex]],
"open": False,
}
heapq.heappush(daysHeap, [dayIndex, closedDayHours])
else:
if opens == closes == "":
opens = "09:00"
closes = "21:30"
elif opens == "" and closes != "":
opens = "09:00"
closes = datetime.strptime(closes, "%H%M").strftime("%H:%M")
elif opens != "" and closes == "":
closes = "21:30"
opens = datetime.strptime(opens, "%H%M").strftime("%H:%M")
else:
opens = datetime.strptime(opens, "%H%M").strftime("%H:%M")
closes = datetime.strptime(closes, "%H%M").strftime("%H:%M")
actualHours = {"open": opens, "close": closes}
keyHours = {
"day": dayKeys[daysArray[dayIndex]],
"open": True,
"hours": [actualHours],
}
heapq.heappush(daysHeap, [dayIndex, keyHours])
except:
closedDayHours = {
"day": dayKeys[daysArray[dayIndex]],
"open": False,
}
heapq.heappush(daysHeap, [dayIndex, closedDayHours])
# Check for any missing days and ensure all days are in order for insertion into our database
for day in daysHeap:
if day[1]["day"] != dayKeys[day[0]]:
day[0] = intermediaryDayKeys[day[1]["day"]]
if len(daysHeap) < 7:
for dayDone in dayKeys.keys():
if dayDone not in dayDoneSet:
closedDayHours = {
"day": dayKeys[daysArray[dayIndex]],
"open": False,
}
heapq.heappush(daysHeap, [dayDone, closedDayHours])
hoursArray = [i[1] for i in heapq.nsmallest(7, daysHeap)]
latitude = res["tiendasFull"][index]["lt"]
longitude = res["tiendasFull"][index]["lg"]
mercadonaArray.append([(float(latitude), float(longitude)), hoursArray])
mercadonaDB = pd.DataFrame(mercadonaArray, columns=["Coordinates", "OpeningHours"])
mercadonaDB.to_csv("Mercadona.csv")
return True
def set_up_migros_database():
API_URL = "https://web-api.migros.ch/widgets/stores"
headers = {
"Accept-Language": "de",
"Origin": "https://filialen.migros.ch",
}
params = (
("key", "loh7Diephiengaiv"),
("filters[markets][0][0]", "super"),
("filters[markets][0][2]", "voi"),
("filters[markets][0][3]", "mp"),
("limit", "737"),
)
try:
rq = requests.get(API_URL, headers=headers, params=params)
res = rq.json()
if len(res) == 0:
return False
except:
return False
migrosArray = []
dayKeys = {
0: "Monday",
1: "Tuesday",
2: "Wednesday",
3: "Thursday",
4: "Friday",
5: "Saturday",
6: "Sunday",
}
intermediaryDayKeys = {
"Monday": 0,
"Tuesday": 1,
"Wednesday": 2,
"Thursday": 3,
"Friday": 4,
"Saturday": 5,
"Sunday": 6,
None: None,
}
for index in range(len(res["stores"])):
dayDoneSet = set()
daysHeap = []
openingHours = res["stores"][index]["markets"][0]["opening_hours"][0][
"opening_hours"
]
dayCounter = 0
for dayIndex in range(len(openingHours)):
if dayIndex not in dayDoneSet:
try:
day = openingHours[dayIndex]["day_of_week"] - 1
dayDoneSet.add(day)
# keyHours processing code
# changes done because some stores opens two times a day.
opens_firstHalf = openingHours[dayIndex]["time_open1"]
closes_firstHalf = openingHours[dayIndex]["time_close1"]
opens_secondHalf = openingHours[dayIndex]["time_open2"]
closes_secondHalf = openingHours[dayIndex]["time_close2"]
if (
opens_firstHalf
== closes_firstHalf
== opens_secondHalf
== closes_secondHalf
):
closedDayHours = {
"day": dayKeys[day],
"open": False,
}
heapq.heappush(daysHeap, [day, closedDayHours])
else:
if opens_secondHalf == closes_secondHalf:
actualHours = {
"open": opens_firstHalf,
"close": closes_firstHalf,
}
keyHours = {
"day": dayKeys[day],
"open": True,
"hours": [actualHours],
}
heapq.heappush(daysHeap, [day, keyHours])
else:
actualHours_firstHalf = {
"open": opens_firstHalf,
"close": closes_firstHalf,
}
actualHours_secondHalf = {
"open": opens_secondHalf,
"close": closes_secondHalf,
}
keyHours = {
"day": dayKeys[day],
"open": True,
"hours": [
actualHours_firstHalf,
actualHours_secondHalf,
],
}
heapq.heappush(daysHeap, [day, keyHours])
except:
closedDayHours = {
"day": dayKeys[day],
"open": False,
}
heapq.heappush(daysHeap, [day, closedDayHours])
# Check for any missing days and ensure all days are in order for insertion into our database
for day in daysHeap:
if day[1]["day"] != dayKeys[day[0]]:
day[0] = intermediaryDayKeys[day[1]["day"]]
if len(daysHeap) < 7:
for dayDone in dayKeys.keys():
if dayDone not in dayDoneSet:
closedDayHours = {
"day": dayKeys[dayDone],
"open": False,
}
heapq.heappush(daysHeap, [dayDone, closedDayHours])
hoursArray = [i[1] for i in heapq.nsmallest(7, daysHeap)]
latitude = res["stores"][index]["location"]["geo"]["lat"]
longitude = res["stores"][index]["location"]["geo"]["lon"]
migrosArray.append([(float(latitude), float(longitude)), hoursArray])
migrosDB = pd.DataFrame(migrosArray, columns=["Coordinates", "OpeningHours"])
migrosDB.to_csv("Migros.csv")
return True
def set_up_kaufland_database():
API_URL = "https://www.kaufland.de/.klstorefinder.json"
kauflandArray = []
dayKeys = {
0: "Monday",
1: "Tuesday",
2: "Wednesday",
3: "Thursday",
4: "Friday",
5: "Saturday",
6: "Sunday",
}
intermediaryDayKeys = {
"Monday": 0,
"Tuesday": 1,
"Wednesday": 2,
"Thursday": 3,
"Friday": 4,
"Saturday": 5,
"Sunday": 6,
None: None,
}
try:
rq = requests.get(API_URL)
res = rq.json()
if len(res) == 0:
return False
except:
return False
for index in range(len(res)):
dayDoneSet = set()
daysHeap = []
openingHours = res[index]["wod"]
dayCounter = 0
for dayIndex in range(len(openingHours)):
day = dayIndex
#if statement to deal with days being included twice (implemnted due to a bug in rewe system)
if dayIndex not in dayDoneSet:
try:
dayDoneSet.add(
intermediaryDayKeys[openingHours[dayIndex].split("|")[0]]
)
# keyHours processing code
opens = openingHours[dayIndex].split("|")[1]
closes = openingHours[dayIndex].split("|")[2]
if opens == closes:
closedDayHours = {
"day": openingHours[dayIndex].split("|")[0],
"open": False,
}
heapq.heappush(daysHeap, [day, closedDayHours])
actualHours = {"open": opens, "close": closes}
keyHours = {
"day": openingHours[dayIndex].split("|")[0],
"open": True,
"hours": [actualHours],
}
heapq.heappush(daysHeap, [day, keyHours])
except:
closedDayHours = {
"day": openingHours[dayIndex].split("|")[0],
"open": False,
}
heapq.heappush(daysHeap, [day, closedDayHours])
# Check for any missing days and ensure all days are in order for insertion into our database
for day in daysHeap:
if day[1]["day"] != dayKeys[day[0]]:
day[0] = intermediaryDayKeys[day[1]["day"]]
if len(daysHeap) < 7:
for dayDone in dayKeys.keys():
if dayDone not in dayDoneSet:
closedDayHours = {
"day": dayKeys[dayDone],
"open": False,
}
heapq.heappush(daysHeap, [dayDone, closedDayHours])
hoursArray = [i[1] for i in heapq.nsmallest(7, daysHeap)]
latitude = res[index]["lat"]
longitude = res[index]["lng"]
kauflandArray.append([(float(latitude), float(longitude)), hoursArray])
kauflandDB = pd.DataFrame(kauflandArray, columns=["Coordinates", "OpeningHours"])
kauflandDB.to_csv("Kaufland.csv")
return True
#Section for functions to call our local databases:
def get_rewe_data(lat, lng):
desiredCoords = [lat, lng]
reweDB = pd.read_csv("REWE.csv", index_col="Unnamed: 0", converters={'Coordinates': eval, 'OpeningHours' : eval})
reweDB["Distances"] = haversine_vector([desiredCoords]*len(reweDB["Coordinates"]), list(reweDB["Coordinates"]))
closestStoreIndex = reweDB["Distances"].idxmin()
if reweDB["Distances"][closestStoreIndex] > radius:
return False
return reweDB["OpeningHours"][closestStoreIndex]
def get_netto_data(lat, lng):
#pass lat and lng as arrays of length 1 if you want the storeDistance to be returned too
if isinstance(lat, list) :
returnDistanceToo = True
lat = lat[0]
lng = lng[0]
else:
returnDistanceToo = False
desiredCoords = [lat, lng]
nettoDB = pd.read_csv("Netto.csv", index_col="Unnamed: 0", converters={'Coordinates': eval, 'OpeningHours' : eval})
nettoDB["Distances"] = haversine_vector([desiredCoords]*len(nettoDB["Coordinates"]), list(nettoDB["Coordinates"]))
closestStoreIndex = nettoDB["Distances"].idxmin()
try:
if nettoDB["Distances"][closestStoreIndex] > radius:
return False
if returnDistanceToo:
return nettoDB["Distances"][closestStoreIndex], nettoDB["OpeningHours"][closestStoreIndex]
else:
return nettoDB["OpeningHours"][closestStoreIndex]
except:
print("NETTO MYSTERIOUS ERROR")
print(nettoDB)
print(nettoDB["OpeningHours"])
print(closestStoreIndex)
return False
def get_netto_brands_data(lat, lng):
netto = get_netto_data([lat], [lng])
nettoMD = get_netto_marken_discount_data([lat], [lng])
if netto and not nettoMD:
return netto[1]
elif nettoMD and not netto:
return nettoMD[1]
elif not nettoMD and not netto:
return False
elif netto[0] < nettoMD[0]:
if netto[1] > radius:
return False
return netto[1]
else:
if netto[0] > radius:
return False
return nettoMD[1]
def get_mercadona_data(lat, lng):
# pass lat and lng as arrays of length 1 if you want the storeDistance to be returned too
if isinstance(lat, list):
returnDistanceToo = True
lat = lat[0]
lng = lng[0]
else:
returnDistanceToo = False
desiredCoords = [lat, lng]
mercadonaDB = pd.read_csv(
"Mercadona.csv",
index_col="Unnamed: 0",
converters={"Coordinates": eval, "OpeningHours": eval},
)
mercadonaDB["Distances"] = haversine_vector(
[desiredCoords] * len(mercadonaDB["Coordinates"]),
list(mercadonaDB["Coordinates"]),
)
closestStoreIndex = mercadonaDB["Distances"].idxmin()
if mercadonaDB["Distances"][closestStoreIndex] > radius:
return False
if returnDistanceToo:
return (
mercadonaDB["Distances"][closestStoreIndex],
mercadonaDB["OpeningHours"][closestStoreIndex],
)
else:
return mercadonaDB["OpeningHours"][closestStoreIndex]
def get_migros_data(lat, lng):
# pass lat and lng as arrays of length 1 if you want the storeDistance to be returned too
if isinstance(lat, list):
returnDistanceToo = True
lat = lat[0]
lng = lng[0]
else:
returnDistanceToo = False
desiredCoords = [lat, lng]
migrosDB = pd.read_csv(
"Migros.csv",
index_col="Unnamed: 0",
converters={"Coordinates": eval, "OpeningHours": eval},
)
migrosDB["Distances"] = haversine_vector(
[desiredCoords] * len(migrosDB["Coordinates"]), list(migrosDB["Coordinates"]),
)
closestStoreIndex = migrosDB["Distances"].idxmin()
if migrosDB["Distances"][closestStoreIndex] > radius:
return False
if returnDistanceToo:
return (
migrosDB["Distances"][closestStoreIndex],
migrosDB["OpeningHours"][closestStoreIndex],
)
else:
return migrosDB["OpeningHours"][closestStoreIndex]
def get_kaufland_data(lat, lng):
# pass lat and lng as arrays of length 1 if you want the storeDistance to be returned too
if isinstance(lat, list):
returnDistanceToo = True
lat = lat[0]
lng = lng[0]
else:
returnDistanceToo = False
desiredCoords = [lat, lng]
kauflandDB = pd.read_csv(
"Kaufland.csv",
index_col="Unnamed: 0",
converters={"Coordinates": eval, "OpeningHours": eval},
)
kauflandDB["Distances"] = haversine_vector(
[desiredCoords] * len(kauflandDB["Coordinates"]),
list(kauflandDB["Coordinates"]),
)
closestStoreIndex = kauflandDB["Distances"].idxmin()
if kauflandDB["Distances"][closestStoreIndex] > radius:
return False
if returnDistanceToo:
return (
kauflandDB["Distances"][closestStoreIndex],
kauflandDB["OpeningHours"][closestStoreIndex],
)
else:
return kauflandDB["OpeningHours"][closestStoreIndex]
#Section for functions to call external API's (all ones that dont require us to have set up an internal DB):
def get_netto_marken_discount_data(lat, lng):
#pass lat and lng as arrays of length 1 if you want the storeDistance to be returned too
if isinstance(lat, list) :
returnDistanceToo = True
lat = lat[0]
lng = lng[0]
else:
returnDistanceToo = False
API_URL = "https://www.netto-online.de/INTERSHOP/web/WFS/Plus-NettoDE-Site/de_DE/-/EUR/ViewNettoStoreFinder-GetStoreItems"
#The conversion rates below have been estimated through experimentation, and should approximately preserve radius (although the geometry will be a cross between a square and a circle)
params = { 's' : float(lat) - radius / 70,
'n' : float(lat) + radius / 70,
'w' : float(lng) - radius / 110,
'e' : float(lng) + radius / 110
}
rq = requests.get(API_URL, params=params)
if rq.status_code != 200:
return False
try:
res = rq.json()
if len(res) == 0:
print(2)
return False
except:
return False
storeHeap = []
for index in range(len(res)):
storeLat, storeLng = float(res[index]["coord_latitude"]), float(res[index]["coord_longitude"])
#compute distance between the two points using the haversine function
storeDistance = haversine((lat, lng),(storeLat, storeLng))
heapq.heappush(storeHeap, [storeDistance,res[index]])
res = heapq.nsmallest(limit, storeHeap)
i = 0
#INSERT POTENTIAL CHECK THAT STORE MATCHES DESIRED STORENAME!!
#e.g.:
# while True:
# if name != res[0]['name'] or res[0]['other_name']:
# i += 1
# else:
# break
intermediaryDayKeys = { 'Mo.' : 0, 'Di.' : 1, 'Mi.' : 2, 'Do.' : 3, 'Fr.' : 4, 'Sa.' : 5, 'So.' : 6, None : None}
dayKeys = { 0 : 'Monday', 1 : 'Tuesday', 2 : 'Wednesday', 3 : 'Thursday', 4 : 'Friday', 5 : 'Saturday', 6 : 'Sunday'}
dayDoneSet = set()
daysHeap = []
storeDistance = res[i][0]
openingHours = res[i][1]["store_opening"]
dayRanges = openingHours.split("<br />")[:-1]
for dayRange in range(len(dayRanges)):
daysAndTimes = dayRanges[dayRange].split(":")
days = daysAndTimes[0]
days = days.split("-")
startDay = intermediaryDayKeys[days[0]]
if len(days) == 1:
endDay = startDay
elif len(days) == 2:
endDay = intermediaryDayKeys[days[1]]
else:
return False
#deal with wrap around windows e.g. sunday to tuesday
if startDay > endDay:
startDay += -7
times = daysAndTimes[1]
if "geschlossen" in times:
for day in range(startDay, endDay+1):
if day < 0:
day += 7
#if statement to deal with incorrect responses where multiple ranges cover the same day (implemnted due to a bug in their system)
if day not in dayDoneSet:
dayDoneSet.add(day)
closedDayHours = { 'day' : dayKeys[day],
'open' : False }
heapq.heappush(daysHeap, [day, closedDayHours])
else:
try:
times = times.replace(".",":")
times = times.split()
if len(times) != 4:
#means this method is non exhaustive (e.g. multiple time slots) and must be amended
return False
opens = times[0]
closes = times[2]
if len(opens) == 4:
opens = "0" + opens
if len(closes) == 4:
closes = "0" + closes
if len(opens) != 5 or len(closes) != 5:
#means this method is non exhaustive (e.g. doesnt catch store closure) and must be amended
return False
actualHours = [{'open' : opens, 'close' : closes}]
for day in range(startDay, endDay+1):
if day < 0:
day += 7
#if statement to deal with incorrect responses where multiple ranges cover the same day (implemnted due to a bug in their system)
if day not in dayDoneSet:
dayDoneSet.add(day)
keyHours = {'day' : dayKeys[day],
'open' : True,
'hours' : actualHours
}
heapq.heappush(daysHeap, [day,keyHours])
except:
for day in range(startDay, endDay+1):
if day < 0:
day += 7
#if statement to deal with incorrect responses where multiple ranges cover the same day (implemnted due to a bug in their system)
if day not in dayDoneSet:
dayDoneSet.add(day)
closedDayHours = { 'day' : dayKeys[day],
'open' : False }
heapq.heappush(daysHeap, [day, closedDayHours])
# simple heap method to check for any missing days (method which could be deployed to all other API functions quite easily)
for missingDay in set(dayKeys.keys()).difference(dayDoneSet):
closedDayHours = {
"day": dayKeys[missingDay],
"open": False
}
heapq.heappush(daysHeap, [missingDay, closedDayHours])
if len(daysHeap) != 7:
return False
hoursArray = [i[1] for i in heapq.nsmallest(7, daysHeap)]
if returnDistanceToo:
return storeDistance, hoursArray
else:
if storeDistance > radius:
return False
return hoursArray
def get_sainsburys_data(lat,lng):
API_URL = "https://stores.sainsburys.co.uk/api/v1/stores/"
params = {
'fields': 'slfe-list-2.21',
'api_client_id': 'slfe',
'store_type': 'main,local',
'sort': 'by_distance',
'within': radius,
'limit': limit,
'page': '1',
'lat': lat,
'lon': lng,
}
rq = requests.get(API_URL, params=params)
if rq.status_code != 200:
# print(rq.json())
return False
try:
res = rq.json()
if res["page_meta"]["total"] == 0:
return False
res = res["results"]
except:
return False
dayKeys = { 0 : 'Monday', 1 : 'Tuesday', 2 : 'Wednesday', 3 : 'Thursday', 4 : 'Friday', 5 : 'Saturday', 6 : 'Sunday'}
i=0
#INSERT POTENTIAL CHECK THAT STORE MATCHES DESIRED STORENAME!! (res[0]['name'] or res[0]['other_name'])
#e.g.:
# while True:
# if name != res[0]['name'] or res[0]['other_name']:
# i += 1
# else:
# break
if res[i]["distance"] > radius * 0.621371:
return False
openingHours = res[i]['opening_times']
dayDoneSet = set()
daysHeap = []
for index in range(len(openingHours)):
key = openingHours[index]['day']
#if statement to deal with days being included twice (implemnted due to a bug in rewe system)
if key not in dayDoneSet:
dayDoneSet.add(key)
#keyHours processing code
actualHours = []
for timeSlotNumber in range(len(openingHours[index]['times'])):
try:
opens = openingHours[index]['times'][timeSlotNumber]['start_time']
closes = openingHours[index]['times'][timeSlotNumber]['end_time']
actualHoursDict = { 'open' : opens,
'close' : closes}
actualHours.append(actualHoursDict)
except:
#If dictionary keys start_time or end_time dont exist, assume store is closed on that day
closedDayHours = { 'day' : dayKeys[key],
'open' : False }
heapq.heappush(daysHeap, [key,closedDayHours])
break
keyHours = {'day' : dayKeys[key],
'open' : True,
'hours' : actualHours
}
heapq.heappush(daysHeap, [key,keyHours])
#Check for any missing days and ensure all days are in order for insertion into our database
for missingDay in set(dayKeys.keys()).difference(dayDoneSet):
closedDayHours = {
"day": dayKeys[missingDay],
"open": False
}
heapq.heappush(daysHeap, [missingDay, closedDayHours])
if len(daysHeap) != 7:
return False
hoursArray = [i[1] for i in heapq.nsmallest(7, daysHeap)]
return hoursArray
def get_asda_data(lat,lng):
import json
API_URL = "https://storelocator.asda.com/index.html"
params = { 'q' : "{0},{1}".format(lat,lng)}
headers = {
"accept": "application/json",
}
rq = requests.get(API_URL,params=params, headers = headers)
if rq.status_code != 200:
print(rq.json())
return False
# res = json.dumps(rq.text)
try:
res = rq.json()["response"]
if res["count"] == 0:
return False
except:
return False
i = 0
#INSERT POTENTIAL CHECK THAT STORE MATCHES DESIRED STORENAME!! (res["entities"][0]["name"])
#e.g.:
# while True:
# if name != res["entities"][i]["name"]:
# i += 1
# else:
# break
if res["entities"][i]["distance"]["distanceKilometers"] > radius:
return False
openingHours = res["entities"][i]["profile"]["hours"]["normalHours"]
hoursArray = []
intermediaryDayKeys = { 'MONDAY' : 0, 'TUESDAY' : 1, 'WEDNESDAY' : 2, 'THURSDAY' : 3, 'FRIDAY' : 4, 'SATURDAY' : 5, 'SUNDAY' : 6}
dayKeys = { 0 : 'Monday', 1 : 'Tuesday', 2 : 'Wednesday', 3 : 'Thursday', 4 : 'Friday', 5 : 'Saturday', 6 : 'Sunday'}
dayDoneSet = set()
daysHeap = []
for index in range(len(openingHours)):
day = intermediaryDayKeys[openingHours[index]["day"]]
#if statement to deal with days being included twice (implemnted due to a bug in rewe system)
if day not in dayDoneSet:
dayDoneSet.add(day)
if openingHours[index]["isClosed"] != False:
closedDayHours = { 'day' : dayKeys[day],
'open' : False }
heapq.heappush(daysHeap, [day,closedDayHours])
else:
actualHours = []
for timeSlotNumber in range(len(openingHours[index]['intervals'])):
try:
actualHoursDict = {}
start = str(openingHours[index]['intervals'][timeSlotNumber]['start'])
if start == "0":
start = "00:00"
elif len(start) == 3:
start = "0{0}:{1}".format(start[0],start[1:])
else:
start = "{0}:{1}".format(start[:2],start[2:])
end = str(openingHours[index]['intervals'][timeSlotNumber]['end'])
if end == "0":
end = "00:00"
elif len(end) == 3:
end = "0{0}:{1}".format(end[0],end[1:])
else:
end = "{0}:{1}".format(end[:2],end[2:])
actualHoursDict['open'] = start
actualHoursDict['close'] = end
actualHours.append(actualHoursDict)
except:
#If dictionary keys start_time or end_time dont exist, assume store is closed on that day
closedDayHours = { 'day' : dayKeys[day],
'open' : False }
heapq.heappush(daysHeap, [day,closedDayHours])
break
keyHours = {'day' : dayKeys[day],
'open' : True,
'hours' : actualHours
}
heapq.heappush(daysHeap, [day,keyHours])
#Check for any missing days and ensure all days are in order for insertion into our database
for missingDay in set(dayKeys.keys()).difference(dayDoneSet):
closedDayHours = {
"day": dayKeys[missingDay],
"open": False
}
heapq.heappush(daysHeap, [missingDay, closedDayHours])
if len(daysHeap) != 7:
return False
hoursArray = [i[1] for i in heapq.nsmallest(7, daysHeap)]
return hoursArray
def get_tesco_data(lat, lng):
API_URL = "https://api.tesco.com/tescolocation/v3/locations/search"
params = { 'offset' : 0,
'limit' : limit,
'sort' : 'near:"{0},{1}"'.format(lat,lng),
'filter' : "category:Store AND isoCountryCode:x-uk",
'fields' : "name,geo,openingHours"
#known fields: "name,geo,openingHours,altIds.branchNumber,contact,facilities"
}
headers = {"x-appkey": "store-locator-web-cde"}
rq = requests.get(API_URL, params=params, headers=headers)
if rq.status_code != 200:
print(rq.json())
return False
try:
res = rq.json()['results']
if len(res) == 0:
return False
except:
return False
i=0
#INSERT POTENTIAL CHECK THAT STORE MATCHES DESIRED STORENAME!! (res[0]['location']['name'])
#e.g.:
# while True:
# if name != res[i]['location']['name']:
# i += 1
# else:
# break
if res[i]["distanceFrom"]["value"] > 0.621371*radius:
return False
openingHours = res[i]['location']['openingHours'][0]['standardOpeningHours']
dayKeys = { 'mo' : 'Monday', 'tu' : 'Tuesday', 'we' : 'Wednesday', 'th' : 'Thursday', 'fr' : 'Friday', 'sa' : 'Saturday', 'su' : 'Sunday'}
hoursArray = []
for key in ['mo','tu','we','th','fr','sa','su']:
try:
if openingHours[key]['isOpen'] == 'true':
actualHours = {'open' : openingHours[key]['open'][:2] + ":" + openingHours[key]['open'][2:],
'close' : openingHours[key]['close'][:2] + ":" + openingHours[key]['close'][2:]}
keyHours = {'day' : dayKeys[key],
'open' : True,
'hours' : [actualHours]
}
else:
keyHours = {'day' : dayKeys[key],
'open' : False}
except:
keyHours = {'day' : dayKeys[key],