윤영준 윤영준 05-24
working on connecting inference and postprocess
@ad162f2f1d692197d090192f4f78af5f16c515ce
config_files/endpoints.py
--- config_files/endpoints.py
+++ config_files/endpoints.py
@@ -1,0 +1,3 @@
+INFERENCE_ENDPOINT = "http://localhost:12345/cctv/infer"
+POSTPROCESS_ENDPOINT = "http://localhost:13579/postprocess/postprocess"
+MAIN_SYSTEM_ENDPOINT = ""
(파일 끝에 줄바꿈 문자 없음)
inference_endpoint.py
--- inference_endpoint.py
+++ inference_endpoint.py
@@ -1,15 +1,19 @@
 import numpy as np
-from flask import Flask, request
-from flask_restx import Api, Resource, fields
 import os
-from datetime import datetime
-from yoloseg.inference_ import Inference, overlay_mask
 import cv2
 import time
+from datetime import datetime
 from zoneinfo import ZoneInfo
-import base64
+
+from flask import Flask, request
+from flask_restx import Api, Resource, fields
 import requests
 from requests_toolbelt import MultipartEncoder
+import base64
+
+from yoloseg.inference_ import Inference, overlay_mask
+from config_files.endpoints import POSTPROCESS_ENDPOINT
+
 # from config_files import API_ENDPOINT_MAIN
 
 app = Flask(__name__)
@@ -59,9 +63,10 @@
         self.image = None
         self.image_type = None
         self.seg_image = None
+        self.flag_detected = False
         self.area_percent = 0
         self.time_zone = self.time_zone = ZoneInfo("Asia/Seoul")
-        self.endpoint = None
+        self.endpoint = POSTPROCESS_ENDPOINT
 
     @ns.response(200, 'Success')
     @ns.response(400, 'Validation Error')
@@ -83,21 +88,24 @@
 
         t1 = time.time()
         detections, self.mask = inference_engine.run_inference(cv2.resize(image, model_input_shape))
-
         t2 = time.time()
-        if len(self.mask) > 0:
-            self.mask = cv2.resize(self.mask, (image.shape[0], image.shape[1]))
-            self.mask_blob = cv2.imencode('.png', self.mask)
-            self.mask_blob = self.mask.tobytes()
-
-
         print(t2 - t1)
 
         if len(self.mask) != 0:
+            self.flag_detected = True
+        else:
+            self.flag_detected = False
+
+        if self.flag_detected:
+            self.mask = cv2.resize(self.mask, (image.shape[0], image.shape[1]))
+            self.mask_blob = cv2.imencode('.png', self.mask)
+            self.mask_blob = self.mask.tobytes()
             self.seg_image = overlay_mask(image, self.mask[0], color=(0, 255, 0), alpha=0.3)
-            self.area_percent = 0
-        else :
             self.area_percent = np.sum(self.mask) / image.shape[0] * image.shape[1]
+        else :
+            self.area_percent = 0
+
+
 
         self.send_result()
         # write another post request for pushing a detection result
@@ -105,6 +113,7 @@
 
     def send_result(self):
         time_sent = datetime.now(self.time_zone).strftime("yyyy-MM-dd'T'HH:mm:ss'Z'")
+        print(str(self.flag_detected))
         header = {
             'Content-Type': f'{self.image_type}',
             'x-time-sent': time_sent,
@@ -112,54 +121,52 @@
             'x-cctv-latitude': str(self.cctv_latitude),
             'x-cctv-longitude': str(self.cctv_longitude),
             'x-area-percentage' : str(self.area_percent),
+            'x-flag_detected' : str(self.flag_detected),  #"True" or "False"
         }
         session = requests.Session()
 
