Files
ytdlp-tui/app/models.py
T
2026-09-19 14:18:15 +02:00

95 lines
2.8 KiB
Python

"""Data models and pure logic for interpreting yt-dlp ``--dump-json`` output.
None of this module touches the UI or external processes; it only knows how
to turn a parsed JSON document into the pieces of information the rest of
the application needs.
"""
from __future__ import annotations
from dataclasses import dataclass
from typing import Any
#: The only protocol value considered downloadable by this application.
VALID_PROTOCOL = "m3u8_native"
#: The resolution value yt-dlp uses to mark an audio-only format.
AUDIO_ONLY_RESOLUTION = "audio only"
@dataclass(frozen=True)
class FormatEntry:
"""One selectable entry from yt-dlp's ``formats`` list.
Attributes correspond 1:1 to the yt-dlp JSON attributes named in the
requirements: ``format_id``, ``resolution``, ``acodec``, ``vcodec`` and
``format``. ``protocol`` is kept too since it drives filtering.
"""
format_id: str
resolution: str
acodec: str
vcodec: str
format: str
protocol: str
@property
def is_audio_only(self) -> bool:
return self.resolution == AUDIO_ONLY_RESOLUTION
@property
def display_text(self) -> str:
"""The ``format`` attribute with underscores replaced by blanks."""
return self.format.replace("_", " ")
@classmethod
def from_json(cls, raw: dict[str, Any]) -> "FormatEntry":
def _clean(value: Any) -> str:
if value is None or value == "none":
return "none"
return str(value)
return cls(
format_id=str(raw.get("format_id", "")),
resolution=str(raw.get("resolution", "")),
acodec=_clean(raw.get("acodec")),
vcodec=_clean(raw.get("vcodec")),
format=str(raw.get("format", "")),
protocol=str(raw.get("protocol", "")),
)
@dataclass
class VideoInfo:
"""Everything extracted from one yt-dlp ``--dump-json`` document."""
fulltitle: str
audio_formats: list[FormatEntry]
video_formats: list[FormatEntry]
@property
def is_split(self) -> bool:
"""True when audio and video are offered as separate formats."""
return len(self.audio_formats) > 0
@classmethod
def from_json(cls, raw: dict[str, Any]) -> "VideoInfo":
formats_raw = raw.get("formats") or []
# Only m3u8_native survives; anything using https (or any other
# protocol) is skipped, per the requirements.
filtered = [
FormatEntry.from_json(f)
for f in formats_raw
if f.get("protocol") == VALID_PROTOCOL
]
audio_formats = [f for f in filtered if f.is_audio_only]
video_formats = [f for f in filtered if not f.is_audio_only]
return cls(
fulltitle=str(raw.get("fulltitle", "")),
audio_formats=audio_formats,
video_formats=video_formats,
)