ishworrsubedii commited on
Commit
066c36c
·
verified ·
1 Parent(s): 4a066d9

feat: update model and convert images to RGB for prediction display

Browse files

This commit includes the update of the model used for predictions. Additionally, it introduces a change to convert images to RGB format for better prediction display.

Files changed (37) hide show
  1. .gitignore +1 -2
  2. Dockerfile +17 -0
  3. README.md +94 -61
  4. __pycache__/streamlit_app.cpython-39.pyc +0 -0
  5. app.py +2 -3
  6. demos/__pycache__/__init__.cpython-39.pyc +0 -0
  7. demos/__pycache__/single_image_inference.cpython-39.pyc +0 -0
  8. demos/alert_service_example.py +1 -1
  9. demos/cam_service_example/start_frame_capturing.py +1 -1
  10. demos/cam_service_example/stop_frame_capturing.py +4 -0
  11. demos/image_load_service_example/start_image_load_example.py +23 -3
  12. demos/image_load_service_example/stop_image_load_example.py +5 -3
  13. demos/single_image_inference.py +9 -3
  14. img.png +0 -0
  15. main.py +1 -1
  16. requirements.txt +6 -7
  17. resources/models/v2/best.pt +3 -0
  18. src/__init__.py +4 -0
  19. src/__pycache__/__init__.cpython-39.pyc +0 -0
  20. src/api/__init__.py +4 -0
  21. src/api/fast_api.py +86 -0
  22. src/services/__init__.py +64 -0
  23. src/services/__pycache__/__init__.cpython-39.pyc +0 -0
  24. src/services/alert_service/__init__.py +4 -0
  25. src/services/alert_service/alert_service.py +30 -0
  26. src/services/entity/__init__.py +0 -0
  27. src/services/entity/entity_config.py +7 -0
  28. src/services/image_capture_service/__init__.py +0 -0
  29. src/services/image_capture_service/capture_main.py +95 -0
  30. src/services/image_capture_service/image_load_main.py +87 -0
  31. src/services/weapon_det_service/__init__.py +0 -0
  32. src/services/weapon_det_service/__pycache__/__init__.cpython-39.pyc +0 -0
  33. src/services/weapon_det_service/__pycache__/weapon_detection_service.cpython-39.pyc +0 -0
  34. src/services/weapon_det_service/weapon_detection_service.py +35 -0
  35. src/utils/__init__.py +0 -0
  36. src/utils/settings.py +60 -0
  37. streamlit_app.py +1 -2
.gitignore CHANGED
@@ -158,6 +158,5 @@ cython_debug/
158
  # and can be added to the global gitignore or merged into this file. For a more nuclear
159
  # option (not recommended) you can uncomment the following to ignore the entire idea folder.
160
  .idea/
161
- resources
162
- images
163
 
 
158
  # and can be added to the global gitignore or merged into this file. For a more nuclear
159
  # option (not recommended) you can uncomment the following to ignore the entire idea folder.
160
  .idea/
161
+
 
162
 
Dockerfile ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # base image
2
+ FROM python:3.10
3
+
4
+ # working directory
5
+ WORKDIR /app
6
+
7
+ # Copy the current directory contents into the container at /app
8
+ COPY . .
9
+
10
+ # Install any needed packages specified in requirements.txt
11
+ RUN pip install --no-cache-dir -r requirements.txt
12
+
13
+ # Expose the port the app runs in (streamlit default port)
14
+ EXPOSE 8000
15
+
16
+ # Run app.py when the container launches
17
+ CMD ["streamlit", "run", "app.py"]
README.md CHANGED
@@ -1,95 +1,98 @@
1
- ---
2
-
3
- title: Weapon Detection
4
- emoji: 🐢
5
- colorFrom: green
6
- colorTo: green
7
- sdk: streamlit
8
- python_version: 3.10
9
- sdk_version: 1.32.2
10
- app_file: app.py
11
- pinned: false
12
-
13
- ---
14
-
15
  # weapon-detection-alert-location-share
16
 
17
  This project focuses on enhancing the security of different places, like public areas and banks, by implementing a
18
- robust gun detection and location-sharing system. The system is designed to capture images from an IP camera
19
- strategically placed within the bank premises. When a captured image contains an identifiable gun, the system takes
20
- appropriate actions, such as sending alerts or sharing the location of the detected firearm.
21
 
22
  1. **Image Capture:**
23
 
24
- Utilizes an IP camera to continuously capture images in real-time within the camera range.Images are processed and
25
  analyzed for potential gun presence.
26
 
27
  2. **Gun Detection:**
28
 
29
  Employs advanced computer vision algorithms for accurate gun detection in captured images.
30
  The system recognizes various types of firearms and distinguishes them from other objects.
 
31
  3. Alert Systems:
32
 
33
  When a gun is detected, the system triggers immediate alerts.
34
  Alerts can be configured to notify security personnel, law enforcement, and relevant authorities.
35
- 4. Location Sharing:
36
 
37
- If a gun is detected, the system captures the location of the incident.
38
- The location information is shared in real-time with designated security personnel and law enforcement agencies.
39
 
40
- ## File Structure
 
 
 
 
 
41
 
42
- File structure of the project
43
 
