NEXAS commited on
Commit
2ab65e0
·
verified ·
1 Parent(s): 29d5834

Update utils/ingest_video.py

Browse files
Files changed (1) hide show
  1. utils/ingest_video.py +60 -89
utils/ingest_video.py CHANGED
@@ -1,11 +1,10 @@
1
- import zipfile
2
  import os
 
3
  import chromadb
4
  from chromadb.utils.embedding_functions import OpenCLIPEmbeddingFunction
5
  from chromadb.utils.data_loaders import ImageLoader
6
- import cv2
7
 
8
- # Initialize ChromaDB Persistent Client
9
  path = "mm_vdb2"
10
  client = chromadb.PersistentClient(path=path)
11
 
@@ -17,65 +16,33 @@ video_collection = client.get_or_create_collection(
17
  data_loader=image_loader
18
  )
19
 
20
- def unzip_file_flat(zip_path, extract_to):
21
- """
22
- Unzips a zip file and extracts all files into a single directory, ignoring internal folders.
23
-
24
- Args:
25
- zip_path (str): Path to the zip file.
26
- extract_to (str): Directory where the contents should be extracted.
27
- """
28
- try:
29
- os.makedirs(extract_to, exist_ok=True) # Ensure the output directory exists
30
-
31
- with zipfile.ZipFile(zip_path, 'r') as zip_ref:
32
- for file in zip_ref.namelist():
33
- if not file.endswith('/'): # Ignore directories
34
- file_name = os.path.basename(file)
35
- if not file_name: # Skip if it's a directory entry
36
- continue
37
- extracted_path = os.path.join(extract_to, file_name)
38
-
39
- # Handle filename conflicts by appending a number to duplicates
40
- base_name, ext = os.path.splitext(file_name)
41
- counter = 1
42
- while os.path.exists(extracted_path):
43
- extracted_path = os.path.join(extract_to, f"{base_name}_{counter}{ext}")
44
- counter += 1
45
-
46
- with zip_ref.open(file) as source, open(extracted_path, 'wb') as target:
47
- target.write(source.read())
48
- print(f"Successfully extracted {zip_path} to {extract_to}")
49
- except Exception as e:
50
- print(f"An error occurred while unzipping {zip_path}: {e}")
51
-
52
  def extract_frames(video_folder, output_folder):
53
  """
54
- Extracts frames from video files at regular intervals.
55
-
56
  Args:
57
- video_folder (str): Folder containing video files.
58
- output_folder (str): Folder to save extracted frames.
59
  """
60
- os.makedirs(output_folder, exist_ok=True)
 
61
 
62
  for video_filename in os.listdir(video_folder):
63
- if video_filename.lower().endswith('.mp4'):
64
  video_path = os.path.join(video_folder, video_filename)
65
  video_capture = cv2.VideoCapture(video_path)
66
  fps = video_capture.get(cv2.CAP_PROP_FPS)
67
- if fps == 0:
68
- print(f"Warning: FPS is zero for {video_filename}. Skipping.")
69
- continue
70
  frame_count = int(video_capture.get(cv2.CAP_PROP_FRAME_COUNT))
 
71
 
72
  output_subfolder = os.path.join(output_folder, os.path.splitext(video_filename)[0])
73
- os.makedirs(output_subfolder, exist_ok=True)
 
74
 
75
  success, image = video_capture.read()
76
  frame_number = 0
77
  while success:
78
- # Extract frame at the start, every 5 seconds, and the last frame
79
  if frame_number == 0 or frame_number % int(fps * 5) == 0 or frame_number == frame_count - 1:
80
  frame_time = frame_number / fps
81
  output_frame_filename = os.path.join(output_subfolder, f'frame_{int(frame_time)}.jpg')
@@ -85,27 +52,33 @@ def extract_frames(video_folder, output_folder):
85
  frame_number += 1
86
 
87
  video_capture.release()
