-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
1083 lines (945 loc) · 50.5 KB
/
Copy pathapp.py
File metadata and controls
1083 lines (945 loc) · 50.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import json
import streamlit as st
import pandas as pd
import requests
import plotly.express as px
import plotly.graph_objects as go
from datetime import datetime, timedelta, date
from pathlib import Path
from dotenv import load_dotenv
load_dotenv()
# ── Page config ───────────────────────────────────────────────────────────────
st.set_page_config(
page_title="Health Dashboard",
page_icon="🩺",
layout="wide",
initial_sidebar_state="collapsed",
)
# ── Constants ─────────────────────────────────────────────────────────────────
DATA_DIR = Path(__file__).parent / "data"
DATA_DIR.mkdir(exist_ok=True)
MANUAL_LOG = DATA_DIR / "manual_log.csv"
OURA_BASE = "https://api.ouraring.com/v2/usercollection"
MANUAL_COLUMNS = [
"date", "nicotine_pouches", "vape_puffs", "caffeine_mg",
"weight_lbs", "cpap_ahi", "cpap_hours", "cpap_flow_limit_95", "notes",
]
STREAKS_FILE = DATA_DIR / "streaks.json"
# ── Styles ────────────────────────────────────────────────────────────────────
st.markdown("""
<style>
/* Tighten top padding */
.block-container { padding-top: 1.5rem; }
/* Metric card */
[data-testid="metric-container"] {
background: #1e1e2e;
border-radius: 12px;
padding: 12px 16px;
border: 1px solid #2a2a3e;
}
/* Tab strip */
.stTabs [data-baseweb="tab-list"] { gap: 6px; }
.stTabs [data-baseweb="tab"] {
border-radius: 8px 8px 0 0;
padding: 6px 18px;
}
/* ── Hamburger toggle for collapsed sidebar ─────────────────────────── */
[data-testid="collapsedControl"] {
position: fixed;
top: 12px;
left: 12px;
z-index: 999;
background: #1e1e2e;
border: 1px solid #2a2a3e;
border-radius: 10px;
width: 44px;
height: 44px;
display: flex;
align-items: center;
justify-content: center;
transition: background 0.2s ease;
}
[data-testid="collapsedControl"]:hover {
background: #2a2a3e;
}
[data-testid="collapsedControl"] svg {
width: 22px;
height: 22px;
color: #60a5fa;
}
/* ── Sidebar close button styling ───────────────────────────────────── */
[data-testid="stSidebar"] button[kind="header"] {
background: #1e1e2e;
border: 1px solid #2a2a3e;
border-radius: 10px;
width: 36px;
height: 36px;
transition: background 0.2s ease;
}
[data-testid="stSidebar"] button[kind="header"]:hover {
background: #2a2a3e;
}
[data-testid="stSidebar"] button[kind="header"] svg {
color: #60a5fa;
}
/* ── Mobile responsive ────────────────────────────────────────────── */
@media (max-width: 768px) {
/* Stack columns vertically */
[data-testid="stHorizontalBlock"] {
flex-direction: column !important;
}
[data-testid="stHorizontalBlock"] > [data-testid="stColumn"] {
width: 100% !important;
flex: 1 1 100% !important;
}
/* Compact top padding */
.block-container { padding-top: 1rem; padding-left: 1rem; padding-right: 1rem; }
/* Smaller title on mobile */
h1 { font-size: 1.5rem !important; }
/* Full-width metric cards */
[data-testid="metric-container"] {
padding: 10px 14px;
margin-bottom: 6px;
}
/* Larger tap targets for form inputs */
[data-testid="stSidebar"] input,
[data-testid="stSidebar"] button {
min-height: 44px;
font-size: 16px !important; /* prevents iOS zoom on focus */
}
/* Radio buttons more tappable */
.stRadio label { padding: 8px 4px; }
}
</style>
""", unsafe_allow_html=True)
# ── Data helpers ──────────────────────────────────────────────────────────────
def init_manual_log() -> pd.DataFrame:
if not MANUAL_LOG.exists():
pd.DataFrame(columns=MANUAL_COLUMNS).to_csv(MANUAL_LOG, index=False)
df = pd.read_csv(MANUAL_LOG, dtype=str)
for col in MANUAL_COLUMNS:
if col not in df.columns:
df[col] = None
# Deduplicate: if multiple rows for the same date, keep the last one
df = df.drop_duplicates(subset=["date"], keep="last").reset_index(drop=True)
return df[MANUAL_COLUMNS]
def save_manual_log(df: pd.DataFrame):
df.to_csv(MANUAL_LOG, index=False)
def upsert_row(df: pd.DataFrame, new_row: dict) -> pd.DataFrame:
"""Insert or update a row by date."""
mask = df["date"] == str(new_row["date"])
if mask.any():
for k, v in new_row.items():
df.loc[mask, k] = v
else:
df = pd.concat([df, pd.DataFrame([new_row])], ignore_index=True)
return df
def parse_duration_hours(value) -> float | None:
"""Convert HH:MM:SS, HH:MM, or plain numeric strings to decimal hours."""
if value is None:
return None
s = str(value).strip()
if not s or s.lower() in ("nan", "none", ""):
return None
# Already a plain number
try:
return float(s)
except ValueError:
pass
# HH:MM:SS or HH:MM
parts = s.split(":")
try:
if len(parts) == 3:
h, m, sec = int(parts[0]), int(parts[1]), float(parts[2])
return h + m / 60 + sec / 3600
elif len(parts) == 2:
h, m = int(parts[0]), int(parts[1])
return h + m / 60
except Exception:
pass
return None
@st.cache_data(ttl=300, show_spinner=False)
def fetch_oura(endpoint: str, token: str, start: str, end: str):
try:
r = requests.get(
f"{OURA_BASE}/{endpoint}",
headers={"Authorization": f"Bearer {token}"},
params={"start_date": start, "end_date": end},
timeout=12,
)
if r.status_code == 200:
return r.json().get("data", [])
elif r.status_code == 401:
return {"error": "Invalid API token — check your token at cloud.ouraring.com"}
return {"error": f"Oura API returned {r.status_code}"}
except requests.exceptions.Timeout:
return {"error": "Request timed out — check your internet connection"}
except Exception as e:
return {"error": str(e)}
def oura_records_to_df(records, extra_fields: list[str]) -> pd.DataFrame:
"""Flatten Oura API records into a DataFrame."""
if isinstance(records, dict) and "error" in records:
st.error(f"⚠️ Oura: {records['error']}")
return pd.DataFrame()
if not records:
return pd.DataFrame()
rows = []
for d in records:
day_str = d.get("day") or (d.get("timestamp") or "")[:10]
row = {"date": pd.Timestamp(day_str)}
for f in extra_fields:
val = d.get(f)
# Flatten contributor sub-dicts
if isinstance(val, dict):
for k, v in val.items():
row[f"{f}_{k}"] = v
else:
row[f] = val
rows.append(row)
return pd.DataFrame(rows).sort_values("date").reset_index(drop=True)
def line_chart(df, x, y, title, color="#60a5fa", yunit="", yrange=None):
fig = px.line(df, x=x, y=y, markers=True,
color_discrete_sequence=[color], template="plotly_dark")
layout = dict(
paper_bgcolor="rgba(0,0,0,0)", plot_bgcolor="rgba(0,0,0,0)",
margin=dict(l=0, r=0, t=36, b=0),
title=dict(text=title, font_size=14),
xaxis_title="", yaxis_title=yunit,
showlegend=False,
)
if yrange:
layout["yaxis"] = dict(range=yrange, title=yunit)
fig.update_layout(**layout)
fig.update_traces(line_width=2)
return fig
def bar_chart(df, x, y, title, color="#60a5fa", yunit="", hline=None, hline_label=""):
fig = px.bar(df, x=x, y=y, title=title,
color_discrete_sequence=[color], template="plotly_dark")
if hline is not None:
fig.add_hline(y=hline, line_dash="dash", line_color="#6b7280",
annotation_text=hline_label, annotation_position="top right")
fig.update_layout(
paper_bgcolor="rgba(0,0,0,0)", plot_bgcolor="rgba(0,0,0,0)",
margin=dict(l=0, r=0, t=36, b=0),
xaxis_title="", yaxis_title=yunit,
)
return fig
def score_bands(fig):
"""Add green/yellow/red score bands to a figure with a 0–100 y axis."""
fig.add_hrect(y0=85, y1=100, fillcolor="#22c55e", opacity=0.06, line_width=0)
fig.add_hrect(y0=70, y1=85, fillcolor="#eab308", opacity=0.06, line_width=0)
fig.add_hrect(y0=0, y1=70, fillcolor="#ef4444", opacity=0.06, line_width=0)
return fig
def latest_val(df, col):
if df.empty or col not in df.columns:
return None
s = pd.to_numeric(df[col], errors="coerce").dropna()
return s.iloc[-1] if len(s) else None
def calc_delta(df, col):
"""Return the difference between the last two non-null values, or None."""
if df.empty or col not in df.columns:
return None
s = pd.to_numeric(df[col], errors="coerce").dropna()
if len(s) < 2:
return None
return round(float(s.iloc[-1] - s.iloc[-2]), 1)
# ── Streak helpers ────────────────────────────────────────────────────────────
def load_streaks() -> list[dict]:
if STREAKS_FILE.exists():
return json.loads(STREAKS_FILE.read_text())
return []
def save_streaks(streaks: list[dict]):
STREAKS_FILE.write_text(json.dumps(streaks, indent=2))
def streak_duration(start_date: date, as_of: date | None = None):
"""Return a human-readable duration string and total days."""
today = as_of or date.today()
delta = today - start_date
total_days = delta.days
if total_days < 0:
return "starts in the future", 0
years = total_days // 365
remaining = total_days % 365
months = remaining // 30
days = remaining % 30
parts = []
if years:
parts.append(f"{years}y")
if months:
parts.append(f"{months}m")
parts.append(f"{days}d")
return " ".join(parts), total_days
# ── Sidebar ───────────────────────────────────────────────────────────────────
with st.sidebar:
with st.expander("⚙️ Settings", expanded=True):
# Seed from .env on first load
if "oura_token" not in st.session_state:
st.session_state["oura_token"] = os.getenv("OURA_TOKEN", "")
oura_token = st.text_input(
"Oura API Token",
type="password",
value=st.session_state["oura_token"],
placeholder="Paste your personal access token",
help="Or set OURA_TOKEN in a .env file to load automatically",
)
if oura_token:
st.session_state["oura_token"] = oura_token
with st.expander("📅 Date Range", expanded=True):
col_a, col_b = st.columns(2)
with col_a:
start_date = st.date_input("From", value=date.today() - timedelta(days=30))
with col_b:
end_date = st.date_input("To", value=date.today())
with st.expander("✏️ Log Entry", expanded=False):
with st.form("manual_entry", clear_on_submit=True):
log_date = st.date_input("Date", value=date.today())
nicotine = st.number_input("Nicotine pouches", min_value=0, max_value=99, step=1, value=0)
vape_puffs = st.number_input("Vape puffs", min_value=0, max_value=9999, step=1, value=0)
caffeine = st.number_input("Caffeine (mg)", min_value=0, max_value=3000, step=25, value=0)
weight = st.number_input("Weight (lbs)", min_value=0.0, max_value=999.0, step=0.1,
format="%.1f", value=0.0)
cpap_ahi = st.number_input("CPAP AHI", min_value=0.0, max_value=999.0, step=0.1,
format="%.1f", value=0.0)
cpap_hours = st.number_input("CPAP hours used", min_value=0.0, max_value=24.0, step=0.25,
format="%.2f", value=0.0)
cpap_flow_limit = st.number_input("95% Flow Limitation", min_value=0.0, max_value=999.0,
step=0.01, format="%.2f", value=0.0)
notes = st.text_input("Notes")
submitted = st.form_submit_button("💾 Save", use_container_width=True, type="primary")
if submitted:
df_log = init_manual_log()
new_row = {
"date": str(log_date),
"nicotine_pouches": nicotine if nicotine > 0 else None,
"vape_puffs": vape_puffs if vape_puffs > 0 else None,
"caffeine_mg": caffeine if caffeine > 0 else None,
"weight_lbs": weight if weight > 0 else None,
"cpap_ahi": cpap_ahi if cpap_ahi > 0 else None,
"cpap_hours": cpap_hours if cpap_hours > 0 else None,
"cpap_flow_limit_95": cpap_flow_limit if cpap_flow_limit > 0 else None,
"notes": notes or None,
}
df_log = upsert_row(df_log, new_row)
save_manual_log(df_log)
st.success(f"Saved {log_date}")
st.cache_data.clear()
# ── Title ─────────────────────────────────────────────────────────────────────
st.title("🩺 Health Dashboard")
start_str = start_date.isoformat()
end_str = end_date.isoformat()
# ── Fetch Oura ────────────────────────────────────────────────────────────────
token = st.session_state.get("oura_token", "")
sleep_raw, readiness_raw, activity_raw = [], [], []
if token:
with st.spinner("Fetching Oura data…"):
sleep_raw = fetch_oura("daily_sleep", token, start_str, end_str)
readiness_raw = fetch_oura("daily_readiness", token, start_str, end_str)
activity_raw = fetch_oura("daily_activity", token, start_str, end_str)
else:
st.info("👈 Enter your Oura API token in the sidebar to load sleep, readiness, and activity data.")
df_sleep = oura_records_to_df(sleep_raw, ["score", "contributors"])
df_readiness = oura_records_to_df(readiness_raw, ["score", "contributors", "temperature_deviation"])
df_activity = oura_records_to_df(activity_raw, ["score", "steps", "active_calories", "equivalent_walking_distance"])
# ── Load manual data filtered to date range ───────────────────────────────────
df_all_manual = init_manual_log()
df_all_manual["date"] = pd.to_datetime(df_all_manual["date"], errors="coerce")
df_manual = df_all_manual[
(df_all_manual["date"] >= pd.Timestamp(start_date)) &
(df_all_manual["date"] <= pd.Timestamp(end_date))
].copy().sort_values("date").reset_index(drop=True)
for col in ["nicotine_pouches", "vape_puffs", "caffeine_mg", "weight_lbs", "cpap_ahi", "cpap_hours", "cpap_flow_limit_95"]:
df_manual[col] = pd.to_numeric(df_manual[col], errors="coerce")
# Forward-fill weight so gaps carry the last known value for charts
df_manual["weight_lbs"] = df_manual["weight_lbs"].ffill()
# ── Tabs ──────────────────────────────────────────────────────────────────────
(tab_overview, tab_sleep, tab_readiness,
tab_activity, tab_lifestyle, tab_cpap, tab_data) = st.tabs([
"📊 Overview", "😴 Sleep", "⚡ Readiness",
"🏃 Activity", "☕ Lifestyle", "😮💨 CPAP", "🗃️ Data",
])
# ══════════════════════════════════════════════════════════════════════════════
# OVERVIEW
# ══════════════════════════════════════════════════════════════════════════════
with tab_overview:
# ── Streaks ───────────────────────────────────────────────────────────────
streaks = load_streaks()
if streaks:
streak_cols = st.columns(len(streaks))
for col, s in zip(streak_cols, streaks):
start = date.fromisoformat(s["start_date"])
label, total_days = streak_duration(start)
emoji = s.get("emoji", "🔥")
with col:
st.markdown(
f"""<div style="background:linear-gradient(135deg,#1e1e2e,#2a2a3e);
border-radius:14px;padding:18px 20px;border:1px solid #3a3a5e;
text-align:center;margin-bottom:12px;">
<div style="font-size:1.6em;">{emoji}</div>
<div style="font-size:1.8em;font-weight:800;margin:4px 0;
background:linear-gradient(90deg,#4ade80,#60a5fa);
-webkit-background-clip:text;-webkit-text-fill-color:transparent;">
{total_days:,} days</div>
<div style="font-size:0.95em;color:#ccc;font-weight:600;">
{s['name']}</div>
<div style="font-size:0.8em;color:#888;margin-top:2px;">
{label} · since {start.strftime('%b %-d, %Y')}</div>
</div>""",
unsafe_allow_html=True,
)
st.subheader("Most Recent Values")
def safe_int(v):
try:
return int(float(v))
except Exception:
return None
def safe_float(v, decimals=1):
try:
return round(float(v), decimals)
except Exception:
return None
sleep_score = safe_int(latest_val(df_sleep, "score"))
readiness_score = safe_int(latest_val(df_readiness, "score"))
steps = safe_int(latest_val(df_activity, "steps"))
nicotine_latest = safe_int(latest_val(df_manual, "nicotine_pouches"))
vape_latest = safe_int(latest_val(df_manual, "vape_puffs"))
caffeine_latest = safe_int(latest_val(df_manual, "caffeine_mg"))
ahi_latest = safe_float(latest_val(df_manual, "cpap_ahi"))
weight_latest = safe_float(latest_val(df_manual, "weight_lbs"))
# Compute deltas (change from previous data point)
d_sleep = calc_delta(df_sleep, "score")
d_readiness = calc_delta(df_readiness, "score")
d_steps = calc_delta(df_activity, "steps")
d_nicotine = calc_delta(df_manual, "nicotine_pouches")
d_vape = calc_delta(df_manual, "vape_puffs")
d_caffeine = calc_delta(df_manual, "caffeine_mg")
d_ahi = calc_delta(df_manual, "cpap_ahi")
d_weight = calc_delta(df_manual, "weight_lbs")
m1, m2, m3, m4 = st.columns(4)
m5, m6, m7, m8 = st.columns(4)
m1.metric("😴 Sleep Score", sleep_score if sleep_score is not None else "—",
delta=d_sleep, delta_color="normal")
m2.metric("⚡ Readiness", readiness_score if readiness_score is not None else "—",
delta=d_readiness, delta_color="normal")
m3.metric("👟 Steps", f"{steps:,}" if steps is not None else "—",
delta=f"{d_steps:+,.0f}" if d_steps is not None else None, delta_color="normal")
m4.metric("⚖️ Weight", f"{weight_latest} lbs" if weight_latest is not None else "—",
delta=f"{d_weight:+.1f} lbs" if d_weight is not None else None, delta_color="off")
m5.metric("🫧 Pouches", f"{nicotine_latest}" if nicotine_latest is not None else "—",
delta=d_nicotine, delta_color="inverse")
m6.metric("💨 Vape puffs", f"{vape_latest}" if vape_latest is not None else "—",
delta=d_vape, delta_color="inverse")
m7.metric("☕ Caffeine", f"{caffeine_latest} mg" if caffeine_latest is not None else "—",
delta=f"{d_caffeine:+.0f} mg" if d_caffeine is not None else None, delta_color="inverse")
m8.metric("😮💨 CPAP AHI", f"{ahi_latest}" if ahi_latest is not None else "—",
delta=d_ahi, delta_color="inverse")
st.divider()
st.subheader(f"Trends — {start_date.strftime('%b %-d')} → {end_date.strftime('%b %-d, %Y')}")
r1c1, r1c2, r1c3 = st.columns(3)
r2c1, r2c2, r2c3, r2c4, r2c5 = st.columns(5)
with r1c1:
if not df_sleep.empty and "score" in df_sleep:
st.plotly_chart(line_chart(df_sleep, "date", "score", "Sleep Score",
"#818cf8", yrange=[0, 100]), use_container_width=True)
else:
st.caption("Sleep — no data")
with r1c2:
if not df_readiness.empty and "score" in df_readiness:
st.plotly_chart(line_chart(df_readiness, "date", "score", "Readiness Score",
"#4ade80", yrange=[0, 100]), use_container_width=True)
else:
st.caption("Readiness — no data")
with r1c3:
if not df_activity.empty and "steps" in df_activity:
st.plotly_chart(bar_chart(df_activity, "date", "steps", "Daily Steps",
"#f59e0b", "steps", hline=10000, hline_label="10k"), use_container_width=True)
else:
st.caption("Steps — no data")
with r2c1:
if not df_manual.empty and df_manual["nicotine_pouches"].notna().any():
st.plotly_chart(bar_chart(df_manual, "date", "nicotine_pouches", "Pouches",
"#f87171", "pouches/day"), use_container_width=True)
else:
st.caption("Pouches — no data logged")
with r2c2:
if not df_manual.empty and df_manual["vape_puffs"].notna().any():
st.plotly_chart(bar_chart(df_manual, "date", "vape_puffs", "Vape Puffs",
"#fb923c", "puffs/day"), use_container_width=True)
else:
st.caption("Vape — no data logged")
with r2c3:
if not df_manual.empty and df_manual["caffeine_mg"].notna().any():
st.plotly_chart(bar_chart(df_manual, "date", "caffeine_mg", "Caffeine",
"#fbbf24", "mg/day", hline=400, hline_label="400mg"), use_container_width=True)
else:
st.caption("Caffeine — no data logged")
with r2c4:
if not df_manual.empty and df_manual["weight_lbs"].notna().any():
st.plotly_chart(line_chart(df_manual, "date", "weight_lbs", "Weight",
"#a78bfa", "lbs"), use_container_width=True)
else:
st.caption("Weight — no data logged")
with r2c5:
if not df_manual.empty and df_manual["cpap_ahi"].notna().any():
st.plotly_chart(line_chart(df_manual, "date", "cpap_ahi", "CPAP AHI",
"#60a5fa", "events/hr"), use_container_width=True)
else:
st.caption("CPAP — no data logged")
# ── Correlations ─────────────────────────────────────────────────────────
if not df_manual.empty and not df_sleep.empty:
# Merge manual data with sleep scores on date
df_manual_dt = df_manual.copy()
df_sleep_dt = df_sleep[["date", "score"]].rename(columns={"score": "sleep_score"}).copy()
df_sleep_dt["sleep_score"] = pd.to_numeric(df_sleep_dt["sleep_score"], errors="coerce")
df_corr = pd.merge(df_manual_dt, df_sleep_dt, on="date", how="inner")
# Also merge readiness if available
if not df_readiness.empty:
df_read_dt = df_readiness[["date", "score"]].rename(columns={"score": "readiness_score"}).copy()
df_read_dt["readiness_score"] = pd.to_numeric(df_read_dt["readiness_score"], errors="coerce")
df_corr = pd.merge(df_corr, df_read_dt, on="date", how="left")
# Build list of correlations that have enough data
corr_charts = []
MIN_POINTS = 5
if "caffeine_mg" in df_corr.columns:
df_caf_sleep = df_corr[df_corr["caffeine_mg"].notna() & df_corr["sleep_score"].notna()]
if len(df_caf_sleep) >= MIN_POINTS:
corr_charts.append(("caffeine_mg", "sleep_score", "Caffeine vs Sleep Score",
"Caffeine (mg)", "Sleep Score", "#fbbf24", df_caf_sleep))
if "nicotine_pouches" in df_corr.columns:
df_nic_sleep = df_corr[df_corr["nicotine_pouches"].notna() & df_corr["sleep_score"].notna()]
if len(df_nic_sleep) >= MIN_POINTS:
corr_charts.append(("nicotine_pouches", "sleep_score", "Pouches vs Sleep Score",
"Pouches", "Sleep Score", "#f87171", df_nic_sleep))
if "readiness_score" in df_corr.columns and "caffeine_mg" in df_corr.columns:
df_caf_read = df_corr[df_corr["caffeine_mg"].notna() & df_corr["readiness_score"].notna()]
if len(df_caf_read) >= MIN_POINTS:
corr_charts.append(("caffeine_mg", "readiness_score", "Caffeine vs Readiness",
"Caffeine (mg)", "Readiness Score", "#4ade80", df_caf_read))
if corr_charts:
st.divider()
st.subheader("Correlations")
st.caption("Scatter plots showing relationships between your habits and Oura scores. "
"Trend lines help reveal patterns — but correlation isn't causation!")
corr_cols = st.columns(len(corr_charts))
for col, (x_col, y_col, title, x_label, y_label, color, df_plot) in zip(corr_cols, corr_charts):
with col:
fig_corr = px.scatter(
df_plot, x=x_col, y=y_col,
trendline="ols",
color_discrete_sequence=[color],
template="plotly_dark",
)
fig_corr.update_layout(
title=dict(text=title, font_size=14),
paper_bgcolor="rgba(0,0,0,0)", plot_bgcolor="rgba(0,0,0,0)",
margin=dict(l=0, r=0, t=36, b=0),
xaxis_title=x_label, yaxis_title=y_label,
showlegend=False,
)
fig_corr.update_traces(marker=dict(size=8, opacity=0.7))
st.plotly_chart(fig_corr, use_container_width=True)
# ══════════════════════════════════════════════════════════════════════════════
# SLEEP
# ══════════════════════════════════════════════════════════════════════════════
with tab_sleep:
if df_sleep.empty:
st.info("No sleep data — add your Oura API token in the sidebar.")
else:
# Score over time
fig = line_chart(df_sleep, "date", "score", "Sleep Score", "#818cf8", yrange=[0, 100])
score_bands(fig)
st.plotly_chart(fig, use_container_width=True)
# Contributors
contrib_map = {
"contributors_deep_sleep": "Deep Sleep",
"contributors_rem_sleep": "REM Sleep",
"contributors_sleep_efficiency": "Efficiency",
"contributors_restfulness": "Restfulness",
"contributors_sleep_latency": "Latency",
"contributors_sleep_timing": "Timing",
"contributors_total_sleep": "Total Sleep",
}
avail_contribs = [c for c in contrib_map if c in df_sleep.columns
and df_sleep[c].notna().any()]
if avail_contribs:
st.subheader("Sleep Contributors")
colors = px.colors.qualitative.Pastel
fig2 = go.Figure()
for i, col in enumerate(avail_contribs):
fig2.add_trace(go.Scatter(
x=df_sleep["date"], y=df_sleep[col],
name=contrib_map[col],
mode="lines+markers",
line=dict(color=colors[i % len(colors)], width=2),
))
fig2.update_layout(
template="plotly_dark",
paper_bgcolor="rgba(0,0,0,0)", plot_bgcolor="rgba(0,0,0,0)",
yaxis=dict(range=[0, 100], title="Contributor Score"),
xaxis_title="",
margin=dict(l=0, r=0, t=10, b=0),
legend=dict(orientation="h", yanchor="bottom", y=1.02, xanchor="left", x=0),
)
st.plotly_chart(fig2, use_container_width=True)
st.subheader("Raw Data")
disp = df_sleep.copy()
disp["date"] = disp["date"].dt.date
st.dataframe(disp.sort_values("date", ascending=False).set_index("date"),
use_container_width=True)
# ══════════════════════════════════════════════════════════════════════════════
# READINESS
# ══════════════════════════════════════════════════════════════════════════════
with tab_readiness:
if df_readiness.empty:
st.info("No readiness data — add your Oura API token in the sidebar.")
else:
fig = line_chart(df_readiness, "date", "score", "Readiness Score", "#4ade80", yrange=[0, 100])
score_bands(fig)
st.plotly_chart(fig, use_container_width=True)
# Temperature deviation
if "temperature_deviation" in df_readiness.columns and df_readiness["temperature_deviation"].notna().any():
st.subheader("Body Temperature Deviation")
df_temp = df_readiness[df_readiness["temperature_deviation"].notna()].copy()
df_temp["temperature_deviation"] = pd.to_numeric(df_temp["temperature_deviation"], errors="coerce")
fig_temp = px.bar(
df_temp, x="date", y="temperature_deviation",
color="temperature_deviation",
color_continuous_scale="RdBu_r",
color_continuous_midpoint=0,
template="plotly_dark",
)
fig_temp.update_layout(
paper_bgcolor="rgba(0,0,0,0)", plot_bgcolor="rgba(0,0,0,0)",
yaxis_title="°C from baseline", xaxis_title="",
margin=dict(l=0, r=0, t=10, b=0), coloraxis_showscale=False,
)
st.plotly_chart(fig_temp, use_container_width=True)
# Readiness contributors
contrib_map_r = {
"contributors_activity_balance": "Activity Balance",
"contributors_body_temperature": "Body Temp",
"contributors_hrv_balance": "HRV Balance",
"contributors_previous_day_activity": "Prev Day Activity",
"contributors_previous_night": "Previous Night",
"contributors_recovery_index": "Recovery Index",
"contributors_resting_heart_rate": "Resting HR",
"contributors_sleep_balance": "Sleep Balance",
}
avail_r = [c for c in contrib_map_r if c in df_readiness.columns
and df_readiness[c].notna().any()]
if avail_r:
st.subheader("Readiness Contributors")
colors = px.colors.qualitative.Pastel
fig_r = go.Figure()
for i, col in enumerate(avail_r):
fig_r.add_trace(go.Scatter(
x=df_readiness["date"], y=df_readiness[col],
name=contrib_map_r[col], mode="lines+markers",
line=dict(color=colors[i % len(colors)], width=2),
))
fig_r.update_layout(
template="plotly_dark",
paper_bgcolor="rgba(0,0,0,0)", plot_bgcolor="rgba(0,0,0,0)",
yaxis=dict(range=[0, 100], title="Contributor Score"),
xaxis_title="", margin=dict(l=0, r=0, t=10, b=0),
legend=dict(orientation="h", yanchor="bottom", y=1.02),
)
st.plotly_chart(fig_r, use_container_width=True)
st.subheader("Raw Data")
disp = df_readiness.copy()
disp["date"] = disp["date"].dt.date
st.dataframe(disp.sort_values("date", ascending=False).set_index("date"),
use_container_width=True)
# ══════════════════════════════════════════════════════════════════════════════
# ACTIVITY
# ══════════════════════════════════════════════════════════════════════════════
with tab_activity:
if df_activity.empty:
st.info("No activity data — add your Oura API token in the sidebar.")
else:
c1, c2 = st.columns(2)
with c1:
if "steps" in df_activity.columns:
df_act_steps = df_activity[pd.to_numeric(df_activity["steps"], errors="coerce").notna()].copy()
df_act_steps["steps"] = pd.to_numeric(df_act_steps["steps"])
fig_steps = bar_chart(df_act_steps, "date", "steps", "Daily Steps",
"#f59e0b", "steps", hline=10000, hline_label="10k goal")
st.plotly_chart(fig_steps, use_container_width=True)
with c2:
if "active_calories" in df_activity.columns:
df_cal = df_activity[pd.to_numeric(df_activity["active_calories"], errors="coerce").notna()].copy()
df_cal["active_calories"] = pd.to_numeric(df_cal["active_calories"])
fig_cal = bar_chart(df_cal, "date", "active_calories", "Active Calories",
"#f87171", "kcal")
st.plotly_chart(fig_cal, use_container_width=True)
if "score" in df_activity.columns:
df_activity["score"] = pd.to_numeric(df_activity["score"], errors="coerce")
fig_act_score = line_chart(df_activity, "date", "score", "Activity Score",
"#34d399", yrange=[0, 100])
score_bands(fig_act_score)
st.plotly_chart(fig_act_score, use_container_width=True)
st.subheader("Raw Data")
disp = df_activity.copy()
disp["date"] = disp["date"].dt.date
st.dataframe(disp.sort_values("date", ascending=False).set_index("date"),
use_container_width=True)
# ══════════════════════════════════════════════════════════════════════════════
# LIFESTYLE (Nicotine + Caffeine)
# ══════════════════════════════════════════════════════════════════════════════
with tab_lifestyle:
@st.fragment
def lifestyle_fragment():
# Local date range for Lifestyle tab
range_options = {"30 days": 30, "90 days": 90, "6 months": 180, "1 year": 365, "All time": None}
sel = st.radio("Date range", list(range_options.keys()), horizontal=True, index=0, key="lifestyle_range")
days_back = range_options[sel]
if days_back is not None:
ls_start = pd.Timestamp(date.today() - timedelta(days=days_back))
df_ls = df_all_manual[df_all_manual["date"] >= ls_start].copy()
else:
df_ls = df_all_manual.copy()
df_ls = df_ls.sort_values("date").reset_index(drop=True)
for col in ["nicotine_pouches", "vape_puffs", "caffeine_mg", "weight_lbs", "cpap_ahi", "cpap_hours", "cpap_flow_limit_95"]:
df_ls[col] = pd.to_numeric(df_ls[col], errors="coerce")
df_ls["weight_lbs"] = df_ls["weight_lbs"].ffill()
has_nic = not df_ls.empty and df_ls["nicotine_pouches"].notna().any()
has_vape = not df_ls.empty and df_ls["vape_puffs"].notna().any()
has_caf = not df_ls.empty and df_ls["caffeine_mg"].notna().any()
has_weight = not df_ls.empty and df_ls["weight_lbs"].notna().any()
if not has_nic and not has_vape and not has_caf and not has_weight:
st.info("No lifestyle data yet — use the sidebar form to log nicotine, caffeine, and weight.")
else:
c1, c2, c3 = st.columns(3)
with c1:
st.subheader("🫧 Pouches")
if has_nic:
df_nic = df_ls[df_ls["nicotine_pouches"].notna()]
st.plotly_chart(bar_chart(df_nic, "date", "nicotine_pouches",
"Pouches per Day", "#f87171", "pouches"),
use_container_width=True)
ma, mb = st.columns(2)
ma.metric("Avg / day", f"{df_nic['nicotine_pouches'].mean():.1f}")
mb.metric("Total", f"{int(df_nic['nicotine_pouches'].sum())}")
else:
st.caption("No data in this date range.")
with c2:
st.subheader("💨 Vape Puffs")
if has_vape:
df_vape = df_ls[df_ls["vape_puffs"].notna()]
st.plotly_chart(bar_chart(df_vape, "date", "vape_puffs",
"Puffs per Day", "#fb923c", "puffs"),
use_container_width=True)
ma, mb = st.columns(2)
ma.metric("Avg / day", f"{df_vape['vape_puffs'].mean():.0f}")
mb.metric("Total", f"{int(df_vape['vape_puffs'].sum())}")
else:
st.caption("No data in this date range.")
with c3:
st.subheader("☕ Caffeine")
if has_caf:
df_caf = df_ls[df_ls["caffeine_mg"].notna()]
st.plotly_chart(bar_chart(df_caf, "date", "caffeine_mg",
"Caffeine per Day", "#fbbf24", "mg",
hline=400, hline_label="400mg daily max"),
use_container_width=True)
ma, mb = st.columns(2)
ma.metric("Avg / day", f"{df_caf['caffeine_mg'].mean():.0f} mg")
mb.metric("Peak day", f"{df_caf['caffeine_mg'].max():.0f} mg")
else:
st.caption("No data in this date range.")
st.divider()
st.subheader("⚖️ Weight")
if has_weight:
df_wt = df_ls[df_ls["weight_lbs"].notna()]
st.plotly_chart(line_chart(df_wt, "date", "weight_lbs", "Weight Over Time",
"#a78bfa", "lbs"), use_container_width=True)
ma, mb, mc = st.columns(3)
ma.metric("Current", f"{df_wt['weight_lbs'].iloc[-1]:.1f} lbs")
mb.metric("Avg", f"{df_wt['weight_lbs'].mean():.1f} lbs")
mc.metric("Range", f"{df_wt['weight_lbs'].min():.1f} – {df_wt['weight_lbs'].max():.1f} lbs")
else:
st.caption("No weight data in this date range.")
lifestyle_fragment()
# ══════════════════════════════════════════════════════════════════════════════
# CPAP
# ══════════════════════════════════════════════════════════════════════════════
with tab_cpap:
st.subheader("😮💨 CPAP Data")
@st.fragment
def oscar_import_fragment():
with st.expander("📂 Import from OSCAR CSV export"):
st.markdown(
"In OSCAR: open a session → **File → Export → Daily Summary CSV**. "
"Then upload that file here."
)
uploaded = st.file_uploader("Upload OSCAR daily summary CSV", type=["csv"],
key="oscar_upload")
if uploaded:
try:
df_oscar = pd.read_csv(uploaded)
st.write("**Preview (first 5 rows):**")
st.dataframe(df_oscar.head())
all_cols = ["(skip)"] + list(df_oscar.columns)
def best_match(keywords):
for kw in keywords:
for i, c in enumerate(all_cols):
if kw in c.lower():
return i
return 0
col_date = st.selectbox("Date column", all_cols,
index=best_match(["date", "day"]))
col_ahi = st.selectbox("AHI column", all_cols,
index=best_match(["ahi"]))
col_hours = st.selectbox("Total time / Usage hours column", all_cols,
index=best_match(["total time", "hour", "duration", "usage"]))
col_flow = st.selectbox("95% Flow Limit column", all_cols,
index=best_match(["95% flow", "flow limit"]))
if st.button("⬆️ Import OSCAR Data", type="primary"):
df_log = init_manual_log()
imported = 0
for _, row in df_oscar.iterrows():
if col_date == "(skip)":
continue
try:
entry_date = str(pd.Timestamp(row[col_date]).date())
except Exception:
continue
updates: dict = {"date": entry_date}
if col_ahi != "(skip)":
updates["cpap_ahi"] = row.get(col_ahi)
if col_hours != "(skip)":
updates["cpap_hours"] = parse_duration_hours(row.get(col_hours))
if col_flow != "(skip)":
updates["cpap_flow_limit_95"] = row.get(col_flow)
df_log = upsert_row(df_log, updates)
imported += 1
save_manual_log(df_log)
st.success(f"Imported {imported} OSCAR records!")
st.cache_data.clear()
st.rerun()
except Exception as e:
st.error(f"Error reading file: {e}")
oscar_import_fragment()
# Charts
df_cpap = df_manual[
df_manual["cpap_ahi"].notna() |
df_manual["cpap_hours"].notna() |
df_manual["cpap_flow_limit_95"].notna()
]
if df_cpap.empty:
st.info("No CPAP data yet. Import from OSCAR above or log entries via the sidebar.")
else:
c1, c2 = st.columns(2)
with c1:
st.subheader("AHI Over Time")
df_ahi = df_cpap[df_cpap["cpap_ahi"].notna()]
if not df_ahi.empty:
fig_ahi = px.line(df_ahi, x="date", y="cpap_ahi", markers=True,
color_discrete_sequence=["#60a5fa"], template="plotly_dark")
fig_ahi.add_hrect(y0=0, y1=5, fillcolor="#22c55e", opacity=0.07, line_width=0,
annotation_text="Normal (<5)", annotation_position="top right")
fig_ahi.add_hrect(y0=5, y1=15, fillcolor="#eab308", opacity=0.07, line_width=0,
annotation_text="Mild (5–15)", annotation_position="bottom right")
fig_ahi.add_hrect(y0=15, y1=30, fillcolor="#ef4444", opacity=0.07, line_width=0)
fig_ahi.update_layout(
paper_bgcolor="rgba(0,0,0,0)", plot_bgcolor="rgba(0,0,0,0)",
margin=dict(l=0, r=0, t=10, b=0),
yaxis_title="Events/hr", xaxis_title="",
)
st.plotly_chart(fig_ahi, use_container_width=True)
avg_ahi = df_ahi["cpap_ahi"].mean()
st.metric("Average AHI", f"{avg_ahi:.2f}", help="Lower is better. Goal: <5")
with c2:
st.subheader("Usage Hours")
df_hrs = df_cpap[df_cpap["cpap_hours"].notna()]
if not df_hrs.empty:
fig_hrs = bar_chart(df_hrs, "date", "cpap_hours", "Usage per Night",
"#818cf8", "hours", hline=4, hline_label="4hr minimum")
st.plotly_chart(fig_hrs, use_container_width=True)
avg_hrs = df_hrs["cpap_hours"].mean()
st.metric("Average hours/night", f"{avg_hrs:.1f}")
if df_cpap["cpap_flow_limit_95"].notna().any():
st.subheader("95% Flow Limitation")
df_fl = df_cpap[df_cpap["cpap_flow_limit_95"].notna()]
fig_fl = line_chart(df_fl, "date", "cpap_flow_limit_95",
"95% Flow Limitation", "#a78bfa", "")
st.plotly_chart(fig_fl, use_container_width=True)
# ══════════════════════════════════════════════════════════════════════════════
# RAW DATA
# ══════════════════════════════════════════════════════════════════════════════
with tab_data:
st.subheader("Manual Log — All Entries")
@st.fragment