SuriRaja commited on
Commit
3a3c94c
·
1 Parent(s): 931480f

Update services/video_service.py

Browse files
Files changed (1) hide show
  1. 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
- VIDEO_FOLDER = "data"
 
8
 
9
- def list_video_files():
10
- """List all video files inside the data/ folder."""
11
- return [os.path.join(VIDEO_FOLDER, f) for f in os.listdir(VIDEO_FOLDER) if f.endswith(".mp4")]
12
 
13
- def get_random_video_frame():
14
- """Randomly pick a video from the folder and stream frames from it."""
15
- video_files = list_video_files()
16
- if not video_files:
17
- raise FileNotFoundError("No video files found in the 'data/' folder.")
18
-
19
- video_path = random.choice(video_files)
20
- cap = cv2.VideoCapture(video_path)
21
- while cap.isOpened():
22
- ret, frame = cap.read()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
  if not ret:
24
- # Restart when video ends
25
- cap.release()
26
- cap = cv2.VideoCapture(video_path)
27
- continue
28
- yield frame, os.path.basename(video_path)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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