88
- print(f"Frames extracted from {video_filename} to {output_subfolder}")
89
 
90
  def add_frames_to_chromadb(video_dir, frames_dir):
91
  """
92
- Adds metadata and URIs of video frames to ChromaDB collection.
93
-
94
  Args:
95
- video_dir (str): Directory containing original video files.
96
- frames_dir (str): Directory containing extracted frames.
97
  """
 
98
  video_frames = {}
99
 
100
- # Since all video files are directly in video_dir, no subfolders
101
  for video_file in os.listdir(video_dir):
102
- if video_file.lower().endswith('.mp4'):
103
- video_title = os.path.splitext(video_file)[0]
104
  frame_folder = os.path.join(frames_dir, video_title)
105
  if os.path.exists(frame_folder):
106
- video_frames[video_title] = [f for f in os.listdir(frame_folder) if f.lower().endswith('.jpg')]
 
 
 
 
 
 
107
 
108
- ids, uris, metadatas = [], [], []
109
  for video_title, frames in video_frames.items():
110
  video_path = os.path.join(video_dir, f"{video_title}.mp4")
111
  for frame in frames:
@@ -115,41 +88,39 @@ def add_frames_to_chromadb(video_dir, frames_dir):
115
  uris.append(frame_path)
116
  metadatas.append({'video_uri': video_path})
117
 
118
- if ids:
119
- video_collection.add(ids=ids, uris=uris, metadatas=metadatas)
120
- print(f"Added {len(ids)} frames to ChromaDB collection from {len(video_frames)} videos.")
121
- else:
122
- print("No frames to add to ChromaDB.")
123
 
124
- def process_uploaded_files(zip_files, extract_dir="extracted_videos", frame_output_dir="video"):
125
  """
126
- Processes uploaded zip files by extracting their contents, processing video files,
127
- and adding their frames to ChromaDB.
128
 
129
  Args:
130
- zip_files (list): List of paths to uploaded zip files.
131
- extract_dir (str): Directory to extract zip contents.
132
- frame_output_dir (str): Directory to store extracted frames.
 
133
  """
134
- os.makedirs(extract_dir, exist_ok=True)
135
- os.makedirs(frame_output_dir, exist_ok=True)
136
-
137
- for zip_file in zip_files:
138
- print(f"Processing {zip_file}...")
139
- unzip_file_flat(zip_file, extract_dir)
140
-
141
- # After extraction, all video files are directly in extract_dir
142
- extract_frames(extract_dir, frame_output_dir)
143
- add_frames_to_chromadb(extract_dir, frame_output_dir)
144
-
145
- # # Example Usage
146
- # if __name__ == "__main__":
147
- # # Example list of uploaded zip file paths
148
- # uploaded_files = [
149
- # "uploaded/video_package1.zip",
150
- # "uploaded/video_package2.zip"
151
- # ]
152
- # extract_dir = "extracted_videos" # All videos extracted here directly
153
- # frame_output_dir = "video_frames" # All frames stored here
154
-
155
- # process_uploaded_files(uploaded_files, extract_dir, frame_output_dir)
 
 
1
  import os
2
+ import cv2
3
  import chromadb
4
  from chromadb.utils.embedding_functions import OpenCLIPEmbeddingFunction
5
  from chromadb.utils.data_loaders import ImageLoader
 
6
 
7
+ # Initialize ChromaDB client and collection
8
  path = "mm_vdb2"
9
  client = chromadb.PersistentClient(path=path)
10
 
 
16
  data_loader=image_loader
17
  )
18
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
  def extract_frames(video_folder, output_folder):
20
  """
21
+ Extracts frames from all videos in the video_folder and saves them in the output_folder.
22
+
23
  Args:
24
+ video_folder (str): Path to the folder containing video files.
25
+ output_folder (str): Path to the folder where extracted frames will be saved.
26
  """
