Compare commits

...
Author SHA1 Message Date
TTlaji f4c4d6eb4b fix: keep mobile video inline
Deploy Speaking Practice / deploy (push) Successful in 3s
2026-07-13 00:14:29 +08:00
TTlaji bef5e764a0 fix: keep study controls visible
Deploy Speaking Practice / deploy (push) Successful in 5s
2026-07-12 23:15:23 +08:00
TTlaji 0c12ce5f33 feat: enforce single active user session
Deploy Speaking Practice / deploy (push) Successful in 26s
2026-06-15 14:40:33 +08:00
TTlaji 0cf6f62e23 fix: hide used activation codes
Deploy Speaking Practice / deploy (push) Successful in 1m33s
2026-06-15 13:45:50 +08:00
TTlaji 64e7cc5d8b feat: sync learning progress to backend
Deploy Speaking Practice / deploy (push) Successful in 44s
2026-06-15 12:52:20 +08:00
TTlaji 67dcea21d0 style: polish responsive typography and transcript states
Deploy Speaking Practice / deploy (push) Successful in 2m13s
2026-06-09 22:56:57 +08:00
TTlaji cd29764963 style: fix disabled secondary button states 2026-06-09 00:28:46 +08:00
TTlaji a38fc638ee style: fix disabled danger and ai primary states 2026-06-08 23:30:17 +08:00
TTlaji 15ac501843 style: refresh primary and danger buttons 2026-06-08 23:15:54 +08:00
TTlaji 51c8c82e1d style: preserve focus rings on chips and secondary buttons 2026-06-08 23:08:37 +08:00
TTlaji 22831540ef style: refresh chips and secondary buttons 2026-06-08 23:02:45 +08:00
TTlaji 468415066e style: add button style tokens 2026-06-08 22:56:47 +08:00
TTlaji b024743cd8 Add button chip style refresh implementation plan 2026-06-08 22:55:03 +08:00
TTlaji c18a5d4c2d Add button chip style refresh design spec 2026-06-08 22:52:36 +08:00
TTlaji 215bfad260 style: focus practice modes in right panel
Deploy Speaking Practice / deploy (push) Successful in 1m25s
2026-06-08 19:17:48 +08:00
TTlaji b4197fb588 feat: toggle right panel practice views 2026-06-08 19:13:47 +08:00
TTlaji b8d9520fa9 refactor: move study practice markup to right panel 2026-06-08 19:10:36 +08:00
TTlaji cbf62236cf Add study right mode panel implementation plan 2026-06-08 19:08:22 +08:00
TTlaji 584fb3e5f1 Add study right mode panel design spec 2026-06-08 17:21:19 +08:00
TTlaji d78ddc7e00 fix: ignore apostrophes in practice answers 2026-06-08 15:19:05 +08:00
TTlaji a6ac042e83 style: polish study practice modes 2026-06-08 15:07:57 +08:00
TTlaji 06766c3079 feat: add study practice panel wiring 2026-06-08 15:02:28 +08:00
TTlaji 202fb5ade9 feat: add practice answer helpers 2026-06-08 14:54:41 +08:00
TTlaji 2e62600b0d test: add practice mode helper coverage 2026-06-08 14:50:32 +08:00
TTlaji 35e0665e7a Add study practice modes implementation plan 2026-06-08 14:40:02 +08:00
TTlaji 4c5501093d Add study practice modes design spec 2026-06-08 14:33:24 +08:00
TTlaji 2d3ff21222 feat: add activation-code auth
Deploy Speaking Practice / deploy (push) Successful in 24s
2026-06-05 16:56:30 +08:00
TTlaji 8f3fd04618 docs: design activation auth flow 2026-06-05 16:36:09 +08:00
TTlaji 3a51c389be fix: keep deploy ssh key out of action logs
Deploy Speaking Practice / deploy (push) Successful in 1m4s
2026-06-05 01:23:05 +08:00
TTlaji fa3111ce0b chore: add gitea auto deploy workflow
Deploy Speaking Practice / deploy (push) Failing after 12m14s
2026-06-05 01:06:13 +08:00
TTlaji 1e9228e50a feat: protect admin APIs 2026-06-05 00:25:20 +08:00
TTlaji 4f027a3728 chore: add server update script 2026-06-04 23:59:09 +08:00
TTlaji 0608b84664 feat: refine subtitle flow and study UI 2026-06-04 01:26:41 +08:00
TTlaji 6a6fd347bd feat: add local whisper subtitle generation 2026-06-03 23:37:21 +08:00
TTlaji 5228765473 feat: align subtitles from first 10 seconds audio 2026-06-03 15:10:49 +08:00
TTlaji 93e06ca40a feat: add fine subtitle timing shift 2026-06-03 14:26:29 +08:00
TTlaji b66034c8a9 feat: add manual subtitle timing shift 2026-06-03 14:15:11 +08:00
TTlaji ae4791143c fix: constrain subtitle AI to preserve timestamps 2026-06-03 14:07:33 +08:00
TTlaji 5ff72bf1b6 fix: enable AI subtitles after material save 2026-06-03 13:51:13 +08:00
TTlaji 72072c884c feat: add DeepSeek subtitle AI workflow 2026-06-03 00:57:59 +08:00
56 changed files with 8760 additions and 374 deletions

No files matched your search

