eduport-vision / downloader.py
aoxo's picture
Create downloader.py
27e31d1 verified
import os
import csv
import yt_dlp as youtube_dl
import cv2
from moviepy.editor import VideoFileClip
def download_and_extract_frames(csv_file, output_base_folder='video_frames'):
# Create base output folder if it doesn't exist
os.makedirs(output_base_folder, exist_ok=True)
# Read the CSV file
with open(csv_file, 'r') as file:
csv_reader = csv.reader(file)
# Skip header if exists
next(csv_reader, None)
# Process each video
for row in csv_reader:
try:
video_name, video_link = row
# Sanitize video name for folder creation
safe_video_name = ''.join(c if c.isalnum() or c in ['-', '_'] else '_' for c in video_name)
# Setup download options
ydl_opts = {
'outtmpl': f'./{safe_video_name}.%(ext)s',
'format': 'bestvideo+bestaudio/best',
'no_color': True, # Disable color output
'no_warnings': True # Suppress warnings
}
# Download video
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
ydl.download([video_link])
# Find the downloaded video file
downloaded_files = os.listdir('.')
video_files = [f for f in downloaded_files if f.startswith(safe_video_name) and
(f.endswith('.mp4') or f.endswith('.webm') or f.endswith('.mkv'))]
if not video_files:
print(f"Error: No video file found for {video_name}")
continue
# Create folder for frames
frame_folder = os.path.join(output_base_folder, safe_video_name)
os.makedirs(frame_folder, exist_ok=True)
# Process each downloaded video file
for video_file in video_files:
# Extract frames
video = cv2.VideoCapture(video_file)
frame_count = 0
while True:
ret, frame = video.read()
if not ret:
break
# Save frame
frame_path = os.path.join(frame_folder, f'frame_{frame_count:04d}.jpg')
cv2.imwrite(frame_path, frame)
frame_count += 1
# Release video capture
video.release()
print(f"Processed {video_name} from {video_file}: {frame_count} frames extracted")
except Exception as e:
print(f"Error processing {video_name}: {str(e)}")
# Continue to next video if one fails
continue
# Usage
if __name__ == "__main__":
download_and_extract_frames('videos.csv')