cloudnet-api-client 0.1.2__tar.gz → 0.2.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.
Files changed (21) hide show
  1. {cloudnet_api_client-0.1.2 → cloudnet_api_client-0.2.0}/CHANGELOG.md +14 -0
  2. cloudnet_api_client-0.2.0/PKG-INFO +160 -0
  3. cloudnet_api_client-0.2.0/README.md +133 -0
  4. {cloudnet_api_client-0.1.2 → cloudnet_api_client-0.2.0}/cloudnet_api_client/__init__.py +1 -0
  5. cloudnet_api_client-0.2.0/cloudnet_api_client/client.py +338 -0
  6. {cloudnet_api_client-0.1.2 → cloudnet_api_client-0.2.0}/cloudnet_api_client/containers.py +3 -3
  7. {cloudnet_api_client-0.1.2 → cloudnet_api_client-0.2.0}/cloudnet_api_client/dl.py +43 -8
  8. cloudnet_api_client-0.2.0/cloudnet_api_client/py.typed +0 -0
  9. cloudnet_api_client-0.2.0/cloudnet_api_client/utils.py +19 -0
  10. cloudnet_api_client-0.2.0/cloudnet_api_client/version.py +1 -0
  11. {cloudnet_api_client-0.1.2 → cloudnet_api_client-0.2.0}/pyproject.toml +2 -2
  12. cloudnet_api_client-0.1.2/PKG-INFO +0 -148
  13. cloudnet_api_client-0.1.2/README.md +0 -123
  14. cloudnet_api_client-0.1.2/cloudnet_api_client/client.py +0 -258
  15. cloudnet_api_client-0.1.2/cloudnet_api_client/utils.py +0 -21
  16. cloudnet_api_client-0.1.2/cloudnet_api_client/version.py +0 -1
  17. {cloudnet_api_client-0.1.2 → cloudnet_api_client-0.2.0}/.github/workflows/publish.yml +0 -0
  18. {cloudnet_api_client-0.1.2 → cloudnet_api_client-0.2.0}/.github/workflows/test.yml +0 -0
  19. {cloudnet_api_client-0.1.2 → cloudnet_api_client-0.2.0}/.gitignore +0 -0
  20. {cloudnet_api_client-0.1.2 → cloudnet_api_client-0.2.0}/.pre-commit-config.yaml +0 -0
  21. {cloudnet_api_client-0.1.2 → cloudnet_api_client-0.2.0}/LICENSE +0 -0
@@ -5,6 +5,20 @@ All notable changes to this project will be documented in this file.
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
+ ## 0.2.0 – 2025-04-01
9
+
10
+ - Add download progress bar
11
+ - Add `adownload` function for asynchronous context
12
+ - Only retry on aiohttp errors
13
+ - Extend date parameters
14
+ - Improve type hints
15
+
16
+ ## 0.1.3 – 2025-03-31
17
+
18
+ - Add py.typed
19
+ - Add optimum model to metadata response
20
+ - Add model_id parameter
21
+
8
22
  ## 0.1.2 – 2025-03-27
9
23
 
10
24
  - Add method to fetch instruments
