Bulk asynchronous downloader for multiple file hosts
Python asynciobunkrcyberdropdownloaderdropboxfilestergofilegoogle-drivemediafiremegamega-nzonedrivepatreonpawchivepinterestpixeldraintransfer-ittwitchtwittervk
perf: throttle concurrent HLS download tasks (#1295)
NTFSvolume071986973151
diff --git a/cyberdrop_dl/downloader/downloader.py b/cyberdrop_dl/downloader/downloader.pyindex b7d16d146..e01bb22b7 100644--- a/cyberdrop_dl/downloader/downloader.py+++ b/cyberdrop_dl/downloader/downloader.py@@ -10,7 +10,7 @@ from datetime import datetimefrom functools import wrapsfrom http import HTTPStatusfrom pathlib import Path-from typing import TYPE_CHECKING, ParamSpec, TypeVar+from typing import TYPE_CHECKING, NamedTuple, ParamSpec, TypeVarfrom aiohttp import ClientConnectorError, ClientError, ClientResponseError@@ -24,7 +24,7 @@ from cyberdrop_dl.exceptions import (RestrictedFiletypeError,TooManyCrawlerErrors,)-from cyberdrop_dl.utils import ffmpeg+from cyberdrop_dl.utils import aio, ffmpegfrom cyberdrop_dl.utils.database.tables.history_table import get_db_pathfrom cyberdrop_dl.utils.logger import logfrom cyberdrop_dl.utils.utilities import error_handling_wrapper, get_size_or_none, parse_url@@ -32,6 +32,8 @@ from cyberdrop_dl.utils.utilities import error_handling_wrapper, get_size_or_non# Windows epoch is January 1, 1601. Unix epoch is January 1, 1970WIN_EPOCH_OFFSET = 116444736e9MAC_OS_SET_FILE = None+_VIDEO_HLS_BATCH_SIZE = 10+_AUDIO_HLS_BATCH_SIZE = 50# Try to import win32con for Windows constants, fallback to hardcoded values if unavailable@@ -67,6 +69,12 @@ if TYPE_CHECKING:P = ParamSpec("P")R = TypeVar("R")++class SegmentDownloadResult(NamedTuple):+ item: MediaItem+ downloaded: bool++KNOWN_BAD_URLS = {"https://i.imgur.com/removed.png": 404,"https://saint2.su/assets/notfound.gif": 404,@@ -181,7 +189,7 @@ class Downloader:self.update_queued_files()task_id = self.manager.progress_manager.file_progress.add_task(domain=self.domain, filename=media_item.filename)media_item.set_task_id(task_id)- video, audio, _ = await self._download_rendition_group(media_item, m3u8_group)+ video, audio, _subs = await self._download_rendition_group(media_item, m3u8_group)if not audio:await asyncio.to_thread(video.rename, media_item.complete_file)else:@@ -203,25 +211,26 @@ class Downloader:async def download(m3u8: M3U8):assert m3u8.media_typedownload_folder = media_item.complete_file.with_suffix(".cdl_hls") / m3u8.media_type- items, tasks = self._make_hls_tasks(media_item, m3u8, download_folder)- n_segmets = len(tasks)+ coros = self._prepare_hls_downloads(media_item, m3u8, download_folder)+ n_segmets = len(m3u8.segments)if n_segmets > 1:suffix = f".{m3u8.media_type}.ts"else:- suffix = media_item.complete_file.suffix + items[0].url.suffix+ suffix = media_item.complete_file.suffix + Path(m3u8.segments[0].absolute_uri).suffixoutput = media_item.complete_file.with_suffix(suffix)if await asyncio.to_thread(output.is_file):return output- tasks_results = await asyncio.gather(*tasks)- n_successful = sum(1 for r in tasks_results if r)+ batch_size = _VIDEO_HLS_BATCH_SIZE if m3u8.media_type == "video" else _AUDIO_HLS_BATCH_SIZE+ tasks_results = await aio.gather(coros, batch_size=batch_size)+ n_successful = sum(1 for result in tasks_results if result.downloaded)if n_successful != n_segmets:msg = f"Download of some segments failed. Successful: {n_successful:,}/{n_segmets:,} "raise DownloadError("HLS Seg Error", msg, media_item)- seg_paths = [item.complete_file for item in items if item.complete_file]+ seg_paths = [result.item.complete_file for result in tasks_results]if n_segmets > 1:ffmpeg_result = await ffmpeg.concat(seg_paths, output)@@ -248,21 +257,20 @@ class Downloader:video = await download(m3u8_group.video)return video, audio, subtitles- def _make_hls_tasks(+ def _prepare_hls_downloads(self, media_item: MediaItem, m3u8: M3U8, download_folder: Path- ) -> tuple[list[MediaItem], list[Coroutine[None, None, bool]]]:- seg_media_items: list[MediaItem] = []+ ) -> list[Coroutine[None, None, SegmentDownloadResult]]:padding = max(5, len(str(len(m3u8.segments))))- semaphore_hls = asyncio.Semaphore(10 if m3u8.media_type == "video" else 50)-def create_segments() -> Generator[HlsSegment]:for index, segment in enumerate(m3u8.segments, 1):assert segment.uriname = f"{index:0{padding}d}.cdl_hsl"yield HlsSegment(segment.title, name, parse_url(segment.absolute_uri))- def make_download_task(segment: HlsSegment) -> Coroutine[None, None, bool]:+ async def download_segment(segment: HlsSegment):+ # TODO: segments download should bypass the downloads slots limits.+ # They count as a single downloadseg_media_item = MediaItem.from_item(media_item,segment.url,@@ -275,17 +283,13 @@ class Downloader:# reference=media_item,# skip_hashing=True,)- seg_media_items.append(seg_media_item)-- async def run() -> bool:- # TODO: segments download should bypass the downloads slots limits.- # They count as a single download- async with semaphore_hls:- return await self.start_download(seg_media_item)- return run()+ return SegmentDownloadResult(+ seg_media_item,+ await self.start_download(seg_media_item),+ )- return seg_media_items, [make_download_task(segment) for segment in create_segments()]+ return [download_segment(segment) for segment in create_segments()]async def finalize_download(self, media_item: MediaItem, downloaded: bool) -> None:if downloaded:diff --git a/cyberdrop_dl/utils/aio.py b/cyberdrop_dl/utils/aio.pyindex 963c4c683..2fb25b7b5 100644--- a/cyberdrop_dl/utils/aio.py+++ b/cyberdrop_dl/utils/aio.py@@ -9,14 +9,14 @@ from stat import S_ISREGfrom typing import TYPE_CHECKING, ParamSpec, TypeVar, castif TYPE_CHECKING:- from collections.abc import Awaitable+ from collections.abc import Awaitable, Sequence_P = ParamSpec("_P")_T = TypeVar("_T")_R = TypeVar("_R")-async def gather(*coros: Awaitable[_T], batch_size: int = 10) -> list[_T]:+async def gather(coros: Sequence[Awaitable[_T]], batch_size: int = 10) -> list[_T]:"""Like `asyncio.gather`, but creates tasks lazily to minimize event loop overhead.This function ensures there are never more than `batch_size` tasks created at any given time.@@ -25,9 +25,6 @@ async def gather(*coros: Awaitable[_T], batch_size: int = 10) -> list[_T]:are cancelled and any remaning task in the queue will be ignored."""- # TODO: Use this function for HLS downloads to prevent creating thousands of tasks- # for each segment (most of them wait forever becuase they use the same semaphore)-semaphore = asyncio.BoundedSemaphore(batch_size)results: list[_T] = cast("list[_T]", [None] * len(coros))