-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPDATA.py
345 lines (257 loc) · 10 KB
/
PDATA.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
#!/usr/bin/env python
'''
__author__: Valdir Junior
'''
import re
from unicodedata import normalize
import csv
import requests
import pymysql
from xlsxwriter.workbook import Workbook
import datetime
import pandas as pd
import math
class SELENA:
con = None
def __init__(self):
self.con = pymysql.connect(user='app', password='root', db='PDATA',cursorclass=pymysql.cursors.DictCursor)
def cleanBo(self, historic):
historic = normalize('NFD', historic).encode('ASCII', 'ignore').decode('ASCII')
return historic.strip('*,.- ').upper()
def openAudited(self, path):
with open(path, newline='', encoding='latin1') as f:
reader = csv.reader(f, delimiter=';')
rg = []
city = ''
state = ''
for row in reader:
ln = {}
ln['key'] = row[0]
ln['year'] = row[1]
if row[3] != city or row[2] != state:
city = row[3]
state = row[2]
city_info = requests.get('http://localhost:5000/api/0.1/info/'+state+'/'+city).json() #conect with BRASA (API for brazilian states and cities)
if 'error' not in city_info:
ln['city'] = city_info['info']['id']
else:
ln['city'] = city_info['info']['id']
ln['event'] = row[7]
ln['classification'] = row[10]
ln['historic'] = row[8]
rg.append(ln)
return rg
def getIdClassification(self, classification):
cursor = self.con.cursor()
query = "SELECT id FROM classification WHERE initials = %s"
cursor.execute(query,(classification))
data = cursor.fetchone()
if data is not None:
return data['id']
def getIdEvent(self, event):
cursor = self.con.cursor()
query = "SELECT id FROM typeEvent WHERE UPPER(description) = UPPER(%s)"
cursor.execute(query,(event))
data = cursor.fetchone()
if data is not None:
return data['id']
def insertAudit(self, event):
try:
cursor = self.con.cursor()
query = "INSERT INTO audit (boKey, year, idTypeEvent, IdClassification, idBrazilianCity, historic) VALUES (%s, %s, %s, %s, %s, %s)"
cursor.execute(query, (event['key'], event['year'], event['event'], event['classification'], event['city'], event['historic']))
self.con.commit()
finally:
return True
def getAmountEc(self):
ec = {}
ec['1'] = input('Informe a quantidade EC1: ')
ec['2'] = input('Informe a quantidade EC2: ')
ec['3'] = input('Informe a quantidade EC3: ')
return ec
def writeHeader(self, sheet):
sheet.write('A1', 'Chave')
sheet.write('B1', 'Ano')
sheet.write('C1', 'UF')
sheet.write('D1', 'Cidade')
sheet.write('E1', 'Bairro')
sheet.write('F1', 'Logradouro')
sheet.write('G1', 'Classificação')
sheet.write('H1', 'Evento')
sheet.write('I1', 'Histórico')
sheet.write('J1', 'Analista')
sheet.write('K1', 'Classificao Para')
sheet.write('L1', 'Motivo da Reclassificação')
return sheet
def generateAudit(self, amountEc):
#get date in us format to create the file
date = str(datetime.datetime.now()).split()[0]
file = date+'_nao_auditado_ec1_ec2_ec3.xlsx'
workbook = Workbook(file)
sheet = workbook.add_worksheet()
sheet = self.writeHeader(sheet)
con = pymysql.connect(user='app', password='root')
try:
cursor = con.cursor()
print(amountEc)
start = 1
for key in amountEc:
print('\nBuscando '+amountEc[key]+' Registros de EC'+key+' ...')
query = "SELECT 'Chave', 'Ano', 'UF', 'Cidade', 'Bairro', 'Logradouro', 'Classificação', 'Evento', 'Histórico' UNION ALL \
SELECT concat(registros.SP.ID_DELEGACIA,'-',registros.SP.ANO_BO,'-',registros.SP.NUM_BO) as Chave,\
prevcrime.bo.yearBo as Ano, registros.SP.ID_UF as UF, registros.SP.CIDADE as Cidade, registros.SP.BAIRRO as Bairro, registros.SP.LOGRADOURO as Logradouro,\
concat('EC',prevcrime.dataclassification.idTypeEc) as Classificação,\
CASE\
WHEN prevcrime.bo.idTypeCrime = 1 THEN 'ROUBO'\
WHEN prevcrime.bo.idTypeCrime = 2 THEN 'FURTO'\
ELSE NULL\
END as Evento,\
trim(prevcrime.bo.historicBo) as Histórico\
FROM registros.SP\
LEFT JOIN prevcrime.bo ON (prevcrime.bo.yearBo = registros.SP.ANO_BO AND prevcrime.bo.idBo = NUM_BO AND prevcrime.bo.idPoliceStation = registros.SP.ID_DELEGACIA)\
LEFT JOIN prevcrime.dataclassification ON (prevcrime.bo.id = prevcrime.dataclassification.idBo)\
WHERE prevcrime.dataclassification.idTypeEc = "+key+" AND registros.SP.enviado_auditoria = 0 ORDER BY rand() LIMIT "+amountEc[key]+";"
cursor.execute(query)
print('\nEscrevendo EC%s...' % key)
for r, row in enumerate(cursor.fetchall(), start=start):
for c, col in enumerate(row):
sheet.write(r, c, col)
start = start+int(amountEc[key])
finally:
workbook.close()
con.close()
def validateAmoutEc(self, amount, idEc):
try:
cursor = self.con.cursor()
query = "SELECT COUNT(1) as amount FROM audit WHERE IdClassification = %s"
cursor.execute(query, (idEc))
dbAmount = cursor.fetchone()['amount']
if dbAmount < amount:
amount = dbAmount
finally:
return amount
def generateMLTraining(self, amount):
try:
cursor = self.con.cursor()
query = "SELECT id, initials FROM classification"
cursor.execute(query)
ecs = cursor.fetchall()
data = []
for ec in ecs:
print (ec['initials'])
ec['amount'] = self.validateAmoutEc(amount, ec['id'])
query = "SELECT DISTINCT cl.initials, ad.historic FROM audit ad LEFT JOIN classification cl ON (cl.id = ad.IdClassification) WHERE cl.initials = %s ORDER BY RAND() LIMIT %s"
cursor.execute(query, (ec['initials'], ec['amount']))
con.commit()
data += cursor.fetchall()
for dt in data:
dt['historic'] = self.cleanBo(dt['historic'])
df = pd.DataFrame(data, columns = ['initials','historic'])
df.to_csv('data/EC_training_SP.csv', sep=';', line_terminator='\n',header=False, index=False)
finally:
return True
def generateMLTrainingRO(self, amount):
con = pymysql.connect(user='app', password='root', db='registros',cursorclass=pymysql.cursors.DictCursor) #conect with external database for getting registers for training our ML
try:
cursor = con.cursor()
ecs = ['1','2','3']
data = []
for ec in ecs:
query = "SELECT DISTINCT CONCAT('EC', ec_auditoria) as initials, historico FROM ro WHERE ec_auditoria = %s ORDER BY RAND() LIMIT %s"
cursor.execute(query, (ec, 2000))
con.commit()
data += cursor.fetchall()
for dt in data:
dt['historico'] = self.cleanBo(dt['historico'])
df = pd.DataFrame(data, columns = ['initials','historico'])
df.to_csv('data/EC_training_RO.csv', sep=';', line_terminator='\n',header=False, index=False)
finally:
return True
def generateMLTesting(self, amount):
try:
cursor = self.con.cursor()
query = "SELECT id, initials FROM classification"
cursor.execute(query)
ecs = cursor.fetchall()
data = []
for ec in ecs:
print (ec['initials'])
ec['amount'] = self.validateAmoutEc(amount, ec['id'])
query = "SELECT DISTINCT cl.initials, ad.historic FROM audit ad LEFT JOIN classification cl ON (cl.id = ad.IdClassification) WHERE cl.initials = %s ORDER BY RAND() LIMIT %s"
cursor.execute(query, (ec['initials'], ec['amount']))
# con.commit()
data += cursor.fetchall()
for dt in data:
dt['historic'] = self.cleanBo(dt['historic'])
df = pd.DataFrame(data, columns = ['initials','historic'])
df.to_csv('data/EC_testing.csv', sep=';', line_terminator='\n',header=False, index=False)
finally:
return True
def prepareClassification(self, year):
con = pymysql.connect(user='app', password='root', db='registros',cursorclass=pymysql.cursors.DictCursor) #conect with external database for getting registers for classification by ML
try:
cursor = con.cursor()
print('Contanto Registros...')
query = 'SELECT COUNT(1) AS TOTAL FROM ro WHERE ano = %s'
cursor.execute(query, (year))
amount = cursor.fetchone()['TOTAL']
tparts = math.ceil(float(amount)/30000)
part = 1
previous = 0
while part <= tparts:
print('Buscando Registros...')
query = 'SELECT nr_ocorr, ano, COALESCE(historico, "") as historico FROM ro WHERE ano = %s LIMIT %s, %s'
cursor.execute(query, (year, previous*30000, 30000))
pdata = cursor.fetchall()
for dt in pdata:
dt['historico'] = self.cleanBo(dt['historico'])
print('Escrevendo Registros no Arquivo...')
df = pd.DataFrame(pdata, columns=['nr_ocorr','ano','historico'])
df.to_csv('data/EC_classify_ro_'+year+'_'+str(part)+'_n.csv', sep=';', line_terminator='\n', header=False, index=False)
previous = int(part)
part+=1
# for dt in data:
# dt['HISTORICO_BO'] = self.cleanBo(dt['HISTORICO_BO'])
# print('Escrevendo Registros no Arquivo...')
# df = pd.DataFrame(data, columns=['nr_ocorr','ano','historico'])
# df.to_csv('data/EC_classify_ro_'+year+'.csv', sep=';', line_terminator='\n', header=False, index=False)
finally:
con.close()
def showMenu(self):
print (30 * "-" + "AÇÕES" + 30 * "-")
print ("1 - Gerar Planilha de Auditoria")
print ("2 - Importa Dados Auditados")
print ("3 - Gerar Treinamento para ML")
print ("4 - Gerar Teste para ML")
print ("5 - Registros para Classificação/ML")
print ("0 - Sair")
print (65 * "-")
def main(self):
loop = True
while loop:
self.showMenu()
choice = input("Escolha a ação pelo número: ")
if choice == '1':
amount = self.getAmountEc()
self.generateAudit(amount)
elif choice == '2':
path = input("Caminho do arquivo: ")
data = self.openAudited(path)
for reg in data:
reg['classification'] = self.getIdClassification(reg['classification'])
reg['event'] = self.getIdEvent(reg['event'])
if reg['classification'] is not None:
self.insertAudit(reg)
elif choice == '3':
self.generateMLTrainingRO(2000)
elif choice == '4':
self.generateMLTesting(1000)
elif choice == '5':
year = input("Ano para classificação: ")
self.prepareClassification(year)
elif choice == '0':
self.con.close()
loop = False
if __name__ == "__main__":
sl = SELENA()
sl.main()