44
- ```commandline
45
 
 
 
46
  ├── config
47
- │   ├── config.ini
48
- │   └── config.yaml
49
- ├── examples
50
- │   ├── start_cap.py
51
- │   └── stop_cap.py
52
  ├── images
53
- │   ├── cam_images
54
-    └── detected_image
55
- │   ├── img_1.png
56
- │   └── img.png
57
  ├── logs
58
- │   └── gun_det.log
 
59
  ├── resources
 
 
 
 
60
  │   └── models
61
- │   └── yolov7.pt
62
- ├── services
63
- │   ├── entity
64
- │   │   └── __init__.py
65
- │   ├── gun_det_service
66
- │   │   ├── detection_example_cam.py
67
- │   │   └── __init__.py
68
- │   ├── image_capture
69
- │   │   ├── capture_main.py
70
- │   │   ├── __init__.py
71
- │   │   ├── main_start_stop.py
72
- │   │   └── yolov7_detection_example.py
73
- │   ├── image_load
74
  │   │   ├── __init__.py
75
- │   │   ├── main_load.py
76
- │   │   ├── main_start_stop.py
77
- │   │   ├── start_load.py
78
- │   │   └── stop_load.py
79
  │   ├── __init__.py
80
- │   └── location_share
81
-    └── __init__.py
82
- ├── utils
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83
  │   ├─��� __init__.py
84
- │   ├── __pycache__
85
- │   │   ├── __init__.cpython-310.pyc
86
- │   │   └── settings.cpython-310.pyc
87
- │   └── settings.py
88
  ├── Dockerfiles
 
89
  ├── main.py
90
  ├── README.md
91
  ├── requirements.txt
92
- └── visualization
93
 
94
 
95
  ```
@@ -115,26 +118,56 @@ File structure of the project
115
 
116
  4. **Perform Inference/Prediction:**
117
  ```bash
118
- python3 main.py
119
  streamlit run streamlit_app.py
120
  ```
121
 
122
  - We have to run both programs for inference. py for fastapi post request and streamlit for UI for the prediction.
 
 
 
 
123
 
124
  ### Docker
125
 
126
  ```commandline
 
 
 
 
 
 
 
127
  ```
128
 
129
  # 🔥Features
130
 
 
 
 
131
  # ⚠️ Limitations
132
 
 
 
 
133
  # Future Work
134
 
 
 
 
 
135
  # Demo
136
 
 
 
 
 
 
137
  # Recommendations
138
 
139
  Your recommendations are highly valuable, and I highly value your insights and suggestions to enhance this project! Feel
140
- free to propose new features, report bugs, or suggest improvements.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  # weapon-detection-alert-location-share
2
 
3
  This project focuses on enhancing the security of different places, like public areas and banks, by implementing a
4
+ robust gun detection and alert system. The system is designed to capture images from an IP camera strategically placed.
5
+ within the bank's premises. When a captured image contains an identifiable gun, the system takes
6
+ appropriate actions, such as playing alerts or sharing the location of the detected weapons, including knife and guns.
7
 
8
  1. **Image Capture:**
9
 
10
+ Utilizes an IP camera to continuously capture images in real-time within the camera range. Images are processed and
11
  analyzed for potential gun presence.
12
 
13
  2. **Gun Detection:**
14
 
15
  Employs advanced computer vision algorithms for accurate gun detection in captured images.
16
  The system recognizes various types of firearms and distinguishes them from other objects.
17
+
18
  3. Alert Systems:
19
 
20
  When a gun is detected, the system triggers immediate alerts.
21
  Alerts can be configured to notify security personnel, law enforcement, and relevant authorities.
 
22
 
23
+ # 🚀 Technologies
 
24
 
25
+ - **Python**
26
+ - **FastAPI**
27
+ - **Streamlit**
28
+ - **YOLO**
29
+ - **OpenCV**
30
+ - **Docker**
31
 
32
+ # File Structure
33
 
34
+ File structure of the project
35
 
36
+ ```angular2html
37
+ .
38
  ├── config
39
+ │   └── config.ini
 
 
 
 
40
  ├── images
41
+ │   └── cam_images
42
+    └── th-3711382641.jpg
 
 
43
  ├── logs
44
+ │   ├── gun_det.log
45
+ │   └── ipcam.log
46
  ├── resources
47
+ │   ├── alert
48
+ │   │   └── alert.mp3
49
+ │   ├── flag_load_image
50
+ │   ├── image_capturing
51
  │   └── models
52
+ │   ├── best.pt
53
+ │   ├── v1
54
+    │   └── best.pt
55
+ ├── src
56
+ │   ├── api
57
+ │   │   ├── fast_api.py
 
 
 
 
 
 
 
58
  │   │   ├── __init__.py
 
 
 
 
59
  │   ├── __init__.py
60
+ │   ├── services
61
+    │   ├── alert_service
62
+ │   │   │   ├── alert_service.py
63
+ │   │   │   ├── __init__.py
64
+ │   │   │   └── __pycache__
65
+ │   │   ├── entity
66
+ │   │   │   ├── entity_config.py
67
+ │   │   │   └── __init__.py
68
+ │   │   ├── image_capture_service
69
+ │   │   │   ├── capture_main.py
70
+ │   │   │   ├── image_load_main.py
71
+ │   │   │   ├── __init__.py
72
+ │   │   ├── __init__.py
73
+ │   │   └── weapon_det_service
74
+ │   │   ├── __init__.py
75
+ │   │   └── weapon_detection_service.py
76
+ │   └── utils
77
+ │   ├── __init__.py
78
+ │   ├── __pycache__
79
+ │   └── settings.py
80
+ ├── demos
81
+ │   ├── alert_service_example.py
82
+ │   ├── cam_service_example
83
+ │   │   ├── start_frame_capturing.py
84
+ │   │   └── stop_frame_capturing.py
85
+ │   ├── image_load_service_example
86
+ │   │   ├── start_image_load_example.py
87
+ │   │   └── stop_image_load_example.py
88
  │   ├─��� __init__.py
89
+ │   └── single_image_inference.py
 
 
 
90
  ├── Dockerfiles
91
+ ├── app.py
92
  ├── main.py
93
  ├── README.md
94
  ├── requirements.txt
95
+ └── streamlit_app.py
96
 
97
 
98
  ```
 
