-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsf_police_calls_visualization_server.py
181 lines (170 loc) · 8.02 KB
/
sf_police_calls_visualization_server.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
import http.server
import socketserver
from urllib import parse
from http import HTTPStatus
from hashlib import sha256
from gevent import os
import matplotlib.image as mim
import sys
sys.path.append('c:/prog/python/scimple')
import scm.scimple as scm
from scm.scimple import pyspark_utils
from gmplot import gmplot
from os import mkdir
from os.path import isdir
class Plotter:
"""
cache same requests
"""
sc, spark = pyspark_utils.contexts()
df = spark.read.option('header', 'true').option('separator', ',').csv("./data/police-department-incidents_.csv")
df.createGlobalTempView("calls")
svg_pool = set(map(lambda e: e[:e.index('.')], os.listdir("plots")))
if not isdir('./plots'): mkdir('./plots')
def __init__(self):
raise RuntimeError("Singleton can't be instanciated")
@staticmethod
def plot_over_is_time_stamp(string_plot_over):
return string_plot_over in {"Year", "YearAndMonth", "DayOfMonth", "Hour", "Month"}
@staticmethod
def getSvgFromQueryDict(query_dict):
hashed = sha256(str(query_dict).encode("utf-8")).hexdigest()
print(hashed)
if hashed in Plotter.svg_pool:
return hashed
elif query_dict["query_type"] == "plot":
title=f"Plot over {query_dict['plot_over']}"
WHERE = ""
conditions_list = []
if "type" in query_dict:
Category = f"Type==\"{query_dict['type']}\""
conditions_list.append(Category)
elif "category" in query_dict:
Category = f"Category==\"{query_dict['category']}\""
conditions_list.append(Category)
if "resolution" in query_dict:
Resolution = f"Resolution==\"{query_dict['resolution']}\""
conditions_list.append(Resolution)
if len(conditions_list):
title += " with " + " and ".join(conditions_list)
WHERE = "WHERE " + " AND ".join(conditions_list)
if not Plotter.plot_over_is_time_stamp(query_dict["plot_over"]):
ORDERBY = "ORDER BY count(*) DESC"
else:
ORDERBY = f"ORDER BY {query_dict['plot_over']}"
sql_query = f"""SELECT {query_dict["plot_over"]}, count(*) FROM global_temp.calls
{WHERE}
GROUP BY {query_dict["plot_over"]} {ORDERBY}"""
print(sql_query)
query_res = Plotter.spark.sql(sql_query).collect()
if not Plotter.plot_over_is_time_stamp(query_dict["plot_over"]):
# if query_dict["plot_over"] == "DayOfWeek":
# plot = scm.Plot().add(
# x=["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"],
# y=lambda i, x: query_res[i], marker="bar")
# else:
plot = scm.Plot(xlabel=query_dict["plot_over"], ylabel="Calls Number").add(query_res, 0, 1, marker="bar")
else:
plot = scm.Plot(xlabel=query_dict["plot_over"], ylabel="Calls Number").add(query_res, 0, 1, marker=".", markersize=3, colored_area=0.3)
plot.axe.set_title(title, fontsize=7)
plot.save_as_svg(file_name=hashed, dir_name='plots', aspect=2.7)
Plotter.svg_pool.add(hashed)
return hashed
elif query_dict["query_type"] == "map":
title = f"{query_dict['plot_over']} calls"
AND = ""
conditions_list = []
if "type" in query_dict:
Category = f"Type==\"{query_dict['type']}\""
conditions_list.append(Category)
elif "category" in query_dict:
Category = f"Category==\"{query_dict['category']}\""
conditions_list.append(Category)
if "resolution" in query_dict:
Resolution = f"Resolution==\"{query_dict['resolution']}\""
conditions_list.append(Resolution)
if len(conditions_list):
title += " with " + " and ".join(conditions_list)
AND = "AND " + " AND ".join(conditions_list)
date_start, date_end = query_dict['plot_over'].split(",")
sql_query = f"""SELECT FLOAT(X), FLOAT(Y) FROM global_temp.calls
WHERE "{date_start}" <= SUBSTRING(Date, 0, 10) AND SUBSTRING(Date, 0, 10) <= "{date_end}"
{AND}"""
print(sql_query)
query_res = Plotter.spark.sql(sql_query).collect()
plot = scm.Plot()
plot.axe.imshow(mim.imread("./imgs/sf.png"))
plot.axe.set_xticks([])
plot.axe.set_yticks([])
plot.add(list(map(lambda e: ((e[0] + 122.44) * 2700 + 277, -1 * ((e[1] - 37.76) * 3320 - 243)), query_res)), 0,
1, marker=".", markersize=3, colored_by="#dd8888", alpha=0.5)
print(list(map(lambda e: ((e[0] + 122.44) * 2700 + 277, -1 * ((e[1] - 37.76) * 3320 - 243)), query_res)))
plot.axe.set_title(title, fontsize=7)
plot.save_as_svg(file_name=hashed, dir_name='plots')
Plotter.svg_pool.add(hashed)
gmap = gmplot.GoogleMapPlotter(37.766956, -122.438481, 13, apikey="AIzaSyA9A99zBkS2QcO0yW9_sHcey57B7fJlhF8")
lons, lats = [e[0] for e in query_res], [e[1] for e in query_res]
gmap.scatter(lats, lons, '#000000', size=25, marker=False)
gmap.draw("maps/{name}.html".format(name=hashed))
return hashed
class SFPoliceCallsVisualizationServer(http.server.SimpleHTTPRequestHandler):
PORT = 8000
def send_head(self):
path = self.translate_path(self.path)
f = None
parts = parse.urlsplit(self.path)
query_dict = parse.parse_qs(parts.query)
query_dict = {key: query_dict[key][0] for key in query_dict}
if os.path.isdir(path):
if not parts.path.endswith('/'):
# redirect browser - doing basically what apache does
self.send_response(HTTPStatus.MOVED_PERMANENTLY)
new_parts = (parts[0], parts[1], parts[2] + '/',
parts[3], parts[4])
new_url = parse.urlunsplit(new_parts)
self.send_header("Location", new_url)
self.end_headers()
return None
for index in "index.html", "index.htm":
index = os.path.join(path, index)
if os.path.exists(index):
path = index
break
else:
return self.list_directory(path)
ctype = self.guess_type(path)
try:
f = open(path, 'rb')
except OSError:
self.send_error(HTTPStatus.NOT_FOUND, "File not found")
return None
try:
self.send_response(HTTPStatus.OK)
self.send_header("Content-type", ctype)
fs = os.fstat(f.fileno())
self.send_header("Content-Length", str(fs[6]))
self.send_header("Last-Modified", self.date_time_string(fs.st_mtime))
if "query_type" in query_dict:
print(query_dict, parts)
img_name = Plotter.getSvgFromQueryDict(query_dict)
if query_dict["query_type"] == "map":
self.send_header('img', f'<a href="maps/{img_name}.html"><img src="plots/{img_name}.svg" width="380px"></img></a>')
else:
self.send_header('img', f'<img src="plots/{img_name}.svg" width="1000px"></img>')
self.end_headers()
return f
except:
f.close()
raise
def do_GET(self):
"""Serve a GET request."""
f = self.send_head()
if f:
try:
self.copyfile(f, self.wfile)
except:
f.close()
Handler = SFPoliceCallsVisualizationServer
with socketserver.TCPServer(("", SFPoliceCallsVisualizationServer.PORT), Handler) as httpd:
print("serving at port", SFPoliceCallsVisualizationServer.PORT)
httpd.serve_forever()