Bulk asynchronous downloader for multiple file hosts
Python asynciobunkrcyberdropdownloaderdropboxfilestergofilegoogle-drivemediafiremegamega-nzonedrivepatreonpawchivepinterestpixeldraintransfer-ittwitchtwittervk
feat: add custom methods for ffprobe (URL and files) (#971)
NTFSvolume491d417d9c9b
diff --git a/cyberdrop_dl/data_structures/url_objects.py b/cyberdrop_dl/data_structures/url_objects.pyindex c6e49dac2..fa78a0fc8 100644--- a/cyberdrop_dl/data_structures/url_objects.py+++ b/cyberdrop_dl/data_structures/url_objects.py@@ -11,6 +11,7 @@ from typing import TYPE_CHECKING, NamedTuplefrom yarl import URLfrom cyberdrop_dl.exceptions import MaxChildrenError+from cyberdrop_dl.types import is_absolute_http_urlfrom cyberdrop_dl.utils.utilities import sanitize_folderif TYPE_CHECKING:@@ -19,6 +20,7 @@ if TYPE_CHECKING:from rich.progress import TaskIDfrom cyberdrop_dl.managers.manager import Manager+ from cyberdrop_dl.types import AbsoluteHttpURLclass ScrapeItemType(IntEnum):@@ -42,16 +44,18 @@ class HlsSegment(NamedTuple):@dataclass(unsafe_hash=True, slots=True)class MediaItem:- url: URL+ url: AbsoluteHttpURLorigin: InitVar[ScrapeItem | MediaItem]download_folder: Pathfilename: stroriginal_filename: str | None = None- debrid_link: URL | None = field(default=None, hash=False, compare=False)+ debrid_link: AbsoluteHttpURL | None = field(default=None, hash=False, compare=False)duration: float | None = field(default=None, hash=False, compare=False)ext: str = ""is_segment: bool = False- fallbacks: Callable[..., URL] | list[URL] | None = field(default=None, hash=False, compare=False)+ fallbacks: Callable[..., AbsoluteHttpURL] | list[AbsoluteHttpURL] | None = field(+ default=None, hash=False, compare=False+ )# exclude from __init__parent_media_item: MediaItem | None = field(init=False, default=None, hash=False, compare=False)@@ -69,8 +73,8 @@ class MediaItem:referer: URL = field(init=False)album_id: str | None = field(init=False)datetime: int | None = field(init=False, hash=False, compare=False)- parents: list[URL] = field(init=False, hash=False, compare=False)- parent_threads: set[URL] = field(init=False, hash=False, compare=False)+ parents: list[AbsoluteHttpURL] = field(init=False, hash=False, compare=False)+ parent_threads: set[AbsoluteHttpURL] = field(init=False, hash=False, compare=False)def __post_init__(self, origin: ScrapeItem | MediaItem) -> None:self.referer = origin.url@@ -102,7 +106,7 @@ class MediaItem:@dataclass(kw_only=True, slots=True)class ScrapeItem:- url: URL+ url: AbsoluteHttpURLparent_title: str = ""part_of_album: bool = Falsealbum_id: str | None = None@@ -110,8 +114,8 @@ class ScrapeItem:retry: bool = Falseretry_path: Path | None = None- parents: list[URL] = field(default_factory=list, init=False)- parent_threads: set[URL] = field(default_factory=set, init=False)+ parents: list[AbsoluteHttpURL] = field(default_factory=list, init=False)+ parent_threads: set[AbsoluteHttpURL] = field(default_factory=set, init=False)children: int = field(default=0, init=False)children_limit: int = field(default=0, init=False)type: ScrapeItemType | None = field(default=None, init=False)@@ -175,9 +179,11 @@ class ScrapeItem:) -> ScrapeItem:"""Creates a scrape item."""scrape_item = self.copy()+ assert is_absolute_http_url(url)scrape_item.url = urlif add_parent:new_parent = add_parent if isinstance(add_parent, URL) else self.url+ assert is_absolute_http_url(new_parent)scrape_item.parents.append(new_parent)if new_title_part:scrape_item.add_to_parent_title(new_title_part)diff --git a/cyberdrop_dl/types.py b/cyberdrop_dl/types.pyindex de7059cd2..df10ac0c7 100644--- a/cyberdrop_dl/types.py+++ b/cyberdrop_dl/types.py@@ -10,7 +10,7 @@ from __future__ import annotationsfrom collections.abc import Sequencefrom functools import partialfrom pathlib import Path-from typing import Annotated, Any, TypeAlias, TypeGuard, TypeVar, final+from typing import TYPE_CHECKING, Annotated, Any, Literal, NewType, TypeAlias, TypeGuard, TypeVarimport yarlfrom pydantic import (@@ -38,29 +38,21 @@ from cyberdrop_dl.utils.validators import (pydantyc_yarl_url,)+if TYPE_CHECKING:-def do_nothing(cls=None) -> Any: ...+ class AbsoluteHttpURL(yarl.URL):+ absolute: Literal[True]+ scheme: Literal["http", "https"]+ def host(self) -> str: # type: ignore+ """Decoded host part of URL."""-og_init_subclass = yarl.URL.__init_subclass__+else:+ AbsoluteHttpURL = yarl.URL-yarl.URL.__init_subclass__ = do_nothing # type: ignore--@final-class AbsoluteHttpURL(yarl.URL):- def __init__(*args, **kwargs) -> None:- raise RuntimeError("Do not create instances, call yarl.URL and them assert validate")-- def host(self) -> str: # type: ignore- """Decoded host part of URL."""-- @staticmethod- def validate(url: yarl.URL) -> TypeGuard[AbsoluteHttpURL]:- return url.absolute and url.scheme.startswith("http")---yarl.URL.__init_subclass__ = og_init_subclass+def is_absolute_http_url(url: yarl.URL) -> TypeGuard[AbsoluteHttpURL]:+ return url.absolute and url.scheme.startswith("http")# ~~~~~ Strings ~~~~~~~@@ -125,3 +117,4 @@ U32Int: TypeAlias = intU32IntArray: TypeAlias = Array[U32Int]U32IntSequence: TypeAlias = Sequence[U32Int]AnyDict: TypeAlias = dict[str, Any]+AbsolutePath = NewType("AbsolutePath", Path)diff --git a/cyberdrop_dl/utils/ffmpeg.py b/cyberdrop_dl/utils/ffmpeg.pyindex 6a5d5e327..5f8b14de6 100644--- a/cyberdrop_dl/utils/ffmpeg.py+++ b/cyberdrop_dl/utils/ffmpeg.py@@ -1,40 +1,37 @@from __future__ import annotationsimport asyncio+import jsonimport shutilimport subprocess-from datetime import datetime+from dataclasses import asdict, dataclass, field+from datetime import datetime, timedelta+from fractions import Fractionfrom functools import lru_cache-from typing import TYPE_CHECKING, NamedTuple+from pathlib import Path+from typing import TYPE_CHECKING, Any, Literal, NamedTuple, Required, Self, TypedDict, overloadimport aiofilesimport aiofiles.os+from multidict import CIMultiDict+from yarl import URL+from cyberdrop_dl.types import is_absolute_http_urlfrom cyberdrop_dl.utils.logger import log_debug+from cyberdrop_dl.utils.utilities import get_valid_dictif TYPE_CHECKING:- from collections.abc import Sequence- from pathlib import Path+ from collections.abc import Generator, Mapping, Sequencefrom cyberdrop_dl.managers.manager import Manager++FFPROBE_CALL_PREFIX = "ffprobe", "-hide_banner", "-loglevel", "error", "-show_streams", "-print_format", "json"FFMPEG_CALL_PREFIX = "ffmpeg", "-y", "-loglevel", "error"CONCAT_INPUT_ARGS = "-f", "concat", "-safe", "0", "-i"CODEC_COPY = "-c", "copy"-class SubProcessResult(NamedTuple):- return_code: int | None- stdout: str- stderr: str- success: bool- command: tuple-- def as_dict(self) -> dict:- joined_command = " ".join(self.command)- return self._asdict() | {"command": joined_command}--class FFmpeg:def __init__(self, manager: Manager) -> None:self.manager = manager@@ -58,6 +55,38 @@ class FFmpeg:await async_delete_files(concat_file_path, *input_files)return result+ @overload+ @staticmethod+ async def probe(input: Path, /) -> FFprobeResult: ...++ @overload+ @staticmethod+ async def probe(input: URL, /, *, headers: Mapping[str, str] | None = None) -> FFprobeResult: ...++ @staticmethod+ async def probe(input: Path | URL, /, *, headers: Mapping[str, str] | None = None) -> FFprobeResult:+ if isinstance(input, URL):+ assert is_absolute_http_url(input)++ elif isinstance(input, Path):+ assert input.is_absolute()+ assert not headers++ else:+ raise ValueError("Can only probe a Path or a yarl.URL")++ command = *FFPROBE_CALL_PREFIX, str(input)+ if headers:+ add_headers = []+ for name, value in headers.items():+ add_headers.extend(["-headers", f"{name}: {value}"])++ command = *command, *add_headers+ result = await _run_command(command)+ default: FFprobeOutput = {"streams": []}+ output = json.loads(result.stdout) if result.success else default+ return FFprobeResult(output)+async def async_delete_files(*files: Path) -> None:await asyncio.gather(*[aiofiles.os.unlink(file) for file in files])@@ -75,19 +104,6 @@ async def _concat(concat_input_file: Path, output_file: Path):return await _run_command(command)-async def _run_command(command: Sequence[str]) -> SubProcessResult:- joined_command = " ".join(command)- log_debug(f"Running ffmpeg command: {joined_command}")- process = await asyncio.create_subprocess_exec(*command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)- stdout, stderr = await process.communicate()- return_code = process.returncode- stdout_str = stdout.decode("utf-8", errors="ignore")- stderr_str = stderr.decode("utf-8", errors="ignore")- results = SubProcessResult(return_code, stdout_str, stderr_str, return_code == 0, tuple(command))- log_debug(results.as_dict())- return results--@lru_cachedef get_ffmpeg_version() -> str | None:try:@@ -101,3 +117,190 @@ def get_ffmpeg_version() -> str | None:return Noneelse:return stdout.split("version", 1)[-1].split("Copyright")[0].strip()+++# ~~~~~~~~~~~~~~~~~~~~~~~~~~~ FFprobe ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+++class Duration(NamedTuple):+ # "00:03:48.250000000"+ days: int = 0+ hours: int = 0+ minutes: int = 0+ seconds: float = 0++ @staticmethod+ def parse(duration: float | str) -> float:+ if isinstance(duration, float | int):+ return duration+ try:+ return float(duration)+ except (ValueError, TypeError):+ pass+ days, _, other_parts = duration.partition(" ")+ if days:+ days = "".join(char for char in days if char.isdigit())+ else:+ days = "0"++ time_parts = other_parts.split(":")+ missing_parts = [0 for _ in range(3 - len(time_parts))]+ seconds = float(Fraction(time_parts.pop(-1)))+ int_parts = map(int, (days, *missing_parts, *time_parts))+ return Duration(*int_parts, seconds=seconds).as_timedelta().total_seconds()++ def as_timedelta(self) -> timedelta:+ return timedelta(**self._asdict())+++class StreamDict(TypedDict, total=False):+ index: Required[int]+ codec_type: Required[Literal["video", "audio", "subtitle"]]+++class FFprobeOutput(TypedDict, total=False):+ streams: Required[list[StreamDict]]+++class Tags(CIMultiDict[Any]): ...+++class FPS(float):+ def __str__(self) -> str:+ return str(int(self)) if self.is_integer() else f"{self:.2f}"+++@dataclass(frozen=True, kw_only=True)+class Stream:+ index: int+ codec_name: str+ codec_type: str+ bitrate: int | None+ duration: float | None+ tags: Tags++ @property+ def length(self) -> float | None:+ return self.duration++ @property+ def codec(self) -> str:+ return self.codec_name++ @classmethod+ def validate(cls, stream_info: Mapping[str, Any]) -> dict[str, Any]:+ info = get_valid_dict(cls, stream_info)+ tags = Tags(stream_info.get("tags", {}))+ duration: float | str | None = stream_info.get("duration") or tags.get("duration")+ bitrate = int(stream_info.get("bitrate") or stream_info.get("bit_rate") or 0) or None+ duration = Duration.parse(duration) if duration else None+ return info | {"tags": tags, "duration": duration, "bitrate": bitrate}++ @classmethod+ def new(cls, stream_info: Mapping[str, Any]) -> Self:+ return cls(**cls.validate(stream_info))++ def as_dict(self) -> dict[str, Any]:+ return asdict(self) | {"tags": dict(self.tags)}+++@dataclass(frozen=True, kw_only=True)+class AudioStream(Stream):+ sample_rate: int | None+ codec_type: Literal["audio"] = "audio"++ @classmethod+ def validate(cls, stream_info: StreamDict) -> dict[str, Any]:+ sample_rate = int(float(stream_info.get("sample_rate", 0))) or None+ defaults = super().validate(stream_info)+ return defaults | {"sample_rate": sample_rate}+++@dataclass(frozen=True, kw_only=True)+class VideoStream(Stream):+ width: int | None+ height: int | None+ fps: FPS | None+ resolution: str | None+ codec_type: Literal["video"] = "video"++ @classmethod+ def validate(cls, stream_info: StreamDict) -> dict[str, Any]:+ width = int(float(stream_info.get("width", 0))) or None+ height = int(float(stream_info.get("height", 0))) or None+ resolution = fps = None+ if width and height:+ resolution: str | None = f"{width}x{height}"++ if (avg_fps := stream_info.get("avg_frame_rate")) and str(avg_fps) not in {"0/0", "0", "0.0"}:+ fps: FPS | None = FPS(Fraction(avg_fps))++ defaults = super().validate(stream_info)+ return defaults | {"width": width, "height": height, "fps": fps, "resolution": resolution}+++@dataclass+class FFprobeResult:+ ffprobe_output: FFprobeOutput+ streams: tuple[Stream, ...] = field(init=False)++ def __post_init__(self) -> None:+ streams: list[Stream] = []+ for stream in self.ffprobe_output.get("streams", []):+ if stream["codec_type"] == "video":+ streams.append(VideoStream.new(stream))+ elif stream["codec_type"] == "audio":+ streams.append(AudioStream.new(stream))++ self.streams = tuple(streams)++ def video_streams(self) -> Generator[VideoStream]:+ for stream in self.streams:+ if isinstance(stream, VideoStream):+ yield stream++ def audio_streams(self) -> Generator[AudioStream]:+ for stream in self.streams:+ if isinstance(stream, AudioStream):+ yield stream++ @property+ def audio(self) -> AudioStream:+ """First audio stream"""+ return next(self.audio_streams())++ @property+ def video(self) -> VideoStream:+ """First video stream"""+ return next(self.video_streams())++ def __bool__(self) -> bool:+ return bool(self.ffprobe_output.get("streams"))+++# ~~~~~~~~~~~~~~~~~~~~~~ Subprocess ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+++class SubProcessResult(NamedTuple):+ return_code: int | None+ stdout: str+ stderr: str+ success: bool+ command: tuple++ def as_dict(self) -> dict:+ joined_command = " ".join(self.command)+ return self._asdict() | {"command": joined_command}+++async def _run_command(command: Sequence[str]) -> SubProcessResult:+ joined_command = " ".join(command)+ log_debug(f"Running command: {joined_command}")+ process = await asyncio.create_subprocess_exec(*command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)+ stdout, stderr = await process.communicate()+ return_code = process.returncode+ stdout_str = stdout.decode("utf-8", errors="ignore")+ stderr_str = stderr.decode("utf-8", errors="ignore")+ results = SubProcessResult(return_code, stdout_str, stderr_str, return_code == 0, tuple(command))+ log_debug(results.as_dict())+ return resultsdiff --git a/cyberdrop_dl/utils/utilities.py b/cyberdrop_dl/utils/utilities.pyindex b968a177e..ef8dc7927 100644--- a/cyberdrop_dl/utils/utilities.py+++ b/cyberdrop_dl/utils/utilities.py@@ -403,7 +403,7 @@ def set_default_app_if_none(file_path: Path) -> bool:return False-def get_valid_dict(dataclass: Dataclass | type[Dataclass], info: dict[str, Any]) -> dict[str, Any]:+def get_valid_dict(dataclass: Dataclass | type[Dataclass], info: Mapping[str, Any]) -> dict[str, Any]:"""Remove all keys that are not fields in the dataclass"""return {k: v for k, v in info.items() if k in get_field_names(dataclass)}