118
 
119
  4. **Perform Inference/Prediction:**
120
  ```bash
 
121
  streamlit run streamlit_app.py
122
  ```
123
 
124
  - We have to run both programs for inference. py for fastapi post request and streamlit for UI for the prediction.
125
+ 5. **Perform Single Image Inference:**
126
+ ```bash
127
+ streamlit run app.py
128
+ ```
129
 
130
  ### Docker
131
 
132
  ```commandline
133
+ docker build -t myapp .
134
+ ```
135
+
136
+ Then run the docker container
137
+
138
+ ```commandline
139
+ docker myapp
140
  ```
141
 
142
  # 🔥Features
143
 
144
+ - **Real-time Gun Detection:** The system can detect guns in real-time images captured by an IP camera.
145
+ - **Alert System:** The system can send alerts to security personnel and law enforcement when a gun is detected.
146
+
147
  # ⚠️ Limitations
148
 
149
+ - The system may not be able to detect guns in low-light conditions or when the weapon is partially obscured.
150
+ - Accuracy may vary based on the quality of the images captured by the IP camera.
151
+
152
  # Future Work
153
 
154
+ - One of the future work is to train the model on diverse datasets to improve the model's performance and accuracy.
155
+ - Implement and test the system in real-world scenarios using raspberry pi or other edge devices.
156
+ - Develop a feature to share the location of detected with the authorities.
157
+
158
  # Demo
159
 
