vided 0.1.2__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- vided/__init__.py +84 -0
- vided/__main__.py +4 -0
- vided/cli.py +347 -0
- vided/contact_sheet.py +257 -0
- vided/data/__init__.py +1 -0
- vided/data/silero_vad_16k_op15.onnx +0 -0
- vided/errors.py +21 -0
- vided/ffmpeg.py +200 -0
- vided/filtergraph.py +107 -0
- vided/frames.py +101 -0
- vided/project.py +238 -0
- vided/redactions.py +136 -0
- vided/render.py +78 -0
- vided/static/__init__.py +0 -0
- vided/static/app.js +1368 -0
- vided/static/index.html +121 -0
- vided/static/styles.css +808 -0
- vided/time_ranges.py +87 -0
- vided/trimmer.py +932 -0
- vided/ui_server.py +170 -0
- vided/vad.py +495 -0
- vided-0.1.2.dist-info/METADATA +492 -0
- vided-0.1.2.dist-info/RECORD +26 -0
- vided-0.1.2.dist-info/WHEEL +4 -0
- vided-0.1.2.dist-info/entry_points.txt +2 -0
- vided-0.1.2.dist-info/licenses/LICENSE +21 -0
vided/errors.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class VidedError(Exception):
|
|
5
|
+
"""Base class for expected vided errors."""
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class ProjectError(VidedError):
|
|
9
|
+
"""Raised when a project file or project state is invalid."""
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class ValidationError(VidedError, ValueError):
|
|
13
|
+
"""Raised when user-provided data fails validation."""
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class ExternalToolError(VidedError, RuntimeError):
|
|
17
|
+
"""Raised when an external media tool is missing or fails."""
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class OptionalDependencyError(VidedError, RuntimeError):
|
|
21
|
+
"""Raised when an optional dependency needed for a feature is missing."""
|
vided/ffmpeg.py
ADDED
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import shutil
|
|
5
|
+
import subprocess
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import Any, Literal, overload
|
|
9
|
+
|
|
10
|
+
from .errors import ExternalToolError
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class ToolError(ExternalToolError):
|
|
14
|
+
"""Raised when an external media tool fails."""
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@dataclass(frozen=True)
|
|
18
|
+
class VideoInfo:
|
|
19
|
+
path: Path
|
|
20
|
+
width: int
|
|
21
|
+
height: int
|
|
22
|
+
duration: float
|
|
23
|
+
fps: float | None
|
|
24
|
+
video_codec: str | None
|
|
25
|
+
audio_codec: str | None
|
|
26
|
+
has_audio: bool
|
|
27
|
+
audio_sample_rate: int | None = None
|
|
28
|
+
audio_channels: int | None = None
|
|
29
|
+
|
|
30
|
+
def as_dict(self) -> dict[str, Any]:
|
|
31
|
+
return {
|
|
32
|
+
"path": str(self.path),
|
|
33
|
+
"width": self.width,
|
|
34
|
+
"height": self.height,
|
|
35
|
+
"duration": self.duration,
|
|
36
|
+
"fps": self.fps,
|
|
37
|
+
"video_codec": self.video_codec,
|
|
38
|
+
"audio_codec": self.audio_codec,
|
|
39
|
+
"has_audio": self.has_audio,
|
|
40
|
+
"audio_sample_rate": self.audio_sample_rate,
|
|
41
|
+
"audio_channels": self.audio_channels,
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def ensure_tool(name: str) -> str:
|
|
46
|
+
resolved = shutil.which(name)
|
|
47
|
+
if resolved is None:
|
|
48
|
+
raise ToolError(f"Required tool '{name}' was not found on PATH. Install it and try again.")
|
|
49
|
+
return resolved
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
@overload
|
|
53
|
+
def run_command(
|
|
54
|
+
argv: list[str],
|
|
55
|
+
*,
|
|
56
|
+
cwd: Path | None = None,
|
|
57
|
+
output: Literal["none"] = "none",
|
|
58
|
+
dry_run: bool = False,
|
|
59
|
+
) -> subprocess.CompletedProcess[str]: ...
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
@overload
|
|
63
|
+
def run_command(
|
|
64
|
+
argv: list[str],
|
|
65
|
+
*,
|
|
66
|
+
cwd: Path | None = None,
|
|
67
|
+
output: Literal["text"],
|
|
68
|
+
dry_run: bool = False,
|
|
69
|
+
) -> subprocess.CompletedProcess[str]: ...
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
@overload
|
|
73
|
+
def run_command(
|
|
74
|
+
argv: list[str],
|
|
75
|
+
*,
|
|
76
|
+
cwd: Path | None = None,
|
|
77
|
+
output: Literal["bytes"],
|
|
78
|
+
dry_run: bool = False,
|
|
79
|
+
) -> subprocess.CompletedProcess[bytes]: ...
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def run_command(
|
|
83
|
+
argv: list[str],
|
|
84
|
+
*,
|
|
85
|
+
cwd: Path | None = None,
|
|
86
|
+
output: Literal["none", "text", "bytes"] = "none",
|
|
87
|
+
dry_run: bool = False,
|
|
88
|
+
) -> subprocess.CompletedProcess[str] | subprocess.CompletedProcess[bytes]:
|
|
89
|
+
"""Run an external command with predictable output and error handling."""
|
|
90
|
+
|
|
91
|
+
printable = " ".join(argv)
|
|
92
|
+
if dry_run:
|
|
93
|
+
if output != "none":
|
|
94
|
+
raise ValueError("dry_run is only supported when output='none'")
|
|
95
|
+
print(f"[dry-run] {printable}")
|
|
96
|
+
return subprocess.CompletedProcess(argv, 0, "", "")
|
|
97
|
+
|
|
98
|
+
text = output != "bytes"
|
|
99
|
+
capture_output = output != "none"
|
|
100
|
+
try:
|
|
101
|
+
return subprocess.run(
|
|
102
|
+
argv,
|
|
103
|
+
cwd=str(cwd) if cwd else None,
|
|
104
|
+
check=True,
|
|
105
|
+
text=text,
|
|
106
|
+
stdout=subprocess.PIPE if capture_output else None,
|
|
107
|
+
stderr=subprocess.PIPE if capture_output else None,
|
|
108
|
+
)
|
|
109
|
+
except subprocess.CalledProcessError as exc:
|
|
110
|
+
stderr = _command_output_text(exc.stderr)
|
|
111
|
+
stdout = _command_output_text(exc.stdout)
|
|
112
|
+
details = "\n".join(part for part in [stdout, stderr] if part.strip())
|
|
113
|
+
raise ToolError(f"Command failed: {printable}\n{details}".rstrip()) from exc
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _command_output_text(value: str | bytes | None) -> str:
|
|
117
|
+
if value is None:
|
|
118
|
+
return ""
|
|
119
|
+
if isinstance(value, bytes):
|
|
120
|
+
return value.decode(errors="replace")
|
|
121
|
+
return value
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def _parse_fraction(value: str | None) -> float | None:
|
|
125
|
+
if not value or value == "0/0":
|
|
126
|
+
return None
|
|
127
|
+
if "/" in value:
|
|
128
|
+
left, right = value.split("/", 1)
|
|
129
|
+
try:
|
|
130
|
+
denominator = float(right)
|
|
131
|
+
if denominator == 0:
|
|
132
|
+
return None
|
|
133
|
+
return float(left) / denominator
|
|
134
|
+
except ValueError:
|
|
135
|
+
return None
|
|
136
|
+
try:
|
|
137
|
+
return float(value)
|
|
138
|
+
except ValueError:
|
|
139
|
+
return None
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def probe_media(path: Path) -> VideoInfo:
|
|
143
|
+
"""Return the basic media info this project needs."""
|
|
144
|
+
|
|
145
|
+
ensure_tool("ffprobe")
|
|
146
|
+
result = run_command(
|
|
147
|
+
[
|
|
148
|
+
"ffprobe",
|
|
149
|
+
"-v",
|
|
150
|
+
"error",
|
|
151
|
+
"-print_format",
|
|
152
|
+
"json",
|
|
153
|
+
"-show_format",
|
|
154
|
+
"-show_streams",
|
|
155
|
+
str(path),
|
|
156
|
+
],
|
|
157
|
+
output="text",
|
|
158
|
+
)
|
|
159
|
+
data = json.loads(result.stdout)
|
|
160
|
+
streams = data.get("streams", [])
|
|
161
|
+
video = next((s for s in streams if s.get("codec_type") == "video"), None)
|
|
162
|
+
if video is None:
|
|
163
|
+
raise ToolError(f"No video stream found in {path}")
|
|
164
|
+
|
|
165
|
+
audio = next((s for s in streams if s.get("codec_type") == "audio"), None)
|
|
166
|
+
fmt = data.get("format", {})
|
|
167
|
+
|
|
168
|
+
duration_raw = video.get("duration") or fmt.get("duration") or 0
|
|
169
|
+
try:
|
|
170
|
+
duration = float(duration_raw)
|
|
171
|
+
except (TypeError, ValueError):
|
|
172
|
+
duration = 0.0
|
|
173
|
+
|
|
174
|
+
width = int(video.get("width") or 0)
|
|
175
|
+
height = int(video.get("height") or 0)
|
|
176
|
+
|
|
177
|
+
# Some mobile videos carry rotation metadata. This skeleton records encoded dimensions;
|
|
178
|
+
# the README notes that rotation normalization is a v1 limitation.
|
|
179
|
+
fps = _parse_fraction(video.get("avg_frame_rate")) or _parse_fraction(video.get("r_frame_rate"))
|
|
180
|
+
|
|
181
|
+
return VideoInfo(
|
|
182
|
+
path=path,
|
|
183
|
+
width=width,
|
|
184
|
+
height=height,
|
|
185
|
+
duration=duration,
|
|
186
|
+
fps=fps,
|
|
187
|
+
video_codec=video.get("codec_name"),
|
|
188
|
+
audio_codec=audio.get("codec_name") if audio else None,
|
|
189
|
+
has_audio=audio is not None,
|
|
190
|
+
audio_sample_rate=int(audio["sample_rate"]) if audio and audio.get("sample_rate") else None,
|
|
191
|
+
audio_channels=int(audio["channels"]) if audio and audio.get("channels") else None,
|
|
192
|
+
)
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def seconds(value: float | int | str) -> str:
|
|
196
|
+
"""Format seconds for ffmpeg-ish command arguments."""
|
|
197
|
+
|
|
198
|
+
if isinstance(value, str):
|
|
199
|
+
return value
|
|
200
|
+
return f"{float(value):.6f}s"
|
vided/filtergraph.py
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import re
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
|
|
6
|
+
from .redactions import Redaction
|
|
7
|
+
|
|
8
|
+
_COLOR_RE = re.compile(r"^[A-Za-z0-9#@._-]+$")
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def _expr_between(start: float, end: float) -> str:
|
|
12
|
+
# Commas inside expressions must be escaped for ffmpeg's filtergraph parser.
|
|
13
|
+
return f"between(t\\,{start:.6f}\\,{end:.6f})"
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _if_between_x(start: float, end: float, x: int) -> str:
|
|
17
|
+
return f"if({_expr_between(start, end)}\\,{x}\\,NAN)"
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _clean_color(value: str | None, fallback: str = "black") -> str:
|
|
21
|
+
if value and _COLOR_RE.match(value):
|
|
22
|
+
return value
|
|
23
|
+
return fallback
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def build_debug_filtergraph(redactions: list[Redaction]) -> str:
|
|
27
|
+
"""Build a visible-box preview filtergraph."""
|
|
28
|
+
|
|
29
|
+
if not redactions:
|
|
30
|
+
return "[0:v]setpts=PTS-STARTPTS[vout]"
|
|
31
|
+
|
|
32
|
+
parts: list[str] = ["[0:v]setpts=PTS-STARTPTS[v0]"]
|
|
33
|
+
current = "v0"
|
|
34
|
+
for idx, r in enumerate(redactions, start=1):
|
|
35
|
+
out = "vout" if idx == len(redactions) else f"v{idx}"
|
|
36
|
+
enable = _expr_between(r.start, r.end)
|
|
37
|
+
# Fill with a translucent box and draw an opaque border. This is easier to see than a border only.
|
|
38
|
+
parts.append(
|
|
39
|
+
f"[{current}]drawbox=x={r.rect.x}:y={r.rect.y}:w={r.rect.w}:h={r.rect.h}:"
|
|
40
|
+
f"color=red@0.28:t=fill:enable='{enable}',"
|
|
41
|
+
f"drawbox=x={r.rect.x}:y={r.rect.y}:w={r.rect.w}:h={r.rect.h}:"
|
|
42
|
+
f"color=red:t=3:enable='{enable}'[{out}]"
|
|
43
|
+
)
|
|
44
|
+
current = out
|
|
45
|
+
return ";\n".join(parts)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def build_final_filtergraph(redactions: list[Redaction]) -> str:
|
|
49
|
+
"""Build the final blur/solid redaction filtergraph."""
|
|
50
|
+
|
|
51
|
+
if not redactions:
|
|
52
|
+
return "[0:v]setpts=PTS-STARTPTS[vout]"
|
|
53
|
+
|
|
54
|
+
solid = [r for r in redactions if r.style.get("type") == "solid"]
|
|
55
|
+
blur = [r for r in redactions if r.style.get("type", "blur") != "solid"]
|
|
56
|
+
|
|
57
|
+
parts: list[str] = []
|
|
58
|
+
base_label = "base0"
|
|
59
|
+
parts.append(f"[0:v]setpts=PTS-STARTPTS[{base_label}]")
|
|
60
|
+
|
|
61
|
+
for idx, r in enumerate(solid, start=1):
|
|
62
|
+
out = f"base{idx}"
|
|
63
|
+
color = _clean_color(str(r.style.get("color", "black")))
|
|
64
|
+
enable = _expr_between(r.start, r.end)
|
|
65
|
+
parts.append(
|
|
66
|
+
f"[{base_label}]drawbox=x={r.rect.x}:y={r.rect.y}:w={r.rect.w}:h={r.rect.h}:"
|
|
67
|
+
f"color={color}:t=fill:enable='{enable}'[{out}]"
|
|
68
|
+
)
|
|
69
|
+
base_label = out
|
|
70
|
+
|
|
71
|
+
if not blur:
|
|
72
|
+
# Relabel the last base as vout. ffmpeg's null filter is a simple way to do that.
|
|
73
|
+
parts.append(f"[{base_label}]null[vout]")
|
|
74
|
+
return ";\n".join(parts)
|
|
75
|
+
|
|
76
|
+
split_labels = "".join(f"[r{idx}src]" for idx in range(len(blur)))
|
|
77
|
+
parts.append(f"[{base_label}]split={len(blur) + 1}[base]{split_labels}")
|
|
78
|
+
|
|
79
|
+
for idx, r in enumerate(blur):
|
|
80
|
+
requested_radius = int(r.style.get("luma_radius", 18))
|
|
81
|
+
power = int(r.style.get("luma_power", 3))
|
|
82
|
+
# Keep radii legal for cropped yuv420p streams. Chroma planes are usually smaller
|
|
83
|
+
# than luma planes, so explicitly set a smaller chroma radius instead of letting
|
|
84
|
+
# ffmpeg copy the luma radius into chroma_radius.
|
|
85
|
+
min_side = max(1, min(r.rect.w, r.rect.h))
|
|
86
|
+
luma_radius = max(1, min(requested_radius, max(1, min_side // 2)))
|
|
87
|
+
chroma_radius = max(1, min(requested_radius, max(1, min_side // 4)))
|
|
88
|
+
parts.append(
|
|
89
|
+
f"[r{idx}src]crop=w={r.rect.w}:h={r.rect.h}:x={r.rect.x}:y={r.rect.y},"
|
|
90
|
+
f"boxblur=luma_radius={luma_radius}:luma_power={power}:"
|
|
91
|
+
f"chroma_radius={chroma_radius}:chroma_power={power}[r{idx}]"
|
|
92
|
+
)
|
|
93
|
+
|
|
94
|
+
current = "base"
|
|
95
|
+
for idx, r in enumerate(blur):
|
|
96
|
+
out = "vout" if idx == len(blur) - 1 else f"vblur{idx}"
|
|
97
|
+
x_expr = _if_between_x(r.start, r.end, r.rect.x)
|
|
98
|
+
parts.append(f"[{current}][r{idx}]overlay=x='{x_expr}':y={r.rect.y}:eof_action=pass[{out}]")
|
|
99
|
+
current = out
|
|
100
|
+
|
|
101
|
+
return ";\n".join(parts)
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def write_filtergraph(path: Path, graph: str) -> Path:
|
|
105
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
106
|
+
path.write_text(graph + "\n", encoding="utf-8")
|
|
107
|
+
return path
|
vided/frames.py
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import shutil
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
from .ffmpeg import ensure_tool, probe_media, run_command
|
|
8
|
+
from .project import load_project, project_paths, save_project, write_json
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def generate_frames(
|
|
12
|
+
project_root: Path,
|
|
13
|
+
*,
|
|
14
|
+
interval_seconds: float | None = None,
|
|
15
|
+
thumbnail_width: int | None = None,
|
|
16
|
+
overwrite: bool = False,
|
|
17
|
+
dry_run: bool = False,
|
|
18
|
+
) -> Path:
|
|
19
|
+
ensure_tool("ffmpeg")
|
|
20
|
+
cfg = load_project(project_root)
|
|
21
|
+
p = project_paths(project_root, config=cfg)
|
|
22
|
+
trimmed = p.trimmed
|
|
23
|
+
if not trimmed.exists():
|
|
24
|
+
raise FileNotFoundError(f"Trimmed video not found: {trimmed}. Run `vided trim` first.")
|
|
25
|
+
|
|
26
|
+
frame_cfg: dict[str, Any] = cfg.get("frames", {})
|
|
27
|
+
interval_seconds = float(interval_seconds or frame_cfg.get("interval_seconds", 1.0))
|
|
28
|
+
thumbnail_width = int(thumbnail_width or frame_cfg.get("thumbnail_width", 640))
|
|
29
|
+
if interval_seconds <= 0:
|
|
30
|
+
raise ValueError("interval_seconds must be greater than 0")
|
|
31
|
+
if thumbnail_width <= 0:
|
|
32
|
+
raise ValueError("thumbnail_width must be greater than 0")
|
|
33
|
+
|
|
34
|
+
if p.frames_dir.exists() and overwrite and not dry_run:
|
|
35
|
+
shutil.rmtree(p.frames_dir)
|
|
36
|
+
if not dry_run:
|
|
37
|
+
p.frames_dir.mkdir(parents=True, exist_ok=True)
|
|
38
|
+
|
|
39
|
+
existing = list(p.frames_dir.glob("frame_*.jpg")) if p.frames_dir.exists() else []
|
|
40
|
+
if existing and not overwrite and not dry_run:
|
|
41
|
+
raise FileExistsError(
|
|
42
|
+
f"Frames already exist in {p.frames_dir}. Use --overwrite to regenerate them."
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
fps = 1.0 / interval_seconds
|
|
46
|
+
frame_pattern = p.frames_dir / "frame_%06d.jpg"
|
|
47
|
+
vf = f"fps={fps:.8f},scale={thumbnail_width}:-2"
|
|
48
|
+
cmd = [
|
|
49
|
+
"ffmpeg",
|
|
50
|
+
"-hide_banner",
|
|
51
|
+
"-y" if overwrite else "-n",
|
|
52
|
+
"-i",
|
|
53
|
+
str(trimmed),
|
|
54
|
+
"-vf",
|
|
55
|
+
vf,
|
|
56
|
+
"-q:v",
|
|
57
|
+
"2",
|
|
58
|
+
str(frame_pattern),
|
|
59
|
+
]
|
|
60
|
+
run_command(cmd, dry_run=dry_run)
|
|
61
|
+
|
|
62
|
+
if dry_run:
|
|
63
|
+
return p.frames_json
|
|
64
|
+
|
|
65
|
+
info = probe_media(trimmed)
|
|
66
|
+
frames = []
|
|
67
|
+
for idx, file in enumerate(sorted(p.frames_dir.glob("frame_*.jpg"))):
|
|
68
|
+
t = min(idx * interval_seconds, max(info.duration, 0.0))
|
|
69
|
+
frames.append(
|
|
70
|
+
{
|
|
71
|
+
"index": idx,
|
|
72
|
+
"time": round(t, 6),
|
|
73
|
+
"image": f"frames/{file.name}",
|
|
74
|
+
}
|
|
75
|
+
)
|
|
76
|
+
|
|
77
|
+
frames_json = {
|
|
78
|
+
"schema_version": 1,
|
|
79
|
+
"video": {
|
|
80
|
+
"path": str(trimmed),
|
|
81
|
+
"width": info.width,
|
|
82
|
+
"height": info.height,
|
|
83
|
+
"duration": info.duration,
|
|
84
|
+
},
|
|
85
|
+
"interval_seconds": interval_seconds,
|
|
86
|
+
"thumbnail_width": thumbnail_width,
|
|
87
|
+
"frames": frames,
|
|
88
|
+
}
|
|
89
|
+
write_json(p.frames_json, frames_json)
|
|
90
|
+
|
|
91
|
+
cfg.setdefault("frames", {})
|
|
92
|
+
cfg["frames"].update(
|
|
93
|
+
{
|
|
94
|
+
"interval_seconds": interval_seconds,
|
|
95
|
+
"thumbnail_width": thumbnail_width,
|
|
96
|
+
"last_generated_count": len(frames),
|
|
97
|
+
}
|
|
98
|
+
)
|
|
99
|
+
cfg["trimmed_video"] = info.as_dict()
|
|
100
|
+
save_project(project_root, cfg)
|
|
101
|
+
return p.frames_json
|
vided/project.py
ADDED
|
@@ -0,0 +1,238 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import shutil
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from datetime import datetime, timezone
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import Any, Mapping
|
|
9
|
+
|
|
10
|
+
from .ffmpeg import VideoInfo, probe_media
|
|
11
|
+
|
|
12
|
+
PROJECT_FILE = "project.json"
|
|
13
|
+
REDACTIONS_FILE = "redactions.json"
|
|
14
|
+
FRAMES_FILE = "work/frames/frames.json"
|
|
15
|
+
_MISSING = object()
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass(frozen=True)
|
|
19
|
+
class ProjectPaths:
|
|
20
|
+
root: Path
|
|
21
|
+
input_dir: Path
|
|
22
|
+
work_dir: Path
|
|
23
|
+
frames_dir: Path
|
|
24
|
+
output_dir: Path
|
|
25
|
+
original: Path
|
|
26
|
+
trimmed: Path
|
|
27
|
+
project_json: Path
|
|
28
|
+
redactions_json: Path
|
|
29
|
+
frames_json: Path
|
|
30
|
+
filtergraph: Path
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def project_paths(
|
|
34
|
+
project_root: Path,
|
|
35
|
+
*,
|
|
36
|
+
config: Mapping[str, Any] | None = None,
|
|
37
|
+
) -> ProjectPaths:
|
|
38
|
+
project_root = project_root.resolve()
|
|
39
|
+
input_dir = project_root / "input"
|
|
40
|
+
work_dir = project_root / "work"
|
|
41
|
+
frames_dir = work_dir / "frames"
|
|
42
|
+
output_dir = project_root / "output"
|
|
43
|
+
if config is None:
|
|
44
|
+
config = _read_project_config_for_paths(project_root)
|
|
45
|
+
original = project_root / str(config.get("original_path", "input/original.mp4"))
|
|
46
|
+
trimmed = project_root / str(config.get("trimmed_path", "work/trimmed.mp4"))
|
|
47
|
+
return ProjectPaths(
|
|
48
|
+
root=project_root,
|
|
49
|
+
input_dir=input_dir,
|
|
50
|
+
work_dir=work_dir,
|
|
51
|
+
frames_dir=frames_dir,
|
|
52
|
+
output_dir=output_dir,
|
|
53
|
+
original=original,
|
|
54
|
+
trimmed=trimmed,
|
|
55
|
+
project_json=project_root / PROJECT_FILE,
|
|
56
|
+
redactions_json=project_root / REDACTIONS_FILE,
|
|
57
|
+
frames_json=project_root / FRAMES_FILE,
|
|
58
|
+
filtergraph=work_dir / "filtergraph.txt",
|
|
59
|
+
)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def paths(root: Path) -> ProjectPaths:
|
|
63
|
+
return project_paths(root)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _read_project_config_for_paths(project_root: Path) -> dict[str, Any]:
|
|
67
|
+
path = project_root / PROJECT_FILE
|
|
68
|
+
if not path.exists():
|
|
69
|
+
return {}
|
|
70
|
+
try:
|
|
71
|
+
data = json.loads(path.read_text(encoding="utf-8"))
|
|
72
|
+
except (OSError, json.JSONDecodeError):
|
|
73
|
+
return {}
|
|
74
|
+
return data if isinstance(data, dict) else {}
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def ensure_project_dirs(p: ProjectPaths) -> None:
|
|
78
|
+
p.input_dir.mkdir(parents=True, exist_ok=True)
|
|
79
|
+
p.work_dir.mkdir(parents=True, exist_ok=True)
|
|
80
|
+
p.frames_dir.mkdir(parents=True, exist_ok=True)
|
|
81
|
+
p.output_dir.mkdir(parents=True, exist_ok=True)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def read_json(path: Path, default: Any = _MISSING) -> Any:
|
|
85
|
+
if not path.exists():
|
|
86
|
+
if default is not _MISSING:
|
|
87
|
+
return default
|
|
88
|
+
raise FileNotFoundError(path)
|
|
89
|
+
return json.loads(path.read_text(encoding="utf-8"))
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def write_json(path: Path, data: Any) -> None:
|
|
93
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
94
|
+
path.write_text(json.dumps(data, indent=2, sort_keys=False) + "\n", encoding="utf-8")
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def load_project(project_root: Path) -> dict[str, Any]:
|
|
98
|
+
p = project_paths(project_root)
|
|
99
|
+
return read_json(p.project_json)
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def save_project(project_root: Path, data: dict[str, Any]) -> None:
|
|
103
|
+
p = project_paths(project_root, config=data)
|
|
104
|
+
write_json(p.project_json, data)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def create_project(
|
|
108
|
+
source: Path,
|
|
109
|
+
project_root: Path,
|
|
110
|
+
*,
|
|
111
|
+
frame_interval: float = 1.0,
|
|
112
|
+
copy_input: bool = True,
|
|
113
|
+
overwrite: bool = False,
|
|
114
|
+
) -> dict[str, Any]:
|
|
115
|
+
source = source.expanduser().resolve()
|
|
116
|
+
project_root = project_root.expanduser().resolve()
|
|
117
|
+
if not source.exists():
|
|
118
|
+
raise FileNotFoundError(source)
|
|
119
|
+
if project_root.exists() and any(project_root.iterdir()) and not overwrite:
|
|
120
|
+
raise FileExistsError(
|
|
121
|
+
f"Project folder already exists and is not empty: {project_root}. "
|
|
122
|
+
"Use --overwrite to reuse it."
|
|
123
|
+
)
|
|
124
|
+
|
|
125
|
+
p = project_paths(project_root)
|
|
126
|
+
ensure_project_dirs(p)
|
|
127
|
+
|
|
128
|
+
original_ext = source.suffix.lower() or ".mp4"
|
|
129
|
+
original_path = p.input_dir / f"original{original_ext}"
|
|
130
|
+
if copy_input:
|
|
131
|
+
shutil.copy2(source, original_path)
|
|
132
|
+
else:
|
|
133
|
+
if original_path.exists() or original_path.is_symlink():
|
|
134
|
+
original_path.unlink()
|
|
135
|
+
original_path.symlink_to(source)
|
|
136
|
+
|
|
137
|
+
src_info = probe_media(original_path)
|
|
138
|
+
config = default_project_config(
|
|
139
|
+
original_path=original_path,
|
|
140
|
+
source_path=source,
|
|
141
|
+
source_info=src_info,
|
|
142
|
+
frame_interval=frame_interval,
|
|
143
|
+
)
|
|
144
|
+
write_json(p.project_json, config)
|
|
145
|
+
write_json(
|
|
146
|
+
p.redactions_json,
|
|
147
|
+
default_redactions(
|
|
148
|
+
src_info,
|
|
149
|
+
trimmed_path=project_paths(project_root, config=config).trimmed,
|
|
150
|
+
),
|
|
151
|
+
)
|
|
152
|
+
return config
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def default_project_config(
|
|
156
|
+
*,
|
|
157
|
+
original_path: Path,
|
|
158
|
+
source_path: Path,
|
|
159
|
+
source_info: VideoInfo,
|
|
160
|
+
frame_interval: float,
|
|
161
|
+
) -> dict[str, Any]:
|
|
162
|
+
return {
|
|
163
|
+
"schema_version": 1,
|
|
164
|
+
"created_at": datetime.now(timezone.utc).isoformat(),
|
|
165
|
+
"source_path": str(source_path),
|
|
166
|
+
"original_path": str(original_path.relative_to(original_path.parents[1])),
|
|
167
|
+
"trimmed_path": "work/trimmed.mp4",
|
|
168
|
+
"video": source_info.as_dict(),
|
|
169
|
+
"trim": {
|
|
170
|
+
"detector": "audio",
|
|
171
|
+
"mode": "hybrid",
|
|
172
|
+
"margin": "0.2s",
|
|
173
|
+
"smooth": "0.2s,0.1s",
|
|
174
|
+
"audio_threshold": 0.04,
|
|
175
|
+
"long_silence_min_seconds": 1.5,
|
|
176
|
+
"silent_speed": 8.0,
|
|
177
|
+
"mute_silent_audio": True,
|
|
178
|
+
"silent_volume": 0.0,
|
|
179
|
+
"speed_indicator": {
|
|
180
|
+
"enabled": False,
|
|
181
|
+
"corner": "top-right",
|
|
182
|
+
"style": "dark",
|
|
183
|
+
"min_display_seconds": 1.0,
|
|
184
|
+
},
|
|
185
|
+
"vad": {
|
|
186
|
+
"threshold": 0.5,
|
|
187
|
+
"min_speech_duration_ms": 250,
|
|
188
|
+
"min_silence_duration_ms": 300,
|
|
189
|
+
"speech_pad_ms": 150,
|
|
190
|
+
"merge_speech_gap_seconds": 0.25,
|
|
191
|
+
"manual_keep_ranges": [],
|
|
192
|
+
},
|
|
193
|
+
},
|
|
194
|
+
"frames": {
|
|
195
|
+
"interval_seconds": frame_interval,
|
|
196
|
+
"thumbnail_width": 640,
|
|
197
|
+
},
|
|
198
|
+
"render": {
|
|
199
|
+
"video_codec": "libx264",
|
|
200
|
+
"crf": 16,
|
|
201
|
+
"preset": "medium",
|
|
202
|
+
"pixel_format": "yuv420p",
|
|
203
|
+
"audio_codec": "copy",
|
|
204
|
+
},
|
|
205
|
+
"redaction_defaults": {
|
|
206
|
+
"buffer_pre_seconds": 0.5,
|
|
207
|
+
"buffer_post_seconds": 0.5,
|
|
208
|
+
"style": {
|
|
209
|
+
"type": "blur",
|
|
210
|
+
"filter": "boxblur",
|
|
211
|
+
"luma_radius": 18,
|
|
212
|
+
"luma_power": 3,
|
|
213
|
+
},
|
|
214
|
+
},
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def default_redactions(info: VideoInfo, *, trimmed_path: Path) -> dict[str, Any]:
|
|
219
|
+
return {
|
|
220
|
+
"schema_version": 1,
|
|
221
|
+
"video": {
|
|
222
|
+
"path": str(trimmed_path),
|
|
223
|
+
"width": info.width,
|
|
224
|
+
"height": info.height,
|
|
225
|
+
"duration": info.duration,
|
|
226
|
+
},
|
|
227
|
+
"defaults": {
|
|
228
|
+
"buffer_pre_seconds": 0.5,
|
|
229
|
+
"buffer_post_seconds": 0.5,
|
|
230
|
+
"style": {
|
|
231
|
+
"type": "blur",
|
|
232
|
+
"filter": "boxblur",
|
|
233
|
+
"luma_radius": 18,
|
|
234
|
+
"luma_power": 3,
|
|
235
|
+
},
|
|
236
|
+
},
|
|
237
|
+
"redactions": [],
|
|
238
|
+
}
|