@@ -0,0 +1,160 @@
1
+ Metadata-Version: 2.4
2
+ Name: cloudnet-api-client
3
+ Version: 0.2.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
+ Requires-Dist: tqdm
18
+ Provides-Extra: dev
19
+ Requires-Dist: pre-commit; extra == 'dev'
20
+ Requires-Dist: release-version; extra == 'dev'
21
+ Requires-Dist: types-requests; extra == 'dev'
22
+ Requires-Dist: types-tqdm; extra == 'dev'
23
+ Provides-Extra: test
24
+ Requires-Dist: mypy; extra == 'test'
25
+ Requires-Dist: pytest; extra == 'test'
26
+ Description-Content-Type: text/markdown
27
+
28
+ [![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)
29
+
30
+ # cloudnet-api-client
31
+
32
+ Official Python client for the [Cloudnet data portal API](https://docs.cloudnet.fmi.fi/api/data-portal.html).
33
+
34
+ ## Installation
35
+
36
+ ```bash
37
+ python3 -m pip install cloudnet-api-client
38
+ ```
39
+
40
+ ## Quickstart
41
+
42
+ ```python
43
+ import cloudnet_api_client as cac
44
+
45
+ client = cac.APIClient()
46
+
47
+ sites = client.sites(type="cloudnet")
48
+ products = client.products()
49
+
50
+ metadata = client.metadata("hyytiala", "2021-01-01", product=["mwr", "radar"])
51
+ cac.download(metadata, "data/")
52
+
53
+ raw_metadata = client.raw_metadata("granada", date="2024-01", instrument_id="parsivel")
54
+ cac.download(raw_metadata, "data_raw/")
55
+ ```
56
+
57
+ ## Documentation
58
+
59
+ ### `APIClient().metadata()` and `raw_metadata()` &rarr; `list[Metadata]`
60
+
61
+ Fetch product and raw file metadata from the Cloudnet data portal.
62
+
63
+ Parameters:
64
+
65
+ | name | type | default | example |
66
+ | --------------- | --------------------------- | ------- | ---------------------------------------------------- |
67
+ | site_id | `str` | | "hyytiala" |
68
+ | date | `str` or `date` | `None` | "2024-01-01" |
69
+ | date_from | `str` or `date` | `None` | "2025-01-01" |
70
+ | date_to | `str` or `date` | `None` | "2025-01-01" |
71
+ | updated_at | `str`, `date` or `datetime` | `None` | "2025-01-01T12:00:00" |
72
+ | updated_at_from | `str`, `date` or `datetime` | `None` | "2025-01-01T12:00:00" |
73
+ | updated_at_to | `str`, `date` or `datetime` | `None` | "2025-01-01T12:00:00" |
74
+ | instrument_id | `str` or `list[str]` | `None` | "rpg-fmcw-94" |
75
+ | instrument_pid | `str` or `list[str]` | `None` | "https://hdl.handle.net/21.12132/3.191564170f8a4686" |
76
+ | product\* | `str` or `list[str]` | `None` | "classification" |
77
+ | show_legacy\* | `bool` | `False` | |
78
+
79
+ \* = only in `metadata()`
80
+
81
+ **Date Handling**
82
+
83
+ The `date`, `date_from` and `date_to` parameters support:
84
+
85
+ - "YYYY-MM-DD" — a specific date
86
+ - "YYYY-MM" — the entire month
87
+ - "YYYY" — the entire year
88
+ - Or directly as `datetime.date` object
89
+
90
+ In addition to these, the `updated_at`, `updated_at_from` and `updated_at_to` parameters support:
91
+
92
+ - "YYYY-MM-DDTHH" — a specific hour
93
+ - "YYYY-MM-DDTHH:MM" — a specific minute
94
+ - "YYYY-MM-DDTHH:MM:SS" — a specific second
95
+ - "YYYY-MM-DDTHH:MM:SS.FFFFFF" — a specific microsecond
96
+ - Or directly as `datetime.datetime` object
97
+
98
+ **Return value**
99
+
100
+ Both methods return a list of `dataclass` instances, `ProductMetadata` and `RawMetadata`, respectively.
101
+
102
+ ### `APIClient().filter(list[Metadata])` &rarr; `list[Metadata]`
103
+
104
+ Additional filtering of fetched metadata.
105
+
106
+ Parameters:
107
+
108
+ | name | type | default |
109
+ | ------------------ | ---------------------------------------------- | ------- |
110
+ | metadata | `list[RawMetadata]` or `list[ProductMetadata]` | |
111
+ | include_pattern | `str` | `None` |
112
+ | exclude_pattern | `str` | `None` |
113
+ | filename_prefix | `str` | `None` |
114
+ | filename_suffix | `str` | `None` |
115
+ | include_tag_subset | `set[str]` | `None` |
116
+ | exclude_tag_subset | `set[str]` | `None` |
117
+
118
+ ### `APIClient().sites()` &rarr; `list[Site]`
119
+
120
+ Fetch cloudnet sites.
121
+
122
+ Parameters:
123
+
124
+ | name | type | Choices | default |
125
+ | ---- | -------------------- | ----------------------------------------- | ------- |
126
+ | type | `str` or `list[str]` | "cloudnet", "campaign", "model", "hidden" | `None` |
127
+
128
+ ### `APIClient().products()` &rarr; `list[Product]`
129
+
130
+ Fetch cloudnet products.
131
+
132
+ Parameters:
133
+
134
+ | name | type | Choices | default |
135
+ | ---- | -------------------- | ----------------------------------------- | ------- |
136
+ | type | `str` or `list[str]` | "instrument", "geophysical", "evaluation" | `None` |
137
+
138
+ ### `APIClient().instruments()` &rarr; `list[Instrument]`
139
+
140
+ Fetch cloudnet instruments.
141
+
142
+ ### `cloudnet_api_client.download(list[Metadata])`
143
+
144
+ Download files from the fetched metadata.
145
+
146
+ Parameters:
147
+
148
+ | name | type | default |
149
+ | ----------------- | ---------------------------------------------- | ------- |
150
+ | metadata | `list[RawMetadata]` or `list[ProductMetadata]` | |
151
+ | output_directory | `PathLike` or `str` | |
152
+ | concurrency_limit | `int` | 5 |
153
+ | progress | `bool` or `None` | `None` |
154
+
155
+ There's also an asynchronous version of this function:
156
+ `cloudnet_api_client.adownload`. It's useful for usage inside Jupyter notebook.
157
+
158
+ ## License
159
+
160
+ MIT
@@ -0,0 +1,133 @@
1
+ [![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)
2
+
3
+ # cloudnet-api-client
4
+
5
+ Official Python client for the [Cloudnet data portal API](https://docs.cloudnet.fmi.fi/api/data-portal.html).
6
+
7
+ ## Installation
8
+
9
+ ```bash
10
+ python3 -m pip install cloudnet-api-client
11
+ ```
12
+
13
+ ## Quickstart
14
+
15
+ ```python
16
+ import cloudnet_api_client as cac
17
+
18
+ client = cac.APIClient()
19
+
20
+ sites = client.sites(type="cloudnet")
21
+ products = client.products()
22
+
23
+ metadata = client.metadata("hyytiala", "2021-01-01", product=["mwr", "radar"])
24
+ cac.download(metadata, "data/")
25
+
26
+ raw_metadata = client.raw_metadata("granada", date="2024-01", instrument_id="parsivel")
27
+ cac.download(raw_metadata, "data_raw/")
28
+ ```
29
+
30
+ ## Documentation
31
+
32
+ ### `APIClient().metadata()` and `raw_metadata()` &rarr; `list[Metadata]`
33
+
34
+ Fetch product and raw file metadata from the Cloudnet data portal.
35
+
36
+ Parameters:
37
+
38
+ | name | type | default | example |
39
+ | --------------- | --------------------------- | ------- | ---------------------------------------------------- |
40
+ | site_id | `str` | | "hyytiala" |
41
+ | date | `str` or `date` | `None` | "2024-01-01" |
42
+ | date_from | `str` or `date` | `None` | "2025-01-01" |
43
+ | date_to | `str` or `date` | `None` | "2025-01-01" |
44
+ | updated_at | `str`, `date` or `datetime` | `None` | "2025-01-01T12:00:00" |
45
+ | updated_at_from | `str`, `date` or `datetime` | `None` | "2025-01-01T12:00:00" |
46
+ | updated_at_to | `str`, `date` or `datetime` | `None` | "2025-01-01T12:00:00" |
47
+ | instrument_id | `str` or `list[str]` | `None` | "rpg-fmcw-94" |
48
+ | instrument_pid | `str` or `list[str]` | `None` | "https://hdl.handle.net/21.12132/3.191564170f8a4686" |
49
+ | product\* | `str` or `list[str]` | `None` | "classification" |
50
+ | show_legacy\* | `bool` | `False` | |
51
+
52
+ \* = only in `metadata()`
53
+
54
+ **Date Handling**
55
+
56
+ The `date`, `date_from` and `date_to` parameters support:
57
+
58
+ - "YYYY-MM-DD" — a specific date
59
+ - "YYYY-MM" — the entire month
60
+ - "YYYY" — the entire year
61
+ - Or directly as `datetime.date` object
62
+
63
+ In addition to these, the `updated_at`, `updated_at_from` and `updated_at_to` parameters support:
64
+
65
+ - "YYYY-MM-DDTHH" — a specific hour
66
+ - "YYYY-MM-DDTHH:MM" — a specific minute
67
+ - "YYYY-MM-DDTHH:MM:SS" — a specific second
68
+ - "YYYY-MM-DDTHH:MM:SS.FFFFFF" — a specific microsecond
69
+ - Or directly as `datetime.datetime` object
70
+
71
+ **Return value**
72
+
73
+ Both methods return a list of `dataclass` instances, `ProductMetadata` and `RawMetadata`, respectively.
74
+
75
+ ### `APIClient().filter(list[Metadata])` &rarr; `list[Metadata]`
76
+
77
+ Additional filtering of fetched metadata.
78
+
79
+ Parameters:
80
+
81
+ | name | type | default |
82
+ | ------------------ | ---------------------------------------------- | ------- |
83
+ | metadata | `list[RawMetadata]` or `list[ProductMetadata]` | |
84
+ | include_pattern | `str` | `None` |
85
+ | exclude_pattern | `str` | `None` |
86
+ | filename_prefix | `str` | `None` |
87
+ | filename_suffix | `str` | `None` |
88
+ | include_tag_subset | `set[str]` | `None` |
89
+ | exclude_tag_subset | `set[str]` | `None` |
90
+
91
+ ### `APIClient().sites()` &rarr; `list[Site]`
92
+
93
+ Fetch cloudnet sites.
94
+
95
+ Parameters:
96
+
97
+ | name | type | Choices | default |
98
+ | ---- | -------------------- | ----------------------------------------- | ------- |
99
+ | type | `str` or `list[str]` | "cloudnet", "campaign", "model", "hidden" | `None` |
100
+
101
+ ### `APIClient().products()` &rarr; `list[Product]`
102
+
103
+ Fetch cloudnet products.
104
+
105
+ Parameters:
106
+
107
+ | name | type | Choices | default |
108
+ | ---- | -------------------- | ----------------------------------------- | ------- |
109
+ | type | `str` or `list[str]` | "instrument", "geophysical", "evaluation" | `None` |
110
+
111
+ ### `APIClient().instruments()` &rarr; `list[Instrument]`
112
+
113
+ Fetch cloudnet instruments.
114
+
115
+ ### `cloudnet_api_client.download(list[Metadata])`
116
+
117
+ Download files from the fetched metadata.
118
+
119
+ Parameters:
120
+
121
+ | name | type | default |
122
+ | ----------------- | ---------------------------------------------- | ------- |
123
+ | metadata | `list[RawMetadata]` or `list[ProductMetadata]` | |
124
+ | output_directory | `PathLike` or `str` | |
125
+ | concurrency_limit | `int` | 5 |
126
+ | progress | `bool` or `None` | `None` |
127
+
128
+ There's also an asynchronous version of this function:
129
+ `cloudnet_api_client.adownload`. It's useful for usage inside Jupyter notebook.
130
+
131
+ ## License
132
+
133
+ MIT
@@ -1,2 +1,3 @@
1
1
  from .client import APIClient as APIClient
2
+ from .dl import adownload as adownload
2
3
  from .dl import download as download
@@ -0,0 +1,338 @@
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
+ DateTimeParam = str | datetime.datetime | datetime.date | None
26
+ QueryParam = str | list[str] | None
27
+
28
+
29
+ class APIClient:
30
+ def __init__(
31
+ self,
32
+ base_url: str = "https://cloudnet.fmi.fi/api/",
33
+ session: requests.Session | None = None,
34
+ ) -> None:
35
+ self.base_url = base_url
36
+ self.session = session or _make_session()
37
+
38
+ def sites(self, type: SITE_TYPE | list[SITE_TYPE] | None = None) -> list[Site]:
39
+ params = {"type": type}
40
+ res = self._get_response("sites", params)
41
+ return _build_objects(res, Site)
42
+
43
+ def products(
44
+ self, type: PRODUCT_TYPE | list[PRODUCT_TYPE] | None = None
45
+ ) -> list[Product]:
46
+ res = self._get_response("products")
47
+ data = _build_objects(res, Product)
48
+ if isinstance(type, str):
49
+ data = [obj for obj in data if type in obj.type]
50
+ elif isinstance(type, list):
51
+ data = [obj for obj in data if any(t in obj.type for t in type)]
52
+ return data
53
+
54
+ def instruments(self) -> list[Instrument]:
55
+ res = self._get_response("instrument-pids")
56
+ return [
57
+ Instrument(
58
+ instrument_id=obj["instrument"]["id"],
59
+ model=obj["model"],
60
+ type=obj["type"],
61
+ uuid=obj["uuid"],
62
+ pid=obj["pid"],
63
+ owners=obj["owners"],
64
+ serial_number=obj["serialNumber"],
65
+ name=obj["name"],
66
+ )
67
+ for obj in res
68
+ ]
69
+
70
+ def metadata(
71
+ self,
72
+ site_id: str,
73
+ date: DateParam = None,
74
+ date_from: DateParam = None,
75
+ date_to: DateParam = None,
76
+ updated_at: DateTimeParam = None,
77
+ updated_at_from: DateTimeParam = None,
78
+ updated_at_to: DateTimeParam = None,
79
+ instrument_id: QueryParam = None,
80
+ instrument_pid: QueryParam = None,
81
+ model_id: QueryParam = None,
82
+ product: QueryParam = None,
83
+ show_legacy: bool = False,
84
+ ) -> list[ProductMetadata]:
85
+ params = {
86
+ "site": site_id,
87
+ "instrument": instrument_id,
88
+ "instrumentPid": instrument_pid,
89
+ "product": product,
90
+ "showLegacy": show_legacy,
91
+ }
92
+ _add_date_params(
93
+ params, date, date_from, date_to, updated_at, updated_at_from, updated_at_to
94
+ )
95
+
96
+ files_res = self._get_response("files", params)
97
+
98
+ # Add model files if requested
99
+ if not product or "model" in product:
100
+ for key in ("showLegacy", "product", "instrument", "instrumentPid"):
101
+ del params[key]
102
+ params["model"] = model_id
103
+ files_res += self._get_response("model-files", params)
104
+
105
+ return _build_meta_objects(files_res)
106
+
107
+ def raw_metadata(
108
+ self,
109
+ site_id: str,
110
+ date: DateParam = None,
111
+ date_from: DateParam = None,
112
+ date_to: DateParam = None,
113
+ updated_at: DateTimeParam = None,
114
+ updated_at_from: DateTimeParam = None,
115
+ updated_at_to: DateTimeParam = None,
116
+ instrument_id: QueryParam = None,
117
+ instrument_pid: QueryParam = None,
118
+ ) -> list[RawMetadata]:
119
+ params = {
120
+ "site": site_id,
121
+ "instrument": instrument_id,
122
+ "instrumentPid": instrument_pid,
123
+ }
124
+ _add_date_params(
125
+ params, date, date_from, date_to, updated_at, updated_at_from, updated_at_to
126
+ )
127
+ res = self._get_response("raw-files", params)
128
+ return _build_raw_meta_objects(res)
129
+
130
+ @staticmethod
131
+ def filter(
132
+ metadata: list[Metadata],
133
+ include_pattern: str | None = None,
134
+ exclude_pattern: str | None = None,
135
+ filename_prefix: str | None = None,
136
+ filename_suffix: str | None = None,
137
+ include_tag_subset: set[str] | None = None,
138
+ exclude_tag_subset: set[str] | None = None,
139
+ ) -> list[Metadata]:
140
+ if include_pattern:
141
+ metadata = [
142
+ m for m in metadata if re.search(include_pattern, m.filename, re.I)
143
+ ]
144
+ if exclude_pattern:
145
+ metadata = [
146
+ m for m in metadata if not re.search(exclude_pattern, m.filename, re.I)
147
+ ]
148
+ if filename_prefix:
149
+ metadata = [m for m in metadata if m.filename.startswith(filename_prefix)]
150
+ if filename_suffix:
151
+ metadata = [m for m in metadata if m.filename.endswith(filename_suffix)]
152
+ if include_tag_subset:
153
+ metadata = [
154
+ m
155
+ for m in metadata
156
+ if isinstance(m, RawMetadata)
157
+ and m.tags
158
+ and include_tag_subset.issubset(m.tags)
159
+ ]
160
+ if exclude_tag_subset:
161
+ metadata = [
162
+ m
163
+ for m in metadata
164
+ if isinstance(m, RawMetadata)
165
+ and m.tags
166
+ and not exclude_tag_subset.issubset(m.tags)
167
+ ]
168
+ return metadata
169
+
170
+ def _get_response(self, endpoint: str, params: dict | None = None) -> list[dict]:
171
+ url = urljoin(self.base_url, endpoint)
172
+ res = self.session.get(url, params=params, timeout=120)
173
+ res.raise_for_status()
174
+ return res.json()
175
+
176
+
177
+ def _add_date_params(
178
+ params: dict,
179
+ date: DateParam,
180
+ date_from: DateParam,
181
+ date_to: DateParam,
182
+ updated_at: DateTimeParam,
183
+ updated_at_from: DateTimeParam,
184
+ updated_at_to: DateTimeParam,
185
+ ):
186
+ if date is not None and (date_from is not None or date_to is not None):
187
+ msg = "Cannot use 'date' with 'date_from' and 'date_to'"
188
+ raise ValueError(msg)
189
+ if date is not None:
190
+ start, stop = _parse_date(date)
191
+ params["dateFrom"] = start.isoformat()
192
+ params["dateTo"] = stop.isoformat()
193
+ if date_from is not None:
194
+ params["dateFrom"] = _parse_date(date_from)[0].isoformat()
195
+ if date_to is not None:
196
+ params["dateTo"] = _parse_date(date_to)[1].isoformat()
197
+
198
+ if updated_at is not None and (
199
+ updated_at_from is not None or updated_at_to is not None
200
+ ):
201
+ msg = "Cannot use 'updated_at' with 'updated_at_from' and 'updated_at_to'"
202
+ raise ValueError(msg)
203
+ if updated_at is not None:
204
+ start, stop = _parse_datetime(updated_at)
205
+ params["updatedAtFrom"] = start.isoformat()
206
+ params["updatedAtTo"] = stop.isoformat()
207
+ if updated_at_from is not None:
208
+ params["updatedAtFrom"] = _parse_datetime(updated_at_from)[0].isoformat()
209
+ if updated_at_to is not None:
210
+ params["updatedAtTo"] = _parse_datetime(updated_at_to)[1].isoformat()
211
+
212
+
213
+ def _parse_date(date: DateParam) -> tuple[datetime.date, datetime.date]:
214
+ if isinstance(date, datetime.date):
215
+ return date, date
216
+ error = ValueError(f"Invalid date format: {date}")
217
+ if isinstance(date, str):
218
+ try:
219
+ parts = [int(part) for part in date.split("-")]
220
+ except ValueError:
221
+ raise error from None
222
+ match parts:
223
+ case [year, month, day]:
224
+ date = datetime.date(year, month, day)
225
+ return date, date
226
+ case [year, month]:
227
+ last_day_number = calendar.monthrange(year, month)[1]
228
+ return datetime.date(year, month, 1), datetime.date(
229
+ year, month, last_day_number
230
+ )
231
+ case [year]:
232
+ return datetime.date(year, 1, 1), datetime.date(year, 12, 31)
233
+ raise error
234
+
235
+
236
+ def _parse_datetime(dt: DateTimeParam) -> tuple[datetime.datetime, datetime.datetime]:
237
+ if isinstance(dt, datetime.datetime):
238
+ return dt, dt
239
+ if isinstance(dt, datetime.date):
240
+ return datetime.datetime.combine(
241
+ dt, datetime.time(0, 0, 0, 0)
242
+ ), datetime.datetime.combine(dt, datetime.time(23, 59, 59, 999999))
243
+ if isinstance(dt, str):
244
+ patterns = {
245
+ ("%Y", "years"),
246
+ ("%Y-%m", "months"),
247
+ ("%Y-%m-%d", "days"),
248
+ ("%Y-%m-%dT%H", "hours"),
249
+ ("%Y-%m-%dT%H:%M", "minutes"),
250
+ ("%Y-%m-%dT%H:%M:%S", "seconds"),
251
+ ("%Y-%m-%dT%H:%M:%S.%f", "microseconds"),
252
+ }
253
+ for fmt, unit in patterns:
254
+ try:
255
+ start_date = datetime.datetime.strptime(dt, fmt)
256
+ except ValueError:
257
+ continue
258
+ if unit == "years":
259
+ end_date = start_date.replace(year=start_date.year + 1)
260
+ elif unit == "months":
261
+ if start_date.month == 12:
262
+ end_date = start_date.replace(year=start_date.year + 1, month=1)
263
+ else:
264
+ end_date = start_date.replace(month=start_date.month + 1)
265
+ elif unit == "days":
266
+ end_date = start_date + datetime.timedelta(days=1)
267
+ elif unit == "hours":
268
+ end_date = start_date + datetime.timedelta(hours=1)
269
+ elif unit == "minutes":
270
+ end_date = start_date + datetime.timedelta(minutes=1)
271
+ elif unit == "seconds":
272
+ end_date = start_date + datetime.timedelta(seconds=1)
273
+ elif unit == "microseconds":
274
+ return start_date, start_date
275
+ return start_date, end_date - datetime.timedelta(microseconds=1)
276
+ msg = f"Invalid datetime format: {dt}"
277
+ raise ValueError(msg)
278
+
279
+
280
+ def _build_objects(res: list[dict], object_type: type[T]) -> list[T]:
281
+ assert is_dataclass(object_type)
282
+ field_names = {f.name for f in fields(object_type)}
283
+ objects = [
284
+ object_type(
285
+ **{_to_snake(k): v for k, v in obj.items() if _to_snake(k) in field_names}
286
+ )
287
+ for obj in res
288
+ ]
289
+ return cast(list[T], objects)
290
+
291
+
292
+ def _build_meta_objects(res: list[dict]) -> list[ProductMetadata]:
293
+ field_names = {f.name for f in fields(ProductMetadata)} - {"product"}
294
+ return [
295
+ ProductMetadata(
296
+ **{_to_snake(k): v for k, v in obj.items() if _to_snake(k) in field_names},
297
+ product=Product(
298
+ id=obj["product"]["id"],
299
+ human_readable_name=obj["product"]["humanReadableName"],
300
+ type=[obj["product"]["type"][1:-1]],
301
+ experimental=obj["product"]["experimental"],
302
+ ),
303
+ )
304
+ for obj in res
305
+ ]
306
+
307
+
308
+ def _build_raw_meta_objects(res: list[dict]) -> list[RawMetadata]:
309
+ field_names = {f.name for f in fields(RawMetadata)} - {"instrument"}
310
+ return [
311
+ RawMetadata(
312
+ **{_to_snake(k): v for k, v in obj.items() if _to_snake(k) in field_names},
313
+ instrument=Instrument(
314
+ instrument_id=obj["instrumentInfo"]["instrumentId"],
315
+ model=obj["instrumentInfo"]["model"],
316
+ type=obj["instrumentInfo"]["type"],
317
+ uuid=obj["instrumentInfo"]["uuid"],
318
+ pid=obj["instrumentInfo"]["pid"],
319
+ owners=obj["instrumentInfo"]["owners"],
320
+ serial_number=obj["instrumentInfo"]["serialNumber"],
321
+ name=obj["instrumentInfo"]["name"],
322
+ ),
323
+ )
324
+ for obj in res
325
+ ]
326
+
327
+
328
+ def _to_snake(name: str) -> str:
329
+ return re.sub(r"(?<!^)(?=[A-Z])", "_", name).lower()
330
+
331
+
332
+ def _make_session() -> requests.Session:
333
+ session = requests.Session()
334
+ retry_strategy = Retry(total=10, backoff_factor=0.1, status_forcelist=[524])
335
+ adapter = HTTPAdapter(max_retries=retry_strategy)
336
+ session.mount("https://", adapter)
337
+ session.mount("http://", adapter)
338
+ return session
@@ -3,7 +3,7 @@ from dataclasses import dataclass
3
3
  from typing import Literal
4
4
 
5
5
  SITE_TYPE = Literal["cloudnet", "model", "hidden", "campaign"]
6
- PRODUCT_TYPE = Literal["instrument", "geophysical", "evaluation"]
6
+ PRODUCT_TYPE = Literal["instrument", "geophysical", "evaluation", "model"]
7
7
 
8
8
 
9
9
  @dataclass(frozen=True, slots=True)
@@ -19,7 +19,7 @@ class Site:
19
19
  country: str
20
20
  country_code: str
21
21
  country_subdivision_code: str | None
22
- type: SITE_TYPE
22
+ type: list[SITE_TYPE]
23
23
  status: Literal["active", "inactive"]
24
24
  gaw: str | None
25
25
 
@@ -28,7 +28,7 @@ class Site:
28
28
  class Product:
29
29
  id: str
30
30
  human_readable_name: str
31
- type: PRODUCT_TYPE
31
+ type: list[PRODUCT_TYPE]
32
32
  experimental: bool
33
33
 
34
34