#!/usr/bin/env python3 """Fetch enriched YouTube metadata via yt-dlp. Usage: python3 fetch_metadata.py VIDEO_ID Besides the YTDLP_* lines it leaves a small sidecar, $XDG_CACHE_HOME/video-lens/metadata/ .json, from which render_report.py takes the channel id for the gallery meta block, and the duration in seconds and the language for the share data block, so the agent never has to copy them (026 §9.1; the R2 run directory will absorb this). """ import argparse import html import json import os import pathlib import re import subprocess import sys import time sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) from venv_env import ytdlp_path # noqa: E402 _SETUP = pathlib.Path(__file__).resolve().parent / "setup.py" YTDLP_MISSING_MSG = (f"ERROR:YTDLP_MISSING: yt-dlp not installed — run: python3 \"{_SETUP}\" yt-dlp" " (or brew install yt-dlp)") METADATA_DIR = ( pathlib.Path(os.environ.get("XDG_CACHE_HOME") or (pathlib.Path.home() / ".cache")) / "video-lens" / "metadata" ) DESC_LIMIT = 3000 # code points; the description is context for the model and the local report only def _clip_description(text, limit=DESC_LIMIT): """Cut a long description at its last line break within `limit` and end it with "…" on a line of its own, so a chapter list or a link never ends mid-line. When that line break would keep less than half of `limit` (a short intro, then one long paragraph), cut at the last space instead, and mid-word only when the second half of `limit` has no space either.""" if len(text) <= limit: return text head = text[:limit + 1] floor = limit // 2 cut = head.rfind("\n") if cut >= floor: return head[:cut].rstrip() + "\n\u2026" cut = head.rfind(" ") return (head[:cut] if cut >= floor else text[:limit]).rstrip() + " \u2026" def _linkify(line): parts = [] last = 0 for m in re.finditer(r"https?://\S+", line): parts.append(html.escape(line[last:m.start()])) url = m.group() parts.append( f'' f"{html.escape(url)}" ) last = m.end() parts.append(html.escape(line[last:])) return "".join(parts) def _format_views(vc): if vc is None: return "" return (f"{vc/1e6:.1f}M views" if vc >= 1e6 else f"{vc/1e3:.0f}K views" if vc >= 1e3 else f"{vc} views") def _format_duration(dur_s): if not dur_s: return "" h, rem = divmod(int(dur_s), 3600) m2 = rem // 60 return f"{h}h {m2}m" if h > 0 else f"{m2} min" def _primary_lang(code): return (code or "").split("-")[0].split("_")[0].lower() def _detect_language(data): """Primary ISO-639-1 language subtag from a yt-dlp info dict, or ''.""" lang = _primary_lang(data.get("language")) if lang: return lang # Multi-audio videos list every dubbed track as its own format; # language_preference marks the original audio (10) above dubs, so take # the highest-preference language rather than the first in format order. best_pref = None for fmt in (data.get("formats") or []): fl = _primary_lang(fmt.get("language")) if not fl or fl == "und": continue pref = fmt.get("language_preference") pref = -1000 if pref is None else pref if best_pref is None or pref > best_pref: best_pref = pref lang = fl return lang def _format_published(upload_date): if len(upload_date) != 8: return "" months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] return f"{months[int(upload_date[4:6])-1]} {int(upload_date[6:8])} {upload_date[:4]}" def write_sidecar(video_id, data): """Best-effort: a failed write only costs the gallery a channel id.""" if not re.fullmatch(r"[A-Za-z0-9_-]{11}", video_id or ""): return try: METADATA_DIR.mkdir(parents=True, exist_ok=True, mode=0o700) (METADATA_DIR / f"{video_id}.json").write_text(json.dumps({ "videoId": video_id, "channelId": data.get("channel_id") or "", "channel": data.get("channel") or "", "durationS": int(data["duration"]) if isinstance(data.get("duration"), (int, float)) else None, "lang": _detect_language(data), "fetchedAt": int(time.time()), }), encoding="utf-8") except OSError: pass def main(): parser = argparse.ArgumentParser() parser.add_argument("video_id") args = parser.parse_args() video_id = args.video_id url = f"https://www.youtube.com/watch?v={video_id}" ytdlp = ytdlp_path() if ytdlp is None: print(YTDLP_MISSING_MSG) sys.exit(0) try: result = subprocess.run( [ytdlp, "--skip-download", "--quiet", "--no-warnings", "--no-check-formats", "--dump-json", url], capture_output=True, text=True, timeout=60, ) except FileNotFoundError: print(YTDLP_MISSING_MSG) sys.exit(0) except subprocess.TimeoutExpired: print("ERROR:YTDLP_TIMEOUT: yt-dlp timed out after 60s") sys.exit(0) raw = result.stdout if not raw.strip(): stderr_hint = result.stderr.strip()[:200] print(f"ERROR:YTDLP_NO_OUTPUT: yt-dlp produced no output — {stderr_hint}") sys.exit(0) try: data = json.loads(raw) except json.JSONDecodeError as e: print(f"ERROR:YTDLP_JSON_ERROR: {e} — raw output: {raw[:200]}") sys.exit(0) desc_raw = _clip_description(data.get("description") or "") desc_html = "
".join(_linkify(line) for line in desc_raw.split("\n")) chapters = data.get("chapters") or [] published = _format_published(data.get("upload_date") or "") views = _format_views(data.get("view_count")) duration = _format_duration(data.get("duration")) print(f'YTDLP_TITLE: {data.get("title") or ""}') print(f'YTDLP_CHANNEL: {data.get("channel") or ""}') print(f'YTDLP_CHANNEL_ID: {data.get("channel_id") or ""}') print(f"YTDLP_PUBLISHED: {published}") print(f"YTDLP_VIEWS: {views}") print(f"YTDLP_DURATION: {duration}") print(f"YTDLP_DESC_HTML: {desc_html}") print(f"YTDLP_CHAPTERS: {json.dumps(chapters)}") print(f"YTDLP_LANGUAGE: {_detect_language(data)}") write_sidecar(video_id, data) if __name__ == "__main__": main()