From f41e9c1bfeee2f41b1089588f977a4f62226a435 Mon Sep 17 00:00:00 2001 From: pawank925 Date: Tue, 24 Nov 2026 17:30:58 +0530 Subject: [PATCH 1/4] =?UTF-8?q?Support=20=C3=A0=20la=20carte=20dependency?= =?UTF-8?q?=20extras?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Move runtime dependencies into optional extras (zim, image, video, download, filesystem, html, rewriting, i18n, all), keep beartype as the only base dependency, and raise actionable ImportErrors when an extra is missing. Resolve cross-feature imports at call time so each extra stands alone. Add metadata/import tests, a CI matrix, docs, and changelog entries. Fixes #244 --- .github/workflows/QA.yaml | 2 +- .github/workflows/Tests.yaml | 76 +++++- CHANGELOG.md | 13 + README.md | 40 ++- pyproject.toml | 85 ++++--- src/zimscraperlib/_extras.py | 10 + src/zimscraperlib/download.py | 15 +- src/zimscraperlib/filesystem.py | 7 +- src/zimscraperlib/html.py | 7 +- src/zimscraperlib/i18n.py | 11 +- src/zimscraperlib/image/conversion.py | 9 +- src/zimscraperlib/image/optimization.py | 29 ++- src/zimscraperlib/image/probing.py | 19 +- src/zimscraperlib/image/transformation.py | 9 +- src/zimscraperlib/image/utils.py | 9 +- src/zimscraperlib/rewriting/css.py | 25 +- src/zimscraperlib/rewriting/html.py | 7 +- src/zimscraperlib/rewriting/js_ast.py | 9 +- src/zimscraperlib/rewriting/url_rewriting.py | 7 +- src/zimscraperlib/video/encoding.py | 3 +- src/zimscraperlib/zim/__init__.py | 7 +- src/zimscraperlib/zim/archive.py | 11 +- src/zimscraperlib/zim/creator.py | 56 ++++- src/zimscraperlib/zim/dedup.py | 9 +- src/zimscraperlib/zim/filesystem.py | 3 +- src/zimscraperlib/zim/indexing.py | 9 +- src/zimscraperlib/zim/items.py | 12 +- src/zimscraperlib/zim/metadata.py | 57 +++-- src/zimscraperlib/zim/providers.py | 13 +- tests/conftest.py | 17 +- tests/test_extras.py | 252 +++++++++++++++++++ 31 files changed, 691 insertions(+), 147 deletions(-) create mode 100644 src/zimscraperlib/_extras.py create mode 100644 tests/test_extras.py diff --git a/.github/workflows/QA.yaml b/.github/workflows/QA.yaml index df10d11f..a6fb4847 100644 --- a/.github/workflows/QA.yaml +++ b/.github/workflows/QA.yaml @@ -62,7 +62,7 @@ jobs: - name: Install dependencies (and project) run: | pip install -U pip - pip install -e .[qa,scripts,test] + pip install -e .[all,qa,scripts,test] - name: Check Linting run: inv check-lint diff --git a/.github/workflows/Tests.yaml b/.github/workflows/Tests.yaml index e8ddb33f..5c9c4836 100644 --- a/.github/workflows/Tests.yaml +++ b/.github/workflows/Tests.yaml @@ -40,6 +40,80 @@ jobs: name: rules retention-days: 1 + check-extras-errors: + runs-on: ubuntu-24.04 + + steps: + - name: Checkout repo + uses: actions/checkout@v7 + + - name: Set up Python + uses: actions/setup-python@v7 + with: + python-version-file: pyproject.toml + architecture: x64 + + - name: Install minimal dependencies (and project) + run: | + pip install -U pip + pip install -e .[test] + + - name: Check optional dependency errors + run: pytest -q tests/test_extras.py + + check-extras: + runs-on: ubuntu-24.04 + needs: generate-rules + strategy: + fail-fast: false + matrix: + include: + - extra: none + module: zimscraperlib + - extra: zim + module: zimscraperlib.zim + - extra: image + module: zimscraperlib.image + - extra: video + module: zimscraperlib.video + - extra: download + module: zimscraperlib.download + - extra: filesystem + module: zimscraperlib.filesystem + - extra: html + module: zimscraperlib.html + - extra: rewriting + module: zimscraperlib.rewriting.html + - extra: i18n + module: zimscraperlib.i18n + + steps: + - name: Checkout repo + uses: actions/checkout@v7 + + - name: Restore rules artifact + uses: actions/download-artifact@v8 + with: + name: rules + + - name: Set up Python + uses: actions/setup-python@v7 + with: + python-version-file: pyproject.toml + architecture: x64 + + - name: Install dependencies (and project) + run: | + pip install -U pip + if [ "${{ matrix.extra }}" = "none" ]; then + pip install -e . + else + pip install -e ".[${{ matrix.extra }}]" + fi + + - name: Import module using only that extra + run: python -c "import importlib; importlib.import_module('${{ matrix.module }}')" + run-python-tests: runs-on: ubuntu-24.04 needs: generate-rules @@ -65,7 +139,7 @@ jobs: - name: Install dependencies (and project) run: | pip install -U pip - pip install -e .[test,scripts] + pip install -e .[all,test,scripts] - name: Run the tests run: inv coverage --args "--runslow --runinstalled -vvv" diff --git a/CHANGELOG.md b/CHANGELOG.md index 77dcde76..e0310f36 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,19 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Added + +- Optional dependency groups `zim`, `image`, `video`, `download`, `filesystem`, `html`, `rewriting`, `i18n` and `all`; the base install now only requires `beartype` (#244) +- Missing optional dependencies now raise an `ImportError` naming the extra to install (#244) + +### Changed + +- Cross-feature imports are now resolved where they are used, so each extra only needs its own dependencies (#244) + +### Fixed + +- The `rewriting` extra now declares `tinycss2` explicitly instead of relying on it being pulled in through `CairoSVG` (#244) + ## [5.6.0] - 2026-11-20 ### Added diff --git a/README.md b/README.md index c9f54725..f77b9584 100644 --- a/README.md +++ b/README.md @@ -34,33 +34,49 @@ See documentation at [Read the Docs](https://python-scraperlib.readthedocs.io/) # Dependencies -Most dependencies are installed automatically by pip (from PyPI by default). The following system packages may be required depending on which features you use: +The base install only pulls in `beartype`. Install the extras for the features you use: -- **libmagic** — required for file type detection (used in most scrapers) -- **wget** — required only for `zimscraperlib.download` functions -- **FFmpeg** — required only for video processing functions -- **gifsicle** (>=1.92) — required only for GIF optimization -- **libcairo** — required only for SVG-to-PNG conversion -- **libzim** — auto-installed via PyPI, not available on Windows -- **Pillow** — auto-installed via PyPI; pre-built wheels are used by default and no system image libraries are needed. Only if you need to build Pillow from source should you install additional system libraries — see [Pillow's build documentation](https://pillow.readthedocs.io/en/latest/installation/building-from-source.html) for details. - > **Note:** To run the full test suite, all system dependencies listed above must be installed. +```sh +python -m pip install 'zimscraperlib[zim,image]' +python -m pip install 'zimscraperlib[all]' +``` + +Importing a module whose extra is missing raises an `ImportError` naming the extra to install. + +| Extra | Python dependencies for | System dependencies | +| --- | --- | --- | +| `zim` | `zimscraperlib.zim` | none (`libzim` ships wheels, except on unsupported platforms) | +| `image` | `zimscraperlib.image` | libcairo for SVG conversion, gifsicle (>=1.92) for GIF optimization | +| `video` | `zimscraperlib.video` | FFmpeg | +| `download` | `zimscraperlib.download` | none; wget is only needed if your scraper calls it itself | +| `filesystem` | `zimscraperlib.filesystem` and MIME-type detection | libmagic | +| `html` | `zimscraperlib.html` | none | +| `rewriting` | `zimscraperlib.rewriting` | none | +| `i18n` | `zimscraperlib.i18n` | none | +| `all` | every runtime extra | every system dependency above | + +Pillow uses pre-built wheels by default; no system image libraries are needed unless you build it from source (see [Pillow's build documentation](https://pillow.readthedocs.io/en/latest/installation/building-from-source.html)). + +> **Note:** To run the full test suite, install `all` and all system dependencies listed above. + +To install every system dependency listed above: ## macOS ```sh -brew install libmagic wget ffmpeg gifsicle cairo +brew install libmagic ffmpeg gifsicle cairo ``` ## Linux ```sh -sudo apt install libmagic1 wget ffmpeg gifsicle libcairo2 +sudo apt install libmagic1 ffmpeg gifsicle libcairo2 ``` ## Alpine ```sh -apk add ffmpeg gifsicle libmagic wget cairo +apk add ffmpeg gifsicle libmagic cairo ``` # Contribution diff --git a/pyproject.toml b/pyproject.toml index 5b9cb159..5b001bb0 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -10,16 +10,23 @@ requires-python = ">=3.14,<3.15" description = "Collection of python tools to re-use common code across scrapers" readme = "README.md" dependencies = [ - "iso639-lang>=2.4.0,<3.0", - "requests>=2.25.1,<3.0", - "colorthief==0.2.1", - "python-resize-image>=1.1.19,<1.2", - "Babel>=2.9,<3.0", - "python-magic>=0.4.3,<0.5", + "beartype>=0.19,<0.24", +] +dynamic = ["authors", "classifiers", "keywords", "license", "version", "urls"] + +[tool.hatch.metadata.hooks.openzim-metadata] +kind = "scraper" +additional-classifiers = [ + "Development Status :: 5 - Production/Stable", + "Intended Audience :: Developers", +] + +[tool.hatch.build.hooks.openzim-build] + +[project.optional-dependencies] +zim = [ "libzim>=3.8.0,<4.0", - "beautifulsoup4>=4.9.3,<5.0", - "lxml>=4.6.3,<7.0", - "optimize-images>=1.3.6,<3.0", + "xxhash>=2.0,<5.0", # regex has no upper-bound due to "date-based" release numbers, no semver, so their # promise is that they will never (or always) break the API, and the API is very # limited and we use only a very small subset of it. @@ -27,15 +34,36 @@ dependencies = [ # pymupdf-lite is the official build of pymupdf without its layout engine, and # without the heavy dependencies (onnxruntime, numpy, ...) it brings since 2.0 "pymupdf-lite>=2.0,<3.0", + "types-xxhash>=2.0,<4.0", +] +image = [ + "pillow>=7.0.0,<14.0", + "colorthief==0.2.1", + # piexif is pinned because of its irregular release management + "piexif==1.1.3", + "optimize-images>=1.3.6,<3.0", + "python-resize-image>=1.1.19,<1.2", "CairoSVG>=2.2.0,<3.0", - "beartype>=0.19,<0.24", +] +video = [] +download = [ + "requests>=2.25.1,<3.0", + "urllib3>=1.26.5,<2.9.0", # youtube-dl should be updated as frequently as possible "yt-dlp", - "pillow>=7.0.0,<14.0", - "urllib3>=1.26.5,<2.9.0", - "piexif==1.1.3", # this dep is a nightmare in terms of release management, better pinned just like in optimize-images anyway +] +filesystem = [ + "python-magic>=0.4.3,<0.5", +] +html = [ + "beautifulsoup4>=4.9.3,<5.0", + "lxml>=4.6.3,<7.0", +] +rewriting = [ + "beautifulsoup4>=4.9.3,<5.0", + "lxml>=4.6.3,<7.0", "idna>=2.5,<4.0", - "xxhash>=2.0,<5.0", + "tinycss2>=1.2,<2.0", # Parsing JavaScript well enough to know which names a script declares at its # top level (see rewriting/js_ast.py). tree-sitter rather than a pure-Python # parser because the input is whatever the live web served: esprima is ES2017 @@ -43,20 +71,14 @@ dependencies = [ # shipped code, and a parse failure here silently restores the bug this fixes. "tree-sitter>=0.23,<1.0", "tree-sitter-javascript>=0.23,<1.0", - "types-xxhash>=2.0,<4.0", ] -dynamic = ["authors", "classifiers", "keywords", "license", "version", "urls"] - -[tool.hatch.metadata.hooks.openzim-metadata] -kind = "scraper" -additional-classifiers = [ - "Development Status :: 5 - Production/Stable", - "Intended Audience :: Developers", +i18n = [ + "Babel>=2.9,<3.0", + "iso639-lang>=2.4.0,<3.0", +] +all = [ + "zimscraperlib[zim,image,video,download,filesystem,html,rewriting,i18n]", ] - -[tool.hatch.build.hooks.openzim-build] - -[project.optional-dependencies] scripts = [ "invoke==3.0.3", # jinja2 is required to generate JS and Python rules at build time @@ -90,10 +112,7 @@ docs = [ dev = [ "ipython==9.17.1", "pre-commit==4.7.0", - "zimscraperlib[scripts]", - "zimscraperlib[qa]", - "zimscraperlib[test]", - "zimscraperlib[docs]", + "zimscraperlib[all,scripts,qa,test,docs]", ] [project.scripts] @@ -126,7 +145,7 @@ artifacts = [ features = ["dev"] [tool.hatch.envs.test] -features = ["scripts", "test"] +features = ["scripts", "test", "all"] [tool.hatch.envs.test.scripts] run = "inv test --args '{args}'" @@ -138,7 +157,7 @@ html = "inv coverage --html --args '{args}'" [tool.hatch.envs.qa] template = "qa" skip-install = false -features = ["scripts", "qa", "test"] +features = ["scripts", "qa", "test", "all"] [tool.hatch.envs.qa.scripts] check-lint = "inv check-lint --args '{args}'" @@ -150,7 +169,7 @@ fix-lint = "inv fix-lint --args '{args}'" fix-all = "inv fix-all --args '{args}'" [tool.hatch.envs.docs] -features = ["scripts", "docs"] +features = ["scripts", "docs", "all"] [tool.hatch.envs.docs.scripts] serve = "inv docs-serve --args '{args}'" diff --git a/src/zimscraperlib/_extras.py b/src/zimscraperlib/_extras.py new file mode 100644 index 00000000..1d94534c --- /dev/null +++ b/src/zimscraperlib/_extras.py @@ -0,0 +1,10 @@ +from typing import NoReturn + + +def missing_extra(extra: str, error: ModuleNotFoundError) -> NoReturn: + name = error.name or "an optional dependency" + raise ImportError( + f"Missing dependency '{name}' required by the '{extra}' extra. " + f"Install it with `python -m pip install 'zimscraperlib[{extra}]'` " + f"or `python -m pip install 'zimscraperlib[all]'`." + ) from error diff --git a/src/zimscraperlib/download.py b/src/zimscraperlib/download.py index 4fb55f08..d3325533 100644 --- a/src/zimscraperlib/download.py +++ b/src/zimscraperlib/download.py @@ -6,11 +6,16 @@ from typing import Any, ClassVar from urllib.parse import urlparse -import requests -import requests.adapters -import requests.structures -import urllib3.util -import yt_dlp as youtube_dl # pyright: ignore[reportMissingTypeStubs] +from zimscraperlib._extras import missing_extra + +try: + import requests + import requests.adapters + import requests.structures + import urllib3.util + import yt_dlp as youtube_dl # pyright: ignore[reportMissingTypeStubs] +except ModuleNotFoundError as exc: + raise missing_extra("download", exc) from exc from zimscraperlib import logger from zimscraperlib.constants import ( diff --git a/src/zimscraperlib/filesystem.py b/src/zimscraperlib/filesystem.py index fe9cc35e..c2b452eb 100644 --- a/src/zimscraperlib/filesystem.py +++ b/src/zimscraperlib/filesystem.py @@ -7,7 +7,12 @@ from tempfile import TemporaryDirectory from typing import Any -import magic +from zimscraperlib._extras import missing_extra + +try: + import magic +except ModuleNotFoundError as exc: + raise missing_extra("filesystem", exc) from exc # override some MIME-types found by libmagic to different ones MIME_OVERRIDES = { diff --git a/src/zimscraperlib/html.py b/src/zimscraperlib/html.py index 386459b6..db748ec5 100644 --- a/src/zimscraperlib/html.py +++ b/src/zimscraperlib/html.py @@ -3,7 +3,12 @@ import pathlib from typing import BinaryIO, TextIO -from bs4 import BeautifulSoup, element +from zimscraperlib._extras import missing_extra + +try: + from bs4 import BeautifulSoup, element +except ModuleNotFoundError as exc: + raise missing_extra("html", exc) from exc from zimscraperlib.types import ARTICLE_MIME diff --git a/src/zimscraperlib/i18n.py b/src/zimscraperlib/i18n.py index 5adf2078..85f1ac62 100644 --- a/src/zimscraperlib/i18n.py +++ b/src/zimscraperlib/i18n.py @@ -1,8 +1,13 @@ import re -import babel -import iso639 # pyright: ignore[reportMissingTypeStubs] -import iso639.exceptions # pyright: ignore[reportMissingTypeStubs] +from zimscraperlib._extras import missing_extra + +try: + import babel + import iso639 # pyright: ignore[reportMissingTypeStubs] + import iso639.exceptions # pyright: ignore[reportMissingTypeStubs] +except ModuleNotFoundError as exc: + raise missing_extra("i18n", exc) from exc ISO_LEVELS = ["1", "2b", "2t", "3", "5"] diff --git a/src/zimscraperlib/image/conversion.py b/src/zimscraperlib/image/conversion.py index 27cd411c..a41faf55 100644 --- a/src/zimscraperlib/image/conversion.py +++ b/src/zimscraperlib/image/conversion.py @@ -2,8 +2,13 @@ import pathlib from typing import Any -import cairosvg # pyright: ignore[reportMissingTypeStubs] -from PIL.Image import open as pilopen +from zimscraperlib._extras import missing_extra + +try: + import cairosvg # pyright: ignore[reportMissingTypeStubs] + from PIL.Image import open as pilopen +except ModuleNotFoundError as exc: + raise missing_extra("image", exc) from exc from zimscraperlib.constants import ALPHA_NOT_SUPPORTED from zimscraperlib.image.probing import format_for diff --git a/src/zimscraperlib/image/optimization.py b/src/zimscraperlib/image/optimization.py index 5f9c7d09..5f6e34e6 100644 --- a/src/zimscraperlib/image/optimization.py +++ b/src/zimscraperlib/image/optimization.py @@ -26,18 +26,23 @@ import warnings from dataclasses import dataclass -import piexif # pyright: ignore[reportMissingTypeStubs] -from optimize_images.img_aux_processing import ( # pyright: ignore[reportMissingTypeStubs] - do_reduce_colors, - rebuild_palette, -) -from optimize_images.img_aux_processing import ( # pyright: ignore[reportMissingTypeStubs] - remove_transparency as remove_alpha, -) -from optimize_images.img_dynamic_quality import ( # pyright: ignore[reportMissingTypeStubs] - jpeg_dynamic_quality, -) -from PIL import Image +from zimscraperlib._extras import missing_extra + +try: + import piexif # pyright: ignore[reportMissingTypeStubs] + from optimize_images.img_aux_processing import ( # pyright: ignore[reportMissingTypeStubs] + do_reduce_colors, + rebuild_palette, + ) + from optimize_images.img_aux_processing import ( # pyright: ignore[reportMissingTypeStubs] + remove_transparency as remove_alpha, + ) + from optimize_images.img_dynamic_quality import ( # pyright: ignore[reportMissingTypeStubs] + jpeg_dynamic_quality, + ) + from PIL import Image +except ModuleNotFoundError as exc: + raise missing_extra("image", exc) from exc from zimscraperlib.image.probing import format_for diff --git a/src/zimscraperlib/image/probing.py b/src/zimscraperlib/image/probing.py index 6a8d2634..684ceb49 100644 --- a/src/zimscraperlib/image/probing.py +++ b/src/zimscraperlib/image/probing.py @@ -3,12 +3,16 @@ import pathlib import re -import colorthief # pyright: ignore[reportMissingTypeStubs] -import PIL.Image -from PIL.Image import EXTENSION as PIL_FMT_EXTENSION -from PIL.Image import init as init_pil +from zimscraperlib._extras import missing_extra + +try: + import colorthief # pyright: ignore[reportMissingTypeStubs] + import PIL.Image + from PIL.Image import EXTENSION as PIL_FMT_EXTENSION + from PIL.Image import init as init_pil +except ModuleNotFoundError as exc: + raise missing_extra("image", exc) from exc -from zimscraperlib.filesystem import get_content_mimetype, get_file_mimetype init_pil() # populate the PIL_FMT_EXTENSION dictionary @@ -75,6 +79,11 @@ def format_for( with PIL.Image.open(src) as img: return img.format except PIL.UnidentifiedImageError: + from zimscraperlib.filesystem import ( # noqa: PLC0415 + get_content_mimetype, + get_file_mimetype, + ) + # Fallback based on mimetype for SVG which are not supported by PIL if ( isinstance(src, pathlib.Path) diff --git a/src/zimscraperlib/image/transformation.py b/src/zimscraperlib/image/transformation.py index 750df41d..ee1e4d87 100644 --- a/src/zimscraperlib/image/transformation.py +++ b/src/zimscraperlib/image/transformation.py @@ -1,8 +1,13 @@ import io import pathlib -from PIL.Image import open as pilopen -from resizeimage import resizeimage # pyright: ignore[reportMissingTypeStubs] +from zimscraperlib._extras import missing_extra + +try: + from PIL.Image import open as pilopen + from resizeimage import resizeimage # pyright: ignore[reportMissingTypeStubs] +except ModuleNotFoundError as exc: + raise missing_extra("image", exc) from exc from zimscraperlib.constants import ALPHA_NOT_SUPPORTED from zimscraperlib.image.utils import save_image diff --git a/src/zimscraperlib/image/utils.py b/src/zimscraperlib/image/utils.py index 99b48757..398c27ef 100644 --- a/src/zimscraperlib/image/utils.py +++ b/src/zimscraperlib/image/utils.py @@ -2,8 +2,13 @@ import pathlib from typing import IO, Any -from PIL.Image import Image -from PIL.ImageFile import ImageFile +from zimscraperlib._extras import missing_extra + +try: + from PIL.Image import Image + from PIL.ImageFile import ImageFile +except ModuleNotFoundError as exc: + raise missing_extra("image", exc) from exc def save_image( diff --git a/src/zimscraperlib/rewriting/css.py b/src/zimscraperlib/rewriting/css.py index df3739b5..2cfb740d 100644 --- a/src/zimscraperlib/rewriting/css.py +++ b/src/zimscraperlib/rewriting/css.py @@ -16,16 +16,21 @@ from functools import partial from typing import Any -from tinycss2 import ( # pyright: ignore[reportMissingTypeStubs] - ast, - parse_declaration_list, # pyright: ignore[reportUnknownVariableType] - parse_stylesheet, # pyright: ignore[reportUnknownVariableType] - parse_stylesheet_bytes, # pyright: ignore[reportUnknownVariableType] - serialize, # pyright: ignore[reportUnknownVariableType] -) -from tinycss2.serializer import ( # pyright: ignore[reportMissingTypeStubs] - serialize_url, # pyright: ignore[reportUnknownVariableType] -) +from zimscraperlib._extras import missing_extra + +try: + from tinycss2 import ( # pyright: ignore[reportMissingTypeStubs] + ast, + parse_declaration_list, # pyright: ignore[reportUnknownVariableType] + parse_stylesheet, # pyright: ignore[reportUnknownVariableType] + parse_stylesheet_bytes, # pyright: ignore[reportUnknownVariableType] + serialize, # pyright: ignore[reportUnknownVariableType] + ) + from tinycss2.serializer import ( # pyright: ignore[reportMissingTypeStubs] + serialize_url, # pyright: ignore[reportUnknownVariableType] + ) +except ModuleNotFoundError as exc: + raise missing_extra("rewriting", exc) from exc from zimscraperlib import logger from zimscraperlib.rewriting.rx_replacer import RxRewriter, TransformationRule diff --git a/src/zimscraperlib/rewriting/html.py b/src/zimscraperlib/rewriting/html.py index 35247d46..54afe8ec 100644 --- a/src/zimscraperlib/rewriting/html.py +++ b/src/zimscraperlib/rewriting/html.py @@ -23,7 +23,12 @@ from inspect import Signature, signature from typing import Any, NamedTuple -from bs4 import BeautifulSoup +from zimscraperlib._extras import missing_extra + +try: + from bs4 import BeautifulSoup +except ModuleNotFoundError as exc: + raise missing_extra("rewriting", exc) from exc from zimscraperlib.rewriting.css import CssRewriter from zimscraperlib.rewriting.js import JsRewriter diff --git a/src/zimscraperlib/rewriting/js_ast.py b/src/zimscraperlib/rewriting/js_ast.py index 2f662543..c928eaa7 100644 --- a/src/zimscraperlib/rewriting/js_ast.py +++ b/src/zimscraperlib/rewriting/js_ast.py @@ -28,8 +28,13 @@ from dataclasses import dataclass -import tree_sitter_javascript -from tree_sitter import Language, Node, Parser +from zimscraperlib._extras import missing_extra + +try: + import tree_sitter_javascript + from tree_sitter import Language, Node, Parser +except ModuleNotFoundError as exc: + raise missing_extra("rewriting", exc) from exc __all__ = ["Declaration", "TopLevel", "node_text", "parse_top_level"] diff --git a/src/zimscraperlib/rewriting/url_rewriting.py b/src/zimscraperlib/rewriting/url_rewriting.py index 01362040..b38544c9 100644 --- a/src/zimscraperlib/rewriting/url_rewriting.py +++ b/src/zimscraperlib/rewriting/url_rewriting.py @@ -97,7 +97,12 @@ uses_relative, ) -import idna +from zimscraperlib._extras import missing_extra + +try: + import idna +except ModuleNotFoundError as exc: + raise missing_extra("rewriting", exc) from exc from zimscraperlib import logger from zimscraperlib.rewriting.rules import DEFUZZY_RULES, FUZZY_RULES diff --git a/src/zimscraperlib/video/encoding.py b/src/zimscraperlib/video/encoding.py index 1d75a176..a8a58ba9 100644 --- a/src/zimscraperlib/video/encoding.py +++ b/src/zimscraperlib/video/encoding.py @@ -5,7 +5,6 @@ from copy import deepcopy from zimscraperlib import logger -from zimscraperlib.filesystem import path_from from zimscraperlib.logging import nicer_args_join @@ -54,6 +53,8 @@ def reencode( failsafe - Run in failsafe mode """ + from zimscraperlib.filesystem import path_from # noqa: PLC0415 + with path_from(existing_tmp_path or tempfile.TemporaryDirectory()) as tmp_dir: tmp_path = pathlib.Path(tmp_dir).joinpath(f"video.tmp{dst_path.suffix}") args = _build_ffmpeg_args( diff --git a/src/zimscraperlib/zim/__init__.py b/src/zimscraperlib/zim/__init__.py index 0c96bc9a..e22bfefc 100644 --- a/src/zimscraperlib/zim/__init__.py +++ b/src/zimscraperlib/zim/__init__.py @@ -6,7 +6,12 @@ zim.items: item to add to creator zim.archive: read ZIM files, accessing or searching its content""" -from libzim.writer import Blob # pyright: ignore[reportMissingModuleSource] +from zimscraperlib._extras import missing_extra + +try: + from libzim.writer import Blob # pyright: ignore[reportMissingModuleSource] +except ModuleNotFoundError as exc: + raise missing_extra("zim", exc) from exc from zimscraperlib.zim.archive import Archive from zimscraperlib.zim.creator import Creator diff --git a/src/zimscraperlib/zim/archive.py b/src/zimscraperlib/zim/archive.py index 2e456769..7abe66b8 100644 --- a/src/zimscraperlib/zim/archive.py +++ b/src/zimscraperlib/zim/archive.py @@ -9,9 +9,14 @@ from collections.abc import Iterable from types import TracebackType -import libzim.reader # pyright: ignore[reportMissingModuleSource] -import libzim.search # pyright: ignore[reportMissingModuleSource] -import libzim.suggestion # pyright: ignore[reportMissingModuleSource] +from zimscraperlib._extras import missing_extra + +try: + import libzim.reader # pyright: ignore[reportMissingModuleSource] + import libzim.search # pyright: ignore[reportMissingModuleSource] + import libzim.suggestion # pyright: ignore[reportMissingModuleSource] +except ModuleNotFoundError as exc: + raise missing_extra("zim", exc) from exc from zimscraperlib.zim._libkiwix import CounterMap, convertTags, parseMimetypeCounter diff --git a/src/zimscraperlib/zim/creator.py b/src/zimscraperlib/zim/creator.py index e07c055c..f620b596 100644 --- a/src/zimscraperlib/zim/creator.py +++ b/src/zimscraperlib/zim/creator.py @@ -22,24 +22,22 @@ import weakref from contextlib import suppress from types import TracebackType +from typing import TYPE_CHECKING, Any -import libzim.writer # pyright: ignore[reportMissingModuleSource] -import PIL.Image +from zimscraperlib._extras import missing_extra + +try: + import libzim.writer # pyright: ignore[reportMissingModuleSource] +except ModuleNotFoundError as exc: + raise missing_extra("zim", exc) from exc from zimscraperlib import logger from zimscraperlib.constants import FRONT_ARTICLE_MIMETYPES -from zimscraperlib.filesystem import ( - delete_callback, - get_content_mimetype, - get_file_mimetype, -) -from zimscraperlib.i18n import is_valid_iso_639_3 from zimscraperlib.types import get_mime_for_name from zimscraperlib.typing import Callback from zimscraperlib.zim.indexing import IndexData from zimscraperlib.zim.items import StaticItem from zimscraperlib.zim.metadata import ( - DEFAULT_DEV_ZIM_METADATA, MANDATORY_ZIM_METADATA_KEYS, AnyMetadata, IllustrationBasedMetadata, @@ -65,6 +63,11 @@ def mimetype_for( ) -> str | None: """mimetype as provided or guessed from fpath, path or content""" if not mimetype: + from zimscraperlib.filesystem import ( # noqa: PLC0415 + get_content_mimetype, + get_file_mimetype, + ) + mimetype = ( get_file_mimetype(fpath) if fpath @@ -141,8 +144,11 @@ def config_indexing( Note: title indexing is always performed by libzim and cannot be disabled via this method; only the full-text index is toggled.""" language = language or self._get_first_language_metadata_value() or "" - if indexing and not is_valid_iso_639_3(language): - raise ValueError("Not a valid ISO-639-3 language code") + if indexing: + from zimscraperlib.i18n import is_valid_iso_639_3 # noqa: PLC0415 + + if not is_valid_iso_639_3(language): + raise ValueError("Not a valid ISO-639-3 language code") super().config_indexing(indexing, language) self.__indexing_configured = True self.__indexing_value = indexing @@ -161,7 +167,9 @@ def _log_metadata(self): # illustration mandates an Image if re.match(r"^Illustration_(\d+)x(\d+)@(\d+)$", name): try: - with PIL.Image.open(io.BytesIO(metadata.libzim_value)) as img: + from PIL import Image # noqa: PLC0415 + + with Image.open(io.BytesIO(metadata.libzim_value)) as img: logger.debug( f"Metadata: {name} is a {len(metadata.libzim_value)} bytes " f"{img.size[0]}x{img.size[1]}px {img.format} Image" @@ -172,6 +180,10 @@ def _log_metadata(self): # bytes are either encoded string or arbitrary data if isinstance(metadata.value, bytes | io.BytesIO): + from zimscraperlib.filesystem import ( # noqa: PLC0415 + get_content_mimetype, + ) + raw_value = ( metadata.value if isinstance(metadata.value, bytes) @@ -320,6 +332,10 @@ def config_dev_metadata( Extra metadata can be passed, and they are not checked for proper key prefix """ + from zimscraperlib.zim.metadata import ( # noqa: PLC0415 + DEFAULT_DEV_ZIM_METADATA, + ) + return self.config_metadata( std_metadata=DEFAULT_DEV_ZIM_METADATA, extra_metadata=( @@ -385,6 +401,8 @@ def add_item_for( hints[libzim.writer.Hint.COMPRESS] = should_compress if delete_fpath and fpath: + from zimscraperlib.filesystem import delete_callback # noqa: PLC0415 + callbacks.append(Callback(func=delete_callback, args=(fpath,))) self.add_item( @@ -526,5 +544,19 @@ def __exit__( _live_creators: weakref.WeakSet[Creator] = weakref.WeakSet() +if TYPE_CHECKING: + DEFAULT_DEV_ZIM_METADATA: StandardMetadataList + atexit.register(Creator._abandon_live_creators) # pyright: ignore[reportPrivateUsage] + + +def __getattr__(name: str) -> Any: + if name == "DEFAULT_DEV_ZIM_METADATA": + from zimscraperlib.zim.metadata import ( # noqa: PLC0415 + DEFAULT_DEV_ZIM_METADATA, + ) + + globals()[name] = DEFAULT_DEV_ZIM_METADATA + return DEFAULT_DEV_ZIM_METADATA + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") diff --git a/src/zimscraperlib/zim/dedup.py b/src/zimscraperlib/zim/dedup.py index 7f9f2cf1..4a6740ac 100644 --- a/src/zimscraperlib/zim/dedup.py +++ b/src/zimscraperlib/zim/dedup.py @@ -2,8 +2,13 @@ import re from typing import Any -import xxhash -from libzim.writer import Hint # pyright: ignore[reportMissingModuleSource] +from zimscraperlib._extras import missing_extra + +try: + import xxhash + from libzim.writer import Hint # pyright: ignore[reportMissingModuleSource] +except ModuleNotFoundError as exc: + raise missing_extra("zim", exc) from exc from zimscraperlib.zim.creator import Creator diff --git a/src/zimscraperlib/zim/filesystem.py b/src/zimscraperlib/zim/filesystem.py index 3b410f07..d3b09b09 100644 --- a/src/zimscraperlib/zim/filesystem.py +++ b/src/zimscraperlib/zim/filesystem.py @@ -30,7 +30,6 @@ from collections.abc import Sequence from zimscraperlib import logger -from zimscraperlib.filesystem import get_file_mimetype from zimscraperlib.types import get_mime_for_name from zimscraperlib.zim import metadata from zimscraperlib.zim.creator import Creator @@ -45,6 +44,8 @@ def __init__( root: pathlib.Path, filepath: pathlib.Path, ): + from zimscraperlib.filesystem import get_file_mimetype # noqa: PLC0415 + super().__init__() self.root = root self.filepath = filepath diff --git a/src/zimscraperlib/zim/indexing.py b/src/zimscraperlib/zim/indexing.py index 24e0412e..10da963a 100644 --- a/src/zimscraperlib/zim/indexing.py +++ b/src/zimscraperlib/zim/indexing.py @@ -3,8 +3,13 @@ import io import pathlib -import libzim.writer # pyright: ignore[reportMissingModuleSource] -import pymupdf # pyright: ignore[reportMissingTypeStubs] +from zimscraperlib._extras import missing_extra + +try: + import libzim.writer # pyright: ignore[reportMissingModuleSource] + import pymupdf # pyright: ignore[reportMissingTypeStubs] +except ModuleNotFoundError as exc: + raise missing_extra("zim", exc) from exc from zimscraperlib import logger diff --git a/src/zimscraperlib/zim/items.py b/src/zimscraperlib/zim/items.py index 267ea60e..f2bf8f7d 100644 --- a/src/zimscraperlib/zim/items.py +++ b/src/zimscraperlib/zim/items.py @@ -8,9 +8,13 @@ from collections.abc import Callable from typing import Any -import libzim.writer # pyright: ignore[reportMissingModuleSource] +from zimscraperlib._extras import missing_extra + +try: + import libzim.writer # pyright: ignore[reportMissingModuleSource] +except ModuleNotFoundError as exc: + raise missing_extra("zim", exc) from exc -from zimscraperlib.filesystem import get_content_mimetype, get_file_mimetype from zimscraperlib.zim.indexing import ( IndexData, get_epub_index_data, @@ -149,6 +153,10 @@ def get_contentprovider(self) -> libzim.writer.ContentProvider: def _get_auto_index(self): """Populate item index data and title automatically from content""" + from zimscraperlib.filesystem import ( # noqa: PLC0415 + get_content_mimetype, + get_file_mimetype, + ) # content was set manually content = getattr(self, "content", None) diff --git a/src/zimscraperlib/zim/metadata.py b/src/zimscraperlib/zim/metadata.py index 79e13907..40ded99d 100644 --- a/src/zimscraperlib/zim/metadata.py +++ b/src/zimscraperlib/zim/metadata.py @@ -5,9 +5,14 @@ from collections.abc import Iterable from dataclasses import asdict, dataclass, fields from itertools import filterfalse -from typing import Any, TypeVar +from typing import TYPE_CHECKING, Any, TypeVar -import regex +from zimscraperlib._extras import missing_extra + +try: + import regex +except ModuleNotFoundError as exc: + raise missing_extra("zim", exc) from exc from zimscraperlib.constants import ( DEFAULT_ZIM_ILLLUSTRATION_SCALE, @@ -17,8 +22,6 @@ MAXIMUM_LONG_DESCRIPTION_METADATA_LENGTH, RECOMMENDED_MAX_TITLE_LENGTH, ) -from zimscraperlib.i18n import is_valid_iso_639_3 -from zimscraperlib.image.probing import is_valid_image from zimscraperlib.inputs import unique_values from zimscraperlib.typing import SupportsRead, SupportsSeekableRead @@ -311,6 +314,8 @@ def get_cleaned_value(self, value: Iterable[str] | str) -> list[str]: elif self.require_deduplication: value = unique_values(value) if self.oz_only_iso636_3_allowed and APPLY_RECOMMENDATIONS: + from zimscraperlib.i18n import is_valid_iso_639_3 # noqa: PLC0415 + invalid_codes = list(filterfalse(is_valid_iso_639_3, value)) if invalid_codes: raise ValueError( @@ -356,6 +361,8 @@ def __init__( # native type is PNG image buffer def get_cleaned_value(self, value: bytes | io.IOBase | io.BytesIO) -> bytes: + from zimscraperlib.image.probing import is_valid_image # noqa: PLC0415 + value = self.get_binary_from(value) if not is_valid_image( image=value, @@ -528,21 +535,29 @@ def __init__(self, name: str, value: str) -> None: MANDATORY_ZIM_METADATA_KEYS: list[str] = StandardMetadataList.get_reserved_names() - -DEFAULT_DEV_ZIM_METADATA = StandardMetadataList( - Name=NameMetadata("Test Name"), - Title=TitleMetadata("Test Title"), - Creator=CreatorMetadata("Test Creator"), - Publisher=PublisherMetadata("Test Publisher"), - Date=DateMetadata(dt.date(2023, 1, 1)), - Description=DescriptionMetadata("Test Description"), - Language=LanguageMetadata("fra"), - # blank 48x48 transparent PNG - Illustration_48x48_at_1=DefaultIllustrationMetadata( - base64.b64decode( - "iVBORw0KGgoAAAANSUhEUgAAADAAAAAwAQMAAABtzGvEAAAAGXRFWHRTb2Z0d2FyZQBB" - "ZG9iZSBJbWFnZVJlYWR5ccllPAAAAANQTFRFR3BMgvrS0gAAAAF0Uk5TAEDm2GYAAAAN" - "SURBVBjTY2AYBdQEAAFQAAGn4toWAAAAAElFTkSuQmCC" +if TYPE_CHECKING: + DEFAULT_DEV_ZIM_METADATA: StandardMetadataList + + +def __getattr__(name: str) -> Any: + if name != "DEFAULT_DEV_ZIM_METADATA": + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") + + default_metadata = StandardMetadataList( + Name=NameMetadata("Test Name"), + Title=TitleMetadata("Test Title"), + Creator=CreatorMetadata("Test Creator"), + Publisher=PublisherMetadata("Test Publisher"), + Date=DateMetadata(dt.date(2023, 1, 1)), + Description=DescriptionMetadata("Test Description"), + Language=LanguageMetadata("fra"), + Illustration_48x48_at_1=DefaultIllustrationMetadata( + base64.b64decode( + "iVBORw0KGgoAAAANSUhEUgAAADAAAAAwAQMAAABtzGvEAAAAGXRFWHRTb2Z0d2FyZQBB" + "ZG9iZSBJbWFnZVJlYWR5ccllPAAAAANQTFRFR3BMgvrS0gAAAAF0Uk5TAEDm2GYAAAAN" + "SURBVBjTY2AYBdQEAAFQAAGn4toWAAAAAElFTkSuQmCC" + ), ), - ), -) + ) + globals()[name] = default_metadata + return default_metadata diff --git a/src/zimscraperlib/zim/providers.py b/src/zimscraperlib/zim/providers.py index 54f81628..86b096cd 100644 --- a/src/zimscraperlib/zim/providers.py +++ b/src/zimscraperlib/zim/providers.py @@ -10,8 +10,12 @@ import pathlib from collections.abc import Generator -import libzim.writer # pyright: ignore[reportMissingModuleSource] -import requests +from zimscraperlib._extras import missing_extra + +try: + import libzim.writer # pyright: ignore[reportMissingModuleSource] +except ModuleNotFoundError as exc: + raise missing_extra("zim", exc) from exc class FileProvider(libzim.writer.FileProvider): @@ -67,6 +71,11 @@ class URLProvider(libzim.writer.ContentProvider): def __init__(self, url: str, size: int | None = None, ref: object | None = None): from zimscraperlib.download import get_retry_adapter # noqa: PLC0415 + try: + import requests # noqa: PLC0415 + except ModuleNotFoundError as exc: + raise missing_extra("download", exc) from exc + super().__init__() self.url = url self.size = size if size is not None else self.get_size_of(url) diff --git a/tests/conftest.py b/tests/conftest.py index af4a3c78..bbc39c85 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -2,9 +2,6 @@ import zipfile import pytest -import requests - -from zimscraperlib.download import stream_file def pytest_addoption(parser: pytest.Parser): @@ -90,6 +87,8 @@ def gzip_html_url() -> str: def _serves_gzipped(url: str) -> bool: """Whether this URL answers, and answers gzipped. Never raises.""" + import requests # noqa: PLC0415 + try: response = requests.get( url, headers={"Accept-Encoding": "gzip"}, timeout=10, stream=True @@ -115,6 +114,12 @@ def file_src(fname: str) -> pathlib.Path: return pathlib.Path(__file__).parent.joinpath("files", fname) +def _stream_file(url: str, dst: pathlib.Path) -> None: + from zimscraperlib.download import stream_file # noqa: PLC0415 + + stream_file(url, dst) + + @pytest.fixture(scope="module") def png_image() -> pathlib.Path: return file_src("commons48.png") @@ -200,7 +205,7 @@ def valid_user_agent(): def small_zim_file(tmpdir_factory: pytest.TempdirFactory) -> pathlib.Path: dst = pathlib.Path(tmpdir_factory.mktemp("data") / "small.zim") - stream_file( + _stream_file( "https://github.com/openzim/zim-testing-suite/raw/v0.3/data/nons/small.zim", dst, ) @@ -211,7 +216,7 @@ def small_zim_file(tmpdir_factory: pytest.TempdirFactory) -> pathlib.Path: def ns_zim_file(tmpdir_factory: pytest.TempdirFactory) -> pathlib.Path: dst = pathlib.Path(tmpdir_factory.mktemp("data") / "ns.zim") - stream_file( + _stream_file( "https://github.com/openzim/zim-testing-suite/raw/v0.4/data/withns/" "wikibooks_be_all_nopic_2017-02.zim", dst, @@ -223,7 +228,7 @@ def ns_zim_file(tmpdir_factory: pytest.TempdirFactory) -> pathlib.Path: def real_zim_file(tmpdir_factory: pytest.TempdirFactory) -> pathlib.Path: dst = pathlib.Path(tmpdir_factory.mktemp("data") / "small.zim") - stream_file( + _stream_file( "https://github.com/openzim/zim-testing-suite/raw/v0.3/data/withns/" "wikipedia_en_climate_change_nopic_2020-01.zim", dst, diff --git a/tests/test_extras.py b/tests/test_extras.py new file mode 100644 index 00000000..a6756eb2 --- /dev/null +++ b/tests/test_extras.py @@ -0,0 +1,252 @@ +import importlib.metadata +import re +import subprocess +import sys + +import pytest + +RUNTIME_EXTRA_DEPENDENCIES: dict[str, set[str]] = { + "zim": { + "libzim", + "xxhash", + "regex", + "pymupdf-lite", + "types-xxhash", + }, + "image": { + "pillow", + "colorthief", + "piexif", + "optimize-images", + "python-resize-image", + "cairosvg", + }, + "video": set(), + "download": {"requests", "urllib3", "yt-dlp"}, + "filesystem": {"python-magic"}, + "html": {"beautifulsoup4", "lxml"}, + "rewriting": { + "beautifulsoup4", + "lxml", + "idna", + "tinycss2", + "tree-sitter", + "tree-sitter-javascript", + }, + "i18n": {"babel", "iso639-lang"}, +} + +EXTRA_ROOTS: dict[str, set[str]] = { + "zim": {"libzim", "regex", "pymupdf", "xxhash"}, + "image": { + "PIL", + "cairosvg", + "colorthief", + "piexif", + "optimize_images", + "resizeimage", + }, + "video": set(), + "download": {"requests", "urllib3", "yt_dlp"}, + "filesystem": {"magic"}, + "html": {"bs4", "lxml"}, + "rewriting": { + "bs4", + "lxml", + "idna", + "tinycss2", + "tree_sitter", + "tree_sitter_javascript", + }, + "i18n": {"babel", "iso639"}, +} + +OPTIONAL_ROOTS: set[str] = set() +for roots in EXTRA_ROOTS.values(): + OPTIONAL_ROOTS.update(roots) + +CHILD = """ +import importlib +import sys + +blocked = set(sys.argv[1].split(",")) +module = sys.argv[2] + +class Blocker: + def find_spec(self, fullname, path=None, target=None): + root = fullname.split(".", 1)[0] + if root in blocked: + raise ModuleNotFoundError(f"No module named {root!r}", name=root) + return None + +sys.meta_path.insert(0, Blocker()) +try: + importlib.import_module(module) +except ImportError as exc: + print(str(exc)) +else: + raise SystemExit(0) +raise SystemExit(1) +""" + + +def _run_child(blocked: str, module: str) -> subprocess.CompletedProcess[str]: + return subprocess.run( + [sys.executable, "-c", CHILD, blocked, module], + capture_output=True, + text=True, + check=False, + ) + + +def _requirement_name(requirement: str) -> str: + match = re.match(r"^([A-Za-z0-9_.-]+)", requirement) + assert match is not None + return match.group(1).lower() + + +def _names_for_extra(extra: str | None) -> set[str]: + requirements = importlib.metadata.requires("zimscraperlib") or [] + return { + _requirement_name(requirement) + for requirement in requirements + if (extra is None and "extra ==" not in requirement) + or (extra is not None and f"extra == '{extra}'" in requirement) + } + + +def test_runtime_extras_are_declared() -> None: + declared = set( + importlib.metadata.metadata("zimscraperlib").get_all("Provides-Extra") or [] + ) + assert set(RUNTIME_EXTRA_DEPENDENCIES) <= declared + + +def test_core_dependencies_are_minimal() -> None: + assert _names_for_extra(None) == {"beartype"} + + +@pytest.mark.parametrize(("extra", "expected"), RUNTIME_EXTRA_DEPENDENCIES.items()) +def test_extra_dependencies(extra: str, expected: set[str]) -> None: + assert _names_for_extra(extra) == expected + + +def test_all_extra_covers_runtime_dependencies() -> None: + expected: set[str] = set() + for dependencies in RUNTIME_EXTRA_DEPENDENCIES.values(): + expected.update(dependencies) + assert _names_for_extra("all") == expected + + +@pytest.mark.parametrize( + ("extra", "module"), + [ + ("download", "zimscraperlib.download"), + ("filesystem", "zimscraperlib.filesystem"), + ("html", "zimscraperlib.html"), + ("i18n", "zimscraperlib.i18n"), + ("image", "zimscraperlib.image"), + ("rewriting", "zimscraperlib.rewriting.css"), + ("zim", "zimscraperlib.zim"), + ], +) +def test_missing_extra_message(extra: str, module: str) -> None: + result = _run_child(",".join(sorted(EXTRA_ROOTS[extra])), module) + assert result.returncode != 0 + assert any(f"'{root}'" in result.stdout for root in EXTRA_ROOTS[extra]) + assert f"zimscraperlib[{extra}]" in result.stdout + assert "python -m pip install" in result.stdout + + +def test_core_import_needs_no_optional_dependencies() -> None: + result = _run_child(",".join(sorted(OPTIONAL_ROOTS)), "zimscraperlib") + assert result.returncode == 0 + assert result.stdout == "" + + +def test_video_import_needs_no_python_dependencies() -> None: + result = _run_child(",".join(sorted(OPTIONAL_ROOTS)), "zimscraperlib.video") + assert result.returncode == 0 + assert result.stdout == "" + + +def _remove_module(monkeypatch: pytest.MonkeyPatch, name: str) -> None: + for key in tuple(sys.modules): + if key == name or key.startswith(f"{name}."): + monkeypatch.delitem(sys.modules, key, raising=False) + + +def _block_module(monkeypatch: pytest.MonkeyPatch, name: str) -> None: + _remove_module(monkeypatch, name) + monkeypatch.setitem(sys.modules, name, None) + + +def _import_without(monkeypatch: pytest.MonkeyPatch, extra: str, module: str) -> None: + _remove_module(monkeypatch, module) + for root in EXTRA_ROOTS[extra]: + _block_module(monkeypatch, root) + with pytest.raises(ImportError, match=rf"zimscraperlib\[{extra}\]"): + importlib.import_module(module) + + +@pytest.mark.installed +@pytest.mark.parametrize( + ("extra", "module"), + [ + ("zim", "zimscraperlib.zim"), + ("zim", "zimscraperlib.zim.archive"), + ("zim", "zimscraperlib.zim.creator"), + ("zim", "zimscraperlib.zim.dedup"), + ("zim", "zimscraperlib.zim.indexing"), + ("zim", "zimscraperlib.zim.items"), + ("zim", "zimscraperlib.zim.metadata"), + ("zim", "zimscraperlib.zim.providers"), + ("image", "zimscraperlib.image.conversion"), + ("image", "zimscraperlib.image.optimization"), + ("image", "zimscraperlib.image.probing"), + ("image", "zimscraperlib.image.transformation"), + ("image", "zimscraperlib.image.utils"), + ("rewriting", "zimscraperlib.rewriting.css"), + ("rewriting", "zimscraperlib.rewriting.html"), + ("rewriting", "zimscraperlib.rewriting.js_ast"), + ("rewriting", "zimscraperlib.rewriting.url_rewriting"), + ("download", "zimscraperlib.download"), + ("filesystem", "zimscraperlib.filesystem"), + ("html", "zimscraperlib.html"), + ("i18n", "zimscraperlib.i18n"), + ], +) +def test_missing_extra_error( + monkeypatch: pytest.MonkeyPatch, extra: str, module: str +) -> None: + _import_without(monkeypatch, extra, module) + + +@pytest.mark.installed +def test_url_provider_missing_download_extra(monkeypatch: pytest.MonkeyPatch) -> None: + importlib.import_module("zimscraperlib.download") + _block_module(monkeypatch, "requests") + + from zimscraperlib.zim.providers import URLProvider # noqa: PLC0415 + + with pytest.raises(ImportError, match=r"zimscraperlib\[download\]"): + URLProvider("https://example.com") + + +@pytest.mark.installed +def test_creator_lazy_default_metadata(monkeypatch: pytest.MonkeyPatch) -> None: + _remove_module(monkeypatch, "zimscraperlib.zim.creator") + creator = importlib.import_module("zimscraperlib.zim.creator") + + assert creator.DEFAULT_DEV_ZIM_METADATA.Name.value == "Test Name" + assert creator.DEFAULT_DEV_ZIM_METADATA is creator.DEFAULT_DEV_ZIM_METADATA + unknown = "UNKNOWN_ATTRIBUTE" + with pytest.raises(AttributeError): + getattr(creator, unknown) + + +def test_missing_extra_without_module_name() -> None: + from zimscraperlib._extras import missing_extra # noqa: PLC0415 + + with pytest.raises(ImportError, match="an optional dependency"): + missing_extra("test", ModuleNotFoundError()) From ae92070429a055df6ad5b86307e8e0a95151b7a7 Mon Sep 17 00:00:00 2001 From: pawank925 Date: Thu, 26 Nov 2026 16:30:09 +0530 Subject: [PATCH 2/4] Address review feedback on optional dependency extras - Move to ubuntu-26.04 and drop unnecessary explicit x64 architecture. - Move the missing_extra import into image conversion's except block. - Make path_from dependency-free so video can import it without filesystem. - Restore conftest imports and install download in the focused extras job. - Mark the extras change as breaking and clarify the README download row. - Keep DEFAULT_DEV_ZIM_METADATA explicit and eager without requiring i18n or image. --- .github/workflows/QA.yaml | 6 +-- .github/workflows/Tests.yaml | 18 +++---- CHANGELOG.md | 7 +-- README.md | 2 +- src/zimscraperlib/_paths.py | 23 ++++++++ src/zimscraperlib/filesystem.py | 28 +++------- src/zimscraperlib/image/conversion.py | 4 +- src/zimscraperlib/video/encoding.py | 3 +- src/zimscraperlib/zim/creator.py | 21 +------- src/zimscraperlib/zim/metadata.py | 75 ++++++++++++++++----------- tests/conftest.py | 17 +++--- tests/test_extras.py | 11 ++-- 12 files changed, 105 insertions(+), 110 deletions(-) create mode 100644 src/zimscraperlib/_paths.py diff --git a/.github/workflows/QA.yaml b/.github/workflows/QA.yaml index a6fb4847..5e70e73f 100644 --- a/.github/workflows/QA.yaml +++ b/.github/workflows/QA.yaml @@ -8,7 +8,7 @@ on: jobs: generate-rules: - runs-on: ubuntu-24.04 + runs-on: ubuntu-26.04 steps: - name: Checkout repo @@ -41,7 +41,7 @@ jobs: retention-days: 1 check-python-qa: - runs-on: ubuntu-24.04 + runs-on: ubuntu-26.04 needs: generate-rules steps: @@ -74,7 +74,7 @@ jobs: run: inv check-type check-javascript-qa: - runs-on: ubuntu-24.04 + runs-on: ubuntu-26.04 needs: generate-rules steps: diff --git a/.github/workflows/Tests.yaml b/.github/workflows/Tests.yaml index 5c9c4836..940100cd 100644 --- a/.github/workflows/Tests.yaml +++ b/.github/workflows/Tests.yaml @@ -8,7 +8,7 @@ on: jobs: generate-rules: - runs-on: ubuntu-24.04 + runs-on: ubuntu-26.04 steps: - name: Checkout repo @@ -41,7 +41,7 @@ jobs: retention-days: 1 check-extras-errors: - runs-on: ubuntu-24.04 + runs-on: ubuntu-26.04 steps: - name: Checkout repo @@ -51,18 +51,17 @@ jobs: uses: actions/setup-python@v7 with: python-version-file: pyproject.toml - architecture: x64 - - name: Install minimal dependencies (and project) + - name: Install test dependencies (and project) run: | pip install -U pip - pip install -e .[test] + pip install -e '.[test,download]' - name: Check optional dependency errors run: pytest -q tests/test_extras.py check-extras: - runs-on: ubuntu-24.04 + runs-on: ubuntu-26.04 needs: generate-rules strategy: fail-fast: false @@ -100,7 +99,6 @@ jobs: uses: actions/setup-python@v7 with: python-version-file: pyproject.toml - architecture: x64 - name: Install dependencies (and project) run: | @@ -115,7 +113,7 @@ jobs: run: python -c "import importlib; importlib.import_module('${{ matrix.module }}')" run-python-tests: - runs-on: ubuntu-24.04 + runs-on: ubuntu-26.04 needs: generate-rules steps: @@ -156,7 +154,7 @@ jobs: python3 -m build --sdist --wheel run-js-tests: - runs-on: ubuntu-24.04 + runs-on: ubuntu-26.04 needs: generate-rules steps: @@ -197,7 +195,7 @@ jobs: working-directory: javascript build-docs: # validate that doc can be built - runs-on: ubuntu-24.04 + runs-on: ubuntu-26.04 needs: generate-rules steps: diff --git a/CHANGELOG.md b/CHANGELOG.md index e0310f36..900eacd9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,13 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] -### Added - -- Optional dependency groups `zim`, `image`, `video`, `download`, `filesystem`, `html`, `rewriting`, `i18n` and `all`; the base install now only requires `beartype` (#244) -- Missing optional dependencies now raise an `ImportError` naming the extra to install (#244) - ### Changed +- **Breaking:** Runtime dependencies are now optional extras (`zim`, `image`, `video`, `download`, `filesystem`, `html`, `rewriting`, `i18n`, `all`); a base install only provides `beartype`, so install `zimscraperlib[all]` (or the extras you need) to keep the previous behavior (#244) +- Missing optional dependencies now raise an `ImportError` naming the extra to install (#244) - Cross-feature imports are now resolved where they are used, so each extra only needs its own dependencies (#244) ### Fixed diff --git a/README.md b/README.md index f77b9584..e04c07e4 100644 --- a/README.md +++ b/README.md @@ -48,7 +48,7 @@ Importing a module whose extra is missing raises an `ImportError` naming the ext | `zim` | `zimscraperlib.zim` | none (`libzim` ships wheels, except on unsupported platforms) | | `image` | `zimscraperlib.image` | libcairo for SVG conversion, gifsicle (>=1.92) for GIF optimization | | `video` | `zimscraperlib.video` | FFmpeg | -| `download` | `zimscraperlib.download` | none; wget is only needed if your scraper calls it itself | +| `download` | `zimscraperlib.download` | none; downloads use `requests`, not `wget` | | `filesystem` | `zimscraperlib.filesystem` and MIME-type detection | libmagic | | `html` | `zimscraperlib.html` | none | | `rewriting` | `zimscraperlib.rewriting` | none | diff --git a/src/zimscraperlib/_paths.py b/src/zimscraperlib/_paths.py new file mode 100644 index 00000000..d3385bf2 --- /dev/null +++ b/src/zimscraperlib/_paths.py @@ -0,0 +1,23 @@ +"""Dependency-free helpers shared by features with different extras.""" + +import pathlib +from contextlib import contextmanager +from tempfile import TemporaryDirectory +from typing import Any + + +@contextmanager +def path_from(path: pathlib.Path | TemporaryDirectory[Any] | str): + """Context manager to get a Path from a path as string, Path or TemporaryDirectory + + Since scraperlib wants to manipulate only Path, scrapers might often needs this + to create a path from what they have, especially since TemporaryDirectory context + manager returns a string which is not really handy. + """ + if isinstance(path, pathlib.Path): + yield path + elif isinstance(path, TemporaryDirectory): + with path as pathname: + yield pathlib.Path(pathname) + else: + yield pathlib.Path(path) diff --git a/src/zimscraperlib/filesystem.py b/src/zimscraperlib/filesystem.py index c2b452eb..593ef92e 100644 --- a/src/zimscraperlib/filesystem.py +++ b/src/zimscraperlib/filesystem.py @@ -3,11 +3,16 @@ Shortcuts to retrieve mime type using magic""" import pathlib -from contextlib import contextmanager -from tempfile import TemporaryDirectory -from typing import Any from zimscraperlib._extras import missing_extra +from zimscraperlib._paths import path_from + +__all__ = [ + "delete_callback", + "get_content_mimetype", + "get_file_mimetype", + "path_from", +] try: import magic @@ -47,20 +52,3 @@ def get_content_mimetype(content: bytes | str) -> str: def delete_callback(fpath: pathlib.Path): """helper deleting passed filepath""" fpath.unlink(missing_ok=True) - - -@contextmanager -def path_from(path: pathlib.Path | TemporaryDirectory[Any] | str): - """Context manager to get a Path from a path as string, Path or TemporaryDirectory - - Since scraperlib wants to manipulate only Path, scrapers might often needs this - to create a path from what they have, especially since TemporaryDirectory context - manager returns a string which is not really handy. - """ - if isinstance(path, pathlib.Path): - yield path - elif isinstance(path, TemporaryDirectory): - with path as pathname: - yield pathlib.Path(pathname) - else: - yield pathlib.Path(path) diff --git a/src/zimscraperlib/image/conversion.py b/src/zimscraperlib/image/conversion.py index a41faf55..1d201425 100644 --- a/src/zimscraperlib/image/conversion.py +++ b/src/zimscraperlib/image/conversion.py @@ -2,12 +2,12 @@ import pathlib from typing import Any -from zimscraperlib._extras import missing_extra - try: import cairosvg # pyright: ignore[reportMissingTypeStubs] from PIL.Image import open as pilopen except ModuleNotFoundError as exc: + from zimscraperlib._extras import missing_extra + raise missing_extra("image", exc) from exc from zimscraperlib.constants import ALPHA_NOT_SUPPORTED diff --git a/src/zimscraperlib/video/encoding.py b/src/zimscraperlib/video/encoding.py index a8a58ba9..3dc1de51 100644 --- a/src/zimscraperlib/video/encoding.py +++ b/src/zimscraperlib/video/encoding.py @@ -5,6 +5,7 @@ from copy import deepcopy from zimscraperlib import logger +from zimscraperlib._paths import path_from from zimscraperlib.logging import nicer_args_join @@ -53,8 +54,6 @@ def reencode( failsafe - Run in failsafe mode """ - from zimscraperlib.filesystem import path_from # noqa: PLC0415 - with path_from(existing_tmp_path or tempfile.TemporaryDirectory()) as tmp_dir: tmp_path = pathlib.Path(tmp_dir).joinpath(f"video.tmp{dst_path.suffix}") args = _build_ffmpeg_args( diff --git a/src/zimscraperlib/zim/creator.py b/src/zimscraperlib/zim/creator.py index f620b596..52e61989 100644 --- a/src/zimscraperlib/zim/creator.py +++ b/src/zimscraperlib/zim/creator.py @@ -22,7 +22,6 @@ import weakref from contextlib import suppress from types import TracebackType -from typing import TYPE_CHECKING, Any from zimscraperlib._extras import missing_extra @@ -38,6 +37,7 @@ from zimscraperlib.zim.indexing import IndexData from zimscraperlib.zim.items import StaticItem from zimscraperlib.zim.metadata import ( + DEFAULT_DEV_ZIM_METADATA, MANDATORY_ZIM_METADATA_KEYS, AnyMetadata, IllustrationBasedMetadata, @@ -332,10 +332,6 @@ def config_dev_metadata( Extra metadata can be passed, and they are not checked for proper key prefix """ - from zimscraperlib.zim.metadata import ( # noqa: PLC0415 - DEFAULT_DEV_ZIM_METADATA, - ) - return self.config_metadata( std_metadata=DEFAULT_DEV_ZIM_METADATA, extra_metadata=( @@ -544,19 +540,4 @@ def __exit__( _live_creators: weakref.WeakSet[Creator] = weakref.WeakSet() -if TYPE_CHECKING: - DEFAULT_DEV_ZIM_METADATA: StandardMetadataList - - atexit.register(Creator._abandon_live_creators) # pyright: ignore[reportPrivateUsage] - - -def __getattr__(name: str) -> Any: - if name == "DEFAULT_DEV_ZIM_METADATA": - from zimscraperlib.zim.metadata import ( # noqa: PLC0415 - DEFAULT_DEV_ZIM_METADATA, - ) - - globals()[name] = DEFAULT_DEV_ZIM_METADATA - return DEFAULT_DEV_ZIM_METADATA - raise AttributeError(f"module {__name__!r} has no attribute {name!r}") diff --git a/src/zimscraperlib/zim/metadata.py b/src/zimscraperlib/zim/metadata.py index 40ded99d..623b973f 100644 --- a/src/zimscraperlib/zim/metadata.py +++ b/src/zimscraperlib/zim/metadata.py @@ -5,7 +5,7 @@ from collections.abc import Iterable from dataclasses import asdict, dataclass, fields from itertools import filterfalse -from typing import TYPE_CHECKING, Any, TypeVar +from typing import Any, TypeVar from zimscraperlib._extras import missing_extra @@ -295,8 +295,16 @@ class TextListBasedMetadata(MetadataBase[list[str]]): value: list[str] # we accept single str input but store as list[str] require_textlist_cleanup = True require_utf8_encoding = True + _skip_validation: bool = False - def __init__(self, value: Iterable[str] | str, name: str | None = None) -> None: + def __init__( + self, + value: Iterable[str] | str, + name: str | None = None, + *, + skip_validation: bool = False, + ) -> None: + self._skip_validation = skip_validation super().__init__(value=value, name=name) # native type is list[str] @@ -313,7 +321,11 @@ def get_cleaned_value(self, value: Iterable[str] | str) -> list[str]: raise ValueError("Duplicate entries not allowed") elif self.require_deduplication: value = unique_values(value) - if self.oz_only_iso636_3_allowed and APPLY_RECOMMENDATIONS: + if ( + self.oz_only_iso636_3_allowed + and APPLY_RECOMMENDATIONS + and not self._skip_validation + ): from zimscraperlib.i18n import is_valid_iso_639_3 # noqa: PLC0415 invalid_codes = list(filterfalse(is_valid_iso_639_3, value)) @@ -353,17 +365,26 @@ class IllustrationBasedMetadata(Metadata): value: bytes meta_mimetype = "image/png" + _skip_validation: bool = False def __init__( - self, value: bytes | io.IOBase | io.BytesIO, name: str | None = None + self, + value: bytes | io.IOBase | io.BytesIO, + name: str | None = None, + *, + skip_validation: bool = False, ) -> None: + self._skip_validation = skip_validation super().__init__(value=value, name=name) # native type is PNG image buffer def get_cleaned_value(self, value: bytes | io.IOBase | io.BytesIO) -> bytes: + value = self.get_binary_from(value) + if self._skip_validation: + return value + from zimscraperlib.image.probing import is_valid_image # noqa: PLC0415 - value = self.get_binary_from(value) if not is_valid_image( image=value, imformat="PNG", @@ -535,29 +556,23 @@ def __init__(self, name: str, value: str) -> None: MANDATORY_ZIM_METADATA_KEYS: list[str] = StandardMetadataList.get_reserved_names() -if TYPE_CHECKING: - DEFAULT_DEV_ZIM_METADATA: StandardMetadataList - - -def __getattr__(name: str) -> Any: - if name != "DEFAULT_DEV_ZIM_METADATA": - raise AttributeError(f"module {__name__!r} has no attribute {name!r}") - - default_metadata = StandardMetadataList( - Name=NameMetadata("Test Name"), - Title=TitleMetadata("Test Title"), - Creator=CreatorMetadata("Test Creator"), - Publisher=PublisherMetadata("Test Publisher"), - Date=DateMetadata(dt.date(2023, 1, 1)), - Description=DescriptionMetadata("Test Description"), - Language=LanguageMetadata("fra"), - Illustration_48x48_at_1=DefaultIllustrationMetadata( - base64.b64decode( - "iVBORw0KGgoAAAANSUhEUgAAADAAAAAwAQMAAABtzGvEAAAAGXRFWHRTb2Z0d2FyZQBB" - "ZG9iZSBJbWFnZVJlYWR5ccllPAAAAANQTFRFR3BMgvrS0gAAAAF0Uk5TAEDm2GYAAAAN" - "SURBVBjTY2AYBdQEAAFQAAGn4toWAAAAAElFTkSuQmCC" - ), +# Both bundled values are known-valid; skipping their validation keeps the `zim` +# extra independent from the `image` and `i18n` extras. +DEFAULT_DEV_ZIM_METADATA = StandardMetadataList( + Name=NameMetadata("Test Name"), + Title=TitleMetadata("Test Title"), + Creator=CreatorMetadata("Test Creator"), + Publisher=PublisherMetadata("Test Publisher"), + Date=DateMetadata(dt.date(2023, 1, 1)), + Description=DescriptionMetadata("Test Description"), + Language=LanguageMetadata("fra", skip_validation=True), + # blank 48x48 transparent PNG + Illustration_48x48_at_1=DefaultIllustrationMetadata( + base64.b64decode( + "iVBORw0KGgoAAAANSUhEUgAAADAAAAAwAQMAAABtzGvEAAAAGXRFWHRTb2Z0d2FyZQBB" + "ZG9iZSBJbWFnZVJlYWR5ccllPAAAAANQTFRFR3BMgvrS0gAAAAF0Uk5TAEDm2GYAAAAN" + "SURBVBjTY2AYBdQEAAFQAAGn4toWAAAAAElFTkSuQmCC" ), - ) - globals()[name] = default_metadata - return default_metadata + skip_validation=True, + ), +) diff --git a/tests/conftest.py b/tests/conftest.py index bbc39c85..af4a3c78 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -2,6 +2,9 @@ import zipfile import pytest +import requests + +from zimscraperlib.download import stream_file def pytest_addoption(parser: pytest.Parser): @@ -87,8 +90,6 @@ def gzip_html_url() -> str: def _serves_gzipped(url: str) -> bool: """Whether this URL answers, and answers gzipped. Never raises.""" - import requests # noqa: PLC0415 - try: response = requests.get( url, headers={"Accept-Encoding": "gzip"}, timeout=10, stream=True @@ -114,12 +115,6 @@ def file_src(fname: str) -> pathlib.Path: return pathlib.Path(__file__).parent.joinpath("files", fname) -def _stream_file(url: str, dst: pathlib.Path) -> None: - from zimscraperlib.download import stream_file # noqa: PLC0415 - - stream_file(url, dst) - - @pytest.fixture(scope="module") def png_image() -> pathlib.Path: return file_src("commons48.png") @@ -205,7 +200,7 @@ def valid_user_agent(): def small_zim_file(tmpdir_factory: pytest.TempdirFactory) -> pathlib.Path: dst = pathlib.Path(tmpdir_factory.mktemp("data") / "small.zim") - _stream_file( + stream_file( "https://github.com/openzim/zim-testing-suite/raw/v0.3/data/nons/small.zim", dst, ) @@ -216,7 +211,7 @@ def small_zim_file(tmpdir_factory: pytest.TempdirFactory) -> pathlib.Path: def ns_zim_file(tmpdir_factory: pytest.TempdirFactory) -> pathlib.Path: dst = pathlib.Path(tmpdir_factory.mktemp("data") / "ns.zim") - _stream_file( + stream_file( "https://github.com/openzim/zim-testing-suite/raw/v0.4/data/withns/" "wikibooks_be_all_nopic_2017-02.zim", dst, @@ -228,7 +223,7 @@ def ns_zim_file(tmpdir_factory: pytest.TempdirFactory) -> pathlib.Path: def real_zim_file(tmpdir_factory: pytest.TempdirFactory) -> pathlib.Path: dst = pathlib.Path(tmpdir_factory.mktemp("data") / "small.zim") - _stream_file( + stream_file( "https://github.com/openzim/zim-testing-suite/raw/v0.3/data/withns/" "wikipedia_en_climate_change_nopic_2020-01.zim", dst, diff --git a/tests/test_extras.py b/tests/test_extras.py index a6756eb2..a872e737 100644 --- a/tests/test_extras.py +++ b/tests/test_extras.py @@ -234,15 +234,14 @@ def test_url_provider_missing_download_extra(monkeypatch: pytest.MonkeyPatch) -> @pytest.mark.installed -def test_creator_lazy_default_metadata(monkeypatch: pytest.MonkeyPatch) -> None: +def test_creator_reexports_default_dev_metadata( + monkeypatch: pytest.MonkeyPatch, +) -> None: _remove_module(monkeypatch, "zimscraperlib.zim.creator") + metadata = importlib.import_module("zimscraperlib.zim.metadata") creator = importlib.import_module("zimscraperlib.zim.creator") - assert creator.DEFAULT_DEV_ZIM_METADATA.Name.value == "Test Name" - assert creator.DEFAULT_DEV_ZIM_METADATA is creator.DEFAULT_DEV_ZIM_METADATA - unknown = "UNKNOWN_ATTRIBUTE" - with pytest.raises(AttributeError): - getattr(creator, unknown) + assert creator.DEFAULT_DEV_ZIM_METADATA is metadata.DEFAULT_DEV_ZIM_METADATA def test_missing_extra_without_module_name() -> None: From 540c41fbfe4b6f66fdb61a23ae7e8dff0bd63064 Mon Sep 17 00:00:00 2001 From: pawank925 Date: Thu, 26 Nov 2026 16:34:39 +0530 Subject: [PATCH 3/4] Allow wider bitrate variance on newer ffmpeg FFmpeg on ubuntu-26.04 reports the MP3 fixture bitrate about 1.9% higher than the expected value. Widen the existing test tolerance from 1% to 5%. --- tests/video/test_video.py | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/tests/video/test_video.py b/tests/video/test_video.py index 81c4406f..ee54fb51 100644 --- a/tests/video/test_video.py +++ b/tests/video/test_video.py @@ -162,12 +162,13 @@ def test_get_media_info( assert result.keys() == expected.keys() assert result["codecs"] == expected["codecs"] assert result["duration"] == expected["duration"] - # for bitrate, we need to allow some variability, not all ffmpeg version are - # reporting the same values (e.g. Alpine Linux is reporting 3837275 instead of - # 3818365 for video.mp4) ; we allow 1% variability with following assertion + # for bitrate, we need to allow some variability, not all ffmpeg versions + # report the same values (e.g. Alpine Linux reports 3837275 instead of + # 3818365 for video.mp4, and Ubuntu 26.04 reports 131533 instead of + # 129066 for audio.mp3); we allow 5% variability with the following assertion assert ( abs(100.0 * (result["bitrate"] - expected["bitrate"]) / expected["bitrate"]) - < 1 + < 5 ) From a71372688ff6313bc7e5d00dc1687f1174036509 Mon Sep 17 00:00:00 2001 From: pawank925 Date: Sat, 28 Nov 2026 10:59:25 +0530 Subject: [PATCH 4/4] Address final review feedback on optional extras - Expose path_from from a public zimscraperlib.paths module instead of the hidden _paths module, with its tests alongside the other top-level modules. - Drop the legacy zimscraperlib.filesystem.path_from import path for this major release and document the move in the changelog. - Give the release a dedicated Breaking Changes section at the top of the Unreleased notes. --- CHANGELOG.md | 5 +-- src/zimscraperlib/filesystem.py | 2 -- src/zimscraperlib/{_paths.py => paths.py} | 2 +- src/zimscraperlib/video/encoding.py | 2 +- tests/filesystem/test_filesystem.py | 41 --------------------- tests/test_paths.py | 43 +++++++++++++++++++++++ 6 files changed, 48 insertions(+), 47 deletions(-) rename src/zimscraperlib/{_paths.py => paths.py} (90%) create mode 100644 tests/test_paths.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 900eacd9..5d1f9079 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,9 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] -### Changed +### Breaking Changes -- **Breaking:** Runtime dependencies are now optional extras (`zim`, `image`, `video`, `download`, `filesystem`, `html`, `rewriting`, `i18n`, `all`); a base install only provides `beartype`, so install `zimscraperlib[all]` (or the extras you need) to keep the previous behavior (#244) +- Runtime dependencies are now optional extras (`zim`, `image`, `video`, `download`, `filesystem`, `html`, `rewriting`, `i18n`, `all`); a base install only provides `beartype`, so install `zimscraperlib[all]` (or the extras you need) to keep the previous behavior (#244) +- `path_from` moved from `zimscraperlib.filesystem` to the new public `zimscraperlib.paths` module (#244) - Missing optional dependencies now raise an `ImportError` naming the extra to install (#244) - Cross-feature imports are now resolved where they are used, so each extra only needs its own dependencies (#244) diff --git a/src/zimscraperlib/filesystem.py b/src/zimscraperlib/filesystem.py index 593ef92e..d7d099dc 100644 --- a/src/zimscraperlib/filesystem.py +++ b/src/zimscraperlib/filesystem.py @@ -5,13 +5,11 @@ import pathlib from zimscraperlib._extras import missing_extra -from zimscraperlib._paths import path_from __all__ = [ "delete_callback", "get_content_mimetype", "get_file_mimetype", - "path_from", ] try: diff --git a/src/zimscraperlib/_paths.py b/src/zimscraperlib/paths.py similarity index 90% rename from src/zimscraperlib/_paths.py rename to src/zimscraperlib/paths.py index d3385bf2..1d68f0c4 100644 --- a/src/zimscraperlib/_paths.py +++ b/src/zimscraperlib/paths.py @@ -1,4 +1,4 @@ -"""Dependency-free helpers shared by features with different extras.""" +"""Helpers for building `pathlib.Path` objects from common scraper inputs.""" import pathlib from contextlib import contextmanager diff --git a/src/zimscraperlib/video/encoding.py b/src/zimscraperlib/video/encoding.py index 3dc1de51..3b2c85c6 100644 --- a/src/zimscraperlib/video/encoding.py +++ b/src/zimscraperlib/video/encoding.py @@ -5,8 +5,8 @@ from copy import deepcopy from zimscraperlib import logger -from zimscraperlib._paths import path_from from zimscraperlib.logging import nicer_args_join +from zimscraperlib.paths import path_from def _build_ffmpeg_args( diff --git a/tests/filesystem/test_filesystem.py b/tests/filesystem/test_filesystem.py index a25fcb14..a3b5dc76 100644 --- a/tests/filesystem/test_filesystem.py +++ b/tests/filesystem/test_filesystem.py @@ -1,5 +1,4 @@ import pathlib -from tempfile import TemporaryDirectory from typing import Any import magic @@ -9,7 +8,6 @@ delete_callback, get_content_mimetype, get_file_mimetype, - path_from, ) @@ -62,42 +60,3 @@ def test_delete_callback(tmp_path: pathlib.Path): # wrong path should not be a problem delete_callback(pathlib.Path("/foo.txt")) - - -def test_path_from_tmp_dir(): - tempdir = TemporaryDirectory() - with path_from(tempdir) as tmp_dir: - file = tmp_dir / "file.txt" - file.touch() - assert file.exists() - assert pathlib.Path(tempdir.name).exists() - - assert not pathlib.Path(tempdir.name).exists() - - -def test_path_from_path(): - tempdir = TemporaryDirectory() - tempdir_path = pathlib.Path(tempdir.name) - with path_from(tempdir_path) as tmp_dir: - file = tmp_dir / "file.txt" - file.touch() - assert file.exists() - assert pathlib.Path(tempdir.name).exists() - - assert pathlib.Path(tempdir.name).exists() - tempdir.cleanup() - assert not pathlib.Path(tempdir.name).exists() - - -def test_path_from_str(): - tempdir = TemporaryDirectory() - tempdir_path = pathlib.Path(tempdir.name) - with path_from(str(tempdir_path)) as tmp_dir: - file = tmp_dir / "file.txt" - file.touch() - assert file.exists() - assert pathlib.Path(tempdir.name).exists() - - assert pathlib.Path(tempdir.name).exists() - tempdir.cleanup() - assert not pathlib.Path(tempdir.name).exists() diff --git a/tests/test_paths.py b/tests/test_paths.py new file mode 100644 index 00000000..0681bac6 --- /dev/null +++ b/tests/test_paths.py @@ -0,0 +1,43 @@ +import pathlib +from tempfile import TemporaryDirectory + +from zimscraperlib.paths import path_from + + +def test_path_from_tmp_dir(): + tempdir = TemporaryDirectory() + with path_from(tempdir) as tmp_dir: + file = tmp_dir / "file.txt" + file.touch() + assert file.exists() + assert pathlib.Path(tempdir.name).exists() + + assert not pathlib.Path(tempdir.name).exists() + + +def test_path_from_path(): + tempdir = TemporaryDirectory() + tempdir_path = pathlib.Path(tempdir.name) + with path_from(tempdir_path) as tmp_dir: + file = tmp_dir / "file.txt" + file.touch() + assert file.exists() + assert pathlib.Path(tempdir.name).exists() + + assert pathlib.Path(tempdir.name).exists() + tempdir.cleanup() + assert not pathlib.Path(tempdir.name).exists() + + +def test_path_from_str(): + tempdir = TemporaryDirectory() + tempdir_path = pathlib.Path(tempdir.name) + with path_from(str(tempdir_path)) as tmp_dir: + file = tmp_dir / "file.txt" + file.touch() + assert file.exists() + assert pathlib.Path(tempdir.name).exists() + + assert pathlib.Path(tempdir.name).exists() + tempdir.cleanup() + assert not pathlib.Path(tempdir.name).exists()