diff --git a/README.md b/README.md index b6fd8cd..27d1484 100644 --- a/README.md +++ b/README.md @@ -43,6 +43,7 @@ mygarmin update D:\myGarmin # all of the above + build + export | AlpineQuest | Copy the `.trk` files from the phone (AlpineQuest folder, `Landmarks`/`Tracks`). | | Garmin watch | Connect by USB and run `mygarmin watch`, or copy the watch's `GARMIN` folder and import it. | | Races | Optional `races.csv` in the library: `date,event,time[,km,age_grade,position,pb]` (km defaults to 5). | +| Blood tests | A spreadsheet (.xlsx or .csv) with a `Date` column and columns such as `Ferritin [ug/L] (30-400)`, `Hb`; optional `Min`/`Max` target columns. Import it once; it is read again at every update. | ## How it works The full picture (data flows, database, de-duplication, dashboard, exports) is in [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md). In short: diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 81a736a..d7583d5 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -57,11 +57,11 @@ One folder per person, chosen by the user: | Path | Contents | |---|---| -| `settings.json` | name, birth year, sex, home time zone, optional `copy_dashboard_to` paths | +| `settings.json` | name, birth year, sex, home time zone, optional `copy_dashboard_to` paths and `lab_files` (blood test spreadsheets) | | `myGarmin.db` | the SQLite database (below) | | `originals/garmin_fit/` | activity FIT files, named by local start time (`2024-05-01-07-30-00.fit`) | | `originals/garmin_health/`, `garmin_courses/` | health FITs (monitoring, sleep, HRV…) and courses, kept for later use | -| `originals/tcx/`, `alpinequest/`, `gpx/`, `strava/` | the other sources, under their original names | +| `originals/tcx/`, `alpinequest/`, `gpx/`, `strava/`, `labs/` | the other sources, under their original names | | `races.csv` | optional, typed by the user: `date,event,time[,km,age_grade,position,pb]` | | `dashboard.html`, `all_activities.csv` | built outputs | | `exports/tracks_gpx.zip`, `exports/tracks_trk.zip` | built outputs, one track per outing, in year folders | @@ -137,7 +137,8 @@ erDiagram training load and status, race predictions, endurance and hill score). New values are merged in, so a later source can complete or correct a day. - **health_series:** values that are not daily: `vo2` (per sport), `fage` (fitness age), `bp` (blood pressure, with any - haemoglobin value found in the note), `lthr` (lactate-threshold heart rate). + haemoglobin value found in the note), `lthr` (lactate-threshold heart rate), `lab` (blood test results: ferritin, + haemoglobin, serum iron, transferrin saturation, each with its lab, reference range and the user's target range). ## Getting data in @@ -213,6 +214,14 @@ Uses the unofficial `python-garminconnect` library (read-only). Garmin has no pe - **Health:** every day from the last stored day minus 3 days up to today. The last days are re-fetched because Garmin completes them later. The fields are the same as from the export, so both sources fill the same records. - **Pacing:** calls are spaced 0.3 s apart. A failing call is logged and skipped. +### Blood test spreadsheets (`sources/labs.py`) +For results the user keeps in Excel (.xlsx) or a .csv, e.g. ferritin during treatment for iron overload. +- **Layout:** a header row with a `Date` column. Other columns are recognised by their header: ferritin (or a µg/L or ng/mL unit), haemoglobin/Hb, serum iron, transferrin saturation. A range in brackets, such as `(30-400)`, is the lab's reference range; what is left of the header is the lab's name. Columns headed `Min` and `Max` are the user's own target range. +- **Only typed-in numbers count.** Cells with a formula (estimates, differences) are skipped, so a sheet can keep its own calculations. +- **Two lab methods** in two columns stay separate series: the dashboard draws the one with most results as a line and the other as points. +- **Kept in sync:** importing a sheet from disk adds its path to `lab_files` in the settings. Every dashboard build reads those sheets again and replaces their earlier results, so edits and deleted rows show. A sheet that is missing (moved, drive offline) keeps its last results; change the path in the app's settings. +- A sheet found inside a folder or zip is imported once and kept under `originals/labs/`. + ## Time zones (`timeutil.py`) Every activity keeps its UTC start and the offset to local time. The offset comes from: 1. the file itself (FIT `local_timestamp`, rounded to 15 min); else @@ -251,6 +260,8 @@ flowchart LR 5. `all_activities.csv` lists **every** row, including duplicates and flagged ones, with the reason, for checking in Excel. 6. The dashboard is also copied to any `copy_dashboard_to` paths in the settings. +Before step 1, the blood test sheets in `lab_files` are read again. + ## Exports (`export.py`) - **Which tracks:** the same as on the dashboard, but only with GPS. One file per outing, so duplicate recordings never appear twice. - **Full resolution:** points are re-read from each original file (FIT, TCX, GPX, AlpineQuest or Strava). diff --git a/packaging/myGarmin.spec b/packaging/myGarmin.spec index 0a495cd..ebdec93 100644 --- a/packaging/myGarmin.spec +++ b/packaging/myGarmin.spec @@ -8,7 +8,7 @@ for pkg in ('webview', 'clr_loader', 'pythonnet', 'garminconnect', 'curl_cffi', d, b, h = collect_all(pkg); datas += d; binaries += b; hidden += h a = Analysis(['launcher.py'], pathex=['../src'], binaries=binaries, datas=datas, - hiddenimports=hidden + ['mygarmin.sources.garmin_api', 'mygarmin.sources.watch', 'mygarmin.cli', 'mygarmin.export', 'mygarmin.report', 'mygarmin.dedupe', 'clr'], + hiddenimports=hidden + ['mygarmin.sources.garmin_api', 'mygarmin.sources.watch', 'mygarmin.cli', 'mygarmin.export', 'mygarmin.report', 'mygarmin.dedupe', 'mygarmin.sources.labs', 'openpyxl', 'clr'], excludes=['tkinter', 'matplotlib', 'pandas', 'PIL', 'pytest'], noarchive=False) pyz = PYZ(a.pure) exe = EXE(pyz, a.scripts, [], exclude_binaries=True, name='myGarmin', icon='myGarmin.ico', diff --git a/pyproject.toml b/pyproject.toml index 59884aa..e4c5d74 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -9,7 +9,7 @@ description = "Local-first activity and health logbook for Garmin, Strava and Al readme = "README.md" requires-python = ">=3.12" license = "MIT" -dependencies = ["fitparse>=1.2", "timezonefinder>=6"] +dependencies = ["fitparse>=1.2", "timezonefinder>=6", "openpyxl>=3.1"] [project.optional-dependencies] api = ["garminconnect>=0.3.19", "curl_cffi"] diff --git a/src/mygarmin/app/__init__.py b/src/mygarmin/app/__init__.py index 24419c0..06b6ba2 100644 --- a/src/mygarmin/app/__init__.py +++ b/src/mygarmin/app/__init__.py @@ -83,7 +83,7 @@ class Api: def pick_files(self): import webview r = self._window.create_file_dialog(webview.FileDialog.OPEN, allow_multiple=True, - file_types=('Activity and export files (*.zip;*.fit;*.tcx;*.gpx;*.trk;*.gz)', 'All files (*.*)')) + file_types=('Activity, export and blood test files (*.zip;*.fit;*.tcx;*.gpx;*.trk;*.gz;*.xlsx;*.csv)', 'All files (*.*)')) return list(r) if r else [] def _use(self, lib): @@ -105,11 +105,12 @@ class Api: def close_library(self): self._lib = None; _save_app_state(library=None); return self.state() - def save_settings(self, name, birth_year, sex, tz, copies): + def save_settings(self, name, birth_year, sex, tz, copies, lab_files=None): ZoneInfo(tz) lib = Library.create(self._lib.root, name=name or None, birth_year=int(birth_year) if birth_year else None, sex=sex or None, home_tz=tz) p = lib.path('settings.json'); s = json.load(open(p, encoding='utf-8')) s['copy_dashboard_to'] = [c.strip() for c in (copies or '').splitlines() if c.strip()] + if lab_files is not None: s['lab_files'] = [c.strip().strip('"') for c in lab_files.splitlines() if c.strip()] json.dump(s, open(p, 'w', encoding='utf-8'), indent=1) return self._use(Library(lib.root)) diff --git a/src/mygarmin/app/ui.html b/src/mygarmin/app/ui.html index c6bcc91..58b8aac 100644 --- a/src/mygarmin/app/ui.html +++ b/src/mygarmin/app/ui.html @@ -128,7 +128,7 @@ details[open] > summary { margin-bottom: 10px }

