NEXAS commited on
Commit
27dc37c
·
verified ·
1 Parent(s): 257537d

Update utils/ingest_video.py

Browse files
Files changed (1) hide show
  1. utils/ingest_video.py +85 -52
utils/ingest_video.py CHANGED
@@ -1,12 +1,11 @@
1
- import gdown
2
  import zipfile
3
  import os
4
  import chromadb
5
  from chromadb.utils.embedding_functions import OpenCLIPEmbeddingFunction
6
  from chromadb.utils.data_loaders import ImageLoader
7
-
8
  import cv2
9
 
 
10
  path = "mm_vdb2"
11
  client = chromadb.PersistentClient(path=path)
12
 
@@ -18,46 +17,65 @@ video_collection = client.get_or_create_collection(
18
  data_loader=image_loader
19
  )
20
 
21
- def unzip_file(zip_path, extract_to):
22
  """
23
- Unzips a zip file to the specified directory.
24
-
25
  Args:
26
  zip_path (str): Path to the zip file.
27
  extract_to (str): Directory where the contents should be extracted.
28
  """
29
  try:
30
- # Ensure the destination directory exists
31
- os.makedirs(extract_to, exist_ok=True)
32
 
33
- # Open the zip file
34
  with zipfile.ZipFile(zip_path, 'r') as zip_ref:
35
- # Extract all the contents
36
- zip_ref.extractall(extract_to)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
  print(f"Successfully extracted {zip_path} to {extract_to}")
38
  except Exception as e:
39
- print(f"An error occurred: {e}")
40
-
41
 
42
  def extract_frames(video_folder, output_folder):
43
- if not os.path.exists(output_folder):
44
- os.makedirs(output_folder)
 
 
 
 
 
 
45
 
46
  for video_filename in os.listdir(video_folder):
47
- if video_filename.endswith('.mp4'):
48
  video_path = os.path.join(video_folder, video_filename)
49
  video_capture = cv2.VideoCapture(video_path)
50
  fps = video_capture.get(cv2.CAP_PROP_FPS)
 
 
 
51
  frame_count = int(video_capture.get(cv2.CAP_PROP_FRAME_COUNT))
52
- duration = frame_count / fps
53
 
54
  output_subfolder = os.path.join(output_folder, os.path.splitext(video_filename)[0])
55
- if not os.path.exists(output_subfolder):
56
- os.makedirs(output_subfolder)
57
 
58
  success, image = video_capture.read()
59
  frame_number = 0
60
  while success:
 
61
  if frame_number == 0 or frame_number % int(fps * 5) == 0 or frame_number == frame_count - 1:
62
  frame_time = frame_number / fps
63
  output_frame_filename = os.path.join(output_subfolder, f'frame_{int(frame_time)}.jpg')
@@ -67,25 +85,27 @@ def extract_frames(video_folder, output_folder):
67
  frame_number += 1
68
 
69
  video_capture.release()
 
70
 
71
  def add_frames_to_chromadb(video_dir, frames_dir):
72
- # Dictionary to hold video titles and their corresponding frames
 
 
 
 
 
 
73
  video_frames = {}
74
 
75
- # Process each video and associate its frames
76
  for video_file in os.listdir(video_dir):
77
- if video_file.endswith('.mp4'):
78
- video_title = video_file[:-4]
79
  frame_folder = os.path.join(frames_dir, video_title)
80
  if os.path.exists(frame_folder):
81
- # List all jpg files in the folder
82
- video_frames[video_title] = [f for f in os.listdir(frame_folder) if f.endswith('.jpg')]
83
-
84
- # Prepare ids, uris and metadatas
85
- ids = []
86
- uris = []
87
- metadatas = []
88
 
 
89
  for video_title, frames in video_frames.items():
90
  video_path = os.path.join(video_dir, f"{video_title}.mp4")
91
  for frame in frames:
@@ -95,28 +115,41 @@ def add_frames_to_chromadb(video_dir, frames_dir):
95
  uris.append(frame_path)
96
  metadatas.append({'video_uri': video_path})
97
 
98
- video_collection.add(ids=ids, uris=uris, metadatas=metadatas)
99
-
100
- # Running it
101
-
102
-
103
 
104
- def intiate_video():
105
- file_id = "1Fm8Cge1VM4w8fmE0cZfRKhIQV0UgBXzp"
106
- output_file = r"video/StockVideos-CC01.zip"
107
- gdown.download(f"https://drive.google.com/uc?id={file_id}", output_file, quiet=False)
108
-
109
- print(f"File downloaded successfully: {output_file}")
110
- # Example Usage
111
- zip_file_path = r"video/StockVideos-CC01.zip"
112
- destination_folder = r"video"
113
- unzip_file(zip_file_path, destination_folder)
114
- print("Unzipped")
115
- video_folder_path = r'video/StockVideos-CC0'
116
- output_folder_path = r'video/StockVideos-CC0-frames'
117
-
118
- extract_frames(video_folder_path, output_folder_path)
119
 
120
- add_frames_to_chromadb(video_folder_path, output_folder_path)
121
- return video_collection
122
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
  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
  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
  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, frame_output_dir):
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)