hexss 0.2.0__tar.gz → 0.2.2__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.
@@ -1,4 +1,4 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: hexss
3
- Version: 0.2.0
3
+ Version: 0.2.2
4
4
  License-File: LICENSE
@@ -0,0 +1,4 @@
1
+ from hexss.server import camera_server
2
+
3
+ if __name__ == '__main__':
4
+ camera_server.run()
@@ -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.0
3
+ Version: 0.2.2
4
4
  License-File: LICENSE
@@ -13,4 +13,6 @@ hexss/example/example.py
13
13
  hexss/json/__init__.py
14
14
  hexss/json/json_utils.py
15
15
  hexss/multiprocessing/__init__.py
16
- hexss/server/__init__.py
16
+ hexss/server/__init__.py
17
+ hexss/server/camera_server.py
18
+ 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.0',
5
+ version='0.2.2',
6
6
  packages=find_packages(),
7
+ include_package_data=True,
7
8
  install_requires=[],
8
9
  )
@@ -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.main 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
File without changes
File without changes