PhotosAPI/modules/exif_reader.py

50 lines
1.2 KiB
Python
Raw Permalink Normal View History

2023-06-23 13:17:01 +03:00
import contextlib
2023-08-14 14:44:07 +03:00
from pathlib import Path
from typing import Mapping, Union
2023-06-23 13:17:01 +03:00
2023-01-02 14:10:10 +02:00
from exif import Image
2023-03-12 15:59:13 +02:00
2023-01-02 14:10:10 +02:00
def decimal_coords(coords: float, ref: str) -> float:
"""Get latitude/longitude from coord and direction reference
### Args:
* coords (`float`): _description_
* ref (`str`): _description_
### Returns:
* float: Decimal degrees
2023-03-12 15:59:13 +02:00
"""
2023-01-02 14:10:10 +02:00
decimal_degrees = coords[0] + coords[1] / 60 + coords[2] / 3600
2023-06-23 13:17:01 +03:00
if ref in {"S", "W"}:
2023-01-02 14:10:10 +02:00
decimal_degrees = -decimal_degrees
2023-06-23 13:17:01 +03:00
2023-01-02 16:08:46 +02:00
return round(decimal_degrees, 5)
2023-01-02 14:10:10 +02:00
2023-03-12 15:59:13 +02:00
2023-08-14 14:44:07 +03:00
def extract_location(filepath: Union[str, Path]) -> Mapping[str, float]:
2023-01-02 14:10:10 +02:00
"""Get location data from image
### Args:
* filepath (`str`): Path to file location
### Returns:
2023-01-02 16:08:46 +02:00
* dict: `{ "lng": float, "lat": float, "alt": float }`
2023-03-12 15:59:13 +02:00
"""
2023-01-02 14:10:10 +02:00
2023-03-12 15:59:13 +02:00
output = {"lng": 0.0, "lat": 0.0, "alt": 0.0}
2023-01-02 14:10:10 +02:00
2023-03-12 15:59:13 +02:00
with open(filepath, "rb") as src:
2023-01-02 14:10:10 +02:00
img = Image(src)
if img.has_exif is False:
return output
2023-06-23 13:17:01 +03:00
with contextlib.suppress(AttributeError):
2023-01-02 16:08:46 +02:00
output["lng"] = decimal_coords(img.gps_longitude, img.gps_longitude_ref)
output["lat"] = decimal_coords(img.gps_latitude, img.gps_latitude_ref)
output["alt"] = img.gps_altitude
2023-01-02 14:10:10 +02:00
2023-03-12 15:59:13 +02:00
return output