윤영준 윤영준 05-21
postprocess 작성중
@31b338374e6b29ca1935166b575736866baf1e0e
 
config_files/endpoints.py (added)
+++ config_files/endpoints.py
@@ -0,0 +1,0 @@
hls_streaming/hls.py
--- hls_streaming/hls.py
+++ hls_streaming/hls.py
@@ -100,6 +100,8 @@
         header = {
             'Content-Type': f'image/{image_type}',
             'x-time-sent': time_sent,
+            # Why are you encoding string? because post method has a problem with sending not english chars.
+            # (It defaults to latin-1 encoding and not straight forward to change)
             'x-cctv-name': base64.b64encode(str(self.cctvid).encode('utf-8')).decode('ascii'),
             'x-cctv-latitude' : str(self.lat),
             'x-cctv-longitude' : str(self.lon),
inference_endpoint.py
--- inference_endpoint.py
+++ inference_endpoint.py
@@ -7,6 +7,9 @@
 import cv2
 import time
 import base64
+import requests
+from requests_toolbelt import MultipartEncoder
+from config_files import API_ENDPOINT_MAIN
 
 app = Flask(__name__)
 api = Api(app, version='1.0', title='CCTV Image Upload API',
@@ -44,40 +47,89 @@
 @ns.route('/infer', )
 class ImageUpload(Resource):
     # @ns.expect(image_upload_model, validate=True)
+    def __init__(self):
+        super().__init__(api)
+        self.time_sent = None
+        self.cctv_latitude = None
+        self.cctv_longitude = None
+        self.cctv_info = None
+        self.mask = None
+        self.mask_blob = None
+        self.image = None
+        self.image_type = None
+        self.area_percent = 0
+
     @ns.response(200, 'Success')
     @ns.response(400, 'Validation Error')
     def post(self):
         if 'file' not in request.files:
             ns.abort(400, 'No image part in the request')
-        image = request.files['file']
-        cctv_info = base64.b64decode(request.headers.get('x-cctv-name', '')).decode('UTF-8')
-        time_sent = request.headers.get('x-time-sent', '')
-        cctv_latitude = request.headers.get('x-cctv-latitude', 'Not provided')
-        cctv_longitude = request.headers.get('x-cctv-longitude', 'Not provided')
+        self.image = request.files['file']
+        self.image_type = request.headers.get('Content-Type')
+        self.cctv_info = base64.b64decode(request.headers.get('x-cctv-name', '')).decode('UTF-8')
+        self.time_sent = request.headers.get('x-time-sent', '')
+        self.cctv_latitude = request.headers.get('x-cctv-latitude', 'Not provided')
+        self.cctv_longitude = request.headers.get('x-cctv-longitude', 'Not provided')
 
-        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
-        image = image.read()
+        # timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
+        image = self.image.read()
         image = np.frombuffer(image, np.uint8)
         image = cv2.imdecode(image, cv2.IMREAD_COLOR)
-        filename = f"{timestamp}_{cctv_info}.png"
+        # filename = f"{timestamp}_{self.cctv_info}.png"
 
         t1 = time.time()
-        detections, mask_maps = inference_engine.run_inference(image)
+        detections, self.mask = inference_engine.run_inference(image)
+        self.mask_blob = cv2.imencode(self.mask)
+        self.mask_blob = self.mask.tobytes()
         t2 = time.time()
 
         print(t2 - t1)
 
-        if len(mask_maps) != 0:
-            seg_image = overlay_mask(image, mask_maps[0], color=(0, 255, 0), alpha=0.3)
-            area_percent = 0
+        if len(self.mask) != 0:
+            seg_image = overlay_mask(image, self.mask[0], color=(0, 255, 0), alpha=0.3)
+            self.area_percent = 0
         else :
-            area_percent = np.sum(mask_maps) / image.shape[0] * image.shape[1]
+            self.area_percent = np.sum(self.mask) / image.shape[0] * image.shape[1]
 
+        self.send_result()
         # write another post request for pushing a detection result
-        return {"message": f"Image {filename} uploaded successfully!"}
+        return {"message": f"Image {self.mask} uploaded successfully!"}
 
     def send_result(self):
-        pass
+        time_sent = datetime.now(self.time_zone).strftime("yyyy-MM-dd'T'HH:mm:ss'Z'")
+        header = {
+            'Content-Type': f'{self.image_type}',
+            'x-time-sent': time_sent,
+            'x-cctv-name': base64.b64encode(str(self.cctv_info).encode('utf-8')).decode('ascii'),
+            'x-cctv-latitude': str(self.cctv_latitude),
+            'x-cctv-longitude': str(self.cctv_longitude),
+            'x-area-percentage' : str(self.area_percent),
+        }
+        session = requests.Session()
+
+        try:
+            multipart_data = MultipartEncoder(
+                fields={
+                    'image': (
+                        f'frame_{self.cctv_info}.{self.image_type}',
+                        self.image,
+                        f'image/{self.image_type}'
+                    ),
+                    'mask' : (
+                        f'frame_mask_{self.cctv_info}.{self.image_type}',
+                        self.mask_blob,
+                        f'image/{self.image_type}'
+                    )
+                }
+            )
+            header["Content-Type"] = multipart_data.content_type
+            response = session.post(self.endpoint, headers=header, data=multipart_data)
+
+        except Exception as e:
+            print(e)
+            print("Can not connect to the analyzer server. Check the endpoint address or connection.\n"
+                  f"Can not connect to : {self.endpoint}")
+
 
 if __name__ == '__main__':
     app.run(debug=True, port=12345)
postprocessing.py
--- postprocessing.py
+++ postprocessing.py
@@ -14,4 +14,31 @@
           description='A postprocessing that dynamically decides how frequently send image and detection result')
 
 # Namespace definition
-ns = api.namespace('cctv', description='CCTV operations')
(파일 끝에 줄바꿈 문자 없음)
+ns = api.namespace('cctv', description='CCTV operations')
+
[email protected]('/postprocess', )
+class get_inference_result(Resource):
+    def __init__(self):
+        super().__init__(api)
+        self.time_sent = None
+        self.cctv_latitude = None
+        self.cctv_longitude = None
+        self.cctv_info = None
+        self.mask = None
+        self.image = None
+        self.image_type = None
+        self.area_percent = 0
+
+    @ns.response(200, 'Success')
+    @ns.response(400, 'Validation Error')
+    def post(self):
+        self.image = request.files['image']
+        self.mask = request.files['mask']
+        self.cctv_info = base64.b64decode(request.headers.get('x-cctv-name', '')).decode('UTF-8')
+        self.cctv_latitude = request.headers.get('x-cctv-latitude')
+        self.cctv_longitude = request.headers.get('x-cctv-longitude')
+        self.image_type = request.headers.get('Content-Type')
+        self.area_percent = request.headers.get('x-area-percentage')
+
+
+
Add a comment
List