forked from DG-20/HackTogether---AccuVision
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
339 lines (301 loc) · 14.5 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
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
# importing all the required libraries
import dash
import dash_core_components as dcc
import dash_html_components as html
import pandas as pd
import time
import plotly.io as pio
import plotly.express as px
import plotly.graph_objects as go
from dash.dependencies import Input, Output
from dayGetter import get_day
# Setting the template for the graph to a pre-defined plotly theme.
pio.templates.default = 'plotly_dark'
# Starting the app
app = dash.Dash(__name__)
app.config.suppress_callback_exceptions = True
# Title for the website.
app.title = "AccuVision"
bestTime = ""
bestDay = ""
currentCount = ""
# Reading data from Google Sheets using Pandas through URLs as CSV files and storing as data frames.
WalShaw_Current = pd.read_csv(
"https://docs.google.com/spreadsheets/d/1F-fvele1EorJJ6Vdm8T5gG3lOP_hapmwyIoXEZIeZ6A/export?gid=496819679&format=csv", index_col=None)
WalShaw_Previous = pd.read_csv(
"https://docs.google.com/spreadsheets/d/1ii_78RxFOF98gipDtC_31VMzUhAfYvOd69R1a3f098A/export?gid=688427654&format=csv", index_col=None)
CostcoHeritage_Current = pd.read_csv(
"https://docs.google.com/spreadsheets/d/1Fh37SZr6vFYi-1GGrdAsSrYB8Vv1VGhKWJUeyp981zA/export?gid=1224033525&format=csv", index_col=None)
CostcoHeritage_Previous = pd.read_csv(
"https://docs.google.com/spreadsheets/d/1dB_NgzL0c5qBn1A3y2rPkRcBDTfSYofg6F0BuZ8eFsk/export?gid=583703077&format=csv", index_col=None)
YMCAShaw_Previous = pd.read_csv(
"https://docs.google.com/spreadsheets/d/1agLC1TUQz2N_9vle5FXpVZ5lAieVDgidTVmqKw4JbZk/export?gid=1278973156&format=csv", index_col=None)
YMCAShaw_Current = pd.read_csv(
"https://docs.google.com/spreadsheets/d/1SQOCXvnZUW74ES4R-37HorE3A2_-hnrxnvjq_A1fLK4/export?gid=1144356892&format=csv", index_col=None)
week1 = pd.read_csv(
"https://docs.google.com/spreadsheets/d/1hgcC3dLOoQFVB5-EbkkKNQlFo5GQrcCFzzOsmUSUSWY/export?format=csv", index_col=None)
# Approximate areas of buildings obtained through Google Maps measuring app.
WalShaw_Area = 14519
CostcoHeritage_Area = 13576
YMCAShaw_Area = 6028
# Using dayGetter.py to obtain the day of the week.
day = get_day()[0]
daysOfWeek = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
# This is where the HTML5 is incorporated through the .layout backbone of plotly.
app.layout = html.Div(
children=[
html.Div([
# Logo and title.
html.Div(id="title"),
html.Img(src="assets/Accuvision_Logo_v3.png",
height="70", width="220.925"),
html.H1("AccuVision")
]),
#Introductory message.
html.H4(""" In these times of uncertainty during the COVID-19 pandemic, the necessity for limiting public contact is greater than ever.
In order to assist you with doing so, AccuVision provides real-time data about the number of people within an establishment at
any given point over the course of the current and past week. We hope AccuVision helps you stay safe in these unprecedented times.""",
title='Introduction to AccuVision',
className='text_area'),
html.Div(children=[
html.Div([
# Dropdown to select from the establishment that user would like to view data for.
dcc.Dropdown(
id="buildingSelector",
options=[
{"label": "Costco Heritage", "value": "Costco-Heritage"},
{"label": "Walmart Shawnessy",
"value": "Walmart-Shawnessy"},
{"label": "YMCA Shawnessy", "value": "YMCA-Shawnessy"}
],
placeholder="Select a Building",
clearable=False,
className='dropdown',
searchable=False,
# Default selected establishment in this code is YMCA-Shawnessy (customizable).
value = "Walmart-Shawnessy"
),
# Dropdown to select the day of the week as another required filter.
dcc.Dropdown(
# id that will link dropdown menu to input for callbacks.
id="daySelector",
# Creating labels and values for the labels that are linked to the csv file.
options=[
{"label": "Saturday", "value": "Saturday"},
{"label": "Sunday", "value": "Sunday"},
{"label": "Monday", "value": "Monday"},
{"label": "Tuesday", "value": "Tuesday"},
{"label": "Wednesday", "value": "Wednesday"},
{"label": "Thursday", "value": "Thursday"},
{"label": "Friday", "value": "Friday"}
],
# Enables multiple graphs to be displayed and overlayed for better comparison.
multi=True,
# Default value is set to the current day of the week.
value=day,
placeholder="Select a Day",
searchable=False,
clearable=True,
className='dropdown',
),
# Slider for selecting which week's information is to be viewed. For demo purposes, both weeks are pre-filled,
# however upon deployment, the weekly information will be filled as time progresses.
dcc.Slider(id="weekGetter",
min=1,
max=2,
# Default value is set to display previous week information.
value=1,
marks={
1: {'label': 'Previous Week', 'style': {'color': '#fff'}},
2: {'label': 'Current Week', 'style': {'color': '#fff'}},
},
className='slider',
)
], className="left_side"),
# Div element for the graph. The id is used as output in the callback according to the filters selected.
html.Div([
dcc.Graph(id='ourGraph'),
], className="right_side"),
], className="side_by_side"),
# The div element which contains the general information displayed based on the filters selected
html.Div(children = [
html.Div([
html.P(id="generalInfo", children=True),
], className = 'left_side2'),
html.Div([
html.H4('Select a range below using the slider to determine the day which has the least traffic in the specified time:', className = 'selectRangeText'),
html.Div([
html.H5('From:', title='Range (From)', className='from'),
html.H5('To:', title='Range (To)', className='to'),
], className = 'FromToTitle'),
dcc.RangeSlider(
min = 6,
max = 23,
value=[6, 23],
id = "predictiveDay",
marks={
6: {'label': '6:00',},
7: {'label': '7:00',},
8: {'label': '8:00',},
9: {'label': '9:00',},
10: {'label': '10:00',},
11: {'label': '11:00',},
12: {'label': '12:00',},
13: {'label': '13:00',},
14: {'label': '14:00',},
15: {'label': '15:00',},
16: {'label': '16:00',},
17: {'label': '17:00',},
18: {'label': '18:00',},
19: {'label': '19:00',},
20: {'label': '20:00',},
21: {'label': '21:00',},
22: {'label': '22:00',},
23: {'label': '23:00',},
},
),
html.P(id = 'predictBestDay', children = True)
], className = "right_side2"),
], className = 'side_by_side2'),
],
# Added styling to be able to display side by side for a better user experience.
id="mainContainer", style={"display": "flex", "flex-direction": "column"})
# First callback. This is to display the graph based on the inputs selected.
@app.callback(
Output('ourGraph', 'figure'),
Input('daySelector', 'value'),
Input('weekGetter', 'value'),
Input('buildingSelector', 'value')
)
def update_graph(day, week, building):
# Changing the CSV based on the building selected.
sheetToReadFrom_Previous = WalShaw_Previous
sheetToReadFrom_Current = WalShaw_Current
if building == "Costco-Heritage":
sheetToReadFrom_Previous = CostcoHeritage_Previous
sheetToReadFrom_Current = CostcoHeritage_Current
elif building == "YMCA-Shawnessy":
sheetToReadFrom_Previous = YMCAShaw_Previous
sheetToReadFrom_Current = YMCAShaw_Current
# If nothing is selected, don't display anything.
if len(day) == 0:
day = "None"
# X-axis of graph is Time of Day from csv file, and the y-axis is the day(s) that are selected.
if week == 1:
fig = px.line(sheetToReadFrom_Previous, x="Time of Day", y=day,
title="Number of People in Building at Different Times")
if week == 2:
fig = px.line(sheetToReadFrom_Current, x="Time of Day", y=day,
title="Number of People in Building at Different Times")
# Updating y-axis title and the legend title.
fig.update_layout(yaxis_title="Number of People")
fig.update_layout(legend_title="Day of Week")
return fig
# Second callback to the paragraph tag where the output is dependent of the filters chosen by the user.
@app.callback(
Output('generalInfo', 'children'),
Input('daySelector', 'value'),
Input('buildingSelector', 'value')
)
def update_info(day, building):
buildingArea = WalShaw_Area
#Determining which Google Sheets to read from based on the input of the building
#With Walmart-Shawnessy as the current default.
sheetToReadFrom_Previous = WalShaw_Previous
if building == "Costco-Heritage":
sheetToReadFrom_Previous = CostcoHeritage_Previous
buildingArea = CostcoHeritage_Area
elif building == "YMCA-Shawnessy":
sheetToReadFrom_Previous = YMCAShaw_Previous
buildingArea = YMCAShaw_Area
oneDay = True
if len(day) != 1:
oneDay = False
if isinstance(day, str) == True:
oneDay = True
if oneDay == False:
return "Select a day to display general information about it."
else:
#This returns a string which provides the user the day in the previous week which contained the least number of people in total.
indexOfSuggestedDay = dayWithLeast(day, building, sheetToReadFrom_Previous)
liveCounter = displayLiveCounter(day, building, sheetToReadFrom_Previous)
return f"""Currently, there are {displayLiveCounter(day, building, sheetToReadFrom_Previous):.0f} people in {building}.\nAccording to last week's data, the day with the least number of visitors in {building} was: {daysOfWeek[indexOfSuggestedDay]}.\nEach current visitor in {building} has {buildingArea/liveCounter:.0f} m²/person space."""
@app.callback(
Output('predictBestDay', 'children'),
Input('buildingSelector', 'value'),
Input('predictiveDay', 'value')
)
def predictiveDayUpdate(building, timeSelected):
timeSelected = [f"{timeSelected[0]}:00", f"{timeSelected[1]}:00"]
sheetToReadFrom_Previous = WalShaw_Previous
if building == "Costco-Heritage":
sheetToReadFrom_Previous = CostcoHeritage_Previous
elif building == "YMCA-Shawnessy":
sheetToReadFrom_Previous = YMCAShaw_Previous
return f"""Based on your inputs, {daysOfWeek[predictiveRange(building, sheetToReadFrom_Previous, timeSelected)]} was the day
last week in which there were the fewest number of people in {building}."""
def dayWithLeast(day, building, sheetToReadFrom_Previous):
prevmon = sheetToReadFrom_Previous['Monday'].sum()
prevtue = sheetToReadFrom_Previous['Tuesday'].sum()
prevwed = sheetToReadFrom_Previous['Wednesday'].sum()
prevthu = sheetToReadFrom_Previous['Thursday'].sum()
prevfri = sheetToReadFrom_Previous['Friday'].sum()
prevsat = sheetToReadFrom_Previous['Saturday'].sum()
prevsun = sheetToReadFrom_Previous['Sunday'].sum()
bigday = (prevmon, prevtue, prevwed, prevthu, prevfri, prevsat, prevsun)
dayIndex = bigday.index(min(bigday))
return dayIndex
def displayLiveCounter(day, building, sheetToReadFrom_Previous):
#Finding the total number of lines so as to read the most recent counter value
lastLine = len(sheetToReadFrom_Previous)
#Based on the day, get the column number to read from a specific cell
if day == "Monday":
dayIndex = 1
elif day == "Tuesday":
dayIndex = 2
elif day == "Wednesday":
dayIndex = 3
elif day == "Thursday":
dayIndex = 4
elif day == "Friday":
dayIndex = 5
elif day == "Saturday":
dayIndex = 6
elif day == "Sunday":
dayIndex = 7
else:
dayIndex = 8
#Returning the most recent counter value
return sheetToReadFrom_Previous.iloc[1046 - 1, dayIndex]
def predictiveRange(building, sheetToReadFrom_Previous, timeSelected):
input1="{x}".format(x=timeSelected[0])
input2="{y}".format(y=timeSelected[1])
prevmonT = pd.DataFrame(sheetToReadFrom_Previous['Monday'])
prevmonT.loc[input1:input2]
a = prevmonT.sum()
prevtueT = pd.DataFrame(sheetToReadFrom_Previous['Tuesday'])
prevtueT.loc[input1:input2]
b = prevtueT.sum()
prevwedT = pd.DataFrame(sheetToReadFrom_Previous['Wednesday'])
prevwedT.loc[input1:input2]
c = prevwedT.sum()
prevthuT = pd.DataFrame(sheetToReadFrom_Previous['Thursday'])
prevthuT.loc[input1:input2]
d = prevthuT.sum()
prevfriT = pd.DataFrame(sheetToReadFrom_Previous['Friday'])
prevfriT.loc[input1:input2]
e = prevfriT.sum()
prevsatT = pd.DataFrame(sheetToReadFrom_Previous['Saturday'])
prevsatT.loc[input1:input2]
f = prevsatT.sum()
prevsunT = pd.DataFrame(sheetToReadFrom_Previous['Sunday'])
prevsunT.loc[input1:input2]
g = prevsunT.sum()
bestOptions = (float(a.to_string(index = False)),float(b.to_string(index = False)),
float(c.to_string(index = False)),float(d.to_string(index = False)),
float(e.to_string(index = False)),float(f.to_string(index = False)),float(g.to_string(index = False)))
bestOption = bestOptions.index(min(bestOptions))
return bestOption
# Running it
if __name__ == "__main__":
app.run_server(debug=False)