forked from BeeAlarmed/BeeAlarmed
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.py
238 lines (191 loc) · 7.16 KB
/
server.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
#!/usr/bin/env python3
import json
import multiprocessing
from ImageProvider import ImageProvider
from ImageConsumer import ImageConsumer
from ImageExtractor import ImageExtractor
from LoRaWANThread import LoRaWANThread
from Visual import Visual
from Utils import get_args, get_config
import logging
import time
import sys
from Statistics import getStatistics
from multiprocessing import Process, Value, Array
import queue
import os
import cgi
import time
from http.server import ThreadingHTTPServer, BaseHTTPRequestHandler
# Only load neural network if needed. the overhead is quite large
if get_config("NN_ENABLE"):
from BeeClassification import BeeClassification
logging.basicConfig(level=logging.DEBUG, format='%(process)d %(asctime)s - %(name)s - %(levelname)s - \t%(message)s')
logger = logging.getLogger(__name__)
def main(video)->str:
context = {
'stats': getStatistics()
}
imgProvider = ImageProvider(context, video_file=video)
while(not (imgProvider.isStarted() or imgProvider.isDone())):
time.sleep(1)
if imgProvider.isDone():
logger.error("Aborted, ImageProvider did not start. Please see log for errors!")
return ""
# Enable bee classification process only when its enabled
imgClassifier = None
if get_config("NN_ENABLE"):
imgClassifier = BeeClassification()
# Create processes and connect message queues between them
lorawan = None
if get_config("RN2483A_LORA_ENABLE"):
lorawan = LoRaWANThread()
imgExtractor = ImageExtractor()
imgConsumer = ImageConsumer(context)
visualiser = Visual()
stats = Array('c', 1000)
imgConsumer.setStatsQueue(stats)
imgConsumer.setContext(context)
imgConsumer.setImageQueue(imgProvider.getQueue())
imgConsumer.setVisualQueue(visualiser.getInQueue())
if get_config("NN_ENABLE"):
imgExtractor.setResultQueue(imgClassifier.getQueue())
imgConsumer.setClassifierResultQueue(imgClassifier.getResultQueue())
imgExtractor.setInQueue(imgConsumer.getPositionQueue())
# Start the processes
imgConsumer.start()
imgExtractor.start()
visualiser.start()
if lorawan is not None:
lorawan.start()
# Quit program if end of video-file is reached or
# the camera got disconnected
#imgConsumer.join()
while True:
time.sleep(0.01)
if imgConsumer.isDone() or imgProvider.isDone():
break
# Tear down all running process to ensure that we don't get any zombies
if lorawan is not None:
lorawan.stop()
imgProvider.stop()
imgExtractor.stop()
visualiser.stop()
imgConsumer.stop()
imgConsumer.join()
res = stats.value.decode('utf-8')
print(res)
if imgClassifier:
imgClassifier.stop()
imgClassifier.join()
imgExtractor.join()
imgProvider.join()
visualiser.join()
return res
UPLOAD_DIR = '/app/tmp'
class UploadHandler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200) # Send 200 OK status code
self.send_header('Content-type', 'text/html')
self.end_headers()
# Send the HTML form as the response body
form_html = '''
<html>
<body>
<form method="POST" enctype="multipart/form-data">
<input type="file" name="file" />
<input type="submit" value="Upload" />
</form>
</body>
</html>
'''
self.wfile.write(form_html.encode('utf-8'))
def do_POST(self):
# Add CORS headers to allow requests from any domain
self.send_response(200)
self.send_header('Access-Control-Allow-Origin', '*')
self.send_header('Access-Control-Allow-Methods', 'POST')
self.send_header('Access-Control-Allow-Headers', 'Content-Type')
self.end_headers()
content_type = self.headers.get('Content-Type')
print(content_type)
if content_type == 'application/json':
self.process_video_from_json_with_filepath()
else:
if content_type == 'multipart/form-data':
self.process_video_from_payload()
def process_video_from_json_with_filepath(self):
# Read JSON payload from request body
content_length = int(self.headers['Content-Length'])
post_data = self.rfile.read(content_length)
try:
# Parse JSON payload
payload = json.loads(post_data)
filename = payload.get('filename')
# print the filename
print(filename)
if not filename:
self.wfile.write(b'No filename provided in JSON payload')
return
# Construct the path to the file in /tmp
filepath = os.path.join(UPLOAD_DIR, filename)
# Check if the file exists
if not os.path.exists(filepath):
self.wfile.write(b'File not found in ' + filepath.encode('utf-8'))
return
# check if file is readable
if not os.access(filepath, os.R_OK):
self.wfile.write(b'File is not readable')
return
# Inference the video file
result = main(filepath)
self.wfile.write(result.encode('utf-8'))
# try:
# os.remove(filepath)
#print(f"File '{filepath}' deleted successfully.")
# except FileNotFoundError:
# print(f"File '{filepath}' not found.")
# except Exception as e:
# print(f"An error occurred: {e}")
except json.JSONDecodeError:
self.wfile.write(b'Invalid JSON payload')
return
except Exception as e:
self.wfile.write(f'An error occurred: {str(e)}'.encode('utf-8'))
return
def process_video_from_payload(self):
# Parse the form data
form = cgi.FieldStorage(
fp=self.rfile,
headers=self.headers,
environ={'REQUEST_METHOD': 'POST'}
)
# Check if the 'video' field exists
if 'file' not in form:
self.wfile.write(b'No video file uploaded')
return
# Get the video file data
video_file = form['file']
_, file_extension = os.path.splitext(video_file.filename)
timestamp = str(int(time.time())) # Generate a timestamp
filename = timestamp + file_extension
# Save the file to the uploads directory
filepath = os.path.join(UPLOAD_DIR, filename)
with open(filepath, 'wb') as file:
file.write(video_file.file.read())
# Inference the video file
result = main(filepath)
self.wfile.write(result.encode('utf-8'))
try:
os.remove(filepath)
print(f"File '{filepath}' deleted successfully.")
except FileNotFoundError:
print(f"File '{filepath}' not found.")
except Exception as e:
print(f"An error occurred: {e}")
if __name__ == '__main__':
os.makedirs(UPLOAD_DIR, exist_ok=True)
server_address = ('', 9100)
httpd = ThreadingHTTPServer(server_address, UploadHandler)
print('Server is listening on port 9100')
httpd.serve_forever()