From 314cc4aad549a2e7263ed978e1f7d07542aa1c48 Mon Sep 17 00:00:00 2001 From: im-rk Date: Sat, 3 Oct 2026 14:22:41 +0530 Subject: [PATCH 1/3] feat(revision): quiz mistakes become weak spots and a personal revision reel --- src/components/SavedView.tsx | 8 ++++- src/components/StudyPanel.tsx | 35 +++++++++++++++---- src/components/WatchView.tsx | 2 +- src/components/WeakSpots.tsx | 61 +++++++++++++++++++++++++++++++++ src/lib/saved.ts | 15 +++++++- src/lib/weak-spots.ts | 39 +++++++++++++++++++++ tests/unit/weak-spots.test.ts | 64 +++++++++++++++++++++++++++++++++++ 7 files changed, 215 insertions(+), 9 deletions(-) create mode 100644 src/components/WeakSpots.tsx create mode 100644 src/lib/weak-spots.ts create mode 100644 tests/unit/weak-spots.test.ts diff --git a/src/components/SavedView.tsx b/src/components/SavedView.tsx index 72db2bb..b9ac122 100644 --- a/src/components/SavedView.tsx +++ b/src/components/SavedView.tsx @@ -3,10 +3,11 @@ import Image from "next/image"; import Link from "next/link"; +import { WeakSpots } from "@/components/WeakSpots"; import { useLiteUrl } from "@/lib/data-saver"; import { formatTime } from "@/lib/format"; import { thumbUrl } from "@/lib/media"; -import { clearSaved, toggleSavedMoment, useRecentQuestions, useSavedMoments, useWatchProgress } from "@/lib/saved"; +import { clearSaved, toggleSavedMoment, useRecentQuestions, useSavedMoments, useWatchProgress, useWeakSpots } from "@/lib/saved"; // The learner's Saved page: everything here lives on this device (src/lib/saved.ts). export function SavedView() { @@ -14,6 +15,7 @@ export function SavedView() { const moments = useSavedMoments(); const questions = useRecentQuestions(); const progress = useWatchProgress(); + const weak = useWeakSpots(); return (
@@ -25,6 +27,10 @@ export function SavedView() { )} +
clearSaved("weak")}> + +
+
clearSaved("moments")}> {moments.length === 0 ? ( Tap Save on any answer clip or search result to keep the moment here. diff --git a/src/components/StudyPanel.tsx b/src/components/StudyPanel.tsx index 860b611..1481df2 100644 --- a/src/components/StudyPanel.tsx +++ b/src/components/StudyPanel.tsx @@ -5,11 +5,13 @@ import { useState } from "react"; import { useLiteUrl } from "@/lib/data-saver"; import { formatTime } from "@/lib/format"; import { reelUrl } from "@/lib/media"; +import { recordQuizResult } from "@/lib/saved"; +import { weakKey } from "@/lib/weak-spots"; import type { StudyPack } from "@/lib/study-pack-schema"; -type Props = { pack: StudyPack; publicId: string; onSeek: (seconds: number) => void }; +type Props = { pack: StudyPack; lectureId: string; title: string; publicId: string; onSeek: (seconds: number) => void }; -export function StudyPanel({ pack, publicId, onSeek }: Props) { +export function StudyPanel({ pack, lectureId, title, publicId, onSeek }: Props) { const reel = reelUrl(pack.highlights.map((h) => ({ publicId, startS: h.startS, endS: h.endS, label: h.label ?? undefined }))); return ( @@ -54,7 +56,7 @@ export function StudyPanel({ pack, publicId, onSeek }: Props) {
)} - {pack.quiz.length > 0 && } + {pack.quiz.length > 0 && }
); } @@ -79,7 +81,9 @@ function ReelButton({ url, title, subtitle }: { url: string; title: string; subt ); } -function Quiz({ quiz, publicId, onSeek }: { quiz: StudyPack["quiz"]; publicId: string; onSeek: (seconds: number) => void }) { +type QuizProps = { quiz: StudyPack["quiz"]; lectureId: string; title: string; publicId: string; onSeek: (seconds: number) => void }; + +function Quiz({ quiz, lectureId, title, publicId, onSeek }: QuizProps) { const [answers, setAnswers] = useState>({}); // Bumped on every retry so the "missed" reel remounts closed instead of replaying the old one. const [round, setRound] = useState(0); @@ -125,7 +129,26 @@ function Quiz({ quiz, publicId, onSeek }: { quiz: StudyPack["quiz"]; publicId: s key={option} type="button" disabled={done} - onClick={() => setAnswers((a) => ({ ...a, [i]: j }))} + onClick={() => { + setAnswers((a) => ({ ...a, [i]: j })); + // A wrong answer becomes a weak spot (shown on Saved); a right answer clears one. + recordQuizResult( + { + key: weakKey(lectureId, q.question), + lectureId, + publicId, + title, + question: q.question, + answer: q.options[q.correctIndex] ?? "", + explanation: q.explanation, + segmentId: q.segmentId, + startS: q.startS, + endS: q.endS, + at: Date.now(), + }, + j === q.correctIndex, + ); + }} className={`rounded-lg border px-3 py-2 text-left text-sm transition-colors ${ state === "right" ? "border-ready bg-ready/10" @@ -167,7 +190,7 @@ function Quiz({ quiz, publicId, onSeek }: { quiz: StudyPack["quiz"]; publicId: s

{correct === quiz.length ? "All correct. You've got this session." - : `${missed.length} to review. The explanations are in the session itself.`} + : `${missed.length} to review. They are saved as weak spots, with a revision reel, on your Saved page.`}

{missedReel && (
diff --git a/src/components/WatchView.tsx b/src/components/WatchView.tsx index 0cc1353..689bcc0 100644 --- a/src/components/WatchView.tsx +++ b/src/components/WatchView.tsx @@ -148,7 +148,7 @@ export function WatchView({ lectureId, publicId, title, durationS, startAt, sear )} {tab === "study" && pack ? (
- +
) : tab === "chapters" ? (
    diff --git a/src/components/WeakSpots.tsx b/src/components/WeakSpots.tsx new file mode 100644 index 0000000..8ce4aae --- /dev/null +++ b/src/components/WeakSpots.tsx @@ -0,0 +1,61 @@ +"use client"; + +import Link from "next/link"; + +import { ReelPlayer } from "@/components/ReelPlayer"; +import { formatTime } from "@/lib/format"; +import { reelUrl } from "@/lib/media"; +import { removeWeakSpot, useWeakSpots } from "@/lib/saved"; +import { weakSpotClips } from "@/lib/weak-spots"; + +// Weak spots: every quiz question you got wrong, with the answer, the teacher's explanation and one reel that +// replays exactly those explanations, from any sessions. A question leaves the list when you answer it right. +export function WeakSpots() { + const spots = useWeakSpots(); + const reel = reelUrl(weakSpotClips(spots)); + + if (spots.length === 0) { + return ( +

    + Quiz questions you get wrong collect here, with a video of exactly what to relearn. Try a session's{" "} + + Check yourself + {" "} + quiz. +

    + ); + } + + return ( +
    + {reel && ( + + )} +
      + {spots.map((s) => ( +
    • +

      {s.question}

      +

      + Answer: {s.answer} +

      +

      {s.explanation}

      +

      {s.title}

      +
      + + ▶ Watch the explanation ({formatTime(s.startS)}) + + +
      +
    • + ))} +
    +
    + ); +} diff --git a/src/lib/saved.ts b/src/lib/saved.ts index c661997..ea83d12 100644 --- a/src/lib/saved.ts +++ b/src/lib/saved.ts @@ -2,6 +2,8 @@ import { useMemo, useSyncExternalStore } from "react"; +import { applyQuizResult, WEAK_SPOT_LIMIT, type WeakSpot } from "@/lib/weak-spots"; + // The learner's own library, kept on this device only (no account, nothing sent anywhere): saved moments, // recent questions and where they stopped watching. Every read and write tolerates blocked storage // (private mode, disabled site data), in which case the features simply show nothing. @@ -24,11 +26,12 @@ const KEYS = { moments: "pravaha-saved-moments", questions: "pravaha-recent-questions", progress: "pravaha-watch-progress", + weak: "pravaha-weak-spots", } as const; type Key = (typeof KEYS)[keyof typeof KEYS]; const CHANGE = "pravaha-saved-change"; -const LIMITS: Record = { [KEYS.moments]: 100, [KEYS.questions]: 30, [KEYS.progress]: 12 }; +const LIMITS: Record = { [KEYS.moments]: 100, [KEYS.questions]: 30, [KEYS.progress]: 12, [KEYS.weak]: WEAK_SPOT_LIMIT }; function readRaw(key: Key): string | null { try { @@ -75,6 +78,16 @@ function useStored(key: Key): T[] { export const useSavedMoments = () => useStored(KEYS.moments); export const useRecentQuestions = () => useStored(KEYS.questions); export const useWatchProgress = () => useStored(KEYS.progress); +export const useWeakSpots = () => useStored(KEYS.weak); + +// Quiz answers feed the weak spots: a wrong answer adds the question, a right one clears it. +export function recordQuizResult(spot: WeakSpot, correct: boolean) { + write(KEYS.weak, applyQuizResult(parse(readRaw(KEYS.weak)), spot, correct)); +} + +export function removeWeakSpot(key: string) { + write(KEYS.weak, parse(readRaw(KEYS.weak)).filter((s) => s.key !== key)); +} export function toggleSavedMoment(moment: Omit): boolean { const items = parse(readRaw(KEYS.moments)); diff --git a/src/lib/weak-spots.ts b/src/lib/weak-spots.ts new file mode 100644 index 0000000..3c7e684 --- /dev/null +++ b/src/lib/weak-spots.ts @@ -0,0 +1,39 @@ +import type { ReelClip } from "@/lib/media"; + +// Weak spots: the quiz questions a learner got wrong, remembered on this device (src/lib/saved.ts) until they +// get them right. Pure, so the rules are unit-tested. + +export type WeakSpot = { + key: string; + lectureId: string; + publicId: string; + title: string; + question: string; + answer: string; + explanation: string; + segmentId: number; + startS: number; + endS: number; + at: number; +}; + +export const WEAK_SPOT_LIMIT = 50; + +export const weakKey = (lectureId: string, question: string) => `${lectureId}|${question.trim().toLowerCase()}`; + +// A wrong answer moves the question to the front (newest first, no duplicates); a right answer clears it. +export function applyQuizResult(list: WeakSpot[], spot: WeakSpot, correct: boolean): WeakSpot[] { + const rest = list.filter((s) => s.key !== spot.key); + return correct ? rest : [spot, ...rest].slice(0, WEAK_SPOT_LIMIT); +} + +// The explanation clip for each weak spot, newest first, labelled with the question so the reel says what you +// are about to relearn. reelUrl() enforces the clip and length caps. +export function weakSpotClips(spots: WeakSpot[]): ReelClip[] { + return spots.map((s, i) => ({ + publicId: s.publicId, + startS: s.startS, + endS: s.endS, + label: `${i + 1} · ${s.question.length > 44 ? `${s.question.slice(0, 43).trimEnd()}…` : s.question}`, + })); +} diff --git a/tests/unit/weak-spots.test.ts b/tests/unit/weak-spots.test.ts new file mode 100644 index 0000000..772f697 --- /dev/null +++ b/tests/unit/weak-spots.test.ts @@ -0,0 +1,64 @@ +import { describe, expect, it } from "vitest"; + +import { reelUrl } from "@/lib/media"; +import { applyQuizResult, weakKey, weakSpotClips, WEAK_SPOT_LIMIT, type WeakSpot } from "@/lib/weak-spots"; + +const spot = (question: string, at = 1, lectureId = "L1"): WeakSpot => ({ + key: weakKey(lectureId, question), + lectureId, + publicId: `pravaha/${lectureId}`, + title: "Session", + question, + answer: "A", + explanation: "Because.", + segmentId: at, + startS: at * 10, + endS: at * 10 + 8, + at, +}); + +describe("applyQuizResult", () => { + it("adds a wrong answer at the front, newest first", () => { + const list = applyQuizResult(applyQuizResult([], spot("Q1", 1), false), spot("Q2", 2), false); + expect(list.map((s) => s.question)).toEqual(["Q2", "Q1"]); + }); + + it("clears a question once it is answered correctly", () => { + const list = applyQuizResult([spot("Q1"), spot("Q2", 2)], spot("Q1"), true); + expect(list.map((s) => s.question)).toEqual(["Q2"]); + }); + + it("does not duplicate a question missed again: it moves to the front", () => { + const list = applyQuizResult([spot("Q1", 1), spot("Q2", 2)], spot("Q2", 3), false); + expect(list.map((s) => [s.question, s.at])).toEqual([["Q2", 3], ["Q1", 1]]); + }); + + it("keys a question by session and normalised text, so the same text in two sessions stays separate", () => { + expect(weakKey("L1", " What is X? ")).toBe(weakKey("L1", "what is x?")); + expect(weakKey("L1", "Q")).not.toBe(weakKey("L2", "Q")); + }); + + it("keeps at most the limit", () => { + let list: WeakSpot[] = []; + for (let i = 0; i < WEAK_SPOT_LIMIT + 5; i++) list = applyQuizResult(list, spot(`Q${i}`, i), false); + expect(list).toHaveLength(WEAK_SPOT_LIMIT); + expect(list[0]!.question).toBe(`Q${WEAK_SPOT_LIMIT + 4}`); + }); +}); + +describe("weakSpotClips", () => { + it("labels each clip with its question and builds a reel across sessions, capped at 5 clips", () => { + const spots = Array.from({ length: 7 }, (_, i) => spot(`Question ${i + 1}`, i + 1, `L${i % 2}`)); + const clips = weakSpotClips(spots); + expect(clips[0]!.label).toBe("1 · Question 1"); + const reel = reelUrl(clips)!; + expect(reel.clips).toBe(5); + expect(reel.url).toContain("fl_splice"); + }); + + it("shortens long questions in the label", () => { + const [clip] = weakSpotClips([spot("Why does the learning rate need to decrease during training of deep networks?")]); + expect(clip!.label!.length).toBeLessThanOrEqual(50); + expect(clip!.label).toMatch(/…$/); + }); +}); From 0ddd23c188ac96b24b4466d9a2220c4deb16bd85 Mon Sep 17 00:00:00 2001 From: im-rk Date: Sat, 3 Oct 2026 14:22:42 +0530 Subject: [PATCH 2/3] feat(notes): a timestamp-linked study sheet per session, as Markdown or PDF --- src/app/api/lectures/[id]/notes/route.ts | 19 ++++ src/app/layout.tsx | 4 +- src/app/notes/[id]/page.tsx | 137 +++++++++++++++++++++++ src/app/watch/[id]/page.tsx | 8 ++ src/components/NotesActions.tsx | 33 ++++++ src/lib/notes-data.ts | 19 ++++ src/lib/notes.ts | 73 ++++++++++++ tests/unit/notes.test.ts | 75 +++++++++++++ 8 files changed, 366 insertions(+), 2 deletions(-) create mode 100644 src/app/api/lectures/[id]/notes/route.ts create mode 100644 src/app/notes/[id]/page.tsx create mode 100644 src/components/NotesActions.tsx create mode 100644 src/lib/notes-data.ts create mode 100644 src/lib/notes.ts create mode 100644 tests/unit/notes.test.ts diff --git a/src/app/api/lectures/[id]/notes/route.ts b/src/app/api/lectures/[id]/notes/route.ts new file mode 100644 index 0000000..04062be --- /dev/null +++ b/src/app/api/lectures/[id]/notes/route.ts @@ -0,0 +1,19 @@ +import { NextResponse } from "next/server"; + +import { apiError } from "@/lib/http"; +import { notesFilename, notesToMarkdown } from "@/lib/notes"; +import { loadNotes } from "@/lib/notes-data"; + +export const dynamic = "force-dynamic"; + +// A session's study notes: JSON by default, or `?format=md` for Markdown (`&download=1` as a file). +export async function GET(request: Request, { params }: { params: Promise<{ id: string }> }) { + const loaded = await loadNotes((await params).id); + if (!loaded) return apiError(404, "not_found", "No study notes for this session."); + const { searchParams } = new URL(request.url); + if (searchParams.get("format") !== "md") return NextResponse.json(loaded.notes); + + const headers: Record = { "Content-Type": "text/markdown; charset=utf-8" }; + if (searchParams.get("download")) headers["Content-Disposition"] = `attachment; filename="${notesFilename(loaded.notes.title)}"`; + return new NextResponse(notesToMarkdown(loaded.notes), { headers }); +} diff --git a/src/app/layout.tsx b/src/app/layout.tsx index a78bf21..de83d1a 100644 --- a/src/app/layout.tsx +++ b/src/app/layout.tsx @@ -45,7 +45,7 @@ export default function RootLayout({ children }: { children: React.ReactNode }) Skip to content -
    +
    {trialHoursLeft !== null && ( diff --git a/src/components/NotesActions.tsx b/src/components/NotesActions.tsx new file mode 100644 index 0000000..25c1c53 --- /dev/null +++ b/src/components/NotesActions.tsx @@ -0,0 +1,33 @@ +"use client"; + +import { useState } from "react"; + +// Copy as Markdown, download the .md file, or print / save as PDF. Hidden when printing. +export function NotesActions({ markdown, downloadHref }: { markdown: string; downloadHref: string }) { + const [copied, setCopied] = useState(false); + + async function copy() { + try { + await navigator.clipboard.writeText(markdown); + setCopied(true); + setTimeout(() => setCopied(false), 2000); + } catch { + // Clipboard blocked: the download button still works. + } + } + + const btn = "rounded-lg border border-border px-3 py-1.5 text-sm font-medium hover:border-accent"; + return ( +
    + + + Download .md + + +
    + ); +} diff --git a/src/lib/notes-data.ts b/src/lib/notes-data.ts new file mode 100644 index 0000000..9addec6 --- /dev/null +++ b/src/lib/notes-data.ts @@ -0,0 +1,19 @@ +import "server-only"; +import { cache } from "react"; +import { z } from "zod"; + +import { getLecture, getSegments, type Lecture } from "@/lib/lectures"; +import { buildNotes, hasContent, type Notes } from "@/lib/notes"; +import { publicBaseUrl } from "@/lib/site"; +import { getStudyPack } from "@/lib/study-packs"; + +// Notes for a ready session (any visibility: like its Watch page, the unguessable id is the access), or null +// when it isn't ready or there is nothing to put on the sheet. +export const loadNotes = cache(async (id: string): Promise<{ lecture: Lecture; notes: Notes } | null> => { + if (!z.uuid().safeParse(id).success) return null; + const lecture = await getLecture(id); + if (!lecture || lecture.status !== "ready") return null; + const [segments, pack] = await Promise.all([getSegments(lecture.id), getStudyPack(lecture.id)]); + const notes = buildNotes({ lecture, segments, pack, baseUrl: publicBaseUrl() }); + return hasContent(notes) ? { lecture, notes } : null; +}); diff --git a/src/lib/notes.ts b/src/lib/notes.ts new file mode 100644 index 0000000..cd2d652 --- /dev/null +++ b/src/lib/notes.ts @@ -0,0 +1,73 @@ +import { formatTime } from "@/lib/format"; +import type { StudyPack } from "@/lib/study-pack-schema"; + +// A study sheet for one session, built from what Pravaha already knows: the Study Pack and the AI chapters. +// Every point carries its timestamp and a link that opens the session at that second. No AI call, so it is +// instant and can't contradict the session. Pure, so it is unit-tested. + +export type Stamp = { t: number; label: string; url: string }; +export type Notes = { + title: string; + speaker: string | null; + durationS: number | null; + watchUrl: string; + summary: string[]; + concepts: (Stamp & { name: string })[]; + chapters: (Stamp & { title: string })[]; + quiz: (Stamp & { question: string; answer: string; explanation: string })[]; +}; + +type Input = { + lecture: { id: string; title: string; speaker: string | null; durationS: number | null }; + segments: { startS: number; chapterTitle: string | null }[]; + pack: StudyPack | null; + baseUrl: string; +}; + +export function buildNotes({ lecture, segments, pack, baseUrl }: Input): Notes { + const url = (t: number) => `${baseUrl}/watch/${lecture.id}?t=${Math.floor(t)}`; + const stamp = (t: number): Stamp => ({ t, label: formatTime(t), url: url(t) }); + + // Chapters are consecutive segments sharing a title; each starts where its first segment does. + const chapters: Notes["chapters"] = []; + for (const s of segments) { + if (s.chapterTitle && chapters.at(-1)?.title !== s.chapterTitle) chapters.push({ ...stamp(s.startS), title: s.chapterTitle }); + } + + return { + title: lecture.title, + speaker: lecture.speaker, + durationS: lecture.durationS, + watchUrl: url(0), + summary: pack?.summary ?? [], + concepts: [...(pack?.concepts ?? [])].sort((a, b) => a.startS - b.startS).map((c) => ({ ...stamp(c.startS), name: c.name })), + chapters, + quiz: (pack?.quiz ?? []).map((q) => ({ + ...stamp(q.startS), + question: q.question, + answer: q.options[q.correctIndex] ?? "", + explanation: q.explanation, + })), + }; +} + +export const hasContent = (n: Notes) => n.summary.length + n.concepts.length + n.chapters.length + n.quiz.length > 0; + +// Markdown that pastes cleanly into Notion, Obsidian, a GitHub gist or a message to a study group. +export function notesToMarkdown(n: Notes): string { + const meta = [n.speaker, n.durationS ? formatTime(n.durationS) : null, `[Watch the session](${n.watchUrl})`].filter(Boolean); + const lines = [`# ${n.title}`, "", meta.join(" · ")]; + const section = (heading: string, body: string[]) => body.length && lines.push("", `## ${heading}`, "", ...body); + section("In short", n.summary.map((s) => `- ${s}`)); + section("Key concepts", n.concepts.map((c) => `- **${c.name}** · [${c.label}](${c.url})`)); + section("Chapters", n.chapters.map((c) => `- [${c.label}](${c.url}) ${c.title}`)); + section( + "Check yourself", + n.quiz.flatMap((q, i) => [`${i + 1}. ${q.question}`, ` - **Answer:** ${q.answer}`, ` - ${q.explanation} ([${q.label}](${q.url}))`]), + ); + lines.push("", "---", "Made with Pravaha: ask your recordings, watch the answer."); + return lines.join("\n") + "\n"; +} + +export const notesFilename = (title: string) => + `${title.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 60) || "study-notes"}.md`; diff --git a/tests/unit/notes.test.ts b/tests/unit/notes.test.ts new file mode 100644 index 0000000..1775e23 --- /dev/null +++ b/tests/unit/notes.test.ts @@ -0,0 +1,75 @@ +import { describe, expect, it } from "vitest"; + +import { buildNotes, hasContent, notesFilename, notesToMarkdown } from "@/lib/notes"; +import type { StudyPack } from "@/lib/study-pack-schema"; + +const lecture = { id: "11111111-1111-4111-8111-111111111111", title: "Gradient Descent: Basics", speaker: "Prof. Rao", durationS: 754 }; +const baseUrl = "https://pravaha.test"; +const m = (segmentId: number, startS: number) => ({ segmentId, startS, endS: startS + 10 }); + +const pack: StudyPack = { + summary: ["Gradient descent minimises a loss.", "Learning rate sets the step."], + concepts: [ + { ...m(3, 120.4), name: "Learning rate" }, + { ...m(1, 15), name: "Loss function" }, + ], + quiz: [{ ...m(2, 61.9), question: "What does the learning rate control?", options: ["Step size", "Depth", "Width", "Bias"], correctIndex: 0, explanation: "It scales each update." }], + highlights: [], +}; +const segments = [ + { startS: 0, chapterTitle: "Intro" }, + { startS: 20, chapterTitle: "Intro" }, + { startS: 60, chapterTitle: "Update rule" }, + { startS: 130, chapterTitle: null }, +]; + +describe("buildNotes", () => { + const notes = buildNotes({ lecture, segments, pack, baseUrl }); + + it("links every point to its second in the session", () => { + expect(notes.watchUrl).toBe(`${baseUrl}/watch/${lecture.id}?t=0`); + expect(notes.concepts.map((c) => [c.name, c.label, c.url])).toEqual([ + ["Loss function", "0:15", `${baseUrl}/watch/${lecture.id}?t=15`], + ["Learning rate", "2:00", `${baseUrl}/watch/${lecture.id}?t=120`], + ]); + expect(notes.quiz[0]).toMatchObject({ answer: "Step size", label: "1:01" }); + }); + + it("builds chapters from consecutive segments with the same title", () => { + expect(notes.chapters.map((c) => [c.title, c.label])).toEqual([["Intro", "0:00"], ["Update rule", "1:00"]]); + }); + + it("still makes a useful sheet from chapters alone when there is no Study Pack", () => { + const bare = buildNotes({ lecture, segments, pack: null, baseUrl }); + expect(bare.summary).toEqual([]); + expect(hasContent(bare)).toBe(true); + expect(hasContent(buildNotes({ lecture, segments: [], pack: null, baseUrl }))).toBe(false); + }); +}); + +describe("notesToMarkdown", () => { + const md = notesToMarkdown(buildNotes({ lecture, segments, pack, baseUrl })); + + it("writes headings, timestamp links and the quiz answers", () => { + expect(md).toContain("# Gradient Descent: Basics"); + expect(md).toContain("Prof. Rao · 12:34 · [Watch the session](https://pravaha.test/watch/"); + expect(md).toContain("- **Learning rate** · [2:00](https://pravaha.test/watch/11111111-1111-4111-8111-111111111111?t=120)"); + expect(md).toContain("## Chapters"); + expect(md).toContain("1. What does the learning rate control?"); + expect(md).toContain(" - **Answer:** Step size"); + }); + + it("leaves out sections that are empty", () => { + const md2 = notesToMarkdown(buildNotes({ lecture, segments: [], pack: { ...pack, quiz: [] }, baseUrl })); + expect(md2).not.toContain("## Chapters"); + expect(md2).not.toContain("## Check yourself"); + expect(md2).toContain("## In short"); + }); +}); + +describe("notesFilename", () => { + it("makes a safe .md name", () => { + expect(notesFilename("Gradient Descent: Basics!")).toBe("gradient-descent-basics.md"); + expect(notesFilename("???")).toBe("study-notes.md"); + }); +}); From 489100bc983db756b54f2e0dbdc91a4b173f9804 Mon Sep 17 00:00:00 2001 From: im-rk Date: Sat, 3 Oct 2026 14:22:43 +0530 Subject: [PATCH 3/3] docs(phase-22): weak spots, study notes, API, README and e2e --- CHANGELOG.md | 2 + README.md | 2 + docs/API.md | 8 ++++ docs/DEMO.md | 2 + docs/IMPLEMENTATION_PLAN.md | 1 + .../phases/PHASE-22-weak-spots-study-notes.md | 19 ++++++++ openapi.yaml | 12 +++++ tests/e2e/revision.spec.ts | 45 +++++++++++++++++++ 8 files changed, 91 insertions(+) create mode 100644 docs/phases/PHASE-22-weak-spots-study-notes.md create mode 100644 tests/e2e/revision.spec.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 2e67fdd..9538be6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,8 @@ Format: [Keep a Changelog](https://keepachangelog.com/); versioning: [SemVer](ht ## [Unreleased] ### Added +- Weak spots on Saved: wrong quiz answers become a personal revision reel of the explanations you missed (Phase 22) +- Study notes `/notes/[id]` and `GET /api/lectures/[id]/notes`: a timestamp-linked study sheet per session, as Markdown or PDF (Phase 22) - Data saver: a header switch (automatic on Save-Data and 2G/3G) that serves lighter Cloudinary renditions and the `sd` streaming ladder; 33–76% fewer bytes measured (Phase 21) - Concept Map `/concepts` and Compare view `/concepts/[key]`: the same concept from every teacher as one Compare Reel (Phase 19) - Cloudinary asset index: tags and contextual metadata on each session's asset, synced from the Studio and read back with the Search API (Phase 19) diff --git a/README.md b/README.md index 1ffc23f..33eb937 100644 --- a/README.md +++ b/README.md @@ -78,6 +78,8 @@ Colleges, clubs and coaching institutes record hundreds of hours of lectures and | **Concept Map** | `/concepts` lines up every concept your lectures teach and how many different teachers explain it. Open one and hear the same idea from each lecturer, back to back, as one Cloudinary-spliced video, until one explanation clicks. | | **Learning Paths** | `/learn`: type a topic and get a 3–5 step course, ordered basics first, drawn from moments across the library and edited into one video. | | **Data saver** | One switch (and automatic on Save-Data or 2G/3G) serves smaller, lower-quality Cloudinary renditions: thumbnails 76% lighter, clips and reels 38–41%, and a streaming ladder that tops out at 0.9 Mbps instead of 3.4. Built for India’s mobile data. | +| **Weak spots** | Quiz mistakes are remembered on your device and come back as **one Cloudinary reel of exactly the explanations you missed**, with the answer and the second to jump to. Get a question right and it leaves the list. | +| **Study notes** | Every session has a study sheet at `/notes/[id]`: summary, key concepts, chapters and the quiz with answers, each point linked to its timestamp. Copy it as Markdown, download it, or save it as a PDF. | | **Study Packs** | Every session gets a summary, key concepts, a quiz whose explanations **play the moment** the teacher explains it, and a "Session in 60 seconds" highlight reel. Pravaha generates them automatically from the transcript. | | **Moments** | One tap turns any cited clip into a vertical, AI-cropped, subtitled short for WhatsApp or Instagram, with its own share page and preview card. The short is just a Cloudinary URL; nothing is rendered. | | **Insights** | Organizers see what learners ask, the **knowledge gaps** the library can't answer yet (what to record next), and which Moments get shared. Every report downloads as CSV. Visitors can explore a read-only demo of the Studio. | diff --git a/docs/API.md b/docs/API.md index ff04f4a..cb78633 100644 --- a/docs/API.md +++ b/docs/API.md @@ -160,3 +160,11 @@ Retrieval now rewrites a question into the library's vocabulary when it is in an ### `POST /api/organizer/index` · `GET /api/organizer/index` - **Auth:** organizer cookie (`401` otherwise) · `maxDuration` 60 s - `POST` writes tags and contextual metadata onto every session's Cloudinary asset, then returns `{ synced, skipped, assets }` read back with the Search API. `GET` returns just `{ assets: [{ publicId, tags, context }] }` + +## Phase 22 additions + +### `GET /api/lectures/[id]/notes` +- **Auth:** public (the unguessable session id is the access, like the Watch page) +- **Query:** `format=md` returns Markdown (`text/markdown`); add `download=1` for a `Content-Disposition: attachment` `.md` file. Without `format`, JSON +- **Response (JSON):** `{ title, speaker, durationS, watchUrl, summary[], concepts[{ name, t, label, url }], chapters[{ title, t, label, url }], quiz[{ question, answer, explanation, t, label, url }] }`; every `url` opens the session at that second +- **Errors:** `404` the session isn't ready, doesn't exist, or has no summary, chapters or quiz yet diff --git a/docs/DEMO.md b/docs/DEMO.md index ba4d40f..4be5b80 100644 --- a/docs/DEMO.md +++ b/docs/DEMO.md @@ -26,6 +26,8 @@ Never show setup, code, dashboards or waiting. Every shot is the problem, the pr | 2:24–2:35 | **Cloudinary under the hood** panel on the answer: each URL step explained | "Every clip, reel and short is a Cloudinary transformation, and Pravaha shows exactly which." | | 2:35–2:45 | Architecture strip: Cloudinary (transcription · chaptering · streaming · g_auto · e_preview · transformations) + Pravaha (retrieval · grounded Ask · Moments · Insights) · team | "Cloudinary turns video into data. Pravaha turns data into answers you can watch. Code Blooded, Track 3." | +**Study shots (if there is time):** answer a quiz question wrong → `/saved` → **Play my weak-spot reel** ("What you get wrong comes back as video.") → a session’s **Study notes** → **Download .md** ("Every point links to the second the teacher said it.") + **Bonus shot (if there is time):** header → **Data saver** on → the same answer reel and thumbnails reload visibly lighter. Voice-over: "Built for India’s mobile data: one switch, and Cloudinary serves everything at a fraction of the bytes." ## Pre-Recording Checklist diff --git a/docs/IMPLEMENTATION_PLAN.md b/docs/IMPLEMENTATION_PLAN.md index 67e4502..7fcd947 100644 --- a/docs/IMPLEMENTATION_PLAN.md +++ b/docs/IMPLEMENTATION_PLAN.md @@ -95,3 +95,4 @@ The core loop (Phases 01–09) is built and verified on real Cloudinary + Neon. | 18 | Query understanding, Learning Paths, AI reliability | Rewrite questions into the library's words (and translate them), honest near-miss answers, `/learn` micro-courses as one Cloudinary reel, circuit breaker + deep health | ✅ done (Oct 3) | | 19 | Concept Map & Cloudinary asset index | Same concept, every teacher, as one Compare Reel; tags + contextual metadata on Cloudinary assets, read back with the Search API | ✅ done (Oct 3) | | 21 | Data saver | Light Cloudinary renditions (35–76% fewer bytes, sd streaming ladder) for slow or metered connections; follows Save-Data and 2G/3G automatically | ✅ done (Oct 3) | +| 22 | Weak spots & study notes | Quiz mistakes become a personal revision reel; every session exports a timestamp-linked study sheet (Markdown / print) | ✅ done (Oct 3) | diff --git a/docs/phases/PHASE-22-weak-spots-study-notes.md b/docs/phases/PHASE-22-weak-spots-study-notes.md new file mode 100644 index 0000000..15b0f43 --- /dev/null +++ b/docs/phases/PHASE-22-weak-spots-study-notes.md @@ -0,0 +1,19 @@ +# Phase 22 — Weak spots and study notes + +**Status: DONE (Oct 3)** · branch `feature/weak-spots-study-notes` + +## Why +Study Packs already quiz a learner, but the result vanished when the tab closed, and a good session left nothing to take away. These two features close the loop: **what you got wrong comes back as video**, and **every session leaves a study sheet you can keep**. + +## What shipped +1. **Weak spots** (`src/lib/weak-spots.ts`, `src/components/WeakSpots.tsx`, Saved page): every quiz answer is recorded on this device (`saved.ts`). A wrong answer adds the question (newest first, no duplicates, 50 max); a right answer clears it. The Saved page lists each one with the correct answer, the teacher's explanation and a link to the second it is explained, plus **one Cloudinary reel** (`fl_splice`) of exactly those explanations across sessions, each clip labelled with its question. "I've got this" dismisses one. Nothing leaves the device. +2. **Study notes** (`/notes/[id]`, `GET /api/lectures/[id]/notes`, `src/lib/notes.ts`): a sheet per session built from the Study Pack and the AI chapters: summary, key concepts, chapters, and the quiz with answers. **Every point is linked to its timestamp.** Copy it as Markdown (Notion, Obsidian, a study group chat), download the `.md`, or print / save as PDF (the site header and footer are hidden when printing). The Markdown carries absolute links, so they work wherever it is pasted. It has its own share card. No AI call: it is instant and cannot contradict the session. The Watch page links to it. + +## Decisions +- Weak spots live in `localStorage`, like Saved moments: no account, no tracking, works offline from the Saved page. The cost is that they don't follow a learner to another device. Accounts would fix that, but they aren't worth the privacy cost here. +- Notes are built, not generated: a sheet that only reorganises verified Study Pack content can't hallucinate. A session with chapters but no Study Pack still gets a useful sheet; one with neither returns 404. +- The weak-spot reel reuses `reelUrl()`, so it inherits the 5-clip / 90-second cap and data saver. + +## Verification +- 13 new unit tests (`weak-spots`, `notes`). +- In a real browser against the real library: a wrong answer on a session's quiz appears under Weak spots on `/saved` with a reel; "I've got this" clears it. `/notes/[id]` renders 9 timestamp links; the Markdown export returns `text/markdown` with a `.md` attachment name; a bad id returns 404. diff --git a/openapi.yaml b/openapi.yaml index 2061082..89d22a0 100644 --- a/openapi.yaml +++ b/openapi.yaml @@ -492,3 +492,15 @@ paths: responses: '200': { description: Assets with tags and contextual metadata, content: { application/json: { schema: { type: object } } } } '401': { description: Not an organizer } + /lectures/{id}/notes: + get: + summary: A session's study notes, every point linked to its timestamp + operationId: getStudyNotes + security: [{}] + parameters: + - { name: id, in: path, required: true, schema: { type: string, format: uuid } } + - { name: format, in: query, required: false, schema: { type: string, enum: [md] }, description: 'md returns Markdown instead of JSON' } + - { name: download, in: query, required: false, schema: { type: string }, description: 'With format=md, send as an attachment' } + responses: + '200': { description: Notes as JSON, or Markdown with format=md, content: { application/json: { schema: { type: object } }, text/markdown: { schema: { type: string } } } } + '404': { description: No notes for this session, content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } } diff --git a/tests/e2e/revision.spec.ts b/tests/e2e/revision.spec.ts new file mode 100644 index 0000000..da6827c --- /dev/null +++ b/tests/e2e/revision.spec.ts @@ -0,0 +1,45 @@ +import { expect, test } from "@playwright/test"; + +// Weak spots and study notes against the deployed app (like smoke.spec.ts). + +async function firstSessionPath(page: import("@playwright/test").Page) { + await page.goto("/"); + const href = await page.locator('a[href^="/watch/"]').first().getAttribute("href"); + expect(href).toMatch(/^\/watch\/[0-9a-f-]{36}/); + return href!.split("?")[0]!; +} + +test("a wrong quiz answer becomes a weak spot with a revision reel, and clears when dismissed", async ({ page }) => { + await page.goto(await firstSessionPath(page)); + await page.getByRole("tab", { name: /study/i }).click(); + const first = page.locator("ol > li").filter({ hasText: "1." }).first(); + // Try each option until one is marked incorrect (the correct one can't be known from the page). + for (let i = 0; i < 4; i++) { + const q = page.locator("ol > li").filter({ hasText: "1." }).first(); + await q.locator("button").nth(i).click(); + if (await q.getByText("Not quite").count()) break; + await page.reload(); + await page.getByRole("tab", { name: /study/i }).click(); + } + await expect(first.getByText("Not quite")).toBeVisible(); + + await page.goto("/saved"); + await expect(page.getByRole("heading", { name: /Weak spots/ })).toBeVisible(); + await expect(page.getByRole("button", { name: /weak-spot reel/i })).toBeVisible(); + await page.getByRole("button", { name: /got this/i }).first().click(); + await expect(page.getByText(/collect here/)).toBeVisible(); +}); + +test("study notes list timestamps that link back into the session, and download as Markdown", async ({ page, request }) => { + const watch = await firstSessionPath(page); + const id = watch.replace("/watch/", ""); + await page.goto(`/notes/${id}`); + await expect(page.getByRole("button", { name: /Copy as Markdown/ })).toBeVisible(); + await expect(page.locator('a[href*="?t="]').first()).toBeVisible(); + + const md = await request.get(`/api/lectures/${id}/notes?format=md&download=1`); + expect(md.status()).toBe(200); + expect(md.headers()["content-type"]).toContain("text/markdown"); + expect(md.headers()["content-disposition"]).toContain(".md"); + expect(await md.text()).toMatch(/^# .+\n/); +});