a5586424bb815f7841fdd587bbc134175c56e358
[ealt-edge.git] / example-apps / ROBO / retail_app / inventry / retail_app.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 config
18 from flask_sslify import SSLify
19 from flask import Flask, request, jsonify, Response
20 from flask_cors import CORS
21 from camera_driver.capture_frame import VideoCamera, VideoFile
22 from influxdb import InfluxDBClient
23 import json
24 import time
25 import requests
26
27
28 app = Flask(__name__)
29 CORS(app)
30 sslify = SSLify(app)
31 app.config['JSON_AS_ASCII'] = False
32 app.config['UPLOAD_PATH'] = '/usr/app/images/'
33 app.config['supports_credentials'] = True
34 app.config['CORS_SUPPORTS_CREDENTIALS'] = True
35 app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024
36 ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg'])
37 count = 0
38 listOfMsgs = []
39 listOfCameras = []
40 listOfVideos = []
41
42
43 class inventry_info:
44     """
45     Store the data and manage multiple input video feeds
46     """
47     def __init__(self, current_count=0, total_count=0, time=0):
48             self.type = "Shelf_INV"
49             self.labels = "Bottles"
50             self.current_count = current_count
51             self.total_count = total_count
52             self.time = time
53
54     def setcurrentcount(self, current_count):
55             self.current_count = current_count
56
57     def settotalcount(self, total_count):
58             self.total_count = total_count
59
60     def getcurrentcount(self):
61             return self.current_count
62
63     def gettotalcount(self):
64             return self.total_count
65
66     def setlabel(self, labels):
67             self.labels = labels
68
69     def getlabel(self):
70             return self.labels
71
72     def settime(self, time):
73             self.labels = time
74
75     def gettime(self):
76             return self.time
77
78 def store_data(inventry_info):
79     """
80     store time series data in influx db
81     """
82     # TODO config, schema table, DB, fill data set
83     create_database()
84     store_info_db(inventry_info)
85
86
87 def shelf_inventry(video_capture, camera_info):
88     """
89     人脸识别
90     """
91     global count
92     labels = "bottles"
93     process_this_frame = 0
94     while True:
95         success, frame = video_capture.get_frame()
96         if not success:
97             break
98         if process_this_frame == 0:
99             url = config.detection_url + "/v1/obj_detection/detect"
100             # info1 = cv2.imencode(".jpg", rgb_small_frame)[1].tobytes()
101             data = json.loads(requests.post(url, data=frame,
102                                             verify=config.ssl_cacertpath).text)
103         inven_info = inventry_info()
104         current_count = data[count]
105         labels = data[labels]
106         total_count = inven_info.current_count + inven_info.total_count
107         inven_info.setcurrentcount(current_count)
108         inven_info.settotalcount(total_count)
109         inven_info.setlabel(labels)
110         inven_info.utime = time.time()
111         store_data(inven_info)
112
113
114 def store_info_db(inven_info):
115     """
116     Send "shelf" data to InfluxDB
117
118     :param inven_info: Inventry object
119     :return: None
120     """
121     global db_client
122     json_body = [
123         {
124             "measurement": inven_info.type,
125             "tags": {
126                 "object": "bottles",
127             },
128             "fields": {
129                 "time": inven_info.time,
130                 "Current Count": inven_info.current_count,
131                 "Total Count": inven_info.total_count,
132             }
133         }]
134     db_client.write_points(json_body)
135
136
137 def create_database():
138     """
139     Connect to InfluxDB and create the database
140
141     :return: None
142     """
143     global db_client
144
145     proxy = {"http": "http://{}:{}".format(config.IPADDRESS, config.PORT)}
146     db_client = InfluxDBClient(host=config.IPADDRESS, port=config.PORT,
147                                proxies=proxy, database=config.DATABASE_NAME)
148     db_client.create_database(config.DATABASE_NAME)
149
150
151 @app.route('/v1/monitor/cameras', methods=['POST'])
152 def add_camera():
153     camera_info = request.json
154     app.logger.info("Received message from ClientIP [" + request.remote_addr
155                     + "] Operation [" + request.method + "]" +
156                     " Resource [" + request.url + "]")
157     camera_info = {"name": camera_info["name"],
158                    "rtspurl": camera_info["rtspurl"],
159                    "location": camera_info["location"]}
160     listOfCameras.append(camera_info)
161     return Response("success")
162
163
164 @app.route('/v1/monitor/cameras/<name>/<rtspurl>/<location>', methods=['GET'])
165 def get_camera(name, rtspurl, location):
166     """
167     register camera with location
168     """
169     app.logger.info("Received message from ClientIP [" + request.remote_addr
170                     + "] Operation [" + request.method + "]" +
171                     " Resource [" + request.url + "]")
172     camera_info = {"name": name, "rtspurl": rtspurl, "location": location}
173     if "mp4" in camera_info["rtspurl"]:
174         video_file = VideoFile(camera_info["rtspurl"])
175         video_dict = {camera_info["name"]: video_file}
176         listOfVideos.append(video_dict)
177         return Response(shelf_inventry(video_file, camera_info["name"]),
178                         mimetype='multipart/x-mixed-replace; boundary=frame')
179     else:
180         video_file = VideoCamera(camera_info["rtspurl"])
181         video_dict = {camera_info["name"]: video_file}
182         listOfVideos.append(video_dict)
183         return Response(shelf_inventry(video_file, camera_info["name"]),
184                         mimetype='multipart/x-mixed-replace; boundary=frame')
185
186
187 @app.route('/v1/monitor/cameras/<camera_name>', methods=['DELETE'])
188 def delete_camera(camera_name):
189     app.logger.info("Received message from ClientIP [" + request.remote_addr
190                     + "] Operation [" + request.method + "]" +
191                     " Resource [" + request.url + "]")
192     for video1 in listOfVideos:
193         if camera_name in video1:
194             video_obj = video1[camera_name]
195             video_obj.delete()
196     for camera in listOfCameras:
197         if camera_name == camera["name"]:
198             listOfCameras.remove(camera)
199     for msg in listOfMsgs:
200         if camera_name in msg["msg"]:
201             listOfMsgs.remove(msg)
202     return Response("success")
203
204
205 @app.route('/v1/monitor/cameras')
206 def query_cameras():
207     app.logger.info("Received message from ClientIP [" + request.remote_addr
208                     + "] Operation [" + request.method + "]" +
209                     " Resource [" + request.url + "]")
210     return jsonify(listOfCameras)
211     return Response("success")
212
213
214 def start_server(handler):
215     app.logger.addHandler(handler)
216     if config.ssl_enabled:
217         context = (config.ssl_certfilepath, config.ssl_keyfilepath)
218         app.run(host=config.server_address, debug=True, ssl_context=context,
219                 threaded=True, port=config.server_port)
220     else:
221         app.run(host=config.server_address, debug=True, threaded=True,
222                 port=config.server_port)