160
+ For single image inference i have used huggingface here you can try it
161
+ out [here](https://huggingface.co/spaces/ishworrsubedii/weapon-detection)
162
+
163
+ ![img.png](img.png)
164
+
165
  # Recommendations
166
 
167
  Your recommendations are highly valuable, and I highly value your insights and suggestions to enhance this project! Feel
168
+ free to propose new features, report bugs, or suggest improvements.
169
+
170
+ # Contributors
171
+
172
+ Contributions are always welcome! If you'd like to contribute to this project or have any suggestions, please feel free
173
+ to reach out or submit a pull request.
__pycache__/streamlit_app.cpython-39.pyc ADDED
Binary file (1.19 kB). View file
 
app.py CHANGED
@@ -4,16 +4,14 @@ Date: 2024-04-04
4
  """
5
  import streamlit as st
6
  from PIL import Image
 
7
 
8
  from demos.single_image_inference import single_image_inference
9
 
10
- # Constants
11
  MAX_FILE_SIZE = 5 * 1024 * 1024 # 5MB
12
 
13
- # Configure Streamlit
14
  st.set_page_config(layout="wide", page_title="Weapon Detection")
15
 
16
- # Write to Streamlit
17
  st.write("## Weapon Detection")
18
  st.write(
19
  "This app uses a custom trained yolov8 model to detect weapons in images. Upload an image to see the detection results."
@@ -33,6 +31,7 @@ def process_image(upload):
33
 
34
  processed_image = single_image_inference(image)
35
  col2.write("Predicted Image")
 
36
  col2.image(processed_image)
37
  st.sidebar.markdown("\n")
38
  except Exception as e:
 
4
  """
5
  import streamlit as st
6
  from PIL import Image
7
+ import cv2
8
 
9
  from demos.single_image_inference import single_image_inference
10
 
 
11
  MAX_FILE_SIZE = 5 * 1024 * 1024 # 5MB
12
 
 
13
  st.set_page_config(layout="wide", page_title="Weapon Detection")
14
 
 
15
  st.write("## Weapon Detection")
16
  st.write(
17
  "This app uses a custom trained yolov8 model to detect weapons in images. Upload an image to see the detection results."
 
31
 
32
  processed_image = single_image_inference(image)
33
  col2.write("Predicted Image")
34
+ processed_image = cv2.cvtColor(processed_image, cv2.COLOR_BGR2RGB)
35
  col2.image(processed_image)
36
  st.sidebar.markdown("\n")
37
  except Exception as e:
demos/__pycache__/__init__.cpython-39.pyc CHANGED
Binary files a/demos/__pycache__/__init__.cpython-39.pyc and b/demos/__pycache__/__init__.cpython-39.pyc differ
 
demos/__pycache__/single_image_inference.cpython-39.pyc CHANGED
Binary files a/demos/__pycache__/single_image_inference.cpython-39.pyc and b/demos/__pycache__/single_image_inference.cpython-39.pyc differ
 
demos/alert_service_example.py CHANGED
@@ -2,7 +2,7 @@
2
  Created By: ishwor subedi
3
  Date: 2023-12-30
4
  """
5
- from services.alert_service.alert_service import AlertService
6
 
7
  if __name__ == '__main__':
8
  alert_service = AlertService("resources/alert/alert.mp3")
 
2
  Created By: ishwor subedi
3
  Date: 2023-12-30
4
  """
5
+ from src.services.alert_service.alert_service import AlertService
6
 
7
  if __name__ == '__main__':
8
  alert_service = AlertService("resources/alert/alert.mp3")
demos/cam_service_example/start_frame_capturing.py CHANGED
@@ -1,6 +1,6 @@
1
  import os
2
  import time
3
- from services.image_capture_service.capture_main import FrameSaver
4
 
5
 
6
  class ImageCaptureService:
 
1
  import os
2
  import time
3
+ from src.services.image_capture_service.capture_main import FrameSaver
4
 
5
 
6
  class ImageCaptureService:
demos/cam_service_example/stop_frame_capturing.py CHANGED
@@ -6,6 +6,10 @@ class StopImageCaptureServiceExample:
6
  self.stop_flag_path = stop_flag_path
7
 
8
  def stop_example_ipcam_webcam(self):
 
 
 
 
9
  try:
10
  with open(self.stop_flag_path, 'w') as flag_file:
11
  flag_file.write("True")
 
6
  self.stop_flag_path = stop_flag_path
7
 
8
  def stop_example_ipcam_webcam(self):
9
+ """
10
+ Stop the image capturing service
11
+ :return:
12
+ """
13
  try:
14
  with open(self.stop_flag_path, 'w') as flag_file:
15
  flag_file.write("True")
demos/image_load_service_example/start_image_load_example.py CHANGED
@@ -1,8 +1,7 @@
1
  import os
2
- import sys
3
  import time
4
- import threading
5
- from services.image_capture_service.image_load_main import ImageLoad
6
 
7
 
8
  class StartImageLoadExample:
@@ -14,6 +13,10 @@ class StartImageLoadExample:
14
  self.running = False
15
 
16
  def create_stop_flag(self):
 
 
 
 
17
  try:
18
  with open(self.flag_path, 'w') as flag_file:
19
  flag_file.write('False')
@@ -21,6 +24,10 @@ class StartImageLoadExample:
21
  print(f"Error creating stop flag: {e}")
22
 
23
  def check_stop_flag(self):
 
 
 
 
24
  try:
25
  if os.path.exists(self.flag_path):
26
  with open(self.flag_path, 'r') as flag_file:
@@ -33,6 +40,11 @@ class StartImageLoadExample:
33
  return False
34
 
35
  def update_stop_flag(self, value):
 
 
 
 
 
36
  try:
37
  with open(self.flag_path, 'w') as flag_file:
38
  flag_file.write(str(value))
@@ -40,6 +52,10 @@ class StartImageLoadExample:
40
  print(f"Error updating stop flag: {e}")
41
 
42
  def start_service(self):
 
 
 
 
43
  try:
44
  self.running = True
45
  start_load = ImageLoad(self.image_dir, self.model_path)
@@ -70,6 +86,10 @@ class StartImageLoadExample:
70
  "Issue encountered while stopping image loading services_trinetra in finally block.")
71
 
72
  def stop_service(self):
 
 
 
 
73
  self.update_stop_flag("True")
74
 
75
 
 
1
  import os
 
2
  import time
3
+
4
+ from src.services.image_capture_service.image_load_main import ImageLoad
5
 
6
 
7
  class StartImageLoadExample:
 
13
  self.running = False
14
 
15
  def create_stop_flag(self):
16
+ """
17
+ Create a stop flag file
18
+ :return:
19
+ """
20
  try:
21
  with open(self.flag_path, 'w') as flag_file:
22
  flag_file.write('False')
 
24
  print(f"Error creating stop flag: {e}")
25
 
26
  def check_stop_flag(self):
27
+ """
28
+ Check the stop flag
29
+ :return:
30
+ """
31
  try:
32
  if os.path.exists(self.flag_path):
33
  with open(self.flag_path, 'r') as flag_file:
 
40
  return False
41
 
42
  def update_stop_flag(self, value):
43
+ """
44
+ Update the stop flag
45
+ :param value: value to update the stop flag
46
+ :return:
47
+ """
48
  try:
49
  with open(self.flag_path, 'w') as flag_file:
50
  flag_file.write(str(value))
 
52
  print(f"Error updating stop flag: {e}")
53
 
54
  def start_service(self):
55
+ """
56
+ Start the image loading service
57
+ :return:
58
+ """
59
  try:
60
  self.running = True
61
  start_load = ImageLoad(self.image_dir, self.model_path)
 
86
  "Issue encountered while stopping image loading services_trinetra in finally block.")
87
 
88
  def stop_service(self):
89
+ """
90
+ Stop the image loading service
91
+ :return:
92
+ """
93
  self.update_stop_flag("True")
94
 
95
 
demos/image_load_service_example/stop_image_load_example.py CHANGED
@@ -3,9 +3,7 @@ Created By: ishwor subedi
3
  Date: 2023-12-28
4
  """
5
 
6
- import os
7
- import os
8
- from services import ipcam_logger
9
 
10
 
11
  class StopImageLoadServiceExample:
@@ -14,6 +12,10 @@ class StopImageLoadServiceExample:
14
  self.logger = ipcam_logger()
15
 
16
  def stop_service(self):
 
 
 
 
17
  try:
18
  with open(self.stop_flag_path, 'w') as flag_file:
19
  flag_file.write("True")
 
3
  Date: 2023-12-28
4
  """
5
 
6
+ from src.services import ipcam_logger
 
 
7
 
8
 
9
  class StopImageLoadServiceExample:
 
12
  self.logger = ipcam_logger()
13
 
