aoxo commited on
Commit
27e31d1
·
verified ·
1 Parent(s): 85f52a9

Create downloader.py

Browse files
Files changed (1) hide show
  1. downloader.py +78 -0
downloader.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import csv
3
+ import yt_dlp as youtube_dl
4
+ import cv2
5
+ from moviepy.editor import VideoFileClip
6
+
7
+ def download_and_extract_frames(csv_file, output_base_folder='video_frames'):
8
+ # Create base output folder if it doesn't exist
9
+ os.makedirs(output_base_folder, exist_ok=True)
10
+
11
+ # Read the CSV file
12
+ with open(csv_file, 'r') as file:
13
+ csv_reader = csv.reader(file)
14
+ # Skip header if exists
15
+ next(csv_reader, None)
16
+
17
+ # Process each video
18
+ for row in csv_reader:
19
+ try:
20
+ video_name, video_link = row
21
+
22
+ # Sanitize video name for folder creation
23
+ safe_video_name = ''.join(c if c.isalnum() or c in ['-', '_'] else '_' for c in video_name)
24
+
25
+ # Setup download options
26
+ ydl_opts = {
27
+ 'outtmpl': f'./{safe_video_name}.%(ext)s',
28
+ 'format': 'bestvideo+bestaudio/best',
29
+ 'no_color': True, # Disable color output
30
+ 'no_warnings': True # Suppress warnings
31
+ }
32
+
33
+ # Download video
34
+ with youtube_dl.YoutubeDL(ydl_opts) as ydl:
35
+ ydl.download([video_link])
36
+
37
+ # Find the downloaded video file
38
+ downloaded_files = os.listdir('.')
39
+ video_files = [f for f in downloaded_files if f.startswith(safe_video_name) and
40
+ (f.endswith('.mp4') or f.endswith('.webm') or f.endswith('.mkv'))]
41
+
42
+ if not video_files:
43
+ print(f"Error: No video file found for {video_name}")
44
+ continue
45
+
46
+ # Create folder for frames
47
+ frame_folder = os.path.join(output_base_folder, safe_video_name)
48
+ os.makedirs(frame_folder, exist_ok=True)
49
+
50
+ # Process each downloaded video file
51
+ for video_file in video_files:
52
+ # Extract frames
53
+ video = cv2.VideoCapture(video_file)
54
+ frame_count = 0
55
+
56
+ while True:
57
+ ret, frame = video.read()
58
+ if not ret:
59
+ break
60
+
61
+ # Save frame
62
+ frame_path = os.path.join(frame_folder, f'frame_{frame_count:04d}.jpg')
63
+ cv2.imwrite(frame_path, frame)
64
+ frame_count += 1
65
+
66
+ # Release video capture
67
+ video.release()
68
+
69
+ print(f"Processed {video_name} from {video_file}: {frame_count} frames extracted")
70
+
71
+ except Exception as e:
72
+ print(f"Error processing {video_name}: {str(e)}")
73
+ # Continue to next video if one fails
74
+ continue
75
+
76
+ # Usage
77
+ if __name__ == "__main__":
78
+ download_and_extract_frames('videos.csv')