hexss 0.2.1__tar.gz → 0.3.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (27) hide show
  1. {hexss-0.2.1 → hexss-0.3.0}/PKG-INFO +1 -1
  2. hexss-0.3.0/hexss/constants/__init__.py +1 -0
  3. hexss-0.3.0/hexss/example/camera_server.py +4 -0
  4. hexss-0.3.0/hexss/example/multicore.py +33 -0
  5. hexss-0.3.0/hexss/example/multicore2.py +56 -0
  6. hexss-0.3.0/hexss/multiprocessing/__init__.py +2 -0
  7. hexss-0.3.0/hexss/multiprocessing/multicore.py +23 -0
  8. hexss-0.3.0/hexss/server/__init__.py +1 -0
  9. hexss-0.3.0/hexss/server/camera_server.py +218 -0
  10. hexss-0.3.0/hexss/server/templates/simulate_CCTV.html +128 -0
  11. {hexss-0.2.1 → hexss-0.3.0}/hexss.egg-info/PKG-INFO +1 -1
  12. {hexss-0.2.1 → hexss-0.3.0}/hexss.egg-info/SOURCES.txt +7 -1
  13. {hexss-0.2.1 → hexss-0.3.0}/setup.py +2 -1
  14. hexss-0.2.1/hexss/example/__init__.py +0 -0
  15. hexss-0.2.1/hexss/example/camera_server.py +0 -6
  16. hexss-0.2.1/hexss/server/__init__.py +0 -1
  17. {hexss-0.2.1 → hexss-0.3.0}/LICENSE +0 -0
  18. {hexss-0.2.1 → hexss-0.3.0}/hexss/__init__.py +0 -0
  19. {hexss-0.2.1 → hexss-0.3.0}/hexss/constants/cml.py +0 -0
  20. {hexss-0.2.1/hexss/constants → hexss-0.3.0/hexss/example}/__init__.py +0 -0
  21. {hexss-0.2.1 → hexss-0.3.0}/hexss/example/example.py +0 -0
  22. {hexss-0.2.1 → hexss-0.3.0}/hexss/json/__init__.py +0 -0
  23. {hexss-0.2.1 → hexss-0.3.0}/hexss/json/json_utils.py +0 -0
  24. /hexss-0.2.1/hexss/multiprocessing/__init__.py → /hexss-0.3.0/hexss/multiprocessing/func.py +0 -0
  25. {hexss-0.2.1 → hexss-0.3.0}/hexss.egg-info/dependency_links.txt +0 -0
  26. {hexss-0.2.1 → hexss-0.3.0}/hexss.egg-info/top_level.txt +0 -0
  27. {hexss-0.2.1 → hexss-0.3.0}/setup.cfg +0 -0
@@ -1,4 +1,4 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: hexss
3
- Version: 0.2.1
3
+ Version: 0.3.0
4
4
  License-File: LICENSE
