Blood test spreadsheets: ferritin, Hb, iron in the health section

- sources/labs.py reads .xlsx/.csv sheets with a Date column; columns are
  recognised by header (ferritin, Hb, serum iron, transferrin saturation),
  with the lab's reference range and the user's Min/Max target. Formula
  cells are skipped.
- Importing a sheet from disk remembers it in settings "lab_files"; every
  dashboard build reads it again. Editable in the app's settings.
- Dashboard: ferritin chart (log scale, main lab as a line, a second lab
  as points, target range dashed), results table and a finding.
- openpyxl added as a dependency and to the installer bundle.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Riaan Doorduin
2026-11-15 13:20:25 +02:00
parent c6a1eb199d
commit 0d3da5f2df
11 changed files with 224 additions and 16 deletions

View File

@@ -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))

View File

@@ -128,7 +128,7 @@ details[open] > summary { margin-bottom: 10px }
<h2>Add data</h2>
<div id="drop">
<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">
<button class="job" onclick="ui.chooseFiles()">Choose files…</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>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">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 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>
@@ -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() {

View File

@@ -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()

View File

@@ -133,11 +133,15 @@ 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>
<div id="bpBlock" hidden>
<h3 class="sub">Blood pressure and haemoglobin (entered by hand)</h3>
<div class="grid2">
<h3 class="sub" id="bpHead">Blood pressure and haemoglobin (entered by hand)</h3>
<div class="grid2" 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="scroll"><table id="tBp"></table></div>
</div>
<div class="grid2" id="labGrid" hidden>
<div class="card" style="align-content:start"><h3 id="labHead">Ferritin</h3><p class="note" id="labNote"></p><div class="legend" id="hLabLeg"></div><div class="chartbox"><canvas id="cLab" role="img" aria-label="Blood test results over time"></canvas></div></div>
<div class="scroll"><table id="tLab"></table></div>
</div>
</div>
</section>
@@ -383,6 +387,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);
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.']) }
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('');
const hm_ = [...new Set(has('sleep').map(r => r.d.slice(0, 7)))];
@@ -415,8 +424,28 @@ 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 } });
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' })]);
if (HEALTH.bp.length || LM.length) $('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()]
.filter(Boolean).join(', ').replace(/, ([^,]*)$/, ' and $1').replace(/^./, c => c.toUpperCase()) + ' (entered by hand)';
$('bpGrid').hidden = !HEALTH.bp.length;
if (LM.length) {
$('labGrid').hidden = false;
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), P = LM.map(r => ({ ...r, t: Date.parse(r.d) }));
$('labHead').textContent = `${LNAME[lm]} (${LM[0].unit})`;
const refs = labs.map(l => [l, LM.find(r => (r.lab || '') === l && r.ref)?.ref]).filter(([, r]) => r);
$('labNote').textContent = (refs.length ? 'Lab reference range: ' + refs.map(([l, r]) => `${l ? l + ' ' : ''}${r[0]}–${r[1]}`).join(', ') + '. ' : '') +
(P.some(r => r.target) ? 'Dashed lines: your own target range. ' : '') + (lm === 'ferritin' ? 'Log scale, so low values stay readable.' : '');
const tgt = P.filter(r => r.target), cols = [1, 0, 3, 6, 2];
leg('hLabLeg', [...labs.map((l, i) => [l || LNAME[lm], color(cols[i % 5])]), ...(tgt.length ? [['Your target', css('--muted'), true]] : [])]);
new Chart($('cLab'), { type: 'line', data: { datasets: [
...labs.map((l, i) => line(P.filter(r => (r.lab || '') === l).map(r => ({ x: r.t, y: r.v })), color(cols[i % 5]), { label: l || LNAME[lm], pointRadius: 3, showLine: l === labs[0] })),
...(tgt.length ? [0, 1].map(k => line(tgt.map(r => ({ x: r.t, y: r.target[k] })), css('--muted'), { label: k ? 'Target max' : 'Target min', stepped: true, borderDash: [5, 4], borderWidth: 1.5, pointHoverRadius: 0 })) : [])] },
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} ${LM[0].unit}` } } },
scales: { x: { ...xAxis, min: P[0].t - 15 * 864e5, max: P.at(-1).t + 15 * 864e5 }, y: { type: lm === 'ferritin' ? 'logarithmic' : 'linear', grid, ...(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 })) } } : {}) } } } });
$('tLab').innerHTML = '<thead><tr><th class="l">Date</th><th class="l">Test</th><th>Result</th><th class="l">Lab</th><th>Reference</th></tr></thead><tbody>' +
[...LABS].reverse().map(r => `<tr><td>${r.d}</td><td class="l">${LNAME[r.m]}</td><td>${r.v} ${r.unit}</td><td class="l dim">${(r.lab || '').replace(/[<>&]/g, '')}</td><td class="dim">${r.ref ? r.ref.join('–') : ''}</td></tr>`).join('') + '</tbody>';
}
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: [

View File

@@ -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

View 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