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)
`).join('') + '';
+ }
if (HEALTH.bp.length) {
- $('bpBlock').hidden = false;
const B = HEALTH.bp.map(b => ({ ...b, t: Date.parse(b.d) }));
leg('hBpLeg', [['Systolic', color(4)], ['Diastolic', color(0)], ...(B.some(b => b.hb) ? [['Haemoglobin (right axis)', color(2)]] : [])]);
new Chart($('cBp'), { type: 'line', data: { datasets: [
diff --git a/src/mygarmin/sources/__init__.py b/src/mygarmin/sources/__init__.py
index cf50c47..420bdb2 100644
--- a/src/mygarmin/sources/__init__.py
+++ b/src/mygarmin/sources/__init__.py
@@ -40,7 +40,9 @@ def _root_of(name, marker):
def import_path(lib, path, log=print):
"""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))
stats = collections.Counter()
# 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/')]
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:
- 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()
return stats
diff --git a/src/mygarmin/sources/labs.py b/src/mygarmin/sources/labs.py
new file mode 100644
index 0000000..edfe853
--- /dev/null
+++ b/src/mygarmin/sources/labs.py
@@ -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
diff --git a/tests/test_labs.py b/tests/test_labs.py
new file mode 100644
index 0000000..13546a1
--- /dev/null
+++ b/tests/test_labs.py
@@ -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