Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

feat(video_lesson): add a Remotion lesson kit and build runtime

SeleiXi53c08252d780
diff --git a/deeptutor/agents/video_lesson/__init__.py b/deeptutor/agents/video_lesson/__init__.py
new file mode 100644
index 000000000..fb72ebbec
--- /dev/null
+++ b/deeptutor/agents/video_lesson/__init__.py
@@ -0,0 +1 @@
+"""Video lesson capability: Remotion explainers played live in the browser."""
diff --git a/deeptutor/agents/video_lesson/remotion/build.mjs b/deeptutor/agents/video_lesson/remotion/build.mjs
new file mode 100644
index 000000000..33db66d0f
--- /dev/null
+++ b/deeptutor/agents/video_lesson/remotion/build.mjs
@@ -0,0 +1,129 @@
+// Compile a model-written Remotion lesson (Lesson.tsx + the shipped kit) into a browser player
+// script. Before bundling, sample frames are rendered in a permission-restricted Node process so
+// runtime errors come back to the model instead of reaching the learner.
+//
+// node build.mjs <Lesson.tsx> <out.js>
+//
+// DEEPTUTOR_REMOTION_RUNTIME names the directory whose node_modules holds remotion, react and
+// esbuild (see package.json next to this file). Prints one JSON line: {ok, stage, errors, frames}.
+
+import {createRequire} from "node:module";
+import {mkdtempSync, writeFileSync, rmSync} from "node:fs";
+import {tmpdir} from "node:os";
+import {dirname, join, resolve} from "node:path";
+import {spawnSync} from "node:child_process";
+
+const runtime = resolve(process.env.DEEPTUTOR_REMOTION_RUNTIME || ".");
+const require = createRequire(join(runtime, "package.json"));
+const esbuild = require("esbuild");
+const [lessonArg, outArg] = process.argv.slice(2);
+const lesson = resolve(lessonArg).replace(/\\/g, "/");
+const nodePaths = [join(runtime, "node_modules")];
+
+const report = (o) => { console.log(JSON.stringify(o)); process.exit(o.ok ? 0 : 1); };
+const fmtErrors = (e) => (e.errors || [e]).slice(0, 12).map((x) =>
+ x.location ? `${x.location.line}:${x.location.column} ${x.text}\n ${x.location.lineText}` : String(x.text || x.message || x));
+
+// The lesson may import only React, Remotion and its own kit; everything else is a compile error.
+const ALLOWED = /^(react|react\/jsx-runtime|react-dom|react-dom\/server|react-dom\/client|remotion|@remotion\/player)$/;
+const onlyAllowedImports = {
+ name: "only-allowed-imports",
+ setup(build) {
+ const home = dirname(lesson);
+ const inside = (p) => p.replace(/\\/g, "/").startsWith(home + "/");
+ build.onResolve({filter: /.*/}, (args) => {
+ if (args.kind === "entry-point" || ALLOWED.test(args.path)) return undefined;
+ // packages pulling in their own dependencies are not the lesson's imports
+ if (!args.importer || !inside(args.importer)) return undefined;
+ const target = resolve(args.resolveDir, args.path).replace(/\\/g, "/");
+ if (target === lesson || (args.path.startsWith(".") && inside(target))) return undefined;
+ return {errors: [{text: `import "${args.path}" is not allowed; use react, remotion and ./kit only`}]};
+ });
+ },
+};
+
+const common = {bundle: true, jsx: "automatic", nodePaths, logLevel: "silent", plugins: [onlyAllowedImports],
+ loader: {".tsx": "tsx", ".ts": "ts"}, define: {"process.env.NODE_ENV": '"production"'}};
+
+// 1. Node check: render sample frames through @remotion/player's <Thumbnail>.
+const tmp = mkdtempSync(join(tmpdir(), "dt-lesson-"));
+const checkEntry = join(tmp, "check.tsx");
+writeFileSync(checkEntry, `
+import {renderToPipeableStream} from "react-dom/server";
+import {Writable} from "node:stream";
+import {Thumbnail} from "@remotion/player";
+import {Lesson, LESSON} from ${JSON.stringify(lesson)};
+// Streamed rendering reports errors thrown below a Suspense boundary through onError;
+// renderToString would silently render the fallback instead.
+const render = (element) => new Promise((done) => {
+ let html = "";
+ const thrown = [];
+ const sink = new Writable({write(chunk, _enc, next) { html += chunk; next(); }});
+ sink.on("finish", () => done({html, thrown}));
+ const stream = renderToPipeableStream(element, {
+ onError(error) { thrown.push(error); },
+ onShellError(error) { thrown.push(error); done({html, thrown}); },
+ onAllReady() { stream.pipe(sink); },
+ });
+});
+const errors = [], frames = [];
+const cfg = LESSON || {};
+for (const k of ["durationInFrames", "fps", "width", "height"])
+ if (!Number.isFinite(cfg[k]) || cfg[k] <= 0) errors.push("LESSON." + k + " must be a positive number");
+if (!errors.length) {
+ const n = cfg.durationInFrames, samples = 24;
+ for (let i = 0; i <= samples; i++) {
+ const f = Math.min(n - 1, Math.round((n - 1) * i / samples));
+ const realError = console.error;
+ const logged = [];
+ console.error = (...a) => logged.push(a.map(String).join(" ").slice(0, 300));
+ const {html, thrown} = await render(<Thumbnail component={Lesson} compositionWidth={cfg.width}
+ compositionHeight={cfg.height} durationInFrames={n} fps={cfg.fps} frameToDisplay={f} />);
+ console.error = realError;
+ frames.push({frame: f, chars: html.length});
+ for (const e of thrown) errors.push("frame " + f + ": " + ((e && e.message) || e));
+ if (!thrown.length && html.length < 400) errors.push("frame " + f + ": almost nothing rendered");
+ for (const l of logged) if (!/Warning: Each child|useLayoutEffect|The above error occurred/.test(l)) errors.push("frame " + f + " console.error: " + l);
+ }
+}
+console.log(JSON.stringify({errors: [...new Set(errors)].slice(0, 20), frames}));
+`);
+try {
+ await esbuild.build({...common, entryPoints: [checkEntry], outfile: join(tmp, "check.mjs"), platform: "node",
+ format: "esm", banner: {js: "import {createRequire as __cr} from 'module'; const require = __cr(import.meta.url);"}});
+} catch (e) {
+ rmSync(tmp, {recursive: true, force: true});
+ report({ok: false, stage: "compile", errors: fmtErrors(e)});
+}
+// Model code runs here: no file writes, child processes, workers or native addons.
+const run = spawnSync(process.execPath, ["--permission", `--allow-fs-read=${tmp}`, join(tmp, "check.mjs")],
+ {encoding: "utf8", timeout: 180000});
+rmSync(tmp, {recursive: true, force: true});
+let checked;
+try { checked = JSON.parse(run.stdout.trim().split("\n").pop()); }
+catch { report({ok: false, stage: "render", errors: [(run.stderr || run.stdout || "no output").slice(-1500)]}); }
+if (checked.errors.length) report({ok: false, stage: "render", errors: checked.errors, frames: checked.frames});
+
+// 2. Browser bundle: the composition inside a <Player> with controls; ?frame=N opens paused there.
+const entry = join(dirname(resolve(outArg)), "_entry.tsx");
+writeFileSync(entry, `
+import {createRoot} from "react-dom/client";
+import {Player} from "@remotion/player";
+import {Lesson, LESSON} from ${JSON.stringify(lesson)};
+const query = new URLSearchParams(location.search);
+const still = query.has("frame") ? Math.max(0, Math.min(LESSON.durationInFrames - 1, Number(query.get("frame")) || 0)) : null;
+createRoot(document.getElementById("player")).render(
+ <Player component={Lesson} durationInFrames={LESSON.durationInFrames} fps={LESSON.fps}
+ compositionWidth={LESSON.width} compositionHeight={LESSON.height} initialFrame={still ?? 0}
+ controls autoPlay={false} loop clickToPlay showVolumeControls={false} allowFullscreen
+ style={{width: "100%", aspectRatio: LESSON.width + " / " + LESSON.height}} />);
+`);
+try {
+ await esbuild.build({...common, entryPoints: [entry], outfile: resolve(outArg), platform: "browser",
+ format: "iife", minify: true});
+} catch (e) {
+ report({ok: false, stage: "bundle", errors: fmtErrors(e)});
+} finally {
+ rmSync(entry, {force: true});
+}
+report({ok: true, stage: "done", errors: [], frames: checked.frames});
diff --git a/deeptutor/agents/video_lesson/remotion/china_outline.json b/deeptutor/agents/video_lesson/remotion/china_outline.json
new file mode 100644
index 000000000..eac97e8d2
--- /dev/null
+++ b/deeptutor/agents/video_lesson/remotion/china_outline.json
@@ -0,0 +1 @@
+[[[124.52,40.22],[126.04,40.93],[126.69,41.75],[128.11,41.36],[128.32,41.58],[128.03,42.0],[128.95,42.03],[129.34,42.45],[129.7,42.43],[129.9,43.0],[130.65,42.43],[130.41,42.73],[131.15,42.94],[131.31,43.39],[130.97,44.85],[131.89,45.34],[133.14,45.13],[133.14,45.43],[133.91,46.25],[134.18,47.33],[134.78,47.72],[134.55,47.98],[134.68,48.26],[135.1,48.44],[133.13,48.13],[132.56,47.72],[130.98,47.71],[130.67,48.11],[130.85,48.3],[130.54,48.61],[130.68,48.88],[130.24,48.87],[129.52,49.42],[127.82,49.59],[127.53,49.83],[127.6,50.24],[126.92,51.06],[126.56,52.14],[125.97,52.63],[126.12,52.77],[125.68,52.86],[125.61,53.08],[123.27,53.56],[120.88,53.29],[120.03,52.77],[120.08,52.59],[120.73,52.54],[120.79,52.16],[120.09,51.68],[119.13,50.39],[119.35,50.17],[117.81,49.52],[116.72,49.85],[115.82,48.26],[115.53,48.16],[115.94,47.68],[116.79,47.9],[117.38,47.64],[117.81,48.02],[118.57,47.99],[119.72,47.2],[119.91,46.67],[117.42,46.58],[117.37,46.36],[116.59,46.29],[116.17,45.69],[114.55,45.39],[113.63,44.75],[111.9,45.05],[111.42,44.36],[111.95,43.69],[109.54,42.47],[107.47,42.46],[105.01,41.58],[104.52,41.66],[104.53,41.88],[103.42,41.88],[100.86,42.67],[96.39,42.73],[95.33,44.03],[95.41,44.3],[94.72,44.34],[93.51,44.97],[90.88,45.19],[90.68,45.58],[91.03,46.02],[91.05,46.72],[90.38,47.64],[89.57,48.04],[89.08,47.99],[87.97,48.58],[87.82,49.17],[87.11,49.16],[86.73,48.99],[86.58,48.54],[85.59,48.19],[85.55,47.06],[84.96,46.86],[83.03,47.22],[82.27,45.62],[82.56,45.2],[81.79,45.38],[79.89,44.91],[80.4,44.63],[80.8,43.18],[80.38,43.03],[80.6,42.89],[80.26,42.83],[80.14,42.03],[78.16,41.38],[77.78,41.02],[76.89,41.03],[76.33,40.34],[75.71,40.28],[75.6,40.66],[74.84,40.52],[74.91,40.34],[74.02,40.09],[73.87,39.48],[73.5,39.38],[73.84,39.01],[73.8,38.61],[74.86,38.48],[74.89,37.67],[75.14,37.36],[74.5,37.07],[75.87,36.67],[76.16,35.82],[76.56,35.92],[77.2,35.52],[78.14,35.49],[78.02,35.23],[78.28,34.62],[79.04,34.33],[78.66,34.09],[78.68,33.65],[79.15,33.18],[79.31,32.6],[78.97,32.33],[78.74,32.7],[78.4,32.53],[78.47,32.13],[78.76,31.95],[78.76,31.36],[79.1,30.99],[79.67,30.98],[81.13,30.02],[81.42,30.42],[82.1,30.35],[82.18,30.07],[83.27,29.57],[83.6,29.17],[84.12,29.29],[84.48,28.74],[85.13,28.68],[85.11,28.34],[85.72,28.37],[86.0,27.91],[86.19,28.17],[86.41,27.9],[86.7,28.1],[87.23,27.81],[88.76,28.07],[88.98,27.21],[89.24,27.8],[89.79,28.24],[91.03,27.86],[91.46,28.0],[91.59,27.54],[92.06,27.39],[92.11,26.85],[93.57,26.94],[94.28,27.58],[95.74,28.28],[96.28,28.23],[97.1,27.74],[97.69,28.52],[98.14,28.14],[98.32,27.52],[98.71,27.55],[98.78,26.62],[98.58,26.12],[98.71,25.86],[98.17,25.62],[97.55,24.74],[97.77,24.26],[97.53,23.93],[98.88,24.15],[98.67,23.8],[98.89,23.21],[99.56,22.93],[99.32,22.74],[99.22,22.11],[99.97,22.05],[100.24,21.47],[101.12,21.77],[101.22,21.23],[101.76,21.15],[101.67,22.48],[102.27,22.42],[102.51,22.77],[103.03,22.44],[103.32,22.81],[103.96,22.5],[104.12,22.81],[104.74,22.83],[104.8,23.11],[105.33,23.39],[105.88,22.92],[106.84,22.8],[106.56,22.46],[106.7,21.96],[107.36,21.6],[108.23,21.49],[108.63,21.68],[109.14,21.57],[109.14,21.39],[109.89,21.44],[109.66,20.93],[109.93,20.21],[110.54,20.42],[110.21,21.05],[112.14,21.79],[112.93,21.84],[113.09,22.13],[113.27,21.87],[113.57,22.08],[113.68,22.73],[113.89,22.44],[114.38,22.6],[114.51,22.44],[114.71,22.79],[114.89,22.54],[115.19,22.82],[115.58,22.65],[115.65,22.87],[116.51,22.93],[116.89,23.5],[117.46,23.58],[117.91,24.01],[118.12,24.57],[118.61,24.52],[118.65,24.84],[118.99,24.88],[118.92,25.26],[119.12,25.01],[119.38,25.25],[119.22,25.47],[119.87,25.46],[119.79,25.67],[119.68,25.48],[119.48,25.63],[119.72,26.01],[119.6,26.17],[119.95,26.35],[119.58,26.62],[119.94,26.78],[119.83,26.52],[120.14,26.64],[120.05,26.86],[120.55,27.16],[120.71,27.68],[121.19,27.82],[121.06,28.1],[121.63,28.25],[121.54,28.66],[121.77,28.86],[121.61,29.17],[121.99,29.11],[121.83,29.65],[122.14,29.9],[121.06,30.56],[121.68,30.82],[122.13,30.6],[121.95,31.07],[121.34,31.51],[121.98,31.46],[121.86,31.96],[120.96,32.61],[120.31,34.31],[119.21,34.98],[120.31,35.97],[120.18,36.2],[120.71,36.13],[120.69,36.39],[120.97,36.47],[120.85,36.62],[122.53,36.9],[122.71,37.39],[121.57,37.44],[120.73,37.83],[120.23,37.69],[119.74,37.13],[119.33,37.12],[119.0,37.32],[118.99,37.62],[119.28,37.74],[118.97,38.09],[118.02,38.2],[117.64,38.53],[117.65,38.83],[118.03,39.22],[118.49,38.91],[118.58,39.13],[118.93,39.12],[119.54,39.89],[120.49,40.2],[121.13,40.87],[121.82,40.89],[122.27,40.48],[121.23,39.55],[121.27,39.37],[121.72,39.36],[121.63,39.08],[121.09,38.92],[121.14,38.72],[123.27,39.75],[124.15,39.75]],[[110.11,20.03],[109.3,19.92],[108.64,19.35],[108.64,18.49],[109.58,18.14],[110.5,18.65],[111.04,19.76],[110.69,20.16]],[[120.44,22.44],[120.85,21.88],[121.03,22.65],[121.43,23.14],[122.01,25.0],[121.62,25.29],[121.02,25.04],[120.1,23.7],[120.02,23.07]]]
diff --git a/deeptutor/agents/video_lesson/remotion/kit.tsx b/deeptutor/agents/video_lesson/remotion/kit.tsx
new file mode 100644
index 000000000..740b25aa4
--- /dev/null
+++ b/deeptutor/agents/video_lesson/remotion/kit.tsx
@@ -0,0 +1,406 @@
+// Lesson kit: the only building blocks a video lesson may use. DeepTutor's cream/terracotta palette,
+// Lora + Geist type, and restrained motion live here, so the model composes content instead of
+// inventing styling. Every component reads the frame from its enclosing <Sequence>.
+import React, {createContext, useContext} from "react";
+import {AbsoluteFill, Easing, interpolate, useCurrentFrame} from "remotion";
+import outline from "./china_outline.json";
+
+export const T = {
+ paper: "#fdfcf9", paper2: "#f5f2ea", ink: "#1c1816", soft: "#3b3430", muted: "#6d645a",
+ rule: "#e6decc", accent: "#b0501e", blue: "#2f5d8a", green: "#3d6b4f",
+ serif: "Lora, 'Noto Serif SC', 'Songti SC', 'SimSun', serif",
+ sans: "Geist, 'PingFang SC', 'Microsoft YaHei', 'Noto Sans SC', sans-serif",
+ mono: "'Geist Mono', ui-monospace, monospace",
+};
+export const W = 1920, H = 1080;
+type Tone = "ink" | "soft" | "accent" | "muted" | "blue" | "green";
+const tone = (t: Tone = "ink") => ({ink: T.ink, soft: T.soft, accent: T.accent, muted: T.muted, blue: T.blue, green: T.green}[t]);
+
+const ease = Easing.bezier(0.2, 0.8, 0.2, 1);
+/** 0→1 progress that starts `delay` frames into the current Sequence and lasts `dur` frames. */
+export function useProgress(delay = 0, dur = 18): number {
+ const f = useCurrentFrame();
+ return interpolate(f, [delay, delay + Math.max(1, dur)], [0, 1],
+ {extrapolateLeft: "clamp", extrapolateRight: "clamp", easing: ease});
+}
+
+// ------------------------------------------------------------------ page and text
+
+/** Full-frame paper page. `eyebrow` is the small section label in the top-left corner. */
+export const Stage: React.FC<{eyebrow?: string; page?: string; children?: React.ReactNode}> = ({eyebrow, page, children}) => (
+ <AbsoluteFill style={{background: T.paper, color: T.ink, fontFamily: T.sans}}>
+ {eyebrow && <div style={{position: "absolute", left: 120, top: 70, font: `500 26px ${T.sans}`, color: T.muted,
+ letterSpacing: "0.06em"}}>{eyebrow}</div>}
+ {page && <div style={{position: "absolute", right: 120, top: 70, font: `500 24px ${T.mono}`, color: T.muted}}>{page}</div>}
+ {children}
+ </AbsoluteFill>
+);
+
+/** Fades in and rises 14px; wrap any absolutely placed content in it. */
+export const Reveal: React.FC<{delay?: number; dur?: number; x?: number; y?: number; w?: number;
+ style?: React.CSSProperties; children?: React.ReactNode}> = ({delay = 0, dur = 16, x, y, w, style, children}) => {
+ const p = useProgress(delay, dur);
+ const placed: React.CSSProperties = x !== undefined || y !== undefined
+ ? {position: "absolute", left: x ?? 0, top: y ?? 0, width: w} : {};
+ return <div style={{...placed, ...style, opacity: p, transform: `translateY(${(1 - p) * 14}px)`}}>{children}</div>;
+};
+
+/** Serif headline with an optional small kicker above it. */
+export const Title: React.FC<{kicker?: string; x?: number; y?: number; w?: number; size?: number; delay?: number;
+ children?: React.ReactNode}> = ({kicker, x = 120, y = 150, w = 1500, size = 76, delay = 0, children}) => (
+ <Reveal x={x} y={y} w={w} delay={delay}>
+ {kicker && <div style={{font: `600 28px ${T.sans}`, color: T.accent, marginBottom: 18, letterSpacing: "0.04em"}}>{kicker}</div>}
+ <div style={{font: `500 ${size}px/1.22 ${T.serif}`, color: T.ink}}>{children}</div>
+ </Reveal>
+);
+
+/** Body paragraph. */
+export const Body: React.FC<{x: number; y: number; w?: number; size?: number; delay?: number; color?: Tone;
+ children?: React.ReactNode}> = ({x, y, w = 760, size = 36, delay = 0, color = "soft", children}) => (
+ <Reveal x={x} y={y} w={w} delay={delay}>
+ <div style={{font: `400 ${size}px/1.65 ${T.sans}`, color: tone(color)}}>{children}</div>
+ </Reveal>
+);
+
+/** Inline emphasis inside Body/Title text. */
+export const Em: React.FC<{tone?: Tone; children?: React.ReactNode}> = ({tone: t = "accent", children}) => (
+ <span style={{color: tone(t), fontWeight: 600}}>{children}</span>
+);
+
+/** Inline math in serif italic; use <Frac> for fractions. */
+export const Formula: React.FC<{size?: number; children?: React.ReactNode}> = ({size, children}) => (
+ <span style={{fontFamily: T.serif, fontStyle: "italic", fontSize: size, whiteSpace: "nowrap"}}>{children}</span>
+);
+export const Frac: React.FC<{num: React.ReactNode; den: React.ReactNode}> = ({num, den}) => (
+ <span style={{display: "inline-flex", flexDirection: "column", alignItems: "center", verticalAlign: "middle",
+ fontSize: "0.82em", lineHeight: 1.1, margin: "0 0.15em"}}>
+ <span style={{padding: "0 0.2em"}}>{num}</span>
+ <span style={{borderTop: "2px solid currentColor", padding: "0 0.2em"}}>{den}</span>
+ </span>
+);
+
+/** Teacher's spoken line at the bottom of the frame. `lines[i].at` is the frame (inside the Sequence) it starts. */
+export const Narration: React.FC<{lines: {at: number; text: React.ReactNode}[]}> = ({lines}) => {
+ const f = useCurrentFrame();
+ const i = lines.reduce((k, l, j) => (f >= l.at ? j : k), -1);
+ if (i < 0) return null;
+ const local = f - lines[i].at;
+ const p = interpolate(local, [0, 10], [0, 1], {extrapolateRight: "clamp"});
+ return (
+ <div style={{position: "absolute", left: 120, right: 120, bottom: 64, borderTop: `2px solid ${T.rule}`, paddingTop: 22}}>
+ <div style={{font: `400 38px/1.55 ${T.sans}`, color: T.ink, opacity: p, maxWidth: 1500}}>{lines[i].text}</div>
+ </div>
+ );
+};
+
+/** A note card with a left rule; good for a definition, a treaty, or one key fact. */
+export const Card: React.FC<{x: number; y: number; w?: number; title?: string; tone?: Tone; delay?: number;
+ children?: React.ReactNode}> = ({x, y, w = 560, title, tone: t = "accent", delay = 0, children}) => (
+ <Reveal x={x} y={y} w={w} delay={delay}>
+ <div style={{background: "#fff", border: `1.5px solid ${T.rule}`, borderLeft: `6px solid ${tone(t)}`, borderRadius: 8,
+ padding: "22px 28px"}}>
+ {title && <div style={{font: `600 32px ${T.sans}`, color: T.ink, marginBottom: 8}}>{title}</div>}
+ <div style={{font: `400 30px/1.6 ${T.sans}`, color: T.soft}}>{children}</div>
+ </div>
+ </Reveal>
+);
+
+/** A number that counts from `from` to `to`. */
+export const Count: React.FC<{from: number; to: number; delay?: number; dur?: number; digits?: number;
+ style?: React.CSSProperties}> = ({from, to, delay = 0, dur = 30, digits = 0, style}) => {
+ const p = useProgress(delay, dur);
+ return <span style={{fontVariantNumeric: "tabular-nums", ...style}}>{(from + (to - from) * p).toFixed(digits)}</span>;
+};
+
+// ------------------------------------------------------------------ hand-drawn marks
+
+function wobble(points: [number, number][], seed: number, amp: number): string {
+ let s = seed;
+ const rnd = () => ((s = (s * 9301 + 49297) % 233280) / 233280 - 0.5) * amp;
+ return points.map(([x, y], i) => `${i ? "L" : "M"}${(x + rnd()).toFixed(1)} ${(y + rnd()).toFixed(1)}`).join(" ");
+}
+
+/** Draws an underline, circle, or box around a frame region, as if by pen. Coordinates are frame pixels. */
+export const Mark: React.FC<{x: number; y: number; w: number; h: number; kind?: "underline" | "circle" | "box";
+ delay?: number; dur?: number; tone?: Tone}> = ({x, y, w, h, kind = "underline", delay = 0, dur = 16, tone: t = "accent"}) => {
+ const p = useProgress(delay, dur);
+ let pts: [number, number][];
+ if (kind === "underline") pts = Array.from({length: 9}, (_, i) => [x + (w * i) / 8, y + h + 6 + Math.sin(i) * 2]);
+ else if (kind === "box") pts = [[x - 8, y - 8], [x + w + 8, y - 6], [x + w + 6, y + h + 8], [x - 6, y + h + 6], [x - 8, y - 4]];
+ else pts = Array.from({length: 34}, (_, i) => {
+ const a = (i / 30) * 2 * Math.PI - 0.6;
+ return [x + w / 2 + (w / 2 + 18) * Math.cos(a), y + h / 2 + (h / 2 + 14) * Math.sin(a)];
+ });
+ return (
+ <svg width={W} height={H} style={{position: "absolute", left: 0, top: 0, pointerEvents: "none"}}>
+ <path d={wobble(pts, x * 7 + y, kind === "underline" ? 2 : 4)} pathLength={1} fill="none"
+ stroke={tone(t)} strokeWidth={4} strokeLinecap="round" strokeLinejoin="round"
+ strokeDasharray={1} strokeDashoffset={1 - p} />
+ </svg>
+ );
+};
+
+/** A gently curved arrow between two frame points, drawn over `dur` frames. */
+export const Arrow: React.FC<{from: [number, number]; to: [number, number]; bend?: number; delay?: number; dur?: number;
+ tone?: Tone; label?: string}> = ({from, to, bend = 0.18, delay = 0, dur = 18, tone: t = "muted", label}) => {
+ const p = useProgress(delay, dur);
+ const [x1, y1] = from, [x2, y2] = to;
+ const mx = (x1 + x2) / 2 - (y2 - y1) * bend, my = (y1 + y2) / 2 + (x2 - x1) * bend;
+ const ang = Math.atan2(y2 - my, x2 - mx);
+ const head = (d: number) => `${x2 - 18 * Math.cos(ang + d)},${y2 - 18 * Math.sin(ang + d)}`;
+ return (
+ <svg width={W} height={H} style={{position: "absolute", left: 0, top: 0, pointerEvents: "none"}}>
+ <path d={`M${x1} ${y1} Q${mx} ${my} ${x2} ${y2}`} pathLength={1} fill="none" stroke={tone(t)} strokeWidth={3}
+ strokeDasharray={1} strokeDashoffset={1 - p} strokeLinecap="round" />
+ <polyline points={`${head(0.45)} ${x2},${y2} ${head(-0.45)}`} fill="none" stroke={tone(t)} strokeWidth={3}
+ opacity={p > 0.95 ? 1 : 0} strokeLinejoin="round" />
+ {label && <text x={mx} y={my - 12} textAnchor="middle" fill={T.muted} opacity={p}
+ style={{font: `500 26px ${T.sans}`}}>{label}</text>}
+ </svg>
+ );
+};
+
+// ------------------------------------------------------------------ plots
+
+type PlotCtx = {sx: (x: number) => number; sy: (y: number) => number; x: number; y: number; w: number; h: number;
+ xDomain: [number, number]; yDomain: [number, number]};
+const PlotContext = createContext<PlotCtx | null>(null);
+const usePlot = () => {
+ const c = useContext(PlotContext);
+ if (!c) throw new Error("Curve/Dots/Cobweb/HLine/VLine/PlotLabel must be inside <Plot>");
+ return c;
+};
+
+/** Axes in a frame rectangle; children draw in data coordinates. */
+export const Plot: React.FC<{x: number; y: number; w: number; h: number; xDomain: [number, number];
+ yDomain: [number, number]; xTicks?: number[]; yTicks?: number[]; xLabel?: string; yLabel?: string; delay?: number;
+ tickFormat?: (v: number) => string; children?: React.ReactNode}> = (props) => {
+ const {x, y, w, h, xDomain, yDomain, xTicks = [], yTicks = [], xLabel, yLabel, delay = 0, children} = props;
+ const fmt = props.tickFormat || ((v: number) => String(v));
+ const p = useProgress(delay, 20);
+ const sx = (v: number) => x + ((v - xDomain[0]) / (xDomain[1] - xDomain[0])) * w;
+ const sy = (v: number) => y + h - ((v - yDomain[0]) / (yDomain[1] - yDomain[0])) * h;
+ return (
+ <PlotContext.Provider value={{sx, sy, x, y, w, h, xDomain, yDomain}}>
+ <svg width={W} height={H} style={{position: "absolute", left: 0, top: 0, overflow: "visible"}}>
+ <g opacity={p}>
+ {yTicks.map((v) => <g key={"y" + v}>
+ <line x1={x} x2={x + w} y1={sy(v)} y2={sy(v)} stroke={T.rule} strokeWidth={1.5} />
+ <text x={x - 16} y={sy(v) + 9} textAnchor="end" fill={T.muted} style={{font: `400 26px ${T.mono}`}}>{fmt(v)}</text>
+ </g>)}
+ {xTicks.map((v) => <text key={"x" + v} x={sx(v)} y={y + h + 42} textAnchor="middle" fill={T.muted}
+ style={{font: `400 26px ${T.mono}`}}>{fmt(v)}</text>)}
+ <line x1={x} x2={x + w} y1={y + h} y2={y + h} stroke={T.ink} strokeWidth={2} />
+ <line x1={x} x2={x} y1={y} y2={y + h} stroke={T.ink} strokeWidth={2} />
+ {xLabel && <text x={x + w} y={y + h + 84} textAnchor="end" fill={T.soft} style={{font: `500 28px ${T.sans}`}}>{xLabel}</text>}
+ {yLabel && <text x={x} y={y - 24} fill={T.soft} style={{font: `500 28px ${T.sans}`}}>{yLabel}</text>}
+ </g>
+ {children}
+ </svg>
+ </PlotContext.Provider>
+ );
+};
+
+/** y = fn(x), drawn left to right. */
+export const Curve: React.FC<{fn: (x: number) => number; domain?: [number, number]; delay?: number; dur?: number;
+ tone?: Tone; width?: number; dashed?: boolean; label?: string; labelAt?: number}> = (props) => {
+ const c = usePlot();
+ const {fn, delay = 0, dur = 36, tone: t = "ink", width = 4, dashed, label} = props;
+ const [a, b] = props.domain || c.xDomain;
+ const p = useProgress(delay, dur);
+ const pts: string[] = [];
+ for (let i = 0; i <= 160; i++) {
+ const xv = a + ((b - a) * i) / 160, yv = fn(xv);
+ if (Number.isFinite(yv) && yv >= c.yDomain[0] - 1e-9 && yv <= c.yDomain[1] + 1e-9) pts.push(`${c.sx(xv).toFixed(1)},${c.sy(yv).toFixed(1)}`);
+ }
+ const lx = props.labelAt ?? b;
+ return <g>
+ <polyline points={pts.join(" ")} pathLength={1} fill="none" stroke={tone(t)} strokeWidth={width}
+ strokeDasharray={dashed ? undefined : 1} strokeDashoffset={dashed ? undefined : 1 - p}
+ opacity={dashed ? p : 1} strokeLinejoin="round" style={dashed ? {strokeDasharray: "10 8"} : undefined} />
+ {label && <text x={c.sx(lx) + 12} y={c.sy(fn(lx)) - 14} fill={tone(t)} opacity={p}
+ style={{font: `italic 500 30px ${T.serif}`}}>{label}</text>}
+ </g>;
+};
+
+/** Points that appear one by one, `every` frames apart, optionally joined and labelled. */
+export const Dots: React.FC<{data: [number, number][]; delay?: number; every?: number; tone?: Tone; join?: boolean;
+ labels?: (string | null)[]; r?: number}> = ({data, delay = 0, every = 10, tone: t = "accent", join, labels, r = 8}) => {
+ const c = usePlot();
+ const f = useCurrentFrame();
+ const shown = data.filter((_, i) => f >= delay + i * every);
+ return <g>
+ {join && shown.length > 1 && <polyline points={shown.map(([a, b]) => `${c.sx(a)},${c.sy(b)}`).join(" ")}
+ fill="none" stroke={tone(t)} strokeWidth={2.5} opacity={0.55} />}
+ {shown.map(([a, b], i) => {
+ const k = interpolate(f - (delay + i * every), [0, 8], [0, 1], {extrapolateRight: "clamp"});
+ return <g key={i} opacity={k}>
+ <circle cx={c.sx(a)} cy={c.sy(b)} r={r * (0.6 + 0.4 * k)} fill={tone(t)} />
+ {labels && labels[i] && <text x={c.sx(a)} y={c.sy(b) - 20} textAnchor="middle" fill={T.soft}
+ style={{font: `500 24px ${T.mono}`}}>{labels[i]}</text>}
+ </g>;
+ })}
+ </g>;
+};
+
+/** Cobweb diagram for x_{n+1} = f(x_n): the staircase between y = f(x) and y = x. */
+export const Cobweb: React.FC<{f: (x: number) => number; x0: number; steps: number; delay?: number; every?: number;
+ tone?: Tone}> = ({f: fn, x0, steps, delay = 0, every = 14, tone: t = "accent"}) => {
+ const c = usePlot();
+ const frame = useCurrentFrame();
+ const segs: [number, number, number, number][] = [];
+ let xv = x0;
+ segs.push([xv, c.yDomain[0], xv, fn(xv)]);
+ for (let i = 0; i < steps; i++) {
+ const yv = fn(xv);
+ segs.push([xv, yv, yv, yv]);
+ segs.push([yv, yv, yv, fn(yv)]);
+ xv = yv;
+ }
+ return <g>{segs.map(([a, b, cc, d], i) => {
+ const k = interpolate(frame - (delay + i * every), [0, every * 0.8], [0, 1],
+ {extrapolateLeft: "clamp", extrapolateRight: "clamp"});
+ if (k <= 0) return null;
+ return <line key={i} x1={c.sx(a)} y1={c.sy(b)} x2={c.sx(a + (cc - a) * k)} y2={c.sy(b + (d - b) * k)}
+ stroke={tone(t)} strokeWidth={3} opacity={i === 0 ? 0.6 : 1} strokeDasharray={i === 0 ? "6 6" : undefined} />;
+ })}</g>;
+};
+
+/** Horizontal / vertical reference line with a label at its end. */
+export const HLine: React.FC<{y: number; label?: string; delay?: number; tone?: Tone}> = ({y, label, delay = 0, tone: t = "blue"}) => {
+ const c = usePlot();
+ const p = useProgress(delay, 18);
+ return <g opacity={p}>
+ <line x1={c.x} x2={c.x + c.w} y1={c.sy(y)} y2={c.sy(y)} stroke={tone(t)} strokeWidth={2.5} strokeDasharray="10 8" />
+ {label && <text x={c.x + c.w - 6} y={c.sy(y) - 14} textAnchor="end" fill={tone(t)} style={{font: `500 28px ${T.sans}`}}>{label}</text>}
+ </g>;
+};
+export const VLine: React.FC<{x: number; label?: string; delay?: number; tone?: Tone}> = ({x, label, delay = 0, tone: t = "blue"}) => {
+ const c = usePlot();
+ const p = useProgress(delay, 18);
+ return <g opacity={p}>
+ <line x1={c.sx(x)} x2={c.sx(x)} y1={c.y} y2={c.y + c.h} stroke={tone(t)} strokeWidth={2.5} strokeDasharray="10 8" />
+ {label && <text x={c.sx(x) + 10} y={c.y + 30} fill={tone(t)} style={{font: `500 28px ${T.sans}`}}>{label}</text>}
+ </g>;
+};
+/** Text at a data coordinate. */
+export const PlotLabel: React.FC<{x: number; y: number; text: string; delay?: number; tone?: Tone; anchor?: "start" | "middle" | "end"}> =
+ ({x, y, text, delay = 0, tone: t = "soft", anchor = "start"}) => {
+ const c = usePlot();
+ const p = useProgress(delay, 14);
+ return <text x={c.sx(x)} y={c.sy(y)} textAnchor={anchor} opacity={p} fill={tone(t)}
+ style={{font: `500 28px ${T.sans}`}}>{text}</text>;
+ };
+
+// ------------------------------------------------------------------ timeline
+
+/** Honest-scale timeline. Events appear one by one; labels alternate above/below the axis. */
+export const Timeline: React.FC<{start: number; end: number; x?: number; y?: number; w?: number;
+ events: {year: number; label: string; tone?: Tone}[]; eras?: {from: number; to: number; label: string}[];
+ delay?: number; every?: number; focus?: number}> = (props) => {
+ const {start, end, x = 140, y = 560, w = 1640, events, eras = [], delay = 0, every = 12, focus} = props;
+ const f = useCurrentFrame();
+ const p = useProgress(delay, 24);
+ const sx = (v: number) => x + ((v - start) / (end - start)) * w;
+ const step = (end - start) > 60 ? 10 : 5;
+ const ticks: number[] = [];
+ for (let v = Math.ceil(start / step) * step; v <= end; v += step) ticks.push(v);
+ return (
+ <svg width={W} height={H} style={{position: "absolute", left: 0, top: 0, overflow: "visible"}}>
+ {eras.map((e, i) => <g key={"e" + i} opacity={p}>
+ <rect x={sx(e.from)} y={y - 250} width={sx(e.to) - sx(e.from)} height={8} rx={4}
+ fill={i % 2 ? T.muted : T.accent} opacity={0.35} />
+ <text x={sx(e.from)} y={y - 266} fill={T.muted} style={{font: `500 24px ${T.sans}`}}>{e.label}</text>
+ </g>)}
+ <line x1={x} x2={x + w * p} y1={y} y2={y} stroke={T.ink} strokeWidth={2.5} />
+ {ticks.map((v) => <g key={v} opacity={p}>
+ <line x1={sx(v)} x2={sx(v)} y1={y} y2={y + 12} stroke={T.muted} strokeWidth={2} />
+ <text x={sx(v)} y={y + 46} textAnchor="middle" fill={T.muted} style={{font: `400 24px ${T.mono}`}}>{v}</text>
+ </g>)}
+ {events.map((e, i) => {
+ const k = interpolate(f - (delay + 20 + i * every), [0, 12], [0, 1], {extrapolateLeft: "clamp", extrapolateRight: "clamp"});
+ if (k <= 0) return null;
+ const up = i % 2 === 0, lift = up ? -(70 + (i % 4 === 0 ? 0 : 60)) : 90 + (i % 4 === 1 ? 0 : 60);
+ const hot = focus === e.year || e.tone === "accent";
+ const col = hot ? T.accent : tone(e.tone || "ink");
+ return <g key={i} opacity={focus !== undefined && !hot ? 0.45 * k : k}>
+ <line x1={sx(e.year)} x2={sx(e.year)} y1={y} y2={y + (lift + (up ? 12 : -30)) * k} stroke={col} strokeWidth={1.5} />
+ <circle cx={sx(e.year)} cy={y} r={hot ? 10 : 7} fill={col} />
+ <text x={sx(e.year)} y={y + lift - (up ? 34 : -8)} textAnchor="middle" fill={col}
+ style={{font: `500 24px ${T.mono}`}}>{e.year}</text>
+ <text x={sx(e.year)} y={y + lift + (up ? -2 : 40)} textAnchor="middle" fill={hot ? T.accent : T.ink}
+ style={{font: `${hot ? 600 : 500} 28px ${T.sans}`}}>{e.label}</text>
+ </g>;
+ })}
+ </svg>
+ );
+};
+
+// ------------------------------------------------------------------ map
+
+/** Place names the map understands, as [longitude, latitude]. */
+export const PLACES: Record<string, [number, number]> = {
+ 北京: [116.4, 39.9], 天津: [117.2, 39.13], 上海: [121.47, 31.23], 南京: [118.8, 32.06], 广州: [113.26, 23.13],
+ 香港: [114.17, 22.3], 澳门: [113.54, 22.19], 武昌: [114.31, 30.55], 武汉: [114.31, 30.59], 长沙: [112.94, 28.23],
+ 南昌: [115.86, 28.68], 瑞金: [116.03, 25.89], 井冈山: [114.17, 26.57], 遵义: [106.93, 27.73], 延安: [109.49, 36.59],
+ 重庆: [106.55, 29.56], 西安: [108.94, 34.34], 沈阳: [123.43, 41.8], 旅顺: [121.26, 38.81], 大连: [121.61, 38.91],
+ 威海: [122.12, 37.51], 青岛: [120.38, 36.07], 台北: [121.56, 25.04], 台湾: [120.96, 23.7], 福州: [119.3, 26.08],
+ 厦门: [118.09, 24.48], 宁波: [121.55, 29.87], 杭州: [120.16, 30.27], 金田: [110.08, 23.39], 桂林: [110.29, 25.27],
+ 成都: [104.07, 30.57], 昆明: [102.83, 24.88], 贵阳: [106.63, 26.65], 济南: [117.0, 36.65], 太原: [112.55, 37.87],
+ 哈尔滨: [126.63, 45.75], 长春: [125.32, 43.82], 西柏坡: [114.0, 38.35], 卢沟桥: [116.21, 39.85], 徐州: [117.28, 34.2],
+ 锦州: [121.13, 41.1], 拉萨: [91.13, 29.65], 乌鲁木齐: [87.62, 43.83], 兰州: [103.83, 36.06], 海口: [110.35, 20.02],
+ 汕头: [116.68, 23.35], 大渡河: [102.25, 29.25], 赤水: [105.7, 28.58], 吴淞口: [121.5, 31.4], 虎门: [113.67, 22.8],
+};
+type Where = string | [number, number];
+
+/** China outline with places and routes. `places`/`routes` take names from PLACES or [lon, lat]. */
+export const ChinaMap: React.FC<{x?: number; y?: number; h?: number; delay?: number;
+ places?: {at: Where; label?: string; delay?: number; tone?: Tone}[];
+ routes?: {via: Where[]; delay?: number; dur?: number; tone?: Tone; label?: string}[]}> = (props) => {
+ const {x = 880, y = 140, h = 700, delay = 0, places = [], routes = []} = props;
+ const f = useCurrentFrame();
+ const p = useProgress(delay, 24);
+ const [lo0, lo1, la0, la1] = [73, 135.5, 17.5, 54];
+ const kx = Math.cos((36 * Math.PI) / 180);
+ const s = h / (la1 - la0);
+ const pr = ([lon, lat]: [number, number]): [number, number] => [x + (lon - lo0) * kx * s, y + (la1 - lat) * s];
+ const at = (w: Where): [number, number] => {
+ const ll = typeof w === "string" ? PLACES[w] : w;
+ if (!ll) throw new Error(`ChinaMap: unknown place "${w}" (use a PLACES name or [lon, lat])`);
+ return pr(ll);
+ };
+ void lo1;
+ return (
+ <svg width={W} height={H} style={{position: "absolute", left: 0, top: 0, overflow: "visible"}}>
+ <g opacity={p}>
+ {(outline as number[][][]).map((ring, i) => <polygon key={i} points={ring.map((ll) => pr(ll as [number, number]).join(",")).join(" ")}
+ fill={T.paper2} stroke={T.muted} strokeWidth={2} strokeLinejoin="round" />)}
+ </g>
+ {routes.map((r, i) => {
+ const pts = r.via.map(at);
+ const k = interpolate(f, [(r.delay ?? delay + 20), (r.delay ?? delay + 20) + (r.dur ?? 40)], [0, 1],
+ {extrapolateLeft: "clamp", extrapolateRight: "clamp", easing: ease});
+ if (k <= 0) return null;
+ const d = pts.map(([a, b], j) => `${j ? "L" : "M"}${a} ${b}`).join(" ");
+ const [lx, ly] = pts[Math.floor(pts.length / 2)];
+ return <g key={"r" + i}>
+ <path d={d} pathLength={1} fill="none" stroke={tone(r.tone || "accent")} strokeWidth={4}
+ strokeDasharray={1} strokeDashoffset={1 - k} strokeLinecap="round" strokeLinejoin="round" />
+ {r.label && <text x={lx + 14} y={ly - 14} fill={tone(r.tone || "accent")} opacity={k}
+ style={{font: `500 26px ${T.sans}`}}>{r.label}</text>}
+ </g>;
+ })}
+ {places.map((pl, i) => {
+ const k = interpolate(f, [(pl.delay ?? delay + 20 + i * 8), (pl.delay ?? delay + 20 + i * 8) + 12], [0, 1],
+ {extrapolateLeft: "clamp", extrapolateRight: "clamp"});
+ if (k <= 0) return null;
+ const [a, b] = at(pl.at);
+ const col = tone(pl.tone || "ink");
+ return <g key={"p" + i} opacity={k}>
+ <circle cx={a} cy={b} r={8 + 8 * (1 - k)} fill={col} />
+ <text x={a + 16} y={b + 9} fill={col} style={{font: `600 28px ${T.sans}`}}>{pl.label ?? (typeof pl.at === "string" ? pl.at : "")}</text>
+ </g>;
+ })}
+ </svg>
+ );
+};
diff --git a/deeptutor/agents/video_lesson/remotion/package.json b/deeptutor/agents/video_lesson/remotion/package.json
new file mode 100644
index 000000000..6c7f68be7
--- /dev/null
+++ b/deeptutor/agents/video_lesson/remotion/package.json
@@ -0,0 +1,12 @@
+{
+ "name": "deeptutor-video-lesson-runtime",
+ "private": true,
+ "type": "module",
+ "dependencies": {
+ "@remotion/player": "4.0.537",
+ "esbuild": "0.28.2",
+ "react": "19.3.1",
+ "react-dom": "19.3.1",
+ "remotion": "4.0.537"
+ }
+}
diff --git a/deeptutor/agents/video_lesson/runtime.py b/deeptutor/agents/video_lesson/runtime.py
new file mode 100644
index 000000000..ccc1136aa
--- /dev/null
+++ b/deeptutor/agents/video_lesson/runtime.py
@@ -0,0 +1,189 @@
+"""Remotion runtime for video lessons: install once, compile per lesson, wrap in a page.
+
+The model writes ``Lesson.tsx`` against the shipped kit (``remotion/kit.tsx``).
+``build.mjs`` compiles it with esbuild, renders sample frames in a
+permission-restricted Node process, and bundles it with ``@remotion/player``.
+The page this module writes is self-contained: the learner's browser plays the
+composition live, so no video file is ever encoded on the server.
+"""
+
+from __future__ import annotations
+
+import asyncio
+from dataclasses import dataclass, field
+from html import escape
+import json
+import os
+from pathlib import Path
+import shutil
+
+from deeptutor.services.path_service import get_path_service
+
+ASSETS_DIR = Path(__file__).resolve().parent / "remotion"
+KIT_FILES = ("kit.tsx", "china_outline.json")
+BUILD_TIMEOUT_S = 600
+INSTALL_TIMEOUT_S = 900
+
+_install_lock = asyncio.Lock()
+
+
+class VideoLessonRuntimeError(RuntimeError):
+ """The Node toolchain for video lessons is missing or could not be installed."""
+
+
+@dataclass
+class BuildResult:
+ ok: bool
+ stage: str
+ errors: list[str] = field(default_factory=list)
+ frames: list[dict] = field(default_factory=list)
+
+
+def runtime_dir() -> Path:
+ """Where the npm packages live; ``DEEPTUTOR_REMOTION_RUNTIME`` overrides the default."""
+ override = os.environ.get("DEEPTUTOR_REMOTION_RUNTIME", "").strip()
+ if override:
+ return Path(override).expanduser().resolve()
+ return get_path_service().get_runtime_state_dir() / "remotion"
+
+
+def _node() -> str:
+ node = shutil.which("node")
+ if not node:
+ raise VideoLessonRuntimeError(
+ "Video lessons need Node.js 22+ on the server (the `node` command was not found)."
+ )
+ return node
+
+
+def _installed(root: Path) -> bool:
+ manifest = json.loads((ASSETS_DIR / "package.json").read_text(encoding="utf-8"))
+ for name, version in manifest["dependencies"].items():
+ pkg = root / "node_modules" / name / "package.json"
+ if not pkg.is_file():
+ return False
+ if json.loads(pkg.read_text(encoding="utf-8")).get("version") != version:
+ return False
+ return True
+
+
+async def ensure_runtime() -> Path:
+ """Install the pinned npm packages on first use; later calls return immediately."""
+ _node()
+ root = runtime_dir()
+ if _installed(root):
+ return root
+ async with _install_lock:
+ if _installed(root):
+ return root
+ npm = shutil.which("npm")
+ if not npm:
+ raise VideoLessonRuntimeError(
+ "Video lessons need npm to install Remotion on first use."
+ )
+ root.mkdir(parents=True, exist_ok=True)
+ shutil.copy(ASSETS_DIR / "package.json", root / "package.json")
+ proc = await asyncio.create_subprocess_exec(
+ npm,
+ "install",
+ "--no-audit",
+ "--no-fund",
+ "--omit=dev",
+ cwd=root,
+ stdout=asyncio.subprocess.PIPE,
+ stderr=asyncio.subprocess.STDOUT,
+ )
+ try:
+ out, _ = await asyncio.wait_for(proc.communicate(), timeout=INSTALL_TIMEOUT_S)
+ except asyncio.TimeoutError as exc:
+ proc.kill()
+ raise VideoLessonRuntimeError("Installing Remotion timed out.") from exc
+ if proc.returncode != 0 or not _installed(root):
+ tail = out.decode("utf-8", errors="replace")[-1500:]
+ raise VideoLessonRuntimeError(f"Installing Remotion failed:\n{tail}")
+ return root
+
+
+def prepare_workdir(work_dir: Path, code: str) -> Path:
+ """Write the lesson next to a fresh copy of the kit and return the lesson path."""
+ work_dir.mkdir(parents=True, exist_ok=True)
+ for name in KIT_FILES:
+ shutil.copy(ASSETS_DIR / name, work_dir / name)
+ lesson = work_dir / "Lesson.tsx"
+ lesson.write_text(code, encoding="utf-8")
+ return lesson
+
+
+async def build_lesson(lesson: Path, bundle: Path) -> BuildResult:
+ """Compile, frame-check and bundle one lesson. Failures come back as data for the model."""
+ root = await ensure_runtime()
+ proc = await asyncio.create_subprocess_exec(
+ _node(),
+ str(ASSETS_DIR / "build.mjs"),
+ str(lesson),
+ str(bundle),
+ env={**os.environ, "DEEPTUTOR_REMOTION_RUNTIME": str(root)},
+ stdout=asyncio.subprocess.PIPE,
+ stderr=asyncio.subprocess.PIPE,
+ )
+ try:
+ out, err = await asyncio.wait_for(proc.communicate(), timeout=BUILD_TIMEOUT_S)
+ except asyncio.TimeoutError:
+ proc.kill()
+ return BuildResult(False, "timeout", [f"build did not finish within {BUILD_TIMEOUT_S}s"])
+ lines = out.decode("utf-8", errors="replace").strip().splitlines()
+ try:
+ data = json.loads(lines[-1])
+ except (IndexError, json.JSONDecodeError):
+ detail = (err.decode("utf-8", errors="replace") or "no output")[-1500:]
+ return BuildResult(False, "build", [detail])
+ return BuildResult(
+ ok=bool(data.get("ok")),
+ stage=str(data.get("stage", "")),
+ errors=[str(e) for e in data.get("errors") or []],
+ frames=list(data.get("frames") or []),
+ )
+
+
+PAGE = """<!doctype html>
+<html lang="{lang}">
+<head>
+<meta charset="utf-8">
+<meta name="viewport" content="width=device-width, initial-scale=1">
+<title>{title}</title>
+<link href="https://fonts.googleapis.com/css2?family=Geist:wght@400;500;600&family=Geist+Mono:wght@400;500&family=Lora:ital,wght@0,400;0,500;0,600;1,500&display=swap" rel="stylesheet">
+<style>
+* {{ box-sizing: border-box }}
+html, body {{ margin: 0; background: #fdfcf9 }}
+#player {{ width: 100%; max-width: 1280px; margin: 0 auto }}
+</style>
+</head>
+<body>
+<div id="player"></div>
+<script>{bundle}</script>
+</body>
+</html>
+"""
+
+
+def write_page(bundle: Path, page: Path, *, title: str, language: str) -> Path:
+ script = bundle.read_text(encoding="utf-8").replace("</script", "<\\/script")
+ page.parent.mkdir(parents=True, exist_ok=True)
+ page.write_text(
+ PAGE.format(
+ lang="zh-CN" if language.startswith("zh") else "en", title=escape(title), bundle=script
+ ),
+ encoding="utf-8",
+ )
+ return page
+
+
+__all__ = [
+ "BuildResult",
+ "VideoLessonRuntimeError",
+ "build_lesson",
+ "ensure_runtime",
+ "prepare_workdir",
+ "runtime_dir",
+ "write_page",
+]
diff --git a/pyproject.toml b/pyproject.toml
index 3b68bbca5..12f2ee6e5 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -336,6 +336,9 @@ deeptutor = [
"**/*.sh",
"**/*.j2",
"**/*.jinja",
+ # video_lesson's Remotion kit and build script, compiled at run time
+ "**/*.tsx",
+ "**/*.mjs",
]
deeptutor_cli = ["**/*.md"]
deeptutor_web = ["**/*", ".next/**/*"]
diff --git a/tests/agents/video_lesson/__init__.py b/tests/agents/video_lesson/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/tests/agents/video_lesson/test_runtime.py b/tests/agents/video_lesson/test_runtime.py
new file mode 100644
index 000000000..4498f95a0
--- /dev/null
+++ b/tests/agents/video_lesson/test_runtime.py
@@ -0,0 +1,34 @@
+"""The shipped Remotion runtime assets and the player page."""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+from deeptutor.agents.video_lesson.runtime import ASSETS_DIR, KIT_FILES, prepare_workdir, write_page
+
+
+def test_shipped_runtime_assets_exist() -> None:
+ for name in (*KIT_FILES, "build.mjs", "package.json"):
+ assert (ASSETS_DIR / name).is_file(), name
+ deps = json.loads((ASSETS_DIR / "package.json").read_text(encoding="utf-8"))["dependencies"]
+ # Pinned exactly: a lesson that compiled once must compile the same way later.
+ assert all(v[0].isdigit() for v in deps.values())
+
+
+def test_prepare_workdir_copies_the_kit(tmp_path: Path) -> None:
+ lesson = prepare_workdir(tmp_path / "source", "export const x = 1;")
+ assert lesson.read_text(encoding="utf-8") == "export const x = 1;"
+ for name in KIT_FILES:
+ assert (tmp_path / "source" / name).is_file()
+
+
+def test_write_page_inlines_the_bundle_safely(tmp_path: Path) -> None:
+ bundle = tmp_path / "player.js"
+ bundle.write_text('console.log("</script><b>x</b>");', encoding="utf-8")
+ page = write_page(bundle, tmp_path / "out" / "lesson.html", title="a < b", language="zh")
+ html = page.read_text(encoding="utf-8")
+ assert html.count("</script>") == 1
+ assert "<\/script><b>x</b>" in html
+ assert "<title>a &lt; b</title>" in html
+ assert 'lang="zh-CN"' in html