|
| 1 | +"""Podcast RSS/Atom feed expansion for ``assembly transcribe``. |
| 2 | +
|
| 3 | +A feed URL names a whole show, so transcribing it means transcribing every |
| 4 | +episode. ``feed_episode_urls`` fetches the URL and, when ``feedparser`` recognizes |
| 5 | +it as an RSS or Atom feed, returns its episode enclosure URLs (in feed order — |
| 6 | +newest first) for the batch path to transcribe, one resumable sidecar per episode. |
| 7 | +The enclosures are direct media URLs the API fetches itself, so — unlike a YouTube |
| 8 | +or podcast *page*, which yt-dlp downloads first — no local download step is needed. |
| 9 | +
|
| 10 | +Detection is deliberately narrow so a direct media URL or ordinary web page still |
| 11 | +falls through to the single-source path untouched (and is never fetched twice): |
| 12 | +only an http(s) URL whose path is feed-shaped — no extension, or one of |
| 13 | +``.xml``/``.rss``/``.atom`` — and that no dedicated yt-dlp extractor already claims |
| 14 | +is sniffed, the response body is bounded, and only content ``feedparser`` parses as |
| 15 | +a real feed with at least one enclosure is treated as a feed. We hand ``feedparser`` |
| 16 | +the already-fetched bytes (never the URL) so our bounded, safe fetch below stays the |
| 17 | +only network path. |
| 18 | +""" |
| 19 | + |
| 20 | +from __future__ import annotations |
| 21 | + |
| 22 | +from pathlib import PurePosixPath |
| 23 | +from urllib.parse import urlsplit |
| 24 | + |
| 25 | +from pydantic import BaseModel, Field |
| 26 | + |
| 27 | +from aai_cli.core import youtube |
| 28 | + |
| 29 | +# A feed lives at an extensionless URL (e.g. feeds.simplecast.com/<id>) or a feed |
| 30 | +# document (.xml/.rss/.atom). Every other path — .mp3, .txt, .pdf — is never a feed, |
| 31 | +# so it is left for the single-source path and never fetched here. |
| 32 | +_FEED_URL_SUFFIXES = frozenset({"", ".xml", ".rss", ".atom"}) |
| 33 | + |
| 34 | +# Bound the download so a hostile or huge URL can't exhaust memory; 10 MB of feed |
| 35 | +# already holds thousands of episodes, far past any realistic batch. |
| 36 | +_MAX_FEED_BYTES = 10 * 1024 * 1024 # pragma: no mutate -- tuning knob, not behavior |
| 37 | +_FETCH_TIMEOUT_SECONDS = 15.0 # pragma: no mutate -- tuning knob, not behavior |
| 38 | + |
| 39 | + |
| 40 | +class _Enclosure(BaseModel): |
| 41 | + """One ``<enclosure>`` / Atom enclosure link; ``href`` is the media URL.""" |
| 42 | + |
| 43 | + href: str = "" |
| 44 | + |
| 45 | + |
| 46 | +class _Entry(BaseModel): |
| 47 | + # default_factory (not a shared `= []`) so each entry gets its own list, and the |
| 48 | + # typed factory keeps the field's element type known under pyright strict. |
| 49 | + enclosures: list[_Enclosure] = Field(default_factory=list[_Enclosure]) |
| 50 | + |
| 51 | + |
| 52 | +class _ParsedFeed(BaseModel): |
| 53 | + """The slice of feedparser's untyped result we use, validated into a real type |
| 54 | + (the project pattern for untyped third-party returns — cf. core/wer.py).""" |
| 55 | + |
| 56 | + # feedparser sets ``version`` to a non-empty id ("rss20", "atom10", …) for a |
| 57 | + # recognized feed and to "" for anything it doesn't recognize as one. |
| 58 | + version: str = "" |
| 59 | + entries: list[_Entry] = Field(default_factory=list[_Entry]) |
| 60 | + |
| 61 | + |
| 62 | +def feed_episode_urls(url: str) -> list[str] | None: |
| 63 | + """The episode media URLs if `url` is a podcast feed, else ``None``. |
| 64 | +
|
| 65 | + Returns ``None`` (stay single-source) for a direct-media URL, a yt-dlp page, |
| 66 | + an unreachable URL, or any content that isn't a feed carrying enclosures. |
| 67 | + """ |
| 68 | + if not _looks_like_feed_url(url) or youtube.is_downloadable_url(url): |
| 69 | + return None |
| 70 | + body = _fetch(url) |
| 71 | + if body is None: |
| 72 | + return None |
| 73 | + return _episode_urls(body) |
| 74 | + |
| 75 | + |
| 76 | +def _looks_like_feed_url(url: str) -> bool: |
| 77 | + """True when the URL path is feed-shaped: extensionless or a feed document.""" |
| 78 | + suffix = PurePosixPath(urlsplit(url).path).suffix.lower() |
| 79 | + return suffix in _FEED_URL_SUFFIXES |
| 80 | + |
| 81 | + |
| 82 | +def _episode_urls(body: str) -> list[str] | None: |
| 83 | + """The enclosure URLs in a feed body, deduped in document order; ``None`` when |
| 84 | + feedparser doesn't recognize it as a feed or it carries no enclosures.""" |
| 85 | + import feedparser |
| 86 | + |
| 87 | + # feedparser ships only partial inline types (its parse signature is Unknown), |
| 88 | + # so the result is validated through _ParsedFeed below; mirror remotefs.py's |
| 89 | + # fsspec shim in ignoring the unavoidable unknown-member report on the call. |
| 90 | + raw = feedparser.parse(body) # pyright: ignore[reportUnknownMemberType] |
| 91 | + parsed = _ParsedFeed.model_validate(raw) |
| 92 | + if not parsed.version: |
| 93 | + return None |
| 94 | + urls = [enc.href for entry in parsed.entries for enc in entry.enclosures if enc.href] |
| 95 | + deduped = list(dict.fromkeys(urls)) |
| 96 | + return deduped or None |
| 97 | + |
| 98 | + |
| 99 | +def _fetch(url: str) -> str | None: |
| 100 | + """Up to ``_MAX_FEED_BYTES`` of `url` decoded as text, or ``None`` on any failure |
| 101 | + or when the response is obviously binary media (audio/video/image).""" |
| 102 | + import httpx2 as httpx |
| 103 | + |
| 104 | + chunks: list[bytes] = [] |
| 105 | + try: |
| 106 | + with ( |
| 107 | + httpx.Client(timeout=_FETCH_TIMEOUT_SECONDS, follow_redirects=True) as client, |
| 108 | + client.stream("GET", url) as response, |
| 109 | + ): |
| 110 | + if not response.is_success: |
| 111 | + return None |
| 112 | + content_type = response.headers.get("content-type", "").lower() |
| 113 | + if content_type.startswith(("audio/", "video/", "image/")): |
| 114 | + return None |
| 115 | + total = 0 |
| 116 | + for chunk in response.iter_bytes(): |
| 117 | + chunks.append(chunk) |
| 118 | + total += len(chunk) |
| 119 | + if total >= _MAX_FEED_BYTES: |
| 120 | + break |
| 121 | + except (httpx.HTTPError, OSError): |
| 122 | + return None |
| 123 | + return b"".join(chunks).decode("utf-8", "replace") |
0 commit comments