-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
84 lines (61 loc) · 2.46 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
from collections import Counter
import time
from flask import Flask, render_template, request
import os
from werkzeug.utils import secure_filename
import requests
from loguru import logger
from pymongo import MongoClient, DESCENDING
from dotenv.main import load_dotenv
load_dotenv()
app = Flask(__name__, static_url_path='')
# HOST_MACHINE = os.getenv('HOST_MACHINE', "localhost")
YOLO_URL = f'http://yolo5-service:8081'
# MONGO_URL = f'mongodb://mongodb:27017'
@app.route('/', methods=['POST'])
def upload_file():
file = request.files['file']
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
p = os.path.join(app.config['UPLOAD_FOLDER'], filename)
logger.info(f'request detect service with {p}')
res = requests.post(f'{YOLO_URL}/predict', files={
'file': (p, open(p, 'rb'), 'image/png')
})
detections = res.json()
logger.info(f'response from detect service with {detections}')
# calc summary
element_counts = Counter([l['class'] for l in detections])
s = ''
for element, count in element_counts.items():
s += f"{element}: {count}\n"
# write result to mongo
logger.info('writing results to db')
document = {
'client_ip': request.remote_addr,
'detections': detections,
'filename': filename,
'summary': s,
'time': time.time()
}
inserted_document = client['objectDetection']['predictions'].insert_one(document)
logger.info(f'inserted document id {inserted_document.inserted_id}')
return render_template('result.html', filename=f'data/{filename}', summary=s, detections=detections)
@app.route("/", methods=['GET'])
def home():
return render_template('index.html')
@app.route("/recent", methods=['GET'])
def recent():
doc = client['objectDetection']['predictions'].find_one(
{'client_ip': request.remote_addr},
sort=[('time', DESCENDING)])
if doc:
return render_template('result.html', filename=f'data/{doc["filename"]}', summary=doc['summary'],
detections=doc['detections'])
return render_template('result.html', filename='', summary='No recent detection found', detections={})
if __name__ == "__main__":
app.config['UPLOAD_FOLDER'] = 'static/data'
logger.info(f'Initializing MongoDB connection')
MONGO_URL = f'mongodb://mongodb:27017'
client = MongoClient(MONGO_URL)
app.run(host='0.0.0.0', port=8082, debug=True)