cloudnet-api-client 0.1.0__py3-none-any.whl

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.
@@ -0,0 +1,2 @@
1
+ from .client import APIClient as APIClient
2
+ from .dl import download as download
@@ -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,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
+ [![CI](https://github.com/actris-cloudnet/cloudnet-api-client/actions/workflows/test.yml/badge.svg)](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()` &rarr; `[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])` &rarr; `[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,10 @@
1
+ cloudnet_api_client/__init__.py,sha256=JPAo-7s_m8hOaUoo3dD2y4-1adnWRc3cDlPYZZ4iCBQ,80
2
+ cloudnet_api_client/client.py,sha256=XCD7fDiccuZK0svHjpdKg-Xlk4tIy_S_DTZM85fozKs,7673
3
+ cloudnet_api_client/containers.py,sha256=ZiFYajBJSqozPidtSNMWNirLW28EgLIK9nBVhUcmbPE,1633
4
+ cloudnet_api_client/dl.py,sha256=DIKAmufx4CHFHwbkNlMf8ewAvyDvk7R9yPXe44ljsIg,2846
5
+ cloudnet_api_client/utils.py,sha256=bsaXzBTdfWxtmNnFV0TCjguoMs7Lg5O7Zr1Zqg1mhmQ,668
6
+ cloudnet_api_client/version.py,sha256=kUR5RAFc7HCeiqdlX36dZOHkUI5wI6V_43RpEcD8b-0,22
7
+ cloudnet_api_client-0.1.0.dist-info/METADATA,sha256=EhiSJaEAC_yBblDyEZBzK11I0prHhY5m7qiYasAR0ZU,4525
8
+ cloudnet_api_client-0.1.0.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
9
+ cloudnet_api_client-0.1.0.dist-info/licenses/LICENSE,sha256=Y6pKDExM0r2aQQ6V2hHcb08_nqD7KutrC-aUhKuxDH4,1089
10
+ cloudnet_api_client-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.27.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -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.