Add data

Drop files or folders here - Garmin or Strava export zips, a copied watch GARMIN folder, or .fit .tcx .gpx .trk files + Garmin or Strava export zips, a copied watch GARMIN folder, or .fit .tcx .gpx .trk files, or a blood test spreadsheet (.xlsx)
@@ -182,6 +182,7 @@ details[open] > summary { margin-bottom: 10px } +
Rebuild the dashboard afterwards to apply.
@@ -232,7 +233,7 @@ const ui = { $('openDash').disabled = !L.dashboard; const s = L.settings; if (!$('settingsBox').open) { $('sName').value = s.name || ''; $('sBirth').value = s.birth_year || ''; $('sSex').value = s.sex || ''; $('sTz').value = s.home_tz || 'UTC'; - $('sCopies').value = (s.copy_dashboard_to || []).join('\n') } + $('sCopies').value = (s.copy_dashboard_to || []).join('\n'); $('sLabs').value = (s.lab_files || []).join('\n') } }, busy(name) { $('busy').textContent = name ? `Working: ${name}…` : ''; $('busy').classList.toggle('hidden', !name); @@ -253,7 +254,7 @@ const ui = { }, async open() { ui.render(await ui.call('open_library', $('openPath').value.trim())) }, async saveSettings() { - const st = await ui.call('save_settings', $('sName').value.trim(), $('sBirth').value, $('sSex').value, $('sTz').value.trim() || 'UTC', $('sCopies').value); + const st = await ui.call('save_settings', $('sName').value.trim(), $('sBirth').value, $('sSex').value, $('sTz').value.trim() || 'UTC', $('sCopies').value, $('sLabs').value); $('settingsBox').open = false; ui.render(st); ui.log('Settings saved.'); }, async login() { diff --git a/src/mygarmin/report/__init__.py b/src/mygarmin/report/__init__.py index 1f5b1c4..2e98a98 100644 --- a/src/mygarmin/report/__init__.py +++ b/src/mygarmin/report/__init__.py @@ -32,13 +32,16 @@ def data(lib): t = lib.db.execute('SELECT pts FROM tracks WHERE activity_id=?', (a['id'],)).fetchone() if t: tracks[a['file']] = json.loads(t[0]) days = lib.days() - health = {'days': days, 'vo2': lib.series('vo2'), 'fage': lib.series('fage'), 'bp': lib.series('bp'), 'lthr': lib.series('lthr')} if days else None + health = {'days': days, 'vo2': lib.series('vo2'), 'fage': lib.series('fage'), 'bp': lib.series('bp'), 'lthr': lib.series('lthr'), + 'labs': [{k: v for k, v in r.items() if k != 'src'} for r in lib.series('lab')]} if days else None s = lib.settings return {'profile': {'name': s.get('name'), 'birth_year': s.get('birth_year'), 'sex': s.get('sex')}, 'acts': acts, 'tracks': tracks, 'health': health, 'races': races(lib), 'built': datetime.now().strftime('%Y-%m-%d %H:%M'), 'version': __version__} def build(lib, out=None, log=print): + from ..sources import labs + labs.refresh(lib, log) # blood test spreadsheets named in settings.json "lab_files" d = data(lib) if not d['acts']: raise SystemExit('No activities in the library yet: import some first.') tpl = open(os.path.join(os.path.dirname(__file__), 'dashboard.html'), encoding='utf-8').read() diff --git a/src/mygarmin/report/dashboard.html b/src/mygarmin/report/dashboard.html index 3010fc3..2917192 100644 --- a/src/mygarmin/report/dashboard.html +++ b/src/mygarmin/report/dashboard.html @@ -133,11 +133,15 @@ h3.sub { margin: 8px 0 0; font: 600 16px var(--body) }

Training load: last 7 days against your usual (acute vs chronic)