27
+ if not os.path.exists(output_folder):
28
+ os.makedirs(output_folder)
29
 
30
  for video_filename in os.listdir(video_folder):
31
+ if video_filename.endswith('.mp4'):
32
  video_path = os.path.join(video_folder, video_filename)
33
  video_capture = cv2.VideoCapture(video_path)
34
  fps = video_capture.get(cv2.CAP_PROP_FPS)
 
 
 
35
  frame_count = int(video_capture.get(cv2.CAP_PROP_FRAME_COUNT))
36
+ duration = frame_count / fps
37
 
38
  output_subfolder = os.path.join(output_folder, os.path.splitext(video_filename)[0])
39
+ if not os.path.exists(output_subfolder):
40
+ os.makedirs(output_subfolder)
41
 
42
  success, image = video_capture.read()
43
  frame_number = 0
44
  while success:
45
+ # Save frames at 0 seconds, every 5 seconds, and the last frame
46
  if frame_number == 0 or frame_number % int(fps * 5) == 0 or frame_number == frame_count - 1:
47
  frame_time = frame_number / fps
48
  output_frame_filename = os.path.join(output_subfolder, f'frame_{int(frame_time)}.jpg')
 
52
  frame_number += 1
53
 
54
  video_capture.release()
55
+
56
 
57
  def add_frames_to_chromadb(video_dir, frames_dir):
58
  """
59
+ Adds extracted frames from videos to the ChromaDB collection.
60
+
61
  Args:
62
+ video_dir (str): Path to the folder containing video files.
63
+ frames_dir (str): Path to the folder containing the extracted frames.
64
  """
65
+ # Dictionary to hold video titles and their corresponding frames
66
  video_frames = {}
67
 
68
+ # Process each video and associate its frames
69
  for video_file in os.listdir(video_dir):
70
+ if video_file.endswith('.mp4'):
71
+ video_title = video_file[:-4]
72
  frame_folder = os.path.join(frames_dir, video_title)
73
  if os.path.exists(frame_folder):
74
+ # List all jpg files in the folder
75
+ video_frames[video_title] = [f for f in os.listdir(frame_folder) if f.endswith('.jpg')]
76
+
77
+ # Prepare ids, uris, and metadatas for ChromaDB
78
+ ids = []
79
+ uris = []
80
+ metadatas = []
81
 
 
82
  for video_title, frames in video_frames.items():
83
  video_path = os.path.join(video_dir, f"{video_title}.mp4")
84
  for frame in frames:
 
88
  uris.append(frame_path)
89
  metadatas.append({'video_uri': video_path})
90
 
91
+ # Add frames to the ChromaDB collection
92
+ video_collection.add(ids=ids, uris=uris, metadatas=metadatas)
93
+
 
 
94
 
95
+ def initiate_video(video_folder_path):
96
  """
97
+ Initiates the video processing pipeline: extracts frames from videos
98
+ and adds them to the ChromaDB collection.
99
 
100
  Args:
101
+ video_folder_path (str): Path to the folder containing video files.
102
+
103
+ Returns:
104
+ The ChromaDB collection with the added frames.
105
  """
106
+ try:
107
+ print("Starting video processing pipeline...")
108
+
109
+ # Define output folder for extracted frames
110
+ output_folder_path = os.path.join(video_folder_path, 'extracted_frames')
111
+
112
+ # Extract frames from videos
113
+ print("Extracting frames...")
114
+ extract_frames(video_folder_path, output_folder_path)
115
+ print("Frames extracted successfully.")
116
+
117
+ # Add frames to ChromaDB collection
118
+ print("Adding frames to ChromaDB...")
119
+ add_frames_to_chromadb(video_folder_path, output_folder_path)
120
+ print("Frames added to ChromaDB successfully.")
121
+
122
+ return video_collection
123
+
124
+ except Exception as e:
125
+ print(f"An error occurred during video processing: {e}")
126
+ return None