File size: 6,958 Bytes
c39093b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
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
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
#!/usr/bin/env python3
"""
Script to randomly extract k frames from WebP files in data/shots/ and save them as PNG files.

Usage:
    python random_frame_extractor.py <k> <output_dir>
    
Where:
    k: Number of frames to extract
    output_dir: Directory to save the extracted frames

Input:  data/shots/sample-XXX-Y.webp (randomly selected)
Output: <output_dir>/sample-XXX-Y-fZ.png (where Z is the frame number, e.g., f20 for frame 20)
"""

import os
import sys
import random
from pathlib import Path
from PIL import Image
import re
import argparse


def get_frame_count(webp_path):
    """
    Get the total number of frames in a WebP file.
    
    Args:
        webp_path (Path): Path to the WebP file
        
    Returns:
        int: Number of frames in the file
    """
    try:
        with Image.open(webp_path) as img:
            frame_count = 0
            try:
                while True:
                    img.seek(frame_count)
                    frame_count += 1
            except EOFError:
                pass
            return max(1, frame_count)  # At least 1 frame for static images
    except Exception as e:
        print(f"Error reading {webp_path}: {e}")
        return 0


def extract_random_frames(webp_path, output_dir, num_frames_to_extract):
    """
    Extract random frames from a WebP file and save them as PNG files.
    
    Args:
        webp_path (Path): Path to the input WebP file
        output_dir (Path): Directory to save the extracted frames
        num_frames_to_extract (int): Number of frames to extract from this file
        
    Returns:
        list: List of extracted frame filenames
    """
    try:
        # Parse filename to get sample and shot numbers
        filename = webp_path.stem  # e.g., "sample-123-2"
        match = re.match(r'sample-(\d+)-(\d+)', filename)
        if not match:
            print(f"Warning: Filename {filename} doesn't match expected pattern")
            return []
        
        sample_num = match.group(1)
        shot_num = match.group(2)
        
        # Get total frame count
        total_frames = get_frame_count(webp_path)
        if total_frames == 0:
            return []
        
        # Determine how many frames to extract (don't exceed available frames)
        frames_to_extract = min(num_frames_to_extract, total_frames)
        
        # Select random frame indices
        if total_frames == 1:
            selected_frames = [0]
        else:
            selected_frames = sorted(random.sample(range(total_frames), frames_to_extract))
        
        extracted_files = []
        
        with Image.open(webp_path) as img:
            for frame_idx in selected_frames:
                try:
                    # Seek to the specific frame
                    img.seek(frame_idx)
                    
                    # Convert to RGB if necessary
                    frame = img.convert('RGB')
                    
                    # Create output filename: sample-XXX-Y-fZ.png
                    output_filename = f"sample-{sample_num}-{shot_num}-f{frame_idx}.png"
                    output_path = output_dir / output_filename
                    
                    # Save the frame as PNG
                    frame.save(output_path)
                    extracted_files.append(output_filename)
                    print(f"Extracted frame {frame_idx} from {webp_path.name}: {output_filename}")
                    
                except Exception as e:
                    print(f"Error extracting frame {frame_idx} from {webp_path}: {e}")
        
        return extracted_files
        
    except Exception as e:
        print(f"Error processing {webp_path}: {e}")
        return []


def main():
    """Main function to randomly extract k frames from WebP files"""
    
    # Parse command line arguments
    parser = argparse.ArgumentParser(description='Randomly extract k frames from WebP files')
    parser.add_argument('k', type=int, help='Number of frames to extract')
    parser.add_argument('output_dir', type=str, help='Output directory for extracted frames')
    parser.add_argument('--frames-per-file', type=int, default=3, 
                       help='Maximum frames to extract per WebP file (default: 3)')
    parser.add_argument('--seed', type=int, help='Random seed for reproducible results')
    
    args = parser.parse_args()
    
    if args.k <= 0:
        print("Error: k must be a positive integer")
        sys.exit(1)
    
    # Set random seed if provided
    if args.seed is not None:
        random.seed(args.seed)
        print(f"Using random seed: {args.seed}")
    
    # Set up paths
    script_dir = Path(__file__).parent
    shots_dir = script_dir / "data" / "shots"
    output_dir = Path(args.output_dir)
    
    # Check if shots directory exists
    if not shots_dir.exists():
        print(f"Error: Shots directory not found: {shots_dir}")
        sys.exit(1)
    
    # Create output directory if it doesn't exist
    output_dir.mkdir(parents=True, exist_ok=True)
    print(f"Output directory: {output_dir}")
    
    # Find all WebP files
    webp_files = list(shots_dir.glob('sample-*.webp'))
    
    if not webp_files:
        print(f"No WebP files found in {shots_dir}")
        sys.exit(1)
    
    print(f"Found {len(webp_files)} WebP files available")
    
    # Calculate how many files we need to process
    frames_per_file = args.frames_per_file
    files_needed = (args.k + frames_per_file - 1) // frames_per_file  # Ceiling division
    files_needed = min(files_needed, len(webp_files))
    
    # Randomly select WebP files
    selected_files = random.sample(webp_files, files_needed)
    print(f"Randomly selected {len(selected_files)} WebP files")
    
    total_extracted = 0
    extracted_files = []
    
    # Process each selected WebP file
    for i, webp_file in enumerate(selected_files):
        remaining_frames = args.k - total_extracted
        if remaining_frames <= 0:
            break
        
        # Calculate how many frames to extract from this file
        frames_from_this_file = min(frames_per_file, remaining_frames)
        
        print(f"\nProcessing ({i+1}/{len(selected_files)}): {webp_file.name}")
        print(f"Extracting up to {frames_from_this_file} frames...")
        
        files = extract_random_frames(webp_file, output_dir, frames_from_this_file)
        extracted_files.extend(files)
        total_extracted += len(files)
    
    print(f"\n=== Summary ===")
    print(f"Target frames: {args.k}")
    print(f"Frames extracted: {total_extracted}")
    print(f"Files processed: {len(selected_files)}")
    print(f"Output directory: {output_dir}")
    
    if total_extracted < args.k:
        print(f"Warning: Only extracted {total_extracted} frames out of {args.k} requested")
    
    print(f"\nExtracted files:")
    for filename in extracted_files:
        print(f"  {filename}")


if __name__ == "__main__":
    main()