[Git][debian-gis-team/pyspectral][master] 6 commits: New upstream version 0.14.4+ds

Antonio Valentino (@antonio.valentino) gitlab at salsa.debian.org
Sun Nov 22 09:40:28 GMT 2026



Antonio Valentino pushed to branch master at Debian GIS Project / pyspectral


Commits:
5a5e9a0c by Antonio Valentino at 2026-11-22T09:07:26+00:00
New upstream version 0.14.4+ds
- - - - -
5567c424 by Antonio Valentino at 2026-11-22T09:07:29+00:00
Update upstream source from tag 'upstream/0.14.4+ds'

Update to upstream version '0.14.4+ds'
with Debian dir 6a71abf090d0a9ce2f404e0a4788984e771718a0
- - - - -
57ef7079 by Antonio Valentino at 2026-11-22T09:08:40+00:00
New upstream version

- - - - -
21d92b25 by Antonio Valentino at 2026-11-22T09:17:49+00:00
Refresh all patches

- - - - -
e4841ef5 by Antonio Valentino at 2026-11-22T09:26:22+00:00
New manpage for mirror_pyspectral_data

- - - - -
c8664ec3 by Antonio Valentino at 2026-11-22T09:26:45+00:00
Set distribution to unstable

- - - - -


23 changed files:

- .pre-commit-config.yaml
- + AGENTS.md
- CHANGELOG.md
- CHANGELOG_RSR_DATA.rst
- + CLAUDE.md
- + RELEASE_NEW_RSR_DATA.md
- + bin/mirror_pyspectral_data.py
- continuous_integration/environment.yaml
- debian/changelog
- + debian/man/mirror_pyspectral_data.1
- debian/patches/0001-Fix-install-data.patch
- doc/installation.rst
- doc/rtd_environment.yaml
- pyspectral/bandnames.py
- pyspectral/etc/pyspectral.yaml
- pyspectral/near_infrared_reflectance.py
- pyspectral/tests/test_utils.py
- pyspectral/utils.py
- rsr_convert_scripts/agri_rsr.py
- rsr_convert_scripts/ghi_rsr.py
- rsr_convert_scripts/mersirm_rsr.py
- rsr_convert_scripts/metimage_rsr.py
- setup.py


Changes:

=====================================
.pre-commit-config.yaml
=====================================
@@ -7,7 +7,7 @@ repos:
     - id: flake8
       additional_dependencies: [flake8-docstrings, flake8-debugger, flake8-bugbear]
 -   repo: https://github.com/pycqa/isort
-    rev: 8.0.1
+    rev: 10.0.0b2
     hooks:
       - id: isort
         language_version: python3


=====================================
AGENTS.md
=====================================
@@ -0,0 +1,109 @@
+# CLAUDE.md
+
+This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
+
+## Project
+
+Pyspectral (pytroll) reads satellite imager relative spectral response (RSR) functions and
+uses them for radiative calculations: solar flux per band, radiance<->brightness-temperature
+conversion, 3.7 micron NIR reflectance separation, and Rayleigh/aerosol atmospheric
+correction of VIS bands. It is a library, mainly consumed by Satpy; there is no application
+entry point, only the helper scripts in `bin/`.
+
+## Commands
+
+```bash
+pip install -e .                       # development install (setuptools_scm writes pyspectral/version.py)
+pytest pyspectral/tests                # full test suite
+pytest pyspectral/tests/test_rayleigh.py::TestRayleigh::test_get_reflectance   # single test
+pytest --cov=pyspectral pyspectral/tests --cov-report=xml                      # as CI runs it
+pre-commit run -a                      # flake8 (+docstrings/debugger/bugbear) and isort
+cd doc && make html                    # sphinx docs
+```
+
+Line length is 120 (flake8 and isort). flake8-docstrings is enabled, so every module,
+class and function needs a docstring. Python >= 3.10; CI runs 3.10-3.12 on conda
+environments built from `continuous_integration/environment.yaml`.
+
+Missing test dependencies in this environment should be installed with
+`micromamba install -p /opt/conda -c conda-forge <pkg>` (e.g. `responses`, needed by
+`test_utils.py`).
+
+PRs go against `pre-master`, not `main`.
+
+## Architecture
+
+### Data flow
+
+Almost everything starts from `RelativeSpectralResponse` (`rsr_reader.py`), which loads a
+sensor's RSR from Pyspectral's own unified HDF5 format into
+`rsr[band_name][detector]{"wavelength", "response", "central_wavelength"}`. The HDF5 files
+are *not* in the repository: they are downloaded on demand from Zenodo. The higher-level
+calculators build on that:
+
+- `solar.SolarIrradianceSpectrum` - TOA solar spectrum (`pyspectral/data/e490_00a.dat`),
+  convolved with an RSR to get in-band solar flux.
+- `radiance_tb_conversion.RadTbConverter` - RSR-weighted radiance <-> Tb using
+  `blackbody.py` (Planck). `SeviriRadTbConverter` is a specialisation.
+- `near_infrared_reflectance.Calculator` - subclasses `RadTbConverter`; splits the 3.7/3.9
+  micron signal into solar and terrestrial parts. Caches a Tb<->radiance LUT as an `.npz`
+  under `tb2rad_dir` (default: tempdir).
+- `rayleigh.Rayleigh` - interpolates precomputed Rayleigh/aerosol LUTs (HDF5, per aerosol
+  type and standard atmosphere) with `geotiepoints.MultilinearInterpolator`. LUTs are also
+  downloaded from Zenodo.
+- `atm_correction_ir.AtmosphericalCorrection` - old parametric limb-cooling correction.
+
+### Configuration and downloaded data
+
+`config.get_config()` reads `pyspectral/etc/pyspectral.yaml`, or the file pointed to by the
+`PSP_CONFIG_FILE` environment variable. It resolves `rsr_dir` and `rayleigh_dir`, defaulting
+to the platformdirs user data dir, and creates them. The same YAML doubles as the place
+where users point the `rsr_convert_scripts/` at original agency RSR files (one section per
+`<Platform>-<instrument>`), which is why it is so long.
+
+Download behaviour is governed by `download_from_internet` in that YAML plus version
+stamp files written next to the data: `RSR_DATA_VERSION` / `ATM_CORRECTION_LUT_VERSION` in
+`utils.py` are compared against `PYSPECTRAL_RSR_VERSION` / `PYSPECTRAL_ATM_CORR_LUT_*` files
+in the data dirs to decide whether to re-download. When RSR data on Zenodo is updated, bump
+`RSR_DATA_VERSION` and `HTTP_PYSPECTRAL_RSR` together.
+
+Zenodo is the default source but not the only one: `get_rsr_url()` / `get_rayleigh_lut_url()`
+build the download URLs, and when a mirror is configured (`PSP_DATA_BASE_URL` environment
+variable, or `download_base_url` in the YAML) they point at it instead, using the versioned
+layout that `mirror_data()` and `bin/mirror_pyspectral_data.py` produce. Any new download
+should go through those functions rather than reading a URL constant directly.
+
+`utils.INSTRUMENTS` maps platform -> instrument(s) and is the authority on which
+platform/sensor combinations exist; `check_and_adjust_instrument_name` and
+`rayleigh.normalize_sensor` reconcile the several spellings in use (`avhrr-3` vs `avhrr/3`,
+`mersi2` vs `mersi-2`). `bandnames.BANDNAMES` maps sensor-specific band names to the generic
+names used internally, so most public APIs accept a band name *or* a wavelength in microns.
+
+### Dask handling
+
+Dask is an optional dependency, so modules do `try: import dask.array as da / except
+ImportError`. Computational functions must work on plain numpy arrays, dask arrays and
+xarray DataArrays alike. The `@use_map_blocks_on("<arg>")` decorator in `utils.py` is the
+standard way to get that: it passes numpy straight through and wraps chunked input in
+`da.map_blocks`, preserving the xarray wrapper.
+
+### Tests and downloads
+
+`pyspectral/tests/conftest.py` installs an autouse fixture that makes any download attempt
+raise. A test that genuinely needs the network must be marked
+`@pytest.mark.allow_downloads(use=True)`. Tests therefore work against fake RSR/LUT data
+built by `pyspectral/testing.py`.
+
+`pyspectral.testing` is public API, not test-only helpers: it exists so that downstream
+projects (Satpy) can mock Pyspectral's downloads in their own test suites. It offers
+high-level context managers (`mock_pyspectral_downloads`, `mock_rsr`, `mock_rayleigh`,
+`mock_tb_conversion`) layered on lower-level ones that create fake files and override the
+config. Keep it importable without test-only dependencies, and cover it in
+`tests/test_testing.py`.
+
+### rsr_convert_scripts/
+
+One script per sensor, converting original agency RSR data (Excel, text, netCDF, ...) into
+the unified HDF5 format, usually via `raw_reader.InstrumentRSR` plus `utils.convert2hdf5`.
+These are excluded from coverage and are only run by maintainers when an agency publishes
+updated responses; the result is uploaded to Zenodo rather than committed here.


