shivanis14 commited on
Commit
89afe89
1 Parent(s): d4dce4f

Add application file

Browse files
Files changed (2) hide show
  1. app.py +129 -0
  2. orb_motion_detection.py +310 -0
app.py ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import io
3
+ import numpy as np
4
+ import torch
5
+ #from decord import cpu, VideoReader, bridge
6
+ from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
7
+ from orb_motion_detection import detect_fast_motion
8
+ import time, os
9
+
10
+ def process_video(video, start_time, end_time, quant=8):
11
+ start = time.time()
12
+
13
+ output_dir = "motion_detection_results"
14
+ os.system(f"rm -rf {output_dir}")
15
+ os.system(f"mkdir {output_dir}")
16
+
17
+ DEVICE = 'cuda' if torch.cuda.is_available() else 'cpu'
18
+ TORCH_TYPE = torch.bfloat16 if torch.cuda.is_available() and torch.cuda.get_device_capability()[0] >= 8 else torch.float16
19
+
20
+ MODEL_PATH = "THUDM/cogvlm2-video-llama3-base"
21
+
22
+ if 'int4' in MODEL_PATH:
23
+ quant = 4
24
+
25
+ strategy = 'base' if 'cogvlm2-video-llama3-base' in MODEL_PATH else 'chat'
26
+ print(f"Using {strategy} model")
27
+
28
+ timestamps, fast_frames = detect_fast_motion(video.name, output_dir, end_time, start_time, motion_threshold=1.5)
29
+
30
+ history = []
31
+ if len(fast_frames) > 0:
32
+ video_data = np.array(fast_frames[0:min(48, len(fast_frames))]) # Shape: (num_frames, height, width, channels)
33
+ video_data = np.transpose(video_data, (3, 0, 1, 2)) # RGB channels first
34
+ video_tensor = torch.tensor(video_data) # Convert to tensor
35
+
36
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_PATH, trust_remote_code=True)
37
+
38
+ if quant == 4:
39
+ model = AutoModelForCausalLM.from_pretrained(
40
+ MODEL_PATH,
41
+ torch_dtype=TORCH_TYPE,
42
+ trust_remote_code=True,
43
+ quantization_config=BitsAndBytesConfig(
44
+ load_in_4bit=True,
45
+ bnb_4bit_compute_dtype=TORCH_TYPE,
46
+ ),
47
+ low_cpu_mem_usage=True
48
+ ).eval()
49
+ elif quant == 8:
50
+ model = AutoModelForCausalLM.from_pretrained(
51
+ MODEL_PATH,
52
+ torch_dtype=TORCH_TYPE,
53
+ trust_remote_code=True,
54
+ quantization_config=BitsAndBytesConfig(
55
+ load_in_8bit=True,
56
+ bnb_4bit_compute_dtype=TORCH_TYPE,
57
+ ),
58
+ low_cpu_mem_usage=True
59
+ ).eval()
60
+ else:
61
+ model = AutoModelForCausalLM.from_pretrained(
62
+ MODEL_PATH,
63
+ torch_dtype=TORCH_TYPE,
64
+ trust_remote_code=True
65
+ ).eval().to(DEVICE)
66
+
67
+ query = "Describe the actions in the video frames focusing on physical abuse, violence, or someone falling down."
68
+ print(f"Query: {query}")
69
+
70
+ inputs = model.build_conversation_input_ids(
71
+ tokenizer=tokenizer,
72
+ query=query,
73
+ images=[video_tensor],
74
+ history=history,
75
+ template_version=strategy
76
+ )
77
+
78
+ inputs = {
79
+ 'input_ids': inputs['input_ids'].unsqueeze(0).to(DEVICE),
80
+ 'token_type_ids': inputs['token_type_ids'].unsqueeze(0).to(DEVICE),
81
+ 'attention_mask': inputs['attention_mask'].unsqueeze(0).to(DEVICE),
82
+ 'images': [[inputs['images'][0].to('cuda').to(TORCH_TYPE)]],
83
+ }
84
+
85
+ gen_kwargs = {
86
+ "max_new_tokens": 2048,
87
+ "pad_token_id": 128002,
88
+ "top_k": 1,
89
+ "do_sample": True,
90
+ "top_p": 0.1,
91
+ "temperature": 0.1,
92
+ }
93
+
94
+ with torch.no_grad():
95
+ outputs = model.generate(**inputs, **gen_kwargs)
96
+ outputs = outputs[:, inputs['input_ids'].shape[1]:]
97
+ response = tokenizer.decode(outputs[0], skip_special_tokens=True)
98
+ print("\nCogVLM2-Video:", response)
99
+ history.append((query, response))
100
+
101
+ result = f"Response: {response}"
102
+ else:
103
+ result = "No aggressive behaviour found. Nobody falling down."
104
+
105
+ end = time.time()
106
+ execution_time = f"Execution time for {video.name}: {end - start} seconds. Duration of the video was {end_time - start_time} seconds."
107
+
108
+ return result
109
+
110
+
111
+ # Create Gradio Interface
112
+ def gradio_interface():
113
+ video_input = gr.File(label="Upload video file (.mp4)", type="filepath")
114
+ start_time = gr.Number(value=0.0, label="Start time (seconds)")
115
+ end_time = gr.Number(value=15.0, label="End time (seconds)")
116
+
117
+ interface = gr.Interface(
118
+ fn=process_video,
119
+ inputs=[video_input, start_time, end_time],
120
+ outputs="text",
121
+ title="Senior Safety Monitoring System",
122
+ description="Upload a video and specify the time range for analysis. The model will detect fast motion and describe actions such as physical abuse or someone falling down."
123
+ )
124
+
125
+ interface.launch(share=True)
126
+
127
+
128
+ if __name__ == "__main__":
129
+ gradio_interface()
orb_motion_detection.py ADDED
@@ -0,0 +1,310 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2, os, time, math
2
+ import numpy as np
3
+ from skimage.metrics import structural_similarity as ssim
4
+ import matplotlib.pyplot as plt
5
+
6
+ def compute_optical_flow(prev_gray, curr_gray):
7
+ flow = cv2.calcOpticalFlowFarneback(prev_gray, curr_gray, None, 0.5, 3, 15, 3, 5, 1.2, 0)
8
+ magnitude, _ = cv2.cartToPolar(flow[..., 0], flow[..., 1])
9
+ #print(f"DEBUG : max and min values are {np.max(magnitude)} {np.min(magnitude)}")
10
+ return np.max(magnitude)
11
+
12
+ def compute_orb_distance(prev_frame, curr_frame, match_threshold = 40):
13
+ # Initialize ORB detector
14
+ orb = cv2.ORB_create()
15
+
16
+ # Find the keypoints and descriptors with ORB
17
+ kp1, des1 = orb.detectAndCompute(prev_frame, None)
18
+ kp2, des2 = orb.detectAndCompute(curr_frame, None)
19
+
20
+ # Create BFMatcher object
21
+ bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)
22
+
23
+ # Match descriptors
24
+ orig_matches = bf.match(des1, des2)
25
+
26
+ matches = [match for match in orig_matches if match.distance < match_threshold]
27
+
28
+ # Sort them in the order of their distance (descriptor similarity)
29
+ matches = sorted(matches, key=lambda x: x.distance)
30
+
31
+ # Calculate average descriptor distance of top 10% matches
32
+ num_matches = len(matches) # Use 10% of matches
33
+ if num_matches == 0:
34
+ return 0
35
+
36
+ max_descriptor_distance = max(match.distance for match in matches[:num_matches])
37
+
38
+ # Calculate Euclidean distances (physical movement) for top matches
39
+ euclidean_distances = []
40
+ for match in matches[:num_matches]:
41
+ # Get keypoint coordinates from both frames
42
+ pt1 = np.array(kp1[match.queryIdx].pt) # Coordinates in prev_frame
43
+ pt2 = np.array(kp2[match.trainIdx].pt) # Coordinates in curr_frame
44
+
45
+ # Compute Euclidean distance between matched keypoints
46
+ euclidean_distance = np.sqrt((pt1[0] - pt2[0])**2 + (pt1[1] - pt2[1])**2)
47
+ #print(f"DEBUG!! euclidean_distance is {euclidean_distance} between {pt1} and {pt2}")
48
+ euclidean_distances.append(euclidean_distance)
49
+
50
+ # Average Euclidean distance (keypoint movement)
51
+ max_movement_distance = np.max(euclidean_distances)
52
+
53
+ # Normalize max descriptor distance (for 256-bit ORB descriptors)
54
+ normalized_descriptor_distance = max_descriptor_distance / 256
55
+
56
+ # Return both descriptor similarity and keypoint movement
57
+ #print(f"DEBUG!! max_descriptor_distance : {max_descriptor_distance}")
58
+ return max_movement_distance
59
+
60
+
61
+ def compute_ssim(prev_frame, curr_frame):
62
+ return ssim(prev_frame, curr_frame, data_range=255)
63
+
64
+ def compute_pixel_diff(prev_frame, curr_frame):
65
+ diff = cv2.absdiff(prev_frame, curr_frame)
66
+ return np.mean(diff)
67
+
68
+ def preprocess_frame(frame, width=640, height=360):
69
+ target_size = (width, height)
70
+ resized_frame = cv2.resize(frame, target_size, interpolation=cv2.INTER_AREA) # Use INTER_AREA for shrinking
71
+ return resized_frame
72
+
73
+ def smooth_curve(data, window_size=5):
74
+ return np.convolve(data, np.ones(window_size)/window_size, mode='valid')
75
+
76
+ def find_timestamp_clusters(fast_motion_timestamps, min_time_gap=5):
77
+ clusters = [] # List to hold the clusters of timestamps
78
+ current_cluster = [] # Temporary list to hold the current cluster
79
+
80
+ for i, timestamp in enumerate(fast_motion_timestamps):
81
+ # If it's the first timestamp, start a new cluster
82
+ if i == 0:
83
+ current_cluster.append(timestamp)
84
+ else:
85
+ # Check the time difference between the current and previous timestamp
86
+ if timestamp - fast_motion_timestamps[i-1] <= min_time_gap:
87
+ # If the difference is less than or equal to the min_time_gap, add it to the current cluster
88
+ current_cluster.append(timestamp)
89
+ else:
90
+ # If the difference is greater than min_time_gap, finish the current cluster and start a new one
91
+ clusters.append(current_cluster)
92
+ current_cluster = [timestamp]
93
+
94
+ # Add the last cluster to the clusters list
95
+ if current_cluster:
96
+ clusters.append(current_cluster)
97
+
98
+ return clusters
99
+
100
+
101
+ def detect_fast_motion(video_path, output_dir, end_time, start_time, window_size=3, motion_threshold=0.6, step = 2):
102
+ cap = cv2.VideoCapture(video_path)
103
+ fps = cap.get(cv2.CAP_PROP_FPS)
104
+ height = cap.get(cv2.CAP_PROP_FRAME_HEIGHT)
105
+ width = cap.get(cv2.CAP_PROP_FRAME_WIDTH)
106
+
107
+ orb_scores = []
108
+ #optical_flow_scores = []
109
+ ssim_scores = []
110
+ #pixel_diff_scores = []
111
+ timestamps = []
112
+ frame_list = []
113
+
114
+ prev_frame = None
115
+ frame_count = 0
116
+
117
+ while cap.isOpened():
118
+ ret, orig_frame = cap.read()
119
+ if not ret:
120
+ break
121
+ #print(f"DEBUG!! frame : {frame_count} time : {frame_count/fps}")
122
+
123
+ if height == 360 and width == 640:
124
+ frame = orig_frame
125
+ else:
126
+ frame = preprocess_frame(orig_frame, width = 640, height = 360)
127
+
128
+
129
+ if frame_count > end_time * fps:
130
+ break
131
+
132
+ if frame_count < start_time * fps or frame_count % step != 0:
133
+ frame_count += 1
134
+ continue
135
+
136
+ gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
137
+
138
+ if prev_frame is not None:
139
+ #optical_flow_scores.append(compute_optical_flow(prev_frame, gray))
140
+ orb_scores.append(compute_orb_distance(prev_frame, gray))
141
+ ssim_scores.append(compute_ssim(prev_frame, gray))
142
+ #pixel_diff_scores.append(compute_pixel_diff(prev_frame, gray))
143
+ #print(f"DEBUG : time : {frame_count/fps} end_time : {end_time} start_time : {start_time}")
144
+ timestamps.append(frame_count/fps)
145
+ else:
146
+ #optical_flow_scores.append(0)
147
+ orb_scores.append(0)
148
+ ssim_scores.append(1)
149
+ timestamps.append(start_time)
150
+
151
+ frame_list.append(frame)
152
+ prev_frame = gray
153
+ frame_count += 1
154
+
155
+ #if frame_count % 100 == 0:
156
+ # print(f"Processed {frame_count} frames")
157
+
158
+ cap.release()
159
+
160
+ new_fps = len(timestamps)/ (max(timestamps) - min(timestamps))
161
+ print(f"fps : {fps} frame_height : {height} frame_width : {width} New fps is {new_fps}")
162
+ # Normalize scores by image diagonal * time between frame : https://chatgpt.com/share/66f684b9-dd4c-8010-bf9c-421c3c6ef84a
163
+
164
+ #optical_flow_scores = np.array(optical_flow_scores) / (np.sqrt(gray.shape[0]**2 + gray.shape[1]**2) / new_fps)
165
+ ssim_scores = (1 - np.array(ssim_scores)) * new_fps # Invert SSIM scores
166
+ orb_scores = (np.array(orb_scores) * new_fps)/(np.sqrt(640**2 + 360**2))
167
+
168
+ # Smooth both SSIM and ORB scores
169
+ smoothed_ssim_scores = smooth_curve(ssim_scores, window_size=window_size)
170
+ smoothed_orb_scores = smooth_curve(orb_scores, window_size=window_size)
171
+
172
+ #pixel_diff_scores = np.array(pixel_diff_scores) / np.max(pixel_diff_scores)
173
+
174
+ # Combine metrics
175
+ combined_scores = (0.3 * orb_scores) + (0.7 * ssim_scores)
176
+ smoothed_combined_scores = (0.3 * smoothed_orb_scores) + (0.7 * smoothed_ssim_scores)
177
+
178
+ # Adjust X-axis to reflect the center of the window used for smoothing
179
+ adjusted_timestamps = timestamps[window_size // 2 : -(window_size // 2)]
180
+
181
+ # Detect fast motion using sliding window
182
+ fast_motion_timestamps = []
183
+ fast_motion_frames = []
184
+ fast_motion_mags = []
185
+
186
+ #for i in range(len(combined_scores) - window_size + 1):
187
+ # window = combined_scores[i:i + window_size]
188
+ # if np.mean(window) > motion_threshold:
189
+ # #print(f"DEBUG!! mean : {np.mean(window)} i : {i + (start_time * fps)} i+window_size : {i+window_size + (start_time * fps)} window : {window}")
190
+ # #fast_motion_frames.extend(range(i + int(start_time * fps), i + window_size + int(start_time * fps)))
191
+ # fast_motion_mags.extend(combined_scores[i:i + window_size])
192
+ # fast_motion_timestamps.extend(timestamps[i:i + window_size])
193
+
194
+ ids = []
195
+ for i in range(len(combined_scores)):
196
+ if combined_scores[i] > motion_threshold:
197
+ fast_motion_mags.append(combined_scores[i])
198
+ fast_motion_timestamps.append(timestamps[i])
199
+ fast_motion_frames.append(frame_list[i])
200
+ ids.append(i)
201
+
202
+ padded_fast_motion_frames = []
203
+ padded_fast_motion_timestamps = []
204
+
205
+ if len(ids) < 5 and len(ids) > 0:
206
+ #Padding fast_motion_frames and fast_motion_timestamps
207
+ padded_fast_motion_frames.extend(frame_list[min(ids) - 2:min(ids)])
208
+ padded_fast_motion_timestamps.extend(timestamps[min(ids) - 2:min(ids)])
209
+
210
+ padded_fast_motion_frames.extend(fast_motion_frames)
211
+ padded_fast_motion_timestamps.extend(fast_motion_timestamps)
212
+
213
+ padded_fast_motion_frames.extend(frame_list[max(ids) + 1:max(ids) + 3])
214
+ padded_fast_motion_timestamps.extend(timestamps[max(ids) + 1:max(ids) + 3])
215
+ print(f"padded_fast_motion_timestamps are {padded_fast_motion_timestamps}. Length of padded_fast_motion_timestamps is {len(padded_fast_motion_frames)}")
216
+ else:
217
+ padded_fast_motion_frames = fast_motion_frames
218
+ padded_fast_motion_timestamps = fast_motion_timestamps
219
+
220
+ # Plot results
221
+ plt.figure(figsize=(12, 6))
222
+ plt.plot(adjusted_timestamps, smoothed_orb_scores, label='ORB Distance')
223
+ plt.plot(adjusted_timestamps, smoothed_ssim_scores, label='Inverted SSIM')
224
+ #plt.plot(adjusted_timestamps, optical_flow_scores, label='Optical Flow')
225
+ plt.plot(adjusted_timestamps, smoothed_combined_scores, label='Combined Score')
226
+ plt.axhline(y=motion_threshold, color='r', linestyle='--', label='Threshold')
227
+ plt.xlabel('Frame')
228
+ plt.ylabel('Normalized Score')
229
+ plt.title('Motion Detection Metrics')
230
+ plt.legend()
231
+ plt.savefig(f"{output_dir}/motion_detection_plot_smoothened_{video_path.split('/')[-1].split('.')[0]}.png")
232
+
233
+ # Plot results
234
+ plt.figure(figsize=(12, 6))
235
+ #plt.plot(timestamps, orb_scores, label='ORB Distance')
236
+ plt.plot(timestamps, ssim_scores, label='Inverted SSIM')
237
+ #plt.plot(timestamps, optical_flow_scores, label='Optical Flow')
238
+ plt.plot(timestamps, combined_scores, label='Combined Score')
239
+ plt.axhline(y=motion_threshold, color='r', linestyle='--', label='Threshold')
240
+ plt.xlabel('Frame')
241
+ plt.ylabel('Normalized Score')
242
+ plt.title('Motion Detection Metrics')
243
+ plt.legend()
244
+ plt.savefig(f"{output_dir}/motion_detection_plot_raw_{video_path.split('/')[-1].split('.')[0]}.png")
245
+
246
+
247
+ # Print results
248
+ print(f"Max motion score is {np.max(combined_scores)} and mean motion score is {np.mean(combined_scores)} from {np.min(timestamps)} to {np.max(timestamps)}")
249
+ print(f"Detected {len(fast_motion_timestamps)} frames when step = {step}.")
250
+ try:
251
+ print(f"fast motion between {np.min(fast_motion_timestamps)} and {np.max(fast_motion_timestamps)}")
252
+ except:
253
+ pass
254
+
255
+ #for i in range(len(fast_motion_timestamps)):
256
+ # timestamp = fast_motion_timestamps[i]
257
+ # mag = fast_motion_mags[i]
258
+ # print(f"(Time: {timestamp:.2f}s) (Magnitude : {mag:.2f})")
259
+
260
+ if len(fast_motion_timestamps) == 0:
261
+ print("FAST MOTION NOT DETECTED!")
262
+ return [], []
263
+ elif len(fast_motion_timestamps) > 0.5 * len(combined_scores):
264
+ print("More than half of the video has fast motion")
265
+ return fast_motion_timestamps, padded_fast_motion_frames
266
+ else:
267
+ timestamp_clusters = find_timestamp_clusters(fast_motion_timestamps, min_time_gap = 5)
268
+ for timestamp_cluster in timestamp_clusters:
269
+ print(f"min time : {np.min(timestamp_cluster)} max time : {np.max(timestamp_cluster)} length : {len(timestamp_cluster)}")
270
+ return timestamp_clusters, padded_fast_motion_frames
271
+
272
+
273
+ '''
274
+ # Open the video file
275
+ video_path = "../test_videos/"
276
+ mp4_files = [f for f in os.listdir(video_path) if f.endswith('.mp4')]
277
+ output_dir = "motion_detection_results"
278
+ os.system(f"rm -rf {output_dir}")
279
+ os.system(f"mkdir {output_dir}")
280
+ end_time = 15
281
+ start_time = 0
282
+
283
+ for mp4_file in mp4_files:
284
+ print(f"\nAnalyzing video {mp4_file}")
285
+
286
+ if mp4_file == "8.mp4":
287
+ end_time = 60
288
+ start_time = 0
289
+ elif mp4_file == "6.mp4":
290
+ end_time = 32
291
+ start_time = 0
292
+ elif mp4_file == "3.mp4":
293
+ end_time = 6.5 #To remove last few frames that are blurry
294
+ start_time = 0
295
+ elif mp4_file == "2.mp4":
296
+ end_time = 182
297
+ start_time = 140
298
+ else:
299
+ end_time = 15
300
+ start_time = 0
301
+
302
+ #if mp4_file != "3.mp4" and mp4_file != "5.mp4" and mp4_file != "6.mp4":
303
+ # continue
304
+
305
+ start = time.time()
306
+ fast_motion_timestamps = detect_fast_motion(video_path + mp4_file, output_dir, end_time, start_time, motion_threshold = 1.5)
307
+ end = time.time()
308
+
309
+ print(f"Execution time for {mp4_file} : {end - start} seconds. Duration of the video was {end_time - start_time} seconds")
310
+ '''