PhotosAPI/modules/exif_reader.py

50 lines
1.2 KiB
Python

import contextlib
from pathlib import Path
from typing import Mapping, Union
from exif import Image
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
"""
decimal_degrees = coords[0] + coords[1] / 60 + coords[2] / 3600
if ref in {"S", "W"}:
decimal_degrees = -decimal_degrees
return round(decimal_degrees, 5)
def extract_location(filepath: Union[str, Path]) -> Mapping[str, float]:
"""Get location data from image
### Args:
* filepath (`str`): Path to file location
### Returns:
* dict: `{ "lng": float, "lat": float, "alt": float }`
"""
output = {"lng": 0.0, "lat": 0.0, "alt": 0.0}
with open(filepath, "rb") as src:
img = Image(src)
if img.has_exif is False:
return output
with contextlib.suppress(AttributeError):
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
return output