Update utils/ingest_video.py
Browse files- utils/ingest_video.py +121 -121
utils/ingest_video.py
CHANGED
@@ -1,122 +1,122 @@
|
|
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 |
-
|
13 |
-
image_loader = ImageLoader()
|
14 |
-
CLIP = OpenCLIPEmbeddingFunction()
|
15 |
-
video_collection = client.get_or_create_collection(
|
16 |
-
name='video_collection',
|
17 |
-
embedding_function=CLIP,
|
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')
|
64 |
-
cv2.imwrite(output_frame_filename, image)
|
65 |
-
|
66 |
-
success, image = video_capture.read()
|
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:
|
92 |
-
frame_id = f"{frame[:-4]}_{video_title}"
|
93 |
-
frame_path = os.path.join(frames_dir, video_title, frame)
|
94 |
-
ids.append(frame_id)
|
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
|
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
|
112 |
-
destination_folder = r"video"
|
113 |
-
unzip_file(zip_file_path, destination_folder)
|
114 |
-
print("Unzipped")
|
115 |
-
video_folder_path = r'video
|
116 |
-
output_folder_path = r'video
|
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 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 |
+
|
13 |
+
image_loader = ImageLoader()
|
14 |
+
CLIP = OpenCLIPEmbeddingFunction()
|
15 |
+
video_collection = client.get_or_create_collection(
|
16 |
+
name='video_collection',
|
17 |
+
embedding_function=CLIP,
|
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')
|
64 |
+
cv2.imwrite(output_frame_filename, image)
|
65 |
+
|
66 |
+
success, image = video_capture.read()
|
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:
|
92 |
+
frame_id = f"{frame[:-4]}_{video_title}"
|
93 |
+
frame_path = os.path.join(frames_dir, video_title, frame)
|
94 |
+
ids.append(frame_id)
|
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 |
|