+15
View File
@@ -0,0 +1,15 @@
TEXT_AI_API_KEY=
TEXT_AI_BASE_URL=https://api.deepseek.com
TEXT_AI_MODEL=deepseek-v4-pro
TEXT_AI_PROVIDER=deepseek
TEXT_AI_PROTOCOL=openai
TEXT_AI_BATCH_SIZE=0
TEXT_AI_TIMEOUT_SECONDS=120
ADMIN_USERNAME=admin
ADMIN_PASSWORD=change-me
LOCAL_WHISPER_ENABLED=true
LOCAL_WHISPER_MODEL=small
LOCAL_WHISPER_DEVICE=cpu
LOCAL_WHISPER_COMPUTE_TYPE=int8
+32
View File
@@ -0,0 +1,32 @@
name: Deploy Speaking Practice
on:
push:
branches:
- feature/deepseek-subtitle-ai
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- name: Deploy to server
env:
SERVER_HOST: ${{ secrets.SERVER_HOST }}
SERVER_USER: ${{ secrets.SERVER_USER }}
SERVER_SSH_KEY: ${{ secrets.SERVER_SSH_KEY }}
run: |
set -euo pipefail
mkdir -p ~/.ssh
chmod 700 ~/.ssh
printf '%s\n' "$SERVER_SSH_KEY" > ~/.ssh/deploy_key
chmod 600 ~/.ssh/deploy_key
ssh-keyscan -H "$SERVER_HOST" >> ~/.ssh/known_hosts
ssh -i ~/.ssh/deploy_key \
-o IdentitiesOnly=yes \
"$SERVER_USER@$SERVER_HOST" \
"cd /opt/speaking-practice && ./scripts/update-server.sh"
+2
View File
@@ -1,7 +1,9 @@
backend/speaking_lab.sqlite
uploads/videos/
uploads/subtitles/
uploads/images/
__pycache__/
*.pyc
*.lnk
ui-redesign-smoke.png
.env
+43 -10
View File
@@ -4,25 +4,22 @@
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Speaking Lab 后台管理</title>
<link rel="stylesheet" href="./styles.css">
<link rel="stylesheet" href="./styles.css?v=20260609-typography">
</head>
<body class="admin-page">
<header class="topbar admin-topbar">
<div class="brand">
<div>
<h1>后台管理</h1>
<p id="adminIdentity">请先使用管理员账号登录。</p>
<p id="adminIdentity">正在验证管理员账号...</p>
</div>
</div>
<a class="secondary-action" href="./index.html">返回学习页</a>
<div class="top-actions">
<a class="secondary-action" href="./index.html">返回首页</a>
<button id="adminLogoutBtn" type="button">退出</button>
</div>
</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">
@@ -34,6 +31,10 @@
<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="adminCoverFile" type="file" accept="image/*">
</label>
<label class="file-input" data-default-label="选择视频文件">
<span>选择视频文件</span>
<input id="adminVideoFile" type="file" accept="video/*">
@@ -47,6 +48,18 @@
<span>中文字幕 .srt/.vtt</span>
<input id="adminSubtitleZh" type="file" accept=".srt,.vtt,text/vtt,text/plain">
</label>
<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="generateLocalWhisperSubtitlesBtn" class="secondary-action" type="button" disabled>本地生成英文字幕</button>
<button id="processAiSubtitlesBtn" type="button" disabled>AI 修复并翻译字幕</button>
</div>
<p id="aiSubtitleReport" class="admin-ai-report" hidden></p>
</section>
<div id="adminSubtitleEditor" class="admin-subtitle-editor" hidden></div>
<button id="adminSubmitBtn" type="submit">添加到视频库</button>
</form>
@@ -60,8 +73,28 @@
<div id="adminMessage" class="admin-message" hidden></div>
<div id="adminVideoList" class="admin-video-list"></div>
</section>
<section class="admin-panel">
<div class="admin-list-heading">
<h2>账号管理</h2>
<button id="refreshUsersBtn" class="secondary-action" type="button">刷新</button>
</div>
<div id="adminUserList" class="admin-user-list"></div>
</section>
<section class="admin-panel">
<div class="admin-list-heading">
<h2>激活卡密</h2>
</div>
<form id="activationCodeForm" class="activation-code-form">
<input id="activationCodeQuantity" type="number" min="1" max="100" value="1" aria-label="生成数量">
<button type="submit">生成卡密</button>
</form>
<div id="activationCodeList" class="activation-code-list"></div>
</section>
</main>
<script src="./admin.js"></script>
<script src="./auth.js?v=20260605-auth"></script>
<script src="./admin.js?v=20260605-auth"></script>
</body>
</html>
+478 -31
View File
@@ -1,10 +1,11 @@
const STORAGE_KEY = "speaking-lab-state-v1";
const ADMIN_TOKEN_KEY = "speaking-lab-auth-token-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,
logoutBtn: IS_BROWSER ? document.querySelector("#adminLogoutBtn") : null,
formTitle: IS_BROWSER ? document.querySelector("#adminFormTitle") : null,
form: IS_BROWSER ? document.querySelector("#adminCreateForm") : null,
submitBtn: IS_BROWSER ? document.querySelector("#adminSubmitBtn") : null,
@@ -13,17 +14,30 @@ const els = {
speaker: IS_BROWSER ? document.querySelector("#adminSpeaker") : null,
description: IS_BROWSER ? document.querySelector("#adminDescription") : null,
tags: IS_BROWSER ? document.querySelector("#adminTags") : null,
coverFile: IS_BROWSER ? document.querySelector("#adminCoverFile") : 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,
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,
generateLocalWhisperSubtitlesBtn: IS_BROWSER ? document.querySelector("#generateLocalWhisperSubtitlesBtn") : null,
refreshBtn: IS_BROWSER ? document.querySelector("#refreshVideosBtn") : null,
refreshUsersBtn: IS_BROWSER ? document.querySelector("#refreshUsersBtn") : null,
message: IS_BROWSER ? document.querySelector("#adminMessage") : null,
videoList: IS_BROWSER ? document.querySelector("#adminVideoList") : null,
userList: IS_BROWSER ? document.querySelector("#adminUserList") : null,
activationCodeForm: IS_BROWSER ? document.querySelector("#activationCodeForm") : null,
activationCodeQuantity: IS_BROWSER ? document.querySelector("#activationCodeQuantity") : null,
activationCodeList: IS_BROWSER ? document.querySelector("#activationCodeList") : null,
};
let videos = [];
let users = [];
let activationCodes = [];
let editingVideo = null;
let editableSubtitles = createEmptySubtitleEditState();
@@ -41,18 +55,11 @@ function loadState() {
}
}
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 (IS_BROWSER && window.SpeakingAuth) {
return window.SpeakingAuth.apiRequest(path, options);
}
const response = await fetch(path, withAdminToken(options));
if (!response.ok) {
let message = "请求失败,请重试。";
try {
@@ -66,24 +73,93 @@ async function apiRequest(path, options = {}) {
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;
async function initializeAdmin() {
els.form.addEventListener("submit", addVideo);
els.refreshBtn.addEventListener("click", loadVideos);
els.refreshUsersBtn?.addEventListener("click", loadUsers);
els.activationCodeForm?.addEventListener("submit", generateActivationCodes);
els.logoutBtn?.addEventListener("click", () => window.SpeakingAuth.logout());
els.cancelEditBtn.addEventListener("click", resetFormMode);
els.testAiBtn?.addEventListener("click", testAiConnection);
els.processAiSubtitlesBtn?.addEventListener("click", processAiSubtitles);
els.generateLocalWhisperSubtitlesBtn?.addEventListener("click", generateLocalWhisperSubtitles);
bindFileInputs();
const user = await window.SpeakingAuth.requireSession({ adminOnly: true });
if (!user) return;
unlockAdmin(user.username);
}
function lockAdmin(message = "") {
if (!els.content) return;
els.identity.textContent = "未登录管理员账号";
if (els.locked) els.locked.hidden = false;
els.content.hidden = true;
if (els.adminLoginMessage) {
els.adminLoginMessage.hidden = !message;
els.adminLoginMessage.textContent = message;
els.adminLoginMessage.classList.toggle("error", Boolean(message));
}
}
function unlockAdmin(username) {
els.identity.textContent = `${username} · 管理员`;
els.content.hidden = false;
loadAiStatus();
loadVideos();
loadUsers();
loadActivationCodes();
}
async function loginAdmin(event) {
event.preventDefault();
const username = els.adminUsername.value.trim();
const password = els.adminPassword.value;
if (!username || !password) return;
try {
const result = await window.SpeakingAuth.login(username, password);
if (result?.role !== "admin") {
window.SpeakingAuth.clearSession();
throw new Error("需要管理员账号。");
}
if (els.adminLoginMessage) els.adminLoginMessage.hidden = true;
els.adminLoginForm.reset();
unlockAdmin(result.username || username);
} catch (error) {
clearStoredAdminToken(window.sessionStorage);
lockAdmin(error.message || "管理员账号或密码错误。");
}
}
async function verifyStoredAdminCredentials() {
try {
const result = await apiRequest("/api/admin/session");
unlockAdmin(result.username || "");
} catch {
clearStoredAdminToken(window.sessionStorage);
lockAdmin("管理员登录已失效,请重新登录。");
}
}
function withAdminToken(options = {}) {
const token = IS_BROWSER ? getStoredAdminToken(window.sessionStorage) : "";
if (!token) return options;
const headers = new Headers(options.headers || {});
headers.set("Authorization", `Bearer ${token}`);
return { ...options, headers };
}
function getStoredAdminToken(storage) {
return String(storage.getItem(ADMIN_TOKEN_KEY) || "");
}
function setStoredAdminToken(storage, token) {
storage.setItem(ADMIN_TOKEN_KEY, String(token || ""));
}
function clearStoredAdminToken(storage) {
storage.removeItem(ADMIN_TOKEN_KEY);
}
function getFileInputState(file, defaultLabel) {
@@ -103,7 +179,7 @@ function getFileInputState(file, defaultLabel) {
}
function bindFileInputs() {
[els.videoFile, els.subtitleEn, els.subtitleZh].forEach((input) => {
[els.coverFile, els.videoFile, els.subtitleEn, els.subtitleZh].forEach((input) => {
const label = input?.closest(".file-input");
if (!label) return;
@@ -125,7 +201,7 @@ function updateFileInputLabel(input) {
}
function resetFileInputs() {
[els.videoFile, els.subtitleEn, els.subtitleZh].forEach((input) => {
[els.coverFile, els.videoFile, els.subtitleEn, els.subtitleZh].forEach((input) => {
if (input) updateFileInputLabel(input);
});
}
@@ -142,6 +218,179 @@ function clearMessage() {
els.message.classList.remove("error");
}
async function loadAiStatus() {
if (!els.aiStatus) return;
try {
const status = await apiRequest("/api/ai/status");
const aiButtonState = getAiSubtitleButtonState(status, editingVideo);
const localWhisperButtonState = getLocalWhisperButtonState(status, editingVideo);
els.aiStatus.textContent = aiButtonState.hint || localWhisperButtonState.hint || status.message || "AI 状态未知。";
if (els.processAiSubtitlesBtn) {
els.processAiSubtitlesBtn.disabled = aiButtonState.disabled;
}
if (els.generateLocalWhisperSubtitlesBtn) {
els.generateLocalWhisperSubtitlesBtn.disabled = localWhisperButtonState.disabled;
}
} catch (error) {
els.aiStatus.textContent = error.message || "AI 状态读取失败。";
if (els.processAiSubtitlesBtn) els.processAiSubtitlesBtn.disabled = true;
if (els.generateLocalWhisperSubtitlesBtn) els.generateLocalWhisperSubtitlesBtn.disabled = true;
}
}
function getAiSubtitleButtonState(status, selectedVideo) {
if (!status?.configured) {
return {
disabled: true,
hint: "请先配置 DeepSeek API。",
};
}
if (!selectedVideo) {
return {
disabled: true,
hint: "请先在右侧素材列表点“编辑”。",
};
}
return {
disabled: false,
hint: "",
};
}
function getLocalWhisperButtonState(status, selectedVideo) {
if (!status?.localWhisperEnabled) {
return {
disabled: true,
hint: "请先开启本地 Whisper。",
};
}
if (!selectedVideo) {
return {
disabled: true,
hint: "请先在右侧素材列表点“编辑”。",
};
}
return {
disabled: false,
hint: "",
};
}
function shouldConfirmSubtitleOverwrite(video) {
const subtitles = video?.subtitles || {};
return Boolean(subtitles.en?.content);
}
function setAiReportText(text) {
if (!els.aiReport) return;
els.aiReport.hidden = false;
els.aiReport.textContent = text;
}
function startLocalWhisperProgress() {
const stages = [
"处理进度:提取音频...",
"处理进度:生成英文字幕...",
];
setAiReportText(stages[0]);
const timers = [
window.setTimeout(() => setAiReportText(stages[1]), 1200),
];
return () => timers.forEach((timer) => window.clearTimeout(timer));
}
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 generateLocalWhisperSubtitles() {
if (!editingVideo) {
showMessage("请先选择一个素材。", true);
return;
}
if (shouldConfirmSubtitleOverwrite(editingVideo)) {
const confirmed = window.confirm("当前素材已有英文字幕,重新生成会覆盖它。继续吗?");
if (!confirmed) return;
}
const button = els.generateLocalWhisperSubtitlesBtn;
if (!button) return;
const stopProgress = startLocalWhisperProgress();
button.disabled = true;
button.textContent = "处理中...";
try {
const result = await apiRequest(`/api/videos/${editingVideo.id}/local-whisper/subtitles`, { method: "POST" });
const report = result.report || {};
setAiReportText([
"处理进度:完成",
`英文字幕 ${report.english_count || 0} 条`,
"本地 Whisper 已完成",
].join(";") + "。");
await loadVideos();
const updated = videos.find((video) => String(video.id) === String(editingVideo.id));
if (updated) startEditingVideo(updated);
showMessage("本地英文字幕生成完成。");
} catch (error) {
const message = error.message || "本地英文字幕生成失败。";
setAiReportText(`处理失败:${message}`);
showMessage(message, true);
} finally {
stopProgress();
button.textContent = "本地生成英文字幕";
await loadAiStatus();
}
}
async function processAiSubtitles() {
if (!editingVideo) {
showMessage("请先选择一个素材。", true);
return;
}
const button = els.processAiSubtitlesBtn;
if (!button) return;
button.disabled = true;
button.textContent = "AI 处理中...";
try {
const result = await apiRequest(`/api/videos/${editingVideo.id}/ai/subtitles`, { method: "POST" });
const report = result.report || {};
if (els.aiReport) {
els.aiReport.hidden = false;
els.aiReport.textContent = [
`处理完成:删除重复 ${report.duplicate_count || 0} 条`,
`删除空白 ${report.empty_count || 0} 条`,
`生成中文 ${report.translation_count || 0} 条`,
].join(",") + "。";
}
await loadVideos();
const updated = videos.find((video) => String(video.id) === String(editingVideo.id));
if (updated) startEditingVideo(updated);
showMessage("AI 字幕处理完成。");
} catch (error) {
const message = error.message || "AI 字幕处理失败。";
setAiReportText(`处理失败:${message}`);
showMessage(message, true);
} finally {
button.textContent = "AI 修复并翻译字幕";
await loadAiStatus();
}
}
async function loadVideos() {
clearMessage();
els.videoList.innerHTML = `<div class="empty-state">正在加载素材...</div>`;
@@ -202,6 +451,167 @@ function renderVideos() {
els.videoList.appendChild(fragment);
}
async function loadUsers() {
if (!els.userList) return;
els.userList.innerHTML = `<div class="empty-state">正在加载账号...</div>`;
try {
users = await apiRequest("/api/admin/users");
renderUsers();
} catch (error) {
els.userList.innerHTML = `<div class="empty-state">${error.message || "账号加载失败。"}</div>`;
}
}
function renderUsers() {
if (!els.userList) return;
els.userList.innerHTML = "";
if (!users.length) {
els.userList.innerHTML = `<div class="empty-state">还没有注册用户。</div>`;
return;
}
const fragment = document.createDocumentFragment();
users.forEach((user) => {
const item = document.createElement("article");
const details = document.createElement("div");
const action = document.createElement("button");
item.className = "admin-user-item";
details.innerHTML = `
<h3></h3>
<p></p>
`;
details.querySelector("h3").textContent = user.username;
details.querySelector("p").textContent = [
user.role === "admin" ? "管理员" : "普通用户",
user.isActive ? "启用中" : "已停用",
user.lastLoginAt ? `最近登录 ${user.lastLoginAt}` : `创建于 ${user.createdAt || "-"}`,
].join(" · ");
action.type = "button";
action.className = user.isActive ? "danger-action" : "secondary-action";
action.textContent = user.isActive ? "停用" : "启用";
action.disabled = user.role === "admin";
action.addEventListener("click", () => updateUserStatus(user, !user.isActive));
item.append(details, action);
fragment.appendChild(item);
});
els.userList.appendChild(fragment);
}
async function updateUserStatus(user, isActive) {
try {
await apiRequest(`/api/admin/users/${user.id}`, {
method: "PATCH",
body: JSON.stringify({ isActive }),
});
await loadUsers();
} catch (error) {
showMessage(error.message || "账号状态更新失败。", true);
}
}
async function loadActivationCodes() {
if (!els.activationCodeList) return;
els.activationCodeList.innerHTML = `<div class="empty-state">正在加载卡密...</div>`;
try {
activationCodes = await apiRequest("/api/admin/activation-codes");
renderActivationCodes();
} catch (error) {
els.activationCodeList.innerHTML = `<div class="empty-state">${error.message || "卡密加载失败。"}</div>`;
}
}
async function generateActivationCodes(event) {
event.preventDefault();
const quantity = Number(els.activationCodeQuantity.value) || 1;
try {
await apiRequest("/api/admin/activation-codes", {
method: "POST",
body: JSON.stringify({ quantity }),
});
els.activationCodeQuantity.value = "1";
await loadActivationCodes();
} catch (error) {
showMessage(error.message || "卡密生成失败。", true);
}
}
function renderActivationCodes() {
if (!els.activationCodeList) return;
els.activationCodeList.innerHTML = "";
if (!activationCodes.length) {
els.activationCodeList.innerHTML = `<div class="empty-state">还没有激活卡密。</div>`;
return;
}
const fragment = document.createDocumentFragment();
activationCodes.forEach((code) => {
const item = document.createElement("article");
const details = document.createElement("div");
const actions = document.createElement("div");
const copyButton = document.createElement("button");
const deleteButton = document.createElement("button");
const isUsed = code.status === "used";
item.className = "activation-code-item";
details.innerHTML = `
<h3></h3>
<p></p>
`;
details.querySelector("h3").textContent = code.code;
details.querySelector("p").textContent = isUsed
? `已使用 · ${code.usedByUsername || "-"} · ${code.usedAt || "-"}`
: `未使用 · 创建于 ${code.createdAt || "-"}`;
actions.className = "admin-video-actions";
copyButton.type = "button";
copyButton.className = "secondary-action";
copyButton.textContent = "复制";
copyButton.addEventListener("click", () => copyActivationCode(code.code, copyButton));
deleteButton.type = "button";
deleteButton.className = "danger-action";
deleteButton.textContent = "删除";
deleteButton.disabled = isUsed;
deleteButton.addEventListener("click", () => deleteActivationCode(code));
actions.append(copyButton, deleteButton);
item.append(details, actions);
fragment.appendChild(item);
});
els.activationCodeList.appendChild(fragment);
}
async function copyActivationCode(code, button) {
try {
await navigator.clipboard.writeText(code);
button.textContent = getActivationCodeCopiedLabel();
window.setTimeout(() => {
button.textContent = "复制";
}, 1200);
} catch {
showMessage(getActivationCodeCopyFallbackMessage(code), false);
}
}
function getActivationCodeCopiedLabel() {
return "已复制";
}
function getActivationCodeCopyFallbackMessage(code) {
return `复制失败,请手动复制:${code}`;
}
async function deleteActivationCode(code) {
const confirmed = window.confirm(`确定删除卡密 ${code.code} 吗?`);
if (!confirmed) return;
try {
await apiRequest(`/api/admin/activation-codes/${code.id}`, { method: "DELETE" });
await loadActivationCodes();
} catch (error) {
showMessage(error.message || "卡密删除失败。", true);
}
}
function formatTags(tags) {
return Array.isArray(tags) && tags.length ? tags.join(" / ") : "未分类";
}
@@ -232,6 +642,7 @@ function startEditingVideo(video) {
resetFileInputs();
renderSubtitleEditor();
renderVideos();
loadAiStatus();
}
function resetFormMode() {
@@ -243,8 +654,23 @@ function resetFormMode() {
els.form.dataset.mode = "add";
els.form.reset();
resetFileInputs();
if (els.aiReport) els.aiReport.hidden = true;
renderSubtitleEditor();
renderVideos();
loadAiStatus();
}
function pickVideoAfterSave(videoList, response, previousEditingVideo) {
const savedVideo = response?.video || response;
if (savedVideo?.id) {
return videoList.find((video) => String(video.id) === String(savedVideo.id)) || savedVideo;
}
if (previousEditingVideo?.id) {
return videoList.find((video) => String(video.id) === String(previousEditingVideo.id)) || previousEditingVideo;
}
return null;
}
async function addVideo(event) {
@@ -270,22 +696,29 @@ async function addVideo(event) {
formData.append("tags", els.tags.value.trim());
formData.append("video_url", els.videoUrl.value.trim());
if (els.coverFile.files?.[0]) formData.append("cover_file", els.coverFile.files[0]);
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);
const previousEditingVideo = editingVideo;
try {
const path = editingVideo ? `/api/videos/${editingVideo.id}` : "/api/videos";
const method = editingVideo ? "PATCH" : "POST";
await apiRequest(path, {
const response = await apiRequest(path, {
method,
body: formData,
});
const successMessage = editingVideo ? "素材已更新。" : "素材已添加。";
requestSucceeded = true;
resetFormMode();
await loadVideos();
const savedVideo = pickVideoAfterSave(videos, response, previousEditingVideo);
if (savedVideo) {
startEditingVideo(savedVideo);
} else {
resetFormMode();
}
showMessage(successMessage);
} catch (error) {
showMessage(error.message || (editingVideo ? "更新素材失败。" : "添加素材失败。"), true);
@@ -296,7 +729,20 @@ async function addVideo(event) {
}
if (typeof module !== "undefined" && module.exports) {
module.exports = { getFileInputState, parseSubtitleBlocks, buildWebVtt };
module.exports = {
getFileInputState,
parseSubtitleBlocks,
buildWebVtt,
getAiSubtitleButtonState,
getLocalWhisperButtonState,
shouldConfirmSubtitleOverwrite,
pickVideoAfterSave,
getActivationCodeCopiedLabel,
getActivationCodeCopyFallbackMessage,
getStoredAdminToken,
setStoredAdminToken,
clearStoredAdminToken,
};
}
function createEmptySubtitleEditState() {
@@ -396,6 +842,7 @@ function hasSubtitleText(textRows) {
.trim().length > 0;
}
function renderSubtitleEditor() {
if (!els.subtitleEditor) return;
els.subtitleEditor.innerHTML = "";
@@ -446,7 +893,7 @@ function renderSubtitleEditor() {
});
}
els.subtitleEditor.appendChild(section);
els.subtitleEditor.appendChild(section);
});
}
+289 -81
View File
@@ -5,9 +5,6 @@ const IS_BROWSER = typeof document !== "undefined";
const els = {
video: IS_BROWSER ? document.querySelector("#video") : null,
emptyVideo: IS_BROWSER ? document.querySelector("#emptyVideo") : null,
loginForm: IS_BROWSER ? document.querySelector("#loginForm") : null,
emailInput: IS_BROWSER ? document.querySelector("#emailInput") : null,
passwordInput: IS_BROWSER ? document.querySelector("#passwordInput") : null,
userMenu: IS_BROWSER ? document.querySelector("#userMenu") : null,
userLabel: IS_BROWSER ? document.querySelector("#userLabel") : null,
logoutBtn: IS_BROWSER ? document.querySelector("#logoutBtn") : null,
@@ -16,9 +13,7 @@ const els = {
videoList: IS_BROWSER ? document.querySelector("#videoList") : null,
videoCount: IS_BROWSER ? document.querySelector("#videoCount") : null,
videoTitle: IS_BROWSER ? document.querySelector("#videoTitle") : null,
continueBtn: IS_BROWSER ? document.querySelector("#continueBtn") : null,
favoriteBtn: IS_BROWSER ? document.querySelector("#favoriteBtn") : null,
watchLaterBtn: IS_BROWSER ? document.querySelector("#watchLaterBtn") : null,
previousBtn: IS_BROWSER ? document.querySelector("#previousBtn") : null,
replayBtn: IS_BROWSER ? document.querySelector("#replayBtn") : null,
nextBtn: IS_BROWSER ? document.querySelector("#nextBtn") : null,
@@ -32,7 +27,16 @@ const els = {
secondarySubtitle: IS_BROWSER ? document.querySelector("#secondarySubtitle") : null,
subtitleMeta: IS_BROWSER ? document.querySelector("#subtitleMeta") : null,
transcriptList: IS_BROWSER ? document.querySelector("#transcriptList") : null,
rightPanelTitle: IS_BROWSER ? document.querySelector("#rightPanelTitle") : null,
rightPracticeView: IS_BROWSER ? document.querySelector("#rightPracticeView") : null,
modeTabs: IS_BROWSER ? document.querySelectorAll(".tab[data-mode]") : [],
practiceModeLabel: IS_BROWSER ? document.querySelector("#practiceModeLabel") : null,
practicePromptText: IS_BROWSER ? document.querySelector("#practicePromptText") : null,
practiceReferenceText: IS_BROWSER ? document.querySelector("#practiceReferenceText") : null,
practiceAnswerRow: IS_BROWSER ? document.querySelector("#practiceAnswerRow") : null,
practiceAnswerInput: IS_BROWSER ? document.querySelector("#practiceAnswerInput") : null,
checkPracticeBtn: IS_BROWSER ? document.querySelector("#checkPracticeBtn") : null,
practiceFeedback: IS_BROWSER ? document.querySelector("#practiceFeedback") : null,
adminEntryBtn: IS_BROWSER ? document.querySelector("#adminEntryBtn") : null,
savedLists: IS_BROWSER ? document.querySelector("#savedLists") : null,
};
@@ -142,8 +146,13 @@ let hlsInstance = null;
let libraryLoadMessage = "";
let lastProgressSaveAt = 0;
let pendingRestoreProgress = null;
let currentSessionUser = null;
let progressSyncQueue = null;
async function apiRequest(path, options = {}) {
if (IS_BROWSER && window.SpeakingAuth) {
return window.SpeakingAuth.apiRequest(path, options);
}
const response = await fetch(path, options);
if (!response.ok) {
let message = "请求失败,请重试。";
@@ -189,6 +198,15 @@ if (IS_BROWSER) {
}
async function initializeApp() {
currentSessionUser = await window.SpeakingAuth.requireSession();
if (!currentSessionUser) return;
ensureLocalUserForSession(currentSessionUser);
progressSyncQueue = window.SpeakingProgressSync?.createProgressSyncQueue({
getUser: getCurrentUser,
apiRequest,
saveState,
}) || null;
try {
libraryLoadMessage = "";
const videos = await apiRequest("/api/videos");
@@ -202,6 +220,8 @@ async function initializeApp() {
libraryLoadMessage = "后端视频库加载失败,当前显示示例素材。";
}
await syncLearningProgressFromBackend();
const requestedVideoId = getRequestedVideoId();
if (requestedVideoId && getVideo(requestedVideoId)) {
activeVideoId = requestedVideoId;
@@ -216,35 +236,20 @@ async function initializeApp() {
}
function bindEvents() {
els.loginForm.addEventListener("submit", (event) => {
event.preventDefault();
loginOrRegister();
});
els.logoutBtn.addEventListener("click", () => {
state.currentUserId = null;
saveState();
renderAccount();
renderSavedLists();
renderVideoMeta();
});
els.logoutBtn.addEventListener("click", () => window.SpeakingAuth.logout());
els.searchInput?.addEventListener("input", renderLibrary);
els.modeTabs.forEach((tab) => {
tab.addEventListener("click", () => {
subtitleMode = tab.dataset.mode || "bilingual";
state.subtitleMode = subtitleMode;
saveState();
renderSubtitleModeTabs();
renderTranscript();
syncSubtitles();
setStudyMode(tab.dataset.mode || "bilingual");
});
});
els.practiceAnswerInput?.addEventListener("input", clearPracticeFeedback);
els.checkPracticeBtn?.addEventListener("click", checkPracticeAnswer);
els.video.addEventListener("timeupdate", handleTimeUpdate);
els.previousBtn.addEventListener("click", () => jumpRelative(-1));
els.replayBtn.addEventListener("click", () => jumpToLine(activeLineIndex >= 0 ? activeLineIndex : 0));
els.nextBtn.addEventListener("click", () => jumpRelative(1));
els.continueBtn.addEventListener("click", continueLearning);
els.favoriteBtn.addEventListener("click", () => toggleSaved("favorites"));
els.watchLaterBtn.addEventListener("click", () => toggleSaved("watchLater"));
els.recordBtn.addEventListener("click", startRecording);
els.stopRecordBtn.addEventListener("click", stopRecording);
els.playRecordingBtn.addEventListener("click", () => {
@@ -272,22 +277,14 @@ function renderAll() {
}
function renderAccount() {
const user = getCurrentUser();
els.loginForm.hidden = Boolean(user);
els.userMenu.hidden = !user;
if (user) {
els.userLabel.textContent = `${user.email}${user.role === "admin" ? " · 管理员" : ""}`;
}
els.userMenu.hidden = false;
els.userLabel.textContent = currentSessionUser?.username || "";
renderAdminAccess();
renderContinueAction();
}
function renderAdminAccess() {
if (!els.adminEntryBtn) return;
const user = getCurrentUser();
const email = String(user?.email || "").toLowerCase();
const isAdmin = user?.role === "admin" || email.includes("admin");
els.adminEntryBtn.hidden = !isAdmin;
els.adminEntryBtn.hidden = currentSessionUser?.role !== "admin";
}
function renderLibrary() {
@@ -389,8 +386,8 @@ function selectVideo(id) {
renderTranscript();
restoreProgressForActiveVideo();
syncSubtitles();
renderPracticePanel();
updateNavigationState();
renderContinueAction();
}
async function loadVideoSource(video) {
@@ -434,9 +431,8 @@ function renderVideoMeta() {
const video = getActiveVideo();
if (!video) return;
const user = getCurrentUser();
els.videoTitle.textContent = video.title;
if (els.videoTitle) els.videoTitle.textContent = video.title;
els.favoriteBtn.textContent = user?.favorites.includes(video.id) ? "已收藏" : "收藏";
els.watchLaterBtn.textContent = user?.watchLater.includes(video.id) ? "已加入稍后再看" : "稍后再看";
}
function renderSubtitleModeTabs() {
@@ -445,6 +441,76 @@ function renderSubtitleModeTabs() {
});
}
function isInputPracticeMode(mode = subtitleMode) {
return mode === "dictation" || mode === "translation";
}
function setStudyMode(mode) {
subtitleMode = practiceModeLabels[mode] ? mode : "bilingual";
state.subtitleMode = subtitleMode;
saveState();
clearPracticeResponse();
renderSubtitleModeTabs();
renderTranscript();
syncSubtitles();
renderPracticePanel();
}
function getActiveCuePair() {
const video = getActiveVideo();
const index = activeLineIndex >= 0 ? activeLineIndex : 0;
return {
english: video?.subtitles?.en?.cues?.[index] || null,
chinese: video?.subtitles?.zh?.cues?.[index] || null,
};
}
function clearPracticeFeedback() {
if (!els.practiceFeedback) return;
els.practiceFeedback.textContent = "";
els.practiceFeedback.className = "practice-feedback";
}
function clearPracticeResponse() {
if (els.practiceAnswerInput) els.practiceAnswerInput.value = "";
clearPracticeFeedback();
}
function renderPracticePanel() {
const isPracticeMode = isInputPracticeMode();
if (els.rightPracticeView) els.rightPracticeView.hidden = !isPracticeMode;
if (els.transcriptList) els.transcriptList.hidden = isPracticeMode;
if (els.rightPanelTitle) {
els.rightPanelTitle.textContent = isPracticeMode ? practiceModeLabels[subtitleMode] : "字幕列表";
}
if (!els.practiceModeLabel || !els.practicePromptText || !els.practiceReferenceText) return;
const viewState = getPracticeViewState(subtitleMode, getActiveCuePair());
els.practiceModeLabel.textContent = viewState.label;
els.practicePromptText.textContent = viewState.promptText;
els.practiceReferenceText.textContent = isPracticeMode ? viewState.referenceText : "";
if (els.practiceAnswerRow) els.practiceAnswerRow.hidden = !viewState.inputVisible;
if (els.checkPracticeBtn) els.checkPracticeBtn.disabled = viewState.inputVisible && !viewState.canCheck;
if (viewState.feedbackHint && els.practiceFeedback && !els.practiceFeedback.textContent) {
els.practiceFeedback.textContent = viewState.feedbackHint;
els.practiceFeedback.className = "practice-feedback is-muted";
}
}
function checkPracticeAnswer() {
if (!els.practiceAnswerInput || !els.practiceFeedback) return;
const viewState = getPracticeViewState(subtitleMode, getActiveCuePair());
const result = comparePracticeAnswer(els.practiceAnswerInput.value, viewState.expectedText);
els.practiceFeedback.textContent = result.isCorrect || !result.reference
? result.message
: `${result.message} ${result.reference}`;
els.practiceFeedback.className = `practice-feedback is-${result.status}`;
}
function renderTranscript() {
const primary = getPrimaryCues();
const secondary = getSecondaryCues();
@@ -453,12 +519,16 @@ function renderTranscript() {
els.transcriptList.innerHTML = "";
if (!primary.length) {
els.subtitleMeta.textContent = modeConfig.message || "当前视频没有可用字幕。";
if (els.subtitleMeta) els.subtitleMeta.textContent = modeConfig.message || "当前视频没有可用字幕。";
els.transcriptList.innerHTML = `<div class="empty-state">${modeConfig.message || "请在后台上传 .srt 或 .vtt 字幕。"}</div>`;
return;
}
els.subtitleMeta.textContent = modeConfig.message || `${primary.length} 句 · 点击文字稿跳转到对应片段`;
if (els.subtitleMeta) {
els.subtitleMeta.textContent = isInputPracticeMode()
? "专注练习当前句"
: modeConfig.message || `${primary.length} 句 · 点击文字稿跳转到对应片段`;
}
const fragment = document.createDocumentFragment();
primary.forEach((cue, index) => {
@@ -552,6 +622,8 @@ function setActiveLine(index, scrollIntoView) {
}
syncSubtitles();
clearPracticeResponse();
renderPracticePanel();
updateNavigationState();
saveActiveProgress({ activeLineIndex: index }, true);
}
@@ -560,8 +632,9 @@ function syncSubtitles() {
const primary = getPrimaryCues()[activeLineIndex];
const secondary = getSecondaryCues()[activeLineIndex];
const modeConfig = getActiveSubtitleModeConfig();
els.primarySubtitle.textContent = primary?.text || "";
els.secondarySubtitle.textContent = modeConfig.showSecondary && secondary ? secondary.text : "";
if (els.primarySubtitle) els.primarySubtitle.textContent = primary?.text || "";
if (els.secondarySubtitle) els.secondarySubtitle.textContent = modeConfig.showSecondary && secondary ? secondary.text : "";
renderPracticePanel();
}
function updateNavigationState() {
@@ -586,8 +659,8 @@ function saveActiveProgress(partial = {}, immediate = false) {
if (immediate || now - lastProgressSaveAt > 1500) {
lastProgressSaveAt = now;
saveState();
renderContinueAction();
renderLibrary();
scheduleProgressSync();
}
}
@@ -605,26 +678,6 @@ function restoreProgressForActiveVideo() {
}
}
function continueLearning() {
const progress = getActiveProgress();
if (!progress) return;
if (progress.currentTime > 1) {
els.video.currentTime = progress.currentTime;
}
if (progress.activeLineIndex >= 0 && getPrimaryCues()[progress.activeLineIndex]) {
jumpToLine(progress.activeLineIndex);
return;
}
els.video.play().catch(() => {});
}
function renderContinueAction() {
const progress = getActiveProgress();
const hasProgress = Boolean(progress && (progress.currentTime > 1 || progress.activeLineIndex > 0));
els.continueBtn.hidden = !hasProgress;
}
function toggleLineStatus(index, status, event) {
event.stopPropagation();
const progress = getActiveProgress();
@@ -642,6 +695,7 @@ function toggleLineStatus(index, status, event) {
progress.updatedAt = new Date().toISOString();
saveState();
scheduleProgressSync();
renderTranscript();
renderLibrary();
}
@@ -659,21 +713,38 @@ function toggleSaved(field) {
user[field] = [...list, activeVideoId];
}
saveState();
scheduleProgressSync();
renderVideoMeta();
renderSavedLists();
}
async function syncLearningProgressFromBackend() {
if (!window.SpeakingProgressSync) return;
try {
await window.SpeakingProgressSync.syncLearningState({
user: getCurrentUser(),
apiRequest,
saveState,
});
} catch (error) {
console.warn("Learning progress sync failed", error);
}
}
function scheduleProgressSync() {
progressSyncQueue?.schedule();
}
function renderSavedLists() {
if (!els.savedLists) return;
const user = getCurrentUser();
if (!user) {
els.savedLists.innerHTML = "登录后可使用收藏和稍后再看。";
els.savedLists.innerHTML = "登录后可使用收藏。";
return;
}
els.savedLists.innerHTML = `
<div><strong>收藏</strong><br>${renderSavedNames(user.favorites)}</div>
<div><strong>稍后再看</strong><br>${renderSavedNames(user.watchLater)}</div>
`;
}
@@ -682,34 +753,22 @@ function renderSavedNames(ids) {
return ids.map((id) => getVideo(id)?.title).filter(Boolean).join("、");
}
function loginOrRegister() {
const email = els.emailInput.value.trim().toLowerCase();
const password = els.passwordInput.value;
if (!email || !password) return;
function ensureLocalUserForSession(sessionUser) {
const email = sessionUser.username;
let user = state.users.find((item) => item.email === email);
if (!user) {
user = {
id: `user-${Date.now()}`,
id: `server-${sessionUser.id || email}`,
email,
password,
role: email.includes("admin") ? "admin" : "user",
role: sessionUser.role || "user",
favorites: [],
watchLater: [],
progress: {},
};
state.users.push(user);
} else if (user.password !== password) {
alert("密码不匹配。");
return;
}
state.currentUserId = user.id;
saveState();
els.loginForm.reset();
renderAccount();
renderVideoMeta();
renderSavedLists();
}
async function startRecording() {
@@ -779,6 +838,134 @@ function getSecondaryCues() {
return video?.subtitles?.[config.secondaryCode]?.cues || [];
}
const practiceModeLabels = {
bilingual: "双语",
english: "英文",
chinese: "中文",
dictation: "听写",
translation: "中译英",
};
function normalizePracticeAnswer(text) {
return String(text || "")
.toLowerCase()
.replace(/['’‘]/g, "")
.replace(/[“”]/g, "\"")
.replace(/[-–—]+/g, " ")
.replace(/[.,!?;:"()[\]{},。!?;:“”、]/g, " ")
.replace(/\s+/g, " ")
.trim();
}
function comparePracticeAnswer(input, expected) {
const reference = String(expected || "").trim();
const normalizedInput = normalizePracticeAnswer(input);
const normalizedExpected = normalizePracticeAnswer(expected);
if (!normalizedInput) {
return {
status: "empty",
isCorrect: false,
reference,
message: "请输入答案后再核对。",
};
}
if (!normalizedExpected) {
return {
status: "missing-reference",
isCorrect: false,
reference,
message: "当前句没有可核对的英文参考。",
};
}
if (normalizedInput === normalizedExpected) {
return {
status: "correct",
isCorrect: true,
reference,
message: "完全匹配。",
};
}
return {
status: "incorrect",
isCorrect: false,
reference,
message: "还不完全一致,参考答案如下。",
};
}
function getPracticeViewState(mode, cuePair = {}) {
const englishText = cuePair.english?.text?.trim() || "";
const chineseText = cuePair.chinese?.text?.trim() || "";
const normalizedMode = practiceModeLabels[mode] ? mode : "bilingual";
if (normalizedMode === "dictation") {
return {
mode: normalizedMode,
label: practiceModeLabels[normalizedMode],
promptText: "听音频,写出当前英文句子。",
referenceText: "",
expectedText: englishText,
inputVisible: true,
canCheck: Boolean(englishText),
feedbackHint: englishText ? "" : "当前句没有可核对的英文参考。",
};
}
if (normalizedMode === "translation") {
return {
mode: normalizedMode,
label: practiceModeLabels[normalizedMode],
promptText: chineseText || "当前句没有中文字幕。",
referenceText: "根据中文写出英文句子。",
expectedText: englishText,
inputVisible: true,
canCheck: Boolean(englishText),
feedbackHint: englishText ? "" : "当前句没有可核对的英文参考。",
};
}
if (normalizedMode === "english") {
return {
mode: normalizedMode,
label: practiceModeLabels[normalizedMode],
promptText: englishText || "当前句没有英文字幕。",
referenceText: "",
expectedText: englishText,
inputVisible: false,
canCheck: false,
feedbackHint: "",
};
}
if (normalizedMode === "chinese") {
return {
mode: normalizedMode,
label: practiceModeLabels[normalizedMode],
promptText: chineseText || "当前句没有中文字幕。",
referenceText: "",
expectedText: englishText,
inputVisible: false,
canCheck: false,
feedbackHint: "",
};
}
return {
mode: "bilingual",
label: practiceModeLabels.bilingual,
promptText: englishText || "当前句没有英文字幕。",
referenceText: chineseText,
expectedText: englishText,
inputVisible: false,
canCheck: false,
feedbackHint: "",
};
}
function getActiveSubtitleModeConfig() {
const video = getActiveVideo();
return getSubtitleModeConfig(subtitleMode, video?.subtitles || {});
@@ -807,6 +994,24 @@ function getSubtitleModeConfig(mode, subtitles = {}) {
};
}
if (mode === "translation") {
return {
primaryCode: hasChinese ? "zh" : fallbackCode,
secondaryCode: "",
showSecondary: false,
message: hasChinese ? "" : "当前素材没有中文字幕。",
};
}
if (mode === "dictation") {
return {
primaryCode: hasEnglish ? "en" : fallbackCode,
secondaryCode: "",
showSecondary: false,
message: "",
};
}
return {
primaryCode: hasEnglish ? "en" : fallbackCode,
secondaryCode: "",
@@ -1063,6 +1268,9 @@ if (typeof module !== "undefined" && module.exports) {
calculatePracticeSummary,
formatProgressSummary,
getSubtitleModeConfig,
normalizePracticeAnswer,
comparePracticeAnswer,
getPracticeViewState,
parseSubtitle,
};
}
+141
View File
@@ -0,0 +1,141 @@
(function () {
const IS_BROWSER = typeof window !== "undefined";
const TOKEN_KEY = "speaking-lab-auth-token-v1";
const USER_KEY = "speaking-lab-auth-user-v1";
function getToken() {
return window.sessionStorage.getItem(TOKEN_KEY) || "";
}
function getStoredUser() {
try {
return JSON.parse(window.sessionStorage.getItem(USER_KEY) || "null");
} catch {
return null;
}
}
function setSession(payload) {
if (!payload?.token || !payload?.user) return null;
window.sessionStorage.setItem(TOKEN_KEY, payload.token);
window.sessionStorage.setItem(USER_KEY, JSON.stringify(payload.user));
return payload.user;
}
function clearSession() {
window.sessionStorage.removeItem(TOKEN_KEY);
window.sessionStorage.removeItem(USER_KEY);
}
function getLoginUrl() {
const current = `${window.location.pathname}${window.location.search}`;
return `./login.html?next=${encodeURIComponent(current)}`;
}
function isUnauthorizedStatus(status) {
return Number(status) === 401;
}
function redirectToLogin() {
clearSession();
window.location.href = getLoginUrl();
}
async function apiRequest(path, options = {}) {
const headers = new Headers(options.headers || {});
if (options.body && !(options.body instanceof FormData) && !headers.has("Content-Type")) {
headers.set("Content-Type", "application/json");
}
const token = getToken();
if (token) headers.set("Authorization", `Bearer ${token}`);
const response = await fetch(path, { ...options, headers });
if (!response.ok) {
let message = "请求失败,请重试。";
try {
const payload = await response.json();
message = payload.detail || message;
} catch {
message = response.statusText || message;
}
if (isUnauthorizedStatus(response.status)) {
redirectToLogin();
}
throw new Error(message);
}
return response.json();
}
async function login(username, password) {
const payload = await apiRequest("/api/auth/login", {
method: "POST",
body: JSON.stringify({ username, password }),
});
setSession(payload);
return payload.user;
}
async function register(activationCode, username, password) {
const payload = await apiRequest("/api/auth/register", {
method: "POST",
body: JSON.stringify({ activationCode, username, password }),
});
setSession(payload);
return payload.user;
}
async function requireSession(options = {}) {
const token = getToken();
if (!token) {
if (options.redirect !== false) window.location.href = getLoginUrl();
return null;
}
try {
const payload = await apiRequest("/api/auth/session");
setSession({ token, user: payload.user });
if (options.adminOnly && payload.user.role !== "admin") {
if (options.redirect !== false) window.location.href = "./index.html";
return null;
}
return payload.user;
} catch {
clearSession();
if (options.redirect !== false) window.location.href = getLoginUrl();
return null;
}
}
function logout() {
clearSession();
window.location.href = "./login.html";
}
if (IS_BROWSER) {
window.SpeakingAuth = {
apiRequest,
clearSession,
getLoginUrl,
getStoredUser,
getToken,
isUnauthorizedStatus,
login,
logout,
register,
requireSession,
setSession,
};
}
if (typeof module !== "undefined" && module.exports) {
module.exports = {
getLoginUrlForPath(path) {
return `./login.html?next=${encodeURIComponent(path)}`;
},
isUnauthorizedStatus,
shouldShowAdminEntry(user) {
return user?.role === "admin";
},
};
}
})();
+127
View File
@@ -0,0 +1,127 @@
from __future__ import annotations
from dataclasses import dataclass
import os
from pathlib import Path
from .local_whisper import LocalWhisperConfig
PROJECT_DIR = Path(__file__).resolve().parent.parent
ENV_PATH = PROJECT_DIR / ".env"
@dataclass(frozen=True)
class DeepSeekConfig:
api_key: str
base_url: str
model: str
audio_model: str
provider: str
protocol: str
translation_batch_size: int
timeout_seconds: int
def read_env_file(path: Path = ENV_PATH) -> dict[str, str]:
if not path.exists():
return {}
values: dict[str, str] = {}
for raw_line in path.read_text(encoding="utf-8-sig").splitlines():
line = raw_line.strip()
if not line or line.startswith("#") or "=" not in line:
continue
key, value = line.split("=", 1)
values[key.strip().lstrip("\ufeff")] = value.strip().strip('"').strip("'")
return values
def get_config_value(key: str, default: str = "") -> str:
env_values = read_env_file()
return os.getenv(key, env_values.get(key, default)).strip()
def load_text_ai_config() -> DeepSeekConfig:
api_key = (
get_config_value("TEXT_AI_API_KEY")
or get_config_value("AI_API_KEY")
or get_config_value("DEEPSEEK_API_KEY")
)
base_url = (
get_config_value("TEXT_AI_BASE_URL")
or get_config_value("AI_BASE_URL")
or get_config_value("DEEPSEEK_BASE_URL", "https://api.deepseek.com")
)
model = (
get_config_value("TEXT_AI_MODEL")
or get_config_value("AI_TEXT_MODEL")
or get_config_value("DEEPSEEK_MODEL", "deepseek-chat")
)
return DeepSeekConfig(
api_key=api_key,
base_url=base_url.rstrip("/"),
model=model,
audio_model=get_config_value("TEXT_AI_AUDIO_MODEL") or get_config_value("AI_AUDIO_MODEL") or model,
provider=get_config_value("TEXT_AI_PROVIDER") or get_config_value("AI_PROVIDER", "deepseek") or "deepseek",
protocol=(get_config_value("TEXT_AI_PROTOCOL") or get_config_value("AI_API_PROTOCOL", "openai") or "openai").lower(),
translation_batch_size=parse_non_negative_int_config(get_config_value("TEXT_AI_BATCH_SIZE") or get_config_value("AI_TRANSLATION_BATCH_SIZE", "40"), 40),
timeout_seconds=parse_int_config(get_config_value("TEXT_AI_TIMEOUT_SECONDS") or get_config_value("AI_TIMEOUT_SECONDS", "120"), 120),
)
def load_local_whisper_config() -> LocalWhisperConfig:
return LocalWhisperConfig(
enabled=parse_bool_config(get_config_value("LOCAL_WHISPER_ENABLED", "false")),
model=get_config_value("LOCAL_WHISPER_MODEL", "small") or "small",
device=get_config_value("LOCAL_WHISPER_DEVICE", "cpu") or "cpu",
compute_type=get_config_value("LOCAL_WHISPER_COMPUTE_TYPE", "int8") or "int8",
)
def load_deepseek_config() -> DeepSeekConfig:
api_key = get_config_value("AI_API_KEY") or get_config_value("DEEPSEEK_API_KEY")
base_url = get_config_value("AI_BASE_URL") or get_config_value("DEEPSEEK_BASE_URL", "https://api.deepseek.com")
model = get_config_value("AI_TEXT_MODEL") or get_config_value("DEEPSEEK_MODEL", "deepseek-chat")
return DeepSeekConfig(
api_key=api_key,
base_url=base_url.rstrip("/"),
model=model,
audio_model=get_config_value("AI_AUDIO_MODEL") or model,
provider=get_config_value("AI_PROVIDER", "deepseek") or "deepseek",
protocol=(get_config_value("AI_API_PROTOCOL", "openai") or "openai").lower(),
translation_batch_size=parse_int_config(get_config_value("AI_TRANSLATION_BATCH_SIZE", "5"), 5),
timeout_seconds=parse_int_config(get_config_value("AI_TIMEOUT_SECONDS", "180"), 180),
)
def get_ai_status() -> dict[str, object]:
text_config = load_text_ai_config()
return {
"configured": bool(text_config.api_key),
"provider": text_config.provider,
"protocol": text_config.protocol,
"model": text_config.model,
"localWhisperEnabled": load_local_whisper_config().enabled,
"message": "AI API 已配置。" if text_config.api_key else "未配置 TEXT_AI_API_KEY,请在 .env 中填写。",
}
def parse_int_config(value: str, default: int) -> int:
try:
parsed = int(str(value).strip())
except (TypeError, ValueError):
return default
return parsed if parsed > 0 else default
def parse_non_negative_int_config(value: str, default: int) -> int:
try:
parsed = int(str(value).strip())
except (TypeError, ValueError):
return default
return parsed if parsed >= 0 else default
def parse_bool_config(value: str) -> bool:
return str(value or "").strip().lower() in {"1", "true", "yes", "on"}
+99
View File
@@ -0,0 +1,99 @@
import base64
import hashlib
import hmac
import json
import secrets
import time
PASSWORD_ALGORITHM = "pbkdf2_sha256"
PASSWORD_ITERATIONS = 120_000
TOKEN_TTL_SECONDS = 60 * 60 * 24 * 7
def _b64url_encode(value: bytes) -> str:
return base64.urlsafe_b64encode(value).decode("ascii").rstrip("=")
def _b64url_decode(value: str) -> bytes:
padding = "=" * (-len(value) % 4)
return base64.urlsafe_b64decode(value + padding)
def hash_password(password: str) -> str:
salt = secrets.token_hex(16)
digest = hashlib.pbkdf2_hmac(
"sha256",
password.encode("utf-8"),
salt.encode("ascii"),
PASSWORD_ITERATIONS,
).hex()
return f"{PASSWORD_ALGORITHM}${PASSWORD_ITERATIONS}${salt}${digest}"
def verify_password(password: str, stored_hash: str) -> bool:
try:
algorithm, iterations_raw, salt, expected = stored_hash.split("$", 3)
iterations = int(iterations_raw)
except (ValueError, AttributeError):
return False
if algorithm != PASSWORD_ALGORITHM:
return False
actual = hashlib.pbkdf2_hmac(
"sha256",
password.encode("utf-8"),
salt.encode("ascii"),
iterations,
).hex()
return hmac.compare_digest(actual, expected)
def create_auth_token(payload: dict[str, object], secret: str, ttl_seconds: int = TOKEN_TTL_SECONDS) -> str:
token_payload = {
**payload,
"exp": int(time.time()) + ttl_seconds,
}
payload_json = json.dumps(token_payload, separators=(",", ":"), sort_keys=True).encode("utf-8")
payload_part = _b64url_encode(payload_json)
signature = hmac.new(secret.encode("utf-8"), payload_part.encode("ascii"), hashlib.sha256).digest()
return f"{payload_part}.{_b64url_encode(signature)}"
def verify_auth_token(token: str, secret: str) -> dict[str, object] | None:
try:
payload_part, signature_part = token.split(".", 1)
except ValueError:
return None
expected_signature = hmac.new(
secret.encode("utf-8"),
payload_part.encode("ascii"),
hashlib.sha256,
).digest()
try:
actual_signature = _b64url_decode(signature_part)
except (ValueError, base64.binascii.Error):
return None
if not hmac.compare_digest(actual_signature, expected_signature):
return None
try:
payload = json.loads(_b64url_decode(payload_part).decode("utf-8"))
except (ValueError, UnicodeDecodeError):
return None
if int(payload.get("exp") or 0) < int(time.time()):
return None
return payload if isinstance(payload, dict) else None
def normalize_username(username: str) -> str:
return username.strip().lower()
def generate_activation_code() -> str:
groups = [secrets.token_urlsafe(4).replace("-", "X").replace("_", "Y").upper()[:6] for _ in range(3)]
return "SL-" + "-".join(groups)
+462 -4
View File
@@ -38,6 +38,7 @@ def initialize_database() -> None:
description TEXT,
tags TEXT,
video_url TEXT,
cover_url TEXT,
duration_seconds INTEGER,
status TEXT NOT NULL DEFAULT 'draft',
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
@@ -76,6 +77,51 @@ def initialize_database() -> None:
ON user_interactions (user_id);
"""
)
video_columns = {
row["name"]
for row in connection.execute("PRAGMA table_info(videos)").fetchall()
}
if "cover_url" not in video_columns:
connection.execute("ALTER TABLE videos ADD COLUMN cover_url TEXT")
user_columns = {
row["name"]
for row in connection.execute("PRAGMA table_info(users)").fetchall()
}
if "is_active" not in user_columns:
connection.execute("ALTER TABLE users ADD COLUMN is_active INTEGER NOT NULL DEFAULT 1")
if "last_login_at" not in user_columns:
connection.execute("ALTER TABLE users ADD COLUMN last_login_at TEXT")
if "session_token" not in user_columns:
connection.execute("ALTER TABLE users ADD COLUMN session_token TEXT")
interaction_columns = {
row["name"]
for row in connection.execute("PRAGMA table_info(user_interactions)").fetchall()
}
if "payload_json" not in interaction_columns:
connection.execute("ALTER TABLE user_interactions ADD COLUMN payload_json TEXT")
connection.executescript(
"""
CREATE TABLE IF NOT EXISTS activation_codes (
id INTEGER PRIMARY KEY AUTOINCREMENT,
code TEXT NOT NULL UNIQUE,
created_by TEXT NOT NULL,
used_by_user_id INTEGER,
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
used_at TEXT,
status TEXT NOT NULL DEFAULT 'unused',
FOREIGN KEY (used_by_user_id) REFERENCES users (id) ON DELETE SET NULL
);
CREATE INDEX IF NOT EXISTS idx_activation_codes_status
ON activation_codes (status);
"""
)
connection.execute(
"""
DELETE FROM activation_codes
WHERE status != 'unused'
"""
)
connection.execute(
"""
DELETE FROM subtitles
@@ -94,6 +140,373 @@ def initialize_database() -> None:
)
def row_to_user(row: sqlite3.Row) -> dict[str, object]:
return {
"id": row["id"],
"username": repair_mojibake_text(row["email"]),
"displayName": repair_mojibake_text(row["display_name"] or row["email"]),
"role": row["role"],
"isActive": bool(row["is_active"]),
"createdAt": row["created_at"],
"updatedAt": row["updated_at"],
"lastLoginAt": row["last_login_at"] or "",
"sessionToken": row["session_token"] or "",
}
def row_to_activation_code(row: sqlite3.Row) -> dict[str, object]:
return {
"id": row["id"],
"code": row["code"],
"createdBy": row["created_by"],
"status": row["status"],
"createdAt": row["created_at"],
"usedAt": row["used_at"] or "",
"usedByUserId": row["used_by_user_id"],
"usedByUsername": repair_mojibake_text(row["used_by_username"] or ""),
}
def get_user_by_username(username: str) -> dict[str, object] | None:
with get_connection() as connection:
row = connection.execute(
"""
SELECT *
FROM users
WHERE email = ?
""",
(repair_mojibake_text(username),),
).fetchone()
return row_to_user(row) if row else None
def get_user_auth_record(username: str) -> sqlite3.Row | None:
with get_connection() as connection:
return connection.execute(
"""
SELECT *
FROM users
WHERE email = ?
""",
(repair_mojibake_text(username),),
).fetchone()
def get_user_by_id(user_id: int) -> dict[str, object] | None:
with get_connection() as connection:
row = connection.execute(
"""
SELECT *
FROM users
WHERE id = ?
""",
(user_id,),
).fetchone()
return row_to_user(row) if row else None
def list_users() -> list[dict[str, object]]:
with get_connection() as connection:
rows = connection.execute(
"""
SELECT *
FROM users
ORDER BY created_at DESC, id DESC
"""
).fetchall()
return [row_to_user(row) for row in rows]
def update_user_active(user_id: int, is_active: bool) -> dict[str, object] | None:
with get_connection() as connection:
cursor = connection.execute(
"""
UPDATE users
SET is_active = ?,
updated_at = CURRENT_TIMESTAMP
WHERE id = ?
AND role != 'admin'
""",
(1 if is_active else 0, user_id),
)
if cursor.rowcount == 0:
return None
return get_user_by_id(user_id)
def normalize_interaction_indexes(value: object) -> list[int]:
if not isinstance(value, list):
return []
indexes = {
int(item)
for item in value
if isinstance(item, int) or (isinstance(item, str) and item.isdigit())
}
return sorted(index for index in indexes if index >= 0)
def normalize_progress_payload(payload: dict[str, object] | None, current_time_ms: int | None = None) -> dict[str, object]:
payload = payload if isinstance(payload, dict) else {}
current_time = payload.get("currentTime")
if not isinstance(current_time, (int, float)):
current_time = (current_time_ms or 0) / 1000
active_line_index = payload.get("activeLineIndex")
if not isinstance(active_line_index, int) or active_line_index < 0:
active_line_index = 0
return {
"currentTime": float(current_time or 0),
"activeLineIndex": active_line_index,
"practicedLineIndexes": normalize_interaction_indexes(payload.get("practicedLineIndexes")),
"difficultLineIndexes": normalize_interaction_indexes(payload.get("difficultLineIndexes")),
"updatedAt": str(payload.get("updatedAt") or ""),
}
def get_existing_video_ids(connection: sqlite3.Connection) -> set[int]:
rows = connection.execute("SELECT id FROM videos").fetchall()
return {int(row["id"]) for row in rows}
def parse_interaction_video_id(video_id: str | int) -> int | None:
try:
parsed = int(video_id)
except (TypeError, ValueError):
return None
return parsed if parsed > 0 else None
def get_user_learning_state(user_id: int) -> dict[str, object]:
with get_connection() as connection:
rows = connection.execute(
"""
SELECT video_id, interaction_type, current_time_ms, payload_json, updated_at
FROM user_interactions
WHERE user_id = ?
AND interaction_type IN ('favorite', 'progress')
ORDER BY video_id ASC
""",
(user_id,),
).fetchall()
favorites: list[str] = []
progress: dict[str, dict[str, object]] = {}
for row in rows:
video_id = str(row["video_id"])
if row["interaction_type"] == "favorite":
favorites.append(video_id)
continue
try:
payload = json.loads(row["payload_json"] or "{}")
except json.JSONDecodeError:
payload = {}
normalized = normalize_progress_payload(payload, row["current_time_ms"])
if not normalized["updatedAt"]:
normalized["updatedAt"] = row["updated_at"] or ""
progress[video_id] = normalized
return {
"favorites": sorted(set(favorites), key=lambda item: int(item)),
"progress": progress,
}
def save_user_learning_state(
user_id: int,
*,
favorites: list[str],
progress: dict[str, dict[str, object]],
) -> dict[str, object]:
with get_connection() as connection:
existing_video_ids = get_existing_video_ids(connection)
favorite_ids = [
parsed
for item in favorites
if (parsed := parse_interaction_video_id(item)) in existing_video_ids
]
progress_items = {
parsed: normalize_progress_payload(payload)
for item, payload in progress.items()
if (parsed := parse_interaction_video_id(item)) in existing_video_ids
}
connection.execute(
"""
DELETE FROM user_interactions
WHERE user_id = ?
AND interaction_type = 'favorite'
""",
(user_id,),
)
for video_id in sorted(set(favorite_ids)):
connection.execute(
"""
INSERT INTO user_interactions (user_id, video_id, interaction_type)
VALUES (?, ?, 'favorite')
ON CONFLICT(user_id, video_id, interaction_type) DO UPDATE SET
updated_at = CURRENT_TIMESTAMP
""",
(user_id, video_id),
)
connection.execute(
"""
DELETE FROM user_interactions
WHERE user_id = ?
AND interaction_type = 'progress'
""",
(user_id,),
)
for video_id, payload in progress_items.items():
current_time_ms = int(round(float(payload["currentTime"]) * 1000))
connection.execute(
"""
INSERT INTO user_interactions (
user_id, video_id, interaction_type, current_time_ms, payload_json
)
VALUES (?, ?, 'progress', ?, ?)
ON CONFLICT(user_id, video_id, interaction_type) DO UPDATE SET
current_time_ms = excluded.current_time_ms,
payload_json = excluded.payload_json,
updated_at = CURRENT_TIMESTAMP
""",
(
user_id,
video_id,
current_time_ms,
json.dumps(payload, ensure_ascii=False),
),
)
return get_user_learning_state(user_id)
def mark_user_login(user_id: int) -> None:
with get_connection() as connection:
connection.execute(
"""
UPDATE users
SET last_login_at = CURRENT_TIMESTAMP,
updated_at = CURRENT_TIMESTAMP
WHERE id = ?
""",
(user_id,),
)
def rotate_user_session_token(user_id: int, session_token: str) -> None:
with get_connection() as connection:
connection.execute(
"""
UPDATE users
SET session_token = ?,
last_login_at = CURRENT_TIMESTAMP,
updated_at = CURRENT_TIMESTAMP
WHERE id = ?
""",
(session_token, user_id),
)
def register_user_with_activation(*, username: str, password_hash: str, activation_code: str) -> dict[str, object]:
clean_username = repair_mojibake_text(username)
clean_code = activation_code.strip().upper()
with get_connection() as connection:
code_row = connection.execute(
"""
SELECT *
FROM activation_codes
WHERE code = ?
AND status = 'unused'
""",
(clean_code,),
).fetchone()
if code_row is None:
raise ValueError("activation_code_unavailable")
try:
cursor = connection.execute(
"""
INSERT INTO users (
email, password_hash, display_name, role, is_active
)
VALUES (?, ?, ?, 'user', 1)
""",
(clean_username, password_hash, clean_username),
)
except sqlite3.IntegrityError as exc:
raise ValueError("username_exists") from exc
user_id = int(cursor.lastrowid)
connection.execute(
"""
DELETE FROM activation_codes
WHERE id = ?
""",
(code_row["id"],),
)
user = get_user_by_id(user_id)
if user is None:
raise RuntimeError("Registered user could not be loaded")
return user
def create_activation_codes(codes: list[str], created_by: str) -> list[dict[str, object]]:
created_ids: list[int] = []
with get_connection() as connection:
for code in codes:
cursor = connection.execute(
"""
INSERT INTO activation_codes (code, created_by)
VALUES (?, ?)
""",
(code, created_by),
)
created_ids.append(int(cursor.lastrowid))
with get_connection() as connection:
placeholders = ",".join("?" for _ in created_ids)
rows = connection.execute(
f"""
SELECT activation_codes.*, users.email AS used_by_username
FROM activation_codes
LEFT JOIN users ON users.id = activation_codes.used_by_user_id
WHERE activation_codes.id IN ({placeholders})
ORDER BY activation_codes.id DESC
""",
created_ids,
).fetchall()
return [row_to_activation_code(row) for row in rows]
def list_activation_codes() -> list[dict[str, object]]:
with get_connection() as connection:
rows = connection.execute(
"""
SELECT activation_codes.*, users.email AS used_by_username
FROM activation_codes
LEFT JOIN users ON users.id = activation_codes.used_by_user_id
WHERE activation_codes.status = 'unused'
ORDER BY activation_codes.created_at DESC, activation_codes.id DESC
"""
).fetchall()
return [row_to_activation_code(row) for row in rows]
def delete_unused_activation_code(code_id: int) -> bool:
with get_connection() as connection:
cursor = connection.execute(
"""
DELETE FROM activation_codes
WHERE id = ?
AND status = 'unused'
""",
(code_id,),
)
return cursor.rowcount > 0
def repair_mojibake_text(value: str | None) -> str:
if not value:
return ""
@@ -145,6 +558,7 @@ def row_to_video(row: sqlite3.Row, subtitle_rows: list[sqlite3.Row]) -> dict[str
"tags": tags if isinstance(tags, list) and tags else ["未分类"],
"duration": row["duration_seconds"] or 0,
"videoUrl": row["video_url"] or "",
"coverUrl": row["cover_url"] or "",
"sourceType": "url" if str(row["video_url"] or "").startswith(("http://", "https://")) else "local-file",
"subtitles": subtitles,
}
@@ -157,15 +571,16 @@ def create_video(
description: str | None,
tags: list[str],
video_url: str,
cover_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
title, speaker, description, tags, video_url, cover_url, status
)
VALUES (?, ?, ?, ?, ?, 'published')
VALUES (?, ?, ?, ?, ?, ?, 'published')
""",
(
title,
@@ -173,6 +588,7 @@ def create_video(
repair_mojibake_text(description or ""),
json.dumps([repair_mojibake_text(tag) for tag in tags], ensure_ascii=False),
repair_mojibake_text(video_url),
repair_mojibake_text(cover_url),
),
)
video_id = int(cursor.lastrowid)
@@ -259,7 +675,7 @@ def delete_video(video_id: int) -> dict[str, object] | None:
with get_connection() as connection:
video_row = connection.execute(
"""
SELECT id, video_url
SELECT id, video_url, cover_url
FROM videos
WHERE id = ?
""",
@@ -280,6 +696,8 @@ def delete_video(video_id: int) -> dict[str, object] | None:
upload_paths = []
if video_row["video_url"]:
upload_paths.append(video_row["video_url"])
if video_row["cover_url"]:
upload_paths.append(video_row["cover_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,))
@@ -298,12 +716,13 @@ def update_video(
description: str | None,
tags: list[str],
video_url: str | None,
cover_url: str | None = None,
subtitles: list[dict[str, str]],
) -> dict[str, object] | None:
with get_connection() as connection:
existing = connection.execute(
"""
SELECT id, video_url
SELECT id, video_url, cover_url
FROM videos
WHERE id = ?
""",
@@ -316,6 +735,9 @@ def update_video(
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"])
final_cover_url = cover_url if cover_url is not None else existing["cover_url"]
if cover_url is not None and existing["cover_url"] and existing["cover_url"] != cover_url:
old_upload_paths.append(existing["cover_url"])
connection.execute(
"""
@@ -325,6 +747,7 @@ def update_video(
description = ?,
tags = ?,
video_url = ?,
cover_url = ?,
updated_at = CURRENT_TIMESTAMP
WHERE id = ?
""",
@@ -334,6 +757,7 @@ def update_video(
repair_mojibake_text(description or ""),
json.dumps([repair_mojibake_text(tag) for tag in tags], ensure_ascii=False),
repair_mojibake_text(final_video_url),
repair_mojibake_text(final_cover_url or ""),
video_id,
),
)
@@ -382,6 +806,40 @@ def update_video(
}
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),
),
)
def table_names() -> list[str]:
with get_connection() as connection:
rows = connection.execute(
+194
View File
@@ -0,0 +1,194 @@
from __future__ import annotations
import base64
import json
import re
import urllib.error
import urllib.request
from pathlib import Path
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("未配置 AI_API_KEY。")
if self.config.protocol == "anthropic":
return self._anthropic_chat_json(system_prompt, user_payload)
return self._openai_chat_json(system_prompt, user_payload)
def audio_json(self, system_prompt: str, audio_path: Path, user_text: str) -> dict[str, object]:
if not self.config.api_key:
raise DeepSeekError("未配置 AI_API_KEY。")
if self.config.protocol == "anthropic":
return self._anthropic_audio_json(system_prompt, audio_path, user_text)
return self._openai_audio_json(system_prompt, audio_path, user_text)
def _openai_chat_json(self, system_prompt: str, user_payload: dict[str, object]) -> dict[str, object]:
body = {
"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"},
}
payload = self._post_json("/chat/completions", body, self._openai_headers(), "AI 请求失败")
content = payload.get("choices", [{}])[0].get("message", {}).get("content", "")
return self._parse_json_text(content, "AI 返回内容不是有效 JSON。")
def _openai_audio_json(self, system_prompt: str, audio_path: Path, user_text: str) -> dict[str, object]:
audio_data = base64.b64encode(audio_path.read_bytes()).decode("ascii")
body = {
"model": self.config.audio_model,
"messages": [
{"role": "system", "content": system_prompt},
{
"role": "user",
"content": [
{"type": "text", "text": user_text},
{
"type": "input_audio",
"input_audio": {
"data": f"data:audio/wav;base64,{audio_data}",
"format": "wav",
},
},
],
},
],
"response_format": {"type": "json_object"},
}
payload = self._post_json("/chat/completions", body, self._openai_headers(), "音频识别请求失败")
content = payload.get("choices", [{}])[0].get("message", {}).get("content", "")
return self._parse_json_text(content, "音频识别返回内容不是有效 JSON。")
def _anthropic_chat_json(self, system_prompt: str, user_payload: dict[str, object]) -> dict[str, object]:
body = {
"model": self.config.model,
"max_tokens": 4096,
"system": system_prompt,
"messages": [
{
"role": "user",
"content": [
{
"type": "text",
"text": (
"Return only one valid JSON object. Do not use markdown fences or extra text.\n"
f"{json.dumps(user_payload, ensure_ascii=False)}"
),
}
],
}
],
}
payload = self._post_json("/v1/messages", body, self._anthropic_headers(), "Anthropic 请求失败")
return self._parse_json_text(self._extract_anthropic_text(payload), "Anthropic 返回内容不是有效 JSON。")
def _anthropic_audio_json(self, system_prompt: str, audio_path: Path, user_text: str) -> dict[str, object]:
audio_data = base64.b64encode(audio_path.read_bytes()).decode("ascii")
body = {
"model": self.config.audio_model,
"max_tokens": 1024,
"system": system_prompt,
"messages": [
{
"role": "user",
"content": [
{"type": "text", "text": user_text},
{
"type": "input_audio",
"source": {
"type": "base64",
"media_type": "audio/wav",
"data": audio_data,
},
},
],
}
],
}
payload = self._post_json("/v1/messages", body, self._anthropic_headers(), "Anthropic 音频识别请求失败")
return self._parse_json_text(self._extract_anthropic_text(payload), "Anthropic 音频识别返回内容不是有效 JSON。")
def _post_json(
self,
path: str,
body: dict[str, object],
headers: dict[str, str],
error_prefix: str,
) -> dict[str, object]:
request = urllib.request.Request(
f"{self.config.base_url}{path}",
data=json.dumps(body).encode("utf-8"),
headers=headers,
method="POST",
)
try:
with urllib.request.urlopen(request, timeout=self.timeout_seconds) as response:
return json.loads(response.read().decode("utf-8"))
except urllib.error.HTTPError as error:
detail = error.read().decode("utf-8", errors="replace")
raise DeepSeekError(f"{error_prefix}:{error.code} {detail}") from error
except Exception as error:
raise DeepSeekError(f"{error_prefix}:{error}") from error
def _openai_headers(self) -> dict[str, str]:
return {
"Authorization": f"Bearer {self.config.api_key}",
"Content-Type": "application/json",
}
def _anthropic_headers(self) -> dict[str, str]:
return {
"x-api-key": self.config.api_key,
"anthropic-version": "2023-06-01",
"Content-Type": "application/json",
}
def _extract_anthropic_text(self, payload: dict[str, object]) -> str:
blocks = payload.get("content", [])
if not isinstance(blocks, list):
return ""
texts = [
str(block.get("text", ""))
for block in blocks
if isinstance(block, dict) and block.get("type") == "text"
]
return "\n".join(texts).strip()
def _parse_json_text(self, content: str, error_message: str) -> dict[str, object]:
json_text = self._extract_json_text(content)
try:
return json.loads(json_text)
except json.JSONDecodeError as error:
raise DeepSeekError(error_message) from error
def _extract_json_text(self, content: str) -> str:
text = str(content or "").strip()
if not text:
return text
fenced = re.search(r"```(?:json)?\s*(\{.*?\})\s*```", text, re.IGNORECASE | re.DOTALL)
if fenced:
return fenced.group(1).strip()
start = text.find("{")
if start < 0:
return text
decoder = json.JSONDecoder()
try:
_, end = decoder.raw_decode(text[start:])
except json.JSONDecodeError:
return text
return text[start:start + end].strip()
+101
View File
@@ -0,0 +1,101 @@
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
import importlib
import subprocess
import tempfile
from .subtitle_tools import format_timestamp
class LocalWhisperError(RuntimeError):
pass
@dataclass(frozen=True)
class LocalWhisperConfig:
enabled: bool
model: str
device: str
compute_type: str
def transcribe_video_to_vtt(video_path: Path, config: LocalWhisperConfig) -> str:
if not config.enabled:
raise LocalWhisperError("本地 Whisper 未启用。")
if not video_path.exists():
raise LocalWhisperError("视频文件不存在,无法生成字幕。")
with tempfile.TemporaryDirectory() as temp_dir:
audio_path = Path(temp_dir) / "whisper-audio.wav"
extract_audio_for_whisper(video_path, audio_path)
segments = transcribe_audio(audio_path, config)
return build_vtt_from_segments(segments)
def extract_audio_for_whisper(video_path: Path, audio_path: Path) -> None:
command = [
"ffmpeg",
"-y",
"-i",
str(video_path),
"-vn",
"-ac",
"1",
"-ar",
"16000",
str(audio_path),
]
try:
subprocess.run(command, check=True, capture_output=True)
except FileNotFoundError as error:
raise LocalWhisperError("未找到 ffmpeg,请先安装 ffmpeg。") from error
except subprocess.CalledProcessError as error:
detail = error.stderr.decode("utf-8", errors="replace")
raise LocalWhisperError(f"ffmpeg 提取音频失败:{detail}") from error
def transcribe_audio(audio_path: Path, config: LocalWhisperConfig) -> list[dict[str, object]]:
faster_whisper = import_optional("faster_whisper")
if faster_whisper is None:
raise LocalWhisperError("未安装 faster-whisper,请先安装后再生成本地字幕。")
model = faster_whisper.WhisperModel(
config.model,
device=config.device,
compute_type=config.compute_type,
)
segments, _info = model.transcribe(
str(audio_path),
language="en",
vad_filter=True,
)
return [
{
"start": float(segment.start),
"end": float(segment.end),
"text": str(segment.text).strip(),
}
for segment in segments
if str(segment.text).strip()
]
def import_optional(module_name: str):
try:
return importlib.import_module(module_name)
except ImportError:
return None
def build_vtt_from_segments(segments: list[dict[str, object]]) -> str:
blocks: list[str] = []
for index, segment in enumerate(segments, 1):
text = str(segment.get("text", "")).strip()
if not text:
continue
start = float(segment.get("start", 0) or 0)
end = float(segment.get("end", start) or start)
blocks.append(f"{index}\n{format_timestamp(start)} --> {format_timestamp(end)}\n{text}")
return "WEBVTT\n\n" + "\n\n".join(blocks).strip() + "\n"
+472 -2
View File
@@ -1,34 +1,64 @@
from pathlib import Path
import secrets
from urllib.parse import urlparse
from uuid import uuid4
from fastapi import FastAPI, File, Form, HTTPException, UploadFile
from fastapi import Depends, FastAPI, File, Form, HTTPException, UploadFile
from pydantic import BaseModel, Field
from fastapi.responses import FileResponse
from fastapi.security import HTTPAuthorizationCredentials, HTTPBasic, HTTPBasicCredentials, HTTPBearer
from fastapi.staticfiles import StaticFiles
from .ai_config import get_ai_status, get_config_value, load_local_whisper_config, load_text_ai_config
from .auth import (
create_auth_token,
generate_activation_code,
hash_password,
normalize_username,
verify_auth_token,
verify_password,
)
from .db import (
DATABASE_PATH,
create_activation_codes,
create_video,
delete_video,
delete_unused_activation_code,
get_user_auth_record,
get_user_by_id,
get_user_learning_state,
initialize_database,
list_activation_codes,
list_users,
list_videos,
mark_user_login,
parse_tags,
register_user_with_activation,
rotate_user_session_token,
save_user_learning_state,
table_names,
get_video,
update_user_active,
update_video,
upsert_video_subtitle,
)
from .deepseek_client import DeepSeekClient, DeepSeekError
from .local_whisper import LocalWhisperError, transcribe_video_to_vtt
from .subtitle_ai import process_subtitles_with_ai
PROJECT_DIR = Path(__file__).resolve().parent.parent
UPLOADS_DIR = PROJECT_DIR / "uploads"
VIDEO_EXTENSIONS = {".mp4", ".webm", ".mov", ".m4v"}
SUBTITLE_EXTENSIONS = {".srt", ".vtt"}
IMAGE_EXTENSIONS = {".jpg", ".jpeg", ".png", ".webp", ".gif"}
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 / "images").mkdir(parents=True, exist_ok=True)
(UPLOADS_DIR / "subtitles").mkdir(parents=True, exist_ok=True)
@@ -113,9 +143,51 @@ def cleanup_upload_urls(upload_urls: list[str]) -> list[str]:
return warnings
def save_generated_subtitle_file(content: str, language_code: str) -> str:
subtitles_dir = UPLOADS_DIR / "subtitles"
subtitles_dir.mkdir(parents=True, exist_ok=True)
filename = f"{uuid4().hex}.ai.{language_code}.vtt"
(subtitles_dir / filename).write_text(content, encoding="utf-8")
return f"/uploads/subtitles/{filename}"
ensure_upload_directories()
app = FastAPI(title="Speaking Lab API")
admin_security = HTTPBasic(auto_error=False)
bearer_security = HTTPBearer(auto_error=False)
class LoginRequest(BaseModel):
username: str
password: str
class RegisterRequest(BaseModel):
activationCode: str
username: str
password: str
class GenerateActivationCodesRequest(BaseModel):
quantity: int = 1
class UpdateUserStatusRequest(BaseModel):
isActive: bool
class VideoProgressPayload(BaseModel):
currentTime: float = 0
activeLineIndex: int = 0
practicedLineIndexes: list[int] = Field(default_factory=list)
difficultLineIndexes: list[int] = Field(default_factory=list)
updatedAt: str = ""
class LearningStateRequest(BaseModel):
favorites: list[str] = Field(default_factory=list)
progress: dict[str, VideoProgressPayload] = Field(default_factory=dict)
@app.on_event("startup")
@@ -149,14 +221,249 @@ def api_get_video(video_id: int) -> dict[str, object]:
return video
def get_token_secret() -> str:
configured = get_config_value("AUTH_SECRET")
if configured:
return configured
admin_password = get_config_value("ADMIN_PASSWORD")
return admin_password or "speaking-lab-development-secret"
def build_user_response(username: str, role: str, user_id: int | None = None) -> dict[str, object]:
return {
"id": user_id,
"username": username,
"role": role,
}
def create_session_payload(username: str, role: str, user_id: int | None = None) -> dict[str, object]:
session_token = secrets.token_urlsafe(32) if user_id else ""
if user_id:
rotate_user_session_token(user_id, session_token)
token = create_auth_token(
{
"username": username,
"role": role,
"userId": user_id,
"sessionToken": session_token,
},
get_token_secret(),
)
return {
"token": token,
"user": build_user_response(username, role, user_id),
}
def validate_bearer_session(token: str) -> dict[str, object] | None:
payload = verify_auth_token(token, get_token_secret())
if not payload:
return None
role = str(payload.get("role") or "")
username = str(payload.get("username") or "")
if role == "admin" and username:
return build_user_response(username, "admin", None)
user_id = int(payload.get("userId") or 0)
session_token = str(payload.get("sessionToken") or "")
user = get_user_by_id(user_id) if user_id else None
if not user or not user["isActive"]:
return None
if user["username"] != username:
return None
current_session_token = str(user.get("sessionToken") or "")
if current_session_token and current_session_token != session_token:
return None
return build_user_response(str(user["username"]), str(user["role"]), int(user["id"]))
def require_session(credentials: HTTPAuthorizationCredentials | None = Depends(bearer_security)) -> dict[str, object]:
if credentials is None:
raise HTTPException(status_code=401, detail="请先登录。")
session = validate_bearer_session(credentials.credentials)
if session is None:
raise HTTPException(status_code=401, detail="登录已失效,请重新登录。")
return session
@app.post("/api/auth/login")
def api_auth_login(request: LoginRequest) -> dict[str, object]:
username = normalize_username(request.username)
password = request.password
if not username or not password:
raise HTTPException(status_code=400, detail="请输入账号和密码。")
admin_username = normalize_username(get_config_value("ADMIN_USERNAME"))
admin_password = get_config_value("ADMIN_PASSWORD")
if admin_username and admin_password and username == admin_username:
if not secrets.compare_digest(password, admin_password):
raise HTTPException(status_code=401, detail="账号或密码错误。")
return create_session_payload(admin_username, "admin")
user = get_user_auth_record(username)
if user is None or not verify_password(password, user["password_hash"]):
raise HTTPException(status_code=401, detail="账号或密码错误。")
if not bool(user["is_active"]):
raise HTTPException(status_code=403, detail="账号已停用,请联系管理员。")
mark_user_login(int(user["id"]))
return create_session_payload(str(user["email"]), str(user["role"]), int(user["id"]))
@app.post("/api/auth/register")
def api_auth_register(request: RegisterRequest) -> dict[str, object]:
username = normalize_username(request.username)
password = request.password
activation_code = request.activationCode.strip().upper()
if not activation_code:
raise HTTPException(status_code=400, detail="请输入激活卡密。")
if not username or not password:
raise HTTPException(status_code=400, detail="请输入账号和密码。")
if len(password) < 6:
raise HTTPException(status_code=400, detail="密码至少需要 6 位。")
try:
user = register_user_with_activation(
username=username,
password_hash=hash_password(password),
activation_code=activation_code,
)
except ValueError as error:
if str(error) == "username_exists":
raise HTTPException(status_code=409, detail="账号已存在。") from error
raise HTTPException(status_code=400, detail="激活卡密无效或已被使用。") from error
mark_user_login(int(user["id"]))
return create_session_payload(str(user["username"]), str(user["role"]), int(user["id"]))
@app.get("/api/auth/session")
def api_auth_session(session: dict[str, object] = Depends(require_session)) -> dict[str, object]:
return {"ok": True, "user": session}
def require_user_id(session: dict[str, object]) -> int:
user_id = session.get("id")
if not isinstance(user_id, int) or user_id <= 0:
raise HTTPException(status_code=403, detail="闇€瑕佹櫘閫氱敤鎴风櫥褰曘€?")
return user_id
@app.get("/api/me/progress")
def api_get_my_progress(session: dict[str, object] = Depends(require_session)) -> dict[str, object]:
return get_user_learning_state(require_user_id(session))
@app.put("/api/me/progress")
def api_save_my_progress(
request: LearningStateRequest,
session: dict[str, object] = Depends(require_session),
) -> dict[str, object]:
return save_user_learning_state(
require_user_id(session),
favorites=request.favorites,
progress={video_id: payload.dict() for video_id, payload in request.progress.items()},
)
def require_admin(
credentials: HTTPBasicCredentials | None = Depends(admin_security),
bearer: HTTPAuthorizationCredentials | None = Depends(bearer_security),
) -> dict[str, str]:
admin_username = get_config_value("ADMIN_USERNAME")
admin_password = get_config_value("ADMIN_PASSWORD")
if not admin_username or not admin_password:
raise HTTPException(
status_code=503,
detail="未配置 ADMIN_USERNAME / ADMIN_PASSWORD,请先在 .env 中填写管理员账号密码。",
)
if credentials is not None:
username_ok = secrets.compare_digest(credentials.username, admin_username)
password_ok = secrets.compare_digest(credentials.password, admin_password)
if username_ok and password_ok:
return {"username": admin_username, "role": "admin"}
if bearer is not None and hasattr(bearer, "credentials"):
session = validate_bearer_session(bearer.credentials)
if session and session["role"] == "admin":
return {"username": str(session["username"]), "role": "admin"}
raise HTTPException(
status_code=401,
detail="需要管理员账号。",
)
@app.get("/api/admin/session")
def api_admin_session(admin: dict[str, str] = Depends(require_admin)) -> dict[str, object]:
return {"ok": True, "username": admin["username"], "role": "admin"}
@app.get("/api/admin/users")
def api_admin_users(admin: dict[str, str] = Depends(require_admin)) -> list[dict[str, object]]:
return list_users()
@app.patch("/api/admin/users/{user_id}")
def api_admin_update_user(
user_id: int,
request: UpdateUserStatusRequest,
admin: dict[str, str] = Depends(require_admin),
) -> dict[str, object]:
user = update_user_active(user_id, request.isActive)
if user is None:
raise HTTPException(status_code=404, detail="用户不存在,或不能修改管理员账号。")
return {"ok": True, "user": user}
@app.get("/api/admin/activation-codes")
def api_admin_activation_codes(admin: dict[str, str] = Depends(require_admin)) -> list[dict[str, object]]:
return list_activation_codes()
@app.post("/api/admin/activation-codes")
def api_admin_create_activation_codes(
request: GenerateActivationCodesRequest,
admin: dict[str, str] = Depends(require_admin),
) -> dict[str, object]:
if request.quantity < 1 or request.quantity > 100:
raise HTTPException(status_code=400, detail="一次只能生成 1 到 100 个卡密。")
codes: list[str] = []
while len(codes) < request.quantity:
code = generate_activation_code()
if code not in codes:
codes.append(code)
created = create_activation_codes(codes, admin["username"])
return {"ok": True, "codes": created}
@app.delete("/api/admin/activation-codes/{code_id}")
def api_admin_delete_activation_code(
code_id: int,
admin: dict[str, str] = Depends(require_admin),
) -> dict[str, object]:
if not delete_unused_activation_code(code_id):
raise HTTPException(status_code=400, detail="已使用的卡密不能删除。")
return {"ok": True, "deletedCodeId": code_id}
@app.post("/api/videos")
async def api_create_video(
admin: dict[str, str] = Depends(require_admin),
title: str = Form(...),
speaker: str = Form(""),
description: str = Form(""),
tags: str = Form(""),
video_url: str = Form(""),
video_file: UploadFile | None = File(None),
cover_file: UploadFile | None = File(None),
subtitle_en: UploadFile | None = File(None),
subtitle_zh: UploadFile | None = File(None),
) -> dict[str, object]:
@@ -175,6 +482,9 @@ async def api_create_video(
if extension_for_upload(video_file) not in VIDEO_EXTENSIONS:
raise HTTPException(status_code=400, detail="视频文件格式不支持")
if cover_file is not None and extension_for_upload(cover_file) not in IMAGE_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"),
@@ -195,6 +505,12 @@ async def api_create_video(
saved_paths.append(UPLOADS_DIR / "videos" / video_filename)
final_video_url = f"/uploads/videos/{video_filename}"
final_cover_url = ""
if cover_file is not None:
cover_filename = await save_binary_upload(cover_file, UPLOADS_DIR / "images")
saved_paths.append(UPLOADS_DIR / "images" / cover_filename)
final_cover_url = f"/uploads/images/{cover_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")
@@ -215,6 +531,7 @@ async def api_create_video(
description=description.strip(),
tags=parse_tags(tags),
video_url=final_video_url,
cover_url=final_cover_url,
subtitles=subtitles,
)
except Exception:
@@ -225,6 +542,7 @@ async def api_create_video(
@app.patch("/api/videos/{video_id}")
async def api_update_video(
video_id: int,
admin: dict[str, str] = Depends(require_admin),
title: str = Form(...),
speaker: str = Form(""),
description: str = Form(""),
@@ -233,6 +551,7 @@ async def api_update_video(
subtitle_en_content: str | None = Form(None),
subtitle_zh_content: str | None = Form(None),
video_file: UploadFile | None = File(None),
cover_file: UploadFile | None = File(None),
subtitle_en: UploadFile | None = File(None),
subtitle_zh: UploadFile | None = File(None),
) -> dict[str, object]:
@@ -254,6 +573,9 @@ async def api_update_video(
if video_file is not None and extension_for_upload(video_file) not in VIDEO_EXTENSIONS:
raise HTTPException(status_code=400, detail="视频文件格式不支持")
if cover_file is not None and extension_for_upload(cover_file) not in IMAGE_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"),
@@ -273,6 +595,12 @@ async def api_update_video(
saved_paths.append(UPLOADS_DIR / "videos" / video_filename)
final_video_url = f"/uploads/videos/{video_filename}"
final_cover_url: str | None = None
if cover_file is not None:
cover_filename = await save_binary_upload(cover_file, UPLOADS_DIR / "images")
saved_paths.append(UPLOADS_DIR / "images" / cover_filename)
final_cover_url = f"/uploads/images/{cover_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")
@@ -313,6 +641,7 @@ async def api_update_video(
description=description.strip(),
tags=parse_tags(tags),
video_url=final_video_url,
cover_url=final_cover_url,
subtitles=subtitles,
)
if updated is None:
@@ -334,7 +663,7 @@ async def api_update_video(
@app.delete("/api/videos/{video_id}")
def api_delete_video(video_id: int) -> dict[str, object]:
def api_delete_video(video_id: int, admin: dict[str, str] = Depends(require_admin)) -> dict[str, object]:
deleted = delete_video(video_id)
if deleted is None:
raise HTTPException(status_code=404, detail="视频不存在")
@@ -348,6 +677,147 @@ def api_delete_video(video_id: int) -> dict[str, object]:
}
@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(admin: dict[str, str] = Depends(require_admin)) -> dict[str, object]:
status = get_ai_status()
if not status["configured"]:
raise HTTPException(status_code=400, detail=status["message"])
try:
text_ai_config = load_text_ai_config()
client = DeepSeekClient(text_ai_config, timeout_seconds=text_ai_config.timeout_seconds)
client.chat_json(
"请只返回 JSON:{\"ok\":true}",
{"task": "ping", "expected": {"ok": True}},
)
except DeepSeekError as error:
raise HTTPException(status_code=400, detail=str(error)) from error
return {"ok": True, "message": "AI API 连接正常。"}
@app.post("/api/videos/{video_id}/ai/subtitles")
def api_process_video_subtitles(video_id: int, admin: dict[str, str] = Depends(require_admin)) -> 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="视频不存在")
subtitles = video.get("subtitles", {})
if not isinstance(subtitles, dict):
raise HTTPException(status_code=400, detail="字幕数据异常。")
english_subtitle = subtitles.get("en", {})
if not isinstance(english_subtitle, dict) or not english_subtitle.get("content"):
raise HTTPException(status_code=400, detail="请先上传英文字幕。")
try:
text_ai_config = load_text_ai_config()
client = DeepSeekClient(text_ai_config, timeout_seconds=text_ai_config.timeout_seconds)
result = process_subtitles_with_ai(
str(english_subtitle["content"]),
client,
batch_size=text_ai_config.translation_batch_size,
)
except (DeepSeekError, ValueError) as error:
raise HTTPException(status_code=400, detail=str(error)) from error
english_file_path = save_generated_subtitle_file(str(result["subtitle_en_content"]), "en")
upsert_video_subtitle(
video_id,
language_code="en",
language_name="English",
format="vtt",
file_path=english_file_path,
content=str(result["subtitle_en_content"]),
)
chinese_file_path = save_generated_subtitle_file(str(result["subtitle_zh_content"]), "zh")
upsert_video_subtitle(
video_id,
language_code="zh",
language_name="中文",
format="vtt",
file_path=chinese_file_path,
content=str(result["subtitle_zh_content"]),
)
return {
"video": get_video(video_id),
"report": result["report"],
}
def save_processed_subtitles(video_id: int, subtitles: dict[str, object], result: dict[str, object]) -> None:
english_subtitle = subtitles.get("en", {})
english_file_path = ""
if isinstance(english_subtitle, dict):
english_file_path = str(english_subtitle.get("filePath") or "")
upsert_video_subtitle(
video_id,
language_code="en",
language_name="English",
format="vtt",
file_path=english_file_path,
content=str(result["subtitle_en_content"]),
)
chinese_subtitle = subtitles.get("zh", {})
chinese_file_path = ""
if isinstance(chinese_subtitle, dict):
chinese_file_path = str(chinese_subtitle.get("filePath") or "")
upsert_video_subtitle(
video_id,
language_code="zh",
language_name="中文",
format="vtt",
file_path=chinese_file_path,
content=str(result["subtitle_zh_content"]),
)
@app.post("/api/videos/{video_id}/local-whisper/subtitles")
def api_generate_local_whisper_subtitles(video_id: int, admin: dict[str, str] = Depends(require_admin)) -> dict[str, object]:
video = get_video(video_id)
if video is None:
raise HTTPException(status_code=404, detail="视频不存在")
video_path = upload_url_to_path(str(video.get("videoUrl") or ""))
if not video_path:
raise HTTPException(status_code=400, detail="本地 Whisper 只能处理本地上传的视频文件。")
try:
whisper_config = load_local_whisper_config()
english_vtt = transcribe_video_to_vtt(video_path, whisper_config)
except LocalWhisperError 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="",
content=english_vtt,
)
return {
"video": get_video(video_id),
"report": {
"local_whisper_generated": True,
"english_count": english_vtt.count("-->"),
},
}
@app.get("/")
def read_index() -> FileResponse:
return FileResponse(PROJECT_DIR / "index.html")
+121
View File
@@ -0,0 +1,121 @@
from __future__ import annotations
from .subtitle_tools import SubtitleCue, build_vtt, clean_english_subtitle
TRANSLATION_SYSTEM_PROMPT = """
你是英语学习产品的字幕处理助手。输入是按顺序排列的英文字幕。
请只返回 JSON,格式为 {"translations":[{"index":1,"zh":"中文翻译"}]}。
要求:
1. 只翻译英文文本,不要改写原文含义。
2. 不要修改时间轴,不要生成任何 start/end/time 字段。
3. 不要增删字幕条数,每个输入 index 必须返回且只返回一条中文。
4. translations 可以乱序,但 index 必须和输入完全一致。
5. 中文自然,适合英语学习;不要解释。
""".strip()
def process_subtitles_with_ai(
english_content: str,
client,
batch_size: int = 0,
) -> dict[str, object]:
cleaned = clean_english_subtitle(english_content)
if not cleaned.cues:
raise ValueError("英文字幕为空,无法处理。")
english_cues = cleaned.cues
translations = translate_cues(english_cues, client, batch_size)
zh_cues = []
for index, cue in enumerate(english_cues, 1):
translation = translations[index]
zh_text = str(translation.get("zh", "")).strip()
if not zh_text:
raise ValueError(f"AI 返回了空翻译:index {index}")
zh_cues.append({"start": cue.start, "end": cue.end, "text": zh_text})
translation_batches = count_batches(len(english_cues), batch_size)
return {
"subtitle_en_content": build_vtt(english_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),
"translation_batches": translation_batches,
},
}
def translate_cues(
cues: list[SubtitleCue],
client,
batch_size: int,
) -> dict[int, dict[str, object]]:
translations: dict[int, dict[str, object]] = {}
indexed_cues = list(enumerate(cues, 1))
effective_batch_size = int(batch_size or 0)
batches = (
[indexed_cues]
if effective_batch_size <= 0 or effective_batch_size >= len(indexed_cues)
else [indexed_cues[start:start + effective_batch_size] for start in range(0, len(indexed_cues), effective_batch_size)]
)
for batch in batches:
expected_indexes = {index for index, _cue in batch}
collect_translations(batch, expected_indexes, translations, client)
missing = sorted(expected_indexes - translations.keys())
if missing:
missing_batch = [(index, cue) for index, cue in batch if index in missing]
collect_translations(missing_batch, set(missing), translations, client)
missing = sorted(expected_indexes - translations.keys())
if missing:
for index, cue in [(index, cue) for index, cue in batch if index in missing]:
collect_translations([(index, cue)], {index}, translations, client)
missing = sorted(expected_indexes - translations.keys())
if missing:
raise ValueError(f"AI 返回的翻译条数和英文字幕条数不一致,缺少 index:{missing[:10]}")
return translations
def collect_translations(
batch: list[tuple[int, SubtitleCue]],
expected_indexes: set[int],
translations: dict[int, dict[str, object]],
client,
) -> None:
if not batch:
return
payload = {
"cues": [
{"index": index, "text": cue.text}
for index, cue in batch
]
}
response = client.chat_json(TRANSLATION_SYSTEM_PROMPT, payload)
batch_translations = response.get("translations")
if not isinstance(batch_translations, list):
raise ValueError("AI 返回结果缺少 translations。")
for item in batch_translations:
if not isinstance(item, dict):
continue
try:
item_index = int(item.get("index"))
except (TypeError, ValueError):
continue
if item_index in expected_indexes:
translations[item_index] = item
def count_batches(cue_count: int, batch_size: int) -> int:
effective_batch_size = int(batch_size or 0)
if cue_count <= 0:
return 0
if effective_batch_size <= 0 or effective_batch_size >= cue_count:
return 1
return (cue_count + effective_batch_size - 1) // effective_batch_size
+127
View File
@@ -0,0 +1,127 @@
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*"
r"(?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("&nbsp;", "").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"
def parse_timestamp(value: str) -> float:
clean = str(value).replace(",", ".").split()[0]
parts = clean.split(":")
try:
numbers = [float(part) for part in parts]
except ValueError:
return 0.0
if len(numbers) == 3:
return numbers[0] * 3600 + numbers[1] * 60 + numbers[2]
if len(numbers) == 2:
return numbers[0] * 60 + numbers[1]
return numbers[0] if numbers else 0.0
def format_timestamp(seconds: float) -> str:
total_milliseconds = max(0, round((seconds or 0) * 1000))
hours = total_milliseconds // 3_600_000
minutes = (total_milliseconds % 3_600_000) // 60_000
whole_seconds = (total_milliseconds % 60_000) // 1000
milliseconds = total_milliseconds % 1000
return f"{hours:02d}:{minutes:02d}:{whole_seconds:02d}.{milliseconds:03d}"
@@ -0,0 +1,75 @@
# Speaking Lab Home Premium Cards 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:** Restyle the home page with a spacious premium card-based learning library look.
**Architecture:** Keep the existing HTML and JavaScript. Implement the design through `styles.css` by updating page background, home grid layout, dashboard surfaces, metric button states, material card presentation, stat bar styling, and chip styling.
**Tech Stack:** CSS, existing vanilla HTML/JS, existing local FastAPI server for browser verification.
---
## Task 1: Restyle Home Layout And Dashboard
**Files:**
- Modify: `F:\ooo\speaking-practice-local\styles.css`
- [ ] **Step 1: Update page background and home shell**
Set `.home-page` to `#f8fafc`, and `.home-shell` to a 280px sidebar grid with larger gap and padding.
- [ ] **Step 2: Update dashboard surface**
Make `.home-dashboard-title` and `.home-metric` feel premium: white background, 16px radius, soft gray shadow, smooth transition.
- [ ] **Step 3: Add metric hover and active states**
Hover should lift slightly and deepen the border/shadow. Active should use a subtle blue-tinted or teal-tinted background, not harsh black.
## Task 2: Restyle Material Grid And Cards
**Files:**
- Modify: `F:\ooo\speaking-practice-local\styles.css`
- [ ] **Step 1: Update card grid**
Use `repeat(auto-fill, minmax(320px, 1fr))` and `gap: 24px`.
- [ ] **Step 2: Update material cards**
Use white cards, 16px radius, overflow hidden, soft shadow, and `translateY(-4px)` hover.
- [ ] **Step 3: Update cover and card body**
Set cover height to 180px. Increase card body padding. Improve title weight/color/line-height.
- [ ] **Step 4: Update stats**
Make `.home-card-stats` a compact bottom bar with a dashed top border and horizontal flex-like grid.
## Task 3: Restyle Chips And Verify
**Files:**
- Modify: `F:\ooo\speaking-practice-local\styles.css`
- [ ] **Step 1: Update `.chip`**
Make chips capsule-shaped with soft gray default state and strong active state.
- [ ] **Step 2: Run 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
```
- [ ] **Step 3: Browser verify**
Open `http://127.0.0.1:8000/` and confirm layout, cards, hover behavior, chips, and no text overlap.
@@ -0,0 +1,64 @@
# Speaking Lab Study Toolbar Polish 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:** Center the main sentence controls, enlarge the loop toggle, remove continue/watch-later actions from the study toolbar, and polish the study page visual consistency.
**Architecture:** Update `study.html` toolbar zones, remove now-unused visible bindings from `app.js`, and restyle the toolbar in `styles.css`. Keep existing recording, favorite, sentence navigation, and loop behavior.
**Tech Stack:** Vanilla HTML, CSS, JavaScript.
---
## Task 1: Update Toolbar Markup
**Files:**
- Modify: `F:\ooo\speaking-practice-local\study.html`
- [ ] Replace toolbar content with three zones:
- `.recording-controls`: `录音 / 停止 / 回放`
- `.sentence-controls`: `上一句 / 重播 / 下一句`
- `.study-side-actions`: enlarged loop toggle and `收藏`
## Task 2: Remove Deleted Button Bindings
**Files:**
- Modify: `F:\ooo\speaking-practice-local\app.js`
- [ ] Remove `continueBtn` and `watchLaterBtn` DOM references.
- [ ] Remove event listeners for `continueLearning` and `watchLater`.
- [ ] Remove visible text updates for `watchLaterBtn`.
- [ ] Guard or remove `renderContinueAction()` calls so no missing element is referenced.
## Task 3: Style Unified Toolbar
**Files:**
- Modify: `F:\ooo\speaking-practice-local\styles.css`
- [ ] Make `.tool-row` a three-column grid: left, center, right.
- [ ] Style `.sentence-controls` as the centered primary control group.
- [ ] Style `.recording-controls` as secondary.
- [ ] Enlarge `.toggle` inside `.study-side-actions`.
- [ ] Keep narrow viewport wrapping without horizontal overflow.
## Task 4: Verify
Run:
```powershell
node --check app.js
node --check home.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 check:
- Open `http://127.0.0.1:8000/study.html`.
- Confirm `继续学习` and `稍后再看` are gone.
- Confirm `上一句 / 重播 / 下一句` are centered.
- Confirm loop toggle is larger.
- Confirm favorite remains.
- Confirm no horizontal overflow.
@@ -0,0 +1,95 @@
# Speaking Lab Activation Auth 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 activation-code registration, server-backed login, admin-only account/code management, and gated access to the learning pages.
**Architecture:** Reuse FastAPI and SQLite. Add focused auth helpers in `backend/auth.py`, extend `backend/db.py` for users and activation codes, expose auth/admin APIs in `backend/main.py`, then replace local fake login in frontend with a shared `auth.js` module and a new `login.html/login.js`.
**Tech Stack:** FastAPI, SQLite, plain HTML/CSS/JavaScript, Node syntax checks, Python compile checks.
---
### Task 1: Backend Auth Storage And Helpers
**Files:**
- Create: `backend/auth.py`
- Modify: `backend/db.py`
- Test: `tests/auth_helpers_test.py`
- [ ] Add SQLite columns `users.is_active` and `users.last_login_at` in `initialize_database`.
- [ ] Add `activation_codes` table and indexes in `initialize_database`.
- [ ] Add user CRUD helpers, activation code helpers, and password hashing helpers.
- [ ] Add signed token helpers in `backend/auth.py`.
- [ ] Add focused Python tests for password hashing, token roundtrip, user creation, activation code use, and disabled user behavior.
### Task 2: Backend Auth And Admin APIs
**Files:**
- Modify: `backend/main.py`
- Test: `tests/auth_routes_test.py`
- [ ] Add Pydantic request models for login, register, code generation, and user status changes.
- [ ] Add `POST /api/auth/login`, `POST /api/auth/register`, and `GET /api/auth/session`.
- [ ] Extend admin dependency to accept either current HTTP Basic admin credentials or `Authorization: Bearer <token>` with admin role.
- [ ] Add `GET /api/admin/users`, `PATCH /api/admin/users/{user_id}`, `GET /api/admin/activation-codes`, `POST /api/admin/activation-codes`, and `DELETE /api/admin/activation-codes/{code_id}`.
- [ ] Add route tests for normal login, admin login, registration with activation code, reused code rejection, normal-user admin rejection, and admin code generation.
### Task 3: Shared Frontend Auth And Login Page
**Files:**
- Create: `auth.js`
- Create: `login.html`
- Create: `login.js`
- Modify: `styles.css`
- Test: `tests/auth-ui-helpers.test.mjs`
- [ ] Add browser auth helpers for token storage, session check, logout, and authenticated fetch.
- [ ] Build the centered login/register page inspired by the reference HTML.
- [ ] Add login/register UI logic and frontend password confirmation checks.
- [ ] Add CSS for the auth page card, form fields, mode switching, and messages.
- [ ] Add Node tests for pure auth helper functions where practical.
### Task 4: Gate Home And Study Pages
**Files:**
- Modify: `index.html`
- Modify: `home.js`
- Modify: `study.html`
- Modify: `app.js`
- Modify: `styles.css`
- [ ] Remove inline email login/register forms.
- [ ] Load `auth.js` before page scripts.
- [ ] Require a valid session before rendering home/study content.
- [ ] Show username and logout in the top bar.
- [ ] Show backend/admin entry only for admin users.
- [ ] Remove duplicate study-entry control from the study-side/right-side area.
- [ ] Keep existing browser-local learning progress data intact.
### Task 5: Admin Account And Activation Code UI
**Files:**
- Modify: `admin.html`
- Modify: `admin.js`
- Modify: `styles.css`
- Test: existing admin Node tests plus syntax checks
- [ ] Switch admin session to the shared bearer-token auth flow while keeping existing Basic helper functions exportable for tests if needed.
- [ ] Add account management panel with user status rows and enable/disable buttons.
- [ ] Add activation code panel with quantity input, generated code list, copy buttons, used status, and unused delete buttons.
- [ ] Ensure material upload/edit/delete continues to use authenticated admin requests.
### Task 6: Verification, Commit, Push
**Files:**
- All changed files
- [ ] Run Python compile checks.
- [ ] Run backend route/helper tests.
- [ ] Run Node syntax checks.
- [ ] Run existing Node helper tests.
- [ ] Start local server and smoke-test login, admin code generation, registration, normal-user blocking, and admin material page access.
- [ ] Commit implementation.
- [ ] Push to `origin feature/deepseek-subtitle-ai`.
@@ -0,0 +1,426 @@
# Speaking Lab Button Chip Style Refresh 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:** Refresh Speaking Lab buttons and chips into a TEco-inspired flat, refined style using CSS only.
**Architecture:** Keep all HTML, class names, IDs, and JavaScript behavior unchanged. Update `styles.css` by introducing shared button tokens in `:root`, then overriding existing button, chip, secondary, danger, and primary action selectors with consistent states. Verify through syntax checks and browser inspection on home, study, admin, and login pages.
**Tech Stack:** Plain HTML/CSS/JavaScript, existing FastAPI static server, in-app browser verification.
---
### Task 1: Button Token Foundation
**Files:**
- Modify: `styles.css`
- [ ] **Step 1: Add shared button tokens to `:root`**
Insert these variables inside the existing `:root` block after `--danger`:
```css
--control-surface: #f1eee7;
--control-surface-hover: #e8e1d6;
--control-surface-active: #ddd4c7;
--control-border: rgba(67, 56, 45, 0.10);
--control-ink: #33413c;
--control-muted: #746b60;
--primary-solid: #2f4b45;
--primary-solid-hover: #263f3a;
--primary-solid-active: #203631;
--primary-soft-shadow: 0 10px 22px rgba(47, 75, 69, 0.16);
--danger-soft: #fdecec;
--danger-soft-hover: #f9dddd;
--danger-ink: #9f2f35;
--focus-ring: 0 0 0 3px rgba(47, 125, 99, 0.18);
```
- [ ] **Step 2: Run a quick CSS selector scan**
Run:
```powershell
rg -n "--control-surface|--primary-solid|--danger-soft|--focus-ring" styles.css
```
Expected: each token appears in `:root`.
- [ ] **Step 3: Commit token foundation**
Run:
```powershell
git add styles.css
git commit -m "style: add button style tokens"
```
### Task 2: Chips and Secondary Actions
**Files:**
- Modify: `styles.css`
- [ ] **Step 1: Replace the existing `.chip` block**
Replace the current `.chip`, `.chip:hover`, and `.chip.active` rules with:
```css
.chip {
min-height: 32px;
border: 1px solid transparent;
border-radius: 999px;
padding: 0 15px;
color: var(--control-ink);
background: var(--control-surface);
box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.54);
font-size: 12px;
font-weight: 750;
white-space: nowrap;
transition: color 160ms ease, background 160ms ease, border-color 160ms ease, box-shadow 160ms ease, transform 160ms ease;
}
.chip:hover {
border-color: var(--control-border);
background: var(--control-surface-hover);
box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.58), 0 8px 18px rgba(47, 64, 57, 0.09);
transform: translateY(-1px);
}
.chip.active {
color: #fffdf8;
border-color: var(--primary-solid);
background: var(--primary-solid);
box-shadow: var(--primary-soft-shadow);
}
```
- [ ] **Step 2: Replace `.primary-link, .secondary-action` and `.secondary-action:hover` area**
Update the existing `.primary-link, .secondary-action`, `.primary-link`, `.primary-link:hover`, and `.secondary-action:hover` rules near the admin styles so secondary actions use:
```css
.secondary-action {
min-height: 34px;
display: inline-flex;
align-items: center;
justify-content: center;
border: 1px solid transparent;
border-radius: 10px;
padding: 0 12px;
color: var(--control-muted);
background: rgba(241, 238, 231, 0.88);
box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.52);
font-size: 13px;
font-weight: 750;
text-decoration: none;
white-space: nowrap;
transition: color 160ms ease, background 160ms ease, border-color 160ms ease, box-shadow 160ms ease, transform 160ms ease;
}
.secondary-action:hover {
color: var(--control-ink);
border-color: var(--control-border);
background: var(--control-surface-hover);
box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.58), 0 8px 18px rgba(47, 64, 57, 0.08);
transform: translateY(-1px);
}
.secondary-action:active {
background: var(--control-surface-active);
box-shadow: inset 0 1px 2px rgba(47, 64, 57, 0.12);
transform: translateY(0);
}
```
Keep any more specific layout rules, such as `.admin-video-actions .secondary-action` widths, after this block.
- [ ] **Step 3: Add focus-visible support**
Near the button state rules, add:
```css
.chip:focus-visible,
.secondary-action:focus-visible {
outline: none;
box-shadow: var(--focus-ring);
}
```
- [ ] **Step 4: Verify selectors**
Run:
```powershell
rg -n "\\.chip|\\.secondary-action|focus-visible" styles.css
```
Expected: the new chip and secondary-action rules are present once as the main definitions, with responsive/layout overrides preserved.
- [ ] **Step 5: Commit chips and secondary actions**
Run:
```powershell
git add styles.css
git commit -m "style: refresh chips and secondary buttons"
```
### Task 3: Danger and Primary Actions
**Files:**
- Modify: `styles.css`
- [ ] **Step 1: Replace `.danger-action` rules**
Replace `.danger-action` and `.danger-action:hover` with:
```css
.danger-action {
min-height: 34px;
border: 1px solid rgba(159, 47, 53, 0.10);
border-radius: 10px;
padding: 0 12px;
color: var(--danger-ink);
background: var(--danger-soft);
box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.55);
font-size: 13px;
font-weight: 800;
transition: color 160ms ease, background 160ms ease, border-color 160ms ease, box-shadow 160ms ease, transform 160ms ease;
}
.danger-action:hover {
border-color: rgba(159, 47, 53, 0.16);
color: #84262c;
background: var(--danger-soft-hover);
box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.58), 0 8px 18px rgba(159, 47, 53, 0.08);
transform: translateY(-1px);
}
.danger-action:active {
background: #f4cccc;
box-shadow: inset 0 1px 2px rgba(159, 47, 53, 0.14);
transform: translateY(0);
}
.danger-action:focus-visible {
outline: none;
box-shadow: 0 0 0 3px rgba(159, 47, 53, 0.14);
}
```
- [ ] **Step 2: Consolidate primary action selectors**
Add this block after the global button disabled rules and before inputs:
```css
.primary-link,
#adminSubmitBtn,
.auth-form button[type="submit"],
.login-form button,
.admin-form button[type="submit"],
.activation-code-form button[type="submit"],
.practice-answer-row button {
border-color: var(--primary-solid);
color: #fffdf8;
background: var(--primary-solid);
box-shadow: var(--primary-soft-shadow);
font-weight: 800;
transition: color 160ms ease, background 160ms ease, border-color 160ms ease, box-shadow 160ms ease, transform 160ms ease;
}
.primary-link:hover,
#adminSubmitBtn:hover,
.auth-form button[type="submit"]:hover,
.login-form button:hover,
.admin-form button[type="submit"]:hover,
.activation-code-form button[type="submit"]:hover,
.practice-answer-row button:hover {
border-color: var(--primary-solid-hover);
color: #fffdf8;
background: var(--primary-solid-hover);
box-shadow: 0 12px 26px rgba(47, 75, 69, 0.20);
transform: translateY(-1px);
}
.primary-link:active,
#adminSubmitBtn:active,
.auth-form button[type="submit"]:active,
.login-form button:active,
.admin-form button[type="submit"]:active,
.activation-code-form button[type="submit"]:active,
.practice-answer-row button:active {
border-color: var(--primary-solid-active);
background: var(--primary-solid-active);
box-shadow: 0 6px 14px rgba(47, 75, 69, 0.14);
transform: translateY(0);
}
.primary-link:focus-visible,
#adminSubmitBtn:focus-visible,
.auth-form button[type="submit"]:focus-visible,
.login-form button:focus-visible,
.admin-form button[type="submit"]:focus-visible,
.activation-code-form button[type="submit"]:focus-visible,
.practice-answer-row button:focus-visible {
outline: none;
box-shadow: var(--primary-soft-shadow), var(--focus-ring);
}
```
- [ ] **Step 3: Keep disabled state readable**
After the primary block, add:
```css
.primary-link:disabled,
#adminSubmitBtn:disabled,
.auth-form button[type="submit"]:disabled,
.login-form button:disabled,
.admin-form button[type="submit"]:disabled,
.activation-code-form button[type="submit"]:disabled,
.practice-answer-row button:disabled {
border-color: #d8d2c8;
color: #9b9388;
background: #e8e2d8;
box-shadow: none;
transform: none;
}
```
- [ ] **Step 4: Remove or neutralize conflicting older primary blocks**
Ensure these older rules do not override the new primary system with old teal/navy colors:
```css
.login-form button,
.admin-form button[type="submit"] {
color: #fff;
background: var(--brand);
border-color: var(--brand);
}
```
and:
```css
.practice-answer-row button {
color: #ffffff;
border-color: var(--brand);
background: var(--brand);
font-weight: 800;
}
```
Either remove those declarations or update them to match the new variables.
- [ ] **Step 5: Verify selector conflicts**
Run:
```powershell
rg -n "var\\(--brand\\)|var\\(--accent\\)|#111827|#0f172a|\\.danger-action|\\.primary-link|#adminSubmitBtn|practice-answer-row button" styles.css
```
Expected: old brand/accent rules may remain for non-button surfaces, but primary/danger action definitions should use the new variables.
- [ ] **Step 6: Commit danger and primary actions**
Run:
```powershell
git add styles.css
git commit -m "style: refresh primary and danger buttons"
```
### Task 4: Browser Verification and Final Polish
**Files:**
- Modify if needed: `styles.css`
- [ ] **Step 1: Run static checks**
Run:
```powershell
node --check app.js
node --check home.js
node --check admin.js
node --check login.js
```
Expected: all commands exit with code 0.
- [ ] **Step 2: Start the local server**
Run:
```powershell
python -m uvicorn backend.main:app --host 127.0.0.1 --port 8000
```
Expected: server starts and serves the app at `http://127.0.0.1:8000`.
- [ ] **Step 3: Inspect desktop views**
Open these pages in the browser:
```text
http://127.0.0.1:8000/index.html
http://127.0.0.1:8000/study.html
http://127.0.0.1:8000/admin.html
http://127.0.0.1:8000/login.html
```
Expected:
- chips are compact capsules;
- secondary buttons are quiet and refined;
- danger buttons are soft rose, not bright red;
- primary buttons use deep green solid styling;
- no button text overflows or overlaps.
- [ ] **Step 4: Inspect mobile-width views**
Use a viewport around `390x844` and revisit home, study, admin, and login.
Expected: wrapping still works, buttons remain tappable, and no text escapes the control bounds.
- [ ] **Step 5: Apply final CSS polish if needed**
If browser inspection reveals a problem, make only targeted CSS edits. Example fixes:
```css
.admin-video-actions .secondary-action,
.danger-action {
min-width: 70px;
}
.chip {
line-height: 1;
}
```
- [ ] **Step 6: Run final checks**
Run:
```powershell
node --check app.js
node --check home.js
node --check admin.js
node --check login.js
git diff --check
```
Expected: all checks pass, and `git diff --check` reports no whitespace errors.
- [ ] **Step 7: Commit final polish**
Run:
```powershell
git add styles.css
git commit -m "style: polish button responsive states"
```
If no final polish was needed after Task 3, skip this commit.
@@ -0,0 +1,911 @@
# Speaking Lab Study Practice Modes 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 five study modes to the learning page, with `听写` and `中译英` input in the left current-sentence practice area and no `挖空` mode.
**Architecture:** Extend the existing `subtitleMode` / `.tab[data-mode]` pattern instead of adding a second mode system. Add pure answer-checking helpers to `app.js` for Node tests, add a left-side practice panel in `study.html`, and style it in `styles.css` as part of the current video control surface.
**Tech Stack:** Vanilla HTML, CSS, JavaScript, Node `assert` tests.
---
## File Structure
- `F:\ooo\speaking-practice-local\study.html`: move the mode bar into the left learning surface, add the current sentence practice panel, and keep the right transcript as a browsing/status panel.
- `F:\ooo\speaking-practice-local\app.js`: add practice helper functions, export them for tests, bind practice panel DOM events, render mode-specific prompts, and clear practice feedback on sentence or mode changes.
- `F:\ooo\speaking-practice-local\styles.css`: style the left mode bar, practice panel, answer row, feedback states, and responsive wrapping.
- `F:\ooo\speaking-practice-local\tests\practice-helpers.test.mjs`: cover answer normalization, answer comparison, and practice view-state derivation.
## Task 1: Add Failing Practice Helper Tests
**Files:**
- Create: `F:\ooo\speaking-practice-local\tests\practice-helpers.test.mjs`
- [ ] **Step 1: Create the test file**
Create `tests\practice-helpers.test.mjs` with:
```javascript
import assert from "node:assert/strict";
import {
normalizePracticeAnswer,
comparePracticeAnswer,
getPracticeViewState,
getSubtitleModeConfig,
} from "../app.js";
assert.equal(normalizePracticeAnswer(" Hello, WORLD! "), "hello world");
assert.equal(normalizePracticeAnswer("I’m ready."), "i'm ready");
assert.equal(normalizePracticeAnswer("Are you ok? Yes!"), "are you ok yes");
assert.equal(normalizePracticeAnswer("Listen--then write"), "listen then write");
assert.deepEqual(comparePracticeAnswer("", "Good technology should help."), {
status: "empty",
isCorrect: false,
reference: "Good technology should help.",
message: "请输入答案后再核对。",
});
assert.deepEqual(comparePracticeAnswer("good technology should help", "Good technology should help."), {
status: "correct",
isCorrect: true,
reference: "Good technology should help.",
message: "完全匹配。",
});
assert.deepEqual(comparePracticeAnswer("Good technology should help!", "Good technology should help."), {
status: "correct",
isCorrect: true,
reference: "Good technology should help.",
message: "完全匹配。",
});
assert.deepEqual(comparePracticeAnswer("Good tools help.", "Good technology should help."), {
status: "incorrect",
isCorrect: false,
reference: "Good technology should help.",
message: "还不完全一致,参考答案如下。",
});
assert.deepEqual(comparePracticeAnswer("anything", ""), {
status: "missing-reference",
isCorrect: false,
reference: "",
message: "当前句没有可核对的英文参考。",
});
const cuePair = {
english: {
start: 0,
end: 3.5,
text: "Good technology should make people feel more capable.",
},
chinese: {
start: 0,
end: 3.5,
text: "好的技术应该让人感觉自己更有能力。",
},
};
assert.deepEqual(getPracticeViewState("bilingual", cuePair), {
mode: "bilingual",
label: "双语",
promptText: "Good technology should make people feel more capable.",
referenceText: "好的技术应该让人感觉自己更有能力。",
expectedText: "Good technology should make people feel more capable.",
inputVisible: false,
canCheck: false,
feedbackHint: "",
});
assert.deepEqual(getPracticeViewState("dictation", cuePair), {
mode: "dictation",
label: "听写",
promptText: "听音频,写出当前英文句子。",
referenceText: "",
expectedText: "Good technology should make people feel more capable.",
inputVisible: true,
canCheck: true,
feedbackHint: "",
});
assert.deepEqual(getPracticeViewState("translation", cuePair), {
mode: "translation",
label: "中译英",
promptText: "好的技术应该让人感觉自己更有能力。",
referenceText: "根据中文写出英文句子。",
expectedText: "Good technology should make people feel more capable.",
inputVisible: true,
canCheck: true,
feedbackHint: "",
});
assert.deepEqual(getPracticeViewState("translation", { english: cuePair.english, chinese: null }), {
mode: "translation",
label: "中译英",
promptText: "当前句没有中文字幕。",
referenceText: "根据中文写出英文句子。",
expectedText: "Good technology should make people feel more capable.",
inputVisible: true,
canCheck: true,
feedbackHint: "",
});
assert.deepEqual(getPracticeViewState("dictation", { english: null, chinese: cuePair.chinese }), {
mode: "dictation",
label: "听写",
promptText: "听音频,写出当前英文句子。",
referenceText: "",
expectedText: "",
inputVisible: true,
canCheck: false,
feedbackHint: "当前句没有可核对的英文参考。",
});
assert.deepEqual(getSubtitleModeConfig("dictation", { en: {}, zh: {} }), {
primaryCode: "en",
secondaryCode: "",
showSecondary: false,
message: "",
});
assert.deepEqual(getSubtitleModeConfig("translation", { en: {}, zh: {} }), {
primaryCode: "zh",
secondaryCode: "",
showSecondary: false,
message: "",
});
```
- [ ] **Step 2: Run the new test and verify it fails**
Run:
```powershell
node tests\practice-helpers.test.mjs
```
Expected: FAIL with an import error for `normalizePracticeAnswer`, `comparePracticeAnswer`, or `getPracticeViewState`.
- [ ] **Step 3: Commit the failing test**
```powershell
git add tests\practice-helpers.test.mjs
git commit -m "test: add practice mode helper coverage"
```
## Task 2: Implement Practice Helper Functions
**Files:**
- Modify: `F:\ooo\speaking-practice-local\app.js`
- Test: `F:\ooo\speaking-practice-local\tests\practice-helpers.test.mjs`
- [ ] **Step 1: Add mode labels and helper functions near `getSubtitleModeConfig`**
Add this code before `function getActiveSubtitleModeConfig()`:
```javascript
const practiceModeLabels = {
bilingual: "双语",
english: "英文",
chinese: "中文",
dictation: "听写",
translation: "中译英",
};
function normalizePracticeAnswer(text) {
return String(text || "")
.toLowerCase()
.replace(/[’‘]/g, "'")
.replace(/[“”]/g, "\"")
.replace(/[-–—]+/g, " ")
.replace(/[.,!?;:"()[\]{},。!?;:“”‘’、]/g, " ")
.replace(/\s+/g, " ")
.trim();
}
function comparePracticeAnswer(input, expected) {
const reference = String(expected || "").trim();
const normalizedInput = normalizePracticeAnswer(input);
const normalizedExpected = normalizePracticeAnswer(expected);
if (!normalizedInput) {
return {
status: "empty",
isCorrect: false,
reference,
message: "请输入答案后再核对。",
};
}
if (!normalizedExpected) {
return {
status: "missing-reference",
isCorrect: false,
reference,
message: "当前句没有可核对的英文参考。",
};
}
if (normalizedInput === normalizedExpected) {
return {
status: "correct",
isCorrect: true,
reference,
message: "完全匹配。",
};
}
return {
status: "incorrect",
isCorrect: false,
reference,
message: "还不完全一致,参考答案如下。",
};
}
function getPracticeViewState(mode, cuePair = {}) {
const englishText = cuePair.english?.text?.trim() || "";
const chineseText = cuePair.chinese?.text?.trim() || "";
const normalizedMode = practiceModeLabels[mode] ? mode : "bilingual";
if (normalizedMode === "dictation") {
return {
mode: normalizedMode,
label: practiceModeLabels[normalizedMode],
promptText: "听音频,写出当前英文句子。",
referenceText: "",
expectedText: englishText,
inputVisible: true,
canCheck: Boolean(englishText),
feedbackHint: englishText ? "" : "当前句没有可核对的英文参考。",
};
}
if (normalizedMode === "translation") {
return {
mode: normalizedMode,
label: practiceModeLabels[normalizedMode],
promptText: chineseText || "当前句没有中文字幕。",
referenceText: "根据中文写出英文句子。",
expectedText: englishText,
inputVisible: true,
canCheck: Boolean(englishText),
feedbackHint: englishText ? "" : "当前句没有可核对的英文参考。",
};
}
if (normalizedMode === "english") {
return {
mode: normalizedMode,
label: practiceModeLabels[normalizedMode],
promptText: englishText || "当前句没有英文字幕。",
referenceText: "",
expectedText: englishText,
inputVisible: false,
canCheck: false,
feedbackHint: "",
};
}
if (normalizedMode === "chinese") {
return {
mode: normalizedMode,
label: practiceModeLabels[normalizedMode],
promptText: chineseText || "当前句没有中文字幕。",
referenceText: "",
expectedText: englishText,
inputVisible: false,
canCheck: false,
feedbackHint: "",
};
}
return {
mode: "bilingual",
label: practiceModeLabels.bilingual,
promptText: englishText || "当前句没有英文字幕。",
referenceText: chineseText,
expectedText: englishText,
inputVisible: false,
canCheck: false,
feedbackHint: "",
};
}
```
- [ ] **Step 2: Extend `getSubtitleModeConfig` for input modes**
In `getSubtitleModeConfig(mode, subtitles = {})`, add this branch after the `chinese` branch and before the final English fallback:
```javascript
if (mode === "translation") {
return {
primaryCode: hasChinese ? "zh" : fallbackCode,
secondaryCode: "",
showSecondary: false,
message: hasChinese ? "" : "当前素材没有中文字幕。",
};
}
if (mode === "dictation") {
return {
primaryCode: hasEnglish ? "en" : fallbackCode,
secondaryCode: "",
showSecondary: false,
message: "",
};
}
```
- [ ] **Step 3: Export the new helpers**
At the bottom `module.exports` block, add:
```javascript
normalizePracticeAnswer,
comparePracticeAnswer,
getPracticeViewState,
```
The export block should include the existing exports plus these three names.
- [ ] **Step 4: Run the helper tests**
Run:
```powershell
node tests\practice-helpers.test.mjs
```
Expected: PASS with no output.
- [ ] **Step 5: Run existing progress tests**
Run:
```powershell
node tests\progress-helpers.test.mjs
```
Expected: PASS with no output.
- [ ] **Step 6: Commit helper implementation**
```powershell
git add app.js tests\practice-helpers.test.mjs
git commit -m "feat: add practice answer helpers"
```
## Task 3: Add Left Practice Panel Markup and DOM Wiring
**Files:**
- Modify: `F:\ooo\speaking-practice-local\study.html`
- Modify: `F:\ooo\speaking-practice-local\app.js`
- [ ] **Step 1: Move mode buttons into the left video panel**
In `study.html`, insert this block after the closing `</div>` for `.tool-row` and before `<div class="recording-line">`:
```html
<section class="practice-panel" aria-label="当前句练习">
<div class="practice-mode-bar tabs" aria-label="学习模式">
<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>
<button class="tab" type="button" data-mode="dictation">听写</button>
<button class="tab" type="button" data-mode="translation">中译英</button>
</div>
<div class="practice-body">
<div class="practice-prompt">
<span id="practiceModeLabel" class="practice-label">双语</span>
<p id="practicePromptText" class="practice-primary"></p>
<p id="practiceReferenceText" class="practice-secondary"></p>
</div>
<div id="practiceAnswerRow" class="practice-answer-row" hidden>
<textarea id="practiceAnswerInput" rows="2" placeholder="输入你的英文答案"></textarea>
<button id="checkPracticeBtn" type="button">核对</button>
</div>
<p id="practiceFeedback" class="practice-feedback" aria-live="polite"></p>
</div>
</section>
```
- [ ] **Step 2: Replace the right transcript mode buttons with a transcript heading**
In `study.html`, replace the existing `.transcript-toolbar` contents:
```html
<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>
```
with:
```html
<div class="transcript-title">
<strong>字幕列表</strong>
<span id="subtitleMeta"></span>
</div>
```
This keeps `.transcript-toolbar` in place for layout and lets existing `els.subtitleMeta` become useful.
- [ ] **Step 3: Add practice DOM references**
In `app.js`, add these properties to the `els` object:
```javascript
practiceModeLabel: IS_BROWSER ? document.querySelector("#practiceModeLabel") : null,
practicePromptText: IS_BROWSER ? document.querySelector("#practicePromptText") : null,
practiceReferenceText: IS_BROWSER ? document.querySelector("#practiceReferenceText") : null,
practiceAnswerRow: IS_BROWSER ? document.querySelector("#practiceAnswerRow") : null,
practiceAnswerInput: IS_BROWSER ? document.querySelector("#practiceAnswerInput") : null,
checkPracticeBtn: IS_BROWSER ? document.querySelector("#checkPracticeBtn") : null,
practiceFeedback: IS_BROWSER ? document.querySelector("#practiceFeedback") : null,
```
- [ ] **Step 4: Replace mode tab click handling**
In `bindEvents()`, replace the existing `els.modeTabs.forEach` body with:
```javascript
els.modeTabs.forEach((tab) => {
tab.addEventListener("click", () => {
setStudyMode(tab.dataset.mode || "bilingual");
});
});
```
Then add practice input event listeners in `bindEvents()` after the mode tab listener:
```javascript
els.practiceAnswerInput?.addEventListener("input", clearPracticeFeedback);
els.checkPracticeBtn?.addEventListener("click", checkPracticeAnswer);
```
- [ ] **Step 5: Add mode and practice render functions**
Add these functions after `renderSubtitleModeTabs()`:
```javascript
function setStudyMode(mode) {
subtitleMode = practiceModeLabels[mode] ? mode : "bilingual";
state.subtitleMode = subtitleMode;
saveState();
clearPracticeResponse();
renderSubtitleModeTabs();
renderTranscript();
syncSubtitles();
renderPracticePanel();
}
function getActiveCuePair() {
const video = getActiveVideo();
const index = activeLineIndex >= 0 ? activeLineIndex : 0;
return {
english: video?.subtitles?.en?.cues?.[index] || null,
chinese: video?.subtitles?.zh?.cues?.[index] || null,
};
}
function clearPracticeFeedback() {
if (!els.practiceFeedback) return;
els.practiceFeedback.textContent = "";
els.practiceFeedback.className = "practice-feedback";
}
function clearPracticeResponse() {
if (els.practiceAnswerInput) els.practiceAnswerInput.value = "";
clearPracticeFeedback();
}
function renderPracticePanel() {
if (!els.practiceModeLabel || !els.practicePromptText || !els.practiceReferenceText) return;
const viewState = getPracticeViewState(subtitleMode, getActiveCuePair());
els.practiceModeLabel.textContent = viewState.label;
els.practicePromptText.textContent = viewState.promptText;
els.practiceReferenceText.textContent = viewState.referenceText;
if (els.practiceAnswerRow) els.practiceAnswerRow.hidden = !viewState.inputVisible;
if (els.checkPracticeBtn) els.checkPracticeBtn.disabled = viewState.inputVisible && !viewState.canCheck;
if (viewState.feedbackHint && els.practiceFeedback && !els.practiceFeedback.textContent) {
els.practiceFeedback.textContent = viewState.feedbackHint;
els.practiceFeedback.className = "practice-feedback is-muted";
}
}
function checkPracticeAnswer() {
if (!els.practiceAnswerInput || !els.practiceFeedback) return;
const viewState = getPracticeViewState(subtitleMode, getActiveCuePair());
const result = comparePracticeAnswer(els.practiceAnswerInput.value, viewState.expectedText);
els.practiceFeedback.textContent = result.isCorrect || !result.reference
? result.message
: `${result.message} ${result.reference}`;
els.practiceFeedback.className = `practice-feedback is-${result.status}`;
}
```
- [ ] **Step 6: Render practice panel during page updates**
In `selectVideo(id)`, after `syncSubtitles();`, add:
```javascript
renderPracticePanel();
```
In `setActiveLine(index, scrollIntoView)`, after `syncSubtitles();`, add:
```javascript
clearPracticeResponse();
renderPracticePanel();
```
In `syncSubtitles()`, after the existing subtitle text updates, add:
```javascript
renderPracticePanel();
```
- [ ] **Step 7: Run syntax check**
Run:
```powershell
node --check app.js
```
Expected: PASS with no syntax errors.
- [ ] **Step 8: Commit markup and wiring**
```powershell
git add study.html app.js
git commit -m "feat: add study practice panel wiring"
```
## Task 4: Style Practice Modes and Practice Panel
**Files:**
- Modify: `F:\ooo\speaking-practice-local\styles.css`
- [ ] **Step 1: Update video panel row sizing**
Replace:
```css
.video-panel {
min-width: 0;
min-height: 0;
overflow: hidden;
display: grid;
grid-template-rows: minmax(520px, 1fr) auto auto;
}
```
with:
```css
.video-panel {
min-width: 0;
min-height: 0;
overflow: hidden;
display: grid;
grid-template-rows: minmax(500px, 1fr) auto auto auto;
}
```
- [ ] **Step 2: Add practice panel styles after `.tool-row` button styles**
Add:
```css
.practice-panel {
display: grid;
gap: 12px;
padding: 13px 16px 14px;
border-top: 1px solid var(--line);
background: #fbfdfd;
}
.practice-mode-bar {
flex-wrap: wrap;
gap: 5px;
}
.practice-mode-bar .tab {
min-height: 32px;
border: 1px solid transparent;
border-radius: 999px;
padding: 0 13px;
color: #344054;
background: #eef4f6;
font-weight: 750;
}
.practice-mode-bar .tab:hover {
border-color: #b9dcd5;
background: var(--brand-soft);
}
.practice-mode-bar .tab.active {
color: #fff;
border-color: var(--accent);
background: var(--accent);
}
.practice-body {
display: grid;
gap: 10px;
}
.practice-prompt {
min-height: 70px;
display: grid;
align-content: center;
gap: 5px;
padding: 12px 14px;
border: 1px solid #dde7ef;
border-radius: 8px;
background: #ffffff;
}
.practice-label {
color: var(--brand);
font-size: 12px;
font-weight: 850;
}
.practice-primary,
.practice-secondary,
.practice-feedback {
margin: 0;
}
.practice-primary {
color: #172033;
font-size: 16px;
line-height: 1.45;
font-weight: 750;
}
.practice-secondary {
color: var(--muted);
font-size: 13px;
line-height: 1.45;
}
.practice-answer-row {
display: grid;
grid-template-columns: minmax(0, 1fr) auto;
gap: 9px;
align-items: stretch;
}
.practice-answer-row textarea {
min-height: 58px;
resize: vertical;
}
.practice-answer-row button {
min-width: 76px;
min-height: 42px;
align-self: start;
color: #ffffff;
border-color: var(--brand);
background: var(--brand);
font-weight: 800;
}
.practice-answer-row button:hover {
border-color: #0d625c;
background: #0d625c;
}
.practice-answer-row button:disabled {
color: #98a2b3;
border-color: #d8e2ec;
background: #e8eef5;
}
.practice-feedback {
min-height: 20px;
color: var(--muted);
font-size: 13px;
line-height: 1.45;
}
.practice-feedback.is-correct {
color: #047857;
font-weight: 750;
}
.practice-feedback.is-incorrect,
.practice-feedback.is-empty,
.practice-feedback.is-missing-reference {
color: var(--danger);
font-weight: 700;
}
.practice-feedback.is-muted {
color: var(--muted);
}
```
- [ ] **Step 3: Add transcript title styles near `.transcript-toolbar`**
Add:
```css
.transcript-title {
display: grid;
gap: 3px;
}
.transcript-title strong {
font-size: 14px;
}
.transcript-title span {
color: var(--muted);
font-size: 12px;
}
```
- [ ] **Step 4: Update mobile video panel row sizing**
In the `@media (max-width: 560px)` block, replace:
```css
.video-panel {
grid-template-rows: minmax(360px, 1fr) auto auto;
}
```
with:
```css
.video-panel {
grid-template-rows: minmax(340px, 1fr) auto auto auto;
}
```
- [ ] **Step 5: Add mobile stacking for the answer row**
Inside the `@media (max-width: 560px)` block, add:
```css
.practice-panel {
padding: 12px;
}
.practice-answer-row {
grid-template-columns: 1fr;
}
.practice-answer-row button {
width: 100%;
}
```
- [ ] **Step 6: Run CSS visual scan by searching new selectors**
Run:
```powershell
Select-String -Path styles.css -Pattern 'practice-panel|practice-mode-bar|practice-answer-row|transcript-title'
```
Expected: output includes all four selector groups.
- [ ] **Step 7: Commit styles**
```powershell
git add styles.css
git commit -m "style: polish study practice modes"
```
## Task 5: Verification
**Files:**
- Verify: `F:\ooo\speaking-practice-local\study.html`
- Verify: `F:\ooo\speaking-practice-local\app.js`
- Verify: `F:\ooo\speaking-practice-local\styles.css`
- Verify: `F:\ooo\speaking-practice-local\tests\practice-helpers.test.mjs`
- [ ] **Step 1: Run JavaScript syntax checks**
```powershell
node --check app.js
node --check home.js
node --check admin.js
```
Expected: each command exits successfully with no syntax errors.
- [ ] **Step 2: Run Node helper tests**
```powershell
node tests\practice-helpers.test.mjs
node tests\progress-helpers.test.mjs
node tests\admin-file-input.test.mjs
```
Expected: each command exits successfully with no output.
- [ ] **Step 3: Run backend syntax checks**
```powershell
python -m py_compile backend\main.py backend\db.py
```
Expected: command exits successfully with no output.
- [ ] **Step 4: Start the local server**
Run:
```powershell
python -m uvicorn backend.main:app --host 127.0.0.1 --port 8000
```
Expected: server starts on `http://127.0.0.1:8000`.
- [ ] **Step 5: Browser check the study page**
Open:
```text
http://127.0.0.1:8000/study.html
```
Confirm:
- The mode bar appears on the left below the video controls.
- The mode bar shows exactly `双语`, `英文`, `中文`, `听写`, `中译英`.
- `挖空` does not appear.
- The right panel heading is `字幕列表`, not a mode input area.
- `听写` shows the answer input on the left.
- `中译英` shows the answer input on the left and uses the Chinese cue as the prompt.
- `双语`, `英文`, and `中文` hide the answer input.
- A correct answer with different case or punctuation shows `完全匹配。`.
- A wrong answer shows the reference English.
- Clicking another transcript sentence clears the input and feedback.
- Previous, replay, next, loop, favorite, practiced, difficult, and recording controls still respond.
- [ ] **Step 6: Browser check narrow layout**
Resize the viewport to about 390px wide.
Confirm:
- Mode buttons wrap without horizontal scrolling.
- The answer input and check button stack cleanly.
- No button text overflows.
- The transcript rows remain readable.
- [ ] **Step 7: Final status check**
Run:
```powershell
git status --short
```
Expected: only intended feature files are modified or the working tree is clean after commits. Existing unrelated local files from earlier work may remain; do not revert them.
## Self-Review Notes
- Spec coverage: tasks cover the five modes, removal of `挖空`, left-side input, right transcript as navigation/status, simple checking, input reset, missing subtitle handling, styling, and verification.
- Placeholder scan: this plan uses explicit file paths, commands, expected results, function names, and code blocks.
- Type consistency: mode ids are `bilingual`, `english`, `chinese`, `dictation`, and `translation` across HTML, helper tests, helper implementation, and rendering.
@@ -0,0 +1,461 @@
# Speaking Lab Study Right Mode Panel 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 the learning mode bar and focused practice UI into the right panel, while display modes show the transcript list and input modes hide it.
**Architecture:** Reuse the existing practice helpers and mode state. Move existing markup from the left video panel into the right panel, then make `app.js` toggle between transcript-list view and focused-practice view based on `subtitleMode`.
**Tech Stack:** Vanilla HTML, CSS, JavaScript, Node `assert` tests, FastAPI static app for browser verification.
---
## File Structure
- `F:\ooo\speaking-practice-local\study.html`: move existing practice mode/prompt markup from below the video controls into the right panel.
- `F:\ooo\speaking-practice-local\app.js`: toggle right-panel views by mode and keep practice reset/checking behavior.
- `F:\ooo\speaking-practice-local\styles.css`: remove the extra left-panel row and restyle the right panel for transcript vs focused practice modes.
- `F:\ooo\speaking-practice-local\tests\practice-helpers.test.mjs`: no changes expected; existing helper coverage should continue to pass.
## Task 1: Move Practice Markup Into Right Panel
**Files:**
- Modify: `F:\ooo\speaking-practice-local\study.html`
- [ ] **Step 1: Move the practice panel out of the video panel**
In `study.html`, remove this entire block from inside `.video-panel`, currently between `.tool-row` and `.recording-line`:
```html
<section class="practice-panel" aria-label="当前句练习">
<div class="practice-mode-bar tabs" aria-label="学习模式">
<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>
<button class="tab" type="button" data-mode="dictation">听写</button>
<button class="tab" type="button" data-mode="translation">中译英</button>
</div>
<div class="practice-body">
<div class="practice-prompt">
<span id="practiceModeLabel" class="practice-label">双语</span>
<p id="practicePromptText" class="practice-primary"></p>
<p id="practiceReferenceText" class="practice-secondary"></p>
</div>
<div id="practiceAnswerRow" class="practice-answer-row" hidden>
<textarea id="practiceAnswerInput" rows="2" placeholder="输入你的英文答案"></textarea>
<button id="checkPracticeBtn" type="button">核对</button>
</div>
<p id="practiceFeedback" class="practice-feedback" aria-live="polite"></p>
</div>
</section>
```
- [ ] **Step 2: Add the mode bar to the right panel toolbar**
Replace the current right panel toolbar:
```html
<div class="transcript-toolbar">
<div class="transcript-title">
<strong>字幕列表</strong>
<span id="subtitleMeta"></span>
</div>
</div>
```
with:
```html
<div class="transcript-toolbar">
<div class="practice-mode-bar tabs" aria-label="学习模式">
<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>
<button class="tab" type="button" data-mode="dictation">听写</button>
<button class="tab" type="button" data-mode="translation">中译英</button>
</div>
<div class="transcript-title">
<strong id="rightPanelTitle">字幕列表</strong>
<span id="subtitleMeta"></span>
</div>
</div>
```
- [ ] **Step 3: Add focused practice view inside the right panel**
Insert this block after the closing `</div>` for `.transcript-toolbar` and before `<div id="transcriptList"`:
```html
<section id="rightPracticeView" class="right-practice-view" aria-label="当前句练习" hidden>
<div class="practice-body">
<div class="practice-prompt">
<span id="practiceModeLabel" class="practice-label">双语</span>
<p id="practicePromptText" class="practice-primary"></p>
<p id="practiceReferenceText" class="practice-secondary"></p>
</div>
<div id="practiceAnswerRow" class="practice-answer-row" hidden>
<textarea id="practiceAnswerInput" rows="4" placeholder="输入你的英文答案"></textarea>
<button id="checkPracticeBtn" type="button">核对</button>
</div>
<p id="practiceFeedback" class="practice-feedback" aria-live="polite"></p>
</div>
</section>
```
- [ ] **Step 4: Verify there is no left practice panel**
Run:
```powershell
Select-String -Path study.html -Pattern 'practice-panel|rightPracticeView|practice-mode-bar|rightPanelTitle'
```
Expected:
- No `practice-panel` result.
- One `rightPracticeView` result.
- One `practice-mode-bar` result in the right panel.
- One `rightPanelTitle` result.
- [ ] **Step 5: Commit markup movement**
```powershell
git add study.html
git commit -m "refactor: move study practice markup to right panel"
```
## Task 2: Toggle Right Panel Views By Mode
**Files:**
- Modify: `F:\ooo\speaking-practice-local\app.js`
- [ ] **Step 1: Add right-panel DOM references**
In the `els` object near the existing transcript/practice refs, add:
```javascript
rightPanelTitle: IS_BROWSER ? document.querySelector("#rightPanelTitle") : null,
rightPracticeView: IS_BROWSER ? document.querySelector("#rightPracticeView") : null,
```
- [ ] **Step 2: Add view mode helper**
Add this helper after `renderSubtitleModeTabs()`:
```javascript
function isInputPracticeMode(mode = subtitleMode) {
return mode === "dictation" || mode === "translation";
}
```
- [ ] **Step 3: Update `renderPracticePanel()` to toggle panel visibility**
Replace the current `renderPracticePanel()` function with:
```javascript
function renderPracticePanel() {
const isPracticeMode = isInputPracticeMode();
if (els.rightPracticeView) els.rightPracticeView.hidden = !isPracticeMode;
if (els.transcriptList) els.transcriptList.hidden = isPracticeMode;
if (els.rightPanelTitle) {
els.rightPanelTitle.textContent = isPracticeMode ? practiceModeLabels[subtitleMode] : "字幕列表";
}
if (!els.practiceModeLabel || !els.practicePromptText || !els.practiceReferenceText) return;
const viewState = getPracticeViewState(subtitleMode, getActiveCuePair());
els.practiceModeLabel.textContent = viewState.label;
els.practicePromptText.textContent = viewState.promptText;
els.practiceReferenceText.textContent = isPracticeMode ? viewState.referenceText : "";
if (els.practiceAnswerRow) els.practiceAnswerRow.hidden = !viewState.inputVisible;
if (els.checkPracticeBtn) els.checkPracticeBtn.disabled = viewState.inputVisible && !viewState.canCheck;
if (viewState.feedbackHint && els.practiceFeedback && !els.practiceFeedback.textContent) {
els.practiceFeedback.textContent = viewState.feedbackHint;
els.practiceFeedback.className = "practice-feedback is-muted";
}
}
```
- [ ] **Step 4: Update subtitle meta for focused modes**
In `renderTranscript()`, replace:
```javascript
if (els.subtitleMeta) els.subtitleMeta.textContent = modeConfig.message || `${primary.length} 句 · 点击文字稿跳转到对应片段`;
```
with:
```javascript
if (els.subtitleMeta) {
els.subtitleMeta.textContent = isInputPracticeMode()
? "专注练习当前句"
: modeConfig.message || `${primary.length} 句 · 点击文字稿跳转到对应片段`;
}
```
Do not return early. The transcript list can still be rebuilt while hidden so sentence status and active line state remain intact.
- [ ] **Step 5: Run syntax and helper tests**
Run:
```powershell
node --check app.js
node tests\practice-helpers.test.mjs
node tests\progress-helpers.test.mjs
```
Expected: all commands pass with no output.
- [ ] **Step 6: Commit view toggling**
```powershell
git add app.js
git commit -m "feat: toggle right panel practice views"
```
## Task 3: Restyle Right Panel And Restore Video Panel Rows
**Files:**
- Modify: `F:\ooo\speaking-practice-local\styles.css`
- [ ] **Step 1: Restore video panel row count**
Replace:
```css
.video-panel {
min-width: 0;
min-height: 0;
overflow: hidden;
display: grid;
grid-template-rows: minmax(500px, 1fr) auto auto auto;
}
```
with:
```css
.video-panel {
min-width: 0;
min-height: 0;
overflow: hidden;
display: grid;
grid-template-rows: minmax(520px, 1fr) auto auto;
}
```
- [ ] **Step 2: Update transcript toolbar layout**
Replace the existing `.transcript-toolbar` block with:
```css
.transcript-toolbar {
display: grid;
gap: 10px;
padding: 12px 14px;
border-bottom: 1px solid var(--line);
}
```
- [ ] **Step 3: Replace left practice panel styling with right practice view styling**
Replace:
```css
.practice-panel {
display: grid;
gap: 12px;
padding: 13px 16px 14px;
border-top: 1px solid var(--line);
background: #fbfdfd;
}
```
with:
```css
.right-practice-view {
min-height: 0;
overflow: auto;
padding: 14px;
background: #fbfdfd;
}
```
- [ ] **Step 4: Tune focused practice spacing**
After the `.practice-body` block, add:
```css
.right-practice-view .practice-body {
min-height: 100%;
align-content: start;
gap: 12px;
}
```
Replace the `.practice-prompt` block with:
```css
.practice-prompt {
min-height: 118px;
display: grid;
align-content: center;
gap: 7px;
padding: 16px;
border: 1px solid #dde7ef;
border-radius: 8px;
background: #ffffff;
}
```
- [ ] **Step 5: Remove mobile rules for the removed left practice panel**
In the `@media (max-width: 560px)` block, replace:
```css
.video-panel {
grid-template-rows: minmax(340px, 1fr) auto auto auto;
}
```
with:
```css
.video-panel {
grid-template-rows: minmax(360px, 1fr) auto auto;
}
```
Remove this block:
```css
.practice-panel {
padding: 12px;
}
```
Keep the `.practice-answer-row` one-column and button-width rules, because they still apply to the right focused practice view on mobile.
- [ ] **Step 6: Run selector scan**
Run:
```powershell
Select-String -Path styles.css -Pattern 'practice-panel|right-practice-view|practice-mode-bar|transcript-toolbar|grid-template-rows: minmax'
```
Expected:
- No `.practice-panel` selector remains.
- `.right-practice-view` appears.
- `.practice-mode-bar` appears.
- `.transcript-toolbar` appears.
- Desktop video rows are `minmax(520px, 1fr) auto auto`.
- Mobile video rows are `minmax(360px, 1fr) auto auto`.
- [ ] **Step 7: Commit styles**
```powershell
git add styles.css
git commit -m "style: focus practice modes in right panel"
```
## Task 4: Verification
**Files:**
- Verify: `F:\ooo\speaking-practice-local\study.html`
- Verify: `F:\ooo\speaking-practice-local\app.js`
- Verify: `F:\ooo\speaking-practice-local\styles.css`
- [ ] **Step 1: Run automated checks**
```powershell
node --check app.js
node --check home.js
node --check admin.js
node tests\practice-helpers.test.mjs
node tests\progress-helpers.test.mjs
node tests\admin-file-input.test.mjs
python -m py_compile backend\main.py backend\db.py
```
Expected: all commands pass with no output.
- [ ] **Step 2: Start or reuse local server**
Run:
```powershell
python -m uvicorn backend.main:app --host 127.0.0.1 --port 8000
```
Expected: server is available at `http://127.0.0.1:8000`.
- [ ] **Step 3: Browser check desktop layout**
Open:
```text
http://127.0.0.1:8000/study.html
```
Confirm:
- The left video area has no mode bar and no practice input.
- The left video panel rows are video, toolbar, recording line only.
- The right panel mode bar shows exactly `双语`, `英文`, `中文`, `听写`, `中译英`.
- `挖空` does not appear.
- In `双语`, `英文`, and `中文`, the transcript list is visible.
- In `听写`, the transcript list is hidden and only dictation UI is visible.
- In `中译英`, the transcript list is hidden and only translation UI is visible.
- Correct and incorrect answer checking still works.
- Switching modes clears input and feedback.
- Moving to next sentence clears input and feedback.
- [ ] **Step 4: Browser check preserved controls**
Confirm:
- Previous, replay, and next still move between cues.
- Loop checkbox remains visible and clickable.
- Favorite remains visible and clickable.
- Recording buttons remain in the left toolbar.
- `已练` and `难句` still appear and work in transcript display modes.
- [ ] **Step 5: Browser check narrow viewport**
Resize to about 390px wide.
Confirm:
- Right panel stacks below the video as before.
- Mode buttons wrap without horizontal overflow.
- `听写` and `中译英` focused views do not show the transcript list.
- Input and check button stack cleanly.
- No text overlaps or spills outside buttons.
- [ ] **Step 6: Final status check**
Run:
```powershell
git status --short
```
Expected: implementation files are committed. Existing unrelated local edits may remain and must not be reverted.
## Self-Review Notes
- Spec coverage: tasks cover keeping the two-column structure, moving learning controls out of the left video area, placing the mode bar in the right panel, showing transcript only for display modes, hiding transcript for `听写` and `中译英`, preserving existing controls, and excluding `挖空`.
- Placeholder scan: no `TBD`, `TODO`, or unspecified implementation steps are present.
- Type consistency: mode ids remain `bilingual`, `english`, `chinese`, `dictation`, and `translation`.
@@ -0,0 +1,86 @@
# Speaking Lab Home Premium Cards UI Design
## Goal
Upgrade the home page visual design into a cleaner, higher-quality learning library interface.
This pass focuses on spacing, cards, dashboard polish, material card quality, and category chips.
## Scope
Included:
- Home page background and layout spacing.
- Home shell grid with a 280px sidebar and adaptive content area.
- White dashboard surface with 16px radius and soft shadow.
- Metric card hover and active transitions.
- Larger, clearer metric numbers.
- Responsive material card grid using `repeat(auto-fill, minmax(320px, 1fr))`.
- Premium white material cards with 16px radius, soft shadow, and hover lift.
- Fixed 180px cover area.
- More comfortable card content spacing and title hierarchy.
- Dashed divider above card stats.
- Card stats as a compact horizontal bottom bar.
- Capsule category chips with soft default state and strong active state.
Excluded:
- README changes.
- Backend changes.
- Study page changes.
- Admin page changes.
- New data fields.
- Custom thumbnail upload.
- Real image extraction.
## Visual Rules
Use:
- page background `#f8fafc`
- cards `#ffffff`
- soft gray borders
- soft non-black shadows
- 16px radii for dashboard and material cards
- 20px pill radii for chips
- subtle motion: `translateY(-4px)` on material card hover
Avoid:
- heavy dark shadows
- large gradients dominating cards
- reducing readability
- layout shifts on hover
## Implementation Notes
The existing HTML structure already supports the design.
Implementation should primarily modify `styles.css`.
The existing generated cover tones can remain, but the cover area should have a stable 180px height and feel more refined.
The existing `dl.home-card-stats` should be restyled as a bottom stat bar instead of boxed mini cards.
## Verification
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 the page background is light gray-blue.
3. Confirm sidebar width and spacing feel more premium.
4. Confirm material card grid uses wider cards.
5. Hover a material card and confirm it lifts smoothly.
6. Confirm category chips are capsule-shaped.
7. Confirm no text overlaps on desktop or narrow viewport.
@@ -0,0 +1,73 @@
# Speaking Lab Study Toolbar Polish Design
## Goal
Refine the study page toolbar so the core English practice controls feel centered, focused, and visually consistent with the upgraded home page UI.
## Scope
Included:
- Remove `继续学习` from the study page toolbar.
- Remove `稍后再看` from the study page toolbar.
- Keep `收藏`.
- Place `上一句 / 重播 / 下一句` in the visual center as the primary practice controls.
- Place recording controls as secondary controls on the left.
- Place a larger loop toggle and favorite action on the right.
- Style the toolbar and buttons with a premium white-card look matching the home page.
Excluded:
- Removing existing localStorage `watchLater` data.
- Removing helper functions unrelated to visible toolbar behavior.
- Backend changes.
- README changes.
- Home page changes.
## Layout
The toolbar uses three zones:
- Left: `录音 / 停止 / 回放`
- Center: `上一句 / 重播 / 下一句`
- Right: large `循环` toggle and `收藏`
On narrow screens, the zones may wrap but should remain readable and should not overflow horizontally.
## Behavior
Existing behavior remains:
- Previous sentence jumps back one cue.
- Replay jumps to current sentence.
- Next sentence jumps forward one cue.
- Loop checkbox controls sentence loop.
- Favorite toggles current material in favorites.
- Recording controls keep existing browser recording behavior.
Removed behavior:
- The study page no longer exposes a `继续学习` button.
- The study page no longer exposes a `稍后再看` button.
## Verification
Run:
```powershell
node --check app.js
node --check home.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/study.html`.
2. Confirm `上一句 / 重播 / 下一句` are centered.
3. Confirm `循环` is larger and easy to see.
4. Confirm `继续学习` and `稍后再看` do not appear.
5. Confirm `收藏` still works.
6. Confirm no horizontal overflow on a narrow viewport.
@@ -0,0 +1,241 @@
# Speaking Lab Activation Auth Design
## Goal
Turn Speaking Lab from a local-only prototype into a shareable private product prototype with gated registration.
Users should be able to register only after entering a valid activation code. Registered users can use the home and study pages. Admins can upload and manage learning materials, generate activation codes, and manage user accounts.
## Scope
Included:
- New centered login/register page inspired by the provided TEco Lab reference.
- Login with server-stored username and password.
- Registration with one-time activation code.
- Server-side SQLite storage for users and activation codes.
- Session-style browser login state using a token returned by the backend.
- Admin-only backend APIs for user listing, user enable/disable, activation code generation, activation code listing, and unused activation code deletion.
- Admin page sections for account management and activation code management.
- Home and study pages redirect unauthenticated users to the login page.
- Home and study pages show the admin entry only for admin users.
- Remove duplicate "enter study page" entry from the study page/right-side learning area.
Excluded for this pass:
- Email verification.
- Paid checkout.
- Password reset.
- Multi-device session management UI.
- Per-user cloud sync for study progress.
- Advanced user roles beyond `user` and `admin`.
- Expiring activation codes.
- Bulk CSV import/export of activation codes.
## Roles
User:
- Logs in with a registered server account.
- Can access home and study pages.
- Can study, favorite, and keep existing browser-local learning progress.
- Cannot see admin buttons.
- Cannot access admin APIs.
Admin:
- Logs in with `.env` `ADMIN_USERNAME` and `ADMIN_PASSWORD`.
- Can access home, study, and admin pages.
- Can use existing material upload/edit/delete tools.
- Can view and disable users.
- Can generate and manage activation codes.
## User Flow
Login:
1. Visitor opens `/`, `/study.html`, or `/admin.html`.
2. If no valid auth token is stored, the page redirects to `/login.html`.
3. Visitor enters username and password.
4. Backend validates credentials.
5. Frontend stores returned auth token and role in `sessionStorage`.
6. Admin users go to the admin page if they came from admin, otherwise home.
7. Normal users go to home or the originally requested study URL.
Registration:
1. Visitor clicks the register link on the login page.
2. Visitor enters activation code.
3. Backend checks the code exists and is unused.
4. Visitor enters username and password.
5. Backend creates a user, marks the activation code as used, and returns a login token.
6. Frontend stores the token and sends the user to home.
Admin activation code management:
1. Admin opens the admin page.
2. Admin enters a quantity and clicks generate.
3. Backend creates random one-time codes.
4. Admin can copy codes and share them manually.
5. Used codes show the bound username and used time.
6. Unused codes can be deleted.
Admin account management:
1. Admin opens the admin page.
2. Admin sees registered users with status, role, created time, and last login time.
3. Admin can disable or enable normal users.
4. Disabled users cannot log in.
## Data Model
Extend the existing SQLite database.
Existing `users` table should be reused. It already has `email`, `password_hash`, `display_name`, and `role`; for this pass:
- Treat `email` as the unique login username field to avoid a risky migration.
- Store display name as the same value for this version.
- Add `is_active INTEGER NOT NULL DEFAULT 1`.
- Add `last_login_at TEXT`.
New `activation_codes` table:
- `id INTEGER PRIMARY KEY AUTOINCREMENT`
- `code TEXT NOT NULL UNIQUE`
- `created_by TEXT NOT NULL`
- `used_by_user_id INTEGER`
- `created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP`
- `used_at TEXT`
- `status TEXT NOT NULL DEFAULT 'unused'`
Valid statuses:
- `unused`
- `used`
## Backend API
Public auth APIs:
- `POST /api/auth/login`
- Body: `{ "username": "...", "password": "..." }`
- Returns: `{ "token": "...", "user": { "username": "...", "role": "user|admin" } }`
- `POST /api/auth/register`
- Body: `{ "activationCode": "...", "username": "...", "password": "..." }`
- Returns the same shape as login.
- `GET /api/auth/session`
- Requires `Authorization: Bearer <token>`.
- Returns the current user and role.
Admin APIs:
- `GET /api/admin/users`
- `PATCH /api/admin/users/{user_id}`
- Body: `{ "isActive": true|false }`
- `GET /api/admin/activation-codes`
- `POST /api/admin/activation-codes`
- Body: `{ "quantity": 1-100 }`
- `DELETE /api/admin/activation-codes/{code_id}`
- Only allowed for unused codes.
Existing material and AI admin APIs remain protected by the current admin credential mechanism, but frontend requests should use the authenticated admin session. Internally, the backend can support both the existing Basic admin credentials and the new Bearer admin token during this transition.
## Frontend
`login.html`:
- Full viewport centered layout.
- White translucent card with subtle blur and shadow.
- Brand title `Speaking Lab`.
- Login mode: username, password, login button.
- Register mode: activation code, username, password, confirm password, register button.
- Small links for switching between login and register.
`index.html` and `home.js`:
- Remove the inline email login/register form.
- Require authenticated session before rendering user-specific controls.
- Show username in the top bar.
- Show admin entry only when role is `admin`.
`study.html` and `app.js`:
- Remove the inline email login/register form.
- Require authenticated session.
- Keep learning progress in browser storage for now.
- Remove duplicate "enter study page" control from the right-side learning area if present.
- Show admin entry only for admin users if such an entry exists.
`admin.html` and `admin.js`:
- Admin page should verify admin session before rendering admin content.
- Keep the existing material management form.
- Add account management panel.
- Add activation code management panel.
## Security Notes
This is a product prototype, not a full commercial auth system.
Required safeguards for this pass:
- Passwords must be hashed server-side before storage.
- Activation codes must be random and hard to guess.
- Admin-only APIs must reject normal user tokens.
- Disabled users must be blocked at login and session check.
- Tokens should be signed using an `.env` secret if configured, with a development fallback warning.
Deferred safeguards:
- HttpOnly cookies.
- CSRF protection.
- Rate limiting.
- Password reset.
- Audit logs.
## Error Handling
Login:
- Wrong credentials: show a clear Chinese error meaning "account or password is incorrect."
- Disabled account: show a clear Chinese error meaning "account is disabled, contact admin."
Registration:
- Missing activation code: show a clear Chinese error asking for an activation code.
- Invalid or used activation code: show a clear Chinese error that the code is invalid or already used.
- Duplicate username: show a clear Chinese error that the account already exists.
- Password mismatch handled in frontend before request.
Admin:
- Non-admin access: redirect to login or show a clear Chinese error that admin access is required.
- Deleting used activation code: show a clear Chinese error that used activation codes cannot be deleted.
## Testing
Automated checks:
```powershell
python -m py_compile backend\main.py backend\db.py
node --check login.js
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
```
Manual browser checks:
1. Open `/` while logged out and confirm redirect to `/login.html`.
2. Try a bad login and confirm a clear error.
3. Log in as admin and confirm the admin button appears.
4. Generate an activation code in admin.
5. Log out and register a normal user with that code.
6. Confirm the normal user can access home/study and cannot see admin.
7. Confirm the used activation code cannot be reused.
8. Disable the user in admin.
9. Confirm the disabled user can no longer log in.
@@ -0,0 +1,117 @@
# Speaking Lab Button and Chip Style Refresh Design
## Goal
Refresh all Speaking Lab buttons and chips into a flatter, more refined style inspired by the saved TEco Lab reference page while preserving the current HTML structure and class names.
This is a CSS-only visual refactor unless implementation discovers a narrow accessibility issue that cannot be solved with CSS. Existing behavior, event wiring, IDs, and class names must remain unchanged.
## Reference Interpretation
The TEco Lab reference uses compact controls with:
- rounded-full chips and rounded-lg buttons;
- small, dense typography around 12px to 14px;
- low-contrast neutral backgrounds for inactive controls;
- solid dark/highlight backgrounds only for active or primary controls;
- minimal borders, soft inset or low shadow texture, and smooth hover/active feedback.
Speaking Lab should adapt those ideas to its Study Notebook direction: warm paper surfaces, deep green primary actions, subdued neutrals, and soft warning colors.
## Scope
Update `styles.css` for these existing selectors and related states:
- `.chip` and `.chip.active`;
- `.secondary-action`;
- `.danger-action`;
- `.primary-link`;
- `#adminSubmitBtn`;
- primary form buttons such as `.auth-form button[type="submit"]`, `.admin-form button[type="submit"]`, `.activation-code-form button[type="submit"]`, and `.practice-answer-row button`;
- relevant disabled, hover, active, and focus-visible states.
Do not rename selectors, add new required HTML, or change JavaScript behavior.
## Visual Rules
### Chips
`.chip` should become a compact capsule:
- pill radius;
- 12px font size;
- medium-bold weight;
- horizontal padding that supports short Chinese labels without crowding;
- inactive background in warm light neutral;
- no hard border in the default state;
- hover background slightly darker with subtle elevation;
- `.active` background deep green or dark ink, white text, and a low shadow.
### Secondary Actions
`.secondary-action` should be quiet and tactile:
- no heavy border;
- light warm neutral or translucent white background;
- muted text color;
- rounded-lg or small pill shape depending on existing dimensions;
- hover smoothly darkens the surface and text;
- active state gently presses down;
- disabled state is visibly inactive without looking broken.
This should cover admin entry, logout, cancel edit, refresh, edit, copy, and other secondary operations that use this class or existing secondary-action variants.
### Danger Actions
`.danger-action` should be soft warning, not pure red:
- pale rose background;
- dark rose text;
- transparent or rose-tinted border;
- hover deepens the rose background and text slightly;
- active state presses down;
- disabled state uses muted rose/neutral colors.
### Primary Actions
`#adminSubmitBtn`, `.primary-link`, login submit, activation-code submit, AI primary action, and practice check buttons should share a clear primary treatment:
- solid deep green background;
- white or warm-white text;
- minimal border matching the background;
- rounded pill or 10px radius based on control context;
- subtle shadow/elevation;
- hover slightly lightens or darkens while lifting by 1px;
- active removes the lift and compresses visually;
- focus-visible ring uses a soft green halo.
## Compatibility
The changes must not break:
- home category filters and material cards;
- study mode tabs and recording/sentence controls;
- login/register form controls;
- admin create/edit form buttons;
- admin video/user/activation-code action rows;
- disabled buttons and hidden states.
Existing responsive rules should keep working. If a button currently becomes full-width or wraps on small screens, preserve that behavior.
## Testing
Verification should include:
- syntax sanity via existing JS checks if implementation touches no JS;
- browser visual checks for home, study, admin, and login pages;
- at least one desktop viewport and one mobile-width viewport;
- confirm hover/active/focus/disabled states are not visually broken where practical;
- confirm no text overflows inside buttons or chips.
## Non-Goals
- No page structure redesign in this task.
- No new icon system in this task.
- No JavaScript behavior changes.
- No changes to backend or data model.
- No full Study Notebook layout implementation beyond button and chip styling.
@@ -0,0 +1,184 @@
# Speaking Lab Study Practice Modes Design
## Goal
Add lightweight sentence-level practice modes to the study page, using the current video sentence as the learning unit. The page should keep the video and controls on the left as the active practice area, while the transcript on the right remains a browsing and navigation surface.
The confirmed direction is "mode bar + current sentence practice area":
- Keep practice tied to the current subtitle cue.
- Put dictation and translation input on the left, below the video control area.
- Keep the right transcript focused on finding, jumping to, and marking sentences.
- Remove the cloze / fill-in-the-blank idea from this version.
## Scope
Included:
- Add study modes: `双语`, `英文`, `中文`, `听写`, `中译英`.
- Remove `挖空` from the planned feature set.
- Add a current sentence practice panel in the left control area.
- Move dictation-style input to the left practice panel.
- Keep the right transcript panel for subtitle browsing, sentence jumping, practiced status, difficult status, and favorites.
- Add simple answer checking for input modes.
- Reset the practice input and feedback when the current sentence or mode changes.
- Add focused tests for answer normalization and checking helpers.
Excluded:
- AI scoring or natural-language feedback.
- Backend changes.
- Database changes.
- Persistent per-sentence practice history.
- New routes or pages.
- Cloze / fill-in-the-blank practice.
- Replacing the existing video, recording, or transcript systems.
## UX
The study page keeps its current two-column learning layout:
- Left: video, playback controls, recording controls, current sentence practice panel.
- Right: transcript list and sentence status controls.
The mode controls should feel like one connected learning mode bar, not separate unrelated buttons. They can reuse the existing subtitle tab pattern if that fits the current markup and styling.
When the user selects a display-only mode:
- `双语`: show English and Chinese for the current sentence and transcript.
- `英文`: emphasize or show English only.
- `中文`: emphasize or show Chinese only.
When the user selects an input mode:
- `听写`: the left practice panel prompts the user to listen and type the current English sentence.
- `中译英`: the left practice panel shows the Chinese sentence and asks the user to type the English sentence.
The input area should sit close to the replay / previous / next controls so the workflow is natural:
1. Replay the current sentence.
2. Type an answer.
3. Check the answer.
4. Move to the next sentence.
The right transcript should not contain the dictation input. It may still visually reflect the selected mode, but its primary job remains scanning and navigation.
## Behavior
Mode changes:
- Selecting a mode updates the active learning mode immediately.
- Changing mode clears the practice text and feedback.
- Display modes do not require an answer field.
- Input modes show the answer field and check action.
Sentence changes:
- Moving to previous, replaying, next, or clicking a transcript cue keeps the selected mode.
- Changing the active cue clears the current practice text and feedback.
- Existing loop, favorite, practiced, difficult, recording, and replay behavior remains unchanged.
Answer checking:
- Normalize both the learner answer and expected English before comparison.
- Ignore letter case.
- Ignore common punctuation and extra whitespace.
- If normalized answers match, show a positive "correct" result.
- If they do not match, show a short mismatch result with the reference English answer.
Empty answer handling:
- If the user checks an empty answer, show a gentle prompt to type an answer first.
- Empty answers should not be marked correct.
Missing subtitle data:
- If the current cue has no English text, disable checking and show that no reference answer is available.
- If `中译英` has no Chinese text, still allow the mode but show a neutral placeholder instead of breaking layout.
## Components
Use existing study page structures where possible:
- `study.html`: add or adjust mode controls and the left practice panel markup.
- `app.js`: extend the current subtitle mode state into practice modes.
- `styles.css`: style the mode bar and practice panel so they match the current focused learning UI.
Recommended helper boundaries in `app.js`:
- `normalizePracticeAnswer(text)`: returns a comparison-safe answer string.
- `comparePracticeAnswer(input, expected)`: returns an object describing empty, correct, or incorrect state.
- `getPracticeViewState(mode, cue)`: derives prompt text, expected answer availability, and whether input should be visible.
These helpers should be pure where practical so they can be tested without a browser.
## Data Flow
The feature should use the current in-browser state only:
- Active mode is held in the existing page state.
- Practice input is held in DOM state or lightweight page state.
- Feedback is recalculated when the user checks an answer.
- No new API calls are needed.
- No new localStorage schema is needed for this first version.
The selected material and subtitle cues continue to come from the existing material loading flow.
## Visual Design
The practice panel should feel like part of the left control surface, not a separate dashboard card.
Design requirements:
- Compact enough to keep the video dominant.
- Clear prompt label for `听写` and `中译英`.
- Stable height so switching modes does not make the page jump heavily.
- Input, check button, and feedback should fit on desktop and mobile.
- Feedback should use restrained color states, such as soft green for correct and soft amber or red for mismatch.
- No decorative backgrounds, large hero styling, or nested cards.
On small screens:
- The mode bar may wrap.
- The input and check action may stack.
- Text must not overflow buttons or overlap adjacent content.
## Testing
Automated checks should include:
```powershell
node --check app.js
node tests\progress-helpers.test.mjs
node tests\admin-file-input.test.mjs
```
Add a focused Node test for practice helpers, covering:
- Case-insensitive matching.
- Punctuation-insensitive matching.
- Extra whitespace normalization.
- Empty answer handling.
- Incorrect answer returns the reference answer.
Manual browser checks:
1. Open `http://127.0.0.1:8000/study.html`.
2. Confirm the mode bar shows `双语`, `英文`, `中文`, `听写`, `中译英`.
3. Confirm `挖空` does not appear.
4. Select `听写` and confirm the input appears on the left below the video controls.
5. Confirm the right transcript does not contain the dictation input.
6. Type a matching answer with different case or punctuation and confirm it passes.
7. Type a wrong answer and confirm the reference English appears.
8. Move to another sentence and confirm input and feedback reset.
9. Confirm replay, previous, next, loop, favorite, practiced, difficult, and recording still work.
10. Check a narrow viewport for wrapping and text overflow.
## Acceptance Criteria
- The study page has five modes: `双语`, `英文`, `中文`, `听写`, `中译英`.
- No `挖空` mode exists in the UI or implementation for this version.
- Dictation input lives in the left control / practice area.
- The right transcript remains a navigation and status panel.
- Simple answer checking works without backend or AI dependencies.
- Existing study page controls continue to work.
@@ -0,0 +1,174 @@
# Speaking Lab Study Right Mode Panel Design
## Goal
Fix the study page practice-mode UI so the video area stays clean and the right panel changes content based on the selected learning mode.
The current functionality is correct, but the current placement makes the left video area feel crowded because the mode bar and practice panel sit below the video controls. The revised design keeps the existing two-column page structure and moves mode-specific learning content into the existing right panel.
## Scope
Included:
- Keep the existing page structure: left video stage, right learning panel.
- Remove the mode bar and practice panel from below the video controls.
- Put the mode bar at the top of the right panel.
- For `双语`, `英文`, and `中文`, show the normal transcript list in the right panel.
- For `听写`, hide the transcript list and show only the dictation practice view.
- For `中译英`, hide the transcript list and show only the translation practice view.
- Keep the existing answer checking behavior.
- Keep the existing previous, replay, next, loop, favorite, recording, practiced, and difficult behavior.
- Keep `挖空` out of the UI.
Excluded:
- Backend changes.
- Database changes.
- New persistent practice history.
- AI scoring.
- Changing the left/right page grid.
- Adding a separate route or modal.
- Reworking video playback controls.
## UX
The study page remains visually stable:
- Left column: video, recording controls, sentence navigation, loop, favorite, recording status.
- Right column: one learning panel that switches its internal content by mode.
The right panel has a compact mode bar at the top:
- `双语`
- `英文`
- `中文`
- `听写`
- `中译英`
Display modes:
- `双语`, `英文`, and `中文` show the transcript list.
- The transcript list remains scrollable.
- Transcript rows still support clicking to jump to a sentence.
- `已练` and `难句` remain visible on transcript rows.
Input modes:
- `听写` replaces the transcript list with a focused dictation view.
- `中译英` replaces the transcript list with a focused translation view.
- In these two modes, the right panel should not show the full subtitle list.
- The focused view should show only the controls needed for that mode: current sentence context, input, check button, feedback, and reference answer after checking.
## Behavior
Mode changes:
- Selecting a display mode switches the right panel to transcript-list view.
- Selecting `听写` switches the right panel to dictation view.
- Selecting `中译英` switches the right panel to translation view.
- Changing mode clears the current practice input and feedback.
Sentence changes:
- Previous, replay, next, and transcript-row clicks still update the active sentence.
- Changing the active sentence clears practice input and feedback.
- In `听写` or `中译英`, the focused practice view updates to the new current sentence.
Answer checking:
- Reuse the existing lightweight answer checking.
- Continue ignoring case, common punctuation, apostrophes, and extra whitespace.
- Correct answers show the existing positive result.
- Incorrect answers show the existing mismatch result and reference English.
- Empty answers prompt the learner to type first.
- Missing English reference disables or blocks checking with the existing missing-reference message.
Transcript visibility:
- The transcript list is visible only for `双语`, `英文`, and `中文`.
- The transcript list is hidden for `听写` and `中译英`.
- The app should not remove transcript data or status controls; it only changes what is visible.
## Components
`study.html`:
- Move the existing `.practice-mode-bar` into the right panel toolbar area.
- Move the existing `.practice-body` into the right panel as a focused practice view.
- Keep `#transcriptList` in the right panel.
- Remove the left-side `.practice-panel` from the video panel.
`app.js`:
- Keep the existing mode state and answer helper functions.
- Render the right panel as either transcript mode or focused practice mode.
- Ensure `renderTranscript()` still builds transcript rows for display modes.
- Ensure practice rendering no longer depends on the practice panel being below the video.
`styles.css`:
- Remove the extra video-panel row created for the left practice panel.
- Style the right panel as a single surface with:
- mode bar at top
- transcript list for display modes
- focused practice view for input modes
- Keep mobile behavior simple: the right panel stacks below the video as it already does.
## Visual Design
The right panel should feel like the learning console:
- Mode bar stays compact and visible at the top of the right panel.
- Display modes prioritize scanning subtitles.
- Input modes prioritize a calm single-task practice surface.
- The focused practice view should have enough spacing to feel intentional, but not like a marketing card.
- Avoid nested cards, decorative backgrounds, large hero typography, and extra explanatory text.
For `听写`:
- Show a short label such as `听写`.
- Show a prompt telling the learner to listen and type the current English sentence.
- Do not show the English sentence before checking.
For `中译英`:
- Show a short label such as `中译英`.
- Show the Chinese current sentence prominently.
- Show the English reference only after checking, or through the existing mismatch feedback.
## Testing
Automated checks:
```powershell
node --check app.js
node --check home.js
node --check admin.js
node tests\practice-helpers.test.mjs
node tests\progress-helpers.test.mjs
node tests\admin-file-input.test.mjs
python -m py_compile backend\main.py backend\db.py
```
Manual browser checks:
1. Open `http://127.0.0.1:8000/study.html`.
2. Confirm the left video area no longer contains the mode bar or practice panel.
3. Confirm the right panel has the mode bar.
4. Select `双语`, `英文`, and `中文`; confirm the transcript list is visible.
5. Select `听写`; confirm the transcript list is hidden and only dictation UI is visible.
6. Select `中译英`; confirm the transcript list is hidden and only translation UI is visible.
7. Confirm `挖空` does not appear.
8. Confirm checking correct and incorrect answers still works.
9. Confirm changing sentence clears input and feedback.
10. Confirm previous, replay, next, loop, favorite, recording, practiced, and difficult still work.
11. Check desktop and narrow viewport for no horizontal overflow or text overlap.
## Acceptance Criteria
- The left video/control area is clean and does not contain learning mode buttons or practice input.
- The right panel contains the mode bar.
- Display modes show the transcript list.
- `听写` and `中译英` hide the transcript list and show only their focused practice UI.
- Existing practice checking behavior continues to work.
- No `挖空` mode appears.
+84 -42
View File
@@ -2,9 +2,6 @@ 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"),
@@ -20,30 +17,26 @@ let state = loadState();
let videos = [];
let activeTag = "全部";
let activeStatus = "all";
let currentSessionUser = null;
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();
});
els.logoutBtn.addEventListener("click", () => window.SpeakingAuth.logout());
}
async function initializeHome() {
currentSessionUser = await window.SpeakingAuth.requireSession();
if (!currentSessionUser) return;
ensureLocalUserForSession(currentSessionUser);
renderAccount();
els.status.textContent = "正在加载素材...";
try {
videos = await apiRequest("/api/videos");
await syncLearningProgressFromBackend();
renderHome();
} catch (error) {
els.status.textContent = error.message || "素材加载失败。";
@@ -52,6 +45,9 @@ async function initializeHome() {
}
async function apiRequest(path, options = {}) {
if (window.SpeakingAuth) {
return window.SpeakingAuth.apiRequest(path, options);
}
const response = await fetch(path, options);
if (!response.ok) {
let message = "请求失败,请重试。";
@@ -104,7 +100,7 @@ function renderCategories() {
function renderDashboard() {
const user = getCurrentUser();
const metrics = calculateDashboardMetrics(user);
els.dashboardUser.textContent = user ? user.email : "登录后记录进度";
renderStudyPlan(metrics, user);
els.metricFilters.innerHTML = "";
getMetricItems(metrics).forEach((item) => {
@@ -128,6 +124,23 @@ function renderDashboard() {
});
}
function renderStudyPlan(metrics, user) {
const practiced = metrics.practicedLines;
const total = metrics.totalLines;
const percent = total ? Math.round((practiced / total) * 100) : 0;
const headline = practiced > 0 ? `已练 ${practiced} 句` : "准备开始";
const plan = user
? total > 0
? `今日计划:精听 10 分钟 · 完成度 ${percent}%`
: "今日计划:先添加一份素材"
: "今日计划:登录后记录学习进度";
els.dashboardUser.innerHTML = `
<strong>${headline}</strong>
<small>${plan}</small>
`;
}
function getMetricItems(metrics) {
return [
{ key: "all", label: "当前素材", value: metrics.total, hint: "持续更新中", icon: "::", tone: "blue" },
@@ -144,6 +157,15 @@ function calculateDashboardMetrics(user) {
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;
const lineSummary = videos.reduce((summary, video) => {
const totalLines = getDefaultCueCount(video);
const progress = getVideoProgress(user, video.id);
const practiced = progress.practicedLineIndexes.filter((index) => index < totalLines || totalLines === 0).length;
return {
practicedLines: summary.practicedLines + practiced,
totalLines: summary.totalLines + totalLines,
};
}, { practicedLines: 0, totalLines: 0 });
return {
total: videos.length,
@@ -151,6 +173,8 @@ function calculateDashboardMetrics(user) {
unstudied: Math.max(0, videos.length - studied),
favorites,
difficult,
practicedLines: lineSummary.practicedLines,
totalLines: lineSummary.totalLines,
};
}
@@ -178,6 +202,7 @@ function createVideoCard(video) {
card.className = "home-card";
card.innerHTML = `
<div class="home-cover tone-${coverTone}">
<img class="home-cover-image" alt="">
<span class="home-cover-badge"></span>
<button class="home-favorite" type="button" aria-label="收藏素材"></button>
<strong></strong>
@@ -209,6 +234,15 @@ function createVideoCard(video) {
card.querySelector(".home-cover-badge").textContent = tags[0] || "素材";
card.querySelector(".home-cover strong").textContent = getCoverText(video.title);
const cover = card.querySelector(".home-cover");
const coverImage = card.querySelector(".home-cover-image");
const coverUrl = String(video.coverUrl || "").trim();
if (coverUrl) {
cover.classList.add("has-image");
coverImage.src = coverUrl;
coverImage.alt = `${video.title || "Speaking Lab"} 封面`;
}
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));
@@ -220,7 +254,8 @@ function createVideoCard(video) {
statValues[2].textContent = `${difficultCount}`;
const favorite = card.querySelector(".home-favorite");
favorite.textContent = isFavorite ? "已收藏" : "收藏";
favorite.textContent = isFavorite ? "♥" : "♡";
favorite.setAttribute("aria-label", isFavorite ? "取消收藏素材" : "收藏素材");
favorite.classList.toggle("active", isFavorite);
favorite.addEventListener("click", (event) => {
event.preventDefault();
@@ -270,7 +305,7 @@ function getEmptyMessage(filtered) {
const query = els.searchInput.value.trim();
if (!videos.length) {
return isAdmin(user) ? "还没有素材,去后台添加第一个素材。" : "暂无素材。";
return "暂无素材。";
}
if (!user && ["studied", "favorites", "difficult"].includes(activeStatus)) {
return "登录后可以查看你的学习记录。";
@@ -331,42 +366,29 @@ function getCoverTone(id) {
}
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) ? " · 管理员" : ""}`;
els.userMenu.hidden = false;
els.userLabel.textContent = currentSessionUser?.username || "";
if (els.adminLink) {
els.adminLink.hidden = currentSessionUser?.role !== "admin";
}
}
function loginOrRegister() {
const email = els.emailInput.value.trim().toLowerCase();
const password = els.passwordInput.value;
if (!email || !password) return;
function ensureLocalUserForSession(sessionUser) {
const email = sessionUser.username;
let user = state.users.find((item) => item.email === email);
if (!user) {
user = {
id: `user-${Date.now()}`,
id: `server-${sessionUser.id || email}`,
email,
password,
role: email.includes("admin") ? "admin" : "user",
role: sessionUser.role || "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) {
@@ -386,14 +408,10 @@ function toggleFavorite(videoId) {
user.favorites = [...favorites];
saveState();
scheduleProgressSync();
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;
}
@@ -491,3 +509,27 @@ function loadState() {
function saveState() {
localStorage.setItem(STORAGE_KEY, JSON.stringify(state));
}
async function syncLearningProgressFromBackend() {
if (!window.SpeakingProgressSync) return;
try {
await window.SpeakingProgressSync.syncLearningState({
user: getCurrentUser(),
apiRequest,
saveState,
});
} catch (error) {
console.warn("Learning progress sync failed", error);
}
}
function scheduleProgressSync() {
if (!window.SpeakingProgressSync) return;
const queue = window.SpeakingProgressSync.createProgressSyncQueue({
getUser: getCurrentUser,
apiRequest,
saveState,
delay: 300,
});
queue.schedule();
}
+11 -12
View File
@@ -4,7 +4,7 @@
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Speaking Lab</title>
<link rel="stylesheet" href="./styles.css">
<link rel="stylesheet" href="./styles.css?v=20260609-typography">
</head>
<body class="home-page">
<header class="topbar home-topbar">
@@ -14,14 +14,9 @@
<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>
<a id="homeAdminLink" class="secondary-action" href="./admin.html" hidden>后台</a>
<div id="homeUserMenu" class="user-menu">
<span id="homeUserLabel"></span>
<a id="homeAdminLink" class="secondary-action" href="./admin.html" hidden>管理</a>
<button id="homeLogoutBtn" type="button">退出</button>
</div>
</div>
@@ -30,8 +25,11 @@
<main class="home-shell">
<aside class="home-dashboard" aria-label="学习概览">
<div class="home-dashboard-title">
<span>学习概览</span>
<strong id="homeDashboardUser">本地学习</strong>
<span>今日学习</span>
<div id="homeDashboardUser" class="home-plan-card">
<strong>准备开始</strong>
<small>今日计划:精听 10 分钟</small>
</div>
</div>
<div id="homeMetricFilters" class="home-metrics"></div>
</aside>
@@ -42,7 +40,6 @@
<h2>素材库</h2>
<p>搜索素材,按分类和学习状态继续练习。</p>
</div>
<a class="primary-link" href="./study.html">进入学习页</a>
</div>
<div id="homeCategoryFilters" class="home-categories"></div>
@@ -51,6 +48,8 @@
</section>
</main>
<script src="./home.js"></script>
<script src="./auth.js?v=20260605-auth"></script>
<script src="./progress-sync.js?v=20260615-progress-sync"></script>
<script src="./home.js?v=20260609-home-mobile"></script>
</body>
</html>
+54
View File
@@ -0,0 +1,54 @@
<!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?v=20260609-typography">
</head>
<body class="auth-page">
<main class="auth-shell">
<section class="auth-card" aria-labelledby="authTitle">
<div class="auth-heading">
<h1 id="authTitle">登录 Speaking Lab</h1>
<p>真实语料学英语</p>
</div>
<form id="authForm" class="auth-form">
<label id="activationCodeField" hidden>
<span>激活卡密</span>
<input id="activationCodeInput" type="text" autocomplete="one-time-code" spellcheck="false">
</label>
<label>
<span>账号</span>
<input id="usernameInput" type="text" autocomplete="username" autocapitalize="off" autocorrect="off" spellcheck="false" required>
</label>
<label>
<span>密码</span>
<input id="passwordInput" type="password" autocomplete="current-password" required>
</label>
<label id="confirmPasswordField" hidden>
<span>确认密码</span>
<input id="confirmPasswordInput" type="password" autocomplete="new-password">
</label>
<button id="authSubmitBtn" type="submit">登录</button>
</form>
<p id="authMessage" class="auth-message" hidden></p>
<div class="auth-links">
<button id="switchToLoginBtn" type="button" hidden>已有账号,去登录</button>
<span id="authDivider" aria-hidden="true">|</span>
<button id="switchToRegisterBtn" type="button">立即注册</button>
</div>
</section>
<footer class="auth-footer">
<span>Speaking Lab</span>
</footer>
</main>
<script src="./auth.js?v=20260605-auth"></script>
<script src="./login.js?v=20260605-auth"></script>
</body>
</html>
+101
View File
@@ -0,0 +1,101 @@
const els = {
title: document.querySelector("#authTitle"),
form: document.querySelector("#authForm"),
activationCodeField: document.querySelector("#activationCodeField"),
activationCodeInput: document.querySelector("#activationCodeInput"),
usernameInput: document.querySelector("#usernameInput"),
passwordInput: document.querySelector("#passwordInput"),
confirmPasswordField: document.querySelector("#confirmPasswordField"),
confirmPasswordInput: document.querySelector("#confirmPasswordInput"),
submitBtn: document.querySelector("#authSubmitBtn"),
message: document.querySelector("#authMessage"),
switchToLoginBtn: document.querySelector("#switchToLoginBtn"),
switchToRegisterBtn: document.querySelector("#switchToRegisterBtn"),
divider: document.querySelector("#authDivider"),
};
let mode = "login";
bindEvents();
initializeLoginPage();
function bindEvents() {
els.form.addEventListener("submit", handleSubmit);
els.switchToLoginBtn.addEventListener("click", () => setMode("login"));
els.switchToRegisterBtn.addEventListener("click", () => setMode("register"));
}
async function initializeLoginPage() {
const user = await window.SpeakingAuth.requireSession({ redirect: false });
if (user) {
goNext(user);
}
}
function setMode(nextMode) {
mode = nextMode;
const isRegister = mode === "register";
els.title.textContent = isRegister ? "注册 Speaking Lab" : "登录 Speaking Lab";
els.activationCodeField.hidden = !isRegister;
els.confirmPasswordField.hidden = !isRegister;
els.activationCodeInput.required = isRegister;
els.confirmPasswordInput.required = isRegister;
els.passwordInput.autocomplete = isRegister ? "new-password" : "current-password";
els.submitBtn.textContent = isRegister ? "激活并注册" : "登录";
els.switchToLoginBtn.hidden = !isRegister;
els.switchToRegisterBtn.hidden = isRegister;
els.divider.hidden = isRegister;
clearMessage();
}
async function handleSubmit(event) {
event.preventDefault();
clearMessage();
const username = els.usernameInput.value.trim();
const password = els.passwordInput.value;
const activationCode = els.activationCodeInput.value.trim();
const confirmPassword = els.confirmPasswordInput.value;
if (mode === "register" && password !== confirmPassword) {
showMessage("两次输入的密码不一致。", true);
return;
}
els.submitBtn.disabled = true;
els.submitBtn.textContent = mode === "register" ? "正在注册..." : "正在登录...";
try {
const user = mode === "register"
? await window.SpeakingAuth.register(activationCode, username, password)
: await window.SpeakingAuth.login(username, password);
goNext(user);
} catch (error) {
showMessage(error.message || "操作失败,请重试。", true);
} finally {
els.submitBtn.disabled = false;
els.submitBtn.textContent = mode === "register" ? "激活并注册" : "登录";
}
}
function goNext(user) {
const params = new URLSearchParams(window.location.search);
const next = params.get("next") || "./index.html";
if (next.includes("admin.html") && user.role !== "admin") {
window.location.href = "./index.html";
return;
}
window.location.href = next;
}
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");
}
+167
View File
@@ -0,0 +1,167 @@
(function () {
const IS_BROWSER = typeof window !== "undefined";
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 {
currentTime: Number(progress.currentTime) || 0,
activeLineIndex: Number.isInteger(progress.activeLineIndex) && progress.activeLineIndex >= 0
? progress.activeLineIndex
: 0,
practicedLineIndexes: normalizeIndexList(progress.practicedLineIndexes),
difficultLineIndexes: normalizeIndexList(progress.difficultLineIndexes),
updatedAt: String(progress.updatedAt || ""),
};
}
function normalizeRemoteLearningState(payload = {}) {
const progress = {};
Object.entries(payload.progress || {}).forEach(([videoId, item]) => {
progress[String(videoId)] = normalizeProgress(item);
});
return {
favorites: normalizeIdList(payload.favorites),
progress,
};
}
function normalizeIdList(value) {
if (!Array.isArray(value)) return [];
return [...new Set(value.map((item) => String(item)).filter(Boolean))]
.sort((a, b) => Number(a) - Number(b));
}
function mergeProgress(localProgress = {}, remoteProgress = {}) {
const merged = {};
const videoIds = new Set([
...Object.keys(localProgress || {}),
...Object.keys(remoteProgress || {}),
]);
videoIds.forEach((videoId) => {
const local = normalizeProgress(localProgress[videoId]);
const remote = normalizeProgress(remoteProgress[videoId]);
const localTime = Date.parse(local.updatedAt || "") || 0;
const remoteTime = Date.parse(remote.updatedAt || "") || 0;
const newest = remoteTime >= localTime ? remote : local;
merged[String(videoId)] = {
...newest,
practicedLineIndexes: normalizeIndexList([
...local.practicedLineIndexes,
...remote.practicedLineIndexes,
]),
difficultLineIndexes: normalizeIndexList([
...local.difficultLineIndexes,
...remote.difficultLineIndexes,
]),
};
});
return merged;
}
function mergeLearningState(localUser, remoteState) {
const remote = normalizeRemoteLearningState(remoteState);
return {
favorites: normalizeIdList([...(localUser?.favorites || []), ...remote.favorites]),
progress: mergeProgress(localUser?.progress || {}, remote.progress),
};
}
function applyLearningStateToUser(user, learningState) {
if (!user) return null;
const normalized = normalizeRemoteLearningState(learningState);
user.favorites = normalized.favorites;
user.progress = normalized.progress;
return user;
}
function buildLearningStatePayload(user) {
return {
favorites: normalizeIdList(user?.favorites || []),
progress: normalizeRemoteLearningState({ progress: user?.progress || {} }).progress,
};
}
async function fetchRemoteLearningState(apiRequest) {
if (!apiRequest) return { favorites: [], progress: {} };
return normalizeRemoteLearningState(await apiRequest("/api/me/progress"));
}
async function saveRemoteLearningState(apiRequest, user) {
if (!apiRequest || !user) return { favorites: [], progress: {} };
return normalizeRemoteLearningState(await apiRequest("/api/me/progress", {
method: "PUT",
body: JSON.stringify(buildLearningStatePayload(user)),
}));
}
async function syncLearningState({ user, apiRequest, saveState }) {
if (!user || !apiRequest) return null;
const remote = await fetchRemoteLearningState(apiRequest);
const merged = mergeLearningState(user, remote);
applyLearningStateToUser(user, merged);
saveState?.();
const saved = await saveRemoteLearningState(apiRequest, user);
applyLearningStateToUser(user, mergeLearningState(user, saved));
saveState?.();
return saved;
}
function createProgressSyncQueue({ getUser, apiRequest, saveState, delay = 800 }) {
let timer = null;
let inFlight = null;
async function flush() {
if (timer) {
clearTimeout(timer);
timer = null;
}
const user = getUser?.();
if (!user || !apiRequest) return null;
inFlight = saveRemoteLearningState(apiRequest, user)
.then((saved) => {
applyLearningStateToUser(user, mergeLearningState(user, saved));
saveState?.();
return saved;
})
.catch(() => null)
.finally(() => {
inFlight = null;
});
return inFlight;
}
function schedule() {
if (timer) clearTimeout(timer);
timer = setTimeout(flush, delay);
}
return { schedule, flush, get inFlight() { return inFlight; } };
}
const api = {
applyLearningStateToUser,
buildLearningStatePayload,
createProgressSyncQueue,
fetchRemoteLearningState,
mergeLearningState,
normalizeProgress,
normalizeRemoteLearningState,
saveRemoteLearningState,
syncLearningState,
};
if (IS_BROWSER) {
window.SpeakingProgressSync = api;
}
if (typeof module !== "undefined" && module.exports) {
module.exports = api;
}
})();
+42
View File
@@ -0,0 +1,42 @@
#!/usr/bin/env bash
set -euo pipefail
APP_DIR="${APP_DIR:-/opt/speaking-practice}"
SERVICE_NAME="${SERVICE_NAME:-speaking-practice}"
BRANCH_NAME="${BRANCH_NAME:-feature/deepseek-subtitle-ai}"
PYTHON_BIN="${PYTHON_BIN:-$APP_DIR/.venv/bin/python}"
echo "==> Updating Speaking Lab"
echo "App directory: $APP_DIR"
echo "Branch: $BRANCH_NAME"
echo "Service: $SERVICE_NAME"
echo
cd "$APP_DIR"
echo "==> Fetching latest code"
git fetch origin
git checkout "$BRANCH_NAME"
git pull --ff-only origin "$BRANCH_NAME"
echo
echo "==> Checking Python files"
"$PYTHON_BIN" -m py_compile \
backend/main.py \
backend/db.py \
backend/ai_config.py \
backend/deepseek_client.py \
backend/local_whisper.py \
backend/subtitle_ai.py \
backend/subtitle_tools.py
echo
echo "==> Restarting service"
systemctl restart "$SERVICE_NAME"
echo
echo "==> Service status"
systemctl status "$SERVICE_NAME" --no-pager -l
echo
echo "Update complete."
+48 -37
View File
@@ -3,8 +3,8 @@
<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">
<title>Speaking Lab 学习页</title>
<link rel="stylesheet" href="./styles.css?v=20260712-study-controls">
</head>
<body>
<header class="topbar">
@@ -13,12 +13,9 @@
</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>
<a class="secondary-action" href="./index.html">首页</a>
<a id="adminEntryBtn" class="secondary-action" href="./admin.html" hidden>后台</a>
<div id="userMenu" class="user-menu">
<span id="userLabel"></span>
<button id="logoutBtn" type="button">退出</button>
</div>
@@ -29,40 +26,30 @@
<section class="left-stage">
<section class="video-panel">
<div class="video-frame">
<video id="video" controls preload="metadata" crossorigin="anonymous"></video>
<video id="video" controls preload="metadata" crossorigin="anonymous" playsinline webkit-playsinline></video>
<div id="emptyVideo" class="empty-video">
<strong>选择或上传一个视频</strong>
<span>支持本地 MP4/WebM 和 HLS 地址</span>
<strong>选择一个视频</strong>
<span>从首页选择素材后开始练习。</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 class="recording-controls">
<button id="recordBtn" type="button" title="录音">录音</button>
<button id="stopRecordBtn" type="button" disabled title="停止">停止</button>
<button id="playRecordingBtn" type="button" disabled title="回放我的录音">回放</button>
</div>
<div class="video-actions">
<button id="continueBtn" type="button" hidden>继续学习</button>
<div class="sentence-controls">
<button id="previousBtn" type="button" title="上一句">上一句</button>
<button id="replayBtn" type="button" title="重播">重播</button>
<button id="nextBtn" type="button" title="下一句">下一句</button>
</div>
<div class="study-side-actions">
<label class="toggle">
<input id="loopToggle" type="checkbox">
<span>循环</span>
</label>
<button id="favoriteBtn" type="button">收藏</button>
<button id="watchLaterBtn" type="button">稍后再看</button>
</div>
</div>
@@ -75,18 +62,42 @@
<aside class="transcript-panel">
<div class="transcript-toolbar">
<div class="tabs">
<div class="practice-mode-bar tabs" aria-label="学习模式">
<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>
<button class="tab" type="button" data-mode="dictation">听写</button>
<button class="tab" type="button" data-mode="translation">中译英</button>
</div>
<div class="transcript-title">
<strong id="rightPanelTitle">字幕列表</strong>
<span id="subtitleMeta"></span>
</div>
</div>
<section id="rightPracticeView" class="right-practice-view" aria-label="当前句练习" hidden>
<div class="practice-body">
<div class="practice-prompt">
<span id="practiceModeLabel" class="practice-label">双语</span>
<p id="practicePromptText" class="practice-primary"></p>
<p id="practiceReferenceText" class="practice-secondary"></p>
</div>
<div id="practiceAnswerRow" class="practice-answer-row" hidden>
<textarea id="practiceAnswerInput" rows="4" placeholder="输入你的英文答案"></textarea>
<button id="checkPracticeBtn" type="button">核对</button>
</div>
<p id="practiceFeedback" class="practice-feedback" aria-live="polite"></p>
</div>
</section>
<div id="transcriptList" class="transcript-list">
<div class="empty-state">上传字幕后,每一句都会变成可点击的片段。</div>
</div>
</aside>
</main>
<script src="./app.js"></script>
<script src="./auth.js?v=20260605-auth"></script>
<script src="./progress-sync.js?v=20260615-progress-sync"></script>
<script src="./app.js?v=20260605-auth"></script>
</body>
</html>
+990 -154
View File
File diff suppressed because it is too large. Load diff
+12
View File
@@ -0,0 +1,12 @@
import assert from "node:assert/strict";
import adminHelpers from "../admin.js";
assert.equal(
adminHelpers.getActivationCodeCopyFallbackMessage("SL-ABC123"),
"复制失败,请手动复制:SL-ABC123",
);
assert.equal(
adminHelpers.getActivationCodeCopiedLabel(),
"已复制",
);
+63
View File
@@ -0,0 +1,63 @@
import assert from "node:assert/strict";
import adminHelpers from "../admin.js";
const {
getAiSubtitleButtonState,
getLocalWhisperButtonState,
getStoredAdminToken,
pickVideoAfterSave,
setStoredAdminToken,
shouldConfirmSubtitleOverwrite,
} = adminHelpers;
assert.deepEqual(getAiSubtitleButtonState({ configured: false }, { id: 1 }), {
disabled: true,
hint: "请先配置 DeepSeek API。",
});
assert.deepEqual(getAiSubtitleButtonState({ configured: true }, null), {
disabled: true,
hint: "请先在右侧素材列表点“编辑”。",
});
assert.deepEqual(getAiSubtitleButtonState({ configured: true }, { id: 1 }), {
disabled: false,
hint: "",
});
assert.deepEqual(getLocalWhisperButtonState({ configured: false, localWhisperEnabled: true }, { id: 1 }), {
disabled: false,
hint: "",
});
assert.deepEqual(getLocalWhisperButtonState({ configured: true, localWhisperEnabled: false }, { id: 1 }), {
disabled: true,
hint: "请先开启本地 Whisper。",
});
assert.deepEqual(getLocalWhisperButtonState({ configured: true, localWhisperEnabled: true }, null), {
disabled: true,
hint: "请先在右侧素材列表点“编辑”。",
});
const created = { id: 9, title: "New material" };
const previous = { id: 7, title: "Old material" };
assert.equal(pickVideoAfterSave([previous, created], { video: created }, null), created);
assert.equal(pickVideoAfterSave([previous, created], { ok: true }, previous), previous);
assert.equal(shouldConfirmSubtitleOverwrite(null), false);
assert.equal(shouldConfirmSubtitleOverwrite({ subtitles: {} }), false);
assert.equal(shouldConfirmSubtitleOverwrite({ subtitles: { en: { content: "WEBVTT\n\nhello" } } }), true);
assert.equal(shouldConfirmSubtitleOverwrite({ subtitles: { zh: { content: "WEBVTT\n\nhello" } } }), false);
const memoryStorage = new Map();
const fakeSessionStorage = {
getItem: (key) => memoryStorage.get(key) || null,
setItem: (key, value) => memoryStorage.set(key, value),
removeItem: (key) => memoryStorage.delete(key),
};
assert.equal(getStoredAdminToken(fakeSessionStorage), "");
setStoredAdminToken(fakeSessionStorage, "admin-token-value");
assert.equal(getStoredAdminToken(fakeSessionStorage), "admin-token-value");
assert.equal([...memoryStorage.values()].some((value) => String(value).includes("secret")), false);
+5
View File
@@ -19,6 +19,11 @@ function run() {
title: "a-very-long-subtitle-file-name-for-practice.vtt",
isSelected: true,
});
assert.deepEqual(getFileInputState({ name: "lesson-cover.jpg" }, "封面图片"), {
text: "已选:lesson-cover.jpg",
title: "lesson-cover.jpg",
isSelected: true,
});
}
run();
+6 -1
View File
@@ -1,5 +1,7 @@
import assert from "node:assert/strict";
import { buildWebVtt, parseSubtitleBlocks } from "../admin.js";
import adminHelpers from "../admin.js";
const { buildWebVtt, parseSubtitleBlocks } = adminHelpers;
const cues = parseSubtitleBlocks(`WEBVTT
@@ -38,3 +40,6 @@ assert.equal(buildWebVtt(cues), `WEBVTT
Second line
continued
`);
assert.equal(adminHelpers.shiftCueTimeRange, undefined);
assert.equal(adminHelpers.shiftSubtitleCues, undefined);
+94
View File
@@ -0,0 +1,94 @@
import json
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from backend.ai_config import DeepSeekConfig
from backend.deepseek_client import DeepSeekClient
class FakeResponse:
def __init__(self, payload):
self.payload = payload
def __enter__(self):
return self
def __exit__(self, exc_type, exc, tb):
return False
def read(self):
return json.dumps(self.payload).encode("utf-8")
def make_config() -> DeepSeekConfig:
return DeepSeekConfig(
api_key="test-key",
base_url="https://coding.simgreek.com",
model="qwen-plus",
audio_model="qwen-plus",
provider="qwen",
protocol="anthropic",
translation_batch_size=20,
timeout_seconds=180,
)
def test_anthropic_chat_json_posts_messages_request(monkeypatch):
captured = {}
def fake_urlopen(request, timeout):
captured["url"] = request.full_url
captured["headers"] = dict(request.header_items())
captured["body"] = json.loads(request.data.decode("utf-8"))
return FakeResponse({
"content": [
{"type": "text", "text": '{"translations":[{"index":1,"zh":"你好"}]}'}
]
})
monkeypatch.setattr("backend.deepseek_client.urllib.request.urlopen", fake_urlopen)
client = DeepSeekClient(make_config())
result = client.chat_json("Return JSON only.", {"cues": [{"index": 1, "text": "Hello"}]})
assert captured["url"] == "https://coding.simgreek.com/v1/messages"
assert captured["body"]["model"] == "qwen-plus"
assert captured["body"]["system"] == "Return JSON only."
assert captured["body"]["messages"][0]["role"] == "user"
assert "x-api-key" in {key.lower(): value for key, value in captured["headers"].items()}
assert result["translations"][0]["zh"] == "你好"
def test_chat_json_accepts_markdown_wrapped_json(monkeypatch):
def fake_urlopen(request, timeout):
return FakeResponse({
"content": [
{
"type": "text",
"text": 'Here is the result:\n```json\n{"translations":[{"index":1,"zh":"你好"}]}\n```',
}
]
})
monkeypatch.setattr("backend.deepseek_client.urllib.request.urlopen", fake_urlopen)
client = DeepSeekClient(make_config())
result = client.chat_json("Return JSON only.", {"cues": [{"index": 1, "text": "Hello"}]})
assert result["translations"][0]["zh"] == "你好"
if __name__ == "__main__":
class MonkeyPatch:
def setattr(self, target, value):
parts = target.split(".")
module = __import__(".".join(parts[:2]), fromlist=[parts[1]])
current = module
for part in parts[2:-1]:
current = getattr(current, part)
setattr(current, parts[-1], value)
test_anthropic_chat_json_posts_messages_request(MonkeyPatch())
test_chat_json_accepts_markdown_wrapped_json(MonkeyPatch())
+169
View File
@@ -0,0 +1,169 @@
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from backend import ai_config
from backend.ai_config import (
get_ai_status,
load_deepseek_config,
load_local_whisper_config,
load_text_ai_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 "AI_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"
def test_load_deepseek_config_accepts_generic_ai_names(monkeypatch):
monkeypatch.setenv("AI_API_KEY", "generic-key")
monkeypatch.setenv("AI_BASE_URL", "https://coding.simgreek.com/v1")
monkeypatch.setenv("AI_TEXT_MODEL", "qwen-plus")
monkeypatch.setenv("AI_AUDIO_MODEL", "qwen-omni-turbo")
monkeypatch.setenv("AI_API_PROTOCOL", "anthropic")
monkeypatch.setenv("AI_TRANSLATION_BATCH_SIZE", "15")
monkeypatch.setenv("AI_TIMEOUT_SECONDS", "180")
config = load_deepseek_config()
assert config.api_key == "generic-key"
assert config.base_url == "https://coding.simgreek.com/v1"
assert config.model == "qwen-plus"
assert config.audio_model == "qwen-omni-turbo"
assert config.protocol == "anthropic"
assert config.translation_batch_size == 15
assert config.timeout_seconds == 180
def test_load_split_text_config(monkeypatch):
monkeypatch.setenv("TEXT_AI_API_KEY", "text-key")
monkeypatch.setenv("TEXT_AI_BASE_URL", "https://api.deepseek.com")
monkeypatch.setenv("TEXT_AI_MODEL", "deepseek-chat")
monkeypatch.setenv("TEXT_AI_PROTOCOL", "openai")
text_config = load_text_ai_config()
assert text_config.api_key == "text-key"
assert text_config.base_url == "https://api.deepseek.com"
assert text_config.model == "deepseek-chat"
assert text_config.protocol == "openai"
def test_text_ai_batch_size_allows_zero(monkeypatch):
monkeypatch.setenv("TEXT_AI_API_KEY", "text-key")
monkeypatch.setenv("TEXT_AI_BATCH_SIZE", "0")
config = load_text_ai_config()
assert config.translation_batch_size == 0
def test_load_local_whisper_config(monkeypatch):
monkeypatch.setenv("LOCAL_WHISPER_ENABLED", "true")
monkeypatch.setenv("LOCAL_WHISPER_MODEL", "small")
monkeypatch.setenv("LOCAL_WHISPER_DEVICE", "cpu")
monkeypatch.setenv("LOCAL_WHISPER_COMPUTE_TYPE", "int8")
config = load_local_whisper_config()
assert config.enabled is True
assert config.model == "small"
assert config.device == "cpu"
assert config.compute_type == "int8"
def test_ai_status_uses_configured_provider_name(monkeypatch):
monkeypatch.setenv("AI_API_KEY", "generic-key")
monkeypatch.setenv("AI_PROVIDER", "qwen")
monkeypatch.setenv("AI_TEXT_MODEL", "qwen-plus")
status = get_ai_status()
assert status["configured"] is True
assert status["provider"] == "qwen"
assert status["model"] == "qwen-plus"
assert "AI API" in status["message"]
def test_read_env_file_accepts_utf8_bom():
import tempfile
with tempfile.TemporaryDirectory() as temp_dir:
env_path = Path(temp_dir) / ".env"
env_path.write_bytes(b"\xef\xbb\xbfAI_API_KEY=test-key\nAI_API_PROTOCOL=anthropic\n")
values = ai_config.read_env_file(env_path)
assert values["AI_API_KEY"] == "test-key"
assert values["AI_API_PROTOCOL"] == "anthropic"
class EnvPatch:
def __init__(self):
self.originals = {}
def setenv(self, key, value):
import os
self.originals.setdefault(key, os.environ.get(key))
os.environ[key] = value
def delenv(self, key, raising=True):
import os
self.originals.setdefault(key, os.environ.get(key))
if key in os.environ:
del os.environ[key]
elif raising:
raise KeyError(key)
def restore(self):
import os
for key, value in self.originals.items():
if value is None:
os.environ.pop(key, None)
else:
os.environ[key] = value
if __name__ == "__main__":
test_read_env_file_accepts_utf8_bom()
patch = EnvPatch()
original_read_env_file = ai_config.read_env_file
ai_config.read_env_file = lambda path=ai_config.ENV_PATH: {}
try:
test_ai_status_reports_missing_key(patch)
patch.restore()
test_load_deepseek_config_uses_defaults(patch)
patch.restore()
test_load_deepseek_config_accepts_generic_ai_names(patch)
patch.restore()
test_load_split_text_config(patch)
patch.restore()
test_text_ai_batch_size_allows_zero(patch)
patch.restore()
test_load_local_whisper_config(patch)
patch.restore()
test_ai_status_uses_configured_provider_name(patch)
finally:
patch.restore()
ai_config.read_env_file = original_read_env_file
+263
View File
@@ -0,0 +1,263 @@
import sys
import tempfile
from pathlib import Path
from fastapi import HTTPException
from fastapi.security import HTTPBasicCredentials
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from backend import ai_config, main
from backend.ai_config import DeepSeekConfig
from backend.deepseek_client import DeepSeekError
class EnvPatch:
def __init__(self):
self.originals = {}
self.attributes = []
def delenv(self, key, raising=True):
import os
self.originals.setdefault(key, os.environ.get(key))
if key in os.environ:
del os.environ[key]
elif raising:
raise KeyError(key)
def restore(self):
import os
for key, value in self.originals.items():
if value is None:
os.environ.pop(key, None)
else:
os.environ[key] = value
while self.attributes:
target, name, original = self.attributes.pop()
setattr(target, name, original)
def setattr(self, target, name, value):
self.attributes.append((target, name, getattr(target, name)))
setattr(target, name, value)
def test_ai_status_route_reports_missing_key(monkeypatch):
monkeypatch.delenv("DEEPSEEK_API_KEY", raising=False)
status = main.api_ai_status()
assert status["configured"] is False
assert "TEXT_AI_API_KEY" in status["message"]
def test_ai_test_route_rejects_missing_key(monkeypatch):
monkeypatch.delenv("DEEPSEEK_API_KEY", raising=False)
try:
main.api_ai_test()
except HTTPException as error:
assert error.status_code == 400
assert "TEXT_AI_API_KEY" in error.detail
else:
raise AssertionError("api_ai_test should reject missing DeepSeek API key")
def test_admin_credentials_require_matching_env_values(monkeypatch):
monkeypatch.setattr(main, "get_config_value", lambda key, default="": {
"ADMIN_USERNAME": "owner",
"ADMIN_PASSWORD": "secret",
}.get(key, default))
result = main.require_admin(HTTPBasicCredentials(username="owner", password="secret"))
assert result["username"] == "owner"
def test_admin_credentials_reject_wrong_password(monkeypatch):
monkeypatch.setattr(main, "get_config_value", lambda key, default="": {
"ADMIN_USERNAME": "owner",
"ADMIN_PASSWORD": "secret",
}.get(key, default))
try:
main.require_admin(HTTPBasicCredentials(username="owner", password="wrong"))
except HTTPException as error:
assert error.status_code == 401
else:
raise AssertionError("wrong admin password should be rejected")
def test_admin_credentials_reject_missing_config(monkeypatch):
monkeypatch.setattr(main, "get_config_value", lambda key, default="": "")
try:
main.require_admin(HTTPBasicCredentials(username="owner", password="secret"))
except HTTPException as error:
assert error.status_code == 503
assert "ADMIN_USERNAME" in error.detail
else:
raise AssertionError("missing admin config should be rejected")
def make_text_config() -> DeepSeekConfig:
return DeepSeekConfig(
api_key="test-key",
base_url="https://api.example.com",
model="demo-model",
audio_model="demo-audio-model",
provider="demo",
protocol="openai",
translation_batch_size=40,
timeout_seconds=120,
)
def test_ai_test_route_calls_model_client(monkeypatch):
calls = []
class FakeClient:
def __init__(self, config, timeout_seconds):
calls.append(("init", config.model, timeout_seconds))
def chat_json(self, system_prompt, user_payload):
calls.append(("chat_json", system_prompt, user_payload))
return {"ok": True}
monkeypatch.setattr(main, "get_ai_status", lambda: {"configured": True})
monkeypatch.setattr(main, "load_text_ai_config", make_text_config)
monkeypatch.setattr(main, "DeepSeekClient", FakeClient)
result = main.api_ai_test()
assert result["ok"] is True
assert calls[0] == ("init", "demo-model", 120)
assert calls[1][0] == "chat_json"
assert calls[1][2]["task"] == "ping"
def test_ai_test_route_reports_model_client_failure(monkeypatch):
class FakeClient:
def __init__(self, config, timeout_seconds):
pass
def chat_json(self, system_prompt, user_payload):
raise DeepSeekError("bad key")
monkeypatch.setattr(main, "get_ai_status", lambda: {"configured": True})
monkeypatch.setattr(main, "load_text_ai_config", make_text_config)
monkeypatch.setattr(main, "DeepSeekClient", FakeClient)
try:
main.api_ai_test()
except HTTPException as error:
assert error.status_code == 400
assert "bad key" in error.detail
else:
raise AssertionError("api_ai_test should report model client failures")
def test_ai_subtitle_route_writes_processed_vtt_files(monkeypatch):
calls = []
with tempfile.TemporaryDirectory() as temp_dir:
uploads_dir = Path(temp_dir) / "uploads"
monkeypatch.setattr(main, "UPLOADS_DIR", uploads_dir)
monkeypatch.setattr(main, "get_ai_status", lambda: {"configured": True})
monkeypatch.setattr(main, "load_text_ai_config", make_text_config)
monkeypatch.setattr(main, "DeepSeekClient", lambda config, timeout_seconds: object())
monkeypatch.setattr(
main,
"get_video",
lambda video_id: {
"id": video_id,
"subtitles": {
"en": {
"content": "WEBVTT\n\n1\n00:00:00.000 --> 00:00:01.000\nHello.",
"filePath": "/uploads/subtitles/original.vtt",
}
},
},
)
monkeypatch.setattr(
main,
"process_subtitles_with_ai",
lambda content, client, batch_size: {
"subtitle_en_content": "WEBVTT\n\n1\n00:00:00.000 --> 00:00:01.000\nHello.\n",
"subtitle_zh_content": "WEBVTT\n\n1\n00:00:00.000 --> 00:00:01.000\n你好。\n",
"report": {"duplicate_count": 0, "empty_count": 0, "translation_count": 1},
},
)
def fake_upsert_video_subtitle(video_id, **kwargs):
calls.append({"video_id": video_id, **kwargs})
monkeypatch.setattr(main, "upsert_video_subtitle", fake_upsert_video_subtitle)
result = main.api_process_video_subtitles(9)
assert result["report"]["translation_count"] == 1
assert len(calls) == 2
assert calls[0]["language_code"] == "en"
assert calls[1]["language_code"] == "zh"
assert calls[0]["file_path"].startswith("/uploads/subtitles/")
assert calls[0]["file_path"].endswith(".ai.en.vtt")
assert calls[1]["file_path"].endswith(".ai.zh.vtt")
assert (uploads_dir / calls[0]["file_path"].removeprefix("/uploads/")).read_text(encoding="utf-8").startswith("WEBVTT")
assert "你好" in (uploads_dir / calls[1]["file_path"].removeprefix("/uploads/")).read_text(encoding="utf-8")
def test_local_whisper_route_generates_only_english_subtitle(monkeypatch):
calls = []
monkeypatch.setattr(main, "get_video", lambda video_id: {"id": video_id, "videoUrl": "/uploads/videos/demo.mp4", "subtitles": {}})
monkeypatch.setattr(main, "upload_url_to_path", lambda value: Path("uploads/videos/demo.mp4"))
monkeypatch.setattr(main, "load_local_whisper_config", lambda: object())
monkeypatch.setattr(main, "transcribe_video_to_vtt", lambda video_path, config: "WEBVTT\n\n1\n00:00:00.000 --> 00:00:01.000\nHello.\n")
def fake_process_subtitles_with_ai(*args, **kwargs):
raise AssertionError("local whisper route should not call AI translation")
def fake_upsert_video_subtitle(video_id, **kwargs):
calls.append({"video_id": video_id, **kwargs})
monkeypatch.setattr(main, "process_subtitles_with_ai", fake_process_subtitles_with_ai)
monkeypatch.setattr(main, "upsert_video_subtitle", fake_upsert_video_subtitle)
result = main.api_generate_local_whisper_subtitles(7)
assert result["report"]["local_whisper_generated"] is True
assert result["report"]["english_count"] == 1
assert len(calls) == 1
assert calls[0]["video_id"] == 7
assert calls[0]["language_code"] == "en"
assert "subtitle_zh_content" not in calls[0]
if __name__ == "__main__":
patch = EnvPatch()
original_read_env_file = ai_config.read_env_file
ai_config.read_env_file = lambda path=ai_config.ENV_PATH: {}
try:
test_ai_status_route_reports_missing_key(patch)
patch.restore()
test_ai_test_route_rejects_missing_key(patch)
patch.restore()
test_admin_credentials_require_matching_env_values(patch)
patch.restore()
test_admin_credentials_reject_wrong_password(patch)
patch.restore()
test_admin_credentials_reject_missing_config(patch)
patch.restore()
test_ai_test_route_calls_model_client(patch)
patch.restore()
test_ai_test_route_reports_model_client_failure(patch)
patch.restore()
test_ai_subtitle_route_writes_processed_vtt_files(patch)
patch.restore()
test_local_whisper_route_generates_only_english_subtitle(patch)
finally:
patch.restore()
ai_config.read_env_file = original_read_env_file
+11
View File
@@ -0,0 +1,11 @@
import assert from "node:assert/strict";
import authHelpers from "../auth.js";
const { getLoginUrlForPath, isUnauthorizedStatus, shouldShowAdminEntry } = authHelpers;
assert.equal(getLoginUrlForPath("/study.html?video=2"), "./login.html?next=%2Fstudy.html%3Fvideo%3D2");
assert.equal(isUnauthorizedStatus(401), true);
assert.equal(isUnauthorizedStatus(403), false);
assert.equal(shouldShowAdminEntry({ role: "admin" }), true);
assert.equal(shouldShowAdminEntry({ role: "user" }), false);
assert.equal(shouldShowAdminEntry(null), false);
+105
View File
@@ -0,0 +1,105 @@
import tempfile
from pathlib import Path
import sys
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from backend import db
from backend.auth import create_auth_token, hash_password, verify_auth_token, verify_password
class TempDatabase:
def __enter__(self):
self.temp_dir = tempfile.TemporaryDirectory(ignore_cleanup_errors=True)
self.original = db.DATABASE_PATH
db.DATABASE_PATH = Path(self.temp_dir.name) / "test.sqlite"
db.initialize_database()
return db.DATABASE_PATH
def __exit__(self, exc_type, exc, tb):
db.DATABASE_PATH = self.original
self.temp_dir.cleanup()
def test_password_hash_roundtrip():
stored = hash_password("secret123")
assert stored != "secret123"
assert verify_password("secret123", stored) is True
assert verify_password("wrong", stored) is False
def test_auth_token_roundtrip_and_tamper_rejection():
token = create_auth_token({"username": "student", "role": "user", "userId": 1}, "secret")
payload = verify_auth_token(token, "secret")
assert payload["username"] == "student"
assert payload["role"] == "user"
assert verify_auth_token(token + "x", "secret") is None
def test_activation_code_registers_user_once():
with TempDatabase():
created = db.create_activation_codes(["SL-ABC123-DEF456-GHI789"], "admin")
assert created[0]["status"] == "unused"
user = db.register_user_with_activation(
username="student",
password_hash=hash_password("secret123"),
activation_code="SL-ABC123-DEF456-GHI789",
)
assert user["username"] == "student"
codes = db.list_activation_codes()
assert codes == []
try:
db.register_user_with_activation(
username="student2",
password_hash=hash_password("secret123"),
activation_code="SL-ABC123-DEF456-GHI789",
)
except ValueError as error:
assert str(error) == "activation_code_unavailable"
else:
raise AssertionError("used activation code should not register another user")
def test_initialize_database_removes_legacy_used_activation_codes():
with TempDatabase():
with db.get_connection() as connection:
cursor = connection.execute(
"""
INSERT INTO users (email, password_hash, display_name)
VALUES ('legacy-user', 'hash', 'legacy-user')
"""
)
connection.execute(
"""
INSERT INTO activation_codes (
code, created_by, used_by_user_id, used_at, status
)
VALUES ('SL-USED12-USED34-USED56', 'admin', ?, CURRENT_TIMESTAMP, 'used')
""",
(int(cursor.lastrowid),),
)
with db.get_connection() as connection:
count = connection.execute(
"SELECT COUNT(*) AS count FROM activation_codes WHERE status = 'used'"
).fetchone()["count"]
assert count == 1
db.initialize_database()
with db.get_connection() as connection:
count = connection.execute("SELECT COUNT(*) AS count FROM activation_codes").fetchone()["count"]
assert count == 0
if __name__ == "__main__":
test_password_hash_roundtrip()
test_auth_token_roundtrip_and_tamper_rejection()
test_activation_code_registers_user_once()
test_initialize_database_removes_legacy_used_activation_codes()
+208
View File
@@ -0,0 +1,208 @@
import sys
import tempfile
from pathlib import Path
from fastapi import HTTPException
from fastapi.security import HTTPAuthorizationCredentials
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from backend import db, main
class EnvPatch:
def __init__(self):
self.attributes = []
def setattr(self, target, name, value):
self.attributes.append((target, name, getattr(target, name)))
setattr(target, name, value)
def restore(self):
while self.attributes:
target, name, original = self.attributes.pop()
setattr(target, name, original)
class TempDatabase:
def __enter__(self):
self.temp_dir = tempfile.TemporaryDirectory(ignore_cleanup_errors=True)
self.original = db.DATABASE_PATH
db.DATABASE_PATH = Path(self.temp_dir.name) / "test.sqlite"
db.initialize_database()
return db.DATABASE_PATH
def __exit__(self, exc_type, exc, tb):
db.DATABASE_PATH = self.original
self.temp_dir.cleanup()
def configure_admin(monkeypatch):
monkeypatch.setattr(main, "get_config_value", lambda key, default="": {
"ADMIN_USERNAME": "admin",
"ADMIN_PASSWORD": "admin123",
"AUTH_SECRET": "test-secret",
}.get(key, default))
def test_admin_login_can_generate_activation_code(monkeypatch):
configure_admin(monkeypatch)
with TempDatabase():
login = main.api_auth_login(main.LoginRequest(username="admin", password="admin123"))
assert login["user"]["role"] == "admin"
bearer = HTTPAuthorizationCredentials(scheme="Bearer", credentials=login["token"])
admin = main.require_admin(credentials=None, bearer=bearer)
created = main.api_admin_create_activation_codes(
main.GenerateActivationCodesRequest(quantity=2),
admin=admin,
)
assert len(created["codes"]) == 2
assert created["codes"][0]["code"].startswith("SL-")
def test_activation_registration_login_and_reuse_rejection(monkeypatch):
configure_admin(monkeypatch)
with TempDatabase():
admin_login = main.api_auth_login(main.LoginRequest(username="admin", password="admin123"))
admin = main.require_admin(
credentials=None,
bearer=HTTPAuthorizationCredentials(scheme="Bearer", credentials=admin_login["token"]),
)
created = main.api_admin_create_activation_codes(
main.GenerateActivationCodesRequest(quantity=1),
admin=admin,
)
code = created["codes"][0]["code"]
registered = main.api_auth_register(main.RegisterRequest(
activationCode=code,
username="student",
password="secret123",
))
assert registered["user"]["username"] == "student"
assert registered["user"]["role"] == "user"
assert main.api_admin_activation_codes(admin=admin) == []
login = main.api_auth_login(main.LoginRequest(username="student", password="secret123"))
session = main.api_auth_session(main.require_session(
HTTPAuthorizationCredentials(scheme="Bearer", credentials=login["token"])
))
assert session["user"]["username"] == "student"
try:
main.api_auth_register(main.RegisterRequest(
activationCode=code,
username="student2",
password="secret123",
))
except HTTPException as error:
assert error.status_code == 400
else:
raise AssertionError("used activation code should be rejected")
def test_new_user_login_invalidates_previous_bearer_token(monkeypatch):
configure_admin(monkeypatch)
with TempDatabase():
db.create_activation_codes(["SL-ABC123-DEF456-GHI789"], "admin")
main.api_auth_register(main.RegisterRequest(
activationCode="SL-ABC123-DEF456-GHI789",
username="student",
password="secret123",
))
first_login = main.api_auth_login(main.LoginRequest(username="student", password="secret123"))
first_bearer = HTTPAuthorizationCredentials(scheme="Bearer", credentials=first_login["token"])
assert main.api_auth_session(main.require_session(first_bearer))["user"]["username"] == "student"
second_login = main.api_auth_login(main.LoginRequest(username="student", password="secret123"))
second_bearer = HTTPAuthorizationCredentials(scheme="Bearer", credentials=second_login["token"])
assert main.api_auth_session(main.require_session(second_bearer))["user"]["username"] == "student"
try:
main.require_session(first_bearer)
except HTTPException as error:
assert error.status_code == 401
else:
raise AssertionError("old bearer token should be invalid after a newer login")
def test_legacy_bearer_token_works_until_user_logs_in_again(monkeypatch):
configure_admin(monkeypatch)
with TempDatabase():
db.create_activation_codes(["SL-ABC123-DEF456-GHI789"], "admin")
registered = main.api_auth_register(main.RegisterRequest(
activationCode="SL-ABC123-DEF456-GHI789",
username="student",
password="secret123",
))
legacy_token = main.create_auth_token(
{"username": "student", "role": "user", "userId": registered["user"]["id"]},
main.get_token_secret(),
)
with db.get_connection() as connection:
connection.execute(
"UPDATE users SET session_token = NULL WHERE id = ?",
(registered["user"]["id"],),
)
legacy_bearer = HTTPAuthorizationCredentials(scheme="Bearer", credentials=legacy_token)
assert main.api_auth_session(main.require_session(legacy_bearer))["user"]["username"] == "student"
main.api_auth_login(main.LoginRequest(username="student", password="secret123"))
try:
main.require_session(legacy_bearer)
except HTTPException as error:
assert error.status_code == 401
else:
raise AssertionError("legacy token should expire after the account logs in again")
def test_normal_user_cannot_use_admin_dependency(monkeypatch):
configure_admin(monkeypatch)
with TempDatabase():
db.create_activation_codes(["SL-ABC123-DEF456-GHI789"], "admin")
registered = main.api_auth_register(main.RegisterRequest(
activationCode="SL-ABC123-DEF456-GHI789",
username="student",
password="secret123",
))
try:
main.require_admin(
credentials=None,
bearer=HTTPAuthorizationCredentials(scheme="Bearer", credentials=registered["token"]),
)
except HTTPException as error:
assert error.status_code == 401
else:
raise AssertionError("normal user token should not pass admin dependency")
if __name__ == "__main__":
patch = EnvPatch()
try:
configure_admin(patch)
test_admin_login_can_generate_activation_code(patch)
patch.restore()
configure_admin(patch)
test_activation_registration_login_and_reuse_rejection(patch)
patch.restore()
configure_admin(patch)
test_new_user_login_invalidates_previous_bearer_token(patch)
patch.restore()
configure_admin(patch)
test_legacy_bearer_token_works_until_user_logs_in_again(patch)
patch.restore()
configure_admin(patch)
test_normal_user_cannot_use_admin_dependency(patch)
finally:
patch.restore()
+62
View File
@@ -0,0 +1,62 @@
import sys
import tempfile
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from backend import db
class PatchDbPath:
def __init__(self, path):
self.path = path
self.original = db.DATABASE_PATH
def __enter__(self):
db.DATABASE_PATH = self.path
return self
def __exit__(self, exc_type, exc, tb):
db.DATABASE_PATH = self.original
def test_cover_url_round_trips_and_old_cover_is_cleaned():
with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as temp_dir:
database_path = Path(temp_dir) / "speaking_lab.sqlite"
with PatchDbPath(database_path):
db.initialize_database()
created = db.create_video(
title="Cover demo",
speaker="Teacher",
description="",
tags=["口语"],
video_url="/uploads/videos/demo.mp4",
cover_url="/uploads/images/cover-a.jpg",
subtitles=[],
)
assert created["coverUrl"] == "/uploads/images/cover-a.jpg"
assert db.get_video(int(created["id"]))["coverUrl"] == "/uploads/images/cover-a.jpg"
updated = db.update_video(
int(created["id"]),
title="Cover demo updated",
speaker="Teacher",
description="",
tags=["口语"],
video_url=None,
cover_url="/uploads/images/cover-b.jpg",
subtitles=[],
)
assert updated["video"]["coverUrl"] == "/uploads/images/cover-b.jpg"
assert "/uploads/images/cover-a.jpg" in updated["oldUploadPaths"]
deleted = db.delete_video(int(created["id"]))
assert "/uploads/images/cover-b.jpg" in deleted["uploadPaths"]
if __name__ == "__main__":
test_cover_url_round_trips_and_old_cover_is_cleaned()
+12
View File
@@ -0,0 +1,12 @@
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { fileURLToPath } from "node:url";
import { dirname, join } from "node:path";
const __dirname = dirname(fileURLToPath(import.meta.url));
const html = readFileSync(join(__dirname, "..", "index.html"), "utf8");
assert.equal(
html.includes('<a class="primary-link" href="./study.html">进入学习页</a>'),
false,
);
+31
View File
@@ -0,0 +1,31 @@
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
const __dirname = dirname(fileURLToPath(import.meta.url));
const css = readFileSync(join(__dirname, "..", "styles.css"), "utf8");
assert.match(
css,
/@media\s*\(max-width:\s*720px\)[\s\S]*\.home-topbar\s*\{[\s\S]*position:\s*static;/,
"mobile home topbar should not remain sticky and tall above the content",
);
assert.match(
css,
/@media\s*\(max-width:\s*720px\)[\s\S]*\.home-topbar\s+\.top-actions\s*\{[\s\S]*display:\s*grid;[\s\S]*grid-template-columns:\s*minmax\(0,\s*1fr\)\s+auto;/,
"mobile top actions should keep search and account controls compact",
);
assert.match(
css,
/@media\s*\(max-width:\s*720px\)[\s\S]*\.home-metrics\s*\{[\s\S]*grid-template-columns:\s*1fr;/,
"mobile dashboard metrics should use one readable column",
);
assert.match(
css,
/\.home-favorite\s*\{[\s\S]*min-width:\s*44px;[\s\S]*min-height:\s*44px;/,
"favorite buttons should meet mobile touch target sizing",
);
+155
View File
@@ -0,0 +1,155 @@
import sys
import tempfile
from pathlib import Path
from fastapi.security import HTTPAuthorizationCredentials
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from backend import db, main
from backend.auth import hash_password
class EnvPatch:
def __init__(self):
self.attributes = []
def setattr(self, target, name, value):
self.attributes.append((target, name, getattr(target, name)))
setattr(target, name, value)
def restore(self):
while self.attributes:
target, name, original = self.attributes.pop()
setattr(target, name, original)
class TempDatabase:
def __enter__(self):
self.temp_dir = tempfile.TemporaryDirectory(ignore_cleanup_errors=True)
self.original = db.DATABASE_PATH
db.DATABASE_PATH = Path(self.temp_dir.name) / "test.sqlite"
db.initialize_database()
return db.DATABASE_PATH
def __exit__(self, exc_type, exc, tb):
db.DATABASE_PATH = self.original
self.temp_dir.cleanup()
def configure_auth(monkeypatch):
monkeypatch.setattr(main, "get_config_value", lambda key, default="": {
"ADMIN_USERNAME": "admin",
"ADMIN_PASSWORD": "admin123",
"AUTH_SECRET": "test-secret",
}.get(key, default))
def create_student_session():
user = db.register_user_with_activation(
username="student",
password_hash=hash_password("secret123"),
activation_code="SL-ABC123-DEF456-GHI789",
)
login = main.api_auth_login(main.LoginRequest(username="student", password="secret123"))
return main.require_session(
HTTPAuthorizationCredentials(scheme="Bearer", credentials=login["token"])
), user
def create_video_record():
return db.create_video(
title="Lesson One",
speaker="Teacher",
description="",
tags=["口语"],
video_url="https://example.com/lesson-one.mp4",
subtitles=[],
)
def test_learning_progress_round_trips_for_logged_in_user(monkeypatch):
configure_auth(monkeypatch)
with TempDatabase():
db.create_activation_codes(["SL-ABC123-DEF456-GHI789"], "admin")
session, _user = create_student_session()
video = create_video_record()
saved = main.api_save_my_progress(
main.LearningStateRequest(
favorites=[str(video["id"])],
progress={
str(video["id"]): main.VideoProgressPayload(
currentTime=42.6,
activeLineIndex=3,
practicedLineIndexes=[0, 2, 2],
difficultLineIndexes=[1],
updatedAt="2026-06-14T10:00:00.000Z",
)
},
),
session=session,
)
loaded = main.api_get_my_progress(session=session)
assert saved == loaded
assert loaded["favorites"] == [str(video["id"])]
progress = loaded["progress"][str(video["id"])]
assert progress["currentTime"] == 42.6
assert progress["activeLineIndex"] == 3
assert progress["practicedLineIndexes"] == [0, 2]
assert progress["difficultLineIndexes"] == [1]
def test_learning_progress_save_replaces_removed_favorite_and_merges_progress(monkeypatch):
configure_auth(monkeypatch)
with TempDatabase():
db.create_activation_codes(["SL-ABC123-DEF456-GHI789"], "admin")
session, _user = create_student_session()
video = create_video_record()
main.api_save_my_progress(
main.LearningStateRequest(
favorites=[str(video["id"])],
progress={
str(video["id"]): main.VideoProgressPayload(
currentTime=10,
practicedLineIndexes=[0],
difficultLineIndexes=[2],
)
},
),
session=session,
)
loaded = main.api_save_my_progress(
main.LearningStateRequest(
favorites=[],
progress={
str(video["id"]): main.VideoProgressPayload(
currentTime=12,
practicedLineIndexes=[0, 1],
difficultLineIndexes=[],
)
},
),
session=session,
)
assert loaded["favorites"] == []
assert loaded["progress"][str(video["id"])]["currentTime"] == 12
assert loaded["progress"][str(video["id"])]["practicedLineIndexes"] == [0, 1]
assert loaded["progress"][str(video["id"])]["difficultLineIndexes"] == []
if __name__ == "__main__":
patch = EnvPatch()
try:
configure_auth(patch)
test_learning_progress_round_trips_for_logged_in_user(patch)
patch.restore()
configure_auth(patch)
test_learning_progress_save_replaces_removed_favorite_and_merges_progress(patch)
finally:
patch.restore()
+28
View File
@@ -0,0 +1,28 @@
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from backend.local_whisper import build_vtt_from_segments
def test_build_vtt_from_whisper_segments():
segments = [
{"start": 0.0, "end": 2.5, "text": "Hello world."},
{"start": 2.5, "end": 5.0, "text": "This is a test."},
]
assert build_vtt_from_segments(segments) == """WEBVTT
1
00:00:00.000 --> 00:00:02.500
Hello world.
2
00:00:02.500 --> 00:00:05.000
This is a test.
"""
if __name__ == "__main__":
test_build_vtt_from_whisper_segments()
+136
View File
@@ -0,0 +1,136 @@
import assert from "node:assert/strict";
import {
normalizePracticeAnswer,
comparePracticeAnswer,
getPracticeViewState,
getSubtitleModeConfig,
} from "../app.js";
assert.equal(normalizePracticeAnswer(" Hello, WORLD! "), "hello world");
assert.equal(normalizePracticeAnswer("I’m ready."), "im ready");
assert.equal(normalizePracticeAnswer("Are you ok? Yes!"), "are you ok yes");
assert.equal(normalizePracticeAnswer("Listen--then write"), "listen then write");
assert.deepEqual(comparePracticeAnswer("", "Good technology should help."), {
status: "empty",
isCorrect: false,
reference: "Good technology should help.",
message: "请输入答案后再核对。",
});
assert.deepEqual(comparePracticeAnswer("good technology should help", "Good technology should help."), {
status: "correct",
isCorrect: true,
reference: "Good technology should help.",
message: "完全匹配。",
});
assert.deepEqual(comparePracticeAnswer("Good technology should help!", "Good technology should help."), {
status: "correct",
isCorrect: true,
reference: "Good technology should help.",
message: "完全匹配。",
});
assert.deepEqual(comparePracticeAnswer("dont stop", "Don’t stop."), {
status: "correct",
isCorrect: true,
reference: "Don’t stop.",
message: "完全匹配。",
});
assert.deepEqual(comparePracticeAnswer("Good tools help.", "Good technology should help."), {
status: "incorrect",
isCorrect: false,
reference: "Good technology should help.",
message: "还不完全一致,参考答案如下。",
});
assert.deepEqual(comparePracticeAnswer("anything", ""), {
status: "missing-reference",
isCorrect: false,
reference: "",
message: "当前句没有可核对的英文参考。",
});
const cuePair = {
english: {
start: 0,
end: 3.5,
text: "Good technology should make people feel more capable.",
},
chinese: {
start: 0,
end: 3.5,
text: "好的技术应该让人感觉自己更有能力。",
},
};
assert.deepEqual(getPracticeViewState("bilingual", cuePair), {
mode: "bilingual",
label: "双语",
promptText: "Good technology should make people feel more capable.",
referenceText: "好的技术应该让人感觉自己更有能力。",
expectedText: "Good technology should make people feel more capable.",
inputVisible: false,
canCheck: false,
feedbackHint: "",
});
assert.deepEqual(getPracticeViewState("dictation", cuePair), {
mode: "dictation",
label: "听写",
promptText: "听音频,写出当前英文句子。",
referenceText: "",
expectedText: "Good technology should make people feel more capable.",
inputVisible: true,
canCheck: true,
feedbackHint: "",
});
assert.deepEqual(getPracticeViewState("translation", cuePair), {
mode: "translation",
label: "中译英",
promptText: "好的技术应该让人感觉自己更有能力。",
referenceText: "根据中文写出英文句子。",
expectedText: "Good technology should make people feel more capable.",
inputVisible: true,
canCheck: true,
feedbackHint: "",
});
assert.deepEqual(getPracticeViewState("translation", { english: cuePair.english, chinese: null }), {
mode: "translation",
label: "中译英",
promptText: "当前句没有中文字幕。",
referenceText: "根据中文写出英文句子。",
expectedText: "Good technology should make people feel more capable.",
inputVisible: true,
canCheck: true,
feedbackHint: "",
});
assert.deepEqual(getPracticeViewState("dictation", { english: null, chinese: cuePair.chinese }), {
mode: "dictation",
label: "听写",
promptText: "听音频,写出当前英文句子。",
referenceText: "",
expectedText: "",
inputVisible: true,
canCheck: false,
feedbackHint: "当前句没有可核对的英文参考。",
});
assert.deepEqual(getSubtitleModeConfig("dictation", { en: {}, zh: {} }), {
primaryCode: "en",
secondaryCode: "",
showSecondary: false,
message: "",
});
assert.deepEqual(getSubtitleModeConfig("translation", { en: {}, zh: {} }), {
primaryCode: "zh",
secondaryCode: "",
showSecondary: false,
message: "",
});
+55
View File
@@ -0,0 +1,55 @@
import assert from "node:assert/strict";
import progressSync from "../progress-sync.js";
const {
buildLearningStatePayload,
mergeLearningState,
normalizeRemoteLearningState,
} = progressSync;
const localUser = {
favorites: ["1"],
progress: {
"1": {
currentTime: 10,
activeLineIndex: 1,
practicedLineIndexes: [0],
difficultLineIndexes: [2],
updatedAt: "2026-06-14T08:00:00.000Z",
},
},
};
const remote = normalizeRemoteLearningState({
favorites: ["2"],
progress: {
"1": {
currentTime: 12,
activeLineIndex: 2,
practicedLineIndexes: [1],
difficultLineIndexes: [3],
updatedAt: "2026-06-14T09:00:00.000Z",
},
"2": {
currentTime: 4,
activeLineIndex: 0,
practicedLineIndexes: [],
difficultLineIndexes: [0],
},
},
});
assert.deepEqual(remote.favorites, ["2"]);
assert.deepEqual(remote.progress["1"].practicedLineIndexes, [1]);
const merged = mergeLearningState(localUser, remote);
assert.deepEqual(merged.favorites, ["1", "2"]);
assert.equal(merged.progress["1"].currentTime, 12);
assert.equal(merged.progress["1"].activeLineIndex, 2);
assert.deepEqual(merged.progress["1"].practicedLineIndexes, [0, 1]);
assert.deepEqual(merged.progress["1"].difficultLineIndexes, [2, 3]);
assert.deepEqual(merged.progress["2"].difficultLineIndexes, [0]);
const payload = buildLearningStatePayload(merged);
assert.deepEqual(payload.favorites, ["1", "2"]);
assert.deepEqual(payload.progress["1"].practicedLineIndexes, [0, 1]);
+134
View File
@@ -0,0 +1,134 @@
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from backend.subtitle_ai import process_subtitles_with_ai
class FakeClient:
def chat_json(self, system_prompt, user_payload):
assert "不要修改时间轴" in system_prompt
assert "start" not in user_payload["cues"][0]
assert "end" not in user_payload["cues"][0]
return {
"translations": [
{
"index": 1,
"start": "00:00:99.000",
"end": "00:00:99.999",
"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
assert "00:00:00.872 --> 00:00:04.959" in result["subtitle_en_content"]
assert "00:00:00.872 --> 00:00:04.959" in result["subtitle_zh_content"]
assert "timestamp_calibrated" not in result["report"]
assert "timestamp_offset_seconds" not in result["report"]
class SingleBatchClient:
def __init__(self):
self.calls = []
def chat_json(self, system_prompt, user_payload):
self.calls.append(user_payload)
return {
"translations": [
{"index": 3, "zh": "第三句"},
{"index": 1, "zh": "第一句"},
{"index": 2, "zh": "第二句"},
]
}
def test_process_subtitles_with_ai_translates_all_cues_by_default_and_matches_index():
raw = """WEBVTT
00:00:00.000 --> 00:00:01.000
One.
00:00:01.000 --> 00:00:02.000
Two.
00:00:02.000 --> 00:00:03.000
Three.
"""
client = SingleBatchClient()
result = process_subtitles_with_ai(raw, client)
assert len(client.calls) == 1
assert [cue["index"] for cue in client.calls[0]["cues"]] == [1, 2, 3]
assert "第一句" in result["subtitle_zh_content"]
assert "第二句" in result["subtitle_zh_content"]
assert "第三句" in result["subtitle_zh_content"]
assert result["subtitle_zh_content"].index("第一句") < result["subtitle_zh_content"].index("第二句")
assert result["subtitle_zh_content"].index("第二句") < result["subtitle_zh_content"].index("第三句")
assert result["report"]["translation_batches"] == 1
class MissingThenRepairClient:
def __init__(self):
self.calls = []
def chat_json(self, system_prompt, user_payload):
self.calls.append(user_payload)
indexes = [cue["index"] for cue in user_payload["cues"]]
if indexes == [1, 2, 3]:
return {
"translations": [
{"index": 1, "zh": "第一句"},
{"index": 3, "zh": "第三句"},
]
}
if indexes == [2]:
return {"translations": [{"index": 2, "zh": "第二句"}]}
raise AssertionError(f"unexpected retry indexes: {indexes}")
def test_process_subtitles_with_ai_repairs_missing_translation_indexes():
raw = """WEBVTT
00:00:00.000 --> 00:00:01.000
One.
00:00:01.000 --> 00:00:02.000
Two.
00:00:02.000 --> 00:00:03.000
Three.
"""
client = MissingThenRepairClient()
result = process_subtitles_with_ai(raw, client)
assert [[cue["index"] for cue in call["cues"]] for call in client.calls] == [[1, 2, 3], [2]]
assert "第一句" in result["subtitle_zh_content"]
assert "第二句" in result["subtitle_zh_content"]
assert "第三句" in result["subtitle_zh_content"]
assert result["report"]["translation_count"] == 3
if __name__ == "__main__":
test_process_subtitles_with_ai_returns_clean_en_and_zh_vtt()
test_process_subtitles_with_ai_translates_all_cues_by_default_and_matches_index()
test_process_subtitles_with_ai_repairs_missing_translation_indexes()
+48
View File
@@ -0,0 +1,48 @@
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
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
&nbsp;
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"
if __name__ == "__main__":
test_clean_english_subtitle_removes_empty_and_duplicate_cues()
test_build_vtt_outputs_numbered_blocks()
@@ -0,0 +1,25 @@
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
const __dirname = dirname(fileURLToPath(import.meta.url));
const css = readFileSync(join(__dirname, "..", "styles.css"), "utf8");
assert.match(
css,
/\.line-button\.is-practiced\s*\{[\s\S]*background:\s*#ecfdf3;[\s\S]*border-color:\s*#86efac;[\s\S]*box-shadow:\s*inset 3px 0 0 #16a34a;/,
"practiced transcript rows should use a clear green row highlight",
);
assert.match(
css,
/\.line-button\.is-difficult\s*\{[\s\S]*background:\s*#fffaf0;[\s\S]*box-shadow:\s*inset 3px 0 0 var\(--gold\);/,
"difficult transcript rows should keep the existing gold row highlight",
);
assert.doesNotMatch(
css,
/\.line-status-button\.practiced\.active\s*\{[\s\S]*#16a34a/,
"the stronger practiced color should belong to the transcript row, not the status button",
);
+31
View File
@@ -0,0 +1,31 @@
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
const __dirname = dirname(fileURLToPath(import.meta.url));
const css = readFileSync(join(__dirname, "..", "styles.css"), "utf8");
assert.match(
css,
/--font-sans:\s*Inter,\s*"Noto Sans SC",\s*"Microsoft YaHei UI",\s*"PingFang SC"/,
"global font stack should pair polished Latin and Chinese UI fonts",
);
assert.match(
css,
/body\s*\{[\s\S]*font-family:\s*var\(--font-sans\);[\s\S]*line-height:\s*1\.5;[\s\S]*text-rendering:\s*optimizeLegibility;[\s\S]*-webkit-font-smoothing:\s*antialiased;/,
"body should use the shared font stack with improved rendering",
);
assert.match(
css,
/\.brand h1\s*\{[\s\S]*font-weight:\s*760;[\s\S]*letter-spacing:\s*0;/,
"brand title should use a refined strong weight",
);
assert.match(
css,
/\.home-card-body h3\s*\{[\s\S]*font-weight:\s*760;[\s\S]*line-height:\s*1\.35;/,
"home card titles should be less heavy and easier to scan",
);