14
  def stop_service(self):
15
+ """
16
+ Stop the image loading service
17
+ :return:
18
+ """
19
  try:
20
  with open(self.stop_flag_path, 'w') as flag_file:
21
  flag_file.write("True")
demos/single_image_inference.py CHANGED
@@ -2,18 +2,24 @@
2
  Created By: ishwor subedi
3
  Date: 2024-04-04
4
  """
5
- from services.weapon_det_service.weapon_detection_service import DetectionService
6
  import cv2 as cv
7
 
 
 
8
 
9
  def single_image_inference(image_path):
 
 
 
 
 
10
  detection_service = DetectionService(
11
- model_path='resources/models/v1/best.pt',
12
 
13
  )
14
  results = detection_service.image_det_save(
15
  image_path=image_path,
16
- thresh=0.5
17
  )
18
  for result in results:
19
  original_image = result.orig_img
 
2
  Created By: ishwor subedi
3
  Date: 2024-04-04
4
  """
 
5
  import cv2 as cv
6
 
7
+ from src.services.weapon_det_service.weapon_detection_service import DetectionService
8
+
9
 
10
  def single_image_inference(image_path):
11
+ """
12
+ This function is used to detect the weapon in the image and save the image with bounding box
13
+ :param image_path: image path to detect the weapon
14
+ :return: image vector with bounding box
15
+ """
16
  detection_service = DetectionService(
17
+ model_path='resources/models/v2/best.pt',
18
 
19
  )
20
  results = detection_service.image_det_save(
21
  image_path=image_path,
22
+ thresh=0.4
23
  )
24
  for result in results:
25
  original_image = result.orig_img
img.png ADDED
main.py CHANGED
@@ -4,7 +4,7 @@ Date: 2024-01-02
4
  """
5
  import uvicorn
6
 
7
- from services.api.fast_api import app
8
 
9
  if __name__ == "__main__":
10
  uvicorn.run(app, host="localhost", port=8000)
 
4
  """
5
  import uvicorn
6
 
7
+ from src.api.fast_api import app
8
 
9
  if __name__ == "__main__":
10
  uvicorn.run(app, host="localhost", port=8000)
requirements.txt CHANGED
@@ -1,13 +1,12 @@
1
- ensure==1.0.4
2
  fastapi==0.110.1
3
- imagehash==4.3.1
4
- opencv_python==4.9.0.80
 
 
5
  pandas==2.2.1
6
  Pillow==10.3.0
7
  pygame==2.5.2
8
- PyYAML==6.0.1
9
- PyYAML==6.0.1
10
  Requests==2.31.0
11
- streamlit==1.32.2
12
- ultralytics==8.1.42
13
  uvicorn==0.29.0
 
 
1
  fastapi==0.110.1
2
+ ImageHash==4.3.1
3
+ opencv_contrib_python==4.6.0.66
4
+ opencv_python==4.8.1.78
5
+ opencv_python_headless==4.8.0.74
6
  pandas==2.2.1
7
  Pillow==10.3.0
8
  pygame==2.5.2
 
 
9
  Requests==2.31.0
10
+ streamlit==1.29.0
11
+ ultralytics==8.0.230
12
  uvicorn==0.29.0
resources/models/v2/best.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b5eaacb7deeabd85f8b98ed37c084627fc7640bae7b2c6fa91d7e4e209c1f741
3
+ size 12351346
src/__init__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ """
2
+ Created By: ishwor subedi
3
+ Date: 2024-04-04
4
+ """
src/__pycache__/__init__.cpython-39.pyc ADDED
Binary file (197 Bytes). View file
 
