Skip to content

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

feat(video-learning): export timestamped notes as markdown (#1203) (#1204)

evan188199-tech793c8e24b8b0
diff --git a/deeptutor/api/routers/video_learning.py b/deeptutor/api/routers/video_learning.py
index 0218610b0..025ff8f38 100644
--- a/deeptutor/api/routers/video_learning.py
+++ b/deeptutor/api/routers/video_learning.py
@@ -167,6 +167,22 @@ async def list_video_notes(material_id: str) -> list[dict[str, Any]]:
raise _note_error(exc) from exc
[email protected]("/materials/{material_id}/notes.md")
+async def export_video_notes(material_id: str) -> Response:
+ try:
+ markdown = video_notes.export_notes(video_notes.get_notebook_manager(), material_id)
+ return Response(
+ markdown,
+ media_type="text/markdown",
+ headers={
+ "Cache-Control": "no-store",
+ "Content-Disposition": 'attachment; filename="video-notes.md"',
+ },
+ )
+ except Exception as exc:
+ raise _note_error(exc) from exc
+
+
@router.post("/materials/{material_id}/notes")
async def create_video_note(material_id: str, payload: CreateVideoNoteRequest) -> dict[str, Any]:
try:
diff --git a/deeptutor/video_learning/notes.py b/deeptutor/video_learning/notes.py
index fa2483fc8..8ebde156b 100644
--- a/deeptutor/video_learning/notes.py
+++ b/deeptutor/video_learning/notes.py
@@ -114,6 +114,33 @@ def list_notes(manager: NotebookManager, material_id: str) -> list[dict[str, Any
return notes
+def export_notes(manager: NotebookManager, material_id: str) -> str:
+ material = get_timed_media_store().get(material_id)
+ notes = list_notes(manager, material_id)
+ title = _clip_text(
+ str(material.get("metadata", {}).get("title") or "Timed media").strip() or "Timed media",
+ 140,
+ )
+ lines = [f"# Video notes: {title}"]
+ if not notes:
+ lines.extend(["", "_No timestamped notes captured yet._"])
+ return "\n".join(lines).strip() + "\n"
+
+ for note in notes:
+ lines.extend(
+ (
+ "",
+ f"## {_format_time(note['time_seconds'])}",
+ "",
+ str(note.get("body") or "").strip(),
+ )
+ )
+ quote = _clip_text(note.get("quote"))
+ if quote:
+ lines.extend(("", f"> {quote}"))
+ return "\n".join(lines).strip() + "\n"
+
+
def create_note(
manager: NotebookManager, material_id: str, body: str, time_seconds: float
) -> dict[str, Any]:
@@ -199,6 +226,7 @@ __all__ = [
"NOTEBOOK_NAME",
"create_note",
"delete_note",
+ "export_notes",
"get_notebook_manager",
"list_notes",
"update_note",
diff --git a/tests/video_learning/test_router.py b/tests/video_learning/test_router.py
index 498ebbe53..20595f3db 100644
--- a/tests/video_learning/test_router.py
+++ b/tests/video_learning/test_router.py
@@ -190,6 +190,59 @@ def test_video_note_errors_are_bounded_and_useful(client: TestClient) -> None:
assert client.put(f"{notes_url}/missing-note", json={"body": "Note"}).status_code == 404
+def test_video_notes_export_markdown_and_stay_account_scoped(
+ client: TestClient,
+ notebook_manager: NotebookManager,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ material = _material()
+ material["metadata"]["title"] = "Timestamped lesson"
+ material["transcript"]["cues"] = [
+ {"start": 1.25, "end": 3.5, "text": "First quoted idea."},
+ {"start": 65, "end": 70, "text": "Second quoted idea."},
+ {"start": 80, "end": 90, "text": "Unquoted transcript tail."},
+ ]
+ service.get_timed_media_store().save(material)
+ material_id = str(material["material_id"])
+ notes_url = f"/api/video-learning/materials/{material_id}/notes"
+ export_url = f"{notes_url}.md"
+
+ empty_response = client.get(export_url)
+ assert empty_response.status_code == 200
+ assert empty_response.headers["content-type"].startswith("text/markdown")
+ assert empty_response.text == (
+ "# Video notes: Timestamped lesson\n\n_No timestamped notes captured yet._\n"
+ )
+
+ client.post(notes_url, json={"body": "Opening note", "time_seconds": 2})
+ client.post(notes_url, json={"body": "Later note", "time_seconds": 66})
+
+ response = client.get(export_url)
+ assert response.status_code == 200
+ assert response.headers["content-disposition"] == 'attachment; filename="video-notes.md"'
+ assert response.text == (
+ "# Video notes: Timestamped lesson\n\n"
+ "## 0:02\n\nOpening note\n\n> First quoted idea.\n\n"
+ "## 1:06\n\nLater note\n\n> Second quoted idea.\n"
+ )
+ assert "Unquoted transcript tail" not in response.text
+ assert "https://youtu.be" not in response.text
+ assert "provider_cache" not in response.text
+ assert "dQw4w9WgXcQ" not in response.text
+
+ other_manager = NotebookManager(
+ base_dir=str(notebook_manager.base_dir.parent / "export-account-notebooks")
+ )
+ monkeypatch.setattr(video_notes, "get_notebook_manager", lambda: other_manager)
+ isolated = client.get(export_url)
+ assert isolated.status_code == 200
+ assert "Opening note" not in isolated.text
+ assert "Later note" not in isolated.text
+
+ monkeypatch.setattr(video_notes, "get_notebook_manager", lambda: notebook_manager)
+ assert client.get("/api/video-learning/materials/0123456789abcdef/notes.md").status_code == 404
+
+
def test_progress_does_not_replace_known_duration_with_client_value(client: TestClient) -> None:
material = _material(duration=100)
service.get_timed_media_store().save(material)
diff --git a/web/components/watching/WatchingPane.tsx b/web/components/watching/WatchingPane.tsx
index 01a63fb8a..4e4aa0b0e 100644
--- a/web/components/watching/WatchingPane.tsx
+++ b/web/components/watching/WatchingPane.tsx
@@ -5,6 +5,7 @@ import {
AlertTriangle,
Check,
Captions,
+ Copy,
ExternalLink,
Loader2,
Pencil,
@@ -22,6 +23,7 @@ import type { PlayerController } from "@/lib/video-player-controller";
import {
createVideoNote,
deleteVideoNote,
+ exportVideoNotes,
listVideoNotes,
saveVideoProgress,
updateVideoNote,
@@ -62,7 +64,10 @@ export function WatchingPane({ onClose }: { onClose(): void }) {
const [editingNoteId, setEditingNoteId] = useState<string | null>(null);
const [editingDraft, setEditingDraft] = useState("");
const [noteBusy, setNoteBusy] = useState(false);
+ const [notesExportBusy, setNotesExportBusy] = useState(false);
+ const [notesCopied, setNotesCopied] = useState(false);
const [pendingDeleteId, setPendingDeleteId] = useState<string | null>(null);
+ const notesExportRequestRef = useRef(0);
const controllerRef = useRef<PlayerController | null>(null);
const activeMaterialIdRef = useRef(materialId);
const lastSavedRef = useRef(0);
@@ -166,6 +171,9 @@ export function WatchingPane({ onClose }: { onClose(): void }) {
setEditingNoteId(null);
setEditingDraft("");
setPendingDeleteId(null);
+ notesExportRequestRef.current += 1;
+ setNotesExportBusy(false);
+ setNotesCopied(false);
if (!materialId) {
setNotesLoading(false);
return () => {
@@ -216,6 +224,7 @@ export function WatchingPane({ onClose }: { onClose(): void }) {
if (activeMaterialIdRef.current !== requestedMaterialId) return;
setNotes((current) => sortNotes([...current, saved]));
setNoteDraft("");
+ setNotesCopied(false);
} catch (caught) {
if (activeMaterialIdRef.current !== requestedMaterialId) return;
setNotesError(
@@ -247,6 +256,7 @@ export function WatchingPane({ onClose }: { onClose(): void }) {
);
setEditingNoteId(null);
setEditingDraft("");
+ setNotesCopied(false);
} catch (caught) {
if (activeMaterialIdRef.current !== requestedMaterialId) return;
setNotesError(
@@ -273,6 +283,7 @@ export function WatchingPane({ onClose }: { onClose(): void }) {
setEditingDraft("");
}
setPendingDeleteId(null);
+ setNotesCopied(false);
} catch (caught) {
if (activeMaterialIdRef.current !== requestedMaterialId) return;
setNotesError(
@@ -283,6 +294,31 @@ export function WatchingPane({ onClose }: { onClose(): void }) {
}
};
+ const copyNotes = async () => {
+ if (!material || !notes.length || notesExportBusy) return;
+ const requestedMaterialId = material.material_id;
+ const requestId = ++notesExportRequestRef.current;
+ setNotesExportBusy(true);
+ setNotesCopied(false);
+ try {
+ const markdown = await exportVideoNotes(requestedMaterialId);
+ await navigator.clipboard.writeText(markdown);
+ if (notesExportRequestRef.current !== requestId) return;
+ setNotesCopied(true);
+ } catch (caught) {
+ if (notesExportRequestRef.current !== requestId) return;
+ setNotesError(
+ caught instanceof Error
+ ? caught.message
+ : t("Notes could not be copied."),
+ );
+ } finally {
+ if (notesExportRequestRef.current === requestId) {
+ setNotesExportBusy(false);
+ }
+ }
+ };
+
const closePane = () => {
persist();
close();
@@ -568,6 +604,21 @@ export function WatchingPane({ onClose }: { onClose(): void }) {
)}
{t("Add video note")}
</button>
+ <button
+ type="button"
+ onClick={() => void copyNotes()}
+ disabled={notesExportBusy || !notes.length}
+ className="inline-flex items-center gap-1.5 rounded-lg border border-[var(--border)] px-3 py-2 text-sm disabled:opacity-50"
+ >
+ {notesExportBusy ? (
+ <Loader2 className="h-4 w-4 animate-spin" />
+ ) : notesCopied ? (
+ <Check className="h-4 w-4" />
+ ) : (
+ <Copy className="h-4 w-4" />
+ )}
+ {notesCopied ? t("Notes copied") : t("Copy notes")}
+ </button>
</form>
{notesError && (
diff --git a/web/lib/video-learning-api.ts b/web/lib/video-learning-api.ts
index 65fbe6de4..fe81e48a7 100644
--- a/web/lib/video-learning-api.ts
+++ b/web/lib/video-learning-api.ts
@@ -78,20 +78,31 @@ export interface VideoLearningSettings {
async function unwrap<T>(response: Response): Promise<T> {
if (!response.ok) {
- const payload = await response.json().catch(() => ({}));
- const detail = (payload as { detail?: unknown })?.detail;
- const message =
- typeof detail === "string"
- ? detail
- : typeof (detail as { message?: unknown } | undefined)?.message ===
- "string"
- ? (detail as { message: string }).message
- : null;
- throw new Error(message || `Request failed (${response.status})`);
+ throw await responseError(response);
}
return (await response.json()) as T;
}
+async function responseError(response: Response): Promise<Error> {
+ const payload = await response.json().catch(() => ({}));
+ const detail = (payload as { detail?: unknown })?.detail;
+ const message =
+ typeof detail === "string"
+ ? detail
+ : typeof (detail as { message?: unknown } | undefined)?.message ===
+ "string"
+ ? (detail as { message: string }).message
+ : null;
+ return new Error(message || `Request failed (${response.status})`);
+}
+
+async function unwrapText(response: Response): Promise<string> {
+ if (!response.ok) {
+ throw await responseError(response);
+ }
+ return response.text();
+}
+
export async function listVideoNotes(materialId: string): Promise<VideoNote[]> {
return unwrap(
await apiFetch(
@@ -122,6 +133,17 @@ export async function createVideoNote(
);
}
+export async function exportVideoNotes(materialId: string): Promise<string> {
+ return unwrapText(
+ await apiFetch(
+ apiUrl(
+ `/api/video-learning/materials/${encodeURIComponent(materialId)}/notes.md`,
+ ),
+ { cache: "no-store" },
+ ),
+ );
+}
+
export async function updateVideoNote(
materialId: string,
noteId: string,
diff --git a/web/locales/en/app.json b/web/locales/en/app.json
index 3f13043ad..6a9025336 100644
--- a/web/locales/en/app.json
+++ b/web/locales/en/app.json
@@ -4523,6 +4523,8 @@
"Reading extensions": "Reading extensions",
"Video notes": "Video notes",
"Add video note": "Add video note",
+ "Copy notes": "Copy notes",
+ "Notes copied": "Notes copied",
"Save video note": "Save video note",
"Note at {{time}}": "Note at {{time}}",
"Edit note at {{time}}": "Edit note at {{time}}",
@@ -4532,6 +4534,7 @@
"No notes yet.": "No notes yet.",
"Loading notes.": "Loading notes.",
"Notes could not be loaded.": "Notes could not be loaded.",
+ "Notes could not be copied.": "Notes could not be copied.",
"Note was not saved.": "Note was not saved.",
"Note was not deleted.": "Note was not deleted.",
"Video learning panels": "Video learning panels",
diff --git a/web/locales/zh/app.json b/web/locales/zh/app.json
index 8576f7c93..b41b765f3 100644
--- a/web/locales/zh/app.json
+++ b/web/locales/zh/app.json
@@ -4523,6 +4523,8 @@
"Reading extensions": "阅读扩展",
"Video notes": "视频笔记",
"Add video note": "添加视频笔记",
+ "Copy notes": "复制笔记",
+ "Notes copied": "笔记已复制",
"Save video note": "保存视频笔记",
"Note at {{time}}": "{{time}} 的笔记",
"Edit note at {{time}}": "编辑 {{time}} 的笔记",
@@ -4532,6 +4534,7 @@
"No notes yet.": "暂无笔记。",
"Loading notes.": "正在加载笔记。",
"Notes could not be loaded.": "无法加载笔记。",
+ "Notes could not be copied.": "无法复制笔记。",
"Note was not saved.": "笔记未保存。",
"Note was not deleted.": "笔记未删除。",
"Video learning panels": "视频学习面板",
diff --git a/web/tests/e2e/video-learning.audit.ts b/web/tests/e2e/video-learning.audit.ts
index df825f80e..abdd8e0f6 100644
--- a/web/tests/e2e/video-learning.audit.ts
+++ b/web/tests/e2e/video-learning.audit.ts
@@ -12,6 +12,8 @@ test("YouTube learning survives reload and switches to Invidious without silent
let materialRequestCount = 0;
let savedPosition = 0;
let nativeResolveCount = 0;
+ let exportRequestCount = 0;
+ let exportShouldFail = false;
let nextNoteId = 1;
const notes: Array<{
notebook_id: string;
@@ -79,6 +81,8 @@ test("YouTube learning survives reload and switches to Invidious without silent
},
});
+ await page.context().grantPermissions(["clipboard-read", "clipboard-write"]);
+
await page.addInitScript(() => {
class FakePlayer {
current = 0;
@@ -183,6 +187,15 @@ test("YouTube learning survives reload and switches to Invidious without silent
if (path.endsWith("/notes") && request.method() === "GET") {
return json(notes);
}
+ if (path.endsWith("/notes.md")) {
+ exportRequestCount += 1;
+ if (exportShouldFail) return json({ detail: "Notes export failed" }, 500);
+ return route.fulfill({
+ status: 200,
+ contentType: "text/markdown",
+ body: "# Video notes: Timestamped lesson\n\n## 0:08\n\nFirst timestamped note\n",
+ });
+ }
if (path.endsWith("/notes") && request.method() === "POST") {
const body = request.postDataJSON() as {
body: string;
@@ -261,10 +274,24 @@ test("YouTube learning survives reload and switches to Invidious without silent
await page.getByRole("tab", { name: "Video notes" }).click();
await expect(page.getByText("No notes yet.")).toBeVisible();
+ await expect(page.getByRole("button", { name: "Copy notes" })).toBeDisabled();
await page.getByPlaceholder("Note at 0:08").fill("First timestamped note");
await page.getByRole("button", { name: "Add video note" }).click();
await expect(page.getByText("First timestamped note")).toBeVisible();
await expect(page.getByText("The first grounded concept.")).toBeVisible();
+ await page.getByRole("button", { name: "Copy notes" }).click();
+ await expect(page.getByRole("button", { name: "Notes copied" })).toBeVisible();
+ await expect.poll(() => exportRequestCount).toBe(1);
+ await expect(
+ page.evaluate(() => navigator.clipboard.readText()),
+ ).resolves.toContain("First timestamped note");
+
+ exportShouldFail = true;
+ await page.getByRole("button", { name: "Notes copied" }).click();
+ await expect(
+ page.getByRole("alert").filter({ hasText: "Notes export failed" }),
+ ).toBeVisible();
+ exportShouldFail = false;
await page.goto("/");
await page.waitForTimeout(100);