Shami96 commited on
Commit
8ab8202
·
verified ·
1 Parent(s): f4b5761

Create video.py

Browse files
Files changed (1) hide show
  1. video.py +53 -0
video.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import subprocess
2
+ from pathlib import Path
3
+ import cv2
4
+
5
+ from config import FRAMES_SUBDIR
6
+
7
+ def ensure_dir(p: Path):
8
+ p.mkdir(parents=True, exist_ok=True)
9
+
10
+ def extract_audio_ffmpeg(video_path: Path, wav_path: Path, sr: int = 16000):
11
+ ensure_dir(wav_path.parent)
12
+ cmd = [
13
+ "ffmpeg", "-y",
14
+ "-i", str(video_path),
15
+ "-vn", # no video
16
+ "-ac", "1",
17
+ "-ar", str(sr),
18
+ str(wav_path),
19
+ ]
20
+ subprocess.run(cmd, check=True)
21
+ return wav_path
22
+
23
+ def extract_frames(video_path: Path, out_dir: Path, interval_sec: float, max_frames: int):
24
+ ensure_dir(out_dir)
25
+ cap = cv2.VideoCapture(str(video_path))
26
+ if not cap.isOpened():
27
+ raise RuntimeError("Cannot open video")
28
+ fps = cap.get(cv2.CAP_PROP_FPS) or 25.0
29
+ step = max(int(fps * interval_sec), 1)
30
+
31
+ idx, saved = 0, 0
32
+ while True:
33
+ ok, frame = cap.read()
34
+ if not ok:
35
+ break
36
+ if idx % step == 0:
37
+ (out_dir / f"frame_{saved:05d}.jpg").write_bytes(
38
+ cv2.imencode(".jpg", frame, [int(cv2.IMWRITE_JPEG_QUALITY), 92])[1].tobytes()
39
+ )
40
+ saved += 1
41
+ if saved >= max_frames:
42
+ break
43
+ idx += 1
44
+ cap.release()
45
+ return saved
46
+
47
+ def prepare_dirs(out_root: Path, video_file: Path):
48
+ base = video_file.stem
49
+ run_dir = out_root / base
50
+ frames_dir = run_dir / FRAMES_SUBDIR
51
+ ensure_dir(run_dir)
52
+ ensure_dir(frames_dir)
53
+ return run_dir, frames_dir