stepwise / report.py
Ashish-K's picture
Leaving a quiz submits it (one warning); chat nudge with alarm and ask-again options
00466c9 verified
Raw History Blame Contribute Delete
13.6 kB
"""The 📈 Report: a child's numbers for a period, and an encouraging coach that comments on them.
The numbers are counted here, never by the model. The coach (Opus 5.5) sees only these
numbers and idea names, not chat transcripts or answers, and writes a short commentary
for either the child or a parent; both can ask follow-up questions.
"""
from __future__ import annotations
import json
from datetime import datetime, timedelta, timezone
from tutor import CHAPTERS, OPUS, turn_cost
CHAT_CAP_MIN, QUIZ_CAP_MIN = 45, 30 # a chat or quiz left open counts at most this long
ATOM_NAMES = {a["id"]: (a["statement"], ch["subject"], ch["chapter"]) for ch in CHAPTERS.values() for a in ch["atoms"]}
def _dt(s: str) -> datetime:
d = datetime.fromisoformat(str(s).replace("Z", "+00:00"))
return d if d.tzinfo else d.replace(tzinfo=timezone.utc)
def _in(s, a: datetime, b: datetime) -> bool:
try:
return a <= _dt(s) < b
except (ValueError, TypeError):
return False
def _minutes(store, sid: str, a: datetime, b: datetime) -> tuple[float, int, list]:
mins, n, sessions = 0.0, 0, []
for s in store.chats.values():
if s["studentId"] != sid or not _in(s["started"], a, b):
continue
if sum(1 for m in s["transcript"] if m["role"] == "student") < 2:
continue
m = min(CHAT_CAP_MIN, max(1.0, (_dt(s["updated"]) - _dt(s["started"])).total_seconds() / 60))
mins += m
n += 1
sessions.append(s)
return mins, n, sessions
def period_stats(store, sets: dict, sid: str, a: datetime, b: datetime) -> dict:
"""Everything the Report shows for one child between a (inclusive) and b (exclusive)."""
quizzes = [x for x in store.attempts if x["studentId"] == sid and _in(x["submittedAt"], a, b)]
chat_min, n_chats, sessions = _minutes(store, sid, a, b)
quiz_min = sum(min(QUIZ_CAP_MIN, (x.get("durationSec") or 0) / 60) for x in quizzes)
pcts = [round(100 * x["score"] / x["max"]) if x["max"] else 0 for x in quizzes]
chunks = store.progress.get(sid, {}).get("chunks", {})
parts = [k for k, v in chunks.items() if v.get("status") == "learned" and _in(v.get("at", ""), a, b)]
# topics touched in the period, and which of them were new (no earlier chat or quiz on that chapter)
first_seen: dict[str, str] = {}
for s in store.chats.values():
if s["studentId"] == sid:
first_seen[s.get("chapterId", s.get("setId"))] = min(first_seen.get(s.get("chapterId", s.get("setId")), s["started"]), s["started"])
for x in store.attempts:
if x["studentId"] == sid:
cid = (sets.get(x["setId"]) or {}).get("chapterId") or x["setId"].split("_q")[0]
first_seen[cid] = min(first_seen.get(cid, x["submittedAt"]), x["submittedAt"])
touched = {s.get("chapterId", s.get("setId")) for s in sessions} | {(sets.get(x["setId"]) or {}).get("chapterId") or x["setId"] for x in quizzes}
touched = {c for c in touched if c in CHAPTERS}
new_chapters = sorted(CHAPTERS[c]["chapter"] for c in touched if _in(first_seen.get(c, ""), a, b))
# strong and weak ideas, from every answer recorded on each idea in the period
per_atom: dict[str, list] = {}
for atom, st in store.mastery.get(sid, {}).items():
for e in st.get("log", []):
if _in(e.get("t", ""), a, b):
per_atom.setdefault(atom, []).append(bool(e.get("ok")))
strong, weak = [], []
for atom, oks in per_atom.items():
name = ATOM_NAMES.get(atom)
if not name:
continue
right, n = sum(oks), len(oks)
item = {"idea": name[0], "subject": name[1], "chapter": name[2], "right": right, "of": n}
if n >= 2 and right == n:
strong.append(item)
elif n - right >= 2 or (n >= 2 and right / n < 0.5):
weak.append(item)
strong.sort(key=lambda x: -x["of"])
weak.sort(key=lambda x: (x["right"] / x["of"], -x["of"]))
feelings: dict[str, int] = {}
for f in store.feedback.values():
if f.get("by") == sid and _in(f.get("created", ""), a, b):
for t in f.get("tags", []):
if t in ("feeling lost", "feeling repetitive", "got insight", "gaining confidence"):
feelings[t] = feelings.get(t, 0) + 1
not_learnt = sum(len(x.get("notLearnt") or []) for x in quizzes)
# focus: counted in the browser (on screen and in use / away / switches), only where it was recorded
fa = fw = fs = 0
for x in quizzes:
f = x.get("focus") or {}
fa, fw, fs = fa + f.get("activeSec", 0), fw + f.get("awaySec", 0), fs + f.get("switches", 0)
for s in store.chats.values():
if s["studentId"] != sid:
continue
for m in s["transcript"]:
f = m.get("focus")
if f and m["role"] == "student" and _in(m.get("t", ""), a, b):
# a reply after a very long gap (came back the next day) counts as one switch, not hours away
fa, fw, fs = fa + f.get("activeSec", 0), fw + min(f.get("awaySec", 0), 3600), fs + f.get("switches", 0)
left = sum(1 for x in quizzes if x.get("leftQuiz"))
focus = ({"focusedMinutes": round(fa / 60), "awayMinutes": round(fw / 60), "switchesAway": fs,
"focusedShare": round(100 * fa / (fa + fw)) if fa + fw else None, "quizzesSubmittedByLeaving": left} if fa + fw or left else None)
by_subject: dict[str, dict] = {}
for x, p in zip(quizzes, pcts):
d = by_subject.setdefault(x["subject"] or "Other", {"quizzes": 0, "total": 0})
d["quizzes"] += 1
d["total"] += p
for d in by_subject.values():
d["average"] = round(d.pop("total") / d["quizzes"])
days = []
day = a
while day < b and len(days) < 62:
nxt = day + timedelta(days=1)
dq = [p for x, p in zip(quizzes, pcts) if _in(x["submittedAt"], day, nxt)]
dm, _, _ = _minutes(store, sid, day, nxt)
dm += sum(min(QUIZ_CAP_MIN, (x.get("durationSec") or 0) / 60) for x in quizzes if _in(x["submittedAt"], day, nxt))
days.append({"date": day.date().isoformat(), "minutes": round(dm), "quizzes": len(dq),
"average": round(sum(dq) / len(dq)) if dq else None})
day = nxt
return {
"from": a.isoformat(), "to": b.isoformat(),
"minutes": round(chat_min + quiz_min), "activeDays": sum(1 for d in days if d["minutes"] or d["quizzes"]),
"tutorSessions": n_chats, "partsLearnt": len(parts),
"partTitles": [p.split("/")[-1] for p in parts][:12],
"quizzes": len(quizzes), "average": round(sum(pcts) / len(pcts)) if pcts else None,
"best": max(pcts) if pcts else None, "fullMarks": sum(1 for p in pcts if p == 100),
"bySubject": by_subject, "chaptersWorkedOn": sorted(CHAPTERS[c]["chapter"] for c in touched),
"newChapters": new_chapters, "strong": strong[:6], "weak": weak[:6],
"feelings": feelings, "notLearntYet": not_learnt, "days": days, "focus": focus,
"recentQuizzes": [{"title": (sets.get(x["setId"]) or {}).get("title") or x.get("chapter", ""), "subject": x["subject"],
"percent": p, "date": x["submittedAt"][:10]} for x, p in sorted(zip(quizzes, pcts), key=lambda z: z[0]["submittedAt"], reverse=True)[:8]],
}
def report(store, sets: dict, sid: str, a: datetime, b: datetime) -> dict:
"""This period plus the same-length period just before it, for the trend."""
cur = period_stats(store, sets, sid, a, b)
prev = period_stats(store, sets, sid, a - (b - a), a)
cur["previous"] = {k: prev[k] for k in ("minutes", "quizzes", "average", "partsLearnt", "activeDays")}
return cur
COACH_RULES = """You are the StepWise coach. You comment on a Cambridge IGCSE student's study record for a period, using ONLY the numbers given (counted by the app). You never see their chats or answers, so never invent details, topics or scores that aren't in the numbers.
Write for the reader named below:
- the STUDENT (about 15): talk to them directly ("you"), warm and honest, like a good coach. Never patronising, never gushing.
- a PARENT: talk about the child by name, and give the parent one or two concrete ways to support (what to praise, what to ask about), never pressure.
First reply: four short parts, each starting with an emoji label on its own line.
For the STUDENT:
🌟 What went well — 1–3 specific things from the numbers (effort, parts learnt, strong ideas, improvement).
🎯 Pay attention to — the 2–3 most useful things (weak ideas by name, low scores, gaps, feeling lost).
📈 Compared with before — one or two lines on the trend against the previous period.
👉 Next step — one clear, doable thing for the next day or two.
For a PARENT:
🌟 What went well — 1–3 specific things worth praising, from the numbers.
🎯 Keep an eye on — the 2–3 most useful things (weak ideas by name, low scores, gaps, feeling lost), calmly.
📈 Compared with before — one or two lines on the trend.
🤝 How you can help — one or two concrete things to say or ask, and what not to push on.
Keep the whole first reply under 200 words. Plain text, short lines, no tables, no headings other than those labels.
If the period is empty or nearly empty, say so kindly, without guilt, and suggest one small way to start. Praise effort and specific progress, not just high scores. Treat "not learnt yet" answers and "feeling lost" presses as honest and useful, not as failures.
"focus" (when present) is measured, not estimated: minutes with StepWise on screen and in use, minutes away (another app or tab, screen off, or 3+ minutes with no tap or typing) and how many times they switched away. Mention it in one short line only when it says something useful (for example most of the time was away, or focus was strong), as a study habit, never as blame or suspicion. For a parent, suggest a practical help such as a phone-free half hour.
Follow-up questions: answer briefly (under 120 words), from the numbers only. If asked something the numbers can't answer, say so and suggest where in the app to look (📚 Subjects, 💬 Chats)."""
def coach_reply(client_factory, audience: str, child: str, reader: str, label: str, stats: dict, history: list[dict]) -> tuple[str, float]:
"""history: [{"role": "user"|"assistant", "content": str}], may be empty for the first commentary."""
client = client_factory()
numbers = {k: v for k, v in stats.items() if k not in ("days",)}
intro = (f"Reader: {'the STUDENT, ' + child if audience == 'child' else 'a PARENT, ' + reader + ', about their child ' + child}.\n"
f"Period: {label} ({stats['from'][:10]} to {stats['to'][:10]}).\n"
f"Numbers (JSON; minutes are estimates, capped per session):\n{json.dumps(numbers, ensure_ascii=False)}")
messages = [{"role": "user", "content": intro + "\n\nPlease write the commentary."}]
for m in history[-12:]:
if m.get("role") in ("user", "assistant") and str(m.get("content", "")).strip():
messages.append({"role": m["role"], "content": str(m["content"])[:2000]})
# the conversation must alternate and end on the reader's turn
merged: list[dict] = []
for m in messages:
if merged and merged[-1]["role"] == m["role"]:
merged[-1]["content"] += "\n\n" + m["content"]
else:
merged.append(dict(m))
if merged[-1]["role"] != "user":
merged.append({"role": "user", "content": "Please carry on."})
resp = client.beta.messages.create(
model=OPUS, max_tokens=4000, betas=["server-side-fallback-2026-07-01"], fallbacks="default",
output_config={"effort": "medium"}, system=COACH_RULES, messages=merged)
text = "\n".join(b.text for b in resp.content if b.type == "text").strip()
if resp.stop_reason == "refusal" or not text:
text = "Sorry, I couldn't write that just now. Try again in a moment."
return text, turn_cost(getattr(resp, "model", None) or OPUS, resp.usage)
def period_bounds(kind: str, start: str | None, end: str | None, tz_offset_min: int = 0) -> tuple[datetime, datetime, str]:
"""today | week | month | 7d | 30d | custom (start, end as YYYY-MM-DD, end inclusive), in the viewer's time zone."""
tz = timezone(timedelta(minutes=-tz_offset_min))
now_local = datetime.now(tz)
today = now_local.replace(hour=0, minute=0, second=0, microsecond=0)
if kind == "today":
a, b, label = today, today + timedelta(days=1), "Today"
elif kind == "yesterday":
a, b, label = today - timedelta(days=1), today, "Yesterday"
elif kind == "week":
a = today - timedelta(days=today.weekday())
b, label = today + timedelta(days=1), "This week"
elif kind == "lastweek":
b = today - timedelta(days=today.weekday())
a, label = b - timedelta(days=7), "Last week"
elif kind == "month":
a, b, label = today.replace(day=1), today + timedelta(days=1), "This month"
elif kind == "30d":
a, b, label = today - timedelta(days=29), today + timedelta(days=1), "Last 30 days"
else:
a = datetime.fromisoformat(start).replace(tzinfo=tz) if start else today - timedelta(days=6)
b = (datetime.fromisoformat(end).replace(tzinfo=tz) if end else today) + timedelta(days=1)
if b <= a or (b - a).days > 366:
raise ValueError("bad range")
label = f"{a.date().isoformat()} to {(b - timedelta(days=1)).date().isoformat()}"
return a.astimezone(timezone.utc), b.astimezone(timezone.utc), label