-
Notifications
You must be signed in to change notification settings - Fork 2
/
app.py
518 lines (457 loc) · 22.8 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
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
import dash
from flask import Flask
import dash_core_components as dcc
import dash_html_components as html
from pyspark.sql.functions import col
from dash.dependencies import Input, Output
from pyspark.sql import SparkSession, functions
from forecasting.forecasting import crime_forecasting
from arrests_history.arrests_history import arrest_history
from area_wise_analysis.ward_level_analysis import ward_analysis
from severity_deduction.crime_severity import severity_deduction
from chicago_wordcloud.chicago_wordcloud import generate_wordcloud
from area_wise_analysis.district_level_analysis import district_analysis
from area_wise_analysis.communityarea_level_analysis import communityarea_analysis
from data_operations.data_operations import get_cassandra_table, generate_master_tables, generate_tables
"""
# Command to run the file (makes connection to cassandra database)
spark-submit --packages datastax:spark-cassandra-connector:2.4.0-s_2.11 app.py
"""
app = Flask(__name__)
cluster_seeds = ['127.0.0.1']
spark = SparkSession.builder.appName('Chicago Crime Analysis').config('spark.cassandra.connection.host',\
','.join(cluster_seeds)).getOrCreate()
sc = spark.sparkContext
# Our cassandra keyspace
KEYSPACE = 'pirates'
"""
## Run ETL on RAW DATA and generate master table in cassandra
generate_master_tables(format='cassandra', truncate='no', drop_table='no')
## Run all data operations and generate child tables
generate_tables(format='cassandra')
## Generate Word Cloud
generate_wordcloud()
## Generate severity deduction
severity_deduction(KEYSPACE='pirates')
## Generate Arrest history
arrest_history()
#Generate Area-wise Arrest Analysis
ward_analysis()
district_analysis()
communityarea_analysis()
#Crime Forecasting
crime_forecasting()
"""
## Get data from cassandra
hourly_major_crime = get_cassandra_table(table_name='hourly_major_crime', KEYSPACE='pirates')
crime_2010 = get_cassandra_table(table_name='crime_2010', KEYSPACE='pirates')
crime_2011 = get_cassandra_table(table_name='crime_2011', KEYSPACE='pirates')
crime_2012 = get_cassandra_table(table_name='crime_2012', KEYSPACE='pirates')
crime_2013 = get_cassandra_table(table_name='crime_2013', KEYSPACE='pirates')
crime_2014 = get_cassandra_table(table_name='crime_2014', KEYSPACE='pirates')
crime_2015 = get_cassandra_table(table_name='crime_2015', KEYSPACE='pirates')
crime_2016 = get_cassandra_table(table_name='crime_2016', KEYSPACE='pirates')
crime_2017 = get_cassandra_table(table_name='crime_2017', KEYSPACE='pirates')
crime_2018 = get_cassandra_table(table_name='crime_2018', KEYSPACE='pirates')
geo_crime = get_cassandra_table(table_name='geolocation', KEYSPACE='pirates')
# Crime count month wise for different years
count_all_2010 = crime_2010.groupBy('month_number').agg(functions.sum('count').alias('cnt')).sort('month_number')
count_all_2010_list = [int(row.cnt) for row in count_all_2010.collect()]
count_all_2011 = crime_2011.groupBy('month_number').agg(functions.sum('count').alias('cnt')).sort('month_number')
count_all_2011_list = [int(row.cnt) for row in count_all_2011.collect()]
count_all_2012 = crime_2012.groupBy('month_number').agg(functions.sum('count').alias('cnt')).sort('month_number')
count_all_2012_list = [int(row.cnt) for row in count_all_2012.collect()]
count_all_2013 = crime_2013.groupBy('month_number').agg(functions.sum('count').alias('cnt')).sort('month_number')
count_all_2013_list = [int(row.cnt) for row in count_all_2013.collect()]
count_all_2014 = crime_2014.groupBy('month_number').agg(functions.sum('count').alias('cnt')).sort('month_number')
count_all_2014_list = [int(row.cnt) for row in count_all_2014.collect()]
count_all_2015 = crime_2015.groupBy('month_number').agg(functions.sum('count').alias('cnt')).sort('month_number')
count_all_2015_list = [int(row.cnt) for row in count_all_2015.collect()]
count_all_2016 = crime_2016.groupBy('month_number').agg(functions.sum('count').alias('cnt')).sort('month_number')
count_all_2016_list = [int(row.cnt) for row in count_all_2016.collect()]
count_all_2017 = crime_2017.groupBy('month_number').agg(functions.sum('count').alias('cnt')).sort('month_number')
count_all_2017_list = [int(row.cnt) for row in count_all_2017.collect()]
count_all_2018 = crime_2018.groupBy('month_number').agg(functions.sum('count').alias('cnt')).sort('month_number')
count_all_2018_list = [int(row.cnt) for row in count_all_2018.collect()]
# Creating essential lists
am_pm = list(hourly_major_crime.select('am_pm').distinct().toPandas()['am_pm'])
crimes = list(hourly_major_crime.select('crimetype').distinct().toPandas()['crimetype'])
month_list = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
year_list = list(geo_crime.select('year').distinct().toPandas()['year'])
# geo crime data for scatter map box/geo crime density
geo_df = geo_crime.select('latitude', 'longitude', 'crimetype', 'year').cache()
# Integrating Flask on top of Dash server
dashapp = dash.Dash(__name__, server= app, url_base_pathname='/')
#Switching to multiple tabs. Allowed callbacks outside of Main Layout
dashapp.config['suppress_callback_exceptions'] = True
#Tab styling
tabs_styles = {
'height': '44px'
}
tab_style = {
'borderBottom': '1px solid #d6d6d6',
'padding': '6px',
'fontWeight': 'bold'
}
tab_selected_style = {
'borderTop': '1px solid #d6d6d6',
'borderBottom': '1px solid #d6d6d6',
'backgroundColor': '#119DFF',
'color': 'white',
'padding': '6px'
}
#Webapp layout
with app.app_context():
dashapp.layout = html.Div(
children=[
html.Div([
# --header section
html.Div([
html.H2('Chicago Crime Analysis'),
], style={'text-align': 'center', 'width': '100%', 'display': 'inline-block', 'vertical-align': 'middle','font-family':'Helvetica'}),
dcc.Tabs(id="tabs-example", value='interactive', children=[
dcc.Tab(label='Interactive Visualizations', value='interactive', style=tab_style, selected_style=tab_selected_style),
dcc.Tab(label='WordCloud', value='wordcloud', style=tab_style, selected_style=tab_selected_style),
dcc.Tab(label='Forecasting', value='forecasting', style=tab_style, selected_style=tab_selected_style),
dcc.Tab(label="Static Visualizations", value="static", style=tab_style, selected_style=tab_selected_style)
], style=tabs_styles),
html.Div(id='tabs-content-example')
],style={'width': '100%','background-position': 'initial initial', 'background-repeat': 'initial initial'},
)
], style={'background-image': 'url("./static/images/chicago.jpg")'})
#Render pageview according to tabs
@dashapp.callback(Output('tabs-content-example', 'children'),
[Input('tabs-example', 'value')])
def render_content(tab):
if tab == 'interactive':
return html.Div([
html.Div([
html.Div([
html.P(
'Crime Type',
className="control_label",
style={
'textAlign': 'center'
}
),
dcc.Dropdown(
id='crimetype-column',
options=[{'label': i, 'value': i} for i in crimes],
value='robbery'
),
],
style={'width': '25%', 'display': 'inline-block'}),
html.Div([
html.P(
'Day Timing',
className="control_label",
style={
'textAlign': 'center'
}
),
dcc.Dropdown(
id='day-night-column',
options=[{'label': i, 'value': i} for i in am_pm],
value='AM'
),
], style={'width': '25%', 'display': 'inline-block'}),
html.Div([
dcc.Checklist(id="list_all_crime",
options=[{'label': 'All Crime', 'value': 'all'}]),
], style={'width': '20%', 'float':'right','padding': '60px 50px 0px 30px'}),
],
style={
'borderBottom': 'thin lightgrey solid',
'backgroundColor': 'rgb(250, 250, 250)',
'padding': '10px 5px'
}),
html.Div([
html.Div([
dcc.Graph(id='x-time-series')
], style={'display': 'inline-block', 'width': '47%', 'margin-left': '2.5%'}, className='six columns'),
html.Div([
dcc.Graph(id='x-month-series')
], style={'display': 'inline-block', 'width': '47%', 'margin-left': '1.2%'}, className='six columns'),
], className='row',style={'padding': '10px 5px'}),
html.Div([
html.P(
'Drag the slider to change the year',
className="control_label",
style={
'textAlign': 'center'
}
),
dcc.Slider(
id='year-slider',
min=min(year_list),
max=max(year_list),
value=max(year_list),
marks={str(year): str(year) for year in year_list},
step=None
),
], style={'width': '50%', 'margin-left': '25%', 'padding': '0px 20px 20px 20px',
'borderBottom': 'thin lightgrey solid',
'backgroundColor': 'rgb(250, 250, 250)'}),
html.Div([
dcc.Graph(id='my-graph')
], style={'display': 'block', 'width': '70%', 'margin-left': '10%', 'padding': '30px 20px 20px 20px'}),
], style={'margin-top': '10px'})
elif tab == 'wordcloud':
return html.Div([
html.Div([
html.P(
'WordCloud based on Crime Type',
className="control_label",
style={'textAlign': 'center','width': '50%', 'margin-left': '25%', 'padding': '10px 10px 10px 10px', 'borderBottom': 'thin lightgrey solid',
'backgroundColor': 'rgb(250, 250, 250)','font-family':'Helvetica','font-size':'18px'}
),
html.Img(src="./static/images/wc_crimetype.png",style={'width':'98%','height':'800px'})
], style={'display': 'inline-block', 'width': '49%'}, className='six columns'),
html.Div([
html.P(
'WordCloud based on Crime Location ',
className="control_label",
style={'textAlign': 'center', 'width': '50%', 'margin-left': '25%',
'padding': '10px 10px 10px 10px', 'borderBottom': 'thin lightgrey solid',
'backgroundColor': 'rgb(250, 250, 250)', 'font-family': 'Helvetica', 'font-size': '18px'}
),
html.Img(src="./static/images/wc_location_description.png",style={'width':'98%','height':'800px'})
], style={'display': 'inline-block', 'width': '49%'}, className='six columns'),
], className='row',
style={
'padding': '10px 5px',
'margin-left':'3%',
'margin-top': '10px'
})
elif tab == 'forecasting':
return html.Div([
html.Div([
html.P(
'Crime forecast for 2019',
className="control_label",
style={'textAlign': 'center', 'width': '50%', 'margin-left': '25%',
'padding': '10px 10px 10px 10px', 'borderBottom': 'thin lightgrey solid',
'backgroundColor': 'rgb(250, 250, 250)', 'font-family': 'Helvetica', 'font-size': '18px'}
),
html.Img(src="./static/images/forecasting/forecast.png", style={'width': '98%', 'height': '500px'})
], style={'display': 'inline-block', 'width': '60%', 'margin-left': '20%'}),
html.Div([
html.P(
'Crime Rate Trend over years',
className="control_label",
style={'textAlign': 'center', 'width': '50%', 'margin-left': '25%',
'padding': '10px 10px 10px 10px', 'borderBottom': 'thin lightgrey solid',
'backgroundColor': 'rgb(250, 250, 250)', 'font-family': 'Helvetica', 'font-size': '18px'}
),
html.Img(src="./static/images/forecasting/trends.png", style={'width': '98%', 'height': '500px'})
], style={'display': 'inline-block', 'width': '60%', 'margin-left': '20%'}),
], style={
'padding': '10px 5px',
'margin-left': '3%',
'margin-top': '10px'
}),
elif tab == 'static':
return html.Div([
html.Div([
html.Div([
html.Img(src="./static/images/crime_severity.png",style={'width':'60%','height':'500px'})
], style={'display': 'inline-block', 'width': '100%','margin-left':'20%'}),
]),
html.Div([
html.Div([
html.Img(src="./static/images/percentageofarrests.png", style={'width': '98%', 'height': '600px'})
], style={'display': 'inline-block', 'width': '49%'}, className='six columns'),
html.Div([
html.Img(src="./static/images/successfularrests.png", style={'width': '98%', 'height': '600px'})
], style={'display': 'inline-block', 'width': '49%'}, className='six columns'),
], className='row',
style={
'padding': '10px 5px',
'margin-left': '3%'
}),
html.Div([
html.Img(src="./static/images/district_static.png", style={'width': '60%', 'height': '600px'})
], style={'display': 'inline-block', 'width': '100%', 'margin-left': '20%'}),
html.Div([
html.Img(src="./static/images/ward_static.png",
style={'width': '60%', 'height': '600px'})
], style={'display': 'inline-block', 'width': '100%', 'margin-left': '20%'}),
html.Div([
html.Img(src="./static/images/communityarea_static.png",
style={'width': '60%', 'height': '600px'})
], style={'display': 'inline-block', 'width': '100%', 'margin-left': '20%'}),
html.Div([
html.Div([
html.P(
'Crime Location vs Count',
className="control_label",
style={'textAlign': 'center', 'width': '50%', 'margin-left': '25%',
'padding': '10px 10px 10px 10px', 'borderBottom': 'thin lightgrey solid',
'backgroundColor': 'rgb(250, 250, 250)', 'font-family': 'Helvetica', 'font-size': '18px'}
),
html.Img(src="./static/images/location_description_count.png",
style={'width': '98%', 'height': '600px'})
], style={'display': 'inline-block', 'width': '49%'}, className='six columns'),
html.Div([
html.P(
'Crime Type vs Count',
className="control_label",
style={'textAlign': 'center', 'width': '50%', 'margin-left': '25%',
'padding': '10px 10px 10px 10px', 'borderBottom': 'thin lightgrey solid',
'backgroundColor': 'rgb(250, 250, 250)', 'font-family': 'Helvetica', 'font-size': '18px'}
),
html.Img(src="./static/images/theft_count.png", style={'width': '98%', 'height': '600px'})
], style={'display': 'inline-block', 'width': '49%'}, className='six columns'),
], className='row',
style={
'padding': '10px 5px',
'margin-left': '3%'
}),
], style={'margin-top': '10px'})
def create_time_series(dff, title):
return {
'data': [dict(
x=list(dff.select('hour_info').toPandas()['hour_info']),
y=list(dff.select('count').toPandas()['count']),
mode='lines+markers'
)],
'layout': {
'height': 350,
'margin': {'l': 40, 'b': 30, 'r': 10, 't': 40},
'annotations': [{
'x': 0, 'y': 0.85, 'xanchor': 'left', 'yanchor': 'bottom',
'xref': 'paper', 'yref': 'paper', 'showarrow': False,
'align': 'center', 'bgcolor': 'rgba(255, 255, 255, 0.5)',
'text': title
}],
'title' : "Hourly intensity of " + title.capitalize(),
'xaxis': {
'title': "Time",
},
'yaxis': {
'title': "Count",
},
}
}
#Return hourly count of crime
@dashapp.callback(
Output('x-time-series', 'figure'),
[Input('crimetype-column', 'value'),
Input('day-night-column', 'value'),
])
def update_crime_day_night_timeseries(xaxis_column_name, yaxis_column_name):
dff = hourly_major_crime.filter(hourly_major_crime['crimetype'] == xaxis_column_name).filter(hourly_major_crime['am_pm'] == yaxis_column_name).sort('hour_info')
title = '{}'.format(xaxis_column_name)
return create_time_series(dff,title)
#Return coordinates for crime in various years
@dashapp.callback(
Output('my-graph', 'figure'),
[Input('crimetype-column', 'value'),
Input('year-slider', 'value')])
def update_geo_graph(crimetype,year):
dff = geo_df.filter(geo_df['year'] == year).filter(geo_df['crimetype'] == crimetype)
return {
'data': [{
'lat': list(dff.select('latitude').toPandas()['latitude']),
'lon': list(dff.select('longitude').toPandas()['longitude']),
'type': 'scattermapbox',
}],
'layout': {'mapbox': {'accesstoken': 'pk.eyJ1IjoiZGFya2xvcmQwNyIsImEiOiJjazNlODhjN2cwMG9mM2ltOGVjMDJhbjRoIn0.dSTEqXzCSY69cWjdklL-HQ','bearing':0,
'pitch':0,'zoom':9,'center':{'lat':41.88,'lon':-87.67}},'width':1000,'height':600,'title' : "Crime Density of " + crimetype.capitalize() +" in " + str(year)}
}
#Plotting month time series
def create_month_series(dff,title,year):
return {
'data': [dict(
x=month_list,
y=dff,
mode='lines+markers'
)],
'layout': {
'height': 350,
'margin': {'l': 40, 'b': 30, 'r': 10, 't': 40},
'annotations': [{
'x': 0, 'y': 0.85, 'xanchor': 'left', 'yanchor': 'bottom',
'xref': 'paper', 'yref': 'paper', 'showarrow': False,
'align': 'left', 'bgcolor': 'rgba(255, 255, 255, 0.5)',
'text': title
}],
'title': "Analysis of " + title.capitalize() + " in " + str(year),
'xaxis':{
'title': "Month",
},
'yaxis' : {
'title': "Count",
},
}
}
# Return monthly count of different crime types
@dashapp.callback(
Output('x-month-series', 'figure'),
[Input('crimetype-column', 'value'),
Input('year-slider', 'value'),
Input('list_all_crime', 'value')
])
def update_month_timeseries(xaxis_column_name, yaxis_column_name, all_crime_checkbox):
if yaxis_column_name == 2010:
if all_crime_checkbox:
crime_theft_list = count_all_2010_list
else:
crime_theft = crime_2010.select('month_number', 'crimetype', col('count').alias('cnt')).filter(crime_2010['crimetype'] == xaxis_column_name).sort('month_number')
crime_theft_list = [int(row.cnt) for row in crime_theft.collect()]
elif yaxis_column_name == 2011:
if all_crime_checkbox:
crime_theft_list = count_all_2011_list
else:
crime_theft = crime_2011.select('month_number', 'crimetype', col('count').alias('cnt')).filter(crime_2011['crimetype'] == xaxis_column_name).sort('month_number')
crime_theft_list = [int(row.cnt) for row in crime_theft.collect()]
elif yaxis_column_name == 2012:
if all_crime_checkbox:
crime_theft_list = count_all_2012_list
else:
crime_theft = crime_2012.select('month_number', 'crimetype', col('count').alias('cnt')).filter(crime_2012['crimetype'] == xaxis_column_name).sort('month_number')
crime_theft_list = [int(row.cnt) for row in crime_theft.collect()]
elif yaxis_column_name == 2013:
if all_crime_checkbox:
crime_theft_list = count_all_2013_list
else:
crime_theft = crime_2013.select('month_number', 'crimetype', col('count').alias('cnt')).filter(crime_2013['crimetype'] == xaxis_column_name).sort('month_number')
crime_theft_list = [int(row.cnt) for row in crime_theft.collect()]
elif yaxis_column_name == 2014:
if all_crime_checkbox:
crime_theft_list = count_all_2014_list
else:
crime_theft = crime_2014.select('month_number', 'crimetype', col('count').alias('cnt')).filter(crime_2014['crimetype'] == xaxis_column_name).sort('month_number')
crime_theft_list = [int(row.cnt) for row in crime_theft.collect()]
elif yaxis_column_name == 2015:
if all_crime_checkbox:
crime_theft_list = count_all_2015_list
else:
crime_theft = crime_2015.select('month_number', 'crimetype', col('count').alias('cnt')).filter(crime_2015['crimetype'] == xaxis_column_name).sort('month_number')
crime_theft_list = [int(row.cnt) for row in crime_theft.collect()]
elif yaxis_column_name == 2016:
if all_crime_checkbox:
crime_theft_list = count_all_2016_list
else:
crime_theft = crime_2016.select('month_number', 'crimetype', col('count').alias('cnt')).filter(crime_2016['crimetype'] == xaxis_column_name).sort('month_number')
crime_theft_list = [int(row.cnt) for row in crime_theft.collect()]
elif yaxis_column_name == 2017:
if all_crime_checkbox:
crime_theft_list = count_all_2017_list
else:
crime_theft = crime_2017.select('month_number', 'crimetype', col('count').alias('cnt')).filter(crime_2017['crimetype'] == xaxis_column_name).sort('month_number')
crime_theft_list = [int(row.cnt) for row in crime_theft.collect()]
else:
if all_crime_checkbox:
crime_theft_list = count_all_2018_list
else:
crime_theft = crime_2018.select('month_number', 'crimetype', col('count').alias('cnt')).filter(crime_2018['crimetype'] == xaxis_column_name).sort('month_number')
crime_theft_list = [int(row.cnt) for row in crime_theft.collect()]
if all_crime_checkbox:
title = '{}'.format('all crimes')
else:
title = '{}'.format(xaxis_column_name)
return create_month_series(crime_theft_list, title,yaxis_column_name)
#Run Flask server
if __name__ == '__main__':
app.run()