Advertisement
Guest User

Untitled

a guest
Mar 20th, 2019
154
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.73 KB | None | 0 0
  1. #import flask and required functions
  2. from flask import Flask, render_template, request
  3. #import pandas
  4. import pandas as pd
  5. #standar library imports
  6. import contextlib
  7. import errno
  8. import os
  9. import sys
  10. import warnings
  11. #import bokeh components
  12. from bokeh.embed import server_document,components
  13. from bokeh.layouts import column,widgetbox
  14. from bokeh.models import ColumnDataSource,HoverTool,GMapPlot, GMapOptions, ColumnDataSource, Circle, DataRange1d, Select
  15. from bokeh.server.server import Server
  16. from tornado.ioloop import IOLoop
  17. from bokeh.io import curdoc
  18. from bokeh.plotting import *
  19. from bokeh.application import Application
  20. from bokeh.application.handlers import ScriptHandler, DirectoryHandler, NotebookHandler
  21.  
  22. #define flask application
  23. app = Flask(__name__)
  24.  
  25. def build_single_handler_applications(paths, argvs=None):
  26.     applications = {}
  27.     argvs = {} or argvs
  28.     for path in paths:
  29.         application = build_single_handler_application(path, argvs.get(path, []))
  30.         route = application.handlers[0].url_path()
  31.         if not route:
  32.             if '/' in applications:
  33.                 raise RuntimeError("Don't know the URL path to use for %s" % (path))
  34.         route = '/'
  35.         applications[route] = application
  36.     return applications
  37. #addmod map function
  38. def modMap(doc):
  39.     #open excel file
  40.     file = pd.ExcelFile("C:\\Users\\Dell1525\\Desktop\\project\\dataset3Geo.xlsx",parse_dates=['Year'])
  41.     #parse the first sheet in ecel file
  42.     dataset2 = file.parse('Sheet1')
  43.     #formate date comlumn
  44.     dataset2['Year'] = pd.to_datetime(dataset2['Year']).apply(lambda x:x.strftime('%Y'))
  45.     #create data source for column data
  46.     dataPoints = ColumnDataSource(data=dataset2)
  47.     #add tools and map options
  48.     tools='pan','wheel_zoom','reset','hover'
  49.     map_options = GMapOptions(lat=54.794953, lng=-6.817343, map_type='roadmap', zoom=8)
  50.     api_key = ''
  51.     #create plot on gmap
  52.     p = gmap(api_key, map_options, title="Crime Map of Northern Ireland",tools=tools)  
  53.     r = p.circle(x="Long", y="Lat", size=15, fill_color="blue", fill_alpha=0.8, source=dataPoints)  
  54.     #create simple selection widgets
  55.     selecYear = Select(options = ['2017','2016','2015','2014','2013','2012','2011','2010','2009','2008','2007','2006','2005','2004','2003','2002','2001'],value = '2017', title = 'Select The Year ')
  56.     crimeSelect = Select(options = ['All Cimes','Violent Offences','Burglary','Theft','Criminal Damage','Drug Offences','Other Offences'],value='Violence with injury',title='Select Crime:')
  57.     #perform exploratory data analysis based on users input
  58.     def select_callback(attr, old,new):
  59.         selectedYear = selecYear.value
  60.         selectedCrime = crimeSelect.value
  61.     if selecYear.value == selectedYear or crimeSelect.value == selectedCrime:  
  62.         newYear = dataset2[dataset2['Year'] == selectedYear]
  63.         newCrimesinYear = newYear[newYear['CrimeType'] == selectedCrime]
  64.         newdata = ColumnDataSource(newCrimesinYear)
  65.         r.data_source.data=newdata.data
  66.     #add new data hover tooltips
  67.     p.hover.tooltips=[('Year','@Year'),('Area','@Area'),('CrimeType','@CrimeType'),('Recorded Offences','@RecordedOffences')]
  68.     selecYear.on_change('value',select_callback)
  69.     crimeSelect.on_change('value',select_callback)
  70.     #add elements to application
  71.     doc.add_root(selectedYear,selectedCrime,p)
  72.    
  73. #create main timeseries plot
  74. def modifyTimeSeries(doc):
  75.     #import pandas for data management
  76.     import pandas as pd
  77.     #open excel file
  78.     file = pd.ExcelFile("C:\\Users\\Dell1525\\Desktop\\project\\newdataset2.xlsx",parse_dates=['Date'])
  79.     #parse the first sheet in ecel file
  80.     dataset2 = file.parse('Sheet1')
  81.     #create data source for column data
  82.     dataPoints = ColumnDataSource(dataset2)
  83.     #create default chart and line
  84.     p = figure(title= "Recorded Crimes Sep 2016 to Aug 2018", y_axis_type="linear",x_axis_type="datetime",
  85.           plot_height=500,plot_width=500)  
  86.     p.line(x = 'Date', y = 'RecordedOffences', source = dataPoints, color = 'red')
  87.     #callback method which will change slider values
  88.     def callback(attr, old,new):
  89.         selectedTown = select_widget1.value
  90.     selectedCrime = select_widget2.value
  91.     if select_widget1.value == selectedTown or select_widget2.value == selectedCrime:  
  92.         newTown = dataset2[dataset2['PolicingDistrict'] == selectedTown]
  93.         newCrimeinTown = newTown[newTown['CrimeType'] == selectedCrime]
  94.         #column data source for plot
  95.         dataPoints.data = ColumnDataSource(newCrimeinTown).data
  96.     select_widget1 = Select(options = ['Belfast','Lisburn','Ards','Newry','Armagh','Dungannon','Omagh','Londonderry','Antrim','Newtownabbey'],value = 'Belfast', title = 'Select Policing District ')
  97.     select_widget2 = Select(options = ['Violence with injury','Violence without injury','Sexual offences','Robbery','Criminal damage','Trafficking of drugs','Possession of drugs','Possession of weapons','Public order offences'],value = 'Violence with injury', title = 'Select Crime Type')
  98.     doc.add_root(column(slider_widget1,slider_widget2, p))
  99.    
  100. files=[]
  101. for file in os.listdir("bokeh"):
  102.     if file.endswith('.py'):
  103.         file="map"+file
  104.         files.append(file)
  105.  
  106. argvs = {}
  107. urls = []
  108. for i in files:
  109.     argvs[i] = None
  110.     urls.append(i.split('\\')[-1].split('.')[0])
  111. host = 'http://localhost:5006/map'
  112.  
  113. apps = build_single_handler_applications(files, argvs)
  114.  
  115. bokeh_tornado = BokehTornado(apps, extra_websocket_origins=["localhost:8000"])
  116. bokeh_http = HTTPServer(bokeh_tornado)
  117. sockets, port = bind_sockets("localhost:8000", 5000)
  118. bokeh_http.add_sockets(sockets)
  119.    
  120. #add navigation
  121. @app.route("/")
  122. #add another route for easier access to index
  123. @app.route("/home")
  124. def index():
  125.     return render_template('index.html')
  126.  
  127. @app.route("/predict")
  128. def predictions():
  129.     return "<h1>Predictions Based on PSNI Collected Data</h1>"
  130.  
  131. @app.route("/analysis")
  132. def analysis():
  133.     #get features
  134.     return render_template('data.html')
  135.  
  136. @app.route("/analysis/timeSeries",methods=['GET'])
  137. def getTimePlot():
  138.    script = server_document('http://localhost:5006/timeseries')
  139.    return render_template("displaytimeseries.html", script=script, template="Flask")   
  140. def startPlotserver():
  141.     server.start()
  142.     server = Server({'/timeseries': modifyTimeSeries}, io_loop=IOLoop(), allow_websocket_origin=["localhost:8000"])
  143.     server.io_loop.start()
  144. if __name__ == '__main__':
  145.     print('Opening single process Flask app with embedded Bokeh application on http://localhost:8000/')
  146.     print()
  147.     print('Multiple connections may block the Bokeh app in this configuration!')
  148.     print('See "flask_gunicorn_embed.py" for one way to run multi-process')
  149.     app.run(port=5000, debug=True)
  150.    
  151. @app.route('/crimeMap', methods=['GET'])
  152. def getCrimeMap():
  153.     bokeh_script = server_document("http://localhost:5006:%d/map" % port)
  154.     return render_template("displaymap1.html", bokeh_script=bokeh_script)
  155. #while script is running directly run the app
  156. if __name__ == "__main__":
  157.     app.run(debug=True)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement