local-flight-map 0.0.1__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.
Files changed (38) hide show
  1. local_flight_map/__init__.py +0 -0
  2. local_flight_map/__main__.py +25 -0
  3. local_flight_map/api/__init__.py +41 -0
  4. local_flight_map/api/adsbexchange.py +391 -0
  5. local_flight_map/api/base.py +176 -0
  6. local_flight_map/api/hexdb.py +211 -0
  7. local_flight_map/api/opensky.py +467 -0
  8. local_flight_map/ui/__init__.py +3 -0
  9. local_flight_map/ui/folium/__init__.py +5 -0
  10. local_flight_map/ui/folium/js/markercluster_icon_create_function.js +38 -0
  11. local_flight_map/ui/folium/js/realtime_get_feature_id.js +1 -0
  12. local_flight_map/ui/folium/js/realtime_point_to_layer.js +177 -0
  13. local_flight_map/ui/folium/js/realtime_source.js +23 -0
  14. local_flight_map/ui/folium/js/realtime_update_feature.js +165 -0
  15. local_flight_map/ui/folium/jscode.py +41 -0
  16. local_flight_map/ui/folium/markercluster.py +16 -0
  17. local_flight_map/ui/folium/realtime.py +13 -0
  18. local_flight_map/ui/panel/__init__.py +3 -0
  19. local_flight_map/ui/panel/config.py +82 -0
  20. local_flight_map/ui/panel/data.py +122 -0
  21. local_flight_map/ui/panel/interface.py +256 -0
  22. local_flight_map/ui/panel/layers.py +121 -0
  23. local_flight_map/ui/panel/static/icons/civil_helicopter.png +0 -0
  24. local_flight_map/ui/panel/static/icons/civil_plane_1.png +0 -0
  25. local_flight_map/ui/panel/static/icons/civil_plane_2.png +0 -0
  26. local_flight_map/ui/panel/static/icons/civil_plane_3.png +0 -0
  27. local_flight_map/ui/panel/static/icons/clouds.png +0 -0
  28. local_flight_map/ui/panel/static/icons/forbidden.png +0 -0
  29. local_flight_map/ui/panel/static/icons/mil_plane_1.png +0 -0
  30. local_flight_map/ui/panel/static/icons/mil_plane_2.png +0 -0
  31. local_flight_map/ui/panel/static/icons/police_helicopter.png +0 -0
  32. local_flight_map/ui/panel/static/js/flight_marker_utils.js +78 -0
  33. local_flight_map-0.0.1.dist-info/METADATA +279 -0
  34. local_flight_map-0.0.1.dist-info/RECORD +38 -0
  35. local_flight_map-0.0.1.dist-info/WHEEL +5 -0
  36. local_flight_map-0.0.1.dist-info/entry_points.txt +2 -0
  37. local_flight_map-0.0.1.dist-info/licenses/LICENSE +21 -0
  38. local_flight_map-0.0.1.dist-info/top_level.txt +1 -0
File without changes
@@ -0,0 +1,25 @@
1
+ import asyncio
2
+
3
+ from .api import ApiClient, ApiConfig
4
+ from .ui import MapInterface, MapConfig
5
+
6
+
7
+ async def amain():
8
+ api_config = ApiConfig()
9
+ map_config = MapConfig()
10
+ async with (
11
+ ApiClient(api_config) as client,
12
+ MapInterface(
13
+ config=map_config,
14
+ client=client
15
+ ) as map_interface
16
+ ):
17
+ await map_interface.serve()
18
+
19
+
20
+ def main():
21
+ asyncio.run(amain())
22
+
23
+
24
+ if __name__ == "__main__":
25
+ main()
@@ -0,0 +1,41 @@
1
+ from typing import Optional
2
+
3
+ from .opensky import OpenSkyClient, OpenSkyConfig
4
+ from .hexdb import HexDbClient, HexDbConfig
5
+ from .adsbexchange import AdsbExchangeClient, AdsbExchangeConfig
6
+ from .base import BBox, Location
7
+
8
+
9
+ class ApiConfig(OpenSkyConfig, HexDbConfig, AdsbExchangeConfig):
10
+ pass
11
+
12
+
13
+ class ApiClient(OpenSkyClient, HexDbClient, AdsbExchangeClient):
14
+ def __init__(self, config: Optional[ApiConfig] = None):
15
+ config = config or ApiConfig()
16
+ OpenSkyClient.__init__(self, config)
17
+ HexDbClient.__init__(self, config)
18
+ AdsbExchangeClient.__init__(self, config)
19
+
20
+ async def __aenter__(self):
21
+ """Enter the async context manager"""
22
+ await OpenSkyClient.__aenter__(self)
23
+ await HexDbClient.__aenter__(self)
24
+ await AdsbExchangeClient.__aenter__(self)
25
+ return self
26
+
27
+ async def __aexit__(self, exc_type, exc_val, exc_tb):
28
+ """Exit the async context manager"""
29
+ await OpenSkyClient.__aexit__(self, exc_type, exc_val, exc_tb)
30
+ await HexDbClient.__aexit__(self, exc_type, exc_val, exc_tb)
31
+ await AdsbExchangeClient.__aexit__(self, exc_type, exc_val, exc_tb)
32
+
33
+
34
+ __all__ = [
35
+ k for k, v in globals().items() if v in (
36
+ ApiConfig,
37
+ ApiClient,
38
+ BBox,
39
+ Location
40
+ )
41
+ ]
@@ -0,0 +1,391 @@
1
+ from dataclasses import dataclass
2
+ from typing import List, Optional, Union, Dict, Any
3
+ from pydantic import Field
4
+ from urllib.parse import urlparse
5
+ from async_lru import alru_cache
6
+ from .base import BaseClient, BaseConfig, ResponseObject, Location
7
+
8
+
9
+ @dataclass
10
+ class AircraftProperties(ResponseObject):
11
+ """
12
+ Represents an aircraft from ADSB Exchange API.
13
+
14
+ Attributes:
15
+ hex: The ICAO24 address of the transmitter in hex string representation.
16
+ type: The type of the aircraft (e.g., adsb_icao, mlat).
17
+ flight: The callsign of the aircraft. Can be None.
18
+ r: The registration of the aircraft. Can be None.
19
+ t: The type code of the aircraft. Can be None.
20
+ dbFlags: The database flags of the aircraft. Can be None.
21
+ alt_baro: The barometric altitude of the aircraft. Can be "ground" or a number.
22
+ alt_geom: The geometric altitude of the aircraft. Can be None.
23
+ gs: The ground speed of the aircraft in knots. Can be None.
24
+ ias: The indicated airspeed of the aircraft in knots. Can be None.
25
+ tas: The true airspeed of the aircraft in knots. Can be None.
26
+ mach: The Mach number of the aircraft. Can be None.
27
+ wd: The wind direction in degrees. Can be None.
28
+ ws: The wind speed in knots. Can be None.
29
+ oat: The outside air temperature in Celsius. Can be None.
30
+ tat: The total air temperature in Celsius. Can be None.
31
+ track: The track angle in degrees. Can be None.
32
+ track_rate: The rate of change of track angle in degrees per second. Can be None.
33
+ roll: The roll angle in degrees. Can be None.
34
+ mag_heading: The magnetic heading in degrees. Can be None.
35
+ true_heading: The true heading in degrees. Can be None.
36
+ baro_rate: The barometric rate of climb/descent in feet per minute. Can be None.
37
+ geom_rate: The geometric rate of climb/descent in feet per minute. Can be None.
38
+ squawk: The squawk code of the aircraft. Can be None.
39
+ emergency: The emergency status of the aircraft. Can be None.
40
+ category: The category of the aircraft. Can be None.
41
+ nav_qnh: The QNH pressure in hPa. Can be None.
42
+ nav_altitude_mcp: The MCP selected altitude in feet. Can be None.
43
+ nav_altitude_fms: The FMS selected altitude in feet. Can be None.
44
+ nav_heading: The selected heading in degrees. Can be None.
45
+ nav_modes: The navigation modes. Can be None.
46
+ lat: The latitude of the aircraft. Can be None.
47
+ lon: The longitude of the aircraft. Can be None.
48
+ nic: The navigation integrity category. Can be None.
49
+ rc: The radius of containment. Can be None.
50
+ seen_pos: The time since last position update in seconds. Can be None.
51
+ version: The version of the aircraft's ADS-B system. Can be None.
52
+ nic_baro: The barometric navigation integrity category. Can be None.
53
+ nac_p: The navigation accuracy category for position. Can be None.
54
+ nac_v: The navigation accuracy category for velocity. Can be None.
55
+ sil: The surveillance integrity level. Can be None.
56
+ sil_type: The type of surveillance integrity level. Can be None.
57
+ gva: The geometric vertical accuracy. Can be None.
58
+ sda: The system design assurance. Can be None.
59
+ alert: The alert flag. Can be None.
60
+ spi: The special position indicator flag. Can be None.
61
+ mlat: The multilateration sources. Can be None.
62
+ tisb: The TIS-B sources. Can be None.
63
+ messages: The number of messages received. Can be None.
64
+ seen: The time since last update in seconds. Can be None.
65
+ rssi: The received signal strength indicator in dBm. Can be None.
66
+ gpsOkBefore: The time since last GPS update in seconds. Can be None.
67
+ gpsOkLat: The latitude of the GPS update. Can be None.
68
+ gpsOkLon: The longitude of the GPS update. Can be None.
69
+ """
70
+ hex: str
71
+ type: str
72
+ flight: Optional[str]
73
+ r: Optional[str]
74
+ t: Optional[str]
75
+ dbFlags: Optional[int]
76
+ alt_baro: Union[str, int]
77
+ alt_geom: Optional[int]
78
+ gs: Optional[float]
79
+ ias: Optional[float]
80
+ tas: Optional[float]
81
+ mach: Optional[float]
82
+ wd: Optional[float]
83
+ ws: Optional[float]
84
+ oat: Optional[float]
85
+ tat: Optional[float]
86
+ track: Optional[float]
87
+ track_rate: Optional[float]
88
+ roll: Optional[float]
89
+ mag_heading: Optional[float]
90
+ true_heading: Optional[float]
91
+ baro_rate: Optional[float]
92
+ geom_rate: Optional[float]
93
+ squawk: Optional[str]
94
+ emergency: Optional[str]
95
+ category: Optional[str]
96
+ nav_qnh: Optional[float]
97
+ nav_altitude_mcp: Optional[int]
98
+ nav_altitude_fms: Optional[int]
99
+ nav_heading: Optional[float]
100
+ nav_modes: Optional[List[str]]
101
+ lat: Optional[float]
102
+ lon: Optional[float]
103
+ nic: Optional[int]
104
+ rc: Optional[int]
105
+ seen_pos: Optional[float]
106
+ version: Optional[int]
107
+ nic_baro: Optional[int]
108
+ nac_p: Optional[int]
109
+ nac_v: Optional[int]
110
+ sil: Optional[int]
111
+ sil_type: Optional[str]
112
+ gva: Optional[int]
113
+ sda: Optional[int]
114
+ alert: Optional[int]
115
+ spi: Optional[int]
116
+ mlat: Optional[List[str]]
117
+ tisb: Optional[List[str]]
118
+ messages: Optional[int]
119
+ seen: Optional[float]
120
+ rssi: Optional[float]
121
+ gpsOkBefore: Optional[float]
122
+ gpsOkLat: Optional[float]
123
+ gpsOkLon: Optional[float]
124
+
125
+ def to_geojson(self) -> Dict[str, Any]:
126
+ return {
127
+ "type": "Feature",
128
+ "geometry": {
129
+ "type": "Point",
130
+ "coordinates": [
131
+ self.gpsOkLon if self.gpsOkLon else self.lon,
132
+ self.gpsOkLat if self.gpsOkLat else self.lat
133
+ ]
134
+ },
135
+ "properties": {
136
+ "icao24_code": self.hex,
137
+ "callsign": self.flight,
138
+ "registration": self.r,
139
+ "type": self.t,
140
+ "baro_altitude": self.alt_baro,
141
+ "geom_altitude": self.alt_geom,
142
+ "ground_speed": self.gs,
143
+ "indicated_airspeed": self.ias,
144
+ "true_airspeed": self.tas,
145
+ "mach": self.mach,
146
+ "wind_direction": self.wd,
147
+ "wind_speed": self.ws,
148
+ "outside_air_temperature": self.oat,
149
+ "total_air_temperature": self.tat,
150
+ "track_angle": self.track,
151
+ "track_rate": self.track_rate,
152
+ "roll_angle": self.roll,
153
+ "magnetic_heading": self.mag_heading,
154
+ "true_heading": self.true_heading,
155
+ "baro_rate_of_climb_descent": self.baro_rate,
156
+ "geom_rate_of_climb_descent": self.geom_rate,
157
+ "squawk_code": self.squawk,
158
+ "emergency_status": self.emergency,
159
+ "category": self.category,
160
+ "qnh_pressure": self.nav_qnh,
161
+ "mcp_altitude": self.nav_altitude_mcp,
162
+ "fms_altitude": self.nav_altitude_fms,
163
+ "heading": self.nav_heading,
164
+ "navigation_modes": self.nav_modes,
165
+ "latitude": self.lat,
166
+ "longitude": self.lon,
167
+ "navigation_integrity_category": self.nic,
168
+ "radius_of_containment": self.rc,
169
+ "time_since_last_position_update": self.seen_pos,
170
+ "version": self.version,
171
+ "baro_navigation_integrity_category": self.nic_baro,
172
+ "navigation_accuracy_category_for_position": self.nac_p,
173
+ "navigation_accuracy_category_for_velocity": self.nac_v,
174
+ "surveillance_integrity_level": self.sil,
175
+ "surveillance_integrity_level_type": self.sil_type,
176
+ "geometric_vertical_accuracy": self.gva,
177
+ "system_design_assurance": self.sda,
178
+ "alert_flag": self.alert,
179
+ "special_position_indicator_flag": self.spi,
180
+ "multilateration_sources": self.mlat,
181
+ "tisb_sources": self.tisb,
182
+ "number_of_messages_received": self.messages,
183
+ "time_since_last_update": self.seen,
184
+ "received_signal_strength_indicator": self.rssi,
185
+ "time_since_last_gps_update": self.gpsOkBefore,
186
+ "latitude_of_gps_update": self.gpsOkLat,
187
+ "longitude_of_gps_update": self.gpsOkLon
188
+ }
189
+ }
190
+
191
+
192
+ @dataclass
193
+ class AdsbExchangeResponse(ResponseObject):
194
+ """
195
+ Represents a response from ADSB Exchange API.
196
+
197
+ Attributes:
198
+ ac: List of aircraft data.
199
+ msg: Message from the API.
200
+ now: Current timestamp in milliseconds since epoch.
201
+ total: Total number of aircraft.
202
+ ctime: Client timestamp in milliseconds since epoch.
203
+ ptime: Processing time in milliseconds.
204
+ """
205
+ ac: List[AircraftProperties]
206
+ msg: str
207
+ now: int
208
+ total: int
209
+ ctime: int
210
+ ptime: int
211
+
212
+ @classmethod
213
+ def from_dict(cls, data: Dict[str, Any]) -> 'AdsbExchangeResponse':
214
+ return cls(
215
+ ac=[AircraftProperties.from_dict(aircraft) for aircraft in data['ac'] or []],
216
+ msg=data['msg'],
217
+ now=data['now'],
218
+ total=data['total'],
219
+ ctime=data['ctime'],
220
+ ptime=data['ptime']
221
+ )
222
+
223
+ def to_geojson(self) -> Dict[str, Any]:
224
+ return {
225
+ "type": "FeatureCollection",
226
+ "features": [aircraft.to_geojson() for aircraft in self.ac]
227
+ }
228
+
229
+
230
+ class AdsbExchangeConfig(BaseConfig):
231
+ """
232
+ Config for the AdsbExchange API.
233
+
234
+ Attributes:
235
+ adsbexchange_base_url: The base URL for the AdsbExchange API.
236
+ adsbexchange_api_key: The API key for the AdsbExchange API.
237
+ """
238
+ adsbexchange_base_url: str = Field(
239
+ default="https://adsbexchange-com1.p.rapidapi.com/",
240
+ description="The base URL for the AdsbExchange API"
241
+ )
242
+ adsbexchange_api_key: str = Field(
243
+ default="",
244
+ description="The API key for the AdsbExchange API",
245
+ repr=False,
246
+ exclude=True
247
+ )
248
+
249
+
250
+ class AdsbExchangeClient(BaseClient):
251
+ """
252
+ Client for the AdsbExchange API.
253
+ """
254
+ def __init__(self, config: Optional[AdsbExchangeConfig] = None):
255
+ config = config or AdsbExchangeConfig()
256
+ BaseClient.__init__(
257
+ self,
258
+ config=config,
259
+ base_url=config.adsbexchange_base_url,
260
+ headers={
261
+ 'X-RapidAPI-Key': config.adsbexchange_api_key,
262
+ 'X-RapidAPI-Host': urlparse(config.adsbexchange_base_url).netloc
263
+ }
264
+ )
265
+
266
+ async def __aexit__(self, exc_type, exc_val, exc_tb):
267
+ await self.get_aircraft_from_adsbexchange_by_registration.cache_close()
268
+ await self.get_aircraft_from_adsbexchange_by_icao24.cache_close()
269
+ await self.get_aircraft_from_adsbexchange_by_callsign.cache_close()
270
+ await self.get_aircraft_from_adsbexchange_by_squawk.cache_close()
271
+ await self.get_military_aircrafts_from_adsbexchange.cache_close()
272
+ await self.get_aircraft_from_adsbexchange_within_range.cache_close()
273
+ await super(AdsbExchangeClient, self).__aexit__(exc_type, exc_val, exc_tb)
274
+
275
+ @alru_cache(maxsize=1000)
276
+ async def get_aircraft_from_adsbexchange_by_registration(
277
+ self,
278
+ registration: str
279
+ ) -> Optional[AdsbExchangeResponse]:
280
+ """
281
+ Get aircraft information from ADSB Exchange by registration.
282
+
283
+ Args:
284
+ registration: The registration of the aircraft.
285
+
286
+ Returns:
287
+ Optional[AdsbExchangeResponse]: The aircraft information.
288
+ """
289
+ async with self._session.get("/v2/registration/{registration}".format(
290
+ registration=registration.strip()
291
+ )) as response:
292
+ data = await self._handle_response(response)
293
+ return AdsbExchangeResponse.from_dict(data) if data else None
294
+
295
+ @alru_cache(ttl=0.1)
296
+ async def get_aircraft_from_adsbexchange_by_icao24(
297
+ self,
298
+ icao24: str
299
+ ) -> Optional[AdsbExchangeResponse]:
300
+ """
301
+ Get aircraft information from ADSB Exchange by ICAO24.
302
+
303
+ Args:
304
+ icao24: The ICAO24 of the aircraft.
305
+
306
+ Returns:
307
+ Optional[AdsbExchangeResponse]: The aircraft information.
308
+ """
309
+ async with self._session.get("/v2/icao/{icao24}".format(
310
+ icao24=icao24.strip()
311
+ )) as response:
312
+ data = await self._handle_response(response)
313
+ return AdsbExchangeResponse.from_dict(data) if data else None
314
+
315
+ @alru_cache(ttl=0.1)
316
+ async def get_aircraft_from_adsbexchange_by_callsign(
317
+ self,
318
+ callsign: str
319
+ ) -> Optional[AdsbExchangeResponse]:
320
+ """
321
+ Get aircraft information from ADSB Exchange by callsign.
322
+
323
+ Args:
324
+ callsign: The callsign of the aircraft.
325
+
326
+ Returns:
327
+ Optional[AdsbExchangeResponse]: The aircraft information.
328
+ """
329
+ async with self._session.get("/v2/callsign/{callsign}".format(
330
+ callsign=callsign.lower().strip()
331
+ )) as response:
332
+ data = await self._handle_response(response)
333
+ return AdsbExchangeResponse.from_dict(data) if data else None
334
+
335
+ @alru_cache(ttl=0.1)
336
+ async def get_aircraft_from_adsbexchange_by_squawk(
337
+ self,
338
+ squawk: str
339
+ ) -> Optional[AdsbExchangeResponse]:
340
+ """
341
+ Get aircraft information from ADSB Exchange by squawk.
342
+
343
+ Args:
344
+ squawk: The squawk of the aircraft.
345
+
346
+ Returns:
347
+ Optional[AdsbExchangeResponse]: The aircraft information.
348
+ """
349
+ async with self._session.get("/v2/sqk/{squawk}".format(
350
+ squawk=squawk.strip()
351
+ )) as response:
352
+ data = await self._handle_response(response)
353
+ return AdsbExchangeResponse.from_dict(data) if data else None
354
+
355
+ @alru_cache(ttl=0.1)
356
+ async def get_military_aircrafts_from_adsbexchange(
357
+ self,
358
+ ) -> Optional[AdsbExchangeResponse]:
359
+ """
360
+ Get military aircrafts from ADSB Exchange.
361
+
362
+ Returns:
363
+ Optional[AdsbExchangeResponse]: The military aircrafts information.
364
+ """
365
+ async with self._session.get("/v2/mil") as response:
366
+ data = await self._handle_response(response)
367
+ return AdsbExchangeResponse.from_dict(data) if data else None
368
+
369
+ @alru_cache(ttl=0.1)
370
+ async def get_aircraft_from_adsbexchange_within_range(
371
+ self,
372
+ center: Location,
373
+ radius: int
374
+ ) -> Optional[AdsbExchangeResponse]:
375
+ """
376
+ Get aircraft information from ADSB Exchange within a range.
377
+
378
+ Args:
379
+ center: The center of the range.
380
+ radius: The radius of the range in nautical miles.
381
+
382
+ Returns:
383
+ Optional[AdsbExchangeResponse]: The aircraft information.
384
+ """
385
+ async with self._session.get("/v2/lat/{lat}/lon/{lon}/dist/{radius}".format(
386
+ lat=center.latitude,
387
+ lon=center.longitude,
388
+ radius=radius
389
+ )) as response:
390
+ data = await self._handle_response(response)
391
+ return AdsbExchangeResponse.from_dict(data) if data else None
@@ -0,0 +1,176 @@
1
+ import aiohttp
2
+ from typing import Optional, NamedTuple, Dict, Any, List, Union
3
+ import math
4
+ from dataclasses import asdict
5
+ import json
6
+ from itertools import zip_longest
7
+ from pydantic_settings import BaseSettings, SettingsConfigDict
8
+
9
+
10
+ class Location(NamedTuple):
11
+ latitude: float
12
+ longitude: float
13
+
14
+
15
+ class BBox(NamedTuple):
16
+ min_lat: float # South
17
+ max_lat: float # North
18
+ min_lon: float # West
19
+ max_lon: float # East
20
+
21
+ def validate(self):
22
+ """
23
+ Validate the bounding box.
24
+
25
+ Raises:
26
+ ValueError: If the bounding box is invalid.
27
+ """
28
+ if 90 < self.min_lat or self.min_lat < -90:
29
+ raise ValueError(f"Invalid latitude value: {self.min_lat}")
30
+ if 90 < self.max_lat or self.max_lat < -90:
31
+ raise ValueError(f"Invalid latitude value: {self.max_lat}")
32
+ if 180 < self.min_lon or self.min_lon < -180:
33
+ raise ValueError(f"Invalid longitude value: {self.min_lon}")
34
+ if 180 < self.max_lon or self.max_lon < -180:
35
+ raise ValueError(f"Invalid longitude value: {self.max_lon}")
36
+ if self.min_lat >= self.max_lat:
37
+ raise ValueError(f"min_lat must be less than max_lat: {self.min_lat} >= {self.max_lat}")
38
+ if self.min_lon >= self.max_lon:
39
+ raise ValueError(f"min_lon must be less than max_lon: {self.min_lon} >= {self.max_lon}")
40
+
41
+ @classmethod
42
+ def get_bbox_by_radius(cls, center: Location, radius: float) -> 'BBox':
43
+ """
44
+ Get a bounding box by a center and a radius.
45
+
46
+ Args:
47
+ center: The center of the bounding box in degrees (latitude, longitude)
48
+ radius: The radius of the bounding box in nautical miles
49
+
50
+ Returns:
51
+ A BBox object
52
+
53
+ Raises:
54
+ ValueError: If radius is negative or if latitude is at the poles
55
+ """
56
+ if radius < 0:
57
+ raise ValueError("Radius must be non-negative")
58
+
59
+ if abs(center.latitude) > 89.9:
60
+ raise ValueError("Cannot calculate bounding box near the poles")
61
+
62
+ latitude_in_degrees = radius / 60
63
+ longitude_in_degrees = radius / 60 / math.cos(math.radians(center.latitude))
64
+
65
+ longitude_in_degrees = min(longitude_in_degrees, 180)
66
+
67
+ return BBox(
68
+ min_lat=max(center.latitude - latitude_in_degrees, -90),
69
+ max_lat=min(center.latitude + latitude_in_degrees, 90),
70
+ min_lon=max(center.longitude - longitude_in_degrees, -180),
71
+ max_lon=min(center.longitude + longitude_in_degrees, 180)
72
+ )
73
+
74
+
75
+ class ResponseObject:
76
+ """
77
+ Base class for all response objects.
78
+ """
79
+ __annotations__: Dict[str, Any] = {}
80
+
81
+ def to_dict(self) -> Dict[str, Any]:
82
+ return asdict(self)
83
+
84
+ @classmethod
85
+ def from_dict(cls, data: Dict[str, Any]) -> 'ResponseObject':
86
+ defaults = {}
87
+ for field_name, field_type in cls.__annotations__.items():
88
+ if hasattr(field_type, "__origin__"):
89
+ if field_type.__origin__ is Union:
90
+ try:
91
+ defaults[field_name] = field_type.__args__[1]()
92
+ except Exception:
93
+ defaults[field_name] = None
94
+ elif field_type.__origin__ is Union:
95
+ defaults[field_name] = None
96
+ defaults.update(data)
97
+ return cls(**defaults)
98
+
99
+ def to_json(self) -> str:
100
+ return json.dumps(self.to_dict())
101
+
102
+ @classmethod
103
+ def from_json(cls, json_str: str) -> 'ResponseObject':
104
+ return cls.from_dict(json.loads(json_str))
105
+
106
+ @classmethod
107
+ def from_list(cls, data: List[Any]) -> 'ResponseObject':
108
+ return cls.from_dict(dict(zip_longest(cls.__annotations__.keys(), data)))
109
+
110
+
111
+ class BaseConfig(BaseSettings):
112
+ model_config = SettingsConfigDict(
113
+ env_file=".env",
114
+ env_file_encoding="utf-8",
115
+ env_nested_delimiter="_",
116
+ frozen=True,
117
+ extra="ignore",
118
+ case_sensitive=False
119
+ )
120
+
121
+
122
+ class BaseClient:
123
+ """
124
+ Base class for all API clients.
125
+ """
126
+ def __init__(self, config: Optional[BaseConfig] = None, **session_params: Dict[str, Any]):
127
+ """
128
+ Initialize the client.
129
+
130
+ Args:
131
+ config: The configuration to use for the client.
132
+ session_params: Additional parameters for the session.
133
+ """
134
+ self._config = config or BaseConfig()
135
+ self._session_params = session_params
136
+ self._session = aiohttp.ClientSession(**self._session_params)
137
+
138
+ async def close(self):
139
+ """
140
+ Close the client.
141
+ """
142
+ if self._session:
143
+ await self._session.close()
144
+ self._session = None
145
+
146
+ async def __aenter__(self) -> 'BaseClient':
147
+ """
148
+ Enter the context manager.
149
+ """
150
+ return self
151
+
152
+ async def __aexit__(self, exc_type, exc_val, exc_tb):
153
+ """
154
+ Exit the context manager.
155
+ """
156
+ _ = (exc_type, exc_val, exc_tb)
157
+ await self.close()
158
+
159
+ async def _handle_response(self, response: aiohttp.ClientResponse) -> Optional[Any]:
160
+ """
161
+ Handle the response from the API.
162
+
163
+ Args:
164
+ response: The response from the API.
165
+
166
+ Returns:
167
+ The response from the API. None if the response is 404.
168
+
169
+ Raises:
170
+ aiohttp.ClientError: If the response is not successful.
171
+ """
172
+ if response.status == 404:
173
+ return None
174
+
175
+ response.raise_for_status()
176
+ return await response.json() or None