cloudnet-api-client 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- cloudnet_api_client-0.1.0/.github/workflows/publish.yml +36 -0
- cloudnet_api_client-0.1.0/.github/workflows/test.yml +27 -0
- cloudnet_api_client-0.1.0/.gitignore +3 -0
- cloudnet_api_client-0.1.0/.pre-commit-config.yaml +40 -0
- cloudnet_api_client-0.1.0/CHANGELOG.md +10 -0
- cloudnet_api_client-0.1.0/LICENSE +21 -0
- cloudnet_api_client-0.1.0/PKG-INFO +115 -0
- cloudnet_api_client-0.1.0/README.md +90 -0
- cloudnet_api_client-0.1.0/cloudnet_api_client/__init__.py +2 -0
- cloudnet_api_client-0.1.0/cloudnet_api_client/client.py +225 -0
- cloudnet_api_client-0.1.0/cloudnet_api_client/containers.py +68 -0
- cloudnet_api_client-0.1.0/cloudnet_api_client/dl.py +85 -0
- cloudnet_api_client-0.1.0/cloudnet_api_client/utils.py +21 -0
- cloudnet_api_client-0.1.0/cloudnet_api_client/version.py +1 -0
- cloudnet_api_client-0.1.0/pyproject.toml +48 -0
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
name: Upload Python Package
|
|
2
|
+
|
|
3
|
+
on:
|
|
4
|
+
push:
|
|
5
|
+
tags:
|
|
6
|
+
- "v*.*.*"
|
|
7
|
+
|
|
8
|
+
jobs:
|
|
9
|
+
deploy:
|
|
10
|
+
runs-on: ubuntu-latest
|
|
11
|
+
permissions:
|
|
12
|
+
contents: write
|
|
13
|
+
id-token: write
|
|
14
|
+
steps:
|
|
15
|
+
- uses: actions/checkout@v4
|
|
16
|
+
- name: Set up Python
|
|
17
|
+
uses: actions/setup-python@v5
|
|
18
|
+
with:
|
|
19
|
+
python-version: "3.10"
|
|
20
|
+
- name: Install dependencies
|
|
21
|
+
run: python -m pip install build
|
|
22
|
+
- name: Build package
|
|
23
|
+
run: python -m build
|
|
24
|
+
- name: Publish package
|
|
25
|
+
uses: pypa/gh-action-pypi-publish@release/v1
|
|
26
|
+
- name: Generate changelog
|
|
27
|
+
run: |
|
|
28
|
+
version=${GITHUB_REF#refs/tags/v}
|
|
29
|
+
sed "0,/^## ${version//./\\.}/d;/^## /,\$d" CHANGELOG.md > ${{ github.workspace }}-CHANGELOG.txt
|
|
30
|
+
echo "name=cloudnet-api-client $version" >> $GITHUB_OUTPUT
|
|
31
|
+
id: changelog
|
|
32
|
+
- name: Create release
|
|
33
|
+
uses: softprops/action-gh-release@v1
|
|
34
|
+
with:
|
|
35
|
+
name: ${{ steps.changelog.outputs.name }}
|
|
36
|
+
body_path: ${{ github.workspace }}-CHANGELOG.txt
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
name: Run tests
|
|
2
|
+
|
|
3
|
+
on: [push, pull_request]
|
|
4
|
+
|
|
5
|
+
jobs:
|
|
6
|
+
build:
|
|
7
|
+
strategy:
|
|
8
|
+
matrix:
|
|
9
|
+
os: [ubuntu-latest]
|
|
10
|
+
python-version: ["3.10", "3.11", "3.12", "3.13"]
|
|
11
|
+
|
|
12
|
+
runs-on: ${{ matrix.os }}
|
|
13
|
+
steps:
|
|
14
|
+
- uses: actions/checkout@v4
|
|
15
|
+
- name: Set up Python ${{ matrix.python-version }}
|
|
16
|
+
uses: actions/setup-python@v5
|
|
17
|
+
with:
|
|
18
|
+
python-version: ${{ matrix.python-version }}
|
|
19
|
+
cache: "pip"
|
|
20
|
+
- name: Install dependencies
|
|
21
|
+
run: |
|
|
22
|
+
pip install --upgrade pip
|
|
23
|
+
pip install .[dev,test]
|
|
24
|
+
- name: Run pre-commit checks
|
|
25
|
+
if: startsWith(matrix.os, 'ubuntu-')
|
|
26
|
+
run: |
|
|
27
|
+
pre-commit run --all-files --show-diff-on-failure
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
exclude: ^tests/data/
|
|
2
|
+
repos:
|
|
3
|
+
- repo: https://github.com/pre-commit/pre-commit-hooks
|
|
4
|
+
rev: v5.0.0
|
|
5
|
+
hooks:
|
|
6
|
+
- id: check-case-conflict
|
|
7
|
+
- id: check-executables-have-shebangs
|
|
8
|
+
- id: check-merge-conflict
|
|
9
|
+
- id: check-shebang-scripts-are-executable
|
|
10
|
+
- id: end-of-file-fixer
|
|
11
|
+
- id: fix-byte-order-marker
|
|
12
|
+
- id: mixed-line-ending
|
|
13
|
+
args: ["--fix", "lf"]
|
|
14
|
+
- id: trailing-whitespace
|
|
15
|
+
- repo: https://github.com/astral-sh/ruff-pre-commit
|
|
16
|
+
rev: v0.11.0
|
|
17
|
+
hooks:
|
|
18
|
+
- id: ruff
|
|
19
|
+
args: ["--fix"]
|
|
20
|
+
- id: ruff-format
|
|
21
|
+
- repo: local
|
|
22
|
+
hooks:
|
|
23
|
+
- id: mypy
|
|
24
|
+
name: mypy
|
|
25
|
+
entry: mypy
|
|
26
|
+
language: system
|
|
27
|
+
types: [python]
|
|
28
|
+
require_serial: true
|
|
29
|
+
- repo: https://github.com/pre-commit/mirrors-prettier
|
|
30
|
+
rev: v3.1.0
|
|
31
|
+
hooks:
|
|
32
|
+
- id: prettier
|
|
33
|
+
- repo: https://github.com/pappasam/toml-sort
|
|
34
|
+
rev: v0.24.2
|
|
35
|
+
hooks:
|
|
36
|
+
- id: toml-sort-fix
|
|
37
|
+
- repo: https://github.com/crate-ci/typos
|
|
38
|
+
rev: v1.30.2
|
|
39
|
+
hooks:
|
|
40
|
+
- id: typos
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes to this project will be documented in this file.
|
|
4
|
+
|
|
5
|
+
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
|
6
|
+
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
7
|
+
|
|
8
|
+
## 0.1.0 – 2025-03-27
|
|
9
|
+
|
|
10
|
+
- Initial release
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 Finnish Meteorological Institute
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: cloudnet-api-client
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Cloudnet API client
|
|
5
|
+
Author-email: Simo Tukiainen <simo.tukiainen@fmi.fi>
|
|
6
|
+
License-File: LICENSE
|
|
7
|
+
Classifier: Development Status :: 3 - Alpha
|
|
8
|
+
Classifier: Intended Audience :: Science/Research
|
|
9
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
10
|
+
Classifier: Operating System :: OS Independent
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: Topic :: Scientific/Engineering :: Atmospheric Science
|
|
13
|
+
Requires-Python: >=3.10
|
|
14
|
+
Requires-Dist: aiohttp
|
|
15
|
+
Requires-Dist: numpy
|
|
16
|
+
Requires-Dist: requests
|
|
17
|
+
Provides-Extra: dev
|
|
18
|
+
Requires-Dist: pre-commit; extra == 'dev'
|
|
19
|
+
Requires-Dist: release-version; extra == 'dev'
|
|
20
|
+
Requires-Dist: types-requests; extra == 'dev'
|
|
21
|
+
Provides-Extra: test
|
|
22
|
+
Requires-Dist: mypy; extra == 'test'
|
|
23
|
+
Requires-Dist: pytest; extra == 'test'
|
|
24
|
+
Description-Content-Type: text/markdown
|
|
25
|
+
|
|
26
|
+
[](https://github.com/actris-cloudnet/cloudnet-api-client/actions/workflows/test.yml)
|
|
27
|
+
|
|
28
|
+
# cloudnet-api-client
|
|
29
|
+
|
|
30
|
+
Official Python package for using Cloudnet API
|
|
31
|
+
|
|
32
|
+
## Quickstart
|
|
33
|
+
|
|
34
|
+
```python
|
|
35
|
+
import cloudnet_api_client as cac
|
|
36
|
+
|
|
37
|
+
client = cac.APIClient()
|
|
38
|
+
|
|
39
|
+
sites = client.sites(type="cloudnet")
|
|
40
|
+
products = client.products()
|
|
41
|
+
|
|
42
|
+
metadata = client.metadata("hyytiala", "2021-01-01", product=["mwr", "radar"])
|
|
43
|
+
cac.download(metadata, "data")
|
|
44
|
+
|
|
45
|
+
raw_metadata = client.metadata("hyytiala", "2021-01-01")
|
|
46
|
+
cac.download(raw_metadata, "data_raw")
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
## Documentation
|
|
50
|
+
|
|
51
|
+
### `APIClient().metadata()` and `raw_metadata()` → `[Metadata]`
|
|
52
|
+
|
|
53
|
+
Fetch product and raw file metadata from the Cloudnet data portal.
|
|
54
|
+
|
|
55
|
+
Parameters:
|
|
56
|
+
|
|
57
|
+
| name | type | default | example |
|
|
58
|
+
| -------------- | ------------------------ | ------- | ---------------------------------------------------- |
|
|
59
|
+
| site_id | `str` | | "hyytiala" |
|
|
60
|
+
| date | `str` or `datetime.date` | `None` | "2024-01-01" |
|
|
61
|
+
| date_from | `str` or `datetime.date` | `None` | "2025-01-01" |
|
|
62
|
+
| date_to | `str` or `datetime.date` | `None` | "2025-01-01" |
|
|
63
|
+
| instrument_id | `str` or `[str]` | `None` | "rpg-fmcw-94" |
|
|
64
|
+
| instrument_pid | `str` or `[str]` | `None` | "https://hdl.handle.net/21.12132/3.191564170f8a4686" |
|
|
65
|
+
| product\* | `str` or `[str]` | `None` | "classification" |
|
|
66
|
+
| show_legacy\* | `bool` | `False` | |
|
|
67
|
+
|
|
68
|
+
\* = only in `metadata()`
|
|
69
|
+
|
|
70
|
+
**Date Handling**
|
|
71
|
+
|
|
72
|
+
The `date` parameter supports:
|
|
73
|
+
|
|
74
|
+
- "YYYY-MM-DD" — a specific date
|
|
75
|
+
- "YYYY-MM" — the entire month
|
|
76
|
+
- "YYYY" — the entire year
|
|
77
|
+
- Or directly as `datetime.date` object
|
|
78
|
+
|
|
79
|
+
The `date_from` and `date_to` parameters should be "YYYY-MM-DD" or `datetime.date`. If `date` is defined, `date_from` and `date_to` have no effect.
|
|
80
|
+
|
|
81
|
+
**Return value**
|
|
82
|
+
|
|
83
|
+
Both methods return a list of `dataclass` instances, `ProductMetadata` and `RawMetadata`, respectively.
|
|
84
|
+
|
|
85
|
+
### `APIClient().filter([Metadata])` → `[Metadata]`
|
|
86
|
+
|
|
87
|
+
Additional filtering of fetched metadata.
|
|
88
|
+
|
|
89
|
+
Parameters:
|
|
90
|
+
|
|
91
|
+
| name | type | default |
|
|
92
|
+
| ------------------ | -------------------------------------- | ------- |
|
|
93
|
+
| metadata | `[RawMetadata]` or `[ProductMetadata]` | |
|
|
94
|
+
| include_pattern | `str` | `None` |
|
|
95
|
+
| exclude_pattern | `str` | `None` |
|
|
96
|
+
| filename_prefix | `str` | `None` |
|
|
97
|
+
| filename_suffix | `str` | `None` |
|
|
98
|
+
| include_tag_subset | `{str}` | `None` |
|
|
99
|
+
| exclude_tag_subset | `{str}` | `None` |
|
|
100
|
+
|
|
101
|
+
### `cloudnet_api_client.download([Metadata])`
|
|
102
|
+
|
|
103
|
+
Function to download files from fetched metadata.
|
|
104
|
+
|
|
105
|
+
Parameters:
|
|
106
|
+
|
|
107
|
+
| name | type | default |
|
|
108
|
+
| ----------------- | -------------------------------------- | ------- |
|
|
109
|
+
| metadata | `[RawMetadata]` or `[ProductMetadata]` | |
|
|
110
|
+
| output_directory | `PathLike` | |
|
|
111
|
+
| concurrency_limit | `int` | 5 |
|
|
112
|
+
|
|
113
|
+
## License
|
|
114
|
+
|
|
115
|
+
MIT
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
[](https://github.com/actris-cloudnet/cloudnet-api-client/actions/workflows/test.yml)
|
|
2
|
+
|
|
3
|
+
# cloudnet-api-client
|
|
4
|
+
|
|
5
|
+
Official Python package for using Cloudnet API
|
|
6
|
+
|
|
7
|
+
## Quickstart
|
|
8
|
+
|
|
9
|
+
```python
|
|
10
|
+
import cloudnet_api_client as cac
|
|
11
|
+
|
|
12
|
+
client = cac.APIClient()
|
|
13
|
+
|
|
14
|
+
sites = client.sites(type="cloudnet")
|
|
15
|
+
products = client.products()
|
|
16
|
+
|
|
17
|
+
metadata = client.metadata("hyytiala", "2021-01-01", product=["mwr", "radar"])
|
|
18
|
+
cac.download(metadata, "data")
|
|
19
|
+
|
|
20
|
+
raw_metadata = client.metadata("hyytiala", "2021-01-01")
|
|
21
|
+
cac.download(raw_metadata, "data_raw")
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
## Documentation
|
|
25
|
+
|
|
26
|
+
### `APIClient().metadata()` and `raw_metadata()` → `[Metadata]`
|
|
27
|
+
|
|
28
|
+
Fetch product and raw file metadata from the Cloudnet data portal.
|
|
29
|
+
|
|
30
|
+
Parameters:
|
|
31
|
+
|
|
32
|
+
| name | type | default | example |
|
|
33
|
+
| -------------- | ------------------------ | ------- | ---------------------------------------------------- |
|
|
34
|
+
| site_id | `str` | | "hyytiala" |
|
|
35
|
+
| date | `str` or `datetime.date` | `None` | "2024-01-01" |
|
|
36
|
+
| date_from | `str` or `datetime.date` | `None` | "2025-01-01" |
|
|
37
|
+
| date_to | `str` or `datetime.date` | `None` | "2025-01-01" |
|
|
38
|
+
| instrument_id | `str` or `[str]` | `None` | "rpg-fmcw-94" |
|
|
39
|
+
| instrument_pid | `str` or `[str]` | `None` | "https://hdl.handle.net/21.12132/3.191564170f8a4686" |
|
|
40
|
+
| product\* | `str` or `[str]` | `None` | "classification" |
|
|
41
|
+
| show_legacy\* | `bool` | `False` | |
|
|
42
|
+
|
|
43
|
+
\* = only in `metadata()`
|
|
44
|
+
|
|
45
|
+
**Date Handling**
|
|
46
|
+
|
|
47
|
+
The `date` parameter supports:
|
|
48
|
+
|
|
49
|
+
- "YYYY-MM-DD" — a specific date
|
|
50
|
+
- "YYYY-MM" — the entire month
|
|
51
|
+
- "YYYY" — the entire year
|
|
52
|
+
- Or directly as `datetime.date` object
|
|
53
|
+
|
|
54
|
+
The `date_from` and `date_to` parameters should be "YYYY-MM-DD" or `datetime.date`. If `date` is defined, `date_from` and `date_to` have no effect.
|
|
55
|
+
|
|
56
|
+
**Return value**
|
|
57
|
+
|
|
58
|
+
Both methods return a list of `dataclass` instances, `ProductMetadata` and `RawMetadata`, respectively.
|
|
59
|
+
|
|
60
|
+
### `APIClient().filter([Metadata])` → `[Metadata]`
|
|
61
|
+
|
|
62
|
+
Additional filtering of fetched metadata.
|
|
63
|
+
|
|
64
|
+
Parameters:
|
|
65
|
+
|
|
66
|
+
| name | type | default |
|
|
67
|
+
| ------------------ | -------------------------------------- | ------- |
|
|
68
|
+
| metadata | `[RawMetadata]` or `[ProductMetadata]` | |
|
|
69
|
+
| include_pattern | `str` | `None` |
|
|
70
|
+
| exclude_pattern | `str` | `None` |
|
|
71
|
+
| filename_prefix | `str` | `None` |
|
|
72
|
+
| filename_suffix | `str` | `None` |
|
|
73
|
+
| include_tag_subset | `{str}` | `None` |
|
|
74
|
+
| exclude_tag_subset | `{str}` | `None` |
|
|
75
|
+
|
|
76
|
+
### `cloudnet_api_client.download([Metadata])`
|
|
77
|
+
|
|
78
|
+
Function to download files from fetched metadata.
|
|
79
|
+
|
|
80
|
+
Parameters:
|
|
81
|
+
|
|
82
|
+
| name | type | default |
|
|
83
|
+
| ----------------- | -------------------------------------- | ------- |
|
|
84
|
+
| metadata | `[RawMetadata]` or `[ProductMetadata]` | |
|
|
85
|
+
| output_directory | `PathLike` | |
|
|
86
|
+
| concurrency_limit | `int` | 5 |
|
|
87
|
+
|
|
88
|
+
## License
|
|
89
|
+
|
|
90
|
+
MIT
|
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
import calendar
|
|
2
|
+
import datetime
|
|
3
|
+
import re
|
|
4
|
+
from dataclasses import fields, is_dataclass
|
|
5
|
+
from typing import TypeVar, cast
|
|
6
|
+
from urllib.parse import urljoin
|
|
7
|
+
|
|
8
|
+
import requests
|
|
9
|
+
from requests.adapters import HTTPAdapter
|
|
10
|
+
from urllib3.util.retry import Retry
|
|
11
|
+
|
|
12
|
+
from cloudnet_api_client.containers import (
|
|
13
|
+
PRODUCT_TYPE,
|
|
14
|
+
SITE_TYPE,
|
|
15
|
+
Instrument,
|
|
16
|
+
Metadata,
|
|
17
|
+
Product,
|
|
18
|
+
ProductMetadata,
|
|
19
|
+
RawMetadata,
|
|
20
|
+
Site,
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
T = TypeVar("T")
|
|
24
|
+
DateParam = str | datetime.date | None
|
|
25
|
+
QueryParam = str | list[str] | None
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class APIClient:
|
|
29
|
+
def __init__(
|
|
30
|
+
self,
|
|
31
|
+
base_url: str = "https://cloudnet.fmi.fi/api/",
|
|
32
|
+
session: requests.Session | None = None,
|
|
33
|
+
) -> None:
|
|
34
|
+
self.base_url = base_url
|
|
35
|
+
self.session = session or _make_session()
|
|
36
|
+
|
|
37
|
+
def sites(self, type: SITE_TYPE | list[SITE_TYPE] | None = None) -> list[Site]:
|
|
38
|
+
params = {"type": type}
|
|
39
|
+
res = self._get_response("sites", params)
|
|
40
|
+
return _build_objects(res, Site)
|
|
41
|
+
|
|
42
|
+
def products(
|
|
43
|
+
self, type: PRODUCT_TYPE | list[PRODUCT_TYPE] | None = None
|
|
44
|
+
) -> list[Product]:
|
|
45
|
+
res = self._get_response("products")
|
|
46
|
+
data = _build_objects(res, Product)
|
|
47
|
+
if isinstance(type, str):
|
|
48
|
+
data = [obj for obj in data if type in obj.type]
|
|
49
|
+
elif isinstance(type, list):
|
|
50
|
+
data = [obj for obj in data if any(t in obj.type for t in type)]
|
|
51
|
+
return data
|
|
52
|
+
|
|
53
|
+
def metadata(
|
|
54
|
+
self,
|
|
55
|
+
site_id: str,
|
|
56
|
+
date: DateParam = None,
|
|
57
|
+
date_from: DateParam = None,
|
|
58
|
+
date_to: DateParam = None,
|
|
59
|
+
instrument_id: QueryParam = None,
|
|
60
|
+
instrument_pid: QueryParam = None,
|
|
61
|
+
product: QueryParam = None,
|
|
62
|
+
show_legacy: bool = False,
|
|
63
|
+
) -> list[ProductMetadata]:
|
|
64
|
+
params = {
|
|
65
|
+
"site": site_id,
|
|
66
|
+
"instrument": instrument_id,
|
|
67
|
+
"instrumentPid": instrument_pid,
|
|
68
|
+
"product": product,
|
|
69
|
+
"showLegacy": show_legacy,
|
|
70
|
+
}
|
|
71
|
+
date_params = self._mangle_dates(date, date_from, date_to)
|
|
72
|
+
params.update(date_params)
|
|
73
|
+
res = self._get_response("files", params)
|
|
74
|
+
return _build_objects(res, ProductMetadata)
|
|
75
|
+
|
|
76
|
+
def raw_metadata(
|
|
77
|
+
self,
|
|
78
|
+
site_id: str,
|
|
79
|
+
date: DateParam = None,
|
|
80
|
+
date_from: DateParam = None,
|
|
81
|
+
date_to: DateParam = None,
|
|
82
|
+
instrument_id: QueryParam = None,
|
|
83
|
+
instrument_pid: QueryParam = None,
|
|
84
|
+
) -> list[RawMetadata]:
|
|
85
|
+
params = {
|
|
86
|
+
"site": site_id,
|
|
87
|
+
"instrument": instrument_id,
|
|
88
|
+
"instrumentPid": instrument_pid,
|
|
89
|
+
}
|
|
90
|
+
date_params = self._mangle_dates(date, date_from, date_to)
|
|
91
|
+
params.update(date_params)
|
|
92
|
+
res = self._get_response("raw-files", params)
|
|
93
|
+
return _build_raw_meta_objects(res)
|
|
94
|
+
|
|
95
|
+
@staticmethod
|
|
96
|
+
def filter(
|
|
97
|
+
metadata: list[Metadata],
|
|
98
|
+
include_pattern: str | None = None,
|
|
99
|
+
exclude_pattern: str | None = None,
|
|
100
|
+
filename_prefix: str | None = None,
|
|
101
|
+
filename_suffix: str | None = None,
|
|
102
|
+
include_tag_subset: set[str] | None = None,
|
|
103
|
+
exclude_tag_subset: set[str] | None = None,
|
|
104
|
+
) -> list[Metadata]:
|
|
105
|
+
if include_pattern:
|
|
106
|
+
metadata = [
|
|
107
|
+
m for m in metadata if re.search(include_pattern, m.filename, re.I)
|
|
108
|
+
]
|
|
109
|
+
if exclude_pattern:
|
|
110
|
+
metadata = [
|
|
111
|
+
m for m in metadata if not re.search(exclude_pattern, m.filename, re.I)
|
|
112
|
+
]
|
|
113
|
+
if filename_prefix:
|
|
114
|
+
metadata = [m for m in metadata if m.filename.startswith(filename_prefix)]
|
|
115
|
+
if filename_suffix:
|
|
116
|
+
metadata = [m for m in metadata if m.filename.endswith(filename_suffix)]
|
|
117
|
+
if include_tag_subset:
|
|
118
|
+
metadata = [
|
|
119
|
+
m
|
|
120
|
+
for m in metadata
|
|
121
|
+
if isinstance(m, RawMetadata)
|
|
122
|
+
and m.tags
|
|
123
|
+
and include_tag_subset.issubset(m.tags)
|
|
124
|
+
]
|
|
125
|
+
if exclude_tag_subset:
|
|
126
|
+
metadata = [
|
|
127
|
+
m
|
|
128
|
+
for m in metadata
|
|
129
|
+
if isinstance(m, RawMetadata)
|
|
130
|
+
and m.tags
|
|
131
|
+
and not exclude_tag_subset.issubset(m.tags)
|
|
132
|
+
]
|
|
133
|
+
return metadata
|
|
134
|
+
|
|
135
|
+
def _get_response(self, endpoint: str, params: dict | None = None) -> list[dict]:
|
|
136
|
+
url = urljoin(self.base_url, endpoint)
|
|
137
|
+
res = self.session.get(url, params=params, timeout=120)
|
|
138
|
+
res.raise_for_status()
|
|
139
|
+
return res.json()
|
|
140
|
+
|
|
141
|
+
def _mangle_dates(
|
|
142
|
+
self, date: DateParam, date_from: DateParam, date_to: DateParam
|
|
143
|
+
) -> dict:
|
|
144
|
+
params = {}
|
|
145
|
+
if isinstance(date, str):
|
|
146
|
+
if re.fullmatch(r"\d{4}-\d{2}-\d{2}", date):
|
|
147
|
+
params["date"] = self._parse_date(date)
|
|
148
|
+
elif re.fullmatch(r"\d{4}-\d{2}", date):
|
|
149
|
+
date = datetime.datetime.strptime(date, "%Y-%m")
|
|
150
|
+
last_day_number = calendar.monthrange(date.year, date.month)[1]
|
|
151
|
+
params["dateFrom"] = datetime.date(date.year, date.month, 1)
|
|
152
|
+
params["dateTo"] = datetime.date(date.year, date.month, last_day_number)
|
|
153
|
+
elif re.fullmatch(r"\d{4}", date):
|
|
154
|
+
params["dateFrom"] = datetime.date(int(date), 1, 1)
|
|
155
|
+
params["dateTo"] = datetime.date(int(date), 12, 31)
|
|
156
|
+
else:
|
|
157
|
+
raise ValueError("Invalid date format")
|
|
158
|
+
elif isinstance(date, datetime.date):
|
|
159
|
+
params["date"] = date
|
|
160
|
+
else:
|
|
161
|
+
if date_from:
|
|
162
|
+
params["dateFrom"] = self._parse_date(date_from)
|
|
163
|
+
if date_to:
|
|
164
|
+
params["dateTo"] = self._parse_date(date_to)
|
|
165
|
+
return params
|
|
166
|
+
|
|
167
|
+
@staticmethod
|
|
168
|
+
def _parse_date(date: DateParam) -> datetime.date:
|
|
169
|
+
if not date:
|
|
170
|
+
raise ValueError("Date parameter is required")
|
|
171
|
+
if isinstance(date, datetime.date):
|
|
172
|
+
return date
|
|
173
|
+
try:
|
|
174
|
+
return datetime.datetime.strptime(date, "%Y-%m-%d").date()
|
|
175
|
+
except ValueError as e:
|
|
176
|
+
raise ValueError(f"Invalid date format: {date}") from e
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def _build_objects(res: list[dict], object_type: type[T]) -> list[T]:
|
|
180
|
+
assert is_dataclass(object_type)
|
|
181
|
+
field_names = {f.name for f in fields(object_type)}
|
|
182
|
+
instances = [
|
|
183
|
+
object_type(
|
|
184
|
+
**{_to_snake(k): v for k, v in obj.items() if _to_snake(k) in field_names}
|
|
185
|
+
)
|
|
186
|
+
for obj in res
|
|
187
|
+
]
|
|
188
|
+
return cast(list[T], instances)
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def _build_raw_meta_objects(res: list[dict]) -> list[RawMetadata]:
|
|
192
|
+
field_names = {f.name for f in fields(RawMetadata)} - {"instrument"}
|
|
193
|
+
return [
|
|
194
|
+
RawMetadata(
|
|
195
|
+
**{_to_snake(k): v for k, v in obj.items() if _to_snake(k) in field_names},
|
|
196
|
+
instrument=_construct_instrument(obj),
|
|
197
|
+
)
|
|
198
|
+
for obj in res
|
|
199
|
+
]
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def _construct_instrument(obj: dict) -> Instrument:
|
|
203
|
+
return Instrument(
|
|
204
|
+
instrument_id=obj["instrumentInfo"]["instrumentId"],
|
|
205
|
+
model=obj["instrumentInfo"]["model"],
|
|
206
|
+
type=obj["instrumentInfo"]["type"],
|
|
207
|
+
uuid=obj["instrumentInfo"]["uuid"],
|
|
208
|
+
pid=obj["instrumentInfo"]["pid"],
|
|
209
|
+
owners=obj["instrumentInfo"]["owners"],
|
|
210
|
+
serial_number=obj["instrumentInfo"]["serialNumber"],
|
|
211
|
+
name=obj["instrumentInfo"]["name"],
|
|
212
|
+
)
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def _to_snake(name: str) -> str:
|
|
216
|
+
return re.sub(r"(?<!^)(?=[A-Z])", "_", name).lower()
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def _make_session() -> requests.Session:
|
|
220
|
+
session = requests.Session()
|
|
221
|
+
retry_strategy = Retry(total=10, backoff_factor=0.1, status_forcelist=[524])
|
|
222
|
+
adapter = HTTPAdapter(max_retries=retry_strategy)
|
|
223
|
+
session.mount("https://", adapter)
|
|
224
|
+
session.mount("http://", adapter)
|
|
225
|
+
return session
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import uuid
|
|
2
|
+
from dataclasses import dataclass
|
|
3
|
+
from typing import Literal
|
|
4
|
+
|
|
5
|
+
SITE_TYPE = Literal["cloudnet", "model", "hidden", "campaign"]
|
|
6
|
+
PRODUCT_TYPE = Literal["instrument", "geophysical", "evaluation"]
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
@dataclass(frozen=True, slots=True)
|
|
10
|
+
class Site:
|
|
11
|
+
id: str
|
|
12
|
+
human_readable_name: str
|
|
13
|
+
station_name: str | None
|
|
14
|
+
latitude: float
|
|
15
|
+
longitude: float
|
|
16
|
+
altitude: float
|
|
17
|
+
dvas_id: str | None
|
|
18
|
+
actris_id: int | None
|
|
19
|
+
country: str
|
|
20
|
+
country_code: str
|
|
21
|
+
country_subdivision_code: str | None
|
|
22
|
+
type: SITE_TYPE
|
|
23
|
+
status: Literal["active", "inactive"]
|
|
24
|
+
gaw: str | None
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@dataclass(frozen=True, slots=True)
|
|
28
|
+
class Product:
|
|
29
|
+
id: str
|
|
30
|
+
human_readable_name: str
|
|
31
|
+
type: PRODUCT_TYPE
|
|
32
|
+
experimental: bool
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@dataclass(frozen=True, slots=True)
|
|
36
|
+
class Instrument:
|
|
37
|
+
instrument_id: str # CLU internal identifier, e.g. "rpg-fmcw-94"
|
|
38
|
+
model: str # From ACTRIS Vocabulary, e.g. "RPG-FMCW-94 DP"
|
|
39
|
+
type: str # From ACTRIS Vocabulary, e.g. "Doppler non-scanning cloud radar"
|
|
40
|
+
name: str # e.g. "FMI RPG-FMCW-94 (Pallas)"
|
|
41
|
+
uuid: uuid.UUID
|
|
42
|
+
pid: str
|
|
43
|
+
owners: list[str]
|
|
44
|
+
serial_number: str | None
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
@dataclass(frozen=True, slots=True)
|
|
48
|
+
class Metadata:
|
|
49
|
+
uuid: uuid.UUID
|
|
50
|
+
checksum: str
|
|
51
|
+
size: int
|
|
52
|
+
filename: str
|
|
53
|
+
measurement_date: str
|
|
54
|
+
download_url: str
|
|
55
|
+
created_at: str
|
|
56
|
+
updated_at: str
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
@dataclass(frozen=True, slots=True)
|
|
60
|
+
class RawMetadata(Metadata):
|
|
61
|
+
status: Literal["created", "uploaded", "processed", "invalid"]
|
|
62
|
+
instrument: Instrument
|
|
63
|
+
tags: list[str] | None
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
@dataclass(frozen=True, slots=True)
|
|
67
|
+
class ProductMetadata(Metadata):
|
|
68
|
+
product: Product
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
import logging
|
|
3
|
+
import os
|
|
4
|
+
from os import PathLike
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
import aiohttp
|
|
8
|
+
|
|
9
|
+
from cloudnet_api_client import utils
|
|
10
|
+
from cloudnet_api_client.containers import ProductMetadata, RawMetadata
|
|
11
|
+
|
|
12
|
+
MetadataList = list[ProductMetadata] | list[RawMetadata]
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def download(
|
|
16
|
+
metadata: MetadataList, output_directory: str | PathLike, concurrency_limit: int = 5
|
|
17
|
+
) -> None:
|
|
18
|
+
os.makedirs(output_directory, exist_ok=True)
|
|
19
|
+
asyncio.run(_download_files(metadata, output_directory, concurrency_limit))
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
async def _download_files(
|
|
23
|
+
metadata: MetadataList, output_path: str | PathLike, concurrency_limit: int
|
|
24
|
+
) -> None:
|
|
25
|
+
semaphore = asyncio.Semaphore(concurrency_limit)
|
|
26
|
+
async with aiohttp.ClientSession() as session:
|
|
27
|
+
tasks = []
|
|
28
|
+
for meta in metadata:
|
|
29
|
+
destination = output_path / Path(meta.download_url.split("/")[-1])
|
|
30
|
+
if destination.exists() and _file_checksum_matches(meta, destination):
|
|
31
|
+
logging.info(f"Already downloaded: {destination}")
|
|
32
|
+
continue
|
|
33
|
+
task = asyncio.create_task(
|
|
34
|
+
_download_file_with_retries(
|
|
35
|
+
session, meta.download_url, destination, semaphore
|
|
36
|
+
)
|
|
37
|
+
)
|
|
38
|
+
tasks.append(task)
|
|
39
|
+
await asyncio.gather(*tasks)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
async def _download_file_with_retries(
|
|
43
|
+
session: aiohttp.ClientSession,
|
|
44
|
+
url: str,
|
|
45
|
+
destination: Path,
|
|
46
|
+
semaphore: asyncio.Semaphore,
|
|
47
|
+
max_retries: int = 3,
|
|
48
|
+
) -> None:
|
|
49
|
+
"""Attempt to download a file, retrying up to max_retries times if needed."""
|
|
50
|
+
for attempt in range(1, max_retries + 1):
|
|
51
|
+
try:
|
|
52
|
+
await _download_file(session, url, destination, semaphore)
|
|
53
|
+
return
|
|
54
|
+
except Exception as e:
|
|
55
|
+
logging.warning(f"Attempt {attempt} failed for {url}: {e}")
|
|
56
|
+
if attempt == max_retries:
|
|
57
|
+
logging.error(f"Giving up on {url} after {max_retries} attempts.")
|
|
58
|
+
else:
|
|
59
|
+
# Exponential backoff before retrying
|
|
60
|
+
await asyncio.sleep(2**attempt)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
async def _download_file(
|
|
64
|
+
session: aiohttp.ClientSession,
|
|
65
|
+
url: str,
|
|
66
|
+
destination: Path,
|
|
67
|
+
semaphore: asyncio.Semaphore,
|
|
68
|
+
) -> None:
|
|
69
|
+
async with semaphore:
|
|
70
|
+
async with session.get(url) as response:
|
|
71
|
+
response.raise_for_status()
|
|
72
|
+
with destination.open("wb") as file_out:
|
|
73
|
+
while True:
|
|
74
|
+
chunk = await response.content.read(8192)
|
|
75
|
+
if not chunk:
|
|
76
|
+
break
|
|
77
|
+
file_out.write(chunk)
|
|
78
|
+
logging.info(f"Downloaded: {destination}")
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _file_checksum_matches(
|
|
82
|
+
meta: ProductMetadata | RawMetadata, destination: Path
|
|
83
|
+
) -> bool:
|
|
84
|
+
fun = utils.md5sum if isinstance(meta, RawMetadata) else utils.sha256sum
|
|
85
|
+
return fun(destination) == meta.checksum
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import base64
|
|
2
|
+
import hashlib
|
|
3
|
+
import os
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def sha256sum(filename: str | os.PathLike) -> str:
|
|
7
|
+
return _calc_hash_sum(filename, "sha256", is_base64=False)
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def md5sum(filename: str | os.PathLike, *, is_base64: bool = False) -> str:
|
|
11
|
+
return _calc_hash_sum(filename, "md5", is_base64=is_base64)
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _calc_hash_sum(filename, method, *, is_base64: bool) -> str:
|
|
15
|
+
hash_sum = getattr(hashlib, method)()
|
|
16
|
+
with open(filename, "rb") as f:
|
|
17
|
+
for byte_block in iter(lambda: f.read(4096), b""):
|
|
18
|
+
hash_sum.update(byte_block)
|
|
19
|
+
if is_base64:
|
|
20
|
+
return base64.encodebytes(hash_sum.digest()).decode("utf-8").strip()
|
|
21
|
+
return hash_sum.hexdigest()
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.1.0"
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "cloudnet-api-client"
|
|
7
|
+
authors = [
|
|
8
|
+
{name = "Simo Tukiainen", email = "simo.tukiainen@fmi.fi"},
|
|
9
|
+
]
|
|
10
|
+
description = "Cloudnet API client"
|
|
11
|
+
readme = "README.md"
|
|
12
|
+
requires-python = ">=3.10"
|
|
13
|
+
classifiers = [
|
|
14
|
+
"Development Status :: 3 - Alpha",
|
|
15
|
+
"Intended Audience :: Science/Research",
|
|
16
|
+
"License :: OSI Approved :: MIT License",
|
|
17
|
+
"Operating System :: OS Independent",
|
|
18
|
+
"Programming Language :: Python :: 3",
|
|
19
|
+
"Topic :: Scientific/Engineering :: Atmospheric Science",
|
|
20
|
+
]
|
|
21
|
+
dependencies = ["aiohttp", "numpy", "requests"]
|
|
22
|
+
dynamic = ["version"]
|
|
23
|
+
|
|
24
|
+
[project.optional-dependencies]
|
|
25
|
+
test = ["mypy", "pytest"]
|
|
26
|
+
dev = ["pre-commit", "release-version", "types-requests"]
|
|
27
|
+
|
|
28
|
+
[tool.hatch.version]
|
|
29
|
+
path = "cloudnet_api_client/version.py"
|
|
30
|
+
|
|
31
|
+
[tool.release-version]
|
|
32
|
+
filename = "cloudnet_api_client/version.py"
|
|
33
|
+
pattern = ["__version__ = \"(?P<major>\\d+).(?P<minor>\\d+).(?P<patch>\\d+)\""]
|
|
34
|
+
changelog = "CHANGELOG.md"
|
|
35
|
+
|
|
36
|
+
[tool.ruff.lint]
|
|
37
|
+
select = ["B", "D", "E", "F", "I", "PLC", "PLE", "PLW", "SIM", "UP"]
|
|
38
|
+
ignore = ["D1"]
|
|
39
|
+
|
|
40
|
+
[tool.ruff.lint.per-file-ignores]
|
|
41
|
+
"__init__.py" = ["PLC0414"]
|
|
42
|
+
|
|
43
|
+
[tool.ruff.lint.pydocstyle]
|
|
44
|
+
convention = "google"
|
|
45
|
+
|
|
46
|
+
[tool.tomlsort]
|
|
47
|
+
trailing_comma_inline_array = true
|
|
48
|
+
sort_inline_arrays = true
|