=====================================
CHANGELOG.md
=====================================
@@ -1,3 +1,21 @@
+## Version 0.14.4 (2026/11/18)
+
+### Pull Requests Merged
+
+#### Bugs fixed
+
+* [PR 292](https://github.com/pytroll/pyspectral/pull/292) - Add 'metimage' bandnames mapping
+
+#### Features added
+
+* [PR 305](https://github.com/pytroll/pyspectral/pull/305) - Add latest metimage rsr v10
+* [PR 301](https://github.com/pytroll/pyspectral/pull/301) - Remove Python 3.10 and 3.11 support and cleanup safer tarball extraction
+* [PR 297](https://github.com/pytroll/pyspectral/pull/297) - Add zenodo mirroring
+* [PR 295](https://github.com/pytroll/pyspectral/pull/295) - Fix conversion script for v10 of METimage SRF
+
+In this release 5 pull requests were closed.
+
+
 ## Version 0.14.3 (2026/04/02)
 
 ### Issues Closed


=====================================
CHANGELOG_RSR_DATA.rst
=====================================
@@ -1,6 +1,14 @@
 Changelog for the Relative Spectral Response data
 =================================================
 
+Version v1.6.2 (Tue Nov 17 01:21:13 PM CET 2026)
+
+-------------------------------------------
+
+* Update the METimage RSR with v10 released by EUMETSAT during August 2026
+  Filename = EPS-SGA1-METIMAGE_SRF_V10.nc
+
+
 Version v1.6.1 (Wed Apr  1 08:14:23 PM CEST 2026)
 
 -------------------------------------------


=====================================
CLAUDE.md
=====================================
@@ -0,0 +1 @@
+ at AGENTS.md


=====================================
RELEASE_NEW_RSR_DATA.md
=====================================
@@ -0,0 +1,33 @@
+
+* First download the latest pyspectral-rsr data archive from Zenodo: Search
+  zenodo for "Satellite Sensor Relative Spectral Response data", and select the
+  latest version and click the download button at the bottom of the page.
+
+* Unpack it into an empty directory
+
+* Add you new HDF5 RSR data file into the same directory
+
+* Bump the version tag stored in the PYSPECTRAL_RSR_VERSION file
+
+* Update the CHANGELOG_RSR_DATA.rst in the pyspectral code with a description
+  of the new RSR data.
+
+* Make a new tar file of the content of the directory just updated. E.g.:
+    %> tar cvzf ../pyspectral_rsr_data.tgz rsr_* PYSPECTRAL_RSR_VERSION
+
+* Upload the new tar file to Zenodo: Click "New version". Then click "Upload files". Upload the tarfile.
+
+* Update the author list accordingly
+
+* Update the description field with the changelog. Take the changelog
+  description just added above in CHANGELOG_RSR_DATA.rst and paste on Zenodo.
+
+* Write the version tag (e.g. v1.6.2) in the "Version" field
+
+* Click the "Preview" at the top right and check the release. Then go back, and
+  click "Publish" when satisfied.
+
+* Once ready, get the download link and upgrade the link in the
+  pyspectral/utils.py module accordingly. Also upgrade the version tag there.
+
+* Update the Pyspectral on github (make a new PR) and make a new release.


=====================================
bin/mirror_pyspectral_data.py
=====================================
@@ -0,0 +1,58 @@
+#!/usr/bin/env python
+
+"""Mirror the pyspectral data files for serving them from a local web location.
+
+Download the relative spectral response and atmospheric correction LUT
+tarballs and store them, unextracted, in the directory layout that pyspectral
+expects from a mirror. The resulting directory can be copied to a web server,
+and pyspectral installations can then be pointed at it with the
+``PSP_DATA_BASE_URL`` environment variable instead of downloading from Zenodo.
+
+"""
+
+import argparse
+import logging
+
+from pyspectral.utils import AEROSOL_TYPES, logging_off, logging_on, mirror_data
+
+LOG = logging.getLogger(__name__)
+
+
+def main():
+    """Mirror the pyspectral data files."""
+    parser = argparse.ArgumentParser(description=__doc__.split("\n", maxsplit=1)[0])
+    parser.add_argument("-o", "--destination", required=True, type=str,
+                        help="Directory to write the mirrored files to")
+    parser.add_argument("-a", "--aerosol_types", nargs="*", type=str, default=AEROSOL_TYPES,
+                        help="Aerosol types to mirror the atmospheric correction LUTs for")
+    parser.add_argument("--no_rsr", action="store_true", default=False,
+                        help="Do not mirror the relative spectral responses")
+    parser.add_argument("--no_luts", action="store_true", default=False,
+                        help="Do not mirror the atmospheric correction LUTs")
+    parser.add_argument("--source_base_url", type=str, default=None,
+                        help=("Base URL to download the files from, for mirroring another mirror. "
+                              "Defaults to the upstream locations on Zenodo"))
+    parser.add_argument("-f", "--overwrite", action="store_true", default=False,
+                        help="Download files even if they are already mirrored")
+    parser.add_argument("-d", "--dry_run", action="store_true", default=False,
+                        help="Dry run - no action")
+    parser.add_argument("-v", "--verbose", action="store_true", help="Turn logging on")
+
+    args = parser.parse_args()
+
+    if args.verbose:
+        logging_on(logging.DEBUG)
+    else:
+        logging_off()
+
+    mirror_data(args.destination,
+                aerosol_types=args.aerosol_types,
+                include_rsr=not args.no_rsr,
+                include_luts=not args.no_luts,
+                source_base_url=args.source_base_url,
+                overwrite=args.overwrite,
+                dry_run=args.dry_run)
+
+
+if __name__ == "__main__":
+    main()


=====================================
continuous_integration/environment.yaml
=====================================
@@ -6,7 +6,7 @@ dependencies:
   - dask
   - distributed
   - toolz
-  - Cython
+  - cython
   - sphinx
   - matplotlib
   - scipy


=====================================
debian/changelog
=====================================
@@ -1,9 +1,15 @@
-pyspectral (0.14.3+ds-2) UNRELEASED; urgency=medium
+pyspectral (0.14.4+ds-1) unstable; urgency=medium
 
-  * Team upload.
+  [ Bas Couwenberg ]
   * Bump Standards-Version to 4.7.4, no changes.
 
- -- Bas Couwenberg <sebastic at debian.org>  Sat, 04 Apr 2026 10:19:53 +0200
+  [ Antonio Valentino ]
+  * New upstream release.
+  * debian/patches:
+    - Refresh all patches.
+  * Add man page for mirror_pyspectral_data.
+
+ -- Antonio Valentino <antonio.valentino at tiscali.it>  Sun, 22 Nov 2026 09:26:27 +0000
 
 pyspectral (0.14.3+ds-1) unstable; urgency=medium
 


=====================================
debian/man/mirror_pyspectral_data.1
=====================================
@@ -0,0 +1,43 @@
+.\" DO NOT MODIFY THIS FILE!  It was generated by help2man 1.49.3.
+.TH MIRROR_PYSPECTRAL_DATA.PY "1" "November 2026" "mirror_pyspectral_data 0.14.4" "User Commands"
+.SH NAME
+mirror_pyspectral_data.py \- Mirror the pyspectral data files 
+.SH DESCRIPTION
+usage: mirror_pyspectral_data.py [\-h] \fB\-o\fR DESTINATION [\-a [AEROSOL_TYPES ...]]
+.TP
+[\-\-no_rsr] [\-\-no_luts]
+[\-\-source_base_url SOURCE_BASE_URL] [\-f] [\-d]
+[\-v]
+.PP
+Mirror the pyspectral data files for serving them from a local web location.
+.SS "options:"
+.TP
+\fB\-h\fR, \fB\-\-help\fR
+show this help message and exit
+.TP
+\fB\-o\fR, \fB\-\-destination\fR DESTINATION
+Directory to write the mirrored files to
+.TP
+\fB\-a\fR, \fB\-\-aerosol_types\fR [AEROSOL_TYPES ...]
+Aerosol types to mirror the atmospheric correction
+LUTs for
+.TP
+\fB\-\-no_rsr\fR
+Do not mirror the relative spectral responses
+.TP
+\fB\-\-no_luts\fR
+Do not mirror the atmospheric correction LUTs
+.TP
+\fB\-\-source_base_url\fR SOURCE_BASE_URL
+Base URL to download the files from, for mirroring
+another mirror. Defaults to the upstream locations on
+Zenodo
+.TP
+\fB\-f\fR, \fB\-\-overwrite\fR
+Download files even if they are already mirrored
+.TP
+\fB\-d\fR, \fB\-\-dry_run\fR
+Dry run \- no action
+.TP
+\fB\-v\fR, \fB\-\-verbose\fR
+Turn logging on


=====================================
debian/patches/0001-Fix-install-data.patch
=====================================
@@ -8,17 +8,17 @@ Forwarded: not-needed
  1 file changed, 2 insertions(+), 2 deletions(-)
 
 diff --git a/setup.py b/setup.py
-index 0f2b79b..d4cde8f 100644
+index 9991a54..4fb085c 100644
 --- a/setup.py
 +++ b/setup.py
-@@ -56,8 +56,8 @@ setup(name=NAME,
-       scripts=['bin/plot_rsr.py', 'bin/composite_rsr_plot.py',
+@@ -57,8 +57,8 @@ setup(name=NAME,
                 'bin/download_atm_correction_luts.py',
-                'bin/download_rsr.py'],
+                'bin/download_rsr.py',
+                'bin/mirror_pyspectral_data.py'],
 -      data_files=[('share', ['pyspectral/data/e490_00a.dat',
 -                             'pyspectral/data/MSG_SEVIRI_Spectral_Response_Characterisation.XLS'])],
-+      # data_files=[('share/', ['pyspectral/data/e490_00a.dat',
++      # data_files=[('share', ['pyspectral/data/e490_00a.dat',
 +      #                        'pyspectral/data/MSG_SEVIRI_Spectral_Response_Characterisation.XLS'])],
-       python_requires='>=3.10',
+       python_requires='>=3.12',
        zip_safe=False,
        )


=====================================
doc/installation.rst
=====================================
@@ -33,7 +33,9 @@ satellite imaging sensors are available in a unified hdf5 format. Secondly,
 PySpectral comes with a set of Look-Up-Tables (LUTs) for the atmospheric
 correction in the short wave spectral range.
 
-Both these datasets downloads automagically from `zenodo.org`_ when needed.
+Both these datasets downloads automagically from `zenodo.org`_ when needed. If
+you run many processing chains, and want to avoid them all downloading from the
+same upstream host, the data can be mirrored locally, see :ref:`mirroring`.
 
 On default these static data will reside in the platform specific standard
 destination for storing user data, via the use of the platformdirs_ package. On
@@ -168,6 +170,66 @@ And then adjust the *pyspectral.yaml* so data downloading will not be attempted
    download_from_internet = False
 
 
+.. _mirroring:
+
+Mirroring the static data
+^^^^^^^^^^^^^^^^^^^^^^^^^
+
+When several processing chains run *PySpectral* independently of each other,
+they may all try to download the static data from `zenodo.org`_ at about the
+same time. The upstream host may then start rate limiting the traffic, and the
+downloads fail. To avoid that, the data can be mirrored on a web server of your
+own, and *PySpectral* can be told to download from there instead.
+
+The *mirror_pyspectral_data.py* script downloads the tarballs and stores them,
+unextracted, in the directory layout a mirror is expected to serve:
+
+  .. code::
+
+   python ~/.local/bin/mirror_pyspectral_data.py -o /path/to/mirror -v
+
+This creates::
+
+   /path/to/mirror/rsr/<rsr version>/pyspectral_rsr_data.tgz
+   /path/to/mirror/luts/<lut version>/pyspectral_atm_correction_luts_<aerosol type>.tgz
+
+Copy (or rsync) that directory to the location your web server serves, and
+point the processing chains at it with the ``PSP_DATA_BASE_URL`` environment
+variable::
+
+  $> PSP_DATA_BASE_URL=https://www.example.com/pyspectral; export PSP_DATA_BASE_URL
+
+Alternatively, set it in the configuration file, which the environment variable
+overrides if both are used:
+
+.. code-block:: ini
+
+   download_base_url = https://www.example.com/pyspectral
+
+Everything else stays the same: the version checks, the ``download_from_internet``
+setting and the ``download_rsr.py`` and ``download_atm_correction_luts.py``
+scripts all work as before, they just fetch the tarballs from the mirror.
+
+Since the version of the data is part of the path, one mirror can serve several
+versions of the data at the same time. Upgrading *PySpectral* in one processing
+chain, and mirroring the data version it needs, therefore does not disturb the
+chains that still run an older version. Only the files that are missing are
+downloaded, so the script can be re-run, for example from cron, to pick up new
+data versions:
+
+  .. code::
+
+   python ~/.local/bin/mirror_pyspectral_data.py -o /path/to/mirror -v
+
+Use the ``-a`` option to limit the mirroring to the aerosol distributions you
+actually use, and ``--no_rsr`` or ``--no_luts`` to mirror only one of the two
+datasets:
+
+  .. code::
+
+   python ~/.local/bin/mirror_pyspectral_data.py -o /path/to/mirror -a desert_aerosol marine_clean_aerosol -v
+
+
 .. _pyspectral rsr: https://zenodo.org/record/1012412/files/pyspectral_rsr_data.tgz
 .. _eumetsat: http://www.eumetsat.int/website/wcm/idc/idcplg?IdcService=GET_FILE&dDocName=ZIP_MSG_SEVIRI_SPEC_RES_CHAR&RevisionSelectionMethod=LatestReleased&Rendition=Web
 .. _GSICS: http://www.wmo.int/pages/prog/sat/GSICS/


=====================================
doc/rtd_environment.yaml
=====================================
@@ -2,7 +2,7 @@ name: readthedocs
 channels:
   - conda-forge
 dependencies:
-  - python=3.11
+  - python=3.14
   - pip
   - pytest
   - sphinx


=====================================
pyspectral/bandnames.py
=====================================
@@ -188,24 +188,27 @@ BANDNAMES['slstr'] = {'S1': 'ch1',
                       'F2': 'ch8',
                       }
 
-BANDNAMES['VII'] = {'vii_443': 'vii-4',
-                    'vii_555': 'vii-8',
-                    'vii_668': 'vii-12',
-                    'vii_752': 'vii-15',
-                    'vii_763': 'vii-16',
-                    'vii_865': 'vii-17',
-                    'vii_914': 'vii-20',
-                    'vii_1240': 'vii-22',
-                    'vii_1375': 'vii-23',
-                    'vii_1630': 'vii-24',
-                    'vii_2250': 'vii-25',
-                    'vii_3740': 'vii-26',
-                    'vii_3959': 'vii-28',
-                    'vii_4050': 'vii-30',
-                    'vii_6725': 'vii-33',
-                    'vii_7325': 'vii-34',
-                    'vii_8540': 'vii-35',
-                    'vii_10690': 'vii-37',
-                    'vii_12020': 'vii-39',
-                    'vii_13345': 'vii-40',
-                    }
+BANDNAMES['metimage'] = {'vii_443': 'vii-4',
+                         'vii_555': 'vii-8',
+                         'vii_668': 'vii-12',
+                         'vii_752': 'vii-15',
+                         'vii_763': 'vii-16',
+                         'vii_865': 'vii-17',
+                         'vii_914': 'vii-20',
+                         'vii_1240': 'vii-22',
+                         'vii_1375': 'vii-23',
+                         'vii_1630': 'vii-24',
+                         'vii_2250': 'vii-25',
+                         'vii_3740': 'vii-26',
+                         'vii_3959': 'vii-28',
+                         'vii_4050': 'vii-30',
+                         'vii_6725': 'vii-33',
+                         'vii_7325': 'vii-34',
+                         'vii_8540': 'vii-35',
+                         'vii_10690': 'vii-37',
+                         'vii_12020': 'vii-39',
+                         'vii_13345': 'vii-40',
+                         }
+
+# Kept for backwards compatibility with the old key.
+BANDNAMES['VII'] = BANDNAMES['metimage']


=====================================
pyspectral/etc/pyspectral.yaml
=====================================
@@ -15,6 +15,14 @@
 # LUTs are downloaded from internet:
 download_from_internet: True
 
+# On default the data are downloaded from zenodo.org. If you run many
+# processing chains you may want to mirror the data on a web server of your own
+# to avoid being rate limited by the upstream host. Create the mirror with the
+# 'mirror_pyspectral_data.py' script, copy it to your web server, and give the
+# URL it is served from here. The PSP_DATA_BASE_URL environment variable
+# overrides this setting:
+#download_base_url: https://www.example.com/pyspectral
+
 # Everything below this line should not need to be changed!
 # Changes may be done if you want to change the name of the radiance<->Tb LUT filenames,
 # or if you want to store those files in different directories dependning on the platform/sensor.


=====================================
pyspectral/near_infrared_reflectance.py
=====================================
@@ -14,7 +14,7 @@ import numpy as np
 try:
     from dask.array import asanyarray, isnan, logical_or, where
 except ImportError:
-    from numpy import where, logical_or, asanyarray, isnan
+    from numpy import asanyarray, isnan, logical_or, where
 
 from pyspectral.config import get_config
 from pyspectral.radiance_tb_conversion import RadTbConverter


=====================================
pyspectral/tests/test_utils.py
=====================================
@@ -295,11 +295,33 @@ def test_download_rsr(tmp_path):
         assert version_file.read() == version_data
 
 
-def _create_fake_rsr_tarball_bytes(version_data=utils.RSR_DATA_VERSION):
+ at pytest.mark.allow_downloads(use=True)
+def test_download_rsr_refuses_path_traversal(tmp_path):
+    """Test that a tarball member can't be extracted outside of the destination directory."""
+    dest_dir = tmp_path / "rsr"
+    dest_dir.mkdir()
+    tar_data = _create_fake_rsr_tarball_bytes(member_name="../escaped.txt")
+    with responses.RequestsMock() as rsps:
+        rsps.add(
+            "GET",
+            utils.HTTP_PYSPECTRAL_RSR,
+            body=tar_data,
+            status=200,
+            content_type="application/octet-stream",
+            headers={
+                "Content-Length": str(len(tar_data)),
+            },
+        )
+        with pytest.raises(tarfile.OutsideDestinationError):
+            utils.download_rsr(dest_dir=str(dest_dir))
+    assert not (tmp_path / "escaped.txt").exists()
+
+
+def _create_fake_rsr_tarball_bytes(version_data=utils.RSR_DATA_VERSION, member_name=utils.RSR_DATA_VERSION_FILENAME):
     file_obj = BytesIO()
 
     with tarfile.open(mode="w:gz", fileobj=file_obj) as rsr_tar:
-        info = tarfile.TarInfo(utils.RSR_DATA_VERSION_FILENAME)
+        info = tarfile.TarInfo(member_name)
         info.size = len(version_data)
         rsr_tar.addfile(info, BytesIO(version_data.encode("ascii")))
 
@@ -368,11 +390,12 @@ def _create_fake_lut_tarball_bytes(aerosol_types):
 
 
 @contextlib.contextmanager
-def _fake_get_config(tmp_path):
+def _fake_get_config(tmp_path, **extra_options):
     def _get_config():
         return {
             "rayleigh_dir": str(tmp_path),
             "rsr_dir": str(tmp_path),
+            **extra_options,
         }
     with unittest.mock.patch("pyspectral.utils.get_config") as get_config:
         get_config.side_effect = _get_config
@@ -394,6 +417,247 @@ def _check_expected_aerosol_files(atypes_to_create, tmp_path):
             assert not atype_fn.is_file()
 
 
+MIRROR_BASE_URL = "https://www.example.com/pyspectral"
+
+
+def test_get_base_url_not_configured(tmp_path, monkeypatch):
+    """Test that no mirror is used when neither environment nor config define one."""
+    monkeypatch.delenv(utils.BASE_URL_ENV_VAR, raising=False)
+    with _fake_get_config(tmp_path):
+        assert utils.get_base_url() is None
+
+
+def test_get_base_url_from_environment(tmp_path, monkeypatch):
+    """Test getting the mirror base URL from the environment variable."""
+    monkeypatch.setenv(utils.BASE_URL_ENV_VAR, MIRROR_BASE_URL + "/")
+    with _fake_get_config(tmp_path):
+        assert utils.get_base_url() == MIRROR_BASE_URL
+
+
+def test_get_base_url_from_config(tmp_path, monkeypatch):
+    """Test getting the mirror base URL from the configuration file."""
+    monkeypatch.delenv(utils.BASE_URL_ENV_VAR, raising=False)
+    with _fake_get_config(tmp_path, download_base_url=MIRROR_BASE_URL):
+        assert utils.get_base_url() == MIRROR_BASE_URL
+
+
+def test_get_base_url_environment_overrides_config(tmp_path, monkeypatch):
+    """Test that the environment variable takes precedence over the configuration file."""
+    monkeypatch.setenv(utils.BASE_URL_ENV_VAR, MIRROR_BASE_URL)
+    with _fake_get_config(tmp_path, download_base_url="https://www.example.com/other"):
+        assert utils.get_base_url() == MIRROR_BASE_URL
+
+
+def test_get_rsr_url_default(tmp_path, monkeypatch):
+    """Test that the RSR are downloaded from zenodo when no mirror is configured."""
+    monkeypatch.delenv(utils.BASE_URL_ENV_VAR, raising=False)
+    with _fake_get_config(tmp_path):
+        assert utils.get_rsr_url() == utils.HTTP_PYSPECTRAL_RSR
+
+
+def test_get_rsr_url_mirror(monkeypatch):
+    """Test that the RSR URL of a mirror includes the data version."""
+    monkeypatch.setenv(utils.BASE_URL_ENV_VAR, MIRROR_BASE_URL)
+    exp_url = f"{MIRROR_BASE_URL}/rsr/{utils.RSR_DATA_VERSION}/pyspectral_rsr_data.tgz"
+    assert utils.get_rsr_url() == exp_url
+    assert utils.get_rsr_url(base_url=MIRROR_BASE_URL + "/") == exp_url
+
+
+def test_get_rayleigh_lut_url_default(tmp_path, monkeypatch):
+    """Test that the LUTs are downloaded from zenodo when no mirror is configured."""
+    monkeypatch.delenv(utils.BASE_URL_ENV_VAR, raising=False)
+    with _fake_get_config(tmp_path):
+        for aerosol_type in utils.AEROSOL_TYPES:
+            assert utils.get_rayleigh_lut_url(aerosol_type) == utils.HTTPS_RAYLEIGH_LUTS[aerosol_type]
+
+
+ at pytest.mark.parametrize(
+    ("aerosol_type", "exp_name"),
+    [
+        ("desert_aerosol", "desert_aerosol"),
+        ("rayleigh_only", "no_aerosol"),
+    ]
+)
+def test_get_rayleigh_lut_url_mirror(monkeypatch, aerosol_type, exp_name):
+    """Test that the LUT URL of a mirror includes the data version and the upstream file name."""
+    monkeypatch.setenv(utils.BASE_URL_ENV_VAR, MIRROR_BASE_URL)
+    version = utils.ATM_CORRECTION_LUT_VERSION[aerosol_type]["version"]
+    exp_url = f"{MIRROR_BASE_URL}/luts/{version}/pyspectral_atm_correction_luts_{exp_name}.tgz"
+    assert utils.get_rayleigh_lut_url(aerosol_type) == exp_url
+
+
+def test_download_rsr_logs_the_url(tmp_path, monkeypatch, caplog):
+    """Test that the URL the RSR are downloaded from is logged at info level."""
+    monkeypatch.setenv(utils.BASE_URL_ENV_VAR, MIRROR_BASE_URL)
+    with _fake_get_config(tmp_path), caplog.at_level(logging.INFO):
+        utils.download_rsr(dry_run=True)
+    assert utils.get_rsr_url(base_url=MIRROR_BASE_URL) in caplog.text
+
+
+def test_download_luts_logs_the_url(tmp_path, monkeypatch, caplog):
+    """Test that the URL the LUTs are downloaded from is logged at info level."""
+    monkeypatch.setenv(utils.BASE_URL_ENV_VAR, MIRROR_BASE_URL)
+    aerosol_types = ["desert_aerosol"]
+    with _fake_get_config(tmp_path), caplog.at_level(logging.INFO):
+        utils.download_luts(aerosol_types=aerosol_types, dry_run=True)
+    assert utils.get_rayleigh_lut_url("desert_aerosol", base_url=MIRROR_BASE_URL) in caplog.text
+
+
+ at pytest.mark.allow_downloads(use=True)
+def test_download_rsr_from_mirror(tmp_path, monkeypatch):
+    """Test that download_rsr uses the configured mirror."""
+    monkeypatch.setenv(utils.BASE_URL_ENV_VAR, MIRROR_BASE_URL)
+    version_data = "v1.2.3.4.5"
+    tar_data = _create_fake_rsr_tarball_bytes(version_data)
+    with responses.RequestsMock() as rsps:
+        rsps.add(
+            "GET",
+            utils.get_rsr_url(base_url=MIRROR_BASE_URL),
+            body=tar_data,
+            status=200,
+            content_type="application/octet-stream",
+            headers={"Content-Length": str(len(tar_data))},
+        )
+        utils.download_rsr(dest_dir=str(tmp_path))
+    assert (tmp_path / "PYSPECTRAL_RSR_VERSION").is_file()
+
+
+ at pytest.mark.allow_downloads(use=True)
+def test_download_luts_from_mirror(tmp_path, monkeypatch):
+    """Test that download_luts uses the configured mirror."""
+    monkeypatch.setenv(utils.BASE_URL_ENV_VAR, MIRROR_BASE_URL)
+    aerosol_types = ["desert_aerosol"]
+    tar_data = _create_fake_lut_tarball_bytes(aerosol_types=aerosol_types)
+    with responses.RequestsMock() as rsps:
+        rsps.add(
+            "GET",
+            utils.get_rayleigh_lut_url("desert_aerosol", base_url=MIRROR_BASE_URL),
+            body=tar_data,
+            status=200,
+            content_type="application/octet-stream",
+            headers={"Content-Length": str(len(tar_data))},
+        )
+        with _fake_get_config(tmp_path):
+            utils.download_luts(aerosol_types=aerosol_types)
+    _check_expected_aerosol_files(aerosol_types, tmp_path)
+
+
+def test_mirror_data_dry_run(tmp_path):
+    """Test that a dry run of mirror_data downloads nothing."""
+    with unittest.mock.patch("pyspectral.utils.requests") as requests_mock:
+        mirrored = utils.mirror_data(tmp_path, dry_run=True)
+    requests_mock.assert_not_called()
+    assert len(mirrored) == len(utils.AEROSOL_TYPES) + 1
+    assert not any(pathname.exists() for pathname in mirrored)
+
+
+ at pytest.mark.allow_downloads(use=True)
+def test_mirror_data(tmp_path):
+    """Test that mirror_data stores the tarballs in the layout the downloads expect."""
+    aerosol_types = ["desert_aerosol", "rayleigh_only"]
+    with _mirror_source_urls_mocked(aerosol_types):
+        mirrored = utils.mirror_data(tmp_path, aerosol_types=aerosol_types)
+
+    exp_rsr_path = tmp_path / "rsr" / utils.RSR_DATA_VERSION / "pyspectral_rsr_data.tgz"
+    lut_version = utils.ATM_CORRECTION_LUT_VERSION["desert_aerosol"]["version"]
+    exp_lut_path = tmp_path / "luts" / lut_version / "pyspectral_atm_correction_luts_desert_aerosol.tgz"
+    exp_rayleigh_path = tmp_path / "luts" / lut_version / "pyspectral_atm_correction_luts_no_aerosol.tgz"
+    assert mirrored == [exp_rsr_path, exp_lut_path, exp_rayleigh_path]
+    assert all(pathname.is_file() for pathname in mirrored)
+    assert not list(tmp_path.rglob("*.part"))
+
+    # the files end up where the downloading functions ask a mirror for them
+    exp_urls = [utils.get_rsr_url(base_url=MIRROR_BASE_URL)]
+    exp_urls += [utils.get_rayleigh_lut_url(atype, base_url=MIRROR_BASE_URL) for atype in aerosol_types]
+    mirror_urls = [MIRROR_BASE_URL + "/" + pathname.relative_to(tmp_path).as_posix() for pathname in mirrored]
+    assert mirror_urls == exp_urls
+
+
+ at pytest.mark.allow_downloads(use=True)
+def test_mirror_data_skips_existing_files(tmp_path):
+    """Test that re-running mirror_data doesn't download what is already mirrored."""
+    aerosol_types = ["desert_aerosol"]
+    with _mirror_source_urls_mocked(aerosol_types):
+        utils.mirror_data(tmp_path, aerosol_types=aerosol_types)
+
+    with unittest.mock.patch("pyspectral.utils.requests") as requests_mock:
+        mirrored = utils.mirror_data(tmp_path, aerosol_types=aerosol_types)
+    requests_mock.assert_not_called()
+    assert all(pathname.is_file() for pathname in mirrored)
+
+    with _mirror_source_urls_mocked(aerosol_types) as rsps:
+        utils.mirror_data(tmp_path, aerosol_types=aerosol_types, overwrite=True)
+        assert len(rsps.calls) == 2
+
+
+ at pytest.mark.allow_downloads(use=True)
+def test_mirror_data_from_another_mirror(tmp_path):
+    """Test that a mirror can be filled from another mirror instead of from zenodo."""
+    aerosol_types = ["desert_aerosol"]
+    tar_data = _create_fake_lut_tarball_bytes(aerosol_types=aerosol_types)
+    with responses.RequestsMock() as rsps:
+        rsps.add(
+            "GET",
+            utils.get_rayleigh_lut_url("desert_aerosol", base_url=MIRROR_BASE_URL),
+            body=tar_data,
+            status=200,
+            content_type="application/octet-stream",
+            headers={"Content-Length": str(len(tar_data))},
+        )
+        utils.mirror_data(tmp_path, aerosol_types=aerosol_types, include_rsr=False,
+                          source_base_url=MIRROR_BASE_URL)
+    assert list(tmp_path.rglob("*.tgz"))
+
+
+ at pytest.mark.allow_downloads(use=True)
+def test_mirror_data_incomplete_download(tmp_path):
+    """Test that a corrupt download doesn't leave a file that later runs consider mirrored."""
+    with responses.RequestsMock() as rsps:
+        rsps.add(
+            "GET",
+            utils.HTTP_PYSPECTRAL_RSR,
+            body=b"not a tarball",
+            status=200,
+            content_type="application/octet-stream",
+            headers={"Content-Length": "13"},
+        )
+        with pytest.raises(tarfile.TarError):
+            utils.mirror_data(tmp_path, include_luts=False)
+    assert not list(tmp_path.rglob("*.tgz"))
+    assert not list(tmp_path.rglob("*.part"))
+
+
+def test_mirror_data_unknown_aerosol_type(tmp_path):
+    """Test that an unknown aerosol type is reported before anything is downloaded."""
+    with pytest.raises(ValueError, match="no_such_aerosol"):
+        utils.mirror_data(tmp_path, aerosol_types=["no_such_aerosol"])
+
+
+ at contextlib.contextmanager
+def _mirror_source_urls_mocked(aerosol_types):
+    """Mock the upstream zenodo URLs that mirror_data downloads from."""
+    rsr_tar_data = _create_fake_rsr_tarball_bytes()
+    lut_tar_data = _create_fake_lut_tarball_bytes(aerosol_types=aerosol_types)
+    with responses.RequestsMock() as rsps:
+        rsps.add(
+            "GET",
+            utils.HTTP_PYSPECTRAL_RSR,
+            body=rsr_tar_data,
+            status=200,
+            content_type="application/octet-stream",
+            headers={"Content-Length": str(len(rsr_tar_data))},
+        )
+        rsps.add(
+            "GET",
+            re.compile(re.escape(utils.LUT_URL_PREFIX) + r"_.+\.tgz"),
+            body=lut_tar_data,
+            status=200,
+            content_type="application/octet-stream",
+            headers={"Content-Length": str(len(lut_tar_data))},
+        )
+        yield rsps
+
+
 @pytest.mark.parametrize(
     ("platform_name", "input_value_sensor", "exp_sensor_name"),
     [


=====================================
pyspectral/utils.py
=====================================
@@ -4,9 +4,9 @@ from __future__ import annotations
 
 import logging
 import os
-import sys
 import tarfile
 import warnings
+from collections.abc import Iterable
 from functools import wraps
 from inspect import getfullargspec
 from pathlib import Path
@@ -95,9 +95,9 @@ INSTRUMENT_TRANSLATION_DASH2SLASH = {"avhrr-1": "avhrr/1",
                                      "avhrr-2": "avhrr/2",
                                      "avhrr-3": "avhrr/3"}
 
-HTTP_PYSPECTRAL_RSR = "https://zenodo.org/records/19373017/files/pyspectral_rsr_data.tgz"
+HTTP_PYSPECTRAL_RSR = "https://zenodo.org/records/24309825/files/pyspectral_rsr_data.tgz"
 RSR_DATA_VERSION_FILENAME = "PYSPECTRAL_RSR_VERSION"
-RSR_DATA_VERSION = "v1.6.1"
+RSR_DATA_VERSION = "v1.6.2"
 
 
 ATM_CORRECTION_LUT_VERSION = {}
@@ -142,6 +142,75 @@ for atype in AEROSOL_TYPES:
     url = "{prefix}_{name}.tgz".format(prefix=LUT_URL_PREFIX, name=name)
     HTTPS_RAYLEIGH_LUTS[atype] = url
 
+#: Name of the environment variable overriding the base URL of the data downloads
+BASE_URL_ENV_VAR = "PSP_DATA_BASE_URL"
+#: Name of the configuration option overriding the base URL of the data downloads
+BASE_URL_CONFIG_OPTION = "download_base_url"
+
+#: Path of the RSR tarball relative to the mirror base URL
+RSR_MIRROR_PATH = "rsr/{version}/pyspectral_rsr_data.tgz"
+#: Path of an atmospheric correction LUT tarball relative to the mirror base URL
+LUT_MIRROR_PATH = "luts/{version}/pyspectral_atm_correction_luts_{name}.tgz"
+
+
+def get_base_url() -> str | None:
+    """Get the base URL of a mirror of the pyspectral data files, if one is configured.
+
+    The mirror is taken from the ``PSP_DATA_BASE_URL`` environment variable, or,
+    if that is not set, from the ``download_base_url`` option in the pyspectral
+    configuration file. If neither is set, ``None`` is returned, meaning that
+    the default upstream locations on Zenodo are used.
+
+    See :func:`mirror_data` for creating the directory structure that such a
+    mirror is expected to serve.
+
+    """
+    base_url = os.environ.get(BASE_URL_ENV_VAR)
+    if base_url is None:
+        base_url = get_config().get(BASE_URL_CONFIG_OPTION)
+    if not base_url:
+        return None
+    return base_url.rstrip("/")
+
+
+def _aerosol_type_to_lut_name(aerosol_type: str) -> str:
+    """Get the name used in the LUT tarball filename for an aerosol type."""
+    return {"rayleigh_only": "no_aerosol"}.get(aerosol_type, aerosol_type)
+
+
+def get_rsr_url(base_url: str | None = None) -> str:
+    """Get the URL to download the relative spectral responses from.
+
+    Args:
+        base_url: Base URL of a mirror of the pyspectral data files. Defaults
+            to the mirror configured via :func:`get_base_url`, and to the
+            upstream location on Zenodo if no mirror is configured.
+
+    """
+    base_url = base_url if base_url is not None else get_base_url()
+    if base_url is None:
+        return HTTP_PYSPECTRAL_RSR
+    return base_url.rstrip("/") + "/" + RSR_MIRROR_PATH.format(version=RSR_DATA_VERSION)
+
+
+def get_rayleigh_lut_url(aerosol_type: str, base_url: str | None = None) -> str:
+    """Get the URL to download the atmospheric correction LUTs of one aerosol type from.
+
+    Args:
+        aerosol_type: Aerosol type to get the URL for. See :data:`AEROSOL_TYPES`
+            for the full list.
+        base_url: Base URL of a mirror of the pyspectral data files. Defaults
+            to the mirror configured via :func:`get_base_url`, and to the
+            upstream location on Zenodo if no mirror is configured.
+
+    """
+    base_url = base_url if base_url is not None else get_base_url()
+    if base_url is None:
+        return HTTPS_RAYLEIGH_LUTS[aerosol_type]
+    version = ATM_CORRECTION_LUT_VERSION[aerosol_type]["version"]
+    lut_path = LUT_MIRROR_PATH.format(version=version, name=_aerosol_type_to_lut_name(aerosol_type))
+    return base_url.rstrip("/") + "/" + lut_path
+
 
 def get_rayleigh_lut_dir(aerosol_type: str) -> Path:
     """Get the rayleigh LUT directory for the specified aerosol type."""
@@ -375,12 +444,13 @@ def download_rsr(dest_dir: str | Path | None = None, dry_run: bool = False) -> N
 
     LOG.info(f"Download RSR files and store in directory {dest_path}")
     filename = dest_path / "pyspectral_rsr_data.tgz"
-    LOG.debug(f"RSR URL: {HTTP_PYSPECTRAL_RSR}")
+    rsr_url = get_rsr_url()
+    LOG.info(f"RSR URL: {rsr_url}")
     LOG.debug(f"Destination = {dest_path}")
     if dry_run:
         return
 
-    _download_tarball_and_extract(HTTP_PYSPECTRAL_RSR, filename, dest_path)
+    _download_tarball_and_extract(rsr_url, filename, dest_path)
 
 
 def download_luts(aerosol_types=None, dry_run=False, aerosol_type=None):
@@ -401,8 +471,8 @@ def download_luts(aerosol_types=None, dry_run=False, aerosol_type=None):
     aerosol_types = _get_aerosol_types(aerosol_types, aerosol_type)
     for subname in aerosol_types:
         LOG.debug("Aerosol type: %s", subname)
-        lut_tarball_url = HTTPS_RAYLEIGH_LUTS[subname]
-        LOG.debug("Atmospheric LUT URL = %s", lut_tarball_url)
+        lut_tarball_url = get_rayleigh_lut_url(subname)
+        LOG.info("Atmospheric LUT URL = %s", lut_tarball_url)
 
         subdir_path = get_rayleigh_lut_dir(subname)
         LOG.debug(f"Create directory: {subdir_path}")
@@ -428,6 +498,119 @@ def _get_aerosol_types(aerosol_types, aerosol_type):
     return aerosol_types
 
 
+def mirror_data(
+        dest_dir: str | Path,
+        aerosol_types: Iterable[str] | None = None,
+        include_rsr: bool = True,
+        include_luts: bool = True,
+        source_base_url: str | None = None,
+        overwrite: bool = False,
+        dry_run: bool = False,
+) -> list[Path]:
+    """Mirror the pyspectral data tarballs into a directory that can be served over HTTP(S).
+
+    This downloads the same tarballs that :func:`download_rsr` and
+    :func:`download_luts` fetch, but instead of extracting them it stores them
+    unmodified in the directory layout that pyspectral expects from a mirror::
+
+        <dest_dir>/rsr/<rsr version>/pyspectral_rsr_data.tgz
+        <dest_dir>/luts/<lut version>/pyspectral_atm_correction_luts_<name>.tgz
+
+    Copying (or rsync:ing) the resulting directory to a web server and pointing
+    the ``PSP_DATA_BASE_URL`` environment variable at the URL it is served from
+    makes all pyspectral installations download from there instead of from
+    Zenodo. This is useful when many processing chains would otherwise hit the
+    upstream host at the same time and get rate limited.
+
+    Because the version of the data is part of the path, mirroring a new
+    version of the data does not invalidate the files an older pyspectral
+    installation is asking for. Re-running this function only downloads the
+    files that are missing, so it can be run repeatedly, for example from cron.
+
+    Args:
+        dest_dir: Directory to write the mirrored files to. Created if needed.
+        aerosol_types: Aerosol types to mirror the LUTs for. Defaults to all
+            aerosol types. See :data:`AEROSOL_TYPES` for the full list.
+        include_rsr: Whether to mirror the relative spectral responses.
+            Defaults to True.
+        include_luts: Whether to mirror the atmospheric correction LUTs.
+            Defaults to True.
+        source_base_url: Base URL to download the files from. Defaults to the
+            upstream locations on Zenodo. Note that, unlike the downloading
+            functions, this deliberately ignores the configured mirror so that
+            a mirror is not refreshed from itself.
+        overwrite: Download files even if they already exist in ``dest_dir``.
+            Defaults to False, meaning existing files are left untouched.
+        dry_run: If True, don't download anything, only log what would be
+            downloaded. Defaults to False.
+
+    Returns:
+        The paths of all files the mirror consists of, including the ones that
+        already existed.
+
+    """
+    dest_path = Path(dest_dir)
+    urls_and_paths = _mirror_urls_and_paths(aerosol_types, include_rsr, include_luts, source_base_url)
+
+    mirrored_files = []
+    for url, relative_path in urls_and_paths:
+        local_pathname = dest_path / relative_path
+        mirrored_files.append(local_pathname)
+        if local_pathname.is_file() and not overwrite:
+            LOG.info("Already mirrored, skipping: %s", local_pathname)
+            continue
+        LOG.info("Mirroring %s -> %s", url, local_pathname)
+        if dry_run:
+            continue
+        local_pathname.parent.mkdir(parents=True, exist_ok=True)
+        _download_tarball_to(url, local_pathname)
+    return mirrored_files
+
+
+def _mirror_urls_and_paths(
+        aerosol_types: Iterable[str] | None,
+        include_rsr: bool,
+        include_luts: bool,
+        source_base_url: str | None,
+) -> list[tuple[str, str]]:
+    """Get the (source URL, path relative to the mirror root) pairs to mirror."""
+    urls_and_paths = []
+    if include_rsr:
+        url = HTTP_PYSPECTRAL_RSR if source_base_url is None else get_rsr_url(source_base_url)
+        urls_and_paths.append((url, RSR_MIRROR_PATH.format(version=RSR_DATA_VERSION)))
+    if include_luts:
+        for aerosol_type in (AEROSOL_TYPES if aerosol_types is None else aerosol_types):
+            if aerosol_type not in ATM_CORRECTION_LUT_VERSION:
+                raise ValueError(f"Unknown aerosol type: {aerosol_type}")
+            url = (HTTPS_RAYLEIGH_LUTS[aerosol_type] if source_base_url is None
+                   else get_rayleigh_lut_url(aerosol_type, source_base_url))
+            relative_path = LUT_MIRROR_PATH.format(
+                version=ATM_CORRECTION_LUT_VERSION[aerosol_type]["version"],
+                name=_aerosol_type_to_lut_name(aerosol_type),
+            )
+            urls_and_paths.append((url, relative_path))
+    return urls_and_paths
+
+
+def _download_tarball_to(url: str, local_pathname: Path) -> None:
+    """Download a tarball, checking that it is readable before putting it in place.
+
+    The file is downloaded to a temporary name and only moved to its final
+    location once it has been verified. An interrupted or corrupt download
+    therefore doesn't leave a file behind that later runs would consider
+    already mirrored.
+
+    """
+    incomplete_pathname = local_pathname.with_name(local_pathname.name + ".part")
+    try:
+        _download_file(url, incomplete_pathname)
+        with tarfile.open(incomplete_pathname) as tar:
+            tar.getmembers()
+        incomplete_pathname.replace(local_pathname)
+    finally:
+        incomplete_pathname.unlink(missing_ok=True)
+
+
 HEADERS = {
     "User-Agent": "pyspectral (+https://github.com/pytroll/pyspectral)",
     "Accept": "*/*",
@@ -435,10 +618,19 @@ HEADERS = {
 
 
 def _download_tarball_and_extract(tarball_url: str, local_pathname: Path, extract_dir: Path) -> None:
+    _download_file(tarball_url, local_pathname)
+
+    with tarfile.open(local_pathname) as tar:
+        tar.extractall(extract_dir, filter="data")
+
+    os.remove(local_pathname)
+
+
+def _download_file(url: str, local_pathname: Path) -> None:
     chunk_size = 1024 * 1024  # 1 MB
 
     response = requests.get(
-        tarball_url,
+        url,
         headers=HEADERS,
         stream=True,
         allow_redirects=True,
@@ -454,12 +646,6 @@ def _download_tarball_and_extract(tarball_url: str, local_pathname: Path, extrac
             if data:
                 handle.write(data)
 
-    tar_kwargs = {} if sys.version_info < (3, 12) else {"filter": "data"}
-    with tarfile.open(local_pathname) as tar:
-        tar.extractall(extract_dir, **tar_kwargs)  # type: ignore
-
-    os.remove(local_pathname)
-
 
 def _tqdm_or_iter(an_iterable, **tqdm_kwargs):
     """Wrap an iterable with tqdm if it is available, otherwise return the iterable."""


=====================================
rsr_convert_scripts/agri_rsr.py
=====================================
@@ -7,9 +7,8 @@ import os
 import numpy as np
 
 from pyspectral.raw_reader import InstrumentRSR
-from pyspectral.utils import INSTRUMENTS
+from pyspectral.utils import INSTRUMENTS, get_logger, logging_on
 from pyspectral.utils import convert2hdf5 as tohdf5
-from pyspectral.utils import get_logger, logging_on
 
 FY4_AGRI_BAND_NAMES = ['ch1', 'ch2', 'ch3', 'ch4', 'ch5', 'ch6', 'ch7', 'ch8',
                        'ch9', 'ch10', 'ch11', 'ch12', 'ch13', 'ch14', 'ch15']


=====================================
rsr_convert_scripts/ghi_rsr.py
=====================================
@@ -7,9 +7,8 @@ import os
 import numpy as np
 
 from pyspectral.raw_reader import InstrumentRSR
-from pyspectral.utils import INSTRUMENTS
+from pyspectral.utils import INSTRUMENTS, get_logger, logging_on
 from pyspectral.utils import convert2hdf5 as tohdf5
-from pyspectral.utils import get_logger, logging_on
 
 FY4_GHI_BAND_NAMES = ['ch1', 'ch2', 'ch3', 'ch4', 'ch5', 'ch6', 'ch7']
 BANDNAME_SCALE2MICROMETERS = {'FY-4B': {'ch1': 0.001,


=====================================
rsr_convert_scripts/mersirm_rsr.py
=====================================
@@ -7,9 +7,8 @@ import os
 import numpy as np
 
 from pyspectral.raw_reader import InstrumentRSR
-from pyspectral.utils import INSTRUMENTS
+from pyspectral.utils import INSTRUMENTS, get_logger, logging_on
 from pyspectral.utils import convert2hdf5 as tohdf5
-from pyspectral.utils import get_logger, logging_on
 
 FY3_MERSIRM_BAND_NAMES = ['ch1', 'ch2', 'ch3', 'ch4', 'ch5', 'ch6', 'ch7', 'ch8']
 


=====================================
rsr_convert_scripts/metimage_rsr.py
=====================================
@@ -32,11 +32,11 @@ def get_groupname_from_bandname(band):
     groupname = "LVWIR"
     wv = int(band.split("_")[-1])
     if wv > 6000:
-        groupname = "LVWIR"
+        groupname = "Instrument/ISRF/LVWIR"
     elif wv > 1000:
-        groupname = "SMWIR"
+        groupname = "Instrument/ISRF/SMWIR"
     else:
-        groupname = "VISNIR"
+        groupname = "Instrument/ISRF/VISNIR"
     return groupname
 
 


=====================================
setup.py
=====================================
@@ -55,9 +55,10 @@ setup(name=NAME,
                       'dask': dask_extra},
       scripts=['bin/plot_rsr.py', 'bin/composite_rsr_plot.py',
                'bin/download_atm_correction_luts.py',
-               'bin/download_rsr.py'],
+               'bin/download_rsr.py',
+               'bin/mirror_pyspectral_data.py'],
       data_files=[('share', ['pyspectral/data/e490_00a.dat',
                              'pyspectral/data/MSG_SEVIRI_Spectral_Response_Characterisation.XLS'])],
-      python_requires='>=3.10',
+      python_requires='>=3.12',
       zip_safe=False,
       )



View it on GitLab: https://salsa.debian.org/debian-gis-team/pyspectral/-/compare/3e5a73cd66998cb41cf669bcffcece2765f30a6b...c8664ec375233b4421631856d29354092077657d

-- 
View it on GitLab: https://salsa.debian.org/debian-gis-team/pyspectral/-/compare/3e5a73cd66998cb41cf669bcffcece2765f30a6b...c8664ec375233b4421631856d29354092077657d
You're receiving this email because of your account on salsa.debian.org. Manage all notifications: https://salsa.debian.org/-/profile/notifications | Help: https://salsa.debian.org/help


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://alioth-lists.debian.net/pipermail/pkg-grass-devel/attachments/20261122/db91bf1f/attachment-0001.htm>


More information about the Pkg-grass-devel mailing list