src/api/__init__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ """
2
+ Created By: ishwor subedi
3
+ Date: 2023-12-28
4
+ """
src/api/fast_api.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI
2
+ from fastapi.responses import JSONResponse
3
+ from fastapi import HTTPException
4
+ import uvicorn
5
+ from demos.cam_service_example.start_frame_capturing import ImageCaptureService
6
+ from demos.cam_service_example.stop_frame_capturing import StopImageCaptureServiceExample
7
+ from demos.image_load_service_example.start_image_load_example import StartImageLoadExample
8
+ from demos.image_load_service_example.stop_image_load_example import StopImageLoadServiceExample
9
+
10
+ app = FastAPI()
11
+
12
+
13
+ def start_ipcam():
14
+ flag_path = "resources/flag"
15
+
16
+ source = 'rtsp://ishwor:subedi@192.168.1.106:5555/h264_opus.sdp'
17
+
18
+ image_path_to_save = "images/cam_images"
19
+ image_hash_threshold = 5
20
+ image_capture_start_example = ImageCaptureService(flag_path, source, image_path_to_save,
21
+ image_hash_threshold)
22
+ image_capture_start_example.start_service()
23
+
24
+
25
+ def stop_ipcam():
26
+ flag_path = "resources/flag"
27
+
28
+ image_capture_stop_example = StopImageCaptureServiceExample(flag_path)
29
+ image_capture_stop_example.stop_load_image_example()
30
+
31
+
32
+ def start_detection():
33
+ flag_path = "resources/flag_load_image"
34
+
35
+ image_dir_path = "images/cam_images"
36
+
37
+ start_load_image_example = StartImageLoadExample(flag_path, image_dir_path, model_path="resources/model/v1/best.pt")
38
+ start_load_image_example.start_service()
39
+
40
+
41
+ def stop_detection():
42
+ flag_path = "resources/flag_load_image"
43
+
44
+ stop_load_image_example = StopImageLoadServiceExample(flag_path)
45
+ stop_load_image_example.stop_service()
46
+
47
+
48
+ # FastAPI Endpoints
49
+ @app.post("/start_ipcam_server")
50
+ def start_ipcam_server_api():
51
+ try:
52
+ start_ipcam()
53
+ return JSONResponse(content={"message": "IP Cam Server started!"}, status_code=200)
54
+ except Exception as e:
55
+ raise HTTPException(status_code=500, detail=str(e))
56
+
57
+
58
+ @app.post("/stop_ipcam_server")
59
+ def stop_ipcam_server_api():
60
+ try:
61
+ stop_ipcam()
62
+ return JSONResponse(content={"message": "IP Cam Server stopped!"}, status_code=200)
63
+ except Exception as e:
64
+ raise HTTPException(status_code=500, detail=str(e))
65
+
66
+
67
+ @app.post("/start_detection_service")
68
+ def start_detection_service_api():
69
+ try:
70
+ start_detection()
71
+ return JSONResponse(content={"message": "Image loading Server started!"}, status_code=200)
72
+ except Exception as e:
73
+ raise HTTPException(status_code=500, detail=str(e))
74
+
75
+
76
+ @app.post("/stop_detection_service")
77
+ def stop_detection_service_api():
78
+ try:
79
+ stop_detection()
80
+ return JSONResponse(content={"message": "Image loading Server stopped!"}, status_code=200)
81
+ except Exception as e:
82
+ raise HTTPException(status_code=500, detail=str(e))
83
+
84
+
85
+ if __name__ == "__main__":
86
+ uvicorn.run(app, host="localhost", port=8001)
src/services/__init__.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ import logging
4
+
5
+
6
+ def configure_logger(logger_name, log_filename, log_dir="logs"):
7
+ """
8
+ Configures a logger with specified parameters.
9
+
10
+ :param logger_name: Name of the logger.
11
+ :param log_filename: Name of the log file.
12
+ :param log_dir: Directory where logs will be stored. Defaults to "logs".
13
+ :return: Configured logger.
14
+ """
15
+ logging_str = "[%(asctime)s:%(levelname)s:%(module)s:%(message)s]"
16
+
17
+ log_path = os.path.join(log_dir, log_filename)
18
+ os.makedirs(log_dir, exist_ok=True)
19
+
20
+ logger = logging.getLogger(logger_name)
21
+ logger.setLevel(logging.INFO)
22
+
23
+ formatter = logging.Formatter(logging_str)
24
+
25
+ file_handler = logging.FileHandler(log_path)
26
+ file_handler.setFormatter(formatter)
27
+
28
+ stream_handler = logging.StreamHandler(sys.stdout)
29
+ stream_handler.setFormatter(formatter)
30
+
31
+ logger.addHandler(file_handler)
32
+ logger.addHandler(stream_handler)
33
+
34
+ return logger
35
+
36
+
37
+ def main_sys_logger(log_dir="logs"):
38
+ """
39
+ Configures and returns the main system logger.
40
+
41
+ :param log_dir: Directory where logs will be stored. Defaults to "logs".
42
+ :return: Main system logger.
43
+ """
44
+ return configure_logger("main_sys_logger", "gun_det.log", log_dir)
45
+
46
+
47
+ def ipcam_logger(log_dir="logs"):
48
+ """
49
+ Configures and returns the IP camera logger.
50
+
51
+ :param log_dir: Directory where logs will be stored. Defaults to "logs".
52
+ :return: IP camera logger.
53
+ """
54
+ return configure_logger("ipcam_logger", "ipcam.log", log_dir)
55
+
56
+
57
+ def detection_logger(log_dir="logs"):
58
+ """
59
+ Configures and returns the detection logger.
60
+
61
+ :param log_dir: Directory where logs will be stored. Defaults to "logs".
62
+ :return: Detection logger.
63
+ """
64
+ return configure_logger("detection_logger", "detection.log", log_dir)
src/services/__pycache__/__init__.cpython-39.pyc ADDED
Binary file (1.97 kB). View file
 
