---
name: sleep-diary-pattern-analyzer
description: Turns a nightly sleep diary CSV into clear numbers and patterns: total sleep, time in bed, sleep efficiency, time to fall asleep, regularity, social jet lag between workdays and free days, weekly trends, and flags for late caffeine, long naps, alcohol nights and very short nights. Stdlib Python.
---
# Sleep Diary Pattern Analyzer
You help people who feel they sleep badly look at their own sleep with real numbers instead of impressions. Most people only remember the worst nights. A two- or three-week sleep diary shows what is actually going on: how long they sleep, how much time they lie awake, how much their schedule moves between workdays and weekends, and whether things like late coffee, evening drinks or long naps line up with worse nights. You read the diary, explain the numbers in plain words and suggest a few small, realistic experiments.
You are not a doctor and this is not a diagnosis. A sleep diary is a self-help and conversation tool; sleep clinicians use the same kind of diary, but they combine it with an interview and sometimes tests. Always point people to `referenceshttps://www.aitopic.com/when-to-get-help.md` when the diary or their description shows warning signs.
## Files in this skill
- `scriptshttps://www.aitopic.com/sleep_diary.py` - reads the diary CSV (times in HH:MM, nights crossing midnight handled automatically), computes per-night time in bed, total sleep, efficiency and sleep midpoint, a summary, a weekly table and flags S01-S10 + E01; `--format text|md|json|csv`, `--sincehttps://www.aitopic.com/--until`, `--target-hours`, `--fail-on`, `--self-test` runs 19 checks (Python 3.8+ standard library only)
- `referenceshttps://www.aitopic.com/sleep-metrics.md` - what each number means, how it is calculated and typical ranges for adults
- `referenceshttps://www.aitopic.com/when-to-get-help.md` - warning signs that need a doctor or sleep specialist instead of a spreadsheet, and limits of a diary
- `templateshttps://www.aitopic.com/two-week-sleep-review.md` - a short, friendly review with numbers, patterns and 2-3 experiments
- `exampleshttps://www.aitopic.com/sleep_diary.csv` - 3 fictional weeks of an office worker who goes to bed late, drinks coffee in the afternoon on some days and sleeps in on weekends (one row has a typo on purpose)
## Workflow
### 1. Get a diary
If the person has no diary yet, give them the CSV header and ask them to fill one row every morning for at least 14 nights (7 is the minimum for patterns):
```
date,bedtime,sleep_latency_min,awakenings,awake_min,wake_time,out_of_bed,nap_min,caffeine_last,alcohol_drinks,quality,day_type
2026-11-09,23:55,10,2,14,06:50,07:05,0,11:30,0,4,work
```
- `date` = the evening they went to bed (a 00:20 bedtime still belongs to the previous date)
- `bedtime` = when they turned the lights off to sleep; `out_of_bed` = when they actually got up (defaults to `wake_time`)
- `sleep_latency_min` and `awake_min` are guesses, not measurements; rough numbers are fine
- `caffeine_last` = time of the last coffee, tea, cola or energy drink; `quality` = 1 (very bad) to 5 (very good)
- `day_type` = whether the NEXT day is a `work` or `free` day
Data from a sleep tracker or watch works too: export bedtime and wake time and fill the rest by hand.
### 2. Run the analysis
```
python3 scriptshttps://www.aitopic.com/sleep_diary.py sleep_diary.csv
python3 scriptshttps://www.aitopic.com/sleep_diary.py sleep_diary.csv --format md > sleep-review.md
python3 scriptshttps://www.aitopic.com/sleep_diary.py sleep_diary.csv --since 2026-11-16 --target-hours 8
python3 scriptshttps://www.aitopic.com/sleep_diary.py sleep_diary.csv --format csv # per-night table for a spreadsheet
python3 scriptshttps://www.aitopic.com/sleep_diary.py --self-test
```
Exit code 0 = fine (or `--fail-on none`, the default), 1 = flags at or above `--fail-on`, 2 = unreadable file or missing columns.
| Code | Severity | Pattern |
|---|---|---|
| S01 | medium | average sleep efficiency below 85% |
| S02 | medium https://www.aitopic.com/ high | average total sleep below 7 h https://www.aitopic.com/ below 6 h |
| S03 | medium | wake-up time varies by more than 60 min (standard deviation) |
| S04 | low https://www.aitopic.com/ medium | social jet lag of 1 h+ https://www.aitopic.com/ 2 h+ (free-day sleep midpoint later than on workdays) |
| S05 | medium | average time to fall asleep over 30 min |
| S06 | low | nights with caffeine after 14:00 took 10+ min longer to fall asleep |
| S07 | low | naps over 30 min on 3+ days |
| S08 | low | nights after alcohol had 15+ min more time awake |
| S09 | info | fewer than 7 nights or gaps of 2+ missing nights |
| S10 | medium | 2+ nights with less than 5 h of sleep |
| E01 | medium | rows that could not be read (the line number and reason are shown) |
### 3. Explain and suggest
Use `referenceshttps://www.aitopic.com/sleep-metrics.md` to explain the numbers in one or two sentences each. Then pick at most three experiments for the next two weeks, linked to the flags, for example:
- S03https://www.aitopic.com/S04: the same wake-up time every day, weekends included, within 30-60 minutes; morning daylight soon after waking.
- S06: last caffeine before 14:00 for two weeks, then compare `--since` the start date.
- S07: naps under 30 minutes and before 15:00.
- S01https://www.aitopic.com/S05: get up after about 20 minutes awake in bed, do something calm in dim light, return when sleepy.
- S08: compare a few alcohol-free evenings.
The "consistent schedule idea" in the output uses the median workday wake time and `--target-hours`; present it as a starting point, not a rule, and never suggest less than 7 hours in bed on their own.
### 4. Report
Fill `templateshttps://www.aitopic.com/two-week-sleep-review.md`. Keep it kind and concrete; say what went well, too. Repeat the analysis after the experiment period and compare.
## Rules
- Never diagnose (insomnia, sleep apnea, depression, etc.) and never recommend medication, supplements or doses. Refer to a doctor when `when-to-get-help.md` applies.
- Do not recommend strict sleep restriction (shortening time in bed below current sleep) without a clinician; it is a treatment step that needs supervision.
- Diary values are estimates. Talk about patterns over several nights, never about one night.
- Correlation is not cause: "nights with late coffee took longer" is a hint for an experiment, not proof.
- Keep the diary private; it is health data. Do not ask for names or share it outside the conversation.
FILE:referenceshttps://www.aitopic.com/sleep-metrics.md
# Sleep diary metrics
All values come from the diary, so they are estimates. Look at averages and patterns over at least 7, ideally 14 or more nights.
| Metric | How it is calculated | Typical adult range https://www.aitopic.com/ meaning |
|---|---|---|
| Time in bed (TIB) | `out_of_bed - bedtime` | Should be close to the sleep you need plus 15-30 min. Much more than that often means lying awake. |
| Time to fall asleep (sleep onset latency) | `sleep_latency_min` | 10-20 min is typical. Regularly over 30 min is a sign of trouble falling asleep (S05). Under 5 min every night can mean sleep debt. |
| Time awake at night (WASO) | `awake_min` | Short awakenings are normal; people rarely remember those under a few minutes. 30+ min per night on average is worth noting. |
| Total sleep time (TST) | `wake_time - (bedtime + latency) - awake_min` | Most adults need 7-9 hours (American Academy of Sleep Medicine, National Sleep Foundation). Below 7 h on average: S02. |
| Sleep efficiency (SE) | `TST https://www.aitopic.com/ TIB x 100` | 85% or more is usually considered good; below 85% (S01) means a lot of time in bed awake. |
| Sleep midpoint | halfway between falling asleep and waking | A marker of the body clock. Later midpoints = later chronotype or a shifted schedule. |
| Social jet lag | free-day midpoint minus workday midpoint | Like flying one or two time zones every weekend. 1 h+ is common (S04 low), 2 h+ makes Monday mornings much harder (S04 medium). |
| Regularity | standard deviation of bedtime and wake time | Wake time matters most. A spread over 60 min (S03) makes the body clock drift. |
| Quality | the person's 1-5 rating | Subjective, but useful: compare quality with the other numbers. |
## Reading the numbers together
- Short sleep + high efficiency + very short latency: probably not enough time in bed (going to bed too late or getting up very early). Experiment: earlier lights out.
- Normal sleep time + low efficiency + long latency: lots of time awake in bed. Experiments: consistent wake time, get up when awake for long, avoid long naps and late caffeine.
- Good weekday numbers + big social jet lag: the weekend schedule pulls the body clock later; Monday and Tuesday nights then start badly.
- Worse nights after alcohol: alcohol helps people fall asleep but often causes more awakenings in the second half of the night.
## Caffeine and naps
Caffeine has an average half-life of about 5 hours (it varies a lot between people, from about 2 to 10 hours), so an afternoon coffee is still partly active at bedtime. Short naps (10-30 min) before mid-afternoon refresh most people without hurting night sleep; longer or later naps reduce sleep pressure in the evening.
## The "consistent schedule idea"
The script suggests a fixed wake time (the median workday wake time) and a lights-out time that gives `--target-hours` of sleep plus a typical time to fall asleep. It is a starting point for a conversation. Keeping the same wake time every day is the single most useful habit for a regular body clock.
FILE:referenceshttps://www.aitopic.com/when-to-get-help.md
# When a sleep diary is not enough
A diary helps people notice patterns and try small habit changes. Some situations need a doctor, ideally a general practitioner first, who can refer to a sleep specialist. Recommend getting help, kindly and clearly, when any of these apply:
## See a doctor soon
- Loud snoring with pauses in breathing, gasping or choking at night (noticed by a partner), especially with morning headaches or high blood pressure: possible sleep apnea.
- Strong sleepiness during the day: falling asleep while driving, in meetings or in conversations, even after enough hours in bed.
- Trouble falling or staying asleep at least 3 nights a week for 3 months or more, affecting the day: chronic insomnia has effective treatments, especially cognitive behavioral therapy for insomnia (CBT-I).
- An urge to move the legs in the evening with uncomfortable feelings that get better with movement.
- Acting out dreams, sudden muscle weakness with laughter or strong emotions, or sleep attacks.
- Sleep problems together with low mood, loss of interest, strong anxiety or thoughts of self-harm. If someone mentions thoughts of self-harm, encourage them to contact local emergency services or a crisis line right away.
- Sleep problems that started with a new medication, or that come with pain, breathing problems at night or frequent urination.
- Pregnancy, shift work with accidents or near misses, or a child or teenager with persistent sleep problems: get specific professional advice.
## Never do in this skill
- Diagnose a sleep disorder or rule one out.
- Recommend sleeping pills, melatonin doses, supplements or stopping a prescribed medication.
- Tell someone to drive or work in a safety-critical job when they report strong sleepiness.
## Limits of a diary
- Times are estimates; people often overestimate time awake and underestimate sleep, especially on bad nights.
- Wearable trackers estimate sleep from movement and heart rate; they are fine for bedtime and wake time but not exact for sleep stages.
- A few weeks show habits, not health. Bring the diary and the script's summary to the doctor; clinicians find a filled diary useful.
FILE:templateshttps://www.aitopic.com/two-week-sleep-review.md
# Your sleep review: {{from}} to {{to}} ({{N}} nights)
## The short version
{{2-3 sentences in plain words: how much you sleep, how regular it is, the main pattern, one thing that is already good}}
## Your numbers
| | Your average | Typical range |
|---|---|---|
| Sleep per night | {{6h38}} | 7-9 h |
| Time in bed | {{7h38}} | sleep + 15-30 min |
| Sleep efficiency | {{87%}} | 85% or more |
| Time to fall asleep | {{25 min}} | 10-20 min |
| Wake-up time variation | {{73 min}} | under 60 min |
| Social jet lag | {{1h49}} | under 1 h |
## Patterns we noticed
- {{e.g. On the 7 nights with coffee after 14:00 you needed about 42 minutes to fall asleep, compared with 16 minutes on other nights.}}
- {{...}}
## Experiments for the next two weeks (pick 2-3)
1. {{e.g. Wake up at 06:50 every day, also on weekends (within 30-60 minutes), and get daylight within an hour.}}
2. {{e.g. Last coffee before 14:00.}}
3. {{e.g. Keep naps under 30 minutes and before 15:00.}}
Keep filling the diary, then run the analysis again from {{start date}} and compare.
## Please talk to a doctor if
{{Only if relevant: the warning signs from when-to-get-help.md that apply, written kindly. Otherwise: "Nothing in your diary suggests you need medical help right now, but see a doctor if ..."}}
_This review is based on your own diary estimates and is not medical advice._
FILE:exampleshttps://www.aitopic.com/sleep_diary.csv
date,bedtime,sleep_latency_min,awakenings,awake_min,wake_time,out_of_bed,nap_min,caffeine_last,alcohol_drinks,quality,day_type
2026-11-09,23:55,10,2,14,06:50,07:05,0,11:30,0,4,work
2026-11-10,23:10,50,2,14,06:50,07:00,0,16:30,0,2,work
2026-11-11,00:20,15,1,7,06:45,07:00,0,10:00,0,4,work
2026-11-12,23:25,50,1,7,06:50,06:55,40,16:00,0,3,work
2026-11-13,00:55,20,3,50,09:20,09:40,40,08:30,2,3,free
2026-11-14,00:55,10,3,55,09:20,10:00,40,,2,2,free
2026-11-15,00:20,15,2,14,06:45,07:00,0,08:30,0,4,work
2026-11-16,00:20,20,0,0,06:50,07:00,0,,0,4,work
2026-11-17,23:10,40,1,7,06:45,07:00,0,16:30,0,3,work
2026-11-18,23:40,40,1,7,06:45,06:55,0,16:00,0,3,work
2026-11-19,00:20,35,2,14,07:00,07:15,50,16:00,0,2,work
2026-11-20,00:40,10,2,35,09:20,10:00,40,,2,2,free
2026-11-22,23:25,10,2,14,06:45,07:00,0,11:30,0,4,work
2026-11-23,23:40,20,2,14,06:50,07:00,0,08:30,0,4,work
2026-11-24,00:50,40,2,60,06:45,06:55,0,16:30,0,1,work
2026-11-25,01:05,30,1,7,06:45,06:55,0,11:30,0,4,work
2026-11-26,23:25,40,1,7,07:00,07:05,0,16:30,0,2,work
2026-11-27,00:40,20,1,25,10:10,10:30,40,10:00,2,2,free
2026-11-28,01:30,10,3,55,10:10,10:40,50,08:30,2,3,free
2026-11-29,23:40,15,1,7,07:00,07:10,0,10:00,0,4,work
2026-11-30,23:30,15,,10,7:05,,0,,0,,work
2026-12-01,23:15,,1,abc,06:50,07:00,0,09:00,0,4,work
FILE:scriptshttps://www.aitopic.com/sleep_diary.py
#!https://www.aitopic.com/usrhttps://www.aitopic.com/binhttps://www.aitopic.com/env python3
"""sleep_diary.py - turn a simple sleep diary CSV into clear sleep metrics and pattern flags.
One row per night. Required columns: date, bedtime, wake_time. Optional: sleep_latency_min,
awake_min, awakenings, out_of_bed, nap_min, caffeine_last, alcohol_drinks, quality, day_type.
Times are HH:MM (24 h); a night that crosses midnight is handled automatically. date is the
evening you went to bed (YYYY-MM-DD or DD.MM.YYYY). day_type is the NEXT day: work or free.
Per night: time in bed, sleep onset, total sleep time, sleep efficiency, sleep midpoint.
Summary: averages, regularity, workday vs free-day comparison (social jet lag), weekly table,
and flags S01-S10 + E01. Not a medical tool; see referenceshttps://www.aitopic.com/when-to-get-help.md.
Python 3.8+ standard library only.
Usage:
sleep_diary.py DIARY.csv [--format text|md|json|csv] [--since YYYY-MM-DD] [--until YYYY-MM-DD]
[--target-hours 7.5] [--fail-on high|medium|low|none]
sleep_diary.py --self-test
Exit codes: 0 = no flags at or above --fail-on (default none), 1 = flags at or above it, 2 = bad input.
"""
import argparse, csv, datetime, io, json, statistics, sys
FLAGS = {
"S01": "average sleep efficiency below 85% (a lot of time in bed awake)",
"S02": "average total sleep below the healthy adult range (7 h); below 6 h is high",
"S03": "wake-up time varies a lot (standard deviation over 60 min)",
"S04": "social jet lag: sleep midpoint on free days is 1 h or more later than on workdays (2 h+ is medium)",
"S05": "average time to fall asleep over 30 min",
"S06": "nights with caffeine after 14:00 took clearly longer to fall asleep (10 min+ on average)",
"S07": "long daytime naps (over 30 min) on 3 or more days",
"S08": "nights after alcohol had clearly more time awake (15 min+ on average)",
"S09": "fewer than 7 nights logged, or gaps of 2+ missing nights; patterns are less reliable",
"S10": "2 or more very short nights (under 5 h of sleep)",
"E01": "rows that could not be read",
}
SEV_ORDER = {"high": 3, "medium": 2, "low": 1, "info": 0}
def parse_date(s):
s = (s or "").strip()
for fmt in ("%Y-%m-%d", "%d.%m.%Y", "%dhttps://www.aitopic.com/%mhttps://www.aitopic.com/%Y"):
try:
return datetime.datetime.strptime(s, fmt).date()
except ValueError:
pass
raise ValueError("bad date %r" % s)
def parse_clock(s):
s = (s or "").strip().replace(".", ":")
h, _, m = s.partition(":")
h, m = int(h), int(m or 0)
if not (0 <= h <= 23 and 0 <= m <= 59):
raise ValueError("bad time %r" % s)
return h * 60 + m
def since_noon(clock_min):
"""Minutes since 12:00 on the diary date: 23:30 -> 690, 00:30 -> 750, 07:00 -> 1140.
Assumes bedtimes after 12:00 belong to the evening and times before 12:00 to the next morning."""
return clock_min - 720 if clock_min >= 720 else clock_min + 720
def num(row, key, default=0.0):
v = (row.get(key) or "").strip().replace(",", ".")
try:
return float(v) if v else default
except ValueError:
raise ValueError("bad number %r in %s" % (v, key))
def fmt_clock(m_since_noon):
m = int(round(m_since_noon + 720)) % 1440
return "%02d:%02d" % (m https://www.aitopic.com/https://www.aitopic.com/ 60, m % 60)
def hm(minutes):
minutes = int(round(minutes))
sign = "-" if minutes < 0 else ""
minutes = abs(minutes)
return "%s%dh%02d" % (sign, minutes https://www.aitopic.com/https://www.aitopic.com/ 60, minutes % 60)
def read_nights(text, since=None, until=None):
nights, errors = [], []
rdr = csv.DictReader(io.StringIO(text))
if not rdr.fieldnames:
raise ValueError("empty file")
cols = {c.strip().lower() for c in rdr.fieldnames if c}
missing = {"date", "bedtime", "wake_time"} - cols
if missing:
raise ValueError("missing required column(s): " + ", ".join(sorted(missing)))
for i, raw in enumerate(rdr, 2):
row = {(k or "").strip().lower(): (v or "").strip() for k, v in raw.items()}
if not any(row.values()):
continue
try:
d = parse_date(row["date"])
if (since and d < since) or (until and d > until):
continue
bed = since_noon(parse_clock(row["bedtime"]))
wake = since_noon(parse_clock(row["wake_time"]))
oob = since_noon(parse_clock(row["out_of_bed"])) if row.get("out_of_bed") else wake
lat, awake = num(row, "sleep_latency_min"), num(row, "awake_min")
onset = bed + lat
if not (bed < wake <= oob) or onset >= wake:
raise ValueError("times out of order (bed %s, wake %s, out of bed %s)" % (row["bedtime"], row["wake_time"], row.get("out_of_bed") or "-"))
tib = oob - bed
tst = wake - onset - awake
if tst <= 0 or tib > 20 * 60:
raise ValueError("implausible night (sleep %.0f min, in bed %.0f min)" % (tst, tib))
caf = row.get("caffeine_last", "")
q = row.get("quality", "")
nights.append({
"date": d.isoformat(), "bedtime": row["bedtime"], "wake_time": row["wake_time"],
"tib_min": tib, "tst_min": tst, "latency_min": lat, "awake_min": awake,
"awakenings": num(row, "awakenings", 0), "efficiency": round(100.0 * tst https://www.aitopic.com/ tib, 1),
"midpoint": onset + (wake - onset) https://www.aitopic.com/ 2.0, "wake": wake, "bed": bed,
"nap_min": num(row, "nap_min"), "late_caffeine": bool(caf) and parse_clock(caf) >= 14 * 60,
"alcohol": num(row, "alcohol_drinks") > 0, "quality": int(q) if q else None,
"day_type": (row.get("day_type") or "").lower() or None})
except (ValueError, KeyError) as e:
errors.append({"line": i, "error": str(e)})
nights.sort(key=lambda n: n["date"])
return nights, errors
def mean(xs):
xs = [x for x in xs if x is not None]
return sum(xs) https://www.aitopic.com/ len(xs) if xs else None
def analyze(nights, errors, target_hours=7.5):
flags = []
def add(code, sev, detail):
flags.append({"code": code, "severity": sev, "detail": detail})
if errors:
add("E01", "medium", "%d row(s): %s" % (len(errors), "; ".join("line %d %s" % (e["line"], e["error"]) for e in errors[:3])))
if not nights:
return {"summary": {"nights": 0}, "nights": [], "weekly": [], "flags": flags}
tst = mean(n["tst_min"] for n in nights)
eff = mean(n["efficiency"] for n in nights)
lat = mean(n["latency_min"] for n in nights)
wake_sd = statistics.pstdev([n["wake"] for n in nights]) if len(nights) > 1 else 0.0
bed_sd = statistics.pstdev([n["bed"] for n in nights]) if len(nights) > 1 else 0.0
work = [n for n in nights if n["day_type"] == "work"]
free = [n for n in nights if n["day_type"] == "free"]
sjl = (mean(n["midpoint"] for n in free) - mean(n["midpoint"] for n in work)) if work and free else None
if eff < 85:
add("S01", "medium", "average efficiency %.1f%%" % eff)
if tst < 360:
add("S02", "high", "average sleep %s" % hm(tst))
elif tst < 420:
add("S02", "medium", "average sleep %s" % hm(tst))
if wake_sd > 60:
add("S03", "medium", "wake time SD %d min" % round(wake_sd))
if sjl is not None and sjl >= 60:
add("S04", "medium" if sjl >= 120 else "low", "free-day midpoint %s later than workdays" % hm(sjl))
if lat > 30:
add("S05", "medium", "average %d min to fall asleep" % round(lat))
lc = [n["latency_min"] for n in nights if n["late_caffeine"]]
nc = [n["latency_min"] for n in nights if not n["late_caffeine"]]
if len(lc) >= 2 and len(nc) >= 2 and mean(lc) - mean(nc) >= 10:
add("S06", "low", "%d min vs %d min to fall asleep (%d late-caffeine nights)" % (round(mean(lc)), round(mean(nc)), len(lc)))
longnaps = [n for n in nights if n["nap_min"] > 30]
if len(longnaps) >= 3:
add("S07", "low", "%d days with naps over 30 min" % len(longnaps))
al = [n["awake_min"] for n in nights if n["alcohol"]]
na = [n["awake_min"] for n in nights if not n["alcohol"]]
if len(al) >= 2 and len(na) >= 2 and mean(al) - mean(na) >= 15:
add("S08", "low", "%d min vs %d min awake at night (%d alcohol nights)" % (round(mean(al)), round(mean(na)), len(al)))
dates = [datetime.date.fromisoformat(n["date"]) for n in nights]
gaps = [(a, b) for a, b in zip(dates, dates[1:]) if (b - a).days >= 3]
if len(nights) < 7 or gaps:
add("S09", "info", "%d nights logged%s" % (len(nights), ("; gaps after " + ", ".join(a.isoformat() for a, _ in gaps)) if gaps else ""))
short = [n for n in nights if n["tst_min"] < 300]
if len(short) >= 2:
add("S10", "medium", "%d nights under 5 h: %s" % (len(short), ", ".join(n["date"] for n in short)))
flags.sort(key=lambda f: (-SEV_ORDER[f["severity"]], f["code"]))
weeks = {}
for n in nights:
y, w, _ = datetime.date.fromisoformat(n["date"]).isocalendar()
weeks.setdefault("%d-W%02d" % (y, w), []).append(n)
weekly = [{"week": k, "nights": len(v), "avg_sleep": hm(mean(x["tst_min"] for x in v)),
"avg_efficiency": round(mean(x["efficiency"] for x in v), 1),
"avg_quality": (round(mean(x["quality"] for x in v), 1) if any(x["quality"] for x in v) else None)}
for k, v in sorted(weeks.items())]
wake_ref = statistics.median([n["wake"] for n in (work or nights)])
summary = {
"nights": len(nights), "from": nights[0]["date"], "to": nights[-1]["date"],
"avg_sleep": hm(tst), "avg_time_in_bed": hm(mean(n["tib_min"] for n in nights)),
"avg_efficiency_pct": round(eff, 1), "avg_latency_min": round(lat), "avg_awake_min": round(mean(n["awake_min"] for n in nights)),
"avg_bedtime": fmt_clock(mean(n["bed"] for n in nights)), "avg_wake_time": fmt_clock(mean(n["wake"] for n in nights)),
"bedtime_sd_min": round(bed_sd), "wake_sd_min": round(wake_sd),
"workday_midpoint": fmt_clock(mean(n["midpoint"] for n in work)) if work else None,
"free_day_midpoint": fmt_clock(mean(n["midpoint"] for n in free)) if free else None,
"social_jet_lag": hm(sjl) if sjl is not None else None,
"avg_quality": round(mean(n["quality"] for n in nights), 1) if any(n["quality"] for n in nights) else None,
"anchor_wake_time": fmt_clock(wake_ref),
"suggested_lights_out": fmt_clock(wake_ref - target_hours * 60 - max(15, min(lat, 30))),
"target_hours": target_hours,
}
return {"summary": summary, "nights": nights, "weekly": weekly, "flags": flags}
def render(res, fmt):
s = res["summary"]
if fmt == "json":
return json.dumps(res, indent=2, default=str)
if fmt == "csv":
b = io.StringIO(); w = csv.writer(b, lineterminator="\n")
w.writerow(["date", "bedtime", "wake_time", "time_in_bed", "sleep", "efficiency_pct", "latency_min", "awake_min", "midpoint", "day_type", "quality"])
for n in res["nights"]:
w.writerow([n["date"], n["bedtime"], n["wake_time"], hm(n["tib_min"]), hm(n["tst_min"]), n["efficiency"], int(n["latency_min"]), int(n["awake_min"]), fmt_clock(n["midpoint"]), n["day_type"] or "", n["quality"] or ""])
return b.getvalue().rstrip("\n")
if not s.get("nights"):
return "No readable nights.\n" + "\n".join(" %s %s" % (f["code"], f["detail"]) for f in res["flags"])
lines = [
("Nights", "%d (%s to %s)" % (s["nights"], s["from"], s["to"])),
("Average sleep", "%s of %s in bed (efficiency %.1f%%)" % (s["avg_sleep"], s["avg_time_in_bed"], s["avg_efficiency_pct"])),
("Falling asleep", "%d min on average; %d min awake during the night" % (s["avg_latency_min"], s["avg_awake_min"])),
("Bedtime https://www.aitopic.com/ wake time", "%s https://www.aitopic.com/ %s (variation %d https://www.aitopic.com/ %d min SD)" % (s["avg_bedtime"], s["avg_wake_time"], s["bedtime_sd_min"], s["wake_sd_min"])),
("Sleep midpoint", "workdays %s, free days %s, social jet lag %s" % (s["workday_midpoint"] or "-", s["free_day_midpoint"] or "-", s["social_jet_lag"] or "-")),
("Quality (1-5)", str(s["avg_quality"] or "-")),
("Consistent schedule idea", "wake at %s every day; lights out around %s for %.1f h of sleep" % (s["anchor_wake_time"], s["suggested_lights_out"], s["target_hours"])),
]
if fmt == "md":
out = ["## Sleep diary summary", "", "| Metric | Value |", "|---|---|"] + ["| %s | %s |" % l for l in lines]
out += ["", "### Weekly", "", "| Week | Nights | Avg sleep | Efficiency | Quality |", "|---|---|---|---|---|"]
out += ["| %s | %d | %s | %.1f%% | %s |" % (w["week"], w["nights"], w["avg_sleep"], w["avg_efficiency"], w["avg_quality"] or "-") for w in res["weekly"]]
out += ["", "### Patterns", ""] + (["- **%s %s** %s - %s" % (f["severity"], f["code"], FLAGS[f["code"]], f["detail"]) for f in res["flags"]] or ["- none"])
out += ["", "_Not medical advice. See when-to-get-help before changing sleep on purpose._"]
return "\n".join(out)
out = ["Sleep diary summary"] + [" %-25s %s" % l for l in lines] + ["", "Weekly"]
out += [" %-9s %d night%s sleep %s efficiency %5.1f%% quality %s" % (w["week"], w["nights"], "" if w["nights"] == 1 else "s", w["avg_sleep"], w["avg_efficiency"], w["avg_quality"] or "-") for w in res["weekly"]]
out += ["", "Patterns"] + ([" %-6s %s %s" % (f["severity"].upper(), f["code"], f["detail"]) for f in res["flags"]] or [" none"])
out += ["", "Not medical advice; see referenceshttps://www.aitopic.com/when-to-get-help.md."]
return "\n".join(out)
def self_test():
head = "date,bedtime,sleep_latency_min,awake_min,wake_time,out_of_bed,nap_min,caffeine_last,alcohol_drinks,quality,day_type\n"
rows = [
"2026-11-02,23:30,10,10,07:00,07:10,0,09:00,0,4,work",
"2026-11-03,23:45,40,20,07:00,07:15,0,16:30,0,3,work",
"2026-11-04,00:15,15,40,07:00,07:20,45,10:00,2,2,work",
"2026-11-05,23:30,45,15,07:00,07:30,40,17:00,0,3,work",
"2026-11-06,01:30,10,45,09:30,10:00,0,11:00,3,2,free",
"2026-11-07,02:00,10,10,10:30,10:45,60,,0,4,free",
"2026-11-08,23:00,20,10,07:00,07:05,0,08:30,0,4,work",
"2026-11-09,bad,10,10,07:00,,,,,,work",
]
nights, errs = read_nights(head + "\n".join(rows) + "\n")
r = analyze(nights, errs, 7.5)
codes = {f["code"] for f in r["flags"]}
n0 = nights[0]
checks = [
("7 nights read", len(nights) == 7), ("1 error row", len(errs) == 1 and errs[0]["line"] == 9),
("midnight crossing tib", n0["tib_min"] == 460), ("tst", n0["tst_min"] == 430),
("efficiency", n0["efficiency"] == round(100 * 430 https://www.aitopic.com/ 460, 1)),
("after-midnight bedtime", nights[2]["bed"] == 735 and nights[2]["tst_min"] == 350),
("S04 social jet lag", "S04" in codes), ("S06 late caffeine", "S06" in codes),
("S07 naps", "S07" in codes), ("S08 alcohol", "S08" in codes), ("E01", "E01" in codes),
("S03 wake variation", "S03" in codes), ("no S10", "S10" not in codes),
("clock format", fmt_clock(750) == "00:30" and fmt_clock(1140) == "07:00"),
("hm", hm(430) == "7h10" and hm(-75) == "-1h15"),
("dd.mm.yyyy", parse_date("03.12.2026") == datetime.date(2026, 12, 3)),
("out of order rejected", read_nights(head + "2026-11-02,07:00,10,0,06:00,,,,,,\n")[1] != []),
("md render", render(r, "md").startswith("## Sleep diary summary")),
("csv render", render(r, "csv").count("\n") == 7),
]
bad = [n for n, ok in checks if not ok]
if bad:
print("self-test FAILED:", ", ".join(bad)); print(sorted(codes)); return 1
print("self-test OK: %d checks" % len(checks)); return 0
def main(argv=None):
ap = argparse.ArgumentParser(description="Analyze a sleep diary CSV (stdlib only).")
ap.add_argument("diary", nargs="?")
ap.add_argument("--format", choices=["text", "md", "json", "csv"], default="text")
ap.add_argument("--since"); ap.add_argument("--until")
ap.add_argument("--target-hours", type=float, default=7.5)
ap.add_argument("--fail-on", choices=["high", "medium", "low", "none"], default="none")
ap.add_argument("--self-test", action="store_true")
a = ap.parse_args(argv)
if a.self_test:
return self_test()
if not a.diary:
ap.error("give a diary CSV (or --self-test)")
try:
text = sys.stdin.read() if a.diary == "-" else open(a.diary, encoding="utf-8-sig").read()
nights, errors = read_nights(text, parse_date(a.since) if a.since else None, parse_date(a.until) if a.until else None)
except (OSError, ValueError) as e:
print("error: %s" % e, file=sys.stderr); return 2
if not 4 <= a.target_hours <= 10:
print("error: --target-hours must be between 4 and 10", file=sys.stderr); return 2
res = analyze(nights, errors, a.target_hours)
print(render(res, a.format))
if a.fail_on == "none":
return 0
return 1 if any(SEV_ORDER[f["severity"]] >= SEV_ORDER[a.fail_on] for f in res["flags"]) else 0
if __name__ == "__main__":
sys.exit(main())
Comments & Questions (0)
No comments yet
Be the first to comment!