@@ -0,0 +1 @@
1
+ from .cml import *
@@ -0,0 +1,4 @@
1
+ from hexss.server import camera_server
2
+
3
+ if __name__ == '__main__':
4
+ camera_server.run()
@@ -0,0 +1,33 @@
1
+ import time
2
+ from hexss.constants import RED, BLUE, ENDC
3
+ from hexss.multiprocessing import Multicore
4
+
5
+
6
+ def func1(data):
7
+ while True:
8
+ data['func1'] = data.get('func1', 0) + 1
9
+ data['list'].append(data['func1'])
10
+ if len(data['list']) > 20:
11
+ data['list'] = data['list'][:20]
12
+ print(f'{RED}{data["func1"]} {data['list']}{ENDC}')
13
+ time.sleep(1)
14
+
15
+
16
+ def func2(data):
17
+ while True:
18
+ data['func2'] = data.get('func2', 0) + 1
19
+ print(f'{BLUE}{data["func2"]}{ENDC}')
20
+ time.sleep(2)
21
+
22
+
23
+ if __name__ == '__main__':
24
+ m = Multicore()
25
+ m.set_data({
26
+ 'func1': -50,
27
+ 'func2': -50,
28
+ 'list': []
29
+ })
30
+ m.add_func(func1)
31
+ m.add_func(func2)
32
+ m.start()
33
+ m.join()
@@ -0,0 +1,56 @@
1
+ import cv2
2
+ from hexss.multiprocessing import Multicore
3
+
4
+
5
+ def capture_video(data):
6
+ cap = cv2.VideoCapture(0)
7
+ if not cap.isOpened():
8
+ print("Error: Could not open camera.")
9
+ data['play'] = False
10
+ return
11
+
12
+ while data['play']:
13
+ ret, frame = cap.read()
14
+ if not ret:
15
+ print("Error: Failed to capture frame.")
16
+ data['play'] = False
17
+ data['frame'] = frame.copy()
18
+ cap.release()
19
+
20
+
21
+ def process_video(data):
22
+ while data['play']:
23
+ if 'frame' in data and data['frame'] is not None:
24
+ cv2.imshow('frame', data['frame'])
25
+ if cv2.waitKey(1) & 0xFF == ord('q'):
26
+ data['play'] = False
27
+ cv2.destroyAllWindows()
28
+
29
+
30
+ # def capture_video(data):
31
+ # cap = cv2.VideoCapture(0)
32
+ # while data['play']:
33
+ # ret, frame = cap.read()
34
+ # data['frame'] = frame.copy()
35
+ #
36
+ #
37
+ # def process_video(data):
38
+ # while data['play']:
39
+ # if data['frame'] is not None:
40
+ # cv2.imshow('frame', data['frame'])
41
+ #
42
+ # if cv2.waitKey(1) & 0xFF == ord('q'):
43
+ # data['play'] = False
44
+ #
45
+ # cv2.destroyAllWindows()
46
+
47
+ if __name__ == '__main__':
48
+ m = Multicore()
49
+ m.set_data({
50
+ 'play': True,
51
+ 'frame': None,
52
+ })
53
+ m.add_func(capture_video)
54
+ m.add_func(process_video)
55
+ m.start()
56
+ m.join()
@@ -0,0 +1,2 @@
1
+ from .multicore import Multicore
2
+ from .func import dict_to_manager_dict, list_to_manager_list
@@ -0,0 +1,23 @@
1
+ from multiprocessing import Process, Manager
2
+ from hexss.multiprocessing.func import dict_to_manager_dict
3
+
4
+
5
+ class Multicore:
6
+ def __init__(self):
7
+ self.processes = []
8
+ self.manager = Manager()
9
+ self.data = self.manager.dict()
10
+
11
+ def set_data(self, data: dict):
12
+ self.data = dict_to_manager_dict(self.manager, data)
13
+
14
+ def add_func(self, func):
15
+ self.processes.append(Process(target=func, args=(self.data,)))
16
+
17
+ def start(self):
18
+ for process in self.processes:
19
+ process.start()
20
+
21
+ def join(self):
22
+ for process in self.processes:
23
+ process.join()
@@ -0,0 +1 @@
1
+
@@ -0,0 +1,218 @@
1
+ import multiprocessing
2
+ import time
3
+ from typing import Dict, Any, List
4
+ import numpy as np
5
+ from flask import Flask, render_template, Response, request, redirect, url_for
6
+ import socket
7
+ import cv2
8
+ from datetime import datetime
9
+ from hexss import json_load, json_update, dict_to_manager_dict
10
+ import platform
11
+ import logging
12
+ import signal
13
+ import sys
14
+
15
+ if platform.system() == "Windows":
16
+ import mss
17
+ else:
18
+ mss = None
19
+
20
+ app = Flask(__name__)
21
+ logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
22
+
23
+
24
+ def display_capture(data: Dict[str, Any]) -> None:
25
+ if platform.system() != "Windows":
26
+ logging.warning("Display capture is only supported on Windows.")
27
+ return
28
+
29
+ with mss.mss() as sct:
30
+ while True:
31
+ try:
32
+ screenshot = sct.grab(sct.monitors[0])
33
+ image = np.array(screenshot)
34
+ data['display_capture'] = image
35
+ except Exception as e:
36
+ logging.error(f"Error in display capture: {e}")
37
+ time.sleep(1)
38
+
39
+
40
+ def video_capture(data: Dict[str, Any], camera_id: int) -> None:
41
+ def setup() -> cv2.VideoCapture:
42
+ cap = cv2.VideoCapture(camera_id)
43
+ cap.set(3, data['camera'][camera_id]['width_height'][0])
44
+ cap.set(4, data['camera'][camera_id]['width_height'][1])
45
+ data['camera'][camera_id]['width_height_from_cap'] = [int(cap.get(3)), int(cap.get(4))]
46
+ return cap
47
+
48
+ cap = setup()
49
+ while True:
50
+ try:
51
+ if data['camera'][camera_id]['setup']:
52
+ data['camera'][camera_id]['setup'] = False
53
+ cap.release()
54
+ cap = setup()
55
+
56
+ if data['camera'][camera_id]['camera_enabled']:
57
+ status, img = cap.read()
58
+ data['camera'][camera_id]['status'] = status
59
+ if status:
60
+ data['camera'][camera_id]['img'] = img.copy()
61
+ else:
62
+ logging.warning(f"Failed to capture image from camera {camera_id}")
63
+ time.sleep(1)
64
+ cap.release()
65
+ cap = setup()
66
+ else:
67
+ data['camera'][camera_id]['status'] = False
68
+ data['camera'][camera_id]['img'] = np.full((480, 640, 3), (50, 50, 50), dtype=np.uint8)
69
+ except Exception as e:
70
+ logging.error(f"Error in video capture for camera {camera_id}: {e}")
71
+ time.sleep(1)
72
+
73
+
74
+ def get_data(data: Dict[str, Any], source: str, camera_id: int, quality=100) -> np.ndarray:
75
+ if source == 'video_capture':
76
+ frame = data['camera'][camera_id]['img']
77
+ status = data['camera'][camera_id]['status']
78
+ if not status:
79
+ frame = np.full((480, 640, 3), (50, 50, 50), dtype=np.uint8)
80
+ cv2.putText(frame, f'Failed to capture image', (30, 50), 1, 2, (0, 0, 255), 2)
81
+ cv2.putText(frame, f'from camera {camera_id}', (30, 90), 1, 2, (0, 0, 255), 2)
82
+ cv2.putText(frame, datetime.now().strftime('%Y-%m-%d %H:%M:%S'), (30, 130), 1, 2, (0, 0, 255), 2)
83
+ else: # source == 'display_capture':
84
+ frame = data['display_capture']
85
+ if quality == 100:
86
+ ret, buffer = cv2.imencode('.jpg', frame)
87
+ else:
88
+ encode_param = [cv2.IMWRITE_JPEG_QUALITY, quality] # Adjust quality (0-100)
89
+ ret, buffer = cv2.imencode('.jpg', frame, encode_param)
90
+ return buffer
91
+
92
+
93
+ @app.route('/')
94
+ def index():
95
+ data = app.config['data']
96
+ camera_states = [
97
+ {
98
+ 'camera_enabled': data['camera'][camera_id]['camera_enabled'],
99
+ 'width': data['camera'][camera_id]['width_height_from_cap'][0],
100
+ 'height': data['camera'][camera_id]['width_height_from_cap'][1]
101
+ } for camera_id in range(len(data['camera']))
102
+ ]
103
+ return render_template('simulate_CCTV.html', camera_states=camera_states)
104
+
105
+
106
+ @app.route('/update_cameras', methods=['POST'])
107
+ def update_cameras():
108
+ data = app.config['data']
109
+ for camera_id in range(len(data['camera'])):
110
+ camera_key = f'camera_{camera_id}'
111
+ data['camera'][camera_id]['camera_enabled'] = camera_key in request.form
112
+ width = request.form.get(f'w{camera_key}')
113
+ height = request.form.get(f'h{camera_key}')
114
+ if width and height:
115
+ data['camera'][camera_id]['width_height'] = [int(width), int(height)]
116
+ data['camera'][camera_id]['width_height_from_cap'] = [None, None]
117
+ data['camera'][camera_id]['setup'] = True
118
+
119
+ # update config file
120
+ config = json_load('camera_server_config.json')
121
+ config['camera'][camera_id]['width_height'] = [int(width), int(height)]
122
+ json_update('camera_server_config.json', config)
123
+
124
+ return redirect(url_for('index'))
125
+
126
+
127
+ @app.route('/image')
128
+ def get_image():
129
+ source = request.args.get('source', default='display_capture', type=str) # display_capture, video_capture,
130
+ camera_id = request.args.get('id', default=0, type=int) # 1, 2, ...
131
+ quality = request.args.get('quality', default=100, type=int)
132
+ buffer = get_data(app.config['data'], source, camera_id, quality)
133
+ return Response(buffer.tobytes(), mimetype='image/jpeg')
134
+
135
+
136
+ @app.route('/video')
137
+ def get_video():
138
+ source = request.args.get('source', default='display_capture', type=str)
139
+ camera_id = request.args.get('id', default=0, type=int)
140
+ quality = request.args.get('quality', default=30, type=int)
141
+
142
+ def generate():
143
+ while True:
144
+ buffer = get_data(app.config['data'], source, camera_id, quality)
145
+ frame = buffer.tobytes()
146
+ yield (b'--frame\r\n'
147
+ b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')
148
+
149
+ return Response(generate(), mimetype='multipart/x-mixed-replace; boundary=frame')
150
+
151
+
152
+ def run_server(data: Dict[str, Any]) -> None:
153
+ log = logging.getLogger('werkzeug')
154
+ log.disabled = True
155
+ app.config['data'] = data
156
+ ipv4 = data['ipv4']
157
+ port = data['port']
158
+ logging.info(f"Running on http://{ipv4}:{port}")
159
+ app.run(host=ipv4, port=port, debug=False, use_reloader=False)
160
+
161
+
162
+ def signal_handler(signum, frame):
163
+ logging.info("Received signal to terminate. Shutting down...")
164
+ sys.exit(0)
165
+
166
+
167
+ def run():
168
+ multiprocessing.freeze_support()
169
+ manager = multiprocessing.Manager()
170
+ config = json_load('camera_server_config.json', {
171
+ "ipv4": "auto",
172
+ "port": 2000,
173
+ "camera": [
174
+ {
175
+ "width_height": [640, 480]
176
+ }
177
+ ]
178
+ })
179
+ json_update('camera_server_config.json', config)
180
+ data = dict_to_manager_dict(manager, config)
181
+ if data['ipv4'] == 'auto':
182
+ hostname = socket.gethostname()
183
+ data['ipv4'] = socket.gethostbyname(hostname)
184
+
185
+ for camera_id in range(len(data['camera'])):
186
+ data['camera'][camera_id]['status'] = False
187
+ data['camera'][camera_id]['img'] = np.full((480, 640, 3), (50, 50, 50), dtype=np.uint8)
188
+ data['camera'][camera_id]['camera_enabled'] = True # Default to enabled
189
+ data['camera'][camera_id]['width_height_from_cap'] = [None, None]
190
+ data['camera'][camera_id]['setup'] = False
191
+ data['display_capture'] = np.full((480, 640, 3), (50, 50, 50), dtype=np.uint8)
192
+
193
+ processes: List[multiprocessing.Process] = [
194
+ multiprocessing.Process(target=video_capture, args=(data, camera_id))
195
+ for camera_id in range(len(data['camera']))
196
+ ]
197
+ processes.append(multiprocessing.Process(target=display_capture, args=(data,)))
198
+ processes.append(multiprocessing.Process(target=run_server, args=(data,)))
199
+
200
+ signal.signal(signal.SIGINT, signal_handler)
201
+ signal.signal(signal.SIGTERM, signal_handler)
202
+
203
+ for process in processes:
204
+ process.start()
205
+
206
+ try:
207
+ for process in processes:
208
+ process.join()
209
+ except KeyboardInterrupt:
210
+ logging.info("Keyboard interrupt received. Terminating processes...")
211
+ finally:
212
+ for process in processes:
213
+ process.terminate()
214
+ process.join()
215
+
216
+
217
+ if __name__ == "__main__":
218
+ run()
@@ -0,0 +1,128 @@
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <title>Video Streaming</title>
7
+ <style>
8
+ body {
9
+ font-family: Arial, sans-serif;
10
+ line-height: 1.6;
11
+ padding: 20px;
12
+ }
13
+
14
+ table {
15
+ width: 100%;
16
+ border-collapse: collapse;
17
+ margin-bottom: 20px;
18
+ }
19
+
20
+ th, td {
21
+ border: 1px solid #ddd;
22
+ padding: 15px;
23
+ text-align: left;
24
+ }
25
+
26
+ h1 {
27
+ color: #333;
28
+ margin-top: 50px;
29
+ margin-bottom: 10px;
30
+ }
31
+
32
+ .camera-control {
33
+ margin-bottom: 15px;
34
+ }
35
+
36
+ input[type="checkbox"] {
37
+ margin-right: 10px;
38
+ }
39
+
40
+ input[type="number"] {
41
+ width: 60px;
42
+ }
43
+
44
+ button {
45
+ padding: 10px 15px;
46
+ background-color: #4CAF50;
47
+ color: white;
48
+ border: none;
49
+ cursor: pointer;
50
+ }
51
+
52
+ button:hover {
53
+ background-color: #45a049;
54
+ }
55
+ </style>
56
+ </head>
57
+ <body>
58
+ <h1>Camera Result</h1>
59
+ <table>
60
+ <tr>
61
+ <th>Link</th>
62
+ <th>Video</th>
63
+ </tr>
64
+ <tr>
65
+ <td>
66
+ for image: <a href="/image?source=display_capture">/image?source=display_capture</a><br>
67
+ for video: <a href="/video?source=display_capture">/video?source=display_capture</a>
68
+ </td>
69
+ <td><img src="{{ url_for('get_video') }}" width="300" alt="Display Capture"></td>
70
+ </tr>
71
+ {% for i in range(camera_states|length) %}
72
+ <tr>
73
+ <td>
74
+ for image: <a href="/image?source=video_capture&id={{ i }}">/image?source=video_capture&id={{ i }}</a><br>
75
+ for video: <a href="/video?source=video_capture&id={{ i }}">/video?source=video_capture&id={{ i }}</a>
76
+ </td>
77
+ <td><img src="{{ url_for('get_video') }}?source=video_capture&id={{ i }}" width="300" alt="Video Capture"></td>
78
+ </tr>
79
+ {% endfor %}
80
+ </table>
81
+ <h1>Camera Control</h1>
82
+ <form action="{{ url_for('update_cameras') }}" method="post">
83
+ {% for camera in camera_states %}
84
+ <div class="camera-control">
85
+ <label>
86
+ <input type="checkbox" name="camera_{{ loop.index0 }}" {% if camera.camera_enabled %}checked{% endif %}>
87
+ Camera {{ loop.index0 }}
88
+ </label>
89
+ <label>
90
+ Width:
91
+ <input type="number" name="wcamera_{{ loop.index0 }}" value="{{ camera.width }}">
92
+ </label>
93
+ <label>
94
+ Height:
95
+ <input type="number" name="hcamera_{{ loop.index0 }}" value="{{ camera.height }}">
96
+ </label>
97
+ </div>
98
+ {% endfor %}
99
+ <button type="submit">Update Cameras</button>
100
+ </form>
101
+ <h1>Note</h1>
102
+ /<a style="color: red">image</a>?source=<a style="color: blue">video_capture</a>&id=<a style="color: Orange">0</a>
103
+ &quality=<a style="color: fuchsia">30</a><br>
104
+ <table>
105
+ <tr>
106
+ <td><b>path</b></td>
107
+ <td><a style="color: red">image, video</a></td>
108
+ <td><b>default val</b></td>
109
+ </tr>
110
+ <tr>
111
+ <td><b>source</b></td>
112
+ <td style="color: blue">display_capture, video_capture</td>
113
+ <td>display_capture</td>
114
+ </tr>
115
+ <tr>
116
+ <td><b>id (camera id)</b></td>
117
+ <td style="color: Orange">0, 1, ...</td>
118
+ <td>0</td>
119
+ </tr>
120
+ <tr>
121
+ <td><b>quality</b></td>
122
+ <td style="color: fuchsia">0-100</td>
123
+ <td>100 for image <br>and 30 for video</td>
124
+ </tr>
125
+ </table>
126
+
127
+ </body>
128
+ </html>
@@ -1,4 +1,4 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: hexss
3
- Version: 0.2.1
3
+ Version: 0.3.0
4
4
  License-File: LICENSE
@@ -10,7 +10,13 @@ hexss/constants/cml.py
10
10
  hexss/example/__init__.py
11
11
  hexss/example/camera_server.py
12
12
  hexss/example/example.py
13
+ hexss/example/multicore.py
14
+ hexss/example/multicore2.py
13
15
  hexss/json/__init__.py
14
16
  hexss/json/json_utils.py
15
17
  hexss/multiprocessing/__init__.py
16
- hexss/server/__init__.py
18
+ hexss/multiprocessing/func.py
19
+ hexss/multiprocessing/multicore.py
20
+ hexss/server/__init__.py
21
+ hexss/server/camera_server.py
22
+ hexss/server/templates/simulate_CCTV.html
@@ -2,7 +2,8 @@ from setuptools import setup, find_packages
2
2
 
3
3
  setup(
4
4
  name='hexss',
5
- version='0.2.1',
5
+ version='0.3.0',
6
6
  packages=find_packages(),
7
+ include_package_data=True,
7
8
  install_requires=[],
8
9
  )
File without changes
@@ -1,6 +0,0 @@
1
- from multiprocessing import freeze_support
2
- from hexss.server import start_camera_server
3
-
4
- if __name__ == '__main__':
5
- freeze_support()
6
- start_camera_server()
@@ -1 +0,0 @@
1
- from .Simulate_CCTV.camera_server import start_camera_server
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes