added Interface defination
[ealt-edge.git] / example-apps / ROBO / aPaaS / Obj_Detection_service / detection / obj_detection_service.py
1 #
2 # Copyright 2020 Huawei Technologies Co., Ltd.
3 #
4 # Licensed under the Apache License, Version 2.0 (the "License");
5 # you may not use this file except in compliance with the License.
6 # You may obtain a copy of the License at
7 #
8 #     http://www.apache.org/licenses/LICENSE-2.0
9 #
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS,
12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
15 #
16
17 import os
18 import config
19 from flask_sslify import SSLify
20 from flask import Flask, request, jsonify, Response
21 from flask_cors import CORS
22 from werkzeug import secure_filename
23
24
25 class model_info():
26     def __init__(self, model_name):
27         self.model = 'model_info/MobileNetSSD_deploy.caffemodel'
28         self.model_name = model_name
29         self.prototxt = 'model_info/MobileNetSSD_deploy.prototxt'
30         self.confidenceLevel = 80
31
32     def get_model(self):
33         return self.model
34
35     def get_prototxt(self):
36         return self.prototxt
37
38     def get_model_name(self):
39         return self.model_name
40
41     def set_confidence_level(self, confidenceLevel):
42         self.confidenceLevel = confidenceLevel
43
44     def get_confidence_level(self):
45         return self.confidenceLevel
46
47     def update_model(self, model, prototxt, model_name):
48         self.prototxt = prototxt
49         self.model = model
50         self.model_name = model_name
51
52
53 # Labels of Network.
54 classNames = {0: 'background',
55               1: 'aeroplane', 2: 'bicycle', 3: 'bird', 4: 'boat',
56               5: 'bottle', 6: 'bus', 7: 'car', 8: 'cat', 9: 'chair',
57               10: 'cow', 11: 'diningtable', 12: 'dog', 13: 'horse',
58               14: 'motorbike', 15: 'person', 16: 'pottedplant',
59               17: 'sheep', 18: 'sofa', 19: 'train', 20: 'tvmonitor'}
60
61 app = Flask(__name__)
62 CORS(app)
63 sslify = SSLify(app)
64 app.config['JSON_AS_ASCII'] = False
65 app.config['UPLOAD_PATH'] = '/usr/app/images/'
66 app.config['supports_credentials'] = True
67 app.config['CORS_SUPPORTS_CREDENTIALS'] = True
68 app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024
69 ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg'])
70 count = 0
71 listOfMsgs = []
72
73
74 def Detection(img):
75     return
76
77
78 def allowed_file(filename):
79     return '.' in filename and filename.rsplit('.', 1)[1].lower()\
80            in ALLOWED_EXTENSIONS
81
82
83 @app.route('/mep/v1/obj_detection/uploadModel', methods=['POST'])
84 def uploadModel():
85     """
86     upload model
87     :return: html file
88     """
89     app.logger.info("Received message from ClientIP [" + request.remote_addr
90                     + "] Operation [" + request.method + "]" +
91                     " Resource [" + request.url + "]")
92
93     modelInfo = model_info("caffe")
94     modelInfo.update_model("caffe", "mobilenet_ssd", "prototext")
95     return Response("success")
96
97
98 @app.route('/mep/v1/obj_detection/confidencelevel', methods=['POST'])
99 def setConfidenceLevel():
100     """
101     Trigger the video_feed() function on opening "0.0.0.0:5000/video_feed" URL
102     :return:
103     """
104     app.logger.info("Received message from ClientIP [" + request.remote_addr
105                     + "] Operation [" + request.method + "]" +
106                     " Resource [" + request.url + "]")
107
108     confidenceLevel = 80
109     modelInfo = model_info("caffe")
110     modelInfo.set_confidence_level(confidenceLevel)
111     return Response("success")
112
113
114 @app.route('/mep/v1/obj_detection/detect', methods=['GET'])
115 def Obj_Detection():
116     """
117     Trigger the Obj detection on input frame/image
118     Input: frame/image
119     :return: imposed frame, count, Obj type, time taken by detection
120     """
121     app.logger.info("Received message from ClientIP [" + request.remote_addr
122                     + "] Operation [" + request.method + "]" +
123                     " Resource [" + request.url + "]")
124
125     if 'file' not in request.files:
126         raise IOError('No file')
127
128     file = request.files['file']
129     if file.filename == '':
130         app.logger.info('No file selected for uploading')
131         raise IOError('No file')
132     if file and allowed_file(file.filename):
133         filename = secure_filename(file.filename)
134         file.save(os.path.join(app.config['UPLOAD_PATH'], filename))
135         app.logger.info('File successfully uploaded')
136         Detect_result = Detection(filename)
137     else:
138         app.logger.info('Allowed file types are txt, pdf, png, jpg, jpeg, gif')
139         return Response("failure")
140     # return jsonify({'Face number': num, 'Result': 'upload success'})
141     return jsonify(Detect_result)
142
143
144 def start_server(handler):
145     app.logger.addHandler(handler)
146     if config.ssl_enabled:
147         context = (config.ssl_certfilepath, config.ssl_keyfilepath)
148         app.run(host=config.server_address, debug=True, ssl_context=context,
149                 threaded=True, port=config.server_port)
150     else:
151         app.run(host=config.server_address, debug=True, threaded=True,
152                 port=config.server_port)