cams-ncp-client 0.0.1__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.
@@ -0,0 +1,19 @@
1
+ MIT License
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy
4
+ of this software and associated documentation files (the "Software"), to deal
5
+ in the Software without restriction, including without limitation the rights
6
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7
+ copies of the Software, and to permit persons to whom the Software is
8
+ furnished to do so, subject to the following conditions:
9
+
10
+ The above copyright notice and this permission notice shall be included in all
11
+ copies or substantial portions of the Software.
12
+
13
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19
+ SOFTWARE.
@@ -0,0 +1,89 @@
1
+ Metadata-Version: 2.1
2
+ Name: cams-ncp-client
3
+ Version: 0.0.1
4
+ Summary: Python Client for the CAMS NCP API.
5
+ Author: Roeland Maes
6
+ Author-email: roeland.maes@vito.be
7
+ Requires-Python: >=3.10,<4.0
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: Programming Language :: Python :: 3.10
10
+ Classifier: Programming Language :: Python :: 3.11
11
+ Classifier: Programming Language :: Python :: 3.12
12
+ Provides-Extra: loguru
13
+ Requires-Dist: SASAIR (>=0.1,<0.2)
14
+ Requires-Dist: loguru (>=0.7,<0.8) ; extra == "loguru"
15
+ Requires-Dist: pandas (>=2.1,<3.0)
16
+ Requires-Dist: pydantic (>=2.0,<3.0)
17
+ Requires-Dist: requests (>=2.31,<3.0)
18
+ Description-Content-Type: text/markdown
19
+
20
+
21
+ # CAMS NCP Client
22
+
23
+ ## Description
24
+
25
+ CAMS NCP Client is a Python client for the CAMS NCP API.
26
+
27
+
28
+ ## Installation with pip
29
+
30
+ To install the package, you can use the following command:
31
+
32
+ ```bash
33
+ pip install cams-ncp-client
34
+ ```
35
+
36
+
37
+ ## Building from Source
38
+
39
+ TODO
40
+
41
+
42
+ ## Configuration
43
+
44
+ TODO
45
+
46
+
47
+ ## Usage
48
+
49
+ Here are some example usages of the package:
50
+ TODO
51
+
52
+
53
+ ## Contributing
54
+
55
+ If you want to contribute to spio, please follow the standard contributing guidelines and push your changes to a new branch in
56
+ https://git.vito.be/projects/MARVIN/repos/cams-ncp-client
57
+
58
+
59
+ ## Testing
60
+
61
+ TODO
62
+
63
+ ## CI/CD
64
+
65
+ TODO
66
+
67
+
68
+ ### Updating the Package Version
69
+
70
+ To update the package version:
71
+
72
+ 1. Tag the code with the new version number in the format `major.minor.fix`.
73
+ 2. Push the tagged code to the appropriate branch.
74
+
75
+ ### Pipeline Automation
76
+
77
+ The CI/CD pipeline is fully automated using Jenkins. Pipeline details are defined in the `Jenkinsfile` located in the repository root.
78
+
79
+ ## Contact
80
+
81
+ For questions or issues, please reach out to the project maintainers:
82
+
83
+ - **Roeland Maes**: [roeland.maes@vito.be](mailto:roeland.maes@vito.be)
84
+
85
+
86
+ ## License
87
+
88
+ This project is licensed under the MIT License. See the `LICENSE.md` file for details.
89
+
@@ -0,0 +1,69 @@
1
+
2
+ # CAMS NCP Client
3
+
4
+ ## Description
5
+
6
+ CAMS NCP Client is a Python client for the CAMS NCP API.
7
+
8
+
9
+ ## Installation with pip
10
+
11
+ To install the package, you can use the following command:
12
+
13
+ ```bash
14
+ pip install cams-ncp-client
15
+ ```
16
+
17
+
18
+ ## Building from Source
19
+
20
+ TODO
21
+
22
+
23
+ ## Configuration
24
+
25
+ TODO
26
+
27
+
28
+ ## Usage
29
+
30
+ Here are some example usages of the package:
31
+ TODO
32
+
33
+
34
+ ## Contributing
35
+
36
+ If you want to contribute to spio, please follow the standard contributing guidelines and push your changes to a new branch in
37
+ https://git.vito.be/projects/MARVIN/repos/cams-ncp-client
38
+
39
+
40
+ ## Testing
41
+
42
+ TODO
43
+
44
+ ## CI/CD
45
+
46
+ TODO
47
+
48
+
49
+ ### Updating the Package Version
50
+
51
+ To update the package version:
52
+
53
+ 1. Tag the code with the new version number in the format `major.minor.fix`.
54
+ 2. Push the tagged code to the appropriate branch.
55
+
56
+ ### Pipeline Automation
57
+
58
+ The CI/CD pipeline is fully automated using Jenkins. Pipeline details are defined in the `Jenkinsfile` located in the repository root.
59
+
60
+ ## Contact
61
+
62
+ For questions or issues, please reach out to the project maintainers:
63
+
64
+ - **Roeland Maes**: [roeland.maes@vito.be](mailto:roeland.maes@vito.be)
65
+
66
+
67
+ ## License
68
+
69
+ This project is licensed under the MIT License. See the `LICENSE.md` file for details.
@@ -0,0 +1,24 @@
1
+
2
+ [tool.poetry]
3
+ name = "cams-ncp-client"
4
+ version = "0.0.1"
5
+ description = "Python Client for the CAMS NCP API."
6
+ authors = ["Roeland Maes <roeland.maes@vito.be>"]
7
+ packages = [
8
+ { include = "cams_ncp_client", from = "src" }
9
+ ]
10
+ readme = "README.md"
11
+
12
+ [tool.poetry.dependencies]
13
+ python = "^3.10"
14
+ requests = "^2.31"
15
+ pydantic = "^2.0"
16
+ pandas = "^2.1"
17
+ SASAIR = "^0.1"
18
+ loguru = { version = "^0.7", optional = true }
19
+
20
+ [tool.poetry.extras]
21
+ loguru = ["loguru"]
22
+
23
+ [tool.poetry-git-version-plugin]
24
+ make_alpha_version = false
File without changes
@@ -0,0 +1,95 @@
1
+ from http import HTTPStatus
2
+ from typing import List, Optional, Type, TypeVar, Final
3
+
4
+ import requests
5
+ from loguru import logger
6
+
7
+ from cams_ncp_client.schemas.common import TableData
8
+ from vito.sas.air.api_client import RESTclient
9
+
10
+ API_V1: Final[str] = "api/v1"
11
+ PRIVATE_API_V1: Final[str] = "private/v1"
12
+
13
+ T = TypeVar('T')
14
+
15
+
16
+ class BaseClient(RESTclient):
17
+ """
18
+ Base client for the CAMS NCP API.
19
+ This class provides methods to build URLs for public and private APIs,
20
+ and to parse responses into specified models.
21
+ It inherits from the RESTclient class, which handles HTTP requests.
22
+
23
+ Attributes:
24
+ base_url (str): The base URL for the API.
25
+ session (requests.Session): Session for making HTTP requests.
26
+ """
27
+
28
+ def __init__(self, base_url: str, session: Optional[requests.Session] = None):
29
+ super().__init__(base_url, session)
30
+
31
+ def _build_url_public_api(self, *parts: str) -> str:
32
+ return self._build_url(API_V1, *parts)
33
+
34
+ def _build_url_private_api(self, *parts: str) -> str:
35
+ return self._build_url(PRIVATE_API_V1, *parts)
36
+
37
+ def parse_typed_response(self, response: requests.Response, model: Type[T]) -> T:
38
+ """
39
+ Parses a single response into the specified model.
40
+ """
41
+ try:
42
+ if response.status_code >= HTTPStatus.BAD_REQUEST:
43
+ logger.exception(response.text)
44
+ response.raise_for_status()
45
+ return model(**response.json())
46
+ except requests.RequestException as e:
47
+ logger.error(f"HTTP error: {e} | URL: {response.url}")
48
+ raise
49
+ except Exception as e:
50
+ logger.error(f"Response parsing failed: {e} | Response: {response.text}")
51
+ raise
52
+
53
+ def parse_table_response(self, response: requests.Response, model: Type[T]) -> TableData[T]:
54
+ """
55
+ Parses a response into a TableData object (of the specified model type)
56
+ """
57
+ try:
58
+ if response.status_code >= HTTPStatus.BAD_REQUEST:
59
+ logger.exception(response.text)
60
+ response.raise_for_status()
61
+ response_json = response.json()
62
+
63
+ data = [model(**item) for item in response_json.get("data", [])]
64
+ offset = response_json.get("offset", 0)
65
+ limit = response_json.get("limit", len(data))
66
+ count = response_json.get("count", len(data))
67
+
68
+ return TableData(
69
+ data=data,
70
+ offset=offset,
71
+ limit=limit,
72
+ count=count
73
+ )
74
+ except requests.RequestException as e:
75
+ logger.error(f"HTTP error: {e} | URL: {response.url}")
76
+ raise
77
+ except Exception as e:
78
+ logger.error(f"List response parsing failed: {e} | Response: {response.text}")
79
+ raise
80
+
81
+ def parse_list_response(self, response: requests.Response, model: Type[T]) -> List[T]:
82
+ """
83
+ Parses a list response into a List of the specified model.
84
+ """
85
+ try:
86
+ if response.status_code >= HTTPStatus.BAD_REQUEST:
87
+ logger.exception(response.text)
88
+ response.raise_for_status()
89
+ return [model(**item) for item in response.json()]
90
+ except requests.RequestException as e:
91
+ logger.error(f"HTTP error: {e} | URL: {response.url}")
92
+ raise
93
+ except Exception as e:
94
+ logger.error(f"List response parsing failed: {e} | Response: {response.text}")
95
+ raise
@@ -0,0 +1,184 @@
1
+ from pathlib import Path
2
+ from typing import List
3
+
4
+ from loguru import logger
5
+
6
+ from cams_ncp_client._base import BaseClient
7
+
8
+
9
+ class CamsFileClient(BaseClient):
10
+ """
11
+ Client for interacting with measuring stations.
12
+ """
13
+
14
+ def upload_cams_file(self,
15
+ year: int,
16
+ month: int,
17
+ day: int,
18
+ pollutant: str,
19
+ cams_model: str,
20
+ forecast_days: int,
21
+ file_path: Path):
22
+ """
23
+ Upload CAMS data file to the API.
24
+
25
+ Args:
26
+ year: The year of the CAMS data
27
+ month: The month of the CAMS data (1-12)
28
+ day: The day of the CAMS data (1-31)
29
+ pollutant: The pollutant type
30
+ cams_model: The CAMS model name
31
+ forecast_days: The number of forecasted days
32
+ file_path: Path to the file to upload
33
+
34
+ Returns:
35
+ Response from the API as a dictionary
36
+
37
+ Raises:
38
+ ValueError: If parameters are invalid
39
+ FileNotFoundError: If the file doesn't exist
40
+ requests.RequestException: For API communication errors
41
+ """
42
+ # Validate parameters
43
+ if not 1900 < year <= 2200:
44
+ raise ValueError(f"{year} is not a valid year. Year must be between 1900 and 2200")
45
+ if not 1 <= month <= 12:
46
+ raise ValueError("Month must be between 1 and 12")
47
+ if not 1 <= day <= 31:
48
+ raise ValueError("Day must be between 1 and 31")
49
+ if not file_path.exists():
50
+ raise FileNotFoundError(f"File not found: {file_path}")
51
+
52
+ # Prepare the endpoint URL
53
+ url = self._build_url_private_api(f"/cams/{year}/{month}/{day}")
54
+
55
+ # Prepare form data
56
+ form_data = {
57
+ "pollutant": pollutant,
58
+ "cams_model": cams_model,
59
+ "forecast_days": forecast_days
60
+ }
61
+
62
+ # Prepare file
63
+ with open(file_path, 'rb') as f:
64
+ files = {'file': (file_path.name, f)}
65
+ response = self._exec_post(url, data=form_data, files=files)
66
+
67
+ # Raise exception for HTTP errors
68
+ logger.debug(f"upload_cams() url: {url} response code: {response.status_code}, json: {response.json()}")
69
+ response.raise_for_status()
70
+
71
+
72
+ def download_cams_file(self,
73
+ year: int,
74
+ month: int,
75
+ day: int,
76
+ pollutant: str,
77
+ cams_model: str,
78
+ forecast_days: int,
79
+ output_path: Path | str) -> Path:
80
+ """
81
+ Download CAMS data file from the API.
82
+
83
+ Args:
84
+ year: The year of the CAMS data (>1900, <=2200)
85
+ month: The month of the CAMS data (1-12)
86
+ day: The day of the CAMS data (1-31)
87
+ pollutant: The pollutant type
88
+ cams_model: The CAMS model name
89
+ forecast_days: The number of forecasted days
90
+ output_path: Output directory or file path where the downloaded file will be saved.
91
+
92
+ Returns:
93
+ Path object pointing to the downloaded file
94
+
95
+ Raises:
96
+ ValueError: If parameters are invalid
97
+ requests.RequestException: For API communication errors
98
+ IOError: If the output file cannot be written
99
+ """
100
+ # Validate parameters
101
+ if not 1900 < year <= 2200:
102
+ raise ValueError("Year must be between 2001 and 3000")
103
+ if not 1 <= month <= 12:
104
+ raise ValueError("Month must be between 1 and 12")
105
+ if not 1 <= day <= 31:
106
+ raise ValueError("Day must be between 1 and 31")
107
+
108
+ if not isinstance(output_path, Path):
109
+ output_path = Path(output_path)
110
+
111
+ # Prepare the endpoint URL - note using different base URL for public endpoint
112
+ # Assuming public route is at the same base but without the /private part
113
+ url = self._build_url_public_api(f"/cams/{year}/{month}/{day}")
114
+
115
+ # Prepare query parameters
116
+ params = {
117
+ "pollutant": pollutant,
118
+ "cams_model": cams_model,
119
+ "forecast_days": forecast_days
120
+ }
121
+
122
+ # Send the request with stream=True to handle large files efficiently
123
+ response = self._exec_get(url, params=params, stream=True)
124
+
125
+ # Raise exception for HTTP errors
126
+ response.raise_for_status()
127
+
128
+ # Get filename from Content-Disposition header or create a default one
129
+ filename = None
130
+ content_disposition = response.headers.get('Content-Disposition')
131
+ if content_disposition:
132
+ import re
133
+ filename_match = re.search(r'filename="?([^"]+)"?', content_disposition)
134
+ if filename_match:
135
+ filename = filename_match.group(1)
136
+
137
+ if not filename:
138
+ raise ValueError("Filename not found in response headers. Please specify the output path.")
139
+
140
+ # Determine the output file path
141
+ output_path.mkdir(parents=True, exist_ok=True)
142
+ file_path = output_path / filename
143
+
144
+ # Write the file
145
+ with open(file_path, 'wb') as f:
146
+ for chunk in response.iter_content(chunk_size=8192):
147
+ f.write(chunk)
148
+
149
+ return file_path
150
+
151
+ def list_cams_files(self, year: int, month: int, day: int) -> List[str]:
152
+ """
153
+ List all CAMS files for a given date.
154
+
155
+ Args:
156
+ year: The year of the CAMS data
157
+ month: The month of the CAMS data (1-12)
158
+ day: The day of the CAMS data (1-31)
159
+
160
+ Returns:
161
+ List of file names
162
+
163
+ Raises:
164
+ ValueError: If parameters are invalid
165
+ requests.RequestException: For API communication errors
166
+ """
167
+ # Validate parameters
168
+ if not 1900 < year <= 2200:
169
+ raise ValueError("Year must be between 1900 and 2200")
170
+ if not 1 <= month <= 12:
171
+ raise ValueError("Month must be between 1 and 12")
172
+ if not 1 <= day <= 31:
173
+ raise ValueError("Day must be between 1 and 31")
174
+
175
+ url = self._build_url_public_api(f"/cams/{year}/{month}/{day}/files")
176
+ response = self._exec_get(url)
177
+ response.raise_for_status()
178
+
179
+ # Parse JSON response
180
+ string_list: List[str] = response.json()
181
+ assert isinstance(string_list, list), "Expected a list of strings"
182
+ for item in string_list:
183
+ assert isinstance(item, str), f"Expected a string, got {type(item)}"
184
+ return string_list
@@ -0,0 +1,80 @@
1
+ from typing import Optional
2
+
3
+ import requests
4
+
5
+ from cams_ncp_client.cams_file import CamsFileClient
6
+ from cams_ncp_client.forecast import ForecastClient
7
+ from cams_ncp_client.model import ModelClient
8
+ from cams_ncp_client.observation import ObservationClient
9
+ from cams_ncp_client.quantity import QuantityClient
10
+ from cams_ncp_client.station import StationClient
11
+ from vito.sas.air.utils.date_utils import iso_utc_to_datetime
12
+
13
+
14
+ # from cams_ncp_api.client.utils.date_utils import iso_utc_to_datetime
15
+
16
+
17
+ class CamsNcpApiClient:
18
+
19
+
20
+ """
21
+ Client for interacting with the CAMS NCP API.
22
+
23
+ Attributes:
24
+ base_url (str): The base URL for the API.
25
+ session (requests.Session): Session for making HTTP requests.
26
+
27
+ Usage:
28
+ >>> client = CamsNcpApiClient(base_url="http://localhost:5050")
29
+ >>> quantities = client.quantity.get_quantities_df()
30
+ >>> stations = client.station.find_stations(limit=10, quantity="PM10")
31
+ >>> observations = client.observation.find_observations(station_name="42N016", start_time=iso_utc_to_datetime("2023-01-01T00:00:00Z"))
32
+ """
33
+ def __init__(self,
34
+ base_url: str,
35
+ session: Optional[requests.Session] = None
36
+ ):
37
+ self.base_url = base_url.rstrip('/')
38
+ self.session = session if session is not None else requests.Session()
39
+ self._station = None
40
+ self._quantity = None
41
+ self._observation = None
42
+ self._forecast = None
43
+ self._model = None
44
+ self._cams_file = None
45
+
46
+ @property
47
+ def station(self) -> StationClient:
48
+ if self._station is None:
49
+ self._station = StationClient(self.base_url, self.session)
50
+ return self._station
51
+
52
+ @property
53
+ def quantity(self) -> QuantityClient:
54
+ if self._quantity is None:
55
+ self._quantity = QuantityClient(self.base_url, self.session)
56
+ return self._quantity
57
+
58
+ @property
59
+ def observation(self) -> ObservationClient:
60
+ if self._observation is None:
61
+ self._observation = ObservationClient(self.base_url, self.session)
62
+ return self._observation
63
+
64
+ @property
65
+ def forecast(self) -> ForecastClient:
66
+ if self._forecast is None:
67
+ self._forecast = ForecastClient(self.base_url, self.session)
68
+ return self._forecast
69
+
70
+ @property
71
+ def model(self) -> ModelClient:
72
+ if self._model is None:
73
+ self._model = ModelClient(self.base_url, self.session)
74
+ return self._model
75
+
76
+ @property
77
+ def cams_file(self) -> CamsFileClient:
78
+ if self._cams_file is None:
79
+ self._cams_file = CamsFileClient(self.base_url, self.session)
80
+ return self._cams_file