Bulk asynchronous downloader for multiple file hosts
Python asynciobunkrcyberdropdownloaderdropboxfilestergofilegoogle-drivemediafiremegamega-nzonedrivepatreonpawchivepinterestpixeldraintransfer-ittwitchtwittervk
refactor: move profiling to its own module (#678)
NTFSvolumea43fae0d4b27
diff --git a/cyberdrop_dl/env.py b/cyberdrop_dl/env.pyindex 12a925863..f042e01d4 100644--- a/cyberdrop_dl/env.py+++ b/cyberdrop_dl/env.py@@ -7,4 +7,5 @@ if KEY:KEY = sha256(KEY.encode("utf-8")).hexdigest()DEBUG_LOG_FILE_FOLDER = os.getenv("CDL_DEBUG_LOG_FILE_FOLDER")-DEBUG_VAR = RUNNING_IN_IDE or DEBUG_LOG_FILE_FOLDER+PROFILING = os.getenv("CDL_PROFILING")+DEBUG_VAR = RUNNING_IN_IDE or DEBUG_LOG_FILE_FOLDER or PROFILINGdiff --git a/cyberdrop_dl/main.py b/cyberdrop_dl/main.pyindex ab315b0f4..cc1a4c463 100644--- a/cyberdrop_dl/main.py+++ b/cyberdrop_dl/main.py@@ -3,7 +3,6 @@ from __future__ import annotationsimport asyncioimport contextlibimport logging-import osimport sysfrom functools import wrapsfrom pathlib import Path@@ -35,7 +34,7 @@ STARTUP_LOGGER_FILE = Path().cwd().joinpath("startup.log")STARTUP_LOGGER_CONSOLE = None-def startup() -> Manager | None:+def startup() -> Manager:"""Starts the program and returns the manager.This will also run the UI for the program@@ -65,6 +64,7 @@ def startup() -> Manager | None:file = sources.get(e.title)handle_validation_error(e, file=file)+ sys.exit(1)except KeyboardInterrupt:startup_logger.info("Exiting...")@@ -268,8 +268,10 @@ async def director(manager: Manager) -> None:def main():profiling: bool = False- if not (profiling or os.getenv("CDL_PROFILING")):+ if not (profiling or env.PROFILING):return actual_main()+ from cyberdrop_dl.profiling import profile+profile(actual_main)@@ -290,44 +292,5 @@ def actual_main() -> None:sys.exit(exit_code)-def profile(func: Callable) -> None:- import cProfile- import pstats- import shutil- from contextlib import contextmanager- from datetime import datetime- from tempfile import TemporaryDirectory-- @contextmanager- def temp_dir_context():- with TemporaryDirectory() as temp_dir:- old_cwd = Path.cwd()- temp_dir_path = Path(temp_dir).resolve()- cookies_dir = old_cwd / "AppData/Cookies"- if cookies_dir.is_dir():- temp_cookies_dir = temp_dir_path / "AppData/Cookies"- temp_cookies_dir.mkdir(parents=True, exist_ok=True)- for cookie_file in cookies_dir.glob("*.txt"):- shutil.copy(cookie_file, temp_cookies_dir)-- os.chdir(temp_dir_path)- log_file = old_cwd / "cyberdrop_dl_debug.log"- print(f"Using {temp_dir_path} as temp AppData dir") # noqa: T201- try:- yield- finally:- os.chdir(old_cwd)- new_path = Path(f"cyberdrop_dl_debug_{datetime.now().strftime('%Y%m%d_%H%M%S')}.log")- shutil.move(log_file, new_path)-- with temp_dir_context(), cProfile.Profile() as cdl_profile:- with contextlib.suppress(SystemExit):- func()-- results = pstats.Stats(cdl_profile)- results.sort_stats(pstats.SortKey.TIME)- results.dump_stats(filename="cyberdrop_dl.profiling")--if __name__ == "__main__":main()diff --git a/cyberdrop_dl/profiling.py b/cyberdrop_dl/profiling.pynew file mode 100644index 000000000..ba2cdfd24--- /dev/null+++ b/cyberdrop_dl/profiling.py@@ -0,0 +1,69 @@+# ruff : noqa: T201++from __future__ import annotations++import contextlib+import cProfile+import os+import pstats+import shutil+from contextlib import contextmanager+from datetime import datetime+from pathlib import Path+from tempfile import TemporaryDirectory+from typing import TYPE_CHECKING++from cyberdrop_dl import env++if TYPE_CHECKING:+ from collections.abc import Callable+++def profile(func: Callable) -> None:+ @contextmanager+ def temp_dir_context():+ with TemporaryDirectory() as temp_dir:+ profile = setup_profile(temp_dir)+ try:+ yield+ finally:+ destroy_profile(*profile)+ input("Press any key to finish and delete the profile folder: ")++ with temp_dir_context(), cProfile.Profile() as cdl_profile:+ with contextlib.suppress(SystemExit):+ func()++ print("Generating profile report..")+ results = pstats.Stats(cdl_profile)+ results.sort_stats(pstats.SortKey.TIME)+ results.dump_stats(filename="cyberdrop_dl.profiling")+ print("DONE!")+++def setup_profile(temp_dir: Path | str) -> tuple[Path, Path]:+ old_cwd = Path.cwd()+ temp_dir_path = Path(temp_dir).resolve()+ cookies_dir = old_cwd / "AppData/Cookies"+ if cookies_dir.is_dir():+ temp_cookies_dir = temp_dir_path / "AppData/Cookies"+ temp_cookies_dir.mkdir(parents=True, exist_ok=True)+ for cookie_file in cookies_dir.glob("*.txt"):+ shutil.copy(cookie_file, temp_cookies_dir)++ os.chdir(temp_dir_path)+ print(f"Using {temp_dir_path} as temp AppData dir")+ env.DEBUG_LOG_FILE_FOLDER = temp_dir_path+ return old_cwd, temp_dir_path+++def destroy_profile(old_cwd: Path, temp_dir_path: Path) -> None:+ os.chdir(old_cwd)+ suffix = "profiling"+ old_log_file = temp_dir_path / "cyberdrop_dl_debug.log"+ if env.PROFILING == "use_date":+ suffix += f"_{datetime.now().strftime('%Y%m%d_%H%M%S')}"+ new_log_file = Path(f"cyberdrop_dl_debug_{suffix}.log").resolve()+ shutil.move(old_log_file, new_log_file)+ print(f"Profile AppData folder: {temp_dir_path}")+ print(f"Debug log file: {new_log_file}")