Fataj commited on
Commit
09cc4f9
·
verified ·
1 Parent(s): e22f43a

Upload extractor.py

Browse files
Files changed (1) hide show
  1. extractor.py +59 -0
extractor.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import shutil
3
+ import tempfile
4
+ import zipfile
5
+ from pathlib import Path
6
+ import ffmpeg
7
+ import gradio as gr
8
+
9
+ RESOLUTIONS = {
10
+ "Original": None,
11
+ "512x512": (512, 512),
12
+ "768x768": (768, 768),
13
+ "1024x576": (1024, 576)
14
+ }
15
+
16
+ def extract_frames(video_path, fps=1, resolution=None):
17
+ temp_dir = tempfile.mkdtemp()
18
+ output_dir = Path(temp_dir) / "frames"
19
+ output_dir.mkdir(parents=True, exist_ok=True)
20
+
21
+ output_pattern = str(output_dir / "frame_%04d.jpg")
22
+
23
+ filters = [f"fps={fps}", "unsharp=5:5:1.0"]
24
+ if resolution:
25
+ filters.append(f"scale={resolution[0]}:{resolution[1]}")
26
+ filter_str = ",".join(filters)
27
+
28
+ try:
29
+ (
30
+ ffmpeg
31
+ .input(video_path)
32
+ .output(output_pattern, vf=filter_str, qscale=2)
33
+ .run()
34
+ )
35
+ except ffmpeg.Error as e:
36
+ print("FFmpeg error:", e)
37
+ raise gr.Error("Failed to extract frames with FFmpeg.")
38
+
39
+ return output_dir
40
+
41
+
42
+ def zip_frames(frame_dir):
43
+ zip_path = tempfile.NamedTemporaryFile(delete=False, suffix=".zip").name
44
+ with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zipf:
45
+ for file_path in Path(frame_dir).glob("*.jpg"):
46
+ zipf.write(file_path, arcname=file_path.name)
47
+ return zip_path
48
+
49
+
50
+ def process_video(video_path, fps, resolution_label):
51
+ resolution = RESOLUTIONS[resolution_label]
52
+ try:
53
+ frames_path = extract_frames(video_path, fps, resolution)
54
+ zip_path = zip_frames(frames_path)
55
+ shutil.rmtree(frames_path.parent)
56
+ return zip_path
57
+ except Exception as e:
58
+ print("Error during processing:", str(e))
59
+ raise gr.Error(f"Failed to extract frames: {str(e)}")