-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.py
executable file
·196 lines (139 loc) · 5.21 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
# -*- coding: utf-8 -*-
#!/usr/bin/env pythonimport urllib
import json
import os
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask import request
from flask import make_response
from flask import jsonify
from datetime import date, datetime
from decimal import Decimal
from flask_cors import CORS, cross_origin
from flask import render_template
import requests
# Flask app should start in global layout
app = Flask(__name__)
app.config['CORS_HEADERS'] = 'Content-Type'
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:@192.168.43.214/bobot'
cors = CORS(app, resources={r"/*": {"origins": "*"}})
db = SQLAlchemy(app)
migrate = Migrate(app, db)
#app.config['SQLALCHEMY_DATABASE_URI'] = os.environ['DATABASE_URL']
def create_app():
app = Flask(__name__)
db.init_app(app)
return app
@app.route('/')
@app.route('/index')
def index():
return render_template('index.html')
@app.route('/getOcorrencias', methods=['GET'])
@cross_origin()
def getOcorrencias():
data = []
for u in db.session.query(Ocorrencia).all():
data.append(row2dict(u))
return json.dumps(data)
@app.route('/getOcorrenciasPorTipo', methods=['GET'])
@cross_origin()
def getOcorrenciasPorTipo():
req = request.args.get('tipo')
data = []
for u in db.session.query(Ocorrencia).filter_by(tipo=req):
data.append(row2dict(u))
return json.dumps(data)
def row2dict(row):
return dict((col, getattr(row, col)) for col in row.__table__.columns.keys())
def alchemyencoder(obj):
"""JSON encoder function for SQLAlchemy special classes."""
if isinstance(obj, datetime.date):
return obj.isoformat()
elif isinstance(obj, decimal.Decimal):
return float(obj)
@app.route('/setOcorrencia', methods=['POST'])
def setOcorrencia():
req = request.get_json(silent=True, force=True)
ocorrencia = Ocorrencia();
contexto = getContexto(req)
ocorrencia.tipo = getTipo(contexto)
ocorrencia.data = getData(contexto)
onde = getMapsAdress(contexto)
ocorrencia.turno = getTurno(contexto)
ocorrencia.descricao = contexto['descricao']
ocorrencia.motivo = contexto['motivo']
if(len(onde) != 1):
resposta = "Desculpe, não consegui encontrar resultados para esse endereço, nos informe um endereço mais detalhado, por exemplo, 'Rua Augusta, São Paulo'"
res = json.dumps({
"speech": resposta,
"displayText" : resposta,
"source" : "",
"contextOut" : [{'name': 'onde', 'lifespan' : 2, 'paramaters': {}}]
}, indent=4)
else:
ocorrencia.latitude = onde[0]['geometry']['location']['lat']
ocorrencia.longitude = onde[0]['geometry']['location']['lng']
db.session.add(ocorrencia)
db.session.commit()
resposta = "Seus dados foram salvos com sucesso, obrigado pela contribuição e sentimos muito pelo infortúnio. Lembramos que é muito importante registrar o boletin de ocorrência, você pode fazer isso online, acessando esse link: http://www.delegaciaonline.pb.gov.br/delegacia-web/pages/index.xhtml"
res = json.dumps({
"speech": resposta,
"displayText" : resposta,
"source" : "",
}, indent=4)
r = make_response(res)
r.headers['Content-Type'] = 'application/json'
return r
def getContexto(req):
if req.get("result") == None:
return {}
dados = req.get('result')
return dados['contexts'][0]['parameters']
def getTipo(contexto):
tipo = contexto['violencia']
if tipo == "violência sexual":
return "vio_sex"
elif tipo == "homicídio":
return "homicidio"
return tipo
def getData(contexto):
quando = contexto['quando']
hoje = date.today()
if quando == 'hoje':
return str(hoje)
elif quando == 'ontem':
return str(date.fromordinal(hoje.toordinal()-1))
elif quando == 'semana passada':
return str(date.fromordinal(hoje.toordinal()-8))
elif quando == 'mes passado':
return str(date.fromordinal(hoje.toordinal()-45))
def getMapsAdress(contexto):
onde = contexto['local_ocorrencia'].replace(' ', '+')
key = "AIzaSyAZlmj6WXcngnHLGxZh9wgUeFwLPlzQNJM"
response = requests.get(
"https://maps.googleapis.com/maps/api/place/textsearch/json?"+
"query="+onde+
"&key="+key)
req = response.json()
print(req)
results = req.get('results')
return results
def getTurno(contexto):
turno = contexto['turno']
if turno == 'manhã':
return "manha"
return turno
class Ocorrencia(db.Model):
__tablename__ = 'tb_ocorrencias'
id = db.Column(db.Integer, primary_key=True)
tipo = db.Column(db.String(100), nullable=False)
data = db.Column(db.String(100), nullable=False)
turno = db.Column(db.String(100), nullable=False)
latitude = db.Column(db.String(100), nullable=False)
longitude = db.Column(db.String(100), nullable=False)
descricao = db.Column(db.String(255), nullable=True)
motivo = db.Column(db.String(255), nullable=True)
if __name__ == '__main__':
port = int(os.getenv('PORT', 5000))
app.run(debug=True, port=port, host='0.0.0.0')