diff --git a/deeptutor/api/routers/guided_learning.py b/deeptutor/api/routers/guided_learning.py index 29d3bbfa7..12046d589 100644 --- a/deeptutor/api/routers/guided_learning.py +++ b/deeptutor/api/routers/guided_learning.py @@ -259,3 +259,69 @@ async def redo_progress(book_id: str): if qpath.exists(): qpath.unlink() return {"status": "ok"} + + +class NotebookRecordInput(BaseModel): + id: str + type: str = "note" + title: str = "" + output: str = "" + + +class GenerateFromNotebookRequest(BaseModel): + notebook_id: str + records: list[NotebookRecordInput] + + +@router.post("/progress/{book_id}/generate-from-notebook") +async def generate_from_notebook(book_id: str, body: GenerateFromNotebookRequest): + if not book_id or ".." in book_id or "/" in book_id or "\\" in book_id or ":" in book_id: + raise HTTPException(status_code=400, detail="Invalid book_id") + if not body.records: + raise HTTPException(status_code=400, detail="No records provided") + + records_text = "\n\n".join( + f"[{r.type}] {r.title}: {r.output[:500]}" + for r in body.records[:20] + ) + from deeptutor.services.llm import complete + prompt = f"""根据以下笔记本记录,提取知识点并组织为学习模块。 +每个模块包含:name(模块名)、knowledge_points(知识点列表,每个有 name 和 type)。 +type 可选:memory / concept / procedure / design。 +返回 JSON: {{"modules": [{{"name": "...", "knowledge_points": [{{"name": "...", "type": "concept"}}]}}]}} + +笔记本记录: +{records_text}""" + response = await complete(prompt=prompt, system_prompt="你是学习模块规划助手。只输出 JSON。") + import json + try: + data = json.loads(response) + except json.JSONDecodeError: + raise HTTPException(status_code=500, detail="LLM returned invalid JSON") + + modules_raw = data.get("modules", []) + service = get_learning_service() + progress = service.get_or_create(book_id) + modules = [] + for i, m in enumerate(modules_raw): + kps = [ + KnowledgePoint( + id=f"{book_id}_nb{i}_kp{j}", + name=kp["name"], + type=kp.get("type", "concept"), + module_id=f"{book_id}_nb{i}", + ) + for j, kp in enumerate(m.get("knowledge_points", [])) + ] + modules.append(LearningModule( + id=f"{book_id}_nb{i}", + name=m.get("name", f"模块 {i+1}"), + order=i, + pass_threshold=0.7, + knowledge_points=kps, + )) + service.init_modules(progress, modules) + progress.current_module_id = modules[0].id if modules else "" + progress.current_kp_index = 0 + service.save(progress) + return {"status": "ok", "module_count": len(modules), "modules": [m.model_dump() for m in modules]} diff --git a/web/app/(workspace)/learning/[bookId]/page.tsx b/web/app/(workspace)/learning/[bookId]/page.tsx index cb59174d6..cd132f0d1 100644 --- a/web/app/(workspace)/learning/[bookId]/page.tsx +++ b/web/app/(workspace)/learning/[bookId]/page.tsx @@ -141,7 +141,7 @@ export default function LearningBookPage() { return; } if (evt.type === "module_changed") { - const e = evt as Record; + const e = evt as unknown as Record; if (e.success !== false) { setCurrentModuleId(typeof e.module_id === "string" ? e.module_id : ""); } diff --git a/web/app/(workspace)/learning/page.tsx b/web/app/(workspace)/learning/page.tsx index f9ce9fcfb..41d268536 100644 --- a/web/app/(workspace)/learning/page.tsx +++ b/web/app/(workspace)/learning/page.tsx @@ -17,6 +17,7 @@ import { redoProgress, type ProgressSummary, } from "@/lib/learning-api"; +import CreateModuleDialog from "@/components/learning/CreateModuleDialog"; type Tab = "current" | "completed" | "all"; @@ -27,6 +28,7 @@ export default function LearningPage() { const [loading, setLoading] = useState(true); const [tab, setTab] = useState("all"); const [toast, setToast] = useState(""); + const [dialogOpen, setDialogOpen] = useState(false); const loadProgress = useCallback(async () => { try { @@ -85,7 +87,7 @@ export default function LearningPage() {

+ + + {/* Tabs */} +
+ {tabs.map((tb) => ( + + ))} +
+ + {/* Content */} +
+ {error && ( +
+ {error} +
+ )} + + {/* Manual Tab */} + {tab === "manual" && ( +
+
+ + setManualBookId(e.target.value)} + placeholder="manual" + className="w-full rounded-md border border-[var(--border)] bg-[var(--background)] px-3 py-1.5 text-sm text-[var(--foreground)] placeholder:text-[var(--muted-foreground)]/50 focus:border-[var(--primary)]/40 focus:outline-none" + /> +
+
+ + setModuleName(e.target.value)} + placeholder={t("guidedLearning.moduleNamePlaceholder")} + className="w-full rounded-md border border-[var(--border)] bg-[var(--background)] px-3 py-1.5 text-sm text-[var(--foreground)] placeholder:text-[var(--muted-foreground)]/50 focus:border-[var(--primary)]/40 focus:outline-none" + /> +
+
+ + {kpRows.map((row, i) => ( +
+ { + const next = [...kpRows]; + next[i] = { ...next[i], name: e.target.value }; + setKpRows(next); + }} + placeholder={t("guidedLearning.kpNamePlaceholder")} + className="flex-1 rounded-md border border-[var(--border)] bg-[var(--background)] px-3 py-1.5 text-sm text-[var(--foreground)] placeholder:text-[var(--muted-foreground)]/50 focus:border-[var(--primary)]/40 focus:outline-none" + /> + + {kpRows.length > 1 && ( + + )} +
+ ))} + +
+
+ )} + + {/* Book Tab */} + {tab === "book" && ( +
+ {loadingBooks ? ( +
+ +
+ ) : books.length === 0 ? ( +
+ {t("guidedLearning.noBooks")} +
+ ) : ( + <> +
+ {books.map((book) => ( + + ))} +
+ {selectedBookId && ( +
+ {loadingChapters ? ( +
+ + {t("guidedLearning.loadingChapters")} +
+ ) : bookChapters.length === 0 ? ( +
+ {t("guidedLearning.noChapters")} +
+ ) : ( +
+

+ {t("guidedLearning.chaptersToImport", { count: bookChapters.length })} +

+
+ {bookChapters.map((ch, i) => ( +
+ + {ch.title} + + ({(ch.learning_objectives ?? []).length} {t("guidedLearning.kps")}) + +
+ ))} +
+
+ )} +
+ )} + + )} +
+ )} + + {/* KB Tab */} + {tab === "kb" && ( +
+ {loadingKb ? ( +
+ +
+ ) : kbList.length === 0 ? ( +
+ {t("guidedLearning.noKb")} +
+ ) : ( +
+ {kbList.map((kb) => ( + + ))} +
+ )} +
+ )} + + {/* Notebook Tab */} + {tab === "notebook" && ( +
+ {loadingNotebooks ? ( +
+ +
+ ) : notebooks.length === 0 ? ( +
+ {t("guidedLearning.noNotebooks")} +
+ ) : ( + <> +
+ {notebooks.map((nb) => ( + + ))} +
+ {selectedNotebook && ( +
+ {loadingRecords ? ( +
+ + {t("guidedLearning.loadingRecords")} +
+ ) : notebookRecords.length === 0 ? ( +
+ {t("guidedLearning.noRecords")} +
+ ) : ( +
+

+ {t("guidedLearning.selectRecords")} ({selectedRecordIds.size} {t("guidedLearning.selected")}) +

+
+ {notebookRecords.slice(0, 20).map((rec) => ( + + ))} +
+ {notebookRecords.length > 20 && ( +

+ {t("guidedLearning.recordsLimited")} +

+ )} +
+ )} +
+ )} + + )} +
+ )} +
+ + {/* Footer */} +
+ + +
+ + + ); +} diff --git a/web/lib/learning-api.ts b/web/lib/learning-api.ts index 5e00ce510..04822cbae 100644 --- a/web/lib/learning-api.ts +++ b/web/lib/learning-api.ts @@ -78,3 +78,33 @@ export async function importFromBook(bookId: string, chapters: { title: string; if (!res.ok) throw new Error(`Failed to import from book: ${res.status}`); return res.json(); } + +export interface BookSummary { + id: string; + title: string; + description?: string; + status: string; + chapter_count: number; + page_count: number; +} + +export async function listBooks(): Promise { + const res = await apiFetch(apiUrl("/api/v1/books")); + if (!res.ok) throw new Error(`Failed to list books: ${res.status}`); + const data = await res.json(); + return data.books ?? []; +} + +export async function generateModulesFromNotebook( + bookId: string, + notebookId: string, + records: { id: string; type: string; title: string; output: string }[], +): Promise<{ modules: ModuleInit[] }> { + const res = await apiFetch(apiUrl(`/api/v1/learning/progress/${encodeURIComponent(bookId)}/generate-from-notebook`), { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ notebook_id: notebookId, records }), + }); + if (!res.ok) throw new Error(`Failed to generate modules from notebook: ${res.status}`); + return res.json(); +} diff --git a/web/locales/en/app.json b/web/locales/en/app.json index 91013ae5c..7d5172943 100644 --- a/web/locales/en/app.json +++ b/web/locales/en/app.json @@ -1651,6 +1651,43 @@ "guidedLearning.stage.completed": "Completed", "Start learning": "Start learning", "guidedLearning.alreadyHasProgress": "You already have learning progress for this book. Continuing...", + "guidedLearning.tabManual": "Manual", + "guidedLearning.tabBook": "From Book", + "guidedLearning.tabKb": "From KB", + "guidedLearning.tabNotebook": "From Notebook", + "guidedLearning.bookId": "Book ID", + "guidedLearning.moduleName": "Module Name", + "guidedLearning.moduleNamePlaceholder": "e.g. Introduction to Algebra", + "guidedLearning.kpNamePlaceholder": "Knowledge point name", + "guidedLearning.addKp": "Add knowledge point", + "guidedLearning.noBooks": "No books available", + "guidedLearning.chapters": "chapters", + "guidedLearning.loadingChapters": "Loading chapters...", + "guidedLearning.noChapters": "No chapters found in this book", + "guidedLearning.chaptersToImport": "{{count}} chapters to import", + "guidedLearning.kps": "KPs", + "guidedLearning.noKb": "No knowledge bases available", + "guidedLearning.noNotebooks": "No notebooks available", + "guidedLearning.records": "records", + "guidedLearning.loadingRecords": "Loading records...", + "guidedLearning.noRecords": "This notebook has no records", + "guidedLearning.selectRecords": "Select records to import", + "guidedLearning.selected": "selected", + "guidedLearning.recordsLimited": "Only the first 20 records are shown.", + "guidedLearning.cancel": "Cancel", + "guidedLearning.create": "Create", + "guidedLearning.generateModules": "Generate Modules", + "guidedLearning.moduleNameRequired": "Please enter a module name or at least one knowledge point.", + "guidedLearning.untitledModule": "Untitled Module", + "guidedLearning.createModuleFailed": "Failed to create module", + "guidedLearning.importBookFailed": "Failed to import from book", + "guidedLearning.importKbFailed": "Failed to import from knowledge base", + "guidedLearning.importNotebookFailed": "Failed to generate modules from notebook", + "guidedLearning.loadBooksFailed": "Failed to load books", + "guidedLearning.loadKbFailed": "Failed to load knowledge bases", + "guidedLearning.loadNotebooksFailed": "Failed to load notebooks", + "guidedLearning.loadChaptersFailed": "Failed to load chapters", + "guidedLearning.loadRecordsFailed": "Failed to load notebook records", "knowledgeType.memory": "Rote Memory", "knowledgeType.concept": "Conceptual", "knowledgeType.procedure": "Procedural", diff --git a/web/locales/zh/app.json b/web/locales/zh/app.json index 2f79e18f6..e28cbe082 100644 --- a/web/locales/zh/app.json +++ b/web/locales/zh/app.json @@ -1651,6 +1651,43 @@ "guidedLearning.stage.completed": "已完成", "Start learning": "开始学习", "guidedLearning.alreadyHasProgress": "该书已有学习进度,将直接继续学习。", + "guidedLearning.tabManual": "手动创建", + "guidedLearning.tabBook": "从书籍导入", + "guidedLearning.tabKb": "从知识库导入", + "guidedLearning.tabNotebook": "从笔记本导入", + "guidedLearning.bookId": "书籍 ID", + "guidedLearning.moduleName": "模块名称", + "guidedLearning.moduleNamePlaceholder": "如:线性代数入门", + "guidedLearning.kpNamePlaceholder": "知识点名称", + "guidedLearning.addKp": "添加知识点", + "guidedLearning.noBooks": "暂无可用书籍", + "guidedLearning.chapters": "章节", + "guidedLearning.loadingChapters": "加载章节中...", + "guidedLearning.noChapters": "该书未找到章节", + "guidedLearning.chaptersToImport": "将导入 {{count}} 个章节", + "guidedLearning.kps": "知识点", + "guidedLearning.noKb": "暂无可用知识库", + "guidedLearning.noNotebooks": "暂无可用笔记本", + "guidedLearning.records": "条记录", + "guidedLearning.loadingRecords": "加载记录中...", + "guidedLearning.noRecords": "该笔记本暂无记录", + "guidedLearning.selectRecords": "选择要导入的记录", + "guidedLearning.selected": "已选", + "guidedLearning.recordsLimited": "仅显示前 20 条记录。", + "guidedLearning.cancel": "取消", + "guidedLearning.create": "创建", + "guidedLearning.generateModules": "生成模块", + "guidedLearning.moduleNameRequired": "请输入模块名称或至少一个知识点。", + "guidedLearning.untitledModule": "未命名模块", + "guidedLearning.createModuleFailed": "创建模块失败", + "guidedLearning.importBookFailed": "从书籍导入失败", + "guidedLearning.importKbFailed": "从知识库导入失败", + "guidedLearning.importNotebookFailed": "从笔记本生成模块失败", + "guidedLearning.loadBooksFailed": "加载书籍失败", + "guidedLearning.loadKbFailed": "加载知识库失败", + "guidedLearning.loadNotebooksFailed": "加载笔记本失败", + "guidedLearning.loadChaptersFailed": "加载章节失败", + "guidedLearning.loadRecordsFailed": "加载笔记本记录失败", "knowledgeType.memory": "记忆型", "knowledgeType.concept": "概念型", "knowledgeType.procedure": "程序型",