-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.py
More file actions
389 lines (323 loc) · 12.4 KB
/
main.py
File metadata and controls
389 lines (323 loc) · 12.4 KB
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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
from flask import Flask, request, jsonify, send_from_directory
from flask_cors import CORS
import cv2
import numpy as np
from datetime import datetime, timedelta
import os
import tempfile
from collections import deque
import random
app = Flask(__name__, static_folder='frontend', static_url_path='')
CORS(app, resources={r"/*": {"origins": "*"}})
# Configuration
UPLOAD_FOLDER = 'uploads'
if not os.path.exists(UPLOAD_FOLDER):
os.makedirs(UPLOAD_FOLDER)
app.config['MAX_CONTENT_LENGTH'] = 100 * 1024 * 1024 # 100MB limit
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
# Rolling average buffers
temp_history = deque(maxlen=10)
ph_history = deque(maxlen=10)
flow_history = deque(maxlen=10)
def determine_emotion(temp, ph, flow):
if temp > 35 and flow > 80:
return "angry"
elif ph < 5 or ph > 9:
return "sad"
elif flow > 90 and 25 <= temp <= 40:
return "excited"
elif temp < 10 and flow < 30:
return "calm"
elif 20 <= temp <= 30 and 6.5 <= ph <= 8.5 and 40 <= flow <= 60:
return "happy"
else:
return "neutral"
def calc_flow(prev_gray, gray):
# Calculate optical flow using Farneback method
flow = cv2.calcOpticalFlowFarneback(prev_gray, gray,
None, 0.5, 3, 15, 3, 5, 1.2, 0)
# Calculate magnitude and angle of 2D vectors
magnitude, angle = cv2.cartToPolar(flow[..., 0], flow[..., 1])
# Apply thresholding to remove noise
threshold = np.mean(magnitude) * 0.5
magnitude[magnitude < threshold] = 0
# Calculate flow metrics
flow_mean = np.mean(magnitude)
flow_std = np.std(magnitude)
# Scale the flow value to a more meaningful range (0-100)
scaled_flow = (flow_mean * flow_std) * 5
# Ensure the value is within reasonable bounds
scaled_flow = np.clip(scaled_flow, 0, 100)
return scaled_flow
def analyze_frame(prev_gray, frame):
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
# Flow estimation
flow_speed = calc_flow(prev_gray, gray) * 100
# Brightness for temperature
brightness = np.mean(hsv[:, :, 2])
temperature = (brightness / 255) * 50
# Clarity for pH
edges = cv2.Canny(frame, 100, 200)
edge_density = np.mean(edges)
color_std = np.std(hsv[:, :, 1])
ph_level = 7 - (edge_density / 255) * 3 + (color_std / 255) * 3
ph_level = np.clip(ph_level, 0, 14)
# Smooth values
temp_history.append(temperature)
ph_history.append(ph_level)
flow_history.append(flow_speed)
temp_avg = np.mean(temp_history)
ph_avg = np.mean(ph_history)
flow_avg = np.mean(flow_history)
emotion = determine_emotion(temp_avg, ph_avg, flow_avg)
return temp_avg, ph_avg, flow_avg, emotion, gray
@app.route('/')
def serve_index():
return send_from_directory(app.static_folder, 'index.html')
@app.route('/climate')
def serve_climate():
return send_from_directory(app.static_folder, 'climate.html')
@app.route('/frontend/<path:path>')
def serve_static(path):
return send_from_directory('frontend', path)
@app.route('/api/drowning', methods=['POST'])
def detect_drowning():
try:
if 'video' not in request.files:
return jsonify({"error": "No video file provided"}), 400
video_file = request.files['video']
if video_file.filename == '':
return jsonify({"error": "No selected file"}), 400
if not video_file.filename.lower().endswith(('.mp4', '.avi', '.mov', '.mkv')):
return jsonify({"error": "Invalid file type. Please upload a video file (mp4, avi, mov, or mkv)"}), 400
# Save and process the video
filename = os.path.join(app.config['UPLOAD_FOLDER'],
f"video_{datetime.now().strftime('%Y%m%d_%H%M%S')}.mp4")
video_file.save(filename)
# Process the video
cap = cv2.VideoCapture(filename)
ret, first_frame = cap.read()
if not ret:
return jsonify({"error": "Failed to read video"}), 400
prev_gray = cv2.cvtColor(first_frame, cv2.COLOR_BGR2GRAY)
temp, ph, flow, emotion, _ = analyze_frame(prev_gray, first_frame)
# Clean up
cap.release()
os.remove(filename)
return jsonify({
"temperature": float(temp),
"ph": float(ph),
"flow": float(flow),
"emotion": emotion
})
except Exception as e:
print(f"Error processing video: {str(e)}")
return jsonify({"error": str(e)}), 500
@app.route('/api/flow', methods=['POST'])
def get_flow_rate():
try:
if 'frame' not in request.files:
return jsonify({"error": "No frame provided"}), 400
# Read the current frame
frame_file = request.files['frame']
frame_data = frame_file.read()
nparr = np.frombuffer(frame_data, np.uint8)
frame = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
if frame is None:
return jsonify({"error": "Invalid frame data"}), 400
# Convert frame to grayscale
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# Get the previous frame
prev_gray = None
if 'prev_gray' in request.files:
prev_frame_file = request.files['prev_gray']
prev_frame_data = prev_frame_file.read()
prev_nparr = np.frombuffer(prev_frame_data, np.uint8)
prev_frame = cv2.imdecode(prev_nparr, cv2.IMREAD_COLOR)
if prev_frame is not None:
prev_gray = cv2.cvtColor(prev_frame, cv2.COLOR_BGR2GRAY)
if prev_gray is None:
return jsonify({"flow": 0.0})
# Calculate flow rate
flow_speed = calc_flow(prev_gray, gray)
# Add to history and calculate moving average
flow_history.append(flow_speed)
flow_avg = np.mean(flow_history)
# Scale the flow rate to m³/s (approximate conversion)
scaled_flow = flow_avg * 0.1 # Scale factor to convert to m³/s
return jsonify({
"flow": float(scaled_flow)
})
except Exception as e:
print(f"Error processing frame: {str(e)}")
return jsonify({"error": str(e)}), 500
@app.route('/api/emotion', methods=['GET'])
def get_emotion():
try:
# Get the latest metrics
temperature = get_latest_metric('temperature')
ph = get_latest_metric('ph')
flow_rate = get_latest_metric('flow_rate')
dissolved_oxygen = get_latest_metric('dissolved_oxygen')
water_level = get_latest_metric('water_level')
clarity = get_latest_metric('clarity')
# Get historical data
temperature_history = get_metric_history('temperature', 24) # Last 24 hours
water_level_history = get_metric_history('water_level', 24)
flow_rate_history = get_metric_history('flow_rate', 24)
ecosystem_history = get_metric_history('ecosystem', 24)
# Calculate the river's emotion based on metrics
emotion = calculate_river_emotion(temperature, ph, flow_rate, dissolved_oxygen)
return jsonify({
'emotion': emotion,
'temperature': temperature,
'ph': ph,
'flow_rate': flow_rate,
'dissolved_oxygen': dissolved_oxygen,
'water_level': water_level,
'clarity': clarity,
'temperature_history': temperature_history,
'water_level_history': water_level_history,
'flow_rate_history': flow_rate_history,
'ecosystem_history': ecosystem_history
})
except Exception as e:
print(f"Error in get_emotion: {str(e)}")
return jsonify({'error': str(e)}), 500
@app.route('/api/alerts', methods=['GET'])
def get_alerts():
# Get latest metrics
temperature = get_latest_metric('temperature')['value']
ph = get_latest_metric('ph')['value']
flow_rate = get_latest_metric('flow_rate')['value']
dissolved_oxygen = get_latest_metric('dissolved_oxygen')['value']
alerts = []
timestamp = datetime.now().isoformat()
# Temperature alerts
if temperature > 28:
alerts.append({
'type': 'temperature',
'severity': 'high',
'message': 'High temperature detected - potential risk to aquatic life',
'value': temperature,
'timestamp': timestamp
})
elif temperature < 15:
alerts.append({
'type': 'temperature',
'severity': 'low',
'message': 'Low temperature detected - monitor for ecosystem stress',
'value': temperature,
'timestamp': timestamp
})
# pH alerts
if ph > 8.5:
alerts.append({
'type': 'ph',
'severity': 'high',
'message': 'High pH levels - potential alkalinity issues',
'value': ph,
'timestamp': timestamp
})
elif ph < 6.5:
alerts.append({
'type': 'ph',
'severity': 'low',
'message': 'Low pH levels - potential acidity issues',
'value': ph,
'timestamp': timestamp
})
# Flow rate alerts
if flow_rate > 150:
alerts.append({
'type': 'flow',
'severity': 'high',
'message': 'High flow rate - potential flood risk',
'value': flow_rate,
'timestamp': timestamp
})
elif flow_rate < 30:
alerts.append({
'type': 'flow',
'severity': 'low',
'message': 'Low flow rate - potential drought conditions',
'value': flow_rate,
'timestamp': timestamp
})
# Dissolved oxygen alerts
if dissolved_oxygen < 5:
alerts.append({
'type': 'oxygen',
'severity': 'low',
'message': 'Low oxygen levels - critical for aquatic life',
'value': dissolved_oxygen,
'timestamp': timestamp
})
# Add awareness tips
awareness_tips = [
'Regular monitoring helps maintain river health',
'Report any unusual changes in water color or smell',
'Keep the riverbanks clean and free of debris',
'Avoid disturbing natural habitats along the river',
'Be mindful of water usage during dry seasons'
]
return jsonify({
'alerts': alerts,
'awareness_tips': random.sample(awareness_tips, 2), # Return 2 random tips
'timestamp': timestamp
})
def get_latest_metric(metric_name):
# Simulated metrics for testing
metrics = {
'temperature': 24.7,
'ph': 7.5,
'flow_rate': 90.0,
'dissolved_oxygen': 8.9,
'water_level': 2.3,
'clarity': 85
}
return metrics.get(metric_name, 0)
def get_metric_history(metric_name, hours):
history = []
now = datetime.now()
# Generate sample historical data
base_values = {
'temperature': 24.7,
'water_level': 2.3,
'flow_rate': 90.0,
'ecosystem': 85
}
base_value = base_values.get(metric_name, 0)
for i in range(hours):
timestamp = now - timedelta(hours=i)
# Add some random variation to create realistic-looking data
value = base_value + (random.random() - 0.5) * 2
history.append({
'timestamp': timestamp.isoformat(),
'value': round(value, 2)
})
return history
def calculate_river_emotion(temperature, ph, flow_rate, dissolved_oxygen):
# Define optimal ranges
temp_optimal = (18, 25)
ph_optimal = (6.5, 8.5)
flow_optimal = (50, 150)
oxygen_optimal = (7, 12)
# Calculate stress levels
temp_stress = abs((temperature - sum(temp_optimal)/2) / (temp_optimal[1] - temp_optimal[0]))
ph_stress = abs((ph - sum(ph_optimal)/2) / (ph_optimal[1] - ph_optimal[0]))
flow_stress = abs((flow_rate - sum(flow_optimal)/2) / (flow_optimal[1] - flow_optimal[0]))
oxygen_stress = abs((dissolved_oxygen - sum(oxygen_optimal)/2) / (oxygen_optimal[1] - oxygen_optimal[0]))
total_stress = (temp_stress + ph_stress + flow_stress + oxygen_stress) / 4
# Determine emotion based on stress level
if total_stress < 0.2:
return 'happy'
elif total_stress < 0.4:
return 'neutral'
elif total_stress < 0.6:
return 'sad'
else:
return 'angry'
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0', port=8001)