Download src/video/tuition/fullChapterPlan.ts from asnannp/DocDoeAI: direct link, hf CLI and curl.
- Browser
- Download file 57 kB
-
https://huggingface.co/spaces/asnannp/DocDoeAI/resolve/main/src/video/tuition/fullChapterPlan.ts
- Command line
-
hf download hf://spaces/asnannp/DocDoeAI/src/video/tuition/fullChapterPlan.ts
-
curl -L -o fullChapterPlan.ts https://huggingface.co/spaces/asnannp/DocDoeAI/resolve/main/src/video/tuition/fullChapterPlan.ts
57 kB
/**
* Day 17 β a full ~40 minute, continuously-teaching Sound Waves chapter plan.
*
* Day 13-16 built a general 40-60 minute plan (`buildTuitionVideoPlan`) and a
* dedicated 8-10 minute segment (`buildFirstRealSegmentPlan`). Both proved a
* real problem in production: the general plan's non-concept segments
* (formula, worked_example, common_mistakes, board_answer, practice_sample,
* recap_revision) never got the Day14 "one short beat per scene" treatment,
* so a 40-minute render ended up with a single 187-second static scene for
* common_mistakes and another for recap_revision β exactly the "one board
* image for 2-4 minutes" complaint.
*
* This module applies that same fine-grained, teacher-paced treatment to
* EVERY subtopic across all seven Sound Waves missions (M1-M7), covering all
* 27 subtopics the chapter needs, with no scene longer than ~35 seconds and
* every scene carrying multiple short, sentence-by-sentence narration blocks
* instead of one long paragraph. Nothing is invented: every line traces back
* to the same curated M1-M7 seeds used everywhere else in this engine.
*/
import type { TuitionLessonSeed } from "../../lib/teaching/physicsLessonSeeds";
import { getSubjectStrategy } from "./subjectStrategies";
import {
mkNarration,
nextSceneId,
nextBeatId,
deriveRearrangements,
findNumericalSeedFor,
deriveWorkedExample,
firstSentence,
chapterSeeds,
SAMPLE_PRACTICE_NOTE,
} from "./lessonVideoPlan";
import {
TUITION_VIDEO_FPS,
TUITION_VIDEO_SCHEMA_VERSION,
type AttentionCue,
type BoardAction,
type NarrationBlock,
type TeachingBeat,
type TuitionSegmentKind,
type TuitionVideoPlan,
type TuitionVideoSegment,
type TuitionVideoSubject,
type VideoScene,
} from "./types";
export type BuildFullChapterPlanInput = {
classLevel: string;
board: string;
subject: TuitionVideoSubject;
chapter: string;
targetDurationMinutes?: number;
};
const DEFAULT_TARGET_MINUTES = 40;
/**
* Real Deepgram Aura audio measured ~171 wpm in an earlier synthesis run
* (16,756 characters -> 1,069.2s of real audio), against the shared 130wpm
* `subjectStrategies.ts` planning default every other part of this engine
* uses. Using the real rate here means the plan's *estimated* duration is a
* close proxy for the *real* rendered duration, so a content-volume tuning
* pass doesn't need several expensive TTS-and-render round trips to
* converge on the 38-42 minute band.
*/
const REAL_TTS_WPM = 172;
/**
* Day 20 β the duration band now measures PROJECTED SPOKEN minutes (narration
* estimate + injected think pauses), not `totalDurationSeconds`. The old
* metric added a 7-second board buffer per scene (~24 min across 200+ scenes)
* that the real audio-driven timeline never plays β which is exactly why the
* previous render "passed" a 38-42 estimate band and then came out at 25.9
* real minutes. Spoken minutes track the real class length: the Jul 6 render's
* spoken projection matched its 25.9-minute MP4 within ~10%.
*/
export const FULL_CHAPTER_DURATION_BAND = { min: 28, max: 60 };
/** Projected real speech minutes: narration estimates + injected pauses (no board buffers). */
export function estimateSpokenMinutes(plan: TuitionVideoPlan): number {
const blocks = plan.segments.flatMap((seg) => seg.scenes).flatMap((s) => s.narration);
const seconds = blocks.reduce((sum, n) => sum + n.estimatedSeconds + (n.pauseAfterSeconds ?? 0), 0);
return seconds / 60;
}
const SEGMENT_TITLES: Record<TuitionSegmentKind, string> = {
opening: "Opening β today's lesson goal",
concept: "Concept teaching",
visual_board: "Diagrams and board work",
formula: "Formula and wave quantities",
worked_example: "Worked numerical method",
common_mistakes: "Common mistakes to avoid",
board_answer: "Board-style exam answers",
practice_sample: "Sample practice questions",
recap_revision: "Recap and revision",
homework: "Homework and next step",
};
/** Split a longer explanation into short, sentence-paced chunks (same rule as Day 16). */
const DECIMAL_POINT_PLACEHOLDER = "\u0000";
function splitIntoShortSentences(text: string, maxWords = 16): string[] {
// Protect decimal points (e.g. "0.1 s", "1.5 m") from being treated as a
// sentence boundary below β otherwise a number like "0.1" is torn into
// "0." and "1 ...", corrupting the reading.
const protectedText = text.replace(/(\d)\.(\d)/g, `$1${DECIMAL_POINT_PLACEHOLDER}$2`);
const rawSentences =
protectedText
.match(/[^.!?]+[.!?]?/g)
?.map((s) => s.trim().split(DECIMAL_POINT_PLACEHOLDER).join("."))
.filter(Boolean) ?? [text];
// Drop any fragment that is pure punctuation/whitespace once trimmed (e.g.
// the isolated "." a "..." flashcard separator produces once the sentence
// regex above splits on each dot individually) β a real bug found by
// reviewing a rendered still where a scene's spoken/subtitle line was
// literally ".". A naturally short but COMPLETE sentence (e.g. a curated
// "No example" common-mistake note, 2 words) is real content and must not
// be dropped here just for being short β a real bug found by tracing a
// "stuck" 16s voice gap back to two such short mistakes silently
// disappearing (each was the only "sentence" in its own text, so the old
// fold-into-previous logic had nothing to fold into and skipped them
// entirely). Only the word-count-splitting loop below can produce a
// genuine orphan tail fragment (e.g. "on." split off a 17-word sentence),
// and that is where the fold-back logic belongs.
const sentences = rawSentences.filter((s) => /[a-zA-Z0-9]/.test(s));
const parts: string[] = [];
for (const sentence of sentences) {
const words = sentence.split(/\s+/).filter(Boolean);
if (words.length <= maxWords) {
parts.push(sentence);
continue;
}
// Prefer splitting at a clause boundary (comma, semicolon, en/em dash)
// near the middle of a long sentence over a raw word-count cut β a raw
// cut can strand a tiny tail chunk like "on." by itself, which reads as
// a broken mid-sentence pause. Look for the clause boundary closest to
// (but not past) the maxWords mark.
let remaining = words;
while (remaining.length > maxWords) {
const window = remaining.slice(0, maxWords + 4);
let splitAt = -1;
for (let i = Math.min(maxWords, window.length) - 1; i >= Math.floor(maxWords * 0.5); i--) {
// A standalone dash token (its own word, e.g. "medium β it needs")
// must start the NEXT chunk, not trail the current one β splitting
// after it left a real bug ("...through a material medium β" as its
// own dangling line, found by reviewing a rendered still).
if (/^[,;β-]+$/.test(window[i])) {
splitAt = i;
break;
}
if (/[,;β-]$/.test(window[i])) {
splitAt = i + 1;
break;
}
}
if (splitAt === -1) splitAt = maxWords;
const chunk = remaining.slice(0, splitAt).join(" ");
parts.push(chunk);
remaining = remaining.slice(splitAt);
}
if (remaining.length > 0) {
// Never leave a tail shorter than 3 words dangling on its own β fold
// it back into the previous chunk instead of emitting an orphan like
// "on." as its own line.
if (remaining.length < 3 && parts.length > 0) {
parts[parts.length - 1] = `${parts[parts.length - 1]} ${remaining.join(" ")}`;
} else {
parts.push(remaining.join(" "));
}
}
}
return parts.filter(Boolean);
}
const DIGIT_WORDS = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"];
function digitsToWords(digits: string): string {
return digits.split("").map((d) => DIGIT_WORDS[Number(d)]).join(" ");
}
/**
* TTS-input-only transform: "0.1 second" -> "zero point one second". Only
* decimals change β whole numbers like "340 m/s" are left as numerals since
* TTS engines already read plain integers correctly. Never apply this to
* `narration.text` itself (board/subtitle text must keep the written form a
* student would actually copy) β only to the text handed to a TTS provider.
*/
export function toSpokenForm(text: string): string {
let spoken = text.replace(/(\d+)\.(\d+)/g, (_match, whole: string, frac: string) => {
const wholeWord = whole === "0" ? "zero" : digitsToWords(whole);
return `${wholeWord} point ${digitsToWords(frac)}`;
});
// Replace common physics Greek letters with their spoken names
spoken = spoken.replace(/Ξ»/g, "lambda");
spoken = spoken.replace(/ΞΌ/g, "mu");
spoken = spoken.replace(/ΞΈ/g, "theta");
spoken = spoken.replace(/Ξ©/g, "ohms");
return spoken;
}
/**
* Scene duration for the audio-driven pipeline: narration time (the real
* cost, since audio drives the video) plus a small fixed buffer for board
* activity, not the full additive board-action cost `sceneDurationFromContent`
* uses elsewhere. Board actions still render β and still count fully toward
* the visual-action density target β but they animate concurrently with
* narration (chalk reveals, diagram draws) rather than as silent dead time
* tacked on afterward, so they should not inflate scene length on their own.
* This keeps voice/visual gaps short instead of leaving one big silent tail
* per scene once real TTS audio replaces the word-count estimate.
*/
const BOARD_BUFFER_SECONDS = 7;
function computeSceneDuration(narration: NarrationBlock[], board: BoardAction[]): number {
const narrationTotal = narration.reduce((sum, n) => sum + n.estimatedSeconds, 0);
return Math.max(8, narrationTotal + (board.length > 0 ? BOARD_BUFFER_SECONDS : 0));
}
type PushSceneOptions = {
diagram?: VideoScene["diagram"];
diagramKind?: VideoScene["diagramKind"];
hasMedium?: boolean;
examAnswer?: VideoScene["examAnswer"];
recap?: VideoScene["recap"];
practice?: VideoScene["practice"];
formula?: VideoScene["formula"];
splitScreen?: VideoScene["splitScreen"];
quiz?: VideoScene["quiz"];
hotspot?: VideoScene["hotspot"];
};
/**
* Build one micro-teaching scene: short sentence-paced narration blocks +
* matching board actions, kept to a real teacher's pace (~15-30s). This is
* the single building block every subtopic below is made from.
*/
function buildMicroScene(
segmentKind: TuitionSegmentKind,
title: string,
text: string,
wpm: number,
opts: PushSceneOptions & { attentionCue?: AttentionCue; emphasisWords?: string[]; beatKind?: TeachingBeat["kind"] } = {},
): VideoScene {
const parts = splitIntoShortSentences(text);
const narration: NarrationBlock[] = parts.map((part, i) =>
mkNarration(nextSceneId(segmentKind), part, wpm, undefined, opts.emphasisWords, i === 0 ? opts.attentionCue : undefined),
);
// A scene with `teachingBeats` renders via ConceptBeatsCard, which reads
// `beat.kind`/`beat.attentionCue` for its icon and badge β it never reads
// `boardActions` type. So the board action here is pure duration-cost
// bookkeeping (it still counts toward the visual-action density target);
// using the cheapest type keeps that count without inflating scene length.
// Day 20 exception: notebook beats DO write a real `notebook_note` action β
// it is the machine-checkable marker that a copy moment carries a visible
// note (the master-teacher checker fails any copy cue without one), and the
// default (non-beats) render branch uses it to draw the NotebookNote card.
const board: BoardAction[] = [{ type: "write_heading", text: title }];
parts.forEach((part) =>
board.push(opts.beatKind === "notebook" ? { type: "notebook_note", text: part } : { type: "highlight", text: part }),
);
const beat: TeachingBeat = {
id: nextBeatId(),
kind: opts.beatKind ?? "explain",
text,
attentionCue: opts.attentionCue,
emphasisWords: opts.emphasisWords,
};
return {
id: nextSceneId(segmentKind),
title,
segmentKind,
subject: "Physics",
chapter: "Sound Waves",
durationSeconds: computeSceneDuration(narration, board),
narration,
onScreenText: [title, ...parts],
visualInstructions: ["Reveal the beat and hold"],
boardActions: board,
teachingBeats:
opts.diagram || opts.examAnswer || opts.recap || opts.practice || opts.formula || opts.splitScreen || opts.quiz || opts.hotspot
? undefined
: [beat],
diagram: opts.diagram,
diagramKind: opts.diagramKind,
hasMedium: opts.hasMedium,
examAnswer: opts.examAnswer,
recap: opts.recap,
practice: opts.practice,
formula: opts.formula,
splitScreen: opts.splitScreen,
quiz: opts.quiz,
hotspot: opts.hotspot,
cursorPlan: [opts.beatKind === "notebook" ? "Hold on the notebook note so the student can copy" : "Point to the beat as it is spoken"],
recapNote: firstSentence(text),
};
}
/**
* Build one scene from SEVERAL short, already-authored texts (e.g. every
* keyNote, or a quiz question + answer + explanation), one narration block
* per text. This is how a scene stays real-teacher-dense (several short
* sentences) without inventing anything: it just uses more of what the
* curated seed already says, instead of only its headline field.
*/
function buildMultiTextScene(
segmentKind: TuitionSegmentKind,
title: string,
texts: string[],
wpm: number,
opts: PushSceneOptions & { attentionCue?: AttentionCue; beatKind?: TeachingBeat["kind"] } = {},
): VideoScene {
const flat = texts.flatMap((t) => splitIntoShortSentences(t));
const narration: NarrationBlock[] = flat.map((part, i) =>
mkNarration(nextSceneId(segmentKind), part, wpm, undefined, undefined, i === 0 ? opts.attentionCue : undefined),
);
// Same reasoning as buildMicroScene: boardActions here are duration-cost
// bookkeeping for a teachingBeats-driven scene (ConceptBeatsCard renders
// from `beat.kind`/`beat.attentionCue`, not from this array), so every
// entry uses the cheapest type. Count still matches the text count, which
// is what the visual-action density target measures.
const board: BoardAction[] = [{ type: "write_heading", text: title }];
// Board-action count no longer drives scene duration (see
// computeSceneDuration), so every line gets its own visual action β
// this is what keeps the visual-action gap short across a long,
// many-line scene instead of only the first couple of lines.
// Day 20 β notebook lines write real `notebook_note` actions (see the
// matching note in buildMicroScene): the marker the copy-note checker
// verifies, and the note text the NotebookNote card renders from.
flat.forEach((text) =>
board.push(opts.beatKind === "notebook" ? { type: "notebook_note", text } : { type: "highlight", text }),
);
// One beat per line, not one beat joining every line with `.join(" ")` β
// the joined form read as an unpunctuated run-on wall of text on the board
// (a real bug found by reviewing a rendered still: several distinct recap
// points glued into one sentence with no separators). ConceptBeatsCard
// already renders a list of beats as separate bulleted lines, so this is
// the correct shape for a multi-line scene; only the first beat keeps the
// attention cue, matching the narration blocks above.
// Day 20 β a "question" scene only marks its actual question lines with the
// question kind (the "?" icon); its statement lines are plain "explain"
// beats. Before this, an intro line like "Now let's measure the speed of a
// wave." rendered with a "?" glyph because the whole scene was kind
// "question" (verified on a baseline still β every line had "?").
const kindFor = (text: string): TeachingBeat["kind"] => {
const kind = opts.beatKind ?? "explain";
if (kind !== "question") return kind;
return text.trim().endsWith("?") ? "question" : "explain";
};
const beats: TeachingBeat[] = flat.map((text, i) => ({
id: nextBeatId(),
kind: kindFor(text),
text,
attentionCue: i === 0 ? opts.attentionCue : undefined,
}));
return {
id: nextSceneId(segmentKind),
title,
segmentKind,
subject: "Physics",
chapter: "Sound Waves",
durationSeconds: computeSceneDuration(narration, board),
narration,
onScreenText: [title, ...flat],
visualInstructions: ["Reveal each line and hold"],
boardActions: board,
teachingBeats: beats,
cursorPlan: [opts.beatKind === "notebook" ? "Hold on the notebook note so the student can copy" : "Point to each line as it is spoken"],
recapNote: flat[0] ?? title,
};
}
/** A dedicated diagram/board-frame scene, reusing the mission's own visualBoard frame. */
function buildFrameScene(
segmentKind: TuitionSegmentKind,
frame: TuitionLessonSeed["visualBoard"]["frames"][number],
wpm: number,
diagramKind?: VideoScene["diagramKind"],
hasMedium?: boolean,
): VideoScene {
const spokenText = `${frame.title}. ${frame.teacherAction} ${frame.studentFocus}`;
const parts = splitIntoShortSentences(spokenText);
const narration = parts.map((part) => mkNarration(nextSceneId(segmentKind), part, wpm));
const board: BoardAction[] = [
{ type: "write_heading", text: frame.title },
{ type: "draw", description: frame.diagramDescription ?? frame.title },
...frame.boardText.map((t): BoardAction => ({ type: "highlight", text: t })),
];
return {
id: nextSceneId(segmentKind),
title: frame.title,
segmentKind,
subject: "Physics",
chapter: "Sound Waves",
durationSeconds: computeSceneDuration(narration, board),
narration,
onScreenText: [frame.title, ...frame.boardText],
visualInstructions: [frame.teacherAction, "Draw in order", "Pause for the student to copy"],
boardActions: board,
diagram: {
title: frame.title,
description: frame.diagramDescription ?? frame.title,
labels: frame.boardText,
drawSteps: [frame.teacherAction],
imageUrl: frame.imageUrl,
},
diagramKind,
hasMedium,
cursorPlan: ["Trace the diagram as it is spoken"],
recapNote: frame.studentFocus,
};
}
/**
* A checkpoint scene for the mission's misconception check, plus one short
* scene per quiz item (question -> pause -> answer + explanation). Kept as
* separate scenes (not one crammed scene) so each stays in the ~15-25s
* range instead of one scene absorbing every quiz item's narration.
*/
/**
* A bare fill-in-the-blank quiz answer (e.g. "longitudinal", "hertz") has no
* capital letter or terminal punctuation of its own β concatenating it
* directly with the explanation sentence that follows produced a real bug
* ("Answer: longitudinal Particles vibrate...", found by reviewing a
* rendered still) that reads as one broken run-on. Answers that are already
* complete sentences (e.g. "Compressions and rarefactions.") pass through
* unchanged since they already end in punctuation.
*/
function normalizeQuizAnswer(answer: string): string {
const trimmed = answer.trim();
const withPeriod = /[.!?]$/.test(trimmed) ? trimmed : `${trimmed}.`;
return withPeriod.charAt(0).toUpperCase() + withPeriod.slice(1);
}
/**
* Checkpoint (misconception check), then one Question-only scene followed
* by its own separate Answer-only scene for every quiz item, then a
* notebook scene (trick + keyNotes). Question and Answer used to share one
* scene β a real bug found by reviewing a rendered still: both were visible
* on screen together with no think-time in between, instead of a question
* the student can attempt before the answer appears.
*/
function buildCheckpointAndNotebookScene(segmentKind: TuitionSegmentKind, seed: TuitionLessonSeed, wpm: number): VideoScene[] {
const scenes: VideoScene[] = [];
scenes.push(
buildMicroScene(segmentKind, seed.missionTitle, seed.recall.misconceptionCheck, wpm, {
attentionCue: "pause_and_think",
beatKind: "checkpoint",
}),
);
for (const q of seed.quiz) {
// Day 20 β the question scene now ENDS with a spoken "pause and try"
// beat plus injected audio silence, so the think time is real (in the
// narration track) instead of only implied by the scene cut.
const questionScene = buildMultiTextScene(
segmentKind,
seed.missionTitle,
[`Question: ${q.question}`, "Pause and try this yourself first."],
wpm,
{ beatKind: "checkpoint", attentionCue: "pause_and_think" },
);
const lastBlock = questionScene.narration[questionScene.narration.length - 1];
if (lastBlock) lastBlock.pauseAfterSeconds = 2.5;
scenes.push(questionScene);
scenes.push(
buildMicroScene(segmentKind, seed.missionTitle, `Answer: ${normalizeQuizAnswer(q.answer)} ${q.explanation}`.trim(), wpm, {
beatKind: "checkpoint",
attentionCue: "exam_point",
}),
);
}
const trickText = seed.docDoeTrick
? [`Remember this with: ${seed.docDoeTrick.title}.`, `${seed.docDoeTrick.trick} ${seed.docDoeTrick.whyItWorks}`]
: [];
if (trickText.length > 0) {
scenes.push(
buildMultiTextScene(segmentKind, seed.missionTitle, trickText, wpm, {
attentionCue: "copy_this",
beatKind: "notebook",
}),
);
}
return scenes;
}
/**
* Hook (+ what a good answer includes) + explain blocks + example +
* checkpoint (+ every quiz item as a Q&A check) + notebook (every keyNote),
* shared by every concept-style mission. Every extra line here is a real
* field from the seed that earlier days left unused β not invented text.
*/
function buildMalayalamSupportScenes(
segmentKind: TuitionSegmentKind,
seed: TuitionLessonSeed,
wpm: number,
): VideoScene[] {
const support = seed.teach.manglishSupport?.trim();
if (!support) return [];
return [
buildMicroScene(segmentKind, `${seed.missionTitle} β Malayalam support`, support, wpm, {
beatKind: "explain",
}),
];
}
function buildConceptCore(seed: TuitionLessonSeed, wpm: number): VideoScene[] {
const scenes: VideoScene[] = [];
// Hook + question ONLY β a real bug found by reviewing a rendered still:
// this scene used to immediately follow its own recall question with
// "Good answers include: ..." on the very same screen, giving the student
// zero think time. That reveal now happens in its own scene after the
// explanation blocks below, so there is real teaching in between the
// question and its answer.
// Day 20 β the mission OPENS with its one-line hook question (seed.hookLine)
// before any definition, and the recall question gets injected think
// silence. The "important" cue is gone from intros: it fired on every
// mission's greeting line, which taught students to ignore it.
const opener = buildMultiTextScene(
"concept",
seed.missionTitle,
[...(seed.hookLine ? [seed.hookLine] : []), seed.teach.teacherIntro, seed.recall.prompt],
wpm,
{ beatKind: "question" },
);
const openerLast = opener.narration[opener.narration.length - 1];
if (openerLast) openerLast.pauseAfterSeconds = 2;
scenes.push(opener);
if (seed.teach.analogy) {
scenes.push(buildMicroScene("concept", seed.missionTitle, seed.teach.analogy, wpm, { beatKind: "example" }));
}
for (const block of seed.teach.explanationBlocks) {
scenes.push(buildMicroScene("concept", block.heading, block.explanation, wpm, { emphasisWords: block.keyTerms }));
}
scenes.push(...buildMalayalamSupportScenes("concept", seed, wpm));
scenes.push(
buildMicroScene("concept", seed.missionTitle, `Good answers include: ${seed.recall.expectedPoints.join(". ")}.`, wpm, {
beatKind: "checkpoint",
attentionCue: "exam_point",
}),
);
// Day 18 β a dedicated "Copy this" scene straight from the seed's own
// keyNotes, before the combined checkpoint+notebook scene below (which
// still carries the DocDoe trick + overflow quiz items). This gives every
// mission's headline notebook lines their own clearly-labelled moment
// instead of only appearing bundled with the trick/quiz overflow.
if (seed.keyNotes.length > 0) {
scenes.push(
buildMultiTextScene("concept", seed.missionTitle, seed.keyNotes, wpm, { beatKind: "notebook", attentionCue: "copy_this" }),
);
}
scenes.push(...buildCheckpointAndNotebookScene("concept", seed, wpm));
if (seed.splitScreen) {
const text = "Notice the difference. " + seed.splitScreen.left.caption + " " + seed.splitScreen.right.caption;
scenes.push(buildMicroScene("concept", seed.missionTitle, text, wpm, { splitScreen: seed.splitScreen }));
}
if (seed.hotspot) {
const text = "Pay close attention here. " + seed.hotspot.importantNote;
scenes.push(buildMicroScene("concept", seed.missionTitle, text, wpm, { hotspot: seed.hotspot }));
}
if (seed.quizTimer) {
const text = "Time for a quick check. " + seed.quizTimer.question;
scenes.push(buildMicroScene("concept", seed.missionTitle, text, wpm, { quiz: seed.quizTimer }));
}
return scenes;
}
// Day 20 β frame titles that get a dedicated small SVG diagram instead of
// the generic DiagramFrame text scaffold (which showed the diagram's plain
// description as on-screen text β readable as an unfinished placeholder).
// Matched by title (stable across missions) rather than mission id + index,
// since "Sound reflects"/"0.1 second rule" and "SONAR"/"Ultrasound" each
// recur in more than one mission's visual_board frames.
const TITLE_TO_DIAGRAM_KIND: Record<string, VideoScene["diagramKind"]> = {
"Sound reflects": "reflection",
"0.1 second rule": "timing",
SONAR: "sonar",
Ultrasound: "ultrasound",
};
/** Diagram scenes for a mission's visualBoard frames, in `visual_board`. */
function buildDiagramScenes(seed: TuitionLessonSeed, wpm: number): VideoScene[] {
return seed.visualBoard.frames.map((frame, i) => {
const isM1 = seed.missionId === "M1";
const diagramKind = isM1 && i === 0 ? "vibration" : isM1 && (i === 1 || i === 2) ? "medium" : TITLE_TO_DIAGRAM_KIND[frame.title];
const hasMedium = isM1 && i === 2 ? false : isM1 && i === 1 ? true : undefined;
return buildFrameScene("visual_board", frame, wpm, diagramKind, hasMedium);
});
}
/**
* Exam-keywords scene (every answer point, correctly labelled "Exam
* keywords") and a SEPARATE common-mistake scene (correctly labelled
* "Common mistake") β these used to be one scene where the mistake line
* incorrectly carried the exam_point beat kind/star icon. Splitting them is
* also part of the Day 18 duration expansion: one merged scene becomes two.
*/
function buildExamPointAndMistake(seed: TuitionLessonSeed, wpm: number): VideoScene[] {
const exam = seed.examAnswers[0];
if (!exam) return [];
// Day 20 β the "Exam keywords" scene now shows the exam KEYWORDS (the
// seed's own scoring words), not the full answer points: the label used to
// say "Exam keywords" over answer sentences, while the actual keywords were
// never shown anywhere on screen. Full answers still teach in the dedicated
// board_answer segment.
const scenes: VideoScene[] = [
buildMultiTextScene(
"concept",
seed.missionTitle,
[
`These are the words examiners look for: ${exam.keywords.join(", ")}.`,
`Use them in your answer to: ${exam.question}`,
],
wpm,
{
attentionCue: "exam_point",
beatKind: "exam_point",
},
),
];
for (const mistake of exam.commonMistakes) {
// Day 20 β no attentionCue: see the matching note in buildTeachingSection.
scenes.push(buildMicroScene("concept", seed.missionTitle, `Common mistake: ${mistake}`, wpm, { beatKind: "mistake" }));
}
return scenes;
}
/** Mini recap scenes closing out a mission β summary/must-remember, then its flashcards, kept as two short scenes. */
function buildMissionRecap(seed: TuitionLessonSeed, wpm: number): VideoScene[] {
const scenes = [
buildMultiTextScene(
"concept",
`${seed.missionTitle} β recap`,
[...seed.recap.summary, ...seed.recap.mustRemember, ...seed.revisionSave.revisionNotes],
wpm,
{ beatKind: "explain" },
),
];
// One scene per flashcard, not all of a mission's flashcards bundled into
// one scene β bundling them showed every card's front AND back at once
// (a real bug found by reviewing a rendered still: a "flashcards" scene
// with several Q/A pairs all visible together, no actual flip/reveal).
for (const f of seed.revisionSave.flashcards) {
scenes.push(
buildMicroScene("concept", `${seed.missionTitle} β flashcards`, `${f.front} Answer: ${f.back}`, wpm, { beatKind: "explain" }),
);
}
return scenes;
}
/* ------------------------------ per-mission builders ------------------------------ */
function buildConceptScenes(seed: TuitionLessonSeed, wpm: number): VideoScene[] {
return [...buildConceptCore(seed, wpm), ...buildDiagramScenes(seed, wpm), ...buildExamPointAndMistake(seed, wpm), ...buildMissionRecap(seed, wpm)];
}
/**
* Day 20 β a short "so far you learned" bridge after every second mission:
* reconnects the ideas just taught (their own must-remember lines) before the
* class moves on, so a weak student never loses the thread of the chapter.
*/
function buildBridgeScene(covered: TuitionLessonSeed[], wpm: number, segmentKind: TuitionSegmentKind): VideoScene {
const learnedLines = covered.map((s) => `${s.missionTitle}: ${s.recap.mustRemember[0] ?? s.recap.summary[0] ?? ""}`.trim());
const last = covered[covered.length - 1];
const keyword = last.examAnswers[0]?.keywords[0];
return buildMultiTextScene(
segmentKind,
"So far, you learned",
[
"Before we move on, connect what you just learned.",
...learnedLines,
...(keyword ? [`The exam word to remember here is: ${keyword}.`] : []),
],
wpm,
{ beatKind: "recap" },
);
}
/** Formula-mission scenes (currently M4 β Frequency, Wavelength and Wave Speed). */
function buildFormulaScenes(seed: TuitionLessonSeed, allSeeds: TuitionLessonSeed[], wpm: number): VideoScene[] {
const scenes: VideoScene[] = [];
// Day 20 β the recall question is NO LONGER bundled with its own
// "Good answers include: ..." reveal (both were on one screen β verified on
// a baseline still). The question scene ends with injected think silence;
// the reveal happens in its own scene after the explanation blocks, same as
// buildConceptCore. The "important" cue is gone from the greeting line.
const opener = buildMultiTextScene(
"formula",
seed.missionTitle,
[...(seed.hookLine ? [seed.hookLine] : []), seed.teach.teacherIntro, seed.recall.prompt],
wpm,
{ beatKind: "question" },
);
const openerLast = opener.narration[opener.narration.length - 1];
if (openerLast) openerLast.pauseAfterSeconds = 2;
scenes.push(opener);
if (seed.teach.analogy) scenes.push(buildMicroScene("formula", seed.missionTitle, seed.teach.analogy, wpm, { beatKind: "example" }));
for (const block of seed.teach.explanationBlocks) {
scenes.push(buildMicroScene("formula", block.heading, block.explanation, wpm, { emphasisWords: block.keyTerms }));
}
scenes.push(...buildMalayalamSupportScenes("formula", seed, wpm));
scenes.push(
buildMicroScene("formula", seed.missionTitle, `Good answers include: ${seed.recall.expectedPoints.join(". ")}.`, wpm, {
beatKind: "checkpoint",
}),
);
scenes.push(...seed.visualBoard.frames.map((frame) => buildFrameScene("formula", frame, wpm)));
const primaryFormula = seed.formulas[0];
// Day 20 β before the formula card appears, one spoken line explains WHY
// this formula exists (its use), so the formula lands as a tool rather than
// a fact to memorise. Uses the formula's own curated commonUseCase text.
if (primaryFormula?.commonUseCase) {
scenes.push(
buildMicroScene(
"formula",
seed.missionTitle,
`Why do we need a formula here? Because in the exam you will be asked: ${primaryFormula.commonUseCase} This one formula answers all of those.`,
wpm,
{ beatKind: "explain" },
),
);
}
if (primaryFormula) {
const rearrangements = deriveRearrangements(primaryFormula);
const numericalSeed = findNumericalSeedFor(primaryFormula, allSeeds);
const workedExample = deriveWorkedExample(numericalSeed);
scenes.push({
id: nextSceneId("formula"),
title: primaryFormula.formula,
segmentKind: "formula",
subject: "Physics",
chapter: "Sound Waves",
durationSeconds: computeSceneDuration(
[mkNarration(nextSceneId("formula"), primaryFormula.meaning, wpm)],
[{ type: "write_heading", text: primaryFormula.formula }],
),
narration: [
mkNarration(nextSceneId("formula"), primaryFormula.meaning, wpm),
...(rearrangements ? [mkNarration(nextSceneId("formula"), `We can rearrange it: ${rearrangements.join(", or ")}.`, wpm)] : []),
],
onScreenText: [primaryFormula.formula, primaryFormula.meaning],
visualInstructions: ["Reveal the formula box, then the symbols"],
boardActions: [
{ type: "write_heading", text: primaryFormula.formula },
{ type: "write_line", text: primaryFormula.meaning },
...primaryFormula.symbols.map((s): BoardAction => ({ type: "highlight", text: `${s.symbol} = ${s.meaning}` })),
],
layout: "formulaWithSymbols",
formula: {
formula: primaryFormula.formula,
meaning: primaryFormula.meaning,
symbols: primaryFormula.symbols,
rearrangements,
workedExample,
},
cursorPlan: ["Point to each symbol as it is named"],
recapNote: primaryFormula.meaning,
});
}
const secondaryFormula = seed.formulas[1];
if (secondaryFormula) {
scenes.push(
buildMicroScene("formula", secondaryFormula.formula, secondaryFormula.meaning, wpm, { emphasisWords: [secondaryFormula.formula] }),
);
}
if (seed.keyNotes.length > 0) {
scenes.push(
buildMultiTextScene("formula", seed.missionTitle, seed.keyNotes, wpm, { beatKind: "notebook", attentionCue: "copy_this" }),
);
}
scenes.push(...buildCheckpointAndNotebookScene("formula", seed, wpm).map((s) => ({ ...s, segmentKind: "formula" as const })));
scenes.push(...buildExamPointAndMistake(seed, wpm).map((s) => ({ ...s, segmentKind: "formula" as const })));
scenes.push(...buildMissionRecap(seed, wpm).map((s) => ({ ...s, segmentKind: "formula" as const })));
return scenes;
}
/** Numerical-mission scenes (currently M5 β Numericals using v = fΞ»), in `worked_example`. */
function buildWorkedExampleScenes(seed: TuitionLessonSeed, wpm: number): VideoScene[] {
const scenes: VideoScene[] = [];
// Day 20 β hook-first opener with injected think silence; "important" cue
// dropped (see buildConceptCore).
const opener = buildMultiTextScene(
"worked_example",
seed.missionTitle,
[...(seed.hookLine ? [seed.hookLine] : []), seed.teach.teacherIntro, seed.recall.prompt],
wpm,
{ beatKind: "question" },
);
const openerLast = opener.narration[opener.narration.length - 1];
if (openerLast) openerLast.pauseAfterSeconds = 2;
scenes.push(opener);
for (const block of seed.teach.explanationBlocks) {
scenes.push(buildMicroScene("worked_example", block.heading, block.explanation, wpm, { emphasisWords: block.keyTerms }));
}
scenes.push(...buildMalayalamSupportScenes("worked_example", seed, wpm));
scenes.push(...seed.visualBoard.frames.map((frame) => buildFrameScene("worked_example", frame, wpm)));
// Day 20 β every fully-stepped exam numerical teaches as its own sequence:
// read the question β given values β formula β each substitute/solve step β
// final answer with unit (a notebook moment) β the unit-trap warning. All
// text comes from the seed's own examAnswers; nothing is invented here.
if (seed.contentType === "numerical") {
const formulaText = seed.formulas[0]?.formula;
seed.examAnswers.forEach((exam, exampleIndex) => {
const readScene = buildMultiTextScene(
"worked_example",
`Worked numerical ${exampleIndex + 1}`,
[`Read the question carefully: ${exam.question}`, "Pause and note down what is given."],
wpm,
{ beatKind: "question", attentionCue: "pause_and_think" },
);
const readLast = readScene.narration[readScene.narration.length - 1];
if (readLast) readLast.pauseAfterSeconds = 2.5;
scenes.push(readScene);
const [given, ...working] = exam.answerPoints;
if (given) {
scenes.push(buildMicroScene("worked_example", "Step 1 β Given", given, wpm, { beatKind: "explain" }));
}
if (formulaText) {
scenes.push(
buildMicroScene("worked_example", "Step 2 β Formula", `We use ${formulaText}.`, wpm, {
beatKind: "explain",
emphasisWords: [formulaText],
}),
);
}
working.forEach((step, i) => {
const isLast = i === working.length - 1;
scenes.push(
buildMicroScene(
"worked_example",
isLast ? "Final answer" : `Step ${3 + i} β Substitute and solve`,
isLast ? `${step} Always write the unit with the final answer.` : step,
wpm,
{ beatKind: isLast ? "notebook" : "explain", attentionCue: isLast ? "copy_this" : undefined },
),
);
});
for (const trap of exam.commonMistakes) {
scenes.push(
buildMicroScene("worked_example", `Worked numerical ${exampleIndex + 1}`, `Common mistake: ${trap}. Most students lose marks exactly here.`, wpm, {
beatKind: "mistake",
}),
);
}
});
}
// Day 18 β the four-step numerical method from the mission's own yourTurn,
// each step its own paced scene. Kept for non-numerical worked examples.
if (seed.contentType !== "numerical" && seed.yourTurn) {
const [given, formulaStep, substitute, answer] = seed.yourTurn.expectedAnswerPoints;
const steps: Array<[string, string | undefined]> = [
["Step 1 β Given", given],
["Step 2 β Formula", formulaStep],
["Step 3 β Substitute", substitute],
["Step 4 β Answer", answer],
];
for (const [heading, text] of steps) {
if (text) scenes.push(buildMicroScene("worked_example", heading, text, wpm, { beatKind: "explain" }));
}
}
scenes.push(...buildCheckpointAndNotebookScene("worked_example", seed, wpm).map((s) => ({ ...s, segmentKind: "worked_example" as const })));
scenes.push(...buildExamPointAndMistake(seed, wpm).map((s) => ({ ...s, segmentKind: "worked_example" as const })));
scenes.push(...buildMissionRecap(seed, wpm).map((s) => ({ ...s, segmentKind: "worked_example" as const })));
return scenes;
}
/** Collect every distinct common mistake across all missions, one short scene each, in `common_mistakes`. */
function buildCommonMistakesScenes(seeds: TuitionLessonSeed[], wpm: number): VideoScene[] {
const seen = new Set<string>();
const mistakes: string[] = [];
for (const seed of seeds) {
for (const exam of seed.examAnswers) {
for (const mistake of exam.commonMistakes) {
if (!seen.has(mistake)) {
seen.add(mistake);
mistakes.push(mistake);
}
}
}
}
const scenes: VideoScene[] = [];
for (let i = 0; i < mistakes.length; i += 2) {
// Day 20 β no attentionCue: see the matching note in buildTeachingSection.
scenes.push(buildMultiTextScene("common_mistakes", "Common mistake", mistakes.slice(i, i + 2), wpm, { beatKind: "mistake" }));
}
return scenes;
}
/** M6-driven board-style exam answers, in `board_answer`, using the real ExamAnswerCard. */
function buildBoardAnswerScenes(seeds: TuitionLessonSeed[], wpm: number): VideoScene[] {
const m6 = seeds.find((s) => s.missionId === "M6");
const scenes: VideoScene[] = [];
if (m6) {
scenes.push(
buildMultiTextScene("board_answer", m6.missionTitle, [m6.teach.teacherIntro, m6.recall.prompt], wpm, {
attentionCue: "important",
beatKind: "question",
}),
);
for (const block of m6.teach.explanationBlocks) {
scenes.push(buildMicroScene("board_answer", block.heading, block.explanation, wpm, { emphasisWords: block.keyTerms }));
}
}
for (const seed of seeds) {
for (const exam of seed.examAnswers) {
const narration: NarrationBlock[] = [
mkNarration(nextSceneId("board_answer"), `Exam question, ${exam.marks} marks: ${exam.question}`, wpm, undefined, undefined, "exam_point"),
...exam.answerPoints.map((point) => mkNarration(nextSceneId("board_answer"), point, wpm)),
mkNarration(nextSceneId("board_answer"), `Key words for this answer: ${exam.keywords.join(", ")}.`, wpm),
mkNarration(nextSceneId("board_answer"), `Board-style version: ${exam.boardStyleRewrite}`, wpm),
];
// ExamAnswerCard renders from `examAnswer` below, not from boardActions
// β so these are duration-cost bookkeeping only, same as beat scenes.
const examBoard: BoardAction[] = [
{ type: "write_heading", text: `${exam.marks}-mark answer` },
{ type: "highlight", text: exam.question },
{ type: "highlight", text: exam.boardStyleRewrite },
...exam.keywords.slice(0, 3).map((k): BoardAction => ({ type: "highlight", text: k })),
];
scenes.push({
id: nextSceneId("board_answer"),
title: `${exam.marks}-mark: ${exam.question}`,
segmentKind: "board_answer",
subject: "Physics",
chapter: "Sound Waves",
durationSeconds: computeSceneDuration(narration, examBoard),
narration,
onScreenText: [exam.question, ...exam.keywords],
visualInstructions: ["Write the model answer", "Underline each scoring keyword"],
boardActions: examBoard,
examAnswer: { question: exam.question, marks: exam.marks, boardStyleRewrite: exam.boardStyleRewrite, keywords: exam.keywords, commonMistakes: exam.commonMistakes },
cursorPlan: ["Underline each keyword as it is named"],
recapNote: "Write the keywords to score full marks.",
});
}
}
return scenes;
}
/** Clearly-labelled sample practice from a few missions' yourTurn prompts, in `practice_sample`. */
function buildPracticeSampleScenes(seeds: TuitionLessonSeed[], wpm: number): VideoScene[] {
const picks = ["M1", "M2", "M3", "M4", "M5", "M6"];
const scenes: VideoScene[] = [];
for (const missionId of picks) {
const seed = seeds.find((s) => s.missionId === missionId);
if (!seed?.yourTurn) continue;
const isNumerical = seed.contentType === "numerical" && seed.formulas.length > 0;
const solutionSteps = isNumerical
? [
{ label: "Given", text: firstSentence(seed.yourTurn.prompt) },
{ label: "Formula", text: seed.yourTurn.expectedAnswerPoints[0] ?? "" },
{ label: "Substitute", text: seed.yourTurn.expectedAnswerPoints[1] ?? "" },
{ label: "Answer", text: seed.yourTurn.expectedAnswerPoints[2] ?? "" },
].filter((s) => s.text)
: undefined;
const marksSplit = seed.correctionRubric.scoringPoints.map((sp) => ({ step: sp.point, marks: sp.marks }));
const narration: NarrationBlock[] = [
mkNarration(nextSceneId("practice_sample"), `Your turn β sample practice: ${seed.yourTurn.prompt}`, wpm, undefined, undefined, "pause_and_think"),
mkNarration(nextSceneId("practice_sample"), `Now let's check it together.`, wpm),
];
scenes.push({
id: nextSceneId("practice_sample"),
title: `Sample practice: ${seed.missionTitle}`,
segmentKind: "practice_sample",
subject: "Physics",
chapter: "Sound Waves",
durationSeconds: computeSceneDuration(narration, [{ type: "write_heading", text: "Your turn" }]),
narration,
onScreenText: [seed.yourTurn.prompt],
visualInstructions: ["Show the question", "Pause", "Reveal the solution step by step"],
boardActions: [
{ type: "write_heading", text: "Your turn" },
{ type: "write_line", text: seed.yourTurn.prompt },
{ type: "highlight_box", text: "Pause and think" },
],
layout: "pauseAndPractice",
practice: {
id: `practice-${missionId}`,
prompt: seed.yourTurn.prompt,
marks: seed.correctionRubric.maxMarks,
modelAnswerPoints: seed.yourTurn.expectedAnswerPoints,
keywords: seed.yourTurn.expectedAnswerPoints,
isSample: true,
sampleNote: SAMPLE_PRACTICE_NOTE,
solutionSteps,
marksSplit,
},
cursorPlan: ["Hold on the question so the student can attempt it first"],
recapNote: seed.yourTurn.prompt,
});
}
return scenes;
}
/** M7-driven recap scenes plus one consolidated recap card, in `recap_revision`. */
function buildRecapRevisionScenes(seeds: TuitionLessonSeed[], wpm: number): VideoScene[] {
const m7 = seeds.find((s) => s.missionId === "M7");
const scenes: VideoScene[] = [];
if (m7) {
scenes.push(
buildMultiTextScene("recap_revision", m7.missionTitle, [m7.teach.teacherIntro, m7.recall.prompt], wpm, {
attentionCue: "important",
beatKind: "question",
}),
);
for (const block of m7.teach.explanationBlocks) {
scenes.push(buildMicroScene("recap_revision", block.heading, block.explanation, wpm, { emphasisWords: block.keyTerms }));
}
}
// Capped to what actually fits legibly in RecapCard's two-column layout β
// a rendered still showed 22 combined onScreenText lines (12 summary + 10
// must-remember), which the checker's per-column check confirmed was a
// real overcrowding risk in the must-remember + common-mistakes column
// (10 + 6 = 16 lines). Narration is unaffected: it already only speaks
// the first 6 of each list regardless of these caps.
const allSummary = seeds.flatMap((s) => s.recap.summary).slice(0, 8);
const allMustRemember = seeds.flatMap((s) => s.recap.mustRemember).slice(0, 6);
const allMistakes = Array.from(new Set(seeds.flatMap((s) => s.examAnswers.flatMap((e) => e.commonMistakes)))).slice(0, 4);
const flashcardTexts = seeds.flatMap((s) => s.revisionSave.flashcards.map((f) => `${f.front} ... ${f.back}`));
for (let i = 0; i < flashcardTexts.length; i += 3) {
scenes.push(
buildMultiTextScene("recap_revision", "Rapid-fire revision", flashcardTexts.slice(i, i + 3), wpm, { beatKind: "explain" }),
);
}
const narration: NarrationBlock[] = [
mkNarration(nextSceneId("recap_revision"), `Let's recap the whole chapter. ${allSummary.slice(0, 6).join(". ")}.`, wpm),
mkNarration(nextSceneId("recap_revision"), `Remember: ${allMustRemember.slice(0, 6).join(". ")}.`, wpm),
];
scenes.push({
id: nextSceneId("recap_revision"),
title: "Chapter recap",
segmentKind: "recap_revision",
subject: "Physics",
chapter: "Sound Waves",
durationSeconds: computeSceneDuration(narration, [{ type: "write_heading", text: "Recap" }]),
narration,
onScreenText: [...allSummary, ...allMustRemember],
visualInstructions: ["Read each recap point calmly"],
boardActions: [
{ type: "write_heading", text: "Recap" },
...allSummary.map((s): BoardAction => ({ type: "write_bullet", text: s })),
...allMustRemember.map((s): BoardAction => ({ type: "highlight_box", text: s })),
],
recap: {
summaryPoints: allSummary,
mustRemember: allMustRemember,
revisionNotes: seeds.flatMap((s) => s.revisionSave.revisionNotes).slice(0, 10),
commonMistakes: allMistakes,
examAnswerStructure: "Direct answer, then keywords, then a short closing line.",
actionLine: "After this video: revise these points and try one practice question.",
},
cursorPlan: ["Hold briefly so the student can copy"],
recapNote: "Whole-chapter recap.",
});
return scenes;
}
function buildHomeworkScene(seeds: TuitionLessonSeed[], chapter: string, wpm: number): VideoScene {
const bestTask = [...seeds]
.sort((a, b) => b.correctionRubric.maxMarks - a.correctionRubric.maxMarks)
.find((seed) => seed.yourTurn?.prompt)?.yourTurn?.prompt;
const text = bestTask
? `For homework, answer this ${chapter} question in your notebook: ${bestTask}`
: `For homework, revise the key ideas from ${chapter} and answer one textbook exercise question in your notebook.`;
return buildMicroScene("homework", "Homework and next step", text, wpm, { attentionCue: "copy_this", beatKind: "notebook" });
}
/**
* Chapter-wide opening. This used to repeat "By the end: {goal}" once per
* mission (7 near-identical scenes in a row) β a real teacher opens with a
* short, concrete "remember these first" hook, then teaches slowly, not a
* wall of objective statements. This version says "By the end" exactly once
* and folds every mission's goal into one natural roadmap sentence instead.
*/
function buildChapterOpeningScenes(seeds: TuitionLessonSeed[], chapter: string, wpm: number): VideoScene[] {
const scenes: VideoScene[] = [];
const firstTerms = Array.from(new Set(seeds.flatMap((seed) => seed.tags))).slice(0, 3);
const roadmap = seeds.map((seed) => seed.missionTitle).filter(Boolean);
scenes.push(
buildMultiTextScene(
"opening",
`${chapter} β today's class`,
[
`Welcome to today's full ${chapter} class.`,
firstTerms.length > 0
? `Keep these starting ideas ready: ${firstTerms.join(", ")}.`
: "We will build this chapter one idea at a time.",
"We will connect each idea to its diagram, formula, and exam use.",
],
wpm,
{ attentionCue: "important", beatKind: "question" },
),
);
// One bullet per mission goal (not one sentence gluing all 7 together with
// "; then") β a real crowding issue found in a rendered still: the joined
// form was a 6-line wall of text on one scene. buildMultiTextScene gives
// each goal its own beat/bullet line instead. Split across two scenes
// (not one, with all 7 missions) β a single scene with the intro line
// plus 7 goals was 8 on-screen lines, another real crowding bug found the
// same way. Only the first half says "By the end of today" once, so this
// still isn't the Day 18 repeated-objective-dump bug β that was the same
// phrase said once per mission (7 times), not one phrase split over two
// adjacent scenes.
const goals = seeds.map((seed) => seed.goal.replace(/\.$/, "") + ".");
const half = Math.ceil(goals.length / 2);
scenes.push(
buildMultiTextScene("opening", `${chapter} β today's class`, [`By the end of today, you will be able to:`, ...goals.slice(0, half)], wpm, {
beatKind: "explain",
}),
);
if (goals.length > half) {
scenes.push(
buildMultiTextScene("opening", `${chapter} β today's class`, ["And also:", ...goals.slice(half)], wpm, { beatKind: "explain" }),
);
}
const roadmapChunks = Array.from({ length: Math.ceil(roadmap.length / 3) }, (_, index) => roadmap.slice(index * 3, index * 3 + 3));
roadmapChunks.forEach((chunk, index) => {
const isFirst = index === 0;
const isLast = index === roadmapChunks.length - 1;
scenes.push(
buildMultiTextScene(
"opening",
`${chapter} β today's class`,
[
isFirst ? "Copy today's roadmap." : "Continue the chapter roadmap.",
...chunk,
...(isLast ? ["After the concepts: common mistakes, board-style answers, practice, and a final revision."] : []),
],
wpm,
{ attentionCue: isFirst ? "copy_this" : undefined, beatKind: "notebook" },
),
);
});
return scenes;
}
/* ------------------------------ assembly ------------------------------ */
function placeholderPlan(input: BuildFullChapterPlanInput, reason: string): TuitionVideoPlan {
const segments: TuitionVideoSegment[] = (Object.keys(SEGMENT_TITLES) as TuitionSegmentKind[]).map((kind) => ({
id: `segment-${kind}`,
kind,
title: SEGMENT_TITLES[kind],
scenes: [],
durationSeconds: 0,
needsContentReview: true,
}));
return {
schemaVersion: TUITION_VIDEO_SCHEMA_VERSION,
generatedAt: new Date().toISOString(),
fps: TUITION_VIDEO_FPS,
classLevel: input.classLevel,
board: input.board,
subject: input.subject,
chapter: input.chapter,
language: "English + Malayalam",
examGoal: "Board-exam readiness",
honestyNote: reason,
targetDurationMinutes: input.targetDurationMinutes ?? DEFAULT_TARGET_MINUTES,
totalDurationSeconds: 0,
segments,
needsContentReview: true,
strategyReady: false,
};
}
/** Build the full ~40 minute, continuously-teaching chapter plan. */
export function buildFullChapterTeachingPlan(input: BuildFullChapterPlanInput): TuitionVideoPlan {
const strategy = getSubjectStrategy(input.subject);
if (!strategy.ready) return placeholderPlan(input, `${input.subject} is not wired for video yet.`);
const seeds = chapterSeeds(input.subject, input.chapter);
if (seeds.length === 0) return placeholderPlan(input, `No curated lesson seeds found for ${input.chapter}.`);
const wpm = REAL_TTS_WPM;
const chapter = seeds[0].chapterTitle;
const scenesByKind = new Map<TuitionSegmentKind, VideoScene[]>();
const push = (kind: TuitionSegmentKind, scenes: VideoScene[]) => {
scenesByKind.set(kind, [...(scenesByKind.get(kind) ?? []), ...scenes]);
};
push("opening", buildChapterOpeningScenes(seeds, chapter, wpm));
// Day 20 β every mission teaches ONCE, in SSLC order, through its own
// content-type builder. The old extra `push("visual_board", ...)` replayed
// every mission's identical diagram frames a second time in a separate
// segment β pure repetition, not revision β so it is gone; diagrams teach
// inline where the concept needs them. After every second mission, a short
// "so far you learned" bridge reconnects the ideas before moving on.
const segmentKindFor = (seed: TuitionLessonSeed): TuitionSegmentKind =>
seed.contentType === "formula" ? "formula" : seed.contentType === "numerical" || seed.contentType === "exam_answer" ? "worked_example" : "concept";
seeds.forEach((seed, i) => {
if (seed.contentType === "formula") {
push("formula", buildFormulaScenes(seed, seeds, wpm));
} else if (seed.contentType === "numerical" || seed.contentType === "exam_answer") {
push("worked_example", buildWorkedExampleScenes(seed, wpm));
} else {
push("concept", buildConceptScenes(seed, wpm));
}
const isBridgePoint = i % 2 === 1 || i === seeds.length - 1;
if (isBridgePoint && i > 0) {
const covered = seeds.slice(Math.max(0, i - 1), i + 1);
push(segmentKindFor(seed), [buildBridgeScene(covered, wpm, segmentKindFor(seed))]);
}
});
push("common_mistakes", buildCommonMistakesScenes(seeds, wpm));
push("board_answer", buildBoardAnswerScenes(seeds, wpm));
push("practice_sample", buildPracticeSampleScenes(seeds, wpm));
push("recap_revision", buildRecapRevisionScenes(seeds, wpm));
push("homework", [buildHomeworkScene(seeds, chapter, wpm)]);
const segmentOrder: TuitionSegmentKind[] = [
"opening",
"concept",
"visual_board",
"formula",
"worked_example",
"common_mistakes",
"board_answer",
"practice_sample",
"recap_revision",
"homework",
];
const segments: TuitionVideoSegment[] = segmentOrder.map((kind) => {
// The low-level scene builders predate multi-subject video and still carry
// Physics defaults. The assembled plan is authoritative, so stamp every
// scene with the real requested subject and curated chapter here.
const scenes = (scenesByKind.get(kind) ?? []).map((scene) => ({ ...scene, subject: input.subject, chapter }));
const durationSeconds = scenes.reduce((sum, s) => sum + s.durationSeconds, 0);
return {
id: `segment-${kind}`,
kind,
title: SEGMENT_TITLES[kind],
scenes,
durationSeconds,
needsContentReview: scenes.length === 0,
};
});
const totalDurationSeconds = segments.reduce((sum, s) => sum + s.durationSeconds, 0);
return {
schemaVersion: TUITION_VIDEO_SCHEMA_VERSION,
generatedAt: new Date().toISOString(),
fps: TUITION_VIDEO_FPS,
classLevel: input.classLevel,
board: input.board,
subject: input.subject,
chapter,
language: "English + Malayalam",
examGoal: "Board-exam readiness",
honestyNote:
`This is a source-backed, continuously-taught full-chapter video covering ${chapter}. Sample practice is clearly labelled and is not full previous-question-paper coverage.`,
targetDurationMinutes: input.targetDurationMinutes ?? DEFAULT_TARGET_MINUTES,
totalDurationSeconds,
segments,
needsContentReview: false,
strategyReady: true,
};
}
/**
* Day 17 β a full ~40 minute, continuously-teaching Sound Waves chapter plan.
*
* Day 13-16 built a general 40-60 minute plan (`buildTuitionVideoPlan`) and a
* dedicated 8-10 minute segment (`buildFirstRealSegmentPlan`). Both proved a
* real problem in production: the general plan's non-concept segments
* (formula, worked_example, common_mistakes, board_answer, practice_sample,
* recap_revision) never got the Day14 "one short beat per scene" treatment,
* so a 40-minute render ended up with a single 187-second static scene for
* common_mistakes and another for recap_revision β exactly the "one board
* image for 2-4 minutes" complaint.
*
* This module applies that same fine-grained, teacher-paced treatment to
* EVERY subtopic across all seven Sound Waves missions (M1-M7), covering all
* 27 subtopics the chapter needs, with no scene longer than ~35 seconds and
* every scene carrying multiple short, sentence-by-sentence narration blocks
* instead of one long paragraph. Nothing is invented: every line traces back
* to the same curated M1-M7 seeds used everywhere else in this engine.
*/
import type { TuitionLessonSeed } from "../../lib/teaching/physicsLessonSeeds";
import { getSubjectStrategy } from "./subjectStrategies";
import {
mkNarration,
nextSceneId,
nextBeatId,
deriveRearrangements,
findNumericalSeedFor,
deriveWorkedExample,
firstSentence,
chapterSeeds,
SAMPLE_PRACTICE_NOTE,
} from "./lessonVideoPlan";
import {
TUITION_VIDEO_FPS,
TUITION_VIDEO_SCHEMA_VERSION,
type AttentionCue,
type BoardAction,
type NarrationBlock,
type TeachingBeat,
type TuitionSegmentKind,
type TuitionVideoPlan,
type TuitionVideoSegment,
type TuitionVideoSubject,
type VideoScene,
} from "./types";
export type BuildFullChapterPlanInput = {
classLevel: string;
board: string;
subject: TuitionVideoSubject;
chapter: string;
targetDurationMinutes?: number;
};
const DEFAULT_TARGET_MINUTES = 40;
/**
* Real Deepgram Aura audio measured ~171 wpm in an earlier synthesis run
* (16,756 characters -> 1,069.2s of real audio), against the shared 130wpm
* `subjectStrategies.ts` planning default every other part of this engine
* uses. Using the real rate here means the plan's *estimated* duration is a
* close proxy for the *real* rendered duration, so a content-volume tuning
* pass doesn't need several expensive TTS-and-render round trips to
* converge on the 38-42 minute band.
*/
const REAL_TTS_WPM = 172;
/**
* Day 20 β the duration band now measures PROJECTED SPOKEN minutes (narration
* estimate + injected think pauses), not `totalDurationSeconds`. The old
* metric added a 7-second board buffer per scene (~24 min across 200+ scenes)
* that the real audio-driven timeline never plays β which is exactly why the
* previous render "passed" a 38-42 estimate band and then came out at 25.9
* real minutes. Spoken minutes track the real class length: the Jul 6 render's
* spoken projection matched its 25.9-minute MP4 within ~10%.
*/
export const FULL_CHAPTER_DURATION_BAND = { min: 28, max: 60 };
/** Projected real speech minutes: narration estimates + injected pauses (no board buffers). */
export function estimateSpokenMinutes(plan: TuitionVideoPlan): number {
const blocks = plan.segments.flatMap((seg) => seg.scenes).flatMap((s) => s.narration);
const seconds = blocks.reduce((sum, n) => sum + n.estimatedSeconds + (n.pauseAfterSeconds ?? 0), 0);
return seconds / 60;
}
const SEGMENT_TITLES: Record<TuitionSegmentKind, string> = {
opening: "Opening β today's lesson goal",
concept: "Concept teaching",
visual_board: "Diagrams and board work",
formula: "Formula and wave quantities",
worked_example: "Worked numerical method",
common_mistakes: "Common mistakes to avoid",
board_answer: "Board-style exam answers",
practice_sample: "Sample practice questions",
recap_revision: "Recap and revision",
homework: "Homework and next step",
};
/** Split a longer explanation into short, sentence-paced chunks (same rule as Day 16). */