"""Turning the event log into answers: when did she last eat, how much did she sleep, what does a typical day look like. All computed in Python from a few hundred rows, so it works the same on SQLite and Postgres.""" from collections import Counter from dataclasses import dataclass, field from datetime import date, datetime, timedelta from statistics import mean, median from zoneinfo import ZoneInfo from sqlalchemy import select from sqlalchemy.orm import Session from ..config import get_settings from ..models import Device, Event, Kind, Profile from ..timeutil import Formatter, fmt_duration, local_day_bounds, local_today, safe_zone, utcnow from .catalog import CATEGORIES, NURSE_SIDES, battery_percent from .events import effective_end, events_between, is_stale, live, open_sessions, recent_events # Feeding presses this close together are one feed (left side, then right side). FEED_GAP = timedelta(minutes=30) # ---------------------------------------------------------------- feeds @dataclass class Feed: events: list[Event] @property def start(self) -> datetime: return self.events[0].started_at @property def sides(self) -> list[str]: return [NURSE_SIDES[e.kind_slug] for e in self.events if e.kind_slug in NURSE_SIDES] @property def label(self) -> str: parts: list[str] = [] sides = self.sides if sides: parts.append("Nursing " + " → ".join(_dedupe_runs(sides))) for e in self.events: if e.kind_slug not in NURSE_SIDES and e.kind.label not in parts: parts.append(e.kind.label) return " + ".join(parts) def _dedupe_runs(items: list[str]) -> list[str]: out: list[str] = [] for it in items: if not out or out[-1] != it: out.append(it) return out def group_feeds(events: list[Event]) -> list[Feed]: """Group feeding events into feeds: a new feed starts after a FEED_GAP pause.""" feeds: list[Feed] = [] last: Event | None = None for ev in sorted((e for e in events if e.kind.category == "feeding"), key=lambda e: e.started_at): if last is None or ev.started_at - last.started_at > FEED_GAP: feeds.append(Feed([ev])) else: feeds[-1].events.append(ev) last = ev return feeds def next_side(feeds: list[Feed]) -> str | None: """Suggest the breast to start on: the opposite of the last nursing feed's first side.""" for feed in reversed(feeds): if feed.sides: return "R" if feed.sides[0] == "L" else "L" return None # ---------------------------------------------------------------- per-day stats @dataclass class DayStats: day: date feeds: int = 0 wet: int = 0 dirty: int = 0 pump: int = 0 sleep_min: float = 0.0 longest_sleep_min: float = 0.0 naps: int = 0 counts: Counter = field(default_factory=Counter) has_data: bool = False @property def sleep_h(self) -> float: return self.sleep_min / 60 def _days(first: date, last: date) -> list[date]: return [first + timedelta(days=i) for i in range((last - first).days + 1)] def daily_stats(db: Session, tz: ZoneInfo, first: date, last: date, now: datetime | None = None) -> list[DayStats]: now = now or utcnow() start, _ = local_day_bounds(first, tz) _, end = local_day_bounds(last, tz) events = events_between(db, start - FEED_GAP, end) stats = {d: DayStats(d) for d in _days(first, last)} for feed in group_feeds(events): d = feed.start.astimezone(tz).date() if d in stats: stats[d].feeds += 1 for ev in events: start_day = ev.started_at.astimezone(tz).date() if start_day in stats: stats[start_day].has_data = True stats[start_day].counts[ev.kind_slug] += 1 if ev.kind.is_duration: s, e = ev.started_at, effective_end(ev, now) minutes = (e - s).total_seconds() / 60 if ev.kind.category == "sleep": if start_day in stats: stats[start_day].naps += 1 stats[start_day].longest_sleep_min = max(stats[start_day].longest_sleep_min, minutes) # A night's sleep counts towards each day it covers. for d in _days(max(first, start_day), min(last, e.astimezone(tz).date())): d0, d1 = local_day_bounds(d, tz) overlap = (min(e, d1) - max(s, d0)).total_seconds() / 60 if overlap > 0: stats[d].sleep_min += overlap stats[d].has_data = True elif start_day in stats: ds = stats[start_day] if ev.kind_slug == "wet": ds.wet += 1 elif ev.kind_slug == "dirty": ds.dirty += 1 elif ev.kind.category == "pump": ds.pump += 1 return [stats[d] for d in sorted(stats)] def averages(days: list[DayStats]) -> dict[str, float | None]: """Mean per day over the days that have any data (so the days before the device arrived don't drag the averages down).""" with_data = [d for d in days if d.has_data] if not with_data: return {"feeds": None, "sleep_min": None, "wet": None, "dirty": None, "days": 0} return { "feeds": mean(d.feeds for d in with_data), "sleep_min": mean(d.sleep_min for d in with_data), "wet": mean(d.wet for d in with_data), "dirty": mean(d.dirty for d in with_data), "days": len(with_data), } def feed_intervals(feeds: list[Feed]) -> list[float]: """Minutes between the starts of consecutive feeds (gaps over 12 h are ignored: those are missing data, not a real interval).""" gaps = [(b.start - a.start).total_seconds() / 60 for a, b in zip(feeds, feeds[1:])] return [g for g in gaps if g <= 12 * 60] # ---------------------------------------------------------------- rhythm chart @dataclass class Mark: cat: str # sleep | feeding | diaper | other shape: str # bar | dot | diamond | ring | tick left: float # % across the day width: float = 0.0 tip: str = "" open: bool = False @dataclass class RhythmRow: day: date marks: list[Mark] now_pct: float | None = None RHYTHM_CATS = {"sleep", "feeding", "diaper"} # everything else is drawn as grey "other" def rhythm(db: Session, tz: ZoneInfo, f: Formatter, first: date, last: date, now: datetime | None = None) -> list[RhythmRow]: """One row per day (newest first): sleep as bars, feeds as dots, diapers as diamonds.""" now = now or utcnow() start, _ = local_day_bounds(first, tz) _, end = local_day_bounds(last, tz) events = events_between(db, start - FEED_GAP, end) rows = [] for d in reversed(_days(first, last)): d0, d1 = local_day_bounds(d, tz) span = (d1 - d0).total_seconds() # 23 or 25 h on DST days def pct(t: datetime) -> float: return max(0.0, min(100.0, (t - d0).total_seconds() / span * 100)) marks: list[Mark] = [] for ev in events: cat = ev.kind.category if ev.kind.is_duration: s, e = ev.started_at, effective_end(ev, now) if e <= d0 or s >= d1: continue dur = fmt_duration((e - s).total_seconds()) tip = f"{ev.kind.emoji} {ev.kind.label} · {f.time(s)}–{f.time(e) if ev.ended_at else 'now'} · {dur}" marks.append( Mark( cat=cat if cat == "sleep" else "other", shape="bar", left=pct(s), width=max(0.4, pct(e) - pct(s)), tip=tip, open=ev.ended_at is None, ) ) elif d0 <= ev.started_at < d1 and cat != "feeding": shape = "tick" if cat == "diaper": shape = "diamond" if ev.kind_slug == "dirty" else "ring" marks.append( Mark( cat=cat if cat in RHYTHM_CATS else "other", shape=shape, left=pct(ev.started_at), tip=f"{ev.kind.emoji} {ev.kind.label} · {f.time(ev.started_at)}", ) ) for feed in group_feeds(events): if d0 <= feed.start < d1: marks.append( Mark( cat="feeding", shape="dot", left=pct(feed.start), tip=f"{feed.events[0].kind.emoji} {feed.label} · {f.time(feed.start)}", ) ) # Bars first so dots and diamonds sit on top of them. marks.sort(key=lambda m: (m.shape != "bar", m.left)) rows.append(RhythmRow(day=d, marks=marks, now_pct=pct(now) if d0 <= now < d1 else None)) return rows # ---------------------------------------------------------------- the "Today" summary @dataclass class Alert: level: str # info | warning | serious text: str href: str | None = None link_text: str | None = None @dataclass class Summary: now: datetime tz: ZoneInfo last_feed: Feed | None next_side: str | None last_diaper: Event | None last_sleep: Event | None open: list[Event] today: DayStats avg: dict[str, float | None] feed_interval_min: float | None recent: list[Event] device: Device | None alerts: list[Alert] @property def sleeping(self) -> Event | None: return next((e for e in self.open if e.kind.category == "sleep" and not is_stale(e, self.now)), None) def latest_in_category(db: Session, category: str, limit: int = 1) -> list[Event]: q = ( select(Event) .join(Event.kind) .where(live(), Kind.category == category) .order_by(Event.started_at.desc()) .limit(limit) ) return list(db.scalars(q)) def build_summary(db: Session, profile: Profile, now: datetime | None = None) -> Summary: now = now or utcnow() tz = safe_zone(profile.timezone) today = local_today(tz, now) recent_feeding = list(reversed(latest_in_category(db, "feeding", limit=40))) feeds = group_feeds(recent_feeding) diapers = latest_in_category(db, "diaper") sleeps = latest_in_category(db, "sleep") week = daily_stats(db, tz, today - timedelta(days=7), today, now) feeds_7d = [f for f in feeds if f.start >= now - timedelta(days=7)] intervals = feed_intervals(feeds_7d) devices = list(db.scalars(select(Device).where(Device.revoked_at.is_(None)))) devices.sort(key=lambda d: d.last_seen_at or d.created_at, reverse=True) opens = open_sessions(db) return Summary( now=now, tz=tz, last_feed=feeds[-1] if feeds else None, next_side=next_side(feeds), last_diaper=diapers[0] if diapers else None, last_sleep=sleeps[0] if sleeps else None, open=opens, today=week[-1], avg=averages(week[:-1]), feed_interval_min=median(intervals) if intervals else None, recent=recent_events(db, 8), device=devices[0] if devices else None, alerts=build_alerts(devices, opens, profile, now), ) def build_alerts(devices: list[Device], opens: list[Event], profile: Profile, now: datetime) -> list[Alert]: f = Formatter(safe_zone(profile.timezone), profile.clock_24h) alerts: list[Alert] = [] settings = get_settings() if settings.is_production and not settings.login_required: alerts.append(Alert("serious", "This dashboard has no password. Set DASHBOARD_PASSWORD on your host.")) for ev in opens: if is_stale(ev, now): alerts.append( Alert( "warning", f"{ev.kind.label} started {f.when(ev.started_at)} was never stopped.", href=f"/events/{ev.id}", link_text="Fix the end time", ) ) if not devices: alerts.append(Alert("info", "No Mamadachi is connected yet.", href="/device", link_text="Add a device")) for dev in devices: if dev.last_seen_at is None: alerts.append(Alert("info", f"{dev.name} hasn't synced yet.", href="/device", link_text="Setup steps")) continue silent = now - dev.last_seen_at if silent > timedelta(hours=max(24, 3 * profile.sync_interval_min / 60)): alerts.append( Alert( "warning", f"{dev.name} last synced {f.ago(dev.last_seen_at, now)}. Presses since then are still on the device.", href="/device", link_text="Device details", ) ) pct = battery_percent(dev.battery_mv) if pct is not None and not dev.charging and pct <= 20: alerts.append( Alert( "serious" if pct <= 10 else "warning", f"{dev.name} battery is at {pct}%. Charge it over USB-C.", ) ) if dev.clock_skew_s is not None and abs(dev.clock_skew_s) > 120: alerts.append( Alert( "info", f"{dev.name}'s clock was {fmt_duration(abs(dev.clock_skew_s))} off at its last sync; " "its event times were corrected.", ) ) return alerts def category_label(cat: str) -> str: return CATEGORIES.get(cat, cat.title())