-
Notifications
You must be signed in to change notification settings - Fork 0
/
APIFunctions.py
265 lines (209 loc) · 11.7 KB
/
APIFunctions.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
import Logger
import datetime
import API
import db_objects as db
from utilities import *
from constants import *
def get_routes():
routes = [
db.Route(name=RED_LINE_ASHMONT),
db.Route(name=RED_LINE_BRAINTREE),
db.Route(name=GREEN_LINE_B),
db.Route(name=GREEN_LINE_C),
db.Route(name=GREEN_LINE_D),
db.Route(name=GREEN_LINE_E),
db.Route(name=BLUE_LINE),
db.Route(name=ORANGE_LINE),
]
return routes
def get_stations(session):
stations = []
routes = session.query(db.Route).all()
populate_red = False
for route in routes:
if route.name == RED_LINE_ASHMONT or route.name == RED_LINE_BRAINTREE:
populate_red = True
continue
api_result = API.get("stopsbyroute", {'route': route.name})['direction'][0]['stop']
for item in api_result:
accessible = True
if item['parent_station_name'] in NON_ACCESSIBLE_STATIONS:
accessible = False
new_station = db.Station(route_id=route.id,
name_human_readable=item['parent_station_name'],
name_api=item['parent_station'],
location_lat=item['stop_lat'],
location_lng=item['stop_lon'],
accessible=accessible)
stations.append(new_station)
if populate_red:
ashmont = []
ashmont_added_jfk = False
braintree = []
braintree_added_jfk = False
route_id_ashmont = session.query(db.Route).filter(db.Route.name == RED_LINE_ASHMONT).first().id
route_id_braintree = session.query(db.Route).filter(db.Route.name == RED_LINE_BRAINTREE).first().id
api_result = API.get("stopsbyroute", {'route': 'Red'})['direction'][0]['stop']
for item in api_result:
accessible = True
if item['parent_station_name'] in NON_ACCESSIBLE_STATIONS:
accessible = False
if item['parent_station_name'] in RED_LINE_BRAINTREE_STATIONS:
new_station = db.Station(route_id=route_id_braintree,
name_human_readable=item['parent_station_name'],
name_api=item['parent_station'],
location_lat=item['stop_lat'],
accessible=accessible,
location_lng=item['stop_lon'])
braintree.append(new_station)
elif item['parent_station_name'] in RED_LINE_ASHMONT_STATIONS:
new_station = db.Station(route_id=route_id_ashmont, name_human_readable=item['parent_station_name'],
name_api=item['parent_station'], location_lat=item['stop_lat'],
location_lng=item['stop_lon'], accessible=accessible)
ashmont.append(new_station)
else:
new_station_ashmont = db.Station(route_id=route_id_ashmont,
name_human_readable=item['parent_station_name'],
name_api=item['parent_station'],
location_lat=item['stop_lat'],
location_lng=item['stop_lon'], accessible=accessible)
new_station_braintree = db.Station(route_id=route_id_braintree,
name_human_readable=item['parent_station_name'],
name_api=item['parent_station'],
location_lat=item['stop_lat'],
location_lng=item['stop_lon'],
accessible=accessible)
if new_station_ashmont.name_api == 'place-jfk':
if not ashmont_added_jfk:
ashmont_added_jfk = True
ashmont.append(new_station_ashmont)
else:
ashmont.append(new_station_ashmont)
if new_station_braintree.name_api == 'place-jfk':
if not braintree_added_jfk:
braintree_added_jfk = True
braintree.append(new_station_braintree)
else:
braintree.append(new_station_braintree)
stations.extend(ashmont)
stations.extend(braintree)
return stations
def sync_trips_and_records(routes, session):
Logger.log.info("Syncing trips...")
Logger.log.info("Input routes: %s" % routes)
if 'Red-Ashmont' in routes or 'Red-Braintree' in routes:
routes.remove('Red-Ashmont')
routes.remove('Red-Braintree')
routes.append('Red')
Logger.log.info("Using routes: %s" % routes)
to_save = []
route_string = ",".join(routes)
data = API.get("vehiclesbyroutes", {'routes': route_string})
mode = data['mode']
for route in mode:
route_sub = route['route']
for route_sub_sub in route_sub:
route_name = route_sub_sub['route_id']
Logger.log.info("Processing route %s" % route_name)
for direction in route_sub_sub['direction']:
for trip in direction['trip']:
# The MBTA sometimes just throws us random bs
# Love you guys, but...really?
if trip['trip_name'] == u'':
continue
trip['trip_name'] = trip['trip_name'].replace('Forest Hills Orange Line', 'Forest Hills')
# Now we have a trip
trips_with_same_id = session.query(db.Trip).filter(db.Trip.api_id == trip['trip_id']).filter(
db.Trip.date == datetime.datetime.utcnow().date())
# print("trips_with_same_id is {}".format(trips_with_same_id.count()))
if trips_with_same_id.count() == 1:
# Create a trip record object
new_trip_record = db.TripRecord(trip_id=trips_with_same_id.first().id,
location_lat=trip['vehicle']['vehicle_lat'],
location_lng=trip['vehicle']['vehicle_lon'],
stamp=datetime.datetime.utcnow())
to_save.append(new_trip_record)
# Update the trip's last seen time
session.query(db.Trip).filter(db.Trip.id == trips_with_same_id.first().id)\
.update({'stamp_last_seen' : datetime.datetime.utcnow()})
elif trips_with_same_id.count() == 0:
# Create a trip object
if 'Red' in route_name:
if string_contains_ashmont_anything(trip['trip_name']):
route_name = constants.RED_LINE_ASHMONT
elif string_contains_braintree_anything(trip['trip_name']):
route_name = constants.RED_LINE_BRAINTREE
else:
route_name = constants.RED_LINE_ASHMONT
route_id = session.query(db.Route).filter(db.Route.name == route_name).first().id
station_pair = origin_and_destination_stations(session, trip, route_id)
origin_station_id = station_pair[0]
destination_station_id = station_pair[1]
new_trip = db.Trip(api_id=trip['trip_id'],
route_id=route_id,
origin_station_id=origin_station_id,
destination_station_id=destination_station_id,
lead=str(trip['vehicle']['vehicle_label']),
date=datetime.datetime.utcnow(),
stamp_first_seen=datetime.datetime.utcnow(),
stamp_last_seen=datetime.datetime.utcnow())
session.add(new_trip)
session.commit()
new_trip_record = db.TripRecord(trip_id=new_trip.id,
location_lat=trip['vehicle']['vehicle_lat'],
location_lng=trip['vehicle']['vehicle_lon'],
stamp=datetime.datetime.utcnow())
to_save.append(new_trip_record)
else:
raise RuntimeError("There were multiple trip objects with the same id: %s" % trips_with_same_id)
for object in to_save:
session.merge(object)
session.commit()
return to_save
def sync_predictions(routes, session):
Logger.log.info("Syncing predictions...")
Logger.log.info("Input routes: %s" % routes)
if 'Red-Ashmont' in routes or 'Red-Braintree' in routes:
routes.remove('Red-Ashmont')
routes.remove('Red-Braintree')
routes.append('Red')
Logger.log.info("Using routes: %s" % routes)
to_save = []
route_string = ",".join(routes)
data = API.get("predictionsbyroutes", {'routes': route_string})
mode = data['mode']
for route in mode:
route_sub = route['route']
for route_sub_sub in route_sub:
route_name = route_sub_sub['route_id']
Logger.log.info("Processing route %s" % route_name)
for direction in route_sub_sub['direction']:
for trip in direction['trip']:
api_trip_id = trip['trip_id']
trip_ref = session.query(db.Trip).filter(db.Trip.api_id == api_trip_id).first()
if trip_ref is None:
Logger.log.info('No trip record for this prediction. trip_api_id: %s' % api_trip_id)
continue
for stop in trip['stop']:
stop_name = stop['stop_name'].split(' -')[0]
if 'JFK/UMASS' in stop_name:
stop_name = stop_name.split(' ')[0]
try:
station_id = session.query(db.Station).filter(db.Station.route_id == trip_ref.route_id)\
.filter(db.Station.name_human_readable.like('%' + stop_name + '%')).first().id
except AttributeError as e:
station_id = station_with_most_similar_name(session, trip_ref.route_id, stop_name)
try:
seconds = stop['pre_away']
new_prediction_record = db.PredictionRecord(trip_id=trip_ref.id,
stamp=datetime.datetime.utcnow(),
station_id=station_id,
seconds_away_from_stop=seconds)
to_save.append(new_prediction_record)
except KeyError as e:
continue
Logger.log.info('trip %s has terminated' % api_trip_id)
for object in to_save:
session.merge(object)
session.commit()
return to_save