Spaces:
Sleeping
Sleeping
Update services/video_service.py
Browse files- services/video_service.py +56 -23
services/video_service.py
CHANGED
@@ -1,28 +1,61 @@
|
|
1 |
-
# services/video_service.py
|
2 |
-
|
3 |
-
import cv2
|
4 |
-
import random
|
5 |
import os
|
|
|
|
|
6 |
|
7 |
-
|
|
|
8 |
|
9 |
-
|
10 |
-
|
11 |
-
return [os.path.join(VIDEO_FOLDER, f) for f in os.listdir(VIDEO_FOLDER) if f.endswith(".mp4")]
|
12 |
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
23 |
if not ret:
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import os
|
2 |
+
import random
|
3 |
+
import cv2
|
4 |
|
5 |
+
# Path to the directory containing anomaly videos
|
6 |
+
VIDEO_DIR = "sample_videos"
|
7 |
|
8 |
+
# Supported video extensions
|
9 |
+
VIDEO_EXTENSIONS = ['.mp4', '.avi', '.mov']
|
|
|
10 |
|
11 |
+
# Load all video file paths once at startup
|
12 |
+
video_files = [
|
13 |
+
os.path.join(VIDEO_DIR, file)
|
14 |
+
for file in os.listdir(VIDEO_DIR)
|
15 |
+
if any(file.lower().endswith(ext) for ext in VIDEO_EXTENSIONS)
|
16 |
+
]
|
17 |
+
|
18 |
+
if not video_files:
|
19 |
+
raise ValueError(f"No valid videos found in {VIDEO_DIR}. Please upload videos first.")
|
20 |
+
|
21 |
+
# Random state for reproducibility if needed
|
22 |
+
random_state = random.Random()
|
23 |
+
|
24 |
+
# Global frame iterator and capture
|
25 |
+
current_video = None
|
26 |
+
frame_iterator = None
|
27 |
+
|
28 |
+
def open_new_video():
|
29 |
+
global current_video, frame_iterator
|
30 |
+
video_path = random_state.choice(video_files)
|
31 |
+
current_video = cv2.VideoCapture(video_path)
|
32 |
+
|
33 |
+
if not current_video.isOpened():
|
34 |
+
raise IOError(f"Cannot open video: {video_path}")
|
35 |
+
|
36 |
+
frame_iterator = iter_video_frames(current_video)
|
37 |
+
|
38 |
+
def iter_video_frames(video_cap):
|
39 |
+
while True:
|
40 |
+
ret, frame = video_cap.read()
|
41 |
if not ret:
|
42 |
+
break
|
43 |
+
yield frame
|
44 |
+
|
45 |
+
video_cap.release()
|
46 |
+
|
47 |
+
# Main function to get next frame
|
48 |
+
|
49 |
+
def get_random_video_frame():
|
50 |
+
global current_video, frame_iterator
|
51 |
+
|
52 |
+
if frame_iterator is None:
|
53 |
+
open_new_video()
|
54 |
+
|
55 |
+
try:
|
56 |
+
frame = next(frame_iterator)
|
57 |
+
return frame
|
58 |
+
except StopIteration:
|
59 |
+
open_new_video()
|
60 |
+
frame = next(frame_iterator)
|
61 |
+
return frame
|