Initial speaking practice site
This commit is contained in:
commit
bcebeaef82
38 files changed
+10698
No files matched your search
@@ -0,0 +1,7 @@
|
|||||||
|
backend/speaking_lab.sqlite
|
||||||
|
uploads/videos/
|
||||||
|
uploads/subtitles/
|
||||||
|
__pycache__/
|
||||||
|
*.pyc
|
||||||
|
*.lnk
|
||||||
|
ui-redesign-smoke.png
|
||||||
@@ -0,0 +1,99 @@
|
|||||||
|
# Speaking Lab
|
||||||
|
|
||||||
|
Local first-version prototype for English speaking practice.
|
||||||
|
|
||||||
|
## Install
|
||||||
|
|
||||||
|
Install the backend dependencies when running the FastAPI server locally:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
python -m pip install fastapi uvicorn python-multipart
|
||||||
|
```
|
||||||
|
|
||||||
|
`python-multipart` is required because `POST /api/videos` uses FastAPI `Form` and `File` uploads.
|
||||||
|
|
||||||
|
## Run
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
cd F:\ooo\speaking-practice-local
|
||||||
|
python -m uvicorn backend.main:app --reload --host 127.0.0.1 --port 8000
|
||||||
|
```
|
||||||
|
|
||||||
|
Open:
|
||||||
|
|
||||||
|
```text
|
||||||
|
http://127.0.0.1:8000
|
||||||
|
```
|
||||||
|
|
||||||
|
API docs:
|
||||||
|
|
||||||
|
```text
|
||||||
|
http://127.0.0.1:8000/docs
|
||||||
|
```
|
||||||
|
|
||||||
|
Admin page:
|
||||||
|
|
||||||
|
```text
|
||||||
|
http://127.0.0.1:8000/admin.html
|
||||||
|
```
|
||||||
|
|
||||||
|
## What works
|
||||||
|
|
||||||
|
- Local video library with tags and fuzzy keyword search.
|
||||||
|
- Basic login/register stored in browser localStorage.
|
||||||
|
- Admin mode when the email contains `admin`.
|
||||||
|
- Favorites and watch-later lists.
|
||||||
|
- Dedicated admin page for adding and deleting materials.
|
||||||
|
- Admin upload for local video files or video/HLS URLs.
|
||||||
|
- Admin upload for English and Chinese `.srt` / `.vtt` subtitles.
|
||||||
|
- Multilingual subtitle selectors.
|
||||||
|
- Bilingual subtitle display.
|
||||||
|
- Click transcript lines to jump the video to the matching timestamp.
|
||||||
|
- Current transcript line highlighting.
|
||||||
|
- Sentence replay, previous/next sentence, sentence loop.
|
||||||
|
- Browser microphone recording and local playback.
|
||||||
|
|
||||||
|
## Notes
|
||||||
|
|
||||||
|
- This first version is a local browser app, not a production server app.
|
||||||
|
- User login state, favorites, and watch-later lists are still stored in browser localStorage.
|
||||||
|
- Added content library videos and subtitles are persisted through the FastAPI backend.
|
||||||
|
- FastAPI initializes `backend/speaking_lab.sqlite` on startup.
|
||||||
|
|
||||||
|
## Content Library
|
||||||
|
|
||||||
|
The admin page saves videos and subtitles through the FastAPI backend.
|
||||||
|
|
||||||
|
Supported first-version flow:
|
||||||
|
|
||||||
|
- Log in with an email containing `admin`.
|
||||||
|
- Click the small `管理` button beside the `素材` heading, or open `/admin.html`.
|
||||||
|
- Add a title, speaker, description, and comma-separated tags.
|
||||||
|
- Choose either a local video file or a video/HLS URL.
|
||||||
|
- Optionally upload English and Chinese `.srt` / `.vtt` subtitle files.
|
||||||
|
- Delete materials from the admin page when you no longer want them.
|
||||||
|
- Refresh the browser and confirm the added video remains in the library.
|
||||||
|
|
||||||
|
Uploaded files are stored locally:
|
||||||
|
|
||||||
|
- Videos: `uploads/videos/`
|
||||||
|
- Subtitles: `uploads/subtitles/`
|
||||||
|
|
||||||
|
Metadata is stored in SQLite:
|
||||||
|
|
||||||
|
- `backend/speaking_lab.sqlite`
|
||||||
|
|
||||||
|
## Admin Page
|
||||||
|
|
||||||
|
Content management is handled on a separate local admin page:
|
||||||
|
|
||||||
|
```text
|
||||||
|
http://127.0.0.1:8000/admin.html
|
||||||
|
```
|
||||||
|
|
||||||
|
In this prototype, an admin is any local user whose email contains `admin`.
|
||||||
|
After logging in as an admin on the study page, a small `管理` button appears
|
||||||
|
beside the `素材` heading. The admin page supports adding and deleting
|
||||||
|
materials. Editing and subtitle replacement are planned for later.
|
||||||
|
|
||||||
|
This phase does not include web editing, real authentication, learning progress sync, or server deployment.
|
||||||
+67
@@ -0,0 +1,67 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="zh-CN">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<title>Speaking Lab 后台管理</title>
|
||||||
|
<link rel="stylesheet" href="./styles.css">
|
||||||
|
</head>
|
||||||
|
<body class="admin-page">
|
||||||
|
<header class="topbar admin-topbar">
|
||||||
|
<div class="brand">
|
||||||
|
<div>
|
||||||
|
<h1>后台管理</h1>
|
||||||
|
<p id="adminIdentity">请先使用管理员账号登录。</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<a class="secondary-action" href="./index.html">返回学习页</a>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<main id="adminLocked" class="admin-locked empty-state" hidden>
|
||||||
|
<h2>需要管理员账号</h2>
|
||||||
|
<p>请返回学习页,使用管理员账号登录后再进入后台。</p>
|
||||||
|
<a class="primary-link" href="./index.html">返回登录</a>
|
||||||
|
</main>
|
||||||
|
|
||||||
|
<main id="adminContent" class="admin-shell" hidden>
|
||||||
|
<section class="admin-panel">
|
||||||
|
<div class="admin-form-heading">
|
||||||
|
<h2 id="adminFormTitle">添加素材</h2>
|
||||||
|
<button id="cancelEditBtn" class="secondary-action" type="button" hidden>取消编辑</button>
|
||||||
|
</div>
|
||||||
|
<form id="adminCreateForm" class="admin-form">
|
||||||
|
<input id="adminTitle" type="text" placeholder="视频标题" required>
|
||||||
|
<input id="adminSpeaker" type="text" placeholder="演讲者 / 片段来源">
|
||||||
|
<textarea id="adminDescription" placeholder="简介"></textarea>
|
||||||
|
<input id="adminTags" type="text" placeholder="标签,用逗号分隔,如 科技,设计">
|
||||||
|
<label class="file-input" data-default-label="选择视频文件">
|
||||||
|
<span>选择视频文件</span>
|
||||||
|
<input id="adminVideoFile" type="file" accept="video/*">
|
||||||
|
</label>
|
||||||
|
<input id="adminVideoUrl" type="url" placeholder="或填写视频 / HLS 地址">
|
||||||
|
<label class="file-input" data-default-label="英文字幕 .srt/.vtt">
|
||||||
|
<span>英文字幕 .srt/.vtt</span>
|
||||||
|
<input id="adminSubtitleEn" type="file" accept=".srt,.vtt,text/vtt,text/plain">
|
||||||
|
</label>
|
||||||
|
<label class="file-input" data-default-label="中文字幕 .srt/.vtt">
|
||||||
|
<span>中文字幕 .srt/.vtt</span>
|
||||||
|
<input id="adminSubtitleZh" type="file" accept=".srt,.vtt,text/vtt,text/plain">
|
||||||
|
</label>
|
||||||
|
<div id="adminSubtitleEditor" class="admin-subtitle-editor" hidden></div>
|
||||||
|
<button id="adminSubmitBtn" type="submit">添加到视频库</button>
|
||||||
|
</form>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="admin-panel">
|
||||||
|
<div class="admin-list-heading">
|
||||||
|
<h2>素材列表</h2>
|
||||||
|
<button id="refreshVideosBtn" class="secondary-action" type="button">刷新</button>
|
||||||
|
</div>
|
||||||
|
<div id="adminMessage" class="admin-message" hidden></div>
|
||||||
|
<div id="adminVideoList" class="admin-video-list"></div>
|
||||||
|
</section>
|
||||||
|
</main>
|
||||||
|
|
||||||
|
<script src="./admin.js"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,491 @@
|
|||||||
|
const STORAGE_KEY = "speaking-lab-state-v1";
|
||||||
|
const IS_BROWSER = typeof document !== "undefined";
|
||||||
|
|
||||||
|
const els = {
|
||||||
|
identity: IS_BROWSER ? document.querySelector("#adminIdentity") : null,
|
||||||
|
locked: IS_BROWSER ? document.querySelector("#adminLocked") : null,
|
||||||
|
content: IS_BROWSER ? document.querySelector("#adminContent") : null,
|
||||||
|
formTitle: IS_BROWSER ? document.querySelector("#adminFormTitle") : null,
|
||||||
|
form: IS_BROWSER ? document.querySelector("#adminCreateForm") : null,
|
||||||
|
submitBtn: IS_BROWSER ? document.querySelector("#adminSubmitBtn") : null,
|
||||||
|
cancelEditBtn: IS_BROWSER ? document.querySelector("#cancelEditBtn") : null,
|
||||||
|
title: IS_BROWSER ? document.querySelector("#adminTitle") : null,
|
||||||
|
speaker: IS_BROWSER ? document.querySelector("#adminSpeaker") : null,
|
||||||
|
description: IS_BROWSER ? document.querySelector("#adminDescription") : null,
|
||||||
|
tags: IS_BROWSER ? document.querySelector("#adminTags") : null,
|
||||||
|
videoFile: IS_BROWSER ? document.querySelector("#adminVideoFile") : null,
|
||||||
|
videoUrl: IS_BROWSER ? document.querySelector("#adminVideoUrl") : null,
|
||||||
|
subtitleEn: IS_BROWSER ? document.querySelector("#adminSubtitleEn") : null,
|
||||||
|
subtitleZh: IS_BROWSER ? document.querySelector("#adminSubtitleZh") : null,
|
||||||
|
subtitleEditor: IS_BROWSER ? document.querySelector("#adminSubtitleEditor") : null,
|
||||||
|
refreshBtn: IS_BROWSER ? document.querySelector("#refreshVideosBtn") : null,
|
||||||
|
message: IS_BROWSER ? document.querySelector("#adminMessage") : null,
|
||||||
|
videoList: IS_BROWSER ? document.querySelector("#adminVideoList") : null,
|
||||||
|
};
|
||||||
|
|
||||||
|
let videos = [];
|
||||||
|
let editingVideo = null;
|
||||||
|
let editableSubtitles = createEmptySubtitleEditState();
|
||||||
|
|
||||||
|
if (IS_BROWSER) initializeAdmin();
|
||||||
|
|
||||||
|
function loadState() {
|
||||||
|
try {
|
||||||
|
const saved = JSON.parse(localStorage.getItem(STORAGE_KEY) || "{}");
|
||||||
|
return {
|
||||||
|
users: Array.isArray(saved.users) ? saved.users : [],
|
||||||
|
currentUserId: saved.currentUserId || null,
|
||||||
|
};
|
||||||
|
} catch {
|
||||||
|
return { users: [], currentUserId: null };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function getCurrentUser() {
|
||||||
|
const state = loadState();
|
||||||
|
return state.users.find((user) => user.id === state.currentUserId) || null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function isAdmin(user) {
|
||||||
|
const email = String(user?.email || "").toLowerCase();
|
||||||
|
return user?.role === "admin" || email.includes("admin");
|
||||||
|
}
|
||||||
|
|
||||||
|
async function apiRequest(path, options = {}) {
|
||||||
|
const response = await fetch(path, options);
|
||||||
|
if (!response.ok) {
|
||||||
|
let message = "请求失败,请重试。";
|
||||||
|
try {
|
||||||
|
const payload = await response.json();
|
||||||
|
message = payload.detail || message;
|
||||||
|
} catch {
|
||||||
|
message = response.statusText || message;
|
||||||
|
}
|
||||||
|
throw new Error(message);
|
||||||
|
}
|
||||||
|
return response.json();
|
||||||
|
}
|
||||||
|
|
||||||
|
function initializeAdmin() {
|
||||||
|
const user = getCurrentUser();
|
||||||
|
if (!isAdmin(user)) {
|
||||||
|
els.identity.textContent = "未登录管理员账号";
|
||||||
|
els.locked.hidden = false;
|
||||||
|
els.content.hidden = true;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
els.identity.textContent = `${user.email} · 管理员`;
|
||||||
|
els.locked.hidden = true;
|
||||||
|
els.content.hidden = false;
|
||||||
|
|
||||||
|
els.form.addEventListener("submit", addVideo);
|
||||||
|
els.refreshBtn.addEventListener("click", loadVideos);
|
||||||
|
els.cancelEditBtn.addEventListener("click", resetFormMode);
|
||||||
|
bindFileInputs();
|
||||||
|
loadVideos();
|
||||||
|
}
|
||||||
|
|
||||||
|
function getFileInputState(file, defaultLabel) {
|
||||||
|
if (!file) {
|
||||||
|
return {
|
||||||
|
text: defaultLabel,
|
||||||
|
title: defaultLabel,
|
||||||
|
isSelected: false,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
text: `已选:${file.name}`,
|
||||||
|
title: file.name,
|
||||||
|
isSelected: true,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function bindFileInputs() {
|
||||||
|
[els.videoFile, els.subtitleEn, els.subtitleZh].forEach((input) => {
|
||||||
|
const label = input?.closest(".file-input");
|
||||||
|
if (!label) return;
|
||||||
|
|
||||||
|
label.dataset.defaultLabel ||= label.textContent.trim();
|
||||||
|
input.addEventListener("change", () => updateFileInputLabel(input));
|
||||||
|
updateFileInputLabel(input);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function updateFileInputLabel(input) {
|
||||||
|
const label = input.closest(".file-input");
|
||||||
|
const textNode = label?.querySelector("span");
|
||||||
|
if (!label || !textNode) return;
|
||||||
|
|
||||||
|
const state = getFileInputState(input.files?.[0] || null, label.dataset.defaultLabel || textNode.textContent);
|
||||||
|
textNode.textContent = state.text;
|
||||||
|
label.title = state.title;
|
||||||
|
label.classList.toggle("is-selected", state.isSelected);
|
||||||
|
}
|
||||||
|
|
||||||
|
function resetFileInputs() {
|
||||||
|
[els.videoFile, els.subtitleEn, els.subtitleZh].forEach((input) => {
|
||||||
|
if (input) updateFileInputLabel(input);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function showMessage(text, isError = false) {
|
||||||
|
els.message.hidden = false;
|
||||||
|
els.message.textContent = text;
|
||||||
|
els.message.classList.toggle("error", isError);
|
||||||
|
}
|
||||||
|
|
||||||
|
function clearMessage() {
|
||||||
|
els.message.hidden = true;
|
||||||
|
els.message.textContent = "";
|
||||||
|
els.message.classList.remove("error");
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadVideos() {
|
||||||
|
clearMessage();
|
||||||
|
els.videoList.innerHTML = `<div class="empty-state">正在加载素材...</div>`;
|
||||||
|
try {
|
||||||
|
videos = await apiRequest("/api/videos");
|
||||||
|
renderVideos();
|
||||||
|
} catch (error) {
|
||||||
|
els.videoList.innerHTML = "";
|
||||||
|
showMessage(error.message || "素材加载失败。", true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderVideos() {
|
||||||
|
els.videoList.innerHTML = "";
|
||||||
|
if (!videos.length) {
|
||||||
|
els.videoList.innerHTML = `<div class="empty-state">还没有素材。</div>`;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const fragment = document.createDocumentFragment();
|
||||||
|
videos.forEach((video) => {
|
||||||
|
const item = document.createElement("article");
|
||||||
|
const title = document.createElement("h3");
|
||||||
|
const meta = document.createElement("p");
|
||||||
|
const subtitles = document.createElement("p");
|
||||||
|
const details = document.createElement("div");
|
||||||
|
const actions = document.createElement("div");
|
||||||
|
const editButton = document.createElement("button");
|
||||||
|
const deleteButton = document.createElement("button");
|
||||||
|
|
||||||
|
item.className = "admin-video-item";
|
||||||
|
if (String(editingVideo?.id) === String(video.id)) item.classList.add("is-editing");
|
||||||
|
meta.className = "admin-video-meta";
|
||||||
|
subtitles.className = "admin-video-subtitles";
|
||||||
|
actions.className = "admin-video-actions";
|
||||||
|
editButton.className = "secondary-action";
|
||||||
|
editButton.type = "button";
|
||||||
|
deleteButton.className = "danger-action";
|
||||||
|
deleteButton.type = "button";
|
||||||
|
|
||||||
|
title.textContent = video.title || "Untitled";
|
||||||
|
meta.textContent = [
|
||||||
|
video.speaker || "Unknown",
|
||||||
|
formatTags(video.tags),
|
||||||
|
getSourceLabel(video),
|
||||||
|
].join(" · ");
|
||||||
|
subtitles.textContent = getSubtitleLabel(video);
|
||||||
|
editButton.textContent = "编辑";
|
||||||
|
editButton.addEventListener("click", () => startEditingVideo(video));
|
||||||
|
deleteButton.textContent = "删除";
|
||||||
|
deleteButton.addEventListener("click", () => deleteVideo(video));
|
||||||
|
|
||||||
|
details.append(title, meta, subtitles);
|
||||||
|
actions.append(editButton, deleteButton);
|
||||||
|
item.append(details, actions);
|
||||||
|
fragment.appendChild(item);
|
||||||
|
});
|
||||||
|
els.videoList.appendChild(fragment);
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatTags(tags) {
|
||||||
|
return Array.isArray(tags) && tags.length ? tags.join(" / ") : "未分类";
|
||||||
|
}
|
||||||
|
|
||||||
|
function getSourceLabel(video) {
|
||||||
|
if (video.sourceType === "url") return "链接";
|
||||||
|
if (video.sourceType === "local-file") return "本地文件";
|
||||||
|
return video.videoUrl ? "视频源" : "未设置视频源";
|
||||||
|
}
|
||||||
|
|
||||||
|
function getSubtitleLabel(video) {
|
||||||
|
const subtitleCodes = Object.keys(video.subtitles || {});
|
||||||
|
return subtitleCodes.length ? `字幕:${subtitleCodes.join(" / ")}` : "字幕:无";
|
||||||
|
}
|
||||||
|
|
||||||
|
function startEditingVideo(video) {
|
||||||
|
editingVideo = video;
|
||||||
|
editableSubtitles = createSubtitleEditState(video);
|
||||||
|
els.formTitle.textContent = "编辑素材";
|
||||||
|
els.submitBtn.textContent = "保存修改";
|
||||||
|
els.cancelEditBtn.hidden = false;
|
||||||
|
els.title.value = video.title || "";
|
||||||
|
els.speaker.value = video.speaker === "Unknown" ? "" : video.speaker || "";
|
||||||
|
els.description.value = video.description || "";
|
||||||
|
els.tags.value = formatTags(video.tags) === "未分类" ? "" : formatTags(video.tags).replaceAll(" / ", ",");
|
||||||
|
els.videoUrl.value = video.sourceType === "url" ? video.videoUrl || "" : "";
|
||||||
|
els.form.dataset.mode = "edit";
|
||||||
|
resetFileInputs();
|
||||||
|
renderSubtitleEditor();
|
||||||
|
renderVideos();
|
||||||
|
}
|
||||||
|
|
||||||
|
function resetFormMode() {
|
||||||
|
editingVideo = null;
|
||||||
|
editableSubtitles = createEmptySubtitleEditState();
|
||||||
|
els.formTitle.textContent = "添加素材";
|
||||||
|
els.submitBtn.textContent = "添加到视频库";
|
||||||
|
els.cancelEditBtn.hidden = true;
|
||||||
|
els.form.dataset.mode = "add";
|
||||||
|
els.form.reset();
|
||||||
|
resetFileInputs();
|
||||||
|
renderSubtitleEditor();
|
||||||
|
renderVideos();
|
||||||
|
}
|
||||||
|
|
||||||
|
async function addVideo(event) {
|
||||||
|
event.preventDefault();
|
||||||
|
clearMessage();
|
||||||
|
|
||||||
|
const title = els.title.value.trim();
|
||||||
|
if (!title) {
|
||||||
|
showMessage("标题不能为空。", true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const submitButton = els.form.querySelector('button[type="submit"]');
|
||||||
|
const previousText = submitButton.textContent;
|
||||||
|
let requestSucceeded = false;
|
||||||
|
submitButton.disabled = true;
|
||||||
|
submitButton.textContent = editingVideo ? "正在保存..." : "正在添加...";
|
||||||
|
|
||||||
|
const formData = new FormData();
|
||||||
|
formData.append("title", title);
|
||||||
|
formData.append("speaker", els.speaker.value.trim());
|
||||||
|
formData.append("description", els.description.value.trim());
|
||||||
|
formData.append("tags", els.tags.value.trim());
|
||||||
|
formData.append("video_url", els.videoUrl.value.trim());
|
||||||
|
|
||||||
|
if (els.videoFile.files?.[0]) formData.append("video_file", els.videoFile.files[0]);
|
||||||
|
if (els.subtitleEn.files?.[0]) formData.append("subtitle_en", els.subtitleEn.files[0]);
|
||||||
|
if (els.subtitleZh.files?.[0]) formData.append("subtitle_zh", els.subtitleZh.files[0]);
|
||||||
|
if (editingVideo) appendEditedSubtitleContent(formData);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const path = editingVideo ? `/api/videos/${editingVideo.id}` : "/api/videos";
|
||||||
|
const method = editingVideo ? "PATCH" : "POST";
|
||||||
|
await apiRequest(path, {
|
||||||
|
method,
|
||||||
|
body: formData,
|
||||||
|
});
|
||||||
|
const successMessage = editingVideo ? "素材已更新。" : "素材已添加。";
|
||||||
|
requestSucceeded = true;
|
||||||
|
resetFormMode();
|
||||||
|
await loadVideos();
|
||||||
|
showMessage(successMessage);
|
||||||
|
} catch (error) {
|
||||||
|
showMessage(error.message || (editingVideo ? "更新素材失败。" : "添加素材失败。"), true);
|
||||||
|
} finally {
|
||||||
|
submitButton.disabled = false;
|
||||||
|
if (!requestSucceeded) submitButton.textContent = previousText;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (typeof module !== "undefined" && module.exports) {
|
||||||
|
module.exports = { getFileInputState, parseSubtitleBlocks, buildWebVtt };
|
||||||
|
}
|
||||||
|
|
||||||
|
function createEmptySubtitleEditState() {
|
||||||
|
return { en: null, zh: null };
|
||||||
|
}
|
||||||
|
|
||||||
|
function createSubtitleEditState(video) {
|
||||||
|
return {
|
||||||
|
en: createSubtitleTrackState(video, "en"),
|
||||||
|
zh: createSubtitleTrackState(video, "zh"),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function createSubtitleTrackState(video, languageCode) {
|
||||||
|
const subtitle = video.subtitles?.[languageCode];
|
||||||
|
if (!subtitle?.content) return null;
|
||||||
|
return {
|
||||||
|
languageCode,
|
||||||
|
languageName: languageCode === "zh" ? "中文字幕" : "英文字幕",
|
||||||
|
originalContent: subtitle.content,
|
||||||
|
cues: parseSubtitleBlocks(subtitle.content),
|
||||||
|
dirty: false,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseSubtitleBlocks(content) {
|
||||||
|
const normalized = String(content || "")
|
||||||
|
.replace(/^\uFEFF/, "")
|
||||||
|
.replace(/\r/g, "");
|
||||||
|
const cues = [];
|
||||||
|
let currentCue = null;
|
||||||
|
let pendingIdentifier = "";
|
||||||
|
|
||||||
|
normalized.split("\n").forEach((line) => {
|
||||||
|
const row = line.trim();
|
||||||
|
if (!row) {
|
||||||
|
addSubtitleEditCue(cues, currentCue);
|
||||||
|
currentCue = null;
|
||||||
|
pendingIdentifier = "";
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (/^WEBVTT\b/i.test(row)) return;
|
||||||
|
|
||||||
|
if (isSubtitleTimeRow(row)) {
|
||||||
|
addSubtitleEditCue(cues, currentCue);
|
||||||
|
currentCue = { identifier: pendingIdentifier, timeRange: row, textRows: [] };
|
||||||
|
pendingIdentifier = "";
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (currentCue) {
|
||||||
|
currentCue.textRows.push(row);
|
||||||
|
} else {
|
||||||
|
pendingIdentifier = pendingIdentifier ? `${pendingIdentifier} ${row}` : row;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
addSubtitleEditCue(cues, currentCue);
|
||||||
|
return cues;
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseSubtitleEditBlock(block, fallbackIndex) {
|
||||||
|
const rows = block.split("\n").map((row) => row.trim()).filter(Boolean);
|
||||||
|
const timeRowIndex = rows.findIndex((row) => row.includes("-->"));
|
||||||
|
if (timeRowIndex < 0) return null;
|
||||||
|
const identifier = timeRowIndex > 0 ? rows.slice(0, timeRowIndex).join(" ") : "";
|
||||||
|
const timeRange = rows[timeRowIndex];
|
||||||
|
const textRows = rows.slice(timeRowIndex + 1);
|
||||||
|
return createSubtitleEditCue(identifier, timeRange, textRows, fallbackIndex);
|
||||||
|
}
|
||||||
|
|
||||||
|
function isSubtitleTimeRow(row) {
|
||||||
|
return /\d{1,2}:\d{2}(?::\d{2})?[\.,]\d{3}\s*-->\s*\d{1,2}:\d{2}(?::\d{2})?[\.,]\d{3}/.test(row);
|
||||||
|
}
|
||||||
|
|
||||||
|
function addSubtitleEditCue(cues, cue) {
|
||||||
|
const parsed = cue ? createSubtitleEditCue(cue.identifier, cue.timeRange, cue.textRows, cues.length) : null;
|
||||||
|
if (parsed) cues.push(parsed);
|
||||||
|
}
|
||||||
|
|
||||||
|
function createSubtitleEditCue(identifier, timeRange, textRows, fallbackIndex) {
|
||||||
|
if (!hasSubtitleText(textRows)) return null;
|
||||||
|
return {
|
||||||
|
id: `${timeRange}-${identifier || fallbackIndex || textRows.join(" ").slice(0, 20)}`,
|
||||||
|
identifier,
|
||||||
|
timeRange,
|
||||||
|
text: textRows.join("\n"),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function hasSubtitleText(textRows) {
|
||||||
|
return textRows
|
||||||
|
.join("")
|
||||||
|
.replace(/ /gi, "")
|
||||||
|
.replace(/\u00a0/g, "")
|
||||||
|
.trim().length > 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderSubtitleEditor() {
|
||||||
|
if (!els.subtitleEditor) return;
|
||||||
|
els.subtitleEditor.innerHTML = "";
|
||||||
|
els.subtitleEditor.hidden = !editingVideo;
|
||||||
|
if (!editingVideo) return;
|
||||||
|
|
||||||
|
const tracks = [editableSubtitles.en, editableSubtitles.zh].filter(Boolean);
|
||||||
|
if (!tracks.length) {
|
||||||
|
els.subtitleEditor.innerHTML = `<div class="empty-state">当前素材没有可删除的字幕。</div>`;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
tracks.forEach((track) => {
|
||||||
|
const section = document.createElement("section");
|
||||||
|
section.className = "admin-subtitle-section";
|
||||||
|
section.innerHTML = `
|
||||||
|
<div class="admin-subtitle-heading">
|
||||||
|
<h3></h3>
|
||||||
|
<span></span>
|
||||||
|
</div>
|
||||||
|
<div class="admin-subtitle-cues"></div>
|
||||||
|
`;
|
||||||
|
section.querySelector("h3").textContent = track.languageName;
|
||||||
|
section.querySelector("span").textContent = `${track.cues.length} 条`;
|
||||||
|
const list = section.querySelector(".admin-subtitle-cues");
|
||||||
|
|
||||||
|
if (!track.cues.length) {
|
||||||
|
list.innerHTML = `<div class="empty-state">这个字幕轨道已删空。</div>`;
|
||||||
|
} else {
|
||||||
|
track.cues.forEach((cue, index) => {
|
||||||
|
const item = document.createElement("article");
|
||||||
|
item.className = "admin-subtitle-cue";
|
||||||
|
item.innerHTML = `
|
||||||
|
<div>
|
||||||
|
<strong></strong>
|
||||||
|
<p></p>
|
||||||
|
</div>
|
||||||
|
<button class="danger-action" type="button">删除</button>
|
||||||
|
`;
|
||||||
|
item.querySelector("strong").textContent = cue.timeRange;
|
||||||
|
item.querySelector("p").textContent = cue.text.replace(/\n+/g, " ");
|
||||||
|
item.querySelector("button").addEventListener("click", () => {
|
||||||
|
track.cues.splice(index, 1);
|
||||||
|
track.dirty = true;
|
||||||
|
renderSubtitleEditor();
|
||||||
|
});
|
||||||
|
list.appendChild(item);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
els.subtitleEditor.appendChild(section);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function appendEditedSubtitleContent(formData) {
|
||||||
|
if (editableSubtitles.en?.dirty && !els.subtitleEn.files?.[0]) {
|
||||||
|
formData.append("subtitle_en_content", buildWebVtt(editableSubtitles.en.cues));
|
||||||
|
}
|
||||||
|
if (editableSubtitles.zh?.dirty && !els.subtitleZh.files?.[0]) {
|
||||||
|
formData.append("subtitle_zh_content", buildWebVtt(editableSubtitles.zh.cues));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildWebVtt(cues) {
|
||||||
|
const blocks = cues.map((cue, index) => [
|
||||||
|
String(index + 1),
|
||||||
|
cue.timeRange,
|
||||||
|
cue.text,
|
||||||
|
].join("\n"));
|
||||||
|
return ["WEBVTT", ...blocks].join("\n\n").trim() + "\n";
|
||||||
|
}
|
||||||
|
|
||||||
|
async function deleteVideo(video) {
|
||||||
|
const confirmed = window.confirm("确定删除这个素材吗?此操作不可恢复。");
|
||||||
|
if (!confirmed) return;
|
||||||
|
|
||||||
|
clearMessage();
|
||||||
|
try {
|
||||||
|
const result = await apiRequest(`/api/videos/${video.id}`, {
|
||||||
|
method: "DELETE",
|
||||||
|
});
|
||||||
|
videos = videos.filter((item) => String(item.id) !== String(video.id));
|
||||||
|
renderVideos();
|
||||||
|
|
||||||
|
if (Array.isArray(result.warnings) && result.warnings.length) {
|
||||||
|
showMessage(`素材已删除,但有文件未能删除:${result.warnings.join(";")}`, true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
showMessage("素材已删除。");
|
||||||
|
} catch (error) {
|
||||||
|
showMessage(error.message || "删除素材失败。", true);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
|
||||||
+396
@@ -0,0 +1,396 @@
|
|||||||
|
from pathlib import Path
|
||||||
|
import json
|
||||||
|
import sqlite3
|
||||||
|
|
||||||
|
|
||||||
|
BASE_DIR = Path(__file__).resolve().parent
|
||||||
|
DATABASE_PATH = BASE_DIR / "speaking_lab.sqlite"
|
||||||
|
MOJIBAKE_MARKERS = ("Ã", "Â", "â", "ä", "å", "æ", "ç", "è", "é")
|
||||||
|
|
||||||
|
|
||||||
|
def get_connection() -> sqlite3.Connection:
|
||||||
|
connection = sqlite3.connect(DATABASE_PATH)
|
||||||
|
connection.row_factory = sqlite3.Row
|
||||||
|
connection.execute("PRAGMA foreign_keys = ON")
|
||||||
|
return connection
|
||||||
|
|
||||||
|
|
||||||
|
def initialize_database() -> None:
|
||||||
|
BASE_DIR.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
|
with get_connection() as connection:
|
||||||
|
connection.executescript(
|
||||||
|
"""
|
||||||
|
CREATE TABLE IF NOT EXISTS users (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
email TEXT NOT NULL UNIQUE,
|
||||||
|
password_hash TEXT NOT NULL,
|
||||||
|
display_name TEXT,
|
||||||
|
role TEXT NOT NULL DEFAULT 'user',
|
||||||
|
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS videos (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
title TEXT NOT NULL,
|
||||||
|
speaker TEXT,
|
||||||
|
description TEXT,
|
||||||
|
tags TEXT,
|
||||||
|
video_url TEXT,
|
||||||
|
duration_seconds INTEGER,
|
||||||
|
status TEXT NOT NULL DEFAULT 'draft',
|
||||||
|
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS subtitles (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
video_id INTEGER NOT NULL,
|
||||||
|
language_code TEXT NOT NULL,
|
||||||
|
language_name TEXT,
|
||||||
|
format TEXT NOT NULL,
|
||||||
|
file_path TEXT,
|
||||||
|
content TEXT,
|
||||||
|
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
FOREIGN KEY (video_id) REFERENCES videos (id) ON DELETE CASCADE
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS user_interactions (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
user_id INTEGER NOT NULL,
|
||||||
|
video_id INTEGER NOT NULL,
|
||||||
|
interaction_type TEXT NOT NULL,
|
||||||
|
current_time_ms INTEGER,
|
||||||
|
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
UNIQUE (user_id, video_id, interaction_type),
|
||||||
|
FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE,
|
||||||
|
FOREIGN KEY (video_id) REFERENCES videos (id) ON DELETE CASCADE
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_videos_title ON videos (title);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_subtitles_video_id ON subtitles (video_id);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_user_interactions_user_id
|
||||||
|
ON user_interactions (user_id);
|
||||||
|
"""
|
||||||
|
)
|
||||||
|
connection.execute(
|
||||||
|
"""
|
||||||
|
DELETE FROM subtitles
|
||||||
|
WHERE id NOT IN (
|
||||||
|
SELECT MAX(id)
|
||||||
|
FROM subtitles
|
||||||
|
GROUP BY video_id, language_code
|
||||||
|
)
|
||||||
|
"""
|
||||||
|
)
|
||||||
|
connection.execute(
|
||||||
|
"""
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS idx_subtitles_video_language
|
||||||
|
ON subtitles (video_id, language_code)
|
||||||
|
"""
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def repair_mojibake_text(value: str | None) -> str:
|
||||||
|
if not value:
|
||||||
|
return ""
|
||||||
|
|
||||||
|
repaired = value
|
||||||
|
for _ in range(2):
|
||||||
|
if not any(marker in repaired for marker in MOJIBAKE_MARKERS):
|
||||||
|
break
|
||||||
|
try:
|
||||||
|
candidate = repaired.encode("latin1").decode("utf-8")
|
||||||
|
except UnicodeError:
|
||||||
|
break
|
||||||
|
if candidate == repaired:
|
||||||
|
break
|
||||||
|
repaired = candidate
|
||||||
|
return repaired
|
||||||
|
|
||||||
|
|
||||||
|
def parse_tags(tags_text: str | None) -> list[str]:
|
||||||
|
tags = [
|
||||||
|
tag.strip()
|
||||||
|
for tag in repair_mojibake_text(tags_text).replace(",", ",").split(",")
|
||||||
|
if tag.strip()
|
||||||
|
]
|
||||||
|
return tags or ["未分类"]
|
||||||
|
|
||||||
|
|
||||||
|
def row_to_video(row: sqlite3.Row, subtitle_rows: list[sqlite3.Row]) -> dict[str, object]:
|
||||||
|
subtitles: dict[str, dict[str, str]] = {}
|
||||||
|
for subtitle in subtitle_rows:
|
||||||
|
subtitles[subtitle["language_code"]] = {
|
||||||
|
"languageName": repair_mojibake_text(subtitle["language_name"] or subtitle["language_code"]),
|
||||||
|
"format": subtitle["format"],
|
||||||
|
"filePath": subtitle["file_path"],
|
||||||
|
"content": repair_mojibake_text(subtitle["content"] or ""),
|
||||||
|
}
|
||||||
|
|
||||||
|
try:
|
||||||
|
tags = json.loads(row["tags"] or "[]")
|
||||||
|
except json.JSONDecodeError:
|
||||||
|
tags = parse_tags(row["tags"])
|
||||||
|
tags = [repair_mojibake_text(str(tag)) for tag in tags] if isinstance(tags, list) else parse_tags(str(tags))
|
||||||
|
|
||||||
|
return {
|
||||||
|
"id": row["id"],
|
||||||
|
"title": repair_mojibake_text(row["title"]),
|
||||||
|
"speaker": repair_mojibake_text(row["speaker"] or "Unknown"),
|
||||||
|
"description": repair_mojibake_text(row["description"] or ""),
|
||||||
|
"tags": tags if isinstance(tags, list) and tags else ["未分类"],
|
||||||
|
"duration": row["duration_seconds"] or 0,
|
||||||
|
"videoUrl": row["video_url"] or "",
|
||||||
|
"sourceType": "url" if str(row["video_url"] or "").startswith(("http://", "https://")) else "local-file",
|
||||||
|
"subtitles": subtitles,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def create_video(
|
||||||
|
*,
|
||||||
|
title: str,
|
||||||
|
speaker: str | None,
|
||||||
|
description: str | None,
|
||||||
|
tags: list[str],
|
||||||
|
video_url: str,
|
||||||
|
subtitles: list[dict[str, str]],
|
||||||
|
) -> dict[str, object]:
|
||||||
|
with get_connection() as connection:
|
||||||
|
cursor = connection.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO videos (
|
||||||
|
title, speaker, description, tags, video_url, status
|
||||||
|
)
|
||||||
|
VALUES (?, ?, ?, ?, ?, 'published')
|
||||||
|
""",
|
||||||
|
(
|
||||||
|
title,
|
||||||
|
repair_mojibake_text(speaker or "Unknown"),
|
||||||
|
repair_mojibake_text(description or ""),
|
||||||
|
json.dumps([repair_mojibake_text(tag) for tag in tags], ensure_ascii=False),
|
||||||
|
repair_mojibake_text(video_url),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
video_id = int(cursor.lastrowid)
|
||||||
|
|
||||||
|
for subtitle in subtitles:
|
||||||
|
connection.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO subtitles (
|
||||||
|
video_id, language_code, language_name, format, file_path, content
|
||||||
|
)
|
||||||
|
VALUES (?, ?, ?, ?, ?, ?)
|
||||||
|
""",
|
||||||
|
(
|
||||||
|
video_id,
|
||||||
|
subtitle["language_code"],
|
||||||
|
repair_mojibake_text(subtitle["language_name"]),
|
||||||
|
subtitle["format"],
|
||||||
|
subtitle["file_path"],
|
||||||
|
repair_mojibake_text(subtitle["content"]),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
video = get_video(video_id)
|
||||||
|
if video is None:
|
||||||
|
raise RuntimeError("Created video could not be loaded")
|
||||||
|
return video
|
||||||
|
|
||||||
|
|
||||||
|
def list_videos() -> list[dict[str, object]]:
|
||||||
|
with get_connection() as connection:
|
||||||
|
video_rows = connection.execute(
|
||||||
|
"""
|
||||||
|
SELECT *
|
||||||
|
FROM videos
|
||||||
|
WHERE status = 'published'
|
||||||
|
ORDER BY created_at DESC, id DESC
|
||||||
|
"""
|
||||||
|
).fetchall()
|
||||||
|
subtitle_rows = connection.execute(
|
||||||
|
"""
|
||||||
|
SELECT *
|
||||||
|
FROM subtitles
|
||||||
|
ORDER BY id ASC
|
||||||
|
"""
|
||||||
|
).fetchall()
|
||||||
|
|
||||||
|
subtitles_by_video: dict[int, list[sqlite3.Row]] = {}
|
||||||
|
for subtitle in subtitle_rows:
|
||||||
|
subtitles_by_video.setdefault(int(subtitle["video_id"]), []).append(subtitle)
|
||||||
|
|
||||||
|
return [
|
||||||
|
row_to_video(row, subtitles_by_video.get(int(row["id"]), []))
|
||||||
|
for row in video_rows
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def get_video(video_id: int) -> dict[str, object] | None:
|
||||||
|
with get_connection() as connection:
|
||||||
|
row = connection.execute(
|
||||||
|
"""
|
||||||
|
SELECT *
|
||||||
|
FROM videos
|
||||||
|
WHERE id = ? AND status = 'published'
|
||||||
|
""",
|
||||||
|
(video_id,),
|
||||||
|
).fetchone()
|
||||||
|
if row is None:
|
||||||
|
return None
|
||||||
|
|
||||||
|
subtitle_rows = connection.execute(
|
||||||
|
"""
|
||||||
|
SELECT *
|
||||||
|
FROM subtitles
|
||||||
|
WHERE video_id = ?
|
||||||
|
ORDER BY id ASC
|
||||||
|
""",
|
||||||
|
(video_id,),
|
||||||
|
).fetchall()
|
||||||
|
|
||||||
|
return row_to_video(row, subtitle_rows)
|
||||||
|
|
||||||
|
|
||||||
|
def delete_video(video_id: int) -> dict[str, object] | None:
|
||||||
|
with get_connection() as connection:
|
||||||
|
video_row = connection.execute(
|
||||||
|
"""
|
||||||
|
SELECT id, video_url
|
||||||
|
FROM videos
|
||||||
|
WHERE id = ?
|
||||||
|
""",
|
||||||
|
(video_id,),
|
||||||
|
).fetchone()
|
||||||
|
if video_row is None:
|
||||||
|
return None
|
||||||
|
|
||||||
|
subtitle_rows = connection.execute(
|
||||||
|
"""
|
||||||
|
SELECT file_path
|
||||||
|
FROM subtitles
|
||||||
|
WHERE video_id = ?
|
||||||
|
""",
|
||||||
|
(video_id,),
|
||||||
|
).fetchall()
|
||||||
|
|
||||||
|
upload_paths = []
|
||||||
|
if video_row["video_url"]:
|
||||||
|
upload_paths.append(video_row["video_url"])
|
||||||
|
upload_paths.extend(row["file_path"] for row in subtitle_rows if row["file_path"])
|
||||||
|
|
||||||
|
connection.execute("DELETE FROM videos WHERE id = ?", (video_id,))
|
||||||
|
|
||||||
|
return {
|
||||||
|
"deletedVideoId": video_id,
|
||||||
|
"uploadPaths": upload_paths,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def update_video(
|
||||||
|
video_id: int,
|
||||||
|
*,
|
||||||
|
title: str,
|
||||||
|
speaker: str | None,
|
||||||
|
description: str | None,
|
||||||
|
tags: list[str],
|
||||||
|
video_url: str | None,
|
||||||
|
subtitles: list[dict[str, str]],
|
||||||
|
) -> dict[str, object] | None:
|
||||||
|
with get_connection() as connection:
|
||||||
|
existing = connection.execute(
|
||||||
|
"""
|
||||||
|
SELECT id, video_url
|
||||||
|
FROM videos
|
||||||
|
WHERE id = ?
|
||||||
|
""",
|
||||||
|
(video_id,),
|
||||||
|
).fetchone()
|
||||||
|
if existing is None:
|
||||||
|
return None
|
||||||
|
|
||||||
|
old_upload_paths = []
|
||||||
|
final_video_url = video_url if video_url is not None else existing["video_url"]
|
||||||
|
if video_url is not None and existing["video_url"] and existing["video_url"] != video_url:
|
||||||
|
old_upload_paths.append(existing["video_url"])
|
||||||
|
|
||||||
|
connection.execute(
|
||||||
|
"""
|
||||||
|
UPDATE videos
|
||||||
|
SET title = ?,
|
||||||
|
speaker = ?,
|
||||||
|
description = ?,
|
||||||
|
tags = ?,
|
||||||
|
video_url = ?,
|
||||||
|
updated_at = CURRENT_TIMESTAMP
|
||||||
|
WHERE id = ?
|
||||||
|
""",
|
||||||
|
(
|
||||||
|
title,
|
||||||
|
repair_mojibake_text(speaker or "Unknown"),
|
||||||
|
repair_mojibake_text(description or ""),
|
||||||
|
json.dumps([repair_mojibake_text(tag) for tag in tags], ensure_ascii=False),
|
||||||
|
repair_mojibake_text(final_video_url),
|
||||||
|
video_id,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
for subtitle in subtitles:
|
||||||
|
existing_subtitle = connection.execute(
|
||||||
|
"""
|
||||||
|
SELECT file_path
|
||||||
|
FROM subtitles
|
||||||
|
WHERE video_id = ? AND language_code = ?
|
||||||
|
""",
|
||||||
|
(video_id, subtitle["language_code"]),
|
||||||
|
).fetchone()
|
||||||
|
if existing_subtitle and existing_subtitle["file_path"] != subtitle["file_path"]:
|
||||||
|
old_upload_paths.append(existing_subtitle["file_path"])
|
||||||
|
|
||||||
|
connection.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO subtitles (
|
||||||
|
video_id, language_code, language_name, format, file_path, content
|
||||||
|
)
|
||||||
|
VALUES (?, ?, ?, ?, ?, ?)
|
||||||
|
ON CONFLICT(video_id, language_code) DO UPDATE SET
|
||||||
|
language_name = excluded.language_name,
|
||||||
|
format = excluded.format,
|
||||||
|
file_path = excluded.file_path,
|
||||||
|
content = excluded.content,
|
||||||
|
updated_at = CURRENT_TIMESTAMP
|
||||||
|
""",
|
||||||
|
(
|
||||||
|
video_id,
|
||||||
|
subtitle["language_code"],
|
||||||
|
repair_mojibake_text(subtitle["language_name"]),
|
||||||
|
subtitle["format"],
|
||||||
|
subtitle["file_path"],
|
||||||
|
repair_mojibake_text(subtitle["content"]),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
video = get_video(video_id)
|
||||||
|
if video is None:
|
||||||
|
return None
|
||||||
|
return {
|
||||||
|
"video": video,
|
||||||
|
"oldUploadPaths": old_upload_paths,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def table_names() -> list[str]:
|
||||||
|
with get_connection() as connection:
|
||||||
|
rows = connection.execute(
|
||||||
|
"""
|
||||||
|
SELECT name
|
||||||
|
FROM sqlite_master
|
||||||
|
WHERE type = 'table'
|
||||||
|
AND name NOT LIKE 'sqlite_%'
|
||||||
|
ORDER BY name
|
||||||
|
"""
|
||||||
|
).fetchall()
|
||||||
|
return [row["name"] for row in rows]
|
||||||
+356
@@ -0,0 +1,356 @@
|
|||||||
|
from pathlib import Path
|
||||||
|
from urllib.parse import urlparse
|
||||||
|
from uuid import uuid4
|
||||||
|
|
||||||
|
from fastapi import FastAPI, File, Form, HTTPException, UploadFile
|
||||||
|
from fastapi.responses import FileResponse
|
||||||
|
from fastapi.staticfiles import StaticFiles
|
||||||
|
|
||||||
|
from .db import (
|
||||||
|
DATABASE_PATH,
|
||||||
|
create_video,
|
||||||
|
delete_video,
|
||||||
|
initialize_database,
|
||||||
|
list_videos,
|
||||||
|
parse_tags,
|
||||||
|
table_names,
|
||||||
|
get_video,
|
||||||
|
update_video,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
PROJECT_DIR = Path(__file__).resolve().parent.parent
|
||||||
|
UPLOADS_DIR = PROJECT_DIR / "uploads"
|
||||||
|
VIDEO_EXTENSIONS = {".mp4", ".webm", ".mov", ".m4v"}
|
||||||
|
SUBTITLE_EXTENSIONS = {".srt", ".vtt"}
|
||||||
|
UPLOAD_CHUNK_SIZE = 1024 * 1024
|
||||||
|
|
||||||
|
|
||||||
|
def ensure_upload_directories() -> None:
|
||||||
|
UPLOADS_DIR.mkdir(parents=True, exist_ok=True)
|
||||||
|
(UPLOADS_DIR / "videos").mkdir(parents=True, exist_ok=True)
|
||||||
|
(UPLOADS_DIR / "subtitles").mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
|
|
||||||
|
def extension_for_upload(upload: UploadFile) -> str:
|
||||||
|
return Path(upload.filename or "").suffix.lower()
|
||||||
|
|
||||||
|
|
||||||
|
def safe_upload_name(upload: UploadFile) -> str:
|
||||||
|
extension = extension_for_upload(upload)
|
||||||
|
return f"{uuid4().hex}{extension}"
|
||||||
|
|
||||||
|
|
||||||
|
async def save_upload(upload: UploadFile, target_dir: Path) -> tuple[str, str]:
|
||||||
|
target_dir.mkdir(parents=True, exist_ok=True)
|
||||||
|
filename = safe_upload_name(upload)
|
||||||
|
target_path = target_dir / filename
|
||||||
|
content = await upload.read()
|
||||||
|
try:
|
||||||
|
target_path.write_bytes(content)
|
||||||
|
except OSError as exc:
|
||||||
|
target_path.unlink(missing_ok=True)
|
||||||
|
raise HTTPException(status_code=500, detail="保存文件失败,请重试") from exc
|
||||||
|
return filename, content.decode("utf-8-sig", errors="replace")
|
||||||
|
|
||||||
|
|
||||||
|
async def save_binary_upload(upload: UploadFile, target_dir: Path) -> str:
|
||||||
|
target_dir.mkdir(parents=True, exist_ok=True)
|
||||||
|
filename = safe_upload_name(upload)
|
||||||
|
target_path = target_dir / filename
|
||||||
|
try:
|
||||||
|
with target_path.open("wb") as target_file:
|
||||||
|
while chunk := await upload.read(UPLOAD_CHUNK_SIZE):
|
||||||
|
target_file.write(chunk)
|
||||||
|
except OSError as exc:
|
||||||
|
target_path.unlink(missing_ok=True)
|
||||||
|
raise HTTPException(status_code=500, detail="保存文件失败,请重试") from exc
|
||||||
|
return filename
|
||||||
|
|
||||||
|
|
||||||
|
def cleanup_saved_files(paths: list[Path]) -> None:
|
||||||
|
for path in paths:
|
||||||
|
try:
|
||||||
|
path.unlink(missing_ok=True)
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def upload_url_to_path(value: str) -> Path | None:
|
||||||
|
if not value.startswith("/uploads/"):
|
||||||
|
return None
|
||||||
|
|
||||||
|
relative_parts = value.removeprefix("/uploads/").split("/")
|
||||||
|
if any(part in {"", ".", ".."} for part in relative_parts):
|
||||||
|
return None
|
||||||
|
|
||||||
|
candidate = (UPLOADS_DIR / Path(*relative_parts)).resolve()
|
||||||
|
uploads_root = UPLOADS_DIR.resolve()
|
||||||
|
|
||||||
|
try:
|
||||||
|
candidate.relative_to(uploads_root)
|
||||||
|
except ValueError:
|
||||||
|
return None
|
||||||
|
|
||||||
|
return candidate
|
||||||
|
|
||||||
|
|
||||||
|
def is_supported_video_url(value: str) -> bool:
|
||||||
|
parsed = urlparse(value)
|
||||||
|
return parsed.scheme in {"http", "https"} and bool(parsed.netloc)
|
||||||
|
|
||||||
|
|
||||||
|
def cleanup_upload_urls(upload_urls: list[str]) -> list[str]:
|
||||||
|
warnings: list[str] = []
|
||||||
|
for upload_url in upload_urls:
|
||||||
|
path = upload_url_to_path(str(upload_url))
|
||||||
|
if path is None:
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
path.unlink(missing_ok=True)
|
||||||
|
except OSError:
|
||||||
|
warnings.append(f"无法删除文件: {path}")
|
||||||
|
return warnings
|
||||||
|
|
||||||
|
|
||||||
|
ensure_upload_directories()
|
||||||
|
|
||||||
|
app = FastAPI(title="Speaking Lab API")
|
||||||
|
|
||||||
|
|
||||||
|
@app.on_event("startup")
|
||||||
|
def on_startup() -> None:
|
||||||
|
initialize_database()
|
||||||
|
ensure_upload_directories()
|
||||||
|
|
||||||
|
|
||||||
|
app.mount("/uploads", StaticFiles(directory=UPLOADS_DIR), name="uploads")
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/api/health")
|
||||||
|
def health_check() -> dict[str, object]:
|
||||||
|
return {
|
||||||
|
"ok": True,
|
||||||
|
"database": str(DATABASE_PATH),
|
||||||
|
"tables": table_names(),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/api/videos")
|
||||||
|
def api_list_videos() -> list[dict[str, object]]:
|
||||||
|
return list_videos()
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/api/videos/{video_id}")
|
||||||
|
def api_get_video(video_id: int) -> dict[str, object]:
|
||||||
|
video = get_video(video_id)
|
||||||
|
if video is None:
|
||||||
|
raise HTTPException(status_code=404, detail="视频不存在")
|
||||||
|
return video
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/api/videos")
|
||||||
|
async def api_create_video(
|
||||||
|
title: str = Form(...),
|
||||||
|
speaker: str = Form(""),
|
||||||
|
description: str = Form(""),
|
||||||
|
tags: str = Form(""),
|
||||||
|
video_url: str = Form(""),
|
||||||
|
video_file: UploadFile | None = File(None),
|
||||||
|
subtitle_en: UploadFile | None = File(None),
|
||||||
|
subtitle_zh: UploadFile | None = File(None),
|
||||||
|
) -> dict[str, object]:
|
||||||
|
clean_title = title.strip()
|
||||||
|
if not clean_title:
|
||||||
|
raise HTTPException(status_code=400, detail="标题不能为空")
|
||||||
|
|
||||||
|
clean_video_url = video_url.strip()
|
||||||
|
if video_file is None and not clean_video_url:
|
||||||
|
raise HTTPException(status_code=400, detail="请上传视频文件或填写视频地址")
|
||||||
|
|
||||||
|
if video_file is None and not is_supported_video_url(clean_video_url):
|
||||||
|
raise HTTPException(status_code=400, detail="视频地址必须以 http:// 或 https:// 开头")
|
||||||
|
|
||||||
|
if video_file is not None:
|
||||||
|
if extension_for_upload(video_file) not in VIDEO_EXTENSIONS:
|
||||||
|
raise HTTPException(status_code=400, detail="视频文件格式不支持")
|
||||||
|
|
||||||
|
subtitle_uploads: list[tuple[UploadFile, str, str, str]] = []
|
||||||
|
for upload, language_code, language_name in (
|
||||||
|
(subtitle_en, "en", "English"),
|
||||||
|
(subtitle_zh, "zh", "中文"),
|
||||||
|
):
|
||||||
|
if upload is None:
|
||||||
|
continue
|
||||||
|
extension = extension_for_upload(upload)
|
||||||
|
if extension not in SUBTITLE_EXTENSIONS:
|
||||||
|
raise HTTPException(status_code=400, detail="字幕只支持 .srt 或 .vtt")
|
||||||
|
subtitle_uploads.append((upload, language_code, language_name, extension))
|
||||||
|
|
||||||
|
saved_paths: list[Path] = []
|
||||||
|
try:
|
||||||
|
final_video_url = clean_video_url
|
||||||
|
if video_file is not None:
|
||||||
|
video_filename = await save_binary_upload(video_file, UPLOADS_DIR / "videos")
|
||||||
|
saved_paths.append(UPLOADS_DIR / "videos" / video_filename)
|
||||||
|
final_video_url = f"/uploads/videos/{video_filename}"
|
||||||
|
|
||||||
|
subtitles: list[dict[str, str]] = []
|
||||||
|
for upload, language_code, language_name, extension in subtitle_uploads:
|
||||||
|
subtitle_filename, subtitle_text = await save_upload(upload, UPLOADS_DIR / "subtitles")
|
||||||
|
saved_paths.append(UPLOADS_DIR / "subtitles" / subtitle_filename)
|
||||||
|
subtitles.append(
|
||||||
|
{
|
||||||
|
"language_code": language_code,
|
||||||
|
"language_name": language_name,
|
||||||
|
"format": extension.removeprefix("."),
|
||||||
|
"file_path": f"/uploads/subtitles/{subtitle_filename}",
|
||||||
|
"content": subtitle_text,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
return create_video(
|
||||||
|
title=clean_title,
|
||||||
|
speaker=speaker.strip(),
|
||||||
|
description=description.strip(),
|
||||||
|
tags=parse_tags(tags),
|
||||||
|
video_url=final_video_url,
|
||||||
|
subtitles=subtitles,
|
||||||
|
)
|
||||||
|
except Exception:
|
||||||
|
cleanup_saved_files(saved_paths)
|
||||||
|
raise
|
||||||
|
|
||||||
|
|
||||||
|
@app.patch("/api/videos/{video_id}")
|
||||||
|
async def api_update_video(
|
||||||
|
video_id: int,
|
||||||
|
title: str = Form(...),
|
||||||
|
speaker: str = Form(""),
|
||||||
|
description: str = Form(""),
|
||||||
|
tags: str = Form(""),
|
||||||
|
video_url: str = Form(""),
|
||||||
|
subtitle_en_content: str | None = Form(None),
|
||||||
|
subtitle_zh_content: str | None = Form(None),
|
||||||
|
video_file: UploadFile | None = File(None),
|
||||||
|
subtitle_en: UploadFile | None = File(None),
|
||||||
|
subtitle_zh: UploadFile | None = File(None),
|
||||||
|
) -> dict[str, object]:
|
||||||
|
existing = get_video(video_id)
|
||||||
|
if existing is None:
|
||||||
|
raise HTTPException(status_code=404, detail="视频不存在")
|
||||||
|
|
||||||
|
clean_title = title.strip()
|
||||||
|
if not clean_title:
|
||||||
|
raise HTTPException(status_code=400, detail="标题不能为空")
|
||||||
|
|
||||||
|
clean_video_url = video_url.strip()
|
||||||
|
final_video_url: str | None = None
|
||||||
|
if video_file is None and clean_video_url:
|
||||||
|
if not is_supported_video_url(clean_video_url) and not clean_video_url.startswith("/uploads/"):
|
||||||
|
raise HTTPException(status_code=400, detail="视频地址必须以 http:// 或 https:// 开头")
|
||||||
|
final_video_url = clean_video_url
|
||||||
|
|
||||||
|
if video_file is not None and extension_for_upload(video_file) not in VIDEO_EXTENSIONS:
|
||||||
|
raise HTTPException(status_code=400, detail="视频文件格式不支持")
|
||||||
|
|
||||||
|
subtitle_uploads: list[tuple[UploadFile, str, str, str]] = []
|
||||||
|
for upload, language_code, language_name in (
|
||||||
|
(subtitle_en, "en", "English"),
|
||||||
|
(subtitle_zh, "zh", "中文"),
|
||||||
|
):
|
||||||
|
if upload is None:
|
||||||
|
continue
|
||||||
|
extension = extension_for_upload(upload)
|
||||||
|
if extension not in SUBTITLE_EXTENSIONS:
|
||||||
|
raise HTTPException(status_code=400, detail="字幕只支持 .srt 或 .vtt")
|
||||||
|
subtitle_uploads.append((upload, language_code, language_name, extension))
|
||||||
|
|
||||||
|
saved_paths: list[Path] = []
|
||||||
|
try:
|
||||||
|
if video_file is not None:
|
||||||
|
video_filename = await save_binary_upload(video_file, UPLOADS_DIR / "videos")
|
||||||
|
saved_paths.append(UPLOADS_DIR / "videos" / video_filename)
|
||||||
|
final_video_url = f"/uploads/videos/{video_filename}"
|
||||||
|
|
||||||
|
subtitles: list[dict[str, str]] = []
|
||||||
|
for upload, language_code, language_name, extension in subtitle_uploads:
|
||||||
|
subtitle_filename, subtitle_text = await save_upload(upload, UPLOADS_DIR / "subtitles")
|
||||||
|
saved_paths.append(UPLOADS_DIR / "subtitles" / subtitle_filename)
|
||||||
|
subtitles.append(
|
||||||
|
{
|
||||||
|
"language_code": language_code,
|
||||||
|
"language_name": language_name,
|
||||||
|
"format": extension.removeprefix("."),
|
||||||
|
"file_path": f"/uploads/subtitles/{subtitle_filename}",
|
||||||
|
"content": subtitle_text,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
uploaded_language_codes = {language_code for _, language_code, _, _ in subtitle_uploads}
|
||||||
|
existing_subtitles = existing.get("subtitles", {})
|
||||||
|
for language_code, language_name, content in (
|
||||||
|
("en", "English", subtitle_en_content),
|
||||||
|
("zh", "中文", subtitle_zh_content),
|
||||||
|
):
|
||||||
|
if content is None or language_code in uploaded_language_codes:
|
||||||
|
continue
|
||||||
|
existing_subtitle = existing_subtitles.get(language_code, {})
|
||||||
|
subtitles.append(
|
||||||
|
{
|
||||||
|
"language_code": language_code,
|
||||||
|
"language_name": existing_subtitle.get("languageName") or language_name,
|
||||||
|
"format": existing_subtitle.get("format") or "vtt",
|
||||||
|
"file_path": existing_subtitle.get("filePath") or "",
|
||||||
|
"content": content,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
updated = update_video(
|
||||||
|
video_id,
|
||||||
|
title=clean_title,
|
||||||
|
speaker=speaker.strip(),
|
||||||
|
description=description.strip(),
|
||||||
|
tags=parse_tags(tags),
|
||||||
|
video_url=final_video_url,
|
||||||
|
subtitles=subtitles,
|
||||||
|
)
|
||||||
|
if updated is None:
|
||||||
|
cleanup_saved_files(saved_paths)
|
||||||
|
raise HTTPException(status_code=404, detail="视频不存在")
|
||||||
|
|
||||||
|
warnings = cleanup_upload_urls([str(path) for path in updated["oldUploadPaths"]])
|
||||||
|
return {
|
||||||
|
"ok": True,
|
||||||
|
"video": updated["video"],
|
||||||
|
"warnings": warnings,
|
||||||
|
}
|
||||||
|
except HTTPException:
|
||||||
|
cleanup_saved_files(saved_paths)
|
||||||
|
raise
|
||||||
|
except Exception:
|
||||||
|
cleanup_saved_files(saved_paths)
|
||||||
|
raise
|
||||||
|
|
||||||
|
|
||||||
|
@app.delete("/api/videos/{video_id}")
|
||||||
|
def api_delete_video(video_id: int) -> dict[str, object]:
|
||||||
|
deleted = delete_video(video_id)
|
||||||
|
if deleted is None:
|
||||||
|
raise HTTPException(status_code=404, detail="视频不存在")
|
||||||
|
|
||||||
|
warnings = cleanup_upload_urls([str(path) for path in deleted["uploadPaths"]])
|
||||||
|
|
||||||
|
return {
|
||||||
|
"ok": True,
|
||||||
|
"deletedVideoId": deleted["deletedVideoId"],
|
||||||
|
"warnings": warnings,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/")
|
||||||
|
def read_index() -> FileResponse:
|
||||||
|
return FileResponse(PROJECT_DIR / "index.html")
|
||||||
|
|
||||||
|
|
||||||
|
app.mount("/", StaticFiles(directory=PROJECT_DIR), name="static")
|
||||||
@@ -0,0 +1,841 @@
|
|||||||
|
# Speaking Lab Admin Page Implementation Plan
|
||||||
|
|
||||||
|
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||||
|
|
||||||
|
**Goal:** Move material management to a dedicated admin page with add and delete support, and show a small study-page admin entry only for local admin users.
|
||||||
|
|
||||||
|
**Architecture:** Keep the current local prototype auth model in `localStorage`. Add backend deletion helpers and a `DELETE /api/videos/{video_id}` endpoint, remove embedded admin UI from the study page, and add a separate static `admin.html` + `admin.js` page that uses the existing create endpoint plus the new delete endpoint.
|
||||||
|
|
||||||
|
**Tech Stack:** FastAPI, Python `sqlite3`, vanilla JavaScript, localStorage, local filesystem uploads.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## File Structure
|
||||||
|
|
||||||
|
- Modify `F:\ooo\speaking-practice-local\backend\db.py`: add a helper to collect uploaded file paths and delete a video row.
|
||||||
|
- Modify `F:\ooo\speaking-practice-local\backend\main.py`: add safe uploaded-file deletion and `DELETE /api/videos/{video_id}`.
|
||||||
|
- Modify `F:\ooo\speaking-practice-local\index.html`: remove embedded admin dock and add a hidden admin button beside the material rail heading.
|
||||||
|
- Modify `F:\ooo\speaking-practice-local\app.js`: remove study-page admin form logic, show/hide the admin button for admins, and navigate to `admin.html`.
|
||||||
|
- Add `F:\ooo\speaking-practice-local\admin.html`: standalone admin page.
|
||||||
|
- Add `F:\ooo\speaking-practice-local\admin.js`: admin-only local gate, add material, list materials, delete material.
|
||||||
|
- Modify `F:\ooo\speaking-practice-local\styles.css`: add styles for the rail admin button and admin page.
|
||||||
|
- Modify `F:\ooo\speaking-practice-local\README.md`: document the dedicated admin page.
|
||||||
|
|
||||||
|
The project is not a git repository. Do not initialize git or commit during implementation.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Task 1: Add Backend Delete Support
|
||||||
|
|
||||||
|
**Files:**
|
||||||
|
- Modify: `F:\ooo\speaking-practice-local\backend\db.py`
|
||||||
|
- Modify: `F:\ooo\speaking-practice-local\backend\main.py`
|
||||||
|
|
||||||
|
- [ ] **Step 1: Add database helper in `backend/db.py`**
|
||||||
|
|
||||||
|
Add this function after `get_video()`:
|
||||||
|
|
||||||
|
```python
|
||||||
|
def delete_video(video_id: int) -> dict[str, object] | None:
|
||||||
|
with get_connection() as connection:
|
||||||
|
video_row = connection.execute(
|
||||||
|
"""
|
||||||
|
SELECT id, video_url
|
||||||
|
FROM videos
|
||||||
|
WHERE id = ?
|
||||||
|
""",
|
||||||
|
(video_id,),
|
||||||
|
).fetchone()
|
||||||
|
if video_row is None:
|
||||||
|
return None
|
||||||
|
|
||||||
|
subtitle_rows = connection.execute(
|
||||||
|
"""
|
||||||
|
SELECT file_path
|
||||||
|
FROM subtitles
|
||||||
|
WHERE video_id = ?
|
||||||
|
""",
|
||||||
|
(video_id,),
|
||||||
|
).fetchall()
|
||||||
|
|
||||||
|
upload_paths = []
|
||||||
|
if video_row["video_url"]:
|
||||||
|
upload_paths.append(video_row["video_url"])
|
||||||
|
upload_paths.extend(row["file_path"] for row in subtitle_rows if row["file_path"])
|
||||||
|
|
||||||
|
connection.execute("DELETE FROM videos WHERE id = ?", (video_id,))
|
||||||
|
|
||||||
|
return {
|
||||||
|
"deletedVideoId": video_id,
|
||||||
|
"uploadPaths": upload_paths,
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
- [ ] **Step 2: Import `delete_video` in `backend/main.py`**
|
||||||
|
|
||||||
|
Update the `.db` import list to include:
|
||||||
|
|
||||||
|
```python
|
||||||
|
delete_video,
|
||||||
|
```
|
||||||
|
|
||||||
|
- [ ] **Step 3: Add safe upload path resolution in `backend/main.py`**
|
||||||
|
|
||||||
|
Add this helper after `cleanup_saved_files()`:
|
||||||
|
|
||||||
|
```python
|
||||||
|
def upload_url_to_path(value: str) -> Path | None:
|
||||||
|
if not value.startswith("/uploads/"):
|
||||||
|
return None
|
||||||
|
|
||||||
|
relative = value.removeprefix("/uploads/").replace("/", "\\")
|
||||||
|
candidate = (UPLOADS_DIR / relative).resolve()
|
||||||
|
uploads_root = UPLOADS_DIR.resolve()
|
||||||
|
|
||||||
|
try:
|
||||||
|
candidate.relative_to(uploads_root)
|
||||||
|
except ValueError:
|
||||||
|
return None
|
||||||
|
|
||||||
|
return candidate
|
||||||
|
```
|
||||||
|
|
||||||
|
- [ ] **Step 4: Add delete endpoint in `backend/main.py`**
|
||||||
|
|
||||||
|
Add this after `api_create_video()`:
|
||||||
|
|
||||||
|
```python
|
||||||
|
@app.delete("/api/videos/{video_id}")
|
||||||
|
def api_delete_video(video_id: int) -> dict[str, object]:
|
||||||
|
deleted = delete_video(video_id)
|
||||||
|
if deleted is None:
|
||||||
|
raise HTTPException(status_code=404, detail="视频不存在")
|
||||||
|
|
||||||
|
warnings: list[str] = []
|
||||||
|
for upload_url in deleted["uploadPaths"]:
|
||||||
|
path = upload_url_to_path(str(upload_url))
|
||||||
|
if path is None:
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
path.unlink(missing_ok=True)
|
||||||
|
except OSError:
|
||||||
|
warnings.append(f"无法删除文件: {path}")
|
||||||
|
|
||||||
|
return {
|
||||||
|
"ok": True,
|
||||||
|
"deletedVideoId": deleted["deletedVideoId"],
|
||||||
|
"warnings": warnings,
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
- [ ] **Step 5: Run backend checks**
|
||||||
|
|
||||||
|
Run:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
python -m py_compile backend\main.py backend\db.py
|
||||||
|
python -c "from backend.main import app; print([route.path for route in app.routes if route.path.startswith('/api/videos')])"
|
||||||
|
```
|
||||||
|
|
||||||
|
Expected:
|
||||||
|
|
||||||
|
- compile command exits with no output
|
||||||
|
- output includes `/api/videos/{video_id}` for both GET and DELETE route registrations
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Task 2: Clean Study Page And Add Admin Entry
|
||||||
|
|
||||||
|
**Files:**
|
||||||
|
- Modify: `F:\ooo\speaking-practice-local\index.html`
|
||||||
|
- Modify: `F:\ooo\speaking-practice-local\app.js`
|
||||||
|
|
||||||
|
- [ ] **Step 1: Add admin button beside material heading**
|
||||||
|
|
||||||
|
In `index.html`, replace:
|
||||||
|
|
||||||
|
```html
|
||||||
|
<div class="rail-heading">
|
||||||
|
<strong>素材</strong>
|
||||||
|
<span id="videoCount">0</span>
|
||||||
|
</div>
|
||||||
|
```
|
||||||
|
|
||||||
|
with:
|
||||||
|
|
||||||
|
```html
|
||||||
|
<div class="rail-heading">
|
||||||
|
<div class="rail-title">
|
||||||
|
<strong>素材</strong>
|
||||||
|
<button id="adminEntryBtn" class="icon-button admin-entry" type="button" title="后台管理" hidden>管理</button>
|
||||||
|
</div>
|
||||||
|
<span id="videoCount">0</span>
|
||||||
|
</div>
|
||||||
|
```
|
||||||
|
|
||||||
|
- [ ] **Step 2: Remove embedded admin dock**
|
||||||
|
|
||||||
|
Delete the entire `<aside class="admin-dock">...</aside>` block from `index.html`.
|
||||||
|
|
||||||
|
- [ ] **Step 3: Update element references in `app.js`**
|
||||||
|
|
||||||
|
In the `els` object:
|
||||||
|
|
||||||
|
Add:
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
adminEntryBtn: document.querySelector("#adminEntryBtn"),
|
||||||
|
```
|
||||||
|
|
||||||
|
Remove these entries:
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
adminForm: document.querySelector("#adminForm"),
|
||||||
|
adminTitle: document.querySelector("#adminTitle"),
|
||||||
|
adminSpeaker: document.querySelector("#adminSpeaker"),
|
||||||
|
adminDescription: document.querySelector("#adminDescription"),
|
||||||
|
adminTags: document.querySelector("#adminTags"),
|
||||||
|
adminVideoFile: document.querySelector("#adminVideoFile"),
|
||||||
|
adminVideoUrl: document.querySelector("#adminVideoUrl"),
|
||||||
|
adminSubtitleEn: document.querySelector("#adminSubtitleEn"),
|
||||||
|
adminSubtitleZh: document.querySelector("#adminSubtitleZh"),
|
||||||
|
updateCurrentBtn: document.querySelector("#updateCurrentBtn"),
|
||||||
|
adminStatus: document.querySelector("#adminStatus"),
|
||||||
|
```
|
||||||
|
|
||||||
|
- [ ] **Step 4: Update events in `app.js`**
|
||||||
|
|
||||||
|
Remove:
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
els.adminForm.addEventListener("submit", addVideoFromAdmin);
|
||||||
|
els.updateCurrentBtn.addEventListener("click", updateCurrentVideoInfo);
|
||||||
|
```
|
||||||
|
|
||||||
|
Add:
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
els.adminEntryBtn.addEventListener("click", () => {
|
||||||
|
window.location.href = "admin.html";
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
- [ ] **Step 5: Replace `renderAdminAccess()` in `app.js`**
|
||||||
|
|
||||||
|
Replace the existing function with:
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
function renderAdminAccess() {
|
||||||
|
const user = getCurrentUser();
|
||||||
|
const isAdmin = user?.role === "admin";
|
||||||
|
els.adminEntryBtn.hidden = !isAdmin;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
- [ ] **Step 6: Remove study-page admin functions in `app.js`**
|
||||||
|
|
||||||
|
Delete these functions completely:
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
async function addVideoFromAdmin(event) { ... }
|
||||||
|
function fillAdminForm(video) { ... }
|
||||||
|
function updateCurrentVideoInfo() { ... }
|
||||||
|
```
|
||||||
|
|
||||||
|
Remove the call to `fillAdminForm(video);` from `selectVideo()`.
|
||||||
|
|
||||||
|
- [ ] **Step 7: Run frontend syntax check**
|
||||||
|
|
||||||
|
Run:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
node --check app.js
|
||||||
|
```
|
||||||
|
|
||||||
|
Expected: no output, exit code 0.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Task 3: Add Standalone Admin Page
|
||||||
|
|
||||||
|
**Files:**
|
||||||
|
- Add: `F:\ooo\speaking-practice-local\admin.html`
|
||||||
|
- Add: `F:\ooo\speaking-practice-local\admin.js`
|
||||||
|
|
||||||
|
- [ ] **Step 1: Create `admin.html`**
|
||||||
|
|
||||||
|
Create the file:
|
||||||
|
|
||||||
|
```html
|
||||||
|
<!doctype html>
|
||||||
|
<html lang="zh-CN">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<title>Speaking Lab 后台管理</title>
|
||||||
|
<link rel="stylesheet" href="./styles.css">
|
||||||
|
</head>
|
||||||
|
<body class="admin-page">
|
||||||
|
<header class="admin-topbar">
|
||||||
|
<div>
|
||||||
|
<h1>后台管理</h1>
|
||||||
|
<p id="adminIdentity">请先使用管理员账号登录。</p>
|
||||||
|
</div>
|
||||||
|
<a class="secondary-action" href="./index.html">返回学习页</a>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<main id="adminLocked" class="admin-locked" hidden>
|
||||||
|
<h2>需要管理员账号</h2>
|
||||||
|
<p>请返回学习页,使用邮箱包含 admin 的账号登录后再进入后台。</p>
|
||||||
|
<a class="primary-link" href="./index.html">去登录</a>
|
||||||
|
</main>
|
||||||
|
|
||||||
|
<main id="adminContent" class="admin-shell" hidden>
|
||||||
|
<section class="admin-panel">
|
||||||
|
<h2>添加素材</h2>
|
||||||
|
<form id="adminCreateForm" class="admin-create-form">
|
||||||
|
<input id="adminTitle" type="text" placeholder="视频标题" required>
|
||||||
|
<input id="adminSpeaker" type="text" placeholder="演讲者 / 片段来源">
|
||||||
|
<textarea id="adminDescription" placeholder="简介"></textarea>
|
||||||
|
<input id="adminTags" type="text" placeholder="标签,用逗号分隔,如 科技,设计">
|
||||||
|
<label class="file-input">
|
||||||
|
<span>选择视频文件</span>
|
||||||
|
<input id="adminVideoFile" type="file" accept="video/*">
|
||||||
|
</label>
|
||||||
|
<input id="adminVideoUrl" type="url" placeholder="或填写视频 / HLS 地址">
|
||||||
|
<label class="file-input">
|
||||||
|
<span>英文字幕 .srt/.vtt</span>
|
||||||
|
<input id="adminSubtitleEn" type="file" accept=".srt,.vtt,text/vtt,text/plain">
|
||||||
|
</label>
|
||||||
|
<label class="file-input">
|
||||||
|
<span>中文字幕 .srt/.vtt</span>
|
||||||
|
<input id="adminSubtitleZh" type="file" accept=".srt,.vtt,text/vtt,text/plain">
|
||||||
|
</label>
|
||||||
|
<button type="submit">添加到视频库</button>
|
||||||
|
</form>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="admin-panel">
|
||||||
|
<div class="admin-list-heading">
|
||||||
|
<h2>素材列表</h2>
|
||||||
|
<button id="refreshVideosBtn" class="secondary-action" type="button">刷新</button>
|
||||||
|
</div>
|
||||||
|
<div id="adminMessage" class="admin-message" hidden></div>
|
||||||
|
<div id="adminVideoList" class="admin-video-list"></div>
|
||||||
|
</section>
|
||||||
|
</main>
|
||||||
|
|
||||||
|
<script src="./admin.js"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
```
|
||||||
|
|
||||||
|
- [ ] **Step 2: Create `admin.js`**
|
||||||
|
|
||||||
|
Create the file:
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
const STORAGE_KEY = "speaking-lab-state-v1";
|
||||||
|
|
||||||
|
const els = {
|
||||||
|
identity: document.querySelector("#adminIdentity"),
|
||||||
|
locked: document.querySelector("#adminLocked"),
|
||||||
|
content: document.querySelector("#adminContent"),
|
||||||
|
form: document.querySelector("#adminCreateForm"),
|
||||||
|
title: document.querySelector("#adminTitle"),
|
||||||
|
speaker: document.querySelector("#adminSpeaker"),
|
||||||
|
description: document.querySelector("#adminDescription"),
|
||||||
|
tags: document.querySelector("#adminTags"),
|
||||||
|
videoFile: document.querySelector("#adminVideoFile"),
|
||||||
|
videoUrl: document.querySelector("#adminVideoUrl"),
|
||||||
|
subtitleEn: document.querySelector("#adminSubtitleEn"),
|
||||||
|
subtitleZh: document.querySelector("#adminSubtitleZh"),
|
||||||
|
refreshBtn: document.querySelector("#refreshVideosBtn"),
|
||||||
|
message: document.querySelector("#adminMessage"),
|
||||||
|
videoList: document.querySelector("#adminVideoList"),
|
||||||
|
};
|
||||||
|
|
||||||
|
let videos = [];
|
||||||
|
|
||||||
|
initializeAdmin();
|
||||||
|
|
||||||
|
function loadState() {
|
||||||
|
try {
|
||||||
|
const saved = JSON.parse(localStorage.getItem(STORAGE_KEY) || "{}");
|
||||||
|
return {
|
||||||
|
users: Array.isArray(saved.users) ? saved.users : [],
|
||||||
|
currentUserId: saved.currentUserId || null,
|
||||||
|
};
|
||||||
|
} catch {
|
||||||
|
return { users: [], currentUserId: null };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function getCurrentUser() {
|
||||||
|
const state = loadState();
|
||||||
|
return state.users.find((user) => user.id === state.currentUserId) || null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function isAdmin(user) {
|
||||||
|
return user?.role === "admin" || user?.email?.includes("admin");
|
||||||
|
}
|
||||||
|
|
||||||
|
async function apiRequest(path, options = {}) {
|
||||||
|
const response = await fetch(path, options);
|
||||||
|
if (!response.ok) {
|
||||||
|
let message = "请求失败,请重试。";
|
||||||
|
try {
|
||||||
|
const payload = await response.json();
|
||||||
|
message = payload.detail || message;
|
||||||
|
} catch {
|
||||||
|
message = response.statusText || message;
|
||||||
|
}
|
||||||
|
throw new Error(message);
|
||||||
|
}
|
||||||
|
return response.json();
|
||||||
|
}
|
||||||
|
|
||||||
|
function initializeAdmin() {
|
||||||
|
const user = getCurrentUser();
|
||||||
|
if (!isAdmin(user)) {
|
||||||
|
els.identity.textContent = "未登录管理员账号";
|
||||||
|
els.locked.hidden = false;
|
||||||
|
els.content.hidden = true;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
els.identity.textContent = `${user.email} · 管理员`;
|
||||||
|
els.locked.hidden = true;
|
||||||
|
els.content.hidden = false;
|
||||||
|
|
||||||
|
els.form.addEventListener("submit", addVideo);
|
||||||
|
els.refreshBtn.addEventListener("click", loadVideos);
|
||||||
|
loadVideos();
|
||||||
|
}
|
||||||
|
|
||||||
|
function showMessage(text, isError = false) {
|
||||||
|
els.message.hidden = false;
|
||||||
|
els.message.textContent = text;
|
||||||
|
els.message.classList.toggle("error", isError);
|
||||||
|
}
|
||||||
|
|
||||||
|
function clearMessage() {
|
||||||
|
els.message.hidden = true;
|
||||||
|
els.message.textContent = "";
|
||||||
|
els.message.classList.remove("error");
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadVideos() {
|
||||||
|
clearMessage();
|
||||||
|
try {
|
||||||
|
videos = await apiRequest("/api/videos");
|
||||||
|
renderVideos();
|
||||||
|
} catch (error) {
|
||||||
|
showMessage(error.message || "素材加载失败。", true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderVideos() {
|
||||||
|
els.videoList.innerHTML = "";
|
||||||
|
if (!videos.length) {
|
||||||
|
els.videoList.innerHTML = `<div class="empty-state">还没有素材。</div>`;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const fragment = document.createDocumentFragment();
|
||||||
|
videos.forEach((video) => {
|
||||||
|
const item = document.createElement("article");
|
||||||
|
item.className = "admin-video-item";
|
||||||
|
const subtitleCodes = Object.keys(video.subtitles || {});
|
||||||
|
item.innerHTML = `
|
||||||
|
<div>
|
||||||
|
<h3></h3>
|
||||||
|
<p class="admin-video-meta"></p>
|
||||||
|
<p class="admin-video-subtitles"></p>
|
||||||
|
</div>
|
||||||
|
<button class="danger-action" type="button">删除</button>
|
||||||
|
`;
|
||||||
|
item.querySelector("h3").textContent = video.title || "Untitled";
|
||||||
|
item.querySelector(".admin-video-meta").textContent = [
|
||||||
|
video.speaker || "Unknown",
|
||||||
|
Array.isArray(video.tags) ? video.tags.join(" / ") : "未分类",
|
||||||
|
video.sourceType === "url" ? "链接" : "本地文件",
|
||||||
|
].join(" · ");
|
||||||
|
item.querySelector(".admin-video-subtitles").textContent = subtitleCodes.length
|
||||||
|
? `字幕:${subtitleCodes.join(" / ")}`
|
||||||
|
: "字幕:无";
|
||||||
|
item.querySelector(".danger-action").addEventListener("click", () => deleteVideo(video));
|
||||||
|
fragment.appendChild(item);
|
||||||
|
});
|
||||||
|
els.videoList.appendChild(fragment);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function addVideo(event) {
|
||||||
|
event.preventDefault();
|
||||||
|
clearMessage();
|
||||||
|
|
||||||
|
const title = els.title.value.trim();
|
||||||
|
if (!title) {
|
||||||
|
showMessage("标题不能为空", true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const submitButton = els.form.querySelector('button[type="submit"]');
|
||||||
|
const previousText = submitButton.textContent;
|
||||||
|
submitButton.disabled = true;
|
||||||
|
submitButton.textContent = "正在添加...";
|
||||||
|
|
||||||
|
const formData = new FormData();
|
||||||
|
formData.append("title", title);
|
||||||
|
formData.append("speaker", els.speaker.value.trim());
|
||||||
|
formData.append("description", els.description.value.trim());
|
||||||
|
formData.append("tags", els.tags.value.trim());
|
||||||
|
formData.append("video_url", els.videoUrl.value.trim());
|
||||||
|
|
||||||
|
if (els.videoFile.files?.[0]) formData.append("video_file", els.videoFile.files[0]);
|
||||||
|
if (els.subtitleEn.files?.[0]) formData.append("subtitle_en", els.subtitleEn.files[0]);
|
||||||
|
if (els.subtitleZh.files?.[0]) formData.append("subtitle_zh", els.subtitleZh.files[0]);
|
||||||
|
|
||||||
|
try {
|
||||||
|
await apiRequest("/api/videos", {
|
||||||
|
method: "POST",
|
||||||
|
body: formData,
|
||||||
|
});
|
||||||
|
els.form.reset();
|
||||||
|
showMessage("素材已添加。");
|
||||||
|
await loadVideos();
|
||||||
|
} catch (error) {
|
||||||
|
showMessage(error.message || "添加素材失败。", true);
|
||||||
|
} finally {
|
||||||
|
submitButton.disabled = false;
|
||||||
|
submitButton.textContent = previousText;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function deleteVideo(video) {
|
||||||
|
const confirmed = window.confirm("确定删除这个素材吗?此操作不可恢复。");
|
||||||
|
if (!confirmed) return;
|
||||||
|
|
||||||
|
clearMessage();
|
||||||
|
try {
|
||||||
|
const result = await apiRequest(`/api/videos/${video.id}`, {
|
||||||
|
method: "DELETE",
|
||||||
|
});
|
||||||
|
videos = videos.filter((item) => String(item.id) !== String(video.id));
|
||||||
|
renderVideos();
|
||||||
|
const warningText = Array.isArray(result.warnings) && result.warnings.length
|
||||||
|
? `素材已删除,但有文件未能删除:${result.warnings.join(";")}`
|
||||||
|
: "素材已删除。";
|
||||||
|
showMessage(warningText, Boolean(result.warnings?.length));
|
||||||
|
} catch (error) {
|
||||||
|
showMessage(error.message || "删除素材失败。", true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
- [ ] **Step 3: Run admin script syntax check**
|
||||||
|
|
||||||
|
Run:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
node --check admin.js
|
||||||
|
```
|
||||||
|
|
||||||
|
Expected: no output, exit code 0.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Task 4: Add Styles For Admin Entry And Page
|
||||||
|
|
||||||
|
**Files:**
|
||||||
|
- Modify: `F:\ooo\speaking-practice-local\styles.css`
|
||||||
|
|
||||||
|
- [ ] **Step 1: Add rail admin button styles**
|
||||||
|
|
||||||
|
Add these styles near the existing rail/list styles:
|
||||||
|
|
||||||
|
```css
|
||||||
|
.rail-title {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.icon-button.admin-entry {
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
background: var(--surface);
|
||||||
|
color: var(--muted);
|
||||||
|
border-radius: 6px;
|
||||||
|
padding: 4px 8px;
|
||||||
|
font-size: 12px;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
|
||||||
|
.icon-button.admin-entry:hover {
|
||||||
|
color: var(--text);
|
||||||
|
border-color: var(--accent);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
- [ ] **Step 2: Add admin page styles**
|
||||||
|
|
||||||
|
Append:
|
||||||
|
|
||||||
|
```css
|
||||||
|
.admin-page {
|
||||||
|
min-height: 100vh;
|
||||||
|
background: var(--bg);
|
||||||
|
color: var(--text);
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-topbar {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 16px;
|
||||||
|
padding: 18px 24px;
|
||||||
|
border-bottom: 1px solid var(--border);
|
||||||
|
background: var(--surface);
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-topbar h1 {
|
||||||
|
margin: 0;
|
||||||
|
font-size: 22px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-topbar p {
|
||||||
|
margin: 4px 0 0;
|
||||||
|
color: var(--muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-shell {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: minmax(320px, 420px) minmax(0, 1fr);
|
||||||
|
gap: 16px;
|
||||||
|
padding: 16px 24px 32px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-panel,
|
||||||
|
.admin-locked {
|
||||||
|
background: var(--surface);
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: 8px;
|
||||||
|
padding: 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-locked {
|
||||||
|
max-width: 520px;
|
||||||
|
margin: 48px auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-create-form {
|
||||||
|
display: grid;
|
||||||
|
gap: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-create-form input,
|
||||||
|
.admin-create-form textarea {
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-list-heading {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-message {
|
||||||
|
margin: 12px 0;
|
||||||
|
padding: 10px 12px;
|
||||||
|
border-radius: 6px;
|
||||||
|
background: #ecfdf5;
|
||||||
|
color: #047857;
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-message.error {
|
||||||
|
background: #fef2f2;
|
||||||
|
color: #b91c1c;
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-video-list {
|
||||||
|
display: grid;
|
||||||
|
gap: 10px;
|
||||||
|
margin-top: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-video-item {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 12px;
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: 8px;
|
||||||
|
padding: 12px;
|
||||||
|
background: var(--bg);
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-video-item h3 {
|
||||||
|
margin: 0 0 6px;
|
||||||
|
font-size: 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-video-meta,
|
||||||
|
.admin-video-subtitles {
|
||||||
|
margin: 0;
|
||||||
|
color: var(--muted);
|
||||||
|
font-size: 13px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.danger-action {
|
||||||
|
border: 1px solid #fecaca;
|
||||||
|
background: #fff1f2;
|
||||||
|
color: #be123c;
|
||||||
|
border-radius: 6px;
|
||||||
|
padding: 8px 12px;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
|
||||||
|
.primary-link,
|
||||||
|
.secondary-action {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
min-height: 36px;
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: 6px;
|
||||||
|
padding: 0 12px;
|
||||||
|
color: var(--text);
|
||||||
|
text-decoration: none;
|
||||||
|
background: var(--surface);
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 900px) {
|
||||||
|
.admin-shell {
|
||||||
|
grid-template-columns: 1fr;
|
||||||
|
padding: 12px;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
- [ ] **Step 3: Run syntax smoke checks**
|
||||||
|
|
||||||
|
Run:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
node --check app.js
|
||||||
|
node --check admin.js
|
||||||
|
```
|
||||||
|
|
||||||
|
Expected: both pass with no output.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Task 5: Document And Verify
|
||||||
|
|
||||||
|
**Files:**
|
||||||
|
- Modify: `F:\ooo\speaking-practice-local\README.md`
|
||||||
|
|
||||||
|
- [ ] **Step 1: Update README**
|
||||||
|
|
||||||
|
Add this section:
|
||||||
|
|
||||||
|
````markdown
|
||||||
|
## Admin Page
|
||||||
|
|
||||||
|
Content management is handled on a separate local admin page:
|
||||||
|
|
||||||
|
```text
|
||||||
|
http://127.0.0.1:8000/admin.html
|
||||||
|
```
|
||||||
|
|
||||||
|
In this prototype, an admin is any local user whose email contains `admin`.
|
||||||
|
After logging in as an admin on the study page, a small `管理` button appears
|
||||||
|
beside the `素材` heading. The admin page supports adding and deleting
|
||||||
|
materials. Editing and subtitle replacement are planned for later.
|
||||||
|
```
|
||||||
|
````
|
||||||
|
|
||||||
|
- [ ] **Step 2: Run static checks**
|
||||||
|
|
||||||
|
Run:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
python -m py_compile backend\main.py backend\db.py
|
||||||
|
node --check app.js
|
||||||
|
node --check admin.js
|
||||||
|
```
|
||||||
|
|
||||||
|
Expected: no output, exit code 0.
|
||||||
|
|
||||||
|
- [ ] **Step 3: Start the dev server**
|
||||||
|
|
||||||
|
Run:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
python -m uvicorn backend.main:app --reload --host 127.0.0.1 --port 8000
|
||||||
|
```
|
||||||
|
|
||||||
|
Expected output includes `Uvicorn running on http://127.0.0.1:8000`.
|
||||||
|
|
||||||
|
- [ ] **Step 4: Verify backend delete endpoint**
|
||||||
|
|
||||||
|
Create a temporary URL video through the API, then delete it:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
$created = curl.exe -s -X POST http://127.0.0.1:8000/api/videos `
|
||||||
|
-F "title=Delete Smoke Test" `
|
||||||
|
-F "video_url=https://example.com/delete-smoke.mp4" | ConvertFrom-Json
|
||||||
|
|
||||||
|
Invoke-RestMethod -Method Delete "http://127.0.0.1:8000/api/videos/$($created.id)"
|
||||||
|
```
|
||||||
|
|
||||||
|
Expected delete response:
|
||||||
|
|
||||||
|
```text
|
||||||
|
ok deletedVideoId warnings
|
||||||
|
-- -------------- --------
|
||||||
|
True <id> {}
|
||||||
|
```
|
||||||
|
|
||||||
|
- [ ] **Step 5: Verify pages**
|
||||||
|
|
||||||
|
Open:
|
||||||
|
|
||||||
|
```text
|
||||||
|
http://127.0.0.1:8000
|
||||||
|
http://127.0.0.1:8000/admin.html
|
||||||
|
http://127.0.0.1:8000/docs
|
||||||
|
```
|
||||||
|
|
||||||
|
Expected:
|
||||||
|
|
||||||
|
- Normal user does not see the `管理` button beside `素材`.
|
||||||
|
- Admin user sees the `管理` button.
|
||||||
|
- `admin.html` shows locked state when not logged in as admin.
|
||||||
|
- `admin.html` shows add form and material list when logged in as admin.
|
||||||
|
- `/docs` includes `DELETE /api/videos/{video_id}`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Self-Review
|
||||||
|
|
||||||
|
Spec coverage:
|
||||||
|
|
||||||
|
- Dedicated admin page: Task 3.
|
||||||
|
- Admin-only study-page entry: Task 2.
|
||||||
|
- Remove embedded admin dock: Task 2.
|
||||||
|
- Add material from admin page: Task 3.
|
||||||
|
- Delete material from admin page: Tasks 1 and 3.
|
||||||
|
- Safe local file deletion: Task 1.
|
||||||
|
- Documentation and verification: Task 5.
|
||||||
|
|
||||||
|
Placeholder scan:
|
||||||
|
|
||||||
|
- No placeholder markers or unspecified implementation steps.
|
||||||
|
|
||||||
|
Type consistency:
|
||||||
|
|
||||||
|
- Backend delete response uses `deletedVideoId` and `warnings`.
|
||||||
|
- Admin frontend reads `video.id`, `video.sourceType`, `video.subtitles`, and the existing backend list shape.
|
||||||
|
- Local admin rule reuses `speaking-lab-state-v1`.
|
||||||
@@ -0,0 +1,808 @@
|
|||||||
|
# Speaking Lab Content Library Implementation Plan
|
||||||
|
|
||||||
|
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||||
|
|
||||||
|
**Goal:** Build the first real content-library slice so admins can add videos with uploaded files or URLs plus English/Chinese subtitles, and the library persists in SQLite after refresh.
|
||||||
|
|
||||||
|
**Architecture:** Keep the current FastAPI + SQLite backend and vanilla frontend. Add a small backend content-library module for database serialization, file validation, and multipart uploads, then switch the frontend video library from browser-only storage to `/api/videos`.
|
||||||
|
|
||||||
|
**Tech Stack:** FastAPI, Python `sqlite3`, vanilla JavaScript, browser `FormData`, local filesystem uploads.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## File Structure
|
||||||
|
|
||||||
|
- Modify `F:\ooo\speaking-practice-local\backend\db.py`: add helpers for video/subtitle inserts and video serialization.
|
||||||
|
- Modify `F:\ooo\speaking-practice-local\backend\main.py`: mount uploads, add `GET /api/videos`, `GET /api/videos/{video_id}`, and `POST /api/videos`.
|
||||||
|
- Modify `F:\ooo\speaking-practice-local\app.js`: load videos from the API, submit admin uploads with `FormData`, normalize backend subtitle content into existing cue objects, and keep localStorage only for user/session state.
|
||||||
|
- Modify `F:\ooo\speaking-practice-local\README.md`: document the new content-library behavior and manual verification.
|
||||||
|
|
||||||
|
The project currently has no test runner or git repository in `speaking-practice-local`. Use focused manual and API verification in this plan. If the project is later initialized as a git repository, commit after each completed task using the suggested commit messages.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Task 1: Add Backend Video Persistence Helpers
|
||||||
|
|
||||||
|
**Files:**
|
||||||
|
- Modify: `F:\ooo\speaking-practice-local\backend\db.py`
|
||||||
|
|
||||||
|
- [ ] **Step 1: Add imports and helper functions**
|
||||||
|
|
||||||
|
Add these imports near the top:
|
||||||
|
|
||||||
|
```python
|
||||||
|
import json
|
||||||
|
```
|
||||||
|
|
||||||
|
Add these helpers after `initialize_database()`:
|
||||||
|
|
||||||
|
```python
|
||||||
|
def parse_tags(tags_text: str | None) -> list[str]:
|
||||||
|
tags = [
|
||||||
|
tag.strip()
|
||||||
|
for tag in (tags_text or "").replace(",", ",").split(",")
|
||||||
|
if tag.strip()
|
||||||
|
]
|
||||||
|
return tags or ["未分类"]
|
||||||
|
|
||||||
|
|
||||||
|
def row_to_video(row: sqlite3.Row, subtitle_rows: list[sqlite3.Row]) -> dict[str, object]:
|
||||||
|
subtitles: dict[str, dict[str, str]] = {}
|
||||||
|
for subtitle in subtitle_rows:
|
||||||
|
subtitles[subtitle["language_code"]] = {
|
||||||
|
"languageName": subtitle["language_name"] or subtitle["language_code"],
|
||||||
|
"format": subtitle["format"],
|
||||||
|
"filePath": subtitle["file_path"],
|
||||||
|
"content": subtitle["content"] or "",
|
||||||
|
}
|
||||||
|
|
||||||
|
try:
|
||||||
|
tags = json.loads(row["tags"] or "[]")
|
||||||
|
except json.JSONDecodeError:
|
||||||
|
tags = parse_tags(row["tags"])
|
||||||
|
|
||||||
|
return {
|
||||||
|
"id": row["id"],
|
||||||
|
"title": row["title"],
|
||||||
|
"speaker": row["speaker"] or "Unknown",
|
||||||
|
"description": row["description"] or "",
|
||||||
|
"tags": tags if isinstance(tags, list) and tags else ["未分类"],
|
||||||
|
"duration": row["duration_seconds"] or 0,
|
||||||
|
"videoUrl": row["video_url"] or "",
|
||||||
|
"sourceType": "url" if str(row["video_url"] or "").startswith(("http://", "https://")) else "local-file",
|
||||||
|
"subtitles": subtitles,
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
- [ ] **Step 2: Add insert and read helpers**
|
||||||
|
|
||||||
|
Add these functions after `row_to_video()`:
|
||||||
|
|
||||||
|
```python
|
||||||
|
def create_video(
|
||||||
|
*,
|
||||||
|
title: str,
|
||||||
|
speaker: str | None,
|
||||||
|
description: str | None,
|
||||||
|
tags: list[str],
|
||||||
|
video_url: str,
|
||||||
|
subtitles: list[dict[str, str]],
|
||||||
|
) -> dict[str, object]:
|
||||||
|
with get_connection() as connection:
|
||||||
|
cursor = connection.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO videos (
|
||||||
|
title, speaker, description, tags, video_url, status
|
||||||
|
)
|
||||||
|
VALUES (?, ?, ?, ?, ?, 'published')
|
||||||
|
""",
|
||||||
|
(
|
||||||
|
title,
|
||||||
|
speaker or "Unknown",
|
||||||
|
description or "",
|
||||||
|
json.dumps(tags, ensure_ascii=False),
|
||||||
|
video_url,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
video_id = int(cursor.lastrowid)
|
||||||
|
|
||||||
|
for subtitle in subtitles:
|
||||||
|
connection.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO subtitles (
|
||||||
|
video_id, language_code, language_name, format, file_path, content
|
||||||
|
)
|
||||||
|
VALUES (?, ?, ?, ?, ?, ?)
|
||||||
|
""",
|
||||||
|
(
|
||||||
|
video_id,
|
||||||
|
subtitle["language_code"],
|
||||||
|
subtitle["language_name"],
|
||||||
|
subtitle["format"],
|
||||||
|
subtitle["file_path"],
|
||||||
|
subtitle["content"],
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
video = get_video(video_id)
|
||||||
|
if video is None:
|
||||||
|
raise RuntimeError("Created video could not be loaded")
|
||||||
|
return video
|
||||||
|
|
||||||
|
|
||||||
|
def list_videos() -> list[dict[str, object]]:
|
||||||
|
with get_connection() as connection:
|
||||||
|
video_rows = connection.execute(
|
||||||
|
"""
|
||||||
|
SELECT *
|
||||||
|
FROM videos
|
||||||
|
WHERE status = 'published'
|
||||||
|
ORDER BY created_at DESC, id DESC
|
||||||
|
"""
|
||||||
|
).fetchall()
|
||||||
|
subtitle_rows = connection.execute(
|
||||||
|
"""
|
||||||
|
SELECT *
|
||||||
|
FROM subtitles
|
||||||
|
ORDER BY id ASC
|
||||||
|
"""
|
||||||
|
).fetchall()
|
||||||
|
|
||||||
|
subtitles_by_video: dict[int, list[sqlite3.Row]] = {}
|
||||||
|
for subtitle in subtitle_rows:
|
||||||
|
subtitles_by_video.setdefault(int(subtitle["video_id"]), []).append(subtitle)
|
||||||
|
|
||||||
|
return [
|
||||||
|
row_to_video(row, subtitles_by_video.get(int(row["id"]), []))
|
||||||
|
for row in video_rows
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def get_video(video_id: int) -> dict[str, object] | None:
|
||||||
|
with get_connection() as connection:
|
||||||
|
row = connection.execute(
|
||||||
|
"""
|
||||||
|
SELECT *
|
||||||
|
FROM videos
|
||||||
|
WHERE id = ? AND status = 'published'
|
||||||
|
""",
|
||||||
|
(video_id,),
|
||||||
|
).fetchone()
|
||||||
|
if row is None:
|
||||||
|
return None
|
||||||
|
|
||||||
|
subtitle_rows = connection.execute(
|
||||||
|
"""
|
||||||
|
SELECT *
|
||||||
|
FROM subtitles
|
||||||
|
WHERE video_id = ?
|
||||||
|
ORDER BY id ASC
|
||||||
|
""",
|
||||||
|
(video_id,),
|
||||||
|
).fetchall()
|
||||||
|
|
||||||
|
return row_to_video(row, subtitle_rows)
|
||||||
|
```
|
||||||
|
|
||||||
|
- [ ] **Step 3: Run a syntax check**
|
||||||
|
|
||||||
|
Run:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
python -m py_compile backend\db.py
|
||||||
|
```
|
||||||
|
|
||||||
|
Expected: command exits with no output.
|
||||||
|
|
||||||
|
Suggested commit if this directory is later made a git repo:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git add backend/db.py
|
||||||
|
git commit -m "backend: add video persistence helpers"
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Task 2: Add Video Library API Endpoints
|
||||||
|
|
||||||
|
**Files:**
|
||||||
|
- Modify: `F:\ooo\speaking-practice-local\backend\main.py`
|
||||||
|
|
||||||
|
- [ ] **Step 1: Add FastAPI imports**
|
||||||
|
|
||||||
|
Replace the current FastAPI import block with:
|
||||||
|
|
||||||
|
```python
|
||||||
|
from pathlib import Path
|
||||||
|
from uuid import uuid4
|
||||||
|
|
||||||
|
from fastapi import FastAPI, File, Form, HTTPException, UploadFile
|
||||||
|
from fastapi.responses import FileResponse
|
||||||
|
from fastapi.staticfiles import StaticFiles
|
||||||
|
|
||||||
|
from .db import (
|
||||||
|
DATABASE_PATH,
|
||||||
|
create_video,
|
||||||
|
initialize_database,
|
||||||
|
list_videos,
|
||||||
|
parse_tags,
|
||||||
|
table_names,
|
||||||
|
get_video,
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
- [ ] **Step 2: Add upload validation constants and helpers**
|
||||||
|
|
||||||
|
Add this after `UPLOADS_DIR = PROJECT_DIR / "uploads"`:
|
||||||
|
|
||||||
|
```python
|
||||||
|
VIDEO_EXTENSIONS = {".mp4", ".webm", ".mov", ".m4v"}
|
||||||
|
SUBTITLE_EXTENSIONS = {".srt", ".vtt"}
|
||||||
|
|
||||||
|
|
||||||
|
def extension_for_upload(upload: UploadFile) -> str:
|
||||||
|
return Path(upload.filename or "").suffix.lower()
|
||||||
|
|
||||||
|
|
||||||
|
def safe_upload_name(upload: UploadFile) -> str:
|
||||||
|
extension = extension_for_upload(upload)
|
||||||
|
return f"{uuid4().hex}{extension}"
|
||||||
|
|
||||||
|
|
||||||
|
async def save_upload(upload: UploadFile, target_dir: Path) -> tuple[str, str]:
|
||||||
|
target_dir.mkdir(parents=True, exist_ok=True)
|
||||||
|
filename = safe_upload_name(upload)
|
||||||
|
target_path = target_dir / filename
|
||||||
|
content = await upload.read()
|
||||||
|
try:
|
||||||
|
target_path.write_bytes(content)
|
||||||
|
except OSError as exc:
|
||||||
|
raise HTTPException(status_code=500, detail="保存文件失败,请重试") from exc
|
||||||
|
return filename, content.decode("utf-8-sig", errors="replace")
|
||||||
|
|
||||||
|
|
||||||
|
async def save_binary_upload(upload: UploadFile, target_dir: Path) -> str:
|
||||||
|
target_dir.mkdir(parents=True, exist_ok=True)
|
||||||
|
filename = safe_upload_name(upload)
|
||||||
|
target_path = target_dir / filename
|
||||||
|
content = await upload.read()
|
||||||
|
try:
|
||||||
|
target_path.write_bytes(content)
|
||||||
|
except OSError as exc:
|
||||||
|
raise HTTPException(status_code=500, detail="保存文件失败,请重试") from exc
|
||||||
|
return filename
|
||||||
|
```
|
||||||
|
|
||||||
|
- [ ] **Step 3: Mount uploaded files**
|
||||||
|
|
||||||
|
Add this after the `on_startup()` function:
|
||||||
|
|
||||||
|
```python
|
||||||
|
app.mount("/uploads", StaticFiles(directory=UPLOADS_DIR), name="uploads")
|
||||||
|
```
|
||||||
|
|
||||||
|
Leave the existing final `app.mount("/", StaticFiles(directory=PROJECT_DIR), name="static")` at the bottom so `/uploads/...` is matched before the root static mount.
|
||||||
|
|
||||||
|
- [ ] **Step 4: Add list and detail endpoints**
|
||||||
|
|
||||||
|
Add this after `health_check()`:
|
||||||
|
|
||||||
|
```python
|
||||||
|
@app.get("/api/videos")
|
||||||
|
def api_list_videos() -> list[dict[str, object]]:
|
||||||
|
return list_videos()
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/api/videos/{video_id}")
|
||||||
|
def api_get_video(video_id: int) -> dict[str, object]:
|
||||||
|
video = get_video(video_id)
|
||||||
|
if video is None:
|
||||||
|
raise HTTPException(status_code=404, detail="视频不存在")
|
||||||
|
return video
|
||||||
|
```
|
||||||
|
|
||||||
|
- [ ] **Step 5: Add create endpoint**
|
||||||
|
|
||||||
|
Add this after `api_get_video()`:
|
||||||
|
|
||||||
|
```python
|
||||||
|
@app.post("/api/videos")
|
||||||
|
async def api_create_video(
|
||||||
|
title: str = Form(...),
|
||||||
|
speaker: str = Form(""),
|
||||||
|
description: str = Form(""),
|
||||||
|
tags: str = Form(""),
|
||||||
|
video_url: str = Form(""),
|
||||||
|
video_file: UploadFile | None = File(None),
|
||||||
|
subtitle_en: UploadFile | None = File(None),
|
||||||
|
subtitle_zh: UploadFile | None = File(None),
|
||||||
|
) -> dict[str, object]:
|
||||||
|
clean_title = title.strip()
|
||||||
|
if not clean_title:
|
||||||
|
raise HTTPException(status_code=400, detail="标题不能为空")
|
||||||
|
|
||||||
|
clean_video_url = video_url.strip()
|
||||||
|
if video_file is None and not clean_video_url:
|
||||||
|
raise HTTPException(status_code=400, detail="请上传视频文件或填写视频地址")
|
||||||
|
|
||||||
|
final_video_url = clean_video_url
|
||||||
|
if video_file is not None:
|
||||||
|
if extension_for_upload(video_file) not in VIDEO_EXTENSIONS:
|
||||||
|
raise HTTPException(status_code=400, detail="视频文件格式不支持")
|
||||||
|
video_filename = await save_binary_upload(video_file, UPLOADS_DIR / "videos")
|
||||||
|
final_video_url = f"/uploads/videos/{video_filename}"
|
||||||
|
|
||||||
|
subtitles: list[dict[str, str]] = []
|
||||||
|
for upload, language_code, language_name in (
|
||||||
|
(subtitle_en, "en", "English"),
|
||||||
|
(subtitle_zh, "zh", "中文"),
|
||||||
|
):
|
||||||
|
if upload is None:
|
||||||
|
continue
|
||||||
|
extension = extension_for_upload(upload)
|
||||||
|
if extension not in SUBTITLE_EXTENSIONS:
|
||||||
|
raise HTTPException(status_code=400, detail="字幕只支持 .srt 或 .vtt")
|
||||||
|
subtitle_filename, subtitle_text = await save_upload(upload, UPLOADS_DIR / "subtitles")
|
||||||
|
subtitles.append(
|
||||||
|
{
|
||||||
|
"language_code": language_code,
|
||||||
|
"language_name": language_name,
|
||||||
|
"format": extension.removeprefix("."),
|
||||||
|
"file_path": f"/uploads/subtitles/{subtitle_filename}",
|
||||||
|
"content": subtitle_text,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
return create_video(
|
||||||
|
title=clean_title,
|
||||||
|
speaker=speaker.strip(),
|
||||||
|
description=description.strip(),
|
||||||
|
tags=parse_tags(tags),
|
||||||
|
video_url=final_video_url,
|
||||||
|
subtitles=subtitles,
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
- [ ] **Step 6: Run a syntax check**
|
||||||
|
|
||||||
|
Run:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
python -m py_compile backend\main.py backend\db.py
|
||||||
|
```
|
||||||
|
|
||||||
|
Expected: command exits with no output.
|
||||||
|
|
||||||
|
- [ ] **Step 7: Verify the API imports**
|
||||||
|
|
||||||
|
Run:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
python -c "from backend.main import app; print(app.title)"
|
||||||
|
```
|
||||||
|
|
||||||
|
Expected output:
|
||||||
|
|
||||||
|
```text
|
||||||
|
Speaking Lab API
|
||||||
|
```
|
||||||
|
|
||||||
|
Suggested commit if this directory is later made a git repo:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git add backend/main.py backend/db.py
|
||||||
|
git commit -m "backend: add content library api"
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Task 3: Switch Frontend Library Loading to the API
|
||||||
|
|
||||||
|
**Files:**
|
||||||
|
- Modify: `F:\ooo\speaking-practice-local\app.js`
|
||||||
|
|
||||||
|
- [ ] **Step 1: Add API helper functions**
|
||||||
|
|
||||||
|
Add this after the `let hlsInstance = null;` line:
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
async function apiRequest(path, options = {}) {
|
||||||
|
const response = await fetch(path, options);
|
||||||
|
if (!response.ok) {
|
||||||
|
let message = "请求失败,请重试。";
|
||||||
|
try {
|
||||||
|
const payload = await response.json();
|
||||||
|
message = payload.detail || message;
|
||||||
|
} catch {
|
||||||
|
message = response.statusText || message;
|
||||||
|
}
|
||||||
|
throw new Error(message);
|
||||||
|
}
|
||||||
|
return response.json();
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeVideoFromApi(video) {
|
||||||
|
const subtitles = {};
|
||||||
|
Object.entries(video.subtitles || {}).forEach(([code, subtitle]) => {
|
||||||
|
subtitles[code] = {
|
||||||
|
languageName: subtitle.languageName || code,
|
||||||
|
format: subtitle.format || "",
|
||||||
|
filePath: subtitle.filePath || "",
|
||||||
|
content: subtitle.content || "",
|
||||||
|
cues: parseSubtitle(subtitle.content || ""),
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
id: video.id,
|
||||||
|
title: video.title || "Untitled",
|
||||||
|
speaker: video.speaker || "Unknown",
|
||||||
|
description: video.description || "",
|
||||||
|
tags: Array.isArray(video.tags) && video.tags.length ? video.tags : ["未分类"],
|
||||||
|
duration: video.duration || 0,
|
||||||
|
videoUrl: video.videoUrl || "",
|
||||||
|
sourceType: video.sourceType || "url",
|
||||||
|
subtitles,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
- [ ] **Step 2: Replace startup calls**
|
||||||
|
|
||||||
|
Replace:
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
hydrate();
|
||||||
|
bindEvents();
|
||||||
|
renderAll();
|
||||||
|
selectVideo(activeVideoId);
|
||||||
|
```
|
||||||
|
|
||||||
|
with:
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
bindEvents();
|
||||||
|
initializeApp();
|
||||||
|
```
|
||||||
|
|
||||||
|
- [ ] **Step 3: Replace `hydrate()` with API startup loading**
|
||||||
|
|
||||||
|
Replace the entire `hydrate()` function with:
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
async function initializeApp() {
|
||||||
|
try {
|
||||||
|
const videos = await apiRequest("/api/videos");
|
||||||
|
state.videos = videos.map(normalizeVideoFromApi);
|
||||||
|
if (!state.videos.length) {
|
||||||
|
state.videos = sampleVideos;
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error(error);
|
||||||
|
state.videos = sampleVideos;
|
||||||
|
els.videoList.innerHTML = `<div class="empty-state">后端视频库加载失败,当前显示示例素材。</div>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!getVideo(activeVideoId)) {
|
||||||
|
activeVideoId = state.videos[0]?.id || null;
|
||||||
|
}
|
||||||
|
|
||||||
|
renderAll();
|
||||||
|
if (activeVideoId) selectVideo(activeVideoId);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
- [ ] **Step 4: Keep video library out of localStorage**
|
||||||
|
|
||||||
|
Replace `saveState()` with:
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
function saveState() {
|
||||||
|
const persistable = {
|
||||||
|
users: state.users,
|
||||||
|
currentUserId: state.currentUserId,
|
||||||
|
activeVideoId: state.activeVideoId,
|
||||||
|
};
|
||||||
|
localStorage.setItem(STORAGE_KEY, JSON.stringify(persistable));
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Replace the `loadState()` return object so `videos` is always empty on load:
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
function loadState() {
|
||||||
|
try {
|
||||||
|
const saved = JSON.parse(localStorage.getItem(STORAGE_KEY) || "{}");
|
||||||
|
return {
|
||||||
|
users: Array.isArray(saved.users) ? saved.users : [],
|
||||||
|
currentUserId: saved.currentUserId || null,
|
||||||
|
videos: [],
|
||||||
|
activeVideoId: saved.activeVideoId || null,
|
||||||
|
};
|
||||||
|
} catch {
|
||||||
|
return { users: [], currentUserId: null, videos: [], activeVideoId: null };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
- [ ] **Step 5: Run a quick static syntax check**
|
||||||
|
|
||||||
|
Run:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
node --check app.js
|
||||||
|
```
|
||||||
|
|
||||||
|
Expected output:
|
||||||
|
|
||||||
|
```text
|
||||||
|
```
|
||||||
|
|
||||||
|
The expected output is empty; the command should exit with code 0.
|
||||||
|
|
||||||
|
Suggested commit if this directory is later made a git repo:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git add app.js
|
||||||
|
git commit -m "frontend: load videos from api"
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Task 4: Submit Admin Video Adds to the Backend
|
||||||
|
|
||||||
|
**Files:**
|
||||||
|
- Modify: `F:\ooo\speaking-practice-local\app.js`
|
||||||
|
|
||||||
|
- [ ] **Step 1: Replace `addVideoFromAdmin()`**
|
||||||
|
|
||||||
|
Replace the full `addVideoFromAdmin(event)` function with:
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
async function addVideoFromAdmin(event) {
|
||||||
|
event.preventDefault();
|
||||||
|
if (getCurrentUser()?.role !== "admin") return;
|
||||||
|
|
||||||
|
const title = els.adminTitle.value.trim();
|
||||||
|
if (!title) {
|
||||||
|
alert("标题不能为空");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const submitButton = els.adminForm.querySelector('button[type="submit"]');
|
||||||
|
const previousText = submitButton.textContent;
|
||||||
|
submitButton.disabled = true;
|
||||||
|
submitButton.textContent = "正在添加...";
|
||||||
|
|
||||||
|
const formData = new FormData();
|
||||||
|
formData.append("title", title);
|
||||||
|
formData.append("speaker", els.adminSpeaker.value.trim());
|
||||||
|
formData.append("description", els.adminDescription.value.trim());
|
||||||
|
formData.append("tags", els.adminTags.value.trim());
|
||||||
|
formData.append("video_url", els.adminVideoUrl.value.trim());
|
||||||
|
|
||||||
|
const videoFile = els.adminVideoFile.files?.[0];
|
||||||
|
const enFile = els.adminSubtitleEn.files?.[0];
|
||||||
|
const zhFile = els.adminSubtitleZh.files?.[0];
|
||||||
|
if (videoFile) formData.append("video_file", videoFile);
|
||||||
|
if (enFile) formData.append("subtitle_en", enFile);
|
||||||
|
if (zhFile) formData.append("subtitle_zh", zhFile);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const created = normalizeVideoFromApi(await apiRequest("/api/videos", {
|
||||||
|
method: "POST",
|
||||||
|
body: formData,
|
||||||
|
}));
|
||||||
|
state.videos = [created, ...state.videos.filter((video) => String(video.id) !== String(created.id))];
|
||||||
|
els.adminForm.reset();
|
||||||
|
renderLibrary();
|
||||||
|
selectVideo(created.id);
|
||||||
|
} catch (error) {
|
||||||
|
alert(error.message || "添加视频失败,请重试。");
|
||||||
|
} finally {
|
||||||
|
submitButton.disabled = false;
|
||||||
|
submitButton.textContent = previousText;
|
||||||
|
renderAdminAccess();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
- [ ] **Step 2: Guard current-video editing for API-backed videos**
|
||||||
|
|
||||||
|
Replace `updateCurrentVideoInfo()` with:
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
function updateCurrentVideoInfo() {
|
||||||
|
alert("第一版内容库暂不支持网页编辑。请重新添加一条新视频。");
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
- [ ] **Step 3: Verify admin form controls recover after submit**
|
||||||
|
|
||||||
|
After Step 1, keep the existing `renderAdminAccess()` function unchanged:
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
[...els.adminForm.elements].forEach((element) => {
|
||||||
|
element.disabled = !isAdmin;
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
Manual check after implementation:
|
||||||
|
|
||||||
|
- Log in with an admin email.
|
||||||
|
- Submit the admin form with an intentionally invalid request, such as no video file and no video URL.
|
||||||
|
- Confirm an error appears.
|
||||||
|
- Confirm the submit button text returns to `添加到视频库`.
|
||||||
|
- Confirm the admin form inputs are enabled again.
|
||||||
|
|
||||||
|
- [ ] **Step 4: Run a quick static syntax check**
|
||||||
|
|
||||||
|
Run:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
node --check app.js
|
||||||
|
```
|
||||||
|
|
||||||
|
Expected: command exits with no output.
|
||||||
|
|
||||||
|
Suggested commit if this directory is later made a git repo:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git add app.js
|
||||||
|
git commit -m "frontend: submit admin videos to backend"
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Task 5: Document and Manually Verify the Content Library
|
||||||
|
|
||||||
|
**Files:**
|
||||||
|
- Modify: `F:\ooo\speaking-practice-local\README.md`
|
||||||
|
|
||||||
|
- [ ] **Step 1: Add content-library notes to README**
|
||||||
|
|
||||||
|
Append this section to the README:
|
||||||
|
|
||||||
|
```markdown
|
||||||
|
## Content Library
|
||||||
|
|
||||||
|
The admin form now saves videos and subtitles through the FastAPI backend.
|
||||||
|
|
||||||
|
Supported first-version flow:
|
||||||
|
|
||||||
|
- Log in with an email containing `admin`.
|
||||||
|
- Add a title, speaker, description, and comma-separated tags.
|
||||||
|
- Choose either a local video file or a video/HLS URL.
|
||||||
|
- Optionally upload English and Chinese `.srt` / `.vtt` subtitle files.
|
||||||
|
- Refresh the browser and confirm the added video remains in the library.
|
||||||
|
|
||||||
|
Uploaded files are stored locally:
|
||||||
|
|
||||||
|
- Videos: `uploads/videos/`
|
||||||
|
- Subtitles: `uploads/subtitles/`
|
||||||
|
|
||||||
|
Metadata is stored in SQLite:
|
||||||
|
|
||||||
|
- `backend/speaking_lab.sqlite`
|
||||||
|
|
||||||
|
This phase does not include web editing, deletion, real authentication, learning progress sync, or server deployment.
|
||||||
|
```
|
||||||
|
|
||||||
|
- [ ] **Step 2: Start the dev server**
|
||||||
|
|
||||||
|
Run:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
python -m uvicorn backend.main:app --reload --host 127.0.0.1 --port 8000
|
||||||
|
```
|
||||||
|
|
||||||
|
Expected output includes:
|
||||||
|
|
||||||
|
```text
|
||||||
|
Uvicorn running on http://127.0.0.1:8000
|
||||||
|
```
|
||||||
|
|
||||||
|
- [ ] **Step 3: Verify health and list endpoints**
|
||||||
|
|
||||||
|
In a second terminal, run:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
Invoke-RestMethod http://127.0.0.1:8000/api/health
|
||||||
|
Invoke-RestMethod http://127.0.0.1:8000/api/videos
|
||||||
|
```
|
||||||
|
|
||||||
|
Expected:
|
||||||
|
|
||||||
|
- `/api/health` returns `ok: True`.
|
||||||
|
- `/api/videos` returns an array. It may be empty.
|
||||||
|
|
||||||
|
- [ ] **Step 4: Verify external URL creation by API**
|
||||||
|
|
||||||
|
Create a small subtitle file for testing:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
@"
|
||||||
|
1
|
||||||
|
00:00:00,000 --> 00:00:02,000
|
||||||
|
Hello from Speaking Lab.
|
||||||
|
"@ | Set-Content -LiteralPath .\test-en.srt -Encoding UTF8
|
||||||
|
```
|
||||||
|
|
||||||
|
Run:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
curl.exe -X POST http://127.0.0.1:8000/api/videos `
|
||||||
|
-F "title=API Smoke Test" `
|
||||||
|
-F "speaker=Tester" `
|
||||||
|
-F "description=Created from curl" `
|
||||||
|
-F "tags=测试,API" `
|
||||||
|
-F "video_url=https://example.com/video.mp4" `
|
||||||
|
-F "subtitle_en=@test-en.srt"
|
||||||
|
```
|
||||||
|
|
||||||
|
Expected response includes:
|
||||||
|
|
||||||
|
```json
|
||||||
|
"title":"API Smoke Test"
|
||||||
|
```
|
||||||
|
|
||||||
|
- [ ] **Step 5: Verify browser flow**
|
||||||
|
|
||||||
|
Open:
|
||||||
|
|
||||||
|
```text
|
||||||
|
http://127.0.0.1:8000
|
||||||
|
```
|
||||||
|
|
||||||
|
Manual expected behavior:
|
||||||
|
|
||||||
|
- Log in with an email containing `admin`.
|
||||||
|
- Submit a video URL with English and Chinese subtitles.
|
||||||
|
- The new video appears at the top of the material list.
|
||||||
|
- Refresh the browser.
|
||||||
|
- The new video remains in the material list.
|
||||||
|
- Selecting the video shows parsed subtitle lines.
|
||||||
|
|
||||||
|
- [ ] **Step 6: Verify API docs**
|
||||||
|
|
||||||
|
Open:
|
||||||
|
|
||||||
|
```text
|
||||||
|
http://127.0.0.1:8000/docs
|
||||||
|
```
|
||||||
|
|
||||||
|
Expected:
|
||||||
|
|
||||||
|
- `GET /api/videos` is visible.
|
||||||
|
- `GET /api/videos/{video_id}` is visible.
|
||||||
|
- `POST /api/videos` is visible.
|
||||||
|
|
||||||
|
Suggested commit if this directory is later made a git repo:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git add README.md
|
||||||
|
git commit -m "docs: document content library flow"
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Self-Review
|
||||||
|
|
||||||
|
Spec coverage:
|
||||||
|
|
||||||
|
- Backend content APIs are covered by Tasks 1 and 2.
|
||||||
|
- Uploaded video and subtitle storage are covered by Task 2.
|
||||||
|
- SQLite video/subtitle persistence is covered by Task 1.
|
||||||
|
- Frontend API loading and admin submit behavior are covered by Tasks 3 and 4.
|
||||||
|
- Manual verification and docs are covered by Task 5.
|
||||||
|
|
||||||
|
Placeholder scan:
|
||||||
|
|
||||||
|
- No placeholder markers or unspecified implementation steps.
|
||||||
|
- The plan intentionally excludes edit/delete, real authentication, learning records, and deployment, matching the approved spec.
|
||||||
|
|
||||||
|
Type consistency:
|
||||||
|
|
||||||
|
- Backend returns camelCase properties expected by the existing frontend: `videoUrl`, `sourceType`, `languageName`, and `filePath`.
|
||||||
|
- Frontend normalizes subtitle `content` into existing `cues`.
|
||||||
|
- Video ids may become numbers from SQLite; comparisons that need robustness use string conversion in the admin insert path.
|
||||||
@@ -0,0 +1,582 @@
|
|||||||
|
# Speaking Lab Learning Progress v1 Implementation Plan
|
||||||
|
|
||||||
|
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||||
|
|
||||||
|
**Goal:** Add local per-user learning progress, continue learning, and per-line practiced/difficult status to the study page.
|
||||||
|
|
||||||
|
**Architecture:** Keep progress entirely in the existing `speaking-lab-state-v1` localStorage state. Add pure progress helper functions to `app.js` and export them for small Node tests, then wire those helpers into the existing study-page render and event flow. No backend schema or admin-page changes are required.
|
||||||
|
|
||||||
|
**Tech Stack:** Vanilla HTML/CSS/JS, browser `localStorage`, Node built-in `assert` for helper tests, existing FastAPI backend unchanged.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## File Structure
|
||||||
|
|
||||||
|
- Modify `F:\ooo\speaking-practice-local\index.html`: add a `继续学习` button beside existing video actions.
|
||||||
|
- Modify `F:\ooo\speaking-practice-local\app.js`: add progress helpers, local state migration, save/restore logic, transcript status controls, and material-list progress summaries.
|
||||||
|
- Modify `F:\ooo\speaking-practice-local\styles.css`: style continue action, transcript status controls, and progress labels.
|
||||||
|
- Add `F:\ooo\speaking-practice-local\tests\progress-helpers.test.mjs`: Node tests for pure helper behavior.
|
||||||
|
- Keep `F:\ooo\speaking-practice-local\backend\main.py` and `backend\db.py` unchanged except for verification.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Task 1: Add Progress Helper Tests
|
||||||
|
|
||||||
|
**Files:**
|
||||||
|
- Add: `F:\ooo\speaking-practice-local\tests\progress-helpers.test.mjs`
|
||||||
|
- Modify: `F:\ooo\speaking-practice-local\app.js`
|
||||||
|
|
||||||
|
- [ ] **Step 1: Create failing helper tests**
|
||||||
|
|
||||||
|
Create `tests\progress-helpers.test.mjs`:
|
||||||
|
|
||||||
|
```js
|
||||||
|
import assert from "node:assert/strict";
|
||||||
|
import {
|
||||||
|
createEmptyProgress,
|
||||||
|
getVideoProgress,
|
||||||
|
toggleLineIndex,
|
||||||
|
calculatePracticeSummary,
|
||||||
|
formatProgressSummary,
|
||||||
|
} from "../app.js";
|
||||||
|
|
||||||
|
const empty = createEmptyProgress();
|
||||||
|
assert.deepEqual(empty, {
|
||||||
|
currentTime: 0,
|
||||||
|
activeLineIndex: 0,
|
||||||
|
practicedLineIndexes: [],
|
||||||
|
difficultLineIndexes: [],
|
||||||
|
updatedAt: "",
|
||||||
|
});
|
||||||
|
|
||||||
|
const user = { progress: {} };
|
||||||
|
const progress = getVideoProgress(user, "video-1");
|
||||||
|
assert.deepEqual(progress.practicedLineIndexes, []);
|
||||||
|
assert.equal(user.progress["video-1"], progress);
|
||||||
|
|
||||||
|
assert.deepEqual(toggleLineIndex([0, 2], 1), [0, 1, 2]);
|
||||||
|
assert.deepEqual(toggleLineIndex([0, 1, 2], 1), [0, 2]);
|
||||||
|
assert.deepEqual(toggleLineIndex([2, 2, 0], 1), [0, 1, 2]);
|
||||||
|
|
||||||
|
assert.deepEqual(calculatePracticeSummary({
|
||||||
|
practicedLineIndexes: [0, 2],
|
||||||
|
}, 5), {
|
||||||
|
practiced: 2,
|
||||||
|
total: 5,
|
||||||
|
percent: 40,
|
||||||
|
});
|
||||||
|
|
||||||
|
assert.equal(formatProgressSummary({
|
||||||
|
practicedLineIndexes: [0, 2],
|
||||||
|
currentTime: 124.4,
|
||||||
|
}, 5), "已练 2/5 · 40%");
|
||||||
|
|
||||||
|
assert.equal(formatProgressSummary({
|
||||||
|
practicedLineIndexes: [],
|
||||||
|
currentTime: 124.4,
|
||||||
|
}, 0), "看到 02:04");
|
||||||
|
|
||||||
|
assert.equal(formatProgressSummary({
|
||||||
|
practicedLineIndexes: [],
|
||||||
|
currentTime: 0,
|
||||||
|
}, 0), "");
|
||||||
|
```
|
||||||
|
|
||||||
|
- [ ] **Step 2: Run test and confirm it fails**
|
||||||
|
|
||||||
|
Run:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
node tests\progress-helpers.test.mjs
|
||||||
|
```
|
||||||
|
|
||||||
|
Expected: fails because `app.js` does not export these helpers yet.
|
||||||
|
|
||||||
|
- [ ] **Step 3: Add test-safe exports and pure helpers in `app.js`**
|
||||||
|
|
||||||
|
Add `const IS_BROWSER = typeof document !== "undefined";` near the top, guard DOM queries with `IS_BROWSER`, and only call `bindEvents()` / `initializeApp()` in the browser.
|
||||||
|
|
||||||
|
Add pure helpers:
|
||||||
|
|
||||||
|
```js
|
||||||
|
function createEmptyProgress() {
|
||||||
|
return {
|
||||||
|
currentTime: 0,
|
||||||
|
activeLineIndex: 0,
|
||||||
|
practicedLineIndexes: [],
|
||||||
|
difficultLineIndexes: [],
|
||||||
|
updatedAt: "",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeProgress(progress) {
|
||||||
|
return {
|
||||||
|
...createEmptyProgress(),
|
||||||
|
...(progress || {}),
|
||||||
|
currentTime: Number(progress?.currentTime) || 0,
|
||||||
|
activeLineIndex: Number.isInteger(progress?.activeLineIndex) ? progress.activeLineIndex : 0,
|
||||||
|
practicedLineIndexes: normalizeIndexList(progress?.practicedLineIndexes),
|
||||||
|
difficultLineIndexes: normalizeIndexList(progress?.difficultLineIndexes),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeIndexList(value) {
|
||||||
|
if (!Array.isArray(value)) return [];
|
||||||
|
return [...new Set(value.map(Number).filter((index) => Number.isInteger(index) && index >= 0))].sort((a, b) => a - b);
|
||||||
|
}
|
||||||
|
|
||||||
|
function ensureUserProgress(user) {
|
||||||
|
if (!user) return null;
|
||||||
|
if (!user.progress || typeof user.progress !== "object") user.progress = {};
|
||||||
|
Object.keys(user.progress).forEach((videoId) => {
|
||||||
|
user.progress[videoId] = normalizeProgress(user.progress[videoId]);
|
||||||
|
});
|
||||||
|
return user.progress;
|
||||||
|
}
|
||||||
|
|
||||||
|
function getVideoProgress(user, videoId) {
|
||||||
|
const progressMap = ensureUserProgress(user);
|
||||||
|
if (!progressMap) return createEmptyProgress();
|
||||||
|
const key = String(videoId);
|
||||||
|
progressMap[key] = normalizeProgress(progressMap[key]);
|
||||||
|
return progressMap[key];
|
||||||
|
}
|
||||||
|
|
||||||
|
function toggleLineIndex(indexes, index) {
|
||||||
|
const normalized = normalizeIndexList(indexes);
|
||||||
|
if (normalized.includes(index)) {
|
||||||
|
return normalized.filter((item) => item !== index);
|
||||||
|
}
|
||||||
|
return normalizeIndexList([...normalized, index]);
|
||||||
|
}
|
||||||
|
|
||||||
|
function calculatePracticeSummary(progress, totalLines) {
|
||||||
|
const total = Math.max(0, Number(totalLines) || 0);
|
||||||
|
const practiced = normalizeIndexList(progress?.practicedLineIndexes).filter((index) => index < total).length;
|
||||||
|
const percent = total ? Math.round((practiced / total) * 100) : 0;
|
||||||
|
return { practiced, total, percent };
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatProgressSummary(progress, totalLines) {
|
||||||
|
const summary = calculatePracticeSummary(progress, totalLines);
|
||||||
|
if (summary.total > 0 && summary.practiced > 0) {
|
||||||
|
return `已练 ${summary.practiced}/${summary.total} · ${summary.percent}%`;
|
||||||
|
}
|
||||||
|
const currentTime = Number(progress?.currentTime) || 0;
|
||||||
|
if (currentTime > 1) return `看到 ${formatTime(currentTime)}`;
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
At the bottom:
|
||||||
|
|
||||||
|
```js
|
||||||
|
if (typeof module !== "undefined" && module.exports) {
|
||||||
|
module.exports = {
|
||||||
|
createEmptyProgress,
|
||||||
|
getVideoProgress,
|
||||||
|
toggleLineIndex,
|
||||||
|
calculatePracticeSummary,
|
||||||
|
formatProgressSummary,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
- [ ] **Step 4: Run helper test**
|
||||||
|
|
||||||
|
Run:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
node tests\progress-helpers.test.mjs
|
||||||
|
```
|
||||||
|
|
||||||
|
Expected: exit code 0.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Task 2: Wire Progress Save And Continue Learning
|
||||||
|
|
||||||
|
**Files:**
|
||||||
|
- Modify: `F:\ooo\speaking-practice-local\index.html`
|
||||||
|
- Modify: `F:\ooo\speaking-practice-local\app.js`
|
||||||
|
|
||||||
|
- [ ] **Step 1: Add continue button to `index.html`**
|
||||||
|
|
||||||
|
Inside `<div class="video-actions">`, before favorite/watch-later:
|
||||||
|
|
||||||
|
```html
|
||||||
|
<button id="continueBtn" type="button" hidden>继续学习</button>
|
||||||
|
```
|
||||||
|
|
||||||
|
- [ ] **Step 2: Add element and state fields in `app.js`**
|
||||||
|
|
||||||
|
Add `continueBtn` to `els`, add:
|
||||||
|
|
||||||
|
```js
|
||||||
|
let lastProgressSaveAt = 0;
|
||||||
|
let pendingRestoreProgress = null;
|
||||||
|
```
|
||||||
|
|
||||||
|
- [ ] **Step 3: Migrate users to include progress**
|
||||||
|
|
||||||
|
In `loadState()`, after reading users, normalize each user:
|
||||||
|
|
||||||
|
```js
|
||||||
|
const users = Array.isArray(saved.users) ? saved.users.map(normalizeUser) : [];
|
||||||
|
```
|
||||||
|
|
||||||
|
Add:
|
||||||
|
|
||||||
|
```js
|
||||||
|
function normalizeUser(user) {
|
||||||
|
const normalized = {
|
||||||
|
...user,
|
||||||
|
favorites: Array.isArray(user.favorites) ? user.favorites : [],
|
||||||
|
watchLater: Array.isArray(user.watchLater) ? user.watchLater : [],
|
||||||
|
};
|
||||||
|
ensureUserProgress(normalized);
|
||||||
|
return normalized;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
When creating a new user, include `progress: {}`.
|
||||||
|
|
||||||
|
- [ ] **Step 4: Save playback progress**
|
||||||
|
|
||||||
|
Add helpers:
|
||||||
|
|
||||||
|
```js
|
||||||
|
function getActiveProgress() {
|
||||||
|
const user = getCurrentUser();
|
||||||
|
if (!user || !activeVideoId) return null;
|
||||||
|
return getVideoProgress(user, activeVideoId);
|
||||||
|
}
|
||||||
|
|
||||||
|
function saveActiveProgress(partial = {}, immediate = false) {
|
||||||
|
const progress = getActiveProgress();
|
||||||
|
if (!progress) return;
|
||||||
|
Object.assign(progress, partial, { updatedAt: new Date().toISOString() });
|
||||||
|
const now = Date.now();
|
||||||
|
if (immediate || now - lastProgressSaveAt > 1500) {
|
||||||
|
lastProgressSaveAt = now;
|
||||||
|
saveState();
|
||||||
|
renderContinueAction();
|
||||||
|
renderLibrary();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Update `handleTimeUpdate()` to call:
|
||||||
|
|
||||||
|
```js
|
||||||
|
saveActiveProgress({ currentTime: els.video.currentTime || 0 });
|
||||||
|
```
|
||||||
|
|
||||||
|
Update `setActiveLine()` to call:
|
||||||
|
|
||||||
|
```js
|
||||||
|
saveActiveProgress({ activeLineIndex: index }, true);
|
||||||
|
```
|
||||||
|
|
||||||
|
Add a `beforeunload` listener in `bindEvents()`:
|
||||||
|
|
||||||
|
```js
|
||||||
|
window.addEventListener("beforeunload", () => {
|
||||||
|
if (els.video && activeVideoId) {
|
||||||
|
saveActiveProgress({ currentTime: els.video.currentTime || 0, activeLineIndex: Math.max(activeLineIndex, 0) }, true);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
- [ ] **Step 5: Restore and continue**
|
||||||
|
|
||||||
|
In `selectVideo(id)`, before `loadVideoSource(video)`, set:
|
||||||
|
|
||||||
|
```js
|
||||||
|
pendingRestoreProgress = getActiveProgress();
|
||||||
|
```
|
||||||
|
|
||||||
|
Add:
|
||||||
|
|
||||||
|
```js
|
||||||
|
function restoreProgressForActiveVideo() {
|
||||||
|
const progress = pendingRestoreProgress;
|
||||||
|
pendingRestoreProgress = null;
|
||||||
|
if (!progress) return;
|
||||||
|
|
||||||
|
const cues = getPrimaryCues();
|
||||||
|
const restoredIndex = cues[progress.activeLineIndex] ? progress.activeLineIndex : 0;
|
||||||
|
if (cues.length) setActiveLine(restoredIndex, true);
|
||||||
|
|
||||||
|
if (progress.currentTime > 1) {
|
||||||
|
els.video.currentTime = progress.currentTime;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function continueLearning() {
|
||||||
|
const progress = getActiveProgress();
|
||||||
|
if (!progress) return;
|
||||||
|
if (progress.currentTime > 1) els.video.currentTime = progress.currentTime;
|
||||||
|
if (progress.activeLineIndex >= 0) jumpToLine(progress.activeLineIndex);
|
||||||
|
els.video.play().catch(() => {});
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderContinueAction() {
|
||||||
|
const progress = getActiveProgress();
|
||||||
|
const hasProgress = Boolean(progress && (progress.currentTime > 1 || progress.activeLineIndex > 0));
|
||||||
|
els.continueBtn.hidden = !hasProgress;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Call `restoreProgressForActiveVideo()` after `renderTranscript()` in `selectVideo()`.
|
||||||
|
|
||||||
|
Bind `continueBtn` click to `continueLearning()`.
|
||||||
|
|
||||||
|
- [ ] **Step 6: Run syntax check**
|
||||||
|
|
||||||
|
Run:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
node --check app.js
|
||||||
|
node tests\progress-helpers.test.mjs
|
||||||
|
```
|
||||||
|
|
||||||
|
Expected: both pass.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Task 3: Add Per-Line Practiced And Difficult Controls
|
||||||
|
|
||||||
|
**Files:**
|
||||||
|
- Modify: `F:\ooo\speaking-practice-local\app.js`
|
||||||
|
- Modify: `F:\ooo\speaking-practice-local\styles.css`
|
||||||
|
|
||||||
|
- [ ] **Step 1: Update transcript line markup**
|
||||||
|
|
||||||
|
In `renderTranscript()`, add a status area inside each `.line-button`:
|
||||||
|
|
||||||
|
```html
|
||||||
|
<div class="line-status" aria-label="练习状态">
|
||||||
|
<button class="line-status-button practiced" type="button" data-status="practiced">已练</button>
|
||||||
|
<button class="line-status-button difficult" type="button" data-status="difficult">难句</button>
|
||||||
|
</div>
|
||||||
|
```
|
||||||
|
|
||||||
|
Use real DOM creation or the existing template, but make sure nested button clicks do not trigger line jump.
|
||||||
|
|
||||||
|
- [ ] **Step 2: Add toggle function**
|
||||||
|
|
||||||
|
Add:
|
||||||
|
|
||||||
|
```js
|
||||||
|
function toggleLineStatus(index, status, event) {
|
||||||
|
event.stopPropagation();
|
||||||
|
const progress = getActiveProgress();
|
||||||
|
if (!progress) {
|
||||||
|
alert("请先登录后再记录学习进度。");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (status === "practiced") {
|
||||||
|
progress.practicedLineIndexes = toggleLineIndex(progress.practicedLineIndexes, index);
|
||||||
|
}
|
||||||
|
if (status === "difficult") {
|
||||||
|
progress.difficultLineIndexes = toggleLineIndex(progress.difficultLineIndexes, index);
|
||||||
|
}
|
||||||
|
progress.updatedAt = new Date().toISOString();
|
||||||
|
saveState();
|
||||||
|
renderTranscript();
|
||||||
|
renderLibrary();
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
- [ ] **Step 3: Apply active classes**
|
||||||
|
|
||||||
|
When rendering each line:
|
||||||
|
|
||||||
|
```js
|
||||||
|
const progress = getActiveProgress();
|
||||||
|
const practiced = progress?.practicedLineIndexes.includes(index);
|
||||||
|
const difficult = progress?.difficultLineIndexes.includes(index);
|
||||||
|
button.classList.toggle("is-practiced", practiced);
|
||||||
|
button.classList.toggle("is-difficult", difficult);
|
||||||
|
```
|
||||||
|
|
||||||
|
Set `.active` on status buttons when their status applies.
|
||||||
|
|
||||||
|
- [ ] **Step 4: Style controls**
|
||||||
|
|
||||||
|
Add CSS:
|
||||||
|
|
||||||
|
```css
|
||||||
|
.line-status {
|
||||||
|
display: flex;
|
||||||
|
gap: 5px;
|
||||||
|
justify-content: flex-end;
|
||||||
|
align-items: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.line-status-button {
|
||||||
|
min-height: 26px;
|
||||||
|
padding: 0 7px;
|
||||||
|
border-radius: 6px;
|
||||||
|
font-size: 12px;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.line-status-button.practiced.active {
|
||||||
|
color: #047857;
|
||||||
|
border-color: #9bd8c0;
|
||||||
|
background: #ecfdf5;
|
||||||
|
}
|
||||||
|
|
||||||
|
.line-status-button.difficult.active {
|
||||||
|
color: #92400e;
|
||||||
|
border-color: #f5c56f;
|
||||||
|
background: #fffbeb;
|
||||||
|
}
|
||||||
|
|
||||||
|
.line-button.is-practiced {
|
||||||
|
border-color: #ccebdd;
|
||||||
|
}
|
||||||
|
|
||||||
|
.line-button.is-difficult {
|
||||||
|
box-shadow: inset 3px 0 0 var(--gold);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
- [ ] **Step 5: Run checks**
|
||||||
|
|
||||||
|
Run:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
node --check app.js
|
||||||
|
node tests\progress-helpers.test.mjs
|
||||||
|
```
|
||||||
|
|
||||||
|
Expected: both pass.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Task 4: Show Material List Progress
|
||||||
|
|
||||||
|
**Files:**
|
||||||
|
- Modify: `F:\ooo\speaking-practice-local\app.js`
|
||||||
|
- Modify: `F:\ooo\speaking-practice-local\styles.css`
|
||||||
|
|
||||||
|
- [ ] **Step 1: Add progress summary to video items**
|
||||||
|
|
||||||
|
In `renderLibrary()`, add another `<small class="video-progress"></small>` inside each `.video-item`.
|
||||||
|
|
||||||
|
Compute:
|
||||||
|
|
||||||
|
```js
|
||||||
|
const progress = getVideoProgress(getCurrentUser(), video.id);
|
||||||
|
const primaryCueCount = getDefaultCueCount(video);
|
||||||
|
const summary = formatProgressSummary(progress, primaryCueCount);
|
||||||
|
```
|
||||||
|
|
||||||
|
Add:
|
||||||
|
|
||||||
|
```js
|
||||||
|
function getDefaultCueCount(video) {
|
||||||
|
if (video?.subtitles?.en?.cues?.length) return video.subtitles.en.cues.length;
|
||||||
|
const firstTrack = Object.values(video?.subtitles || {})[0];
|
||||||
|
return firstTrack?.cues?.length || 0;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Only show the progress node when `summary` is not empty.
|
||||||
|
|
||||||
|
- [ ] **Step 2: Style progress summary**
|
||||||
|
|
||||||
|
Add:
|
||||||
|
|
||||||
|
```css
|
||||||
|
.video-progress {
|
||||||
|
color: var(--brand);
|
||||||
|
font-weight: 700;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
- [ ] **Step 3: Run checks**
|
||||||
|
|
||||||
|
Run:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
node --check app.js
|
||||||
|
node tests\progress-helpers.test.mjs
|
||||||
|
```
|
||||||
|
|
||||||
|
Expected: both pass.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Task 5: Verify End To End
|
||||||
|
|
||||||
|
**Files:**
|
||||||
|
- No new code unless verification reveals a bug.
|
||||||
|
|
||||||
|
- [ ] **Step 1: Run static checks**
|
||||||
|
|
||||||
|
Run:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
python -m py_compile backend\main.py backend\db.py
|
||||||
|
node --check app.js
|
||||||
|
node --check admin.js
|
||||||
|
node tests\progress-helpers.test.mjs
|
||||||
|
node tests\admin-file-input.test.mjs
|
||||||
|
```
|
||||||
|
|
||||||
|
Expected: all exit code 0.
|
||||||
|
|
||||||
|
- [ ] **Step 2: Start or confirm dev server**
|
||||||
|
|
||||||
|
Run if needed:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
python -m uvicorn backend.main:app --reload --host 127.0.0.1 --port 8000
|
||||||
|
```
|
||||||
|
|
||||||
|
Expected: `http://127.0.0.1:8000` responds.
|
||||||
|
|
||||||
|
- [ ] **Step 3: Browser smoke test**
|
||||||
|
|
||||||
|
Open `http://127.0.0.1:8000`.
|
||||||
|
|
||||||
|
Manual checks:
|
||||||
|
|
||||||
|
- Log in as a normal user.
|
||||||
|
- Open a video with subtitles.
|
||||||
|
- Mark one line `已练`.
|
||||||
|
- Mark another line `难句`.
|
||||||
|
- Confirm left material list shows progress.
|
||||||
|
- Refresh the page.
|
||||||
|
- Confirm progress and line statuses remain.
|
||||||
|
- Click `继续学习` and confirm it jumps to saved progress.
|
||||||
|
- Log in as another user and confirm progress is separate.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Self-Review
|
||||||
|
|
||||||
|
Spec coverage:
|
||||||
|
|
||||||
|
- Save last playback time: Task 2.
|
||||||
|
- Save active subtitle line: Task 2.
|
||||||
|
- Continue learning action: Task 2.
|
||||||
|
- Per-line practiced/difficult controls: Task 3.
|
||||||
|
- Material list progress: Task 4.
|
||||||
|
- LocalStorage-only persistence: Task 2.
|
||||||
|
- Tests for helpers: Task 1 and Task 5.
|
||||||
|
|
||||||
|
Placeholder scan:
|
||||||
|
|
||||||
|
- No placeholder markers remain.
|
||||||
|
- All implementation steps include exact files and commands.
|
||||||
|
|
||||||
|
Type consistency:
|
||||||
|
|
||||||
|
- Progress fields consistently use `currentTime`, `activeLineIndex`, `practicedLineIndexes`, `difficultLineIndexes`, and `updatedAt`.
|
||||||
|
- Video IDs are normalized with `String(videoId)`.
|
||||||
@@ -0,0 +1,775 @@
|
|||||||
|
# Speaking Lab DeepSeek Subtitle AI Implementation Plan
|
||||||
|
|
||||||
|
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||||
|
|
||||||
|
**Goal:** Add a beginner-friendly DeepSeek-powered admin workflow that cleans English subtitles and generates matching Chinese subtitles.
|
||||||
|
|
||||||
|
**Architecture:** Keep subtitle parsing/cleaning local and deterministic, and use DeepSeek only for translation/text JSON generation. Add a small backend provider boundary so future audio-based ASR timestamp calibration can be added without rewriting the admin UI.
|
||||||
|
|
||||||
|
**Tech Stack:** FastAPI, SQLite, vanilla JavaScript admin page, Python stdlib/httpx if available, Node-based frontend tests.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## File Structure
|
||||||
|
|
||||||
|
- Create `backend/ai_config.py`: environment parsing and AI status helpers.
|
||||||
|
- Create `backend/subtitle_tools.py`: VTT/SRT parsing, duplicate removal, and VTT building.
|
||||||
|
- Create `backend/deepseek_client.py`: DeepSeek chat API client.
|
||||||
|
- Create `backend/subtitle_ai.py`: workflow orchestration.
|
||||||
|
- Modify `backend/main.py`: add AI status/test/process endpoints.
|
||||||
|
- Modify `backend/db.py`: add helper to update/upsert subtitle content for one video.
|
||||||
|
- Modify `admin.html`: add AI subtitle panel.
|
||||||
|
- Modify `admin.js`: call new endpoints and display status/report.
|
||||||
|
- Modify `styles.css`: style the compact admin AI panel.
|
||||||
|
- Add Python tests under `tests/`.
|
||||||
|
- Add Node/admin tests if frontend helper logic is extracted.
|
||||||
|
|
||||||
|
### Task 1: Local Subtitle Tools
|
||||||
|
|
||||||
|
**Files:**
|
||||||
|
- Create: `backend/subtitle_tools.py`
|
||||||
|
- Test: `tests/subtitle_tools_test.py`
|
||||||
|
|
||||||
|
- [ ] **Step 1: Write the failing test**
|
||||||
|
|
||||||
|
```python
|
||||||
|
from backend.subtitle_tools import build_vtt, clean_english_subtitle
|
||||||
|
|
||||||
|
|
||||||
|
def test_clean_english_subtitle_removes_empty_and_duplicate_cues():
|
||||||
|
raw = """WEBVTT
|
||||||
|
|
||||||
|
00:00:00.000 --> 00:00:00.001
|
||||||
|
|
||||||
|
00:00:00.872 --> 00:00:04.959
|
||||||
|
My first job as an investor
|
||||||
|
was when I was 24 years old,
|
||||||
|
|
||||||
|
00:00:00.872 --> 00:00:04.959
|
||||||
|
My first job as an investor
|
||||||
|
was when I was 24 years old,
|
||||||
|
"""
|
||||||
|
|
||||||
|
result = clean_english_subtitle(raw)
|
||||||
|
|
||||||
|
assert result.original_count == 3
|
||||||
|
assert result.cleaned_count == 1
|
||||||
|
assert result.duplicate_count == 1
|
||||||
|
assert result.empty_count == 1
|
||||||
|
assert result.cues[0].start == "00:00:00.872"
|
||||||
|
assert result.cues[0].end == "00:00:04.959"
|
||||||
|
assert result.cues[0].text == "My first job as an investor\nwas when I was 24 years old,"
|
||||||
|
|
||||||
|
|
||||||
|
def test_build_vtt_outputs_numbered_blocks():
|
||||||
|
result = build_vtt([
|
||||||
|
{
|
||||||
|
"start": "00:00:00.872",
|
||||||
|
"end": "00:00:04.959",
|
||||||
|
"text": "My first job as an investor",
|
||||||
|
}
|
||||||
|
])
|
||||||
|
|
||||||
|
assert result == "WEBVTT\n\n1\n00:00:00.872 --> 00:00:04.959\nMy first job as an investor\n"
|
||||||
|
```
|
||||||
|
|
||||||
|
- [ ] **Step 2: Run test to verify it fails**
|
||||||
|
|
||||||
|
Run: `python tests\subtitle_tools_test.py`
|
||||||
|
|
||||||
|
Expected: FAIL with `ModuleNotFoundError` or missing function.
|
||||||
|
|
||||||
|
- [ ] **Step 3: Implement subtitle tools**
|
||||||
|
|
||||||
|
Create `backend/subtitle_tools.py` with:
|
||||||
|
|
||||||
|
```python
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from dataclasses import dataclass
|
||||||
|
import re
|
||||||
|
|
||||||
|
|
||||||
|
TIME_RE = re.compile(
|
||||||
|
r"(?P<start>\d{1,2}:\d{2}:\d{2}[\.,]\d{3})\s*-->\s*(?P<end>\d{1,2}:\d{2}:\d{2}[\.,]\d{3})"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class SubtitleCue:
|
||||||
|
start: str
|
||||||
|
end: str
|
||||||
|
text: str
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class CleanSubtitleResult:
|
||||||
|
cues: list[SubtitleCue]
|
||||||
|
original_count: int
|
||||||
|
cleaned_count: int
|
||||||
|
duplicate_count: int
|
||||||
|
empty_count: int
|
||||||
|
|
||||||
|
|
||||||
|
def normalize_time(value: str) -> str:
|
||||||
|
return value.replace(",", ".")
|
||||||
|
|
||||||
|
|
||||||
|
def has_visible_text(rows: list[str]) -> bool:
|
||||||
|
text = "".join(rows).replace(" ", "").replace("\u00a0", "").strip()
|
||||||
|
return bool(text)
|
||||||
|
|
||||||
|
|
||||||
|
def parse_subtitle(content: str) -> list[SubtitleCue]:
|
||||||
|
cues: list[SubtitleCue] = []
|
||||||
|
current_time: tuple[str, str] | None = None
|
||||||
|
text_rows: list[str] = []
|
||||||
|
|
||||||
|
def flush() -> None:
|
||||||
|
nonlocal current_time, text_rows
|
||||||
|
if current_time and text_rows:
|
||||||
|
cues.append(SubtitleCue(current_time[0], current_time[1], "\n".join(text_rows).strip()))
|
||||||
|
current_time = None
|
||||||
|
text_rows = []
|
||||||
|
|
||||||
|
for raw_line in str(content or "").replace("\r", "").replace("\ufeff", "").split("\n"):
|
||||||
|
row = raw_line.strip()
|
||||||
|
if not row:
|
||||||
|
flush()
|
||||||
|
continue
|
||||||
|
if row.upper().startswith("WEBVTT") or row.isdigit():
|
||||||
|
continue
|
||||||
|
match = TIME_RE.search(row)
|
||||||
|
if match:
|
||||||
|
flush()
|
||||||
|
current_time = (normalize_time(match.group("start")), normalize_time(match.group("end")))
|
||||||
|
continue
|
||||||
|
if current_time:
|
||||||
|
text_rows.append(row)
|
||||||
|
|
||||||
|
flush()
|
||||||
|
return cues
|
||||||
|
|
||||||
|
|
||||||
|
def clean_english_subtitle(content: str) -> CleanSubtitleResult:
|
||||||
|
parsed = parse_subtitle(content)
|
||||||
|
cleaned: list[SubtitleCue] = []
|
||||||
|
seen: set[tuple[str, str, str]] = set()
|
||||||
|
duplicate_count = 0
|
||||||
|
empty_count = 0
|
||||||
|
|
||||||
|
for cue in parsed:
|
||||||
|
rows = cue.text.splitlines()
|
||||||
|
if not has_visible_text(rows):
|
||||||
|
empty_count += 1
|
||||||
|
continue
|
||||||
|
key = (cue.start, cue.end, cue.text.strip())
|
||||||
|
if key in seen:
|
||||||
|
duplicate_count += 1
|
||||||
|
continue
|
||||||
|
seen.add(key)
|
||||||
|
cleaned.append(cue)
|
||||||
|
|
||||||
|
return CleanSubtitleResult(
|
||||||
|
cues=cleaned,
|
||||||
|
original_count=len(parsed),
|
||||||
|
cleaned_count=len(cleaned),
|
||||||
|
duplicate_count=duplicate_count,
|
||||||
|
empty_count=empty_count,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def build_vtt(cues: list[SubtitleCue] | list[dict[str, str]]) -> str:
|
||||||
|
blocks: list[str] = []
|
||||||
|
for index, cue in enumerate(cues, 1):
|
||||||
|
start = cue.start if isinstance(cue, SubtitleCue) else cue["start"]
|
||||||
|
end = cue.end if isinstance(cue, SubtitleCue) else cue["end"]
|
||||||
|
text = cue.text if isinstance(cue, SubtitleCue) else cue["text"]
|
||||||
|
blocks.append(f"{index}\n{start} --> {end}\n{text.strip()}")
|
||||||
|
return "WEBVTT\n\n" + "\n\n".join(blocks).strip() + "\n"
|
||||||
|
```
|
||||||
|
|
||||||
|
- [ ] **Step 4: Run test to verify it passes**
|
||||||
|
|
||||||
|
Run: `python tests\subtitle_tools_test.py`
|
||||||
|
|
||||||
|
Expected: PASS with exit code 0.
|
||||||
|
|
||||||
|
### Task 2: AI Config and DeepSeek Client
|
||||||
|
|
||||||
|
**Files:**
|
||||||
|
- Create: `backend/ai_config.py`
|
||||||
|
- Create: `backend/deepseek_client.py`
|
||||||
|
- Test: `tests/ai_config_test.py`
|
||||||
|
|
||||||
|
- [ ] **Step 1: Write failing config test**
|
||||||
|
|
||||||
|
```python
|
||||||
|
import os
|
||||||
|
|
||||||
|
from backend.ai_config import get_ai_status, load_deepseek_config
|
||||||
|
|
||||||
|
|
||||||
|
def test_ai_status_reports_missing_key(monkeypatch):
|
||||||
|
monkeypatch.delenv("DEEPSEEK_API_KEY", raising=False)
|
||||||
|
|
||||||
|
status = get_ai_status()
|
||||||
|
|
||||||
|
assert status["configured"] is False
|
||||||
|
assert "DEEPSEEK_API_KEY" in status["message"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_load_deepseek_config_uses_defaults(monkeypatch):
|
||||||
|
monkeypatch.setenv("DEEPSEEK_API_KEY", "test-key")
|
||||||
|
monkeypatch.delenv("DEEPSEEK_BASE_URL", raising=False)
|
||||||
|
monkeypatch.delenv("DEEPSEEK_MODEL", raising=False)
|
||||||
|
|
||||||
|
config = load_deepseek_config()
|
||||||
|
|
||||||
|
assert config.api_key == "test-key"
|
||||||
|
assert config.base_url == "https://api.deepseek.com"
|
||||||
|
assert config.model == "deepseek-chat"
|
||||||
|
```
|
||||||
|
|
||||||
|
- [ ] **Step 2: Run test to verify it fails**
|
||||||
|
|
||||||
|
Run: `python tests\ai_config_test.py`
|
||||||
|
|
||||||
|
Expected: FAIL with missing module.
|
||||||
|
|
||||||
|
- [ ] **Step 3: Implement config and client**
|
||||||
|
|
||||||
|
Create `backend/ai_config.py`:
|
||||||
|
|
||||||
|
```python
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from dataclasses import dataclass
|
||||||
|
import os
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class DeepSeekConfig:
|
||||||
|
api_key: str
|
||||||
|
base_url: str
|
||||||
|
model: str
|
||||||
|
|
||||||
|
|
||||||
|
def load_deepseek_config() -> DeepSeekConfig:
|
||||||
|
return DeepSeekConfig(
|
||||||
|
api_key=os.getenv("DEEPSEEK_API_KEY", "").strip(),
|
||||||
|
base_url=os.getenv("DEEPSEEK_BASE_URL", "https://api.deepseek.com").strip().rstrip("/"),
|
||||||
|
model=os.getenv("DEEPSEEK_MODEL", "deepseek-chat").strip(),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def get_ai_status() -> dict[str, object]:
|
||||||
|
config = load_deepseek_config()
|
||||||
|
if not config.api_key:
|
||||||
|
return {
|
||||||
|
"configured": False,
|
||||||
|
"provider": "deepseek",
|
||||||
|
"model": config.model,
|
||||||
|
"message": "未配置 DEEPSEEK_API_KEY,请在 .env 或环境变量中填写。",
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
"configured": True,
|
||||||
|
"provider": "deepseek",
|
||||||
|
"model": config.model,
|
||||||
|
"message": "DeepSeek API 已配置。",
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Create `backend/deepseek_client.py`:
|
||||||
|
|
||||||
|
```python
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import urllib.error
|
||||||
|
import urllib.request
|
||||||
|
|
||||||
|
from .ai_config import DeepSeekConfig
|
||||||
|
|
||||||
|
|
||||||
|
class DeepSeekError(RuntimeError):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class DeepSeekClient:
|
||||||
|
def __init__(self, config: DeepSeekConfig, timeout_seconds: int = 60):
|
||||||
|
self.config = config
|
||||||
|
self.timeout_seconds = timeout_seconds
|
||||||
|
|
||||||
|
def chat_json(self, system_prompt: str, user_payload: dict[str, object]) -> dict[str, object]:
|
||||||
|
if not self.config.api_key:
|
||||||
|
raise DeepSeekError("未配置 DEEPSEEK_API_KEY。")
|
||||||
|
|
||||||
|
body = json.dumps({
|
||||||
|
"model": self.config.model,
|
||||||
|
"messages": [
|
||||||
|
{"role": "system", "content": system_prompt},
|
||||||
|
{"role": "user", "content": json.dumps(user_payload, ensure_ascii=False)},
|
||||||
|
],
|
||||||
|
"response_format": {"type": "json_object"},
|
||||||
|
}).encode("utf-8")
|
||||||
|
request = urllib.request.Request(
|
||||||
|
f"{self.config.base_url}/chat/completions",
|
||||||
|
data=body,
|
||||||
|
headers={
|
||||||
|
"Authorization": f"Bearer {self.config.api_key}",
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
},
|
||||||
|
method="POST",
|
||||||
|
)
|
||||||
|
|
||||||
|
try:
|
||||||
|
with urllib.request.urlopen(request, timeout=self.timeout_seconds) as response:
|
||||||
|
payload = json.loads(response.read().decode("utf-8"))
|
||||||
|
except urllib.error.HTTPError as error:
|
||||||
|
detail = error.read().decode("utf-8", errors="replace")
|
||||||
|
raise DeepSeekError(f"DeepSeek 请求失败:{error.code} {detail}") from error
|
||||||
|
except Exception as error:
|
||||||
|
raise DeepSeekError(f"DeepSeek 请求失败:{error}") from error
|
||||||
|
|
||||||
|
content = payload.get("choices", [{}])[0].get("message", {}).get("content", "")
|
||||||
|
try:
|
||||||
|
return json.loads(content)
|
||||||
|
except json.JSONDecodeError as error:
|
||||||
|
raise DeepSeekError("DeepSeek 返回内容不是有效 JSON。") from error
|
||||||
|
```
|
||||||
|
|
||||||
|
- [ ] **Step 4: Run config test**
|
||||||
|
|
||||||
|
Run: `python tests\ai_config_test.py`
|
||||||
|
|
||||||
|
Expected: PASS with exit code 0.
|
||||||
|
|
||||||
|
### Task 3: Subtitle AI Orchestrator
|
||||||
|
|
||||||
|
**Files:**
|
||||||
|
- Create: `backend/subtitle_ai.py`
|
||||||
|
- Test: `tests/subtitle_ai_test.py`
|
||||||
|
|
||||||
|
- [ ] **Step 1: Write failing orchestration test**
|
||||||
|
|
||||||
|
```python
|
||||||
|
from backend.subtitle_ai import process_subtitles_with_ai
|
||||||
|
|
||||||
|
|
||||||
|
class FakeClient:
|
||||||
|
def chat_json(self, system_prompt, user_payload):
|
||||||
|
return {
|
||||||
|
"translations": [
|
||||||
|
{"index": 1, "zh": "我第一次做投资人是在 24 岁。"}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def test_process_subtitles_with_ai_returns_clean_en_and_zh_vtt():
|
||||||
|
raw = """WEBVTT
|
||||||
|
|
||||||
|
00:00:00.872 --> 00:00:04.959
|
||||||
|
My first job as an investor was when I was 24 years old,
|
||||||
|
|
||||||
|
00:00:00.872 --> 00:00:04.959
|
||||||
|
My first job as an investor was when I was 24 years old,
|
||||||
|
"""
|
||||||
|
|
||||||
|
result = process_subtitles_with_ai(raw, FakeClient())
|
||||||
|
|
||||||
|
assert "My first job as an investor" in result["subtitle_en_content"]
|
||||||
|
assert "我第一次做投资人是在 24 岁。" in result["subtitle_zh_content"]
|
||||||
|
assert result["report"]["duplicate_count"] == 1
|
||||||
|
assert result["report"]["translation_count"] == 1
|
||||||
|
```
|
||||||
|
|
||||||
|
- [ ] **Step 2: Run test to verify it fails**
|
||||||
|
|
||||||
|
Run: `python tests\subtitle_ai_test.py`
|
||||||
|
|
||||||
|
Expected: FAIL with missing module.
|
||||||
|
|
||||||
|
- [ ] **Step 3: Implement orchestrator**
|
||||||
|
|
||||||
|
Create `backend/subtitle_ai.py`:
|
||||||
|
|
||||||
|
```python
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from .subtitle_tools import build_vtt, clean_english_subtitle
|
||||||
|
|
||||||
|
|
||||||
|
TRANSLATION_SYSTEM_PROMPT = """
|
||||||
|
你是英语学习产品的字幕翻译助手。输入是按顺序排列的英文字幕。
|
||||||
|
请只返回 JSON,格式为 {"translations":[{"index":1,"zh":"中文翻译"}]}。
|
||||||
|
要求:中文自然,适合英语学习;不要增删字幕条数;不要解释。
|
||||||
|
""".strip()
|
||||||
|
|
||||||
|
|
||||||
|
def process_subtitles_with_ai(english_content: str, client) -> dict[str, object]:
|
||||||
|
cleaned = clean_english_subtitle(english_content)
|
||||||
|
if not cleaned.cues:
|
||||||
|
raise ValueError("英文字幕为空,无法处理。")
|
||||||
|
|
||||||
|
payload = {
|
||||||
|
"cues": [
|
||||||
|
{"index": index, "text": cue.text}
|
||||||
|
for index, cue in enumerate(cleaned.cues, 1)
|
||||||
|
]
|
||||||
|
}
|
||||||
|
response = client.chat_json(TRANSLATION_SYSTEM_PROMPT, payload)
|
||||||
|
translations = response.get("translations")
|
||||||
|
if not isinstance(translations, list):
|
||||||
|
raise ValueError("AI 返回结果缺少 translations。")
|
||||||
|
if len(translations) != len(cleaned.cues):
|
||||||
|
raise ValueError("AI 返回的翻译条数和英文字幕条数不一致。")
|
||||||
|
|
||||||
|
zh_cues = []
|
||||||
|
for cue, translation in zip(cleaned.cues, translations):
|
||||||
|
zh_text = str(translation.get("zh", "")).strip()
|
||||||
|
if not zh_text:
|
||||||
|
raise ValueError("AI 返回了空翻译。")
|
||||||
|
zh_cues.append({"start": cue.start, "end": cue.end, "text": zh_text})
|
||||||
|
|
||||||
|
return {
|
||||||
|
"subtitle_en_content": build_vtt(cleaned.cues),
|
||||||
|
"subtitle_zh_content": build_vtt(zh_cues),
|
||||||
|
"report": {
|
||||||
|
"original_count": cleaned.original_count,
|
||||||
|
"cleaned_count": cleaned.cleaned_count,
|
||||||
|
"duplicate_count": cleaned.duplicate_count,
|
||||||
|
"empty_count": cleaned.empty_count,
|
||||||
|
"translation_count": len(zh_cues),
|
||||||
|
"timestamp_calibrated": False,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
- [ ] **Step 4: Run test**
|
||||||
|
|
||||||
|
Run: `python tests\subtitle_ai_test.py`
|
||||||
|
|
||||||
|
Expected: PASS with exit code 0.
|
||||||
|
|
||||||
|
### Task 4: Backend API Endpoints
|
||||||
|
|
||||||
|
**Files:**
|
||||||
|
- Modify: `backend/db.py`
|
||||||
|
- Modify: `backend/main.py`
|
||||||
|
- Test: `tests/ai_api_test.py`
|
||||||
|
|
||||||
|
- [ ] **Step 1: Add DB helper test**
|
||||||
|
|
||||||
|
Use an existing SQLite test pattern if present. If no test harness exists, test through the API in Step 2 instead.
|
||||||
|
|
||||||
|
- [ ] **Step 2: Implement DB helper**
|
||||||
|
|
||||||
|
In `backend/db.py`, add:
|
||||||
|
|
||||||
|
```python
|
||||||
|
def upsert_video_subtitle(
|
||||||
|
video_id: int,
|
||||||
|
*,
|
||||||
|
language_code: str,
|
||||||
|
language_name: str,
|
||||||
|
format: str,
|
||||||
|
file_path: str,
|
||||||
|
content: str,
|
||||||
|
) -> None:
|
||||||
|
with get_connection() as connection:
|
||||||
|
connection.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO subtitles (
|
||||||
|
video_id, language_code, language_name, format, file_path, content
|
||||||
|
)
|
||||||
|
VALUES (?, ?, ?, ?, ?, ?)
|
||||||
|
ON CONFLICT(video_id, language_code) DO UPDATE SET
|
||||||
|
language_name = excluded.language_name,
|
||||||
|
format = excluded.format,
|
||||||
|
file_path = excluded.file_path,
|
||||||
|
content = excluded.content,
|
||||||
|
updated_at = CURRENT_TIMESTAMP
|
||||||
|
""",
|
||||||
|
(
|
||||||
|
video_id,
|
||||||
|
language_code,
|
||||||
|
repair_mojibake_text(language_name),
|
||||||
|
format,
|
||||||
|
file_path,
|
||||||
|
repair_mojibake_text(content),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
- [ ] **Step 3: Add API endpoints**
|
||||||
|
|
||||||
|
In `backend/main.py`, import:
|
||||||
|
|
||||||
|
```python
|
||||||
|
from .ai_config import get_ai_status, load_deepseek_config
|
||||||
|
from .deepseek_client import DeepSeekClient, DeepSeekError
|
||||||
|
from .subtitle_ai import process_subtitles_with_ai
|
||||||
|
from .db import upsert_video_subtitle
|
||||||
|
```
|
||||||
|
|
||||||
|
Add endpoints before static mounts:
|
||||||
|
|
||||||
|
```python
|
||||||
|
@app.get("/api/ai/status")
|
||||||
|
def api_ai_status() -> dict[str, object]:
|
||||||
|
return get_ai_status()
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/api/ai/test")
|
||||||
|
def api_ai_test() -> dict[str, object]:
|
||||||
|
status = get_ai_status()
|
||||||
|
if not status["configured"]:
|
||||||
|
raise HTTPException(status_code=400, detail=status["message"])
|
||||||
|
return {"ok": True, "message": "DeepSeek API 配置已读取。"}
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/api/videos/{video_id}/ai/subtitles")
|
||||||
|
def api_process_video_subtitles(video_id: int) -> dict[str, object]:
|
||||||
|
status = get_ai_status()
|
||||||
|
if not status["configured"]:
|
||||||
|
raise HTTPException(status_code=400, detail=status["message"])
|
||||||
|
|
||||||
|
video = get_video(video_id)
|
||||||
|
if video is None:
|
||||||
|
raise HTTPException(status_code=404, detail="视频不存在")
|
||||||
|
english = video.get("subtitles", {}).get("en", {}).get("content", "")
|
||||||
|
if not english:
|
||||||
|
raise HTTPException(status_code=400, detail="请先上传英文字幕。")
|
||||||
|
|
||||||
|
try:
|
||||||
|
result = process_subtitles_with_ai(english, DeepSeekClient(load_deepseek_config()))
|
||||||
|
except (DeepSeekError, ValueError) as error:
|
||||||
|
raise HTTPException(status_code=400, detail=str(error)) from error
|
||||||
|
|
||||||
|
upsert_video_subtitle(
|
||||||
|
video_id,
|
||||||
|
language_code="en",
|
||||||
|
language_name="English",
|
||||||
|
format="vtt",
|
||||||
|
file_path=video.get("subtitles", {}).get("en", {}).get("filePath", ""),
|
||||||
|
content=str(result["subtitle_en_content"]),
|
||||||
|
)
|
||||||
|
upsert_video_subtitle(
|
||||||
|
video_id,
|
||||||
|
language_code="zh",
|
||||||
|
language_name="中文",
|
||||||
|
format="vtt",
|
||||||
|
file_path=video.get("subtitles", {}).get("zh", {}).get("filePath", ""),
|
||||||
|
content=str(result["subtitle_zh_content"]),
|
||||||
|
)
|
||||||
|
|
||||||
|
return {
|
||||||
|
"video": get_video(video_id),
|
||||||
|
"report": result["report"],
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
- [ ] **Step 4: Run backend syntax checks**
|
||||||
|
|
||||||
|
Run: `python -m py_compile backend\main.py backend\db.py backend\ai_config.py backend\deepseek_client.py backend\subtitle_ai.py backend\subtitle_tools.py`
|
||||||
|
|
||||||
|
Expected: PASS with exit code 0.
|
||||||
|
|
||||||
|
### Task 5: Admin UI
|
||||||
|
|
||||||
|
**Files:**
|
||||||
|
- Modify: `admin.html`
|
||||||
|
- Modify: `admin.js`
|
||||||
|
- Modify: `styles.css`
|
||||||
|
|
||||||
|
- [ ] **Step 1: Add AI panel markup**
|
||||||
|
|
||||||
|
In `admin.html`, place near `adminSubtitleEditor`:
|
||||||
|
|
||||||
|
```html
|
||||||
|
<section class="admin-ai-panel">
|
||||||
|
<div>
|
||||||
|
<h3>AI 字幕处理</h3>
|
||||||
|
<p id="aiSubtitleStatus">正在读取 AI 配置...</p>
|
||||||
|
</div>
|
||||||
|
<div class="admin-ai-actions">
|
||||||
|
<button id="testAiBtn" class="secondary-action" type="button">测试 AI 连接</button>
|
||||||
|
<button id="processAiSubtitlesBtn" type="button">AI 修复并翻译字幕</button>
|
||||||
|
</div>
|
||||||
|
<p id="aiSubtitleReport" class="admin-ai-report" hidden></p>
|
||||||
|
</section>
|
||||||
|
```
|
||||||
|
|
||||||
|
- [ ] **Step 2: Wire elements in `admin.js`**
|
||||||
|
|
||||||
|
Add to `els`:
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
aiStatus: IS_BROWSER ? document.querySelector("#aiSubtitleStatus") : null,
|
||||||
|
aiReport: IS_BROWSER ? document.querySelector("#aiSubtitleReport") : null,
|
||||||
|
testAiBtn: IS_BROWSER ? document.querySelector("#testAiBtn") : null,
|
||||||
|
processAiSubtitlesBtn: IS_BROWSER ? document.querySelector("#processAiSubtitlesBtn") : null,
|
||||||
|
```
|
||||||
|
|
||||||
|
In `initializeAdmin()` add:
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
els.testAiBtn?.addEventListener("click", testAiConnection);
|
||||||
|
els.processAiSubtitlesBtn?.addEventListener("click", processAiSubtitles);
|
||||||
|
loadAiStatus();
|
||||||
|
```
|
||||||
|
|
||||||
|
Add functions:
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
async function loadAiStatus() {
|
||||||
|
if (!els.aiStatus) return;
|
||||||
|
try {
|
||||||
|
const status = await apiRequest("/api/ai/status");
|
||||||
|
els.aiStatus.textContent = status.message || "AI 状态未知。";
|
||||||
|
els.processAiSubtitlesBtn.disabled = !status.configured || !editingVideo;
|
||||||
|
} catch (error) {
|
||||||
|
els.aiStatus.textContent = error.message || "AI 状态读取失败。";
|
||||||
|
els.processAiSubtitlesBtn.disabled = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function testAiConnection() {
|
||||||
|
try {
|
||||||
|
const result = await apiRequest("/api/ai/test", { method: "POST" });
|
||||||
|
showMessage(result.message || "AI 连接正常。");
|
||||||
|
await loadAiStatus();
|
||||||
|
} catch (error) {
|
||||||
|
showMessage(error.message || "AI 连接失败。", true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function processAiSubtitles() {
|
||||||
|
if (!editingVideo) {
|
||||||
|
showMessage("请先选择一个素材。", true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
els.processAiSubtitlesBtn.disabled = true;
|
||||||
|
els.processAiSubtitlesBtn.textContent = "AI 处理中...";
|
||||||
|
try {
|
||||||
|
const result = await apiRequest(`/api/videos/${editingVideo.id}/ai/subtitles`, { method: "POST" });
|
||||||
|
const report = result.report || {};
|
||||||
|
els.aiReport.hidden = false;
|
||||||
|
els.aiReport.textContent = `处理完成:删除重复 ${report.duplicate_count || 0} 条,删除空白 ${report.empty_count || 0} 条,生成中文 ${report.translation_count || 0} 条。`;
|
||||||
|
await loadVideos();
|
||||||
|
const updated = videos.find((video) => String(video.id) === String(editingVideo.id));
|
||||||
|
if (updated) startEditingVideo(updated);
|
||||||
|
} catch (error) {
|
||||||
|
showMessage(error.message || "AI 字幕处理失败。", true);
|
||||||
|
} finally {
|
||||||
|
els.processAiSubtitlesBtn.textContent = "AI 修复并翻译字幕";
|
||||||
|
await loadAiStatus();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Call `loadAiStatus()` inside `startEditingVideo()` and `resetFormMode()`.
|
||||||
|
|
||||||
|
- [ ] **Step 3: Add CSS**
|
||||||
|
|
||||||
|
In `styles.css`, add:
|
||||||
|
|
||||||
|
```css
|
||||||
|
.admin-ai-panel {
|
||||||
|
display: grid;
|
||||||
|
gap: 10px;
|
||||||
|
padding: 12px;
|
||||||
|
border: 1px solid var(--line);
|
||||||
|
border-radius: 8px;
|
||||||
|
background: var(--panel-soft);
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-ai-panel h3,
|
||||||
|
.admin-ai-panel p {
|
||||||
|
margin: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-ai-actions {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-ai-report {
|
||||||
|
color: var(--muted);
|
||||||
|
font-size: 13px;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
- [ ] **Step 4: Run frontend checks**
|
||||||
|
|
||||||
|
Run:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
node --check admin.js
|
||||||
|
node --check app.js
|
||||||
|
```
|
||||||
|
|
||||||
|
Expected: PASS with exit code 0.
|
||||||
|
|
||||||
|
### Task 6: Verification
|
||||||
|
|
||||||
|
**Files:**
|
||||||
|
- No new files.
|
||||||
|
|
||||||
|
- [ ] **Step 1: Run Python tests**
|
||||||
|
|
||||||
|
Run:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
python tests\subtitle_tools_test.py
|
||||||
|
python tests\ai_config_test.py
|
||||||
|
python tests\subtitle_ai_test.py
|
||||||
|
python tests\encoding_repair_test.py
|
||||||
|
python -m py_compile backend\main.py backend\db.py
|
||||||
|
```
|
||||||
|
|
||||||
|
Expected: all exit 0.
|
||||||
|
|
||||||
|
- [ ] **Step 2: Run frontend tests**
|
||||||
|
|
||||||
|
Run:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
node --check admin.js
|
||||||
|
node --check app.js
|
||||||
|
node --check home.js
|
||||||
|
node tests\admin-file-input.test.mjs
|
||||||
|
node tests\admin-subtitle-editor.test.mjs
|
||||||
|
node tests\progress-helpers.test.mjs
|
||||||
|
```
|
||||||
|
|
||||||
|
Expected: all exit 0.
|
||||||
|
|
||||||
|
- [ ] **Step 3: Manual local check without API key**
|
||||||
|
|
||||||
|
Start the local server and open `http://127.0.0.1:8000/admin.html`.
|
||||||
|
|
||||||
|
Expected:
|
||||||
|
|
||||||
|
- Admin page loads.
|
||||||
|
- AI status says `未配置 DEEPSEEK_API_KEY`.
|
||||||
|
- Clicking `AI 修复并翻译字幕` does not crash the page.
|
||||||
|
|
||||||
|
- [ ] **Step 4: Manual local check with API key**
|
||||||
|
|
||||||
|
Set environment variable:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
$env:DEEPSEEK_API_KEY="your_key_here"
|
||||||
|
```
|
||||||
|
|
||||||
|
Restart server and open admin page.
|
||||||
|
|
||||||
|
Expected:
|
||||||
|
|
||||||
|
- AI status says DeepSeek is configured.
|
||||||
|
- Processing a material with English subtitles creates a Chinese subtitle track.
|
||||||
|
- Report shows duplicate and translation counts.
|
||||||
|
|
||||||
@@ -0,0 +1,300 @@
|
|||||||
|
# Speaking Lab Focused Learning UI Implementation Plan
|
||||||
|
|
||||||
|
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||||
|
|
||||||
|
**Goal:** Apply a clean English-learning UI direction with icon-led dashboard cards and a more focused study workspace.
|
||||||
|
|
||||||
|
**Architecture:** Keep the upgrade frontend-only. `home.js` adds icon metadata for metric cards, while `styles.css` changes visual treatment for the home dashboard, material cards, study video panel, subtitle prompt, toolbar, and transcript states. No backend, README, or data-model changes are required.
|
||||||
|
|
||||||
|
**Tech Stack:** Vanilla JavaScript, CSS, HTML, existing FastAPI server for browser verification.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Task 1: Add Metric Icon Metadata
|
||||||
|
|
||||||
|
**Files:**
|
||||||
|
- Modify: `F:\ooo\speaking-practice-local\home.js`
|
||||||
|
|
||||||
|
- [ ] **Step 1: Update `getMetricItems(metrics)`**
|
||||||
|
|
||||||
|
Replace each metric object with an `icon` and `tone`:
|
||||||
|
|
||||||
|
```js
|
||||||
|
function getMetricItems(metrics) {
|
||||||
|
return [
|
||||||
|
{ key: "all", label: "当前素材", value: metrics.total, hint: "持续更新中", icon: "::", tone: "blue" },
|
||||||
|
{ key: "studied", label: "已学习", value: metrics.studied, hint: "我的打卡", icon: "✓", tone: "green" },
|
||||||
|
{ key: "unstudied", label: "未学习", value: metrics.unstudied, hint: "未完成", icon: "○", tone: "slate" },
|
||||||
|
{ key: "favorites", label: "已收藏", value: metrics.favorites, hint: "收藏的视频", icon: "♡", tone: "rose" },
|
||||||
|
{ key: "difficult", label: "难句素材", value: metrics.difficult, hint: "重点复习", icon: "!", tone: "amber" },
|
||||||
|
];
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
- [ ] **Step 2: Update metric button markup in `renderDashboard()`**
|
||||||
|
|
||||||
|
Use:
|
||||||
|
|
||||||
|
```js
|
||||||
|
button.className = `home-metric tone-${item.tone}${activeStatus === item.key ? " active" : ""}`;
|
||||||
|
button.dataset.status = item.key;
|
||||||
|
button.innerHTML = `
|
||||||
|
<span class="home-metric-icon" aria-hidden="true">${item.icon}</span>
|
||||||
|
<span class="home-metric-copy">
|
||||||
|
<span class="home-metric-label">${item.label}</span>
|
||||||
|
<small>${item.hint}</small>
|
||||||
|
</span>
|
||||||
|
<strong>${item.value}</strong>
|
||||||
|
`;
|
||||||
|
```
|
||||||
|
|
||||||
|
- [ ] **Step 3: Run syntax check**
|
||||||
|
|
||||||
|
Run:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
node --check home.js
|
||||||
|
```
|
||||||
|
|
||||||
|
Expected: no output.
|
||||||
|
|
||||||
|
## Task 2: Polish Home Dashboard And Cards
|
||||||
|
|
||||||
|
**Files:**
|
||||||
|
- Modify: `F:\ooo\speaking-practice-local\styles.css`
|
||||||
|
|
||||||
|
- [ ] **Step 1: Update root colors**
|
||||||
|
|
||||||
|
Use a calm learning palette:
|
||||||
|
|
||||||
|
```css
|
||||||
|
:root {
|
||||||
|
color-scheme: light;
|
||||||
|
--bg: #f4f7fb;
|
||||||
|
--panel: #ffffff;
|
||||||
|
--panel-soft: #f7fafc;
|
||||||
|
--ink: #172033;
|
||||||
|
--muted: #667085;
|
||||||
|
--line: #dfe6ef;
|
||||||
|
--accent: #0f2742;
|
||||||
|
--brand: #0f766e;
|
||||||
|
--brand-soft: #e4f5f1;
|
||||||
|
--gold: #c98a12;
|
||||||
|
--danger: #b42318;
|
||||||
|
--shadow: 0 12px 30px rgba(25, 37, 59, 0.08);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
- [ ] **Step 2: Replace metric card CSS**
|
||||||
|
|
||||||
|
Update `.home-metric` and related selectors to icon-card layout:
|
||||||
|
|
||||||
|
```css
|
||||||
|
.home-metric {
|
||||||
|
min-height: 76px;
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: 38px minmax(0, 1fr) auto;
|
||||||
|
align-items: center;
|
||||||
|
gap: 10px;
|
||||||
|
padding: 12px;
|
||||||
|
text-align: left;
|
||||||
|
border-radius: 8px;
|
||||||
|
background: var(--panel);
|
||||||
|
box-shadow: var(--shadow);
|
||||||
|
}
|
||||||
|
|
||||||
|
.home-metric-icon {
|
||||||
|
width: 34px;
|
||||||
|
height: 34px;
|
||||||
|
display: grid;
|
||||||
|
place-items: center;
|
||||||
|
border-radius: 10px;
|
||||||
|
font-weight: 900;
|
||||||
|
}
|
||||||
|
|
||||||
|
.home-metric-copy,
|
||||||
|
.home-metric-label {
|
||||||
|
display: block;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.home-metric-label {
|
||||||
|
font-weight: 800;
|
||||||
|
}
|
||||||
|
|
||||||
|
.home-metric small {
|
||||||
|
color: var(--muted);
|
||||||
|
font-size: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.home-metric strong {
|
||||||
|
font-size: 24px;
|
||||||
|
line-height: 1;
|
||||||
|
font-variant-numeric: tabular-nums;
|
||||||
|
}
|
||||||
|
|
||||||
|
.home-metric.tone-blue .home-metric-icon {
|
||||||
|
color: #087ea4;
|
||||||
|
background: #e6f7fb;
|
||||||
|
}
|
||||||
|
|
||||||
|
.home-metric.tone-green .home-metric-icon {
|
||||||
|
color: #047857;
|
||||||
|
background: #e9f9f0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.home-metric.tone-slate .home-metric-icon {
|
||||||
|
color: #475467;
|
||||||
|
background: #eef2f7;
|
||||||
|
}
|
||||||
|
|
||||||
|
.home-metric.tone-rose .home-metric-icon {
|
||||||
|
color: #be123c;
|
||||||
|
background: #fff1f4;
|
||||||
|
}
|
||||||
|
|
||||||
|
.home-metric.tone-amber .home-metric-icon {
|
||||||
|
color: #9a5c00;
|
||||||
|
background: #fff7df;
|
||||||
|
}
|
||||||
|
|
||||||
|
.home-metric.active {
|
||||||
|
border-color: #b9dcd5;
|
||||||
|
background: #f0fbf8;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
- [ ] **Step 3: Lighten card covers**
|
||||||
|
|
||||||
|
Update cover gradients to avoid heavy admin feel:
|
||||||
|
|
||||||
|
```css
|
||||||
|
.home-cover.tone-1 { background: linear-gradient(135deg, #0f766e, #1d6f8f); }
|
||||||
|
.home-cover.tone-2 { background: linear-gradient(135deg, #2563eb, #0f766e); }
|
||||||
|
.home-cover.tone-3 { background: linear-gradient(135deg, #475569, #2563eb); }
|
||||||
|
.home-cover.tone-4 { background: linear-gradient(135deg, #9a5c00, #be6b21); }
|
||||||
|
.home-cover.tone-5 { background: linear-gradient(135deg, #334155, #0f766e); }
|
||||||
|
```
|
||||||
|
|
||||||
|
## Task 3: Polish Study Workspace
|
||||||
|
|
||||||
|
**Files:**
|
||||||
|
- Modify: `F:\ooo\speaking-practice-local\styles.css`
|
||||||
|
|
||||||
|
- [ ] **Step 1: Add focused study styling**
|
||||||
|
|
||||||
|
Update existing study selectors:
|
||||||
|
|
||||||
|
```css
|
||||||
|
.video-panel,
|
||||||
|
.transcript-panel,
|
||||||
|
.lesson-rail {
|
||||||
|
border-color: #dce5ee;
|
||||||
|
}
|
||||||
|
|
||||||
|
.video-frame {
|
||||||
|
background: #0b1220;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tool-row {
|
||||||
|
background: #ffffff;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tool-row button {
|
||||||
|
border-color: #d8e2ec;
|
||||||
|
background: #f8fafc;
|
||||||
|
font-weight: 650;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tool-row button:hover {
|
||||||
|
border-color: #b9dcd5;
|
||||||
|
background: var(--brand-soft);
|
||||||
|
}
|
||||||
|
|
||||||
|
.subtitle-card {
|
||||||
|
min-height: 116px;
|
||||||
|
padding: 18px 28px;
|
||||||
|
background: #f8fbfb;
|
||||||
|
}
|
||||||
|
|
||||||
|
#primarySubtitle {
|
||||||
|
font-size: 22px;
|
||||||
|
letter-spacing: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
#secondarySubtitle {
|
||||||
|
color: #667085;
|
||||||
|
font-size: 15px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.line-button {
|
||||||
|
border-radius: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.line-button.active {
|
||||||
|
background: #f4fbf9;
|
||||||
|
border-color: #b9dcd5;
|
||||||
|
box-shadow: inset 4px 0 0 var(--brand);
|
||||||
|
}
|
||||||
|
|
||||||
|
.line-button.is-practiced {
|
||||||
|
background: #f7fdf9;
|
||||||
|
}
|
||||||
|
|
||||||
|
.line-button.is-difficult {
|
||||||
|
background: #fffaf0;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
- [ ] **Step 2: Confirm mobile styles still exist**
|
||||||
|
|
||||||
|
Run:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
rg -n "@media \\(max-width: 860px\\)|@media \\(max-width: 720px\\)" styles.css
|
||||||
|
```
|
||||||
|
|
||||||
|
Expected: both media blocks still exist.
|
||||||
|
|
||||||
|
## Task 4: Verify
|
||||||
|
|
||||||
|
**Files:**
|
||||||
|
- Verify: `F:\ooo\speaking-practice-local\home.js`
|
||||||
|
- Verify: `F:\ooo\speaking-practice-local\app.js`
|
||||||
|
- Verify: `F:\ooo\speaking-practice-local\admin.js`
|
||||||
|
- Verify: `F:\ooo\speaking-practice-local\styles.css`
|
||||||
|
|
||||||
|
- [ ] **Step 1: Run automated checks**
|
||||||
|
|
||||||
|
Run:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
node --check home.js
|
||||||
|
node --check app.js
|
||||||
|
node --check admin.js
|
||||||
|
python -m py_compile backend\main.py backend\db.py
|
||||||
|
node tests\progress-helpers.test.mjs
|
||||||
|
node tests\admin-file-input.test.mjs
|
||||||
|
```
|
||||||
|
|
||||||
|
Expected: all pass.
|
||||||
|
|
||||||
|
- [ ] **Step 2: Browser check home page**
|
||||||
|
|
||||||
|
Open:
|
||||||
|
|
||||||
|
```text
|
||||||
|
http://127.0.0.1:8000/
|
||||||
|
```
|
||||||
|
|
||||||
|
Confirm metric cards show icons and still filter.
|
||||||
|
|
||||||
|
- [ ] **Step 3: Browser check study page**
|
||||||
|
|
||||||
|
Open:
|
||||||
|
|
||||||
|
```text
|
||||||
|
http://127.0.0.1:8000/study.html
|
||||||
|
```
|
||||||
|
|
||||||
|
Confirm subtitle prompt, toolbar, and transcript feel more like a learning workspace and no text overlaps.
|
||||||
@@ -0,0 +1,762 @@
|
|||||||
|
# Speaking Lab Home Dashboard v1 Implementation Plan
|
||||||
|
|
||||||
|
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||||
|
|
||||||
|
**Goal:** Upgrade the home page into a learning dashboard with overview metrics, status filters, richer material cards, and home-page favorite toggles.
|
||||||
|
|
||||||
|
**Architecture:** Keep the feature entirely in the existing frontend home page. `index.html` owns the dashboard markup, `home.js` owns browser-side metric/filter/card behavior using `/api/videos` plus existing localStorage state, and `styles.css` owns the responsive layout and card styling. No backend, README, or deployment changes are required.
|
||||||
|
|
||||||
|
**Tech Stack:** Vanilla HTML, CSS, JavaScript, FastAPI `/api/videos`, browser `localStorage`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## File Structure
|
||||||
|
|
||||||
|
- Modify `F:\ooo\speaking-practice-local\index.html`: add dashboard overview panel and metric button containers.
|
||||||
|
- Modify `F:\ooo\speaking-practice-local\home.js`: add active status filter, dashboard metrics, personal filter empty states, favorite toggles, and richer card metadata.
|
||||||
|
- Modify `F:\ooo\speaking-practice-local\styles.css`: style the two-column dashboard, metric buttons, upgraded cards, and mobile stacking.
|
||||||
|
- Do not modify `F:\ooo\speaking-practice-local\README.md`.
|
||||||
|
- Do not modify backend files unless verification exposes an unrelated syntax issue.
|
||||||
|
|
||||||
|
## Task 1: Add Home Dashboard Markup
|
||||||
|
|
||||||
|
**Files:**
|
||||||
|
- Modify: `F:\ooo\speaking-practice-local\index.html`
|
||||||
|
|
||||||
|
- [ ] **Step 1: Replace the home main layout**
|
||||||
|
|
||||||
|
Replace the current `<main class="home-shell">...</main>` block with this structure:
|
||||||
|
|
||||||
|
```html
|
||||||
|
<main class="home-shell">
|
||||||
|
<aside class="home-dashboard" aria-label="学习概览">
|
||||||
|
<div class="home-dashboard-title">
|
||||||
|
<span>学习概览</span>
|
||||||
|
<strong id="homeDashboardUser">本地学习</strong>
|
||||||
|
</div>
|
||||||
|
<div id="homeMetricFilters" class="home-metrics"></div>
|
||||||
|
</aside>
|
||||||
|
|
||||||
|
<section class="home-library">
|
||||||
|
<div class="home-heading">
|
||||||
|
<div>
|
||||||
|
<h2>素材库</h2>
|
||||||
|
<p>搜索素材,按分类和学习状态继续练习。</p>
|
||||||
|
</div>
|
||||||
|
<a class="primary-link" href="./study.html">进入学习页</a>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="homeCategoryFilters" class="home-categories"></div>
|
||||||
|
<div id="homeStatus" class="home-status"></div>
|
||||||
|
<div id="homeGrid" class="home-grid"></div>
|
||||||
|
</section>
|
||||||
|
</main>
|
||||||
|
```
|
||||||
|
|
||||||
|
- [ ] **Step 2: Verify the markup has all IDs needed by JavaScript**
|
||||||
|
|
||||||
|
Run:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
rg -n "homeDashboardUser|homeMetricFilters|homeCategoryFilters|homeStatus|homeGrid" index.html
|
||||||
|
```
|
||||||
|
|
||||||
|
Expected: each ID appears exactly once.
|
||||||
|
|
||||||
|
## Task 2: Implement Dashboard Metrics And Filters
|
||||||
|
|
||||||
|
**Files:**
|
||||||
|
- Modify: `F:\ooo\speaking-practice-local\home.js`
|
||||||
|
|
||||||
|
- [ ] **Step 1: Add new DOM references and status state**
|
||||||
|
|
||||||
|
Extend the `els` object with:
|
||||||
|
|
||||||
|
```js
|
||||||
|
dashboardUser: document.querySelector("#homeDashboardUser"),
|
||||||
|
metricFilters: document.querySelector("#homeMetricFilters"),
|
||||||
|
```
|
||||||
|
|
||||||
|
Add this state next to `activeTag`:
|
||||||
|
|
||||||
|
```js
|
||||||
|
let activeStatus = "all";
|
||||||
|
```
|
||||||
|
|
||||||
|
- [ ] **Step 2: Update render flow**
|
||||||
|
|
||||||
|
In `renderHome()`, call `renderDashboard()` before categories are rendered:
|
||||||
|
|
||||||
|
```js
|
||||||
|
function renderHome() {
|
||||||
|
renderDashboard();
|
||||||
|
renderCategories();
|
||||||
|
const filtered = getFilteredVideos();
|
||||||
|
const emptyMessage = getEmptyMessage(filtered);
|
||||||
|
|
||||||
|
els.status.textContent = filtered.length ? `${filtered.length} 个素材` : emptyMessage;
|
||||||
|
els.grid.innerHTML = "";
|
||||||
|
|
||||||
|
if (!filtered.length) return;
|
||||||
|
|
||||||
|
const fragment = document.createDocumentFragment();
|
||||||
|
filtered.forEach((video) => {
|
||||||
|
fragment.appendChild(createVideoCard(video));
|
||||||
|
});
|
||||||
|
els.grid.appendChild(fragment);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
- [ ] **Step 3: Add dashboard rendering helpers**
|
||||||
|
|
||||||
|
Add these functions below `renderCategories()`:
|
||||||
|
|
||||||
|
```js
|
||||||
|
function renderDashboard() {
|
||||||
|
const user = getCurrentUser();
|
||||||
|
const metrics = calculateDashboardMetrics(user);
|
||||||
|
els.dashboardUser.textContent = user ? user.email : "登录后记录进度";
|
||||||
|
els.metricFilters.innerHTML = "";
|
||||||
|
|
||||||
|
getMetricItems(metrics).forEach((item) => {
|
||||||
|
const button = document.createElement("button");
|
||||||
|
button.type = "button";
|
||||||
|
button.className = `home-metric${activeStatus === item.key ? " active" : ""}`;
|
||||||
|
button.dataset.status = item.key;
|
||||||
|
button.innerHTML = `
|
||||||
|
<span>${item.label}</span>
|
||||||
|
<strong>${item.value}</strong>
|
||||||
|
<small>${item.hint}</small>
|
||||||
|
`;
|
||||||
|
button.addEventListener("click", () => {
|
||||||
|
activeStatus = item.key;
|
||||||
|
renderHome();
|
||||||
|
});
|
||||||
|
els.metricFilters.appendChild(button);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function getMetricItems(metrics) {
|
||||||
|
return [
|
||||||
|
{ key: "all", label: "当前素材", value: metrics.total, hint: "可学习内容" },
|
||||||
|
{ key: "studied", label: "已学", value: metrics.studied, hint: "有学习记录" },
|
||||||
|
{ key: "unstudied", label: "未学", value: metrics.unstudied, hint: "还未开始" },
|
||||||
|
{ key: "favorites", label: "已收藏", value: metrics.favorites, hint: "收藏的视频" },
|
||||||
|
{ key: "difficult", label: "难句素材", value: metrics.difficult, hint: "含难句标记" },
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
function calculateDashboardMetrics(user) {
|
||||||
|
const loadedIds = new Set(videos.map((video) => String(video.id)));
|
||||||
|
const studied = videos.filter((video) => hasStudyProgress(user, video.id)).length;
|
||||||
|
const favoriteIds = new Set((user?.favorites || []).map(String));
|
||||||
|
const favorites = [...favoriteIds].filter((id) => loadedIds.has(id)).length;
|
||||||
|
const difficult = videos.filter((video) => getVideoProgress(user, video.id).difficultLineIndexes.length > 0).length;
|
||||||
|
|
||||||
|
return {
|
||||||
|
total: videos.length,
|
||||||
|
studied,
|
||||||
|
unstudied: Math.max(0, videos.length - studied),
|
||||||
|
favorites,
|
||||||
|
difficult,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function hasStudyProgress(user, videoId) {
|
||||||
|
if (!user) return false;
|
||||||
|
const progress = getVideoProgress(user, videoId);
|
||||||
|
return progress.currentTime > 1
|
||||||
|
|| progress.activeLineIndex > 0
|
||||||
|
|| progress.practicedLineIndexes.length > 0;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
- [ ] **Step 4: Extend filtering**
|
||||||
|
|
||||||
|
Replace `getFilteredVideos()` with:
|
||||||
|
|
||||||
|
```js
|
||||||
|
function getFilteredVideos() {
|
||||||
|
const query = els.searchInput.value.trim().toLowerCase();
|
||||||
|
const user = getCurrentUser();
|
||||||
|
|
||||||
|
return videos.filter((video) => {
|
||||||
|
const tags = normalizeTags(video.tags);
|
||||||
|
const matchesTag = activeTag === "全部" || tags.includes(activeTag);
|
||||||
|
const matchesStatus = matchesStatusFilter(video, user);
|
||||||
|
const haystack = [video.title, video.speaker, video.description, tags.join(" ")]
|
||||||
|
.join(" ")
|
||||||
|
.toLowerCase();
|
||||||
|
return matchesTag && matchesStatus && (!query || haystack.includes(query));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function matchesStatusFilter(video, user) {
|
||||||
|
if (activeStatus === "all") return true;
|
||||||
|
if (activeStatus === "studied") return hasStudyProgress(user, video.id);
|
||||||
|
if (activeStatus === "unstudied") return !hasStudyProgress(user, video.id);
|
||||||
|
if (activeStatus === "favorites") return Boolean(user?.favorites.map(String).includes(String(video.id)));
|
||||||
|
if (activeStatus === "difficult") return getVideoProgress(user, video.id).difficultLineIndexes.length > 0;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
- [ ] **Step 5: Add empty-state messaging**
|
||||||
|
|
||||||
|
Add this function below the filtering helpers:
|
||||||
|
|
||||||
|
```js
|
||||||
|
function getEmptyMessage(filtered) {
|
||||||
|
const user = getCurrentUser();
|
||||||
|
const query = els.searchInput.value.trim();
|
||||||
|
|
||||||
|
if (!videos.length) {
|
||||||
|
return isAdmin(user) ? "还没有素材,去后台添加第一个素材。" : "暂无素材。";
|
||||||
|
}
|
||||||
|
if (!user && ["studied", "favorites", "difficult"].includes(activeStatus)) {
|
||||||
|
return "登录后可以查看你的学习记录。";
|
||||||
|
}
|
||||||
|
if (activeStatus === "favorites") return "还没有收藏素材。";
|
||||||
|
if (activeStatus === "difficult") return "还没有标记难句。";
|
||||||
|
if (query || activeTag !== "全部") return "没有匹配的素材。";
|
||||||
|
return filtered.length ? "" : "没有匹配的素材。";
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
- [ ] **Step 6: Syntax check**
|
||||||
|
|
||||||
|
Run:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
node --check home.js
|
||||||
|
```
|
||||||
|
|
||||||
|
Expected: no output and exit code 0.
|
||||||
|
|
||||||
|
## Task 3: Upgrade Material Cards
|
||||||
|
|
||||||
|
**Files:**
|
||||||
|
- Modify: `F:\ooo\speaking-practice-local\home.js`
|
||||||
|
- Modify: `F:\ooo\speaking-practice-local\styles.css`
|
||||||
|
|
||||||
|
- [ ] **Step 1: Replace `createVideoCard(video)`**
|
||||||
|
|
||||||
|
Replace the current function with:
|
||||||
|
|
||||||
|
```js
|
||||||
|
function createVideoCard(video) {
|
||||||
|
const card = document.createElement("article");
|
||||||
|
const user = getCurrentUser();
|
||||||
|
const tags = normalizeTags(video.tags);
|
||||||
|
const subtitleLabel = getSubtitleLabel(video);
|
||||||
|
const totalLines = getDefaultCueCount(video);
|
||||||
|
const progress = getVideoProgress(user, video.id);
|
||||||
|
const summary = calculatePracticeSummary(progress, totalLines);
|
||||||
|
const progressLabel = formatProgressSummary(progress, totalLines);
|
||||||
|
const difficultCount = progress.difficultLineIndexes.filter((index) => index < totalLines || totalLines === 0).length;
|
||||||
|
const coverTone = getCoverTone(video.id);
|
||||||
|
const isFavorite = Boolean(user?.favorites.map(String).includes(String(video.id)));
|
||||||
|
|
||||||
|
card.className = "home-card";
|
||||||
|
card.innerHTML = `
|
||||||
|
<div class="home-cover tone-${coverTone}">
|
||||||
|
<span class="home-cover-badge"></span>
|
||||||
|
<button class="home-favorite" type="button" aria-label="收藏素材"></button>
|
||||||
|
<strong></strong>
|
||||||
|
</div>
|
||||||
|
<a class="home-card-link" href="./study.html?video=${encodeURIComponent(video.id)}">
|
||||||
|
<div class="home-card-body">
|
||||||
|
<h3></h3>
|
||||||
|
<p class="home-card-meta"></p>
|
||||||
|
<div class="home-card-tags"></div>
|
||||||
|
<dl class="home-card-stats">
|
||||||
|
<div>
|
||||||
|
<dt>句子</dt>
|
||||||
|
<dd></dd>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<dt>进度</dt>
|
||||||
|
<dd></dd>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<dt>难句</dt>
|
||||||
|
<dd></dd>
|
||||||
|
</div>
|
||||||
|
</dl>
|
||||||
|
<p class="home-card-subtitles"></p>
|
||||||
|
<p class="home-progress" hidden></p>
|
||||||
|
</div>
|
||||||
|
</a>
|
||||||
|
`;
|
||||||
|
|
||||||
|
card.querySelector(".home-cover-badge").textContent = tags[0] || "素材";
|
||||||
|
card.querySelector(".home-cover strong").textContent = getCoverText(video.title);
|
||||||
|
card.querySelector("h3").textContent = video.title || "Untitled";
|
||||||
|
card.querySelector(".home-card-meta").textContent = video.speaker || "Unknown";
|
||||||
|
card.querySelector(".home-card-tags").append(...tags.map(createTagPill));
|
||||||
|
card.querySelector(".home-card-subtitles").textContent = subtitleLabel;
|
||||||
|
|
||||||
|
const statValues = card.querySelectorAll(".home-card-stats dd");
|
||||||
|
statValues[0].textContent = totalLines ? `${totalLines}` : "-";
|
||||||
|
statValues[1].textContent = totalLines ? `${summary.percent}%` : "未开始";
|
||||||
|
statValues[2].textContent = `${difficultCount}`;
|
||||||
|
|
||||||
|
const favorite = card.querySelector(".home-favorite");
|
||||||
|
favorite.textContent = isFavorite ? "已收藏" : "收藏";
|
||||||
|
favorite.classList.toggle("active", isFavorite);
|
||||||
|
favorite.addEventListener("click", (event) => {
|
||||||
|
event.preventDefault();
|
||||||
|
event.stopPropagation();
|
||||||
|
toggleFavorite(video.id);
|
||||||
|
});
|
||||||
|
|
||||||
|
const progressNode = card.querySelector(".home-progress");
|
||||||
|
progressNode.textContent = progressLabel || "还未开始";
|
||||||
|
progressNode.hidden = false;
|
||||||
|
|
||||||
|
return card;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
- [ ] **Step 2: Add favorite toggle helper**
|
||||||
|
|
||||||
|
Add this function below `loginOrRegister()`:
|
||||||
|
|
||||||
|
```js
|
||||||
|
function toggleFavorite(videoId) {
|
||||||
|
const user = getCurrentUser();
|
||||||
|
if (!user) {
|
||||||
|
alert("请先登录。第一版会自动注册新邮箱。");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const key = String(videoId);
|
||||||
|
const favorites = new Set((user.favorites || []).map(String));
|
||||||
|
if (favorites.has(key)) {
|
||||||
|
favorites.delete(key);
|
||||||
|
} else {
|
||||||
|
favorites.add(key);
|
||||||
|
}
|
||||||
|
|
||||||
|
user.favorites = [...favorites];
|
||||||
|
saveState();
|
||||||
|
renderHome();
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
- [ ] **Step 3: Syntax check**
|
||||||
|
|
||||||
|
Run:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
node --check home.js
|
||||||
|
```
|
||||||
|
|
||||||
|
Expected: no output and exit code 0.
|
||||||
|
|
||||||
|
## Task 4: Style Dashboard And Upgraded Cards
|
||||||
|
|
||||||
|
**Files:**
|
||||||
|
- Modify: `F:\ooo\speaking-practice-local\styles.css`
|
||||||
|
|
||||||
|
- [ ] **Step 1: Replace home layout styles**
|
||||||
|
|
||||||
|
Replace the existing `.home-shell`, `.home-library`, `.home-heading`, `.home-grid`, `.home-card`, `.home-card-link`, `.home-cover`, `.home-card-body`, `.home-card-meta`, `.home-card-subtitles`, `.home-progress`, `.home-card-tags`, and related home card blocks with the updated home section styles below:
|
||||||
|
|
||||||
|
```css
|
||||||
|
.home-shell {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: 260px minmax(0, 1fr);
|
||||||
|
gap: 18px;
|
||||||
|
max-width: 1240px;
|
||||||
|
margin: 0 auto;
|
||||||
|
padding: 20px 24px 40px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.home-dashboard,
|
||||||
|
.home-library {
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.home-dashboard {
|
||||||
|
align-self: start;
|
||||||
|
position: sticky;
|
||||||
|
top: 82px;
|
||||||
|
display: grid;
|
||||||
|
gap: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.home-dashboard-title {
|
||||||
|
padding: 14px;
|
||||||
|
border: 1px solid var(--line);
|
||||||
|
border-radius: 8px;
|
||||||
|
background: var(--panel);
|
||||||
|
box-shadow: var(--shadow);
|
||||||
|
}
|
||||||
|
|
||||||
|
.home-dashboard-title span,
|
||||||
|
.home-dashboard-title strong {
|
||||||
|
display: block;
|
||||||
|
}
|
||||||
|
|
||||||
|
.home-dashboard-title span {
|
||||||
|
color: var(--muted);
|
||||||
|
font-size: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.home-dashboard-title strong {
|
||||||
|
margin-top: 4px;
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
white-space: nowrap;
|
||||||
|
font-size: 15px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.home-metrics {
|
||||||
|
display: grid;
|
||||||
|
gap: 9px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.home-metric {
|
||||||
|
min-height: 72px;
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: minmax(0, 1fr) auto;
|
||||||
|
align-items: center;
|
||||||
|
gap: 4px 10px;
|
||||||
|
padding: 11px 12px;
|
||||||
|
text-align: left;
|
||||||
|
border-radius: 8px;
|
||||||
|
background: var(--panel);
|
||||||
|
box-shadow: var(--shadow);
|
||||||
|
}
|
||||||
|
|
||||||
|
.home-metric span,
|
||||||
|
.home-metric small {
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.home-metric span {
|
||||||
|
font-weight: 700;
|
||||||
|
}
|
||||||
|
|
||||||
|
.home-metric strong {
|
||||||
|
font-size: 24px;
|
||||||
|
line-height: 1;
|
||||||
|
font-variant-numeric: tabular-nums;
|
||||||
|
}
|
||||||
|
|
||||||
|
.home-metric small {
|
||||||
|
grid-column: 1 / -1;
|
||||||
|
color: var(--muted);
|
||||||
|
font-size: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.home-metric.active {
|
||||||
|
color: #fff;
|
||||||
|
border-color: var(--accent);
|
||||||
|
background: var(--accent);
|
||||||
|
}
|
||||||
|
|
||||||
|
.home-metric.active small {
|
||||||
|
color: rgba(255, 255, 255, 0.72);
|
||||||
|
}
|
||||||
|
|
||||||
|
.home-heading {
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: flex-start;
|
||||||
|
gap: 16px;
|
||||||
|
margin-bottom: 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.home-heading h2 {
|
||||||
|
margin: 0;
|
||||||
|
font-size: 24px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.home-heading p {
|
||||||
|
margin: 6px 0 0;
|
||||||
|
color: var(--muted);
|
||||||
|
font-size: 13px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.home-categories {
|
||||||
|
display: flex;
|
||||||
|
gap: 8px;
|
||||||
|
overflow-x: auto;
|
||||||
|
padding: 2px 0 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.home-status {
|
||||||
|
min-height: 22px;
|
||||||
|
color: var(--muted);
|
||||||
|
font-size: 13px;
|
||||||
|
margin-bottom: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.home-grid {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
|
||||||
|
gap: 14px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.home-card {
|
||||||
|
min-width: 0;
|
||||||
|
overflow: hidden;
|
||||||
|
border: 1px solid var(--line);
|
||||||
|
border-radius: 8px;
|
||||||
|
background: var(--panel);
|
||||||
|
box-shadow: var(--shadow);
|
||||||
|
}
|
||||||
|
|
||||||
|
.home-card-link {
|
||||||
|
display: block;
|
||||||
|
color: inherit;
|
||||||
|
text-decoration: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.home-card:hover .home-cover {
|
||||||
|
filter: saturate(1.08);
|
||||||
|
}
|
||||||
|
|
||||||
|
.home-cover {
|
||||||
|
position: relative;
|
||||||
|
min-height: 138px;
|
||||||
|
display: grid;
|
||||||
|
align-content: space-between;
|
||||||
|
padding: 14px;
|
||||||
|
color: #fff;
|
||||||
|
background: #0f766e;
|
||||||
|
}
|
||||||
|
|
||||||
|
.home-favorite {
|
||||||
|
position: absolute;
|
||||||
|
top: 10px;
|
||||||
|
right: 10px;
|
||||||
|
min-height: 28px;
|
||||||
|
border-color: rgba(255, 255, 255, 0.38);
|
||||||
|
color: #fff;
|
||||||
|
background: rgba(17, 24, 39, 0.3);
|
||||||
|
font-size: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.home-favorite:hover,
|
||||||
|
.home-favorite.active {
|
||||||
|
color: #111827;
|
||||||
|
background: #fff;
|
||||||
|
border-color: #fff;
|
||||||
|
}
|
||||||
|
|
||||||
|
.home-cover.tone-1 {
|
||||||
|
background: linear-gradient(135deg, #0f766e, #164e63);
|
||||||
|
}
|
||||||
|
|
||||||
|
.home-cover.tone-2 {
|
||||||
|
background: linear-gradient(135deg, #7c3aed, #0f766e);
|
||||||
|
}
|
||||||
|
|
||||||
|
.home-cover.tone-3 {
|
||||||
|
background: linear-gradient(135deg, #1d4ed8, #4338ca);
|
||||||
|
}
|
||||||
|
|
||||||
|
.home-cover.tone-4 {
|
||||||
|
background: linear-gradient(135deg, #b45309, #be123c);
|
||||||
|
}
|
||||||
|
|
||||||
|
.home-cover.tone-5 {
|
||||||
|
background: linear-gradient(135deg, #334155, #0f766e);
|
||||||
|
}
|
||||||
|
|
||||||
|
.home-cover-badge {
|
||||||
|
width: fit-content;
|
||||||
|
max-width: calc(100% - 86px);
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
white-space: nowrap;
|
||||||
|
border: 1px solid rgba(255, 255, 255, 0.34);
|
||||||
|
border-radius: 999px;
|
||||||
|
padding: 4px 8px;
|
||||||
|
background: rgba(255, 255, 255, 0.14);
|
||||||
|
font-size: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.home-cover strong {
|
||||||
|
font-size: 34px;
|
||||||
|
line-height: 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
.home-card-body {
|
||||||
|
padding: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.home-card-body h3 {
|
||||||
|
margin: 0;
|
||||||
|
font-size: 16px;
|
||||||
|
line-height: 1.35;
|
||||||
|
}
|
||||||
|
|
||||||
|
.home-card-meta,
|
||||||
|
.home-card-subtitles,
|
||||||
|
.home-progress {
|
||||||
|
margin: 6px 0 0;
|
||||||
|
color: var(--muted);
|
||||||
|
font-size: 12px;
|
||||||
|
line-height: 1.4;
|
||||||
|
}
|
||||||
|
|
||||||
|
.home-card-tags {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 6px;
|
||||||
|
margin-top: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.home-card-tags span {
|
||||||
|
border-radius: 999px;
|
||||||
|
padding: 3px 7px;
|
||||||
|
color: #334155;
|
||||||
|
background: #eef2f7;
|
||||||
|
font-size: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.home-card-stats {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(3, minmax(0, 1fr));
|
||||||
|
gap: 6px;
|
||||||
|
margin: 12px 0 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.home-card-stats div {
|
||||||
|
min-width: 0;
|
||||||
|
padding: 8px;
|
||||||
|
border-radius: 7px;
|
||||||
|
background: var(--panel-soft);
|
||||||
|
}
|
||||||
|
|
||||||
|
.home-card-stats dt,
|
||||||
|
.home-card-stats dd {
|
||||||
|
margin: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.home-card-stats dt {
|
||||||
|
color: var(--muted);
|
||||||
|
font-size: 11px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.home-card-stats dd {
|
||||||
|
margin-top: 3px;
|
||||||
|
font-weight: 800;
|
||||||
|
font-size: 13px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.home-progress {
|
||||||
|
color: var(--brand);
|
||||||
|
font-weight: 700;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
- [ ] **Step 2: Update mobile styles**
|
||||||
|
|
||||||
|
In the `@media (max-width: 720px)` block, use:
|
||||||
|
|
||||||
|
```css
|
||||||
|
@media (max-width: 720px) {
|
||||||
|
.home-shell {
|
||||||
|
grid-template-columns: 1fr;
|
||||||
|
padding: 14px 12px 28px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.home-dashboard {
|
||||||
|
position: static;
|
||||||
|
}
|
||||||
|
|
||||||
|
.home-metrics {
|
||||||
|
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||||
|
}
|
||||||
|
|
||||||
|
.home-heading {
|
||||||
|
align-items: stretch;
|
||||||
|
flex-direction: column;
|
||||||
|
}
|
||||||
|
|
||||||
|
.home-search {
|
||||||
|
max-width: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.home-grid {
|
||||||
|
grid-template-columns: 1fr;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
- [ ] **Step 3: Check for duplicate home style blocks**
|
||||||
|
|
||||||
|
Run:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
rg -n "\.home-shell|\.home-dashboard|\.home-card-stats|\.home-favorite" styles.css
|
||||||
|
```
|
||||||
|
|
||||||
|
Expected: selectors exist, and old conflicting `.home-shell` single-column rules are not duplicated outside media queries.
|
||||||
|
|
||||||
|
## Task 5: Full Verification
|
||||||
|
|
||||||
|
**Files:**
|
||||||
|
- Verify: `F:\ooo\speaking-practice-local\home.js`
|
||||||
|
- Verify: `F:\ooo\speaking-practice-local\app.js`
|
||||||
|
- Verify: `F:\ooo\speaking-practice-local\admin.js`
|
||||||
|
- Verify: `F:\ooo\speaking-practice-local\backend\main.py`
|
||||||
|
- Verify: `F:\ooo\speaking-practice-local\backend\db.py`
|
||||||
|
|
||||||
|
- [ ] **Step 1: Run automated checks**
|
||||||
|
|
||||||
|
Run:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
node --check home.js
|
||||||
|
node --check app.js
|
||||||
|
node --check admin.js
|
||||||
|
python -m py_compile backend\main.py backend\db.py
|
||||||
|
node tests\progress-helpers.test.mjs
|
||||||
|
node tests\admin-file-input.test.mjs
|
||||||
|
```
|
||||||
|
|
||||||
|
Expected: all commands finish with exit code 0.
|
||||||
|
|
||||||
|
- [ ] **Step 2: Start or reuse the local server**
|
||||||
|
|
||||||
|
If no server is running, run:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
python -m uvicorn backend.main:app --reload --host 127.0.0.1 --port 8000
|
||||||
|
```
|
||||||
|
|
||||||
|
Expected: server listens on `http://127.0.0.1:8000/`.
|
||||||
|
|
||||||
|
- [ ] **Step 3: Browser verification**
|
||||||
|
|
||||||
|
Open:
|
||||||
|
|
||||||
|
```text
|
||||||
|
http://127.0.0.1:8000/
|
||||||
|
```
|
||||||
|
|
||||||
|
Confirm:
|
||||||
|
|
||||||
|
- the left learning overview appears
|
||||||
|
- metric buttons update the grid
|
||||||
|
- search and category chips still work
|
||||||
|
- material cards show sentence, progress, difficult, subtitle, and favorite information
|
||||||
|
- favorite button toggles without opening the study page
|
||||||
|
- clicking the card body opens `study.html?video=<id>`
|
||||||
|
- admin link remains visible only for admin users
|
||||||
|
|
||||||
|
- [ ] **Step 4: Confirm README was not modified**
|
||||||
|
|
||||||
|
Run:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
git diff -- README.md
|
||||||
|
```
|
||||||
|
|
||||||
|
Expected if inside a git repo: no diff. If not inside a git repo, this command may report that the directory is not a repository; in that case, manually confirm `README.md` was not edited.
|
||||||
@@ -0,0 +1,238 @@
|
|||||||
|
# Speaking Lab Home Page v1 Implementation Plan
|
||||||
|
|
||||||
|
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||||
|
|
||||||
|
**Goal:** Make `/` a dedicated material-browsing home page with search, categories, generated preview covers, and card navigation into the study page.
|
||||||
|
|
||||||
|
**Architecture:** Move the existing study page markup from `index.html` to `study.html`, then replace `index.html` with a home page powered by new `home.js`. Reuse `/api/videos` and the existing `speaking-lab-state-v1` localStorage structure for login/admin state and progress summaries. Keep backend API unchanged except making `/` return the new home page.
|
||||||
|
|
||||||
|
**Tech Stack:** FastAPI static files, vanilla HTML/CSS/JS, localStorage, existing Node helper tests.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## File Structure
|
||||||
|
|
||||||
|
- Create `F:\ooo\speaking-practice-local\study.html`: current study page markup, loading `app.js`.
|
||||||
|
- Replace `F:\ooo\speaking-practice-local\index.html`: new home page markup, loading `home.js`.
|
||||||
|
- Create `F:\ooo\speaking-practice-local\home.js`: home page state, API load, search/category filtering, generated covers, login/admin UI, and card navigation.
|
||||||
|
- Modify `F:\ooo\speaking-practice-local\app.js`: read `?video=<id>` on study page load.
|
||||||
|
- Modify `F:\ooo\speaking-practice-local\styles.css`: add home page/card/cover styles.
|
||||||
|
- Modify `F:\ooo\speaking-practice-local\backend\main.py`: keep `/` returning `index.html`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Task 1: Split Home And Study Pages
|
||||||
|
|
||||||
|
**Files:**
|
||||||
|
- Create: `F:\ooo\speaking-practice-local\study.html`
|
||||||
|
- Modify: `F:\ooo\speaking-practice-local\index.html`
|
||||||
|
|
||||||
|
- [ ] **Step 1: Copy current study markup to `study.html`**
|
||||||
|
|
||||||
|
Copy the current contents of `index.html` exactly into `study.html`.
|
||||||
|
|
||||||
|
- [ ] **Step 2: Replace `index.html` with home shell**
|
||||||
|
|
||||||
|
Use a home page structure with:
|
||||||
|
|
||||||
|
```html
|
||||||
|
<body class="home-page">
|
||||||
|
<header class="topbar home-topbar">...</header>
|
||||||
|
<main class="home-shell">
|
||||||
|
<section class="home-library">
|
||||||
|
<div id="homeCategoryFilters" class="home-categories"></div>
|
||||||
|
<div id="homeStatus" class="home-status"></div>
|
||||||
|
<div id="homeGrid" class="home-grid"></div>
|
||||||
|
</section>
|
||||||
|
</main>
|
||||||
|
<script src="./home.js"></script>
|
||||||
|
</body>
|
||||||
|
```
|
||||||
|
|
||||||
|
Include login/register fields equivalent to the study page and an admin link/button hidden by default.
|
||||||
|
|
||||||
|
- [ ] **Step 3: Run syntax-neutral check**
|
||||||
|
|
||||||
|
Run:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
Select-String -Path index.html,study.html -Pattern "home.js|app.js|study-shell|home-grid"
|
||||||
|
```
|
||||||
|
|
||||||
|
Expected:
|
||||||
|
|
||||||
|
- `index.html` references `home.js` and `home-grid`.
|
||||||
|
- `study.html` references `app.js` and `study-shell`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Task 2: Add Home Page Logic
|
||||||
|
|
||||||
|
**Files:**
|
||||||
|
- Create: `F:\ooo\speaking-practice-local\home.js`
|
||||||
|
|
||||||
|
- [ ] **Step 1: Create home.js**
|
||||||
|
|
||||||
|
Implement:
|
||||||
|
|
||||||
|
- load local state from `speaking-lab-state-v1`
|
||||||
|
- login/register/logout matching existing local behavior
|
||||||
|
- load `/api/videos`
|
||||||
|
- search by title, speaker, description, tags
|
||||||
|
- category filtering by tags
|
||||||
|
- render generated cover cards
|
||||||
|
- show subtitle languages
|
||||||
|
- show progress summaries using local helper equivalents
|
||||||
|
- click card -> `study.html?video=<id>`
|
||||||
|
|
||||||
|
- [ ] **Step 2: Run check**
|
||||||
|
|
||||||
|
Run:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
node --check home.js
|
||||||
|
```
|
||||||
|
|
||||||
|
Expected: exit code 0.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Task 3: Teach Study Page URL Selection
|
||||||
|
|
||||||
|
**Files:**
|
||||||
|
- Modify: `F:\ooo\speaking-practice-local\app.js`
|
||||||
|
|
||||||
|
- [ ] **Step 1: Add requested video helper**
|
||||||
|
|
||||||
|
Add:
|
||||||
|
|
||||||
|
```js
|
||||||
|
function getRequestedVideoId() {
|
||||||
|
if (!IS_BROWSER) return null;
|
||||||
|
return new URLSearchParams(window.location.search).get("video");
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
- [ ] **Step 2: Prefer requested video after API load**
|
||||||
|
|
||||||
|
In `initializeApp()`, after loading videos and before fallback selection, use:
|
||||||
|
|
||||||
|
```js
|
||||||
|
const requestedVideoId = getRequestedVideoId();
|
||||||
|
if (requestedVideoId && getVideo(requestedVideoId)) {
|
||||||
|
activeVideoId = requestedVideoId;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
- [ ] **Step 3: Run checks**
|
||||||
|
|
||||||
|
Run:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
node --check app.js
|
||||||
|
node tests\progress-helpers.test.mjs
|
||||||
|
```
|
||||||
|
|
||||||
|
Expected: both pass.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Task 4: Add Home Styles
|
||||||
|
|
||||||
|
**Files:**
|
||||||
|
- Modify: `F:\ooo\speaking-practice-local\styles.css`
|
||||||
|
|
||||||
|
- [ ] **Step 1: Add home page CSS**
|
||||||
|
|
||||||
|
Add styles for:
|
||||||
|
|
||||||
|
- `.home-page`
|
||||||
|
- `.home-topbar`
|
||||||
|
- `.home-shell`
|
||||||
|
- `.home-categories`
|
||||||
|
- `.home-grid`
|
||||||
|
- `.home-card`
|
||||||
|
- `.home-cover`
|
||||||
|
- `.home-card-meta`
|
||||||
|
- `.home-progress`
|
||||||
|
- responsive mobile grid
|
||||||
|
|
||||||
|
- [ ] **Step 2: Run smoke checks**
|
||||||
|
|
||||||
|
Run:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
node --check home.js
|
||||||
|
node --check app.js
|
||||||
|
```
|
||||||
|
|
||||||
|
Expected: both pass.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Task 5: Verify Locally
|
||||||
|
|
||||||
|
**Files:**
|
||||||
|
- No code unless verification reveals a defect.
|
||||||
|
|
||||||
|
- [ ] **Step 1: Static verification**
|
||||||
|
|
||||||
|
Run:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
python -m py_compile backend\main.py backend\db.py
|
||||||
|
node --check home.js
|
||||||
|
node --check app.js
|
||||||
|
node --check admin.js
|
||||||
|
node tests\progress-helpers.test.mjs
|
||||||
|
node tests\admin-file-input.test.mjs
|
||||||
|
```
|
||||||
|
|
||||||
|
Expected: all pass.
|
||||||
|
|
||||||
|
- [ ] **Step 2: Browser verification**
|
||||||
|
|
||||||
|
Open:
|
||||||
|
|
||||||
|
```text
|
||||||
|
http://127.0.0.1:8000/
|
||||||
|
```
|
||||||
|
|
||||||
|
Expected:
|
||||||
|
|
||||||
|
- Home page appears.
|
||||||
|
- Search input is visible.
|
||||||
|
- Category chips render.
|
||||||
|
- Cards render with generated covers.
|
||||||
|
- Clicking a card opens `study.html?video=<id>`.
|
||||||
|
|
||||||
|
Open:
|
||||||
|
|
||||||
|
```text
|
||||||
|
http://127.0.0.1:8000/study.html
|
||||||
|
http://127.0.0.1:8000/admin.html
|
||||||
|
```
|
||||||
|
|
||||||
|
Expected both still work.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Self-Review
|
||||||
|
|
||||||
|
Spec coverage:
|
||||||
|
|
||||||
|
- `/` opens home page: Tasks 1 and 5.
|
||||||
|
- Current study page moves to `study.html`: Task 1.
|
||||||
|
- Search/categories/cards/generated covers: Tasks 2 and 4.
|
||||||
|
- Card navigation to `study.html?video=<id>`: Tasks 2 and 3.
|
||||||
|
- Admin entry for admin users: Task 2.
|
||||||
|
- No backend schema/API changes: plan keeps backend unchanged.
|
||||||
|
|
||||||
|
Placeholder scan:
|
||||||
|
|
||||||
|
- No unresolved placeholders.
|
||||||
|
|
||||||
|
Type consistency:
|
||||||
|
|
||||||
|
- Video IDs are strings in frontend navigation.
|
||||||
|
- Home state uses the same `speaking-lab-state-v1` key as existing pages.
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
# Speaking Lab Material Edit v1 Implementation Plan
|
||||||
|
|
||||||
|
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||||
|
|
||||||
|
**Goal:** Add backend and admin-page support for editing existing materials, including replacing video and subtitle files.
|
||||||
|
|
||||||
|
**Architecture:** Extend the existing FastAPI/SQLite content-library path with an update helper and `PATCH /api/videos/{video_id}` endpoint. Reuse the existing admin form as an add/edit form, keeping add mode as the default and switching to edit mode from the material list.
|
||||||
|
|
||||||
|
**Tech Stack:** FastAPI multipart forms, SQLite, vanilla JS, existing CSS.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Tasks
|
||||||
|
|
||||||
|
1. Backend update helper in `backend/db.py`.
|
||||||
|
2. PATCH endpoint and safe replacement cleanup in `backend/main.py`.
|
||||||
|
3. Admin form edit mode in `admin.html` and `admin.js`.
|
||||||
|
4. Admin list edit action styling in `styles.css`.
|
||||||
|
5. Static and API smoke verification.
|
||||||
|
|
||||||
|
## Verification Commands
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
python -m py_compile backend\main.py backend\db.py
|
||||||
|
node --check admin.js
|
||||||
|
node --check app.js
|
||||||
|
node tests\admin-file-input.test.mjs
|
||||||
|
node tests\progress-helpers.test.mjs
|
||||||
|
```
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
# Speaking Lab Study Focus Layout Implementation Plan
|
||||||
|
|
||||||
|
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task.
|
||||||
|
|
||||||
|
**Goal:** Remove the study page material rail and let the video learning panel occupy that space.
|
||||||
|
|
||||||
|
**Architecture:** Remove rail markup in `study.html`, make related `app.js` DOM operations optional, and simplify `styles.css` layout so `.left-stage` becomes a single video panel column.
|
||||||
|
|
||||||
|
**Tech Stack:** Vanilla HTML, CSS, JavaScript.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Task 1: Remove Rail Markup
|
||||||
|
|
||||||
|
- Modify `study.html`.
|
||||||
|
- Delete the `.lesson-rail` block inside `.left-stage`.
|
||||||
|
- Keep `.video-panel` unchanged.
|
||||||
|
|
||||||
|
## Task 2: Guard Rail JavaScript
|
||||||
|
|
||||||
|
- Modify `app.js`.
|
||||||
|
- Ensure event listeners for `searchInput`, `tagFilters`, `videoList`, `videoCount`, and `adminEntryBtn` only run when those elements exist.
|
||||||
|
- Make `renderLibrary()` return early when rail elements are absent.
|
||||||
|
- Make `renderAdminAccess()` tolerate a missing admin button.
|
||||||
|
|
||||||
|
## Task 3: Expand Video Layout
|
||||||
|
|
||||||
|
- Modify `styles.css`.
|
||||||
|
- Change `.left-stage` from `grid-template-columns: 220px minmax(0, 1fr)` to `grid-template-columns: minmax(0, 1fr)`.
|
||||||
|
- Remove responsive overrides that reintroduce a rail width.
|
||||||
|
- Keep transcript panel on the right.
|
||||||
|
|
||||||
|
## Task 4: Verify
|
||||||
|
|
||||||
|
Run:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
node --check app.js
|
||||||
|
node --check home.js
|
||||||
|
node --check admin.js
|
||||||
|
node tests\progress-helpers.test.mjs
|
||||||
|
node tests\admin-file-input.test.mjs
|
||||||
|
```
|
||||||
|
|
||||||
|
Open `http://127.0.0.1:8000/study.html` and confirm the left rail is gone and the video panel is wider.
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
# Speaking Lab Subtitle Delete Cues Implementation Plan
|
||||||
|
|
||||||
|
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task.
|
||||||
|
|
||||||
|
**Goal:** Add admin-side deletion of whole subtitle cue blocks.
|
||||||
|
|
||||||
|
**Architecture:** Backend accepts optional updated subtitle text fields on PATCH. Admin JS parses subtitle text into cue blocks, renders delete buttons during edit mode, rebuilds VTT text from remaining cue blocks, and sends updated content with the existing material edit request.
|
||||||
|
|
||||||
|
**Tech Stack:** FastAPI form fields, SQLite subtitle content, vanilla JavaScript admin page.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Task 1: Backend Content Update
|
||||||
|
|
||||||
|
- Modify `backend/main.py`.
|
||||||
|
- Add optional `subtitle_en_content` and `subtitle_zh_content` form fields to PATCH.
|
||||||
|
- Convert provided content fields into subtitle update payloads when no replacement file exists for that language.
|
||||||
|
|
||||||
|
## Task 2: Admin Markup
|
||||||
|
|
||||||
|
- Modify `admin.html`.
|
||||||
|
- Add a container below the subtitle upload inputs for subtitle cue deletion sections.
|
||||||
|
|
||||||
|
## Task 3: Admin Subtitle State
|
||||||
|
|
||||||
|
- Modify `admin.js`.
|
||||||
|
- Add cue parsing and VTT rebuilding helpers.
|
||||||
|
- Track editable subtitle cues for the current editing material.
|
||||||
|
- Render per-language cue lists with `删除` buttons.
|
||||||
|
- Append updated subtitle content to FormData on edit save.
|
||||||
|
|
||||||
|
## Task 4: Styles
|
||||||
|
|
||||||
|
- Modify `styles.css`.
|
||||||
|
- Add compact admin subtitle cue list styles.
|
||||||
|
|
||||||
|
## Task 5: Verify
|
||||||
|
|
||||||
|
Run automated checks and manually verify admin delete/save/study-page reload.
|
||||||
@@ -0,0 +1,174 @@
|
|||||||
|
# Speaking Lab Admin Page Design
|
||||||
|
|
||||||
|
## Goal
|
||||||
|
|
||||||
|
Move content management out of the study page and into a dedicated local admin page. The first admin page supports only adding and deleting materials, keeping the study page focused on learning.
|
||||||
|
|
||||||
|
## Scope
|
||||||
|
|
||||||
|
In scope:
|
||||||
|
|
||||||
|
- Add a dedicated `admin.html` page.
|
||||||
|
- Add a small admin entry button beside the left material rail title on `index.html`.
|
||||||
|
- Show the admin entry button only when the current local user is an admin.
|
||||||
|
- Remove the bottom `后台管理` dock from the study page.
|
||||||
|
- Support adding materials from the new admin page through the existing `POST /api/videos` endpoint.
|
||||||
|
- Support deleting materials from the new admin page through a new `DELETE /api/videos/{video_id}` endpoint.
|
||||||
|
- Delete local uploaded video and subtitle files when deleting a material.
|
||||||
|
- Keep external video/HLS URLs untouched when deleting a material.
|
||||||
|
|
||||||
|
Out of scope:
|
||||||
|
|
||||||
|
- Editing video title, speaker, description, tags, or URL.
|
||||||
|
- Replacing subtitles after creation.
|
||||||
|
- Real backend authentication or sessions.
|
||||||
|
- User roles stored in SQLite.
|
||||||
|
- Batch delete, undo, recycle bin, or soft delete.
|
||||||
|
- Server deployment.
|
||||||
|
|
||||||
|
## Admin Visibility
|
||||||
|
|
||||||
|
This phase keeps the current local prototype auth rule:
|
||||||
|
|
||||||
|
- A user is an admin when their email contains `admin`.
|
||||||
|
- Login state remains in browser `localStorage`.
|
||||||
|
- The study page shows the admin entry button only for admin users.
|
||||||
|
- The admin page checks the same local login state. If the visitor is not an admin, it shows a simple message telling them to return to the study page and log in with an admin email.
|
||||||
|
|
||||||
|
This is not secure server-side authorization. It is acceptable for the local prototype phase and should be replaced when real multi-user deployment starts.
|
||||||
|
|
||||||
|
## Study Page Changes
|
||||||
|
|
||||||
|
The study page should become learning-focused.
|
||||||
|
|
||||||
|
Changes:
|
||||||
|
|
||||||
|
- Remove the bottom `后台管理` dock from `index.html`.
|
||||||
|
- Keep login/register in the top bar.
|
||||||
|
- In the left material rail header, show:
|
||||||
|
- `素材`
|
||||||
|
- current video count
|
||||||
|
- a small admin button when the current user is admin
|
||||||
|
- Clicking the admin button navigates to `admin.html`.
|
||||||
|
|
||||||
|
The existing study page continues to load videos through `GET /api/videos`, use demo videos as empty-library fallback, and preserve existing study behaviors.
|
||||||
|
|
||||||
|
## Admin Page
|
||||||
|
|
||||||
|
Add `admin.html` and `admin.js`.
|
||||||
|
|
||||||
|
The admin page has:
|
||||||
|
|
||||||
|
- Header with product name and a return-to-study button.
|
||||||
|
- Admin status area showing the current local admin email.
|
||||||
|
- Add material form:
|
||||||
|
- title
|
||||||
|
- speaker
|
||||||
|
- description
|
||||||
|
- comma-separated tags
|
||||||
|
- local video file
|
||||||
|
- video/HLS URL
|
||||||
|
- English `.srt` / `.vtt` subtitle
|
||||||
|
- Chinese `.srt` / `.vtt` subtitle
|
||||||
|
- Material list:
|
||||||
|
- title
|
||||||
|
- speaker
|
||||||
|
- tags
|
||||||
|
- source type
|
||||||
|
- subtitle availability
|
||||||
|
- delete button
|
||||||
|
|
||||||
|
First-version behavior:
|
||||||
|
|
||||||
|
- Add uses existing `POST /api/videos`.
|
||||||
|
- On successful add, the form resets and the list reloads.
|
||||||
|
- Delete asks for confirmation with `确定删除这个素材吗?此操作不可恢复。`
|
||||||
|
- Confirmed delete calls `DELETE /api/videos/{video_id}`.
|
||||||
|
- Successful delete removes the item from the list.
|
||||||
|
|
||||||
|
## Backend Delete Design
|
||||||
|
|
||||||
|
Add `DELETE /api/videos/{video_id}`.
|
||||||
|
|
||||||
|
Behavior:
|
||||||
|
|
||||||
|
- If the video does not exist, return 404 with `视频不存在`.
|
||||||
|
- Before deleting database rows, collect local file paths:
|
||||||
|
- `videos.video_url` if it starts with `/uploads/`
|
||||||
|
- every related `subtitles.file_path` if it starts with `/uploads/`
|
||||||
|
- Delete the video row from SQLite. Existing foreign key cascade deletes related subtitle rows.
|
||||||
|
- After the database delete succeeds, attempt to remove collected local files from disk.
|
||||||
|
- Ignore missing files.
|
||||||
|
- If a file cannot be deleted, keep the database delete successful and return a response that includes a warning list.
|
||||||
|
|
||||||
|
Suggested response:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"ok": true,
|
||||||
|
"deletedVideoId": 1,
|
||||||
|
"warnings": []
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
If file deletion has warnings:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"ok": true,
|
||||||
|
"deletedVideoId": 1,
|
||||||
|
"warnings": ["无法删除文件: uploads/videos/example.mp4"]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Data And File Safety
|
||||||
|
|
||||||
|
Delete only files under the project `uploads/` directory. Never delete arbitrary paths from database content.
|
||||||
|
|
||||||
|
Implementation rule:
|
||||||
|
|
||||||
|
- Convert `/uploads/...` URLs to filesystem paths under the project upload directory.
|
||||||
|
- Resolve the path.
|
||||||
|
- Delete it only if the resolved path is inside `UPLOADS_DIR`.
|
||||||
|
|
||||||
|
This prevents a bad database value from deleting unrelated local files.
|
||||||
|
|
||||||
|
## Testing
|
||||||
|
|
||||||
|
Manual verification:
|
||||||
|
|
||||||
|
1. Start the app:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
cd F:\ooo\speaking-practice-local
|
||||||
|
python -m uvicorn backend.main:app --reload --host 127.0.0.1 --port 8000
|
||||||
|
```
|
||||||
|
|
||||||
|
2. Open `http://127.0.0.1:8000`.
|
||||||
|
3. Log in with a normal email. Confirm the material rail does not show the admin button.
|
||||||
|
4. Log out, then log in with an email containing `admin`. Confirm the admin button appears beside `素材`.
|
||||||
|
5. Click the admin button. Confirm `admin.html` opens.
|
||||||
|
6. Add a URL-based material with subtitles from the admin page.
|
||||||
|
7. Return to the study page and confirm the new material appears.
|
||||||
|
8. Return to the admin page and delete the material.
|
||||||
|
9. Return to the study page and confirm the deleted material no longer appears.
|
||||||
|
10. Add a local video-file material with subtitles, then delete it. Confirm uploaded files are removed from `uploads/videos/` and `uploads/subtitles/`.
|
||||||
|
11. Open `http://127.0.0.1:8000/docs` and confirm `DELETE /api/videos/{video_id}` appears.
|
||||||
|
|
||||||
|
Automated or command-line checks:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
python -m py_compile backend\main.py backend\db.py
|
||||||
|
node --check app.js
|
||||||
|
node --check admin.js
|
||||||
|
```
|
||||||
|
|
||||||
|
## Future Work
|
||||||
|
|
||||||
|
Likely follow-up phases:
|
||||||
|
|
||||||
|
- Edit video metadata.
|
||||||
|
- Replace subtitles.
|
||||||
|
- Add backend-backed accounts and real admin authorization.
|
||||||
|
- Add import/export backup.
|
||||||
|
- Add server deployment flow.
|
||||||
@@ -0,0 +1,150 @@
|
|||||||
|
# Speaking Lab Content Library Design
|
||||||
|
|
||||||
|
## Goal
|
||||||
|
|
||||||
|
Turn the current Speaking Lab prototype into a local product prototype with a real content library. The first implementation focuses on content management: admins can add a video with metadata, choose either a local video file or a video/HLS URL, upload English and Chinese subtitles at the same time, and see the content persist after refresh.
|
||||||
|
|
||||||
|
## Scope
|
||||||
|
|
||||||
|
In scope:
|
||||||
|
|
||||||
|
- Add backend video library APIs.
|
||||||
|
- Save uploaded video files under `uploads/videos/`.
|
||||||
|
- Save uploaded subtitle files under `uploads/subtitles/`.
|
||||||
|
- Store video metadata and subtitle records in SQLite.
|
||||||
|
- Load the video list from the backend on page startup.
|
||||||
|
- Keep existing playback, subtitle display, search, tag filtering, and transcript-click behavior where possible.
|
||||||
|
|
||||||
|
Out of scope for this phase:
|
||||||
|
|
||||||
|
- Editing or deleting videos from the web UI.
|
||||||
|
- Replacing subtitles after a video has been created.
|
||||||
|
- Real user authentication or permissions.
|
||||||
|
- Learning records, favorites, watch-later, playback progress, or AI speaking feedback.
|
||||||
|
- Server deployment, Docker, domains, HTTPS, or cloud storage.
|
||||||
|
|
||||||
|
## Recommended Approach
|
||||||
|
|
||||||
|
Use the minimal content-library API approach.
|
||||||
|
|
||||||
|
The backend keeps the current FastAPI + SQLite structure. The frontend admin form submits a `FormData` payload to the backend instead of creating temporary browser-only object URLs. The backend decides whether the video source is an uploaded file or an external URL, saves files when present, writes database rows, and returns a normalized video object for the frontend to render.
|
||||||
|
|
||||||
|
## API Design
|
||||||
|
|
||||||
|
Add these endpoints:
|
||||||
|
|
||||||
|
```text
|
||||||
|
GET /api/videos
|
||||||
|
GET /api/videos/{video_id}
|
||||||
|
POST /api/videos
|
||||||
|
```
|
||||||
|
|
||||||
|
`POST /api/videos` accepts multipart form data:
|
||||||
|
|
||||||
|
```text
|
||||||
|
title
|
||||||
|
speaker
|
||||||
|
description
|
||||||
|
tags
|
||||||
|
video_file optional
|
||||||
|
video_url optional
|
||||||
|
subtitle_en optional
|
||||||
|
subtitle_zh optional
|
||||||
|
```
|
||||||
|
|
||||||
|
Validation rules:
|
||||||
|
|
||||||
|
- `title` is required.
|
||||||
|
- At least one of `video_file` or `video_url` is required.
|
||||||
|
- If both `video_file` and `video_url` are present, the uploaded file wins.
|
||||||
|
- Subtitle files are optional.
|
||||||
|
- Uploaded subtitles must use `.srt` or `.vtt`.
|
||||||
|
- Uploaded videos should use common browser-playable video formats such as `.mp4`, `.webm`, `.mov`, or `.m4v`.
|
||||||
|
- Tags are submitted as comma-separated text and returned to the frontend as an array.
|
||||||
|
|
||||||
|
## Data Design
|
||||||
|
|
||||||
|
Reuse the existing `videos` and `subtitles` tables.
|
||||||
|
|
||||||
|
`videos` usage:
|
||||||
|
|
||||||
|
- `title`: required video title.
|
||||||
|
- `speaker`: speaker or source label.
|
||||||
|
- `description`: optional description.
|
||||||
|
- `tags`: JSON string, for example `["technology", "design"]`.
|
||||||
|
- `video_url`: final playable URL. For uploaded files this is a local static URL such as `/uploads/videos/example.mp4`; for external sources this is the original video or HLS URL.
|
||||||
|
- `status`: set to `published` for this phase.
|
||||||
|
|
||||||
|
`subtitles` usage:
|
||||||
|
|
||||||
|
- `video_id`: parent video.
|
||||||
|
- `language_code`: `en` or `zh`.
|
||||||
|
- `language_name`: `English` or `中文`.
|
||||||
|
- `format`: `srt` or `vtt`.
|
||||||
|
- `file_path`: local static URL such as `/uploads/subtitles/example.srt`.
|
||||||
|
- `content`: raw subtitle text.
|
||||||
|
|
||||||
|
The frontend can continue parsing subtitle content into cues with the existing parser.
|
||||||
|
|
||||||
|
## Frontend Behavior
|
||||||
|
|
||||||
|
On page startup, the frontend calls `GET /api/videos` and renders the returned videos in the existing material list. The existing local demo videos remain as an empty-library fallback only; they are not automatically inserted into the database.
|
||||||
|
|
||||||
|
When an admin submits the existing backstage form:
|
||||||
|
|
||||||
|
1. Build `FormData` from title, speaker, description, tags, video file, video URL, English subtitle, and Chinese subtitle.
|
||||||
|
2. Submit it to `POST /api/videos`.
|
||||||
|
3. Disable the submit button and show an adding state while the request is running.
|
||||||
|
4. On success, insert the returned video at the top of the list, clear the form, and select the new video.
|
||||||
|
5. On failure, show the backend error message.
|
||||||
|
|
||||||
|
Existing behavior to preserve:
|
||||||
|
|
||||||
|
- Search by title, speaker, description, and tags.
|
||||||
|
- Tag filtering.
|
||||||
|
- Bilingual subtitle display.
|
||||||
|
- Click transcript line to jump the video.
|
||||||
|
- Current subtitle highlighting during playback.
|
||||||
|
|
||||||
|
## Error Handling
|
||||||
|
|
||||||
|
Backend errors should be clear enough for a non-technical local user:
|
||||||
|
|
||||||
|
- Missing title: `标题不能为空`
|
||||||
|
- Missing video source: `请上传视频文件或填写视频地址`
|
||||||
|
- Unsupported subtitle file: `字幕只支持 .srt 或 .vtt`
|
||||||
|
- Unsupported video file: `视频文件格式不支持`
|
||||||
|
- File save failure: `保存文件失败,请重试`
|
||||||
|
|
||||||
|
The frontend can use a simple alert for this phase. A toast or notification system is out of scope.
|
||||||
|
|
||||||
|
## Testing
|
||||||
|
|
||||||
|
Manual verification:
|
||||||
|
|
||||||
|
1. Start the app:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
cd F:\ooo\speaking-practice-local
|
||||||
|
python -m uvicorn backend.main:app --reload --host 127.0.0.1 --port 8000
|
||||||
|
```
|
||||||
|
|
||||||
|
2. Open `http://127.0.0.1:8000`.
|
||||||
|
3. Log in with an email containing `admin`.
|
||||||
|
4. Add a video using an external video or HLS URL plus English and Chinese subtitles.
|
||||||
|
5. Refresh the page and confirm the video remains in the list.
|
||||||
|
6. Add a video using a local video file plus subtitles.
|
||||||
|
7. Refresh the page and confirm the local video remains playable.
|
||||||
|
8. Confirm subtitles render and transcript clicks jump playback.
|
||||||
|
9. Open `http://127.0.0.1:8000/docs` and confirm the three video APIs are visible.
|
||||||
|
|
||||||
|
## Future Work
|
||||||
|
|
||||||
|
Likely next phases after this content-library slice:
|
||||||
|
|
||||||
|
- Add edit and delete actions for videos.
|
||||||
|
- Persist real user accounts and admin permissions.
|
||||||
|
- Move favorites, watch-later, and playback progress from `localStorage` to SQLite.
|
||||||
|
- Add import/export or backup for the local content library.
|
||||||
|
- Package a beginner-friendly local startup script.
|
||||||
|
- Later, prepare server deployment once the local product loop is stable.
|
||||||
@@ -0,0 +1,227 @@
|
|||||||
|
# Speaking Lab Learning Progress v1 Design
|
||||||
|
|
||||||
|
## Goal
|
||||||
|
|
||||||
|
Add a local-first learning progress layer so a learner can leave a video, come back later, and immediately know where to continue and which subtitle lines still need practice.
|
||||||
|
|
||||||
|
## Current Context
|
||||||
|
|
||||||
|
Speaking Lab already has:
|
||||||
|
|
||||||
|
- A study page that loads videos from `/api/videos`.
|
||||||
|
- Subtitle parsing and clickable transcript lines.
|
||||||
|
- Playback controls for previous, replay, next, and loop.
|
||||||
|
- Local login stored in `localStorage` under `speaking-lab-state-v1`.
|
||||||
|
- Per-user favorites and watch-later lists stored locally.
|
||||||
|
- An admin page for adding and deleting materials.
|
||||||
|
|
||||||
|
This feature keeps the same local-first model. It does not add backend users, cloud sync, or production authentication.
|
||||||
|
|
||||||
|
## Scope
|
||||||
|
|
||||||
|
Learning Progress v1 includes:
|
||||||
|
|
||||||
|
- Save the last playback time for each user and video.
|
||||||
|
- Save the last active subtitle line for each user and video.
|
||||||
|
- Add a `继续学习` action when a video has saved progress.
|
||||||
|
- Restore progress when the learner opens a video.
|
||||||
|
- Add per-line practice status controls:
|
||||||
|
- `已练`
|
||||||
|
- `难句`
|
||||||
|
- Show practice status on transcript lines.
|
||||||
|
- Show progress in the left material list, for example `35%`.
|
||||||
|
- Store all progress in browser `localStorage`.
|
||||||
|
|
||||||
|
Learning Progress v1 excludes:
|
||||||
|
|
||||||
|
- Backend progress persistence.
|
||||||
|
- Multi-device sync.
|
||||||
|
- Learning calendars, streaks, charts, or dashboards.
|
||||||
|
- Persistent recording history.
|
||||||
|
- AI pronunciation scoring.
|
||||||
|
- Real authentication or role enforcement.
|
||||||
|
|
||||||
|
## User Experience
|
||||||
|
|
||||||
|
### Continue Learning
|
||||||
|
|
||||||
|
When a logged-in learner opens a video with saved progress:
|
||||||
|
|
||||||
|
- The video restores to the last saved playback time.
|
||||||
|
- The transcript restores the previously active line when possible.
|
||||||
|
- A `继续学习` button appears in the existing video action area.
|
||||||
|
- Clicking `继续学习` jumps to the saved time and plays from there.
|
||||||
|
|
||||||
|
If there is no saved progress for the current video:
|
||||||
|
|
||||||
|
- The `继续学习` button is hidden or disabled.
|
||||||
|
- The existing learning controls behave as they do today.
|
||||||
|
|
||||||
|
### Transcript Line Status
|
||||||
|
|
||||||
|
Each transcript line gets two compact controls:
|
||||||
|
|
||||||
|
- `已练`: marks the line as practiced.
|
||||||
|
- `难句`: marks the line as difficult.
|
||||||
|
|
||||||
|
The two states are independent:
|
||||||
|
|
||||||
|
- A line can be only practiced.
|
||||||
|
- A line can be only difficult.
|
||||||
|
- A line can be both practiced and difficult.
|
||||||
|
- Clicking an active state again removes that state.
|
||||||
|
|
||||||
|
Visual behavior:
|
||||||
|
|
||||||
|
- Practiced lines use a calm success state.
|
||||||
|
- Difficult lines use a warm warning state.
|
||||||
|
- Status controls stay compact and do not push transcript text into awkward wrapping.
|
||||||
|
|
||||||
|
### Material List Progress
|
||||||
|
|
||||||
|
Each video item in the left material list shows a compact progress label:
|
||||||
|
|
||||||
|
- With subtitles: `已练 3/10 · 30%`
|
||||||
|
- Without subtitles but with playback progress: `看到 02:14`
|
||||||
|
- With no progress: no extra progress label, keeping the list quiet.
|
||||||
|
|
||||||
|
Progress percentage is calculated from practiced subtitle lines:
|
||||||
|
|
||||||
|
```text
|
||||||
|
practiced line count / primary subtitle line count
|
||||||
|
```
|
||||||
|
|
||||||
|
If the current primary subtitle language changes, the denominator follows the currently loaded primary cues for that video. If a video has no subtitle cues, v1 falls back to displaying saved playback time only.
|
||||||
|
|
||||||
|
## Data Model
|
||||||
|
|
||||||
|
Progress is stored inside each local user object in `speaking-lab-state-v1`.
|
||||||
|
|
||||||
|
Existing user shape:
|
||||||
|
|
||||||
|
```js
|
||||||
|
{
|
||||||
|
id: "user-...",
|
||||||
|
email: "learner@example.com",
|
||||||
|
password: "...",
|
||||||
|
role: "user",
|
||||||
|
favorites: [],
|
||||||
|
watchLater: []
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
New user shape:
|
||||||
|
|
||||||
|
```js
|
||||||
|
{
|
||||||
|
id: "user-...",
|
||||||
|
email: "learner@example.com",
|
||||||
|
password: "...",
|
||||||
|
role: "user",
|
||||||
|
favorites: [],
|
||||||
|
watchLater: [],
|
||||||
|
progress: {
|
||||||
|
"video-id": {
|
||||||
|
currentTime: 124.5,
|
||||||
|
activeLineIndex: 6,
|
||||||
|
practicedLineIndexes: [0, 1, 2],
|
||||||
|
difficultLineIndexes: [4, 6],
|
||||||
|
updatedAt: "2026-06-01T12:00:00.000Z"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Compatibility:
|
||||||
|
|
||||||
|
- Existing users without `progress` get `progress: {}` when loaded or updated.
|
||||||
|
- Existing saved localStorage data must continue to work.
|
||||||
|
- Video IDs are stored as strings because API video IDs are normalized to strings in the frontend.
|
||||||
|
|
||||||
|
## Save Rules
|
||||||
|
|
||||||
|
Playback progress saves:
|
||||||
|
|
||||||
|
- On video `timeupdate`, save `currentTime`.
|
||||||
|
- Throttle saves to avoid writing localStorage too frequently.
|
||||||
|
- Save immediately when selecting a different video.
|
||||||
|
- Save immediately when the page is about to unload.
|
||||||
|
|
||||||
|
Line progress saves:
|
||||||
|
|
||||||
|
- When active transcript line changes, save `activeLineIndex`.
|
||||||
|
- When the user toggles `已练` or `难句`, save the updated arrays immediately.
|
||||||
|
|
||||||
|
Privacy and locality:
|
||||||
|
|
||||||
|
- All progress remains in the browser.
|
||||||
|
- Clearing browser storage clears progress.
|
||||||
|
|
||||||
|
## Error Handling
|
||||||
|
|
||||||
|
If localStorage read fails:
|
||||||
|
|
||||||
|
- Fall back to an empty state, matching existing behavior.
|
||||||
|
|
||||||
|
If localStorage write fails:
|
||||||
|
|
||||||
|
- Keep the UI usable for the current session.
|
||||||
|
- Avoid showing noisy errors for every time update.
|
||||||
|
|
||||||
|
If a saved line index is out of range after subtitles are replaced:
|
||||||
|
|
||||||
|
- Keep saved playback time.
|
||||||
|
- Ignore the invalid line index and use the first available line.
|
||||||
|
|
||||||
|
If a video is deleted:
|
||||||
|
|
||||||
|
- Old progress entries may remain in localStorage.
|
||||||
|
- They are harmless because deleted videos will not render.
|
||||||
|
- Cleanup can be handled later when backend user sync exists.
|
||||||
|
|
||||||
|
## UI Placement
|
||||||
|
|
||||||
|
Study page changes only:
|
||||||
|
|
||||||
|
- Add `继续学习` beside existing `收藏` and `稍后再看`.
|
||||||
|
- Add status controls inside each transcript line.
|
||||||
|
- Add progress text to each material item under speaker/tags.
|
||||||
|
|
||||||
|
Admin page does not change for this feature.
|
||||||
|
|
||||||
|
## Testing
|
||||||
|
|
||||||
|
Manual verification:
|
||||||
|
|
||||||
|
1. Log in as a normal user.
|
||||||
|
2. Open a video with subtitles.
|
||||||
|
3. Jump to a subtitle line and play briefly.
|
||||||
|
4. Mark one line as `已练`.
|
||||||
|
5. Mark another line as `难句`.
|
||||||
|
6. Refresh the page.
|
||||||
|
7. Confirm the same video restores progress.
|
||||||
|
8. Confirm transcript line statuses remain visible.
|
||||||
|
9. Confirm the left material list shows progress.
|
||||||
|
10. Log out and log in as another user.
|
||||||
|
11. Confirm the second user does not inherit the first user's progress.
|
||||||
|
|
||||||
|
Automated checks:
|
||||||
|
|
||||||
|
- Add small Node tests for pure progress helpers:
|
||||||
|
- default progress creation
|
||||||
|
- practiced percentage calculation
|
||||||
|
- line status toggle behavior
|
||||||
|
- progress summary formatting
|
||||||
|
- Keep existing syntax checks:
|
||||||
|
- `node --check app.js`
|
||||||
|
- `node --check admin.js`
|
||||||
|
|
||||||
|
## Future Extensions
|
||||||
|
|
||||||
|
After v1 works locally, good next steps are:
|
||||||
|
|
||||||
|
- Backend progress persistence.
|
||||||
|
- A small `我的学习` page.
|
||||||
|
- Review mode that filters only difficult lines.
|
||||||
|
- Recording history attached to specific subtitle lines.
|
||||||
|
- Export/import local progress before account sync exists.
|
||||||
@@ -0,0 +1,101 @@
|
|||||||
|
# Speaking Lab DeepSeek Subtitle AI Design
|
||||||
|
|
||||||
|
## Goal
|
||||||
|
|
||||||
|
Add an admin-side AI subtitle workflow that can clean downloaded English subtitle files and generate aligned Chinese translations after a material has been uploaded. The first version uses DeepSeek for text processing and translation, while keeping true audio-based timestamp calibration behind a future ASR provider boundary.
|
||||||
|
|
||||||
|
## User Experience
|
||||||
|
|
||||||
|
The admin page shows an `AI 修复并翻译字幕` action for an existing material that has English subtitles. If DeepSeek is not configured, the action remains visible but reports a clear setup message instead of failing silently.
|
||||||
|
|
||||||
|
The setup path is intentionally simple for a beginner:
|
||||||
|
|
||||||
|
```env
|
||||||
|
DEEPSEEK_API_KEY=your_key_here
|
||||||
|
DEEPSEEK_BASE_URL=https://api.deepseek.com
|
||||||
|
DEEPSEEK_MODEL=deepseek-chat
|
||||||
|
```
|
||||||
|
|
||||||
|
After the local server restarts, the admin can click `测试 AI 连接`. If the connection works, `AI 修复并翻译字幕` becomes usable.
|
||||||
|
|
||||||
|
## First Version Scope
|
||||||
|
|
||||||
|
The first version does these things:
|
||||||
|
|
||||||
|
- Parse uploaded English VTT/SRT into cue objects.
|
||||||
|
- Remove empty cues and exact duplicate cues.
|
||||||
|
- Keep the original English wording when the downloaded subtitle content is already correct.
|
||||||
|
- Ask DeepSeek to translate each cleaned English cue into natural Chinese for English learners.
|
||||||
|
- Save a clean English VTT and a matching Chinese VTT back to the material.
|
||||||
|
- Return a processing report, including cue count before/after, duplicate count, and translation count.
|
||||||
|
|
||||||
|
The first version does not promise automatic audio timestamp correction. It exposes the structure needed for that later, but does not pretend DeepSeek can listen to the uploaded video.
|
||||||
|
|
||||||
|
## Architecture
|
||||||
|
|
||||||
|
Backend additions:
|
||||||
|
|
||||||
|
- `backend/ai_config.py`: reads environment variables and reports whether DeepSeek is configured.
|
||||||
|
- `backend/subtitle_tools.py`: parses, cleans, deduplicates, and builds VTT files.
|
||||||
|
- `backend/deepseek_client.py`: small HTTP client for the DeepSeek-compatible chat API.
|
||||||
|
- `backend/subtitle_ai.py`: orchestrates clean-and-translate processing.
|
||||||
|
- New API endpoints in `backend/main.py`:
|
||||||
|
- `GET /api/ai/status`
|
||||||
|
- `POST /api/ai/test`
|
||||||
|
- `POST /api/videos/{video_id}/ai/subtitles`
|
||||||
|
|
||||||
|
Frontend additions:
|
||||||
|
|
||||||
|
- Admin page AI panel near the subtitle editor.
|
||||||
|
- Buttons for `测试 AI 连接` and `AI 修复并翻译字幕`.
|
||||||
|
- Status and result messages shown in plain Chinese.
|
||||||
|
|
||||||
|
## Data Flow
|
||||||
|
|
||||||
|
1. Admin uploads video and English subtitles as usual.
|
||||||
|
2. Admin clicks `AI 修复并翻译字幕`.
|
||||||
|
3. Backend loads the material and English subtitle content from SQLite.
|
||||||
|
4. `subtitle_tools` parses and cleans cues locally.
|
||||||
|
5. `deepseek_client` sends the cleaned cue list to DeepSeek for Chinese translation.
|
||||||
|
6. `subtitle_ai` validates that translation count matches English cue count.
|
||||||
|
7. Backend updates the existing English subtitle and upserts the Chinese subtitle.
|
||||||
|
8. Admin page refreshes the material list and shows a report.
|
||||||
|
|
||||||
|
## Error Handling
|
||||||
|
|
||||||
|
If API config is missing, return a friendly `400` with the missing setup information.
|
||||||
|
|
||||||
|
If DeepSeek returns invalid JSON or the wrong number of translations, return a readable error and leave the existing material unchanged.
|
||||||
|
|
||||||
|
If the material has no English subtitle, return a readable error saying English subtitles are required first.
|
||||||
|
|
||||||
|
If the API call times out, return a readable retry message and leave existing subtitles unchanged.
|
||||||
|
|
||||||
|
## Future ASR Calibration
|
||||||
|
|
||||||
|
True timestamp calibration needs an ASR provider that can process audio and return sentence or word timestamps. The first version prepares the interface boundary but leaves `ASR_PROVIDER` disabled.
|
||||||
|
|
||||||
|
Later flow:
|
||||||
|
|
||||||
|
```text
|
||||||
|
video -> extract audio -> ASR timestamps -> align cleaned English text -> DeepSeek translate -> save EN/ZH VTT
|
||||||
|
```
|
||||||
|
|
||||||
|
DeepSeek remains the translation and text cleanup provider. ASR can be added as a separate provider without changing the admin workflow.
|
||||||
|
|
||||||
|
## Testing
|
||||||
|
|
||||||
|
Unit tests cover:
|
||||||
|
|
||||||
|
- Empty cue removal.
|
||||||
|
- Exact duplicate cue removal.
|
||||||
|
- VTT rebuild output.
|
||||||
|
- Missing DeepSeek config status.
|
||||||
|
- Translation count validation.
|
||||||
|
|
||||||
|
Integration-style tests cover:
|
||||||
|
|
||||||
|
- AI endpoint rejects missing API key clearly.
|
||||||
|
- AI endpoint rejects materials without English subtitles.
|
||||||
|
- AI endpoint updates English and Chinese subtitles when given a fake DeepSeek client.
|
||||||
|
|
||||||
@@ -0,0 +1,120 @@
|
|||||||
|
# Speaking Lab Focused Learning UI Design
|
||||||
|
|
||||||
|
## Goal
|
||||||
|
|
||||||
|
Refine Speaking Lab's interface so it feels more like a focused English learning product instead of a generic admin-style dashboard.
|
||||||
|
|
||||||
|
The selected direction is a clean, focused learning workspace with small icon-led status cards.
|
||||||
|
|
||||||
|
## Visual Direction
|
||||||
|
|
||||||
|
Use a restrained learning-app style:
|
||||||
|
|
||||||
|
- calm background
|
||||||
|
- white panels
|
||||||
|
- compact cards
|
||||||
|
- clear learning status
|
||||||
|
- small icons beside dashboard metrics
|
||||||
|
- strong but limited teal accent
|
||||||
|
- softer supporting colors for learned, unstudied, favorites, and difficult items
|
||||||
|
|
||||||
|
Avoid:
|
||||||
|
|
||||||
|
- heavy marketing hero styling
|
||||||
|
- decorative blobs
|
||||||
|
- large gradients
|
||||||
|
- overly colorful one-off cards
|
||||||
|
- changing the app structure or data model
|
||||||
|
|
||||||
|
## Scope
|
||||||
|
|
||||||
|
This UI pass includes:
|
||||||
|
|
||||||
|
- Home dashboard metric cards with small icons.
|
||||||
|
- More learning-oriented dashboard card layout:
|
||||||
|
- icon on the left
|
||||||
|
- label and hint in the middle
|
||||||
|
- count on the right
|
||||||
|
- Home material cards with slightly clearer hierarchy.
|
||||||
|
- Study page visual polish:
|
||||||
|
- video panel feels like a focused practice surface
|
||||||
|
- subtitle area feels more like a training prompt
|
||||||
|
- transcript lines have clearer current, practiced, and difficult states
|
||||||
|
- toolbar buttons feel less generic
|
||||||
|
|
||||||
|
This UI pass excludes:
|
||||||
|
|
||||||
|
- README edits.
|
||||||
|
- Backend changes.
|
||||||
|
- New API endpoints.
|
||||||
|
- New user data fields.
|
||||||
|
- Real icon libraries.
|
||||||
|
- Custom thumbnail upload.
|
||||||
|
- Major layout restructuring.
|
||||||
|
|
||||||
|
## Home Page Details
|
||||||
|
|
||||||
|
Dashboard metric cards should use text icons implemented in HTML/CSS:
|
||||||
|
|
||||||
|
- current materials: `::`
|
||||||
|
- studied: check mark
|
||||||
|
- unstudied: clock-like circle
|
||||||
|
- favorites: heart
|
||||||
|
- difficult materials: marker symbol
|
||||||
|
|
||||||
|
Icons should be small and familiar, with soft tinted backgrounds.
|
||||||
|
|
||||||
|
Metric cards should remain clickable filters.
|
||||||
|
|
||||||
|
The active metric card should still be visually obvious, but it should not feel like a dark admin button. Use a restrained accent state.
|
||||||
|
|
||||||
|
## Study Page Details
|
||||||
|
|
||||||
|
The study page should better communicate that the learner is practicing English:
|
||||||
|
|
||||||
|
- Use a slightly softer page background.
|
||||||
|
- Keep the video as the main focus.
|
||||||
|
- Make the subtitle card look like a prompt area:
|
||||||
|
- primary English line larger and clearer
|
||||||
|
- Chinese line quieter
|
||||||
|
- enough padding for comfortable reading
|
||||||
|
- Make the tool row more compact and training-like.
|
||||||
|
- Make transcript rows cleaner:
|
||||||
|
- active row has a visible left accent
|
||||||
|
- practiced row has a soft green treatment
|
||||||
|
- difficult row has a soft amber treatment
|
||||||
|
- status buttons remain easy to scan
|
||||||
|
|
||||||
|
No behavior changes are required.
|
||||||
|
|
||||||
|
## Testing
|
||||||
|
|
||||||
|
Automated checks:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
node --check home.js
|
||||||
|
node --check app.js
|
||||||
|
node --check admin.js
|
||||||
|
python -m py_compile backend\main.py backend\db.py
|
||||||
|
node tests\progress-helpers.test.mjs
|
||||||
|
node tests\admin-file-input.test.mjs
|
||||||
|
```
|
||||||
|
|
||||||
|
Browser checks:
|
||||||
|
|
||||||
|
1. Open `http://127.0.0.1:8000/`.
|
||||||
|
2. Confirm dashboard metric cards show small icons.
|
||||||
|
3. Confirm metric cards still filter materials.
|
||||||
|
4. Confirm home cards still open `study.html?video=<id>`.
|
||||||
|
5. Open `http://127.0.0.1:8000/study.html`.
|
||||||
|
6. Confirm video area, subtitle prompt, toolbar, and transcript look more like a learning workspace.
|
||||||
|
7. Confirm no text overlaps on the current browser width.
|
||||||
|
|
||||||
|
## Future Extensions
|
||||||
|
|
||||||
|
Later UI improvements can include:
|
||||||
|
|
||||||
|
- replacing text icons with a real icon library
|
||||||
|
- custom cover images
|
||||||
|
- a dedicated difficult-sentence review page
|
||||||
|
- daily learning streaks
|
||||||
@@ -0,0 +1,235 @@
|
|||||||
|
# Speaking Lab Home Dashboard v1 Design
|
||||||
|
|
||||||
|
## Goal
|
||||||
|
|
||||||
|
Upgrade the existing home page from a simple material grid into a learning dashboard that feels useful as a shareable product prototype.
|
||||||
|
|
||||||
|
The dashboard should help a learner answer three questions quickly:
|
||||||
|
|
||||||
|
- What can I study?
|
||||||
|
- What have I already studied?
|
||||||
|
- Which saved or difficult materials should I return to?
|
||||||
|
|
||||||
|
## Current Context
|
||||||
|
|
||||||
|
Speaking Lab currently has:
|
||||||
|
|
||||||
|
- `index.html`: home page with search, tag chips, material cards, and admin link.
|
||||||
|
- `home.js`: loads `/api/videos`, renders generated covers, and reads local user progress.
|
||||||
|
- `study.html` and `app.js`: learning workspace with subtitles, progress, favorites, watch-later, and difficult-line tracking.
|
||||||
|
- `admin.html` and `admin.js`: local admin page for adding, editing, replacing, and deleting materials.
|
||||||
|
- Local user state in `localStorage` under `speaking-lab-state-v1`.
|
||||||
|
- Material metadata from FastAPI and SQLite through `GET /api/videos`.
|
||||||
|
|
||||||
|
No README changes are part of this upgrade.
|
||||||
|
|
||||||
|
## Scope
|
||||||
|
|
||||||
|
Home Dashboard v1 includes:
|
||||||
|
|
||||||
|
- Add a left overview panel on the home page.
|
||||||
|
- Show dashboard metrics:
|
||||||
|
- total materials
|
||||||
|
- studied materials
|
||||||
|
- unstudied materials
|
||||||
|
- favorite materials
|
||||||
|
- materials with difficult lines
|
||||||
|
- Add status filters:
|
||||||
|
- all
|
||||||
|
- studied
|
||||||
|
- unstudied
|
||||||
|
- favorites
|
||||||
|
- difficult
|
||||||
|
- Keep existing search and tag/category filters.
|
||||||
|
- Combine status, search, and tag filters.
|
||||||
|
- Upgrade material cards with:
|
||||||
|
- favorite toggle
|
||||||
|
- sentence count
|
||||||
|
- practiced percentage
|
||||||
|
- difficult-line count
|
||||||
|
- subtitle language summary
|
||||||
|
- latest progress hint
|
||||||
|
- Keep card click behavior opening `study.html?video=<id>`.
|
||||||
|
- Keep admin link visible only to local admin users.
|
||||||
|
|
||||||
|
Home Dashboard v1 excludes:
|
||||||
|
|
||||||
|
- README updates.
|
||||||
|
- Real backend accounts.
|
||||||
|
- Server-side learning progress.
|
||||||
|
- Uploading custom thumbnails.
|
||||||
|
- Extracting thumbnails from video files.
|
||||||
|
- Backend search or filter endpoints.
|
||||||
|
- Calendar/check-in features.
|
||||||
|
- Separate pages for favorites or difficult sentences.
|
||||||
|
|
||||||
|
## Layout
|
||||||
|
|
||||||
|
The home page becomes a two-column dashboard on desktop:
|
||||||
|
|
||||||
|
- Left column:
|
||||||
|
- product name and compact learning overview
|
||||||
|
- metric buttons for total, studied, unstudied, favorites, and difficult
|
||||||
|
- Right column:
|
||||||
|
- heading and primary material grid
|
||||||
|
- search and category controls
|
||||||
|
- status text
|
||||||
|
- material cards
|
||||||
|
|
||||||
|
On smaller screens, the overview panel stacks above the grid.
|
||||||
|
|
||||||
|
The design should stay practical and work-focused. It should look like a learning tool, not a marketing landing page.
|
||||||
|
|
||||||
|
## Filters
|
||||||
|
|
||||||
|
Dashboard status filters are represented by metric buttons in the overview panel.
|
||||||
|
|
||||||
|
Filter rules:
|
||||||
|
|
||||||
|
- `all`: every material.
|
||||||
|
- `studied`: material has practiced lines or playback progress.
|
||||||
|
- `unstudied`: material has no practiced lines and no playback progress.
|
||||||
|
- `favorites`: material ID is in the current user's favorites.
|
||||||
|
- `difficult`: material progress has at least one difficult line.
|
||||||
|
|
||||||
|
If the visitor is not logged in:
|
||||||
|
|
||||||
|
- `studied`, `favorites`, and `difficult` counts are zero.
|
||||||
|
- Clicking those filters shows an empty state that asks the learner to log in before tracking personal learning data.
|
||||||
|
- `all` and `unstudied` still work from the material list.
|
||||||
|
|
||||||
|
Search and tag filters combine with the active status filter.
|
||||||
|
|
||||||
|
## Dashboard Metrics
|
||||||
|
|
||||||
|
Metrics are calculated in the browser from loaded videos and local user state.
|
||||||
|
|
||||||
|
Definitions:
|
||||||
|
|
||||||
|
- total materials: number of videos loaded from `/api/videos`.
|
||||||
|
- studied materials: materials with `currentTime > 1`, `activeLineIndex > 0`, or at least one practiced line.
|
||||||
|
- unstudied materials: total minus studied materials for the current user.
|
||||||
|
- favorite materials: current user's `favorites` list intersected with loaded videos.
|
||||||
|
- difficult materials: materials whose progress has at least one difficult line.
|
||||||
|
|
||||||
|
Metrics should update immediately after:
|
||||||
|
|
||||||
|
- login or logout
|
||||||
|
- clicking a favorite button on a card
|
||||||
|
- changing filters
|
||||||
|
- reloading materials
|
||||||
|
|
||||||
|
Study-page progress changes are already stored in localStorage. The home page reads that state when it loads.
|
||||||
|
|
||||||
|
## Material Cards
|
||||||
|
|
||||||
|
Each card displays:
|
||||||
|
|
||||||
|
- generated preview cover
|
||||||
|
- title
|
||||||
|
- speaker/source
|
||||||
|
- tags
|
||||||
|
- subtitle language summary
|
||||||
|
- sentence count
|
||||||
|
- practiced percentage
|
||||||
|
- difficult-line count
|
||||||
|
- progress hint, such as `已练 3/12 · 25%` or `看到 02:04`
|
||||||
|
- favorite button
|
||||||
|
|
||||||
|
Favorite behavior:
|
||||||
|
|
||||||
|
- Clicking the favorite button toggles the current video in the user's `favorites`.
|
||||||
|
- The click does not open the study page.
|
||||||
|
- If no user is logged in, show a short alert asking the learner to log in first.
|
||||||
|
|
||||||
|
Card navigation:
|
||||||
|
|
||||||
|
- Clicking the non-button area opens `study.html?video=<id>`.
|
||||||
|
|
||||||
|
## Empty States
|
||||||
|
|
||||||
|
Empty states should explain the current filter result.
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
|
||||||
|
- No materials at all:
|
||||||
|
- admin user: `还没有素材,去后台添加第一个素材。`
|
||||||
|
- normal visitor: `暂无素材。`
|
||||||
|
- Search or category has no matches:
|
||||||
|
- `没有匹配的素材。`
|
||||||
|
- Personal filter without login:
|
||||||
|
- `登录后可以查看你的学习记录。`
|
||||||
|
- Favorites filter with no favorites:
|
||||||
|
- `还没有收藏素材。`
|
||||||
|
- Difficult filter with no difficult materials:
|
||||||
|
- `还没有标记难句。`
|
||||||
|
|
||||||
|
## State And Data
|
||||||
|
|
||||||
|
No backend changes are required.
|
||||||
|
|
||||||
|
Home Dashboard v1 uses:
|
||||||
|
|
||||||
|
- `GET /api/videos`
|
||||||
|
- `localStorage` key `speaking-lab-state-v1`
|
||||||
|
- existing user shape:
|
||||||
|
- `favorites`
|
||||||
|
- `watchLater`
|
||||||
|
- `progress`
|
||||||
|
|
||||||
|
Helper logic in `home.js` should stay local to the home page. Shared backend schema is unchanged.
|
||||||
|
|
||||||
|
## Error Handling
|
||||||
|
|
||||||
|
If `/api/videos` fails:
|
||||||
|
|
||||||
|
- show the API error or a clear fallback message
|
||||||
|
- clear the grid
|
||||||
|
- avoid crashing metric rendering
|
||||||
|
|
||||||
|
If localStorage is malformed:
|
||||||
|
|
||||||
|
- fall back to an empty user state
|
||||||
|
- continue rendering materials
|
||||||
|
|
||||||
|
If a progress entry refers to a deleted material:
|
||||||
|
|
||||||
|
- ignore it in dashboard metrics
|
||||||
|
|
||||||
|
## Testing
|
||||||
|
|
||||||
|
Automated checks:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
node --check home.js
|
||||||
|
node --check app.js
|
||||||
|
node --check admin.js
|
||||||
|
python -m py_compile backend\main.py backend\db.py
|
||||||
|
node tests\progress-helpers.test.mjs
|
||||||
|
node tests\admin-file-input.test.mjs
|
||||||
|
```
|
||||||
|
|
||||||
|
Manual browser checks:
|
||||||
|
|
||||||
|
1. Open `http://127.0.0.1:8000/`.
|
||||||
|
2. Confirm the dashboard overview appears.
|
||||||
|
3. Confirm materials render as cards.
|
||||||
|
4. Search by title, speaker, and tag.
|
||||||
|
5. Click a category chip and confirm it combines with search.
|
||||||
|
6. Log in as a normal user.
|
||||||
|
7. Favorite a card from the home page and confirm the favorite count updates.
|
||||||
|
8. Click the favorite filter and confirm only favorites show.
|
||||||
|
9. Open a material, mark one line practiced and one line difficult, then return home.
|
||||||
|
10. Confirm studied and difficult counts update after reload.
|
||||||
|
11. Confirm clicking a card opens `study.html?video=<id>`.
|
||||||
|
12. Confirm an admin user still sees the admin link.
|
||||||
|
|
||||||
|
## Future Extensions
|
||||||
|
|
||||||
|
Good follow-up features after this:
|
||||||
|
|
||||||
|
- Upload custom cover images in the admin page.
|
||||||
|
- Add a dedicated difficult-sentence review page.
|
||||||
|
- Add a daily learning/check-in calendar.
|
||||||
|
- Move user progress to SQLite when preparing for shared accounts.
|
||||||
|
- Add real authentication before deploying publicly.
|
||||||
@@ -0,0 +1,215 @@
|
|||||||
|
# Speaking Lab Home Page v1 Design
|
||||||
|
|
||||||
|
## Goal
|
||||||
|
|
||||||
|
Add a dedicated home page for browsing learning materials, so `http://127.0.0.1:8000/` feels like a shareable product entry instead of opening directly inside the study workspace.
|
||||||
|
|
||||||
|
## Current Context
|
||||||
|
|
||||||
|
Speaking Lab currently has:
|
||||||
|
|
||||||
|
- `index.html`: the study page.
|
||||||
|
- `app.js`: study-page logic for loading videos, search, tags, subtitles, recording, favorites, watch-later, and learning progress.
|
||||||
|
- `admin.html` and `admin.js`: admin material management.
|
||||||
|
- `/api/videos`: returns material metadata, tags, video URLs, subtitles, and source type.
|
||||||
|
- Local user state in `localStorage`.
|
||||||
|
|
||||||
|
The current left-side material rail is useful inside the study page, but it is too narrow to work as the product home page.
|
||||||
|
|
||||||
|
## Scope
|
||||||
|
|
||||||
|
Home Page v1 includes:
|
||||||
|
|
||||||
|
- Make `/` open the new home page.
|
||||||
|
- Move the current study experience to `study.html`.
|
||||||
|
- Add `home.html` and `home.js`.
|
||||||
|
- Home page supports searching materials.
|
||||||
|
- Home page supports category filtering from material tags.
|
||||||
|
- Home page shows material cards in a responsive grid.
|
||||||
|
- Cards show an automatic preview cover when no real thumbnail exists.
|
||||||
|
- Cards show title, speaker/source, tags, subtitle languages, and learning progress.
|
||||||
|
- Clicking a card opens `study.html?video=<id>`.
|
||||||
|
- The study page reads `?video=<id>` and opens that material first.
|
||||||
|
- Admin entry remains available for admin users.
|
||||||
|
|
||||||
|
Home Page v1 excludes:
|
||||||
|
|
||||||
|
- Uploading custom thumbnails.
|
||||||
|
- Automatically extracting thumbnails from video files.
|
||||||
|
- Pagination.
|
||||||
|
- Advanced sorting.
|
||||||
|
- Multi-level category management.
|
||||||
|
- Backend search endpoints.
|
||||||
|
- Server-side user authentication.
|
||||||
|
|
||||||
|
## Page Routing
|
||||||
|
|
||||||
|
Routes after this feature:
|
||||||
|
|
||||||
|
```text
|
||||||
|
/
|
||||||
|
```
|
||||||
|
|
||||||
|
Shows the new home page.
|
||||||
|
|
||||||
|
```text
|
||||||
|
/study.html
|
||||||
|
```
|
||||||
|
|
||||||
|
Shows the current learning workspace.
|
||||||
|
|
||||||
|
```text
|
||||||
|
/study.html?video=<id>
|
||||||
|
```
|
||||||
|
|
||||||
|
Opens the learning workspace and selects the requested material.
|
||||||
|
|
||||||
|
```text
|
||||||
|
/admin.html
|
||||||
|
```
|
||||||
|
|
||||||
|
Shows the existing admin page.
|
||||||
|
|
||||||
|
## Home Page Layout
|
||||||
|
|
||||||
|
The home page uses a product-library layout:
|
||||||
|
|
||||||
|
- Top bar:
|
||||||
|
- `Speaking Lab`
|
||||||
|
- Search input
|
||||||
|
- Login/register or current user
|
||||||
|
- Admin link shown only for admin users
|
||||||
|
- Category row:
|
||||||
|
- `全部`
|
||||||
|
- One chip per tag from loaded materials
|
||||||
|
- Main content:
|
||||||
|
- Responsive grid of material cards
|
||||||
|
- Empty state when no materials match
|
||||||
|
|
||||||
|
The home page should be practical and product-like, not a marketing landing page. It should prioritize finding and opening materials.
|
||||||
|
|
||||||
|
## Material Card
|
||||||
|
|
||||||
|
Each card displays:
|
||||||
|
|
||||||
|
- Preview cover area.
|
||||||
|
- Title.
|
||||||
|
- Speaker/source.
|
||||||
|
- Tags.
|
||||||
|
- Subtitle language summary, for example `英文 / 中文`.
|
||||||
|
- Learning progress summary, for example `已练 2/15 · 13%` or `看到 02:04`.
|
||||||
|
|
||||||
|
Clicking anywhere on a card opens:
|
||||||
|
|
||||||
|
```text
|
||||||
|
study.html?video=<id>
|
||||||
|
```
|
||||||
|
|
||||||
|
## Preview Cover Strategy
|
||||||
|
|
||||||
|
Home Page v1 uses generated CSS preview covers instead of real video thumbnails.
|
||||||
|
|
||||||
|
Reason:
|
||||||
|
|
||||||
|
- Local and remote videos may not be safe or easy to screenshot in the browser.
|
||||||
|
- Cross-origin video URLs may block frame extraction.
|
||||||
|
- A generated cover is reliable and fast for the prototype.
|
||||||
|
|
||||||
|
Generated cover contents:
|
||||||
|
|
||||||
|
- Large short title or initials.
|
||||||
|
- First tag as a category badge.
|
||||||
|
- Subtle color variant based on material ID.
|
||||||
|
|
||||||
|
Future extension:
|
||||||
|
|
||||||
|
- Add a backend `thumbnail_url` field.
|
||||||
|
- Allow admin upload of cover images.
|
||||||
|
- Show real thumbnail when available, generated cover as fallback.
|
||||||
|
|
||||||
|
## Search And Category Behavior
|
||||||
|
|
||||||
|
Search matches:
|
||||||
|
|
||||||
|
- Title.
|
||||||
|
- Speaker/source.
|
||||||
|
- Description.
|
||||||
|
- Tags.
|
||||||
|
|
||||||
|
Category filtering:
|
||||||
|
|
||||||
|
- `全部` shows all materials.
|
||||||
|
- Clicking a tag chip filters cards whose tags include that tag.
|
||||||
|
- Search and category filters combine.
|
||||||
|
|
||||||
|
## Study Page Behavior
|
||||||
|
|
||||||
|
The current study page becomes `study.html`.
|
||||||
|
|
||||||
|
Changes:
|
||||||
|
|
||||||
|
- It keeps existing playback, subtitles, recording, progress, favorites, and admin entry behavior.
|
||||||
|
- On load, it checks `URLSearchParams` for `video`.
|
||||||
|
- If the requested video exists, it selects that video.
|
||||||
|
- If the requested video does not exist, it falls back to existing active-video behavior.
|
||||||
|
|
||||||
|
The study page may keep the left material rail for quick switching during learning.
|
||||||
|
|
||||||
|
## State And Data
|
||||||
|
|
||||||
|
Home page uses:
|
||||||
|
|
||||||
|
- `GET /api/videos` for materials.
|
||||||
|
- The same `speaking-lab-state-v1` localStorage key for users and progress.
|
||||||
|
|
||||||
|
No new database table is required.
|
||||||
|
|
||||||
|
No backend API change is required for Home Page v1.
|
||||||
|
|
||||||
|
## Error Handling
|
||||||
|
|
||||||
|
If `/api/videos` fails:
|
||||||
|
|
||||||
|
- Show a clear local error state.
|
||||||
|
- Home page may show demo/sample materials only if the study page already uses those as fallback.
|
||||||
|
|
||||||
|
If no materials exist:
|
||||||
|
|
||||||
|
- Show an empty state that points admin users to `admin.html`.
|
||||||
|
- Non-admin users see a simple “暂无素材” state.
|
||||||
|
|
||||||
|
If `study.html?video=<id>` references a missing material:
|
||||||
|
|
||||||
|
- Select the first available material.
|
||||||
|
- Do not crash.
|
||||||
|
|
||||||
|
## Testing
|
||||||
|
|
||||||
|
Automated checks:
|
||||||
|
|
||||||
|
- `node --check home.js`
|
||||||
|
- `node --check app.js`
|
||||||
|
- Existing helper tests still pass.
|
||||||
|
|
||||||
|
Manual/browser verification:
|
||||||
|
|
||||||
|
1. Open `http://127.0.0.1:8000/`.
|
||||||
|
2. Confirm the home page appears, not the study workspace.
|
||||||
|
3. Confirm materials render as cards.
|
||||||
|
4. Confirm search filters by title/source/tag.
|
||||||
|
5. Confirm category chips filter cards.
|
||||||
|
6. Confirm each card has a generated preview cover.
|
||||||
|
7. Click a card.
|
||||||
|
8. Confirm `study.html?video=<id>` opens and selects that material.
|
||||||
|
9. Confirm `admin.html` still works.
|
||||||
|
10. Confirm logged-in admin users can see an admin entry on the home page.
|
||||||
|
|
||||||
|
## Future Extensions
|
||||||
|
|
||||||
|
Good follow-up features:
|
||||||
|
|
||||||
|
- Upload custom thumbnail in admin page.
|
||||||
|
- Add `我的学习` section on the home page.
|
||||||
|
- Add sorting by recently studied, newest, or most practiced.
|
||||||
|
- Add collections or curated playlists.
|
||||||
|
- Move search/filter to backend when the library becomes large.
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
# Speaking Lab Material Edit v1 Design
|
||||||
|
|
||||||
|
## Goal
|
||||||
|
|
||||||
|
Allow an admin to update already uploaded materials without deleting and recreating them.
|
||||||
|
|
||||||
|
## Scope
|
||||||
|
|
||||||
|
Material Edit v1 includes:
|
||||||
|
|
||||||
|
- Add an `编辑` action to each material in the admin list.
|
||||||
|
- Load the selected material into the existing admin form.
|
||||||
|
- Allow editing title, speaker/source, description, tags, and video URL.
|
||||||
|
- Allow replacing the video file.
|
||||||
|
- Allow replacing English and Chinese subtitle files independently.
|
||||||
|
- Preserve existing files when no replacement file is selected.
|
||||||
|
- Save changes through `PATCH /api/videos/{video_id}`.
|
||||||
|
- Clean up old local uploaded files when they are replaced.
|
||||||
|
- Add `取消编辑` to return the form to add mode.
|
||||||
|
|
||||||
|
Material Edit v1 excludes:
|
||||||
|
|
||||||
|
- Rich subtitle editing in the browser.
|
||||||
|
- Removing a single subtitle without replacing it.
|
||||||
|
- Server-side authentication or permissions.
|
||||||
|
- Version history or undo.
|
||||||
|
|
||||||
|
## Backend Behavior
|
||||||
|
|
||||||
|
`PATCH /api/videos/{video_id}` accepts multipart form data:
|
||||||
|
|
||||||
|
- `title`
|
||||||
|
- `speaker`
|
||||||
|
- `description`
|
||||||
|
- `tags`
|
||||||
|
- `video_url`
|
||||||
|
- optional `video_file`
|
||||||
|
- optional `subtitle_en`
|
||||||
|
- optional `subtitle_zh`
|
||||||
|
|
||||||
|
Rules:
|
||||||
|
|
||||||
|
- Title is required.
|
||||||
|
- If a new video file is uploaded, it replaces the old video source.
|
||||||
|
- If no new video file is uploaded, `video_url` is used as the video source.
|
||||||
|
- If `video_url` is left empty during edit and no video file is uploaded, the existing video source is preserved.
|
||||||
|
- Replaced local files under `/uploads/...` are deleted safely.
|
||||||
|
- Remote `http://` / `https://` URLs are never deleted as files.
|
||||||
|
|
||||||
|
## Frontend Behavior
|
||||||
|
|
||||||
|
Admin page form has two modes:
|
||||||
|
|
||||||
|
- Add mode: submit creates a new material.
|
||||||
|
- Edit mode: submit updates the selected material.
|
||||||
|
|
||||||
|
When entering edit mode:
|
||||||
|
|
||||||
|
- Form heading changes to `编辑素材`.
|
||||||
|
- Submit button changes to `保存修改`.
|
||||||
|
- Existing text fields are filled.
|
||||||
|
- File buttons show that existing files are retained unless replaced.
|
||||||
|
- Material being edited is visually highlighted in the list.
|
||||||
|
|
||||||
|
When update succeeds:
|
||||||
|
|
||||||
|
- Form resets to add mode.
|
||||||
|
- Material list refreshes.
|
||||||
|
- Success message says `素材已更新。`
|
||||||
|
|
||||||
|
## Verification
|
||||||
|
|
||||||
|
- Static checks pass.
|
||||||
|
- Create a temporary material through API.
|
||||||
|
- Patch its title/tags.
|
||||||
|
- Patch its subtitle or video file when a local test file is available.
|
||||||
|
- Confirm `GET /api/videos/{id}` returns updated data.
|
||||||
|
- Delete the temporary material.
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
# Speaking Lab Study Focus Layout Design
|
||||||
|
|
||||||
|
## Goal
|
||||||
|
|
||||||
|
Make the study page focus on the active learning session by removing the left material rail. Material discovery now lives on the home page, so the study page should give more room to the video, subtitle controls, and transcript.
|
||||||
|
|
||||||
|
## Scope
|
||||||
|
|
||||||
|
Included:
|
||||||
|
|
||||||
|
- Remove the left material rail from `study.html`.
|
||||||
|
- Let the video learning panel occupy the space previously used by the rail.
|
||||||
|
- Keep the right transcript panel.
|
||||||
|
- Keep video playback, line navigation, recording, subtitles, continue learning, favorites, and watch-later.
|
||||||
|
- Keep admin access on the home page; the study page no longer needs the rail-side admin button.
|
||||||
|
- Add JavaScript guards so removed rail elements do not cause runtime errors.
|
||||||
|
|
||||||
|
Excluded:
|
||||||
|
|
||||||
|
- Home page changes.
|
||||||
|
- README changes.
|
||||||
|
- Backend changes.
|
||||||
|
- Admin page changes.
|
||||||
|
- New navigation or routing.
|
||||||
|
|
||||||
|
## Behavior
|
||||||
|
|
||||||
|
The study page still opens the selected material from `study.html?video=<id>`.
|
||||||
|
|
||||||
|
If the user opens `study.html` directly:
|
||||||
|
|
||||||
|
- The page selects the previously active video or the first available video.
|
||||||
|
- The user can return to the home page manually through browser navigation or direct URL.
|
||||||
|
|
||||||
|
The material list search and tag filtering UI is removed from the study page.
|
||||||
|
|
||||||
|
## Testing
|
||||||
|
|
||||||
|
Run:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
node --check app.js
|
||||||
|
node --check home.js
|
||||||
|
node --check admin.js
|
||||||
|
node tests\progress-helpers.test.mjs
|
||||||
|
node tests\admin-file-input.test.mjs
|
||||||
|
```
|
||||||
|
|
||||||
|
Manual checks:
|
||||||
|
|
||||||
|
1. Open `http://127.0.0.1:8000/study.html`.
|
||||||
|
2. Confirm the left material rail is gone.
|
||||||
|
3. Confirm the video panel starts near the left edge of the study layout.
|
||||||
|
4. Confirm subtitle tabs and transcript still render.
|
||||||
|
5. Open from a home card and confirm `study.html?video=<id>` still selects the material.
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
# Speaking Lab Subtitle Delete Cues Design
|
||||||
|
|
||||||
|
## Goal
|
||||||
|
|
||||||
|
Allow an admin to delete problematic subtitle cue blocks from an already uploaded material without editing cue text or timestamps.
|
||||||
|
|
||||||
|
## Scope
|
||||||
|
|
||||||
|
Included:
|
||||||
|
|
||||||
|
- Add subtitle cue deletion UI in the existing admin edit flow.
|
||||||
|
- Support English and Chinese subtitle tracks independently.
|
||||||
|
- Delete whole cue blocks only.
|
||||||
|
- Save updated subtitle content through the existing material update request.
|
||||||
|
- Keep existing subtitle file replacement support.
|
||||||
|
|
||||||
|
Excluded:
|
||||||
|
|
||||||
|
- Editing subtitle text.
|
||||||
|
- Editing timestamps.
|
||||||
|
- Reordering subtitle cues.
|
||||||
|
- Deleting video materials.
|
||||||
|
- Study page subtitle editing.
|
||||||
|
- README changes.
|
||||||
|
|
||||||
|
## Backend
|
||||||
|
|
||||||
|
Extend `PATCH /api/videos/{video_id}` with optional form fields:
|
||||||
|
|
||||||
|
- `subtitle_en_content`
|
||||||
|
- `subtitle_zh_content`
|
||||||
|
|
||||||
|
When those fields are provided and no replacement upload is provided for that language, update the corresponding subtitle row content in SQLite.
|
||||||
|
|
||||||
|
Existing uploaded subtitle file paths can stay unchanged because this local prototype reads subtitle content from the database response.
|
||||||
|
|
||||||
|
## Admin UI
|
||||||
|
|
||||||
|
When an admin clicks `编辑` on a material:
|
||||||
|
|
||||||
|
- Show an English subtitle deletion section if the material has English subtitle content.
|
||||||
|
- Show a Chinese subtitle deletion section if the material has Chinese subtitle content.
|
||||||
|
- Each cue shows time range and text.
|
||||||
|
- Each cue has a `删除` button.
|
||||||
|
- Deleted cues disappear from the list immediately.
|
||||||
|
- Saving the material submits the remaining subtitle content.
|
||||||
|
|
||||||
|
When the admin cancels editing or starts editing another material, subtitle deletion state resets.
|
||||||
|
|
||||||
|
## Testing
|
||||||
|
|
||||||
|
Run:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
python -m py_compile backend\main.py backend\db.py
|
||||||
|
node --check admin.js
|
||||||
|
node --check app.js
|
||||||
|
node --check home.js
|
||||||
|
node tests\admin-file-input.test.mjs
|
||||||
|
node tests\progress-helpers.test.mjs
|
||||||
|
```
|
||||||
|
|
||||||
|
Manual checks:
|
||||||
|
|
||||||
|
1. Log in as admin and open `admin.html`.
|
||||||
|
2. Edit a material with subtitles.
|
||||||
|
3. Delete one subtitle cue.
|
||||||
|
4. Save.
|
||||||
|
5. Reopen the material in study page and confirm the deleted cue is gone.
|
||||||
@@ -0,0 +1,191 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="zh-CN">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<title>Speaking Lab UI Style Options</title>
|
||||||
|
<style>
|
||||||
|
* { box-sizing: border-box; }
|
||||||
|
body {
|
||||||
|
margin: 0;
|
||||||
|
background: #f3f5f8;
|
||||||
|
color: #172033;
|
||||||
|
font-family: Inter, ui-sans-serif, system-ui, "Segoe UI", sans-serif;
|
||||||
|
}
|
||||||
|
main {
|
||||||
|
max-width: 1180px;
|
||||||
|
margin: 0 auto;
|
||||||
|
padding: 28px;
|
||||||
|
}
|
||||||
|
h1 { margin: 0; font-size: 24px; }
|
||||||
|
.intro { margin: 8px 0 22px; color: #667085; }
|
||||||
|
.grid {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(3, minmax(0, 1fr));
|
||||||
|
gap: 16px;
|
||||||
|
}
|
||||||
|
.option {
|
||||||
|
overflow: hidden;
|
||||||
|
border: 1px solid #d8dee8;
|
||||||
|
border-radius: 10px;
|
||||||
|
background: #fff;
|
||||||
|
box-shadow: 0 16px 36px rgba(20, 29, 45, 0.08);
|
||||||
|
}
|
||||||
|
.option-body { padding: 14px; }
|
||||||
|
.option h2 { margin: 0 0 6px; font-size: 17px; }
|
||||||
|
.option p { margin: 0; color: #667085; font-size: 13px; line-height: 1.5; }
|
||||||
|
.mock {
|
||||||
|
min-height: 470px;
|
||||||
|
padding: 14px;
|
||||||
|
border-bottom: 1px solid #e4e7ec;
|
||||||
|
}
|
||||||
|
.mock-top {
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: center;
|
||||||
|
margin-bottom: 14px;
|
||||||
|
font-size: 12px;
|
||||||
|
font-weight: 800;
|
||||||
|
}
|
||||||
|
.pill {
|
||||||
|
border-radius: 999px;
|
||||||
|
padding: 4px 8px;
|
||||||
|
font-size: 11px;
|
||||||
|
}
|
||||||
|
.mock-layout {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: 92px 1fr;
|
||||||
|
gap: 10px;
|
||||||
|
}
|
||||||
|
.side, .panel, .card, .video, .line {
|
||||||
|
border-radius: 8px;
|
||||||
|
}
|
||||||
|
.side {
|
||||||
|
display: grid;
|
||||||
|
gap: 8px;
|
||||||
|
}
|
||||||
|
.metric { padding: 9px; font-size: 11px; font-weight: 800; }
|
||||||
|
.metric strong { float: right; font-size: 18px; }
|
||||||
|
.content { display: grid; gap: 10px; }
|
||||||
|
.search { height: 30px; border-radius: 7px; }
|
||||||
|
.cards { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; }
|
||||||
|
.card { min-height: 112px; padding: 9px; }
|
||||||
|
.card-cover { height: 46px; border-radius: 7px; margin-bottom: 8px; }
|
||||||
|
.small-line { height: 8px; border-radius: 999px; margin-top: 6px; }
|
||||||
|
.study-mock { display: grid; grid-template-columns: 1.15fr .85fr; gap: 10px; }
|
||||||
|
.video { height: 150px; }
|
||||||
|
.subtitle { padding: 11px; text-align: center; font-size: 12px; font-weight: 800; }
|
||||||
|
.transcript { display: grid; gap: 7px; }
|
||||||
|
.line { padding: 8px; font-size: 11px; }
|
||||||
|
.a .mock { background: #f6f8fb; }
|
||||||
|
.a .pill, .a .metric.active { color: #fff; background: #111827; }
|
||||||
|
.a .metric, .a .card, .a .line, .a .subtitle { background: #fff; border: 1px solid #e1e6ef; }
|
||||||
|
.a .search, .a .small-line { background: #e6ebf2; }
|
||||||
|
.a .card-cover, .a .video { background: linear-gradient(135deg, #0f766e, #164e63); }
|
||||||
|
.b .mock { background: #f4fbf9; }
|
||||||
|
.b .pill, .b .metric.active { color: #063f3b; background: #bff1df; }
|
||||||
|
.b .metric, .b .card, .b .line, .b .subtitle { background: #ffffff; border: 1px solid #cde9df; }
|
||||||
|
.b .search, .b .small-line { background: #dff5ed; }
|
||||||
|
.b .card-cover, .b .video { background: linear-gradient(135deg, #0f766e, #22c55e); }
|
||||||
|
.c .mock { background: #fff8ec; }
|
||||||
|
.c .pill, .c .metric.active { color: #fff; background: #9a5c00; }
|
||||||
|
.c .metric, .c .card, .c .line, .c .subtitle { background: #fffdf8; border: 1px solid #f0dfbf; }
|
||||||
|
.c .search, .c .small-line { background: #f6e7c8; }
|
||||||
|
.c .card-cover, .c .video { background: linear-gradient(135deg, #1f2937, #c98a12); }
|
||||||
|
@media (max-width: 900px) {
|
||||||
|
.grid { grid-template-columns: 1fr; }
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<main>
|
||||||
|
<h1>选择一个更适合英语学习的 UI 气质</h1>
|
||||||
|
<p class="intro">先看整体感觉,不用纠结细节。选定方向后,再把它应用到首页和学习页。</p>
|
||||||
|
<section class="grid">
|
||||||
|
<article class="option a">
|
||||||
|
<div class="mock">
|
||||||
|
<div class="mock-top"><span>Speaking Lab</span><span class="pill">专注练习</span></div>
|
||||||
|
<div class="mock-layout">
|
||||||
|
<div class="side">
|
||||||
|
<div class="metric active">当前 <strong>12</strong></div>
|
||||||
|
<div class="metric">已学 <strong>3</strong></div>
|
||||||
|
<div class="metric">难句 <strong>8</strong></div>
|
||||||
|
</div>
|
||||||
|
<div class="content">
|
||||||
|
<div class="search"></div>
|
||||||
|
<div class="cards">
|
||||||
|
<div class="card"><div class="card-cover"></div><b>TED Talk</b><div class="small-line"></div></div>
|
||||||
|
<div class="card"><div class="card-cover"></div><b>Interview</b><div class="small-line"></div></div>
|
||||||
|
</div>
|
||||||
|
<div class="study-mock">
|
||||||
|
<div><div class="video"></div><div class="subtitle">Shadowing one sentence at a time</div></div>
|
||||||
|
<div class="transcript"><div class="line">00:12 English sentence</div><div class="line">中文释义</div><div class="line">已练 · 难句</div></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="option-body">
|
||||||
|
<h2>A. 清爽专注型</h2>
|
||||||
|
<p>像学习工作台,安静、克制、信息清楚。适合长期使用,不容易视觉疲劳。</p>
|
||||||
|
</div>
|
||||||
|
</article>
|
||||||
|
|
||||||
|
<article class="option b">
|
||||||
|
<div class="mock">
|
||||||
|
<div class="mock-top"><span>Speaking Lab</span><span class="pill">口语成长</span></div>
|
||||||
|
<div class="mock-layout">
|
||||||
|
<div class="side">
|
||||||
|
<div class="metric active">当前 <strong>12</strong></div>
|
||||||
|
<div class="metric">已学 <strong>3</strong></div>
|
||||||
|
<div class="metric">难句 <strong>8</strong></div>
|
||||||
|
</div>
|
||||||
|
<div class="content">
|
||||||
|
<div class="search"></div>
|
||||||
|
<div class="cards">
|
||||||
|
<div class="card"><div class="card-cover"></div><b>TED Talk</b><div class="small-line"></div></div>
|
||||||
|
<div class="card"><div class="card-cover"></div><b>Interview</b><div class="small-line"></div></div>
|
||||||
|
</div>
|
||||||
|
<div class="study-mock">
|
||||||
|
<div><div class="video"></div><div class="subtitle">Listen · Repeat · Review</div></div>
|
||||||
|
<div class="transcript"><div class="line">00:12 English sentence</div><div class="line">中文释义</div><div class="line">已练 · 难句</div></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="option-body">
|
||||||
|
<h2>B. 轻松成长型</h2>
|
||||||
|
<p>更亲和、有一点绿色成长感。看起来更像个人学习 App,氛围轻松。</p>
|
||||||
|
</div>
|
||||||
|
</article>
|
||||||
|
|
||||||
|
<article class="option c">
|
||||||
|
<div class="mock">
|
||||||
|
<div class="mock-top"><span>Speaking Lab</span><span class="pill">精听课堂</span></div>
|
||||||
|
<div class="mock-layout">
|
||||||
|
<div class="side">
|
||||||
|
<div class="metric active">当前 <strong>12</strong></div>
|
||||||
|
<div class="metric">已学 <strong>3</strong></div>
|
||||||
|
<div class="metric">难句 <strong>8</strong></div>
|
||||||
|
</div>
|
||||||
|
<div class="content">
|
||||||
|
<div class="search"></div>
|
||||||
|
<div class="cards">
|
||||||
|
<div class="card"><div class="card-cover"></div><b>TED Talk</b><div class="small-line"></div></div>
|
||||||
|
<div class="card"><div class="card-cover"></div><b>Interview</b><div class="small-line"></div></div>
|
||||||
|
</div>
|
||||||
|
<div class="study-mock">
|
||||||
|
<div><div class="video"></div><div class="subtitle">Comprehension first, fluency later</div></div>
|
||||||
|
<div class="transcript"><div class="line">00:12 English sentence</div><div class="line">中文释义</div><div class="line">已练 · 难句</div></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="option-body">
|
||||||
|
<h2>C. 精听课堂型</h2>
|
||||||
|
<p>更像课程/训练营,暖色更明显。适合做“认真学习”的感觉,但可能稍重。</p>
|
||||||
|
</div>
|
||||||
|
</article>
|
||||||
|
</section>
|
||||||
|
</main>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,493 @@
|
|||||||
|
const STORAGE_KEY = "speaking-lab-state-v1";
|
||||||
|
|
||||||
|
const els = {
|
||||||
|
searchInput: document.querySelector("#homeSearchInput"),
|
||||||
|
loginForm: document.querySelector("#homeLoginForm"),
|
||||||
|
emailInput: document.querySelector("#homeEmailInput"),
|
||||||
|
passwordInput: document.querySelector("#homePasswordInput"),
|
||||||
|
userMenu: document.querySelector("#homeUserMenu"),
|
||||||
|
userLabel: document.querySelector("#homeUserLabel"),
|
||||||
|
logoutBtn: document.querySelector("#homeLogoutBtn"),
|
||||||
|
adminLink: document.querySelector("#homeAdminLink"),
|
||||||
|
dashboardUser: document.querySelector("#homeDashboardUser"),
|
||||||
|
metricFilters: document.querySelector("#homeMetricFilters"),
|
||||||
|
categoryFilters: document.querySelector("#homeCategoryFilters"),
|
||||||
|
status: document.querySelector("#homeStatus"),
|
||||||
|
grid: document.querySelector("#homeGrid"),
|
||||||
|
};
|
||||||
|
|
||||||
|
let state = loadState();
|
||||||
|
let videos = [];
|
||||||
|
let activeTag = "全部";
|
||||||
|
let activeStatus = "all";
|
||||||
|
|
||||||
|
bindEvents();
|
||||||
|
initializeHome();
|
||||||
|
|
||||||
|
function bindEvents() {
|
||||||
|
els.searchInput.addEventListener("input", renderHome);
|
||||||
|
els.loginForm.addEventListener("submit", (event) => {
|
||||||
|
event.preventDefault();
|
||||||
|
loginOrRegister();
|
||||||
|
});
|
||||||
|
els.logoutBtn.addEventListener("click", () => {
|
||||||
|
state.currentUserId = null;
|
||||||
|
saveState();
|
||||||
|
renderAccount();
|
||||||
|
renderHome();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async function initializeHome() {
|
||||||
|
renderAccount();
|
||||||
|
els.status.textContent = "正在加载素材...";
|
||||||
|
|
||||||
|
try {
|
||||||
|
videos = await apiRequest("/api/videos");
|
||||||
|
renderHome();
|
||||||
|
} catch (error) {
|
||||||
|
els.status.textContent = error.message || "素材加载失败。";
|
||||||
|
els.grid.innerHTML = "";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function apiRequest(path, options = {}) {
|
||||||
|
const response = await fetch(path, options);
|
||||||
|
if (!response.ok) {
|
||||||
|
let message = "请求失败,请重试。";
|
||||||
|
try {
|
||||||
|
const payload = await response.json();
|
||||||
|
message = payload.detail || message;
|
||||||
|
} catch {
|
||||||
|
message = response.statusText || message;
|
||||||
|
}
|
||||||
|
throw new Error(message);
|
||||||
|
}
|
||||||
|
return response.json();
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderHome() {
|
||||||
|
renderDashboard();
|
||||||
|
renderCategories();
|
||||||
|
const filtered = getFilteredVideos();
|
||||||
|
const emptyMessage = getEmptyMessage(filtered);
|
||||||
|
|
||||||
|
els.status.textContent = filtered.length ? `${filtered.length} 个素材` : emptyMessage;
|
||||||
|
els.grid.innerHTML = "";
|
||||||
|
|
||||||
|
if (!filtered.length) return;
|
||||||
|
|
||||||
|
const fragment = document.createDocumentFragment();
|
||||||
|
filtered.forEach((video) => {
|
||||||
|
fragment.appendChild(createVideoCard(video));
|
||||||
|
});
|
||||||
|
els.grid.appendChild(fragment);
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderCategories() {
|
||||||
|
const tags = ["全部", ...new Set(videos.flatMap((video) => normalizeTags(video.tags)))];
|
||||||
|
els.categoryFilters.innerHTML = "";
|
||||||
|
|
||||||
|
tags.forEach((tag) => {
|
||||||
|
const button = document.createElement("button");
|
||||||
|
button.type = "button";
|
||||||
|
button.className = `chip${tag === activeTag ? " active" : ""}`;
|
||||||
|
button.textContent = tag;
|
||||||
|
button.addEventListener("click", () => {
|
||||||
|
activeTag = tag;
|
||||||
|
renderHome();
|
||||||
|
});
|
||||||
|
els.categoryFilters.appendChild(button);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderDashboard() {
|
||||||
|
const user = getCurrentUser();
|
||||||
|
const metrics = calculateDashboardMetrics(user);
|
||||||
|
els.dashboardUser.textContent = user ? user.email : "登录后记录进度";
|
||||||
|
els.metricFilters.innerHTML = "";
|
||||||
|
|
||||||
|
getMetricItems(metrics).forEach((item) => {
|
||||||
|
const button = document.createElement("button");
|
||||||
|
button.type = "button";
|
||||||
|
button.className = `home-metric tone-${item.tone}${activeStatus === item.key ? " active" : ""}`;
|
||||||
|
button.dataset.status = item.key;
|
||||||
|
button.innerHTML = `
|
||||||
|
<span class="home-metric-icon" aria-hidden="true">${item.icon}</span>
|
||||||
|
<span class="home-metric-copy">
|
||||||
|
<span class="home-metric-label">${item.label}</span>
|
||||||
|
<small>${item.hint}</small>
|
||||||
|
</span>
|
||||||
|
<strong>${item.value}</strong>
|
||||||
|
`;
|
||||||
|
button.addEventListener("click", () => {
|
||||||
|
activeStatus = item.key;
|
||||||
|
renderHome();
|
||||||
|
});
|
||||||
|
els.metricFilters.appendChild(button);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function getMetricItems(metrics) {
|
||||||
|
return [
|
||||||
|
{ key: "all", label: "当前素材", value: metrics.total, hint: "持续更新中", icon: "::", tone: "blue" },
|
||||||
|
{ key: "studied", label: "已学习", value: metrics.studied, hint: "我的打卡", icon: "✓", tone: "green" },
|
||||||
|
{ key: "unstudied", label: "未学习", value: metrics.unstudied, hint: "未完成", icon: "○", tone: "slate" },
|
||||||
|
{ key: "favorites", label: "已收藏", value: metrics.favorites, hint: "收藏的视频", icon: "♡", tone: "rose" },
|
||||||
|
{ key: "difficult", label: "难句素材", value: metrics.difficult, hint: "重点复习", icon: "!", tone: "amber" },
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
function calculateDashboardMetrics(user) {
|
||||||
|
const loadedIds = new Set(videos.map((video) => String(video.id)));
|
||||||
|
const studied = videos.filter((video) => hasStudyProgress(user, video.id)).length;
|
||||||
|
const favoriteIds = new Set((user?.favorites || []).map(String));
|
||||||
|
const favorites = [...favoriteIds].filter((id) => loadedIds.has(id)).length;
|
||||||
|
const difficult = videos.filter((video) => getVideoProgress(user, video.id).difficultLineIndexes.length > 0).length;
|
||||||
|
|
||||||
|
return {
|
||||||
|
total: videos.length,
|
||||||
|
studied,
|
||||||
|
unstudied: Math.max(0, videos.length - studied),
|
||||||
|
favorites,
|
||||||
|
difficult,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function hasStudyProgress(user, videoId) {
|
||||||
|
if (!user) return false;
|
||||||
|
const progress = getVideoProgress(user, videoId);
|
||||||
|
return progress.currentTime > 1
|
||||||
|
|| progress.activeLineIndex > 0
|
||||||
|
|| progress.practicedLineIndexes.length > 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
function createVideoCard(video) {
|
||||||
|
const card = document.createElement("article");
|
||||||
|
const user = getCurrentUser();
|
||||||
|
const tags = normalizeTags(video.tags);
|
||||||
|
const subtitleLabel = getSubtitleLabel(video);
|
||||||
|
const totalLines = getDefaultCueCount(video);
|
||||||
|
const progress = getVideoProgress(user, video.id);
|
||||||
|
const summary = calculatePracticeSummary(progress, totalLines);
|
||||||
|
const progressLabel = formatProgressSummary(progress, totalLines);
|
||||||
|
const difficultCount = progress.difficultLineIndexes.filter((index) => index < totalLines || totalLines === 0).length;
|
||||||
|
const coverTone = getCoverTone(video.id);
|
||||||
|
const isFavorite = Boolean(user?.favorites.map(String).includes(String(video.id)));
|
||||||
|
|
||||||
|
card.className = "home-card";
|
||||||
|
card.innerHTML = `
|
||||||
|
<div class="home-cover tone-${coverTone}">
|
||||||
|
<span class="home-cover-badge"></span>
|
||||||
|
<button class="home-favorite" type="button" aria-label="收藏素材"></button>
|
||||||
|
<strong></strong>
|
||||||
|
</div>
|
||||||
|
<a class="home-card-link" href="./study.html?video=${encodeURIComponent(video.id)}">
|
||||||
|
<div class="home-card-body">
|
||||||
|
<h3></h3>
|
||||||
|
<p class="home-card-meta"></p>
|
||||||
|
<div class="home-card-tags"></div>
|
||||||
|
<dl class="home-card-stats">
|
||||||
|
<div>
|
||||||
|
<dt>句子</dt>
|
||||||
|
<dd></dd>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<dt>进度</dt>
|
||||||
|
<dd></dd>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<dt>难句</dt>
|
||||||
|
<dd></dd>
|
||||||
|
</div>
|
||||||
|
</dl>
|
||||||
|
<p class="home-card-subtitles"></p>
|
||||||
|
<p class="home-progress" hidden></p>
|
||||||
|
</div>
|
||||||
|
</a>
|
||||||
|
`;
|
||||||
|
|
||||||
|
card.querySelector(".home-cover-badge").textContent = tags[0] || "素材";
|
||||||
|
card.querySelector(".home-cover strong").textContent = getCoverText(video.title);
|
||||||
|
card.querySelector("h3").textContent = video.title || "Untitled";
|
||||||
|
card.querySelector(".home-card-meta").textContent = video.speaker || "Unknown";
|
||||||
|
card.querySelector(".home-card-tags").append(...tags.map(createTagPill));
|
||||||
|
card.querySelector(".home-card-subtitles").textContent = subtitleLabel;
|
||||||
|
|
||||||
|
const statValues = card.querySelectorAll(".home-card-stats dd");
|
||||||
|
statValues[0].textContent = totalLines ? `${totalLines}` : "-";
|
||||||
|
statValues[1].textContent = totalLines ? `${summary.percent}%` : "未开始";
|
||||||
|
statValues[2].textContent = `${difficultCount}`;
|
||||||
|
|
||||||
|
const favorite = card.querySelector(".home-favorite");
|
||||||
|
favorite.textContent = isFavorite ? "已收藏" : "收藏";
|
||||||
|
favorite.classList.toggle("active", isFavorite);
|
||||||
|
favorite.addEventListener("click", (event) => {
|
||||||
|
event.preventDefault();
|
||||||
|
event.stopPropagation();
|
||||||
|
toggleFavorite(video.id);
|
||||||
|
});
|
||||||
|
|
||||||
|
const progressNode = card.querySelector(".home-progress");
|
||||||
|
progressNode.textContent = progressLabel || "还未开始";
|
||||||
|
progressNode.hidden = false;
|
||||||
|
|
||||||
|
return card;
|
||||||
|
}
|
||||||
|
|
||||||
|
function createTagPill(tag) {
|
||||||
|
const span = document.createElement("span");
|
||||||
|
span.textContent = tag;
|
||||||
|
return span;
|
||||||
|
}
|
||||||
|
|
||||||
|
function getFilteredVideos() {
|
||||||
|
const query = els.searchInput.value.trim().toLowerCase();
|
||||||
|
const user = getCurrentUser();
|
||||||
|
|
||||||
|
return videos.filter((video) => {
|
||||||
|
const tags = normalizeTags(video.tags);
|
||||||
|
const matchesTag = activeTag === "全部" || tags.includes(activeTag);
|
||||||
|
const matchesStatus = matchesStatusFilter(video, user);
|
||||||
|
const haystack = [video.title, video.speaker, video.description, tags.join(" ")]
|
||||||
|
.join(" ")
|
||||||
|
.toLowerCase();
|
||||||
|
return matchesTag && matchesStatus && (!query || haystack.includes(query));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function matchesStatusFilter(video, user) {
|
||||||
|
if (activeStatus === "all") return true;
|
||||||
|
if (activeStatus === "studied") return hasStudyProgress(user, video.id);
|
||||||
|
if (activeStatus === "unstudied") return !hasStudyProgress(user, video.id);
|
||||||
|
if (activeStatus === "favorites") return Boolean(user?.favorites.map(String).includes(String(video.id)));
|
||||||
|
if (activeStatus === "difficult") return getVideoProgress(user, video.id).difficultLineIndexes.length > 0;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
function getEmptyMessage(filtered) {
|
||||||
|
const user = getCurrentUser();
|
||||||
|
const query = els.searchInput.value.trim();
|
||||||
|
|
||||||
|
if (!videos.length) {
|
||||||
|
return isAdmin(user) ? "还没有素材,去后台添加第一个素材。" : "暂无素材。";
|
||||||
|
}
|
||||||
|
if (!user && ["studied", "favorites", "difficult"].includes(activeStatus)) {
|
||||||
|
return "登录后可以查看你的学习记录。";
|
||||||
|
}
|
||||||
|
if (activeStatus === "favorites") return "还没有收藏素材。";
|
||||||
|
if (activeStatus === "difficult") return "还没有标记难句。";
|
||||||
|
if (query || activeTag !== "全部") return "没有匹配的素材。";
|
||||||
|
return filtered.length ? "" : "没有匹配的素材。";
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeTags(tags) {
|
||||||
|
return Array.isArray(tags) && tags.length ? tags : ["未分类"];
|
||||||
|
}
|
||||||
|
|
||||||
|
function getSubtitleLabel(video) {
|
||||||
|
const codes = Object.keys(video.subtitles || {});
|
||||||
|
if (!codes.length) return "无字幕";
|
||||||
|
return codes.map((code) => {
|
||||||
|
if (code === "en") return "英文";
|
||||||
|
if (code === "zh") return "中文";
|
||||||
|
return code;
|
||||||
|
}).join(" / ");
|
||||||
|
}
|
||||||
|
|
||||||
|
function getDefaultCueCount(video) {
|
||||||
|
const subtitles = video.subtitles || {};
|
||||||
|
const enContent = subtitles.en?.content || "";
|
||||||
|
if (enContent) return parseSubtitleCount(enContent);
|
||||||
|
const firstTrack = Object.values(subtitles)[0];
|
||||||
|
return parseSubtitleCount(firstTrack?.content || "");
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseSubtitleCount(text) {
|
||||||
|
const normalized = text
|
||||||
|
.replace(/^\uFEFF/, "")
|
||||||
|
.replace(/\r/g, "")
|
||||||
|
.replace(/^WEBVTT.*\n+/i, "")
|
||||||
|
.trim();
|
||||||
|
if (!normalized) return 0;
|
||||||
|
return normalized.split(/\n{2,}/).filter((block) => block.includes("-->")).length;
|
||||||
|
}
|
||||||
|
|
||||||
|
function getCoverText(title) {
|
||||||
|
const clean = String(title || "Speaking Lab").trim();
|
||||||
|
if (/[\u4e00-\u9fa5]/.test(clean)) return clean.slice(0, 6);
|
||||||
|
return clean
|
||||||
|
.split(/\s+/)
|
||||||
|
.filter(Boolean)
|
||||||
|
.slice(0, 3)
|
||||||
|
.map((word) => word[0])
|
||||||
|
.join("")
|
||||||
|
.toUpperCase();
|
||||||
|
}
|
||||||
|
|
||||||
|
function getCoverTone(id) {
|
||||||
|
const value = String(id || "").split("").reduce((sum, char) => sum + char.charCodeAt(0), 0);
|
||||||
|
return (value % 5) + 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderAccount() {
|
||||||
|
const user = getCurrentUser();
|
||||||
|
els.loginForm.hidden = Boolean(user);
|
||||||
|
els.userMenu.hidden = !user;
|
||||||
|
els.adminLink.hidden = !isAdmin(user);
|
||||||
|
if (user) {
|
||||||
|
els.userLabel.textContent = `${user.email}${isAdmin(user) ? " · 管理员" : ""}`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function loginOrRegister() {
|
||||||
|
const email = els.emailInput.value.trim().toLowerCase();
|
||||||
|
const password = els.passwordInput.value;
|
||||||
|
if (!email || !password) return;
|
||||||
|
|
||||||
|
let user = state.users.find((item) => item.email === email);
|
||||||
|
if (!user) {
|
||||||
|
user = {
|
||||||
|
id: `user-${Date.now()}`,
|
||||||
|
email,
|
||||||
|
password,
|
||||||
|
role: email.includes("admin") ? "admin" : "user",
|
||||||
|
favorites: [],
|
||||||
|
watchLater: [],
|
||||||
|
progress: {},
|
||||||
|
};
|
||||||
|
state.users.push(user);
|
||||||
|
} else if (user.password !== password) {
|
||||||
|
alert("密码不匹配。");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
state.currentUserId = user.id;
|
||||||
|
saveState();
|
||||||
|
els.loginForm.reset();
|
||||||
|
renderAccount();
|
||||||
|
renderHome();
|
||||||
|
}
|
||||||
|
|
||||||
|
function toggleFavorite(videoId) {
|
||||||
|
const user = getCurrentUser();
|
||||||
|
if (!user) {
|
||||||
|
alert("请先登录。第一版会自动注册新邮箱。");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const key = String(videoId);
|
||||||
|
const favorites = new Set((user.favorites || []).map(String));
|
||||||
|
if (favorites.has(key)) {
|
||||||
|
favorites.delete(key);
|
||||||
|
} else {
|
||||||
|
favorites.add(key);
|
||||||
|
}
|
||||||
|
|
||||||
|
user.favorites = [...favorites];
|
||||||
|
saveState();
|
||||||
|
renderHome();
|
||||||
|
}
|
||||||
|
|
||||||
|
function isAdmin(user) {
|
||||||
|
const email = String(user?.email || "").toLowerCase();
|
||||||
|
return user?.role === "admin" || email.includes("admin");
|
||||||
|
}
|
||||||
|
|
||||||
|
function getCurrentUser() {
|
||||||
|
return state.users.find((user) => user.id === state.currentUserId) || null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function createEmptyProgress() {
|
||||||
|
return {
|
||||||
|
currentTime: 0,
|
||||||
|
activeLineIndex: 0,
|
||||||
|
practicedLineIndexes: [],
|
||||||
|
difficultLineIndexes: [],
|
||||||
|
updatedAt: "",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeIndexList(value) {
|
||||||
|
if (!Array.isArray(value)) return [];
|
||||||
|
return [...new Set(value.map(Number).filter((index) => Number.isInteger(index) && index >= 0))]
|
||||||
|
.sort((a, b) => a - b);
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeProgress(progress) {
|
||||||
|
return {
|
||||||
|
...createEmptyProgress(),
|
||||||
|
...(progress || {}),
|
||||||
|
currentTime: Number(progress?.currentTime) || 0,
|
||||||
|
activeLineIndex: Number.isInteger(progress?.activeLineIndex) ? progress.activeLineIndex : 0,
|
||||||
|
practicedLineIndexes: normalizeIndexList(progress?.practicedLineIndexes),
|
||||||
|
difficultLineIndexes: normalizeIndexList(progress?.difficultLineIndexes),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function ensureUserProgress(user) {
|
||||||
|
if (!user) return null;
|
||||||
|
if (!user.progress || typeof user.progress !== "object") user.progress = {};
|
||||||
|
Object.keys(user.progress).forEach((videoId) => {
|
||||||
|
user.progress[videoId] = normalizeProgress(user.progress[videoId]);
|
||||||
|
});
|
||||||
|
return user.progress;
|
||||||
|
}
|
||||||
|
|
||||||
|
function getVideoProgress(user, videoId) {
|
||||||
|
const progressMap = ensureUserProgress(user);
|
||||||
|
if (!progressMap) return createEmptyProgress();
|
||||||
|
const key = String(videoId);
|
||||||
|
progressMap[key] = normalizeProgress(progressMap[key]);
|
||||||
|
return progressMap[key];
|
||||||
|
}
|
||||||
|
|
||||||
|
function calculatePracticeSummary(progress, totalLines) {
|
||||||
|
const total = Math.max(0, Number(totalLines) || 0);
|
||||||
|
const practiced = normalizeIndexList(progress?.practicedLineIndexes).filter((index) => index < total).length;
|
||||||
|
const percent = total ? Math.round((practiced / total) * 100) : 0;
|
||||||
|
return { practiced, total, percent };
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatProgressSummary(progress, totalLines) {
|
||||||
|
const summary = calculatePracticeSummary(progress, totalLines);
|
||||||
|
if (summary.total > 0 && summary.practiced > 0) {
|
||||||
|
return `已练 ${summary.practiced}/${summary.total} · ${summary.percent}%`;
|
||||||
|
}
|
||||||
|
const currentTime = Number(progress?.currentTime) || 0;
|
||||||
|
if (currentTime > 1) return `看到 ${formatTime(currentTime)}`;
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatTime(seconds) {
|
||||||
|
const total = Math.max(0, Math.floor(seconds));
|
||||||
|
const minutes = Math.floor(total / 60);
|
||||||
|
const rest = total % 60;
|
||||||
|
return `${String(minutes).padStart(2, "0")}:${String(rest).padStart(2, "0")}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeUser(user) {
|
||||||
|
const normalized = {
|
||||||
|
...user,
|
||||||
|
favorites: Array.isArray(user?.favorites) ? user.favorites : [],
|
||||||
|
watchLater: Array.isArray(user?.watchLater) ? user.watchLater : [],
|
||||||
|
};
|
||||||
|
ensureUserProgress(normalized);
|
||||||
|
return normalized;
|
||||||
|
}
|
||||||
|
|
||||||
|
function loadState() {
|
||||||
|
try {
|
||||||
|
const saved = JSON.parse(localStorage.getItem(STORAGE_KEY) || "{}");
|
||||||
|
return {
|
||||||
|
users: Array.isArray(saved.users) ? saved.users.map(normalizeUser) : [],
|
||||||
|
currentUserId: saved.currentUserId || null,
|
||||||
|
};
|
||||||
|
} catch {
|
||||||
|
return { users: [], currentUserId: null };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function saveState() {
|
||||||
|
localStorage.setItem(STORAGE_KEY, JSON.stringify(state));
|
||||||
|
}
|
||||||
+56
@@ -0,0 +1,56 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="zh-CN">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<title>Speaking Lab</title>
|
||||||
|
<link rel="stylesheet" href="./styles.css">
|
||||||
|
</head>
|
||||||
|
<body class="home-page">
|
||||||
|
<header class="topbar home-topbar">
|
||||||
|
<div class="brand">
|
||||||
|
<h1>Speaking Lab</h1>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="top-actions">
|
||||||
|
<input id="homeSearchInput" class="search-input home-search" type="search" placeholder="搜索素材、演讲者、标签">
|
||||||
|
<form id="homeLoginForm" class="login-form">
|
||||||
|
<input id="homeEmailInput" type="email" placeholder="邮箱" autocomplete="email" required>
|
||||||
|
<input id="homePasswordInput" type="password" placeholder="密码" autocomplete="current-password" required>
|
||||||
|
<button id="homeLoginBtn" type="submit">登录 / 注册</button>
|
||||||
|
</form>
|
||||||
|
<div id="homeUserMenu" class="user-menu" hidden>
|
||||||
|
<span id="homeUserLabel"></span>
|
||||||
|
<a id="homeAdminLink" class="secondary-action" href="./admin.html" hidden>管理</a>
|
||||||
|
<button id="homeLogoutBtn" type="button">退出</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<main class="home-shell">
|
||||||
|
<aside class="home-dashboard" aria-label="学习概览">
|
||||||
|
<div class="home-dashboard-title">
|
||||||
|
<span>学习概览</span>
|
||||||
|
<strong id="homeDashboardUser">本地学习</strong>
|
||||||
|
</div>
|
||||||
|
<div id="homeMetricFilters" class="home-metrics"></div>
|
||||||
|
</aside>
|
||||||
|
|
||||||
|
<section class="home-library">
|
||||||
|
<div class="home-heading">
|
||||||
|
<div>
|
||||||
|
<h2>素材库</h2>
|
||||||
|
<p>搜索素材,按分类和学习状态继续练习。</p>
|
||||||
|
</div>
|
||||||
|
<a class="primary-link" href="./study.html">进入学习页</a>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="homeCategoryFilters" class="home-categories"></div>
|
||||||
|
<div id="homeStatus" class="home-status"></div>
|
||||||
|
<div id="homeGrid" class="home-grid"></div>
|
||||||
|
</section>
|
||||||
|
</main>
|
||||||
|
|
||||||
|
<script src="./home.js"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
+92
@@ -0,0 +1,92 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="zh-CN">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<title>Speaking Lab</title>
|
||||||
|
<link rel="stylesheet" href="./styles.css">
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<header class="topbar">
|
||||||
|
<div class="brand">
|
||||||
|
<h1>Speaking Lab</h1>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="top-actions">
|
||||||
|
<form id="loginForm" class="login-form">
|
||||||
|
<input id="emailInput" type="email" placeholder="邮箱" autocomplete="email" required>
|
||||||
|
<input id="passwordInput" type="password" placeholder="密码" autocomplete="current-password" required>
|
||||||
|
<button id="loginBtn" type="submit">登录 / 注册</button>
|
||||||
|
</form>
|
||||||
|
<div id="userMenu" class="user-menu" hidden>
|
||||||
|
<span id="userLabel"></span>
|
||||||
|
<button id="logoutBtn" type="button">退出</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<main class="study-shell">
|
||||||
|
<section class="left-stage">
|
||||||
|
<section class="video-panel">
|
||||||
|
<div class="video-frame">
|
||||||
|
<video id="video" controls preload="metadata" crossorigin="anonymous"></video>
|
||||||
|
<div id="emptyVideo" class="empty-video">
|
||||||
|
<strong>选择或上传一个视频</strong>
|
||||||
|
<span>支持本地 MP4/WebM 和 HLS 地址</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="tool-row">
|
||||||
|
<button id="previousBtn" type="button" title="上一句">上一句</button>
|
||||||
|
<button id="replayBtn" type="button" title="重播">重播</button>
|
||||||
|
<button id="nextBtn" type="button" title="下一句">下一句</button>
|
||||||
|
<button id="recordBtn" type="button" title="录音">录音</button>
|
||||||
|
<button id="stopRecordBtn" type="button" disabled title="停止">停止</button>
|
||||||
|
<button id="playRecordingBtn" type="button" disabled title="回放我的录音">回放</button>
|
||||||
|
<label class="toggle">
|
||||||
|
<input id="loopToggle" type="checkbox">
|
||||||
|
<span>循环</span>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="subtitle-card">
|
||||||
|
<p id="primarySubtitle"></p>
|
||||||
|
<p id="secondarySubtitle"></p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="lesson-meta">
|
||||||
|
<div>
|
||||||
|
<h2 id="videoTitle">还没有选择视频</h2>
|
||||||
|
<p id="subtitleMeta">请选择视频。</p>
|
||||||
|
</div>
|
||||||
|
<div class="video-actions">
|
||||||
|
<button id="continueBtn" type="button" hidden>继续学习</button>
|
||||||
|
<button id="favoriteBtn" type="button">收藏</button>
|
||||||
|
<button id="watchLaterBtn" type="button">稍后再看</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="recording-line">
|
||||||
|
<span id="recordingStatus">麦克风只在当前浏览器会话中使用。</span>
|
||||||
|
<audio id="recordingAudio" controls hidden></audio>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<aside class="transcript-panel">
|
||||||
|
<div class="transcript-toolbar">
|
||||||
|
<div class="tabs">
|
||||||
|
<button class="tab active" type="button" data-mode="bilingual">双语</button>
|
||||||
|
<button class="tab" type="button" data-mode="english">英文</button>
|
||||||
|
<button class="tab" type="button" data-mode="chinese">中文</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div id="transcriptList" class="transcript-list">
|
||||||
|
<div class="empty-state">上传字幕后,每一句都会变成可点击的片段。</div>
|
||||||
|
</div>
|
||||||
|
</aside>
|
||||||
|
</main>
|
||||||
|
|
||||||
|
<script src="./app.js"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
+1321
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,24 @@
|
|||||||
|
import assert from "node:assert/strict";
|
||||||
|
import { getFileInputState } from "../admin.js";
|
||||||
|
|
||||||
|
function run() {
|
||||||
|
assert.deepEqual(getFileInputState(null, "选择视频文件"), {
|
||||||
|
text: "选择视频文件",
|
||||||
|
title: "选择视频文件",
|
||||||
|
isSelected: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
assert.deepEqual(getFileInputState({ name: "lesson-one-shadowing.mp4" }, "选择视频文件"), {
|
||||||
|
text: "已选:lesson-one-shadowing.mp4",
|
||||||
|
title: "lesson-one-shadowing.mp4",
|
||||||
|
isSelected: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
assert.deepEqual(getFileInputState({ name: "a-very-long-subtitle-file-name-for-practice.vtt" }, "英文字幕 .srt/.vtt"), {
|
||||||
|
text: "已选:a-very-long-subtitle-file-name-for-practice.vtt",
|
||||||
|
title: "a-very-long-subtitle-file-name-for-practice.vtt",
|
||||||
|
isSelected: true,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
run();
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
import assert from "node:assert/strict";
|
||||||
|
import { buildWebVtt, parseSubtitleBlocks } from "../admin.js";
|
||||||
|
|
||||||
|
const cues = parseSubtitleBlocks(`WEBVTT
|
||||||
|
|
||||||
|
00:00:00.000 --> 00:00:04.000
|
||||||
|
First line
|
||||||
|
|
||||||
|
00:00:04.000 --> 00:00:08.000
|
||||||
|
Second line
|
||||||
|
continued
|
||||||
|
`);
|
||||||
|
|
||||||
|
assert.equal(cues.length, 2);
|
||||||
|
assert.equal(cues[0].timeRange, "00:00:00.000 --> 00:00:04.000");
|
||||||
|
assert.equal(cues[0].text, "First line");
|
||||||
|
assert.equal(cues[1].text, "Second line\ncontinued");
|
||||||
|
|
||||||
|
const malformedCues = parseSubtitleBlocks(`WEBVTT
|
||||||
|
|
||||||
|
00:00:00.000 --> 00:00:00.001
|
||||||
|
\u00a0
|
||||||
|
00:00:00.872 --> 00:00:04.959
|
||||||
|
My first job as an investor
|
||||||
|
was when I was 24 years old,
|
||||||
|
`);
|
||||||
|
|
||||||
|
assert.equal(malformedCues.length, 1);
|
||||||
|
assert.equal(malformedCues[0].timeRange, "00:00:00.872 --> 00:00:04.959");
|
||||||
|
assert.equal(malformedCues[0].text, "My first job as an investor\nwas when I was 24 years old,");
|
||||||
|
assert.equal(malformedCues[0].text.includes("-->"), false);
|
||||||
|
|
||||||
|
cues.splice(0, 1);
|
||||||
|
assert.equal(buildWebVtt(cues), `WEBVTT
|
||||||
|
|
||||||
|
1
|
||||||
|
00:00:04.000 --> 00:00:08.000
|
||||||
|
Second line
|
||||||
|
continued
|
||||||
|
`);
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||||
|
|
||||||
|
from backend.db import repair_mojibake_text
|
||||||
|
|
||||||
|
|
||||||
|
def test_repairs_chinese_mojibake():
|
||||||
|
assert repair_mojibake_text("æªåç±»") == "未分类"
|
||||||
|
|
||||||
|
|
||||||
|
def test_repairs_english_punctuation_mojibake():
|
||||||
|
assert repair_mojibake_text("employeesâ lives") == "employees’ lives"
|
||||||
|
|
||||||
|
|
||||||
|
def test_keeps_normal_text_unchanged():
|
||||||
|
assert repair_mojibake_text("未分类") == "未分类"
|
||||||
|
assert repair_mojibake_text("English") == "English"
|
||||||
@@ -0,0 +1,94 @@
|
|||||||
|
import assert from "node:assert/strict";
|
||||||
|
import {
|
||||||
|
createEmptyProgress,
|
||||||
|
getVideoProgress,
|
||||||
|
toggleLineIndex,
|
||||||
|
calculatePracticeSummary,
|
||||||
|
formatProgressSummary,
|
||||||
|
getSubtitleModeConfig,
|
||||||
|
parseSubtitle,
|
||||||
|
} from "../app.js";
|
||||||
|
|
||||||
|
const empty = createEmptyProgress();
|
||||||
|
assert.deepEqual(empty, {
|
||||||
|
currentTime: 0,
|
||||||
|
activeLineIndex: 0,
|
||||||
|
practicedLineIndexes: [],
|
||||||
|
difficultLineIndexes: [],
|
||||||
|
updatedAt: "",
|
||||||
|
});
|
||||||
|
|
||||||
|
const user = { progress: {} };
|
||||||
|
const progress = getVideoProgress(user, "video-1");
|
||||||
|
assert.deepEqual(progress.practicedLineIndexes, []);
|
||||||
|
assert.equal(user.progress["video-1"], progress);
|
||||||
|
|
||||||
|
assert.deepEqual(toggleLineIndex([0, 2], 1), [0, 1, 2]);
|
||||||
|
assert.deepEqual(toggleLineIndex([0, 1, 2], 1), [0, 2]);
|
||||||
|
assert.deepEqual(toggleLineIndex([2, 2, 0], 1), [0, 1, 2]);
|
||||||
|
|
||||||
|
assert.deepEqual(calculatePracticeSummary({
|
||||||
|
practicedLineIndexes: [0, 2],
|
||||||
|
}, 5), {
|
||||||
|
practiced: 2,
|
||||||
|
total: 5,
|
||||||
|
percent: 40,
|
||||||
|
});
|
||||||
|
|
||||||
|
assert.equal(formatProgressSummary({
|
||||||
|
practicedLineIndexes: [0, 2],
|
||||||
|
currentTime: 124.4,
|
||||||
|
}, 5), "已练 2/5 · 40%");
|
||||||
|
|
||||||
|
assert.equal(formatProgressSummary({
|
||||||
|
practicedLineIndexes: [],
|
||||||
|
currentTime: 124.4,
|
||||||
|
}, 0), "看到 02:04");
|
||||||
|
|
||||||
|
assert.equal(formatProgressSummary({
|
||||||
|
practicedLineIndexes: [],
|
||||||
|
currentTime: 0,
|
||||||
|
}, 0), "");
|
||||||
|
|
||||||
|
assert.deepEqual(getSubtitleModeConfig("bilingual", { en: {}, zh: {} }), {
|
||||||
|
primaryCode: "en",
|
||||||
|
secondaryCode: "zh",
|
||||||
|
showSecondary: true,
|
||||||
|
message: "",
|
||||||
|
});
|
||||||
|
|
||||||
|
assert.deepEqual(getSubtitleModeConfig("english", { en: {}, zh: {} }), {
|
||||||
|
primaryCode: "en",
|
||||||
|
secondaryCode: "",
|
||||||
|
showSecondary: false,
|
||||||
|
message: "",
|
||||||
|
});
|
||||||
|
|
||||||
|
assert.deepEqual(getSubtitleModeConfig("chinese", { en: {}, zh: {} }), {
|
||||||
|
primaryCode: "zh",
|
||||||
|
secondaryCode: "",
|
||||||
|
showSecondary: false,
|
||||||
|
message: "",
|
||||||
|
});
|
||||||
|
|
||||||
|
assert.deepEqual(getSubtitleModeConfig("chinese", { en: {} }), {
|
||||||
|
primaryCode: "en",
|
||||||
|
secondaryCode: "",
|
||||||
|
showSecondary: false,
|
||||||
|
message: "当前素材没有中文字幕。",
|
||||||
|
});
|
||||||
|
|
||||||
|
const malformedVtt = `WEBVTT
|
||||||
|
|
||||||
|
00:00:00.000 --> 00:00:00.001
|
||||||
|
\u00a0
|
||||||
|
00:00:00.872 --> 00:00:04.959
|
||||||
|
My first job as an investor
|
||||||
|
was when I was 24 years old,
|
||||||
|
`;
|
||||||
|
|
||||||
|
const parsedCues = parseSubtitle(malformedVtt);
|
||||||
|
assert.equal(parsedCues.length, 1);
|
||||||
|
assert.equal(parsedCues[0].start, 0.872);
|
||||||
|
assert.equal(parsedCues[0].text, "My first job as an investor was when I was 24 years old,");
|
||||||
|
assert.equal(parsedCues[0].text.includes("-->"), false);
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
@echo off
|
||||||
|
cd /d "%~dp0"
|
||||||
|
|
||||||
|
echo Starting Speaking Lab server...
|
||||||
|
echo.
|
||||||
|
echo Website: http://127.0.0.1:8000
|
||||||
|
echo.
|
||||||
|
|
||||||
|
python -c "import fastapi, uvicorn, multipart" >nul 2>nul
|
||||||
|
if errorlevel 1 (
|
||||||
|
echo Missing dependencies. Installing now...
|
||||||
|
python -m pip install fastapi uvicorn python-multipart
|
||||||
|
if errorlevel 1 (
|
||||||
|
echo.
|
||||||
|
echo Dependency installation failed. Please check your Python installation.
|
||||||
|
pause
|
||||||
|
exit /b 1
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
start "Speaking Lab Server" cmd /k cd /d "%~dp0" ^&^& python -m uvicorn backend.main:app --reload --host 127.0.0.1 --port 8000
|
||||||
|
|
||||||
|
echo Waiting for the server to be ready...
|
||||||
|
powershell -NoProfile -ExecutionPolicy Bypass -Command "$ready=$false; for($i=0; $i -lt 60; $i++){ try { $r=Invoke-WebRequest -Uri 'http://127.0.0.1:8000/api/videos' -UseBasicParsing -TimeoutSec 1; if($r.StatusCode -eq 200){ $ready=$true; break } } catch { Start-Sleep -Milliseconds 500 } }; if(-not $ready){ exit 1 }"
|
||||||
|
|
||||||
|
if errorlevel 1 (
|
||||||
|
echo.
|
||||||
|
echo Server did not start successfully.
|
||||||
|
echo Please check the "Speaking Lab Server" window for the error message.
|
||||||
|
pause
|
||||||
|
exit /b 1
|
||||||
|
)
|
||||||
|
|
||||||
|
echo Server is ready. Opening the website...
|
||||||
|
start "" "http://127.0.0.1:8000"
|
||||||
|
|
||||||
|
echo.
|
||||||
|
echo Website opened. Keep the "Speaking Lab Server" window open while using it.
|
||||||
|
echo You can close this window now.
|
||||||
|
pause
|
||||||
Reference in new issue
Block a user