This repository has been archived by the owner on Dec 30, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 49
/
app.py
182 lines (139 loc) · 4.7 KB
/
app.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
import os
import json
import requests
import settings
import pkg_resources
from flask import Flask, Response, render_template, request
from backend import utils
from backend.preprocessing import TripTimePreprocessor
from backend.models import TripTimeEstimator
APP = Flask(__name__)
def get_trip_time(start_id, end_id):
"""
Trip time prediction using k boosted trees
:param start_id: str
start station id
:param end_id: str
end station id
:return: pred float
predicted trip time (in minutes)
valid bool
true if valid station ids were passed
"""
prep = TripTimePreprocessor()
model = TripTimeEstimator(n_folds=10)
valid = True
try:
# build feature array based on station id
prep.set(start_id, mode='start')
prep.set(end_id, mode='end')
# run preprocessing and inference
data = prep.transform()
pred = model.predict(data)
except KeyError:
# one or more id invalid
pred = 0.
valid = False
return pred, valid
@APP.route('/')
def index():
"""
User interface - main page
"""
return render_template('index.html')
@APP.route('/get_stations', methods=['GET'])
def get_stations():
"""
User interface - station info
GET: json
valid station ids with names and coordinates
"""
path = 'assets/station_data/'
file = 'station_names_v3.json'
realpath = pkg_resources.resource_filename('backend', os.path.join(path, file))
with open(realpath, 'r') as f:
data = json.load(f)
return Response(json.dumps(data, indent=4), status=200, mimetype='application/json')
@APP.route('/get_prediction', methods=['POST'])
def get_prediction():
"""
User interface - trip time prediction
POST: json
start and end station ids
"""
start_id = request.json['start']
end_id = request.json['end']
pred, valid = get_trip_time(start_id, end_id)
if valid:
payload = {'predicted': pred}
payload = json.dumps(payload)
code = 200
else:
payload = {'predicted': 'who knows'}
code = 404
return Response(payload, status=code, mimetype='application/json')
@APP.route('/proxy/mapbox')
def proxy_mapbox():
"""
Serves as proxy for mapbox API calls
hiding exposed API key
"""
# get requested tile params
args = ['x', 'y', 'z', 'id']
params = {arg: request.args.get(arg) for arg in args}
token = settings.MAPBOX_API_KEY
# server-side mapbox API call to hide the key
mapbox_url = utils.format_mapbox_url(**params)
r = requests.get(mapbox_url, params={'access_token': token})
return Response(r.content, status=r.status_code, mimetype=r.headers['content-type'])
@APP.route('/api', methods=['GET'])
def api():
"""
API - trip time prediction
example call: /api?start=42&end=63
GET: json
predicted travel time form
start station to end station
and metadata
"""
# get station ids and run inference
start_id = request.args.get('start', type=str)
end_id = request.args.get('end', type=str)
pred, valid = get_trip_time(start_id, end_id)
if valid:
path = 'assets/station_data/'
file = 'station_names.json'
realpath = pkg_resources.resource_filename('backend', os.path.join(path, file))
with open(realpath, 'r') as f:
# load json with metadata and add to response
data = json.load(f)
start = data[start_id]
end = data[end_id]
payload = {'start': start, 'destination': end, 'time_predicted': pred}
payload = json.dumps(payload, indent=4)
code = 200
else:
# could not find station in lookup
payload = {'error: Invalid station id passed to API'}
code = 404
return Response(payload, status=code, mimetype='application/json')
@APP.route('/api/stations', methods=['GET'])
def api_stations():
"""
API - station info
example call: /api/stations
GET: json
valid station ids with names
"""
path = 'assets/station_data/'
file = 'station_names.json'
realpath = pkg_resources.resource_filename('backend', os.path.join(path, file))
with open(realpath, 'r') as f:
data = json.load(f)
payload = {}
for key in data.keys():
# load json with station ids and names
payload[key] = data[key]['name']
return Response(json.dumps(payload, indent=4), status=200, mimetype='application/json')
if __name__ == '__main__':
APP.run(host='0.0.0.0', port=4242)