-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.py
177 lines (121 loc) · 5.53 KB
/
app.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
import datetime
import cv2
import threading
from datetime import datetime
from flask import Flask, render_template, Response
from ultralytics import YOLO
import os
import time
import requests
import json
app = Flask(__name__)
# make a folder named snapshot to save the snap while the accident is detected
snapshot_dir = "public/snapshots"
os.makedirs(snapshot_dir, exist_ok=True)
frame_count = 0 # Initialize frame_count outside of any function
model = YOLO("acc_best.pt")
frame_skip = 5
classnames = ["moderate-accident", "fatal-accident", "Normal"]
#this function sends http post request to the server
def send_accident_data_to_server(accident_data, headers=None):
# Define the API endpoint
api_endpoint = "http://localhost:3000/api/accidents"
#Convert the data to JSON
json_payload = json.dumps(accident_data)
# Send the POST request to the server with the JSON payload
headers = {'Content-Type': 'application/json'}
response = requests.post(api_endpoint, data=json_payload, headers=headers)
# Check the server's response
if response.status_code == 201:
print("Data sent successfully!")
return True
else:
print("Data upload failed.")
return False
#post request
def annotate_frame(frame, custom_text):
now = datetime.now()
current_time = now.strftime("%Y-%m-%d %H:%M:%S")
font = cv2.FONT_HERSHEY_SIMPLEX
cv2.putText(frame, current_time, (10, 30), font, 1, (0, 0, 255), 2, cv2.LINE_AA)
cv2.putText(frame, custom_text, (10, 60), font, 1, (0, 255, 0), 2, cv2.LINE_AA)
results = model.predict(frame)
# Track whether a snapshot has been taken
snapshot_taken = False
annotated_frame = results[0].plot()
return annotated_frame
def generate_frames(video_path, custom_text):
global frame_count
cap = cv2.VideoCapture(video_path)
frame_count = 0
snapshot_taken = False
while True:
success, frame = cap.read()
if not success:
break
frame_count += 1
if frame_count % frame_skip == 0:
# Detect "moderate-accident" and take a snapshot if not already taken
results = model.predict(frame)
for r in results:
for c in r.boxes.cls:
class_name = model.names[int(c)]
if ("moderate-accident" in class_name or "fatal-accident" in class_name) and not snapshot_taken:
print("Accident Detected:", class_name)
# generating the unique id
current_time = datetime.now()
timestamp_with_microseconds = current_time.timestamp()
microseconds = int((timestamp_with_microseconds % 1) * 1e6)
unique_number = int(timestamp_with_microseconds * 1e6) + microseconds
#snap shot is taken here
snapshot_filename = os.path.join(snapshot_dir, f"snapshot_{unique_number}.jpg")
cv2.imwrite(snapshot_filename, frame)
snapshot_taken = True
# if port 49 is not working then the new IP address will be
# ipaddress=f"HTTP://127.0.0.1:5000/{custom_text}"
# and comment this line
ipaddress=f"http://127.0.0.1:49/{custom_text}"
accident_data={
"photos":f"snapshots/snapshot_{unique_number}.jpg",
"ipAddress":ipaddress
}
print(accident_data)
#send http post request to the server
send_accident_data_to_server(accident_data)
break # Exit the loop once the snapshot is taken
annotated_frame = annotate_frame(frame, custom_text)
_, buffer = cv2.imencode('.jpg', annotated_frame)
frame_bytes = buffer.tobytes()
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + frame_bytes + b'\r\n')
cap.release()
# @app.route('/video')
# def video():
# video_path = "test1.mp4"
# custom_text = "pulchowk"
# return Response(generate_frames(video_path, custom_text), mimetype='multipart/x-mixed-replace; boundary=frame')
# while running the file go to the index.html page and render the templates
@app.route('/')
def index():
return render_template('index.html')
# hosting the video in the different path and passsing the video link to the path.
@app.route('/maitighar')
def video1():
video_path = "maitighar.mp4"
custom_text = "maitighar"
return Response(generate_frames(video_path, custom_text), mimetype='multipart/x-mixed-replace; boundary=frame')
@app.route('/koteshore')
def video2():
video_path = "koteshore.mp4"
custom_text = "koteshore"
return Response(generate_frames(video_path, custom_text), mimetype='multipart/x-mixed-replace; boundary=frame')
@app.route('/test')
def video3():
video_path = "test1.mp4"
custom_text = "test"
return Response(generate_frames(video_path, custom_text), mimetype='multipart/x-mixed-replace; boundary=frame')
# hosting the entire file in the port 49
# if the port 49 is not working then remove port=49 and update the ipaddress from above
if __name__ == '__main__':
app.run(port=49, debug=False)
# app.run(debug=False)