Compare commits
6 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c7a0c8f4b9 | ||
|
|
e41249e8b5 | ||
|
|
03dabb2a3a | ||
|
|
b5521d6731 | ||
|
|
0d3da5f2df | ||
| c6a1eb199d |
@@ -43,8 +43,10 @@ mygarmin update D:\myGarmin # all of the above + build + export
|
|||||||
| AlpineQuest | Copy the `.trk` files from the phone (AlpineQuest folder, `Landmarks`/`Tracks`). |
|
| 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. |
|
| 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). |
|
| 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
|
## How it works
|
||||||
|
The full picture (data flows, database, de-duplication, dashboard, exports) is in [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md). In short:
|
||||||
- Originals are copied unchanged into `<library>/originals/`; the SQLite database `myGarmin.db` and everything else can
|
- Originals are copied unchanged into `<library>/originals/`; the SQLite database `myGarmin.db` and everything else can
|
||||||
be rebuilt from them. Importing the same file twice does nothing.
|
be rebuilt from them. Importing the same file twice does nothing.
|
||||||
- One outing recorded by several sources (watch, phone, Strava) is kept once, preferring the watch.
|
- One outing recorded by several sources (watch, phone, Strava) is kept once, preferring the watch.
|
||||||
|
|||||||
283
docs/ARCHITECTURE.md
Normal file
283
docs/ARCHITECTURE.md
Normal file
@@ -0,0 +1,283 @@
|
|||||||
|
# How myGarmin works
|
||||||
|
|
||||||
|
This document explains how data gets in, what is stored where, and how the dashboard and the exports are made.
|
||||||
|
Module names refer to `src/mygarmin/`.
|
||||||
|
|
||||||
|
## The big picture
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
flowchart LR
|
||||||
|
subgraph IN[Data sources]
|
||||||
|
W[Garmin watch<br/>USB / MTP]
|
||||||
|
GE[Garmin Connect<br/>export zip]
|
||||||
|
API[Garmin Connect API<br/>unofficial]
|
||||||
|
SE[Strava<br/>export zip]
|
||||||
|
AQ[AlpineQuest<br/>.trk files]
|
||||||
|
F[Loose files<br/>.fit .tcx .gpx]
|
||||||
|
end
|
||||||
|
subgraph LIB[Library folder]
|
||||||
|
O[(originals/<br/>untouched files)]
|
||||||
|
DB[(myGarmin.db<br/>SQLite)]
|
||||||
|
end
|
||||||
|
subgraph OUT[Outputs]
|
||||||
|
D[dashboard.html]
|
||||||
|
C[all_activities.csv]
|
||||||
|
X[exports/<br/>tracks_gpx.zip<br/>tracks_trk.zip]
|
||||||
|
end
|
||||||
|
W -->|watch.pull| IMP
|
||||||
|
GE --> IMP
|
||||||
|
SE --> IMP
|
||||||
|
AQ --> IMP
|
||||||
|
F --> IMP
|
||||||
|
API -->|garmin_api.sync| IMP
|
||||||
|
IMP[Importers<br/>sources/] --> O
|
||||||
|
IMP --> DB
|
||||||
|
DB --> DD[dedupe.run]
|
||||||
|
DD --> DB
|
||||||
|
DB --> R[report.build] --> D & C
|
||||||
|
DB --> E[export.run]
|
||||||
|
O --> E --> X
|
||||||
|
```
|
||||||
|
|
||||||
|
The pipeline always runs in the same order: **import → de-duplicate → build → export**. The command line (`cli.py`) and the
|
||||||
|
app window (`app/`) are two front ends to the same functions; `mygarmin update` and the app's *Update everything* run the
|
||||||
|
whole chain.
|
||||||
|
|
||||||
|
Three principles shape everything:
|
||||||
|
1. **Originals are kept unchanged.** Every imported file is copied once into `originals/<source>/`. The database, the
|
||||||
|
dashboard and the exports can always be rebuilt from them.
|
||||||
|
2. **Importing is idempotent.** Files are recognised by content (MD5). Importing the same zip or folder again changes
|
||||||
|
nothing, so users can simply re-import everything they have.
|
||||||
|
3. **Nothing is thrown away.** Duplicates, car trips and broken recordings are *marked*, not deleted, and a later rule
|
||||||
|
change can bring them back.
|
||||||
|
|
||||||
|
## The library folder
|
||||||
|
|
||||||
|
One folder per person, chosen by the user:
|
||||||
|
|
||||||
|
| Path | Contents |
|
||||||
|
|---|---|
|
||||||
|
| `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/`, `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 |
|
||||||
|
|
||||||
|
Things that belong to the PC, not the library, live in `%LOCALAPPDATA%\myGarmin\`:
|
||||||
|
- `app.json`: last and recent libraries;
|
||||||
|
- `tokens\<hash>\`: the Garmin Connect login, one per library. It is kept off the library because a library may sit on a shared drive;
|
||||||
|
- `webview\`: the app window's browser data;
|
||||||
|
- `app.log`, `cli.log`: error and command logs.
|
||||||
|
|
||||||
|
## The database
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
erDiagram
|
||||||
|
files {
|
||||||
|
text md5 PK
|
||||||
|
text path
|
||||||
|
text source
|
||||||
|
text kind
|
||||||
|
text imported
|
||||||
|
}
|
||||||
|
activities {
|
||||||
|
int id PK
|
||||||
|
text source
|
||||||
|
text file UK
|
||||||
|
text start_utc
|
||||||
|
int utc_offset_min
|
||||||
|
text start_local
|
||||||
|
real elapsed_s
|
||||||
|
real moving_s
|
||||||
|
text sport
|
||||||
|
text sub_sport
|
||||||
|
text name
|
||||||
|
real dist_m
|
||||||
|
real ascent_m
|
||||||
|
int avg_hr
|
||||||
|
int max_hr
|
||||||
|
int kcal
|
||||||
|
real te_aerobic
|
||||||
|
real vo2max
|
||||||
|
int npts
|
||||||
|
real lat
|
||||||
|
real lon
|
||||||
|
text flag
|
||||||
|
int dup_of
|
||||||
|
}
|
||||||
|
tracks {
|
||||||
|
int activity_id PK
|
||||||
|
text pts
|
||||||
|
}
|
||||||
|
health_days {
|
||||||
|
text date PK
|
||||||
|
text data
|
||||||
|
}
|
||||||
|
health_series {
|
||||||
|
text kind PK
|
||||||
|
text date PK
|
||||||
|
text key PK
|
||||||
|
text data
|
||||||
|
}
|
||||||
|
activities ||--o| tracks : "simplified map line"
|
||||||
|
activities ||--o| activities : "dup_of"
|
||||||
|
```
|
||||||
|
|
||||||
|
- **files:** every original ever stored, by MD5. This is what makes imports idempotent.
|
||||||
|
- **activities:** one row per recording from any source, with a summary in common units (metres, seconds) and
|
||||||
|
UTC plus local start time.
|
||||||
|
- `flag` says why a row is left out of the dashboard: `transport`, `too short` and `no time` are hidden; `suspect GPS`
|
||||||
|
is shown but kept out of pace figures; `summary only` is shown.
|
||||||
|
- `dup_of` points at the recording of the same outing that is kept.
|
||||||
|
- **tracks:** about 400 points per activity, enough for the map. Full-resolution tracks are always re-read from the originals.
|
||||||
|
- **health_days:** one JSON record per calendar day (sleep, resting HR, HRV, stress, Body Battery, steps, readiness,
|
||||||
|
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), `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
|
||||||
|
|
||||||
|
### One entry point: `sources.import_path`
|
||||||
|
Anything can be imported: a single file, a folder, or a zip, including zips inside zips (Garmin's export nests its files).
|
||||||
|
`walk()` lists every file without unpacking to disk, then the importer decides what each one is:
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
flowchart TD
|
||||||
|
P[path: file, folder or zip] --> WK[walk: list all files,<br/>open nested zips, un-gzip]
|
||||||
|
WK --> Q1{activities.csv with<br/>'Activity ID' column?}
|
||||||
|
Q1 -->|yes| ST[Strava export importer]
|
||||||
|
WK --> Q2{DI_CONNECT/ in path?}
|
||||||
|
Q2 -->|yes| GX[Garmin export importer]
|
||||||
|
WK --> REST[everything else] --> T{extension}
|
||||||
|
T -->|.fit| FIT[import_fit]
|
||||||
|
T -->|.tcx| TCX[import_tcx]
|
||||||
|
T -->|.trk| TRK[import_trk]
|
||||||
|
T -->|.gpx| GPX[import_gpx]
|
||||||
|
T -->|other| IGN[ignored]
|
||||||
|
```
|
||||||
|
|
||||||
|
Account exports are recognised first, because their files only make sense together (Strava's names, times and sports are
|
||||||
|
in `activities.csv`, not in the track files). Every other file is imported on its own.
|
||||||
|
|
||||||
|
### Per file type (`sources/files.py`, readers in `formats/`)
|
||||||
|
|
||||||
|
| Type | What happens |
|
||||||
|
|---|---|
|
||||||
|
| **FIT** (`formats/fit.py`) | Already-known content is skipped. The file type is read straight from the header (fast enough for Garmin's ~11,000 uploaded files). Health and course FITs are only stored. Activity FITs: the session summary (distance, timer and elapsed time, ascent, heart rate, calories, training effect) plus GPS points; VO2max comes from an undocumented Garmin message. Stored as `originals/garmin_fit/<local start>.fit`, the same name the watch uses. |
|
||||||
|
| **TCX** (`formats/tcx.py`) | Summed from the laps; sport from the file name (old Garmin software put it there) or the `Sport` attribute; ascent with 3 m hysteresis. A second file with the same start is stored as a copy but not counted (old software saved many). |
|
||||||
|
| **AlpineQuest .trk** (`formats/aqtrk.py`) | Binary format per Psyberia's spec (current and pre-2.2.8 versions). Tracks with fewer than 10 timed points are stored only. The summary is computed from the points (see *Tracks without a summary*). Sport from AlpineQuest's activity tag, else guessed by speed. |
|
||||||
|
| **GPX** (`formats/gpx.py`) | Any creator. Files without a timed track (routes, waypoints) are stored only. Otherwise as AlpineQuest. |
|
||||||
|
|
||||||
|
### Tracks without a summary (`formats/geo.py`, `files.from_points`)
|
||||||
|
Phone tracks carry only points, so distance and time are worked out:
|
||||||
|
- **Distance:** sum of great-circle steps, skipping fixes with accuracy worse than 50 m.
|
||||||
|
- **Moving time:** time between points moving at 0.3–70 m/s with gaps under 5 min.
|
||||||
|
- **Ascent:** rises of more than 5 m (noise filter).
|
||||||
|
- **Flags:**
|
||||||
|
- `too short`: under 300 m or under 5 min moving.
|
||||||
|
- `transport`: tagged car, plane, train, boat or bus; or average above 28 km/h; or the 90th-percentile speed above 45 km/h.
|
||||||
|
- **Sport when untagged:** cycling from 12 km/h; running from 7.5 km/h; otherwise hiking (200 m+ climb or over 3 h), else walking.
|
||||||
|
|
||||||
|
### Strava export (`sources/strava.py`)
|
||||||
|
One row of `activities.csv` per activity:
|
||||||
|
- **Name, type, times:** from the CSV, which is UTC and has some columns twice; either copy may hold the value.
|
||||||
|
- **Points:** from the activity file (`.fit.gz`, `.gpx` or `.tcx`).
|
||||||
|
- **Time fixes:**
|
||||||
|
- Elapsed time falls back to the track's own time span.
|
||||||
|
- Moving time under 60 s (very sparse old tracks) is replaced by the elapsed time.
|
||||||
|
- **Flags:**
|
||||||
|
- `no time`: no usable time at all.
|
||||||
|
- `suspect GPS`: a "run" faster than 3:30/km, faster than 30 km/h at peak, or under 4:30/km while moving less than 55% of the elapsed time (GPS glitches and rides saved as runs).
|
||||||
|
|
||||||
|
### Garmin Connect export (`sources/garmin_export.py`)
|
||||||
|
- **Health JSON** under `DI_CONNECT/`. Every file ends in NUL padding, which is stripped before parsing.
|
||||||
|
- Daily summary (`UDSFile`): resting HR (Garmin's 7-day average), steps, intensity minutes (moderate + 2 × vigorous), all-day stress, Body Battery high and low.
|
||||||
|
- Sleep: stages, score, SpO2, respiration and sleep stress. Nights under 1 h of sleep are skipped. Bed and wake times are stored as local clock hours, with evening times negative so averages around midnight work.
|
||||||
|
- HRV, training readiness (the morning value preferred; HRV glitches outside 10–200 ms dropped), acute and chronic load, training status, race predictions, endurance and hill score.
|
||||||
|
- VO2max, fitness age, blood pressure (haemoglobin parsed from the note) and lactate threshold go to `health_series`.
|
||||||
|
- **Uploaded files:** of the FITs in `DI-Connect-Uploaded-Files/*.zip`, only activities are imported. The monitoring files are already covered by the JSON. This is how activities missing from a watch archive turn up.
|
||||||
|
|
||||||
|
### Garmin watch over USB (`sources/watch.py`)
|
||||||
|
- **Finding the watch:** newer watches have no drive letter on Windows (MTP). The watch is found by Garmin's USB vendor ID `091e`, which works in any Windows language and never matches a phone.
|
||||||
|
- **Copying:** its `Activity`, `Monitor`, `Sleep`, `HRVStatus`, `Metrics`, `Courses`, … folders are copied through the Windows Shell to a temporary folder. That folder is then imported like any other, and deleted.
|
||||||
|
- **Older watches** that appear as a drive can simply be imported as a folder.
|
||||||
|
|
||||||
|
### Garmin Connect API (`sources/garmin_api.py`)
|
||||||
|
Uses the unofficial `python-garminconnect` library (read-only). Garmin has no personal API.
|
||||||
|
- **Login:** once, with password and MFA code. Only a self-refreshing token is stored, per library, on the PC.
|
||||||
|
- **Activities:** everything since the newest FIT in the library minus 3 days. Each is downloaded in its original format: a zip holding the very same FIT file the watch made, so it goes through `import_fit` and can never create a duplicate.
|
||||||
|
- **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
|
||||||
|
2. the time zone at the first GPS point (offline lookup with `timezonefinder`, daylight saving included); else
|
||||||
|
3. the library's home time zone.
|
||||||
|
|
||||||
|
## De-duplication (`dedupe.py`)
|
||||||
|
One outing is often recorded several times: watch, phone app and Strava. All copies are imported; afterwards a single pass
|
||||||
|
decides which one to keep:
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
flowchart LR
|
||||||
|
A[all activities except<br/>transport / too short / no time] --> S[sort by source priority,<br/>then start time]
|
||||||
|
S --> L{for each: an already-kept<br/>activity of the same outing?}
|
||||||
|
L -->|yes| M[mark dup_of = kept one]
|
||||||
|
L -->|no| K[keep]
|
||||||
|
```
|
||||||
|
|
||||||
|
- **Priority:** FIT (watch) > TCX (older Garmin) > AlpineQuest > Strava > GPX. The watch has heart rate and the best summary.
|
||||||
|
- **Same outing:** the starts are less than 15 min apart, **or** more than half of the lower-priority recording lies
|
||||||
|
inside the kept one. The second rule catches a phone that was started late; it deliberately lets a short run recorded
|
||||||
|
during a long phone-tracked ride stand on its own.
|
||||||
|
- **Same source:** only starts less than 60 s apart count (the same activity saved twice).
|
||||||
|
- The pass is rerun after every import and recomputes all `dup_of` values from scratch, so it reflects the current rules.
|
||||||
|
|
||||||
|
## Building the dashboard (`report/`)
|
||||||
|
1. Select the activities to show: not a duplicate, and flag empty, `suspect GPS` or `summary only`.
|
||||||
|
2. Collect one JSON object: profile (name, birth year, sex), activities, simplified tracks, health days and series, and races from `races.csv`.
|
||||||
|
3. Put it into the template `report/dashboard.html` (`__DATA__`) and write a single self-contained HTML file.
|
||||||
|
Charts (Chart.js) and the map (Leaflet with Esri and OpenTopoMap tiles) load from the web; everything else is in the file.
|
||||||
|
4. Everything visible is computed **in the page** from that data, so nothing personal is in the template:
|
||||||
|
- the header: sources, years covered, gaps without recordings;
|
||||||
|
- totals, the year-by-year table, monthly volume and fitness charts;
|
||||||
|
- the findings: busiest year, fastest running period, VO2max rated against the Cooper Institute norms for the person's age and sex, efficiency trend, maximum heart rate. Headlines pick their wording from the direction of the data ("getting shorter" or "longer");
|
||||||
|
- the sleep and health section and the races section, only when there is data.
|
||||||
|
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).
|
||||||
|
- **Two zips, in year folders:**
|
||||||
|
- `tracks_gpx.zip` (with heart rate as Garmin's GPX extension);
|
||||||
|
- `tracks_trk.zip` in AlpineQuest's own format, ready to copy to the phone. Every `.trk` is read back and compared before it is written.
|
||||||
|
- **File names:** local start, sport and name (`2024-05-04-08-00_running_Saturday-5k.trk`).
|
||||||
|
|
||||||
|
## The app window (`app/`)
|
||||||
|
- **Window:** a pywebview window (WebView2 on Windows) showing `app/ui.html`, which calls the Python `Api` class.
|
||||||
|
- **Jobs:** import, watch, sync, build, export and update run one at a time in a worker thread. Each streams its log lines into the page and refreshes the overview when done.
|
||||||
|
- **Garmin MFA:** the login waits while the page asks for the code.
|
||||||
|
- **Startup:** the window opens the last library used. Only one copy runs at a time, because a second would block on the shared browser data. Startup errors are shown in a message box and written to `app.log`.
|
||||||
|
|
||||||
|
## Installer (`packaging/`)
|
||||||
|
- **Bundle:** PyInstaller makes a one-folder, windowed `myGarmin.exe` with Python and all libraries inside.
|
||||||
|
- **Installer:** Inno Setup wraps it into `myGarmin-setup-<version>.exe`. It installs per user without admin rights, checks for WebView2, and its uninstaller never touches libraries.
|
||||||
|
- **Command line:** given arguments, the bundled exe runs the CLI and writes its output to `cli.log`.
|
||||||
|
- **Build:** run `packaging\build.ps1`.
|
||||||
@@ -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
|
d, b, h = collect_all(pkg); datas += d; binaries += b; hidden += h
|
||||||
|
|
||||||
a = Analysis(['launcher.py'], pathex=['../src'], binaries=binaries, datas=datas,
|
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)
|
excludes=['tkinter', 'matplotlib', 'pandas', 'PIL', 'pytest'], noarchive=False)
|
||||||
pyz = PYZ(a.pure)
|
pyz = PYZ(a.pure)
|
||||||
exe = EXE(pyz, a.scripts, [], exclude_binaries=True, name='myGarmin', icon='myGarmin.ico',
|
exe = EXE(pyz, a.scripts, [], exclude_binaries=True, name='myGarmin', icon='myGarmin.ico',
|
||||||
|
|||||||
@@ -4,12 +4,12 @@ build-backend = "setuptools.build_meta"
|
|||||||
|
|
||||||
[project]
|
[project]
|
||||||
name = "mygarmin"
|
name = "mygarmin"
|
||||||
version = "0.1.0"
|
version = "0.1.1"
|
||||||
description = "Local-first activity and health logbook for Garmin, Strava and AlpineQuest data"
|
description = "Local-first activity and health logbook for Garmin, Strava and AlpineQuest data"
|
||||||
readme = "README.md"
|
readme = "README.md"
|
||||||
requires-python = ">=3.12"
|
requires-python = ">=3.12"
|
||||||
license = "MIT"
|
license = "MIT"
|
||||||
dependencies = ["fitparse>=1.2", "timezonefinder>=6"]
|
dependencies = ["fitparse>=1.2", "timezonefinder>=6", "openpyxl>=3.1"]
|
||||||
|
|
||||||
[project.optional-dependencies]
|
[project.optional-dependencies]
|
||||||
api = ["garminconnect>=0.3.19", "curl_cffi"]
|
api = ["garminconnect>=0.3.19", "curl_cffi"]
|
||||||
|
|||||||
@@ -1,2 +1,2 @@
|
|||||||
"""myGarmin: local-first activity and health logbook for Garmin, Strava and AlpineQuest data."""
|
"""myGarmin: local-first activity and health logbook for Garmin, Strava and AlpineQuest data."""
|
||||||
__version__ = '0.1.0'
|
__version__ = '0.1.1'
|
||||||
|
|||||||
@@ -83,7 +83,7 @@ class Api:
|
|||||||
def pick_files(self):
|
def pick_files(self):
|
||||||
import webview
|
import webview
|
||||||
r = self._window.create_file_dialog(webview.FileDialog.OPEN, allow_multiple=True,
|
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 []
|
return list(r) if r else []
|
||||||
|
|
||||||
def _use(self, lib):
|
def _use(self, lib):
|
||||||
@@ -105,11 +105,12 @@ class Api:
|
|||||||
def close_library(self):
|
def close_library(self):
|
||||||
self._lib = None; _save_app_state(library=None); return self.state()
|
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)
|
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)
|
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'))
|
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()]
|
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)
|
json.dump(s, open(p, 'w', encoding='utf-8'), indent=1)
|
||||||
return self._use(Library(lib.root))
|
return self._use(Library(lib.root))
|
||||||
|
|
||||||
|
|||||||
@@ -128,7 +128,7 @@ details[open] > summary { margin-bottom: 10px }
|
|||||||
<h2>Add data</h2>
|
<h2>Add data</h2>
|
||||||
<div id="drop">
|
<div id="drop">
|
||||||
<b>Drop files or folders here</b>
|
<b>Drop files or folders here</b>
|
||||||
<span class="muted">Garmin or Strava export zips, a copied watch <code>GARMIN</code> folder, or .fit .tcx .gpx .trk files</span>
|
<span class="muted">Garmin or Strava export zips, a copied watch <code>GARMIN</code> folder, or .fit .tcx .gpx .trk files, or a blood test spreadsheet (.xlsx)</span>
|
||||||
<div class="row" style="justify-content:center;margin-top:12px">
|
<div class="row" style="justify-content:center;margin-top:12px">
|
||||||
<button class="job" onclick="ui.chooseFiles()">Choose files…</button>
|
<button class="job" onclick="ui.chooseFiles()">Choose files…</button>
|
||||||
<button class="job" onclick="ui.chooseFolder()">Choose a folder…</button>
|
<button class="job" onclick="ui.chooseFolder()">Choose a folder…</button>
|
||||||
@@ -182,6 +182,7 @@ details[open] > summary { margin-bottom: 10px }
|
|||||||
<label>Sex<select id="sSex"><option value="">Not set</option><option value="M">Male</option><option value="F">Female</option></select></label>
|
<label>Sex<select id="sSex"><option value="">Not set</option><option value="M">Male</option><option value="F">Female</option></select></label>
|
||||||
<label>Home time zone<input id="sTz" list="tzList"></label>
|
<label>Home time zone<input id="sTz" list="tzList"></label>
|
||||||
<label class="wide">Also copy the dashboard to (one path per line, e.g. a OneDrive folder)<textarea id="sCopies"></textarea></label>
|
<label class="wide">Also copy the dashboard to (one path per line, e.g. a OneDrive folder)<textarea id="sCopies"></textarea></label>
|
||||||
|
<label class="wide">Blood test spreadsheets, read again at every update (.xlsx or .csv, one path per line; a Date column plus e.g. Ferritin, Hb)<textarea id="sLabs"></textarea></label>
|
||||||
</div>
|
</div>
|
||||||
<div class="row" style="margin-top:10px"><button class="primary" onclick="ui.saveSettings()">Save settings</button><span class="note">Rebuild the dashboard afterwards to apply.</span></div>
|
<div class="row" style="margin-top:10px"><button class="primary" onclick="ui.saveSettings()">Save settings</button><span class="note">Rebuild the dashboard afterwards to apply.</span></div>
|
||||||
</details>
|
</details>
|
||||||
@@ -232,7 +233,7 @@ const ui = {
|
|||||||
$('openDash').disabled = !L.dashboard;
|
$('openDash').disabled = !L.dashboard;
|
||||||
const s = L.settings;
|
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';
|
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(name) {
|
||||||
$('busy').textContent = name ? `Working: ${name}…` : ''; $('busy').classList.toggle('hidden', !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 open() { ui.render(await ui.call('open_library', $('openPath').value.trim())) },
|
||||||
async saveSettings() {
|
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.');
|
$('settingsBox').open = false; ui.render(st); ui.log('Settings saved.');
|
||||||
},
|
},
|
||||||
async login() {
|
async login() {
|
||||||
|
|||||||
@@ -32,13 +32,16 @@ def data(lib):
|
|||||||
t = lib.db.execute('SELECT pts FROM tracks WHERE activity_id=?', (a['id'],)).fetchone()
|
t = lib.db.execute('SELECT pts FROM tracks WHERE activity_id=?', (a['id'],)).fetchone()
|
||||||
if t: tracks[a['file']] = json.loads(t[0])
|
if t: tracks[a['file']] = json.loads(t[0])
|
||||||
days = lib.days()
|
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
|
s = lib.settings
|
||||||
return {'profile': {'name': s.get('name'), 'birth_year': s.get('birth_year'), 'sex': s.get('sex')},
|
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),
|
'acts': acts, 'tracks': tracks, 'health': health, 'races': races(lib),
|
||||||
'built': datetime.now().strftime('%Y-%m-%d %H:%M'), 'version': __version__}
|
'built': datetime.now().strftime('%Y-%m-%d %H:%M'), 'version': __version__}
|
||||||
|
|
||||||
def build(lib, out=None, log=print):
|
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)
|
d = data(lib)
|
||||||
if not d['acts']: raise SystemExit('No activities in the library yet: import some first.')
|
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()
|
tpl = open(os.path.join(os.path.dirname(__file__), 'dashboard.html'), encoding='utf-8').read()
|
||||||
|
|||||||
@@ -133,10 +133,9 @@ h3.sub { margin: 8px 0 0; font: 600 16px var(--body) }
|
|||||||
<div class="card" data-k="acute"><h3>Training load: last 7 days against your usual (acute vs chronic)</h3><div class="legend" id="hLoadLeg"></div><div class="chartbox"><canvas id="cLoad" role="img" aria-label="Acute and chronic training load"></canvas></div></div>
|
<div class="card" data-k="acute"><h3>Training load: last 7 days against your usual (acute vs chronic)</h3><div class="legend" id="hLoadLeg"></div><div class="chartbox"><canvas id="cLoad" role="img" aria-label="Acute and chronic training load"></canvas></div></div>
|
||||||
</div>
|
</div>
|
||||||
<div id="bpBlock" hidden>
|
<div id="bpBlock" hidden>
|
||||||
<h3 class="sub">Blood pressure and haemoglobin (entered by hand)</h3>
|
<h3 class="sub" id="bpHead">Blood pressure and haemoglobin (entered by hand)</h3>
|
||||||
<div class="grid2">
|
<div id="bpGrid">
|
||||||
<div class="card" style="align-content:start"><div class="legend" id="hBpLeg"></div><div class="chartbox"><canvas id="cBp" role="img" aria-label="Blood pressure and haemoglobin readings"></canvas></div></div>
|
<div class="card" style="align-content:start"><p class="note" id="bpNote" hidden></p><div class="legend" id="hBpLeg"></div><div class="chartbox" style="height:420px"><canvas id="cBp" role="img" aria-label="Blood pressure, haemoglobin and blood test results over time"></canvas></div></div>
|
||||||
<div class="scroll"><table id="tBp"></table></div>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
@@ -383,6 +382,11 @@ if (hd) (function () {
|
|||||||
if (HEALTH.bp.length) { const s = HEALTH.bp.map(b => b.sys), d = HEALTH.bp.map(b => b.dia), hb = HEALTH.bp.filter(b => b.hb).map(b => b.hb);
|
if (HEALTH.bp.length) { const s = HEALTH.bp.map(b => b.sys), d = HEALTH.bp.map(b => b.dia), hb = HEALTH.bp.filter(b => b.hb).map(b => b.hb);
|
||||||
F.push(['Blood pressure' + (hb.length ? ' and haemoglobin' : ''), `${HEALTH.bp.length} readings since ${HEALTH.bp[0].d.slice(0, 7)}: ${range(s)} / ${range(d)} mmHg (median ${med(s)}/${med(d)}).` +
|
F.push(['Blood pressure' + (hb.length ? ' and haemoglobin' : ''), `${HEALTH.bp.length} readings since ${HEALTH.bp[0].d.slice(0, 7)}: ${range(s)} / ${range(d)} mmHg (median ${med(s)}/${med(d)}).` +
|
||||||
(hb.length ? ` Haemoglobin ${range(hb)} g/dL.` : '') + ' These are your own entries; discuss them with a doctor rather than relying on this summary.']) }
|
(hb.length ? ` Haemoglobin ${range(hb)} g/dL.` : '') + ' These are your own entries; discuss them with a doctor rather than relying on this summary.']) }
|
||||||
|
const LABS = HEALTH.labs || [], LNAME = { ferritin: 'Ferritin', hb: 'Haemoglobin', iron: 'Serum iron', tsat: 'Transferrin saturation', transferrin: 'Transferrin' };
|
||||||
|
const lm = ['ferritin', 'hb', 'iron', 'tsat', 'transferrin'].find(m => LABS.some(r => r.m === m)), LM = LABS.filter(r => r.m === lm);
|
||||||
|
if (LM.length) { const a = LM[0], z = LM.at(-1), t = z.target, lo = Math.min(...LM.map(r => r.v)), hi = Math.max(...LM.map(r => r.v));
|
||||||
|
F.push([LNAME[lm], `${LM.length} results since ${a.d.slice(0, 7)}: <b>${a.v}</b> → <b>${z.v} ${z.unit}</b> (${z.d}; lowest ${lo}, highest ${hi}).` +
|
||||||
|
(t ? ` The latest is ${z.v < t[0] ? 'below' : z.v > t[1] ? 'above' : 'within'} your target of ${t[0]}–${t[1]}.` : '') + ' Results from your own spreadsheet; discuss them with a doctor rather than relying on this summary.']) }
|
||||||
$('hFind').innerHTML = F.map(([t, p]) => `<article><h3>${t}</h3><p>${p}</p></article>`).join('');
|
$('hFind').innerHTML = F.map(([t, p]) => `<article><h3>${t}</h3><p>${p}</p></article>`).join('');
|
||||||
|
|
||||||
const hm_ = [...new Set(has('sleep').map(r => r.d.slice(0, 7)))];
|
const hm_ = [...new Set(has('sleep').map(r => r.d.slice(0, 7)))];
|
||||||
@@ -415,17 +419,35 @@ if (hd) (function () {
|
|||||||
tchart('cPred', [line(series('p5k'), color(0), { label: 'Predicted' }), dots(r5.map(r => ({ x: Date.parse(r.date), y: r.sec })), color(1), { label: 'Race', pointRadius: 5 })], { yfmt: mmss, tfmt: mmss, y: { reverse: true } });
|
tchart('cPred', [line(series('p5k'), color(0), { label: 'Predicted' }), dots(r5.map(r => ({ x: Date.parse(r.date), y: r.sec })), color(1), { label: 'Race', pointRadius: 5 })], { yfmt: mmss, tfmt: mmss, y: { reverse: true } });
|
||||||
leg('hLoadLeg', [['Acute load (7 days)', color(1)], ['Chronic load (4 weeks)', color(0)]]);
|
leg('hLoadLeg', [['Acute load (7 days)', color(1)], ['Chronic load (4 weeks)', color(0)]]);
|
||||||
tchart('cLoad', [line(series('acute'), color(1), { label: 'Acute', borderWidth: 1.5 }), line(series('chronic'), color(0), { label: 'Chronic' })]);
|
tchart('cLoad', [line(series('acute'), color(1), { label: 'Acute', borderWidth: 1.5 }), line(series('chronic'), color(0), { label: 'Chronic' })]);
|
||||||
if (HEALTH.bp.length) {
|
if (HEALTH.bp.length || LM.length) $('bpBlock').hidden = false;
|
||||||
$('bpBlock').hidden = false;
|
$('bpHead').textContent = [HEALTH.bp.length && 'Blood pressure', (HEALTH.bp.some(b => b.hb) || LABS.some(r => r.m === 'hb')) && 'haemoglobin', LM.length && lm !== 'hb' && LNAME[lm].toLowerCase()]
|
||||||
const B = HEALTH.bp.map(b => ({ ...b, t: Date.parse(b.d) }));
|
.filter(Boolean).join(', ').replace(/, ([^,]*)$/, ' and $1').replace(/^./, c => c.toUpperCase()) + ' (entered by hand)';
|
||||||
leg('hBpLeg', [['Systolic', color(4)], ['Diastolic', color(0)], ...(B.some(b => b.hb) ? [['Haemoglobin (right axis)', color(2)]] : [])]);
|
if (HEALTH.bp.length || LM.length) { // one chart: blood pressure (left axis), haemoglobin and the main blood test (right axes)
|
||||||
new Chart($('cBp'), { type: 'line', data: { datasets: [
|
const B = HEALTH.bp.map(b => ({ ...b, t: Date.parse(b.d) })), P = LM.map(r => ({ ...r, t: Date.parse(r.d) }));
|
||||||
line(B.map(b => ({ x: b.t, y: b.sys })), color(4), { label: 'Systolic', pointRadius: 3 }), line(B.map(b => ({ x: b.t, y: b.dia })), color(0), { label: 'Diastolic', pointRadius: 3 }),
|
const HB = [...B.filter(b => b.hb).map(b => ({ x: b.t, y: b.hb })), ...(lm !== 'hb' ? LABS.filter(r => r.m === 'hb').map(r => ({ x: Date.parse(r.d), y: r.v })) : [])].sort((a, b) => a.x - b.x);
|
||||||
dots(B.filter(b => b.hb).map(b => ({ x: b.t, y: b.hb })), color(2), { label: 'Hb', pointRadius: 4, yAxisID: 'y2' })] },
|
const labs = [...new Set(LM.map(r => r.lab || ''))].sort((a, b) => LM.filter(r => (r.lab || '') === b).length - LM.filter(r => (r.lab || '') === a).length);
|
||||||
options: { maintainAspectRatio: false, parsing: false, plugins: { legend: { display: false }, tooltip: { ...tip, callbacks: { title: i => fmtD(i[0].raw.x), label: i => `${i.dataset.label}: ${i.raw.y}${i.dataset.label === 'Hb' ? ' g/dL' : ' mmHg'}` } } },
|
const tgt = P.filter(r => r.target), cols = [1, 3, 6], unit = LM[0]?.unit, name = LNAME[lm];
|
||||||
scales: { x: { ...xAxis, min: undefined }, y: { grid, suggestedMin: 50, suggestedMax: 140 }, y2: { display: B.some(b => b.hb), position: 'right', grid: { display: false }, suggestedMin: 12, suggestedMax: 17 } } } });
|
const refs = labs.map(l => [l, LM.find(r => (r.lab || '') === l && r.ref)?.ref]).filter(([, r]) => r);
|
||||||
$('tBp').innerHTML = '<thead><tr><th class="l">Date</th><th>Blood pressure</th><th>Pulse</th><th>Hb g/dL</th><th class="l">Note</th></tr></thead><tbody>' +
|
if (LM.length) { $('bpNote').hidden = false;
|
||||||
[...B].reverse().map(b => `<tr><td>${b.d}</td><td>${b.sys}/${b.dia}</td><td>${b.pulse ?? ''}</td><td>${b.hb ?? ''}</td><td class="l dim">${(b.note || '').replace(/[<>&]/g, '')}</td></tr>`).join('') + '</tbody>';
|
$('bpNote').textContent = `${name} on the outer right axis` + (lm === 'ferritin' ? ' (log scale, so low values stay readable)' : '') + '. ' +
|
||||||
|
(refs.length ? 'Lab reference range: ' + refs.map(([l, r]) => `${l ? l + ' ' : ''}${r[0]}–${r[1]}`).join(', ') + ` ${unit}. ` : '') + (tgt.length ? 'Dashed: your own target range.' : '') }
|
||||||
|
leg('hBpLeg', [...(B.length ? [['Systolic', color(4)], ['Diastolic', color(0)]] : []), ...(HB.length ? [['Haemoglobin', color(2)]] : []),
|
||||||
|
...labs.map((l, i) => [`${name}${l ? ' ' + l : ''}`, color(cols[i % 3])]), ...(tgt.length ? [[`${name} target`, css('--muted'), true]] : [])]);
|
||||||
|
const ds = [
|
||||||
|
...(B.length ? [line(B.map(b => ({ x: b.t, y: b.sys, b })), color(4), { label: 'Systolic', unit: 'mmHg', pointRadius: 3 }), line(B.map(b => ({ x: b.t, y: b.dia, b })), color(0), { label: 'Diastolic', unit: 'mmHg', pointRadius: 3 })] : []),
|
||||||
|
...(HB.length ? [dots(HB, color(2), { label: 'Hb', unit: 'g/dL', pointRadius: 4, yAxisID: 'y2' })] : []),
|
||||||
|
...labs.map((l, i) => line(P.filter(r => (r.lab || '') === l).map(r => ({ x: r.t, y: r.v })), color(cols[i % 3]), { label: `${name}${l ? ' ' + l : ''}`, unit, pointRadius: 3, showLine: l === labs[0], yAxisID: 'y3' })),
|
||||||
|
...(tgt.length ? [0, 1].map(k => line(tgt.map(r => ({ x: r.t, y: r.target[k] })), css('--muted'), { label: `Target ${k ? 'max' : 'min'}`, unit, stepped: true, borderDash: [5, 4], borderWidth: 1.5, pointHoverRadius: 0, yAxisID: 'y3' })) : [])];
|
||||||
|
const ts = [...B.map(b => b.t), ...HB.map(h => h.x), ...P.map(r => r.t)], ttl = text => ({ display: true, text, color: css('--muted') });
|
||||||
|
new Chart($('cBp'), { type: 'line', data: { datasets: ds },
|
||||||
|
options: { maintainAspectRatio: false, parsing: false, interaction: { mode: 'nearest', intersect: false }, // hover near a point: a callout with its value
|
||||||
|
plugins: { legend: { display: false }, tooltip: { ...tip, filter: i => !i.dataset.label.startsWith('Target'), callbacks: { title: i => fmtD(i[0].raw.x),
|
||||||
|
label: i => i.raw.b ? `Blood pressure: ${i.raw.b.sys}/${i.raw.b.dia} mmHg` + (i.raw.b.pulse ? `, pulse ${i.raw.b.pulse}` : '') : `${i.dataset.label}: ${i.raw.y} ${i.dataset.unit}` } } },
|
||||||
|
scales: { x: { ...xAxis, min: Math.min(...ts) - 15 * 864e5, max: Math.max(...ts) + 15 * 864e5 },
|
||||||
|
y: { display: B.length > 0, grid, suggestedMin: 50, suggestedMax: 140, title: ttl('mmHg') },
|
||||||
|
y2: { display: HB.length > 0, position: 'right', grid: { display: false }, suggestedMin: 12, suggestedMax: 17, title: ttl('Hb g/dL') },
|
||||||
|
y3: { display: LM.length > 0, position: 'right', grid: { display: B.length === 0 }, title: ttl(`${name} ${unit}`), type: lm === 'ferritin' ? 'logarithmic' : 'linear',
|
||||||
|
...(lm === 'ferritin' ? { afterBuildTicks: ax => { ax.ticks = [5, 10, 20, 50, 100, 200, 500, 1000, 2000, 5000].filter(v => v >= ax.min && v <= ax.max).map(value => ({ value })) } } : {}) } } } });
|
||||||
}
|
}
|
||||||
})();
|
})();
|
||||||
|
|
||||||
|
|||||||
@@ -40,7 +40,9 @@ def _root_of(name, marker):
|
|||||||
|
|
||||||
def import_path(lib, path, log=print):
|
def import_path(lib, path, log=print):
|
||||||
"""Import everything under `path` into the library; returns a Counter of what happened."""
|
"""Import everything under `path` into the library; returns a Counter of what happened."""
|
||||||
from . import files, strava, garmin_export
|
from . import files, strava, garmin_export, labs
|
||||||
|
if os.path.isfile(path) and labs.is_sheet(path) and labs.read(open(path, 'rb').read(), path):
|
||||||
|
return collections.Counter({'blood test results': labs.add_file(lib, path, log)}) # kept in settings, re-read at every build
|
||||||
items = list(walk(path))
|
items = list(walk(path))
|
||||||
stats = collections.Counter()
|
stats = collections.Counter()
|
||||||
# account exports first: their files need the export's own index (Strava) or are mostly health data (Garmin)
|
# account exports first: their files need the export's own index (Strava) or are mostly health data (Garmin)
|
||||||
@@ -55,6 +57,6 @@ def import_path(lib, path, log=print):
|
|||||||
part = [i for i in items if i.name.startswith(r + 'DI_CONNECT/')]
|
part = [i for i in items if i.name.startswith(r + 'DI_CONNECT/')]
|
||||||
stats.update(garmin_export.import_export(lib, part, log)); used |= {i.name for i in items if i.name.startswith(r)}
|
stats.update(garmin_export.import_export(lib, part, log)); used |= {i.name for i in items if i.name.startswith(r)}
|
||||||
for i in items:
|
for i in items:
|
||||||
if i.name not in used: stats[files.import_file(lib, i)] += 1
|
if i.name not in used: stats[labs.import_item(lib, i) if labs.is_sheet(i.base) else files.import_file(lib, i)] += 1
|
||||||
lib.commit()
|
lib.commit()
|
||||||
return stats
|
return stats
|
||||||
|
|||||||
130
src/mygarmin/sources/labs.py
Normal file
130
src/mygarmin/sources/labs.py
Normal file
@@ -0,0 +1,130 @@
|
|||||||
|
"""Blood test results kept in a spreadsheet (.xlsx or .csv): ferritin, haemoglobin, serum iron, transferrin saturation.
|
||||||
|
|
||||||
|
The sheet needs a header row with a 'Date' column; other columns are recognised by their header text, e.g.
|
||||||
|
'Ferritin [ug/L] Roche (30-400)'. A range in brackets is kept as the lab's reference range, the rest of the header
|
||||||
|
(here 'Roche') as the lab's name, and columns headed 'Min' and 'Max' as your own target range. Only typed-in numbers
|
||||||
|
count: cells with a formula (estimates, differences) are skipped. Sheets listed in settings.json "lab_files" are
|
||||||
|
read again at every dashboard build, so the dashboard follows the spreadsheet."""
|
||||||
|
import csv, io, os, re
|
||||||
|
from datetime import date, datetime
|
||||||
|
|
||||||
|
MARKERS = [ # (marker, unit, header pattern); first match wins
|
||||||
|
('ferritin', 'µg/L', r'ferrit|feritien|ferratin|[uµ]g\s*/\s*l\b|ng\s*/\s*ml'),
|
||||||
|
('tsat', '%', r'transf\w*\s*sat|\btsat\b|saturation'),
|
||||||
|
('transferrin', 'g/L', r'transferr?in'),
|
||||||
|
('iron', 'µmol/L', r'\biron\b|\byster\b|serum\s*fe\b'),
|
||||||
|
('hb', 'g/dL', r'\bhg?b\b|h(?:a|ae|e)?moglobi|himoglobien'),
|
||||||
|
]
|
||||||
|
NOISE = r'ferrit\w*|feritien|ferratin\w*|transferr?in|saturation|tsat|serum|iron|yster|h(?:a|ae|e)?moglobi\w*|himoglobien|\bhg?b\b|\blab\b|\[.*?\]|\(.*?\)|[uµ]g\s*/\s*l|ng\s*/\s*ml|g\s*/\s*dl|µmol\s*/\s*l|%'
|
||||||
|
|
||||||
|
def _columns(header):
|
||||||
|
"""{column index: role} for one header row, or None when there is no Date column or no marker."""
|
||||||
|
txt = [re.sub(r'\s+', ' ', str(h or '')).strip() for h in header]
|
||||||
|
low = [t.lower() for t in txt]
|
||||||
|
if 'date' not in low and 'datum' not in low: return None
|
||||||
|
cols = {(low.index('date') if 'date' in low else low.index('datum')): {'role': 'date'}}
|
||||||
|
for i, t in enumerate(low):
|
||||||
|
if i in cols or not t: continue
|
||||||
|
if t in ('min', 'target min'): cols[i] = {'role': 'tmin'}; continue
|
||||||
|
if t in ('max', 'target max'): cols[i] = {'role': 'tmax'}; continue
|
||||||
|
for m, unit, pat in MARKERS:
|
||||||
|
if re.search(pat, t):
|
||||||
|
ref = re.search(r'(\d+(?:[.,]\d+)?)\s*[-–]\s*(\d+(?:[.,]\d+)?)', t)
|
||||||
|
lab = re.sub(r'\s+', ' ', re.sub(NOISE, ' ', txt[i], flags=re.I)).strip(' -:,')
|
||||||
|
cols[i] = {'role': 'value', 'm': m, 'unit': unit, 'lab': lab or None,
|
||||||
|
'ref': [float(ref.group(1).replace(',', '.')), float(ref.group(2).replace(',', '.'))] if ref else None}
|
||||||
|
break
|
||||||
|
return cols if any(c['role'] == 'value' for c in cols.values()) else None
|
||||||
|
|
||||||
|
def _rows_xlsx(data):
|
||||||
|
"""Rows of (value, typed) pairs from the first sheet with a usable header; typed = a number or date typed in, not a formula."""
|
||||||
|
import openpyxl
|
||||||
|
f = openpyxl.load_workbook(io.BytesIO(data)) # formulas as text
|
||||||
|
v = openpyxl.load_workbook(io.BytesIO(data), data_only=True) # the values Excel saved
|
||||||
|
for ws in f.worksheets:
|
||||||
|
wv = v[ws.title]
|
||||||
|
for fr, vr in zip(ws.iter_rows(), wv.iter_rows()):
|
||||||
|
yield ws.title, [(c2.value, not (isinstance(c1.value, str) and c1.value.startswith('='))) for c1, c2 in zip(fr, vr)]
|
||||||
|
|
||||||
|
def _rows_csv(data):
|
||||||
|
text = data.decode('utf-8-sig', errors='replace')
|
||||||
|
dialect = csv.Sniffer().sniff(text[:4096], delimiters=',;\t') if text.strip() else csv.excel
|
||||||
|
for r in csv.reader(io.StringIO(text), dialect):
|
||||||
|
yield '', [(x.strip(), True) for x in r]
|
||||||
|
|
||||||
|
def _num(x):
|
||||||
|
if isinstance(x, (int, float)) and not isinstance(x, bool): return float(x)
|
||||||
|
if isinstance(x, str):
|
||||||
|
m = re.fullmatch(r'\s*[<>]?\s*(\d+(?:[.,]\d+)?)\s*', x)
|
||||||
|
if m: return float(m.group(1).replace(',', '.'))
|
||||||
|
return None
|
||||||
|
|
||||||
|
def _day(x):
|
||||||
|
if isinstance(x, datetime): return x.date().isoformat()
|
||||||
|
if isinstance(x, date): return x.isoformat()
|
||||||
|
if isinstance(x, str):
|
||||||
|
for fmt in ('%Y-%m-%d', '%Y/%m/%d', '%d/%m/%Y', '%d-%m-%Y', '%d.%m.%Y', '%d %b %Y', '%d %B %Y'):
|
||||||
|
try: return datetime.strptime(x.strip()[:20], fmt).date().isoformat()
|
||||||
|
except ValueError: pass
|
||||||
|
return None
|
||||||
|
|
||||||
|
def read(data, name):
|
||||||
|
"""All typed-in results in the sheet: [{'d', 'm', 'v', 'unit', 'lab', 'ref', 'target'}, ...]."""
|
||||||
|
rows = _rows_xlsx(data) if name.lower().endswith(('.xlsx', '.xlsm')) else _rows_csv(data)
|
||||||
|
out, cols, sheet = [], None, None
|
||||||
|
for title, r in rows:
|
||||||
|
if title != sheet: sheet, cols = title, None
|
||||||
|
if cols is None:
|
||||||
|
cols = _columns([x for x, _ in r]); continue
|
||||||
|
get = lambda role: next(((r[i][0], r[i][1]) for i, c in cols.items() if c['role'] == role and i < len(r)), (None, False))
|
||||||
|
d = _day(get('date')[0])
|
||||||
|
if not d: continue
|
||||||
|
tmin, tmax = _num(get('tmin')[0]), _num(get('tmax')[0])
|
||||||
|
for i, c in cols.items():
|
||||||
|
if c['role'] != 'value' or i >= len(r) or not r[i][1]: continue
|
||||||
|
v = _num(r[i][0])
|
||||||
|
if v is None: continue
|
||||||
|
out.append({'d': d, 'm': c['m'], 'v': round(v, 2), 'unit': c['unit'], 'lab': c['lab'], 'ref': c['ref'],
|
||||||
|
'target': [tmin, tmax] if tmin is not None and tmax is not None and c['m'] == 'ferritin' else None})
|
||||||
|
return out
|
||||||
|
|
||||||
|
def is_sheet(name): return name.lower().endswith(('.xlsx', '.xlsm', '.csv'))
|
||||||
|
|
||||||
|
def _save(lib, results, src):
|
||||||
|
lib.db.execute("DELETE FROM health_series WHERE kind='lab' AND json_extract(data, '$.src')=?", (src,)) # rows removed from the sheet go too
|
||||||
|
for r in results:
|
||||||
|
lib.add_series('lab', r['d'], f"{r['m']}:{r['lab'] or ''}", {k: v for k, v in r.items() if k != 'd'} | {'src': src})
|
||||||
|
return len(results)
|
||||||
|
|
||||||
|
def import_item(lib, item):
|
||||||
|
"""A sheet found while importing (also inside a folder or zip); the original is kept under originals/labs/."""
|
||||||
|
data = item.read()
|
||||||
|
try: res = read(data, item.base)
|
||||||
|
except Exception: return 'not an activity file'
|
||||||
|
if not res: return 'not an activity file'
|
||||||
|
lib.store(data, 'labs', item.base, kind='labs')
|
||||||
|
_save(lib, res, item.base)
|
||||||
|
return 'blood test results'
|
||||||
|
|
||||||
|
def add_file(lib, path, log=print):
|
||||||
|
"""Remember a sheet on disk in settings.json "lab_files" (read again at every build) and read it now."""
|
||||||
|
import json
|
||||||
|
path = os.path.abspath(path)
|
||||||
|
p = lib.path('settings.json'); s = json.load(open(p, encoding='utf-8'))
|
||||||
|
if path not in (s.get('lab_files') or []):
|
||||||
|
s['lab_files'] = (s.get('lab_files') or []) + [path]
|
||||||
|
json.dump(s, open(p, 'w', encoding='utf-8'), indent=1); lib.settings['lab_files'] = s['lab_files']
|
||||||
|
log(f' {path} will be read again at every update (Settings: blood test spreadsheets)')
|
||||||
|
return refresh(lib, log, only=path)
|
||||||
|
|
||||||
|
def refresh(lib, log=print, only=None):
|
||||||
|
"""Read the sheets in settings "lab_files" again; a sheet that is missing (moved, offline) keeps its last results."""
|
||||||
|
n = 0
|
||||||
|
for p in lib.settings.get('lab_files') or []:
|
||||||
|
if only and p != only: continue
|
||||||
|
if not os.path.exists(p): log(f' blood test sheet not found, kept the last results: {p}'); continue
|
||||||
|
try: k = _save(lib, read(open(p, 'rb').read(), p), p)
|
||||||
|
except Exception as e: log(f' could not read {p}: {e}'); continue
|
||||||
|
log(f' {k} blood test results from {os.path.basename(p)}'); n += k
|
||||||
|
lib.commit()
|
||||||
|
return n
|
||||||
30
tests/test_labs.py
Normal file
30
tests/test_labs.py
Normal file
@@ -0,0 +1,30 @@
|
|||||||
|
"""Blood test spreadsheet: typed-in values are read, formula cells skipped, and edits to the sheet show at the next read."""
|
||||||
|
from datetime import datetime
|
||||||
|
import openpyxl
|
||||||
|
from mygarmin.library import Library
|
||||||
|
from mygarmin.sources import import_path, labs
|
||||||
|
|
||||||
|
def sheet(path, extra_row=True):
|
||||||
|
wb = openpyxl.Workbook(); ws = wb.active
|
||||||
|
ws.append(['Notes'])
|
||||||
|
ws.append(['Date', 'Min', 'Max', 'Ferritin [ug/L] LabOne (30-400)', 'Lab LabTwo (20-250 ug/L)', 'Haemoglobin'])
|
||||||
|
ws.append([datetime(2024, 1, 10), 50, 100, 300, None, 14.5])
|
||||||
|
ws.append([datetime(2024, 1, 10), 50, 100, '=D3*0.9', None, None]) # an estimate: must be skipped
|
||||||
|
ws.append([datetime(2024, 2, 10), 50, 100, None, 180, None])
|
||||||
|
if extra_row: ws.append([datetime(2024, 3, 10), 50, 100, 120, None, None])
|
||||||
|
wb.save(path)
|
||||||
|
|
||||||
|
def test_lab_sheet(tmp_path):
|
||||||
|
lib = Library.create(str(tmp_path / 'lib'), name='Test')
|
||||||
|
p = str(tmp_path / 'results.xlsx'); sheet(p)
|
||||||
|
st = import_path(lib, p, log=lambda *a: None)
|
||||||
|
assert st['blood test results'] == 4
|
||||||
|
rows = lib.series('lab')
|
||||||
|
fer = [r for r in rows if r['m'] == 'ferritin']
|
||||||
|
assert [(r['d'], r['v'], r['lab']) for r in fer] == [('2024-01-10', 300.0, 'LabOne'), ('2024-02-10', 180.0, 'LabTwo'), ('2024-03-10', 120.0, 'LabOne')]
|
||||||
|
assert fer[0]['ref'] == [30.0, 400.0] and fer[0]['target'] == [50.0, 100.0] and fer[1]['ref'] == [20.0, 250.0]
|
||||||
|
assert [r['v'] for r in rows if r['m'] == 'hb'] == [14.5]
|
||||||
|
assert Library(lib.root).settings['lab_files'] == [p]
|
||||||
|
sheet(p, extra_row=False) # a row deleted in the sheet goes at the next read
|
||||||
|
labs.refresh(Library(lib.root), log=lambda *a: None)
|
||||||
|
assert len([r for r in lib.series('lab') if r['m'] == 'ferritin']) == 2
|
||||||
Reference in New Issue
Block a user