From 105928238f9cd250db215092f1710827b97bb03e Mon Sep 17 00:00:00 2001 From: karlicoss Date: Tue, 31 Oct 2023 00:47:31 +0000 Subject: [PATCH 001/122] vk_messages_backup: some cleanup + switch to get_files --- my/vk/vk_messages_backup.py | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/my/vk/vk_messages_backup.py b/my/vk/vk_messages_backup.py index 1837385..c73587f 100644 --- a/my/vk/vk_messages_backup.py +++ b/my/vk/vk_messages_backup.py @@ -2,8 +2,8 @@ VK data (exported by [[https://github.com/Totktonada/vk_messages_backup][Totktonada/vk_messages_backup]]) ''' # note: could reuse the original repo, but little point I guess since VK closed their API -from datetime import datetime from dataclasses import dataclass +from datetime import datetime import json from typing import Dict, Iterator @@ -22,6 +22,7 @@ TZ = pytz.timezone('Europe/Moscow') Uid = int + @dataclass(frozen=True) class User: id: Uid @@ -45,8 +46,10 @@ class Message: Users = Dict[Uid, User] + + def users() -> Users: - files = list(sorted(config.storage_path.glob('user_*.json'))) + files = get_files(config.storage_path, glob='user_*.json') res = {} for f in files: j = json.loads(f.read_text()) @@ -60,6 +63,8 @@ def users() -> Users: GROUP_CHAT_MIN_ID = 2000000000 + + def _parse_chat(*, msg: Json, udict: Users) -> Chat: # exported with newer api, peer_id is a proper identifier both for users and chats peer_id = msg.get('peer_id') @@ -88,13 +93,13 @@ def _parse_chat(*, msg: Json, udict: Users) -> Chat: def _parse_msg(*, msg: Json, chat: Chat, udict: Users) -> Message: mid = msg['id'] - md = msg['date'] + md = msg['date'] dt = datetime.fromtimestamp(md, tz=TZ) # todo attachments? e.g. url could be an attachment # todo might be forwarded? - mb = msg.get('body') + mb = msg.get('body') if mb is None: mb = msg.get('text') assert mb is not None, msg @@ -103,7 +108,7 @@ def _parse_msg(*, msg: Json, chat: Chat, udict: Users) -> Message: if out: user = udict[config.user_id] else: - mu = msg.get('user_id') or msg.get('from_id') + mu = msg.get('user_id') or msg.get('from_id') assert mu is not None, msg user = udict[mu] return Message( @@ -118,8 +123,7 @@ def _parse_msg(*, msg: Json, chat: Chat, udict: Users) -> Message: def _messages() -> Iterator[Res[Message]]: udict = users() - uchats = list(sorted(config.storage_path.glob('userchat_*.json' ))) + \ - list(sorted(config.storage_path.glob('groupchat_*.json'))) + uchats = get_files(config.storage_path, glob='userchat_*.json') + get_files(config.storage_path, glob='groupchat_*.json') for f in uchats: j = json.loads(f.read_text()) # ugh. very annoying, sometimes not possible to extract title from last message From 7631f1f2e498e8a1829c02e3543bb8dd88770ffd Mon Sep 17 00:00:00 2001 From: karlicoss Date: Thu, 2 Nov 2023 00:27:09 +0000 Subject: [PATCH 002/122] monzo.monzoexport: initial module --- my/config.py | 5 +++++ my/monzo/monzoexport.py | 45 +++++++++++++++++++++++++++++++++++++++++ tox.ini | 1 + 3 files changed, 51 insertions(+) create mode 100644 my/monzo/monzoexport.py diff --git a/my/config.py b/my/config.py index 9cc9c11..ac44f41 100644 --- a/my/config.py +++ b/my/config.py @@ -269,3 +269,8 @@ class whatsapp: class harmonic: export_path: Paths + + +class monzo: + class monzoexport: + export_path: Paths diff --git a/my/monzo/monzoexport.py b/my/monzo/monzoexport.py new file mode 100644 index 0000000..3aa0cf5 --- /dev/null +++ b/my/monzo/monzoexport.py @@ -0,0 +1,45 @@ +""" +Monzo transactions data (using https://github.com/karlicoss/monzoexport ) +""" +REQUIRES = [ + 'git+https://github.com/karlicoss/monzoexport', +] + +from dataclasses import dataclass +from pathlib import Path +from typing import Sequence, Iterator + +from my.core import ( + Paths, + get_files, + make_logger, +) +import my.config + + +@dataclass +class config(my.config.monzo.monzoexport): + ''' + Uses [[https://github.com/karlicoss/monzoexport][ghexport]] outputs. + ''' + + export_path: Paths + '''path[s]/glob to the exported JSON data''' + + +logger = make_logger(__name__) + + +def inputs() -> Sequence[Path]: + return get_files(config.export_path) + + +import monzoexport.dal as dal + + +def _dal() -> dal.DAL: + return dal.DAL(inputs()) + + +def transactions() -> Iterator[dal.MonzoTransaction]: + return _dal().transactions() diff --git a/tox.ini b/tox.ini index ac0a68d..dad6d9b 100644 --- a/tox.ini +++ b/tox.ini @@ -153,6 +153,7 @@ commands = my.ip.all \ my.kobo \ my.location.gpslogger \ + my.monzo.monzoexport \ my.orgmode \ my.pdfs \ my.pinboard \ From 5630621ec1be12144f6779f02984a79eacd90d24 Mon Sep 17 00:00:00 2001 From: karlicoss Date: Mon, 6 Nov 2023 22:25:00 +0000 Subject: [PATCH 003/122] my.pinboard: some cleanup --- my/pinboard.py | 26 +++++++++++++++++++------- 1 file changed, 19 insertions(+), 7 deletions(-) diff --git a/my/pinboard.py b/my/pinboard.py index 354f15c..ef4ca36 100644 --- a/my/pinboard.py +++ b/my/pinboard.py @@ -5,22 +5,34 @@ REQUIRES = [ 'git+https://github.com/karlicoss/pinbexport', ] -from my.config import pinboard as config +from dataclasses import dataclass +from pathlib import Path +from typing import Iterator, Sequence +from my.core import get_files, Paths, Res +import my.config import pinbexport.dal as pinbexport + +@dataclass +class config(my.config.pinboard): # TODO rename to pinboard.pinbexport? + # TODO rename to export_path? + export_dir: Paths + + +# TODO not sure if should keep this import here? Bookmark = pinbexport.Bookmark +def inputs() -> Sequence[Path]: + return get_files(config.export_dir) + + # yep; clearly looks that the purpose of my. package is to wire files to DAL implicitly; otherwise it's just passtrhough. def dal() -> pinbexport.DAL: - from .core import get_files - inputs = get_files(config.export_dir) # todo rename to export_path - model = pinbexport.DAL(inputs) - return model + return pinbexport.DAL(inputs()) -from typing import Iterable -def bookmarks() -> Iterable[pinbexport.Bookmark]: +def bookmarks() -> Iterator[Res[pinbexport.Bookmark]]: return dal().bookmarks() From 4ac3bbb101973135c81bc84a9d40282081034851 Mon Sep 17 00:00:00 2001 From: karlicoss Date: Mon, 6 Nov 2023 23:31:56 +0000 Subject: [PATCH 004/122] my.bumble.android: fix message deduplication --- my/bumble/android.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/my/bumble/android.py b/my/bumble/android.py index 86c9d1e..3a159da 100644 --- a/my/bumble/android.py +++ b/my/bumble/android.py @@ -106,10 +106,11 @@ def _handle_db(db: sqlite3.Connection) -> Iterator[EntitiesRes]: def _key(r: EntitiesRes): if isinstance(r, _Message): - if '&srv_width=' in r.text: + if '/hidden?' in r.text: # ugh. seems that image URLs change all the time in the db? # can't access them without login anyway # so use a different key for such messages + # todo maybe normalize text instead? since it's gonna always trigger diffs down the line return (r.id, r.created) return r From 19353e996d2d757bf43126c4149abdc7be482681 Mon Sep 17 00:00:00 2001 From: karlicoss Date: Mon, 6 Nov 2023 23:42:22 +0000 Subject: [PATCH 005/122] my.hackernews.harmonic: use orjson + add __hash__ for Saved object plus some minor cleanup --- my/hackernews/harmonic.py | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/my/hackernews/harmonic.py b/my/hackernews/harmonic.py index 6070510..3b4ae61 100644 --- a/my/hackernews/harmonic.py +++ b/my/hackernews/harmonic.py @@ -1,16 +1,16 @@ """ [[https://play.google.com/store/apps/details?id=com.simon.harmonichackernews][Harmonic]] app for Hackernews """ -REQUIRES = ['lxml'] +REQUIRES = ['lxml', 'orjson'] from dataclasses import dataclass from datetime import datetime, timezone -import json +import orjson from pathlib import Path from typing import Any, Dict, Iterator, List, Optional, Sequence, TypedDict, cast from lxml import etree -from more_itertools import unique_everseen, one +from more_itertools import one from my.core import ( Paths, @@ -21,15 +21,16 @@ from my.core import ( make_logger, stat, ) +from my.core.common import unique_everseen +import my.config from .common import hackernews_link, SavedBase -from my.config import harmonic as user_config logger = make_logger(__name__) @dataclass -class harmonic(user_config): +class harmonic(my.config.harmonic): export_path: Paths @@ -76,6 +77,10 @@ class Saved(SavedBase): def hackernews_link(self) -> str: return hackernews_link(self.uid) + def __hash__(self) -> int: + # meh. but seems like the easiest and fastest way to hash a dict? + return hash(orjson.dumps(self.raw)) + _PREFIX = 'com.simon.harmonichackernews.KEY_SHARED_PREFERENCES' @@ -95,7 +100,7 @@ def _saved() -> Iterator[Res[Saved]]: cached: Dict[str, Cached] = {} for sid in cached_ids: res = one(cast(List[Any], tr.xpath(f'//*[@name="{_PREFIX}_CACHED_STORY{sid}"]'))) - j = json.loads(res.text) + j = orjson.loads(res.text) cached[sid] = j res = one(cast(List[Any], tr.xpath(f'//*[@name="{_PREFIX}_BOOKMARKS"]'))) @@ -112,7 +117,7 @@ def _saved() -> Iterator[Res[Saved]]: def saved() -> Iterator[Res[Saved]]: - yield from unique_everseen(_saved()) + yield from unique_everseen(_saved) def stats() -> Stats: From 33f8d867e23e3459035196be328a6768c126d609 Mon Sep 17 00:00:00 2001 From: karlicoss Date: Tue, 7 Nov 2023 21:07:32 +0000 Subject: [PATCH 006/122] my.browser.export: cleanup - make logging INFO (default) -- otherwise it's too quiet during processing lots of databases - can pass inputs cachew directly now --- my/browser/export.py | 38 ++++++++++++++++++-------------------- 1 file changed, 18 insertions(+), 20 deletions(-) diff --git a/my/browser/export.py b/my/browser/export.py index 46a4217..ce5a6de 100644 --- a/my/browser/export.py +++ b/my/browser/export.py @@ -4,20 +4,18 @@ Parses browser history using [[http://github.com/seanbreckenridge/browserexport] REQUIRES = ["browserexport"] -from my.config import browser as user_config -from my.core import Paths, dataclass - - -@dataclass -class config(user_config.export): - # path[s]/glob to your backed up browser history sqlite files - export_path: Paths - - +from dataclasses import dataclass from pathlib import Path -from typing import Iterator, Sequence, List +from typing import Iterator, Sequence -from my.core import Stats, get_files, LazyLogger +import my.config +from my.core import ( + Paths, + Stats, + get_files, + make_logger, + stat, +) from my.core.common import mcachew from browserexport.merge import read_and_merge, Visit @@ -25,7 +23,13 @@ from browserexport.merge import read_and_merge, Visit from .common import _patch_browserexport_logs -logger = LazyLogger(__name__, level="warning") +@dataclass +class config(my.config.browser.export): + # path[s]/glob to your backed up browser history sqlite files + export_path: Paths + + +logger = make_logger(__name__) _patch_browserexport_logs(logger.level) @@ -34,16 +38,10 @@ def inputs() -> Sequence[Path]: return get_files(config.export_path) -def _cachew_depends_on() -> List[str]: - return [str(f) for f in inputs()] - - -@mcachew(depends_on=_cachew_depends_on, logger=logger) +@mcachew(depends_on=inputs, logger=logger) def history() -> Iterator[Visit]: yield from read_and_merge(inputs()) def stats() -> Stats: - from my.core import stat - return {**stat(history)} From e547acfa5907bbd53dd72604f5f6a7b70cf33946 Mon Sep 17 00:00:00 2001 From: karlicoss Date: Tue, 7 Nov 2023 21:09:48 +0000 Subject: [PATCH 007/122] general: update minimal cachew version had quite a few useful fixes/performance optimizations since --- setup.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/setup.py b/setup.py index 42ffeaa..b857662 100644 --- a/setup.py +++ b/setup.py @@ -59,7 +59,7 @@ def main() -> None: # todo document these? 'orjson', # for my.core.serialize 'pyfzf_iter', # for my.core.denylist - 'cachew>=0.8.0', + 'cachew>=0.15.20231019 ', 'mypy', # used for config checks 'colorlog', # for colored logs 'enlighten', # for CLI progress bars From ac5f71c68b91462180cf78e8f454b502052b2cc9 Mon Sep 17 00:00:00 2001 From: karlicoss Date: Fri, 10 Nov 2023 01:59:21 +0000 Subject: [PATCH 008/122] my.jawbone: get rid of matplotlib import on top level --- my/jawbone/__init__.py | 15 +++++++++------ tox.ini | 1 - 2 files changed, 9 insertions(+), 7 deletions(-) diff --git a/my/jawbone/__init__.py b/my/jawbone/__init__.py index 4b41242..7f4d6bd 100644 --- a/my/jawbone/__init__.py +++ b/my/jawbone/__init__.py @@ -1,3 +1,5 @@ +from __future__ import annotations + from typing import Dict, Any, List, Iterable import json from functools import lru_cache @@ -155,9 +157,6 @@ def stats(): #### NOTE: most of the stuff below is deprecated and remnants of my old code! #### sorry for it, feel free to remove if you don't need it -import matplotlib.pyplot as plt # type: ignore -from matplotlib.figure import Figure # type: ignore -from matplotlib.axes import Axes # type: ignore def hhmm(time: datetime): return time.strftime("%H:%M") @@ -168,9 +167,10 @@ def hhmm(time: datetime): # fromstart = time - sleep.created # return fromstart / tick -import matplotlib.dates as mdates # type: ignore -def plot_one(sleep: SleepEntry, fig: Figure, axes: Axes, xlims=None, showtext=True): +def plot_one(sleep: SleepEntry, fig, axes, xlims=None, showtext=True): + import matplotlib.dates as mdates # type: ignore[import-not-found] + span = sleep.completed - sleep.created print(f"{sleep.xid} span: {span}") @@ -253,7 +253,10 @@ def predicate(sleep: SleepEntry): # TODO move to dashboard -def plot(): +def plot() -> None: + from matplotlib.figure import Figure # type: ignore[import-not-found] + import matplotlib.pyplot as plt # type: ignore[import-not-found] + # TODO FIXME melatonin data melatonin_data = {} # type: ignore[var-annotated] diff --git a/tox.ini b/tox.ini index dad6d9b..0de357f 100644 --- a/tox.ini +++ b/tox.ini @@ -171,7 +171,6 @@ commands = -p {[testenv]package_name} \ --exclude 'my/coding/codeforces.py' \ --exclude 'my/coding/topcoder.py' \ - --exclude 'my/jawbone/.*' \ --txt-report .coverage.mypy-misc \ --html-report .coverage.mypy-misc \ {posargs} From 65c617ed94e39cd3d12d58c5d6b35f894f41f892 Mon Sep 17 00:00:00 2001 From: karlicoss Date: Fri, 10 Nov 2023 02:00:37 +0000 Subject: [PATCH 009/122] my.emfit: add missing properties to fake data generator --- my/emfit/__init__.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/my/emfit/__init__.py b/my/emfit/__init__.py index 1ec3341..30b693c 100644 --- a/my/emfit/__init__.py +++ b/my/emfit/__init__.py @@ -170,6 +170,8 @@ def fake_data(nights: int = 500) -> Iterator: from my.core.cfg import tmp_config from tempfile import TemporaryDirectory + import pytz + with TemporaryDirectory() as td: tdir = Path(td) gen = dal.FakeData() @@ -178,6 +180,8 @@ def fake_data(nights: int = 500) -> Iterator: class override: class emfit: export_path = tdir + excluded_sids = () + timezone = pytz.timezone('Europe/London') # meh with tmp_config(modules=__name__, config=override) as cfg: yield cfg From 70bb9ed0c5e5aa3e4996c61880af1a5328a66017 Mon Sep 17 00:00:00 2001 From: karlicoss Date: Fri, 10 Nov 2023 02:03:20 +0000 Subject: [PATCH 010/122] location.google_takeout_semantic: handle None visitConfidence --- my/location/google_takeout_semantic.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/my/location/google_takeout_semantic.py b/my/location/google_takeout_semantic.py index fcf7f01..b4f16db 100644 --- a/my/location/google_takeout_semantic.py +++ b/my/location/google_takeout_semantic.py @@ -54,8 +54,9 @@ def locations() -> Iterator[Res[Location]]: for g in events(): if isinstance(g, SemanticLocation): - if g.visitConfidence < require_confidence: - logger.debug(f"Skipping {g} due to low confidence ({g.visitConfidence}))") + visitConfidence = g.visitConfidence + if visitConfidence is None or visitConfidence < require_confidence: + logger.debug(f"Skipping {g} due to low confidence ({visitConfidence}))") continue yield Location( lon=g.lng, From 996169aa295775f45d4828f9a1893840091a24ae Mon Sep 17 00:00:00 2001 From: karlicoss Date: Fri, 10 Nov 2023 22:09:48 +0000 Subject: [PATCH 011/122] time.tz.via_location: more consistent behaviour wrt caching previously it was possible to cachew never properly initialize the cache because if you only queried some dates in the past because we never made it to the end of _iter_tzs also some minor cleanup --- my/time/tz/via_location.py | 160 ++++++++++++++++++------------------- 1 file changed, 79 insertions(+), 81 deletions(-) diff --git a/my/time/tz/via_location.py b/my/time/tz/via_location.py index 1ed1ba7..612341a 100644 --- a/my/time/tz/via_location.py +++ b/my/time/tz/via_location.py @@ -6,6 +6,24 @@ REQUIRES = [ 'timezonefinder', ] +from collections import Counter +from dataclasses import dataclass +from datetime import date, datetime +from functools import lru_cache +import heapq +from itertools import groupby +import os +from typing import Iterator, Optional, Tuple, Any, List, Iterable, Set, Dict + +import pytz + +from my.core import make_logger, stat, Stats, datetime_aware +from my.core.common import mcachew +from my.core.source import import_source +from my.core.warnings import high + +from my.location.common import LatLon + ## user might not have tz config section, so makes sense to be more defensive about it # todo might be useful to extract a helper for this @@ -27,8 +45,6 @@ if 'user_config' not in globals(): ## -from my.core import dataclass - @dataclass class config(user_config): # less precise, but faster @@ -46,55 +62,33 @@ class config(user_config): _iter_tz_refresh_time: int = 6 -from collections import Counter -from datetime import date, datetime -from functools import lru_cache -from itertools import groupby -from typing import Iterator, NamedTuple, Optional, Tuple, Any, List, Iterable, Set +logger = make_logger(__name__) -import heapq -import pytz -from more_itertools import seekable -from my.core.common import LazyLogger, mcachew, tzdatetime -from my.core.source import import_source - -logger = LazyLogger(__name__, level='warning') - -@lru_cache(2) +@lru_cache(None) def _timezone_finder(fast: bool) -> Any: if fast: # less precise, but faster from timezonefinder import TimezoneFinderL as Finder else: - from timezonefinder import TimezoneFinder as Finder # type: ignore + from timezonefinder import TimezoneFinder as Finder # type: ignore return Finder(in_memory=True) -# todo move to common? -Zone = str - - -# NOTE: for now only daily resolution is supported... later will implement something more efficient -class DayWithZone(NamedTuple): - day: date - zone: Zone - - -from my.location.common import LatLon - # for backwards compatibility -def _locations() -> Iterator[Tuple[LatLon, datetime]]: +def _locations() -> Iterator[Tuple[LatLon, datetime_aware]]: try: import my.location.all + for loc in my.location.all.locations(): if loc.accuracy is not None and loc.accuracy > config.require_accuracy: continue yield ((loc.lat, loc.lon), loc.dt) except Exception as e: - from my.core.warnings import high - logger.exception("Could not setup via_location using my.location.all provider, falling back to legacy google implementation", exc_info=e) + logger.exception( + "Could not setup via_location using my.location.all provider, falling back to legacy google implementation", exc_info=e + ) high("Setup my.google.takeout.parser, then my.location.all for better google takeout/location data") import my.location.google @@ -102,10 +96,22 @@ def _locations() -> Iterator[Tuple[LatLon, datetime]]: for gloc in my.location.google.locations(): yield ((gloc.lat, gloc.lon), gloc.dt) + # TODO: could use heapmerge or sort the underlying iterators somehow? # see https://github.com/karlicoss/HPI/pull/237#discussion_r858372934 -def _sorted_locations() -> List[Tuple[LatLon, datetime]]: - return list(sorted(_locations(), key=lambda x: x[1])) +def _sorted_locations() -> List[Tuple[LatLon, datetime_aware]]: + return sorted(_locations(), key=lambda x: x[1]) + + +# todo move to common? +Zone = str + + +# NOTE: for now only daily resolution is supported... later will implement something more efficient +@dataclass(unsafe_hash=True) +class DayWithZone: + day: date + zone: Zone def _find_tz_for_locs(finder: Any, locs: Iterable[Tuple[LatLon, datetime]]) -> Iterator[DayWithZone]: @@ -120,20 +126,22 @@ def _find_tz_for_locs(finder: Any, locs: Iterable[Tuple[LatLon, datetime]]) -> I # TODO this is probably a bit expensive... test & benchmark ldt = dt.astimezone(tz) ndate = ldt.date() - #if pdt is not None and ndate < pdt.date(): + # if pdt is not None and ndate < pdt.date(): # # TODO for now just drop and collect the stats # # I guess we'd have minor drops while air travel... # warnings.append("local time goes backwards {ldt} ({tz}) < {pdt}") # continue - #pdt = ldt - z = tz.zone; assert z is not None + # pdt = ldt + z = tz.zone + assert z is not None yield DayWithZone(day=ndate, zone=z) + # Note: this takes a while, as the upstream since _locations isn't sorted, so this # has to do an iterative sort of the entire my.locations.all list def _iter_local_dates() -> Iterator[DayWithZone]: - finder = _timezone_finder(fast=config.fast) # rely on the default - #pdt = None + finder = _timezone_finder(fast=config.fast) # rely on the default + # pdt = None # TODO: warnings doesn't actually warn? # warnings = [] @@ -157,7 +165,7 @@ def _iter_local_dates_fallback() -> Iterator[DayWithZone]: yield from _find_tz_for_locs(_timezone_finder(fast=config.fast), _fallback_locations()) -def most_common(lst: List[DayWithZone]) -> DayWithZone: +def most_common(lst: Iterator[DayWithZone]) -> DayWithZone: res, _ = Counter(lst).most_common(1)[0] return res @@ -181,59 +189,49 @@ def _iter_tz_depends_on() -> str: # refresh _iter_tzs every few hours -- don't think a better depends_on is possible dynamically -@mcachew(logger=logger, depends_on=_iter_tz_depends_on) +@mcachew(depends_on=_iter_tz_depends_on) def _iter_tzs() -> Iterator[DayWithZone]: # since we have no control over what order the locations are returned, # we need to sort them first before we can do a groupby - local_dates: List[DayWithZone] = list(_iter_local_dates()) - local_dates.sort(key=lambda p: p.day) + by_day = lambda p: p.day + + local_dates: List[DayWithZone] = sorted(_iter_local_dates(), key=by_day) logger.debug(f"no. of items using exact locations: {len(local_dates)}") - local_dates_fallback: List[DayWithZone] = list(_iter_local_dates_fallback()) - local_dates_fallback.sort(key=lambda p: p.day) + local_dates_fallback: List[DayWithZone] = sorted(_iter_local_dates_fallback(), key=by_day) # find days that are in fallback but not in local_dates (i.e., missing days) - local_dates_set: Set[date] = set(d.day for d in local_dates) + local_dates_set: Set[date] = {d.day for d in local_dates} use_fallback_days: List[DayWithZone] = [d for d in local_dates_fallback if d.day not in local_dates_set] logger.debug(f"no. of items being used from fallback locations: {len(use_fallback_days)}") # combine local_dates and missing days from fallback into a sorted list - all_dates = heapq.merge(local_dates, use_fallback_days, key=lambda p: p.day) + all_dates = heapq.merge(local_dates, use_fallback_days, key=by_day) + # todo could probably use heapify here instead of heapq.merge? - for d, gr in groupby(all_dates, key=lambda p: p.day): - logger.info(f"processed {d}{', using fallback' if d in local_dates_set else ''}") - zone = most_common(list(gr)).zone + for d, gr in groupby(all_dates, key=by_day): + logger.debug(f"processed {d}{', using fallback' if d in local_dates_set else ''}") + zone = most_common(gr).zone yield DayWithZone(day=d, zone=zone) @lru_cache(1) -def loc_tz_getter() -> Iterator[DayWithZone]: - # seekable makes it cache the emitted values - return seekable(_iter_tzs()) +def _day2zone() -> Dict[date, pytz.BaseTzInfo]: + # NOTE: kinda unfortunate that this will have to process all days before returning result for just one + # however otherwise cachew cache might never be initialized properly + # so we'll always end up recomputing everyting during subsequent runs + return {dz.day: pytz.timezone(dz.zone) for dz in _iter_tzs()} -# todo expose zone names too? -@lru_cache(maxsize=None) def _get_day_tz(d: date) -> Optional[pytz.BaseTzInfo]: - sit = loc_tz_getter() - # todo hmm. seeking is not super efficient... might need to use some smarter dict-based cache - # hopefully, this method itself caches stuff forthe users, so won't be too bad - sit.seek(0) # type: ignore - - zone: Optional[str] = None - for x, tz in sit: - if x == d: - zone = tz - if x >= d: - break - return None if zone is None else pytz.timezone(zone) + return _day2zone().get(d) # ok to cache, there are only a few home locations? -@lru_cache(maxsize=None) +@lru_cache(None) def _get_home_tz(loc: LatLon) -> Optional[pytz.BaseTzInfo]: (lat, lng) = loc - finder = _timezone_finder(fast=False) # ok to use slow here for better precision + finder = _timezone_finder(fast=False) # ok to use slow here for better precision zone = finder.timezone_at(lat=lat, lng=lng) if zone is None: # TODO shouldn't really happen, warn? @@ -242,7 +240,7 @@ def _get_home_tz(loc: LatLon) -> Optional[pytz.BaseTzInfo]: return pytz.timezone(zone) -def _get_tz(dt: datetime) -> Optional[pytz.BaseTzInfo]: +def get_tz(dt: datetime) -> Optional[pytz.BaseTzInfo]: ''' Given a datetime, returns the timezone for that date. ''' @@ -258,16 +256,14 @@ def _get_tz(dt: datetime) -> Optional[pytz.BaseTzInfo]: # that datetime is between, else fallback on your first home location, so it acts # as a last resort from my.location.fallback import via_home as home + loc = list(home.estimate_location(dt)) assert len(loc) == 1, f"should only have one home location, received {loc}" return _get_home_tz(loc=(loc[0].lat, loc[0].lon)) -# expose as 'public' function -get_tz = _get_tz - -def localize(dt: datetime) -> tzdatetime: - tz = _get_tz(dt) +def localize(dt: datetime) -> datetime_aware: + tz = get_tz(dt) if tz is None: # TODO -- this shouldn't really happen.. think about it carefully later return dt @@ -275,20 +271,17 @@ def localize(dt: datetime) -> tzdatetime: return tz.localize(dt) -from ...core import stat, Stats -def stats(quick: bool=False) -> Stats: +def stats(quick: bool = False) -> Stats: if quick: prev, config.sort_locations = config.sort_locations, False - res = { - 'first': next(_iter_local_dates()) - } + res = {'first': next(_iter_local_dates())} config.sort_locations = prev return res # TODO not sure what would be a good stat() for this module... # might be nice to print some actual timezones? # there aren't really any great iterables to expose - import os VIA_LOCATION_START_YEAR = int(os.environ.get("VIA_LOCATION_START_YEAR", 1990)) + def localized_years(): last = datetime.now().year + 2 # note: deliberately take + 2 years, so the iterator exhausts. otherwise stuff might never get cached @@ -296,4 +289,9 @@ def stats(quick: bool=False) -> Stats: for Y in range(VIA_LOCATION_START_YEAR, last): dt = datetime.fromisoformat(f'{Y}-01-01 01:01:01') yield localize(dt) + return stat(localized_years) + + +# deprecated -- still used in some other modules so need to keep +_get_tz = get_tz From 657ce08ac85b49711464accebc07b230619d9f8a Mon Sep 17 00:00:00 2001 From: karlicoss Date: Fri, 10 Nov 2023 22:28:28 +0000 Subject: [PATCH 012/122] fix mypy issues after mypy/libraries updates --- my/core/_deprecated/kompress.py | 8 ++++---- my/core/cachew.py | 2 +- my/core/preinit.py | 2 +- my/core/query.py | 2 +- my/core/query_range.py | 2 +- my/instagram/common.py | 2 +- 6 files changed, 9 insertions(+), 9 deletions(-) diff --git a/my/core/_deprecated/kompress.py b/my/core/_deprecated/kompress.py index cd1bd9d..25b8a20 100644 --- a/my/core/_deprecated/kompress.py +++ b/my/core/_deprecated/kompress.py @@ -162,7 +162,7 @@ class ZipPath(zipfile_Path): # NOTE: is_dir/is_file might not behave as expected, the base class checks it only based on the slash in path # seems that root/at are not exposed in the docs, so might be an implementation detail - root: zipfile.ZipFile + root: zipfile.ZipFile # type: ignore[assignment] at: str @property @@ -191,14 +191,14 @@ class ZipPath(zipfile_Path): # note: seems that zip always uses forward slash, regardless OS? return zipfile_Path(self.root, self.at + '/') - def rglob(self, glob: str) -> Sequence[ZipPath]: + def rglob(self, glob: str) -> Iterator[ZipPath]: # note: not 100% sure about the correctness, but seem fine? # Path.match() matches from the right, so need to rpaths = [p for p in self.root.namelist() if p.startswith(self.at)] rpaths = [p for p in rpaths if Path(p).match(glob)] - return [ZipPath(self.root, p) for p in rpaths] + return (ZipPath(self.root, p) for p in rpaths) - def relative_to(self, other: ZipPath) -> Path: + def relative_to(self, other: ZipPath) -> Path: # type: ignore[override, unused-ignore] assert self.filepath == other.filepath, (self.filepath, other.filepath) return self.subpath.relative_to(other.subpath) diff --git a/my/core/cachew.py b/my/core/cachew.py index 7dd62d2..cc5a95b 100644 --- a/my/core/cachew.py +++ b/my/core/cachew.py @@ -7,7 +7,7 @@ import sys from typing import Optional, Iterator, cast, TYPE_CHECKING, TypeVar, Callable, overload, Union, Any, Type import warnings -import appdirs +import appdirs # type: ignore[import-untyped] PathIsh = Union[str, Path] # avoid circular import from .common diff --git a/my/core/preinit.py b/my/core/preinit.py index 88bcb27..8c0f6a4 100644 --- a/my/core/preinit.py +++ b/my/core/preinit.py @@ -4,7 +4,7 @@ from pathlib import Path # - it's imported from my.core.init (so we wan't to keep this file as small/reliable as possible, hence not common or something) # - we still need this function in __main__, so has to be separate from my/core/init.py def get_mycfg_dir() -> Path: - import appdirs + import appdirs # type: ignore[import-untyped] import os # not sure if that's necessary, i.e. could rely on PYTHONPATH instead # on the other hand, by using MY_CONFIG we are guaranteed to load it from the desired path? diff --git a/my/core/query.py b/my/core/query.py index 4e00569..7c22838 100644 --- a/my/core/query.py +++ b/my/core/query.py @@ -178,7 +178,7 @@ pass 'drop_exceptions' to ignore exceptions""") return lambda o: o.get(key, default) # type: ignore[union-attr] else: if hasattr(obj, key): - return lambda o: getattr(o, key, default) # type: ignore[arg-type] + return lambda o: getattr(o, key, default) # Note: if the attribute you're ordering by is an Optional type, # and on some objects it'll return None, the getattr(o, field_name, default) won't diff --git a/my/core/query_range.py b/my/core/query_range.py index a1cfaed..afde933 100644 --- a/my/core/query_range.py +++ b/my/core/query_range.py @@ -327,7 +327,7 @@ def select_range( # we should search for on each value in the iterator if order_value is None and order_by_value_type is not None: # search for that type on the iterator object - order_value = lambda o: isinstance(o, order_by_value_type) # type: ignore + order_value = lambda o: isinstance(o, order_by_value_type) # if the user supplied a order_key, and/or we've generated an order_value, create # the function that accesses that type on each value in the iterator diff --git a/my/instagram/common.py b/my/instagram/common.py index 36c6b83..4df07a1 100644 --- a/my/instagram/common.py +++ b/my/instagram/common.py @@ -68,6 +68,6 @@ def _merge_messages(*sources: Iterator[Res[Message]]) -> Iterator[Res[Message]]: if user is not None: repls['user'] = user if len(repls) > 0: - m = replace(m, **repls) # type: ignore[type-var, misc] # ugh mypy is confused because of Protocol? + m = replace(m, **repls) # type: ignore[type-var] # ugh mypy is confused because of Protocol? mmap[k] = m yield m From 7b1cec9326609583c4ae4c542dd352df70ba9c11 Mon Sep 17 00:00:00 2001 From: karlicoss Date: Fri, 10 Nov 2023 23:02:11 +0000 Subject: [PATCH 013/122] codeforces/topcode: move to top level and check in ci --- my/{coding => }/codeforces.py | 15 +++++---------- my/{coding => }/topcoder.py | 16 +++++----------- tox.ini | 2 -- 3 files changed, 10 insertions(+), 23 deletions(-) rename my/{coding => }/codeforces.py (87%) rename my/{coding => }/topcoder.py (83%) diff --git a/my/coding/codeforces.py b/my/codeforces.py similarity index 87% rename from my/coding/codeforces.py rename to my/codeforces.py index a8b0f65..a97c360 100644 --- a/my/coding/codeforces.py +++ b/my/codeforces.py @@ -1,4 +1,3 @@ -#!/usr/bin/env python3 from my.config import codeforces as config # type: ignore[attr-defined] @@ -8,8 +7,8 @@ import json from typing import NamedTuple, Dict, Iterator -from ..core import get_files, Res, unwrap -from ..core.konsume import ignore, wrap +from my.core import get_files, Res +from my.core.konsume import ignore, wrap Cid = int @@ -72,20 +71,16 @@ class Competition(NamedTuple): ignore(json, 'rank', 'oldRating', 'newRating') -def iter_data() -> Iterator[Res[Competition]]: +def data() -> Iterator[Res[Competition]]: cmap = get_contests() last = max(get_files(config.export_path, 'codeforces*.json')) with wrap(json.loads(last.read_text())) as j: - j['status'].ignore() - res = j['result'].zoom() + j['status'].ignore() # type: ignore[index] + res = j['result'].zoom() # type: ignore[index] for c in list(res): # TODO maybe we want 'iter' method?? ignore(c, 'handle', 'ratingUpdateTimeSeconds') yield from Competition.make(cmap=cmap, json=c) c.consume() # TODO maybe if they are all empty, no need to consume?? - - -def get_data(): - return list(sorted(iter_data(), key=Competition.when.fget)) diff --git a/my/coding/topcoder.py b/my/topcoder.py similarity index 83% rename from my/coding/topcoder.py rename to my/topcoder.py index 96bcdf7..7432379 100644 --- a/my/coding/topcoder.py +++ b/my/topcoder.py @@ -1,16 +1,14 @@ -#!/usr/bin/env python3 from my.config import topcoder as config # type: ignore[attr-defined] from datetime import datetime from functools import cached_property import json -from typing import NamedTuple, Dict, Iterator +from typing import NamedTuple, Iterator -from ..core import get_files, Res, unwrap, Json -from ..core.error import Res, unwrap -from ..core.konsume import zoom, wrap, ignore +from my.core import get_files, Res, Json +from my.core.konsume import zoom, wrap, ignore def _get_latest() -> Json: @@ -54,11 +52,11 @@ class Competition(NamedTuple): ) -def iter_data() -> Iterator[Res[Competition]]: +def data() -> Iterator[Res[Competition]]: with wrap(_get_latest()) as j: ignore(j, 'id', 'version') - res = j['result'].zoom() + res = j['result'].zoom() # type: ignore[index] ignore(res, 'success', 'status', 'metadata') cont = res['content'].zoom() @@ -77,7 +75,3 @@ def iter_data() -> Iterator[Res[Competition]]: yield from Competition.make(json=c) c.consume() - -def get_data(): - return list(sorted(iter_data(), key=Competition.when.fget)) - diff --git a/tox.ini b/tox.ini index 0de357f..a48e0df 100644 --- a/tox.ini +++ b/tox.ini @@ -169,8 +169,6 @@ commands = {envpython} -m mypy --install-types --non-interactive \ -p {[testenv]package_name} \ - --exclude 'my/coding/codeforces.py' \ - --exclude 'my/coding/topcoder.py' \ --txt-report .coverage.mypy-misc \ --html-report .coverage.mypy-misc \ {posargs} From 37643c098ff60e7cf1260da69e9d2e820f2b9850 Mon Sep 17 00:00:00 2001 From: karlicoss Date: Fri, 10 Nov 2023 23:03:55 +0000 Subject: [PATCH 014/122] tox: remove cat coverage index from tox, it's not very useful anyway --- tox.ini | 5 ----- 1 file changed, 5 deletions(-) diff --git a/tox.ini b/tox.ini index a48e0df..06d1476 100644 --- a/tox.ini +++ b/tox.ini @@ -116,7 +116,6 @@ commands = [testenv:mypy-core] -allowlist_externals = cat commands = {envpython} -m pip install --use-pep517 -e .[testing,optional] {envpython} -m pip install orgparse # used it core.orgmode? @@ -127,13 +126,11 @@ commands = --txt-report .coverage.mypy-core \ --html-report .coverage.mypy-core \ {posargs} - cat .coverage.mypy-core/index.txt # specific modules that are known to be mypy compliant (to avoid false negatives) # todo maybe split into separate jobs? need to add comment how to run [testenv:mypy-misc] -allowlist_externals = cat commands = {envpython} -m pip install --use-pep517 -e .[testing,optional] @@ -172,8 +169,6 @@ commands = --txt-report .coverage.mypy-misc \ --html-report .coverage.mypy-misc \ {posargs} - # txt report is a bit more convenient to view on CI - cat .coverage.mypy-misc/index.txt {envpython} -m mypy --install-types --non-interactive \ tests From bde43d6a7a8817c60da2c2f47d64a8f71132f27b Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Sat, 11 Nov 2023 00:28:13 +0000 Subject: [PATCH 015/122] my.body.sleep: massive speedup for average temperature calculation --- my/body/sleep/common.py | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/my/body/sleep/common.py b/my/body/sleep/common.py index 7bc1021..e84c8d5 100644 --- a/my/body/sleep/common.py +++ b/my/body/sleep/common.py @@ -17,15 +17,21 @@ class Combine: bdf = BM.dataframe() temp = bdf['temp'] + # sort index and drop nans, otherwise indexing with [start: end] gonna complain + temp = pd.Series( + temp.values, + index=pd.to_datetime(temp.index, utc=True) + ).sort_index() + temp = temp.loc[temp.index.dropna()] + def calc_avg_temperature(row): start = row['sleep_start'] end = row['sleep_end'] if pd.isna(start) or pd.isna(end): return None - between = (start <= temp.index) & (temp.index <= end) # on no temp data, returns nan, ok - return temp[between].mean() + return temp[start: end].mean() df['avg_temp'] = df.apply(calc_avg_temperature, axis=1) return df From 09e0f66892d8d336698193312ed8773386a25ef7 Mon Sep 17 00:00:00 2001 From: karlicoss Date: Sun, 19 Nov 2023 17:49:16 +0000 Subject: [PATCH 016/122] tox: disable --parallel flag in hpi module install It's been so flaky it ends up taking more time to merge stuff. See https://github.com/karlicoss/HPI/issues/306 --- tox.ini | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tox.ini b/tox.ini index 06d1476..e51d0b6 100644 --- a/tox.ini +++ b/tox.ini @@ -134,7 +134,7 @@ commands = commands = {envpython} -m pip install --use-pep517 -e .[testing,optional] - {envpython} -m my.core module install --parallel \ + {envpython} -m my.core module install \ my.arbtt \ my.browser.export \ my.coding.commits \ From a843407e40d05960650b6e1cee6cd0a63f8f09d1 Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Sun, 19 Nov 2023 22:45:02 +0000 Subject: [PATCH 017/122] core/compat: move fromisoformat to .core.compat module --- my/arbtt.py | 7 ++++--- my/core/common.py | 28 ++++++++++------------------ my/core/compat.py | 39 +++++++++++++++++++++++++++++++++++++++ my/core/query_range.py | 4 ++-- my/polar.py | 8 ++++---- my/rss/feedbin.py | 5 +++-- my/runnerup.py | 7 ++++--- my/stackexchange/gdpr.py | 5 +++-- 8 files changed, 69 insertions(+), 34 deletions(-) diff --git a/my/arbtt.py b/my/arbtt.py index 5683515..941a05f 100644 --- a/my/arbtt.py +++ b/my/arbtt.py @@ -23,7 +23,7 @@ def inputs() -> Sequence[Path]: from .core import dataclass, Json, PathIsh, datetime_aware -from .core.common import isoparse +from .core.compat import fromisoformat @dataclass @@ -39,6 +39,7 @@ class Entry: @property def dt(self) -> datetime_aware: # contains utc already + # TODO after python>=3.11, could just use fromisoformat ds = self.json['date'] elen = 27 lds = len(ds) @@ -46,10 +47,10 @@ class Entry: # ugh. sometimes contains less that 6 decimal points ds = ds[:-1] + '0' * (elen - lds) + 'Z' elif lds > elen: - # ahd sometimes more... + # and sometimes more... ds = ds[:elen - 1] + 'Z' - return isoparse(ds) + return fromisoformat(ds) @property def active(self) -> Optional[str]: diff --git a/my/core/common.py b/my/core/common.py index 85b9386..f1441a9 100644 --- a/my/core/common.py +++ b/my/core/common.py @@ -313,20 +313,18 @@ class classproperty(Generic[_R]): # def __get__(self) -> _R: # return self.f() -# TODO deprecate in favor of datetime_aware -tzdatetime = datetime +# for now just serves documentation purposes... but one day might make it statically verifiable where possible? +# TODO e.g. maybe use opaque mypy alias? +datetime_naive = datetime +datetime_aware = datetime -# TODO doctests? -def isoparse(s: str) -> tzdatetime: - """ - Parses timestamps formatted like 2020-05-01T10:32:02.925961Z - """ - # TODO could use dateutil? but it's quite slow as far as I remember.. - # TODO support non-utc.. somehow? - assert s.endswith('Z'), s - s = s[:-1] + '+00:00' - return datetime.fromisoformat(s) +# TODO deprecate +tzdatetime = datetime_aware + + +# TODO deprecate (although could be used in modules) +from .compat import fromisoformat as isoparse import re @@ -590,12 +588,6 @@ def asdict(thing: Any) -> Json: raise TypeError(f'Could not convert object {thing} to dict') -# for now just serves documentation purposes... but one day might make it statically verifiable where possible? -# TODO e.g. maybe use opaque mypy alias? -datetime_naive = datetime -datetime_aware = datetime - - def assert_subpackage(name: str) -> None: # can lead to some unexpected issues if you 'import cachew' which being in my/core directory.. so let's protect against it # NOTE: if we use overlay, name can be smth like my.origg.my.core.cachew ... diff --git a/my/core/compat.py b/my/core/compat.py index 48e194b..9cdea27 100644 --- a/my/core/compat.py +++ b/my/core/compat.py @@ -76,3 +76,42 @@ if sys.version_info[:2] <= (3, 9): return lo else: from bisect import bisect_left + + +from datetime import datetime +if sys.version_info[:2] >= (3, 11): + fromisoformat = datetime.fromisoformat +else: + def fromisoformat(date_string: str) -> datetime: + # didn't support Z as "utc" before 3.11 + if date_string.endswith('Z'): + # NOTE: can be removed from 3.11? + # https://docs.python.org/3/library/datetime.html#datetime.datetime.fromisoformat + date_string = date_string[:-1] + '+00:00' + return datetime.fromisoformat(date_string) + + +def test_fromisoformat() -> None: + from datetime import timezone + + # feedbin has this format + assert fromisoformat('2020-05-01T10:32:02.925961Z') == datetime( + 2020, 5, 1, 10, 32, 2, 925961, timezone.utc, + ) + + # polar has this format + assert fromisoformat('2018-11-28T22:04:01.304Z') == datetime( + 2018, 11, 28, 22, 4, 1, 304000, timezone.utc, + ) + + # stackexchange, runnerup has this format + assert fromisoformat('2020-11-30T00:53:12Z') == datetime( + 2020, 11, 30, 0, 53, 12, 0, timezone.utc, + ) + + # arbtt has this format (sometimes less/more than 6 digits in milliseconds) + # TODO doesn't work atm, not sure if really should be supported... + # maybe should have flags for weird formats? + # assert isoparse('2017-07-18T18:59:38.21731Z') == datetime( + # 2017, 7, 18, 18, 59, 38, 217310, timezone.utc, + # ) diff --git a/my/core/query_range.py b/my/core/query_range.py index afde933..dfb9e55 100644 --- a/my/core/query_range.py +++ b/my/core/query_range.py @@ -24,7 +24,7 @@ from .query import ( ET, ) -from .common import isoparse +from .compat import fromisoformat timedelta_regex = re.compile(r"^((?P[\.\d]+?)w)?((?P[\.\d]+?)d)?((?P[\.\d]+?)h)?((?P[\.\d]+?)m)?((?P[\.\d]+?)s)?$") @@ -78,7 +78,7 @@ def parse_datetime_float(date_str: str) -> float: except ValueError: pass try: - return isoparse(ds).timestamp() + return fromisoformat(ds).timestamp() except (AssertionError, ValueError): pass diff --git a/my/polar.py b/my/polar.py index fe59d00..cd2c719 100644 --- a/my/polar.py +++ b/my/polar.py @@ -42,7 +42,7 @@ from typing import List, Dict, Iterable, NamedTuple, Sequence, Optional import json from .core import LazyLogger, Json, Res -from .core.common import isoparse +from .core.compat import fromisoformat from .core.error import echain, sort_res_by from .core.konsume import wrap, Zoomable, Wdict @@ -145,7 +145,7 @@ class Loader: cmap[hlid] = ccs ccs.append(Comment( cid=cid.value, - created=isoparse(crt.value), + created=fromisoformat(crt.value), text=html.value, # TODO perhaps coonvert from html to text or org? )) v.consume() @@ -183,7 +183,7 @@ class Loader: yield Highlight( hid=hid, - created=isoparse(crt), + created=fromisoformat(crt), selection=text, comments=tuple(comments), tags=tuple(htags), @@ -221,7 +221,7 @@ class Loader: path = Path(config.polar_dir) / 'stash' / filename yield Book( - created=isoparse(added), + created=fromisoformat(added), uid=self.uid, path=path, title=title, diff --git a/my/rss/feedbin.py b/my/rss/feedbin.py index 8ba25b8..6160abc 100644 --- a/my/rss/feedbin.py +++ b/my/rss/feedbin.py @@ -7,7 +7,8 @@ from my.config import feedbin as config from pathlib import Path from typing import Sequence -from ..core.common import listify, get_files, isoparse +from ..core.common import listify, get_files +from ..core.compat import fromisoformat from .common import Subscription @@ -22,7 +23,7 @@ def parse_file(f: Path): raw = json.loads(f.read_text()) for r in raw: yield Subscription( - created_at=isoparse(r['created_at']), + created_at=fromisoformat(r['created_at']), title=r['title'], url=r['site_url'], id=r['id'], diff --git a/my/runnerup.py b/my/runnerup.py index f12d9b3..ca09466 100644 --- a/my/runnerup.py +++ b/my/runnerup.py @@ -11,7 +11,8 @@ from pathlib import Path from typing import Iterable from .core import Res, get_files -from .core.common import isoparse, Json +from .core.common import Json +from .core.compat import fromisoformat import tcxparser # type: ignore[import-untyped] @@ -44,7 +45,7 @@ def _parse(f: Path) -> Workout: return { 'id' : f.name, # not sure? - 'start_time' : isoparse(tcx.started_at), + 'start_time' : fromisoformat(tcx.started_at), 'duration' : timedelta(seconds=tcx.duration), 'sport' : sport, 'heart_rate_avg': tcx.hr_avg, @@ -58,7 +59,7 @@ def _parse(f: Path) -> Workout: # tcx.hr_values(), # # todo cadence? # ): - # t = isoparse(ts) + # t = fromisoformat(ts) def workouts() -> Iterable[Res[Workout]]: diff --git a/my/stackexchange/gdpr.py b/my/stackexchange/gdpr.py index 18b2b4d..2f3b98d 100644 --- a/my/stackexchange/gdpr.py +++ b/my/stackexchange/gdpr.py @@ -16,7 +16,8 @@ config = make_config(stackexchange) # TODO just merge all of them and then filter?.. not sure -from ..core.common import Json, isoparse +from ..core.common import Json +from ..core.compat import fromisoformat from typing import NamedTuple, Iterable from datetime import datetime class Vote(NamedTuple): @@ -25,7 +26,7 @@ class Vote(NamedTuple): @property def when(self) -> datetime: - return isoparse(self.j['eventTime']) + return fromisoformat(self.j['eventTime']) # todo Url return type? @property From 224ba521e36ae0326f433c4adadcfafdb7da3c3e Mon Sep 17 00:00:00 2001 From: Sean Breckenridge Date: Sun, 3 Dec 2023 09:49:05 -0800 Subject: [PATCH 018/122] gpslogger: catch broken xml file error --- my/location/gpslogger.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/my/location/gpslogger.py b/my/location/gpslogger.py index 17f828f..29e2547 100644 --- a/my/location/gpslogger.py +++ b/my/location/gpslogger.py @@ -23,6 +23,7 @@ from pathlib import Path from typing import Iterator, Sequence, List import gpxpy +from gpxpy.gpx import GPXXMLSyntaxException from more_itertools import unique_everseen from my.core import Stats, LazyLogger @@ -58,7 +59,11 @@ def locations() -> Iterator[Location]: def _extract_locations(path: Path) -> Iterator[Location]: with path.open("r") as gf: - gpx_obj = gpxpy.parse(gf) + try: + gpx_obj = gpxpy.parse(gf) + except GPXXMLSyntaxException as e: + logger.warning("failed to parse XML %s: %s", path, e) + return for track in gpx_obj.tracks: for segment in track.segments: for point in segment.points: From 84d835962dcabb93c5e0cd31af2e43dc1c42020f Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Wed, 20 Dec 2023 02:06:41 +0000 Subject: [PATCH 019/122] docs: some documentation/thoughts on properly implementing overlay packages --- doc/OVERLAYS.org | 144 +++++++++++++++++++ doc/overlays/install_packages.sh | 4 + doc/overlays/main/setup.py | 17 +++ doc/overlays/main/src/my/py.typed | 0 doc/overlays/main/src/my/reddit.py | 11 ++ doc/overlays/main/src/my/twitter/all.py | 7 + doc/overlays/main/src/my/twitter/common.py | 11 ++ doc/overlays/main/src/my/twitter/gdpr.py | 9 ++ doc/overlays/overlay/setup.py | 17 +++ doc/overlays/overlay/src/my/py.typed | 0 doc/overlays/overlay/src/my/twitter/all.py | 8 ++ doc/overlays/overlay/src/my/twitter/talon.py | 9 ++ 12 files changed, 237 insertions(+) create mode 100644 doc/OVERLAYS.org create mode 100755 doc/overlays/install_packages.sh create mode 100644 doc/overlays/main/setup.py create mode 100644 doc/overlays/main/src/my/py.typed create mode 100644 doc/overlays/main/src/my/reddit.py create mode 100644 doc/overlays/main/src/my/twitter/all.py create mode 100644 doc/overlays/main/src/my/twitter/common.py create mode 100644 doc/overlays/main/src/my/twitter/gdpr.py create mode 100644 doc/overlays/overlay/setup.py create mode 100644 doc/overlays/overlay/src/my/py.typed create mode 100644 doc/overlays/overlay/src/my/twitter/all.py create mode 100644 doc/overlays/overlay/src/my/twitter/talon.py diff --git a/doc/OVERLAYS.org b/doc/OVERLAYS.org new file mode 100644 index 0000000..3ac6b07 --- /dev/null +++ b/doc/OVERLAYS.org @@ -0,0 +1,144 @@ +NOTE this kinda overlaps with [[file:MODULE_DESIGN.org][the module design doc]], should be unified in the future. + +# This is describing TODO +# TODO goals +# - overrides +# - proper mypy support +# - TODO reusing parent modules? + +# You can see them TODO in overlays dir + +Consider a toy package/module structure with minimal code, wihout any actual data parsing, just for demonstration purposes. + +- =main= package structure + # TODO do links + + - =my/twitter/gdpr.py= + Extracts Twitter data from GDPR archive. + - =my/twitter/all.py= + Merges twitter data from multiple sources (only =gdpr= in this case), so data consumers are agnostic of specific data sources used. + This will be overriden by =overlay=. + - =my/twitter/common.py= + Contains helper function to merge data, so they can be reused by overlay's =all.py=. + - =my/reddit.py= + Extracts Reddit data -- this won't be overridden by the overlay, we just keep it for demonstration purposes. + +- =overlay= package structure + + - =my/twitter/talon.py= + Extracts Twitter data from Talon android app. + - =my/twitter/all.py= + Override for =all.py= from =main= package -- it merges together data from =gpdr= and =talon= modules. + +# TODO mention resolution? reorder_editable + +* Installing + +NOTE: this was tested with =python 3.10= and =pip 23.3.2=. + +To install, we run: + +: pip3 install --user -e overlay/ +: pip3 install --user -e main/ + +# TODO mention non-editable installs (this bit will still work with non-editable install) + +As a result, we get: + +: pip3 list | grep hpi +: hpi-main 0.0.0 /project/main/src +: hpi-overlay 0.0.0 /project/overlay/src + +: cat ~/.local/lib/python3.10/site-packages/easy-install.pth +: /project/overlay/src +: /project/main/src + +(the order above is important, so =overlay= takes precedence over =main= TODO link) + +Verify the setup: + +: $ python3 -c 'import my; print(my.__path__)' +: _NamespacePath(['/project/overlay/src/my', '/project/main/src/my']) + +This basically means that modules will be searched in both paths, with overlay taking precedence. + +* Testing + +: $ python3 -c 'import my.reddit as R; print(R.upvotes())' +: [main] my.reddit hello +: ['reddit upvote1', 'reddit upvote2'] + +Just as expected here, =my.reddit= is imported from the =main= package, since it doesn't exist in =overlay=. + +Let's theck twitter now: + +: $ python3 -c 'import my.twitter.all as T; print(T.tweets())' +: [overlay] my.twitter.all hello +: [main] my.twitter.common hello +: [main] my.twitter.gdpr hello +: [overlay] my.twitter.talon hello +: ['gdpr tweet 1', 'gdpr tweet 2', 'talon tweet 1', 'talon tweet 2'] + +As expected, =my.twitter.all= was imported from the =overlay=. +As you can see it's merged data from =gdpr= (from =main= package) and =talon= (from =overlay= package). + +So far so good, let's see how it works with mypy. + +* Mypy support + +To check that mypy works as expected I injected some statements in modules that have no impact on runtime, +but should trigger mypy, like this =trigger_mypy_error: str = 123=: + +Let's run it: + +: $ mypy --namespace-packages --strict -p my +: overlay/src/my/twitter/talon.py:9: error: Incompatible types in assignment (expression has type "int", variable has type "str") +: [assignment] +: trigger_mypy_error: str = 123 +: ^ +: Found 1 error in 1 file (checked 4 source files) + +Hmm, this did find the statement in the =overlay=, but missed everything from =main= (e.g. =reddit.py= and =gdpr.py= should have also triggered the check). + +First, let's check which sources mypy is processing: + +: $ mypy --namespace-packages --strict -p my -v 2>&1 | grep BuildSource +: LOG: Found source: BuildSource(path='/project/overlay/src/my', module='my', has_text=False, base_dir=None) +: LOG: Found source: BuildSource(path='/project/overlay/src/my/twitter', module='my.twitter', has_text=False, base_dir=None) +: LOG: Found source: BuildSource(path='/project/overlay/src/my/twitter/all.py', module='my.twitter.all', has_text=False, base_dir=None) +: LOG: Found source: BuildSource(path='/project/overlay/src/my/twitter/talon.py', module='my.twitter.talon', has_text=False, base_dir=None) + +So seems like mypy is not processing anything from =main= package at all? + +At this point I cloned mypy, put a breakpoint, and found out this is the culprit: https://github.com/python/mypy/blob/1dd8e7fe654991b01bd80ef7f1f675d9e3910c3a/mypy/modulefinder.py#L288 + +This basically returns the first path where it finds =my= package, which happens to be the overlay in this case. +So everything else is ignored? + +It even seems to have a test for a similar usecase, which is quite sad. +https://github.com/python/mypy/blob/1dd8e7fe654991b01bd80ef7f1f675d9e3910c3a/mypy/test/testmodulefinder.py#L64-L71 + +TODO For now I'm going to open an issue in mypy repository and ask why is that the case. + +But ok, maybe mypy treats =main= as an external package somhow but still type checks it properly? +Let's see what's going on with imports: + +: $ mypy --namespace-packages --strict -p my --follow-imports=error +: overlay/src/my/twitter/talon.py:9: error: Incompatible types in assignment (expression has type "int", variable has type "str") +: [assignment] +: trigger_mypy_error: str = 123 +: ^ +: overlay/src/my/twitter/all.py:3: error: Import of "my.twitter.common" ignored [misc] +: from .common import merge +: ^ +: overlay/src/my/twitter/all.py:6: error: Import of "my.twitter.gdpr" ignored [misc] +: from . import gdpr +: ^ +: overlay/src/my/twitter/all.py:6: note: (Using --follow-imports=error, module not passed on command line) +: overlay/src/my/twitter/all.py: note: In function "tweets": +: overlay/src/my/twitter/all.py:8: error: Returning Any from function declared to return "List[str]" [no-any-return] +: return merge(gdpr, talon) +: ^ +: Found 4 errors in 2 files (checked 4 source files) + +Nope -- looks like it's completely unawareof =main=, and what's worst, by default (without tweaking =--follow-imports=), these errors would be suppressed. diff --git a/doc/overlays/install_packages.sh b/doc/overlays/install_packages.sh new file mode 100755 index 0000000..3fc38d3 --- /dev/null +++ b/doc/overlays/install_packages.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -eux +pip3 install --user -e overlay/ +pip3 install --user -e main/ diff --git a/doc/overlays/main/setup.py b/doc/overlays/main/setup.py new file mode 100644 index 0000000..51ac55c --- /dev/null +++ b/doc/overlays/main/setup.py @@ -0,0 +1,17 @@ +from setuptools import setup, find_namespace_packages # type: ignore + + +def main() -> None: + pkgs = find_namespace_packages('src') + pkg = min(pkgs) + setup( + name='hpi-main', + zip_safe=False, + packages=pkgs, + package_dir={'': 'src'}, + package_data={pkg: ['py.typed']}, + ) + + +if __name__ == '__main__': + main() diff --git a/doc/overlays/main/src/my/py.typed b/doc/overlays/main/src/my/py.typed new file mode 100644 index 0000000..e69de29 diff --git a/doc/overlays/main/src/my/reddit.py b/doc/overlays/main/src/my/reddit.py new file mode 100644 index 0000000..ae4e481 --- /dev/null +++ b/doc/overlays/main/src/my/reddit.py @@ -0,0 +1,11 @@ +print(f'[main] {__name__} hello') + + +def upvotes() -> list[str]: + return [ + 'reddit upvote1', + 'reddit upvote2', + ] + + +trigger_mypy_error: str = 123 diff --git a/doc/overlays/main/src/my/twitter/all.py b/doc/overlays/main/src/my/twitter/all.py new file mode 100644 index 0000000..feb9fce --- /dev/null +++ b/doc/overlays/main/src/my/twitter/all.py @@ -0,0 +1,7 @@ +print(f'[main] {__name__} hello') + +from .common import merge + +def tweets() -> list[str]: + from . import gdpr + return merge(gdpr) diff --git a/doc/overlays/main/src/my/twitter/common.py b/doc/overlays/main/src/my/twitter/common.py new file mode 100644 index 0000000..4121b5b --- /dev/null +++ b/doc/overlays/main/src/my/twitter/common.py @@ -0,0 +1,11 @@ +print(f'[main] {__name__} hello') + +from typing import Protocol + +class Source(Protocol): + def tweets(self) -> list[str]: + ... + +def merge(*sources: Source) -> list[str]: + from itertools import chain + return list(chain.from_iterable(src.tweets() for src in sources)) diff --git a/doc/overlays/main/src/my/twitter/gdpr.py b/doc/overlays/main/src/my/twitter/gdpr.py new file mode 100644 index 0000000..22ea220 --- /dev/null +++ b/doc/overlays/main/src/my/twitter/gdpr.py @@ -0,0 +1,9 @@ +print(f'[main] {__name__} hello') + +def tweets() -> list[str]: + return [ + 'gdpr tweet 1', + 'gdpr tweet 2', + ] + +trigger_mypy_error: str = 123 diff --git a/doc/overlays/overlay/setup.py b/doc/overlays/overlay/setup.py new file mode 100644 index 0000000..aaaa244 --- /dev/null +++ b/doc/overlays/overlay/setup.py @@ -0,0 +1,17 @@ +from setuptools import setup, find_namespace_packages # type: ignore + + +def main() -> None: + pkgs = find_namespace_packages('src') + pkg = min(pkgs) + setup( + name='hpi-overlay', + zip_safe=False, + packages=pkgs, + package_dir={'': 'src'}, + package_data={pkg: ['py.typed']}, + ) + + +if __name__ == '__main__': + main() diff --git a/doc/overlays/overlay/src/my/py.typed b/doc/overlays/overlay/src/my/py.typed new file mode 100644 index 0000000..e69de29 diff --git a/doc/overlays/overlay/src/my/twitter/all.py b/doc/overlays/overlay/src/my/twitter/all.py new file mode 100644 index 0000000..895d84b --- /dev/null +++ b/doc/overlays/overlay/src/my/twitter/all.py @@ -0,0 +1,8 @@ +print(f'[overlay] {__name__} hello') + +from .common import merge + +def tweets() -> list[str]: + from . import gdpr + from . import talon + return merge(gdpr, talon) diff --git a/doc/overlays/overlay/src/my/twitter/talon.py b/doc/overlays/overlay/src/my/twitter/talon.py new file mode 100644 index 0000000..782236c --- /dev/null +++ b/doc/overlays/overlay/src/my/twitter/talon.py @@ -0,0 +1,9 @@ +print(f'[overlay] {__name__} hello') + +def tweets() -> list[str]: + return [ + 'talon tweet 1', + 'talon tweet 2', + ] + +trigger_mypy_error: str = 123 From adbc0e73a26d1db53badc577e17c90f8a483973f Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Wed, 20 Dec 2023 18:07:34 +0000 Subject: [PATCH 020/122] docs: add note about directly checking overlays with mypy --- doc/OVERLAYS.org | 44 ++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 40 insertions(+), 4 deletions(-) diff --git a/doc/OVERLAYS.org b/doc/OVERLAYS.org index 3ac6b07..8580d53 100644 --- a/doc/OVERLAYS.org +++ b/doc/OVERLAYS.org @@ -32,7 +32,7 @@ Consider a toy package/module structure with minimal code, wihout any actual dat # TODO mention resolution? reorder_editable -* Installing +* Installing (editable install) NOTE: this was tested with =python 3.10= and =pip 23.3.2=. @@ -62,7 +62,7 @@ Verify the setup: This basically means that modules will be searched in both paths, with overlay taking precedence. -* Testing +* Testing (editable install) : $ python3 -c 'import my.reddit as R; print(R.upvotes())' : [main] my.reddit hello @@ -84,7 +84,7 @@ As you can see it's merged data from =gdpr= (from =main= package) and =talon= (f So far so good, let's see how it works with mypy. -* Mypy support +* Mypy support (editable install) To check that mypy works as expected I injected some statements in modules that have no impact on runtime, but should trigger mypy, like this =trigger_mypy_error: str = 123=: @@ -118,7 +118,7 @@ So everything else is ignored? It even seems to have a test for a similar usecase, which is quite sad. https://github.com/python/mypy/blob/1dd8e7fe654991b01bd80ef7f1f675d9e3910c3a/mypy/test/testmodulefinder.py#L64-L71 -TODO For now I'm going to open an issue in mypy repository and ask why is that the case. +For now, I opened an issue in mypy repository https://github.com/python/mypy/issues/16683 But ok, maybe mypy treats =main= as an external package somhow but still type checks it properly? Let's see what's going on with imports: @@ -142,3 +142,39 @@ Let's see what's going on with imports: : Found 4 errors in 2 files (checked 4 source files) Nope -- looks like it's completely unawareof =main=, and what's worst, by default (without tweaking =--follow-imports=), these errors would be suppressed. + +* What if we don't install at all? +Instead of editable install let's try running mypy directly over source files + +First let's only check =main= package: + +: $ MYPYPATH=main/src mypy --namespace-packages --strict -p my +: main/src/my/twitter/gdpr.py:9: error: Incompatible types in assignment (expression has type "int", variable has type "str") [assignment] +: trigger_mypy_error: str = 123 +: ^~~ +: main/src/my/reddit.py:11: error: Incompatible types in assignment (expression has type "int", variable has type "str") [assignment] +: trigger_mypy_error: str = 123 +: ^~~ +: Found 2 errors in 2 files (checked 6 source files) + +As expected, it found both errors. + +Now with overlay as well: + +: $ MYPYPATH=overlay/src:main/src mypy --namespace-packages --strict -p my +: overlay/src/my/twitter/all.py:6: note: In module imported here: +: main/src/my/twitter/gdpr.py:9: error: Incompatible types in assignment (expression has type "int", variable has type "str") [assignment] +: trigger_mypy_error: str = 123 +: ^~~ +: overlay/src/my/twitter/talon.py:9: error: Incompatible types in assignment (expression has type "int", variable has type "str") +: [assignment] +: trigger_mypy_error: str = 123 +: ^~~ +: Found 2 errors in 2 files (checked 4 source files) + +Interesting enough, this is slightly better than the editable install (it detected error in =gdpr.py= as well). +But still no =reddit.py= error. + +TODO possibly worth submitting to mypy issue tracker as well... + +Overall it seems that properly type checking modules in overlays (especially the ones actually overriding/extending base modules) is kinda problematic. From a8f8858cb188bf4517cab2338e4ec3894f8fce7a Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Fri, 22 Dec 2023 02:46:41 +0000 Subject: [PATCH 021/122] docs: document more experiments with overlays in docs --- doc/OVERLAYS.org | 142 +++++++++++++++++- doc/overlays/overlay2/setup.py | 17 +++ doc/overlays/overlay2/src/my/py.typed | 0 .../overlay2/src/my/twitter/__init__.py | 13 ++ doc/overlays/overlay3/setup.py | 17 +++ doc/overlays/overlay3/src/my/py.typed | 0 doc/overlays/overlay3/src/my/twitter/_hook.py | 9 ++ 7 files changed, 196 insertions(+), 2 deletions(-) create mode 100644 doc/overlays/overlay2/setup.py create mode 100644 doc/overlays/overlay2/src/my/py.typed create mode 100644 doc/overlays/overlay2/src/my/twitter/__init__.py create mode 100644 doc/overlays/overlay3/setup.py create mode 100644 doc/overlays/overlay3/src/my/py.typed create mode 100644 doc/overlays/overlay3/src/my/twitter/_hook.py diff --git a/doc/OVERLAYS.org b/doc/OVERLAYS.org index 8580d53..98687b7 100644 --- a/doc/OVERLAYS.org +++ b/doc/OVERLAYS.org @@ -1,5 +1,7 @@ NOTE this kinda overlaps with [[file:MODULE_DESIGN.org][the module design doc]], should be unified in the future. +Relevant discussion about overlays: https://github.com/karlicoss/HPI/issues/102 + # This is describing TODO # TODO goals # - overrides @@ -62,7 +64,7 @@ Verify the setup: This basically means that modules will be searched in both paths, with overlay taking precedence. -* Testing (editable install) +* Testing runtime behaviour (editable install) : $ python3 -c 'import my.reddit as R; print(R.upvotes())' : [main] my.reddit hello @@ -143,6 +145,30 @@ Let's see what's going on with imports: Nope -- looks like it's completely unawareof =main=, and what's worst, by default (without tweaking =--follow-imports=), these errors would be suppressed. +What if we check =my.twitter= directly? + +: $ mypy --namespace-packages --strict -p my.twitter --follow-imports=error +: overlay/src/my/twitter/talon.py:9: error: Incompatible types in assignment (expression has type "int", variable has type "str") +: [assignment] +: trigger_mypy_error: str = 123 +: ^~~ +: overlay/src/my/twitter: error: Ancestor package "my" ignored [misc] +: overlay/src/my/twitter: note: (Using --follow-imports=error, submodule passed on command line) +: overlay/src/my/twitter/all.py:3: error: Import of "my.twitter.common" ignored [misc] +: from .common import merge +: ^ +: overlay/src/my/twitter/all.py:3: note: (Using --follow-imports=error, module not passed on command line) +: overlay/src/my/twitter/all.py:6: error: Import of "my.twitter.gdpr" ignored [misc] +: from . import gdpr +: ^ +: overlay/src/my/twitter/all.py: note: In function "tweets": +: overlay/src/my/twitter/all.py:8: error: Returning Any from function declared to return "list[str]" [no-any-return] +: return merge(gdpr, talon) +: ^~~~~~~~~~~~~~~~~~~~~~~~~ +: Found 5 errors in 3 files (checked 3 source files) + +Now we're also getting =error: Ancestor package "my" ignored [misc]= .. not ideal. + * What if we don't install at all? Instead of editable install let's try running mypy directly over source files @@ -177,4 +203,116 @@ But still no =reddit.py= error. TODO possibly worth submitting to mypy issue tracker as well... -Overall it seems that properly type checking modules in overlays (especially the ones actually overriding/extending base modules) is kinda problematic. +Overall it seems that properly type checking HPI setup as a whole is kinda problematic, especially if the modules actually override/extend base modules. + +* Modifying (monkey patching) original module in the overlay +Let's say we want to modify/monkey patch =my.twitter.talon= module from =main=, for example, convert "gdpr" to uppercase, i.e. =tweet.replace('gdpr', 'GDPR')=. + +# TODO see overlay2/ + +I think our options are: + +- symlink to the 'parent' packages, e.g. =main= in the case + + Alternatively, somehow install =main= under a different name/alias (managed by pip). + + This is discussed here: https://github.com/karlicoss/HPI/issues/102 + + The main upside is that it's relatively simple and (sort of works with mypy). + + There are a few big downsides: + - creates a parallel package hierarchy (to the one maintained by pip), symlinks will need to be carefully managed manually + + This may not be such a huge deal if you don't have too many overlays. + However this results in problems if you're trying to switch between two different HPI checkouts (e.g. stable and development). If you have symlinks into "stable" from the overlay then stable modules will sometimes be picked up when you're expecting "development" package. + + - symlinks pointing outside of the source tree might cause pip install to go into infinite loop + + - it modifies the package name + + This may potentially result in some confusing behaviours. + + One thing I noticed for example is that cachew caches might get duplicated. + + - it might not work in all cases or might result in recursive imports + +- do not shadow the original module + + Basically instead of shadowing via namespace package mechanism and creating identically named module, + create some sort of hook that would patch the original =my.twitter.talon= module from =main=. + + The downside is that it's a bit unclear where to do that, we need some sort of entry point? + + - it could be some global dynamic hook defined in the overlay, and then executed from =my.core= + + However, it's a bit intrusive, and unclear how to handle errors. E.g. what if we're monkey patching a module that we weren't intending to use, don't have dependencies installed and it's crashing? + + Perhaps core could support something like =_hook= in each of HPI's modules? + Note that it can't be =my.twitter.all=, since we might want to override =.all= itself. + + The downside is is this probably not going to work well with =tmp_config= and such -- we'll need to somehow execute the hook again on reloading the module? + + - ideally we'd have something that integrates with =importlib= and executed automatically when module is imported? + + TODO explore these: + + - https://stackoverflow.com/questions/43571737/how-to-implement-an-import-hook-that-can-modify-the-source-code-on-the-fly-using + - https://github.com/brettlangdon/importhook + + This one is pretty intrusive, and has some issues, e.g. https://github.com/brettlangdon/importhook/issues/4 + + Let's try it: + : $ PYTHONPATH=overlay3/src:main/src python3 -c 'import my.twitter._hook; import my.twitter.all as M; print(M.tweets())' + : [main] my.twitter.all hello + : [main] my.twitter.common hello + : [main] my.twitter.gdpr hello + : EXECUTING IMPORT HOOK! + : ['GDPR tweet 1', 'GDPR tweet 2'] + + Ok it worked, and seems pretty neat. + However sadly it doesn't work with =tmp_config= (TODO add a proper demo?) + Not sure if it's more of an issue with =tmp_config= implementation (which is very hacky), or =importhook= itself? + + In addition, still the question is where to put the hook itself, but in that case even a global one could be fine. + + - define hook in =my/twitter/__init__.py= + + Basically, use =extend_path= to make it behave like a namespace package, but in addition, patch original =my.twitter.talon=? + + : $ cat overlay2/src/my/twitter/__init__.py + : print(f'[overlay2] {__name__} hello') + : + : from pkgutil import extend_path + : __path__ = extend_path(__path__, __name__) + : + : def hack_gdpr_module() -> None: + : from . import gdpr + : tweets_orig = gdpr.tweets + : def tweets_patched(): + : return [t.replace('gdpr', 'GDPR') for t in tweets_orig()] + : gdpr.tweets = tweets_patched + : + : hack_gdpr_module() + + This actually seems to work?? + + : PYTHONPATH=overlay2/src:main/src python3 -c 'import my.twitter.all as M; print(M.tweets())' + : [overlay2] my.twitter hello + : [main] my.twitter.gdpr hello + : [main] my.twitter.all hello + : [main] my.twitter.common hello + : ['GDPR tweet 1', 'GDPR tweet 2'] + + However, this doesn't stack, i.e. if the 'parent' overlay had its own =__init__.py=, it won't get called. + +- shadow the original module and temporarily modify =__path__= before importing the same module from the parent overlay + + This approach is implemented in =my.core.experimental.import_original_module= + + TODO demonstrate it properly, but I think that also works in a 'chain' of overlays + + Seems like that option is the most promising so far, albeit very hacky. + +Note that none of these options work well with mypy (since it's all dynamic hackery), even if you disregard the issues described in the previous sections. + +# TODO .pkg files? somewhat interesting... https://github.com/python/cpython/blob/3.12/Lib/pkgutil.py#L395-L410 diff --git a/doc/overlays/overlay2/setup.py b/doc/overlays/overlay2/setup.py new file mode 100644 index 0000000..e34e7de --- /dev/null +++ b/doc/overlays/overlay2/setup.py @@ -0,0 +1,17 @@ +from setuptools import setup, find_namespace_packages # type: ignore + + +def main() -> None: + pkgs = find_namespace_packages('src') + pkg = min(pkgs) + setup( + name='hpi-overlay2', + zip_safe=False, + packages=pkgs, + package_dir={'': 'src'}, + package_data={pkg: ['py.typed']}, + ) + + +if __name__ == '__main__': + main() diff --git a/doc/overlays/overlay2/src/my/py.typed b/doc/overlays/overlay2/src/my/py.typed new file mode 100644 index 0000000..e69de29 diff --git a/doc/overlays/overlay2/src/my/twitter/__init__.py b/doc/overlays/overlay2/src/my/twitter/__init__.py new file mode 100644 index 0000000..9c5674f --- /dev/null +++ b/doc/overlays/overlay2/src/my/twitter/__init__.py @@ -0,0 +1,13 @@ +print(f'[overlay2] {__name__} hello') + +from pkgutil import extend_path +__path__ = extend_path(__path__, __name__) + +def hack_gdpr_module() -> None: + from . import gdpr + tweets_orig = gdpr.tweets + def tweets_patched(): + return [t.replace('gdpr', 'GDPR') for t in tweets_orig()] + gdpr.tweets = tweets_patched + +hack_gdpr_module() diff --git a/doc/overlays/overlay3/setup.py b/doc/overlays/overlay3/setup.py new file mode 100644 index 0000000..106a115 --- /dev/null +++ b/doc/overlays/overlay3/setup.py @@ -0,0 +1,17 @@ +from setuptools import setup, find_namespace_packages # type: ignore + + +def main() -> None: + pkgs = find_namespace_packages('src') + pkg = min(pkgs) + setup( + name='hpi-overlay3', + zip_safe=False, + packages=pkgs, + package_dir={'': 'src'}, + package_data={pkg: ['py.typed']}, + ) + + +if __name__ == '__main__': + main() diff --git a/doc/overlays/overlay3/src/my/py.typed b/doc/overlays/overlay3/src/my/py.typed new file mode 100644 index 0000000..e69de29 diff --git a/doc/overlays/overlay3/src/my/twitter/_hook.py b/doc/overlays/overlay3/src/my/twitter/_hook.py new file mode 100644 index 0000000..ce249ae --- /dev/null +++ b/doc/overlays/overlay3/src/my/twitter/_hook.py @@ -0,0 +1,9 @@ +import importhook + +@importhook.on_import('my.twitter.gdpr') +def on_import(gdpr): + print("EXECUTING IMPORT HOOK!") + tweets_orig = gdpr.tweets + def tweets_patched(): + return [t.replace('gdpr', 'GDPR') for t in tweets_orig()] + gdpr.tweets = tweets_patched From 3d75abafe96c6ff10563a7c0f96cf3eed7455410 Mon Sep 17 00:00:00 2001 From: karlicoss Date: Sat, 23 Dec 2023 02:33:23 +0000 Subject: [PATCH 022/122] my.twitter.android: some intial work on pasring sqlite databases from official Android app --- my/twitter/android.py | 93 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 93 insertions(+) create mode 100644 my/twitter/android.py diff --git a/my/twitter/android.py b/my/twitter/android.py new file mode 100644 index 0000000..ac834df --- /dev/null +++ b/my/twitter/android.py @@ -0,0 +1,93 @@ +""" +Data from offficial app for Android +""" +from struct import unpack_from, calcsize + +from my.core.sqlite import sqlite_connect_immutable + + +def _parse_content(data: bytes): + pos = 0 + + def skip(count: int) -> None: + nonlocal pos + pos += count + + def getstring(slen: int) -> str: + if slen == 1: + lfmt = '>B' + elif slen == 2: + lfmt = '>H' + else: + raise RuntimeError + + (sz,) = unpack_from(lfmt, data, offset=pos) + skip(slen) + assert sz > 0 + assert sz <= 10000 # sanity check? + + # soo, this is how it should ideally work: + # (ss,) = unpack_from(f'{sz}s', data, offset=pos) + # skip(sz) + # however sometimes there is a discrepancy between string length in header and actual length (if you stare at the data) + # example is 1725868458246570412 + # wtf??? (see logging below) + + # ughhhh + seps = [ + b'I\x08', + b'I\x09', + ] + sep_idxs = [data[pos:].find(sep) for sep in seps] + sep_idxs = [i for i in sep_idxs if i != -1] + assert len(sep_idxs) > 0 + sep_idx = min(sep_idxs) + + # print("EXPECTED LEN", sz, "GOT", sep_idx, "DIFF", sep_idx - sz) + + zz = data[pos : pos + sep_idx] + return zz.decode('utf8') + + skip(2) # always starts with 4a03? + + (xx,) = unpack_from('B', data, offset=pos) + skip(1) + # print("TYPE:", xx) + + # wtf is this... maybe it's a bitmask? + slen = { + 66 : 1, + 67 : 2, + 106: 1, + 107: 2, + }[xx] + + try: + print(getstring(slen=slen)) + finally: + pass + # print(data[pos:]) + + +PATH_TO_DB = '/path/to/db' + + +with sqlite_connect_immutable(PATH_TO_DB) as db: + # TODO use statuses table instead? + # has r_ent_content?? + # TODO hmm r_ent_content contains expanded urls? + # but they are still ellipsized? e.g. you can check 1692905005479580039 + # TODO also I think content table has mappings from short urls to full, need to extract + for (tid, blob, blob2) in db.execute( + f'SELECT statuses_status_id, CAST(statuses_content AS BLOB), CAST(statuses_r_ent_content AS BLOB) FROM timeline_view WHERE statuses_bookmarked = 1', + ): + if blob is None: # TODO exclude in sql query? + continue + print("----") + try: + print("PARSING", tid) + _parse_content(blob) + # _parse_content(blob2) + except UnicodeDecodeError as ue: + raise ue + # print("DECODING ERROR FOR ", tid, ue.object) From a4a7bc41b90e3968dfa39b31712f6fb9edc74570 Mon Sep 17 00:00:00 2001 From: karlicoss Date: Sat, 23 Dec 2023 23:14:21 +0000 Subject: [PATCH 023/122] my.twitter.android: extract entities --- my/twitter/android.py | 52 ++++++++++++++++++++++++++++++++++++++----- 1 file changed, 47 insertions(+), 5 deletions(-) diff --git a/my/twitter/android.py b/my/twitter/android.py index ac834df..dbb4946 100644 --- a/my/twitter/android.py +++ b/my/twitter/android.py @@ -1,6 +1,7 @@ """ Data from offficial app for Android """ +import re from struct import unpack_from, calcsize from my.core.sqlite import sqlite_connect_immutable @@ -46,6 +47,7 @@ def _parse_content(data: bytes): # print("EXPECTED LEN", sz, "GOT", sep_idx, "DIFF", sep_idx - sz) zz = data[pos : pos + sep_idx] + skip(sep_idx) return zz.decode('utf8') skip(2) # always starts with 4a03? @@ -62,11 +64,51 @@ def _parse_content(data: bytes): 107: 2, }[xx] - try: - print(getstring(slen=slen)) - finally: - pass - # print(data[pos:]) + text = getstring(slen=slen) + + # after the main tweet text it contains entities (e.g. shortened urls) + # however couldn't reverse engineer the schema properly, the links are kinda all over the place + + # TODO this also contains image alt descriptions? + # see 1665029077034565633 + + extracted = [] + linksep = 0x6a + while True: + m = re.search(b'\x6a.http', data[pos:]) + if m is None: + break + + qq = m.start() + pos += qq + + while True: + if data[pos] != linksep: + break + pos += 1 + (sz,) = unpack_from('B', data, offset=pos) + pos += 1 + (ss,) = unpack_from(f'{sz}s', data, offset=pos) + pos += sz + extracted.append(ss) + + replacements = {} + i = 0 + while i < len(extracted): + if b'https://t.co/' in extracted[i]: + key = extracted[i].decode('utf8') + value = extracted[i + 1].decode('utf8') + i += 2 + replacements[key] = value + else: + i += 1 + + for k, v in replacements.items(): + text = text.replace(k, v) + assert 'https://t.co/' not in text # make sure we detected all links + + print(text) + PATH_TO_DB = '/path/to/db' From 51209c547e7a756d4e21b02512a875a474a26c28 Mon Sep 17 00:00:00 2001 From: karlicoss Date: Sun, 24 Dec 2023 00:06:29 +0000 Subject: [PATCH 024/122] my.twitter.android: refactor into a proper module for now only extracting bookmarks, will use it for some time and see how it goes --- my/config.py | 2 + my/core/common.py | 1 + my/twitter/android.py | 119 +++++++++++++++++++++++++++++++++--------- 3 files changed, 96 insertions(+), 26 deletions(-) diff --git a/my/config.py b/my/config.py index ac44f41..e9b0ec8 100644 --- a/my/config.py +++ b/my/config.py @@ -177,6 +177,8 @@ class twitter_archive: class twitter: class talon: export_path: Paths + class android: + export_path: Paths class twint: diff --git a/my/core/common.py b/my/core/common.py index f1441a9..c429c8c 100644 --- a/my/core/common.py +++ b/my/core/common.py @@ -686,6 +686,7 @@ def unique_everseen( if key is None: # todo check key return type as well? but it's more likely to be hashable if os.environ.get('HPI_CHECK_UNIQUE_EVERSEEN') is not None: + # TODO return better error here, e.g. if there is no return type it crashes _check_all_hashable(fun) return more_itertools.unique_everseen(iterable=iterable, key=key) diff --git a/my/twitter/android.py b/my/twitter/android.py index dbb4946..be411e3 100644 --- a/my/twitter/android.py +++ b/my/twitter/android.py @@ -1,13 +1,49 @@ """ -Data from offficial app for Android +Twitter data from offficial app for Android """ -import re -from struct import unpack_from, calcsize +from __future__ import annotations +from dataclasses import dataclass +from datetime import datetime, timezone +from pathlib import Path +import re +from struct import unpack_from +from typing import Iterator, Sequence + +from my.core import datetime_aware, get_files, LazyLogger, Paths, Res +from my.core.common import unique_everseen from my.core.sqlite import sqlite_connect_immutable +import my.config -def _parse_content(data: bytes): +from .common import permalink + +logger = LazyLogger(__name__) + + +@dataclass +class config(my.config.twitter.android): + # paths[s]/glob to the exported sqlite databases + export_path: Paths + + +def inputs() -> Sequence[Path]: + return get_files(config.export_path) + + +@dataclass(unsafe_hash=True) +class Tweet: + id_str: str + created_at: datetime_aware + screen_name: str + text: str + + @property + def permalink(self) -> str: + return permalink(screen_name=self.screen_name, id=self.id_str) + + +def _parse_content(data: bytes) -> str: pos = 0 def skip(count: int) -> None: @@ -107,29 +143,60 @@ def _parse_content(data: bytes): text = text.replace(k, v) assert 'https://t.co/' not in text # make sure we detected all links - print(text) + return text - -PATH_TO_DB = '/path/to/db' +def _process_one(f: Path) -> Iterator[Res[Tweet]]: + with sqlite_connect_immutable(f) as db: + # NOTE: + # - it also has statuses_r_ent_content which has entities' links replaced + # but they are still ellipsized (e.g. check 1692905005479580039) + # so let's just uses statuses_content + # - there is also timeline_created_at, but they look like made up timestamps + # don't think they represent bookmarking time + # - not sure what's timeline_type? + # seems like 30 means bookmarks? + # there is one tweet with timeline type 18, but it has timeline_is_preview=1 + for ( + tweet_id, + user_name, + user_username, + created_ms, + blob, + ) in db.execute( + ''' + SELECT + statuses_status_id, + users_name, + users_username, + statuses_created, + CAST(statuses_content AS BLOB) + FROM timeline_view + WHERE statuses_bookmarked = 1 + ORDER BY timeline_sort_index DESC + ''', + ): + if blob is None: # TODO exclude in sql query? + continue + yield Tweet( + id_str=tweet_id, + # TODO double check it's utc? + created_at=datetime.fromtimestamp(created_ms / 1000, tz=timezone.utc), + screen_name=user_username, + text=_parse_content(blob), + ) -with sqlite_connect_immutable(PATH_TO_DB) as db: - # TODO use statuses table instead? - # has r_ent_content?? - # TODO hmm r_ent_content contains expanded urls? - # but they are still ellipsized? e.g. you can check 1692905005479580039 - # TODO also I think content table has mappings from short urls to full, need to extract - for (tid, blob, blob2) in db.execute( - f'SELECT statuses_status_id, CAST(statuses_content AS BLOB), CAST(statuses_r_ent_content AS BLOB) FROM timeline_view WHERE statuses_bookmarked = 1', - ): - if blob is None: # TODO exclude in sql query? - continue - print("----") - try: - print("PARSING", tid) - _parse_content(blob) - # _parse_content(blob2) - except UnicodeDecodeError as ue: - raise ue - # print("DECODING ERROR FOR ", tid, ue.object) +def bookmarks() -> Iterator[Res[Tweet]]: + # TODO might need to sort by timeline_sort_index again? + # not sure if each database contains full history of bookmarks (likely not!) + def it() -> Iterator[Res[Tweet]]: + paths = inputs() + total = len(paths) + width = len(str(total)) + for idx, path in enumerate(paths): + logger.info(f'processing [{idx:>{width}}/{total:>{width}}] {path}') + yield from _process_one(path) + + # TODO hmm maybe unique_everseen should be a decorator? + return unique_everseen(it) From 1c452b12d44e8ac79fd9cd3b2590b4dae61c2fba Mon Sep 17 00:00:00 2001 From: karlicoss Date: Thu, 28 Dec 2023 00:04:49 +0000 Subject: [PATCH 025/122] twitter.android: extract likes and own tweets as well --- my/twitter/android.py | 91 ++++++++++++++++++++++++++++++++++--------- 1 file changed, 72 insertions(+), 19 deletions(-) diff --git a/my/twitter/android.py b/my/twitter/android.py index be411e3..a05d15a 100644 --- a/my/twitter/android.py +++ b/my/twitter/android.py @@ -1,5 +1,5 @@ """ -Twitter data from offficial app for Android +Twitter data from official app for Android """ from __future__ import annotations @@ -28,6 +28,9 @@ class config(my.config.twitter.android): def inputs() -> Sequence[Path]: + # NOTE: individual databases are very patchy. + # e.g. some contain hundreds of my bookmarks, whereas other contain just a few + # good motivation for synthetic exports return get_files(config.export_path) @@ -146,17 +149,48 @@ def _parse_content(data: bytes) -> str: return text -def _process_one(f: Path) -> Iterator[Res[Tweet]]: +# NOTE: +# - it also has statuses_r_ent_content which has entities' links replaced +# but they are still ellipsized (e.g. check 1692905005479580039) +# so let's just uses statuses_content +# - there is also timeline_created_at, but they look like made up timestamps +# don't think they represent bookmarking time +# - timeline_type +# 7, 8, 9: some sort of notifications or cursors, should exclude +# 17: ??? some cursors but also tweets +# 18: ??? relatively few, maybe 20 of them, also they all have timeline_is_preview=1? +# most of them have our own id as timeline_sender? +# I think it might actually be 'replies' tab -- also contains some retweets etc +# 26: ??? very low sort index +# 28: weird, contains lots of our own tweets, but also a bunch of unrelated.. +# 29: seems like it contains the favorites! +# 30: seems like it contains the bookmarks +# 34: contains some tweets -- not sure.. +# 63: contains the bulk of data +# 69: ??? just a few tweets +# - timeline_data_type +# 1 : the bulk of tweets, but also some notifications etc?? +# 2 : who-to-follow/community-to-join. contains a couple of tweets, but their corresponding status_id is NULL +# 8 : who-to-follow/notfication +# 13: semantic-core/who-to-follow +# 14: cursor +# 17: trends +# 27: notification +# 31: some superhero crap +# 37: semantic-core +# 42: community-to-join +# - timeline_entity_type +# 1 : contains the bulk of data -- either tweet-*/promoted-tweet-*. However some notification-* and some just contain raw ids?? +# 11: some sort of 'superhero-superhero' crap +# 13: always cursors +# 15: tweet-*/tweet:*/home-conversation-*/trends-*/and lots of other crap +# 31: always notification-* +# - timeline_data_type_group +# 0 : tweets? +# 6 : always notifications?? +# 42: tweets (bulk of them) +def _process_one(f: Path, *, where: str) -> Iterator[Res[Tweet]]: with sqlite_connect_immutable(f) as db: - # NOTE: - # - it also has statuses_r_ent_content which has entities' links replaced - # but they are still ellipsized (e.g. check 1692905005479580039) - # so let's just uses statuses_content - # - there is also timeline_created_at, but they look like made up timestamps - # don't think they represent bookmarking time - # - not sure what's timeline_type? - # seems like 30 means bookmarks? - # there is one tweet with timeline type 18, but it has timeline_is_preview=1 for ( tweet_id, user_name, @@ -164,7 +198,7 @@ def _process_one(f: Path) -> Iterator[Res[Tweet]]: created_ms, blob, ) in db.execute( - ''' + f''' SELECT statuses_status_id, users_name, @@ -172,12 +206,14 @@ def _process_one(f: Path) -> Iterator[Res[Tweet]]: statuses_created, CAST(statuses_content AS BLOB) FROM timeline_view - WHERE statuses_bookmarked = 1 + WHERE timeline_data_type == 1 /* the only one containing tweets (among with some other stuff) */ + AND timeline_data_type_group != 6 /* excludes notifications (some of them even have statuses_bookmarked == 1) */ + AND {where} ORDER BY timeline_sort_index DESC ''', + # TODO not sure about timeline_sort_index for favorites ): - if blob is None: # TODO exclude in sql query? - continue + assert blob is not None # just in case, but should be filtered by the sql query yield Tweet( id_str=tweet_id, # TODO double check it's utc? @@ -186,17 +222,34 @@ def _process_one(f: Path) -> Iterator[Res[Tweet]]: text=_parse_content(blob), ) - -def bookmarks() -> Iterator[Res[Tweet]]: +def _entities(*, where: str) -> Iterator[Res[Tweet]]: # TODO might need to sort by timeline_sort_index again? - # not sure if each database contains full history of bookmarks (likely not!) def it() -> Iterator[Res[Tweet]]: paths = inputs() total = len(paths) width = len(str(total)) for idx, path in enumerate(paths): logger.info(f'processing [{idx:>{width}}/{total:>{width}}] {path}') - yield from _process_one(path) + yield from _process_one(path, where=where) # TODO hmm maybe unique_everseen should be a decorator? return unique_everseen(it) + +def bookmarks() -> Iterator[Res[Tweet]]: + # NOTE: in principle we get the bulk of bookmarks via timeline_type == 30 filter + # however we still might miss on a few (I think the timeline_type 30 only refreshes when you enter bookmarks in the app) + # if you bookmarked in the home feed, it might end up as status_bookmarked == 1 but not necessarily as timeline_type 30 + return _entities(where='statuses_bookmarked == 1') + +def likes() -> Iterator[Res[Tweet]]: + # NOTE: similarly to bookmarks, we could use timeline_type == 29, but it's only refreshed if we actually open likes tab + return _entities(where='statuses_favorited == 1') + +def tweets() -> Iterator[Res[Tweet]]: + # NOTE: seemed like the only way to distinguish our own user reliably? + # could also try matching on users._id == 1, but not sure if it's guaranteed + select_self_user_id = 'SELECT user_id FROM users WHERE extended_profile_fields IS NOT NULL' + + # NOTE: where timeline_type == 18 covers quite a few of our on tweets, but not everything + # querying by our own user id seems the most exhaustive + return _entities(where=f'timeline_sender_id == ({select_self_user_id})') From a0ce666024b0c96a1a36741ba50fc36cbc687183 Mon Sep 17 00:00:00 2001 From: karlicoss Date: Thu, 28 Dec 2023 00:13:01 +0000 Subject: [PATCH 026/122] my.youtube.takeout: fix exception handling --- my/youtube/takeout.py | 1 + 1 file changed, 1 insertion(+) diff --git a/my/youtube/takeout.py b/my/youtube/takeout.py index 79b4549..8fe8f2c 100644 --- a/my/youtube/takeout.py +++ b/my/youtube/takeout.py @@ -37,6 +37,7 @@ def watched() -> Iterable[Res[Watched]]: for e in events(): if isinstance(e, Exception): yield e + continue if not isinstance(e, Activity): continue From 3ec362fce90ae9f8d5b6a9b248c07168ba194089 Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Thu, 28 Dec 2023 18:07:57 +0000 Subject: [PATCH 027/122] fbmessenger.android: expose contacts --- my/fbmessenger/android.py | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/my/fbmessenger/android.py b/my/fbmessenger/android.py index fa313ea..ecf0eb0 100644 --- a/my/fbmessenger/android.py +++ b/my/fbmessenger/android.py @@ -111,12 +111,18 @@ def _process_db_msys(db: sqlite3.Connection) -> Iterator[Res[Entity]]: senders: Dict[str, Sender] = {} for r in db.execute('SELECT CAST(id AS TEXT) AS id, name FROM contacts'): s = Sender( - id=r['id'], + id=r['id'], # looks like it's server id? same used on facebook site name=r['name'], ) + # NOTE https://www.messenger.com/t/{contant_id} for permalink senders[s.id] = s yield s + # TODO what is fb transport?? + # TODO what are client_contacts?? has pk or something + + # TODO client_threads/client_messages -- possibly for end to end encryption or something? + # TODO can we get it from db? could infer as the most common id perhaps? self_id = config.facebook_id thread_users: Dict[str, List[Sender]] = {} @@ -237,6 +243,15 @@ def _process_db_threads_db2(db: sqlite3.Connection) -> Iterator[Res[Entity]]: ) +def contacts() -> Iterator[Res[Sender]]: + for x in unique_everseen(_entities): + if isinstance(x, Exception): + yield x + continue + if isinstance(x, Sender): + yield x + + def messages() -> Iterator[Res[Message]]: senders: Dict[str, Sender] = {} msgs: Dict[str, Message] = {} From 1b187b2c1b35544462eb674052279373e2c88971 Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Fri, 29 Dec 2023 00:53:14 +0000 Subject: [PATCH 028/122] whatsapp.android: expose all entities extracted from the db --- my/whatsapp/android.py | 22 ++++++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/my/whatsapp/android.py b/my/whatsapp/android.py index 295d831..3dfed3e 100644 --- a/my/whatsapp/android.py +++ b/my/whatsapp/android.py @@ -7,7 +7,7 @@ from dataclasses import dataclass from datetime import datetime, timezone from pathlib import Path import sqlite3 -from typing import Sequence, Iterator, Optional +from typing import Union, Sequence, Iterator, Optional from my.core import get_files, Paths, datetime_aware, Res, make_logger, make_config from my.core.common import unique_everseen @@ -56,7 +56,10 @@ class Message: text: Optional[str] -def _process_db(db: sqlite3.Connection): +Entity = Union[Chat, Sender, Message] + + +def _process_db(db: sqlite3.Connection) -> Iterator[Entity]: # TODO later, split out Chat/Sender objects separately to safe on object creation, similar to other android data sources chats = {} @@ -73,6 +76,7 @@ def _process_db(db: sqlite3.Connection): id=chat_id, name=subject, ) + yield chat chats[chat.id] = chat senders = {} @@ -88,6 +92,7 @@ def _process_db(db: sqlite3.Connection): id=r['raw_string'], name=None, ) + yield s senders[r['_id']] = s # NOTE: hmm, seems that message_view or available_message_view use lots of NULL as ... @@ -187,7 +192,7 @@ def _process_db(db: sqlite3.Connection): yield m -def _messages() -> Iterator[Res[Message]]: +def _entities() -> Iterator[Res[Entity]]: paths = inputs() total = len(paths) width = len(str(total)) @@ -200,5 +205,14 @@ def _messages() -> Iterator[Res[Message]]: yield echain(RuntimeError(f'While processing {path}'), cause=e) +def entities() -> Iterator[Res[Entity]]: + return unique_everseen(_entities) + + def messages() -> Iterator[Res[Message]]: - yield from unique_everseen(_messages) + # TODO hmm, specify key=lambda m: m.id? + # not sure since might be useful to keep track of sender changes etc + # probably best not to, or maybe query messages/senders separately and merge later? + for e in entities(): + if isinstance(e, (Exception, Message)): + yield e From 93e475795dabd1ff366c8f1e5993cf566eed5252 Mon Sep 17 00:00:00 2001 From: Sean Breckenridge Date: Sat, 30 Dec 2023 16:52:14 -0800 Subject: [PATCH 029/122] google takeout: support multiple locales uses the known locales in google_takeout_parser to determine the expected paths for each locale, and performs a partial match on the paths to detect and use match_structure --- my/google/takeout/parser.py | 20 +++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) diff --git a/my/google/takeout/parser.py b/my/google/takeout/parser.py index 96acfff..2322ef0 100644 --- a/my/google/takeout/parser.py +++ b/my/google/takeout/parser.py @@ -64,13 +64,19 @@ def inputs() -> Sequence[Path]: return get_files(config.takeout_path) -EXPECTED = ( - "My Activity", - "Chrome", - "Location History", - "Youtube", - "YouTube and YouTube Music", -) +try: + from google_takeout_parser.locales.main import get_paths_for_functions + + EXPECTED = tuple(get_paths_for_functions()) + +except ImportError: + EXPECTED = ( + "My Activity", + "Chrome", + "Location History", + "Youtube", + "YouTube and YouTube Music", + ) google_takeout_version = str(getattr(google_takeout_parser, '__version__', 'unknown')) From 87a8a7781bfb335dfc139a62ca0e04bb8045087f Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Mon, 1 Jan 2024 23:15:43 +0000 Subject: [PATCH 030/122] my.google.maps: intitial module for extracting placed data from Android app --- my/config.py | 4 + my/google/maps/_android_protobuf.py | 113 ++++++++++++++++ my/google/maps/android.py | 202 ++++++++++++++++++++++++++++ tox.ini | 1 + 4 files changed, 320 insertions(+) create mode 100644 my/google/maps/_android_protobuf.py create mode 100644 my/google/maps/android.py diff --git a/my/config.py b/my/config.py index e9b0ec8..a92b2bc 100644 --- a/my/config.py +++ b/my/config.py @@ -68,6 +68,10 @@ class pinboard: export_dir: Paths = '' class google: + class maps: + class android: + export_path: Paths = '' + takeout_path: Paths = '' diff --git a/my/google/maps/_android_protobuf.py b/my/google/maps/_android_protobuf.py new file mode 100644 index 0000000..1d43ae0 --- /dev/null +++ b/my/google/maps/_android_protobuf.py @@ -0,0 +1,113 @@ +from my.core import __NOT_HPI_MODULE__ + +# NOTE: this tool was quite useful https://github.com/aj3423/aproto + +from google.protobuf import descriptor_pool, descriptor_pb2, message_factory + +TYPE_STRING = descriptor_pb2.FieldDescriptorProto.TYPE_STRING +TYPE_BYTES = descriptor_pb2.FieldDescriptorProto.TYPE_BYTES +TYPE_UINT64 = descriptor_pb2.FieldDescriptorProto.TYPE_UINT64 +TYPE_MESSAGE = descriptor_pb2.FieldDescriptorProto.TYPE_MESSAGE + +OPTIONAL = descriptor_pb2.FieldDescriptorProto.LABEL_OPTIONAL +REQUIRED = descriptor_pb2.FieldDescriptorProto.LABEL_REQUIRED + + +def get_place_protos(): + f1 = descriptor_pb2.DescriptorProto(name='xf1') + # TODO 2 -> 5 is address? 2 -> 6 is a pair of coordinates + f1.field.add(name='title', number=3, type=TYPE_STRING, label=REQUIRED) + f1.field.add(name='note' , number=4, type=TYPE_STRING, label=OPTIONAL) + # TODO what's the difference between required and optional? doesn't impact decoding? + + ts = descriptor_pb2.DescriptorProto(name='Timestamp') + ts.field.add(name='seconds', number=1, type=TYPE_UINT64, label=REQUIRED) + ts.field.add(name='nanos' , number=2, type=TYPE_UINT64, label=REQUIRED) + + f1.field.add(name='created', number=10 ,type=TYPE_MESSAGE, label=REQUIRED, type_name=ts.name) + f1.field.add(name='updated', number=11 ,type=TYPE_MESSAGE, label=REQUIRED, type_name=ts.name) + + f2 = descriptor_pb2.DescriptorProto(name='xf2') + f2.field.add(name='addr1', number=2, type=TYPE_STRING, label=REQUIRED) + f2.field.add(name='addr2', number=3, type=TYPE_STRING, label=REQUIRED) + f2.field.add(name='f21' , number=4, type=TYPE_BYTES , label=REQUIRED) + f2.field.add(name='f22' , number=5, type=TYPE_UINT64, label=REQUIRED) + f2.field.add(name='f23' , number=6, type=TYPE_STRING, label=REQUIRED) + # NOTE: this also contains place ID + + f3 = descriptor_pb2.DescriptorProto(name='xf3') + # NOTE: looks like it's the same as 'updated' from above?? + f3.field.add(name='f31', number=1, type=TYPE_UINT64, label=OPTIONAL) + + descriptor_proto = descriptor_pb2.DescriptorProto(name='PlaceParser') + descriptor_proto.field.add(name='f1', number=1, type=TYPE_MESSAGE, label=REQUIRED, type_name=f1.name) + descriptor_proto.field.add(name='f2', number=2, type=TYPE_MESSAGE, label=REQUIRED, type_name=f2.name) + descriptor_proto.field.add(name='f3', number=3, type=TYPE_MESSAGE, label=OPTIONAL, type_name=f3.name) + descriptor_proto.field.add(name='f4', number=4, type=TYPE_STRING , label=OPTIONAL) + # NOTE: f4 is the list id + + return [descriptor_proto, ts, f1, f2, f3] + + +def get_labeled_protos(): + address = descriptor_pb2.DescriptorProto(name='address') + # 1: address + # 2: parts of address (multiple) + # 3: full address + address.field.add(name='full', number=3, type=TYPE_STRING, label=REQUIRED) + + main = descriptor_pb2.DescriptorProto(name='LabeledParser') + # field 1 contains item type and item id + main.field.add(name='title' , number=3, type=TYPE_STRING , label=REQUIRED) + main.field.add(name='address', number=5, type=TYPE_MESSAGE, label=OPTIONAL, type_name=address.name) + + return [main, address] + + +def get_list_protos(): + f1 = descriptor_pb2.DescriptorProto(name='xf1') + f1.field.add(name='name', number=5, type=TYPE_STRING, label=REQUIRED) + + main = descriptor_pb2.DescriptorProto(name='ListParser') + main.field.add(name='f1', number=1, type=TYPE_MESSAGE, label=REQUIRED, type_name=f1.name) + main.field.add(name='f2', number=2, type=TYPE_STRING , label=REQUIRED) + + return [main, f1] + + +def make_parser(main, *extras): + file_descriptor_proto = descriptor_pb2.FileDescriptorProto(name='dynamic.proto', package='dynamic_package') + for proto in [main, *extras]: + file_descriptor_proto.message_type.add().CopyFrom(proto) + + pool = descriptor_pool.DescriptorPool() + file_descriptor = pool.Add(file_descriptor_proto) + + message_descriptor = pool.FindMessageTypeByName(f'{file_descriptor_proto.package}.{main.name}') + factory = message_factory.MessageFactory(pool) + dynamic_message_class = factory.GetPrototype(message_descriptor) + + return dynamic_message_class + + +place_parser_class = make_parser(*get_place_protos()) +labeled_parser_class = make_parser(*get_labeled_protos()) +list_parser_class = make_parser(*get_list_protos()) + + +def parse_place(blob: bytes): + m = place_parser_class() + m.ParseFromString(blob) + return m + + +def parse_labeled(blob: bytes): + m = labeled_parser_class() + m.ParseFromString(blob) + return m + + +def parse_list(blob: bytes): + msg = list_parser_class() + msg.ParseFromString(blob) + return msg diff --git a/my/google/maps/android.py b/my/google/maps/android.py new file mode 100644 index 0000000..279231a --- /dev/null +++ b/my/google/maps/android.py @@ -0,0 +1,202 @@ +""" +Extracts data from the official Google Maps app for Android (uses gmm_sync.db for now) +""" +from __future__ import annotations + +REQUIRES = [ + "protobuf", # for parsing blobs from the database +] + +from dataclasses import dataclass +from datetime import datetime, timezone +from pathlib import Path +from typing import Any, Iterator, Optional, Sequence +from urllib.parse import quote + +from my.core import datetime_aware, get_files, LazyLogger, Paths, Res +from my.core.common import unique_everseen +from my.core.sqlite import sqlite_connection + +import my.config + +from ._android_protobuf import parse_labeled, parse_list, parse_place + + +logger = LazyLogger(__name__) + + +@dataclass +class config(my.config.google.maps.android): + # paths[s]/glob to the exported sqlite databases + export_path: Paths + + +def inputs() -> Sequence[Path]: + # TODO note sure if need to use all dbs? possibly the last one contains everything? + return get_files(config.export_path) + + +PlaceId = str +ListId = str +ListName = str + + +@dataclass(eq=True, frozen=True) +class Location: + lat: float + lon: float + + @property + def url(self) -> str: + return f'https://maps.google.com/?q={self.lat},{self.lon}' + + +@dataclass(unsafe_hash=True) +class Place: + id: PlaceId + list_name: ListName # TODO maybe best to keep list id? + created_at: datetime_aware # TODO double check it's utc? + updated_at: datetime_aware # TODO double check it's utc? + title: str + location: Location + address: Optional[str] + note: Optional[str] + + @property + def place_url(self) -> str: + title = quote(self.title) + return f'https://www.google.com/maps/place/{title}/data=!4m2!3m1!1s{self.id}' + + @property + def location_url(self) -> str: + return self.location.url + + +def _process_one(f: Path): + with sqlite_connection(f, row_factory='row') as conn: + msg: Any + + lists: dict[ListId, ListName] = {} + for row in conn.execute('SELECT * FROM sync_item_data WHERE corpus == 13'): # 13 looks like lists (e.g. saved/favorited etc) + server_id = row['server_id'] + + if server_id is None: + # this is the case for Travel plans, Followed places, Offers + # todo alternatively could use string_index column instead maybe? + continue + + blob = row['item_proto'] + msg = parse_list(blob) + name = msg.f1.name + lists[server_id] = name + + for row in conn.execute('SELECT * FROM sync_item_data WHERE corpus == 11'): # this looks like 'Labeled' list + ts = row['timestamp'] / 1000 + created = datetime.fromtimestamp(ts, tz=timezone.utc) + + server_id = row['server_id'] + [item_type, item_id] = server_id.split(':') + if item_type != '3': + # the ones that are not 3 are home/work address? + continue + + blob = row['item_proto'] + msg = parse_labeled(blob) + address = msg.address.full + if address == '': + address = None + + location = Location(lat=row['latitude_e6'] / 1e6, lon=row['longitude_e6'] / 1e6) + + yield Place( + id=item_id, + list_name='Labeled', + created_at=created, + updated_at=created, # doesn't look like it has 'updated'? + title=msg.title, + location=location, + address=address, + note=None, # don't think these allow notes + ) + + for row in conn.execute('SELECT * FROM sync_item_data WHERE corpus == 14'): # this looks like actual individual places + server_id = row['server_id'] + [list_id, _, id1, id2] = server_id.split(':') + item_id = f'{id1}:{id2}' + + list_name = lists[list_id] + + blob = row['item_proto'] + msg = parse_place(blob) + title = msg.f1.title + note = msg.f1.note + if note == '': # seems that protobuf does that? + note = None + + # TODO double check timezone + created = datetime.fromtimestamp(msg.f1.created.seconds, tz=timezone.utc).replace(microsecond=msg.f1.created.nanos // 1000) + + # NOTE: this one seems to be the same as row['timestamp'] + updated = datetime.fromtimestamp(msg.f1.updated.seconds, tz=timezone.utc).replace(microsecond=msg.f1.updated.nanos // 1000) + + address = msg.f2.addr1 # NOTE: there is also addr2, but they seem identical :shrug: + if address == '': + address = None + + location = Location(lat=row['latitude_e6'] / 1e6, lon=row['longitude_e6'] / 1e6) + + place = Place( + id=item_id, + list_name=list_name, + created_at=created, + updated_at=updated, + title=title, + location=location, + address=address, + note=note, + ) + + # ugh. in my case it's violated by one place by about 1 second?? + # assert place.created_at <= place.updated_at + yield place + + +def saved() -> Iterator[Res[Place]]: + def it() -> Iterator[Res[Place]]: + paths = inputs() + total = len(paths) + width = len(str(total)) + for idx, path in enumerate(paths): + logger.info(f'processing [{idx:>{width}}/{total:>{width}}] {path}') + yield from _process_one(path) + return unique_everseen(it) + + +# Summary of databases on Android (as of 20240101) +# -1_optimized_threads.notifications.db -- empty +# 1_optimized_threads.notifications.db -- empty +# 1_tasks.notifications.db -- empty +# -1_threads.notifications.db -- empty +# 1_threads.notifications.db -- doesn't look like anything interested, some trip anniversaries etc? +# 1_thread_surveys.notifications.db -- empty +# 2_threads.notifications.db -- empty +# accounts.notifications.db -- just one row with account id +# brella_example_store -- empty +# gmm_myplaces.db -- contains just a few places? I think it's a subset of "Labeled" +# gmm_storage.db -- pretty huge, like 50Mb. I suspect it contains cache for places on maps or something +# gmm_sync.db -- processed above +# gnp_fcm_database -- list of accounts +# google_app_measurement_local.db -- empty +# inbox_notifications.db -- nothing interesting +# _room_notifications.db -- trip anniversaties? +# lighter_messaging_1.db -- empty +# lighter_messaging_2.db -- empty +# lighter_registration.db -- empty +# peopleCache__com.google_14.db -- contacts cache or something +# portable_geller_.db -- looks like analytics +# primes_example_store -- looks like analytics +# pseudonymous_room_notifications.db -- looks like analytics +# ue3.db -- empty +# ugc_photos_location_data.db -- empty +# ugc-sync.db -- empty +# updates-tab-visit.db -- empty diff --git a/tox.ini b/tox.ini index e51d0b6..25874f4 100644 --- a/tox.ini +++ b/tox.ini @@ -143,6 +143,7 @@ commands = my.fbmessenger.export \ my.github.ghexport \ my.goodreads \ + my.google.maps.android \ my.google.takeout.parser \ my.hackernews.harmonic \ my.hypothesis \ From 7236024c7a2e2af56c846ae27036e5f281b6c44b Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Tue, 12 Mar 2024 21:59:35 +0000 Subject: [PATCH 031/122] my.twitter.android: better detection of own user id --- my/twitter/android.py | 32 +++++++++++++++++++++++++++----- 1 file changed, 27 insertions(+), 5 deletions(-) diff --git a/my/twitter/android.py b/my/twitter/android.py index a05d15a..fc5d230 100644 --- a/my/twitter/android.py +++ b/my/twitter/android.py @@ -149,6 +149,24 @@ def _parse_content(data: bytes) -> str: return text +_SELECT_OWN_TWEETS = '_SELECT_OWN_TWEETS' + + +def get_own_user_id(conn) -> str: + # unclear what's the reliable way to query it, so we use multiple different ones and arbitrate + # NOTE: 'SELECT DISTINCT ev_owner_id FROM lists' doesn't work, might include lists from other people? + res = set() + for q in [ + 'SELECT DISTINCT list_mapping_user_id FROM list_mapping', + 'SELECT DISTINCT owner_id FROM cursors', + 'SELECT DISTINCT user_id FROM users WHERE _id == 1', + ]: + for (r,) in conn.execute(q): + res.add(r) + assert len(res) == 1, res + return str(list(res)[0]) + + # NOTE: # - it also has statuses_r_ent_content which has entities' links replaced # but they are still ellipsized (e.g. check 1692905005479580039) @@ -191,6 +209,10 @@ def _parse_content(data: bytes) -> str: # 42: tweets (bulk of them) def _process_one(f: Path, *, where: str) -> Iterator[Res[Tweet]]: with sqlite_connect_immutable(f) as db: + if _SELECT_OWN_TWEETS in where: + own_user_id = get_own_user_id(db) + where = where.replace(_SELECT_OWN_TWEETS, own_user_id) + for ( tweet_id, user_name, @@ -222,6 +244,7 @@ def _process_one(f: Path, *, where: str) -> Iterator[Res[Tweet]]: text=_parse_content(blob), ) + def _entities(*, where: str) -> Iterator[Res[Tweet]]: # TODO might need to sort by timeline_sort_index again? def it() -> Iterator[Res[Tweet]]: @@ -235,21 +258,20 @@ def _entities(*, where: str) -> Iterator[Res[Tweet]]: # TODO hmm maybe unique_everseen should be a decorator? return unique_everseen(it) + def bookmarks() -> Iterator[Res[Tweet]]: # NOTE: in principle we get the bulk of bookmarks via timeline_type == 30 filter # however we still might miss on a few (I think the timeline_type 30 only refreshes when you enter bookmarks in the app) # if you bookmarked in the home feed, it might end up as status_bookmarked == 1 but not necessarily as timeline_type 30 return _entities(where='statuses_bookmarked == 1') + def likes() -> Iterator[Res[Tweet]]: # NOTE: similarly to bookmarks, we could use timeline_type == 29, but it's only refreshed if we actually open likes tab return _entities(where='statuses_favorited == 1') -def tweets() -> Iterator[Res[Tweet]]: - # NOTE: seemed like the only way to distinguish our own user reliably? - # could also try matching on users._id == 1, but not sure if it's guaranteed - select_self_user_id = 'SELECT user_id FROM users WHERE extended_profile_fields IS NOT NULL' +def tweets() -> Iterator[Res[Tweet]]: # NOTE: where timeline_type == 18 covers quite a few of our on tweets, but not everything # querying by our own user id seems the most exhaustive - return _entities(where=f'timeline_sender_id == ({select_self_user_id})') + return _entities(where=f'timeline_sender_id == {_SELECT_OWN_TWEETS}') From 0f3d09915cb26860d00535f78289fe1a3bed6794 Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Tue, 12 Mar 2024 22:03:21 +0000 Subject: [PATCH 032/122] ci: update actions versions --- .github/workflows/main.yml | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index f49c6b5..53d8e53 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -45,11 +45,11 @@ jobs: # ugh https://github.com/actions/toolkit/blob/main/docs/commands.md#path-manipulation - run: echo "$HOME/.local/bin" >> $GITHUB_PATH - - uses: actions/setup-python@v4 + - uses: actions/setup-python@v5 with: python-version: ${{ matrix.python-version }} - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 with: submodules: recursive fetch-depth: 0 # nicer to have all git history when debugging/for tests @@ -61,12 +61,12 @@ jobs: - run: bash .ci/run - if: matrix.platform == 'ubuntu-latest' # no need to compute coverage for other platforms - uses: actions/upload-artifact@v3 + uses: actions/upload-artifact@v4 with: name: .coverage.mypy-misc_${{ matrix.platform }}_${{ matrix.python-version }} path: .coverage.mypy-misc/ - if: matrix.platform == 'ubuntu-latest' # no need to compute coverage for other platforms - uses: actions/upload-artifact@v3 + uses: actions/upload-artifact@v4 with: name: .coverage.mypy-core_${{ matrix.platform }}_${{ matrix.python-version }} path: .coverage.mypy-core/ @@ -79,11 +79,11 @@ jobs: # ugh https://github.com/actions/toolkit/blob/main/docs/commands.md#path-manipulation - run: echo "$HOME/.local/bin" >> $GITHUB_PATH - - uses: actions/setup-python@v4 + - uses: actions/setup-python@v5 with: python-version: '3.8' - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 with: submodules: recursive From 477b7e8fd30192b82547573fc78fa99128763f99 Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Tue, 12 Mar 2024 22:03:46 +0000 Subject: [PATCH 033/122] docs: minor update to overlays docs --- doc/OVERLAYS.org | 4 ++++ doc/overlays/install_packages.sh | 4 ++-- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/doc/OVERLAYS.org b/doc/OVERLAYS.org index 98687b7..1e6cf8f 100644 --- a/doc/OVERLAYS.org +++ b/doc/OVERLAYS.org @@ -64,6 +64,10 @@ Verify the setup: This basically means that modules will be searched in both paths, with overlay taking precedence. +** Installing with =--use-pep517= + +See here for discussion https://github.com/seanbreckenridge/reorder_editable/issues/2, but TLDR it should work similarly. + * Testing runtime behaviour (editable install) : $ python3 -c 'import my.reddit as R; print(R.upvotes())' diff --git a/doc/overlays/install_packages.sh b/doc/overlays/install_packages.sh index 3fc38d3..5853e08 100755 --- a/doc/overlays/install_packages.sh +++ b/doc/overlays/install_packages.sh @@ -1,4 +1,4 @@ #!/bin/bash set -eux -pip3 install --user -e overlay/ -pip3 install --user -e main/ +pip3 install --user "$@" -e main/ +pip3 install --user "$@" -e overlay/ From 751ed02f4303ee79d8d89cab3f7175514b1c2f19 Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Tue, 12 Mar 2024 22:16:35 +0000 Subject: [PATCH 034/122] tests: pin pytest version to <8 for now, having some test collection errors https://docs.pytest.org/en/stable/changelog.html#collection-changes --- setup.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/setup.py b/setup.py index b857662..e6bc9fa 100644 --- a/setup.py +++ b/setup.py @@ -47,7 +47,7 @@ def main() -> None: install_requires=INSTALL_REQUIRES, extras_require={ 'testing': [ - 'pytest', + 'pytest<8', # FIXME <8 is temporary workaround till we fix collection with pytest 8; see https://docs.pytest.org/en/stable/changelog.html#collection-changes 'ruff', 'mypy', 'lxml', # for mypy coverage From 103ea2096ee842dd10172ae68574173875a6dbea Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Wed, 13 Mar 2024 00:18:12 +0000 Subject: [PATCH 035/122] my.coding.commits: fix for git repo discovery after fdfind v9 --- my/coding/commits.py | 1 + 1 file changed, 1 insertion(+) diff --git a/my/coding/commits.py b/my/coding/commits.py index 67ee77d..51f9222 100644 --- a/my/coding/commits.py +++ b/my/coding/commits.py @@ -155,6 +155,7 @@ def git_repos_in(roots: List[Path]) -> List[Path]: _fd_path(), # '--follow', # right, not so sure about follow... make configurable? '--hidden', + '--no-ignore', # otherwise doesn't go inside .git directory (from fd v9) '--full-path', '--type', 'f', '/HEAD', # judging by is_git_dir, it should always be here.. From 8a8a1ebb0e8eeaa612bf78e8f3aa6c2fc3942df4 Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Wed, 3 Apr 2024 19:58:44 +0100 Subject: [PATCH 036/122] my.tinder.android: better error handing and fix case with empty db --- my/tinder/android.py | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/my/tinder/android.py b/my/tinder/android.py index 7e5f535..56ee1cb 100644 --- a/my/tinder/android.py +++ b/my/tinder/android.py @@ -92,7 +92,10 @@ def _entities() -> Iterator[Res[_Entity]]: for idx, path in enumerate(paths): logger.info(f'processing [{idx:>{width}}/{total:>{width}}] {path}') with sqlite_connection(path, immutable=True, row_factory='row') as db: - yield from _handle_db(db) + try: + yield from _handle_db(db) + except Exception as e: + yield e def _handle_db(db: sqlite3.Connection) -> Iterator[Res[_Entity]]: @@ -103,8 +106,9 @@ def _handle_db(db: sqlite3.Connection) -> Iterator[Res[_Entity]]: # shit, sometime in 2023 profile_user_view stoppped containing user profile.. # presumably the most common from_id/to_id would be our own username counter = Counter([id_ for (id_,) in db.execute('SELECT from_id FROM message UNION ALL SELECT to_id FROM message')]) - [(you_id, _)] = counter.most_common(1) - yield Person(id=you_id, name='you') + if len(counter) > 0: # this might happen if db is empty (e.g. user got logged out) + [(you_id, _)] = counter.most_common(1) + yield Person(id=you_id, name='you') for row in chain( user_profile_rows, From 35dd5d82a0e399f684fb3d09763bab44146927fc Mon Sep 17 00:00:00 2001 From: seanbreckenridge Date: Wed, 5 Jun 2024 14:03:03 -0700 Subject: [PATCH 037/122] smscalls: parse mms from smscalls export (#370) * initial mms exploration --- my/smscalls.py | 162 +++++++++++++++++++++++++++++++++++++++++++++- tests/smscalls.py | 3 +- 2 files changed, 163 insertions(+), 2 deletions(-) diff --git a/my/smscalls.py b/my/smscalls.py index dbcf8b2..23fb5cc 100644 --- a/my/smscalls.py +++ b/my/smscalls.py @@ -20,7 +20,7 @@ config = make_config(smscalls) from datetime import datetime, timezone from pathlib import Path -from typing import NamedTuple, Iterator, Set, Tuple, Optional +from typing import NamedTuple, Iterator, Set, Tuple, Optional, Any, Dict, List from lxml import etree @@ -150,6 +150,165 @@ def _extract_messages(path: Path) -> Iterator[Res[Message]]: ) +class MMSContentPart(NamedTuple): + sequence_index: int + content_type: str + filename: str + text: Optional[str] + data: Optional[str] + + +class MMS(NamedTuple): + dt: datetime + dt_readable: str + parts: List[MMSContentPart] + # NOTE: these is often something like 'Name 1, Name 2', but might be different depending on your client + who: Optional[str] + # NOTE: This can be a single phone number, or multiple, split by '~' or ','. Its better to think + # of this as a 'key' or 'conversation ID', phone numbers are also present in 'addresses' + phone_number: str + addresses: List[Tuple[str, int]] + # 1 = Received, 2 = Sent, 3 = Draft, 4 = Outbox + message_type: int + + @property + def from_user(self) -> str: + # since these can be group messages, we can't just check message_type, + # we need to iterate through and find who sent it + # who is CC/'To' is not obvious in many message clients + # + # 129 = BCC, 130 = CC, 151 = To, 137 = From + for (addr, _type) in self.addresses: + if _type == 137: + return addr + else: + # hmm, maybe return instead? but this probably shouldnt happen, means + # something is very broken + raise RuntimeError(f'No from address matching 137 found in {self.addresses}') + + @property + def from_me(self) -> bool: + return self.message_type == 2 + + +def mms() -> Iterator[Res[MMS]]: + files = get_files(config.export_path, glob='sms-*.xml') + + emitted: Set[Tuple[datetime, Optional[str], str]] = set() + for p in files: + for c in _extract_mms(p): + if isinstance(c, Exception): + yield c + continue + key = (c.dt, c.phone_number, c.from_user) + if key in emitted: + continue + emitted.add(key) + yield c + + +def _resolve_null_str(value: Optional[str]) -> Optional[str]: + if value is None: + return None + # hmm.. theres some risk of the text actually being 'null', but theres + # no way to distinguish that from XML values + if value == 'null': + return None + return value + + +def _extract_mms(path: Path) -> Iterator[Res[MMS]]: + tr = etree.parse(str(path)) + + for mxml in tr.findall('mms'): + dt = mxml.get('date') + dt_readable = mxml.get('readable_date') + message_type = mxml.get('msg_box') + + who = mxml.get('contact_name') + if who is not None and who in UNKNOWN: + who = None + phone_number = mxml.get('address') + + if dt is None or dt_readable is None or message_type is None or phone_number is None: + mxml_str = etree.tostring(mxml).decode('utf-8') + yield RuntimeError(f'Missing one or more required attributes [date, readable_date, msg_box, address] in {mxml_str}') + continue + + addresses: List[Tuple[str, int]] = [] + for addr_parent in mxml.findall('addrs'): + for addr in addr_parent.findall('addr'): + addr_data = addr.attrib + user_address = addr_data.get('address') + user_type = addr_data.get('type') + if user_address is None or user_type is None: + addr_str = etree.tostring(addr_parent).decode() + yield RuntimeError(f'Missing one or more required attributes [address, type] in {addr_str}') + continue + if not user_type.isdigit(): + yield RuntimeError(f'Invalid address type {user_type} {type(user_type)}, cannot convert to number') + continue + addresses.append((user_address, int(user_type))) + + content: List[MMSContentPart] = [] + + for part_root in mxml.findall('parts'): + + for part in part_root.findall('part'): + + # the first item is an SMIL XML element encoded as a string which describes + # how the rest of the parts are laid out + # https://www.w3.org/TR/SMIL3/smil-timing.html#Timing-TimeContainerSyntax + # An example: + # + # + # This seems pretty useless, so we should try and skip it, and just return the + # text/images/data + # + # man, attrib is some internal cpython ._Attrib type which can't + # be typed by any sort of mappingproxy. maybe a protocol could work..? + part_data: Dict[str, Any] = part.attrib # type: ignore + seq: Optional[str] = part_data.get('seq') + if seq == '-1': + continue + + if seq is None or not seq.isdigit(): + yield RuntimeError(f'seq must be a number, was seq={seq} {type(seq)} in {part_data}') + continue + + charset_type: Optional[str] = _resolve_null_str(part_data.get('ct')) + filename: Optional[str] = _resolve_null_str(part_data.get('name')) + # in some cases (images, cards), the filename is set in 'cl' instead + if filename is None: + filename = _resolve_null_str(part_data.get('cl')) + text: Optional[str] = _resolve_null_str(part_data.get('text')) + data: Optional[str] = _resolve_null_str(part_data.get('data')) + + if charset_type is None or filename is None or (text is None and data is None): + yield RuntimeError(f'Missing one or more required attributes [ct, name, (text, data)] must be present in {part_data}') + continue + + content.append( + MMSContentPart( + sequence_index=int(seq), + content_type=charset_type, + filename=filename, + text=text, + data=data + ) + ) + + yield MMS( + dt=_parse_dt_ms(dt), + dt_readable=dt_readable, + who=who, + phone_number=phone_number, + message_type=int(message_type), + parts=content, + addresses=addresses, + ) + + # See https://github.com/karlicoss/HPI/pull/90#issuecomment-702422351 # for potentially parsing timezone from the readable_date def _parse_dt_ms(d: str) -> datetime: @@ -162,4 +321,5 @@ def stats() -> Stats: return { **stat(calls), **stat(messages), + **stat(mms), } diff --git a/tests/smscalls.py b/tests/smscalls.py index d063de1..ef78786 100644 --- a/tests/smscalls.py +++ b/tests/smscalls.py @@ -4,6 +4,7 @@ from my.tests.common import skip_if_not_karlicoss as pytestmark # TODO implement via stat? def test() -> None: - from my.smscalls import calls, messages + from my.smscalls import calls, messages, mms assert len(list(calls())) > 10 assert len(list(messages())) > 10 + assert len(list(mms())) > 10 From c9c0e1954313b1ae531791ea1a361265ace2776f Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Sat, 3 Aug 2024 15:03:55 +0100 Subject: [PATCH 038/122] my.instagram.gdpr: fix for new format --- my/instagram/gdpr.py | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/my/instagram/gdpr.py b/my/instagram/gdpr.py index 233f040..1415d55 100644 --- a/my/instagram/gdpr.py +++ b/my/instagram/gdpr.py @@ -1,6 +1,7 @@ """ Instagram data (uses [[https://www.instagram.com/download/request][official GDPR export]]) """ + from dataclasses import dataclass from datetime import datetime import json @@ -103,7 +104,12 @@ def _entitites_from_path(path: Path) -> Iterator[Res[Union[User, _Message]]]: # old path, used up to somewhere between feb-aug 2022 personal_info = path / 'account_information' - j = json.loads((personal_info / 'personal_information.json').read_text()) + personal_info_json = personal_info / 'personal_information.json' + if not personal_info_json.exists(): + # new path, started somewhere around april 2024 + personal_info_json = personal_info / 'personal_information' / 'personal_information.json' + + j = json.loads(personal_info_json.read_text()) [profile] = j['profile_user'] pdata = profile['string_map_data'] username = pdata['Username']['value'] From 0e6dd32afe1a49de3dacecaede7ee149ab67e4b9 Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Sat, 3 Aug 2024 15:27:11 +0100 Subject: [PATCH 039/122] ci: minor fixes after mypy update --- my/core/common.py | 12 ++++++------ my/core/error.py | 4 ++-- my/core/query.py | 4 ++-- my/core/query_range.py | 2 +- my/core/serialize.py | 7 ++++--- my/instagram/android.py | 2 +- ruff.toml | 2 +- tox.ini | 2 +- 8 files changed, 18 insertions(+), 17 deletions(-) diff --git a/my/core/common.py b/my/core/common.py index c429c8c..f7bb010 100644 --- a/my/core/common.py +++ b/my/core/common.py @@ -1,6 +1,7 @@ from glob import glob as do_glob from pathlib import Path from datetime import datetime +from dataclasses import is_dataclass, asdict as dataclasses_asdict import functools from contextlib import contextmanager import os @@ -292,15 +293,14 @@ Json = Dict[str, Any] from typing import TypeVar, Callable, Generic -_C = TypeVar('_C') _R = TypeVar('_R') # https://stackoverflow.com/a/5192374/706389 class classproperty(Generic[_R]): - def __init__(self, f: Callable[[_C], _R]) -> None: + def __init__(self, f: Callable[..., _R]) -> None: self.f = f - def __get__(self, obj: None, cls: _C) -> _R: + def __get__(self, obj, cls) -> _R: return self.f(cls) @@ -580,9 +580,9 @@ def asdict(thing: Any) -> Json: # todo exception? if isinstance(thing, dict): return thing - import dataclasses as D - if D.is_dataclass(thing): - return D.asdict(thing) + if is_dataclass(thing): + assert not isinstance(thing, type) # to help mypy + return dataclasses_asdict(thing) if is_namedtuple(thing): return thing._asdict() raise TypeError(f'Could not convert object {thing} to dict') diff --git a/my/core/error.py b/my/core/error.py index e1737c1..fa59137 100644 --- a/my/core/error.py +++ b/my/core/error.py @@ -195,7 +195,7 @@ def warn_my_config_import_error(err: Union[ImportError, AttributeError], help_ur import click if help_url is None: help_url = MODULE_SETUP_URL - if type(err) == ImportError: + if type(err) is ImportError: if err.name != 'my.config': return False # parse name that user attempted to import @@ -207,7 +207,7 @@ You may be missing the '{section_name}' section from your config. See {help_url}\ """, fg='yellow', err=True) return True - elif type(err) == AttributeError: + elif type(err) is AttributeError: # test if user had a nested config block missing # https://github.com/karlicoss/HPI/issues/223 if hasattr(err, 'obj') and hasattr(err, "name"): diff --git a/my/core/query.py b/my/core/query.py index 7c22838..071f7e0 100644 --- a/my/core/query.py +++ b/my/core/query.py @@ -214,7 +214,7 @@ def _determine_order_by_value_key(obj_res: ET) -> Any: Returns either the class, or a tuple of the dictionary keys """ key = obj_res.__class__ - if key == dict: + if key is dict: # assuming same keys signify same way to determine ordering return tuple(obj_res.keys()) # type: ignore[union-attr] return key @@ -583,7 +583,7 @@ def test_couldnt_determine_order() -> None: res = list(select(iter([object()]), order_value=lambda o: isinstance(o, datetime))) assert len(res) == 1 assert isinstance(res[0], Unsortable) - assert type(res[0].obj) == object + assert type(res[0].obj) is object # same value type, different keys, with clashing keys diff --git a/my/core/query_range.py b/my/core/query_range.py index dfb9e55..2b3a3d3 100644 --- a/my/core/query_range.py +++ b/my/core/query_range.py @@ -471,7 +471,7 @@ def test_range_predicate() -> None: ) # filter from 0 to 5 - rn: Optional[RangeTuple] = RangeTuple("0", "5", None) + rn: RangeTuple = RangeTuple("0", "5", None) zero_to_five_filter: Optional[Where] = int_filter_func(unparsed_range=rn) assert zero_to_five_filter is not None # this is just a Where function, given some input it return True/False if the value is allowed diff --git a/my/core/serialize.py b/my/core/serialize.py index c5f4cba..1f55f40 100644 --- a/my/core/serialize.py +++ b/my/core/serialize.py @@ -1,5 +1,5 @@ import datetime -import dataclasses +from dataclasses import is_dataclass, asdict from pathlib import Path from decimal import Decimal from typing import Any, Optional, Callable, NamedTuple @@ -33,8 +33,9 @@ def _default_encode(obj: Any) -> Any: # convert paths to their string representation if isinstance(obj, Path): return str(obj) - if dataclasses.is_dataclass(obj): - return dataclasses.asdict(obj) + if is_dataclass(obj): + assert not isinstance(obj, type) # to help mypy + return asdict(obj) if isinstance(obj, Exception): return error_to_json(obj) # if something was stored as 'decimal', you likely diff --git a/my/instagram/android.py b/my/instagram/android.py index ea5ee35..96b75d2 100644 --- a/my/instagram/android.py +++ b/my/instagram/android.py @@ -92,7 +92,7 @@ class MessageError(RuntimeError): super().__init__(msg_id, *rest) self.rest = rest - def __hash__(self, other): + def __hash__(self): return hash(self.rest) def __eq__(self, other) -> bool: diff --git a/ruff.toml b/ruff.toml index 0be93e0..54f621c 100644 --- a/ruff.toml +++ b/ruff.toml @@ -1,4 +1,4 @@ -ignore = [ +lint.ignore = [ ### too opinionated style checks "E501", # too long lines "E702", # Multiple statements on one line (semicolon) diff --git a/tox.ini b/tox.ini index 25874f4..0676eef 100644 --- a/tox.ini +++ b/tox.ini @@ -26,7 +26,7 @@ passenv = [testenv:ruff] commands = {envpython} -m pip install --use-pep517 -e .[testing] - {envpython} -m ruff my/ + {envpython} -m ruff check my/ # just the very core tests with minimal dependencies From d5fccf1874f5306445830377d5418776ccaa4ede Mon Sep 17 00:00:00 2001 From: karlicoss Date: Thu, 28 Dec 2023 02:07:27 +0000 Subject: [PATCH 040/122] twitter.android: more comments on timeline types --- my/twitter/android.py | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/my/twitter/android.py b/my/twitter/android.py index fc5d230..af16b11 100644 --- a/my/twitter/android.py +++ b/my/twitter/android.py @@ -1,6 +1,7 @@ """ Twitter data from official app for Android """ + from __future__ import annotations from dataclasses import dataclass @@ -93,12 +94,11 @@ def _parse_content(data: bytes) -> str: (xx,) = unpack_from('B', data, offset=pos) skip(1) - # print("TYPE:", xx) # wtf is this... maybe it's a bitmask? slen = { - 66 : 1, - 67 : 2, + 66: 1, + 67: 2, 106: 1, 107: 2, }[xx] @@ -112,7 +112,7 @@ def _parse_content(data: bytes) -> str: # see 1665029077034565633 extracted = [] - linksep = 0x6a + linksep = 0x6A while True: m = re.search(b'\x6a.http', data[pos:]) if m is None: @@ -175,7 +175,8 @@ def get_own_user_id(conn) -> str: # don't think they represent bookmarking time # - timeline_type # 7, 8, 9: some sort of notifications or cursors, should exclude -# 17: ??? some cursors but also tweets +# 14: some converstaionthread stuff? +# 17: ??? some cursors but also tweets NOTE: they seem to contribute to user's tweets data, so make sure not to delete # 18: ??? relatively few, maybe 20 of them, also they all have timeline_is_preview=1? # most of them have our own id as timeline_sender? # I think it might actually be 'replies' tab -- also contains some retweets etc From 9e72672b4f765dc1807ac15990322a0a4087648b Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Sat, 3 Aug 2024 16:43:10 +0100 Subject: [PATCH 041/122] legacy google takeout: fix timezone localization --- my/google/takeout/html.py | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/my/google/takeout/html.py b/my/google/takeout/html.py index 5d65a86..d393957 100644 --- a/my/google/takeout/html.py +++ b/my/google/takeout/html.py @@ -5,12 +5,14 @@ Google Takeout exports: browsing history, search/youtube/google play activity from enum import Enum import re from pathlib import Path -from datetime import datetime, timezone +from datetime import datetime from html.parser import HTMLParser from typing import List, Optional, Any, Callable, Iterable, Tuple from collections import OrderedDict from urllib.parse import unquote +import pytz + from ...core.time import abbr_to_timezone @@ -29,7 +31,8 @@ def parse_dt(s: str) -> datetime: # old takeouts didn't have timezone # hopefully it was utc? Legacy, so no that much of an issue anymore.. # todo although maybe worth adding timezone from location provider? - tz = timezone.utc + # note: need to use pytz here for localize call later + tz = pytz.utc else: s, tzabbr = s.rsplit(maxsplit=1) tz = abbr_to_timezone(tzabbr) From 652ee9b875275d25ca4cbfdee4f63c8f822b3ba7 Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Sat, 3 Aug 2024 18:45:22 +0100 Subject: [PATCH 042/122] fbmessenger.android: fix minor issue with processing thread participants --- my/fbmessenger/android.py | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/my/fbmessenger/android.py b/my/fbmessenger/android.py index ecf0eb0..8a4bf4c 100644 --- a/my/fbmessenger/android.py +++ b/my/fbmessenger/android.py @@ -1,6 +1,7 @@ """ Messenger data from Android app database (in =/data/data/com.facebook.orca/databases/threads_db2=) """ + from __future__ import annotations from dataclasses import dataclass @@ -111,7 +112,7 @@ def _process_db_msys(db: sqlite3.Connection) -> Iterator[Res[Entity]]: senders: Dict[str, Sender] = {} for r in db.execute('SELECT CAST(id AS TEXT) AS id, name FROM contacts'): s = Sender( - id=r['id'], # looks like it's server id? same used on facebook site + id=r['id'], # looks like it's server id? same used on facebook site name=r['name'], ) # NOTE https://www.messenger.com/t/{contant_id} for permalink @@ -129,14 +130,17 @@ def _process_db_msys(db: sqlite3.Connection) -> Iterator[Res[Entity]]: for r in db.execute('SELECT CAST(thread_key AS TEXT) AS thread_key, CAST(contact_id AS TEXT) AS contact_id FROM participants'): thread_key = r['thread_key'] user_key = r['contact_id'] - if self_id is not None and user_key == self_id: - # exclude yourself, otherwise it's just spammy to show up in all participants - continue ll = thread_users.get(thread_key) if ll is None: ll = [] thread_users[thread_key] = ll + + if self_id is not None and user_key == self_id: + # exclude yourself, otherwise it's just spammy to show up in all participants + # TODO not sure about that, maybe change later + continue + ll.append(senders[user_key]) # 15 is a weird thread that doesn't have any participants and messages From 2c63fe25c0aedcf11f83053cc1fcd1868fb7bacc Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Mon, 5 Aug 2024 22:53:25 +0100 Subject: [PATCH 043/122] my.twitter.android: get data from statues table rather that timeline_view --- my/twitter/android.py | 95 +++++++++++++++++++++++++++---------------- 1 file changed, 60 insertions(+), 35 deletions(-) diff --git a/my/twitter/android.py b/my/twitter/android.py index af16b11..f40ad0e 100644 --- a/my/twitter/android.py +++ b/my/twitter/android.py @@ -9,7 +9,7 @@ from datetime import datetime, timezone from pathlib import Path import re from struct import unpack_from -from typing import Iterator, Sequence +from typing import Iterator, Sequence, Set from my.core import datetime_aware, get_files, LazyLogger, Paths, Res from my.core.common import unique_everseen @@ -209,41 +209,66 @@ def get_own_user_id(conn) -> str: # 6 : always notifications?? # 42: tweets (bulk of them) def _process_one(f: Path, *, where: str) -> Iterator[Res[Tweet]]: + # meh... maybe separate this function into special ones for tweets/bookmarks/likes + select_own = _SELECT_OWN_TWEETS in where with sqlite_connect_immutable(f) as db: - if _SELECT_OWN_TWEETS in where: + if select_own: own_user_id = get_own_user_id(db) - where = where.replace(_SELECT_OWN_TWEETS, own_user_id) + db_where = where.replace(_SELECT_OWN_TWEETS, own_user_id) + else: + db_where = where - for ( - tweet_id, - user_name, - user_username, - created_ms, - blob, - ) in db.execute( - f''' + # NOTE: we used to get this from 'timeline_view' + # however seems that it's missing a fair amount of data that's present instatuses table... + QUERY = ''' SELECT - statuses_status_id, - users_name, - users_username, - statuses_created, - CAST(statuses_content AS BLOB) - FROM timeline_view - WHERE timeline_data_type == 1 /* the only one containing tweets (among with some other stuff) */ - AND timeline_data_type_group != 6 /* excludes notifications (some of them even have statuses_bookmarked == 1) */ - AND {where} - ORDER BY timeline_sort_index DESC - ''', - # TODO not sure about timeline_sort_index for favorites - ): - assert blob is not None # just in case, but should be filtered by the sql query - yield Tweet( - id_str=tweet_id, - # TODO double check it's utc? - created_at=datetime.fromtimestamp(created_ms / 1000, tz=timezone.utc), - screen_name=user_username, - text=_parse_content(blob), - ) + CAST(statuses.status_id AS TEXT), /* int by default */ + users.username, + statuses.created, + CAST(statuses.content AS BLOB), + statuses.quoted_tweet_id + FROM statuses FULL OUTER JOIN users + ON statuses.author_id == users.user_id + WHERE + /* there are sometimes a few shitty statuses in the db with weird ids which are duplicating other tweets + don't want to filter by status_id < 10 ** 10, since there might legit be statuses with low ids? + so this is the best I came up with.. + */ + NOT (statuses.in_r_user_id == -1 AND statuses.in_r_status_id == -1 AND statuses.conversation_id == 0) + ''' + + def _query_one(*, where: str, quoted: Set[int]) -> Iterator[Res[Tweet]]: + for ( + tweet_id, + user_username, + created_ms, + blob, + quoted_id, + ) in db.execute(f'{QUERY} AND {where}'): + quoted.add(quoted_id) # if no quoted tweet, id is 0 here + + try: + content = _parse_content(blob) + except Exception as e: + yield e + continue + + yield Tweet( + id_str=tweet_id, + # TODO double check it's utc? + created_at=datetime.fromtimestamp(created_ms / 1000, tz=timezone.utc), + screen_name=user_username, + text=content, + ) + + quoted: Set[int] = set() + yield from _query_one(where=db_where, quoted=quoted) + # get quoted tweets 'recursively' + # TODO maybe do it for favs/bookmarks too? not sure + while select_own and len(quoted) > 0: + db_where = 'status_id IN (' + ','.join(map(str, sorted(quoted))) + ')' + quoted = set() + yield from _query_one(where=db_where, quoted=quoted) def _entities(*, where: str) -> Iterator[Res[Tweet]]: @@ -264,15 +289,15 @@ def bookmarks() -> Iterator[Res[Tweet]]: # NOTE: in principle we get the bulk of bookmarks via timeline_type == 30 filter # however we still might miss on a few (I think the timeline_type 30 only refreshes when you enter bookmarks in the app) # if you bookmarked in the home feed, it might end up as status_bookmarked == 1 but not necessarily as timeline_type 30 - return _entities(where='statuses_bookmarked == 1') + return _entities(where='statuses.bookmarked == 1') def likes() -> Iterator[Res[Tweet]]: # NOTE: similarly to bookmarks, we could use timeline_type == 29, but it's only refreshed if we actually open likes tab - return _entities(where='statuses_favorited == 1') + return _entities(where='statuses.favorited == 1') def tweets() -> Iterator[Res[Tweet]]: # NOTE: where timeline_type == 18 covers quite a few of our on tweets, but not everything # querying by our own user id seems the most exhaustive - return _entities(where=f'timeline_sender_id == {_SELECT_OWN_TWEETS}') + return _entities(where=f'users.user_id == {_SELECT_OWN_TWEETS} OR statuses.retweeted == 1') From b615ba10b15df8dee8406a62b56feb829ab1fbf9 Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Mon, 5 Aug 2024 23:15:49 +0100 Subject: [PATCH 044/122] ci: temporary suppress pandas mypy error in check_dateish --- my/core/pandas.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/my/core/pandas.py b/my/core/pandas.py index 1b7a644..621682f 100644 --- a/my/core/pandas.py +++ b/my/core/pandas.py @@ -50,7 +50,7 @@ def check_dateish(s: SeriesT[S1]) -> Iterable[str]: all_timestamps = s.apply(lambda x: isinstance(x, (pd.Timestamp, datetime))).all() if not all_timestamps: return # not sure why it would happen, but ok - tzs = s.map(lambda x: x.tzinfo).drop_duplicates() + tzs = s.map(lambda x: x.tzinfo).drop_duplicates() # type: ignore[union-attr, var-annotated, arg-type, return-value, unused-ignore] examples = s[tzs.index] # todo not so sure this warning is that useful... except for stuff without tz yield f''' From 3aebc573e80f3686e218eeb924a29b92221e5020 Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Tue, 6 Aug 2024 20:41:50 +0100 Subject: [PATCH 045/122] tests: use updated conftest from pymplate, this allows to run individual test modules properly e.g. pytest --pyargs my.core.tests.test_get_files --- conftest.py | 47 +++++++++++++++++++++++++++++++++ my/core/tests/test_get_files.py | 9 +++++-- 2 files changed, 54 insertions(+), 2 deletions(-) create mode 100644 conftest.py diff --git a/conftest.py b/conftest.py new file mode 100644 index 0000000..b959cfa --- /dev/null +++ b/conftest.py @@ -0,0 +1,47 @@ +# this is a hack to monkey patch pytest so it handles tests inside namespace packages without __init__.py properly +# without it, pytest can't discover the package root for some reason +# also see https://github.com/karlicoss/pytest_namespace_pkgs for more + +import os +import pathlib +from typing import Optional + +import _pytest.main +import _pytest.pathlib + +# we consider all dirs in repo/ to be namespace packages +root_dir = pathlib.Path(__file__).absolute().parent.resolve() # / 'src' +assert root_dir.exists(), root_dir + +# TODO assert it contains package name?? maybe get it via setuptools.. + +namespace_pkg_dirs = [str(d) for d in root_dir.iterdir() if d.is_dir()] + +# resolve_package_path is called from _pytest.pathlib.import_path +# takes a full abs path to the test file and needs to return the path to the 'root' package on the filesystem +resolve_pkg_path_orig = _pytest.pathlib.resolve_package_path +def resolve_package_path(path: pathlib.Path) -> Optional[pathlib.Path]: + result = path # search from the test file upwards + for parent in result.parents: + if str(parent) in namespace_pkg_dirs: + return parent + if os.name == 'nt': + # ??? for some reason on windows it is trying to call this against conftest? but not on linux/osx + if path.name == 'conftest.py': + return resolve_pkg_path_orig(path) + raise RuntimeError("Couldn't determine path for ", path) +_pytest.pathlib.resolve_package_path = resolve_package_path + + +# without patching, the orig function returns just a package name for some reason +# (I think it's used as a sort of fallback) +# so we need to point it at the absolute path properly +# not sure what are the consequences.. maybe it wouldn't be able to run against installed packages? not sure.. +search_pypath_orig = _pytest.main.search_pypath +def search_pypath(module_name: str) -> str: + mpath = root_dir / module_name.replace('.', os.sep) + if not mpath.is_dir(): + mpath = mpath.with_suffix('.py') + assert mpath.exists(), mpath # just in case + return str(mpath) +_pytest.main.search_pypath = search_pypath diff --git a/my/core/tests/test_get_files.py b/my/core/tests/test_get_files.py index 2bdc903..e9f216a 100644 --- a/my/core/tests/test_get_files.py +++ b/my/core/tests/test_get_files.py @@ -175,12 +175,17 @@ TMP = tempfile.gettempdir() test_path = Path(TMP) / 'hpi_test' -def setup(): +@pytest.fixture(autouse=True) +def prepare(): teardown() test_path.mkdir() + try: + yield + finally: + teardown() -def teardown(): +def teardown() -> None: if test_path.is_dir(): shutil.rmtree(test_path) From fb8e9909a498c16a92e276e13e40ab8fb1ce189c Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Tue, 6 Aug 2024 23:09:56 +0100 Subject: [PATCH 046/122] tests: simplify tests for my.core.serialize a bit and simplify tox file --- my/core/pytest.py | 22 ++++++ my/core/serialize.py | 127 ++++++++++++++++++++++------------ setup.py | 5 +- tests/serialize.py | 1 - tests/serialize_simplejson.py | 23 ------ tox.ini | 19 +---- 6 files changed, 109 insertions(+), 88 deletions(-) create mode 100644 my/core/pytest.py delete mode 100644 tests/serialize.py delete mode 100644 tests/serialize_simplejson.py diff --git a/my/core/pytest.py b/my/core/pytest.py new file mode 100644 index 0000000..a2596fb --- /dev/null +++ b/my/core/pytest.py @@ -0,0 +1,22 @@ +""" +Helpers to prevent depending on pytest in runtime +""" + +from .common import assert_subpackage; assert_subpackage(__name__) + +import sys +import typing + +under_pytest = 'pytest' in sys.modules + +if typing.TYPE_CHECKING or under_pytest: + import pytest + + parametrize = pytest.mark.parametrize +else: + + def parametrize(*args, **kwargs): + def wrapper(f): + return f + + return wrapper diff --git a/my/core/serialize.py b/my/core/serialize.py index 1f55f40..563e114 100644 --- a/my/core/serialize.py +++ b/my/core/serialize.py @@ -2,11 +2,12 @@ import datetime from dataclasses import is_dataclass, asdict from pathlib import Path from decimal import Decimal -from typing import Any, Optional, Callable, NamedTuple +from typing import Any, Optional, Callable, NamedTuple, Protocol from functools import lru_cache from .common import is_namedtuple from .error import error_to_json +from .pytest import parametrize # note: it would be nice to combine the 'asdict' and _default_encode to some function # that takes a complex python object and returns JSON-compatible fields, while still @@ -16,6 +17,8 @@ from .error import error_to_json DefaultEncoder = Callable[[Any], Any] +Dumps = Callable[[Any], str] + def _default_encode(obj: Any) -> Any: """ @@ -75,22 +78,29 @@ def _dumps_factory(**kwargs) -> Callable[[Any], str]: kwargs["default"] = use_default - try: - import orjson + prefer_factory: Optional[str] = kwargs.pop('_prefer_factory', None) + + def orjson_factory() -> Optional[Dumps]: + try: + import orjson + except ModuleNotFoundError: + return None # todo: add orjson.OPT_NON_STR_KEYS? would require some bitwise ops # most keys are typically attributes from a NT/Dataclass, # so most seem to work: https://github.com/ijl/orjson#opt_non_str_keys - def _orjson_dumps(obj: Any) -> str: + def _orjson_dumps(obj: Any) -> str: # TODO rename? # orjson returns json as bytes, encode to string return orjson.dumps(obj, **kwargs).decode('utf-8') return _orjson_dumps - except ModuleNotFoundError: - pass - try: - from simplejson import dumps as simplejson_dumps + def simplejson_factory() -> Optional[Dumps]: + try: + from simplejson import dumps as simplejson_dumps + except ModuleNotFoundError: + return None + # if orjson couldn't be imported, try simplejson # This is included for compatibility reasons because orjson # is rust-based and compiling on rarer architectures may not work @@ -105,18 +115,37 @@ def _dumps_factory(**kwargs) -> Callable[[Any], str]: return _simplejson_dumps - except ModuleNotFoundError: - pass + def stdlib_factory() -> Optional[Dumps]: + import json + from .warnings import high - import json - from .warnings import high + high( + "You might want to install 'orjson' to support serialization for lots more types! If that does not work for you, you can install 'simplejson' instead" + ) - high("You might want to install 'orjson' to support serialization for lots more types! If that does not work for you, you can install 'simplejson' instead") + def _stdlib_dumps(obj: Any) -> str: + return json.dumps(obj, **kwargs) - def _stdlib_dumps(obj: Any) -> str: - return json.dumps(obj, **kwargs) + return _stdlib_dumps - return _stdlib_dumps + factories = { + 'orjson': orjson_factory, + 'simplejson': simplejson_factory, + 'stdlib': stdlib_factory, + } + + if prefer_factory is not None: + factory = factories[prefer_factory] + res = factory() + assert res is not None, prefer_factory + return res + + for factory in factories.values(): + res = factory() + if res is not None: + return res + else: + raise RuntimeError("Should not happen!") def dumps( @@ -154,8 +183,17 @@ def dumps( return _dumps_factory(default=default, **kwargs)(obj) -def test_serialize_fallback() -> None: - import json as jsn # dont cause possible conflicts with module code +@parametrize('factory', ['orjson', 'simplejson', 'stdlib']) +def test_dumps(factory: str) -> None: + import pytest + + orig_dumps = globals()['dumps'] # hack to prevent error from using local variable before declaring + + def dumps(*args, **kwargs) -> str: + kwargs['_prefer_factory'] = factory + return orig_dumps(*args, **kwargs) + + import json as json_builtin # dont cause possible conflicts with module code # can't use a namedtuple here, since the default json.dump serializer # serializes namedtuples as tuples, which become arrays @@ -166,36 +204,12 @@ def test_serialize_fallback() -> None: # the lru_cache'd warning may have already been sent, # so checking may be nondeterministic? import warnings + with warnings.catch_warnings(): warnings.simplefilter("ignore") - res = jsn.loads(dumps(X)) + res = json_builtin.loads(dumps(X)) assert res == [5, 5.0] - -# this needs to be defined here to prevent a mypy bug -# see https://github.com/python/mypy/issues/7281 -class _A(NamedTuple): - x: int - y: float - - -def test_nt_serialize() -> None: - import json as jsn # dont cause possible conflicts with module code - import orjson # import to make sure this is installed - - res: str = dumps(_A(x=1, y=2.0)) - assert res == '{"x":1,"y":2.0}' - - # test orjson option kwarg - data = {datetime.date(year=1970, month=1, day=1): 5} - res2 = jsn.loads(dumps(data, option=orjson.OPT_NON_STR_KEYS)) - assert res2 == {'1970-01-01': 5} - - -def test_default_serializer() -> None: - import pytest - import json as jsn # dont cause possible conflicts with module code - class Unserializable: def __init__(self, x: int): self.x = x @@ -209,7 +223,7 @@ def test_default_serializer() -> None: def _serialize(self) -> Any: return {"x": self.x, "y": self.y} - res = jsn.loads(dumps(WithUnderscoreSerialize(6))) + res = json_builtin.loads(dumps(WithUnderscoreSerialize(6))) assert res == {"x": 6, "y": 6.0} # test passing additional 'default' func @@ -221,5 +235,26 @@ def test_default_serializer() -> None: # this serializes both Unserializable, which is a custom type otherwise # not handled, and timedelta, which is handled by the '_default_encode' # in the 'wrapped_default' function - res2 = jsn.loads(dumps(Unserializable(10), default=_serialize_with_default)) + res2 = json_builtin.loads(dumps(Unserializable(10), default=_serialize_with_default)) assert res2 == {"x": 10, "y": 10.0} + + if factory == 'orjson': + import orjson + + # test orjson option kwarg + data = {datetime.date(year=1970, month=1, day=1): 5} + res2 = json_builtin.loads(dumps(data, option=orjson.OPT_NON_STR_KEYS)) + assert res2 == {'1970-01-01': 5} + + +@parametrize('factory', ['orjson', 'simplejson']) +def test_dumps_namedtuple(factory: str) -> None: + import json as json_builtin # dont cause possible conflicts with module code + import orjson # import to make sure this is installed + + class _A(NamedTuple): + x: int + y: float + + res: str = dumps(_A(x=1, y=2.0), _prefer_factory=factory) + assert json_builtin.loads(res) == {'x': 1, 'y': 2.0} diff --git a/setup.py b/setup.py index e6bc9fa..ab96616 100644 --- a/setup.py +++ b/setup.py @@ -47,13 +47,16 @@ def main() -> None: install_requires=INSTALL_REQUIRES, extras_require={ 'testing': [ - 'pytest<8', # FIXME <8 is temporary workaround till we fix collection with pytest 8; see https://docs.pytest.org/en/stable/changelog.html#collection-changes + 'pytest', 'ruff', 'mypy', 'lxml', # for mypy coverage # used in some tests.. although shouldn't rely on it 'pandas', + + 'orjson', # for my.core.serialize and denylist + 'simplejson', # for my.core.serialize ], 'optional': [ # todo document these? diff --git a/tests/serialize.py b/tests/serialize.py deleted file mode 100644 index d9ee9a3..0000000 --- a/tests/serialize.py +++ /dev/null @@ -1 +0,0 @@ -from my.core.serialize import * diff --git a/tests/serialize_simplejson.py b/tests/serialize_simplejson.py deleted file mode 100644 index d421a15..0000000 --- a/tests/serialize_simplejson.py +++ /dev/null @@ -1,23 +0,0 @@ -''' -This file should only run when simplejson is installed, -but orjson is not installed to check compatibility -''' - -# none of these should fail - -import json -import simplejson -import pytest - -from my.core.serialize import dumps, _A - -def test_simplejson_fallback() -> None: - - # should fail to import - with pytest.raises(ModuleNotFoundError): - import orjson - - # simplejson should serialize namedtuple properly - res: str = dumps(_A(x=1, y=2.0)) - assert json.loads(res) == {"x": 1, "y": 2.0} - diff --git a/tox.ini b/tox.ini index 0676eef..0b75b44 100644 --- a/tox.ini +++ b/tox.ini @@ -34,14 +34,11 @@ commands = commands = {envpython} -m pip install --use-pep517 -e .[testing] - # seems that denylist tests rely on it? ideally we should get rid of this in tests-core - {envpython} -m pip install orjson - {envpython} -m pytest \ # importlib is the new suggested import-mode # without it test package names end up as core.tests.* instead of my.core.tests.* --import-mode=importlib \ - --pyargs my.core \ + --pyargs {[testenv]package_name}.core \ # ignore orgmode because it imports orgparse # tbh not sure if it even belongs to core, maybe move somewhere else.. # same with pandas? @@ -49,9 +46,6 @@ commands = # causes error during test collection on 3.8 # dataset is deprecated anyway so whatever --ignore my/core/dataset.py \ - # this test uses orjson which is an optional dependency - # it would be covered by tests-all - -k 'not test_nt_serialize' \ {posargs} @@ -63,14 +57,7 @@ setenv = MY_CONFIG = nonexistent commands = {envpython} -m pip install --use-pep517 -e .[testing] - # installed to test my.core.serialize while using simplejson and not orjson - {envpython} -m pip install simplejson - {envpython} -m pytest \ - tests/serialize_simplejson.py \ - {posargs} - {envpython} -m pip install cachew - {envpython} -m pip install orjson {envpython} -m my.core module install my.location.google {envpython} -m pip install ijson # optional dependency @@ -103,9 +90,7 @@ commands = {envpython} -m pytest tests \ # ignore some tests which might take a while to run on ci.. --ignore tests/takeout.py \ - --ignore tests/extra/polar.py \ - # dont run simplejson compatibility test since orjson is now installed - --ignore tests/serialize_simplejson.py \ + --ignore tests/extra/polar.py {posargs} From 074e24c3098aed3da81155c51f6afb1c28debc46 Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Tue, 6 Aug 2024 23:44:01 +0100 Subject: [PATCH 047/122] general: deprecate my.core.dataset and simplify tox file --- my/core/_deprecated/dataset.py | 12 ++++++++++++ my/core/dataset.py | 32 +++----------------------------- my/core/serialize.py | 3 +-- tox.ini | 3 --- 4 files changed, 16 insertions(+), 34 deletions(-) create mode 100644 my/core/_deprecated/dataset.py diff --git a/my/core/_deprecated/dataset.py b/my/core/_deprecated/dataset.py new file mode 100644 index 0000000..9cca2fd --- /dev/null +++ b/my/core/_deprecated/dataset.py @@ -0,0 +1,12 @@ +from ..common import PathIsh +from ..sqlite import sqlite_connect_immutable + + +def connect_readonly(db: PathIsh): + import dataset # type: ignore + + # see https://github.com/pudo/dataset/issues/136#issuecomment-128693122 + # todo not sure if mode=ro has any benefit, but it doesn't work on read-only filesystems + # maybe it should autodetect readonly filesystems and apply this? not sure + creator = lambda: sqlite_connect_immutable(db) + return dataset.connect('sqlite:///', engine_kwargs={'creator': creator}) diff --git a/my/core/dataset.py b/my/core/dataset.py index 31de4f4..40237a0 100644 --- a/my/core/dataset.py +++ b/my/core/dataset.py @@ -1,31 +1,5 @@ -from __future__ import annotations -from .common import assert_subpackage; assert_subpackage(__name__) +from . import warnings -from .common import PathIsh -from .sqlite import sqlite_connect_immutable +warnings.high(f"{__name__} is deprecated, please use dataset directly if you need or switch to my.core.sqlite") -## sadly dataset doesn't have any type definitions -from typing import Iterable, Iterator, Dict, Optional, Any, Protocol -from contextlib import AbstractContextManager - - -# NOTE: may not be true in general, but will be in the vast majority of cases -row_type_T = Dict[str, Any] - - -class TableT(Iterable, Protocol): - def find(self, *, order_by: Optional[str]=None) -> Iterator[row_type_T]: ... - - -class DatabaseT(AbstractContextManager['DatabaseT'], Protocol): - def __getitem__(self, table: str) -> TableT: ... -## - -# TODO wonder if also need to open without WAL.. test this on read-only directory/db file -def connect_readonly(db: PathIsh) -> DatabaseT: - import dataset # type: ignore - # see https://github.com/pudo/dataset/issues/136#issuecomment-128693122 - # todo not sure if mode=ro has any benefit, but it doesn't work on read-only filesystems - # maybe it should autodetect readonly filesystems and apply this? not sure - creator = lambda: sqlite_connect_immutable(db) - return dataset.connect('sqlite:///', engine_kwargs={'creator': creator}) +from ._deprecated.dataset import * diff --git a/my/core/serialize.py b/my/core/serialize.py index 563e114..b5b1b3a 100644 --- a/my/core/serialize.py +++ b/my/core/serialize.py @@ -2,7 +2,7 @@ import datetime from dataclasses import is_dataclass, asdict from pathlib import Path from decimal import Decimal -from typing import Any, Optional, Callable, NamedTuple, Protocol +from typing import Any, Optional, Callable, NamedTuple from functools import lru_cache from .common import is_namedtuple @@ -250,7 +250,6 @@ def test_dumps(factory: str) -> None: @parametrize('factory', ['orjson', 'simplejson']) def test_dumps_namedtuple(factory: str) -> None: import json as json_builtin # dont cause possible conflicts with module code - import orjson # import to make sure this is installed class _A(NamedTuple): x: int diff --git a/tox.ini b/tox.ini index 0b75b44..02acdfc 100644 --- a/tox.ini +++ b/tox.ini @@ -43,9 +43,6 @@ commands = # tbh not sure if it even belongs to core, maybe move somewhere else.. # same with pandas? --ignore my/core/orgmode.py \ - # causes error during test collection on 3.8 - # dataset is deprecated anyway so whatever - --ignore my/core/dataset.py \ {posargs} From 34593c032d7360f09642da889a6ca0b236bda810 Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Wed, 7 Aug 2024 00:55:30 +0100 Subject: [PATCH 048/122] tests: move more tests into core, more consistent tests running in tox --- my/core/tests/auto_stats.py | 1 + my/core/tests/common.py | 12 +++++ my/core/tests/test_cachew.py | 53 ++++++++++++++++++++ my/core/tests/test_common.py | 54 +++++++++++++++++++++ my/tests/common.py | 2 +- tests/misc.py | 94 ------------------------------------ tox.ini | 10 ++-- 7 files changed, 127 insertions(+), 99 deletions(-) create mode 100644 my/core/tests/common.py create mode 100644 my/core/tests/test_cachew.py create mode 100644 my/core/tests/test_common.py delete mode 100644 tests/misc.py diff --git a/my/core/tests/auto_stats.py b/my/core/tests/auto_stats.py index 2c09b5b..bf4764c 100644 --- a/my/core/tests/auto_stats.py +++ b/my/core/tests/auto_stats.py @@ -1,6 +1,7 @@ """ Helper 'module' for test_guess_stats """ + from contextlib import contextmanager from dataclasses import dataclass from datetime import datetime, timedelta diff --git a/my/core/tests/common.py b/my/core/tests/common.py new file mode 100644 index 0000000..d6fb71e --- /dev/null +++ b/my/core/tests/common.py @@ -0,0 +1,12 @@ +import os + +import pytest + + +V = 'HPI_TESTS_USES_OPTIONAL_DEPS' + +# TODO use it for serialize tests that are using simplejson/orjson? +skip_if_uses_optional_deps = pytest.mark.skipif( + V not in os.environ, + reason=f'test only works when optional dependencies are installed. Set env variable {V}=true to override.', +) diff --git a/my/core/tests/test_cachew.py b/my/core/tests/test_cachew.py new file mode 100644 index 0000000..86344fd --- /dev/null +++ b/my/core/tests/test_cachew.py @@ -0,0 +1,53 @@ +from .common import skip_if_uses_optional_deps as pytestmark + +from typing import List + +# TODO ugh, this is very messy.. need to sort out config overriding here + + +def test_cachew() -> None: + from cachew import settings + + settings.ENABLE = True # by default it's off in tests (see conftest.py) + + from my.core.common import mcachew + + called = 0 + + # TODO ugh. need doublewrap or something to avoid having to pass parens + @mcachew() + def cf() -> List[int]: + nonlocal called + called += 1 + return [1, 2, 3] + + list(cf()) + cc = called + # todo ugh. how to clean cache? + # assert called == 1 # precondition, to avoid turdes from previous tests + + assert list(cf()) == [1, 2, 3] + assert called == cc + + +def test_cachew_dir_none() -> None: + from cachew import settings + + settings.ENABLE = True # by default it's off in tests (see conftest.py) + + from my.core.cachew import cache_dir + from my.core.common import mcachew + from my.core.core_config import _reset_config as reset + + with reset() as cc: + cc.cache_dir = None + called = 0 + + @mcachew(cache_path=cache_dir() / 'ctest') + def cf() -> List[int]: + nonlocal called + called += 1 + return [called, called, called] + + assert list(cf()) == [1, 1, 1] + assert list(cf()) == [2, 2, 2] diff --git a/my/core/tests/test_common.py b/my/core/tests/test_common.py new file mode 100644 index 0000000..a2019e4 --- /dev/null +++ b/my/core/tests/test_common.py @@ -0,0 +1,54 @@ +from typing import Iterable, List +import warnings + +from ..common import ( + warn_if_empty, + _warn_iterable, +) + + +def test_warn_if_empty() -> None: + @warn_if_empty + def nonempty() -> Iterable[str]: + yield 'a' + yield 'aba' + + @warn_if_empty + def empty() -> List[int]: + return [] + + # should be rejected by mypy! + # todo how to actually test it? + # @warn_if_empty + # def baad() -> float: + # return 0.00 + + # reveal_type(nonempty) + # reveal_type(empty) + + with warnings.catch_warnings(record=True) as w: + assert list(nonempty()) == ['a', 'aba'] + assert len(w) == 0 + + eee = empty() + assert eee == [] + assert len(w) == 1 + + +def test_warn_iterable() -> None: + i1: List[str] = ['a', 'b'] + i2: Iterable[int] = iter([1, 2, 3]) + # reveal_type(i1) + # reveal_type(i2) + x1 = _warn_iterable(i1) + x2 = _warn_iterable(i2) + # vvvv this should be flagged by mypy + # _warn_iterable(123) + # reveal_type(x1) + # reveal_type(x2) + with warnings.catch_warnings(record=True) as w: + assert x1 is i1 # should be unchanged! + assert len(w) == 0 + + assert list(x2) == [1, 2, 3] + assert len(w) == 0 diff --git a/my/tests/common.py b/my/tests/common.py index c8d88ff..e3060e1 100644 --- a/my/tests/common.py +++ b/my/tests/common.py @@ -9,7 +9,7 @@ V = 'HPI_TESTS_KARLICOSS' skip_if_not_karlicoss = pytest.mark.skipif( V not in os.environ, - reason=f'test only works on @karlicoss data for now. Set evn variable {V}=true to override.', + reason=f'test only works on @karlicoss data for now. Set env variable {V}=true to override.', ) diff --git a/tests/misc.py b/tests/misc.py deleted file mode 100644 index 7e666d7..0000000 --- a/tests/misc.py +++ /dev/null @@ -1,94 +0,0 @@ -from typing import Iterable, List -import warnings -from my.core import warn_if_empty - - -def test_warn_if_empty() -> None: - @warn_if_empty - def nonempty() -> Iterable[str]: - yield 'a' - yield 'aba' - - @warn_if_empty - def empty() -> List[int]: - return [] - - # should be rejected by mypy! - # todo how to actually test it? - # @warn_if_empty - # def baad() -> float: - # return 0.00 - - # reveal_type(nonempty) - # reveal_type(empty) - - with warnings.catch_warnings(record=True) as w: - assert list(nonempty()) == ['a', 'aba'] - assert len(w) == 0 - - eee = empty() - assert eee == [] - assert len(w) == 1 - - -def test_warn_iterable() -> None: - from my.core.common import _warn_iterable - i1: List[str] = ['a', 'b'] - i2: Iterable[int] = iter([1, 2, 3]) - # reveal_type(i1) - # reveal_type(i2) - x1 = _warn_iterable(i1) - x2 = _warn_iterable(i2) - # vvvv this should be flagged by mypy - # _warn_iterable(123) - # reveal_type(x1) - # reveal_type(x2) - with warnings.catch_warnings(record=True) as w: - assert x1 is i1 # should be unchanged! - assert len(w) == 0 - - assert list(x2) == [1, 2, 3] - assert len(w) == 0 - - -def test_cachew() -> None: - from cachew import settings - settings.ENABLE = True # by default it's off in tests (see conftest.py) - - from my.core.cachew import cache_dir - from my.core.common import mcachew - - called = 0 - # FIXME ugh. need doublewrap or something - @mcachew() - def cf() -> List[int]: - nonlocal called - called += 1 - return [1, 2, 3] - - list(cf()) - cc = called - # todo ugh. how to clean cache? - # assert called == 1 # precondition, to avoid turdes from previous tests - - assert list(cf()) == [1, 2, 3] - assert called == cc - - -def test_cachew_dir_none() -> None: - from cachew import settings - settings.ENABLE = True # by default it's off in tests (see conftest.py) - - from my.core.cachew import cache_dir - from my.core.common import mcachew - from my.core.core_config import _reset_config as reset - with reset() as cc: - cc.cache_dir = None - called = 0 - @mcachew(cache_path=cache_dir() / 'ctest') - def cf() -> List[int]: - nonlocal called - called += 1 - return [called, called, called] - assert list(cf()) == [1, 1, 1] - assert list(cf()) == [2, 2, 2] diff --git a/tox.ini b/tox.ini index 02acdfc..248469e 100644 --- a/tox.ini +++ b/tox.ini @@ -48,9 +48,11 @@ commands = # todo maybe also have core tests and misc tests? since ideally want them without dependencies [testenv:tests-all] -# deliberately set to nonexistent path to check the fallback logic -# TODO not sure if need it? -setenv = MY_CONFIG = nonexistent +setenv = + # deliberately set to nonexistent path to check the fallback logic + # TODO not sure if need it? + MY_CONFIG=nonexistent + HPI_TESTS_USES_OPTIONAL_DEPS=true commands = {envpython} -m pip install --use-pep517 -e .[testing] @@ -81,7 +83,7 @@ commands = # importlib is the new suggested import-mode # without it test package names end up as core.tests.* instead of my.core.tests.* --import-mode=importlib \ - --pyargs {[testenv]package_name}.tests \ + --pyargs {[testenv]package_name}.core {[testenv]package_name}.tests \ {posargs} {envpython} -m pytest tests \ From c69a0b43baeffb1fae5f35b5914f07040d1c30b6 Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Sat, 10 Aug 2024 18:35:30 +0300 Subject: [PATCH 049/122] my.vk.favorites: some minor cleanup --- my/vk/favorites.py | 36 +++++++++++++++++------------------- 1 file changed, 17 insertions(+), 19 deletions(-) diff --git a/my/vk/favorites.py b/my/vk/favorites.py index eb1a89b..9caae6d 100644 --- a/my/vk/favorites.py +++ b/my/vk/favorites.py @@ -1,29 +1,27 @@ -# todo: uses my private export script? -from datetime import datetime +# todo: uses my private export script?, timezone +from dataclasses import dataclass +from datetime import datetime, timezone import json -from typing import NamedTuple, Iterable, Sequence, Optional +from typing import Iterator, Iterable, Optional +from my.core import Json, datetime_aware, stat, Stats +from my.core.error import Res from my.config import vk as config # type: ignore[attr-defined] -class Favorite(NamedTuple): - dt: datetime +@dataclass +class Favorite: + dt: datetime_aware title: str url: Optional[str] text: str -from ..core import Json -from ..core.error import Res - - skip = ( 'graffiti', 'poll', - - # TODO could be useful.. - 'note', + 'note', # TODO could be useful.. 'doc', 'audio', 'photo', @@ -32,10 +30,11 @@ skip = ( 'page', ) + def parse_fav(j: Json) -> Favorite: # TODO copy_history?? url = None - title = '' # TODO ??? + title = '' # TODO ??? atts = j.get('attachments', []) for a in atts: if any(k in a for k in skip): @@ -47,14 +46,14 @@ def parse_fav(j: Json) -> Favorite: # TODO would be nice to include user return Favorite( - dt=datetime.utcfromtimestamp(j['date']), + dt=datetime.fromtimestamp(j['date'], tz=timezone.utc), title=title, url=url, text=j['text'], ) -def _iter_favs() -> Iterable[Res]: +def _iter_favs() -> Iterator[Res]: jj = json.loads(config.favs_file.read_text()) for j in jj: try: @@ -65,7 +64,7 @@ def _iter_favs() -> Iterable[Res]: yield ex -def favorites() -> Sequence[Res]: +def favorites() -> Iterable[Res]: it = _iter_favs() # trick to sort errors along with the actual objects # TODO wonder if there is a shorter way? @@ -76,12 +75,11 @@ def favorites() -> Sequence[Res]: for i, f in enumerate(favs): if not isinstance(f, Exception): prev = f.dt - keys.append((prev, i)) # include index to resolve ties + keys.append((prev, i)) # include index to resolve ties sorted_items = [p[1] for p in sorted(zip(keys, favs))] # return sorted_items -def stats(): - from ..core import stat +def stats() -> Stats: return stat(favorites) From 069264ce52046d0feeee9fd46850339354256900 Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Sat, 10 Aug 2024 19:28:28 +0300 Subject: [PATCH 050/122] core.common: get rid of deprecated utcfromtimestamp --- my/core/common.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/my/core/common.py b/my/core/common.py index f7bb010..98dbacb 100644 --- a/my/core/common.py +++ b/my/core/common.py @@ -511,10 +511,10 @@ def _stat_iterable(it: Iterable[C], quick: bool = False) -> Any: def test_stat_iterable() -> None: - from datetime import datetime, timedelta + from datetime import datetime, timedelta, timezone from typing import NamedTuple - dd = datetime.utcfromtimestamp(123) + dd = datetime.fromtimestamp(123, tz=timezone.utc) day = timedelta(days=3) X = NamedTuple('X', [('x', int), ('d', datetime)]) From 1e1e8d8494c5296d276c1191d8581f6d2df3833c Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Sat, 10 Aug 2024 23:42:32 +0300 Subject: [PATCH 051/122] my.topcoder: get rid of kjson in favor of using builtin dict methods --- my/core/compat.py | 6 +++ my/topcoder.py | 104 ++++++++++++++++++++++++++-------------------- 2 files changed, 65 insertions(+), 45 deletions(-) diff --git a/my/core/compat.py b/my/core/compat.py index 9cdea27..e984695 100644 --- a/my/core/compat.py +++ b/my/core/compat.py @@ -115,3 +115,9 @@ def test_fromisoformat() -> None: # assert isoparse('2017-07-18T18:59:38.21731Z') == datetime( # 2017, 7, 18, 18, 59, 38, 217310, timezone.utc, # ) + + +if sys.version_info[:2] >= (3, 10): + from types import NoneType +else: + NoneType = type(None) diff --git a/my/topcoder.py b/my/topcoder.py index 7432379..d9631dc 100644 --- a/my/topcoder.py +++ b/my/topcoder.py @@ -1,77 +1,91 @@ from my.config import topcoder as config # type: ignore[attr-defined] -from datetime import datetime +from dataclasses import dataclass from functools import cached_property import json -from typing import NamedTuple, Iterator +from pathlib import Path +from typing import Iterator, Sequence + +from my.core import get_files, Res, datetime_aware +from my.core.compat import fromisoformat, NoneType -from my.core import get_files, Res, Json -from my.core.konsume import zoom, wrap, ignore +def inputs() -> Sequence[Path]: + return get_files(config.export_path) -def _get_latest() -> Json: - pp = max(get_files(config.export_path)) - return json.loads(pp.read_text()) - - -class Competition(NamedTuple): +@dataclass +class Competition: contest_id: str contest: str percentile: float - dates: str + date_str: str @cached_property def uid(self) -> str: return self.contest_id - def __hash__(self): - return hash(self.contest_id) - @cached_property - def when(self) -> datetime: - return datetime.strptime(self.dates, '%Y-%m-%dT%H:%M:%S.%fZ') + def when(self) -> datetime_aware: + return fromisoformat(self.date_str) @cached_property def summary(self) -> str: return f'participated in {self.contest}: {self.percentile:.0f}' @classmethod - def make(cls, json) -> Iterator[Res['Competition']]: - ignore(json, 'rating', 'placement') - cid = json['challengeId'].zoom().value - cname = json['challengeName'].zoom().value - percentile = json['percentile'].zoom().value - dates = json['date'].zoom().value + def make(cls, j) -> Iterator[Res['Competition']]: + assert isinstance(j.pop('rating'), float) + assert isinstance(j.pop('placement'), int) + + cid = j.pop('challengeId') + cname = j.pop('challengeName') + percentile = j.pop('percentile') + date_str = j.pop('date') + yield cls( contest_id=cid, contest=cname, percentile=percentile, - dates=dates, + date_str=date_str, ) +def _parse_one(p: Path) -> Iterator[Res[Competition]]: + j = json.loads(p.read_text()) + + # this is kind of an experiment to parse it exhaustively, making sure we don't miss any data + assert isinstance(j.pop('version'), str) + assert isinstance(j.pop('id'), str) + [j] = j.values() # zoom in + + assert j.pop('success') is True, j + assert j.pop('status') == 200, j + assert j.pop('metadata') is None, j + [j] = j.values() # zoom in + + # todo hmm, potentially error handling could be nicer since .pop just reports key error + # also by the time error is reported, key is already removed? + for k in ['handle', 'handleLower', 'userId', 'createdAt', 'updatedAt', 'createdBy', 'updatedBy']: + # check it's primitive + assert isinstance(j.pop(k), (str, bool, float, int, NoneType)), k + + j.pop('DEVELOP') # TODO how to handle it? + [j] = j.values() # zoom in, DATA_SCIENCE section + + mm = j.pop('MARATHON_MATCH') + [mm] = mm.values() # zoom into historu + + srm = j.pop('SRM') + [srm] = srm.values() # zoom into history + + assert len(j) == 0, j + + for c in mm + srm: + yield from Competition.make(j=c) + + def data() -> Iterator[Res[Competition]]: - with wrap(_get_latest()) as j: - ignore(j, 'id', 'version') - - res = j['result'].zoom() # type: ignore[index] - ignore(res, 'success', 'status', 'metadata') - - cont = res['content'].zoom() - ignore(cont, 'handle', 'handleLower', 'userId', 'createdAt', 'updatedAt', 'createdBy', 'updatedBy') - - cont['DEVELOP'].ignore() # TODO handle it?? - ds = cont['DATA_SCIENCE'].zoom() - - mar, srm = zoom(ds, 'MARATHON_MATCH', 'SRM') - - mar = mar['history'].zoom() - srm = srm['history'].zoom() - # TODO right, I guess I could rely on pylint for unused variables?? - - for c in mar + srm: - yield from Competition.make(json=c) - c.consume() - + *_, last = inputs() + return _parse_one(last) From 1317914bfff217e747edcc93f8167b2bad14f3fb Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Mon, 12 Aug 2024 14:56:18 +0300 Subject: [PATCH 052/122] general: add 'destructive parsing' (kinda what we were doing in my.core.konsume) to my.experimental also some cleanup for my.codeforces and my.topcoder --- my/codeforces.py | 126 ++++++++++++------------- my/core/konsume.py | 31 ++++++ my/experimental/destructive_parsing.py | 60 ++++++++++++ my/topcoder.py | 63 +++++++------ 4 files changed, 183 insertions(+), 97 deletions(-) create mode 100644 my/experimental/destructive_parsing.py diff --git a/my/codeforces.py b/my/codeforces.py index a97c360..7b37ec6 100644 --- a/my/codeforces.py +++ b/my/codeforces.py @@ -1,86 +1,80 @@ -from my.config import codeforces as config # type: ignore[attr-defined] - - +from dataclasses import dataclass from datetime import datetime, timezone from functools import cached_property import json -from typing import NamedTuple, Dict, Iterator +from pathlib import Path +from typing import Dict, Iterator, Sequence + +from my.core import get_files, Res, datetime_aware +from my.core.common import assert_never + +from my.config import codeforces as config # type: ignore[attr-defined] -from my.core import get_files, Res -from my.core.konsume import ignore, wrap +def inputs() -> Sequence[Path]: + return get_files(config.export_path) -Cid = int - -class Contest(NamedTuple): - cid: Cid - when: datetime - - @classmethod - def make(cls, j) -> 'Contest': - return cls( - cid=j['id'], - when=datetime.fromtimestamp(j['startTimeSeconds'], tz=timezone.utc), - ) - -Cmap = Dict[Cid, Contest] +ContestId = int -def get_contests() -> Cmap: - last = max(get_files(config.export_path, 'allcontests*.json')) - j = json.loads(last.read_text()) - d = {} - for c in j['result']: - cc = Contest.make(c) - d[cc.cid] = cc - return d +@dataclass +class Contest: + contest_id: ContestId + when: datetime_aware + name: str -class Competition(NamedTuple): - contest_id: Cid - contest: str - cmap: Cmap +@dataclass +class Competition: + contest: Contest + old_rating: int + new_rating: int @cached_property - def uid(self) -> Cid: - return self.contest_id + def when(self) -> datetime_aware: + return self.contest.when - def __hash__(self): - return hash(self.contest_id) - @cached_property - def when(self) -> datetime: - return self.cmap[self.uid].when +# todo not sure if parser is the best name? hmm +class Parser: + def __init__(self, *, inputs: Sequence[Path]) -> None: + self.inputs = inputs + self.contests: Dict[ContestId, Contest] = {} - @cached_property - def summary(self) -> str: - return f'participated in {self.contest}' # TODO + def _parse_allcontests(self, p: Path) -> Iterator[Contest]: + j = json.loads(p.read_text()) + for c in j['result']: + yield Contest( + contest_id=c['id'], + when=datetime.fromtimestamp(c['startTimeSeconds'], tz=timezone.utc), + name=c['name'], + ) - @classmethod - def make(cls, cmap, json) -> Iterator[Res['Competition']]: - # TODO try here?? - contest_id = json['contestId'].zoom().value - contest = json['contestName'].zoom().value - yield cls( - contest_id=contest_id, - contest=contest, - cmap=cmap, - ) - # TODO ytry??? - ignore(json, 'rank', 'oldRating', 'newRating') + def _parse_competitions(self, p: Path) -> Iterator[Competition]: + j = json.loads(p.read_text()) + for c in j['result']: + contest_id = c['contestId'] + contest = self.contests[contest_id] + yield Competition( + contest=contest, + old_rating=c['oldRating'], + new_rating=c['newRating'], + ) + + def parse(self) -> Iterator[Res[Competition]]: + for path in inputs(): + if 'allcontests' in path.name: + # these contain information about all CF contests along with useful metadata + for contest in self._parse_allcontests(path): + # TODO some method to assert on mismatch if it exists? not sure + self.contests[contest.contest_id] = contest + elif 'codeforces' in path.name: + # these contain only contests the user participated in + yield from self._parse_competitions(path) + else: + raise RuntimeError("shouldn't happen") # TODO switch to compat.assert_never def data() -> Iterator[Res[Competition]]: - cmap = get_contests() - last = max(get_files(config.export_path, 'codeforces*.json')) - - with wrap(json.loads(last.read_text())) as j: - j['status'].ignore() # type: ignore[index] - res = j['result'].zoom() # type: ignore[index] - - for c in list(res): # TODO maybe we want 'iter' method?? - ignore(c, 'handle', 'ratingUpdateTimeSeconds') - yield from Competition.make(cmap=cmap, json=c) - c.consume() - # TODO maybe if they are all empty, no need to consume?? + return Parser(inputs=inputs()).parse() diff --git a/my/core/konsume.py b/my/core/konsume.py index 588bfe1..10bea8d 100644 --- a/my/core/konsume.py +++ b/my/core/konsume.py @@ -209,3 +209,34 @@ def test_zoom() -> None: # TODO type check this... + +# TODO feels like the whole thing kind of unnecessarily complex +# - cons: +# - in most cases this is not even needed? who cares if we miss a few attributes? +# - pro: on the other hand it could be interesting to know about new attributes in data, +# and without this kind of processing we wouldn't even know +# alternatives +# - manually process data +# e.g. use asserts, dict.pop and dict.values() methods to unpack things +# - pros: +# - very simple, since uses built in syntax +# - very performant, as fast as it gets +# - very flexible, easy to adjust behaviour +# - cons: +# - can forget to assert about extra entities etc, so error prone +# - if we do something like =assert j.pop('status') == 200, j=, by the time assert happens we already popped item -- makes erro handling harder +# - a bit verbose.. so probably requires some helper functions though (could be much leaner than current konsume though) +# - if we assert, then terminates parsing too early, if we're defensive then inflates the code a lot with if statements +# - TODO perhaps combine warnings somehow or at least only emit once per module? +# - hmm actually tbh if we carefully go through everything and don't make copies, then only requires one assert at the very end? +# - TODO this is kinda useful? https://discuss.python.org/t/syntax-for-dictionnary-unpacking-to-variables/18718 +# operator.itemgetter? +# - TODO can use match operator in python for this? quite nice actually! and allows for dynamic behaviour +# only from 3.10 tho, and gonna be tricky to do dynamic defensive behaviour with this +# - TODO in a sense, blenser already would hint if some meaningful fields aren't being processed? only if they are changing though +# - define a "schema" for data, then just recursively match data against the schema? +# possibly pydantic already does something like that? not sure about performance though +# pros: +# - much simpler to extend and understand what's going on +# cons: +# - more rigid, so it becomes tricky to do dynamic stuff (e.g. if schema actually changes) diff --git a/my/experimental/destructive_parsing.py b/my/experimental/destructive_parsing.py new file mode 100644 index 0000000..3fc739c --- /dev/null +++ b/my/experimental/destructive_parsing.py @@ -0,0 +1,60 @@ +from dataclasses import dataclass +from typing import Any, Iterator, List, Tuple + +from my.core import assert_never +from my.core.compat import NoneType + + +# TODO Popper? not sure +@dataclass +class Helper: + manager: 'Manager' + item: Any # todo realistically, list or dict? could at least type as indexable or something + path: Tuple[str, ...] + + def pop_if_primitive(self, *keys: str) -> None: + """ + The idea that primitive TODO + """ + item = self.item + for k in keys: + v = item[k] + if isinstance(v, (str, bool, float, int, NoneType)): + item.pop(k) # todo kinda unfortunate to get dict item twice.. but not sure if can avoid? + + def check(self, key: str, expected: Any) -> None: + actual = self.item.pop(key) + assert actual == expected, (key, actual, expected) + + def zoom(self, key: str) -> 'Helper': + return self.manager.helper(item=self.item.pop(key), path=self.path + (key,)) + + +def is_empty(x) -> bool: + if isinstance(x, dict): + return len(x) == 0 + elif isinstance(x, list): + return all(map(is_empty, x)) + else: + assert_never(x) + + +class Manager: + def __init__(self) -> None: + self.helpers: List[Helper] = [] + + def helper(self, item: Any, *, path: Tuple[str, ...] = ()) -> Helper: + res = Helper(manager=self, item=item, path=path) + self.helpers.append(res) + return res + + def check(self) -> Iterator[Exception]: + remaining = [] + for h in self.helpers: + # TODO recursively check it's primitive? + if is_empty(h.item): + continue + remaining.append((h.path, h.item)) + if len(remaining) == 0: + return + yield RuntimeError(f'Unparsed items remaining: {remaining}') diff --git a/my/topcoder.py b/my/topcoder.py index d9631dc..8e39252 100644 --- a/my/topcoder.py +++ b/my/topcoder.py @@ -1,6 +1,3 @@ -from my.config import topcoder as config # type: ignore[attr-defined] - - from dataclasses import dataclass from functools import cached_property import json @@ -8,7 +5,10 @@ from pathlib import Path from typing import Iterator, Sequence from my.core import get_files, Res, datetime_aware -from my.core.compat import fromisoformat, NoneType +from my.core.compat import fromisoformat +from my.experimental.destructive_parsing import Manager + +from my.config import topcoder as config # type: ignore[attr-defined] def inputs() -> Sequence[Path]: @@ -30,10 +30,6 @@ class Competition: def when(self) -> datetime_aware: return fromisoformat(self.date_str) - @cached_property - def summary(self) -> str: - return f'participated in {self.contest}: {self.percentile:.0f}' - @classmethod def make(cls, j) -> Iterator[Res['Competition']]: assert isinstance(j.pop('rating'), float) @@ -53,38 +49,43 @@ class Competition: def _parse_one(p: Path) -> Iterator[Res[Competition]]: - j = json.loads(p.read_text()) + d = json.loads(p.read_text()) - # this is kind of an experiment to parse it exhaustively, making sure we don't miss any data - assert isinstance(j.pop('version'), str) - assert isinstance(j.pop('id'), str) - [j] = j.values() # zoom in + # TODO manager should be a context manager? + m = Manager() - assert j.pop('success') is True, j - assert j.pop('status') == 200, j - assert j.pop('metadata') is None, j - [j] = j.values() # zoom in + h = m.helper(d) + h.pop_if_primitive('version', 'id') - # todo hmm, potentially error handling could be nicer since .pop just reports key error - # also by the time error is reported, key is already removed? - for k in ['handle', 'handleLower', 'userId', 'createdAt', 'updatedAt', 'createdBy', 'updatedBy']: - # check it's primitive - assert isinstance(j.pop(k), (str, bool, float, int, NoneType)), k + h = h.zoom('result') + h.check('success', True) + h.check('status', 200) + h.pop_if_primitive('metadata') - j.pop('DEVELOP') # TODO how to handle it? - [j] = j.values() # zoom in, DATA_SCIENCE section + h = h.zoom('content') + h.pop_if_primitive('handle', 'handleLower', 'userId', 'createdAt', 'updatedAt', 'createdBy', 'updatedBy') - mm = j.pop('MARATHON_MATCH') - [mm] = mm.values() # zoom into historu + # NOTE at the moment it's empty for me, but it will result in an error later if there is some data here + h.zoom('DEVELOP').zoom('subTracks') - srm = j.pop('SRM') - [srm] = srm.values() # zoom into history + h = h.zoom('DATA_SCIENCE') + # TODO multi zoom? not sure which axis, e.g. + # zoom('SRM', 'history') or zoom('SRM', 'MARATHON_MATCH') + # or zoom(('SRM', 'history'), ('MARATHON_MATCH', 'history')) + srms = h.zoom('SRM').zoom('history') + mms = h.zoom('MARATHON_MATCH').zoom('history') - assert len(j) == 0, j - - for c in mm + srm: + for c in srms.item + mms.item: + # NOTE: so here we are actually just using pure dicts in .make method + # this is kinda ok since it will be checked by parent Helper + # but also expects cooperation from .make method (e.g. popping items from the dict) + # could also wrap in helper and pass to .make .. not sure + # an argument could be made that .make isn't really a class methond.. + # it's pretty specific to this parser onl yield from Competition.make(j=c) + yield from m.check() + def data() -> Iterator[Res[Competition]]: *_, last = inputs() From a7439c7846868350d1d6473a891a0114e3aafeb4 Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Mon, 12 Aug 2024 15:45:59 +0300 Subject: [PATCH 053/122] general: move assert_never to my.core.compat as it's in stdlib from 3.11 rely on typing-extensions for fallback introducing typing-extensions dependency without fallback, should be ok since it's in the top 10 of popular packages --- my/bumble/android.py | 3 ++- my/codeforces.py | 3 +-- my/core/__init__.py | 6 +++--- my/core/common.py | 15 ++++++++++----- my/core/compat.py | 12 ++++++++++++ my/core/sqlite.py | 3 ++- my/experimental/destructive_parsing.py | 3 +-- my/fbmessenger/android.py | 3 ++- my/tinder/android.py | 3 ++- setup.py | 1 + 10 files changed, 36 insertions(+), 16 deletions(-) diff --git a/my/bumble/android.py b/my/bumble/android.py index 3a159da..54a0441 100644 --- a/my/bumble/android.py +++ b/my/bumble/android.py @@ -54,9 +54,10 @@ class Message(_BaseMessage): import json from typing import Union -from ..core import Res, assert_never +from ..core import Res import sqlite3 from ..core.sqlite import sqlite_connect_immutable, select +from my.core.compat import assert_never EntitiesRes = Res[Union[Person, _Message]] diff --git a/my/codeforces.py b/my/codeforces.py index 7b37ec6..f2d150a 100644 --- a/my/codeforces.py +++ b/my/codeforces.py @@ -6,7 +6,6 @@ from pathlib import Path from typing import Dict, Iterator, Sequence from my.core import get_files, Res, datetime_aware -from my.core.common import assert_never from my.config import codeforces as config # type: ignore[attr-defined] @@ -73,7 +72,7 @@ class Parser: # these contain only contests the user participated in yield from self._parse_competitions(path) else: - raise RuntimeError("shouldn't happen") # TODO switch to compat.assert_never + raise RuntimeError(f"shouldn't happen: {path.name}") def data() -> Iterator[Res[Competition]]: diff --git a/my/core/__init__.py b/my/core/__init__.py index d753760..c79e36e 100644 --- a/my/core/__init__.py +++ b/my/core/__init__.py @@ -4,7 +4,7 @@ from .common import Json from .common import warn_if_empty from .common import stat, Stats from .common import datetime_naive, datetime_aware -from .common import assert_never +from .compat import assert_never from .cfg import make_config from .error import Res, unwrap @@ -26,7 +26,7 @@ __all__ = [ 'warn_if_empty', 'stat', 'Stats', 'datetime_aware', 'datetime_naive', - 'assert_never', + 'assert_never', # TODO maybe deprecate from use in my.core? will be in stdlib soon 'make_config', @@ -34,7 +34,7 @@ __all__ = [ 'Res', 'unwrap', - 'dataclass', 'Path', + 'dataclass', 'Path', # TODO deprecate these from use in my.core ] diff --git a/my/core/common.py b/my/core/common.py index 98dbacb..9874bed 100644 --- a/my/core/common.py +++ b/my/core/common.py @@ -27,7 +27,10 @@ from typing import ( get_origin, ) import warnings + from . import warnings as core_warnings +from . import compat +from .compat import deprecated # some helper functions PathIsh = Union[Path, str] @@ -633,11 +636,6 @@ class DummyExecutor(Executor): self._shutdown = True -# see https://hakibenita.com/python-mypy-exhaustive-checking#exhaustiveness-checking -def assert_never(value: NoReturn) -> NoReturn: - assert False, f'Unhandled value: {value} ({type(value).__name__})' - - def _check_all_hashable(fun): # TODO ok, take callable? hints = get_type_hints(fun) @@ -693,6 +691,13 @@ def unique_everseen( ## legacy imports, keeping them here for backwards compatibility +## hiding behind TYPE_CHECKING so it works in runtime +## in principle, warnings.deprecated decorator should cooperate with mypy, but doesn't look like it works atm? +## perhaps it doesn't work when it's used from typing_extensions +if not TYPE_CHECKING: + assert_never = deprecated('use my.core.compat.assert_never instead')(compat.assert_never) + +# TODO wrap in deprecated decorator as well? from functools import cached_property as cproperty from typing import Literal from .cachew import mcachew diff --git a/my/core/compat.py b/my/core/compat.py index e984695..2c1687d 100644 --- a/my/core/compat.py +++ b/my/core/compat.py @@ -121,3 +121,15 @@ if sys.version_info[:2] >= (3, 10): from types import NoneType else: NoneType = type(None) + + +if sys.version_info[:2] >= (3, 13): + from warnings import deprecated +else: + from typing_extensions import deprecated + + +if sys.version_info[:2] >= (3, 11): + from typing import assert_never +else: + from typing_extensions import assert_never diff --git a/my/core/sqlite.py b/my/core/sqlite.py index e04f6fc..2580e15 100644 --- a/my/core/sqlite.py +++ b/my/core/sqlite.py @@ -9,7 +9,8 @@ from tempfile import TemporaryDirectory from typing import Tuple, Any, Iterator, Callable, Optional, Union, Literal -from .common import PathIsh, assert_never +from .common import PathIsh +from .compat import assert_never def sqlite_connect_immutable(db: PathIsh) -> sqlite3.Connection: diff --git a/my/experimental/destructive_parsing.py b/my/experimental/destructive_parsing.py index 3fc739c..05c5920 100644 --- a/my/experimental/destructive_parsing.py +++ b/my/experimental/destructive_parsing.py @@ -1,8 +1,7 @@ from dataclasses import dataclass from typing import Any, Iterator, List, Tuple -from my.core import assert_never -from my.core.compat import NoneType +from my.core.compat import NoneType, assert_never # TODO Popper? not sure diff --git a/my/fbmessenger/android.py b/my/fbmessenger/android.py index 8a4bf4c..bc06114 100644 --- a/my/fbmessenger/android.py +++ b/my/fbmessenger/android.py @@ -10,8 +10,9 @@ from pathlib import Path import sqlite3 from typing import Iterator, Sequence, Optional, Dict, Union, List -from my.core import get_files, Paths, datetime_aware, Res, assert_never, LazyLogger, make_config +from my.core import get_files, Paths, datetime_aware, Res, LazyLogger, make_config from my.core.common import unique_everseen +from my.core.compat import assert_never from my.core.error import echain from my.core.sqlite import sqlite_connection diff --git a/my/tinder/android.py b/my/tinder/android.py index 56ee1cb..d9b256b 100644 --- a/my/tinder/android.py +++ b/my/tinder/android.py @@ -11,8 +11,9 @@ from pathlib import Path import sqlite3 from typing import Sequence, Iterator, Union, Dict, List, Mapping -from my.core import Paths, get_files, Res, assert_never, stat, Stats, datetime_aware, make_logger +from my.core import Paths, get_files, Res, stat, Stats, datetime_aware, make_logger from my.core.common import unique_everseen +from my.core.compat import assert_never from my.core.error import echain from my.core.sqlite import sqlite_connection import my.config diff --git a/setup.py b/setup.py index ab96616..cf4b79f 100644 --- a/setup.py +++ b/setup.py @@ -5,6 +5,7 @@ from setuptools import setup, find_namespace_packages # type: ignore INSTALL_REQUIRES = [ 'pytz', # even though it's not needed by the core, it's so common anyway... + 'typing-extensions', # one of the most common pypi packages, ok to depend for core 'appdirs', # very common, and makes it portable 'more-itertools', # it's just too useful and very common anyway 'decorator' , # less pain in writing correct decorators. very mature and stable, so worth keeping in core From 973c4205df8908ec47a0139780d947ca63368936 Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Mon, 12 Aug 2024 16:46:21 +0300 Subject: [PATCH 054/122] core: cleanup deprecations, exclude from type checking and show runtime warnings among affected things: - core.common.assert_never - core.common.cproperty - core.common.isoparse - core.common.mcachew - core.common.the - core.common.tzdatetime - core.compat.sqlite_backup --- my/bluemaestro.py | 2 +- my/browser/export.py | 2 +- my/coding/commits.py | 3 +- my/core/common.py | 62 +++++++++++++----------- my/core/compat.py | 67 ++++++++++++++------------ my/core/tests/test_cachew.py | 4 +- my/core/tests/test_get_files.py | 4 +- my/emfit/__init__.py | 3 +- my/github/ghexport.py | 5 +- my/google/takeout/parser.py | 3 +- my/lastfm.py | 3 +- my/location/google.py | 4 +- my/location/google_takeout.py | 7 ++- my/location/google_takeout_semantic.py | 7 ++- my/location/gpslogger.py | 3 +- my/orgmode.py | 3 +- my/pdfs.py | 3 +- my/photos/main.py | 8 +-- my/reddit/rexport.py | 2 +- my/rescuetime.py | 2 +- my/rss/feedbin.py | 8 ++- my/time/tz/common.py | 10 ++-- my/time/tz/main.py | 4 +- my/time/tz/via_location.py | 2 +- 24 files changed, 118 insertions(+), 103 deletions(-) diff --git a/my/bluemaestro.py b/my/bluemaestro.py index 8f05aac..3e25cae 100644 --- a/my/bluemaestro.py +++ b/my/bluemaestro.py @@ -21,7 +21,7 @@ from my.core import ( Stats, influxdb, ) -from my.core.common import mcachew +from my.core.cachew import mcachew from my.core.error import unwrap from my.core.pandas import DataFrameT, as_dataframe from my.core.sqlite import sqlite_connect_immutable diff --git a/my/browser/export.py b/my/browser/export.py index ce5a6de..1b428b5 100644 --- a/my/browser/export.py +++ b/my/browser/export.py @@ -16,7 +16,7 @@ from my.core import ( make_logger, stat, ) -from my.core.common import mcachew +from my.core.cachew import mcachew from browserexport.merge import read_and_merge, Visit diff --git a/my/coding/commits.py b/my/coding/commits.py index 51f9222..dac3b1f 100644 --- a/my/coding/commits.py +++ b/my/coding/commits.py @@ -14,8 +14,7 @@ from typing import List, Optional, Iterator, Set, Sequence, cast from my.core import PathIsh, LazyLogger, make_config -from my.core.cachew import cache_dir -from my.core.common import mcachew +from my.core.cachew import cache_dir, mcachew from my.core.warnings import high diff --git a/my/core/common.py b/my/core/common.py index 9874bed..460a658 100644 --- a/my/core/common.py +++ b/my/core/common.py @@ -14,7 +14,6 @@ from typing import ( Iterable, Iterator, List, - NoReturn, Optional, Sequence, TYPE_CHECKING, @@ -70,17 +69,6 @@ T = TypeVar('T') K = TypeVar('K') V = TypeVar('V') -# TODO deprecate? more_itertools.one should be used -def the(l: Iterable[T]) -> T: - it = iter(l) - try: - first = next(it) - except StopIteration: - raise RuntimeError('Empty iterator?') - assert all(e == first for e in it) - return first - - # TODO more_itertools.bucket? def group_by_key(l: Iterable[T], key: Callable[[T], K]) -> Dict[K, List[T]]: res: Dict[K, List[T]] = {} @@ -322,14 +310,6 @@ datetime_naive = datetime datetime_aware = datetime -# TODO deprecate -tzdatetime = datetime_aware - - -# TODO deprecate (although could be used in modules) -from .compat import fromisoformat as isoparse - - import re # https://stackoverflow.com/a/295466/706389 def get_valid_filename(s: str) -> str: @@ -554,7 +534,7 @@ def test_guess_datetime() -> None: from dataclasses import dataclass from typing import NamedTuple - dd = isoparse('2021-02-01T12:34:56Z') + dd = compat.fromisoformat('2021-02-01T12:34:56Z') # ugh.. https://github.com/python/mypy/issues/7281 A = NamedTuple('A', [('x', int)]) @@ -690,15 +670,41 @@ def unique_everseen( return more_itertools.unique_everseen(iterable=iterable, key=key) -## legacy imports, keeping them here for backwards compatibility +### legacy imports, keeping them here for backwards compatibility ## hiding behind TYPE_CHECKING so it works in runtime ## in principle, warnings.deprecated decorator should cooperate with mypy, but doesn't look like it works atm? ## perhaps it doesn't work when it's used from typing_extensions if not TYPE_CHECKING: - assert_never = deprecated('use my.core.compat.assert_never instead')(compat.assert_never) -# TODO wrap in deprecated decorator as well? -from functools import cached_property as cproperty -from typing import Literal -from .cachew import mcachew -## + @deprecated('use my.core.compat.assert_never instead') + def assert_never(*args, **kwargs): + return compat.assert_never(*args, **kwargs) + + @deprecated('use my.core.compat.fromisoformat instead') + def isoparse(*args, **kwargs): + return compat.fromisoformat(*args, **kwargs) + + @deprecated('use more_itertools.one instead') + def the(*args, **kwargs): + import more_itertools + + return more_itertools.one(*args, **kwargs) + + @deprecated('use functools.cached_property instead') + def cproperty(*args, **kwargs): + import functools + + return functools.cached_property(*args, **kwargs) + + # todo wrap these in deprecated decorator as well? + from .cachew import mcachew # noqa: F401 + + from typing import Literal # noqa: F401 + + # TODO hmm how to deprecate it in runtime? tricky cause it's actually a class? + tzdatetime = datetime_aware +else: + from .compat import Never + + tzdatetime = Never # makes it invalid as a type while working in runtime +### diff --git a/my/core/compat.py b/my/core/compat.py index 2c1687d..d73c60c 100644 --- a/my/core/compat.py +++ b/my/core/compat.py @@ -2,56 +2,58 @@ Contains backwards compatibility helpers for different python versions. If something is relevant to HPI itself, please put it in .hpi_compat instead ''' -import os + import sys from typing import TYPE_CHECKING -windows = os.name == 'nt' +if sys.version_info[:2] >= (3, 13): + from warnings import deprecated +else: + from typing_extensions import deprecated # keeping just for backwards compatibility, used to have compat implementation for 3.6 -import sqlite3 -def sqlite_backup(*, source: sqlite3.Connection, dest: sqlite3.Connection, **kwargs) -> None: - source.backup(dest, **kwargs) +if not TYPE_CHECKING: + import sqlite3 + + @deprecated('use .backup method on sqlite3.Connection directly instead') + def sqlite_backup(*, source: sqlite3.Connection, dest: sqlite3.Connection, **kwargs) -> None: + # TODO warn here? + source.backup(dest, **kwargs) # can remove after python3.9 (although need to keep the method itself for bwd compat) def removeprefix(text: str, prefix: str) -> str: if text.startswith(prefix): - return text[len(prefix):] + return text[len(prefix) :] return text -## used to have compat function before 3.8 for these -from functools import cached_property -from typing import Literal, Protocol, TypedDict +## used to have compat function before 3.8 for these, keeping for runtime back compatibility +if not TYPE_CHECKING: + from functools import cached_property + from typing import Literal, Protocol, TypedDict +else: + from typing_extensions import Literal, Protocol, TypedDict ## if sys.version_info[:2] >= (3, 10): from typing import ParamSpec else: - if TYPE_CHECKING: - from typing_extensions import ParamSpec - else: - from typing import NamedTuple, Any - # erm.. I guess as long as it's not crashing, whatever... - class _ParamSpec: - def __call__(self, args): - class _res: - args = None - kwargs = None - return _res - ParamSpec = _ParamSpec() + from typing_extensions import ParamSpec # bisect_left doesn't have a 'key' parameter (which we use) # till python3.10 if sys.version_info[:2] <= (3, 9): from typing import List, TypeVar, Any, Optional, Callable + X = TypeVar('X') + # copied from python src + # fmt: off def bisect_left(a: List[Any], x: Any, lo: int=0, hi: Optional[int]=None, *, key: Optional[Callable[..., Any]]=None) -> int: if lo < 0: raise ValueError('lo must be non-negative') @@ -74,19 +76,22 @@ if sys.version_info[:2] <= (3, 9): else: hi = mid return lo + # fmt: on + else: from bisect import bisect_left from datetime import datetime + if sys.version_info[:2] >= (3, 11): fromisoformat = datetime.fromisoformat else: + # fromisoformat didn't support Z as "utc" before 3.11 + # https://docs.python.org/3/library/datetime.html#datetime.datetime.fromisoformat + def fromisoformat(date_string: str) -> datetime: - # didn't support Z as "utc" before 3.11 if date_string.endswith('Z'): - # NOTE: can be removed from 3.11? - # https://docs.python.org/3/library/datetime.html#datetime.datetime.fromisoformat date_string = date_string[:-1] + '+00:00' return datetime.fromisoformat(date_string) @@ -94,6 +99,7 @@ else: def test_fromisoformat() -> None: from datetime import timezone + # fmt: off # feedbin has this format assert fromisoformat('2020-05-01T10:32:02.925961Z') == datetime( 2020, 5, 1, 10, 32, 2, 925961, timezone.utc, @@ -108,6 +114,7 @@ def test_fromisoformat() -> None: assert fromisoformat('2020-11-30T00:53:12Z') == datetime( 2020, 11, 30, 0, 53, 12, 0, timezone.utc, ) + # fmt: on # arbtt has this format (sometimes less/more than 6 digits in milliseconds) # TODO doesn't work atm, not sure if really should be supported... @@ -123,13 +130,13 @@ else: NoneType = type(None) -if sys.version_info[:2] >= (3, 13): - from warnings import deprecated -else: - from typing_extensions import deprecated - - if sys.version_info[:2] >= (3, 11): from typing import assert_never else: from typing_extensions import assert_never + + +if sys.version_info[:2] >= (3, 11): + from typing import Never +else: + from typing_extensions import Never diff --git a/my/core/tests/test_cachew.py b/my/core/tests/test_cachew.py index 86344fd..5f7dd65 100644 --- a/my/core/tests/test_cachew.py +++ b/my/core/tests/test_cachew.py @@ -10,7 +10,7 @@ def test_cachew() -> None: settings.ENABLE = True # by default it's off in tests (see conftest.py) - from my.core.common import mcachew + from my.core.cachew import mcachew called = 0 @@ -36,7 +36,7 @@ def test_cachew_dir_none() -> None: settings.ENABLE = True # by default it's off in tests (see conftest.py) from my.core.cachew import cache_dir - from my.core.common import mcachew + from my.core.cachew import mcachew from my.core.core_config import _reset_config as reset with reset() as cc: diff --git a/my/core/tests/test_get_files.py b/my/core/tests/test_get_files.py index e9f216a..52e43f8 100644 --- a/my/core/tests/test_get_files.py +++ b/my/core/tests/test_get_files.py @@ -6,7 +6,6 @@ from typing import TYPE_CHECKING import zipfile from ..common import get_files -from ..compat import windows from ..kompress import CPath, ZipPath import pytest @@ -56,8 +55,9 @@ def test_single_file() -> None: ''' assert get_files('/tmp/hpi_test/file.ext') == (Path('/tmp/hpi_test/file.ext'),) + is_windows = os.name == 'nt' "if the path starts with ~, we expand it" - if not windows: # windows doesn't have bashrc.. ugh + if not is_windows: # windows doesn't have bashrc.. ugh assert get_files('~/.bashrc') == (Path('~').expanduser() / '.bashrc',) diff --git a/my/emfit/__init__.py b/my/emfit/__init__.py index 30b693c..7fae8ea 100644 --- a/my/emfit/__init__.py +++ b/my/emfit/__init__.py @@ -21,8 +21,7 @@ from my.core import ( Res, Stats, ) -from my.core.common import mcachew -from my.core.cachew import cache_dir +from my.core.cachew import cache_dir, mcachew from my.core.error import set_error_datetime, extract_error_datetime from my.core.pandas import DataFrameT diff --git a/my/github/ghexport.py b/my/github/ghexport.py index d446c35..9dc8fd5 100644 --- a/my/github/ghexport.py +++ b/my/github/ghexport.py @@ -42,10 +42,11 @@ except ModuleNotFoundError as e: ############################ from functools import lru_cache +from pathlib import Path from typing import Tuple, Dict, Sequence, Optional -from my.core import get_files, Path, LazyLogger -from my.core.common import mcachew +from my.core import get_files, LazyLogger +from my.core.cachew import mcachew from .common import Event, parse_dt, Results, EventIds diff --git a/my/google/takeout/parser.py b/my/google/takeout/parser.py index 2322ef0..952c9b6 100644 --- a/my/google/takeout/parser.py +++ b/my/google/takeout/parser.py @@ -19,7 +19,8 @@ import os from typing import List, Sequence, cast from pathlib import Path from my.core import make_config, dataclass -from my.core.common import Stats, LazyLogger, mcachew, get_files, Paths +from my.core.cachew import mcachew +from my.core.common import Stats, LazyLogger, get_files, Paths from my.core.error import ErrorPolicy from my.core.structure import match_structure diff --git a/my/lastfm.py b/my/lastfm.py index 90484b4..64ef1b3 100644 --- a/my/lastfm.py +++ b/my/lastfm.py @@ -26,7 +26,8 @@ import json from pathlib import Path from typing import NamedTuple, Sequence, Iterable -from my.core.common import mcachew, Json, get_files +from my.core.cachew import mcachew +from my.core.common import Json, get_files def inputs() -> Sequence[Path]: diff --git a/my/location/google.py b/my/location/google.py index ed37231..c1539e7 100644 --- a/my/location/google.py +++ b/my/location/google.py @@ -19,8 +19,8 @@ import re # pip3 install geopy import geopy # type: ignore -from ..core.common import LazyLogger, mcachew -from ..core.cachew import cache_dir +from my.core.common import LazyLogger +from my.core.cachew import cache_dir, mcachew from my.core.warnings import high diff --git a/my/location/google_takeout.py b/my/location/google_takeout.py index a1c1403..2fac270 100644 --- a/my/location/google_takeout.py +++ b/my/location/google_takeout.py @@ -9,7 +9,8 @@ from typing import Iterator from my.google.takeout.parser import events, _cachew_depends_on from google_takeout_parser.models import Location as GoogleLocation -from my.core.common import mcachew, LazyLogger, Stats +from my.core.cachew import mcachew +from my.core.common import LazyLogger, stat, Stats from .common import Location logger = LazyLogger(__name__) @@ -33,6 +34,4 @@ def locations() -> Iterator[Location]: def stats() -> Stats: - from my.core import stat - - return {**stat(locations)} + return stat(locations) diff --git a/my/location/google_takeout_semantic.py b/my/location/google_takeout_semantic.py index b4f16db..014959c 100644 --- a/my/location/google_takeout_semantic.py +++ b/my/location/google_takeout_semantic.py @@ -13,7 +13,8 @@ from my.google.takeout.parser import events, _cachew_depends_on as _parser_cache from google_takeout_parser.models import PlaceVisit as SemanticLocation from my.core import dataclass, make_config -from my.core.common import mcachew, LazyLogger, Stats +from my.core.cachew import mcachew +from my.core.common import LazyLogger, Stats, stat from my.core.error import Res from .common import Location @@ -72,6 +73,4 @@ def locations() -> Iterator[Res[Location]]: def stats() -> Stats: - from my.core import stat - - return {**stat(locations)} + return stat(locations) diff --git a/my/location/gpslogger.py b/my/location/gpslogger.py index 29e2547..8fb59d0 100644 --- a/my/location/gpslogger.py +++ b/my/location/gpslogger.py @@ -27,7 +27,8 @@ from gpxpy.gpx import GPXXMLSyntaxException from more_itertools import unique_everseen from my.core import Stats, LazyLogger -from my.core.common import get_files, mcachew +from my.core.cachew import mcachew +from my.core.common import get_files from .common import Location diff --git a/my/orgmode.py b/my/orgmode.py index 8293b74..c27f5a7 100644 --- a/my/orgmode.py +++ b/my/orgmode.py @@ -12,8 +12,7 @@ import re from typing import List, Sequence, Iterable, NamedTuple, Optional, Tuple from my.core import get_files -from my.core.common import mcachew -from my.core.cachew import cache_dir +from my.core.cachew import cache_dir, mcachew from my.core.orgmode import collect from my.config import orgmode as user_config diff --git a/my/pdfs.py b/my/pdfs.py index 5355d8a..3305eca 100644 --- a/my/pdfs.py +++ b/my/pdfs.py @@ -15,8 +15,9 @@ from typing import NamedTuple, List, Optional, Iterator, Sequence from my.core import LazyLogger, get_files, Paths, PathIsh +from my.core.cachew import mcachew from my.core.cfg import Attrs, make_config -from my.core.common import mcachew, group_by_key +from my.core.common import group_by_key from my.core.error import Res, split_errors diff --git a/my/photos/main.py b/my/photos/main.py index c491ac1..622d475 100644 --- a/my/photos/main.py +++ b/my/photos/main.py @@ -13,11 +13,11 @@ import json from pathlib import Path from typing import Optional, NamedTuple, Iterator, Iterable, List -from geopy.geocoders import Nominatim # type: ignore +from geopy.geocoders import Nominatim # type: ignore -from ..core.common import LazyLogger, mcachew, fastermime -from ..core.error import Res, sort_res_by -from ..core.cachew import cache_dir +from my.core.common import LazyLogger, fastermime +from my.core.error import Res, sort_res_by +from my.core.cachew import cache_dir, mcachew from my.config import photos as config # type: ignore[attr-defined] diff --git a/my/reddit/rexport.py b/my/reddit/rexport.py index a7be39b..6a6be61 100644 --- a/my/reddit/rexport.py +++ b/my/reddit/rexport.py @@ -20,8 +20,8 @@ from my.core import ( Paths, Stats, ) +from my.core.cachew import mcachew from my.core.cfg import make_config, Attrs -from my.core.common import mcachew from my.config import reddit as uconfig diff --git a/my/rescuetime.py b/my/rescuetime.py index 75684d9..774b587 100644 --- a/my/rescuetime.py +++ b/my/rescuetime.py @@ -10,7 +10,7 @@ from datetime import timedelta from typing import Sequence, Iterable from my.core import get_files, make_logger -from my.core.common import mcachew +from my.core.cachew import mcachew from my.core.error import Res, split_errors from my.config import rescuetime as config diff --git a/my/rss/feedbin.py b/my/rss/feedbin.py index 6160abc..16d4417 100644 --- a/my/rss/feedbin.py +++ b/my/rss/feedbin.py @@ -7,8 +7,8 @@ from my.config import feedbin as config from pathlib import Path from typing import Sequence -from ..core.common import listify, get_files -from ..core.compat import fromisoformat +from my.core.common import listify, get_files +from my.core.compat import fromisoformat from .common import Subscription @@ -33,12 +33,10 @@ def parse_file(f: Path): from typing import Iterable from .common import SubscriptionState def states() -> Iterable[SubscriptionState]: - # meh - from dateutil.parser import isoparse for f in inputs(): # TODO ugh. depends on my naming. not sure if useful? dts = f.stem.split('_')[-1] - dt = isoparse(dts) + dt = fromisoformat(dts) subs = parse_file(f) yield dt, subs diff --git a/my/time/tz/common.py b/my/time/tz/common.py index e2c428d..107410a 100644 --- a/my/time/tz/common.py +++ b/my/time/tz/common.py @@ -1,7 +1,7 @@ from datetime import datetime -from typing import Callable, cast +from typing import Callable, Literal, cast -from ...core.common import tzdatetime, Literal +from my.core.common import datetime_aware ''' @@ -30,7 +30,11 @@ def default_policy() -> TzPolicy: return 'keep' -def localize_with_policy(lfun: Callable[[datetime], tzdatetime], dt: datetime, policy: TzPolicy=default_policy()) -> tzdatetime: +def localize_with_policy( + lfun: Callable[[datetime], datetime_aware], + dt: datetime, + policy: TzPolicy=default_policy() +) -> datetime_aware: tz = dt.tzinfo if tz is None: return lfun(dt) diff --git a/my/time/tz/main.py b/my/time/tz/main.py index 624d7aa..6180160 100644 --- a/my/time/tz/main.py +++ b/my/time/tz/main.py @@ -2,10 +2,10 @@ Timezone data provider, used to localize timezone-unaware timestamps for other modules ''' from datetime import datetime -from ...core.common import tzdatetime +from my.core.common import datetime_aware # todo hmm, kwargs isn't mypy friendly.. but specifying types would require duplicating default args. uhoh -def localize(dt: datetime, **kwargs) -> tzdatetime: +def localize(dt: datetime, **kwargs) -> datetime_aware: # todo document patterns for combining multiple data sources # e.g. see https://github.com/karlicoss/HPI/issues/89#issuecomment-716495136 from . import via_location as L diff --git a/my/time/tz/via_location.py b/my/time/tz/via_location.py index 612341a..b66ff8a 100644 --- a/my/time/tz/via_location.py +++ b/my/time/tz/via_location.py @@ -17,8 +17,8 @@ from typing import Iterator, Optional, Tuple, Any, List, Iterable, Set, Dict import pytz +from my.core.cachew import mcachew from my.core import make_logger, stat, Stats, datetime_aware -from my.core.common import mcachew from my.core.source import import_source from my.core.warnings import high From c64d7f5b676026e145340eca6865f534ff3b2ae4 Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Tue, 13 Aug 2024 10:22:39 +0300 Subject: [PATCH 055/122] core: cleanup itertool style helpers - deprecate group_by_key, should use itertool.bucket instead - move make_dict and ensure_unique to my.core.utils.itertools --- my/core/common.py | 94 +++++++------------------------------- my/core/utils/itertools.py | 77 +++++++++++++++++++++++++++++++ my/github/ghexport.py | 5 +- my/jawbone/__init__.py | 12 +++-- my/pdfs.py | 6 ++- my/rtm.py | 11 +++-- my/tests/reddit.py | 7 +-- 7 files changed, 119 insertions(+), 93 deletions(-) create mode 100644 my/core/utils/itertools.py diff --git a/my/core/common.py b/my/core/common.py index 460a658..0be4dae 100644 --- a/my/core/common.py +++ b/my/core/common.py @@ -65,84 +65,6 @@ def import_dir(path: PathIsh, extra: str='') -> types.ModuleType: return import_from(p.parent, p.name + extra) -T = TypeVar('T') -K = TypeVar('K') -V = TypeVar('V') - -# TODO more_itertools.bucket? -def group_by_key(l: Iterable[T], key: Callable[[T], K]) -> Dict[K, List[T]]: - res: Dict[K, List[T]] = {} - for i in l: - kk = key(i) - lst = res.get(kk, []) - lst.append(i) - res[kk] = lst - return res - - -def _identity(v: T) -> V: # type: ignore[type-var] - return cast(V, v) - - -# ugh. nothing in more_itertools? -def ensure_unique( - it: Iterable[T], - *, - key: Callable[[T], K], - value: Callable[[T], V]=_identity, - key2value: Optional[Dict[K, V]]=None -) -> Iterable[T]: - if key2value is None: - key2value = {} - for i in it: - k = key(i) - v = value(i) - pv = key2value.get(k, None) - if pv is not None: - raise RuntimeError(f"Duplicate key: {k}. Previous value: {pv}, new value: {v}") - key2value[k] = v - yield i - - -def test_ensure_unique() -> None: - import pytest - assert list(ensure_unique([1, 2, 3], key=lambda i: i)) == [1, 2, 3] - - dups = [1, 2, 1, 4] - # this works because it's lazy - it = ensure_unique(dups, key=lambda i: i) - - # but forcing throws - with pytest.raises(RuntimeError, match='Duplicate key'): - list(it) - - # hacky way to force distinct objects? - list(ensure_unique(dups, key=lambda i: object())) - - -def make_dict( - it: Iterable[T], - *, - key: Callable[[T], K], - value: Callable[[T], V]=_identity -) -> Dict[K, V]: - res: Dict[K, V] = {} - uniques = ensure_unique(it, key=key, value=value, key2value=res) - for _ in uniques: - pass # force the iterator - return res - - -def test_make_dict() -> None: - it = range(5) - d = make_dict(it, key=lambda i: i, value=lambda i: i % 2) - assert d == {0: 0, 1: 1, 2: 0, 3: 1, 4: 0} - - # check type inference - d2: Dict[str, int ] = make_dict(it, key=lambda i: str(i)) - d3: Dict[str, bool] = make_dict(it, key=lambda i: str(i), value=lambda i: i % 2 == 0) - - # https://stackoverflow.com/a/12377059/706389 def listify(fn=None, wrapper=list): """ @@ -696,6 +618,22 @@ if not TYPE_CHECKING: return functools.cached_property(*args, **kwargs) + @deprecated('use more_itertools.bucket instead') + def group_by_key(l, key): + res = {} + for i in l: + kk = key(i) + lst = res.get(kk, []) + lst.append(i) + res[kk] = lst + return res + + @deprecated('use my.core.utils.make_dict instead') + def make_dict(*args, **kwargs): + from .utils import itertools as UI + + return UI.make_dict(*args, **kwargs) + # todo wrap these in deprecated decorator as well? from .cachew import mcachew # noqa: F401 diff --git a/my/core/utils/itertools.py b/my/core/utils/itertools.py new file mode 100644 index 0000000..78b91de --- /dev/null +++ b/my/core/utils/itertools.py @@ -0,0 +1,77 @@ +""" +Various helpers/transforms of iterators + +Ideally this should be as small as possible and we should rely on stdlib itertools or more_itertools +""" + +from typing import Callable, Dict, Iterable, TypeVar, cast + + +T = TypeVar('T') +K = TypeVar('K') +V = TypeVar('V') + + +def _identity(v: T) -> V: # type: ignore[type-var] + return cast(V, v) + + +# ugh. nothing in more_itertools? +# perhaps duplicates_everseen? but it doesn't yield non-unique elements? +def ensure_unique(it: Iterable[T], *, key: Callable[[T], K]) -> Iterable[T]: + key2item: Dict[K, T] = {} + for i in it: + k = key(i) + pi = key2item.get(k, None) + if pi is not None: + raise RuntimeError(f"Duplicate key: {k}. Previous value: {pi}, new value: {i}") + key2item[k] = i + yield i + + +def test_ensure_unique() -> None: + import pytest + + assert list(ensure_unique([1, 2, 3], key=lambda i: i)) == [1, 2, 3] + + dups = [1, 2, 1, 4] + # this works because it's lazy + it = ensure_unique(dups, key=lambda i: i) + + # but forcing throws + with pytest.raises(RuntimeError, match='Duplicate key'): + list(it) + + # hacky way to force distinct objects? + list(ensure_unique(dups, key=lambda i: object())) + + +def make_dict( + it: Iterable[T], + *, + key: Callable[[T], K], + # TODO make value optional instead? but then will need a typing override for it? + value: Callable[[T], V] = _identity, +) -> Dict[K, V]: + with_keys = ((key(i), i) for i in it) + uniques = ensure_unique(with_keys, key=lambda p: p[0]) + res: Dict[K, V] = {} + for k, i in uniques: + res[k] = i if value is None else value(i) + return res + + +def test_make_dict() -> None: + import pytest + + it = range(5) + d = make_dict(it, key=lambda i: i, value=lambda i: i % 2) + assert d == {0: 0, 1: 1, 2: 0, 3: 1, 4: 0} + + it = range(5) + with pytest.raises(RuntimeError, match='Duplicate key'): + d = make_dict(it, key=lambda i: i % 2, value=lambda i: i) + + # check type inference + d2: Dict[str, int] = make_dict(it, key=lambda i: str(i)) + d3: Dict[str, bool] = make_dict(it, key=lambda i: str(i), value=lambda i: i % 2 == 0) diff --git a/my/github/ghexport.py b/my/github/ghexport.py index 9dc8fd5..80106a5 100644 --- a/my/github/ghexport.py +++ b/my/github/ghexport.py @@ -65,11 +65,10 @@ def _dal() -> dal.DAL: @mcachew(depends_on=inputs) def events() -> Results: - from my.core.common import ensure_unique - key = lambda e: object() if isinstance(e, Exception) else e.eid + # key = lambda e: object() if isinstance(e, Exception) else e.eid # crap. sometimes API events can be repeated with exactly the same payload and different id # yield from ensure_unique(_events(), key=key) - yield from _events() + return _events() def _events() -> Results: diff --git a/my/jawbone/__init__.py b/my/jawbone/__init__.py index 7f4d6bd..0659bc6 100644 --- a/my/jawbone/__init__.py +++ b/my/jawbone/__init__.py @@ -108,16 +108,22 @@ def load_sleeps() -> List[SleepEntry]: from ..core.error import Res, set_error_datetime, extract_error_datetime def pre_dataframe() -> Iterable[Res[SleepEntry]]: + from more_itertools import bucket + sleeps = load_sleeps() # todo emit error if graph doesn't exist?? sleeps = [s for s in sleeps if s.graph.exists()] # TODO careful.. - from ..core.common import group_by_key - for dd, group in group_by_key(sleeps, key=lambda s: s.date_).items(): + + bucketed = bucket(sleeps, key=lambda s: s.date_) + + for dd in bucketed: + group = list(bucketed[dd]) if len(group) == 1: yield group[0] else: err = RuntimeError(f'Multiple sleeps per night, not supported yet: {group}') - set_error_datetime(err, dt=dd) # type: ignore[arg-type] + dt = datetime.combine(dd, time.min) + set_error_datetime(err, dt=dt) logger.exception(err) yield err diff --git a/my/pdfs.py b/my/pdfs.py index 3305eca..b3ef85d 100644 --- a/my/pdfs.py +++ b/my/pdfs.py @@ -17,10 +17,10 @@ from typing import NamedTuple, List, Optional, Iterator, Sequence from my.core import LazyLogger, get_files, Paths, PathIsh from my.core.cachew import mcachew from my.core.cfg import Attrs, make_config -from my.core.common import group_by_key from my.core.error import Res, split_errors +from more_itertools import bucket import pdfannots @@ -169,7 +169,9 @@ def annotated_pdfs(*, filelist: Optional[Sequence[PathIsh]]=None) -> Iterator[Re ait = annotations() vit, eit = split_errors(ait, ET=Exception) - for k, g in group_by_key(vit, key=lambda a: a.path).items(): + bucketed = bucket(vit, key=lambda a: a.path) + for k in bucketed: + g = list(bucketed[k]) yield Pdf(path=Path(k), annotations=g) yield from eit diff --git a/my/rtm.py b/my/rtm.py index 8d41e7a..56f4d07 100644 --- a/my/rtm.py +++ b/my/rtm.py @@ -11,13 +11,15 @@ from functools import cached_property import re from typing import Dict, List, Iterator -from .core.common import LazyLogger, get_files, group_by_key, make_dict +from my.core.common import LazyLogger, get_files +from my.core.utils.itertools import make_dict from my.config import rtm as config -import icalendar # type: ignore -from icalendar.cal import Todo # type: ignore +from more_itertools import bucket +import icalendar # type: ignore +from icalendar.cal import Todo # type: ignore logger = LazyLogger(__name__) @@ -96,7 +98,8 @@ class DAL: def get_todos_by_title(self) -> Dict[str, List[MyTodo]]: todos = self.all_todos() - return group_by_key(todos, lambda todo: todo.title) + bucketed = bucket(todos, lambda todo: todo.title) + return {k: list(bucketed[k]) for k in bucketed} def dal(): diff --git a/my/tests/reddit.py b/my/tests/reddit.py index 4af95ae..fb8d6d2 100644 --- a/my/tests/reddit.py +++ b/my/tests/reddit.py @@ -1,9 +1,10 @@ from my.core.cfg import tmp_config -from my.core.common import make_dict +from my.core.utils.itertools import ensure_unique # todo ugh, it's discovered as a test??? from .common import testdata +from more_itertools import consume import pytest # deliberately use mixed style imports on the top level and inside the methods to test tmp_config stuff @@ -36,8 +37,8 @@ def test_saves() -> None: saves = list(saved()) assert len(saves) > 0 - # just check that they are unique (makedict will throw) - make_dict(saves, key=lambda s: s.sid) + # will throw if not unique + consume(ensure_unique(saves, key=lambda s: s.sid)) def test_preserves_extra_attr() -> None: From 66c08a6c8067bcee00876f1cd726ff2a3290567f Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Wed, 14 Aug 2024 10:59:47 +0300 Subject: [PATCH 056/122] core.common: move listify to core.utils.itertools, use better typing annotations for it also some minor refactoring of my.rss --- my/core/common.py | 31 +++++++--------------------- my/core/utils/itertools.py | 41 +++++++++++++++++++++++++++++++++++++- my/rss/all.py | 3 ++- my/rss/common.py | 28 +++++++++++++------------- my/rss/feedbin.py | 29 ++++++++++----------------- my/rss/feedly.py | 14 ++++++------- 6 files changed, 81 insertions(+), 65 deletions(-) diff --git a/my/core/common.py b/my/core/common.py index 0be4dae..920657a 100644 --- a/my/core/common.py +++ b/my/core/common.py @@ -65,29 +65,6 @@ def import_dir(path: PathIsh, extra: str='') -> types.ModuleType: return import_from(p.parent, p.name + extra) -# https://stackoverflow.com/a/12377059/706389 -def listify(fn=None, wrapper=list): - """ - Wraps a function's return value in wrapper (e.g. list) - Useful when an algorithm can be expressed more cleanly as a generator - """ - def listify_return(fn): - @functools.wraps(fn) - def listify_helper(*args, **kw): - return wrapper(fn(*args, **kw)) - return listify_helper - if fn is None: - return listify_return - return listify_return(fn) - - -# todo use in bluemaestro -# def dictify(fn=None, key=None, value=None): -# def md(it): -# return make_dict(it, key=key, value=value) -# return listify(fn=fn, wrapper=md) - - from .logging import setup_logger, LazyLogger @@ -628,12 +605,18 @@ if not TYPE_CHECKING: res[kk] = lst return res - @deprecated('use my.core.utils.make_dict instead') + @deprecated('use my.core.utils.itertools.make_dict instead') def make_dict(*args, **kwargs): from .utils import itertools as UI return UI.make_dict(*args, **kwargs) + @deprecated('use my.core.utils.itertools.listify instead') + def listify(*args, **kwargs): + from .utils import itertools as UI + + return UI.listify(*args, **kwargs) + # todo wrap these in deprecated decorator as well? from .cachew import mcachew # noqa: F401 diff --git a/my/core/utils/itertools.py b/my/core/utils/itertools.py index 78b91de..cab4b2c 100644 --- a/my/core/utils/itertools.py +++ b/my/core/utils/itertools.py @@ -4,8 +4,11 @@ Various helpers/transforms of iterators Ideally this should be as small as possible and we should rely on stdlib itertools or more_itertools """ -from typing import Callable, Dict, Iterable, TypeVar, cast +from typing import Callable, Dict, Iterable, Iterator, TypeVar, List, cast, TYPE_CHECKING +from ..compat import ParamSpec + +from decorator import decorator T = TypeVar('T') K = TypeVar('K') @@ -75,3 +78,39 @@ def test_make_dict() -> None: # check type inference d2: Dict[str, int] = make_dict(it, key=lambda i: str(i)) d3: Dict[str, bool] = make_dict(it, key=lambda i: str(i), value=lambda i: i % 2 == 0) + + +LFP = ParamSpec('LFP') +LV = TypeVar('LV') + + +@decorator +def _listify(func: Callable[LFP, Iterable[LV]], *args: LFP.args, **kwargs: LFP.kwargs) -> List[LV]: + """ + Wraps a function's return value in wrapper (e.g. list) + Useful when an algorithm can be expressed more cleanly as a generator + """ + return list(func(*args, **kwargs)) + + +# ugh. decorator library has stub types, but they are way too generic? +# tried implementing my own stub, but failed -- not sure if it's possible at all? +# so seems easiest to just use specialize instantiations of decorator instead +if TYPE_CHECKING: + + def listify(func: Callable[LFP, Iterable[LV]]) -> Callable[LFP, List[LV]]: ... + +else: + listify = _listify + + +def test_listify() -> None: + @listify + def it() -> Iterator[int]: + yield 1 + yield 2 + + res = it() + from typing_extensions import assert_type # TODO move to compat? + assert_type(res, List[int]) + assert res == [1, 2] diff --git a/my/rss/all.py b/my/rss/all.py index 61f9fab..b4dbdbd 100644 --- a/my/rss/all.py +++ b/my/rss/all.py @@ -1,6 +1,7 @@ ''' Unified RSS data, merged from different services I used historically ''' + # NOTE: you can comment out the sources you're not using from . import feedbin, feedly @@ -12,5 +13,5 @@ def subscriptions() -> Iterable[Subscription]: # TODO google reader? yield from compute_subscriptions( feedbin.states(), - feedly .states(), + feedly.states(), ) diff --git a/my/rss/common.py b/my/rss/common.py index f3893b7..54067d6 100644 --- a/my/rss/common.py +++ b/my/rss/common.py @@ -1,30 +1,32 @@ -# shared Rss stuff -from datetime import datetime -from typing import NamedTuple, Optional, List, Dict +from my.core import __NOT_HPI_MODULE__ + +from dataclasses import dataclass, replace +from itertools import chain +from typing import Optional, List, Dict, Iterable, Tuple, Sequence + +from my.core import warn_if_empty, datetime_aware -class Subscription(NamedTuple): +@dataclass +class Subscription: title: str url: str - id: str # TODO not sure about it... + id: str # TODO not sure about it... # eh, not all of them got reasonable 'created' time - created_at: Optional[datetime] - subscribed: bool=True + created_at: Optional[datetime_aware] + subscribed: bool = True -from typing import Iterable, Tuple, Sequence # snapshot of subscriptions at time -SubscriptionState = Tuple[datetime, Sequence[Subscription]] +SubscriptionState = Tuple[datetime_aware, Sequence[Subscription]] -from ..core import warn_if_empty @warn_if_empty def compute_subscriptions(*sources: Iterable[SubscriptionState]) -> List[Subscription]: """ Keeps track of everything I ever subscribed to. In addition, keeps track of unsubscribed as well (so you'd remember when and why you unsubscribed) """ - from itertools import chain states = list(chain.from_iterable(sources)) # TODO keep 'source'/'provider'/'service' attribute? @@ -45,7 +47,5 @@ def compute_subscriptions(*sources: Iterable[SubscriptionState]) -> List[Subscri res = [] for u, x in sorted(by_url.items()): present = u in last_urls - res.append(x._replace(subscribed=present)) + res.append(replace(x, subscribed=present)) return res - -from ..core import __NOT_HPI_MODULE__ diff --git a/my/rss/feedbin.py b/my/rss/feedbin.py index 16d4417..dc13a17 100644 --- a/my/rss/feedbin.py +++ b/my/rss/feedbin.py @@ -2,24 +2,22 @@ Feedbin RSS reader """ -from my.config import feedbin as config - +import json from pathlib import Path -from typing import Sequence +from typing import Iterator, Sequence -from my.core.common import listify, get_files +from my.core import get_files, stat, Stats from my.core.compat import fromisoformat -from .common import Subscription +from .common import Subscription, SubscriptionState + +from my.config import feedbin as config def inputs() -> Sequence[Path]: return get_files(config.export_path) -import json - -@listify -def parse_file(f: Path): +def parse_file(f: Path) -> Iterator[Subscription]: raw = json.loads(f.read_text()) for r in raw: yield Subscription( @@ -30,19 +28,14 @@ def parse_file(f: Path): ) -from typing import Iterable -from .common import SubscriptionState -def states() -> Iterable[SubscriptionState]: +def states() -> Iterator[SubscriptionState]: for f in inputs(): # TODO ugh. depends on my naming. not sure if useful? dts = f.stem.split('_')[-1] dt = fromisoformat(dts) - subs = parse_file(f) + subs = list(parse_file(f)) yield dt, subs -def stats(): - from more_itertools import ilen, last - return { - 'subscriptions': ilen(last(states())[1]) - } +def stats() -> Stats: + return stat(states) diff --git a/my/rss/feedly.py b/my/rss/feedly.py index 4611ced..55bcf9b 100644 --- a/my/rss/feedly.py +++ b/my/rss/feedly.py @@ -1,14 +1,15 @@ """ Feedly RSS reader """ + from my.config import feedly as config from datetime import datetime, timezone import json from pathlib import Path -from typing import Iterable, Sequence +from typing import Iterator, Sequence -from ..core.common import listify, get_files +from my.core import get_files from .common import Subscription, SubscriptionState @@ -16,13 +17,12 @@ def inputs() -> Sequence[Path]: return get_files(config.export_path) -@listify -def parse_file(f: Path): +def parse_file(f: Path) -> Iterator[Subscription]: raw = json.loads(f.read_text()) for r in raw: # err, some even don't have website.. rid = r['id'] - website = r.get('website', rid) # meh + website = r.get('website', rid) # meh yield Subscription( created_at=None, title=r['title'], @@ -31,9 +31,9 @@ def parse_file(f: Path): ) -def states() -> Iterable[SubscriptionState]: +def states() -> Iterator[SubscriptionState]: for f in inputs(): dts = f.stem.split('_')[-1] dt = datetime.strptime(dts, '%Y%m%d%H%M%S').replace(tzinfo=timezone.utc) - subs = parse_file(f) + subs = list(parse_file(f)) yield dt, subs From 770dba5506ecd96bf52ca47cd880b7b2ca62c8c7 Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Wed, 14 Aug 2024 11:28:50 +0300 Subject: [PATCH 057/122] core.common: move away import related stuff to my.core.utils.imports moving without backward compatibility, since it's extremely unlikely they are used for any external modules in fact, unclear if these methods still have much value at all, but keeping for now just in case --- my/core/common.py | 31 ------------------------------- my/core/compat.py | 10 ++-------- my/core/hpi_compat.py | 2 +- my/core/utils/imports.py | 37 +++++++++++++++++++++++++++++++++++++ my/core/utils/itertools.py | 3 ++- my/demo.py | 2 +- tests/extra/polar.py | 2 +- 7 files changed, 44 insertions(+), 43 deletions(-) create mode 100644 my/core/utils/imports.py diff --git a/my/core/common.py b/my/core/common.py index 920657a..389dedc 100644 --- a/my/core/common.py +++ b/my/core/common.py @@ -34,37 +34,6 @@ from .compat import deprecated # some helper functions PathIsh = Union[Path, str] -# TODO only used in tests? not sure if useful at all. -def import_file(p: PathIsh, name: Optional[str] = None) -> types.ModuleType: - p = Path(p) - if name is None: - name = p.stem - import importlib.util - spec = importlib.util.spec_from_file_location(name, p) - assert spec is not None, f"Fatal error; Could not create module spec from {name} {p}" - foo = importlib.util.module_from_spec(spec) - loader = spec.loader; assert loader is not None - loader.exec_module(foo) - return foo - - -def import_from(path: PathIsh, name: str) -> types.ModuleType: - path = str(path) - try: - sys.path.append(path) - import importlib - return importlib.import_module(name) - finally: - sys.path.remove(path) - - -def import_dir(path: PathIsh, extra: str='') -> types.ModuleType: - p = Path(path) - if p.parts[0] == '~': - p = p.expanduser() # TODO eh. not sure about this.. - return import_from(p.parent, p.name + extra) - - from .logging import setup_logger, LazyLogger diff --git a/my/core/compat.py b/my/core/compat.py index d73c60c..7bbe509 100644 --- a/my/core/compat.py +++ b/my/core/compat.py @@ -131,12 +131,6 @@ else: if sys.version_info[:2] >= (3, 11): - from typing import assert_never + from typing import assert_never, assert_type, Never else: - from typing_extensions import assert_never - - -if sys.version_info[:2] >= (3, 11): - from typing import Never -else: - from typing_extensions import Never + from typing_extensions import assert_never, assert_type, Never diff --git a/my/core/hpi_compat.py b/my/core/hpi_compat.py index 61121de..3c567d9 100644 --- a/my/core/hpi_compat.py +++ b/my/core/hpi_compat.py @@ -101,7 +101,7 @@ Please install {' '.join(requires)} as PIP packages (see the corresponding READM def _get_dal(cfg, module_name: str): mpath = getattr(cfg, module_name, None) if mpath is not None: - from .common import import_dir + from .utils.imports import import_dir return import_dir(mpath, '.dal') else: diff --git a/my/core/utils/imports.py b/my/core/utils/imports.py new file mode 100644 index 0000000..efd8e9a --- /dev/null +++ b/my/core/utils/imports.py @@ -0,0 +1,37 @@ +import importlib +import importlib.util +from pathlib import Path +import sys +from typing import Optional +from types import ModuleType + +from ..common import PathIsh + + +# TODO only used in tests? not sure if useful at all. +def import_file(p: PathIsh, name: Optional[str] = None) -> ModuleType: + p = Path(p) + if name is None: + name = p.stem + spec = importlib.util.spec_from_file_location(name, p) + assert spec is not None, f"Fatal error; Could not create module spec from {name} {p}" + foo = importlib.util.module_from_spec(spec) + loader = spec.loader; assert loader is not None + loader.exec_module(foo) + return foo + + +def import_from(path: PathIsh, name: str) -> ModuleType: + path = str(path) + sys.path.append(path) + try: + return importlib.import_module(name) + finally: + sys.path.remove(path) + + +def import_dir(path: PathIsh, extra: str = '') -> ModuleType: + p = Path(path) + if p.parts[0] == '~': + p = p.expanduser() # TODO eh. not sure about this.. + return import_from(p.parent, p.name + extra) diff --git a/my/core/utils/itertools.py b/my/core/utils/itertools.py index cab4b2c..7046acf 100644 --- a/my/core/utils/itertools.py +++ b/my/core/utils/itertools.py @@ -105,12 +105,13 @@ else: def test_listify() -> None: + from ..compat import assert_type + @listify def it() -> Iterator[int]: yield 1 yield 2 res = it() - from typing_extensions import assert_type # TODO move to compat? assert_type(res, List[int]) assert res == [1, 2] diff --git a/my/demo.py b/my/demo.py index 75954d6..645be4f 100644 --- a/my/demo.py +++ b/my/demo.py @@ -23,7 +23,7 @@ class demo(user_config): def external_module(self): rpath = self.external if rpath is not None: - from .core.common import import_dir + from .core.utils.imports import import_dir return import_dir(rpath) import my.config.repos.external as m # type: ignore diff --git a/tests/extra/polar.py b/tests/extra/polar.py index b2bc562..b5858b6 100644 --- a/tests/extra/polar.py +++ b/tests/extra/polar.py @@ -15,7 +15,7 @@ def test_hpi(prepare: str) -> None: assert len(list(get_entries())) > 1 def test_orger(prepare: str, tmp_path: Path) -> None: - from my.core.common import import_from, import_file + from my.core.utils.imports import import_from, import_file om = import_file(ROOT / 'orger/modules/polar.py') # reload(om) From 06084a8787786bacc76705fd9e2177023a52d9fb Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Wed, 14 Aug 2024 12:56:48 +0300 Subject: [PATCH 058/122] my.core.common: move warn_if_empty to my.core.utils.itertools, cleanup and add more tests --- my/core/__init__.py | 2 +- my/core/common.py | 64 ++------------------- my/core/tests/test_common.py | 54 ------------------ my/core/utils/itertools.py | 105 ++++++++++++++++++++++++++++++++++- my/ip/all.py | 2 +- 5 files changed, 112 insertions(+), 115 deletions(-) delete mode 100644 my/core/tests/test_common.py diff --git a/my/core/__init__.py b/my/core/__init__.py index c79e36e..0ba8bda 100644 --- a/my/core/__init__.py +++ b/my/core/__init__.py @@ -1,10 +1,10 @@ # this file only keeps the most common & critical types/utility functions from .common import get_files, PathIsh, Paths from .common import Json -from .common import warn_if_empty from .common import stat, Stats from .common import datetime_naive, datetime_aware from .compat import assert_never +from .utils.itertools import warn_if_empty from .cfg import make_config from .error import Res, unwrap diff --git a/my/core/common.py b/my/core/common.py index 389dedc..f84a395 100644 --- a/my/core/common.py +++ b/my/core/common.py @@ -185,64 +185,6 @@ def get_valid_filename(s: str) -> str: return re.sub(r'(?u)[^-\w.]', '', s) -from typing import Generic, Sized, Callable - - -# X = TypeVar('X') -def _warn_iterator(it, f: Any=None): - emitted = False - for i in it: - yield i - emitted = True - if not emitted: - warnings.warn(f"Function {f} didn't emit any data, make sure your config paths are correct") - - -# TODO ugh, so I want to express something like: -# X = TypeVar('X') -# C = TypeVar('C', bound=Iterable[X]) -# _warn_iterable(it: C) -> C -# but apparently I can't??? ugh. -# https://github.com/python/typing/issues/548 -# I guess for now overloads are fine... - -from typing import overload -X = TypeVar('X') -@overload -def _warn_iterable(it: List[X] , f: Any=None) -> List[X] : ... -@overload -def _warn_iterable(it: Iterable[X], f: Any=None) -> Iterable[X]: ... -def _warn_iterable(it, f=None): - if isinstance(it, Sized): - sz = len(it) - if sz == 0: - warnings.warn(f"Function {f} returned empty container, make sure your config paths are correct") - return it - else: - return _warn_iterator(it, f=f) - - -# ok, this seems to work... -# https://github.com/python/mypy/issues/1927#issue-167100413 -FL = TypeVar('FL', bound=Callable[..., List]) -FI = TypeVar('FI', bound=Callable[..., Iterable]) - -@overload -def warn_if_empty(f: FL) -> FL: ... -@overload -def warn_if_empty(f: FI) -> FI: ... - - -def warn_if_empty(f): - from functools import wraps - - @wraps(f) - def wrapped(*args, **kwargs): - res = f(*args, **kwargs) - return _warn_iterable(res, f=f) - return wrapped - - # global state that turns on/off quick stats # can use the 'quick_stats' contextmanager # to enable/disable this in cli so that module 'stats' @@ -586,6 +528,12 @@ if not TYPE_CHECKING: return UI.listify(*args, **kwargs) + @deprecated('use my.core.warn_if_empty instead') + def warn_if_empty(*args, **kwargs): + from .utils import itertools as UI + + return UI.listify(*args, **kwargs) + # todo wrap these in deprecated decorator as well? from .cachew import mcachew # noqa: F401 diff --git a/my/core/tests/test_common.py b/my/core/tests/test_common.py deleted file mode 100644 index a2019e4..0000000 --- a/my/core/tests/test_common.py +++ /dev/null @@ -1,54 +0,0 @@ -from typing import Iterable, List -import warnings - -from ..common import ( - warn_if_empty, - _warn_iterable, -) - - -def test_warn_if_empty() -> None: - @warn_if_empty - def nonempty() -> Iterable[str]: - yield 'a' - yield 'aba' - - @warn_if_empty - def empty() -> List[int]: - return [] - - # should be rejected by mypy! - # todo how to actually test it? - # @warn_if_empty - # def baad() -> float: - # return 0.00 - - # reveal_type(nonempty) - # reveal_type(empty) - - with warnings.catch_warnings(record=True) as w: - assert list(nonempty()) == ['a', 'aba'] - assert len(w) == 0 - - eee = empty() - assert eee == [] - assert len(w) == 1 - - -def test_warn_iterable() -> None: - i1: List[str] = ['a', 'b'] - i2: Iterable[int] = iter([1, 2, 3]) - # reveal_type(i1) - # reveal_type(i2) - x1 = _warn_iterable(i1) - x2 = _warn_iterable(i2) - # vvvv this should be flagged by mypy - # _warn_iterable(123) - # reveal_type(x1) - # reveal_type(x2) - with warnings.catch_warnings(record=True) as w: - assert x1 is i1 # should be unchanged! - assert len(w) == 0 - - assert list(x2) == [1, 2, 3] - assert len(w) == 0 diff --git a/my/core/utils/itertools.py b/my/core/utils/itertools.py index 7046acf..3997310 100644 --- a/my/core/utils/itertools.py +++ b/my/core/utils/itertools.py @@ -4,7 +4,8 @@ Various helpers/transforms of iterators Ideally this should be as small as possible and we should rely on stdlib itertools or more_itertools """ -from typing import Callable, Dict, Iterable, Iterator, TypeVar, List, cast, TYPE_CHECKING +from typing import Callable, Dict, Iterable, Iterator, Sized, TypeVar, List, cast, TYPE_CHECKING +import warnings from ..compat import ParamSpec @@ -115,3 +116,105 @@ def test_listify() -> None: res = it() assert_type(res, List[int]) assert res == [1, 2] + + +@decorator +def _warn_if_empty(func, *args, **kwargs): + # so there is a more_itertools.peekable which could work nicely for these purposes + # the downside is that it would start advancing the generator right after it's created + # , which can be somewhat confusing + iterable = func(*args, **kwargs) + + if isinstance(iterable, Sized): + sz = len(iterable) + if sz == 0: + # todo use hpi warnings here? + warnings.warn(f"Function {func} returned empty container, make sure your config paths are correct") + return iterable + else: # must be an iterator + + def wit(): + empty = True + for i in iterable: + yield i + empty = False + if empty: + warnings.warn(f"Function {func} didn't emit any data, make sure your config paths are correct") + + return wit() + + +if TYPE_CHECKING: + FF = TypeVar('FF', bound=Callable[..., Iterable]) + + def warn_if_empty(f: FF) -> FF: ... + +else: + warn_if_empty = _warn_if_empty + + +def test_warn_if_empty_iterator() -> None: + from ..compat import assert_type + + @warn_if_empty + def nonempty() -> Iterator[str]: + yield 'a' + yield 'aba' + + with warnings.catch_warnings(record=True) as w: + res1 = nonempty() + assert len(w) == 0 # warning isn't emitted until iterator is consumed + assert_type(res1, Iterator[str]) + # assert isinstance(res1, generator) # FIXME ??? how + assert list(res1) == ['a', 'aba'] + assert len(w) == 0 + + @warn_if_empty + def empty() -> Iterator[int]: + yield from [] + + with warnings.catch_warnings(record=True) as w: + res2 = empty() + assert len(w) == 0 # warning isn't emitted until iterator is consumed + assert_type(res2, Iterator[int]) + # assert isinstance(res1, generator) # FIXME ??? how + assert list(res2) == [] + assert len(w) == 1 + + +def test_warn_if_empty_list() -> None: + from ..compat import assert_type + + ll = [1, 2, 3] + + @warn_if_empty + def nonempty() -> List[int]: + return ll + + + with warnings.catch_warnings(record=True) as w: + res1 = nonempty() + assert len(w) == 0 + assert_type(res1, List[int]) + assert isinstance(res1, list) + assert res1 is ll # object should be unchanged! + + + @warn_if_empty + def empty() -> List[str]: + return [] + + + with warnings.catch_warnings(record=True) as w: + res2 = empty() + assert len(w) == 1 + assert_type(res2, List[str]) + assert isinstance(res2, list) + assert res2 == [] + + +def test_warn_if_empty_unsupported() -> None: + # these should be rejected by mypy! (will show "unused type: ignore" if we break it) + @warn_if_empty # type: ignore[type-var] + def bad_return_type() -> float: + return 0.00 diff --git a/my/ip/all.py b/my/ip/all.py index f4cdb37..46c1fec 100644 --- a/my/ip/all.py +++ b/my/ip/all.py @@ -11,7 +11,7 @@ REQUIRES = ["git+https://github.com/seanbreckenridge/ipgeocache"] from typing import Iterator -from my.core.common import Stats, warn_if_empty +from my.core import Stats, warn_if_empty from my.ip.common import IP From bcc4c1530432754f1f5a9bca759ee48ea6535046 Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Thu, 15 Aug 2024 13:28:45 +0300 Subject: [PATCH 059/122] core: cleanup my.core.common.unique_everseen - move to my.core.utils.itertools - more robust check for hashable types -- now checks in runtime (since the one based on types purely isn't necessarily sound) - add more testing --- my/core/common.py | 59 +------------ my/core/tests/common.py | 19 +++++ my/core/utils/itertools.py | 168 +++++++++++++++++++++++++++++++++++-- 3 files changed, 183 insertions(+), 63 deletions(-) diff --git a/my/core/common.py b/my/core/common.py index f84a395..bfc3505 100644 --- a/my/core/common.py +++ b/my/core/common.py @@ -6,13 +6,11 @@ import functools from contextlib import contextmanager import os import sys -import types from typing import ( Any, Callable, Dict, Iterable, - Iterator, List, Optional, Sequence, @@ -21,9 +19,6 @@ from typing import ( TypeVar, Union, cast, - get_args, - get_type_hints, - get_origin, ) import warnings @@ -426,58 +421,8 @@ class DummyExecutor(Executor): self._shutdown = True -def _check_all_hashable(fun): - # TODO ok, take callable? - hints = get_type_hints(fun) - # TODO needs to be defensive like in cachew? - return_type = hints.get('return') - # TODO check if None - origin = get_origin(return_type) # Iterator etc? - (arg,) = get_args(return_type) - # options we wanna handle are simple type on the top level or union - arg_origin = get_origin(arg) - - if sys.version_info[:2] >= (3, 10): - is_uniontype = arg_origin is types.UnionType - else: - is_uniontype = False - - is_union = arg_origin is Union or is_uniontype - if is_union: - to_check = get_args(arg) - else: - to_check = (arg,) - - no_hash = [ - t - for t in to_check - # seems that objects that have not overridden hash have the attribute but it's set to None - if getattr(t, '__hash__', None) is None - ] - assert len(no_hash) == 0, f'Types {no_hash} are not hashable, this will result in significant performance downgrade for unique_everseen' - - -_UET = TypeVar('_UET') -_UEU = TypeVar('_UEU') - - -def unique_everseen( - fun: Callable[[], Iterable[_UET]], - key: Optional[Callable[[_UET], _UEU]] = None, -) -> Iterator[_UET]: - # TODO support normal iterable as well? - import more_itertools - - # NOTE: it has to take original callable, because otherwise we don't have access to generator type annotations - iterable = fun() - - if key is None: - # todo check key return type as well? but it's more likely to be hashable - if os.environ.get('HPI_CHECK_UNIQUE_EVERSEEN') is not None: - # TODO return better error here, e.g. if there is no return type it crashes - _check_all_hashable(fun) - - return more_itertools.unique_everseen(iterable=iterable, key=key) +# TODO deprecate and suggest to use one from my.core directly? not sure +from .utils.itertools import unique_everseen ### legacy imports, keeping them here for backwards compatibility diff --git a/my/core/tests/common.py b/my/core/tests/common.py index d6fb71e..a102ad3 100644 --- a/my/core/tests/common.py +++ b/my/core/tests/common.py @@ -1,4 +1,6 @@ +from contextlib import contextmanager import os +from typing import Iterator, Optional import pytest @@ -10,3 +12,20 @@ skip_if_uses_optional_deps = pytest.mark.skipif( V not in os.environ, reason=f'test only works when optional dependencies are installed. Set env variable {V}=true to override.', ) + + +# TODO maybe move to hpi core? +@contextmanager +def tmp_environ_set(key: str, value: Optional[str]) -> Iterator[None]: + prev_value = os.environ.get(key) + if value is None: + os.environ.pop(key, None) + else: + os.environ[key] = value + try: + yield + finally: + if prev_value is None: + os.environ.pop(key, None) + else: + os.environ[key] = prev_value diff --git a/my/core/utils/itertools.py b/my/core/utils/itertools.py index 3997310..e8802bb 100644 --- a/my/core/utils/itertools.py +++ b/my/core/utils/itertools.py @@ -4,12 +4,26 @@ Various helpers/transforms of iterators Ideally this should be as small as possible and we should rely on stdlib itertools or more_itertools """ -from typing import Callable, Dict, Iterable, Iterator, Sized, TypeVar, List, cast, TYPE_CHECKING +from collections.abc import Hashable +from typing import ( + Callable, + Dict, + Iterable, + Iterator, + List, + Optional, + Sized, + Union, + TypeVar, + cast, + TYPE_CHECKING, +) import warnings from ..compat import ParamSpec from decorator import decorator +import more_itertools T = TypeVar('T') K = TypeVar('K') @@ -165,7 +179,6 @@ def test_warn_if_empty_iterator() -> None: res1 = nonempty() assert len(w) == 0 # warning isn't emitted until iterator is consumed assert_type(res1, Iterator[str]) - # assert isinstance(res1, generator) # FIXME ??? how assert list(res1) == ['a', 'aba'] assert len(w) == 0 @@ -177,7 +190,6 @@ def test_warn_if_empty_iterator() -> None: res2 = empty() assert len(w) == 0 # warning isn't emitted until iterator is consumed assert_type(res2, Iterator[int]) - # assert isinstance(res1, generator) # FIXME ??? how assert list(res2) == [] assert len(w) == 1 @@ -191,7 +203,6 @@ def test_warn_if_empty_list() -> None: def nonempty() -> List[int]: return ll - with warnings.catch_warnings(record=True) as w: res1 = nonempty() assert len(w) == 0 @@ -199,12 +210,10 @@ def test_warn_if_empty_list() -> None: assert isinstance(res1, list) assert res1 is ll # object should be unchanged! - @warn_if_empty def empty() -> List[str]: return [] - with warnings.catch_warnings(record=True) as w: res2 = empty() assert len(w) == 1 @@ -218,3 +227,150 @@ def test_warn_if_empty_unsupported() -> None: @warn_if_empty # type: ignore[type-var] def bad_return_type() -> float: return 0.00 + + +_HT = TypeVar('_HT', bound=Hashable) + + +# NOTE: ideally we'do It = TypeVar('It', bound=Iterable[_HT]), and function would be It -> It +# Sadly this doesn't work in mypy, doesn't look like we can have double bound TypeVar +# Not a huge deal, since this function is for unique_eversee and +# we need to pass iterator to unique_everseen anyway +# TODO maybe contribute to more_itertools? https://github.com/more-itertools/more-itertools/issues/898 +def check_if_hashable(iterable: Iterable[_HT]) -> Iterable[_HT]: + """ + NOTE: Despite Hashable bound, typing annotation doesn't guarantee runtime safety + Consider hashable type X, and Y that inherits from X, but not hashable + Then l: List[X] = [Y(...)] is a valid expression, and type checks against Hashable, + but isn't runtime hashable + """ + # Sadly this doesn't work 100% correctly with dataclasses atm... + # they all are considered hashable: https://github.com/python/mypy/issues/11463 + + if isinstance(iterable, Iterator): + + def res() -> Iterator[_HT]: + for i in iterable: + assert isinstance(i, Hashable), i + # ugh. need a cast due to https://github.com/python/mypy/issues/10817 + yield cast(_HT, i) + + return res() + else: + # hopefully, iterable that can be iterated over multiple times? + # not sure if should have 'allowlist' of types that don't have to be transformed instead? + for i in iterable: + assert isinstance(i, Hashable), i + return iterable + + +# TODO different policies -- error/warn/ignore? +def test_check_if_hashable() -> None: + from dataclasses import dataclass + from typing import Set, Tuple + import pytest + from ..compat import assert_type + + x1: List[int] = [1, 2] + r1 = check_if_hashable(x1) + # tgype: ignore[comparison-overlap] # object should be unchanged + assert r1 is x1 + assert_type(r1, Iterable[int]) + + x2: Iterator[Union[int, str]] = iter((123, 'aba')) + r2 = check_if_hashable(x2) + assert list(r2) == [123, 'aba'] + assert_type(r2, Iterable[Union[int, str]]) + + x3: Tuple[object, ...] = (789, 'aba') + r3 = check_if_hashable(x3) + # ttype: ignore[comparison-overlap] # object should be unchanged + assert r3 is x3 + assert_type(r3, Iterable[object]) + + x4: List[Set[int]] = [{1, 2, 3}, {4, 5, 6}] + with pytest.raises(Exception): + # should be rejected by mypy sice set isn't Hashable, but also throw at runtime + r4 = check_if_hashable(x4) # type: ignore[type-var] + + x5: Iterator[object] = iter([{1, 2}, {3, 4}]) + # here, we hide behind object, which is hashable + # so mypy can't really help us anything + r5 = check_if_hashable(x5) + with pytest.raises(Exception): + # note: this only throws when iterator is advanced + list(r5) + + # dataclass is unhashable by default! unless frozen=True and eq=True, or unsafe_hash=True + @dataclass(unsafe_hash=True) + class X: + a: int + + x6: List[X] = [X(a=123)] + r6 = check_if_hashable(x6) + assert x6 is r6 + + # inherited dataclass will not be hashable! + @dataclass + class Y(X): + b: str + + x7: List[Y] = [Y(a=123, b='aba')] + with pytest.raises(Exception): + # ideally that would also be rejected by mypy, but currently there is a bug + # which treats all dataclasses as hashable: https://github.com/python/mypy/issues/11463 + check_if_hashable(x7) + + +_UET = TypeVar('_UET') +_UEU = TypeVar('_UEU') + + +# NOTE: for historic reasons, this function had to accept Callable that retuns iterator +# instead of just iterator +# TODO maybe deprecated Callable support? not sure +def unique_everseen( + fun: Union[ + Callable[[], Iterable[_UET]], + Iterable[_UET] + ], + key: Optional[Callable[[_UET], _UEU]] = None, +) -> Iterator[_UET]: + import os + + if callable(fun): + iterable = fun() + else: + iterable = fun + + if key is None: + # todo check key return type as well? but it's more likely to be hashable + if os.environ.get('HPI_CHECK_UNIQUE_EVERSEEN') is not None: + iterable = check_if_hashable(iterable) + + return more_itertools.unique_everseen(iterable=iterable, key=key) + + +def test_unique_everseen() -> None: + import pytest + from ..tests.common import tmp_environ_set + + def fun_good() -> Iterator[int]: + yield 123 + + def fun_bad(): + return [{1, 2}, {1, 2}, {1, 3}] + + with tmp_environ_set('HPI_CHECK_UNIQUE_EVERSEEN', 'yes'): + assert list(unique_everseen(fun_good)) == [123] + + with pytest.raises(Exception): + # since function retuns a list rather than iterator, check happens immediately + # , even without advancing the iterator + unique_everseen(fun_bad) + + good_list = [4, 3, 2, 1, 2, 3, 4] + assert list(unique_everseen(good_list)) == [4, 3, 2, 1] + + with tmp_environ_set('HPI_CHECK_UNIQUE_EVERSEEN', None): + assert list(unique_everseen(fun_bad)) == [{1, 2}, {1, 3}] From 18529257e76350ba65901060610aa294a3f3629b Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Thu, 15 Aug 2024 14:15:23 +0300 Subject: [PATCH 060/122] core.common: move DummyExecutor to core.common.utils.concurrent without backwards compat, unlikely it's been used by anyone --- my/core/common.py | 40 ----------------------------- my/core/utils/concurrent.py | 51 +++++++++++++++++++++++++++++++++++++ my/pdfs.py | 2 +- 3 files changed, 52 insertions(+), 41 deletions(-) create mode 100644 my/core/utils/concurrent.py diff --git a/my/core/common.py b/my/core/common.py index bfc3505..739971c 100644 --- a/my/core/common.py +++ b/my/core/common.py @@ -5,7 +5,6 @@ from dataclasses import is_dataclass, asdict as dataclasses_asdict import functools from contextlib import contextmanager import os -import sys from typing import ( Any, Callable, @@ -382,45 +381,6 @@ def assert_subpackage(name: str) -> None: assert name == '__main__' or 'my.core' in name, f'Expected module __name__ ({name}) to be __main__ or start with my.core' -from .compat import ParamSpec -_P = ParamSpec('_P') -_T = TypeVar('_T') - -# https://stackoverflow.com/a/10436851/706389 -from concurrent.futures import Future, Executor -class DummyExecutor(Executor): - def __init__(self, max_workers: Optional[int]=1) -> None: - self._shutdown = False - self._max_workers = max_workers - - if TYPE_CHECKING: - if sys.version_info[:2] <= (3, 8): - # 3.8 doesn't support ParamSpec as Callable arg :( - # and any attempt to type results in incompatible supertype.. so whatever - def submit(self, fn, *args, **kwargs): ... - else: - def submit(self, fn: Callable[_P, _T], /, *args: _P.args, **kwargs: _P.kwargs) -> Future[_T]: ... - else: - def submit(self, fn, *args, **kwargs): - if self._shutdown: - raise RuntimeError('cannot schedule new futures after shutdown') - - f: Future[Any] = Future() - try: - result = fn(*args, **kwargs) - except KeyboardInterrupt: - raise - except BaseException as e: - f.set_exception(e) - else: - f.set_result(result) - - return f - - def shutdown(self, wait: bool=True, **kwargs) -> None: - self._shutdown = True - - # TODO deprecate and suggest to use one from my.core directly? not sure from .utils.itertools import unique_everseen diff --git a/my/core/utils/concurrent.py b/my/core/utils/concurrent.py new file mode 100644 index 0000000..cc17cda --- /dev/null +++ b/my/core/utils/concurrent.py @@ -0,0 +1,51 @@ +from concurrent.futures import Future, Executor +import sys +from typing import Any, Callable, Optional, TypeVar, TYPE_CHECKING + +from ..compat import ParamSpec + + +_P = ParamSpec('_P') +_T = TypeVar('_T') + + +# https://stackoverflow.com/a/10436851/706389 +class DummyExecutor(Executor): + """ + This is useful if you're already using Executor for parallelising, + but also want to provide an option to run the code serially (e.g. for debugging) + """ + def __init__(self, max_workers: Optional[int] = 1) -> None: + self._shutdown = False + self._max_workers = max_workers + + if TYPE_CHECKING: + if sys.version_info[:2] <= (3, 8): + # 3.8 doesn't support ParamSpec as Callable arg :( + # and any attempt to type results in incompatible supertype.. so whatever + def submit(self, fn, *args, **kwargs): ... + + else: + + def submit(self, fn: Callable[_P, _T], /, *args: _P.args, **kwargs: _P.kwargs) -> Future[_T]: ... + + else: + + def submit(self, fn, *args, **kwargs): + if self._shutdown: + raise RuntimeError('cannot schedule new futures after shutdown') + + f: Future[Any] = Future() + try: + result = fn(*args, **kwargs) + except KeyboardInterrupt: + raise + except BaseException as e: + f.set_exception(e) + else: + f.set_result(result) + + return f + + def shutdown(self, wait: bool = True, **kwargs) -> None: + self._shutdown = True diff --git a/my/pdfs.py b/my/pdfs.py index b3ef85d..0ab4af3 100644 --- a/my/pdfs.py +++ b/my/pdfs.py @@ -121,7 +121,7 @@ def _iter_annotations(pdfs: Sequence[Path]) -> Iterator[Res[Annotation]]: # todo how to print to stdout synchronously? # todo global config option not to use pools? useful for debugging.. from concurrent.futures import ProcessPoolExecutor - from my.core.common import DummyExecutor + from my.core.utils.concurrent import DummyExecutor workers = None # use 0 for debugging Pool = DummyExecutor if workers == 0 else ProcessPoolExecutor with Pool(workers) as pool: From c45c51af22aa9346bfd1613fccefa0617cec5bf6 Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Thu, 15 Aug 2024 17:51:46 +0300 Subject: [PATCH 061/122] core.common: move stats-related stuff to my.core.stats and add more thorough tests/docs deprecate core.common.stat and core.common.Stats with backwards compatibility --- my/calendar/holidays.py | 4 +- my/core/__init__.py | 2 +- my/core/__main__.py | 13 +- my/core/common.py | 193 +------------- my/core/stats.py | 333 +++++++++++++++++++++++-- my/core/util.py | 12 - my/google/takeout/parser.py | 6 +- my/location/google.py | 2 +- my/location/google_takeout.py | 2 +- my/location/google_takeout_semantic.py | 3 +- my/reddit/all.py | 3 +- my/reddit/pushshift.py | 4 +- my/rescuetime.py | 3 +- my/smscalls.py | 9 +- 14 files changed, 343 insertions(+), 246 deletions(-) diff --git a/my/calendar/holidays.py b/my/calendar/holidays.py index 6fa3560..f73bf70 100644 --- a/my/calendar/holidays.py +++ b/my/calendar/holidays.py @@ -9,7 +9,8 @@ from datetime import date, datetime, timedelta from functools import lru_cache from typing import Union -from ..core.time import zone_to_countrycode +from my.core import Stats +from my.core.time import zone_to_countrycode @lru_cache(1) @@ -46,7 +47,6 @@ def is_workday(d: DateIsh) -> bool: return not is_holiday(d) -from ..core.common import Stats def stats() -> Stats: # meh, but not sure what would be a better test? res = {} diff --git a/my/core/__init__.py b/my/core/__init__.py index 0ba8bda..3881485 100644 --- a/my/core/__init__.py +++ b/my/core/__init__.py @@ -1,7 +1,7 @@ # this file only keeps the most common & critical types/utility functions from .common import get_files, PathIsh, Paths from .common import Json -from .common import stat, Stats +from .stats import stat, Stats from .common import datetime_naive, datetime_aware from .compat import assert_never from .utils.itertools import warn_if_empty diff --git a/my/core/__main__.py b/my/core/__main__.py index ca88513..c9a4945 100644 --- a/my/core/__main__.py +++ b/my/core/__main__.py @@ -243,9 +243,8 @@ def modules_check(*, verbose: bool, list_all: bool, quick: bool, for_modules: Li import contextlib - from .common import quick_stats - from .util import get_stats, HPIModule - from .stats import guess_stats + from .util import HPIModule + from .stats import get_stats, quick_stats from .error import warn_my_config_import_error mods: Iterable[HPIModule] @@ -276,11 +275,8 @@ def modules_check(*, verbose: bool, list_all: bool, quick: bool, for_modules: Li continue info(f'{click.style("OK", fg="green")} : {m:<50}') - # first try explicitly defined stats function: - stats = get_stats(m) - if stats is None: - # then try guessing.. not sure if should log somehow? - stats = guess_stats(m, quick=quick) + # TODO add hpi 'stats'? instead of doctor? not sure + stats = get_stats(m, guess=True) if stats is None: eprint(" - no 'stats' function, can't check the data") @@ -291,6 +287,7 @@ def modules_check(*, verbose: bool, list_all: bool, quick: bool, for_modules: Li try: kwargs = {} + # todo hmm why wouldn't they be callable?? if callable(stats) and 'quick' in inspect.signature(stats).parameters: kwargs['quick'] = quick with quick_context: diff --git a/my/core/common.py b/my/core/common.py index 739971c..926861d 100644 --- a/my/core/common.py +++ b/my/core/common.py @@ -3,7 +3,6 @@ from pathlib import Path from datetime import datetime from dataclasses import is_dataclass, asdict as dataclasses_asdict import functools -from contextlib import contextmanager import os from typing import ( Any, @@ -11,13 +10,11 @@ from typing import ( Dict, Iterable, List, - Optional, Sequence, TYPE_CHECKING, Tuple, TypeVar, Union, - cast, ) import warnings @@ -179,183 +176,6 @@ def get_valid_filename(s: str) -> str: return re.sub(r'(?u)[^-\w.]', '', s) -# global state that turns on/off quick stats -# can use the 'quick_stats' contextmanager -# to enable/disable this in cli so that module 'stats' -# functions don't have to implement custom 'quick' logic -QUICK_STATS = False - - -# in case user wants to use the stats functions/quick option -# elsewhere -- can use this decorator instead of editing -# the global state directly -@contextmanager -def quick_stats(): - global QUICK_STATS - prev = QUICK_STATS - try: - QUICK_STATS = True - yield - finally: - QUICK_STATS = prev - - -C = TypeVar('C') -Stats = Dict[str, Any] -StatsFun = Callable[[], Stats] -# todo not sure about return type... -def stat( - func: Union[Callable[[], Iterable[C]], Iterable[C]], - *, - quick: bool = False, - name: Optional[str] = None, -) -> Stats: - if callable(func): - fr = func() - if hasattr(fr, '__enter__') and hasattr(fr, '__exit__'): - # context managers has Iterable type, but they aren't data providers - # sadly doesn't look like there is a way to tell from typing annotations - return {} - fname = func.__name__ - else: - # meh. means it's just a list.. not sure how to generate a name then - fr = func - fname = f'unnamed_{id(fr)}' - type_name = type(fr).__name__ - if type_name == 'DataFrame': - # dynamic, because pandas is an optional dependency.. - df = cast(Any, fr) # todo ugh, not sure how to annotate properly - res = dict( - dtypes=df.dtypes.to_dict(), - rows=len(df), - ) - else: - res = _stat_iterable(fr, quick=quick) - - stat_name = name if name is not None else fname - return { - stat_name: res, - } - - -def _stat_iterable(it: Iterable[C], quick: bool = False) -> Any: - from more_itertools import ilen, take, first - - # todo not sure if there is something in more_itertools to compute this? - total = 0 - errors = 0 - first_item = None - last_item = None - - def funcit(): - nonlocal errors, first_item, last_item, total - for x in it: - total += 1 - if isinstance(x, Exception): - errors += 1 - else: - last_item = x - if first_item is None: - first_item = x - yield x - - eit = funcit() - count: Any - if quick or QUICK_STATS: - initial = take(100, eit) - count = len(initial) - if first(eit, None) is not None: # todo can actually be none... - # haven't exhausted - count = f'{count}+' - else: - count = ilen(eit) - - res = { - 'count': count, - } - - if total == 0: - # not sure but I guess a good balance? wouldn't want to throw early here? - res['warning'] = 'THE ITERABLE RETURNED NO DATA' - - if errors > 0: - res['errors'] = errors - - def stat_item(item): - if item is None: - return None - if isinstance(item, Path): - return str(item) - return guess_datetime(item) - - if (stat_first := stat_item(first_item)) is not None: - res['first'] = stat_first - - if (stat_last := stat_item(last_item)) is not None: - res['last'] = stat_last - - return res - - -def test_stat_iterable() -> None: - from datetime import datetime, timedelta, timezone - from typing import NamedTuple - - dd = datetime.fromtimestamp(123, tz=timezone.utc) - day = timedelta(days=3) - - X = NamedTuple('X', [('x', int), ('d', datetime)]) - - def it(): - yield RuntimeError('oops!') - for i in range(2): - yield X(x=i, d=dd + day * i) - yield RuntimeError('bad!') - for i in range(3): - yield X(x=i * 10, d=dd + day * (i * 10)) - yield X(x=123, d=dd + day * 50) - - res = _stat_iterable(it()) - assert res['count'] == 1 + 2 + 1 + 3 + 1 - assert res['errors'] == 1 + 1 - assert res['last'] == dd + day * 50 - - -# experimental, not sure about it.. -def guess_datetime(x: Any) -> Optional[datetime]: - # todo hmm implement withoutexception.. - try: - d = asdict(x) - except: # noqa: E722 bare except - return None - for k, v in d.items(): - if isinstance(v, datetime): - return v - return None - -def test_guess_datetime() -> None: - from datetime import datetime - from dataclasses import dataclass - from typing import NamedTuple - - dd = compat.fromisoformat('2021-02-01T12:34:56Z') - - # ugh.. https://github.com/python/mypy/issues/7281 - A = NamedTuple('A', [('x', int)]) - B = NamedTuple('B', [('x', int), ('created', datetime)]) - - assert guess_datetime(A(x=4)) is None - assert guess_datetime(B(x=4, created=dd)) == dd - - @dataclass - class C: - a: datetime - x: int - assert guess_datetime(C(a=dd, x=435)) == dd - # TODO not sure what to return when multiple datetime fields? - # TODO test @property? - - def is_namedtuple(thing: Any) -> bool: # basic check to see if this is namedtuple-like _asdict = getattr(thing, '_asdict', None) @@ -389,6 +209,9 @@ from .utils.itertools import unique_everseen ## hiding behind TYPE_CHECKING so it works in runtime ## in principle, warnings.deprecated decorator should cooperate with mypy, but doesn't look like it works atm? ## perhaps it doesn't work when it's used from typing_extensions + +from .compat import Never + if not TYPE_CHECKING: @deprecated('use my.core.compat.assert_never instead') @@ -439,6 +262,12 @@ if not TYPE_CHECKING: return UI.listify(*args, **kwargs) + @deprecated('use my.core.stat instead') + def stat(*args, **kwargs): + from . import stats + + return stats.stat(*args, **kwargs) + # todo wrap these in deprecated decorator as well? from .cachew import mcachew # noqa: F401 @@ -447,7 +276,7 @@ if not TYPE_CHECKING: # TODO hmm how to deprecate it in runtime? tricky cause it's actually a class? tzdatetime = datetime_aware else: - from .compat import Never - tzdatetime = Never # makes it invalid as a type while working in runtime + +Stats = Never ### diff --git a/my/core/stats.py b/my/core/stats.py index 44735b8..d5a43c3 100644 --- a/my/core/stats.py +++ b/my/core/stats.py @@ -1,23 +1,181 @@ ''' Helpers for hpi doctor/stats functionality. ''' + import collections +from contextlib import contextmanager +from datetime import datetime import importlib import inspect +from pathlib import Path +from types import ModuleType import typing -from typing import Optional, Callable, Any, Iterator, Sequence, Dict, List +from typing import ( + Any, + Callable, + Dict, + Iterable, + Iterator, + List, + Optional, + Protocol, + Sequence, + Union, + cast, +) -from .common import StatsFun, Stats, stat + +Stats = Dict[str, Any] + + +class StatsFun(Protocol): + def __call__(self, quick: bool = False) -> Stats: ... + + +# global state that turns on/off quick stats +# can use the 'quick_stats' contextmanager +# to enable/disable this in cli so that module 'stats' +# functions don't have to implement custom 'quick' logic +QUICK_STATS = False + + +# in case user wants to use the stats functions/quick option +# elsewhere -- can use this decorator instead of editing +# the global state directly +@contextmanager +def quick_stats(): + global QUICK_STATS + prev = QUICK_STATS + try: + QUICK_STATS = True + yield + finally: + QUICK_STATS = prev + + +def stat( + func: Union[Callable[[], Iterable[Any]], Iterable[Any]], + *, + quick: bool = False, + name: Optional[str] = None, +) -> Stats: + """ + Extracts various statistics from a passed iterable/callable, e.g.: + - number of items + - first/last item + - timestamps associated with first/last item + + If quick is set, then only first 100 items of the iterable will be processed + """ + if callable(func): + fr = func() + if hasattr(fr, '__enter__') and hasattr(fr, '__exit__'): + # context managers has Iterable type, but they aren't data providers + # sadly doesn't look like there is a way to tell from typing annotations + # Ideally we'd detect this in is_data_provider... + # but there is no way of knowing without actually calling it first :( + return {} + fname = func.__name__ + else: + # meh. means it's just a list.. not sure how to generate a name then + fr = func + fname = f'unnamed_{id(fr)}' + type_name = type(fr).__name__ + extras = {} + if type_name == 'DataFrame': + # dynamic, because pandas is an optional dependency.. + df = cast(Any, fr) # todo ugh, not sure how to annotate properly + df = df.reset_index() + + fr = df.to_dict(orient='records') + + dtypes = df.dtypes.to_dict() + extras['dtypes'] = dtypes + + res = _stat_iterable(fr, quick=quick) + res.update(extras) + + stat_name = name if name is not None else fname + return { + stat_name: res, + } + + +def test_stat() -> None: + # the bulk of testing is in test_stat_iterable + + # works with 'anonymous' lists + res = stat([1, 2, 3]) + [(name, v)] = res.items() + # note: name will be a little funny since anonymous list doesn't have one + assert v == {'count': 3} + # + + # works with functions: + def fun(): + return [4, 5, 6] + + assert stat(fun) == {'fun': {'count': 3}} + # + + # context managers are technically iterable + # , but usually we wouldn't want to compute stats for them + # this is mainly intended for guess_stats, + # since it can't tell whether the function is a ctx manager without calling it + @contextmanager + def cm(): + yield 1 + yield 3 + + assert stat(cm) == {} # type: ignore[arg-type] + # + + # works with pandas dataframes + import pandas as pd + import numpy as np + + def df() -> pd.DataFrame: + dates = pd.date_range(start='2024-02-10 08:00', end='2024-02-11 16:00', freq='5h') + return pd.DataFrame([f'value{i}' for i, _ in enumerate(dates)], index=dates, columns=['value']) + + assert stat(df) == { + 'df': { + 'count': 7, + 'dtypes': { + 'index': np.dtype(' Optional[StatsFun]: + stats: Optional[StatsFun] = None + try: + module = importlib.import_module(module_name) + except Exception: + return None + stats = getattr(module, 'stats', None) + if stats is None: + stats = guess_stats(module) + return stats # TODO maybe could be enough to annotate OUTPUTS or something like that? # then stats could just use them as hints? -def guess_stats(module_name: str, quick: bool = False) -> Optional[StatsFun]: - providers = guess_data_providers(module_name) +def guess_stats(module: ModuleType) -> Optional[StatsFun]: + """ + If the module doesn't have explicitly defined 'stat' function, + this is used to try to guess what could be included in stats automatically + """ + providers = _guess_data_providers(module) if len(providers) == 0: return None - def auto_stats() -> Stats: + def auto_stats(quick: bool = False) -> Stats: res = {} for k, v in providers.items(): res.update(stat(v, quick=quick, name=k)) @@ -27,12 +185,11 @@ def guess_stats(module_name: str, quick: bool = False) -> Optional[StatsFun]: def test_guess_stats() -> None: - from datetime import datetime import my.core.tests.auto_stats as M - auto_stats = guess_stats(M.__name__) + auto_stats = guess_stats(M) assert auto_stats is not None - res = auto_stats() + res = auto_stats(quick=False) assert res == { 'inputs': { @@ -48,15 +205,15 @@ def test_guess_stats() -> None: } -def guess_data_providers(module_name: str) -> Dict[str, Callable]: - module = importlib.import_module(module_name) +def _guess_data_providers(module: ModuleType) -> Dict[str, Callable]: mfunctions = inspect.getmembers(module, inspect.isfunction) return {k: v for k, v in mfunctions if is_data_provider(v)} -# todo how to exclude deprecated stuff? +# todo how to exclude deprecated data providers? def is_data_provider(fun: Any) -> bool: """ + Criteria for being a "data provider": 1. returns iterable or something like that 2. takes no arguments? (otherwise not callable by stats anyway?) 3. doesn't start with an underscore (those are probably helper functions?) @@ -72,7 +229,7 @@ def is_data_provider(fun: Any) -> bool: return False # has at least one argument without default values - if len(list(sig_required_params(sig))) > 0: + if len(list(_sig_required_params(sig))) > 0: return False if hasattr(fun, '__name__'): @@ -88,7 +245,7 @@ def is_data_provider(fun: Any) -> bool: if return_type is None: return False - return type_is_iterable(return_type) + return _type_is_iterable(return_type) def test_is_data_provider() -> None: @@ -99,6 +256,7 @@ def test_is_data_provider() -> None: def no_return_type(): return [1, 2, 3] + assert not idp(no_return_type) lam = lambda: [1, 2] @@ -106,27 +264,34 @@ def test_is_data_provider() -> None: def has_extra_args(count) -> List[int]: return list(range(count)) + assert not idp(has_extra_args) def has_return_type() -> Sequence[str]: return ['a', 'b', 'c'] + assert idp(has_return_type) def _helper_func() -> Iterator[Any]: yield 1 + assert not idp(_helper_func) def inputs() -> Iterator[Any]: yield 1 + assert idp(inputs) def producer_inputs() -> Iterator[Any]: yield 1 + assert idp(producer_inputs) -# return any parameters the user is required to provide - those which don't have default values -def sig_required_params(sig: inspect.Signature) -> Iterator[inspect.Parameter]: +def _sig_required_params(sig: inspect.Signature) -> Iterator[inspect.Parameter]: + """ + Returns parameters the user is required to provide - e.g. ones that don't have default values + """ for param in sig.parameters.values(): if param.default == inspect.Parameter.empty: yield param @@ -136,21 +301,24 @@ def test_sig_required_params() -> None: def x() -> int: return 5 - assert len(list(sig_required_params(inspect.signature(x)))) == 0 + + assert len(list(_sig_required_params(inspect.signature(x)))) == 0 def y(arg: int) -> int: return arg - assert len(list(sig_required_params(inspect.signature(y)))) == 1 + + assert len(list(_sig_required_params(inspect.signature(y)))) == 1 # from stats perspective, this should be treated as a data provider as well # could be that the default value to the data provider is the 'default' # path to use for inputs/a function to provide input data def z(arg: int = 5) -> int: return arg - assert len(list(sig_required_params(inspect.signature(z)))) == 0 + + assert len(list(_sig_required_params(inspect.signature(z)))) == 0 -def type_is_iterable(type_spec) -> bool: +def _type_is_iterable(type_spec) -> bool: origin = typing.get_origin(type_spec) if origin is None: return False @@ -167,9 +335,7 @@ def type_is_iterable(type_spec) -> bool: # todo docstring test? def test_type_is_iterable() -> None: - from typing import List, Sequence, Iterable, Dict, Any - - fun = type_is_iterable + fun = _type_is_iterable assert not fun(None) assert not fun(int) assert not fun(Any) @@ -178,3 +344,126 @@ def test_type_is_iterable() -> None: assert fun(List[int]) assert fun(Sequence[Dict[str, str]]) assert fun(Iterable[Any]) + + +def _stat_item(item): + if item is None: + return None + if isinstance(item, Path): + return str(item) + return _guess_datetime(item) + + +def _stat_iterable(it: Iterable[Any], quick: bool = False) -> Stats: + from more_itertools import ilen, take, first + + # todo not sure if there is something in more_itertools to compute this? + total = 0 + errors = 0 + first_item = None + last_item = None + + def funcit(): + nonlocal errors, first_item, last_item, total + for x in it: + total += 1 + if isinstance(x, Exception): + errors += 1 + else: + last_item = x + if first_item is None: + first_item = x + yield x + + eit = funcit() + count: Any + if quick or QUICK_STATS: + initial = take(100, eit) + count = len(initial) + if first(eit, None) is not None: # todo can actually be none... + # haven't exhausted + count = f'{count}+' + else: + count = ilen(eit) + + res = { + 'count': count, + } + + if total == 0: + # not sure but I guess a good balance? wouldn't want to throw early here? + res['warning'] = 'THE ITERABLE RETURNED NO DATA' + + if errors > 0: + res['errors'] = errors + + if (stat_first := _stat_item(first_item)) is not None: + res['first'] = stat_first + + if (stat_last := _stat_item(last_item)) is not None: + res['last'] = stat_last + + return res + + +def test_stat_iterable() -> None: + from datetime import datetime, timedelta, timezone + from typing import NamedTuple + + dd = datetime.fromtimestamp(123, tz=timezone.utc) + day = timedelta(days=3) + + X = NamedTuple('X', [('x', int), ('d', datetime)]) + + def it(): + yield RuntimeError('oops!') + for i in range(2): + yield X(x=i, d=dd + day * i) + yield RuntimeError('bad!') + for i in range(3): + yield X(x=i * 10, d=dd + day * (i * 10)) + yield X(x=123, d=dd + day * 50) + + res = _stat_iterable(it()) + assert res['count'] == 1 + 2 + 1 + 3 + 1 + assert res['errors'] == 1 + 1 + assert res['last'] == dd + day * 50 + + +# experimental, not sure about it.. +def _guess_datetime(x: Any) -> Optional[datetime]: + from .common import asdict # avoid circular imports + + # todo hmm implement without exception.. + try: + d = asdict(x) + except: # noqa: E722 bare except + return None + for k, v in d.items(): + if isinstance(v, datetime): + return v + return None + + +def test_guess_datetime() -> None: + from dataclasses import dataclass + from typing import NamedTuple + from .compat import fromisoformat + + dd = fromisoformat('2021-02-01T12:34:56Z') + + # ugh.. https://github.com/python/mypy/issues/7281 + A = NamedTuple('A', [('x', int)]) + B = NamedTuple('B', [('x', int), ('created', datetime)]) + + assert _guess_datetime(A(x=4)) is None + assert _guess_datetime(B(x=4, created=dd)) == dd + + @dataclass + class C: + a: datetime + x: int + + assert _guess_datetime(C(a=dd, x=435)) == dd + # TODO not sure what to return when multiple datetime fields? + # TODO test @property? diff --git a/my/core/util.py b/my/core/util.py index 1ca2de1..57e41d4 100644 --- a/my/core/util.py +++ b/my/core/util.py @@ -1,6 +1,5 @@ from pathlib import Path from itertools import chain -from importlib import import_module import os import pkgutil import sys @@ -15,17 +14,6 @@ def modules() -> Iterable[HPIModule]: yield m -from .common import StatsFun -def get_stats(module: str) -> Optional[StatsFun]: - # todo detect via ast? - try: - mod = import_module(module) - except Exception: - return None - - return getattr(mod, 'stats', None) - - __NOT_HPI_MODULE__ = 'Import this to mark a python file as a helper, not an actual HPI module' from .discovery_pure import NOT_HPI_MODULE_VAR assert NOT_HPI_MODULE_VAR in globals() # check name consistency diff --git a/my/google/takeout/parser.py b/my/google/takeout/parser.py index 952c9b6..3ddd99d 100644 --- a/my/google/takeout/parser.py +++ b/my/google/takeout/parser.py @@ -18,9 +18,9 @@ from contextlib import ExitStack import os from typing import List, Sequence, cast from pathlib import Path -from my.core import make_config, dataclass +from my.core import make_config, dataclass, stat, Stats from my.core.cachew import mcachew -from my.core.common import Stats, LazyLogger, get_files, Paths +from my.core.common import LazyLogger, get_files, Paths from my.core.error import ErrorPolicy from my.core.structure import match_structure @@ -133,8 +133,6 @@ def events(disable_takeout_cache: bool = DISABLE_TAKEOUT_CACHE) -> CacheResults: def stats() -> Stats: - from my.core import stat - return { **stat(events), } diff --git a/my/location/google.py b/my/location/google.py index c1539e7..11cb576 100644 --- a/my/location/google.py +++ b/my/location/google.py @@ -19,6 +19,7 @@ import re # pip3 install geopy import geopy # type: ignore +from my.core import stat, Stats from my.core.common import LazyLogger from my.core.cachew import cache_dir, mcachew @@ -164,7 +165,6 @@ def locations(**kwargs) -> Iterable[Location]: return _iter_locations(path=last_takeout, **kwargs) -from ..core.common import stat, Stats def stats() -> Stats: return stat(locations) diff --git a/my/location/google_takeout.py b/my/location/google_takeout.py index 2fac270..eb757ce 100644 --- a/my/location/google_takeout.py +++ b/my/location/google_takeout.py @@ -9,8 +9,8 @@ from typing import Iterator from my.google.takeout.parser import events, _cachew_depends_on from google_takeout_parser.models import Location as GoogleLocation +from my.core import stat, Stats, LazyLogger from my.core.cachew import mcachew -from my.core.common import LazyLogger, stat, Stats from .common import Location logger = LazyLogger(__name__) diff --git a/my/location/google_takeout_semantic.py b/my/location/google_takeout_semantic.py index 014959c..4257f81 100644 --- a/my/location/google_takeout_semantic.py +++ b/my/location/google_takeout_semantic.py @@ -12,9 +12,8 @@ from typing import Iterator, List from my.google.takeout.parser import events, _cachew_depends_on as _parser_cachew_depends_on from google_takeout_parser.models import PlaceVisit as SemanticLocation -from my.core import dataclass, make_config +from my.core import dataclass, make_config, stat, LazyLogger, Stats from my.core.cachew import mcachew -from my.core.common import LazyLogger, Stats, stat from my.core.error import Res from .common import Location diff --git a/my/reddit/all.py b/my/reddit/all.py index a668081..daedba1 100644 --- a/my/reddit/all.py +++ b/my/reddit/all.py @@ -1,5 +1,5 @@ from typing import Iterator -from my.core.common import Stats +from my.core import stat, Stats from my.core.source import import_source from .common import Save, Upvote, Comment, Submission, _merge_comments @@ -58,7 +58,6 @@ def upvoted() -> Iterator[Upvote]: yield from upvoted() def stats() -> Stats: - from my.core import stat return { **stat(saved), **stat(comments), diff --git a/my/reddit/pushshift.py b/my/reddit/pushshift.py index 1c7ec8d..9580005 100644 --- a/my/reddit/pushshift.py +++ b/my/reddit/pushshift.py @@ -8,8 +8,9 @@ REQUIRES = [ "git+https://github.com/seanbreckenridge/pushshift_comment_export", ] -from my.core.common import Paths, Stats from dataclasses import dataclass + +from my.core import Paths, Stats, stat from my.core.cfg import make_config # note: keeping pushshift import before config import, so it's handled gracefully by import_source @@ -43,7 +44,6 @@ def comments() -> Iterator[PComment]: yield from read_file(f) def stats() -> Stats: - from my.core import stat return { **stat(comments) } diff --git a/my/rescuetime.py b/my/rescuetime.py index 774b587..c493e8e 100644 --- a/my/rescuetime.py +++ b/my/rescuetime.py @@ -9,7 +9,7 @@ from pathlib import Path from datetime import timedelta from typing import Sequence, Iterable -from my.core import get_files, make_logger +from my.core import get_files, make_logger, stat, Stats from my.core.cachew import mcachew from my.core.error import Res, split_errors @@ -47,7 +47,6 @@ def dataframe() -> DataFrameT: return as_dataframe(entries()) -from .core import stat, Stats def stats() -> Stats: return { **stat(groups), diff --git a/my/smscalls.py b/my/smscalls.py index 23fb5cc..f436709 100644 --- a/my/smscalls.py +++ b/my/smscalls.py @@ -7,7 +7,9 @@ Exported using https://play.google.com/store/apps/details?id=com.riteshsahu.SMSB REQUIRES = ['lxml'] -from .core import Paths, dataclass +from dataclasses import dataclass + +from my.core import get_files, stat, Paths, Stats from my.config import smscalls as user_config @dataclass @@ -15,7 +17,7 @@ class smscalls(user_config): # path[s] that SMSBackupRestore syncs XML files to export_path: Paths -from .core.cfg import make_config +from my.core.cfg import make_config config = make_config(smscalls) from datetime import datetime, timezone @@ -24,7 +26,6 @@ from typing import NamedTuple, Iterator, Set, Tuple, Optional, Any, Dict, List from lxml import etree -from my.core.common import get_files, Stats from my.core.error import Res @@ -316,8 +317,6 @@ def _parse_dt_ms(d: str) -> datetime: def stats() -> Stats: - from .core import stat - return { **stat(calls), **stat(messages), From 88f3c17c2726d9c2449043dc8599413892b0325d Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Thu, 15 Aug 2024 18:44:12 +0300 Subject: [PATCH 062/122] core.common: move mime-related stuff to my.core.mime no backward compat, unlikely it was used by anyone else --- my/core/common.py | 22 ---------------------- my/core/mime.py | 34 ++++++++++++++++++++++++++++++++++ my/photos/main.py | 3 ++- 3 files changed, 36 insertions(+), 23 deletions(-) create mode 100644 my/core/mime.py diff --git a/my/core/common.py b/my/core/common.py index 926861d..32e277b 100644 --- a/my/core/common.py +++ b/my/core/common.py @@ -2,7 +2,6 @@ from glob import glob as do_glob from pathlib import Path from datetime import datetime from dataclasses import is_dataclass, asdict as dataclasses_asdict -import functools import os from typing import ( Any, @@ -117,27 +116,6 @@ def get_files( return tuple(paths) -@functools.lru_cache(1) -def _magic(): - import magic # type: ignore - return magic.Magic(mime=True) - - -# TODO could reuse in pdf module? -import mimetypes # todo do I need init()? -# todo wtf? fastermime thinks it's mime is application/json even if the extension is xz?? -# whereas magic detects correctly: application/x-zstd and application/x-xz -def fastermime(path: PathIsh) -> str: - paths = str(path) - # mimetypes is faster - (mime, _) = mimetypes.guess_type(paths) - if mime is not None: - return mime - # magic is slower but returns more stuff - # TODO Result type?; it's kinda racey, but perhaps better to let the caller decide? - return _magic().from_file(paths) - - Json = Dict[str, Any] diff --git a/my/core/mime.py b/my/core/mime.py new file mode 100644 index 0000000..c8abc7e --- /dev/null +++ b/my/core/mime.py @@ -0,0 +1,34 @@ +""" +Utils for mime/filetype handling +""" + +from .common import assert_subpackage; assert_subpackage(__name__) + +import functools + +from .common import PathIsh + + +@functools.lru_cache(1) +def _magic(): + import magic # type: ignore + + # TODO also has uncompess=True? could be useful + return magic.Magic(mime=True) + + +# TODO could reuse in pdf module? +import mimetypes # todo do I need init()? + + +# todo wtf? fastermime thinks it's mime is application/json even if the extension is xz?? +# whereas magic detects correctly: application/x-zstd and application/x-xz +def fastermime(path: PathIsh) -> str: + paths = str(path) + # mimetypes is faster, so try it first + (mime, _) = mimetypes.guess_type(paths) + if mime is not None: + return mime + # magic is slower but handles more types + # TODO Result type?; it's kinda racey, but perhaps better to let the caller decide? + return _magic().from_file(paths) diff --git a/my/photos/main.py b/my/photos/main.py index 622d475..6262eac 100644 --- a/my/photos/main.py +++ b/my/photos/main.py @@ -15,9 +15,10 @@ from typing import Optional, NamedTuple, Iterator, Iterable, List from geopy.geocoders import Nominatim # type: ignore -from my.core.common import LazyLogger, fastermime +from my.core import LazyLogger from my.core.error import Res, sort_res_by from my.core.cachew import cache_dir, mcachew +from my.core.mime import fastermime from my.config import photos as config # type: ignore[attr-defined] From 7f8a5023107adb21947d0b35031c0367f859f471 Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Thu, 15 Aug 2024 18:49:19 +0300 Subject: [PATCH 063/122] core.common: move assert_subpackage to my.core.internal --- my/core/cachew.py | 2 +- my/core/common.py | 6 ------ my/core/freezer.py | 2 +- my/core/influxdb.py | 3 ++- my/core/internal.py | 9 +++++++++ my/core/kompress.py | 2 +- my/core/mime.py | 2 +- my/core/pytest.py | 2 +- my/core/sqlite.py | 2 +- 9 files changed, 17 insertions(+), 13 deletions(-) create mode 100644 my/core/internal.py diff --git a/my/core/cachew.py b/my/core/cachew.py index cc5a95b..bcd838d 100644 --- a/my/core/cachew.py +++ b/my/core/cachew.py @@ -1,4 +1,4 @@ -from .common import assert_subpackage; assert_subpackage(__name__) +from .internal import assert_subpackage; assert_subpackage(__name__) from contextlib import contextmanager import logging diff --git a/my/core/common.py b/my/core/common.py index 32e277b..f23ffbf 100644 --- a/my/core/common.py +++ b/my/core/common.py @@ -173,12 +173,6 @@ def asdict(thing: Any) -> Json: raise TypeError(f'Could not convert object {thing} to dict') -def assert_subpackage(name: str) -> None: - # can lead to some unexpected issues if you 'import cachew' which being in my/core directory.. so let's protect against it - # NOTE: if we use overlay, name can be smth like my.origg.my.core.cachew ... - assert name == '__main__' or 'my.core' in name, f'Expected module __name__ ({name}) to be __main__ or start with my.core' - - # TODO deprecate and suggest to use one from my.core directly? not sure from .utils.itertools import unique_everseen diff --git a/my/core/freezer.py b/my/core/freezer.py index 649a2b7..09ba032 100644 --- a/my/core/freezer.py +++ b/my/core/freezer.py @@ -1,4 +1,4 @@ -from .common import assert_subpackage; assert_subpackage(__name__) +from .internal import assert_subpackage; assert_subpackage(__name__) import dataclasses as dcl import inspect diff --git a/my/core/influxdb.py b/my/core/influxdb.py index 8407264..4f0e4c4 100644 --- a/my/core/influxdb.py +++ b/my/core/influxdb.py @@ -1,7 +1,8 @@ ''' TODO doesn't really belong to 'core' morally, but can think of moving out later ''' -from .common import assert_subpackage; assert_subpackage(__name__) + +from .internal import assert_subpackage; assert_subpackage(__name__) from typing import Iterable, Any, Optional, Dict diff --git a/my/core/internal.py b/my/core/internal.py new file mode 100644 index 0000000..8b9882b --- /dev/null +++ b/my/core/internal.py @@ -0,0 +1,9 @@ +""" +Utils specific to hpi core, shouldn't really be used by HPI modules +""" + + +def assert_subpackage(name: str) -> None: + # can lead to some unexpected issues if you 'import cachew' which being in my/core directory.. so let's protect against it + # NOTE: if we use overlay, name can be smth like my.origg.my.core.cachew ... + assert name == '__main__' or 'my.core' in name, f'Expected module __name__ ({name}) to be __main__ or start with my.core' diff --git a/my/core/kompress.py b/my/core/kompress.py index 25dba8c..6ab3228 100644 --- a/my/core/kompress.py +++ b/my/core/kompress.py @@ -1,4 +1,4 @@ -from .common import assert_subpackage; assert_subpackage(__name__) +from .internal import assert_subpackage; assert_subpackage(__name__) from . import warnings # do this later -- for now need to transition modules to avoid using kompress directly (e.g. ZipPath) diff --git a/my/core/mime.py b/my/core/mime.py index c8abc7e..cf5bdf5 100644 --- a/my/core/mime.py +++ b/my/core/mime.py @@ -2,7 +2,7 @@ Utils for mime/filetype handling """ -from .common import assert_subpackage; assert_subpackage(__name__) +from .internal import assert_subpackage; assert_subpackage(__name__) import functools diff --git a/my/core/pytest.py b/my/core/pytest.py index a2596fb..c73c71a 100644 --- a/my/core/pytest.py +++ b/my/core/pytest.py @@ -2,7 +2,7 @@ Helpers to prevent depending on pytest in runtime """ -from .common import assert_subpackage; assert_subpackage(__name__) +from .internal import assert_subpackage; assert_subpackage(__name__) import sys import typing diff --git a/my/core/sqlite.py b/my/core/sqlite.py index 2580e15..4a471a9 100644 --- a/my/core/sqlite.py +++ b/my/core/sqlite.py @@ -1,4 +1,4 @@ -from .common import assert_subpackage; assert_subpackage(__name__) +from .internal import assert_subpackage; assert_subpackage(__name__) from contextlib import contextmanager From 2b0f92c88334e343520fb3a2ee2bceb68725b04c Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Fri, 16 Aug 2024 00:14:44 +0300 Subject: [PATCH 064/122] my.core: deprecate Path/dataclass imports from my.core during type checking runtime still works for backwards compatibility --- my/arbtt.py | 6 ++++-- my/browser/active_browser.py | 3 ++- my/core/__init__.py | 14 +++++++++----- my/core/core_config.py | 6 ++++-- my/google/takeout/parser.py | 3 ++- my/lastfm.py | 3 ++- my/location/fallback/via_ip.py | 3 ++- my/location/google_takeout_semantic.py | 3 ++- my/location/gpslogger.py | 5 ++++- my/stackexchange/gdpr.py | 6 +++--- 10 files changed, 34 insertions(+), 18 deletions(-) diff --git a/my/arbtt.py b/my/arbtt.py index 941a05f..6de8cb2 100644 --- a/my/arbtt.py +++ b/my/arbtt.py @@ -6,6 +6,7 @@ REQUIRES = ['ijson', 'cffi'] # NOTE likely also needs libyajl2 from apt or elsewhere? +from dataclasses import dataclass from pathlib import Path from typing import Sequence, Iterable, List, Optional @@ -22,8 +23,9 @@ def inputs() -> Sequence[Path]: return get_files(user_config.logfiles) -from .core import dataclass, Json, PathIsh, datetime_aware -from .core.compat import fromisoformat + +from my.core import Json, PathIsh, datetime_aware +from my.core.compat import fromisoformat @dataclass diff --git a/my/browser/active_browser.py b/my/browser/active_browser.py index 601182a..6f335bd 100644 --- a/my/browser/active_browser.py +++ b/my/browser/active_browser.py @@ -4,9 +4,10 @@ Parses active browser history by backing it up with [[http://github.com/seanbrec REQUIRES = ["browserexport", "sqlite_backup"] +from dataclasses import dataclass from my.config import browser as user_config -from my.core import Paths, dataclass +from my.core import Paths @dataclass diff --git a/my/core/__init__.py b/my/core/__init__.py index 3881485..fa50413 100644 --- a/my/core/__init__.py +++ b/my/core/__init__.py @@ -1,4 +1,6 @@ # this file only keeps the most common & critical types/utility functions +from typing import TYPE_CHECKING + from .common import get_files, PathIsh, Paths from .common import Json from .stats import stat, Stats @@ -12,10 +14,12 @@ from .logging import make_logger, LazyLogger from .util import __NOT_HPI_MODULE__ -# just for brevity in modules -# todo not sure about these.. maybe best to rely on regular imports.. perhaps compare? -from dataclasses import dataclass -from pathlib import Path +if not TYPE_CHECKING: + # we used to keep these here for brevity, but feels like it only adds confusion, + # e.g. suggest that we perhaps somehow modify builtin behaviour or whatever + # so best to prefer explicit behaviour + from dataclasses import dataclass + from pathlib import Path __all__ = [ @@ -34,7 +38,7 @@ __all__ = [ 'Res', 'unwrap', - 'dataclass', 'Path', # TODO deprecate these from use in my.core + 'dataclass', 'Path', ] diff --git a/my/core/core_config.py b/my/core/core_config.py index e70dc05..889dbf9 100644 --- a/my/core/core_config.py +++ b/my/core/core_config.py @@ -1,10 +1,13 @@ ''' Bindings for the 'core' HPI configuration ''' + +from dataclasses import dataclass +from pathlib import Path import re from typing import Sequence, Optional -from . import warnings, PathIsh, Path +from . import warnings, PathIsh try: from my.config import core as user_config # type: ignore[attr-defined] @@ -21,7 +24,6 @@ except Exception as e: _HPI_CACHE_DIR_DEFAULT = '' -from dataclasses import dataclass @dataclass class Config(user_config): ''' diff --git a/my/google/takeout/parser.py b/my/google/takeout/parser.py index 3ddd99d..173f99a 100644 --- a/my/google/takeout/parser.py +++ b/my/google/takeout/parser.py @@ -15,10 +15,11 @@ the cachew cache REQUIRES = ["git+https://github.com/seanbreckenridge/google_takeout_parser"] from contextlib import ExitStack +from dataclasses import dataclass import os from typing import List, Sequence, cast from pathlib import Path -from my.core import make_config, dataclass, stat, Stats +from my.core import make_config, stat, Stats from my.core.cachew import mcachew from my.core.common import LazyLogger, get_files, Paths from my.core.error import ErrorPolicy diff --git a/my/lastfm.py b/my/lastfm.py index 64ef1b3..37cec50 100644 --- a/my/lastfm.py +++ b/my/lastfm.py @@ -2,7 +2,8 @@ Last.fm scrobbles ''' -from my.core import Paths, dataclass, make_logger +from dataclasses import dataclass +from my.core import Paths, make_logger from my.config import lastfm as user_config diff --git a/my/location/fallback/via_ip.py b/my/location/fallback/via_ip.py index f637552..87802e7 100644 --- a/my/location/fallback/via_ip.py +++ b/my/location/fallback/via_ip.py @@ -4,9 +4,10 @@ Converts IP addresses provided by my.location.ip to estimated locations REQUIRES = ["git+https://github.com/seanbreckenridge/ipgeocache"] +from dataclasses import dataclass from datetime import timedelta -from my.core import dataclass, Stats, make_config +from my.core import Stats, make_config from my.config import location from my.core.warnings import medium diff --git a/my/location/google_takeout_semantic.py b/my/location/google_takeout_semantic.py index 4257f81..5f2c055 100644 --- a/my/location/google_takeout_semantic.py +++ b/my/location/google_takeout_semantic.py @@ -7,12 +7,13 @@ Extracts semantic location history using google_takeout_parser REQUIRES = ["git+https://github.com/seanbreckenridge/google_takeout_parser"] +from dataclasses import dataclass from typing import Iterator, List from my.google.takeout.parser import events, _cachew_depends_on as _parser_cachew_depends_on from google_takeout_parser.models import PlaceVisit as SemanticLocation -from my.core import dataclass, make_config, stat, LazyLogger, Stats +from my.core import make_config, stat, LazyLogger, Stats from my.core.cachew import mcachew from my.core.error import Res from .common import Location diff --git a/my/location/gpslogger.py b/my/location/gpslogger.py index 8fb59d0..6d158a0 100644 --- a/my/location/gpslogger.py +++ b/my/location/gpslogger.py @@ -4,8 +4,11 @@ Parse [[https://github.com/mendhak/gpslogger][gpslogger]] .gpx (xml) files REQUIRES = ["gpxpy"] + +from dataclasses import dataclass + from my.config import location -from my.core import Paths, dataclass +from my.core import Paths @dataclass diff --git a/my/stackexchange/gdpr.py b/my/stackexchange/gdpr.py index 2f3b98d..5292bef 100644 --- a/my/stackexchange/gdpr.py +++ b/my/stackexchange/gdpr.py @@ -5,8 +5,9 @@ Stackexchange data (uses [[https://stackoverflow.com/legal/gdpr/request][officia # TODO need to merge gdpr and stexport ### config +from dataclasses import dataclass from my.config import stackexchange as user_config -from ..core import dataclass, PathIsh, make_config, get_files +from my.core import PathIsh, make_config, get_files, Json @dataclass class stackexchange(user_config): gdpr_path: PathIsh # path to GDPR zip file @@ -16,8 +17,7 @@ config = make_config(stackexchange) # TODO just merge all of them and then filter?.. not sure -from ..core.common import Json -from ..core.compat import fromisoformat +from my.core.compat import fromisoformat from typing import NamedTuple, Iterable from datetime import datetime class Vote(NamedTuple): From 614c929f95e79ad000c45da72813564cc2b6689e Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Fri, 16 Aug 2024 11:46:29 +0300 Subject: [PATCH 065/122] core.common: move Json, datetime_aware, datetime_naive, is_namedtuple, asdict to my.core.types --- my/core/__init__.py | 7 ++++-- my/core/common.py | 53 ++++++++++++++------------------------------ my/core/error.py | 3 ++- my/core/influxdb.py | 3 ++- my/core/pandas.py | 3 ++- my/core/query.py | 4 ++-- my/core/serialize.py | 2 +- my/core/stats.py | 4 ++-- my/core/time.py | 2 +- my/core/types.py | 36 ++++++++++++++++++++++++++++++ my/goodreads.py | 3 +-- my/lastfm.py | 3 +-- my/runnerup.py | 5 ++--- my/time/tz/common.py | 2 +- my/time/tz/main.py | 4 +++- 15 files changed, 78 insertions(+), 56 deletions(-) create mode 100644 my/core/types.py diff --git a/my/core/__init__.py b/my/core/__init__.py index fa50413..c65991a 100644 --- a/my/core/__init__.py +++ b/my/core/__init__.py @@ -2,9 +2,12 @@ from typing import TYPE_CHECKING from .common import get_files, PathIsh, Paths -from .common import Json from .stats import stat, Stats -from .common import datetime_naive, datetime_aware +from .types import ( + Json, + datetime_aware, + datetime_naive, +) from .compat import assert_never from .utils.itertools import warn_if_empty diff --git a/my/core/common.py b/my/core/common.py index f23ffbf..efd6f48 100644 --- a/my/core/common.py +++ b/my/core/common.py @@ -1,12 +1,8 @@ from glob import glob as do_glob from pathlib import Path -from datetime import datetime -from dataclasses import is_dataclass, asdict as dataclasses_asdict import os from typing import ( - Any, Callable, - Dict, Iterable, List, Sequence, @@ -116,9 +112,6 @@ def get_files( return tuple(paths) -Json = Dict[str, Any] - - from typing import TypeVar, Callable, Generic _R = TypeVar('_R') @@ -141,11 +134,6 @@ class classproperty(Generic[_R]): # def __get__(self) -> _R: # return self.f() -# for now just serves documentation purposes... but one day might make it statically verifiable where possible? -# TODO e.g. maybe use opaque mypy alias? -datetime_naive = datetime -datetime_aware = datetime - import re # https://stackoverflow.com/a/295466/706389 @@ -154,25 +142,6 @@ def get_valid_filename(s: str) -> str: return re.sub(r'(?u)[^-\w.]', '', s) -def is_namedtuple(thing: Any) -> bool: - # basic check to see if this is namedtuple-like - _asdict = getattr(thing, '_asdict', None) - return (_asdict is not None) and callable(_asdict) - - -def asdict(thing: Any) -> Json: - # todo primitive? - # todo exception? - if isinstance(thing, dict): - return thing - if is_dataclass(thing): - assert not isinstance(thing, type) # to help mypy - return dataclasses_asdict(thing) - if is_namedtuple(thing): - return thing._asdict() - raise TypeError(f'Could not convert object {thing} to dict') - - # TODO deprecate and suggest to use one from my.core directly? not sure from .utils.itertools import unique_everseen @@ -182,8 +151,6 @@ from .utils.itertools import unique_everseen ## in principle, warnings.deprecated decorator should cooperate with mypy, but doesn't look like it works atm? ## perhaps it doesn't work when it's used from typing_extensions -from .compat import Never - if not TYPE_CHECKING: @deprecated('use my.core.compat.assert_never instead') @@ -243,12 +210,26 @@ if not TYPE_CHECKING: # todo wrap these in deprecated decorator as well? from .cachew import mcachew # noqa: F401 + # TODO hmm how to deprecate these in runtime? + # tricky cause they are actually classes/types + from typing import Literal # noqa: F401 - # TODO hmm how to deprecate it in runtime? tricky cause it's actually a class? + from .stats import Stats + from .types import ( + Json, + datetime_naive, + datetime_aware, + ) + tzdatetime = datetime_aware else: - tzdatetime = Never # makes it invalid as a type while working in runtime + from .compat import Never -Stats = Never + # make these invalid during type check while working in runtime + Stats = Never + tzdatetime = Never + Json = Never + datetime_naive = Never + datetime_aware = Never ### diff --git a/my/core/error.py b/my/core/error.py index fa59137..2432a5d 100644 --- a/my/core/error.py +++ b/my/core/error.py @@ -6,6 +6,8 @@ See https://beepb00p.xyz/mypy-error-handling.html#kiss for more detail from itertools import tee from typing import Union, TypeVar, Iterable, List, Tuple, Type, Optional, Callable, Any, cast, Iterator, Literal +from .types import Json + T = TypeVar('T') E = TypeVar('E', bound=Exception) # TODO make covariant? @@ -176,7 +178,6 @@ def extract_error_datetime(e: Exception) -> Optional[datetime]: import traceback -from .common import Json def error_to_json(e: Exception) -> Json: estr = ''.join(traceback.format_exception(Exception, e, e.__traceback__)) return {'error': estr} diff --git a/my/core/influxdb.py b/my/core/influxdb.py index 4f0e4c4..2ac2c79 100644 --- a/my/core/influxdb.py +++ b/my/core/influxdb.py @@ -6,7 +6,8 @@ from .internal import assert_subpackage; assert_subpackage(__name__) from typing import Iterable, Any, Optional, Dict -from .common import LazyLogger, asdict, Json +from .common import LazyLogger +from .types import asdict, Json logger = LazyLogger(__name__) diff --git a/my/core/pandas.py b/my/core/pandas.py index 621682f..2b34b23 100644 --- a/my/core/pandas.py +++ b/my/core/pandas.py @@ -13,7 +13,8 @@ from typing import TYPE_CHECKING, Any, Iterable, Type, Dict, Literal, Callable, from decorator import decorator from . import warnings, Res -from .common import LazyLogger, Json, asdict +from .common import LazyLogger +from .types import Json, asdict from .error import error_to_json, extract_error_datetime diff --git a/my/core/query.py b/my/core/query.py index 071f7e0..4d7363e 100644 --- a/my/core/query.py +++ b/my/core/query.py @@ -14,8 +14,8 @@ from typing import TypeVar, Tuple, Optional, Union, Callable, Iterable, Iterator import more_itertools -import my.core.error as err -from .common import is_namedtuple +from . import error as err +from .types import is_namedtuple from .error import Res, unwrap from .warnings import low diff --git a/my/core/serialize.py b/my/core/serialize.py index b5b1b3a..e38bca5 100644 --- a/my/core/serialize.py +++ b/my/core/serialize.py @@ -5,8 +5,8 @@ from decimal import Decimal from typing import Any, Optional, Callable, NamedTuple from functools import lru_cache -from .common import is_namedtuple from .error import error_to_json +from .types import is_namedtuple from .pytest import parametrize # note: it would be nice to combine the 'asdict' and _default_encode to some function diff --git a/my/core/stats.py b/my/core/stats.py index d5a43c3..d724068 100644 --- a/my/core/stats.py +++ b/my/core/stats.py @@ -24,6 +24,8 @@ from typing import ( cast, ) +from .types import asdict + Stats = Dict[str, Any] @@ -432,8 +434,6 @@ def test_stat_iterable() -> None: # experimental, not sure about it.. def _guess_datetime(x: Any) -> Optional[datetime]: - from .common import asdict # avoid circular imports - # todo hmm implement without exception.. try: d = asdict(x) diff --git a/my/core/time.py b/my/core/time.py index 7698332..430b082 100644 --- a/my/core/time.py +++ b/my/core/time.py @@ -3,7 +3,7 @@ from typing import Sequence, Dict import pytz -from .common import datetime_aware, datetime_naive +from .types import datetime_aware, datetime_naive def user_forced() -> Sequence[str]: diff --git a/my/core/types.py b/my/core/types.py new file mode 100644 index 0000000..c1b0add --- /dev/null +++ b/my/core/types.py @@ -0,0 +1,36 @@ +from .internal import assert_subpackage; assert_subpackage(__name__) + +from dataclasses import is_dataclass, asdict as dataclasses_asdict +from datetime import datetime +from typing import ( + Any, + Dict, +) + + +Json = Dict[str, Any] + + +# for now just serves documentation purposes... but one day might make it statically verifiable where possible? +# TODO e.g. maybe use opaque mypy alias? +datetime_naive = datetime +datetime_aware = datetime + + +def is_namedtuple(thing: Any) -> bool: + # basic check to see if this is namedtuple-like + _asdict = getattr(thing, '_asdict', None) + return (_asdict is not None) and callable(_asdict) + + +def asdict(thing: Any) -> Json: + # todo primitive? + # todo exception? + if isinstance(thing, dict): + return thing + if is_dataclass(thing): + assert not isinstance(thing, type) # to help mypy + return dataclasses_asdict(thing) + if is_namedtuple(thing): + return thing._asdict() + raise TypeError(f'Could not convert object {thing} to dict') diff --git a/my/goodreads.py b/my/goodreads.py index acf2bb9..864bd64 100644 --- a/my/goodreads.py +++ b/my/goodreads.py @@ -7,7 +7,7 @@ REQUIRES = [ from dataclasses import dataclass -from my.core import Paths +from my.core import datetime_aware, Paths from my.config import goodreads as user_config @dataclass @@ -61,7 +61,6 @@ def books() -> Iterator[dal.Book]: ####### # todo ok, not sure these really belong here... -from my.core.common import datetime_aware @dataclass class Event: dt: datetime_aware diff --git a/my/lastfm.py b/my/lastfm.py index 37cec50..6618738 100644 --- a/my/lastfm.py +++ b/my/lastfm.py @@ -3,7 +3,7 @@ Last.fm scrobbles ''' from dataclasses import dataclass -from my.core import Paths, make_logger +from my.core import Paths, Json, make_logger, get_files from my.config import lastfm as user_config @@ -28,7 +28,6 @@ from pathlib import Path from typing import NamedTuple, Sequence, Iterable from my.core.cachew import mcachew -from my.core.common import Json, get_files def inputs() -> Sequence[Path]: diff --git a/my/runnerup.py b/my/runnerup.py index ca09466..a21075a 100644 --- a/my/runnerup.py +++ b/my/runnerup.py @@ -10,9 +10,8 @@ from datetime import timedelta from pathlib import Path from typing import Iterable -from .core import Res, get_files -from .core.common import Json -from .core.compat import fromisoformat +from my.core import Res, get_files, Json +from my.core.compat import fromisoformat import tcxparser # type: ignore[import-untyped] diff --git a/my/time/tz/common.py b/my/time/tz/common.py index 107410a..89150c7 100644 --- a/my/time/tz/common.py +++ b/my/time/tz/common.py @@ -1,7 +1,7 @@ from datetime import datetime from typing import Callable, Literal, cast -from my.core.common import datetime_aware +from my.core import datetime_aware ''' diff --git a/my/time/tz/main.py b/my/time/tz/main.py index 6180160..fafc5fe 100644 --- a/my/time/tz/main.py +++ b/my/time/tz/main.py @@ -1,8 +1,10 @@ ''' Timezone data provider, used to localize timezone-unaware timestamps for other modules ''' + from datetime import datetime -from my.core.common import datetime_aware + +from my.core import datetime_aware # todo hmm, kwargs isn't mypy friendly.. but specifying types would require duplicating default args. uhoh def localize(dt: datetime, **kwargs) -> datetime_aware: From 7023088d13f05a2b2987c3b7c43744b5869b4a25 Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Fri, 16 Aug 2024 12:12:40 +0300 Subject: [PATCH 066/122] core.common: deprecate outdated LazyLogger alias --- my/core/__init__.py | 7 ++++++- my/core/__main__.py | 4 ++-- my/core/common.py | 15 +++++++++++---- my/core/influxdb.py | 4 ++-- my/core/logging.py | 16 +++++++++++++--- my/core/pandas.py | 4 ++-- my/core/structure.py | 4 ++-- my/foursquare.py | 4 ++-- my/google/takeout/parser.py | 5 ++--- my/jawbone/__init__.py | 4 ++-- my/location/fallback/via_ip.py | 4 ++-- my/location/google.py | 5 ++--- my/rtm.py | 4 ++-- 13 files changed, 50 insertions(+), 30 deletions(-) diff --git a/my/core/__init__.py b/my/core/__init__.py index c65991a..247aab0 100644 --- a/my/core/__init__.py +++ b/my/core/__init__.py @@ -13,10 +13,15 @@ from .utils.itertools import warn_if_empty from .cfg import make_config from .error import Res, unwrap -from .logging import make_logger, LazyLogger +from .logging import ( + make_logger, +) from .util import __NOT_HPI_MODULE__ +LazyLogger = make_logger # TODO deprecate this in favor of make_logger + + if not TYPE_CHECKING: # we used to keep these here for brevity, but feels like it only adds confusion, # e.g. suggest that we perhaps somehow modify builtin behaviour or whatever diff --git a/my/core/__main__.py b/my/core/__main__.py index c9a4945..e0d5c12 100644 --- a/my/core/__main__.py +++ b/my/core/__main__.py @@ -485,8 +485,8 @@ def _locate_functions_or_prompt(qualified_names: List[str], prompt: bool = True) def _warn_exceptions(exc: Exception) -> None: - from my.core.common import LazyLogger - logger = LazyLogger('CLI', level='warning') + from my.core import make_logger + logger = make_logger('CLI', level='warning') logger.exception(f'hpi query: {exc}') diff --git a/my/core/common.py b/my/core/common.py index efd6f48..f20e1d4 100644 --- a/my/core/common.py +++ b/my/core/common.py @@ -15,14 +15,11 @@ import warnings from . import warnings as core_warnings from . import compat -from .compat import deprecated # some helper functions +# TODO start deprecating this? soon we'd be able to use Path | str syntax which is shorter and more explicit PathIsh = Union[Path, str] -from .logging import setup_logger, LazyLogger - - Paths = Union[Sequence[PathIsh], PathIsh] @@ -152,6 +149,7 @@ from .utils.itertools import unique_everseen ## perhaps it doesn't work when it's used from typing_extensions if not TYPE_CHECKING: + from .compat import deprecated @deprecated('use my.core.compat.assert_never instead') def assert_never(*args, **kwargs): @@ -207,9 +205,18 @@ if not TYPE_CHECKING: return stats.stat(*args, **kwargs) + @deprecated('use my.core.make_logger instead') + def LazyLogger(*args, **kwargs): + from . import logging + + return logging.LazyLogger(*args, **kwargs) + # todo wrap these in deprecated decorator as well? from .cachew import mcachew # noqa: F401 + # this is kinda internal, should just use my.core.logging.setup_logger if necessary + from .logging import setup_logger + # TODO hmm how to deprecate these in runtime? # tricky cause they are actually classes/types diff --git a/my/core/influxdb.py b/my/core/influxdb.py index 2ac2c79..c4b6409 100644 --- a/my/core/influxdb.py +++ b/my/core/influxdb.py @@ -6,11 +6,11 @@ from .internal import assert_subpackage; assert_subpackage(__name__) from typing import Iterable, Any, Optional, Dict -from .common import LazyLogger +from .logging import make_logger from .types import asdict, Json -logger = LazyLogger(__name__) +logger = make_logger(__name__) class config: diff --git a/my/core/logging.py b/my/core/logging.py index 5d2af99..882ab12 100644 --- a/my/core/logging.py +++ b/my/core/logging.py @@ -4,7 +4,7 @@ from functools import lru_cache import logging import os import sys -from typing import Union +from typing import Union, TYPE_CHECKING import warnings @@ -249,6 +249,16 @@ if __name__ == '__main__': ## legacy/deprecated methods for backwards compatilibity -LazyLogger = make_logger -logger = make_logger +if not TYPE_CHECKING: + from .compat import deprecated + + @deprecated('use make_logger instead') + def LazyLogger(*args, **kwargs): + return make_logger(*args, **kwargs) + + @deprecated('use make_logger instead') + def logger(*args, **kwargs): + return make_logger(*args, **kwargs) + + ## diff --git a/my/core/pandas.py b/my/core/pandas.py index 2b34b23..5688aa3 100644 --- a/my/core/pandas.py +++ b/my/core/pandas.py @@ -13,12 +13,12 @@ from typing import TYPE_CHECKING, Any, Iterable, Type, Dict, Literal, Callable, from decorator import decorator from . import warnings, Res -from .common import LazyLogger +from .logging import make_logger from .types import Json, asdict from .error import error_to_json, extract_error_datetime -logger = LazyLogger(__name__) +logger = make_logger(__name__) if TYPE_CHECKING: diff --git a/my/core/structure.py b/my/core/structure.py index 7a0c2a2..458440e 100644 --- a/my/core/structure.py +++ b/my/core/structure.py @@ -8,10 +8,10 @@ from typing import Sequence, Generator, List, Union, Tuple from contextlib import contextmanager from pathlib import Path -from .common import LazyLogger +from .logging import make_logger -logger = LazyLogger(__name__, level="info") +logger = make_logger(__name__, level="info") def _structure_exists(base_dir: Path, paths: Sequence[str], partial: bool = False) -> bool: diff --git a/my/foursquare.py b/my/foursquare.py index b50ab0e..63e1837 100644 --- a/my/foursquare.py +++ b/my/foursquare.py @@ -9,11 +9,11 @@ import json # TODO pytz for timezone??? -from .core.common import get_files, LazyLogger +from my.core import get_files, make_logger from my.config import foursquare as config -logger = LazyLogger(__name__) +logger = make_logger(__name__) def inputs(): diff --git a/my/google/takeout/parser.py b/my/google/takeout/parser.py index 173f99a..c4e5682 100644 --- a/my/google/takeout/parser.py +++ b/my/google/takeout/parser.py @@ -19,9 +19,8 @@ from dataclasses import dataclass import os from typing import List, Sequence, cast from pathlib import Path -from my.core import make_config, stat, Stats +from my.core import make_config, stat, Stats, get_files, Paths, make_logger from my.core.cachew import mcachew -from my.core.common import LazyLogger, get_files, Paths from my.core.error import ErrorPolicy from my.core.structure import match_structure @@ -52,7 +51,7 @@ class google(user_config): config = make_config(google) -logger = LazyLogger(__name__, level="warning") +logger = make_logger(__name__, level="warning") # patch the takeout parser logger to match the computed loglevel from google_takeout_parser.log import setup as setup_takeout_logger diff --git a/my/jawbone/__init__.py b/my/jawbone/__init__.py index 0659bc6..5d43296 100644 --- a/my/jawbone/__init__.py +++ b/my/jawbone/__init__.py @@ -8,9 +8,9 @@ from pathlib import Path import pytz -from ..core.common import LazyLogger +from my.core import make_logger -logger = LazyLogger(__name__) +logger = make_logger(__name__) from my.config import jawbone as config # type: ignore[attr-defined] diff --git a/my/location/fallback/via_ip.py b/my/location/fallback/via_ip.py index 87802e7..db03c7c 100644 --- a/my/location/fallback/via_ip.py +++ b/my/location/fallback/via_ip.py @@ -27,13 +27,13 @@ config = make_config(ip_config) from functools import lru_cache from typing import Iterator, List -from my.core.common import LazyLogger +from my.core import make_logger from my.core.compat import bisect_left from my.ip.all import ips from my.location.common import Location from my.location.fallback.common import FallbackLocation, DateExact, _datetime_timestamp -logger = LazyLogger(__name__, level="warning") +logger = make_logger(__name__, level="warning") def fallback_locations() -> Iterator[FallbackLocation]: diff --git a/my/location/google.py b/my/location/google.py index 11cb576..a7a92d3 100644 --- a/my/location/google.py +++ b/my/location/google.py @@ -19,8 +19,7 @@ import re # pip3 install geopy import geopy # type: ignore -from my.core import stat, Stats -from my.core.common import LazyLogger +from my.core import stat, Stats, make_logger from my.core.cachew import cache_dir, mcachew from my.core.warnings import high @@ -33,7 +32,7 @@ high("Please set up my.google.takeout.parser module for better takeout support") USE_GREP = False -logger = LazyLogger(__name__) +logger = make_logger(__name__) class Location(NamedTuple): diff --git a/my/rtm.py b/my/rtm.py index 56f4d07..22752fe 100644 --- a/my/rtm.py +++ b/my/rtm.py @@ -11,7 +11,7 @@ from functools import cached_property import re from typing import Dict, List, Iterator -from my.core.common import LazyLogger, get_files +from my.core import make_logger, get_files from my.core.utils.itertools import make_dict from my.config import rtm as config @@ -22,7 +22,7 @@ import icalendar # type: ignore from icalendar.cal import Todo # type: ignore -logger = LazyLogger(__name__) +logger = make_logger(__name__) # TODO extract in a module to parse RTM's ical? From 7bfce72b7c72f470e0dcb2847c0abaf437a90a0a Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Fri, 16 Aug 2024 13:25:19 +0300 Subject: [PATCH 067/122] core: cleanup/sort imports according to `ruff check --select I` --- my/core/__init__.py | 20 +++++++++---------- my/core/__main__.py | 21 ++++++++++---------- my/core/_cpu_pool.py | 5 ++--- my/core/_deprecated/kompress.py | 15 +++++++------- my/core/cachew.py | 17 +++++++++++++--- my/core/cfg.py | 15 +++++++------- my/core/common.py | 17 ++++++++-------- my/core/compat.py | 7 +++---- my/core/core_config.py | 13 +++++++----- my/core/denylist.py | 12 +++++------ my/core/discovery_pure.py | 8 ++++---- my/core/error.py | 35 +++++++++++++++++++++++++-------- my/core/experimental.py | 2 +- my/core/freezer.py | 4 +++- my/core/hpi_compat.py | 2 +- my/core/influxdb.py | 12 +++++------ my/core/init.py | 2 +- my/core/konsume.py | 5 +++++ my/core/logging.py | 8 +++++--- my/core/orgmode.py | 8 +++++++- my/core/pandas.py | 7 +++---- my/core/preinit.py | 4 +++- my/core/query.py | 20 +++++++++++++++---- my/core/query_range.py | 14 ++++++------- my/core/serialize.py | 9 +++++---- my/core/source.py | 4 ++-- my/core/sqlite.py | 8 +++----- my/core/stats.py | 12 +++++------ my/core/structure.py | 6 ++---- my/core/tests/auto_stats.py | 2 +- my/core/tests/common.py | 3 +-- my/core/tests/denylist.py | 6 +++--- my/core/tests/sqlite.py | 4 ++-- my/core/tests/structure.py | 3 +-- my/core/tests/test_cachew.py | 3 +-- my/core/tests/test_cli.py | 2 +- my/core/tests/test_get_files.py | 8 ++++---- my/core/time.py | 2 +- my/core/types.py | 4 ++-- my/core/util.py | 15 +++++++++----- my/core/utils/concurrent.py | 6 +++--- my/core/utils/imports.py | 4 ++-- my/core/utils/itertools.py | 15 ++++++++------ my/core/warnings.py | 12 ++++++++--- my/location/common.py | 4 ++-- 45 files changed, 235 insertions(+), 170 deletions(-) diff --git a/my/core/__init__.py b/my/core/__init__.py index 247aab0..19be7fe 100644 --- a/my/core/__init__.py +++ b/my/core/__init__.py @@ -1,23 +1,21 @@ # this file only keeps the most common & critical types/utility functions from typing import TYPE_CHECKING -from .common import get_files, PathIsh, Paths -from .stats import stat, Stats +from .cfg import make_config +from .common import PathIsh, Paths, get_files +from .compat import assert_never +from .error import Res, unwrap +from .logging import ( + make_logger, +) +from .stats import Stats, stat from .types import ( Json, datetime_aware, datetime_naive, ) -from .compat import assert_never -from .utils.itertools import warn_if_empty - -from .cfg import make_config -from .error import Res, unwrap -from .logging import ( - make_logger, -) from .util import __NOT_HPI_MODULE__ - +from .utils.itertools import warn_if_empty LazyLogger = make_logger # TODO deprecate this in favor of make_logger diff --git a/my/core/__main__.py b/my/core/__main__.py index e0d5c12..276de26 100644 --- a/my/core/__main__.py +++ b/my/core/__main__.py @@ -1,17 +1,17 @@ -from contextlib import ExitStack import functools import importlib import inspect -from itertools import chain import os import shlex import shutil import sys import tempfile import traceback -from typing import Optional, Sequence, Iterable, List, Type, Any, Callable +from contextlib import ExitStack +from itertools import chain from pathlib import Path -from subprocess import check_call, run, PIPE, CompletedProcess, Popen +from subprocess import PIPE, CompletedProcess, Popen, check_call, run +from typing import Any, Callable, Iterable, List, Optional, Sequence, Type import click @@ -221,6 +221,8 @@ See https://github.com/karlicoss/HPI/blob/master/doc/SETUP.org#setting-up-module from .util import HPIModule, modules + + def _modules(*, all: bool=False) -> Iterable[HPIModule]: skipped = [] for m in modules(): @@ -243,9 +245,9 @@ def modules_check(*, verbose: bool, list_all: bool, quick: bool, for_modules: Li import contextlib - from .util import HPIModule - from .stats import get_stats, quick_stats from .error import warn_my_config_import_error + from .stats import get_stats, quick_stats + from .util import HPIModule mods: Iterable[HPIModule] if len(for_modules) == 0: @@ -437,7 +439,7 @@ def _ui_getchar_pick(choices: Sequence[str], prompt: str = 'Select from: ') -> i def _locate_functions_or_prompt(qualified_names: List[str], prompt: bool = True) -> Iterable[Callable[..., Any]]: - from .query import locate_qualified_function, QueryException + from .query import QueryException, locate_qualified_function from .stats import is_data_provider # if not connected to a terminal, can't prompt @@ -511,8 +513,7 @@ def query_hpi_functions( raise_exceptions: bool, drop_exceptions: bool, ) -> None: - from .query_range import select_range, RangeTuple - import my.core.error as err + from .query_range import RangeTuple, select_range # chain list of functions from user, in the order they wrote them on the CLI input_src = chain(*(f() for f in _locate_functions_or_prompt(qualified_names))) @@ -825,7 +826,7 @@ def query_cmd( hpi query --order-type datetime --after '2016-01-01' --before '2019-01-01' my.reddit.all.comments ''' - from datetime import datetime, date + from datetime import date, datetime chosen_order_type: Optional[Type] if order_type == "datetime": diff --git a/my/core/_cpu_pool.py b/my/core/_cpu_pool.py index 5ac66de..2369075 100644 --- a/my/core/_cpu_pool.py +++ b/my/core/_cpu_pool.py @@ -10,10 +10,9 @@ how many cores we want to dedicate to the DAL. Enabled by the env variable, specifying how many cores to dedicate e.g. "HPI_CPU_POOL=4 hpi query ..." """ -from concurrent.futures import ProcessPoolExecutor import os -from typing import cast, Optional - +from concurrent.futures import ProcessPoolExecutor +from typing import Optional, cast _NOT_SET = cast(ProcessPoolExecutor, object()) _INSTANCE: Optional[ProcessPoolExecutor] = _NOT_SET diff --git a/my/core/_deprecated/kompress.py b/my/core/_deprecated/kompress.py index 25b8a20..7eb9b37 100644 --- a/my/core/_deprecated/kompress.py +++ b/my/core/_deprecated/kompress.py @@ -4,13 +4,13 @@ Various helpers for compression # fmt: off from __future__ import annotations -from datetime import datetime -from functools import total_ordering import io import pathlib -from pathlib import Path import sys -from typing import Union, IO, Sequence, Any, Iterator +from datetime import datetime +from functools import total_ordering +from pathlib import Path +from typing import IO, Any, Iterator, Sequence, Union PathIsh = Union[Path, str] @@ -31,7 +31,7 @@ def is_compressed(p: Path) -> bool: def _zstd_open(path: Path, *args, **kwargs) -> IO: - import zstandard as zstd # type: ignore + import zstandard as zstd # type: ignore fh = path.open('rb') dctx = zstd.ZstdDecompressor() reader = dctx.stream_reader(fh) @@ -85,7 +85,7 @@ def kopen(path: PathIsh, *args, mode: str='rt', **kwargs) -> IO: # todo 'expected "BinaryIO"'?? return io.TextIOWrapper(ifile, encoding=encoding) elif name.endswith(Ext.lz4): - import lz4.frame # type: ignore + import lz4.frame # type: ignore return lz4.frame.open(str(pp), mode, *args, **kwargs) elif name.endswith(Ext.zstd) or name.endswith(Ext.zst): kwargs['mode'] = mode @@ -101,8 +101,8 @@ def kopen(path: PathIsh, *args, mode: str='rt', **kwargs) -> IO: return pp.open(mode, *args, **kwargs) -import typing import os +import typing if typing.TYPE_CHECKING: # otherwise mypy can't figure out that BasePath is a type alias.. @@ -147,6 +147,7 @@ def kexists(path: PathIsh, subpath: str) -> bool: import zipfile + if sys.version_info[:2] >= (3, 8): # meh... zipfile.Path is not available on 3.7 zipfile_Path = zipfile.Path diff --git a/my/core/cachew.py b/my/core/cachew.py index bcd838d..e0e7adf 100644 --- a/my/core/cachew.py +++ b/my/core/cachew.py @@ -1,11 +1,22 @@ from .internal import assert_subpackage; assert_subpackage(__name__) -from contextlib import contextmanager import logging -from pathlib import Path import sys -from typing import Optional, Iterator, cast, TYPE_CHECKING, TypeVar, Callable, overload, Union, Any, Type import warnings +from contextlib import contextmanager +from pathlib import Path +from typing import ( + TYPE_CHECKING, + Any, + Callable, + Iterator, + Optional, + Type, + TypeVar, + Union, + cast, + overload, +) import appdirs # type: ignore[import-untyped] diff --git a/my/core/cfg.py b/my/core/cfg.py index 0b59537..a71a7e3 100644 --- a/my/core/cfg.py +++ b/my/core/cfg.py @@ -1,6 +1,10 @@ from __future__ import annotations -from typing import TypeVar, Type, Callable, Dict, Any +import importlib +import re +import sys +from contextlib import ExitStack, contextmanager +from typing import Any, Callable, Dict, Iterator, Optional, Type, TypeVar Attrs = Dict[str, Any] @@ -27,8 +31,8 @@ def make_config(cls: Type[C], migration: Callable[[Attrs], Attrs]=lambda x: x) - F = TypeVar('F') -from contextlib import contextmanager -from typing import Iterator + + @contextmanager def _override_config(config: F) -> Iterator[F]: ''' @@ -46,9 +50,6 @@ def _override_config(config: F) -> Iterator[F]: delattr(config, k) -import importlib -import sys -from typing import Optional ModuleRegex = str @contextmanager def _reload_modules(modules: ModuleRegex) -> Iterator[None]: @@ -79,8 +80,6 @@ def _reload_modules(modules: ModuleRegex) -> Iterator[None]: sys.modules.pop(m, None) -from contextlib import ExitStack -import re @contextmanager def tmp_config(*, modules: Optional[ModuleRegex]=None, config=None): if modules is None: diff --git a/my/core/common.py b/my/core/common.py index f20e1d4..9a58caf 100644 --- a/my/core/common.py +++ b/my/core/common.py @@ -1,20 +1,20 @@ +import os +import warnings from glob import glob as do_glob from pathlib import Path -import os from typing import ( + TYPE_CHECKING, Callable, Iterable, List, Sequence, - TYPE_CHECKING, Tuple, TypeVar, Union, ) -import warnings -from . import warnings as core_warnings from . import compat +from . import warnings as core_warnings # some helper functions # TODO start deprecating this? soon we'd be able to use Path | str syntax which is shorter and more explicit @@ -92,7 +92,7 @@ def get_files( traceback.print_stack() if guess_compression: - from .kompress import CPath, is_compressed, ZipPath + from .kompress import CPath, ZipPath, is_compressed # NOTE: wrap is just for backwards compat with vendorized kompress # with kompress library, only is_compressed check and Cpath should be enough @@ -109,7 +109,7 @@ def get_files( return tuple(paths) -from typing import TypeVar, Callable, Generic +from typing import Callable, Generic, TypeVar _R = TypeVar('_R') @@ -133,6 +133,8 @@ class classproperty(Generic[_R]): import re + + # https://stackoverflow.com/a/295466/706389 def get_valid_filename(s: str) -> str: s = str(s).strip().replace(' ', '_') @@ -142,7 +144,6 @@ def get_valid_filename(s: str) -> str: # TODO deprecate and suggest to use one from my.core directly? not sure from .utils.itertools import unique_everseen - ### legacy imports, keeping them here for backwards compatibility ## hiding behind TYPE_CHECKING so it works in runtime ## in principle, warnings.deprecated decorator should cooperate with mypy, but doesn't look like it works atm? @@ -225,8 +226,8 @@ if not TYPE_CHECKING: from .stats import Stats from .types import ( Json, - datetime_naive, datetime_aware, + datetime_naive, ) tzdatetime = datetime_aware diff --git a/my/core/compat.py b/my/core/compat.py index 7bbe509..4372a01 100644 --- a/my/core/compat.py +++ b/my/core/compat.py @@ -6,7 +6,6 @@ If something is relevant to HPI itself, please put it in .hpi_compat instead import sys from typing import TYPE_CHECKING - if sys.version_info[:2] >= (3, 13): from warnings import deprecated else: @@ -48,7 +47,7 @@ else: # bisect_left doesn't have a 'key' parameter (which we use) # till python3.10 if sys.version_info[:2] <= (3, 9): - from typing import List, TypeVar, Any, Optional, Callable + from typing import Any, Callable, List, Optional, TypeVar X = TypeVar('X') @@ -131,6 +130,6 @@ else: if sys.version_info[:2] >= (3, 11): - from typing import assert_never, assert_type, Never + from typing import Never, assert_never, assert_type else: - from typing_extensions import assert_never, assert_type, Never + from typing_extensions import Never, assert_never, assert_type diff --git a/my/core/core_config.py b/my/core/core_config.py index 889dbf9..9036971 100644 --- a/my/core/core_config.py +++ b/my/core/core_config.py @@ -2,18 +2,18 @@ Bindings for the 'core' HPI configuration ''' +import re from dataclasses import dataclass from pathlib import Path -import re -from typing import Sequence, Optional +from typing import Optional, Sequence -from . import warnings, PathIsh +from . import PathIsh, warnings try: from my.config import core as user_config # type: ignore[attr-defined] except Exception as e: try: - from my.config import common as user_config # type: ignore[attr-defined] + from my.config import common as user_config # type: ignore[attr-defined] warnings.high("'common' config section is deprecated. Please rename it to 'core'.") except Exception as e2: # make it defensive, because it's pretty commonly used and would be annoying if it breaks hpi doctor etc. @@ -116,12 +116,15 @@ class Config(user_config): from .cfg import make_config + config = make_config(Config) ### tests start -from typing import Iterator from contextlib import contextmanager as ctx +from typing import Iterator + + @ctx def _reset_config() -> Iterator[Config]: # todo maybe have this decorator for the whole of my.config? diff --git a/my/core/denylist.py b/my/core/denylist.py index 8c18e06..7ca0ddf 100644 --- a/my/core/denylist.py +++ b/my/core/denylist.py @@ -5,19 +5,19 @@ A helper module for defining denylists for sources programmatically For docs, see doc/DENYLIST.md """ -import sys -import json import functools +import json +import sys from collections import defaultdict -from typing import TypeVar, Set, Any, Mapping, Iterator, Dict, List from pathlib import Path +from typing import Any, Dict, Iterator, List, Mapping, Set, TypeVar import click from more_itertools import seekable -from my.core.serialize import dumps -from my.core.common import PathIsh -from my.core.warnings import medium +from my.core.common import PathIsh +from my.core.serialize import dumps +from my.core.warnings import medium T = TypeVar("T") diff --git a/my/core/discovery_pure.py b/my/core/discovery_pure.py index 85b75ab..63d9922 100644 --- a/my/core/discovery_pure.py +++ b/my/core/discovery_pure.py @@ -16,11 +16,11 @@ NOT_HPI_MODULE_VAR = '__NOT_HPI_MODULE__' ### import ast -import os -from typing import Optional, Sequence, List, NamedTuple, Iterable, cast, Any -from pathlib import Path -import re import logging +import os +import re +from pathlib import Path +from typing import Any, Iterable, List, NamedTuple, Optional, Sequence, cast ''' None means that requirements weren't defined (different from empty requirements) diff --git a/my/core/error.py b/my/core/error.py index 2432a5d..c4dff07 100644 --- a/my/core/error.py +++ b/my/core/error.py @@ -3,14 +3,28 @@ Various error handling helpers See https://beepb00p.xyz/mypy-error-handling.html#kiss for more detail """ +import traceback +from datetime import datetime from itertools import tee -from typing import Union, TypeVar, Iterable, List, Tuple, Type, Optional, Callable, Any, cast, Iterator, Literal +from typing import ( + Any, + Callable, + Iterable, + Iterator, + List, + Literal, + Optional, + Tuple, + Type, + TypeVar, + Union, + cast, +) from .types import Json - T = TypeVar('T') -E = TypeVar('E', bound=Exception) # TODO make covariant? +E = TypeVar('E', bound=Exception) # TODO make covariant? ResT = Union[T, E] @@ -18,6 +32,7 @@ Res = ResT[T, Exception] ErrorPolicy = Literal["yield", "raise", "drop"] + def notnone(x: Optional[T]) -> T: assert x is not None return x @@ -29,6 +44,7 @@ def unwrap(res: Res[T]) -> T: else: return res + def drop_exceptions(itr: Iterator[Res[T]]) -> Iterator[T]: """Return non-errors from the iterable""" for o in itr: @@ -146,23 +162,23 @@ def test_sort_res_by() -> None: # helpers to associate timestamps with the errors (so something meaningful could be displayed on the plots, for example) # todo document it under 'patterns' somewhere... - # todo proper typevar? -from datetime import datetime def set_error_datetime(e: Exception, dt: Optional[datetime]) -> None: if dt is None: return e.args = e.args + (dt,) # todo not sure if should return new exception? + def attach_dt(e: Exception, *, dt: Optional[datetime]) -> Exception: set_error_datetime(e, dt) return e + # todo it might be problematic because might mess with timezones (when it's converted to string, it's converted to a shift) def extract_error_datetime(e: Exception) -> Optional[datetime]: import re - from datetime import datetime + for x in reversed(e.args): if isinstance(x, datetime): return x @@ -177,7 +193,6 @@ def extract_error_datetime(e: Exception) -> Optional[datetime]: return None -import traceback def error_to_json(e: Exception) -> Json: estr = ''.join(traceback.format_exception(Exception, e, e.__traceback__)) return {'error': estr} @@ -185,6 +200,7 @@ def error_to_json(e: Exception) -> Json: MODULE_SETUP_URL = 'https://github.com/karlicoss/HPI/blob/master/doc/SETUP.org#private-configuration-myconfig' + def warn_my_config_import_error(err: Union[ImportError, AttributeError], help_url: Optional[str] = None) -> bool: """ If the user tried to import something from my.config but it failed, @@ -193,7 +209,9 @@ def warn_my_config_import_error(err: Union[ImportError, AttributeError], help_ur Returns True if it matched a possible config error """ import re + import click + if help_url is None: help_url = MODULE_SETUP_URL if type(err) is ImportError: @@ -226,7 +244,8 @@ See {help_url} or check the corresponding module.py file for an example\ def test_datetime_errors() -> None: - import pytz + import pytz # noqa: I001 + dt_notz = datetime.now() dt_tz = datetime.now(tz=pytz.timezone('Europe/Amsterdam')) for dt in [dt_tz, dt_notz]: diff --git a/my/core/experimental.py b/my/core/experimental.py index c10ba71..1a78272 100644 --- a/my/core/experimental.py +++ b/my/core/experimental.py @@ -1,6 +1,6 @@ import sys -from typing import Any, Dict, Optional import types +from typing import Any, Dict, Optional # The idea behind this one is to support accessing "overlaid/shadowed" modules from namespace packages diff --git a/my/core/freezer.py b/my/core/freezer.py index 09ba032..e46525b 100644 --- a/my/core/freezer.py +++ b/my/core/freezer.py @@ -2,7 +2,7 @@ from .internal import assert_subpackage; assert_subpackage(__name__) import dataclasses as dcl import inspect -from typing import TypeVar, Type, Any +from typing import Any, Type, TypeVar D = TypeVar('D') @@ -22,6 +22,8 @@ def _freeze_dataclass(Orig: Type[D]): # todo need some decorator thingie? from typing import Generic + + class Freezer(Generic[D]): ''' Some magic which converts dataclass properties into fields. diff --git a/my/core/hpi_compat.py b/my/core/hpi_compat.py index 3c567d9..bad0b17 100644 --- a/my/core/hpi_compat.py +++ b/my/core/hpi_compat.py @@ -2,8 +2,8 @@ Contains various backwards compatibility/deprecation helpers relevant to HPI itself. (as opposed to .compat module which implements compatibility between python versions) """ -import os import inspect +import os import re from types import ModuleType from typing import Iterator, List, Optional, TypeVar diff --git a/my/core/influxdb.py b/my/core/influxdb.py index c4b6409..c39f6af 100644 --- a/my/core/influxdb.py +++ b/my/core/influxdb.py @@ -4,11 +4,12 @@ TODO doesn't really belong to 'core' morally, but can think of moving out later from .internal import assert_subpackage; assert_subpackage(__name__) -from typing import Iterable, Any, Optional, Dict +from typing import Any, Dict, Iterable, Optional + +import click from .logging import make_logger -from .types import asdict, Json - +from .types import Json, asdict logger = make_logger(__name__) @@ -28,7 +29,7 @@ def fill(it: Iterable[Any], *, measurement: str, reset: bool=RESET_DEFAULT, dt_c db = config.db - from influxdb import InfluxDBClient # type: ignore + from influxdb import InfluxDBClient # type: ignore client = InfluxDBClient() # todo maybe create if not exists? # client.create_database(db) @@ -106,6 +107,7 @@ def magic_fill(it, *, name: Optional[str]=None, reset: bool=RESET_DEFAULT) -> No it = it() from itertools import tee + from more_itertools import first, one it, x = tee(it) f = first(x, default=None) @@ -125,8 +127,6 @@ def magic_fill(it, *, name: Optional[str]=None, reset: bool=RESET_DEFAULT) -> No fill(it, measurement=name, reset=reset, dt_col=dtf) -import click - @click.group() def main() -> None: pass diff --git a/my/core/init.py b/my/core/init.py index bec3a9a..49148de 100644 --- a/my/core/init.py +++ b/my/core/init.py @@ -14,9 +14,9 @@ Please let me know if you are aware of a better way of dealing with this! # separate function to present namespace pollution def setup_config() -> None: - from pathlib import Path import sys import warnings + from pathlib import Path from .preinit import get_mycfg_dir mycfg_dir = get_mycfg_dir() diff --git a/my/core/konsume.py b/my/core/konsume.py index 10bea8d..ac1b100 100644 --- a/my/core/konsume.py +++ b/my/core/konsume.py @@ -94,6 +94,8 @@ class Wvalue(Zoomable): from typing import Tuple + + def _wrap(j, parent=None) -> Tuple[Zoomable, List[Zoomable]]: res: Zoomable cc: List[Zoomable] @@ -123,6 +125,7 @@ def _wrap(j, parent=None) -> Tuple[Zoomable, List[Zoomable]]: from contextlib import contextmanager from typing import Iterator + class UnconsumedError(Exception): pass @@ -146,6 +149,8 @@ Expected {c} to be fully consumed by the parser. from typing import cast + + def test_unconsumed() -> None: import pytest with pytest.raises(UnconsumedError): diff --git a/my/core/logging.py b/my/core/logging.py index 882ab12..734c1e0 100644 --- a/my/core/logging.py +++ b/my/core/logging.py @@ -1,11 +1,11 @@ from __future__ import annotations -from functools import lru_cache import logging import os import sys -from typing import Union, TYPE_CHECKING import warnings +from functools import lru_cache +from typing import TYPE_CHECKING, Union def test() -> None: @@ -222,7 +222,9 @@ def make_logger(name: str, *, level: LevelIsh = None) -> logging.Logger: # OK, when stdout is not a tty, enlighten doesn't log anything, good def get_enlighten(): # TODO could add env variable to disable enlighten for a module? - from unittest.mock import Mock # Mock to return stub so cients don't have to think about it + from unittest.mock import ( + Mock, # Mock to return stub so cients don't have to think about it + ) # for now hidden behind the flag since it's a little experimental if os.environ.get('ENLIGHTEN_ENABLE', None) is None: diff --git a/my/core/orgmode.py b/my/core/orgmode.py index 5894b23..d9a254c 100644 --- a/my/core/orgmode.py +++ b/my/core/orgmode.py @@ -2,6 +2,8 @@ Various helpers for reading org-mode data """ from datetime import datetime + + def parse_org_datetime(s: str) -> datetime: s = s.strip('[]') for fmt, cl in [ @@ -21,8 +23,10 @@ def parse_org_datetime(s: str) -> datetime: # TODO I guess want to borrow inspiration from bs4? element type <-> tag; and similar logic for find_one, find_all +from typing import Callable, Iterable, TypeVar + from orgparse import OrgNode -from typing import Iterable, TypeVar, Callable + V = TypeVar('V') def collect(n: OrgNode, cfun: Callable[[OrgNode], Iterable[V]]) -> Iterable[V]: @@ -32,6 +36,8 @@ def collect(n: OrgNode, cfun: Callable[[OrgNode], Iterable[V]]) -> Iterable[V]: from more_itertools import one from orgparse.extra import Table + + def one_table(o: OrgNode) -> Table: return one(collect(o, lambda n: (x for x in n.body_rich if isinstance(x, Table)))) diff --git a/my/core/pandas.py b/my/core/pandas.py index 5688aa3..8abbb1f 100644 --- a/my/core/pandas.py +++ b/my/core/pandas.py @@ -8,15 +8,14 @@ from __future__ import annotations import dataclasses from datetime import datetime, timezone from pprint import pformat -from typing import TYPE_CHECKING, Any, Iterable, Type, Dict, Literal, Callable, TypeVar +from typing import TYPE_CHECKING, Any, Callable, Dict, Iterable, Literal, Type, TypeVar from decorator import decorator -from . import warnings, Res +from . import Res, warnings +from .error import error_to_json, extract_error_datetime from .logging import make_logger from .types import Json, asdict -from .error import error_to_json, extract_error_datetime - logger = make_logger(__name__) diff --git a/my/core/preinit.py b/my/core/preinit.py index 8c0f6a4..be5477b 100644 --- a/my/core/preinit.py +++ b/my/core/preinit.py @@ -1,11 +1,13 @@ from pathlib import Path + # todo preinit isn't really a good name? it's only in a separate file because # - it's imported from my.core.init (so we wan't to keep this file as small/reliable as possible, hence not common or something) # - we still need this function in __main__, so has to be separate from my/core/init.py def get_mycfg_dir() -> Path: - import appdirs # type: ignore[import-untyped] import os + + import appdirs # type: ignore[import-untyped] # not sure if that's necessary, i.e. could rely on PYTHONPATH instead # on the other hand, by using MY_CONFIG we are guaranteed to load it from the desired path? mvar = os.environ.get('MY_CONFIG') diff --git a/my/core/query.py b/my/core/query.py index 4d7363e..cf85b1b 100644 --- a/my/core/query.py +++ b/my/core/query.py @@ -10,16 +10,27 @@ import importlib import inspect import itertools from datetime import datetime -from typing import TypeVar, Tuple, Optional, Union, Callable, Iterable, Iterator, Dict, Any, NamedTuple, List +from typing import ( + Any, + Callable, + Dict, + Iterable, + Iterator, + List, + NamedTuple, + Optional, + Tuple, + TypeVar, + Union, +) import more_itertools from . import error as err -from .types import is_namedtuple from .error import Res, unwrap +from .types import is_namedtuple from .warnings import low - T = TypeVar("T") ET = Res[T] @@ -687,9 +698,10 @@ def test_raise_exceptions() -> None: def test_wrap_unsortable_with_error_and_warning() -> None: - import pytest from collections import Counter + import pytest + # by default should wrap unsortable (error) with pytest.warns(UserWarning, match=r"encountered exception"): res = list(select(_mixed_iter_errors(), order_value=lambda o: isinstance(o, datetime))) diff --git a/my/core/query_range.py b/my/core/query_range.py index 2b3a3d3..d077225 100644 --- a/my/core/query_range.py +++ b/my/core/query_range.py @@ -9,24 +9,22 @@ See the select_range function below import re import time +from datetime import date, datetime, timedelta from functools import lru_cache -from datetime import datetime, timedelta, date -from typing import Callable, Iterator, NamedTuple, Optional, Any, Type +from typing import Any, Callable, Iterator, NamedTuple, Optional, Type import more_itertools +from .compat import fromisoformat from .query import ( - QueryException, - select, + ET, OrderFunc, + QueryException, Where, _handle_generate_order_by, - ET, + select, ) -from .compat import fromisoformat - - timedelta_regex = re.compile(r"^((?P[\.\d]+?)w)?((?P[\.\d]+?)d)?((?P[\.\d]+?)h)?((?P[\.\d]+?)m)?((?P[\.\d]+?)s)?$") diff --git a/my/core/serialize.py b/my/core/serialize.py index e38bca5..b196d47 100644 --- a/my/core/serialize.py +++ b/my/core/serialize.py @@ -1,13 +1,13 @@ import datetime -from dataclasses import is_dataclass, asdict -from pathlib import Path +from dataclasses import asdict, is_dataclass from decimal import Decimal -from typing import Any, Optional, Callable, NamedTuple from functools import lru_cache +from pathlib import Path +from typing import Any, Callable, NamedTuple, Optional from .error import error_to_json -from .types import is_namedtuple from .pytest import parametrize +from .types import is_namedtuple # note: it would be nice to combine the 'asdict' and _default_encode to some function # that takes a complex python object and returns JSON-compatible fields, while still @@ -117,6 +117,7 @@ def _dumps_factory(**kwargs) -> Callable[[Any], str]: def stdlib_factory() -> Optional[Dumps]: import json + from .warnings import high high( diff --git a/my/core/source.py b/my/core/source.py index 6d0f0fd..9488ae2 100644 --- a/my/core/source.py +++ b/my/core/source.py @@ -3,9 +3,9 @@ Decorator to gracefully handle importing a data source, or warning and yielding nothing (or a default) when its not available """ -from functools import wraps -from typing import Any, Iterator, TypeVar, Callable, Optional, Iterable import warnings +from functools import wraps +from typing import Any, Callable, Iterable, Iterator, Optional, TypeVar from .warnings import medium diff --git a/my/core/sqlite.py b/my/core/sqlite.py index 4a471a9..47bd78b 100644 --- a/my/core/sqlite.py +++ b/my/core/sqlite.py @@ -1,13 +1,12 @@ from .internal import assert_subpackage; assert_subpackage(__name__) -from contextlib import contextmanager -from pathlib import Path import shutil import sqlite3 +from contextlib import contextmanager +from pathlib import Path from tempfile import TemporaryDirectory -from typing import Tuple, Any, Iterator, Callable, Optional, Union, Literal - +from typing import Any, Callable, Iterator, Literal, Optional, Tuple, Union, overload from .common import PathIsh from .compat import assert_never @@ -98,7 +97,6 @@ def sqlite_copy_and_open(db: PathIsh) -> sqlite3.Connection: # and then the return type ends up as Iterator[Tuple[str, ...]], which isn't desirable :( # a bit annoying to have this copy-pasting, but hopefully not a big issue -from typing import overload @overload def select(cols: Tuple[str ], rest: str, *, db: sqlite3.Connection) -> \ Iterator[Tuple[Any ]]: ... diff --git a/my/core/stats.py b/my/core/stats.py index d724068..08821a2 100644 --- a/my/core/stats.py +++ b/my/core/stats.py @@ -3,13 +3,13 @@ Helpers for hpi doctor/stats functionality. ''' import collections -from contextlib import contextmanager -from datetime import datetime import importlib import inspect +import typing +from contextlib import contextmanager +from datetime import datetime from pathlib import Path from types import ModuleType -import typing from typing import ( Any, Callable, @@ -26,7 +26,6 @@ from typing import ( from .types import asdict - Stats = Dict[str, Any] @@ -133,8 +132,8 @@ def test_stat() -> None: # # works with pandas dataframes - import pandas as pd import numpy as np + import pandas as pd def df() -> pd.DataFrame: dates = pd.date_range(start='2024-02-10 08:00', end='2024-02-11 16:00', freq='5h') @@ -357,7 +356,7 @@ def _stat_item(item): def _stat_iterable(it: Iterable[Any], quick: bool = False) -> Stats: - from more_itertools import ilen, take, first + from more_itertools import first, ilen, take # todo not sure if there is something in more_itertools to compute this? total = 0 @@ -448,6 +447,7 @@ def _guess_datetime(x: Any) -> Optional[datetime]: def test_guess_datetime() -> None: from dataclasses import dataclass from typing import NamedTuple + from .compat import fromisoformat dd = fromisoformat('2021-02-01T12:34:56Z') diff --git a/my/core/structure.py b/my/core/structure.py index 458440e..df25e37 100644 --- a/my/core/structure.py +++ b/my/core/structure.py @@ -1,16 +1,14 @@ +import atexit import os import shutil import tempfile import zipfile -import atexit - -from typing import Sequence, Generator, List, Union, Tuple from contextlib import contextmanager from pathlib import Path +from typing import Generator, List, Sequence, Tuple, Union from .logging import make_logger - logger = make_logger(__name__, level="info") diff --git a/my/core/tests/auto_stats.py b/my/core/tests/auto_stats.py index bf4764c..d10d4c4 100644 --- a/my/core/tests/auto_stats.py +++ b/my/core/tests/auto_stats.py @@ -6,7 +6,7 @@ from contextlib import contextmanager from dataclasses import dataclass from datetime import datetime, timedelta from pathlib import Path -from typing import Iterable, Sequence, Iterator +from typing import Iterable, Iterator, Sequence @dataclass diff --git a/my/core/tests/common.py b/my/core/tests/common.py index a102ad3..22a74d7 100644 --- a/my/core/tests/common.py +++ b/my/core/tests/common.py @@ -1,10 +1,9 @@ -from contextlib import contextmanager import os +from contextlib import contextmanager from typing import Iterator, Optional import pytest - V = 'HPI_TESTS_USES_OPTIONAL_DEPS' # TODO use it for serialize tests that are using simplejson/orjson? diff --git a/my/core/tests/denylist.py b/my/core/tests/denylist.py index cca757d..8016282 100644 --- a/my/core/tests/denylist.py +++ b/my/core/tests/denylist.py @@ -1,8 +1,8 @@ -from datetime import datetime import json -from pathlib import Path -from typing import NamedTuple, Iterator import warnings +from datetime import datetime +from pathlib import Path +from typing import Iterator, NamedTuple from ..denylist import DenyList diff --git a/my/core/tests/sqlite.py b/my/core/tests/sqlite.py index b3ecffe..1ad0748 100644 --- a/my/core/tests/sqlite.py +++ b/my/core/tests/sqlite.py @@ -1,7 +1,7 @@ -from concurrent.futures import ProcessPoolExecutor -from pathlib import Path import shutil import sqlite3 +from concurrent.futures import ProcessPoolExecutor +from pathlib import Path from tempfile import TemporaryDirectory from ..sqlite import sqlite_connect_immutable, sqlite_copy_and_open diff --git a/my/core/tests/structure.py b/my/core/tests/structure.py index beb8e7f..6a94fc4 100644 --- a/my/core/tests/structure.py +++ b/my/core/tests/structure.py @@ -1,9 +1,8 @@ from pathlib import Path -from ..structure import match_structure - import pytest +from ..structure import match_structure structure_data: Path = Path(__file__).parent / "structure_data" diff --git a/my/core/tests/test_cachew.py b/my/core/tests/test_cachew.py index 5f7dd65..70ac76f 100644 --- a/my/core/tests/test_cachew.py +++ b/my/core/tests/test_cachew.py @@ -35,8 +35,7 @@ def test_cachew_dir_none() -> None: settings.ENABLE = True # by default it's off in tests (see conftest.py) - from my.core.cachew import cache_dir - from my.core.cachew import mcachew + from my.core.cachew import cache_dir, mcachew from my.core.core_config import _reset_config as reset with reset() as cc: diff --git a/my/core/tests/test_cli.py b/my/core/tests/test_cli.py index 4d847ae..1838e84 100644 --- a/my/core/tests/test_cli.py +++ b/my/core/tests/test_cli.py @@ -1,6 +1,6 @@ import os -from subprocess import check_call import sys +from subprocess import check_call def test_lists_modules() -> None: diff --git a/my/core/tests/test_get_files.py b/my/core/tests/test_get_files.py index 52e43f8..68be4d9 100644 --- a/my/core/tests/test_get_files.py +++ b/my/core/tests/test_get_files.py @@ -1,15 +1,15 @@ import os -from pathlib import Path import shutil import tempfile -from typing import TYPE_CHECKING import zipfile +from pathlib import Path +from typing import TYPE_CHECKING + +import pytest from ..common import get_files from ..kompress import CPath, ZipPath -import pytest - # hack to replace all /tmp with 'real' tmp dir # not ideal, but makes tests more concise diff --git a/my/core/time.py b/my/core/time.py index 430b082..83a407b 100644 --- a/my/core/time.py +++ b/my/core/time.py @@ -1,5 +1,5 @@ from functools import lru_cache -from typing import Sequence, Dict +from typing import Dict, Sequence import pytz diff --git a/my/core/types.py b/my/core/types.py index c1b0add..b1cf103 100644 --- a/my/core/types.py +++ b/my/core/types.py @@ -1,13 +1,13 @@ from .internal import assert_subpackage; assert_subpackage(__name__) -from dataclasses import is_dataclass, asdict as dataclasses_asdict +from dataclasses import asdict as dataclasses_asdict +from dataclasses import is_dataclass from datetime import datetime from typing import ( Any, Dict, ) - Json = Dict[str, Any] diff --git a/my/core/util.py b/my/core/util.py index 57e41d4..b48a450 100644 --- a/my/core/util.py +++ b/my/core/util.py @@ -1,21 +1,24 @@ -from pathlib import Path -from itertools import chain import os import pkgutil import sys -from typing import List, Iterable, Optional +from itertools import chain +from pathlib import Path +from types import ModuleType +from typing import Iterable, List, Optional -from .discovery_pure import HPIModule, ignored, _is_not_module_src, has_stats +from .discovery_pure import HPIModule, _is_not_module_src, has_stats, ignored def modules() -> Iterable[HPIModule]: import my + for m in _iter_all_importables(my): yield m __NOT_HPI_MODULE__ = 'Import this to mark a python file as a helper, not an actual HPI module' from .discovery_pure import NOT_HPI_MODULE_VAR + assert NOT_HPI_MODULE_VAR in globals() # check name consistency def is_not_hpi_module(module: str) -> Optional[str]: @@ -23,6 +26,7 @@ def is_not_hpi_module(module: str) -> Optional[str]: None if a module, otherwise returns reason ''' import importlib + path: Optional[str] = None try: # TODO annoying, this can cause import of the parent module? @@ -41,7 +45,6 @@ def is_not_hpi_module(module: str) -> Optional[str]: return None -from types import ModuleType # todo reuse in readme/blog post # borrowed from https://github.com/sanitizers/octomachinery/blob/24288774d6dcf977c5033ae11311dbff89394c89/tests/circular_imports_test.py#L22-L55 def _iter_all_importables(pkg: ModuleType) -> Iterable[HPIModule]: @@ -192,6 +195,7 @@ from my.core import __NOT_HPI_MODULE__ ''') import sys + orig_path = list(sys.path) try: sys.path.insert(0, str(badp)) @@ -226,6 +230,7 @@ def stats(): ''') import sys + orig_path = list(sys.path) try: sys.path.insert(0, str(badp)) diff --git a/my/core/utils/concurrent.py b/my/core/utils/concurrent.py index cc17cda..3553cd9 100644 --- a/my/core/utils/concurrent.py +++ b/my/core/utils/concurrent.py @@ -1,10 +1,9 @@ -from concurrent.futures import Future, Executor import sys -from typing import Any, Callable, Optional, TypeVar, TYPE_CHECKING +from concurrent.futures import Executor, Future +from typing import TYPE_CHECKING, Any, Callable, Optional, TypeVar from ..compat import ParamSpec - _P = ParamSpec('_P') _T = TypeVar('_T') @@ -15,6 +14,7 @@ class DummyExecutor(Executor): This is useful if you're already using Executor for parallelising, but also want to provide an option to run the code serially (e.g. for debugging) """ + def __init__(self, max_workers: Optional[int] = 1) -> None: self._shutdown = False self._max_workers = max_workers diff --git a/my/core/utils/imports.py b/my/core/utils/imports.py index efd8e9a..4666a5e 100644 --- a/my/core/utils/imports.py +++ b/my/core/utils/imports.py @@ -1,9 +1,9 @@ import importlib import importlib.util -from pathlib import Path import sys -from typing import Optional +from pathlib import Path from types import ModuleType +from typing import Optional from ..common import PathIsh diff --git a/my/core/utils/itertools.py b/my/core/utils/itertools.py index e8802bb..023484d 100644 --- a/my/core/utils/itertools.py +++ b/my/core/utils/itertools.py @@ -4,8 +4,10 @@ Various helpers/transforms of iterators Ideally this should be as small as possible and we should rely on stdlib itertools or more_itertools """ +import warnings from collections.abc import Hashable from typing import ( + TYPE_CHECKING, Callable, Dict, Iterable, @@ -13,18 +15,16 @@ from typing import ( List, Optional, Sized, - Union, TypeVar, + Union, cast, - TYPE_CHECKING, ) -import warnings + +import more_itertools +from decorator import decorator from ..compat import ParamSpec -from decorator import decorator -import more_itertools - T = TypeVar('T') K = TypeVar('K') V = TypeVar('V') @@ -268,7 +268,9 @@ def check_if_hashable(iterable: Iterable[_HT]) -> Iterable[_HT]: def test_check_if_hashable() -> None: from dataclasses import dataclass from typing import Set, Tuple + import pytest + from ..compat import assert_type x1: List[int] = [1, 2] @@ -353,6 +355,7 @@ def unique_everseen( def test_unique_everseen() -> None: import pytest + from ..tests.common import tmp_environ_set def fun_good() -> Iterator[int]: diff --git a/my/core/warnings.py b/my/core/warnings.py index 7051f34..82e539b 100644 --- a/my/core/warnings.py +++ b/my/core/warnings.py @@ -6,8 +6,8 @@ E.g. would be nice to propagate the warnings in the UI (it's even a subclass of ''' import sys -from typing import Optional import warnings +from typing import TYPE_CHECKING, Optional import click @@ -48,5 +48,11 @@ def high(message: str, *args, **kwargs) -> None: _warn(message, *args, **kwargs) -# NOTE: deprecated -- legacy import -from warnings import warn \ No newline at end of file +if not TYPE_CHECKING: + from .compat import deprecated + + @deprecated('use warnings.warn directly instead') + def warn(*args, **kwargs): + import warnings + + return warnings.warn(*args, **kwargs) diff --git a/my/location/common.py b/my/location/common.py index 7824bef..510e005 100644 --- a/my/location/common.py +++ b/my/location/common.py @@ -41,9 +41,9 @@ def locations_to_gpx(locations: Iterable[LocationProtocol], buffer: TextIO) -> I try: import gpxpy.gpx except ImportError as ie: - from my.core.warnings import warn + from my.core.warnings import high - warn("gpxpy not installed, cannot write to gpx. 'pip install gpxpy'") + high("gpxpy not installed, cannot write to gpx. 'pip install gpxpy'") raise ie gpx = gpxpy.gpx.GPX() From 245ad220578a3f3a7db1414bb7d5379f77fb1fd3 Mon Sep 17 00:00:00 2001 From: karlicoss Date: Sat, 17 Aug 2024 12:56:13 +0100 Subject: [PATCH 068/122] core.common: bring back asdict backwards compat -- was used in orger --- my/core/common.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/my/core/common.py b/my/core/common.py index 9a58caf..225ff2c 100644 --- a/my/core/common.py +++ b/my/core/common.py @@ -212,6 +212,12 @@ if not TYPE_CHECKING: return logging.LazyLogger(*args, **kwargs) + @deprecated('use my.core.types.asdict instead') + def asdict(*args, **kwargs): + from . import types + + return types.asdict(*args, **kwargs) + # todo wrap these in deprecated decorator as well? from .cachew import mcachew # noqa: F401 From 5ec357915bbe13a664392ca245d996d00e27acb8 Mon Sep 17 00:00:00 2001 From: karlicoss Date: Sat, 17 Aug 2024 12:59:03 +0100 Subject: [PATCH 069/122] core.common: add test for classproperty --- my/core/common.py | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/my/core/common.py b/my/core/common.py index 225ff2c..dcd1074 100644 --- a/my/core/common.py +++ b/my/core/common.py @@ -5,6 +5,7 @@ from pathlib import Path from typing import ( TYPE_CHECKING, Callable, + Generic, Iterable, List, Sequence, @@ -109,11 +110,12 @@ def get_files( return tuple(paths) -from typing import Callable, Generic, TypeVar - _R = TypeVar('_R') + # https://stackoverflow.com/a/5192374/706389 +# NOTE: it was added to stdlib in 3.9 and then deprecated in 3.11 +# seems that the suggested solution is to use custom decorator? class classproperty(Generic[_R]): def __init__(self, f: Callable[..., _R]) -> None: self.f = f @@ -122,6 +124,19 @@ class classproperty(Generic[_R]): return self.f(cls) +def test_classproperty() -> None: + from .compat import assert_type + + class C: + @classproperty + def prop(cls) -> str: + return 'hello' + + res = C.prop + assert res == 'hello' + assert_type(res, str) + + # hmm, this doesn't really work with mypy well.. # https://github.com/python/mypy/issues/6244 # class staticproperty(Generic[_R]): From 9f017fb29be53866e19ffdf9054b6ac6f011a9cd Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Mon, 19 Aug 2024 23:50:12 +0100 Subject: [PATCH 070/122] my.core.pandas: add more tests --- my/core/pandas.py | 126 ++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 110 insertions(+), 16 deletions(-) diff --git a/my/core/pandas.py b/my/core/pandas.py index 8abbb1f..8ad93cb 100644 --- a/my/core/pandas.py +++ b/my/core/pandas.py @@ -1,6 +1,7 @@ ''' Various pandas helpers and convenience functions ''' + from __future__ import annotations # todo not sure if belongs to 'core'. It's certainly 'more' core than actual modules, but still not essential @@ -8,12 +9,22 @@ from __future__ import annotations import dataclasses from datetime import datetime, timezone from pprint import pformat -from typing import TYPE_CHECKING, Any, Callable, Dict, Iterable, Literal, Type, TypeVar +from typing import ( + TYPE_CHECKING, + Any, + Callable, + Dict, + Iterable, + Iterator, + Literal, + Type, + TypeVar, +) from decorator import decorator -from . import Res, warnings -from .error import error_to_json, extract_error_datetime +from . import warnings +from .error import Res, error_to_json, extract_error_datetime from .logging import make_logger from .types import Json, asdict @@ -38,7 +49,7 @@ else: S1 = Any -def check_dateish(s: SeriesT[S1]) -> Iterable[str]: +def _check_dateish(s: SeriesT[S1]) -> Iterable[str]: import pandas as pd # noqa: F811 not actually a redefinition ctype = s.dtype @@ -62,9 +73,37 @@ def check_dateish(s: SeriesT[S1]) -> Iterable[str]: def test_check_dateish() -> None: import pandas as pd - # todo just a dummy test to check it doesn't crash, need something meaningful - s1 = pd.Series([1, 2, 3]) - list(check_dateish(s1)) + from .compat import fromisoformat + + # empty series shouldn't warn + assert list(_check_dateish(pd.Series([]))) == [] + + # if no dateimes, shouldn't return any warnings + assert list(_check_dateish(pd.Series([1, 2, 3]))) == [] + + # all values are datetimes, shouldn't warn + # fmt: off + assert list(_check_dateish(pd.Series([ + fromisoformat('2024-08-19T01:02:03'), + fromisoformat('2024-08-19T03:04:05'), + ]))) == [] + # fmt: on + + # mixture of timezones -- should warn + # fmt: off + assert len(list(_check_dateish(pd.Series([ + fromisoformat('2024-08-19T01:02:03'), + fromisoformat('2024-08-19T03:04:05Z'), + ])))) == 1 + # fmt: on + + # TODO hmm. maybe this should actually warn? + # fmt: off + assert len(list(_check_dateish(pd.Series([ + 'whatever', + fromisoformat('2024-08-19T01:02:03'), + ])))) == 0 + # fmt: on # fmt: off @@ -102,7 +141,7 @@ def check_dataframe(f: FuncT, error_col_policy: ErrorColPolicy = 'add_if_missing # makes sense to keep super defensive try: for col, data in df.reset_index().items(): - for w in check_dateish(data): + for w in _check_dateish(data): warnings.low(f"{tag}, column '{col}': {w}") except Exception as e: logger.exception(e) @@ -126,8 +165,7 @@ def error_to_row(e: Exception, *, dt_col: str = 'dt', tz: timezone | None = None return err_dict -# todo not sure about naming -def to_jsons(it: Iterable[Res[Any]]) -> Iterable[Json]: +def _to_jsons(it: Iterable[Res[Any]]) -> Iterable[Json]: for r in it: if isinstance(r, Exception): yield error_to_row(r) @@ -162,7 +200,7 @@ def as_dataframe(it: Iterable[Res[Any]], schema: Schema | None = None) -> DataFr import pandas as pd # noqa: F811 not actually a redefinition columns = None if schema is None else list(_as_columns(schema).keys()) - return pd.DataFrame(to_jsons(it), columns=columns) + return pd.DataFrame(_to_jsons(it), columns=columns) # ugh. in principle this could be inside the test @@ -172,20 +210,76 @@ def as_dataframe(it: Iterable[Res[Any]], schema: Schema | None = None) -> DataFr # see https://github.com/pytest-dev/pytest/issues/7856 @dataclasses.dataclass class _X: + # FIXME try moving inside? x: int def test_as_dataframe() -> None: + import numpy as np + import pandas as pd import pytest + from pandas.testing import assert_frame_equal - it = (dict(i=i, s=f'str{i}') for i in range(10)) + from .compat import fromisoformat + + it = (dict(i=i, s=f'str{i}') for i in range(5)) with pytest.warns(UserWarning, match=r"No 'error' column") as record_warnings: # noqa: F841 df: DataFrameT = as_dataframe(it) # todo test other error col policies - assert list(df.columns) == ['i', 's', 'error'] - assert len(as_dataframe([])) == 0 + # fmt: off + assert_frame_equal( + df, + pd.DataFrame({ + 'i' : [0 , 1 , 2 , 3 , 4 ], + 's' : ['str0', 'str1', 'str2', 'str3', 'str4'], + # NOTE: error column is always added + 'error': [None , None , None , None , None ], + }), + ) + # fmt: on + assert_frame_equal(as_dataframe([]), pd.DataFrame(columns=['error'])) - # makes sense to specify the schema so the downstream program doesn't fail in case of empty iterable df2: DataFrameT = as_dataframe([], schema=_X) - assert list(df2.columns) == ['x', 'error'] + assert_frame_equal( + df2, + # FIXME hmm. x column type should be an int?? and error should be string (or object??) + pd.DataFrame(columns=['x', 'error']), + ) + + @dataclasses.dataclass + class S: + value: str + + def it2() -> Iterator[Res[S]]: + yield S(value='test') + yield RuntimeError('i failed') + + df = as_dataframe(it2()) + # fmt: off + assert_frame_equal( + df, + pd.DataFrame(data={ + 'value': ['test', np.nan ], + 'error': [np.nan, 'RuntimeError: i failed\n'], + 'dt' : [np.nan, np.nan ], + }).astype(dtype={'dt': 'float'}), # FIXME should be datetime64 as below + ) + # fmt: on + + def it3() -> Iterator[Res[S]]: + yield S(value='aba') + yield RuntimeError('whoops') + yield S(value='cde') + yield RuntimeError('exception with datetime', fromisoformat('2024-08-19T22:47:01Z')) + + df = as_dataframe(it3()) + + # fmt: off + assert_frame_equal(df, pd.DataFrame(data={ + 'value': ['aba' , np.nan , 'cde' , np.nan ], + 'error': [np.nan, 'RuntimeError: whoops\n', np.nan, "RuntimeError: ('exception with datetime', datetime.datetime(2024, 8, 19, 22, 47, 1, tzinfo=datetime.timezone.utc))\n"], + # note: dt column is added even if errors don't have an associated datetime + 'dt' : [np.nan, np.nan , np.nan, '2024-08-19 22:47:01+00:00'], + }).astype(dtype={'dt': 'datetime64[ns, UTC]'})) + # fmt: on From d154825591b2b2c074b42852cea9ddd510928fca Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Fri, 23 Aug 2024 00:00:16 +0100 Subject: [PATCH 071/122] my.bluemaestro: make config construction lazy following the discussions here: https://github.com/karlicoss/HPI/issues/46#issuecomment-2295464073 --- my/bluemaestro.py | 51 +++++++++++++++++++++++++++++++------------- tests/bluemaestro.py | 8 ++----- 2 files changed, 38 insertions(+), 21 deletions(-) diff --git a/my/bluemaestro.py b/my/bluemaestro.py index 3e25cae..12c114f 100644 --- a/my/bluemaestro.py +++ b/my/bluemaestro.py @@ -4,36 +4,58 @@ """ # todo most of it belongs to DAL... but considering so few people use it I didn't bother for now +import re +import sqlite3 +from abc import abstractmethod from dataclasses import dataclass from datetime import datetime, timedelta from pathlib import Path -import re -import sqlite3 -from typing import Iterable, Sequence, Set, Optional +from typing import Iterable, Optional, Protocol, Sequence, Set import pytz from my.core import ( + Paths, + Res, + Stats, get_files, make_logger, - Res, stat, - Stats, - influxdb, + unwrap, ) from my.core.cachew import mcachew -from my.core.error import unwrap from my.core.pandas import DataFrameT, as_dataframe from my.core.sqlite import sqlite_connect_immutable -from my.config import bluemaestro as config + +class config(Protocol): + @property + @abstractmethod + def export_path(self) -> Paths: + raise NotImplementedError + + @property + def tz(self) -> pytz.BaseTzInfo: + # fixme: later, rely on the timezone provider + # NOTE: the timezone should be set with respect to the export date!!! + return pytz.timezone('Europe/London') + # TODO when I change tz, check the diff + + +def make_config() -> config: + from my.config import bluemaestro as user_config + + class combined_config(user_config, config): ... + + return combined_config() logger = make_logger(__name__) def inputs() -> Sequence[Path]: - return get_files(config.export_path) + cfg = make_config() + return get_files(cfg.export_path) Celsius = float @@ -50,12 +72,6 @@ class Measurement: dewpoint: Celsius -# fixme: later, rely on the timezone provider -# NOTE: the timezone should be set with respect to the export date!!! -tz = pytz.timezone('Europe/London') -# TODO when I change tz, check the diff - - def is_bad_table(name: str) -> bool: # todo hmm would be nice to have a hook that can patch any module up to delegate = getattr(config, 'is_bad_table', None) @@ -64,6 +80,9 @@ def is_bad_table(name: str) -> bool: @mcachew(depends_on=inputs) def measurements() -> Iterable[Res[Measurement]]: + cfg = make_config() + tz = cfg.tz + # todo ideally this would be via arguments... but needs to be lazy paths = inputs() total = len(paths) @@ -211,6 +230,8 @@ def dataframe() -> DataFrameT: def fill_influxdb() -> None: + from my.core import influxdb + influxdb.fill(measurements(), measurement=__name__) diff --git a/tests/bluemaestro.py b/tests/bluemaestro.py index 84d3eb0..63ce589 100644 --- a/tests/bluemaestro.py +++ b/tests/bluemaestro.py @@ -1,19 +1,15 @@ from pathlib import Path -from typing import TYPE_CHECKING, Iterator, Any +from typing import Iterator from more_itertools import one import pytest -if TYPE_CHECKING: - from my.bluemaestro import Measurement -else: - Measurement = Any +from my.bluemaestro import measurements, Measurement def ok_measurements() -> Iterator[Measurement]: - from my.bluemaestro import measurements for m in measurements(): assert not isinstance(m, Exception) yield m From 5a67f0bafe354514b3490385430a73ad0f55b970 Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Fri, 23 Aug 2024 00:47:00 +0100 Subject: [PATCH 072/122] pdfs: migrate config to Protocol with properties allowes to remove a whole bunch of hacky crap from tests! --- my/pdfs.py | 86 +++++++++++++++++++++++----------------------- my/tests/common.py | 4 +++ tests/pdfs.py | 30 +++++----------- 3 files changed, 56 insertions(+), 64 deletions(-) diff --git a/my/pdfs.py b/my/pdfs.py index 0ab4af3..524c68b 100644 --- a/my/pdfs.py +++ b/my/pdfs.py @@ -1,64 +1,64 @@ ''' PDF documents and annotations on your filesystem ''' + REQUIRES = [ 'git+https://github.com/0xabu/pdfannots', # todo not sure if should use pypi version? ] -from datetime import datetime -from dataclasses import dataclass -import io -from pathlib import Path import time -from typing import NamedTuple, List, Optional, Iterator, Sequence +from datetime import datetime +from pathlib import Path +from typing import Iterator, List, NamedTuple, Optional, Protocol, Sequence +import pdfannots +from more_itertools import bucket -from my.core import LazyLogger, get_files, Paths, PathIsh +from my.core import PathIsh, Paths, Stats, get_files, make_logger, stat from my.core.cachew import mcachew -from my.core.cfg import Attrs, make_config from my.core.error import Res, split_errors -from more_itertools import bucket -import pdfannots - - -from my.config import pdfs as user_config - -@dataclass -class pdfs(user_config): - paths: Paths = () # allowed to be empty for 'filelist' logic +class config(Protocol): + @property + def paths(self) -> Paths: + return () # allowed to be empty for 'filelist' logic def is_ignored(self, p: Path) -> bool: """ - Used to ignore some extremely heavy files - is_ignored function taken either from config, - or if not defined, it's a function that returns False + You can override this in user config if you want to ignore some files that are tooheavy """ - user_ignore = getattr(user_config, 'is_ignored', None) - if user_ignore is not None: - return user_ignore(p) - return False - @staticmethod - def _migration(attrs: Attrs) -> Attrs: - roots = 'roots' - if roots in attrs: # legacy name - attrs['paths'] = attrs[roots] - from my.core.warnings import high - high(f'"{roots}" is deprecated! Use "paths" instead.') - return attrs + +def make_config() -> config: + from my.config import pdfs as user_config + + class migration: + @property + def paths(self) -> Paths: + roots = getattr(user_config, 'roots', None) + if roots is not None: + from my.core.warnings import high + + high('"roots" is deprecated! Use "paths" instead.') + return roots + else: + return () + + class combined_config(user_config, migration, config): ... + + return combined_config() -config = make_config(pdfs, migration=pdfs._migration) +logger = make_logger(__name__) -logger = LazyLogger(__name__) def inputs() -> Sequence[Path]: - all_files = get_files(config.paths, glob='**/*.pdf') - return [p for p in all_files if not config.is_ignored(p)] + cfg = make_config() + all_files = get_files(cfg.paths, glob='**/*.pdf') + return [p for p in all_files if not cfg.is_ignored(p)] # TODO canonical names/fingerprinting? @@ -121,14 +121,13 @@ def _iter_annotations(pdfs: Sequence[Path]) -> Iterator[Res[Annotation]]: # todo how to print to stdout synchronously? # todo global config option not to use pools? useful for debugging.. from concurrent.futures import ProcessPoolExecutor + from my.core.utils.concurrent import DummyExecutor + workers = None # use 0 for debugging Pool = DummyExecutor if workers == 0 else ProcessPoolExecutor with Pool(workers) as pool: - futures = [ - pool.submit(get_annots, pdf) - for pdf in pdfs - ] + futures = [pool.submit(get_annots, pdf) for pdf in pdfs] for f, pdf in zip(futures, pdfs): try: yield from f.result() @@ -161,11 +160,13 @@ class Pdf(NamedTuple): return self.created -def annotated_pdfs(*, filelist: Optional[Sequence[PathIsh]]=None) -> Iterator[Res[Pdf]]: +def annotated_pdfs(*, filelist: Optional[Sequence[PathIsh]] = None) -> Iterator[Res[Pdf]]: if filelist is not None: # hacky... keeping it backwards compatible # https://github.com/karlicoss/HPI/pull/74 - config.paths = filelist + from my.config import pdfs as user_config + + user_config.paths = filelist ait = annotations() vit, eit = split_errors(ait, ET=Exception) @@ -176,10 +177,9 @@ def annotated_pdfs(*, filelist: Optional[Sequence[PathIsh]]=None) -> Iterator[Re yield from eit -from my.core import stat, Stats def stats() -> Stats: return { - **stat(annotations) , + **stat(annotations), **stat(annotated_pdfs), } diff --git a/my/tests/common.py b/my/tests/common.py index e3060e1..f8b645d 100644 --- a/my/tests/common.py +++ b/my/tests/common.py @@ -20,6 +20,10 @@ def reset_modules() -> None: ''' to_unload = [m for m in sys.modules if re.match(r'my[.]?', m)] for m in to_unload: + if 'my.pdfs' in m: + # temporary hack -- since my.pdfs migrated to a 'lazy' config, this isn't necessary anymore + # but if we reset module anyway, it confuses the ProcessPool inside my.pdfs + continue del sys.modules[m] diff --git a/tests/pdfs.py b/tests/pdfs.py index 63b1319..6db669f 100644 --- a/tests/pdfs.py +++ b/tests/pdfs.py @@ -1,17 +1,16 @@ +import inspect from pathlib import Path +import pytest from more_itertools import ilen -import pytest - +from my.core.cfg import tmp_config from my.tests.common import testdata +from my.pdfs import annotated_pdfs, annotations, get_annots + def test_module(with_config) -> None: - # TODO crap. if module is imported too early (on the top level, it makes it super hard to override config) - # need to at least detect it... - from my.pdfs import annotations, annotated_pdfs - # todo check types etc as well assert ilen(annotations()) >= 3 assert ilen(annotated_pdfs()) >= 1 @@ -22,12 +21,13 @@ def test_with_error(with_config, tmp_path: Path) -> None: root = tmp_path g = root / 'garbage.pdf' g.write_text('garbage') + from my.config import pdfs + # meh. otherwise legacy config value 'wins' del pdfs.roots # type: ignore[attr-defined] pdfs.paths = (root,) - from my.pdfs import annotations annots = list(annotations()) [annot] = annots assert isinstance(annot, Exception) @@ -35,9 +35,6 @@ def test_with_error(with_config, tmp_path: Path) -> None: @pytest.fixture def with_config(): - from my.tests.common import reset_modules - reset_modules() # todo ugh.. getting boilerplaty.. need to make it a bit more automatic.. - # extra_data = Path(__file__).absolute().parent / 'extra/data/polar' # assert extra_data.exists(), extra_data # todo hmm, turned out no annotations in these ones.. whatever @@ -47,13 +44,9 @@ def with_config(): testdata(), ] - import my.core.cfg as C - with C.tmp_config() as config: + with tmp_config() as config: config.pdfs = user_config - try: - yield - finally: - reset_modules() + yield EXPECTED_HIGHLIGHTS = { @@ -68,8 +61,6 @@ def test_get_annots() -> None: Test get_annots, with a real PDF file get_annots should return a list of three Annotation objects """ - from my.pdfs import get_annots - annotations = get_annots(testdata() / 'pdfs' / 'Information Architecture for the World Wide Web.pdf') assert len(annotations) == 3 assert set([a.highlight for a in annotations]) == EXPECTED_HIGHLIGHTS @@ -80,12 +71,9 @@ def test_annotated_pdfs_with_filelist() -> None: Test annotated_pdfs, with a real PDF file annotated_pdfs should return a list of one Pdf object, with three Annotations """ - from my.pdfs import annotated_pdfs - filelist = [testdata() / 'pdfs' / 'Information Architecture for the World Wide Web.pdf'] annotations_generator = annotated_pdfs(filelist=filelist) - import inspect assert inspect.isgeneratorfunction(annotated_pdfs) highlights_from_pdfs = [] From 1215181af533ba49bbb7658de66b259333e90310 Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Sun, 25 Aug 2024 16:36:34 +0100 Subject: [PATCH 073/122] core: move stuff from tests/demo.py to my/core/tests/test_config.py also clean all this up a bit --- my/core/__init__.py | 4 +- my/core/tests/test_config.py | 132 +++++++++++++++++++++++++++++++++++ my/demo.py | 53 ++++++++------ tests/demo.py | 118 ------------------------------- 4 files changed, 164 insertions(+), 143 deletions(-) create mode 100644 my/core/tests/test_config.py delete mode 100644 tests/demo.py diff --git a/my/core/__init__.py b/my/core/__init__.py index 19be7fe..ba633f6 100644 --- a/my/core/__init__.py +++ b/my/core/__init__.py @@ -4,7 +4,7 @@ from typing import TYPE_CHECKING from .cfg import make_config from .common import PathIsh, Paths, get_files from .compat import assert_never -from .error import Res, unwrap +from .error import Res, unwrap, notnone from .logging import ( make_logger, ) @@ -42,7 +42,7 @@ __all__ = [ '__NOT_HPI_MODULE__', - 'Res', 'unwrap', + 'Res', 'unwrap', 'notnone', 'dataclass', 'Path', ] diff --git a/my/core/tests/test_config.py b/my/core/tests/test_config.py new file mode 100644 index 0000000..c76f5d9 --- /dev/null +++ b/my/core/tests/test_config.py @@ -0,0 +1,132 @@ +""" +Various tests that are checking behaviour of user config wrt to various things +""" + +import sys +from pathlib import Path + +import pytest +import pytz +from more_itertools import ilen + +import my.config +from my.core import notnone +from my.demo import items, make_config + + +# run the same test multiple times to make sure there are not issues with import order etc +@pytest.mark.parametrize('run_id', ['1', '2']) +def test_override_config(tmp_path: Path, run_id: str) -> None: + class user_config: + username = f'user_{run_id}' + data_path = f'{tmp_path}/*.json' + + my.config.demo = user_config # type: ignore[misc, assignment] + + [item1, item2] = items() + assert item1.username == f'user_{run_id}' + assert item2.username == f'user_{run_id}' + + +@pytest.mark.skip(reason="won't work at the moment because of inheritance") +def test_dynamic_config_simplenamespace(tmp_path: Path) -> None: + from types import SimpleNamespace + + user_config = SimpleNamespace( + username='user3', + data_path=f'{tmp_path}/*.json', + ) + my.config.demo = user_config # type: ignore[misc, assignment] + + cfg = make_config() + + assert cfg.username == 'user3' + + +def test_mixin_attribute_handling(tmp_path: Path) -> None: + """ + Tests that arbitrary mixin attributes work with our config handling pattern + """ + + nytz = pytz.timezone('America/New_York') + + class user_config: + # check that override is taken into the account + timezone = nytz + + irrelevant = 'hello' + + username = 'UUU' + data_path = f'{tmp_path}/*.json' + + my.config.demo = user_config # type: ignore[misc, assignment] + + cfg = make_config() + + assert cfg.username == 'UUU' + + # mypy doesn't know about it, but the attribute is there + assert getattr(cfg, 'irrelevant') == 'hello' + + # check that overridden default attribute is actually getting overridden + assert cfg.timezone == nytz + + [item1, item2] = items() + assert item1.username == 'UUU' + assert notnone(item1.dt.tzinfo).zone == nytz.zone # type: ignore[attr-defined] + assert item2.username == 'UUU' + assert notnone(item2.dt.tzinfo).zone == nytz.zone # type: ignore[attr-defined] + + +# use multiple identical tests to make sure there are no issues with cached imports etc +@pytest.mark.parametrize('run_id', ['1', '2']) +def test_dynamic_module_import(tmp_path: Path, run_id: str) -> None: + """ + Test for dynamic hackery in config properties + e.g. importing some external modules + """ + + ext = tmp_path / 'external' + ext.mkdir() + (ext / '__init__.py').write_text( + ''' +def transform(x): + from .submodule import do_transform + return do_transform(x) + +''' + ) + (ext / 'submodule.py').write_text( + f''' +def do_transform(x): + return {{"total_{run_id}": sum(x.values())}} +''' + ) + + class user_config: + username = 'someuser' + data_path = f'{tmp_path}/*.json' + external = f'{ext}' + + my.config.demo = user_config # type: ignore[misc, assignment] + + [item1, item2] = items() + assert item1.raw == {f'total_{run_id}': 1 + 123}, item1 + assert item2.raw == {f'total_{run_id}': 2 + 456}, item2 + + # need to reset these modules, otherwise they get cached + # kind of relevant to my.core.cfg.tmp_config + sys.modules.pop('external', None) + sys.modules.pop('external.submodule', None) + + +@pytest.fixture(autouse=True) +def prepare_data(tmp_path: Path): + (tmp_path / 'data.json').write_text( + ''' +[ + {"key": 1, "value": 123}, + {"key": 2, "value": 456} +] +''' + ) diff --git a/my/demo.py b/my/demo.py index 645be4f..e27b5dd 100644 --- a/my/demo.py +++ b/my/demo.py @@ -2,19 +2,23 @@ Just a demo module for testing and documentation purposes ''' -from .core import Paths, PathIsh - -from typing import Optional -from datetime import tzinfo, timezone - -from my.config import demo as user_config +import json +from abc import abstractmethod from dataclasses import dataclass +from datetime import datetime, timezone, tzinfo +from pathlib import Path +from typing import Iterable, Optional, Protocol, Sequence + +from my.core import Json, PathIsh, Paths, get_files -@dataclass -class demo(user_config): +class config(Protocol): data_path: Paths + + # this is to check required attribute handling username: str + + # this is to check optional attribute handling timezone: tzinfo = timezone.utc external: Optional[PathIsh] = None @@ -23,47 +27,50 @@ class demo(user_config): def external_module(self): rpath = self.external if rpath is not None: - from .core.utils.imports import import_dir + from my.core.utils.imports import import_dir + return import_dir(rpath) - import my.config.repos.external as m # type: ignore + import my.config.repos.external as m # type: ignore + return m -from .core import make_config -config = make_config(demo) +def make_config() -> config: + from my.config import demo as user_config -# TODO not sure about type checking? -external = config.external_module + class combined_config(user_config, config): ... + return combined_config() -from pathlib import Path -from typing import Sequence, Iterable -from datetime import datetime -from .core import Json, get_files @dataclass class Item: ''' Some completely arbitrary artificial stuff, just for testing ''' + username: str raw: Json dt: datetime def inputs() -> Sequence[Path]: - return get_files(config.data_path) + cfg = make_config() + return get_files(cfg.data_path) -import json def items() -> Iterable[Item]: + cfg = make_config() + + transform = (lambda i: i) if cfg.external is None else cfg.external_module.transform + for f in inputs(): - dt = datetime.fromtimestamp(f.stat().st_mtime, tz=config.timezone) + dt = datetime.fromtimestamp(f.stat().st_mtime, tz=cfg.timezone) j = json.loads(f.read_text()) for raw in j: yield Item( - username=config.username, - raw=external.identity(raw), + username=cfg.username, + raw=transform(raw), dt=dt, ) diff --git a/tests/demo.py b/tests/demo.py deleted file mode 100644 index 73a6c65..0000000 --- a/tests/demo.py +++ /dev/null @@ -1,118 +0,0 @@ -import sys -from pathlib import Path -from more_itertools import ilen - -# TODO NOTE: this wouldn't work because of an early my.config.demo import -# from my.demo import items - -def test_dynamic_config_1(tmp_path: Path) -> None: - import my.config - - class user_config: - username = 'user' - data_path = f'{tmp_path}/*.json' - external = f'{tmp_path}/external' - my.config.demo = user_config # type: ignore[misc, assignment] - - from my.demo import items - [item1, item2] = items() - assert item1.username == 'user' - - -# exactly the same test, but using a different config, to test out the behaviour w.r.t. import order -def test_dynamic_config_2(tmp_path: Path) -> None: - # doesn't work without it! - # because the config from test_dybamic_config_1 is cached in my.demo.demo - del sys.modules['my.demo'] - - import my.config - - class user_config: - username = 'user2' - data_path = f'{tmp_path}/*.json' - external = f'{tmp_path}/external' - my.config.demo = user_config # type: ignore[misc, assignment] - - from my.demo import items - [item1, item2] = items() - assert item1.username == 'user2' - - -import pytest - -@pytest.mark.skip(reason="won't work at the moment because of inheritance") -def test_dynamic_config_simplenamespace(tmp_path: Path) -> None: - # doesn't work without it! - # because the config from test_dybamic_config_1 is cached in my.demo.demo - del sys.modules['my.demo'] - - import my.config - from types import SimpleNamespace - - user_config = SimpleNamespace( - username='user3', - data_path=f'{tmp_path}/*.json', - ) - my.config.demo = user_config # type: ignore[misc, assignment] - - from my.demo import config - assert config.username == 'user3' - - -# make sure our config handling pattern does it as expected -def test_attribute_handling(tmp_path: Path) -> None: - # doesn't work without it! - # because the config from test_dybamic_config_1 is cached in my.demo.demo - del sys.modules['my.demo'] - - import pytz - nytz = pytz.timezone('America/New_York') - - import my.config - class user_config: - # check that override is taken into the account - timezone = nytz - - irrelevant = 'hello' - - username = 'UUU' - data_path = f'{tmp_path}/*.json' - external = f'{tmp_path}/external' - - - my.config.demo = user_config # type: ignore[misc, assignment] - - from my.demo import config - - assert config.username == 'UUU' - - # mypy doesn't know about it, but the attribute is there - assert getattr(config, 'irrelevant') == 'hello' - - # check that overridden default attribute is actually getting overridden - assert config.timezone == nytz - - - -@pytest.fixture(autouse=True) -def prepare(tmp_path: Path): - (tmp_path / 'data.json').write_text(''' -[ - {"key1": 1}, - {"key2": 2} -] -''') - ext = tmp_path / 'external' - ext.mkdir() - (ext / '__init__.py').write_text(''' -def identity(x): - from .submodule import hello - hello(x) - return x - -''') - (ext / 'submodule.py').write_text('hello = lambda x: print("hello " + str(x))') - yield - ex = 'my.config.repos.external' - if ex in sys.modules: - del sys.modules[ex] From 2ff2dcfc003d2ff0e0440d91b2778eee3c2e851c Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Sun, 25 Aug 2024 18:51:34 +0100 Subject: [PATCH 074/122] tests: move test checkign for my_config handling to core/tests/test_config.py allows to remove the hacky reset_modules thing from setup fixture --- my/core/tests/test_config.py | 47 ++++++++++++++++++++++++++++++++++++ tests/config.py | 41 ++----------------------------- 2 files changed, 49 insertions(+), 39 deletions(-) diff --git a/my/core/tests/test_config.py b/my/core/tests/test_config.py index c76f5d9..a318a95 100644 --- a/my/core/tests/test_config.py +++ b/my/core/tests/test_config.py @@ -3,6 +3,7 @@ Various tests that are checking behaviour of user config wrt to various things """ import sys +import os from pathlib import Path import pytest @@ -13,6 +14,10 @@ import my.config from my.core import notnone from my.demo import items, make_config +from .common import tmp_environ_set + +# TODO would be nice to randomize test order here to catch various config issues + # run the same test multiple times to make sure there are not issues with import order etc @pytest.mark.parametrize('run_id', ['1', '2']) @@ -120,6 +125,48 @@ def do_transform(x): sys.modules.pop('external.submodule', None) +@pytest.mark.parametrize('run_id', ['1', '2']) +def test_my_config_env_variable(tmp_path: Path, run_id: str) -> None: + """ + Tests handling of MY_CONFIG variable + """ + + # ugh. so by this point, my.config is already loaded (default stub), so we need to unload it + sys.modules.pop('my.config', None) + # but my.config itself relies on my.core.init hook, so unless it's reloaded too it wouldn't help + sys.modules.pop('my.core', None) + sys.modules.pop('my.core.init', None) + # it's a bit of a mouthful of course, but in most cases MY_CONFIG would be set once + # , and before hpi runs, so hopefully it's not a huge deal + cfg_dir = tmp_path / 'my' + cfg_file = cfg_dir / 'config.py' + cfg_dir.mkdir() + + cfg_file.write_text( + f''' +# print("IMPORTING CONFIG {run_id}") +class demo: + username = 'xxx_{run_id}' + data_path = r'{tmp_path}{os.sep}*.json' # need raw string for windows... +''' + ) + + with tmp_environ_set('MY_CONFIG', str(tmp_path)): + [item1, item2] = items() + assert item1.username == f'xxx_{run_id}' + assert item2.username == f'xxx_{run_id}' + + # sigh.. so this is cached in sys.path + # so it takes precedence later during next import, not giving the MY_CONFIG hook + # (imported from builtin my.config) to kick in + sys.path.remove(str(tmp_path)) + + # FIXME ideally this shouldn't be necessary? + # remove this after we fixup my.tests.reddit and my.tests.commits + # (they were failing ci when running all tests) + sys.modules.pop('my.config', None) + + @pytest.fixture(autouse=True) def prepare_data(tmp_path: Path): (tmp_path / 'data.json').write_text( diff --git a/tests/config.py b/tests/config.py index 101f7df..acfe1f1 100644 --- a/tests/config.py +++ b/tests/config.py @@ -1,6 +1,7 @@ from pathlib import Path +# TODO move this somewhere else -- there are more specific tests covering this now def test_dynamic_configuration(notes: Path) -> None: import pytz from types import SimpleNamespace as NS @@ -26,42 +27,11 @@ def test_dynamic_configuration(notes: Path) -> None: import pytest -def test_environment_variable(tmp_path: Path) -> None: - cfg_dir = tmp_path / 'my' - cfg_file = cfg_dir / 'config.py' - cfg_dir.mkdir() - cfg_file.write_text(''' -class feedly: - pass -class just_for_test: - pass -''') - - import os - oenv = dict(os.environ) - try: - os.environ['MY_CONFIG'] = str(tmp_path) - # should not raise at least - import my.rss.feedly - - import my.config as c - assert hasattr(c, 'just_for_test') - finally: - os.environ.clear() - os.environ.update(oenv) - - import sys - # TODO wtf??? doesn't work without unlink... is it caching something? - cfg_file.unlink() - del sys.modules['my.config'] # meh.. - - import my.config as c - assert not hasattr(c, 'just_for_test') - from dataclasses import dataclass +# TODO this test should probs be deprecated? it's more of a documentation? def test_user_config() -> None: from my.core.common import classproperty class user_config: @@ -117,10 +87,3 @@ Some misc stuff yield ndir finally: pass - - -@pytest.fixture(autouse=True) -def prepare(): - from my.tests.common import reset_modules - reset_modules() - yield From 7cae9d5bf367f0c5d2a1cc158cb5782a523666b1 Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Sun, 25 Aug 2024 22:36:54 +0100 Subject: [PATCH 075/122] my.google.takeout.paths: migrate to new style lazy config also clean up tests a little and move into my.tests.location.google --- my/google/takeout/paths.py | 45 ++++++++++++++++++------------ my/tests/common.py | 4 +++ my/tests/location/google.py | 55 +++++++++++++++++++++++++++++++++++++ tests/location.py | 28 ------------------- 4 files changed, 86 insertions(+), 46 deletions(-) create mode 100644 my/tests/location/google.py delete mode 100644 tests/location.py diff --git a/my/google/takeout/paths.py b/my/google/takeout/paths.py index 5b53149..948cf2e 100644 --- a/my/google/takeout/paths.py +++ b/my/google/takeout/paths.py @@ -2,44 +2,53 @@ Module for locating and accessing [[https://takeout.google.com][Google Takeout]] data ''' -from dataclasses import dataclass -from ...core.common import Paths, get_files -from ...core.util import __NOT_HPI_MODULE__ - -from my.config import google as user_config +from abc import abstractmethod +from pathlib import Path +from typing import Iterable, Optional, Protocol from more_itertools import last -@dataclass -class google(user_config): - takeout_path: Paths # path/paths/glob for the takeout zips -### +from my.core import __NOT_HPI_MODULE__, Paths, get_files + + +class config: + """ + path/paths/glob for the takeout zips + """ + + @property + @abstractmethod + def takeout_path(self) -> Paths: + raise NotImplementedError + # TODO rename 'google' to 'takeout'? not sure -from ...core.cfg import make_config -config = make_config(google) -from pathlib import Path -from typing import Optional, Iterable +def make_config() -> config: + from my.config import google as user_config + + class combined_config(user_config, config): ... + + return combined_config() -def get_takeouts(*, path: Optional[str]=None) -> Iterable[Path]: +def get_takeouts(*, path: Optional[str] = None) -> Iterable[Path]: """ Sometimes google splits takeout into multiple archives, so we need to detect the ones that contain the path we need """ - # TODO FIXME zip is not great.. + # TODO zip is not great.. # allow a lambda expression? that way the user could restrict it - for takeout in get_files(config.takeout_path, glob='*.zip'): + cfg = make_config() + for takeout in get_files(cfg.takeout_path, glob='*.zip'): if path is None or (takeout / path).exists(): yield takeout -def get_last_takeout(*, path: Optional[str]=None) -> Optional[Path]: +def get_last_takeout(*, path: Optional[str] = None) -> Optional[Path]: return last(get_takeouts(path=path), default=None) # TODO might be a good idea to merge across multiple takeouts... # perhaps even a special takeout module that deals with all of this automatically? # e.g. accumulate, filter and maybe report useless takeouts? - diff --git a/my/tests/common.py b/my/tests/common.py index f8b645d..962ee46 100644 --- a/my/tests/common.py +++ b/my/tests/common.py @@ -31,3 +31,7 @@ def testdata() -> Path: d = Path(__file__).absolute().parent.parent.parent / 'testdata' assert d.exists(), d return d + + +# prevent pytest from treating this as test +testdata.__test__ = False # type: ignore[attr-defined] diff --git a/my/tests/location/google.py b/my/tests/location/google.py new file mode 100644 index 0000000..612522b --- /dev/null +++ b/my/tests/location/google.py @@ -0,0 +1,55 @@ +""" +Tests for LEGACY location provider + +Keeping for now for backwards compatibility +""" + +from pathlib import Path + +import pytest +from more_itertools import one + +from my.core.cfg import tmp_config +from my.location.google import locations + + +def test_google_locations() -> None: + locs = list(locations()) + assert len(locs) == 3810, len(locs) + + last = locs[-1] + assert last.dt.strftime('%Y%m%d %H:%M:%S') == '20170802 13:01:56' # should be utc + # todo approx + assert last.lat == 46.5515350 + assert last.lon == 16.4742742 + # todo check altitude + + +@pytest.fixture(autouse=True) +def prepare(tmp_path: Path): + + # TODO could just pick a part of shared config? not sure + _takeout_path = _prepare_takeouts_dir(tmp_path) + + class google: + takeout_path = _takeout_path + + with tmp_config() as config: + config.google = google + yield + + +def _prepare_takeouts_dir(tmp_path: Path) -> Path: + from ..common import testdata + + try: + track = one(testdata().rglob('italy-slovenia-2017-07-29.json')) + except ValueError: + raise RuntimeError('testdata not found, setup git submodules?') + + # todo ugh. unnecessary zipping, but at the moment takeout provider doesn't support plain dirs + import zipfile + + with zipfile.ZipFile(tmp_path / 'takeout.zip', 'w') as zf: + zf.writestr('Takeout/Location History/Location History.json', track.read_bytes()) + return tmp_path diff --git a/tests/location.py b/tests/location.py deleted file mode 100644 index 2597d5e..0000000 --- a/tests/location.py +++ /dev/null @@ -1,28 +0,0 @@ -from pathlib import Path - -import pytest - - -def test() -> None: - from my.location.google import locations - locs = list(locations()) - assert len(locs) == 3810 - - last = locs[-1] - assert last.dt.strftime('%Y%m%d %H:%M:%S') == '20170802 13:01:56' # should be utc - # todo approx - assert last.lat == 46.5515350 - assert last.lon == 16.4742742 - # todo check altitude - - -@pytest.fixture(autouse=True) -def prepare(tmp_path: Path): - from .shared_config import temp_config - user_config = temp_config(tmp_path) - - import my.core.cfg as C - with C.tmp_config() as config: - config.google = user_config.google - yield - From 094519acafc681d15a0e395e1dbe9b62641846ce Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Sun, 25 Aug 2024 23:06:26 +0100 Subject: [PATCH 076/122] tests: disable cachew in my.tests subpackage --- my/tests/conftest.py | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 my/tests/conftest.py diff --git a/my/tests/conftest.py b/my/tests/conftest.py new file mode 100644 index 0000000..4e67f71 --- /dev/null +++ b/my/tests/conftest.py @@ -0,0 +1,8 @@ +import pytest + +# I guess makes sense by default +@pytest.fixture(autouse=True) +def without_cachew(): + from my.core.cachew import disabled_cachew + with disabled_cachew(): + yield From 270080bd562aec0489a9b3573e00882756736342 Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Mon, 26 Aug 2024 00:08:09 +0100 Subject: [PATCH 077/122] core.error: better defensive handling for my.core.source when parts of config are missing --- my/core/error.py | 27 +++++++++++++++++++++++---- my/core/source.py | 2 +- 2 files changed, 24 insertions(+), 5 deletions(-) diff --git a/my/core/error.py b/my/core/error.py index c4dff07..7489f69 100644 --- a/my/core/error.py +++ b/my/core/error.py @@ -201,7 +201,12 @@ def error_to_json(e: Exception) -> Json: MODULE_SETUP_URL = 'https://github.com/karlicoss/HPI/blob/master/doc/SETUP.org#private-configuration-myconfig' -def warn_my_config_import_error(err: Union[ImportError, AttributeError], help_url: Optional[str] = None) -> bool: +def warn_my_config_import_error( + err: Union[ImportError, AttributeError], + *, + help_url: Optional[str] = None, + module_name: Optional[str] = None, +) -> bool: """ If the user tried to import something from my.config but it failed, possibly due to missing the config block in my.config? @@ -233,10 +238,24 @@ See {help_url}\ config_obj = cast(object, getattr(err, 'obj')) # the object that caused the attribute error # e.g. active_browser for my.browser nested_block_name = err.name - if config_obj.__module__ == 'my.config': - click.secho(f"""You're likely missing the nested config block for '{getattr(config_obj, '__name__', str(config_obj))}.{nested_block_name}'. + errmsg = f"""You're likely missing the nested config block for '{getattr(config_obj, '__name__', str(config_obj))}.{nested_block_name}'. See {help_url} or check the corresponding module.py file for an example\ -""", fg='yellow', err=True) +""" + if config_obj.__module__ == 'my.config': + click.secho(errmsg, fg='yellow', err=True) + return True + if module_name is not None and nested_block_name == module_name.split('.')[-1]: + # this tries to cover cases like these + # user config: + # class location: + # class via_ip: + # accuracy = 10_000 + # then when we import it, we do something like + # from my.config import location + # user_config = location.via_ip + # so if location is present, but via_ip is not, we get + # AttributeError: type object 'location' has no attribute 'via_ip' + click.secho(errmsg, fg='yellow', err=True) return True else: click.echo(f"Unexpected error... {err}", err=True) diff --git a/my/core/source.py b/my/core/source.py index 9488ae2..6e0a78a 100644 --- a/my/core/source.py +++ b/my/core/source.py @@ -65,7 +65,7 @@ class core: """) # try to check if this is a config error or based on dependencies not being installed if isinstance(err, (ImportError, AttributeError)): - matched_config_err = warn_my_config_import_error(err, help_url=help_url) + matched_config_err = warn_my_config_import_error(err, module_name=module_name, help_url=help_url) # if we determined this wasn't a config error, and it was an attribute error # it could be *any* attribute error -- we should raise this since its otherwise a fatal error # from some code in the module failing From a5643206a0dc2735bc383ef700afd71439d8b192 Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Mon, 26 Aug 2024 02:00:51 +0100 Subject: [PATCH 078/122] general: make time.tz.via_location user config lazy, move tests to my.tests package also gets rid of the problematic reset_modules thingie --- my/calendar/holidays.py | 2 +- my/core/compat.py | 2 + my/location/fallback/via_ip.py | 4 +- my/tests/calendar.py | 9 ++ my/tests/common.py | 16 --- my/tests/conftest.py | 2 + .../tests/location/fallback.py | 54 +++++---- .../tests/shared_tz_config.py | 75 ++++++------ my/tests/tz.py | 107 ++++++++++++++++++ my/time/tz/via_location.py | 107 ++++++++++++------ tests/calendar.py | 19 ---- tests/orgmode.py | 7 +- tests/takeout.py | 2 +- tests/tz.py | 95 ---------------- tox.ini | 1 - 15 files changed, 269 insertions(+), 233 deletions(-) create mode 100644 my/tests/calendar.py rename tests/location_fallback.py => my/tests/location/fallback.py (86%) rename tests/shared_config.py => my/tests/shared_tz_config.py (55%) create mode 100644 my/tests/tz.py delete mode 100644 tests/calendar.py delete mode 100644 tests/tz.py diff --git a/my/calendar/holidays.py b/my/calendar/holidays.py index f73bf70..af51696 100644 --- a/my/calendar/holidays.py +++ b/my/calendar/holidays.py @@ -19,7 +19,7 @@ def _calendar(): # todo switch to using time.tz.main once _get_tz stabilizes? from ..time.tz import via_location as LTZ # TODO would be nice to do it dynamically depending on the past timezones... - tz = LTZ._get_tz(datetime.now()) + tz = LTZ.get_tz(datetime.now()) assert tz is not None zone = tz.zone; assert zone is not None code = zone_to_countrycode(zone) diff --git a/my/core/compat.py b/my/core/compat.py index 4372a01..eccaf07 100644 --- a/my/core/compat.py +++ b/my/core/compat.py @@ -125,8 +125,10 @@ def test_fromisoformat() -> None: if sys.version_info[:2] >= (3, 10): from types import NoneType + from typing import TypeAlias else: NoneType = type(None) + from typing_extensions import TypeAlias if sys.version_info[:2] >= (3, 11): diff --git a/my/location/fallback/via_ip.py b/my/location/fallback/via_ip.py index db03c7c..79a452c 100644 --- a/my/location/fallback/via_ip.py +++ b/my/location/fallback/via_ip.py @@ -29,7 +29,6 @@ from typing import Iterator, List from my.core import make_logger from my.core.compat import bisect_left -from my.ip.all import ips from my.location.common import Location from my.location.fallback.common import FallbackLocation, DateExact, _datetime_timestamp @@ -37,6 +36,9 @@ logger = make_logger(__name__, level="warning") def fallback_locations() -> Iterator[FallbackLocation]: + # prefer late import since ips get overridden in tests + from my.ip.all import ips + dur = config.for_duration.total_seconds() for ip in ips(): lat, lon = ip.latlon diff --git a/my/tests/calendar.py b/my/tests/calendar.py new file mode 100644 index 0000000..b5f856c --- /dev/null +++ b/my/tests/calendar.py @@ -0,0 +1,9 @@ +from my.calendar.holidays import is_holiday + +from .shared_tz_config import config # autoused fixture + + +def test_is_holiday() -> None: + assert is_holiday('20190101') + assert not is_holiday('20180601') + assert is_holiday('20200906') # national holiday in Bulgaria diff --git a/my/tests/common.py b/my/tests/common.py index 962ee46..cf5c632 100644 --- a/my/tests/common.py +++ b/my/tests/common.py @@ -1,7 +1,5 @@ import os from pathlib import Path -import re -import sys import pytest @@ -13,20 +11,6 @@ skip_if_not_karlicoss = pytest.mark.skipif( ) -def reset_modules() -> None: - ''' - A hack to 'unload' HPI modules, otherwise some modules might cache the config - TODO: a bit crap, need a better way.. - ''' - to_unload = [m for m in sys.modules if re.match(r'my[.]?', m)] - for m in to_unload: - if 'my.pdfs' in m: - # temporary hack -- since my.pdfs migrated to a 'lazy' config, this isn't necessary anymore - # but if we reset module anyway, it confuses the ProcessPool inside my.pdfs - continue - del sys.modules[m] - - def testdata() -> Path: d = Path(__file__).absolute().parent.parent.parent / 'testdata' assert d.exists(), d diff --git a/my/tests/conftest.py b/my/tests/conftest.py index 4e67f71..cc7bb7e 100644 --- a/my/tests/conftest.py +++ b/my/tests/conftest.py @@ -1,8 +1,10 @@ import pytest + # I guess makes sense by default @pytest.fixture(autouse=True) def without_cachew(): from my.core.cachew import disabled_cachew + with disabled_cachew(): yield diff --git a/tests/location_fallback.py b/my/tests/location/fallback.py similarity index 86% rename from tests/location_fallback.py rename to my/tests/location/fallback.py index aad33ee..10a4e5b 100644 --- a/tests/location_fallback.py +++ b/my/tests/location/fallback.py @@ -2,32 +2,23 @@ To test my.location.fallback_location.all """ +from datetime import datetime, timedelta, timezone from typing import Iterator -from datetime import datetime, timezone, timedelta +import pytest from more_itertools import ilen -from my.ip.common import IP - -def data() -> Iterator[IP]: - # random IP addresses - yield IP(addr="67.98.113.0", dt=datetime(2020, 1, 1, 12, 0, 0, tzinfo=timezone.utc)) - yield IP(addr="67.98.112.0", dt=datetime(2020, 1, 15, 12, 0, 0, tzinfo=timezone.utc)) - yield IP(addr="59.40.113.87", dt=datetime(2020, 2, 1, 12, 0, 0, tzinfo=timezone.utc)) - yield IP(addr="59.40.139.87", dt=datetime(2020, 2, 1, 16, 0, 0, tzinfo=timezone.utc)) - yield IP(addr="161.235.192.228", dt=datetime(2020, 3, 1, 12, 0, 0, tzinfo=timezone.utc)) - -# redefine the my.ip.all function using data for testing import my.ip.all as ip_module -ip_module.ips = data - +from my.ip.common import IP from my.location.fallback import via_ip +from ..shared_tz_config import config # autoused fixture + + # these are all tests for the bisect algorithm defined in via_ip.py # to make sure we can correctly find IPs that are within the 'for_duration' of a given datetime - def test_ip_fallback() -> None: - # make sure that the data override works + # precondition, make sure that the data override works assert ilen(ip_module.ips()) == ilen(data()) assert ilen(ip_module.ips()) == ilen(via_ip.fallback_locations()) assert ilen(via_ip.fallback_locations()) == 5 @@ -47,7 +38,9 @@ def test_ip_fallback() -> None: assert len(est) == 1 # right after the 'for_duration' for an IP - est = list(via_ip.estimate_location(datetime(2020, 1, 1, 12, 0, 0, tzinfo=timezone.utc) + via_ip.config.for_duration + timedelta(seconds=1))) + est = list( + via_ip.estimate_location(datetime(2020, 1, 1, 12, 0, 0, tzinfo=timezone.utc) + via_ip.config.for_duration + timedelta(seconds=1)) + ) assert len(est) == 0 # on 2/1/2020, threes one IP if before 16:30 @@ -75,8 +68,8 @@ def test_ip_fallback() -> None: # # redefine fallback_estimators to prevent possible namespace packages the user # may have installed from having side effects testing this - from my.location.fallback import all - from my.location.fallback import via_home + from my.location.fallback import all, via_home + def _fe() -> Iterator[all.LocationEstimator]: yield via_ip.estimate_location yield via_home.estimate_location @@ -88,6 +81,7 @@ def test_ip_fallback() -> None: # # just passing via_ip should give one IP from my.location.fallback.common import _iter_estimate_from + raw_est = list(_iter_estimate_from(use_dt, (via_ip.estimate_location,))) assert len(raw_est) == 1 assert raw_est[0].datasource == "via_ip" @@ -110,7 +104,7 @@ def test_ip_fallback() -> None: # should have used the IP from via_ip since it was more accurate assert all_est.datasource == "via_ip" - # test that a home defined in shared_config.py is used if no IP is found + # test that a home defined in shared_tz_config.py is used if no IP is found loc = all.estimate_location(datetime(2021, 1, 1, 12, 30, 0, tzinfo=timezone.utc)) assert loc.datasource == "via_home" @@ -121,5 +115,21 @@ def test_ip_fallback() -> None: assert (loc.lat, loc.lon) != (bulgaria.lat, bulgaria.lon) -# re-use prepare fixture for overriding config from shared_config.py -from .tz import prepare +def data() -> Iterator[IP]: + # random IP addresses + yield IP(addr="67.98.113.0", dt=datetime(2020, 1, 1, 12, 0, 0, tzinfo=timezone.utc)) + yield IP(addr="67.98.112.0", dt=datetime(2020, 1, 15, 12, 0, 0, tzinfo=timezone.utc)) + yield IP(addr="59.40.113.87", dt=datetime(2020, 2, 1, 12, 0, 0, tzinfo=timezone.utc)) + yield IP(addr="59.40.139.87", dt=datetime(2020, 2, 1, 16, 0, 0, tzinfo=timezone.utc)) + yield IP(addr="161.235.192.228", dt=datetime(2020, 3, 1, 12, 0, 0, tzinfo=timezone.utc)) + + +@pytest.fixture(autouse=True) +def prepare(config): + before = ip_module.ips + # redefine the my.ip.all function using data for testing + ip_module.ips = data + try: + yield + finally: + ip_module.ips = before diff --git a/tests/shared_config.py b/my/tests/shared_tz_config.py similarity index 55% rename from tests/shared_config.py rename to my/tests/shared_tz_config.py index c2f6973..3d95a9e 100644 --- a/tests/shared_config.py +++ b/my/tests/shared_tz_config.py @@ -1,47 +1,26 @@ -# Defines some shared config for tests +""" +Helper to test various timezone/location dependent things +""" -from datetime import datetime, date, timezone +from datetime import date, datetime, timezone from pathlib import Path -from typing import Any, NamedTuple -import my.time.tz.via_location as LTZ +import pytest from more_itertools import one - -class SharedConfig(NamedTuple): - google: Any - location: Any - time: Any +from my.core.cfg import tmp_config -def _prepare_google_config(tmp_path: Path): - from my.tests.common import testdata - try: - track = one(testdata().rglob('italy-slovenia-2017-07-29.json')) - except ValueError: - raise RuntimeError('testdata not found, setup git submodules?') +@pytest.fixture(autouse=True) +def config(tmp_path: Path): + # TODO could just pick a part of shared config? not sure + _takeout_path = _prepare_takeouts_dir(tmp_path) - - # todo ugh. unnecessary zipping, but at the moment takeout provider doesn't support plain dirs - import zipfile - with zipfile.ZipFile(tmp_path / 'takeout.zip', 'w') as zf: - zf.writestr('Takeout/Location History/Location History.json', track.read_bytes()) - - class google_config: - takeout_path = tmp_path - return google_config - - -# pass tmp_path from pytest to this helper function -# see tests/tz.py as an example -def temp_config(temp_path: Path) -> Any: - from my.tests.common import reset_modules - reset_modules() - - LTZ.config.fast = True + class google: + takeout_path = _takeout_path class location: - home_accuracy = 30_000 + # fmt: off home = ( # supports ISO strings ('2005-12-04' , (42.697842, 23.325973)), # Bulgaria, Sofia @@ -50,16 +29,32 @@ def temp_config(temp_path: Path) -> Any: # check tz handling.. (datetime.fromtimestamp(1600000000, tz=timezone.utc), (55.7558 , 37.6173 )), # Moscow, Russia ) + # fmt: on # note: order doesn't matter, will be sorted in the data provider - class via_ip: - accuracy = 15_000 - class gpslogger: - pass class time: class tz: class via_location: - pass # just rely on the defaults... + fast = True # some tests rely on it + + with tmp_config() as cfg: + cfg.google = google + cfg.location = location + cfg.time = time + yield cfg - return SharedConfig(google=_prepare_google_config(temp_path), location=location, time=time) +def _prepare_takeouts_dir(tmp_path: Path) -> Path: + from .common import testdata + + try: + track = one(testdata().rglob('italy-slovenia-2017-07-29.json')) + except ValueError: + raise RuntimeError('testdata not found, setup git submodules?') + + # todo ugh. unnecessary zipping, but at the moment takeout provider doesn't support plain dirs + import zipfile + + with zipfile.ZipFile(tmp_path / 'takeout.zip', 'w') as zf: + zf.writestr('Takeout/Location History/Location History.json', track.read_bytes()) + return tmp_path diff --git a/my/tests/tz.py b/my/tests/tz.py new file mode 100644 index 0000000..db88278 --- /dev/null +++ b/my/tests/tz.py @@ -0,0 +1,107 @@ +import sys +from datetime import datetime, timedelta + +import pytest +import pytz + +import my.time.tz.main as tz_main +import my.time.tz.via_location as tz_via_location +from my.core import notnone +from my.core.compat import fromisoformat + +from .shared_tz_config import config # autoused fixture + + +def getzone(dt: datetime) -> str: + tz = notnone(dt.tzinfo) + return getattr(tz, 'zone') + + +@pytest.mark.parametrize('fast', [False, True]) +def test_iter_tzs(fast: bool, config) -> None: + # TODO hmm.. maybe need to make sure we start with empty config? + config.time.tz.via_location.fast = fast + + ll = list(tz_via_location._iter_tzs()) + zones = [x.zone for x in ll] + + if fast: + assert zones == [ + 'Europe/Rome', + 'Europe/Rome', + 'Europe/Vienna', + 'Europe/Vienna', + 'Europe/Vienna', + ] + else: + assert zones == [ + 'Europe/Rome', + 'Europe/Rome', + 'Europe/Ljubljana', + 'Europe/Ljubljana', + 'Europe/Ljubljana', + ] + + +def test_past() -> None: + """ + Should fallback to the 'home' location provider + """ + dt = fromisoformat('2000-01-01 12:34:45') + dt = tz_main.localize(dt) + assert getzone(dt) == 'America/New_York' + + +def test_future() -> None: + """ + For locations in the future should rely on 'home' location + """ + fut = datetime.now() + timedelta(days=100) + fut = tz_main.localize(fut) + assert getzone(fut) == 'Europe/Moscow' + + +def test_get_tz(config) -> None: + # todo hmm, the way it's implemented at the moment, never returns None? + get_tz = tz_via_location.get_tz + + # not present in the test data + tz = get_tz(fromisoformat('2020-01-01 10:00:00')) + assert notnone(tz).zone == 'Europe/Sofia' + + tz = get_tz(fromisoformat('2017-08-01 11:00:00')) + assert notnone(tz).zone == 'Europe/Vienna' + + tz = get_tz(fromisoformat('2017-07-30 10:00:00')) + assert notnone(tz).zone == 'Europe/Rome' + + tz = get_tz(fromisoformat('2020-10-01 14:15:16')) + assert tz is not None + + on_windows = sys.platform == 'win32' + if not on_windows: + tz = get_tz(datetime.min) + assert tz is not None + else: + # seems this fails because windows doesn't support same date ranges + # https://stackoverflow.com/a/41400321/ + with pytest.raises(OSError): + get_tz(datetime.min) + + +def test_policies() -> None: + naive = fromisoformat('2017-07-30 10:00:00') + assert naive.tzinfo is None # just in case + + # actual timezone at the time + assert getzone(tz_main.localize(naive)) == 'Europe/Rome' + + z = pytz.timezone('America/New_York') + aware = z.localize(naive) + + assert getzone(tz_main.localize(aware)) == 'America/New_York' + + assert getzone(tz_main.localize(aware, policy='convert')) == 'Europe/Rome' + + with pytest.raises(RuntimeError): + assert tz_main.localize(aware, policy='throw') diff --git a/my/time/tz/via_location.py b/my/time/tz/via_location.py index b66ff8a..329e330 100644 --- a/my/time/tz/via_location.py +++ b/my/time/tz/via_location.py @@ -1,52 +1,43 @@ ''' Timezone data provider, guesses timezone based on location data (e.g. GPS) ''' + REQUIRES = [ # for determining timezone by coordinate 'timezonefinder', ] +import heapq +import os from collections import Counter from dataclasses import dataclass from datetime import date, datetime from functools import lru_cache -import heapq from itertools import groupby -import os -from typing import Iterator, Optional, Tuple, Any, List, Iterable, Set, Dict +from typing import ( + TYPE_CHECKING, + Any, + Dict, + Iterable, + Iterator, + List, + Optional, + Protocol, + Set, + Tuple, +) import pytz +from my.core import Stats, datetime_aware, make_logger, stat from my.core.cachew import mcachew -from my.core import make_logger, stat, Stats, datetime_aware +from my.core.compat import TypeAlias from my.core.source import import_source from my.core.warnings import high - from my.location.common import LatLon -## user might not have tz config section, so makes sense to be more defensive about it -# todo might be useful to extract a helper for this -try: - from my.config import time -except ImportError as ie: - if ie.name != 'time': - raise ie -else: - try: - user_config = time.tz.via_location - except AttributeError as ae: - if not ("'tz'" in str(ae) or "'via_location'"): - raise ae - -# deliberately dynamic to prevent confusing mypy -if 'user_config' not in globals(): - globals()['user_config'] = object -## - - -@dataclass -class config(user_config): +class config(Protocol): # less precise, but faster fast: bool = True @@ -62,6 +53,43 @@ class config(user_config): _iter_tz_refresh_time: int = 6 +def _get_user_config(): + ## user might not have tz config section, so makes sense to be more defensive about it + + class empty_config: ... + + try: + from my.config import time + except ImportError as ie: + if "'time'" not in str(ie): + raise ie + else: + return empty_config + + try: + user_config = time.tz.via_location + except AttributeError as ae: + if not ("'tz'" in str(ae) or "'via_location'" in str(ae)): + raise ae + else: + return empty_config + + return user_config + + +def make_config() -> config: + if TYPE_CHECKING: + import my.config + + user_config: TypeAlias = my.config.time.tz.via_location + else: + user_config = _get_user_config() + + class combined_config(user_config, config): ... + + return combined_config() + + logger = make_logger(__name__) @@ -78,6 +106,7 @@ def _timezone_finder(fast: bool) -> Any: # for backwards compatibility def _locations() -> Iterator[Tuple[LatLon, datetime_aware]]: try: + raise RuntimeError import my.location.all for loc in my.location.all.locations(): @@ -140,13 +169,14 @@ def _find_tz_for_locs(finder: Any, locs: Iterable[Tuple[LatLon, datetime]]) -> I # Note: this takes a while, as the upstream since _locations isn't sorted, so this # has to do an iterative sort of the entire my.locations.all list def _iter_local_dates() -> Iterator[DayWithZone]: - finder = _timezone_finder(fast=config.fast) # rely on the default + cfg = make_config() + finder = _timezone_finder(fast=cfg.fast) # rely on the default # pdt = None # TODO: warnings doesn't actually warn? # warnings = [] locs: Iterable[Tuple[LatLon, datetime]] - locs = _sorted_locations() if config.sort_locations else _locations() + locs = _sorted_locations() if cfg.sort_locations else _locations() yield from _find_tz_for_locs(finder, locs) @@ -158,11 +188,13 @@ def _iter_local_dates() -> Iterator[DayWithZone]: def _iter_local_dates_fallback() -> Iterator[DayWithZone]: from my.location.fallback.all import fallback_locations as flocs + cfg = make_config() + def _fallback_locations() -> Iterator[Tuple[LatLon, datetime]]: for loc in sorted(flocs(), key=lambda x: x.dt): yield ((loc.lat, loc.lon), loc.dt) - yield from _find_tz_for_locs(_timezone_finder(fast=config.fast), _fallback_locations()) + yield from _find_tz_for_locs(_timezone_finder(fast=cfg.fast), _fallback_locations()) def most_common(lst: Iterator[DayWithZone]) -> DayWithZone: @@ -180,7 +212,8 @@ def _iter_tz_depends_on() -> str: 2022-04-26_12 2022-04-26_18 """ - mod = config._iter_tz_refresh_time + cfg = make_config() + mod = cfg._iter_tz_refresh_time assert mod >= 1 day = str(date.today()) hr = datetime.now().hour @@ -293,5 +326,13 @@ def stats(quick: bool = False) -> Stats: return stat(localized_years) -# deprecated -- still used in some other modules so need to keep -_get_tz = get_tz +## deprecated -- keeping for now as might be used in other modules? +if not TYPE_CHECKING: + from my.core.compat import deprecated + + @deprecated('use get_tz function instead') + def _get_tz(*args, **kwargs): + return get_tz(*args, **kwargs) + + +## diff --git a/tests/calendar.py b/tests/calendar.py deleted file mode 100644 index 3435da3..0000000 --- a/tests/calendar.py +++ /dev/null @@ -1,19 +0,0 @@ -from pathlib import Path - -import pytest - -from my.calendar.holidays import is_holiday - - -def test() -> None: - assert is_holiday('20190101') - assert not is_holiday('20180601') - assert is_holiday('20200906') # national holiday in Bulgaria - - -@pytest.fixture(autouse=True) -def prepare(tmp_path: Path): - from . import tz - # todo meh. fixtures can't be called directly? - orig = tz.prepare.__wrapped__ # type: ignore - yield from orig(tmp_path) diff --git a/tests/orgmode.py b/tests/orgmode.py index 37d783e..9b5cc59 100644 --- a/tests/orgmode.py +++ b/tests/orgmode.py @@ -1,10 +1,9 @@ from my.tests.common import skip_if_not_karlicoss as pytestmark -from my import orgmode -from my.core.orgmode import collect - - def test() -> None: + from my import orgmode + from my.core.orgmode import collect + # meh results = list(orgmode.query().collect_all(lambda n: [n] if 'python' in n.tags else [])) assert len(results) > 5 diff --git a/tests/takeout.py b/tests/takeout.py index cddc684..47d405b 100644 --- a/tests/takeout.py +++ b/tests/takeout.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python3 +from my.tests.common import skip_if_not_karlicoss as pytestmark from datetime import datetime, timezone from itertools import islice import pytz diff --git a/tests/tz.py b/tests/tz.py deleted file mode 100644 index d86c5cb..0000000 --- a/tests/tz.py +++ /dev/null @@ -1,95 +0,0 @@ -import sys -from datetime import datetime, timedelta -from pathlib import Path - -import pytest -import pytz - -from my.core.error import notnone - -import my.time.tz.main as TZ -import my.time.tz.via_location as LTZ - - -def test_iter_tzs() -> None: - ll = list(LTZ._iter_tzs()) - assert len(ll) > 3 - - -def test_past() -> None: - # should fallback to the home location provider - dt = D('20000101 12:34:45') - dt = TZ.localize(dt) - tz = dt.tzinfo - assert tz is not None - assert getattr(tz, 'zone') == 'America/New_York' - - -def test_future() -> None: - fut = datetime.now() + timedelta(days=100) - # shouldn't crash at least - assert TZ.localize(fut) is not None - - -def test_tz() -> None: - # todo hmm, the way it's implemented at the moment, never returns None? - - # not present in the test data - tz = LTZ._get_tz(D('20200101 10:00:00')) - assert notnone(tz).zone == 'Europe/Sofia' - - tz = LTZ._get_tz(D('20170801 11:00:00')) - assert notnone(tz).zone == 'Europe/Vienna' - - tz = LTZ._get_tz(D('20170730 10:00:00')) - assert notnone(tz).zone == 'Europe/Rome' - - tz = LTZ._get_tz(D('20201001 14:15:16')) - assert tz is not None - - on_windows = sys.platform == 'win32' - if not on_windows: - tz = LTZ._get_tz(datetime.min) - assert tz is not None - else: - # seems this fails because windows doesn't support same date ranges - # https://stackoverflow.com/a/41400321/ - with pytest.raises(OSError): - LTZ._get_tz(datetime.min) - - -def test_policies() -> None: - getzone = lambda dt: getattr(dt.tzinfo, 'zone') - - naive = D('20170730 10:00:00') - # actual timezone at the time - assert getzone(TZ.localize(naive)) == 'Europe/Rome' - - z = pytz.timezone('America/New_York') - aware = z.localize(naive) - - assert getzone(TZ.localize(aware)) == 'America/New_York' - - assert getzone(TZ.localize(aware, policy='convert')) == 'Europe/Rome' - - - with pytest.raises(RuntimeError): - assert TZ.localize(aware, policy='throw') - - -def D(dstr: str) -> datetime: - return datetime.strptime(dstr, '%Y%m%d %H:%M:%S') - - - -@pytest.fixture(autouse=True) -def prepare(tmp_path: Path): - from .shared_config import temp_config - conf = temp_config(tmp_path) - - import my.core.cfg as C - with C.tmp_config() as config: - config.google = conf.google - config.time = conf.time - config.location = conf.location - yield diff --git a/tox.ini b/tox.ini index 248469e..20f730b 100644 --- a/tox.ini +++ b/tox.ini @@ -88,7 +88,6 @@ commands = {envpython} -m pytest tests \ # ignore some tests which might take a while to run on ci.. - --ignore tests/takeout.py \ --ignore tests/extra/polar.py {posargs} From b87d1c970a870eda11cc48f45d074c286dae15e6 Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Mon, 26 Aug 2024 03:34:45 +0100 Subject: [PATCH 079/122] tests: move remaining tests from tests/ to my.tests, cleanup corresponding modules --- my/body/weight.py | 35 ++++++++---- my/orgmode.py | 36 ++++++++---- my/pdfs.py | 8 +-- {tests => my/tests}/bluemaestro.py | 12 ++-- my/tests/body/weight.py | 57 +++++++++++++++++++ {tests => my/tests}/pdfs.py | 3 +- my/tests/reddit.py | 9 +-- tests/config.py | 89 ------------------------------ tox.ini | 5 -- 9 files changed, 120 insertions(+), 134 deletions(-) rename {tests => my/tests}/bluemaestro.py (86%) create mode 100644 my/tests/body/weight.py rename {tests => my/tests}/pdfs.py (99%) delete mode 100644 tests/config.py diff --git a/my/body/weight.py b/my/body/weight.py index def3e87..277b4d1 100644 --- a/my/body/weight.py +++ b/my/body/weight.py @@ -2,21 +2,29 @@ Weight data (manually logged) ''' +from dataclasses import dataclass from datetime import datetime -from typing import NamedTuple, Iterator +from typing import Any, Iterator -from ..core import LazyLogger -from ..core.error import Res, set_error_datetime, extract_error_datetime +from my.core import make_logger +from my.core.error import Res, extract_error_datetime, set_error_datetime -from .. import orgmode +from my import orgmode -from my.config import weight as config # type: ignore[attr-defined] +config = Any -log = LazyLogger('my.body.weight') +def make_config() -> config: + from my.config import weight as user_config # type: ignore[attr-defined] + + return user_config() -class Entry(NamedTuple): +log = make_logger(__name__) + + +@dataclass +class Entry: dt: datetime value: float # TODO comment?? @@ -26,6 +34,8 @@ Result = Res[Entry] def from_orgmode() -> Iterator[Result]: + cfg = make_config() + orgs = orgmode.query() for o in orgmode.query().all(): if 'weight' not in o.tags: @@ -46,8 +56,8 @@ def from_orgmode() -> Iterator[Result]: yield e continue # FIXME use timezone provider - created = config.default_timezone.localize(created) - assert created is not None #??? somehow mypy wasn't happy? + created = cfg.default_timezone.localize(created) + assert created is not None # ??? somehow mypy wasn't happy? yield Entry( dt=created, value=w, @@ -57,19 +67,21 @@ def from_orgmode() -> Iterator[Result]: def make_dataframe(data: Iterator[Result]): import pandas as pd + def it(): for e in data: if isinstance(e, Exception): dt = extract_error_datetime(e) yield { - 'dt' : dt, + 'dt': dt, 'error': str(e), } else: yield { - 'dt' : e.dt, + 'dt': e.dt, 'weight': e.value, } + df = pd.DataFrame(it()) df.set_index('dt', inplace=True) # TODO not sure about UTC?? @@ -81,6 +93,7 @@ def dataframe(): entries = from_orgmode() return make_dataframe(entries) + # TODO move to a submodule? e.g. my.body.weight.orgmode? # so there could be more sources # not sure about my.body thing though diff --git a/my/orgmode.py b/my/orgmode.py index c27f5a7..cf14e43 100644 --- a/my/orgmode.py +++ b/my/orgmode.py @@ -6,18 +6,28 @@ REQUIRES = [ 'orgparse', ] +import re from datetime import datetime from pathlib import Path -import re -from typing import List, Sequence, Iterable, NamedTuple, Optional, Tuple +from typing import Iterable, List, NamedTuple, Optional, Sequence, Tuple -from my.core import get_files +import orgparse + +from my.core import Paths, Stats, get_files, stat from my.core.cachew import cache_dir, mcachew from my.core.orgmode import collect -from my.config import orgmode as user_config -import orgparse +class config: + paths: Paths + + +def make_config() -> config: + from my.config import orgmode as user_config + + class combined_config(user_config, config): ... + + return combined_config() # temporary? hack to cache org-mode notes @@ -28,10 +38,13 @@ class OrgNote(NamedTuple): def inputs() -> Sequence[Path]: - return get_files(user_config.paths) + cfg = make_config() + return get_files(cfg.paths) _rgx = re.compile(orgparse.date.gene_timestamp_regex(brtype='inactive'), re.VERBOSE) + + def _created(n: orgparse.OrgNode) -> Tuple[Optional[datetime], str]: heading = n.heading # meh.. support in orgparse? @@ -41,7 +54,7 @@ def _created(n: orgparse.OrgNode) -> Tuple[Optional[datetime], str]: # try to guess from heading m = _rgx.search(heading) if m is not None: - createds = m.group(0) # could be None + createds = m.group(0) # could be None if createds is None: return (None, heading) assert isinstance(createds, str) @@ -67,7 +80,7 @@ def to_note(x: orgparse.OrgNode) -> OrgNote: created = None return OrgNote( created=created, - heading=heading, # todo include the body? + heading=heading, # todo include the body? tags=list(x.tags), ) @@ -84,14 +97,15 @@ def _cachew_cache_path(_self, f: Path) -> Path: def _cachew_depends_on(_self, f: Path): return (f, f.stat().st_mtime) - + class Query: def __init__(self, files: Sequence[Path]) -> None: self.files = files # TODO yield errors? @mcachew( - cache_path=_cachew_cache_path, force_file=True, + cache_path=_cachew_cache_path, + force_file=True, depends_on=_cachew_depends_on, ) def _iterate(self, f: Path) -> Iterable[OrgNote]: @@ -114,8 +128,8 @@ def query() -> Query: return Query(files=inputs()) -from my.core import Stats, stat def stats() -> Stats: def outlines(): return query().all() + return stat(outlines) diff --git a/my/pdfs.py b/my/pdfs.py index 524c68b..1cedfd5 100644 --- a/my/pdfs.py +++ b/my/pdfs.py @@ -10,7 +10,7 @@ REQUIRES = [ import time from datetime import datetime from pathlib import Path -from typing import Iterator, List, NamedTuple, Optional, Protocol, Sequence +from typing import Iterator, List, NamedTuple, Optional, Protocol, Sequence, TYPE_CHECKING import pdfannots from more_itertools import bucket @@ -185,8 +185,6 @@ def stats() -> Stats: ### legacy/misc stuff -iter_annotations = annotations # for backwards compatibility +if not TYPE_CHECKING: + iter_annotations = annotations ### - -# can use 'hpi query my.pdfs.annotations -o pprint' to test -# diff --git a/tests/bluemaestro.py b/my/tests/bluemaestro.py similarity index 86% rename from tests/bluemaestro.py rename to my/tests/bluemaestro.py index 63ce589..2d7c81e 100644 --- a/tests/bluemaestro.py +++ b/my/tests/bluemaestro.py @@ -1,12 +1,12 @@ -from pathlib import Path from typing import Iterator +import pytest from more_itertools import one -import pytest +from my.bluemaestro import Measurement, measurements +from my.core.cfg import tmp_config - -from my.bluemaestro import measurements, Measurement +from .common import testdata def ok_measurements() -> Iterator[Measurement]: @@ -26,7 +26,7 @@ def test() -> None: # check that timezone is set properly assert dts == '20200824 22' - assert len(tp) == 1 # should be unique + assert len(tp) == 1 # should be unique # 2.5 K + 4 K datapoints, somewhat overlapping assert len(res2020) < 6000 @@ -46,14 +46,12 @@ def test_old_db() -> None: @pytest.fixture(autouse=True) def prepare(): - from my.tests.common import testdata bmdata = testdata() / 'hpi-testdata' / 'bluemaestro' assert bmdata.exists(), bmdata class bluemaestro: export_path = bmdata - from my.core.cfg import tmp_config with tmp_config() as config: config.bluemaestro = bluemaestro yield diff --git a/my/tests/body/weight.py b/my/tests/body/weight.py new file mode 100644 index 0000000..069e940 --- /dev/null +++ b/my/tests/body/weight.py @@ -0,0 +1,57 @@ +from pathlib import Path +import pytz +from my.core.cfg import tmp_config +import pytest +from my.body.weight import from_orgmode + + +def test_body_weight() -> None: + weights = [0.0 if isinstance(x, Exception) else x.value for x in from_orgmode()] + + assert weights == [ + 0.0, + 62.0, + 0.0, + 61.0, + 62.0, + 0.0, + ] + + +@pytest.fixture(autouse=True) +def prepare(tmp_path: Path): + ndir = tmp_path / 'notes' + ndir.mkdir() + logs = ndir / 'logs.org' + logs.write_text( + ''' +#+TITLE: Stuff I'm logging + +* Weight (org-capture) :weight: +** [2020-05-01 Fri 09:00] 62 +** 63 + this should be ignored, got no timestamp +** [2020-05-03 Sun 08:00] 61 +** [2020-05-04 Mon 10:00] 62 +''' + ) + misc = ndir / 'misc.org' + misc.write_text( + ''' +Some misc stuff + +* unrelated note :weight:whatever: +''' + ) + + class orgmode: + paths = [ndir] + + class weight: + # TODO ugh. this belongs to tz provider or global config or something + default_timezone = pytz.timezone('Europe/London') + + with tmp_config() as cfg: + cfg.orgmode = orgmode + cfg.weight = weight + yield diff --git a/tests/pdfs.py b/my/tests/pdfs.py similarity index 99% rename from tests/pdfs.py rename to my/tests/pdfs.py index 6db669f..bd1e93a 100644 --- a/tests/pdfs.py +++ b/my/tests/pdfs.py @@ -5,9 +5,8 @@ import pytest from more_itertools import ilen from my.core.cfg import tmp_config -from my.tests.common import testdata - from my.pdfs import annotated_pdfs, annotations, get_annots +from my.tests.common import testdata def test_module(with_config) -> None: diff --git a/my/tests/reddit.py b/my/tests/reddit.py index fb8d6d2..4f1ec51 100644 --- a/my/tests/reddit.py +++ b/my/tests/reddit.py @@ -1,15 +1,16 @@ +import pytest +from more_itertools import consume + from my.core.cfg import tmp_config from my.core.utils.itertools import ensure_unique -# todo ugh, it's discovered as a test??? from .common import testdata -from more_itertools import consume -import pytest # deliberately use mixed style imports on the top level and inside the methods to test tmp_config stuff -import my.reddit.rexport as my_reddit_rexport +# todo won't really be necessary once we migrate to lazy user config import my.reddit.all as my_reddit_all +import my.reddit.rexport as my_reddit_rexport def test_basic_1() -> None: diff --git a/tests/config.py b/tests/config.py deleted file mode 100644 index acfe1f1..0000000 --- a/tests/config.py +++ /dev/null @@ -1,89 +0,0 @@ -from pathlib import Path - - -# TODO move this somewhere else -- there are more specific tests covering this now -def test_dynamic_configuration(notes: Path) -> None: - import pytz - from types import SimpleNamespace as NS - - from my.core.cfg import tmp_config - with tmp_config() as C: - C.orgmode = NS(paths=[notes]) - # TODO ugh. this belongs to tz provider or global config or something - C.weight = NS(default_timezone=pytz.timezone('Europe/London')) - - from my.body.weight import from_orgmode - weights = [0.0 if isinstance(x, Exception) else x.value for x in from_orgmode()] - - assert weights == [ - 0.0, - 62.0, - 0.0, - 61.0, - 62.0, - 0.0, - ] - -import pytest - - - -from dataclasses import dataclass - - -# TODO this test should probs be deprecated? it's more of a documentation? -def test_user_config() -> None: - from my.core.common import classproperty - class user_config: - param1 = 'abacaba' - # TODO fuck. properties don't work here??? - @classproperty - def param2(cls) -> int: - return 456 - - extra = 'extra!' - - @dataclass - class test_config(user_config): - param1: str - param2: int # type: ignore[assignment] # TODO need to figure out how to trick mypy for @classproperty - param3: str = 'default' - - assert test_config.param1 == 'abacaba' - assert test_config.param2 == 456 - assert test_config.param3 == 'default' - assert test_config.extra == 'extra!' - - from my.core.cfg import make_config - c = make_config(test_config) - assert c.param1 == 'abacaba' - assert c.param2 == 456 - assert c.param3 == 'default' - assert c.extra == 'extra!' - - -@pytest.fixture -def notes(tmp_path: Path): - ndir = tmp_path / 'notes' - ndir.mkdir() - logs = ndir / 'logs.org' - logs.write_text(''' -#+TITLE: Stuff I'm logging - -* Weight (org-capture) :weight: -** [2020-05-01 Fri 09:00] 62 -** 63 - this should be ignored, got no timestamp -** [2020-05-03 Sun 08:00] 61 -** [2020-05-04 Mon 10:00] 62 - ''') - misc = ndir / 'misc.org' - misc.write_text(''' -Some misc stuff - -* unrelated note :weight:whatever: - ''') - try: - yield ndir - finally: - pass diff --git a/tox.ini b/tox.ini index 20f730b..6b95088 100644 --- a/tox.ini +++ b/tox.ini @@ -86,11 +86,6 @@ commands = --pyargs {[testenv]package_name}.core {[testenv]package_name}.tests \ {posargs} - {envpython} -m pytest tests \ - # ignore some tests which might take a while to run on ci.. - --ignore tests/extra/polar.py - {posargs} - [testenv:demo] commands = From b1fe23b8d0d2ede92c4c17c7199f537c0523317b Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Mon, 26 Aug 2024 03:50:32 +0100 Subject: [PATCH 080/122] my.rss.feedly/my.twittr.talon -- migrate to use lazy user configs --- my/rss/feedly.py | 28 ++++++++++++++++++++++------ my/twitter/talon.py | 34 ++++++++++++++++++++++++---------- 2 files changed, 46 insertions(+), 16 deletions(-) diff --git a/my/rss/feedly.py b/my/rss/feedly.py index 55bcf9b..127ef61 100644 --- a/my/rss/feedly.py +++ b/my/rss/feedly.py @@ -2,19 +2,35 @@ Feedly RSS reader """ -from my.config import feedly as config - -from datetime import datetime, timezone import json +from abc import abstractmethod +from datetime import datetime, timezone from pathlib import Path -from typing import Iterator, Sequence +from typing import Iterator, Protocol, Sequence + +from my.core import Paths, get_files -from my.core import get_files from .common import Subscription, SubscriptionState +class config(Protocol): + @property + @abstractmethod + def export_path(self) -> Paths: + raise NotImplementedError + + +def make_config() -> config: + from my.config import feedly as user_config + + class combined_config(user_config, config): ... + + return combined_config() + + def inputs() -> Sequence[Path]: - return get_files(config.export_path) + cfg = make_config() + return get_files(cfg.export_path) def parse_file(f: Path) -> Iterator[Subscription]: diff --git a/my/twitter/talon.py b/my/twitter/talon.py index 306a735..1b79727 100644 --- a/my/twitter/talon.py +++ b/my/twitter/talon.py @@ -1,12 +1,15 @@ """ Twitter data from Talon app database (in =/data/data/com.klinker.android.twitter_l/databases/=) """ + from __future__ import annotations -from dataclasses import dataclass -from datetime import datetime, timezone import re import sqlite3 +from abc import abstractmethod +from dataclasses import dataclass +from datetime import datetime, timezone +from pathlib import Path from typing import Iterator, Sequence, Union from my.core import Paths, Res, datetime_aware, get_files @@ -15,18 +18,25 @@ from my.core.sqlite import sqlite_connection from .common import TweetId, permalink -from my.config import twitter as user_config + +class config: + @property + @abstractmethod + def export_path(self) -> Paths: + raise NotImplementedError -@dataclass -class config(user_config.talon): - # paths[s]/glob to the exported sqlite databases - export_path: Paths +def make_config() -> config: + from my.config import twitter as user_config + + class combined_config(user_config.talon, config): + pass + + return combined_config() -from pathlib import Path def inputs() -> Sequence[Path]: - return get_files(config.export_path) + return get_files(make_config().export_path) @dataclass(unsafe_hash=True) @@ -46,12 +56,16 @@ class Tweet: @dataclass(unsafe_hash=True) class _IsTweet: tweet: Tweet + + @dataclass(unsafe_hash=True) class _IsFavorire: tweet: Tweet Entity = Union[_IsTweet, _IsFavorire] + + def _entities() -> Iterator[Res[Entity]]: for f in inputs(): yield from _process_one(f) @@ -59,7 +73,7 @@ def _entities() -> Iterator[Res[Entity]]: def _process_one(f: Path) -> Iterator[Res[Entity]]: handlers = { - 'user_tweets.db' : _process_user_tweets, + 'user_tweets.db': _process_user_tweets, 'favorite_tweets.db': _process_favorite_tweets, } fname = f.name From c08ddbc781b4cc79441e9d0d856957a94791fb7f Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Tue, 27 Aug 2024 21:02:39 +0100 Subject: [PATCH 081/122] general: small updates for typing while trying out pyright --- my/core/common.py | 2 +- my/core/stats.py | 2 +- my/core/util.py | 2 +- my/core/utils/itertools.py | 8 +++----- my/google/takeout/html.py | 5 ++--- my/hypothesis.py | 5 +++-- my/smscalls.py | 2 +- 7 files changed, 12 insertions(+), 14 deletions(-) diff --git a/my/core/common.py b/my/core/common.py index dcd1074..d0b737e 100644 --- a/my/core/common.py +++ b/my/core/common.py @@ -133,8 +133,8 @@ def test_classproperty() -> None: return 'hello' res = C.prop - assert res == 'hello' assert_type(res, str) + assert res == 'hello' # hmm, this doesn't really work with mypy well.. diff --git a/my/core/stats.py b/my/core/stats.py index 08821a2..bfedbd2 100644 --- a/my/core/stats.py +++ b/my/core/stats.py @@ -2,7 +2,7 @@ Helpers for hpi doctor/stats functionality. ''' -import collections +import collections.abc import importlib import inspect import typing diff --git a/my/core/util.py b/my/core/util.py index b48a450..0c596fa 100644 --- a/my/core/util.py +++ b/my/core/util.py @@ -25,7 +25,7 @@ def is_not_hpi_module(module: str) -> Optional[str]: ''' None if a module, otherwise returns reason ''' - import importlib + import importlib.util path: Optional[str] = None try: diff --git a/my/core/utils/itertools.py b/my/core/utils/itertools.py index 023484d..66f82bd 100644 --- a/my/core/utils/itertools.py +++ b/my/core/utils/itertools.py @@ -275,20 +275,18 @@ def test_check_if_hashable() -> None: x1: List[int] = [1, 2] r1 = check_if_hashable(x1) - # tgype: ignore[comparison-overlap] # object should be unchanged - assert r1 is x1 assert_type(r1, Iterable[int]) + assert r1 is x1 x2: Iterator[Union[int, str]] = iter((123, 'aba')) r2 = check_if_hashable(x2) - assert list(r2) == [123, 'aba'] assert_type(r2, Iterable[Union[int, str]]) + assert list(r2) == [123, 'aba'] x3: Tuple[object, ...] = (789, 'aba') r3 = check_if_hashable(x3) - # ttype: ignore[comparison-overlap] # object should be unchanged - assert r3 is x3 assert_type(r3, Iterable[object]) + assert r3 is x3 # object should be unchanged x4: List[Set[int]] = [{1, 2, 3}, {4, 5, 6}] with pytest.raises(Exception): diff --git a/my/google/takeout/html.py b/my/google/takeout/html.py index d393957..3ce692c 100644 --- a/my/google/takeout/html.py +++ b/my/google/takeout/html.py @@ -8,7 +8,6 @@ from pathlib import Path from datetime import datetime from html.parser import HTMLParser from typing import List, Optional, Any, Callable, Iterable, Tuple -from collections import OrderedDict from urllib.parse import unquote import pytz @@ -94,8 +93,8 @@ class TakeoutHTMLParser(HTMLParser): def handle_starttag(self, tag, attrs): if self.state == State.INSIDE and tag == 'a': self.state = State.PARSING_LINK - attrs = OrderedDict(attrs) - hr = attrs['href'] + [hr] = (v for k, v in attrs if k == 'href') + assert hr is not None # sometimes it's starts with this prefix, it's apparently clicks from google search? or visits from chrome address line? who knows... # TODO handle http? diff --git a/my/hypothesis.py b/my/hypothesis.py index 55fff64..82104cd 100644 --- a/my/hypothesis.py +++ b/my/hypothesis.py @@ -41,6 +41,7 @@ except ModuleNotFoundError as e: dal = pre_pip_dal_handler('hypexport', e, config, requires=REQUIRES) +DAL = dal.DAL Highlight = dal.Highlight Page = dal.Page @@ -49,8 +50,8 @@ def inputs() -> Sequence[Path]: return get_files(config.export_path) -def _dal() -> dal.DAL: - return dal.DAL(inputs()) +def _dal() -> DAL: + return DAL(inputs()) # TODO they are in reverse chronological order... diff --git a/my/smscalls.py b/my/smscalls.py index f436709..b56026d 100644 --- a/my/smscalls.py +++ b/my/smscalls.py @@ -24,7 +24,7 @@ from datetime import datetime, timezone from pathlib import Path from typing import NamedTuple, Iterator, Set, Tuple, Optional, Any, Dict, List -from lxml import etree +import lxml.etree as etree from my.core.error import Res From d244c7cc4e17bc9010829c34dd4b88aaba5e5981 Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Tue, 27 Aug 2024 22:50:37 +0100 Subject: [PATCH 082/122] ruff: enable and fix C4 ruleset --- my/coding/commits.py | 4 ++-- my/core/_deprecated/kompress.py | 2 +- my/core/common.py | 2 +- my/core/freezer.py | 6 ++++-- my/core/influxdb.py | 12 ++++++------ my/core/pandas.py | 2 +- my/core/query.py | 10 +++++----- my/core/sqlite.py | 2 +- my/emfit/__init__.py | 2 +- my/github/gdpr.py | 4 ++-- my/lastfm.py | 9 +++++---- my/location/fallback/via_home.py | 2 +- my/media/imdb.py | 2 +- my/pdfs.py | 2 +- my/rescuetime.py | 13 +++++++------ my/tests/pdfs.py | 2 +- my/twitter/archive.py | 2 +- my/youtube/takeout.py | 2 +- ruff.toml | 6 ++++++ 19 files changed, 48 insertions(+), 38 deletions(-) diff --git a/my/coding/commits.py b/my/coding/commits.py index dac3b1f..20b66a0 100644 --- a/my/coding/commits.py +++ b/my/coding/commits.py @@ -161,14 +161,14 @@ def git_repos_in(roots: List[Path]) -> List[Path]: *roots, ]).decode('utf8').splitlines() - candidates = set(Path(o).resolve().absolute().parent for o in outputs) + candidates = {Path(o).resolve().absolute().parent for o in outputs} # exclude stuff within .git dirs (can happen for submodules?) candidates = {c for c in candidates if '.git' not in c.parts[:-1]} candidates = {c for c in candidates if is_git_dir(c)} - repos = list(sorted(map(_git_root, candidates))) + repos = sorted(map(_git_root, candidates)) return repos diff --git a/my/core/_deprecated/kompress.py b/my/core/_deprecated/kompress.py index 7eb9b37..89e5745 100644 --- a/my/core/_deprecated/kompress.py +++ b/my/core/_deprecated/kompress.py @@ -244,7 +244,7 @@ class ZipPath(zipfile_Path): # see https://en.wikipedia.org/wiki/ZIP_(file_format)#Structure dt = datetime(*self.root.getinfo(self.at).date_time) ts = int(dt.timestamp()) - params = dict( + params = dict( # noqa: C408 st_mode=0, st_ino=0, st_dev=0, diff --git a/my/core/common.py b/my/core/common.py index d0b737e..ba4ce6b 100644 --- a/my/core/common.py +++ b/my/core/common.py @@ -80,7 +80,7 @@ def get_files( paths.append(src) if sort: - paths = list(sorted(paths)) + paths = sorted(paths) if len(paths) == 0: # todo make it conditionally defensive based on some global settings diff --git a/my/core/freezer.py b/my/core/freezer.py index e46525b..93bceb7 100644 --- a/my/core/freezer.py +++ b/my/core/freezer.py @@ -60,8 +60,10 @@ class _A: def test_freezer() -> None: - - val = _A(x=dict(an_int=123, an_any=[1, 2, 3])) + val = _A(x={ + 'an_int': 123, + 'an_any': [1, 2, 3], + }) af = Freezer(_A) fval = af.freeze(val) diff --git a/my/core/influxdb.py b/my/core/influxdb.py index c39f6af..b1d6b9b 100644 --- a/my/core/influxdb.py +++ b/my/core/influxdb.py @@ -72,16 +72,16 @@ def fill(it: Iterable[Any], *, measurement: str, reset: bool=RESET_DEFAULT, dt_c fields = filter_dict(d) - yield dict( - measurement=measurement, + yield { + 'measurement': measurement, # TODO maybe good idea to tag with database file/name? to inspect inconsistencies etc.. # hmm, so tags are autoindexed and might be faster? # not sure what's the big difference though # "fields are data and tags are metadata" - tags=tags, - time=dt, - fields=fields, - ) + 'tags': tags, + 'time': dt, + 'fields': fields, + } from more_itertools import chunked # "The optimal batch size is 5000 lines of line protocol." diff --git a/my/core/pandas.py b/my/core/pandas.py index 8ad93cb..d38465a 100644 --- a/my/core/pandas.py +++ b/my/core/pandas.py @@ -222,7 +222,7 @@ def test_as_dataframe() -> None: from .compat import fromisoformat - it = (dict(i=i, s=f'str{i}') for i in range(5)) + it = ({'i': i, 's': f'str{i}'} for i in range(5)) with pytest.warns(UserWarning, match=r"No 'error' column") as record_warnings: # noqa: F841 df: DataFrameT = as_dataframe(it) # todo test other error col policies diff --git a/my/core/query.py b/my/core/query.py index cf85b1b..54cd9db 100644 --- a/my/core/query.py +++ b/my/core/query.py @@ -655,7 +655,7 @@ def test_wrap_unsortable() -> None: # by default, wrap unsortable res = list(select(_mixed_iter(), order_key="z")) - assert Counter(map(lambda t: type(t).__name__, res)) == Counter({"_A": 4, "Unsortable": 2}) + assert Counter(type(t).__name__ for t in res) == Counter({"_A": 4, "Unsortable": 2}) def test_disabled_wrap_unsorted() -> None: @@ -674,7 +674,7 @@ def test_drop_unsorted() -> None: # test drop unsortable, should remove them before the 'sorted' call res = list(select(_mixed_iter(), order_key="z", wrap_unsorted=False, drop_unsorted=True)) assert len(res) == 4 - assert Counter(map(lambda t: type(t).__name__, res)) == Counter({"_A": 4}) + assert Counter(type(t).__name__ for t in res) == Counter({"_A": 4}) def test_drop_exceptions() -> None: @@ -705,7 +705,7 @@ def test_wrap_unsortable_with_error_and_warning() -> None: # by default should wrap unsortable (error) with pytest.warns(UserWarning, match=r"encountered exception"): res = list(select(_mixed_iter_errors(), order_value=lambda o: isinstance(o, datetime))) - assert Counter(map(lambda t: type(t).__name__, res)) == Counter({"_A": 4, "_B": 2, "Unsortable": 1}) + assert Counter(type(t).__name__ for t in res) == Counter({"_A": 4, "_B": 2, "Unsortable": 1}) # compare the returned error wrapped in the Unsortable returned_error = next((o for o in res if isinstance(o, Unsortable))).obj assert "Unhandled error!" == str(returned_error) @@ -717,7 +717,7 @@ def test_order_key_unsortable() -> None: # both unsortable and items which dont match the order_by (order_key) in this case should be classified unsorted res = list(select(_mixed_iter_errors(), order_key="z")) - assert Counter(map(lambda t: type(t).__name__, res)) == Counter({"_A": 4, "Unsortable": 3}) + assert Counter(type(t).__name__ for t in res) == Counter({"_A": 4, "Unsortable": 3}) def test_order_default_param() -> None: @@ -737,7 +737,7 @@ def test_no_recursive_unsortables() -> None: # select to select as input, wrapping unsortables the first time, second should drop them # reverse=True to send errors to the end, so the below order_key works res = list(select(_mixed_iter_errors(), order_key="z", reverse=True)) - assert Counter(map(lambda t: type(t).__name__, res)) == Counter({"_A": 4, "Unsortable": 3}) + assert Counter(type(t).__name__ for t in res) == Counter({"_A": 4, "Unsortable": 3}) # drop_unsorted dropped = list(select(res, order_key="z", drop_unsorted=True)) diff --git a/my/core/sqlite.py b/my/core/sqlite.py index 47bd78b..08a80e5 100644 --- a/my/core/sqlite.py +++ b/my/core/sqlite.py @@ -35,7 +35,7 @@ SqliteRowFactory = Callable[[sqlite3.Cursor, sqlite3.Row], Any] def dict_factory(cursor, row): fields = [column[0] for column in cursor.description] - return {key: value for key, value in zip(fields, row)} + return dict(zip(fields, row)) Factory = Union[SqliteRowFactory, Literal['row', 'dict']] diff --git a/my/emfit/__init__.py b/my/emfit/__init__.py index 7fae8ea..71a483f 100644 --- a/my/emfit/__init__.py +++ b/my/emfit/__init__.py @@ -189,7 +189,7 @@ def fake_data(nights: int = 500) -> Iterator: # TODO remove/deprecate it? I think used by timeline def get_datas() -> List[Emfit]: # todo ugh. run lint properly - return list(sorted(datas(), key=lambda e: e.start)) # type: ignore + return sorted(datas(), key=lambda e: e.start) # type: ignore # TODO move away old entries if there is a diff?? diff --git a/my/github/gdpr.py b/my/github/gdpr.py index 1fde7c9..4ca8e84 100644 --- a/my/github/gdpr.py +++ b/my/github/gdpr.py @@ -51,12 +51,12 @@ def events() -> Iterable[Res[Event]]: # a bit naughty and ad-hoc, but we will generify reading from tar.gz. once we have more examples # another one is zulip archive if last.is_dir(): - files = list(sorted(last.glob('*.json'))) # looks like all files are in the root + files = sorted(last.glob('*.json')) # looks like all files are in the root open_file = lambda f: f.open() else: # treat as .tar.gz tfile = tarfile.open(last) - files = list(sorted(map(Path, tfile.getnames()))) + files = sorted(map(Path, tfile.getnames())) files = [p for p in files if len(p.parts) == 1 and p.suffix == '.json'] open_file = lambda p: notnone(tfile.extractfile(f'./{p}')) # NOTE odd, doesn't work without ./ diff --git a/my/lastfm.py b/my/lastfm.py index 6618738..d20ebf3 100644 --- a/my/lastfm.py +++ b/my/lastfm.py @@ -83,9 +83,10 @@ def stats() -> Stats: def fill_influxdb() -> None: from my.core import influxdb + # todo needs to be more automatic - sd = (dict( - dt=x.dt, - track=x.track, - ) for x in scrobbles()) + sd = ({ + 'dt': x.dt, + 'track': x.track, + } for x in scrobbles()) influxdb.fill(sd, measurement=__name__) diff --git a/my/location/fallback/via_home.py b/my/location/fallback/via_home.py index 259dcaa..199ebb0 100644 --- a/my/location/fallback/via_home.py +++ b/my/location/fallback/via_home.py @@ -55,7 +55,7 @@ class Config(user_config): if dt.tzinfo is None: dt = dt.replace(tzinfo=timezone.utc) res.append((dt, loc)) - res = list(sorted(res, key=lambda p: p[0])) + res = sorted(res, key=lambda p: p[0]) return res diff --git a/my/media/imdb.py b/my/media/imdb.py index b7ecbde..df6d62d 100644 --- a/my/media/imdb.py +++ b/my/media/imdb.py @@ -33,7 +33,7 @@ def iter_movies() -> Iterator[Movie]: def get_movies() -> List[Movie]: - return list(sorted(iter_movies(), key=lambda m: m.created)) + return sorted(iter_movies(), key=lambda m: m.created) def test(): diff --git a/my/pdfs.py b/my/pdfs.py index 1cedfd5..db49c0e 100644 --- a/my/pdfs.py +++ b/my/pdfs.py @@ -97,7 +97,7 @@ def get_annots(p: Path) -> List[Annotation]: b = time.time() with p.open('rb') as fo: doc = pdfannots.process_file(fo, emit_progress_to=None) - annots = [a for a in doc.iter_annots()] + annots = list(doc.iter_annots()) # also has outlines are kinda like TOC, I don't really need them a = time.time() took = a - b diff --git a/my/rescuetime.py b/my/rescuetime.py index c493e8e..76a0d4c 100644 --- a/my/rescuetime.py +++ b/my/rescuetime.py @@ -82,12 +82,13 @@ def fake_data(rows: int=1000) -> Iterator: def fill_influxdb() -> None: - from .core import influxdb - it = (dict( - dt=e.dt, - duration_d=e.duration_s, - tags=dict(activity=e.activity), - ) for e in entries() if isinstance(e, Entry)) # TODO handle errors in core.influxdb + from my.core import influxdb + + it = ({ + 'dt': e.dt, + 'duration_d': e.duration_s, + 'tags': {'activity': e.activity}, + } for e in entries() if isinstance(e, Entry)) # TODO handle errors in core.influxdb influxdb.fill(it, measurement=__name__) diff --git a/my/tests/pdfs.py b/my/tests/pdfs.py index bd1e93a..3702424 100644 --- a/my/tests/pdfs.py +++ b/my/tests/pdfs.py @@ -62,7 +62,7 @@ def test_get_annots() -> None: """ annotations = get_annots(testdata() / 'pdfs' / 'Information Architecture for the World Wide Web.pdf') assert len(annotations) == 3 - assert set([a.highlight for a in annotations]) == EXPECTED_HIGHLIGHTS + assert {a.highlight for a in annotations} == EXPECTED_HIGHLIGHTS def test_annotated_pdfs_with_filelist() -> None: diff --git a/my/twitter/archive.py b/my/twitter/archive.py index 0ea6b24..685f7fc 100644 --- a/my/twitter/archive.py +++ b/my/twitter/archive.py @@ -105,7 +105,7 @@ class Tweet: repls.append((fr, to, me['display_url'])) # todo not sure, maybe use media_url_https instead? # for now doing this for compatibility with twint - repls = list(sorted(repls)) + repls = sorted(repls) parts = [] idx = 0 for fr, to, what in repls: diff --git a/my/youtube/takeout.py b/my/youtube/takeout.py index 8fe8f2c..99d65d9 100644 --- a/my/youtube/takeout.py +++ b/my/youtube/takeout.py @@ -120,4 +120,4 @@ def _watched_legacy() -> Iterable[Watched]: watches.append(Watched(url=url, title=title, when=dt)) # todo hmm they already come sorted.. wonder if should just rely on it.. - return list(sorted(watches, key=lambda e: e.when)) + return sorted(watches, key=lambda e: e.when) diff --git a/ruff.toml b/ruff.toml index 54f621c..db926da 100644 --- a/ruff.toml +++ b/ruff.toml @@ -1,3 +1,9 @@ +lint.extend-select = [ + "F", # flakes rules -- default, but extend just in case + "E", # pycodestyle -- default, but extend just in case + "C4", # flake8-comprehensions -- unnecessary list/map/dict calls +] + lint.ignore = [ ### too opinionated style checks "E501", # too long lines From 118c2d44849b4df661cf07a91d690e91ec1a6069 Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Tue, 27 Aug 2024 23:12:57 +0100 Subject: [PATCH 083/122] ruff: enable UP ruleset for detecting python deprecations --- my/core/__main__.py | 4 ++-- my/core/_deprecated/kompress.py | 10 ++-------- my/core/query.py | 2 +- my/core/query_range.py | 3 +-- my/core/stats.py | 13 +++++++++---- my/core/tests/denylist.py | 3 +-- my/core/util.py | 3 +-- my/time/tz/via_location.py | 2 +- ruff.toml | 9 +++++++++ 9 files changed, 27 insertions(+), 22 deletions(-) diff --git a/my/core/__main__.py b/my/core/__main__.py index 276de26..986b05f 100644 --- a/my/core/__main__.py +++ b/my/core/__main__.py @@ -16,7 +16,7 @@ from typing import Any, Callable, Iterable, List, Optional, Sequence, Type import click -@functools.lru_cache() +@functools.lru_cache def mypy_cmd() -> Optional[Sequence[str]]: try: # preferably, use mypy from current python env @@ -43,7 +43,7 @@ def run_mypy(cfg_path: Path) -> Optional[CompletedProcess]: cmd = mypy_cmd() if cmd is None: return None - mres = run([ + mres = run([ # noqa: UP022 *cmd, '--namespace-packages', '--color-output', # not sure if works?? diff --git a/my/core/_deprecated/kompress.py b/my/core/_deprecated/kompress.py index 89e5745..803e515 100644 --- a/my/core/_deprecated/kompress.py +++ b/my/core/_deprecated/kompress.py @@ -148,14 +148,8 @@ def kexists(path: PathIsh, subpath: str) -> bool: import zipfile -if sys.version_info[:2] >= (3, 8): - # meh... zipfile.Path is not available on 3.7 - zipfile_Path = zipfile.Path -else: - if typing.TYPE_CHECKING: - zipfile_Path = Any - else: - zipfile_Path = object +# meh... zipfile.Path is not available on 3.7 +zipfile_Path = zipfile.Path @total_ordering diff --git a/my/core/query.py b/my/core/query.py index 54cd9db..bc7e222 100644 --- a/my/core/query.py +++ b/my/core/query.py @@ -707,7 +707,7 @@ def test_wrap_unsortable_with_error_and_warning() -> None: res = list(select(_mixed_iter_errors(), order_value=lambda o: isinstance(o, datetime))) assert Counter(type(t).__name__ for t in res) == Counter({"_A": 4, "_B": 2, "Unsortable": 1}) # compare the returned error wrapped in the Unsortable - returned_error = next((o for o in res if isinstance(o, Unsortable))).obj + returned_error = next(o for o in res if isinstance(o, Unsortable)).obj assert "Unhandled error!" == str(returned_error) diff --git a/my/core/query_range.py b/my/core/query_range.py index d077225..761b045 100644 --- a/my/core/query_range.py +++ b/my/core/query_range.py @@ -526,9 +526,8 @@ def test_parse_timedelta_string() -> None: def test_parse_datetime_float() -> None: - pnow = parse_datetime_float("now") - sec_diff = abs((pnow - datetime.now().timestamp())) + sec_diff = abs(pnow - datetime.now().timestamp()) # should probably never fail? could mock time.time # but there seems to be issues with doing that use C-libraries (as time.time) does # https://docs.python.org/3/library/unittest.mock-examples.html#partial-mocking diff --git a/my/core/stats.py b/my/core/stats.py index bfedbd2..85c2a99 100644 --- a/my/core/stats.py +++ b/my/core/stats.py @@ -414,7 +414,9 @@ def test_stat_iterable() -> None: dd = datetime.fromtimestamp(123, tz=timezone.utc) day = timedelta(days=3) - X = NamedTuple('X', [('x', int), ('d', datetime)]) + class X(NamedTuple): + x: int + d: datetime def it(): yield RuntimeError('oops!') @@ -452,9 +454,12 @@ def test_guess_datetime() -> None: dd = fromisoformat('2021-02-01T12:34:56Z') - # ugh.. https://github.com/python/mypy/issues/7281 - A = NamedTuple('A', [('x', int)]) - B = NamedTuple('B', [('x', int), ('created', datetime)]) + class A(NamedTuple): + x: int + + class B(NamedTuple): + x: int + created: datetime assert _guess_datetime(A(x=4)) is None assert _guess_datetime(B(x=4, created=dd)) == dd diff --git a/my/core/tests/denylist.py b/my/core/tests/denylist.py index 8016282..2688319 100644 --- a/my/core/tests/denylist.py +++ b/my/core/tests/denylist.py @@ -91,8 +91,7 @@ def test_denylist(tmp_path: Path) -> None: assert "59.40.113.87" not in [i.addr for i in filtered] - with open(tf, "r") as f: - data_json = json.loads(f.read()) + data_json = json.loads(tf.read_text()) assert data_json == [ { diff --git a/my/core/util.py b/my/core/util.py index 0c596fa..fdd10f9 100644 --- a/my/core/util.py +++ b/my/core/util.py @@ -12,8 +12,7 @@ from .discovery_pure import HPIModule, _is_not_module_src, has_stats, ignored def modules() -> Iterable[HPIModule]: import my - for m in _iter_all_importables(my): - yield m + yield from _iter_all_importables(my) __NOT_HPI_MODULE__ = 'Import this to mark a python file as a helper, not an actual HPI module' diff --git a/my/time/tz/via_location.py b/my/time/tz/via_location.py index 329e330..d74bdc3 100644 --- a/my/time/tz/via_location.py +++ b/my/time/tz/via_location.py @@ -218,7 +218,7 @@ def _iter_tz_depends_on() -> str: day = str(date.today()) hr = datetime.now().hour hr_truncated = hr // mod * mod - return "{}_{}".format(day, hr_truncated) + return f"{day}_{hr_truncated}" # refresh _iter_tzs every few hours -- don't think a better depends_on is possible dynamically diff --git a/ruff.toml b/ruff.toml index db926da..dda279b 100644 --- a/ruff.toml +++ b/ruff.toml @@ -1,7 +1,10 @@ +target-version = "py38" # NOTE: inferred from pyproject.toml if present + lint.extend-select = [ "F", # flakes rules -- default, but extend just in case "E", # pycodestyle -- default, but extend just in case "C4", # flake8-comprehensions -- unnecessary list/map/dict calls + "UP", # detect deprecated python stdlib stuff ] lint.ignore = [ @@ -28,4 +31,10 @@ lint.ignore = [ "F841", # Local variable `count` is assigned to but never used "F401", # imported but unused ### + +### TODO should be fine to use these with from __future__ import annotations? +### there was some issue with cachew though... double check this? + "UP006", # use type instead of Type + "UP007", # use X | Y instead of Union +### ] From 664c40e3e8a590b63e76354ad907fb6d4567494b Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Tue, 27 Aug 2024 23:37:17 +0100 Subject: [PATCH 084/122] ruff: enable FBT rules to detect boolean arguments use without kwargs --- my/body/sleep/common.py | 2 +- my/core/__main__.py | 13 +++++++------ my/core/common.py | 9 +++++---- my/core/denylist.py | 5 +++-- my/core/influxdb.py | 2 +- my/core/konsume.py | 2 +- my/core/query.py | 19 +++++++++++++------ my/core/stats.py | 6 +++--- my/core/structure.py | 2 +- my/core/utils/concurrent.py | 2 +- my/endomondo.py | 2 +- my/google/takeout/parser.py | 2 +- my/jawbone/__init__.py | 2 +- my/location/fallback/all.py | 2 +- my/location/fallback/common.py | 2 +- my/tests/tz.py | 2 +- my/time/tz/via_location.py | 4 ++-- my/topcoder.py | 2 +- ruff.toml | 9 +++++---- 19 files changed, 50 insertions(+), 39 deletions(-) diff --git a/my/body/sleep/common.py b/my/body/sleep/common.py index e84c8d5..1100814 100644 --- a/my/body/sleep/common.py +++ b/my/body/sleep/common.py @@ -7,7 +7,7 @@ class Combine: self.modules = modules @cdf - def dataframe(self, with_temperature: bool=True) -> DataFrameT: + def dataframe(self, *, with_temperature: bool=True) -> DataFrameT: import pandas as pd # todo include 'source'? df = pd.concat([m.dataframe() for m in self.modules]) diff --git a/my/core/__main__.py b/my/core/__main__.py index 986b05f..d3c0cc7 100644 --- a/my/core/__main__.py +++ b/my/core/__main__.py @@ -438,7 +438,7 @@ def _ui_getchar_pick(choices: Sequence[str], prompt: str = 'Select from: ') -> i return result_map[ch] -def _locate_functions_or_prompt(qualified_names: List[str], prompt: bool = True) -> Iterable[Callable[..., Any]]: +def _locate_functions_or_prompt(qualified_names: List[str], *, prompt: bool = True) -> Iterable[Callable[..., Any]]: from .query import QueryException, locate_qualified_function from .stats import is_data_provider @@ -588,7 +588,7 @@ def query_hpi_functions( @click.group() @click.option("--debug", is_flag=True, default=False, help="Show debug logs") -def main(debug: bool) -> None: +def main(*, debug: bool) -> None: ''' Human Programming Interface @@ -637,7 +637,7 @@ def _module_autocomplete(ctx: click.Context, args: Sequence[str], incomplete: st @click.option('-q', '--quick', is_flag=True, help='Only run partial checks (first 100 items)') @click.option('-S', '--skip-config-check', 'skip_conf', is_flag=True, help='Skip configuration check') @click.argument('MODULE', nargs=-1, required=False, shell_complete=_module_autocomplete) -def doctor_cmd(verbose: bool, list_all: bool, quick: bool, skip_conf: bool, module: Sequence[str]) -> None: +def doctor_cmd(*, verbose: bool, list_all: bool, quick: bool, skip_conf: bool, module: Sequence[str]) -> None: ''' Run various checks @@ -671,7 +671,7 @@ def config_create_cmd() -> None: @main.command(name='modules', short_help='list available modules') @click.option('--all', 'list_all', is_flag=True, help='List all modules, including disabled') -def module_cmd(list_all: bool) -> None: +def module_cmd(*, list_all: bool) -> None: '''List available modules''' list_modules(list_all=list_all) @@ -684,7 +684,7 @@ def module_grp() -> None: @module_grp.command(name='requires', short_help='print module reqs') @click.argument('MODULES', shell_complete=_module_autocomplete, nargs=-1, required=True) -def module_requires_cmd(modules: Sequence[str]) -> None: +def module_requires_cmd(*, modules: Sequence[str]) -> None: ''' Print MODULES requirements @@ -701,7 +701,7 @@ def module_requires_cmd(modules: Sequence[str]) -> None: is_flag=True, help='Bypass PEP 668 and install dependencies into the system-wide python package directory.') @click.argument('MODULES', shell_complete=_module_autocomplete, nargs=-1, required=True) -def module_install_cmd(user: bool, parallel: bool, break_system_packages: bool, modules: Sequence[str]) -> None: +def module_install_cmd(*, user: bool, parallel: bool, break_system_packages: bool, modules: Sequence[str]) -> None: ''' Install dependencies for modules using pip @@ -782,6 +782,7 @@ def module_install_cmd(user: bool, parallel: bool, break_system_packages: bool, help='ignore any errors returned as objects from the functions') @click.argument('FUNCTION_NAME', nargs=-1, required=True, shell_complete=_module_autocomplete) def query_cmd( + *, function_name: Sequence[str], output: str, stream: bool, diff --git a/my/core/common.py b/my/core/common.py index ba4ce6b..b97866f 100644 --- a/my/core/common.py +++ b/my/core/common.py @@ -26,10 +26,11 @@ Paths = Union[Sequence[PathIsh], PathIsh] DEFAULT_GLOB = '*' def get_files( - pp: Paths, - glob: str=DEFAULT_GLOB, - sort: bool=True, - guess_compression: bool=True, + pp: Paths, + glob: str=DEFAULT_GLOB, + *, + sort: bool=True, + guess_compression: bool=True, ) -> Tuple[Path, ...]: """ Helper function to avoid boilerplate. diff --git a/my/core/denylist.py b/my/core/denylist.py index 7ca0ddf..92faf2c 100644 --- a/my/core/denylist.py +++ b/my/core/denylist.py @@ -96,6 +96,7 @@ class DenyList: def filter( self, itr: Iterator[T], + *, invert: bool = False, ) -> Iterator[T]: denyf = functools.partial(self._allow, deny_map=self.load()) @@ -103,7 +104,7 @@ class DenyList: return filter(lambda x: not denyf(x), itr) return filter(denyf, itr) - def deny(self, key: str, value: Any, write: bool = False) -> None: + def deny(self, key: str, value: Any, *, write: bool = False) -> None: ''' add a key/value pair to the denylist ''' @@ -111,7 +112,7 @@ class DenyList: self._load() self._deny_raw({key: self._stringify_value(value)}, write=write) - def _deny_raw(self, data: Dict[str, Any], write: bool = False) -> None: + def _deny_raw(self, data: Dict[str, Any], *, write: bool = False) -> None: self._deny_raw_list.append(data) if write: self.write() diff --git a/my/core/influxdb.py b/my/core/influxdb.py index b1d6b9b..25eeba1 100644 --- a/my/core/influxdb.py +++ b/my/core/influxdb.py @@ -135,7 +135,7 @@ def main() -> None: @main.command(name='populate', short_help='populate influxdb') @click.option('--reset', is_flag=True, help='Reset Influx measurements before inserting', show_default=True) @click.argument('FUNCTION_NAME', type=str, required=True) -def populate(function_name: str, reset: bool) -> None: +def populate(*, function_name: str, reset: bool) -> None: from .__main__ import _locate_functions_or_prompt [provider] = list(_locate_functions_or_prompt([function_name])) # todo could have a non-interactive version which populates from all data sources for the provider? diff --git a/my/core/konsume.py b/my/core/konsume.py index ac1b100..0e4a2fe 100644 --- a/my/core/konsume.py +++ b/my/core/konsume.py @@ -131,7 +131,7 @@ class UnconsumedError(Exception): # TODO think about error policy later... @contextmanager -def wrap(j, throw=True) -> Iterator[Zoomable]: +def wrap(j, *, throw=True) -> Iterator[Zoomable]: w, children = _wrap(j) yield w diff --git a/my/core/query.py b/my/core/query.py index bc7e222..daf702d 100644 --- a/my/core/query.py +++ b/my/core/query.py @@ -131,11 +131,12 @@ def attribute_func(obj: T, where: Where, default: Optional[U] = None) -> Optiona def _generate_order_by_func( - obj_res: Res[T], - key: Optional[str] = None, - where_function: Optional[Where] = None, - default: Optional[U] = None, - force_unsortable: bool = False, + obj_res: Res[T], + *, + key: Optional[str] = None, + where_function: Optional[Where] = None, + default: Optional[U] = None, + force_unsortable: bool = False, ) -> Optional[OrderFunc]: """ Accepts an object Res[T] (Instance of some class or Exception) @@ -274,6 +275,7 @@ def _wrap_unsorted(itr: Iterator[ET], orderfunc: OrderFunc) -> Tuple[Iterator[Un # the second being items for which orderfunc returned a non-none value def _handle_unsorted( itr: Iterator[ET], + *, orderfunc: OrderFunc, drop_unsorted: bool, wrap_unsorted: bool @@ -503,7 +505,12 @@ Will attempt to call iter() on the value""") # note: can't just attach sort unsortable values in the same iterable as the # other items because they don't have any lookups for order_key or functions # to handle items in the order_by_lookup dictionary - unsortable, itr = _handle_unsorted(itr, order_by_chosen, drop_unsorted, wrap_unsorted) + unsortable, itr = _handle_unsorted( + itr, + orderfunc=order_by_chosen, + drop_unsorted=drop_unsorted, + wrap_unsorted=wrap_unsorted, + ) # run the sort, with the computed order by function itr = iter(sorted(itr, key=order_by_chosen, reverse=reverse)) # type: ignore[arg-type] diff --git a/my/core/stats.py b/my/core/stats.py index 85c2a99..4c9fb0c 100644 --- a/my/core/stats.py +++ b/my/core/stats.py @@ -30,7 +30,7 @@ Stats = Dict[str, Any] class StatsFun(Protocol): - def __call__(self, quick: bool = False) -> Stats: ... + def __call__(self, *, quick: bool = False) -> Stats: ... # global state that turns on/off quick stats @@ -176,7 +176,7 @@ def guess_stats(module: ModuleType) -> Optional[StatsFun]: if len(providers) == 0: return None - def auto_stats(quick: bool = False) -> Stats: + def auto_stats(*, quick: bool = False) -> Stats: res = {} for k, v in providers.items(): res.update(stat(v, quick=quick, name=k)) @@ -355,7 +355,7 @@ def _stat_item(item): return _guess_datetime(item) -def _stat_iterable(it: Iterable[Any], quick: bool = False) -> Stats: +def _stat_iterable(it: Iterable[Any], *, quick: bool = False) -> Stats: from more_itertools import first, ilen, take # todo not sure if there is something in more_itertools to compute this? diff --git a/my/core/structure.py b/my/core/structure.py index df25e37..149a22a 100644 --- a/my/core/structure.py +++ b/my/core/structure.py @@ -12,7 +12,7 @@ from .logging import make_logger logger = make_logger(__name__, level="info") -def _structure_exists(base_dir: Path, paths: Sequence[str], partial: bool = False) -> bool: +def _structure_exists(base_dir: Path, paths: Sequence[str], *, partial: bool = False) -> bool: """ Helper function for match_structure to check if all subpaths exist at some base directory diff --git a/my/core/utils/concurrent.py b/my/core/utils/concurrent.py index 3553cd9..5f11ab0 100644 --- a/my/core/utils/concurrent.py +++ b/my/core/utils/concurrent.py @@ -47,5 +47,5 @@ class DummyExecutor(Executor): return f - def shutdown(self, wait: bool = True, **kwargs) -> None: + def shutdown(self, wait: bool = True, **kwargs) -> None: # noqa: FBT001,FBT002 self._shutdown = True diff --git a/my/endomondo.py b/my/endomondo.py index d314e97..1d7acc2 100644 --- a/my/endomondo.py +++ b/my/endomondo.py @@ -44,7 +44,7 @@ def workouts() -> Iterable[Res[Workout]]: from .core.pandas import check_dataframe, DataFrameT @check_dataframe -def dataframe(defensive: bool=True) -> DataFrameT: +def dataframe(*, defensive: bool=True) -> DataFrameT: def it(): for w in workouts(): if isinstance(w, Exception): diff --git a/my/google/takeout/parser.py b/my/google/takeout/parser.py index c4e5682..258ab96 100644 --- a/my/google/takeout/parser.py +++ b/my/google/takeout/parser.py @@ -91,7 +91,7 @@ def _cachew_depends_on() -> List[str]: # ResultsType is a Union of all of the models in google_takeout_parser @mcachew(depends_on=_cachew_depends_on, logger=logger, force_file=True) -def events(disable_takeout_cache: bool = DISABLE_TAKEOUT_CACHE) -> CacheResults: +def events(disable_takeout_cache: bool = DISABLE_TAKEOUT_CACHE) -> CacheResults: # noqa: FBT001 error_policy = config.error_policy count = 0 emitted = GoogleEventSet() diff --git a/my/jawbone/__init__.py b/my/jawbone/__init__.py index 5d43296..1706a54 100644 --- a/my/jawbone/__init__.py +++ b/my/jawbone/__init__.py @@ -174,7 +174,7 @@ def hhmm(time: datetime): # return fromstart / tick -def plot_one(sleep: SleepEntry, fig, axes, xlims=None, showtext=True): +def plot_one(sleep: SleepEntry, fig, axes, xlims=None, *, showtext=True): import matplotlib.dates as mdates # type: ignore[import-not-found] span = sleep.completed - sleep.created diff --git a/my/location/fallback/all.py b/my/location/fallback/all.py index 0c7b8cd..a5daa05 100644 --- a/my/location/fallback/all.py +++ b/my/location/fallback/all.py @@ -24,7 +24,7 @@ def fallback_estimators() -> Iterator[LocationEstimator]: yield _home_estimate -def estimate_location(dt: DateExact, first_match: bool=False, under_accuracy: Optional[int] = None) -> FallbackLocation: +def estimate_location(dt: DateExact, *, first_match: bool=False, under_accuracy: Optional[int] = None) -> FallbackLocation: loc = estimate_from(dt, estimators=list(fallback_estimators()), first_match=first_match, under_accuracy=under_accuracy) # should never happen if the user has home configured if loc is None: diff --git a/my/location/fallback/common.py b/my/location/fallback/common.py index fd508c6..13bc603 100644 --- a/my/location/fallback/common.py +++ b/my/location/fallback/common.py @@ -18,7 +18,7 @@ class FallbackLocation(LocationProtocol): elevation: Optional[float] = None datasource: Optional[str] = None # which module provided this, useful for debugging - def to_location(self, end: bool = False) -> Location: + def to_location(self, *, end: bool = False) -> Location: ''' by default the start date is used for the location If end is True, the start date + duration is used diff --git a/my/tests/tz.py b/my/tests/tz.py index db88278..92d8f3b 100644 --- a/my/tests/tz.py +++ b/my/tests/tz.py @@ -18,7 +18,7 @@ def getzone(dt: datetime) -> str: @pytest.mark.parametrize('fast', [False, True]) -def test_iter_tzs(fast: bool, config) -> None: +def test_iter_tzs(*, fast: bool, config) -> None: # TODO hmm.. maybe need to make sure we start with empty config? config.time.tz.via_location.fast = fast diff --git a/my/time/tz/via_location.py b/my/time/tz/via_location.py index d74bdc3..156a5db 100644 --- a/my/time/tz/via_location.py +++ b/my/time/tz/via_location.py @@ -94,7 +94,7 @@ logger = make_logger(__name__) @lru_cache(None) -def _timezone_finder(fast: bool) -> Any: +def _timezone_finder(*, fast: bool) -> Any: if fast: # less precise, but faster from timezonefinder import TimezoneFinderL as Finder @@ -304,7 +304,7 @@ def localize(dt: datetime) -> datetime_aware: return tz.localize(dt) -def stats(quick: bool = False) -> Stats: +def stats(*, quick: bool = False) -> Stats: if quick: prev, config.sort_locations = config.sort_locations, False res = {'first': next(_iter_local_dates())} diff --git a/my/topcoder.py b/my/topcoder.py index 8e39252..07f71be 100644 --- a/my/topcoder.py +++ b/my/topcoder.py @@ -58,7 +58,7 @@ def _parse_one(p: Path) -> Iterator[Res[Competition]]: h.pop_if_primitive('version', 'id') h = h.zoom('result') - h.check('success', True) + h.check('success', expected=True) h.check('status', 200) h.pop_if_primitive('metadata') diff --git a/ruff.toml b/ruff.toml index dda279b..a8af399 100644 --- a/ruff.toml +++ b/ruff.toml @@ -1,10 +1,11 @@ target-version = "py38" # NOTE: inferred from pyproject.toml if present lint.extend-select = [ - "F", # flakes rules -- default, but extend just in case - "E", # pycodestyle -- default, but extend just in case - "C4", # flake8-comprehensions -- unnecessary list/map/dict calls - "UP", # detect deprecated python stdlib stuff + "F", # flakes rules -- default, but extend just in case + "E", # pycodestyle -- default, but extend just in case + "C4", # flake8-comprehensions -- unnecessary list/map/dict calls + "UP", # detect deprecated python stdlib stuff + "FBT", # detect use of boolean arguments ] lint.ignore = [ From b594377a599acbc14eb9a2b17e88ca87fcc1a727 Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Wed, 28 Aug 2024 00:00:54 +0100 Subject: [PATCH 085/122] ruff: enable RUF ruleset --- my/arbtt.py | 2 +- my/bluemaestro.py | 4 ++-- my/core/__main__.py | 2 +- my/core/error.py | 4 ++-- my/core/source.py | 2 +- my/core/structure.py | 22 +++++++++++----------- my/core/time.py | 2 +- my/core/util.py | 2 +- my/experimental/destructive_parsing.py | 2 +- my/google/takeout/html.py | 2 +- my/location/common.py | 2 +- my/photos/main.py | 2 +- my/polar.py | 2 +- my/twitter/android.py | 5 +++-- ruff.toml | 3 +++ 15 files changed, 31 insertions(+), 27 deletions(-) diff --git a/my/arbtt.py b/my/arbtt.py index 6de8cb2..2bcf291 100644 --- a/my/arbtt.py +++ b/my/arbtt.py @@ -81,7 +81,7 @@ def entries() -> Iterable[Entry]: cmds = [base] # rely on default else: # otherwise, 'merge' them - cmds = [base + ['--logfile', f] for f in inps] + cmds = [[*base, '--logfile', f] for f in inps] import ijson.backends.yajl2_cffi as ijson # type: ignore from subprocess import Popen, PIPE diff --git a/my/bluemaestro.py b/my/bluemaestro.py index 12c114f..50338bb 100644 --- a/my/bluemaestro.py +++ b/my/bluemaestro.py @@ -104,7 +104,7 @@ def measurements() -> Iterable[Res[Measurement]]: f'SELECT "{path.name}" as name, Time, Temperature, Humidity, Pressure, Dewpoint FROM data ORDER BY log_index' ) oldfmt = True - db_dts = list(db.execute('SELECT last_download FROM info'))[0][0] + [(db_dts,)] = db.execute('SELECT last_download FROM info') if db_dts == 'N/A': # ??? happens for 20180923-20180928 continue @@ -137,7 +137,7 @@ def measurements() -> Iterable[Res[Measurement]]: processed_tables |= set(log_tables) # todo use later? - frequencies = [list(db.execute(f'SELECT interval from {t.replace("_log", "_meta")}'))[0][0] for t in log_tables] + frequencies = [list(db.execute(f'SELECT interval from {t.replace("_log", "_meta")}'))[0][0] for t in log_tables] # noqa: RUF015 # todo could just filter out the older datapoints?? dunno. diff --git a/my/core/__main__.py b/my/core/__main__.py index d3c0cc7..3af8e08 100644 --- a/my/core/__main__.py +++ b/my/core/__main__.py @@ -392,7 +392,7 @@ def module_install(*, user: bool, module: Sequence[str], parallel: bool=False, b # I think it only helps for pypi artifacts (not git!), # and only if they weren't cached for r in requirements: - cmds.append(pre_cmd + [r]) + cmds.append([*pre_cmd, r]) else: if parallel: warning('parallel install is not supported on this platform, installing sequentially...') diff --git a/my/core/error.py b/my/core/error.py index 7489f69..cd8d093 100644 --- a/my/core/error.py +++ b/my/core/error.py @@ -153,7 +153,7 @@ def test_sort_res_by() -> None: Exc('last'), ] - results2 = sort_res_by(ress + [0], lambda x: int(x)) + results2 = sort_res_by([*ress, 0], lambda x: int(x)) assert results2 == [Exc('last'), 0] + results[:-1] assert sort_res_by(['caba', 'a', 'aba', 'daba'], key=lambda x: len(x)) == ['a', 'aba', 'caba', 'daba'] @@ -166,7 +166,7 @@ def test_sort_res_by() -> None: def set_error_datetime(e: Exception, dt: Optional[datetime]) -> None: if dt is None: return - e.args = e.args + (dt,) + e.args = (*e.args, dt) # todo not sure if should return new exception? diff --git a/my/core/source.py b/my/core/source.py index 6e0a78a..4510ef0 100644 --- a/my/core/source.py +++ b/my/core/source.py @@ -61,7 +61,7 @@ def import_source( warnings.warn(f"""If you don't want to use this module, to hide this message, add '{module_name}' to your core config disabled_modules in your config, like: class core: - disabled_modules = [{repr(module_name)}] + disabled_modules = [{module_name!r}] """) # try to check if this is a config error or based on dependencies not being installed if isinstance(err, (ImportError, AttributeError)): diff --git a/my/core/structure.py b/my/core/structure.py index 149a22a..be5b307 100644 --- a/my/core/structure.py +++ b/my/core/structure.py @@ -67,21 +67,21 @@ def match_structure( export_dir ├── exp_2020 - │   ├── channel_data - │   │   ├── data1 - │   │   └── data2 - │   ├── index.json - │   ├── messages - │   │   └── messages.csv - │   └── profile - │   └── settings.json + │ ├── channel_data + │ │ ├── data1 + │ │ └── data2 + │ ├── index.json + │ ├── messages + │ │ └── messages.csv + │ └── profile + │ └── settings.json └── exp_2021 ├── channel_data - │   ├── data1 - │   └── data2 + │ ├── data1 + │ └── data2 ├── index.json ├── messages - │   └── messages.csv + │ └── messages.csv └── profile └── settings.json diff --git a/my/core/time.py b/my/core/time.py index 83a407b..5a47c3d 100644 --- a/my/core/time.py +++ b/my/core/time.py @@ -21,7 +21,7 @@ def user_forced() -> Sequence[str]: def _abbr_to_timezone_map() -> Dict[str, pytz.BaseTzInfo]: # also force UTC to always correspond to utc # this makes more sense than Zulu it ends up by default - timezones = pytz.all_timezones + ['UTC'] + list(user_forced()) + timezones = [*pytz.all_timezones, 'UTC', *user_forced()] res: Dict[str, pytz.BaseTzInfo] = {} for tzname in timezones: diff --git a/my/core/util.py b/my/core/util.py index fdd10f9..b49acf6 100644 --- a/my/core/util.py +++ b/my/core/util.py @@ -74,7 +74,7 @@ def _discover_path_importables(pkg_pth: Path, pkg_name: str) -> Iterable[HPIModu continue rel_pt = pkg_dir_path.relative_to(pkg_pth) - pkg_pref = '.'.join((pkg_name, ) + rel_pt.parts) + pkg_pref = '.'.join((pkg_name, *rel_pt.parts)) yield from _walk_packages( (str(pkg_dir_path), ), prefix=f'{pkg_pref}.', diff --git a/my/experimental/destructive_parsing.py b/my/experimental/destructive_parsing.py index 05c5920..056cc0b 100644 --- a/my/experimental/destructive_parsing.py +++ b/my/experimental/destructive_parsing.py @@ -26,7 +26,7 @@ class Helper: assert actual == expected, (key, actual, expected) def zoom(self, key: str) -> 'Helper': - return self.manager.helper(item=self.item.pop(key), path=self.path + (key,)) + return self.manager.helper(item=self.item.pop(key), path=(*self.path, key)) def is_empty(x) -> bool: diff --git a/my/google/takeout/html.py b/my/google/takeout/html.py index 3ce692c..750beac 100644 --- a/my/google/takeout/html.py +++ b/my/google/takeout/html.py @@ -122,7 +122,7 @@ class TakeoutHTMLParser(HTMLParser): # JamiexxVEVO # Jun 21, 2018, 5:48:34 AM # Products: - #  YouTube + # YouTube def handle_data(self, data): if self.state == State.OUTSIDE: if data[:-1].strip() in ("Watched", "Visited"): diff --git a/my/location/common.py b/my/location/common.py index 510e005..f406370 100644 --- a/my/location/common.py +++ b/my/location/common.py @@ -70,7 +70,7 @@ def locations_to_gpx(locations: Iterable[LocationProtocol], buffer: TextIO) -> I ) except AttributeError: yield TypeError( - f"Expected a Location or Location-like object, got {type(location)} {repr(location)}" + f"Expected a Location or Location-like object, got {type(location)} {location!r}" ) continue gpx_segment.points.append(point) diff --git a/my/photos/main.py b/my/photos/main.py index 6262eac..63a6fea 100644 --- a/my/photos/main.py +++ b/my/photos/main.py @@ -209,7 +209,7 @@ def print_all() -> None: if isinstance(p, Exception): print('ERROR!', p) else: - print(f"{str(p.dt):25} {p.path} {p.geo}") + print(f"{p.dt!s:25} {p.path} {p.geo}") # todo cachew -- improve AttributeError: type object 'tuple' has no attribute '__annotations__' -- improve errors? # todo cachew -- invalidate if function code changed? diff --git a/my/polar.py b/my/polar.py index cd2c719..197de18 100644 --- a/my/polar.py +++ b/my/polar.py @@ -27,7 +27,7 @@ class polar(user_config): ''' Polar config is optional, you only need it if you want to specify custom 'polar_dir' ''' - polar_dir: PathIsh = Path('~/.polar').expanduser() + polar_dir: PathIsh = Path('~/.polar').expanduser() # noqa: RUF009 defensive: bool = True # pass False if you want it to fail faster on errors (useful for debugging) diff --git a/my/twitter/android.py b/my/twitter/android.py index f40ad0e..7adfeb6 100644 --- a/my/twitter/android.py +++ b/my/twitter/android.py @@ -155,7 +155,7 @@ _SELECT_OWN_TWEETS = '_SELECT_OWN_TWEETS' def get_own_user_id(conn) -> str: # unclear what's the reliable way to query it, so we use multiple different ones and arbitrate # NOTE: 'SELECT DISTINCT ev_owner_id FROM lists' doesn't work, might include lists from other people? - res = set() + res: Set[str] = set() for q in [ 'SELECT DISTINCT list_mapping_user_id FROM list_mapping', 'SELECT DISTINCT owner_id FROM cursors', @@ -164,7 +164,8 @@ def get_own_user_id(conn) -> str: for (r,) in conn.execute(q): res.add(r) assert len(res) == 1, res - return str(list(res)[0]) + [r] = res + return r # NOTE: diff --git a/ruff.toml b/ruff.toml index a8af399..2b77622 100644 --- a/ruff.toml +++ b/ruff.toml @@ -6,6 +6,7 @@ lint.extend-select = [ "C4", # flake8-comprehensions -- unnecessary list/map/dict calls "UP", # detect deprecated python stdlib stuff "FBT", # detect use of boolean arguments + "RUF", # various ruff-specific rules ] lint.ignore = [ @@ -38,4 +39,6 @@ lint.ignore = [ "UP006", # use type instead of Type "UP007", # use X | Y instead of Union ### + "RUF100", # unused noqa -- handle later + "RUF012", # mutable class attrs should be annotated with ClassVar... ugh pretty annoying for user configs ] From d0df8e8f2db2dd0a1776fa7bad54f2bbbba1bde1 Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Wed, 28 Aug 2024 00:29:06 +0100 Subject: [PATCH 086/122] ruff: enable PLR rules and fix bug in my.github.gdpr._is_bot --- my/github/gdpr.py | 2 +- ruff.toml | 16 ++++++++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/my/github/gdpr.py b/my/github/gdpr.py index 4ca8e84..acbeb8f 100644 --- a/my/github/gdpr.py +++ b/my/github/gdpr.py @@ -145,7 +145,7 @@ def _parse_repository(d: Dict) -> Event: def _is_bot(user: Optional[str]) -> bool: if user is None: return False - return "[bot]" in "user" + return "[bot]" in user def _parse_issue_comment(d: Dict) -> Event: diff --git a/ruff.toml b/ruff.toml index 2b77622..69af75a 100644 --- a/ruff.toml +++ b/ruff.toml @@ -7,6 +7,10 @@ lint.extend-select = [ "UP", # detect deprecated python stdlib stuff "FBT", # detect use of boolean arguments "RUF", # various ruff-specific rules + + "PLR", + # "S", # bandit (security checks) -- tends to be not very useful, lots of nitpicks + # "DTZ", # datetimes checks -- complaining about missing tz and mostly false positives ] lint.ignore = [ @@ -41,4 +45,16 @@ lint.ignore = [ ### "RUF100", # unused noqa -- handle later "RUF012", # mutable class attrs should be annotated with ClassVar... ugh pretty annoying for user configs + +### these are just nitpicky, we usually know better + "PLR0911", # too many return statements + "PLR0912", # too many branches + "PLR0913", # too many function arguments + "PLR0915", # too many statements + "PLR1714", # consider merging multiple comparisons + "PLR2044", # line with empty comment + "PLR5501", # use elif instead of else if + "PLR2004", # magic value in comparison -- super annoying in tests +### + "PLR0402", # import X.Y as Y -- TODO maybe consider enabling it, but double check ] From 72cc8ff3acae427232c28ca32080f22c9164f7d7 Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Wed, 28 Aug 2024 01:13:18 +0100 Subject: [PATCH 087/122] ruff: enable B warnings (mainly suppressed exceptions and unused variables) --- my/bluemaestro.py | 2 +- my/body/exercise/cross_trainer.py | 2 +- my/coding/github.py | 13 ++++++++----- my/core/__main__.py | 4 ++-- my/core/cachew.py | 6 ++++-- my/core/common.py | 7 +++---- my/core/error.py | 2 +- my/core/hpi_compat.py | 4 ++-- my/core/init.py | 6 +++--- my/core/logging.py | 6 +++--- my/core/orgmode.py | 12 ++++++------ my/core/query.py | 4 ++-- my/core/query_range.py | 2 +- my/core/source.py | 2 +- my/core/stats.py | 2 +- my/core/util.py | 4 ++-- my/core/utils/itertools.py | 7 ++++--- my/core/warnings.py | 10 +++++----- my/jawbone/__init__.py | 2 +- my/location/google.py | 11 ++++++----- my/media/imdb.py | 2 +- my/polar.py | 4 ++-- my/reddit/rexport.py | 6 +++--- my/rss/common.py | 2 +- my/tests/location/google.py | 4 ++-- my/tests/shared_tz_config.py | 4 ++-- my/time/tz/common.py | 2 +- my/twitter/archive.py | 4 ++-- ruff.toml | 10 +++++++++- tests/github.py | 4 +++- 30 files changed, 83 insertions(+), 67 deletions(-) diff --git a/my/bluemaestro.py b/my/bluemaestro.py index 50338bb..5d0968b 100644 --- a/my/bluemaestro.py +++ b/my/bluemaestro.py @@ -153,7 +153,7 @@ def measurements() -> Iterable[Res[Measurement]]: oldfmt = False db_dt = None - for i, (name, tsc, temp, hum, pres, dewp) in enumerate(datas): + for (name, tsc, temp, hum, pres, dewp) in datas: if is_bad_table(name): continue diff --git a/my/body/exercise/cross_trainer.py b/my/body/exercise/cross_trainer.py index d073f43..edbb557 100644 --- a/my/body/exercise/cross_trainer.py +++ b/my/body/exercise/cross_trainer.py @@ -105,7 +105,7 @@ def dataframe() -> DataFrameT: rows = [] idxs = [] # type: ignore[var-annotated] NO_ENDOMONDO = 'no endomondo matches' - for i, row in mdf.iterrows(): + for _i, row in mdf.iterrows(): rd = row.to_dict() mdate = row['date'] if pd.isna(mdate): diff --git a/my/coding/github.py b/my/coding/github.py index 9358b04..de64f05 100644 --- a/my/coding/github.py +++ b/my/coding/github.py @@ -1,9 +1,12 @@ -import warnings +from typing import TYPE_CHECKING -warnings.warn('my.coding.github is deprecated! Please use my.github.all instead!') +from my.core import warnings + +warnings.high('my.coding.github is deprecated! Please use my.github.all instead!') # todo why aren't DeprecationWarning shown by default?? -from ..github.all import events, get_events +if not TYPE_CHECKING: + from ..github.all import events, get_events -# todo deprecate properly -iter_events = events + # todo deprecate properly + iter_events = events diff --git a/my/core/__main__.py b/my/core/__main__.py index 3af8e08..c5e4552 100644 --- a/my/core/__main__.py +++ b/my/core/__main__.py @@ -456,9 +456,9 @@ def _locate_functions_or_prompt(qualified_names: List[str], *, prompt: bool = Tr # user to select a 'data provider' like function try: mod = importlib.import_module(qualname) - except Exception: + except Exception as ie: eprint(f"During fallback, importing '{qualname}' as module failed") - raise qr_err + raise qr_err from ie # find data providers in this module data_providers = [f for _, f in inspect.getmembers(mod, inspect.isfunction) if is_data_provider(f)] diff --git a/my/core/cachew.py b/my/core/cachew.py index e0e7adf..dc6ed79 100644 --- a/my/core/cachew.py +++ b/my/core/cachew.py @@ -2,7 +2,6 @@ from .internal import assert_subpackage; assert_subpackage(__name__) import logging import sys -import warnings from contextlib import contextmanager from pathlib import Path from typing import ( @@ -20,6 +19,9 @@ from typing import ( import appdirs # type: ignore[import-untyped] +from . import warnings + + PathIsh = Union[str, Path] # avoid circular import from .common @@ -116,7 +118,7 @@ def _mcachew_impl(cache_path=_cache_path_dflt, **kwargs): try: import cachew except ModuleNotFoundError: - warnings.warn('cachew library not found. You might want to install it to speed things up. See https://github.com/karlicoss/cachew') + warnings.high('cachew library not found. You might want to install it to speed things up. See https://github.com/karlicoss/cachew') return lambda orig_func: orig_func else: kwargs['cache_path'] = cache_path diff --git a/my/core/common.py b/my/core/common.py index b97866f..5f8d03a 100644 --- a/my/core/common.py +++ b/my/core/common.py @@ -1,5 +1,4 @@ import os -import warnings from glob import glob as do_glob from pathlib import Path from typing import ( @@ -15,7 +14,7 @@ from typing import ( ) from . import compat -from . import warnings as core_warnings +from . import warnings as warnings # some helper functions # TODO start deprecating this? soon we'd be able to use Path | str syntax which is shorter and more explicit @@ -63,7 +62,7 @@ def get_files( gs = str(src) if '*' in gs: if glob != DEFAULT_GLOB: - warnings.warn(f"{caller()}: treating {gs} as glob path. Explicit glob={glob} argument is ignored!") + warnings.medium(f"{caller()}: treating {gs} as glob path. Explicit glob={glob} argument is ignored!") paths.extend(map(Path, do_glob(gs))) elif os.path.isdir(str(src)): # NOTE: we're using os.path here on purpose instead of src.is_dir @@ -85,7 +84,7 @@ def get_files( if len(paths) == 0: # todo make it conditionally defensive based on some global settings - core_warnings.high(f''' + warnings.high(f''' {caller()}: no paths were matched against {pp}. This might result in missing data. Likely, the directory you passed is empty. '''.strip()) # traceback is useful to figure out what config caused it? diff --git a/my/core/error.py b/my/core/error.py index cd8d093..e869614 100644 --- a/my/core/error.py +++ b/my/core/error.py @@ -119,7 +119,7 @@ def sort_res_by(items: Iterable[Res[T]], key: Callable[[Any], K]) -> List[Res[T] group = [] results: List[Res[T]] = [] - for v, grp in sorted(groups, key=lambda p: p[0]): # type: ignore[return-value, arg-type] # TODO SupportsLessThan?? + for _v, grp in sorted(groups, key=lambda p: p[0]): # type: ignore[return-value, arg-type] # TODO SupportsLessThan?? results.extend(grp) results.extend(group) # handle last group (it will always be errors only) diff --git a/my/core/hpi_compat.py b/my/core/hpi_compat.py index bad0b17..9330e49 100644 --- a/my/core/hpi_compat.py +++ b/my/core/hpi_compat.py @@ -6,7 +6,7 @@ import inspect import os import re from types import ModuleType -from typing import Iterator, List, Optional, TypeVar +from typing import Iterator, List, Optional, Sequence, TypeVar from . import warnings @@ -71,7 +71,7 @@ def pre_pip_dal_handler( name: str, e: ModuleNotFoundError, cfg, - requires=[], + requires: Sequence[str] = (), ) -> ModuleType: ''' https://github.com/karlicoss/HPI/issues/79 diff --git a/my/core/init.py b/my/core/init.py index 49148de..7a30955 100644 --- a/my/core/init.py +++ b/my/core/init.py @@ -25,7 +25,7 @@ def setup_config() -> None: warnings.warn(f""" 'my.config' package isn't found! (expected at '{mycfg_dir}'). This is likely to result in issues. See https://github.com/karlicoss/HPI/blob/master/doc/SETUP.org#setting-up-the-modules for more info. -""".strip()) +""".strip(), stacklevel=1) return mpath = str(mycfg_dir) @@ -47,7 +47,7 @@ See https://github.com/karlicoss/HPI/blob/master/doc/SETUP.org#setting-up-the-mo warnings.warn(f""" Importing 'my.config' failed! (error: {ex}). This is likely to result in issues. See https://github.com/karlicoss/HPI/blob/master/doc/SETUP.org#setting-up-the-modules for more info. -""") +""", stacklevel=1) else: # defensive just in case -- __file__ may not be present if there is some dynamic magic involved used_config_file = getattr(my.config, '__file__', None) @@ -63,7 +63,7 @@ See https://github.com/karlicoss/HPI/blob/master/doc/SETUP.org#setting-up-the-mo Expected my.config to be located at {mycfg_dir}, but instead its path is {used_config_path}. This will likely cause issues down the line -- double check {mycfg_dir} structure. See https://github.com/karlicoss/HPI/blob/master/doc/SETUP.org#setting-up-the-modules for more info. -""", +""", stacklevel=1 ) diff --git a/my/core/logging.py b/my/core/logging.py index 734c1e0..bdee9aa 100644 --- a/my/core/logging.py +++ b/my/core/logging.py @@ -15,7 +15,7 @@ def test() -> None: ## prepare exception for later try: - None.whatever # type: ignore[attr-defined] + None.whatever # type: ignore[attr-defined] # noqa: B018 except Exception as e: ex = e ## @@ -146,7 +146,7 @@ def _setup_handlers_and_formatters(name: str) -> None: # try colorlog first, so user gets nice colored logs import colorlog except ModuleNotFoundError: - warnings.warn("You might want to 'pip install colorlog' for nice colored logs") + warnings.warn("You might want to 'pip install colorlog' for nice colored logs", stacklevel=1) formatter = logging.Formatter(FORMAT_NOCOLOR) else: # log_color/reset are specific to colorlog @@ -233,7 +233,7 @@ def get_enlighten(): try: import enlighten # type: ignore[import-untyped] except ModuleNotFoundError: - warnings.warn("You might want to 'pip install enlighten' for a nice progress bar") + warnings.warn("You might want to 'pip install enlighten' for a nice progress bar", stacklevel=1) return Mock() diff --git a/my/core/orgmode.py b/my/core/orgmode.py index d9a254c..c70ded6 100644 --- a/my/core/orgmode.py +++ b/my/core/orgmode.py @@ -6,12 +6,12 @@ from datetime import datetime def parse_org_datetime(s: str) -> datetime: s = s.strip('[]') - for fmt, cl in [ - ("%Y-%m-%d %a %H:%M", datetime), - ("%Y-%m-%d %H:%M" , datetime), - # todo not sure about these... fallback on 00:00? - # ("%Y-%m-%d %a" , date), - # ("%Y-%m-%d" , date), + for fmt, _cls in [ + ("%Y-%m-%d %a %H:%M", datetime), + ("%Y-%m-%d %H:%M" , datetime), + # todo not sure about these... fallback on 00:00? + # ("%Y-%m-%d %a" , date), + # ("%Y-%m-%d" , date), ]: try: return datetime.strptime(s, fmt) diff --git a/my/core/query.py b/my/core/query.py index daf702d..c337e5c 100644 --- a/my/core/query.py +++ b/my/core/query.py @@ -72,7 +72,7 @@ def locate_function(module_name: str, function_name: str) -> Callable[[], Iterab if func is not None and callable(func): return func except Exception as e: - raise QueryException(str(e)) + raise QueryException(str(e)) # noqa: B904 raise QueryException(f"Could not find function '{function_name}' in '{module_name}'") @@ -468,7 +468,7 @@ Will attempt to call iter() on the value""") try: itr: Iterator[ET] = iter(it) except TypeError as t: - raise QueryException("Could not convert input src to an Iterator: " + str(t)) + raise QueryException("Could not convert input src to an Iterator: " + str(t)) # noqa: B904 # if both drop_exceptions and drop_exceptions are provided for some reason, # should raise exceptions before dropping them diff --git a/my/core/query_range.py b/my/core/query_range.py index 761b045..0a1b321 100644 --- a/my/core/query_range.py +++ b/my/core/query_range.py @@ -109,7 +109,7 @@ def _datelike_to_float(dl: Any) -> float: try: return parse_datetime_float(dl) except QueryException as q: - raise QueryException(f"While attempting to extract datetime from {dl}, to order by datetime:\n\n" + str(q)) + raise QueryException(f"While attempting to extract datetime from {dl}, to order by datetime:\n\n" + str(q)) # noqa: B904 class RangeTuple(NamedTuple): diff --git a/my/core/source.py b/my/core/source.py index 4510ef0..52c58c1 100644 --- a/my/core/source.py +++ b/my/core/source.py @@ -62,7 +62,7 @@ def import_source( class core: disabled_modules = [{module_name!r}] -""") +""", stacklevel=1) # try to check if this is a config error or based on dependencies not being installed if isinstance(err, (ImportError, AttributeError)): matched_config_err = warn_my_config_import_error(err, module_name=module_name, help_url=help_url) diff --git a/my/core/stats.py b/my/core/stats.py index 4c9fb0c..aa05355 100644 --- a/my/core/stats.py +++ b/my/core/stats.py @@ -440,7 +440,7 @@ def _guess_datetime(x: Any) -> Optional[datetime]: d = asdict(x) except: # noqa: E722 bare except return None - for k, v in d.items(): + for _k, v in d.items(): if isinstance(v, datetime): return v return None diff --git a/my/core/util.py b/my/core/util.py index b49acf6..fb3edf8 100644 --- a/my/core/util.py +++ b/my/core/util.py @@ -93,11 +93,11 @@ def _discover_path_importables(pkg_pth: Path, pkg_name: str) -> Iterable[HPIModu def _walk_packages(path: Iterable[str], prefix: str='', onerror=None) -> Iterable[HPIModule]: """ Modified version of https://github.com/python/cpython/blob/d50a0700265536a20bcce3fb108c954746d97625/Lib/pkgutil.py#L53, - to alvoid importing modules that are skipped + to avoid importing modules that are skipped """ from .core_config import config - def seen(p, m={}): + def seen(p, m={}): # noqa: B006 if p in m: return True m[p] = True diff --git a/my/core/utils/itertools.py b/my/core/utils/itertools.py index 66f82bd..b945ad8 100644 --- a/my/core/utils/itertools.py +++ b/my/core/utils/itertools.py @@ -24,6 +24,8 @@ import more_itertools from decorator import decorator from ..compat import ParamSpec +from .. import warnings as core_warnings + T = TypeVar('T') K = TypeVar('K') @@ -142,8 +144,7 @@ def _warn_if_empty(func, *args, **kwargs): if isinstance(iterable, Sized): sz = len(iterable) if sz == 0: - # todo use hpi warnings here? - warnings.warn(f"Function {func} returned empty container, make sure your config paths are correct") + core_warnings.medium(f"Function {func} returned empty container, make sure your config paths are correct") return iterable else: # must be an iterator @@ -153,7 +154,7 @@ def _warn_if_empty(func, *args, **kwargs): yield i empty = False if empty: - warnings.warn(f"Function {func} didn't emit any data, make sure your config paths are correct") + core_warnings.medium(f"Function {func} didn't emit any data, make sure your config paths are correct") return wit() diff --git a/my/core/warnings.py b/my/core/warnings.py index 82e539b..2ffc3e4 100644 --- a/my/core/warnings.py +++ b/my/core/warnings.py @@ -12,7 +12,7 @@ from typing import TYPE_CHECKING, Optional import click -def _colorize(x: str, color: Optional[str]=None) -> str: +def _colorize(x: str, color: Optional[str] = None) -> str: if color is None: return x @@ -24,10 +24,10 @@ def _colorize(x: str, color: Optional[str]=None) -> str: return click.style(x, fg=color) -def _warn(message: str, *args, color: Optional[str]=None, **kwargs) -> None: +def _warn(message: str, *args, color: Optional[str] = None, **kwargs) -> None: stacklevel = kwargs.get('stacklevel', 1) - kwargs['stacklevel'] = stacklevel + 2 # +1 for this function, +1 for medium/high wrapper - warnings.warn(_colorize(message, color=color), *args, **kwargs) + kwargs['stacklevel'] = stacklevel + 2 # +1 for this function, +1 for medium/high wrapper + warnings.warn(_colorize(message, color=color), *args, **kwargs) # noqa: B028 def low(message: str, *args, **kwargs) -> None: @@ -55,4 +55,4 @@ if not TYPE_CHECKING: def warn(*args, **kwargs): import warnings - return warnings.warn(*args, **kwargs) + return warnings.warn(*args, **kwargs) # noqa: B028 diff --git a/my/jawbone/__init__.py b/my/jawbone/__init__.py index 1706a54..affe230 100644 --- a/my/jawbone/__init__.py +++ b/my/jawbone/__init__.py @@ -274,7 +274,7 @@ def plot() -> None: fig: Figure = plt.figure(figsize=(15, sleeps_count * 1)) axarr = fig.subplots(nrows=len(sleeps)) - for i, (sleep, axes) in enumerate(zip(sleeps, axarr)): + for (sleep, axes) in zip(sleeps, axarr): plot_one(sleep, fig, axes, showtext=True) used = melatonin_data.get(sleep.date_, None) sused: str diff --git a/my/location/google.py b/my/location/google.py index a7a92d3..b966ec6 100644 --- a/my/location/google.py +++ b/my/location/google.py @@ -22,9 +22,10 @@ import geopy # type: ignore from my.core import stat, Stats, make_logger from my.core.cachew import cache_dir, mcachew -from my.core.warnings import high +from my.core import warnings -high("Please set up my.google.takeout.parser module for better takeout support") + +warnings.high("Please set up my.google.takeout.parser module for better takeout support") # otherwise uses ijson @@ -52,8 +53,7 @@ def _iter_via_ijson(fo) -> Iterable[TsLatLon]: # pip3 install ijson cffi import ijson.backends.yajl2_cffi as ijson # type: ignore except: - import warnings - warnings.warn("Falling back to default ijson because 'cffi' backend isn't found. It's up to 2x faster, you might want to check it out") + warnings.medium("Falling back to default ijson because 'cffi' backend isn't found. It's up to 2x faster, you might want to check it out") import ijson # type: ignore for d in ijson.items(fo, 'locations.item'): @@ -105,7 +105,8 @@ def _iter_locations_fo(fit) -> Iterable[Location]: errors += 1 if float(errors) / total > 0.01: # todo make defensive? - raise RuntimeError('too many errors! aborting') + # todo exceptiongroup? + raise RuntimeError('too many errors! aborting') # noqa: B904 else: continue diff --git a/my/media/imdb.py b/my/media/imdb.py index df6d62d..c66f5dc 100644 --- a/my/media/imdb.py +++ b/my/media/imdb.py @@ -22,7 +22,7 @@ def iter_movies() -> Iterator[Movie]: with last.open() as fo: reader = csv.DictReader(fo) - for i, line in enumerate(reader): + for line in reader: # TODO extract directors?? title = line['Title'] rating = int(line['You rated']) diff --git a/my/polar.py b/my/polar.py index 197de18..9125f17 100644 --- a/my/polar.py +++ b/my/polar.py @@ -166,7 +166,7 @@ class Loader: htags: List[str] = [] if 'tags' in h: ht = h['tags'].zoom() - for k, v in list(ht.items()): + for _k, v in list(ht.items()): ctag = v.zoom() ctag['id'].consume() ct = ctag['label'].zoom() @@ -199,7 +199,7 @@ class Loader: def load_items(self, metas: Json) -> Iterable[Highlight]: - for p, meta in metas.items(): + for _p, meta in metas.items(): with wrap(meta, throw=not config.defensive) as meta: yield from self.load_item(meta) diff --git a/my/reddit/rexport.py b/my/reddit/rexport.py index 6a6be61..5dcd7d9 100644 --- a/my/reddit/rexport.py +++ b/my/reddit/rexport.py @@ -144,9 +144,9 @@ if not TYPE_CHECKING: try: # here we just check that types are available, we don't actually want to import them # fmt: off - dal.Subreddit - dal.Profile - dal.Multireddit + dal.Subreddit # noqa: B018 + dal.Profil # noqa: B018e + dal.Multireddit # noqa: B018 # fmt: on except AttributeError as ae: warnings.high(f'{ae} : please update "rexport" installation') diff --git a/my/rss/common.py b/my/rss/common.py index 54067d6..bb75297 100644 --- a/my/rss/common.py +++ b/my/rss/common.py @@ -32,7 +32,7 @@ def compute_subscriptions(*sources: Iterable[SubscriptionState]) -> List[Subscri by_url: Dict[str, Subscription] = {} # ah. dates are used for sorting - for when, state in sorted(states): + for _when, state in sorted(states): # TODO use 'when'? for feed in state: if feed.url not in by_url: diff --git a/my/tests/location/google.py b/my/tests/location/google.py index 612522b..43b8646 100644 --- a/my/tests/location/google.py +++ b/my/tests/location/google.py @@ -44,8 +44,8 @@ def _prepare_takeouts_dir(tmp_path: Path) -> Path: try: track = one(testdata().rglob('italy-slovenia-2017-07-29.json')) - except ValueError: - raise RuntimeError('testdata not found, setup git submodules?') + except ValueError as e: + raise RuntimeError('testdata not found, setup git submodules?') from e # todo ugh. unnecessary zipping, but at the moment takeout provider doesn't support plain dirs import zipfile diff --git a/my/tests/shared_tz_config.py b/my/tests/shared_tz_config.py index 3d95a9e..810d989 100644 --- a/my/tests/shared_tz_config.py +++ b/my/tests/shared_tz_config.py @@ -49,8 +49,8 @@ def _prepare_takeouts_dir(tmp_path: Path) -> Path: try: track = one(testdata().rglob('italy-slovenia-2017-07-29.json')) - except ValueError: - raise RuntimeError('testdata not found, setup git submodules?') + except ValueError as e: + raise RuntimeError('testdata not found, setup git submodules?') from e # todo ugh. unnecessary zipping, but at the moment takeout provider doesn't support plain dirs import zipfile diff --git a/my/time/tz/common.py b/my/time/tz/common.py index 89150c7..13c8ac0 100644 --- a/my/time/tz/common.py +++ b/my/time/tz/common.py @@ -33,7 +33,7 @@ def default_policy() -> TzPolicy: def localize_with_policy( lfun: Callable[[datetime], datetime_aware], dt: datetime, - policy: TzPolicy=default_policy() + policy: TzPolicy=default_policy() # noqa: B008 ) -> datetime_aware: tz = dt.tzinfo if tz is None: diff --git a/my/twitter/archive.py b/my/twitter/archive.py index 685f7fc..d326d70 100644 --- a/my/twitter/archive.py +++ b/my/twitter/archive.py @@ -14,9 +14,9 @@ except ImportError as ie: try: from my.config import twitter as user_config # type: ignore[assignment] except ImportError: - raise ie # raise the original exception.. must be something else + raise ie # raise the original exception.. must be something else # noqa: B904 else: - from ..core import warnings + from my.core import warnings warnings.high('my.config.twitter is deprecated! Please rename it to my.config.twitter_archive in your config') ## diff --git a/ruff.toml b/ruff.toml index 69af75a..3d97fc9 100644 --- a/ruff.toml +++ b/ruff.toml @@ -7,8 +7,11 @@ lint.extend-select = [ "UP", # detect deprecated python stdlib stuff "FBT", # detect use of boolean arguments "RUF", # various ruff-specific rules + "PLR", # 'refactor' rules + "B", # 'bugbear' set -- various possible bugs + + - "PLR", # "S", # bandit (security checks) -- tends to be not very useful, lots of nitpicks # "DTZ", # datetimes checks -- complaining about missing tz and mostly false positives ] @@ -57,4 +60,9 @@ lint.ignore = [ "PLR2004", # magic value in comparison -- super annoying in tests ### "PLR0402", # import X.Y as Y -- TODO maybe consider enabling it, but double check + + "B009", # calling gettattr with constant attribute -- this is useful to convince mypy + "B010", # same as above, but setattr + "B017", # pytest.raises(Exception) + "B023", # seems to result in false positives? ] diff --git a/tests/github.py b/tests/github.py index 6b7df23..ed89053 100644 --- a/tests/github.py +++ b/tests/github.py @@ -5,11 +5,13 @@ from more_itertools import ilen def test_gdpr() -> None: import my.github.gdpr as gdpr + assert ilen(gdpr.events()) > 100 def test() -> None: - from my.coding.github import get_events + from my.github.all import get_events + events = get_events() assert ilen(events) > 100 for e in events: From 985c0f94e633dcab9f51e0da459ad049d8f8c73b Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Wed, 28 Aug 2024 01:51:14 +0100 Subject: [PATCH 088/122] ruff: attempt to enable ARG checks, suppress in some places --- my/core/pytest.py | 2 +- my/core/utils/itertools.py | 6 +++--- my/pdfs.py | 2 +- ruff.toml | 4 ++-- 4 files changed, 7 insertions(+), 7 deletions(-) diff --git a/my/core/pytest.py b/my/core/pytest.py index c73c71a..e514957 100644 --- a/my/core/pytest.py +++ b/my/core/pytest.py @@ -15,7 +15,7 @@ if typing.TYPE_CHECKING or under_pytest: parametrize = pytest.mark.parametrize else: - def parametrize(*args, **kwargs): + def parametrize(*_args, **_kwargs): def wrapper(f): return f diff --git a/my/core/utils/itertools.py b/my/core/utils/itertools.py index b945ad8..ae9402d 100644 --- a/my/core/utils/itertools.py +++ b/my/core/utils/itertools.py @@ -63,7 +63,7 @@ def test_ensure_unique() -> None: list(it) # hacky way to force distinct objects? - list(ensure_unique(dups, key=lambda i: object())) + list(ensure_unique(dups, key=lambda _: object())) def make_dict( @@ -115,7 +115,7 @@ def _listify(func: Callable[LFP, Iterable[LV]], *args: LFP.args, **kwargs: LFP.k # so seems easiest to just use specialize instantiations of decorator instead if TYPE_CHECKING: - def listify(func: Callable[LFP, Iterable[LV]]) -> Callable[LFP, List[LV]]: ... + def listify(func: Callable[LFP, Iterable[LV]]) -> Callable[LFP, List[LV]]: ... # noqa: ARG001 else: listify = _listify @@ -162,7 +162,7 @@ def _warn_if_empty(func, *args, **kwargs): if TYPE_CHECKING: FF = TypeVar('FF', bound=Callable[..., Iterable]) - def warn_if_empty(f: FF) -> FF: ... + def warn_if_empty(func: FF) -> FF: ... # noqa: ARG001 else: warn_if_empty = _warn_if_empty diff --git a/my/pdfs.py b/my/pdfs.py index db49c0e..de9324d 100644 --- a/my/pdfs.py +++ b/my/pdfs.py @@ -25,7 +25,7 @@ class config(Protocol): def paths(self) -> Paths: return () # allowed to be empty for 'filelist' logic - def is_ignored(self, p: Path) -> bool: + def is_ignored(self, p: Path) -> bool: # noqa: ARG002 """ You can override this in user config if you want to ignore some files that are tooheavy """ diff --git a/ruff.toml b/ruff.toml index 3d97fc9..e7c6f07 100644 --- a/ruff.toml +++ b/ruff.toml @@ -10,8 +10,8 @@ lint.extend-select = [ "PLR", # 'refactor' rules "B", # 'bugbear' set -- various possible bugs - - + # "FA", # TODO enable later after we make sure cachew works? + # "ARG", # TODO useful, but results in some false positives in pytest fixtures... maybe later # "S", # bandit (security checks) -- tends to be not very useful, lots of nitpicks # "DTZ", # datetimes checks -- complaining about missing tz and mostly false positives ] From bd1e5d2f1167232017fcf5aad34c554582bedc69 Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Wed, 28 Aug 2024 02:16:12 +0100 Subject: [PATCH 089/122] ruff: enable PERF checks set --- my/core/query.py | 2 +- my/core/stats.py | 2 +- my/polar.py | 2 +- ruff.toml | 9 +++++++++ 4 files changed, 12 insertions(+), 3 deletions(-) diff --git a/my/core/query.py b/my/core/query.py index c337e5c..45806fb 100644 --- a/my/core/query.py +++ b/my/core/query.py @@ -114,7 +114,7 @@ def attribute_func(obj: T, where: Where, default: Optional[U] = None) -> Optiona if where(v): return lambda o: o.get(k, default) # type: ignore[union-attr] elif dataclasses.is_dataclass(obj): - for (field_name, _annotation) in obj.__annotations__.items(): + for field_name in obj.__annotations__.keys(): if where(getattr(obj, field_name)): return lambda o: getattr(o, field_name, default) elif is_namedtuple(obj): diff --git a/my/core/stats.py b/my/core/stats.py index aa05355..674a8d1 100644 --- a/my/core/stats.py +++ b/my/core/stats.py @@ -440,7 +440,7 @@ def _guess_datetime(x: Any) -> Optional[datetime]: d = asdict(x) except: # noqa: E722 bare except return None - for _k, v in d.items(): + for v in d.values(): if isinstance(v, datetime): return v return None diff --git a/my/polar.py b/my/polar.py index 9125f17..e52bb14 100644 --- a/my/polar.py +++ b/my/polar.py @@ -199,7 +199,7 @@ class Loader: def load_items(self, metas: Json) -> Iterable[Highlight]: - for _p, meta in metas.items(): + for _p, meta in metas.items(): # noqa: PERF102 with wrap(meta, throw=not config.defensive) as meta: yield from self.load_item(meta) diff --git a/ruff.toml b/ruff.toml index e7c6f07..2c9c39b 100644 --- a/ruff.toml +++ b/ruff.toml @@ -10,6 +10,7 @@ lint.extend-select = [ "PLR", # 'refactor' rules "B", # 'bugbear' set -- various possible bugs + "PERF", # various potential performance speedups # "FA", # TODO enable later after we make sure cachew works? # "ARG", # TODO useful, but results in some false positives in pytest fixtures... maybe later # "S", # bandit (security checks) -- tends to be not very useful, lots of nitpicks @@ -65,4 +66,12 @@ lint.ignore = [ "B010", # same as above, but setattr "B017", # pytest.raises(Exception) "B023", # seems to result in false positives? + + # a bit too annoying, offers to convert for loops to list comprehension + # , which may heart readability + "PERF401", + + # suggests no using exception in for loops + # we do use this technique a lot, plus in 3.11 happy path exception handling is "zero-cost" + "PERF203", ] From 9fd4227abf7fa2619c9f1297e754eead0aee7fc3 Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Wed, 28 Aug 2024 02:50:05 +0100 Subject: [PATCH 090/122] ruff: enable RET/PIE/PLW --- my/coding/commits.py | 3 +- my/core/__main__.py | 10 ++--- my/core/_deprecated/kompress.py | 2 +- my/core/error.py | 3 +- my/core/orgmode.py | 3 +- my/core/query_range.py | 60 +++++++++++++------------- my/core/serialize.py | 3 +- my/core/util.py | 2 +- my/experimental/destructive_parsing.py | 2 +- my/location/fallback/via_home.py | 19 ++++---- my/photos/main.py | 3 +- my/smscalls.py | 7 ++- my/time/tz/via_location.py | 6 +-- ruff.toml | 32 ++++++++++---- 14 files changed, 80 insertions(+), 75 deletions(-) diff --git a/my/coding/commits.py b/my/coding/commits.py index 20b66a0..d4e05b7 100644 --- a/my/coding/commits.py +++ b/my/coding/commits.py @@ -187,8 +187,7 @@ def _repo_depends_on(_repo: Path) -> int: ff = _repo / pp if ff.exists(): return int(ff.stat().st_mtime) - else: - raise RuntimeError(f"Could not find a FETCH_HEAD/HEAD file in {_repo}") + raise RuntimeError(f"Could not find a FETCH_HEAD/HEAD file in {_repo}") def _commits(_repos: List[Path]) -> Iterator[Commit]: diff --git a/my/core/__main__.py b/my/core/__main__.py index c5e4552..8553942 100644 --- a/my/core/__main__.py +++ b/my/core/__main__.py @@ -43,7 +43,7 @@ def run_mypy(cfg_path: Path) -> Optional[CompletedProcess]: cmd = mypy_cmd() if cmd is None: return None - mres = run([ # noqa: UP022 + mres = run([ # noqa: UP022,PLW1510 *cmd, '--namespace-packages', '--color-output', # not sure if works?? @@ -214,10 +214,10 @@ See https://github.com/karlicoss/HPI/blob/master/doc/SETUP.org#setting-up-module if len(errors) > 0: error(f'config check: {len(errors)} errors') return False - else: - # note: shouldn't exit here, might run something else - info('config check: success!') - return True + + # note: shouldn't exit here, might run something else + info('config check: success!') + return True from .util import HPIModule, modules diff --git a/my/core/_deprecated/kompress.py b/my/core/_deprecated/kompress.py index 803e515..cd09c06 100644 --- a/my/core/_deprecated/kompress.py +++ b/my/core/_deprecated/kompress.py @@ -87,7 +87,7 @@ def kopen(path: PathIsh, *args, mode: str='rt', **kwargs) -> IO: elif name.endswith(Ext.lz4): import lz4.frame # type: ignore return lz4.frame.open(str(pp), mode, *args, **kwargs) - elif name.endswith(Ext.zstd) or name.endswith(Ext.zst): + elif name.endswith(Ext.zstd) or name.endswith(Ext.zst): # noqa: PIE810 kwargs['mode'] = mode return _zstd_open(pp, *args, **kwargs) elif name.endswith(Ext.targz): diff --git a/my/core/error.py b/my/core/error.py index e869614..ed26dda 100644 --- a/my/core/error.py +++ b/my/core/error.py @@ -41,8 +41,7 @@ def notnone(x: Optional[T]) -> T: def unwrap(res: Res[T]) -> T: if isinstance(res, Exception): raise res - else: - return res + return res def drop_exceptions(itr: Iterator[Res[T]]) -> Iterator[T]: diff --git a/my/core/orgmode.py b/my/core/orgmode.py index c70ded6..979f288 100644 --- a/my/core/orgmode.py +++ b/my/core/orgmode.py @@ -17,8 +17,7 @@ def parse_org_datetime(s: str) -> datetime: return datetime.strptime(s, fmt) except ValueError: continue - else: - raise RuntimeError(f"Bad datetime string {s}") + raise RuntimeError(f"Bad datetime string {s}") # TODO I guess want to borrow inspiration from bs4? element type <-> tag; and similar logic for find_one, find_all diff --git a/my/core/query_range.py b/my/core/query_range.py index 0a1b321..1f4a7ff 100644 --- a/my/core/query_range.py +++ b/my/core/query_range.py @@ -341,37 +341,37 @@ def select_range( if order_by_chosen is None: raise QueryException("""Can't order by range if we have no way to order_by! Specify a type or a key to order the value by""") - else: - # force drop_unsorted=True so we can use _create_range_filter - # sort the iterable by the generated order_by_chosen function - itr = select(itr, order_by=order_by_chosen, drop_unsorted=True) - filter_func: Optional[Where] - if order_by_value_type in [datetime, date]: - filter_func = _create_range_filter( - unparsed_range=unparsed_range, - end_parser=parse_datetime_float, - within_parser=parse_timedelta_float, - attr_func=order_by_chosen, # type: ignore[arg-type] - default_before=time.time(), - value_coercion_func=_datelike_to_float) - elif order_by_value_type in [int, float]: - # allow primitives to be converted using the default int(), float() callables - filter_func = _create_range_filter( - unparsed_range=unparsed_range, - end_parser=order_by_value_type, - within_parser=order_by_value_type, - attr_func=order_by_chosen, # type: ignore[arg-type] - default_before=None, - value_coercion_func=order_by_value_type) - else: - # TODO: add additional kwargs to let the user sort by other values, by specifying the parsers? - # would need to allow passing the end_parser, within parser, default before and value_coercion_func... - # (seems like a lot?) - raise QueryException("Sorting by custom types is currently unsupported") - # use the created filter function - # we've already applied drop_exceptions and kwargs related to unsortable values above - itr = select(itr, where=filter_func, limit=limit, reverse=reverse) + # force drop_unsorted=True so we can use _create_range_filter + # sort the iterable by the generated order_by_chosen function + itr = select(itr, order_by=order_by_chosen, drop_unsorted=True) + filter_func: Optional[Where] + if order_by_value_type in [datetime, date]: + filter_func = _create_range_filter( + unparsed_range=unparsed_range, + end_parser=parse_datetime_float, + within_parser=parse_timedelta_float, + attr_func=order_by_chosen, # type: ignore[arg-type] + default_before=time.time(), + value_coercion_func=_datelike_to_float) + elif order_by_value_type in [int, float]: + # allow primitives to be converted using the default int(), float() callables + filter_func = _create_range_filter( + unparsed_range=unparsed_range, + end_parser=order_by_value_type, + within_parser=order_by_value_type, + attr_func=order_by_chosen, # type: ignore[arg-type] + default_before=None, + value_coercion_func=order_by_value_type) + else: + # TODO: add additional kwargs to let the user sort by other values, by specifying the parsers? + # would need to allow passing the end_parser, within parser, default before and value_coercion_func... + # (seems like a lot?) + raise QueryException("Sorting by custom types is currently unsupported") + + # use the created filter function + # we've already applied drop_exceptions and kwargs related to unsortable values above + itr = select(itr, where=filter_func, limit=limit, reverse=reverse) else: # wrap_unsorted may be used here if the user specified an order_key, # or manually passed a order_value function diff --git a/my/core/serialize.py b/my/core/serialize.py index b196d47..ab11a20 100644 --- a/my/core/serialize.py +++ b/my/core/serialize.py @@ -145,8 +145,7 @@ def _dumps_factory(**kwargs) -> Callable[[Any], str]: res = factory() if res is not None: return res - else: - raise RuntimeError("Should not happen!") + raise RuntimeError("Should not happen!") def dumps( diff --git a/my/core/util.py b/my/core/util.py index fb3edf8..a247f81 100644 --- a/my/core/util.py +++ b/my/core/util.py @@ -100,7 +100,7 @@ def _walk_packages(path: Iterable[str], prefix: str='', onerror=None) -> Iterabl def seen(p, m={}): # noqa: B006 if p in m: return True - m[p] = True + m[p] = True # noqa: RET503 for info in pkgutil.iter_modules(path, prefix): mname = info.name diff --git a/my/experimental/destructive_parsing.py b/my/experimental/destructive_parsing.py index 056cc0b..b389f7e 100644 --- a/my/experimental/destructive_parsing.py +++ b/my/experimental/destructive_parsing.py @@ -35,7 +35,7 @@ def is_empty(x) -> bool: elif isinstance(x, list): return all(map(is_empty, x)) else: - assert_never(x) + assert_never(x) # noqa: RET503 class Manager: diff --git a/my/location/fallback/via_home.py b/my/location/fallback/via_home.py index 199ebb0..e44c59d 100644 --- a/my/location/fallback/via_home.py +++ b/my/location/fallback/via_home.py @@ -92,13 +92,12 @@ def estimate_location(dt: DateExact) -> Iterator[FallbackLocation]: dt=datetime.fromtimestamp(d, timezone.utc), datasource='via_home') return - else: - # I guess the most reasonable is to fallback on the first location - lat, lon = hist[-1][1] - yield FallbackLocation( - lat=lat, - lon=lon, - accuracy=config.home_accuracy, - dt=datetime.fromtimestamp(d, timezone.utc), - datasource='via_home') - return + + # I guess the most reasonable is to fallback on the first location + lat, lon = hist[-1][1] + yield FallbackLocation( + lat=lat, + lon=lon, + accuracy=config.home_accuracy, + dt=datetime.fromtimestamp(d, timezone.utc), + datasource='via_home') diff --git a/my/photos/main.py b/my/photos/main.py index 63a6fea..c326405 100644 --- a/my/photos/main.py +++ b/my/photos/main.py @@ -43,8 +43,7 @@ class Photo(NamedTuple): for bp in config.paths: if self.path.startswith(bp): return self.path[len(bp):] - else: - raise RuntimeError(f"Weird path {self.path}, can't match against anything") + raise RuntimeError(f"Weird path {self.path}, can't match against anything") @property def name(self) -> str: diff --git a/my/smscalls.py b/my/smscalls.py index b56026d..78bf7ee 100644 --- a/my/smscalls.py +++ b/my/smscalls.py @@ -182,10 +182,9 @@ class MMS(NamedTuple): for (addr, _type) in self.addresses: if _type == 137: return addr - else: - # hmm, maybe return instead? but this probably shouldnt happen, means - # something is very broken - raise RuntimeError(f'No from address matching 137 found in {self.addresses}') + # hmm, maybe return instead? but this probably shouldnt happen, means + # something is very broken + raise RuntimeError(f'No from address matching 137 found in {self.addresses}') @property def from_me(self) -> bool: diff --git a/my/time/tz/via_location.py b/my/time/tz/via_location.py index 156a5db..8f521e0 100644 --- a/my/time/tz/via_location.py +++ b/my/time/tz/via_location.py @@ -63,16 +63,14 @@ def _get_user_config(): except ImportError as ie: if "'time'" not in str(ie): raise ie - else: - return empty_config + return empty_config try: user_config = time.tz.via_location except AttributeError as ae: if not ("'tz'" in str(ae) or "'via_location'" in str(ae)): raise ae - else: - return empty_config + return empty_config return user_config diff --git a/ruff.toml b/ruff.toml index 2c9c39b..3cb9f76 100644 --- a/ruff.toml +++ b/ruff.toml @@ -1,18 +1,22 @@ target-version = "py38" # NOTE: inferred from pyproject.toml if present lint.extend-select = [ - "F", # flakes rules -- default, but extend just in case - "E", # pycodestyle -- default, but extend just in case - "C4", # flake8-comprehensions -- unnecessary list/map/dict calls - "UP", # detect deprecated python stdlib stuff - "FBT", # detect use of boolean arguments - "RUF", # various ruff-specific rules - "PLR", # 'refactor' rules - "B", # 'bugbear' set -- various possible bugs - + "F", # flakes rules -- default, but extend just in case + "E", # pycodestyle -- default, but extend just in case + "C4", # flake8-comprehensions -- unnecessary list/map/dict calls + "UP", # detect deprecated python stdlib stuff + "FBT", # detect use of boolean arguments + "RUF", # various ruff-specific rules + "PLR", # 'refactor' rules + "B", # 'bugbear' set -- various possible bugs "PERF", # various potential performance speedups + "RET", # early returns + "PIE", # 'misc' lints + "PLW", # pylint warnings # "FA", # TODO enable later after we make sure cachew works? + # "PTH", # pathlib migration -- TODO enable later # "ARG", # TODO useful, but results in some false positives in pytest fixtures... maybe later + # "A", # TODO builtin shadowing -- handle later # "S", # bandit (security checks) -- tends to be not very useful, lots of nitpicks # "DTZ", # datetimes checks -- complaining about missing tz and mostly false positives ] @@ -67,6 +71,10 @@ lint.ignore = [ "B017", # pytest.raises(Exception) "B023", # seems to result in false positives? + # complains about useless pass, but has sort of a false positive if the function has a docstring? + # this is common for click entrypoints (e.g. in __main__), so disable + "PIE790", + # a bit too annoying, offers to convert for loops to list comprehension # , which may heart readability "PERF401", @@ -74,4 +82,10 @@ lint.ignore = [ # suggests no using exception in for loops # we do use this technique a lot, plus in 3.11 happy path exception handling is "zero-cost" "PERF203", + + "RET504", # unnecessary assignment before returning -- that can be useful for readability + "RET505", # unnecessary else after return -- can hurt readability + + "PLW0603", # global variable update.. we usually know why we are doing this + "PLW2901", # for loop variable overwritten, usually this is intentional ] From ac08af7aabc09d6fd28f44ba0c155c62382cf96f Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Wed, 28 Aug 2024 02:54:26 +0100 Subject: [PATCH 091/122] ruff: enable PT (pytest) rules --- ruff.toml | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/ruff.toml b/ruff.toml index 3cb9f76..cb9445f 100644 --- a/ruff.toml +++ b/ruff.toml @@ -13,12 +13,17 @@ lint.extend-select = [ "RET", # early returns "PIE", # 'misc' lints "PLW", # pylint warnings + "PT", # pytest stuff # "FA", # TODO enable later after we make sure cachew works? # "PTH", # pathlib migration -- TODO enable later # "ARG", # TODO useful, but results in some false positives in pytest fixtures... maybe later # "A", # TODO builtin shadowing -- handle later # "S", # bandit (security checks) -- tends to be not very useful, lots of nitpicks # "DTZ", # datetimes checks -- complaining about missing tz and mostly false positives + # "EM", # TODO hmm could be helpful to prevent duplicate err msg in traceback.. but kinda annoying + # "FIX", # complains about fixmes/todos -- annoying + # "TD", # complains about todo formatting -- too annoying + # "ALL", ] lint.ignore = [ @@ -88,4 +93,8 @@ lint.ignore = [ "PLW0603", # global variable update.. we usually know why we are doing this "PLW2901", # for loop variable overwritten, usually this is intentional + + "PT004", # deprecated rule, will be removed later + "PT011", # pytest raises should is too broad + "PT012", # pytest raises should contain a single statement ] From c5df3ce1284d3730e6650321a4fe0c922960954f Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Wed, 28 Aug 2024 03:05:24 +0100 Subject: [PATCH 092/122] ruff: enable W, COM, EXE rules --- my/bluemaestro.py | 1 - my/coding/commits.py | 2 +- my/core/discovery_pure.py | 2 +- my/fbmessenger/android.py | 2 +- my/jawbone/__init__.py | 2 +- my/media/imdb.py | 1 - my/rtm.py | 2 +- my/telegram/telegram_backup.py | 2 +- ruff.toml | 19 +++++++++++++------ 9 files changed, 19 insertions(+), 14 deletions(-) diff --git a/my/bluemaestro.py b/my/bluemaestro.py index 5d0968b..4c33fd1 100644 --- a/my/bluemaestro.py +++ b/my/bluemaestro.py @@ -1,4 +1,3 @@ -#!/usr/bin/python3 """ [[https://bluemaestro.com/products/product-details/bluetooth-environmental-monitor-and-logger][Bluemaestro]] temperature/humidity/pressure monitor """ diff --git a/my/coding/commits.py b/my/coding/commits.py index d4e05b7..9661ae5 100644 --- a/my/coding/commits.py +++ b/my/coding/commits.py @@ -136,7 +136,7 @@ def canonical_name(repo: Path) -> str: # else: # rname = r.name # if 'backups/github' in repo: - # pass # TODO + # pass # TODO def _fd_path() -> str: diff --git a/my/core/discovery_pure.py b/my/core/discovery_pure.py index 63d9922..b753de8 100644 --- a/my/core/discovery_pure.py +++ b/my/core/discovery_pure.py @@ -242,7 +242,7 @@ def test_pure() -> None: src = Path(__file__).read_text() # 'import my' is allowed, but # dont allow anything other HPI modules - assert re.findall('import ' + r'my\.\S+', src, re.M) == [] + assert re.findall('import ' + r'my\.\S+', src, re.MULTILINE) == [] assert 'from ' + 'my' not in src diff --git a/my/fbmessenger/android.py b/my/fbmessenger/android.py index bc06114..7e48c78 100644 --- a/my/fbmessenger/android.py +++ b/my/fbmessenger/android.py @@ -228,7 +228,7 @@ def _process_db_threads_db2(db: sqlite3.Connection) -> Iterator[Res[Entity]]: for r in db.execute( ''' - SELECT *, json_extract(sender, "$.user_key") AS user_key FROM messages + SELECT *, json_extract(sender, "$.user_key") AS user_key FROM messages WHERE msg_type NOT IN ( -1, /* these don't have any data at all, likely immediately deleted or something? */ 2 /* these are 'left group' system messages, also a bit annoying since they might reference nonexistent users */ diff --git a/my/jawbone/__init__.py b/my/jawbone/__init__.py index affe230..35112ba 100644 --- a/my/jawbone/__init__.py +++ b/my/jawbone/__init__.py @@ -239,7 +239,7 @@ def plot_one(sleep: SleepEntry, fig, axes, xlims=None, *, showtext=True): # axes.title.set_size(10) if showtext: - axes.text(xlims[1] - timedelta(hours=1.5), 20, str(sleep),) + axes.text(xlims[1] - timedelta(hours=1.5), 20, str(sleep)) # plt.text(sleep.asleep(), 0, hhmm(sleep.asleep())) diff --git a/my/media/imdb.py b/my/media/imdb.py index c66f5dc..df31032 100644 --- a/my/media/imdb.py +++ b/my/media/imdb.py @@ -1,4 +1,3 @@ -#!/usr/bin/env python3 import csv from datetime import datetime from typing import Iterator, List, NamedTuple diff --git a/my/rtm.py b/my/rtm.py index 22752fe..b559ba4 100644 --- a/my/rtm.py +++ b/my/rtm.py @@ -58,7 +58,7 @@ class MyTodo: def get_status(self) -> str: if 'STATUS' not in self.todo: return None # type: ignore - # TODO 'COMPLETED'? + # TODO 'COMPLETED'? return str(self.todo['STATUS']) # TODO tz? diff --git a/my/telegram/telegram_backup.py b/my/telegram/telegram_backup.py index 0617501..ff4f904 100644 --- a/my/telegram/telegram_backup.py +++ b/my/telegram/telegram_backup.py @@ -18,7 +18,7 @@ from my.config import telegram as user_config class config(user_config.telegram_backup): # path to the export database.sqlite export_path: PathIsh - + @dataclass class Chat: diff --git a/ruff.toml b/ruff.toml index cb9445f..8cbc642 100644 --- a/ruff.toml +++ b/ruff.toml @@ -3,17 +3,22 @@ target-version = "py38" # NOTE: inferred from pyproject.toml if present lint.extend-select = [ "F", # flakes rules -- default, but extend just in case "E", # pycodestyle -- default, but extend just in case - "C4", # flake8-comprehensions -- unnecessary list/map/dict calls - "UP", # detect deprecated python stdlib stuff - "FBT", # detect use of boolean arguments - "RUF", # various ruff-specific rules - "PLR", # 'refactor' rules + "W", # various warnings + "B", # 'bugbear' set -- various possible bugs + "C4", # flake8-comprehensions -- unnecessary list/map/dict calls + "COM", # trailing commas + "EXE", # various checks wrt executable files + "FBT", # detect use of boolean arguments + "FURB", # various rules "PERF", # various potential performance speedups - "RET", # early returns "PIE", # 'misc' lints + "PLR", # 'refactor' rules "PLW", # pylint warnings "PT", # pytest stuff + "RET", # early returns + "RUF", # various ruff-specific rules + "UP", # detect deprecated python stdlib stuff # "FA", # TODO enable later after we make sure cachew works? # "PTH", # pathlib migration -- TODO enable later # "ARG", # TODO useful, but results in some false positives in pytest fixtures... maybe later @@ -97,4 +102,6 @@ lint.ignore = [ "PT004", # deprecated rule, will be removed later "PT011", # pytest raises should is too broad "PT012", # pytest raises should contain a single statement + + "COM812", # trailing comma missing -- TODO maybe use this? ] From fc0e0be291795970cec45209e9249d893d5173cc Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Wed, 28 Aug 2024 03:09:32 +0100 Subject: [PATCH 093/122] ruff: enable ICN and PD rules --- my/body/weight.py | 2 +- my/emfit/__init__.py | 4 ++-- ruff.toml | 4 ++++ 3 files changed, 7 insertions(+), 3 deletions(-) diff --git a/my/body/weight.py b/my/body/weight.py index 277b4d1..51e6513 100644 --- a/my/body/weight.py +++ b/my/body/weight.py @@ -83,7 +83,7 @@ def make_dataframe(data: Iterator[Result]): } df = pd.DataFrame(it()) - df.set_index('dt', inplace=True) + df = df.set_index('dt') # TODO not sure about UTC?? df.index = pd.to_datetime(df.index, utc=True) return df diff --git a/my/emfit/__init__.py b/my/emfit/__init__.py index 71a483f..9934903 100644 --- a/my/emfit/__init__.py +++ b/my/emfit/__init__.py @@ -155,9 +155,9 @@ def dataframe() -> DataFrameT: last = s # meh dicts.append(d) - import pandas + import pandas as pd - return pandas.DataFrame(dicts) + return pd.DataFrame(dicts) def stats() -> Stats: diff --git a/ruff.toml b/ruff.toml index 8cbc642..c2c88ef 100644 --- a/ruff.toml +++ b/ruff.toml @@ -9,9 +9,11 @@ lint.extend-select = [ "C4", # flake8-comprehensions -- unnecessary list/map/dict calls "COM", # trailing commas "EXE", # various checks wrt executable files + "ICN", # various import conventions "FBT", # detect use of boolean arguments "FURB", # various rules "PERF", # various potential performance speedups + "PD", # pandas rules "PIE", # 'misc' lints "PLR", # 'refactor' rules "PLW", # pylint warnings @@ -104,4 +106,6 @@ lint.ignore = [ "PT012", # pytest raises should contain a single statement "COM812", # trailing comma missing -- TODO maybe use this? + + "PD901", # generic variable name df ] From affa79ba3ae0aee53eb908dffdeee88800215c45 Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Wed, 28 Aug 2024 03:14:23 +0100 Subject: [PATCH 094/122] my.time.tz.via_location: fix accidental RuntimeError introduced in previous MR --- my/time/tz/via_location.py | 1 - 1 file changed, 1 deletion(-) diff --git a/my/time/tz/via_location.py b/my/time/tz/via_location.py index 8f521e0..4920333 100644 --- a/my/time/tz/via_location.py +++ b/my/time/tz/via_location.py @@ -104,7 +104,6 @@ def _timezone_finder(*, fast: bool) -> Any: # for backwards compatibility def _locations() -> Iterator[Tuple[LatLon, datetime_aware]]: try: - raise RuntimeError import my.location.all for loc in my.location.all.locations(): From 1c5efc46aa18ebfb8fdb5ccbfde03b731e5355bf Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Wed, 28 Aug 2024 03:18:45 +0100 Subject: [PATCH 095/122] ruff: enable TRY rules --- my/core/_deprecated/kompress.py | 3 ++- my/core/time.py | 3 ++- ruff.toml | 7 +++++++ 3 files changed, 11 insertions(+), 2 deletions(-) diff --git a/my/core/_deprecated/kompress.py b/my/core/_deprecated/kompress.py index cd09c06..1cd2636 100644 --- a/my/core/_deprecated/kompress.py +++ b/my/core/_deprecated/kompress.py @@ -141,9 +141,10 @@ open = kopen # TODO deprecate def kexists(path: PathIsh, subpath: str) -> bool: try: kopen(path, subpath) - return True except Exception: return False + else: + return True import zipfile diff --git a/my/core/time.py b/my/core/time.py index 5a47c3d..6de4105 100644 --- a/my/core/time.py +++ b/my/core/time.py @@ -11,10 +11,11 @@ def user_forced() -> Sequence[str]: # https://stackoverflow.com/questions/36067621/python-all-possible-timezone-abbreviations-for-given-timezone-name-and-vise-ve try: from my.config import time as user_config - return user_config.tz.force_abbreviations # type: ignore[attr-defined] except: # todo log/apply policy return [] + else: + return user_config.tz.force_abbreviations # type: ignore[attr-defined] @lru_cache(1) diff --git a/ruff.toml b/ruff.toml index c2c88ef..9a932ef 100644 --- a/ruff.toml +++ b/ruff.toml @@ -20,6 +20,7 @@ lint.extend-select = [ "PT", # pytest stuff "RET", # early returns "RUF", # various ruff-specific rules + "TRY", # various exception handling rules "UP", # detect deprecated python stdlib stuff # "FA", # TODO enable later after we make sure cachew works? # "PTH", # pathlib migration -- TODO enable later @@ -108,4 +109,10 @@ lint.ignore = [ "COM812", # trailing comma missing -- TODO maybe use this? "PD901", # generic variable name df + + "TRY003", # suggests defining exception messages in exception class -- kinda annoying + "TRY004", # prefer TypeError -- don't see the point + "TRY201", # raise without specifying exception name -- sometimes hurts readability + "TRY400", # TODO double check this, might be useful + "TRY401", # redundant exception in logging.exception call? TODO double check, might result in excessive logging ] From d58453410c34d75715b71c041f7a58a4f0954436 Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Wed, 28 Aug 2024 03:58:28 +0100 Subject: [PATCH 096/122] ruff: process remaining existing checks and suppress the annoying ones --- my/coding/commits.py | 4 ++-- my/core/_deprecated/kompress.py | 2 +- my/core/common.py | 2 +- my/core/hpi_compat.py | 2 +- my/photos/main.py | 2 +- ruff.toml | 34 +++++++++++++++++++++++++++++++-- 6 files changed, 38 insertions(+), 8 deletions(-) diff --git a/my/coding/commits.py b/my/coding/commits.py index 9661ae5..31c366e 100644 --- a/my/coding/commits.py +++ b/my/coding/commits.py @@ -178,12 +178,12 @@ def repos() -> List[Path]: # returns modification time for an index to use as hash function def _repo_depends_on(_repo: Path) -> int: - for pp in { + for pp in [ ".git/FETCH_HEAD", ".git/HEAD", "FETCH_HEAD", # bare "HEAD", # bare - }: + ]: ff = _repo / pp if ff.exists(): return int(ff.stat().st_mtime) diff --git a/my/core/_deprecated/kompress.py b/my/core/_deprecated/kompress.py index 1cd2636..63ce523 100644 --- a/my/core/_deprecated/kompress.py +++ b/my/core/_deprecated/kompress.py @@ -27,7 +27,7 @@ class Ext: def is_compressed(p: Path) -> bool: # todo kinda lame way for now.. use mime ideally? # should cooperate with kompress.kopen? - return any(p.name.endswith(ext) for ext in {Ext.xz, Ext.zip, Ext.lz4, Ext.zstd, Ext.zst, Ext.targz}) + return any(p.name.endswith(ext) for ext in [Ext.xz, Ext.zip, Ext.lz4, Ext.zstd, Ext.zst, Ext.targz]) def _zstd_open(path: Path, *args, **kwargs) -> IO: diff --git a/my/core/common.py b/my/core/common.py index 5f8d03a..a2c2ad3 100644 --- a/my/core/common.py +++ b/my/core/common.py @@ -14,7 +14,7 @@ from typing import ( ) from . import compat -from . import warnings as warnings +from . import warnings # some helper functions # TODO start deprecating this? soon we'd be able to use Path | str syntax which is shorter and more explicit diff --git a/my/core/hpi_compat.py b/my/core/hpi_compat.py index 9330e49..6261c23 100644 --- a/my/core/hpi_compat.py +++ b/my/core/hpi_compat.py @@ -123,7 +123,7 @@ class always_supports_sequence(Iterator[V]): self.it = it self._list: Optional[List] = None - def __iter__(self) -> Iterator[V]: + def __iter__(self) -> Iterator[V]: # noqa: PYI034 return self.it.__iter__() def __next__(self) -> V: diff --git a/my/photos/main.py b/my/photos/main.py index c326405..bf912e4 100644 --- a/my/photos/main.py +++ b/my/photos/main.py @@ -65,7 +65,7 @@ def _make_photo_aux(*args, **kwargs) -> List[Result]: def _make_photo(photo: Path, mtype: str, *, parent_geo: Optional[LatLon]) -> Iterator[Result]: exif: Exif - if any(x in mtype for x in {'image/png', 'image/x-ms-bmp', 'video'}): + if any(x in mtype for x in ['image/png', 'image/x-ms-bmp', 'video']): # TODO don't remember why.. logger.debug(f"skipping exif extraction for {photo} due to mime {mtype}") exif = {} diff --git a/ruff.toml b/ruff.toml index 9a932ef..0d3bb16 100644 --- a/ruff.toml +++ b/ruff.toml @@ -15,11 +15,15 @@ lint.extend-select = [ "PERF", # various potential performance speedups "PD", # pandas rules "PIE", # 'misc' lints - "PLR", # 'refactor' rules + "PLC", # pylint convention rules + "PLR", # pylint refactor rules "PLW", # pylint warnings "PT", # pytest stuff + "PYI", # various type hinting rules "RET", # early returns "RUF", # various ruff-specific rules + "TID", # various imports suggestions + "TCH", # various type checking rules "TRY", # various exception handling rules "UP", # detect deprecated python stdlib stuff # "FA", # TODO enable later after we make sure cachew works? @@ -31,10 +35,15 @@ lint.extend-select = [ # "EM", # TODO hmm could be helpful to prevent duplicate err msg in traceback.. but kinda annoying # "FIX", # complains about fixmes/todos -- annoying # "TD", # complains about todo formatting -- too annoying - # "ALL", + # "ANN", # missing type annotations? seems way to string though + + # "ALL", # uncomment this to check for new rules! ] lint.ignore = [ + "D", # annoying nags about docstrings + "N", # pep naming + ### too opinionated style checks "E501", # too long lines "E702", # Multiple statements on one line (semicolon) @@ -115,4 +124,25 @@ lint.ignore = [ "TRY201", # raise without specifying exception name -- sometimes hurts readability "TRY400", # TODO double check this, might be useful "TRY401", # redundant exception in logging.exception call? TODO double check, might result in excessive logging + + "TCH002", # suggests moving imports into type checking blocks -- too annoying + "TCH003", # suggests moving imports into type checking blocks -- too annoying + + "I001", # unsorted import block TODO consider these? + "PGH", # TODO force error code in mypy instead + + # TODO enable TID? + "TID252", # Prefer absolute imports over relative imports from parent modules + + ## too annoying + "T20", # just complains about prints and pprints + "Q", # flake quotes, too annoying + "C90", # some complexity checking + "G004", # logging statement uses f string + "ERA001", # commented out code + "SLF001", # private member accessed + "BLE001", # do not catch 'blind' Exception + "INP001", # complains about implicit namespace packages + "SIM", # some if statements crap + ## ] From 71fdeca5e10d99526b39d7cbd1eb8bd5aa43cbf9 Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Sat, 31 Aug 2024 02:03:22 +0100 Subject: [PATCH 097/122] ci: update mypy config and make ruff config more consistent with other projects --- my/coding/github.py | 2 +- my/config.py | 2 +- my/core/__main__.py | 2 +- my/core/_deprecated/kompress.py | 2 +- my/core/tests/test_config.py | 1 - my/core/utils/concurrent.py | 2 +- my/demo.py | 1 - my/endomondo.py | 2 +- my/foursquare.py | 1 - my/hackernews/common.py | 2 +- my/jawbone/plots.py | 1 - mypy.ini | 9 ++----- ruff.toml | 43 ++++++++++++++++++--------------- 13 files changed, 32 insertions(+), 38 deletions(-) diff --git a/my/coding/github.py b/my/coding/github.py index de64f05..c495554 100644 --- a/my/coding/github.py +++ b/my/coding/github.py @@ -6,7 +6,7 @@ warnings.high('my.coding.github is deprecated! Please use my.github.all instead! # todo why aren't DeprecationWarning shown by default?? if not TYPE_CHECKING: - from ..github.all import events, get_events + from ..github.all import events, get_events # noqa: F401 # todo deprecate properly iter_events = events diff --git a/my/config.py b/my/config.py index a92b2bc..2dd9cda 100644 --- a/my/config.py +++ b/my/config.py @@ -10,7 +10,7 @@ This file is used for: - for loading the actual user config ''' #### NOTE: you won't need this line VVVV in your personal config -from my.core import init +from my.core import init # noqa: F401 ### diff --git a/my/core/__main__.py b/my/core/__main__.py index 8553942..c675676 100644 --- a/my/core/__main__.py +++ b/my/core/__main__.py @@ -577,7 +577,7 @@ def query_hpi_functions( # output == 'repl' eprint(f"\nInteract with the results by using the {click.style('res', fg='green')} variable\n") try: - import IPython # type: ignore[import] + import IPython # type: ignore[import,unused-ignore] except ModuleNotFoundError: eprint("'repl' typically uses ipython, install it with 'python3 -m pip install ipython'. falling back to stdlib...") import code diff --git a/my/core/_deprecated/kompress.py b/my/core/_deprecated/kompress.py index 63ce523..b08f04b 100644 --- a/my/core/_deprecated/kompress.py +++ b/my/core/_deprecated/kompress.py @@ -120,7 +120,7 @@ class CPath(BasePath): Path only has _accessor and _closed slots, so can't directly set .open method _accessor.open has to return file descriptor, doesn't work for compressed stuff. """ - def open(self, *args, **kwargs): + def open(self, *args, **kwargs): # noqa: ARG002 kopen_kwargs = {} mode = kwargs.get('mode') if mode is not None: diff --git a/my/core/tests/test_config.py b/my/core/tests/test_config.py index a318a95..78d1a62 100644 --- a/my/core/tests/test_config.py +++ b/my/core/tests/test_config.py @@ -8,7 +8,6 @@ from pathlib import Path import pytest import pytz -from more_itertools import ilen import my.config from my.core import notnone diff --git a/my/core/utils/concurrent.py b/my/core/utils/concurrent.py index 5f11ab0..146861b 100644 --- a/my/core/utils/concurrent.py +++ b/my/core/utils/concurrent.py @@ -47,5 +47,5 @@ class DummyExecutor(Executor): return f - def shutdown(self, wait: bool = True, **kwargs) -> None: # noqa: FBT001,FBT002 + def shutdown(self, wait: bool = True, **kwargs) -> None: # noqa: FBT001,FBT002,ARG002 self._shutdown = True diff --git a/my/demo.py b/my/demo.py index e27b5dd..0c54792 100644 --- a/my/demo.py +++ b/my/demo.py @@ -3,7 +3,6 @@ Just a demo module for testing and documentation purposes ''' import json -from abc import abstractmethod from dataclasses import dataclass from datetime import datetime, timezone, tzinfo from pathlib import Path diff --git a/my/endomondo.py b/my/endomondo.py index 1d7acc2..293a542 100644 --- a/my/endomondo.py +++ b/my/endomondo.py @@ -31,7 +31,7 @@ def inputs() -> Sequence[Path]: # todo add a doctor check for pip endoexport module import endoexport.dal as dal -from endoexport.dal import Point, Workout +from endoexport.dal import Point, Workout # noqa: F401 from .core import Res diff --git a/my/foursquare.py b/my/foursquare.py index 63e1837..394fdf3 100644 --- a/my/foursquare.py +++ b/my/foursquare.py @@ -4,7 +4,6 @@ Foursquare/Swarm checkins from datetime import datetime, timezone, timedelta from itertools import chain -from pathlib import Path import json # TODO pytz for timezone??? diff --git a/my/hackernews/common.py b/my/hackernews/common.py index 0c5ff9b..6990987 100644 --- a/my/hackernews/common.py +++ b/my/hackernews/common.py @@ -1,6 +1,6 @@ from typing import Protocol -from my.core import datetime_aware, Json +from my.core import datetime_aware def hackernews_link(id: str) -> str: diff --git a/my/jawbone/plots.py b/my/jawbone/plots.py index 5dcb63d..d26d606 100755 --- a/my/jawbone/plots.py +++ b/my/jawbone/plots.py @@ -3,7 +3,6 @@ from pathlib import Path # from kython.plotting import * from csv import DictReader -from itertools import islice from typing import Dict, Any, NamedTuple diff --git a/mypy.ini b/mypy.ini index ebc81a5..9c34fcc 100644 --- a/mypy.ini +++ b/mypy.ini @@ -1,18 +1,13 @@ [mypy] -namespace_packages = True pretty = True show_error_context = True -show_error_codes = True show_column_numbers = True show_error_end = True +warn_redundant_casts = True warn_unused_ignores = True check_untyped_defs = True -enable_error_code = possibly-undefined strict_equality = True - -# a bit annoying, it has optional ipython import which should be ignored in mypy-core configuration.. -[mypy-my.core.__main__] -warn_unused_ignores = False +enable_error_code = possibly-undefined # todo ok, maybe it wasn't such a good idea.. # mainly because then tox picks it up and running against the user config, not the repository config diff --git a/ruff.toml b/ruff.toml index 0d3bb16..5fbd657 100644 --- a/ruff.toml +++ b/ruff.toml @@ -9,6 +9,7 @@ lint.extend-select = [ "C4", # flake8-comprehensions -- unnecessary list/map/dict calls "COM", # trailing commas "EXE", # various checks wrt executable files + # "I", # sort imports "ICN", # various import conventions "FBT", # detect use of boolean arguments "FURB", # various rules @@ -23,26 +24,26 @@ lint.extend-select = [ "RET", # early returns "RUF", # various ruff-specific rules "TID", # various imports suggestions - "TCH", # various type checking rules "TRY", # various exception handling rules "UP", # detect deprecated python stdlib stuff - # "FA", # TODO enable later after we make sure cachew works? + # "FA", # suggest using from __future__ import annotations TODO enable later after we make sure cachew works? # "PTH", # pathlib migration -- TODO enable later - # "ARG", # TODO useful, but results in some false positives in pytest fixtures... maybe later - # "A", # TODO builtin shadowing -- handle later - # "S", # bandit (security checks) -- tends to be not very useful, lots of nitpicks - # "DTZ", # datetimes checks -- complaining about missing tz and mostly false positives + "ARG", # unused argument checks + # "A", # builtin shadowing -- TODO handle later # "EM", # TODO hmm could be helpful to prevent duplicate err msg in traceback.. but kinda annoying - # "FIX", # complains about fixmes/todos -- annoying - # "TD", # complains about todo formatting -- too annoying - # "ANN", # missing type annotations? seems way to string though # "ALL", # uncomment this to check for new rules! ] lint.ignore = [ - "D", # annoying nags about docstrings - "N", # pep naming + "D", # annoying nags about docstrings + "N", # pep naming + "TCH", # type checking rules, mostly just suggests moving imports under TYPE_CHECKING + "S", # bandit (security checks) -- tends to be not very useful, lots of nitpicks + "DTZ", # datetimes checks -- complaining about missing tz and mostly false positives + "FIX", # complains about fixmes/todos -- annoying + "TD", # complains about todo formatting -- too annoying + "ANN", # missing type annotations? seems way to strict though ### too opinionated style checks "E501", # too long lines @@ -62,10 +63,9 @@ lint.ignore = [ "E402", # Module level import not at top of file ### maybe consider these soon -# sometimes it's useful to give a variable a name even if we don't use it as a documentation -# on the other hand, often is a sign of error + # sometimes it's useful to give a variable a name even if we don't use it as a documentation + # on the other hand, often is a sign of error "F841", # Local variable `count` is assigned to but never used - "F401", # imported but unused ### ### TODO should be fine to use these with from __future__ import annotations? @@ -90,8 +90,10 @@ lint.ignore = [ "B009", # calling gettattr with constant attribute -- this is useful to convince mypy "B010", # same as above, but setattr + "B011", # complains about assert False "B017", # pytest.raises(Exception) "B023", # seems to result in false positives? + "B028", # suggest using explicit stacklevel? TODO double check later, but not sure it's useful # complains about useless pass, but has sort of a false positive if the function has a docstring? # this is common for click entrypoints (e.g. in __main__), so disable @@ -115,7 +117,7 @@ lint.ignore = [ "PT011", # pytest raises should is too broad "PT012", # pytest raises should contain a single statement - "COM812", # trailing comma missing -- TODO maybe use this? + "COM812", # trailing comma missing -- mostly just being annoying with long multiline strings "PD901", # generic variable name df @@ -125,15 +127,12 @@ lint.ignore = [ "TRY400", # TODO double check this, might be useful "TRY401", # redundant exception in logging.exception call? TODO double check, might result in excessive logging - "TCH002", # suggests moving imports into type checking blocks -- too annoying - "TCH003", # suggests moving imports into type checking blocks -- too annoying - - "I001", # unsorted import block TODO consider these? "PGH", # TODO force error code in mypy instead - # TODO enable TID? "TID252", # Prefer absolute imports over relative imports from parent modules + "UP038", # suggests using | (union) in isisntance checks.. but it results in slower code + ## too annoying "T20", # just complains about prints and pprints "Q", # flake quotes, too annoying @@ -144,5 +143,9 @@ lint.ignore = [ "BLE001", # do not catch 'blind' Exception "INP001", # complains about implicit namespace packages "SIM", # some if statements crap + "RSE102", # complains about missing parens in exceptions ## + + "ARG001", # ugh, kinda annoying when using pytest fixtures + "F401" , # TODO nice to have, but annoying with NOT_HPI_MODULE thing ] From 27178c09398939d01803e27fcc28d0cefa6d1422 Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Fri, 13 Sep 2024 01:18:40 +0100 Subject: [PATCH 098/122] my.google.takeout.parser: speedup event merging on newer google_takeout_parser versions --- my/google/takeout/parser.py | 19 +++++++++++++++---- my/youtube/takeout.py | 12 ++++++------ 2 files changed, 21 insertions(+), 10 deletions(-) diff --git a/my/google/takeout/parser.py b/my/google/takeout/parser.py index 258ab96..170553a 100644 --- a/my/google/takeout/parser.py +++ b/my/google/takeout/parser.py @@ -31,6 +31,7 @@ ABBR_TIMEZONES.extend(user_forced()) import google_takeout_parser from google_takeout_parser.path_dispatch import TakeoutParser from google_takeout_parser.merge import GoogleEventSet, CacheResults +from google_takeout_parser.models import BaseEvent # see https://github.com/seanbreckenridge/dotfiles/blob/master/.config/my/my/config/__init__.py for an example from my.config import google as user_config @@ -95,6 +96,17 @@ def events(disable_takeout_cache: bool = DISABLE_TAKEOUT_CACHE) -> CacheResults: error_policy = config.error_policy count = 0 emitted = GoogleEventSet() + + try: + emitted_add = emitted.add_if_not_present + except AttributeError: + # compat for older versions of google_takeout_parser which didn't have this method + def emitted_add(other: BaseEvent) -> bool: + if other in emitted: + return False + emitted.add(other) + return True + # reversed shouldn't really matter? but logic is to use newer # takeouts if they're named according to date, since JSON Activity # is nicer than HTML Activity @@ -123,10 +135,9 @@ def events(disable_takeout_cache: bool = DISABLE_TAKEOUT_CACHE) -> CacheResults: elif error_policy == 'drop': pass continue - if event in emitted: - continue - emitted.add(event) - yield event # type: ignore[misc] + + if emitted_add(event): + yield event # type: ignore[misc] logger.debug( f"HPI Takeout merge: from a total of {count} events, removed {count - len(emitted)} duplicates" ) diff --git a/my/youtube/takeout.py b/my/youtube/takeout.py index 99d65d9..284c082 100644 --- a/my/youtube/takeout.py +++ b/my/youtube/takeout.py @@ -1,10 +1,10 @@ from typing import NamedTuple, List, Iterable, TYPE_CHECKING -from ..core import datetime_aware, Res, LazyLogger -from ..core.compat import removeprefix +from my.core import datetime_aware, make_logger, stat, Res, Stats +from my.core.compat import deprecated, removeprefix -logger = LazyLogger(__name__) +logger = make_logger(__name__) class Watched(NamedTuple): @@ -93,7 +93,6 @@ def watched() -> Iterable[Res[Watched]]: ) -from ..core import stat, Stats def stats() -> Stats: return stat(watched) @@ -101,8 +100,9 @@ def stats() -> Stats: ### deprecated stuff (keep in my.media.youtube) if not TYPE_CHECKING: - # "deprecate" by hiding from mypy - get_watched = watched + @deprecated("use 'watched' instead") + def get_watched(*args, **kwargs): + return watched(*args, **kwargs) def _watched_legacy() -> Iterable[Watched]: From 201ddd4d7c45f63f3e3196f6b9be22402822680d Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Mon, 16 Sep 2024 23:41:58 +0100 Subject: [PATCH 099/122] my.core.structure: add support for .tar.gz archives this will be useful to migrate .tar.gz processing to kompress in a backwards compatible way, or to run them against unpacked folder structure if user prefers --- my/core/structure.py | 47 +++++++++++------- my/core/tests/structure.py | 7 +-- .../tests/structure_data/gdpr_export.tar.gz | Bin 0 -> 349 bytes 3 files changed, 33 insertions(+), 21 deletions(-) create mode 100644 my/core/tests/structure_data/gdpr_export.tar.gz diff --git a/my/core/structure.py b/my/core/structure.py index be5b307..fa26532 100644 --- a/my/core/structure.py +++ b/my/core/structure.py @@ -1,6 +1,8 @@ import atexit import os import shutil +import sys +import tarfile import tempfile import zipfile from contextlib import contextmanager @@ -34,6 +36,7 @@ def _structure_exists(base_dir: Path, paths: Sequence[str], *, partial: bool = F ZIP_EXT = {".zip"} +TARGZ_EXT = {".tar.gz"} @contextmanager @@ -44,7 +47,7 @@ def match_structure( partial: bool = False, ) -> Generator[Tuple[Path, ...], None, None]: """ - Given a 'base' directory or zipfile, recursively search for one or more paths that match the + Given a 'base' directory or archive (zip/tar.gz), recursively search for one or more paths that match the pattern described in 'expected'. That can be a single string, or a list of relative paths (as strings) you expect at the same directory. @@ -52,12 +55,12 @@ def match_structure( expected be present, not all of them. This reduces the chances of the user misconfiguring gdpr exports, e.g. - if they zipped the folders instead of the parent directory or vice-versa + if they archived the folders instead of the parent directory or vice-versa When this finds a matching directory structure, it stops searching in that subdirectory and continues onto other possible subdirectories which could match - If base is a zipfile, this extracts the zipfile into a temporary directory + If base is an archive, this extracts it into a temporary directory (configured by core_config.config.get_tmp_dir), and then searches the extracted folder for matching structures @@ -93,12 +96,12 @@ def match_structure( This doesn't require an exhaustive list of expected values, but its a good idea to supply a complete picture of the expected structure to avoid false-positives - This does not recursively unzip zipfiles in the subdirectories, - it only unzips into a temporary directory if 'base' is a zipfile + This does not recursively decompress archives in the subdirectories, + it only unpacks into a temporary directory if 'base' is an archive A common pattern for using this might be to use get_files to get a list - of zipfiles or top-level gdpr export directories, and use match_structure - to search the resulting paths for a export structure you're expecting + of archives or top-level gdpr export directories, and use match_structure + to search the resulting paths for an export structure you're expecting """ from . import core_config as CC @@ -108,26 +111,34 @@ def match_structure( expected = (expected,) is_zip: bool = base.suffix in ZIP_EXT + is_targz: bool = any(base.name.endswith(suffix) for suffix in TARGZ_EXT) searchdir: Path = base.absolute() try: - # if the file given by the user is a zipfile, create a temporary - # directory and extract the zipfile to that temporary directory + # if the file given by the user is an archive, create a temporary + # directory and extract it to that temporary directory # # this temporary directory is removed in the finally block - if is_zip: + if is_zip or is_targz: # sanity check before we start creating directories/rm-tree'ing things - assert base.exists(), f"zipfile at {base} doesn't exist" + assert base.exists(), f"archive at {base} doesn't exist" searchdir = Path(tempfile.mkdtemp(dir=tdir)) - # base might already be a ZipPath, and str(base) would end with / - zf = zipfile.ZipFile(str(base).rstrip('/')) - zf.extractall(path=str(searchdir)) - + if is_zip: + # base might already be a ZipPath, and str(base) would end with / + zf = zipfile.ZipFile(str(base).rstrip('/')) + zf.extractall(path=str(searchdir)) + elif is_targz: + with tarfile.open(str(base)) as tar: + # filter is a security feature, will be required param in later python version + mfilter = {'filter': 'data'} if sys.version_info[:2] >= (3, 12) else {} + tar.extractall(path=str(searchdir), **mfilter) # type: ignore[arg-type] + else: + raise RuntimeError("can't happen") else: if not searchdir.is_dir(): - raise NotADirectoryError(f"Expected either a zipfile or a directory, received {searchdir}") + raise NotADirectoryError(f"Expected either a zip/tar.gz archive or a directory, received {searchdir}") matches: List[Path] = [] possible_targets: List[Path] = [searchdir] @@ -150,9 +161,9 @@ def match_structure( finally: - if is_zip: + if is_zip or is_targz: # make sure we're not mistakenly deleting data - assert str(searchdir).startswith(str(tdir)), f"Expected the temporary directory for extracting zip to start with the temporary directory prefix ({tdir}), found {searchdir}" + assert str(searchdir).startswith(str(tdir)), f"Expected the temporary directory for extracting archive to start with the temporary directory prefix ({tdir}), found {searchdir}" shutil.rmtree(str(searchdir)) diff --git a/my/core/tests/structure.py b/my/core/tests/structure.py index 6a94fc4..741e0ea 100644 --- a/my/core/tests/structure.py +++ b/my/core/tests/structure.py @@ -14,8 +14,9 @@ def test_gdpr_structure_exists() -> None: assert results == (structure_data / "gdpr_subdirs" / "gdpr_export",) -def test_gdpr_unzip() -> None: - with match_structure(structure_data / "gdpr_export.zip", expected=gdpr_expected) as results: +@pytest.mark.parametrize("archive", ["gdpr_export.zip", "gdpr_export.tar.gz"]) +def test_gdpr_unpack(archive: str) -> None: + with match_structure(structure_data / archive, expected=gdpr_expected) as results: assert len(results) == 1 extracted = results[0] index_file = extracted / "messages" / "index.csv" @@ -32,6 +33,6 @@ def test_match_partial() -> None: def test_not_directory() -> None: - with pytest.raises(NotADirectoryError, match=r"Expected either a zipfile or a directory"): + with pytest.raises(NotADirectoryError, match=r"Expected either a zip/tar.gz archive or a directory"): with match_structure(structure_data / "messages/index.csv", expected=gdpr_expected): pass diff --git a/my/core/tests/structure_data/gdpr_export.tar.gz b/my/core/tests/structure_data/gdpr_export.tar.gz new file mode 100644 index 0000000000000000000000000000000000000000..4f0597cdc7f3aa062ae896786375c5df87d49ec0 GIT binary patch literal 349 zcmV-j0iymNiwFP!000021MQgYZh|lrhWmS0!4+sf=;`GcgpM$UlC~O?W%s_i%*2^Y zXFZ&OZgnulN@i{zdo#NJi2B!+HOBA;|M`W&T_3Tv6*Z`7g2m&BlMz zRr;_f-9Fy`jr_m#&-tr{*NS^|K6I{W~;~O0r%hkN&(*g^YHJq_f1z1i2s=UmlQDnG5?Wd^FP|(pSb=n v1m^!d{15&6^N0Ko&VTw3+YIx63cPkc`*w{t0fHb1f; Date: Wed, 18 Sep 2024 23:03:03 +0100 Subject: [PATCH 100/122] my.github.gdpr/my.zulip.organization: use kompress support for tar.gz if it's available otherwise fall back onto unpacking into tmp dir via my.core.structure --- my/core/kompress.py | 6 +-- my/github/gdpr.py | 106 +++++++++++++++++++++++---------------- my/zulip/organization.py | 91 ++++++++++++++++++++++----------- setup.py | 14 +++--- 4 files changed, 135 insertions(+), 82 deletions(-) diff --git a/my/core/kompress.py b/my/core/kompress.py index 6ab3228..7cbf310 100644 --- a/my/core/kompress.py +++ b/my/core/kompress.py @@ -1,4 +1,5 @@ from .internal import assert_subpackage; assert_subpackage(__name__) + from . import warnings # do this later -- for now need to transition modules to avoid using kompress directly (e.g. ZipPath) @@ -8,10 +9,7 @@ try: from kompress import * except ModuleNotFoundError as e: if e.name == 'kompress': - warnings.high('Please install kompress (pip3 install kompress), it will be required in the future. Falling onto vendorized kompress for now.') + warnings.high('Please install kompress (pip3 install kompress). Falling onto vendorized kompress for now.') from ._deprecated.kompress import * # type: ignore[assignment] else: raise e - -# this is deprecated in compress, keep here for backwards compatibility -open = kopen # noqa: F405 diff --git a/my/github/gdpr.py b/my/github/gdpr.py index acbeb8f..a56ff46 100644 --- a/my/github/gdpr.py +++ b/my/github/gdpr.py @@ -1,36 +1,42 @@ """ Github data (uses [[https://github.com/settings/admin][official GDPR export]]) """ -from dataclasses import dataclass + +from __future__ import annotations + import json +from abc import abstractmethod from pathlib import Path -import tarfile -from typing import Iterable, Any, Sequence, Dict, Optional +from typing import Any, Iterator, Sequence -from my.core import get_files, Res, PathIsh, stat, Stats, make_logger -from my.core.cfg import make_config -from my.core.error import notnone, echain - -from .common import Event, parse_dt, EventIds - -# TODO later, use a separate user config? (github_gdpr) -from my.config import github as user_config - - -@dataclass -class github(user_config): - gdpr_dir: PathIsh # path to unpacked GDPR archive - - -config = make_config(github) +from my.core import Paths, Res, Stats, get_files, make_logger, stat, warnings +from my.core.error import echain +from .common import Event, EventIds, parse_dt logger = make_logger(__name__) +class config: + @property + @abstractmethod + def gdpr_dir(self) -> Paths: + raise NotImplementedError + + +def make_config() -> config: + # TODO later, use a separate user config? (github_gdpr) + from my.config import github as user_config + + class combined_config(user_config, config): + pass + + return combined_config() + + def inputs() -> Sequence[Path]: - gdir = config.gdpr_dir - res = get_files(gdir) + gdpr_dir = make_config().gdpr_dir + res = get_files(gdpr_dir) schema_json = [f for f in res if f.name == 'schema.json'] was_unpacked = len(schema_json) > 0 if was_unpacked: @@ -43,22 +49,37 @@ def inputs() -> Sequence[Path]: return res -def events() -> Iterable[Res[Event]]: +def events() -> Iterator[Res[Event]]: last = max(inputs()) logger.info(f'extracting data from {last}') - # a bit naughty and ad-hoc, but we will generify reading from tar.gz. once we have more examples - # another one is zulip archive - if last.is_dir(): - files = sorted(last.glob('*.json')) # looks like all files are in the root - open_file = lambda f: f.open() + root: Path | None = None + + if last.is_dir(): # if it's already CPath, this will match it + root = last else: - # treat as .tar.gz - tfile = tarfile.open(last) - files = sorted(map(Path, tfile.getnames())) - files = [p for p in files if len(p.parts) == 1 and p.suffix == '.json'] - open_file = lambda p: notnone(tfile.extractfile(f'./{p}')) # NOTE odd, doesn't work without ./ + try: + from kompress import CPath + + root = CPath(last) + assert len(list(root.iterdir())) > 0 # trigger to check if we have the kompress version with targz support + except Exception as e: + logger.exception(e) + warnings.high("Upgrade 'kompress' to latest version with native .tar.gz support. Falling back to unpacking to tmp dir.") + + if root is None: + from my.core.structure import match_structure + + with match_structure(last, expected=()) as res: # expected=() matches it regardless any patterns + [root] = res + yield from _process_one(root) + else: + yield from _process_one(root) + + +def _process_one(root: Path) -> Iterator[Res[Event]]: + files = sorted(root.glob('*.json')) # looks like all files are in the root # fmt: off handler_map = { @@ -100,8 +121,7 @@ def events() -> Iterable[Res[Event]]: # ignored continue - with open_file(f) as fo: - j = json.load(fo) + j = json.loads(f.read_text()) for r in j: try: yield handler(r) @@ -116,7 +136,7 @@ def stats() -> Stats: # TODO typing.TypedDict could be handy here.. -def _parse_common(d: Dict) -> Dict: +def _parse_common(d: dict) -> dict: url = d['url'] body = d.get('body') return { @@ -126,7 +146,7 @@ def _parse_common(d: Dict) -> Dict: } -def _parse_repository(d: Dict) -> Event: +def _parse_repository(d: dict) -> Event: pref = 'https://github.com/' url = d['url'] dts = d['created_at'] @@ -142,13 +162,13 @@ def _parse_repository(d: Dict) -> Event: # user may be None if the user was deleted -def _is_bot(user: Optional[str]) -> bool: +def _is_bot(user: str | None) -> bool: if user is None: return False return "[bot]" in user -def _parse_issue_comment(d: Dict) -> Event: +def _parse_issue_comment(d: dict) -> Event: url = d['url'] return Event( **_parse_common(d), @@ -158,7 +178,7 @@ def _parse_issue_comment(d: Dict) -> Event: ) -def _parse_issue(d: Dict) -> Event: +def _parse_issue(d: dict) -> Event: url = d['url'] title = d['title'] return Event( @@ -169,7 +189,7 @@ def _parse_issue(d: Dict) -> Event: ) -def _parse_pull_request(d: Dict) -> Event: +def _parse_pull_request(d: dict) -> Event: dts = d['created_at'] url = d['url'] title = d['title'] @@ -183,7 +203,7 @@ def _parse_pull_request(d: Dict) -> Event: ) -def _parse_project(d: Dict) -> Event: +def _parse_project(d: dict) -> Event: url = d['url'] title = d['name'] is_bot = "[bot]" in d["creator"] @@ -198,7 +218,7 @@ def _parse_project(d: Dict) -> Event: ) -def _parse_release(d: Dict) -> Event: +def _parse_release(d: dict) -> Event: tag = d['tag_name'] return Event( **_parse_common(d), @@ -207,7 +227,7 @@ def _parse_release(d: Dict) -> Event: ) -def _parse_commit_comment(d: Dict) -> Event: +def _parse_commit_comment(d: dict) -> Event: url = d['url'] return Event( **_parse_common(d), diff --git a/my/zulip/organization.py b/my/zulip/organization.py index 8725411..2e0df4b 100644 --- a/my/zulip/organization.py +++ b/my/zulip/organization.py @@ -1,38 +1,55 @@ """ Zulip data from [[https://memex.zulipchat.com/help/export-your-organization][Organization export]] """ + +from __future__ import annotations + +import json +from abc import abstractmethod from dataclasses import dataclass from datetime import datetime, timezone from itertools import count -import json from pathlib import Path -from typing import Sequence, Iterator, Dict, Union +from typing import Iterator, Sequence from my.core import ( - assert_never, - datetime_aware, - get_files, - stat, Json, Paths, Res, Stats, + assert_never, + datetime_aware, + get_files, + make_logger, + stat, + warnings, ) -from my.core.error import notnone -import my.config + +logger = make_logger(__name__) -@dataclass -class organization(my.config.zulip.organization): - # paths[s]/glob to the exported JSON data - export_path: Paths +class config: + @property + @abstractmethod + def export_path(self) -> Paths: + """paths[s]/glob to the exported JSON data""" + raise NotImplementedError + + +def make_config() -> config: + from my.config import zulip as user_config + + class combined_config(user_config.organization, config): + pass + + return combined_config() def inputs() -> Sequence[Path]: # TODO: seems like export ids are kinda random.. # not sure what's the best way to figure out the last without renaming? # could use mtime perhaps? - return get_files(organization.export_path, sort=False) + return get_files(make_config().export_path, sort=False) @dataclass(frozen=True) @@ -85,19 +102,39 @@ class Message: # todo cache it -def _entities() -> Iterator[Res[Union[Server, Sender, _Message]]]: +def _entities() -> Iterator[Res[Server | Sender | _Message]]: last = max(inputs()) - # todo would be nice to switch it to unpacked dirs as well, similar to ZipPath - # I guess makes sense to have a special implementation for .tar.gz considering how common are they - import tarfile + logger.info(f'extracting data from {last}') - tfile = tarfile.open(last) + root: Path | None = None - subdir = tfile.getnames()[0] # there is a directory inside tar file, first name should be that + if last.is_dir(): # if it's already CPath, this will match it + root = last + else: + try: + from kompress import CPath - with notnone(tfile.extractfile(f'{subdir}/realm.json')) as fo: - rj = json.load(fo) + root = CPath(last) + assert len(list(root.iterdir())) > 0 # trigger to check if we have the kompress version with targz support + except Exception as e: + logger.exception(e) + warnings.high("Upgrade 'kompress' to latest version with native .tar.gz support. Falling back to unpacking to tmp dir.") + + if root is None: + from my.core.structure import match_structure + + with match_structure(last, expected=()) as res: # expected=() matches it regardless any patterns + [root] = res + yield from _process_one(root) + else: + yield from _process_one(root) + + +def _process_one(root: Path) -> Iterator[Res[Server | Sender | _Message]]: + [subdir] = root.iterdir() # there is a directory inside tar file, first name should be that + + rj = json.loads((subdir / 'realm.json').read_text()) [sj] = rj['zerver_realm'] server = Server( @@ -136,12 +173,10 @@ def _entities() -> Iterator[Res[Union[Server, Sender, _Message]]]: for idx in count(start=1, step=1): fname = f'messages-{idx:06}.json' - fpath = f'{subdir}/{fname}' - if fpath not in tfile.getnames(): - # tarfile doesn't have .exists? + fpath = subdir / fname + if not fpath.exists(): break - with notnone(tfile.extractfile(fpath)) as fo: - mj = json.load(fo) + mj = json.loads(fpath.read_text()) # TODO handle zerver_usermessage for j in mj['zerver_message']: try: @@ -151,8 +186,8 @@ def _entities() -> Iterator[Res[Union[Server, Sender, _Message]]]: def messages() -> Iterator[Res[Message]]: - id2sender: Dict[int, Sender] = {} - id2server: Dict[int, Server] = {} + id2sender: dict[int, Sender] = {} + id2server: dict[int, Server] = {} for x in _entities(): if isinstance(x, Exception): yield x diff --git a/setup.py b/setup.py index cf4b79f..8335851 100644 --- a/setup.py +++ b/setup.py @@ -4,13 +4,13 @@ from setuptools import setup, find_namespace_packages # type: ignore INSTALL_REQUIRES = [ - 'pytz', # even though it's not needed by the core, it's so common anyway... - 'typing-extensions', # one of the most common pypi packages, ok to depend for core - 'appdirs', # very common, and makes it portable - 'more-itertools', # it's just too useful and very common anyway - 'decorator' , # less pain in writing correct decorators. very mature and stable, so worth keeping in core - 'click>=8.1' , # for the CLI, printing colors, decorator-based - may allow extensions to CLI - 'kompress' , # for transparent access to compressed files via pathlib.Path + 'pytz' , # even though it's not needed by the core, it's so common anyway... + 'typing-extensions' , # one of the most common pypi packages, ok to depend for core + 'appdirs' , # very common, and makes it portable + 'more-itertools' , # it's just too useful and very common anyway + 'decorator' , # less pain in writing correct decorators. very mature and stable, so worth keeping in core + 'click>=8.1' , # for the CLI, printing colors, decorator-based - may allow extensions to CLI + 'kompress>=0.2.20240918' , # for transparent access to compressed files via pathlib.Path ] From 2ca323da8487a2f99d283bd78c8141a35b700cb3 Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Sat, 21 Sep 2024 23:18:50 +0100 Subject: [PATCH 101/122] my.fbmessenger.android: exclude unsent messages to avoid duplication --- my/fbmessenger/android.py | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/my/fbmessenger/android.py b/my/fbmessenger/android.py index 7e48c78..effabab 100644 --- a/my/fbmessenger/android.py +++ b/my/fbmessenger/android.py @@ -168,6 +168,15 @@ def _process_db_msys(db: sqlite3.Connection) -> Iterator[Res[Entity]]: CAST(sender_id AS TEXT) AS sender_id, reply_source_id FROM messages + WHERE + /* Regular message_id conforms to mid.* regex. + However seems that when message is not sent yet it doesn't have this server id yet + (happened only once, but could be just luck of course!) + We exclude these messages to avoid duplication. + However poisitive filter (e.g. message_id LIKE 'mid%') feels a bit wrong, e.g. what if mesage ids change or something + So instead this excludes only such unsent messages. + */ + message_id != offline_threading_id ORDER BY timestamp_ms /* they aren't in order in the database, so need to sort */ ''' ): From e036cc9e8523debe92829ec7dc7b3b867860535f Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Sat, 21 Sep 2024 23:55:06 +0100 Subject: [PATCH 102/122] my.twitter.android: get own user id as string, consistent with rest of module --- my/twitter/android.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/my/twitter/android.py b/my/twitter/android.py index 7adfeb6..ada04ae 100644 --- a/my/twitter/android.py +++ b/my/twitter/android.py @@ -156,10 +156,11 @@ def get_own_user_id(conn) -> str: # unclear what's the reliable way to query it, so we use multiple different ones and arbitrate # NOTE: 'SELECT DISTINCT ev_owner_id FROM lists' doesn't work, might include lists from other people? res: Set[str] = set() + # need to cast as it's int by default for q in [ - 'SELECT DISTINCT list_mapping_user_id FROM list_mapping', - 'SELECT DISTINCT owner_id FROM cursors', - 'SELECT DISTINCT user_id FROM users WHERE _id == 1', + 'SELECT DISTINCT CAST(list_mapping_user_id AS TEXT) FROM list_mapping', + 'SELECT DISTINCT CAST(owner_id AS TEXT) FROM cursors', + 'SELECT DISTINCT CAST(user_id AS TEXT) FROM users WHERE _id == 1', ]: for (r,) in conn.execute(q): res.add(r) From 239e6617fe62f7b14e71092175148255a10f4ac9 Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Sun, 22 Sep 2024 01:48:12 +0100 Subject: [PATCH 103/122] my.twitter.archive: deduplicate tweets based on id_str/created_at and raw tweet text --- my/twitter/archive.py | 73 +++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 71 insertions(+), 2 deletions(-) diff --git a/my/twitter/archive.py b/my/twitter/archive.py index d326d70..5fa89f4 100644 --- a/my/twitter/archive.py +++ b/my/twitter/archive.py @@ -226,11 +226,80 @@ class ZipExport: yield Like(r, screen_name=self.screen_name) +def _cleanup_tweet_json(rj: Json) -> None: + # note: for now this isn't used, was just an attempt to normalise raw data... + + rj.pop('edit_info', None) # useless for downstream processing, but results in dupes, so let's remove it + + ## could probably just take the last one? dunno + rj.pop('retweet_count', None) + rj.pop('favorite_count', None) + ## + + entities = rj.get('entities', {}) + ext_entities = rj.get('extended_entities', {}) + + # TODO shit. unclear how to 'merge' changes to these + # links sometimes change for no apparent reason -- and sometimes old one is still valid but not the new one??? + for m in entities.get('media', {}): + m.pop('media_url', None) + m.pop('media_url_https', None) + for m in ext_entities.get('media', {}): + m.pop('media_url', None) + m.pop('media_url_https', None) + ## + + for m in entities.get('user_mentions', {}): + # changes if user renames themselves... + m.pop('name', None) + + # hmm so can change to -1? maybe if user was deleted? + # but also can change to actually something else?? second example + entities.pop('user_mentions', None) + + # TODO figure out what else is changing there later... + rj.pop('entities', None) + rj.pop('extended_entities', None) + + ## useless attributes which should be fine to exclude + rj.pop('possibly_sensitive', None) # not sure what is this.. sometimes appears with False value?? + rj.pop('withheld_in_countries', None) + rj.pop('lang', None) + ## + + # ugh. might change if the Twitter client was deleted or description renamed?? + rj.pop('source', None) + + ## ugh. sometimes trailing 0 after decimal point is present? + rj.pop('coordinates', None) + rj.get('geo', {}).pop('coordinates', None) + ## + + # ugh. this changes if user changed their name... + # or disappears if account was deleted? + rj.pop('in_reply_to_screen_name', None) + + # todo not sure about list and sorting? although can't hurt considering json is not iterative? def tweets() -> Iterator[Res[Tweet]]: _all = chain.from_iterable(ZipExport(i).tweets() for i in inputs()) - res = unique_everseen(_all, key=json_dumps) - yield from sorted(res, key=lambda t: t.dt) + + # NOTE raw json data in archived tweets changes all the time even for same tweets + # there is an attempt to clean it up... but it's tricky since users rename themselves, twitter stats are changing + # so it's unclear how to pick up + # we should probably 'merge' tweets into a canonical version, e.g. + # - pick latest tweet stats + # - keep history of usernames we were replying to that share the same user id + # - pick 'best' media url somehow?? + # - normalise coordinates data + def key(t: Tweet): + # NOTE: not using t.text, since it actually changes if entities in tweet are changing... + # whereas full_text seems stable + text = t.raw['full_text'] + return (t.created_at, t.id_str, text) + + res = unique_everseen(_all, key=key) + yield from sorted(res, key=lambda t: t.created_at) def likes() -> Iterator[Res[Like]]: From 02dabe9f2b90a472fc878aa31ee7299e094b137d Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Sun, 22 Sep 2024 02:03:28 +0100 Subject: [PATCH 104/122] my.twitter.archive: cleanup linting and use proper configuration via abstract class --- my/twitter/archive.py | 97 ++++++++++++++++++++++--------------------- 1 file changed, 50 insertions(+), 47 deletions(-) diff --git a/my/twitter/archive.py b/my/twitter/archive.py index 5fa89f4..1573754 100644 --- a/my/twitter/archive.py +++ b/my/twitter/archive.py @@ -2,73 +2,75 @@ Twitter data (uses [[https://help.twitter.com/en/managing-your-account/how-to-download-your-twitter-archive][official twitter archive export]]) """ +from __future__ import annotations -# before this config was named 'twitter', doesn't make too much sense for archive -# todo unify with other code like this, e.g. time.tz.via_location -try: - from my.config import twitter_archive as user_config -except ImportError as ie: - if not (ie.name == 'my.config' and 'twitter_archive' in str(ie)): - # must be caused by something else - raise ie - try: - from my.config import twitter as user_config # type: ignore[assignment] - except ImportError: - raise ie # raise the original exception.. must be something else # noqa: B904 - else: - from my.core import warnings - warnings.high('my.config.twitter is deprecated! Please rename it to my.config.twitter_archive in your config') -## - - +import html +import json # hmm interesting enough, orjson didn't give much speedup here? +from abc import abstractmethod from dataclasses import dataclass from datetime import datetime -from itertools import chain -import json # hmm interesting enough, orjson didn't give much speedup here? -from pathlib import Path from functools import cached_property -import html +from itertools import chain +from pathlib import Path from typing import ( + TYPE_CHECKING, Iterator, - List, - Optional, Sequence, ) from more_itertools import unique_everseen from my.core import ( - datetime_aware, - get_files, - make_logger, - stat, Json, Paths, Res, Stats, + datetime_aware, + get_files, + make_logger, + stat, + warnings, ) -from my.core import warnings -from my.core.cfg import make_config from my.core.serialize import dumps as json_dumps from .common import TweetId, permalink - -@dataclass -class twitter_archive(user_config): - export_path: Paths # path[s]/glob to the twitter archive takeout - - -### - -config = make_config(twitter_archive) - - logger = make_logger(__name__) +class config: + @property + @abstractmethod + def export_path(self) -> Paths: + """path[s]/glob to the twitter archive takeout""" + raise NotImplementedError + + +def make_config() -> config: + # before this config was named 'twitter', doesn't make too much sense for archive + # todo unify with other code like this, e.g. time.tz.via_location + try: + from my.config import twitter_archive as user_config + except ImportError as ie: + if not (ie.name == 'my.config' and 'twitter_archive' in str(ie)): + # must be caused by something else + raise ie + try: + from my.config import twitter as user_config # type: ignore[assignment] + except ImportError: + raise ie # raise the original exception.. must be something else # noqa: B904 + else: + warnings.high('my.config.twitter is deprecated! Please rename it to my.config.twitter_archive in your config') + ## + + class combined_config(user_config, config): + pass + + return combined_config() + + def inputs() -> Sequence[Path]: - return get_files(config.export_path) + return get_files(make_config().export_path) # TODO make sure it's not used anywhere else and simplify interface @@ -121,7 +123,7 @@ class Tweet: return res @property - def urls(self) -> List[str]: + def urls(self) -> list[str]: ents = self.entities us = ents['urls'] return [u['expanded_url'] for u in us] @@ -162,10 +164,10 @@ class Like: return self.raw['tweetId'] @property - def text(self) -> Optional[str]: + def text(self) -> str | None: # NOTE: likes basically don't have anything except text and url # ugh. I think none means that tweet was deleted? - res: Optional[str] = self.raw.get('fullText') + res: str | None = self.raw.get('fullText') if res is None: return None res = html.unescape(res) @@ -186,7 +188,7 @@ class ZipExport: if not (self.zpath / 'Your archive.html').exists(): self.old_format = True - def raw(self, what: str, *, fname: Optional[str] = None) -> Iterator[Json]: + def raw(self, what: str, *, fname: str | None = None) -> Iterator[Json]: logger.info(f'{self.zpath} : processing {what}') path = fname or what @@ -317,4 +319,5 @@ def stats() -> Stats: ## Deprecated stuff -Tid = TweetId +if not TYPE_CHECKING: + Tid = TweetId From 3166109f15c08f8a23e60a384047b7f9125c252b Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Sun, 22 Sep 2024 04:27:32 +0100 Subject: [PATCH 105/122] my.core: fix list constructor in always_support_sequence and add some tests --- my/core/hpi_compat.py | 132 ++++++++++++++++++++++++++++++++++++++---- 1 file changed, 121 insertions(+), 11 deletions(-) diff --git a/my/core/hpi_compat.py b/my/core/hpi_compat.py index 6261c23..949046d 100644 --- a/my/core/hpi_compat.py +++ b/my/core/hpi_compat.py @@ -2,6 +2,7 @@ Contains various backwards compatibility/deprecation helpers relevant to HPI itself. (as opposed to .compat module which implements compatibility between python versions) """ + import inspect import os import re @@ -116,32 +117,141 @@ V = TypeVar('V') # named to be kinda consistent with more_itertools, e.g. more_itertools.always_iterable class always_supports_sequence(Iterator[V]): """ - Helper to make migration from Sequence/List to Iterable/Iterator type backwards compatible + Helper to make migration from Sequence/List to Iterable/Iterator type backwards compatible in runtime """ def __init__(self, it: Iterator[V]) -> None: - self.it = it - self._list: Optional[List] = None + self._it = it + self._list: Optional[List[V]] = None + self._lit: Optional[Iterator[V]] = None def __iter__(self) -> Iterator[V]: # noqa: PYI034 - return self.it.__iter__() + if self._list is not None: + self._lit = iter(self._list) + return self def __next__(self) -> V: - return self.it.__next__() + if self._list is not None: + assert self._lit is not None + delegate = self._lit + else: + delegate = self._it + return next(delegate) def __getattr__(self, name): - return getattr(self.it, name) + return getattr(self._it, name) @property - def aslist(self) -> List[V]: + def _aslist(self) -> List[V]: if self._list is None: - qualname = getattr(self.it, '__qualname__', '') # defensive just in case + qualname = getattr(self._it, '__qualname__', '') # defensive just in case warnings.medium(f'Using {qualname} as list is deprecated. Migrate to iterative processing or call list() explicitly.') - self._list = list(self.it) + self._list = list(self._it) + + # this is necessary for list constructor to work correctly + # since it's __iter__ first, then tries to compute length and then starts iterating... + self._lit = iter(self._list) return self._list def __len__(self) -> int: - return len(self.aslist) + return len(self._aslist) def __getitem__(self, i: int) -> V: - return self.aslist[i] + return self._aslist[i] + + +def test_always_supports_sequence_list_constructor() -> None: + exhausted = 0 + + def it() -> Iterator[str]: + nonlocal exhausted + yield from ['a', 'b', 'c'] + exhausted += 1 + + sit = always_supports_sequence(it()) + + # list constructor is a bit special... it's trying to compute length if it's available to optimize memory allocation + # so, what's happening in this case is + # - sit.__iter__ is called + # - sit.__len__ is called + # - sit.__next__ is called + res = list(sit) + assert res == ['a', 'b', 'c'] + assert exhausted == 1 + + res = list(sit) + assert res == ['a', 'b', 'c'] + assert exhausted == 1 # this will iterate over 'cached' list now, so original generator is only exhausted once + + +def test_always_supports_sequence_indexing() -> None: + exhausted = 0 + + def it() -> Iterator[str]: + nonlocal exhausted + yield from ['a', 'b', 'c'] + exhausted += 1 + + sit = always_supports_sequence(it()) + + assert len(sit) == 3 + assert exhausted == 1 + + assert sit[2] == 'c' + assert sit[1] == 'b' + assert sit[0] == 'a' + assert exhausted == 1 + + # a few tests to make sure list-like operations are working.. + assert list(sit) == ['a', 'b', 'c'] + assert [x for x in sit] == ['a', 'b', 'c'] # noqa: C416 + assert list(sit) == ['a', 'b', 'c'] + assert [x for x in sit] == ['a', 'b', 'c'] # noqa: C416 + assert exhausted == 1 + + +def test_always_supports_sequence_next() -> None: + exhausted = 0 + + def it() -> Iterator[str]: + nonlocal exhausted + yield from ['a', 'b', 'c'] + exhausted += 1 + + sit = always_supports_sequence(it()) + + x = next(sit) + assert x == 'a' + assert exhausted == 0 + + x = next(sit) + assert x == 'b' + assert exhausted == 0 + + +def test_always_supports_sequence_iter() -> None: + exhausted = 0 + + def it() -> Iterator[str]: + nonlocal exhausted + yield from ['a', 'b', 'c'] + exhausted += 1 + + sit = always_supports_sequence(it()) + + for x in sit: + assert x == 'a' + break + + x = next(sit) + assert x == 'b' + + assert exhausted == 0 + + x = next(sit) + assert x == 'c' + assert exhausted == 0 + + for _ in sit: + raise RuntimeError # shouldn't trigger, just exhaust the iterator + assert exhausted == 1 From 75639a3d5ec3b07fb7e6b638e9e3c342a23cc1a2 Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Sun, 22 Sep 2024 19:50:58 +0100 Subject: [PATCH 106/122] tox: some prep for potentially using uv on CI instead of pip see https://github.com/karlicoss/HPI/issues/391 --- setup.py | 10 ++++++++ tox.ini | 78 +++++++++++++++++++++++++++++--------------------------- 2 files changed, 51 insertions(+), 37 deletions(-) diff --git a/setup.py b/setup.py index 8335851..e49eee0 100644 --- a/setup.py +++ b/setup.py @@ -58,6 +58,16 @@ def main() -> None: 'orjson', # for my.core.serialize and denylist 'simplejson', # for my.core.serialize + + ## + # ideally we'd use --instal-types in mypy + # , but looks like it doesn't respect uv venv if it's running in it :( + 'types-pytz' , # for my.core + 'types-decorator' , # for my.core.compat + 'pandas-stubs' , # for my.core.pandas + 'types-dateparser', # for my.core.query_range + 'types-simplejson', # for my.core.serialize + ## ], 'optional': [ # todo document these? diff --git a/tox.ini b/tox.ini index 6b95088..4e5dff6 100644 --- a/tox.ini +++ b/tox.ini @@ -24,16 +24,19 @@ passenv = [testenv:ruff] +install_command = {envpython} -m pip install --use-pep517 {opts} {packages} +deps = + -e .[testing] commands = - {envpython} -m pip install --use-pep517 -e .[testing] {envpython} -m ruff check my/ # just the very core tests with minimal dependencies [testenv:tests-core] +install_command = {envpython} -m pip install --use-pep517 {opts} {packages} +deps = + -e .[testing] commands = - {envpython} -m pip install --use-pep517 -e .[testing] - {envpython} -m pytest \ # importlib is the new suggested import-mode # without it test package names end up as core.tests.* instead of my.core.tests.* @@ -53,31 +56,26 @@ setenv = # TODO not sure if need it? MY_CONFIG=nonexistent HPI_TESTS_USES_OPTIONAL_DEPS=true +install_command = {envpython} -m pip install --use-pep517 {opts} {packages} +deps = + -e .[testing] + cachew + ijson # optional dependency for various modules commands = - {envpython} -m pip install --use-pep517 -e .[testing] - - {envpython} -m pip install cachew - - {envpython} -m my.core module install my.location.google - {envpython} -m pip install ijson # optional dependency - - # tz/location - {envpython} -m my.core module install my.time.tz.via_location - {envpython} -m my.core module install my.ip.all - {envpython} -m my.core module install my.location.gpslogger - {envpython} -m my.core module install my.location.fallback.via_ip - {envpython} -m my.core module install my.google.takeout.parser - - {envpython} -m my.core module install my.calendar.holidays - - # my.body.weight dep - {envpython} -m my.core module install my.orgmode - - {envpython} -m my.core module install my.coding.commits - - {envpython} -m my.core module install my.pdfs - - {envpython} -m my.core module install my.reddit.rexport + {envpython} -m my.core module install \ + ## tz/location + my.location.google \ + my.time.tz.via_location \ + my.ip.all \ + my.location.gpslogger \ + my.location.fallback.via_ip \ + my.google.takeout.parser \ + ## + my.calendar.holidays \ + my.orgmode \ # my.body.weight dep + my.coding.commits \ + my.pdfs \ + my.reddit.rexport {envpython} -m pytest \ # importlib is the new suggested import-mode @@ -88,18 +86,20 @@ commands = [testenv:demo] +deps = + git+https://github.com/karlicoss/hypexport commands = - {envpython} -m pip install git+https://github.com/karlicoss/hypexport {envpython} ./demo.py [testenv:mypy-core] +install_command = {envpython} -m pip install --use-pep517 {opts} {packages} +deps = + -e .[testing,optional] + orgparse # for core.orgmode + gpxpy # for hpi query --output gpx commands = - {envpython} -m pip install --use-pep517 -e .[testing,optional] - {envpython} -m pip install orgparse # used it core.orgmode? - {envpython} -m pip install gpxpy # for hpi query --output gpx - - {envpython} -m mypy --install-types --non-interactive \ + {envpython} -m mypy --no-install-types \ -p {[testenv]package_name}.core \ --txt-report .coverage.mypy-core \ --html-report .coverage.mypy-core \ @@ -109,9 +109,13 @@ commands = # specific modules that are known to be mypy compliant (to avoid false negatives) # todo maybe split into separate jobs? need to add comment how to run [testenv:mypy-misc] +install_command = {envpython} -m pip install --use-pep517 {opts} {packages} +deps = + -e .[testing,optional] + lxml-stubs # for my.smscalls + types-protobuf # for my.google.maps.android + types-Pillow # for my.photos commands = - {envpython} -m pip install --use-pep517 -e .[testing,optional] - {envpython} -m my.core module install \ my.arbtt \ my.browser.export \ @@ -143,13 +147,13 @@ commands = my.time.tz.via_location - {envpython} -m mypy --install-types --non-interactive \ + {envpython} -m mypy --no-install-types \ -p {[testenv]package_name} \ --txt-report .coverage.mypy-misc \ --html-report .coverage.mypy-misc \ {posargs} - {envpython} -m mypy --install-types --non-interactive \ + {envpython} -m mypy --no-install-types \ tests # note: this comment doesn't seem relevant anymore, but keeping it in case the issue happens again From 8ed9e1947ec186b7939e2d8a53d07b6ffdd832ed Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Sun, 22 Sep 2024 17:47:05 +0100 Subject: [PATCH 107/122] my.youtube.takeout: deduplicate watched videos and sort out a few minor errors --- my/core/compat.py | 7 ++- my/media/youtube.py | 13 +++-- my/youtube/takeout.py | 115 ++++++++++++++++++++++++++++++++---------- 3 files changed, 102 insertions(+), 33 deletions(-) diff --git a/my/core/compat.py b/my/core/compat.py index eccaf07..29d4f04 100644 --- a/my/core/compat.py +++ b/my/core/compat.py @@ -22,12 +22,17 @@ if not TYPE_CHECKING: source.backup(dest, **kwargs) -# can remove after python3.9 (although need to keep the method itself for bwd compat) +## can remove after python3.9 (although need to keep the method itself for bwd compat) def removeprefix(text: str, prefix: str) -> str: if text.startswith(prefix): return text[len(prefix) :] return text +def removesuffix(text: str, suffix: str) -> str: + if text.endswith(suffix): + return text[:-len(suffix)] + return text +## ## used to have compat function before 3.8 for these, keeping for runtime back compatibility if not TYPE_CHECKING: diff --git a/my/media/youtube.py b/my/media/youtube.py index efaa74b..3ddbc14 100644 --- a/my/media/youtube.py +++ b/my/media/youtube.py @@ -1,5 +1,10 @@ -from ..core.warnings import high -high("DEPRECATED! Please use my.youtube.takeout instead.") -from ..core.util import __NOT_HPI_MODULE__ +from my.core import __NOT_HPI_MODULE__ -from ..youtube.takeout import * +from typing import TYPE_CHECKING + +from my.core.warnings import high + +high("DEPRECATED! Please use my.youtube.takeout instead.") + +if not TYPE_CHECKING: + from my.youtube.takeout import * diff --git a/my/youtube/takeout.py b/my/youtube/takeout.py index 284c082..bbce46a 100644 --- a/my/youtube/takeout.py +++ b/my/youtube/takeout.py @@ -1,13 +1,16 @@ -from typing import NamedTuple, List, Iterable, TYPE_CHECKING +from __future__ import annotations -from my.core import datetime_aware, make_logger, stat, Res, Stats -from my.core.compat import deprecated, removeprefix +from dataclasses import dataclass +from typing import TYPE_CHECKING, Any, Iterable, Iterator +from my.core import Res, Stats, datetime_aware, make_logger, stat, warnings +from my.core.compat import deprecated, removeprefix, removesuffix logger = make_logger(__name__) -class Watched(NamedTuple): +@dataclass +class Watched: url: str title: str when: datetime_aware @@ -16,19 +19,57 @@ class Watched(NamedTuple): def eid(self) -> str: return f'{self.url}-{self.when.isoformat()}' + def is_deleted(self) -> bool: + return self.title == self.url + # todo define error policy? # although it has one from google takeout module.. so not sure -def watched() -> Iterable[Res[Watched]]: + +def watched() -> Iterator[Res[Watched]]: + emitted: dict[Any, Watched] = {} + for w in _watched(): + if isinstance(w, Exception): + yield w # TODO also make unique? + continue + + # older exports (e.g. html) didn't have microseconds + # wheras newer json ones do have them + # seconds resolution is enough to distinguish watched videos + # also we're processing takeouts in HPI in reverse order, so first seen watch would contain microseconds, resulting in better data + without_microsecond = w.when.replace(microsecond=0) + + key = w.url, without_microsecond + prev = emitted.get(key, None) + if prev is not None: + # NOTE: some video titles start with 'Liked ' for liked videos activity + # but they'd have different timestamp, so fine not to handle them as a special case here + if w.title in prev.title: + # often more stuff added to the title, like 'Official Video' + # in this case not worth emitting the change + # also handles the case when titles match + continue + # otherwise if title changed completely, just emit the change... not sure what else we could do? + # could merge titles in the 'titles' field and update dynamically? but a bit complicated, maybe later.. + + # TODO would also be nice to handle is_deleted here somehow... + # but for that would need to process data in direct order vs reversed.. + # not sure, maybe this could use a special mode or something? + + emitted[key] = w + yield w + + +def _watched() -> Iterator[Res[Watched]]: try: - from ..google.takeout.parser import events from google_takeout_parser.models import Activity + + from ..google.takeout.parser import events except ModuleNotFoundError as ex: logger.exception(ex) - from ..core.warnings import high - high("Please set up my.google.takeout.parser module for better youtube support. Falling back to legacy implementation.") - yield from _watched_legacy() + warnings.high("Please set up my.google.takeout.parser module for better youtube support. Falling back to legacy implementation.") + yield from _watched_legacy() # type: ignore[name-defined] return YOUTUBE_VIDEO_LINK = '://www.youtube.com/watch?v=' @@ -43,12 +84,12 @@ def watched() -> Iterable[Res[Watched]]: continue url = e.titleUrl - header = e.header - title = e.title if url is None: continue + header = e.header + if header in {'Image Search', 'Search', 'Chrome'}: # sometimes results in youtube links.. but definitely not watch history continue @@ -61,6 +102,8 @@ def watched() -> Iterable[Res[Watched]]: pass continue + title = e.title + if header == 'youtube.com' and title.startswith('Visited '): continue @@ -76,16 +119,32 @@ def watched() -> Iterable[Res[Watched]]: # also compatible with legacy titles title = removeprefix(title, 'Watched ') + # watches originating from some activity end with this, remove it for consistency + title = removesuffix(title, ' - YouTube') + if YOUTUBE_VIDEO_LINK not in url: - if e.details == ['From Google Ads']: - # weird, sometimes results in odd + if 'youtube.com/post/' in url: + # some sort of channel updates? continue - if title == 'Used YouTube' and e.products == ['Android']: + if 'youtube.com/playlist' in url: + # 'saved playlist' actions + continue + if 'music.youtube.com' in url: + # todo maybe allow it? + continue + if any('From Google Ads' in d for d in e.details): + # weird, sometimes results in odd urls + continue + + if title == 'Used YouTube': continue yield RuntimeError(f'Unexpected url: {e}') continue + # TODO contribute to takeout parser? seems that these still might happen in json data + title = title.replace("\xa0", " ") + yield Watched( url=url, title=title, @@ -100,24 +159,24 @@ def stats() -> Stats: ### deprecated stuff (keep in my.media.youtube) if not TYPE_CHECKING: + @deprecated("use 'watched' instead") def get_watched(*args, **kwargs): return watched(*args, **kwargs) + def _watched_legacy() -> Iterable[Watched]: + from ..google.takeout.html import read_html + from ..google.takeout.paths import get_last_takeout -def _watched_legacy() -> Iterable[Watched]: - from ..google.takeout.html import read_html - from ..google.takeout.paths import get_last_takeout + # todo looks like this one doesn't have retention? so enough to use the last + path = 'Takeout/My Activity/YouTube/MyActivity.html' + last = get_last_takeout(path=path) + if last is None: + return [] - # todo looks like this one doesn't have retention? so enough to use the last - path = 'Takeout/My Activity/YouTube/MyActivity.html' - last = get_last_takeout(path=path) - if last is None: - return [] + watches: list[Watched] = [] + for dt, url, title in read_html(last, path): + watches.append(Watched(url=url, title=title, when=dt)) - watches: List[Watched] = [] - for dt, url, title in read_html(last, path): - watches.append(Watched(url=url, title=title, when=dt)) - - # todo hmm they already come sorted.. wonder if should just rely on it.. - return sorted(watches, key=lambda e: e.when) + # todo hmm they already come sorted.. wonder if should just rely on it.. + return sorted(watches, key=lambda e: e.when) From bf8af6c598803b7ad3bee5d5cbade015ce4b88a7 Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Sun, 22 Sep 2024 22:32:34 +0100 Subject: [PATCH 108/122] tox: try using uv for CI, should result in speedup see https://github.com/karlicoss/HPI/issues/391 --- .ci/run | 13 ++++++++++--- my/core/__main__.py | 3 ++- tox.ini | 10 +++++----- 3 files changed, 17 insertions(+), 9 deletions(-) diff --git a/.ci/run b/.ci/run index fe2719e..7656575 100755 --- a/.ci/run +++ b/.ci/run @@ -11,6 +11,8 @@ if ! command -v sudo; then } fi +# --parallel-live to show outputs while it's running +tox_cmd='run-parallel --parallel-live' if [ -n "${CI-}" ]; then # install OS specific stuff here case "$OSTYPE" in @@ -20,7 +22,8 @@ if [ -n "${CI-}" ]; then ;; cygwin* | msys* | win*) # windows - : + # ugh. parallel stuff seems super flaky under windows, some random failures, "file used by other process" and crap like that + tox_cmd='run' ;; *) # must be linux? @@ -37,5 +40,9 @@ if ! command -v python3 &> /dev/null; then PY_BIN="python" fi -"$PY_BIN" -m pip install --user tox -"$PY_BIN" -m tox --parallel --parallel-live "$@" + +# TODO hmm for some reason installing uv with pip and then running +# "$PY_BIN" -m uv tool fails with missing setuptools error?? +# just uvx directly works, but it's not present in PATH... +"$PY_BIN" -m pip install --user pipx +"$PY_BIN" -m pipx run uv tool run --with=tox-uv tox $tox_cmd "$@" diff --git a/my/core/__main__.py b/my/core/__main__.py index c675676..9ec637c 100644 --- a/my/core/__main__.py +++ b/my/core/__main__.py @@ -373,8 +373,9 @@ def module_install(*, user: bool, module: Sequence[str], parallel: bool=False, b warning('requirements list is empty, no need to install anything') return + use_uv = 'HPI_MODULE_INSTALL_USE_UV' in os.environ pre_cmd = [ - sys.executable, '-m', 'pip', + sys.executable, '-m', *(['uv'] if use_uv else []), 'pip', 'install', *(['--user'] if user else []), # todo maybe instead, forward all the remaining args to pip? *(['--break-system-packages'] if break_system_packages else []), # https://peps.python.org/pep-0668/ diff --git a/tox.ini b/tox.ini index 4e5dff6..d202bd2 100644 --- a/tox.ini +++ b/tox.ini @@ -17,6 +17,9 @@ passenv = PYTHONPYCACHEPREFIX MYPY_CACHE_DIR RUFF_CACHE_DIR +setenv = + HPI_MODULE_INSTALL_USE_UV=true +uv_seed = true # seems necessary so uv creates separate venvs per tox env? # note: --use-pep517 below is necessary for tox --parallel flag to work properly @@ -24,7 +27,6 @@ passenv = [testenv:ruff] -install_command = {envpython} -m pip install --use-pep517 {opts} {packages} deps = -e .[testing] commands = @@ -33,7 +35,6 @@ commands = # just the very core tests with minimal dependencies [testenv:tests-core] -install_command = {envpython} -m pip install --use-pep517 {opts} {packages} deps = -e .[testing] commands = @@ -56,9 +57,9 @@ setenv = # TODO not sure if need it? MY_CONFIG=nonexistent HPI_TESTS_USES_OPTIONAL_DEPS=true -install_command = {envpython} -m pip install --use-pep517 {opts} {packages} deps = -e .[testing] + uv # for hpi module install cachew ijson # optional dependency for various modules commands = @@ -93,7 +94,6 @@ commands = [testenv:mypy-core] -install_command = {envpython} -m pip install --use-pep517 {opts} {packages} deps = -e .[testing,optional] orgparse # for core.orgmode @@ -109,9 +109,9 @@ commands = # specific modules that are known to be mypy compliant (to avoid false negatives) # todo maybe split into separate jobs? need to add comment how to run [testenv:mypy-misc] -install_command = {envpython} -m pip install --use-pep517 {opts} {packages} deps = -e .[testing,optional] + uv # for hpi module install lxml-stubs # for my.smscalls types-protobuf # for my.google.maps.android types-Pillow # for my.photos From 6a6d15704063c328f9bf66330630a53a0c421915 Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Mon, 23 Sep 2024 01:14:49 +0100 Subject: [PATCH 109/122] cli: fix minor race condition in creating hpi_temp_dir --- my/core/__main__.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/my/core/__main__.py b/my/core/__main__.py index 9ec637c..a80aa52 100644 --- a/my/core/__main__.py +++ b/my/core/__main__.py @@ -615,9 +615,8 @@ def main(*, debug: bool) -> None: # to run things at the end (would need to use a callback or pass context) # https://click.palletsprojects.com/en/7.x/commands/#nested-handling-and-contexts - tdir: str = os.path.join(tempfile.gettempdir(), 'hpi_temp_dir') - if not os.path.exists(tdir): - os.makedirs(tdir) + tdir = Path(tempfile.gettempdir()) / 'hpi_temp_dir' + tdir.mkdir(exist_ok=True) os.chdir(tdir) From a8f86e32b981aef62890605e12da9cd59c9cc0c8 Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Mon, 23 Sep 2024 22:01:57 +0100 Subject: [PATCH 110/122] core.time: hotfix for default force_abbreviations attribute --- my/core/time.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/my/core/time.py b/my/core/time.py index 6de4105..fa20a7c 100644 --- a/my/core/time.py +++ b/my/core/time.py @@ -11,11 +11,11 @@ def user_forced() -> Sequence[str]: # https://stackoverflow.com/questions/36067621/python-all-possible-timezone-abbreviations-for-given-timezone-name-and-vise-ve try: from my.config import time as user_config + return user_config.tz.force_abbreviations # type: ignore[attr-defined] # noqa: TRY300 + # note: noqa since we're catching case where config doesn't have attribute here as well except: # todo log/apply policy return [] - else: - return user_config.tz.force_abbreviations # type: ignore[attr-defined] @lru_cache(1) From bc7c3ac25355899f2a4ae56382469d85fd2c33bc Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Sat, 19 Oct 2024 18:27:35 +0100 Subject: [PATCH 111/122] general: python3.9 reached EOL, switch min version also enable 3.13 on CI --- .github/workflows/main.yml | 11 ++++++---- my/core/__main__.py | 4 +--- my/core/_deprecated/kompress.py | 2 +- my/core/compat.py | 24 ++++++++------------- my/core/pandas.py | 2 +- my/core/utils/concurrent.py | 38 +++++++++++---------------------- my/youtube/takeout.py | 6 +++--- setup.py | 2 +- 8 files changed, 36 insertions(+), 53 deletions(-) diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 53d8e53..111d0e9 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -21,19 +21,20 @@ on: jobs: build: strategy: + fail-fast: false matrix: platform: [ubuntu-latest, macos-latest, windows-latest] - python-version: ['3.8', '3.9', '3.10', '3.11', '3.12'] + python-version: ['3.9', '3.10', '3.11', '3.12', '3.13'] exclude: [ # windows runners are pretty scarce, so let's only run lowest and highest python version - {platform: windows-latest, python-version: '3.9' }, {platform: windows-latest, python-version: '3.10'}, {platform: windows-latest, python-version: '3.11'}, + {platform: windows-latest, python-version: '3.12'}, # same, macos is a bit too slow and ubuntu covers python quirks well - {platform: macos-latest , python-version: '3.9' }, {platform: macos-latest , python-version: '3.10' }, {platform: macos-latest , python-version: '3.11' }, + {platform: macos-latest , python-version: '3.12' }, ] runs-on: ${{ matrix.platform }} @@ -63,11 +64,13 @@ jobs: - if: matrix.platform == 'ubuntu-latest' # no need to compute coverage for other platforms uses: actions/upload-artifact@v4 with: + include-hidden-files: true name: .coverage.mypy-misc_${{ matrix.platform }}_${{ matrix.python-version }} path: .coverage.mypy-misc/ - if: matrix.platform == 'ubuntu-latest' # no need to compute coverage for other platforms uses: actions/upload-artifact@v4 with: + include-hidden-files: true name: .coverage.mypy-core_${{ matrix.platform }}_${{ matrix.python-version }} path: .coverage.mypy-core/ @@ -81,7 +84,7 @@ jobs: - uses: actions/setup-python@v5 with: - python-version: '3.8' + python-version: '3.10' - uses: actions/checkout@v4 with: diff --git a/my/core/__main__.py b/my/core/__main__.py index a80aa52..2777008 100644 --- a/my/core/__main__.py +++ b/my/core/__main__.py @@ -171,8 +171,6 @@ See https://github.com/karlicoss/HPI/blob/master/doc/SETUP.org#setting-up-module # use a temporary directory, useful because # - compileall ignores -B, so always craps with .pyc files (annoyng on RO filesystems) # - compileall isn't following symlinks, just silently ignores them - # note: ugh, annoying that copytree requires a non-existing dir before 3.8. - # once we have min version 3.8, can use dirs_exist_ok=True param tdir = Path(td) / 'cfg' # NOTE: compileall still returns code 0 if the path doesn't exist.. # but in our case hopefully it's not an issue @@ -181,7 +179,7 @@ See https://github.com/karlicoss/HPI/blob/master/doc/SETUP.org#setting-up-module try: # this will resolve symlinks when copying # should be under try/catch since might fail if some symlinks are missing - shutil.copytree(cfg_path, tdir) + shutil.copytree(cfg_path, tdir, dirs_exist_ok=True) check_call(cmd) info('syntax check: ' + ' '.join(cmd)) except Exception as e: diff --git a/my/core/_deprecated/kompress.py b/my/core/_deprecated/kompress.py index b08f04b..cd27a7f 100644 --- a/my/core/_deprecated/kompress.py +++ b/my/core/_deprecated/kompress.py @@ -210,7 +210,7 @@ class ZipPath(zipfile_Path): def iterdir(self) -> Iterator[ZipPath]: for s in self._as_dir().iterdir(): - yield ZipPath(s.root, s.at) # type: ignore[attr-defined] + yield ZipPath(s.root, s.at) @property def stem(self) -> str: diff --git a/my/core/compat.py b/my/core/compat.py index 29d4f04..3273ff4 100644 --- a/my/core/compat.py +++ b/my/core/compat.py @@ -21,25 +21,19 @@ if not TYPE_CHECKING: # TODO warn here? source.backup(dest, **kwargs) + # keeping for runtime backwards compatibility (added in 3.9) + @deprecated('use .removeprefix method on string directly instead') + def removeprefix(text: str, prefix: str) -> str: + return text.removeprefix(prefix) -## can remove after python3.9 (although need to keep the method itself for bwd compat) -def removeprefix(text: str, prefix: str) -> str: - if text.startswith(prefix): - return text[len(prefix) :] - return text + @deprecated('use .removesuffix method on string directly instead') + def removesuffix(text: str, suffix: str) -> str: + return text.removesuffix(suffix) + ## -def removesuffix(text: str, suffix: str) -> str: - if text.endswith(suffix): - return text[:-len(suffix)] - return text -## - -## used to have compat function before 3.8 for these, keeping for runtime back compatibility -if not TYPE_CHECKING: + ## used to have compat function before 3.8 for these, keeping for runtime back compatibility from functools import cached_property from typing import Literal, Protocol, TypedDict -else: - from typing_extensions import Literal, Protocol, TypedDict ## diff --git a/my/core/pandas.py b/my/core/pandas.py index d38465a..8f5fd29 100644 --- a/my/core/pandas.py +++ b/my/core/pandas.py @@ -181,7 +181,7 @@ Schema = Any def _as_columns(s: Schema) -> Dict[str, Type]: # todo would be nice to extract properties; add tests for this as well if dataclasses.is_dataclass(s): - return {f.name: f.type for f in dataclasses.fields(s)} + return {f.name: f.type for f in dataclasses.fields(s)} # type: ignore[misc] # ugh, why mypy thinks f.type can return str?? # else must be NamedTuple?? # todo assert my.core.common.is_namedtuple? return getattr(s, '_field_types') diff --git a/my/core/utils/concurrent.py b/my/core/utils/concurrent.py index 146861b..73944ec 100644 --- a/my/core/utils/concurrent.py +++ b/my/core/utils/concurrent.py @@ -1,6 +1,6 @@ import sys from concurrent.futures import Executor, Future -from typing import TYPE_CHECKING, Any, Callable, Optional, TypeVar +from typing import Any, Callable, Optional, TypeVar from ..compat import ParamSpec @@ -19,33 +19,21 @@ class DummyExecutor(Executor): self._shutdown = False self._max_workers = max_workers - if TYPE_CHECKING: - if sys.version_info[:2] <= (3, 8): - # 3.8 doesn't support ParamSpec as Callable arg :( - # and any attempt to type results in incompatible supertype.. so whatever - def submit(self, fn, *args, **kwargs): ... + def submit(self, fn: Callable[_P, _T], /, *args: _P.args, **kwargs: _P.kwargs) -> Future[_T]: + if self._shutdown: + raise RuntimeError('cannot schedule new futures after shutdown') + f: Future[Any] = Future() + try: + result = fn(*args, **kwargs) + except KeyboardInterrupt: + raise + except BaseException as e: + f.set_exception(e) else: + f.set_result(result) - def submit(self, fn: Callable[_P, _T], /, *args: _P.args, **kwargs: _P.kwargs) -> Future[_T]: ... - - else: - - def submit(self, fn, *args, **kwargs): - if self._shutdown: - raise RuntimeError('cannot schedule new futures after shutdown') - - f: Future[Any] = Future() - try: - result = fn(*args, **kwargs) - except KeyboardInterrupt: - raise - except BaseException as e: - f.set_exception(e) - else: - f.set_result(result) - - return f + return f def shutdown(self, wait: bool = True, **kwargs) -> None: # noqa: FBT001,FBT002,ARG002 self._shutdown = True diff --git a/my/youtube/takeout.py b/my/youtube/takeout.py index bbce46a..f29b2e3 100644 --- a/my/youtube/takeout.py +++ b/my/youtube/takeout.py @@ -4,7 +4,7 @@ from dataclasses import dataclass from typing import TYPE_CHECKING, Any, Iterable, Iterator from my.core import Res, Stats, datetime_aware, make_logger, stat, warnings -from my.core.compat import deprecated, removeprefix, removesuffix +from my.core.compat import deprecated logger = make_logger(__name__) @@ -117,10 +117,10 @@ def _watched() -> Iterator[Res[Watched]]: # all titles contain it, so pointless to include 'Watched ' # also compatible with legacy titles - title = removeprefix(title, 'Watched ') + title = title.removeprefix('Watched ') # watches originating from some activity end with this, remove it for consistency - title = removesuffix(title, ' - YouTube') + title = title.removesuffix(' - YouTube') if YOUTUBE_VIDEO_LINK not in url: if 'youtube.com/post/' in url: diff --git a/setup.py b/setup.py index e49eee0..385c810 100644 --- a/setup.py +++ b/setup.py @@ -44,7 +44,7 @@ def main() -> None: author_email='karlicoss@gmail.com', description='A Python interface to my life', - python_requires='>=3.8', + python_requires='>=3.9', install_requires=INSTALL_REQUIRES, extras_require={ 'testing': [ From d3f9a8e8b69542361ad0838a1012a1ad10440b5b Mon Sep 17 00:00:00 2001 From: karlicoss Date: Sat, 19 Oct 2024 20:55:09 +0100 Subject: [PATCH 112/122] core: migrate code to benefit from 3.9 stuff (#401) for now keeping ruff on 3.8 target version, need to sort out modules as well --- my/core/__init__.py | 4 +- my/core/__main__.py | 97 +++++++++++++++++++++------------ my/core/_cpu_pool.py | 9 ++- my/core/_deprecated/kompress.py | 5 +- my/core/cachew.py | 29 +++++----- my/core/cfg.py | 20 +++++-- my/core/common.py | 36 ++++++------ my/core/compat.py | 7 ++- my/core/core_config.py | 33 ++++++----- my/core/denylist.py | 28 +++++----- my/core/discovery_pure.py | 19 ++++--- my/core/error.py | 43 ++++++++------- my/core/experimental.py | 6 +- my/core/freezer.py | 29 +++++----- my/core/hpi_compat.py | 13 +++-- my/core/influxdb.py | 29 +++++++--- my/core/init.py | 2 + my/core/kompress.py | 4 +- my/core/konsume.py | 39 +++++++------ my/core/mime.py | 11 ++-- my/core/orgmode.py | 8 ++- my/core/pandas.py | 7 +-- my/core/preinit.py | 1 + my/core/pytest.py | 4 +- my/core/query.py | 76 ++++++++++++-------------- my/core/query_range.py | 68 +++++++++++++---------- my/core/serialize.py | 20 ++++--- my/core/source.py | 12 +++- my/core/sqlite.py | 47 +++++++++------- my/core/stats.py | 34 +++++------- my/core/structure.py | 14 +++-- my/core/tests/auto_stats.py | 2 +- my/core/tests/common.py | 6 +- my/core/tests/denylist.py | 3 +- my/core/tests/test_cachew.py | 8 +-- my/core/tests/test_config.py | 2 +- my/core/time.py | 15 +++-- my/core/types.py | 13 +++-- my/core/util.py | 28 ++++++---- my/core/utils/concurrent.py | 7 ++- my/core/utils/imports.py | 14 ++--- my/core/utils/itertools.py | 59 +++++++++----------- my/core/warnings.py | 8 ++- 43 files changed, 515 insertions(+), 404 deletions(-) diff --git a/my/core/__init__.py b/my/core/__init__.py index ba633f6..cc549d5 100644 --- a/my/core/__init__.py +++ b/my/core/__init__.py @@ -4,7 +4,7 @@ from typing import TYPE_CHECKING from .cfg import make_config from .common import PathIsh, Paths, get_files from .compat import assert_never -from .error import Res, unwrap, notnone +from .error import Res, notnone, unwrap from .logging import ( make_logger, ) @@ -52,7 +52,7 @@ __all__ = [ # you could put _init_hook.py next to your private my/config # that way you can configure logging/warnings/env variables on every HPI import try: - import my._init_hook # type: ignore[import-not-found] + import my._init_hook # type: ignore[import-not-found] # noqa: F401 except: pass ## diff --git a/my/core/__main__.py b/my/core/__main__.py index 2777008..00ac4ee 100644 --- a/my/core/__main__.py +++ b/my/core/__main__.py @@ -1,3 +1,5 @@ +from __future__ import annotations + import functools import importlib import inspect @@ -7,17 +9,18 @@ import shutil import sys import tempfile import traceback +from collections.abc import Iterable, Sequence from contextlib import ExitStack from itertools import chain from pathlib import Path from subprocess import PIPE, CompletedProcess, Popen, check_call, run -from typing import Any, Callable, Iterable, List, Optional, Sequence, Type +from typing import Any, Callable import click @functools.lru_cache -def mypy_cmd() -> Optional[Sequence[str]]: +def mypy_cmd() -> Sequence[str] | None: try: # preferably, use mypy from current python env import mypy # noqa: F401 fine not to use it @@ -32,7 +35,7 @@ def mypy_cmd() -> Optional[Sequence[str]]: return None -def run_mypy(cfg_path: Path) -> Optional[CompletedProcess]: +def run_mypy(cfg_path: Path) -> CompletedProcess | None: # todo dunno maybe use the same mypy config in repository? # I'd need to install mypy.ini then?? env = {**os.environ} @@ -63,21 +66,27 @@ def eprint(x: str) -> None: # err=True prints to stderr click.echo(x, err=True) + def indent(x: str) -> str: + # todo use textwrap.indent? return ''.join(' ' + l for l in x.splitlines(keepends=True)) -OK = '✅' +OK = '✅' OFF = '🔲' + def info(x: str) -> None: eprint(OK + ' ' + x) + def error(x: str) -> None: eprint('❌ ' + x) + def warning(x: str) -> None: - eprint('❗ ' + x) # todo yellow? + eprint('❗ ' + x) # todo yellow? + def tb(e: Exception) -> None: tb = ''.join(traceback.format_exception(Exception, e, e.__traceback__)) @@ -86,6 +95,7 @@ def tb(e: Exception) -> None: def config_create() -> None: from .preinit import get_mycfg_dir + mycfg_dir = get_mycfg_dir() created = False @@ -94,7 +104,8 @@ def config_create() -> None: my_config = mycfg_dir / 'my' / 'config' / '__init__.py' my_config.parent.mkdir(parents=True) - my_config.write_text(''' + my_config.write_text( + ''' ### HPI personal config ## see # https://github.com/karlicoss/HPI/blob/master/doc/SETUP.org#setting-up-modules @@ -117,7 +128,8 @@ class example: ### you can insert your own configuration below ### but feel free to delete the stuff above if you don't need ti -'''.lstrip()) +'''.lstrip() + ) info(f'created empty config: {my_config}') created = True else: @@ -130,12 +142,13 @@ class example: # todo return the config as a result? def config_ok() -> bool: - errors: List[Exception] = [] + errors: list[Exception] = [] # at this point 'my' should already be imported, so doesn't hurt to extract paths from it import my + try: - paths: List[str] = list(my.__path__) + paths: list[str] = list(my.__path__) except Exception as e: errors.append(e) error('failed to determine module import path') @@ -145,19 +158,23 @@ def config_ok() -> bool: # first try doing as much as possible without actually importing my.config from .preinit import get_mycfg_dir + cfg_path = get_mycfg_dir() # alternative is importing my.config and then getting cfg_path from its __file__/__path__ # not sure which is better tbh ## check we're not using stub config import my.core + try: core_pkg_path = str(Path(my.core.__path__[0]).parent) if str(cfg_path).startswith(core_pkg_path): - error(f''' + error( + f''' Seems that the stub config is used ({cfg_path}). This is likely not going to work. See https://github.com/karlicoss/HPI/blob/master/doc/SETUP.org#setting-up-modules for more information -'''.strip()) +'''.strip() + ) errors.append(RuntimeError('bad config path')) except Exception as e: errors.append(e) @@ -189,7 +206,7 @@ See https://github.com/karlicoss/HPI/blob/master/doc/SETUP.org#setting-up-module ## check types mypy_res = run_mypy(cfg_path) - if mypy_res is not None: # has mypy + if mypy_res is not None: # has mypy rc = mypy_res.returncode if rc == 0: info('mypy check : success') @@ -221,7 +238,7 @@ See https://github.com/karlicoss/HPI/blob/master/doc/SETUP.org#setting-up-module from .util import HPIModule, modules -def _modules(*, all: bool=False) -> Iterable[HPIModule]: +def _modules(*, all: bool = False) -> Iterable[HPIModule]: skipped = [] for m in modules(): if not all and m.skip_reason is not None: @@ -232,7 +249,7 @@ def _modules(*, all: bool=False) -> Iterable[HPIModule]: warning(f'Skipped {len(skipped)} modules: {skipped}. Pass --all if you want to see them.') -def modules_check(*, verbose: bool, list_all: bool, quick: bool, for_modules: List[str]) -> None: +def modules_check(*, verbose: bool, list_all: bool, quick: bool, for_modules: list[str]) -> None: if len(for_modules) > 0: # if you're checking specific modules, show errors # hopefully makes sense? @@ -256,7 +273,7 @@ def modules_check(*, verbose: bool, list_all: bool, quick: bool, for_modules: Li # todo add a --all argument to disregard is_active check? for mr in mods: skip = mr.skip_reason - m = mr.name + m = mr.name if skip is not None: eprint(f'{OFF} {click.style("SKIP", fg="yellow")}: {m:<50} {skip}') continue @@ -306,8 +323,8 @@ def list_modules(*, list_all: bool) -> None: tabulate_warnings() for mr in _modules(all=list_all): - m = mr.name - sr = mr.skip_reason + m = mr.name + sr = mr.skip_reason if sr is None: pre = OK suf = '' @@ -323,17 +340,20 @@ def tabulate_warnings() -> None: Helper to avoid visual noise in hpi modules/doctor ''' import warnings + orig = warnings.formatwarning def override(*args, **kwargs) -> str: res = orig(*args, **kwargs) return ''.join(' ' + x for x in res.splitlines(keepends=True)) + warnings.formatwarning = override # TODO loggers as well? def _requires(modules: Sequence[str]) -> Sequence[str]: from .discovery_pure import module_by_name + mods = [module_by_name(module) for module in modules] res = [] for mod in mods: @@ -360,7 +380,7 @@ def module_requires(*, module: Sequence[str]) -> None: click.echo(x) -def module_install(*, user: bool, module: Sequence[str], parallel: bool=False, break_system_packages: bool=False) -> None: +def module_install(*, user: bool, module: Sequence[str], parallel: bool = False, break_system_packages: bool = False) -> None: if isinstance(module, str): # legacy behavior, used to take a since argument module = [module] @@ -437,7 +457,7 @@ def _ui_getchar_pick(choices: Sequence[str], prompt: str = 'Select from: ') -> i return result_map[ch] -def _locate_functions_or_prompt(qualified_names: List[str], *, prompt: bool = True) -> Iterable[Callable[..., Any]]: +def _locate_functions_or_prompt(qualified_names: list[str], *, prompt: bool = True) -> Iterable[Callable[..., Any]]: from .query import QueryException, locate_qualified_function from .stats import is_data_provider @@ -487,6 +507,7 @@ def _locate_functions_or_prompt(qualified_names: List[str], *, prompt: bool = Tr def _warn_exceptions(exc: Exception) -> None: from my.core import make_logger + logger = make_logger('CLI', level='warning') logger.exception(f'hpi query: {exc}') @@ -498,14 +519,14 @@ def query_hpi_functions( *, output: str = 'json', stream: bool = False, - qualified_names: List[str], - order_key: Optional[str], - order_by_value_type: Optional[Type], + qualified_names: list[str], + order_key: str | None, + order_by_value_type: type | None, after: Any, before: Any, within: Any, reverse: bool = False, - limit: Optional[int], + limit: int | None, drop_unsorted: bool, wrap_unsorted: bool, warn_exceptions: bool, @@ -529,7 +550,8 @@ def query_hpi_functions( warn_exceptions=warn_exceptions, warn_func=_warn_exceptions, raise_exceptions=raise_exceptions, - drop_exceptions=drop_exceptions) + drop_exceptions=drop_exceptions, + ) if output == 'json': from .serialize import dumps @@ -563,7 +585,7 @@ def query_hpi_functions( # can ignore the mypy warning here, locations_to_gpx yields any errors # if you didnt pass it something that matches the LocationProtocol - for exc in locations_to_gpx(res, sys.stdout): # type: ignore[arg-type] + for exc in locations_to_gpx(res, sys.stdout): # type: ignore[arg-type] if warn_exceptions: _warn_exceptions(exc) elif raise_exceptions: @@ -580,6 +602,7 @@ def query_hpi_functions( except ModuleNotFoundError: eprint("'repl' typically uses ipython, install it with 'python3 -m pip install ipython'. falling back to stdlib...") import code + code.interact(local=locals()) else: IPython.embed() @@ -619,13 +642,13 @@ def main(*, debug: bool) -> None: @functools.lru_cache(maxsize=1) -def _all_mod_names() -> List[str]: +def _all_mod_names() -> list[str]: """Should include all modules, in case user is trying to diagnose issues""" # sort this, so that the order doesn't change while tabbing through return sorted([m.name for m in modules()]) -def _module_autocomplete(ctx: click.Context, args: Sequence[str], incomplete: str) -> List[str]: +def _module_autocomplete(ctx: click.Context, args: Sequence[str], incomplete: str) -> list[str]: return [m for m in _all_mod_names() if m.startswith(incomplete)] @@ -784,14 +807,14 @@ def query_cmd( function_name: Sequence[str], output: str, stream: bool, - order_key: Optional[str], - order_type: Optional[str], - after: Optional[str], - before: Optional[str], - within: Optional[str], - recent: Optional[str], + order_key: str | None, + order_type: str | None, + after: str | None, + before: str | None, + within: str | None, + recent: str | None, reverse: bool, - limit: Optional[int], + limit: int | None, drop_unsorted: bool, wrap_unsorted: bool, warn_exceptions: bool, @@ -827,7 +850,7 @@ def query_cmd( from datetime import date, datetime - chosen_order_type: Optional[Type] + chosen_order_type: type | None if order_type == "datetime": chosen_order_type = datetime elif order_type == "date": @@ -863,7 +886,8 @@ def query_cmd( wrap_unsorted=wrap_unsorted, warn_exceptions=warn_exceptions, raise_exceptions=raise_exceptions, - drop_exceptions=drop_exceptions) + drop_exceptions=drop_exceptions, + ) except QueryException as qe: eprint(str(qe)) sys.exit(1) @@ -878,6 +902,7 @@ def query_cmd( def test_requires() -> None: from click.testing import CliRunner + result = CliRunner().invoke(main, ['module', 'requires', 'my.github.ghexport', 'my.browser.export']) assert result.exit_code == 0 assert "github.com/karlicoss/ghexport" in result.output diff --git a/my/core/_cpu_pool.py b/my/core/_cpu_pool.py index 2369075..6b107a7 100644 --- a/my/core/_cpu_pool.py +++ b/my/core/_cpu_pool.py @@ -10,15 +10,18 @@ how many cores we want to dedicate to the DAL. Enabled by the env variable, specifying how many cores to dedicate e.g. "HPI_CPU_POOL=4 hpi query ..." """ + +from __future__ import annotations + import os from concurrent.futures import ProcessPoolExecutor -from typing import Optional, cast +from typing import cast _NOT_SET = cast(ProcessPoolExecutor, object()) -_INSTANCE: Optional[ProcessPoolExecutor] = _NOT_SET +_INSTANCE: ProcessPoolExecutor | None = _NOT_SET -def get_cpu_pool() -> Optional[ProcessPoolExecutor]: +def get_cpu_pool() -> ProcessPoolExecutor | None: global _INSTANCE if _INSTANCE is _NOT_SET: use_cpu_pool = os.environ.get('HPI_CPU_POOL') diff --git a/my/core/_deprecated/kompress.py b/my/core/_deprecated/kompress.py index cd27a7f..ce14fad 100644 --- a/my/core/_deprecated/kompress.py +++ b/my/core/_deprecated/kompress.py @@ -1,16 +1,17 @@ """ Various helpers for compression """ + # fmt: off from __future__ import annotations import io import pathlib -import sys +from collections.abc import Iterator, Sequence from datetime import datetime from functools import total_ordering from pathlib import Path -from typing import IO, Any, Iterator, Sequence, Union +from typing import IO, Any, Union PathIsh = Union[Path, str] diff --git a/my/core/cachew.py b/my/core/cachew.py index dc6ed79..9ccee09 100644 --- a/my/core/cachew.py +++ b/my/core/cachew.py @@ -1,16 +1,18 @@ -from .internal import assert_subpackage; assert_subpackage(__name__) +from __future__ import annotations + +from .internal import assert_subpackage + +assert_subpackage(__name__) import logging import sys +from collections.abc import Iterator from contextlib import contextmanager from pathlib import Path from typing import ( TYPE_CHECKING, Any, Callable, - Iterator, - Optional, - Type, TypeVar, Union, cast, @@ -21,7 +23,6 @@ import appdirs # type: ignore[import-untyped] from . import warnings - PathIsh = Union[str, Path] # avoid circular import from .common @@ -60,12 +61,12 @@ def _appdirs_cache_dir() -> Path: _CACHE_DIR_NONE_HACK = Path('/tmp/hpi/cachew_none_hack') -def cache_dir(suffix: Optional[PathIsh] = None) -> Path: +def cache_dir(suffix: PathIsh | None = None) -> Path: from . import core_config as CC cdir_ = CC.config.get_cache_dir() - sp: Optional[Path] = None + sp: Path | None = None if suffix is not None: sp = Path(suffix) # guess if you do need absolute, better path it directly instead of as suffix? @@ -144,21 +145,19 @@ if TYPE_CHECKING: # we need two versions due to @doublewrap # this is when we just annotate as @cachew without any args @overload # type: ignore[no-overload-impl] - def mcachew(fun: F) -> F: - ... + def mcachew(fun: F) -> F: ... @overload def mcachew( - cache_path: Optional[PathProvider] = ..., + cache_path: PathProvider | None = ..., *, force_file: bool = ..., - cls: Optional[Type] = ..., + cls: type | None = ..., depends_on: HashFunction = ..., - logger: Optional[logging.Logger] = ..., + logger: logging.Logger | None = ..., chunk_by: int = ..., - synthetic_key: Optional[str] = ..., - ) -> Callable[[F], F]: - ... + synthetic_key: str | None = ..., + ) -> Callable[[F], F]: ... else: mcachew = _mcachew_impl diff --git a/my/core/cfg.py b/my/core/cfg.py index a71a7e3..9851443 100644 --- a/my/core/cfg.py +++ b/my/core/cfg.py @@ -3,28 +3,32 @@ from __future__ import annotations import importlib import re import sys +from collections.abc import Iterator from contextlib import ExitStack, contextmanager -from typing import Any, Callable, Dict, Iterator, Optional, Type, TypeVar +from typing import Any, Callable, TypeVar -Attrs = Dict[str, Any] +Attrs = dict[str, Any] C = TypeVar('C') + # todo not sure about it, could be overthinking... # but short enough to change later # TODO document why it's necessary? -def make_config(cls: Type[C], migration: Callable[[Attrs], Attrs]=lambda x: x) -> C: +def make_config(cls: type[C], migration: Callable[[Attrs], Attrs] = lambda x: x) -> C: user_config = cls.__base__ old_props = { # NOTE: deliberately use gettatr to 'force' class properties here - k: getattr(user_config, k) for k in vars(user_config) + k: getattr(user_config, k) + for k in vars(user_config) } new_props = migration(old_props) from dataclasses import fields + params = { k: v for k, v in new_props.items() - if k in {f.name for f in fields(cls)} # type: ignore[arg-type] # see https://github.com/python/typing_extensions/issues/115 + if k in {f.name for f in fields(cls)} # type: ignore[arg-type] # see https://github.com/python/typing_extensions/issues/115 } # todo maybe return type here? return cls(**params) @@ -51,6 +55,8 @@ def _override_config(config: F) -> Iterator[F]: ModuleRegex = str + + @contextmanager def _reload_modules(modules: ModuleRegex) -> Iterator[None]: # need to use list here, otherwise reordering with set might mess things up @@ -81,13 +87,14 @@ def _reload_modules(modules: ModuleRegex) -> Iterator[None]: @contextmanager -def tmp_config(*, modules: Optional[ModuleRegex]=None, config=None): +def tmp_config(*, modules: ModuleRegex | None = None, config=None): if modules is None: assert config is None if modules is not None: assert config is not None import my.config + with ExitStack() as module_reload_stack, _override_config(my.config) as new_config: if config is not None: overrides = {k: v for k, v in vars(config).items() if not k.startswith('__')} @@ -102,6 +109,7 @@ def tmp_config(*, modules: Optional[ModuleRegex]=None, config=None): def test_tmp_config() -> None: class extra: data_path = '/path/to/data' + with tmp_config() as c: assert c.google != 'whatever' assert not hasattr(c, 'extra') diff --git a/my/core/common.py b/my/core/common.py index a2c2ad3..91fe9bd 100644 --- a/my/core/common.py +++ b/my/core/common.py @@ -1,20 +1,18 @@ +from __future__ import annotations + import os +from collections.abc import Iterable, Sequence from glob import glob as do_glob from pathlib import Path from typing import ( TYPE_CHECKING, Callable, Generic, - Iterable, - List, - Sequence, - Tuple, TypeVar, Union, ) -from . import compat -from . import warnings +from . import compat, warnings # some helper functions # TODO start deprecating this? soon we'd be able to use Path | str syntax which is shorter and more explicit @@ -24,20 +22,22 @@ Paths = Union[Sequence[PathIsh], PathIsh] DEFAULT_GLOB = '*' + + def get_files( pp: Paths, - glob: str=DEFAULT_GLOB, + glob: str = DEFAULT_GLOB, *, - sort: bool=True, - guess_compression: bool=True, -) -> Tuple[Path, ...]: + sort: bool = True, + guess_compression: bool = True, +) -> tuple[Path, ...]: """ Helper function to avoid boilerplate. Tuple as return type is a bit friendlier for hashing/caching, so hopefully makes sense """ # TODO FIXME mm, some wrapper to assert iterator isn't empty? - sources: List[Path] + sources: list[Path] if isinstance(pp, Path): sources = [pp] elif isinstance(pp, str): @@ -54,7 +54,7 @@ def get_files( # TODO ugh. very flaky... -3 because [, get_files(), ] return traceback.extract_stack()[-3].filename - paths: List[Path] = [] + paths: list[Path] = [] for src in sources: if src.parts[0] == '~': src = src.expanduser() @@ -64,7 +64,7 @@ def get_files( if glob != DEFAULT_GLOB: warnings.medium(f"{caller()}: treating {gs} as glob path. Explicit glob={glob} argument is ignored!") paths.extend(map(Path, do_glob(gs))) - elif os.path.isdir(str(src)): + elif os.path.isdir(str(src)): # noqa: PTH112 # NOTE: we're using os.path here on purpose instead of src.is_dir # the reason is is_dir for archives might return True and then # this clause would try globbing insize the archives @@ -234,16 +234,14 @@ if not TYPE_CHECKING: return types.asdict(*args, **kwargs) # todo wrap these in deprecated decorator as well? + # TODO hmm how to deprecate these in runtime? + # tricky cause they are actually classes/types + from typing import Literal # noqa: F401 + from .cachew import mcachew # noqa: F401 # this is kinda internal, should just use my.core.logging.setup_logger if necessary from .logging import setup_logger - - # TODO hmm how to deprecate these in runtime? - # tricky cause they are actually classes/types - - from typing import Literal # noqa: F401 - from .stats import Stats from .types import ( Json, diff --git a/my/core/compat.py b/my/core/compat.py index 3273ff4..8f719a8 100644 --- a/my/core/compat.py +++ b/my/core/compat.py @@ -3,6 +3,8 @@ Contains backwards compatibility helpers for different python versions. If something is relevant to HPI itself, please put it in .hpi_compat instead ''' +from __future__ import annotations + import sys from typing import TYPE_CHECKING @@ -29,6 +31,7 @@ if not TYPE_CHECKING: @deprecated('use .removesuffix method on string directly instead') def removesuffix(text: str, suffix: str) -> str: return text.removesuffix(suffix) + ## ## used to have compat function before 3.8 for these, keeping for runtime back compatibility @@ -46,13 +49,13 @@ else: # bisect_left doesn't have a 'key' parameter (which we use) # till python3.10 if sys.version_info[:2] <= (3, 9): - from typing import Any, Callable, List, Optional, TypeVar + from typing import Any, Callable, List, Optional, TypeVar # noqa: UP035 X = TypeVar('X') # copied from python src # fmt: off - def bisect_left(a: List[Any], x: Any, lo: int=0, hi: Optional[int]=None, *, key: Optional[Callable[..., Any]]=None) -> int: + def bisect_left(a: list[Any], x: Any, lo: int=0, hi: int | None=None, *, key: Callable[..., Any] | None=None) -> int: if lo < 0: raise ValueError('lo must be non-negative') if hi is None: diff --git a/my/core/core_config.py b/my/core/core_config.py index 9036971..3f26c03 100644 --- a/my/core/core_config.py +++ b/my/core/core_config.py @@ -2,18 +2,21 @@ Bindings for the 'core' HPI configuration ''' +from __future__ import annotations + import re +from collections.abc import Sequence from dataclasses import dataclass from pathlib import Path -from typing import Optional, Sequence -from . import PathIsh, warnings +from . import warnings try: from my.config import core as user_config # type: ignore[attr-defined] except Exception as e: try: from my.config import common as user_config # type: ignore[attr-defined] + warnings.high("'common' config section is deprecated. Please rename it to 'core'.") except Exception as e2: # make it defensive, because it's pretty commonly used and would be annoying if it breaks hpi doctor etc. @@ -24,6 +27,7 @@ except Exception as e: _HPI_CACHE_DIR_DEFAULT = '' + @dataclass class Config(user_config): ''' @@ -34,7 +38,7 @@ class Config(user_config): cache_dir = '/your/custom/cache/path' ''' - cache_dir: Optional[PathIsh] = _HPI_CACHE_DIR_DEFAULT + cache_dir: Path | str | None = _HPI_CACHE_DIR_DEFAULT ''' Base directory for cachew. - if None , means cache is disabled @@ -44,7 +48,7 @@ class Config(user_config): NOTE: you shouldn't use this attribute in HPI modules directly, use Config.get_cache_dir()/cachew.cache_dir() instead ''' - tmp_dir: Optional[PathIsh] = None + tmp_dir: Path | str | None = None ''' Path to a temporary directory. This can be used temporarily while extracting zipfiles etc... @@ -52,34 +56,36 @@ class Config(user_config): - otherwise , use the specified directory as the base temporary directory ''' - enabled_modules : Optional[Sequence[str]] = None + enabled_modules: Sequence[str] | None = None ''' list of regexes/globs - None means 'rely on disabled_modules' ''' - disabled_modules: Optional[Sequence[str]] = None + disabled_modules: Sequence[str] | None = None ''' list of regexes/globs - None means 'rely on enabled_modules' ''' - def get_cache_dir(self) -> Optional[Path]: + def get_cache_dir(self) -> Path | None: cdir = self.cache_dir if cdir is None: return None if cdir == _HPI_CACHE_DIR_DEFAULT: from .cachew import _appdirs_cache_dir + return _appdirs_cache_dir() else: return Path(cdir).expanduser() def get_tmp_dir(self) -> Path: - tdir: Optional[PathIsh] = self.tmp_dir + tdir: Path | str | None = self.tmp_dir tpath: Path # use tempfile if unset if tdir is None: import tempfile + tpath = Path(tempfile.gettempdir()) / 'HPI' else: tpath = Path(tdir) @@ -87,10 +93,10 @@ class Config(user_config): tpath.mkdir(parents=True, exist_ok=True) return tpath - def _is_module_active(self, module: str) -> Optional[bool]: + def _is_module_active(self, module: str) -> bool | None: # None means the config doesn't specify anything # todo might be nice to return the 'reason' too? e.g. which option has matched - def matches(specs: Sequence[str]) -> Optional[str]: + def matches(specs: Sequence[str]) -> str | None: for spec in specs: # not sure because . (packages separate) matches anything, but I guess unlikely to clash if re.match(spec, module): @@ -106,10 +112,10 @@ class Config(user_config): return None else: return False - else: # not None + else: # not None if off is None: return True - else: # not None + else: # not None # fallback onto the 'enable everything', then the user will notice warnings.medium(f"[module]: conflicting regexes '{on}' and '{off}' are set in the config. Please only use one of them.") return True @@ -121,8 +127,8 @@ config = make_config(Config) ### tests start +from collections.abc import Iterator from contextlib import contextmanager as ctx -from typing import Iterator @ctx @@ -163,4 +169,5 @@ def test_active_modules() -> None: assert cc._is_module_active("my.body.exercise") is True assert len(record_warnings) == 1 + ### tests end diff --git a/my/core/denylist.py b/my/core/denylist.py index 92faf2c..c92f9a0 100644 --- a/my/core/denylist.py +++ b/my/core/denylist.py @@ -5,23 +5,25 @@ A helper module for defining denylists for sources programmatically For docs, see doc/DENYLIST.md """ +from __future__ import annotations + import functools import json import sys from collections import defaultdict +from collections.abc import Iterator, Mapping from pathlib import Path -from typing import Any, Dict, Iterator, List, Mapping, Set, TypeVar +from typing import Any, TypeVar import click from more_itertools import seekable -from my.core.common import PathIsh -from my.core.serialize import dumps -from my.core.warnings import medium +from .serialize import dumps +from .warnings import medium T = TypeVar("T") -DenyMap = Mapping[str, Set[Any]] +DenyMap = Mapping[str, set[Any]] def _default_key_func(obj: T) -> str: @@ -29,9 +31,9 @@ def _default_key_func(obj: T) -> str: class DenyList: - def __init__(self, denylist_file: PathIsh): + def __init__(self, denylist_file: Path | str) -> None: self.file = Path(denylist_file).expanduser().absolute() - self._deny_raw_list: List[Dict[str, Any]] = [] + self._deny_raw_list: list[dict[str, Any]] = [] self._deny_map: DenyMap = defaultdict(set) # deny cli, user can override these @@ -45,7 +47,7 @@ class DenyList: return deny_map: DenyMap = defaultdict(set) - data: List[Dict[str, Any]]= json.loads(self.file.read_text()) + data: list[dict[str, Any]] = json.loads(self.file.read_text()) self._deny_raw_list = data for ignore in data: @@ -112,7 +114,7 @@ class DenyList: self._load() self._deny_raw({key: self._stringify_value(value)}, write=write) - def _deny_raw(self, data: Dict[str, Any], *, write: bool = False) -> None: + def _deny_raw(self, data: dict[str, Any], *, write: bool = False) -> None: self._deny_raw_list.append(data) if write: self.write() @@ -131,7 +133,7 @@ class DenyList: def _deny_cli_remember( self, items: Iterator[T], - mem: Dict[str, T], + mem: dict[str, T], ) -> Iterator[str]: keyf = self._deny_cli_key_func or _default_key_func # i.e., convert each item to a string, and map str -> item @@ -157,10 +159,8 @@ class DenyList: # reset the iterator sit.seek(0) # so we can map the selected string from fzf back to the original objects - memory_map: Dict[str, T] = {} - picker = FzfPrompt( - executable_path=self.fzf_path, default_options="--no-multi" - ) + memory_map: dict[str, T] = {} + picker = FzfPrompt(executable_path=self.fzf_path, default_options="--no-multi") picked_l = picker.prompt( self._deny_cli_remember(itr, memory_map), "--read0", diff --git a/my/core/discovery_pure.py b/my/core/discovery_pure.py index b753de8..18a19c4 100644 --- a/my/core/discovery_pure.py +++ b/my/core/discovery_pure.py @@ -10,6 +10,8 @@ This potentially allows it to be: It should be free of external modules, importlib, exec, etc. etc. ''' +from __future__ import annotations + REQUIRES = 'REQUIRES' NOT_HPI_MODULE_VAR = '__NOT_HPI_MODULE__' @@ -19,8 +21,9 @@ import ast import logging import os import re +from collections.abc import Iterable, Sequence from pathlib import Path -from typing import Any, Iterable, List, NamedTuple, Optional, Sequence, cast +from typing import Any, NamedTuple, Optional, cast ''' None means that requirements weren't defined (different from empty requirements) @@ -30,11 +33,11 @@ Requires = Optional[Sequence[str]] class HPIModule(NamedTuple): name: str - skip_reason: Optional[str] - doc: Optional[str] = None - file: Optional[Path] = None + skip_reason: str | None + doc: str | None = None + file: Path | None = None requires: Requires = None - legacy: Optional[str] = None # contains reason/deprecation warning + legacy: str | None = None # contains reason/deprecation warning def ignored(m: str) -> bool: @@ -55,13 +58,13 @@ def has_stats(src: Path) -> bool: def _has_stats(code: str) -> bool: a: ast.Module = ast.parse(code) for x in a.body: - try: # maybe assign + try: # maybe assign [tg] = cast(Any, x).targets if tg.id == 'stats': return True except: pass - try: # maybe def? + try: # maybe def? name = cast(Any, x).name if name == 'stats': return True @@ -144,7 +147,7 @@ def all_modules() -> Iterable[HPIModule]: def _iter_my_roots() -> Iterable[Path]: import my # doesn't import any code, because of namespace package - paths: List[str] = list(my.__path__) + paths: list[str] = list(my.__path__) if len(paths) == 0: # should probably never happen?, if this code is running, it was imported # because something was added to __path__ to match this name diff --git a/my/core/error.py b/my/core/error.py index ed26dda..b308869 100644 --- a/my/core/error.py +++ b/my/core/error.py @@ -3,19 +3,16 @@ Various error handling helpers See https://beepb00p.xyz/mypy-error-handling.html#kiss for more detail """ +from __future__ import annotations + import traceback +from collections.abc import Iterable, Iterator from datetime import datetime from itertools import tee from typing import ( Any, Callable, - Iterable, - Iterator, - List, Literal, - Optional, - Tuple, - Type, TypeVar, Union, cast, @@ -33,7 +30,7 @@ Res = ResT[T, Exception] ErrorPolicy = Literal["yield", "raise", "drop"] -def notnone(x: Optional[T]) -> T: +def notnone(x: T | None) -> T: assert x is not None return x @@ -60,13 +57,15 @@ def raise_exceptions(itr: Iterable[Res[T]]) -> Iterator[T]: yield o -def warn_exceptions(itr: Iterable[Res[T]], warn_func: Optional[Callable[[Exception], None]] = None) -> Iterator[T]: +def warn_exceptions(itr: Iterable[Res[T]], warn_func: Callable[[Exception], None] | None = None) -> Iterator[T]: # if not provided, use the 'warnings' module if warn_func is None: from my.core.warnings import medium + def _warn_func(e: Exception) -> None: # TODO: print traceback? but user could always --raise-exceptions as well medium(str(e)) + warn_func = _warn_func for o in itr: @@ -81,7 +80,7 @@ def echain(ex: E, cause: Exception) -> E: return ex -def split_errors(l: Iterable[ResT[T, E]], ET: Type[E]) -> Tuple[Iterable[T], Iterable[E]]: +def split_errors(l: Iterable[ResT[T, E]], ET: type[E]) -> tuple[Iterable[T], Iterable[E]]: # TODO would be nice to have ET=Exception default? but it causes some mypy complaints? vit, eit = tee(l) # TODO ugh, not sure if I can reconcile type checking and runtime and convince mypy that ET and E are the same type? @@ -99,7 +98,9 @@ def split_errors(l: Iterable[ResT[T, E]], ET: Type[E]) -> Tuple[Iterable[T], Ite K = TypeVar('K') -def sort_res_by(items: Iterable[Res[T]], key: Callable[[Any], K]) -> List[Res[T]]: + + +def sort_res_by(items: Iterable[Res[T]], key: Callable[[Any], K]) -> list[Res[T]]: """ Sort a sequence potentially interleaved with errors/entries on which the key can't be computed. The general idea is: the error sticks to the non-error entry that follows it @@ -107,7 +108,7 @@ def sort_res_by(items: Iterable[Res[T]], key: Callable[[Any], K]) -> List[Res[T] group = [] groups = [] for i in items: - k: Optional[K] + k: K | None try: k = key(i) except Exception: # error white computing key? dunno, might be nice to handle... @@ -117,10 +118,10 @@ def sort_res_by(items: Iterable[Res[T]], key: Callable[[Any], K]) -> List[Res[T] groups.append((k, group)) group = [] - results: List[Res[T]] = [] - for _v, grp in sorted(groups, key=lambda p: p[0]): # type: ignore[return-value, arg-type] # TODO SupportsLessThan?? + results: list[Res[T]] = [] + for _v, grp in sorted(groups, key=lambda p: p[0]): # type: ignore[return-value, arg-type] # TODO SupportsLessThan?? results.extend(grp) - results.extend(group) # handle last group (it will always be errors only) + results.extend(group) # handle last group (it will always be errors only) return results @@ -162,20 +163,20 @@ def test_sort_res_by() -> None: # helpers to associate timestamps with the errors (so something meaningful could be displayed on the plots, for example) # todo document it under 'patterns' somewhere... # todo proper typevar? -def set_error_datetime(e: Exception, dt: Optional[datetime]) -> None: +def set_error_datetime(e: Exception, dt: datetime | None) -> None: if dt is None: return e.args = (*e.args, dt) # todo not sure if should return new exception? -def attach_dt(e: Exception, *, dt: Optional[datetime]) -> Exception: +def attach_dt(e: Exception, *, dt: datetime | None) -> Exception: set_error_datetime(e, dt) return e # todo it might be problematic because might mess with timezones (when it's converted to string, it's converted to a shift) -def extract_error_datetime(e: Exception) -> Optional[datetime]: +def extract_error_datetime(e: Exception) -> datetime | None: import re for x in reversed(e.args): @@ -201,10 +202,10 @@ MODULE_SETUP_URL = 'https://github.com/karlicoss/HPI/blob/master/doc/SETUP.org#p def warn_my_config_import_error( - err: Union[ImportError, AttributeError], + err: ImportError | AttributeError, *, - help_url: Optional[str] = None, - module_name: Optional[str] = None, + help_url: str | None = None, + module_name: str | None = None, ) -> bool: """ If the user tried to import something from my.config but it failed, @@ -265,7 +266,7 @@ def test_datetime_errors() -> None: import pytz # noqa: I001 dt_notz = datetime.now() - dt_tz = datetime.now(tz=pytz.timezone('Europe/Amsterdam')) + dt_tz = datetime.now(tz=pytz.timezone('Europe/Amsterdam')) for dt in [dt_tz, dt_notz]: e1 = RuntimeError('whatever') assert extract_error_datetime(e1) is None diff --git a/my/core/experimental.py b/my/core/experimental.py index 1a78272..0a1c3b4 100644 --- a/my/core/experimental.py +++ b/my/core/experimental.py @@ -1,6 +1,8 @@ +from __future__ import annotations + import sys import types -from typing import Any, Dict, Optional +from typing import Any # The idea behind this one is to support accessing "overlaid/shadowed" modules from namespace packages @@ -20,7 +22,7 @@ def import_original_module( file: str, *, star: bool = False, - globals: Optional[Dict[str, Any]] = None, + globals: dict[str, Any] | None = None, ) -> types.ModuleType: module_to_restore = sys.modules[module_name] diff --git a/my/core/freezer.py b/my/core/freezer.py index 93bceb7..4fb0e25 100644 --- a/my/core/freezer.py +++ b/my/core/freezer.py @@ -1,29 +1,29 @@ -from .internal import assert_subpackage; assert_subpackage(__name__) +from __future__ import annotations -import dataclasses as dcl +from .internal import assert_subpackage + +assert_subpackage(__name__) + +import dataclasses import inspect -from typing import Any, Type, TypeVar +from typing import Any, Generic, TypeVar D = TypeVar('D') -def _freeze_dataclass(Orig: Type[D]): - ofields = [(f.name, f.type, f) for f in dcl.fields(Orig)] # type: ignore[arg-type] # see https://github.com/python/typing_extensions/issues/115 +def _freeze_dataclass(Orig: type[D]): + ofields = [(f.name, f.type, f) for f in dataclasses.fields(Orig)] # type: ignore[arg-type] # see https://github.com/python/typing_extensions/issues/115 # extract properties along with their types - props = list(inspect.getmembers(Orig, lambda o: isinstance(o, property))) + props = list(inspect.getmembers(Orig, lambda o: isinstance(o, property))) pfields = [(name, inspect.signature(getattr(prop, 'fget')).return_annotation) for name, prop in props] # FIXME not sure about name? # NOTE: sadly passing bases=[Orig] won't work, python won't let us override properties with fields - RRR = dcl.make_dataclass('RRR', fields=[*ofields, *pfields]) + RRR = dataclasses.make_dataclass('RRR', fields=[*ofields, *pfields]) # todo maybe even declare as slots? return props, RRR -# todo need some decorator thingie? -from typing import Generic - - class Freezer(Generic[D]): ''' Some magic which converts dataclass properties into fields. @@ -31,13 +31,13 @@ class Freezer(Generic[D]): For now only supports dataclasses. ''' - def __init__(self, Orig: Type[D]) -> None: + def __init__(self, Orig: type[D]) -> None: self.Orig = Orig self.props, self.Frozen = _freeze_dataclass(Orig) def freeze(self, value: D) -> D: pvalues = {name: getattr(value, name) for name, _ in self.props} - return self.Frozen(**dcl.asdict(value), **pvalues) # type: ignore[call-overload] # see https://github.com/python/typing_extensions/issues/115 + return self.Frozen(**dataclasses.asdict(value), **pvalues) # type: ignore[call-overload] # see https://github.com/python/typing_extensions/issues/115 ### tests @@ -45,7 +45,7 @@ class Freezer(Generic[D]): # this needs to be defined here to prevent a mypy bug # see https://github.com/python/mypy/issues/7281 -@dcl.dataclass +@dataclasses.dataclass class _A: x: Any @@ -71,6 +71,7 @@ def test_freezer() -> None: assert fd['typed'] == 123 assert fd['untyped'] == [1, 2, 3] + ### # TODO shit. what to do with exceptions? diff --git a/my/core/hpi_compat.py b/my/core/hpi_compat.py index 949046d..3687483 100644 --- a/my/core/hpi_compat.py +++ b/my/core/hpi_compat.py @@ -3,11 +3,14 @@ Contains various backwards compatibility/deprecation helpers relevant to HPI its (as opposed to .compat module which implements compatibility between python versions) """ +from __future__ import annotations + import inspect import os import re +from collections.abc import Iterator, Sequence from types import ModuleType -from typing import Iterator, List, Optional, Sequence, TypeVar +from typing import TypeVar from . import warnings @@ -15,7 +18,7 @@ from . import warnings def handle_legacy_import( parent_module_name: str, legacy_submodule_name: str, - parent_module_path: List[str], + parent_module_path: list[str], ) -> bool: ### # this is to trick mypy into treating this as a proper namespace package @@ -122,8 +125,8 @@ class always_supports_sequence(Iterator[V]): def __init__(self, it: Iterator[V]) -> None: self._it = it - self._list: Optional[List[V]] = None - self._lit: Optional[Iterator[V]] = None + self._list: list[V] | None = None + self._lit: Iterator[V] | None = None def __iter__(self) -> Iterator[V]: # noqa: PYI034 if self._list is not None: @@ -142,7 +145,7 @@ class always_supports_sequence(Iterator[V]): return getattr(self._it, name) @property - def _aslist(self) -> List[V]: + def _aslist(self) -> list[V]: if self._list is None: qualname = getattr(self._it, '__qualname__', '') # defensive just in case warnings.medium(f'Using {qualname} as list is deprecated. Migrate to iterative processing or call list() explicitly.') diff --git a/my/core/influxdb.py b/my/core/influxdb.py index 25eeba1..78a439a 100644 --- a/my/core/influxdb.py +++ b/my/core/influxdb.py @@ -2,9 +2,14 @@ TODO doesn't really belong to 'core' morally, but can think of moving out later ''' -from .internal import assert_subpackage; assert_subpackage(__name__) +from __future__ import annotations -from typing import Any, Dict, Iterable, Optional +from .internal import assert_subpackage + +assert_subpackage(__name__) + +from collections.abc import Iterable +from typing import Any import click @@ -21,7 +26,7 @@ class config: RESET_DEFAULT = False -def fill(it: Iterable[Any], *, measurement: str, reset: bool=RESET_DEFAULT, dt_col: str='dt') -> None: +def fill(it: Iterable[Any], *, measurement: str, reset: bool = RESET_DEFAULT, dt_col: str = 'dt') -> None: # todo infer dt column automatically, reuse in stat? # it doesn't like dots, ends up some syntax error? measurement = measurement.replace('.', '_') @@ -30,6 +35,7 @@ def fill(it: Iterable[Any], *, measurement: str, reset: bool=RESET_DEFAULT, dt_c db = config.db from influxdb import InfluxDBClient # type: ignore + client = InfluxDBClient() # todo maybe create if not exists? # client.create_database(db) @@ -40,7 +46,7 @@ def fill(it: Iterable[Any], *, measurement: str, reset: bool=RESET_DEFAULT, dt_c client.delete_series(database=db, measurement=measurement) # TODO need to take schema here... - cache: Dict[str, bool] = {} + cache: dict[str, bool] = {} def good(f, v) -> bool: c = cache.get(f) @@ -59,9 +65,9 @@ def fill(it: Iterable[Any], *, measurement: str, reset: bool=RESET_DEFAULT, dt_c def dit() -> Iterable[Json]: for i in it: d = asdict(i) - tags: Optional[Json] = None - tags_ = d.get('tags') # meh... handle in a more robust manner - if tags_ is not None and isinstance(tags_, dict): # FIXME meh. + tags: Json | None = None + tags_ = d.get('tags') # meh... handle in a more robust manner + if tags_ is not None and isinstance(tags_, dict): # FIXME meh. del d['tags'] tags = tags_ @@ -84,6 +90,7 @@ def fill(it: Iterable[Any], *, measurement: str, reset: bool=RESET_DEFAULT, dt_c } from more_itertools import chunked + # "The optimal batch size is 5000 lines of line protocol." # some chunking is def necessary, otherwise it fails inserted = 0 @@ -97,9 +104,9 @@ def fill(it: Iterable[Any], *, measurement: str, reset: bool=RESET_DEFAULT, dt_c # todo "Specify timestamp precision when writing to InfluxDB."? -def magic_fill(it, *, name: Optional[str]=None, reset: bool=RESET_DEFAULT) -> None: +def magic_fill(it, *, name: str | None = None, reset: bool = RESET_DEFAULT) -> None: if name is None: - assert callable(it) # generators have no name/module + assert callable(it) # generators have no name/module name = f'{it.__module__}:{it.__name__}' assert name is not None @@ -109,6 +116,7 @@ def magic_fill(it, *, name: Optional[str]=None, reset: bool=RESET_DEFAULT) -> No from itertools import tee from more_itertools import first, one + it, x = tee(it) f = first(x, default=None) if f is None: @@ -118,9 +126,11 @@ def magic_fill(it, *, name: Optional[str]=None, reset: bool=RESET_DEFAULT) -> No # TODO can we reuse pandas code or something? # from .pandas import _as_columns + schema = _as_columns(type(f)) from datetime import datetime + dtex = RuntimeError(f'expected single datetime field. schema: {schema}') dtf = one((f for f, t in schema.items() if t == datetime), too_short=dtex, too_long=dtex) @@ -137,6 +147,7 @@ def main() -> None: @click.argument('FUNCTION_NAME', type=str, required=True) def populate(*, function_name: str, reset: bool) -> None: from .__main__ import _locate_functions_or_prompt + [provider] = list(_locate_functions_or_prompt([function_name])) # todo could have a non-interactive version which populates from all data sources for the provider? magic_fill(provider, reset=reset) diff --git a/my/core/init.py b/my/core/init.py index 7a30955..644c7b4 100644 --- a/my/core/init.py +++ b/my/core/init.py @@ -19,6 +19,7 @@ def setup_config() -> None: from pathlib import Path from .preinit import get_mycfg_dir + mycfg_dir = get_mycfg_dir() if not mycfg_dir.exists(): @@ -43,6 +44,7 @@ See https://github.com/karlicoss/HPI/blob/master/doc/SETUP.org#setting-up-the-mo except ImportError as ex: # just in case... who knows what crazy setup users have import logging + logging.exception(ex) warnings.warn(f""" Importing 'my.config' failed! (error: {ex}). This is likely to result in issues. diff --git a/my/core/kompress.py b/my/core/kompress.py index 7cbf310..8accb2d 100644 --- a/my/core/kompress.py +++ b/my/core/kompress.py @@ -1,4 +1,6 @@ -from .internal import assert_subpackage; assert_subpackage(__name__) +from .internal import assert_subpackage + +assert_subpackage(__name__) from . import warnings diff --git a/my/core/konsume.py b/my/core/konsume.py index 0e4a2fe..6d24167 100644 --- a/my/core/konsume.py +++ b/my/core/konsume.py @@ -5,17 +5,21 @@ This can potentially allow both for safer defensive parsing, and let you know if TODO perhaps need to get some inspiration from linear logic to decide on a nice API... ''' +from __future__ import annotations + from collections import OrderedDict -from typing import Any, List +from typing import Any def ignore(w, *keys): for k in keys: w[k].ignore() + def zoom(w, *keys): return [w[k].zoom() for k in keys] + # TODO need to support lists class Zoomable: def __init__(self, parent, *args, **kwargs) -> None: @@ -40,7 +44,7 @@ class Zoomable: assert self.parent is not None self.parent._remove(self) - def zoom(self) -> 'Zoomable': + def zoom(self) -> Zoomable: self.consume() return self @@ -63,6 +67,7 @@ class Wdict(Zoomable, OrderedDict): def this_consumed(self): return len(self) == 0 + # TODO specify mypy type for the index special method? @@ -77,6 +82,7 @@ class Wlist(Zoomable, list): def this_consumed(self): return len(self) == 0 + class Wvalue(Zoomable): def __init__(self, parent, value: Any) -> None: super().__init__(parent) @@ -87,23 +93,20 @@ class Wvalue(Zoomable): return [] def this_consumed(self): - return True # TODO not sure.. + return True # TODO not sure.. def __repr__(self): return 'WValue{' + repr(self.value) + '}' -from typing import Tuple - - -def _wrap(j, parent=None) -> Tuple[Zoomable, List[Zoomable]]: +def _wrap(j, parent=None) -> tuple[Zoomable, list[Zoomable]]: res: Zoomable - cc: List[Zoomable] + cc: list[Zoomable] if isinstance(j, dict): res = Wdict(parent) cc = [res] for k, v in j.items(): - vv, c = _wrap(v, parent=res) + vv, c = _wrap(v, parent=res) res[k] = vv cc.extend(c) return res, cc @@ -122,13 +125,14 @@ def _wrap(j, parent=None) -> Tuple[Zoomable, List[Zoomable]]: raise RuntimeError(f'Unexpected type: {type(j)} {j}') +from collections.abc import Iterator from contextlib import contextmanager -from typing import Iterator class UnconsumedError(Exception): pass + # TODO think about error policy later... @contextmanager def wrap(j, *, throw=True) -> Iterator[Zoomable]: @@ -137,7 +141,7 @@ def wrap(j, *, throw=True) -> Iterator[Zoomable]: yield w for c in children: - if not c.this_consumed(): # TODO hmm. how does it figure out if it's consumed??? + if not c.this_consumed(): # TODO hmm. how does it figure out if it's consumed??? if throw: # TODO need to keep a full path or something... raise UnconsumedError(f''' @@ -153,6 +157,7 @@ from typing import cast def test_unconsumed() -> None: import pytest + with pytest.raises(UnconsumedError): with wrap({'a': 1234}) as w: w = cast(Wdict, w) @@ -163,6 +168,7 @@ def test_unconsumed() -> None: w = cast(Wdict, w) d = w['c']['d'].zoom() + def test_consumed() -> None: with wrap({'a': 1234}) as w: w = cast(Wdict, w) @@ -173,6 +179,7 @@ def test_consumed() -> None: c = w['c'].zoom() d = c['d'].zoom() + def test_types() -> None: # (string, number, object, array, boolean or nul with wrap({'string': 'string', 'number': 3.14, 'boolean': True, 'null': None, 'list': [1, 2, 3]}) as w: @@ -181,9 +188,10 @@ def test_types() -> None: w['number'].consume() w['boolean'].zoom() w['null'].zoom() - for x in list(w['list'].zoom()): # TODO eh. how to avoid the extra list thing? + for x in list(w['list'].zoom()): # TODO eh. how to avoid the extra list thing? x.consume() + def test_consume_all() -> None: with wrap({'aaa': {'bbb': {'hi': 123}}}) as w: w = cast(Wdict, w) @@ -193,11 +201,9 @@ def test_consume_all() -> None: def test_consume_few() -> None: import pytest + pytest.skip('Will think about it later..') - with wrap({ - 'important': 123, - 'unimportant': 'whatever' - }) as w: + with wrap({'important': 123, 'unimportant': 'whatever'}) as w: w = cast(Wdict, w) w['important'].zoom() w.consume_all() @@ -206,6 +212,7 @@ def test_consume_few() -> None: def test_zoom() -> None: import pytest + with wrap({'aaa': 'whatever'}) as w: w = cast(Wdict, w) with pytest.raises(KeyError): diff --git a/my/core/mime.py b/my/core/mime.py index cf5bdf5..8235960 100644 --- a/my/core/mime.py +++ b/my/core/mime.py @@ -2,11 +2,14 @@ Utils for mime/filetype handling """ -from .internal import assert_subpackage; assert_subpackage(__name__) +from __future__ import annotations + +from .internal import assert_subpackage + +assert_subpackage(__name__) import functools - -from .common import PathIsh +from pathlib import Path @functools.lru_cache(1) @@ -23,7 +26,7 @@ import mimetypes # todo do I need init()? # todo wtf? fastermime thinks it's mime is application/json even if the extension is xz?? # whereas magic detects correctly: application/x-zstd and application/x-xz -def fastermime(path: PathIsh) -> str: +def fastermime(path: Path | str) -> str: paths = str(path) # mimetypes is faster, so try it first (mime, _) = mimetypes.guess_type(paths) diff --git a/my/core/orgmode.py b/my/core/orgmode.py index 979f288..96c09a4 100644 --- a/my/core/orgmode.py +++ b/my/core/orgmode.py @@ -1,6 +1,7 @@ """ Various helpers for reading org-mode data """ + from datetime import datetime @@ -22,17 +23,20 @@ def parse_org_datetime(s: str) -> datetime: # TODO I guess want to borrow inspiration from bs4? element type <-> tag; and similar logic for find_one, find_all -from typing import Callable, Iterable, TypeVar +from collections.abc import Iterable +from typing import Callable, TypeVar from orgparse import OrgNode V = TypeVar('V') + def collect(n: OrgNode, cfun: Callable[[OrgNode], Iterable[V]]) -> Iterable[V]: yield from cfun(n) for c in n.children: yield from collect(c, cfun) + from more_itertools import one from orgparse.extra import Table @@ -46,7 +50,7 @@ class TypedTable(Table): tt = super().__new__(TypedTable) tt.__dict__ = orig.__dict__ blocks = list(orig.blocks) - header = blocks[0] # fist block is schema + header = blocks[0] # fist block is schema if len(header) == 2: # TODO later interpret first line as types header = header[1:] diff --git a/my/core/pandas.py b/my/core/pandas.py index 8f5fd29..d444965 100644 --- a/my/core/pandas.py +++ b/my/core/pandas.py @@ -7,17 +7,14 @@ from __future__ import annotations # todo not sure if belongs to 'core'. It's certainly 'more' core than actual modules, but still not essential # NOTE: this file is meant to be importable without Pandas installed import dataclasses +from collections.abc import Iterable, Iterator from datetime import datetime, timezone from pprint import pformat from typing import ( TYPE_CHECKING, Any, Callable, - Dict, - Iterable, - Iterator, Literal, - Type, TypeVar, ) @@ -178,7 +175,7 @@ def _to_jsons(it: Iterable[Res[Any]]) -> Iterable[Json]: Schema = Any -def _as_columns(s: Schema) -> Dict[str, Type]: +def _as_columns(s: Schema) -> dict[str, type]: # todo would be nice to extract properties; add tests for this as well if dataclasses.is_dataclass(s): return {f.name: f.type for f in dataclasses.fields(s)} # type: ignore[misc] # ugh, why mypy thinks f.type can return str?? diff --git a/my/core/preinit.py b/my/core/preinit.py index be5477b..eb3a34f 100644 --- a/my/core/preinit.py +++ b/my/core/preinit.py @@ -8,6 +8,7 @@ def get_mycfg_dir() -> Path: import os import appdirs # type: ignore[import-untyped] + # not sure if that's necessary, i.e. could rely on PYTHONPATH instead # on the other hand, by using MY_CONFIG we are guaranteed to load it from the desired path? mvar = os.environ.get('MY_CONFIG') diff --git a/my/core/pytest.py b/my/core/pytest.py index e514957..ad9e7d7 100644 --- a/my/core/pytest.py +++ b/my/core/pytest.py @@ -2,7 +2,9 @@ Helpers to prevent depending on pytest in runtime """ -from .internal import assert_subpackage; assert_subpackage(__name__) +from .internal import assert_subpackage + +assert_subpackage(__name__) import sys import typing diff --git a/my/core/query.py b/my/core/query.py index 45806fb..50724a7 100644 --- a/my/core/query.py +++ b/my/core/query.py @@ -5,23 +5,20 @@ The main entrypoint to this library is the 'select' function below; try: python3 -c "from my.core.query import select; help(select)" """ +from __future__ import annotations + import dataclasses import importlib import inspect import itertools +from collections.abc import Iterable, Iterator from datetime import datetime from typing import ( Any, Callable, - Dict, - Iterable, - Iterator, - List, NamedTuple, Optional, - Tuple, TypeVar, - Union, ) import more_itertools @@ -51,6 +48,7 @@ class Unsortable(NamedTuple): class QueryException(ValueError): """Used to differentiate query-related errors, so the CLI interface is more expressive""" + pass @@ -63,7 +61,7 @@ def locate_function(module_name: str, function_name: str) -> Callable[[], Iterab """ try: mod = importlib.import_module(module_name) - for (fname, f) in inspect.getmembers(mod, inspect.isfunction): + for fname, f in inspect.getmembers(mod, inspect.isfunction): if fname == function_name: return f # in case the function is defined dynamically, @@ -83,10 +81,10 @@ def locate_qualified_function(qualified_name: str) -> Callable[[], Iterable[ET]] if "." not in qualified_name: raise QueryException("Could not find a '.' in the function name, e.g. my.reddit.rexport.comments") rdot_index = qualified_name.rindex(".") - return locate_function(qualified_name[:rdot_index], qualified_name[rdot_index + 1:]) + return locate_function(qualified_name[:rdot_index], qualified_name[rdot_index + 1 :]) -def attribute_func(obj: T, where: Where, default: Optional[U] = None) -> Optional[OrderFunc]: +def attribute_func(obj: T, where: Where, default: U | None = None) -> OrderFunc | None: """ Attempts to find an attribute which matches the 'where_function' on the object, using some getattr/dict checks. Returns a function which when called with @@ -133,11 +131,11 @@ def attribute_func(obj: T, where: Where, default: Optional[U] = None) -> Optiona def _generate_order_by_func( obj_res: Res[T], *, - key: Optional[str] = None, - where_function: Optional[Where] = None, - default: Optional[U] = None, + key: str | None = None, + where_function: Where | None = None, + default: U | None = None, force_unsortable: bool = False, -) -> Optional[OrderFunc]: +) -> OrderFunc | None: """ Accepts an object Res[T] (Instance of some class or Exception) @@ -202,7 +200,7 @@ pass 'drop_exceptions' to ignore exceptions""") # user must provide either a key or a where predicate if where_function is not None: - func: Optional[OrderFunc] = attribute_func(obj, where_function, default) + func: OrderFunc | None = attribute_func(obj, where_function, default) if func is not None: return func @@ -218,8 +216,6 @@ pass 'drop_exceptions' to ignore exceptions""") return None # couldn't compute a OrderFunc for this class/instance - - # currently using the 'key set' as a proxy for 'this is the same type of thing' def _determine_order_by_value_key(obj_res: ET) -> Any: """ @@ -244,7 +240,7 @@ def _drop_unsorted(itr: Iterator[ET], orderfunc: OrderFunc) -> Iterator[ET]: # try getting the first value from the iterator # similar to my.core.common.warn_if_empty? this doesn't go through the whole iterator though -def _peek_iter(itr: Iterator[ET]) -> Tuple[Optional[ET], Iterator[ET]]: +def _peek_iter(itr: Iterator[ET]) -> tuple[ET | None, Iterator[ET]]: itr = more_itertools.peekable(itr) try: first_item = itr.peek() @@ -255,9 +251,9 @@ def _peek_iter(itr: Iterator[ET]) -> Tuple[Optional[ET], Iterator[ET]]: # similar to 'my.core.error.sort_res_by'? -def _wrap_unsorted(itr: Iterator[ET], orderfunc: OrderFunc) -> Tuple[Iterator[Unsortable], Iterator[ET]]: - unsortable: List[Unsortable] = [] - sortable: List[ET] = [] +def _wrap_unsorted(itr: Iterator[ET], orderfunc: OrderFunc) -> tuple[Iterator[Unsortable], Iterator[ET]]: + unsortable: list[Unsortable] = [] + sortable: list[ET] = [] for o in itr: # if input to select was another select if isinstance(o, Unsortable): @@ -279,7 +275,7 @@ def _handle_unsorted( orderfunc: OrderFunc, drop_unsorted: bool, wrap_unsorted: bool -) -> Tuple[Iterator[Unsortable], Iterator[ET]]: +) -> tuple[Iterator[Unsortable], Iterator[ET]]: # prefer drop_unsorted to wrap_unsorted, if both were present if drop_unsorted: return iter([]), _drop_unsorted(itr, orderfunc) @@ -294,16 +290,16 @@ def _handle_unsorted( # different types. ***This consumes the iterator***, so # you should definitely itertoolts.tee it beforehand # as to not exhaust the values -def _generate_order_value_func(itr: Iterator[ET], order_value: Where, default: Optional[U] = None) -> OrderFunc: +def _generate_order_value_func(itr: Iterator[ET], order_value: Where, default: U | None = None) -> OrderFunc: # TODO: add a kwarg to force lookup for every item? would sort of be like core.common.guess_datetime then - order_by_lookup: Dict[Any, OrderFunc] = {} + order_by_lookup: dict[Any, OrderFunc] = {} # need to go through a copy of the whole iterator here to # pre-generate functions to support sorting mixed types for obj_res in itr: key: Any = _determine_order_by_value_key(obj_res) if key not in order_by_lookup: - keyfunc: Optional[OrderFunc] = _generate_order_by_func( + keyfunc: OrderFunc | None = _generate_order_by_func( obj_res, where_function=order_value, default=default, @@ -324,12 +320,12 @@ def _generate_order_value_func(itr: Iterator[ET], order_value: Where, default: O def _handle_generate_order_by( itr, *, - order_by: Optional[OrderFunc] = None, - order_key: Optional[str] = None, - order_value: Optional[Where] = None, - default: Optional[U] = None, -) -> Tuple[Optional[OrderFunc], Iterator[ET]]: - order_by_chosen: Optional[OrderFunc] = order_by # if the user just supplied a function themselves + order_by: OrderFunc | None = None, + order_key: str | None = None, + order_value: Where | None = None, + default: U | None = None, +) -> tuple[OrderFunc | None, Iterator[ET]]: + order_by_chosen: OrderFunc | None = order_by # if the user just supplied a function themselves if order_by is not None: return order_by, itr if order_key is not None: @@ -354,19 +350,19 @@ def _handle_generate_order_by( def select( - src: Union[Iterable[ET], Callable[[], Iterable[ET]]], + src: Iterable[ET] | Callable[[], Iterable[ET]], *, - where: Optional[Where] = None, - order_by: Optional[OrderFunc] = None, - order_key: Optional[str] = None, - order_value: Optional[Where] = None, - default: Optional[U] = None, + where: Where | None = None, + order_by: OrderFunc | None = None, + order_key: str | None = None, + order_value: Where | None = None, + default: U | None = None, reverse: bool = False, - limit: Optional[int] = None, + limit: int | None = None, drop_unsorted: bool = False, wrap_unsorted: bool = True, warn_exceptions: bool = False, - warn_func: Optional[Callable[[Exception], None]] = None, + warn_func: Callable[[Exception], None] | None = None, drop_exceptions: bool = False, raise_exceptions: bool = False, ) -> Iterator[ET]: @@ -617,7 +613,7 @@ class _B(NamedTuple): # move these to tests/? They are re-used so much in the tests below, # not sure where the best place for these is -def _mixed_iter() -> Iterator[Union[_A, _B]]: +def _mixed_iter() -> Iterator[_A | _B]: yield _A(x=datetime(year=2009, month=5, day=10, hour=4, minute=10, second=1), y=5, z=10) yield _B(y=datetime(year=2015, month=5, day=10, hour=4, minute=10, second=1)) yield _A(x=datetime(year=2005, month=5, day=10, hour=4, minute=10, second=1), y=10, z=2) @@ -626,7 +622,7 @@ def _mixed_iter() -> Iterator[Union[_A, _B]]: yield _A(x=datetime(year=2005, month=4, day=10, hour=4, minute=10, second=1), y=2, z=-5) -def _mixed_iter_errors() -> Iterator[Res[Union[_A, _B]]]: +def _mixed_iter_errors() -> Iterator[Res[_A | _B]]: m = _mixed_iter() yield from itertools.islice(m, 0, 3) yield RuntimeError("Unhandled error!") diff --git a/my/core/query_range.py b/my/core/query_range.py index 1f4a7ff..2a8d7bd 100644 --- a/my/core/query_range.py +++ b/my/core/query_range.py @@ -7,11 +7,14 @@ filtered iterator See the select_range function below """ +from __future__ import annotations + import re import time +from collections.abc import Iterator from datetime import date, datetime, timedelta -from functools import lru_cache -from typing import Any, Callable, Iterator, NamedTuple, Optional, Type +from functools import cache +from typing import Any, Callable, NamedTuple import more_itertools @@ -25,7 +28,9 @@ from .query import ( select, ) -timedelta_regex = re.compile(r"^((?P[\.\d]+?)w)?((?P[\.\d]+?)d)?((?P[\.\d]+?)h)?((?P[\.\d]+?)m)?((?P[\.\d]+?)s)?$") +timedelta_regex = re.compile( + r"^((?P[\.\d]+?)w)?((?P[\.\d]+?)d)?((?P[\.\d]+?)h)?((?P[\.\d]+?)m)?((?P[\.\d]+?)s)?$" +) # https://stackoverflow.com/a/51916936 @@ -88,7 +93,7 @@ def parse_datetime_float(date_str: str) -> float: # dateparser is a bit more lenient than the above, lets you type # all sorts of dates as inputs # https://github.com/scrapinghub/dateparser#how-to-use - res: Optional[datetime] = dateparser.parse(ds, settings={"DATE_ORDER": "YMD"}) + res: datetime | None = dateparser.parse(ds, settings={"DATE_ORDER": "YMD"}) if res is not None: return res.timestamp() @@ -98,7 +103,7 @@ def parse_datetime_float(date_str: str) -> float: # probably DateLike input? but a user could specify an order_key # which is an epoch timestamp or a float value which they # expect to be converted to a datetime to compare -@lru_cache(maxsize=None) +@cache def _datelike_to_float(dl: Any) -> float: if isinstance(dl, datetime): return dl.timestamp() @@ -130,11 +135,12 @@ class RangeTuple(NamedTuple): of the timeframe -- 'before' - before and after - anything after 'after' and before 'before', acts as a time range """ + # technically doesn't need to be Optional[Any], # just to make it more clear these can be None - after: Optional[Any] - before: Optional[Any] - within: Optional[Any] + after: Any | None + before: Any | None + within: Any | None Converter = Callable[[Any], Any] @@ -145,9 +151,9 @@ def _parse_range( unparsed_range: RangeTuple, end_parser: Converter, within_parser: Converter, - parsed_range: Optional[RangeTuple] = None, - error_message: Optional[str] = None -) -> Optional[RangeTuple]: + parsed_range: RangeTuple | None = None, + error_message: str | None = None, +) -> RangeTuple | None: if parsed_range is not None: return parsed_range @@ -176,11 +182,11 @@ def _create_range_filter( end_parser: Converter, within_parser: Converter, attr_func: Where, - parsed_range: Optional[RangeTuple] = None, - default_before: Optional[Any] = None, - value_coercion_func: Optional[Converter] = None, - error_message: Optional[str] = None, -) -> Optional[Where]: + parsed_range: RangeTuple | None = None, + default_before: Any | None = None, + value_coercion_func: Converter | None = None, + error_message: str | None = None, +) -> Where | None: """ Handles: - parsing the user input into values that are comparable to items the iterable returns @@ -272,17 +278,17 @@ def _create_range_filter( def select_range( itr: Iterator[ET], *, - where: Optional[Where] = None, - order_key: Optional[str] = None, - order_value: Optional[Where] = None, - order_by_value_type: Optional[Type] = None, - unparsed_range: Optional[RangeTuple] = None, + where: Where | None = None, + order_key: str | None = None, + order_value: Where | None = None, + order_by_value_type: type | None = None, + unparsed_range: RangeTuple | None = None, reverse: bool = False, - limit: Optional[int] = None, + limit: int | None = None, drop_unsorted: bool = False, wrap_unsorted: bool = False, warn_exceptions: bool = False, - warn_func: Optional[Callable[[Exception], None]] = None, + warn_func: Callable[[Exception], None] | None = None, drop_exceptions: bool = False, raise_exceptions: bool = False, ) -> Iterator[ET]: @@ -317,9 +323,10 @@ def select_range( drop_exceptions=drop_exceptions, raise_exceptions=raise_exceptions, warn_exceptions=warn_exceptions, - warn_func=warn_func) + warn_func=warn_func, + ) - order_by_chosen: Optional[OrderFunc] = None + order_by_chosen: OrderFunc | None = None # if the user didn't specify an attribute to order value, but specified a type # we should search for on each value in the iterator @@ -345,7 +352,7 @@ Specify a type or a key to order the value by""") # force drop_unsorted=True so we can use _create_range_filter # sort the iterable by the generated order_by_chosen function itr = select(itr, order_by=order_by_chosen, drop_unsorted=True) - filter_func: Optional[Where] + filter_func: Where | None if order_by_value_type in [datetime, date]: filter_func = _create_range_filter( unparsed_range=unparsed_range, @@ -353,7 +360,8 @@ Specify a type or a key to order the value by""") within_parser=parse_timedelta_float, attr_func=order_by_chosen, # type: ignore[arg-type] default_before=time.time(), - value_coercion_func=_datelike_to_float) + value_coercion_func=_datelike_to_float, + ) elif order_by_value_type in [int, float]: # allow primitives to be converted using the default int(), float() callables filter_func = _create_range_filter( @@ -362,7 +370,8 @@ Specify a type or a key to order the value by""") within_parser=order_by_value_type, attr_func=order_by_chosen, # type: ignore[arg-type] default_before=None, - value_coercion_func=order_by_value_type) + value_coercion_func=order_by_value_type, + ) else: # TODO: add additional kwargs to let the user sort by other values, by specifying the parsers? # would need to allow passing the end_parser, within parser, default before and value_coercion_func... @@ -470,7 +479,7 @@ def test_range_predicate() -> None: # filter from 0 to 5 rn: RangeTuple = RangeTuple("0", "5", None) - zero_to_five_filter: Optional[Where] = int_filter_func(unparsed_range=rn) + zero_to_five_filter: Where | None = int_filter_func(unparsed_range=rn) assert zero_to_five_filter is not None # this is just a Where function, given some input it return True/False if the value is allowed assert zero_to_five_filter(3) is True @@ -483,6 +492,7 @@ def test_range_predicate() -> None: rn = RangeTuple(None, 3, "3.5") assert list(filter(int_filter_func(unparsed_range=rn, attr_func=identity), src())) == ["0", "1", "2"] + def test_parse_range() -> None: from functools import partial diff --git a/my/core/serialize.py b/my/core/serialize.py index ab11a20..e36da8f 100644 --- a/my/core/serialize.py +++ b/my/core/serialize.py @@ -1,9 +1,11 @@ +from __future__ import annotations + import datetime from dataclasses import asdict, is_dataclass from decimal import Decimal -from functools import lru_cache +from functools import cache from pathlib import Path -from typing import Any, Callable, NamedTuple, Optional +from typing import Any, Callable, NamedTuple from .error import error_to_json from .pytest import parametrize @@ -57,12 +59,12 @@ def _default_encode(obj: Any) -> Any: # could possibly run multiple times/raise warning if you provide different 'default' # functions or change the kwargs? The alternative is to maintain all of this at the module # level, which is just as annoying -@lru_cache(maxsize=None) +@cache def _dumps_factory(**kwargs) -> Callable[[Any], str]: use_default: DefaultEncoder = _default_encode # if the user passed an additional 'default' parameter, # try using that to serialize before before _default_encode - _additional_default: Optional[DefaultEncoder] = kwargs.get("default") + _additional_default: DefaultEncoder | None = kwargs.get("default") if _additional_default is not None and callable(_additional_default): def wrapped_default(obj: Any) -> Any: @@ -78,9 +80,9 @@ def _dumps_factory(**kwargs) -> Callable[[Any], str]: kwargs["default"] = use_default - prefer_factory: Optional[str] = kwargs.pop('_prefer_factory', None) + prefer_factory: str | None = kwargs.pop('_prefer_factory', None) - def orjson_factory() -> Optional[Dumps]: + def orjson_factory() -> Dumps | None: try: import orjson except ModuleNotFoundError: @@ -95,7 +97,7 @@ def _dumps_factory(**kwargs) -> Callable[[Any], str]: return _orjson_dumps - def simplejson_factory() -> Optional[Dumps]: + def simplejson_factory() -> Dumps | None: try: from simplejson import dumps as simplejson_dumps except ModuleNotFoundError: @@ -115,7 +117,7 @@ def _dumps_factory(**kwargs) -> Callable[[Any], str]: return _simplejson_dumps - def stdlib_factory() -> Optional[Dumps]: + def stdlib_factory() -> Dumps | None: import json from .warnings import high @@ -150,7 +152,7 @@ def _dumps_factory(**kwargs) -> Callable[[Any], str]: def dumps( obj: Any, - default: Optional[DefaultEncoder] = None, + default: DefaultEncoder | None = None, **kwargs, ) -> str: """ diff --git a/my/core/source.py b/my/core/source.py index 52c58c1..a309d13 100644 --- a/my/core/source.py +++ b/my/core/source.py @@ -3,9 +3,12 @@ Decorator to gracefully handle importing a data source, or warning and yielding nothing (or a default) when its not available """ +from __future__ import annotations + import warnings +from collections.abc import Iterable, Iterator from functools import wraps -from typing import Any, Callable, Iterable, Iterator, Optional, TypeVar +from typing import Any, Callable, TypeVar from .warnings import medium @@ -26,8 +29,8 @@ _DEFAULT_ITR = () def import_source( *, default: Iterable[T] = _DEFAULT_ITR, - module_name: Optional[str] = None, - help_url: Optional[str] = None, + module_name: str | None = None, + help_url: str | None = None, ) -> Callable[..., Callable[..., Iterator[T]]]: """ doesn't really play well with types, but is used to catch @@ -50,6 +53,7 @@ def import_source( except (ImportError, AttributeError) as err: from . import core_config as CC from .error import warn_my_config_import_error + suppressed_in_conf = False if module_name is not None and CC.config._is_module_active(module_name) is False: suppressed_in_conf = True @@ -72,5 +76,7 @@ class core: if not matched_config_err and isinstance(err, AttributeError): raise err yield from default + return wrapper + return decorator diff --git a/my/core/sqlite.py b/my/core/sqlite.py index 08a80e5..aa41ab3 100644 --- a/my/core/sqlite.py +++ b/my/core/sqlite.py @@ -1,12 +1,16 @@ -from .internal import assert_subpackage; assert_subpackage(__name__) +from __future__ import annotations +from .internal import assert_subpackage # noqa: I001 + +assert_subpackage(__name__) import shutil import sqlite3 +from collections.abc import Iterator from contextlib import contextmanager from pathlib import Path from tempfile import TemporaryDirectory -from typing import Any, Callable, Iterator, Literal, Optional, Tuple, Union, overload +from typing import Any, Callable, Literal, Union, overload from .common import PathIsh from .compat import assert_never @@ -22,6 +26,7 @@ def test_sqlite_connect_immutable(tmp_path: Path) -> None: conn.execute('CREATE TABLE testtable (col)') import pytest + with pytest.raises(sqlite3.OperationalError, match='readonly database'): with sqlite_connect_immutable(db) as conn: conn.execute('DROP TABLE testtable') @@ -33,6 +38,7 @@ def test_sqlite_connect_immutable(tmp_path: Path) -> None: SqliteRowFactory = Callable[[sqlite3.Cursor, sqlite3.Row], Any] + def dict_factory(cursor, row): fields = [column[0] for column in cursor.description] return dict(zip(fields, row)) @@ -40,8 +46,9 @@ def dict_factory(cursor, row): Factory = Union[SqliteRowFactory, Literal['row', 'dict']] + @contextmanager -def sqlite_connection(db: PathIsh, *, immutable: bool=False, row_factory: Optional[Factory]=None) -> Iterator[sqlite3.Connection]: +def sqlite_connection(db: PathIsh, *, immutable: bool = False, row_factory: Factory | None = None) -> Iterator[sqlite3.Connection]: dbp = f'file:{db}' # https://www.sqlite.org/draft/uri.html#uriimmutable if immutable: @@ -97,30 +104,32 @@ def sqlite_copy_and_open(db: PathIsh) -> sqlite3.Connection: # and then the return type ends up as Iterator[Tuple[str, ...]], which isn't desirable :( # a bit annoying to have this copy-pasting, but hopefully not a big issue +# fmt: off @overload -def select(cols: Tuple[str ], rest: str, *, db: sqlite3.Connection) -> \ - Iterator[Tuple[Any ]]: ... +def select(cols: tuple[str ], rest: str, *, db: sqlite3.Connection) -> \ + Iterator[tuple[Any ]]: ... @overload -def select(cols: Tuple[str, str ], rest: str, *, db: sqlite3.Connection) -> \ - Iterator[Tuple[Any, Any ]]: ... +def select(cols: tuple[str, str ], rest: str, *, db: sqlite3.Connection) -> \ + Iterator[tuple[Any, Any ]]: ... @overload -def select(cols: Tuple[str, str, str ], rest: str, *, db: sqlite3.Connection) -> \ - Iterator[Tuple[Any, Any, Any ]]: ... +def select(cols: tuple[str, str, str ], rest: str, *, db: sqlite3.Connection) -> \ + Iterator[tuple[Any, Any, Any ]]: ... @overload -def select(cols: Tuple[str, str, str, str ], rest: str, *, db: sqlite3.Connection) -> \ - Iterator[Tuple[Any, Any, Any, Any ]]: ... +def select(cols: tuple[str, str, str, str ], rest: str, *, db: sqlite3.Connection) -> \ + Iterator[tuple[Any, Any, Any, Any ]]: ... @overload -def select(cols: Tuple[str, str, str, str, str ], rest: str, *, db: sqlite3.Connection) -> \ - Iterator[Tuple[Any, Any, Any, Any, Any ]]: ... +def select(cols: tuple[str, str, str, str, str ], rest: str, *, db: sqlite3.Connection) -> \ + Iterator[tuple[Any, Any, Any, Any, Any ]]: ... @overload -def select(cols: Tuple[str, str, str, str, str, str ], rest: str, *, db: sqlite3.Connection) -> \ - Iterator[Tuple[Any, Any, Any, Any, Any, Any ]]: ... +def select(cols: tuple[str, str, str, str, str, str ], rest: str, *, db: sqlite3.Connection) -> \ + Iterator[tuple[Any, Any, Any, Any, Any, Any ]]: ... @overload -def select(cols: Tuple[str, str, str, str, str, str, str ], rest: str, *, db: sqlite3.Connection) -> \ - Iterator[Tuple[Any, Any, Any, Any, Any, Any, Any ]]: ... +def select(cols: tuple[str, str, str, str, str, str, str ], rest: str, *, db: sqlite3.Connection) -> \ + Iterator[tuple[Any, Any, Any, Any, Any, Any, Any ]]: ... @overload -def select(cols: Tuple[str, str, str, str, str, str, str, str], rest: str, *, db: sqlite3.Connection) -> \ - Iterator[Tuple[Any, Any, Any, Any, Any, Any, Any, Any]]: ... +def select(cols: tuple[str, str, str, str, str, str, str, str], rest: str, *, db: sqlite3.Connection) -> \ + Iterator[tuple[Any, Any, Any, Any, Any, Any, Any, Any]]: ... +# fmt: on def select(cols, rest, *, db): # db arg is last cause that results in nicer code formatting.. diff --git a/my/core/stats.py b/my/core/stats.py index 674a8d1..a553db3 100644 --- a/my/core/stats.py +++ b/my/core/stats.py @@ -2,10 +2,13 @@ Helpers for hpi doctor/stats functionality. ''' +from __future__ import annotations + import collections.abc import importlib import inspect import typing +from collections.abc import Iterable, Iterator, Sequence from contextlib import contextmanager from datetime import datetime from pathlib import Path @@ -13,20 +16,13 @@ from types import ModuleType from typing import ( Any, Callable, - Dict, - Iterable, - Iterator, - List, - Optional, Protocol, - Sequence, - Union, cast, ) from .types import asdict -Stats = Dict[str, Any] +Stats = dict[str, Any] class StatsFun(Protocol): @@ -55,10 +51,10 @@ def quick_stats(): def stat( - func: Union[Callable[[], Iterable[Any]], Iterable[Any]], + func: Callable[[], Iterable[Any]] | Iterable[Any], *, quick: bool = False, - name: Optional[str] = None, + name: str | None = None, ) -> Stats: """ Extracts various statistics from a passed iterable/callable, e.g.: @@ -153,8 +149,8 @@ def test_stat() -> None: # -def get_stats(module_name: str, *, guess: bool = False) -> Optional[StatsFun]: - stats: Optional[StatsFun] = None +def get_stats(module_name: str, *, guess: bool = False) -> StatsFun | None: + stats: StatsFun | None = None try: module = importlib.import_module(module_name) except Exception: @@ -167,7 +163,7 @@ def get_stats(module_name: str, *, guess: bool = False) -> Optional[StatsFun]: # TODO maybe could be enough to annotate OUTPUTS or something like that? # then stats could just use them as hints? -def guess_stats(module: ModuleType) -> Optional[StatsFun]: +def guess_stats(module: ModuleType) -> StatsFun | None: """ If the module doesn't have explicitly defined 'stat' function, this is used to try to guess what could be included in stats automatically @@ -206,7 +202,7 @@ def test_guess_stats() -> None: } -def _guess_data_providers(module: ModuleType) -> Dict[str, Callable]: +def _guess_data_providers(module: ModuleType) -> dict[str, Callable]: mfunctions = inspect.getmembers(module, inspect.isfunction) return {k: v for k, v in mfunctions if is_data_provider(v)} @@ -263,7 +259,7 @@ def test_is_data_provider() -> None: lam = lambda: [1, 2] assert not idp(lam) - def has_extra_args(count) -> List[int]: + def has_extra_args(count) -> list[int]: return list(range(count)) assert not idp(has_extra_args) @@ -340,10 +336,10 @@ def test_type_is_iterable() -> None: assert not fun(None) assert not fun(int) assert not fun(Any) - assert not fun(Dict[int, int]) + assert not fun(dict[int, int]) - assert fun(List[int]) - assert fun(Sequence[Dict[str, str]]) + assert fun(list[int]) + assert fun(Sequence[dict[str, str]]) assert fun(Iterable[Any]) @@ -434,7 +430,7 @@ def test_stat_iterable() -> None: # experimental, not sure about it.. -def _guess_datetime(x: Any) -> Optional[datetime]: +def _guess_datetime(x: Any) -> datetime | None: # todo hmm implement without exception.. try: d = asdict(x) diff --git a/my/core/structure.py b/my/core/structure.py index fa26532..bb049e4 100644 --- a/my/core/structure.py +++ b/my/core/structure.py @@ -1,3 +1,5 @@ +from __future__ import annotations + import atexit import os import shutil @@ -5,9 +7,9 @@ import sys import tarfile import tempfile import zipfile +from collections.abc import Generator, Sequence from contextlib import contextmanager from pathlib import Path -from typing import Generator, List, Sequence, Tuple, Union from .logging import make_logger @@ -42,10 +44,10 @@ TARGZ_EXT = {".tar.gz"} @contextmanager def match_structure( base: Path, - expected: Union[str, Sequence[str]], + expected: str | Sequence[str], *, partial: bool = False, -) -> Generator[Tuple[Path, ...], None, None]: +) -> Generator[tuple[Path, ...], None, None]: """ Given a 'base' directory or archive (zip/tar.gz), recursively search for one or more paths that match the pattern described in 'expected'. That can be a single string, or a list @@ -140,8 +142,8 @@ def match_structure( if not searchdir.is_dir(): raise NotADirectoryError(f"Expected either a zip/tar.gz archive or a directory, received {searchdir}") - matches: List[Path] = [] - possible_targets: List[Path] = [searchdir] + matches: list[Path] = [] + possible_targets: list[Path] = [searchdir] while len(possible_targets) > 0: p = possible_targets.pop(0) @@ -172,7 +174,7 @@ def warn_leftover_files() -> None: from . import core_config as CC base_tmp: Path = CC.config.get_tmp_dir() - leftover: List[Path] = list(base_tmp.iterdir()) + leftover: list[Path] = list(base_tmp.iterdir()) if leftover: logger.debug(f"at exit warning: Found leftover files in temporary directory '{leftover}'. this may be because you have multiple hpi processes running -- if so this can be ignored") diff --git a/my/core/tests/auto_stats.py b/my/core/tests/auto_stats.py index d10d4c4..fc49e03 100644 --- a/my/core/tests/auto_stats.py +++ b/my/core/tests/auto_stats.py @@ -2,11 +2,11 @@ Helper 'module' for test_guess_stats """ +from collections.abc import Iterable, Iterator, Sequence from contextlib import contextmanager from dataclasses import dataclass from datetime import datetime, timedelta from pathlib import Path -from typing import Iterable, Iterator, Sequence @dataclass diff --git a/my/core/tests/common.py b/my/core/tests/common.py index 22a74d7..073ea5f 100644 --- a/my/core/tests/common.py +++ b/my/core/tests/common.py @@ -1,6 +1,8 @@ +from __future__ import annotations + import os +from collections.abc import Iterator from contextlib import contextmanager -from typing import Iterator, Optional import pytest @@ -15,7 +17,7 @@ skip_if_uses_optional_deps = pytest.mark.skipif( # TODO maybe move to hpi core? @contextmanager -def tmp_environ_set(key: str, value: Optional[str]) -> Iterator[None]: +def tmp_environ_set(key: str, value: str | None) -> Iterator[None]: prev_value = os.environ.get(key) if value is None: os.environ.pop(key, None) diff --git a/my/core/tests/denylist.py b/my/core/tests/denylist.py index 2688319..73c3165 100644 --- a/my/core/tests/denylist.py +++ b/my/core/tests/denylist.py @@ -1,8 +1,9 @@ import json import warnings +from collections.abc import Iterator from datetime import datetime from pathlib import Path -from typing import Iterator, NamedTuple +from typing import NamedTuple from ..denylist import DenyList diff --git a/my/core/tests/test_cachew.py b/my/core/tests/test_cachew.py index 70ac76f..a0d2267 100644 --- a/my/core/tests/test_cachew.py +++ b/my/core/tests/test_cachew.py @@ -1,6 +1,6 @@ -from .common import skip_if_uses_optional_deps as pytestmark +from __future__ import annotations -from typing import List +from .common import skip_if_uses_optional_deps as pytestmark # TODO ugh, this is very messy.. need to sort out config overriding here @@ -16,7 +16,7 @@ def test_cachew() -> None: # TODO ugh. need doublewrap or something to avoid having to pass parens @mcachew() - def cf() -> List[int]: + def cf() -> list[int]: nonlocal called called += 1 return [1, 2, 3] @@ -43,7 +43,7 @@ def test_cachew_dir_none() -> None: called = 0 @mcachew(cache_path=cache_dir() / 'ctest') - def cf() -> List[int]: + def cf() -> list[int]: nonlocal called called += 1 return [called, called, called] diff --git a/my/core/tests/test_config.py b/my/core/tests/test_config.py index 78d1a62..f6d12ba 100644 --- a/my/core/tests/test_config.py +++ b/my/core/tests/test_config.py @@ -2,8 +2,8 @@ Various tests that are checking behaviour of user config wrt to various things """ -import sys import os +import sys from pathlib import Path import pytest diff --git a/my/core/time.py b/my/core/time.py index fa20a7c..a9b180d 100644 --- a/my/core/time.py +++ b/my/core/time.py @@ -1,5 +1,7 @@ -from functools import lru_cache -from typing import Dict, Sequence +from __future__ import annotations + +from collections.abc import Sequence +from functools import cache, lru_cache import pytz @@ -11,6 +13,7 @@ def user_forced() -> Sequence[str]: # https://stackoverflow.com/questions/36067621/python-all-possible-timezone-abbreviations-for-given-timezone-name-and-vise-ve try: from my.config import time as user_config + return user_config.tz.force_abbreviations # type: ignore[attr-defined] # noqa: TRY300 # note: noqa since we're catching case where config doesn't have attribute here as well except: @@ -19,15 +22,15 @@ def user_forced() -> Sequence[str]: @lru_cache(1) -def _abbr_to_timezone_map() -> Dict[str, pytz.BaseTzInfo]: +def _abbr_to_timezone_map() -> dict[str, pytz.BaseTzInfo]: # also force UTC to always correspond to utc # this makes more sense than Zulu it ends up by default timezones = [*pytz.all_timezones, 'UTC', *user_forced()] - res: Dict[str, pytz.BaseTzInfo] = {} + res: dict[str, pytz.BaseTzInfo] = {} for tzname in timezones: tz = pytz.timezone(tzname) - infos = getattr(tz, '_tzinfos', []) # not sure if can rely on attr always present? + infos = getattr(tz, '_tzinfos', []) # not sure if can rely on attr always present? for info in infos: abbr = info[-1] # todo could support this with a better error handling strategy? @@ -43,7 +46,7 @@ def _abbr_to_timezone_map() -> Dict[str, pytz.BaseTzInfo]: return res -@lru_cache(maxsize=None) +@cache def abbr_to_timezone(abbr: str) -> pytz.BaseTzInfo: return _abbr_to_timezone_map()[abbr] diff --git a/my/core/types.py b/my/core/types.py index b1cf103..dc19c19 100644 --- a/my/core/types.py +++ b/my/core/types.py @@ -1,14 +1,15 @@ -from .internal import assert_subpackage; assert_subpackage(__name__) +from __future__ import annotations + +from .internal import assert_subpackage + +assert_subpackage(__name__) from dataclasses import asdict as dataclasses_asdict from dataclasses import is_dataclass from datetime import datetime -from typing import ( - Any, - Dict, -) +from typing import Any -Json = Dict[str, Any] +Json = dict[str, Any] # for now just serves documentation purposes... but one day might make it statically verifiable where possible? diff --git a/my/core/util.py b/my/core/util.py index a247f81..74e71e1 100644 --- a/my/core/util.py +++ b/my/core/util.py @@ -1,10 +1,12 @@ +from __future__ import annotations + import os import pkgutil import sys +from collections.abc import Iterable from itertools import chain from pathlib import Path from types import ModuleType -from typing import Iterable, List, Optional from .discovery_pure import HPIModule, _is_not_module_src, has_stats, ignored @@ -20,13 +22,14 @@ from .discovery_pure import NOT_HPI_MODULE_VAR assert NOT_HPI_MODULE_VAR in globals() # check name consistency -def is_not_hpi_module(module: str) -> Optional[str]: + +def is_not_hpi_module(module: str) -> str | None: ''' None if a module, otherwise returns reason ''' import importlib.util - path: Optional[str] = None + path: str | None = None try: # TODO annoying, this can cause import of the parent module? spec = importlib.util.find_spec(module) @@ -35,7 +38,7 @@ def is_not_hpi_module(module: str) -> Optional[str]: except Exception as e: # todo a bit misleading.. it actually shouldn't import in most cases, it's just the weird parent module import thing return "import error (possibly missing config entry)" # todo add exc message? - assert path is not None # not sure if can happen? + assert path is not None # not sure if can happen? if _is_not_module_src(Path(path)): return f"marked explicitly (via {NOT_HPI_MODULE_VAR})" @@ -57,9 +60,10 @@ def _iter_all_importables(pkg: ModuleType) -> Iterable[HPIModule]: def _discover_path_importables(pkg_pth: Path, pkg_name: str) -> Iterable[HPIModule]: - from .core_config import config - """Yield all importables under a given path and package.""" + + from .core_config import config # noqa: F401 + for dir_path, dirs, file_names in os.walk(pkg_pth): file_names.sort() # NOTE: sorting dirs in place is intended, it's the way you're supposed to do it with os.walk @@ -82,6 +86,7 @@ def _discover_path_importables(pkg_pth: Path, pkg_name: str) -> Iterable[HPIModu # TODO might need to make it defensive and yield Exception (otherwise hpi doctor might fail for no good reason) # use onerror=? + # ignored explicitly -> not HPI # if enabled in config -> HPI # if disabled in config -> HPI @@ -90,7 +95,7 @@ def _discover_path_importables(pkg_pth: Path, pkg_name: str) -> Iterable[HPIModu # TODO when do we need to recurse? -def _walk_packages(path: Iterable[str], prefix: str='', onerror=None) -> Iterable[HPIModule]: +def _walk_packages(path: Iterable[str], prefix: str = '', onerror=None) -> Iterable[HPIModule]: """ Modified version of https://github.com/python/cpython/blob/d50a0700265536a20bcce3fb108c954746d97625/Lib/pkgutil.py#L53, to avoid importing modules that are skipped @@ -153,8 +158,9 @@ def _walk_packages(path: Iterable[str], prefix: str='', onerror=None) -> Iterabl path = [p for p in path if not seen(p)] yield from _walk_packages(path, mname + '.', onerror) + # deprecate? -def get_modules() -> List[HPIModule]: +def get_modules() -> list[HPIModule]: return list(modules()) @@ -169,14 +175,14 @@ def test_module_detection() -> None: with reset() as cc: cc.disabled_modules = ['my.location.*', 'my.body.*', 'my.workouts.*', 'my.private.*'] mods = {m.name: m for m in modules()} - assert mods['my.demo'] .skip_reason == "has no 'stats()' function" + assert mods['my.demo'].skip_reason == "has no 'stats()' function" with reset() as cc: cc.disabled_modules = ['my.location.*', 'my.body.*', 'my.workouts.*', 'my.private.*', 'my.lastfm'] - cc.enabled_modules = ['my.demo'] + cc.enabled_modules = ['my.demo'] mods = {m.name: m for m in modules()} - assert mods['my.demo'] .skip_reason is None # not skipped + assert mods['my.demo'].skip_reason is None # not skipped assert mods['my.lastfm'].skip_reason == "suppressed in the user config" diff --git a/my/core/utils/concurrent.py b/my/core/utils/concurrent.py index 73944ec..515c3f1 100644 --- a/my/core/utils/concurrent.py +++ b/my/core/utils/concurrent.py @@ -1,6 +1,7 @@ -import sys +from __future__ import annotations + from concurrent.futures import Executor, Future -from typing import Any, Callable, Optional, TypeVar +from typing import Any, Callable, TypeVar from ..compat import ParamSpec @@ -15,7 +16,7 @@ class DummyExecutor(Executor): but also want to provide an option to run the code serially (e.g. for debugging) """ - def __init__(self, max_workers: Optional[int] = 1) -> None: + def __init__(self, max_workers: int | None = 1) -> None: self._shutdown = False self._max_workers = max_workers diff --git a/my/core/utils/imports.py b/my/core/utils/imports.py index 4666a5e..e0fb01d 100644 --- a/my/core/utils/imports.py +++ b/my/core/utils/imports.py @@ -1,27 +1,27 @@ +from __future__ import annotations + import importlib import importlib.util import sys from pathlib import Path from types import ModuleType -from typing import Optional - -from ..common import PathIsh # TODO only used in tests? not sure if useful at all. -def import_file(p: PathIsh, name: Optional[str] = None) -> ModuleType: +def import_file(p: Path | str, name: str | None = None) -> ModuleType: p = Path(p) if name is None: name = p.stem spec = importlib.util.spec_from_file_location(name, p) assert spec is not None, f"Fatal error; Could not create module spec from {name} {p}" foo = importlib.util.module_from_spec(spec) - loader = spec.loader; assert loader is not None + loader = spec.loader + assert loader is not None loader.exec_module(foo) return foo -def import_from(path: PathIsh, name: str) -> ModuleType: +def import_from(path: Path | str, name: str) -> ModuleType: path = str(path) sys.path.append(path) try: @@ -30,7 +30,7 @@ def import_from(path: PathIsh, name: str) -> ModuleType: sys.path.remove(path) -def import_dir(path: PathIsh, extra: str = '') -> ModuleType: +def import_dir(path: Path | str, extra: str = '') -> ModuleType: p = Path(path) if p.parts[0] == '~': p = p.expanduser() # TODO eh. not sure about this.. diff --git a/my/core/utils/itertools.py b/my/core/utils/itertools.py index ae9402d..501ebbe 100644 --- a/my/core/utils/itertools.py +++ b/my/core/utils/itertools.py @@ -4,17 +4,13 @@ Various helpers/transforms of iterators Ideally this should be as small as possible and we should rely on stdlib itertools or more_itertools """ +from __future__ import annotations + import warnings -from collections.abc import Hashable +from collections.abc import Hashable, Iterable, Iterator, Sized from typing import ( TYPE_CHECKING, Callable, - Dict, - Iterable, - Iterator, - List, - Optional, - Sized, TypeVar, Union, cast, @@ -23,9 +19,8 @@ from typing import ( import more_itertools from decorator import decorator -from ..compat import ParamSpec from .. import warnings as core_warnings - +from ..compat import ParamSpec T = TypeVar('T') K = TypeVar('K') @@ -39,7 +34,7 @@ def _identity(v: T) -> V: # type: ignore[type-var] # ugh. nothing in more_itertools? # perhaps duplicates_everseen? but it doesn't yield non-unique elements? def ensure_unique(it: Iterable[T], *, key: Callable[[T], K]) -> Iterable[T]: - key2item: Dict[K, T] = {} + key2item: dict[K, T] = {} for i in it: k = key(i) pi = key2item.get(k, None) @@ -72,10 +67,10 @@ def make_dict( key: Callable[[T], K], # TODO make value optional instead? but then will need a typing override for it? value: Callable[[T], V] = _identity, -) -> Dict[K, V]: +) -> dict[K, V]: with_keys = ((key(i), i) for i in it) uniques = ensure_unique(with_keys, key=lambda p: p[0]) - res: Dict[K, V] = {} + res: dict[K, V] = {} for k, i in uniques: res[k] = i if value is None else value(i) return res @@ -93,8 +88,8 @@ def test_make_dict() -> None: d = make_dict(it, key=lambda i: i % 2, value=lambda i: i) # check type inference - d2: Dict[str, int] = make_dict(it, key=lambda i: str(i)) - d3: Dict[str, bool] = make_dict(it, key=lambda i: str(i), value=lambda i: i % 2 == 0) + d2: dict[str, int] = make_dict(it, key=lambda i: str(i)) + d3: dict[str, bool] = make_dict(it, key=lambda i: str(i), value=lambda i: i % 2 == 0) LFP = ParamSpec('LFP') @@ -102,7 +97,7 @@ LV = TypeVar('LV') @decorator -def _listify(func: Callable[LFP, Iterable[LV]], *args: LFP.args, **kwargs: LFP.kwargs) -> List[LV]: +def _listify(func: Callable[LFP, Iterable[LV]], *args: LFP.args, **kwargs: LFP.kwargs) -> list[LV]: """ Wraps a function's return value in wrapper (e.g. list) Useful when an algorithm can be expressed more cleanly as a generator @@ -115,7 +110,7 @@ def _listify(func: Callable[LFP, Iterable[LV]], *args: LFP.args, **kwargs: LFP.k # so seems easiest to just use specialize instantiations of decorator instead if TYPE_CHECKING: - def listify(func: Callable[LFP, Iterable[LV]]) -> Callable[LFP, List[LV]]: ... # noqa: ARG001 + def listify(func: Callable[LFP, Iterable[LV]]) -> Callable[LFP, list[LV]]: ... # noqa: ARG001 else: listify = _listify @@ -130,7 +125,7 @@ def test_listify() -> None: yield 2 res = it() - assert_type(res, List[int]) + assert_type(res, list[int]) assert res == [1, 2] @@ -201,24 +196,24 @@ def test_warn_if_empty_list() -> None: ll = [1, 2, 3] @warn_if_empty - def nonempty() -> List[int]: + def nonempty() -> list[int]: return ll with warnings.catch_warnings(record=True) as w: res1 = nonempty() assert len(w) == 0 - assert_type(res1, List[int]) + assert_type(res1, list[int]) assert isinstance(res1, list) assert res1 is ll # object should be unchanged! @warn_if_empty - def empty() -> List[str]: + def empty() -> list[str]: return [] with warnings.catch_warnings(record=True) as w: res2 = empty() assert len(w) == 1 - assert_type(res2, List[str]) + assert_type(res2, list[str]) assert isinstance(res2, list) assert res2 == [] @@ -242,7 +237,7 @@ def check_if_hashable(iterable: Iterable[_HT]) -> Iterable[_HT]: """ NOTE: Despite Hashable bound, typing annotation doesn't guarantee runtime safety Consider hashable type X, and Y that inherits from X, but not hashable - Then l: List[X] = [Y(...)] is a valid expression, and type checks against Hashable, + Then l: list[X] = [Y(...)] is a valid expression, and type checks against Hashable, but isn't runtime hashable """ # Sadly this doesn't work 100% correctly with dataclasses atm... @@ -268,28 +263,27 @@ def check_if_hashable(iterable: Iterable[_HT]) -> Iterable[_HT]: # TODO different policies -- error/warn/ignore? def test_check_if_hashable() -> None: from dataclasses import dataclass - from typing import Set, Tuple import pytest from ..compat import assert_type - x1: List[int] = [1, 2] + x1: list[int] = [1, 2] r1 = check_if_hashable(x1) assert_type(r1, Iterable[int]) assert r1 is x1 - x2: Iterator[Union[int, str]] = iter((123, 'aba')) + x2: Iterator[int | str] = iter((123, 'aba')) r2 = check_if_hashable(x2) assert_type(r2, Iterable[Union[int, str]]) assert list(r2) == [123, 'aba'] - x3: Tuple[object, ...] = (789, 'aba') + x3: tuple[object, ...] = (789, 'aba') r3 = check_if_hashable(x3) assert_type(r3, Iterable[object]) assert r3 is x3 # object should be unchanged - x4: List[Set[int]] = [{1, 2, 3}, {4, 5, 6}] + x4: list[set[int]] = [{1, 2, 3}, {4, 5, 6}] with pytest.raises(Exception): # should be rejected by mypy sice set isn't Hashable, but also throw at runtime r4 = check_if_hashable(x4) # type: ignore[type-var] @@ -307,7 +301,7 @@ def test_check_if_hashable() -> None: class X: a: int - x6: List[X] = [X(a=123)] + x6: list[X] = [X(a=123)] r6 = check_if_hashable(x6) assert x6 is r6 @@ -316,7 +310,7 @@ def test_check_if_hashable() -> None: class Y(X): b: str - x7: List[Y] = [Y(a=123, b='aba')] + x7: list[Y] = [Y(a=123, b='aba')] with pytest.raises(Exception): # ideally that would also be rejected by mypy, but currently there is a bug # which treats all dataclasses as hashable: https://github.com/python/mypy/issues/11463 @@ -331,11 +325,8 @@ _UEU = TypeVar('_UEU') # instead of just iterator # TODO maybe deprecated Callable support? not sure def unique_everseen( - fun: Union[ - Callable[[], Iterable[_UET]], - Iterable[_UET] - ], - key: Optional[Callable[[_UET], _UEU]] = None, + fun: Callable[[], Iterable[_UET]] | Iterable[_UET], + key: Callable[[_UET], _UEU] | None = None, ) -> Iterator[_UET]: import os diff --git a/my/core/warnings.py b/my/core/warnings.py index 2ffc3e4..d67ec7d 100644 --- a/my/core/warnings.py +++ b/my/core/warnings.py @@ -5,14 +5,16 @@ since who looks at the terminal output? E.g. would be nice to propagate the warnings in the UI (it's even a subclass of Exception!) ''' +from __future__ import annotations + import sys import warnings -from typing import TYPE_CHECKING, Optional +from typing import TYPE_CHECKING import click -def _colorize(x: str, color: Optional[str] = None) -> str: +def _colorize(x: str, color: str | None = None) -> str: if color is None: return x @@ -24,7 +26,7 @@ def _colorize(x: str, color: Optional[str] = None) -> str: return click.style(x, fg=color) -def _warn(message: str, *args, color: Optional[str] = None, **kwargs) -> None: +def _warn(message: str, *args, color: str | None = None, **kwargs) -> None: stacklevel = kwargs.get('stacklevel', 1) kwargs['stacklevel'] = stacklevel + 2 # +1 for this function, +1 for medium/high wrapper warnings.warn(_colorize(message, color=color), *args, **kwargs) # noqa: B028 From 8496d131e7e44b3effcc289762a4218aa1457725 Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Sat, 19 Oct 2024 22:10:40 +0100 Subject: [PATCH 113/122] general: migrate modules to use 3.9 features --- my/arbtt.py | 23 +++++++----- my/bluemaestro.py | 11 +++--- my/body/blood.py | 36 ++++++++++--------- my/body/exercise/all.py | 6 ++-- my/body/exercise/cardio.py | 1 - my/body/exercise/cross_trainer.py | 18 ++++++---- my/body/sleep/common.py | 5 +-- my/body/sleep/main.py | 5 ++- my/body/weight.py | 8 ++--- my/books/kobo.py | 7 ++-- my/browser/active_browser.py | 8 +++-- my/browser/all.py | 6 ++-- my/browser/export.py | 9 ++--- my/bumble/android.py | 26 +++++++------- my/calendar/holidays.py | 3 +- my/cfg.py | 1 - my/codeforces.py | 9 +++-- my/coding/commits.py | 34 +++++++++--------- my/common.py | 2 +- my/config.py | 36 ++++++++++--------- my/core/_deprecated/kompress.py | 2 +- my/core/common.py | 4 +-- my/demo.py | 6 ++-- my/emfit/__init__.py | 46 +++++++++++++----------- my/endomondo.py | 24 ++++++++----- my/error.py | 2 +- my/experimental/destructive_parsing.py | 9 ++--- my/fbmessenger/__init__.py | 1 + my/fbmessenger/all.py | 6 ++-- my/fbmessenger/android.py | 35 ++++++++++--------- my/fbmessenger/common.py | 18 ++++++---- my/fbmessenger/export.py | 9 +++-- my/foursquare.py | 9 +++-- my/github/all.py | 3 +- my/github/common.py | 21 ++++++----- my/github/gdpr.py | 3 +- my/github/ghexport.py | 25 +++++++++----- my/goodreads.py | 16 +++++---- my/google/maps/_android_protobuf.py | 4 +-- my/google/maps/android.py | 12 +++---- my/google/takeout/html.py | 28 ++++++++------- my/google/takeout/parser.py | 20 ++++++----- my/google/takeout/paths.py | 12 ++++--- my/hackernews/dogsheep.py | 12 +++---- my/hackernews/harmonic.py | 25 +++++++++----- my/hackernews/materialistic.py | 11 +++--- my/hypothesis.py | 10 +++--- my/instagram/all.py | 5 ++- my/instagram/android.py | 37 ++++++++++---------- my/instagram/common.py | 9 ++--- my/instagram/gdpr.py | 19 +++++----- my/instapaper.py | 10 ++++-- my/ip/all.py | 3 +- my/ip/common.py | 7 ++-- my/jawbone/__init__.py | 23 ++++++------ my/jawbone/plots.py | 17 ++++----- my/kobo.py | 31 +++++++++-------- my/kython/kompress.py | 3 +- my/lastfm.py | 14 +++++--- my/location/all.py | 5 ++- my/location/common.py | 11 +++--- my/location/fallback/all.py | 10 +++--- my/location/fallback/common.py | 31 +++++++++-------- my/location/fallback/via_home.py | 32 ++++++++--------- my/location/fallback/via_ip.py | 8 ++--- my/location/google.py | 21 ++++++----- my/location/google_takeout.py | 7 ++-- my/location/google_takeout_semantic.py | 11 +++--- my/location/gpslogger.py | 10 +++--- my/location/home.py | 4 +-- my/location/via_ip.py | 4 +-- my/materialistic.py | 1 + my/media/imdb.py | 10 +++--- my/media/youtube.py | 2 +- my/monzo/monzoexport.py | 5 +-- my/orgmode.py | 10 +++--- my/pdfs.py | 14 ++++---- my/photos/main.py | 29 +++++++++------- my/photos/utils.py | 15 ++++---- my/pinboard.py | 9 ++--- my/pocket.py | 12 ++++--- my/polar.py | 33 ++++++++++-------- my/reddit/__init__.py | 1 + my/reddit/all.py | 7 ++-- my/reddit/common.py | 10 +++--- my/reddit/pushshift.py | 12 +++---- my/reddit/rexport.py | 17 ++++----- my/rescuetime.py | 23 +++++++----- my/roamresearch.py | 29 +++++++++------- my/rss/all.py | 4 +-- my/rss/common.py | 16 +++++---- my/rss/feedbin.py | 8 ++--- my/rss/feedly.py | 3 +- my/rtm.py | 24 ++++++------- my/runnerup.py | 14 ++++---- my/simple.py | 5 ++- my/smscalls.py | 48 ++++++++++++++------------ my/stackexchange/gdpr.py | 20 ++++++++--- my/stackexchange/stexport.py | 3 +- my/taplog.py | 14 ++++---- my/telegram/telegram_backup.py | 30 ++++++++-------- my/tests/bluemaestro.py | 2 +- my/tests/body/weight.py | 6 ++-- my/tests/commits.py | 7 ++-- my/tests/location/fallback.py | 2 +- my/tests/reddit.py | 10 +++--- my/time/tz/common.py | 1 - my/time/tz/main.py | 1 + my/time/tz/via_location.py | 36 +++++++++---------- my/tinder/android.py | 18 +++++----- my/topcoder.py | 8 ++--- my/twitter/all.py | 6 ++-- my/twitter/android.py | 16 ++++----- my/twitter/archive.py | 3 +- my/twitter/common.py | 10 +++--- my/twitter/talon.py | 3 +- my/twitter/twint.py | 10 +++--- my/util/hpi_heartbeat.py | 11 +++--- my/vk/favorites.py | 13 +++---- my/vk/vk_messages_backup.py | 12 +++---- my/whatsapp/android.py | 23 ++++++------ my/youtube/takeout.py | 3 +- my/zotero.py | 22 ++++++------ my/zulip/organization.py | 2 +- ruff.toml | 16 ++++----- 125 files changed, 889 insertions(+), 739 deletions(-) diff --git a/my/arbtt.py b/my/arbtt.py index 2bcf291..5d4bf8e 100644 --- a/my/arbtt.py +++ b/my/arbtt.py @@ -2,20 +2,22 @@ [[https://github.com/nomeata/arbtt#arbtt-the-automatic-rule-based-time-tracker][Arbtt]] time tracking ''' +from __future__ import annotations + REQUIRES = ['ijson', 'cffi'] # NOTE likely also needs libyajl2 from apt or elsewhere? +from collections.abc import Iterable, Sequence from dataclasses import dataclass from pathlib import Path -from typing import Sequence, Iterable, List, Optional def inputs() -> Sequence[Path]: try: from my.config import arbtt as user_config except ImportError: - from .core.warnings import low + from my.core.warnings import low low("Couldn't find 'arbtt' config section, falling back to the default capture.log (usually in HOME dir). Add 'arbtt' section with logfiles = '' to suppress this warning.") return [] else: @@ -55,7 +57,7 @@ class Entry: return fromisoformat(ds) @property - def active(self) -> Optional[str]: + def active(self) -> str | None: # NOTE: WIP, might change this in the future... ait = (w for w in self.json['windows'] if w['active']) a = next(ait, None) @@ -74,17 +76,18 @@ class Entry: def entries() -> Iterable[Entry]: inps = list(inputs()) - base: List[PathIsh] = ['arbtt-dump', '--format=json'] + base: list[PathIsh] = ['arbtt-dump', '--format=json'] - cmds: List[List[PathIsh]] + cmds: list[list[PathIsh]] if len(inps) == 0: cmds = [base] # rely on default else: # otherwise, 'merge' them cmds = [[*base, '--logfile', f] for f in inps] - import ijson.backends.yajl2_cffi as ijson # type: ignore - from subprocess import Popen, PIPE + from subprocess import PIPE, Popen + + import ijson.backends.yajl2_cffi as ijson # type: ignore for cmd in cmds: with Popen(cmd, stdout=PIPE) as p: out = p.stdout; assert out is not None @@ -93,8 +96,8 @@ def entries() -> Iterable[Entry]: def fill_influxdb() -> None: - from .core.influxdb import magic_fill from .core.freezer import Freezer + from .core.influxdb import magic_fill freezer = Freezer(Entry) fit = (freezer.freeze(e) for e in entries()) # TODO crap, influxdb doesn't like None https://github.com/influxdata/influxdb/issues/7722 @@ -106,6 +109,8 @@ def fill_influxdb() -> None: magic_fill(fit, name=f'{entries.__module__}:{entries.__name__}') -from .core import stat, Stats +from .core import Stats, stat + + def stats() -> Stats: return stat(entries) diff --git a/my/bluemaestro.py b/my/bluemaestro.py index 4c33fd1..8c739f0 100644 --- a/my/bluemaestro.py +++ b/my/bluemaestro.py @@ -2,14 +2,17 @@ [[https://bluemaestro.com/products/product-details/bluetooth-environmental-monitor-and-logger][Bluemaestro]] temperature/humidity/pressure monitor """ +from __future__ import annotations + # todo most of it belongs to DAL... but considering so few people use it I didn't bother for now import re import sqlite3 from abc import abstractmethod +from collections.abc import Iterable, Sequence from dataclasses import dataclass from datetime import datetime, timedelta from pathlib import Path -from typing import Iterable, Optional, Protocol, Sequence, Set +from typing import Protocol import pytz @@ -87,17 +90,17 @@ def measurements() -> Iterable[Res[Measurement]]: total = len(paths) width = len(str(total)) - last: Optional[datetime] = None + last: datetime | None = None # tables are immutable, so can save on processing.. - processed_tables: Set[str] = set() + processed_tables: set[str] = set() for idx, path in enumerate(paths): logger.info(f'processing [{idx:>{width}}/{total:>{width}}] {path}') tot = 0 new = 0 # todo assert increasing timestamp? with sqlite_connect_immutable(path) as db: - db_dt: Optional[datetime] = None + db_dt: datetime | None = None try: datas = db.execute( f'SELECT "{path.name}" as name, Time, Temperature, Humidity, Pressure, Dewpoint FROM data ORDER BY log_index' diff --git a/my/body/blood.py b/my/body/blood.py index fb035eb..867568c 100644 --- a/my/body/blood.py +++ b/my/body/blood.py @@ -2,41 +2,42 @@ Blood tracking (manual org-mode entries) """ +from __future__ import annotations + +from collections.abc import Iterable from datetime import datetime -from typing import Iterable, NamedTuple, Optional +from typing import NamedTuple -from ..core.error import Res -from ..core.orgmode import parse_org_datetime, one_table - - -import pandas as pd import orgparse - +import pandas as pd from my.config import blood as config # type: ignore[attr-defined] +from ..core.error import Res +from ..core.orgmode import one_table, parse_org_datetime + class Entry(NamedTuple): dt: datetime - ketones : Optional[float]=None - glucose : Optional[float]=None + ketones : float | None=None + glucose : float | None=None - vitamin_d : Optional[float]=None - vitamin_b12 : Optional[float]=None + vitamin_d : float | None=None + vitamin_b12 : float | None=None - hdl : Optional[float]=None - ldl : Optional[float]=None - triglycerides: Optional[float]=None + hdl : float | None=None + ldl : float | None=None + triglycerides: float | None=None - source : Optional[str]=None - extra : Optional[str]=None + source : str | None=None + extra : str | None=None Result = Res[Entry] -def try_float(s: str) -> Optional[float]: +def try_float(s: str) -> float | None: l = s.split() if len(l) == 0: return None @@ -105,6 +106,7 @@ def blood_tests_data() -> Iterable[Result]: def data() -> Iterable[Result]: from itertools import chain + from ..core.error import sort_res_by datas = chain(glucose_ketones_data(), blood_tests_data()) return sort_res_by(datas, key=lambda e: e.dt) diff --git a/my/body/exercise/all.py b/my/body/exercise/all.py index e86a5af..d0df747 100644 --- a/my/body/exercise/all.py +++ b/my/body/exercise/all.py @@ -7,10 +7,10 @@ from ...core.pandas import DataFrameT, check_dataframe @check_dataframe def dataframe() -> DataFrameT: # this should be somehow more flexible... - from ...endomondo import dataframe as EDF - from ...runnerup import dataframe as RDF - import pandas as pd + + from ...endomondo import dataframe as EDF + from ...runnerup import dataframe as RDF return pd.concat([ EDF(), RDF(), diff --git a/my/body/exercise/cardio.py b/my/body/exercise/cardio.py index 083b972..d8a6afd 100644 --- a/my/body/exercise/cardio.py +++ b/my/body/exercise/cardio.py @@ -3,7 +3,6 @@ Cardio data, filtered from various data sources ''' from ...core.pandas import DataFrameT, check_dataframe - CARDIO = { 'Running', 'Running, treadmill', diff --git a/my/body/exercise/cross_trainer.py b/my/body/exercise/cross_trainer.py index edbb557..30f96f9 100644 --- a/my/body/exercise/cross_trainer.py +++ b/my/body/exercise/cross_trainer.py @@ -5,16 +5,18 @@ This is probably too specific to my needs, so later I will move it away to a per For now it's worth keeping it here as an example and perhaps utility functions might be useful for other HPI modules. ''' -from datetime import datetime, timedelta -from typing import Optional +from __future__ import annotations -from ...core.pandas import DataFrameT, check_dataframe as cdf -from ...core.orgmode import collect, Table, parse_org_datetime, TypedTable +from datetime import datetime, timedelta + +import pytz from my.config import exercise as config +from ...core.orgmode import Table, TypedTable, collect, parse_org_datetime +from ...core.pandas import DataFrameT +from ...core.pandas import check_dataframe as cdf -import pytz # FIXME how to attach it properly? tz = pytz.timezone('Europe/London') @@ -114,7 +116,7 @@ def dataframe() -> DataFrameT: rows.append(rd) # presumably has an error set continue - idx: Optional[int] + idx: int | None close = edf[edf['start_time'].apply(lambda t: pd_date_diff(t, mdate)).abs() < _DELTA] if len(close) == 0: idx = None @@ -163,7 +165,9 @@ def dataframe() -> DataFrameT: # TODO wtf?? where is speed coming from?? -from ...core import stat, Stats +from ...core import Stats, stat + + def stats() -> Stats: return stat(cross_trainer_data) diff --git a/my/body/sleep/common.py b/my/body/sleep/common.py index 1100814..fc288e5 100644 --- a/my/body/sleep/common.py +++ b/my/body/sleep/common.py @@ -1,5 +1,6 @@ -from ...core import stat, Stats -from ...core.pandas import DataFrameT, check_dataframe as cdf +from ...core import Stats, stat +from ...core.pandas import DataFrameT +from ...core.pandas import check_dataframe as cdf class Combine: diff --git a/my/body/sleep/main.py b/my/body/sleep/main.py index 29b12a7..2460e03 100644 --- a/my/body/sleep/main.py +++ b/my/body/sleep/main.py @@ -1,7 +1,6 @@ -from ... import jawbone -from ... import emfit - +from ... import emfit, jawbone from .common import Combine + _combined = Combine([ jawbone, emfit, diff --git a/my/body/weight.py b/my/body/weight.py index 51e6513..d5478ef 100644 --- a/my/body/weight.py +++ b/my/body/weight.py @@ -2,14 +2,14 @@ Weight data (manually logged) ''' +from collections.abc import Iterator from dataclasses import dataclass from datetime import datetime -from typing import Any, Iterator - -from my.core import make_logger -from my.core.error import Res, extract_error_datetime, set_error_datetime +from typing import Any from my import orgmode +from my.core import make_logger +from my.core.error import Res, extract_error_datetime, set_error_datetime config = Any diff --git a/my/books/kobo.py b/my/books/kobo.py index 2a469d0..899ef31 100644 --- a/my/books/kobo.py +++ b/my/books/kobo.py @@ -1,7 +1,6 @@ -from ..core import warnings +from my.core import warnings warnings.high('my.books.kobo is deprecated! Please use my.kobo instead!') -from ..core.util import __NOT_HPI_MODULE__ - -from ..kobo import * # type: ignore[no-redef] +from my.core.util import __NOT_HPI_MODULE__ +from my.kobo import * # type: ignore[no-redef] diff --git a/my/browser/active_browser.py b/my/browser/active_browser.py index 6f335bd..8051f1b 100644 --- a/my/browser/active_browser.py +++ b/my/browser/active_browser.py @@ -19,16 +19,18 @@ class config(user_config.active_browser): export_path: Paths +from collections.abc import Iterator, Sequence from pathlib import Path -from typing import Sequence, Iterator -from my.core import get_files, Stats, make_logger -from browserexport.merge import read_visits, Visit +from browserexport.merge import Visit, read_visits from sqlite_backup import sqlite_backup +from my.core import Stats, get_files, make_logger + logger = make_logger(__name__) from .common import _patch_browserexport_logs + _patch_browserexport_logs(logger.level) diff --git a/my/browser/all.py b/my/browser/all.py index a7d12b4..feb973a 100644 --- a/my/browser/all.py +++ b/my/browser/all.py @@ -1,9 +1,9 @@ -from typing import Iterator +from collections.abc import Iterator + +from browserexport.merge import Visit, merge_visits from my.core import Stats from my.core.source import import_source -from browserexport.merge import merge_visits, Visit - src_export = import_source(module_name="my.browser.export") src_active = import_source(module_name="my.browser.active_browser") diff --git a/my/browser/export.py b/my/browser/export.py index 1b428b5..351cf6e 100644 --- a/my/browser/export.py +++ b/my/browser/export.py @@ -4,11 +4,12 @@ Parses browser history using [[http://github.com/seanbreckenridge/browserexport] REQUIRES = ["browserexport"] +from collections.abc import Iterator, Sequence from dataclasses import dataclass from pathlib import Path -from typing import Iterator, Sequence -import my.config +from browserexport.merge import Visit, read_and_merge + from my.core import ( Paths, Stats, @@ -18,10 +19,10 @@ from my.core import ( ) from my.core.cachew import mcachew -from browserexport.merge import read_and_merge, Visit - from .common import _patch_browserexport_logs +import my.config # isort: skip + @dataclass class config(my.config.browser.export): diff --git a/my/bumble/android.py b/my/bumble/android.py index 54a0441..3f9fa13 100644 --- a/my/bumble/android.py +++ b/my/bumble/android.py @@ -3,24 +3,24 @@ Bumble data from Android app database (in =/data/data/com.bumble.app/databases/C """ from __future__ import annotations +from collections.abc import Iterator, Sequence from dataclasses import dataclass from datetime import datetime -from typing import Iterator, Sequence, Optional, Dict +from pathlib import Path from more_itertools import unique_everseen -from my.config import bumble as user_config +from my.core import Paths, get_files + +from my.config import bumble as user_config # isort: skip -from ..core import Paths @dataclass class config(user_config.android): # paths[s]/glob to the exported sqlite databases export_path: Paths -from ..core import get_files -from pathlib import Path def inputs() -> Sequence[Path]: return get_files(config.export_path) @@ -43,22 +43,24 @@ class _BaseMessage: @dataclass(unsafe_hash=True) class _Message(_BaseMessage): conversation_id: str - reply_to_id: Optional[str] + reply_to_id: str | None @dataclass(unsafe_hash=True) class Message(_BaseMessage): person: Person - reply_to: Optional[Message] + reply_to: Message | None import json -from typing import Union -from ..core import Res import sqlite3 -from ..core.sqlite import sqlite_connect_immutable, select +from typing import Union + from my.core.compat import assert_never +from ..core import Res +from ..core.sqlite import select, sqlite_connect_immutable + EntitiesRes = Res[Union[Person, _Message]] def _entities() -> Iterator[EntitiesRes]: @@ -120,8 +122,8 @@ _UNKNOWN_PERSON = "UNKNOWN_PERSON" def messages() -> Iterator[Res[Message]]: - id2person: Dict[str, Person] = {} - id2msg: Dict[str, Message] = {} + id2person: dict[str, Person] = {} + id2msg: dict[str, Message] = {} for x in unique_everseen(_entities(), key=_key): if isinstance(x, Exception): yield x diff --git a/my/calendar/holidays.py b/my/calendar/holidays.py index af51696..522672e 100644 --- a/my/calendar/holidays.py +++ b/my/calendar/holidays.py @@ -15,7 +15,8 @@ from my.core.time import zone_to_countrycode @lru_cache(1) def _calendar(): - from workalendar.registry import registry # type: ignore + from workalendar.registry import registry # type: ignore + # todo switch to using time.tz.main once _get_tz stabilizes? from ..time.tz import via_location as LTZ # TODO would be nice to do it dynamically depending on the past timezones... diff --git a/my/cfg.py b/my/cfg.py index e4020b4..9331e8a 100644 --- a/my/cfg.py +++ b/my/cfg.py @@ -1,7 +1,6 @@ import my.config as config from .core import __NOT_HPI_MODULE__ - from .core import warnings as W # still used in Promnesia, maybe in dashboard? diff --git a/my/codeforces.py b/my/codeforces.py index f2d150a..9c6b7c9 100644 --- a/my/codeforces.py +++ b/my/codeforces.py @@ -1,13 +1,12 @@ +import json +from collections.abc import Iterator, Sequence from dataclasses import dataclass from datetime import datetime, timezone from functools import cached_property -import json from pathlib import Path -from typing import Dict, Iterator, Sequence - -from my.core import get_files, Res, datetime_aware from my.config import codeforces as config # type: ignore[attr-defined] +from my.core import Res, datetime_aware, get_files def inputs() -> Sequence[Path]: @@ -39,7 +38,7 @@ class Competition: class Parser: def __init__(self, *, inputs: Sequence[Path]) -> None: self.inputs = inputs - self.contests: Dict[ContestId, Contest] = {} + self.contests: dict[ContestId, Contest] = {} def _parse_allcontests(self, p: Path) -> Iterator[Contest]: j = json.loads(p.read_text()) diff --git a/my/coding/commits.py b/my/coding/commits.py index 31c366e..fe17dee 100644 --- a/my/coding/commits.py +++ b/my/coding/commits.py @@ -1,29 +1,32 @@ """ Git commits data for repositories on your filesystem """ + +from __future__ import annotations + REQUIRES = [ 'gitpython', ] - import shutil -from pathlib import Path -from datetime import datetime, timezone +from collections.abc import Iterator, Sequence from dataclasses import dataclass, field -from typing import List, Optional, Iterator, Set, Sequence, cast +from datetime import datetime, timezone +from pathlib import Path +from typing import Optional, cast - -from my.core import PathIsh, LazyLogger, make_config +from my.core import LazyLogger, PathIsh, make_config from my.core.cachew import cache_dir, mcachew from my.core.warnings import high +from my.config import commits as user_config # isort: skip + -from my.config import commits as user_config @dataclass class commits_cfg(user_config): roots: Sequence[PathIsh] = field(default_factory=list) - emails: Optional[Sequence[str]] = None - names: Optional[Sequence[str]] = None + emails: Sequence[str] | None = None + names: Sequence[str] | None = None # experiment to make it lazy? @@ -40,7 +43,6 @@ def config() -> commits_cfg: import git from git.repo.fun import is_git_dir - log = LazyLogger(__name__, level='info') @@ -93,7 +95,7 @@ def _git_root(git_dir: PathIsh) -> Path: return gd # must be bare -def _repo_commits_aux(gr: git.Repo, rev: str, emitted: Set[str]) -> Iterator[Commit]: +def _repo_commits_aux(gr: git.Repo, rev: str, emitted: set[str]) -> Iterator[Commit]: # without path might not handle pull heads properly for c in gr.iter_commits(rev=rev): if not by_me(c): @@ -120,7 +122,7 @@ def _repo_commits_aux(gr: git.Repo, rev: str, emitted: Set[str]) -> Iterator[Com def repo_commits(repo: PathIsh): gr = git.Repo(str(repo)) - emitted: Set[str] = set() + emitted: set[str] = set() for r in gr.references: yield from _repo_commits_aux(gr=gr, rev=r.path, emitted=emitted) @@ -141,14 +143,14 @@ def canonical_name(repo: Path) -> str: def _fd_path() -> str: # todo move it to core - fd_path: Optional[str] = shutil.which("fdfind") or shutil.which("fd-find") or shutil.which("fd") + fd_path: str | None = shutil.which("fdfind") or shutil.which("fd-find") or shutil.which("fd") if fd_path is None: high("my.coding.commits requires 'fd' to be installed, See https://github.com/sharkdp/fd#installation") assert fd_path is not None return fd_path -def git_repos_in(roots: List[Path]) -> List[Path]: +def git_repos_in(roots: list[Path]) -> list[Path]: from subprocess import check_output outputs = check_output([ _fd_path(), @@ -172,7 +174,7 @@ def git_repos_in(roots: List[Path]) -> List[Path]: return repos -def repos() -> List[Path]: +def repos() -> list[Path]: return git_repos_in(list(map(Path, config().roots))) @@ -190,7 +192,7 @@ def _repo_depends_on(_repo: Path) -> int: raise RuntimeError(f"Could not find a FETCH_HEAD/HEAD file in {_repo}") -def _commits(_repos: List[Path]) -> Iterator[Commit]: +def _commits(_repos: list[Path]) -> Iterator[Commit]: for r in _repos: yield from _cached_commits(r) diff --git a/my/common.py b/my/common.py index 1b56fb5..22e9487 100644 --- a/my/common.py +++ b/my/common.py @@ -1,6 +1,6 @@ from .core.warnings import high + high("DEPRECATED! Please use my.core.common instead.") from .core import __NOT_HPI_MODULE__ - from .core.common import * diff --git a/my/config.py b/my/config.py index 2dd9cda..301bf49 100644 --- a/my/config.py +++ b/my/config.py @@ -9,17 +9,18 @@ This file is used for: - mypy: this file provides some type annotations - for loading the actual user config ''' + +from __future__ import annotations + #### NOTE: you won't need this line VVVV in your personal config -from my.core import init # noqa: F401 +from my.core import init # noqa: F401 # isort: skip ### from datetime import tzinfo from pathlib import Path -from typing import List - -from my.core import Paths, PathIsh +from my.core import PathIsh, Paths class hypothesis: @@ -75,14 +76,16 @@ class google: takeout_path: Paths = '' -from typing import Sequence, Union, Tuple -from datetime import datetime, date, timedelta +from collections.abc import Sequence +from datetime import date, datetime, timedelta +from typing import Union + DateIsh = Union[datetime, date, str] -LatLon = Tuple[float, float] +LatLon = tuple[float, float] class location: # todo ugh, need to think about it... mypy wants the type here to be general, otherwise it can't deduce # and we can't import the types from the module itself, otherwise would be circular. common module? - home: Union[LatLon, Sequence[Tuple[DateIsh, LatLon]]] = (1.0, -1.0) + home: LatLon | Sequence[tuple[DateIsh, LatLon]] = (1.0, -1.0) home_accuracy = 30_000.0 class via_ip: @@ -103,6 +106,8 @@ class location: from typing import Literal + + class time: class tz: policy: Literal['keep', 'convert', 'throw'] @@ -121,10 +126,9 @@ class arbtt: logfiles: Paths -from typing import Optional class commits: - emails: Optional[Sequence[str]] - names: Optional[Sequence[str]] + emails: Sequence[str] | None + names: Sequence[str] | None roots: Sequence[PathIsh] @@ -150,8 +154,8 @@ class tinder: class instagram: class android: export_path: Paths - username: Optional[str] - full_name: Optional[str] + username: str | None + full_name: str | None class gdpr: export_path: Paths @@ -169,7 +173,7 @@ class materialistic: class fbmessenger: class fbmessengerexport: export_db: PathIsh - facebook_id: Optional[str] + facebook_id: str | None class android: export_path: Paths @@ -247,7 +251,7 @@ class runnerup: class emfit: export_path: Path timezone: tzinfo - excluded_sids: List[str] + excluded_sids: list[str] class foursquare: @@ -270,7 +274,7 @@ class roamresearch: class whatsapp: class android: export_path: Paths - my_user_id: Optional[str] + my_user_id: str | None class harmonic: diff --git a/my/core/_deprecated/kompress.py b/my/core/_deprecated/kompress.py index ce14fad..c3f333f 100644 --- a/my/core/_deprecated/kompress.py +++ b/my/core/_deprecated/kompress.py @@ -11,7 +11,7 @@ from collections.abc import Iterator, Sequence from datetime import datetime from functools import total_ordering from pathlib import Path -from typing import IO, Any, Union +from typing import IO, Union PathIsh = Union[Path, str] diff --git a/my/core/common.py b/my/core/common.py index 91fe9bd..aa994ea 100644 --- a/my/core/common.py +++ b/my/core/common.py @@ -63,7 +63,7 @@ def get_files( if '*' in gs: if glob != DEFAULT_GLOB: warnings.medium(f"{caller()}: treating {gs} as glob path. Explicit glob={glob} argument is ignored!") - paths.extend(map(Path, do_glob(gs))) + paths.extend(map(Path, do_glob(gs))) # noqa: PTH207 elif os.path.isdir(str(src)): # noqa: PTH112 # NOTE: we're using os.path here on purpose instead of src.is_dir # the reason is is_dir for archives might return True and then @@ -157,7 +157,7 @@ def get_valid_filename(s: str) -> str: # TODO deprecate and suggest to use one from my.core directly? not sure -from .utils.itertools import unique_everseen +from .utils.itertools import unique_everseen # noqa: F401 ### legacy imports, keeping them here for backwards compatibility ## hiding behind TYPE_CHECKING so it works in runtime diff --git a/my/demo.py b/my/demo.py index 0c54792..fa80b2a 100644 --- a/my/demo.py +++ b/my/demo.py @@ -1,12 +1,14 @@ ''' Just a demo module for testing and documentation purposes ''' +from __future__ import annotations import json +from collections.abc import Iterable, Sequence from dataclasses import dataclass from datetime import datetime, timezone, tzinfo from pathlib import Path -from typing import Iterable, Optional, Protocol, Sequence +from typing import Protocol from my.core import Json, PathIsh, Paths, get_files @@ -20,7 +22,7 @@ class config(Protocol): # this is to check optional attribute handling timezone: tzinfo = timezone.utc - external: Optional[PathIsh] = None + external: PathIsh | None = None @property def external_module(self): diff --git a/my/emfit/__init__.py b/my/emfit/__init__.py index 9934903..0d50b06 100644 --- a/my/emfit/__init__.py +++ b/my/emfit/__init__.py @@ -4,31 +4,34 @@ Consumes data exported by https://github.com/karlicoss/emfitexport """ +from __future__ import annotations + REQUIRES = [ 'git+https://github.com/karlicoss/emfitexport', ] -from contextlib import contextmanager import dataclasses -from datetime import datetime, time, timedelta import inspect +from collections.abc import Iterable, Iterator +from contextlib import contextmanager +from datetime import datetime, time, timedelta from pathlib import Path -from typing import Any, Dict, Iterable, Iterator, List, Optional - -from my.core import ( - get_files, - stat, - Res, - Stats, -) -from my.core.cachew import cache_dir, mcachew -from my.core.error import set_error_datetime, extract_error_datetime -from my.core.pandas import DataFrameT - -from my.config import emfit as config +from typing import Any import emfitexport.dal as dal +from my.core import ( + Res, + Stats, + get_files, + stat, +) +from my.core.cachew import cache_dir, mcachew +from my.core.error import extract_error_datetime, set_error_datetime +from my.core.pandas import DataFrameT + +from my.config import emfit as config # isort: skip + Emfit = dal.Emfit @@ -85,7 +88,7 @@ def datas() -> Iterable[Res[Emfit]]: # TODO should be used for jawbone data as well? def pre_dataframe() -> Iterable[Res[Emfit]]: # TODO shit. I need some sort of interrupted sleep detection? - g: List[Emfit] = [] + g: list[Emfit] = [] def flush() -> Iterable[Res[Emfit]]: if len(g) == 0: @@ -112,10 +115,10 @@ def pre_dataframe() -> Iterable[Res[Emfit]]: def dataframe() -> DataFrameT: - dicts: List[Dict[str, Any]] = [] - last: Optional[Emfit] = None + dicts: list[dict[str, Any]] = [] + last: Emfit | None = None for s in pre_dataframe(): - d: Dict[str, Any] + d: dict[str, Any] if isinstance(s, Exception): edt = extract_error_datetime(s) d = { @@ -166,11 +169,12 @@ def stats() -> Stats: @contextmanager def fake_data(nights: int = 500) -> Iterator: - from my.core.cfg import tmp_config from tempfile import TemporaryDirectory import pytz + from my.core.cfg import tmp_config + with TemporaryDirectory() as td: tdir = Path(td) gen = dal.FakeData() @@ -187,7 +191,7 @@ def fake_data(nights: int = 500) -> Iterator: # TODO remove/deprecate it? I think used by timeline -def get_datas() -> List[Emfit]: +def get_datas() -> list[Emfit]: # todo ugh. run lint properly return sorted(datas(), key=lambda e: e.start) # type: ignore diff --git a/my/endomondo.py b/my/endomondo.py index 293a542..7732c00 100644 --- a/my/endomondo.py +++ b/my/endomondo.py @@ -7,13 +7,14 @@ REQUIRES = [ ] # todo use ast in setup.py or doctor to extract the corresponding pip packages? +from collections.abc import Iterable, Sequence from dataclasses import dataclass from pathlib import Path -from typing import Sequence, Iterable + +from my.config import endomondo as user_config from .core import Paths, get_files -from my.config import endomondo as user_config @dataclass class endomondo(user_config): @@ -33,15 +34,17 @@ def inputs() -> Sequence[Path]: import endoexport.dal as dal from endoexport.dal import Point, Workout # noqa: F401 - from .core import Res + + # todo cachew? def workouts() -> Iterable[Res[Workout]]: _dal = dal.DAL(inputs()) yield from _dal.workouts() -from .core.pandas import check_dataframe, DataFrameT +from .core.pandas import DataFrameT, check_dataframe + @check_dataframe def dataframe(*, defensive: bool=True) -> DataFrameT: @@ -75,7 +78,9 @@ def dataframe(*, defensive: bool=True) -> DataFrameT: return df -from .core import stat, Stats +from .core import Stats, stat + + def stats() -> Stats: return { # todo pretty print stats? @@ -86,13 +91,16 @@ def stats() -> Stats: # TODO make sure it's possible to 'advise' functions and override stuff +from collections.abc import Iterator from contextlib import contextmanager -from typing import Iterator + + @contextmanager def fake_data(count: int=100) -> Iterator: - from my.core.cfg import tmp_config - from tempfile import TemporaryDirectory import json + from tempfile import TemporaryDirectory + + from my.core.cfg import tmp_config with TemporaryDirectory() as td: tdir = Path(td) fd = dal.FakeData() diff --git a/my/error.py b/my/error.py index c0b734c..e3c1e11 100644 --- a/my/error.py +++ b/my/error.py @@ -1,6 +1,6 @@ from .core.warnings import high + high("DEPRECATED! Please use my.core.error instead.") from .core import __NOT_HPI_MODULE__ - from .core.error import * diff --git a/my/experimental/destructive_parsing.py b/my/experimental/destructive_parsing.py index b389f7e..0c4092a 100644 --- a/my/experimental/destructive_parsing.py +++ b/my/experimental/destructive_parsing.py @@ -1,5 +1,6 @@ +from collections.abc import Iterator from dataclasses import dataclass -from typing import Any, Iterator, List, Tuple +from typing import Any from my.core.compat import NoneType, assert_never @@ -9,7 +10,7 @@ from my.core.compat import NoneType, assert_never class Helper: manager: 'Manager' item: Any # todo realistically, list or dict? could at least type as indexable or something - path: Tuple[str, ...] + path: tuple[str, ...] def pop_if_primitive(self, *keys: str) -> None: """ @@ -40,9 +41,9 @@ def is_empty(x) -> bool: class Manager: def __init__(self) -> None: - self.helpers: List[Helper] = [] + self.helpers: list[Helper] = [] - def helper(self, item: Any, *, path: Tuple[str, ...] = ()) -> Helper: + def helper(self, item: Any, *, path: tuple[str, ...] = ()) -> Helper: res = Helper(manager=self, item=item, path=path) self.helpers.append(res) return res diff --git a/my/fbmessenger/__init__.py b/my/fbmessenger/__init__.py index 40fb235..f729de9 100644 --- a/my/fbmessenger/__init__.py +++ b/my/fbmessenger/__init__.py @@ -20,6 +20,7 @@ REQUIRES = [ from my.core.hpi_compat import handle_legacy_import + is_legacy_import = handle_legacy_import( parent_module_name=__name__, legacy_submodule_name='export', diff --git a/my/fbmessenger/all.py b/my/fbmessenger/all.py index 13689db..a057dca 100644 --- a/my/fbmessenger/all.py +++ b/my/fbmessenger/all.py @@ -1,10 +1,10 @@ -from typing import Iterator -from my.core import Res, stat, Stats +from collections.abc import Iterator + +from my.core import Res, Stats from my.core.source import import_source from .common import Message, _merge_messages - src_export = import_source(module_name='my.fbmessenger.export') src_android = import_source(module_name='my.fbmessenger.android') diff --git a/my/fbmessenger/android.py b/my/fbmessenger/android.py index effabab..a16d924 100644 --- a/my/fbmessenger/android.py +++ b/my/fbmessenger/android.py @@ -4,19 +4,20 @@ Messenger data from Android app database (in =/data/data/com.facebook.orca/datab from __future__ import annotations +import sqlite3 +from collections.abc import Iterator, Sequence from dataclasses import dataclass from datetime import datetime, timezone from pathlib import Path -import sqlite3 -from typing import Iterator, Sequence, Optional, Dict, Union, List +from typing import Union -from my.core import get_files, Paths, datetime_aware, Res, LazyLogger, make_config +from my.core import LazyLogger, Paths, Res, datetime_aware, get_files, make_config from my.core.common import unique_everseen from my.core.compat import assert_never from my.core.error import echain from my.core.sqlite import sqlite_connection -from my.config import fbmessenger as user_config +from my.config import fbmessenger as user_config # isort: skip logger = LazyLogger(__name__) @@ -27,7 +28,7 @@ class Config(user_config.android): # paths[s]/glob to the exported sqlite databases export_path: Paths - facebook_id: Optional[str] = None + facebook_id: str | None = None # hmm. this is necessary for default value (= None) to work @@ -42,13 +43,13 @@ def inputs() -> Sequence[Path]: @dataclass(unsafe_hash=True) class Sender: id: str - name: Optional[str] + name: str | None @dataclass(unsafe_hash=True) class Thread: id: str - name: Optional[str] # isn't set for groups or one to one messages + name: str | None # isn't set for groups or one to one messages # todo not sure about order of fields... @@ -56,14 +57,14 @@ class Thread: class _BaseMessage: id: str dt: datetime_aware - text: Optional[str] + text: str | None @dataclass(unsafe_hash=True) class _Message(_BaseMessage): thread_id: str sender_id: str - reply_to_id: Optional[str] + reply_to_id: str | None # todo hmm, on the one hand would be kinda nice to inherit common.Message protocol here @@ -72,7 +73,7 @@ class _Message(_BaseMessage): class Message(_BaseMessage): thread: Thread sender: Sender - reply_to: Optional[Message] + reply_to: Message | None Entity = Union[Sender, Thread, _Message] @@ -110,7 +111,7 @@ def _normalise_thread_id(key) -> str: # NOTE: this is sort of copy pasted from other _process_db method # maybe later could unify them def _process_db_msys(db: sqlite3.Connection) -> Iterator[Res[Entity]]: - senders: Dict[str, Sender] = {} + senders: dict[str, Sender] = {} for r in db.execute('SELECT CAST(id AS TEXT) AS id, name FROM contacts'): s = Sender( id=r['id'], # looks like it's server id? same used on facebook site @@ -127,7 +128,7 @@ def _process_db_msys(db: sqlite3.Connection) -> Iterator[Res[Entity]]: # TODO can we get it from db? could infer as the most common id perhaps? self_id = config.facebook_id - thread_users: Dict[str, List[Sender]] = {} + thread_users: dict[str, list[Sender]] = {} for r in db.execute('SELECT CAST(thread_key AS TEXT) AS thread_key, CAST(contact_id AS TEXT) AS contact_id FROM participants'): thread_key = r['thread_key'] user_key = r['contact_id'] @@ -193,7 +194,7 @@ def _process_db_msys(db: sqlite3.Connection) -> Iterator[Res[Entity]]: def _process_db_threads_db2(db: sqlite3.Connection) -> Iterator[Res[Entity]]: - senders: Dict[str, Sender] = {} + senders: dict[str, Sender] = {} for r in db.execute('''SELECT * FROM thread_users'''): # for messaging_actor_type == 'REDUCED_MESSAGING_ACTOR', name is None # but they are still referenced, so need to keep @@ -207,7 +208,7 @@ def _process_db_threads_db2(db: sqlite3.Connection) -> Iterator[Res[Entity]]: yield s self_id = config.facebook_id - thread_users: Dict[str, List[Sender]] = {} + thread_users: dict[str, list[Sender]] = {} for r in db.execute('SELECT * from thread_participants'): thread_key = r['thread_key'] user_key = r['user_key'] @@ -267,9 +268,9 @@ def contacts() -> Iterator[Res[Sender]]: def messages() -> Iterator[Res[Message]]: - senders: Dict[str, Sender] = {} - msgs: Dict[str, Message] = {} - threads: Dict[str, Thread] = {} + senders: dict[str, Sender] = {} + msgs: dict[str, Message] = {} + threads: dict[str, Thread] = {} for x in unique_everseen(_entities): if isinstance(x, Exception): yield x diff --git a/my/fbmessenger/common.py b/my/fbmessenger/common.py index 33d1b20..0f5a374 100644 --- a/my/fbmessenger/common.py +++ b/my/fbmessenger/common.py @@ -1,6 +1,9 @@ -from my.core import __NOT_HPI_MODULE__ +from __future__ import annotations -from typing import Iterator, Optional, Protocol +from my.core import __NOT_HPI_MODULE__ # isort: skip + +from collections.abc import Iterator +from typing import Protocol from my.core import datetime_aware @@ -10,7 +13,7 @@ class Thread(Protocol): def id(self) -> str: ... @property - def name(self) -> Optional[str]: ... + def name(self) -> str | None: ... class Sender(Protocol): @@ -18,7 +21,7 @@ class Sender(Protocol): def id(self) -> str: ... @property - def name(self) -> Optional[str]: ... + def name(self) -> str | None: ... class Message(Protocol): @@ -29,7 +32,7 @@ class Message(Protocol): def dt(self) -> datetime_aware: ... @property - def text(self) -> Optional[str]: ... + def text(self) -> str | None: ... @property def thread(self) -> Thread: ... @@ -39,8 +42,11 @@ class Message(Protocol): from itertools import chain + from more_itertools import unique_everseen -from my.core import warn_if_empty, Res + +from my.core import Res, warn_if_empty + @warn_if_empty def _merge_messages(*sources: Iterator[Res[Message]]) -> Iterator[Res[Message]]: diff --git a/my/fbmessenger/export.py b/my/fbmessenger/export.py index 201fad8..3b06618 100644 --- a/my/fbmessenger/export.py +++ b/my/fbmessenger/export.py @@ -7,16 +7,15 @@ REQUIRES = [ 'git+https://github.com/karlicoss/fbmessengerexport', ] +from collections.abc import Iterator from contextlib import ExitStack, contextmanager from dataclasses import dataclass -from typing import Iterator - -from my.core import PathIsh, Res, stat, Stats -from my.core.warnings import high -from my.config import fbmessenger as user_config import fbmessengerexport.dal as messenger +from my.config import fbmessenger as user_config +from my.core import PathIsh, Res, Stats, stat +from my.core.warnings import high ### # support old style config diff --git a/my/foursquare.py b/my/foursquare.py index 394fdf3..3b418aa 100644 --- a/my/foursquare.py +++ b/my/foursquare.py @@ -2,15 +2,14 @@ Foursquare/Swarm checkins ''' -from datetime import datetime, timezone, timedelta -from itertools import chain import json +from datetime import datetime, timedelta, timezone +from itertools import chain -# TODO pytz for timezone??? - -from my.core import get_files, make_logger from my.config import foursquare as config +# TODO pytz for timezone??? +from my.core import get_files, make_logger logger = make_logger(__name__) diff --git a/my/github/all.py b/my/github/all.py index f885dde..f5e13cf 100644 --- a/my/github/all.py +++ b/my/github/all.py @@ -3,8 +3,7 @@ Unified Github data (merged from GDPR export and periodic API updates) """ from . import gdpr, ghexport - -from .common import merge_events, Results +from .common import Results, merge_events def events() -> Results: diff --git a/my/github/common.py b/my/github/common.py index e54bc4d..22ba47e 100644 --- a/my/github/common.py +++ b/my/github/common.py @@ -1,24 +1,27 @@ """ Github events and their metadata: comments/issues/pull requests """ -from ..core import __NOT_HPI_MODULE__ + +from __future__ import annotations + +from my.core import __NOT_HPI_MODULE__ # isort: skip +from collections.abc import Iterable from datetime import datetime, timezone -from typing import Optional, NamedTuple, Iterable, Set, Tuple +from typing import NamedTuple, Optional -from ..core import warn_if_empty, LazyLogger -from ..core.error import Res +from my.core import make_logger, warn_if_empty +from my.core.error import Res - -logger = LazyLogger(__name__) +logger = make_logger(__name__) class Event(NamedTuple): dt: datetime summary: str eid: str link: Optional[str] - body: Optional[str]=None + body: Optional[str] = None is_bot: bool = False @@ -27,7 +30,7 @@ Results = Iterable[Res[Event]] @warn_if_empty def merge_events(*sources: Results) -> Results: from itertools import chain - emitted: Set[Tuple[datetime, str]] = set() + emitted: set[tuple[datetime, str]] = set() for e in chain(*sources): if isinstance(e, Exception): yield e @@ -52,7 +55,7 @@ def parse_dt(s: str) -> datetime: # experimental way of supportint event ids... not sure class EventIds: @staticmethod - def repo_created(*, dts: str, name: str, ref_type: str, ref: Optional[str]) -> str: + def repo_created(*, dts: str, name: str, ref_type: str, ref: str | None) -> str: return f'{dts}_repocreated_{name}_{ref_type}_{ref}' @staticmethod diff --git a/my/github/gdpr.py b/my/github/gdpr.py index a56ff46..be56454 100644 --- a/my/github/gdpr.py +++ b/my/github/gdpr.py @@ -6,8 +6,9 @@ from __future__ import annotations import json from abc import abstractmethod +from collections.abc import Iterator, Sequence from pathlib import Path -from typing import Any, Iterator, Sequence +from typing import Any from my.core import Paths, Res, Stats, get_files, make_logger, stat, warnings from my.core.error import echain diff --git a/my/github/ghexport.py b/my/github/ghexport.py index 80106a5..3e17c10 100644 --- a/my/github/ghexport.py +++ b/my/github/ghexport.py @@ -1,13 +1,17 @@ """ Github data: events, comments, etc. (API data) """ + +from __future__ import annotations + REQUIRES = [ 'git+https://github.com/karlicoss/ghexport', ] + from dataclasses import dataclass -from my.core import Paths from my.config import github as user_config +from my.core import Paths @dataclass @@ -21,7 +25,9 @@ class github(user_config): ### -from my.core.cfg import make_config, Attrs +from my.core.cfg import Attrs, make_config + + def migration(attrs: Attrs) -> Attrs: export_dir = 'export_dir' if export_dir in attrs: # legacy name @@ -41,15 +47,14 @@ except ModuleNotFoundError as e: ############################ +from collections.abc import Sequence from functools import lru_cache from pathlib import Path -from typing import Tuple, Dict, Sequence, Optional -from my.core import get_files, LazyLogger +from my.core import LazyLogger, get_files from my.core.cachew import mcachew -from .common import Event, parse_dt, Results, EventIds - +from .common import Event, EventIds, Results, parse_dt logger = LazyLogger(__name__) @@ -82,7 +87,9 @@ def _events() -> Results: yield e -from my.core import stat, Stats +from my.core import Stats, stat + + def stats() -> Stats: return { **stat(events), @@ -99,7 +106,7 @@ def _log_if_unhandled(e) -> None: Link = str EventId = str Body = str -def _get_summary(e) -> Tuple[str, Optional[Link], Optional[EventId], Optional[Body]]: +def _get_summary(e) -> tuple[str, Link | None, EventId | None, Body | None]: # TODO would be nice to give access to raw event within timeline dts = e['created_at'] eid = e['id'] @@ -195,7 +202,7 @@ def _get_summary(e) -> Tuple[str, Optional[Link], Optional[EventId], Optional[Bo return tp, None, None, None -def _parse_event(d: Dict) -> Event: +def _parse_event(d: dict) -> Event: summary, link, eid, body = _get_summary(d) if eid is None: eid = d['id'] # meh diff --git a/my/goodreads.py b/my/goodreads.py index 864bd64..559efda 100644 --- a/my/goodreads.py +++ b/my/goodreads.py @@ -7,15 +7,18 @@ REQUIRES = [ from dataclasses import dataclass -from my.core import datetime_aware, Paths + from my.config import goodreads as user_config +from my.core import Paths, datetime_aware + @dataclass class goodreads(user_config): # paths[s]/glob to the exported JSON data export_path: Paths -from my.core.cfg import make_config, Attrs +from my.core.cfg import Attrs, make_config + def _migration(attrs: Attrs) -> Attrs: export_dir = 'export_dir' @@ -29,18 +32,19 @@ config = make_config(goodreads, migration=_migration) #############################3 -from my.core import get_files -from typing import Sequence, Iterator +from collections.abc import Iterator, Sequence from pathlib import Path +from my.core import get_files + + def inputs() -> Sequence[Path]: return get_files(config.export_path) from datetime import datetime + import pytz - - from goodrexport import dal diff --git a/my/google/maps/_android_protobuf.py b/my/google/maps/_android_protobuf.py index 1d43ae0..615623d 100644 --- a/my/google/maps/_android_protobuf.py +++ b/my/google/maps/_android_protobuf.py @@ -1,8 +1,8 @@ -from my.core import __NOT_HPI_MODULE__ +from my.core import __NOT_HPI_MODULE__ # isort: skip # NOTE: this tool was quite useful https://github.com/aj3423/aproto -from google.protobuf import descriptor_pool, descriptor_pb2, message_factory +from google.protobuf import descriptor_pb2, descriptor_pool, message_factory TYPE_STRING = descriptor_pb2.FieldDescriptorProto.TYPE_STRING TYPE_BYTES = descriptor_pb2.FieldDescriptorProto.TYPE_BYTES diff --git a/my/google/maps/android.py b/my/google/maps/android.py index 279231a..95ecacf 100644 --- a/my/google/maps/android.py +++ b/my/google/maps/android.py @@ -7,20 +7,20 @@ REQUIRES = [ "protobuf", # for parsing blobs from the database ] +from collections.abc import Iterator, Sequence from dataclasses import dataclass from datetime import datetime, timezone from pathlib import Path -from typing import Any, Iterator, Optional, Sequence +from typing import Any from urllib.parse import quote -from my.core import datetime_aware, get_files, LazyLogger, Paths, Res +from my.core import LazyLogger, Paths, Res, datetime_aware, get_files from my.core.common import unique_everseen from my.core.sqlite import sqlite_connection -import my.config - from ._android_protobuf import parse_labeled, parse_list, parse_place +import my.config # isort: skip logger = LazyLogger(__name__) @@ -59,8 +59,8 @@ class Place: updated_at: datetime_aware # TODO double check it's utc? title: str location: Location - address: Optional[str] - note: Optional[str] + address: str | None + note: str | None @property def place_url(self) -> str: diff --git a/my/google/takeout/html.py b/my/google/takeout/html.py index 750beac..3f2b5db 100644 --- a/my/google/takeout/html.py +++ b/my/google/takeout/html.py @@ -2,18 +2,22 @@ Google Takeout exports: browsing history, search/youtube/google play activity ''' -from enum import Enum +from __future__ import annotations + +from my.core import __NOT_HPI_MODULE__ # isort: skip + import re -from pathlib import Path +from collections.abc import Iterable from datetime import datetime +from enum import Enum from html.parser import HTMLParser -from typing import List, Optional, Any, Callable, Iterable, Tuple +from pathlib import Path +from typing import Any, Callable from urllib.parse import unquote import pytz -from ...core.time import abbr_to_timezone - +from my.core.time import abbr_to_timezone # NOTE: https://bugs.python.org/issue22377 %Z doesn't work properly _TIME_FORMATS = [ @@ -36,7 +40,7 @@ def parse_dt(s: str) -> datetime: s, tzabbr = s.rsplit(maxsplit=1) tz = abbr_to_timezone(tzabbr) - dt: Optional[datetime] = None + dt: datetime | None = None for fmt in _TIME_FORMATS: try: dt = datetime.strptime(s, fmt) @@ -73,7 +77,7 @@ class State(Enum): Url = str Title = str -Parsed = Tuple[datetime, Url, Title] +Parsed = tuple[datetime, Url, Title] Callback = Callable[[datetime, Url, Title], None] @@ -83,9 +87,9 @@ class TakeoutHTMLParser(HTMLParser): super().__init__() self.state: State = State.OUTSIDE - self.title_parts: List[str] = [] - self.title: Optional[str] = None - self.url: Optional[str] = None + self.title_parts: list[str] = [] + self.title: str | None = None + self.url: str | None = None self.callback = callback @@ -148,7 +152,7 @@ class TakeoutHTMLParser(HTMLParser): def read_html(tpath: Path, file: str) -> Iterable[Parsed]: - results: List[Parsed] = [] + results: list[Parsed] = [] def cb(dt: datetime, url: Url, title: Title) -> None: results.append((dt, url, title)) parser = TakeoutHTMLParser(callback=cb) @@ -156,5 +160,3 @@ def read_html(tpath: Path, file: str) -> Iterable[Parsed]: data = fo.read() parser.feed(data) return results - -from ...core import __NOT_HPI_MODULE__ diff --git a/my/google/takeout/parser.py b/my/google/takeout/parser.py index 170553a..80c2be1 100644 --- a/my/google/takeout/parser.py +++ b/my/google/takeout/parser.py @@ -14,24 +14,27 @@ the cachew cache REQUIRES = ["git+https://github.com/seanbreckenridge/google_takeout_parser"] +import os +from collections.abc import Sequence from contextlib import ExitStack from dataclasses import dataclass -import os -from typing import List, Sequence, cast from pathlib import Path -from my.core import make_config, stat, Stats, get_files, Paths, make_logger +from typing import cast + +from google_takeout_parser.parse_html.html_time_utils import ABBR_TIMEZONES + +from my.core import Paths, Stats, get_files, make_config, make_logger, stat from my.core.cachew import mcachew from my.core.error import ErrorPolicy from my.core.structure import match_structure - from my.core.time import user_forced -from google_takeout_parser.parse_html.html_time_utils import ABBR_TIMEZONES + ABBR_TIMEZONES.extend(user_forced()) import google_takeout_parser -from google_takeout_parser.path_dispatch import TakeoutParser -from google_takeout_parser.merge import GoogleEventSet, CacheResults +from google_takeout_parser.merge import CacheResults, GoogleEventSet from google_takeout_parser.models import BaseEvent +from google_takeout_parser.path_dispatch import TakeoutParser # see https://github.com/seanbreckenridge/dotfiles/blob/master/.config/my/my/config/__init__.py for an example from my.config import google as user_config @@ -56,6 +59,7 @@ logger = make_logger(__name__, level="warning") # patch the takeout parser logger to match the computed loglevel from google_takeout_parser.log import setup as setup_takeout_logger + setup_takeout_logger(logger.level) @@ -83,7 +87,7 @@ except ImportError: google_takeout_version = str(getattr(google_takeout_parser, '__version__', 'unknown')) -def _cachew_depends_on() -> List[str]: +def _cachew_depends_on() -> list[str]: exports = sorted([str(p) for p in inputs()]) # add google takeout parser pip version to hash, so this re-creates on breaking changes exports.insert(0, f"google_takeout_version: {google_takeout_version}") diff --git a/my/google/takeout/paths.py b/my/google/takeout/paths.py index 948cf2e..6a523e2 100644 --- a/my/google/takeout/paths.py +++ b/my/google/takeout/paths.py @@ -2,13 +2,17 @@ Module for locating and accessing [[https://takeout.google.com][Google Takeout]] data ''' +from __future__ import annotations + +from my.core import __NOT_HPI_MODULE__ # isort: skip + from abc import abstractmethod +from collections.abc import Iterable from pathlib import Path -from typing import Iterable, Optional, Protocol from more_itertools import last -from my.core import __NOT_HPI_MODULE__, Paths, get_files +from my.core import Paths, get_files class config: @@ -33,7 +37,7 @@ def make_config() -> config: return combined_config() -def get_takeouts(*, path: Optional[str] = None) -> Iterable[Path]: +def get_takeouts(*, path: str | None = None) -> Iterable[Path]: """ Sometimes google splits takeout into multiple archives, so we need to detect the ones that contain the path we need """ @@ -45,7 +49,7 @@ def get_takeouts(*, path: Optional[str] = None) -> Iterable[Path]: yield takeout -def get_last_takeout(*, path: Optional[str] = None) -> Optional[Path]: +def get_last_takeout(*, path: str | None = None) -> Path | None: return last(get_takeouts(path=path), default=None) diff --git a/my/hackernews/dogsheep.py b/my/hackernews/dogsheep.py index de6c58d..8303284 100644 --- a/my/hackernews/dogsheep.py +++ b/my/hackernews/dogsheep.py @@ -3,14 +3,14 @@ Hackernews data via Dogsheep [[hacker-news-to-sqlite][https://github.com/dogshee """ from __future__ import annotations +from collections.abc import Iterator, Sequence from dataclasses import dataclass from datetime import datetime, timezone from pathlib import Path -from typing import Iterator, Sequence, Optional -from my.core import get_files, Paths, Res, datetime_aware -from my.core.sqlite import sqlite_connection import my.config +from my.core import Paths, Res, datetime_aware, get_files +from my.core.sqlite import sqlite_connection from .common import hackernews_link @@ -33,9 +33,9 @@ class Item: id: str type: str created: datetime_aware # checked and it's utc - title: Optional[str] # only present for Story - text_html: Optional[str] # should be present for Comment and might for Story - url: Optional[str] # might be present for Story + title: str | None # only present for Story + text_html: str | None # should be present for Comment and might for Story + url: str | None # might be present for Story # todo process 'deleted'? fields? # todo process 'parent'? diff --git a/my/hackernews/harmonic.py b/my/hackernews/harmonic.py index 3b4ae61..08a82e6 100644 --- a/my/hackernews/harmonic.py +++ b/my/hackernews/harmonic.py @@ -1,17 +1,22 @@ """ [[https://play.google.com/store/apps/details?id=com.simon.harmonichackernews][Harmonic]] app for Hackernews """ + +from __future__ import annotations + REQUIRES = ['lxml', 'orjson'] +from collections.abc import Iterator, Sequence from dataclasses import dataclass from datetime import datetime, timezone -import orjson from pathlib import Path -from typing import Any, Dict, Iterator, List, Optional, Sequence, TypedDict, cast +from typing import Any, TypedDict, cast +import orjson from lxml import etree from more_itertools import one +import my.config from my.core import ( Paths, Res, @@ -22,8 +27,10 @@ from my.core import ( stat, ) from my.core.common import unique_everseen -import my.config -from .common import hackernews_link, SavedBase + +from .common import SavedBase, hackernews_link + +import my.config # isort: skip logger = make_logger(__name__) @@ -43,7 +50,7 @@ class Cached(TypedDict): created_at_i: int id: str points: int - test: Optional[str] + test: str | None title: str type: str # TODO Literal['story', 'comment']? comments are only in 'children' field tho url: str @@ -94,16 +101,16 @@ def _saved() -> Iterator[Res[Saved]]: # TODO defensive for each item! tr = etree.parse(path) - res = one(cast(List[Any], tr.xpath(f'//*[@name="{_PREFIX}_CACHED_STORIES_STRINGS"]'))) + res = one(cast(list[Any], tr.xpath(f'//*[@name="{_PREFIX}_CACHED_STORIES_STRINGS"]'))) cached_ids = [x.text.split('-')[0] for x in res] - cached: Dict[str, Cached] = {} + cached: dict[str, Cached] = {} for sid in cached_ids: - res = one(cast(List[Any], tr.xpath(f'//*[@name="{_PREFIX}_CACHED_STORY{sid}"]'))) + res = one(cast(list[Any], tr.xpath(f'//*[@name="{_PREFIX}_CACHED_STORY{sid}"]'))) j = orjson.loads(res.text) cached[sid] = j - res = one(cast(List[Any], tr.xpath(f'//*[@name="{_PREFIX}_BOOKMARKS"]'))) + res = one(cast(list[Any], tr.xpath(f'//*[@name="{_PREFIX}_BOOKMARKS"]'))) for x in res.text.split('-'): ids, item_timestamp = x.split('q') # not sure if timestamp is any useful? diff --git a/my/hackernews/materialistic.py b/my/hackernews/materialistic.py index 4d5cd47..ccf285b 100644 --- a/my/hackernews/materialistic.py +++ b/my/hackernews/materialistic.py @@ -1,19 +1,20 @@ """ [[https://play.google.com/store/apps/details?id=io.github.hidroh.materialistic][Materialistic]] app for Hackernews """ +from collections.abc import Iterator, Sequence from datetime import datetime, timezone from pathlib import Path -from typing import Any, Dict, Iterator, NamedTuple, Sequence +from typing import Any, NamedTuple from more_itertools import unique_everseen -from my.core import get_files, datetime_aware, make_logger +from my.core import datetime_aware, get_files, make_logger from my.core.sqlite import sqlite_connection -from my.config import materialistic as config # todo migrate config to my.hackernews.materialistic - from .common import hackernews_link +# todo migrate config to my.hackernews.materialistic +from my.config import materialistic as config # isort: skip logger = make_logger(__name__) @@ -22,7 +23,7 @@ def inputs() -> Sequence[Path]: return get_files(config.export_path) -Row = Dict[str, Any] +Row = dict[str, Any] class Saved(NamedTuple): diff --git a/my/hypothesis.py b/my/hypothesis.py index 82104cd..15e854b 100644 --- a/my/hypothesis.py +++ b/my/hypothesis.py @@ -4,20 +4,22 @@ REQUIRES = [ 'git+https://github.com/karlicoss/hypexport', ] +from collections.abc import Iterator, Sequence from dataclasses import dataclass from pathlib import Path -from typing import Iterator, Sequence, TYPE_CHECKING +from typing import TYPE_CHECKING from my.core import ( - get_files, - stat, Paths, Res, Stats, + get_files, + stat, ) from my.core.cfg import make_config from my.core.hpi_compat import always_supports_sequence -import my.config + +import my.config # isort: skip @dataclass diff --git a/my/instagram/all.py b/my/instagram/all.py index 8007399..214e6ac 100644 --- a/my/instagram/all.py +++ b/my/instagram/all.py @@ -1,11 +1,10 @@ -from typing import Iterator +from collections.abc import Iterator -from my.core import Res, stat, Stats +from my.core import Res, Stats, stat from my.core.source import import_source from .common import Message, _merge_messages - src_gdpr = import_source(module_name='my.instagram.gdpr') @src_gdpr def _messages_gdpr() -> Iterator[Res[Message]]: diff --git a/my/instagram/android.py b/my/instagram/android.py index 96b75d2..12c11d3 100644 --- a/my/instagram/android.py +++ b/my/instagram/android.py @@ -3,30 +3,29 @@ Bumble data from Android app database (in =/data/data/com.instagram.android/data """ from __future__ import annotations +import json +import sqlite3 +from collections.abc import Iterator, Sequence from dataclasses import dataclass from datetime import datetime -import json from pathlib import Path -import sqlite3 -from typing import Iterator, Sequence, Optional, Dict, Union from my.core import ( - get_files, - Paths, - make_config, - make_logger, - datetime_naive, Json, + Paths, Res, assert_never, + datetime_naive, + get_files, + make_config, + make_logger, ) -from my.core.common import unique_everseen from my.core.cachew import mcachew +from my.core.common import unique_everseen from my.core.error import echain -from my.core.sqlite import sqlite_connect_immutable, select - -from my.config import instagram as user_config +from my.core.sqlite import select, sqlite_connect_immutable +from my.config import instagram as user_config # isort: skip logger = make_logger(__name__) @@ -38,8 +37,8 @@ class instagram_android_config(user_config.android): # sadly doesn't seem easy to extract user's own handle/name from the db... # todo maybe makes more sense to keep in parent class? not sure... - username: Optional[str] = None - full_name: Optional[str] = None + username: str | None = None + full_name: str | None = None config = make_config(instagram_android_config) @@ -101,13 +100,13 @@ class MessageError(RuntimeError): return self.rest == other.rest -def _parse_message(j: Json) -> Optional[_Message]: +def _parse_message(j: Json) -> _Message | None: id = j['item_id'] t = j['item_type'] tid = j['thread_key']['thread_id'] uid = j['user_id'] created = datetime.fromtimestamp(int(j['timestamp']) / 1_000_000) - text: Optional[str] = None + text: str | None = None if t == 'text': text = j['text'] elif t == 'reel_share': @@ -133,7 +132,7 @@ def _parse_message(j: Json) -> Optional[_Message]: ) -def _process_db(db: sqlite3.Connection) -> Iterator[Res[Union[User, _Message]]]: +def _process_db(db: sqlite3.Connection) -> Iterator[Res[User | _Message]]: # TODO ugh. seems like no way to extract username? # sometimes messages (e.g. media_share) contain it in message field # but generally it's not present. ugh @@ -175,7 +174,7 @@ def _process_db(db: sqlite3.Connection) -> Iterator[Res[Union[User, _Message]]]: yield e -def _entities() -> Iterator[Res[Union[User, _Message]]]: +def _entities() -> Iterator[Res[User | _Message]]: # NOTE: definitely need to merge multiple, app seems to recycle old messages # TODO: hmm hard to guarantee timestamp ordering when we use synthetic input data... # todo use TypedDict? @@ -194,7 +193,7 @@ def _entities() -> Iterator[Res[Union[User, _Message]]]: @mcachew(depends_on=inputs) def messages() -> Iterator[Res[Message]]: - id2user: Dict[str, User] = {} + id2user: dict[str, User] = {} for x in unique_everseen(_entities): if isinstance(x, Exception): yield x diff --git a/my/instagram/common.py b/my/instagram/common.py index 4df07a1..17d130f 100644 --- a/my/instagram/common.py +++ b/my/instagram/common.py @@ -1,9 +1,10 @@ +from collections.abc import Iterator from dataclasses import replace from datetime import datetime from itertools import chain -from typing import Iterator, Dict, Any, Protocol +from typing import Any, Protocol -from my.core import warn_if_empty, Res +from my.core import Res, warn_if_empty class User(Protocol): @@ -40,7 +41,7 @@ def _merge_messages(*sources: Iterator[Res[Message]]) -> Iterator[Res[Message]]: # ugh. seems that GDPR thread ids are completely uncorrelated to any android ids (tried searching over all sqlite dump) # so the only way to correlate is to try and match messages # we also can't use unique_everseen here, otherwise will never get a chance to unify threads - mmap: Dict[str, Message] = {} + mmap: dict[str, Message] = {} thread_map = {} user_map = {} @@ -60,7 +61,7 @@ def _merge_messages(*sources: Iterator[Res[Message]]) -> Iterator[Res[Message]]: user_map[m.user.id] = mm.user else: # not emitted yet, need to emit - repls: Dict[str, Any] = {} + repls: dict[str, Any] = {} tid = thread_map.get(m.thread_id) if tid is not None: repls['thread_id'] = tid diff --git a/my/instagram/gdpr.py b/my/instagram/gdpr.py index 1415d55..7454a04 100644 --- a/my/instagram/gdpr.py +++ b/my/instagram/gdpr.py @@ -2,26 +2,27 @@ Instagram data (uses [[https://www.instagram.com/download/request][official GDPR export]]) """ +from __future__ import annotations + +import json +from collections.abc import Iterator, Sequence from dataclasses import dataclass from datetime import datetime -import json from pathlib import Path -from typing import Iterator, Sequence, Dict, Union from more_itertools import bucket from my.core import ( - get_files, Paths, - datetime_naive, Res, assert_never, + datetime_naive, + get_files, make_logger, ) from my.core.common import unique_everseen -from my.config import instagram as user_config - +from my.config import instagram as user_config # isort: skip logger = make_logger(__name__) @@ -70,7 +71,7 @@ def _decode(s: str) -> str: return s.encode('latin-1').decode('utf8') -def _entities() -> Iterator[Res[Union[User, _Message]]]: +def _entities() -> Iterator[Res[User | _Message]]: # it's worth processing all previous export -- sometimes instagram removes some metadata from newer ones # NOTE: here there are basically two options # - process inputs as is (from oldest to newest) @@ -84,7 +85,7 @@ def _entities() -> Iterator[Res[Union[User, _Message]]]: yield from _entitites_from_path(path) -def _entitites_from_path(path: Path) -> Iterator[Res[Union[User, _Message]]]: +def _entitites_from_path(path: Path) -> Iterator[Res[User | _Message]]: # TODO make sure it works both with plan directory # idelaly get_files should return the right thing, and we won't have to force ZipPath/match_structure here # e.g. possible options are: @@ -202,7 +203,7 @@ def _entitites_from_path(path: Path) -> Iterator[Res[Union[User, _Message]]]: # TODO basically copy pasted from android.py... hmm def messages() -> Iterator[Res[Message]]: - id2user: Dict[str, User] = {} + id2user: dict[str, User] = {} for x in unique_everseen(_entities): if isinstance(x, Exception): yield x diff --git a/my/instapaper.py b/my/instapaper.py index df1f70b..d79e7e4 100644 --- a/my/instapaper.py +++ b/my/instapaper.py @@ -7,10 +7,10 @@ REQUIRES = [ from dataclasses import dataclass -from .core import Paths - from my.config import instapaper as user_config +from .core import Paths + @dataclass class instapaper(user_config): @@ -22,6 +22,7 @@ class instapaper(user_config): from .core.cfg import make_config + config = make_config(instapaper) @@ -39,9 +40,12 @@ Bookmark = dal.Bookmark Page = dal.Page -from typing import Sequence, Iterable +from collections.abc import Iterable, Sequence from pathlib import Path + from .core import get_files + + def inputs() -> Sequence[Path]: return get_files(config.export_path) diff --git a/my/ip/all.py b/my/ip/all.py index 46c1fec..e8277c1 100644 --- a/my/ip/all.py +++ b/my/ip/all.py @@ -9,10 +9,9 @@ For an example of how this could be used, see https://github.com/seanbreckenridg REQUIRES = ["git+https://github.com/seanbreckenridge/ipgeocache"] -from typing import Iterator +from collections.abc import Iterator from my.core import Stats, warn_if_empty - from my.ip.common import IP diff --git a/my/ip/common.py b/my/ip/common.py index 244ddc5..ef54ee3 100644 --- a/my/ip/common.py +++ b/my/ip/common.py @@ -2,11 +2,12 @@ Provides location/timezone data from IP addresses, using [[https://github.com/seanbreckenridge/ipgeocache][ipgeocache]] """ -from my.core import __NOT_HPI_MODULE__ +from my.core import __NOT_HPI_MODULE__ # isort: skip import ipaddress -from typing import NamedTuple, Iterator, Tuple +from collections.abc import Iterator from datetime import datetime +from typing import NamedTuple import ipgeocache @@ -22,7 +23,7 @@ class IP(NamedTuple): return ipgeocache.get(self.addr) @property - def latlon(self) -> Tuple[float, float]: + def latlon(self) -> tuple[float, float]: loc: str = self.ipgeocache()["loc"] lat, _, lon = loc.partition(",") return float(lat), float(lon) diff --git a/my/jawbone/__init__.py b/my/jawbone/__init__.py index 35112ba..463d735 100644 --- a/my/jawbone/__init__.py +++ b/my/jawbone/__init__.py @@ -1,10 +1,11 @@ from __future__ import annotations -from typing import Dict, Any, List, Iterable import json +from collections.abc import Iterable +from datetime import date, datetime, time, timedelta from functools import lru_cache -from datetime import datetime, date, time, timedelta from pathlib import Path +from typing import Any import pytz @@ -14,7 +15,6 @@ logger = make_logger(__name__) from my.config import jawbone as config # type: ignore[attr-defined] - BDIR = config.export_dir PHASES_FILE = BDIR / 'phases.json' SLEEPS_FILE = BDIR / 'sleeps.json' @@ -24,7 +24,7 @@ GRAPHS_DIR = BDIR / 'graphs' XID = str # TODO how to shared with backup thing? -Phases = Dict[XID, Any] +Phases = dict[XID, Any] @lru_cache(1) def get_phases() -> Phases: return json.loads(PHASES_FILE.read_text()) @@ -89,7 +89,7 @@ class SleepEntry: # TODO might be useful to cache these?? @property - def phases(self) -> List[datetime]: + def phases(self) -> list[datetime]: # TODO make sure they are consistent with emfit? return [self._fromts(i['time']) for i in get_phases()[self.xid]] @@ -100,12 +100,13 @@ class SleepEntry: return str(self) -def load_sleeps() -> List[SleepEntry]: +def load_sleeps() -> list[SleepEntry]: sleeps = json.loads(SLEEPS_FILE.read_text()) return [SleepEntry(js) for js in sleeps] -from ..core.error import Res, set_error_datetime, extract_error_datetime +from ..core.error import Res, extract_error_datetime, set_error_datetime + def pre_dataframe() -> Iterable[Res[SleepEntry]]: from more_itertools import bucket @@ -129,9 +130,9 @@ def pre_dataframe() -> Iterable[Res[SleepEntry]]: def dataframe(): - dicts: List[Dict[str, Any]] = [] + dicts: list[dict[str, Any]] = [] for s in pre_dataframe(): - d: Dict[str, Any] + d: dict[str, Any] if isinstance(s, Exception): dt = extract_error_datetime(s) d = { @@ -181,7 +182,7 @@ def plot_one(sleep: SleepEntry, fig, axes, xlims=None, *, showtext=True): print(f"{sleep.xid} span: {span}") # pip install imageio - from imageio import imread # type: ignore + from imageio import imread # type: ignore img = imread(sleep.graph) # all of them are 300x300 images apparently @@ -260,8 +261,8 @@ def predicate(sleep: SleepEntry): # TODO move to dashboard def plot() -> None: - from matplotlib.figure import Figure # type: ignore[import-not-found] import matplotlib.pyplot as plt # type: ignore[import-not-found] + from matplotlib.figure import Figure # type: ignore[import-not-found] # TODO FIXME melatonin data melatonin_data = {} # type: ignore[var-annotated] diff --git a/my/jawbone/plots.py b/my/jawbone/plots.py index d26d606..5968412 100755 --- a/my/jawbone/plots.py +++ b/my/jawbone/plots.py @@ -1,10 +1,11 @@ #!/usr/bin/env python3 # TODO this should be in dashboard -from pathlib import Path # from kython.plotting import * from csv import DictReader +from pathlib import Path +from typing import Any, NamedTuple -from typing import Dict, Any, NamedTuple +import matplotlib.pylab as pylab # type: ignore # sleep = [] # with open('2017.csv', 'r') as fo: @@ -12,16 +13,14 @@ from typing import Dict, Any, NamedTuple # for line in islice(reader, 0, 10): # sleep # print(line) - -import matplotlib.pyplot as plt # type: ignore +import matplotlib.pyplot as plt # type: ignore from numpy import genfromtxt -import matplotlib.pylab as pylab # type: ignore pylab.rcParams['figure.figsize'] = (32.0, 24.0) pylab.rcParams['font.size'] = 10 jawboneDataFeatures = Path(__file__).parent / 'features.csv' # Data File Path -featureDesc: Dict[str, str] = {} +featureDesc: dict[str, str] = {} for x in genfromtxt(jawboneDataFeatures, dtype='unicode', delimiter=','): featureDesc[x[0]] = x[1] @@ -52,7 +51,7 @@ class SleepData(NamedTuple): quality: float # ??? @classmethod - def from_jawbone_dict(cls, d: Dict[str, Any]): + def from_jawbone_dict(cls, d: dict[str, Any]): return cls( date=d['DATE'], asleep_time=_safe_mins(_safe_float(d['s_asleep_time'])), @@ -75,7 +74,7 @@ class SleepData(NamedTuple): def iter_useful(data_file: str): - with open(data_file) as fo: + with Path(data_file).open() as fo: reader = DictReader(fo) for d in reader: dt = SleepData.from_jawbone_dict(d) @@ -95,6 +94,7 @@ files = [ ] from kython import concat, parse_date # type: ignore + useful = concat(*(list(iter_useful(str(f))) for f in files)) # for u in useful: @@ -108,6 +108,7 @@ dates = [parse_date(u.date, yearfirst=True, dayfirst=False) for u in useful] # TODO don't need this anymore? it's gonna be in dashboards package from kython.plotting import plot_timestamped # type: ignore + for attr, lims, mavg, fig in [ ('light', (0, 400), 5, None), ('deep', (0, 600), 5, None), diff --git a/my/kobo.py b/my/kobo.py index 85bc50f..b4a1575 100644 --- a/my/kobo.py +++ b/my/kobo.py @@ -7,21 +7,22 @@ REQUIRES = [ 'kobuddy', ] +from collections.abc import Iterator from dataclasses import dataclass -from typing import Iterator - -from my.core import ( - get_files, - stat, - Paths, - Stats, -) -from my.core.cfg import make_config -import my.config import kobuddy -from kobuddy import Highlight, get_highlights from kobuddy import * +from kobuddy import Highlight, get_highlights + +from my.core import ( + Paths, + Stats, + get_files, + stat, +) +from my.core.cfg import make_config + +import my.config # isort: skip @dataclass @@ -51,7 +52,7 @@ def stats() -> Stats: ## TODO hmm. not sure if all this really belongs here?... perhaps orger? -from typing import Callable, Union, List +from typing import Callable, Union # TODO maybe type over T? _Predicate = Callable[[str], bool] @@ -69,17 +70,17 @@ def from_predicatish(p: Predicatish) -> _Predicate: return p -def by_annotation(predicatish: Predicatish, **kwargs) -> List[Highlight]: +def by_annotation(predicatish: Predicatish, **kwargs) -> list[Highlight]: pred = from_predicatish(predicatish) - res: List[Highlight] = [] + res: list[Highlight] = [] for h in get_highlights(**kwargs): if pred(h.annotation): res.append(h) return res -def get_todos() -> List[Highlight]: +def get_todos() -> list[Highlight]: def with_todo(ann): if ann is None: ann = '' diff --git a/my/kython/kompress.py b/my/kython/kompress.py index 01e24e4..a5d9c29 100644 --- a/my/kython/kompress.py +++ b/my/kython/kompress.py @@ -1,5 +1,4 @@ -from my.core import __NOT_HPI_MODULE__ -from my.core import warnings +from my.core import __NOT_HPI_MODULE__, warnings warnings.high('my.kython.kompress is deprecated, please use "kompress" library directly. See https://github.com/karlicoss/kompress') diff --git a/my/lastfm.py b/my/lastfm.py index d20ebf3..cd9fa8b 100644 --- a/my/lastfm.py +++ b/my/lastfm.py @@ -3,9 +3,9 @@ Last.fm scrobbles ''' from dataclasses import dataclass -from my.core import Paths, Json, make_logger, get_files -from my.config import lastfm as user_config +from my.config import lastfm as user_config +from my.core import Json, Paths, get_files, make_logger logger = make_logger(__name__) @@ -19,13 +19,15 @@ class lastfm(user_config): from my.core.cfg import make_config + config = make_config(lastfm) -from datetime import datetime, timezone import json +from collections.abc import Iterable, Sequence +from datetime import datetime, timezone from pathlib import Path -from typing import NamedTuple, Sequence, Iterable +from typing import NamedTuple from my.core.cachew import mcachew @@ -76,7 +78,9 @@ def scrobbles() -> Iterable[Scrobble]: yield Scrobble(raw=raw) -from my.core import stat, Stats +from my.core import Stats, stat + + def stats() -> Stats: return stat(scrobbles) diff --git a/my/location/all.py b/my/location/all.py index fd88721..c6e8cab 100644 --- a/my/location/all.py +++ b/my/location/all.py @@ -2,14 +2,13 @@ Merges location data from multiple sources """ -from typing import Iterator +from collections.abc import Iterator -from my.core import Stats, LazyLogger +from my.core import LazyLogger, Stats from my.core.source import import_source from .common import Location - logger = LazyLogger(__name__, level="warning") diff --git a/my/location/common.py b/my/location/common.py index f406370..4c47ef0 100644 --- a/my/location/common.py +++ b/my/location/common.py @@ -1,12 +1,13 @@ -from datetime import date, datetime -from typing import Union, Tuple, Optional, Iterable, TextIO, Iterator, Protocol -from dataclasses import dataclass +from my.core import __NOT_HPI_MODULE__ # isort: skip -from my.core import __NOT_HPI_MODULE__ +from collections.abc import Iterable, Iterator +from dataclasses import dataclass +from datetime import date, datetime +from typing import Optional, Protocol, TextIO, Union DateIsh = Union[datetime, date, str] -LatLon = Tuple[float, float] +LatLon = tuple[float, float] class LocationProtocol(Protocol): diff --git a/my/location/fallback/all.py b/my/location/fallback/all.py index a5daa05..d340148 100644 --- a/my/location/fallback/all.py +++ b/my/location/fallback/all.py @@ -1,14 +1,16 @@ # TODO: add config here which passes kwargs to estimate_from (under_accuracy) # overwritable by passing the kwarg name here to the top-level estimate_location -from typing import Iterator, Optional +from __future__ import annotations + +from collections.abc import Iterator from my.core.source import import_source from my.location.fallback.common import ( - estimate_from, - FallbackLocation, DateExact, + FallbackLocation, LocationEstimator, + estimate_from, ) @@ -24,7 +26,7 @@ def fallback_estimators() -> Iterator[LocationEstimator]: yield _home_estimate -def estimate_location(dt: DateExact, *, first_match: bool=False, under_accuracy: Optional[int] = None) -> FallbackLocation: +def estimate_location(dt: DateExact, *, first_match: bool=False, under_accuracy: int | None = None) -> FallbackLocation: loc = estimate_from(dt, estimators=list(fallback_estimators()), first_match=first_match, under_accuracy=under_accuracy) # should never happen if the user has home configured if loc is None: diff --git a/my/location/fallback/common.py b/my/location/fallback/common.py index 13bc603..622b2f5 100644 --- a/my/location/fallback/common.py +++ b/my/location/fallback/common.py @@ -1,9 +1,12 @@ from __future__ import annotations -from dataclasses import dataclass -from typing import Optional, Callable, Sequence, Iterator, List, Union -from datetime import datetime, timedelta, timezone -from ..common import LocationProtocol, Location +from collections.abc import Iterator, Sequence +from dataclasses import dataclass +from datetime import datetime, timedelta, timezone +from typing import Callable, Union + +from ..common import Location, LocationProtocol + DateExact = Union[datetime, float, int] # float/int as epoch timestamps Second = float @@ -13,10 +16,10 @@ class FallbackLocation(LocationProtocol): lat: float lon: float dt: datetime - duration: Optional[Second] = None - accuracy: Optional[float] = None - elevation: Optional[float] = None - datasource: Optional[str] = None # which module provided this, useful for debugging + duration: Second | None = None + accuracy: float | None = None + elevation: float | None = None + datasource: str | None = None # which module provided this, useful for debugging def to_location(self, *, end: bool = False) -> Location: ''' @@ -43,9 +46,9 @@ class FallbackLocation(LocationProtocol): lon: float, dt: datetime, end_dt: datetime, - accuracy: Optional[float] = None, - elevation: Optional[float] = None, - datasource: Optional[str] = None, + accuracy: float | None = None, + elevation: float | None = None, + datasource: str | None = None, ) -> FallbackLocation: ''' Create FallbackLocation from a start date and an end date @@ -93,13 +96,13 @@ def estimate_from( estimators: LocationEstimators, *, first_match: bool = False, - under_accuracy: Optional[int] = None, -) -> Optional[FallbackLocation]: + under_accuracy: int | None = None, +) -> FallbackLocation | None: ''' first_match: if True, return the first location found under_accuracy: if set, only return locations with accuracy under this value ''' - found: List[FallbackLocation] = [] + found: list[FallbackLocation] = [] for loc in _iter_estimate_from(dt, estimators): if under_accuracy is not None and loc.accuracy is not None and loc.accuracy > under_accuracy: continue diff --git a/my/location/fallback/via_home.py b/my/location/fallback/via_home.py index e44c59d..f88fee0 100644 --- a/my/location/fallback/via_home.py +++ b/my/location/fallback/via_home.py @@ -2,25 +2,22 @@ Simple location provider, serving as a fallback when more detailed data isn't available ''' +from __future__ import annotations + +from collections.abc import Iterator, Sequence from dataclasses import dataclass from datetime import datetime, time, timezone -from functools import lru_cache -from typing import Sequence, Tuple, Union, cast, List, Iterator +from functools import cache +from typing import cast from my.config import location as user_config +from my.location.common import DateIsh, LatLon +from my.location.fallback.common import DateExact, FallbackLocation -from my.location.common import LatLon, DateIsh -from my.location.fallback.common import FallbackLocation, DateExact @dataclass class Config(user_config): - home: Union[ - LatLon, # either single, 'current' location - Sequence[Tuple[ # or, a sequence of location history - DateIsh, # date when you moved to - LatLon, # the location - ]] - ] + home: LatLon | Sequence[tuple[DateIsh, LatLon]] # default ~30km accuracy # this is called 'home_accuracy' since it lives on the base location.config object, @@ -29,13 +26,13 @@ class Config(user_config): # TODO could make current Optional and somehow determine from system settings? @property - def _history(self) -> Sequence[Tuple[datetime, LatLon]]: + def _history(self) -> Sequence[tuple[datetime, LatLon]]: home1 = self.home # todo ugh, can't test for isnstance LatLon, it's a tuple itself - home2: Sequence[Tuple[DateIsh, LatLon]] + home2: Sequence[tuple[DateIsh, LatLon]] if isinstance(home1[0], tuple): # already a sequence - home2 = cast(Sequence[Tuple[DateIsh, LatLon]], home1) + home2 = cast(Sequence[tuple[DateIsh, LatLon]], home1) else: # must be a pair of coordinates. also doesn't really matter which date to pick? loc = cast(LatLon, home1) @@ -60,10 +57,11 @@ class Config(user_config): from ...core.cfg import make_config + config = make_config(Config) -@lru_cache(maxsize=None) +@cache def get_location(dt: datetime) -> LatLon: ''' Interpolates the location at dt @@ -74,8 +72,8 @@ def get_location(dt: datetime) -> LatLon: # TODO: in python3.8, use functools.cached_property instead? -@lru_cache(maxsize=None) -def homes_cached() -> List[Tuple[datetime, LatLon]]: +@cache +def homes_cached() -> list[tuple[datetime, LatLon]]: return list(config._history) diff --git a/my/location/fallback/via_ip.py b/my/location/fallback/via_ip.py index 79a452c..732af67 100644 --- a/my/location/fallback/via_ip.py +++ b/my/location/fallback/via_ip.py @@ -7,8 +7,8 @@ REQUIRES = ["git+https://github.com/seanbreckenridge/ipgeocache"] from dataclasses import dataclass from datetime import timedelta -from my.core import Stats, make_config from my.config import location +from my.core import Stats, make_config from my.core.warnings import medium @@ -24,13 +24,13 @@ class ip_config(location.via_ip): config = make_config(ip_config) +from collections.abc import Iterator from functools import lru_cache -from typing import Iterator, List from my.core import make_logger from my.core.compat import bisect_left from my.location.common import Location -from my.location.fallback.common import FallbackLocation, DateExact, _datetime_timestamp +from my.location.fallback.common import DateExact, FallbackLocation, _datetime_timestamp logger = make_logger(__name__, level="warning") @@ -60,7 +60,7 @@ def locations() -> Iterator[Location]: @lru_cache(1) -def _sorted_fallback_locations() -> List[FallbackLocation]: +def _sorted_fallback_locations() -> list[FallbackLocation]: fl = list(filter(lambda l: l.duration is not None, fallback_locations())) logger.debug(f"Fallback locations: {len(fl)}, sorting...:") fl.sort(key=lambda l: l.dt.timestamp()) diff --git a/my/location/google.py b/my/location/google.py index b966ec6..750c847 100644 --- a/my/location/google.py +++ b/my/location/google.py @@ -3,28 +3,27 @@ Location data from Google Takeout DEPRECATED: setup my.google.takeout.parser and use my.location.google_takeout instead """ +from __future__ import annotations REQUIRES = [ 'geopy', # checking that coordinates are valid 'ijson', ] +import re +from collections.abc import Iterable, Sequence from datetime import datetime, timezone from itertools import islice from pathlib import Path -from subprocess import Popen, PIPE -from typing import Iterable, NamedTuple, Optional, Sequence, IO, Tuple -import re +from subprocess import PIPE, Popen +from typing import IO, NamedTuple, Optional # pip3 install geopy -import geopy # type: ignore +import geopy # type: ignore -from my.core import stat, Stats, make_logger +from my.core import Stats, make_logger, stat, warnings from my.core.cachew import cache_dir, mcachew -from my.core import warnings - - warnings.high("Please set up my.google.takeout.parser module for better takeout support") @@ -43,7 +42,7 @@ class Location(NamedTuple): alt: Optional[float] -TsLatLon = Tuple[int, int, int] +TsLatLon = tuple[int, int, int] def _iter_via_ijson(fo) -> Iterable[TsLatLon]: @@ -51,10 +50,10 @@ def _iter_via_ijson(fo) -> Iterable[TsLatLon]: # todo extract to common? try: # pip3 install ijson cffi - import ijson.backends.yajl2_cffi as ijson # type: ignore + import ijson.backends.yajl2_cffi as ijson # type: ignore except: warnings.medium("Falling back to default ijson because 'cffi' backend isn't found. It's up to 2x faster, you might want to check it out") - import ijson # type: ignore + import ijson # type: ignore for d in ijson.items(fo, 'locations.item'): yield ( diff --git a/my/location/google_takeout.py b/my/location/google_takeout.py index eb757ce..cb5bef3 100644 --- a/my/location/google_takeout.py +++ b/my/location/google_takeout.py @@ -4,13 +4,14 @@ Extracts locations using google_takeout_parser -- no shared code with the deprec REQUIRES = ["git+https://github.com/seanbreckenridge/google_takeout_parser"] -from typing import Iterator +from collections.abc import Iterator -from my.google.takeout.parser import events, _cachew_depends_on from google_takeout_parser.models import Location as GoogleLocation -from my.core import stat, Stats, LazyLogger +from my.core import LazyLogger, Stats, stat from my.core.cachew import mcachew +from my.google.takeout.parser import _cachew_depends_on, events + from .common import Location logger = LazyLogger(__name__) diff --git a/my/location/google_takeout_semantic.py b/my/location/google_takeout_semantic.py index 5f2c055..7bddfa8 100644 --- a/my/location/google_takeout_semantic.py +++ b/my/location/google_takeout_semantic.py @@ -7,21 +7,24 @@ Extracts semantic location history using google_takeout_parser REQUIRES = ["git+https://github.com/seanbreckenridge/google_takeout_parser"] +from collections.abc import Iterator from dataclasses import dataclass -from typing import Iterator, List -from my.google.takeout.parser import events, _cachew_depends_on as _parser_cachew_depends_on from google_takeout_parser.models import PlaceVisit as SemanticLocation -from my.core import make_config, stat, LazyLogger, Stats +from my.core import LazyLogger, Stats, make_config, stat from my.core.cachew import mcachew from my.core.error import Res +from my.google.takeout.parser import _cachew_depends_on as _parser_cachew_depends_on +from my.google.takeout.parser import events + from .common import Location logger = LazyLogger(__name__) from my.config import location as user_config + @dataclass class semantic_locations_config(user_config.google_takeout_semantic): # a value between 0 and 100, 100 being the most confident @@ -36,7 +39,7 @@ config = make_config(semantic_locations_config) # add config to cachew dependency so it recomputes on config changes -def _cachew_depends_on() -> List[str]: +def _cachew_depends_on() -> list[str]: dep = _parser_cachew_depends_on() dep.insert(0, f"require_confidence={config.require_confidence} accuracy={config.accuracy}") return dep diff --git a/my/location/gpslogger.py b/my/location/gpslogger.py index 6d158a0..bbbf70e 100644 --- a/my/location/gpslogger.py +++ b/my/location/gpslogger.py @@ -20,20 +20,20 @@ class config(location.gpslogger): accuracy: float = 50.0 -from itertools import chain +from collections.abc import Iterator, Sequence from datetime import datetime, timezone +from itertools import chain from pathlib import Path -from typing import Iterator, Sequence, List import gpxpy from gpxpy.gpx import GPXXMLSyntaxException from more_itertools import unique_everseen -from my.core import Stats, LazyLogger +from my.core import LazyLogger, Stats from my.core.cachew import mcachew from my.core.common import get_files -from .common import Location +from .common import Location logger = LazyLogger(__name__, level="warning") @@ -49,7 +49,7 @@ def inputs() -> Sequence[Path]: return sorted(get_files(config.export_path, glob="*.gpx", sort=False), key=_input_sort_key) -def _cachew_depends_on() -> List[float]: +def _cachew_depends_on() -> list[float]: return [p.stat().st_mtime for p in inputs()] diff --git a/my/location/home.py b/my/location/home.py index f6e6978..c82dda7 100644 --- a/my/location/home.py +++ b/my/location/home.py @@ -1,7 +1,7 @@ -from .fallback.via_home import * - from my.core.warnings import high +from .fallback.via_home import * + high( "my.location.home is deprecated, use my.location.fallback.via_home instead, or estimate locations using the higher-level my.location.fallback.all.estimate_location" ) diff --git a/my/location/via_ip.py b/my/location/via_ip.py index df48f8b..d465ad0 100644 --- a/my/location/via_ip.py +++ b/my/location/via_ip.py @@ -1,7 +1,7 @@ REQUIRES = ["git+https://github.com/seanbreckenridge/ipgeocache"] -from .fallback.via_ip import * - from my.core.warnings import high +from .fallback.via_ip import * + high("my.location.via_ip is deprecated, use my.location.fallback.via_ip instead") diff --git a/my/materialistic.py b/my/materialistic.py index 8a6a997..45af3f9 100644 --- a/my/materialistic.py +++ b/my/materialistic.py @@ -1,4 +1,5 @@ from .core.warnings import high + high("DEPRECATED! Please use my.hackernews.materialistic instead.") from .hackernews.materialistic import * diff --git a/my/media/imdb.py b/my/media/imdb.py index df31032..131f6a7 100644 --- a/my/media/imdb.py +++ b/my/media/imdb.py @@ -1,10 +1,12 @@ import csv +from collections.abc import Iterator from datetime import datetime -from typing import Iterator, List, NamedTuple +from typing import NamedTuple -from ..core import get_files +from my.core import get_files + +from my.config import imdb as config # isort: skip -from my.config import imdb as config def _get_last(): return max(get_files(config.export_path)) @@ -31,7 +33,7 @@ def iter_movies() -> Iterator[Movie]: yield Movie(created=created, title=title, rating=rating) -def get_movies() -> List[Movie]: +def get_movies() -> list[Movie]: return sorted(iter_movies(), key=lambda m: m.created) diff --git a/my/media/youtube.py b/my/media/youtube.py index 3ddbc14..9a38c43 100644 --- a/my/media/youtube.py +++ b/my/media/youtube.py @@ -1,4 +1,4 @@ -from my.core import __NOT_HPI_MODULE__ +from my.core import __NOT_HPI_MODULE__ # isort: skip from typing import TYPE_CHECKING diff --git a/my/monzo/monzoexport.py b/my/monzo/monzoexport.py index 3aa0cf5..f5e1cd1 100644 --- a/my/monzo/monzoexport.py +++ b/my/monzo/monzoexport.py @@ -5,16 +5,17 @@ REQUIRES = [ 'git+https://github.com/karlicoss/monzoexport', ] +from collections.abc import Iterator, Sequence from dataclasses import dataclass from pathlib import Path -from typing import Sequence, Iterator from my.core import ( Paths, get_files, make_logger, ) -import my.config + +import my.config # isort: skip @dataclass diff --git a/my/orgmode.py b/my/orgmode.py index cf14e43..10f53c0 100644 --- a/my/orgmode.py +++ b/my/orgmode.py @@ -1,15 +1,17 @@ ''' Programmatic access and queries to org-mode files on the filesystem ''' +from __future__ import annotations REQUIRES = [ 'orgparse', ] import re +from collections.abc import Iterable, Sequence from datetime import datetime from pathlib import Path -from typing import Iterable, List, NamedTuple, Optional, Sequence, Tuple +from typing import NamedTuple, Optional import orgparse @@ -34,7 +36,7 @@ def make_config() -> config: class OrgNote(NamedTuple): created: Optional[datetime] heading: str - tags: List[str] + tags: list[str] def inputs() -> Sequence[Path]: @@ -45,7 +47,7 @@ def inputs() -> Sequence[Path]: _rgx = re.compile(orgparse.date.gene_timestamp_regex(brtype='inactive'), re.VERBOSE) -def _created(n: orgparse.OrgNode) -> Tuple[Optional[datetime], str]: +def _created(n: orgparse.OrgNode) -> tuple[datetime | None, str]: heading = n.heading # meh.. support in orgparse? pp = {} if n.is_root() else n.properties @@ -68,7 +70,7 @@ def _created(n: orgparse.OrgNode) -> Tuple[Optional[datetime], str]: def to_note(x: orgparse.OrgNode) -> OrgNote: # ugh. hack to merely make it cacheable heading = x.heading - created: Optional[datetime] + created: datetime | None try: c, heading = _created(x) if isinstance(c, datetime): diff --git a/my/pdfs.py b/my/pdfs.py index de9324d..eefd573 100644 --- a/my/pdfs.py +++ b/my/pdfs.py @@ -1,6 +1,7 @@ ''' PDF documents and annotations on your filesystem ''' +from __future__ import annotations as _annotations REQUIRES = [ 'git+https://github.com/0xabu/pdfannots', @@ -8,9 +9,10 @@ REQUIRES = [ ] import time +from collections.abc import Iterator, Sequence from datetime import datetime from pathlib import Path -from typing import Iterator, List, NamedTuple, Optional, Protocol, Sequence, TYPE_CHECKING +from typing import TYPE_CHECKING, NamedTuple, Optional, Protocol import pdfannots from more_itertools import bucket @@ -72,7 +74,7 @@ class Annotation(NamedTuple): created: Optional[datetime] # note: can be tz unaware in some bad pdfs... @property - def date(self) -> Optional[datetime]: + def date(self) -> datetime | None: # legacy name return self.created @@ -93,7 +95,7 @@ def _as_annotation(*, raw: pdfannots.Annotation, path: str) -> Annotation: ) -def get_annots(p: Path) -> List[Annotation]: +def get_annots(p: Path) -> list[Annotation]: b = time.time() with p.open('rb') as fo: doc = pdfannots.process_file(fo, emit_progress_to=None) @@ -150,17 +152,17 @@ class Pdf(NamedTuple): annotations: Sequence[Annotation] @property - def created(self) -> Optional[datetime]: + def created(self) -> datetime | None: annots = self.annotations return None if len(annots) == 0 else annots[-1].created @property - def date(self) -> Optional[datetime]: + def date(self) -> datetime | None: # legacy return self.created -def annotated_pdfs(*, filelist: Optional[Sequence[PathIsh]] = None) -> Iterator[Res[Pdf]]: +def annotated_pdfs(*, filelist: Sequence[PathIsh] | None = None) -> Iterator[Res[Pdf]]: if filelist is not None: # hacky... keeping it backwards compatible # https://github.com/karlicoss/HPI/pull/74 diff --git a/my/photos/main.py b/my/photos/main.py index bf912e4..f98cb15 100644 --- a/my/photos/main.py +++ b/my/photos/main.py @@ -1,27 +1,30 @@ """ Photos and videos on your filesystem, their GPS and timestamps """ + +from __future__ import annotations + REQUIRES = [ 'geopy', 'magic', ] # NOTE: also uses fdfind to search photos +import json +from collections.abc import Iterable, Iterator from concurrent.futures import ProcessPoolExecutor as Pool from datetime import datetime -import json from pathlib import Path -from typing import Optional, NamedTuple, Iterator, Iterable, List +from typing import NamedTuple, Optional from geopy.geocoders import Nominatim # type: ignore from my.core import LazyLogger -from my.core.error import Res, sort_res_by from my.core.cachew import cache_dir, mcachew +from my.core.error import Res, sort_res_by from my.core.mime import fastermime -from my.config import photos as config # type: ignore[attr-defined] - +from my.config import photos as config # type: ignore[attr-defined] # isort: skip logger = LazyLogger(__name__) @@ -55,15 +58,15 @@ class Photo(NamedTuple): return f'{config.base_url}{self._basename}' -from .utils import get_exif_from_file, ExifTags, Exif, dt_from_path, convert_ref +from .utils import Exif, ExifTags, convert_ref, dt_from_path, get_exif_from_file Result = Res[Photo] -def _make_photo_aux(*args, **kwargs) -> List[Result]: +def _make_photo_aux(*args, **kwargs) -> list[Result]: # for the process pool.. return list(_make_photo(*args, **kwargs)) -def _make_photo(photo: Path, mtype: str, *, parent_geo: Optional[LatLon]) -> Iterator[Result]: +def _make_photo(photo: Path, mtype: str, *, parent_geo: LatLon | None) -> Iterator[Result]: exif: Exif if any(x in mtype for x in ['image/png', 'image/x-ms-bmp', 'video']): # TODO don't remember why.. @@ -77,7 +80,7 @@ def _make_photo(photo: Path, mtype: str, *, parent_geo: Optional[LatLon]) -> Ite yield e exif = {} - def _get_geo() -> Optional[LatLon]: + def _get_geo() -> LatLon | None: meta = exif.get(ExifTags.GPSINFO, {}) if ExifTags.LAT in meta and ExifTags.LON in meta: return LatLon( @@ -87,7 +90,7 @@ def _make_photo(photo: Path, mtype: str, *, parent_geo: Optional[LatLon]) -> Ite return parent_geo # TODO aware on unaware? - def _get_dt() -> Optional[datetime]: + def _get_dt() -> datetime | None: edt = exif.get(ExifTags.DATETIME, None) if edt is not None: dtimes = edt.replace(' 24', ' 00') # jeez maybe log it? @@ -123,7 +126,7 @@ def _make_photo(photo: Path, mtype: str, *, parent_geo: Optional[LatLon]) -> Ite def _candidates() -> Iterable[Res[str]]: # TODO that could be a bit slow if there are to many extra files? - from subprocess import Popen, PIPE + from subprocess import PIPE, Popen # TODO could extract this to common? # TODO would be nice to reuse get_files (or even let it use find) # that way would be easier to exclude @@ -162,7 +165,7 @@ def _photos(candidates: Iterable[Res[str]]) -> Iterator[Result]: from functools import lru_cache @lru_cache(None) - def get_geo(d: Path) -> Optional[LatLon]: + def get_geo(d: Path) -> LatLon | None: geof = d / 'geo.json' if not geof.exists(): if d == d.parent: @@ -214,5 +217,7 @@ def print_all() -> None: # todo cachew -- invalidate if function code changed? from ..core import Stats, stat + + def stats() -> Stats: return stat(photos) diff --git a/my/photos/utils.py b/my/photos/utils.py index c614c4a..e88def2 100644 --- a/my/photos/utils.py +++ b/my/photos/utils.py @@ -1,11 +1,13 @@ +from __future__ import annotations + +from ..core import __NOT_HPI_MODULE__ # isort: skip + from pathlib import Path -from typing import Dict import PIL.Image -from PIL.ExifTags import TAGS, GPSTAGS +from PIL.ExifTags import GPSTAGS, TAGS - -Exif = Dict +Exif = dict # TODO PIL.ExifTags.TAGS @@ -62,18 +64,15 @@ def convert_ref(cstr, ref: str) -> float: import re from datetime import datetime -from typing import Optional # TODO surely there is a library that does it?? # TODO this belongs to a private overlay or something # basically have a function that patches up dates after the files were yielded.. _DT_REGEX = re.compile(r'\D(\d{8})\D*(\d{6})\D') -def dt_from_path(p: Path) -> Optional[datetime]: +def dt_from_path(p: Path) -> datetime | None: name = p.stem mm = _DT_REGEX.search(name) if mm is None: return None dates = mm.group(1) + mm.group(2) return datetime.strptime(dates, "%Y%m%d%H%M%S") - -from ..core import __NOT_HPI_MODULE__ diff --git a/my/pinboard.py b/my/pinboard.py index ef4ca36..e98dc78 100644 --- a/my/pinboard.py +++ b/my/pinboard.py @@ -5,15 +5,16 @@ REQUIRES = [ 'git+https://github.com/karlicoss/pinbexport', ] +from collections.abc import Iterator, Sequence from dataclasses import dataclass from pathlib import Path -from typing import Iterator, Sequence - -from my.core import get_files, Paths, Res -import my.config import pinbexport.dal as pinbexport +from my.core import Paths, Res, get_files + +import my.config # isort: skip + @dataclass class config(my.config.pinboard): # TODO rename to pinboard.pinbexport? diff --git a/my/pocket.py b/my/pocket.py index b638fba..ff9a788 100644 --- a/my/pocket.py +++ b/my/pocket.py @@ -7,10 +7,10 @@ REQUIRES = [ from dataclasses import dataclass from typing import TYPE_CHECKING -from .core import Paths - from my.config import pocket as user_config +from .core import Paths + @dataclass class pocket(user_config): @@ -23,6 +23,7 @@ class pocket(user_config): from .core.cfg import make_config + config = make_config(pocket) @@ -37,7 +38,7 @@ except ModuleNotFoundError as e: Article = dal.Article -from typing import Sequence, Iterable +from collections.abc import Iterable, Sequence # todo not sure if should be defensive against empty? @@ -51,9 +52,12 @@ def articles() -> Iterable[Article]: yield from _dal().articles() -from .core import stat, Stats +from .core import Stats, stat + + def stats() -> Stats: from itertools import chain + from more_itertools import ilen return { **stat(articles), diff --git a/my/polar.py b/my/polar.py index e52bb14..2172014 100644 --- a/my/polar.py +++ b/my/polar.py @@ -1,11 +1,12 @@ """ [[https://github.com/burtonator/polar-bookshelf][Polar]] articles and highlights """ +from __future__ import annotations + from pathlib import Path -from typing import cast, TYPE_CHECKING +from typing import TYPE_CHECKING, cast - -import my.config +import my.config # isort: skip # todo use something similar to tz.via_location for config fallback if not TYPE_CHECKING: @@ -20,8 +21,11 @@ if user_config is None: pass -from .core import PathIsh from dataclasses import dataclass + +from .core import PathIsh + + @dataclass class polar(user_config): ''' @@ -32,20 +36,21 @@ class polar(user_config): from .core import make_config + config = make_config(polar) # todo not sure where it keeps stuff on Windows? # https://github.com/burtonator/polar-bookshelf/issues/296 -from datetime import datetime -from typing import List, Dict, Iterable, NamedTuple, Sequence, Optional import json +from collections.abc import Iterable, Sequence +from datetime import datetime +from typing import NamedTuple -from .core import LazyLogger, Json, Res +from .core import Json, LazyLogger, Res from .core.compat import fromisoformat from .core.error import echain, sort_res_by -from .core.konsume import wrap, Zoomable, Wdict - +from .core.konsume import Wdict, Zoomable, wrap logger = LazyLogger(__name__) @@ -65,7 +70,7 @@ class Highlight(NamedTuple): comments: Sequence[Comment] tags: Sequence[str] page: int # 1-indexed - color: Optional[str] = None + color: str | None = None Uid = str @@ -73,7 +78,7 @@ class Book(NamedTuple): created: datetime uid: Uid path: Path - title: Optional[str] + title: str | None # TODO hmmm. I think this needs to be defensive as well... # think about it later. items: Sequence[Highlight] @@ -129,7 +134,7 @@ class Loader: pi['dimensions'].consume_all() # TODO how to make it nicer? - cmap: Dict[Hid, List[Comment]] = {} + cmap: dict[Hid, list[Comment]] = {} vals = list(comments) for v in vals: cid = v['id'].zoom() @@ -163,7 +168,7 @@ class Loader: h['rects'].ignore() # TODO make it more generic.. - htags: List[str] = [] + htags: list[str] = [] if 'tags' in h: ht = h['tags'].zoom() for _k, v in list(ht.items()): @@ -242,7 +247,7 @@ def iter_entries() -> Iterable[Result]: yield err -def get_entries() -> List[Result]: +def get_entries() -> list[Result]: # sorting by first annotation is reasonable I guess??? # todo perhaps worth making it a pattern? X() returns iterable, get_X returns reasonably sorted list? return list(sort_res_by(iter_entries(), key=lambda e: e.created)) diff --git a/my/reddit/__init__.py b/my/reddit/__init__.py index e81aaf9..f344eeb 100644 --- a/my/reddit/__init__.py +++ b/my/reddit/__init__.py @@ -20,6 +20,7 @@ REQUIRES = [ from my.core.hpi_compat import handle_legacy_import + is_legacy_import = handle_legacy_import( parent_module_name=__name__, legacy_submodule_name='rexport', diff --git a/my/reddit/all.py b/my/reddit/all.py index daedba1..27e22df 100644 --- a/my/reddit/all.py +++ b/my/reddit/all.py @@ -1,8 +1,9 @@ -from typing import Iterator -from my.core import stat, Stats +from collections.abc import Iterator + +from my.core import Stats, stat from my.core.source import import_source -from .common import Save, Upvote, Comment, Submission, _merge_comments +from .common import Comment, Save, Submission, Upvote, _merge_comments # Man... ideally an all.py file isn't this verbose, but # reddit just feels like that much of a complicated source and diff --git a/my/reddit/common.py b/my/reddit/common.py index c01258b..40f9f6e 100644 --- a/my/reddit/common.py +++ b/my/reddit/common.py @@ -2,12 +2,14 @@ This defines Protocol classes, which make sure that each different type of shared models have a standardized interface """ -from my.core import __NOT_HPI_MODULE__ -from typing import Set, Iterator, Protocol +from my.core import __NOT_HPI_MODULE__ # isort: skip + +from collections.abc import Iterator from itertools import chain +from typing import Protocol -from my.core import datetime_aware, Json +from my.core import Json, datetime_aware # common fields across all the Protocol classes, so generic code can be written @@ -49,7 +51,7 @@ class Submission(RedditBase, Protocol): def _merge_comments(*sources: Iterator[Comment]) -> Iterator[Comment]: #from .rexport import logger #ignored = 0 - emitted: Set[str] = set() + emitted: set[str] = set() for e in chain(*sources): uid = e.id if uid in emitted: diff --git a/my/reddit/pushshift.py b/my/reddit/pushshift.py index 9580005..1bfa048 100644 --- a/my/reddit/pushshift.py +++ b/my/reddit/pushshift.py @@ -10,13 +10,13 @@ REQUIRES = [ from dataclasses import dataclass +# note: keeping pushshift import before config import, so it's handled gracefully by import_source +from pushshift_comment_export.dal import PComment, read_file + +from my.config import reddit as uconfig from my.core import Paths, Stats, stat from my.core.cfg import make_config -# note: keeping pushshift import before config import, so it's handled gracefully by import_source -from pushshift_comment_export.dal import read_file, PComment - -from my.config import reddit as uconfig @dataclass class pushshift_config(uconfig.pushshift): @@ -29,10 +29,10 @@ class pushshift_config(uconfig.pushshift): config = make_config(pushshift_config) -from my.core import get_files -from typing import Sequence, Iterator +from collections.abc import Iterator, Sequence from pathlib import Path +from my.core import get_files def inputs() -> Sequence[Path]: diff --git a/my/reddit/rexport.py b/my/reddit/rexport.py index 5dcd7d9..cb6af01 100644 --- a/my/reddit/rexport.py +++ b/my/reddit/rexport.py @@ -7,23 +7,24 @@ REQUIRES = [ 'git+https://github.com/karlicoss/rexport', ] -from dataclasses import dataclass import inspect +from collections.abc import Iterator, Sequence +from dataclasses import dataclass from pathlib import Path -from typing import TYPE_CHECKING, Iterator, Sequence +from typing import TYPE_CHECKING from my.core import ( - get_files, - make_logger, - warnings, - stat, Paths, Stats, + get_files, + make_logger, + stat, + warnings, ) from my.core.cachew import mcachew -from my.core.cfg import make_config, Attrs +from my.core.cfg import Attrs, make_config -from my.config import reddit as uconfig +from my.config import reddit as uconfig # isort: skip logger = make_logger(__name__) diff --git a/my/rescuetime.py b/my/rescuetime.py index 76a0d4c..0c9fd28 100644 --- a/my/rescuetime.py +++ b/my/rescuetime.py @@ -5,16 +5,15 @@ REQUIRES = [ 'git+https://github.com/karlicoss/rescuexport', ] -from pathlib import Path +from collections.abc import Iterable, Sequence from datetime import timedelta -from typing import Sequence, Iterable +from pathlib import Path -from my.core import get_files, make_logger, stat, Stats +from my.core import Stats, get_files, make_logger, stat from my.core.cachew import mcachew from my.core.error import Res, split_errors -from my.config import rescuetime as config - +from my.config import rescuetime as config # isort: skip logger = make_logger(__name__) @@ -24,6 +23,7 @@ def inputs() -> Sequence[Path]: import rescuexport.dal as dal + DAL = dal.DAL Entry = dal.Entry @@ -43,6 +43,8 @@ def groups(gap: timedelta=timedelta(hours=3)) -> Iterable[Res[Sequence[Entry]]]: # todo automatic dataframe interface? from .core.pandas import DataFrameT, as_dataframe + + def dataframe() -> DataFrameT: return as_dataframe(entries()) @@ -56,16 +58,19 @@ def stats() -> Stats: # basically, hack config and populate it with fake data? fake data generated by DAL, but the rest is handled by this? +from collections.abc import Iterator from contextlib import contextmanager -from typing import Iterator + + # todo take seed, or what? @contextmanager def fake_data(rows: int=1000) -> Iterator: # todo also disable cachew automatically for such things? - from my.core.cfg import tmp_config - from my.core.cachew import disabled_cachew - from tempfile import TemporaryDirectory import json + from tempfile import TemporaryDirectory + + from my.core.cachew import disabled_cachew + from my.core.cfg import tmp_config with disabled_cachew(), TemporaryDirectory() as td: tdir = Path(td) f = tdir / 'rescuetime.json' diff --git a/my/roamresearch.py b/my/roamresearch.py index 2fe06d4..7322774 100644 --- a/my/roamresearch.py +++ b/my/roamresearch.py @@ -1,16 +1,19 @@ """ [[https://roamresearch.com][Roam]] data """ -from datetime import datetime, timezone -from pathlib import Path -from itertools import chain -import re -from typing import NamedTuple, Iterator, List, Optional +from __future__ import annotations -from .core import get_files, LazyLogger, Json +import re +from collections.abc import Iterator +from datetime import datetime, timezone +from itertools import chain +from pathlib import Path +from typing import NamedTuple from my.config import roamresearch as config +from .core import Json, LazyLogger, get_files + logger = LazyLogger(__name__) @@ -57,15 +60,15 @@ class Node(NamedTuple): return datetime.fromtimestamp(rt / 1000, tz=timezone.utc) @property - def title(self) -> Optional[str]: + def title(self) -> str | None: return self.raw.get(Keys.TITLE) @property - def body(self) -> Optional[str]: + def body(self) -> str | None: return self.raw.get(Keys.STRING) @property - def children(self) -> List['Node']: + def children(self) -> list[Node]: # TODO cache? needs a key argument (because of Json) ch = self.raw.get(Keys.CHILDREN, []) return list(map(Node, ch)) @@ -95,7 +98,7 @@ class Node(NamedTuple): # - heading -- notes that haven't been created yet return len(self.body or '') == 0 and len(self.children) == 0 - def traverse(self) -> Iterator['Node']: + def traverse(self) -> Iterator[Node]: # not sure about __iter__, because might be a bit unintuitive that it's recursive.. yield self for c in self.children: @@ -120,7 +123,7 @@ class Node(NamedTuple): return f'Node(created={self.created}, title={self.title}, body={self.body})' @staticmethod - def make(raw: Json) -> Iterator['Node']: + def make(raw: Json) -> Iterator[Node]: is_empty = set(raw.keys()) == {Keys.EDITED, Keys.EDIT_EMAIL, Keys.TITLE} # not sure about that... but daily notes end up like that if is_empty: @@ -130,11 +133,11 @@ class Node(NamedTuple): class Roam: - def __init__(self, raw: List[Json]) -> None: + def __init__(self, raw: list[Json]) -> None: self.raw = raw @property - def notes(self) -> List[Node]: + def notes(self) -> list[Node]: return list(chain.from_iterable(map(Node.make, self.raw))) def traverse(self) -> Iterator[Node]: diff --git a/my/rss/all.py b/my/rss/all.py index b4dbdbd..e10e4d2 100644 --- a/my/rss/all.py +++ b/my/rss/all.py @@ -3,9 +3,9 @@ Unified RSS data, merged from different services I used historically ''' # NOTE: you can comment out the sources you're not using -from . import feedbin, feedly +from collections.abc import Iterable -from typing import Iterable +from . import feedbin, feedly from .common import Subscription, compute_subscriptions diff --git a/my/rss/common.py b/my/rss/common.py index bb75297..bf9506e 100644 --- a/my/rss/common.py +++ b/my/rss/common.py @@ -1,10 +1,12 @@ -from my.core import __NOT_HPI_MODULE__ +from __future__ import annotations +from my.core import __NOT_HPI_MODULE__ # isort: skip + +from collections.abc import Iterable, Sequence from dataclasses import dataclass, replace from itertools import chain -from typing import Optional, List, Dict, Iterable, Tuple, Sequence -from my.core import warn_if_empty, datetime_aware +from my.core import datetime_aware, warn_if_empty @dataclass @@ -13,16 +15,16 @@ class Subscription: url: str id: str # TODO not sure about it... # eh, not all of them got reasonable 'created' time - created_at: Optional[datetime_aware] + created_at: datetime_aware | None subscribed: bool = True # snapshot of subscriptions at time -SubscriptionState = Tuple[datetime_aware, Sequence[Subscription]] +SubscriptionState = tuple[datetime_aware, Sequence[Subscription]] @warn_if_empty -def compute_subscriptions(*sources: Iterable[SubscriptionState]) -> List[Subscription]: +def compute_subscriptions(*sources: Iterable[SubscriptionState]) -> list[Subscription]: """ Keeps track of everything I ever subscribed to. In addition, keeps track of unsubscribed as well (so you'd remember when and why you unsubscribed) @@ -30,7 +32,7 @@ def compute_subscriptions(*sources: Iterable[SubscriptionState]) -> List[Subscri states = list(chain.from_iterable(sources)) # TODO keep 'source'/'provider'/'service' attribute? - by_url: Dict[str, Subscription] = {} + by_url: dict[str, Subscription] = {} # ah. dates are used for sorting for _when, state in sorted(states): # TODO use 'when'? diff --git a/my/rss/feedbin.py b/my/rss/feedbin.py index dc13a17..5f4da0a 100644 --- a/my/rss/feedbin.py +++ b/my/rss/feedbin.py @@ -3,15 +3,15 @@ Feedbin RSS reader """ import json +from collections.abc import Iterator, Sequence from pathlib import Path -from typing import Iterator, Sequence -from my.core import get_files, stat, Stats +from my.core import Stats, get_files, stat from my.core.compat import fromisoformat + from .common import Subscription, SubscriptionState -from my.config import feedbin as config - +from my.config import feedbin as config # isort: skip def inputs() -> Sequence[Path]: return get_files(config.export_path) diff --git a/my/rss/feedly.py b/my/rss/feedly.py index 127ef61..9bf5429 100644 --- a/my/rss/feedly.py +++ b/my/rss/feedly.py @@ -4,9 +4,10 @@ Feedly RSS reader import json from abc import abstractmethod +from collections.abc import Iterator, Sequence from datetime import datetime, timezone from pathlib import Path -from typing import Iterator, Protocol, Sequence +from typing import Protocol from my.core import Paths, get_files diff --git a/my/rtm.py b/my/rtm.py index b559ba4..217c969 100644 --- a/my/rtm.py +++ b/my/rtm.py @@ -6,21 +6,19 @@ REQUIRES = [ 'icalendar', ] +import re +from collections.abc import Iterator from datetime import datetime from functools import cached_property -import re -from typing import Dict, List, Iterator -from my.core import make_logger, get_files -from my.core.utils.itertools import make_dict - -from my.config import rtm as config - - -from more_itertools import bucket import icalendar # type: ignore from icalendar.cal import Todo # type: ignore +from more_itertools import bucket +from my.core import get_files, make_logger +from my.core.utils.itertools import make_dict + +from my.config import rtm as config # isort: skip logger = make_logger(__name__) @@ -32,14 +30,14 @@ class MyTodo: self.revision = revision @cached_property - def notes(self) -> List[str]: + def notes(self) -> list[str]: # TODO can there be multiple?? desc = self.todo['DESCRIPTION'] notes = re.findall(r'---\n\n(.*?)\n\nUpdated:', desc, flags=re.DOTALL) return notes @cached_property - def tags(self) -> List[str]: + def tags(self) -> list[str]: desc = self.todo['DESCRIPTION'] [tags_str] = re.findall(r'\nTags: (.*?)\n', desc, flags=re.DOTALL) if tags_str == 'none': @@ -92,11 +90,11 @@ class DAL: for t in self.cal.walk('VTODO'): yield MyTodo(t, self.revision) - def get_todos_by_uid(self) -> Dict[str, MyTodo]: + def get_todos_by_uid(self) -> dict[str, MyTodo]: todos = self.all_todos() return make_dict(todos, key=lambda t: t.uid) - def get_todos_by_title(self) -> Dict[str, List[MyTodo]]: + def get_todos_by_title(self) -> dict[str, list[MyTodo]]: todos = self.all_todos() bucketed = bucket(todos, lambda todo: todo.title) return {k: list(bucketed[k]) for k in bucketed} diff --git a/my/runnerup.py b/my/runnerup.py index a21075a..f5d7d1e 100644 --- a/my/runnerup.py +++ b/my/runnerup.py @@ -6,17 +6,15 @@ REQUIRES = [ 'python-tcxparser', ] +from collections.abc import Iterable from datetime import timedelta from pathlib import Path -from typing import Iterable - -from my.core import Res, get_files, Json -from my.core.compat import fromisoformat import tcxparser # type: ignore[import-untyped] from my.config import runnerup as config - +from my.core import Json, Res, get_files +from my.core.compat import fromisoformat # TODO later, use a proper namedtuple? Workout = Json @@ -70,6 +68,8 @@ def workouts() -> Iterable[Res[Workout]]: from .core.pandas import DataFrameT, check_dataframe, error_to_row + + @check_dataframe def dataframe() -> DataFrameT: def it(): @@ -85,6 +85,8 @@ def dataframe() -> DataFrameT: return df -from .core import stat, Stats +from .core import Stats, stat + + def stats() -> Stats: return stat(dataframe) diff --git a/my/simple.py b/my/simple.py index 7462291..b7f25cd 100644 --- a/my/simple.py +++ b/my/simple.py @@ -1,12 +1,11 @@ ''' Just a demo module for testing and documentation purposes ''' +from collections.abc import Iterator from dataclasses import dataclass -from typing import Iterator - -from my.core import make_config from my.config import simple as user_config +from my.core import make_config @dataclass diff --git a/my/smscalls.py b/my/smscalls.py index 78bf7ee..ccaac72 100644 --- a/my/smscalls.py +++ b/my/smscalls.py @@ -2,6 +2,7 @@ Phone calls and SMS messages Exported using https://play.google.com/store/apps/details?id=com.riteshsahu.SMSBackupRestore&hl=en_US """ +from __future__ import annotations # See: https://www.synctech.com.au/sms-backup-restore/fields-in-xml-backup-files/ for schema @@ -9,8 +10,9 @@ REQUIRES = ['lxml'] from dataclasses import dataclass -from my.core import get_files, stat, Paths, Stats from my.config import smscalls as user_config +from my.core import Paths, Stats, get_files, stat + @dataclass class smscalls(user_config): @@ -18,11 +20,13 @@ class smscalls(user_config): export_path: Paths from my.core.cfg import make_config + config = make_config(smscalls) +from collections.abc import Iterator from datetime import datetime, timezone from pathlib import Path -from typing import NamedTuple, Iterator, Set, Tuple, Optional, Any, Dict, List +from typing import Any, NamedTuple import lxml.etree as etree @@ -33,7 +37,7 @@ class Call(NamedTuple): dt: datetime dt_readable: str duration_s: int - who: Optional[str] + who: str | None # type - 1 = Incoming, 2 = Outgoing, 3 = Missed, 4 = Voicemail, 5 = Rejected, 6 = Refused List. call_type: int @@ -50,7 +54,7 @@ class Call(NamedTuple): # All the field values are read as-is from the underlying database and no conversion is done by the app in most cases. # # The '(Unknown)' is just what my android phone does, not sure if there are others -UNKNOWN: Set[str] = {'(Unknown)'} +UNKNOWN: set[str] = {'(Unknown)'} def _extract_calls(path: Path) -> Iterator[Res[Call]]: @@ -83,7 +87,7 @@ def calls() -> Iterator[Res[Call]]: files = get_files(config.export_path, glob='calls-*.xml') # TODO always replacing with the latter is good, we get better contact names?? - emitted: Set[datetime] = set() + emitted: set[datetime] = set() for p in files: for c in _extract_calls(p): if isinstance(c, Exception): @@ -98,7 +102,7 @@ def calls() -> Iterator[Res[Call]]: class Message(NamedTuple): dt: datetime dt_readable: str - who: Optional[str] + who: str | None message: str phone_number: str # type - 1 = Received, 2 = Sent, 3 = Draft, 4 = Outbox, 5 = Failed, 6 = Queued @@ -112,7 +116,7 @@ class Message(NamedTuple): def messages() -> Iterator[Res[Message]]: files = get_files(config.export_path, glob='sms-*.xml') - emitted: Set[Tuple[datetime, Optional[str], bool]] = set() + emitted: set[tuple[datetime, str | None, bool]] = set() for p in files: for c in _extract_messages(p): if isinstance(c, Exception): @@ -155,20 +159,20 @@ class MMSContentPart(NamedTuple): sequence_index: int content_type: str filename: str - text: Optional[str] - data: Optional[str] + text: str | None + data: str | None class MMS(NamedTuple): dt: datetime dt_readable: str - parts: List[MMSContentPart] + parts: list[MMSContentPart] # NOTE: these is often something like 'Name 1, Name 2', but might be different depending on your client - who: Optional[str] + who: str | None # NOTE: This can be a single phone number, or multiple, split by '~' or ','. Its better to think # of this as a 'key' or 'conversation ID', phone numbers are also present in 'addresses' phone_number: str - addresses: List[Tuple[str, int]] + addresses: list[tuple[str, int]] # 1 = Received, 2 = Sent, 3 = Draft, 4 = Outbox message_type: int @@ -194,7 +198,7 @@ class MMS(NamedTuple): def mms() -> Iterator[Res[MMS]]: files = get_files(config.export_path, glob='sms-*.xml') - emitted: Set[Tuple[datetime, Optional[str], str]] = set() + emitted: set[tuple[datetime, str | None, str]] = set() for p in files: for c in _extract_mms(p): if isinstance(c, Exception): @@ -207,7 +211,7 @@ def mms() -> Iterator[Res[MMS]]: yield c -def _resolve_null_str(value: Optional[str]) -> Optional[str]: +def _resolve_null_str(value: str | None) -> str | None: if value is None: return None # hmm.. theres some risk of the text actually being 'null', but theres @@ -235,7 +239,7 @@ def _extract_mms(path: Path) -> Iterator[Res[MMS]]: yield RuntimeError(f'Missing one or more required attributes [date, readable_date, msg_box, address] in {mxml_str}') continue - addresses: List[Tuple[str, int]] = [] + addresses: list[tuple[str, int]] = [] for addr_parent in mxml.findall('addrs'): for addr in addr_parent.findall('addr'): addr_data = addr.attrib @@ -250,7 +254,7 @@ def _extract_mms(path: Path) -> Iterator[Res[MMS]]: continue addresses.append((user_address, int(user_type))) - content: List[MMSContentPart] = [] + content: list[MMSContentPart] = [] for part_root in mxml.findall('parts'): @@ -267,8 +271,8 @@ def _extract_mms(path: Path) -> Iterator[Res[MMS]]: # # man, attrib is some internal cpython ._Attrib type which can't # be typed by any sort of mappingproxy. maybe a protocol could work..? - part_data: Dict[str, Any] = part.attrib # type: ignore - seq: Optional[str] = part_data.get('seq') + part_data: dict[str, Any] = part.attrib # type: ignore + seq: str | None = part_data.get('seq') if seq == '-1': continue @@ -276,13 +280,13 @@ def _extract_mms(path: Path) -> Iterator[Res[MMS]]: yield RuntimeError(f'seq must be a number, was seq={seq} {type(seq)} in {part_data}') continue - charset_type: Optional[str] = _resolve_null_str(part_data.get('ct')) - filename: Optional[str] = _resolve_null_str(part_data.get('name')) + charset_type: str | None = _resolve_null_str(part_data.get('ct')) + filename: str | None = _resolve_null_str(part_data.get('name')) # in some cases (images, cards), the filename is set in 'cl' instead if filename is None: filename = _resolve_null_str(part_data.get('cl')) - text: Optional[str] = _resolve_null_str(part_data.get('text')) - data: Optional[str] = _resolve_null_str(part_data.get('data')) + text: str | None = _resolve_null_str(part_data.get('text')) + data: str | None = _resolve_null_str(part_data.get('data')) if charset_type is None or filename is None or (text is None and data is None): yield RuntimeError(f'Missing one or more required attributes [ct, name, (text, data)] must be present in {part_data}') diff --git a/my/stackexchange/gdpr.py b/my/stackexchange/gdpr.py index 5292bef..78987be 100644 --- a/my/stackexchange/gdpr.py +++ b/my/stackexchange/gdpr.py @@ -6,8 +6,11 @@ Stackexchange data (uses [[https://stackoverflow.com/legal/gdpr/request][officia ### config from dataclasses import dataclass + from my.config import stackexchange as user_config -from my.core import PathIsh, make_config, get_files, Json +from my.core import Json, PathIsh, get_files, make_config + + @dataclass class stackexchange(user_config): gdpr_path: PathIsh # path to GDPR zip file @@ -17,9 +20,13 @@ config = make_config(stackexchange) # TODO just merge all of them and then filter?.. not sure -from my.core.compat import fromisoformat -from typing import NamedTuple, Iterable +from collections.abc import Iterable from datetime import datetime +from typing import NamedTuple + +from my.core.compat import fromisoformat + + class Vote(NamedTuple): j: Json # todo ip? @@ -62,7 +69,10 @@ class Vote(NamedTuple): # todo expose vote type? import json + from ..core.error import Res + + def votes() -> Iterable[Res[Vote]]: # TODO there is also some site specific stuff in qa/ directory.. not sure if its' more detailed # todo should be defensive? not sure if present when user has no votes @@ -74,6 +84,8 @@ def votes() -> Iterable[Res[Vote]]: yield Vote(r) -from ..core import stat, Stats +from ..core import Stats, stat + + def stats() -> Stats: return stat(votes) diff --git a/my/stackexchange/stexport.py b/my/stackexchange/stexport.py index 812a155..111ed28 100644 --- a/my/stackexchange/stexport.py +++ b/my/stackexchange/stexport.py @@ -16,7 +16,8 @@ from my.core import ( make_config, stat, ) -import my.config + +import my.config # isort: skip @dataclass diff --git a/my/taplog.py b/my/taplog.py index 51eeb72..5e64a72 100644 --- a/my/taplog.py +++ b/my/taplog.py @@ -1,24 +1,26 @@ ''' [[https://play.google.com/store/apps/details?id=com.waterbear.taglog][Taplog]] app data ''' -from datetime import datetime -from typing import NamedTuple, Dict, Optional, Iterable +from __future__ import annotations -from my.core import get_files, stat, Stats -from my.core.sqlite import sqlite_connection +from collections.abc import Iterable +from datetime import datetime +from typing import NamedTuple from my.config import taplog as user_config +from my.core import Stats, get_files, stat +from my.core.sqlite import sqlite_connection class Entry(NamedTuple): - row: Dict + row: dict @property def id(self) -> str: return str(self.row['_id']) @property - def number(self) -> Optional[float]: + def number(self) -> float | None: ns = self.row['number'] # TODO ?? if isinstance(ns, str): diff --git a/my/telegram/telegram_backup.py b/my/telegram/telegram_backup.py index ff4f904..eea7e50 100644 --- a/my/telegram/telegram_backup.py +++ b/my/telegram/telegram_backup.py @@ -1,17 +1,17 @@ """ Telegram data via [fabianonline/telegram_backup](https://github.com/fabianonline/telegram_backup) tool """ +from __future__ import annotations +import sqlite3 +from collections.abc import Iterator from dataclasses import dataclass from datetime import datetime, timezone -from struct import unpack_from, calcsize -import sqlite3 -from typing import Dict, Iterator, Optional - -from my.core import datetime_aware, PathIsh -from my.core.sqlite import sqlite_connection +from struct import calcsize, unpack_from from my.config import telegram as user_config +from my.core import PathIsh, datetime_aware +from my.core.sqlite import sqlite_connection @dataclass @@ -23,17 +23,17 @@ class config(user_config.telegram_backup): @dataclass class Chat: id: str - name: Optional[str] + name: str | None # not all users have short handle + groups don't have them either? # TODO hmm some groups have it -- it's just the tool doesn't dump them?? - handle: Optional[str] + handle: str | None # not sure if need type? @dataclass class User: id: str - name: Optional[str] + name: str | None @dataclass @@ -44,7 +44,7 @@ class Message: chat: Chat sender: User text: str - extra_media_info: Optional[str] = None + extra_media_info: str | None = None @property def permalink(self) -> str: @@ -61,7 +61,7 @@ class Message: -Chats = Dict[str, Chat] +Chats = dict[str, Chat] def _message_from_row(r: sqlite3.Row, *, chats: Chats, with_extra_media_info: bool) -> Message: ts = r['time'] # desktop export uses UTC (checked by exporting in winter time vs summer time) @@ -70,7 +70,7 @@ def _message_from_row(r: sqlite3.Row, *, chats: Chats, with_extra_media_info: bo chat = chats[r['source_id']] sender = chats[r['sender_id']] - extra_media_info: Optional[str] = None + extra_media_info: str | None = None if with_extra_media_info and r['has_media'] == 1: # also it's quite hacky, so at least for now it's just an optional attribute behind the flag # defensive because it's a bit tricky to correctly parse without a proper api parser.. @@ -90,7 +90,7 @@ def _message_from_row(r: sqlite3.Row, *, chats: Chats, with_extra_media_info: bo ) -def messages(*, extra_where: Optional[str]=None, with_extra_media_info: bool=False) -> Iterator[Message]: +def messages(*, extra_where: str | None=None, with_extra_media_info: bool=False) -> Iterator[Message]: messages_query = 'SELECT * FROM messages WHERE message_type NOT IN ("service_message", "empty_message")' if extra_where is not None: messages_query += ' AND ' + extra_where @@ -106,7 +106,7 @@ def messages(*, extra_where: Optional[str]=None, with_extra_media_info: bool=Fal for r in db.execute('SELECT * FROM users ORDER BY id'): first = r["first_name"] last = r["last_name"] - name: Optional[str] + name: str | None if first is not None and last is not None: name = f'{first} {last}' else: @@ -121,7 +121,7 @@ def messages(*, extra_where: Optional[str]=None, with_extra_media_info: bool=Fal yield _message_from_row(r, chats=chats, with_extra_media_info=with_extra_media_info) -def _extract_extra_media_info(data: bytes) -> Optional[str]: +def _extract_extra_media_info(data: bytes) -> str | None: # ugh... very hacky, but it does manage to extract from 90% of messages that have media pos = 0 diff --git a/my/tests/bluemaestro.py b/my/tests/bluemaestro.py index 2d7c81e..d139a8f 100644 --- a/my/tests/bluemaestro.py +++ b/my/tests/bluemaestro.py @@ -1,4 +1,4 @@ -from typing import Iterator +from collections.abc import Iterator import pytest from more_itertools import one diff --git a/my/tests/body/weight.py b/my/tests/body/weight.py index 069e940..f26ccf2 100644 --- a/my/tests/body/weight.py +++ b/my/tests/body/weight.py @@ -1,8 +1,10 @@ from pathlib import Path -import pytz -from my.core.cfg import tmp_config + import pytest +import pytz + from my.body.weight import from_orgmode +from my.core.cfg import tmp_config def test_body_weight() -> None: diff --git a/my/tests/commits.py b/my/tests/commits.py index c967027..48e349f 100644 --- a/my/tests/commits.py +++ b/my/tests/commits.py @@ -1,14 +1,11 @@ import os from pathlib import Path -from more_itertools import bucket import pytest - - -from my.core.cfg import tmp_config +from more_itertools import bucket from my.coding.commits import commits - +from my.core.cfg import tmp_config pytestmark = pytest.mark.skipif( os.name == 'nt', diff --git a/my/tests/location/fallback.py b/my/tests/location/fallback.py index 10a4e5b..c09b902 100644 --- a/my/tests/location/fallback.py +++ b/my/tests/location/fallback.py @@ -2,8 +2,8 @@ To test my.location.fallback_location.all """ +from collections.abc import Iterator from datetime import datetime, timedelta, timezone -from typing import Iterator import pytest from more_itertools import ilen diff --git a/my/tests/reddit.py b/my/tests/reddit.py index 4f1ec51..4ddccf8 100644 --- a/my/tests/reddit.py +++ b/my/tests/reddit.py @@ -1,16 +1,14 @@ import pytest from more_itertools import consume -from my.core.cfg import tmp_config -from my.core.utils.itertools import ensure_unique - -from .common import testdata - - # deliberately use mixed style imports on the top level and inside the methods to test tmp_config stuff # todo won't really be necessary once we migrate to lazy user config import my.reddit.all as my_reddit_all import my.reddit.rexport as my_reddit_rexport +from my.core.cfg import tmp_config +from my.core.utils.itertools import ensure_unique + +from .common import testdata def test_basic_1() -> None: diff --git a/my/time/tz/common.py b/my/time/tz/common.py index 13c8ac0..c0dd262 100644 --- a/my/time/tz/common.py +++ b/my/time/tz/common.py @@ -3,7 +3,6 @@ from typing import Callable, Literal, cast from my.core import datetime_aware - ''' Depending on the specific data provider and your level of paranoia you might expect different behaviour.. E.g.: - if your objects already have tz info, you might not need to call localize() at all diff --git a/my/time/tz/main.py b/my/time/tz/main.py index fafc5fe..bdd36b1 100644 --- a/my/time/tz/main.py +++ b/my/time/tz/main.py @@ -6,6 +6,7 @@ from datetime import datetime from my.core import datetime_aware + # todo hmm, kwargs isn't mypy friendly.. but specifying types would require duplicating default args. uhoh def localize(dt: datetime, **kwargs) -> datetime_aware: # todo document patterns for combining multiple data sources diff --git a/my/time/tz/via_location.py b/my/time/tz/via_location.py index 4920333..58b5bf7 100644 --- a/my/time/tz/via_location.py +++ b/my/time/tz/via_location.py @@ -2,6 +2,8 @@ Timezone data provider, guesses timezone based on location data (e.g. GPS) ''' +from __future__ import annotations + REQUIRES = [ # for determining timezone by coordinate 'timezonefinder', @@ -10,6 +12,7 @@ REQUIRES = [ import heapq import os from collections import Counter +from collections.abc import Iterable, Iterator from dataclasses import dataclass from datetime import date, datetime from functools import lru_cache @@ -17,14 +20,7 @@ from itertools import groupby from typing import ( TYPE_CHECKING, Any, - Dict, - Iterable, - Iterator, - List, - Optional, Protocol, - Set, - Tuple, ) import pytz @@ -102,7 +98,7 @@ def _timezone_finder(*, fast: bool) -> Any: # for backwards compatibility -def _locations() -> Iterator[Tuple[LatLon, datetime_aware]]: +def _locations() -> Iterator[tuple[LatLon, datetime_aware]]: try: import my.location.all @@ -125,7 +121,7 @@ def _locations() -> Iterator[Tuple[LatLon, datetime_aware]]: # TODO: could use heapmerge or sort the underlying iterators somehow? # see https://github.com/karlicoss/HPI/pull/237#discussion_r858372934 -def _sorted_locations() -> List[Tuple[LatLon, datetime_aware]]: +def _sorted_locations() -> list[tuple[LatLon, datetime_aware]]: return sorted(_locations(), key=lambda x: x[1]) @@ -140,7 +136,7 @@ class DayWithZone: zone: Zone -def _find_tz_for_locs(finder: Any, locs: Iterable[Tuple[LatLon, datetime]]) -> Iterator[DayWithZone]: +def _find_tz_for_locs(finder: Any, locs: Iterable[tuple[LatLon, datetime]]) -> Iterator[DayWithZone]: for (lat, lon), dt in locs: # TODO right. its _very_ slow... zone = finder.timezone_at(lat=lat, lng=lon) @@ -172,7 +168,7 @@ def _iter_local_dates() -> Iterator[DayWithZone]: # TODO: warnings doesn't actually warn? # warnings = [] - locs: Iterable[Tuple[LatLon, datetime]] + locs: Iterable[tuple[LatLon, datetime]] locs = _sorted_locations() if cfg.sort_locations else _locations() yield from _find_tz_for_locs(finder, locs) @@ -187,7 +183,7 @@ def _iter_local_dates_fallback() -> Iterator[DayWithZone]: cfg = make_config() - def _fallback_locations() -> Iterator[Tuple[LatLon, datetime]]: + def _fallback_locations() -> Iterator[tuple[LatLon, datetime]]: for loc in sorted(flocs(), key=lambda x: x.dt): yield ((loc.lat, loc.lon), loc.dt) @@ -225,14 +221,14 @@ def _iter_tzs() -> Iterator[DayWithZone]: # we need to sort them first before we can do a groupby by_day = lambda p: p.day - local_dates: List[DayWithZone] = sorted(_iter_local_dates(), key=by_day) + local_dates: list[DayWithZone] = sorted(_iter_local_dates(), key=by_day) logger.debug(f"no. of items using exact locations: {len(local_dates)}") - local_dates_fallback: List[DayWithZone] = sorted(_iter_local_dates_fallback(), key=by_day) + local_dates_fallback: list[DayWithZone] = sorted(_iter_local_dates_fallback(), key=by_day) # find days that are in fallback but not in local_dates (i.e., missing days) - local_dates_set: Set[date] = {d.day for d in local_dates} - use_fallback_days: List[DayWithZone] = [d for d in local_dates_fallback if d.day not in local_dates_set] + local_dates_set: set[date] = {d.day for d in local_dates} + use_fallback_days: list[DayWithZone] = [d for d in local_dates_fallback if d.day not in local_dates_set] logger.debug(f"no. of items being used from fallback locations: {len(use_fallback_days)}") # combine local_dates and missing days from fallback into a sorted list @@ -246,20 +242,20 @@ def _iter_tzs() -> Iterator[DayWithZone]: @lru_cache(1) -def _day2zone() -> Dict[date, pytz.BaseTzInfo]: +def _day2zone() -> dict[date, pytz.BaseTzInfo]: # NOTE: kinda unfortunate that this will have to process all days before returning result for just one # however otherwise cachew cache might never be initialized properly # so we'll always end up recomputing everyting during subsequent runs return {dz.day: pytz.timezone(dz.zone) for dz in _iter_tzs()} -def _get_day_tz(d: date) -> Optional[pytz.BaseTzInfo]: +def _get_day_tz(d: date) -> pytz.BaseTzInfo | None: return _day2zone().get(d) # ok to cache, there are only a few home locations? @lru_cache(None) -def _get_home_tz(loc: LatLon) -> Optional[pytz.BaseTzInfo]: +def _get_home_tz(loc: LatLon) -> pytz.BaseTzInfo | None: (lat, lng) = loc finder = _timezone_finder(fast=False) # ok to use slow here for better precision zone = finder.timezone_at(lat=lat, lng=lng) @@ -270,7 +266,7 @@ def _get_home_tz(loc: LatLon) -> Optional[pytz.BaseTzInfo]: return pytz.timezone(zone) -def get_tz(dt: datetime) -> Optional[pytz.BaseTzInfo]: +def get_tz(dt: datetime) -> pytz.BaseTzInfo | None: ''' Given a datetime, returns the timezone for that date. ''' diff --git a/my/tinder/android.py b/my/tinder/android.py index d9b256b..a09794f 100644 --- a/my/tinder/android.py +++ b/my/tinder/android.py @@ -3,20 +3,22 @@ Tinder data from Android app database (in =/data/data/com.tinder/databases/tinde """ from __future__ import annotations -from collections import defaultdict, Counter +import sqlite3 +from collections import Counter, defaultdict +from collections.abc import Iterator, Mapping, Sequence from dataclasses import dataclass from datetime import datetime, timezone from itertools import chain from pathlib import Path -import sqlite3 -from typing import Sequence, Iterator, Union, Dict, List, Mapping +from typing import Union -from my.core import Paths, get_files, Res, stat, Stats, datetime_aware, make_logger +from my.core import Paths, Res, Stats, datetime_aware, get_files, make_logger, stat from my.core.common import unique_everseen from my.core.compat import assert_never from my.core.error import echain from my.core.sqlite import sqlite_connection -import my.config + +import my.config # isort: skip logger = make_logger(__name__) @@ -164,8 +166,8 @@ def _parse_msg(row: sqlite3.Row) -> _Message: # todo maybe it's rich_entities method? def entities() -> Iterator[Res[Entity]]: - id2person: Dict[str, Person] = {} - id2match: Dict[str, Match] = {} + id2person: dict[str, Person] = {} + id2match: dict[str, Match] = {} for x in unique_everseen(_entities): if isinstance(x, Exception): yield x @@ -217,7 +219,7 @@ def messages() -> Iterator[Res[Message]]: # todo not sure, maybe it's not fundamental enough to keep here... def match2messages() -> Iterator[Res[Mapping[Match, Sequence[Message]]]]: - res: Dict[Match, List[Message]] = defaultdict(list) + res: dict[Match, list[Message]] = defaultdict(list) for x in entities(): if isinstance(x, Exception): yield x diff --git a/my/topcoder.py b/my/topcoder.py index 07f71be..56403e2 100644 --- a/my/topcoder.py +++ b/my/topcoder.py @@ -1,14 +1,14 @@ +import json +from collections.abc import Iterator, Sequence from dataclasses import dataclass from functools import cached_property -import json from pathlib import Path -from typing import Iterator, Sequence -from my.core import get_files, Res, datetime_aware +from my.core import Res, datetime_aware, get_files from my.core.compat import fromisoformat from my.experimental.destructive_parsing import Manager -from my.config import topcoder as config # type: ignore[attr-defined] +from my.config import topcoder as config # type: ignore[attr-defined] # isort: skip def inputs() -> Sequence[Path]: diff --git a/my/twitter/all.py b/my/twitter/all.py index 4714021..c2c471e 100644 --- a/my/twitter/all.py +++ b/my/twitter/all.py @@ -1,11 +1,11 @@ """ Unified Twitter data (merged from the archive and periodic updates) """ -from typing import Iterator +from collections.abc import Iterator + from ..core import Res from ..core.source import import_source -from .common import merge_tweets, Tweet - +from .common import Tweet, merge_tweets # NOTE: you can comment out the sources you don't need src_twint = import_source(module_name='my.twitter.twint') diff --git a/my/twitter/android.py b/my/twitter/android.py index ada04ae..88c9389 100644 --- a/my/twitter/android.py +++ b/my/twitter/android.py @@ -4,21 +4,21 @@ Twitter data from official app for Android from __future__ import annotations +import re +from collections.abc import Iterator, Sequence from dataclasses import dataclass from datetime import datetime, timezone from pathlib import Path -import re from struct import unpack_from -from typing import Iterator, Sequence, Set -from my.core import datetime_aware, get_files, LazyLogger, Paths, Res +from my.core import LazyLogger, Paths, Res, datetime_aware, get_files from my.core.common import unique_everseen from my.core.sqlite import sqlite_connect_immutable -import my.config - from .common import permalink +import my.config # isort: skip + logger = LazyLogger(__name__) @@ -155,7 +155,7 @@ _SELECT_OWN_TWEETS = '_SELECT_OWN_TWEETS' def get_own_user_id(conn) -> str: # unclear what's the reliable way to query it, so we use multiple different ones and arbitrate # NOTE: 'SELECT DISTINCT ev_owner_id FROM lists' doesn't work, might include lists from other people? - res: Set[str] = set() + res: set[str] = set() # need to cast as it's int by default for q in [ 'SELECT DISTINCT CAST(list_mapping_user_id AS TEXT) FROM list_mapping', @@ -239,7 +239,7 @@ def _process_one(f: Path, *, where: str) -> Iterator[Res[Tweet]]: NOT (statuses.in_r_user_id == -1 AND statuses.in_r_status_id == -1 AND statuses.conversation_id == 0) ''' - def _query_one(*, where: str, quoted: Set[int]) -> Iterator[Res[Tweet]]: + def _query_one(*, where: str, quoted: set[int]) -> Iterator[Res[Tweet]]: for ( tweet_id, user_username, @@ -263,7 +263,7 @@ def _process_one(f: Path, *, where: str) -> Iterator[Res[Tweet]]: text=content, ) - quoted: Set[int] = set() + quoted: set[int] = set() yield from _query_one(where=db_where, quoted=quoted) # get quoted tweets 'recursively' # TODO maybe do it for favs/bookmarks too? not sure diff --git a/my/twitter/archive.py b/my/twitter/archive.py index 1573754..c9d2dbc 100644 --- a/my/twitter/archive.py +++ b/my/twitter/archive.py @@ -7,6 +7,7 @@ from __future__ import annotations import html import json # hmm interesting enough, orjson didn't give much speedup here? from abc import abstractmethod +from collections.abc import Iterator, Sequence from dataclasses import dataclass from datetime import datetime from functools import cached_property @@ -14,8 +15,6 @@ from itertools import chain from pathlib import Path from typing import ( TYPE_CHECKING, - Iterator, - Sequence, ) from more_itertools import unique_everseen diff --git a/my/twitter/common.py b/my/twitter/common.py index 258216f..8c346f6 100644 --- a/my/twitter/common.py +++ b/my/twitter/common.py @@ -1,17 +1,19 @@ -from my.core import __NOT_HPI_MODULE__ +from my.core import __NOT_HPI_MODULE__ # isort: skip +from collections.abc import Iterator from itertools import chain -from typing import Iterator, Any +from typing import Any from more_itertools import unique_everseen - # TODO add proper Protocol for Tweet Tweet = Any TweetId = str -from my.core import warn_if_empty, Res +from my.core import Res, warn_if_empty + + @warn_if_empty def merge_tweets(*sources: Iterator[Res[Tweet]]) -> Iterator[Res[Tweet]]: def key(r: Res[Tweet]): diff --git a/my/twitter/talon.py b/my/twitter/talon.py index 1b79727..dbf2e2e 100644 --- a/my/twitter/talon.py +++ b/my/twitter/talon.py @@ -7,10 +7,11 @@ from __future__ import annotations import re import sqlite3 from abc import abstractmethod +from collections.abc import Iterator, Sequence from dataclasses import dataclass from datetime import datetime, timezone from pathlib import Path -from typing import Iterator, Sequence, Union +from typing import Union from my.core import Paths, Res, datetime_aware, get_files from my.core.common import unique_everseen diff --git a/my/twitter/twint.py b/my/twitter/twint.py index ceb5406..5106923 100644 --- a/my/twitter/twint.py +++ b/my/twitter/twint.py @@ -1,17 +1,17 @@ """ Twitter data (tweets and favorites). Uses [[https://github.com/twintproject/twint][Twint]] data export. """ +from collections.abc import Iterator from dataclasses import dataclass from datetime import datetime, timezone from pathlib import Path -from typing import NamedTuple, Iterator, List +from typing import NamedTuple - -from my.core import Paths, Res, get_files, LazyLogger, Json, datetime_aware, stat, Stats +from my.core import Json, LazyLogger, Paths, Res, Stats, datetime_aware, get_files, stat from my.core.cfg import make_config from my.core.sqlite import sqlite_connection -from my.config import twint as user_config +from my.config import twint as user_config # isort: skip # TODO move to twitter.twint config structure @@ -76,7 +76,7 @@ class Tweet(NamedTuple): return text @property - def urls(self) -> List[str]: + def urls(self) -> list[str]: ustr = self.row['urls'] if len(ustr) == 0: return [] diff --git a/my/util/hpi_heartbeat.py b/my/util/hpi_heartbeat.py index 84790a4..6dcac7e 100644 --- a/my/util/hpi_heartbeat.py +++ b/my/util/hpi_heartbeat.py @@ -5,12 +5,13 @@ In particular the behaviour of import_original_module function The idea of testing is that overlays extend this module, and add their own items to items(), and the checker asserts all overlays have contributed. """ -from my.core import __NOT_HPI_MODULE__ +from my.core import __NOT_HPI_MODULE__ # isort: skip + +import sys +from collections.abc import Iterator from dataclasses import dataclass from datetime import datetime -import sys -from typing import Iterator, List NOW = datetime.now() @@ -19,10 +20,10 @@ NOW = datetime.now() class Item: dt: datetime message: str - path: List[str] + path: list[str] -def get_pkg_path() -> List[str]: +def get_pkg_path() -> list[str]: pkg = sys.modules[__package__] return list(pkg.__path__) diff --git a/my/vk/favorites.py b/my/vk/favorites.py index 9caae6d..5f278ff 100644 --- a/my/vk/favorites.py +++ b/my/vk/favorites.py @@ -1,20 +1,21 @@ # todo: uses my private export script?, timezone +from __future__ import annotations + +import json +from collections.abc import Iterable, Iterator from dataclasses import dataclass from datetime import datetime, timezone -import json -from typing import Iterator, Iterable, Optional - -from my.core import Json, datetime_aware, stat, Stats -from my.core.error import Res from my.config import vk as config # type: ignore[attr-defined] +from my.core import Json, Stats, datetime_aware, stat +from my.core.error import Res @dataclass class Favorite: dt: datetime_aware title: str - url: Optional[str] + url: str | None text: str diff --git a/my/vk/vk_messages_backup.py b/my/vk/vk_messages_backup.py index c73587f..4f593c8 100644 --- a/my/vk/vk_messages_backup.py +++ b/my/vk/vk_messages_backup.py @@ -2,18 +2,16 @@ VK data (exported by [[https://github.com/Totktonada/vk_messages_backup][Totktonada/vk_messages_backup]]) ''' # note: could reuse the original repo, but little point I guess since VK closed their API +import json +from collections.abc import Iterator from dataclasses import dataclass from datetime import datetime -import json -from typing import Dict, Iterator import pytz -from my.core import stat, Stats, Json, Res, datetime_aware, get_files -from my.core.common import unique_everseen - from my.config import vk_messages_backup as config - +from my.core import Json, Res, Stats, datetime_aware, get_files, stat +from my.core.common import unique_everseen # I think vk_messages_backup used this tz? # not sure if vk actually used to return this tz in api? @@ -45,7 +43,7 @@ class Message: body: str -Users = Dict[Uid, User] +Users = dict[Uid, User] def users() -> Users: diff --git a/my/whatsapp/android.py b/my/whatsapp/android.py index 3dfed3e..27ee743 100644 --- a/my/whatsapp/android.py +++ b/my/whatsapp/android.py @@ -3,18 +3,19 @@ Whatsapp data from Android app database (in =/data/data/com.whatsapp/databases/m """ from __future__ import annotations +import sqlite3 +from collections.abc import Iterator, Sequence from dataclasses import dataclass from datetime import datetime, timezone from pathlib import Path -import sqlite3 -from typing import Union, Sequence, Iterator, Optional +from typing import Union -from my.core import get_files, Paths, datetime_aware, Res, make_logger, make_config +from my.core import Paths, Res, datetime_aware, get_files, make_config, make_logger from my.core.common import unique_everseen from my.core.error import echain, notnone from my.core.sqlite import sqlite_connection -import my.config +import my.config # isort: skip logger = make_logger(__name__) @@ -23,7 +24,7 @@ logger = make_logger(__name__) class Config(my.config.whatsapp.android): # paths[s]/glob to the exported sqlite databases export_path: Paths - my_user_id: Optional[str] = None + my_user_id: str | None = None config = make_config(Config) @@ -38,13 +39,13 @@ class Chat: id: str # todo not sure how to support renames? # could change Chat object itself, but this won't work well with incremental processing.. - name: Optional[str] + name: str | None @dataclass(unsafe_hash=True) class Sender: id: str - name: Optional[str] + name: str | None @dataclass(unsafe_hash=True) @@ -53,7 +54,7 @@ class Message: id: str dt: datetime_aware sender: Sender - text: Optional[str] + text: str | None Entity = Union[Chat, Sender, Message] @@ -125,9 +126,9 @@ def _process_db(db: sqlite3.Connection) -> Iterator[Entity]: ts: int = notnone(r['timestamp']) dt = datetime.fromtimestamp(ts / 1000, tz=timezone.utc) - text: Optional[str] = r['text_data'] - media_file_path: Optional[str] = r['file_path'] - media_file_size: Optional[int] = r['file_size'] + text: str | None = r['text_data'] + media_file_path: str | None = r['file_path'] + media_file_size: int | None = r['file_size'] message_type = r['message_type'] diff --git a/my/youtube/takeout.py b/my/youtube/takeout.py index f29b2e3..703715f 100644 --- a/my/youtube/takeout.py +++ b/my/youtube/takeout.py @@ -1,7 +1,8 @@ from __future__ import annotations +from collections.abc import Iterable, Iterator from dataclasses import dataclass -from typing import TYPE_CHECKING, Any, Iterable, Iterator +from typing import TYPE_CHECKING, Any from my.core import Res, Stats, datetime_aware, make_logger, stat, warnings from my.core.compat import deprecated diff --git a/my/zotero.py b/my/zotero.py index 4440aae..8eb34ba 100644 --- a/my/zotero.py +++ b/my/zotero.py @@ -1,14 +1,16 @@ +from __future__ import annotations as _annotations + +import json +import sqlite3 +from collections.abc import Iterator, Sequence from dataclasses import dataclass from datetime import datetime, timezone -import json -from typing import Iterator, Optional, Dict, Any, Sequence from pathlib import Path -import sqlite3 +from typing import Any -from my.core import make_logger, Res, datetime_aware +from my.core import Res, datetime_aware, make_logger from my.core.sqlite import sqlite_copy_and_open - logger = make_logger(__name__) @@ -26,7 +28,7 @@ class Item: """Corresponds to 'Zotero item'""" file: Path title: str - url: Optional[Url] + url: Url | None tags: Sequence[str] @@ -39,8 +41,8 @@ class Annotation: page: int """0-indexed""" - text: Optional[str] - comment: Optional[str] + text: str | None + comment: str | None tags: Sequence[str] color_hex: str """Original hex-encoded color in zotero""" @@ -97,7 +99,7 @@ WHERE ID.fieldID = 13 AND IA.itemID = ? # TODO maybe exclude 'private' methods from detection? -def _query_raw() -> Iterator[Res[Dict[str, Any]]]: +def _query_raw() -> Iterator[Res[dict[str, Any]]]: [db] = inputs() with sqlite_copy_and_open(db) as conn: @@ -157,7 +159,7 @@ def _hex2human(color_hex: str) -> str: }.get(color_hex, color_hex) -def _parse_annotation(r: Dict) -> Annotation: +def _parse_annotation(r: dict) -> Annotation: text = r['text'] comment = r['comment'] # todo use json query for this? diff --git a/my/zulip/organization.py b/my/zulip/organization.py index 2e0df4b..d0cfcb7 100644 --- a/my/zulip/organization.py +++ b/my/zulip/organization.py @@ -6,11 +6,11 @@ from __future__ import annotations import json from abc import abstractmethod +from collections.abc import Iterator, Sequence from dataclasses import dataclass from datetime import datetime, timezone from itertools import count from pathlib import Path -from typing import Iterator, Sequence from my.core import ( Json, diff --git a/ruff.toml b/ruff.toml index 5fbd657..3d803e7 100644 --- a/ruff.toml +++ b/ruff.toml @@ -1,4 +1,4 @@ -target-version = "py38" # NOTE: inferred from pyproject.toml if present +target-version = "py39" # NOTE: inferred from pyproject.toml if present lint.extend-select = [ "F", # flakes rules -- default, but extend just in case @@ -26,8 +26,8 @@ lint.extend-select = [ "TID", # various imports suggestions "TRY", # various exception handling rules "UP", # detect deprecated python stdlib stuff - # "FA", # suggest using from __future__ import annotations TODO enable later after we make sure cachew works? - # "PTH", # pathlib migration -- TODO enable later + "FA", # suggest using from __future__ import annotations + "PTH", # pathlib migration "ARG", # unused argument checks # "A", # builtin shadowing -- TODO handle later # "EM", # TODO hmm could be helpful to prevent duplicate err msg in traceback.. but kinda annoying @@ -35,6 +35,11 @@ lint.extend-select = [ # "ALL", # uncomment this to check for new rules! ] +# Preserve types, even if a file imports `from __future__ import annotations` +# we need this for cachew to work with HPI types on 3.9 +# can probably remove after 3.10? +lint.pyupgrade.keep-runtime-typing = true + lint.ignore = [ "D", # annoying nags about docstrings "N", # pep naming @@ -68,11 +73,6 @@ lint.ignore = [ "F841", # Local variable `count` is assigned to but never used ### -### TODO should be fine to use these with from __future__ import annotations? -### there was some issue with cachew though... double check this? - "UP006", # use type instead of Type - "UP007", # use X | Y instead of Union -### "RUF100", # unused noqa -- handle later "RUF012", # mutable class attrs should be annotated with ClassVar... ugh pretty annoying for user configs From a2b397ec4a83e6fded7c758470c49f6f18f2ab81 Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Tue, 22 Oct 2024 20:50:37 +0100 Subject: [PATCH 114/122] my.whatsapp.android: adapt to new db format --- my/books/kobo.py | 2 +- my/whatsapp/android.py | 33 ++++++++++++++++++++++++++------- 2 files changed, 27 insertions(+), 8 deletions(-) diff --git a/my/books/kobo.py b/my/books/kobo.py index 899ef31..40b7ed7 100644 --- a/my/books/kobo.py +++ b/my/books/kobo.py @@ -3,4 +3,4 @@ from my.core import warnings warnings.high('my.books.kobo is deprecated! Please use my.kobo instead!') from my.core.util import __NOT_HPI_MODULE__ -from my.kobo import * # type: ignore[no-redef] +from my.kobo import * diff --git a/my/whatsapp/android.py b/my/whatsapp/android.py index 27ee743..3cd4436 100644 --- a/my/whatsapp/android.py +++ b/my/whatsapp/android.py @@ -1,6 +1,7 @@ """ Whatsapp data from Android app database (in =/data/data/com.whatsapp/databases/msgstore.db=) """ + from __future__ import annotations import sqlite3 @@ -63,11 +64,27 @@ Entity = Union[Chat, Sender, Message] def _process_db(db: sqlite3.Connection) -> Iterator[Entity]: # TODO later, split out Chat/Sender objects separately to safe on object creation, similar to other android data sources + try: + db.execute('SELECT jid_row_id FROM chat_view') + except sqlite3.OperationalError as oe: + if 'jid_row_id' not in str(oe): + raise oe + new_version_202410 = False + else: + new_version_202410 = True + + if new_version_202410: + chat_id_col = 'jid.raw_string' + jid_join = 'JOIN jid ON jid._id == chat_view.jid_row_id' + else: + chat_id_col = 'chat_view.raw_string_jid' + jid_join = '' + chats = {} for r in db.execute( - ''' - SELECT raw_string_jid AS chat_id, subject - FROM chat_view + f''' + SELECT {chat_id_col} AS chat_id, subject + FROM chat_view {jid_join} WHERE chat_id IS NOT NULL /* seems that it might be null for chats that are 'recycled' (the db is more like an LRU cache) */ ''' ): @@ -89,6 +106,7 @@ def _process_db(db: sqlite3.Connection) -> Iterator[Entity]: ): # TODO seems that msgstore.db doesn't have contact names # perhaps should extract from wa.db and match against wa_contacts.jid? + # TODO these can also be chats? not sure if need to include... s = Sender( id=r['raw_string'], name=None, @@ -100,9 +118,9 @@ def _process_db(db: sqlite3.Connection) -> Iterator[Entity]: # so even if it seems as if it has a column (e.g. for attachment path), there is actually no such data # so makes more sense to just query message column directly for r in db.execute( - ''' + f''' SELECT - C.raw_string_jid AS chat_id, + {chat_id_col} AS chat_id, M.key_id, M.timestamp, sender_jid_row_id, M.from_me, @@ -111,8 +129,9 @@ def _process_db(db: sqlite3.Connection) -> Iterator[Entity]: MM.file_size, M.message_type FROM message AS M - LEFT JOIN chat_view AS C ON M.chat_row_id = C._id - LEFT JOIN message_media AS MM ON M._id = MM.message_row_id + LEFT JOIN chat_view ON M.chat_row_id = chat_view._id + {jid_join} + left JOIN message_media AS MM ON M._id = MM.message_row_id WHERE M.key_id != -1 /* key_id -1 is some sort of fake message where everything is null */ /* type 7 seems to be some dummy system message. sometimes contain chat name, but usually null, so ignore them From 7ab6f0d5cbce2241ba8a7848ff1bf18e147d26cf Mon Sep 17 00:00:00 2001 From: purarue <7804791+purarue@users.noreply.github.com> Date: Fri, 25 Oct 2024 09:39:00 -0700 Subject: [PATCH 115/122] chore: update urls --- README.org | 4 ++-- doc/DENYLIST.md | 6 +++--- doc/MODULES.org | 12 ++++++------ doc/MODULE_DESIGN.org | 8 ++++---- doc/OVERLAYS.org | 2 +- doc/QUERY.md | 6 +++--- doc/SETUP.org | 2 +- misc/.flake8-karlicoss | 2 +- my/browser/active_browser.py | 2 +- my/browser/export.py | 2 +- my/google/takeout/parser.py | 10 +++++----- my/ip/all.py | 4 ++-- my/ip/common.py | 2 +- my/location/fallback/via_ip.py | 2 +- my/location/google_takeout.py | 2 +- my/location/google_takeout_semantic.py | 2 +- my/location/via_ip.py | 2 +- my/reddit/pushshift.py | 6 +++--- 18 files changed, 38 insertions(+), 38 deletions(-) diff --git a/README.org b/README.org index c065a0c..79621a5 100644 --- a/README.org +++ b/README.org @@ -723,10 +723,10 @@ If you want to write modules for personal use but don't want to merge them into Other HPI Repositories: -- [[https://github.com/seanbreckenridge/HPI][seanbreckenridge/HPI]] +- [[https://github.com/purarue/HPI][purarue/HPI]] - [[https://github.com/madelinecameron/hpi][madelinecameron/HPI]] -If you want to create your own to create your own modules/override something here, you can use the [[https://github.com/seanbreckenridge/HPI-template][template]]. +If you want to create your own to create your own modules/override something here, you can use the [[https://github.com/purarue/HPI-template][template]]. * Related links :PROPERTIES: diff --git a/doc/DENYLIST.md b/doc/DENYLIST.md index 440715c..3d8dea0 100644 --- a/doc/DENYLIST.md +++ b/doc/DENYLIST.md @@ -76,7 +76,7 @@ This would typically be used in an overridden `all.py` file, or in a one-off scr which you may want to filter out some items from a source, progressively adding more items to the denylist as you go. -A potential `my/ip/all.py` file might look like (Sidenote: `discord` module from [here](https://github.com/seanbreckenridge/HPI)): +A potential `my/ip/all.py` file might look like (Sidenote: `discord` module from [here](https://github.com/purarue/HPI)): ```python from typing import Iterator @@ -119,9 +119,9 @@ python3 -c 'from my.ip import all; all.deny.deny_cli(all.ips())' To edit the `all.py`, you could either: - install it as editable (`python3 -m pip install --user -e ./HPI`), and then edit the file directly -- or, create a namespace package, which splits the package across multiple directories. For info on that see [`MODULE_DESIGN`](https://github.com/karlicoss/HPI/blob/master/doc/MODULE_DESIGN.org#namespace-packages), [`reorder_editable`](https://github.com/seanbreckenridge/reorder_editable), and possibly the [`HPI-template`](https://github.com/seanbreckenridge/HPI-template) to create your own HPI namespace package to create your own `all.py` file. +- or, create a namespace package, which splits the package across multiple directories. For info on that see [`MODULE_DESIGN`](https://github.com/karlicoss/HPI/blob/master/doc/MODULE_DESIGN.org#namespace-packages), [`reorder_editable`](https://github.com/purarue/reorder_editable), and possibly the [`HPI-template`](https://github.com/purarue/HPI-template) to create your own HPI namespace package to create your own `all.py` file. -For a real example of this see, [seanbreckenridge/HPI-personal](https://github.com/seanbreckenridge/HPI-personal/blob/master/my/ip/all.py) +For a real example of this see, [purarue/HPI-personal](https://github.com/purarue/HPI-personal/blob/master/my/ip/all.py) Sidenote: the reason why we want to specifically override the all.py and not just create a script that filters out the items you're diff --git a/doc/MODULES.org b/doc/MODULES.org index 9f48024..347d88d 100644 --- a/doc/MODULES.org +++ b/doc/MODULES.org @@ -76,7 +76,7 @@ The config snippets below are meant to be modified accordingly and *pasted into You don't have to set up all modules at once, it's recommended to do it gradually, to get the feel of how HPI works. -For an extensive/complex example, you can check out ~@seanbreckenridge~'s [[https://github.com/seanbreckenridge/dotfiles/blob/master/.config/my/my/config/__init__.py][config]] +For an extensive/complex example, you can check out ~@purarue~'s [[https://github.com/purarue/dotfiles/blob/master/.config/my/my/config/__init__.py][config]] # Nested Configurations before the doc generation using the block below ** [[file:../my/reddit][my.reddit]] @@ -96,7 +96,7 @@ For an extensive/complex example, you can check out ~@seanbreckenridge~'s [[http class pushshift: ''' - Uses [[https://github.com/seanbreckenridge/pushshift_comment_export][pushshift]] to get access to old comments + Uses [[https://github.com/purarue/pushshift_comment_export][pushshift]] to get access to old comments ''' # path[s]/glob to the exported JSON data @@ -106,7 +106,7 @@ For an extensive/complex example, you can check out ~@seanbreckenridge~'s [[http ** [[file:../my/browser/][my.browser]] - Parses browser history using [[http://github.com/seanbreckenridge/browserexport][browserexport]] + Parses browser history using [[http://github.com/purarue/browserexport][browserexport]] #+begin_src python class browser: @@ -132,7 +132,7 @@ For an extensive/complex example, you can check out ~@seanbreckenridge~'s [[http You might also be able to use [[file:../my/location/via_ip.py][my.location.via_ip]] which uses =my.ip.all= to provide geolocation data for an IPs (though no IPs are provided from any - of the sources here). For an example of usage, see [[https://github.com/seanbreckenridge/HPI/tree/master/my/ip][here]] + of the sources here). For an example of usage, see [[https://github.com/purarue/HPI/tree/master/my/ip][here]] #+begin_src python class location: @@ -256,9 +256,9 @@ for cls, p in modules: ** [[file:../my/google/takeout/parser.py][my.google.takeout.parser]] - Parses Google Takeout using [[https://github.com/seanbreckenridge/google_takeout_parser][google_takeout_parser]] + Parses Google Takeout using [[https://github.com/purarue/google_takeout_parser][google_takeout_parser]] - See [[https://github.com/seanbreckenridge/google_takeout_parser][google_takeout_parser]] for more information about how to export and organize your takeouts + See [[https://github.com/purarue/google_takeout_parser][google_takeout_parser]] for more information about how to export and organize your takeouts If the =DISABLE_TAKEOUT_CACHE= environment variable is set, this won't cache individual exports in =~/.cache/google_takeout_parser= diff --git a/doc/MODULE_DESIGN.org b/doc/MODULE_DESIGN.org index 7aedf2f..442dbf2 100644 --- a/doc/MODULE_DESIGN.org +++ b/doc/MODULE_DESIGN.org @@ -67,7 +67,7 @@ If you want to disable a source, you have a few options. ... that suppresses the warning message and lets you use ~my.location.all~ without having to change any lines of code -Another benefit is that all the custom sources/data is localized to the ~all.py~ file, so a user can override the ~all.py~ (see the sections below on ~namespace packages~) file in their own HPI repository, adding additional sources without having to maintain a fork and patching in changes as things eventually change. For a 'real world' example of that, see [[https://github.com/seanbreckenridge/HPI#partially-in-usewith-overrides][seanbreckenridge]]s location and ip modules. +Another benefit is that all the custom sources/data is localized to the ~all.py~ file, so a user can override the ~all.py~ (see the sections below on ~namespace packages~) file in their own HPI repository, adding additional sources without having to maintain a fork and patching in changes as things eventually change. For a 'real world' example of that, see [[https://github.com/purarue/HPI#partially-in-usewith-overrides][purarue]]s location and ip modules. This is of course not required for personal or single file modules, its just the pattern that seems to have the least amount of friction for the user, while being extendable, and without using a bulky plugin system to let users add additional sources. @@ -208,13 +208,13 @@ Where ~lastfm.py~ is your version of ~my.lastfm~, which you've copied from this Then, running ~python3 -m pip install -e .~ in that directory would install that as part of the namespace package, and assuming (see below for possible issues) this appears on ~sys.path~ before the upstream repository, your ~lastfm.py~ file overrides the upstream. Adding more files, like ~my.some_new_module~ into that directory immediately updates the global ~my~ package -- allowing you to quickly add new modules without having to re-install. -If you install both directories as editable packages (which has the benefit of any changes you making in either repository immediately updating the globally installed ~my~ package), there are some concerns with which editable install appears on your ~sys.path~ first. If you wanted your modules to override the upstream modules, yours would have to appear on the ~sys.path~ first (this is the same reason that =custom_lastfm_overlay= must be at the front of your ~PYTHONPATH~). For more details and examples on dealing with editable namespace packages in the context of HPI, see the [[https://github.com/seanbreckenridge/reorder_editable][reorder_editable]] repository. +If you install both directories as editable packages (which has the benefit of any changes you making in either repository immediately updating the globally installed ~my~ package), there are some concerns with which editable install appears on your ~sys.path~ first. If you wanted your modules to override the upstream modules, yours would have to appear on the ~sys.path~ first (this is the same reason that =custom_lastfm_overlay= must be at the front of your ~PYTHONPATH~). For more details and examples on dealing with editable namespace packages in the context of HPI, see the [[https://github.com/purarue/reorder_editable][reorder_editable]] repository. There is no limit to how many directories you could install into a single namespace package, which could be a possible way for people to install additional HPI modules, without worrying about the module count here becoming too large to manage. -There are some other users [[https://github.com/hpi/hpi][who have begun publishing their own modules]] as namespace packages, which you could potentially install and use, in addition to this repository, if any of those interest you. If you want to create your own you can use the [[https://github.com/seanbreckenridge/HPI-template][template]] to get started. +There are some other users [[https://github.com/hpi/hpi][who have begun publishing their own modules]] as namespace packages, which you could potentially install and use, in addition to this repository, if any of those interest you. If you want to create your own you can use the [[https://github.com/purarue/HPI-template][template]] to get started. -Though, enabling this many modules may make ~hpi doctor~ look pretty busy. You can explicitly choose to enable/disable modules with a list of modules/regexes in your [[https://github.com/karlicoss/HPI/blob/f559e7cb899107538e6c6bbcf7576780604697ef/my/core/core_config.py#L24-L55][core config]], see [[https://github.com/seanbreckenridge/dotfiles/blob/a1a77c581de31bd55a6af3d11b8af588614a207e/.config/my/my/config/__init__.py#L42-L72][here]] for an example. +Though, enabling this many modules may make ~hpi doctor~ look pretty busy. You can explicitly choose to enable/disable modules with a list of modules/regexes in your [[https://github.com/karlicoss/HPI/blob/f559e7cb899107538e6c6bbcf7576780604697ef/my/core/core_config.py#L24-L55][core config]], see [[https://github.com/purarue/dotfiles/blob/a1a77c581de31bd55a6af3d11b8af588614a207e/.config/my/my/config/__init__.py#L42-L72][here]] for an example. You may use the other modules or [[https://github.com/karlicoss/hpi-personal-overlay][my overlay]] as reference, but python packaging is already a complicated issue, before adding complexities like namespace packages and editable installs on top of it... If you're having trouble extending HPI in this fashion, you can open an issue here, preferably with a link to your code/repository and/or ~setup.py~ you're trying to use. diff --git a/doc/OVERLAYS.org b/doc/OVERLAYS.org index 1e6cf8f..a573007 100644 --- a/doc/OVERLAYS.org +++ b/doc/OVERLAYS.org @@ -66,7 +66,7 @@ This basically means that modules will be searched in both paths, with overlay t ** Installing with =--use-pep517= -See here for discussion https://github.com/seanbreckenridge/reorder_editable/issues/2, but TLDR it should work similarly. +See here for discussion https://github.com/purarue/reorder_editable/issues/2, but TLDR it should work similarly. * Testing runtime behaviour (editable install) diff --git a/doc/QUERY.md b/doc/QUERY.md index b672dff..a85450a 100644 --- a/doc/QUERY.md +++ b/doc/QUERY.md @@ -99,7 +99,7 @@ Commit(committed_dt=datetime.datetime(2023, 4, 14, 23, 9, 1, tzinfo=datetime.tim authored_dt=datetime.datetime(2023, 4, 14, 23, 4, 1, tzinfo=datetime.timezone(datetime.timedelta(days=-1, seconds=61200))), message='sources.smscalls: propogate errors if there are breaking ' 'schema changes', - repo='/home/sean/Repos/promnesia-fork', + repo='/home/username/Repos/promnesia-fork', sha='22a434fca9a28df9b0915ccf16368df129d2c9ce', ref='refs/heads/smscalls-handle-result') ``` @@ -195,7 +195,7 @@ To preview, you can use something like [`qgis`](https://qgis.org/en/site/) or fo chicago trip -(Sidenote: this is [`@seanbreckenridge`](https://github.com/seanbreckenridge/)s locations, on a trip to Chicago) +(Sidenote: this is [`@purarue`](https://github.com/purarue/)s locations, on a trip to Chicago) ## Python reference @@ -301,4 +301,4 @@ The `hpi query` command is a CLI wrapper around the code in [`query.py`](../my/c If you specify a range, drop_unsorted is forced to be True ``` -Those can be imported and accept any sort of iterator, `hpi query` just defaults to the output of functions here. As an example, see [`listens`](https://github.com/seanbreckenridge/HPI-personal/blob/master/scripts/listens) which just passes an generator (iterator) as the first argument to `query_range` +Those can be imported and accept any sort of iterator, `hpi query` just defaults to the output of functions here. As an example, see [`listens`](https://github.com/purarue/HPI-personal/blob/master/scripts/listens) which just passes an generator (iterator) as the first argument to `query_range` diff --git a/doc/SETUP.org b/doc/SETUP.org index 0fced62..ee9571c 100644 --- a/doc/SETUP.org +++ b/doc/SETUP.org @@ -387,7 +387,7 @@ But there is an extra caveat: rexport is already coming with nice [[https://gith Several other HPI modules are following a similar pattern: hypothesis, instapaper, pinboard, kobo, etc. -Since the [[https://github.com/karlicoss/rexport#api-limitations][reddit API has limited results]], you can use [[https://github.com/seanbreckenridge/pushshift_comment_export][my.reddit.pushshift]] to access older reddit comments, which both then get merged into =my.reddit.all.comments= +Since the [[https://github.com/karlicoss/rexport#api-limitations][reddit API has limited results]], you can use [[https://github.com/purarue/pushshift_comment_export][my.reddit.pushshift]] to access older reddit comments, which both then get merged into =my.reddit.all.comments= ** Twitter diff --git a/misc/.flake8-karlicoss b/misc/.flake8-karlicoss index 3c98b96..5933253 100644 --- a/misc/.flake8-karlicoss +++ b/misc/.flake8-karlicoss @@ -32,6 +32,6 @@ ignore = # # as a reference: -# https://github.com/seanbreckenridge/cookiecutter-template/blob/master/%7B%7Bcookiecutter.module_name%7D%7D/setup.cfg +# https://github.com/purarue/cookiecutter-template/blob/master/%7B%7Bcookiecutter.module_name%7D%7D/setup.cfg # and this https://github.com/karlicoss/HPI/pull/151 # find ./my | entr flake8 --ignore=E402,E501,E741,W503,E266,E302,E305,E203,E261,E252,E251,E221,W291,E225,E303,E702,E202,F841,E731,E306,E127 E722,E231 my | grep -v __NOT_HPI_MODULE__ diff --git a/my/browser/active_browser.py b/my/browser/active_browser.py index 8051f1b..1686fc5 100644 --- a/my/browser/active_browser.py +++ b/my/browser/active_browser.py @@ -1,5 +1,5 @@ """ -Parses active browser history by backing it up with [[http://github.com/seanbreckenridge/sqlite_backup][sqlite_backup]] +Parses active browser history by backing it up with [[http://github.com/purarue/sqlite_backup][sqlite_backup]] """ REQUIRES = ["browserexport", "sqlite_backup"] diff --git a/my/browser/export.py b/my/browser/export.py index 351cf6e..52ade0e 100644 --- a/my/browser/export.py +++ b/my/browser/export.py @@ -1,5 +1,5 @@ """ -Parses browser history using [[http://github.com/seanbreckenridge/browserexport][browserexport]] +Parses browser history using [[http://github.com/purarue/browserexport][browserexport]] """ REQUIRES = ["browserexport"] diff --git a/my/google/takeout/parser.py b/my/google/takeout/parser.py index 80c2be1..13fd04a 100644 --- a/my/google/takeout/parser.py +++ b/my/google/takeout/parser.py @@ -1,7 +1,7 @@ """ -Parses Google Takeout using [[https://github.com/seanbreckenridge/google_takeout_parser][google_takeout_parser]] +Parses Google Takeout using [[https://github.com/purarue/google_takeout_parser][google_takeout_parser]] -See [[https://github.com/seanbreckenridge/google_takeout_parser][google_takeout_parser]] for more information +See [[https://github.com/purarue/google_takeout_parser][google_takeout_parser]] for more information about how to export and organize your takeouts If the DISABLE_TAKEOUT_CACHE environment variable is set, this won't cache individual @@ -12,7 +12,7 @@ zip files of the exports, which are temporarily unpacked while creating the cachew cache """ -REQUIRES = ["git+https://github.com/seanbreckenridge/google_takeout_parser"] +REQUIRES = ["git+https://github.com/purarue/google_takeout_parser"] import os from collections.abc import Sequence @@ -36,7 +36,7 @@ from google_takeout_parser.merge import CacheResults, GoogleEventSet from google_takeout_parser.models import BaseEvent from google_takeout_parser.path_dispatch import TakeoutParser -# see https://github.com/seanbreckenridge/dotfiles/blob/master/.config/my/my/config/__init__.py for an example +# see https://github.com/purarue/dotfiles/blob/master/.config/my/my/config/__init__.py for an example from my.config import google as user_config @@ -123,7 +123,7 @@ def events(disable_takeout_cache: bool = DISABLE_TAKEOUT_CACHE) -> CacheResults: else: results = exit_stack.enter_context(match_structure(path, expected=EXPECTED, partial=True)) for m in results: - # e.g. /home/sean/data/google_takeout/Takeout-1634932457.zip") -> 'Takeout-1634932457' + # e.g. /home/username/data/google_takeout/Takeout-1634932457.zip") -> 'Takeout-1634932457' # means that zipped takeouts have nice filenames from cachew cw_id, _, _ = path.name.rpartition(".") # each takeout result is cached as well, in individual databases per-type diff --git a/my/ip/all.py b/my/ip/all.py index e8277c1..c267383 100644 --- a/my/ip/all.py +++ b/my/ip/all.py @@ -3,10 +3,10 @@ An example all.py stub module that provides ip data To use this, you'd add IP providers that yield IPs to the 'ips' function -For an example of how this could be used, see https://github.com/seanbreckenridge/HPI/tree/master/my/ip +For an example of how this could be used, see https://github.com/purarue/HPI/tree/master/my/ip """ -REQUIRES = ["git+https://github.com/seanbreckenridge/ipgeocache"] +REQUIRES = ["git+https://github.com/purarue/ipgeocache"] from collections.abc import Iterator diff --git a/my/ip/common.py b/my/ip/common.py index ef54ee3..b551281 100644 --- a/my/ip/common.py +++ b/my/ip/common.py @@ -1,5 +1,5 @@ """ -Provides location/timezone data from IP addresses, using [[https://github.com/seanbreckenridge/ipgeocache][ipgeocache]] +Provides location/timezone data from IP addresses, using [[https://github.com/purarue/ipgeocache][ipgeocache]] """ from my.core import __NOT_HPI_MODULE__ # isort: skip diff --git a/my/location/fallback/via_ip.py b/my/location/fallback/via_ip.py index 732af67..8b50878 100644 --- a/my/location/fallback/via_ip.py +++ b/my/location/fallback/via_ip.py @@ -2,7 +2,7 @@ Converts IP addresses provided by my.location.ip to estimated locations """ -REQUIRES = ["git+https://github.com/seanbreckenridge/ipgeocache"] +REQUIRES = ["git+https://github.com/purarue/ipgeocache"] from dataclasses import dataclass from datetime import timedelta diff --git a/my/location/google_takeout.py b/my/location/google_takeout.py index cb5bef3..8613257 100644 --- a/my/location/google_takeout.py +++ b/my/location/google_takeout.py @@ -2,7 +2,7 @@ Extracts locations using google_takeout_parser -- no shared code with the deprecated my.location.google """ -REQUIRES = ["git+https://github.com/seanbreckenridge/google_takeout_parser"] +REQUIRES = ["git+https://github.com/purarue/google_takeout_parser"] from collections.abc import Iterator diff --git a/my/location/google_takeout_semantic.py b/my/location/google_takeout_semantic.py index 7bddfa8..e84a932 100644 --- a/my/location/google_takeout_semantic.py +++ b/my/location/google_takeout_semantic.py @@ -5,7 +5,7 @@ Extracts semantic location history using google_takeout_parser # This is a separate module to prevent ImportError and a new config block from breaking # previously functional my.location.google_takeout locations -REQUIRES = ["git+https://github.com/seanbreckenridge/google_takeout_parser"] +REQUIRES = ["git+https://github.com/purarue/google_takeout_parser"] from collections.abc import Iterator from dataclasses import dataclass diff --git a/my/location/via_ip.py b/my/location/via_ip.py index d465ad0..240ec5f 100644 --- a/my/location/via_ip.py +++ b/my/location/via_ip.py @@ -1,4 +1,4 @@ -REQUIRES = ["git+https://github.com/seanbreckenridge/ipgeocache"] +REQUIRES = ["git+https://github.com/purarue/ipgeocache"] from my.core.warnings import high diff --git a/my/reddit/pushshift.py b/my/reddit/pushshift.py index 1bfa048..12f592b 100644 --- a/my/reddit/pushshift.py +++ b/my/reddit/pushshift.py @@ -1,11 +1,11 @@ """ Gives you access to older comments possibly not accessible with rexport using pushshift -See https://github.com/seanbreckenridge/pushshift_comment_export +See https://github.com/purarue/pushshift_comment_export """ REQUIRES = [ - "git+https://github.com/seanbreckenridge/pushshift_comment_export", + "git+https://github.com/purarue/pushshift_comment_export", ] from dataclasses import dataclass @@ -21,7 +21,7 @@ from my.core.cfg import make_config @dataclass class pushshift_config(uconfig.pushshift): ''' - Uses [[https://github.com/seanbreckenridge/pushshift_comment_export][pushshift]] to get access to old comments + Uses [[https://github.com/purarue/pushshift_comment_export][pushshift]] to get access to old comments ''' # path[s]/glob to the exported JSON data From ad55c5c345888abaebf59ae85923339b7ceccbb4 Mon Sep 17 00:00:00 2001 From: Srajan Garg Date: Tue, 12 Nov 2024 19:05:27 -0500 Subject: [PATCH 116/122] fix typo in rexport DAL (#405) * fix typo in rexport DAL --- my/reddit/rexport.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/my/reddit/rexport.py b/my/reddit/rexport.py index cb6af01..262635b 100644 --- a/my/reddit/rexport.py +++ b/my/reddit/rexport.py @@ -146,7 +146,7 @@ if not TYPE_CHECKING: # here we just check that types are available, we don't actually want to import them # fmt: off dal.Subreddit # noqa: B018 - dal.Profil # noqa: B018e + dal.Profile # noqa: B018 dal.Multireddit # noqa: B018 # fmt: on except AttributeError as ae: From a7f05c2cad0c500210f966e0f50e0b309490cc53 Mon Sep 17 00:00:00 2001 From: purarue <7804791+purarue@users.noreply.github.com> Date: Wed, 20 Nov 2024 00:03:40 -0800 Subject: [PATCH 117/122] doc: spelling fixes --- CHANGELOG.md | 2 +- doc/OVERLAYS.org | 6 +++--- doc/QUERY.md | 2 +- my/core/cachew.py | 2 +- my/core/konsume.py | 2 +- my/core/logging.py | 2 +- my/core/tests/test_tmp_config.py | 2 +- my/core/utils/itertools.py | 4 ++-- my/fbmessenger/__init__.py | 2 +- my/fbmessenger/android.py | 2 +- my/instagram/all.py | 2 +- my/instagram/gdpr.py | 4 ++-- my/reddit/__init__.py | 2 +- my/smscalls.py | 4 ++-- my/stackexchange/gdpr.py | 2 +- my/time/tz/via_location.py | 2 +- my/tinder/android.py | 2 +- my/topcoder.py | 2 +- my/twitter/android.py | 2 +- my/twitter/twint.py | 2 +- my/whatsapp/android.py | 2 +- my/youtube/takeout.py | 2 +- 22 files changed, 27 insertions(+), 27 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3dd19df..d60ef35 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,7 +20,7 @@ General/my.core changes: - e81dddddf083ffd81aa7e2b715bd34f59949479c properly resolve class properties in make_config + add test Modules: -- some innitial work on filling **InfluxDB** with HPI data +- some initial work on filling **InfluxDB** with HPI data - pinboard - 42399f6250d9901d93dcedcfe05f7857babcf834: **breaking backwards compatibility**, use pinbexport module directly diff --git a/doc/OVERLAYS.org b/doc/OVERLAYS.org index a573007..7bafa48 100644 --- a/doc/OVERLAYS.org +++ b/doc/OVERLAYS.org @@ -10,7 +10,7 @@ Relevant discussion about overlays: https://github.com/karlicoss/HPI/issues/102 # You can see them TODO in overlays dir -Consider a toy package/module structure with minimal code, wihout any actual data parsing, just for demonstration purposes. +Consider a toy package/module structure with minimal code, without any actual data parsing, just for demonstration purposes. - =main= package structure # TODO do links @@ -19,7 +19,7 @@ Consider a toy package/module structure with minimal code, wihout any actual dat Extracts Twitter data from GDPR archive. - =my/twitter/all.py= Merges twitter data from multiple sources (only =gdpr= in this case), so data consumers are agnostic of specific data sources used. - This will be overriden by =overlay=. + This will be overridden by =overlay=. - =my/twitter/common.py= Contains helper function to merge data, so they can be reused by overlay's =all.py=. - =my/reddit.py= @@ -126,7 +126,7 @@ https://github.com/python/mypy/blob/1dd8e7fe654991b01bd80ef7f1f675d9e3910c3a/myp For now, I opened an issue in mypy repository https://github.com/python/mypy/issues/16683 -But ok, maybe mypy treats =main= as an external package somhow but still type checks it properly? +But ok, maybe mypy treats =main= as an external package somehow but still type checks it properly? Let's see what's going on with imports: : $ mypy --namespace-packages --strict -p my --follow-imports=error diff --git a/doc/QUERY.md b/doc/QUERY.md index a85450a..9a5d9d3 100644 --- a/doc/QUERY.md +++ b/doc/QUERY.md @@ -97,7 +97,7 @@ By default, this just returns the items in the order they were returned by the f hpi query my.coding.commits.commits --order-key committed_dt --limit 1 --reverse --output pprint --stream Commit(committed_dt=datetime.datetime(2023, 4, 14, 23, 9, 1, tzinfo=datetime.timezone(datetime.timedelta(days=-1, seconds=61200))), authored_dt=datetime.datetime(2023, 4, 14, 23, 4, 1, tzinfo=datetime.timezone(datetime.timedelta(days=-1, seconds=61200))), - message='sources.smscalls: propogate errors if there are breaking ' + message='sources.smscalls: propagate errors if there are breaking ' 'schema changes', repo='/home/username/Repos/promnesia-fork', sha='22a434fca9a28df9b0915ccf16368df129d2c9ce', diff --git a/my/core/cachew.py b/my/core/cachew.py index 9ccee09..8ce2f2b 100644 --- a/my/core/cachew.py +++ b/my/core/cachew.py @@ -136,7 +136,7 @@ if TYPE_CHECKING: CC = Callable[P, R] # need to give it a name, if inlined into bound=, mypy runs in a bug PathProvider = Union[PathIsh, Callable[P, PathIsh]] # NOTE: in cachew, HashFunction type returns str - # however in practice, cachew alwasy calls str for its result + # however in practice, cachew always calls str for its result # so perhaps better to switch it to Any in cachew as well HashFunction = Callable[P, Any] diff --git a/my/core/konsume.py b/my/core/konsume.py index 6d24167..41b5a4e 100644 --- a/my/core/konsume.py +++ b/my/core/konsume.py @@ -236,7 +236,7 @@ def test_zoom() -> None: # - very flexible, easy to adjust behaviour # - cons: # - can forget to assert about extra entities etc, so error prone -# - if we do something like =assert j.pop('status') == 200, j=, by the time assert happens we already popped item -- makes erro handling harder +# - if we do something like =assert j.pop('status') == 200, j=, by the time assert happens we already popped item -- makes error handling harder # - a bit verbose.. so probably requires some helper functions though (could be much leaner than current konsume though) # - if we assert, then terminates parsing too early, if we're defensive then inflates the code a lot with if statements # - TODO perhaps combine warnings somehow or at least only emit once per module? diff --git a/my/core/logging.py b/my/core/logging.py index bdee9aa..167a167 100644 --- a/my/core/logging.py +++ b/my/core/logging.py @@ -250,7 +250,7 @@ if __name__ == '__main__': test() -## legacy/deprecated methods for backwards compatilibity +## legacy/deprecated methods for backwards compatibility if not TYPE_CHECKING: from .compat import deprecated diff --git a/my/core/tests/test_tmp_config.py b/my/core/tests/test_tmp_config.py index e5a24cc..d99621d 100644 --- a/my/core/tests/test_tmp_config.py +++ b/my/core/tests/test_tmp_config.py @@ -12,7 +12,7 @@ def _init_default_config() -> None: def test_tmp_config() -> None: ## ugh. ideally this would be on the top level (would be a better test) - ## but pytest imports eveything first, executes hooks, and some reset_modules() fictures mess stuff up + ## but pytest imports everything first, executes hooks, and some reset_modules() fictures mess stuff up ## later would be nice to be a bit more careful about them _init_default_config() from my.simple import items diff --git a/my/core/utils/itertools.py b/my/core/utils/itertools.py index 501ebbe..42b2b77 100644 --- a/my/core/utils/itertools.py +++ b/my/core/utils/itertools.py @@ -321,7 +321,7 @@ _UET = TypeVar('_UET') _UEU = TypeVar('_UEU') -# NOTE: for historic reasons, this function had to accept Callable that retuns iterator +# NOTE: for historic reasons, this function had to accept Callable that returns iterator # instead of just iterator # TODO maybe deprecated Callable support? not sure def unique_everseen( @@ -358,7 +358,7 @@ def test_unique_everseen() -> None: assert list(unique_everseen(fun_good)) == [123] with pytest.raises(Exception): - # since function retuns a list rather than iterator, check happens immediately + # since function returns a list rather than iterator, check happens immediately # , even without advancing the iterator unique_everseen(fun_bad) diff --git a/my/fbmessenger/__init__.py b/my/fbmessenger/__init__.py index f729de9..e5e417c 100644 --- a/my/fbmessenger/__init__.py +++ b/my/fbmessenger/__init__.py @@ -9,7 +9,7 @@ since that allows for easier overriding using namespace packages See https://github.com/karlicoss/HPI/blob/master/doc/MODULE_DESIGN.org#allpy for more info. """ -# prevent it from apprearing in modules list/doctor +# prevent it from appearing in modules list/doctor from ..core import __NOT_HPI_MODULE__ # kinda annoying to keep it, but it's so legacy 'hpi module install my.fbmessenger' works diff --git a/my/fbmessenger/android.py b/my/fbmessenger/android.py index a16d924..db4cc54 100644 --- a/my/fbmessenger/android.py +++ b/my/fbmessenger/android.py @@ -174,7 +174,7 @@ def _process_db_msys(db: sqlite3.Connection) -> Iterator[Res[Entity]]: However seems that when message is not sent yet it doesn't have this server id yet (happened only once, but could be just luck of course!) We exclude these messages to avoid duplication. - However poisitive filter (e.g. message_id LIKE 'mid%') feels a bit wrong, e.g. what if mesage ids change or something + However poisitive filter (e.g. message_id LIKE 'mid%') feels a bit wrong, e.g. what if message ids change or something So instead this excludes only such unsent messages. */ message_id != offline_threading_id diff --git a/my/instagram/all.py b/my/instagram/all.py index 214e6ac..ce78409 100644 --- a/my/instagram/all.py +++ b/my/instagram/all.py @@ -23,7 +23,7 @@ def messages() -> Iterator[Res[Message]]: # TODO in general best to prefer android, it has more data # - message ids # - usernames are correct for Android data - # - thread ids more meaninful? + # - thread ids more meaningful? # but for now prefer gdpr prefix since it makes a bit things a bit more consistent? # e.g. a new batch of android exports can throw off ids if we rely on it for mapping yield from _merge_messages( diff --git a/my/instagram/gdpr.py b/my/instagram/gdpr.py index 7454a04..d417fdb 100644 --- a/my/instagram/gdpr.py +++ b/my/instagram/gdpr.py @@ -76,7 +76,7 @@ def _entities() -> Iterator[Res[User | _Message]]: # NOTE: here there are basically two options # - process inputs as is (from oldest to newest) # this would be more stable wrt newer exports (e.g. existing thread ids won't change) - # the downside is that newer exports seem to have better thread ids, so might be preferrable to use them + # the downside is that newer exports seem to have better thread ids, so might be preferable to use them # - process inputs reversed (from newest to oldest) # the upside is that thread ids/usernames might be better # the downside is that if for example the user renames, thread ids will change _a lot_, might be undesirable.. @@ -137,7 +137,7 @@ def _entitites_from_path(path: Path) -> Iterator[Res[User | _Message]]: j = json.loads(ffile.read_text()) id_len = 10 - # NOTE: I'm not actually sure it's other user's id.., since it corresponds to the whole converstation + # NOTE: I'm not actually sure it's other user's id.., since it corresponds to the whole conversation # but I stared a bit at these ids vs database ids and can't see any way to find the correspondence :( # so basically the only way to merge is to actually try some magic and correlate timestamps/message texts? # another option is perhaps to query user id from username with some free API diff --git a/my/reddit/__init__.py b/my/reddit/__init__.py index f344eeb..982901a 100644 --- a/my/reddit/__init__.py +++ b/my/reddit/__init__.py @@ -9,7 +9,7 @@ since that allows for easier overriding using namespace packages See https://github.com/karlicoss/HPI/blob/master/doc/MODULE_DESIGN.org#allpy for more info. """ -# prevent it from apprearing in modules list/doctor +# prevent it from appearing in modules list/doctor from ..core import __NOT_HPI_MODULE__ # kinda annoying to keep it, but it's so legacy 'hpi module install my.reddit' works diff --git a/my/smscalls.py b/my/smscalls.py index ccaac72..324bc44 100644 --- a/my/smscalls.py +++ b/my/smscalls.py @@ -186,7 +186,7 @@ class MMS(NamedTuple): for (addr, _type) in self.addresses: if _type == 137: return addr - # hmm, maybe return instead? but this probably shouldnt happen, means + # hmm, maybe return instead? but this probably shouldn't happen, means # something is very broken raise RuntimeError(f'No from address matching 137 found in {self.addresses}') @@ -214,7 +214,7 @@ def mms() -> Iterator[Res[MMS]]: def _resolve_null_str(value: str | None) -> str | None: if value is None: return None - # hmm.. theres some risk of the text actually being 'null', but theres + # hmm.. there's some risk of the text actually being 'null', but there's # no way to distinguish that from XML values if value == 'null': return None diff --git a/my/stackexchange/gdpr.py b/my/stackexchange/gdpr.py index 78987be..8ed0d30 100644 --- a/my/stackexchange/gdpr.py +++ b/my/stackexchange/gdpr.py @@ -49,7 +49,7 @@ class Vote(NamedTuple): # hmm, this loads very raw comments without the rest of the page? # - https://meta.stackexchange.com/posts/27319/comments#comment-57475 # - # parentPostId is the original quesion + # parentPostId is the original question # TODO is not always present? fucking hell # seems like there is no way to get a hierarchical comment link.. guess this needs to be handled in Promnesia normalisation... # postId is the answer diff --git a/my/time/tz/via_location.py b/my/time/tz/via_location.py index 58b5bf7..1b2275b 100644 --- a/my/time/tz/via_location.py +++ b/my/time/tz/via_location.py @@ -245,7 +245,7 @@ def _iter_tzs() -> Iterator[DayWithZone]: def _day2zone() -> dict[date, pytz.BaseTzInfo]: # NOTE: kinda unfortunate that this will have to process all days before returning result for just one # however otherwise cachew cache might never be initialized properly - # so we'll always end up recomputing everyting during subsequent runs + # so we'll always end up recomputing everything during subsequent runs return {dz.day: pytz.timezone(dz.zone) for dz in _iter_tzs()} diff --git a/my/tinder/android.py b/my/tinder/android.py index a09794f..5a5d887 100644 --- a/my/tinder/android.py +++ b/my/tinder/android.py @@ -106,7 +106,7 @@ def _handle_db(db: sqlite3.Connection) -> Iterator[Res[_Entity]]: user_profile_rows = list(db.execute('SELECT * FROM profile_user_view')) if len(user_profile_rows) == 0: - # shit, sometime in 2023 profile_user_view stoppped containing user profile.. + # shit, sometime in 2023 profile_user_view stopped containing user profile.. # presumably the most common from_id/to_id would be our own username counter = Counter([id_ for (id_,) in db.execute('SELECT from_id FROM message UNION ALL SELECT to_id FROM message')]) if len(counter) > 0: # this might happen if db is empty (e.g. user got logged out) diff --git a/my/topcoder.py b/my/topcoder.py index 56403e2..40df77c 100644 --- a/my/topcoder.py +++ b/my/topcoder.py @@ -81,7 +81,7 @@ def _parse_one(p: Path) -> Iterator[Res[Competition]]: # but also expects cooperation from .make method (e.g. popping items from the dict) # could also wrap in helper and pass to .make .. not sure # an argument could be made that .make isn't really a class methond.. - # it's pretty specific to this parser onl + # it's pretty specific to this parser only yield from Competition.make(j=c) yield from m.check() diff --git a/my/twitter/android.py b/my/twitter/android.py index 88c9389..8159ee7 100644 --- a/my/twitter/android.py +++ b/my/twitter/android.py @@ -192,7 +192,7 @@ def get_own_user_id(conn) -> str: # - timeline_data_type # 1 : the bulk of tweets, but also some notifications etc?? # 2 : who-to-follow/community-to-join. contains a couple of tweets, but their corresponding status_id is NULL -# 8 : who-to-follow/notfication +# 8 : who-to-follow/notification # 13: semantic-core/who-to-follow # 14: cursor # 17: trends diff --git a/my/twitter/twint.py b/my/twitter/twint.py index 5106923..9d36a93 100644 --- a/my/twitter/twint.py +++ b/my/twitter/twint.py @@ -54,7 +54,7 @@ class Tweet(NamedTuple): # https://github.com/thomasancheriyil/Red-Tide-Detection-based-on-Twitter/blob/beb200be60cc66dcbc394e670513715509837812/python/twitterGapParse.py#L61-L62 # # twint is also saving 'timezone', but this is local machine timezone at the time of scraping? - # perhaps they thought date-time-ms was local time... or just kept it just in case (they are keepin lots on unnecessary stuff in the db) + # perhaps they thought date-time-ms was local time... or just kept it just in case (they are keeping lots on unnecessary stuff in the db) return datetime.fromtimestamp(seconds, tz=tz) @property diff --git a/my/whatsapp/android.py b/my/whatsapp/android.py index 3cd4436..a8dbe8d 100644 --- a/my/whatsapp/android.py +++ b/my/whatsapp/android.py @@ -199,7 +199,7 @@ def _process_db(db: sqlite3.Connection) -> Iterator[Entity]: sender_row_id = r['sender_jid_row_id'] if sender_row_id == 0: # seems that it's always 0 for 1-1 chats - # for group chats our onw id is still 0, but other ids are properly set + # for group chats our own id is still 0, but other ids are properly set if from_me: myself_user_id = config.my_user_id or 'MYSELF_USER_ID' sender = Sender(id=myself_user_id, name=None) # TODO set my own name as well? diff --git a/my/youtube/takeout.py b/my/youtube/takeout.py index 703715f..8eca328 100644 --- a/my/youtube/takeout.py +++ b/my/youtube/takeout.py @@ -36,7 +36,7 @@ def watched() -> Iterator[Res[Watched]]: continue # older exports (e.g. html) didn't have microseconds - # wheras newer json ones do have them + # whereas newer json ones do have them # seconds resolution is enough to distinguish watched videos # also we're processing takeouts in HPI in reverse order, so first seen watch would contain microseconds, resulting in better data without_microsecond = w.when.replace(microsecond=0) From 95a16b956f8ab24bea3002d1428c0c10b30a3455 Mon Sep 17 00:00:00 2001 From: purarue <7804791+purarue@users.noreply.github.com> Date: Tue, 26 Nov 2024 13:53:10 -0800 Subject: [PATCH 118/122] doc: some performance notes for query_range (#409) * doc: some performance notes for query_range * add ruff_cache to gitignore --- .gitignore | 3 +++ my/core/__init__.py | 33 ++++++++++++++++++--------------- my/core/__main__.py | 3 +++ my/core/query_range.py | 4 +++- 4 files changed, 27 insertions(+), 16 deletions(-) diff --git a/.gitignore b/.gitignore index 19c3380..65ba630 100644 --- a/.gitignore +++ b/.gitignore @@ -155,6 +155,9 @@ celerybeat-schedule .dmypy.json dmypy.json +# linters +.ruff_cache/ + # Pyre type checker .pyre/ diff --git a/my/core/__init__.py b/my/core/__init__.py index cc549d5..a8a41f4 100644 --- a/my/core/__init__.py +++ b/my/core/__init__.py @@ -29,22 +29,25 @@ if not TYPE_CHECKING: __all__ = [ - 'get_files', 'PathIsh', 'Paths', - 'Json', - 'make_logger', - 'LazyLogger', # legacy import - 'warn_if_empty', - 'stat', 'Stats', - 'datetime_aware', 'datetime_naive', - 'assert_never', # TODO maybe deprecate from use in my.core? will be in stdlib soon - - 'make_config', - '__NOT_HPI_MODULE__', - - 'Res', 'unwrap', 'notnone', - - 'dataclass', 'Path', + 'Json', + 'LazyLogger', # legacy import + 'Path', + 'PathIsh', + 'Paths', + 'Res', + 'Stats', + 'assert_never', # TODO maybe deprecate from use in my.core? will be in stdlib soon + 'dataclass', + 'datetime_aware', + 'datetime_naive', + 'get_files', + 'make_config', + 'make_logger', + 'notnone', + 'stat', + 'unwrap', + 'warn_if_empty', ] diff --git a/my/core/__main__.py b/my/core/__main__.py index 00ac4ee..7e2d8f9 100644 --- a/my/core/__main__.py +++ b/my/core/__main__.py @@ -538,6 +538,9 @@ def query_hpi_functions( # chain list of functions from user, in the order they wrote them on the CLI input_src = chain(*(f() for f in _locate_functions_or_prompt(qualified_names))) + # NOTE: if passing just one function to this which returns a single namedtuple/dataclass, + # using both --order-key and --order-type will often be faster as it does not need to + # duplicate the iterator in memory, or try to find the --order-type type on each object before sorting res = select_range( input_src, order_key=order_key, diff --git a/my/core/query_range.py b/my/core/query_range.py index 2a8d7bd..83728bf 100644 --- a/my/core/query_range.py +++ b/my/core/query_range.py @@ -337,6 +337,8 @@ def select_range( # if the user supplied a order_key, and/or we've generated an order_value, create # the function that accesses that type on each value in the iterator if order_key is not None or order_value is not None: + # _generate_order_value_func internally here creates a copy of the iterator, which has to + # be consumed in-case we're sorting by mixed types order_by_chosen, itr = _handle_generate_order_by(itr, order_key=order_key, order_value=order_value) # signifies that itr is empty -- can early return here if order_by_chosen is None: @@ -398,7 +400,7 @@ Specify a type or a key to order the value by""") return itr -# re-use items from query for testing +# reuse items from query for testing from .query import _A, _B, _Float, _mixed_iter_errors From d8c53bde34e2a5e68f2bac18941ae426ed468b02 Mon Sep 17 00:00:00 2001 From: purarue <7804791+purarue@users.noreply.github.com> Date: Mon, 25 Nov 2024 16:31:22 -0800 Subject: [PATCH 119/122] smscalls: add phone number to model --- my/smscalls.py | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/my/smscalls.py b/my/smscalls.py index 324bc44..0ff2553 100644 --- a/my/smscalls.py +++ b/my/smscalls.py @@ -37,6 +37,7 @@ class Call(NamedTuple): dt: datetime dt_readable: str duration_s: int + phone_number: str who: str | None # type - 1 = Incoming, 2 = Outgoing, 3 = Missed, 4 = Voicemail, 5 = Rejected, 6 = Refused List. call_type: int @@ -65,12 +66,13 @@ def _extract_calls(path: Path) -> Iterator[Res[Call]]: duration = cxml.get('duration') who = cxml.get('contact_name') call_type = cxml.get('type') + number = cxml.get('number') # if name is missing, its not None (its some string), depends on the phone/message app if who is not None and who in UNKNOWN: who = None - if dt is None or dt_readable is None or duration is None or call_type is None: + if dt is None or dt_readable is None or duration is None or call_type is None or number is None: call_str = etree.tostring(cxml).decode('utf-8') - yield RuntimeError(f"Missing one or more required attributes [date, readable_date, duration, type] in {call_str}") + yield RuntimeError(f"Missing one or more required attributes [date, readable_date, duration, type, number] in {call_str}") continue # TODO we've got local tz here, not sure if useful.. # ok, so readable date is local datetime, changing throughout the backup @@ -78,6 +80,7 @@ def _extract_calls(path: Path) -> Iterator[Res[Call]]: dt=_parse_dt_ms(dt), dt_readable=dt_readable, duration_s=int(duration), + phone_number=number, who=who, call_type=int(call_type), ) From f1d23c5e96d95819d383485f22b480d8d190fe98 Mon Sep 17 00:00:00 2001 From: purarue <7804791+purarue@users.noreply.github.com> Date: Sun, 22 Dec 2024 21:50:03 -0800 Subject: [PATCH 120/122] smscalls: allow large XML files as input once XML files increase past a certain size (was about 220MB for me), the parser just throws an error because the tree is too large (iirc for security reasons) could maybe look at using iterparse in the future to parse it without loading the whole file, but this seems to fix it fine for me --- my/smscalls.py | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/my/smscalls.py b/my/smscalls.py index 0ff2553..27d08be 100644 --- a/my/smscalls.py +++ b/my/smscalls.py @@ -57,9 +57,12 @@ class Call(NamedTuple): # The '(Unknown)' is just what my android phone does, not sure if there are others UNKNOWN: set[str] = {'(Unknown)'} +def _parse_xml(xml: Path) -> Any: + return etree.parse(str(xml), parser=etree.XMLParser(huge_tree=True)) + def _extract_calls(path: Path) -> Iterator[Res[Call]]: - tr = etree.parse(str(path)) + tr = _parse_xml(path) for cxml in tr.findall('call'): dt = cxml.get('date') dt_readable = cxml.get('readable_date') @@ -133,7 +136,7 @@ def messages() -> Iterator[Res[Message]]: def _extract_messages(path: Path) -> Iterator[Res[Message]]: - tr = etree.parse(str(path)) + tr = _parse_xml(path) for mxml in tr.findall('sms'): dt = mxml.get('date') dt_readable = mxml.get('readable_date') @@ -225,8 +228,7 @@ def _resolve_null_str(value: str | None) -> str | None: def _extract_mms(path: Path) -> Iterator[Res[MMS]]: - tr = etree.parse(str(path)) - + tr = _parse_xml(path) for mxml in tr.findall('mms'): dt = mxml.get('date') dt_readable = mxml.get('readable_date') @@ -271,10 +273,7 @@ def _extract_mms(path: Path) -> Iterator[Res[MMS]]: # # This seems pretty useless, so we should try and skip it, and just return the # text/images/data - # - # man, attrib is some internal cpython ._Attrib type which can't - # be typed by any sort of mappingproxy. maybe a protocol could work..? - part_data: dict[str, Any] = part.attrib # type: ignore + part_data: dict[str, Any] = part.attrib seq: str | None = part_data.get('seq') if seq == '-1': continue From 54df429f614a5e5d0617dcd196bf8566608e987c Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Sun, 29 Dec 2024 15:06:49 +0000 Subject: [PATCH 121/122] core.sqlite: add helper SqliteTool to get table schemas --- my/core/sqlite.py | 43 +++++++++++++++++++++++++++++++++++++++ my/fbmessenger/android.py | 4 ++-- 2 files changed, 45 insertions(+), 2 deletions(-) diff --git a/my/core/sqlite.py b/my/core/sqlite.py index aa41ab3..6167d2e 100644 --- a/my/core/sqlite.py +++ b/my/core/sqlite.py @@ -134,3 +134,46 @@ def select(cols: tuple[str, str, str, str, str, str, str, str], rest: str, *, db def select(cols, rest, *, db): # db arg is last cause that results in nicer code formatting.. return db.execute('SELECT ' + ','.join(cols) + ' ' + rest) + + +class SqliteTool: + def __init__(self, connection: sqlite3.Connection) -> None: + self.connection = connection + + def _get_sqlite_master(self) -> dict[str, str]: + res = {} + for c in self.connection.execute('SELECT name, type FROM sqlite_master'): + [name, type_] = c + assert type_ in {'table', 'index', 'view', 'trigger'}, (name, type_) # just in case + res[name] = type_ + return res + + def get_table_names(self) -> list[str]: + master = self._get_sqlite_master() + res = [] + for name, type_ in master.items(): + if type_ != 'table': + continue + res.append(name) + return res + + def get_table_schema(self, name: str) -> dict[str, str]: + """ + Returns map from column name to column type + + NOTE: Sometimes this doesn't work if the db has some extensions (e.g. happens for facebook apps) + In this case you might still be able to use get_table_names + """ + schema: dict[str, str] = {} + for row in self.connection.execute(f'PRAGMA table_info(`{name}`)'): + col = row[1] + type_ = row[2] + # hmm, somewhere between 3.34.1 and 3.37.2, sqlite started normalising type names to uppercase + # let's do this just in case since python < 3.10 are using the old version + # e.g. it could have returned 'blob' and that would confuse blob check (see _check_allowed_blobs) + type_ = type_.upper() + schema[col] = type_ + return schema + + def get_table_schemas(self) -> dict[str, dict[str, str]]: + return {name: self.get_table_schema(name) for name in self.get_table_names()} diff --git a/my/fbmessenger/android.py b/my/fbmessenger/android.py index db4cc54..f6fdb82 100644 --- a/my/fbmessenger/android.py +++ b/my/fbmessenger/android.py @@ -15,7 +15,7 @@ from my.core import LazyLogger, Paths, Res, datetime_aware, get_files, make_conf from my.core.common import unique_everseen from my.core.compat import assert_never from my.core.error import echain -from my.core.sqlite import sqlite_connection +from my.core.sqlite import sqlite_connection, SqliteTool from my.config import fbmessenger as user_config # isort: skip @@ -86,8 +86,8 @@ def _entities() -> Iterator[Res[Entity]]: for idx, path in enumerate(paths): logger.info(f'processing [{idx:>{width}}/{total:>{width}}] {path}') with sqlite_connection(path, immutable=True, row_factory='row') as db: + use_msys = "logging_events_v2" in SqliteTool(db).get_table_names() try: - use_msys = len(list(db.execute('SELECT * FROM sqlite_master WHERE name = "logging_events_v2"'))) > 0 if use_msys: yield from _process_db_msys(db) else: From bb703c8c6a7ef80205030f640316c222bc48a6e1 Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Sun, 29 Dec 2024 15:37:10 +0000 Subject: [PATCH 122/122] twitter.android: fix get_own_user_id for latest exports --- my/twitter/android.py | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/my/twitter/android.py b/my/twitter/android.py index 8159ee7..7e8f170 100644 --- a/my/twitter/android.py +++ b/my/twitter/android.py @@ -161,9 +161,22 @@ def get_own_user_id(conn) -> str: 'SELECT DISTINCT CAST(list_mapping_user_id AS TEXT) FROM list_mapping', 'SELECT DISTINCT CAST(owner_id AS TEXT) FROM cursors', 'SELECT DISTINCT CAST(user_id AS TEXT) FROM users WHERE _id == 1', + # ugh, sometimes all of the above are empty... + # for the rest it seems: + # - is_active_creator is NULL + # - is_graduated is NULL + # - profile_highlighted_info is NULL + 'SELECT DISTINCT CAST(user_id AS TEXT) FROM users WHERE is_active_creator == 0 AND is_graduated == 1 AND profile_highlights_info IS NOT NULL', ]: - for (r,) in conn.execute(q): - res.add(r) + res |= {r for (r,) in conn.execute(q)} + + assert len(res) <= 1, res + if len(res) == 0: + # sometimes even all of the above doesn't help... + # last resort is trying to get from status_groups table + # however we can't always use it because it might contain multiple different owner_id? + # not sure, maybe it will break as well and we'll need to fallback on the most common or something.. + res |= {r for (r,) in conn.execute('SELECT DISTINCT CAST(owner_id AS TEXT) FROM status_groups')} assert len(res) == 1, res [r] = res return r