currentlab 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.
currentlab/__init__.py ADDED
@@ -0,0 +1,21 @@
1
+ """currentlab — Python library for the Current Lab API."""
2
+
3
+ from ._client import RunDate, load_dataset
4
+ from ._exceptions import (
5
+ CurrentLabAPIError,
6
+ CurrentLabAuthError,
7
+ CurrentLabDownloadError,
8
+ CurrentLabError,
9
+ )
10
+
11
+ __version__ = "0.1.0"
12
+
13
+ __all__ = [
14
+ "load_dataset",
15
+ "RunDate",
16
+ "CurrentLabError",
17
+ "CurrentLabAPIError",
18
+ "CurrentLabAuthError",
19
+ "CurrentLabDownloadError",
20
+ "__version__",
21
+ ]
currentlab/_api.py ADDED
@@ -0,0 +1,115 @@
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ from typing import Any
5
+
6
+ import requests
7
+
8
+ from ._exceptions import CurrentLabAPIError, CurrentLabAuthError
9
+
10
+ API_KEY_ENV_VAR = "CURRENT_LAB_API_KEY"
11
+ DEFAULT_BASE_URL = "https://api.current-lab.com"
12
+
13
+
14
+ def _resolve_api_key(api_key: str | None) -> str:
15
+ if api_key:
16
+ return api_key
17
+ key = os.environ.get(API_KEY_ENV_VAR)
18
+ if not key:
19
+ raise CurrentLabAuthError(
20
+ f"No API key found. Set the {API_KEY_ENV_VAR} environment variable "
21
+ "or pass api_key= to load_dataset()."
22
+ )
23
+ return key
24
+
25
+
26
+ def _format_validation_error(response: requests.Response) -> str | None:
27
+ """Extract a concise validation message from a 422 API response."""
28
+ try:
29
+ payload = response.json()
30
+ except ValueError:
31
+ return None
32
+
33
+ detail = payload.get("detail")
34
+ if not isinstance(detail, list):
35
+ return None
36
+
37
+ messages: list[str] = []
38
+ for item in detail:
39
+ if not isinstance(item, dict):
40
+ continue
41
+ loc = item.get("loc")
42
+ msg = item.get("msg")
43
+ input_value = item.get("input")
44
+
45
+ field = loc[-1] if isinstance(loc, list) and loc else None
46
+ if isinstance(field, str) and isinstance(msg, str):
47
+ line = f"{field}: {msg}"
48
+ if input_value is not None:
49
+ line += f" (received: {input_value!r})"
50
+ messages.append(line)
51
+
52
+ if not messages:
53
+ return None
54
+
55
+ return "API validation failed: " + "; ".join(messages)
56
+
57
+
58
+ def request_gridded_file(
59
+ region: str,
60
+ dataset_type: str,
61
+ dataset_source: str,
62
+ file_format: str,
63
+ run_date: str,
64
+ api_key: str | None = None,
65
+ base_url: str = DEFAULT_BASE_URL,
66
+ ) -> dict[str, Any]:
67
+ """POST to the gridded_files endpoint and return the first file entry."""
68
+ key = _resolve_api_key(api_key)
69
+
70
+ try:
71
+ response = requests.post(
72
+ url=f"{base_url}/v0/gridded_files",
73
+ json={
74
+ "region": region,
75
+ "dataset_type": dataset_type,
76
+ "dataset_source": dataset_source,
77
+ "file_format": file_format,
78
+ "run_date": run_date,
79
+ },
80
+ headers={"X-API-Key": key},
81
+ timeout=30,
82
+ )
83
+ except requests.ConnectionError as exc:
84
+ raise CurrentLabAPIError(
85
+ f"Could not reach the Current Lab API at {base_url}. "
86
+ "Check your network connection."
87
+ ) from exc
88
+ except requests.Timeout as exc:
89
+ raise CurrentLabAPIError("Request to the Current Lab API timed out.") from exc
90
+
91
+ if response.status_code in (401, 403):
92
+ raise CurrentLabAuthError(
93
+ f"Authentication failed (HTTP {response.status_code}). "
94
+ "Verify your API key is correct and has access to this resource."
95
+ )
96
+
97
+ try:
98
+ response.raise_for_status()
99
+ except requests.HTTPError as exc:
100
+ if response.status_code == 422:
101
+ validation_message = _format_validation_error(response)
102
+ if validation_message:
103
+ raise CurrentLabAPIError(validation_message) from exc
104
+ raise CurrentLabAPIError(
105
+ f"API request failed with HTTP {response.status_code}: {response.text}"
106
+ ) from exc
107
+
108
+ data = response.json().get("data", [])
109
+ if not data:
110
+ raise CurrentLabAPIError(
111
+ "The API returned no files for the given parameters. "
112
+ "Check that region, dataset_type, and run_date are valid."
113
+ )
114
+
115
+ return data[0]
currentlab/_client.py ADDED
@@ -0,0 +1,121 @@
1
+ from __future__ import annotations
2
+
3
+ from datetime import date, datetime
4
+ from pathlib import Path
5
+ from typing import Optional, Union
6
+
7
+ import xarray as xr
8
+
9
+ from ._api import DEFAULT_BASE_URL, request_gridded_file
10
+ from ._download import download_to_path, temp_download
11
+
12
+ RunDate = Union[str, date, datetime]
13
+
14
+
15
+ def _coerce_run_date(run_date: RunDate) -> str:
16
+ """Normalise run_date to the YYYY-MM-DD string the API expects.
17
+
18
+ ``datetime`` is intentionally handled before ``date`` because
19
+ ``datetime`` is a subclass of ``date``.
20
+ """
21
+ if isinstance(run_date, datetime):
22
+ return run_date.strftime("%Y-%m-%d")
23
+ if isinstance(run_date, date):
24
+ return run_date.strftime("%Y-%m-%d")
25
+ return run_date # already a string (e.g. "latest" or "YYYY-MM-DD")
26
+
27
+
28
+ def load_dataset(
29
+ region: str,
30
+ dataset_type: str,
31
+ dataset_source: str = "auto",
32
+ file_format: str = "netcdf",
33
+ run_date: RunDate = "latest",
34
+ *,
35
+ save_dir: Optional[Union[str, Path]] = None,
36
+ save_path: Optional[Union[str, Path]] = None,
37
+ api_key: Optional[str] = None,
38
+ base_url: str = DEFAULT_BASE_URL,
39
+ ) -> xr.Dataset:
40
+ """Load a Current Lab gridded forecast dataset as an xarray Dataset.
41
+
42
+ Parameters
43
+ ----------
44
+ region : str
45
+ Region identifier, e.g. ``"oahu"``.
46
+ dataset_type : str
47
+ Dataset type, e.g. ``"currents_surface"``, ``"waves"``, ``"wind"``.
48
+ dataset_source : str, optional
49
+ Model or data source. Defaults to ``"auto"`` (server-selected best source).
50
+ file_format : str, optional
51
+ File format to request. Defaults to ``"netcdf"``.
52
+ run_date : str, date, or datetime, optional
53
+ Forecast run date. Accepts a ``datetime.date``, ``datetime.datetime``
54
+ (time component is ignored), or a ``"YYYY-MM-DD"`` string. Pass
55
+ ``"latest"`` to request the most recent available run. Defaults to
56
+ ``"latest"``.
57
+ save_dir : str or Path, optional
58
+ Directory in which to save the downloaded file. The filename is taken from
59
+ the API response. If the file already exists it is loaded without
60
+ re-downloading. Mutually exclusive with *save_path*.
61
+ save_path : str or Path, optional
62
+ Exact file path to save the download to. If the file already exists it is
63
+ loaded without re-downloading. Takes precedence over *save_dir* if both are
64
+ somehow provided (raises ``ValueError`` instead — pass one or the other).
65
+ api_key : str, optional
66
+ Current Lab API key. Defaults to the ``CURRENT_LAB_API_KEY`` environment
67
+ variable.
68
+ base_url : str, optional
69
+ API base URL. Defaults to ``"https://api.current-lab.com"``.
70
+
71
+ Returns
72
+ -------
73
+ xr.Dataset
74
+ The requested forecast dataset.
75
+
76
+ Examples
77
+ --------
78
+ Stream directly into memory (no file saved):
79
+
80
+ >>> ds = currentlab.load_dataset(region="oahu", dataset_type="currents_surface")
81
+
82
+ Save to a directory and reuse on subsequent calls:
83
+
84
+ >>> ds = currentlab.load_dataset(
85
+ ... region="oahu",
86
+ ... dataset_type="waves",
87
+ ... save_dir="./data",
88
+ ... )
89
+ """
90
+ if save_dir is not None and save_path is not None:
91
+ raise ValueError("Provide either save_dir or save_path, not both.")
92
+
93
+ file_info = request_gridded_file(
94
+ region=region,
95
+ dataset_type=dataset_type,
96
+ dataset_source=dataset_source,
97
+ file_format=file_format,
98
+ run_date=_coerce_run_date(run_date),
99
+ api_key=api_key,
100
+ base_url=base_url,
101
+ )
102
+
103
+ download_url: str = file_info["download_url"]
104
+ remote_filename: str = file_info["file_name"]
105
+
106
+ if save_path is not None:
107
+ dest = Path(save_path)
108
+ if not dest.exists():
109
+ download_to_path(download_url, dest)
110
+ return xr.open_dataset(dest, engine="netcdf4")
111
+
112
+ if save_dir is not None:
113
+ dest = Path(save_dir) / remote_filename
114
+ if not dest.exists():
115
+ download_to_path(download_url, dest)
116
+ return xr.open_dataset(dest, engine="netcdf4")
117
+
118
+ # No save location — stream to a temp file, load fully into memory, then clean up.
119
+ with temp_download(download_url) as tmp_path:
120
+ with xr.open_dataset(tmp_path, engine="netcdf4") as ds:
121
+ return ds.load()
@@ -0,0 +1,46 @@
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ import tempfile
5
+ from contextlib import contextmanager
6
+ from pathlib import Path
7
+ from typing import Generator
8
+
9
+ import requests
10
+
11
+ from ._exceptions import CurrentLabDownloadError
12
+
13
+ _CHUNK_SIZE = 65_536 # 64 KB
14
+
15
+
16
+ def _stream_to_file(url: str, dest: Path) -> None:
17
+ """Download a URL to a file path using streaming to handle large files."""
18
+ try:
19
+ with requests.get(url, stream=True, timeout=300) as r:
20
+ r.raise_for_status()
21
+ with open(dest, "wb") as f:
22
+ for chunk in r.iter_content(chunk_size=_CHUNK_SIZE):
23
+ f.write(chunk)
24
+ except requests.RequestException as exc:
25
+ raise CurrentLabDownloadError(f"Download failed: {exc}") from exc
26
+
27
+
28
+ def download_to_path(url: str, dest: Path) -> Path:
29
+ """Download a file to a specific path, creating parent directories as needed."""
30
+ dest.parent.mkdir(parents=True, exist_ok=True)
31
+ _stream_to_file(url, dest)
32
+ return dest
33
+
34
+
35
+ @contextmanager
36
+ def temp_download(url: str) -> Generator[Path, None, None]:
37
+ """Download a file to a temporary location, yielding the path, then clean up."""
38
+ tmp = tempfile.NamedTemporaryFile(suffix=".nc", delete=False)
39
+ tmp_path = Path(tmp.name)
40
+ tmp.close()
41
+ try:
42
+ _stream_to_file(url, tmp_path)
43
+ yield tmp_path
44
+ finally:
45
+ if tmp_path.exists():
46
+ os.unlink(tmp_path)
@@ -0,0 +1,14 @@
1
+ class CurrentLabError(Exception):
2
+ """Base exception for the Current Lab Python library."""
3
+
4
+
5
+ class CurrentLabAuthError(CurrentLabError):
6
+ """Raised when API key is missing or authentication fails."""
7
+
8
+
9
+ class CurrentLabAPIError(CurrentLabError):
10
+ """Raised when the API returns an unexpected or error response."""
11
+
12
+
13
+ class CurrentLabDownloadError(CurrentLabError):
14
+ """Raised when a file download fails."""
currentlab/py.typed ADDED
File without changes
@@ -0,0 +1,188 @@
1
+ Metadata-Version: 2.4
2
+ Name: currentlab
3
+ Version: 0.1.0
4
+ Summary: Python library for the Current Lab API
5
+ Project-URL: Homepage, https://current-lab.com
6
+ Project-URL: Documentation, https://github.com/current-lab/currentlab-python#readme
7
+ Project-URL: Repository, https://github.com/current-lab/currentlab-python
8
+ Project-URL: Bug Tracker, https://github.com/current-lab/currentlab-python/issues
9
+ Author-email: Current Lab <info@current-lab.com>
10
+ License: LICENSE
11
+ License-File: LICENSE
12
+ Keywords: currents,forecast,netcdf,ocean,waves,wind,xarray
13
+ Classifier: Development Status :: 3 - Alpha
14
+ Classifier: Intended Audience :: Science/Research
15
+ Classifier: License :: OSI Approved :: MIT License
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.9
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Topic :: Scientific/Engineering :: Atmospheric Science
22
+ Classifier: Topic :: Scientific/Engineering :: Oceanography
23
+ Requires-Python: >=3.9
24
+ Requires-Dist: netcdf4>=1.6
25
+ Requires-Dist: requests>=2.28
26
+ Requires-Dist: xarray>=2023.1
27
+ Provides-Extra: dev
28
+ Requires-Dist: pytest-cov>=4.0; extra == 'dev'
29
+ Requires-Dist: pytest>=7.0; extra == 'dev'
30
+ Requires-Dist: python-dotenv>=1.0; extra == 'dev'
31
+ Description-Content-Type: text/markdown
32
+
33
+ # currentlab-python
34
+
35
+ The Current Lab Python library provides convenient access to the [Current Lab](https://current-lab.com) API from Python applications. Load gridded forecast files as [xarray](https://docs.xarray.dev) datasets with a single function call.
36
+
37
+ ## Installation
38
+
39
+ ```bash
40
+ pip install currentlab
41
+ ```
42
+
43
+ ## Authentication
44
+
45
+ Set your API key as an environment variable:
46
+
47
+ ```bash
48
+ export CURRENT_LAB_API_KEY="your-api-key"
49
+ ```
50
+
51
+ Or use a `.env` file (see `.env.example`) and load it with [python-dotenv](https://pypi.org/project/python-dotenv/).
52
+
53
+ You can also pass the key directly to any function call via the `api_key=` argument.
54
+
55
+ ## Quick start
56
+
57
+ ```python
58
+ import currentlab
59
+
60
+ ds = currentlab.load_dataset(
61
+ region="oahu",
62
+ dataset_type="currents_surface",
63
+ )
64
+ print(ds)
65
+ ```
66
+
67
+ ## API Reference
68
+
69
+ ### `load_dataset(...)`
70
+
71
+ ```python
72
+ currentlab.load_dataset(
73
+ region,
74
+ dataset_type,
75
+ dataset_source="auto",
76
+ file_format="netcdf",
77
+ run_date="latest",
78
+ *,
79
+ save_dir=None,
80
+ save_path=None,
81
+ api_key=None,
82
+ base_url="https://api.current-lab.com",
83
+ )
84
+ ```
85
+
86
+ | Parameter | Type | Description |
87
+ |---|---|---|
88
+ | `region` | `str` | Region identifier, e.g. `"oahu"` |
89
+ | `dataset_type` | `str` | Dataset type, e.g. `"currents_surface"`, `"wave"`, `"wind_10m"`, `"ocean_3d"` |
90
+ | `dataset_source` | `str` | Model/source selection. Default `"auto"` lets the server pick the best available source |
91
+ | `file_format` | `str` | File format to request. Default `"netcdf"` |
92
+ | `run_date` | `str` | Forecast run date as `"YYYY-MM-DD"`, or `"latest"`. Default `"latest"` |
93
+ | `save_dir` | `str \| Path` | Directory to save the downloaded file. Filename is derived from the API response. File is reused on subsequent calls if it already exists |
94
+ | `save_path` | `str \| Path` | Exact path to save the file to. Reused on subsequent calls if it already exists. Mutually exclusive with `save_dir` |
95
+ | `api_key` | `str` | API key override. Falls back to `CURRENT_LAB_API_KEY` env var |
96
+ | `base_url` | `str` | API base URL override (useful for testing) |
97
+
98
+ Returns an `xr.Dataset`.
99
+
100
+ ## Usage patterns
101
+
102
+ ### Stream into memory (no file saved)
103
+
104
+ A temporary file is created and streamed into memory. The file is deleted after the dataset is closed.
105
+
106
+ ```python
107
+ ds = currentlab.load_dataset(region="oahu", dataset_type="wave")
108
+ ```
109
+
110
+ ### Save to a directory (cached)
111
+
112
+ File name is derived from the API response.
113
+
114
+ ```python
115
+ ds = currentlab.load_dataset(
116
+ region="oahu",
117
+ dataset_type="wave",
118
+ run_date="2025-03-01",
119
+ save_dir="./data",
120
+ )
121
+ ```
122
+
123
+ ### Save to a specific file path (cached)
124
+
125
+ ```python
126
+ ds = currentlab.load_dataset(
127
+ region="oahu",
128
+ dataset_type="currents_surface",
129
+ save_path="./data/oahu_currents_latest.nc",
130
+ )
131
+ ```
132
+
133
+ ### Request a specific run date
134
+
135
+ ```python
136
+ ds = currentlab.load_dataset(
137
+ region="oahu",
138
+ dataset_type="wind_10m",
139
+ run_date="2026-03-09",
140
+ )
141
+ ```
142
+
143
+ ### Working with the dataset
144
+
145
+ The returned object is a standard xarray Dataset, so the full xarray API is available:
146
+
147
+ ```python
148
+ import numpy as np
149
+ import currentlab
150
+
151
+ ds = currentlab.load_dataset(region="oahu", dataset_type="currents_surface")
152
+
153
+ # Compute current speed from u/v components
154
+ ds["speed"] = np.hypot(ds["u"], ds["v"])
155
+ ds["speed"].attrs["long_name"] = "Current Speed"
156
+ ds["speed"].attrs["units"] = "m/s"
157
+
158
+ print(ds["speed"].max().item())
159
+ ```
160
+
161
+ ## Error handling
162
+
163
+ ```python
164
+ from currentlab import CurrentLabAuthError, CurrentLabAPIError, CurrentLabDownloadError
165
+
166
+ try:
167
+ ds = currentlab.load_dataset(region="oahu", dataset_type="currents_surface")
168
+ except CurrentLabAuthError:
169
+ print("Check your CURRENT_LAB_API_KEY.")
170
+ except CurrentLabAPIError as e:
171
+ print(f"API error: {e}")
172
+ except CurrentLabDownloadError as e:
173
+ print(f"Download failed: {e}")
174
+ ```
175
+
176
+ All exceptions inherit from `currentlab.CurrentLabError`.
177
+
178
+
179
+ ## Development
180
+
181
+ ```bash
182
+ git clone https://github.com/current-lab/currentlab-python
183
+ cd currentlab-python
184
+ python3 -m venv .venv
185
+ source .venv/bin/activate
186
+ pip install -e ".[dev]"
187
+ pytest
188
+ ```
@@ -0,0 +1,10 @@
1
+ currentlab/__init__.py,sha256=KMHo_4yJo8HAws8plFAMPItVbgN0YdPvY5z3Jr6wXJg,432
2
+ currentlab/_api.py,sha256=zKMVHB7pvthavoaxPp4-8rBL28aGw0ZnWtdAPJ89Lec,3535
3
+ currentlab/_client.py,sha256=8lyb5OPPhqBWcm7x76WMBX1xX45WuESXWqBOGVAr5GY,4262
4
+ currentlab/_download.py,sha256=lHi90FblhqkEKfV6tga0RUprzJssaZUSI7x2nvNp7Fo,1410
5
+ currentlab/_exceptions.py,sha256=-cBCUVsRg2m6Y75aRsy8MkK4Ip8oOtyRPSq4wLAd3eQ,418
6
+ currentlab/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
7
+ currentlab-0.1.0.dist-info/METADATA,sha256=5cFrn5nbaqRvGH9to-CpGuPZypRE7cZy0VR7_GDgmRA,5379
8
+ currentlab-0.1.0.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87
9
+ currentlab-0.1.0.dist-info/licenses/LICENSE,sha256=PkazLLsKrLoE-t-Z2hyu6S_sSyRMmDSTYjTzArnJopg,1077
10
+ currentlab-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.29.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,7 @@
1
+ Copyright 2026 Current Lab Technologies, Inc.
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
4
+
5
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
6
+
7
+ THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.