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:
@@ -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:
|
||||
|
||||
@@ -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).
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -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"]
|
||||
|
||||
@@ -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))
|
||||
|
||||
|
||||
@@ -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() {
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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: [
|
||||
|
||||
@@ -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
|
||||
|
||||
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