diff --git a/README.md b/README.md index c9ca1da3..fdfa4cf0 100644 --- a/README.md +++ b/README.md @@ -173,6 +173,8 @@ Tell me which tools are missing and help me install them here. Reopen the terminal and agent after installation so they can find the new tools. On Windows, verify Python with `python --version` or `py -3 --version`. Watch supports the **latest yt-dlp release** only, because sites routinely break older ones; it uses the executable available in the active environment. +**TikTok photo slideshows (optional):** put [`gallery-dl`](https://github.com/mikf/gallery-dl) on PATH (`brew install gallery-dl` or `pipx install gallery-dl`). The local engine uses it only when yt-dlp returns no video, and reports each slide as a frame. + ## Chat, Cowork, and browser apps **Watch works in Claude Code:** a **Code** session in [Claude Desktop](#claude-desktop--code), or Claude Code installed with the plugin commands in [VS Code](#claude-code-in-vs-code) or [a terminal](#claude-code-in-a-terminal). Codex and other [local agents](#other-local-agents) work too. diff --git a/skills/watch/SKILL.md b/skills/watch/SKILL.md index 5affb5f9..3796235a 100644 --- a/skills/watch/SKILL.md +++ b/skills/watch/SKILL.md @@ -151,7 +151,7 @@ If a small-model transcript is nonsense, suggest the actual spoken-language hint Cloud fallbacks extract mono 16 kHz MP3 and upload within a conservative 24,000,000-byte file budget. Large files are chunked with source-time offsets restored; missing chunks appear in the final report. Provider errors do not justify automatic provider switching. -For download failures, use the bounded original error and its diagnostic hint. A 403 has no generic fix, but first update yt-dlp with its owning package manager (e.g. `brew upgrade yt-dlp`, `pipx upgrade yt-dlp`) and retry once. Do not hardcode alternate clients, cycle cookies, or disable TLS verification. Preserve available captions when media/probing fails. For hosted environments, local uploads solve downloading only; cloud ASR and cold local-model setup still need permitted network access. +For download failures, use the bounded original error and its diagnostic hint. A 403 has no generic fix, but first update yt-dlp with its owning package manager (e.g. `brew upgrade yt-dlp`, `pipx upgrade yt-dlp`) and retry once. Do not hardcode alternate clients, cycle cookies, or disable TLS verification. Preserve available captions when media/probing fails. For an image slideshow (TikTok photo post), the local engine falls back to `gallery-dl` when it is on PATH; the report lists frames as `slide N` with no timeline, so Read every slide and treat the caption (Title) plus on-slide text as the content. For hosted environments, local uploads solve downloading only; cloud ASR and cold local-model setup still need permitted network access. For follow-ups, reuse evidence already viewed before rerunning. Remove only the disposable **Work dir** created by this invocation when no longer needed. Never delete the parent supplied with `--out-dir`, a user source file, the local venv, or model caches as routine cleanup. diff --git a/skills/watch/scripts/download.py b/skills/watch/scripts/download.py index fc8d0ff8..60025495 100755 --- a/skills/watch/scripts/download.py +++ b/skills/watch/scripts/download.py @@ -4,6 +4,7 @@ import json import re +import shutil import sys import tempfile from pathlib import Path @@ -12,6 +13,8 @@ from runtime import configure_stdio, diagnostic, run_text VIDEO_EXTS = {'.mp4', '.mkv', '.webm', '.mov', '.m4v', '.avi', '.flv', '.wmv'} +AUDIO_EXTS = {'.m4a', '.mp3', '.opus', '.aac'} +IMAGE_EXTS = {'.jpg', '.jpeg', '.png', '.webp'} def is_url(source: str) -> bool: @@ -162,6 +165,43 @@ def fetch_captions(url: str, out_dir: Path, *, sub_lang='auto', cookies_file=Non return result +def download_gallery(url: str, out_dir: Path) -> dict | None: + """Optional gallery-dl fallback for posts yt-dlp can't turn into a video. + + Returns slide images + soundtrack for image posts, or the video file when + gallery-dl fetched one yt-dlp couldn't. None when gallery-dl is not on PATH + or produced nothing usable. + """ + if shutil.which('gallery-dl') is None: + print('[watch] yt-dlp returned no video; install gallery-dl to handle image slideshows', file=sys.stderr) + return None + print('[watch] yt-dlp returned no video, trying gallery-dl…', file=sys.stderr) + result = run_text(['gallery-dl', '-D', str(out_dir), '-f', '{num:>03}.{extension}', + '-o', 'tiktok.audio=true', '--write-info-json', '--', url]) + if result.returncode != 0: + print(f'[watch] gallery-dl failed (exit {result.returncode}): {diagnostic(result.stderr)}', file=sys.stderr) + files = sorted(out_dir.glob('[0-9][0-9][0-9].*')) + images = [p for p in files if p.suffix.lower() in IMAGE_EXTS] + videos = [p for p in files if p.suffix.lower() in VIDEO_EXTS] + audio = [p for p in files if p.suffix.lower() in AUDIO_EXTS] + if not images and not videos: + return None + info = {'url': url} + try: + raw = json.loads((out_dir / 'info.json').read_text(encoding='utf-8')) + author = raw.get('author') if isinstance(raw.get('author'), dict) else {} + info.update({'title': raw.get('desc') or raw.get('description'), + 'uploader': author.get('uniqueId') or author.get('nickname')}) + except FileNotFoundError: + pass + except (OSError, ValueError, AttributeError) as exc: + print(f'[watch] gallery-dl info.json unreadable: {type(exc).__name__}', file=sys.stderr) + media = videos or audio + return {'video_path': str(media[0].resolve()) if media else None, + 'image_paths': None if videos else [str(p.resolve()) for p in images], + 'info': info, 'downloaded': True} + + def download_url(url: str, out_dir: Path, audio_only: bool = False, *, context=None, cookies_file=None, cookies_from_browser=None) -> dict: auth = auth_args(cookies_file, cookies_from_browser) @@ -177,6 +217,26 @@ def download_url(url: str, out_dir: Path, audio_only: bool = False, *, context=N cmd += ['--load-info-json', context['info_path']] else: cmd += ['--', url] + try: + video = _completed_media(cmd, record, run) + except SystemExit as exc: + video, failure = None, exc + # TikTok photo slideshows: yt-dlp rejects /photo/ URLs and returns only the + # soundtrack for /video/ ones, so ask gallery-dl for the slides. + if video is None or (not audio_only and video.suffix.lower() in AUDIO_EXTS): + gallery = download_gallery(url, run / 'gallery') + if gallery: + info = {**(context.get('info') or {}), **{k: v for k, v in gallery['info'].items() if v}} + return {**context, **gallery, 'subtitle_path': context.get('subtitle_path'), + 'info': info, 'run_dir': str(run)} + if video is None: + raise failure + info = context.get('info') or _summary(_read_metadata(run / 'video.info.json'), url) + return {**context, 'video_path': str(video), 'subtitle_path': context.get('subtitle_path'), + 'info': info, 'downloaded': True, 'run_dir': str(run)} + + +def _completed_media(cmd: list[str], record: Path, run: Path) -> Path: _run(cmd) try: lines = record.read_text(encoding='utf-8').splitlines() @@ -191,9 +251,7 @@ def download_url(url: str, out_dir: Path, audio_only: bool = False, *, context=N raise ValueError() except (OSError, ValueError, TypeError): raise SystemExit('yt-dlp did not report one completed, nonempty media file inside this run directory.') from None - info = context.get('info') or _summary(_read_metadata(run / 'video.info.json'), url) - return {**context, 'video_path': str(video), 'subtitle_path': context.get('subtitle_path'), - 'info': info, 'downloaded': True, 'run_dir': str(run)} + return video def download(source: str, out_dir: Path, audio_only: bool = False, **kwargs) -> dict: diff --git a/skills/watch/scripts/frames.py b/skills/watch/scripts/frames.py index d8194e74..f44928d1 100755 --- a/skills/watch/scripts/frames.py +++ b/skills/watch/scripts/frames.py @@ -315,6 +315,53 @@ def parse_timestamps(value: str | None) -> list[float]: return sorted(set(out)) +def extract_slides( + image_paths: list[str], + out_dir: Path, + resolution: int = 512, + max_frames: int | None = 100, +) -> tuple[list[dict], dict]: + """Scale image-post slides (e.g. a TikTok photo slideshow) into frame JPEGs. + + Slides have no timeline and are not deduped: each one is content the post + shows on purpose, so they are kept in post order up to the cap. + """ + if shutil.which("ffmpeg") is None: + raise SystemExit("ffmpeg is not installed. Install with: brew install ffmpeg") + + out_dir.mkdir(parents=True, exist_ok=True) + for existing in out_dir.glob("frame_*.jpg"): + existing.unlink() + + selected = image_paths if max_frames is None else image_paths[:max_frames] + out: list[dict] = [] + for i, src in enumerate(selected): + dest = out_dir / f"frame_{i + 1:04d}.jpg" + result = run_text([ + "ffmpeg", "-hide_banner", "-loglevel", "error", "-y", + "-i", str(Path(src).resolve()), + "-vf", _scale_filter(resolution), + "-q:v", "4", + str(dest), + ]) + if result.returncode != 0: + raise SystemExit(f"ffmpeg slide conversion failed on {src}: {diagnostic(result.stderr)}") + out.append({ + "index": i, + "timestamp_seconds": 0.0, + "path": str(dest), + "reason": "slide", + "slide": i + 1, + }) + meta = { + "engine": "slides", + "candidate_count": len(image_paths), + "selected_count": len(out), + "fallback": False, + } + return out, meta + + def merge_frames(primary: list[dict], pinned: list[dict]) -> list[dict]: """Combine two frame lists into one chronological list and reindex 0..n-1. diff --git a/skills/watch/scripts/watch.py b/skills/watch/scripts/watch.py index b5b322aa..e4a50fc1 100755 --- a/skills/watch/scripts/watch.py +++ b/skills/watch/scripts/watch.py @@ -20,7 +20,7 @@ from config import ConfigError, frame_cap, get_config, load_gemini_key, resolve_engine # noqa: E402 import gemini # noqa: E402 from download import download, fetch_captions, is_url, auth_args # noqa: E402 -from frames import MAX_FPS, auto_fps, auto_fps_focus, extract_at_timestamps, extract_keyframes, extract_scene_or_uniform, format_time, get_metadata, merge_frames, parse_time, parse_timestamps, validate_controls # noqa: E402 +from frames import MAX_FPS, auto_fps, auto_fps_focus, extract_at_timestamps, extract_keyframes, extract_scene_or_uniform, extract_slides, format_time, get_metadata, merge_frames, parse_time, parse_timestamps, validate_controls # noqa: E402 from transcribe import filter_range, format_transcript, parse_vtt # noqa: E402 from whisper import load_api_key, transcribe_video # noqa: E402 from runtime import configure_stdio # noqa: E402 @@ -207,6 +207,10 @@ def main() -> int: except SystemExit as exc: visual_error = f"Media unavailable: {exc}" errors.append(visual_error) + # Image slideshow: frames come from the slides, video_path is only the soundtrack. + slides = dl.get("image_paths") or [] + if slides: + start_sec = end_sec = None # no timeline to focus on try: duration = float((dl.get("info") or {}).get("duration") or 0) @@ -241,7 +245,16 @@ def main() -> int: frame_meta = {"engine": "none", "candidate_count": 0, "selected_count": 0, "fallback": False} cue_meta = {} detail_budget = max_frames - if video_path and meta.get("has_video", bool(meta.get("width"))): + if slides: + if detail != "transcript": + print(f"[watch] image slideshow: converting {len(slides)} slides…", file=sys.stderr) + try: + frames, frame_meta = extract_slides(slides, work / "frames", resolution=args.resolution, + max_frames=max_frames) + except SystemExit as exc: + visual_error = f"Slide conversion unavailable: {exc}" + errors.append(visual_error) + elif video_path and meta.get("has_video", bool(meta.get("width"))): try: if cue_timestamps: cue_frames, cue_meta = extract_at_timestamps( @@ -321,7 +334,12 @@ def main() -> int: range_mode = "focused" if focused else "full" print(f"- **Detail:** {detail}") detail_count = frame_meta.get("selected_count", 0) - if detail != "transcript": + if detail != "transcript" and slides: + print( + f"- **Frames:** {detail_count} of {len(slides)} slides (image slideshow: no timeline, " + "the caption and on-slide text carry the content)" + ) + elif detail != "transcript": cap_label = "unlimited" if detail_budget is None else str(detail_budget) engine = frame_meta.get("engine", "scene") fallback = " fallback" if frame_meta.get("fallback") else "" @@ -385,6 +403,9 @@ def main() -> int: ) print() for frame in frames: + if "slide" in frame: + print(f"- `{frame['path']}` (slide {frame['slide']})") + continue print( f"- `{frame['path']}` " f"(t={format_time(frame['timestamp_seconds'])}, reason={frame.get('reason', 'selected')})" diff --git a/tests/test_download.py b/tests/test_download.py index 545ccbc2..80787ccb 100644 --- a/tests/test_download.py +++ b/tests/test_download.py @@ -46,7 +46,8 @@ def test_cookie_modes_and_conflict(): download.auth_args('jar', 'browser') -def _fake_stages(monkeypatch, *, fail_media=False, media_path=None): +def _fake_stages(monkeypatch, *, fail_media=False, media_path=None, gallery_files=None, gallery_info=None): + """gallery_files=None means gallery-dl is not installed.""" calls = [] def run(cmd): calls.append(cmd) @@ -66,6 +67,20 @@ def run(cmd): record.write_text(json.dumps(str(path)) + '\n') return subprocess.CompletedProcess(cmd, 0, '', '') monkeypatch.setattr(download, '_run', run) + def gallery(cmd, **kwargs): + calls.append(cmd) + out = Path(cmd[cmd.index('-D') + 1]) + out.mkdir(parents=True, exist_ok=True) + for name in gallery_files: + (out / name).write_bytes(b'x') + if gallery_info is not None: + (out / 'info.json').write_text(json.dumps(gallery_info), encoding='utf-8') + return subprocess.CompletedProcess(cmd, 0, '', '') + monkeypatch.setattr(download, 'run_text', gallery) + real_which = download.shutil.which + monkeypatch.setattr(download.shutil, 'which', + lambda name, *a, **kw: (None if gallery_files is None else '/usr/bin/gallery-dl') + if name == 'gallery-dl' else real_which(name, *a, **kw)) return calls @@ -155,3 +170,53 @@ 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' + + +# --- gallery-dl fallback (image slideshows) --------------------------------- + +TIKTOK = 'https://www.tiktok.com/@iloveeestrayyykidsss/photo/7463596003225013536' + + +def test_audio_only_ytdlp_result_falls_back_to_slides(monkeypatch, tmp_path): + # yt-dlp on a slideshow /video/ URL returns just the soundtrack. + run = tmp_path / 'run' + run.mkdir() + _fake_stages(monkeypatch, media_path=run / 'video.mp3', gallery_files=['000.mp3', '001.jpg', '002.jpg', '003.jpg'], + gallery_info={'desc': 'slide caption', 'author': {'uniqueId': 'kev'}}) + result = download.download_url(TIKTOK, tmp_path, context={'run_dir': str(run), 'info': {'title': 'TikTok #1', 'duration': 9}}) + assert [Path(p).name for p in result['image_paths']] == ['001.jpg', '002.jpg', '003.jpg'] + assert Path(result['video_path']).name == '000.mp3' + assert result['info'] == {'title': 'slide caption', 'uploader': 'kev', 'duration': 9, 'url': TIKTOK} + + +def test_unsupported_url_falls_back_to_gallery_video(monkeypatch, tmp_path): + calls = _fake_stages(monkeypatch, fail_media=True, gallery_files=['000.mp4']) + result = download.download_url(TIKTOK, tmp_path) + assert Path(result['video_path']).name == '000.mp4' + assert result['image_paths'] is None + assert calls[-1][0] == 'gallery-dl' and calls[-1][-2:] == ['--', TIKTOK] + + +def test_transcript_mode_keeps_ytdlp_audio_without_gallery(monkeypatch, tmp_path): + run = tmp_path / 'run' + run.mkdir() + calls = _fake_stages(monkeypatch, media_path=run / 'video.m4a', gallery_files=['001.jpg']) + result = download.download_url(URL, tmp_path, audio_only=True, context={'run_dir': str(run), 'info': {'title': 'clip'}}) + assert Path(result['video_path']).name == 'video.m4a' + assert not any(c[0] == 'gallery-dl' for c in calls) + + +def test_missing_gallery_dl_keeps_original_failure(monkeypatch, tmp_path): + _fake_stages(monkeypatch, fail_media=True) + with pytest.raises(SystemExit, match='network'): + download.download_url(TIKTOK, tmp_path) + + +def test_gallery_with_nothing_usable_keeps_ytdlp_audio(monkeypatch, tmp_path): + # Not a slideshow (e.g. a podcast page): gallery-dl finds nothing, audio stays. + run = tmp_path / 'run' + run.mkdir() + _fake_stages(monkeypatch, media_path=run / 'video.mp3', gallery_files=[]) + result = download.download_url(URL, tmp_path, context={'run_dir': str(run), 'info': {'title': 'pod'}}) + assert Path(result['video_path']).name == 'video.mp3' + assert 'image_paths' not in result diff --git a/tests/test_frames.py b/tests/test_frames.py index a5e8b3b1..e092f3f1 100644 --- a/tests/test_frames.py +++ b/tests/test_frames.py @@ -1,6 +1,7 @@ """Keyframe engine + preserved scene/uniform fallbacks.""" from __future__ import annotations +import subprocess from pathlib import Path import frames @@ -140,3 +141,33 @@ 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'] + + +def _slide(path: Path, color: str, size: str = "1080x1440") -> str: + subprocess.run( + ["ffmpeg", "-hide_banner", "-loglevel", "error", "-y", + "-f", "lavfi", "-i", f"color=c={color}:s={size}", "-frames:v", "1", str(path)], + check=True, + ) + return str(path) + + +def test_extract_slides_keeps_order_scales_and_caps(tmp_path: Path): + srcs = [_slide(tmp_path / f"{i:03d}.jpg", c) for i, c in enumerate(["red", "red", "blue"], 1)] + out, meta = frames.extract_slides(srcs, tmp_path / "f", resolution=512, max_frames=2) + assert meta == {"engine": "slides", "candidate_count": 3, "selected_count": 2, "fallback": False} + assert [fr["slide"] for fr in out] == [1, 2] # identical slides are NOT deduped + assert all(fr["reason"] == "slide" for fr in out) + width = subprocess.run( + ["ffprobe", "-v", "error", "-select_streams", "v:0", "-show_entries", "stream=width", + "-of", "csv=p=0", out[0]["path"]], + capture_output=True, text=True, check=True, + ).stdout.strip() + assert width == "512" + + +def test_extract_slides_uncapped(tmp_path: Path): + srcs = [_slide(tmp_path / f"{i:03d}.jpg", "green", "320x240") for i in range(1, 4)] + out, meta = frames.extract_slides(srcs, tmp_path / "f", resolution=512, max_frames=None) + assert len(out) == 3 + assert meta["selected_count"] == 3 diff --git a/tests/test_watch.py b/tests/test_watch.py index 1bc00e9d..b3f8ca4a 100644 --- a/tests/test_watch.py +++ b/tests/test_watch.py @@ -284,3 +284,44 @@ def boom(path, key, **kw): assert 'URL sent to Google' not in out and 'upload to Google failed' in out assert out_dir.is_dir() and list(out_dir.iterdir()) == [], 'the run-owned work dir must be removed' assert static_clip.is_file(), 'the user source file is never deleted' + + +TIKTOK = "https://www.tiktok.com/@iloveeestrayyykidsss/photo/7463596003225013536" + + +def _media(path: Path, *ffmpeg_args: str) -> Path: + subprocess.run(["ffmpeg", "-hide_banner", "-loglevel", "error", "-y", *ffmpeg_args, str(path)], check=True) + return path + + +def _run_slideshow(monkeypatch, capsys, dl: dict, *args: str) -> str: + monkeypatch.delenv("WATCH_DETAIL", raising=False) + monkeypatch.setattr(watch, "fetch_captions", lambda *a, **kw: {"subtitle_path": None, "info": {}}) + monkeypatch.setattr(watch, "download", lambda *a, **kw: dl) + monkeypatch.setattr(sys, "argv", ["watch", TIKTOK, "--no-whisper", "--engine", "local", *args]) + assert watch.main() == 0 + return capsys.readouterr().out + + +def test_slideshow_report_lists_every_slide(monkeypatch, capsys, tmp_path: Path): + slides = [ + str(_media(tmp_path / f"{i:03d}.jpg", "-f", "lavfi", "-i", f"color=c={c}:s=540x720", "-frames:v", "1")) + for i, c in enumerate(["red", "green", "blue"], 1) + ] + audio = _media(tmp_path / "000.m4a", "-f", "lavfi", "-t", "2", "-i", "sine=f=440", "-c:a", "aac") + dl = {"video_path": str(audio), "image_paths": slides, "subtitle_path": None, + "info": {"title": "caption text", "uploader": "kev"}, "downloaded": True} + out = _run_slideshow(monkeypatch, capsys, dl, "--detail", "balanced", "--start", "5") + assert "**Frames:** 3 of 3 slides" in out + slide_lines = [line for line in out.splitlines() if "(slide " in line] + assert len(slide_lines) == 3 and slide_lines[-1].endswith("(slide 3)") + assert "Focus range" not in out # --start is meaningless without a timeline + assert "**Title:** caption text" in out + assert "Visual status" not in out + + +def test_audio_only_download_does_not_crash_frame_engine(monkeypatch, capsys, tmp_path: Path): + audio = _media(tmp_path / "video.mp3", "-f", "lavfi", "-t", "2", "-i", "sine=f=440", "-c:a", "aac", "-f", "adts") + dl = {"video_path": str(audio), "subtitle_path": None, "info": {}, "downloaded": True} + out = _run_slideshow(monkeypatch, capsys, dl, "--detail", "balanced") + assert "_No frames extracted._" in out