src/services/alert_service/__init__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ """
2
+ Created By: ishwor subedi
3
+ Date: 2023-12-29
4
+ """
src/services/alert_service/alert_service.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Created By: ishwor subedi
3
+ Date: 2023-12-30
4
+ """
5
+
6
+ import pygame
7
+
8
+
9
+ class AlertService:
10
+ def __init__(self, alert_sound_path):
11
+ self.alert_sound_path = alert_sound_path
12
+ pygame.init()
13
+
14
+ def play_alert(self):
15
+ """
16
+ This function help us to play the alert sound
17
+ :return:
18
+ """
19
+ try:
20
+ pygame.mixer.init()
21
+ alert_sound = pygame.mixer.Sound(self.alert_sound_path)
22
+ alert_sound.play()
23
+ pygame.time.wait(int(alert_sound.get_length() * 1000)) # Wait for the sound to finish playing
24
+ except pygame.error as e:
25
+ print(f"Error playing alert sound: {e}")
26
+
27
+
28
+ if __name__ == '__main__':
29
+ alert_service = AlertService("resources/alert/alert.mp3")
30
+ alert_service.play_alert()
src/services/entity/__init__.py ADDED
File without changes
src/services/entity/entity_config.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ from dataclasses import dataclass
2
+ from pathlib import Path
3
+
4
+
5
+ @dataclass(frozen=True)
6
+ class StreamLitConfig:
7
+ pass
src/services/image_capture_service/__init__.py ADDED
File without changes
src/services/image_capture_service/capture_main.py ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Author: ishwor subedi
3
+ Date: 2023-12-28
4
+ Project Name:gun-detection
5
+
6
+ """
7
+ import os
8
+ from PIL import Image
9
+ from datetime import datetime
10
+ import threading
11
+ import imagehash
12
+ import cv2 as cv
13
+ from src.utils.settings import get_frame_save_dir
14
+
15
+
16
+ class FrameSaver:
17
+ def __init__(self, source, image_path_to_save, image_hash_threshold):
18
+ self.source = source
19
+ self.image_path_to_save = image_path_to_save
20
+ if self.image_path_to_save is None or not os.path.exists(self.image_path_to_save):
21
+ self.image_path_to_save = get_frame_save_dir()
22
+ self.thread_running = False
23
+ self.frame_save_thread = None
24
+ self.cap = cv.VideoCapture(self.source)
25
+ self.image_hash_threshold = image_hash_threshold
26
+
27
+ def start_stream(self):
28
+ """
29
+ Start the video stream
30
+ :return:
31
+ """
32
+ self.frame_save_thread = threading.Thread(target=self.video_webcam_frame_extraction)
33
+ self.frame_save_thread.start()
34
+ self.thread_running = True
35
+
36
+ def stop_stream(self):
37
+ """
38
+ Stop the video stream
39
+ :return:
40
+ """
41
+ if self.thread_running:
42
+ self.thread_running = False
43
+ self.frame_save_thread.join()
44
+ self.cap.release()
45
+
46
+ def hashing_diff(self, prev_frame, current_frame):
47
+ """
48
+ This function is used to calculate the hash difference between the previous frame and the current frame
49
+ :param prev_frame: previous frame
50
+ :param current_frame: current frame
51
+ :return:
52
+ """
53
+ if prev_frame is None:
54
+ return None
55
+ else:
56
+ hash1 = imagehash.average_hash(Image.fromarray(prev_frame))
57
+ hash2 = imagehash.average_hash(Image.fromarray(current_frame))
58
+ return hash2 - hash1
59
+
60
+ def video_webcam_frame_extraction(self):
61
+ """
62
+ This function is used to extract the frame from the video stream and save the image if the hash difference is greater than the threshold value.
63
+ :return:
64
+ """
65
+
66
+ try:
67
+
68
+ previous_frame = None
69
+ while self.cap.isOpened():
70
+ success, frame = self.cap.read()
71
+ if success:
72
+ hash_diff = self.hashing_diff(previous_frame, frame)
73
+ if hash_diff is None or hash_diff > self.image_hash_threshold:
74
+ current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
75
+ name = os.path.join(self.image_path_to_save, f"{current_time}.jpg")
76
+ success = cv.imwrite(name, frame)
77
+ if success:
78
+ print(f"Saved {name}...")
79
+ else:
80
+ print(f"Failed to save image: {name}")
81
+ previous_frame = frame
82
+ except Exception as e:
83
+ print(f"Exception occurred: {e}")
84
+ try:
85
+ self.stop_stream()
86
+ except Exception as e:
87
+ print(f"Failed to stop stream: {e}")
88
+
89
+
90
+ if __name__ == '__main__':
91
+ source = 'rtsp://ishwor:subedi@192.168.1.106:5555/h264_opus.sdp'
92
+ image_path_to_save = "images/cam_images"
93
+ image_hash_threshold = 5
94
+ image_capture_service = FrameSaver(source, image_path_to_save, image_hash_threshold)
95
+ image_capture_service.video_webcam_frame_extraction()
src/services/image_capture_service/image_load_main.py ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import time
3
+ import threading
4
+ from src.services.weapon_det_service.weapon_detection_service import DetectionService
5
+ import cv2
6
+
7
+
8
+ class ImageLoad:
9
+ def __init__(self, image_dir, model_path, ):
10
+ self.flag = False
11
+ self.thread_running = False
12
+ self.image_load = None
13
+ self.image_path_img = image_dir
14
+ self.latest_image_path = None
15
+ self.detection_service = DetectionService(
16
+ model_path=model_path,
17
+ )
18
+ self.filename = None
19
+ self.display = True
20
+
21
+ self.image_info_save = None
22
+ self.original_image = None
23
+ self.bbox = None
24
+ self.image_display_thread = None
25
+
26
+ def start_load_image(self):
27
+ """
28
+ Start the image loading thread
29
+ :return:
30
+ """
31
+ self.image_load = threading.Thread(target=self.image_list)
32
+
33
+ self.image_load.start()
34
+
35
+ self.thread_running = True
36
+
37
+ def stop_load_image(self):
38
+ """
39
+ Stop the image loading thread
40
+ :return:
41
+ """
42
+ if self.thread_running:
43
+ self.thread_running = False
44
+
45
+ self.image_load.join()
46
+ print("Stopping the image loading thread...")
47
+
48
+ def image_list(self):
49
+ """
50
+ This function is used to load the image from the image directory
51
+ :return: None
52
+ """
53
+ time.sleep(0.1)
54
+ while self.thread_running:
55
+ files = sorted(os.listdir(self.image_path_img))
56
+ for self.filename in files:
57
+ if not self.thread_running:
58
+ break
59
+
60
+ image_path = os.path.join(self.image_path_img, self.filename)
61
+
62
+ self.latest_image_path = image_path
63
+ print("Processing:", self.latest_image_path)
64
+
65
+ rd = cv2.imread(self.latest_image_path)
66
+ time.sleep(0.5)
67
+ if rd is not None:
68
+ results = self.detection_service.image_det_save(image_path=self.latest_image_path,
69
+ thresh=0.5,
70
+ )
71
+ cv2.waitKey(3)
72
+ print('done')
73
+ os.remove(self.latest_image_path)
74
+ else:
75
+ print('Image Loading Failed .......')
76
+
77
+
78
+ if __name__ == '__main__':
79
+ image_load = ImageLoad(
80
+ image_dir='images/cam_images',
81
+ model_path='resources/models/v1/best.pt',
82
+ )
83
+
84
+ image_load.start_load_image()
85
+ # time.sleep(10)
86
+ # image_load.stop_load_image()
87
+ # print("Exiting the program...")
src/services/weapon_det_service/__init__.py ADDED
File without changes
src/services/weapon_det_service/__pycache__/__init__.cpython-39.pyc ADDED
Binary file (169 Bytes). View file
 
