diff --git a/location/__init__.py b/location/__init__.py index d28ada2..f521011 100644 --- a/location/__init__.py +++ b/location/__init__.py @@ -1,7 +1,66 @@ +from typing import NamedTuple, Iterator, List, Iterable +from datetime import datetime import logging +import csv +import geopy.distance # type: ignore def get_logger(): return logging.getLogger("location") +PATH = "/L/data/location/location.csv" +CACHE_PATH = "/L/.cache/location.cache" # TODO need to cache? +# TODO tag?? + +Tag = str + +class Location(NamedTuple): + dt: datetime + lat: float + lon: float + tag: Tag + + +def tagger(dt: datetime, lat: float, lon: float) -> Tag: + TAGS = [ + # removed + ] + for coord, dist, tag in TAGS: + if geopy.distance.distance(coord, (lat, lon)).m < dist: + return tag + else: + return "other" + +def iter_locations() -> Iterator[Location]: + with open(PATH) as fo: + reader = csv.reader(fo) + next(reader) # skip header + for ll in reader: + [ts, lats, lons] = ll + # TODO hmm, is it local?? + dt = datetime.strptime(ts, "%Y-%m-%d %H:%M:%S") + lat = float(lats) + lon = float(lons) + tag = tagger(dt, lat, lon) + yield Location( + dt=dt, + lat=lat, + lon=lon, + tag=tag + ) + +def get_locations(cached: bool=False) -> Iterable[Location]: + import dill # type: ignore + if cached: + with open(CACHE_PATH, 'rb') as fo: + preph = dill.load(fo) + return [Location(**p._asdict()) for p in preph] # meh. but otherwise it's not serialising methods... + else: + return list(iter_locations()) + +def update_cache(): + import dill # type: ignore + datas = get_locations(cached=False) + with open(CACHE_PATH, 'wb') as fo: + dill.dump(datas, fo) diff --git a/location/__main__.py b/location/__main__.py index e4da5b9..10a27dc 100644 --- a/location/__main__.py +++ b/location/__main__.py @@ -1,4 +1,4 @@ -from location import get_logger +from location import get_logger, get_locations, iter_locations logger = get_logger() @@ -6,5 +6,18 @@ from kython.logging import setup_logzero setup_logzero(logger) +import sys - +if len(sys.argv) > 1: + cmd = sys.argv[1] + if cmd == "update_cache": + from location import update_cache, get_locations + update_cache() + get_locations(cached=True) + else: + raise RuntimeError(f"Unknown command {cmd}") +else: + for p in iter_locations(): + pass + # TODO need datetime! + # print(p) diff --git a/update_cache b/update_cache index 6daf62c..3938289 100755 --- a/update_cache +++ b/update_cache @@ -3,5 +3,5 @@ set -eu cd "$(dirname "$0")" -python3 -m photos update_cache +python3 -m location update_cache