-        print(type(self.seg_image))
-        print(type(self.mask))
-        print(type(self.image))
-        try:
-            if len(self.mask) != 0:
-                seg_binary = cv2.imencode('.png', self.seg_image)
-                seg_binary = seg_binary[1].tobytes()
-                multipart_data = MultipartEncoder(
-                    fields={
-                        'image': (
-                            f'frame_{self.cctv_name}.{self.image_type}',
-                            self.image,
-                            f'image/{self.image_type}'
-                        ),
-                        'mask' : (
-                            f'frame_mask_{self.cctv_name}.{self.image_type}',
-                            self.mask_blob,
-                            f'image/{self.image_type}'
-                        ),
-                        'seg_mask' : (
-                            f'frame_seg_{self.cctv_name}.{self.image_type}',
-                            seg_binary,
-                            f'image/{self.image_type}'
-                        )
-                    }
-                )
-                header["Content-Type"] = multipart_data.content_type
-                response = session.post(self.endpoint, headers=header, data=multipart_data)
-            else:
-                multipart_data = MultipartEncoder(
-                    fields={
-                        'image': (
-                            f'frame_{self.cctv_name}.{self.image_type}',
-                            self.image,
-                            f'image/{self.image_type}'
-                        ),
-                    }
-                )
+        # try:
+        if self.flag_detected:
+            seg_binary = cv2.imencode('.png', self.seg_image)
+            seg_binary = seg_binary[1].tobytes()
+            multipart_data = MultipartEncoder(
+                fields={
+                    'image': (
+                        f'frame_{self.cctv_name}.{self.image_type}',
+                        self.image,
+                        f'image/{self.image_type}'
+                    ),
+                    'mask' : (
+                        f'frame_mask_{self.cctv_name}.{self.image_type}',
+                        self.mask_blob,
+                        f'image/{self.image_type}'
+                    ),
+                    'seg_mask' : (
+                        f'frame_seg_{self.cctv_name}.{self.image_type}',
+                        seg_binary,
+                        f'image/{self.image_type}'
+                    )
+                }
+            )
+            header["Content-Type"] = multipart_data.content_type
+            response = session.post(self.endpoint, headers=header, data=multipart_data)
+        else:
+            multipart_data = MultipartEncoder(
+                fields={
+                    'image': (
+                        f'frame_{self.cctv_name}.{self.image_type}',
+                        self.image,
+                        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 postprocessing server. Check the endpoint address or connection.\n"
-                  f"Can not connect to : {self.endpoint}")
+        # except Exception as e:
+        #     print(e)
+        #     print("Can not connect to the postprocessing server. Check the endpoint address or connection.\n"
+        #           f"Can not connect to : {self.endpoint}")
 
 
 if __name__ == '__main__':
postprocess_draft.py
--- postprocess_draft.py
+++ postprocess_draft.py
@@ -18,14 +18,14 @@
           description='A postprocessing and adaptive rate mainserver pusher')
 
 # Namespace definition
-ns = api.namespace('cctv', description='CCTV operations')
+ns = api.namespace('postprocess', description='Postprocessing of inference results')
 
 class StreamSources():
     def __init__(self, buffer_size, normal_send_interval, failure_mode_thres, failure_mode_check_past_n, normal_mode_thres, normal_mode_check_past_n):
         assert failure_mode_thres <= failure_mode_check_past_n, f"failure_mode checker condition is invaild!, failure_mode needs {failure_mode_thres} fails in {failure_mode_check_past_n}, which is not possible!"
         assert normal_mode_thres <= normal_mode_check_past_n, f"normal_mode checker condition is invaild!, normal_mode needs {normal_mode_thres} fails in {normal_mode_check_past_n}, which is not possible!"
-        assert buffer_size < failure_mode_check_past_n, f"'buffer_size' is smaller then failure_mode_thres! This is not possible! This will cause program to never enter failure mode!! \nPrinting relevent args and shutting down!\n buffer_size : {buffer_size}\n failure_mode_thres : {failure_mode_thres}"
-        assert buffer_size < normal_mode_thres, f"'buffer_size' is smaller then normal_mode_thres! This is will cause the program to never revert back to normal mode!! \nPrinting relevent args and shutting down!\n buffer_size : {buffer_size}\n normal_mode_thres : {normal_mode_thres}"
+        assert buffer_size >= failure_mode_check_past_n, f"'buffer_size' is smaller then failure_mode_thres! This is not possible! This will cause program to never enter failure mode!! \nPrinting relevent args and shutting down!\n buffer_size : {buffer_size}\n failure_mode_thres : {failure_mode_thres}"
+        assert buffer_size >= normal_mode_check_past_n, f"'buffer_size' is smaller then normal_mode_thres! This is will cause the program to never revert back to normal mode!! \nPrinting relevent args and shutting down!\n buffer_size : {buffer_size}\n normal_mode_thres : {normal_mode_thres}"
     
         self.sources = {}
         self.buffer_size = buffer_size
@@ -66,7 +66,7 @@
         assert status in ["OK", "FAIL"], f"Invalid status was given!, status must be one of 'OK' or 'FAIL', but given '{status}'!"
         
         if source not in self.sources:
-            raise f"No key found for source. Did you forgot to add it? \n source : {source}"
+            raise ValueError(f"No key found for source. Did you forgot to add it? \n source : {source}")
 
         self.sources[source]["status_counts"].append(status)
         if len(self.sources[source]["status_counts"]) > self.buffer_size:
@@ -113,6 +113,7 @@
         self.image_type = None
         self.seg_image = None
         self.area_percent = 0
+        self.detected = False
         self.memory = StreamSources(
             buffer_size=15,
             normal_send_interval=10,
@@ -131,8 +132,16 @@
         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')
+        self.detected = request.headers.get('x-flag_detected')
+        if self.detected == "True":
+            self.detected = True
+        elif self.detected == "False":
+            self.detected = False
+        else:
+            raise ValueError(f"Invalided value for x-flag_detected : {self.detected}")
+        print(self.detected)
         self.area_percent = request.headers.get('x-area-percentage')
-
+        self.area_percent = float(self.area_percent)
         self.image = request.files['image']
         self.image_type = request.headers.get('Content-Type')
         self.mask = request.files['mask']
@@ -157,7 +166,12 @@
         thres = 0.1
         #TODO temporal pass_fail threshold
         if self.area_percent > thres:
-            ret = 'Fail'
+            ret = 'FAIL'
         else:
             ret = 'OK'
-        return ret
(파일 끝에 줄바꿈 문자 없음)
+        return ret
+
+
+if __name__ == "__main__":
+    print("Postprocess Online")
+    app.run(debug=True, port=13579)
(파일 끝에 줄바꿈 문자 없음)
run_image_anal_backend.sh
--- run_image_anal_backend.sh
+++ run_image_anal_backend.sh
@@ -16,6 +16,9 @@
 #gunicorn --workers=6 inference_endpoint:app
 pids+=($!)
 
+#python postprocess_draft.py
+#pids+=($!)
+
 # Function to kill all processes
 cleanup() {
     echo "Terminating all processes..."
Add a comment
List