diff --git a/.ci/run b/.ci/run
deleted file mode 100755
index 7656575..0000000
--- a/.ci/run
+++ /dev/null
@@ -1,48 +0,0 @@
-#!/bin/bash
-set -eu
-
-cd "$(dirname "$0")"
-cd .. # git root
-
-if ! command -v sudo; then
- # CI or Docker sometimes doesn't have it, so useful to have a dummy
- function sudo {
- "$@"
- }
-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
- darwin*)
- # macos
- brew install fd
- ;;
- 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?
- sudo apt update
- sudo apt install fd-find
- ;;
- esac
-fi
-
-
-PY_BIN="python3"
-# some systems might have python pointing to python3
-if ! command -v python3 &> /dev/null; then
- PY_BIN="python"
-fi
-
-
-# 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/.github/workflows/main.yml b/.github/workflows/main.yml
index 111d0e9..a763cd4 100644
--- a/.github/workflows/main.yml
+++ b/.github/workflows/main.yml
@@ -5,72 +5,49 @@ on:
push:
branches: '*'
tags: 'v[0-9]+.*' # only trigger on 'release' tags for PyPi
- # Ideally I would put this in the pypi job... but github syntax doesn't allow for regexes there :shrug:
- pull_request: # needed to trigger on others' PRs
# Note that people who fork it need to go to "Actions" tab on their fork and click "I understand my workflows, go ahead and enable them".
+ pull_request: # needed to trigger on others' PRs
workflow_dispatch: # needed to trigger workflows manually
- # todo cron?
- inputs:
- debug_enabled:
- type: boolean
- description: 'Run the build with tmate debugging enabled (https://github.com/marketplace/actions/debugging-with-tmate)'
- required: false
- default: false
+ # todo cron?
+env:
+ # useful for scripts & sometimes tests to know
+ CI: true
jobs:
build:
strategy:
- fail-fast: false
matrix:
- platform: [ubuntu-latest, macos-latest, windows-latest]
- 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.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.10' },
- {platform: macos-latest , python-version: '3.11' },
- {platform: macos-latest , python-version: '3.12' },
- ]
+ platform: [ubuntu-latest, macos-latest] # TODO windows-latest??
+ python-version: [3.7, 3.8, 3.9]
runs-on: ${{ matrix.platform }}
- # useful for 'optional' pipelines
- # continue-on-error: ${{ matrix.platform == 'windows-latest' }}
-
steps:
# ugh https://github.com/actions/toolkit/blob/main/docs/commands.md#path-manipulation
- run: echo "$HOME/.local/bin" >> $GITHUB_PATH
- - uses: actions/setup-python@v5
+ - uses: actions/setup-python@v2
with:
python-version: ${{ matrix.python-version }}
+ cache: 'pip'
- - uses: actions/checkout@v4
+ - uses: actions/checkout@v2
with:
submodules: recursive
fetch-depth: 0 # nicer to have all git history when debugging/for tests
- - uses: mxschmitt/action-tmate@v3
- if: ${{ github.event_name == 'workflow_dispatch' && inputs.debug_enabled }}
+ # uncomment for SSH debugging
+ # - uses: mxschmitt/action-tmate@v3
- # explicit bash command is necessary for Windows CI runner, otherwise it thinks it's cmd...
- - run: bash .ci/run
+ - run: scripts/ci/run
- - if: matrix.platform == 'ubuntu-latest' # no need to compute coverage for other platforms
- uses: actions/upload-artifact@v4
+ - uses: actions/upload-artifact@v2
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
+ - uses: actions/upload-artifact@v2
with:
- include-hidden-files: true
name: .coverage.mypy-core_${{ matrix.platform }}_${{ matrix.python-version }}
path: .coverage.mypy-core/
@@ -82,11 +59,12 @@ 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@v5
+ - uses: actions/setup-python@v2
with:
- python-version: '3.10'
+ python-version: '3.7'
+ cache: 'pip'
- - uses: actions/checkout@v4
+ - uses: actions/checkout@v2
with:
submodules: recursive
@@ -95,7 +73,8 @@ jobs:
if: github.event_name != 'pull_request' && github.event.ref == 'refs/heads/master'
env:
TWINE_PASSWORD: ${{ secrets.TWINE_PASSWORD_TEST }}
- run: pip3 install --user --upgrade build twine && .ci/release --test
+ run: pip3 install --user wheel twine && scripts/release --test
+ # TODO run pip install just to test?
- name: 'release to pypi'
# always deploy tags to release pypi
@@ -103,4 +82,4 @@ jobs:
if: github.event_name != 'pull_request' && startsWith(github.event.ref, 'refs/tags')
env:
TWINE_PASSWORD: ${{ secrets.TWINE_PASSWORD }}
- run: pip3 install --user --upgrade build twine && .ci/release
+ run: pip3 install --user wheel twine && scripts/release
diff --git a/.gitignore b/.gitignore
index 65ba630..888867a 100644
--- a/.gitignore
+++ b/.gitignore
@@ -12,7 +12,6 @@
auto-save-list
tramp
.\#*
-*.gpx
# Org-mode
.org-id-locations
@@ -155,9 +154,6 @@ celerybeat-schedule
.dmypy.json
dmypy.json
-# linters
-.ruff_cache/
-
# Pyre type checker
.pyre/
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d60ef35..edaaf02 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -17,10 +17,10 @@ General/my.core changes:
- 746c3da0cadcba3b179688783186d8a0bd0999c5 core.pandas: allow specifying schema; add tests
- 5313984d8fea2b6eef6726b7b346c1f4316acd01 add `tmp_config` context manager for test & adhoc patching
- df9a7f7390aee6c69f1abf1c8d1fc7659ebb957c core.pandas: add check for 'error' column + add empty one by default
-- e81dddddf083ffd81aa7e2b715bd34f59949479c properly resolve class properties in make_config + add test
+- e81dddddf083ffd81aa7e2b715bd34f59949479c proprely resolve class properties in make_config + add test
Modules:
-- some initial work on filling **InfluxDB** with HPI data
+- some innitial work on filling **InfluxDB** with HPI data
- pinboard
- 42399f6250d9901d93dcedcfe05f7857babcf834: **breaking backwards compatibility**, use pinbexport module directly
diff --git a/README.org b/README.org
index 79621a5..865ca42 100644
--- a/README.org
+++ b/README.org
@@ -12,7 +12,6 @@ If you're in a hurry, feel free to jump straight to the [[#usecases][demos]].
- see [[https://github.com/karlicoss/HPI/tree/master/doc/SETUP.org][SETUP]] for the *installation/configuration guide*
- see [[https://github.com/karlicoss/HPI/tree/master/doc/DEVELOPMENT.org][DEVELOPMENT]] for the *development guide*
- see [[https://github.com/karlicoss/HPI/tree/master/doc/DESIGN.org][DESIGN]] for the *design goals*
-- see [[https://github.com/karlicoss/HPI/tree/master/doc/MODULES.org][MODULES]] for *module-specific setup*
- see [[https://github.com/karlicoss/HPI/tree/master/doc/MODULE_DESIGN.org][MODULE_DESIGN]] for some thoughts on structuring modules, and possibly *extending HPI*
- see [[https://beepb00p.xyz/exobrain/projects/hpi.html][exobrain/HPI]] for some of my raw thoughts and todos on the project
@@ -531,7 +530,7 @@ If you like the shell or just want to quickly convert/grab some information from
#+begin_src bash
$ hpi query my.coding.commits.commits --stream # stream JSON objects as they're read
--order-type datetime # find the 'datetime' attribute and order by that
- --after '2020-01-01' --before '2021-01-01' # in 2020
+ --after '2020-01-01 00:00:00' --before '2020-12-31 23:59:59' # in 2020
| jq '.committed_dt' -r # extract the datetime
# mangle the output a bit to group by month and graph it
| cut -d'-' -f-2 | sort | uniq -c | awk '{print $2,$1}' | sort -n | termgraph
@@ -552,8 +551,6 @@ If you like the shell or just want to quickly convert/grab some information from
2020-12: ▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇ 383.00
#+end_src
-See [[https://github.com/karlicoss/HPI/blob/master/doc/QUERY.md][query docs]]
-for more examples
** Querying Roam Research database
:PROPERTIES:
@@ -723,10 +720,10 @@ If you want to write modules for personal use but don't want to merge them into
Other HPI Repositories:
-- [[https://github.com/purarue/HPI][purarue/HPI]]
+- [[https://github.com/seanbreckenridge/HPI][seanbreckenridge/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/purarue/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/seanbreckenridge/HPI-template][template]].
* Related links
:PROPERTIES:
diff --git a/conftest.py b/conftest.py
deleted file mode 100644
index b959cfa..0000000
--- a/conftest.py
+++ /dev/null
@@ -1,47 +0,0 @@
-# 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/demo.py b/demo.py
index 080bc4c..ae0ba06 100755
--- a/demo.py
+++ b/demo.py
@@ -1,35 +1,29 @@
#!/usr/bin/env python3
from subprocess import check_call, DEVNULL
-from shutil import copytree, ignore_patterns
+from shutil import copy, copytree
import os
from os.path import abspath
-from sys import executable as python
from pathlib import Path
my_repo = Path(__file__).absolute().parent
-def run() -> None:
+def run():
# uses fixed paths; worth it for the sake of demonstration
# assumes we're in /tmp/my_demo now
# 1. clone git@github.com:karlicoss/my.git
- copytree(
- my_repo,
- 'my_repo',
- symlinks=True,
- ignore=ignore_patterns('.tox*'), # tox dir might have broken symlinks while tests are running in parallel
- )
+ copytree(my_repo, 'my_repo', symlinks=True)
# 2. prepare repositories you'd be using. For this demo we only set up Hypothesis
tox = 'TOX' in os.environ
if tox: # tox doesn't like --user flag
- check_call(f'{python} -m pip install git+https://github.com/karlicoss/hypexport.git'.split())
+ check_call('pip3 install git+https://github.com/karlicoss/hypexport.git'.split())
else:
try:
import hypexport
except ModuleNotFoundError:
- check_call(f'{python} -m pip --user git+https://github.com/karlicoss/hypexport.git'.split())
+ check_call('pip3 install --user git+https://github.com/karlicoss/hypexport.git'.split())
# 3. prepare some demo Hypothesis data
@@ -54,7 +48,7 @@ def run() -> None:
# 4. now we can use it!
os.chdir(my_repo)
- check_call([python, '-c', '''
+ check_call(['python3', '-c', '''
import my.hypothesis
pages = my.hypothesis.pages()
@@ -112,17 +106,13 @@ def named_temp_dir(name: str):
"""
Fixed name tmp dir
"""
- import tempfile
- td = Path(tempfile.gettempdir()) / name
+ td = (Path('/tmp') / name)
try:
td.mkdir(exist_ok=False)
yield td
finally:
- import os, shutil
- skip_cleanup = 'CI' in os.environ and os.name == 'nt'
- # TODO hmm for some reason cleanup on windows causes AccessError
- if not skip_cleanup:
- shutil.rmtree(str(td))
+ import shutil
+ shutil.rmtree(str(td))
def main():
diff --git a/doc/DENYLIST.md b/doc/DENYLIST.md
deleted file mode 100644
index 3d8dea0..0000000
--- a/doc/DENYLIST.md
+++ /dev/null
@@ -1,130 +0,0 @@
-For code reference, see: [`my.core.denylist.py`](../my/core/denylist.py)
-
-A helper module for defining denylists for sources programmatically (in layman's terms, this lets you remove some particular output from a module you don't want)
-
-Lets you specify a class, an attribute to match on,
-and a JSON file containing a list of values to deny/filter out
-
-As an example, this will use the `my.ip` module, as filtering incorrect IPs was the original use case for this module:
-
-```python
-class IP(NamedTuple):
- addr: str
- dt: datetime
-```
-
-A possible denylist file would contain:
-
-```json
-[
- {
- "addr": "192.168.1.1",
- },
- {
- "dt": "2020-06-02T03:12:00+00:00",
- }
-]
-```
-
-Note that if the value being compared to is not a single (non-array/object) JSON primitive
-(str, int, float, bool, None), it will be converted to a string before comparison
-
-To use this in code:
-
-```python
-from my.ip.all import ips
-filtered = DenyList("~/data/ip_denylist.json").filter(ips())
-```
-
-To add items to the denylist, in python (in a one-off script):
-
-```python
-from my.ip.all import ips
-from my.core.denylist import DenyList
-
-d = DenyList("~/data/ip_denylist.json")
-
-for ip in ips():
- # some custom code you define
- if ip.addr == ...:
- d.deny(key="ip", value=ip.ip)
- d.write()
-```
-
-... or interactively, which requires [`fzf`](https://github.com/junegunn/fzf) and [`pyfzf-iter`](https://pypi.org/project/pyfzf-iter/) (`python3 -m pip install pyfzf-iter`) to be installed:
-
-```python
-from my.ip.all import ips
-from my.core.denylist import DenyList
-
-d = DenyList("~/data/ip_denylist.json")
-d.deny_cli(ips()) # automatically writes after each selection
-```
-
-That will open up an interactive `fzf` prompt, where you can select an item to add to the denylist
-
-This is meant for relatively simple filters, where you want to filter items out
-based on a single attribute of a namedtuple/dataclass. If you want to do something
-more complex, I would recommend overriding the `all.py` file for that source and
-writing your own filter function there.
-
-For more info on all.py:
-
-https://github.com/karlicoss/HPI/blob/master/doc/MODULE_DESIGN.org#allpy
-
-This would typically be used in an overridden `all.py` file, or in a one-off script
-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/purarue/HPI)):
-
-```python
-from typing import Iterator
-
-from my.ip.common import IP
-from my.core.denylist import DenyList
-
-deny = DenyList("~/data/ip_denylist.json")
-
-# all possible data from the source
-def _ips() -> Iterator[IP]:
- from my.ip import discord
- # could add other imports here
-
- yield from discord.ips()
-
-
-# filtered data
-def ips() -> Iterator[IP]:
- yield from deny.filter(_ips())
-```
-
-To add items to the denylist, you could create a `__main__.py` in your namespace package (in this case, `my/ip/__main__.py`), with contents like:
-
-```python
-from my.ip import all
-
-if __name__ == "__main__":
- all.deny.deny_cli(all.ips())
-```
-
-Which could then be called like: `python3 -m my.ip`
-
-Or, you could just run it from the command line:
-
-```
-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/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, [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
-not interested in is because we want to be able to import from `my.ip.all`
-or `my.location.all` from other modules and get the filtered results, without
-having to mix data filtering logic with parsing/loading/caching (the stuff HPI does)
diff --git a/doc/DESIGN.org b/doc/DESIGN.org
index 81137d2..b8d40f9 100644
--- a/doc/DESIGN.org
+++ b/doc/DESIGN.org
@@ -4,7 +4,7 @@ note: this doc is in progress
- interoperable
- # note: this link doesn't work in org, but does for the github preview
+ # note: this link doesnt work in org, but does for the github preview
This is the main motivation and [[file:../README.org#why][why]] I created HPI in the first place.
Ideally it should be possible to hook into anything you can imagine -- regardless the database/programming language/etc.
diff --git a/doc/MODULES.org b/doc/MODULES.org
index 347d88d..a160ecb 100644
--- a/doc/MODULES.org
+++ b/doc/MODULES.org
@@ -16,12 +16,9 @@ If you have some issues with the setup, see [[file:SETUP.org::#troubleshooting][
- [[#toc][TOC]]
- [[#intro][Intro]]
- [[#configs][Configs]]
- - [[#mygoogletakeoutparser][my.google.takeout.parser]]
+ - [[#mygoogletakeoutpaths][my.google.takeout.paths]]
- [[#myhypothesis][my.hypothesis]]
- [[#myreddit][my.reddit]]
- - [[#mybrowser][my.browser]]
- - [[#mylocation][my.location]]
- - [[#mytimetzvia_location][my.time.tz.via_location]]
- [[#mypocket][my.pocket]]
- [[#mytwittertwint][my.twitter.twint]]
- [[#mytwitterarchive][my.twitter.archive]]
@@ -60,23 +57,13 @@ Some explanations:
For more thoughts on modules and their structure, see [[file:MODULE_DESIGN.org][MODULE_DESIGN]]
-* all.py
-
-Some modules have lots of different sources for data. For example,
-~my.location~ (location data) has lots of possible sources -- from
-~my.google.takeout.parser~, using the ~gpslogger~ android app, or through
-geolocating ~my.ip~ addresses. If you only plan on using one the modules, you
-can just import from the individual module, (e.g. ~my.google.takeout.parser~)
-or you can disable the others using the ~core~ config -- See the
-[[https://github.com/karlicoss/HPI/blob/master/doc/MODULE_DESIGN.org#allpy][MODULE_DESIGN]] docs for more details.
-
* Configs
The config snippets below are meant to be modified accordingly and *pasted into your private configuration*, e.g =$MY_CONFIG/my/config.py=.
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 ~@purarue~'s [[https://github.com/purarue/dotfiles/blob/master/.config/my/my/config/__init__.py][config]]
+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]]
# Nested Configurations before the doc generation using the block below
** [[file:../my/reddit][my.reddit]]
@@ -96,19 +83,19 @@ For an extensive/complex example, you can check out ~@purarue~'s [[https://githu
class pushshift:
'''
- Uses [[https://github.com/purarue/pushshift_comment_export][pushshift]] to get access to old comments
+ Uses [[https://github.com/seanbreckenridge/pushshift_comment_export][pushshift]] to get access to old comments
'''
# path[s]/glob to the exported JSON data
export_path: Paths
#+end_src
-
** [[file:../my/browser/][my.browser]]
- Parses browser history using [[http://github.com/purarue/browserexport][browserexport]]
+ Parses browser history using [[http://github.com/seanbreckenridge/browserexport][browserexport]]
#+begin_src python
+ @dataclass
class browser:
class export:
# path[s]/glob to your backed up browser history sqlite files
@@ -118,87 +105,9 @@ For an extensive/complex example, you can check out ~@purarue~'s [[https://githu
# paths to sqlite database files which you use actively
# to read from. For example:
# from browserexport.browsers.all import Firefox
- # export_path = Firefox.locate_database()
+ # active_databases = Firefox.locate_database()
export_path: Paths
#+end_src
-** [[file:../my/location][my.location]]
-
- Merged location history from lots of sources.
-
- The main sources here are
- [[https://github.com/mendhak/gpslogger][gpslogger]] .gpx (XML) files, and
- google takeout (using =my.google.takeout.parser=), with a fallback on
- manually defined home locations.
-
- 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/purarue/HPI/tree/master/my/ip][here]]
-
- #+begin_src python
- class location:
- home = (
- # supports ISO strings
- ('2005-12-04' , (42.697842, 23.325973)), # Bulgaria, Sofia
- # supports date/datetime objects
- (date(year=1980, month=2, day=15) , (40.7128 , -74.0060 )), # NY
- (datetime.fromtimestamp(1600000000, tz=timezone.utc), (55.7558 , 37.6173 )), # Moscow, Russia
- )
- # note: order doesn't matter, will be sorted in the data provider
-
- class gpslogger:
- # path[s]/glob to the exported gpx files
- export_path: Paths
-
- # default accuracy for gpslogger
- accuracy: float = 50.0
-
- class via_ip:
- # guess ~15km accuracy for IP addresses
- accuracy: float = 15_000
- #+end_src
-** [[file:../my/time/tz/via_location.py][my.time.tz.via_location]]
-
- Uses the =my.location= module to determine the timezone for a location.
-
- This can be used to 'localize' timezones. Most modules here return
- datetimes in UTC, to prevent confusion whether or not its a local
- timezone, one from UTC, or one in your timezone.
-
- 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
- - it's safer when either all of your objects are tz aware or all are tz unware, not a mixture
- - you might trust your original timezone, or it might just be UTC, and you want to use something more reasonable
-
- #+begin_src python
- TzPolicy = Literal[
- 'keep' , # if datetime is tz aware, just preserve it
- 'convert', # if datetime is tz aware, convert to provider's tz
- 'throw' , # if datetime is tz aware, throw exception
- ]
- #+end_src
-
- This is still a work in progress, plan is to integrate it with =hpi query=
- so that you can easily convert/localize timezones for some module/data
-
- #+begin_src python
- class time:
- class tz:
- policy = 'keep'
-
- class via_location:
- # less precise, but faster
- fast: bool = True
-
- # sort locations by date
- # in case multiple sources provide them out of order
- sort_locations: bool = True
-
- # if the accuracy for the location is more than 5km (this
- # isn't an accurate location, so shouldn't use it to determine
- # timezone), don't use
- require_accuracy: float = 5_000
- #+end_src
-
# TODO hmm. drawer raw means it can output outlines, but then have to manually erase the generated results. ugh.
@@ -209,17 +118,17 @@ import importlib
# from lint import all_modules # meh
# TODO figure out how to discover configs automatically...
modules = [
- ('google' , 'my.google.takeout.parser'),
- ('hypothesis' , 'my.hypothesis' ),
- ('pocket' , 'my.pocket' ),
- ('twint' , 'my.twitter.twint' ),
- ('twitter_archive', 'my.twitter.archive' ),
- ('lastfm' , 'my.lastfm' ),
- ('polar' , 'my.polar' ),
- ('instapaper' , 'my.instapaper' ),
- ('github' , 'my.github.gdpr' ),
- ('github' , 'my.github.ghexport' ),
- ('kobo' , 'my.kobo' ),
+ ('google' , 'my.google.takeout.paths'),
+ ('hypothesis' , 'my.hypothesis' ),
+ ('pocket' , 'my.pocket' ),
+ ('twint' , 'my.twitter.twint' ),
+ ('twitter_archive', 'my.twitter.archive' ),
+ ('lastfm' , 'my.lastfm' ),
+ ('polar' , 'my.polar' ),
+ ('instapaper' , 'my.instapaper' ),
+ ('github' , 'my.github.gdpr' ),
+ ('github' , 'my.github.ghexport' ),
+ ('kobo' , 'my.kobo' ),
]
def indent(s, spaces=4):
@@ -254,29 +163,14 @@ for cls, p in modules:
#+RESULTS:
-** [[file:../my/google/takeout/parser.py][my.google.takeout.parser]]
- Parses Google Takeout using [[https://github.com/purarue/google_takeout_parser][google_takeout_parser]]
+** [[file:../my/google/takeout/paths.py][my.google.takeout.paths]]
- 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=
-
- The directory set as takeout_path can be unpacked directories, or
- zip files of the exports, which are temporarily unpacked while creating
- the cachew cache
+ Module for locating and accessing [[https://takeout.google.com][Google Takeout]] data
#+begin_src python
- class google(user_config):
- # directory which includes unpacked/zipped takeouts
- takeout_path: Paths
-
- error_policy: ErrorPolicy = 'yield'
-
- # experimental flag to use core.kompress.ZipPath
- # instead of unpacking to a tmp dir via match_structure
- _use_zippath: bool = False
+ class google:
+ takeout_path: Paths # path/paths/glob for the takeout zips
#+end_src
** [[file:../my/hypothesis.py][my.hypothesis]]
diff --git a/doc/MODULE_DESIGN.org b/doc/MODULE_DESIGN.org
index 442dbf2..d51b677 100644
--- a/doc/MODULE_DESIGN.org
+++ b/doc/MODULE_DESIGN.org
@@ -2,77 +2,6 @@ Some thoughts on modules, how to structure them, and adding your own/extending H
This is slightly more advanced, and would be useful if you're trying to extend HPI by developing your own modules, or contributing back to HPI
-* TOC
-:PROPERTIES:
-:TOC: :include all :depth 1 :force (nothing) :ignore (this) :local (nothing)
-:END:
-:CONTENTS:
-- [[#allpy][all.py]]
-- [[#module-count][module count]]
-- [[#single-file-modules][single file modules]]
-- [[#adding-new-modules][Adding new modules]]
-- [[#an-extendable-module-structure][An Extendable module structure]]
-- [[#logging-guidelines][Logging guidelines]]
-:END:
-
-* all.py
-
-Some modules have lots of different sources for data. For example, ~my.location~ (location data) has lots of possible sources -- from ~my.google.takeout.parser~, using the ~gpslogger~ android app, or through geo locating ~my.ip~ addresses. For a module with multiple possible sources, its common to split it into files like:
-
- #+begin_src
- my/location
- ├── all.py -- specifies all possible sources/combines/merges data
- ├── common.py -- defines shared code, e.g. to merge data from across entries, a shared model (namedtuple/dataclass) or protocol
- ├── google_takeout.py -- source for data using my.google.takeout.parser
- ├── gpslogger.py -- source for data using gpslogger
- ├── home.py -- fallback source
- └── via_ip.py -- source using my.ip
- #+end_src
-
-Its common for each of those sources to have their own file, like ~my.location.google_takeout~, ~my.location.gpslogger~ and ~my.location.via_ip~, and then they all get merged into a single function in ~my.location.all~, like:
-
- #+begin_src python
- from .common import Location
-
- def locations() -> Iterator[Location]:
- # can add/comment out sources here to enable/disable them
- yield from _takeout_locations()
- yield from _gpslogger_locations()
-
-
- @import_source(module_name="my.location.google_takeout")
- def _takeout_locations() -> Iterator[Location]:
- from . import google_takeout
- yield from google_takeout.locations()
-
-
- @import_source(module_name="my.location.gpslogger")
- def _gpslogger_locations() -> Iterator[Location]:
- from . import gpslogger
- yield from gpslogger.locations()
- #+end_src
-
-If you want to disable a source, you have a few options.
-
- - If you're using a local editable install or just want to quickly troubleshoot, you can just comment out the line in the ~locations~ function
- - Since these are decorated behind ~import_source~, they automatically catch import/config errors, so instead of fatally erroring and crashing if you don't have a module setup, it'll warn you and continue to process the other sources. To get rid of the warnings, you can add the module you're not planning on using to your core config, like:
-
-#+begin_src python
- class core:
- disabled_modules = (
- "my.location.gpslogger",
- "my.location.via_ip",
- )
-#+end_src
-
-... 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/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.
-
-Another common way an ~all.py~ file is used is to merge data from a periodic export, and a GDPR export (e.g. see the ~stackexchange~, or ~github~ modules)
-
* module count
Having way too many modules could end up being an issue. For now, I'm basically happy to merge new modules - With the current module count, things don't seem to break much, and most of them are modules I use myself, so they get tested with my own data.
@@ -120,32 +49,18 @@ As an example of this, take a look at the [[https://github.com/karlicoss/HPI/tre
- Cons:
- Leads to some code duplication, as you can no longer use helper functions from ~my.core~ in the new repository
- Additional boilerplate - instructions, installation scripts, testing. It's not required, but typically you want to leverage ~setuptools~ to allows ~pip install git+https...~ type installs, which are used in ~hpi module install~
- - Is difficult to convert to a namespace module/directory down the road
Not all HPI Modules are currently at that level of complexity -- some are simple enough that one can understand the file by just reading it top to bottom. Some wouldn't make sense to split off into separate modules for one reason or another.
A related concern is how to structure namespace packages to allow users to easily extend them, and how this conflicts with single file modules (Keep reading below for more information on namespace packages/extension) If a module is converted from a single file module to a namespace with multiple files, it seems this is a breaking change, see [[https://github.com/karlicoss/HPI/issues/89][#89]] for an example of this. The current workaround is to leave it a regular python package with an =__init__.py= for some amount of time and send a deprecation warning, and then eventually remove the =__init__.py= file to convert it into a namespace package. For an example, see the [[https://github.com/karlicoss/HPI/blob/8422c6e420f5e274bd1da91710663be6429c666c/my/reddit/__init__.py][reddit init file]].
-Its quite a pain to have to convert a file from a single file module to a namespace module, so if there's *any* possibility that you might convert it to a namespace package, might as well just start it off as one, to avoid the pain down the road. As an example, say you were creating something to parse ~zsh~ history. Instead of creating ~my/zsh.py~, it would be better to create ~my/zsh/parser.py~. That lets users override the file using editable/namespace packages, and it also means in the future its much more trivial to extend it to something like:
-
- #+begin_src
- my/zsh
- ├── all.py -- e.g. combined/unique/sorted zsh history
- ├── aliases.py -- parse zsh alias files
- ├── common.py -- shared models/merging code
- ├── compdump.py -- parse zsh compdump files
- └── parser.py -- parse individual zsh history files
- #+end_src
-
-There's no requirement to follow this entire structure when you start off, the entire module could live in ~my/zsh/parser.py~, including all the merging/parsing/locating code. It just avoids the trouble in the future, and the only downside is having to type a bit more when importing from it.
-
#+html:
* Adding new modules
As always, if the changes you wish to make are small, or you just want to add a few modules, you can clone and edit an editable install of HPI. See [[file:SETUP.org][SETUP]] for more information
- The "proper way" (unless you want to contribute to the upstream) is to create a separate file hierarchy and add your module to =PYTHONPATH= (or use 'editable namespace packages' as described below, which also modifies your computed ~sys.path~)
+ The "proper way" (unless you want to contribute to the upstream) is to create a separate file hierarchy and add your module to =PYTHONPATH=.
# TODO link to 'overlays' documentation?
You can check my own [[https://github.com/karlicoss/hpi-personal-overlay][personal overlay]] as a reference.
@@ -174,7 +89,7 @@ There's no requirement to follow this entire structure when you start off, the e
Note: this section covers some of the complexities and benefits with this being a namespace package and/or editable install, so it assumes some familiarity with python/imports
-HPI is installed as a namespace package, which allows an additional way to add your own modules. For the details on namespace packages, see [[https://www.python.org/dev/peps/pep-0420/][PEP420]], or the [[https://packaging.python.org/guides/packaging-namespace-packages][packaging docs for a summary]], but for our use case, a sufficient description might be: Namespace packages let you split a package across multiple directories on disk.
+HPI is installed as a namespace package, which allows an additional way to add your own modules. For the details on namespace packges, see [[https://www.python.org/dev/peps/pep-0420/][PEP420]], or the [[https://packaging.python.org/guides/packaging-namespace-packages][packaging docs for a summary]], but for our use case, a sufficient description might be: Namespace packages let you split a package across multiple directories on disk.
Without adding a bulky/boilerplate-y plugin framework to HPI, as that increases the barrier to entry, [[https://packaging.python.org/guides/creating-and-discovering-plugins/#using-namespace-packages][namespace packages offers an alternative]] with little downsides.
@@ -208,13 +123,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/purarue/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/seanbreckenridge/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/purarue/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/seanbreckenridge/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/purarue/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/seanbreckenridge/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.
@@ -222,7 +137,7 @@ You may use the other modules or [[https://github.com/karlicoss/hpi-personal-ove
In this context, 'overlay'/'override' means you create your own namespace package/file structure like described above, and since your files are in front of the upstream repository files in the computed ~sys.path~ (either by using namespace modules, the ~PYTHONPATH~ or ~with_my~), your file overrides the upstream repository
-Related issues: [[https://github.com/karlicoss/HPI/issues/102][#102]], [[https://github.com/karlicoss/HPI/issues/89][#89]], [[https://github.com/karlicoss/HPI/issues/154][#154]]
+This isn't set in stone, and is currently being discussed in multiple issues: [[https://github.com/karlicoss/HPI/issues/102][#102]], [[https://github.com/karlicoss/HPI/issues/89][#89]], [[https://github.com/karlicoss/HPI/issues/154][#154]]
The main goals are:
@@ -230,102 +145,4 @@ The main goals are:
- good interop: e.g. ability to keep with the upstream, use modules coming from separate repositories, etc.
- ideally mypy friendly. This kind of means 'not too dynamic and magical', which is ultimately a good thing even if you don't care about mypy.
-~all.py~ using modules/sources behind ~import_source~ is the solution we've arrived at in HPI, because it meets all of these goals:
-
- - it doesn't require an additional plugin system, is just python imports and
- namespace packages
- - is generally mypy friendly (the only exception is the ~import_source~
- decorator, but that typically returns nothing if the import failed)
- - doesn't require you to maintain a fork of this repository, though you can maintain a separate HPI repository (so no patching/merge conflicts)
- - allows you to easily add/remove sources to the ~all.py~ module, either by:
- - overriding an ~all.py~ in your own repository
- - just commenting out the source/adding 2 lines to import and ~yield from~ your new source
- - doing nothing! (~import_source~ will catch the error and just warn you
- and continue to work without changing any code)
-
-It could be argued that namespace packages and editable installs are a bit complex for a new user to get the hang of, and this is true. But fortunately ~import_source~ means any user just using HPI only needs to follow the instructions when a warning is printed, or peruse the docs here a bit -- there's no need to clone or create your own override to just use the ~all.py~ file.
-
-There's no requirement to use this for individual modules, it just seems to be the best solution we've arrived at so far
-
-* Logging guidelines
-HPI doesn't enforce any specific logging mechanism, you're free to use whatever you prefer in your modules.
-
-However there are some general guidelines for developing modules that can make them more pleasant to use.
-
-- each module should have its unique logger, the easiest way to ensure that is simply use module's ~__name__~ attribute as the logger name
-
- In addition, this ensures the logger hierarchy reflect the package hierarchy.
- For instance, if you initialize the logger for =my.module= with specific settings, the logger for =my.module.helper= would inherit these settings. See more on that [[ https://docs.python.org/3/library/logging.html?highlight=logging#logger-objects][in python docs]].
-
- As a bonus, if you use the module ~__name__~, this logger will be automatically be picked up and used by ~cachew~.
-
-- often modules are processing multiple files, extracting data from each one ([[https://beepb00p.xyz/exports.html#types][incremental/synthetic exports]])
-
- It's nice to log each file name you're processing as =logger.info= so the user of module gets a sense of progress.
- If possible, add the index of file you're processing and the total count.
-
- #+begin_src python
- def process_all_data():
- paths = inputs()
- total = len(paths)
- width = len(str(total))
- for idx, path in enumerate(paths):
- # :>{width} to align the logs vertically
- logger.info(f'processing [{idx:>{width}}/{total:>{width}}] {path}')
- yield from process_path(path)
- #+end_src
-
- If there is a lot of logging happening related to a specific path, instead of adding path to each logging message manually, consider using [[https://docs.python.org/3/library/logging.html?highlight=loggeradapter#logging.LoggerAdapter][LoggerAdapter]].
-
-- log exceptions, but sparingly
-
- Generally it's a good practice to call ~logging.exception~ from the ~except~ clause, so it's immediately visible where the errors are happening.
-
- However, in HPI, instead of crashing on exceptions we often behave defensively and ~yield~ them instead (see [[https://beepb00p.xyz/mypy-error-handling.html][mypy assisted error handling]]).
-
- In this case logging every time may become a bit spammy, so use exception logging sparingly in this case.
- Typically it's best to rely on the downstream data consumer to handle the exceptions properly.
-
-- instead of =logging.getLogger=, it's best to use =my.core.make_logger=
-
- #+begin_src python
- from my.core import make_logger
-
- logger = make_logger(__name__)
-
- # or to set a custom level
- logger = make_logger(__name__, level='warning')
- #+end_src
-
- This sets up some nicer defaults over standard =logging= module:
-
- - colored logs (via =colorlog= library)
- - =INFO= as the initial logging level (instead of default =ERROR=)
- - logging full exception trace when even when logging outside of the exception handler
-
- This is particularly useful for [[https://beepb00p.xyz/mypy-error-handling.html][mypy assisted error handling]].
-
- By default, =logging= only logs the exception message (without the trace) in this case, which makes errors harder to debug.
- - control logging level from the shell via ~LOGGING_LEVEL_*~ env variable
-
- This can be useful to suppress logging output if it's too spammy, or showing more output for debugging.
-
- E.g. ~LOGGING_LEVEL_my_instagram_gdpr=DEBUG hpi query my.instagram.gdpr.messages~
-
- - experimental: passing env variable ~LOGGING_COLLAPSE=~ will "collapse" logging with the same level
-
- Instead of printing new logging line each time, it will 'redraw' the last logged line with a new logging message.
-
- This can be convenient if there are too many logs, you just need logging to get a sense of progress.
-
- - experimental: passing env variable ~ENLIGHTEN_ENABLE=yes~ will display TUI progress bars in some cases
-
- See [[https://github.com/Rockhopper-Technologies/enlighten#readme][https://github.com/Rockhopper-Technologies/enlighten#readme]]
-
- This can be convenient for showing the progress of parallel processing of different files from HPI:
-
- #+BEGIN_EXAMPLE
- ghexport.dal[111] 29%|████████████████████ | 29/100 [00:03<00:07, 10.03 files/s]
- rexport.dal[comments] 17%|████████ | 115/682 [00:03<00:14, 39.15 files/s]
- my.instagram.android 0%|▎ | 3/2631 [00:02<34:50, 1.26 files/s]
- #+END_EXAMPLE
+# TODO: add example with overriding 'all'
diff --git a/doc/OVERLAYS.org b/doc/OVERLAYS.org
deleted file mode 100644
index 7bafa48..0000000
--- a/doc/OVERLAYS.org
+++ /dev/null
@@ -1,322 +0,0 @@
-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
-# - proper mypy support
-# - TODO reusing parent modules?
-
-# You can see them TODO in overlays dir
-
-Consider a toy package/module structure with minimal code, without 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 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=
- 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 (editable install)
-
-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.
-
-** Installing with =--use-pep517=
-
-See here for discussion https://github.com/purarue/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())'
-: [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 (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=:
-
-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
-
-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 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
-: 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.
-
-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
-
-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 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/QUERY.md b/doc/QUERY.md
deleted file mode 100644
index 9a5d9d3..0000000
--- a/doc/QUERY.md
+++ /dev/null
@@ -1,304 +0,0 @@
-`hpi query` is a command line tool for querying the output of any `hpi` function.
-
-```
-Usage: hpi query [OPTIONS] FUNCTION_NAME...
-
- This allows you to query the results from one or more functions in HPI
-
- By default this runs with '-o json', converting the results to JSON and
- printing them to STDOUT
-
- You can specify '-o pprint' to just print the objects using their repr, or
- '-o repl' to drop into a ipython shell with access to the results
-
- While filtering using --order-key datetime, the --after, --before and
- --within flags parse the input to their datetime and timedelta equivalents.
- datetimes can be epoch time, the string 'now', or an date formatted in the
- ISO format. timedelta (durations) are parsed from a similar format to the
- GNU 'sleep' command, e.g. 1w2d8h5m20s -> 1 week, 2 days, 8 hours, 5 minutes,
- 20 seconds
-
- As an example, to query reddit comments I've made in the last month
-
- hpi query --order-type datetime --before now --within 4w my.reddit.all.comments
- or...
- hpi query --recent 4w my.reddit.all.comments
-
- Can also query within a range. To filter comments between 2016 and 2018:
- hpi query --order-type datetime --after '2016-01-01' --before '2019-01-01' my.reddit.all.comments
-
-Options:
- -o, --output [json|pprint|repl|gpx]
- what to do with the result [default: json]
- -s, --stream stream objects from the data source instead
- of printing a list at the end
- -k, --order-key TEXT order by an object attribute or dict key on
- the individual objects returned by the HPI
- function
- -t, --order-type [datetime|date|int|float]
- order by searching for some type on the
- iterable
- -a, --after TEXT while ordering, filter items for the key or
- type larger than or equal to this
- -b, --before TEXT while ordering, filter items for the key or
- type smaller than this
- -w, --within TEXT a range 'after' or 'before' to filter items
- by. see above for further explanation
- -r, --recent TEXT a shorthand for '--order-type datetime
- --reverse --before now --within'. e.g.
- --recent 5d
- --reverse / --no-reverse reverse the results returned from the
- functions
- -l, --limit INTEGER limit the number of items returned from the
- (functions)
- --drop-unsorted if the order of an item can't be determined
- while ordering, drop those items from the
- results
- --wrap-unsorted if the order of an item can't be determined
- while ordering, wrap them into an
- 'Unsortable' object
- --warn-exceptions if any errors are returned, print them as
- errors on STDERR
- --raise-exceptions if any errors are returned (as objects, not
- raised) from the functions, raise them
- --drop-exceptions ignore any errors returned as objects from
- the functions
- --help Show this message and exit.
-```
-
-This works with any function which returns an iterable, for example `my.coding.commits`, which searches for `git commit`s on your computer:
-
-```bash
-hpi query my.coding.commits
-```
-
-When run with a module, this does some analysis of the functions in that module and tries to find ones that look like data sources. If it can't figure out which, it prompts you like:
-
-```
-Which function should be used from 'my.coding.commits'?
-
- 1. commits
- 2. repos
-```
-
-You select the one you want by clicking `1` or `2` on your keyboard. Otherwise, you can provide a fully qualified path, like:
-
-```
-hpi query my.coding.commits.repos
-```
-
-The corresponding `repos` function this queries is defined in [`my/coding/commits.py`](../my/coding/commits.py)
-
-### Ordering/Filtering/Streaming
-
-By default, this just returns the items in the order they were returned by the function. This allows you to filter by specifying a `--order-key`, or `--order-type`. For example, to get the 10 most recent commits. `--order-type datetime` will try to automatically figure out which attribute to use. If it chooses the wrong one (since `Commit`s have both a `committed_dt` and `authored_dt`), you could tell it which to use. For example, to scan my computer and find the most recent commit I made:
-
-```
-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: propagate errors if there are breaking '
- 'schema changes',
- repo='/home/username/Repos/promnesia-fork',
- sha='22a434fca9a28df9b0915ccf16368df129d2c9ce',
- ref='refs/heads/smscalls-handle-result')
-```
-
-To instead limit in some range, you can use `--before` and `--within` to filter by a range. For example, to get all the commits I committed in the last day:
-
-```
-hpi query my.coding.commits.commits --order-type datetime --before now --within 1d
-```
-
-That prints a a list of `Commit` as JSON objects. You could also use `--output pprint` to pretty-print the objects or `--output repl` drop into a REPL.
-
-To process the JSON, you can pipe it to [`jq`](https://github.com/stedolan/jq). I often use `jq length` to get the count of some output:
-
-```
-hpi query my.coding.commits.commits --order-type datetime --before now --within 1d | jq length
-6
-```
-
-Because grabbing data `--before now` is such a common use case, the `--recent` flag is a shorthand for `--order-type datetime --reverse --before now --within`. The same as above, to get the commits from the last day:
-
-```
-hpi query my.coding.commits.commits --recent 1d | jq length
-6
-```
-
-To select a range of commits, you can use `--after` and `--before`, passing ISO or epoch timestamps. Those can be full `datetimes` (`2021-01-01T00:05:30`) or just dates (`2021-01-01`). For example, to get all the commits I made on January 1st, 2021:
-
-```
-hpi query my.coding.commits.commits --order-type datetime --after 2021-01-01 --before 2021-01-02 | jq length
-1
-```
-
-If you have [`dateparser`](https://github.com/scrapinghub/dateparser#how-to-use) installed, this supports dozens more natural language formats:
-
-```
-hpi query my.coding.commits.commits --order-type datetime --after 'last week' --before 'day before yesterday' | jq length
-28
-```
-
-If you're having issues ordering because there are exceptions in your results not all data is sortable (may have `None` for some attributes), you can use `--drop-unsorted` to drop those items from the results, or `--drop-exceptions` to remove the exceptions
-
-You can also stream the results, which is useful for functions that take a while to process or have a lot of data. For example, if you wanted to pick a sha hash from a particular repo, you could combine `jq` to `select` and pick that attribute from the JSON:
-
-```
-hpi query my.coding.commits.commits --recent 30d --stream | jq 'select(.repo | contains("HPI"))' | jq '.sha' -r
-4afa899c8b365b3c10e468f6279c02e316d3b650
-40de162fab741df594b4d9651348ee46ee021e9b
-e1cb229913482074dc5523e57ef0acf6e9ec2bb2
-87c13defd131e39292b93dcea661d3191222dace
-02c738594f2cae36ca4fab43cf9533fe6aa89396
-0b3a2a6ef3a9e4992771aaea0252fb28217b814a
-84817ce72d208038b66f634d4ceb6e3a4c7ec5e9
-47992b8e046d27fc5141839179f06f925c159510
-425615614bd508e28ccceb56f43c692240e429ab
-eed8f949460d768fb1f1c4801e9abab58a5f9021
-d26ad7d9ce6a4718f96346b994c3c1cd0d74380c
-aec517e53c6ac022f2b4cc91261daab5651cebf0
-44b75a88fdfc7af132f61905232877031ce32fcb
-b0ff6f29dd2846e97f8aa85a2ca73736b03254a8
-```
-
-`jq`s `select` function acts on a stream of JSON objects, not a list, so it filters the output of `hpi query` the objects are generated (the goal here is to conserve memory as items which aren't needed are filtered). The alternative would be to print the entire JSON list at the end, like:
-
-`hpi query my.coding.commits.commits --recent 30d | jq '.[] | select(.repo | contains("Repos/HPI"))' | jq '.sha' -r`, using `jq '.[]'` to convert the JSON list into a stream of JSON objects.
-
-## Usage on non-HPI code
-
-The command can accept any qualified function name, so this could for example be used to check the output of [`promnesia`](https://github.com/karlicoss/promnesia) sources:
-
-```
-hpi query promnesia.sources.smscalls | jq length
-371
-```
-
-This can be used on any function that produces an `Iterator`/`Generator` like output, as long as it can be called with no arguments.
-
-## GPX
-
-The `hpi query` command can also be used with the `--output gpx` flag to generate gpx files from a list of locations, like the ones defined in the `my.location` package. This could be used to extract some date range and create a `gpx` file which can then be visualized by a GUI application.
-
-This prints the contents for the `gpx` file to STDOUT, and prints warnings for any objects it could not convert to locations to STDERR, so pipe STDOUT to a output file, like `>out.gpx`
-
-```
-hpi query my.location.all --after '2021-07-01T00:00:00' --before '2021-07-05T00:00:00' --order-type datetime --output gpx >out.gpx
-```
-
-If you want to ignore any errors, you can use `--drop-exceptions`.
-
-To preview, you can use something like [`qgis`](https://qgis.org/en/site/) or for something easier more lightweight, [`gpxsee`](https://github.com/tumic0/GPXSee):
-
-`gpxsee out.gpx`:
-
-
-
-(Sidenote: this is [`@purarue`](https://github.com/purarue/)s locations, on a trip to Chicago)
-
-## Python reference
-
-The `hpi query` command is a CLI wrapper around the code in [`query.py`](../my/core/query.py) and [`query_range.py`](../my/core/query_range.py). The `select` function is the core of this, and `select_range` lets you specify dates, timedelta, start-end ranges, and other CLI-specific code.
-
-`my.core.query.select`:
-
-```
- A function to query, order, sort and filter items from one or more sources
- This supports iterables and lists of mixed types (including handling errors),
- by allowing you to provide custom predicates (functions) which can sort
- by a function, an attribute, dict key, or by the attributes values.
-
- Since this supports mixed types, there's always a possibility
- of KeyErrors or AttributeErrors while trying to find some value to order by,
- so this provides multiple mechanisms to deal with that
-
- 'where' lets you filter items before ordering, to remove possible errors
- or filter the iterator by some condition
-
- There are multiple ways to instruct select on how to order items. The most
- flexible is to provide an 'order_by' function, which takes an item in the
- iterator, does any custom checks you may want and then returns the value to sort by
-
- 'order_key' is best used on items which have a similar structure, or have
- the same attribute name for every item in the iterator. If you have a
- iterator of objects whose datetime is accessed by the 'timestamp' attribute,
- supplying order_key='timestamp' would sort by that (dictionary or attribute) key
-
- 'order_value' is the most confusing, but often the most useful. Instead of
- testing against the keys of an item, this allows you to write a predicate
- (function) to test against its values (dictionary, NamedTuple, dataclass, object).
- If you had an iterator of mixed types and wanted to sort by the datetime,
- but the attribute to access the datetime is different on each type, you can
- provide `order_value=lambda v: isinstance(v, datetime)`, and this will
- try to find that value for each type in the iterator, to sort it by
- the value which is received when the predicate is true
-
- 'order_value' is often used in the 'hpi query' interface, because of its brevity.
- Just given the input function, this can typically sort it by timestamp with
- no human intervention. It can sort of be thought as an educated guess,
- but it can always be improved by providing a more complete guess function
-
- Note that 'order_value' is also the most computationally expensive, as it has
- to copy the iterator in memory (using itertools.tee) to determine how to order it
- in memory
-
- The 'drop_exceptions', 'raise_exceptions', 'warn_exceptions' let you ignore or raise
- when the src contains exceptions. The 'warn_func' lets you provide a custom function
- to call when an exception is encountered instead of using the 'warnings' module
-
- src: an iterable of mixed types, or a function to be called,
- as the input to this function
-
- where: a predicate which filters the results before sorting
-
- order_by: a function which when given an item in the src,
- returns the value to sort by. Similar to the 'key' value
- typically passed directly to 'sorted'
-
- order_key: a string which represents a dict key or attribute name
- to use as they key to sort by
-
- order_value: predicate which determines which attribute on an ADT-like item to sort by,
- when given its value. lambda o: isinstance(o, datetime) is commonly passed to sort
- by datetime, without knowing the attributes or interface for the items in the src
-
- default: while ordering, if the order for an object cannot be determined,
- use this as the default value
-
- reverse: reverse the order of the resulting iterable
-
- limit: limit the results to this many items
-
- drop_unsorted: before ordering, drop any items from the iterable for which a
- order could not be determined. False by default
-
- wrap_unsorted: before ordering, wrap any items into an 'Unsortable' object. Place
- them at the front of the list. True by default
-
- drop_exceptions: ignore any exceptions from the src
-
- raise_exceptions: raise exceptions when received from the input src
-```
-
-`my.core.query_range.select_range`:
-
-```
- A specialized select function which offers generating functions
- to filter/query ranges from an iterable
-
- order_key and order_value are used in the same way they are in select
-
- If you specify order_by_value_type, it tries to search for an attribute
- on each object/type which has that type, ordering the iterable by that value
-
- unparsed_range is a tuple of length 3, specifying 'after', 'before', 'duration',
- i.e. some start point to allow the computed value we're ordering by, some
- end point and a duration (can use the RangeTuple NamedTuple to construct one)
-
- (this is typically parsed/created in my.core.__main__, from CLI flags
-
- 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/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 ee9571c..a10c9b3 100644
--- a/doc/SETUP.org
+++ b/doc/SETUP.org
@@ -105,11 +105,10 @@ You can also install some optional packages
They aren't necessary, but will improve your experience. At the moment these are:
-- [[https://github.com/ijl/orjson][orjson]]: a library for serializing data to JSON, used in ~my.core.serialize~ and the ~hpi query~ interface
- [[https://github.com/karlicoss/cachew][cachew]]: automatic caching library, which can greatly speedup data access
+- [[https://github.com/metachris/logzero][logzero]]: a nice logging library, supporting colors
+- [[https://github.com/ijl/orjson][orjson]]: a library for serializing data to JSON, used in ~my.core.serialize~ and the ~hpi query~ interface
- [[https://github.com/python/mypy][mypy]]: mypy is used for checking configs and troubleshooting
-- [[https://github.com/borntyping/python-colorlog][colorlog]]: colored formatter for ~logging~ module
-- [[https://github.com/Rockhopper-Technologies/enlighten]]: console progress bar library
* Setting up modules
This is an *optional step* as few modules work without extra setup.
@@ -192,13 +191,7 @@ HPI comes with a command line tool that can help you detect potential issues. Ru
If you only have a few modules set up, lots of them will error for you, which is expected, so check the ones you expect to work.
-If you're having issues with ~cachew~ or want to show logs to troubleshoot what may be happening, you can pass the debug flag (e.g., ~hpi --debug doctor my.module_name~) or set the ~LOGGING_LEVEL_HPI~ environment variable (e.g., ~LOGGING_LEVEL_HPI=debug hpi query my.module_name~) to print all logs, including the ~cachew~ dependencies. ~LOGGING_LEVEL_HPI~ could also be used to silence ~info~ logs, like ~LOGGING_LEVEL_HPI=warning hpi ...~
-
-If you want to enable logs for a particular module, you can use the
-~LOGGING_LEVEL_~ prefix and then the module name with underscores, like
-~LOGGING_LEVEL_my_hypothesis=debug hpi query my.hypothesis~
-
-If you want ~HPI~ to autocomplete the module names for you, this comes with shell completion, see [[../misc/completion/][misc/completion]]
+If you're having issues with ~cachew~ or want to show logs to troubleshoot what may be happening, you can pass the debug flag (e.g., ~hpi --debug doctor my.module_name~) or set the ~HPI_LOGS~ environment variable (e.g., ~HPI_LOGS=debug hpi query my.module_name~) to print all logs, including the ~cachew~ dependencies. ~HPI_LOGS~ could also be used to silence ~info~ logs, like ~HPI_LOGS=warning hpi ...~
If you have any ideas on how to improve it, please let me know!
@@ -387,7 +380,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/purarue/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/seanbreckenridge/pushshift_comment_export][my.reddit.pushshift]] to access older reddit comments, which both then get merged into =my.reddit.all.comments=
** Twitter
@@ -457,7 +450,7 @@ connect the data with other apps and libraries!
See more in [[file:../README.org::#how-do-you-use-it]["How do you use it?"]] section.
-Also check out [[https://beepb00p.xyz/myinfra.html#hpi][my personal infrastructure map]] to see where I'm using HPI.
+Also check out [[https://beepb00p.xyz/myinfra.html#hpi][my personal infrastructure map]] to see wher I'm using HPI.
* Adding/modifying modules
# TODO link to 'overlays' documentation?
diff --git a/doc/overlays/install_packages.sh b/doc/overlays/install_packages.sh
deleted file mode 100755
index 5853e08..0000000
--- a/doc/overlays/install_packages.sh
+++ /dev/null
@@ -1,4 +0,0 @@
-#!/bin/bash
-set -eux
-pip3 install --user "$@" -e main/
-pip3 install --user "$@" -e overlay/
diff --git a/doc/overlays/main/setup.py b/doc/overlays/main/setup.py
deleted file mode 100644
index 51ac55c..0000000
--- a/doc/overlays/main/setup.py
+++ /dev/null
@@ -1,17 +0,0 @@
-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/reddit.py b/doc/overlays/main/src/my/reddit.py
deleted file mode 100644
index ae4e481..0000000
--- a/doc/overlays/main/src/my/reddit.py
+++ /dev/null
@@ -1,11 +0,0 @@
-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
deleted file mode 100644
index feb9fce..0000000
--- a/doc/overlays/main/src/my/twitter/all.py
+++ /dev/null
@@ -1,7 +0,0 @@
-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
deleted file mode 100644
index 4121b5b..0000000
--- a/doc/overlays/main/src/my/twitter/common.py
+++ /dev/null
@@ -1,11 +0,0 @@
-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
deleted file mode 100644
index 22ea220..0000000
--- a/doc/overlays/main/src/my/twitter/gdpr.py
+++ /dev/null
@@ -1,9 +0,0 @@
-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
deleted file mode 100644
index aaaa244..0000000
--- a/doc/overlays/overlay/setup.py
+++ /dev/null
@@ -1,17 +0,0 @@
-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/twitter/all.py b/doc/overlays/overlay/src/my/twitter/all.py
deleted file mode 100644
index 895d84b..0000000
--- a/doc/overlays/overlay/src/my/twitter/all.py
+++ /dev/null
@@ -1,8 +0,0 @@
-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
deleted file mode 100644
index 782236c..0000000
--- a/doc/overlays/overlay/src/my/twitter/talon.py
+++ /dev/null
@@ -1,9 +0,0 @@
-print(f'[overlay] {__name__} hello')
-
-def tweets() -> list[str]:
- return [
- 'talon tweet 1',
- 'talon tweet 2',
- ]
-
-trigger_mypy_error: str = 123
diff --git a/doc/overlays/overlay2/setup.py b/doc/overlays/overlay2/setup.py
deleted file mode 100644
index e34e7de..0000000
--- a/doc/overlays/overlay2/setup.py
+++ /dev/null
@@ -1,17 +0,0 @@
-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/twitter/__init__.py b/doc/overlays/overlay2/src/my/twitter/__init__.py
deleted file mode 100644
index 9c5674f..0000000
--- a/doc/overlays/overlay2/src/my/twitter/__init__.py
+++ /dev/null
@@ -1,13 +0,0 @@
-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
deleted file mode 100644
index 106a115..0000000
--- a/doc/overlays/overlay3/setup.py
+++ /dev/null
@@ -1,17 +0,0 @@
-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/twitter/_hook.py b/doc/overlays/overlay3/src/my/twitter/_hook.py
deleted file mode 100644
index ce249ae..0000000
--- a/doc/overlays/overlay3/src/my/twitter/_hook.py
+++ /dev/null
@@ -1,9 +0,0 @@
-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
diff --git a/misc/.flake8-karlicoss b/misc/.flake8-karlicoss
deleted file mode 100644
index 5933253..0000000
--- a/misc/.flake8-karlicoss
+++ /dev/null
@@ -1,37 +0,0 @@
-[flake8]
-ignore =
- ## these mess up vertical aligment
- E126 # continuation line over-indented
- E202 # whitespace before )
- E203 # whitespace before ':' (e.g. in dict)
- E221 # multiple spaces before operator
- E241 # multiple spaces after ,
- E251 # unexpected spaces after =
- E261 # 2 spaces before comment. I actually think it's fine so TODO enable back later (TODO or not? still alignment)
- E271 # multiple spaces after keyword
- E272 # multiple spaces before keyword
- ##
- E266 # 'too many leading # in the comment' -- this is just unnecessary pickiness, sometimes it's nice to format a comment
- E302 # 2 blank lines
- E501 # 'line too long' -- kinda annoying and the default 79 is shit anyway
- E702 E704 # multiple statements on one line -- messes with : ... type declataions + sometimes asserts
- E731 # suggests always using def instead of lambda
-
- E402 # FIXME module level import -- we want it later
- E252 # TODO later -- whitespace around equals?
-# F541: f-string is missing placeholders -- perhaps too picky?
-
-# F841 is pretty useful (unused variables). maybe worth making it an error on CI
-
-
-# for imports: we might want to check these
-# F401 good: unused imports
-# E401: import order
-# F811: redefinition of unused import
-# todo from my.core import __NOT_HPI_MODULE__ this needs to be excluded from 'unused'
-#
-
-# as a reference:
-# 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/misc/check-twitter.sh b/misc/check-twitter.sh
deleted file mode 100755
index 1552673..0000000
--- a/misc/check-twitter.sh
+++ /dev/null
@@ -1,105 +0,0 @@
-#!/bin/bash
-# just a hacky script to check twitter module behaviour w.r.t. merging and normalising data
-# this checks against orger output for @karlicoss data
-
-set -eu
-
-FILE="$1"
-
-function check() {
- x="$1"
- if [[ $(rg --count "$x" "$FILE") != "1" ]]; then
- echo "FAILED! $x"
- fi
-}
-
-# only in old twitter archive data + test mentions
-check '2010-03-24 Wed 10:02.*@GDRussia подлагивает'
-
-# check that old twitter archive data replaces </>
-check '2011-05-12 Thu 17:51.*set ><'
-# this would probs be from twint or something?
-check '2013-06-01 Sat 18:48.* None:
- res = run(cmd, stderr=PIPE)
- errb = res.stderr; assert errb is not None
- err = errb.decode('utf8')
- if should_warn:
- assert MSG in err, res
- else:
- assert MSG not in err, res
- assert res.returncode == 0, res
-
-
-def _check(*cmd: str, should_warn: bool, run_as_cmd: bool=True) -> None:
- expecter = lambda *cmd: expect(*cmd, should_warn=should_warn)
- if cmd[0] == '-c':
- [_, code] = cmd
- if run_as_cmd:
- expecter('python3', '-c', code)
- # check as a script
- with TemporaryDirectory() as tdir:
- script = Path(tdir) / 'script.py'
- script.write_text(code)
- expecter('python3', str(script))
- else:
- expecter('python3', *cmd)
- what = 'warns' if should_warn else ' ' # meh
- logger.info(f"PASSED: {what}: {repr(cmd)}")
-
-
-def check_warn(*cmd: str, **kwargs) -> None:
- _check(*cmd, should_warn=True, **kwargs)
-
-def check_ok(*cmd: str, **kwargs) -> None:
- _check(*cmd, should_warn=False, **kwargs)
-
-
-# NOTE these three are actually sort of OK, they are allowed when it's a proper namespace package with all.py etc.
-# but more likely it means legacy behaviour or just misusing the package?
-# worst case it's just a warning I guess
-check_warn('-c', 'from my import fbmessenger')
-check_warn('-c', 'import my.fbmessenger')
-check_warn('-c', 'from my.fbmessenger import *')
-
-# note: dump_chat_history should really be deprecated, but it's a quick way to check we actually fell back to fbmessenger/export.py
-# NOTE: this is the most common legacy usecase
-check_warn('-c', 'from my.fbmessenger import messages, dump_chat_history')
-check_warn('-m', 'my.core', 'query' , 'my.fbmessenger.messages', '-o', 'pprint', '--limit=10')
-check_warn('-m', 'my.core', 'doctor', 'my.fbmessenger')
-check_warn('-m', 'my.core', 'module', 'requires', 'my.fbmessenger')
-
-# todo kinda annoying it doesn't work when executed as -c (but does as script!)
-# presumably because doesn't have proper line number information?
-# either way, it'a a bit of a corner case, the script behaviour is more important
-check_ok ('-c', 'from my.fbmessenger import export', run_as_cmd=False)
-check_ok ('-c', 'import my.fbmessenger.export')
-check_ok ('-c', 'from my.fbmessenger.export import *')
-check_ok ('-c', 'from my.fbmessenger.export import messages, dump_chat_history')
-check_ok ('-m', 'my.core', 'query' , 'my.fbmessenger.export.messages', '-o', 'pprint', '--limit=10')
-check_ok ('-m', 'my.core', 'doctor', 'my.fbmessenger.export')
-check_ok ('-m', 'my.core', 'module', 'requires', 'my.fbmessenger.export')
-
-# NOTE:
-# to check that overlays work, run something like
-# PYTHONPATH=misc/overlay_for_init_py_test/ hpi query my.fbmessenger.all.messages -s -o pprint --limit=10
-# you should see 1, 2, 3 from mixin.py
-# TODO would be nice to add an automated test for this
-
-# TODO with reddit, currently these don't work properly at all
-# only when imported from scripts etc?
diff --git a/misc/completion/README.md b/misc/completion/README.md
index 344387a..699e27e 100644
--- a/misc/completion/README.md
+++ b/misc/completion/README.md
@@ -10,23 +10,21 @@ eval "$(_HPI_COMPLETE=fish_source hpi)" # in ~/.config/fish/config.fish
That is slightly slower since its generating the completion code on the fly -- see [click docs](https://click.palletsprojects.com/en/8.0.x/shell-completion/#enabling-completion) for more info
-To use the generated completion files in this repository, you need to source the file in `./bash`, `./zsh`, or `./fish` depending on your shell.
-
-If you don't have HPI cloned locally, after installing `HPI` you can generate the file yourself using one of the commands above. For example, for `bash`: `_HPI_COMPLETE=bash_source hpi > ~/.config/hpi_bash_completion`, and then source it like `source ~/.config/hpi_bash_completion`
+To use the completions here:
### bash
-Put `source /path/to/hpi/repo/misc/completion/bash/_hpi` in your `~/.bashrc`
+Put `source /path/to/bash/_hpi` in your `~/.bashrc`
### zsh
You can either source the file:
-`source /path/to/hpi/repo/misc/completion/zsh/_hpi`
+`source /path/to/zsh/_hpi`
..or add the directory to your `fpath` to load it lazily:
-`fpath=("/path/to/hpi/repo/misc/completion/zsh/" "${fpath[@]}")` (Note: the directory, not the script `_hpi`)
+`fpath=("/path/to/zsh/" "${fpath[@]}")` (Note: the directory, not the script `_hpi`)
If your zsh configuration doesn't automatically run `compinit`, after modifying your `fpath` you should:
diff --git a/misc/completion/fish/hpi.fish b/misc/completion/fish/hpi.fish
index 23abca9..e8a8e56 100644
--- a/misc/completion/fish/hpi.fish
+++ b/misc/completion/fish/hpi.fish
@@ -1,5 +1,9 @@
function _hpi_completion;
- set -l response (env _HPI_COMPLETE=fish_complete COMP_WORDS=(commandline -cp) COMP_CWORD=(commandline -t) hpi);
+ set -l response;
+
+ for value in (env _HPI_COMPLETE=fish_complete COMP_WORDS=(commandline -cp) COMP_CWORD=(commandline -t) hpi);
+ set response $response $value;
+ end;
for completion in $response;
set -l metadata (string split "," $completion);
diff --git a/misc/completion/zsh/_hpi b/misc/completion/zsh/_hpi
index 805f564..95190b0 100644
--- a/misc/completion/zsh/_hpi
+++ b/misc/completion/zsh/_hpi
@@ -31,11 +31,5 @@ _hpi_completion() {
fi
}
-if [[ $zsh_eval_context[-1] == loadautofunc ]]; then
- # autoload from fpath, call function directly
- _hpi_completion "$@"
-else
- # eval/source/. command, register function for later
- compdef _hpi_completion hpi
-fi
+compdef _hpi_completion hpi;
diff --git a/misc/overlay_for_init_py_test/my/fbmessenger/all.py b/misc/overlay_for_init_py_test/my/fbmessenger/all.py
deleted file mode 100644
index 848de5f..0000000
--- a/misc/overlay_for_init_py_test/my/fbmessenger/all.py
+++ /dev/null
@@ -1,7 +0,0 @@
-from my.fbmessenger import export
-from . import mixin
-
-
-def messages():
- yield from mixin.messages()
- yield from export.messages()
diff --git a/misc/overlay_for_init_py_test/my/fbmessenger/mixin.py b/misc/overlay_for_init_py_test/my/fbmessenger/mixin.py
deleted file mode 100644
index 2f69480..0000000
--- a/misc/overlay_for_init_py_test/my/fbmessenger/mixin.py
+++ /dev/null
@@ -1,2 +0,0 @@
-def messages():
- yield from ['1', '2', '3']
diff --git a/my/arbtt.py b/my/arbtt.py
index 5d4bf8e..e672e5b 100644
--- a/my/arbtt.py
+++ b/my/arbtt.py
@@ -2,22 +2,18 @@
[[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 my.core.warnings import low
+ from .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:
@@ -25,9 +21,8 @@ def inputs() -> Sequence[Path]:
return get_files(user_config.logfiles)
-
-from my.core import Json, PathIsh, datetime_aware
-from my.core.compat import fromisoformat
+from .core import dataclass, Json, PathIsh, datetime_aware
+from .core.common import isoparse
@dataclass
@@ -43,7 +38,6 @@ 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)
@@ -51,13 +45,13 @@ class Entry:
# ugh. sometimes contains less that 6 decimal points
ds = ds[:-1] + '0' * (elen - lds) + 'Z'
elif lds > elen:
- # and sometimes more...
+ # ahd sometimes more...
ds = ds[:elen - 1] + 'Z'
- return fromisoformat(ds)
+ return isoparse(ds)
@property
- def active(self) -> str | None:
+ def active(self) -> Optional[str]:
# NOTE: WIP, might change this in the future...
ait = (w for w in self.json['windows'] if w['active'])
a = next(ait, None)
@@ -76,18 +70,17 @@ 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]
+ # otherise, 'merge' them
+ cmds = [base + ['--logfile', f] for f in inps]
- from subprocess import PIPE, Popen
-
- import ijson.backends.yajl2_cffi as ijson # type: ignore
+ import ijson.backends.yajl2_cffi as ijson # type: ignore
+ from subprocess import Popen, PIPE
for cmd in cmds:
with Popen(cmd, stdout=PIPE) as p:
out = p.stdout; assert out is not None
@@ -96,8 +89,8 @@ def entries() -> Iterable[Entry]:
def fill_influxdb() -> None:
- from .core.freezer import Freezer
from .core.influxdb import magic_fill
+ from .core.freezer import Freezer
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
@@ -109,8 +102,6 @@ def fill_influxdb() -> None:
magic_fill(fit, name=f'{entries.__module__}:{entries.__name__}')
-from .core import Stats, stat
-
-
+from .core import stat, Stats
def stats() -> Stats:
return stat(entries)
diff --git a/my/bluemaestro.py b/my/bluemaestro.py
old mode 100644
new mode 100755
index 8c739f0..ee85f21
--- a/my/bluemaestro.py
+++ b/my/bluemaestro.py
@@ -1,117 +1,83 @@
+#!/usr/bin/python3
"""
[[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 Protocol
+import re
+import sqlite3
+from typing import Iterable, Sequence, Set, Optional
-import pytz
-
-from my.core import (
- Paths,
- Res,
- Stats,
- get_files,
- make_logger,
- stat,
- unwrap,
-)
-from my.core.cachew import mcachew
-from my.core.pandas import DataFrameT, as_dataframe
+from my.core import get_files, LazyLogger, dataclass, Res
from my.core.sqlite import sqlite_connect_immutable
-
-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
+from my.config import bluemaestro as config
-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__)
+# todo control level via env variable?
+# i.e. HPI_LOGGING_MY_BLUEMAESTRO_LEVEL=debug
+logger = LazyLogger(__name__, level='debug')
def inputs() -> Sequence[Path]:
- cfg = make_config()
- return get_files(cfg.export_path)
+ return get_files(config.export_path)
Celsius = float
Percent = float
-mBar = float
-
+mBar = float
@dataclass
class Measurement:
- dt: datetime # todo aware/naive
- temp: Celsius
+ dt: datetime # todo aware/naive
+ temp : Celsius
humidity: Percent
pressure: mBar
dewpoint: Celsius
+# fixme: later, rely on the timezone provider
+# NOTE: the timezone should be set with respect to the export date!!!
+import pytz # type: ignore
+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)
return False if delegate is None else delegate(name)
-@mcachew(depends_on=inputs)
+from my.core.cachew import cache_dir
+from my.core.common import mcachew
+@mcachew(depends_on=lambda: inputs(), cache_path=cache_dir('bluemaestro'))
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)
- width = len(str(total))
+ dbs = inputs()
- last: datetime | None = None
+ last: Optional[datetime] = None
# tables are immutable, so can save on processing..
- processed_tables: set[str] = set()
- for idx, path in enumerate(paths):
- logger.info(f'processing [{idx:>{width}}/{total:>{width}}] {path}')
+ processed_tables: Set[str] = set()
+ for f in dbs:
+ logger.debug('processing %s', f)
tot = 0
new = 0
# todo assert increasing timestamp?
- with sqlite_connect_immutable(path) as db:
- db_dt: datetime | None = None
+ with sqlite_connect_immutable(f) as db:
+ db_dt: Optional[datetime] = None
try:
- datas = db.execute(
- f'SELECT "{path.name}" as name, Time, Temperature, Humidity, Pressure, Dewpoint FROM data ORDER BY log_index'
- )
+ datas = db.execute(f'SELECT "{f.name}" as name, Time, Temperature, Humidity, Pressure, Dewpoint FROM data ORDER BY log_index')
oldfmt = True
- [(db_dts,)] = db.execute('SELECT last_download FROM info')
+ db_dts = list(db.execute('SELECT last_download FROM info'))[0][0]
if db_dts == 'N/A':
# ??? happens for 20180923-20180928
continue
if db_dts.endswith(':'):
- db_dts += '00' # wtf.. happens on some day
+ db_dts += '00' # wtf.. happens on some day
db_dt = tz.localize(datetime.strptime(db_dts, '%Y-%m-%d %H:%M:%S'))
except sqlite3.OperationalError:
# Right, this looks really bad.
@@ -139,7 +105,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] # noqa: RUF015
+ frequencies = [list(db.execute(f'SELECT interval from {t.replace("_log", "_meta")}'))[0][0] for t in log_tables]
# todo could just filter out the older datapoints?? dunno.
@@ -149,13 +115,13 @@ def measurements() -> Iterable[Res[Measurement]]:
f'SELECT "{t}" AS name, unix, tempReadings / 10.0, humiReadings / 10.0, pressReadings / 10.0, dewpReadings / 10.0 FROM {t}'
for t in log_tables
)
- if len(log_tables) > 0: # ugh. otherwise end up with syntax error..
+ if len(log_tables) > 0: # ugh. otherwise end up with syntax error..
query = f'SELECT * FROM ({query}) ORDER BY name, unix'
datas = db.execute(query)
oldfmt = False
db_dt = None
- for (name, tsc, temp, hum, pres, dewp) in datas:
+ for i, (name, tsc, temp, hum, pres, dewp) in enumerate(datas):
if is_bad_table(name):
continue
@@ -175,11 +141,11 @@ def measurements() -> Iterable[Res[Measurement]]:
## sanity checks (todo make defensive/configurable?)
# not sure how that happens.. but basically they'd better be excluded
- lower = timedelta(days=6000 / 24) # ugh some time ago I only did it once in an hour.. in theory can detect from meta?
- upper = timedelta(days=10) # kinda arbitrary
+ lower = timedelta(days=6000 / 24) # ugh some time ago I only did it once in an hour.. in theory can detect from meta?
+ upper = timedelta(days=10) # kinda arbitrary
if not (db_dt - lower < dt < db_dt + timedelta(days=10)):
# todo could be more defenive??
- yield RuntimeError('timestamp too far out', path, name, db_dt, dt)
+ yield RuntimeError('timestamp too far out', f, name, db_dt, dt)
continue
# err.. sometimes my values are just interleaved with these for no apparent reason???
@@ -187,7 +153,7 @@ def measurements() -> Iterable[Res[Measurement]]:
yield RuntimeError('the weird sensor bug')
continue
- assert -60 <= temp <= 60, (path, dt, temp)
+ assert -60 <= temp <= 60, (f, dt, temp)
##
tot += 1
@@ -204,7 +170,7 @@ def measurements() -> Iterable[Res[Measurement]]:
dewpoint=dewp,
)
yield p
- logger.debug(f'{path}: new {new}/{tot}')
+ logger.debug('%s: new %d/%d', f, new, tot)
# logger.info('total items: %d', len(merged))
# for k, v in merged.items():
# # TODO shit. quite a few of them have varying values... how is that freaking possible????
@@ -214,11 +180,12 @@ def measurements() -> Iterable[Res[Measurement]]:
# for k, v in merged.items():
# yield Point(dt=k, temp=v) # meh?
-
+from my.core import stat, Stats
def stats() -> Stats:
return stat(measurements)
+from my.core.pandas import DataFrameT, as_dataframe
def dataframe() -> DataFrameT:
"""
%matplotlib gtk
@@ -233,7 +200,6 @@ def dataframe() -> DataFrameT:
def fill_influxdb() -> None:
from my.core import influxdb
-
influxdb.fill(measurements(), measurement=__name__)
@@ -241,6 +207,7 @@ def check() -> None:
temps = list(measurements())
latest = temps[:-2]
+ from my.core.error import unwrap
prev = unwrap(latest[-2]).dt
last = unwrap(latest[-1]).dt
@@ -250,12 +217,12 @@ def check() -> None:
#
# TODO also needs to be filtered out on processing, should be rejected on the basis of export date?
- POINTS_STORED = 6000 # on device?
+ POINTS_STORED = 6000 # on device?
FREQ_SEC = 60
SECS_STORED = POINTS_STORED * FREQ_SEC
- HOURS_STORED = POINTS_STORED / (60 * 60 / FREQ_SEC) # around 4 days
+ HOURS_STORED = POINTS_STORED / (60 * 60 / FREQ_SEC) # around 4 days
NOW = datetime.now()
assert NOW - last < timedelta(hours=HOURS_STORED / 2), f'old backup! {last}'
- assert last - prev < timedelta(minutes=3), f'bad interval! {last - prev}'
+ assert last - prev < timedelta(minutes=3), f'bad interval! {last - prev}'
single = (last - prev).seconds
diff --git a/my/body/blood.py b/my/body/blood.py
old mode 100644
new mode 100755
index 867568c..51a5114
--- a/my/body/blood.py
+++ b/my/body/blood.py
@@ -2,42 +2,41 @@
Blood tracking (manual org-mode entries)
"""
-from __future__ import annotations
-
-from collections.abc import Iterable
from datetime import datetime
-from typing import NamedTuple
-
-import orgparse
-import pandas as pd
-
-from my.config import blood as config # type: ignore[attr-defined]
+from typing import Iterable, NamedTuple, Optional
from ..core.error import Res
-from ..core.orgmode import one_table, parse_org_datetime
+from ..core.orgmode import parse_org_datetime, one_table
+
+
+import pandas as pd # type: ignore
+import orgparse
+
+
+from my.config import blood as config
class Entry(NamedTuple):
dt: datetime
- ketones : float | None=None
- glucose : float | None=None
+ ketones : Optional[float]=None
+ glucose : Optional[float]=None
- vitamin_d : float | None=None
- vitamin_b12 : float | None=None
+ vitamin_d : Optional[float]=None
+ vitamin_b12 : Optional[float]=None
- hdl : float | None=None
- ldl : float | None=None
- triglycerides: float | None=None
+ hdl : Optional[float]=None
+ ldl : Optional[float]=None
+ triglycerides: Optional[float]=None
- source : str | None=None
- extra : str | None=None
+ source : Optional[str]=None
+ extra : Optional[str]=None
Result = Res[Entry]
-def try_float(s: str) -> float | None:
+def try_float(s: str) -> Optional[float]:
l = s.split()
if len(l) == 0:
return None
@@ -106,7 +105,6 @@ 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)
@@ -132,3 +130,11 @@ def stats():
def test():
print(dataframe())
assert len(dataframe()) > 10
+
+
+def main():
+ print(data())
+
+
+if __name__ == '__main__':
+ main()
diff --git a/my/body/exercise/all.py b/my/body/exercise/all.py
index d0df747..4fee9d3 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...
- import pandas as pd
-
from ...endomondo import dataframe as EDF
- from ...runnerup import dataframe as RDF
+ from ...runnerup import dataframe as RDF
+
+ import pandas as pd # type: ignore
return pd.concat([
EDF(),
RDF(),
diff --git a/my/body/exercise/cardio.py b/my/body/exercise/cardio.py
index d8a6afd..083b972 100644
--- a/my/body/exercise/cardio.py
+++ b/my/body/exercise/cardio.py
@@ -3,6 +3,7 @@ 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 30f96f9..58c32b2 100644
--- a/my/body/exercise/cross_trainer.py
+++ b/my/body/exercise/cross_trainer.py
@@ -5,18 +5,16 @@ 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 __future__ import annotations
-
from datetime import datetime, timedelta
+from typing import Optional
-import pytz
+from ...core.pandas import DataFrameT, check_dataframe as cdf
+from ...core.orgmode import collect, Table, parse_org_datetime, TypedTable
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')
@@ -80,7 +78,7 @@ def cross_trainer_manual_dataframe() -> DataFrameT:
'''
Only manual org-mode entries
'''
- import pandas as pd
+ import pandas as pd # type: ignore[import]
df = pd.DataFrame(cross_trainer_data())
return df
@@ -93,7 +91,7 @@ def dataframe() -> DataFrameT:
'''
Attaches manually logged data (which Endomondo can't capture) and attaches it to Endomondo
'''
- import pandas as pd
+ import pandas as pd # type: ignore[import]
from ...endomondo import dataframe as EDF
edf = EDF()
@@ -107,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):
@@ -116,7 +114,7 @@ def dataframe() -> DataFrameT:
rows.append(rd) # presumably has an error set
continue
- idx: int | None
+ idx: Optional[int]
close = edf[edf['start_time'].apply(lambda t: pd_date_diff(t, mdate)).abs() < _DELTA]
if len(close) == 0:
idx = None
@@ -148,7 +146,7 @@ def dataframe() -> DataFrameT:
# todo careful about 'how'? we need it to preserve the errors
# maybe pd.merge is better suited for this??
df = edf.join(mdf, how='outer', rsuffix='_manual')
- # todo reindex? so we don't have Nan leftovers
+ # todo reindex? so we dont' have Nan leftovers
# todo set date anyway? maybe just squeeze into the index??
noendo = df['error'] == NO_ENDOMONDO
@@ -165,9 +163,7 @@ def dataframe() -> DataFrameT:
# TODO wtf?? where is speed coming from??
-from ...core import Stats, stat
-
-
+from ...core import stat, Stats
def stats() -> Stats:
return stat(cross_trainer_data)
diff --git a/my/body/sleep/common.py b/my/body/sleep/common.py
index fc288e5..0b6fa1c 100644
--- a/my/body/sleep/common.py
+++ b/my/body/sleep/common.py
@@ -1,6 +1,5 @@
-from ...core import Stats, stat
-from ...core.pandas import DataFrameT
-from ...core.pandas import check_dataframe as cdf
+from ...core import stat, Stats
+from ...core.pandas import DataFrameT, check_dataframe as cdf
class Combine:
@@ -8,8 +7,8 @@ class Combine:
self.modules = modules
@cdf
- def dataframe(self, *, with_temperature: bool=True) -> DataFrameT:
- import pandas as pd
+ def dataframe(self, with_temperature: bool=True) -> DataFrameT:
+ import pandas as pd # type: ignore
# todo include 'source'?
df = pd.concat([m.dataframe() for m in self.modules])
@@ -18,13 +17,6 @@ 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']
diff --git a/my/body/sleep/main.py b/my/body/sleep/main.py
index 2460e03..29b12a7 100644
--- a/my/body/sleep/main.py
+++ b/my/body/sleep/main.py
@@ -1,6 +1,7 @@
-from ... import emfit, jawbone
-from .common import Combine
+from ... import jawbone
+from ... import emfit
+from .common import Combine
_combined = Combine([
jawbone,
emfit,
diff --git a/my/body/weight.py b/my/body/weight.py
index d5478ef..28688b6 100644
--- a/my/body/weight.py
+++ b/my/body/weight.py
@@ -2,29 +2,21 @@
Weight data (manually logged)
'''
-from collections.abc import Iterator
-from dataclasses import dataclass
from datetime import datetime
-from typing import Any
+from typing import NamedTuple, Iterator
-from my import orgmode
-from my.core import make_logger
-from my.core.error import Res, extract_error_datetime, set_error_datetime
+from ..core import LazyLogger
+from ..core.error import Res, set_error_datetime, extract_error_datetime
-config = Any
+from .. import orgmode
+
+from my.config import weight as config
-def make_config() -> config:
- from my.config import weight as user_config # type: ignore[attr-defined]
-
- return user_config()
+log = LazyLogger('my.body.weight')
-log = make_logger(__name__)
-
-
-@dataclass
-class Entry:
+class Entry(NamedTuple):
dt: datetime
value: float
# TODO comment??
@@ -34,8 +26,6 @@ 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:
@@ -56,8 +46,8 @@ def from_orgmode() -> Iterator[Result]:
yield e
continue
# FIXME use timezone provider
- created = cfg.default_timezone.localize(created)
- assert created is not None # ??? somehow mypy wasn't happy?
+ created = config.default_timezone.localize(created)
+ assert created is not None #??? somehow mypy wasn't happy?
yield Entry(
dt=created,
value=w,
@@ -66,24 +56,22 @@ def from_orgmode() -> Iterator[Result]:
def make_dataframe(data: Iterator[Result]):
- import pandas as pd
-
+ import pandas as pd # type: ignore
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 = df.set_index('dt')
+ df.set_index('dt', inplace=True)
# TODO not sure about UTC??
df.index = pd.to_datetime(df.index, utc=True)
return df
@@ -93,7 +81,6 @@ 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/books/kobo.py b/my/books/kobo.py
index 40b7ed7..d5f5416 100644
--- a/my/books/kobo.py
+++ b/my/books/kobo.py
@@ -1,6 +1,7 @@
-from my.core import warnings
+from ..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 *
+from ..core.util import __NOT_HPI_MODULE__
+
+from ..kobo import *
diff --git a/my/browser/active_browser.py b/my/browser/active_browser.py
index 1686fc5..7005573 100644
--- a/my/browser/active_browser.py
+++ b/my/browser/active_browser.py
@@ -1,13 +1,12 @@
"""
-Parses active browser history by backing it up with [[http://github.com/purarue/sqlite_backup][sqlite_backup]]
+Parses active browser history by backing it up with [[http://github.com/seanbreckenridge/sqlite_backup][sqlite_backup]]
"""
REQUIRES = ["browserexport", "sqlite_backup"]
-from dataclasses import dataclass
from my.config import browser as user_config
-from my.core import Paths
+from my.core import Paths, dataclass
@dataclass
@@ -15,23 +14,20 @@ class config(user_config.active_browser):
# paths to sqlite database files which you use actively
# to read from. For example:
# from browserexport.browsers.all import Firefox
- # export_path = Firefox.locate_database()
+ # active_databases = Firefox.locate_database()
export_path: Paths
-from collections.abc import Iterator, Sequence
from pathlib import Path
+from typing import Sequence, Iterator
-from browserexport.merge import Visit, read_visits
+from my.core import get_files, Stats
+from browserexport.merge import read_visits, Visit
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)
+_patch_browserexport_logs()
def inputs() -> Sequence[Path]:
diff --git a/my/browser/all.py b/my/browser/all.py
index feb973a..a7d12b4 100644
--- a/my/browser/all.py
+++ b/my/browser/all.py
@@ -1,9 +1,9 @@
-from collections.abc import Iterator
-
-from browserexport.merge import Visit, merge_visits
+from typing import Iterator
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/common.py b/my/browser/common.py
index 058c134..9427f61 100644
--- a/my/browser/common.py
+++ b/my/browser/common.py
@@ -1,8 +1,11 @@
+import os
from my.core.util import __NOT_HPI_MODULE__
-def _patch_browserexport_logs(level: int):
- # grab the computed level (respects LOGGING_LEVEL_ prefixes) and set it on the browserexport logger
- from browserexport.log import setup as setup_browserexport_logger
+def _patch_browserexport_logs():
+ # patch browserexport logs if HPI_LOGS is present
+ if "HPI_LOGS" in os.environ:
+ from browserexport.log import setup as setup_browserexport_logger
+ from my.core.logging import mklevel
- setup_browserexport_logger(level)
+ setup_browserexport_logger(mklevel(os.environ["HPI_LOGS"]))
diff --git a/my/browser/export.py b/my/browser/export.py
index 52ade0e..3185d53 100644
--- a/my/browser/export.py
+++ b/my/browser/export.py
@@ -1,37 +1,33 @@
"""
-Parses browser history using [[http://github.com/purarue/browserexport][browserexport]]
+Parses browser history using [[http://github.com/seanbreckenridge/browserexport][browserexport]]
"""
REQUIRES = ["browserexport"]
-from collections.abc import Iterator, Sequence
-from dataclasses import dataclass
-from pathlib import Path
-
-from browserexport.merge import Visit, read_and_merge
-
-from my.core import (
- Paths,
- Stats,
- get_files,
- make_logger,
- stat,
-)
-from my.core.cachew import mcachew
-
-from .common import _patch_browserexport_logs
-
-import my.config # isort: skip
+from my.config import browser as user_config
+from my.core import Paths, dataclass
@dataclass
-class config(my.config.browser.export):
+class config(user_config.export):
# path[s]/glob to your backed up browser history sqlite files
export_path: Paths
-logger = make_logger(__name__)
-_patch_browserexport_logs(logger.level)
+from pathlib import Path
+from typing import Iterator, Sequence, List
+
+from my.core import Stats, get_files, LazyLogger
+from my.core.common import mcachew
+
+from browserexport.merge import read_and_merge, Visit
+
+from .common import _patch_browserexport_logs
+
+
+logger = LazyLogger(__name__, level="warning")
+
+_patch_browserexport_logs()
# all of my backed up databases
@@ -39,10 +35,16 @@ def inputs() -> Sequence[Path]:
return get_files(config.export_path)
-@mcachew(depends_on=inputs, logger=logger)
+def _cachew_depends_on() -> List[str]:
+ return [str(f) for f in inputs()]
+
+
+@mcachew(depends_on=_cachew_depends_on, logger=logger)
def history() -> Iterator[Visit]:
yield from read_and_merge(inputs())
def stats() -> Stats:
+ from my.core import stat
+
return {**stat(history)}
diff --git a/my/bumble/android.py b/my/bumble/android.py
index 3f9fa13..31625b1 100644
--- a/my/bumble/android.py
+++ b/my/bumble/android.py
@@ -3,24 +3,23 @@ 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 pathlib import Path
-
-from more_itertools import unique_everseen
-
-from my.core import Paths, get_files
-
-from my.config import bumble as user_config # isort: skip
+from typing import Iterator, Sequence, Optional, Dict
+from my.config import bumble as user_config
+
+
+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,88 +42,57 @@ class _BaseMessage:
@dataclass(unsafe_hash=True)
class _Message(_BaseMessage):
conversation_id: str
- reply_to_id: str | None
+ reply_to_id: Optional[str]
@dataclass(unsafe_hash=True)
class Message(_BaseMessage):
person: Person
- reply_to: Message | None
+ reply_to: Optional[Message]
import json
-import sqlite3
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]:
- for db_file in inputs():
- with sqlite_connect_immutable(db_file) as db:
- yield from _handle_db(db)
-
-
-def _handle_db(db: sqlite3.Connection) -> Iterator[EntitiesRes]:
- # todo hmm not sure
- # on the one hand kinda nice to use dataset..
- # on the other, it's somewhat of a complication, and
- # would be nice to have something type-directed for sql queries though
- # e.g. with typeddict or something, so the number of parameter to the sql query matches?
- for (user_id, user_name) in select(
- ('user_id', 'user_name'),
- 'FROM conversation_info',
- db=db,
- ):
- yield Person(
- user_id=user_id,
- user_name=user_name,
- )
-
- # note: has sender_name, but it's always None
- for ( id, conversation_id , created , is_incoming , payload_type , payload , reply_to_id) in select(
- ('id', 'conversation_id', 'created_timestamp', 'is_incoming', 'payload_type', 'payload', 'reply_to_id'),
- 'FROM message ORDER BY created_timestamp',
- db=db
- ):
- try:
- key = {'TEXT': 'text', 'QUESTION_GAME': 'text', 'IMAGE': 'url', 'GIF': 'url', 'AUDIO': 'url', 'VIDEO': 'url'}[payload_type]
- text = json.loads(payload)[key]
- yield _Message(
- id=id,
- # TODO not sure if utc??
- created=datetime.fromtimestamp(created / 1000),
- is_incoming=bool(is_incoming),
- text=text,
- conversation_id=conversation_id,
- reply_to_id=reply_to_id,
+from ..core.error import Res
+import sqlite3
+from ..core.sqlite import sqlite_connect_immutable
+def _entities() -> Iterator[Res[Union[Person, _Message]]]:
+ last = max(inputs()) # TODO -- need to merge multiple?
+ with sqlite_connect_immutable(last) as db:
+ for row in db.execute(f'SELECT user_id, user_name FROM conversation_info'):
+ (user_id, user_name) = row
+ yield Person(
+ user_id=user_id,
+ user_name=user_name,
)
- except Exception as e:
- yield e
-
-def _key(r: EntitiesRes):
- if isinstance(r, _Message):
- 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
-
-
-_UNKNOWN_PERSON = "UNKNOWN_PERSON"
+ # has sender_name, but it's always None
+ for row in db.execute(f'''
+ SELECT id, conversation_id, created_timestamp, is_incoming, payload_type, payload, reply_to_id
+ FROM message
+ ORDER BY created_timestamp
+ '''):
+ (id, conversation_id, created, is_incoming, payload_type, payload, reply_to_id) = row
+ try:
+ key = {'TEXT': 'text', 'QUESTION_GAME': 'text', 'IMAGE': 'url', 'GIF': 'url'}[payload_type]
+ text = json.loads(payload)[key]
+ yield _Message(
+ id=id,
+ # TODO not sure if utc??
+ created=datetime.fromtimestamp(created / 1000),
+ is_incoming=bool(is_incoming),
+ text=text,
+ conversation_id=conversation_id,
+ reply_to_id=reply_to_id,
+ )
+ except Exception as e:
+ yield e
def messages() -> Iterator[Res[Message]]:
- id2person: dict[str, Person] = {}
- id2msg: dict[str, Message] = {}
- for x in unique_everseen(_entities(), key=_key):
+ id2person: Dict[str, Person] = {}
+ id2msg: Dict[str, Message] = {}
+ for x in _entities():
if isinstance(x, Exception):
yield x
continue
@@ -133,12 +101,8 @@ def messages() -> Iterator[Res[Message]]:
continue
if isinstance(x, _Message):
reply_to_id = x.reply_to_id
- # hmm seems that sometimes there are messages with no corresponding conversation_info?
- # possibly if user never clicked on conversation before..
- person = id2person.get(x.conversation_id)
- if person is None:
- person = Person(user_id=x.conversation_id, user_name=_UNKNOWN_PERSON)
try:
+ person = id2person[x.conversation_id]
reply_to = None if reply_to_id is None else id2msg[reply_to_id]
except Exception as e:
yield e
@@ -154,4 +118,4 @@ def messages() -> Iterator[Res[Message]]:
id2msg[m.id] = m
yield m
continue
- assert_never(x)
+ assert False, type(x) # should be unreachable
diff --git a/my/calendar/holidays.py b/my/calendar/holidays.py
index 522672e..6fa3560 100644
--- a/my/calendar/holidays.py
+++ b/my/calendar/holidays.py
@@ -9,18 +9,16 @@ from datetime import date, datetime, timedelta
from functools import lru_cache
from typing import Union
-from my.core import Stats
-from my.core.time import zone_to_countrycode
+from ..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...
- 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)
@@ -48,6 +46,7 @@ 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/cfg.py b/my/cfg.py
index 9331e8a..e4020b4 100644
--- a/my/cfg.py
+++ b/my/cfg.py
@@ -1,6 +1,7 @@
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
deleted file mode 100644
index 9c6b7c9..0000000
--- a/my/codeforces.py
+++ /dev/null
@@ -1,78 +0,0 @@
-import json
-from collections.abc import Iterator, Sequence
-from dataclasses import dataclass
-from datetime import datetime, timezone
-from functools import cached_property
-from pathlib import Path
-
-from my.config import codeforces as config # type: ignore[attr-defined]
-from my.core import Res, datetime_aware, get_files
-
-
-def inputs() -> Sequence[Path]:
- return get_files(config.export_path)
-
-
-ContestId = int
-
-
-@dataclass
-class Contest:
- contest_id: ContestId
- when: datetime_aware
- name: str
-
-
-@dataclass
-class Competition:
- contest: Contest
- old_rating: int
- new_rating: int
-
- @cached_property
- def when(self) -> datetime_aware:
- return self.contest.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] = {}
-
- 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'],
- )
-
- 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(f"shouldn't happen: {path.name}")
-
-
-def data() -> Iterator[Res[Competition]]:
- return Parser(inputs=inputs()).parse()
diff --git a/doc/overlays/main/src/my/py.typed b/my/coding/__init__.py
similarity index 100%
rename from doc/overlays/main/src/my/py.typed
rename to my/coding/__init__.py
diff --git a/my/coding/codeforces.py b/my/coding/codeforces.py
new file mode 100644
index 0000000..659a2d9
--- /dev/null
+++ b/my/coding/codeforces.py
@@ -0,0 +1,113 @@
+#!/usr/bin/env python3
+from my.config import codeforces as config
+
+from datetime import datetime
+from typing import NamedTuple
+import json
+from typing import Dict, Iterator
+
+from ..common import cproperty, get_files
+from ..error import Res, unwrap
+from ..core.konsume import ignore, wrap
+
+from kython import fget
+# TODO remove
+from kython.kdatetime import as_utc
+
+
+Cid = int
+
+class Contest(NamedTuple):
+ cid: Cid
+ when: datetime
+
+ @classmethod
+ def make(cls, j) -> 'Contest':
+ return cls(
+ cid=j['id'],
+ when=as_utc(j['startTimeSeconds']),
+ )
+
+Cmap = Dict[Cid, Contest]
+
+
+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
+
+
+class Competition(NamedTuple):
+ contest_id: Cid
+ contest: str
+ cmap: Cmap
+
+ @cproperty
+ def uid(self) -> Cid:
+ return self.contest_id
+
+ def __hash__(self):
+ return hash(self.contest_id)
+
+ @cproperty
+ def when(self) -> datetime:
+ return self.cmap[self.uid].when
+
+ @cproperty
+ def summary(self) -> str:
+ return f'participated in {self.contest}' # TODO
+
+ @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 iter_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()
+
+ 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=fget(Competition.when)))
+
+
+def test():
+ assert len(get_data()) > 10
+
+
+def main():
+ for d in iter_data():
+ try:
+ d = unwrap(d)
+ except Exception as e:
+ print(f'ERROR! {d}')
+ else:
+ print(f'{d.when}: {d.summary}')
+
+
+
+if __name__ == '__main__':
+ main()
diff --git a/my/coding/commits.py b/my/coding/commits.py
index fe17dee..5b15db1 100644
--- a/my/coding/commits.py
+++ b/my/coding/commits.py
@@ -1,32 +1,30 @@
"""
Git commits data for repositories on your filesystem
"""
-
-from __future__ import annotations
-
REQUIRES = [
'gitpython',
]
-import shutil
-from collections.abc import Iterator, Sequence
-from dataclasses import dataclass, field
-from datetime import datetime, timezone
-from pathlib import Path
-from typing import Optional, cast
-from my.core import LazyLogger, PathIsh, make_config
-from my.core.cachew import cache_dir, mcachew
+import shutil
+from pathlib import Path
+from datetime import datetime, timezone
+from dataclasses import dataclass, field
+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.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: Sequence[str] | None = None
- names: Sequence[str] | None = None
+ emails: Optional[Sequence[str]] = None
+ names: Optional[Sequence[str]] = None
# experiment to make it lazy?
@@ -40,8 +38,9 @@ def config() -> commits_cfg:
##########################
-import git
-from git.repo.fun import is_git_dir
+import git # type: ignore
+from git.repo.fun import is_git_dir # type: ignore
+
log = LazyLogger(__name__, level='info')
@@ -60,7 +59,7 @@ class Commit:
committed_dt: datetime
authored_dt: datetime
message: str
- repo: str # TODO put canonical name here straight away??
+ repo: str # TODO put canonical name here straightaway??
sha: str
ref: Optional[str] = None
# TODO filter so they are authored by me
@@ -95,7 +94,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):
@@ -122,7 +121,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)
@@ -138,61 +137,61 @@ def canonical_name(repo: Path) -> str:
# else:
# rname = r.name
# if 'backups/github' in repo:
- # pass # TODO
+ # pass # TODO
def _fd_path() -> str:
# todo move it to core
- fd_path: str | None = shutil.which("fdfind") or shutil.which("fd-find") or shutil.which("fd")
+ fd_path: Optional[str] = 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(),
# '--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..
*roots,
]).decode('utf8').splitlines()
- candidates = {Path(o).resolve().absolute().parent for o in outputs}
+ candidates = set(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 = sorted(map(_git_root, candidates))
+ repos = list(sorted(map(_git_root, candidates)))
return repos
-def repos() -> list[Path]:
+def repos() -> List[Path]:
return git_repos_in(list(map(Path, config().roots)))
# 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)
- raise RuntimeError(f"Could not find a FETCH_HEAD/HEAD file in {_repo}")
+ else:
+ 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/coding/github.py b/my/coding/github.py
index c495554..9358b04 100644
--- a/my/coding/github.py
+++ b/my/coding/github.py
@@ -1,12 +1,9 @@
-from typing import TYPE_CHECKING
+import warnings
-from my.core import warnings
-
-warnings.high('my.coding.github is deprecated! Please use my.github.all instead!')
+warnings.warn('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 # noqa: F401
+from ..github.all import events, get_events
- # todo deprecate properly
- iter_events = events
+# todo deprecate properly
+iter_events = events
diff --git a/my/coding/topcoder.py b/my/coding/topcoder.py
new file mode 100644
index 0000000..43a2c8a
--- /dev/null
+++ b/my/coding/topcoder.py
@@ -0,0 +1,101 @@
+#!/usr/bin/env python3
+from my.config import topcoder as config
+
+from datetime import datetime
+from typing import NamedTuple
+import json
+from typing import Dict, Iterator
+
+from ..common import cproperty, get_files
+from ..error import Res, unwrap
+
+# TODO get rid of fget?
+from kython import fget
+from ..core.konsume import zoom, wrap, ignore
+
+
+# TODO json type??
+def _get_latest() -> Dict:
+ pp = max(get_files(config.export_path, glob='*.json'))
+ return json.loads(pp.read_text())
+
+
+class Competition(NamedTuple):
+ contest_id: str
+ contest: str
+ percentile: float
+ dates: str
+
+ @cproperty
+ def uid(self) -> str:
+ return self.contest_id
+
+ def __hash__(self):
+ return hash(self.contest_id)
+
+ @cproperty
+ def when(self) -> datetime:
+ return datetime.strptime(self.dates, '%Y-%m-%dT%H:%M:%S.%fZ')
+
+ @cproperty
+ 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
+ yield cls(
+ contest_id=cid,
+ contest=cname,
+ percentile=percentile,
+ dates=dates,
+ )
+
+
+def iter_data() -> Iterator[Res[Competition]]:
+ with wrap(_get_latest()) as j:
+ ignore(j, 'id', 'version')
+
+ res = j['result'].zoom()
+ 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()
+
+
+def get_data():
+ return list(sorted(iter_data(), key=fget(Competition.when)))
+
+
+def test():
+ assert len(get_data()) > 10
+
+def main():
+ for d in iter_data():
+ try:
+ d = unwrap(d)
+ except Exception as e:
+ print(f'ERROR! {d}')
+ else:
+ print(d.summary)
+
+
+if __name__ == '__main__':
+ main()
diff --git a/my/common.py b/my/common.py
index 22e9487..1b56fb5 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 301bf49..5bb316f 100644
--- a/my/config.py
+++ b/my/config.py
@@ -9,24 +9,17 @@ 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 # isort: skip
+#### vvvv you won't need this VVV in your personal config
+from my.core import init
###
-from datetime import tzinfo
-from pathlib import Path
-
-from my.core import PathIsh, Paths
-
+from my.core import Paths, PathIsh
class hypothesis:
# expects outputs from https://github.com/karlicoss/hypexport
# (it's just the standard Hypothes.is export format)
- export_path: Paths = r'/path/to/hypothesis/data'
+ export_path: Paths = '/path/to/hypothesis/data'
class instapaper:
export_path: Paths = ''
@@ -40,8 +33,6 @@ class pocket:
class github:
export_path: Paths = ''
- gdpr_dir: Paths = ''
-
class reddit:
class rexport:
export_path: Paths = ''
@@ -69,53 +60,22 @@ class pinboard:
export_dir: Paths = ''
class google:
- class maps:
- class android:
- export_path: Paths = ''
-
takeout_path: Paths = ''
-from collections.abc import Sequence
-from datetime import date, datetime, timedelta
-from typing import Union
-
+from typing import Sequence, Union, Tuple
+from datetime import datetime, date
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: LatLon | Sequence[tuple[DateIsh, LatLon]] = (1.0, -1.0)
- home_accuracy = 30_000.0
-
- class via_ip:
- accuracy: float
- for_duration: timedelta
-
- class gpslogger:
- export_path: Paths = ''
- accuracy: float
-
- class google_takeout_semantic:
- # a value between 0 and 100, 100 being the most confident
- # set to 0 to include all locations
- # https://locationhistoryformat.com/reference/semantic/#/$defs/placeVisit/properties/locationConfidence
- require_confidence: float = 40
- # default accuracy for semantic locations
- accuracy: float = 100
-
-
-from typing import Literal
+ home: Union[LatLon, Sequence[Tuple[DateIsh, LatLon]]] = (1.0, -1.0)
class time:
class tz:
- policy: Literal['keep', 'convert', 'throw']
-
- class via_location:
- fast: bool
- sort_locations: bool
- require_accuracy: float
+ pass
class orgmode:
@@ -126,9 +86,10 @@ class arbtt:
logfiles: Paths
+from typing import Optional
class commits:
- emails: Sequence[str] | None
- names: Sequence[str] | None
+ emails: Optional[Sequence[str]]
+ names: Optional[Sequence[str]]
roots: Sequence[PathIsh]
@@ -146,17 +107,9 @@ class bumble:
export_path: Paths
-class tinder:
- class android:
- export_path: Paths
-
-
class instagram:
class android:
export_path: Paths
- username: str | None
- full_name: str | None
-
class gdpr:
export_path: Paths
@@ -166,121 +119,19 @@ class hackernews:
export_path: Paths
-class materialistic:
- export_path: Paths
-
-
class fbmessenger:
class fbmessengerexport:
export_db: PathIsh
- facebook_id: str | None
class android:
export_path: Paths
-class twitter_archive:
- export_path: Paths
-
-
class twitter:
class talon:
export_path: Paths
- class android:
- export_path: Paths
-
-
-class twint:
- export_path: Paths
-
class browser:
class export:
export_path: Paths = ''
class active_browser:
export_path: Paths = ''
-
-
-class telegram:
- class telegram_backup:
- export_path: PathIsh = ''
-
-
-class demo:
- data_path: Paths
- username: str
- timezone: tzinfo
-
-
-class simple:
- count: int
-
-
-class vk_messages_backup:
- storage_path: Path
- user_id: int
-
-
-class kobo:
- export_path: Paths
-
-
-class feedly:
- export_path: Paths
-
-
-class feedbin:
- export_path: Paths
-
-
-class taplog:
- export_path: Paths
-
-
-class lastfm:
- export_path: Paths
-
-
-class rescuetime:
- export_path: Paths
-
-
-class runnerup:
- export_path: Paths
-
-
-class emfit:
- export_path: Path
- timezone: tzinfo
- excluded_sids: list[str]
-
-
-class foursquare:
- export_path: Paths
-
-
-class rtm:
- export_path: Paths
-
-
-class imdb:
- export_path: Paths
-
-
-class roamresearch:
- export_path: Paths
- username: str
-
-
-class whatsapp:
- class android:
- export_path: Paths
- my_user_id: str | None
-
-
-class harmonic:
- export_path: Paths
-
-
-class monzo:
- class monzoexport:
- export_path: Paths
diff --git a/my/core/__init__.py b/my/core/__init__.py
index a8a41f4..f680f37 100644
--- a/my/core/__init__.py
+++ b/my/core/__init__.py
@@ -1,61 +1,17 @@
# this file only keeps the most common & critical types/utility functions
-from typing import TYPE_CHECKING
+from .common import PathIsh, Paths, Json
+from .common import get_files
+from .common import LazyLogger
+from .common import warn_if_empty
+from .common import stat, Stats
+from .common import datetime_naive, datetime_aware
from .cfg import make_config
-from .common import PathIsh, Paths, get_files
-from .compat import assert_never
-from .error import Res, notnone, unwrap
-from .logging import (
- make_logger,
-)
-from .stats import Stats, stat
-from .types import (
- Json,
- datetime_aware,
- datetime_naive,
-)
from .util import __NOT_HPI_MODULE__
-from .utils.itertools import warn_if_empty
-LazyLogger = make_logger # TODO deprecate this in favor of make_logger
+from .error import Res, unwrap
-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__ = [
- '__NOT_HPI_MODULE__',
- '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',
-]
-
-
-## experimental for now
-# 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] # noqa: F401
-except:
- pass
-##
+# just for brevity in modules
+from dataclasses import dataclass
+from pathlib import Path
diff --git a/my/core/__main__.py b/my/core/__main__.py
index 7e2d8f9..22068a6 100644
--- a/my/core/__main__.py
+++ b/my/core/__main__.py
@@ -1,52 +1,50 @@
-from __future__ import annotations
-
import functools
import importlib
import inspect
import os
-import shlex
-import shutil
import sys
-import tempfile
import traceback
-from collections.abc import Iterable, Sequence
-from contextlib import ExitStack
-from itertools import chain
+from typing import Optional, Sequence, Iterable, List, Type, Any, Callable
from pathlib import Path
-from subprocess import PIPE, CompletedProcess, Popen, check_call, run
-from typing import Any, Callable
+from subprocess import check_call, run, PIPE, CompletedProcess
import click
-@functools.lru_cache
-def mypy_cmd() -> Sequence[str] | None:
+@functools.lru_cache()
+def mypy_cmd() -> Optional[Sequence[str]]:
try:
# preferably, use mypy from current python env
- import mypy # noqa: F401 fine not to use it
+ import mypy
+ return [sys.executable, '-m', 'mypy']
except ImportError:
pass
- else:
- return [sys.executable, '-m', 'mypy']
# ok, not ideal but try from PATH
+ import shutil
if shutil.which('mypy'):
return ['mypy']
warning("mypy not found, so can't check config with it. See https://github.com/python/mypy#readme if you want to install it and retry")
return None
-def run_mypy(cfg_path: Path) -> CompletedProcess | None:
+from types import ModuleType
+def run_mypy(pkg: ModuleType) -> Optional[CompletedProcess]:
+ from .preinit import get_mycfg_dir
+ mycfg_dir = get_mycfg_dir()
+ # todo ugh. not sure how to extract it from pkg?
+
# todo dunno maybe use the same mypy config in repository?
# I'd need to install mypy.ini then??
env = {**os.environ}
mpath = env.get('MYPYPATH')
- mpath = str(cfg_path) + ('' if mpath is None else f':{mpath}')
+ mpath = str(mycfg_dir) + ('' if mpath is None else f':{mpath}')
env['MYPYPATH'] = mpath
+
cmd = mypy_cmd()
if cmd is None:
return None
- mres = run([ # noqa: UP022,PLW1510
+ mres = run([
*cmd,
'--namespace-packages',
'--color-output', # not sure if works??
@@ -54,7 +52,7 @@ def run_mypy(cfg_path: Path) -> CompletedProcess | None:
'--show-error-codes',
'--show-error-context',
'--check-untyped-defs',
- '-p', 'my.config',
+ '-p', pkg.__name__,
], stderr=PIPE, stdout=PIPE, env=env)
return mres
@@ -66,27 +64,20 @@ 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__))
@@ -95,7 +86,6 @@ def tb(e: Exception) -> None:
def config_create() -> None:
from .preinit import get_mycfg_dir
-
mycfg_dir = get_mycfg_dir()
created = False
@@ -104,8 +94,7 @@ 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
@@ -128,8 +117,7 @@ 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:
@@ -140,15 +128,13 @@ class example:
sys.exit(1)
-# todo return the config as a result?
+# 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__) # type: ignore[attr-defined]
except Exception as e:
errors.append(e)
error('failed to determine module import path')
@@ -156,89 +142,62 @@ def config_ok() -> bool:
else:
info(f'import order: {paths}')
- # 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'''
+ import my.config as cfg
+ except Exception as e:
+ errors.append(e)
+ error("failed to import the config")
+ tb(e)
+ # todo yield exception here? so it doesn't fail immediately..
+ # I guess it's fairly critical and worth exiting immediately
+ sys.exit(1)
+
+ cfg_path = cfg.__file__# todo might be better to use __path__?
+ info(f"config file : {cfg_path}")
+
+ import my.core as core
+ try:
+ core_pkg_path = str(Path(core.__path__[0]).parent) # type: ignore[attr-defined]
+ if cfg_path.startswith(core_pkg_path):
+ 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)
tb(e)
- else:
- info(f"config path : {cfg_path}")
- ##
- ## check syntax
- with tempfile.TemporaryDirectory() as td:
- # 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
- 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
- cmd = [sys.executable, '-m', 'compileall', '-q', str(tdir)]
+ # todo for some reason compileall.compile_file always returns true??
+ try:
+ cmd = [sys.executable, '-m', 'compileall', str(cfg_path)]
+ check_call(cmd)
+ info('syntax check: ' + ' '.join(cmd))
+ except Exception as e:
+ errors.append(e)
- 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, dirs_exist_ok=True)
- check_call(cmd)
- info('syntax check: ' + ' '.join(cmd))
- except Exception as e:
- errors.append(e)
- tb(e)
- ##
-
- ## check types
- mypy_res = run_mypy(cfg_path)
- if mypy_res is not None: # has mypy
- rc = mypy_res.returncode
+ mres = run_mypy(cfg)
+ if mres is not None: # has mypy
+ rc = mres.returncode
if rc == 0:
info('mypy check : success')
else:
error('mypy check: failed')
errors.append(RuntimeError('mypy failed'))
- sys.stderr.write(indent(mypy_res.stderr.decode('utf8')))
- sys.stderr.write(indent(mypy_res.stdout.decode('utf8')))
- ##
-
- ## finally, try actually importing the config (it should use same cfg_path)
- try:
- import my.config
- except Exception as e:
- errors.append(e)
- error("failed to import the config")
- tb(e)
- ##
+ sys.stderr.write(indent(mres.stderr.decode('utf8')))
+ sys.stderr.write(indent(mres.stdout.decode('utf8')))
if len(errors) > 0:
error(f'config check: {len(errors)} errors')
return False
-
- # note: shouldn't exit here, might run something else
- info('config check: success!')
- return True
+ else:
+ # note: shouldn't exit here, might run something else
+ info('config check: success!')
+ return True
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:
@@ -249,20 +208,21 @@ 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?
verbose = True
vw = '' if verbose else '; pass --verbose to print more information'
+ from . import common
+ common.QUICK_STATS = quick # dirty, but hopefully OK for cli
+
tabulate_warnings()
- import contextlib
-
+ from .util import get_stats, HPIModule
+ from .stats import guess_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:
@@ -273,18 +233,18 @@ 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
try:
- mod = importlib.import_module(m) # noqa: F841
+ mod = importlib.import_module(m)
except Exception as e:
# todo more specific command?
error(f'{click.style("FAIL", fg="red")}: {m:<50} loading failed{vw}')
# check that this is an import error in particular, not because
- # of a ModuleNotFoundError because some dependency wasn't installed
+ # of a ModuleNotFoundError because some dependency wasnt installed
if isinstance(e, (ImportError, AttributeError)):
warn_my_config_import_error(e)
if verbose:
@@ -292,23 +252,19 @@ def modules_check(*, verbose: bool, list_all: bool, quick: bool, for_modules: li
continue
info(f'{click.style("OK", fg="green")} : {m:<50}')
- # TODO add hpi 'stats'? instead of doctor? not sure
- stats = get_stats(m, guess=True)
+ # 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)
if stats is None:
eprint(" - no 'stats' function, can't check the data")
# todo point to a readme on the module structure or something?
continue
- quick_context = quick_stats() if quick else contextlib.nullcontext()
-
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:
- res = stats(**kwargs)
+ res = stats()
assert res is not None, 'stats() returned None'
except Exception as ee:
warning(f' - {click.style("stats:", fg="red")} computing failed{vw}')
@@ -323,8 +279,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 = ''
@@ -340,94 +296,43 @@ 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]:
+def _requires(module: str) -> Sequence[str]:
from .discovery_pure import module_by_name
-
- mods = [module_by_name(module) for module in modules]
- res = []
- for mod in mods:
- if mod.legacy is not None:
- warning(mod.legacy)
-
- reqs = mod.requires
- if reqs is None:
- warning(f"Module {mod.name} has no REQUIRES specification")
- continue
- for r in reqs:
- if r not in res:
- res.append(r)
- return res
+ mod = module_by_name(module)
+ # todo handle when module is missing
+ r = mod.requires
+ if r is None:
+ error(f"Module {module} has no REQUIRES specification")
+ sys.exit(1)
+ return r
-def module_requires(*, module: Sequence[str]) -> None:
- if isinstance(module, str):
- # legacy behavior, used to take a since argument
- module = [module]
- rs = [f"'{x}'" for x in _requires(modules=module)]
+def module_requires(*, module: str) -> None:
+ rs = [f"'{x}'" for x in _requires(module)]
eprint(f'dependencies of {module}')
for x in rs:
click.echo(x)
-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]
-
- requirements = _requires(module)
-
- if len(requirements) == 0:
- 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', *(['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/
+def module_install(*, user: bool, module: str) -> None:
+ # TODO hmm. not sure how it's gonna work -- presumably people use different means of installing...
+ # how do I install into the 'same' environment??
+ import shlex
+ cmd = [
+ sys.executable, '-m', 'pip', 'install',
+ *(['--user'] if user else []), # meh
+ *_requires(module),
]
-
- cmds = []
- # disable parallel on windows, sometimes throws a
- # '[WinError 32] The process cannot access the file because it is being used by another process'
- # same on mac it seems? possible race conditions which are hard to debug?
- # WARNING: Error parsing requirements for sqlalchemy: [Errno 2] No such file or directory: '/Users/runner/work/HPI/HPI/.tox/mypy-misc/lib/python3.7/site-packages/SQLAlchemy-2.0.4.dist-info/METADATA'
- if parallel and sys.platform not in ['win32', 'cygwin', 'darwin']:
- # todo not really sure if it's safe to install in parallel like this
- # but definitely doesn't hurt to experiment for e.g. mypy pipelines
- # pip has '--use-feature=fast-deps', but it doesn't really work
- # 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])
- else:
- if parallel:
- warning('parallel install is not supported on this platform, installing sequentially...')
- # install everything in one cmd
- cmds.append(pre_cmd + list(requirements))
-
- with ExitStack() as exit_stack:
- popens = []
- for cmd in cmds:
- eprint('Running: ' + ' '.join(map(shlex.quote, cmd)))
- popen = exit_stack.enter_context(Popen(cmd))
- popens.append(popen)
-
- for popen in popens:
- ret = popen.wait()
- assert ret == 0, popen
+ eprint('Running: ' + ' '.join(map(shlex.quote, cmd)))
+ check_call(cmd)
def _ui_getchar_pick(choices: Sequence[str], prompt: str = 'Select from: ') -> int:
@@ -457,11 +362,11 @@ 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]]:
- from .query import QueryException, locate_qualified_function
+def _locate_functions_or_prompt(qualified_names: List[str], prompt: bool = True) -> Iterable[Callable[..., Any]]:
+ from .query import locate_qualified_function, QueryException
from .stats import is_data_provider
- # if not connected to a terminal, can't prompt
+ # if not connected to a terminal, cant prompt
if not sys.stdout.isatty():
prompt = False
@@ -475,9 +380,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 as ie:
+ except Exception:
eprint(f"During fallback, importing '{qualname}' as module failed")
- raise qr_err from ie
+ raise qr_err
# find data providers in this module
data_providers = [f for _, f in inspect.getmembers(mod, inspect.isfunction) if is_data_provider(f)]
@@ -491,7 +396,7 @@ def _locate_functions_or_prompt(qualified_names: list[str], *, prompt: bool = Tr
else:
choices = [f.__name__ for f in data_providers]
if prompt is False:
- # there's more than one possible data provider in this module,
+ # theres more than one possible data provider in this module,
# STDOUT is not a TTY, can't prompt
eprint("During fallback, more than one possible data provider, can't prompt since STDOUT is not a TTY")
eprint("Specify one of:")
@@ -505,42 +410,33 @@ def _locate_functions_or_prompt(qualified_names: list[str], *, prompt: bool = Tr
yield data_providers[chosen_index]
-def _warn_exceptions(exc: Exception) -> None:
- from my.core import make_logger
-
- logger = make_logger('CLI', level='warning')
-
- logger.exception(f'hpi query: {exc}')
-
-
# handle the 'hpi query' call
# can raise a QueryException, caught in the click command
def query_hpi_functions(
*,
output: str = 'json',
stream: bool = False,
- qualified_names: list[str],
- order_key: str | None,
- order_by_value_type: type | None,
+ qualified_names: List[str],
+ order_key: Optional[str],
+ order_by_value_type: Optional[Type],
after: Any,
before: Any,
within: Any,
reverse: bool = False,
- limit: int | None,
+ limit: Optional[int],
drop_unsorted: bool,
wrap_unsorted: bool,
- warn_exceptions: bool,
raise_exceptions: bool,
drop_exceptions: bool,
) -> None:
- from .query_range import RangeTuple, select_range
+
+ from itertools import chain
+
+ from .query_range import select_range, RangeTuple
# 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,
@@ -550,11 +446,8 @@ def query_hpi_functions(
limit=limit,
drop_unsorted=drop_unsorted,
wrap_unsorted=wrap_unsorted,
- 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
@@ -577,35 +470,15 @@ def query_hpi_functions(
pprint(item)
else:
pprint(list(res))
- elif output == 'gpx':
- from my.location.common import locations_to_gpx
-
- # if user didn't specify to ignore exceptions, warn if locations_to_gpx
- # cannot process the output of the command. This can be silenced by
- # passing --drop-exceptions
- if not raise_exceptions and not drop_exceptions:
- warn_exceptions = True
-
- # 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]
- if warn_exceptions:
- _warn_exceptions(exc)
- elif raise_exceptions:
- raise exc
- elif drop_exceptions:
- pass
- sys.stdout.flush()
else:
res = list(res) # type: ignore[assignment]
# output == 'repl'
eprint(f"\nInteract with the results by using the {click.style('res', fg='green')} variable\n")
try:
- import IPython # type: ignore[import,unused-ignore]
+ import IPython # type: ignore[import]
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()
@@ -613,16 +486,16 @@ 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
Tool for HPI
Work in progress, will be used for config management, troubleshooting & introspection
'''
- # should overwrite anything else in LOGGING_LEVEL_HPI
+ # should overwrite anything else in HPI_LOGS
if debug:
- os.environ['LOGGING_LEVEL_HPI'] = 'debug'
+ os.environ["HPI_LOGS"] = "debug"
# for potential future reference, if shared state needs to be added to groups
# https://click.palletsprojects.com/en/7.x/commands/#group-invocation-without-command
@@ -631,27 +504,29 @@ def main(*, debug: bool) -> None:
# acts as a contextmanager of sorts - any subcommand will then run
# in something like /tmp/hpi_temp_dir
# to avoid importing relative modules by accident during development
- # maybe can be removed later if there's more test coverage/confidence that nothing
+ # maybe can be removed later if theres more test coverage/confidence that nothing
# would happen?
+ import tempfile
# use a particular directory instead of a random one, since
# click being decorator based means its more complicated
# 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 = Path(tempfile.gettempdir()) / 'hpi_temp_dir'
- tdir.mkdir(exist_ok=True)
+ tdir: str = os.path.join(tempfile.gettempdir(), 'hpi_temp_dir')
+ if not os.path.exists(tdir):
+ os.makedirs(tdir)
os.chdir(tdir)
@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)]
@@ -661,7 +536,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
@@ -695,7 +570,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)
@@ -707,39 +582,34 @@ 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:
+@click.argument('MODULE', shell_complete=_module_autocomplete)
+def module_requires_cmd(module: str) -> None:
'''
- Print MODULES requirements
+ Print MODULE requirements
- MODULES is one or more specific module names (e.g. my.reddit.rexport)
+ MODULE is a specific module name (e.g. my.reddit.rexport)
'''
- module_requires(module=modules)
+ module_requires(module=module)
@module_grp.command(name='install', short_help='install module deps')
@click.option('--user', is_flag=True, help='same as pip --user')
-@click.option('--parallel', is_flag=True, help='EXPERIMENTAL. Install dependencies in parallel.')
-@click.option('-B',
- '--break-system-packages',
- 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:
+@click.argument('MODULE', shell_complete=_module_autocomplete)
+def module_install_cmd(user: bool, module: str) -> None:
'''
- Install dependencies for modules using pip
+ Install dependencies for a module using pip
- MODULES is one or more specific module names (e.g. my.reddit.rexport)
+ MODULE is a specific module name (e.g. my.reddit.rexport)
'''
# todo could add functions to check specific module etc..
- module_install(user=user, module=modules, parallel=parallel, break_system_packages=break_system_packages)
+ module_install(user=user, module=module)
@main.command(name='query', short_help='query the results of a HPI function')
@click.option('-o',
'--output',
default='json',
- type=click.Choice(['json', 'pprint', 'repl', 'gpx']),
+ type=click.Choice(['json', 'pprint', 'repl']),
help='what to do with the result [default: json]')
@click.option('-s',
'--stream',
@@ -792,10 +662,6 @@ def module_install_cmd(*, user: bool, parallel: bool, break_system_packages: boo
default=False,
is_flag=True,
help="if the order of an item can't be determined while ordering, wrap them into an 'Unsortable' object")
-@click.option('--warn-exceptions',
- default=False,
- is_flag=True,
- help="if any errors are returned, print them as errors on STDERR")
@click.option('--raise-exceptions',
default=False,
is_flag=True,
@@ -806,21 +672,19 @@ def module_install_cmd(*, user: bool, parallel: bool, break_system_packages: boo
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,
- order_key: str | None,
- order_type: str | None,
- after: str | None,
- before: str | None,
- within: str | None,
- recent: str | None,
+ order_key: Optional[str],
+ order_type: Optional[str],
+ after: Optional[str],
+ before: Optional[str],
+ within: Optional[str],
+ recent: Optional[str],
reverse: bool,
- limit: int | None,
+ limit: Optional[int],
drop_unsorted: bool,
wrap_unsorted: bool,
- warn_exceptions: bool,
raise_exceptions: bool,
drop_exceptions: bool,
) -> None:
@@ -848,12 +712,12 @@ def query_cmd(
\b
Can also query within a range. To filter comments between 2016 and 2018:
- hpi query --order-type datetime --after '2016-01-01' --before '2019-01-01' my.reddit.all.comments
+ hpi query --order-type datetime --after '2016-01-01 00:00:00' --before '2019-01-01 00:00:00' my.reddit.all.comments
'''
- from datetime import date, datetime
+ from datetime import datetime, date
- chosen_order_type: type | None
+ chosen_order_type: Optional[Type]
if order_type == "datetime":
chosen_order_type = datetime
elif order_type == "date":
@@ -887,10 +751,8 @@ def query_cmd(
limit=limit,
drop_unsorted=drop_unsorted,
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)
@@ -905,11 +767,9 @@ def query_cmd(
def test_requires() -> None:
from click.testing import CliRunner
-
- result = CliRunner().invoke(main, ['module', 'requires', 'my.github.ghexport', 'my.browser.export'])
+ result = CliRunner().invoke(main, ['module', 'requires', 'my.github.ghexport'])
assert result.exit_code == 0
assert "github.com/karlicoss/ghexport" in result.output
- assert "browserexport" in result.output
if __name__ == '__main__':
diff --git a/my/core/_cpu_pool.py b/my/core/_cpu_pool.py
deleted file mode 100644
index 6b107a7..0000000
--- a/my/core/_cpu_pool.py
+++ /dev/null
@@ -1,35 +0,0 @@
-"""
-EXPERIMENTAL! use with caution
-Manages 'global' ProcessPoolExecutor which is 'managed' by HPI itself, and
-can be passed down to DALs to speed up data processing.
-
-The reason to have it managed by HPI is because we don't want DALs instantiate pools
-themselves -- they can't cooperate and it would be hard/infeasible to control
-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 cast
-
-_NOT_SET = cast(ProcessPoolExecutor, object())
-_INSTANCE: ProcessPoolExecutor | None = _NOT_SET
-
-
-def get_cpu_pool() -> ProcessPoolExecutor | None:
- global _INSTANCE
- if _INSTANCE is _NOT_SET:
- use_cpu_pool = os.environ.get('HPI_CPU_POOL')
- if use_cpu_pool is None or int(use_cpu_pool) == 0:
- _INSTANCE = None
- else:
- # NOTE: this won't be cleaned up properly, but I guess it's fine?
- # since this it's basically a singleton for the whole process
- # , and will be destroyed when python exists
- _INSTANCE = ProcessPoolExecutor(max_workers=int(use_cpu_pool))
- return _INSTANCE
diff --git a/my/core/_deprecated/dataset.py b/my/core/_deprecated/dataset.py
deleted file mode 100644
index 9cca2fd..0000000
--- a/my/core/_deprecated/dataset.py
+++ /dev/null
@@ -1,12 +0,0 @@
-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/_deprecated/kompress.py b/my/core/_deprecated/kompress.py
deleted file mode 100644
index c3f333f..0000000
--- a/my/core/_deprecated/kompress.py
+++ /dev/null
@@ -1,261 +0,0 @@
-"""
-Various helpers for compression
-"""
-
-# fmt: off
-from __future__ import annotations
-
-import io
-import pathlib
-from collections.abc import Iterator, Sequence
-from datetime import datetime
-from functools import total_ordering
-from pathlib import Path
-from typing import IO, Union
-
-PathIsh = Union[Path, str]
-
-
-class Ext:
- xz = '.xz'
- zip = '.zip'
- lz4 = '.lz4'
- zstd = '.zstd'
- zst = '.zst'
- targz = '.tar.gz'
-
-
-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])
-
-
-def _zstd_open(path: Path, *args, **kwargs) -> IO:
- import zstandard as zstd # type: ignore
- fh = path.open('rb')
- dctx = zstd.ZstdDecompressor()
- reader = dctx.stream_reader(fh)
-
- mode = kwargs.get('mode', 'rt')
- if mode == 'rb':
- return reader
- else:
- # must be text mode
- kwargs.pop('mode') # TextIOWrapper doesn't like it
- return io.TextIOWrapper(reader, **kwargs) # meh
-
-
-# TODO use the 'dependent type' trick for return type?
-def kopen(path: PathIsh, *args, mode: str='rt', **kwargs) -> IO:
- # just in case, but I think this shouldn't be necessary anymore
- # since when we call .read_text, encoding is passed already
- if mode in {'r', 'rt'}:
- encoding = kwargs.get('encoding', 'utf8')
- else:
- encoding = None
- kwargs['encoding'] = encoding
-
- pp = Path(path)
- name = pp.name
- if name.endswith(Ext.xz):
- import lzma
-
- # ugh. for lzma, 'r' means 'rb'
- # https://github.com/python/cpython/blob/d01cf5072be5511595b6d0c35ace6c1b07716f8d/Lib/lzma.py#L97
- # whereas for regular open, 'r' means 'rt'
- # https://docs.python.org/3/library/functions.html#open
- if mode == 'r':
- mode = 'rt'
- kwargs['mode'] = mode
- return lzma.open(pp, *args, **kwargs)
- elif name.endswith(Ext.zip):
- # eh. this behaviour is a bit dodgy...
- from zipfile import ZipFile
- zfile = ZipFile(pp)
-
- [subpath] = args # meh?
-
- ## oh god... https://stackoverflow.com/a/5639960/706389
- ifile = zfile.open(subpath, mode='r')
- ifile.readable = lambda: True # type: ignore
- ifile.writable = lambda: False # type: ignore
- ifile.seekable = lambda: False # type: ignore
- ifile.read1 = ifile.read # type: ignore
- # TODO pass all kwargs here??
- # todo 'expected "BinaryIO"'??
- return io.TextIOWrapper(ifile, encoding=encoding)
- 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): # noqa: PIE810
- kwargs['mode'] = mode
- return _zstd_open(pp, *args, **kwargs)
- elif name.endswith(Ext.targz):
- import tarfile
- # FIXME pass mode?
- tf = tarfile.open(pp)
- # TODO pass encoding?
- x = tf.extractfile(*args); assert x is not None
- return x
- else:
- return pp.open(mode, *args, **kwargs)
-
-
-import os
-import typing
-
-if typing.TYPE_CHECKING:
- # otherwise mypy can't figure out that BasePath is a type alias..
- BasePath = pathlib.Path
-else:
- BasePath = pathlib.WindowsPath if os.name == 'nt' else pathlib.PosixPath
-
-
-class CPath(BasePath):
- """
- Hacky way to support compressed files.
- If you can think of a better way to do this, please let me know! https://github.com/karlicoss/HPI/issues/20
-
- Ugh. So, can't override Path because of some _flavour thing.
- 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): # noqa: ARG002
- kopen_kwargs = {}
- mode = kwargs.get('mode')
- if mode is not None:
- kopen_kwargs['mode'] = mode
- encoding = kwargs.get('encoding')
- if encoding is not None:
- kopen_kwargs['encoding'] = encoding
- # TODO assert read only?
- return kopen(str(self), **kopen_kwargs)
-
-
-open = kopen # TODO deprecate
-
-
-# meh
-# TODO ideally switch to ZipPath or smth similar?
-# nothing else supports subpath properly anyway
-def kexists(path: PathIsh, subpath: str) -> bool:
- try:
- kopen(path, subpath)
- except Exception:
- return False
- else:
- return True
-
-
-import zipfile
-
-# meh... zipfile.Path is not available on 3.7
-zipfile_Path = zipfile.Path
-
-
-@total_ordering
-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 # type: ignore[assignment]
- at: str
-
- @property
- def filepath(self) -> Path:
- res = self.root.filename
- assert res is not None # make mypy happy
- return Path(res)
-
- @property
- def subpath(self) -> Path:
- return Path(self.at)
-
- def absolute(self) -> ZipPath:
- return ZipPath(self.filepath.absolute(), self.at)
-
- def expanduser(self) -> ZipPath:
- return ZipPath(self.filepath.expanduser(), self.at)
-
- def exists(self) -> bool:
- if self.at == '':
- # special case, the base class returns False in this case for some reason
- return self.filepath.exists()
- return super().exists() or self._as_dir().exists()
-
- def _as_dir(self) -> zipfile_Path:
- # note: seems that zip always uses forward slash, regardless OS?
- return zipfile_Path(self.root, self.at + '/')
-
- 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)
-
- 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)
-
- @property
- def parts(self) -> Sequence[str]:
- # messy, but might be ok..
- return self.filepath.parts + self.subpath.parts
-
- def __truediv__(self, key) -> ZipPath:
- # need to implement it so the return type is not zipfile.Path
- tmp = zipfile_Path(self.root) / self.at / key
- return ZipPath(self.root, tmp.at)
-
- def iterdir(self) -> Iterator[ZipPath]:
- for s in self._as_dir().iterdir():
- yield ZipPath(s.root, s.at)
-
- @property
- def stem(self) -> str:
- return self.subpath.stem
-
- @property # type: ignore[misc]
- def __class__(self):
- return Path
-
- def __eq__(self, other) -> bool:
- # hmm, super class doesn't seem to treat as equals unless they are the same object
- if not isinstance(other, ZipPath):
- return False
- return (self.filepath, self.subpath) == (other.filepath, other.subpath)
-
- def __lt__(self, other) -> bool:
- if not isinstance(other, ZipPath):
- return False
- return (self.filepath, self.subpath) < (other.filepath, other.subpath)
-
- def __hash__(self) -> int:
- return hash((self.filepath, self.subpath))
-
- def stat(self) -> os.stat_result:
- # NOTE: zip datetimes have no notion of time zone, usually they just keep local time?
- # 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( # noqa: C408
- st_mode=0,
- st_ino=0,
- st_dev=0,
- st_nlink=1,
- st_uid=1000,
- st_gid=1000,
- st_size=0, # todo compute it properly?
- st_atime=ts,
- st_mtime=ts,
- st_ctime=ts,
- )
- return os.stat_result(tuple(params.values()))
-
- @property
- def suffix(self) -> str:
- return Path(self.parts[-1]).suffix
-
-# fmt: on
diff --git a/my/core/cachew.py b/my/core/cachew.py
index 8ce2f2b..4ecf51d 100644
--- a/my/core/cachew.py
+++ b/my/core/cachew.py
@@ -1,72 +1,47 @@
-from __future__ import annotations
+from .common import assert_subpackage; assert_subpackage(__name__)
-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,
- TypeVar,
- Union,
- cast,
- overload,
-)
-
-import appdirs # type: ignore[import-untyped]
-
-from . import warnings
-
-PathIsh = Union[str, Path] # avoid circular import from .common
-
+from typing import Optional
def disable_cachew() -> None:
try:
- import cachew # noqa: F401 # unused, it's fine
+ import cachew
except ImportError:
# nothing to disable
return
from cachew import settings
-
settings.ENABLE = False
+from typing import Iterator
@contextmanager
def disabled_cachew() -> Iterator[None]:
try:
- import cachew # noqa: F401 # unused, it's fine
+ import cachew
except ImportError:
# nothing to disable
yield
return
from cachew.extra import disabled_cachew
-
with disabled_cachew():
yield
def _appdirs_cache_dir() -> Path:
+ import appdirs # type: ignore
cd = Path(appdirs.user_cache_dir('my'))
cd.mkdir(exist_ok=True, parents=True)
return cd
-_CACHE_DIR_NONE_HACK = Path('/tmp/hpi/cachew_none_hack')
-
-
-def cache_dir(suffix: PathIsh | None = None) -> Path:
+from . import PathIsh
+def cache_dir(suffix: Optional[PathIsh] = None) -> Path:
from . import core_config as CC
-
cdir_ = CC.config.get_cache_dir()
- sp: Path | None = None
+ sp: Optional[Path] = None
if suffix is not None:
sp = Path(suffix)
# guess if you do need absolute, better path it directly instead of as suffix?
@@ -80,84 +55,9 @@ def cache_dir(suffix: PathIsh | None = None) -> Path:
# this logic is tested via test_cachew_dir_none
if cdir_ is None:
+ from .common import _CACHE_DIR_NONE_HACK
cdir = _CACHE_DIR_NONE_HACK
else:
cdir = cdir_
return cdir if sp is None else cdir / sp
-
-
-"""See core.cachew.cache_dir for the explanation"""
-
-
-_cache_path_dflt = cast(str, object())
-
-
-# TODO I don't really like 'mcachew', just 'cache' would be better... maybe?
-# todo ugh. I think it needs @doublewrap, otherwise @mcachew without args doesn't work
-# but it's a bit problematic.. doublewrap works by defecting if the first arg is callable
-# but here cache_path can also be a callable (for lazy/dynamic path)... so unclear how to detect this
-def _mcachew_impl(cache_path=_cache_path_dflt, **kwargs):
- """
- Stands for 'Maybe cachew'.
- Defensive wrapper around @cachew to make it an optional dependency.
- """
- if cache_path is _cache_path_dflt:
- # wasn't specified... so we need to use cache_dir
- cache_path = cache_dir()
-
- if isinstance(cache_path, (str, Path)):
- try:
- # check that it starts with 'hack' path
- Path(cache_path).relative_to(_CACHE_DIR_NONE_HACK)
- except: # noqa: E722 bare except
- pass # no action needed, doesn't start with 'hack' string
- else:
- # todo show warning? tbh unclear how to detect when user stopped using 'old' way and using suffix instead?
- # if it does, means that user wanted to disable cache
- cache_path = None
- try:
- import cachew
- except ModuleNotFoundError:
- 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
- return cachew.cachew(**kwargs)
-
-
-if TYPE_CHECKING:
- R = TypeVar('R')
- if sys.version_info[:2] >= (3, 10):
- from typing import ParamSpec
- else:
- from typing_extensions import ParamSpec
- P = ParamSpec('P')
- 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 always calls str for its result
- # so perhaps better to switch it to Any in cachew as well
- HashFunction = Callable[P, Any]
-
- F = TypeVar('F', bound=Callable)
-
- # 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: ...
-
- @overload
- def mcachew(
- cache_path: PathProvider | None = ...,
- *,
- force_file: bool = ...,
- cls: type | None = ...,
- depends_on: HashFunction = ...,
- logger: logging.Logger | None = ...,
- chunk_by: int = ...,
- synthetic_key: str | None = ...,
- ) -> Callable[[F], F]: ...
-
-else:
- mcachew = _mcachew_impl
diff --git a/my/core/cfg.py b/my/core/cfg.py
index 9851443..4b5cbed 100644
--- a/my/core/cfg.py
+++ b/my/core/cfg.py
@@ -1,44 +1,34 @@
-from __future__ import annotations
+from typing import TypeVar, Type, Callable, Dict, Any
-import importlib
-import re
-import sys
-from collections.abc import Iterator
-from contextlib import ExitStack, contextmanager
-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)}
}
# todo maybe return type here?
- return cls(**params)
+ return cls(**params) # type: ignore[call-arg]
F = TypeVar('F')
-
-
+from contextlib import contextmanager
+from typing import Iterator
@contextmanager
-def _override_config(config: F) -> Iterator[F]:
+def override_config(config: F) -> Iterator[F]:
'''
Temporary override for config's parameters, useful for testing/fake data/etc.
'''
@@ -54,62 +44,17 @@ def _override_config(config: F) -> Iterator[F]:
delattr(config, k)
-ModuleRegex = str
-
-
+# helper for tests? not sure if could be useful elsewhere
@contextmanager
-def _reload_modules(modules: ModuleRegex) -> Iterator[None]:
- # need to use list here, otherwise reordering with set might mess things up
- def loaded_modules() -> list[str]:
- return [name for name in sys.modules if re.fullmatch(modules, name)]
-
- modules_before = loaded_modules()
-
- # uhh... seems that reversed might make more sense -- not 100% sure why, but this works for tests/reddit.py
- for m in reversed(modules_before):
- # ugh... seems that reload works whereas pop doesn't work in some cases (e.g. on tests/reddit.py)
- # sys.modules.pop(m, None)
- importlib.reload(sys.modules[m])
-
- try:
- yield
- finally:
- modules_after = loaded_modules()
- modules_before_set = set(modules_before)
- for m in modules_after:
- if m in modules_before_set:
- # was previously loaded, so need to reload to pick up old config
- importlib.reload(sys.modules[m])
- else:
- # wasn't previously loaded, so need to unload it
- # otherwise it might fail due to missing config etc
- sys.modules.pop(m, None)
-
-
-@contextmanager
-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('__')}
- for k, v in overrides.items():
- setattr(new_config, k, v)
-
- if modules is not None:
- module_reload_stack.enter_context(_reload_modules(modules))
- yield new_config
+def tmp_config():
+ import my.config as C
+ with override_config(C):
+ yield C # todo not sure?
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')
@@ -118,8 +63,3 @@ def test_tmp_config() -> None:
# todo hmm. not sure what should do about new properties??
assert not hasattr(c, 'extra')
assert c.google != 'whatever'
-
-
-###
-# todo properly deprecate, this isn't really meant for public use
-override_config = _override_config
diff --git a/my/core/common.py b/my/core/common.py
index aa994ea..92806d2 100644
--- a/my/core/common.py
+++ b/my/core/common.py
@@ -1,60 +1,198 @@
-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,
- TypeVar,
- Union,
-)
-
-from . import compat, warnings
+from datetime import datetime
+import functools
+import types
+from typing import Union, Callable, Dict, Iterable, TypeVar, Sequence, List, Optional, Any, cast, Tuple, TYPE_CHECKING
+import warnings
+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
PathIsh = Union[Path, str]
+# TODO only used in tests? not sure if useful at all.
+# TODO port annotations to kython?..
+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) # type: ignore[attr-defined]
+ return foo
+
+
+def import_from(path: PathIsh, name: str) -> types.ModuleType:
+ path = str(path)
+ import sys
+ 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)
+
+
+T = TypeVar('T')
+K = TypeVar('K')
+V = TypeVar('V')
+
+def the(l: Iterable[T]) -> T:
+ it = iter(l)
+ try:
+ first = next(it)
+ except StopIteration as ee:
+ 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]] = {}
+ for i in l:
+ kk = key(i)
+ lst = res.get(kk, [])
+ lst.append(i)
+ res[kk] = lst
+ return res
+
+
+def _identity(v: T) -> V:
+ 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) # type: ignore
+ 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 # type: ignore
+ 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}
+
+
+Cl = TypeVar('Cl')
+R = TypeVar('R')
+
+def cproperty(f: Callable[[Cl], R]) -> R:
+ return property(functools.lru_cache(maxsize=1)(f)) # type: ignore
+
+
+# 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
+
+
Paths = Union[Sequence[PathIsh], PathIsh]
DEFAULT_GLOB = '*'
-
-
def get_files(
- pp: Paths,
- glob: str = DEFAULT_GLOB,
- *,
- sort: bool = True,
- guess_compression: bool = True,
-) -> tuple[Path, ...]:
+ pp: Paths,
+ glob: str=DEFAULT_GLOB,
+ 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):
if pp == '':
# special case -- makes sense for optional data sources, etc
- return () # early return to prevent warnings etc
+ return () # early return to prevent warnings etc
sources = [Path(pp)]
else:
- sources = [p if isinstance(p, Path) else Path(p) for p in pp]
+ sources = [Path(p) for p in pp]
def caller() -> str:
import traceback
-
# 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()
@@ -62,81 +200,139 @@ def get_files(
gs = str(src)
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))) # 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
- # this clause would try globbing insize the archives
- # this is generally undesirable (since modules handle archives themselves)
-
+ warnings.warn(f"{caller()}: treating {gs} as glob path. Explicit glob={glob} argument is ignored!")
+ paths.extend(map(Path, do_glob(gs)))
+ elif src.is_dir():
# todo not sure if should be recursive?
# note: glob='**/*.ext' works without any changes.. so perhaps it's ok as it is
gp: Iterable[Path] = src.glob(glob)
paths.extend(gp)
else:
- assert src.exists(), src
+ if not src.is_file():
+ # todo not sure, might be race condition?
+ raise RuntimeError(f"Expected '{src}' to exist")
# todo assert matches glob??
paths.append(src)
if sort:
- paths = sorted(paths)
+ paths = list(sorted(paths))
if len(paths) == 0:
# todo make it conditionally defensive based on some global settings
- warnings.high(f'''
+ core_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?
import traceback
-
traceback.print_stack()
if guess_compression:
- 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
- def wrap(p: Path) -> Path:
- if isinstance(p, ZipPath):
- return p
- if p.suffix == '.zip':
- return ZipPath(p) # type: ignore[return-value]
- if is_compressed(p):
- return CPath(p)
- return p
-
- paths = [wrap(p) for p in paths]
+ from .kompress import CPath, is_compressed
+ paths = [CPath(p) if is_compressed(p) else p for p in paths]
return tuple(paths)
+# TODO annotate it, perhaps use 'dependent' type (for @doublewrap stuff)
+if TYPE_CHECKING:
+ from typing import Callable, TypeVar
+ from typing_extensions import Protocol
+ # TODO reuse types from cachew? although not sure if we want hard dependency on it in typecheck time..
+ # I guess, later just define pass through once this is fixed: https://github.com/python/typing/issues/270
+ # ok, that's actually a super nice 'pattern'
+ F = TypeVar('F')
+ class McachewType(Protocol):
+ def __call__(
+ self,
+ cache_path: Any=None,
+ *,
+ hashf: Any=None, # todo deprecate
+ depends_on: Any=None,
+ force_file: bool=False,
+ chunk_by: int=0,
+ logger: Any=None,
+ ) -> Callable[[F], F]:
+ ...
+
+ mcachew: McachewType
+
+
+_CACHE_DIR_NONE_HACK = Path('/tmp/hpi/cachew_none_hack')
+"""See core.cachew.cache_dir for the explanation"""
+
+
+_cache_path_dflt = cast(str, object())
+# TODO I don't really like 'mcachew', just 'cache' would be better... maybe?
+# todo ugh. I think it needs @doublewrap, otherwise @mcachew without args doesn't work
+# but it's a bit problematic.. doublewrap works by defecting if the first arg is callable
+# but here cache_path can also be a callable (for lazy/dynamic path)... so unclear how to detect this
+def mcachew(cache_path=_cache_path_dflt, **kwargs): # type: ignore[no-redef]
+ """
+ Stands for 'Maybe cachew'.
+ Defensive wrapper around @cachew to make it an optional dependency.
+ """
+ if cache_path is _cache_path_dflt:
+ # wasn't specified... so we need to use cache_dir
+ from .cachew import cache_dir
+ cache_path = cache_dir()
+
+ if isinstance(cache_path, (str, Path)):
+ try:
+ # check that it starts with 'hack' path
+ Path(cache_path).relative_to(_CACHE_DIR_NONE_HACK)
+ except:
+ pass # no action needed, doesn't start with 'hack' string
+ else:
+ # todo show warning? tbh unclear how to detect when user stopped using 'old' way and using suffix instead?
+ # if it does, means that user wanted to disable cache
+ cache_path = None
+ 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')
+ return lambda orig_func: orig_func
+ else:
+ kwargs['cache_path'] = cache_path
+ return cachew.cachew(**kwargs)
+
+
+@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]
+
+
+from typing import TypeVar, Callable, Generic
+
+_C = TypeVar('_C')
_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:
+ def __init__(self, f: Callable[[_C], _R]) -> None:
self.f = f
- def __get__(self, obj, cls) -> _R:
+ def __get__(self, obj: None, cls: _C) -> _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_type(res, str)
- assert res == 'hello'
-
-
# hmm, this doesn't really work with mypy well..
# https://github.com/python/mypy/issues/6244
# class staticproperty(Generic[_R]):
@@ -146,117 +342,282 @@ def test_classproperty() -> None:
# 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?
+tzdatetime = 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)
+
+from .compat import Literal
+
import re
-
-
# https://stackoverflow.com/a/295466/706389
def get_valid_filename(s: str) -> str:
s = str(s).strip().replace(' ', '_')
return re.sub(r'(?u)[^-\w.]', '', s)
-# TODO deprecate and suggest to use one from my.core directly? not sure
-from .utils.itertools import unique_everseen # noqa: F401
+from typing import Generic, Sized, Callable
-### 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:
- from .compat import deprecated
+# 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")
- @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)
+# 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...
- @deprecated('use more_itertools.one instead')
- def the(*args, **kwargs):
- import more_itertools
+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)
- return more_itertools.one(*args, **kwargs)
- @deprecated('use functools.cached_property instead')
- def cproperty(*args, **kwargs):
- import functools
+# 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])
- return functools.cached_property(*args, **kwargs)
+@overload
+def warn_if_empty(f: FL) -> FL: ...
+@overload
+def warn_if_empty(f: FI) -> FI: ...
- @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.itertools.make_dict instead')
- def make_dict(*args, **kwargs):
- from .utils import itertools as UI
+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 # type: ignore
- return UI.make_dict(*args, **kwargs)
- @deprecated('use my.core.utils.itertools.listify instead')
- def listify(*args, **kwargs):
- from .utils import itertools as UI
+# hacky hook to speed up for 'hpi doctor'
+# todo think about something better
+QUICK_STATS = False
- 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
+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]]) -> Stats:
+ if callable(func):
+ fr = func()
+ 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)}'
+ tname = type(fr).__name__
+ if tname == '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)
+ return {
+ fname: res,
+ }
- return UI.listify(*args, **kwargs)
- @deprecated('use my.core.stat instead')
- def stat(*args, **kwargs):
- from . import stats
+def _stat_iterable(it: Iterable[C]) -> Any:
+ from more_itertools import ilen, take, first
- return stats.stat(*args, **kwargs)
+ # todo not sure if there is something in more_itertools to compute this?
+ total = 0
+ errors = 0
+ last = None
+ def funcit():
+ nonlocal errors, last, total
+ for x in it:
+ total += 1
+ if isinstance(x, Exception):
+ errors += 1
+ else:
+ last = x
+ yield x
- @deprecated('use my.core.make_logger instead')
- def LazyLogger(*args, **kwargs):
- from . import logging
+ eit = funcit()
+ count: Any
+ if 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)
- return logging.LazyLogger(*args, **kwargs)
+ res = {
+ 'count': count,
+ }
- @deprecated('use my.core.types.asdict instead')
- def asdict(*args, **kwargs):
- from . import types
+ 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'
- return types.asdict(*args, **kwargs)
+ if errors > 0:
+ res['errors'] = errors
- # 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
+ if last is not None:
+ dt = guess_datetime(last)
+ if dt is not None:
+ res['last'] = dt
+ return res
- 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
- from .stats import Stats
- from .types import (
- Json,
- datetime_aware,
- datetime_naive,
- )
+def test_stat_iterable() -> None:
+ from datetime import datetime, timedelta
+ from typing import NamedTuple
- tzdatetime = datetime_aware
-else:
- from .compat import Never
+ dd = datetime.utcfromtimestamp(123)
+ day = timedelta(days=3)
- # make these invalid during type check while working in runtime
- Stats = Never
- tzdatetime = Never
- Json = Never
- datetime_naive = Never
- datetime_aware = Never
-###
+ 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:
+ 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 = isoparse('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)
+ return (_asdict is not None) and callable(_asdict)
+
+
+def asdict(thing: Any) -> Json:
+ # todo primitive?
+ # todo exception?
+ if isinstance(thing, dict):
+ return thing
+ import dataclasses as D
+ if D.is_dataclass(thing):
+ return D.asdict(thing)
+ if is_namedtuple(thing):
+ return thing._asdict()
+ raise TypeError(f'Could not convert object {thing} to dict')
+
+
+
+
+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 ...
+ assert name == '__main__' or 'my.core' in name, f'Expected module __name__ ({name}) to be __main__ or start with my.core'
+
+
+# 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
+
+ # TODO: once support for 3.7 is dropped,
+ # can make 'fn' a positional only parameter,
+ # which fixes the mypy error this throws without the type: ignore
+ def submit(self, fn, *args, **kwargs) -> Future: # type: ignore[override]
+ 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) -> None: # type: ignore[override]
+ self._shutdown = True
diff --git a/my/core/compat.py b/my/core/compat.py
index 8f719a8..8fc3ef5 100644
--- a/my/core/compat.py
+++ b/my/core/compat.py
@@ -1,139 +1,83 @@
'''
-Contains backwards compatibility helpers for different python versions.
-If something is relevant to HPI itself, please put it in .hpi_compat instead
+Some backwards compatibility stuff/deprecation helpers
'''
+from types import ModuleType
+from typing import Callable
+
+from . import warnings
+from .common import LazyLogger
+
+
+logger = LazyLogger('my.core.compat')
+
+
+def pre_pip_dal_handler(
+ name: str,
+ e: ModuleNotFoundError,
+ cfg,
+ requires=[],
+) -> ModuleType:
+ '''
+ https://github.com/karlicoss/HPI/issues/79
+ '''
+ if e.name != name:
+ # the module itself was imported, so the problem is with some dependencies
+ raise e
+ try:
+ dal = _get_dal(cfg, name)
+ warnings.high(f'''
+Specifying modules' dependencies in the config or in my/config/repos is deprecated!
+Please install {' '.join(requires)} as PIP packages (see the corresponding README instructions).
+'''.strip(), stacklevel=2)
+ except ModuleNotFoundError as ee:
+ dal = None
+
+ if dal is None:
+ # probably means there was nothing in the old config in the first place
+ # so we should raise the original exception
+ raise e
+ return dal
+
+
+def _get_dal(cfg, module_name: str):
+ mpath = getattr(cfg, module_name, None)
+ if mpath is not None:
+ from .common import import_dir
+ return import_dir(mpath, '.dal')
+ else:
+ from importlib import import_module
+ return import_module(f'my.config.repos.{module_name}.dal')
-from __future__ import annotations
import sys
from typing import TYPE_CHECKING
-if sys.version_info[:2] >= (3, 13):
- from warnings import deprecated
+if sys.version_info[:2] >= (3, 8):
+ from typing import Literal
else:
- from typing_extensions import deprecated
+ if TYPE_CHECKING:
+ from typing_extensions import Literal
+ else:
+ from typing import Union
+ # erm.. I guess as long as it's not crashing, whatever...
+ Literal = Union
-# keeping just for backwards compatibility, used to have compat implementation for 3.6
-if not TYPE_CHECKING:
- import sqlite3
+import os
+windows = os.name == 'nt'
- @deprecated('use .backup method on sqlite3.Connection directly instead')
- def sqlite_backup(*, source: sqlite3.Connection, dest: sqlite3.Connection, **kwargs) -> None:
- # TODO warn here?
+
+import sqlite3
+def sqlite_backup(*, source: sqlite3.Connection, dest: sqlite3.Connection, **kwargs) -> None:
+ if sys.version_info[:2] >= (3, 7):
source.backup(dest, **kwargs)
+ else:
+ # https://stackoverflow.com/a/10856450/706389
+ import io
+ tempfile = io.StringIO()
+ for line in source.iterdump():
+ tempfile.write('%s\n' % line)
+ tempfile.seek(0)
- # 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)
-
- @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
- from functools import cached_property
- from typing import Literal, Protocol, TypedDict
-##
-
-
-if sys.version_info[:2] >= (3, 10):
- from typing import ParamSpec
-else:
- 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 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: int | None=None, *, key: Callable[..., Any] | None=None) -> int:
- if lo < 0:
- raise ValueError('lo must be non-negative')
- if hi is None:
- hi = len(a)
- # Note, the comparison uses "<" to match the
- # __lt__() logic in list.sort() and in heapq.
- if key is None:
- while lo < hi:
- mid = (lo + hi) // 2
- if a[mid] < x:
- lo = mid + 1
- else:
- hi = mid
- else:
- while lo < hi:
- mid = (lo + hi) // 2
- if key(a[mid]) < x:
- lo = mid + 1
- 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:
- if date_string.endswith('Z'):
- date_string = date_string[:-1] + '+00:00'
- return datetime.fromisoformat(date_string)
-
-
-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,
- )
-
- # 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,
- )
- # 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...
- # 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,
- # )
-
-
-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):
- from typing import Never, assert_never, assert_type
-else:
- from typing_extensions import Never, assert_never, assert_type
+ dest.cursor().executescript(tempfile.read())
+ dest.commit()
diff --git a/my/core/core_config.py b/my/core/core_config.py
index 3f26c03..cc8b527 100644
--- a/my/core/core_config.py
+++ b/my/core/core_config.py
@@ -1,33 +1,27 @@
'''
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 Sequence, Optional
-from . import warnings
+from . import warnings, PathIsh, Path
try:
- from my.config import core as user_config # type: ignore[attr-defined]
+ 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, assignment, misc]
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.
# this way it'll at least use the defaults
# todo actually not sure if needs a warning? Perhaps it's okay without it, because the defaults are reasonable enough
- user_config = object
+ user_config = object # type: ignore[assignment, misc]
_HPI_CACHE_DIR_DEFAULT = ''
-
+from dataclasses import dataclass
@dataclass
class Config(user_config):
'''
@@ -38,7 +32,7 @@ class Config(user_config):
cache_dir = '/your/custom/cache/path'
'''
- cache_dir: Path | str | None = _HPI_CACHE_DIR_DEFAULT
+ cache_dir: Optional[PathIsh] = _HPI_CACHE_DIR_DEFAULT
'''
Base directory for cachew.
- if None , means cache is disabled
@@ -48,7 +42,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: Path | str | None = None
+ tmp_dir: Optional[PathIsh] = None
'''
Path to a temporary directory.
This can be used temporarily while extracting zipfiles etc...
@@ -56,36 +50,34 @@ class Config(user_config):
- otherwise , use the specified directory as the base temporary directory
'''
- enabled_modules: Sequence[str] | None = None
+ enabled_modules : Optional[Sequence[str]] = None
'''
list of regexes/globs
- None means 'rely on disabled_modules'
'''
- disabled_modules: Sequence[str] | None = None
+ disabled_modules: Optional[Sequence[str]] = None
'''
list of regexes/globs
- None means 'rely on enabled_modules'
'''
- def get_cache_dir(self) -> Path | None:
+ def get_cache_dir(self) -> Optional[Path]:
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: Path | str | None = self.tmp_dir
+ tdir: Optional[PathIsh] = self.tmp_dir
tpath: Path
# use tempfile if unset
if tdir is None:
import tempfile
-
tpath = Path(tempfile.gettempdir()) / 'HPI'
else:
tpath = Path(tdir)
@@ -93,16 +85,18 @@ class Config(user_config):
tpath.mkdir(parents=True, exist_ok=True)
return tpath
- def _is_module_active(self, module: str) -> bool | None:
+ def _is_module_active(self, module: str) -> Optional[bool]:
# 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]) -> str | None:
+ def matches(specs: Sequence[str]) -> Optional[str]:
for spec in specs:
# not sure because . (packages separate) matches anything, but I guess unlikely to clash
if re.match(spec, module):
return spec
return None
+ enabled = self.enabled_modules
+ disabled = self.disabled_modules
on = matches(self.enabled_modules or [])
off = matches(self.disabled_modules or [])
@@ -112,30 +106,27 @@ 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
from .cfg import make_config
-
config = make_config(Config)
### tests start
-from collections.abc import Iterator
+from typing import Iterator
from contextlib import contextmanager as ctx
-
-
@ctx
def _reset_config() -> Iterator[Config]:
# todo maybe have this decorator for the whole of my.config?
- from .cfg import _override_config
- with _override_config(config) as cc:
+ from .cfg import override_config
+ with override_config(config) as cc:
cc.enabled_modules = None
cc.disabled_modules = None
cc.cache_dir = None
@@ -155,19 +146,18 @@ def test_active_modules() -> None:
with reset() as cc:
cc.enabled_modules = ['my.whatever']
cc.disabled_modules = ['my.body.*']
- assert cc._is_module_active('my.whatever' ) is True
- assert cc._is_module_active('my.core' ) is None
- assert cc._is_module_active('my.body.exercise') is False
+ assert cc._is_module_active('my.whatever' ) is True
+ assert cc._is_module_active('my.core' ) is None
+ assert not cc._is_module_active('my.body.exercise') is True
with reset() as cc:
# if both are set, enable all
cc.disabled_modules = ['my.body.*']
- cc.enabled_modules = ['my.body.exercise']
+ cc.enabled_modules = ['my.body.exercise']
assert cc._is_module_active('my.whatever' ) is None
assert cc._is_module_active('my.core' ) is None
with pytest.warns(UserWarning, match=r"conflicting regexes") as record_warnings:
assert cc._is_module_active("my.body.exercise") is True
assert len(record_warnings) == 1
-
### tests end
diff --git a/my/core/dataset.py b/my/core/dataset.py
index 40237a0..c8591d4 100644
--- a/my/core/dataset.py
+++ b/my/core/dataset.py
@@ -1,5 +1,14 @@
-from . import warnings
+from .common import assert_subpackage; assert_subpackage(__name__)
-warnings.high(f"{__name__} is deprecated, please use dataset directly if you need or switch to my.core.sqlite")
+from .common import PathIsh
+from .sqlite import sqlite_connect_immutable
-from ._deprecated.dataset import *
+
+# TODO wonder if also need to open without WAL.. test this on read-only directory/db file
+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/denylist.py b/my/core/denylist.py
deleted file mode 100644
index c92f9a0..0000000
--- a/my/core/denylist.py
+++ /dev/null
@@ -1,179 +0,0 @@
-"""
-A helper module for defining denylists for sources programmatically
-(in lamens terms, this lets you remove some output from a module you don't want)
-
-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, TypeVar
-
-import click
-from more_itertools import seekable
-
-from .serialize import dumps
-from .warnings import medium
-
-T = TypeVar("T")
-
-DenyMap = Mapping[str, set[Any]]
-
-
-def _default_key_func(obj: T) -> str:
- return str(obj)
-
-
-class DenyList:
- 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_map: DenyMap = defaultdict(set)
-
- # deny cli, user can override these
- self.fzf_path = None
- self._fzf_options = ()
- self._deny_cli_key_func = None
-
- def _load(self) -> None:
- if not self.file.exists():
- medium(f"denylist file {self.file} does not exist")
- return
-
- deny_map: DenyMap = defaultdict(set)
- data: list[dict[str, Any]] = json.loads(self.file.read_text())
- self._deny_raw_list = data
-
- for ignore in data:
- for k, v in ignore.items():
- deny_map[k].add(v)
-
- self._deny_map = deny_map
-
- def load(self) -> DenyMap:
- self._load()
- return self._deny_map
-
- def write(self) -> None:
- if not self._deny_raw_list:
- medium("no denylist data to write")
- return
- self.file.write_text(json.dumps(self._deny_raw_list))
-
- @classmethod
- def _is_json_primitive(cls, val: Any) -> bool:
- return isinstance(val, (str, int, float, bool, type(None)))
-
- @classmethod
- def _stringify_value(cls, val: Any) -> Any:
- # if it's a primitive, just return it
- if cls._is_json_primitive(val):
- return val
- # otherwise, stringify-and-back so we can compare to
- # json data loaded from the denylist file
- return json.loads(dumps(val))
-
- @classmethod
- def _allow(cls, obj: T, deny_map: DenyMap) -> bool:
- for deny_key, deny_set in deny_map.items():
- # this should be done separately and not as part of the getattr
- # because 'null'/None could actually be a value in the denylist,
- # and the user may define behavior to filter that out
- if not hasattr(obj, deny_key):
- return False
- val = cls._stringify_value(getattr(obj, deny_key))
- # this object doesn't have have the attribute in the denylist
- if val in deny_set:
- return False
- # if we tried all the denylist keys and didn't return False,
- # then this object is allowed
- return True
-
- def filter(
- self,
- itr: Iterator[T],
- *,
- invert: bool = False,
- ) -> Iterator[T]:
- denyf = functools.partial(self._allow, deny_map=self.load())
- if invert:
- return filter(lambda x: not denyf(x), itr)
- return filter(denyf, itr)
-
- def deny(self, key: str, value: Any, *, write: bool = False) -> None:
- '''
- add a key/value pair to the denylist
- '''
- if not self._deny_raw_list:
- self._load()
- self._deny_raw({key: self._stringify_value(value)}, write=write)
-
- def _deny_raw(self, data: dict[str, Any], *, write: bool = False) -> None:
- self._deny_raw_list.append(data)
- if write:
- self.write()
-
- def _prompt_keys(self, item: T) -> str:
- import pprint
-
- click.echo(pprint.pformat(item))
- # TODO: extract keys from item by checking if its dataclass/NT etc.?
- resp = click.prompt("Key to deny on").strip()
- if not hasattr(item, resp):
- click.echo(f"Could not find key '{resp}' on item", err=True)
- return self._prompt_keys(item)
- return resp
-
- def _deny_cli_remember(
- self,
- items: Iterator[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
- for item in items:
- key = keyf(item)
- mem[key] = item
- yield key
-
- def deny_cli(self, itr: Iterator[T]) -> None:
- try:
- from pyfzf import FzfPrompt
- except ImportError:
- click.echo("pyfzf is required to use the denylist cli, run 'python3 -m pip install pyfzf_iter'", err=True)
- sys.exit(1)
-
- # wrap in seekable so we can use it multiple times
- # progressively caches the items as we iterate over them
- sit = seekable(itr)
-
- prompt_continue = True
-
- while prompt_continue:
- # 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")
- picked_l = picker.prompt(
- self._deny_cli_remember(itr, memory_map),
- "--read0",
- *self._fzf_options,
- delimiter="\0",
- )
- assert isinstance(picked_l, list)
- if picked_l:
- picked: T = memory_map[picked_l[0]]
- key = self._prompt_keys(picked)
- self.deny(key, getattr(picked, key), write=True)
- click.echo(f"Added {self._deny_raw_list[-1]} to denylist", err=True)
- else:
- click.echo("No item selected", err=True)
-
- prompt_continue = click.confirm("Continue?")
diff --git a/my/core/discovery_pure.py b/my/core/discovery_pure.py
index 18a19c4..17a1976 100644
--- a/my/core/discovery_pure.py
+++ b/my/core/discovery_pure.py
@@ -10,20 +10,16 @@ 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__'
###
import ast
-import logging
-import os
-import re
-from collections.abc import Iterable, Sequence
+from typing import Optional, Sequence, List, NamedTuple, Iterable, cast, Any
from pathlib import Path
-from typing import Any, NamedTuple, Optional, cast
+import re
+import logging
'''
None means that requirements weren't defined (different from empty requirements)
@@ -33,11 +29,10 @@ Requires = Optional[Sequence[str]]
class HPIModule(NamedTuple):
name: str
- skip_reason: str | None
- doc: str | None = None
- file: Path | None = None
+ skip_reason: Optional[str]
+ doc: Optional[str] = None
+ file: Optional[Path] = None
requires: Requires = None
- legacy: str | None = None # contains reason/deprecation warning
def ignored(m: str) -> bool:
@@ -58,13 +53,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
@@ -79,19 +74,9 @@ def _is_not_module_src(src: Path) -> bool:
def _is_not_module_ast(a: ast.Module) -> bool:
- marker = NOT_HPI_MODULE_VAR
return any(
- getattr(node, 'name', None) == marker # direct definition
- or any(getattr(n, 'name', None) == marker for n in getattr(node, 'names', [])) # import from
- for node in a.body
- )
-
-
-def _is_legacy_module(a: ast.Module) -> bool:
- marker = 'handle_legacy_import'
- return any(
- getattr(node, 'name', None) == marker # direct definition
- or any(getattr(n, 'name', None) == marker for n in getattr(node, 'names', [])) # import from
+ getattr(node, 'name', None) == NOT_HPI_MODULE_VAR # direct definition
+ or any(getattr(n, 'name', None) == NOT_HPI_MODULE_VAR for n in getattr(node, 'names', [])) # import from
for node in a.body
)
@@ -122,7 +107,7 @@ def _extract_requirements(a: ast.Module) -> Requires:
elif isinstance(c, ast.Str):
deps.append(c.s)
else:
- raise RuntimeError(f"Expecting string constants only in {REQUIRES} declaration")
+ raise RuntimeError(f"Expecting string contants only in {REQUIRES} declaration")
return tuple(deps)
return None
@@ -147,7 +132,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__) # type: ignore[attr-defined]
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
@@ -166,15 +151,11 @@ def _modules_under_root(my_root: Path) -> Iterable[HPIModule]:
mp = f.relative_to(my_root.parent)
if mp.name == '__init__.py':
mp = mp.parent
- m = str(mp.with_suffix('')).replace(os.sep, '.')
+ m = str(mp.with_suffix('')).replace('/', '.')
if ignored(m):
continue
a: ast.Module = ast.parse(f.read_text())
-
- # legacy modules are 'forced' to be modules so 'hpi module install' still works for older modules
- # a bit messy, will think how to fix it properly later
- legacy_module = _is_legacy_module(a)
- if _is_not_module_ast(a) and not legacy_module:
+ if _is_not_module_ast(a):
continue
doc = ast.get_docstring(a, clean=False)
@@ -184,15 +165,12 @@ def _modules_under_root(my_root: Path) -> Iterable[HPIModule]:
except Exception as e:
logging.exception(e)
- legacy = f'{m} is DEPRECATED. Please refer to the module documentation.' if legacy_module else None
-
yield HPIModule(
name=m,
skip_reason=None,
doc=doc,
file=f.relative_to(my_root.parent),
requires=requires,
- legacy=legacy,
)
@@ -214,7 +192,7 @@ def test() -> None:
def test_demo() -> None:
demo = module_by_name('my.demo')
assert demo.doc is not None
- assert demo.file == Path('my', 'demo.py')
+ assert str(demo.file) == 'my/demo.py'
assert demo.requires is None
@@ -230,12 +208,6 @@ def test_requires() -> None:
assert len(r) == 2 # fragile, but ok for now
-def test_legacy_modules() -> None:
- # shouldn't crash
- module_by_name('my.reddit')
- module_by_name('my.fbmessenger')
-
-
def test_pure() -> None:
"""
We want to keep this module clean of other HPI imports
@@ -245,7 +217,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.MULTILINE) == []
+ assert re.findall('import ' + r'my\.\S+', src, re.M) == []
assert 'from ' + 'my' not in src
diff --git a/my/core/error.py b/my/core/error.py
index b308869..ee63277 100644
--- a/my/core/error.py
+++ b/my/core/error.py
@@ -3,34 +3,19 @@ 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,
- Literal,
- TypeVar,
- Union,
- cast,
-)
+from typing import Union, TypeVar, Iterable, List, Tuple, Type, Optional, Callable, Any, 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]
Res = ResT[T, Exception]
-ErrorPolicy = Literal["yield", "raise", "drop"]
-
-def notnone(x: T | None) -> T:
+def notnone(x: Optional[T]) -> T:
assert x is not None
return x
@@ -38,41 +23,8 @@ def notnone(x: T | None) -> T:
def unwrap(res: Res[T]) -> T:
if isinstance(res, Exception):
raise res
- return res
-
-
-def drop_exceptions(itr: Iterator[Res[T]]) -> Iterator[T]:
- """Return non-errors from the iterable"""
- for o in itr:
- if isinstance(o, Exception):
- continue
- yield o
-
-
-def raise_exceptions(itr: Iterable[Res[T]]) -> Iterator[T]:
- """Raise errors from the iterable, stops the select function"""
- for o in itr:
- if isinstance(o, Exception):
- raise o
- yield o
-
-
-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:
- if isinstance(o, Exception):
- warn_func(o)
- continue
- yield o
+ else:
+ return res
def echain(ex: E, cause: Exception) -> E:
@@ -80,7 +32,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?
@@ -98,9 +50,7 @@ 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
@@ -108,20 +58,20 @@ def sort_res_by(items: Iterable[Res[T]], key: Callable[[Any], K]) -> list[Res[T]
group = []
groups = []
for i in items:
- k: K | None
+ k: Optional[K]
try:
k = key(i)
- except Exception: # error white computing key? dunno, might be nice to handle...
+ except Exception as e:
k = None
group.append(i)
if k is not None:
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
@@ -141,7 +91,7 @@ def test_sort_res_by() -> None:
1,
Exc('last'),
]
- results = sort_res_by(ress, lambda x: int(x))
+ results = sort_res_by(ress, lambda x: int(x)) # type: ignore
assert results == [
1,
'bad',
@@ -153,32 +103,32 @@ 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)) # type: ignore
assert results2 == [Exc('last'), 0] + results[:-1]
assert sort_res_by(['caba', 'a', 'aba', 'daba'], key=lambda x: len(x)) == ['a', 'aba', 'caba', 'daba']
- assert sort_res_by([], key=lambda x: x) == []
+ assert sort_res_by([], key=lambda x: x) == [] # type: ignore
# 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: datetime | None) -> None:
+from datetime import datetime
+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?
-
-def attach_dt(e: Exception, *, dt: datetime | None) -> 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) -> datetime | None:
+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
@@ -193,6 +143,8 @@ def extract_error_datetime(e: Exception) -> datetime | None:
return None
+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}
@@ -200,13 +152,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: ImportError | AttributeError,
- *,
- help_url: str | None = None,
- module_name: str | None = None,
-) -> bool:
+def warn_my_config_import_error(err: Union[ImportError, AttributeError], help_url: str = MODULE_SETUP_URL) -> bool:
"""
If the user tried to import something from my.config but it failed,
possibly due to missing the config block in my.config?
@@ -214,12 +160,8 @@ def warn_my_config_import_error(
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:
+ if type(err) == ImportError:
if err.name != 'my.config':
return False
# parse name that user attempted to import
@@ -231,42 +173,28 @@ You may be missing the '{section_name}' section from your config.
See {help_url}\
""", fg='yellow', err=True)
return True
- elif type(err) is AttributeError:
+ elif type(err) == 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"):
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
- 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\
-"""
+ nested_block_name = err.name # type: ignore[attr-defined]
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)
+ click.secho(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)
return True
else:
click.echo(f"Unexpected error... {err}", err=True)
return False
-def test_datetime_errors() -> None:
- import pytz # noqa: I001
+def test_datetime_errors() -> None:
+ import pytz
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
@@ -276,6 +204,7 @@ def test_datetime_errors() -> None:
e2 = RuntimeError(f'something something {dt} something else')
assert extract_error_datetime(e2) == dt
+
e3 = RuntimeError(str(['one', '2019-11-27T08:56:00', 'three']))
assert extract_error_datetime(e3) is not None
diff --git a/my/core/experimental.py b/my/core/experimental.py
deleted file mode 100644
index 0a1c3b4..0000000
--- a/my/core/experimental.py
+++ /dev/null
@@ -1,66 +0,0 @@
-from __future__ import annotations
-
-import sys
-import types
-from typing import Any
-
-
-# The idea behind this one is to support accessing "overlaid/shadowed" modules from namespace packages
-# See usage examples here:
-# - https://github.com/karlicoss/hpi-personal-overlay/blob/master/src/my/util/hpi_heartbeat.py
-# - https://github.com/karlicoss/hpi-personal-overlay/blob/master/src/my/twitter/all.py
-# Suppose you want to use my.twitter.talon, which isn't in the default all.py
-# You could just copy all.py to your personal overlay, but that would mean duplicating
-# all the code and possible upstream changes.
-# Alternatively, you could import the "original" my.twitter.all module from "overlay" my.twitter.all
-# _ORIG = import_original_module(__name__, __file__)
-# this would magically take care of package import path etc,
-# and should import the "original" my.twitter.all as _ORIG
-# After that you can call its methods, extend etc.
-def import_original_module(
- module_name: str,
- file: str,
- *,
- star: bool = False,
- globals: dict[str, Any] | None = None,
-) -> types.ModuleType:
- module_to_restore = sys.modules[module_name]
-
- # NOTE: we really wanna to hack the actual package of the module
- # rather than just top level my.
- # since that would be a bit less disruptive
- module_pkg = module_to_restore.__package__
- assert module_pkg is not None
- parent = sys.modules[module_pkg]
-
- my_path = parent.__path__._path # type: ignore[attr-defined]
- my_path_orig = list(my_path)
-
- def fixup_path() -> None:
- for i, p in enumerate(my_path_orig):
- starts = file.startswith(p)
- if i == 0:
- # not sure about this.. but I guess it'll always be 0th element?
- assert starts, (my_path_orig, file)
- if starts:
- my_path.remove(p)
- # should remove exactly one item
- assert len(my_path) + 1 == len(my_path_orig), (my_path_orig, file)
-
- try:
- fixup_path()
- try:
- del sys.modules[module_name]
- # NOTE: we're using __import__ instead of importlib.import_module
- # since it's closer to the actual normal import (e.g. imports subpackages etc properly )
- # fromlist=[None] forces it to return rightmost child
- # (otherwise would just return 'my' package)
- res = __import__(module_name, fromlist=[None]) # type: ignore[list-item]
- if star:
- assert globals is not None
- globals.update({k: v for k, v in vars(res).items() if not k.startswith('_')})
- return res
- finally:
- sys.modules[module_name] = module_to_restore
- finally:
- my_path[:] = my_path_orig
diff --git a/my/core/freezer.py b/my/core/freezer.py
index 4fb0e25..abb2973 100644
--- a/my/core/freezer.py
+++ b/my/core/freezer.py
@@ -1,29 +1,27 @@
-from __future__ import annotations
+from .common import assert_subpackage; assert_subpackage(__name__)
-from .internal import assert_subpackage
-
-assert_subpackage(__name__)
-
-import dataclasses
+import dataclasses as dcl
import inspect
-from typing import Any, Generic, TypeVar
+from typing import TypeVar, Type, Any
D = TypeVar('D')
-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
+def _freeze_dataclass(Orig: Type[D]):
+ ofields = [(f.name, f.type, f) for f in dcl.fields(Orig)]
# 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 = dataclasses.make_dataclass('RRR', fields=[*ofields, *pfields])
+ RRR = dcl.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 +29,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(**dataclasses.asdict(value), **pvalues) # type: ignore[call-overload] # see https://github.com/python/typing_extensions/issues/115
+ return self.Frozen(**dcl.asdict(value), **pvalues)
### tests
@@ -45,7 +43,7 @@ class Freezer(Generic[D]):
# this needs to be defined here to prevent a mypy bug
# see https://github.com/python/mypy/issues/7281
-@dataclasses.dataclass
+@dcl.dataclass
class _A:
x: Any
@@ -60,10 +58,8 @@ class _A:
def test_freezer() -> None:
- val = _A(x={
- 'an_int': 123,
- 'an_any': [1, 2, 3],
- })
+
+ val = _A(x=dict(an_int=123, an_any=[1, 2, 3]))
af = Freezer(_A)
fval = af.freeze(val)
@@ -71,7 +67,6 @@ 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
deleted file mode 100644
index 3687483..0000000
--- a/my/core/hpi_compat.py
+++ /dev/null
@@ -1,260 +0,0 @@
-"""
-Contains various backwards compatibility/deprecation helpers relevant to HPI itself.
-(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 TypeVar
-
-from . import warnings
-
-
-def handle_legacy_import(
- parent_module_name: str,
- legacy_submodule_name: str,
- parent_module_path: list[str],
-) -> bool:
- ###
- # this is to trick mypy into treating this as a proper namespace package
- # should only be used for backwards compatibility on packages that are convernted into namespace & all.py pattern
- # - https://www.python.org/dev/peps/pep-0382/#namespace-packages-today
- # - https://github.com/karlicoss/hpi_namespace_experiment
- # - discussion here https://memex.zulipchat.com/#narrow/stream/279601-hpi/topic/extending.20HPI/near/269946944
- from pkgutil import extend_path
-
- parent_module_path[:] = extend_path(parent_module_path, parent_module_name)
- # 'this' source tree ends up first in the pythonpath when we extend_path()
- # so we need to move 'this' source tree towards the end to make sure we prioritize overlays
- parent_module_path[:] = parent_module_path[1:] + parent_module_path[:1]
- ###
-
- # allow stuff like 'import my.module.submodule' and such
- imported_as_parent = False
-
- # allow stuff like 'from my.module import submodule'
- importing_submodule = False
-
- # some hacky traceback to inspect the current stack
- # to see if the user is using the old style of importing
- for f in inspect.stack():
- # seems that when a submodule is imported, at some point it'll call some internal import machinery
- # with 'parent' set to the parent module
- # if parent module is imported first (i.e. in case of deprecated usage), it won't be the case
- args = inspect.getargvalues(f.frame)
- if args.locals.get('parent') == parent_module_name:
- imported_as_parent = True
-
- # this we can only detect from the code I guess
- line = '\n'.join(f.code_context or [])
- if re.match(rf'from\s+{parent_module_name}\s+import\s+{legacy_submodule_name}', line):
- importing_submodule = True
-
- # click sets '_HPI_COMPLETE' env var when it's doing autocompletion
- # otherwise, the warning will be printed every time you try to tab complete
- autocompleting_module_cli = "_HPI_COMPLETE" in os.environ
-
- is_legacy_import = not (imported_as_parent or importing_submodule)
- if is_legacy_import and not autocompleting_module_cli:
- warnings.high(
- f'''\
-importing {parent_module_name} is DEPRECATED! \
-Instead, import from {parent_module_name}.{legacy_submodule_name} or {parent_module_name}.all \
-See https://github.com/karlicoss/HPI/blob/master/doc/MODULE_DESIGN.org#allpy for more info.
-'''
- )
- return is_legacy_import
-
-
-def pre_pip_dal_handler(
- name: str,
- e: ModuleNotFoundError,
- cfg,
- requires: Sequence[str] = (),
-) -> ModuleType:
- '''
- https://github.com/karlicoss/HPI/issues/79
- '''
- if e.name != name:
- # the module itself was imported, so the problem is with some dependencies
- raise e
- try:
- dal = _get_dal(cfg, name)
- warnings.high(
- f'''
-Specifying modules' dependencies in the config or in my/config/repos is deprecated!
-Please install {' '.join(requires)} as PIP packages (see the corresponding README instructions).
-'''.strip(),
- stacklevel=2,
- )
- except ModuleNotFoundError:
- dal = None
-
- if dal is None:
- # probably means there was nothing in the old config in the first place
- # so we should raise the original exception
- raise e
- return dal
-
-
-def _get_dal(cfg, module_name: str):
- mpath = getattr(cfg, module_name, None)
- if mpath is not None:
- from .utils.imports import import_dir
-
- return import_dir(mpath, '.dal')
- else:
- from importlib import import_module
-
- return import_module(f'my.config.repos.{module_name}.dal')
-
-
-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 in runtime
- """
-
- def __init__(self, it: Iterator[V]) -> None:
- self._it = it
- 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:
- self._lit = iter(self._list)
- return self
-
- def __next__(self) -> V:
- 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)
-
- @property
- 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.')
- 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)
-
- def __getitem__(self, i: int) -> V:
- 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
diff --git a/my/core/influxdb.py b/my/core/influxdb.py
index 78a439a..3800dae 100644
--- a/my/core/influxdb.py
+++ b/my/core/influxdb.py
@@ -1,22 +1,14 @@
'''
TODO doesn't really belong to 'core' morally, but can think of moving out later
'''
+from .common import assert_subpackage; assert_subpackage(__name__)
-from __future__ import annotations
+from typing import Iterable, Any, Optional, Dict
-from .internal import assert_subpackage
+from .common import LazyLogger, asdict, Json
-assert_subpackage(__name__)
-from collections.abc import Iterable
-from typing import Any
-
-import click
-
-from .logging import make_logger
-from .types import Json, asdict
-
-logger = make_logger(__name__)
+logger = LazyLogger(__name__)
class config:
@@ -26,7 +18,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('.', '_')
@@ -34,8 +26,7 @@ def fill(it: Iterable[Any], *, measurement: str, reset: bool = RESET_DEFAULT, dt
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)
@@ -46,8 +37,7 @@ def fill(it: Iterable[Any], *, measurement: str, reset: bool = RESET_DEFAULT, dt
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)
if c is not None:
@@ -65,9 +55,9 @@ def fill(it: Iterable[Any], *, measurement: str, reset: bool = RESET_DEFAULT, dt
def dit() -> Iterable[Json]:
for i in it:
d = asdict(i)
- 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.
+ 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.
del d['tags']
tags = tags_
@@ -78,19 +68,19 @@ def fill(it: Iterable[Any], *, measurement: str, reset: bool = RESET_DEFAULT, dt
fields = filter_dict(d)
- yield {
- 'measurement': measurement,
+ yield dict(
+ 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."
# some chunking is def necessary, otherwise it fails
inserted = 0
@@ -104,9 +94,9 @@ def fill(it: Iterable[Any], *, measurement: str, reset: bool = RESET_DEFAULT, dt
# todo "Specify timestamp precision when writing to InfluxDB."?
-def magic_fill(it, *, name: str | None = None, reset: bool = RESET_DEFAULT) -> None:
+def magic_fill(it, *, name: Optional[str]=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
@@ -114,9 +104,7 @@ def magic_fill(it, *, name: str | None = None, reset: bool = RESET_DEFAULT) -> N
it = it()
from itertools import tee
-
from more_itertools import first, one
-
it, x = tee(it)
f = first(x, default=None)
if f is None:
@@ -126,17 +114,17 @@ def magic_fill(it, *, name: str | None = None, reset: bool = RESET_DEFAULT) -> N
# 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)
fill(it, measurement=name, reset=reset, dt_col=dtf)
+import click
+
@click.group()
def main() -> None:
pass
@@ -145,9 +133,8 @@ 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?
magic_fill(provider, reset=reset)
diff --git a/my/core/init.py b/my/core/init.py
index 644c7b4..1fc9e88 100644
--- a/my/core/init.py
+++ b/my/core/init.py
@@ -1,32 +1,43 @@
'''
A hook to insert user's config directory into Python's search path.
-Note that this file is imported only if we don't have custom user config (under my.config namespace) in PYTHONPATH
-Ideally that would be in __init__.py (so it's executed without having to import explicitly)
-But, with namespace packages, we can't have __init__.py in the parent subpackage
-(see http://python-notes.curiousefficiency.org/en/latest/python_concepts/import_traps.html#the-init-py-trap)
+- Ideally that would be in __init__.py (so it's executed without having to import explicityly)
+ But, with namespace packages, we can't have __init__.py in the parent subpackage
+ (see http://python-notes.curiousefficiency.org/en/latest/python_concepts/import_traps.html#the-init-py-trap)
-Instead, this is imported in the stub config (in this repository), so if the stub config is used, it triggers import of the 'real' config.
-
-Please let me know if you are aware of a better way of dealing with this!
+ Please let me know if you are aware of a better way of dealing with this!
'''
+from types import ModuleType
+
+# TODO not ideal to keep it here, but this should really be a leaf in the import tree
+# TODO maybe I don't even need it anymore?
+def assign_module(parent: str, name: str, module: ModuleType) -> None:
+ import sys
+ import importlib
+ parent_module = importlib.import_module(parent)
+ sys.modules[parent + '.' + name] = module
+ if sys.version_info.minor == 6:
+ # ugh. not sure why it's necessary in py36...
+ # TODO that crap should be tested... I guess will get it for free when I run rest of tests in the matrix
+ setattr(parent_module, name, module)
+
+del ModuleType
+
# separate function to present namespace pollution
def setup_config() -> None:
import sys
import warnings
- from pathlib import Path
from .preinit import get_mycfg_dir
-
mycfg_dir = get_mycfg_dir()
if not mycfg_dir.exists():
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(), stacklevel=1)
+""".strip())
return
mpath = str(mycfg_dir)
@@ -34,39 +45,20 @@ See https://github.com/karlicoss/HPI/blob/master/doc/SETUP.org#setting-up-the-mo
# hopefully it doesn't cause any issues
sys.path.insert(0, mpath)
- # remove the stub and reimport the 'real' config
- # likely my.config will always be in sys.modules, but defensive just in case
+ # remove the stub and insert reimport hte 'real' config
if 'my.config' in sys.modules:
+ # TODO FIXME make sure this method isn't called twice...
del sys.modules['my.config']
- # this should import from mpath now
try:
+ # todo import_from instead?? dunno
import my.config
except ImportError as ex:
- # just in case... who knows what crazy setup users have
- import logging
-
- logging.exception(ex)
+ # just in case... who knows what crazy setup users have in mind.
+ # todo log?
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)
- if used_config_file is not None:
- used_config_path = Path(used_config_file)
- try:
- # will crash if it's imported from other dir?
- used_config_path.relative_to(mycfg_dir)
- except ValueError:
- # TODO maybe implement a strict mode where these warnings will be errors?
- warnings.warn(
- f"""
-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
- )
+""")
setup_config()
diff --git a/my/core/internal.py b/my/core/internal.py
deleted file mode 100644
index 8b9882b..0000000
--- a/my/core/internal.py
+++ /dev/null
@@ -1,9 +0,0 @@
-"""
-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 8accb2d..b8e7724 100644
--- a/my/core/kompress.py
+++ b/my/core/kompress.py
@@ -1,17 +1,184 @@
-from .internal import assert_subpackage
+"""
+Various helpers for compression
+"""
+from __future__ import annotations
-assert_subpackage(__name__)
+import pathlib
+from pathlib import Path
+import sys
+from typing import Union, IO, Sequence, Any
+import io
-from . import warnings
+PathIsh = Union[Path, str]
-# do this later -- for now need to transition modules to avoid using kompress directly (e.g. ZipPath)
-# warnings.high('my.core.kompress is deprecated, please use "kompress" library directly. See https://github.com/karlicoss/kompress')
-try:
- from kompress import *
-except ModuleNotFoundError as e:
- if e.name == 'kompress':
- warnings.high('Please install kompress (pip3 install kompress). Falling onto vendorized kompress for now.')
- from ._deprecated.kompress import * # type: ignore[assignment]
+class Ext:
+ xz = '.xz'
+ zip = '.zip'
+ lz4 = '.lz4'
+ zstd = '.zstd'
+ targz = '.tar.gz'
+
+
+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.targz})
+
+
+def _zstd_open(path: Path, *args, **kwargs) -> IO[str]:
+ import zstandard as zstd # type: ignore
+ fh = path.open('rb')
+ dctx = zstd.ZstdDecompressor()
+ reader = dctx.stream_reader(fh)
+ return io.TextIOWrapper(reader, **kwargs) # meh
+
+
+# TODO returns protocol that we can call 'read' against?
+# TODO use the 'dependent type' trick?
+def kopen(path: PathIsh, *args, mode: str='rt', **kwargs) -> IO[str]:
+ # TODO handle mode in *rags?
+ encoding = kwargs.get('encoding', 'utf8')
+ kwargs['encoding'] = encoding
+
+ pp = Path(path)
+ name = pp.name
+ if name.endswith(Ext.xz):
+ import lzma
+ r = lzma.open(pp, mode, *args, **kwargs)
+ # should only happen for binary mode?
+ # file:///usr/share/doc/python3/html/library/lzma.html?highlight=lzma#lzma.open
+ assert not isinstance(r, lzma.LZMAFile), r
+ return r
+ elif name.endswith(Ext.zip):
+ # eh. this behaviour is a bit dodgy...
+ from zipfile import ZipFile
+ zfile = ZipFile(pp)
+
+ [subpath] = args # meh?
+
+ ## oh god... https://stackoverflow.com/a/5639960/706389
+ ifile = zfile.open(subpath, mode='r')
+ ifile.readable = lambda: True # type: ignore
+ ifile.writable = lambda: False # type: ignore
+ ifile.seekable = lambda: False # type: ignore
+ ifile.read1 = ifile.read # type: ignore
+ # TODO pass all kwargs here??
+ # todo 'expected "BinaryIO"'??
+ return io.TextIOWrapper(ifile, encoding=encoding) # type: ignore[arg-type]
+ elif name.endswith(Ext.lz4):
+ import lz4.frame # type: ignore
+ return lz4.frame.open(str(pp), mode, *args, **kwargs)
+ elif name.endswith(Ext.zstd):
+ return _zstd_open(pp, mode, *args, **kwargs)
+ elif name.endswith(Ext.targz):
+ import tarfile
+ # FIXME pass mode?
+ tf = tarfile.open(pp)
+ # TODO pass encoding?
+ x = tf.extractfile(*args); assert x is not None
+ return x # type: ignore[return-value]
else:
- raise e
+ return pp.open(mode, *args, **kwargs)
+
+
+import typing
+import os
+
+if typing.TYPE_CHECKING:
+ # otherwise mypy can't figure out that BasePath is a type alias..
+ BasePath = pathlib.Path
+else:
+ BasePath = pathlib.WindowsPath if os.name == 'nt' else pathlib.PosixPath
+
+
+class CPath(BasePath):
+ """
+ Hacky way to support compressed files.
+ If you can think of a better way to do this, please let me know! https://github.com/karlicoss/HPI/issues/20
+
+ Ugh. So, can't override Path because of some _flavour thing.
+ 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):
+ # TODO assert read only?
+ return kopen(str(self))
+
+
+open = kopen # TODO deprecate
+
+
+# meh
+# TODO ideally switch to ZipPath or smth similar?
+# nothing else supports subpath properly anyway
+def kexists(path: PathIsh, subpath: str) -> bool:
+ try:
+ kopen(path, subpath)
+ return True
+ except Exception:
+ return False
+
+
+import zipfile
+if sys.version_info[:2] >= (3, 8):
+ # meh... zipfile.Path is not available on 3.7
+ ZipPathBase = zipfile.Path
+else:
+ if typing.TYPE_CHECKING:
+ ZipPathBase = Any
+ else:
+ ZipPathBase = object
+
+
+class ZipPath(ZipPathBase):
+ # NOTE: is_dir/is_file might not behave as expected, the base class checks it only based on the slash in path
+
+ # seems that at/root are not exposed in the docs, so might be an implementation detail
+ at: str
+ root: zipfile.ZipFile
+
+ @property
+ def filename(self) -> str:
+ res = self.root.filename
+ assert res is not None # make mypy happy
+ return res
+
+ def absolute(self) -> ZipPath:
+ return ZipPath(Path(self.filename).absolute(), self.at)
+
+ def exists(self) -> bool:
+ if self.at == '':
+ # special case, the base class returns False in this case for some reason
+ return Path(self.filename).exists()
+ return super().exists()
+
+ def rglob(self, glob: str) -> Sequence[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]
+
+ def relative_to(self, other: ZipPath) -> Path:
+ assert self.root == other.root, (self.root, other.root)
+ return Path(self.at).relative_to(Path(other.at))
+
+ @property
+ def parts(self) -> Sequence[str]:
+ # messy, but might be ok..
+ return Path(self.filename).parts + Path(self.at).parts
+
+ @property
+ def stem(self) -> str:
+ return Path(self.at).stem
+
+ @property # type: ignore[misc]
+ def __class__(self):
+ return Path
+
+ def __eq__(self, other) -> bool:
+ # hmm, super class doesn't seem to treat as equals unless they are the same object
+ if not isinstance(other, ZipPath):
+ return False
+ return self.filename == other.filename and Path(self.at) == Path(other.at)
diff --git a/my/core/konsume.py b/my/core/konsume.py
index 41b5a4e..76d629f 100644
--- a/my/core/konsume.py
+++ b/my/core/konsume.py
@@ -5,25 +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
+from typing import Any, List
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:
- super().__init__(*args, **kwargs)
+ super().__init__(*args, **kwargs) # type: ignore
self.parent = parent
# TODO not sure, maybe do it via del??
@@ -44,7 +40,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
@@ -67,7 +63,6 @@ class Wdict(Zoomable, OrderedDict):
def this_consumed(self):
return len(self) == 0
-
# TODO specify mypy type for the index special method?
@@ -82,7 +77,6 @@ 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)
@@ -93,20 +87,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) + '}'
-
-def _wrap(j, parent=None) -> tuple[Zoomable, list[Zoomable]]:
+from typing import Tuple
+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
@@ -124,24 +118,21 @@ def _wrap(j, parent=None) -> tuple[Zoomable, list[Zoomable]]:
else:
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]:
+def wrap(j, throw=True) -> Iterator[Zoomable]:
w, children = _wrap(j)
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'''
@@ -151,13 +142,9 @@ Expected {c} to be fully consumed by the parser.
# TODO log?
pass
-
from typing import cast
-
-
-def test_unconsumed() -> None:
- import pytest
-
+def test_unconsumed():
+ import pytest # type: ignore
with pytest.raises(UnconsumedError):
with wrap({'a': 1234}) as w:
w = cast(Wdict, w)
@@ -168,8 +155,7 @@ def test_unconsumed() -> None:
w = cast(Wdict, w)
d = w['c']['d'].zoom()
-
-def test_consumed() -> None:
+def test_consumed():
with wrap({'a': 1234}) as w:
w = cast(Wdict, w)
a = w['a'].zoom()
@@ -179,8 +165,7 @@ def test_consumed() -> None:
c = w['c'].zoom()
d = c['d'].zoom()
-
-def test_types() -> None:
+def test_types():
# (string, number, object, array, boolean or nul
with wrap({'string': 'string', 'number': 3.14, 'boolean': True, 'null': None, 'list': [1, 2, 3]}) as w:
w = cast(Wdict, w)
@@ -188,22 +173,23 @@ 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:
+def test_consume_all():
with wrap({'aaa': {'bbb': {'hi': 123}}}) as w:
w = cast(Wdict, w)
aaa = w['aaa'].zoom()
aaa['bbb'].consume_all()
-def test_consume_few() -> None:
+def test_consume_few():
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()
@@ -211,8 +197,7 @@ def test_consume_few() -> None:
def test_zoom() -> None:
- import pytest
-
+ import pytest # type: ignore
with wrap({'aaa': 'whatever'}) as w:
w = cast(Wdict, w)
with pytest.raises(KeyError):
@@ -221,34 +206,3 @@ 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 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?
-# - 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/core/logging.py b/my/core/logging.py
index 167a167..03484bf 100644
--- a/my/core/logging.py
+++ b/my/core/logging.py
@@ -1,61 +1,49 @@
-from __future__ import annotations
-
-import logging
-import os
-import sys
-import warnings
-from functools import lru_cache
-from typing import TYPE_CHECKING, Union
+#!/usr/bin/env python3
+'''
+Default logger is a bit meh, see 'test'/run this file for a demo
+TODO name 'klogging' to avoid possible conflict with default 'logging' module
+TODO shit. too late already? maybe use fallback & deprecate
+'''
def test() -> None:
from typing import Callable
+ import logging
+ import sys
M: Callable[[str], None] = lambda s: print(s, file=sys.stderr)
- ## prepare exception for later
- try:
- None.whatever # type: ignore[attr-defined] # noqa: B018
- except Exception as e:
- ex = e
- ##
-
- M(" Logging module's defaults are not great:")
- l = logging.getLogger('default_logger')
+ M(" Logging module's defaults are not great...'")
+ l = logging.getLogger('test_logger')
+ # todo why is mypy unhappy about these???
l.error("For example, this should be logged as error. But it's not even formatted properly, doesn't have logger name or level")
- M("\n The reason is that you need to remember to call basicConfig() first. Let's do it now:")
- logging.basicConfig()
+ M(" The reason is that you need to remember to call basicConfig() first")
l.error("OK, this is better. But the default format kinda sucks, I prefer having timestamps and the file/line number")
- M("\n Also exception logging is kinda lame, doesn't print traceback by default unless you remember to pass exc_info:")
- l.exception(ex) # type: ignore[possibly-undefined]
+ M("")
+ M(" With LazyLogger you get a reasonable logging format, colours and other neat things")
- M("\n\n With make_logger you get a reasonable logging format, colours (via colorlog library) and other neat things:")
-
- ll = make_logger('test') # No need for basicConfig!
+ ll = LazyLogger('test') # No need for basicConfig!
ll.info("default level is INFO")
- ll.debug("... so this shouldn't be displayed")
+ ll.debug(".. so this shouldn't be displayed")
ll.warning("warnings are easy to spot!")
-
- M("\n Exceptions print traceback by default now:")
- ll.exception(ex)
-
- M("\n You can (and should) use it via regular logging.getLogger after that, e.g. let's set logging level to DEBUG now")
- logging.getLogger('test').setLevel(logging.DEBUG)
- ll.debug("... now debug messages are also displayed")
+ ll.exception(RuntimeError("exceptions as well"))
-DEFAULT_LEVEL = 'INFO'
-FORMAT = '{start}[%(levelname)-7s %(asctime)s %(name)s %(filename)s:%(lineno)-4d]{end} %(message)s'
-FORMAT_NOCOLOR = FORMAT.format(start='', end='')
-
+import logging
+from typing import Union, Optional
+import os
Level = int
-LevelIsh = Union[Level, str, None]
+LevelIsh = Optional[Union[Level, str]]
def mklevel(level: LevelIsh) -> Level:
+ # todo put in some global file, like envvars.py
+ glevel = os.environ.get('HPI_LOGS', None)
+ if glevel is not None:
+ level = glevel
if level is None:
return logging.NOTSET
if isinstance(level, int):
@@ -63,204 +51,48 @@ def mklevel(level: LevelIsh) -> Level:
return getattr(logging, level.upper())
-def get_collapse_level() -> Level | None:
- # TODO not sure if should be specific to logger name?
- cl = os.environ.get('LOGGING_COLLAPSE', None)
- if cl is not None:
- return mklevel(cl)
- # legacy name, maybe deprecate?
- cl = os.environ.get('COLLAPSE_DEBUG_LOGS', None)
- if cl is not None:
- return logging.DEBUG
- return None
+FORMAT = '{start}[%(levelname)-7s %(asctime)s %(name)s %(filename)s:%(lineno)d]{end} %(message)s'
+FORMAT_COLOR = FORMAT.format(start='%(color)s', end='%(end_color)s')
+FORMAT_NOCOLOR = FORMAT.format(start='', end='')
+DATEFMT = '%Y-%m-%d %H:%M:%S'
-def get_env_level(name: str) -> Level | None:
- PREFIX = 'LOGGING_LEVEL_' # e.g. LOGGING_LEVEL_my_hypothesis=debug
- # shell doesn't allow using dots in var names without escaping, so also support underscore syntax
- lvl = os.environ.get(PREFIX + name, None) or os.environ.get(PREFIX + name.replace('.', '_'), None)
- if lvl is not None:
- return mklevel(lvl)
- # if LOGGING_LEVEL_HPI is set, use that. This should override anything the module may set as its default
- # this is also set when the user passes the --debug flag in the CLI
- #
- # check after LOGGING_LEVEL_ prefix since that is more specific
- if 'LOGGING_LEVEL_HPI' in os.environ:
- return mklevel(os.environ['LOGGING_LEVEL_HPI'])
- # legacy name, for backwards compatibility
- if 'HPI_LOGS' in os.environ:
- from my.core.warnings import medium
+def setup_logger(logger: logging.Logger, level: LevelIsh) -> None:
+ lvl = mklevel(level)
+ try:
+ import logzero # type: ignore[import]
+ except ModuleNotFoundError:
+ import warnings
- medium('The HPI_LOGS environment variable is deprecated, use LOGGING_LEVEL_HPI instead')
-
- return mklevel(os.environ['HPI_LOGS'])
- return None
-
-
-def setup_logger(logger: str | logging.Logger, *, level: LevelIsh = None) -> None:
- """
- Wrapper to simplify logging setup.
- """
- if isinstance(logger, str):
- logger = logging.getLogger(logger)
-
- if level is None:
- level = DEFAULT_LEVEL
-
- # env level always takes precedence
- env_level = get_env_level(logger.name)
- if env_level is not None:
- lvl = env_level
- else:
- lvl = mklevel(level)
-
- if logger.level == logging.NOTSET:
- # if it's already set, the user requested a different logging level, let's respect that
+ warnings.warn("You might want to install 'logzero' for nice colored logs!")
logger.setLevel(lvl)
-
- _setup_handlers_and_formatters(name=logger.name)
-
-
-# cached since this should only be done once per logger instance
-@lru_cache(None)
-def _setup_handlers_and_formatters(name: str) -> None:
- logger = logging.getLogger(name)
-
- logger.addFilter(AddExceptionTraceback())
-
- collapse_level = get_collapse_level()
- if collapse_level is None or not sys.stderr.isatty():
- handler = logging.StreamHandler()
+ h = logging.StreamHandler()
+ h.setLevel(lvl)
+ h.setFormatter(logging.Formatter(fmt=FORMAT_NOCOLOR, datefmt=DATEFMT))
+ logger.addHandler(h)
+ logger.propagate = False # ugh. otherwise it duplicates log messages? not sure about it..
else:
- handler = CollapseLogsHandler(maxlevel=collapse_level)
-
- # default level for handler is NOTSET, which will make it process all messages
- # we rely on the logger to actually accept/reject log msgs
- logger.addHandler(handler)
-
- # this attribute is set to True by default, which causes log entries to be passed to root logger (e.g. if you call basicConfig beforehand)
- # even if log entry is handled by this logger ... not sure what's the point of this behaviour??
- logger.propagate = False
-
- try:
- # 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", stacklevel=1)
- formatter = logging.Formatter(FORMAT_NOCOLOR)
- else:
- # log_color/reset are specific to colorlog
- FORMAT_COLOR = FORMAT.format(start='%(log_color)s', end='%(reset)s')
- # colorlog should detect tty in principle, but doesn't handle everything for some reason
- # see https://github.com/borntyping/python-colorlog/issues/71
- if handler.stream.isatty():
- formatter = colorlog.ColoredFormatter(FORMAT_COLOR)
- else:
- formatter = logging.Formatter(FORMAT_NOCOLOR)
-
- handler.setFormatter(formatter)
+ formatter = logzero.LogFormatter(
+ fmt=FORMAT_COLOR,
+ datefmt=DATEFMT,
+ )
+ logzero.setup_logger(logger.name, level=lvl, formatter=formatter)
-# by default, logging.exception isn't logging traceback unless called inside of the exception handler
-# which is a bit annoying since we have to pass exc_info explicitly
-# also see https://stackoverflow.com/questions/75121925/why-doesnt-python-logging-exception-method-log-traceback-by-default
-# todo also amend by post about defensive error handling?
-class AddExceptionTraceback(logging.Filter):
- def filter(self, record: logging.LogRecord) -> bool:
- if record.levelname == 'ERROR':
- exc = record.msg
- if isinstance(exc, BaseException):
- if record.exc_info is None or record.exc_info == (None, None, None):
- exc_info = (type(exc), exc, exc.__traceback__)
- record.exc_info = exc_info
- return True
+class LazyLogger(logging.Logger):
+ def __new__(cls, name: str, level: LevelIsh = 'INFO') -> 'LazyLogger':
+ logger = logging.getLogger(name)
+ # this is called prior to all _log calls so makes sense to do it here?
+ def isEnabledFor_lazyinit(*args, logger=logger, orig=logger.isEnabledFor, **kwargs):
+ att = 'lazylogger_init_done'
+ if not getattr(logger, att, False): # init once, if necessary
+ setup_logger(logger, level=level)
+ setattr(logger, att, True)
+ return orig(*args, **kwargs)
-
-# todo also save full log in a file?
-class CollapseLogsHandler(logging.StreamHandler):
- '''
- Collapses subsequent debug log lines and redraws on the same line.
- Hopefully this gives both a sense of progress and doesn't clutter the terminal as much?
- '''
-
- last: bool = False
-
- maxlevel: Level = logging.DEBUG # everything with less or equal level will be collapsed
-
- def __init__(self, *args, maxlevel: Level, **kwargs) -> None:
- super().__init__(*args, **kwargs)
- self.maxlevel = maxlevel
-
- def emit(self, record: logging.LogRecord) -> None:
- try:
- msg = self.format(record)
- cur = record.levelno <= self.maxlevel and '\n' not in msg
- if cur:
- if self.last:
- self.stream.write('\033[K' + '\r') # clear line + return carriage
- else:
- if self.last:
- self.stream.write('\n') # clean up after the last line
- self.last = cur
- columns, _ = os.get_terminal_size(0)
- # ugh. the columns thing is meh. dunno I guess ultimately need curses for that
- # TODO also would be cool to have a terminal post-processor? kinda like tail but aware of logging keywords (INFO/DEBUG/etc)
- self.stream.write(msg + ' ' * max(0, columns - len(msg)) + ('' if cur else '\n'))
- self.flush()
- except:
- self.handleError(record)
-
-
-def make_logger(name: str, *, level: LevelIsh = None) -> logging.Logger:
- logger = logging.getLogger(name)
- setup_logger(logger, level=level)
- return logger
-
-
-# ughh. hacky way to have a single enlighten instance per interpreter, so it can be shared between modules
-# not sure about this. I guess this should definitely be behind some flag
-# 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
- )
-
- # for now hidden behind the flag since it's a little experimental
- if os.environ.get('ENLIGHTEN_ENABLE', None) is None:
- return Mock()
-
- try:
- import enlighten # type: ignore[import-untyped]
- except ModuleNotFoundError:
- warnings.warn("You might want to 'pip install enlighten' for a nice progress bar", stacklevel=1)
-
- return Mock()
-
- # dirty, but otherwise a bit unclear how to share enlighten manager between packages that call each other
- instance = getattr(enlighten, 'INSTANCE', None)
- if instance is not None:
- return instance
- instance = enlighten.get_manager()
- setattr(enlighten, 'INSTANCE', instance)
- return instance
+ logger.isEnabledFor = isEnabledFor_lazyinit # type: ignore[assignment]
+ return logger # type: ignore[return-value]
if __name__ == '__main__':
test()
-
-
-## legacy/deprecated methods for backwards compatibility
-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/mime.py b/my/core/mime.py
deleted file mode 100644
index 8235960..0000000
--- a/my/core/mime.py
+++ /dev/null
@@ -1,37 +0,0 @@
-"""
-Utils for mime/filetype handling
-"""
-
-from __future__ import annotations
-
-from .internal import assert_subpackage
-
-assert_subpackage(__name__)
-
-import functools
-from pathlib import Path
-
-
-@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: Path | str) -> 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/core/orgmode.py b/my/core/orgmode.py
index 96c09a4..5894b23 100644
--- a/my/core/orgmode.py
+++ b/my/core/orgmode.py
@@ -1,46 +1,37 @@
"""
Various helpers for reading org-mode data
"""
-
from datetime import datetime
-
-
def parse_org_datetime(s: str) -> datetime:
s = s.strip('[]')
- 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),
+ 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),
]:
try:
return datetime.strptime(s, fmt)
except ValueError:
continue
- raise RuntimeError(f"Bad datetime string {s}")
+ else:
+ 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
-from collections.abc import Iterable
-from typing import Callable, 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]:
yield from cfun(n)
for c in n.children:
yield from collect(c, cfun)
-
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))))
@@ -50,7 +41,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 d444965..9cf037f 100644
--- a/my/core/pandas.py
+++ b/my/core/pandas.py
@@ -1,54 +1,32 @@
'''
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
# 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 datetime import datetime
from pprint import pformat
-from typing import (
- TYPE_CHECKING,
- Any,
- Callable,
- Literal,
- TypeVar,
-)
+from typing import Optional, TYPE_CHECKING, Any, Iterable, Type, Dict
+from . import warnings, Res
+from .common import LazyLogger, Json, asdict
-from decorator import decorator
-
-from . import warnings
-from .error import Res, error_to_json, extract_error_datetime
-from .logging import make_logger
-from .types import Json, asdict
-
-logger = make_logger(__name__)
+logger = LazyLogger(__name__)
if TYPE_CHECKING:
- import pandas as pd
-
- DataFrameT = pd.DataFrame
- SeriesT = pd.Series
- from pandas._typing import S1 # meh
-
- FuncT = TypeVar('FuncT', bound=Callable[..., DataFrameT])
- # huh interesting -- with from __future__ import annotations don't even need else clause here?
- # but still if other modules import these we do need some fake runtime types here..
-else:
- from typing import Optional
-
+ # this is kinda pointless at the moment, but handy to annotate DF returning methods now
+ # later will be unignored when they implement type annotations
+ import pandas as pd # type: ignore
+ # DataFrameT = pd.DataFrame
+ # TODO ugh. pretty annoying, having any is not very useful since it would allow arbitrary coercions..
+ # ideally want to use a type that's like Any but doesn't allow arbitrary coercions??
+ DataFrameT = Any
+else:
+ # in runtime, make it defensive so it works without pandas
DataFrameT = Any
- SeriesT = Optional # just some type with one argument
- S1 = Any
-def _check_dateish(s: SeriesT[S1]) -> Iterable[str]:
- import pandas as pd # noqa: F811 not actually a redefinition
-
+def check_dateish(s) -> Iterable[str]:
+ import pandas as pd # type: ignore
ctype = s.dtype
if str(ctype).startswith('datetime64'):
return
@@ -57,8 +35,8 @@ def _check_dateish(s: SeriesT[S1]) -> Iterable[str]:
return
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() # type: ignore[union-attr, var-annotated, arg-type, return-value, unused-ignore]
+ return # not sure why it would happen, but ok
+ tzs = s.map(lambda x: x.tzinfo).drop_duplicates()
examples = s[tzs.index]
# todo not so sure this warning is that useful... except for stuff without tz
yield f'''
@@ -67,50 +45,13 @@ def _check_dateish(s: SeriesT[S1]) -> Iterable[str]:
'''.strip()
-def test_check_dateish() -> None:
- import pandas as pd
+from .compat import Literal
- 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
ErrorColPolicy = Literal[
- 'add_if_missing', # add error column if it's missing
- 'warn' , # warn, but do not modify
- 'ignore' , # no warnings
+ 'add_if_missing', # add error column if it's missing
+ 'warn' , # warn, but do not modify
+ 'ignore' , # no warnings
]
-# fmt: on
-
def check_error_column(df: DataFrameT, *, policy: ErrorColPolicy) -> Iterable[str]:
if 'error' in df:
@@ -130,15 +71,19 @@ No 'error' column detected. You probably forgot to handle errors defensively, wh
yield wmsg
-# TODO ugh. typing this is a mess... perhaps should use .compat.ParamSpec?
+from typing import Any, Callable, TypeVar
+FuncT = TypeVar('FuncT', bound=Callable[..., DataFrameT])
+
+# TODO ugh. typing this is a mess... shoul I use mypy_extensions.VarArg/KwArgs?? or what??
+from decorator import decorator
@decorator
-def check_dataframe(f: FuncT, error_col_policy: ErrorColPolicy = 'add_if_missing', *args, **kwargs) -> DataFrameT:
- df: DataFrameT = f(*args, **kwargs)
+def check_dataframe(f: FuncT, error_col_policy: ErrorColPolicy='add_if_missing', *args, **kwargs) -> DataFrameT:
+ df = f(*args, **kwargs)
tag = '{f.__module__}:{f.__name__}'
# makes sense to keep super defensive
try:
- for col, data in df.reset_index().items():
- for w in _check_dateish(data):
+ for col, data in df.reset_index().iteritems():
+ for w in check_dateish(data):
warnings.low(f"{tag}, column '{col}': {w}")
except Exception as e:
logger.exception(e)
@@ -149,11 +94,11 @@ def check_dataframe(f: FuncT, error_col_policy: ErrorColPolicy = 'add_if_missing
logger.exception(e)
return df
-
# todo doctor: could have a suggesion to wrap dataframes with it?? discover by return type?
-def error_to_row(e: Exception, *, dt_col: str = 'dt', tz: timezone | None = None) -> Json:
+def error_to_row(e: Exception, *, dt_col: str='dt', tz=None) -> Json:
+ from .error import error_to_json, extract_error_datetime
edt = extract_error_datetime(e)
if edt is not None and edt.tzinfo is None and tz is not None:
edt = edt.replace(tzinfo=tz)
@@ -162,7 +107,8 @@ def error_to_row(e: Exception, *, dt_col: str = 'dt', tz: timezone | None = None
return err_dict
-def _to_jsons(it: Iterable[Res[Any]]) -> Iterable[Json]:
+# todo not sure about naming
+def to_jsons(it: Iterable[Res[Any]]) -> Iterable[Json]:
for r in it:
if isinstance(r, Exception):
yield error_to_row(r)
@@ -174,11 +120,11 @@ def _to_jsons(it: Iterable[Res[Any]]) -> Iterable[Json]:
# no type for dataclass?
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??
+ import dataclasses as D
+ if D.is_dataclass(s):
+ return {f.name: f.type for f in D.fields(s)}
# else must be NamedTuple??
# todo assert my.core.common.is_namedtuple?
return getattr(s, '_field_types')
@@ -186,7 +132,7 @@ def _as_columns(s: Schema) -> dict[str, type]:
# todo add proper types
@check_dataframe
-def as_dataframe(it: Iterable[Res[Any]], schema: Schema | None = None) -> DataFrameT:
+def as_dataframe(it: Iterable[Res[Any]], schema: Optional[Schema]=None) -> DataFrameT:
# todo warn if schema isn't specified?
# ok nice supports dataframe/NT natively
# https://github.com/pandas-dev/pandas/pull/27999
@@ -194,89 +140,26 @@ def as_dataframe(it: Iterable[Res[Any]], schema: Schema | None = None) -> DataFr
# https://github.com/pandas-dev/pandas/blob/fc9fdba6592bdb5d0d1147ce4d65639acd897565/pandas/core/frame.py#L562
# same for NamedTuple -- seems that it takes whatever schema the first NT has
# so we need to convert each individually... sigh
- import pandas as pd # noqa: F811 not actually a redefinition
-
+ import pandas as pd
columns = None if schema is None else list(_as_columns(schema).keys())
- return pd.DataFrame(_to_jsons(it), columns=columns)
-
-
-# ugh. in principle this could be inside the test
-# might be due to use of from __future__ import annotations
-# can quickly reproduce by running pytest tests/tz.py tests/core/test_pandas.py
-# possibly will be resolved after fix in pytest?
-# see https://github.com/pytest-dev/pytest/issues/7856
-@dataclasses.dataclass
-class _X:
- # FIXME try moving inside?
- x: int
+ return pd.DataFrame(to_jsons(it), columns=columns)
def test_as_dataframe() -> None:
- import numpy as np
- import pandas as pd
import pytest
- from pandas.testing import assert_frame_equal
-
- from .compat import fromisoformat
-
- 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)
+ it = (dict(i=i, s=f'str{i}') for i in range(10))
+ with pytest.warns(UserWarning, match=r"No 'error' column") as record_warnings:
+ df = as_dataframe(it)
# todo test other error col policies
+ assert list(df.columns) == ['i', 's', 'error']
- # 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']))
+ assert len(as_dataframe([])) == 0
- df2: DataFrameT = as_dataframe([], schema=_X)
- 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']),
- )
+ from dataclasses import dataclass
+ @dataclass
+ class X:
+ x: int
- @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
+ # makes sense to specify the schema so the downstream program doesn't fail in case of empty iterable
+ df = as_dataframe([], schema=X)
+ assert list(df.columns) == ['x', 'error']
diff --git a/my/core/preinit.py b/my/core/preinit.py
index eb3a34f..c05ee40 100644
--- a/my/core/preinit.py
+++ b/my/core/preinit.py
@@ -1,14 +1,8 @@
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]
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
deleted file mode 100644
index ad9e7d7..0000000
--- a/my/core/pytest.py
+++ /dev/null
@@ -1,24 +0,0 @@
-"""
-Helpers to prevent depending on pytest in runtime
-"""
-
-from .internal 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/query.py b/my/core/query.py
index 50724a7..385fe5f 100644
--- a/my/core/query.py
+++ b/my/core/query.py
@@ -5,29 +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,
- NamedTuple,
- Optional,
- TypeVar,
-)
+from typing import TypeVar, Tuple, Optional, Union, Callable, Iterable, Iterator, Dict, Any, NamedTuple, List
import more_itertools
-from . import error as err
+from .common import is_namedtuple
from .error import Res, unwrap
-from .types import is_namedtuple
from .warnings import low
+
T = TypeVar("T")
ET = Res[T]
@@ -35,7 +26,7 @@ ET = Res[T]
U = TypeVar("U")
# In a perfect world, the return value from a OrderFunc would just be U,
# not Optional[U]. However, since this has to deal with so many edge
-# cases, there's a possibility that the functions generated by
+# cases, theres a possibility that the functions generated by
# _generate_order_by_func can't find an attribute
OrderFunc = Callable[[ET], Optional[U]]
Where = Callable[[ET], bool]
@@ -48,7 +39,6 @@ class Unsortable(NamedTuple):
class QueryException(ValueError):
"""Used to differentiate query-related errors, so the CLI interface is more expressive"""
-
pass
@@ -61,16 +51,16 @@ 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, func) in inspect.getmembers(mod, inspect.isfunction):
if fname == function_name:
- return f
- # in case the function is defined dynamically,
+ return func
+ # incase the function is defined dynamically,
# like with a globals().setdefault(...) or a module-level __getattr__ function
func = getattr(mod, function_name, None)
if func is not None and callable(func):
return func
except Exception as e:
- raise QueryException(str(e)) # noqa: B904
+ raise QueryException(str(e))
raise QueryException(f"Could not find function '{function_name}' in '{module_name}'")
@@ -81,10 +71,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: U | None = None) -> OrderFunc | None:
+def attribute_func(obj: T, where: Where, default: Optional[U] = None) -> Optional[OrderFunc]:
"""
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
@@ -112,7 +102,7 @@ def attribute_func(obj: T, where: Where, default: U | None = None) -> OrderFunc
if where(v):
return lambda o: o.get(k, default) # type: ignore[union-attr]
elif dataclasses.is_dataclass(obj):
- for field_name in obj.__annotations__.keys():
+ for (field_name, _annotation) in obj.__annotations__.items():
if where(getattr(obj, field_name)):
return lambda o: getattr(o, field_name, default)
elif is_namedtuple(obj):
@@ -129,13 +119,12 @@ def attribute_func(obj: T, where: Where, default: U | None = None) -> OrderFunc
def _generate_order_by_func(
- obj_res: Res[T],
- *,
- key: str | None = None,
- where_function: Where | None = None,
- default: U | None = None,
- force_unsortable: bool = False,
-) -> OrderFunc | None:
+ 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)
@@ -188,7 +177,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)
+ return lambda o: getattr(o, key, default) # type: ignore[arg-type]
# 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
@@ -200,7 +189,7 @@ pass 'drop_exceptions' to ignore exceptions""")
# user must provide either a key or a where predicate
if where_function is not None:
- func: OrderFunc | None = attribute_func(obj, where_function, default)
+ func: Optional[OrderFunc] = attribute_func(obj, where_function, default)
if func is not None:
return func
@@ -216,13 +205,29 @@ pass 'drop_exceptions' to ignore exceptions""")
return None # couldn't compute a OrderFunc for this class/instance
+def _drop_exceptions(itr: Iterator[ET]) -> Iterator[T]:
+ """Return non-errors from the iterable"""
+ for o in itr:
+ if isinstance(o, Exception):
+ continue
+ yield o
+
+
+def _raise_exceptions(itr: Iterable[ET]) -> Iterator[T]:
+ """Raise errors from the iterable, stops the select function"""
+ for o in itr:
+ if isinstance(o, Exception):
+ raise o
+ yield o
+
+
# 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:
"""
Returns either the class, or a tuple of the dictionary keys
"""
key = obj_res.__class__
- if key is dict:
+ if key == dict:
# assuming same keys signify same way to determine ordering
return tuple(obj_res.keys()) # type: ignore[union-attr]
return key
@@ -239,8 +244,8 @@ 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[ET | None, Iterator[ET]]:
+# similar to my.core.common.warn_if_empty? this doesnt go through the whole iterator though
+def _peek_iter(itr: Iterator[ET]) -> Tuple[Optional[ET], Iterator[ET]]:
itr = more_itertools.peekable(itr)
try:
first_item = itr.peek()
@@ -251,9 +256,9 @@ def _peek_iter(itr: Iterator[ET]) -> tuple[ET | None, 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):
@@ -271,11 +276,10 @@ 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
-) -> 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)
@@ -286,20 +290,20 @@ def _handle_unsorted(
return iter([]), itr
-# handles creating an order_value function, using a lookup for
+# handles creating an order_value functon, using a lookup for
# 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: U | None = None) -> OrderFunc:
+def _generate_order_value_func(itr: Iterator[ET], order_value: Where, default: Optional[U] = 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: OrderFunc | None = _generate_order_by_func(
+ keyfunc: Optional[OrderFunc] = _generate_order_by_func(
obj_res,
where_function=order_value,
default=default,
@@ -320,12 +324,12 @@ def _generate_order_value_func(itr: Iterator[ET], order_value: Where, default: U
def _handle_generate_order_by(
itr,
*,
- 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
+ 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
if order_by is not None:
return order_by, itr
if order_key is not None:
@@ -350,19 +354,17 @@ def _handle_generate_order_by(
def select(
- src: Iterable[ET] | Callable[[], Iterable[ET]],
+ src: Union[Iterable[ET], Callable[[], Iterable[ET]]],
*,
- where: Where | None = None,
- order_by: OrderFunc | None = None,
- order_key: str | None = None,
- order_value: Where | None = None,
- default: U | None = None,
+ where: Optional[Where] = None,
+ order_by: Optional[OrderFunc] = None,
+ order_key: Optional[str] = None,
+ order_value: Optional[Where] = None,
+ default: Optional[U] = None,
reverse: bool = False,
- limit: int | None = None,
+ limit: Optional[int] = None,
drop_unsorted: bool = False,
wrap_unsorted: bool = True,
- warn_exceptions: bool = False,
- warn_func: Callable[[Exception], None] | None = None,
drop_exceptions: bool = False,
raise_exceptions: bool = False,
) -> Iterator[ET]:
@@ -372,7 +374,7 @@ def select(
by allowing you to provide custom predicates (functions) which can sort
by a function, an attribute, dict key, or by the attributes values.
- Since this supports mixed types, there's always a possibility
+ Since this supports mixed types, theres always a possibility
of KeyErrors or AttributeErrors while trying to find some value to order by,
so this provides multiple mechanisms to deal with that
@@ -406,9 +408,7 @@ def select(
to copy the iterator in memory (using itertools.tee) to determine how to order it
in memory
- The 'drop_exceptions', 'raise_exceptions', 'warn_exceptions' let you ignore or raise
- when the src contains exceptions. The 'warn_func' lets you provide a custom function
- to call when an exception is encountered instead of using the 'warnings' module
+ The 'drop_exceptions' and 'raise_exceptions' let you ignore or raise when the src contains exceptions
src: an iterable of mixed types, or a function to be called,
as the input to this function
@@ -464,18 +464,15 @@ 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)) # noqa: B904
+ raise QueryException("Could not convert input src to an Iterator: " + str(t))
# if both drop_exceptions and drop_exceptions are provided for some reason,
# should raise exceptions before dropping them
if raise_exceptions:
- itr = err.raise_exceptions(itr)
+ itr = _raise_exceptions(itr)
if drop_exceptions:
- itr = err.drop_exceptions(itr)
-
- if warn_exceptions:
- itr = err.warn_exceptions(itr, warn_func=warn_func)
+ itr = _drop_exceptions(itr)
if where is not None:
itr = filter(where, itr)
@@ -501,15 +498,10 @@ 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,
- orderfunc=order_by_chosen,
- drop_unsorted=drop_unsorted,
- wrap_unsorted=wrap_unsorted,
- )
+ unsortable, itr = _handle_unsorted(itr, order_by_chosen, drop_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]
+ itr = iter(sorted(itr, key=order_by_chosen, reverse=reverse)) # type: ignore[arg-type, type-var]
# re-attach unsortable values to the front/back of the list
if reverse:
@@ -528,6 +520,7 @@ Will attempt to call iter() on the value""")
return itr
+
# classes to use in tests, need to be defined at the top level
# because of a mypy bug
class _Int(NamedTuple):
@@ -557,7 +550,7 @@ def test_basic_orders() -> None:
random.shuffle(input_items)
res = list(select(input_items, order_key="x"))
- assert res == [_Int(1), _Int(2), _Int(3), _Int(4), _Int(5)]
+ assert res == [_Int(1),_Int(2),_Int(3),_Int(4),_Int(5)]
# default int ordering
def custom_order_by(obj: Any) -> Any:
@@ -578,10 +571,12 @@ def test_order_key_multi_type() -> None:
for v in range(1, 6):
yield _Int(v)
+
def floaty_iter() -> Iterator[_Float]:
for v in range(1, 6):
yield _Float(float(v + 0.5))
+
res = list(select(itertools.chain(basic_iter(), floaty_iter()), order_key="x"))
assert res == [
_Int(1), _Float(1.5),
@@ -597,7 +592,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) is object
+ assert type(res[0].obj) == object
# same value type, different keys, with clashing keys
@@ -613,7 +608,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[_A | _B]:
+def _mixed_iter() -> Iterator[Union[_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)
@@ -622,7 +617,7 @@ def _mixed_iter() -> Iterator[_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[_A | _B]]:
+def _mixed_iter_errors() -> Iterator[Res[Union[_A, _B]]]:
m = _mixed_iter()
yield from itertools.islice(m, 0, 3)
yield RuntimeError("Unhandled error!")
@@ -658,7 +653,7 @@ def test_wrap_unsortable() -> None:
# by default, wrap unsortable
res = list(select(_mixed_iter(), order_key="z"))
- assert Counter(type(t).__name__ for t in res) == Counter({"_A": 4, "Unsortable": 2})
+ assert Counter(map(lambda t: type(t).__name__, res)) == Counter({"_A": 4, "Unsortable": 2})
def test_disabled_wrap_unsorted() -> None:
@@ -677,7 +672,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(type(t).__name__ for t in res) == Counter({"_A": 4})
+ assert Counter(map(lambda t: type(t).__name__, res)) == Counter({"_A": 4})
def test_drop_exceptions() -> None:
@@ -701,16 +696,15 @@ def test_raise_exceptions() -> None:
def test_wrap_unsortable_with_error_and_warning() -> None:
- from collections import Counter
-
import pytest
+ from collections import Counter
# 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(type(t).__name__ for t in res) == Counter({"_A": 4, "_B": 2, "Unsortable": 1})
+ assert Counter(map(lambda t: type(t).__name__, 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)
@@ -720,7 +714,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(type(t).__name__ for t in res) == Counter({"_A": 4, "Unsortable": 3})
+ assert Counter(map(lambda t: type(t).__name__, res)) == Counter({"_A": 4, "Unsortable": 3})
def test_order_default_param() -> None:
@@ -740,7 +734,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(type(t).__name__ for t in res) == Counter({"_A": 4, "Unsortable": 3})
+ assert Counter(map(lambda t: type(t).__name__, res)) == Counter({"_A": 4, "Unsortable": 3})
# drop_unsorted
dropped = list(select(res, order_key="z", drop_unsorted=True))
diff --git a/my/core/query_range.py b/my/core/query_range.py
index 83728bf..04952d4 100644
--- a/my/core/query_range.py
+++ b/my/core/query_range.py
@@ -7,30 +7,27 @@ 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 cache
-from typing import Any, Callable, NamedTuple
+from functools import lru_cache
+from datetime import datetime, timedelta, date
+from typing import Callable, Iterator, NamedTuple, Optional, Any, Type
import more_itertools
-from .compat import fromisoformat
from .query import (
- ET,
- OrderFunc,
QueryException,
+ select,
+ OrderFunc,
Where,
_handle_generate_order_by,
- select,
+ ET,
)
-timedelta_regex = re.compile(
- r"^((?P[\.\d]+?)w)?((?P[\.\d]+?)d)?((?P[\.\d]+?)h)?((?P[\.\d]+?)m)?((?P[\.\d]+?)s)?$"
-)
+from .common import isoparse
+
+
+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
@@ -43,7 +40,7 @@ def parse_timedelta_string(timedelta_str: str) -> timedelta:
if parts is None:
raise ValueError(f"Could not parse time duration from {timedelta_str}.\nValid examples: '8h', '1w2d8h5m20s', '2m4s'")
time_params = {name: float(param) for name, param in parts.groupdict().items() if param}
- return timedelta(**time_params)
+ return timedelta(**time_params) # type: ignore[arg-type]
def parse_timedelta_float(timedelta_str: str) -> float:
@@ -76,34 +73,19 @@ def parse_datetime_float(date_str: str) -> float:
return ds_float
try:
# isoformat - default format when you call str() on datetime
- # this also parses dates like '2020-01-01'
return datetime.fromisoformat(ds).timestamp()
except ValueError:
pass
try:
- return fromisoformat(ds).timestamp()
+ return isoparse(ds).timestamp()
except (AssertionError, ValueError):
- pass
-
- try:
- import dateparser
- except ImportError:
- pass
- else:
- # 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: datetime | None = dateparser.parse(ds, settings={"DATE_ORDER": "YMD"})
- if res is not None:
- return res.timestamp()
-
- raise QueryException(f"Was not able to parse {ds} into a datetime")
+ raise QueryException(f"Was not able to parse {ds} into a datetime")
# 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
-@cache
+@lru_cache(maxsize=None)
def _datelike_to_float(dl: Any) -> float:
if isinstance(dl, datetime):
return dl.timestamp()
@@ -114,7 +96,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)) # noqa: B904
+ raise QueryException(f"While attempting to extract datetime from {dl}, to order by datetime:\n\n" + str(q))
class RangeTuple(NamedTuple):
@@ -135,12 +117,11 @@ 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: Any | None
- before: Any | None
- within: Any | None
+ after: Optional[Any]
+ before: Optional[Any]
+ within: Optional[Any]
Converter = Callable[[Any], Any]
@@ -151,15 +132,13 @@ def _parse_range(
unparsed_range: RangeTuple,
end_parser: Converter,
within_parser: Converter,
- parsed_range: RangeTuple | None = None,
- error_message: str | None = None,
-) -> RangeTuple | None:
+ parsed_range: Optional[RangeTuple] = None,
+ error_message: Optional[str] = None) -> Optional[RangeTuple]:
if parsed_range is not None:
return parsed_range
err_msg = error_message or RangeTuple.__doc__
- assert err_msg is not None # make mypy happy
after, before, within = None, None, None
none_count = more_itertools.ilen(filter(lambda o: o is None, list(unparsed_range)))
@@ -182,11 +161,11 @@ def _create_range_filter(
end_parser: Converter,
within_parser: Converter,
attr_func: Where,
- parsed_range: RangeTuple | None = None,
- default_before: Any | None = None,
- value_coercion_func: Converter | None = None,
- error_message: str | None = None,
-) -> Where | None:
+ parsed_range: Optional[RangeTuple] = None,
+ default_before: Optional[Any] = None,
+ value_coercion_func: Optional[Converter] = None,
+ error_message: Optional[str] = None,
+) -> Optional[Where]:
"""
Handles:
- parsing the user input into values that are comparable to items the iterable returns
@@ -240,7 +219,7 @@ def _create_range_filter(
# inclusivity here? Is [after, before) currently,
# items are included on the lower bound but not the
# upper bound
- # typically used for datetimes so doesn't have to
+ # typically used for datetimes so doesnt have to
# be exact in that case
def generated_predicate(obj: Any) -> bool:
ov: Any = attr_func(obj)
@@ -278,17 +257,15 @@ def _create_range_filter(
def select_range(
itr: Iterator[ET],
*,
- 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,
+ 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,
reverse: bool = False,
- limit: int | None = None,
+ limit: Optional[int] = None,
drop_unsorted: bool = False,
wrap_unsorted: bool = False,
- warn_exceptions: bool = False,
- warn_func: Callable[[Exception], None] | None = None,
drop_exceptions: bool = False,
raise_exceptions: bool = False,
) -> Iterator[ET]:
@@ -315,30 +292,21 @@ def select_range(
unparsed_range = None
# some operations to do before ordering/filtering
- if drop_exceptions or raise_exceptions or where is not None or warn_exceptions:
- # doesn't wrap unsortable items, because we pass no order related kwargs
- itr = select(
- itr,
- where=where,
- drop_exceptions=drop_exceptions,
- raise_exceptions=raise_exceptions,
- warn_exceptions=warn_exceptions,
- warn_func=warn_func,
- )
+ if drop_exceptions or raise_exceptions or where is not None:
+ # doesnt wrap unsortable items, because we pass no order related kwargs
+ itr = select(itr, where=where, drop_exceptions=drop_exceptions, raise_exceptions=raise_exceptions)
- order_by_chosen: OrderFunc | None = None
+ order_by_chosen: Optional[OrderFunc] = 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
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)
+ order_value = lambda o: isinstance(o, order_by_value_type) # type: ignore
# 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:
@@ -350,46 +318,44 @@ 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""")
-
- # 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: Where | None
- 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")
+ # 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)
+ # 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
#
# this select is also run if the user didn't specify anything to
# order by, and is just returning the data in the same order as
- # as the source iterable
+ # as the srouce iterable
# i.e. none of the range-related filtering code ran, this is just a select
itr = select(itr,
order_by=order_by_chosen,
@@ -400,7 +366,7 @@ Specify a type or a key to order the value by""")
return itr
-# reuse items from query for testing
+# re-use items from query for testing
from .query import _A, _B, _Float, _mixed_iter_errors
@@ -422,6 +388,7 @@ def test_filter_in_timeframe() -> None:
_A(x=datetime(2009, 5, 10, 4, 10, 1), y=5, z=10),
_B(y=datetime(year=2015, month=5, day=10, hour=4, minute=10, second=1))]
+
rng = RangeTuple(before=str(jan_1_2016), within="52w", after=None)
# from 2016, going back 52 weeks (about a year?)
@@ -471,17 +438,12 @@ def test_range_predicate() -> None:
# convert any float values to ints
coerce_int_parser = lambda o: int(float(o))
- int_filter_func = partial(
- _create_range_filter,
- attr_func=identity,
- end_parser=coerce_int_parser,
- within_parser=coerce_int_parser,
- value_coercion_func=coerce_int_parser,
- )
+ int_filter_func = partial(_create_range_filter, attr_func=identity, end_parser=coerce_int_parser,
+ within_parser=coerce_int_parser, value_coercion_func=coerce_int_parser)
# filter from 0 to 5
- rn: RangeTuple = RangeTuple("0", "5", None)
- zero_to_five_filter: Where | None = int_filter_func(unparsed_range=rn)
+ rn: Optional[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
assert zero_to_five_filter(3) is True
@@ -494,7 +456,6 @@ 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
@@ -517,7 +478,7 @@ def test_parse_range() -> None:
assert res2 == RangeTuple(after=start_date.timestamp(), before=end_date.timestamp(), within=None)
- # can't specify all three
+ # cant specify all three
with pytest.raises(QueryException, match=r"Cannot specify 'after', 'before' and 'within'"):
dt_parse_range(unparsed_range=RangeTuple(str(start_date), str(end_date.timestamp()), "7d"))
@@ -538,8 +499,9 @@ 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
@@ -555,3 +517,4 @@ def test_parse_datetime_float() -> None:
# test parsing isoformat
assert dt.timestamp() == parse_datetime_float(str(dt))
+
diff --git a/my/core/serialize.py b/my/core/serialize.py
index e36da8f..db65adb 100644
--- a/my/core/serialize.py
+++ b/my/core/serialize.py
@@ -1,15 +1,11 @@
-from __future__ import annotations
-
import datetime
-from dataclasses import asdict, is_dataclass
-from decimal import Decimal
-from functools import cache
+import dataclasses
from pathlib import Path
-from typing import Any, Callable, NamedTuple
+from typing import Any, Optional, Callable, NamedTuple
+from functools import lru_cache
+from .common import is_namedtuple
from .error import error_to_json
-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
@@ -19,8 +15,6 @@ from .types import is_namedtuple
DefaultEncoder = Callable[[Any], Any]
-Dumps = Callable[[Any], str]
-
def _default_encode(obj: Any) -> Any:
"""
@@ -38,16 +32,10 @@ def _default_encode(obj: Any) -> Any:
# convert paths to their string representation
if isinstance(obj, Path):
return str(obj)
- if is_dataclass(obj):
- assert not isinstance(obj, type) # to help mypy
- return asdict(obj)
+ if dataclasses.is_dataclass(obj):
+ return dataclasses.asdict(obj)
if isinstance(obj, Exception):
return error_to_json(obj)
- # if something was stored as 'decimal', you likely
- # don't want to convert it to float since you're
- # storing as decimal to not lose the precision
- if isinstance(obj, Decimal):
- return str(obj)
# note: _serialize would only be called for items which aren't already
# serialized as a dataclass or namedtuple
# discussion: https://github.com/karlicoss/HPI/issues/138#issuecomment-801704929
@@ -59,18 +47,19 @@ 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
-@cache
+@lru_cache(maxsize=None)
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: DefaultEncoder | None = kwargs.get("default")
+ _additional_default: Optional[DefaultEncoder] = kwargs.get("default")
if _additional_default is not None and callable(_additional_default):
def wrapped_default(obj: Any) -> Any:
- assert _additional_default is not None
try:
- return _additional_default(obj)
+ # hmm... shouldn't mypy know that _additional_default is not None here?
+ # assert _additional_default is not None
+ return _additional_default(obj) # type: ignore[misc]
except TypeError:
# expected TypeError, signifies couldn't be encoded by custom
# serializer function. Try _default_encode from here
@@ -80,35 +69,28 @@ def _dumps_factory(**kwargs) -> Callable[[Any], str]:
kwargs["default"] = use_default
- prefer_factory: str | None = kwargs.pop('_prefer_factory', None)
-
- def orjson_factory() -> Dumps | None:
- try:
- import orjson
- except ModuleNotFoundError:
- return None
+ try:
+ import orjson
# 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: # TODO rename?
+ def _orjson_dumps(obj: Any) -> str:
# orjson returns json as bytes, encode to string
return orjson.dumps(obj, **kwargs).decode('utf-8')
return _orjson_dumps
+ except ModuleNotFoundError:
+ pass
- def simplejson_factory() -> Dumps | None:
- try:
- from simplejson import dumps as simplejson_dumps
- except ModuleNotFoundError:
- return None
-
+ try:
+ from simplejson import dumps as simplejson_dumps
# 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
# out of the box
#
- # unlike the builtin JSON module which serializes NamedTuples as lists
+ # unlike the builtin JSON modue which serializes NamedTuples as lists
# (even if you provide a default function), simplejson correctly
# serializes namedtuples to dictionaries
@@ -117,42 +99,23 @@ def _dumps_factory(**kwargs) -> Callable[[Any], str]:
return _simplejson_dumps
- def stdlib_factory() -> Dumps | None:
- import json
+ except ModuleNotFoundError:
+ pass
- 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
-
- 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
- raise RuntimeError("Should not happen!")
+ return _stdlib_dumps
def dumps(
obj: Any,
- default: DefaultEncoder | None = None,
+ default: Optional[DefaultEncoder] = None,
**kwargs,
) -> str:
"""
@@ -185,19 +148,12 @@ def dumps(
return _dumps_factory(default=default, **kwargs)(obj)
-@parametrize('factory', ['orjson', 'simplejson', 'stdlib'])
-def test_dumps(factory: str) -> None:
+def test_serialize_fallback() -> None:
+ import json as jsn # dont cause possible conflicts with module code
+
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
+ # cant use a namedtuple here, since the default json.dump serializer
# serializes namedtuples as tuples, which become arrays
# just test with an array of mixed objects
X = [5, datetime.timedelta(seconds=5.0)]
@@ -206,12 +162,37 @@ def test_dumps(factory: str) -> 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 = json_builtin.loads(dumps(X))
+ res = jsn.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}
+ res = jsn.loads(dumps(data, option=orjson.OPT_NON_STR_KEYS))
+ assert res == {'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
@@ -225,37 +206,17 @@ def test_dumps(factory: str) -> None:
def _serialize(self) -> Any:
return {"x": self.x, "y": self.y}
- res = json_builtin.loads(dumps(WithUnderscoreSerialize(6)))
+ res = jsn.loads(dumps(WithUnderscoreSerialize(6)))
assert res == {"x": 6, "y": 6.0}
# test passing additional 'default' func
def _serialize_with_default(o: Any) -> Any:
if isinstance(o, Unserializable):
return {"x": o.x, "y": o.y}
- raise TypeError("Couldn't serialize")
+ raise TypeError("Couldnt serialize")
# 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 = json_builtin.loads(dumps(Unserializable(10), default=_serialize_with_default))
+ res2 = jsn.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
-
- 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/my/core/source.py b/my/core/source.py
index a309d13..07ead1e 100644
--- a/my/core/source.py
+++ b/my/core/source.py
@@ -3,14 +3,9 @@ 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 typing import Any, Iterator, TypeVar, Callable, Optional, Iterable, Any, cast
+from my.core.warnings import medium, warn
from functools import wraps
-from typing import Any, Callable, TypeVar
-
-from .warnings import medium
# The factory function may produce something that has data
# similar to the shared model, but not exactly, so not
@@ -29,8 +24,7 @@ _DEFAULT_ITR = ()
def import_source(
*,
default: Iterable[T] = _DEFAULT_ITR,
- module_name: str | None = None,
- help_url: str | None = None,
+ module_name: Optional[str] = None,
) -> Callable[..., Callable[..., Iterator[T]]]:
"""
doesn't really play well with types, but is used to catch
@@ -53,7 +47,6 @@ 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
@@ -62,21 +55,20 @@ def import_source(
medium(f"Module {factory_func.__qualname__} could not be imported, or isn't configured properly")
else:
medium(f"Module {module_name} ({factory_func.__qualname__}) could not be imported, or isn't configured properly")
- 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:
+ 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 = [{module_name!r}]
-""", stacklevel=1)
+ disabled_modules = [{repr(module_name)}]
+""")
# 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)
+ matched_config_err = warn_my_config_import_error(err)
# 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
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 6167d2e..1b38869 100644
--- a/my/core/sqlite.py
+++ b/my/core/sqlite.py
@@ -1,22 +1,17 @@
-from __future__ import annotations
+from .common import assert_subpackage; assert_subpackage(__name__)
-from .internal import assert_subpackage # noqa: I001
-
-assert_subpackage(__name__)
+from pathlib import Path
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, Literal, Union, overload
+
from .common import PathIsh
-from .compat import assert_never
def sqlite_connect_immutable(db: PathIsh) -> sqlite3.Connection:
+ # https://www.sqlite.org/draft/uri.html#uriimmutable
return sqlite3.connect(f'file:{db}?immutable=1', uri=True)
@@ -25,8 +20,7 @@ def test_sqlite_connect_immutable(tmp_path: Path) -> None:
with sqlite3.connect(db) as conn:
conn.execute('CREATE TABLE testtable (col)')
- import pytest
-
+ import pytest # type: ignore
with pytest.raises(sqlite3.OperationalError, match='readonly database'):
with sqlite_connect_immutable(db) as conn:
conn.execute('DROP TABLE testtable')
@@ -36,46 +30,6 @@ def test_sqlite_connect_immutable(tmp_path: Path) -> None:
conn.execute('DROP TABLE testtable')
-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))
-
-
-Factory = Union[SqliteRowFactory, Literal['row', 'dict']]
-
-
-@contextmanager
-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:
- # assert results in nicer error than sqlite3.OperationalError
- assert Path(db).exists(), db
- dbp = f'{dbp}?immutable=1'
- row_factory_: Any = None
- if row_factory is not None:
- if callable(row_factory):
- row_factory_ = row_factory
- elif row_factory == 'row':
- row_factory_ = sqlite3.Row
- elif row_factory == 'dict':
- row_factory_ = dict_factory
- else:
- assert_never()
-
- conn = sqlite3.connect(dbp, uri=True)
- try:
- conn.row_factory = row_factory_
- with conn:
- yield conn
- finally:
- # Connection context manager isn't actually closing the connection, only keeps transaction
- conn.close()
-
-
# TODO come up with a better name?
# NOTE: this is tested by tests/sqlite.py::test_sqlite_read_with_wal
def sqlite_copy_and_open(db: PathIsh) -> sqlite3.Connection:
@@ -92,88 +46,6 @@ def sqlite_copy_and_open(db: PathIsh) -> sqlite3.Connection:
for p in tocopy:
shutil.copy(p, tdir / p.name)
with sqlite3.connect(str(tdir / dp.name)) as conn:
- conn.backup(target=dest)
- conn.close()
+ from .compat import sqlite_backup
+ sqlite_backup(source=conn, dest=dest)
return dest
-
-
-# NOTE hmm, so this kinda works
-# V = TypeVar('V', bound=Tuple[Any, ...])
-# def select(cols: V, rest: str, *, db: sqlite3.Connection) -> Iterator[V]:
-# but sadly when we pass columns (Tuple[str, ...]), it seems to bind this type to V?
-# 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 ]]: ...
-@overload
-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 ]]: ...
-@overload
-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 ]]: ...
-@overload
-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 ]]: ...
-@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]]: ...
-# fmt: on
-
-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/core/stats.py b/my/core/stats.py
index a553db3..9750061 100644
--- a/my/core/stats.py
+++ b/my/core/stats.py
@@ -1,219 +1,40 @@
'''
Helpers for hpi doctor/stats functionality.
'''
-
-from __future__ import annotations
-
-import collections.abc
+import collections
import importlib
import inspect
+import sys
import typing
-from collections.abc import Iterable, Iterator, Sequence
-from contextlib import contextmanager
-from datetime import datetime
-from pathlib import Path
-from types import ModuleType
-from typing import (
- Any,
- Callable,
- Protocol,
- cast,
-)
+from typing import Optional, Callable, Any, Iterator, Sequence, Dict
-from .types import asdict
-
-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: Callable[[], Iterable[Any]] | Iterable[Any],
- *,
- quick: bool = False,
- name: str | None = 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 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')
- 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(' StatsFun | None:
- stats: StatsFun | None = 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
+from .common import StatsFun, Stats, stat
# 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) -> 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
- """
- providers = _guess_data_providers(module)
+def guess_stats(module_name: str) -> Optional[StatsFun]:
+ providers = guess_data_providers(module_name)
if len(providers) == 0:
return None
-
- def auto_stats(*, quick: bool = False) -> Stats:
- res = {}
- for k, v in providers.items():
- res.update(stat(v, quick=quick, name=k))
- return res
-
+ def auto_stats() -> Stats:
+ return {k: stat(v) for k, v in providers.items()}
return auto_stats
-def test_guess_stats() -> None:
- import my.core.tests.auto_stats as M
-
- auto_stats = guess_stats(M)
- assert auto_stats is not None
- res = auto_stats(quick=False)
-
- assert res == {
- 'inputs': {
- 'count': 3,
- 'first': 'file1.json',
- 'last': 'file3.json',
- },
- 'iter_data': {
- 'count': 9,
- 'first': datetime(2020, 1, 1, 1, 1, 1),
- 'last': datetime(2020, 1, 3, 1, 1, 1),
- },
- }
-
-
-def _guess_data_providers(module: ModuleType) -> dict[str, Callable]:
+def guess_data_providers(module_name: str) -> Dict[str, Callable]:
+ module = importlib.import_module(module_name)
mfunctions = inspect.getmembers(module, inspect.isfunction)
return {k: v for k, v in mfunctions if is_data_provider(v)}
-# todo how to exclude deprecated data providers?
+# todo how to exclude deprecated stuff?
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?)
+ 4. functions isnt the 'inputs' function (or ends with '_inputs')
"""
# todo maybe for 2 allow default arguments? not sure
# one example which could benefit is my.pdfs
@@ -226,23 +47,19 @@ 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__'):
# probably a helper function?
if fun.__name__.startswith('_'):
return False
+ # ignore def inputs; something like comment_inputs or backup_inputs should also be ignored
+ if fun.__name__ == 'inputs' or fun.__name__.endswith('_inputs'):
+ return False
- # inspect.signature might return str instead of a proper type object
- # if from __future__ import annotations is used
- # so best to rely on get_type_hints (which evals the annotations)
- type_hints = typing.get_type_hints(fun)
- return_type = type_hints.get('return')
- if return_type is None:
- return False
-
- return _type_is_iterable(return_type)
+ return_type = sig.return_annotation
+ return type_is_iterable(return_type)
def test_is_data_provider() -> None:
@@ -252,43 +69,36 @@ def test_is_data_provider() -> None:
assert not idp("x")
def no_return_type():
- return [1, 2, 3]
-
+ return [1, 2 ,3]
assert not idp(no_return_type)
lam = lambda: [1, 2]
assert not idp(lam)
- def has_extra_args(count) -> list[int]:
+ def has_extra_args(count) -> typing.List[int]:
return list(range(count))
-
assert not idp(has_extra_args)
- def has_return_type() -> Sequence[str]:
+ def has_return_type() -> typing.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)
+ assert not idp(inputs)
def producer_inputs() -> Iterator[Any]:
yield 1
-
- assert idp(producer_inputs)
+ assert not idp(producer_inputs)
-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
- """
+
+# 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]:
for param in sig.parameters.values():
if param.default == inspect.Parameter.empty:
yield param
@@ -298,24 +108,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:
+ if sys.version_info[1] < 8:
+ # there is no get_origin before 3.8, and retrofitting gonna be a lot of pain
+ return any(x in str(type_spec) for x in ['List', 'Sequence', 'Iterable', 'Iterator'])
origin = typing.get_origin(type_spec)
if origin is None:
return False
@@ -332,139 +142,14 @@ def _type_is_iterable(type_spec) -> bool:
# todo docstring test?
def test_type_is_iterable() -> None:
- fun = _type_is_iterable
+ from typing import List, Sequence, Iterable, Dict, Any
+
+ fun = type_is_iterable
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])
-
-
-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 first, ilen, take
-
- # 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)
-
- class X(NamedTuple):
- 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) -> datetime | None:
- # todo hmm implement without exception..
- try:
- d = asdict(x)
- except: # noqa: E722 bare except
- return None
- for v in d.values():
- 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')
-
- 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
-
- @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/structure.py b/my/core/structure.py
index bb049e4..88b75b8 100644
--- a/my/core/structure.py
+++ b/my/core/structure.py
@@ -1,22 +1,20 @@
-from __future__ import annotations
-
-import atexit
import os
import shutil
-import sys
-import tarfile
import tempfile
import zipfile
-from collections.abc import Generator, Sequence
+import atexit
+
+from typing import Sequence, Generator, List, Union, Tuple
from contextlib import contextmanager
from pathlib import Path
-from .logging import make_logger
-
-logger = make_logger(__name__, level="info")
+from .common import LazyLogger
-def _structure_exists(base_dir: Path, paths: Sequence[str], *, partial: bool = False) -> bool:
+logger = LazyLogger(__name__, level="info")
+
+
+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
@@ -38,18 +36,17 @@ def _structure_exists(base_dir: Path, paths: Sequence[str], *, partial: bool = F
ZIP_EXT = {".zip"}
-TARGZ_EXT = {".tar.gz"}
@contextmanager
def match_structure(
base: Path,
- expected: str | Sequence[str],
+ expected: Union[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
+ Given a 'base' directory or zipfile, 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.
@@ -57,12 +54,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 archived the folders instead of the parent directory or vice-versa
+ if they zipped 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 an archive, this extracts it into a temporary directory
+ If base is a zipfile, this extracts the zipfile into a temporary directory
(configured by core_config.config.get_tmp_dir), and then searches the extracted
folder for matching structures
@@ -72,21 +69,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
@@ -98,12 +95,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 decompress archives in the subdirectories,
- it only unpacks into a temporary directory if 'base' is an archive
+ This does not recursively unzip zipfiles in the subdirectories,
+ it only unzips into a temporary directory if 'base' is a zipfile
A common pattern for using this might be to use get_files to get a list
- of archives or top-level gdpr export directories, and use match_structure
- to search the resulting paths for an export structure you're expecting
+ of zipfiles or top-level gdpr export directories, and use match_structure
+ to search the resulting paths for a export structure you're expecting
"""
from . import core_config as CC
@@ -113,37 +110,28 @@ 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 an archive, create a temporary
- # directory and extract it to that temporary directory
+ # if the file given by the user is a zipfile, create a temporary
+ # directory and extract the zipfile to that temporary directory
#
# this temporary directory is removed in the finally block
- if is_zip or is_targz:
+ if is_zip:
# sanity check before we start creating directories/rm-tree'ing things
- assert base.exists(), f"archive at {base} doesn't exist"
+ assert base.exists(), f"zipfile at {base} doesn't exist"
searchdir = Path(tempfile.mkdtemp(dir=tdir))
- 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")
+ zf = zipfile.ZipFile(base)
+ zf.extractall(path=str(searchdir))
+
else:
if not searchdir.is_dir():
- raise NotADirectoryError(f"Expected either a zip/tar.gz archive or a directory, received {searchdir}")
+ raise NotADirectoryError(f"Expected either a zipfile 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)
@@ -163,9 +151,9 @@ def match_structure(
finally:
- if is_zip or is_targz:
+ if is_zip:
# make sure we're not mistakenly deleting data
- assert str(searchdir).startswith(str(tdir)), f"Expected the temporary directory for extracting archive to start with the temporary directory prefix ({tdir}), found {searchdir}"
+ assert str(searchdir).startswith(str(tdir)), f"Expected the temporary directory for extracting zip to start with the temporary directory prefix ({tdir}), found {searchdir}"
shutil.rmtree(str(searchdir))
@@ -174,7 +162,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/__init__.py b/my/core/tests/__init__.py
deleted file mode 100644
index 9d38c26..0000000
--- a/my/core/tests/__init__.py
+++ /dev/null
@@ -1,3 +0,0 @@
-# hmm, sadly pytest --import-mode importlib --pyargs my.core.tests doesn't work properly without __init__.py
-# although it works if you run either my.core or my.core.tests.sqlite (for example) directly
-# so if it gets in the way could get rid of this later?
diff --git a/my/core/tests/auto_stats.py b/my/core/tests/auto_stats.py
deleted file mode 100644
index fc49e03..0000000
--- a/my/core/tests/auto_stats.py
+++ /dev/null
@@ -1,37 +0,0 @@
-"""
-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
-
-
-@dataclass
-class Item:
- id: str
- dt: datetime
- source: Path
-
-
-def inputs() -> Sequence[Path]:
- return [
- Path('file1.json'),
- Path('file2.json'),
- Path('file3.json'),
- ]
-
-
-def iter_data() -> Iterable[Item]:
- dt = datetime.fromisoformat('2020-01-01 01:01:01')
- for path in inputs():
- for i in range(3):
- yield Item(id=str(i), dt=dt + timedelta(days=i), source=path)
-
-
-@contextmanager
-def some_contextmanager() -> Iterator[str]:
- # this shouldn't end up in guess_stats because context manager is not a data provider
- yield 'hello'
diff --git a/my/core/tests/common.py b/my/core/tests/common.py
deleted file mode 100644
index 073ea5f..0000000
--- a/my/core/tests/common.py
+++ /dev/null
@@ -1,32 +0,0 @@
-from __future__ import annotations
-
-import os
-from collections.abc import Iterator
-from contextlib import contextmanager
-
-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.',
-)
-
-
-# TODO maybe move to hpi core?
-@contextmanager
-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)
- 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/tests/denylist.py b/my/core/tests/denylist.py
deleted file mode 100644
index 73c3165..0000000
--- a/my/core/tests/denylist.py
+++ /dev/null
@@ -1,104 +0,0 @@
-import json
-import warnings
-from collections.abc import Iterator
-from datetime import datetime
-from pathlib import Path
-from typing import NamedTuple
-
-from ..denylist import DenyList
-
-
-class IP(NamedTuple):
- addr: str
- dt: datetime
-
-
-def data() -> Iterator[IP]:
- # random IP addresses
- yield IP(addr="67.98.113.0", dt=datetime(2020, 1, 1))
- yield IP(addr="59.40.113.87", dt=datetime(2020, 2, 1))
- yield IP(addr="161.235.192.228", dt=datetime(2020, 3, 1))
- yield IP(addr="165.243.139.87", dt=datetime(2020, 4, 1))
- yield IP(addr="69.69.141.154", dt=datetime(2020, 5, 1))
- yield IP(addr="50.72.224.80", dt=datetime(2020, 6, 1))
- yield IP(addr="221.67.89.168", dt=datetime(2020, 7, 1))
- yield IP(addr="177.113.119.251", dt=datetime(2020, 8, 1))
- yield IP(addr="93.200.246.215", dt=datetime(2020, 9, 1))
- yield IP(addr="127.105.171.61", dt=datetime(2020, 10, 1))
-
-
-def test_denylist(tmp_path: Path) -> None:
- tf = (tmp_path / "denylist.json").absolute()
- with warnings.catch_warnings(record=True):
- # create empty denylist (though file does not have to exist for denylist to work)
- tf.write_text("[]")
-
- d = DenyList(tf)
-
- d.load()
- assert dict(d._deny_map) == {}
- assert d._deny_raw_list == []
-
- assert list(d.filter(data())) == list(data())
- # no data in denylist yet
- assert len(d._deny_map) == 0
- assert len(d._deny_raw_list) == 0
-
- # add some data
- d.deny(key="addr", value="67.98.113.0")
- # write and reload to update _deny_map, _deny_raw_list
- d.write()
- d.load()
-
- assert len(d._deny_map) == 1
- assert len(d._deny_raw_list) == 1
-
- assert d._deny_raw_list == [{"addr": "67.98.113.0"}]
-
- filtered = list(d.filter(data()))
- assert len(filtered) == 9
- assert "67.98.113.0" not in [i.addr for i in filtered]
-
- assert dict(d._deny_map) == {"addr": {"67.98.113.0"}}
-
- denied = list(d.filter(data(), invert=True))
- assert len(denied) == 1
-
- assert denied[0] == IP(addr="67.98.113.0", dt=datetime(2020, 1, 1))
-
- # add some non-JSON primitive data
-
- d.deny(key="dt", value=datetime(2020, 2, 1))
-
- # test internal behavior, _deny_raw_list should have been updated,
- # but _deny_map doesn't get updated by a call to .deny
- #
- # if we change this just update the test, is just here to ensure
- # this is the behaviour
-
- assert len(d._deny_map) == 1
-
- # write and load to update _deny_map
- d.write()
- d.load()
-
- assert len(d._deny_map) == 2
- assert len(d._deny_raw_list) == 2
-
- assert d._deny_raw_list[-1] == {"dt": "2020-02-01T00:00:00"}
-
- filtered = list(d.filter(data()))
- assert len(filtered) == 8
-
- assert "59.40.113.87" not in [i.addr for i in filtered]
-
- data_json = json.loads(tf.read_text())
-
- assert data_json == [
- {
- "addr": "67.98.113.0",
- },
- {
- "dt": "2020-02-01T00:00:00",
- },
- ]
diff --git a/my/core/tests/structure_data/gdpr_export.tar.gz b/my/core/tests/structure_data/gdpr_export.tar.gz
deleted file mode 100644
index 4f0597c..0000000
Binary files a/my/core/tests/structure_data/gdpr_export.tar.gz and /dev/null differ
diff --git a/my/core/tests/structure_data/gdpr_subdirs/broken_export/comments/comments.json b/my/core/tests/structure_data/gdpr_subdirs/broken_export/comments/comments.json
deleted file mode 100644
index 0967ef4..0000000
--- a/my/core/tests/structure_data/gdpr_subdirs/broken_export/comments/comments.json
+++ /dev/null
@@ -1 +0,0 @@
-{}
diff --git a/my/core/tests/structure_data/gdpr_subdirs/gdpr_export/comments/comments.json b/my/core/tests/structure_data/gdpr_subdirs/gdpr_export/comments/comments.json
deleted file mode 100644
index 0967ef4..0000000
--- a/my/core/tests/structure_data/gdpr_subdirs/gdpr_export/comments/comments.json
+++ /dev/null
@@ -1 +0,0 @@
-{}
diff --git a/my/core/tests/structure_data/gdpr_subdirs/gdpr_export/profile/settings.json b/my/core/tests/structure_data/gdpr_subdirs/gdpr_export/profile/settings.json
deleted file mode 100644
index 0967ef4..0000000
--- a/my/core/tests/structure_data/gdpr_subdirs/gdpr_export/profile/settings.json
+++ /dev/null
@@ -1 +0,0 @@
-{}
diff --git a/my/core/tests/test_cachew.py b/my/core/tests/test_cachew.py
deleted file mode 100644
index a0d2267..0000000
--- a/my/core/tests/test_cachew.py
+++ /dev/null
@@ -1,52 +0,0 @@
-from __future__ import annotations
-
-from .common import skip_if_uses_optional_deps as pytestmark
-
-# 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.cachew 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, 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_cli.py b/my/core/tests/test_cli.py
deleted file mode 100644
index 1838e84..0000000
--- a/my/core/tests/test_cli.py
+++ /dev/null
@@ -1,16 +0,0 @@
-import os
-import sys
-from subprocess import check_call
-
-
-def test_lists_modules() -> None:
- # hack PYTHONUTF8 for windows
- # see https://github.com/karlicoss/promnesia/issues/274
- # https://memex.zulipchat.com/#narrow/stream/279600-promnesia/topic/indexing.3A.20utf8.28emoji.29.20filenames.20in.20Windows
- # necessary for this test cause emooji is causing trouble
- # TODO need to fix it properly
- env = {
- **os.environ,
- 'PYTHONUTF8': '1',
- }
- check_call([sys.executable, '-m', 'my.core', 'modules'], env=env)
diff --git a/my/core/tests/test_config.py b/my/core/tests/test_config.py
deleted file mode 100644
index f6d12ba..0000000
--- a/my/core/tests/test_config.py
+++ /dev/null
@@ -1,178 +0,0 @@
-"""
-Various tests that are checking behaviour of user config wrt to various things
-"""
-
-import os
-import sys
-from pathlib import Path
-
-import pytest
-import pytz
-
-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'])
-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.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(
- '''
-[
- {"key": 1, "value": 123},
- {"key": 2, "value": 456}
-]
-'''
- )
diff --git a/my/core/tests/test_tmp_config.py b/my/core/tests/test_tmp_config.py
deleted file mode 100644
index d99621d..0000000
--- a/my/core/tests/test_tmp_config.py
+++ /dev/null
@@ -1,29 +0,0 @@
-from ..cfg import tmp_config
-
-
-def _init_default_config() -> None:
- import my.config
-
- class default_config:
- count = 5
-
- my.config.simple = default_config # type: ignore[assignment,misc]
-
-
-def test_tmp_config() -> None:
- ## ugh. ideally this would be on the top level (would be a better test)
- ## 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
-
- assert len(list(items())) == 5
-
- class config:
- class simple:
- count = 3
-
- with tmp_config(modules='my.simple', config=config):
- assert len(list(items())) == 3
-
- assert len(list(items())) == 5
diff --git a/my/core/time.py b/my/core/time.py
index a9b180d..b55fae3 100644
--- a/my/core/time.py
+++ b/my/core/time.py
@@ -1,11 +1,8 @@
-from __future__ import annotations
+from functools import lru_cache
+from datetime import tzinfo
+from typing import Sequence
-from collections.abc import Sequence
-from functools import cache, lru_cache
-
-import pytz
-
-from .types import datetime_aware, datetime_naive
+import pytz # type: ignore
def user_forced() -> Sequence[str]:
@@ -13,24 +10,22 @@ 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
+ return user_config.tz.force_abbreviations # type: ignore[attr-defined]
except:
# todo log/apply policy
return []
@lru_cache(1)
-def _abbr_to_timezone_map() -> dict[str, pytz.BaseTzInfo]:
+def _abbr_to_timezone_map():
# 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()]
+ timezones = pytz.all_timezones + ['UTC'] + list(user_forced())
- res: dict[str, pytz.BaseTzInfo] = {}
+ res = {}
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?
@@ -46,23 +41,12 @@ def _abbr_to_timezone_map() -> dict[str, pytz.BaseTzInfo]:
return res
-@cache
-def abbr_to_timezone(abbr: str) -> pytz.BaseTzInfo:
+# todo dammit, lru_cache interferes with mypy?
+@lru_cache(None)
+def abbr_to_timezone(abbr: str) -> tzinfo:
return _abbr_to_timezone_map()[abbr]
-def localize_with_abbr(dt: datetime_naive, *, abbr: str) -> datetime_aware:
- if abbr.lower() == 'utc':
- # best to shortcut here to avoid complications
- return pytz.utc.localize(dt)
-
- tz = abbr_to_timezone(abbr)
- # this will compute the correct UTC offset
- tzinfo = tz.localize(dt).tzinfo
- assert tzinfo is not None # make mypy happy
- return tz.normalize(dt.replace(tzinfo=tzinfo))
-
-
def zone_to_countrycode(zone: str) -> str:
# todo make optional?
return _zones_to_countrycode()[zone]
diff --git a/my/core/types.py b/my/core/types.py
deleted file mode 100644
index dc19c19..0000000
--- a/my/core/types.py
+++ /dev/null
@@ -1,37 +0,0 @@
-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
-
-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/core/util.py b/my/core/util.py
index 74e71e1..222cdec 100644
--- a/my/core/util.py
+++ b/my/core/util.py
@@ -1,35 +1,41 @@
-from __future__ import annotations
-
+from pathlib import Path
+from itertools import chain
+from importlib import import_module
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 List, Iterable, Optional
-from .discovery_pure import HPIModule, _is_not_module_src, has_stats, ignored
+from .discovery_pure import HPIModule, ignored, _is_not_module_src, has_stats
def modules() -> Iterable[HPIModule]:
import my
+ for m in _iter_all_importables(my):
+ yield m
- yield from _iter_all_importables(my)
+
+from .common import StatsFun
+def get_stats(module: str) -> Optional[StatsFun]:
+ # todo detect via ast?
+ try:
+ mod = import_module(module)
+ except Exception as e:
+ 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
-
-def is_not_hpi_module(module: str) -> str | None:
+def is_not_hpi_module(module: str) -> Optional[str]:
'''
None if a module, otherwise returns reason
'''
- import importlib.util
-
- path: str | None = None
+ import importlib
+ path: Optional[str] = None
try:
# TODO annoying, this can cause import of the parent module?
spec = importlib.util.find_spec(module)
@@ -38,7 +44,7 @@ def is_not_hpi_module(module: str) -> str | None:
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})"
@@ -47,6 +53,7 @@ def is_not_hpi_module(module: str) -> str | None:
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]:
@@ -55,15 +62,14 @@ def _iter_all_importables(pkg: ModuleType) -> Iterable[HPIModule]:
_discover_path_importables(Path(p), pkg.__name__)
# todo might need to handle __path__ for individual modules too?
# not sure why __path__ was duplicated, but it did happen..
- for p in set(pkg.__path__)
+ for p in set(pkg.__path__) # type: ignore[attr-defined]
)
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
@@ -78,7 +84,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}.',
@@ -86,7 +92,6 @@ 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
@@ -95,17 +100,17 @@ 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
+ to alvoid importing modules that are skipped
"""
from .core_config import config
- def seen(p, m={}): # noqa: B006
+ def seen(p, m={}):
if p in m:
return True
- m[p] = True # noqa: RET503
+ m[p] = True
for info in pkgutil.iter_modules(path, prefix):
mname = info.name
@@ -156,11 +161,10 @@ def _walk_packages(path: Iterable[str], prefix: str = '', onerror=None) -> Itera
path = getattr(sys.modules[mname], '__path__', None) or []
# don't traverse path items we've seen before
path = [p for p in path if not seen(p)]
- yield from _walk_packages(path, mname + '.', onerror)
-
+ yield from _walk_packages(path, mname+'.', onerror)
# deprecate?
-def get_modules() -> list[HPIModule]:
+def get_modules() -> List[HPIModule]:
return list(modules())
@@ -175,14 +179,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"
@@ -200,7 +204,6 @@ from my.core import __NOT_HPI_MODULE__
''')
import sys
-
orig_path = list(sys.path)
try:
sys.path.insert(0, str(badp))
@@ -226,16 +229,15 @@ def test_bad_modules(tmp_path: Path) -> None:
(par / 'malicious.py').write_text(f'''
from pathlib import Path
-Path(r'{xx}').write_text('aaand your data is gone!')
+Path('{xx}').write_text('aaand your data is gone!')
-raise RuntimeError("FAIL ON IMPORT! naughty.")
+raise RuntimeError("FAIL ON IMPORT! naughy.")
def stats():
return [1, 2, 3]
''')
import sys
-
orig_path = list(sys.path)
try:
sys.path.insert(0, str(badp))
@@ -244,7 +246,7 @@ def stats():
sys.path = orig_path
# shouldn't crash at least
assert res is None # good as far as discovery is concerned
- assert xx.read_text() == 'some precious data' # make sure module wasn't evaluated
+ assert xx.read_text() == 'some precious data' # make sure module wasn't evauluated
### tests end
diff --git a/my/core/utils/concurrent.py b/my/core/utils/concurrent.py
deleted file mode 100644
index 515c3f1..0000000
--- a/my/core/utils/concurrent.py
+++ /dev/null
@@ -1,40 +0,0 @@
-from __future__ import annotations
-
-from concurrent.futures import Executor, Future
-from typing import Any, Callable, TypeVar
-
-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: int | None = 1) -> None:
- self._shutdown = False
- self._max_workers = max_workers
-
- 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)
-
- return f
-
- def shutdown(self, wait: bool = True, **kwargs) -> None: # noqa: FBT001,FBT002,ARG002
- self._shutdown = True
diff --git a/my/core/utils/imports.py b/my/core/utils/imports.py
deleted file mode 100644
index e0fb01d..0000000
--- a/my/core/utils/imports.py
+++ /dev/null
@@ -1,37 +0,0 @@
-from __future__ import annotations
-
-import importlib
-import importlib.util
-import sys
-from pathlib import Path
-from types import ModuleType
-
-
-# TODO only used in tests? not sure if useful at all.
-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.exec_module(foo)
- return foo
-
-
-def import_from(path: Path | str, 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: Path | str, 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
deleted file mode 100644
index 42b2b77..0000000
--- a/my/core/utils/itertools.py
+++ /dev/null
@@ -1,369 +0,0 @@
-"""
-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, Iterable, Iterator, Sized
-from typing import (
- TYPE_CHECKING,
- Callable,
- TypeVar,
- Union,
- cast,
-)
-
-import more_itertools
-from decorator import decorator
-
-from .. import warnings as core_warnings
-from ..compat import ParamSpec
-
-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 _: 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)
-
-
-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]]: ... # noqa: ARG001
-
-else:
- listify = _listify
-
-
-def test_listify() -> None:
- from ..compat import assert_type
-
- @listify
- def it() -> Iterator[int]:
- yield 1
- yield 2
-
- 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:
- core_warnings.medium(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:
- core_warnings.medium(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(func: FF) -> FF: ... # noqa: ARG001
-
-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 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 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
-
-
-_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
-
- import pytest
-
- from ..compat import assert_type
-
- x1: list[int] = [1, 2]
- r1 = check_if_hashable(x1)
- assert_type(r1, Iterable[int])
- assert r1 is x1
-
- 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')
- 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}]
- 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 returns iterator
-# instead of just iterator
-# TODO maybe deprecated Callable support? not sure
-def unique_everseen(
- fun: Callable[[], Iterable[_UET]] | Iterable[_UET],
- key: Callable[[_UET], _UEU] | None = 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 returns 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}]
diff --git a/my/core/warnings.py b/my/core/warnings.py
index d67ec7d..9446fc0 100644
--- a/my/core/warnings.py
+++ b/my/core/warnings.py
@@ -5,20 +5,21 @@ 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
+from typing import Optional
import warnings
-from typing import TYPE_CHECKING
import click
-def _colorize(x: str, color: str | None = None) -> str:
+# just bring in the scope of this module for convenience
+from warnings import warn
+
+def _colorize(x: str, color: Optional[str]=None) -> str:
if color is None:
return x
- if not sys.stderr.isatty():
+ if not sys.stdout.isatty():
return x
# click handles importing/initializing colorama if necessary
# on windows it installs it if necessary
@@ -26,10 +27,10 @@ def _colorize(x: str, color: str | None = None) -> str:
return click.style(x, fg=color)
-def _warn(message: str, *args, color: str | None = 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) # noqa: B028
+ kwargs['stacklevel'] = stacklevel + 2 # +1 for this function, +1 for medium/high wrapper
+ warnings.warn(_colorize(message, color=color), *args, **kwargs)
def low(message: str, *args, **kwargs) -> None:
@@ -48,13 +49,3 @@ def high(message: str, *args, **kwargs) -> None:
'''
kwargs['color'] = 'red'
_warn(message, *args, **kwargs)
-
-
-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) # noqa: B028
diff --git a/my/demo.py b/my/demo.py
index fa80b2a..3a9d1b3 100644
--- a/my/demo.py
+++ b/my/demo.py
@@ -1,77 +1,70 @@
'''
Just a demo module for testing and documentation purposes
'''
-from __future__ import annotations
-import json
-from collections.abc import Iterable, Sequence
+from .core import Paths, PathIsh
+
+from typing import Optional
+from datetime import tzinfo
+import pytz
+
+from my.config import demo as user_config
from dataclasses import dataclass
-from datetime import datetime, timezone, tzinfo
-from pathlib import Path
-from typing import Protocol
-
-from my.core import Json, PathIsh, Paths, get_files
-class config(Protocol):
+@dataclass
+class demo(user_config):
data_path: Paths
-
- # this is to check required attribute handling
username: str
+ timezone: tzinfo = pytz.utc
- # this is to check optional attribute handling
- timezone: tzinfo = timezone.utc
-
- external: PathIsh | None = None
+ external: Optional[PathIsh] = None
@property
def external_module(self):
rpath = self.external
if rpath is not None:
- from my.core.utils.imports import import_dir
-
+ from .core.common 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
-def make_config() -> config:
- from my.config import demo as user_config
+from .core import make_config
+config = make_config(demo)
- class combined_config(user_config, config): ...
+# TODO not sure about type checking?
+external = config.external_module
- 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
+ Some completely arbirary artificial stuff, just for testing
'''
-
username: str
raw: Json
dt: datetime
def inputs() -> Sequence[Path]:
- cfg = make_config()
- return get_files(cfg.data_path)
+ return get_files(config.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=cfg.timezone)
+ dt = datetime.fromtimestamp(f.stat().st_mtime, tz=config.timezone)
j = json.loads(f.read_text())
for raw in j:
yield Item(
- username=cfg.username,
- raw=transform(raw),
+ username=config.username,
+ raw=external.identity(raw),
dt=dt,
)
diff --git a/my/emfit/__init__.py b/my/emfit/__init__.py
old mode 100644
new mode 100755
index 0d50b06..3ad2b15
--- a/my/emfit/__init__.py
+++ b/my/emfit/__init__.py
@@ -1,39 +1,25 @@
+#!/usr/bin/env python3
"""
[[https://shop-eu.emfit.com/products/emfit-qs][Emfit QS]] sleep tracker
Consumes data exported by https://github.com/karlicoss/emfitexport
"""
-
-from __future__ import annotations
-
-REQUIRES = [
- 'git+https://github.com/karlicoss/emfitexport',
-]
-
-import dataclasses
-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
+from typing import Dict, List, Iterable, Any, Optional
+
+from ..core import get_files
+from ..core.common import mcachew
+from ..core.cachew import cache_dir
+from ..core.error import Res, set_error_datetime, extract_error_datetime
+from ..core.pandas import DataFrameT
+
+from my.config import emfit as config
+
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
+# todo ugh. need to make up my mind on log vs logger naming... I guessl ogger makes more sense
+logger = dal.log
+Emfit = dal.Emfit
# TODO move to common?
@@ -42,29 +28,16 @@ def dir_hash(path: Path):
return mtimes
-def _cachew_depends_on():
- return dir_hash(config.export_path)
-
-
# TODO take __file__ into account somehow?
-@mcachew(cache_path=cache_dir() / 'emfit.cache', depends_on=_cachew_depends_on)
+@mcachew(cache_path=cache_dir() / 'emfit.cache', hashf=lambda: dir_hash(config.export_path), logger=dal.log)
def datas() -> Iterable[Res[Emfit]]:
+ import dataclasses
+
# data from emfit is coming in UTC. There is no way (I think?) to know the 'real' timezone, and local times matter more for sleep analysis
- # TODO actually this is wrong?? there is some sort of local offset in the export
+ # TODO actully this is wrong?? check this..
emfit_tz = config.timezone
- ## backwards compatibility (old DAL didn't have cpu_pool argument)
- cpu_pool_arg = 'cpu_pool'
- pass_cpu_pool = cpu_pool_arg in inspect.signature(dal.sleeps).parameters
- if pass_cpu_pool:
- from my.core._cpu_pool import get_cpu_pool
-
- kwargs = {cpu_pool_arg: get_cpu_pool()}
- else:
- kwargs = {}
- ##
-
- for x in dal.sleeps(config.export_path, **kwargs):
+ for x in dal.sleeps(config.export_path):
if isinstance(x, Exception):
yield x
else:
@@ -73,7 +46,6 @@ def datas() -> Iterable[Res[Emfit]]:
continue
# TODO maybe have a helper to 'patch up' all dattetimes in a namedtuple/dataclass?
# TODO do the same for jawbone data?
- # fmt: off
x = dataclasses.replace(
x,
start =x.start .astimezone(emfit_tz),
@@ -81,14 +53,13 @@ def datas() -> Iterable[Res[Emfit]]:
sleep_start=x.sleep_start.astimezone(emfit_tz),
sleep_end =x.sleep_end .astimezone(emfit_tz),
)
- # fmt: on
yield x
# 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:
@@ -99,7 +70,7 @@ def pre_dataframe() -> Iterable[Res[Emfit]]:
yield r
else:
err = RuntimeError(f'Multiple sleeps per night, not supported yet: {g}')
- set_error_datetime(err, dt=datetime.combine(g[0].date, time.min))
+ set_error_datetime(err, dt=g[0].date)
g.clear()
yield err
@@ -115,14 +86,15 @@ def pre_dataframe() -> Iterable[Res[Emfit]]:
def dataframe() -> DataFrameT:
- dicts: list[dict[str, Any]] = []
- last: Emfit | None = None
+ from datetime import timedelta
+ dicts: List[Dict[str, Any]] = []
+ last: Optional[Emfit] = None
for s in pre_dataframe():
- d: dict[str, Any]
+ d: Dict[str, Any]
if isinstance(s, Exception):
edt = extract_error_datetime(s)
d = {
- 'date': edt,
+ 'date' : edt,
'error': str(s),
}
else:
@@ -137,7 +109,6 @@ def dataframe() -> DataFrameT:
# todo ugh. get rid of hardcoding, just generate the schema automatically
# TODO use 'workdays' provider....
- # fmt: off
d = {
'date' : dd,
@@ -154,46 +125,36 @@ def dataframe() -> DataFrameT:
'hrv_change' : hrv_change,
'respiratory_rate_avg': s.respiratory_rate_avg,
}
- # fmt: on
- last = s # meh
+ last = s # meh
dicts.append(d)
- import pandas as pd
- return pd.DataFrame(dicts)
+ import pandas # type: ignore
+ return pandas.DataFrame(dicts)
+from ..core import stat, Stats
def stats() -> Stats:
return stat(pre_dataframe)
+from contextlib import contextmanager
+from typing import Iterator
@contextmanager
-def fake_data(nights: int = 500) -> Iterator:
+def fake_data(nights: int=500) -> Iterator[None]:
+ from ..core.cfg import override_config
from tempfile import TemporaryDirectory
-
- import pytz
-
- from my.core.cfg import tmp_config
-
- with TemporaryDirectory() as td:
+ with override_config(config) as cfg, TemporaryDirectory() as td:
tdir = Path(td)
+ cfg.export_path = tdir
+
gen = dal.FakeData()
gen.fill(tdir, count=nights)
-
- 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
+ yield
# 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
-
-
+ return list(sorted(datas(), key=lambda e: e.start)) # type: ignore
# TODO move away old entries if there is a diff??
diff --git a/my/emfit/plot.py b/my/emfit/plot.py
old mode 100644
new mode 100755
diff --git a/my/endomondo.py b/my/endomondo.py
index 7732c00..0df7aa9 100644
--- a/my/endomondo.py
+++ b/my/endomondo.py
@@ -7,14 +7,13 @@ 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 my.config import endomondo as user_config
+from typing import Sequence, Iterable
from .core import Paths, get_files
+from my.config import endomondo as user_config
@dataclass
class endomondo(user_config):
@@ -32,22 +31,20 @@ def inputs() -> Sequence[Path]:
# todo add a doctor check for pip endoexport module
import endoexport.dal as dal
-from endoexport.dal import Point, Workout # noqa: F401
+from endoexport.dal import Point, Workout
+
from .core import Res
-
-
# todo cachew?
def workouts() -> Iterable[Res[Workout]]:
_dal = dal.DAL(inputs())
yield from _dal.workouts()
-from .core.pandas import DataFrameT, check_dataframe
-
+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):
@@ -69,7 +66,7 @@ def dataframe(*, defensive: bool=True) -> DataFrameT:
# todo check for 'defensive'
d = {'error': f'{e} {w}'}
yield d
- import pandas as pd
+ import pandas as pd # type: ignore
df = pd.DataFrame(it())
# pandas guesses integer, which is pointless for this field (might get coerced to float too)
df['id'] = df['id'].astype(str)
@@ -78,9 +75,7 @@ def dataframe(*, defensive: bool=True) -> DataFrameT:
return df
-from .core import Stats, stat
-
-
+from .core import stat, Stats
def stats() -> Stats:
return {
# todo pretty print stats?
@@ -91,28 +86,21 @@ def stats() -> Stats:
# TODO make sure it's possible to 'advise' functions and override stuff
-from collections.abc import Iterator
from contextlib import contextmanager
-
-
@contextmanager
-def fake_data(count: int=100) -> Iterator:
- import json
+def fake_data(count: int=100):
+ from .core.cfg import override_config
from tempfile import TemporaryDirectory
-
- from my.core.cfg import tmp_config
- with TemporaryDirectory() as td:
+ import json
+ with override_config(endomondo) as cfg, TemporaryDirectory() as td:
tdir = Path(td)
+ cfg.export_path = tdir
+
+ # todo would be nice to somehow expose the generator so it's possible to hack from the outside?
fd = dal.FakeData()
data = fd.generate(count=count)
jf = tdir / 'data.json'
jf.write_text(json.dumps(data))
- class override:
- class endomondo:
- export_path = tdir
-
- with tmp_config(modules=__name__, config=override) as cfg:
- # todo would be nice to somehow expose the generator so it's possible to hack from the outside?
- yield cfg
+ yield
diff --git a/my/error.py b/my/error.py
index e3c1e11..c0b734c 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
deleted file mode 100644
index 0c4092a..0000000
--- a/my/experimental/destructive_parsing.py
+++ /dev/null
@@ -1,60 +0,0 @@
-from collections.abc import Iterator
-from dataclasses import dataclass
-from typing import Any
-
-from my.core.compat import NoneType, assert_never
-
-
-# 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) # noqa: RET503
-
-
-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/fbmessenger/__init__.py b/my/fbmessenger/__init__.py
index e5e417c..910d7a6 100644
--- a/my/fbmessenger/__init__.py
+++ b/my/fbmessenger/__init__.py
@@ -4,30 +4,52 @@ It should be removed in the future, and you should replace any imports
like:
from my.fbmessenger import ...
to:
-from my.fbmessenger.all import ...
+from my.fbmessenger.export import ...
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.
+https://github.com/karlicoss/HPI/issues/102
"""
+# TODO ^^ later, replace the above with from my.fbmessenger.all, when we add more data sources
-# prevent it from appearing in modules list/doctor
-from ..core import __NOT_HPI_MODULE__
+import re
+import inspect
-# kinda annoying to keep it, but it's so legacy 'hpi module install my.fbmessenger' works
-# needs to be on the top level (since it's extracted via ast module)
+
+mname = __name__.split('.')[-1]
+
+# allow stuff like 'import my.module.submodule' and such
+imported_as_parent = False
+
+# allow stuff like 'from my.module import submodule'
+importing_submodule = False
+
+# some hacky traceback to inspect the current stack
+# to see if the user is using the old style of importing
+for f in inspect.stack():
+ # seems that when a submodule is imported, at some point it'll call some internal import machinery
+ # with 'parent' set to the parent module
+ # if parent module is imported first (i.e. in case of deprecated usage), it won't be the case
+ args = inspect.getargvalues(f.frame)
+ if args.locals.get('parent') == f'my.{mname}':
+ imported_as_parent = True
+
+ # this we can only detect from the code I guess
+ line = '\n'.join(f.code_context or [])
+ if re.match(rf'from\s+my\.{mname}\s+import\s+export', line):
+ # todo 'export' is hardcoded, not sure how to infer allowed objects anutomatically..
+ importing_submodule = True
+
+legacy = not (imported_as_parent or importing_submodule)
+
+if legacy:
+ from my.core import warnings as W
+ # TODO: add link to instructions to migrate
+ W.high("DEPRECATED! Instead of my.fbmessengerexport, import from my.fbmessengerexport.export")
+ # only import in legacy mode
+ # otherswise might have unfortunate side effects (e.g. missing imports)
+ from .export import *
+
+# kinda annoying to keep it, but it's so legacy 'hpi module install my.fbmessenger' work
+# needs to be on the top level (since it's extracted via ast module), but hopefully it doesn't hurt here
REQUIRES = [
'git+https://github.com/karlicoss/fbmessengerexport',
]
-
-
-from my.core.hpi_compat import handle_legacy_import
-
-is_legacy_import = handle_legacy_import(
- parent_module_name=__name__,
- legacy_submodule_name='export',
- parent_module_path=__path__,
-)
-
-if is_legacy_import:
- # todo not sure if possible to move this into legacy.py
- from .export import *
-
diff --git a/my/fbmessenger/all.py b/my/fbmessenger/all.py
index a057dca..ca7f064 100644
--- a/my/fbmessenger/all.py
+++ b/my/fbmessenger/all.py
@@ -1,12 +1,13 @@
-from collections.abc import Iterator
-
-from my.core import Res, Stats
+from typing import Iterator
+from my.core import Res
+from my.core.common import 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')
+
+src_export = import_source(module_name=f'my.fbmessenger.export')
+src_android = import_source(module_name=f'my.fbmessenger.android')
@src_export
diff --git a/my/fbmessenger/android.py b/my/fbmessenger/android.py
index f6fdb82..a7ed9d6 100644
--- a/my/fbmessenger/android.py
+++ b/my/fbmessenger/android.py
@@ -1,41 +1,25 @@
"""
Messenger data from Android app database (in =/data/data/com.facebook.orca/databases/threads_db2=)
"""
-
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
-from typing import Union
-
-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, SqliteTool
-
-from my.config import fbmessenger as user_config # isort: skip
+from datetime import datetime
+from typing import Iterator, Sequence, Optional, Dict
-logger = LazyLogger(__name__)
+from my.config import fbmessenger as user_config
+from ..core import Paths
@dataclass
-class Config(user_config.android):
+class config(user_config.android):
# paths[s]/glob to the exported sqlite databases
export_path: Paths
- facebook_id: str | None = None
-
-
-# hmm. this is necessary for default value (= None) to work
-# otherwise Config.facebook_id is always None..
-config = make_config(Config)
-
+from ..core import get_files
+from pathlib import Path
def inputs() -> Sequence[Path]:
return get_files(config.export_path)
@@ -43,28 +27,27 @@ def inputs() -> Sequence[Path]:
@dataclass(unsafe_hash=True)
class Sender:
id: str
- name: str | None
+ name: str
@dataclass(unsafe_hash=True)
class Thread:
id: str
- name: str | None # isn't set for groups or one to one messages
-
+ name: Optional[str]
# todo not sure about order of fields...
@dataclass
class _BaseMessage:
id: str
- dt: datetime_aware
- text: str | None
+ dt: datetime
+ text: Optional[str]
@dataclass(unsafe_hash=True)
class _Message(_BaseMessage):
thread_id: str
sender_id: str
- reply_to_id: str | None
+ reply_to_id: Optional[str]
# todo hmm, on the one hand would be kinda nice to inherit common.Message protocol here
@@ -73,205 +56,85 @@ class _Message(_BaseMessage):
class Message(_BaseMessage):
thread: Thread
sender: Sender
- reply_to: Message | None
+ reply_to: Optional[Message]
+import json
+from typing import Union
+from ..core.error import Res
+from ..core.dataset import connect_readonly
Entity = Union[Sender, Thread, _Message]
-
-
def _entities() -> Iterator[Res[Entity]]:
- paths = inputs()
- total = len(paths)
- width = len(str(total))
- 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:
- if use_msys:
- yield from _process_db_msys(db)
- else:
- yield from _process_db_threads_db2(db)
- except Exception as e:
- yield echain(RuntimeError(f'While processing {path}'), cause=e)
+ for f in inputs():
+ with connect_readonly(f) as db:
+ yield from _process_db(db)
-def _normalise_user_id(ukey: str) -> str:
- # trying to match messages.author from fbchat
- prefix = 'FACEBOOK:'
- assert ukey.startswith(prefix), ukey
- return ukey[len(prefix) :]
-
-
-def _normalise_thread_id(key) -> str:
+def _process_db(db) -> Iterator[Res[Entity]]:
# works both for GROUP:group_id and ONE_TO_ONE:other_user:your_user
- return key.split(':')[1]
+ threadkey2id = lambda key: key.split(':')[1]
-
-# 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] = {}
- 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
- 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]] = {}
- 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']
-
- 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
+ for r in db['threads']:
+ try:
+ yield Thread(
+ id=threadkey2id(r['thread_key']),
+ name=r['name'],
+ )
+ except Exception as e:
+ yield e
continue
- ll.append(senders[user_key])
-
- # 15 is a weird thread that doesn't have any participants and messages
- for r in db.execute('SELECT CAST(thread_key AS TEXT) AS thread_key, thread_name FROM threads WHERE thread_type != 15'):
- thread_key = r['thread_key']
- name = r['thread_name']
- if name is None:
- users = thread_users[thread_key]
- name = ', '.join([u.name or u.id for u in users])
- yield Thread(
- id=thread_key,
- name=name,
- )
-
- # TODO should be quicker to explicitly specify columns rather than SELECT *
- # should probably add it to module development tips?
- for r in db.execute(
- '''
- SELECT
- message_id,
- timestamp_ms,
- text,
- CAST(thread_key AS TEXT) AS thread_key,
- 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 message 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 */
- '''
- ):
- yield _Message(
- id=r['message_id'],
- # TODO double check utc
- dt=datetime.fromtimestamp(r['timestamp_ms'] / 1000, tz=timezone.utc),
- # is_incoming=False, TODO??
- text=r['text'],
- thread_id=r['thread_key'],
- sender_id=r['sender_id'],
- reply_to_id=r['reply_source_id'],
- )
-
-
-def _process_db_threads_db2(db: sqlite3.Connection) -> Iterator[Res[Entity]]:
- 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
- name = r['name']
- user_key = r['user_key']
- s = Sender(
- id=_normalise_user_id(user_key),
- name=name,
- )
- senders[user_key] = s
- yield s
-
- self_id = config.facebook_id
- 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']
- if self_id is not None and user_key == f'FACEBOOK:{self_id}':
- # exclude yourself, otherwise it's just spammy to show up in all participants
+ for r in db['messages'].all(order_by='timestamp_ms'):
+ mtype = r['msg_type']
+ if mtype == -1:
+ # likely immediately deleted or something? doesn't have any data at all
continue
- ll = thread_users.get(thread_key)
- if ll is None:
- ll = []
- thread_users[thread_key] = ll
- ll.append(senders[user_key])
-
- for r in db.execute('SELECT * FROM threads'):
- thread_key = r['thread_key']
- thread_type = thread_key.split(':')[0]
- if thread_type == 'MONTAGE': # no idea what this is?
+ user_id = None
+ try:
+ # todo could use thread_users?
+ sj = json.loads(r['sender'])
+ ukey = sj['user_key']
+ prefix = 'FACEBOOK:'
+ assert ukey.startswith(prefix), ukey
+ user_id = ukey[len(prefix):]
+ yield Sender(
+ id=user_id,
+ name=sj['name'],
+ )
+ except Exception as e:
+ yield e
continue
- name = r['name'] # seems that it's only set for some groups
- if name is None:
- users = thread_users[thread_key]
- name = ', '.join([u.name or u.id for u in users])
- yield Thread(
- id=_normalise_thread_id(thread_key),
- name=name,
- )
- for r in db.execute(
- '''
- 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 */
- )
- ORDER BY timestamp_ms /* they aren't in order in the database, so need to sort */
- '''
- ):
- yield _Message(
- id=r['msg_id'],
- # double checked against some messages in different timezone
- dt=datetime.fromtimestamp(r['timestamp_ms'] / 1000, tz=timezone.utc),
- # is_incoming=False, TODO??
- text=r['text'],
- thread_id=_normalise_thread_id(r['thread_key']),
- sender_id=_normalise_user_id(r['user_key']),
- reply_to_id=r['message_replied_to_id'],
- )
-
-
-def contacts() -> Iterator[Res[Sender]]:
- for x in unique_everseen(_entities):
- if isinstance(x, Exception):
- yield x
+ thread_id = None
+ try:
+ thread_id = threadkey2id(r['thread_key'])
+ except Exception as e:
+ yield e
continue
- if isinstance(x, Sender):
- yield x
+
+ try:
+ assert user_id is not None
+ assert thread_id is not None
+ yield _Message(
+ id=r['msg_id'],
+ dt=datetime.fromtimestamp(r['timestamp_ms'] / 1000),
+ # is_incoming=False, TODO??
+ text=r['text'],
+ thread_id=thread_id,
+ sender_id=user_id,
+ reply_to_id=r['message_replied_to_id']
+ )
+ except Exception as e:
+ yield e
+from more_itertools import unique_everseen
def messages() -> Iterator[Res[Message]]:
- senders: dict[str, Sender] = {}
- msgs: dict[str, Message] = {}
- threads: dict[str, Thread] = {}
- for x in unique_everseen(_entities):
+ senders: Dict[str, Sender] = {}
+ msgs: Dict[str, Message] = {}
+ threads: Dict[str, Thread] = {}
+ for x in unique_everseen(_entities()):
if isinstance(x, Exception):
yield x
continue
@@ -283,12 +146,12 @@ def messages() -> Iterator[Res[Message]]:
continue
if isinstance(x, _Message):
reply_to_id = x.reply_to_id
- # hmm, reply_to be missing due to the synthetic nature of export, so have to be defensive
- reply_to = None if reply_to_id is None else msgs.get(reply_to_id)
- # also would be interesting to merge together entities rather than resulting messages from different sources..
- # then the merging thing could be moved to common?
try:
sender = senders[x.sender_id]
+ # hmm, reply_to be missing due to the synthetic nature of export
+ # also would be interesting to merge together entities rather than resuling messages from different sources..
+ # then the merging thing could be moved to common?
+ reply_to = None if reply_to_id is None else msgs[reply_to_id]
thread = threads[x.thread_id]
except Exception as e:
yield e
@@ -304,6 +167,4 @@ def messages() -> Iterator[Res[Message]]:
msgs[m.id] = m
yield m
continue
- # NOTE: for some reason mypy coverage highlights it as red?
- # but it actually works as expected: i.e. if you omit one of the clauses above, mypy will complain
- assert_never(x)
+ assert False, type(x) # should be unreachable
diff --git a/my/fbmessenger/common.py b/my/fbmessenger/common.py
index 0f5a374..5f8bd85 100644
--- a/my/fbmessenger/common.py
+++ b/my/fbmessenger/common.py
@@ -1,27 +1,24 @@
-from __future__ import annotations
+from my.core import __NOT_HPI_MODULE__
-from my.core import __NOT_HPI_MODULE__ # isort: skip
+from datetime import datetime
+from typing import Iterator, Optional, TYPE_CHECKING
-from collections.abc import Iterator
-from typing import Protocol
-
-from my.core import datetime_aware
+if TYPE_CHECKING:
+ try:
+ from typing import Protocol
+ except ImportError:
+ # requirement of mypy
+ from typing_extensions import Protocol # type: ignore[misc]
+else:
+ Protocol = object
class Thread(Protocol):
@property
def id(self) -> str: ...
- @property
- def name(self) -> str | None: ...
-
-
-class Sender(Protocol):
- @property
- def id(self) -> str: ...
-
- @property
- def name(self) -> str | None: ...
+ # todo hmm it doesn't like it because one from .export is just str, not Optional...
+ # name: Optional[str]
class Message(Protocol):
@@ -29,24 +26,18 @@ class Message(Protocol):
def id(self) -> str: ...
@property
- def dt(self) -> datetime_aware: ...
+ def dt(self) -> datetime: ...
@property
- def text(self) -> str | None: ...
+ def text(self) -> Optional[str]: ...
@property
def thread(self) -> Thread: ...
- @property
- def sender(self) -> Sender: ...
-
from itertools import chain
-
from more_itertools import unique_everseen
-
-from my.core import Res, warn_if_empty
-
+from my.core import warn_if_empty, Res
@warn_if_empty
def _merge_messages(*sources: Iterator[Res[Message]]) -> Iterator[Res[Message]]:
@@ -55,13 +46,5 @@ def _merge_messages(*sources: Iterator[Res[Message]]) -> Iterator[Res[Message]]:
if isinstance(r, Exception):
return str(r)
else:
- # use both just in case, would be easier to spot tz issues
- # similar to twitter, might make sense to generify/document as a pattern
- return (r.id, r.dt)
+ return r.id
yield from unique_everseen(chain(*sources), key=key)
-
-
-# TODO some notes about gdpr export (since there is no module yet)
-# ugh, messages seem to go from new to old in messages_N.json files as N increases :facepalm:
-# seems like it's storing local timestamp :facepalm:
-# checked against a message sent on 4 may 2022
diff --git a/my/fbmessenger/export.py b/my/fbmessenger/export.py
index 3b06618..0edb571 100644
--- a/my/fbmessenger/export.py
+++ b/my/fbmessenger/export.py
@@ -7,15 +7,14 @@ REQUIRES = [
'git+https://github.com/karlicoss/fbmessengerexport',
]
-from collections.abc import Iterator
-from contextlib import ExitStack, contextmanager
from dataclasses import dataclass
+from pathlib import Path
+from typing import Iterator
+
+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
@@ -23,6 +22,7 @@ _new_section = getattr(user_config, 'fbmessengerexport', None)
_old_attr = getattr(user_config, 'export_db', None)
if _new_section is None and _old_attr is not None:
+ from my.core.warnings import high
high("""DEPRECATED! Please modify your fbmessenger config to look like:
class fbmessenger:
@@ -35,25 +35,55 @@ class fbmessenger:
###
+from ..core import PathIsh
@dataclass
class config(user_config.fbmessengerexport):
export_db: PathIsh
-@contextmanager
-def _dal() -> Iterator[messenger.DAL]:
- model = messenger.DAL(config.export_db)
- with ExitStack() as stack:
- if hasattr(model, '__dal__'): # defensive to support legacy fbmessengerexport
- stack.enter_context(model)
- yield model
+def _dal() -> messenger.DAL:
+ return messenger.DAL(config.export_db)
+from ..core import Res
def messages() -> Iterator[Res[messenger.Message]]:
- with _dal() as model:
- for t in model.iter_threads():
- yield from t.iter_messages()
+ model = _dal()
+ for t in model.iter_threads():
+ yield from t.iter_messages()
+from ..core import stat, Stats
def stats() -> Stats:
return stat(messages)
+
+
+### vvv not sure if really belongs here...
+
+def _dump_helper(model: messenger.DAL, tdir: Path) -> None:
+ for t in model.iter_threads():
+ name = t.name.replace('/', '_') # meh..
+ path = tdir / (name + '.txt')
+ with path.open('w') as fo:
+ for m in t.iter_messages(order_by='-timestamp'):
+ # TODO would be nice to have usernames perhaps..
+ dts = m.dt.strftime('%Y-%m-%d %a %H:%M')
+ msg = f"{dts}: {m.text}"
+ print(msg, file=fo)
+
+
+def dump_chat_history(where: PathIsh) -> None:
+ p = Path(where)
+ assert not p.exists() or p.is_dir()
+
+ model = _dal()
+
+ from shutil import rmtree
+ from tempfile import TemporaryDirectory
+ with TemporaryDirectory() as tdir:
+ td = Path(tdir)
+ _dump_helper(model, td)
+
+ if p.exists():
+ rmtree(p)
+ td.rename(p)
+ td.mkdir() # ugh, hacky way of preventing complaints from context manager
diff --git a/my/foursquare.py b/my/foursquare.py
old mode 100644
new mode 100755
index 3b418aa..7325f3c
--- a/my/foursquare.py
+++ b/my/foursquare.py
@@ -2,20 +2,22 @@
Foursquare/Swarm checkins
'''
-import json
-from datetime import datetime, timedelta, timezone
+from datetime import datetime, timezone, timedelta
from itertools import chain
-
-from my.config import foursquare as config
+from pathlib import Path
+import json
# TODO pytz for timezone???
-from my.core import get_files, make_logger
-logger = make_logger(__name__)
+from .core.common import get_files, LazyLogger
+from my.config import foursquare as config
+
+
+logger = LazyLogger(__name__)
def inputs():
- return get_files(config.export_path)
+ return get_files(config.export_path, '*.json')
class Checkin:
@@ -59,7 +61,7 @@ class Place:
def get_raw(fname=None):
if fname is None:
fname = max(inputs())
- j = json.loads(fname.read_text())
+ j = json.loads(Path(fname).read_text())
assert isinstance(j, list)
for chunk in j:
diff --git a/my/github/all.py b/my/github/all.py
index f5e13cf..f885dde 100644
--- a/my/github/all.py
+++ b/my/github/all.py
@@ -3,7 +3,8 @@ Unified Github data (merged from GDPR export and periodic API updates)
"""
from . import gdpr, ghexport
-from .common import Results, merge_events
+
+from .common import merge_events, Results
def events() -> Results:
diff --git a/my/github/common.py b/my/github/common.py
index 22ba47e..6114045 100644
--- a/my/github/common.py
+++ b/my/github/common.py
@@ -1,27 +1,26 @@
"""
Github events and their metadata: comments/issues/pull requests
"""
-
-from __future__ import annotations
-
-from my.core import __NOT_HPI_MODULE__ # isort: skip
+from ..core import __NOT_HPI_MODULE__
-from collections.abc import Iterable
-from datetime import datetime, timezone
-from typing import NamedTuple, Optional
+from datetime import datetime
+from typing import Optional, NamedTuple, Iterable, Set, Tuple
-from my.core import make_logger, warn_if_empty
-from my.core.error import Res
+import pytz
-logger = make_logger(__name__)
+from ..core import warn_if_empty, LazyLogger
+from ..core.error import Res
+
+
+logger = LazyLogger(__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
@@ -30,7 +29,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
@@ -49,13 +48,13 @@ def merge_events(*sources: Results) -> Results:
def parse_dt(s: str) -> datetime:
# TODO isoformat?
- return datetime.strptime(s, '%Y-%m-%dT%H:%M:%SZ').replace(tzinfo=timezone.utc)
+ return pytz.utc.localize(datetime.strptime(s, '%Y-%m-%dT%H:%M:%SZ'))
# experimental way of supportint event ids... not sure
class EventIds:
@staticmethod
- def repo_created(*, dts: str, name: str, ref_type: str, ref: str | None) -> str:
+ def repo_created(*, dts: str, name: str, ref_type: str, ref: Optional[str]) -> str:
return f'{dts}_repocreated_{name}_{ref_type}_{ref}'
@staticmethod
diff --git a/my/github/gdpr.py b/my/github/gdpr.py
index be56454..fe8a64b 100644
--- a/my/github/gdpr.py
+++ b/my/github/gdpr.py
@@ -2,93 +2,39 @@
Github data (uses [[https://github.com/settings/admin][official GDPR export]])
"""
-from __future__ import annotations
-
import json
-from abc import abstractmethod
-from collections.abc import Iterator, Sequence
-from pathlib import Path
-from typing import Any
+from typing import Iterable, Dict, Any
-from my.core import Paths, Res, Stats, get_files, make_logger, stat, warnings
-from my.core.error import echain
+from ..core.error import Res
+from ..core import get_files
-from .common import Event, EventIds, parse_dt
+from .common import Event, parse_dt, EventIds
-logger = make_logger(__name__)
+# TODO later, use a separate user config? (github_gdpr)
+from my.config import github as user_config
+
+from dataclasses import dataclass
+from ..core import PathIsh
+
+@dataclass
+class github(user_config):
+ gdpr_dir: PathIsh # path to unpacked GDPR archive
+
+###
-class config:
- @property
- @abstractmethod
- def gdpr_dir(self) -> Paths:
- raise NotImplementedError
+from ..core.cfg import make_config
+config = make_config(github)
-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]:
- 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:
- # 'legacy' behaviour, we've been passed an extracted export directory
- # although in principle nothing wrong with running against a directory with several unpacked archives
- # so need to think how to support that in the future as well
- return [schema_json[0].parent]
- # otherwise, should contain a bunch of archives?
- # not sure if need to warn if any of them aren't .tar.gz?
- return res
-
-
-def events() -> Iterator[Res[Event]]:
- last = max(inputs())
-
- logger.info(f'extracting data from {last}')
-
- root: Path | None = None
-
- if last.is_dir(): # if it's already CPath, this will match it
- root = last
- else:
- 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
+def events() -> Iterable[Res[Event]]:
+ # TODO FIXME allow using archive here?
+ files = get_files(config.gdpr_dir, glob='*.json')
handler_map = {
'schema' : None,
- 'issue_events_': None, # eh, doesn't seem to have any useful bodies
- 'attachments_' : None, # not sure if useful
- 'users' : None, # just contains random users
- 'bots' : None, # just contains random bots
+ 'issue_events_': None, # eh, doesn't seem to have any useful bodies
+ 'attachments_' : None, # not sure if useful
+ 'users' : None, # just contains random users
'repositories_' : _parse_repository,
'issue_comments_': _parse_issue_comment,
'issues_' : _parse_issue,
@@ -96,18 +42,8 @@ def _process_one(root: Path) -> Iterator[Res[Event]]:
'projects_' : _parse_project,
'releases_' : _parse_release,
'commit_comments': _parse_commit_comment,
- ## TODO need to handle these
- 'pull_request_review_comments_': None,
- 'pull_request_review_threads_': None,
- 'pull_request_reviews_': None,
- ##
- 'repository_files_': None, # repository artifacts, probs not very useful
- 'discussion_categories_': None, # doesn't seem to contain any useful info, just some repo metadata
- 'organizations_': None, # no useful info, just some org metadata
}
- # fmt: on
for f in files:
- logger.info(f'{f} : processing...')
handler: Any
for prefix, h in handler_map.items():
if not f.name.startswith(prefix):
@@ -127,84 +63,80 @@ def _process_one(root: Path) -> Iterator[Res[Event]]:
try:
yield handler(r)
except Exception as e:
- yield echain(RuntimeError(f'While processing file: {f}'), e)
+ yield e
-def stats() -> Stats:
+def stats():
+ from ..core import stat
return {
**stat(events),
}
# 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 {
- 'dt': parse_dt(d['created_at']),
+ 'dt' : parse_dt(d['created_at']),
'link': url,
'body': body,
}
-def _parse_repository(d: dict) -> Event:
+def _parse_repository(d: Dict) -> Event:
pref = 'https://github.com/'
url = d['url']
dts = d['created_at']
- rt = d['type']
- assert url.startswith(pref)
- name = url[len(pref) :]
+ rt = d['type']
+ assert url.startswith(pref); name = url[len(pref):]
eid = EventIds.repo_created(dts=dts, name=name, ref_type=rt, ref=None)
- return Event(
+ return Event( # type: ignore[misc]
**_parse_common(d),
summary='created ' + name,
eid=eid,
)
-# user may be None if the user was deleted
-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(
+ is_bot = "[bot]" in d["user"]
+ return Event( # type: ignore[misc]
**_parse_common(d),
summary=f'commented on issue {url}',
eid='issue_comment_' + url,
- is_bot=_is_bot(d['user']),
+ is_bot=is_bot,
)
-def _parse_issue(d: dict) -> Event:
+def _parse_issue(d: Dict) -> Event:
url = d['url']
title = d['title']
- return Event(
+ is_bot = "[bot]" in d["user"]
+ return Event( # type: ignore[misc]
**_parse_common(d),
summary=f'opened issue {title}',
eid='issue_comment_' + url,
- is_bot=_is_bot(d['user']),
+ is_bot=is_bot,
)
-def _parse_pull_request(d: dict) -> Event:
+def _parse_pull_request(d: Dict) -> Event:
dts = d['created_at']
url = d['url']
title = d['title']
- return Event(
+ is_bot = "[bot]" in d["user"]
+ return Event( # type: ignore[misc]
**_parse_common(d),
# TODO distinguish incoming/outgoing?
# TODO action? opened/closed??
summary=f'opened PR {title}',
eid=EventIds.pr(dts=dts, action='opened', url=url),
- is_bot=_is_bot(d['user']),
+ is_bot=is_bot,
)
-def _parse_project(d: dict) -> Event:
+def _parse_project(d: Dict) -> Event:
url = d['url']
title = d['name']
is_bot = "[bot]" in d["creator"]
@@ -219,18 +151,18 @@ def _parse_project(d: dict) -> Event:
)
-def _parse_release(d: dict) -> Event:
+def _parse_release(d: Dict) -> Event:
tag = d['tag_name']
- return Event(
+ return Event( # type: ignore[misc]
**_parse_common(d),
summary=f'released {tag}',
eid='release_' + tag,
)
-def _parse_commit_comment(d: dict) -> Event:
+def _parse_commit_comment(d: Dict) -> Event:
url = d['url']
- return Event(
+ return Event( # type: ignore[misc]
**_parse_common(d),
summary=f'commented on {url}',
eid='commit_comment_' + url,
diff --git a/my/github/ghexport.py b/my/github/ghexport.py
index 3e17c10..c9ba7ea 100644
--- a/my/github/ghexport.py
+++ b/my/github/ghexport.py
@@ -1,17 +1,13 @@
"""
Github data: events, comments, etc. (API data)
"""
-
-from __future__ import annotations
-
REQUIRES = [
'git+https://github.com/karlicoss/ghexport',
]
-
from dataclasses import dataclass
-from my.config import github as user_config
from my.core import Paths
+from my.config import github as user_config
@dataclass
@@ -25,9 +21,7 @@ class github(user_config):
###
-from my.core.cfg import Attrs, make_config
-
-
+from my.core.cfg import make_config, Attrs
def migration(attrs: Attrs) -> Attrs:
export_dir = 'export_dir'
if export_dir in attrs: # legacy name
@@ -41,20 +35,19 @@ config = make_config(github, migration=migration)
try:
from ghexport import dal
except ModuleNotFoundError as e:
- from my.core.hpi_compat import pre_pip_dal_handler
-
+ from my.core.compat import pre_pip_dal_handler
dal = pre_pip_dal_handler('ghexport', e, config, requires=REQUIRES)
############################
-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 LazyLogger, get_files
-from my.core.cachew import mcachew
+from my.core import get_files, Path, LazyLogger
+from my.core.common import mcachew
+
+from .common import Event, parse_dt, Results, EventIds
-from .common import Event, EventIds, Results, parse_dt
logger = LazyLogger(__name__)
@@ -68,12 +61,13 @@ def _dal() -> dal.DAL:
return dal.DAL(sources)
-@mcachew(depends_on=inputs)
+@mcachew(depends_on=lambda: inputs())
def events() -> Results:
- # key = lambda e: object() if isinstance(e, Exception) else e.eid
+ from my.core.common import ensure_unique
+ 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)
- return _events()
+ yield from _events()
def _events() -> Results:
@@ -87,9 +81,7 @@ def _events() -> Results:
yield e
-from my.core import Stats, stat
-
-
+from my.core import stat, Stats
def stats() -> Stats:
return {
**stat(events),
@@ -106,7 +98,7 @@ def _log_if_unhandled(e) -> None:
Link = str
EventId = str
Body = str
-def _get_summary(e) -> tuple[str, Link | None, EventId | None, Body | None]:
+def _get_summary(e) -> Tuple[str, Optional[Link], Optional[EventId], Optional[Body]]:
# TODO would be nice to give access to raw event within timeline
dts = e['created_at']
eid = e['id']
@@ -136,7 +128,7 @@ def _get_summary(e) -> tuple[str, Link | None, EventId | None, Body | None]:
rt = pl['ref_type']
ref = pl['ref']
if what == 'created':
- # FIXME should handle deletion?...
+ # FIXME should handle delection?...
eid = EventIds.repo_created(dts=dts, name=rname, ref_type=rt, ref=ref)
mref = '' if ref is None else ' ' + ref
# todo link to branch? only contains weird API link though
@@ -202,7 +194,7 @@ def _get_summary(e) -> tuple[str, Link | None, EventId | None, Body | None]:
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 559efda..acf2bb9 100644
--- a/my/goodreads.py
+++ b/my/goodreads.py
@@ -7,18 +7,15 @@ REQUIRES = [
from dataclasses import dataclass
-
+from my.core import 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 Attrs, make_config
-
+from my.core.cfg import make_config, Attrs
def _migration(attrs: Attrs) -> Attrs:
export_dir = 'export_dir'
@@ -32,19 +29,18 @@ config = make_config(goodreads, migration=_migration)
#############################3
-from collections.abc import Iterator, Sequence
-from pathlib import Path
-
from my.core import get_files
-
+from typing import Sequence, Iterator
+from pathlib import Path
def inputs() -> Sequence[Path]:
return get_files(config.export_path)
from datetime import datetime
-
import pytz
+
+
from goodrexport import dal
@@ -65,6 +61,7 @@ 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/google/maps/_android_protobuf.py b/my/google/maps/_android_protobuf.py
deleted file mode 100644
index 615623d..0000000
--- a/my/google/maps/_android_protobuf.py
+++ /dev/null
@@ -1,113 +0,0 @@
-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_pb2, descriptor_pool, 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
deleted file mode 100644
index 95ecacf..0000000
--- a/my/google/maps/android.py
+++ /dev/null
@@ -1,202 +0,0 @@
-"""
-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 collections.abc import Iterator, Sequence
-from dataclasses import dataclass
-from datetime import datetime, timezone
-from pathlib import Path
-from typing import Any
-from urllib.parse import quote
-
-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
-
-from ._android_protobuf import parse_labeled, parse_list, parse_place
-
-import my.config # isort: skip
-
-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: str | None
- note: str | None
-
- @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/my/google/takeout/html.py b/my/google/takeout/html.py
index 3f2b5db..d4d6830 100644
--- a/my/google/takeout/html.py
+++ b/my/google/takeout/html.py
@@ -2,22 +2,18 @@
Google Takeout exports: browsing history, search/youtube/google play activity
'''
-from __future__ import annotations
-
-from my.core import __NOT_HPI_MODULE__ # isort: skip
-
-import re
-from collections.abc import Iterable
-from datetime import datetime
from enum import Enum
-from html.parser import HTMLParser
+import re
from pathlib import Path
-from typing import Any, Callable
+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 my.core.time import abbr_to_timezone
+from ...core.time import abbr_to_timezone
+
# NOTE: https://bugs.python.org/issue22377 %Z doesn't work properly
_TIME_FORMATS = [
@@ -34,13 +30,12 @@ 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?
- # 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)
- dt: datetime | None = None
+ dt: Optional[datetime] = None
for fmt in _TIME_FORMATS:
try:
dt = datetime.strptime(s, fmt)
@@ -77,7 +72,7 @@ class State(Enum):
Url = str
Title = str
-Parsed = tuple[datetime, Url, Title]
+Parsed = Tuple[datetime, Url, Title]
Callback = Callable[[datetime, Url, Title], None]
@@ -87,9 +82,9 @@ class TakeoutHTMLParser(HTMLParser):
super().__init__()
self.state: State = State.OUTSIDE
- self.title_parts: list[str] = []
- self.title: str | None = None
- self.url: str | None = None
+ self.title_parts: List[str] = []
+ self.title: Optional[str] = None
+ self.url: Optional[str] = None
self.callback = callback
@@ -97,8 +92,8 @@ class TakeoutHTMLParser(HTMLParser):
def handle_starttag(self, tag, attrs):
if self.state == State.INSIDE and tag == 'a':
self.state = State.PARSING_LINK
- [hr] = (v for k, v in attrs if k == 'href')
- assert hr is not None
+ attrs = OrderedDict(attrs)
+ hr = attrs['href']
# 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?
@@ -126,7 +121,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"):
@@ -152,11 +147,14 @@ class TakeoutHTMLParser(HTMLParser):
def read_html(tpath: Path, file: str) -> Iterable[Parsed]:
- results: list[Parsed] = []
+ from ...core.kompress import kopen
+ results: List[Parsed] = []
def cb(dt: datetime, url: Url, title: Title) -> None:
results.append((dt, url, title))
parser = TakeoutHTMLParser(callback=cb)
- with (tpath / file).open() as fo:
+ with kopen(tpath, file) as fo:
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
deleted file mode 100644
index 13fd04a..0000000
--- a/my/google/takeout/parser.py
+++ /dev/null
@@ -1,153 +0,0 @@
-"""
-Parses Google Takeout using [[https://github.com/purarue/google_takeout_parser][google_takeout_parser]]
-
-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
-
-The directory set as takeout_path can be unpacked directories, or
-zip files of the exports, which are temporarily unpacked while creating
-the cachew cache
-"""
-
-REQUIRES = ["git+https://github.com/purarue/google_takeout_parser"]
-
-import os
-from collections.abc import Sequence
-from contextlib import ExitStack
-from dataclasses import dataclass
-from pathlib import Path
-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
-
-ABBR_TIMEZONES.extend(user_forced())
-
-import google_takeout_parser
-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/purarue/dotfiles/blob/master/.config/my/my/config/__init__.py for an example
-from my.config import google as user_config
-
-
-@dataclass
-class google(user_config):
- # directory which includes unpacked/zipped takeouts
- takeout_path: Paths
-
- error_policy: ErrorPolicy = 'yield'
-
- # experimental flag to use core.kompress.ZipPath
- # instead of unpacking to a tmp dir via match_structure
- _use_zippath: bool = False
-
-
-config = make_config(google)
-
-
-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)
-
-
-DISABLE_TAKEOUT_CACHE = "DISABLE_TAKEOUT_CACHE" in os.environ
-
-
-def inputs() -> Sequence[Path]:
- return get_files(config.takeout_path)
-
-
-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'))
-
-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}")
- return exports
-
-
-# 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: # noqa: FBT001
- 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
- for path in reversed(inputs()):
- with ExitStack() as exit_stack:
- if config._use_zippath:
- # for later takeouts it's just 'Takeout' dir,
- # but for older (pre 2015) it contains email/date in the subdir name
- results = tuple(cast(Sequence[Path], path.iterdir()))
- else:
- results = exit_stack.enter_context(match_structure(path, expected=EXPECTED, partial=True))
- for m in results:
- # 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
- tk = TakeoutParser(m, cachew_identifier=cw_id, error_policy=error_policy)
- # TODO might be nice to pass hpi cache dir?
- for event in tk.parse(cache=not disable_takeout_cache):
- count += 1
- if isinstance(event, Exception):
- if error_policy == 'yield':
- yield event
- elif error_policy == 'raise':
- raise event
- elif error_policy == 'drop':
- pass
- continue
-
- 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"
- )
-
-
-def stats() -> Stats:
- return {
- **stat(events),
- }
diff --git a/my/google/takeout/paths.py b/my/google/takeout/paths.py
index 6a523e2..ee3e1e7 100644
--- a/my/google/takeout/paths.py
+++ b/my/google/takeout/paths.py
@@ -2,57 +2,46 @@
Module for locating and accessing [[https://takeout.google.com][Google Takeout]] data
'''
-from __future__ import annotations
+from dataclasses import dataclass
+from ...core.common import Paths, get_files
+from ...core.util import __NOT_HPI_MODULE__
-from my.core import __NOT_HPI_MODULE__ # isort: skip
-
-from abc import abstractmethod
-from collections.abc import Iterable
-from pathlib import Path
+from my.config import google as user_config
from more_itertools import last
-from my.core import Paths, get_files
-
-
-class config:
- """
- path/paths/glob for the takeout zips
- """
-
- @property
- @abstractmethod
- def takeout_path(self) -> Paths:
- raise NotImplementedError
-
+@dataclass
+class google(user_config):
+ takeout_path: Paths # path/paths/glob for the takeout zips
+###
# TODO rename 'google' to 'takeout'? not sure
+from ...core.cfg import make_config
+config = make_config(google)
-def make_config() -> config:
- from my.config import google as user_config
+from pathlib import Path
+from typing import Optional, Iterable
- class combined_config(user_config, config): ...
-
- return combined_config()
+from ...core.kompress import kexists
-def get_takeouts(*, path: str | None = 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 zip is not great..
+ # TODO FIXME zip is not great..
# allow a lambda expression? that way the user could restrict it
- cfg = make_config()
- for takeout in get_files(cfg.takeout_path, glob='*.zip'):
- if path is None or (takeout / path).exists():
+ for takeout in get_files(config.takeout_path, glob='*.zip'):
+ if path is None or kexists(takeout, path):
yield takeout
-def get_last_takeout(*, path: str | None = None) -> Path | None:
+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/hackernews/common.py b/my/hackernews/common.py
index 6990987..8c7dd1e 100644
--- a/my/hackernews/common.py
+++ b/my/hackernews/common.py
@@ -1,20 +1,2 @@
-from typing import Protocol
-
-from my.core import datetime_aware
-
-
def hackernews_link(id: str) -> str:
return f'https://news.ycombinator.com/item?id={id}'
-
-
-class SavedBase(Protocol):
- @property
- def when(self) -> datetime_aware: ...
- @property
- def uid(self) -> str: ...
- @property
- def url(self) -> str: ...
- @property
- def title(self) -> str: ...
- @property
- def hackernews_link(self) -> str: ...
diff --git a/my/hackernews/dogsheep.py b/my/hackernews/dogsheep.py
index 8303284..7329690 100644
--- a/my/hackernews/dogsheep.py
+++ b/my/hackernews/dogsheep.py
@@ -3,39 +3,41 @@ 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
-
-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
+from datetime import datetime
+from typing import Iterator, Sequence, Optional, Dict
+from my.config import hackernews as user_config
+
+
+from ..core import Paths
@dataclass
-class config(my.config.hackernews.dogsheep):
+class config(user_config.dogsheep):
# paths[s]/glob to the dogsheep database
export_path: Paths
# todo so much boilerplate... really need some common wildcard imports?...
# at least for stuff which realistically is used in each module like get_files/Sequence/Paths/dataclass/Iterator/Optional
+from ..core import get_files
+from pathlib import Path
def inputs() -> Sequence[Path]:
return get_files(config.export_path)
+from .common import hackernews_link
+
# TODO not sure if worth splitting into Comment and Story?
@dataclass(unsafe_hash=True)
class Item:
id: str
type: str
- created: datetime_aware # checked and it's utc
- 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 is it urc??
+ created: datetime
+ 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
# todo process 'deleted'? fields?
# todo process 'parent'?
@@ -44,21 +46,19 @@ class Item:
return hackernews_link(self.id)
-# TODO hmm kinda annoying that permalink isn't getting serialized
-# maybe won't be such a big problem if we used hpi query directly on objects, without jsons?
-# so we could just take .permalink thing
-
-
+from ..core.error import Res
+from ..core.dataset import connect_readonly
def items() -> Iterator[Res[Item]]:
f = max(inputs())
- with sqlite_connection(f, immutable=True, row_factory='row') as conn:
- for r in conn.execute('SELECT * FROM items ORDER BY time'):
+ with connect_readonly(f) as db:
+ items = db['items']
+ for r in items.all(order_by='time'):
yield Item(
id=r['id'],
type=r['type'],
- created=datetime.fromtimestamp(r['time'], tz=timezone.utc),
+ created=datetime.fromtimestamp(r['time']),
title=r['title'],
- # todo hmm maybe a method to strip off html tags would be nice
+ # todo hmm maybe a method to stip off html tags would be nice
text_html=r['text'],
url=r['url'],
)
diff --git a/my/hackernews/harmonic.py b/my/hackernews/harmonic.py
deleted file mode 100644
index 08a82e6..0000000
--- a/my/hackernews/harmonic.py
+++ /dev/null
@@ -1,134 +0,0 @@
-"""
-[[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
-from pathlib import Path
-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,
- Stats,
- datetime_aware,
- get_files,
- make_logger,
- stat,
-)
-from my.core.common import unique_everseen
-
-from .common import SavedBase, hackernews_link
-
-import my.config # isort: skip
-
-
-logger = make_logger(__name__)
-
-
-@dataclass
-class harmonic(my.config.harmonic):
- export_path: Paths
-
-
-def inputs() -> Sequence[Path]:
- return get_files(harmonic.export_path)
-
-
-class Cached(TypedDict):
- author: str
- created_at_i: int
- id: str
- points: int
- test: str | None
- title: str
- type: str # TODO Literal['story', 'comment']? comments are only in 'children' field tho
- url: str
- # TODO also has children with comments, but not sure I need it?
-
-
-# TODO if we ever add use .text property, need to html.unescape it first
-# TODO reuse SavedBase in materialistic?
-@dataclass
-class Saved(SavedBase):
- raw: Cached
-
- @property
- def when(self) -> datetime_aware:
- ts = self.raw['created_at_i']
- return datetime.fromtimestamp(ts, tz=timezone.utc)
-
- @property
- def uid(self) -> str:
- return self.raw['id']
-
- @property
- def url(self) -> str:
- return self.raw['url']
-
- @property
- def title(self) -> str:
- return self.raw['title']
-
- @property
- 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'
-
-
-def _saved() -> Iterator[Res[Saved]]:
- paths = inputs()
- total = len(paths)
- width = len(str(total))
- for idx, path in enumerate(paths):
- logger.info(f'processing [{idx:>{width}}/{total:>{width}}] {path}')
- # TODO defensive for each item!
- tr = etree.parse(path)
-
- 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] = {}
- for sid in cached_ids:
- 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"]')))
- for x in res.text.split('-'):
- ids, item_timestamp = x.split('q')
- # not sure if timestamp is any useful?
-
- cc = cached.get(ids, None)
- if cc is None:
- # TODO warn or error?
- continue
-
- yield Saved(cc)
-
-
-def saved() -> Iterator[Res[Saved]]:
- yield from unique_everseen(_saved)
-
-
-def stats() -> Stats:
- return {
- **stat(inputs),
- **stat(saved),
- }
diff --git a/my/hackernews/materialistic.py b/my/hackernews/materialistic.py
index ccf285b..65a1cb6 100644
--- a/my/hackernews/materialistic.py
+++ b/my/hackernews/materialistic.py
@@ -1,41 +1,34 @@
"""
[[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, NamedTuple
-from more_itertools import unique_everseen
+REQUIRES = ['dataset']
-from my.core import datetime_aware, get_files, make_logger
-from my.core.sqlite import sqlite_connection
+from datetime import datetime
+from typing import Any, Dict, Iterator, NamedTuple, Sequence
-from .common import hackernews_link
+import pytz
+from my.config import materialistic as config
# todo migrate config to my.hackernews.materialistic
-from my.config import materialistic as config # isort: skip
-
-logger = make_logger(__name__)
+from ..core import get_files
+from pathlib import Path
def inputs() -> Sequence[Path]:
return get_files(config.export_path)
-Row = dict[str, Any]
-
+Row = Dict[str, Any]
+from .common import hackernews_link
class Saved(NamedTuple):
row: Row
- # NOTE: seems like it's the time item was saved (not created originally??)
- # https://github.com/hidroh/materialistic/blob/b631d5111b7487d2328f463bd95e8507c74c3566/app/src/main/java/io/github/hidroh/materialistic/data/MaterialisticDatabase.java#L224
- # but not 100% sure.
@property
- def when(self) -> datetime_aware:
+ def when(self) -> datetime:
ts = int(self.row['time']) / 1000
- return datetime.fromtimestamp(ts, tz=timezone.utc)
+ return datetime.fromtimestamp(ts, tz=pytz.utc)
@property
def uid(self) -> str:
@@ -54,18 +47,13 @@ class Saved(NamedTuple):
return hackernews_link(self.uid)
-def _all_raw() -> Iterator[Row]:
- paths = inputs()
- total = len(paths)
- width = len(str(total))
- for idx, path in enumerate(paths):
- logger.info(f'processing [{idx:>{width}}/{total:>{width}}] {path}')
- with sqlite_connection(path, immutable=True, row_factory='dict') as conn:
- yield from conn.execute('SELECT * FROM saved ORDER BY time')
-
-
+from ..core.dataset import connect_readonly
def raw() -> Iterator[Row]:
- yield from unique_everseen(_all_raw(), key=lambda r: r['itemid'])
+ last = max(inputs())
+ with connect_readonly(last) as db:
+ saved = db['saved']
+ # TODO wonder if it's 'save time' or creation time?
+ yield from saved.all(order_by='time')
def saves() -> Iterator[Saved]:
diff --git a/my/hypothesis.py b/my/hypothesis.py
index 15e854b..370854a 100644
--- a/my/hypothesis.py
+++ b/my/hypothesis.py
@@ -4,26 +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 TYPE_CHECKING
+from datetime import datetime
+from typing import Callable
-from my.core import (
- Paths,
- Res,
- Stats,
- get_files,
- stat,
-)
-from my.core.cfg import make_config
-from my.core.hpi_compat import always_supports_sequence
+from .core import Paths
+
+from my.config import hypothesis as user_config
+
+REQUIRES = [
+ 'git+https://github.com/karlicoss/hypexport',
+]
-import my.config # isort: skip
@dataclass
-class hypothesis(my.config.hypothesis):
+class hypothesis(user_config):
'''
Uses [[https://github.com/karlicoss/hypexport][hypexport]] outputs
'''
@@ -32,39 +28,47 @@ class hypothesis(my.config.hypothesis):
export_path: Paths
+from .core.cfg import make_config
config = make_config(hypothesis)
try:
from hypexport import dal
except ModuleNotFoundError as e:
- from my.core.hpi_compat import pre_pip_dal_handler
-
+ from .core.compat import pre_pip_dal_handler
dal = pre_pip_dal_handler('hypexport', e, config, requires=REQUIRES)
+############################
+
+from typing import List
+from .core.error import Res, sort_res_by
-DAL = dal.DAL
Highlight = dal.Highlight
-Page = dal.Page
+Page = dal.Page
-def inputs() -> Sequence[Path]:
- return get_files(config.export_path)
-
-
-def _dal() -> DAL:
- return DAL(inputs())
+def _dal() -> dal.DAL:
+ from .core import get_files
+ sources = get_files(config.export_path)
+ return dal.DAL(sources)
# TODO they are in reverse chronological order...
-def highlights() -> Iterator[Res[Highlight]]:
- return always_supports_sequence(_dal().highlights())
+def highlights() -> List[Res[Highlight]]:
+ # todo hmm. otherwise mypy complans
+ key: Callable[[Highlight], datetime] = lambda h: h.created
+ return sort_res_by(_dal().highlights(), key=key)
-def pages() -> Iterator[Res[Page]]:
- return always_supports_sequence(_dal().pages())
+# TODO eh. always provide iterators? although sort_res_by could be neat too...
+def pages() -> List[Res[Page]]:
+ # note: mypy report shows "No Anys on this line here", apparently a bug with type aliases
+ # https://github.com/python/mypy/issues/8594
+ key: Callable[[Page], datetime] = lambda h: h.created
+ return sort_res_by(_dal().pages(), key=key)
+from .core import stat, Stats
def stats() -> Stats:
return {
**stat(highlights),
@@ -72,7 +76,12 @@ def stats() -> Stats:
}
-if not TYPE_CHECKING:
- # "deprecate" by hiding from mypy
- get_highlights = highlights
- get_pages = pages
+def _main() -> None:
+ for page in get_pages():
+ print(page)
+
+if __name__ == '__main__':
+ _main()
+
+get_highlights = highlights # todo deprecate
+get_pages = pages # todo deprecate
diff --git a/my/instagram/all.py b/my/instagram/all.py
deleted file mode 100644
index ce78409..0000000
--- a/my/instagram/all.py
+++ /dev/null
@@ -1,36 +0,0 @@
-from collections.abc import Iterator
-
-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]]:
- from . import gdpr
- yield from gdpr.messages()
-
-
-src_android = import_source(module_name='my.instagram.android')
-@src_android
-def _messages_android() -> Iterator[Res[Message]]:
- from . import android
- yield from android.messages()
-
-
-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 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(
- _messages_gdpr(),
- _messages_android(),
- )
-
-
-def stats() -> Stats:
- return stat(messages)
diff --git a/my/instagram/android.py b/my/instagram/android.py
index 12c11d3..c7a86e7 100644
--- a/my/instagram/android.py
+++ b/my/instagram/android.py
@@ -3,47 +3,24 @@ 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
-from pathlib import Path
+from typing import Iterator, Sequence, Optional, Dict
-from my.core import (
- Json,
- Paths,
- Res,
- assert_never,
- datetime_naive,
- get_files,
- make_config,
- make_logger,
-)
-from my.core.cachew import mcachew
-from my.core.common import unique_everseen
-from my.core.error import echain
-from my.core.sqlite import select, sqlite_connect_immutable
+from more_itertools import unique_everseen
-from my.config import instagram as user_config # isort: skip
-
-logger = make_logger(__name__)
+from my.config import instagram as user_config
+from ..core import Paths
@dataclass
-class instagram_android_config(user_config.android):
+class config(user_config.android):
# paths[s]/glob to the exported sqlite databases
export_path: Paths
- # 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: str | None = None
- full_name: str | None = None
-
-
-config = make_config(instagram_android_config)
-
+from ..core import get_files
+from pathlib import Path
def inputs() -> Sequence[Path]:
return get_files(config.export_path)
@@ -59,8 +36,7 @@ class User:
@dataclass
class _BaseMessage:
id: str
- # NOTE: ffs, looks like they keep naive timestamps in the db (checked some random messages)
- created: datetime_naive
+ created: datetime
text: str
thread_id: str
@@ -75,38 +51,19 @@ class _Message(_BaseMessage):
@dataclass(unsafe_hash=True)
class Message(_BaseMessage):
user: User
- # TODO could also extract Thread object? not sure if useful
+ # TODO could also extract Thread objec? not sure if useful
# reply_to: Optional[Message]
-# this is kinda expecrimental
-# basically just using RuntimeError(msg_id, *rest) has an unfortunate consequence:
-# there are way too many 'similar' errors (on different msg_id)
-# however passing msg_id is nice as a means of supplying extra context
-# so this is a compromise, the 'duplicate' errors will be filtered out by unique_everseen
-
-
-class MessageError(RuntimeError):
- def __init__(self, msg_id: str, *rest: str) -> None:
- super().__init__(msg_id, *rest)
- self.rest = rest
-
- def __hash__(self):
- return hash(self.rest)
-
- def __eq__(self, other) -> bool:
- if not isinstance(other, MessageError):
- return False
- return self.rest == other.rest
-
-
-def _parse_message(j: Json) -> _Message | None:
+from ..core import Json
+def _parse_message(j: Json) -> Optional[_Message]:
id = j['item_id']
t = j['item_type']
tid = j['thread_key']['thread_id']
uid = j['user_id']
+ # TODO not sure if utc??
created = datetime.fromtimestamp(int(j['timestamp']) / 1_000_000)
- text: str | None = None
+ text: str
if t == 'text':
text = j['text']
elif t == 'reel_share':
@@ -114,13 +71,10 @@ def _parse_message(j: Json) -> _Message | None:
# the problem is that the links are deliberately expired by instagram..
text = j['reel_share']['text']
elif t == 'action_log':
- # for likes this ends up as 'Liked a message' or reactions
- # which isn't super useful by itself perhaps, but matches GDPR so lets us unify threads better
- text = j['action_log']['description']
+ # something like "X liked message" -- hardly useful?
+ return None
else:
- raise MessageError(id, f"{t} isn't handled yet")
-
- assert text is not None, j
+ raise RuntimeError(f"{id}: {t} isn't handled yet")
return _Message(
id=id,
@@ -132,69 +86,49 @@ def _parse_message(j: Json) -> _Message | None:
)
-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
- for (self_uid,) in select(('user_id',), 'FROM session', db=db):
- yield User(
- id=str(self_uid),
- full_name=config.full_name or 'USERS_OWN_FULL_NAME',
- username=config.full_name or 'USERS_OWN_USERNAME',
- )
-
- for (thread_json,) in select(('thread_info',), 'FROM threads', db=db):
- j = json.loads(thread_json)
- # todo in principle should leave the thread attached to the message?
- # since thread is a group of users?
- pre_users = []
- # inviter usually contains our own user
- if 'inviter' in j:
- # sometimes it's missing (e.g. in broadcast channels)
- pre_users.append(j['inviter'])
- pre_users.extend(j['recipients'])
- for r in pre_users:
- # id disappeared and seems that pk_id is in use now (around december 2022)
- uid = r.get('id') or r.get('pk_id')
- assert uid is not None
- yield User(
- id=str(uid), # for some reason it's int in the db
- full_name=r['full_name'],
- username=r['username'],
- )
-
- for (msg_json,) in select(('message',), 'FROM messages ORDER BY timestamp', db=db):
- # eh, seems to contain everything in json?
- j = json.loads(msg_json)
- try:
- m = _parse_message(j)
- if m is not None:
- yield m
- except Exception as e:
- yield e
-
-
-def _entities() -> Iterator[Res[User | _Message]]:
+import json
+from typing import Union
+from ..core.error import Res
+import sqlite3
+from ..core.sqlite import sqlite_connect_immutable
+def _entities() -> Iterator[Res[Union[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?
- paths = inputs()
- total = len(paths)
- width = len(str(total))
- for idx, path in enumerate(paths):
- logger.info(f'processing [{idx:>{width}}/{total:>{width}}] {path}')
- with sqlite_connect_immutable(path) as db:
- try:
- yield from _process_db(db=db)
- except Exception as e:
- # todo use error policy here
- yield echain(RuntimeError(f'While processing {path}'), cause=e)
+ for f in inputs():
+ with sqlite_connect_immutable(f) as db:
+
+ for row in db.execute(f'SELECT user_id, thread_info FROM threads'):
+ (self_uid, js,) = row
+ # ugh wtf?? no easier way to extract your own user id/name??
+ yield User(
+ id=str(self_uid),
+ full_name='You',
+ username='you',
+ )
+ j = json.loads(js)
+ for r in j['recipients']:
+ yield User(
+ id=str(r['id']), # for some reason it's int in the db
+ full_name=r['full_name'],
+ username=r['username'],
+ )
+
+ for row in db.execute(f'SELECT message FROM messages ORDER BY timestamp'):
+ # eh, seems to contain everything in json?
+ (js,) = row
+ j = json.loads(js)
+ try:
+ m = _parse_message(j)
+ if m is not None:
+ yield m
+ except Exception as e:
+ yield e
-@mcachew(depends_on=inputs)
def messages() -> Iterator[Res[Message]]:
- id2user: dict[str, User] = {}
- for x in unique_everseen(_entities):
+ # TODO would be nicer to use a decorator for unique_everseen?
+ id2user: Dict[str, User] = {}
+ for x in unique_everseen(_entities()):
if isinstance(x, Exception):
yield x
continue
@@ -215,4 +149,4 @@ def messages() -> Iterator[Res[Message]]:
user=user,
)
continue
- assert_never(x)
+ assert False, type(x) # should not happen
diff --git a/my/instagram/common.py b/my/instagram/common.py
deleted file mode 100644
index 17d130f..0000000
--- a/my/instagram/common.py
+++ /dev/null
@@ -1,74 +0,0 @@
-from collections.abc import Iterator
-from dataclasses import replace
-from datetime import datetime
-from itertools import chain
-from typing import Any, Protocol
-
-from my.core import Res, warn_if_empty
-
-
-class User(Protocol):
- id: str
- username: str
- full_name: str
-
-
-class Message(Protocol):
- created: datetime
- text: str
- thread_id: str
-
- # property because it's more mypy friendly
- @property
- def user(self) -> User: ...
-
-
-@warn_if_empty
-def _merge_messages(*sources: Iterator[Res[Message]]) -> Iterator[Res[Message]]:
- # TODO double check it works w.r.t. naive/aware timestamps?
- def key(r: Res[Message]):
- if isinstance(r, Exception):
- # NOTE: using str() against Exception is nice so exceptions with same args are treated the same..
- return str(r)
-
- dt = r.created
- # seems that GDPR has millisecond resolution.. so best to strip them off when merging
- round_us = dt.microsecond // 1000 * 1000
- without_us = r.created.replace(microsecond=round_us)
- # using text as key is a bit crap.. but atm there are no better shared fields
- return (without_us, r.text)
-
- # 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] = {}
- thread_map = {}
- user_map = {}
-
- for m in chain(*sources):
- if isinstance(m, Exception):
- yield m
- continue
-
- k = key(m)
- mm = mmap.get(k)
-
- if mm is not None:
- # already emitted, we get a chance to populate mappings
- if m.thread_id not in thread_map:
- thread_map[m.thread_id] = mm.thread_id
- if m.user.id not in user_map:
- user_map[m.user.id] = mm.user
- else:
- # not emitted yet, need to emit
- repls: dict[str, Any] = {}
- tid = thread_map.get(m.thread_id)
- if tid is not None:
- repls['thread_id'] = tid
- user = user_map.get(m.user.id)
- if user is not None:
- repls['user'] = user
- if len(repls) > 0:
- m = replace(m, **repls) # type: ignore[type-var] # ugh mypy is confused because of Protocol?
- mmap[k] = m
- yield m
diff --git a/my/instagram/gdpr.py b/my/instagram/gdpr.py
index d417fdb..59b4b07 100644
--- a/my/instagram/gdpr.py
+++ b/my/instagram/gdpr.py
@@ -1,32 +1,15 @@
"""
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
-from pathlib import Path
+from typing import Iterator, Any, Sequence, Dict
+
+from my.config import instagram as user_config
from more_itertools import bucket
-from my.core import (
- Paths,
- Res,
- assert_never,
- datetime_naive,
- get_files,
- make_logger,
-)
-from my.core.common import unique_everseen
-
-from my.config import instagram as user_config # isort: skip
-
-logger = make_logger(__name__)
-
-
+from ..core import Paths
@dataclass
class config(user_config.gdpr):
# paths[s]/glob to the exported zip archives
@@ -34,6 +17,8 @@ class config(user_config.gdpr):
# TODO later also support unpacked directories?
+from ..core import get_files
+from pathlib import Path
def inputs() -> Sequence[Path]:
return get_files(config.export_path)
@@ -48,12 +33,10 @@ class User:
@dataclass
class _BaseMessage:
- # ugh, this is insane, but does look like it's just keeping local device time???
- # checked against a message sent on 3 June, which should be UTC+1, but timestamp seems local
- created: datetime_naive
+ # TODO id is missing?
+ created: datetime
text: str
thread_id: str
- # NOTE: doesn't look like there aren't any meaningful message ids in the export
@dataclass(unsafe_hash=True)
@@ -71,21 +54,12 @@ def _decode(s: str) -> str:
return s.encode('latin-1').decode('utf8')
-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)
- # 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 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..
- # (from newest to oldest)
- for path in inputs():
- yield from _entitites_from_path(path)
-
-
-def _entitites_from_path(path: Path) -> Iterator[Res[User | _Message]]:
+import json
+from typing import Union
+from ..core.error import Res
+def _entities() -> Iterator[Res[Union[User, _Message]]]:
+ from ..core.kompress import ZipPath
+ last = ZipPath(max(inputs()))
# 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:
@@ -100,17 +74,7 @@ def _entitites_from_path(path: Path) -> Iterator[Res[User | _Message]]:
# whereas here I don't need it..
# so for now will just implement this adhoc thing and think about properly fixing later
- personal_info = path / 'personal_information'
- if not personal_info.exists():
- # old path, used up to somewhere between feb-aug 2022
- personal_info = path / 'account_information'
-
- 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())
+ j = json.loads((last / 'account_information/personal_information.json').read_text())
[profile] = j['profile_user']
pdata = profile['string_map_data']
username = pdata['Username']['value']
@@ -125,29 +89,21 @@ def _entitites_from_path(path: Path) -> Iterator[Res[User | _Message]]:
)
yield self_user
- files = list(path.rglob('messages/inbox/*/message_*.json'))
- assert len(files) > 0, path
+ files = list(last.rglob('messages/inbox/*/message_*.json'))
+ assert len(files) > 0, last
buckets = bucket(files, key=lambda p: p.parts[-2])
file_map = {k: list(buckets[k]) for k in buckets}
for fname, ffiles in file_map.items():
for ffile in sorted(ffiles, key=lambda p: int(p.stem.split('_')[-1])):
- logger.info(f'{ffile} : processing...')
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 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
- # it's still fragile: e.g. if user deletes themselves there is no more username (it becomes "instagramuser")
- # if we use older exports we might be able to figure it out though... so think about it?
- # it also names grouped ones like instagramuserchrisfoodishblogand25others_einihreoog
- # so I feel like there is just not guaranteed way to correlate :(
+ # NOTE: no match in android db/api responses?
other_id = fname[-id_len:]
# NOTE: no match in android db?
- other_username = fname[: -id_len - 1]
+ other_username = fname[:-id_len - 1]
other_full_name = _decode(j['title'])
yield User(
id=other_id,
@@ -156,37 +112,21 @@ def _entitites_from_path(path: Path) -> Iterator[Res[User | _Message]]:
)
# todo "thread_type": "Regular" ?
- for jm in reversed(j['messages']): # in json, they are in reverse order for some reason
+ for jm in j['messages']:
+ # todo defensive?
try:
+ mtype = jm['type'] # Generic/Share?
content = None
if 'content' in jm:
content = _decode(jm['content'])
- if content.endswith(' to your message '):
- # ugh. for some reason these contain an extra space and that messes up message merging..
- content = content.strip()
else:
- if (share := jm.get('share')) is not None:
- if (share_link := share.get('link')) is not None:
- # somewhere around 20231007, instagram removed these from gdpr links and they show up a lot in various diffs
- share_link = share_link.replace('feed_type=reshare_chaining&', '')
- share_link = share_link.replace('?feed_type=reshare_chaining', '')
- share['link'] = share_link
- if (share_text := share.get('share_text')) is not None:
- share['share_text'] = _decode(share_text)
-
+ share = jm.get('share')
photos = jm.get('photos')
videos = jm.get('videos')
cc = share or photos or videos
if cc is not None:
content = str(cc)
-
- if content is None:
- # this happens e.g. on reel shares..
- # not sure what we can do properly, GPDR has literally no other info in this case
- # on android in this case at the moment we have as content ''
- # so for consistency let's do that too
- content = ''
-
+ assert content is not None, jm
timestamp_ms = jm['timestamp_ms']
sender_name = _decode(jm['sender_name'])
@@ -195,16 +135,17 @@ def _entitites_from_path(path: Path) -> Iterator[Res[User | _Message]]:
created=datetime.fromtimestamp(timestamp_ms / 1000),
text=content,
user_id=user_id,
- thread_id=fname, # meh.. but no better way?
+ thread_id=fname, # meh.. but no better way?
)
except Exception as e:
+ # TODO sometimes messages are just missing content?? even with Generic type
yield e
# TODO basically copy pasted from android.py... hmm
def messages() -> Iterator[Res[Message]]:
- id2user: dict[str, User] = {}
- for x in unique_everseen(_entities):
+ id2user: Dict[str, User] = {}
+ for x in _entities():
if isinstance(x, Exception):
yield x
continue
@@ -224,4 +165,4 @@ def messages() -> Iterator[Res[Message]]:
user=user,
)
continue
- assert_never(x)
+ assert False, type(x) # should not happen
diff --git a/my/instapaper.py b/my/instapaper.py
index d79e7e4..1ab62c2 100644
--- a/my/instapaper.py
+++ b/my/instapaper.py
@@ -7,10 +7,10 @@ REQUIRES = [
from dataclasses import dataclass
-from my.config import instapaper as user_config
-
from .core import Paths
+from my.config import instapaper as user_config
+
@dataclass
class instapaper(user_config):
@@ -22,15 +22,13 @@ class instapaper(user_config):
from .core.cfg import make_config
-
config = make_config(instapaper)
try:
from instapexport import dal
except ModuleNotFoundError as e:
- from my.core.hpi_compat import pre_pip_dal_handler
-
+ from .core.compat import pre_pip_dal_handler
dal = pre_pip_dal_handler('instapexport', e, config, requires=REQUIRES)
############################
@@ -40,12 +38,9 @@ Bookmark = dal.Bookmark
Page = dal.Page
-from collections.abc import Iterable, Sequence
+from typing import Sequence, Iterable
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
deleted file mode 100644
index c267383..0000000
--- a/my/ip/all.py
+++ /dev/null
@@ -1,28 +0,0 @@
-"""
-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/purarue/HPI/tree/master/my/ip
-"""
-
-REQUIRES = ["git+https://github.com/purarue/ipgeocache"]
-
-
-from collections.abc import Iterator
-
-from my.core import Stats, warn_if_empty
-from my.ip.common import IP
-
-
-@warn_if_empty
-def ips() -> Iterator[IP]:
- yield from ()
-
-
-def stats() -> Stats:
- from my.core import stat
-
- return {
- **stat(ips),
- }
diff --git a/my/ip/common.py b/my/ip/common.py
deleted file mode 100644
index b551281..0000000
--- a/my/ip/common.py
+++ /dev/null
@@ -1,44 +0,0 @@
-"""
-Provides location/timezone data from IP addresses, using [[https://github.com/purarue/ipgeocache][ipgeocache]]
-"""
-
-from my.core import __NOT_HPI_MODULE__ # isort: skip
-
-import ipaddress
-from collections.abc import Iterator
-from datetime import datetime
-from typing import NamedTuple
-
-import ipgeocache
-
-from my.core import Json
-
-
-class IP(NamedTuple):
- dt: datetime
- addr: str # an IP address
-
- # TODO: could cache? not sure if it's worth it
- def ipgeocache(self) -> Json:
- return ipgeocache.get(self.addr)
-
- @property
- def latlon(self) -> tuple[float, float]:
- loc: str = self.ipgeocache()["loc"]
- lat, _, lon = loc.partition(",")
- return float(lat), float(lon)
-
- @property
- def tzname(self) -> str:
- tz: str = self.ipgeocache()["timezone"]
- return tz
-
-
-def drop_private(ips: Iterator[IP]) -> Iterator[IP]:
- """
- Helper function that can be used to filter out private IPs
- """
- for ip in ips:
- if ipaddress.ip_address(ip.addr).is_private:
- continue
- yield ip
diff --git a/my/jawbone/__init__.py b/my/jawbone/__init__.py
old mode 100644
new mode 100755
index 463d735..06cb262
--- a/my/jawbone/__init__.py
+++ b/my/jawbone/__init__.py
@@ -1,19 +1,18 @@
-from __future__ import annotations
-
+#!/usr/bin/env python3
+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
-from my.core import make_logger
+from ..core.common import LazyLogger
-logger = make_logger(__name__)
+logger = LazyLogger(__name__)
+
+from my.config import jawbone as config
-from my.config import jawbone as config # type: ignore[attr-defined]
BDIR = config.export_dir
PHASES_FILE = BDIR / 'phases.json'
@@ -24,7 +23,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 +88,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,39 +99,31 @@ 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, extract_error_datetime, set_error_datetime
-
+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..
-
- bucketed = bucket(sleeps, key=lambda s: s.date_)
-
- for dd in bucketed:
- group = list(bucketed[dd])
+ from ..common import group_by_key
+ for dd, group in group_by_key(sleeps, key=lambda s: s.date_).items():
if len(group) == 1:
yield group[0]
else:
err = RuntimeError(f'Multiple sleeps per night, not supported yet: {group}')
- dt = datetime.combine(dd, time.min)
- set_error_datetime(err, dt=dt)
+ set_error_datetime(err, dt=dd)
logger.exception(err)
yield err
def dataframe():
- dicts: list[dict[str, Any]] = []
+ dicts: List[Dict] = []
for s in pre_dataframe():
- d: dict[str, Any]
if isinstance(s, Exception):
dt = extract_error_datetime(s)
d = {
@@ -151,7 +142,7 @@ def dataframe():
}
dicts.append(d)
- import pandas as pd
+ import pandas as pd # type: ignore
return pd.DataFrame(dicts)
# TODO tz is in sleeps json
@@ -164,6 +155,9 @@ 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")
@@ -174,15 +168,14 @@ def hhmm(time: datetime):
# fromstart = time - sleep.created
# return fromstart / tick
+import matplotlib.dates as mdates # type: ignore
-def plot_one(sleep: SleepEntry, fig, axes, xlims=None, *, showtext=True):
- import matplotlib.dates as mdates # type: ignore[import-not-found]
-
+def plot_one(sleep: SleepEntry, fig: Figure, axes: Axes, xlims=None, showtext=True):
span = sleep.completed - sleep.created
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
@@ -240,7 +233,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()))
@@ -250,7 +243,7 @@ def plot_one(sleep: SleepEntry, fig, axes, xlims=None, *, showtext=True):
def predicate(sleep: SleepEntry):
"""
- Filter for comparing similar sleep sessions
+ Filter for comparing similar sleep sesssions
"""
start = sleep.created.time()
end = sleep.completed.time()
@@ -260,10 +253,7 @@ def predicate(sleep: SleepEntry):
# TODO move to dashboard
-def plot() -> None:
- import matplotlib.pyplot as plt # type: ignore[import-not-found]
- from matplotlib.figure import Figure # type: ignore[import-not-found]
-
+def plot():
# TODO FIXME melatonin data
melatonin_data = {} # type: ignore[var-annotated]
@@ -275,7 +265,7 @@ def plot() -> None:
fig: Figure = plt.figure(figsize=(15, sleeps_count * 1))
axarr = fig.subplots(nrows=len(sleeps))
- for (sleep, axes) in zip(sleeps, axarr):
+ for i, (sleep, axes) in enumerate(zip(sleeps, axarr)):
plot_one(sleep, fig, axes, showtext=True)
used = melatonin_data.get(sleep.date_, None)
sused: str
diff --git a/my/jawbone/plots.py b/my/jawbone/plots.py
index 5968412..195ddb5 100755
--- a/my/jawbone/plots.py
+++ b/my/jawbone/plots.py
@@ -1,11 +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 itertools import islice
-import matplotlib.pylab as pylab # type: ignore
+from typing import Dict, Any, NamedTuple
# sleep = []
# with open('2017.csv', 'r') as fo:
@@ -13,14 +13,16 @@ import matplotlib.pylab as pylab # type: ignore
# for line in islice(reader, 0, 10):
# sleep
# print(line)
-import matplotlib.pyplot as plt # type: ignore
-from numpy import genfromtxt
+
+import matplotlib.pyplot as plt # type: ignore
+from numpy import genfromtxt # type: ignore
+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]
@@ -51,7 +53,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'])),
@@ -74,7 +76,7 @@ class SleepData(NamedTuple):
def iter_useful(data_file: str):
- with Path(data_file).open() as fo:
+ with open(data_file) as fo:
reader = DictReader(fo)
for d in reader:
dt = SleepData.from_jawbone_dict(d)
@@ -83,7 +85,7 @@ def iter_useful(data_file: str):
# TODO <<< hmm. these files do contain deep and light sleep??
# also steps stats??
-from my.config import jawbone as config # type: ignore[attr-defined]
+from my.config import jawbone as config
p = config.export_dir / 'old_csv'
# TODO with_my?
@@ -93,8 +95,7 @@ files = [
p / "2017.csv",
]
-from kython import concat, parse_date # type: ignore
-
+from kython import concat, parse_date
useful = concat(*(list(iter_useful(str(f))) for f in files))
# for u in useful:
@@ -107,9 +108,8 @@ dates = [parse_date(u.date, yearfirst=True, dayfirst=False) for u in useful]
# TODO filter outliers?
# 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 [
+from kython.plotting import plot_timestamped
+for attr, lims, mavg, fig in [ # type: ignore
('light', (0, 400), 5, None),
('deep', (0, 600), 5, None),
('total', (200, 600), 5, None),
@@ -128,7 +128,7 @@ for attr, lims, mavg, fig in [
if mavg is not None:
mavgs.append((mavg, 'green'))
fig = plot_timestamped(
- dts,
+ dts, # type: ignore
[getattr(u, attr) for u in useful],
marker='.',
ratio=(16, 4),
diff --git a/my/kobo.py b/my/kobo.py
index b4a1575..337d9c7 100644
--- a/my/kobo.py
+++ b/my/kobo.py
@@ -1,91 +1,74 @@
"""
[[https://uk.kobobooks.com/products/kobo-aura-one][Kobo]] e-ink reader: annotations and reading stats
"""
-from __future__ import annotations
REQUIRES = [
'kobuddy',
]
-from collections.abc import Iterator
-from dataclasses import dataclass
-
-import kobuddy
-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
-
+from .core import Paths, dataclass
+from my.config import kobo as user_config
@dataclass
-class kobo(my.config.kobo):
+class kobo(user_config):
'''
Uses [[https://github.com/karlicoss/kobuddy#as-a-backup-tool][kobuddy]] outputs.
'''
-
# path[s]/glob to the exported databases
export_path: Paths
+from .core.cfg import make_config
config = make_config(kobo)
-# TODO not ideal to set it here.. should switch kobuddy to use a proper DAL
-kobuddy.DATABASES = list(get_files(config.export_path))
+from .core import get_files
+import kobuddy
+# todo not sure about this glob..
+kobuddy.DATABASES = list(get_files(config.export_path, glob='*.sqlite'))
+
+#########################
+
+# hmm, explicit imports make pylint a bit happier?
+from kobuddy import Highlight, get_highlights
+from kobuddy import *
-def highlights() -> Iterator[Highlight]:
- return kobuddy._iter_highlights()
-
+from .core import stat, Stats
def stats() -> Stats:
- return stat(highlights)
-
+ return stat(get_highlights)
## TODO hmm. not sure if all this really belongs here?... perhaps orger?
-from typing import Callable, Union
-
+from typing import Callable, Union, List
# TODO maybe type over T?
_Predicate = Callable[[str], bool]
Predicatish = Union[str, _Predicate]
-
-
def from_predicatish(p: Predicatish) -> _Predicate:
if isinstance(p, str):
-
def ff(s):
return s == p
-
return ff
else:
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 = ''
return 'todo' in ann.lower().split()
-
return by_annotation(with_todo)
diff --git a/my/kython/kompress.py b/my/kython/kompress.py
deleted file mode 100644
index a5d9c29..0000000
--- a/my/kython/kompress.py
+++ /dev/null
@@ -1,5 +0,0 @@
-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')
-
-from my.core.kompress import *
diff --git a/my/kython/kompress.py b/my/kython/kompress.py
new file mode 120000
index 0000000..59edcd1
--- /dev/null
+++ b/my/kython/kompress.py
@@ -0,0 +1 @@
+../core/kompress.py
\ No newline at end of file
diff --git a/my/lastfm.py b/my/lastfm.py
old mode 100644
new mode 100755
index cd9fa8b..ffec05c
--- a/my/lastfm.py
+++ b/my/lastfm.py
@@ -2,13 +2,8 @@
Last.fm scrobbles
'''
-from dataclasses import dataclass
-
+from .core import Paths, dataclass
from my.config import lastfm as user_config
-from my.core import Json, Paths, get_files, make_logger
-
-logger = make_logger(__name__)
-
@dataclass
class lastfm(user_config):
@@ -18,18 +13,18 @@ class lastfm(user_config):
export_path: Paths
-from my.core.cfg import make_config
-
+from .core.cfg import make_config
config = make_config(lastfm)
+from datetime import datetime
import json
-from collections.abc import Iterable, Sequence
-from datetime import datetime, timezone
from pathlib import Path
-from typing import NamedTuple
+from typing import NamedTuple, Sequence, Iterable
-from my.core.cachew import mcachew
+import pytz
+
+from .core.common import mcachew, Json, get_files
def inputs() -> Sequence[Path]:
@@ -49,7 +44,7 @@ class Scrobble(NamedTuple):
@property
def dt(self) -> datetime:
ts = int(self.raw['date'])
- return datetime.fromtimestamp(ts, tz=timezone.utc)
+ return datetime.fromtimestamp(ts, tz=pytz.utc)
@property
def artist(self) -> str:
@@ -71,26 +66,22 @@ class Scrobble(NamedTuple):
@mcachew(depends_on=inputs)
def scrobbles() -> Iterable[Scrobble]:
last = max(inputs())
- logger.info(f'loading data from {last}')
j = json.loads(last.read_text())
for raw in reversed(j):
yield Scrobble(raw=raw)
-from my.core import Stats, stat
-
-
+from .core import stat, Stats
def stats() -> Stats:
return stat(scrobbles)
def fill_influxdb() -> None:
- from my.core import influxdb
-
+ from .core import influxdb
# todo needs to be more automatic
- sd = ({
- 'dt': x.dt,
- 'track': x.track,
- } for x in scrobbles())
+ sd = (dict(
+ dt=x.dt,
+ track=x.track,
+ ) for x in scrobbles())
influxdb.fill(sd, measurement=__name__)
diff --git a/my/location/all.py b/my/location/all.py
deleted file mode 100644
index c6e8cab..0000000
--- a/my/location/all.py
+++ /dev/null
@@ -1,58 +0,0 @@
-"""
-Merges location data from multiple sources
-"""
-
-from collections.abc import Iterator
-
-from my.core import LazyLogger, Stats
-from my.core.source import import_source
-
-from .common import Location
-
-logger = LazyLogger(__name__, level="warning")
-
-
-def locations() -> Iterator[Location]:
- # can add/comment out sources here to disable them, or use core.disabled_modules
- yield from _takeout_locations()
- yield from _takeout_semantic_locations()
- yield from _gpslogger_locations()
- yield from _ip_locations()
-
-
-@import_source(module_name="my.location.google_takeout")
-def _takeout_locations() -> Iterator[Location]:
- from . import google_takeout
- yield from google_takeout.locations()
-
-
-@import_source(module_name="my.location.google_takeout_semantic")
-def _takeout_semantic_locations() -> Iterator[Location]:
- from . import google_takeout_semantic
-
- for event in google_takeout_semantic.locations():
- if isinstance(event, Exception):
- logger.error(f"google_takeout_semantic: {event}")
- continue
- yield event
-
-
-@import_source(module_name="my.location.gpslogger")
-def _gpslogger_locations() -> Iterator[Location]:
- from . import gpslogger
- yield from gpslogger.locations()
-
-
-# TODO: remove, user should use fallback.estimate_location or fallback.fallback_locations instead
-@import_source(module_name="my.location.via_ip")
-def _ip_locations() -> Iterator[Location]:
- from . import via_ip
- yield from via_ip.locations()
-
-
-def stats() -> Stats:
- from my.core import stat
-
- return {
- **stat(locations),
- }
diff --git a/my/location/common.py b/my/location/common.py
deleted file mode 100644
index 4c47ef0..0000000
--- a/my/location/common.py
+++ /dev/null
@@ -1,79 +0,0 @@
-from my.core import __NOT_HPI_MODULE__ # isort: skip
-
-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]
-
-
-class LocationProtocol(Protocol):
- lat: float
- lon: float
- dt: datetime
- accuracy: Optional[float]
- elevation: Optional[float]
- datasource: Optional[str] = None # which module provided this, useful for debugging
-
-
-# TODO: add timezone to this? can use timezonefinder in tz provider instead though
-
-
-# converted from namedtuple to a dataclass so datasource field can be added optionally
-# if we want, can eventually be converted back to a namedtuple when all datasources are compliant
-@dataclass(frozen=True, eq=True)
-class Location(LocationProtocol):
- lat: float
- lon: float
- dt: datetime
- accuracy: Optional[float]
- elevation: Optional[float]
- datasource: Optional[str] = None # which module provided this, useful for debugging
-
-
-def locations_to_gpx(locations: Iterable[LocationProtocol], buffer: TextIO) -> Iterator[Exception]:
- """
- Convert locations to a GPX file, printing to a buffer (an open file, io.StringIO, sys.stdout, etc)
- """
-
- try:
- import gpxpy.gpx
- except ImportError as ie:
- from my.core.warnings import high
-
- high("gpxpy not installed, cannot write to gpx. 'pip install gpxpy'")
- raise ie
-
- gpx = gpxpy.gpx.GPX()
-
- # hmm -- would it be useful to allow the user to split this into tracks?, perhaps by date?
-
- # Create first track in our GPX:
- gpx_track = gpxpy.gpx.GPXTrack()
- gpx.tracks.append(gpx_track)
-
- # Create first segment in our GPX track:
- gpx_segment = gpxpy.gpx.GPXTrackSegment()
- gpx_track.segments.append(gpx_segment)
-
-
- for location in locations:
- try:
- point = gpxpy.gpx.GPXTrackPoint(
- latitude=location.lat,
- longitude=location.lon,
- elevation=location.elevation,
- time=location.dt,
- comment=location.datasource,
- )
- except AttributeError:
- yield TypeError(
- f"Expected a Location or Location-like object, got {type(location)} {location!r}"
- )
- continue
- gpx_segment.points.append(point)
-
- buffer.write(gpx.to_xml())
diff --git a/my/location/fallback/all.py b/my/location/fallback/all.py
deleted file mode 100644
index d340148..0000000
--- a/my/location/fallback/all.py
+++ /dev/null
@@ -1,55 +0,0 @@
-# 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 __future__ import annotations
-
-from collections.abc import Iterator
-
-from my.core.source import import_source
-from my.location.fallback.common import (
- DateExact,
- FallbackLocation,
- LocationEstimator,
- estimate_from,
-)
-
-
-def fallback_locations() -> Iterator[FallbackLocation]:
- # can comment/uncomment sources here to enable/disable them
- yield from _ip_fallback_locations()
-
-
-def fallback_estimators() -> Iterator[LocationEstimator]:
- # can comment/uncomment estimators here to enable/disable them
- # the order of the estimators determines priority if location accuries are equal/unavailable
- yield _ip_estimate
- yield _home_estimate
-
-
-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:
- raise ValueError("Could not estimate location")
- return loc
-
-
-@import_source(module_name="my.location.fallback.via_home")
-def _home_estimate(dt: DateExact) -> Iterator[FallbackLocation]:
- from my.location.fallback.via_home import estimate_location as via_home_estimate
-
- yield from via_home_estimate(dt)
-
-
-@import_source(module_name="my.location.fallback.via_ip")
-def _ip_estimate(dt: DateExact) -> Iterator[FallbackLocation]:
- from my.location.fallback.via_ip import estimate_location as via_ip_estimate
-
- yield from via_ip_estimate(dt)
-
-
-@import_source(module_name="my.location.fallback.via_ip")
-def _ip_fallback_locations() -> Iterator[FallbackLocation]:
- from my.location.fallback.via_ip import fallback_locations as via_ip_fallback
-
- yield from via_ip_fallback()
diff --git a/my/location/fallback/common.py b/my/location/fallback/common.py
deleted file mode 100644
index 622b2f5..0000000
--- a/my/location/fallback/common.py
+++ /dev/null
@@ -1,123 +0,0 @@
-from __future__ import annotations
-
-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
-
-@dataclass
-class FallbackLocation(LocationProtocol):
- lat: float
- lon: float
- dt: datetime
- 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:
- '''
- by default the start date is used for the location
- If end is True, the start date + duration is used
- '''
- dt: datetime = self.dt
- if end and self.duration is not None:
- dt += timedelta(self.duration)
- return Location(
- lat=self.lat,
- lon=self.lon,
- dt=dt,
- accuracy=self.accuracy,
- elevation=self.elevation,
- datasource=self.datasource,
- )
-
- @classmethod
- def from_end_date(
- cls,
- *,
- lat: float,
- lon: float,
- dt: datetime,
- end_dt: datetime,
- accuracy: float | None = None,
- elevation: float | None = None,
- datasource: str | None = None,
- ) -> FallbackLocation:
- '''
- Create FallbackLocation from a start date and an end date
- '''
- if end_dt < dt:
- raise ValueError("end_date must be after dt")
- duration = (end_dt - dt).total_seconds()
- return cls(
- lat=lat,
- lon=lon,
- dt=dt,
- duration=duration,
- accuracy=accuracy,
- elevation=elevation,
- datasource=datasource,
- )
-
-
-# a location estimator can return multiple fallbacks, in case there are
-# differing accuracies/to allow for possible matches to be computed
-# iteratively
-LocationEstimator = Callable[[DateExact], Iterator[FallbackLocation]]
-LocationEstimators = Sequence[LocationEstimator]
-
-# helper function, instead of dealing with datetimes while comparing, just use epoch timestamps
-def _datetime_timestamp(dt: DateExact) -> float:
- if isinstance(dt, datetime):
- try:
- return dt.timestamp()
- except ValueError:
- # https://github.com/python/cpython/issues/75395
- return dt.replace(tzinfo=timezone.utc).timestamp()
- return float(dt)
-
-def _iter_estimate_from(
- dt: DateExact,
- estimators: LocationEstimators,
-) -> Iterator[FallbackLocation]:
- for est in estimators:
- yield from est(dt)
-
-
-def estimate_from(
- dt: DateExact,
- estimators: LocationEstimators,
- *,
- first_match: bool = False,
- 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] = []
- 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
- if first_match:
- return loc
- found.append(loc)
-
- if not found:
- return None
-
- # if all items have accuracy, return the one with the lowest accuracy
- # otherwise, we should prefer the order that the estimators are passed in as
- if all(loc.accuracy is not None for loc in found):
- # return the location with the lowest accuracy
- return min(found, key=lambda loc: loc.accuracy) # type: ignore[return-value, arg-type]
- else:
- # return the first location
- return found[0]
diff --git a/my/location/fallback/via_home.py b/my/location/fallback/via_home.py
deleted file mode 100644
index f88fee0..0000000
--- a/my/location/fallback/via_home.py
+++ /dev/null
@@ -1,101 +0,0 @@
-'''
-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 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
-
-
-@dataclass
-class Config(user_config):
- home: LatLon | Sequence[tuple[DateIsh, LatLon]]
-
- # default ~30km accuracy
- # this is called 'home_accuracy' since it lives on the base location.config object,
- # to differentiate it from accuracy for other providers
- home_accuracy: float = 30_000.0
-
- # TODO could make current Optional and somehow determine from system settings?
- @property
- 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]]
- if isinstance(home1[0], tuple):
- # already a sequence
- 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)
- home2 = [(datetime.min, loc)]
-
- # todo cache?
- res = []
- for x, loc in home2:
- dt: datetime
- if isinstance(x, str):
- dt = datetime.fromisoformat(x)
- elif isinstance(x, datetime):
- dt = x
- else:
- dt = datetime.combine(x, time.min)
- # todo not sure about doing it here, but makes it easier to compare..
- if dt.tzinfo is None:
- dt = dt.replace(tzinfo=timezone.utc)
- res.append((dt, loc))
- res = sorted(res, key=lambda p: p[0])
- return res
-
-
-from ...core.cfg import make_config
-
-config = make_config(Config)
-
-
-@cache
-def get_location(dt: datetime) -> LatLon:
- '''
- Interpolates the location at dt
- '''
- loc = list(estimate_location(dt))
- assert len(loc) == 1
- return loc[0].lat, loc[0].lon
-
-
-# TODO: in python3.8, use functools.cached_property instead?
-@cache
-def homes_cached() -> list[tuple[datetime, LatLon]]:
- return list(config._history)
-
-
-def estimate_location(dt: DateExact) -> Iterator[FallbackLocation]:
- from my.location.fallback.common import _datetime_timestamp
- d: float = _datetime_timestamp(dt)
- hist = list(reversed(homes_cached()))
- for pdt, (lat, lon) in hist:
- if d >= pdt.timestamp():
- 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/location/fallback/via_ip.py b/my/location/fallback/via_ip.py
deleted file mode 100644
index 8b50878..0000000
--- a/my/location/fallback/via_ip.py
+++ /dev/null
@@ -1,102 +0,0 @@
-"""
-Converts IP addresses provided by my.location.ip to estimated locations
-"""
-
-REQUIRES = ["git+https://github.com/purarue/ipgeocache"]
-
-from dataclasses import dataclass
-from datetime import timedelta
-
-from my.config import location
-from my.core import Stats, make_config
-from my.core.warnings import medium
-
-
-@dataclass
-class ip_config(location.via_ip):
- # no real science to this, just a guess of ~15km accuracy for IP addresses
- accuracy: float = 15_000.0
- # default to being accurate for a day
- for_duration: timedelta = timedelta(hours=24)
-
-
-# TODO: move config to location.fallback.via_location instead and add migration
-config = make_config(ip_config)
-
-
-from collections.abc import Iterator
-from functools import lru_cache
-
-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 DateExact, FallbackLocation, _datetime_timestamp
-
-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
- yield FallbackLocation(
- lat=lat,
- lon=lon,
- dt=ip.dt,
- accuracy=config.accuracy,
- duration=dur,
- elevation=None,
- datasource="via_ip",
- )
-
-
-# for compatibility with my.location.via_ip, this shouldn't be used by other modules
-def locations() -> Iterator[Location]:
- medium("locations is deprecated, should use fallback_locations or estimate_location")
- yield from map(FallbackLocation.to_location, fallback_locations())
-
-
-@lru_cache(1)
-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())
- return fl
-
-
-def estimate_location(dt: DateExact) -> Iterator[FallbackLocation]:
- # logger.debug(f"Estimating location for: {dt}")
- fl = _sorted_fallback_locations()
- dt_ts = _datetime_timestamp(dt)
-
- # search to find the first possible location which contains dt (something that started up to
- # config.for_duration ago, and ends after dt)
- idx = bisect_left(fl, dt_ts - config.for_duration.total_seconds(), key=lambda l: l.dt.timestamp())
-
- # all items are before the given dt
- if idx == len(fl):
- return
-
- # iterate through in sorted order, until we find a location that is after the given dt
- while idx < len(fl):
- loc = fl[idx]
- start_time = loc.dt.timestamp()
- # loc.duration is filtered for in _sorted_fallback_locations
- end_time = start_time + loc.duration # type: ignore[operator]
- if start_time <= dt_ts <= end_time:
- # logger.debug(f"Found location for {dt}: {loc}")
- yield loc
- # no more locations could possibly contain dt
- if start_time > dt_ts:
- # logger.debug(f"Passed start time: {end_time} > {dt_ts} ({datetime.fromtimestamp(end_time)} > {datetime.fromtimestamp(dt_ts)})")
- break
- idx += 1
-
-
-def stats() -> Stats:
- from my.core import stat
-
- return {**stat(locations)}
diff --git a/my/location/google.py b/my/location/google.py
index 750c847..f196301 100644
--- a/my/location/google.py
+++ b/my/location/google.py
@@ -1,30 +1,24 @@
"""
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 PIPE, Popen
-from typing import IO, NamedTuple, Optional
+from subprocess import Popen, PIPE
+from typing import Iterable, NamedTuple, Optional, Sequence, IO, Tuple
+import re
# pip3 install geopy
-import geopy # type: ignore
+import geopy # type: ignore
-from my.core import Stats, make_logger, stat, warnings
-from my.core.cachew import cache_dir, mcachew
-
-warnings.high("Please set up my.google.takeout.parser module for better takeout support")
+from ..core.common import LazyLogger, mcachew
+from ..core.cachew import cache_dir
+from ..core import kompress
# otherwise uses ijson
@@ -32,7 +26,7 @@ warnings.high("Please set up my.google.takeout.parser module for better takeout
USE_GREP = False
-logger = make_logger(__name__)
+logger = LazyLogger(__name__)
class Location(NamedTuple):
@@ -42,7 +36,7 @@ class Location(NamedTuple):
alt: Optional[float]
-TsLatLon = tuple[int, int, int]
+TsLatLon = Tuple[int, int, int]
def _iter_via_ijson(fo) -> Iterable[TsLatLon]:
@@ -50,10 +44,11 @@ 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 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")
+ import ijson # type: ignore
for d in ijson.items(fo, 'locations.item'):
yield (
@@ -80,7 +75,7 @@ def _iter_via_grep(fo) -> Iterable[TsLatLon]:
# todo could also use pool? not sure if that would really be faster...
-# search thread could process 100K at once?
+# earch thread could process 100K at once?
# would need to find out a way to know when to stop? process in some sort of sqrt progression??
@@ -104,8 +99,7 @@ def _iter_locations_fo(fit) -> Iterable[Location]:
errors += 1
if float(errors) / total > 0.01:
# todo make defensive?
- # todo exceptiongroup?
- raise RuntimeError('too many errors! aborting') # noqa: B904
+ raise RuntimeError('too many errors! aborting')
else:
continue
@@ -134,7 +128,7 @@ def _iter_locations(path: Path, start=0, stop=None) -> Iterable[Location]:
ctx = path.open('r')
else: # must be a takeout archive
# todo CPath? although not sure if it can be iterative?
- ctx = (path / _LOCATION_JSON).open()
+ ctx = kompress.open(path, _LOCATION_JSON)
if USE_GREP:
unzip = f'unzip -p "{path}" "{_LOCATION_JSON}"'
@@ -164,6 +158,7 @@ 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
deleted file mode 100644
index 8613257..0000000
--- a/my/location/google_takeout.py
+++ /dev/null
@@ -1,38 +0,0 @@
-"""
-Extracts locations using google_takeout_parser -- no shared code with the deprecated my.location.google
-"""
-
-REQUIRES = ["git+https://github.com/purarue/google_takeout_parser"]
-
-from collections.abc import Iterator
-
-from google_takeout_parser.models import Location as GoogleLocation
-
-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__)
-
-
-@mcachew(
- depends_on=_cachew_depends_on,
- logger=logger,
-)
-def locations() -> Iterator[Location]:
- for g in events():
- if isinstance(g, GoogleLocation):
- yield Location(
- lon=g.lng,
- lat=g.lat,
- dt=g.dt,
- accuracy=g.accuracy,
- elevation=None,
- datasource="google_takeout",
- )
-
-
-def stats() -> Stats:
- return stat(locations)
diff --git a/my/location/google_takeout_semantic.py b/my/location/google_takeout_semantic.py
deleted file mode 100644
index e84a932..0000000
--- a/my/location/google_takeout_semantic.py
+++ /dev/null
@@ -1,79 +0,0 @@
-"""
-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/purarue/google_takeout_parser"]
-
-from collections.abc import Iterator
-from dataclasses import dataclass
-
-from google_takeout_parser.models import PlaceVisit as SemanticLocation
-
-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
- # set to 0 to include all locations
- # https://locationhistoryformat.com/reference/semantic/#/$defs/placeVisit/properties/locationConfidence
- require_confidence: int = 40
- # default accuracy for semantic locations
- accuracy: float = 100.0
-
-
-config = make_config(semantic_locations_config)
-
-
-# add config to cachew dependency so it recomputes on config changes
-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
-
-
-
-@mcachew(
- depends_on=_cachew_depends_on,
- logger=logger,
-)
-def locations() -> Iterator[Res[Location]]:
- require_confidence = config.require_confidence
- if require_confidence < 0 or require_confidence > 100:
- yield ValueError("location.google_takeout.semantic_require_confidence must be between 0 and 100")
- return
-
- for g in events():
- if isinstance(g, SemanticLocation):
- 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,
- lat=g.lat,
- dt=g.dt,
- # can accuracy be inferred from visitConfidence?
- # there's no exact distance value in the data, its a 0-100% confidence value...
- accuracy=config.accuracy,
- elevation=None,
- datasource="google_takeout_semantic",
- )
-
-
-
-def stats() -> Stats:
- return stat(locations)
diff --git a/my/location/gpslogger.py b/my/location/gpslogger.py
deleted file mode 100644
index bbbf70e..0000000
--- a/my/location/gpslogger.py
+++ /dev/null
@@ -1,91 +0,0 @@
-"""
-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
-class config(location.gpslogger):
- # path[s]/glob to the synced gpx (XML) files
- export_path: Paths
-
- # default accuracy for gpslogger
- accuracy: float = 50.0
-
-
-from collections.abc import Iterator, Sequence
-from datetime import datetime, timezone
-from itertools import chain
-from pathlib import Path
-
-import gpxpy
-from gpxpy.gpx import GPXXMLSyntaxException
-from more_itertools import unique_everseen
-
-from my.core import LazyLogger, Stats
-from my.core.cachew import mcachew
-from my.core.common import get_files
-
-from .common import Location
-
-logger = LazyLogger(__name__, level="warning")
-
-def _input_sort_key(path: Path) -> str:
- if "_" in path.name:
- return path.name.split("_", maxsplit=1)[1]
- return path.name
-
-
-def inputs() -> Sequence[Path]:
- # gpslogger files can optionally be prefixed by a device id,
- # like b5760c66102a5269_20211214142156.gpx
- return sorted(get_files(config.export_path, glob="*.gpx", sort=False), key=_input_sort_key)
-
-
-def _cachew_depends_on() -> list[float]:
- return [p.stat().st_mtime for p in inputs()]
-
-
-# TODO: could use a better cachew key/this has to recompute every file whenever the newest one changes
-@mcachew(depends_on=_cachew_depends_on, logger=logger)
-def locations() -> Iterator[Location]:
- yield from unique_everseen(
- chain(*map(_extract_locations, inputs())), key=lambda loc: loc.dt
- )
-
-
-def _extract_locations(path: Path) -> Iterator[Location]:
- with path.open("r") as 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:
- if point.time is None:
- continue
- # hmm - for gpslogger, seems that timezone is always SimpleTZ('Z'), which
- # specifies UTC -- see https://github.com/tkrajina/gpxpy/blob/cb243b22841bd2ce9e603fe3a96672fc75edecf2/gpxpy/gpxfield.py#L38
- yield Location(
- lat=point.latitude,
- lon=point.longitude,
- accuracy=config.accuracy,
- elevation=point.elevation,
- dt=datetime.replace(point.time, tzinfo=timezone.utc),
- datasource="gpslogger",
- )
-
-
-def stats() -> Stats:
- from my.core import stat
-
- return {**stat(locations)}
diff --git a/my/location/home.py b/my/location/home.py
index c82dda7..dd7209f 100644
--- a/my/location/home.py
+++ b/my/location/home.py
@@ -1,7 +1,75 @@
-from my.core.warnings import high
+'''
+Simple location provider, serving as a fallback when more detailed data isn't available
+'''
+from dataclasses import dataclass
+from datetime import datetime, date, time, timezone
+from functools import lru_cache
+from typing import Sequence, Tuple, Union, cast
-from .fallback.via_home import *
+from my.config import location as user_config
-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"
-)
+
+DateIsh = Union[datetime, date, str]
+
+# todo hopefully reasonable? might be nice to add name or something too
+LatLon = Tuple[float, float]
+
+@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
+ ]]
+ ]
+ # TODO could make current Optional and somehow determine from system settings?
+ @property
+ 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]]
+ if isinstance(home1[0], tuple):
+ # already a sequence
+ 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)
+ home2 = [(datetime.min, loc)]
+
+ # todo cache?
+ res = []
+ for x, loc in home2:
+ dt: datetime
+ if isinstance(x, str):
+ dt = datetime.fromisoformat(x)
+ elif isinstance(x, datetime):
+ dt = x
+ else:
+ dt = datetime.combine(x, time.min)
+ # todo not sure about doing it here, but makes it easier to compare..
+ if dt.tzinfo is None:
+ dt = dt.replace(tzinfo=timezone.utc)
+ res.append((dt, loc))
+ res = list(sorted(res, key=lambda p: p[0]))
+ return res
+
+
+from ..core.cfg import make_config
+config = make_config(Config)
+
+
+@lru_cache(maxsize=None)
+def get_location(dt: datetime) -> LatLon:
+ '''
+ Interpolates the location at dt
+ '''
+ if dt.tzinfo is None:
+ dt = dt.replace(tzinfo=timezone.utc)
+ hist = list(reversed(config._history))
+ for pdt, loc in hist:
+ if dt >= pdt:
+ return loc
+ else:
+ # I guess the most reasonable is to fallback on the first location
+ return hist[-1][1]
diff --git a/my/location/via_ip.py b/my/location/via_ip.py
deleted file mode 100644
index 240ec5f..0000000
--- a/my/location/via_ip.py
+++ /dev/null
@@ -1,7 +0,0 @@
-REQUIRES = ["git+https://github.com/purarue/ipgeocache"]
-
-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 45af3f9..8a6a997 100644
--- a/my/materialistic.py
+++ b/my/materialistic.py
@@ -1,5 +1,4 @@
from .core.warnings import high
-
high("DEPRECATED! Please use my.hackernews.materialistic instead.")
from .hackernews.materialistic import *
diff --git a/doc/overlays/overlay/src/my/py.typed b/my/media/__init__.py
similarity index 100%
rename from doc/overlays/overlay/src/my/py.typed
rename to my/media/__init__.py
diff --git a/my/media/imdb.py b/my/media/imdb.py
index 131f6a7..c7d5299 100644
--- a/my/media/imdb.py
+++ b/my/media/imdb.py
@@ -1,15 +1,14 @@
+#!/usr/bin/env python3
import csv
-from collections.abc import Iterator
from datetime import datetime
-from typing import NamedTuple
+from typing import Iterator, List, NamedTuple
-from my.core import get_files
-
-from my.config import imdb as config # isort: skip
+from ..common import get_files
+from my.config import imdb as config
def _get_last():
- return max(get_files(config.export_path))
+ return max(get_files(config.export_path, glob='*.csv'))
class Movie(NamedTuple):
@@ -23,7 +22,7 @@ def iter_movies() -> Iterator[Movie]:
with last.open() as fo:
reader = csv.DictReader(fo)
- for line in reader:
+ for i, line in enumerate(reader):
# TODO extract directors??
title = line['Title']
rating = int(line['You rated'])
@@ -33,9 +32,17 @@ def iter_movies() -> Iterator[Movie]:
yield Movie(created=created, title=title, rating=rating)
-def get_movies() -> list[Movie]:
- return sorted(iter_movies(), key=lambda m: m.created)
+def get_movies() -> List[Movie]:
+ return list(sorted(iter_movies(), key=lambda m: m.created))
def test():
assert len(get_movies()) > 10
+
+
+def main():
+ for movie in get_movies():
+ print(movie)
+
+if __name__ == '__main__':
+ main()
diff --git a/my/media/youtube.py b/my/media/youtube.py
old mode 100644
new mode 100755
index 9a38c43..8212f12
--- a/my/media/youtube.py
+++ b/my/media/youtube.py
@@ -1,10 +1,43 @@
-from my.core import __NOT_HPI_MODULE__ # isort: skip
+#!/usr/bin/env python3
+from datetime import datetime
+from typing import NamedTuple, List, Iterable
-from typing import TYPE_CHECKING
+from ..google.takeout.html import read_html
+from ..google.takeout.paths import get_last_takeout
-from my.core.warnings import high
-high("DEPRECATED! Please use my.youtube.takeout instead.")
+class Watched(NamedTuple):
+ url: str
+ title: str
+ when: datetime
+
+ @property
+ def eid(self) -> str:
+ return f'{self.url}-{self.when.isoformat()}'
+
+
+def watched() -> Iterable[Watched]:
+ # TODO need to use a glob? to make up for old takouts that didn't start with Takeout/
+ path = 'Takeout/My Activity/YouTube/MyActivity.html' # looks like this one doesn't have retention? so enough to use the last
+ # TODO YouTube/history/watch-history.html, also YouTube/history/watch-history.json
+ 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))
+
+ # TODO hmm they already come sorted.. wonder if should just rely on it..
+ return list(sorted(watches, key=lambda e: e.when))
+
+
+from ..core import stat, Stats
+def stats() -> Stats:
+ return stat(watched)
+
+
+# todo deprecate
+get_watched = watched
-if not TYPE_CHECKING:
- from my.youtube.takeout import *
diff --git a/my/monzo/monzoexport.py b/my/monzo/monzoexport.py
deleted file mode 100644
index f5e1cd1..0000000
--- a/my/monzo/monzoexport.py
+++ /dev/null
@@ -1,46 +0,0 @@
-"""
-Monzo transactions data (using https://github.com/karlicoss/monzoexport )
-"""
-REQUIRES = [
- 'git+https://github.com/karlicoss/monzoexport',
-]
-
-from collections.abc import Iterator, Sequence
-from dataclasses import dataclass
-from pathlib import Path
-
-from my.core import (
- Paths,
- get_files,
- make_logger,
-)
-
-import my.config # isort: skip
-
-
-@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/my/orgmode.py b/my/orgmode.py
index 10f53c0..d6d31d2 100644
--- a/my/orgmode.py
+++ b/my/orgmode.py
@@ -1,62 +1,48 @@
'''
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 NamedTuple, Optional
+import re
+from typing import List, Sequence, Iterable, NamedTuple, Optional, Tuple
-import orgparse
-
-from my.core import Paths, Stats, get_files, stat
-from my.core.cachew import cache_dir, mcachew
+from my.core import get_files
+from my.core.common import mcachew
+from my.core.cachew import cache_dir
from my.core.orgmode import collect
+from my.config import orgmode as user_config
-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()
+import orgparse
# temporary? hack to cache org-mode notes
class OrgNote(NamedTuple):
created: Optional[datetime]
heading: str
- tags: list[str]
+ tags: List[str]
def inputs() -> Sequence[Path]:
- cfg = make_config()
- return get_files(cfg.paths)
+ return get_files(user_config.paths)
_rgx = re.compile(orgparse.date.gene_timestamp_regex(brtype='inactive'), re.VERBOSE)
-
-
-def _created(n: orgparse.OrgNode) -> tuple[datetime | None, str]:
+def _created(n: orgparse.OrgNode) -> Tuple[Optional[datetime], str]:
heading = n.heading
# meh.. support in orgparse?
- pp = {} if n.is_root() else n.properties
+ pp = {} if n.is_root() else n.properties # type: ignore
createds = pp.get('CREATED', None)
if createds is None:
# 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)
@@ -70,7 +56,7 @@ def _created(n: orgparse.OrgNode) -> tuple[datetime | None, str]:
def to_note(x: orgparse.OrgNode) -> OrgNote:
# ugh. hack to merely make it cacheable
heading = x.heading
- created: datetime | None
+ created: Optional[datetime]
try:
c, heading = _created(x)
if isinstance(c, datetime):
@@ -82,7 +68,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),
)
@@ -92,23 +78,14 @@ def _sanitize(p: Path) -> str:
return re.sub(r'\W', '_', str(p))
-def _cachew_cache_path(_self, f: Path) -> Path:
- return cache_dir() / 'orgmode' / _sanitize(f)
-
-
-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,
- depends_on=_cachew_depends_on,
+ cache_path=lambda _, f: cache_dir() / 'orgmode' / _sanitize(f), force_file=True,
+ depends_on=lambda _, f: (f, f.stat().st_mtime),
)
def _iterate(self, f: Path) -> Iterable[OrgNote]:
o = orgparse.load(f)
@@ -130,8 +107,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
old mode 100644
new mode 100755
index eefd573..1314f0e
--- a/my/pdfs.py
+++ b/my/pdfs.py
@@ -1,66 +1,63 @@
'''
PDF documents and annotations on your filesystem
'''
-from __future__ import annotations as _annotations
-
REQUIRES = [
'git+https://github.com/0xabu/pdfannots',
# todo not sure if should use pypi version?
]
-import time
-from collections.abc import Iterator, Sequence
from datetime import datetime
+from dataclasses import dataclass
+import io
from pathlib import Path
-from typing import TYPE_CHECKING, NamedTuple, Optional, Protocol
+import time
+from typing import NamedTuple, List, Optional, Iterator, Sequence
-import pdfannots
-from more_itertools import bucket
-from my.core import PathIsh, Paths, Stats, get_files, make_logger, stat
-from my.core.cachew import mcachew
+from my.core import LazyLogger, get_files, Paths, PathIsh
+from my.core.cfg import Attrs, make_config
+from my.core.common import mcachew, group_by_key
from my.core.error import Res, split_errors
-class config(Protocol):
- @property
- def paths(self) -> Paths:
- return () # allowed to be empty for 'filelist' logic
+import pdfannots
- def is_ignored(self, p: Path) -> bool: # noqa: ARG002
+
+from my.config import pdfs as user_config
+
+@dataclass
+class pdfs(user_config):
+ paths: Paths = () # allowed to be empty for 'filelist' logic
+
+ def is_ignored(self, p: Path) -> bool:
"""
- You can override this in user config if you want to ignore some files that are tooheavy
+ 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
"""
+ user_ignore = getattr(user_config, 'is_ignored', None)
+ if user_ignore is not None:
+ return user_ignore(p)
+
return False
-
-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()
+ @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
-logger = make_logger(__name__)
+config = make_config(pdfs, migration=pdfs._migration)
+logger = LazyLogger(__name__)
def inputs() -> Sequence[Path]:
- cfg = make_config()
- all_files = get_files(cfg.paths, glob='**/*.pdf')
- return [p for p in all_files if not cfg.is_ignored(p)]
+ all_files = get_files(config.paths, glob='**/*.pdf')
+ return [p for p in all_files if not config.is_ignored(p)]
# TODO canonical names/fingerprinting?
@@ -74,7 +71,7 @@ class Annotation(NamedTuple):
created: Optional[datetime] # note: can be tz unaware in some bad pdfs...
@property
- def date(self) -> datetime | None:
+ def date(self) -> Optional[datetime]:
# legacy name
return self.created
@@ -82,7 +79,7 @@ class Annotation(NamedTuple):
def _as_annotation(*, raw: pdfannots.Annotation, path: str) -> Annotation:
d = vars(raw)
pos = raw.pos
- # make mypy happy (pos always present for Annotation https://github.com/0xabu/pdfannots/blob/dbdfefa158971e1746fae2da139918e9f59439ea/pdfannots/types.py#L302)
+ # make mypy happy (pos alwasy present for Annotation https://github.com/0xabu/pdfannots/blob/dbdfefa158971e1746fae2da139918e9f59439ea/pdfannots/types.py#L302)
assert pos is not None
d['page'] = pos.page.pageno
return Annotation(
@@ -95,11 +92,11 @@ 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)
- annots = list(doc.iter_annots())
+ annots = [a for a in doc.iter_annots()]
# also has outlines are kinda like TOC, I don't really need them
a = time.time()
took = a - b
@@ -123,13 +120,14 @@ 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
-
+ from my.core.common 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()
@@ -152,41 +150,40 @@ class Pdf(NamedTuple):
annotations: Sequence[Annotation]
@property
- def created(self) -> datetime | None:
+ def created(self) -> Optional[datetime]:
annots = self.annotations
return None if len(annots) == 0 else annots[-1].created
@property
- def date(self) -> datetime | None:
+ def date(self) -> Optional[datetime]:
# legacy
return self.created
-def annotated_pdfs(*, filelist: Sequence[PathIsh] | None = 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
- from my.config import pdfs as user_config
-
- user_config.paths = filelist
+ config.paths = filelist
ait = annotations()
vit, eit = split_errors(ait, ET=Exception)
- bucketed = bucket(vit, key=lambda a: a.path)
- for k in bucketed:
- g = list(bucketed[k])
+ for k, g in group_by_key(vit, key=lambda a: a.path).items():
yield Pdf(path=Path(k), annotations=g)
yield from eit
+from my.core import stat, Stats
def stats() -> Stats:
return {
- **stat(annotations),
+ **stat(annotations) ,
**stat(annotated_pdfs),
}
### legacy/misc stuff
-if not TYPE_CHECKING:
- iter_annotations = annotations
+iter_annotations = annotations # for backwards compatibility
###
+
+# can use 'hpi query my.pdfs.annotations -o pprint' to test
+#
diff --git a/my/photos/main.py b/my/photos/main.py
index f98cb15..6be3163 100644
--- a/my/photos/main.py
+++ b/my/photos/main.py
@@ -1,30 +1,26 @@
"""
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 NamedTuple, Optional
+from typing import Optional, NamedTuple, Iterator, Iterable, List
-from geopy.geocoders import Nominatim # type: ignore
+from geopy.geocoders import Nominatim # type: ignore
-from my.core import LazyLogger
-from my.core.cachew import cache_dir, mcachew
-from my.core.error import Res, sort_res_by
-from my.core.mime import fastermime
+from ..core.common import LazyLogger, mcachew, fastermime
+from ..core.error import Res, sort_res_by
+from ..core.cachew import cache_dir
+
+from my.config import photos as config
-from my.config import photos as config # type: ignore[attr-defined] # isort: skip
logger = LazyLogger(__name__)
@@ -46,7 +42,8 @@ class Photo(NamedTuple):
for bp in config.paths:
if self.path.startswith(bp):
return self.path[len(bp):]
- raise RuntimeError(f"Weird path {self.path}, can't match against anything")
+ else:
+ raise RuntimeError(f'Weird path {self.path}, cant match against anything')
@property
def name(self) -> str:
@@ -58,17 +55,17 @@ class Photo(NamedTuple):
return f'{config.base_url}{self._basename}'
-from .utils import Exif, ExifTags, convert_ref, dt_from_path, get_exif_from_file
+from .utils import get_exif_from_file, ExifTags, Exif, dt_from_path, convert_ref
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: LatLon | None) -> Iterator[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 = {}
@@ -80,7 +77,7 @@ def _make_photo(photo: Path, mtype: str, *, parent_geo: LatLon | None) -> Iterat
yield e
exif = {}
- def _get_geo() -> LatLon | None:
+ def _get_geo() -> Optional[LatLon]:
meta = exif.get(ExifTags.GPSINFO, {})
if ExifTags.LAT in meta and ExifTags.LON in meta:
return LatLon(
@@ -90,7 +87,7 @@ def _make_photo(photo: Path, mtype: str, *, parent_geo: LatLon | None) -> Iterat
return parent_geo
# TODO aware on unaware?
- def _get_dt() -> datetime | None:
+ def _get_dt() -> Optional[datetime]:
edt = exif.get(ExifTags.DATETIME, None)
if edt is not None:
dtimes = edt.replace(' 24', ' 00') # jeez maybe log it?
@@ -126,7 +123,7 @@ def _make_photo(photo: Path, mtype: str, *, parent_geo: LatLon | None) -> Iterat
def _candidates() -> Iterable[Res[str]]:
# TODO that could be a bit slow if there are to many extra files?
- from subprocess import PIPE, Popen
+ from subprocess import Popen, PIPE
# 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
@@ -165,7 +162,7 @@ def _photos(candidates: Iterable[Res[str]]) -> Iterator[Result]:
from functools import lru_cache
@lru_cache(None)
- def get_geo(d: Path) -> LatLon | None:
+ def get_geo(d: Path) -> Optional[LatLon]:
geof = d / 'geo.json'
if not geof.exists():
if d == d.parent:
@@ -211,13 +208,11 @@ def print_all() -> None:
if isinstance(p, Exception):
print('ERROR!', p)
else:
- print(f"{p.dt!s:25} {p.path} {p.geo}")
+ print(f"{str(p.dt):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?
from ..core import Stats, stat
-
-
def stats() -> Stats:
return stat(photos)
diff --git a/my/photos/utils.py b/my/photos/utils.py
index e88def2..15d7659 100644
--- a/my/photos/utils.py
+++ b/my/photos/utils.py
@@ -1,13 +1,11 @@
-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 GPSTAGS, TAGS
+import PIL.Image # type: ignore
+from PIL.ExifTags import TAGS, GPSTAGS # type: ignore
-Exif = dict
+
+Exif = Dict
# TODO PIL.ExifTags.TAGS
@@ -50,7 +48,7 @@ def _get_exif_data(image) -> Exif:
def to_degree(value) -> float:
"""Helper function to convert the GPS coordinates
- stored in the EXIF to digress in float format"""
+ stored in the EXIF to degress in float format"""
(d, m, s) = value
return d + (m / 60.0) + (s / 3600.0)
@@ -64,15 +62,18 @@ 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
+# TODO this belogs 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) -> datetime | None:
+def dt_from_path(p: Path) -> Optional[datetime]:
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 e98dc78..354f15c 100644
--- a/my/pinboard.py
+++ b/my/pinboard.py
@@ -5,35 +5,22 @@ REQUIRES = [
'git+https://github.com/karlicoss/pinbexport',
]
-from collections.abc import Iterator, Sequence
-from dataclasses import dataclass
-from pathlib import Path
+from my.config import pinboard as 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?
- # 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:
- return pinbexport.DAL(inputs())
+ from .core import get_files
+ inputs = get_files(config.export_dir) # todo rename to export_path
+ model = pinbexport.DAL(inputs)
+ return model
-def bookmarks() -> Iterator[Res[pinbexport.Bookmark]]:
+from typing import Iterable
+def bookmarks() -> Iterable[pinbexport.Bookmark]:
return dal().bookmarks()
diff --git a/my/pocket.py b/my/pocket.py
index ff9a788..912806d 100644
--- a/my/pocket.py
+++ b/my/pocket.py
@@ -5,12 +5,11 @@ REQUIRES = [
'git+https://github.com/karlicoss/pockexport',
]
from dataclasses import dataclass
-from typing import TYPE_CHECKING
-
-from my.config import pocket as user_config
from .core import Paths
+from my.config import pocket as user_config
+
@dataclass
class pocket(user_config):
@@ -23,22 +22,20 @@ class pocket(user_config):
from .core.cfg import make_config
-
config = make_config(pocket)
try:
from pockexport import dal
except ModuleNotFoundError as e:
- from my.core.hpi_compat import pre_pip_dal_handler
-
+ from .core.compat import pre_pip_dal_handler
dal = pre_pip_dal_handler('pockexport', e, config, requires=REQUIRES)
############################
Article = dal.Article
-from collections.abc import Iterable, Sequence
+from typing import Sequence, Iterable
# todo not sure if should be defensive against empty?
@@ -52,12 +49,9 @@ def articles() -> Iterable[Article]:
yield from _dal().articles()
-from .core import Stats, stat
-
-
+from .core import stat, Stats
def stats() -> Stats:
from itertools import chain
-
from more_itertools import ilen
return {
**stat(articles),
@@ -66,7 +60,5 @@ def stats() -> Stats:
# todo deprecate?
-if not TYPE_CHECKING:
- # "deprecate" by hiding from mypy
- def get_articles() -> Sequence[Article]:
- return list(articles())
+def get_articles() -> Sequence[Article]:
+ return list(articles())
diff --git a/my/polar.py b/my/polar.py
old mode 100644
new mode 100755
index 2172014..2218c29
--- a/my/polar.py
+++ b/my/polar.py
@@ -1,14 +1,12 @@
"""
[[https://github.com/burtonator/polar-bookshelf][Polar]] articles and highlights
"""
-from __future__ import annotations
-
from pathlib import Path
-from typing import TYPE_CHECKING, cast
+from typing import cast, TYPE_CHECKING
-import my.config # isort: skip
-# todo use something similar to tz.via_location for config fallback
+import my.config
+
if not TYPE_CHECKING:
user_config = getattr(my.config, 'polar', None)
else:
@@ -21,36 +19,32 @@ if user_config is None:
pass
-from dataclasses import dataclass
-
from .core import PathIsh
-
-
+from dataclasses import dataclass
@dataclass
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() # noqa: RUF009
+ polar_dir: PathIsh = Path('~/.polar').expanduser()
defensive: bool = True # pass False if you want it to fail faster on errors (useful for debugging)
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
-import json
-from collections.abc import Iterable, Sequence
from datetime import datetime
-from typing import NamedTuple
+from typing import List, Dict, Iterable, NamedTuple, Sequence, Optional
+import json
+
+from .core import LazyLogger, Json
+from .core.common import isoparse
+from .error import Res, echain, sort_res_by
+from .core.konsume import wrap, Zoomable, Wdict
-from .core import Json, LazyLogger, Res
-from .core.compat import fromisoformat
-from .core.error import echain, sort_res_by
-from .core.konsume import Wdict, Zoomable, wrap
logger = LazyLogger(__name__)
@@ -70,7 +64,7 @@ class Highlight(NamedTuple):
comments: Sequence[Comment]
tags: Sequence[str]
page: int # 1-indexed
- color: str | None = None
+ color: Optional[str] = None
Uid = str
@@ -78,7 +72,7 @@ class Book(NamedTuple):
created: datetime
uid: Uid
path: Path
- title: str | None
+ title: Optional[str]
# TODO hmmm. I think this needs to be defensive as well...
# think about it later.
items: Sequence[Highlight]
@@ -114,7 +108,7 @@ class Loader:
# TODO something nicer?
notes = meta['notes'].zoom()
else:
- notes = []
+ notes = [] # TODO FIXME dict?
comments = list(meta['comments'].zoom().values()) if 'comments' in meta else []
meta['questions'].zoom()
meta['flashcards'].zoom()
@@ -134,7 +128,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()
@@ -150,7 +144,7 @@ class Loader:
cmap[hlid] = ccs
ccs.append(Comment(
cid=cid.value,
- created=fromisoformat(crt.value),
+ created=isoparse(crt.value),
text=html.value, # TODO perhaps coonvert from html to text or org?
))
v.consume()
@@ -168,10 +162,10 @@ 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()):
+ for k, v in list(ht.items()):
ctag = v.zoom()
ctag['id'].consume()
ct = ctag['label'].zoom()
@@ -188,7 +182,7 @@ class Loader:
yield Highlight(
hid=hid,
- created=fromisoformat(crt),
+ created=isoparse(crt),
selection=text,
comments=tuple(comments),
tags=tuple(htags),
@@ -197,14 +191,14 @@ class Loader:
)
h.consume()
- # TODO when I add defensive error policy, support it
+ # TODO FIXME when I add defensive error policy, support it
# if len(cmap) > 0:
# raise RuntimeError(f'Unconsumed comments: {cmap}')
# TODO sort by date?
def load_items(self, metas: Json) -> Iterable[Highlight]:
- for _p, meta in metas.items(): # noqa: PERF102
+ for p, meta in metas.items():
with wrap(meta, throw=not config.defensive) as meta:
yield from self.load_item(meta)
@@ -215,10 +209,10 @@ class Loader:
# TODO konsume here as well?
di = j['docInfo']
added = di['added']
- filename = di['filename']
+ filename = di['filename'] # TODO here
title = di.get('title', None)
tags_dict = di['tags']
- pm = j['pageMetas'] # todo handle this too?
+ pm = j['pageMetas'] # TODO FIXME handle this too
# todo defensive?
tags = tuple(t['label'] for t in tags_dict.values())
@@ -226,7 +220,7 @@ class Loader:
path = Path(config.polar_dir) / 'stash' / filename
yield Book(
- created=fromisoformat(added),
+ created=isoparse(added),
uid=self.uid,
path=path,
title=title,
@@ -247,13 +241,20 @@ 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))
-## deprecated
-if not TYPE_CHECKING:
- # "deprecate" by hiding from mypy
- Error = Exception # for backwards compat with Orger; can remove later
+def main():
+ for e in iter_entries():
+ if isinstance(e, Exception):
+ logger.exception(e)
+ else:
+ logger.info('processed %s', e.uid)
+ for i in e.items:
+ logger.info(i)
+
+
+Error = Exception # for backwards compat with Orger; can remove later
diff --git a/my/reddit/__init__.py b/my/reddit/__init__.py
index 982901a..aadd6a0 100644
--- a/my/reddit/__init__.py
+++ b/my/reddit/__init__.py
@@ -6,27 +6,36 @@ from my.reddit import ...
to:
from my.reddit.all import ...
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.
+https://github.com/karlicoss/HPI/issues/102
"""
-# 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
-# needs to be on the top level (since it's extracted via ast module)
+# For now, including this here, since importing the module
+# causes .rexport to be imported, which requires rexport
REQUIRES = [
'git+https://github.com/karlicoss/rexport',
]
+import re
+import traceback
-from my.core.hpi_compat import handle_legacy_import
+# some hacky traceback to inspect the current stack
+# to see if the user is using the old style of importing
+warn = False
+for f in traceback.extract_stack():
+ line = f.line or '' # just in case it's None, who knows..
-is_legacy_import = handle_legacy_import(
- parent_module_name=__name__,
- legacy_submodule_name='rexport',
- parent_module_path=__path__,
-)
+ # cover the most common ways of previously interacting with the module
+ if 'import my.reddit ' in (line + ' '):
+ warn = True
+ elif 'from my import reddit' in line:
+ warn = True
+ elif re.match(r"from my\.reddit\simport\s(comments|saved|submissions|upvoted)", line):
+ warn = True
-if is_legacy_import:
- # todo not sure if possible to move this into legacy.py
- from .rexport import *
+# TODO: add link to instructions to migrate
+if warn:
+ from my.core import warnings as W
+ W.high("DEPRECATED! Instead of my.reddit, import from my.reddit.all instead.")
+
+
+from .rexport import *
diff --git a/my/reddit/all.py b/my/reddit/all.py
index 27e22df..a668081 100644
--- a/my/reddit/all.py
+++ b/my/reddit/all.py
@@ -1,9 +1,8 @@
-from collections.abc import Iterator
-
-from my.core import Stats, stat
+from typing import Iterator
+from my.core.common import Stats
from my.core.source import import_source
-from .common import Comment, Save, Submission, Upvote, _merge_comments
+from .common import Save, Upvote, Comment, Submission, _merge_comments
# Man... ideally an all.py file isn't this verbose, but
# reddit just feels like that much of a complicated source and
@@ -59,6 +58,7 @@ 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/common.py b/my/reddit/common.py
index 40f9f6e..3bb0279 100644
--- a/my/reddit/common.py
+++ b/my/reddit/common.py
@@ -3,13 +3,21 @@ 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__ # isort: skip
-
-from collections.abc import Iterator
+from typing import Dict, Any, Set, Iterator, TYPE_CHECKING
from itertools import chain
-from typing import Protocol
-from my.core import Json, datetime_aware
+from my.core.common import datetime_aware
+
+Json = Dict[str, Any]
+
+if TYPE_CHECKING:
+ try:
+ from typing import Protocol
+ except ImportError:
+ # requirement of mypy
+ from typing_extensions import Protocol # type: ignore[misc]
+else:
+ Protocol = object
# common fields across all the Protocol classes, so generic code can be written
@@ -51,7 +59,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 12f592b..1c7ec8d 100644
--- a/my/reddit/pushshift.py
+++ b/my/reddit/pushshift.py
@@ -1,27 +1,26 @@
"""
Gives you access to older comments possibly not accessible with rexport
using pushshift
-See https://github.com/purarue/pushshift_comment_export
+See https://github.com/seanbreckenridge/pushshift_comment_export
"""
REQUIRES = [
- "git+https://github.com/purarue/pushshift_comment_export",
+ "git+https://github.com/seanbreckenridge/pushshift_comment_export",
]
+from my.core.common import Paths, Stats
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):
'''
- Uses [[https://github.com/purarue/pushshift_comment_export][pushshift]] to get access to old comments
+ Uses [[https://github.com/seanbreckenridge/pushshift_comment_export][pushshift]] to get access to old comments
'''
# path[s]/glob to the exported JSON data
@@ -29,10 +28,10 @@ class pushshift_config(uconfig.pushshift):
config = make_config(pushshift_config)
-from collections.abc import Iterator, Sequence
+from my.core import get_files
+from typing import Sequence, Iterator
from pathlib import Path
-from my.core import get_files
def inputs() -> Sequence[Path]:
@@ -44,6 +43,7 @@ def comments() -> Iterator[PComment]:
yield from read_file(f)
def stats() -> Stats:
+ from my.core import stat
return {
**stat(comments)
}
diff --git a/my/reddit/rexport.py b/my/reddit/rexport.py
old mode 100644
new mode 100755
index 262635b..e7373cd
--- a/my/reddit/rexport.py
+++ b/my/reddit/rexport.py
@@ -1,32 +1,16 @@
"""
Reddit data: saved items/comments/upvotes/etc.
"""
-from __future__ import annotations
-
REQUIRES = [
'git+https://github.com/karlicoss/rexport',
]
-import inspect
-from collections.abc import Iterator, Sequence
-from dataclasses import dataclass
from pathlib import Path
-from typing import TYPE_CHECKING
+from my.core.common import Paths
+from dataclasses import dataclass
+from typing import Any
-from my.core import (
- Paths,
- Stats,
- get_files,
- make_logger,
- stat,
- warnings,
-)
-from my.core.cachew import mcachew
-from my.core.cfg import Attrs, make_config
-
-from my.config import reddit as uconfig # isort: skip
-
-logger = make_logger(__name__)
+from my.config import reddit as uconfig
@dataclass
@@ -39,6 +23,7 @@ class reddit(uconfig):
export_path: Paths
+from my.core.cfg import make_config, Attrs
# hmm, also nice thing about this is that migration is possible to test without the rest of the config?
def migration(attrs: Attrs) -> Attrs:
# new structure, take top-level config and extract 'rexport' class
@@ -47,29 +32,28 @@ def migration(attrs: Attrs) -> Attrs:
ex: uconfig.rexport = attrs['rexport']
attrs['export_path'] = ex.export_path
else:
- warnings.high(
- """DEPRECATED! Please modify your reddit config to look like:
+ from my.core.warnings import high
+ high("""DEPRECATED! Please modify your reddit config to look like:
class reddit:
class rexport:
export_path: Paths = '/path/to/rexport/data'
- """
- )
+ """)
export_dir = 'export_dir'
- if export_dir in attrs: # legacy name
+ if export_dir in attrs: # legacy name
attrs['export_path'] = attrs[export_dir]
- warnings.high(f'"{export_dir}" is deprecated! Please use "export_path" instead."')
+ high(f'"{export_dir}" is deprecated! Please use "export_path" instead."')
return attrs
-
config = make_config(reddit, migration=migration)
###
+# TODO not sure about the laziness...
+
try:
from rexport import dal
except ModuleNotFoundError as e:
- from my.core.hpi_compat import pre_pip_dal_handler
-
+ from my.core.compat import pre_pip_dal_handler
dal = pre_pip_dal_handler('rexport', e, config, requires=REQUIRES)
# TODO ugh. this would import too early
# but on the other hand we do want to bring the objects into the scope for easier imports, etc. ugh!
@@ -77,42 +61,31 @@ except ModuleNotFoundError as e:
# maybe, the config could dynamically detect change and reimport itself? dunno.
###
+############################
+from typing import List, Sequence, Mapping, Iterator, Any
+from my.core.common import mcachew, get_files, LazyLogger, make_dict, Stats
+
+
+logger = LazyLogger(__name__, level='info')
+
+
+from pathlib import Path
def inputs() -> Sequence[Path]:
return get_files(config.export_path)
-# TODO hmm so maybe these import here are not so great
-# the issue is when the dal is updated (e.g. more types added)
-# then user's state can be inconsistent if they update HPI, but don't update the dal
-# maybe best to keep things begind the DAL after all
-
-# fmt: off
-Uid = dal.Sid # str
-Save = dal.Save
-Comment = dal.Comment
-Submission = dal.Submission
-Upvote = dal.Upvote
-# fmt: on
+Uid = dal.Sid # str
+Save = dal.Save
+Comment = dal.Comment
+Submission = dal.Submission
+Upvote = dal.Upvote
def _dal() -> dal.DAL:
- sources = list(inputs())
-
- ## backwards compatibility (old rexport DAL didn't have cpu_pool argument)
- cpu_pool_arg = 'cpu_pool'
- pass_cpu_pool = cpu_pool_arg in inspect.signature(dal.DAL).parameters
- if pass_cpu_pool:
- from my.core._cpu_pool import get_cpu_pool
-
- kwargs = {cpu_pool_arg: get_cpu_pool()}
- else:
- kwargs = {}
- ##
- return dal.DAL(sources, **kwargs)
-
-
-cache = mcachew(depends_on=inputs)
+ inp = list(inputs())
+ return dal.DAL(inp)
+cache = mcachew(depends_on=inputs, logger=logger) # depends on inputs only
@cache
@@ -135,52 +108,142 @@ def upvoted() -> Iterator[Upvote]:
return _dal().upvoted()
-# uhh.. so with from __future__ import annotations, in principle we don't need updated export
-# (with new entity types for function definitions below)
-# however, cachew (as of 0.14.20231004) will crash during to get_type_hints call with these
-# so we need to make cachew decorating defensive here
-# will need to keep this for some time for backwards compatibility till cachew fix catches up
-if not TYPE_CHECKING:
- # in runtime need to be defensive
- try:
- # here we just check that types are available, we don't actually want to import them
- # fmt: off
- dal.Subreddit # noqa: B018
- dal.Profile # noqa: B018
- dal.Multireddit # noqa: B018
- # fmt: on
- except AttributeError as ae:
- warnings.high(f'{ae} : please update "rexport" installation')
- _cache = lambda f: f
- _USING_NEW_REXPORT = False
+### the rest of the file is some elaborate attempt of restoring favorite/unfavorite times
+
+from typing import Dict, Iterable, Iterator, NamedTuple
+from functools import lru_cache
+import pytz
+import re
+from datetime import datetime
+from multiprocessing import Pool
+
+# TODO hmm. apparently decompressing takes quite a bit of time...
+
+class SaveWithDt(NamedTuple):
+ save: Save
+ backup_dt: datetime
+
+ def __getattr__(self, x):
+ return getattr(self.save, x)
+
+# TODO for future events?
+EventKind = SaveWithDt
+
+
+class Event(NamedTuple):
+ dt: datetime
+ text: str
+ kind: EventKind
+ eid: str
+ title: str
+ url: str
+
+ @property
+ def cmp_key(self):
+ return (self.dt, (1 if 'unfavorited' in self.text else 0))
+
+
+Url = str
+
+def _get_bdate(bfile: Path) -> datetime:
+ RE = re.compile(r'reddit.(\d{14})')
+ stem = bfile.stem
+ stem = stem.replace('T', '').replace('Z', '') # adapt for arctee
+ match = RE.search(stem)
+ assert match is not None
+ bdt = pytz.utc.localize(datetime.strptime(match.group(1), "%Y%m%d%H%M%S"))
+ return bdt
+
+
+def _get_state(bfile: Path) -> Dict[Uid, SaveWithDt]:
+ logger.debug('handling %s', bfile)
+
+ bdt = _get_bdate(bfile)
+
+ saves = [SaveWithDt(save, bdt) for save in dal.DAL([bfile]).saved()]
+ return make_dict(
+ sorted(saves, key=lambda p: p.save.created),
+ key=lambda s: s.save.sid,
+ )
+
+# TODO hmm. think about it.. if we set default backups=inputs()
+# it's called early so it ends up as a global variable that we can't monkey patch easily
+@mcachew(lambda backups: backups)
+def _get_events(backups: Sequence[Path], parallel: bool=True) -> Iterator[Event]:
+ # todo cachew: let it transform return type? so you don't have to write a wrapper for lists?
+
+ prev_saves: Mapping[Uid, SaveWithDt] = {}
+ # TODO suppress first batch??
+ # TODO for initial batch, treat event time as creation time
+
+ states: Iterable[Mapping[Uid, SaveWithDt]]
+ if parallel:
+ with Pool() as p:
+ states = p.map(_get_state, backups)
else:
- _cache = cache
- _USING_NEW_REXPORT = True
-else:
- _cache = cache
+ # also make it lazy...
+ states = map(_get_state, backups)
+ # TODO mm, need to make that iterative too?
+ for i, (bfile, saves) in enumerate(zip(backups, states)):
+ bdt = _get_bdate(bfile)
-@_cache
-def subreddits() -> Iterator[dal.Subreddit]:
- return _dal().subreddits()
+ first = i == 0
+ for key in set(prev_saves.keys()).symmetric_difference(set(saves.keys())):
+ ps = prev_saves.get(key, None)
+ if ps is not None:
+ # TODO use backup date, that is more precise...
+ # eh. I guess just take max and it will always be correct?
+ assert not first
+ yield Event(
+ dt=bdt, # TODO average wit ps.save_dt?
+ text="unfavorited",
+ kind=ps,
+ eid=f'unf-{ps.sid}',
+ url=ps.url,
+ title=ps.title,
+ )
+ else: # already in saves
+ s = saves[key]
+ last_saved = s.backup_dt
+ yield Event(
+ dt=s.created if first else last_saved,
+ text=f"favorited{' [initial]' if first else ''}",
+ kind=s,
+ eid=f'fav-{s.sid}',
+ url=s.url,
+ title=s.title,
+ )
+ prev_saves = saves
-@_cache
-def multireddits() -> Iterator[dal.Multireddit]:
- return _dal().multireddits()
+ # TODO a bit awkward, favorited should compare lower than unfavorited?
-
-@_cache
-def profile() -> dal.Profile:
- return _dal().profile()
+@lru_cache(1)
+def events(*args, **kwargs) -> List[Event]:
+ inp = inputs()
+ # 2.2s for 300 files without cachew
+ # 0.2s for 300 files with cachew
+ evit = _get_events(inp, *args, **kwargs) # type: ignore[call-arg]
+ # todo mypy is confused here and thinks it's iterable of Path? perhaps something to do with mcachew?
+ return list(sorted(evit, key=lambda e: e.cmp_key)) # type: ignore[attr-defined,arg-type]
def stats() -> Stats:
+ from my.core import stat
return {
- # fmt: off
**stat(saved ),
**stat(comments ),
**stat(submissions),
**stat(upvoted ),
- # fmt: on
}
+
+
+def main() -> None:
+ for e in events(parallel=False):
+ print(e)
+
+
+if __name__ == '__main__':
+ main()
+
diff --git a/my/rescuetime.py b/my/rescuetime.py
index 0c9fd28..5d64375 100644
--- a/my/rescuetime.py
+++ b/my/rescuetime.py
@@ -5,17 +5,18 @@ REQUIRES = [
'git+https://github.com/karlicoss/rescuexport',
]
-from collections.abc import Iterable, Sequence
-from datetime import timedelta
from pathlib import Path
+from datetime import timedelta
+from typing import Sequence, Iterable
-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 .core import get_files, LazyLogger
+from .core.common import mcachew
+from .core.error import Res, split_errors
-from my.config import rescuetime as config # isort: skip
+from my.config import rescuetime as config
-logger = make_logger(__name__)
+
+log = LazyLogger(__name__, level='info')
def inputs() -> Sequence[Path]:
@@ -23,14 +24,14 @@ def inputs() -> Sequence[Path]:
import rescuexport.dal as dal
-
DAL = dal.DAL
Entry = dal.Entry
-@mcachew(depends_on=inputs)
+@mcachew(depends_on=lambda: inputs())
def entries() -> Iterable[Res[Entry]]:
dal = DAL(inputs())
+ it = dal.entries()
yield from dal.entries()
@@ -43,12 +44,11 @@ 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())
+from .core import stat, Stats
def stats() -> Stats:
return {
**stat(groups),
@@ -58,42 +58,33 @@ 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 typing import Iterator
from contextlib import contextmanager
-
-
# todo take seed, or what?
@contextmanager
-def fake_data(rows: int=1000) -> Iterator:
+def fake_data(rows: int=1000) -> Iterator[None]:
# todo also disable cachew automatically for such things?
- import json
+ from .core.cachew import disabled_cachew
+ from .core.cfg import override_config
from tempfile import TemporaryDirectory
-
- from my.core.cachew import disabled_cachew
- from my.core.cfg import tmp_config
- with disabled_cachew(), TemporaryDirectory() as td:
+ with disabled_cachew(), override_config(config) as cfg, TemporaryDirectory() as td:
tdir = Path(td)
+ cfg.export_path = tdir
f = tdir / 'rescuetime.json'
+ import json
f.write_text(json.dumps(dal.fake_data_generator(rows=rows)))
-
- class override:
- class rescuetime:
- export_path = tdir
-
- with tmp_config(modules=__name__, config=override) as cfg:
- yield cfg
+ yield
# TODO ok, now it's something that actually could run on CI!
# todo would be kinda nice if doctor could run against the fake data, to have a basic health check of the module?
def fill_influxdb() -> None:
- 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
+ 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
influxdb.fill(it, measurement=__name__)
diff --git a/my/roamresearch.py b/my/roamresearch.py
index 7322774..20a4391 100644
--- a/my/roamresearch.py
+++ b/my/roamresearch.py
@@ -1,24 +1,23 @@
"""
[[https://roamresearch.com][Roam]] data
"""
-from __future__ import annotations
-
-import re
-from collections.abc import Iterator
-from datetime import datetime, timezone
-from itertools import chain
+from datetime import datetime
from pathlib import Path
-from typing import NamedTuple
+from itertools import chain
+import re
+from typing import NamedTuple, Iterator, List, Optional
+
+import pytz
+
+from .core import get_files, LazyLogger, Json
from my.config import roamresearch as config
-from .core import Json, LazyLogger, get_files
-
logger = LazyLogger(__name__)
def last() -> Path:
- return max(get_files(config.export_path))
+ return max(get_files(config.export_path, '*.json'))
class Keys:
@@ -39,7 +38,7 @@ class Node(NamedTuple):
def created(self) -> datetime:
ct = self.raw.get(Keys.CREATED)
if ct is not None:
- return datetime.fromtimestamp(ct / 1000, tz=timezone.utc)
+ return datetime.fromtimestamp(ct / 1000, tz=pytz.utc)
# ugh. daily notes don't have create time for some reason???
title = self.title
@@ -51,24 +50,24 @@ class Node(NamedTuple):
return self.edited # fallback TODO log?
# strip off 'th'/'rd' crap
dts = m.group(1) + ' ' + m.group(2) + ' ' + m.group(3)
- dt = datetime.strptime(dts, '%B %d %Y').replace(tzinfo=timezone.utc)
- return dt
+ dt = datetime.strptime(dts, '%B %d %Y')
+ return pytz.utc.localize(dt)
@property
def edited(self) -> datetime:
rt = self.raw[Keys.EDITED]
- return datetime.fromtimestamp(rt / 1000, tz=timezone.utc)
+ return datetime.fromtimestamp(rt / 1000, tz=pytz.utc)
@property
- def title(self) -> str | None:
+ def title(self) -> Optional[str]:
return self.raw.get(Keys.TITLE)
@property
- def body(self) -> str | None:
+ def body(self) -> Optional[str]:
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))
@@ -98,7 +97,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:
@@ -123,7 +122,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:
@@ -133,11 +132,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 e10e4d2..61f9fab 100644
--- a/my/rss/all.py
+++ b/my/rss/all.py
@@ -1,11 +1,10 @@
'''
Unified RSS data, merged from different services I used historically
'''
-
# NOTE: you can comment out the sources you're not using
-from collections.abc import Iterable
-
from . import feedbin, feedly
+
+from typing import Iterable
from .common import Subscription, compute_subscriptions
@@ -13,5 +12,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 bf9506e..f3893b7 100644
--- a/my/rss/common.py
+++ b/my/rss/common.py
@@ -1,40 +1,36 @@
-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 my.core import datetime_aware, warn_if_empty
+# shared Rss stuff
+from datetime import datetime
+from typing import NamedTuple, Optional, List, Dict
-@dataclass
-class Subscription:
+class Subscription(NamedTuple):
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: datetime_aware | None
- subscribed: bool = True
+ created_at: Optional[datetime]
+ subscribed: bool=True
+from typing import Iterable, Tuple, Sequence
# snapshot of subscriptions at time
-SubscriptionState = tuple[datetime_aware, Sequence[Subscription]]
+SubscriptionState = Tuple[datetime, Sequence[Subscription]]
+from ..core import warn_if_empty
@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)
"""
+ from itertools import chain
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):
+ for when, state in sorted(states):
# TODO use 'when'?
for feed in state:
if feed.url not in by_url:
@@ -49,5 +45,7 @@ def compute_subscriptions(*sources: Iterable[SubscriptionState]) -> list[Subscri
res = []
for u, x in sorted(by_url.items()):
present = u in last_urls
- res.append(replace(x, subscribed=present))
+ res.append(x._replace(subscribed=present))
return res
+
+from ..core import __NOT_HPI_MODULE__
diff --git a/my/rss/feedbin.py b/my/rss/feedbin.py
index 5f4da0a..4cd1b8d 100644
--- a/my/rss/feedbin.py
+++ b/my/rss/feedbin.py
@@ -2,40 +2,48 @@
Feedbin RSS reader
"""
-import json
-from collections.abc import Iterator, Sequence
+from my.config import feedbin as config
+
from pathlib import Path
+from typing import Sequence
-from my.core import Stats, get_files, stat
-from my.core.compat import fromisoformat
+from ..core.common import listify, get_files, isoparse
+from .common import Subscription
-from .common import Subscription, SubscriptionState
-
-from my.config import feedbin as config # isort: skip
def inputs() -> Sequence[Path]:
return get_files(config.export_path)
-def parse_file(f: Path) -> Iterator[Subscription]:
+import json
+
+@listify
+def parse_file(f: Path):
raw = json.loads(f.read_text())
for r in raw:
yield Subscription(
- created_at=fromisoformat(r['created_at']),
+ created_at=isoparse(r['created_at']),
title=r['title'],
url=r['site_url'],
id=r['id'],
)
-def states() -> Iterator[SubscriptionState]:
+from typing import Iterable
+from .common import SubscriptionState
+def states() -> Iterable[SubscriptionState]:
+ # meh
+ from dateutil.parser import isoparse # type: ignore
for f in inputs():
# TODO ugh. depends on my naming. not sure if useful?
dts = f.stem.split('_')[-1]
- dt = fromisoformat(dts)
- subs = list(parse_file(f))
+ dt = isoparse(dts)
+ subs = parse_file(f)
yield dt, subs
-def stats() -> Stats:
- return stat(states)
+def stats():
+ from more_itertools import ilen, last
+ return {
+ 'subscriptions': ilen(last(states())[1])
+ }
diff --git a/my/rss/feedly.py b/my/rss/feedly.py
index 9bf5429..df38435 100644
--- a/my/rss/feedly.py
+++ b/my/rss/feedly.py
@@ -2,44 +2,29 @@
Feedly RSS reader
"""
-import json
-from abc import abstractmethod
-from collections.abc import Iterator, Sequence
-from datetime import datetime, timezone
+from my.config import feedly as config
+
from pathlib import Path
-from typing import Protocol
+from typing import Sequence
-from my.core import Paths, 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()
+from ..core.common import listify, get_files
+from .common import Subscription
def inputs() -> Sequence[Path]:
- cfg = make_config()
- return get_files(cfg.export_path)
+ return get_files(config.export_path)
-def parse_file(f: Path) -> Iterator[Subscription]:
+import json
+
+
+@listify
+def parse_file(f: Path):
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'],
@@ -48,9 +33,14 @@ def parse_file(f: Path) -> Iterator[Subscription]:
)
-def states() -> Iterator[SubscriptionState]:
+from datetime import datetime
+from typing import Iterable
+from .common import SubscriptionState
+def states() -> Iterable[SubscriptionState]:
+ import pytz
for f in inputs():
dts = f.stem.split('_')[-1]
- dt = datetime.strptime(dts, '%Y%m%d%H%M%S').replace(tzinfo=timezone.utc)
- subs = list(parse_file(f))
+ dt = datetime.strptime(dts, '%Y%m%d%H%M%S')
+ dt = pytz.utc.localize(dt)
+ subs = parse_file(f)
yield dt, subs
diff --git a/my/rtm.py b/my/rtm.py
old mode 100644
new mode 100755
index 217c969..2fc783f
--- a/my/rtm.py
+++ b/my/rtm.py
@@ -7,20 +7,19 @@ REQUIRES = [
]
import re
-from collections.abc import Iterator
+from typing import Dict, List, Iterator
from datetime import datetime
-from functools import cached_property
-import icalendar # type: ignore
-from icalendar.cal import Todo # type: ignore
-from more_itertools import bucket
+from .common import LazyLogger, get_files, group_by_key, cproperty, make_dict
-from my.core import get_files, make_logger
-from my.core.utils.itertools import make_dict
+from my.config import rtm as config
-from my.config import rtm as config # isort: skip
-logger = make_logger(__name__)
+import icalendar # type: ignore
+from icalendar.cal import Todo # type: ignore
+
+
+logger = LazyLogger(__name__)
# TODO extract in a module to parse RTM's ical?
@@ -29,15 +28,15 @@ class MyTodo:
self.todo = todo
self.revision = revision
- @cached_property
- def notes(self) -> list[str]:
+ @cproperty
+ 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]:
+ @cproperty
+ def tags(self) -> List[str]:
desc = self.todo['DESCRIPTION']
[tags_str] = re.findall(r'\nTags: (.*?)\n', desc, flags=re.DOTALL)
if tags_str == 'none':
@@ -45,22 +44,22 @@ class MyTodo:
tags = [t.strip() for t in tags_str.split(',')]
return tags
- @cached_property
+ @cproperty
def uid(self) -> str:
return str(self.todo['UID'])
- @cached_property
+ @cproperty
def title(self) -> str:
return str(self.todo['SUMMARY'])
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?
- @cached_property
+ @cproperty
def time(self) -> datetime:
t1 = self.todo['DTSTAMP'].dt
t2 = self.todo['LAST-MODIFIED'].dt
@@ -90,14 +89,13 @@ 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}
+ return group_by_key(todos, lambda todo: todo.title)
def dal():
@@ -115,3 +113,7 @@ def active_tasks() -> Iterator[MyTodo]:
if not t.is_completed():
yield t
+
+def print_all_todos():
+ for t in all_tasks():
+ print(t)
diff --git a/my/runnerup.py b/my/runnerup.py
index f5d7d1e..8e31770 100644
--- a/my/runnerup.py
+++ b/my/runnerup.py
@@ -6,15 +6,17 @@ REQUIRES = [
'python-tcxparser',
]
-from collections.abc import Iterable
from datetime import timedelta
from pathlib import Path
+from typing import Iterable
-import tcxparser # type: ignore[import-untyped]
+from .core import Res, get_files
+from .core.common import isoparse, Json
+
+import tcxparser
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
@@ -42,7 +44,7 @@ def _parse(f: Path) -> Workout:
return {
'id' : f.name, # not sure?
- 'start_time' : fromisoformat(tcx.started_at),
+ 'start_time' : isoparse(tcx.started_at),
'duration' : timedelta(seconds=tcx.duration),
'sport' : sport,
'heart_rate_avg': tcx.hr_avg,
@@ -56,7 +58,7 @@ def _parse(f: Path) -> Workout:
# tcx.hr_values(),
# # todo cadence?
# ):
- # t = fromisoformat(ts)
+ # t = isoparse(ts)
def workouts() -> Iterable[Res[Workout]]:
@@ -68,8 +70,6 @@ def workouts() -> Iterable[Res[Workout]]:
from .core.pandas import DataFrameT, check_dataframe, error_to_row
-
-
@check_dataframe
def dataframe() -> DataFrameT:
def it():
@@ -78,15 +78,13 @@ def dataframe() -> DataFrameT:
yield error_to_row(w)
else:
yield w
- import pandas as pd
+ import pandas as pd # type: ignore
df = pd.DataFrame(it())
if 'error' not in df:
df['error'] = None
return df
-from .core import Stats, stat
-
-
+from .core import stat, Stats
def stats() -> Stats:
return stat(dataframe)
diff --git a/my/simple.py b/my/simple.py
deleted file mode 100644
index b7f25cd..0000000
--- a/my/simple.py
+++ /dev/null
@@ -1,20 +0,0 @@
-'''
-Just a demo module for testing and documentation purposes
-'''
-from collections.abc import Iterator
-from dataclasses import dataclass
-
-from my.config import simple as user_config
-from my.core import make_config
-
-
-@dataclass
-class simple(user_config):
- count: int
-
-
-config = make_config(simple)
-
-
-def items() -> Iterator[int]:
- yield from range(config.count)
diff --git a/my/smscalls.py b/my/smscalls.py
index 27d08be..25acf4b 100644
--- a/my/smscalls.py
+++ b/my/smscalls.py
@@ -2,103 +2,61 @@
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
REQUIRES = ['lxml']
-from dataclasses import dataclass
-
+from .core import Paths, dataclass
from my.config import smscalls as user_config
-from my.core import Paths, Stats, get_files, stat
-
@dataclass
class smscalls(user_config):
# path[s] that SMSBackupRestore syncs XML files to
export_path: Paths
-from my.core.cfg import make_config
-
+from .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 Any, NamedTuple
+from typing import NamedTuple, Iterator, Set, Tuple
-import lxml.etree as etree
+from lxml import etree # type: ignore
-from my.core.error import Res
+from .core.common import get_files, Stats
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
+ who: str
@property
def summary(self) -> str:
return f"talked with {self.who} for {self.duration_s} secs"
- @property
- def from_me(self) -> bool:
- return self.call_type == 2
-
-# From docs:
-# 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)'}
-
-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 = _parse_xml(path)
+def _extract_calls(path: Path) -> Iterator[Call]:
+ tr = etree.parse(str(path))
for cxml in tr.findall('call'):
- dt = cxml.get('date')
- dt_readable = cxml.get('readable_date')
- 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 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, 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
yield Call(
- dt=_parse_dt_ms(dt),
- dt_readable=dt_readable,
- duration_s=int(duration),
- phone_number=number,
- who=who,
- call_type=int(call_type),
+ dt=_parse_dt_ms(cxml.get('date')),
+ dt_readable=cxml.get('readable_date'),
+ duration_s=int(cxml.get('duration')),
+ who=cxml.get('contact_name') # TODO number if contact is unavail??
+ # TODO type? must be missing/outgoing/incoming
)
-def calls() -> Iterator[Res[Call]]:
+def calls() -> Iterator[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):
- yield c
- continue
if c.dt in emitted:
continue
emitted.add(c.dt)
@@ -108,26 +66,18 @@ def calls() -> Iterator[Res[Call]]:
class Message(NamedTuple):
dt: datetime
dt_readable: str
- who: str | None
+ who: str
message: str
phone_number: str
- # type - 1 = Received, 2 = Sent, 3 = Draft, 4 = Outbox, 5 = Failed, 6 = Queued
- message_type: int
-
- @property
- def from_me(self) -> bool:
- return self.message_type == 2
+ from_me: bool
-def messages() -> Iterator[Res[Message]]:
+def messages() -> Iterator[Message]:
files = get_files(config.export_path, glob='sms-*.xml')
- emitted: set[tuple[datetime, str | None, bool]] = set()
+ emitted: Set[Tuple[datetime, str, bool]] = set()
for p in files:
for c in _extract_messages(p):
- if isinstance(c, Exception):
- yield c
- continue
key = (c.dt, c.who, c.from_me)
if key in emitted:
continue
@@ -135,183 +85,16 @@ def messages() -> Iterator[Res[Message]]:
yield c
-def _extract_messages(path: Path) -> Iterator[Res[Message]]:
- tr = _parse_xml(path)
+def _extract_messages(path: Path) -> Iterator[Message]:
+ tr = etree.parse(str(path))
for mxml in tr.findall('sms'):
- dt = mxml.get('date')
- dt_readable = mxml.get('readable_date')
- who = mxml.get('contact_name')
- if who is not None and who in UNKNOWN:
- who = None
- message = mxml.get('body')
- phone_number = mxml.get('address')
- message_type = mxml.get('type')
-
- if dt is None or dt_readable is None or message is None or phone_number is None or message_type is None:
- msg_str = etree.tostring(mxml).decode('utf-8')
- yield RuntimeError(f"Missing one or more required attributes [date, readable_date, body, address, type] in {msg_str}")
- continue
yield Message(
- dt=_parse_dt_ms(dt),
- dt_readable=dt_readable,
- who=who,
- message=message,
- phone_number=phone_number,
- message_type=int(message_type),
- )
-
-
-class MMSContentPart(NamedTuple):
- sequence_index: int
- content_type: str
- filename: str
- text: str | None
- data: str | None
-
-
-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: 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]]
- # 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
- # 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}')
-
- @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, str | None, 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: str | None) -> str | None:
- if value is None:
- return None
- # 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
- return value
-
-
-def _extract_mms(path: Path) -> Iterator[Res[MMS]]:
- tr = _parse_xml(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
- part_data: dict[str, Any] = part.attrib
- seq: str | None = 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: 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: 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}')
- 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,
+ dt=_parse_dt_ms(mxml.get('date')),
+ dt_readable=mxml.get('readable_date'),
+ who=mxml.get('contact_name'),
+ message=mxml.get('body'),
+ phone_number=mxml.get('address'),
+ from_me=mxml.get('type') == '2', # 1 is received message, 2 is sent message
)
@@ -322,8 +105,9 @@ def _parse_dt_ms(d: str) -> datetime:
def stats() -> Stats:
+ from .core import stat
+
return {
**stat(calls),
**stat(messages),
- **stat(mms),
}
diff --git a/my/stackexchange/gdpr.py b/my/stackexchange/gdpr.py
index 8ed0d30..4a3182b 100644
--- a/my/stackexchange/gdpr.py
+++ b/my/stackexchange/gdpr.py
@@ -5,12 +5,8 @@ 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 my.core import Json, PathIsh, get_files, make_config
-
-
+from ..core import dataclass, PathIsh, make_config
@dataclass
class stackexchange(user_config):
gdpr_path: PathIsh # path to GDPR zip file
@@ -20,20 +16,16 @@ config = make_config(stackexchange)
# TODO just merge all of them and then filter?.. not sure
-from collections.abc import Iterable
+from ..core.common import Json, isoparse
+from typing import NamedTuple, Iterable
from datetime import datetime
-from typing import NamedTuple
-
-from my.core.compat import fromisoformat
-
-
class Vote(NamedTuple):
j: Json
# todo ip?
@property
def when(self) -> datetime:
- return fromisoformat(self.j['eventTime'])
+ return isoparse(self.j['eventTime'])
# todo Url return type?
@property
@@ -49,7 +41,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 question
+ # parentPostId is the original quesion
# 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
@@ -69,14 +61,12 @@ class Vote(NamedTuple):
# todo expose vote type?
import json
-
+from ..core.kompress import ZipPath
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
- path = max(get_files(config.gdpr_path))
+ path = ZipPath(config.gdpr_path)
votes_path = path / 'analytics' / 'qa\\vote.submit.json' # yes, it does contain a backslash...
j = json.loads(votes_path.read_text(encoding='utf-8-sig')) # not sure why, but this encoding seems necessary
for r in reversed(j): # they seem to be in decreasing order by default
@@ -84,8 +74,6 @@ def votes() -> Iterable[Res[Vote]]:
yield Vote(r)
-from ..core import Stats, stat
-
-
+from ..core import stat, Stats
def stats() -> Stats:
return stat(votes)
diff --git a/my/stackexchange/stexport.py b/my/stackexchange/stexport.py
index 111ed28..6286c83 100644
--- a/my/stackexchange/stexport.py
+++ b/my/stackexchange/stexport.py
@@ -5,39 +5,24 @@ REQUIRES = [
'git+https://github.com/karlicoss/stexport',
]
-from dataclasses import dataclass
-
-from stexport import dal
-
-from my.core import (
- PathIsh,
- Stats,
- get_files,
- make_config,
- stat,
-)
-
-import my.config # isort: skip
-
-
+### config
+from my.config import stackexchange as user_config
+from ..core import dataclass, PathIsh, make_config
@dataclass
-class stackexchange(my.config.stackexchange):
+class stackexchange(user_config):
'''
Uses [[https://github.com/karlicoss/stexport][stexport]] outputs
'''
-
- export_path: PathIsh
-
-
+ export_path: PathIsh # path to GDPR zip file
config = make_config(stackexchange)
-# TODO kinda annoying it's resolving gdpr path here (and fails during make_config if gdpr path isn't available)
-# I guess it's a good argument to avoid clumping configs together
-# or move to my.config.stackexchange.stexport
###
+from stexport import dal
+
# todo lru cache?
def _dal() -> dal.DAL:
+ from ..core import get_files
inputs = get_files(config.export_path)
return dal.DAL(inputs)
@@ -47,9 +32,7 @@ def site(name: str) -> dal.SiteDAL:
return _dal().site_dal(name)
+from ..core import stat, Stats
def stats() -> Stats:
- res = {}
- for name in _dal().sites():
- s = site(name=name)
- res.update({name: stat(s.questions, name='questions')})
- return res
+ s = site('stackoverflow')
+ return stat(s.questions)
diff --git a/my/taplog.py b/my/taplog.py
index 5e64a72..f668a10 100644
--- a/my/taplog.py
+++ b/my/taplog.py
@@ -1,26 +1,24 @@
'''
[[https://play.google.com/store/apps/details?id=com.waterbear.taglog][Taplog]] app data
'''
-from __future__ import annotations
-from collections.abc import Iterable
from datetime import datetime
-from typing import NamedTuple
+from typing import NamedTuple, Dict, Optional, Iterable
+
+from .core import get_files
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) -> float | None:
+ def number(self) -> Optional[float]:
ns = self.row['number']
# TODO ??
if isinstance(ns, str):
@@ -41,17 +39,18 @@ class Entry(NamedTuple):
def timestamp(self) -> datetime:
ts = self.row['timestamp']
# already with timezone apparently
- # TODO not sure if should still localize though? it only kept tz offset, not real tz
+ # TODO not sure if should stil localize though? it only kept tz offset, not real tz
return datetime.fromisoformat(ts)
# TODO also has gps info!
def entries() -> Iterable[Entry]:
last = max(get_files(user_config.export_path))
- with sqlite_connection(last, immutable=True, row_factory='dict') as db:
- # todo is it sorted by timestamp?
- for row in db.execute('SELECT * FROM Log'):
- yield Entry(row)
+ from .core.dataset import connect_readonly
+ db = connect_readonly(last)
+ # todo is it sorted by timestamp?
+ for row in db['Log'].all():
+ yield Entry(row)
# I guess worth having as top level considering it would be quite common?
@@ -61,5 +60,6 @@ def by_button(button: str) -> Iterable[Entry]:
yield e
+from .core import stat, Stats
def stats() -> Stats:
return stat(entries)
diff --git a/my/telegram/telegram_backup.py b/my/telegram/telegram_backup.py
deleted file mode 100644
index eea7e50..0000000
--- a/my/telegram/telegram_backup.py
+++ /dev/null
@@ -1,184 +0,0 @@
-"""
-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 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
-class config(user_config.telegram_backup):
- # path to the export database.sqlite
- export_path: PathIsh
-
-
-@dataclass
-class Chat:
- id: 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: str | None
- # not sure if need type?
-
-
-@dataclass
-class User:
- id: str
- name: str | None
-
-
-@dataclass
-class Message:
- # NOTE: message id is NOT unique globally -- only with respect to chat!
- id: int
- time: datetime_aware
- chat: Chat
- sender: User
- text: str
- extra_media_info: str | None = None
-
- @property
- def permalink(self) -> str:
- handle = self.chat.handle
- if handle is None:
- clink = str(self.chat.id)
- else:
- # FIXME add c/
- clink = f'{handle}'
-
- # NOTE: don't think deep links to messages work for private conversations sadly https://core.telegram.org/api/links#message-links
- # NOTE: doesn't look like this works with private groups at all, doesn't even jump into it
- return f'https://t.me/{clink}/{self.id}'
-
-
-
-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)
- # and telegram_backup timestamps seem same as in desktop export
- time = datetime.fromtimestamp(ts, tz=timezone.utc)
- chat = chats[r['source_id']]
- sender = chats[r['sender_id']]
-
- 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..
- # maybe later we'll improve it
- try:
- extra_media_info = _extract_extra_media_info(data=r['data'])
- except Exception as e:
- pass
-
- return Message(
- id=r['message_id'],
- time=time,
- chat=chat,
- sender=User(id=sender.id, name=sender.name),
- text=r['text'],
- extra_media_info=extra_media_info,
- )
-
-
-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
- messages_query += ' ORDER BY time'
-
- with sqlite_connection(config.export_path, immutable=True, row_factory='row') as db:
- chats: Chats = {}
- for r in db.execute('SELECT * FROM chats ORDER BY id'):
- chat = Chat(id=r['id'], name=r['name'], handle=None)
- assert chat.id not in chats
- chats[chat.id] = chat
-
- for r in db.execute('SELECT * FROM users ORDER BY id'):
- first = r["first_name"]
- last = r["last_name"]
- name: str | None
- if first is not None and last is not None:
- name = f'{first} {last}'
- else:
- name = first or last
-
- chat = Chat(id=r['id'], name=name, handle=r['username'])
- assert chat.id not in chats
- chats[chat.id] = chat
-
- for r in db.execute(messages_query):
- # seems like the only remaining have message_type = 'message'
- yield _message_from_row(r, chats=chats, with_extra_media_info=with_extra_media_info)
-
-
-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
-
- def skip(count: int) -> None:
- nonlocal pos
- pos += count
-
- def getstring() -> str:
- # jesus
- # https://core.telegram.org/type/string
- if data[pos] == 254:
- skip(1)
- (sz1, sz2, sz3) = unpack_from('BBB', data, offset=pos)
- skip(3)
- sz = 256 ** 2 * sz3 + 256 * sz2 + sz1
- short = 0
- else:
- (sz, ) = unpack_from('B', data, offset=pos)
- skip(1)
- short = 1
- assert sz > 0, sz
-
- padding = 0 if (sz + short) % 4 == 0 else 4 - (sz + short) % 4
-
- (ss,) = unpack_from(f'{sz}s{padding}x', data, offset=pos)
- skip(sz + padding)
- try:
- return ss.decode('utf8')
- except UnicodeDecodeError as e:
- raise RuntimeError(f'Failed to decode {ss}') from e
-
- def debug(count: int=10) -> None:
- print([hex(x) for x in data[pos: pos + count]])
- print([chr(x) for x in data[pos: pos + count]])
-
- header = 'H2xII8xI'
- (flags, mid, src, ts) = unpack_from(header, data, offset=pos)
- pos += calcsize(header)
-
- # see https://core.telegram.org/constructor/message
- has_media = (flags >> 9) & 1
- if has_media == 0:
- return None
-
- msg_body = getstring()
- skip(20)
- url1 = getstring()
- url2 = getstring()
- ss_type = getstring()
- # not sure if assert is really necessary her
- # assert ss_type in {
- # 'article',
- # 'photo',
- # 'app',
- # 'video',
- # }, ss_type
- link_title = getstring()
- link_title_2 = getstring()
- link_description = getstring()
- return link_description
diff --git a/my/tests/__init__.py b/my/tests/__init__.py
deleted file mode 100644
index 4ad5bba..0000000
--- a/my/tests/__init__.py
+++ /dev/null
@@ -1,8 +0,0 @@
-# hmm, sadly pytest --import-mode importlib --pyargs my.core.tests doesn't work properly without __init__.py
-# although it works if you run either my.core or my.core.tests.sqlite (for example) directly
-# so if it gets in the way could get rid of this later?
-
-# this particularly sucks here, because otherwise would be nice if people could also just put tests for their my. packages into their tests/ directory
-# maybe some sort of hack could be used later similar to handle_legacy_import?
-
-from my.core import __NOT_HPI_MODULE__
diff --git a/my/tests/body/weight.py b/my/tests/body/weight.py
deleted file mode 100644
index f26ccf2..0000000
--- a/my/tests/body/weight.py
+++ /dev/null
@@ -1,59 +0,0 @@
-from pathlib import Path
-
-import pytest
-import pytz
-
-from my.body.weight import from_orgmode
-from my.core.cfg import tmp_config
-
-
-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/my/tests/calendar.py b/my/tests/calendar.py
deleted file mode 100644
index b5f856c..0000000
--- a/my/tests/calendar.py
+++ /dev/null
@@ -1,9 +0,0 @@
-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
deleted file mode 100644
index cf5c632..0000000
--- a/my/tests/common.py
+++ /dev/null
@@ -1,21 +0,0 @@
-import os
-from pathlib import Path
-
-import pytest
-
-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 env variable {V}=true to override.',
-)
-
-
-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/conftest.py b/my/tests/conftest.py
deleted file mode 100644
index cc7bb7e..0000000
--- a/my/tests/conftest.py
+++ /dev/null
@@ -1,10 +0,0 @@
-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/my/tests/location/fallback.py b/my/tests/location/fallback.py
deleted file mode 100644
index c09b902..0000000
--- a/my/tests/location/fallback.py
+++ /dev/null
@@ -1,135 +0,0 @@
-"""
-To test my.location.fallback_location.all
-"""
-
-from collections.abc import Iterator
-from datetime import datetime, timedelta, timezone
-
-import pytest
-from more_itertools import ilen
-
-import my.ip.all as ip_module
-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:
- # 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
- assert ilen(via_ip._sorted_fallback_locations()) == 5
-
- # confirm duration from via_ip since that is used for bisect
- assert via_ip.config.for_duration == timedelta(hours=24)
-
- # basic tests
-
- # try estimating slightly before the first IP
- est = list(via_ip.estimate_location(datetime(2020, 1, 1, 11, 59, 59, tzinfo=timezone.utc)))
- assert len(est) == 0
-
- # during the duration for the first IP
- est = list(via_ip.estimate_location(datetime(2020, 1, 1, 12, 30, 0, tzinfo=timezone.utc)))
- 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))
- )
- assert len(est) == 0
-
- # on 2/1/2020, threes one IP if before 16:30
- est = list(via_ip.estimate_location(datetime(2020, 2, 1, 12, 30, 0, tzinfo=timezone.utc)))
- assert len(est) == 1
-
- # and two if after 16:30
- est = list(via_ip.estimate_location(datetime(2020, 2, 1, 17, 00, 0, tzinfo=timezone.utc)))
- assert len(est) == 2
-
- # the 12:30 IP should 'expire' before the 16:30 IP, use 3:30PM on the next day
- est = list(via_ip.estimate_location(datetime(2020, 2, 2, 15, 30, 0, tzinfo=timezone.utc)))
- assert len(est) == 1
-
- use_dt = datetime(2020, 3, 1, 12, 15, 0, tzinfo=timezone.utc)
-
- # test last IP
- est = list(via_ip.estimate_location(use_dt))
- assert len(est) == 1
-
- # datetime should be the IPs, not the passed IP (if via_home, it uses the passed dt)
- assert est[0].dt != use_dt
-
- # test interop with other fallback estimators/all.py
- #
- # 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, via_home
-
- def _fe() -> Iterator[all.LocationEstimator]:
- yield via_ip.estimate_location
- yield via_home.estimate_location
-
- all.fallback_estimators = _fe
- assert ilen(all.fallback_estimators()) == 2
-
- # test that all.estimate_location has access to both IPs
- #
- # 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"
- assert raw_est[0].accuracy == 15_000
-
- # passing home should give one
- home_est = list(_iter_estimate_from(use_dt, (via_home.estimate_location,)))
- assert len(home_est) == 1
- assert home_est[0].accuracy == 30_000
-
- # make sure ip accuracy is more accurate
- assert raw_est[0].accuracy < home_est[0].accuracy
-
- # passing both should give two
- raw_est = list(_iter_estimate_from(use_dt, (via_ip.estimate_location, via_home.estimate_location)))
- assert len(raw_est) == 2
-
- # shouldn't raise value error
- all_est = all.estimate_location(use_dt)
- # 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_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"
-
- # test a different home using location.fallback.all
- bulgaria = all.estimate_location(datetime(2006, 1, 1, 12, 30, 0, tzinfo=timezone.utc))
- assert bulgaria.datasource == "via_home"
- assert (bulgaria.lat, bulgaria.lon) == (42.697842, 23.325973)
- assert (loc.lat, loc.lon) != (bulgaria.lat, bulgaria.lon)
-
-
-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/my/tests/location/google.py b/my/tests/location/google.py
deleted file mode 100644
index 43b8646..0000000
--- a/my/tests/location/google.py
+++ /dev/null
@@ -1,55 +0,0 @@
-"""
-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 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
-
- 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/reddit.py b/my/tests/reddit.py
deleted file mode 100644
index 4ddccf8..0000000
--- a/my/tests/reddit.py
+++ /dev/null
@@ -1,63 +0,0 @@
-import pytest
-from more_itertools import consume
-
-# 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:
- # todo maybe this should call stat or something instead?
- # would ensure reasonable stat implementation as well and less duplication
- # note: deliberately use old module (instead of my.reddit.all) to test bwd compatibility
- from my.reddit import saved
-
- assert len(list(saved())) > 0
-
-
-def test_basic_2() -> None:
- # deliberately check call from a different style of import to make sure tmp_config works
- saves = list(my_reddit_rexport.saved())
- assert len(saves) > 0
-
-
-def test_comments() -> None:
- assert len(list(my_reddit_all.comments())) > 0
-
-
-def test_saves() -> None:
- from my.reddit.all import saved
-
- saves = list(saved())
- assert len(saves) > 0
-
- # will throw if not unique
- consume(ensure_unique(saves, key=lambda s: s.sid))
-
-
-def test_preserves_extra_attr() -> None:
- # doesn't strictly belong here (not specific to reddit)
- # but my.reddit does a fair bit of dynamic hacking, so perhaps a good place to check nothing is lost
- from my.reddit import config
-
- assert isinstance(getattr(config, 'please_keep_me'), str)
-
-
-@pytest.fixture(autouse=True, scope='module')
-def prepare():
- data = testdata() / 'hpi-testdata' / 'reddit'
- assert data.exists(), data
-
- # note: deliberately using old config schema so we can test migrations
- class config:
- class reddit:
- export_dir = data
- please_keep_me = 'whatever'
-
- with tmp_config(modules='my.reddit.*', config=config):
- yield
diff --git a/my/tests/shared_tz_config.py b/my/tests/shared_tz_config.py
deleted file mode 100644
index 810d989..0000000
--- a/my/tests/shared_tz_config.py
+++ /dev/null
@@ -1,60 +0,0 @@
-"""
-Helper to test various timezone/location dependent things
-"""
-
-from datetime import date, datetime, timezone
-from pathlib import Path
-
-import pytest
-from more_itertools import one
-
-from my.core.cfg import tmp_config
-
-
-@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)
-
- class google:
- takeout_path = _takeout_path
-
- class location:
- # fmt: off
- home = (
- # supports ISO strings
- ('2005-12-04' , (42.697842, 23.325973)), # Bulgaria, Sofia
- # supports date/datetime objects
- (date(year=1980, month=2, day=15) , (40.7128 , -74.0060 )), # NY
- # 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 time:
- class tz:
- class via_location:
- fast = True # some tests rely on it
-
- with tmp_config() as cfg:
- cfg.google = google
- cfg.location = location
- cfg.time = time
- yield cfg
-
-
-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 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
-
- 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
deleted file mode 100644
index 92d8f3b..0000000
--- a/my/tests/tz.py
+++ /dev/null
@@ -1,107 +0,0 @@
-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/common.py b/my/time/tz/common.py
index c0dd262..b6ebbe5 100644
--- a/my/time/tz/common.py
+++ b/my/time/tz/common.py
@@ -1,7 +1,8 @@
from datetime import datetime
-from typing import Callable, Literal, cast
+from typing import Callable, cast
+
+from ...core.common import tzdatetime, Literal
-from my.core import datetime_aware
'''
Depending on the specific data provider and your level of paranoia you might expect different behaviour.. E.g.:
@@ -9,31 +10,24 @@ Depending on the specific data provider and your level of paranoia you might exp
- it's safer when either all of your objects are tz aware or all are tz unware, not a mixture
- you might trust your original timezone, or it might just be UTC, and you want to use something more reasonable
'''
-TzPolicy = Literal[
+Policy = Literal[
'keep' , # if datetime is tz aware, just preserve it
'convert', # if datetime is tz aware, convert to provider's tz
'throw' , # if datetime is tz aware, throw exception
# todo 'warn'? not sure if very useful
]
-# backwards compatibility
-Policy = TzPolicy
-
-def default_policy() -> TzPolicy:
+def default_policy() -> Policy:
try:
from my.config import time as user_config
- return cast(TzPolicy, user_config.tz.policy)
+ return cast(Policy, user_config.tz.policy)
except Exception as e:
# todo meh.. need to think how to do this more carefully
# rationale: do not mess with user's data unless they want
return 'keep'
-def localize_with_policy(
- lfun: Callable[[datetime], datetime_aware],
- dt: datetime,
- policy: TzPolicy=default_policy() # noqa: B008
-) -> datetime_aware:
+def localize_with_policy(lfun: Callable[[datetime], tzdatetime], dt: datetime, policy: Policy=default_policy()) -> tzdatetime:
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 bdd36b1..624d7aa 100644
--- a/my/time/tz/main.py
+++ b/my/time/tz/main.py
@@ -1,14 +1,11 @@
'''
Timezone data provider, used to localize timezone-unaware timestamps for other modules
'''
-
from datetime import datetime
-
-from my.core import datetime_aware
-
+from ...core.common import tzdatetime
# todo hmm, kwargs isn't mypy friendly.. but specifying types would require duplicating default args. uhoh
-def localize(dt: datetime, **kwargs) -> datetime_aware:
+def localize(dt: datetime, **kwargs) -> tzdatetime:
# 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 1b2275b..e390c43 100644
--- a/my/time/tz/via_location.py
+++ b/my/time/tz/via_location.py
@@ -1,263 +1,116 @@
'''
Timezone data provider, guesses timezone based on location data (e.g. GPS)
'''
-
-from __future__ import annotations
-
REQUIRES = [
# for determining timezone by coordinate
'timezonefinder',
]
-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
from itertools import groupby
-from typing import (
- TYPE_CHECKING,
- Any,
- Protocol,
-)
+from typing import Iterator, NamedTuple, Optional
+from more_itertools import seekable
import pytz
-from my.core import Stats, datetime_aware, make_logger, stat
-from my.core.cachew import mcachew
-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
+from ...core.common import LazyLogger, mcachew, tzdatetime
+from ...core.cachew import cache_dir
+from ...location.google import locations
-class config(Protocol):
- # less precise, but faster
- fast: bool = True
-
- # sort locations by date
- # in case multiple sources provide them out of order
- sort_locations: bool = True
-
- # if the accuracy for the location is more than 5km, don't use
- require_accuracy: float = 5_000
-
- # how often (hours) to refresh the cachew timezone cache
- # this may be removed in the future if we opt for dict-based caching
- _iter_tz_refresh_time: int = 6
+logger = LazyLogger(__name__, level='debug')
-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
- 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
- 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__)
-
-
-@lru_cache(None)
-def _timezone_finder(*, fast: bool) -> Any:
+# todo should move to config? not sure
+_FASTER: bool = True
+@lru_cache(2)
+def _timezone_finder(fast: bool):
if fast:
# less precise, but faster
- from timezonefinder import TimezoneFinderL as Finder
+ from timezonefinder import TimezoneFinderL as Finder # type: ignore
else:
- from timezonefinder import TimezoneFinder as Finder # type: ignore
+ from timezonefinder import TimezoneFinder as Finder # type: ignore
return Finder(in_memory=True)
-# for backwards compatibility
-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:
- 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
-
- 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_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:
+class DayWithZone(NamedTuple):
day: date
zone: Zone
-def _find_tz_for_locs(finder: Any, locs: Iterable[tuple[LatLon, datetime]]) -> Iterator[DayWithZone]:
- for (lat, lon), dt in locs:
+def _iter_local_dates(start=0, stop=None) -> Iterator[DayWithZone]:
+ finder = _timezone_finder(fast=_FASTER) # rely on the default
+ pdt = None
+ warnings = []
+ # todo allow to skip if not noo many errors in row?
+ for l in locations(start=start, stop=stop):
# TODO right. its _very_ slow...
- zone = finder.timezone_at(lat=lat, lng=lon)
- # todo allow to skip if not noo many errors in row?
+ zone = finder.timezone_at(lng=l.lon, lat=l.lat)
if zone is None:
- # warnings.append(f"Couldn't figure out tz for {lat}, {lon}")
+ warnings.append(f"Couldn't figure out tz for {l}")
continue
tz = pytz.timezone(zone)
# TODO this is probably a bit expensive... test & benchmark
- ldt = dt.astimezone(tz)
+ ldt = l.dt.astimezone(tz)
ndate = ldt.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
+ 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
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]:
- 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 cfg.sort_locations else _locations()
-
- yield from _find_tz_for_locs(finder, locs)
-
-
-# my.location.fallback.estimate_location could be used here
-# but iterating through all the locations is faster since this
-# is saved behind cachew
-@import_source(module_name="my.location.fallback.all")
-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=cfg.fast), _fallback_locations())
-
-
-def most_common(lst: Iterator[DayWithZone]) -> DayWithZone:
- res, _ = Counter(lst).most_common(1)[0]
+def most_common(l):
+ res, count = Counter(l).most_common(1)[0] # type: ignore[var-annotated]
return res
-def _iter_tz_depends_on() -> str:
- """
- Since you might get new data which specifies a new timezone sometime
- in the day, this causes _iter_tzs to refresh every _iter_tz_refresh_time hours
- (default 6), like:
- 2022-04-26_00
- 2022-04-26_06
- 2022-04-26_12
- 2022-04-26_18
- """
- cfg = make_config()
- mod = cfg._iter_tz_refresh_time
- assert mod >= 1
- day = str(date.today())
- hr = datetime.now().hour
- hr_truncated = hr // mod * mod
- return f"{day}_{hr_truncated}"
-
-
-# refresh _iter_tzs every few hours -- don't think a better depends_on is possible dynamically
-@mcachew(depends_on=_iter_tz_depends_on)
+@mcachew(cache_path=cache_dir())
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
- 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] = 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]
- 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=by_day)
- # todo could probably use heapify here instead of heapq.merge?
-
- 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
+ for d, gr in groupby(_iter_local_dates(), key=lambda p: p.day):
+ logger.info('processed %s', d)
+ zone = most_common(list(gr)).zone
yield DayWithZone(day=d, zone=zone)
@lru_cache(1)
-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 everything during subsequent runs
- return {dz.day: pytz.timezone(dz.zone) for dz in _iter_tzs()}
+def loc_tz_getter() -> Iterator[DayWithZone]:
+ # seekable makes it cache the emitted values
+ return seekable(_iter_tzs())
-def _get_day_tz(d: date) -> pytz.BaseTzInfo | None:
- return _day2zone().get(d)
+# 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)
# ok to cache, there are only a few home locations?
-@lru_cache(None)
-def _get_home_tz(loc: LatLon) -> pytz.BaseTzInfo | None:
+@lru_cache(maxsize=None)
+def _get_home_tz(loc) -> 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?
@@ -266,30 +119,19 @@ def _get_home_tz(loc: LatLon) -> pytz.BaseTzInfo | None:
return pytz.timezone(zone)
-def get_tz(dt: datetime) -> pytz.BaseTzInfo | None:
- '''
- Given a datetime, returns the timezone for that date.
- '''
+# TODO expose? to main as well?
+def _get_tz(dt: datetime) -> Optional[pytz.BaseTzInfo]:
res = _get_day_tz(d=dt.date())
if res is not None:
return res
# fallback to home tz
- # note: the fallback to fallback.via_home.estimate_location is still needed, since
- # _iter_local_dates_fallback only returns days which we actually have a datetime for
- # (e.g. there was an IP address within a day of that datetime)
- #
- # given a datetime, fallback.via_home.estimate_location will find which home location
- # 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))
+ from ...location import home
+ loc = home.get_location(dt)
+ return _get_home_tz(loc=loc)
-def localize(dt: datetime) -> datetime_aware:
- tz = get_tz(dt)
+def localize(dt: datetime) -> tzdatetime:
+ tz = _get_tz(dt)
if tz is None:
# TODO -- this shouldn't really happen.. think about it carefully later
return dt
@@ -297,35 +139,16 @@ def localize(dt: datetime) -> datetime_aware:
return tz.localize(dt)
-def stats(*, quick: bool = False) -> Stats:
- if quick:
- prev, config.sort_locations = config.sort_locations, False
- res = {'first': next(_iter_local_dates())}
- config.sort_locations = prev
- return res
+from ...core import stat, Stats
+def stats() -> Stats:
# 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
- 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
# need to think about it...
- for Y in range(VIA_LOCATION_START_YEAR, last):
+ for Y in range(1990, last):
dt = datetime.fromisoformat(f'{Y}-01-01 01:01:01')
yield localize(dt)
-
return stat(localized_years)
-
-
-## 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/my/tinder/android.py b/my/tinder/android.py
deleted file mode 100644
index 5a5d887..0000000
--- a/my/tinder/android.py
+++ /dev/null
@@ -1,247 +0,0 @@
-"""
-Tinder data from Android app database (in =/data/data/com.tinder/databases/tinder-3.db=)
-"""
-from __future__ import annotations
-
-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
-from typing import Union
-
-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 # isort: skip
-
-
-logger = make_logger(__name__)
-
-
-@dataclass
-class config(my.config.tinder.android):
- # paths[s]/glob to the exported sqlite databases
- export_path: Paths
-
-
-@dataclass(unsafe_hash=True)
-class Person:
- id: str
- name: str
- # todo bio? it might change, not sure what do we want here
-
-
-@dataclass(unsafe_hash=True)
-class _BaseMatch:
- # for android, checked directly shortly after a match
- when: datetime_aware
- id: str
-
-
-@dataclass(unsafe_hash=True)
-class _Match(_BaseMatch):
- person_id: str
-
-
-@dataclass(unsafe_hash=True)
-class Match(_BaseMatch):
- person: Person
-
-
-# todo again, not sure what's the 'optimal' field order? perhaps the one which gives the most natural sort?
-# so either match id or datetime
-@dataclass
-class _BaseMessage:
- # looks like gdpr takeout does contain GMT (compared against google maps data)
- sent: datetime_aware
- id: str
- text: str
-
-
-@dataclass(unsafe_hash=True)
-class _Message(_BaseMessage):
- match_id: str
- from_id: str
- to_id: str
-
-
-@dataclass
-class Message(_BaseMessage):
- match: Match
- from_: Person
- to: Person
-
-
-# todo hmm I have a suspicion it might be cumulative?
-# although still possible that the user might remove/install app back, so need to keep that in mind
-def inputs() -> Sequence[Path]:
- return get_files(config.export_path)
-
-
-_Entity = Union[Person, _Match, _Message]
-Entity = Union[Person, Match, Message]
-
-
-def _entities() -> Iterator[Res[_Entity]]:
- paths = inputs()
- total = len(paths)
- width = len(str(total))
- 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:
- try:
- yield from _handle_db(db)
- except Exception as e:
- yield e
-
-
-def _handle_db(db: sqlite3.Connection) -> Iterator[Res[_Entity]]:
- # profile_user_view contains our own user id
- user_profile_rows = list(db.execute('SELECT * FROM profile_user_view'))
-
- if len(user_profile_rows) == 0:
- # 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)
- [(you_id, _)] = counter.most_common(1)
- yield Person(id=you_id, name='you')
-
- for row in chain(
- user_profile_rows,
- db.execute('SELECT * FROM match_person'),
- ):
- try:
- yield _parse_person(row)
- except Exception as e:
- # todo attach error context?
- yield e
-
- for row in db.execute('SELECT * FROM match'):
- try:
- yield _parse_match(row)
- except Exception as e:
- yield e
-
- for row in db.execute('SELECT * FROM message'):
- try:
- yield _parse_msg(row)
- except Exception as e:
- yield e
-
-
-def _parse_person(row: sqlite3.Row) -> Person:
- return Person(
- id=row['id'],
- name=row['name'],
- )
-
-
-def _parse_match(row: sqlite3.Row) -> _Match:
- return _Match(
- id=row['id'],
- person_id=row['person_id'],
- when=datetime.fromtimestamp(row['creation_date'] / 1000, tz=timezone.utc),
- )
-
-
-def _parse_msg(row: sqlite3.Row) -> _Message:
- # note it also has raw_message_data -- not sure which is best to use..
- sent = row['sent_date']
- return _Message(
- sent=datetime.fromtimestamp(sent / 1000, tz=timezone.utc),
- id=row['id'],
- text=row['text'],
- match_id=row['match_id'],
- from_id=row['from_id'],
- to_id=row['to_id'],
- )
-
-
-# todo maybe it's rich_entities method?
-def entities() -> Iterator[Res[Entity]]:
- id2person: dict[str, Person] = {}
- id2match: dict[str, Match] = {}
- for x in unique_everseen(_entities):
- if isinstance(x, Exception):
- yield x
- continue
- if isinstance(x, Person):
- id2person[x.id] = x
- yield x
- continue
- if isinstance(x, _Match):
- try:
- person = id2person[x.person_id]
- except Exception as e:
- yield e
- continue
- m = Match(
- id=x.id,
- when=x.when,
- person=person,
- )
- id2match[x.id] = m
- yield m
- continue
- if isinstance(x, _Message):
- try:
- match = id2match[x.match_id]
- from_ = id2person[x.from_id]
- to = id2person[x.to_id]
- except Exception as e:
- yield echain(RuntimeError(f'while processing {x}'), e)
- continue
- yield Message(
- sent=x.sent,
- match=match,
- id=x.id,
- text=x.text,
- from_=from_,
- to=to,
- )
- continue
- assert_never(x)
-
-
-def messages() -> Iterator[Res[Message]]:
- for x in entities():
- if isinstance(x, (Exception, Message)):
- yield x
- continue
-
-
-# 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)
- for x in entities():
- if isinstance(x, Exception):
- yield x
- continue
- if isinstance(x, Match):
- # match might happen without messages so makes sense to handle here
- res[x] # just trigger creation
- continue
- if isinstance(x, Message):
- try:
- ml = res[x.match]
- except Exception as e:
- yield e
- continue
- ml.append(x)
- continue
- yield res
-
-
-# TODO maybe a more natural return type is Iterator[Res[Tuple[Key, Value]]]
-# but this doesn't work straight away because the key might have no corresponding values
-
-
-def stats() -> Stats:
- return stat(messages)
diff --git a/my/topcoder.py b/my/topcoder.py
deleted file mode 100644
index 40df77c..0000000
--- a/my/topcoder.py
+++ /dev/null
@@ -1,92 +0,0 @@
-import json
-from collections.abc import Iterator, Sequence
-from dataclasses import dataclass
-from functools import cached_property
-from pathlib import Path
-
-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] # isort: skip
-
-
-def inputs() -> Sequence[Path]:
- return get_files(config.export_path)
-
-
-@dataclass
-class Competition:
- contest_id: str
- contest: str
- percentile: float
- date_str: str
-
- @cached_property
- def uid(self) -> str:
- return self.contest_id
-
- @cached_property
- def when(self) -> datetime_aware:
- return fromisoformat(self.date_str)
-
- @classmethod
- 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,
- date_str=date_str,
- )
-
-
-def _parse_one(p: Path) -> Iterator[Res[Competition]]:
- d = json.loads(p.read_text())
-
- # TODO manager should be a context manager?
- m = Manager()
-
- h = m.helper(d)
- h.pop_if_primitive('version', 'id')
-
- h = h.zoom('result')
- h.check('success', expected=True)
- h.check('status', 200)
- h.pop_if_primitive('metadata')
-
- h = h.zoom('content')
- h.pop_if_primitive('handle', 'handleLower', 'userId', 'createdAt', 'updatedAt', 'createdBy', 'updatedBy')
-
- # 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')
-
- 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')
-
- 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 only
- yield from Competition.make(j=c)
-
- yield from m.check()
-
-
-def data() -> Iterator[Res[Competition]]:
- *_, last = inputs()
- return _parse_one(last)
diff --git a/my/twitter/all.py b/my/twitter/all.py
index c2c471e..efdc991 100644
--- a/my/twitter/all.py
+++ b/my/twitter/all.py
@@ -1,15 +1,15 @@
"""
Unified Twitter data (merged from the archive and periodic updates)
"""
-from collections.abc import Iterator
-
+from typing import Iterator
from ..core import Res
from ..core.source import import_source
-from .common import Tweet, merge_tweets
+from .common import merge_tweets, Tweet
+
# NOTE: you can comment out the sources you don't need
-src_twint = import_source(module_name='my.twitter.twint')
-src_archive = import_source(module_name='my.twitter.archive')
+src_twint = import_source(module_name=f'my.twitter.twint')
+src_archive = import_source(module_name=f'my.twitter.archive')
@src_twint
@@ -35,15 +35,13 @@ def _likes_archive() -> Iterator[Res[Tweet]]:
def tweets() -> Iterator[Res[Tweet]]:
- # for tweets, archive data is higher quality
yield from merge_tweets(
- _tweets_archive(),
_tweets_twint(),
+ _tweets_archive(),
)
def likes() -> Iterator[Res[Tweet]]:
- # for likes, archive data barely has anything so twint is preferred
yield from merge_tweets(
_likes_twint(),
_likes_archive(),
diff --git a/my/twitter/android.py b/my/twitter/android.py
deleted file mode 100644
index 7e8f170..0000000
--- a/my/twitter/android.py
+++ /dev/null
@@ -1,318 +0,0 @@
-"""
-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
-from struct import unpack_from
-
-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
-
-from .common import permalink
-
-import my.config # isort: skip
-
-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]:
- # 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)
-
-
-@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:
- 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]
- skip(sep_idx)
- return zz.decode('utf8')
-
- skip(2) # always starts with 4a03?
-
- (xx,) = unpack_from('B', data, offset=pos)
- skip(1)
-
- # wtf is this... maybe it's a bitmask?
- slen = {
- 66: 1,
- 67: 2,
- 106: 1,
- 107: 2,
- }[xx]
-
- 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
-
- 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[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',
- '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',
- ]:
- 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
-
-
-# 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
-# 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
-# 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/notification
-# 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]]:
- # 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:
- own_user_id = get_own_user_id(db)
- db_where = where.replace(_SELECT_OWN_TWEETS, own_user_id)
- else:
- db_where = where
-
- # 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
- 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]]:
- # TODO might need to sort by timeline_sort_index again?
- 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, 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: 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'users.user_id == {_SELECT_OWN_TWEETS} OR statuses.retweeted == 1')
diff --git a/my/twitter/archive.py b/my/twitter/archive.py
index c9d2dbc..1362137 100644
--- a/my/twitter/archive.py
+++ b/my/twitter/archive.py
@@ -2,84 +2,63 @@
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
-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
-from itertools import chain
-from pathlib import Path
-from typing import (
- TYPE_CHECKING,
-)
-
-from more_itertools import unique_everseen
-
-from my.core import (
- Json,
- Paths,
- Res,
- Stats,
- datetime_aware,
- get_files,
- make_logger,
- stat,
- warnings,
-)
-from my.core.serialize import dumps as json_dumps
-
-from .common import TweetId, permalink
-
-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
+# before this config was named 'twitter', doesn't make too much sense for archive
+# try to import it defensively..
+try:
+ from my.config import twitter_archive as user_config
+except ImportError as e:
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')
- ##
+ from my.config import twitter as user_config
+ except ImportError:
+ raise e # raise the original exception.. must be something else
+ else:
+ from ..core import warnings
+ 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()
+from dataclasses import dataclass
+from ..core.common import Paths, datetime_aware
+from ..core.error import Res
+
+@dataclass
+class twitter_archive(user_config):
+ export_path: Paths # path[s]/glob to the twitter archive takeout
+
+
+###
+
+from ..core.cfg import make_config
+config = make_config(twitter_archive)
+
+
+from datetime import datetime
+from typing import List, Optional, NamedTuple, Sequence, Iterator
+from pathlib import Path
+import json
+
+from ..core.common import get_files, LazyLogger, Json
+from ..core import kompress
+
+
+
+logger = LazyLogger(__name__, level="warning")
def inputs() -> Sequence[Path]:
- return get_files(make_config().export_path)
+ return get_files(config.export_path)[-1:]
+
+
+Tid = str
# TODO make sure it's not used anywhere else and simplify interface
-@dataclass
-class Tweet:
+class Tweet(NamedTuple):
raw: Json
screen_name: str
@property
- def id_str(self) -> TweetId:
+ def id_str(self) -> str:
return self.raw['id_str']
@property
@@ -89,47 +68,20 @@ class Tweet:
@property
def permalink(self) -> str:
- return permalink(screen_name=self.screen_name, id=self.id_str)
+ return f'https://twitter.com/{self.screen_name}/status/{self.tid}'
@property
def text(self) -> str:
- res: str = self.raw['full_text']
-
- ## replace shortened URLS
- repls = [] # from, to, what
- for ue in self.entities['urls']:
- [fr, to] = map(int, ue['indices'])
- repls.append((fr, to, ue['expanded_url']))
- # seems that media field isn't always set
- for me in self.entities.get('media', []):
- [fr, to] = map(int, me['indices'])
- 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 = sorted(repls)
- parts = []
- idx = 0
- for fr, to, what in repls:
- parts.append(res[idx:fr])
- parts.append(what)
- idx = to
- parts.append(res[idx:])
- res = ''.join(parts)
- ##
-
- # replace stuff like </>
- res = html.unescape(res)
- return res
+ return self.raw['full_text']
@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]
@property
def entities(self) -> Json:
- # todo hmm what is 'extended_entities'
return self.raw['entities']
def __str__(self) -> str:
@@ -140,62 +92,59 @@ class Tweet:
# TODO deprecate tid?
@property
- def tid(self) -> TweetId:
+ def tid(self) -> Tid:
return self.id_str
@property
- def dt(self) -> datetime_aware:
+ def dt(self) -> datetime:
return self.created_at
-@dataclass
-class Like:
+class Like(NamedTuple):
raw: Json
screen_name: str
+ # TODO need to make permalink/link/url consistent across my stuff..
@property
def permalink(self) -> str:
# doesn'tseem like link it export is more specific...
- return permalink(screen_name=self.screen_name, id=self.id_str)
+ return f'https://twitter.com/{self.screen_name}/status/{self.tid}'
@property
- def id_str(self) -> TweetId:
+ def id_str(self) -> Tid:
return self.raw['tweetId']
@property
- def text(self) -> str | None:
- # NOTE: likes basically don't have anything except text and url
+ def text(self) -> Optional[str]:
# ugh. I think none means that tweet was deleted?
- res: str | None = self.raw.get('fullText')
- if res is None:
- return None
- res = html.unescape(res)
- return res
+ return self.raw.get('fullText')
# TODO deprecate?
@property
- def tid(self) -> TweetId:
+ def tid(self) -> Tid:
return self.id_str
+from functools import lru_cache
class ZipExport:
def __init__(self, archive_path: Path) -> None:
- self.zpath = archive_path
- if (self.zpath / 'tweets.csv').exists():
- warnings.high("NOTE: CSV format (pre ~Aug 2018) isn't supported yet, this is likely not going to work.")
- self.old_format = False # changed somewhere around 2020.03
- if not (self.zpath / 'Your archive.html').exists():
+ self.epath = archive_path
+
+ self.old_format = False # changed somewhere around 2020.03
+ if not kompress.kexists(self.epath, 'Your archive.html'):
self.old_format = True
- def raw(self, what: str, *, fname: str | None = None) -> Iterator[Json]:
- logger.info(f'{self.zpath} : processing {what}')
- path = fname or what
+ def raw(self, what: str): # TODO Json in common?
+ logger.info('processing: %s %s', self.epath, what)
+
+ path = what
if not self.old_format:
path = 'data/' + path
path += '.js'
- ddd = (self.zpath / path).read_text()
+ with kompress.kopen(self.epath, path) as fo:
+ ddd = fo.read()
start = ddd.index('[')
ddd = ddd[start:]
for j in json.loads(ddd):
@@ -206,117 +155,37 @@ class ZipExport:
# older format
yield j
- @cached_property
+ @lru_cache(1)
def screen_name(self) -> str:
- [acc] = self.raw(what='account')
+ [acc] = self.raw('account')
return acc['username']
def tweets(self) -> Iterator[Tweet]:
- fname = 'tweets' # since somewhere between mar and oct 2022
- if not (self.zpath / f'data/{fname}.js').exists():
- fname = 'tweet' # old name
- # NOTE: for some reason, created_at doesn't seem to be in order
- # it mostly is, but there are a bunch of one-off random tweets where the time decreases (typically at the very end)
- for r in self.raw(what='tweet', fname=fname):
- yield Tweet(r, screen_name=self.screen_name)
+ for r in self.raw('tweet'):
+ yield Tweet(r, screen_name=self.screen_name())
+
def likes(self) -> Iterator[Like]:
# TODO ugh. would be nice to unify Tweet/Like interface
# however, akeout only got tweetId, full text and url
- for r in self.raw(what='like'):
- 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)
+ for r in self.raw('like'):
+ yield Like(r, screen_name=self.screen_name())
# 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())
-
- # 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)
+ for inp in inputs():
+ yield from sorted(ZipExport(inp).tweets(), key=lambda t: t.dt)
def likes() -> Iterator[Res[Like]]:
- _all = chain.from_iterable(ZipExport(i).likes() for i in inputs())
- res = unique_everseen(_all, key=json_dumps)
- # ugh. likes don't have datetimes..
- yield from res
+ for inp in inputs():
+ yield from ZipExport(inp).likes()
+from ..core import stat, Stats
def stats() -> Stats:
return {
**stat(tweets),
**stat(likes),
}
-
-
-## Deprecated stuff
-if not TYPE_CHECKING:
- Tid = TweetId
diff --git a/my/twitter/common.py b/my/twitter/common.py
index 8c346f6..5fd7daa 100644
--- a/my/twitter/common.py
+++ b/my/twitter/common.py
@@ -1,32 +1,21 @@
-from my.core import __NOT_HPI_MODULE__ # isort: skip
+from my.core import __NOT_HPI_MODULE__
-from collections.abc import Iterator
from itertools import chain
-from typing import Any
+from typing import Iterator, Any
from more_itertools import unique_everseen
+
# TODO add proper Protocol for Tweet
Tweet = Any
-TweetId = str
-
-
-from my.core import Res, warn_if_empty
+from my.core import warn_if_empty, Res
@warn_if_empty
def merge_tweets(*sources: Iterator[Res[Tweet]]) -> Iterator[Res[Tweet]]:
def key(r: Res[Tweet]):
if isinstance(r, Exception):
return str(r)
else:
- # using both fields as key makes it a bit easier to spot TZ issues
- return (r.id_str, r.created_at)
+ return r.id_str
yield from unique_everseen(chain(*sources), key=key)
-
-
-def permalink(*, screen_name: str, id: str) -> str:
- return f'https://twitter.com/{screen_name}/status/{id}'
-
-# NOTE: tweets from archive are coming sorted by created_at
-# NOTE: tweets from twint are also sorted by created_at?
diff --git a/my/twitter/talon.py b/my/twitter/talon.py
index dbf2e2e..4b42b1f 100644
--- a/my/twitter/talon.py
+++ b/my/twitter/talon.py
@@ -1,72 +1,52 @@
"""
Twitter data from Talon app database (in =/data/data/com.klinker.android.twitter_l/databases/=)
"""
-
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 datetime import datetime
+from typing import Iterator, Sequence, Optional, Dict
+
+import pytz
+
+from my.config import twitter as user_config
+
+
+from ..core import Paths, Res, datetime_aware
+@dataclass
+class config(user_config.talon):
+ # paths[s]/glob to the exported sqlite databases
+ export_path: Paths
+
+
+from ..core import get_files
from pathlib import Path
-from typing import Union
-
-from my.core import Paths, Res, datetime_aware, get_files
-from my.core.common import unique_everseen
-from my.core.sqlite import sqlite_connection
-
-from .common import TweetId, permalink
-
-
-class config:
- @property
- @abstractmethod
- def export_path(self) -> Paths:
- raise NotImplementedError
-
-
-def make_config() -> config:
- from my.config import twitter as user_config
-
- class combined_config(user_config.talon, config):
- pass
-
- return combined_config()
-
-
def inputs() -> Sequence[Path]:
- return get_files(make_config().export_path)
+ return get_files(config.export_path)
+
@dataclass(unsafe_hash=True)
class Tweet:
- id_str: TweetId
+ id_str: str
created_at: datetime_aware
screen_name: str
text: str
urls: Sequence[str]
- @property
- def permalink(self) -> str:
- return permalink(screen_name=self.screen_name, id=self.id_str)
-
# meh... just wrappers to tell apart tweets from favorites...
@dataclass(unsafe_hash=True)
class _IsTweet:
tweet: Tweet
-
-
@dataclass(unsafe_hash=True)
class _IsFavorire:
tweet: Tweet
+from typing import Union
+from ..core.dataset import connect_readonly
Entity = Union[_IsTweet, _IsFavorire]
-
-
def _entities() -> Iterator[Res[Entity]]:
for f in inputs():
yield from _process_one(f)
@@ -74,92 +54,67 @@ 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
handler = handlers.get(fname)
if handler is None:
- yield RuntimeError(f"Could not find handler for {fname}")
+ yield RuntimeError(f"Coulnd't find handler for {fname}")
return
- with sqlite_connection(f, immutable=True, row_factory='row') as db:
+ with connect_readonly(f) as db:
yield from handler(db)
-def _process_user_tweets(db: sqlite3.Connection) -> Iterator[Res[Entity]]:
+def _process_user_tweets(db) -> Iterator[Res[Entity]]:
# dunno why it's called 'lists'
- for r in db.execute('SELECT * FROM lists ORDER BY time'):
+ for r in db['lists'].all(order_by='time'):
try:
yield _IsTweet(_parse_tweet(r))
except Exception as e:
yield e
-def _process_favorite_tweets(db: sqlite3.Connection) -> Iterator[Res[Entity]]:
- for r in db.execute('SELECT * FROM favorite_tweets ORDER BY time'):
+def _process_favorite_tweets(db) -> Iterator[Res[Entity]]:
+ for r in db['favorite_tweets'].all(order_by='time'):
try:
yield _IsFavorire(_parse_tweet(r))
except Exception as e:
yield e
+def _parse_tweet(row) -> Tweet:
+ # TODO row['retweeter] if not empty, would be user's name and means retweet?
+ # screen name would be the actual tweet's author
-def _parse_tweet(row: sqlite3.Row) -> Tweet:
# ok so looks like it's tz aware..
# https://github.com/klinker24/talon-for-twitter-android/blob/c3b0612717ba3ea93c0cae6d907d7d86d640069e/app/src/main/java/com/klinker/android/twitter_l/data/sq_lite/FavoriteTweetsDataSource.java#L95
# uses https://docs.oracle.com/javase/7/docs/api/java/util/Date.html#getTime()
# and it's created here, so looks like it's properly parsed from the api
# https://github.com/Twitter4J/Twitter4J/blob/8376fade8d557896bb9319fb46e39a55b134b166/twitter4j-core/src/internal-json/java/twitter4j/ParseUtil.java#L69-L79
- created_at = datetime.fromtimestamp(row['time'] / 1000, tz=timezone.utc)
- text = row['text']
-
- # try explanding URLs.. sadly there are no positions in the db
- urls = row['other_url'].split()
- if len(urls) > 0:
- ellipsis = '...'
- # might have something collapsed
- # e.g. deepmind.com/blog/article/Comp...
- # NOTE: need a one character of lookahead to split on ellipsis.. hence ?=
- for short in re.findall(r'(?:^|\s)([\S]+)' + re.escape(ellipsis) + r'(?=\s|$)', text):
- for full in urls:
- if short in full:
- text = text.replace(short + ellipsis, full)
- break
- #
-
- screen_name = row['screen_name']
- # considering id_str is referring to the retweeter's tweet (rather than the original tweet)
- # makes sense for the permalink to contain the retweeter as well
- # also makes it more compatible to twitter archive
- # a bit sad to lose structured information about RT, but then again we could always just parse it..
- retweeter = row['retweeter']
- if len(retweeter) > 0:
- text = f'RT @{screen_name}: {text}'
- screen_name = retweeter
+ created_at = datetime.fromtimestamp(row['time'] / 1000, tz=pytz.utc)
return Tweet(
id_str=str(row['tweet_id']),
created_at=created_at,
- screen_name=screen_name,
- text=text,
+ screen_name=row['screen_name'],
+ text=row['text'],
# todo hmm text sometimes is trimmed with ellipsis? at least urls
urls=tuple(u for u in row['other_url'].split(' ') if len(u.strip()) > 0),
)
+from more_itertools import unique_everseen
def tweets() -> Iterator[Res[Tweet]]:
- for x in unique_everseen(_entities):
+ for x in unique_everseen(_entities()):
if isinstance(x, Exception):
yield x
elif isinstance(x, _IsTweet):
yield x.tweet
-
def likes() -> Iterator[Res[Tweet]]:
- for x in unique_everseen(_entities):
+ for x in unique_everseen(_entities()):
if isinstance(x, Exception):
yield x
elif isinstance(x, _IsFavorire):
yield x.tweet
-
-# TODO maybe should combine all public iterators into a stats()
diff --git a/my/twitter/twint.py b/my/twitter/twint.py
index 9d36a93..ee84ea1 100644
--- a/my/twitter/twint.py
+++ b/my/twitter/twint.py
@@ -1,17 +1,13 @@
"""
Twitter data (tweets and favorites). Uses [[https://github.com/twintproject/twint][Twint]] data export.
"""
-from collections.abc import Iterator
+
+REQUIRES = ['dataset']
+
+from ..core.common import Paths
+from ..core.error import Res
from dataclasses import dataclass
-from datetime import datetime, timezone
-from pathlib import Path
-from typing import NamedTuple
-
-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 # isort: skip
+from my.config import twint as user_config
# TODO move to twitter.twint config structure
@@ -21,9 +17,17 @@ class twint(user_config):
####
+from ..core.cfg import make_config
config = make_config(twint)
+from datetime import datetime
+from typing import NamedTuple, Iterator, List
+from pathlib import Path
+
+from ..core.common import get_files, LazyLogger, Json, datetime_aware
+from ..core.time import abbr_to_timezone
+
log = LazyLogger(__name__)
@@ -31,60 +35,41 @@ def get_db_path() -> Path:
return max(get_files(config.export_path))
-from .common import TweetId, permalink
-
-
class Tweet(NamedTuple):
row: Json
@property
- def id_str(self) -> TweetId:
+ def id_str(self) -> str:
return self.row['id_str']
@property
def created_at(self) -> datetime_aware:
seconds = self.row['created_at'] / 1000
- tz = timezone.utc
- # NOTE: UTC seems to be the case at least for the older version of schema I was using
- # in twint, it was extracted from "data-time-ms" field in the scraped HML
- # https://github.com/twintproject/twint/blob/e3345426eb24154ff084be22e4fed5cfa4631930/twint/tweet.py#L85
- #
- # I checked against twitter archive which is definitely UTC, and it seems to match
- # also seems that other people are treating it as utc, e.g.
- # 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 keeping lots on unnecessary stuff in the db)
- return datetime.fromtimestamp(seconds, tz=tz)
+ tz_abbr = self.row['timezone']
+ tz = abbr_to_timezone(tz_abbr)
+ dt = datetime.fromtimestamp(seconds, tz=tz)
+ return dt
+ # TODO permalink -- take user into account?
@property
def screen_name(self) -> str:
return self.row['screen_name']
@property
def text(self) -> str:
- text = self.row['tweet']
- mentions_s = self.row['mentions']
- if len(mentions_s) > 0:
- # at some point for no apparent reasions mentions stopped appearing from tweet text in twint
- # note that the order is still inconsisnent against twitter archive, but not much we can do
- mentions = mentions_s.split(',')
- for m in mentions:
- # ugh. sometimes they appear as lowercase in text, sometimes not..
- if m.lower() not in text.lower():
- text = f'@{m} ' + text
- return text
+ return self.row['tweet']
@property
- def urls(self) -> list[str]:
+ def urls(self) -> List[str]:
ustr = self.row['urls']
if len(ustr) == 0:
return []
return ustr.split(',')
+ # TODO move to common
@property
def permalink(self) -> str:
- return permalink(screen_name=self.screen_name, id=self.id_str)
+ return f'https://twitter.com/{self.screen_name}/status/{self.id_str}'
# TODO urls
@@ -107,19 +92,25 @@ WHERE {where}
ORDER BY T.created_at
'''
+def _get_db():
+ from ..core.dataset import connect_readonly
+ db_path = get_db_path()
+ return connect_readonly(db_path)
+
def tweets() -> Iterator[Res[Tweet]]:
- with sqlite_connection(get_db_path(), immutable=True, row_factory='dict') as db:
- res = db.execute(_QUERY.format(where='F.tweet_id IS NULL'))
- yield from map(Tweet, res)
+ db = _get_db()
+ res = db.query(_QUERY.format(where='F.tweet_id IS NULL'))
+ yield from map(Tweet, res)
def likes() -> Iterator[Res[Tweet]]:
- with sqlite_connection(get_db_path(), immutable=True, row_factory='dict') as db:
- res = db.execute(_QUERY.format(where='F.tweet_id IS NOT NULL'))
- yield from map(Tweet, res)
+ db = _get_db()
+ res = db.query(_QUERY.format(where='F.tweet_id IS NOT NULL'))
+ yield from map(Tweet, res)
+from ..core import stat, Stats
def stats() -> Stats:
return {
**stat(tweets),
diff --git a/my/util/hpi_heartbeat.py b/my/util/hpi_heartbeat.py
deleted file mode 100644
index 6dcac7e..0000000
--- a/my/util/hpi_heartbeat.py
+++ /dev/null
@@ -1,55 +0,0 @@
-"""
-Just an helper module for testing HPI overlays
-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__ # isort: skip
-
-import sys
-from collections.abc import Iterator
-from dataclasses import dataclass
-from datetime import datetime
-
-NOW = datetime.now()
-
-
-@dataclass
-class Item:
- dt: datetime
- message: str
- path: list[str]
-
-
-def get_pkg_path() -> list[str]:
- pkg = sys.modules[__package__]
- return list(pkg.__path__)
-
-
-# NOTE: since we're hacking path for my.util
-# imports from my. should work as expected
-# (even though my.config is in the private config)
-from my.config import demo
-
-assert demo.username == 'todo'
-
-# however, this won't work while the module is imported
-# from my.util import extra
-# assert extra.message == 'EXTRA'
-# but it will work when we actually call the function (see below)
-
-
-def items() -> Iterator[Item]:
- from my.config import demo
-
- assert demo.username == 'todo'
-
- # here the import works as expected, since by the time the function is called,
- # all overlays were already processed and paths/sys.modules restored
- from my.util import extra # type: ignore[attr-defined]
-
- assert extra.message == 'EXTRA'
-
- yield Item(dt=NOW, message='hpi main', path=get_pkg_path())
diff --git a/my/vk/favorites.py b/my/vk/favorites.py
index 5f278ff..e6ccbf3 100644
--- a/my/vk/favorites.py
+++ b/my/vk/favorites.py
@@ -1,28 +1,28 @@
-# todo: uses my private export script?, timezone
-from __future__ import annotations
-
+# todo: uses my private export script?
+from datetime import datetime
import json
-from collections.abc import Iterable, Iterator
-from dataclasses import dataclass
-from datetime import datetime, timezone
+from typing import NamedTuple, Iterable, Sequence, Optional
-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
+from my.config import vk as config
-@dataclass
-class Favorite:
- dt: datetime_aware
+class Favorite(NamedTuple):
+ dt: datetime
title: str
- url: str | None
+ url: Optional[str]
text: str
+from ..core import Json
+from ..core.error import Res
+
+
skip = (
'graffiti',
'poll',
- 'note', # TODO could be useful..
+
+ # TODO could be useful..
+ 'note',
'doc',
'audio',
'photo',
@@ -31,11 +31,10 @@ 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.fromtimestamp(j['date'], tz=timezone.utc),
+ dt=datetime.utcfromtimestamp(j['date']),
title=title,
url=url,
text=j['text'],
)
-def _iter_favs() -> Iterator[Res]:
+def _iter_favs() -> Iterable[Res]:
jj = json.loads(config.favs_file.read_text())
for j in jj:
try:
@@ -65,7 +64,7 @@ def _iter_favs() -> Iterator[Res]:
yield ex
-def favorites() -> Iterable[Res]:
+def favorites() -> Sequence[Res]:
it = _iter_favs()
# trick to sort errors along with the actual objects
# TODO wonder if there is a shorter way?
@@ -76,11 +75,12 @@ def favorites() -> Iterable[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() -> Stats:
+def stats():
+ from ..core import stat
return stat(favorites)
diff --git a/my/vk/vk_messages_backup.py b/my/vk/vk_messages_backup.py
index 4f593c8..0e8dc45 100644
--- a/my/vk/vk_messages_backup.py
+++ b/my/vk/vk_messages_backup.py
@@ -2,157 +2,95 @@
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, Iterable, NamedTuple
import pytz
+from ..core import Json
+
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?
-TZ = pytz.timezone('Europe/Moscow')
-Uid = int
+Uid = str
+Name = str
-@dataclass(frozen=True)
-class User:
- id: Uid
- first_name: str
- last_name: str
-
-
-@dataclass(frozen=True)
-class Chat:
- chat_id: str
- title: str
-
-
-@dataclass(frozen=True)
-class Message:
- dt: datetime_aware
- chat: Chat
- id: str # todo not sure it's unique?
- user: User
- body: str
-
-
-Users = dict[Uid, User]
-
+Users = Dict[Uid, Name]
def users() -> Users:
- files = get_files(config.storage_path, glob='user_*.json')
+ # todo cache?
+ files = list(sorted(config.storage_path.glob('user_*.json')))
res = {}
for f in files:
j = json.loads(f.read_text())
uid = j['id']
- res[uid] = User(
- id=uid,
- first_name=j['first_name'],
- last_name=j['last_name'],
- )
+ uf = j['first_name']
+ ul = j['last_name']
+ res[uid] = f'{uf} {ul}'
return res
-GROUP_CHAT_MIN_ID = 2000000000
+class Message(NamedTuple):
+ chat_id: str
+ dt: datetime
+ user: Name
+ body: str
-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')
- if peer_id is not None:
- chat_id = peer_id
- else:
- group_chat_id = msg.get('chat_id')
- if group_chat_id is not None:
- chat_id = GROUP_CHAT_MIN_ID + group_chat_id
- else:
- chat_id = msg['user_id']
+msk_tz = pytz.timezone('Europe/Moscow')
+# todo hmm, vk_messages_backup used this tz? not sure if vk actually used to return this tz in api?
- is_group_chat = chat_id >= GROUP_CHAT_MIN_ID
- if is_group_chat:
- title = msg['title']
- else:
- user_id = msg.get('user_id') or msg.get('from_id')
- assert user_id is not None
- user = udict[user_id]
- title = f'{user.first_name} {user.last_name}'
- return Chat(
- chat_id=chat_id,
- title=title,
- )
+def _parse(x: Json, chat_id: str, udict: Users) -> Message:
+ mid = x['id'] # todo not sure if useful?
+ md = x['date']
-
-def _parse_msg(*, msg: Json, chat: Chat, udict: Users) -> Message:
- mid = msg['id']
- md = msg['date']
-
- dt = datetime.fromtimestamp(md, tz=TZ)
+ dt = datetime.fromtimestamp(md, msk_tz)
# todo attachments? e.g. url could be an attachment
# todo might be forwarded?
- mb = msg.get('body')
+ mb = x.get('body')
if mb is None:
- mb = msg.get('text')
- assert mb is not None, msg
+ mb = x.get('text')
+ assert mb is not None
+
+ mu = x.get('user_id') or x.get('peer_id')
+ assert mu is not None
+ out = x['out'] == 1
+ # todo use name from the config?
+ user = 'you' if out else udict[mu]
+
+ # todo conversation id??
- out = msg['out'] == 1
- if out:
- user = udict[config.user_id]
- else:
- mu = msg.get('user_id') or msg.get('from_id')
- assert mu is not None, msg
- user = udict[mu]
return Message(
+ chat_id=chat_id,
dt=dt,
- chat=chat,
- id=mid,
user=user,
body=mb,
)
-def _messages() -> Iterator[Res[Message]]:
+from ..core.error import Res
+def messages() -> Iterable[Res[Message]]:
udict = users()
- uchats = get_files(config.storage_path, glob='userchat_*.json') + get_files(config.storage_path, glob='groupchat_*.json')
+ uchats = list(sorted(config.storage_path.glob('userchat_*.json' ))) + \
+ list(sorted(config.storage_path.glob('groupchat_*.json')))
for f in uchats:
+ chat_id = f.stem.split('_')[-1]
j = json.loads(f.read_text())
- # ugh. very annoying, sometimes not possible to extract title from last message
- # due to newer api...
- # so just do in defensively until we succeed...
- chat = None
- ex = None
- for m in reversed(j):
+ for x in j:
try:
- chat = _parse_chat(msg=m, udict=udict)
- except Exception as e:
- ex = e
- continue
- if chat is None:
- assert ex is not None
- yield ex
- continue
-
- for msg in j:
- try:
- yield _parse_msg(msg=msg, chat=chat, udict=udict)
+ yield _parse(x, chat_id=chat_id, udict=udict)
except Exception as e:
yield e
-def messages() -> Iterator[Res[Message]]:
- # seems that during backup messages were sometimes duplicated..
- yield from unique_everseen(_messages)
-
-
-def stats() -> Stats:
+def stats():
+ from ..core import stat
return {
**stat(users),
**stat(messages),
diff --git a/my/whatsapp/android.py b/my/whatsapp/android.py
deleted file mode 100644
index a8dbe8d..0000000
--- a/my/whatsapp/android.py
+++ /dev/null
@@ -1,238 +0,0 @@
-"""
-Whatsapp data from Android app database (in =/data/data/com.whatsapp/databases/msgstore.db=)
-"""
-
-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
-from typing import Union
-
-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 # isort: skip
-
-logger = make_logger(__name__)
-
-
-@dataclass
-class Config(my.config.whatsapp.android):
- # paths[s]/glob to the exported sqlite databases
- export_path: Paths
- my_user_id: str | None = None
-
-
-config = make_config(Config)
-
-
-def inputs() -> Sequence[Path]:
- return get_files(config.export_path)
-
-
-@dataclass(unsafe_hash=True)
-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: str | None
-
-
-@dataclass(unsafe_hash=True)
-class Sender:
- id: str
- name: str | None
-
-
-@dataclass(unsafe_hash=True)
-class Message:
- chat: Chat
- id: str
- dt: datetime_aware
- sender: Sender
- text: str | None
-
-
-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(
- 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) */
- '''
- ):
- chat_id = r['chat_id']
- subject = r['subject']
- chat = Chat(
- id=chat_id,
- name=subject,
- )
- yield chat
- chats[chat.id] = chat
-
- senders = {}
- for r in db.execute(
- '''
- SELECT _id, raw_string
- FROM jid
- '''
- ):
- # 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,
- )
- yield s
- senders[r['_id']] = s
-
- # NOTE: hmm, seems that message_view or available_message_view use lots of NULL as ...
- # 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
- {chat_id_col} AS chat_id,
- M.key_id, M.timestamp,
- sender_jid_row_id,
- M.from_me,
- M.text_data,
- MM.file_path,
- MM.file_size,
- M.message_type
- FROM message AS M
- 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
- for normal messages it's 0
- */
- AND M.message_type != 7
- ORDER BY M.timestamp
- '''
- ):
- msg_id: str = notnone(r['key_id'])
- ts: int = notnone(r['timestamp'])
- dt = datetime.fromtimestamp(ts / 1000, tz=timezone.utc)
-
- 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']
-
- if text is None:
- # fmt: off
- text = {
- 5 : '[MAP LOCATION]',
- 10: '[MISSED VOICE CALL]',
- 15: '[DELETED]',
- 16: '[LIVE LOCATION]',
- 64: '[DELETED]', # seems like 'deleted by admin'?
- }.get(message_type)
- # fmt: on
-
- # check against known msg types
- # fmt: off
- if text is None and message_type not in {
- 0, # normal
- 1, # image
- 2, # voice note
- 3, # video
- 7, # "system" message, e.g. chat name
- 8, # document
- 9, # also document?
- 13, # animated gif?
- 20, # webp/sticker?
- }:
- text = f"[UNKNOWN TYPE {message_type}]"
- # fmt: on
-
- if media_file_size is not None:
- # this is always not null for message_media table
- # however media_file_path sometimes may be none
- mm = f'MEDIA: {media_file_path}'
- if text is None:
- text = mm
- else:
- text = text + '\n' + mm
-
- from_me = r['from_me'] == 1
-
- chat_id = r['chat_id']
- if chat_id is None:
- # ugh, I think these might have been edited messages? unclear..
- logger.warning(f"CHAT ID IS NONE, WTF?? {dt} {ts} {text}")
- continue
- chat = chats[chat_id]
-
- 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 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?
- else:
- sender = Sender(id=chat.id, name=None)
- else:
- sender = senders[sender_row_id]
-
- m = Message(chat=chat, id=msg_id, dt=dt, sender=sender, text=text)
- yield m
-
-
-def _entities() -> Iterator[Res[Entity]]:
- paths = inputs()
- total = len(paths)
- width = len(str(total))
- 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:
- try:
- yield from _process_db(db)
- except Exception as e:
- yield echain(RuntimeError(f'While processing {path}'), cause=e)
-
-
-def entities() -> Iterator[Res[Entity]]:
- return unique_everseen(_entities)
-
-
-def messages() -> Iterator[Res[Message]]:
- # 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
diff --git a/my/youtube/takeout.py b/my/youtube/takeout.py
deleted file mode 100644
index 8eca328..0000000
--- a/my/youtube/takeout.py
+++ /dev/null
@@ -1,183 +0,0 @@
-from __future__ import annotations
-
-from collections.abc import Iterable, Iterator
-from dataclasses import dataclass
-from typing import TYPE_CHECKING, Any
-
-from my.core import Res, Stats, datetime_aware, make_logger, stat, warnings
-from my.core.compat import deprecated
-
-logger = make_logger(__name__)
-
-
-@dataclass
-class Watched:
- url: str
- title: str
- when: datetime_aware
-
- @property
- 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() -> 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
- # 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)
-
- 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.models import Activity
-
- from ..google.takeout.parser import events
- except ModuleNotFoundError as ex:
- logger.exception(ex)
- 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='
-
- # TODO would be nice to filter, e.g. it's kinda pointless to process Location events
- for e in events():
- if isinstance(e, Exception):
- yield e
- continue
-
- if not isinstance(e, Activity):
- continue
-
- url = e.titleUrl
-
- 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
-
- if header not in {'YouTube', 'youtube.com'}:
- # TODO hmm -- wonder if these would end up in dupes in takeout? would be nice to check
- # perhaps this would be easier once we have universal ids
- if YOUTUBE_VIDEO_LINK in url:
- # TODO maybe log in this case or something?
- pass
- continue
-
- title = e.title
-
- if header == 'youtube.com' and title.startswith('Visited '):
- continue
-
- if title.startswith('Searched for') and url.startswith('https://www.youtube.com/results'):
- # search activity, don't need it here
- continue
-
- if title.startswith('Subscribed to') and url.startswith('https://www.youtube.com/channel/'):
- # todo might be interesting to process somewhere?
- continue
-
- # all titles contain it, so pointless to include 'Watched '
- # also compatible with legacy titles
- title = title.removeprefix('Watched ')
-
- # watches originating from some activity end with this, remove it for consistency
- title = title.removesuffix(' - YouTube')
-
- if YOUTUBE_VIDEO_LINK not in url:
- if 'youtube.com/post/' in url:
- # some sort of channel updates?
- continue
- 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,
- when=e.time,
- )
-
-
-def stats() -> Stats:
- return stat(watched)
-
-
-### 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
-
- # 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))
-
- # todo hmm they already come sorted.. wonder if should just rely on it..
- return sorted(watches, key=lambda e: e.when)
diff --git a/my/zotero.py b/my/zotero.py
index 8eb34ba..3afc512 100644
--- a/my/zotero.py
+++ b/my/zotero.py
@@ -1,17 +1,15 @@
-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
-from typing import Any
+import sqlite3
-from my.core import Res, datetime_aware, make_logger
+from my.core import LazyLogger, Res, datetime_aware
from my.core.sqlite import sqlite_copy_and_open
-logger = make_logger(__name__)
+
+logger = LazyLogger(__name__, level='debug')
def inputs() -> Sequence[Path]:
@@ -28,7 +26,7 @@ class Item:
"""Corresponds to 'Zotero item'"""
file: Path
title: str
- url: Url | None
+ url: Optional[Url]
tags: Sequence[str]
@@ -41,8 +39,8 @@ class Annotation:
page: int
"""0-indexed"""
- text: str | None
- comment: str | None
+ text: Optional[str]
+ comment: Optional[str]
tags: Sequence[str]
color_hex: str
"""Original hex-encoded color in zotero"""
@@ -99,7 +97,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:
@@ -159,7 +157,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 d0cfcb7..b9bd190 100644
--- a/my/zulip/organization.py
+++ b/my/zulip/organization.py
@@ -1,55 +1,25 @@
"""
Zulip data from [[https://memex.zulipchat.com/help/export-your-organization][Organization export]]
"""
-
-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 typing import Sequence, Iterator, Dict
+
+from my.config import zulip as user_config
+
+from ..core import Paths
+@dataclass
+class organization(user_config.organization):
+ # paths[s]/glob to the exported JSON data
+ export_path: Paths
+
+
from pathlib import Path
-
-from my.core import (
- Json,
- Paths,
- Res,
- Stats,
- assert_never,
- datetime_aware,
- get_files,
- make_logger,
- stat,
- warnings,
-)
-
-logger = make_logger(__name__)
-
-
-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()
-
-
+from ..core import get_files, Json
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(make_config().export_path, sort=False)
+ return get_files(organization.export_path)
+
+
+from datetime import datetime
@dataclass(frozen=True)
@@ -69,11 +39,16 @@ class Sender:
# from the data, seems that subjects are completely implicit and determined by name?
# streams have ids (can extract from realm/zerver_stream), but unclear how to correlate messages/topics to streams?
+
@dataclass(frozen=True)
class _Message:
# todo hmm not sure what would be a good field order..
id: int
- sent: datetime_aware # double checked and they are in utc
+ sent: datetime
+ # TODO hmm kinda unclear whether it uses UTC or not??
+ # https://github.com/zulip/zulip/blob/0c2e4eec200d986a9a020f3e9a651d27216e0e85/zerver/models.py#L3071-L3076
+ # it keeps it tz aware.. but not sure what happens after?
+ # https://github.com/zulip/zulip/blob/1dfddffc8dac744fd6a6fbfd937018074c8bb166/zproject/computed_settings.py#L151
subject: str
sender_id: int
server_id: int
@@ -85,7 +60,7 @@ class _Message:
@dataclass(frozen=True)
class Message:
id: int
- sent: datetime_aware
+ sent: datetime
subject: str
sender: Sender
server: Server
@@ -101,40 +76,20 @@ class Message:
return f'https://{self.server.string_id}.zulipchat.com/#narrow/near/{self.id}'
-# todo cache it
-def _entities() -> Iterator[Res[Server | Sender | _Message]]:
+from typing import Union
+from itertools import count
+import json
+from ..core.error import Res
+from ..core.kompress import kopen, kexists
+# TODO cache it
+def _entities() -> Iterator[Res[Union[Server, Sender, _Message]]]:
+ # TODO hmm -- not sure if max lexicographically will actually be latest?
last = max(inputs())
+ no_suffix = last.name.split('.')[0]
- logger.info(f'extracting data from {last}')
-
- root: Path | None = None
-
- if last.is_dir(): # if it's already CPath, this will match it
- root = last
- else:
- 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[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())
+ # TODO check that it also works with unpacked dirs???
+ with kopen(last, f'{no_suffix}/realm.json') as f:
+ rj = json.load(f)
[sj] = rj['zerver_realm']
server = Server(
@@ -154,29 +109,28 @@ def _process_one(root: Path) -> Iterator[Res[Server | Sender | _Message]]:
for j in rj['zerver_userprofile_crossrealm']: # e.g. zulip bot
yield Sender(
id=j['id'],
- full_name=j['email'], # doesn't seem to have anything
+ full_name=j['email'], # doesn't seem to have anything
email=j['email'],
)
def _parse_message(j: Json) -> _Message:
ds = j['date_sent']
- # fmt: off
return _Message(
id = j['id'],
- sent = datetime.fromtimestamp(ds, tz=timezone.utc),
+ sent = datetime.fromtimestamp(ds),
subject = j['subject'],
sender_id = j['sender'],
server_id = server.id,
content = j['content'],
)
- # fmt: on
for idx in count(start=1, step=1):
fname = f'messages-{idx:06}.json'
- fpath = subdir / fname
- if not fpath.exists():
+ fpath = f'{no_suffix}/{fname}'
+ if not kexists(last, fpath):
break
- mj = json.loads(fpath.read_text())
+ with kopen(last, fpath) as f:
+ mj = json.load(f)
# TODO handle zerver_usermessage
for j in mj['zerver_message']:
try:
@@ -186,8 +140,8 @@ def _process_one(root: Path) -> Iterator[Res[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
@@ -209,8 +163,4 @@ def messages() -> Iterator[Res[Message]]:
content=x.content,
)
continue
- assert_never(x)
-
-
-def stats() -> Stats:
- return {**stat(messages)}
+ assert False # should be unreachable
diff --git a/mypy.ini b/mypy.ini
index 9c34fcc..bc85b74 100644
--- a/mypy.ini
+++ b/mypy.ini
@@ -1,14 +1,9 @@
[mypy]
pretty = True
show_error_context = True
-show_column_numbers = True
-show_error_end = True
-warn_redundant_casts = True
-warn_unused_ignores = True
+show_error_codes = True
check_untyped_defs = True
-strict_equality = True
-enable_error_code = possibly-undefined
-
+namespace_packages = True
# 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
# mypy_path=~/.config/my
diff --git a/pytest.ini b/pytest.ini
index aaa3df2..b6406e2 100644
--- a/pytest.ini
+++ b/pytest.ini
@@ -9,5 +9,3 @@ addopts =
# otherwise it won't discover doctests
# eh? importing too much
# --doctest-modules
- # show all test durations (unless they are too short)
- --durations=0
diff --git a/ruff.toml b/ruff.toml
deleted file mode 100644
index 3d803e7..0000000
--- a/ruff.toml
+++ /dev/null
@@ -1,151 +0,0 @@
-target-version = "py39" # 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
- "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
- # "I", # sort imports
- "ICN", # various import conventions
- "FBT", # detect use of boolean arguments
- "FURB", # various rules
- "PERF", # various potential performance speedups
- "PD", # pandas rules
- "PIE", # 'misc' lints
- "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
- "TRY", # various exception handling rules
- "UP", # detect deprecated python stdlib stuff
- "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
-
- # "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
- "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
- "E702", # Multiple statements on one line (semicolon)
- "E731", # assigning lambda instead of using def
- "E741", # Ambiguous variable name: `l`
- "E742", # Ambiguous class name: `O
- "E401", # Multiple imports on one line
- "F403", # import *` used; unable to detect undefined names
-###
-
-###
- "E722", # Do not use bare `except` ## Sometimes it's useful for defensive imports and that sort of thing..
- "F811", # Redefinition of unused # this gets in the way of pytest fixtures (e.g. in cachew)
-
-## might be nice .. but later and I don't wanna make it strict
- "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
- "F841", # Local variable `count` is assigned to but never used
-###
-
- "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
-
- "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
- "PIE790",
-
- # 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",
-
- "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
-
- "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 -- mostly just being annoying with long multiline strings
-
- "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
-
- "PGH", # TODO force error code in mypy instead
-
- "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
- "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
- "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
-]
diff --git a/scripts/ci/run b/scripts/ci/run
new file mode 100755
index 0000000..a7ea3ba
--- /dev/null
+++ b/scripts/ci/run
@@ -0,0 +1,25 @@
+#!/bin/bash -eu
+
+cd "$(dirname "$0")"
+cd ../..
+
+if ! command -v sudo; then
+ # CI or Docker sometimes doesn't have it, so useful to have a dummy
+ function sudo {
+ "$@"
+ }
+fi
+
+if ! [ -z "$CI" ]; then
+ # install OS specific stuff here
+ if [[ "$OSTYPE" == "darwin"* ]]; then
+ # macos
+ brew install fd
+ else
+ sudo apt update
+ sudo apt install fd-find
+ fi
+fi
+
+pip3 install --user tox
+tox
diff --git a/.ci/release b/scripts/release
similarity index 92%
rename from .ci/release
rename to scripts/release
index 6cff663..0ec687f 100755
--- a/.ci/release
+++ b/scripts/release
@@ -21,7 +21,7 @@ import shutil
is_ci = os.environ.get('CI') is not None
-def main() -> None:
+def main():
import argparse
p = argparse.ArgumentParser()
p.add_argument('--test', action='store_true', help='use test pypi')
@@ -29,7 +29,7 @@ def main() -> None:
extra = []
if args.test:
- extra.extend(['--repository', 'testpypi'])
+ extra.extend(['--repository-url', 'https://test.pypi.org/legacy/'])
root = Path(__file__).absolute().parent.parent
os.chdir(root) # just in case
@@ -42,7 +42,7 @@ def main() -> None:
if dist.exists():
shutil.rmtree(dist)
- check_call(['python3', '-m', 'build'])
+ check_call('python3 setup.py sdist bdist_wheel', shell=True)
TP = 'TWINE_PASSWORD'
password = os.environ.get(TP)
diff --git a/setup.py b/setup.py
index 385c810..1163008 100644
--- a/setup.py
+++ b/setup.py
@@ -4,17 +4,15 @@
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>=0.2.20240918' , # for transparent access to compressed files via pathlib.Path
+ 'pytz', # even though it's not needed by the core, it's so common anyway...
+ '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.0' , # for the CLI, printing colors, decorator-based - may allow extensions to CLI
]
-def main() -> None:
+def main():
pkg = 'my'
subpackages = find_namespace_packages('.', include=('my.*',))
setup(
@@ -44,39 +42,23 @@ def main() -> None:
author_email='karlicoss@gmail.com',
description='A Python interface to my life',
- python_requires='>=3.9',
+ python_requires='>=3.7',
install_requires=INSTALL_REQUIRES,
extras_require={
'testing': [
'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
-
- ##
- # 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?
+ 'logzero',
'orjson', # for my.core.serialize
- 'pyfzf_iter', # for my.core.denylist
- 'cachew>=0.15.20231019 ',
+ 'cachew>=0.8.0',
'mypy', # used for config checks
- 'colorlog', # for colored logs
- 'enlighten', # for CLI progress bars
],
},
entry_points={'console_scripts': ['hpi=my.core.__main__:main']},
diff --git a/my/tests/bluemaestro.py b/tests/bluemaestro.py
similarity index 64%
rename from my/tests/bluemaestro.py
rename to tests/bluemaestro.py
index d139a8f..1416900 100644
--- a/my/tests/bluemaestro.py
+++ b/tests/bluemaestro.py
@@ -1,22 +1,13 @@
-from collections.abc import Iterator
-
-import pytest
+#!/usr/bin/env python3
+from pathlib import Path
from more_itertools import one
-from my.bluemaestro import Measurement, measurements
-from my.core.cfg import tmp_config
-
-from .common import testdata
-
-
-def ok_measurements() -> Iterator[Measurement]:
- for m in measurements():
- assert not isinstance(m, Exception)
- yield m
+import pytest # type: ignore
def test() -> None:
- res2020 = [m for m in ok_measurements() if '2020' in str(m.dt)]
+ from my.bluemaestro import measurements
+ res2020 = [m for m in measurements() if '2020' in str(m.dt)]
tp = [x for x in res2020 if x.temp == 2.1]
assert len(tp) > 0
@@ -26,14 +17,15 @@ 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
+ # 2.5 K + 4 K datapoints, somwhat overlapping
assert len(res2020) < 6000
def test_old_db() -> None:
- res = list(ok_measurements())
+ from my.bluemaestro import measurements
+ res = list(measurements())
r1 = one(x for x in res if x.dt.strftime('%Y%m%d %H:%M:%S') == '20181003 09:07:00')
r2 = one(x for x in res if x.dt.strftime('%Y%m%d %H:%M:%S') == '20181003 09:19:00')
@@ -46,12 +38,14 @@ def test_old_db() -> None:
@pytest.fixture(autouse=True)
def prepare():
+ from .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/tests/calendar.py b/tests/calendar.py
new file mode 100644
index 0000000..f897efe
--- /dev/null
+++ b/tests/calendar.py
@@ -0,0 +1,19 @@
+from pathlib import Path
+
+import pytest # type: ignore
+
+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/cli.py b/tests/cli.py
new file mode 100644
index 0000000..1e3c560
--- /dev/null
+++ b/tests/cli.py
@@ -0,0 +1,4 @@
+from subprocess import check_call
+
+def test_lists_modules() -> None:
+ check_call(['hpi', 'modules'])
diff --git a/my/tests/commits.py b/tests/commits.py
similarity index 54%
rename from my/tests/commits.py
rename to tests/commits.py
index 48e349f..ab4e2c7 100644
--- a/my/tests/commits.py
+++ b/tests/commits.py
@@ -1,19 +1,12 @@
-import os
+# TODO need fdfind on CI?
from pathlib import Path
-import pytest
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',
- reason='TODO figure out how to install fd-find on Windows',
-)
+import pytest
def test() -> None:
+ from my.coding.commits import commits
all_commits = list(commits())
assert len(all_commits) > 100
@@ -29,14 +22,15 @@ def prepare(tmp_path: Path):
# - bare repos
# - canonical name
# - caching?
- hpi_repo_root = Path(__file__).absolute().parent.parent.parent
+ hpi_repo_root = Path(__file__).absolute().parent.parent
assert (hpi_repo_root / '.git').exists(), hpi_repo_root
- class config:
- class commits:
- emails = {'karlicoss@gmail.com'}
- names = {'Dima'}
- roots = [hpi_repo_root]
+ class commits:
+ emails = {'karlicoss@gmail.com'}
+ names = {'Dima'}
+ roots = [hpi_repo_root]
- with tmp_config(modules='my.coding.commits', config=config):
+ from my.core.cfg import tmp_config
+ with tmp_config() as config:
+ config.commits = commits
yield
diff --git a/tests/common.py b/tests/common.py
new file mode 100644
index 0000000..47c2991
--- /dev/null
+++ b/tests/common.py
@@ -0,0 +1,27 @@
+import os
+from pathlib import Path
+
+import pytest
+
+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.',
+)
+
+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..
+ '''
+ import sys
+ import re
+ to_unload = [m for m in sys.modules if re.match(r'my[.]?', m)]
+ for m in to_unload:
+ del sys.modules[m]
+
+
+def testdata() -> Path:
+ d = Path(__file__).absolute().parent.parent / 'testdata'
+ assert d.exists(), d
+ return d
diff --git a/tests/config.py b/tests/config.py
new file mode 100644
index 0000000..49138c3
--- /dev/null
+++ b/tests/config.py
@@ -0,0 +1,126 @@
+from pathlib import Path
+
+
+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 someting
+ 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 # type: ignore
+
+
+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
+
+
+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
+
+
+@pytest.fixture(autouse=True)
+def prepare():
+ from .common import reset_modules
+ reset_modules()
+ yield
diff --git a/tests/conftest.py b/tests/conftest.py
index 4e67f71..334cd19 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -1,4 +1,4 @@
-import pytest
+import pytest # type: ignore
# I guess makes sense by default
@pytest.fixture(autouse=True)
diff --git a/tests/core.py b/tests/core.py
new file mode 100644
index 0000000..72c16ef
--- /dev/null
+++ b/tests/core.py
@@ -0,0 +1,25 @@
+'''
+NOTE: Sigh. it's nice to be able to define the tests next to the source code (so it serves as documentation).
+However, if you run 'pytest --pyargs my.core', it detects 'core' package name (because there is no my/__init__.py)
+(see https://docs.pytest.org/en/latest/goodpractices.html#tests-as-part-of-application-code)
+
+This results in relative imports failing (e.g. from ..kython import...).
+
+By using this helper file, pytest can detect the package name properly. A bit meh, but perhaps after kython is moved into the core,
+we can run against the tests in my.core directly.
+
+'''
+
+from my.core.cfg import *
+from my.core.common import *
+from my.core.core_config import *
+from my.core.error import *
+from my.core.util import *
+from my.core.discovery_pure import *
+from my.core.freezer import *
+from my.core.stats import *
+from my.core.query import *
+from my.core.query_range import *
+from my.core.serialize import test_serialize_fallback
+from my.core.sqlite import *
+from my.core.__main__ import *
diff --git a/my/core/tests/structure_data/gdpr_export.zip b/tests/core/structure_data/gdpr_export.zip
similarity index 100%
rename from my/core/tests/structure_data/gdpr_export.zip
rename to tests/core/structure_data/gdpr_export.zip
diff --git a/doc/overlays/overlay2/src/my/py.typed b/tests/core/structure_data/gdpr_subdirs/broken_export/comments/comments.json
similarity index 100%
rename from doc/overlays/overlay2/src/my/py.typed
rename to tests/core/structure_data/gdpr_subdirs/broken_export/comments/comments.json
diff --git a/my/core/tests/structure_data/gdpr_subdirs/broken_export/messages/index.csv b/tests/core/structure_data/gdpr_subdirs/broken_export/messages/index.csv
similarity index 100%
rename from my/core/tests/structure_data/gdpr_subdirs/broken_export/messages/index.csv
rename to tests/core/structure_data/gdpr_subdirs/broken_export/messages/index.csv
diff --git a/doc/overlays/overlay3/src/my/py.typed b/tests/core/structure_data/gdpr_subdirs/gdpr_export/comments/comments.json
similarity index 100%
rename from doc/overlays/overlay3/src/my/py.typed
rename to tests/core/structure_data/gdpr_subdirs/gdpr_export/comments/comments.json
diff --git a/my/core/tests/structure_data/gdpr_subdirs/gdpr_export/messages/index.csv b/tests/core/structure_data/gdpr_subdirs/gdpr_export/messages/index.csv
similarity index 100%
rename from my/core/tests/structure_data/gdpr_subdirs/gdpr_export/messages/index.csv
rename to tests/core/structure_data/gdpr_subdirs/gdpr_export/messages/index.csv
diff --git a/tests/core/structure_data/gdpr_subdirs/gdpr_export/profile/settings.json b/tests/core/structure_data/gdpr_subdirs/gdpr_export/profile/settings.json
new file mode 100644
index 0000000..e69de29
diff --git a/tests/core/test_kompress.py b/tests/core/test_kompress.py
new file mode 100644
index 0000000..3561444
--- /dev/null
+++ b/tests/core/test_kompress.py
@@ -0,0 +1,108 @@
+import lzma
+from pathlib import Path
+import sys
+import zipfile
+
+from my.core.kompress import kopen, kexists, CPath
+
+import pytest # type: ignore
+
+
+structure_data: Path = Path(__file__).parent / "structure_data"
+
+
+def test_kopen(tmp_path: Path) -> None:
+ "Plaintext handled transparently"
+ assert kopen(tmp_path / 'file' ).read() == 'just plaintext'
+ assert kopen(tmp_path / 'file.xz').read() == 'compressed text'
+
+ "For zips behaviour is a bit different (not sure about all this, tbh...)"
+ assert kopen(tmp_path / 'file.zip', 'path/in/archive').read() == 'data in zip'
+
+
+# TODO here?
+def test_kexists(tmp_path: Path) -> None:
+ # TODO also test top level?
+ assert kexists(str(tmp_path / 'file.zip'), 'path/in/archive')
+ assert not kexists(str(tmp_path / 'file.zip'), 'path/notin/archive')
+
+ # TODO not sure about this?
+ assert not kexists(tmp_path / 'nosuchzip.zip', 'path/in/archive')
+
+
+def test_cpath(tmp_path: Path) -> None:
+ CPath(str(tmp_path / 'file' )).read_text() == 'just plaintext'
+ CPath( tmp_path / 'file.xz').read_text() == 'compressed text'
+ # TODO not sure about zip files??
+
+
+@pytest.fixture(autouse=True)
+def prepare(tmp_path: Path):
+ (tmp_path / 'file').write_text('just plaintext')
+ with (tmp_path / 'file.xz').open('wb') as f:
+ with lzma.open(f, 'w') as lzf:
+ lzf.write(b'compressed text')
+ with zipfile.ZipFile(tmp_path / 'file.zip', 'w') as zf:
+ zf.writestr('path/in/archive', 'data in zip')
+ try:
+ yield None
+ finally:
+ pass
+
+
+@pytest.mark.skipif(
+ sys.version_info[:2] < (3, 8),
+ reason=f"ZipFile.Path is only available since 3.8",
+)
+def test_zippath() -> None:
+ from my.core.kompress import ZipPath
+ target = structure_data / 'gdpr_export.zip'
+ assert target.exists(), target # precondition
+
+ zp = ZipPath(target)
+
+ # magic! convenient to make third party libraries agnostic of ZipPath
+ assert isinstance(zp, Path)
+ # TODO maybe change __str__/__repr__? since it's a bit misleading:
+ # Path('/code/hpi/tests/core/structure_data/gdpr_export.zip', 'gdpr_export/')
+
+ assert ZipPath(target) == ZipPath(target)
+ assert zp.absolute() == zp
+
+ assert zp.exists()
+ assert (zp / 'gdpr_export/comments').exists()
+ # check str constructor just in case
+ assert (ZipPath(str(target)) / 'gdpr_export/comments').exists()
+ assert not (ZipPath(str(target)) / 'whatever').exists()
+
+ matched = list(zp.rglob('*'))
+ assert len(matched) > 0
+ assert all(p.filename == str(target) for p in matched), matched
+
+ rpaths = [str(p.relative_to(zp)) for p in matched]
+ assert rpaths == [
+ 'gdpr_export',
+ 'gdpr_export/comments',
+ 'gdpr_export/comments/comments.json',
+ 'gdpr_export/profile',
+ 'gdpr_export/profile/settings.json',
+ 'gdpr_export/messages',
+ 'gdpr_export/messages/index.csv',
+ ], rpaths
+
+
+ # TODO hmm this doesn't work atm, wheras Path does
+ # not sure if it should be defensive or something...
+ # ZipPath('doesnotexist')
+ # same for this one
+ # assert ZipPath(Path('test'), 'whatever').absolute() == ZipPath(Path('test').absolute(), 'whatever')
+
+ assert (ZipPath(target) / 'gdpr_export/comments').exists()
+
+ jsons = [str(p.relative_to(zp / 'gdpr_export')) for p in zp.rglob('*.json')]
+ assert jsons == [
+ 'comments/comments.json',
+ 'profile/settings.json',
+ ]
+
+ assert list(zp.rglob('mes*')) == [ZipPath(target, 'gdpr_export/messages')]
diff --git a/tests/core/test_pandas.py b/tests/core/test_pandas.py
new file mode 100644
index 0000000..bedab26
--- /dev/null
+++ b/tests/core/test_pandas.py
@@ -0,0 +1 @@
+from my.core.pandas import *
diff --git a/my/core/tests/structure.py b/tests/core/test_structure.py
similarity index 65%
rename from my/core/tests/structure.py
rename to tests/core/test_structure.py
index 741e0ea..1ad46fe 100644
--- a/my/core/tests/structure.py
+++ b/tests/core/test_structure.py
@@ -1,8 +1,9 @@
-from pathlib import Path
-
import pytest
-from ..structure import match_structure
+from pathlib import Path
+
+from my.core.structure import match_structure
+
structure_data: Path = Path(__file__).parent / "structure_data"
@@ -14,9 +15,11 @@ def test_gdpr_structure_exists() -> None:
assert results == (structure_data / "gdpr_subdirs" / "gdpr_export",)
-@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:
+def test_gdpr_unzip() -> None:
+
+ with match_structure(
+ structure_data / "gdpr_export.zip", expected=gdpr_expected
+ ) as results:
assert len(results) == 1
extracted = results[0]
index_file = extracted / "messages" / "index.csv"
@@ -28,11 +31,15 @@ def test_gdpr_unpack(archive: str) -> None:
def test_match_partial() -> None:
# a partial match should match both the 'broken' and 'gdpr_export' directories
- with match_structure(structure_data / "gdpr_subdirs", expected=gdpr_expected, partial=True) as results:
+ with match_structure(
+ structure_data / "gdpr_subdirs", expected=gdpr_expected, partial=True
+ ) as results:
assert len(results) == 2
def test_not_directory() -> None:
- 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):
+ with pytest.raises(NotADirectoryError, match=r"Expected either a zipfile or a directory"):
+ with match_structure(
+ structure_data / "messages/index.csv", expected=gdpr_expected
+ ):
pass
diff --git a/tests/demo.py b/tests/demo.py
new file mode 100644
index 0000000..436bc63
--- /dev/null
+++ b/tests/demo.py
@@ -0,0 +1,118 @@
+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 behavious 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 # type: ignore
+
+@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]
diff --git a/tests/emfit.py b/tests/emfit.py
index b316017..8a779e4 100644
--- a/tests/emfit.py
+++ b/tests/emfit.py
@@ -1,4 +1,4 @@
-from my.tests.common import skip_if_not_karlicoss as pytestmark
+from .common import skip_if_not_karlicoss as pytestmark
def test() -> None:
@@ -13,6 +13,8 @@ def test() -> None:
assert d.sleep_end.tzinfo is not None
+from .common import skip_if_not_karlicoss
+@skip_if_not_karlicoss
def test_tz() -> None:
from my.emfit import datas
# TODO check errors too?
diff --git a/tests/extra/polar.py b/tests/extra/polar.py
index b5858b6..0fddcf3 100644
--- a/tests/extra/polar.py
+++ b/tests/extra/polar.py
@@ -7,7 +7,7 @@ ROOT = Path(__file__).parent.absolute()
OUTPUTS = ROOT / 'outputs'
-import pytest
+import pytest # type: ignore
def test_hpi(prepare: str) -> None:
@@ -15,11 +15,11 @@ def test_hpi(prepare: str) -> None:
assert len(list(get_entries())) > 1
def test_orger(prepare: str, tmp_path: Path) -> None:
- from my.core.utils.imports import import_from, import_file
+ from my.core.common import import_from, import_file
om = import_file(ROOT / 'orger/modules/polar.py')
# reload(om)
- pv = om.PolarView()
+ pv = om.PolarView() # type: ignore
# TODO hmm. worth making public?
OUTPUTS.mkdir(exist_ok=True)
out = OUTPUTS / (get_valid_filename(prepare) + '.org')
@@ -38,7 +38,7 @@ PARAMS = [
def prepare(request):
dotpolar = request.param
class user_config:
- if dotpolar != '': # default
+ if dotpolar != '': # defaul
polar_dir = Path(ROOT / dotpolar)
defensive = False
diff --git a/tests/foursquare.py b/tests/foursquare.py
index a75190f..a9169ff 100644
--- a/tests/foursquare.py
+++ b/tests/foursquare.py
@@ -1,4 +1,4 @@
-from my.tests.common import skip_if_not_karlicoss as pytestmark
+from .common import skip_if_not_karlicoss as pytestmark
def test_checkins() -> None:
from my.foursquare import get_checkins
diff --git a/my/core/tests/test_get_files.py b/tests/get_files.py
similarity index 55%
rename from my/core/tests/test_get_files.py
rename to tests/get_files.py
index 68be4d9..a81b34f 100644
--- a/my/core/tests/test_get_files.py
+++ b/tests/get_files.py
@@ -1,38 +1,32 @@
import os
-import shutil
-import tempfile
-import zipfile
from pathlib import Path
from typing import TYPE_CHECKING
-import pytest
+from my.core.compat import windows
+from my.core.common import get_files
-from ..common import get_files
-from ..kompress import CPath, ZipPath
+import pytest # type: ignore
-# hack to replace all /tmp with 'real' tmp dir
-# not ideal, but makes tests more concise
-# TODO get rid of this, it's super confusing..
+ # hack to replace all /tmp with 'real' tmp dir
+ # not ideal, but makes tests more concise
def _get_files(x, *args, **kwargs):
- from ..common import get_files as get_files_orig
-
+ import my.core.common as C
def repl(x):
if isinstance(x, str):
return x.replace('/tmp', TMP)
elif isinstance(x, Path):
- assert x.parts[:2] == (os.sep, 'tmp') # meh
+ assert x.parts[:2] == (os.sep, 'tmp') # meh
return Path(TMP) / Path(*x.parts[2:])
else:
# iterable?
return [repl(i) for i in x]
x = repl(x)
- res = get_files_orig(x, *args, **kwargs)
- return tuple(type(i)(str(i).replace(TMP, '/tmp')) for i in res) # hack back for asserts..
+ res = C.get_files(x, *args, **kwargs)
+ return tuple(Path(str(i).replace(TMP, '/tmp')) for i in res) # hack back for asserts..
-get_files_orig = get_files
if not TYPE_CHECKING:
get_files = _get_files
@@ -46,6 +40,7 @@ def test_single_file() -> None:
with pytest.raises(Exception):
get_files('/tmp/hpi_test/file.ext')
+
create('/tmp/hpi_test/file.ext')
'''
@@ -53,12 +48,16 @@ def test_single_file() -> None:
1. Return type is a tuple, it's friendlier for hashing/caching
2. It always return pathlib.Path instead of plain strings
'''
- assert get_files('/tmp/hpi_test/file.ext') == (Path('/tmp/hpi_test/file.ext'),)
+ 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 is_windows: # windows doesn't have bashrc.. ugh
- assert get_files('~/.bashrc') == (Path('~').expanduser() / '.bashrc',)
+ if not windows: # windows dowsn't have bashrc.. ugh
+ assert get_files('~/.bashrc') == (
+ Path('~').expanduser() / '.bashrc',
+ )
def test_multiple_files() -> None:
@@ -75,7 +74,6 @@ def test_multiple_files() -> None:
create('/tmp/hpi_test/dir3/')
create('/tmp/hpi_test/dir3/ttt')
- # fmt: off
assert get_files([
Path('/tmp/hpi_test/dir3'), # it takes in Path as well as str
'/tmp/hpi_test/dir1',
@@ -85,7 +83,6 @@ def test_multiple_files() -> None:
Path('/tmp/hpi_test/dir1/zzz'),
Path('/tmp/hpi_test/dir3/ttt'),
)
- # fmt: on
def test_explicit_glob() -> None:
@@ -93,20 +90,20 @@ def test_explicit_glob() -> None:
You can pass a glob to restrict the extensions
'''
- create('/tmp/hpi_test/file_3.gz')
- create('/tmp/hpi_test/file_2.gz')
+ create('/tmp/hpi_test/file_3.zip')
+ create('/tmp/hpi_test/file_2.zip')
create('/tmp/hpi_test/ignoreme')
- create('/tmp/hpi_test/file.gz')
+ create('/tmp/hpi_test/file.zip')
# todo walrus operator would be great here...
expected = (
- Path('/tmp/hpi_test/file_2.gz'),
- Path('/tmp/hpi_test/file_3.gz'),
+ Path('/tmp/hpi_test/file_2.zip'),
+ Path('/tmp/hpi_test/file_3.zip'),
)
- assert get_files('/tmp/hpi_test', 'file_*.gz') == expected
+ assert get_files('/tmp/hpi_test', 'file_*.zip') == expected
"named argument should work too"
- assert get_files('/tmp/hpi_test', glob='file_*.gz') == expected
+ assert get_files('/tmp/hpi_test', glob='file_*.zip') == expected
def test_implicit_glob() -> None:
@@ -118,14 +115,14 @@ def test_implicit_glob() -> None:
create('/tmp/hpi_test/123/')
create('/tmp/hpi_test/123/dummy')
- create('/tmp/hpi_test/123/file.gz')
+ create('/tmp/hpi_test/123/file.zip')
create('/tmp/hpi_test/456/')
create('/tmp/hpi_test/456/dummy')
- create('/tmp/hpi_test/456/file.gz')
+ create('/tmp/hpi_test/456/file.zip')
- assert get_files(['/tmp/hpi_test/*/*.gz']) == (
- Path('/tmp/hpi_test/123/file.gz'),
- Path('/tmp/hpi_test/456/file.gz'),
+ assert get_files(['/tmp/hpi_test/*/*.zip']) == (
+ Path('/tmp/hpi_test/123/file.zip'),
+ Path('/tmp/hpi_test/456/file.zip'),
)
@@ -133,59 +130,27 @@ def test_no_files() -> None:
'''
Test for empty matches. They work, but should result in warning
'''
- assert get_files('') == ()
+ assert get_files('') == ()
# todo test these for warnings?
- assert get_files([]) == ()
+ assert get_files([]) == ()
assert get_files('bad*glob') == ()
-def test_compressed(tmp_path: Path) -> None:
- file1 = tmp_path / 'file_1.zstd'
- file2 = tmp_path / 'file_2.zip'
- file3 = tmp_path / 'file_3.csv'
-
- file1.touch()
- with zipfile.ZipFile(file2, 'w') as zf:
- zf.writestr('path/in/archive', 'data in zip')
- file3.touch()
-
- results = get_files_orig(tmp_path)
- [res1, res2, res3] = results
- assert isinstance(res1, CPath)
- assert isinstance(res2, ZipPath) # NOTE this didn't work on vendorized kompress, but it's fine, was never used?
- assert not isinstance(res3, CPath)
-
- results = get_files_orig(
- [CPath(file1), ZipPath(file2), file3],
- # sorting a mixture of ZipPath/Path was broken in old kompress
- # it almost never happened though (usually it's only a bunch of ZipPath, so not a huge issue)
- sort=False,
- )
- [res1, res2, res3] = results
- assert isinstance(res1, CPath)
- assert isinstance(res2, ZipPath)
- assert not isinstance(res3, CPath)
-
-
# TODO not sure if should uniquify if the filenames end up same?
# TODO not sure about the symlinks? and hidden files?
+import tempfile
TMP = tempfile.gettempdir()
test_path = Path(TMP) / 'hpi_test'
-
-@pytest.fixture(autouse=True)
-def prepare():
+def setup():
teardown()
test_path.mkdir()
- try:
- yield
- finally:
- teardown()
-def teardown() -> None:
+def teardown():
+ import shutil
if test_path.is_dir():
shutil.rmtree(test_path)
diff --git a/tests/github.py b/tests/github.py
index ed89053..5fb5fb9 100644
--- a/tests/github.py
+++ b/tests/github.py
@@ -1,17 +1,15 @@
-from my.tests.common import skip_if_not_karlicoss as pytestmark
+from .common import skip_if_not_karlicoss as pytestmark
from more_itertools import ilen
# todo test against stats? not sure.. maybe both
def test_gdpr() -> None:
import my.github.gdpr as gdpr
-
assert ilen(gdpr.events()) > 100
def test() -> None:
- from my.github.all import get_events
-
+ from my.coding.github import get_events
events = get_events()
assert ilen(events) > 100
for e in events:
diff --git a/tests/goodreads.py b/tests/goodreads.py
index 79e638a..9acab5c 100644
--- a/tests/goodreads.py
+++ b/tests/goodreads.py
@@ -1,4 +1,4 @@
-from my.tests.common import skip_if_not_karlicoss as pytestmark
+from .common import skip_if_not_karlicoss as pytestmark
from more_itertools import ilen
diff --git a/tests/hypothesis.py b/tests/hypothesis.py
index 8ca76dc..f5ee99e 100644
--- a/tests/hypothesis.py
+++ b/tests/hypothesis.py
@@ -1,4 +1,4 @@
-from my.tests.common import skip_if_not_karlicoss as pytestmark
+from .common import skip_if_not_karlicoss as pytestmark
def test() -> None:
from my.hypothesis import pages, highlights
diff --git a/tests/instapaper.py b/tests/instapaper.py
index 862654d..153a716 100644
--- a/tests/instapaper.py
+++ b/tests/instapaper.py
@@ -1,5 +1,4 @@
-from my.tests.common import skip_if_not_karlicoss as pytestmark
-
+from .common import skip_if_not_karlicoss as pytestmark
def test_pages() -> None:
# TODO ugh. need lazy import to simplify testing?
diff --git a/tests/jawbone.py b/tests/jawbone.py
index 0a05e9c..c53459d 100644
--- a/tests/jawbone.py
+++ b/tests/jawbone.py
@@ -1,10 +1,10 @@
-from my.tests.common import skip_if_not_karlicoss as pytestmark
+from .common import skip_if_not_karlicoss as pytestmark
from datetime import date, time
# todo private test.. move away
def test_tz() -> None:
- from my.jawbone import sleeps_by_date # type: ignore[attr-defined]
+ from my.jawbone import sleeps_by_date
sleeps = sleeps_by_date()
for s in sleeps.values():
assert s.sleep_start.tzinfo is not None
diff --git a/tests/lastfm.py b/tests/lastfm.py
index b9e8887..43e8f41 100644
--- a/tests/lastfm.py
+++ b/tests/lastfm.py
@@ -1,4 +1,4 @@
-from my.tests.common import skip_if_not_karlicoss as pytestmark
+from .common import skip_if_not_karlicoss as pytestmark
# todo maybe belongs to common
from more_itertools import ilen
diff --git a/tests/location.py b/tests/location.py
new file mode 100644
index 0000000..298b7ba
--- /dev/null
+++ b/tests/location.py
@@ -0,0 +1,45 @@
+from pathlib import Path
+
+from more_itertools import one
+
+import pytest # type: ignore
+
+
+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 .common import reset_modules
+ reset_modules()
+
+ user_config = _prepare_google_config(tmp_path)
+
+ import my.core.cfg as C
+ with C.tmp_config() as config:
+ config.google = user_config # type: ignore
+ yield
+
+
+def _prepare_google_config(tmp_path: Path):
+ from .common import testdata
+ track = one(testdata().rglob('italy-slovenia-2017-07-29.json'))
+
+ # 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
diff --git a/tests/misc.py b/tests/misc.py
new file mode 100644
index 0000000..7e666d7
--- /dev/null
+++ b/tests/misc.py
@@ -0,0 +1,94 @@
+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/tests/orgmode.py b/tests/orgmode.py
index 9b5cc59..d213a5e 100644
--- a/tests/orgmode.py
+++ b/tests/orgmode.py
@@ -1,9 +1,10 @@
-from my.tests.common import skip_if_not_karlicoss as pytestmark
+from my import orgmode
+from my.core.orgmode import collect
+from .common import skip_if_not_karlicoss
+
+@skip_if_not_karlicoss
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/my/tests/pdfs.py b/tests/pdfs.py
similarity index 72%
rename from my/tests/pdfs.py
rename to tests/pdfs.py
index 3702424..d5134bf 100644
--- a/my/tests/pdfs.py
+++ b/tests/pdfs.py
@@ -1,15 +1,17 @@
-import inspect
from pathlib import Path
-import pytest
from more_itertools import ilen
-from my.core.cfg import tmp_config
-from my.pdfs import annotated_pdfs, annotations, get_annots
-from my.tests.common import testdata
+import pytest
+
+from .common import testdata
def test_module(with_config) -> None:
+ # TODO crap. if module is imported too early (on the top level, it makes it super hard to overrride 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
@@ -20,13 +22,11 @@ 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]
+ del pdfs.roots # meh. otherwise legacy config value 'wins'
pdfs.paths = (root,)
+ from my.pdfs import annotations
annots = list(annotations())
[annot] = annots
assert isinstance(annot, Exception)
@@ -34,6 +34,9 @@ def test_with_error(with_config, tmp_path: Path) -> None:
@pytest.fixture
def with_config():
+ from .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
@@ -43,9 +46,13 @@ def with_config():
testdata(),
]
- with tmp_config() as config:
- config.pdfs = user_config
- yield
+ import my.core.cfg as C
+ with C.tmp_config() as config:
+ config.pdfs = user_config # type: ignore
+ try:
+ yield
+ finally:
+ reset_modules()
EXPECTED_HIGHLIGHTS = {
@@ -60,9 +67,11 @@ 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 {a.highlight for a in annotations} == EXPECTED_HIGHLIGHTS
+ assert set([a.highlight for a in annotations]) == EXPECTED_HIGHLIGHTS
def test_annotated_pdfs_with_filelist() -> None:
@@ -70,9 +79,12 @@ 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 = []
diff --git a/tests/reddit.py b/tests/reddit.py
new file mode 100644
index 0000000..d18b18d
--- /dev/null
+++ b/tests/reddit.py
@@ -0,0 +1,82 @@
+from datetime import datetime
+import pytz
+
+
+def test_basic() -> None:
+ # todo maybe this should call stat or something instead?
+ # would ensure reasonable stat implementation as well and less duplication
+ # note: deliberately use old module (instead of my.reddit.all) to test bwd compatibility
+ from my.reddit import saved, events
+ assert len(list(events())) > 0
+ assert len(list(saved())) > 0
+
+
+def test_comments() -> None:
+ from my.reddit.all import comments
+ assert len(list(comments())) > 0
+
+
+def test_unfav() -> None:
+ from my.reddit import events, saved
+ ev = events()
+ url = 'https://reddit.com/r/QuantifiedSelf/comments/acxy1v/personal_dashboard/'
+ uev = [e for e in ev if e.url == url]
+ assert len(uev) == 2
+ ff = uev[0]
+ # TODO could recover these from takeout perhaps?
+ assert ff.text == 'favorited [initial]'
+ uf = uev[1]
+ assert uf.text == 'unfavorited'
+
+
+def test_saves() -> None:
+ from my.reddit.all import saved
+ saves = list(saved())
+ assert len(saves) > 0
+
+ # just check that they are unique (makedict will throw)
+ from my.core.common import make_dict
+ make_dict(saves, key=lambda s: s.sid)
+
+
+def test_disappearing() -> None:
+ from my.reddit.rexport import events
+ # eh. so for instance, 'metro line colors' is missing from reddit-20190402005024.json for no reason
+ # but I guess it was just a short glitch... so whatever
+ saves = events()
+ favs = [s.kind for s in saves if s.text == 'favorited']
+ [deal_with_it] = [f for f in favs if f.title == '"Deal with it!"']
+ assert deal_with_it.backup_dt == datetime(2019, 4, 1, 23, 10, 25, tzinfo=pytz.utc)
+
+
+def test_unfavorite() -> None:
+ from my.reddit.rexport import events
+ evs = events()
+ unfavs = [s for s in evs if s.text == 'unfavorited']
+ [xxx] = [u for u in unfavs if u.eid == 'unf-19ifop']
+ assert xxx.dt == datetime(2019, 1, 29, 10, 10, 20, tzinfo=pytz.utc)
+
+
+def test_preserves_extra_attr() -> None:
+ # doesn't strictly belong here (not specific to reddit)
+ # but my.reddit does a fair bit of dyunamic hacking, so perhaps a good place to check nothing is lost
+ from my.reddit import config
+ assert isinstance(getattr(config, 'please_keep_me'), str)
+
+
+import pytest # type: ignore
+@pytest.fixture(autouse=True, scope='module')
+def prepare():
+ from .common import testdata
+ data = testdata() / 'hpi-testdata' / 'reddit'
+ assert data.exists(), data
+
+ # note: deliberately using old config schema so we can test migrations
+ class test_config:
+ export_dir = data
+ please_keep_me = 'whatever'
+
+ from my.core.cfg import tmp_config
+ with tmp_config() as config:
+ config.reddit = test_config
+ yield
diff --git a/tests/rtm.py b/tests/rtm.py
index 621e471..93378b6 100644
--- a/tests/rtm.py
+++ b/tests/rtm.py
@@ -1,4 +1,4 @@
-from my.tests.common import skip_if_not_karlicoss as pytestmark
+from .common import skip_if_not_karlicoss as pytestmark
def test() -> None:
diff --git a/tests/serialize.py b/tests/serialize.py
new file mode 100644
index 0000000..d9ee9a3
--- /dev/null
+++ b/tests/serialize.py
@@ -0,0 +1 @@
+from my.core.serialize import *
diff --git a/tests/serialize_simplejson.py b/tests/serialize_simplejson.py
new file mode 100644
index 0000000..d421a15
--- /dev/null
+++ b/tests/serialize_simplejson.py
@@ -0,0 +1,23 @@
+'''
+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/tests/smscalls.py b/tests/smscalls.py
index ef78786..51150f0 100644
--- a/tests/smscalls.py
+++ b/tests/smscalls.py
@@ -1,10 +1,9 @@
-from my.tests.common import skip_if_not_karlicoss as pytestmark
+from .common import skip_if_not_karlicoss as pytestmark
# TODO maybe instead detect if it has any data at all
# if none, then skip the test, say that user doesn't have any data?
# TODO implement via stat?
def test() -> None:
- from my.smscalls import calls, messages, mms
+ from my.smscalls import calls, messages
assert len(list(calls())) > 10
assert len(list(messages())) > 10
- assert len(list(mms())) > 10
diff --git a/my/core/tests/sqlite.py b/tests/sqlite.py
similarity index 87%
rename from my/core/tests/sqlite.py
rename to tests/sqlite.py
index 1ad0748..1b423da 100644
--- a/my/core/tests/sqlite.py
+++ b/tests/sqlite.py
@@ -1,10 +1,10 @@
+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
+
+from my.core.sqlite import sqlite_connect_immutable, sqlite_copy_and_open
def test_sqlite_read_with_wal(tmp_path: Path) -> None:
@@ -27,14 +27,13 @@ def test_sqlite_read_with_wal(tmp_path: Path) -> None:
assert len(wals) == 1
## now run the tests in separate process to ensure there is no potential for reusing sqlite connections or something
- with ProcessPoolExecutor(1) as pool:
+ from concurrent.futures import ProcessPoolExecutor as Pool
+ with Pool(1) as pool:
# merely using it for ctx manager..
- # fmt: off
pool.submit(_test_do_copy , db).result()
pool.submit(_test_do_immutable , db).result()
pool.submit(_test_do_copy_and_open, db).result()
pool.submit(_test_open_asis , db).result()
- # fmt: on
def _test_do_copy(db: Path) -> None:
@@ -44,24 +43,20 @@ def _test_do_copy(db: Path) -> None:
shutil.copy(db, cdb)
with sqlite3.connect(str(cdb)) as conn_copy:
assert len(list(conn_copy.execute('SELECT * FROM testtable'))) == 5
- conn_copy.close()
def _test_do_immutable(db: Path) -> None:
# in readonly mode doesn't touch
with sqlite_connect_immutable(db) as conn_imm:
assert len(list(conn_imm.execute('SELECT * FROM testtable'))) == 5
- conn_imm.close()
def _test_do_copy_and_open(db: Path) -> None:
with sqlite_copy_and_open(db) as conn_mem:
assert len(list(conn_mem.execute('SELECT * FROM testtable'))) == 10
- conn_mem.close()
def _test_open_asis(db: Path) -> None:
# NOTE: this also works... but leaves some potential for DB corruption
with sqlite3.connect(str(db)) as conn_db_2:
assert len(list(conn_db_2.execute('SELECT * FROM testtable'))) == 10
- conn_db_2.close()
diff --git a/tests/takeout.py b/tests/takeout.py
index 47d405b..f45a51d 100644
--- a/tests/takeout.py
+++ b/tests/takeout.py
@@ -1,5 +1,5 @@
-from my.tests.common import skip_if_not_karlicoss as pytestmark
-from datetime import datetime, timezone
+#!/usr/bin/env python3
+from datetime import datetime
from itertools import islice
import pytz
@@ -13,12 +13,12 @@ from more_itertools import ilen
def test_location_perf() -> None:
# 2.80 s for 10 iterations and 10K points
# TODO try switching to jq and see how it goes? not sure..
- print(ilen(islice(LT.iter_locations(), 0, 10000))) # type: ignore
+ print(ilen(islice(LT.iter_locations(), 0, 10000)))
# in theory should support any HTML takeout file?
# although IIRC bookmarks and search-history.html weren't working
-import pytest
+import pytest # type: ignore
@pytest.mark.parametrize(
'path', [
'YouTube/history/watch-history.html',
@@ -43,7 +43,7 @@ def test_myactivity_search() -> None:
results = list(read_html(tpath, path))
res = (
- datetime(year=2018, month=12, day=17, hour=8, minute=16, second=18, tzinfo=timezone.utc),
+ datetime(year=2018, month=12, day=17, hour=8, minute=16, second=18, tzinfo=pytz.utc),
'https://en.wikipedia.org/wiki/Emmy_Noether&usg=AFQjCNGrSW-iDnVA2OTcLsG3I80H_a6y_Q',
'Emmy Noether - Wikipedia',
)
diff --git a/tests/tweets.py b/tests/tweets.py
index 3545296..fefc24e 100644
--- a/tests/tweets.py
+++ b/tests/tweets.py
@@ -1,11 +1,13 @@
-from my.tests.common import skip_if_not_karlicoss as pytestmark
+from .common import skip_if_not_karlicoss as pytestmark
# todo current test doesn't depend on data, in principle...
# should make lazy loading the default..
-from datetime import datetime, timezone
+from datetime import datetime
import json
+import pytz
+
def test_tweet() -> None:
from my.twitter.archive import Tweet
@@ -43,7 +45,7 @@ def test_tweet() -> None:
"""
t = Tweet(json.loads(raw), screen_name='whatever')
assert t.permalink is not None
- assert t.dt == datetime(year=2012, month=8, day=30, hour=7, minute=12, second=48, tzinfo=timezone.utc)
+ assert t.dt == datetime(year=2012, month=8, day=30, hour=7, minute=12, second=48, tzinfo=pytz.utc)
assert t.text == 'this is a test tweet'
assert t.tid == '2328934829084'
assert t.entities is not None
diff --git a/tests/tz.py b/tests/tz.py
new file mode 100644
index 0000000..cb8c513
--- /dev/null
+++ b/tests/tz.py
@@ -0,0 +1,108 @@
+from datetime import datetime, timedelta, date, timezone
+from pathlib import Path
+import sys
+
+import pytest # type: ignore
+import pytz # type: ignore
+
+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
+
+ tz = LTZ._get_tz(datetime.min)
+ assert tz is not None
+
+
+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')
+
+
+# TODO copy pasted from location.py, need to extract some common provider
+@pytest.fixture(autouse=True)
+def prepare(tmp_path: Path):
+ from .common import reset_modules
+ reset_modules()
+
+ LTZ._FASTER = True
+
+ from .location import _prepare_google_config
+ google = _prepare_google_config(tmp_path)
+
+ class location:
+ home = (
+ # supports ISO strings
+ ('2005-12-04' , (42.697842, 23.325973)), # Bulgaria, Sofia
+ # supports date/datetime objects
+ (date(year=1980, month=2, day=15) , (40.7128 , -74.0060 )), # NY
+ # check tz handling..
+ (datetime.fromtimestamp(1600000000, tz=timezone.utc), (55.7558 , 37.6173 )), # Moscow, Russia
+ )
+ # note: order doesn't matter, will be sorted in the data provider
+
+ class time:
+ class tz:
+ pass # just rely on the default..
+
+ import my.core.cfg as C
+ with C.tmp_config() as config:
+ config.google = google
+ config.time = time
+ config.location = location
+ yield
diff --git a/tests/youtube.py b/tests/youtube.py
index f37493b..d514061 100644
--- a/tests/youtube.py
+++ b/tests/youtube.py
@@ -1,36 +1,22 @@
-from my.tests.common import skip_if_not_karlicoss as pytestmark
-
# TODO move elsewhere?
# these tests would only make sense with some existing data? although some of them would work for everyone..
# not sure what's a good way of handling this..
-from datetime import datetime
-import pytz
-from more_itertools import bucket
-
+from .common import skip_if_not_karlicoss as pytestmark
# TODO ugh. if i uncomment this here (on top level), then this test vvv fails
# from my.media.youtube import get_watched, Watched
# HPI_TESTS_KARLICOSS=true pytest -raps tests/tz.py tests/youtube.py
-
def test() -> None:
- from my.youtube.takeout import watched, Watched
- videos = [w for w in watched() if not isinstance(w, Exception)]
- assert len(videos) > 1000
+ from my.media.youtube import get_watched, Watched
+ watched = list(get_watched())
+ assert len(watched) > 1000
- # results in nicer errors, otherwise annoying to check against thousands of videos
- grouped = bucket(videos, key=lambda w: (w.url, w.title))
-
- w1 = Watched(
+ from datetime import datetime
+ import pytz
+ w = Watched(
url='https://www.youtube.com/watch?v=hTGJfRPLe08',
title='Jamie xx - Gosh',
- when=pytz.timezone('Europe/London').localize(datetime(year=2018, month=6, day=21, hour=6, minute=48, second=34)),
+ when=datetime(year=2018, month=6, day=21, hour=5, minute=48, second=34, tzinfo=pytz.utc),
)
- assert w1 in list(grouped[(w1.url, w1.title)])
-
- w2 = Watched(
- url='https://www.youtube.com/watch?v=IZ_8b_Ydsv0',
- title='Why LESS Sensitive Tests Might Be Better',
- when=pytz.utc.localize(datetime(year=2021, month=1, day=15, hour=17, minute=54, second=12)),
- )
- assert w2 in list(grouped[(w2.url, w2.title)])
+ assert w in watched
diff --git a/tox.ini b/tox.ini
index d202bd2..b8c89db 100644
--- a/tox.ini
+++ b/tox.ini
@@ -1,160 +1,133 @@
[tox]
-minversion = 3.21
-# relies on the correct version of Python installed
-envlist = ruff,tests-core,tests-all,demo,mypy-core,mypy-misc
-# https://github.com/tox-dev/tox/issues/20#issuecomment-247788333
-# hack to prevent .tox from crapping to the project directory
-toxworkdir = {env:TOXWORKDIR_BASE:}{toxinidir}/.tox
+minversion = 3.5
[testenv]
-# TODO how to get package name from setuptools?
-package_name = "my"
-passenv =
-# useful for tests to know they are running under ci
- CI
- CI_*
-# respect user's cache dirs to prevent tox from crapping into project dir
- 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
-# otherwise it seems that it tries to modify .eggs dir in parallel and it fails
-
-
-[testenv:ruff]
-deps =
- -e .[testing]
-commands =
- {envpython} -m ruff check my/
+passenv = CI CI_*
# just the very core tests with minimal dependencies
[testenv:tests-core]
-deps =
- -e .[testing]
commands =
- {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 {[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?
- --ignore my/core/orgmode.py \
- {posargs}
+ pip install -e .[testing]
+ python3 -m pytest \
+ tests/core.py \
+ tests/sqlite.py \
+ tests/get_files.py \
+ {posargs}
# todo maybe also have core tests and misc tests? since ideally want them without dependencies
[testenv:tests-all]
-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
-deps =
- -e .[testing]
- uv # for hpi module install
- cachew
- ijson # optional dependency for various modules
+# deliberately set to nonexistent path to check the fallback logic
+# TODO not sure if need it?
+setenv = MY_CONFIG = nonexistent
commands =
- {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
+ pip install -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.*
- --import-mode=importlib \
- --pyargs {[testenv]package_name}.core {[testenv]package_name}.tests \
- {posargs}
+ # installed to test my.core.serialize while using simplejson and not orjson
+ pip install simplejson
+ python3 -m pytest \
+ tests/serialize_simplejson.py \
+ {posargs}
+
+ pip install cachew
+ pip install orjson
+
+ hpi module install my.location.google
+ pip install ijson # optional dependency
+
+ hpi module install my.time.tz.via_location
+
+ hpi module install my.calendar.holidays
+
+ # my.body.weight dep
+ hpi module install my.orgmode
+
+ hpi module install my.coding.commits
+
+ hpi module install my.pdfs
+
+ hpi module install my.reddit.rexport
+
+ python3 -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
+ {posargs}
[testenv:demo]
-deps =
- git+https://github.com/karlicoss/hypexport
commands =
- {envpython} ./demo.py
+ pip install git+https://github.com/karlicoss/hypexport
+ ./demo.py
[testenv:mypy-core]
-deps =
- -e .[testing,optional]
- orgparse # for core.orgmode
- gpxpy # for hpi query --output gpx
+whitelist_externals = cat
commands =
- {envpython} -m mypy --no-install-types \
- -p {[testenv]package_name}.core \
- --txt-report .coverage.mypy-core \
- --html-report .coverage.mypy-core \
- {posargs}
+ pip install -e .[testing,optional]
+ pip install orgparse # used it core.orgmode?
+ # todo add tests?
+ python3 -m mypy --install-types --non-interactive \
+ -p my.core \
+ --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]
-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
commands =
- {envpython} -m my.core module install \
- my.arbtt \
- my.browser.export \
- my.coding.commits \
- my.emfit \
- my.endomondo \
- my.fbmessenger.export \
- my.github.ghexport \
- my.goodreads \
- my.google.maps.android \
- my.google.takeout.parser \
- my.hackernews.harmonic \
- my.hypothesis \
- my.instapaper \
- my.ip.all \
- my.kobo \
- my.location.gpslogger \
- my.monzo.monzoexport \
- my.orgmode \
- my.pdfs \
- my.pinboard \
- my.pocket \
- my.reddit.pushshift \
- my.reddit.rexport \
- my.rescuetime \
- my.runnerup \
- my.smscalls \
- my.stackexchange.stexport \
- my.time.tz.via_location
+ pip install -e .[testing,optional]
+ hpi module install my.browser.export
+ hpi module install my.orgmode
+ hpi module install my.endomondo
+ hpi module install my.github.ghexport
+ hpi module install my.hypothesis
+ hpi module install my.instapaper
+ hpi module install my.pocket
+ hpi module install my.reddit.rexport
+ hpi module install my.reddit.pushshift
+ hpi module install my.stackexchange.stexport
+ hpi module install my.pinboard
+ hpi module install my.arbtt
+ hpi module install my.coding.commits
+ hpi module install my.goodreads
+ hpi module install my.pdfs
+ hpi module install my.smscalls
- {envpython} -m mypy --no-install-types \
- -p {[testenv]package_name} \
- --txt-report .coverage.mypy-misc \
- --html-report .coverage.mypy-misc \
- {posargs}
-
- {envpython} -m mypy --no-install-types \
- tests
+ # todo fuck. -p my.github isn't checking the subpackages?? wtf...
+ # guess it wants .pyi file??
+ python3 -m mypy --install-types --non-interactive \
+ -p my.browser \
+ -p my.endomondo \
+ -p my.github.ghexport \
+ -p my.hypothesis \
+ -p my.instapaper \
+ -p my.pocket \
+ -p my.smscalls \
+ -p my.reddit \
+ -p my.stackexchange.stexport \
+ -p my.pinboard \
+ -p my.body.exercise.cardio \
+ -p my.body.exercise.cross_trainer \
+ -p my.bluemaestro \
+ -p my.location.google \
+ -p my.time.tz.via_location \
+ -p my.calendar.holidays \
+ -p my.arbtt \
+ -p my.coding.commits \
+ -p my.goodreads \
+ -p my.pdfs \
+ --txt-report .coverage.mypy-misc \
+ --html-report .coverage.mypy-misc \
+ {posargs}
+ # txt report is a bit more convenient to view on CI
# note: this comment doesn't seem relevant anymore, but keeping it in case the issue happens again
# > ugh ... need to reset HOME, otherwise user's site-packages are somehow leaking into mypy's path...