Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion skills/watch/scripts/download.py
Original file line number Diff line number Diff line change
Expand Up @@ -115,8 +115,16 @@ def english_first(key): # Unknown source language: prefer English over alphabet
if keys:
key = keys[0]
# Auto mode must prefer original ASR to translated/dubbed metadata.
# With several originals (e.g. ar-orig and en-orig), take the one matching the
# metadata language, else English-first; never just the alphabetically first.
if kind == 'automatic' and language == 'auto' and originals:
key = originals[0]
preferred = [k for k in originals if matches(k)] if target else []
if preferred:
key = min(preferred, key=english_first)
elif len(originals) == 1:
key = originals[0]
elif not target:
key = min(originals, key=english_first)
base = key.removesuffix('-orig')
provenance = 'original' if original and base.split('-')[0] == original.split('-')[0] else 'unknown'
if language != 'auto' and original and base.split('-')[0] != original.split('-')[0]:
Expand Down
12 changes: 9 additions & 3 deletions skills/watch/scripts/frames.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,12 @@

MAX_FPS = 2.0
SCENE_THRESHOLD = 0.20


def _frame_pattern(out_dir: Path) -> str:
"""ffmpeg's image2 muxer treats every '%' in the path as a pattern token, so a
literal '%' in the directory (e.g. a video titled "95%") must be '%%'."""
return str(out_dir.resolve()).replace("%", "%%") + "/frame_%04d.jpg"
# Keep scene-detection results once we have at least this many distinct shots.
# Below this the video is effectively static (screen recording, talking head),
# so we fall back to uniform sampling. Matching the reference fork's behaviour,
Expand Down Expand Up @@ -218,7 +224,7 @@ def extract(
"ffmpeg", "-hide_banner", "-loglevel", "info", "-y",
"-ss", f"{start:.6f}", "-to", f"{end:.6f}", "-i", str(Path(video_path).resolve()),
"-vf", vf, *sync_args(), "-frames:v", str(max_frames), "-q:v", "4",
str(out_dir / "frame_%04d.jpg"),
_frame_pattern(out_dir),
])
if result.returncode != 0:
raise SystemExit(f"ffmpeg frame extraction failed: {diagnostic(result.stderr)}")
Expand Down Expand Up @@ -252,7 +258,7 @@ def extract_scene_candidates(
for existing in out_dir.glob("frame_*.jpg"):
existing.unlink()

output_pattern = str(out_dir / "frame_%04d.jpg")
output_pattern = _frame_pattern(out_dir)
cmd: list[str] = [
"ffmpeg",
"-hide_banner",
Expand Down Expand Up @@ -606,7 +612,7 @@ def extract_keyframes(
for existing in out_dir.glob("frame_*.jpg"):
existing.unlink()

output_pattern = str(out_dir / "frame_%04d.jpg")
output_pattern = _frame_pattern(out_dir)
cmd: list[str] = [
"ffmpeg",
"-hide_banner",
Expand Down
12 changes: 12 additions & 0 deletions tests/test_download.py
Original file line number Diff line number Diff line change
Expand Up @@ -155,3 +155,15 @@ def stages(cmd):
def test_explicit_regional_language_is_not_silently_replaced():
assert download.select_caption({'subtitles': _tracks('en-US')}, 'en-GB') is None
assert download.select_caption({'subtitles': _tracks('en-US')}, 'en')['key'] == 'en-US'


def test_multiple_originals_follow_metadata_language():
# Seen on youtu.be/yf2OwchM9nw: an en-US video whose automatic captions list both
# ar-orig and en-orig. Alphabetical order must not pick the Arabic track.
info = {'extractor_key': 'Youtube', 'language': 'en-US',
'automatic_captions': _tracks('ar', 'ar-orig', 'en', 'en-orig', 'fr')}
assert download.select_caption(info)['key'] == 'en-orig'
info['language'] = None
assert download.select_caption(info)['key'] == 'en-orig' # unknown language: English first
info['language'] = 'ar'
assert download.select_caption(info)['key'] == 'ar-orig'
16 changes: 16 additions & 0 deletions tests/test_frames.py
Original file line number Diff line number Diff line change
Expand Up @@ -140,3 +140,19 @@ def test_single_frame_cap_keeps_first_real_frame(static_clip, tmp_path):
def test_uniform_candidate_count_includes_deduplicated_frames(static_clip, tmp_path):
out, meta = frames.extract_scene_or_uniform(str(static_clip), tmp_path / 'f', fps=2, target_frames=6)
assert meta['candidate_count'] == len(out) + meta['deduped_count']


@pytest.mark.parametrize("engine", ["keyframe", "scene_or_uniform"])
@pytest.mark.parametrize("clip", ["cut_clip", "static_clip"])
def test_percent_in_output_dir_is_literal(engine, clip, tmp_path, request):
# A folder named after a video like "Get Ahead of 95% in 11 Minutes" must not be
# read as part of ffmpeg's frame_%04d.jpg sequence pattern.
out_dir = tmp_path / "Ahead of 95% in 11 Minutes" / "f"
source = str(request.getfixturevalue(clip))
if engine == "keyframe":
out, _ = frames.extract_keyframes(source, out_dir, max_frames=5)
else:
out, _ = frames.extract_scene_or_uniform(source, out_dir, fps=2.0, target_frames=5, max_frames=5)
files = sorted(out_dir.glob("frame_*.jpg"))
assert out and len(files) == len(out)
assert not (out_dir / "frame_%04d.jpg").exists()