Inspiration
Most sleep apps answer the wrong question. They tell you how long you were in bed or draw a generic sleep-stage chart, leaving you to guess what any of it means for how you will actually function this morning.
Scientific research on chronic sleep restriction exposes a dangerous readiness gap: after several short nights, people subjectively adapt to feeling tired even while their reaction speed and cognitive vigilance continue to degrade. That dissociation isn't just a classroom problem where 84% of U.S. 12th graders report insufficient sleep; it is a real-world safety crisis affecting 61.8% of night-shift workers and contributing to 644 U.S. drowsy-driving fatalities in 2024.
We kept coming back to a sharper question: "How well am I functioning right now, compared to my own rested baseline?"
Existing tools either require expensive wearables, reduce sleep to duration alone, or ship sensitive biometric data to the cloud. We wanted an offline-first, smartphone-only system that measures real-time functional readiness, quantifies its own uncertainty, and keeps the most sensitive signal your face strictly on-device.
That became Somno: personalised readiness intelligence from the phone already in your pocket.
What It Does
A Somno check-in takes ~30 seconds and fuses four validated evidence streams into a single, interpretable Sleep Deprivation Index (SDI) from 0 to 100:
- Objective Psychomotor Vigilance (PVT Probe): A short, mobile-adapted reaction-time task measuring response speed, lapses, false starts, and trial-to-trial variability.
- On-Device Ocular & Facial Cues: A 6-second Google ML Kit face scan extracting eyelid closure, blink dynamics, and geometric fatigue cues locally without ever storing or uploading a single image frame.
- Subjective State (Karolinska Sleepiness Scale): A rapid
1-9self-report rating to capture perceived alertness. - Bounded Sleep-Debt Ledger: Tracks recent sleep shortfall and recovery across three distinct physiological components Wake, NREM, and REM debt because different sleep stages accumulate and repay at different rates.
From Score to Action
- Explainable SDI + Confidence Score: Rather than giving you a black-box number, Somno displays which signals drove today's score, how you compare to your personal baseline, and an honest confidence badge reflecting data quality.
- Baseline-Safe Smart Wake Alarm: Carries readiness logic directly into your morning alarm, allowing snoozes only when physiological evidence remains within safe bounds and your hard wake deadline stays feasible.
- Actionable Recovery Guidance: Translates accumulated sleep debt into realistic nightly bedtime targets and multi-day recovery curves.
- Offline-First & Zero-Account Required: Core inference runs 100% locally with no login required; optional cloud sync exists solely to preserve history across devices.
How We Built It
Somno is engineered as a modular, local-first Android application spanning 21,000+ lines of Kotlin and TypeScript, 42 screens, and 8 inference engines:
[4 Input Signals] -> [Quality Gates] -> [Personal Baseline] -> [Quality-Weighted Fusion] -> [SDI + Confidence + Smart Wake]
(PVT, Face, KSS, (Reject dark scans, (Compare me-to-me (Renormalise missing (Plain-language breakdown &
Sleep Ledger) motion, partial runs) z-scores) inputs; never fake 0s) safe alarm control)
- Application & State Layer: Built with React Native, Expo, and TypeScript, using Zustand for deterministic local state management and React Navigation for multi-step check-in and recovery flows.
- On-Device Computer Vision: Powered by Expo Camera and Google ML Kit, extracting temporal, geometric, and photometric ocular features transiently in memory.
- Native Android Alarm Module (Kotlin): Custom native bridge handling exact alarm scheduling, full-screen wake UI, audio/vibration lifecycles, snooze gating, process-death recovery, and device reboot re-arming.
- Local-First Storage & Sync: AsyncStorage for instant offline persistence, paired with optional Supabase (Auth + PostgreSQL) sync featuring deterministic merge rules, stable record IDs, and deletion tombstones.
- Verification & CI/CD: Automated test harnesses covering PVT scoring, sleep-debt dynamics, facial quality gating, sync conflict resolution, and end-to-end UI journeys, enforced via GitHub Actions, EAS, and Gradle.
The Math Behind the Score
Instead of an opaque neural network that cannot explain why it flagged a user as impaired, Somno uses a within-person standardised, quality-weighted linear fusion model. Each valid signal (i \in S) is transformed into a personal z-score (z_i) relative to the user's own rested baseline:
$$ \text{SDI} = \operatorname{clamp}!\left(50 + 10 \sum_{i \in S} \tilde{w}i z_i,\; 0,\; 100\right), \qquad \tilde{w}_i = \frac{w_i q_i}{\sum{j \in S} w_j q_j} $$
- Evidence-Grounded Base Weights: (w_{\text{PVT}} = 0.40), (w_{\text{face}} = 0.25), (w_{\text{debt}} = 0.20), and (w_{\text{KSS}} = 0.15). Subjective sleepiness carries the lowest weight because self-report systematically plateaus under chronic sleep restriction.
- Missing-Signal Invariance: When a user skips the camera scan or has poor lighting, (S) shrinks and the remaining weights (\tilde{w}_i) dynamically renormalise. Somno never substitutes a zero for missing evidence, and automatically lowers the output confidence score.
- Precision Weighting ((q_i)): Objective channels carry a quality term (q_i \in [0, 1])—scaling PVT precision by completed trial count and discounting facial scores when lighting or head motion degrades landmark confidence.
- Bounded Sleep-Debt Term: Sleep debt is mapped via a lower-bounded transform:
$$ z_{\text{debt}} = \max!\left(-3,\; -\frac{\text{debt}_{\text{hours}}}{2}\right) $$
Without this bound, severe multi-night debt could reach (-12\sigma) and mathematically pin the SDI, rendering morning reaction and ocular measurements irrelevant. Clamping preserves sleep debt as one calibrated voice among four.
Validation & Engineering Verification
Before shipping Somno to real users, we validated both our scientific assumptions and our software reliability:
- Empirical Sleep-Restriction Analysis: Tested across 180 repeated observations from 18 sleep-restricted participants. Personal baseline referencing improved impairment discrimination from an ROC AUC of (0.843) to (0.899) ((+6.67\%) relative gain). By Day 9 of restriction, average reaction time slowed by (+88.7\text{ ms}) ((p = 2.9 \times 10^{-5}))—a deficit 17 of 18 participants exhibited even as subjective sleepiness levelled off.
- Property-Based Stress Testing: Generated 250,000 randomised app states across combinations of missing sensors, partial tasks, and edge-case debt histories, executing 2,000,000 automated property checks (testing SDI bounds, monotonicity, missing-input invariance, and Smart Wake safety) with 0 observed violations across 21/21 passing test suites.
- Real-World School Pilot: Deployed Somno in a 2-week pilot with 160 students across 3 schools (alongside a sleep-health workshop reaching 100 students), achieving a 4.7 / 5 user satisfaction score and shifting self-reported bedtimes ~20 minutes earlier.
Challenges We Ran Into
- Handling Imperfect Real-World Inputs Without Faking Certainty: In real life, people check in from dark bedrooms, move during face scans, or rush through short alarm tests. Early iterations treated weak inputs as normal values. We redesigned the inference pipeline around hard quality gates, precision-adjusted renormalisation, and fail-closed confidence reporting.
- Surviving Android Background & Alarm Restrictions: Android Doze mode, OEM battery savers, process death, and device reboots routinely kill JavaScript timers. We engineered a dedicated native Kotlin alarm module with explicit permission flows and boot-time re-arming so morning wake-ups remain rock-solid.
- Balancing Strict Privacy with Optional Cloud Sync: Keeping raw camera frames strictly transient on-device solved biometric privacy, while supporting optional cross-device history required deterministic merge rules and deletion tombstones in Supabase so offline edits never resurrect deleted records.
- Designing Responsible Non-Medical Guardrails: Somno is a personal wellness and readiness tool-not a clinical diagnostic device. Keeping UI copy, uncertainty intervals, and Smart Wake limits strictly aligned with what on-device signals can prove was a core engineering constraint.
What We Learned
- Personal baselines beat population averages: Judging a user against their own rested self turns noisy smartphone sensors into high-signal readiness indicators.
- Quantifying uncertainty builds trust: Showing when evidence is weak- and refusing to guess when sensors fail—makes an AI health tool dramatically more credible than false precision.
- Local-first architecture is a superpower: Running ML Kit and inference engines offline eliminates latency, server costs, and biometric privacy risks from day one.
What's Next
- Expanded Validation & High-Risk Cohorts: Partnering with collegiate athletics teams and shift-work organisations to validate Somno against laboratory alertness benchmarks.
- Adaptive Circadian & Recovery Modelling: Incorporating chronotype and irregular shift schedules into multi-day recovery forecasts.
- Broader OEM Hardware Support: Expanding native Smart Wake battery-optimisation guides across diverse Android manufacturers.
Built With
- android
- edge-ai
- expo.io
- github-actions
- google-ml-kit
- gradle
- health-tech
- kotlin
- on-device-ml
- postgresql
- react-native
- supabase
- typescript
- zustand