justin2341 commited on
Commit
4d44034
·
verified ·
1 Parent(s): b90fbeb

Upload 9 files

Browse files
Files changed (10) hide show
  1. .gitattributes +1 -0
  2. Dockerfile +45 -0
  3. app.py +171 -0
  4. demo.py +100 -0
  5. firesdk.py +22 -0
  6. libfire.so +3 -0
  7. libopencv.zip +3 -0
  8. ncnn.zip +3 -0
  9. requirements.txt +5 -0
  10. run.sh +3 -0
.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ libfire.so filter=lfs diff=lfs merge=lfs -text
Dockerfile ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM openvino/ubuntu20_runtime:2024.5.0
2
+
3
+ USER root
4
+ RUN rm -rf /var/lib/apt/lists/* && apt update && apt install -y unzip \
5
+ libjpeg8 \
6
+ libwebp6 \
7
+ libpng16-16 \
8
+ libtbb2 \
9
+ libtiff5 \
10
+ libtbb-dev \
11
+ libopenexr-dev \
12
+ libgl1-mesa-glx \
13
+ libglib2.0-0 \
14
+ libgomp1
15
+
16
+ # Set up working directory
17
+ RUN mkdir -p /home/openvino/kby-ai-fire
18
+ WORKDIR /home/openvino/kby-ai-fire
19
+
20
+ # Copy shared libraries and application files
21
+ COPY ./libopencv.zip .
22
+ RUN unzip libopencv.zip
23
+ RUN cp -f libopencv/* /usr/local/lib/
24
+ RUN ldconfig
25
+
26
+ # Copy Python and application files
27
+ COPY ./libfire.so .
28
+ COPY ./app.py .
29
+ COPY ./firesdk.py .
30
+ COPY ./requirements.txt .
31
+ COPY ./license.txt .
32
+ COPY ./run.sh .
33
+ COPY ./ncnn.zip .
34
+ RUN unzip ncnn.zip
35
+
36
+ # Install Python dependencies
37
+
38
+ RUN pip3 install --no-cache-dir -r requirements.txt
39
+ # RUN chmod +x ./run.sh
40
+ # USER openvino
41
+ # Set up entrypoint
42
+ CMD ["bash", "./run.sh"]
43
+
44
+ # Expose ports
45
+ EXPOSE 8080 9000
app.py ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ sys.path.append('.')
3
+
4
+ import os
5
+ import base64
6
+ import json
7
+ from ctypes import *
8
+ from firesdk import *
9
+ import cv2
10
+ import numpy as np
11
+ from flask import Flask, request, jsonify
12
+
13
+
14
+ licensePath = "license.txt"
15
+ license = ""
16
+
17
+ machineCode = getMachineCode()
18
+ print("\nmachineCode: ", machineCode.decode('utf-8'))
19
+
20
+ try:
21
+ with open(licensePath, 'r') as file:
22
+ license = file.read().strip()
23
+ except IOError as exc:
24
+ print("failed to open license.txt: ", exc.errno)
25
+
26
+ print("\nlicense: ", license)
27
+
28
+ ret = setActivation(license.encode('utf-8'))
29
+ print("\nactivation: ", ret)
30
+
31
+ ret = initSDK()
32
+ print("init: ", ret)
33
+
34
+ app = Flask(__name__)
35
+
36
+ def mat_to_bytes(mat):
37
+ """
38
+ Convert cv::Mat image data (NumPy array in Python) to raw bytes.
39
+ """
40
+ # Encode cv::Mat as PNG bytes
41
+ is_success, buffer = cv2.imencode(".png", mat)
42
+ if not is_success:
43
+ raise ValueError("Failed to encode cv::Mat image")
44
+ return buffer.tobytes()
45
+
46
+ @app.route('/fire', methods=['POST'])
47
+ def fire():
48
+ result = "None"
49
+ object_name = {}
50
+ box = {}
51
+ pro = {}
52
+
53
+ file = request.files['file']
54
+
55
+ try:
56
+ image = cv2.imdecode(np.frombuffer(file.read(), np.uint8), cv2.IMREAD_COLOR)
57
+ # image = cv2.resize(image, (1024, 640))
58
+ except:
59
+ result = "Failed to open file"
60
+ response = jsonify({"result": result, "class": object_name, "coordinate": box, "score": pro})
61
+
62
+ response.status_code = 200
63
+ response.headers["Content-Type"] = "application/json; charset=utf-8"
64
+ return response
65
+
66
+ img_byte = mat_to_bytes(image)
67
+
68
+ box_array = (c_int * 1024)() # Assuming a maximum of 256 rectangles
69
+ score_array = (c_float * 1024)() # Assuming a maximum of 256 rectangles
70
+ label_array = (c_int * 1024)()
71
+
72
+ cnt = getFireDetection(img_byte, len(img_byte), label_array, box_array, score_array)
73
+
74
+ rectangles = [
75
+ (box_array[i * 4], box_array[i * 4 + 1], box_array[i * 4 + 2], box_array[i * 4 + 3])
76
+ for i in range(cnt)]
77
+ scores = [score_array[i] for i in range(cnt)]
78
+ labels = [label_array[i] for i in range(cnt)]
79
+
80
+ # print(f"detection number: {cnt}, box: {rectangles}, labels: {labels}, scores: {scores} \n")
81
+
82
+ if cnt == 0:
83
+ result = "Nothing Detected !"
84
+ response = jsonify({"result": result, "class": object_name, "coordinate": box, "score": pro})
85
+
86
+ response.status_code = 200
87
+ response.headers["Content-Type"] = "application/json; charset=utf-8"
88
+ return response
89
+
90
+ result = "Fire or Smoke Detected !"
91
+ for i in range(cnt):
92
+ if labels[i] == 0:
93
+ object_name[f"id {i + 1}"] = "fire"
94
+ else:
95
+ object_name[f"id {i + 1}"] = "smoke"
96
+ box[f"id {i + 1}"] = rectangles[i]
97
+ pro[f"id {i + 1}"] = scores[i]
98
+
99
+ response = jsonify({"result": result, "class": object_name, "coordinate": box, "score": pro})
100
+
101
+ response.status_code = 200
102
+ response.headers["Content-Type"] = "application/json; charset=utf-8"
103
+ return response
104
+
105
+ @app.route('/fire_base64', methods=['POST'])
106
+ def fire_base64():
107
+
108
+ result = "None"
109
+ object_name = {}
110
+ box = {}
111
+ pro = {}
112
+
113
+ content = request.get_json()
114
+
115
+ try:
116
+ imageBase64 = content['base64']
117
+ image_data = base64.b64decode(imageBase64)
118
+ np_array = np.frombuffer(image_data, np.uint8)
119
+ image = cv2.imdecode(np_array, cv2.IMREAD_COLOR)
120
+ # image = cv2.resize(image, (1024, 640))
121
+ except:
122
+ result = "Failed to open file1"
123
+ response = jsonify({"result": result, "class": object_name, "coordinate": box, "score": pro})
124
+
125
+ response.status_code = 200
126
+ response.headers["Content-Type"] = "application/json; charset=utf-8"
127
+ return response
128
+
129
+
130
+ img_byte = mat_to_bytes(image)
131
+
132
+ box_array = (c_int * 1024)() # Assuming a maximum of 256 rectangles
133
+ score_array = (c_float * 1024)() # Assuming a maximum of 256 rectangles
134
+ label_array = (c_int * 1024)()
135
+
136
+ cnt = getFireDetection(img_byte, len(img_byte), label_array, box_array, score_array)
137
+
138
+ rectangles = [
139
+ (box_array[i * 4], box_array[i * 4 + 1], box_array[i * 4 + 2], box_array[i * 4 + 3])
140
+ for i in range(cnt)]
141
+ scores = [score_array[i] for i in range(cnt)]
142
+ labels = [label_array[i] for i in range(cnt)]
143
+
144
+ # print(f"detection number: {cnt}, box: {rectangles}, labels: {labels}, scores: {scores} \n")
145
+
146
+ if cnt == 0:
147
+ result = "Nothing Detected !"
148
+ response = jsonify({"result": result, "class": object_name, "coordinate": box, "score": pro})
149
+
150
+ response.status_code = 200
151
+ response.headers["Content-Type"] = "application/json; charset=utf-8"
152
+ return response
153
+
154
+ result = "Fire or Smoke Detected !"
155
+ for i in range(cnt):
156
+ if labels[i] == 0:
157
+ object_name[f"id {i + 1}"] = "fire"
158
+ else:
159
+ object_name[f"id {i + 1}"] = "smoke"
160
+ box[f"id {i + 1}"] = rectangles[i]
161
+ pro[f"id {i + 1}"] = scores[i]
162
+
163
+ response = jsonify({"result": result, "class": object_name, "coordinate": box, "score": pro})
164
+
165
+ response.status_code = 200
166
+ response.headers["Content-Type"] = "application/json; charset=utf-8"
167
+ return response
168
+
169
+ if __name__ == '__main__':
170
+ port = int(os.environ.get("PORT", 8080))
171
+ app.run(host='0.0.0.0', port=port)
demo.py ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import requests
3
+ from PIL import Image
4
+ import io
5
+ import cv2
6
+ import numpy as np
7
+
8
+ alpr_count = 0
9
+ def plot_one_box(x, img, color=None, label=None, score=None, line_thickness=3):
10
+ # Plots one bounding box on image img
11
+ tl = line_thickness or round(0.002 * (img.shape[0] + img.shape[1]) / 2) + 1 # line/font thickness
12
+ color = color
13
+ c1, c2 = (int(x[0]), int(x[1])), (int(x[2])+int(x[0]), int(x[3])+int(x[1]))
14
+ cv2.rectangle(img, c1, c2, color, thickness=tl, lineType=cv2.LINE_AA)
15
+ if label:
16
+ tf = max(tl - 1, 1) # font thickness
17
+ t_size = cv2.getTextSize(label, 0, fontScale=tl / 3, thickness=tf)[0]
18
+ c2 = c1[0] + t_size[0], c1[1] - t_size[1] - 3
19
+ cv2.rectangle(img, c1, c2, color, -1, cv2.LINE_AA) # filled
20
+ cv2.putText(img, label, (c1[0], c1[1] - 2), 0, tl / 3, [0, 0, 0], thickness=tf, lineType=cv2.LINE_AA)
21
+
22
+ pro = f"{score:.3f}"
23
+ t_size = cv2.getTextSize(pro, 0, fontScale=tl / 3, thickness=tf)[0]
24
+ c1 = c2
25
+ c2 = c1[0] + t_size[0], c1[1] + t_size[1] + 3
26
+ cv2.rectangle(img, c1, c2, [0, 255, 255], -1, cv2.LINE_AA) # filled
27
+ cv2.putText(img, pro, (c1[0], c2[1] - 2), 0, tl / 3, [0, 0, 0], thickness=tf, lineType=cv2.LINE_AA)
28
+ return img
29
+
30
+ def fire(frame):
31
+ global fire_count
32
+
33
+ fire_count = fire_count + 1
34
+ print("fire_count", fire_count)
35
+ url = "http://127.0.0.1:8080/fire"
36
+ file = {'file': open(frame, 'rb')}
37
+
38
+ r = requests.post(url=url, files=file)
39
+
40
+ fire_output = None
41
+ result = r.json().get('result')
42
+ object_name = r.json().get('class')
43
+ box = r.json().get('coordinate')
44
+ pro = r.json().get('score')
45
+ # print("\n number: ", plate_number)
46
+ # print("\n coordinate: ", box)
47
+ # print("\n score: ", pro)
48
+ try:
49
+ image = cv2.imread(frame, cv2.IMREAD_COLOR)
50
+ if image is None:
51
+ print('image is null')
52
+ sys.exit()
53
+ # image = cv2.resize(image, (1024, 640))
54
+ for obj_name in object_name:
55
+ # print(plate_number)
56
+ image = plot_one_box(box[obj_name], image, label=object_name[obj_name], score=pro[obj_name], color=[0, 255, 0], line_thickness=1)
57
+ image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
58
+
59
+ fire_output = image.copy()
60
+
61
+ except:
62
+ pass
63
+
64
+ return fire_output
65
+
66
+ with gr.Blocks() as demo:
67
+ gr.Markdown(
68
+ """
69
+ # KBY-AI Fire/Smoke Detection SDK Demo
70
+ We offer SDKs for face recognition, liveness detection(anti-spoofing), ID card recognition and ID document liveness detection.
71
+ We also specialize in providing outsourcing services with a variety of technical stacks like AI(Computer Vision/Machine Learning), mobile apps, and web apps.
72
+
73
+ ##### KYC Verification Demo - https://github.com/kby-ai/KYC-Verification-Demo-Android
74
+ ##### ID Capture Web Demo - https://cap.kby-ai.com
75
+ """
76
+ )
77
+
78
+ with gr.TabItem("Fire/Smoke Detection"):
79
+ gr.Markdown(
80
+ """
81
+ ##### Docker Hub - https://hub.docker.com/r/kbyai/fire-smoke-detection
82
+ ```bash
83
+ sudo docker pull kbyai/fire-smoke-detection:latest
84
+ sudo docker run -v ./license.txt:/home/openvino/kby-ai-fire/license.txt -p 8081:8080 -p 9001:9000 kbyai/fire-smoke-detection:latest
85
+ ```
86
+ """
87
+ )
88
+ with gr.Row():
89
+ with gr.Column():
90
+ alpr_image_input = gr.Image(type='filepath', height=300)
91
+ gr.Examples(['fire_examples/test1.jpg', 'fire_examples/test2.jpg', 'fire_examples/test3.jpg', 'fire_examples/test4.jpg'],
92
+ inputs=alpr_image_input)
93
+ fire_confirmation_button = gr.Button("Confirm")
94
+ with gr.Column():
95
+ fire_output = gr.Image(type="numpy")
96
+
97
+ fire_confirmation_button.click(fire, inputs=alpr_image_input, outputs=fire_output)
98
+ gr.HTML('<a href="https://visitorbadge.io/status?path=https%3A%2F%2Fweb.kby-ai.com%2F"><img src="https://api.visitorbadge.io/api/combined?path=https%3A%2F%2Fweb.kby-ai.com%2F&label=VISITORS&countColor=%23263759" /></a>')
99
+
100
+ demo.launch(server_name="0.0.0.0", server_port=7860)
firesdk.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ from ctypes import *
4
+
5
+ libPath = os.path.abspath(os.path.dirname(__file__)) + '/libfire.so'
6
+ firesdk = cdll.LoadLibrary(libPath)
7
+
8
+ getMachineCode = firesdk.getMachineCode
9
+ getMachineCode.argtypes = []
10
+ getMachineCode.restype = c_char_p
11
+
12
+ setActivation = firesdk.setActivation
13
+ setActivation.argtypes = [c_char_p]
14
+ setActivation.restype = c_int32
15
+
16
+ initSDK = firesdk.initSDK
17
+ initSDK.argtypes = []
18
+ initSDK.restype = c_int32
19
+
20
+ getFireDetection = firesdk.get_fire_using_bytes
21
+ getFireDetection.argtypes = [c_char_p, c_ulong, POINTER(c_int), POINTER(c_int), POINTER(c_float)]
22
+ getFireDetection.restype = c_int32
libfire.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:86958ed0abbfb8e6f6528cf83691dad30d7e9e37ab57a92dc387782a9762c89e
3
+ size 8492591
libopencv.zip ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8845c1412c45c484e054235269944e2ac43c90a148ce3444215fe52049cf7479
3
+ size 61014815
ncnn.zip ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6a702183c67f189f3a29c32186ab99e35b2df47a7f61c74aef2c600e7386059b
3
+ size 32239397
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ flask
2
+ flask-cors
3
+ gradio==3.50.2
4
+ datadog_api_client
5
+ opencv-python
run.sh ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ # cd /home/openvino/kby-ai-alpr
2
+ exec python3 demo.py &
3
+ exec python3 app.py