AI agent skill that researches any topic across Reddit, X, YouTube, HN, Polymarket, and the web - then synthesizes a grounded summary
Python ai-promptsai-skillblueskyclaudeclaude-codeclawhubdeep-researchhackernewsinstagramopenclawpolymarketrecencyredditresearchsocial-mediatiktoktrendstwitterweb-searchyoutube
feat(transcribe): caption-free transcription fallback (U6)
Matt Van Horn6b12caa39efc
diff --git a/CONFIGURATION.md b/CONFIGURATION.mdindex 2031d51b..17d35005 100644--- a/CONFIGURATION.md+++ b/CONFIGURATION.md@@ -65,6 +65,7 @@ The project-scoped file is the cleanest pattern for **per-client setups**: drop| TruthSocial | `TRUTHSOCIAL_TOKEN` | TruthSocial items | yes || Web search | one of: `BRAVE_API_KEY`, `EXA_API_KEY`, `SERPER_API_KEY`, `PARALLEL_API_KEY` | `--auto-resolve` and Step 2 supplements | Brave has a free tier; native WebSearch on Claude Code / Codex / Gemini works as a fallback || Perplexity Deep Research | `OPENROUTER_API_KEY` | `--deep-research` flag (~$0.90/query) | no |+| Caption-free transcription | `GROQ_API_KEY` (free tier, preferred) or `OPENAI_API_KEY` (paid backstop); requires `ffmpeg` | Whisper transcription for audio/video without captions | Groq free tier is generous; needs ffmpeg installed || Jobs / careers pages | none for public ATS pages; web backend improves fallback discovery | `--hiring-signals` and strong Hiring Signals in standard company reports | yes || Apify (alternate scraper) | `APIFY_API_TOKEN` | fallback for Reddit/TikTok/Instagram when ScrapeCreators is exhausted | yes (limited) |diff --git a/skills/last30days/scripts/lib/env.py b/skills/last30days/scripts/lib/env.pyindex 4a16c6e9..4dd794f9 100644--- a/skills/last30days/scripts/lib/env.py+++ b/skills/last30days/scripts/lib/env.py@@ -407,6 +407,10 @@ def get_config() -> dict[str, Any]:('EXCLUDE_SOURCES', ''),('LAST30DAYS_YOUTUBE_SSH_HOST', None),('LAST30DAYS_TRANSCRIPT_TIMEOUT', None),+ # Whisper transcription provider for caption-free audio/video. Groq's+ # free tier is preferred; OPENAI_API_KEY is the paid backstop (already+ # resolved above via openai_auth).+ ('GROQ_API_KEY', None),]for key, default in keys:@@ -665,6 +669,20 @@ def keyless_web_allowed(config: dict[str, Any]) -> bool:return not is_native_search(config)+def transcription_providers(config: dict[str, Any]) -> list[tuple[str, str]]:+ """Ordered (name, api_key) Whisper providers for caption-free transcription.++ Groq (free tier) first, OpenAI (paid) as the backstop. Empty when neither+ key is set, in which case transcription degrades rather than runs.+ """+ providers: list[tuple[str, str]] = []+ if config.get('GROQ_API_KEY'):+ providers.append(('groq', config['GROQ_API_KEY']))+ if config.get('OPENAI_API_KEY'):+ providers.append(('openai', config['OPENAI_API_KEY']))+ return providers++def is_bluesky_available(config: dict[str, Any]) -> bool:"""Check if Bluesky source is available.diff --git a/skills/last30days/scripts/lib/transcribe.py b/skills/last30days/scripts/lib/transcribe.pynew file mode 100644index 00000000..c3dc2b99--- /dev/null+++ b/skills/last30days/scripts/lib/transcribe.py@@ -0,0 +1,232 @@+"""Caption-free transcription: compress -> chunk -> provider-fallback.++When a video/audio item has no captions, this turns the media into text via a+Whisper API. Source-agnostic: the input is a media URL or local path, the output+is transcript text. The pipeline:++ 1. Acquire audio (yt-dlp for a URL, or use a local file as-is).+ 2. Re-encode to a low-bitrate mono stream so most clips fit under the provider+ upload limit.+ 3. If still over the limit, split into bounded-duration chunks.+ 4. Transcribe each chunk through an ordered provider list (Groq free tier+ first, OpenAI paid backstop), with per-chunk fallback, then join.++Never raises. Returns a typed :class:`TranscriptResult`; missing prerequisites+(no ffmpeg, no provider key) yield a degraded result with a reason, consumed by+the source-health layer, rather than a crash.+"""++from __future__ import annotations++import os+import shutil+import subprocess+import tempfile+from dataclasses import dataclass, field+from typing import Optional++from . import env, health++# Whisper's documented upload ceiling. We compress to stay under it and chunk+# when a single clip still exceeds it.+MAX_UPLOAD_BYTES = 25 * 1024 * 1024+CHUNK_SECONDS = 600 # 10-minute chunks when splitting is required++_PROVIDER_ENDPOINTS = {+ "groq": "https://api.groq.com/openai/v1/audio/transcriptions",+ "openai": "https://api.openai.com/v1/audio/transcriptions",+}+_PROVIDER_MODELS = {+ "groq": "whisper-large-v3",+ "openai": "whisper-1",+}+++@dataclass+class TranscriptResult:+ text: str = ""+ ok: bool = False+ reason: str = ""+ provider: str = ""+ chunks: int = 0+ health: Optional[health.SourceHealth] = field(default=None)+++def is_available(config: dict) -> bool:+ """True when ffmpeg is present AND at least one Whisper provider key is set."""+ return bool(shutil.which("ffmpeg")) and bool(env.transcription_providers(config))+++def transcribe_media(+ source: str,+ config: dict,+ timeout: float = 120.0,+) -> TranscriptResult:+ """Transcribe a media URL or local path. Never raises.++ Returns a degraded result (ok=False, reason set) when prerequisites are+ missing or every provider fails, so callers can report the gap honestly.+ """+ if not shutil.which("ffmpeg"):+ return _degraded("ffmpeg not installed", health.MISSING)+ providers = env.transcription_providers(config)+ if not providers:+ return _degraded(+ "no transcription provider key (set GROQ_API_KEY or OPENAI_API_KEY)",+ health.MISSING,+ )++ workdir = tempfile.mkdtemp(prefix="l30d-transcribe-")+ try:+ audio_path = _acquire_audio(source, workdir, timeout=timeout)+ if not audio_path:+ return _degraded("could not acquire/compress audio", health.ERROR)++ chunk_paths = _chunk_audio(audio_path, workdir)+ if not chunk_paths:+ return _degraded("audio chunking produced no segments", health.ERROR)++ texts: list[str] = []+ used_provider = ""+ for chunk in chunk_paths:+ chunk_text, provider = _transcribe_chunk(chunk, providers, timeout=timeout)+ if chunk_text is None:+ return _degraded(+ f"all providers failed on a chunk ({len(texts)}/{len(chunk_paths)} done)",+ health.ERROR,+ )+ texts.append(chunk_text)+ used_provider = provider or used_provider++ joined = "\n".join(t.strip() for t in texts if t.strip())+ if not joined:+ return _degraded("transcription produced empty text", health.DEGRADED)+ return TranscriptResult(+ text=joined,+ ok=True,+ provider=used_provider,+ chunks=len(chunk_paths),+ health=health.SourceHealth(name="transcribe", state=health.OK),+ )+ finally:+ shutil.rmtree(workdir, ignore_errors=True)+++def _degraded(reason: str, state: str) -> TranscriptResult:+ return TranscriptResult(+ ok=False,+ reason=reason,+ health=health.SourceHealth(name="transcribe", state=state, reason=reason),+ )+++def _acquire_audio(source: str, workdir: str, timeout: float) -> Optional[str]:+ """Produce a compressed mono/16kHz/low-bitrate audio file, or None.++ For a URL, extract audio with yt-dlp; for a local path, transcode it. The+ re-encode keeps most clips under the upload ceiling.+ """+ raw = source+ if source.startswith("http"):+ raw = os.path.join(workdir, "raw.m4a")+ if not _run([+ "yt-dlp", "-f", "bestaudio", "-o", raw, "--no-playlist", source+ ], timeout=timeout):+ return None+ if not os.path.exists(raw):+ return None+ elif not os.path.exists(source):+ return None++ out = os.path.join(workdir, "audio.mp3")+ # Mono, 16kHz, 32kbps keeps speech intelligible while shrinking the file.+ if not _run([+ "ffmpeg", "-y", "-i", raw, "-ac", "1", "-ar", "16000", "-b:a", "32k", out+ ], timeout=timeout):+ return None+ return out if os.path.exists(out) else None+++def _chunk_audio(audio_path: str, workdir: str) -> list[str]:+ """Return [audio_path] when small enough, else ffmpeg-segmented chunk paths."""+ try:+ size = os.path.getsize(audio_path)+ except OSError:+ return []+ if size <= MAX_UPLOAD_BYTES:+ return [audio_path]++ pattern = os.path.join(workdir, "chunk_%03d.mp3")+ if not _run([+ "ffmpeg", "-y", "-i", audio_path, "-f", "segment",+ "-segment_time", str(CHUNK_SECONDS), "-c", "copy", pattern+ ]):+ # Fall back to the single (oversized) file; the provider may still accept it.+ return [audio_path]+ chunks = sorted(+ os.path.join(workdir, f) for f in os.listdir(workdir) if f.startswith("chunk_")+ )+ return chunks or [audio_path]+++def _transcribe_chunk(+ path: str,+ providers: list[tuple[str, str]],+ timeout: float,+) -> tuple[Optional[str], str]:+ """Try each provider in order; return (text, provider) or (None, '')."""+ for name, key in providers:+ try:+ text = _post_audio(name, path, key, timeout=timeout)+ except Exception: # noqa: BLE001 - any provider failure -> try the next+ text = None+ if text is not None:+ return text, name+ return None, ""+++def _post_audio(provider: str, path: str, api_key: str, timeout: float) -> Optional[str]:+ """POST one audio file to a Whisper-compatible endpoint; return text or None."""+ import json+ import urllib.request++ endpoint = _PROVIDER_ENDPOINTS[provider]+ model = _PROVIDER_MODELS[provider]+ boundary = "----l30dTranscribeBoundary"+ with open(path, "rb") as fh:+ audio = fh.read()++ parts: list[bytes] = []+ parts.append(f"--{boundary}\r\n".encode())+ parts.append(b'Content-Disposition: form-data; name="model"\r\n\r\n')+ parts.append(f"{model}\r\n".encode())+ parts.append(f"--{boundary}\r\n".encode())+ parts.append(+ b'Content-Disposition: form-data; name="file"; filename="audio.mp3"\r\n'+ b"Content-Type: audio/mpeg\r\n\r\n"+ )+ parts.append(audio)+ parts.append(f"\r\n--{boundary}--\r\n".encode())+ body = b"".join(parts)++ req = urllib.request.Request(+ endpoint,+ data=body,+ headers={+ "Authorization": f"Bearer {api_key}",+ "Content-Type": f"multipart/form-data; boundary={boundary}",+ },+ method="POST",+ )+ with urllib.request.urlopen(req, timeout=timeout) as resp:+ data = json.loads(resp.read().decode("utf-8"))+ return data.get("text")+++def _run(command: list[str], timeout: float = 120.0) -> bool:+ """Run a subprocess; return True on exit 0, False on any failure. No raise."""+ try:+ proc = subprocess.run(command, capture_output=True, timeout=timeout)+ except (FileNotFoundError, OSError, subprocess.TimeoutExpired):+ return False+ return proc.returncode == 0diff --git a/tests/test_transcribe.py b/tests/test_transcribe.pynew file mode 100644index 00000000..8e83a68e--- /dev/null+++ b/tests/test_transcribe.py@@ -0,0 +1,93 @@+"""Tests for scripts/lib/transcribe.py — caption-free transcription fallback (U6)."""++from unittest import mock++from lib import health, transcribe+++class TestPrerequisites:+ def test_missing_ffmpeg_degrades(self):+ with mock.patch.object(transcribe.shutil, "which", return_value=None):+ result = transcribe.transcribe_media("https://x/v", {"GROQ_API_KEY": "k"})+ assert result.ok is False+ assert "ffmpeg" in result.reason+ assert result.health.state == health.MISSING++ def test_no_provider_key_degrades(self):+ with mock.patch.object(transcribe.shutil, "which", return_value="/usr/bin/ffmpeg"):+ result = transcribe.transcribe_media("https://x/v", {})+ assert result.ok is False+ assert "provider" in result.reason+ assert result.health.state == health.MISSING++ def test_is_available(self):+ with mock.patch.object(transcribe.shutil, "which", return_value="/usr/bin/ffmpeg"):+ assert transcribe.is_available({"GROQ_API_KEY": "k"}) is True+ assert transcribe.is_available({}) is False+++class TestTranscribeFlow:+ def _patches(self, chunks, post_side_effect):+ return [+ mock.patch.object(transcribe.shutil, "which", return_value="/usr/bin/ffmpeg"),+ mock.patch.object(transcribe, "_acquire_audio", return_value="/tmp/audio.mp3"),+ mock.patch.object(transcribe, "_chunk_audio", return_value=chunks),+ mock.patch.object(transcribe, "_post_audio", side_effect=post_side_effect),+ mock.patch.object(transcribe.shutil, "rmtree"),+ mock.patch.object(transcribe.tempfile, "mkdtemp", return_value="/tmp/wd"),+ ]++ def test_under_limit_single_chunk(self):+ with mock.patch.object(transcribe.shutil, "which", return_value="/usr/bin/ffmpeg"), \+ mock.patch.object(transcribe, "_acquire_audio", return_value="/tmp/audio.mp3"), \+ mock.patch.object(transcribe, "_chunk_audio", return_value=["/tmp/audio.mp3"]), \+ mock.patch.object(transcribe, "_post_audio", return_value="hello world"), \+ mock.patch.object(transcribe.shutil, "rmtree"), \+ mock.patch.object(transcribe.tempfile, "mkdtemp", return_value="/tmp/wd"):+ result = transcribe.transcribe_media("https://x/v", {"GROQ_API_KEY": "k"})+ assert result.ok is True+ assert result.text == "hello world"+ assert result.chunks == 1+ assert result.provider == "groq"++ def test_over_limit_chunks_joined_in_order(self):+ chunks = ["/tmp/wd/chunk_000.mp3", "/tmp/wd/chunk_001.mp3"]+ with mock.patch.object(transcribe.shutil, "which", return_value="/usr/bin/ffmpeg"), \+ mock.patch.object(transcribe, "_acquire_audio", return_value="/tmp/audio.mp3"), \+ mock.patch.object(transcribe, "_chunk_audio", return_value=chunks), \+ mock.patch.object(transcribe, "_post_audio", side_effect=["part one", "part two"]), \+ mock.patch.object(transcribe.shutil, "rmtree"), \+ mock.patch.object(transcribe.tempfile, "mkdtemp", return_value="/tmp/wd"):+ result = transcribe.transcribe_media("https://x/v", {"GROQ_API_KEY": "k"})+ assert result.ok is True+ assert result.text == "part one\npart two"+ assert result.chunks == 2++ def test_provider_fallback_on_chunk(self):+ # groq raises, openai succeeds -> fallback used.+ def post(provider, path, key, timeout):+ if provider == "groq":+ raise RuntimeError("groq 500")+ return "via openai"+ with mock.patch.object(transcribe.shutil, "which", return_value="/usr/bin/ffmpeg"), \+ mock.patch.object(transcribe, "_acquire_audio", return_value="/tmp/audio.mp3"), \+ mock.patch.object(transcribe, "_chunk_audio", return_value=["/tmp/audio.mp3"]), \+ mock.patch.object(transcribe, "_post_audio", side_effect=post), \+ mock.patch.object(transcribe.shutil, "rmtree"), \+ mock.patch.object(transcribe.tempfile, "mkdtemp", return_value="/tmp/wd"):+ result = transcribe.transcribe_media(+ "https://x/v", {"GROQ_API_KEY": "k", "OPENAI_API_KEY": "o"})+ assert result.ok is True+ assert result.text == "via openai"+ assert result.provider == "openai"++ def test_all_providers_fail_degrades(self):+ with mock.patch.object(transcribe.shutil, "which", return_value="/usr/bin/ffmpeg"), \+ mock.patch.object(transcribe, "_acquire_audio", return_value="/tmp/audio.mp3"), \+ mock.patch.object(transcribe, "_chunk_audio", return_value=["/tmp/audio.mp3"]), \+ mock.patch.object(transcribe, "_post_audio", side_effect=RuntimeError("boom")), \+ mock.patch.object(transcribe.shutil, "rmtree"), \+ mock.patch.object(transcribe.tempfile, "mkdtemp", return_value="/tmp/wd"):+ result = transcribe.transcribe_media("https://x/v", {"GROQ_API_KEY": "k"})+ assert result.ok is False+ assert "all providers failed" in result.reason