Repository navigation
Expand file tree
/
Copy pathvideo.py
More file actions
114 lines (102 loc) · 3.32 KB
/
Copy pathvideo.py
File metadata and controls
114 lines (102 loc) · 3.32 KB
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
from __future__ import annotations
import json
import math
import subprocess
from pathlib import Path
from videoquery.models import ChunkTask
def probe_duration_seconds(source: str | Path, ffprobe_bin: str = "ffprobe") -> float:
command = [
ffprobe_bin,
"-v",
"error",
"-show_entries",
"format=duration",
"-of",
"json",
str(source),
]
try:
completed = subprocess.run(command, check=True, capture_output=True, text=True)
except FileNotFoundError as exc:
raise RuntimeError(
f"{ffprobe_bin!r} was not found. Install FFmpeg or set VIDEOQUERY_FFPROBE_BIN."
) from exc
except subprocess.CalledProcessError as exc:
raise RuntimeError(f"ffprobe failed for {source}: {exc.stderr.strip()}") from exc
payload = json.loads(completed.stdout)
duration = float(payload["format"]["duration"])
if not math.isfinite(duration) or duration <= 0:
raise RuntimeError(f"Could not read a positive duration from {source}")
return duration
def make_chunk_tasks(
*,
video_id: str,
bucket: str,
key: str,
duration_seconds: float,
chunk_seconds: int,
source_etag: str | None = None,
) -> list[ChunkTask]:
if chunk_seconds <= 0:
raise ValueError("chunk_seconds must be positive")
if duration_seconds <= 0:
raise ValueError("duration_seconds must be positive")
tasks: list[ChunkTask] = []
count = int(math.ceil(duration_seconds / chunk_seconds))
for index in range(count):
start_time = float(index * chunk_seconds)
end_time = min(float((index + 1) * chunk_seconds), float(duration_seconds))
tasks.append(
ChunkTask(
video_id=video_id,
s3_bucket=bucket,
s3_key=key,
chunk_id=f"{index:06d}",
start_time=start_time,
end_time=end_time,
source_etag=source_etag,
)
)
return tasks
def extract_frames(
*,
video_path: Path,
output_dir: Path,
start_time: float,
end_time: float,
sample_fps: float,
ffmpeg_bin: str = "ffmpeg",
) -> list[tuple[Path, float]]:
if sample_fps <= 0:
raise ValueError("sample_fps must be positive")
if end_time <= start_time:
raise ValueError("end_time must be greater than start_time")
output_dir.mkdir(parents=True, exist_ok=True)
frame_pattern = output_dir / "frame_%06d.jpg"
command = [
ffmpeg_bin,
"-hide_banner",
"-loglevel",
"error",
"-ss",
f"{start_time:.3f}",
"-to",
f"{end_time:.3f}",
"-i",
str(video_path),
"-vf",
f"fps={sample_fps}",
"-q:v",
"2",
str(frame_pattern),
]
try:
subprocess.run(command, check=True, capture_output=True, text=True)
except FileNotFoundError as exc:
raise RuntimeError(
f"{ffmpeg_bin!r} was not found. Install FFmpeg or set VIDEOQUERY_FFMPEG_BIN."
) from exc
except subprocess.CalledProcessError as exc:
raise RuntimeError(f"ffmpeg failed for {video_path}: {exc.stderr.strip()}") from exc
frames = sorted(output_dir.glob("frame_*.jpg"))
return [(frame, start_time + (index / sample_fps)) for index, frame in enumerate(frames)]