meteo-lt-pkg 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.
meteo_lt/__init__.py ADDED
@@ -0,0 +1,11 @@
1
+ """init.py"""
2
+
3
+ from .api import MeteoLtAPI
4
+ from .models import Coordinates, Place, ForecastTimestamp, Forecast
5
+
6
+ __all__ = [
7
+ 'MeteoLtAPI',
8
+ 'Coordinates',
9
+ 'Place',
10
+ 'ForecastTimestamp',
11
+ 'Forecast']
meteo_lt/api.py ADDED
@@ -0,0 +1,53 @@
1
+ """Main API class script"""
2
+
3
+ import aiohttp
4
+ from scipy.spatial import KDTree
5
+ import numpy as np
6
+
7
+ from .models import Place, Forecast
8
+
9
+
10
+ class MeteoLtAPI:
11
+ """Main API class"""
12
+
13
+ BASE_URL = "https://api.meteo.lt/v1"
14
+ TIMEOUT = 30
15
+ ENCODING = "utf-8"
16
+
17
+ def __init__(self):
18
+ self.places = []
19
+
20
+ async def fetch_places(self):
21
+ """Gets all places from API"""
22
+ async with aiohttp.ClientSession(
23
+ timeout=aiohttp.ClientTimeout(total=self.TIMEOUT)
24
+ ) as session:
25
+ async with session.get(f"{self.BASE_URL}/places") as response:
26
+ response.raise_for_status()
27
+ response.encoding = self.ENCODING
28
+ response_json = await response.json()
29
+ self.places = [Place.from_dict(place) for place in response_json]
30
+
31
+ async def get_nearest_place(self, latitude, longitude):
32
+ """Finds nearest place using provided coordinates"""
33
+ if not self.places:
34
+ await self.fetch_places()
35
+ coordinates = np.array(
36
+ [[place.latitude, place.longitude] for place in self.places]
37
+ )
38
+ tree = KDTree(coordinates)
39
+ _, idx = tree.query([latitude, longitude])
40
+ return self.places[idx]
41
+
42
+ async def get_forecast(self, place_code):
43
+ """Retrieves forecast data from API"""
44
+ async with aiohttp.ClientSession(
45
+ timeout=aiohttp.ClientTimeout(total=self.TIMEOUT)
46
+ ) as session:
47
+ async with session.get(
48
+ f"{self.BASE_URL}/places/{place_code}/forecasts/long-term"
49
+ ) as response:
50
+ response.raise_for_status()
51
+ response.encoding = self.ENCODING
52
+ response_json = await response.json()
53
+ return Forecast.from_dict(response_json)
meteo_lt/models.py ADDED
@@ -0,0 +1,117 @@
1
+ """Models script"""
2
+ from dataclasses import dataclass, field, fields
3
+ from typing import List
4
+ from datetime import datetime, timezone
5
+
6
+ @dataclass
7
+ class Coordinates:
8
+ """Coordinates class"""
9
+ latitude: float
10
+ longitude: float
11
+
12
+ @dataclass
13
+ class Place:
14
+ """Places"""
15
+ code: str
16
+ name: str
17
+ administrative_division: str = field(metadata={"json_key": "administrativeDivision"})
18
+ country: str
19
+ coordinates: Coordinates
20
+
21
+ @property
22
+ def latitude(self):
23
+ """Latitude from coordinates"""
24
+ return self.coordinates.latitude
25
+
26
+ @property
27
+ def longitude(self):
28
+ """Longitude from coordinates"""
29
+ return self.coordinates.longitude
30
+
31
+ @dataclass
32
+ class ForecastTimestamp:
33
+ """ForecastTimestamp"""
34
+ datetime: str = field(metadata={"json_key": "forecastTimeUtc"})
35
+ temperature: float = field(metadata={"json_key": "airTemperature"})
36
+ apparent_temperature: float = field(metadata={"json_key": "feelsLikeTemperature"})
37
+ condition_code: str = field(metadata={"json_key": "conditionCode"})
38
+ wind_speed: float = field(metadata={"json_key": "windSpeed"})
39
+ wind_gust_speed: float = field(metadata={"json_key": "windGust"})
40
+ wind_bearing: float = field(metadata={"json_key": "windDirection"})
41
+ cloud_coverage: float = field(metadata={"json_key": "cloudCover"})
42
+ pressure: float = field(metadata={"json_key": "seaLevelPressure"})
43
+ humidity: float = field(metadata={"json_key": "relativeHumidity"})
44
+ precipitation: float = field(metadata={"json_key": "totalPrecipitation"})
45
+ condition: str = field(init=False)
46
+
47
+ def __post_init__(self):
48
+ self.condition = map_condition(self.condition_code)
49
+
50
+
51
+ @dataclass
52
+ class Forecast:
53
+ """Forecast"""
54
+ place: Place
55
+ forecast_timestamps: List[ForecastTimestamp] = field(
56
+ metadata={"json_key": "forecastTimestamps"}
57
+ )
58
+
59
+ def current_conditions(self) -> ForecastTimestamp:
60
+ """Treat first record as current conditions"""
61
+ return self.forecast_timestamps[0] if self.forecast_timestamps else None
62
+
63
+ def from_dict(cls, data: dict):
64
+ """Utility function to convert a dictionary to a dataclass instance."""
65
+ init_args = {}
66
+ for f in fields(cls):
67
+ if not f.init:
68
+ continue # Skip fields that are not part of the constructor
69
+
70
+ json_key = f.metadata.get('json_key', f.name)
71
+ value = data.get(json_key)
72
+
73
+ # Recursively convert nested dataclasses
74
+ if isinstance(value, dict) and hasattr(f.type, 'from_dict'):
75
+ value = from_dict(f.type, value)
76
+ elif isinstance(value, list) and hasattr(f.type.__args__[0], 'from_dict'):
77
+ value = [from_dict(f.type.__args__[0], item) for item in value]
78
+ elif f.name == 'datetime':
79
+ # Ensure the datetime string is in the correct format
80
+ dt = datetime.fromisoformat(value).astimezone(timezone.utc)
81
+ value = dt.strftime('%Y-%m-%dT%H:%M:%S%z')
82
+
83
+ init_args[f.name] = value
84
+ return cls(**init_args)
85
+
86
+ Coordinates.from_dict = classmethod(from_dict)
87
+ Place.from_dict = classmethod(from_dict)
88
+ ForecastTimestamp.from_dict = classmethod(from_dict)
89
+ Forecast.from_dict = classmethod(from_dict)
90
+
91
+ def map_condition(api_condition):
92
+ """Condition code mapping"""
93
+ condition_mapping = {
94
+ 'clear': 'sunny',
95
+ 'partly-cloudy': 'partlycloudy',
96
+ 'cloudy-with-sunny-intervals': 'partlycloudy',
97
+ 'cloudy': 'cloudy',
98
+ 'thunder': 'lightning',
99
+ 'isolated-thunderstorms': 'lightning-rainy',
100
+ 'thunderstorms': 'lightning-rainy',
101
+ 'heavy-rain-with-thunderstorms': 'lightning-rainy',
102
+ 'light-rain': 'rainy',
103
+ 'rain': 'rainy',
104
+ 'heavy-rain': 'pouring',
105
+ 'light-sleet': 'snowy-rainy',
106
+ 'sleet': 'snowy-rainy',
107
+ 'freezing-rain': 'snowy-rainy',
108
+ 'hail': 'hail',
109
+ 'light-snow': 'snowy',
110
+ 'snow': 'snowy',
111
+ 'heavy-snow': 'snowy',
112
+ 'fog': 'fog',
113
+ None: 'exceptional' # For null or undefined conditions
114
+ }
115
+
116
+ # Default to 'exceptional' if the condition is not found in the mapping
117
+ return condition_mapping.get(api_condition, 'exceptional')
meteo_lt/utils.py ADDED
File without changes
@@ -0,0 +1,25 @@
1
+ Metadata-Version: 2.1
2
+ Name: meteo_lt-pkg
3
+ Version: 0.1.0
4
+ Summary: A library to fetch weather data from api.meteo.lt
5
+ License: MIT
6
+ Author: Brunas
7
+ Author-email: brunonas@gmail.com
8
+ Requires-Python: >=3.10,<4.0
9
+ Classifier: License :: OSI Approved :: MIT License
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3.10
12
+ Classifier: Programming Language :: Python :: 3.11
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Requires-Dist: aiohttp (>=3.9.5,<4.0.0)
15
+ Requires-Dist: asyncio (>=3.4.3,<4.0.0)
16
+ Requires-Dist: scipy (>=1.7.1,<2.0.0)
17
+ Description-Content-Type: text/markdown
18
+
19
+ # Meteo.LT Lithuanian weather forecast package
20
+ Python library for accessing Meteo.lt weather forecast data
21
+
22
+ Please visit https://api.meteo.lt/ for more information
23
+
24
+ If you want to contribute you can use devcontainers in vscode for easiest setup. Please see [instructions here](.devcontainer/README.md)
25
+
@@ -0,0 +1,7 @@
1
+ meteo_lt/__init__.py,sha256=rE-xerkZjxsHOpSw1BbaT4pI4_hYMesWHeSakymkcL4,215
2
+ meteo_lt/api.py,sha256=yxwIFGLX30vKSkPiNg4hymNZQtfHw6ZgX3W4fpISNww,1799
3
+ meteo_lt/models.py,sha256=d1XMav2yHuuIUaVr5zfyAU0OLOf35GPdKziuCbjrNZ4,4167
4
+ meteo_lt/utils.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
+ meteo_lt_pkg-0.1.0.dist-info/METADATA,sha256=466CYRA1ZmzPkYVHaU9UO1sER2Aqw0pPfLb2YjX9qS0,919
6
+ meteo_lt_pkg-0.1.0.dist-info/WHEEL,sha256=sP946D7jFCHeNz5Iq4fL4Lu-PrWrFsgfLXbbkciIZwg,88
7
+ meteo_lt_pkg-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: poetry-core 1.9.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any