Update utils/ingest_video.py
Browse files- 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
|
| 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
|
| 55 |
-
|
| 56 |
Args:
|
| 57 |
-
video_folder (str):
|
| 58 |
-
output_folder (str):
|
| 59 |
"""
|
| 60 |
-
os.
|
|
|
|
| 61 |
|
| 62 |
for video_filename in os.listdir(video_folder):
|
| 63 |
-
if video_filename.
|
| 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.
|
|
|
|
| 74 |
|
| 75 |
success, image = video_capture.read()
|
| 76 |
frame_number = 0
|
| 77 |
while success:
|
| 78 |
-
#
|
| 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 |
-
|
| 89 |
|
| 90 |
def add_frames_to_chromadb(video_dir, frames_dir):
|
| 91 |
"""
|
| 92 |
-
Adds
|
| 93 |
-
|
| 94 |
Args:
|
| 95 |
-
video_dir (str):
|
| 96 |
-
frames_dir (str):
|
| 97 |
"""
|
|
|
|
| 98 |
video_frames = {}
|
| 99 |
|
| 100 |
-
#
|
| 101 |
for video_file in os.listdir(video_dir):
|
| 102 |
-
if video_file.
|
| 103 |
-
video_title =
|
| 104 |
frame_folder = os.path.join(frames_dir, video_title)
|
| 105 |
if os.path.exists(frame_folder):
|
| 106 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
else:
|
| 122 |
-
print("No frames to add to ChromaDB.")
|
| 123 |
|
| 124 |
-
def
|
| 125 |
"""
|
| 126 |
-
|
| 127 |
-
and
|
| 128 |
|
| 129 |
Args:
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
|
|
|
| 133 |
"""
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
#
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 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
|
|
|