src/services/weapon_det_service/__pycache__/weapon_detection_service.cpython-39.pyc ADDED
Binary file (1.33 kB). View file
 
src/services/weapon_det_service/weapon_detection_service.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pathlib import Path
2
+ from ultralytics import YOLO
3
+
4
+
5
+ class DetectionService:
6
+ def __init__(self, model_path):
7
+ self.model_path = model_path
8
+
9
+ def image_det_save(self, image_path, thresh=0.2):
10
+ """
11
+ This function is used to detect the weapon in the image and save the image with bounding box
12
+ :param image_path: image path to detect the weapon
13
+ :param thresh: threshold value for detection
14
+ :return:
15
+ """
16
+
17
+ detector = YOLO(self.model_path)
18
+ results = detector.predict(image_path, conf=thresh, show=False)
19
+
20
+ return results
21
+
22
+
23
+ if __name__ == "__main__":
24
+ detection_service = DetectionService(
25
+ model_path='resources/models/v1/best.pt',
26
+
27
+ )
28
+ input_image_path = Path(
29
+ "/home/ishwor/Downloads/PY-4856_Crosman-Bushmaster-MPW-Full_1558033480-458822316.jpg")
30
+
31
+ detection_service.image_det_save(
32
+ image_path=str(input_image_path),
33
+
34
+ thresh=0.2
35
+ )
src/utils/__init__.py ADDED
File without changes
src/utils/settings.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Author: ishwor subedi
3
+ Date: 2023-12-27
4
+
5
+ """
6
+ import os
7
+
8
+ from src.services import main_sys_logger
9
+ import cv2 as cv
10
+
11
+ main_sys_logger = main_sys_logger()
12
+
13
+
14
+ def get_frame_save_dir():
15
+ """
16
+ Create a directory for saving images from a video.
17
+
18
+ :return:
19
+ str: The path of the created or existing directory.
20
+ """
21
+ root_dir = 'images/cam_images'
22
+
23
+ frame_dir = os.path.join(root_dir)
24
+ if not os.path.exists(frame_dir):
25
+ main_sys_logger.info(f"<<<<<<<<<<<<<<<<<< Folder created {frame_dir} >>>>>>>>>>>>>>>>>>>>")
26
+ os.makedirs(frame_dir)
27
+ return frame_dir
28
+
29
+
30
+ def imutil(image_path, output_path, new_size=None):
31
+ """
32
+ Resize an image using OpenCV.
33
+
34
+ :param image_path: str, path to the input image file.
35
+ :param output_path: str, path to save the resized image.
36
+ :param new_size: tuple, (width, height) of the desired size.
37
+ """
38
+ try:
39
+ image = cv.imread(image_path)
40
+
41
+ if new_size is not None:
42
+ image = cv.resize(image, new_size)
43
+
44
+ cv.imwrite(output_path, image)
45
+ main_sys_logger.info(f"Image saved to: {output_path}")
46
+ except Exception as e:
47
+ main_sys_logger.error(f"Error in imutil: {e}")
48
+
49
+
50
+ # Example usage:
51
+ if __name__ == "__main__":
52
+ # Get the directory for saving frames
53
+ frame_dir = get_frame_save_dir()
54
+
55
+ # Example image path and output path
56
+ input_image_path = 'path/to/your/input/image.jpg'
57
+ output_image_path = os.path.join(frame_dir, 'resized_image.jpg')
58
+
59
+ # Resize the image and save it
60
+ imutil(input_image_path, output_image_path, new_size=(800, 600))
streamlit_app.py CHANGED
@@ -4,7 +4,7 @@ import streamlit as st
4
  import pandas as pd
5
  import uvicorn
6
 
7
- from services.api.fast_api import app
8
 
9
  LOG_DIR = "logs"
10
  API_URL = "http://localhost:8000"
@@ -132,5 +132,4 @@ def main_streamlit():
132
 
133
  if __name__ == '__main__':
134
  uvicorn.run(app, host="localhost", port=8000)
135
-
136
  main_streamlit()
 
4
  import pandas as pd
5
  import uvicorn
6
 
7
+ from src.api.fast_api import app
8
 
9
  LOG_DIR = "logs"
10
  API_URL = "http://localhost:8000"
 
132
 
133
  if __name__ == '__main__':
134
  uvicorn.run(app, host="localhost", port=8000)
 
135
  main_streamlit()