Initial speaking practice site
This commit is contained in:
commit
bcebeaef82
38 files changed
+10698
No files matched your search
@@ -0,0 +1,841 @@
|
||||
# Speaking Lab Admin Page Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** Move material management to a dedicated admin page with add and delete support, and show a small study-page admin entry only for local admin users.
|
||||
|
||||
**Architecture:** Keep the current local prototype auth model in `localStorage`. Add backend deletion helpers and a `DELETE /api/videos/{video_id}` endpoint, remove embedded admin UI from the study page, and add a separate static `admin.html` + `admin.js` page that uses the existing create endpoint plus the new delete endpoint.
|
||||
|
||||
**Tech Stack:** FastAPI, Python `sqlite3`, vanilla JavaScript, localStorage, local filesystem uploads.
|
||||
|
||||
---
|
||||
|
||||
## File Structure
|
||||
|
||||
- Modify `F:\ooo\speaking-practice-local\backend\db.py`: add a helper to collect uploaded file paths and delete a video row.
|
||||
- Modify `F:\ooo\speaking-practice-local\backend\main.py`: add safe uploaded-file deletion and `DELETE /api/videos/{video_id}`.
|
||||
- Modify `F:\ooo\speaking-practice-local\index.html`: remove embedded admin dock and add a hidden admin button beside the material rail heading.
|
||||
- Modify `F:\ooo\speaking-practice-local\app.js`: remove study-page admin form logic, show/hide the admin button for admins, and navigate to `admin.html`.
|
||||
- Add `F:\ooo\speaking-practice-local\admin.html`: standalone admin page.
|
||||
- Add `F:\ooo\speaking-practice-local\admin.js`: admin-only local gate, add material, list materials, delete material.
|
||||
- Modify `F:\ooo\speaking-practice-local\styles.css`: add styles for the rail admin button and admin page.
|
||||
- Modify `F:\ooo\speaking-practice-local\README.md`: document the dedicated admin page.
|
||||
|
||||
The project is not a git repository. Do not initialize git or commit during implementation.
|
||||
|
||||
---
|
||||
|
||||
### Task 1: Add Backend Delete Support
|
||||
|
||||
**Files:**
|
||||
- Modify: `F:\ooo\speaking-practice-local\backend\db.py`
|
||||
- Modify: `F:\ooo\speaking-practice-local\backend\main.py`
|
||||
|
||||
- [ ] **Step 1: Add database helper in `backend/db.py`**
|
||||
|
||||
Add this function after `get_video()`:
|
||||
|
||||
```python
|
||||
def delete_video(video_id: int) -> dict[str, object] | None:
|
||||
with get_connection() as connection:
|
||||
video_row = connection.execute(
|
||||
"""
|
||||
SELECT id, video_url
|
||||
FROM videos
|
||||
WHERE id = ?
|
||||
""",
|
||||
(video_id,),
|
||||
).fetchone()
|
||||
if video_row is None:
|
||||
return None
|
||||
|
||||
subtitle_rows = connection.execute(
|
||||
"""
|
||||
SELECT file_path
|
||||
FROM subtitles
|
||||
WHERE video_id = ?
|
||||
""",
|
||||
(video_id,),
|
||||
).fetchall()
|
||||
|
||||
upload_paths = []
|
||||
if video_row["video_url"]:
|
||||
upload_paths.append(video_row["video_url"])
|
||||
upload_paths.extend(row["file_path"] for row in subtitle_rows if row["file_path"])
|
||||
|
||||
connection.execute("DELETE FROM videos WHERE id = ?", (video_id,))
|
||||
|
||||
return {
|
||||
"deletedVideoId": video_id,
|
||||
"uploadPaths": upload_paths,
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Import `delete_video` in `backend/main.py`**
|
||||
|
||||
Update the `.db` import list to include:
|
||||
|
||||
```python
|
||||
delete_video,
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Add safe upload path resolution in `backend/main.py`**
|
||||
|
||||
Add this helper after `cleanup_saved_files()`:
|
||||
|
||||
```python
|
||||
def upload_url_to_path(value: str) -> Path | None:
|
||||
if not value.startswith("/uploads/"):
|
||||
return None
|
||||
|
||||
relative = value.removeprefix("/uploads/").replace("/", "\\")
|
||||
candidate = (UPLOADS_DIR / relative).resolve()
|
||||
uploads_root = UPLOADS_DIR.resolve()
|
||||
|
||||
try:
|
||||
candidate.relative_to(uploads_root)
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
return candidate
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Add delete endpoint in `backend/main.py`**
|
||||
|
||||
Add this after `api_create_video()`:
|
||||
|
||||
```python
|
||||
@app.delete("/api/videos/{video_id}")
|
||||
def api_delete_video(video_id: int) -> dict[str, object]:
|
||||
deleted = delete_video(video_id)
|
||||
if deleted is None:
|
||||
raise HTTPException(status_code=404, detail="视频不存在")
|
||||
|
||||
warnings: list[str] = []
|
||||
for upload_url in deleted["uploadPaths"]:
|
||||
path = upload_url_to_path(str(upload_url))
|
||||
if path is None:
|
||||
continue
|
||||
try:
|
||||
path.unlink(missing_ok=True)
|
||||
except OSError:
|
||||
warnings.append(f"无法删除文件: {path}")
|
||||
|
||||
return {
|
||||
"ok": True,
|
||||
"deletedVideoId": deleted["deletedVideoId"],
|
||||
"warnings": warnings,
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 5: Run backend checks**
|
||||
|
||||
Run:
|
||||
|
||||
```powershell
|
||||
python -m py_compile backend\main.py backend\db.py
|
||||
python -c "from backend.main import app; print([route.path for route in app.routes if route.path.startswith('/api/videos')])"
|
||||
```
|
||||
|
||||
Expected:
|
||||
|
||||
- compile command exits with no output
|
||||
- output includes `/api/videos/{video_id}` for both GET and DELETE route registrations
|
||||
|
||||
---
|
||||
|
||||
### Task 2: Clean Study Page And Add Admin Entry
|
||||
|
||||
**Files:**
|
||||
- Modify: `F:\ooo\speaking-practice-local\index.html`
|
||||
- Modify: `F:\ooo\speaking-practice-local\app.js`
|
||||
|
||||
- [ ] **Step 1: Add admin button beside material heading**
|
||||
|
||||
In `index.html`, replace:
|
||||
|
||||
```html
|
||||
<div class="rail-heading">
|
||||
<strong>素材</strong>
|
||||
<span id="videoCount">0</span>
|
||||
</div>
|
||||
```
|
||||
|
||||
with:
|
||||
|
||||
```html
|
||||
<div class="rail-heading">
|
||||
<div class="rail-title">
|
||||
<strong>素材</strong>
|
||||
<button id="adminEntryBtn" class="icon-button admin-entry" type="button" title="后台管理" hidden>管理</button>
|
||||
</div>
|
||||
<span id="videoCount">0</span>
|
||||
</div>
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Remove embedded admin dock**
|
||||
|
||||
Delete the entire `<aside class="admin-dock">...</aside>` block from `index.html`.
|
||||
|
||||
- [ ] **Step 3: Update element references in `app.js`**
|
||||
|
||||
In the `els` object:
|
||||
|
||||
Add:
|
||||
|
||||
```javascript
|
||||
adminEntryBtn: document.querySelector("#adminEntryBtn"),
|
||||
```
|
||||
|
||||
Remove these entries:
|
||||
|
||||
```javascript
|
||||
adminForm: document.querySelector("#adminForm"),
|
||||
adminTitle: document.querySelector("#adminTitle"),
|
||||
adminSpeaker: document.querySelector("#adminSpeaker"),
|
||||
adminDescription: document.querySelector("#adminDescription"),
|
||||
adminTags: document.querySelector("#adminTags"),
|
||||
adminVideoFile: document.querySelector("#adminVideoFile"),
|
||||
adminVideoUrl: document.querySelector("#adminVideoUrl"),
|
||||
adminSubtitleEn: document.querySelector("#adminSubtitleEn"),
|
||||
adminSubtitleZh: document.querySelector("#adminSubtitleZh"),
|
||||
updateCurrentBtn: document.querySelector("#updateCurrentBtn"),
|
||||
adminStatus: document.querySelector("#adminStatus"),
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Update events in `app.js`**
|
||||
|
||||
Remove:
|
||||
|
||||
```javascript
|
||||
els.adminForm.addEventListener("submit", addVideoFromAdmin);
|
||||
els.updateCurrentBtn.addEventListener("click", updateCurrentVideoInfo);
|
||||
```
|
||||
|
||||
Add:
|
||||
|
||||
```javascript
|
||||
els.adminEntryBtn.addEventListener("click", () => {
|
||||
window.location.href = "admin.html";
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 5: Replace `renderAdminAccess()` in `app.js`**
|
||||
|
||||
Replace the existing function with:
|
||||
|
||||
```javascript
|
||||
function renderAdminAccess() {
|
||||
const user = getCurrentUser();
|
||||
const isAdmin = user?.role === "admin";
|
||||
els.adminEntryBtn.hidden = !isAdmin;
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 6: Remove study-page admin functions in `app.js`**
|
||||
|
||||
Delete these functions completely:
|
||||
|
||||
```javascript
|
||||
async function addVideoFromAdmin(event) { ... }
|
||||
function fillAdminForm(video) { ... }
|
||||
function updateCurrentVideoInfo() { ... }
|
||||
```
|
||||
|
||||
Remove the call to `fillAdminForm(video);` from `selectVideo()`.
|
||||
|
||||
- [ ] **Step 7: Run frontend syntax check**
|
||||
|
||||
Run:
|
||||
|
||||
```powershell
|
||||
node --check app.js
|
||||
```
|
||||
|
||||
Expected: no output, exit code 0.
|
||||
|
||||
---
|
||||
|
||||
### Task 3: Add Standalone Admin Page
|
||||
|
||||
**Files:**
|
||||
- Add: `F:\ooo\speaking-practice-local\admin.html`
|
||||
- Add: `F:\ooo\speaking-practice-local\admin.js`
|
||||
|
||||
- [ ] **Step 1: Create `admin.html`**
|
||||
|
||||
Create the file:
|
||||
|
||||
```html
|
||||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>Speaking Lab 后台管理</title>
|
||||
<link rel="stylesheet" href="./styles.css">
|
||||
</head>
|
||||
<body class="admin-page">
|
||||
<header class="admin-topbar">
|
||||
<div>
|
||||
<h1>后台管理</h1>
|
||||
<p id="adminIdentity">请先使用管理员账号登录。</p>
|
||||
</div>
|
||||
<a class="secondary-action" href="./index.html">返回学习页</a>
|
||||
</header>
|
||||
|
||||
<main id="adminLocked" class="admin-locked" hidden>
|
||||
<h2>需要管理员账号</h2>
|
||||
<p>请返回学习页,使用邮箱包含 admin 的账号登录后再进入后台。</p>
|
||||
<a class="primary-link" href="./index.html">去登录</a>
|
||||
</main>
|
||||
|
||||
<main id="adminContent" class="admin-shell" hidden>
|
||||
<section class="admin-panel">
|
||||
<h2>添加素材</h2>
|
||||
<form id="adminCreateForm" class="admin-create-form">
|
||||
<input id="adminTitle" type="text" placeholder="视频标题" required>
|
||||
<input id="adminSpeaker" type="text" placeholder="演讲者 / 片段来源">
|
||||
<textarea id="adminDescription" placeholder="简介"></textarea>
|
||||
<input id="adminTags" type="text" placeholder="标签,用逗号分隔,如 科技,设计">
|
||||
<label class="file-input">
|
||||
<span>选择视频文件</span>
|
||||
<input id="adminVideoFile" type="file" accept="video/*">
|
||||
</label>
|
||||
<input id="adminVideoUrl" type="url" placeholder="或填写视频 / HLS 地址">
|
||||
<label class="file-input">
|
||||
<span>英文字幕 .srt/.vtt</span>
|
||||
<input id="adminSubtitleEn" type="file" accept=".srt,.vtt,text/vtt,text/plain">
|
||||
</label>
|
||||
<label class="file-input">
|
||||
<span>中文字幕 .srt/.vtt</span>
|
||||
<input id="adminSubtitleZh" type="file" accept=".srt,.vtt,text/vtt,text/plain">
|
||||
</label>
|
||||
<button type="submit">添加到视频库</button>
|
||||
</form>
|
||||
</section>
|
||||
|
||||
<section class="admin-panel">
|
||||
<div class="admin-list-heading">
|
||||
<h2>素材列表</h2>
|
||||
<button id="refreshVideosBtn" class="secondary-action" type="button">刷新</button>
|
||||
</div>
|
||||
<div id="adminMessage" class="admin-message" hidden></div>
|
||||
<div id="adminVideoList" class="admin-video-list"></div>
|
||||
</section>
|
||||
</main>
|
||||
|
||||
<script src="./admin.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Create `admin.js`**
|
||||
|
||||
Create the file:
|
||||
|
||||
```javascript
|
||||
const STORAGE_KEY = "speaking-lab-state-v1";
|
||||
|
||||
const els = {
|
||||
identity: document.querySelector("#adminIdentity"),
|
||||
locked: document.querySelector("#adminLocked"),
|
||||
content: document.querySelector("#adminContent"),
|
||||
form: document.querySelector("#adminCreateForm"),
|
||||
title: document.querySelector("#adminTitle"),
|
||||
speaker: document.querySelector("#adminSpeaker"),
|
||||
description: document.querySelector("#adminDescription"),
|
||||
tags: document.querySelector("#adminTags"),
|
||||
videoFile: document.querySelector("#adminVideoFile"),
|
||||
videoUrl: document.querySelector("#adminVideoUrl"),
|
||||
subtitleEn: document.querySelector("#adminSubtitleEn"),
|
||||
subtitleZh: document.querySelector("#adminSubtitleZh"),
|
||||
refreshBtn: document.querySelector("#refreshVideosBtn"),
|
||||
message: document.querySelector("#adminMessage"),
|
||||
videoList: document.querySelector("#adminVideoList"),
|
||||
};
|
||||
|
||||
let videos = [];
|
||||
|
||||
initializeAdmin();
|
||||
|
||||
function loadState() {
|
||||
try {
|
||||
const saved = JSON.parse(localStorage.getItem(STORAGE_KEY) || "{}");
|
||||
return {
|
||||
users: Array.isArray(saved.users) ? saved.users : [],
|
||||
currentUserId: saved.currentUserId || null,
|
||||
};
|
||||
} catch {
|
||||
return { users: [], currentUserId: null };
|
||||
}
|
||||
}
|
||||
|
||||
function getCurrentUser() {
|
||||
const state = loadState();
|
||||
return state.users.find((user) => user.id === state.currentUserId) || null;
|
||||
}
|
||||
|
||||
function isAdmin(user) {
|
||||
return user?.role === "admin" || user?.email?.includes("admin");
|
||||
}
|
||||
|
||||
async function apiRequest(path, options = {}) {
|
||||
const response = await fetch(path, options);
|
||||
if (!response.ok) {
|
||||
let message = "请求失败,请重试。";
|
||||
try {
|
||||
const payload = await response.json();
|
||||
message = payload.detail || message;
|
||||
} catch {
|
||||
message = response.statusText || message;
|
||||
}
|
||||
throw new Error(message);
|
||||
}
|
||||
return response.json();
|
||||
}
|
||||
|
||||
function initializeAdmin() {
|
||||
const user = getCurrentUser();
|
||||
if (!isAdmin(user)) {
|
||||
els.identity.textContent = "未登录管理员账号";
|
||||
els.locked.hidden = false;
|
||||
els.content.hidden = true;
|
||||
return;
|
||||
}
|
||||
|
||||
els.identity.textContent = `${user.email} · 管理员`;
|
||||
els.locked.hidden = true;
|
||||
els.content.hidden = false;
|
||||
|
||||
els.form.addEventListener("submit", addVideo);
|
||||
els.refreshBtn.addEventListener("click", loadVideos);
|
||||
loadVideos();
|
||||
}
|
||||
|
||||
function showMessage(text, isError = false) {
|
||||
els.message.hidden = false;
|
||||
els.message.textContent = text;
|
||||
els.message.classList.toggle("error", isError);
|
||||
}
|
||||
|
||||
function clearMessage() {
|
||||
els.message.hidden = true;
|
||||
els.message.textContent = "";
|
||||
els.message.classList.remove("error");
|
||||
}
|
||||
|
||||
async function loadVideos() {
|
||||
clearMessage();
|
||||
try {
|
||||
videos = await apiRequest("/api/videos");
|
||||
renderVideos();
|
||||
} catch (error) {
|
||||
showMessage(error.message || "素材加载失败。", true);
|
||||
}
|
||||
}
|
||||
|
||||
function renderVideos() {
|
||||
els.videoList.innerHTML = "";
|
||||
if (!videos.length) {
|
||||
els.videoList.innerHTML = `<div class="empty-state">还没有素材。</div>`;
|
||||
return;
|
||||
}
|
||||
|
||||
const fragment = document.createDocumentFragment();
|
||||
videos.forEach((video) => {
|
||||
const item = document.createElement("article");
|
||||
item.className = "admin-video-item";
|
||||
const subtitleCodes = Object.keys(video.subtitles || {});
|
||||
item.innerHTML = `
|
||||
<div>
|
||||
<h3></h3>
|
||||
<p class="admin-video-meta"></p>
|
||||
<p class="admin-video-subtitles"></p>
|
||||
</div>
|
||||
<button class="danger-action" type="button">删除</button>
|
||||
`;
|
||||
item.querySelector("h3").textContent = video.title || "Untitled";
|
||||
item.querySelector(".admin-video-meta").textContent = [
|
||||
video.speaker || "Unknown",
|
||||
Array.isArray(video.tags) ? video.tags.join(" / ") : "未分类",
|
||||
video.sourceType === "url" ? "链接" : "本地文件",
|
||||
].join(" · ");
|
||||
item.querySelector(".admin-video-subtitles").textContent = subtitleCodes.length
|
||||
? `字幕:${subtitleCodes.join(" / ")}`
|
||||
: "字幕:无";
|
||||
item.querySelector(".danger-action").addEventListener("click", () => deleteVideo(video));
|
||||
fragment.appendChild(item);
|
||||
});
|
||||
els.videoList.appendChild(fragment);
|
||||
}
|
||||
|
||||
async function addVideo(event) {
|
||||
event.preventDefault();
|
||||
clearMessage();
|
||||
|
||||
const title = els.title.value.trim();
|
||||
if (!title) {
|
||||
showMessage("标题不能为空", true);
|
||||
return;
|
||||
}
|
||||
|
||||
const submitButton = els.form.querySelector('button[type="submit"]');
|
||||
const previousText = submitButton.textContent;
|
||||
submitButton.disabled = true;
|
||||
submitButton.textContent = "正在添加...";
|
||||
|
||||
const formData = new FormData();
|
||||
formData.append("title", title);
|
||||
formData.append("speaker", els.speaker.value.trim());
|
||||
formData.append("description", els.description.value.trim());
|
||||
formData.append("tags", els.tags.value.trim());
|
||||
formData.append("video_url", els.videoUrl.value.trim());
|
||||
|
||||
if (els.videoFile.files?.[0]) formData.append("video_file", els.videoFile.files[0]);
|
||||
if (els.subtitleEn.files?.[0]) formData.append("subtitle_en", els.subtitleEn.files[0]);
|
||||
if (els.subtitleZh.files?.[0]) formData.append("subtitle_zh", els.subtitleZh.files[0]);
|
||||
|
||||
try {
|
||||
await apiRequest("/api/videos", {
|
||||
method: "POST",
|
||||
body: formData,
|
||||
});
|
||||
els.form.reset();
|
||||
showMessage("素材已添加。");
|
||||
await loadVideos();
|
||||
} catch (error) {
|
||||
showMessage(error.message || "添加素材失败。", true);
|
||||
} finally {
|
||||
submitButton.disabled = false;
|
||||
submitButton.textContent = previousText;
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteVideo(video) {
|
||||
const confirmed = window.confirm("确定删除这个素材吗?此操作不可恢复。");
|
||||
if (!confirmed) return;
|
||||
|
||||
clearMessage();
|
||||
try {
|
||||
const result = await apiRequest(`/api/videos/${video.id}`, {
|
||||
method: "DELETE",
|
||||
});
|
||||
videos = videos.filter((item) => String(item.id) !== String(video.id));
|
||||
renderVideos();
|
||||
const warningText = Array.isArray(result.warnings) && result.warnings.length
|
||||
? `素材已删除,但有文件未能删除:${result.warnings.join(";")}`
|
||||
: "素材已删除。";
|
||||
showMessage(warningText, Boolean(result.warnings?.length));
|
||||
} catch (error) {
|
||||
showMessage(error.message || "删除素材失败。", true);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Run admin script syntax check**
|
||||
|
||||
Run:
|
||||
|
||||
```powershell
|
||||
node --check admin.js
|
||||
```
|
||||
|
||||
Expected: no output, exit code 0.
|
||||
|
||||
---
|
||||
|
||||
### Task 4: Add Styles For Admin Entry And Page
|
||||
|
||||
**Files:**
|
||||
- Modify: `F:\ooo\speaking-practice-local\styles.css`
|
||||
|
||||
- [ ] **Step 1: Add rail admin button styles**
|
||||
|
||||
Add these styles near the existing rail/list styles:
|
||||
|
||||
```css
|
||||
.rail-title {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.icon-button.admin-entry {
|
||||
border: 1px solid var(--border);
|
||||
background: var(--surface);
|
||||
color: var(--muted);
|
||||
border-radius: 6px;
|
||||
padding: 4px 8px;
|
||||
font-size: 12px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.icon-button.admin-entry:hover {
|
||||
color: var(--text);
|
||||
border-color: var(--accent);
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Add admin page styles**
|
||||
|
||||
Append:
|
||||
|
||||
```css
|
||||
.admin-page {
|
||||
min-height: 100vh;
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
.admin-topbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 16px;
|
||||
padding: 18px 24px;
|
||||
border-bottom: 1px solid var(--border);
|
||||
background: var(--surface);
|
||||
}
|
||||
|
||||
.admin-topbar h1 {
|
||||
margin: 0;
|
||||
font-size: 22px;
|
||||
}
|
||||
|
||||
.admin-topbar p {
|
||||
margin: 4px 0 0;
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.admin-shell {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(320px, 420px) minmax(0, 1fr);
|
||||
gap: 16px;
|
||||
padding: 16px 24px 32px;
|
||||
}
|
||||
|
||||
.admin-panel,
|
||||
.admin-locked {
|
||||
background: var(--surface);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
padding: 16px;
|
||||
}
|
||||
|
||||
.admin-locked {
|
||||
max-width: 520px;
|
||||
margin: 48px auto;
|
||||
}
|
||||
|
||||
.admin-create-form {
|
||||
display: grid;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.admin-create-form input,
|
||||
.admin-create-form textarea {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.admin-list-heading {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.admin-message {
|
||||
margin: 12px 0;
|
||||
padding: 10px 12px;
|
||||
border-radius: 6px;
|
||||
background: #ecfdf5;
|
||||
color: #047857;
|
||||
}
|
||||
|
||||
.admin-message.error {
|
||||
background: #fef2f2;
|
||||
color: #b91c1c;
|
||||
}
|
||||
|
||||
.admin-video-list {
|
||||
display: grid;
|
||||
gap: 10px;
|
||||
margin-top: 12px;
|
||||
}
|
||||
|
||||
.admin-video-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
padding: 12px;
|
||||
background: var(--bg);
|
||||
}
|
||||
|
||||
.admin-video-item h3 {
|
||||
margin: 0 0 6px;
|
||||
font-size: 16px;
|
||||
}
|
||||
|
||||
.admin-video-meta,
|
||||
.admin-video-subtitles {
|
||||
margin: 0;
|
||||
color: var(--muted);
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.danger-action {
|
||||
border: 1px solid #fecaca;
|
||||
background: #fff1f2;
|
||||
color: #be123c;
|
||||
border-radius: 6px;
|
||||
padding: 8px 12px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.primary-link,
|
||||
.secondary-action {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
min-height: 36px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 6px;
|
||||
padding: 0 12px;
|
||||
color: var(--text);
|
||||
text-decoration: none;
|
||||
background: var(--surface);
|
||||
}
|
||||
|
||||
@media (max-width: 900px) {
|
||||
.admin-shell {
|
||||
grid-template-columns: 1fr;
|
||||
padding: 12px;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Run syntax smoke checks**
|
||||
|
||||
Run:
|
||||
|
||||
```powershell
|
||||
node --check app.js
|
||||
node --check admin.js
|
||||
```
|
||||
|
||||
Expected: both pass with no output.
|
||||
|
||||
---
|
||||
|
||||
### Task 5: Document And Verify
|
||||
|
||||
**Files:**
|
||||
- Modify: `F:\ooo\speaking-practice-local\README.md`
|
||||
|
||||
- [ ] **Step 1: Update README**
|
||||
|
||||
Add this section:
|
||||
|
||||
````markdown
|
||||
## Admin Page
|
||||
|
||||
Content management is handled on a separate local admin page:
|
||||
|
||||
```text
|
||||
http://127.0.0.1:8000/admin.html
|
||||
```
|
||||
|
||||
In this prototype, an admin is any local user whose email contains `admin`.
|
||||
After logging in as an admin on the study page, a small `管理` button appears
|
||||
beside the `素材` heading. The admin page supports adding and deleting
|
||||
materials. Editing and subtitle replacement are planned for later.
|
||||
```
|
||||
````
|
||||
|
||||
- [ ] **Step 2: Run static checks**
|
||||
|
||||
Run:
|
||||
|
||||
```powershell
|
||||
python -m py_compile backend\main.py backend\db.py
|
||||
node --check app.js
|
||||
node --check admin.js
|
||||
```
|
||||
|
||||
Expected: no output, exit code 0.
|
||||
|
||||
- [ ] **Step 3: Start the dev server**
|
||||
|
||||
Run:
|
||||
|
||||
```powershell
|
||||
python -m uvicorn backend.main:app --reload --host 127.0.0.1 --port 8000
|
||||
```
|
||||
|
||||
Expected output includes `Uvicorn running on http://127.0.0.1:8000`.
|
||||
|
||||
- [ ] **Step 4: Verify backend delete endpoint**
|
||||
|
||||
Create a temporary URL video through the API, then delete it:
|
||||
|
||||
```powershell
|
||||
$created = curl.exe -s -X POST http://127.0.0.1:8000/api/videos `
|
||||
-F "title=Delete Smoke Test" `
|
||||
-F "video_url=https://example.com/delete-smoke.mp4" | ConvertFrom-Json
|
||||
|
||||
Invoke-RestMethod -Method Delete "http://127.0.0.1:8000/api/videos/$($created.id)"
|
||||
```
|
||||
|
||||
Expected delete response:
|
||||
|
||||
```text
|
||||
ok deletedVideoId warnings
|
||||
-- -------------- --------
|
||||
True <id> {}
|
||||
```
|
||||
|
||||
- [ ] **Step 5: Verify pages**
|
||||
|
||||
Open:
|
||||
|
||||
```text
|
||||
http://127.0.0.1:8000
|
||||
http://127.0.0.1:8000/admin.html
|
||||
http://127.0.0.1:8000/docs
|
||||
```
|
||||
|
||||
Expected:
|
||||
|
||||
- Normal user does not see the `管理` button beside `素材`.
|
||||
- Admin user sees the `管理` button.
|
||||
- `admin.html` shows locked state when not logged in as admin.
|
||||
- `admin.html` shows add form and material list when logged in as admin.
|
||||
- `/docs` includes `DELETE /api/videos/{video_id}`.
|
||||
|
||||
---
|
||||
|
||||
## Self-Review
|
||||
|
||||
Spec coverage:
|
||||
|
||||
- Dedicated admin page: Task 3.
|
||||
- Admin-only study-page entry: Task 2.
|
||||
- Remove embedded admin dock: Task 2.
|
||||
- Add material from admin page: Task 3.
|
||||
- Delete material from admin page: Tasks 1 and 3.
|
||||
- Safe local file deletion: Task 1.
|
||||
- Documentation and verification: Task 5.
|
||||
|
||||
Placeholder scan:
|
||||
|
||||
- No placeholder markers or unspecified implementation steps.
|
||||
|
||||
Type consistency:
|
||||
|
||||
- Backend delete response uses `deletedVideoId` and `warnings`.
|
||||
- Admin frontend reads `video.id`, `video.sourceType`, `video.subtitles`, and the existing backend list shape.
|
||||
- Local admin rule reuses `speaking-lab-state-v1`.
|
||||
@@ -0,0 +1,808 @@
|
||||
# Speaking Lab Content Library Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** Build the first real content-library slice so admins can add videos with uploaded files or URLs plus English/Chinese subtitles, and the library persists in SQLite after refresh.
|
||||
|
||||
**Architecture:** Keep the current FastAPI + SQLite backend and vanilla frontend. Add a small backend content-library module for database serialization, file validation, and multipart uploads, then switch the frontend video library from browser-only storage to `/api/videos`.
|
||||
|
||||
**Tech Stack:** FastAPI, Python `sqlite3`, vanilla JavaScript, browser `FormData`, local filesystem uploads.
|
||||
|
||||
---
|
||||
|
||||
## File Structure
|
||||
|
||||
- Modify `F:\ooo\speaking-practice-local\backend\db.py`: add helpers for video/subtitle inserts and video serialization.
|
||||
- Modify `F:\ooo\speaking-practice-local\backend\main.py`: mount uploads, add `GET /api/videos`, `GET /api/videos/{video_id}`, and `POST /api/videos`.
|
||||
- Modify `F:\ooo\speaking-practice-local\app.js`: load videos from the API, submit admin uploads with `FormData`, normalize backend subtitle content into existing cue objects, and keep localStorage only for user/session state.
|
||||
- Modify `F:\ooo\speaking-practice-local\README.md`: document the new content-library behavior and manual verification.
|
||||
|
||||
The project currently has no test runner or git repository in `speaking-practice-local`. Use focused manual and API verification in this plan. If the project is later initialized as a git repository, commit after each completed task using the suggested commit messages.
|
||||
|
||||
---
|
||||
|
||||
### Task 1: Add Backend Video Persistence Helpers
|
||||
|
||||
**Files:**
|
||||
- Modify: `F:\ooo\speaking-practice-local\backend\db.py`
|
||||
|
||||
- [ ] **Step 1: Add imports and helper functions**
|
||||
|
||||
Add these imports near the top:
|
||||
|
||||
```python
|
||||
import json
|
||||
```
|
||||
|
||||
Add these helpers after `initialize_database()`:
|
||||
|
||||
```python
|
||||
def parse_tags(tags_text: str | None) -> list[str]:
|
||||
tags = [
|
||||
tag.strip()
|
||||
for tag in (tags_text or "").replace(",", ",").split(",")
|
||||
if tag.strip()
|
||||
]
|
||||
return tags or ["未分类"]
|
||||
|
||||
|
||||
def row_to_video(row: sqlite3.Row, subtitle_rows: list[sqlite3.Row]) -> dict[str, object]:
|
||||
subtitles: dict[str, dict[str, str]] = {}
|
||||
for subtitle in subtitle_rows:
|
||||
subtitles[subtitle["language_code"]] = {
|
||||
"languageName": subtitle["language_name"] or subtitle["language_code"],
|
||||
"format": subtitle["format"],
|
||||
"filePath": subtitle["file_path"],
|
||||
"content": subtitle["content"] or "",
|
||||
}
|
||||
|
||||
try:
|
||||
tags = json.loads(row["tags"] or "[]")
|
||||
except json.JSONDecodeError:
|
||||
tags = parse_tags(row["tags"])
|
||||
|
||||
return {
|
||||
"id": row["id"],
|
||||
"title": row["title"],
|
||||
"speaker": row["speaker"] or "Unknown",
|
||||
"description": row["description"] or "",
|
||||
"tags": tags if isinstance(tags, list) and tags else ["未分类"],
|
||||
"duration": row["duration_seconds"] or 0,
|
||||
"videoUrl": row["video_url"] or "",
|
||||
"sourceType": "url" if str(row["video_url"] or "").startswith(("http://", "https://")) else "local-file",
|
||||
"subtitles": subtitles,
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Add insert and read helpers**
|
||||
|
||||
Add these functions after `row_to_video()`:
|
||||
|
||||
```python
|
||||
def create_video(
|
||||
*,
|
||||
title: str,
|
||||
speaker: str | None,
|
||||
description: str | None,
|
||||
tags: list[str],
|
||||
video_url: str,
|
||||
subtitles: list[dict[str, str]],
|
||||
) -> dict[str, object]:
|
||||
with get_connection() as connection:
|
||||
cursor = connection.execute(
|
||||
"""
|
||||
INSERT INTO videos (
|
||||
title, speaker, description, tags, video_url, status
|
||||
)
|
||||
VALUES (?, ?, ?, ?, ?, 'published')
|
||||
""",
|
||||
(
|
||||
title,
|
||||
speaker or "Unknown",
|
||||
description or "",
|
||||
json.dumps(tags, ensure_ascii=False),
|
||||
video_url,
|
||||
),
|
||||
)
|
||||
video_id = int(cursor.lastrowid)
|
||||
|
||||
for subtitle in subtitles:
|
||||
connection.execute(
|
||||
"""
|
||||
INSERT INTO subtitles (
|
||||
video_id, language_code, language_name, format, file_path, content
|
||||
)
|
||||
VALUES (?, ?, ?, ?, ?, ?)
|
||||
""",
|
||||
(
|
||||
video_id,
|
||||
subtitle["language_code"],
|
||||
subtitle["language_name"],
|
||||
subtitle["format"],
|
||||
subtitle["file_path"],
|
||||
subtitle["content"],
|
||||
),
|
||||
)
|
||||
|
||||
video = get_video(video_id)
|
||||
if video is None:
|
||||
raise RuntimeError("Created video could not be loaded")
|
||||
return video
|
||||
|
||||
|
||||
def list_videos() -> list[dict[str, object]]:
|
||||
with get_connection() as connection:
|
||||
video_rows = connection.execute(
|
||||
"""
|
||||
SELECT *
|
||||
FROM videos
|
||||
WHERE status = 'published'
|
||||
ORDER BY created_at DESC, id DESC
|
||||
"""
|
||||
).fetchall()
|
||||
subtitle_rows = connection.execute(
|
||||
"""
|
||||
SELECT *
|
||||
FROM subtitles
|
||||
ORDER BY id ASC
|
||||
"""
|
||||
).fetchall()
|
||||
|
||||
subtitles_by_video: dict[int, list[sqlite3.Row]] = {}
|
||||
for subtitle in subtitle_rows:
|
||||
subtitles_by_video.setdefault(int(subtitle["video_id"]), []).append(subtitle)
|
||||
|
||||
return [
|
||||
row_to_video(row, subtitles_by_video.get(int(row["id"]), []))
|
||||
for row in video_rows
|
||||
]
|
||||
|
||||
|
||||
def get_video(video_id: int) -> dict[str, object] | None:
|
||||
with get_connection() as connection:
|
||||
row = connection.execute(
|
||||
"""
|
||||
SELECT *
|
||||
FROM videos
|
||||
WHERE id = ? AND status = 'published'
|
||||
""",
|
||||
(video_id,),
|
||||
).fetchone()
|
||||
if row is None:
|
||||
return None
|
||||
|
||||
subtitle_rows = connection.execute(
|
||||
"""
|
||||
SELECT *
|
||||
FROM subtitles
|
||||
WHERE video_id = ?
|
||||
ORDER BY id ASC
|
||||
""",
|
||||
(video_id,),
|
||||
).fetchall()
|
||||
|
||||
return row_to_video(row, subtitle_rows)
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Run a syntax check**
|
||||
|
||||
Run:
|
||||
|
||||
```powershell
|
||||
python -m py_compile backend\db.py
|
||||
```
|
||||
|
||||
Expected: command exits with no output.
|
||||
|
||||
Suggested commit if this directory is later made a git repo:
|
||||
|
||||
```bash
|
||||
git add backend/db.py
|
||||
git commit -m "backend: add video persistence helpers"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 2: Add Video Library API Endpoints
|
||||
|
||||
**Files:**
|
||||
- Modify: `F:\ooo\speaking-practice-local\backend\main.py`
|
||||
|
||||
- [ ] **Step 1: Add FastAPI imports**
|
||||
|
||||
Replace the current FastAPI import block with:
|
||||
|
||||
```python
|
||||
from pathlib import Path
|
||||
from uuid import uuid4
|
||||
|
||||
from fastapi import FastAPI, File, Form, HTTPException, UploadFile
|
||||
from fastapi.responses import FileResponse
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
|
||||
from .db import (
|
||||
DATABASE_PATH,
|
||||
create_video,
|
||||
initialize_database,
|
||||
list_videos,
|
||||
parse_tags,
|
||||
table_names,
|
||||
get_video,
|
||||
)
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Add upload validation constants and helpers**
|
||||
|
||||
Add this after `UPLOADS_DIR = PROJECT_DIR / "uploads"`:
|
||||
|
||||
```python
|
||||
VIDEO_EXTENSIONS = {".mp4", ".webm", ".mov", ".m4v"}
|
||||
SUBTITLE_EXTENSIONS = {".srt", ".vtt"}
|
||||
|
||||
|
||||
def extension_for_upload(upload: UploadFile) -> str:
|
||||
return Path(upload.filename or "").suffix.lower()
|
||||
|
||||
|
||||
def safe_upload_name(upload: UploadFile) -> str:
|
||||
extension = extension_for_upload(upload)
|
||||
return f"{uuid4().hex}{extension}"
|
||||
|
||||
|
||||
async def save_upload(upload: UploadFile, target_dir: Path) -> tuple[str, str]:
|
||||
target_dir.mkdir(parents=True, exist_ok=True)
|
||||
filename = safe_upload_name(upload)
|
||||
target_path = target_dir / filename
|
||||
content = await upload.read()
|
||||
try:
|
||||
target_path.write_bytes(content)
|
||||
except OSError as exc:
|
||||
raise HTTPException(status_code=500, detail="保存文件失败,请重试") from exc
|
||||
return filename, content.decode("utf-8-sig", errors="replace")
|
||||
|
||||
|
||||
async def save_binary_upload(upload: UploadFile, target_dir: Path) -> str:
|
||||
target_dir.mkdir(parents=True, exist_ok=True)
|
||||
filename = safe_upload_name(upload)
|
||||
target_path = target_dir / filename
|
||||
content = await upload.read()
|
||||
try:
|
||||
target_path.write_bytes(content)
|
||||
except OSError as exc:
|
||||
raise HTTPException(status_code=500, detail="保存文件失败,请重试") from exc
|
||||
return filename
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Mount uploaded files**
|
||||
|
||||
Add this after the `on_startup()` function:
|
||||
|
||||
```python
|
||||
app.mount("/uploads", StaticFiles(directory=UPLOADS_DIR), name="uploads")
|
||||
```
|
||||
|
||||
Leave the existing final `app.mount("/", StaticFiles(directory=PROJECT_DIR), name="static")` at the bottom so `/uploads/...` is matched before the root static mount.
|
||||
|
||||
- [ ] **Step 4: Add list and detail endpoints**
|
||||
|
||||
Add this after `health_check()`:
|
||||
|
||||
```python
|
||||
@app.get("/api/videos")
|
||||
def api_list_videos() -> list[dict[str, object]]:
|
||||
return list_videos()
|
||||
|
||||
|
||||
@app.get("/api/videos/{video_id}")
|
||||
def api_get_video(video_id: int) -> dict[str, object]:
|
||||
video = get_video(video_id)
|
||||
if video is None:
|
||||
raise HTTPException(status_code=404, detail="视频不存在")
|
||||
return video
|
||||
```
|
||||
|
||||
- [ ] **Step 5: Add create endpoint**
|
||||
|
||||
Add this after `api_get_video()`:
|
||||
|
||||
```python
|
||||
@app.post("/api/videos")
|
||||
async def api_create_video(
|
||||
title: str = Form(...),
|
||||
speaker: str = Form(""),
|
||||
description: str = Form(""),
|
||||
tags: str = Form(""),
|
||||
video_url: str = Form(""),
|
||||
video_file: UploadFile | None = File(None),
|
||||
subtitle_en: UploadFile | None = File(None),
|
||||
subtitle_zh: UploadFile | None = File(None),
|
||||
) -> dict[str, object]:
|
||||
clean_title = title.strip()
|
||||
if not clean_title:
|
||||
raise HTTPException(status_code=400, detail="标题不能为空")
|
||||
|
||||
clean_video_url = video_url.strip()
|
||||
if video_file is None and not clean_video_url:
|
||||
raise HTTPException(status_code=400, detail="请上传视频文件或填写视频地址")
|
||||
|
||||
final_video_url = clean_video_url
|
||||
if video_file is not None:
|
||||
if extension_for_upload(video_file) not in VIDEO_EXTENSIONS:
|
||||
raise HTTPException(status_code=400, detail="视频文件格式不支持")
|
||||
video_filename = await save_binary_upload(video_file, UPLOADS_DIR / "videos")
|
||||
final_video_url = f"/uploads/videos/{video_filename}"
|
||||
|
||||
subtitles: list[dict[str, str]] = []
|
||||
for upload, language_code, language_name in (
|
||||
(subtitle_en, "en", "English"),
|
||||
(subtitle_zh, "zh", "中文"),
|
||||
):
|
||||
if upload is None:
|
||||
continue
|
||||
extension = extension_for_upload(upload)
|
||||
if extension not in SUBTITLE_EXTENSIONS:
|
||||
raise HTTPException(status_code=400, detail="字幕只支持 .srt 或 .vtt")
|
||||
subtitle_filename, subtitle_text = await save_upload(upload, UPLOADS_DIR / "subtitles")
|
||||
subtitles.append(
|
||||
{
|
||||
"language_code": language_code,
|
||||
"language_name": language_name,
|
||||
"format": extension.removeprefix("."),
|
||||
"file_path": f"/uploads/subtitles/{subtitle_filename}",
|
||||
"content": subtitle_text,
|
||||
}
|
||||
)
|
||||
|
||||
return create_video(
|
||||
title=clean_title,
|
||||
speaker=speaker.strip(),
|
||||
description=description.strip(),
|
||||
tags=parse_tags(tags),
|
||||
video_url=final_video_url,
|
||||
subtitles=subtitles,
|
||||
)
|
||||
```
|
||||
|
||||
- [ ] **Step 6: Run a syntax check**
|
||||
|
||||
Run:
|
||||
|
||||
```powershell
|
||||
python -m py_compile backend\main.py backend\db.py
|
||||
```
|
||||
|
||||
Expected: command exits with no output.
|
||||
|
||||
- [ ] **Step 7: Verify the API imports**
|
||||
|
||||
Run:
|
||||
|
||||
```powershell
|
||||
python -c "from backend.main import app; print(app.title)"
|
||||
```
|
||||
|
||||
Expected output:
|
||||
|
||||
```text
|
||||
Speaking Lab API
|
||||
```
|
||||
|
||||
Suggested commit if this directory is later made a git repo:
|
||||
|
||||
```bash
|
||||
git add backend/main.py backend/db.py
|
||||
git commit -m "backend: add content library api"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 3: Switch Frontend Library Loading to the API
|
||||
|
||||
**Files:**
|
||||
- Modify: `F:\ooo\speaking-practice-local\app.js`
|
||||
|
||||
- [ ] **Step 1: Add API helper functions**
|
||||
|
||||
Add this after the `let hlsInstance = null;` line:
|
||||
|
||||
```javascript
|
||||
async function apiRequest(path, options = {}) {
|
||||
const response = await fetch(path, options);
|
||||
if (!response.ok) {
|
||||
let message = "请求失败,请重试。";
|
||||
try {
|
||||
const payload = await response.json();
|
||||
message = payload.detail || message;
|
||||
} catch {
|
||||
message = response.statusText || message;
|
||||
}
|
||||
throw new Error(message);
|
||||
}
|
||||
return response.json();
|
||||
}
|
||||
|
||||
function normalizeVideoFromApi(video) {
|
||||
const subtitles = {};
|
||||
Object.entries(video.subtitles || {}).forEach(([code, subtitle]) => {
|
||||
subtitles[code] = {
|
||||
languageName: subtitle.languageName || code,
|
||||
format: subtitle.format || "",
|
||||
filePath: subtitle.filePath || "",
|
||||
content: subtitle.content || "",
|
||||
cues: parseSubtitle(subtitle.content || ""),
|
||||
};
|
||||
});
|
||||
|
||||
return {
|
||||
id: video.id,
|
||||
title: video.title || "Untitled",
|
||||
speaker: video.speaker || "Unknown",
|
||||
description: video.description || "",
|
||||
tags: Array.isArray(video.tags) && video.tags.length ? video.tags : ["未分类"],
|
||||
duration: video.duration || 0,
|
||||
videoUrl: video.videoUrl || "",
|
||||
sourceType: video.sourceType || "url",
|
||||
subtitles,
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Replace startup calls**
|
||||
|
||||
Replace:
|
||||
|
||||
```javascript
|
||||
hydrate();
|
||||
bindEvents();
|
||||
renderAll();
|
||||
selectVideo(activeVideoId);
|
||||
```
|
||||
|
||||
with:
|
||||
|
||||
```javascript
|
||||
bindEvents();
|
||||
initializeApp();
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Replace `hydrate()` with API startup loading**
|
||||
|
||||
Replace the entire `hydrate()` function with:
|
||||
|
||||
```javascript
|
||||
async function initializeApp() {
|
||||
try {
|
||||
const videos = await apiRequest("/api/videos");
|
||||
state.videos = videos.map(normalizeVideoFromApi);
|
||||
if (!state.videos.length) {
|
||||
state.videos = sampleVideos;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
state.videos = sampleVideos;
|
||||
els.videoList.innerHTML = `<div class="empty-state">后端视频库加载失败,当前显示示例素材。</div>`;
|
||||
}
|
||||
|
||||
if (!getVideo(activeVideoId)) {
|
||||
activeVideoId = state.videos[0]?.id || null;
|
||||
}
|
||||
|
||||
renderAll();
|
||||
if (activeVideoId) selectVideo(activeVideoId);
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Keep video library out of localStorage**
|
||||
|
||||
Replace `saveState()` with:
|
||||
|
||||
```javascript
|
||||
function saveState() {
|
||||
const persistable = {
|
||||
users: state.users,
|
||||
currentUserId: state.currentUserId,
|
||||
activeVideoId: state.activeVideoId,
|
||||
};
|
||||
localStorage.setItem(STORAGE_KEY, JSON.stringify(persistable));
|
||||
}
|
||||
```
|
||||
|
||||
Replace the `loadState()` return object so `videos` is always empty on load:
|
||||
|
||||
```javascript
|
||||
function loadState() {
|
||||
try {
|
||||
const saved = JSON.parse(localStorage.getItem(STORAGE_KEY) || "{}");
|
||||
return {
|
||||
users: Array.isArray(saved.users) ? saved.users : [],
|
||||
currentUserId: saved.currentUserId || null,
|
||||
videos: [],
|
||||
activeVideoId: saved.activeVideoId || null,
|
||||
};
|
||||
} catch {
|
||||
return { users: [], currentUserId: null, videos: [], activeVideoId: null };
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 5: Run a quick static syntax check**
|
||||
|
||||
Run:
|
||||
|
||||
```powershell
|
||||
node --check app.js
|
||||
```
|
||||
|
||||
Expected output:
|
||||
|
||||
```text
|
||||
```
|
||||
|
||||
The expected output is empty; the command should exit with code 0.
|
||||
|
||||
Suggested commit if this directory is later made a git repo:
|
||||
|
||||
```bash
|
||||
git add app.js
|
||||
git commit -m "frontend: load videos from api"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 4: Submit Admin Video Adds to the Backend
|
||||
|
||||
**Files:**
|
||||
- Modify: `F:\ooo\speaking-practice-local\app.js`
|
||||
|
||||
- [ ] **Step 1: Replace `addVideoFromAdmin()`**
|
||||
|
||||
Replace the full `addVideoFromAdmin(event)` function with:
|
||||
|
||||
```javascript
|
||||
async function addVideoFromAdmin(event) {
|
||||
event.preventDefault();
|
||||
if (getCurrentUser()?.role !== "admin") return;
|
||||
|
||||
const title = els.adminTitle.value.trim();
|
||||
if (!title) {
|
||||
alert("标题不能为空");
|
||||
return;
|
||||
}
|
||||
|
||||
const submitButton = els.adminForm.querySelector('button[type="submit"]');
|
||||
const previousText = submitButton.textContent;
|
||||
submitButton.disabled = true;
|
||||
submitButton.textContent = "正在添加...";
|
||||
|
||||
const formData = new FormData();
|
||||
formData.append("title", title);
|
||||
formData.append("speaker", els.adminSpeaker.value.trim());
|
||||
formData.append("description", els.adminDescription.value.trim());
|
||||
formData.append("tags", els.adminTags.value.trim());
|
||||
formData.append("video_url", els.adminVideoUrl.value.trim());
|
||||
|
||||
const videoFile = els.adminVideoFile.files?.[0];
|
||||
const enFile = els.adminSubtitleEn.files?.[0];
|
||||
const zhFile = els.adminSubtitleZh.files?.[0];
|
||||
if (videoFile) formData.append("video_file", videoFile);
|
||||
if (enFile) formData.append("subtitle_en", enFile);
|
||||
if (zhFile) formData.append("subtitle_zh", zhFile);
|
||||
|
||||
try {
|
||||
const created = normalizeVideoFromApi(await apiRequest("/api/videos", {
|
||||
method: "POST",
|
||||
body: formData,
|
||||
}));
|
||||
state.videos = [created, ...state.videos.filter((video) => String(video.id) !== String(created.id))];
|
||||
els.adminForm.reset();
|
||||
renderLibrary();
|
||||
selectVideo(created.id);
|
||||
} catch (error) {
|
||||
alert(error.message || "添加视频失败,请重试。");
|
||||
} finally {
|
||||
submitButton.disabled = false;
|
||||
submitButton.textContent = previousText;
|
||||
renderAdminAccess();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Guard current-video editing for API-backed videos**
|
||||
|
||||
Replace `updateCurrentVideoInfo()` with:
|
||||
|
||||
```javascript
|
||||
function updateCurrentVideoInfo() {
|
||||
alert("第一版内容库暂不支持网页编辑。请重新添加一条新视频。");
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Verify admin form controls recover after submit**
|
||||
|
||||
After Step 1, keep the existing `renderAdminAccess()` function unchanged:
|
||||
|
||||
```javascript
|
||||
[...els.adminForm.elements].forEach((element) => {
|
||||
element.disabled = !isAdmin;
|
||||
});
|
||||
```
|
||||
|
||||
Manual check after implementation:
|
||||
|
||||
- Log in with an admin email.
|
||||
- Submit the admin form with an intentionally invalid request, such as no video file and no video URL.
|
||||
- Confirm an error appears.
|
||||
- Confirm the submit button text returns to `添加到视频库`.
|
||||
- Confirm the admin form inputs are enabled again.
|
||||
|
||||
- [ ] **Step 4: Run a quick static syntax check**
|
||||
|
||||
Run:
|
||||
|
||||
```powershell
|
||||
node --check app.js
|
||||
```
|
||||
|
||||
Expected: command exits with no output.
|
||||
|
||||
Suggested commit if this directory is later made a git repo:
|
||||
|
||||
```bash
|
||||
git add app.js
|
||||
git commit -m "frontend: submit admin videos to backend"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 5: Document and Manually Verify the Content Library
|
||||
|
||||
**Files:**
|
||||
- Modify: `F:\ooo\speaking-practice-local\README.md`
|
||||
|
||||
- [ ] **Step 1: Add content-library notes to README**
|
||||
|
||||
Append this section to the README:
|
||||
|
||||
```markdown
|
||||
## Content Library
|
||||
|
||||
The admin form now saves videos and subtitles through the FastAPI backend.
|
||||
|
||||
Supported first-version flow:
|
||||
|
||||
- Log in with an email containing `admin`.
|
||||
- Add a title, speaker, description, and comma-separated tags.
|
||||
- Choose either a local video file or a video/HLS URL.
|
||||
- Optionally upload English and Chinese `.srt` / `.vtt` subtitle files.
|
||||
- Refresh the browser and confirm the added video remains in the library.
|
||||
|
||||
Uploaded files are stored locally:
|
||||
|
||||
- Videos: `uploads/videos/`
|
||||
- Subtitles: `uploads/subtitles/`
|
||||
|
||||
Metadata is stored in SQLite:
|
||||
|
||||
- `backend/speaking_lab.sqlite`
|
||||
|
||||
This phase does not include web editing, deletion, real authentication, learning progress sync, or server deployment.
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Start the dev server**
|
||||
|
||||
Run:
|
||||
|
||||
```powershell
|
||||
python -m uvicorn backend.main:app --reload --host 127.0.0.1 --port 8000
|
||||
```
|
||||
|
||||
Expected output includes:
|
||||
|
||||
```text
|
||||
Uvicorn running on http://127.0.0.1:8000
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Verify health and list endpoints**
|
||||
|
||||
In a second terminal, run:
|
||||
|
||||
```powershell
|
||||
Invoke-RestMethod http://127.0.0.1:8000/api/health
|
||||
Invoke-RestMethod http://127.0.0.1:8000/api/videos
|
||||
```
|
||||
|
||||
Expected:
|
||||
|
||||
- `/api/health` returns `ok: True`.
|
||||
- `/api/videos` returns an array. It may be empty.
|
||||
|
||||
- [ ] **Step 4: Verify external URL creation by API**
|
||||
|
||||
Create a small subtitle file for testing:
|
||||
|
||||
```powershell
|
||||
@"
|
||||
1
|
||||
00:00:00,000 --> 00:00:02,000
|
||||
Hello from Speaking Lab.
|
||||
"@ | Set-Content -LiteralPath .\test-en.srt -Encoding UTF8
|
||||
```
|
||||
|
||||
Run:
|
||||
|
||||
```powershell
|
||||
curl.exe -X POST http://127.0.0.1:8000/api/videos `
|
||||
-F "title=API Smoke Test" `
|
||||
-F "speaker=Tester" `
|
||||
-F "description=Created from curl" `
|
||||
-F "tags=测试,API" `
|
||||
-F "video_url=https://example.com/video.mp4" `
|
||||
-F "subtitle_en=@test-en.srt"
|
||||
```
|
||||
|
||||
Expected response includes:
|
||||
|
||||
```json
|
||||
"title":"API Smoke Test"
|
||||
```
|
||||
|
||||
- [ ] **Step 5: Verify browser flow**
|
||||
|
||||
Open:
|
||||
|
||||
```text
|
||||
http://127.0.0.1:8000
|
||||
```
|
||||
|
||||
Manual expected behavior:
|
||||
|
||||
- Log in with an email containing `admin`.
|
||||
- Submit a video URL with English and Chinese subtitles.
|
||||
- The new video appears at the top of the material list.
|
||||
- Refresh the browser.
|
||||
- The new video remains in the material list.
|
||||
- Selecting the video shows parsed subtitle lines.
|
||||
|
||||
- [ ] **Step 6: Verify API docs**
|
||||
|
||||
Open:
|
||||
|
||||
```text
|
||||
http://127.0.0.1:8000/docs
|
||||
```
|
||||
|
||||
Expected:
|
||||
|
||||
- `GET /api/videos` is visible.
|
||||
- `GET /api/videos/{video_id}` is visible.
|
||||
- `POST /api/videos` is visible.
|
||||
|
||||
Suggested commit if this directory is later made a git repo:
|
||||
|
||||
```bash
|
||||
git add README.md
|
||||
git commit -m "docs: document content library flow"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Self-Review
|
||||
|
||||
Spec coverage:
|
||||
|
||||
- Backend content APIs are covered by Tasks 1 and 2.
|
||||
- Uploaded video and subtitle storage are covered by Task 2.
|
||||
- SQLite video/subtitle persistence is covered by Task 1.
|
||||
- Frontend API loading and admin submit behavior are covered by Tasks 3 and 4.
|
||||
- Manual verification and docs are covered by Task 5.
|
||||
|
||||
Placeholder scan:
|
||||
|
||||
- No placeholder markers or unspecified implementation steps.
|
||||
- The plan intentionally excludes edit/delete, real authentication, learning records, and deployment, matching the approved spec.
|
||||
|
||||
Type consistency:
|
||||
|
||||
- Backend returns camelCase properties expected by the existing frontend: `videoUrl`, `sourceType`, `languageName`, and `filePath`.
|
||||
- Frontend normalizes subtitle `content` into existing `cues`.
|
||||
- Video ids may become numbers from SQLite; comparisons that need robustness use string conversion in the admin insert path.
|
||||
@@ -0,0 +1,582 @@
|
||||
# Speaking Lab Learning Progress v1 Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** Add local per-user learning progress, continue learning, and per-line practiced/difficult status to the study page.
|
||||
|
||||
**Architecture:** Keep progress entirely in the existing `speaking-lab-state-v1` localStorage state. Add pure progress helper functions to `app.js` and export them for small Node tests, then wire those helpers into the existing study-page render and event flow. No backend schema or admin-page changes are required.
|
||||
|
||||
**Tech Stack:** Vanilla HTML/CSS/JS, browser `localStorage`, Node built-in `assert` for helper tests, existing FastAPI backend unchanged.
|
||||
|
||||
---
|
||||
|
||||
## File Structure
|
||||
|
||||
- Modify `F:\ooo\speaking-practice-local\index.html`: add a `继续学习` button beside existing video actions.
|
||||
- Modify `F:\ooo\speaking-practice-local\app.js`: add progress helpers, local state migration, save/restore logic, transcript status controls, and material-list progress summaries.
|
||||
- Modify `F:\ooo\speaking-practice-local\styles.css`: style continue action, transcript status controls, and progress labels.
|
||||
- Add `F:\ooo\speaking-practice-local\tests\progress-helpers.test.mjs`: Node tests for pure helper behavior.
|
||||
- Keep `F:\ooo\speaking-practice-local\backend\main.py` and `backend\db.py` unchanged except for verification.
|
||||
|
||||
---
|
||||
|
||||
## Task 1: Add Progress Helper Tests
|
||||
|
||||
**Files:**
|
||||
- Add: `F:\ooo\speaking-practice-local\tests\progress-helpers.test.mjs`
|
||||
- Modify: `F:\ooo\speaking-practice-local\app.js`
|
||||
|
||||
- [ ] **Step 1: Create failing helper tests**
|
||||
|
||||
Create `tests\progress-helpers.test.mjs`:
|
||||
|
||||
```js
|
||||
import assert from "node:assert/strict";
|
||||
import {
|
||||
createEmptyProgress,
|
||||
getVideoProgress,
|
||||
toggleLineIndex,
|
||||
calculatePracticeSummary,
|
||||
formatProgressSummary,
|
||||
} from "../app.js";
|
||||
|
||||
const empty = createEmptyProgress();
|
||||
assert.deepEqual(empty, {
|
||||
currentTime: 0,
|
||||
activeLineIndex: 0,
|
||||
practicedLineIndexes: [],
|
||||
difficultLineIndexes: [],
|
||||
updatedAt: "",
|
||||
});
|
||||
|
||||
const user = { progress: {} };
|
||||
const progress = getVideoProgress(user, "video-1");
|
||||
assert.deepEqual(progress.practicedLineIndexes, []);
|
||||
assert.equal(user.progress["video-1"], progress);
|
||||
|
||||
assert.deepEqual(toggleLineIndex([0, 2], 1), [0, 1, 2]);
|
||||
assert.deepEqual(toggleLineIndex([0, 1, 2], 1), [0, 2]);
|
||||
assert.deepEqual(toggleLineIndex([2, 2, 0], 1), [0, 1, 2]);
|
||||
|
||||
assert.deepEqual(calculatePracticeSummary({
|
||||
practicedLineIndexes: [0, 2],
|
||||
}, 5), {
|
||||
practiced: 2,
|
||||
total: 5,
|
||||
percent: 40,
|
||||
});
|
||||
|
||||
assert.equal(formatProgressSummary({
|
||||
practicedLineIndexes: [0, 2],
|
||||
currentTime: 124.4,
|
||||
}, 5), "已练 2/5 · 40%");
|
||||
|
||||
assert.equal(formatProgressSummary({
|
||||
practicedLineIndexes: [],
|
||||
currentTime: 124.4,
|
||||
}, 0), "看到 02:04");
|
||||
|
||||
assert.equal(formatProgressSummary({
|
||||
practicedLineIndexes: [],
|
||||
currentTime: 0,
|
||||
}, 0), "");
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run test and confirm it fails**
|
||||
|
||||
Run:
|
||||
|
||||
```powershell
|
||||
node tests\progress-helpers.test.mjs
|
||||
```
|
||||
|
||||
Expected: fails because `app.js` does not export these helpers yet.
|
||||
|
||||
- [ ] **Step 3: Add test-safe exports and pure helpers in `app.js`**
|
||||
|
||||
Add `const IS_BROWSER = typeof document !== "undefined";` near the top, guard DOM queries with `IS_BROWSER`, and only call `bindEvents()` / `initializeApp()` in the browser.
|
||||
|
||||
Add pure helpers:
|
||||
|
||||
```js
|
||||
function createEmptyProgress() {
|
||||
return {
|
||||
currentTime: 0,
|
||||
activeLineIndex: 0,
|
||||
practicedLineIndexes: [],
|
||||
difficultLineIndexes: [],
|
||||
updatedAt: "",
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeProgress(progress) {
|
||||
return {
|
||||
...createEmptyProgress(),
|
||||
...(progress || {}),
|
||||
currentTime: Number(progress?.currentTime) || 0,
|
||||
activeLineIndex: Number.isInteger(progress?.activeLineIndex) ? progress.activeLineIndex : 0,
|
||||
practicedLineIndexes: normalizeIndexList(progress?.practicedLineIndexes),
|
||||
difficultLineIndexes: normalizeIndexList(progress?.difficultLineIndexes),
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeIndexList(value) {
|
||||
if (!Array.isArray(value)) return [];
|
||||
return [...new Set(value.map(Number).filter((index) => Number.isInteger(index) && index >= 0))].sort((a, b) => a - b);
|
||||
}
|
||||
|
||||
function ensureUserProgress(user) {
|
||||
if (!user) return null;
|
||||
if (!user.progress || typeof user.progress !== "object") user.progress = {};
|
||||
Object.keys(user.progress).forEach((videoId) => {
|
||||
user.progress[videoId] = normalizeProgress(user.progress[videoId]);
|
||||
});
|
||||
return user.progress;
|
||||
}
|
||||
|
||||
function getVideoProgress(user, videoId) {
|
||||
const progressMap = ensureUserProgress(user);
|
||||
if (!progressMap) return createEmptyProgress();
|
||||
const key = String(videoId);
|
||||
progressMap[key] = normalizeProgress(progressMap[key]);
|
||||
return progressMap[key];
|
||||
}
|
||||
|
||||
function toggleLineIndex(indexes, index) {
|
||||
const normalized = normalizeIndexList(indexes);
|
||||
if (normalized.includes(index)) {
|
||||
return normalized.filter((item) => item !== index);
|
||||
}
|
||||
return normalizeIndexList([...normalized, index]);
|
||||
}
|
||||
|
||||
function calculatePracticeSummary(progress, totalLines) {
|
||||
const total = Math.max(0, Number(totalLines) || 0);
|
||||
const practiced = normalizeIndexList(progress?.practicedLineIndexes).filter((index) => index < total).length;
|
||||
const percent = total ? Math.round((practiced / total) * 100) : 0;
|
||||
return { practiced, total, percent };
|
||||
}
|
||||
|
||||
function formatProgressSummary(progress, totalLines) {
|
||||
const summary = calculatePracticeSummary(progress, totalLines);
|
||||
if (summary.total > 0 && summary.practiced > 0) {
|
||||
return `已练 ${summary.practiced}/${summary.total} · ${summary.percent}%`;
|
||||
}
|
||||
const currentTime = Number(progress?.currentTime) || 0;
|
||||
if (currentTime > 1) return `看到 ${formatTime(currentTime)}`;
|
||||
return "";
|
||||
}
|
||||
```
|
||||
|
||||
At the bottom:
|
||||
|
||||
```js
|
||||
if (typeof module !== "undefined" && module.exports) {
|
||||
module.exports = {
|
||||
createEmptyProgress,
|
||||
getVideoProgress,
|
||||
toggleLineIndex,
|
||||
calculatePracticeSummary,
|
||||
formatProgressSummary,
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Run helper test**
|
||||
|
||||
Run:
|
||||
|
||||
```powershell
|
||||
node tests\progress-helpers.test.mjs
|
||||
```
|
||||
|
||||
Expected: exit code 0.
|
||||
|
||||
---
|
||||
|
||||
## Task 2: Wire Progress Save And Continue Learning
|
||||
|
||||
**Files:**
|
||||
- Modify: `F:\ooo\speaking-practice-local\index.html`
|
||||
- Modify: `F:\ooo\speaking-practice-local\app.js`
|
||||
|
||||
- [ ] **Step 1: Add continue button to `index.html`**
|
||||
|
||||
Inside `<div class="video-actions">`, before favorite/watch-later:
|
||||
|
||||
```html
|
||||
<button id="continueBtn" type="button" hidden>继续学习</button>
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Add element and state fields in `app.js`**
|
||||
|
||||
Add `continueBtn` to `els`, add:
|
||||
|
||||
```js
|
||||
let lastProgressSaveAt = 0;
|
||||
let pendingRestoreProgress = null;
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Migrate users to include progress**
|
||||
|
||||
In `loadState()`, after reading users, normalize each user:
|
||||
|
||||
```js
|
||||
const users = Array.isArray(saved.users) ? saved.users.map(normalizeUser) : [];
|
||||
```
|
||||
|
||||
Add:
|
||||
|
||||
```js
|
||||
function normalizeUser(user) {
|
||||
const normalized = {
|
||||
...user,
|
||||
favorites: Array.isArray(user.favorites) ? user.favorites : [],
|
||||
watchLater: Array.isArray(user.watchLater) ? user.watchLater : [],
|
||||
};
|
||||
ensureUserProgress(normalized);
|
||||
return normalized;
|
||||
}
|
||||
```
|
||||
|
||||
When creating a new user, include `progress: {}`.
|
||||
|
||||
- [ ] **Step 4: Save playback progress**
|
||||
|
||||
Add helpers:
|
||||
|
||||
```js
|
||||
function getActiveProgress() {
|
||||
const user = getCurrentUser();
|
||||
if (!user || !activeVideoId) return null;
|
||||
return getVideoProgress(user, activeVideoId);
|
||||
}
|
||||
|
||||
function saveActiveProgress(partial = {}, immediate = false) {
|
||||
const progress = getActiveProgress();
|
||||
if (!progress) return;
|
||||
Object.assign(progress, partial, { updatedAt: new Date().toISOString() });
|
||||
const now = Date.now();
|
||||
if (immediate || now - lastProgressSaveAt > 1500) {
|
||||
lastProgressSaveAt = now;
|
||||
saveState();
|
||||
renderContinueAction();
|
||||
renderLibrary();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Update `handleTimeUpdate()` to call:
|
||||
|
||||
```js
|
||||
saveActiveProgress({ currentTime: els.video.currentTime || 0 });
|
||||
```
|
||||
|
||||
Update `setActiveLine()` to call:
|
||||
|
||||
```js
|
||||
saveActiveProgress({ activeLineIndex: index }, true);
|
||||
```
|
||||
|
||||
Add a `beforeunload` listener in `bindEvents()`:
|
||||
|
||||
```js
|
||||
window.addEventListener("beforeunload", () => {
|
||||
if (els.video && activeVideoId) {
|
||||
saveActiveProgress({ currentTime: els.video.currentTime || 0, activeLineIndex: Math.max(activeLineIndex, 0) }, true);
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 5: Restore and continue**
|
||||
|
||||
In `selectVideo(id)`, before `loadVideoSource(video)`, set:
|
||||
|
||||
```js
|
||||
pendingRestoreProgress = getActiveProgress();
|
||||
```
|
||||
|
||||
Add:
|
||||
|
||||
```js
|
||||
function restoreProgressForActiveVideo() {
|
||||
const progress = pendingRestoreProgress;
|
||||
pendingRestoreProgress = null;
|
||||
if (!progress) return;
|
||||
|
||||
const cues = getPrimaryCues();
|
||||
const restoredIndex = cues[progress.activeLineIndex] ? progress.activeLineIndex : 0;
|
||||
if (cues.length) setActiveLine(restoredIndex, true);
|
||||
|
||||
if (progress.currentTime > 1) {
|
||||
els.video.currentTime = progress.currentTime;
|
||||
}
|
||||
}
|
||||
|
||||
function continueLearning() {
|
||||
const progress = getActiveProgress();
|
||||
if (!progress) return;
|
||||
if (progress.currentTime > 1) els.video.currentTime = progress.currentTime;
|
||||
if (progress.activeLineIndex >= 0) jumpToLine(progress.activeLineIndex);
|
||||
els.video.play().catch(() => {});
|
||||
}
|
||||
|
||||
function renderContinueAction() {
|
||||
const progress = getActiveProgress();
|
||||
const hasProgress = Boolean(progress && (progress.currentTime > 1 || progress.activeLineIndex > 0));
|
||||
els.continueBtn.hidden = !hasProgress;
|
||||
}
|
||||
```
|
||||
|
||||
Call `restoreProgressForActiveVideo()` after `renderTranscript()` in `selectVideo()`.
|
||||
|
||||
Bind `continueBtn` click to `continueLearning()`.
|
||||
|
||||
- [ ] **Step 6: Run syntax check**
|
||||
|
||||
Run:
|
||||
|
||||
```powershell
|
||||
node --check app.js
|
||||
node tests\progress-helpers.test.mjs
|
||||
```
|
||||
|
||||
Expected: both pass.
|
||||
|
||||
---
|
||||
|
||||
## Task 3: Add Per-Line Practiced And Difficult Controls
|
||||
|
||||
**Files:**
|
||||
- Modify: `F:\ooo\speaking-practice-local\app.js`
|
||||
- Modify: `F:\ooo\speaking-practice-local\styles.css`
|
||||
|
||||
- [ ] **Step 1: Update transcript line markup**
|
||||
|
||||
In `renderTranscript()`, add a status area inside each `.line-button`:
|
||||
|
||||
```html
|
||||
<div class="line-status" aria-label="练习状态">
|
||||
<button class="line-status-button practiced" type="button" data-status="practiced">已练</button>
|
||||
<button class="line-status-button difficult" type="button" data-status="difficult">难句</button>
|
||||
</div>
|
||||
```
|
||||
|
||||
Use real DOM creation or the existing template, but make sure nested button clicks do not trigger line jump.
|
||||
|
||||
- [ ] **Step 2: Add toggle function**
|
||||
|
||||
Add:
|
||||
|
||||
```js
|
||||
function toggleLineStatus(index, status, event) {
|
||||
event.stopPropagation();
|
||||
const progress = getActiveProgress();
|
||||
if (!progress) {
|
||||
alert("请先登录后再记录学习进度。");
|
||||
return;
|
||||
}
|
||||
|
||||
if (status === "practiced") {
|
||||
progress.practicedLineIndexes = toggleLineIndex(progress.practicedLineIndexes, index);
|
||||
}
|
||||
if (status === "difficult") {
|
||||
progress.difficultLineIndexes = toggleLineIndex(progress.difficultLineIndexes, index);
|
||||
}
|
||||
progress.updatedAt = new Date().toISOString();
|
||||
saveState();
|
||||
renderTranscript();
|
||||
renderLibrary();
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Apply active classes**
|
||||
|
||||
When rendering each line:
|
||||
|
||||
```js
|
||||
const progress = getActiveProgress();
|
||||
const practiced = progress?.practicedLineIndexes.includes(index);
|
||||
const difficult = progress?.difficultLineIndexes.includes(index);
|
||||
button.classList.toggle("is-practiced", practiced);
|
||||
button.classList.toggle("is-difficult", difficult);
|
||||
```
|
||||
|
||||
Set `.active` on status buttons when their status applies.
|
||||
|
||||
- [ ] **Step 4: Style controls**
|
||||
|
||||
Add CSS:
|
||||
|
||||
```css
|
||||
.line-status {
|
||||
display: flex;
|
||||
gap: 5px;
|
||||
justify-content: flex-end;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.line-status-button {
|
||||
min-height: 26px;
|
||||
padding: 0 7px;
|
||||
border-radius: 6px;
|
||||
font-size: 12px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.line-status-button.practiced.active {
|
||||
color: #047857;
|
||||
border-color: #9bd8c0;
|
||||
background: #ecfdf5;
|
||||
}
|
||||
|
||||
.line-status-button.difficult.active {
|
||||
color: #92400e;
|
||||
border-color: #f5c56f;
|
||||
background: #fffbeb;
|
||||
}
|
||||
|
||||
.line-button.is-practiced {
|
||||
border-color: #ccebdd;
|
||||
}
|
||||
|
||||
.line-button.is-difficult {
|
||||
box-shadow: inset 3px 0 0 var(--gold);
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 5: Run checks**
|
||||
|
||||
Run:
|
||||
|
||||
```powershell
|
||||
node --check app.js
|
||||
node tests\progress-helpers.test.mjs
|
||||
```
|
||||
|
||||
Expected: both pass.
|
||||
|
||||
---
|
||||
|
||||
## Task 4: Show Material List Progress
|
||||
|
||||
**Files:**
|
||||
- Modify: `F:\ooo\speaking-practice-local\app.js`
|
||||
- Modify: `F:\ooo\speaking-practice-local\styles.css`
|
||||
|
||||
- [ ] **Step 1: Add progress summary to video items**
|
||||
|
||||
In `renderLibrary()`, add another `<small class="video-progress"></small>` inside each `.video-item`.
|
||||
|
||||
Compute:
|
||||
|
||||
```js
|
||||
const progress = getVideoProgress(getCurrentUser(), video.id);
|
||||
const primaryCueCount = getDefaultCueCount(video);
|
||||
const summary = formatProgressSummary(progress, primaryCueCount);
|
||||
```
|
||||
|
||||
Add:
|
||||
|
||||
```js
|
||||
function getDefaultCueCount(video) {
|
||||
if (video?.subtitles?.en?.cues?.length) return video.subtitles.en.cues.length;
|
||||
const firstTrack = Object.values(video?.subtitles || {})[0];
|
||||
return firstTrack?.cues?.length || 0;
|
||||
}
|
||||
```
|
||||
|
||||
Only show the progress node when `summary` is not empty.
|
||||
|
||||
- [ ] **Step 2: Style progress summary**
|
||||
|
||||
Add:
|
||||
|
||||
```css
|
||||
.video-progress {
|
||||
color: var(--brand);
|
||||
font-weight: 700;
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Run checks**
|
||||
|
||||
Run:
|
||||
|
||||
```powershell
|
||||
node --check app.js
|
||||
node tests\progress-helpers.test.mjs
|
||||
```
|
||||
|
||||
Expected: both pass.
|
||||
|
||||
---
|
||||
|
||||
## Task 5: Verify End To End
|
||||
|
||||
**Files:**
|
||||
- No new code unless verification reveals a bug.
|
||||
|
||||
- [ ] **Step 1: Run static checks**
|
||||
|
||||
Run:
|
||||
|
||||
```powershell
|
||||
python -m py_compile backend\main.py backend\db.py
|
||||
node --check app.js
|
||||
node --check admin.js
|
||||
node tests\progress-helpers.test.mjs
|
||||
node tests\admin-file-input.test.mjs
|
||||
```
|
||||
|
||||
Expected: all exit code 0.
|
||||
|
||||
- [ ] **Step 2: Start or confirm dev server**
|
||||
|
||||
Run if needed:
|
||||
|
||||
```powershell
|
||||
python -m uvicorn backend.main:app --reload --host 127.0.0.1 --port 8000
|
||||
```
|
||||
|
||||
Expected: `http://127.0.0.1:8000` responds.
|
||||
|
||||
- [ ] **Step 3: Browser smoke test**
|
||||
|
||||
Open `http://127.0.0.1:8000`.
|
||||
|
||||
Manual checks:
|
||||
|
||||
- Log in as a normal user.
|
||||
- Open a video with subtitles.
|
||||
- Mark one line `已练`.
|
||||
- Mark another line `难句`.
|
||||
- Confirm left material list shows progress.
|
||||
- Refresh the page.
|
||||
- Confirm progress and line statuses remain.
|
||||
- Click `继续学习` and confirm it jumps to saved progress.
|
||||
- Log in as another user and confirm progress is separate.
|
||||
|
||||
---
|
||||
|
||||
## Self-Review
|
||||
|
||||
Spec coverage:
|
||||
|
||||
- Save last playback time: Task 2.
|
||||
- Save active subtitle line: Task 2.
|
||||
- Continue learning action: Task 2.
|
||||
- Per-line practiced/difficult controls: Task 3.
|
||||
- Material list progress: Task 4.
|
||||
- LocalStorage-only persistence: Task 2.
|
||||
- Tests for helpers: Task 1 and Task 5.
|
||||
|
||||
Placeholder scan:
|
||||
|
||||
- No placeholder markers remain.
|
||||
- All implementation steps include exact files and commands.
|
||||
|
||||
Type consistency:
|
||||
|
||||
- Progress fields consistently use `currentTime`, `activeLineIndex`, `practicedLineIndexes`, `difficultLineIndexes`, and `updatedAt`.
|
||||
- Video IDs are normalized with `String(videoId)`.
|
||||
@@ -0,0 +1,775 @@
|
||||
# Speaking Lab DeepSeek Subtitle AI Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** Add a beginner-friendly DeepSeek-powered admin workflow that cleans English subtitles and generates matching Chinese subtitles.
|
||||
|
||||
**Architecture:** Keep subtitle parsing/cleaning local and deterministic, and use DeepSeek only for translation/text JSON generation. Add a small backend provider boundary so future audio-based ASR timestamp calibration can be added without rewriting the admin UI.
|
||||
|
||||
**Tech Stack:** FastAPI, SQLite, vanilla JavaScript admin page, Python stdlib/httpx if available, Node-based frontend tests.
|
||||
|
||||
---
|
||||
|
||||
## File Structure
|
||||
|
||||
- Create `backend/ai_config.py`: environment parsing and AI status helpers.
|
||||
- Create `backend/subtitle_tools.py`: VTT/SRT parsing, duplicate removal, and VTT building.
|
||||
- Create `backend/deepseek_client.py`: DeepSeek chat API client.
|
||||
- Create `backend/subtitle_ai.py`: workflow orchestration.
|
||||
- Modify `backend/main.py`: add AI status/test/process endpoints.
|
||||
- Modify `backend/db.py`: add helper to update/upsert subtitle content for one video.
|
||||
- Modify `admin.html`: add AI subtitle panel.
|
||||
- Modify `admin.js`: call new endpoints and display status/report.
|
||||
- Modify `styles.css`: style the compact admin AI panel.
|
||||
- Add Python tests under `tests/`.
|
||||
- Add Node/admin tests if frontend helper logic is extracted.
|
||||
|
||||
### Task 1: Local Subtitle Tools
|
||||
|
||||
**Files:**
|
||||
- Create: `backend/subtitle_tools.py`
|
||||
- Test: `tests/subtitle_tools_test.py`
|
||||
|
||||
- [ ] **Step 1: Write the failing test**
|
||||
|
||||
```python
|
||||
from backend.subtitle_tools import build_vtt, clean_english_subtitle
|
||||
|
||||
|
||||
def test_clean_english_subtitle_removes_empty_and_duplicate_cues():
|
||||
raw = """WEBVTT
|
||||
|
||||
00:00:00.000 --> 00:00:00.001
|
||||
|
||||
00:00:00.872 --> 00:00:04.959
|
||||
My first job as an investor
|
||||
was when I was 24 years old,
|
||||
|
||||
00:00:00.872 --> 00:00:04.959
|
||||
My first job as an investor
|
||||
was when I was 24 years old,
|
||||
"""
|
||||
|
||||
result = clean_english_subtitle(raw)
|
||||
|
||||
assert result.original_count == 3
|
||||
assert result.cleaned_count == 1
|
||||
assert result.duplicate_count == 1
|
||||
assert result.empty_count == 1
|
||||
assert result.cues[0].start == "00:00:00.872"
|
||||
assert result.cues[0].end == "00:00:04.959"
|
||||
assert result.cues[0].text == "My first job as an investor\nwas when I was 24 years old,"
|
||||
|
||||
|
||||
def test_build_vtt_outputs_numbered_blocks():
|
||||
result = build_vtt([
|
||||
{
|
||||
"start": "00:00:00.872",
|
||||
"end": "00:00:04.959",
|
||||
"text": "My first job as an investor",
|
||||
}
|
||||
])
|
||||
|
||||
assert result == "WEBVTT\n\n1\n00:00:00.872 --> 00:00:04.959\nMy first job as an investor\n"
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run test to verify it fails**
|
||||
|
||||
Run: `python tests\subtitle_tools_test.py`
|
||||
|
||||
Expected: FAIL with `ModuleNotFoundError` or missing function.
|
||||
|
||||
- [ ] **Step 3: Implement subtitle tools**
|
||||
|
||||
Create `backend/subtitle_tools.py` with:
|
||||
|
||||
```python
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
import re
|
||||
|
||||
|
||||
TIME_RE = re.compile(
|
||||
r"(?P<start>\d{1,2}:\d{2}:\d{2}[\.,]\d{3})\s*-->\s*(?P<end>\d{1,2}:\d{2}:\d{2}[\.,]\d{3})"
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
class SubtitleCue:
|
||||
start: str
|
||||
end: str
|
||||
text: str
|
||||
|
||||
|
||||
@dataclass
|
||||
class CleanSubtitleResult:
|
||||
cues: list[SubtitleCue]
|
||||
original_count: int
|
||||
cleaned_count: int
|
||||
duplicate_count: int
|
||||
empty_count: int
|
||||
|
||||
|
||||
def normalize_time(value: str) -> str:
|
||||
return value.replace(",", ".")
|
||||
|
||||
|
||||
def has_visible_text(rows: list[str]) -> bool:
|
||||
text = "".join(rows).replace(" ", "").replace("\u00a0", "").strip()
|
||||
return bool(text)
|
||||
|
||||
|
||||
def parse_subtitle(content: str) -> list[SubtitleCue]:
|
||||
cues: list[SubtitleCue] = []
|
||||
current_time: tuple[str, str] | None = None
|
||||
text_rows: list[str] = []
|
||||
|
||||
def flush() -> None:
|
||||
nonlocal current_time, text_rows
|
||||
if current_time and text_rows:
|
||||
cues.append(SubtitleCue(current_time[0], current_time[1], "\n".join(text_rows).strip()))
|
||||
current_time = None
|
||||
text_rows = []
|
||||
|
||||
for raw_line in str(content or "").replace("\r", "").replace("\ufeff", "").split("\n"):
|
||||
row = raw_line.strip()
|
||||
if not row:
|
||||
flush()
|
||||
continue
|
||||
if row.upper().startswith("WEBVTT") or row.isdigit():
|
||||
continue
|
||||
match = TIME_RE.search(row)
|
||||
if match:
|
||||
flush()
|
||||
current_time = (normalize_time(match.group("start")), normalize_time(match.group("end")))
|
||||
continue
|
||||
if current_time:
|
||||
text_rows.append(row)
|
||||
|
||||
flush()
|
||||
return cues
|
||||
|
||||
|
||||
def clean_english_subtitle(content: str) -> CleanSubtitleResult:
|
||||
parsed = parse_subtitle(content)
|
||||
cleaned: list[SubtitleCue] = []
|
||||
seen: set[tuple[str, str, str]] = set()
|
||||
duplicate_count = 0
|
||||
empty_count = 0
|
||||
|
||||
for cue in parsed:
|
||||
rows = cue.text.splitlines()
|
||||
if not has_visible_text(rows):
|
||||
empty_count += 1
|
||||
continue
|
||||
key = (cue.start, cue.end, cue.text.strip())
|
||||
if key in seen:
|
||||
duplicate_count += 1
|
||||
continue
|
||||
seen.add(key)
|
||||
cleaned.append(cue)
|
||||
|
||||
return CleanSubtitleResult(
|
||||
cues=cleaned,
|
||||
original_count=len(parsed),
|
||||
cleaned_count=len(cleaned),
|
||||
duplicate_count=duplicate_count,
|
||||
empty_count=empty_count,
|
||||
)
|
||||
|
||||
|
||||
def build_vtt(cues: list[SubtitleCue] | list[dict[str, str]]) -> str:
|
||||
blocks: list[str] = []
|
||||
for index, cue in enumerate(cues, 1):
|
||||
start = cue.start if isinstance(cue, SubtitleCue) else cue["start"]
|
||||
end = cue.end if isinstance(cue, SubtitleCue) else cue["end"]
|
||||
text = cue.text if isinstance(cue, SubtitleCue) else cue["text"]
|
||||
blocks.append(f"{index}\n{start} --> {end}\n{text.strip()}")
|
||||
return "WEBVTT\n\n" + "\n\n".join(blocks).strip() + "\n"
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Run test to verify it passes**
|
||||
|
||||
Run: `python tests\subtitle_tools_test.py`
|
||||
|
||||
Expected: PASS with exit code 0.
|
||||
|
||||
### Task 2: AI Config and DeepSeek Client
|
||||
|
||||
**Files:**
|
||||
- Create: `backend/ai_config.py`
|
||||
- Create: `backend/deepseek_client.py`
|
||||
- Test: `tests/ai_config_test.py`
|
||||
|
||||
- [ ] **Step 1: Write failing config test**
|
||||
|
||||
```python
|
||||
import os
|
||||
|
||||
from backend.ai_config import get_ai_status, load_deepseek_config
|
||||
|
||||
|
||||
def test_ai_status_reports_missing_key(monkeypatch):
|
||||
monkeypatch.delenv("DEEPSEEK_API_KEY", raising=False)
|
||||
|
||||
status = get_ai_status()
|
||||
|
||||
assert status["configured"] is False
|
||||
assert "DEEPSEEK_API_KEY" in status["message"]
|
||||
|
||||
|
||||
def test_load_deepseek_config_uses_defaults(monkeypatch):
|
||||
monkeypatch.setenv("DEEPSEEK_API_KEY", "test-key")
|
||||
monkeypatch.delenv("DEEPSEEK_BASE_URL", raising=False)
|
||||
monkeypatch.delenv("DEEPSEEK_MODEL", raising=False)
|
||||
|
||||
config = load_deepseek_config()
|
||||
|
||||
assert config.api_key == "test-key"
|
||||
assert config.base_url == "https://api.deepseek.com"
|
||||
assert config.model == "deepseek-chat"
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run test to verify it fails**
|
||||
|
||||
Run: `python tests\ai_config_test.py`
|
||||
|
||||
Expected: FAIL with missing module.
|
||||
|
||||
- [ ] **Step 3: Implement config and client**
|
||||
|
||||
Create `backend/ai_config.py`:
|
||||
|
||||
```python
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
import os
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class DeepSeekConfig:
|
||||
api_key: str
|
||||
base_url: str
|
||||
model: str
|
||||
|
||||
|
||||
def load_deepseek_config() -> DeepSeekConfig:
|
||||
return DeepSeekConfig(
|
||||
api_key=os.getenv("DEEPSEEK_API_KEY", "").strip(),
|
||||
base_url=os.getenv("DEEPSEEK_BASE_URL", "https://api.deepseek.com").strip().rstrip("/"),
|
||||
model=os.getenv("DEEPSEEK_MODEL", "deepseek-chat").strip(),
|
||||
)
|
||||
|
||||
|
||||
def get_ai_status() -> dict[str, object]:
|
||||
config = load_deepseek_config()
|
||||
if not config.api_key:
|
||||
return {
|
||||
"configured": False,
|
||||
"provider": "deepseek",
|
||||
"model": config.model,
|
||||
"message": "未配置 DEEPSEEK_API_KEY,请在 .env 或环境变量中填写。",
|
||||
}
|
||||
return {
|
||||
"configured": True,
|
||||
"provider": "deepseek",
|
||||
"model": config.model,
|
||||
"message": "DeepSeek API 已配置。",
|
||||
}
|
||||
```
|
||||
|
||||
Create `backend/deepseek_client.py`:
|
||||
|
||||
```python
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
from .ai_config import DeepSeekConfig
|
||||
|
||||
|
||||
class DeepSeekError(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
class DeepSeekClient:
|
||||
def __init__(self, config: DeepSeekConfig, timeout_seconds: int = 60):
|
||||
self.config = config
|
||||
self.timeout_seconds = timeout_seconds
|
||||
|
||||
def chat_json(self, system_prompt: str, user_payload: dict[str, object]) -> dict[str, object]:
|
||||
if not self.config.api_key:
|
||||
raise DeepSeekError("未配置 DEEPSEEK_API_KEY。")
|
||||
|
||||
body = json.dumps({
|
||||
"model": self.config.model,
|
||||
"messages": [
|
||||
{"role": "system", "content": system_prompt},
|
||||
{"role": "user", "content": json.dumps(user_payload, ensure_ascii=False)},
|
||||
],
|
||||
"response_format": {"type": "json_object"},
|
||||
}).encode("utf-8")
|
||||
request = urllib.request.Request(
|
||||
f"{self.config.base_url}/chat/completions",
|
||||
data=body,
|
||||
headers={
|
||||
"Authorization": f"Bearer {self.config.api_key}",
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
method="POST",
|
||||
)
|
||||
|
||||
try:
|
||||
with urllib.request.urlopen(request, timeout=self.timeout_seconds) as response:
|
||||
payload = json.loads(response.read().decode("utf-8"))
|
||||
except urllib.error.HTTPError as error:
|
||||
detail = error.read().decode("utf-8", errors="replace")
|
||||
raise DeepSeekError(f"DeepSeek 请求失败:{error.code} {detail}") from error
|
||||
except Exception as error:
|
||||
raise DeepSeekError(f"DeepSeek 请求失败:{error}") from error
|
||||
|
||||
content = payload.get("choices", [{}])[0].get("message", {}).get("content", "")
|
||||
try:
|
||||
return json.loads(content)
|
||||
except json.JSONDecodeError as error:
|
||||
raise DeepSeekError("DeepSeek 返回内容不是有效 JSON。") from error
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Run config test**
|
||||
|
||||
Run: `python tests\ai_config_test.py`
|
||||
|
||||
Expected: PASS with exit code 0.
|
||||
|
||||
### Task 3: Subtitle AI Orchestrator
|
||||
|
||||
**Files:**
|
||||
- Create: `backend/subtitle_ai.py`
|
||||
- Test: `tests/subtitle_ai_test.py`
|
||||
|
||||
- [ ] **Step 1: Write failing orchestration test**
|
||||
|
||||
```python
|
||||
from backend.subtitle_ai import process_subtitles_with_ai
|
||||
|
||||
|
||||
class FakeClient:
|
||||
def chat_json(self, system_prompt, user_payload):
|
||||
return {
|
||||
"translations": [
|
||||
{"index": 1, "zh": "我第一次做投资人是在 24 岁。"}
|
||||
]
|
||||
}
|
||||
|
||||
|
||||
def test_process_subtitles_with_ai_returns_clean_en_and_zh_vtt():
|
||||
raw = """WEBVTT
|
||||
|
||||
00:00:00.872 --> 00:00:04.959
|
||||
My first job as an investor was when I was 24 years old,
|
||||
|
||||
00:00:00.872 --> 00:00:04.959
|
||||
My first job as an investor was when I was 24 years old,
|
||||
"""
|
||||
|
||||
result = process_subtitles_with_ai(raw, FakeClient())
|
||||
|
||||
assert "My first job as an investor" in result["subtitle_en_content"]
|
||||
assert "我第一次做投资人是在 24 岁。" in result["subtitle_zh_content"]
|
||||
assert result["report"]["duplicate_count"] == 1
|
||||
assert result["report"]["translation_count"] == 1
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run test to verify it fails**
|
||||
|
||||
Run: `python tests\subtitle_ai_test.py`
|
||||
|
||||
Expected: FAIL with missing module.
|
||||
|
||||
- [ ] **Step 3: Implement orchestrator**
|
||||
|
||||
Create `backend/subtitle_ai.py`:
|
||||
|
||||
```python
|
||||
from __future__ import annotations
|
||||
|
||||
from .subtitle_tools import build_vtt, clean_english_subtitle
|
||||
|
||||
|
||||
TRANSLATION_SYSTEM_PROMPT = """
|
||||
你是英语学习产品的字幕翻译助手。输入是按顺序排列的英文字幕。
|
||||
请只返回 JSON,格式为 {"translations":[{"index":1,"zh":"中文翻译"}]}。
|
||||
要求:中文自然,适合英语学习;不要增删字幕条数;不要解释。
|
||||
""".strip()
|
||||
|
||||
|
||||
def process_subtitles_with_ai(english_content: str, client) -> dict[str, object]:
|
||||
cleaned = clean_english_subtitle(english_content)
|
||||
if not cleaned.cues:
|
||||
raise ValueError("英文字幕为空,无法处理。")
|
||||
|
||||
payload = {
|
||||
"cues": [
|
||||
{"index": index, "text": cue.text}
|
||||
for index, cue in enumerate(cleaned.cues, 1)
|
||||
]
|
||||
}
|
||||
response = client.chat_json(TRANSLATION_SYSTEM_PROMPT, payload)
|
||||
translations = response.get("translations")
|
||||
if not isinstance(translations, list):
|
||||
raise ValueError("AI 返回结果缺少 translations。")
|
||||
if len(translations) != len(cleaned.cues):
|
||||
raise ValueError("AI 返回的翻译条数和英文字幕条数不一致。")
|
||||
|
||||
zh_cues = []
|
||||
for cue, translation in zip(cleaned.cues, translations):
|
||||
zh_text = str(translation.get("zh", "")).strip()
|
||||
if not zh_text:
|
||||
raise ValueError("AI 返回了空翻译。")
|
||||
zh_cues.append({"start": cue.start, "end": cue.end, "text": zh_text})
|
||||
|
||||
return {
|
||||
"subtitle_en_content": build_vtt(cleaned.cues),
|
||||
"subtitle_zh_content": build_vtt(zh_cues),
|
||||
"report": {
|
||||
"original_count": cleaned.original_count,
|
||||
"cleaned_count": cleaned.cleaned_count,
|
||||
"duplicate_count": cleaned.duplicate_count,
|
||||
"empty_count": cleaned.empty_count,
|
||||
"translation_count": len(zh_cues),
|
||||
"timestamp_calibrated": False,
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Run test**
|
||||
|
||||
Run: `python tests\subtitle_ai_test.py`
|
||||
|
||||
Expected: PASS with exit code 0.
|
||||
|
||||
### Task 4: Backend API Endpoints
|
||||
|
||||
**Files:**
|
||||
- Modify: `backend/db.py`
|
||||
- Modify: `backend/main.py`
|
||||
- Test: `tests/ai_api_test.py`
|
||||
|
||||
- [ ] **Step 1: Add DB helper test**
|
||||
|
||||
Use an existing SQLite test pattern if present. If no test harness exists, test through the API in Step 2 instead.
|
||||
|
||||
- [ ] **Step 2: Implement DB helper**
|
||||
|
||||
In `backend/db.py`, add:
|
||||
|
||||
```python
|
||||
def upsert_video_subtitle(
|
||||
video_id: int,
|
||||
*,
|
||||
language_code: str,
|
||||
language_name: str,
|
||||
format: str,
|
||||
file_path: str,
|
||||
content: str,
|
||||
) -> None:
|
||||
with get_connection() as connection:
|
||||
connection.execute(
|
||||
"""
|
||||
INSERT INTO subtitles (
|
||||
video_id, language_code, language_name, format, file_path, content
|
||||
)
|
||||
VALUES (?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(video_id, language_code) DO UPDATE SET
|
||||
language_name = excluded.language_name,
|
||||
format = excluded.format,
|
||||
file_path = excluded.file_path,
|
||||
content = excluded.content,
|
||||
updated_at = CURRENT_TIMESTAMP
|
||||
""",
|
||||
(
|
||||
video_id,
|
||||
language_code,
|
||||
repair_mojibake_text(language_name),
|
||||
format,
|
||||
file_path,
|
||||
repair_mojibake_text(content),
|
||||
),
|
||||
)
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Add API endpoints**
|
||||
|
||||
In `backend/main.py`, import:
|
||||
|
||||
```python
|
||||
from .ai_config import get_ai_status, load_deepseek_config
|
||||
from .deepseek_client import DeepSeekClient, DeepSeekError
|
||||
from .subtitle_ai import process_subtitles_with_ai
|
||||
from .db import upsert_video_subtitle
|
||||
```
|
||||
|
||||
Add endpoints before static mounts:
|
||||
|
||||
```python
|
||||
@app.get("/api/ai/status")
|
||||
def api_ai_status() -> dict[str, object]:
|
||||
return get_ai_status()
|
||||
|
||||
|
||||
@app.post("/api/ai/test")
|
||||
def api_ai_test() -> dict[str, object]:
|
||||
status = get_ai_status()
|
||||
if not status["configured"]:
|
||||
raise HTTPException(status_code=400, detail=status["message"])
|
||||
return {"ok": True, "message": "DeepSeek API 配置已读取。"}
|
||||
|
||||
|
||||
@app.post("/api/videos/{video_id}/ai/subtitles")
|
||||
def api_process_video_subtitles(video_id: int) -> dict[str, object]:
|
||||
status = get_ai_status()
|
||||
if not status["configured"]:
|
||||
raise HTTPException(status_code=400, detail=status["message"])
|
||||
|
||||
video = get_video(video_id)
|
||||
if video is None:
|
||||
raise HTTPException(status_code=404, detail="视频不存在")
|
||||
english = video.get("subtitles", {}).get("en", {}).get("content", "")
|
||||
if not english:
|
||||
raise HTTPException(status_code=400, detail="请先上传英文字幕。")
|
||||
|
||||
try:
|
||||
result = process_subtitles_with_ai(english, DeepSeekClient(load_deepseek_config()))
|
||||
except (DeepSeekError, ValueError) as error:
|
||||
raise HTTPException(status_code=400, detail=str(error)) from error
|
||||
|
||||
upsert_video_subtitle(
|
||||
video_id,
|
||||
language_code="en",
|
||||
language_name="English",
|
||||
format="vtt",
|
||||
file_path=video.get("subtitles", {}).get("en", {}).get("filePath", ""),
|
||||
content=str(result["subtitle_en_content"]),
|
||||
)
|
||||
upsert_video_subtitle(
|
||||
video_id,
|
||||
language_code="zh",
|
||||
language_name="中文",
|
||||
format="vtt",
|
||||
file_path=video.get("subtitles", {}).get("zh", {}).get("filePath", ""),
|
||||
content=str(result["subtitle_zh_content"]),
|
||||
)
|
||||
|
||||
return {
|
||||
"video": get_video(video_id),
|
||||
"report": result["report"],
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Run backend syntax checks**
|
||||
|
||||
Run: `python -m py_compile backend\main.py backend\db.py backend\ai_config.py backend\deepseek_client.py backend\subtitle_ai.py backend\subtitle_tools.py`
|
||||
|
||||
Expected: PASS with exit code 0.
|
||||
|
||||
### Task 5: Admin UI
|
||||
|
||||
**Files:**
|
||||
- Modify: `admin.html`
|
||||
- Modify: `admin.js`
|
||||
- Modify: `styles.css`
|
||||
|
||||
- [ ] **Step 1: Add AI panel markup**
|
||||
|
||||
In `admin.html`, place near `adminSubtitleEditor`:
|
||||
|
||||
```html
|
||||
<section class="admin-ai-panel">
|
||||
<div>
|
||||
<h3>AI 字幕处理</h3>
|
||||
<p id="aiSubtitleStatus">正在读取 AI 配置...</p>
|
||||
</div>
|
||||
<div class="admin-ai-actions">
|
||||
<button id="testAiBtn" class="secondary-action" type="button">测试 AI 连接</button>
|
||||
<button id="processAiSubtitlesBtn" type="button">AI 修复并翻译字幕</button>
|
||||
</div>
|
||||
<p id="aiSubtitleReport" class="admin-ai-report" hidden></p>
|
||||
</section>
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Wire elements in `admin.js`**
|
||||
|
||||
Add to `els`:
|
||||
|
||||
```javascript
|
||||
aiStatus: IS_BROWSER ? document.querySelector("#aiSubtitleStatus") : null,
|
||||
aiReport: IS_BROWSER ? document.querySelector("#aiSubtitleReport") : null,
|
||||
testAiBtn: IS_BROWSER ? document.querySelector("#testAiBtn") : null,
|
||||
processAiSubtitlesBtn: IS_BROWSER ? document.querySelector("#processAiSubtitlesBtn") : null,
|
||||
```
|
||||
|
||||
In `initializeAdmin()` add:
|
||||
|
||||
```javascript
|
||||
els.testAiBtn?.addEventListener("click", testAiConnection);
|
||||
els.processAiSubtitlesBtn?.addEventListener("click", processAiSubtitles);
|
||||
loadAiStatus();
|
||||
```
|
||||
|
||||
Add functions:
|
||||
|
||||
```javascript
|
||||
async function loadAiStatus() {
|
||||
if (!els.aiStatus) return;
|
||||
try {
|
||||
const status = await apiRequest("/api/ai/status");
|
||||
els.aiStatus.textContent = status.message || "AI 状态未知。";
|
||||
els.processAiSubtitlesBtn.disabled = !status.configured || !editingVideo;
|
||||
} catch (error) {
|
||||
els.aiStatus.textContent = error.message || "AI 状态读取失败。";
|
||||
els.processAiSubtitlesBtn.disabled = true;
|
||||
}
|
||||
}
|
||||
|
||||
async function testAiConnection() {
|
||||
try {
|
||||
const result = await apiRequest("/api/ai/test", { method: "POST" });
|
||||
showMessage(result.message || "AI 连接正常。");
|
||||
await loadAiStatus();
|
||||
} catch (error) {
|
||||
showMessage(error.message || "AI 连接失败。", true);
|
||||
}
|
||||
}
|
||||
|
||||
async function processAiSubtitles() {
|
||||
if (!editingVideo) {
|
||||
showMessage("请先选择一个素材。", true);
|
||||
return;
|
||||
}
|
||||
els.processAiSubtitlesBtn.disabled = true;
|
||||
els.processAiSubtitlesBtn.textContent = "AI 处理中...";
|
||||
try {
|
||||
const result = await apiRequest(`/api/videos/${editingVideo.id}/ai/subtitles`, { method: "POST" });
|
||||
const report = result.report || {};
|
||||
els.aiReport.hidden = false;
|
||||
els.aiReport.textContent = `处理完成:删除重复 ${report.duplicate_count || 0} 条,删除空白 ${report.empty_count || 0} 条,生成中文 ${report.translation_count || 0} 条。`;
|
||||
await loadVideos();
|
||||
const updated = videos.find((video) => String(video.id) === String(editingVideo.id));
|
||||
if (updated) startEditingVideo(updated);
|
||||
} catch (error) {
|
||||
showMessage(error.message || "AI 字幕处理失败。", true);
|
||||
} finally {
|
||||
els.processAiSubtitlesBtn.textContent = "AI 修复并翻译字幕";
|
||||
await loadAiStatus();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Call `loadAiStatus()` inside `startEditingVideo()` and `resetFormMode()`.
|
||||
|
||||
- [ ] **Step 3: Add CSS**
|
||||
|
||||
In `styles.css`, add:
|
||||
|
||||
```css
|
||||
.admin-ai-panel {
|
||||
display: grid;
|
||||
gap: 10px;
|
||||
padding: 12px;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 8px;
|
||||
background: var(--panel-soft);
|
||||
}
|
||||
|
||||
.admin-ai-panel h3,
|
||||
.admin-ai-panel p {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.admin-ai-actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.admin-ai-report {
|
||||
color: var(--muted);
|
||||
font-size: 13px;
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Run frontend checks**
|
||||
|
||||
Run:
|
||||
|
||||
```powershell
|
||||
node --check admin.js
|
||||
node --check app.js
|
||||
```
|
||||
|
||||
Expected: PASS with exit code 0.
|
||||
|
||||
### Task 6: Verification
|
||||
|
||||
**Files:**
|
||||
- No new files.
|
||||
|
||||
- [ ] **Step 1: Run Python tests**
|
||||
|
||||
Run:
|
||||
|
||||
```powershell
|
||||
python tests\subtitle_tools_test.py
|
||||
python tests\ai_config_test.py
|
||||
python tests\subtitle_ai_test.py
|
||||
python tests\encoding_repair_test.py
|
||||
python -m py_compile backend\main.py backend\db.py
|
||||
```
|
||||
|
||||
Expected: all exit 0.
|
||||
|
||||
- [ ] **Step 2: Run frontend tests**
|
||||
|
||||
Run:
|
||||
|
||||
```powershell
|
||||
node --check admin.js
|
||||
node --check app.js
|
||||
node --check home.js
|
||||
node tests\admin-file-input.test.mjs
|
||||
node tests\admin-subtitle-editor.test.mjs
|
||||
node tests\progress-helpers.test.mjs
|
||||
```
|
||||
|
||||
Expected: all exit 0.
|
||||
|
||||
- [ ] **Step 3: Manual local check without API key**
|
||||
|
||||
Start the local server and open `http://127.0.0.1:8000/admin.html`.
|
||||
|
||||
Expected:
|
||||
|
||||
- Admin page loads.
|
||||
- AI status says `未配置 DEEPSEEK_API_KEY`.
|
||||
- Clicking `AI 修复并翻译字幕` does not crash the page.
|
||||
|
||||
- [ ] **Step 4: Manual local check with API key**
|
||||
|
||||
Set environment variable:
|
||||
|
||||
```powershell
|
||||
$env:DEEPSEEK_API_KEY="your_key_here"
|
||||
```
|
||||
|
||||
Restart server and open admin page.
|
||||
|
||||
Expected:
|
||||
|
||||
- AI status says DeepSeek is configured.
|
||||
- Processing a material with English subtitles creates a Chinese subtitle track.
|
||||
- Report shows duplicate and translation counts.
|
||||
|
||||
@@ -0,0 +1,300 @@
|
||||
# Speaking Lab Focused Learning UI Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** Apply a clean English-learning UI direction with icon-led dashboard cards and a more focused study workspace.
|
||||
|
||||
**Architecture:** Keep the upgrade frontend-only. `home.js` adds icon metadata for metric cards, while `styles.css` changes visual treatment for the home dashboard, material cards, study video panel, subtitle prompt, toolbar, and transcript states. No backend, README, or data-model changes are required.
|
||||
|
||||
**Tech Stack:** Vanilla JavaScript, CSS, HTML, existing FastAPI server for browser verification.
|
||||
|
||||
---
|
||||
|
||||
## Task 1: Add Metric Icon Metadata
|
||||
|
||||
**Files:**
|
||||
- Modify: `F:\ooo\speaking-practice-local\home.js`
|
||||
|
||||
- [ ] **Step 1: Update `getMetricItems(metrics)`**
|
||||
|
||||
Replace each metric object with an `icon` and `tone`:
|
||||
|
||||
```js
|
||||
function getMetricItems(metrics) {
|
||||
return [
|
||||
{ key: "all", label: "当前素材", value: metrics.total, hint: "持续更新中", icon: "::", tone: "blue" },
|
||||
{ key: "studied", label: "已学习", value: metrics.studied, hint: "我的打卡", icon: "✓", tone: "green" },
|
||||
{ key: "unstudied", label: "未学习", value: metrics.unstudied, hint: "未完成", icon: "○", tone: "slate" },
|
||||
{ key: "favorites", label: "已收藏", value: metrics.favorites, hint: "收藏的视频", icon: "♡", tone: "rose" },
|
||||
{ key: "difficult", label: "难句素材", value: metrics.difficult, hint: "重点复习", icon: "!", tone: "amber" },
|
||||
];
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Update metric button markup in `renderDashboard()`**
|
||||
|
||||
Use:
|
||||
|
||||
```js
|
||||
button.className = `home-metric tone-${item.tone}${activeStatus === item.key ? " active" : ""}`;
|
||||
button.dataset.status = item.key;
|
||||
button.innerHTML = `
|
||||
<span class="home-metric-icon" aria-hidden="true">${item.icon}</span>
|
||||
<span class="home-metric-copy">
|
||||
<span class="home-metric-label">${item.label}</span>
|
||||
<small>${item.hint}</small>
|
||||
</span>
|
||||
<strong>${item.value}</strong>
|
||||
`;
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Run syntax check**
|
||||
|
||||
Run:
|
||||
|
||||
```powershell
|
||||
node --check home.js
|
||||
```
|
||||
|
||||
Expected: no output.
|
||||
|
||||
## Task 2: Polish Home Dashboard And Cards
|
||||
|
||||
**Files:**
|
||||
- Modify: `F:\ooo\speaking-practice-local\styles.css`
|
||||
|
||||
- [ ] **Step 1: Update root colors**
|
||||
|
||||
Use a calm learning palette:
|
||||
|
||||
```css
|
||||
:root {
|
||||
color-scheme: light;
|
||||
--bg: #f4f7fb;
|
||||
--panel: #ffffff;
|
||||
--panel-soft: #f7fafc;
|
||||
--ink: #172033;
|
||||
--muted: #667085;
|
||||
--line: #dfe6ef;
|
||||
--accent: #0f2742;
|
||||
--brand: #0f766e;
|
||||
--brand-soft: #e4f5f1;
|
||||
--gold: #c98a12;
|
||||
--danger: #b42318;
|
||||
--shadow: 0 12px 30px rgba(25, 37, 59, 0.08);
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Replace metric card CSS**
|
||||
|
||||
Update `.home-metric` and related selectors to icon-card layout:
|
||||
|
||||
```css
|
||||
.home-metric {
|
||||
min-height: 76px;
|
||||
display: grid;
|
||||
grid-template-columns: 38px minmax(0, 1fr) auto;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
padding: 12px;
|
||||
text-align: left;
|
||||
border-radius: 8px;
|
||||
background: var(--panel);
|
||||
box-shadow: var(--shadow);
|
||||
}
|
||||
|
||||
.home-metric-icon {
|
||||
width: 34px;
|
||||
height: 34px;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
border-radius: 10px;
|
||||
font-weight: 900;
|
||||
}
|
||||
|
||||
.home-metric-copy,
|
||||
.home-metric-label {
|
||||
display: block;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.home-metric-label {
|
||||
font-weight: 800;
|
||||
}
|
||||
|
||||
.home-metric small {
|
||||
color: var(--muted);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.home-metric strong {
|
||||
font-size: 24px;
|
||||
line-height: 1;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.home-metric.tone-blue .home-metric-icon {
|
||||
color: #087ea4;
|
||||
background: #e6f7fb;
|
||||
}
|
||||
|
||||
.home-metric.tone-green .home-metric-icon {
|
||||
color: #047857;
|
||||
background: #e9f9f0;
|
||||
}
|
||||
|
||||
.home-metric.tone-slate .home-metric-icon {
|
||||
color: #475467;
|
||||
background: #eef2f7;
|
||||
}
|
||||
|
||||
.home-metric.tone-rose .home-metric-icon {
|
||||
color: #be123c;
|
||||
background: #fff1f4;
|
||||
}
|
||||
|
||||
.home-metric.tone-amber .home-metric-icon {
|
||||
color: #9a5c00;
|
||||
background: #fff7df;
|
||||
}
|
||||
|
||||
.home-metric.active {
|
||||
border-color: #b9dcd5;
|
||||
background: #f0fbf8;
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Lighten card covers**
|
||||
|
||||
Update cover gradients to avoid heavy admin feel:
|
||||
|
||||
```css
|
||||
.home-cover.tone-1 { background: linear-gradient(135deg, #0f766e, #1d6f8f); }
|
||||
.home-cover.tone-2 { background: linear-gradient(135deg, #2563eb, #0f766e); }
|
||||
.home-cover.tone-3 { background: linear-gradient(135deg, #475569, #2563eb); }
|
||||
.home-cover.tone-4 { background: linear-gradient(135deg, #9a5c00, #be6b21); }
|
||||
.home-cover.tone-5 { background: linear-gradient(135deg, #334155, #0f766e); }
|
||||
```
|
||||
|
||||
## Task 3: Polish Study Workspace
|
||||
|
||||
**Files:**
|
||||
- Modify: `F:\ooo\speaking-practice-local\styles.css`
|
||||
|
||||
- [ ] **Step 1: Add focused study styling**
|
||||
|
||||
Update existing study selectors:
|
||||
|
||||
```css
|
||||
.video-panel,
|
||||
.transcript-panel,
|
||||
.lesson-rail {
|
||||
border-color: #dce5ee;
|
||||
}
|
||||
|
||||
.video-frame {
|
||||
background: #0b1220;
|
||||
}
|
||||
|
||||
.tool-row {
|
||||
background: #ffffff;
|
||||
}
|
||||
|
||||
.tool-row button {
|
||||
border-color: #d8e2ec;
|
||||
background: #f8fafc;
|
||||
font-weight: 650;
|
||||
}
|
||||
|
||||
.tool-row button:hover {
|
||||
border-color: #b9dcd5;
|
||||
background: var(--brand-soft);
|
||||
}
|
||||
|
||||
.subtitle-card {
|
||||
min-height: 116px;
|
||||
padding: 18px 28px;
|
||||
background: #f8fbfb;
|
||||
}
|
||||
|
||||
#primarySubtitle {
|
||||
font-size: 22px;
|
||||
letter-spacing: 0;
|
||||
}
|
||||
|
||||
#secondarySubtitle {
|
||||
color: #667085;
|
||||
font-size: 15px;
|
||||
}
|
||||
|
||||
.line-button {
|
||||
border-radius: 8px;
|
||||
}
|
||||
|
||||
.line-button.active {
|
||||
background: #f4fbf9;
|
||||
border-color: #b9dcd5;
|
||||
box-shadow: inset 4px 0 0 var(--brand);
|
||||
}
|
||||
|
||||
.line-button.is-practiced {
|
||||
background: #f7fdf9;
|
||||
}
|
||||
|
||||
.line-button.is-difficult {
|
||||
background: #fffaf0;
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Confirm mobile styles still exist**
|
||||
|
||||
Run:
|
||||
|
||||
```powershell
|
||||
rg -n "@media \\(max-width: 860px\\)|@media \\(max-width: 720px\\)" styles.css
|
||||
```
|
||||
|
||||
Expected: both media blocks still exist.
|
||||
|
||||
## Task 4: Verify
|
||||
|
||||
**Files:**
|
||||
- Verify: `F:\ooo\speaking-practice-local\home.js`
|
||||
- Verify: `F:\ooo\speaking-practice-local\app.js`
|
||||
- Verify: `F:\ooo\speaking-practice-local\admin.js`
|
||||
- Verify: `F:\ooo\speaking-practice-local\styles.css`
|
||||
|
||||
- [ ] **Step 1: Run automated checks**
|
||||
|
||||
Run:
|
||||
|
||||
```powershell
|
||||
node --check home.js
|
||||
node --check app.js
|
||||
node --check admin.js
|
||||
python -m py_compile backend\main.py backend\db.py
|
||||
node tests\progress-helpers.test.mjs
|
||||
node tests\admin-file-input.test.mjs
|
||||
```
|
||||
|
||||
Expected: all pass.
|
||||
|
||||
- [ ] **Step 2: Browser check home page**
|
||||
|
||||
Open:
|
||||
|
||||
```text
|
||||
http://127.0.0.1:8000/
|
||||
```
|
||||
|
||||
Confirm metric cards show icons and still filter.
|
||||
|
||||
- [ ] **Step 3: Browser check study page**
|
||||
|
||||
Open:
|
||||
|
||||
```text
|
||||
http://127.0.0.1:8000/study.html
|
||||
```
|
||||
|
||||
Confirm subtitle prompt, toolbar, and transcript feel more like a learning workspace and no text overlaps.
|
||||
@@ -0,0 +1,762 @@
|
||||
# Speaking Lab Home Dashboard v1 Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** Upgrade the home page into a learning dashboard with overview metrics, status filters, richer material cards, and home-page favorite toggles.
|
||||
|
||||
**Architecture:** Keep the feature entirely in the existing frontend home page. `index.html` owns the dashboard markup, `home.js` owns browser-side metric/filter/card behavior using `/api/videos` plus existing localStorage state, and `styles.css` owns the responsive layout and card styling. No backend, README, or deployment changes are required.
|
||||
|
||||
**Tech Stack:** Vanilla HTML, CSS, JavaScript, FastAPI `/api/videos`, browser `localStorage`.
|
||||
|
||||
---
|
||||
|
||||
## File Structure
|
||||
|
||||
- Modify `F:\ooo\speaking-practice-local\index.html`: add dashboard overview panel and metric button containers.
|
||||
- Modify `F:\ooo\speaking-practice-local\home.js`: add active status filter, dashboard metrics, personal filter empty states, favorite toggles, and richer card metadata.
|
||||
- Modify `F:\ooo\speaking-practice-local\styles.css`: style the two-column dashboard, metric buttons, upgraded cards, and mobile stacking.
|
||||
- Do not modify `F:\ooo\speaking-practice-local\README.md`.
|
||||
- Do not modify backend files unless verification exposes an unrelated syntax issue.
|
||||
|
||||
## Task 1: Add Home Dashboard Markup
|
||||
|
||||
**Files:**
|
||||
- Modify: `F:\ooo\speaking-practice-local\index.html`
|
||||
|
||||
- [ ] **Step 1: Replace the home main layout**
|
||||
|
||||
Replace the current `<main class="home-shell">...</main>` block with this structure:
|
||||
|
||||
```html
|
||||
<main class="home-shell">
|
||||
<aside class="home-dashboard" aria-label="学习概览">
|
||||
<div class="home-dashboard-title">
|
||||
<span>学习概览</span>
|
||||
<strong id="homeDashboardUser">本地学习</strong>
|
||||
</div>
|
||||
<div id="homeMetricFilters" class="home-metrics"></div>
|
||||
</aside>
|
||||
|
||||
<section class="home-library">
|
||||
<div class="home-heading">
|
||||
<div>
|
||||
<h2>素材库</h2>
|
||||
<p>搜索素材,按分类和学习状态继续练习。</p>
|
||||
</div>
|
||||
<a class="primary-link" href="./study.html">进入学习页</a>
|
||||
</div>
|
||||
|
||||
<div id="homeCategoryFilters" class="home-categories"></div>
|
||||
<div id="homeStatus" class="home-status"></div>
|
||||
<div id="homeGrid" class="home-grid"></div>
|
||||
</section>
|
||||
</main>
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Verify the markup has all IDs needed by JavaScript**
|
||||
|
||||
Run:
|
||||
|
||||
```powershell
|
||||
rg -n "homeDashboardUser|homeMetricFilters|homeCategoryFilters|homeStatus|homeGrid" index.html
|
||||
```
|
||||
|
||||
Expected: each ID appears exactly once.
|
||||
|
||||
## Task 2: Implement Dashboard Metrics And Filters
|
||||
|
||||
**Files:**
|
||||
- Modify: `F:\ooo\speaking-practice-local\home.js`
|
||||
|
||||
- [ ] **Step 1: Add new DOM references and status state**
|
||||
|
||||
Extend the `els` object with:
|
||||
|
||||
```js
|
||||
dashboardUser: document.querySelector("#homeDashboardUser"),
|
||||
metricFilters: document.querySelector("#homeMetricFilters"),
|
||||
```
|
||||
|
||||
Add this state next to `activeTag`:
|
||||
|
||||
```js
|
||||
let activeStatus = "all";
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Update render flow**
|
||||
|
||||
In `renderHome()`, call `renderDashboard()` before categories are rendered:
|
||||
|
||||
```js
|
||||
function renderHome() {
|
||||
renderDashboard();
|
||||
renderCategories();
|
||||
const filtered = getFilteredVideos();
|
||||
const emptyMessage = getEmptyMessage(filtered);
|
||||
|
||||
els.status.textContent = filtered.length ? `${filtered.length} 个素材` : emptyMessage;
|
||||
els.grid.innerHTML = "";
|
||||
|
||||
if (!filtered.length) return;
|
||||
|
||||
const fragment = document.createDocumentFragment();
|
||||
filtered.forEach((video) => {
|
||||
fragment.appendChild(createVideoCard(video));
|
||||
});
|
||||
els.grid.appendChild(fragment);
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Add dashboard rendering helpers**
|
||||
|
||||
Add these functions below `renderCategories()`:
|
||||
|
||||
```js
|
||||
function renderDashboard() {
|
||||
const user = getCurrentUser();
|
||||
const metrics = calculateDashboardMetrics(user);
|
||||
els.dashboardUser.textContent = user ? user.email : "登录后记录进度";
|
||||
els.metricFilters.innerHTML = "";
|
||||
|
||||
getMetricItems(metrics).forEach((item) => {
|
||||
const button = document.createElement("button");
|
||||
button.type = "button";
|
||||
button.className = `home-metric${activeStatus === item.key ? " active" : ""}`;
|
||||
button.dataset.status = item.key;
|
||||
button.innerHTML = `
|
||||
<span>${item.label}</span>
|
||||
<strong>${item.value}</strong>
|
||||
<small>${item.hint}</small>
|
||||
`;
|
||||
button.addEventListener("click", () => {
|
||||
activeStatus = item.key;
|
||||
renderHome();
|
||||
});
|
||||
els.metricFilters.appendChild(button);
|
||||
});
|
||||
}
|
||||
|
||||
function getMetricItems(metrics) {
|
||||
return [
|
||||
{ key: "all", label: "当前素材", value: metrics.total, hint: "可学习内容" },
|
||||
{ key: "studied", label: "已学", value: metrics.studied, hint: "有学习记录" },
|
||||
{ key: "unstudied", label: "未学", value: metrics.unstudied, hint: "还未开始" },
|
||||
{ key: "favorites", label: "已收藏", value: metrics.favorites, hint: "收藏的视频" },
|
||||
{ key: "difficult", label: "难句素材", value: metrics.difficult, hint: "含难句标记" },
|
||||
];
|
||||
}
|
||||
|
||||
function calculateDashboardMetrics(user) {
|
||||
const loadedIds = new Set(videos.map((video) => String(video.id)));
|
||||
const studied = videos.filter((video) => hasStudyProgress(user, video.id)).length;
|
||||
const favoriteIds = new Set((user?.favorites || []).map(String));
|
||||
const favorites = [...favoriteIds].filter((id) => loadedIds.has(id)).length;
|
||||
const difficult = videos.filter((video) => getVideoProgress(user, video.id).difficultLineIndexes.length > 0).length;
|
||||
|
||||
return {
|
||||
total: videos.length,
|
||||
studied,
|
||||
unstudied: Math.max(0, videos.length - studied),
|
||||
favorites,
|
||||
difficult,
|
||||
};
|
||||
}
|
||||
|
||||
function hasStudyProgress(user, videoId) {
|
||||
if (!user) return false;
|
||||
const progress = getVideoProgress(user, videoId);
|
||||
return progress.currentTime > 1
|
||||
|| progress.activeLineIndex > 0
|
||||
|| progress.practicedLineIndexes.length > 0;
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Extend filtering**
|
||||
|
||||
Replace `getFilteredVideos()` with:
|
||||
|
||||
```js
|
||||
function getFilteredVideos() {
|
||||
const query = els.searchInput.value.trim().toLowerCase();
|
||||
const user = getCurrentUser();
|
||||
|
||||
return videos.filter((video) => {
|
||||
const tags = normalizeTags(video.tags);
|
||||
const matchesTag = activeTag === "全部" || tags.includes(activeTag);
|
||||
const matchesStatus = matchesStatusFilter(video, user);
|
||||
const haystack = [video.title, video.speaker, video.description, tags.join(" ")]
|
||||
.join(" ")
|
||||
.toLowerCase();
|
||||
return matchesTag && matchesStatus && (!query || haystack.includes(query));
|
||||
});
|
||||
}
|
||||
|
||||
function matchesStatusFilter(video, user) {
|
||||
if (activeStatus === "all") return true;
|
||||
if (activeStatus === "studied") return hasStudyProgress(user, video.id);
|
||||
if (activeStatus === "unstudied") return !hasStudyProgress(user, video.id);
|
||||
if (activeStatus === "favorites") return Boolean(user?.favorites.map(String).includes(String(video.id)));
|
||||
if (activeStatus === "difficult") return getVideoProgress(user, video.id).difficultLineIndexes.length > 0;
|
||||
return true;
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 5: Add empty-state messaging**
|
||||
|
||||
Add this function below the filtering helpers:
|
||||
|
||||
```js
|
||||
function getEmptyMessage(filtered) {
|
||||
const user = getCurrentUser();
|
||||
const query = els.searchInput.value.trim();
|
||||
|
||||
if (!videos.length) {
|
||||
return isAdmin(user) ? "还没有素材,去后台添加第一个素材。" : "暂无素材。";
|
||||
}
|
||||
if (!user && ["studied", "favorites", "difficult"].includes(activeStatus)) {
|
||||
return "登录后可以查看你的学习记录。";
|
||||
}
|
||||
if (activeStatus === "favorites") return "还没有收藏素材。";
|
||||
if (activeStatus === "difficult") return "还没有标记难句。";
|
||||
if (query || activeTag !== "全部") return "没有匹配的素材。";
|
||||
return filtered.length ? "" : "没有匹配的素材。";
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 6: Syntax check**
|
||||
|
||||
Run:
|
||||
|
||||
```powershell
|
||||
node --check home.js
|
||||
```
|
||||
|
||||
Expected: no output and exit code 0.
|
||||
|
||||
## Task 3: Upgrade Material Cards
|
||||
|
||||
**Files:**
|
||||
- Modify: `F:\ooo\speaking-practice-local\home.js`
|
||||
- Modify: `F:\ooo\speaking-practice-local\styles.css`
|
||||
|
||||
- [ ] **Step 1: Replace `createVideoCard(video)`**
|
||||
|
||||
Replace the current function with:
|
||||
|
||||
```js
|
||||
function createVideoCard(video) {
|
||||
const card = document.createElement("article");
|
||||
const user = getCurrentUser();
|
||||
const tags = normalizeTags(video.tags);
|
||||
const subtitleLabel = getSubtitleLabel(video);
|
||||
const totalLines = getDefaultCueCount(video);
|
||||
const progress = getVideoProgress(user, video.id);
|
||||
const summary = calculatePracticeSummary(progress, totalLines);
|
||||
const progressLabel = formatProgressSummary(progress, totalLines);
|
||||
const difficultCount = progress.difficultLineIndexes.filter((index) => index < totalLines || totalLines === 0).length;
|
||||
const coverTone = getCoverTone(video.id);
|
||||
const isFavorite = Boolean(user?.favorites.map(String).includes(String(video.id)));
|
||||
|
||||
card.className = "home-card";
|
||||
card.innerHTML = `
|
||||
<div class="home-cover tone-${coverTone}">
|
||||
<span class="home-cover-badge"></span>
|
||||
<button class="home-favorite" type="button" aria-label="收藏素材"></button>
|
||||
<strong></strong>
|
||||
</div>
|
||||
<a class="home-card-link" href="./study.html?video=${encodeURIComponent(video.id)}">
|
||||
<div class="home-card-body">
|
||||
<h3></h3>
|
||||
<p class="home-card-meta"></p>
|
||||
<div class="home-card-tags"></div>
|
||||
<dl class="home-card-stats">
|
||||
<div>
|
||||
<dt>句子</dt>
|
||||
<dd></dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>进度</dt>
|
||||
<dd></dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>难句</dt>
|
||||
<dd></dd>
|
||||
</div>
|
||||
</dl>
|
||||
<p class="home-card-subtitles"></p>
|
||||
<p class="home-progress" hidden></p>
|
||||
</div>
|
||||
</a>
|
||||
`;
|
||||
|
||||
card.querySelector(".home-cover-badge").textContent = tags[0] || "素材";
|
||||
card.querySelector(".home-cover strong").textContent = getCoverText(video.title);
|
||||
card.querySelector("h3").textContent = video.title || "Untitled";
|
||||
card.querySelector(".home-card-meta").textContent = video.speaker || "Unknown";
|
||||
card.querySelector(".home-card-tags").append(...tags.map(createTagPill));
|
||||
card.querySelector(".home-card-subtitles").textContent = subtitleLabel;
|
||||
|
||||
const statValues = card.querySelectorAll(".home-card-stats dd");
|
||||
statValues[0].textContent = totalLines ? `${totalLines}` : "-";
|
||||
statValues[1].textContent = totalLines ? `${summary.percent}%` : "未开始";
|
||||
statValues[2].textContent = `${difficultCount}`;
|
||||
|
||||
const favorite = card.querySelector(".home-favorite");
|
||||
favorite.textContent = isFavorite ? "已收藏" : "收藏";
|
||||
favorite.classList.toggle("active", isFavorite);
|
||||
favorite.addEventListener("click", (event) => {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
toggleFavorite(video.id);
|
||||
});
|
||||
|
||||
const progressNode = card.querySelector(".home-progress");
|
||||
progressNode.textContent = progressLabel || "还未开始";
|
||||
progressNode.hidden = false;
|
||||
|
||||
return card;
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Add favorite toggle helper**
|
||||
|
||||
Add this function below `loginOrRegister()`:
|
||||
|
||||
```js
|
||||
function toggleFavorite(videoId) {
|
||||
const user = getCurrentUser();
|
||||
if (!user) {
|
||||
alert("请先登录。第一版会自动注册新邮箱。");
|
||||
return;
|
||||
}
|
||||
|
||||
const key = String(videoId);
|
||||
const favorites = new Set((user.favorites || []).map(String));
|
||||
if (favorites.has(key)) {
|
||||
favorites.delete(key);
|
||||
} else {
|
||||
favorites.add(key);
|
||||
}
|
||||
|
||||
user.favorites = [...favorites];
|
||||
saveState();
|
||||
renderHome();
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Syntax check**
|
||||
|
||||
Run:
|
||||
|
||||
```powershell
|
||||
node --check home.js
|
||||
```
|
||||
|
||||
Expected: no output and exit code 0.
|
||||
|
||||
## Task 4: Style Dashboard And Upgraded Cards
|
||||
|
||||
**Files:**
|
||||
- Modify: `F:\ooo\speaking-practice-local\styles.css`
|
||||
|
||||
- [ ] **Step 1: Replace home layout styles**
|
||||
|
||||
Replace the existing `.home-shell`, `.home-library`, `.home-heading`, `.home-grid`, `.home-card`, `.home-card-link`, `.home-cover`, `.home-card-body`, `.home-card-meta`, `.home-card-subtitles`, `.home-progress`, `.home-card-tags`, and related home card blocks with the updated home section styles below:
|
||||
|
||||
```css
|
||||
.home-shell {
|
||||
display: grid;
|
||||
grid-template-columns: 260px minmax(0, 1fr);
|
||||
gap: 18px;
|
||||
max-width: 1240px;
|
||||
margin: 0 auto;
|
||||
padding: 20px 24px 40px;
|
||||
}
|
||||
|
||||
.home-dashboard,
|
||||
.home-library {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.home-dashboard {
|
||||
align-self: start;
|
||||
position: sticky;
|
||||
top: 82px;
|
||||
display: grid;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.home-dashboard-title {
|
||||
padding: 14px;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 8px;
|
||||
background: var(--panel);
|
||||
box-shadow: var(--shadow);
|
||||
}
|
||||
|
||||
.home-dashboard-title span,
|
||||
.home-dashboard-title strong {
|
||||
display: block;
|
||||
}
|
||||
|
||||
.home-dashboard-title span {
|
||||
color: var(--muted);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.home-dashboard-title strong {
|
||||
margin-top: 4px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
font-size: 15px;
|
||||
}
|
||||
|
||||
.home-metrics {
|
||||
display: grid;
|
||||
gap: 9px;
|
||||
}
|
||||
|
||||
.home-metric {
|
||||
min-height: 72px;
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr) auto;
|
||||
align-items: center;
|
||||
gap: 4px 10px;
|
||||
padding: 11px 12px;
|
||||
text-align: left;
|
||||
border-radius: 8px;
|
||||
background: var(--panel);
|
||||
box-shadow: var(--shadow);
|
||||
}
|
||||
|
||||
.home-metric span,
|
||||
.home-metric small {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.home-metric span {
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.home-metric strong {
|
||||
font-size: 24px;
|
||||
line-height: 1;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.home-metric small {
|
||||
grid-column: 1 / -1;
|
||||
color: var(--muted);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.home-metric.active {
|
||||
color: #fff;
|
||||
border-color: var(--accent);
|
||||
background: var(--accent);
|
||||
}
|
||||
|
||||
.home-metric.active small {
|
||||
color: rgba(255, 255, 255, 0.72);
|
||||
}
|
||||
|
||||
.home-heading {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: flex-start;
|
||||
gap: 16px;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
.home-heading h2 {
|
||||
margin: 0;
|
||||
font-size: 24px;
|
||||
}
|
||||
|
||||
.home-heading p {
|
||||
margin: 6px 0 0;
|
||||
color: var(--muted);
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.home-categories {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
overflow-x: auto;
|
||||
padding: 2px 0 12px;
|
||||
}
|
||||
|
||||
.home-status {
|
||||
min-height: 22px;
|
||||
color: var(--muted);
|
||||
font-size: 13px;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
|
||||
.home-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
|
||||
gap: 14px;
|
||||
}
|
||||
|
||||
.home-card {
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 8px;
|
||||
background: var(--panel);
|
||||
box-shadow: var(--shadow);
|
||||
}
|
||||
|
||||
.home-card-link {
|
||||
display: block;
|
||||
color: inherit;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.home-card:hover .home-cover {
|
||||
filter: saturate(1.08);
|
||||
}
|
||||
|
||||
.home-cover {
|
||||
position: relative;
|
||||
min-height: 138px;
|
||||
display: grid;
|
||||
align-content: space-between;
|
||||
padding: 14px;
|
||||
color: #fff;
|
||||
background: #0f766e;
|
||||
}
|
||||
|
||||
.home-favorite {
|
||||
position: absolute;
|
||||
top: 10px;
|
||||
right: 10px;
|
||||
min-height: 28px;
|
||||
border-color: rgba(255, 255, 255, 0.38);
|
||||
color: #fff;
|
||||
background: rgba(17, 24, 39, 0.3);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.home-favorite:hover,
|
||||
.home-favorite.active {
|
||||
color: #111827;
|
||||
background: #fff;
|
||||
border-color: #fff;
|
||||
}
|
||||
|
||||
.home-cover.tone-1 {
|
||||
background: linear-gradient(135deg, #0f766e, #164e63);
|
||||
}
|
||||
|
||||
.home-cover.tone-2 {
|
||||
background: linear-gradient(135deg, #7c3aed, #0f766e);
|
||||
}
|
||||
|
||||
.home-cover.tone-3 {
|
||||
background: linear-gradient(135deg, #1d4ed8, #4338ca);
|
||||
}
|
||||
|
||||
.home-cover.tone-4 {
|
||||
background: linear-gradient(135deg, #b45309, #be123c);
|
||||
}
|
||||
|
||||
.home-cover.tone-5 {
|
||||
background: linear-gradient(135deg, #334155, #0f766e);
|
||||
}
|
||||
|
||||
.home-cover-badge {
|
||||
width: fit-content;
|
||||
max-width: calc(100% - 86px);
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
border: 1px solid rgba(255, 255, 255, 0.34);
|
||||
border-radius: 999px;
|
||||
padding: 4px 8px;
|
||||
background: rgba(255, 255, 255, 0.14);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.home-cover strong {
|
||||
font-size: 34px;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.home-card-body {
|
||||
padding: 12px;
|
||||
}
|
||||
|
||||
.home-card-body h3 {
|
||||
margin: 0;
|
||||
font-size: 16px;
|
||||
line-height: 1.35;
|
||||
}
|
||||
|
||||
.home-card-meta,
|
||||
.home-card-subtitles,
|
||||
.home-progress {
|
||||
margin: 6px 0 0;
|
||||
color: var(--muted);
|
||||
font-size: 12px;
|
||||
line-height: 1.4;
|
||||
}
|
||||
|
||||
.home-card-tags {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 6px;
|
||||
margin-top: 10px;
|
||||
}
|
||||
|
||||
.home-card-tags span {
|
||||
border-radius: 999px;
|
||||
padding: 3px 7px;
|
||||
color: #334155;
|
||||
background: #eef2f7;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.home-card-stats {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, minmax(0, 1fr));
|
||||
gap: 6px;
|
||||
margin: 12px 0 0;
|
||||
}
|
||||
|
||||
.home-card-stats div {
|
||||
min-width: 0;
|
||||
padding: 8px;
|
||||
border-radius: 7px;
|
||||
background: var(--panel-soft);
|
||||
}
|
||||
|
||||
.home-card-stats dt,
|
||||
.home-card-stats dd {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.home-card-stats dt {
|
||||
color: var(--muted);
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.home-card-stats dd {
|
||||
margin-top: 3px;
|
||||
font-weight: 800;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.home-progress {
|
||||
color: var(--brand);
|
||||
font-weight: 700;
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Update mobile styles**
|
||||
|
||||
In the `@media (max-width: 720px)` block, use:
|
||||
|
||||
```css
|
||||
@media (max-width: 720px) {
|
||||
.home-shell {
|
||||
grid-template-columns: 1fr;
|
||||
padding: 14px 12px 28px;
|
||||
}
|
||||
|
||||
.home-dashboard {
|
||||
position: static;
|
||||
}
|
||||
|
||||
.home-metrics {
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
}
|
||||
|
||||
.home-heading {
|
||||
align-items: stretch;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.home-search {
|
||||
max-width: none;
|
||||
}
|
||||
|
||||
.home-grid {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Check for duplicate home style blocks**
|
||||
|
||||
Run:
|
||||
|
||||
```powershell
|
||||
rg -n "\.home-shell|\.home-dashboard|\.home-card-stats|\.home-favorite" styles.css
|
||||
```
|
||||
|
||||
Expected: selectors exist, and old conflicting `.home-shell` single-column rules are not duplicated outside media queries.
|
||||
|
||||
## Task 5: Full Verification
|
||||
|
||||
**Files:**
|
||||
- Verify: `F:\ooo\speaking-practice-local\home.js`
|
||||
- Verify: `F:\ooo\speaking-practice-local\app.js`
|
||||
- Verify: `F:\ooo\speaking-practice-local\admin.js`
|
||||
- Verify: `F:\ooo\speaking-practice-local\backend\main.py`
|
||||
- Verify: `F:\ooo\speaking-practice-local\backend\db.py`
|
||||
|
||||
- [ ] **Step 1: Run automated checks**
|
||||
|
||||
Run:
|
||||
|
||||
```powershell
|
||||
node --check home.js
|
||||
node --check app.js
|
||||
node --check admin.js
|
||||
python -m py_compile backend\main.py backend\db.py
|
||||
node tests\progress-helpers.test.mjs
|
||||
node tests\admin-file-input.test.mjs
|
||||
```
|
||||
|
||||
Expected: all commands finish with exit code 0.
|
||||
|
||||
- [ ] **Step 2: Start or reuse the local server**
|
||||
|
||||
If no server is running, run:
|
||||
|
||||
```powershell
|
||||
python -m uvicorn backend.main:app --reload --host 127.0.0.1 --port 8000
|
||||
```
|
||||
|
||||
Expected: server listens on `http://127.0.0.1:8000/`.
|
||||
|
||||
- [ ] **Step 3: Browser verification**
|
||||
|
||||
Open:
|
||||
|
||||
```text
|
||||
http://127.0.0.1:8000/
|
||||
```
|
||||
|
||||
Confirm:
|
||||
|
||||
- the left learning overview appears
|
||||
- metric buttons update the grid
|
||||
- search and category chips still work
|
||||
- material cards show sentence, progress, difficult, subtitle, and favorite information
|
||||
- favorite button toggles without opening the study page
|
||||
- clicking the card body opens `study.html?video=<id>`
|
||||
- admin link remains visible only for admin users
|
||||
|
||||
- [ ] **Step 4: Confirm README was not modified**
|
||||
|
||||
Run:
|
||||
|
||||
```powershell
|
||||
git diff -- README.md
|
||||
```
|
||||
|
||||
Expected if inside a git repo: no diff. If not inside a git repo, this command may report that the directory is not a repository; in that case, manually confirm `README.md` was not edited.
|
||||
@@ -0,0 +1,238 @@
|
||||
# Speaking Lab Home Page v1 Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** Make `/` a dedicated material-browsing home page with search, categories, generated preview covers, and card navigation into the study page.
|
||||
|
||||
**Architecture:** Move the existing study page markup from `index.html` to `study.html`, then replace `index.html` with a home page powered by new `home.js`. Reuse `/api/videos` and the existing `speaking-lab-state-v1` localStorage structure for login/admin state and progress summaries. Keep backend API unchanged except making `/` return the new home page.
|
||||
|
||||
**Tech Stack:** FastAPI static files, vanilla HTML/CSS/JS, localStorage, existing Node helper tests.
|
||||
|
||||
---
|
||||
|
||||
## File Structure
|
||||
|
||||
- Create `F:\ooo\speaking-practice-local\study.html`: current study page markup, loading `app.js`.
|
||||
- Replace `F:\ooo\speaking-practice-local\index.html`: new home page markup, loading `home.js`.
|
||||
- Create `F:\ooo\speaking-practice-local\home.js`: home page state, API load, search/category filtering, generated covers, login/admin UI, and card navigation.
|
||||
- Modify `F:\ooo\speaking-practice-local\app.js`: read `?video=<id>` on study page load.
|
||||
- Modify `F:\ooo\speaking-practice-local\styles.css`: add home page/card/cover styles.
|
||||
- Modify `F:\ooo\speaking-practice-local\backend\main.py`: keep `/` returning `index.html`.
|
||||
|
||||
---
|
||||
|
||||
## Task 1: Split Home And Study Pages
|
||||
|
||||
**Files:**
|
||||
- Create: `F:\ooo\speaking-practice-local\study.html`
|
||||
- Modify: `F:\ooo\speaking-practice-local\index.html`
|
||||
|
||||
- [ ] **Step 1: Copy current study markup to `study.html`**
|
||||
|
||||
Copy the current contents of `index.html` exactly into `study.html`.
|
||||
|
||||
- [ ] **Step 2: Replace `index.html` with home shell**
|
||||
|
||||
Use a home page structure with:
|
||||
|
||||
```html
|
||||
<body class="home-page">
|
||||
<header class="topbar home-topbar">...</header>
|
||||
<main class="home-shell">
|
||||
<section class="home-library">
|
||||
<div id="homeCategoryFilters" class="home-categories"></div>
|
||||
<div id="homeStatus" class="home-status"></div>
|
||||
<div id="homeGrid" class="home-grid"></div>
|
||||
</section>
|
||||
</main>
|
||||
<script src="./home.js"></script>
|
||||
</body>
|
||||
```
|
||||
|
||||
Include login/register fields equivalent to the study page and an admin link/button hidden by default.
|
||||
|
||||
- [ ] **Step 3: Run syntax-neutral check**
|
||||
|
||||
Run:
|
||||
|
||||
```powershell
|
||||
Select-String -Path index.html,study.html -Pattern "home.js|app.js|study-shell|home-grid"
|
||||
```
|
||||
|
||||
Expected:
|
||||
|
||||
- `index.html` references `home.js` and `home-grid`.
|
||||
- `study.html` references `app.js` and `study-shell`.
|
||||
|
||||
---
|
||||
|
||||
## Task 2: Add Home Page Logic
|
||||
|
||||
**Files:**
|
||||
- Create: `F:\ooo\speaking-practice-local\home.js`
|
||||
|
||||
- [ ] **Step 1: Create home.js**
|
||||
|
||||
Implement:
|
||||
|
||||
- load local state from `speaking-lab-state-v1`
|
||||
- login/register/logout matching existing local behavior
|
||||
- load `/api/videos`
|
||||
- search by title, speaker, description, tags
|
||||
- category filtering by tags
|
||||
- render generated cover cards
|
||||
- show subtitle languages
|
||||
- show progress summaries using local helper equivalents
|
||||
- click card -> `study.html?video=<id>`
|
||||
|
||||
- [ ] **Step 2: Run check**
|
||||
|
||||
Run:
|
||||
|
||||
```powershell
|
||||
node --check home.js
|
||||
```
|
||||
|
||||
Expected: exit code 0.
|
||||
|
||||
---
|
||||
|
||||
## Task 3: Teach Study Page URL Selection
|
||||
|
||||
**Files:**
|
||||
- Modify: `F:\ooo\speaking-practice-local\app.js`
|
||||
|
||||
- [ ] **Step 1: Add requested video helper**
|
||||
|
||||
Add:
|
||||
|
||||
```js
|
||||
function getRequestedVideoId() {
|
||||
if (!IS_BROWSER) return null;
|
||||
return new URLSearchParams(window.location.search).get("video");
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Prefer requested video after API load**
|
||||
|
||||
In `initializeApp()`, after loading videos and before fallback selection, use:
|
||||
|
||||
```js
|
||||
const requestedVideoId = getRequestedVideoId();
|
||||
if (requestedVideoId && getVideo(requestedVideoId)) {
|
||||
activeVideoId = requestedVideoId;
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Run checks**
|
||||
|
||||
Run:
|
||||
|
||||
```powershell
|
||||
node --check app.js
|
||||
node tests\progress-helpers.test.mjs
|
||||
```
|
||||
|
||||
Expected: both pass.
|
||||
|
||||
---
|
||||
|
||||
## Task 4: Add Home Styles
|
||||
|
||||
**Files:**
|
||||
- Modify: `F:\ooo\speaking-practice-local\styles.css`
|
||||
|
||||
- [ ] **Step 1: Add home page CSS**
|
||||
|
||||
Add styles for:
|
||||
|
||||
- `.home-page`
|
||||
- `.home-topbar`
|
||||
- `.home-shell`
|
||||
- `.home-categories`
|
||||
- `.home-grid`
|
||||
- `.home-card`
|
||||
- `.home-cover`
|
||||
- `.home-card-meta`
|
||||
- `.home-progress`
|
||||
- responsive mobile grid
|
||||
|
||||
- [ ] **Step 2: Run smoke checks**
|
||||
|
||||
Run:
|
||||
|
||||
```powershell
|
||||
node --check home.js
|
||||
node --check app.js
|
||||
```
|
||||
|
||||
Expected: both pass.
|
||||
|
||||
---
|
||||
|
||||
## Task 5: Verify Locally
|
||||
|
||||
**Files:**
|
||||
- No code unless verification reveals a defect.
|
||||
|
||||
- [ ] **Step 1: Static verification**
|
||||
|
||||
Run:
|
||||
|
||||
```powershell
|
||||
python -m py_compile backend\main.py backend\db.py
|
||||
node --check home.js
|
||||
node --check app.js
|
||||
node --check admin.js
|
||||
node tests\progress-helpers.test.mjs
|
||||
node tests\admin-file-input.test.mjs
|
||||
```
|
||||
|
||||
Expected: all pass.
|
||||
|
||||
- [ ] **Step 2: Browser verification**
|
||||
|
||||
Open:
|
||||
|
||||
```text
|
||||
http://127.0.0.1:8000/
|
||||
```
|
||||
|
||||
Expected:
|
||||
|
||||
- Home page appears.
|
||||
- Search input is visible.
|
||||
- Category chips render.
|
||||
- Cards render with generated covers.
|
||||
- Clicking a card opens `study.html?video=<id>`.
|
||||
|
||||
Open:
|
||||
|
||||
```text
|
||||
http://127.0.0.1:8000/study.html
|
||||
http://127.0.0.1:8000/admin.html
|
||||
```
|
||||
|
||||
Expected both still work.
|
||||
|
||||
---
|
||||
|
||||
## Self-Review
|
||||
|
||||
Spec coverage:
|
||||
|
||||
- `/` opens home page: Tasks 1 and 5.
|
||||
- Current study page moves to `study.html`: Task 1.
|
||||
- Search/categories/cards/generated covers: Tasks 2 and 4.
|
||||
- Card navigation to `study.html?video=<id>`: Tasks 2 and 3.
|
||||
- Admin entry for admin users: Task 2.
|
||||
- No backend schema/API changes: plan keeps backend unchanged.
|
||||
|
||||
Placeholder scan:
|
||||
|
||||
- No unresolved placeholders.
|
||||
|
||||
Type consistency:
|
||||
|
||||
- Video IDs are strings in frontend navigation.
|
||||
- Home state uses the same `speaking-lab-state-v1` key as existing pages.
|
||||
@@ -0,0 +1,29 @@
|
||||
# Speaking Lab Material Edit v1 Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** Add backend and admin-page support for editing existing materials, including replacing video and subtitle files.
|
||||
|
||||
**Architecture:** Extend the existing FastAPI/SQLite content-library path with an update helper and `PATCH /api/videos/{video_id}` endpoint. Reuse the existing admin form as an add/edit form, keeping add mode as the default and switching to edit mode from the material list.
|
||||
|
||||
**Tech Stack:** FastAPI multipart forms, SQLite, vanilla JS, existing CSS.
|
||||
|
||||
---
|
||||
|
||||
## Tasks
|
||||
|
||||
1. Backend update helper in `backend/db.py`.
|
||||
2. PATCH endpoint and safe replacement cleanup in `backend/main.py`.
|
||||
3. Admin form edit mode in `admin.html` and `admin.js`.
|
||||
4. Admin list edit action styling in `styles.css`.
|
||||
5. Static and API smoke verification.
|
||||
|
||||
## Verification Commands
|
||||
|
||||
```powershell
|
||||
python -m py_compile backend\main.py backend\db.py
|
||||
node --check admin.js
|
||||
node --check app.js
|
||||
node tests\admin-file-input.test.mjs
|
||||
node tests\progress-helpers.test.mjs
|
||||
```
|
||||
@@ -0,0 +1,45 @@
|
||||
# Speaking Lab Study Focus Layout Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task.
|
||||
|
||||
**Goal:** Remove the study page material rail and let the video learning panel occupy that space.
|
||||
|
||||
**Architecture:** Remove rail markup in `study.html`, make related `app.js` DOM operations optional, and simplify `styles.css` layout so `.left-stage` becomes a single video panel column.
|
||||
|
||||
**Tech Stack:** Vanilla HTML, CSS, JavaScript.
|
||||
|
||||
---
|
||||
|
||||
## Task 1: Remove Rail Markup
|
||||
|
||||
- Modify `study.html`.
|
||||
- Delete the `.lesson-rail` block inside `.left-stage`.
|
||||
- Keep `.video-panel` unchanged.
|
||||
|
||||
## Task 2: Guard Rail JavaScript
|
||||
|
||||
- Modify `app.js`.
|
||||
- Ensure event listeners for `searchInput`, `tagFilters`, `videoList`, `videoCount`, and `adminEntryBtn` only run when those elements exist.
|
||||
- Make `renderLibrary()` return early when rail elements are absent.
|
||||
- Make `renderAdminAccess()` tolerate a missing admin button.
|
||||
|
||||
## Task 3: Expand Video Layout
|
||||
|
||||
- Modify `styles.css`.
|
||||
- Change `.left-stage` from `grid-template-columns: 220px minmax(0, 1fr)` to `grid-template-columns: minmax(0, 1fr)`.
|
||||
- Remove responsive overrides that reintroduce a rail width.
|
||||
- Keep transcript panel on the right.
|
||||
|
||||
## Task 4: Verify
|
||||
|
||||
Run:
|
||||
|
||||
```powershell
|
||||
node --check app.js
|
||||
node --check home.js
|
||||
node --check admin.js
|
||||
node tests\progress-helpers.test.mjs
|
||||
node tests\admin-file-input.test.mjs
|
||||
```
|
||||
|
||||
Open `http://127.0.0.1:8000/study.html` and confirm the left rail is gone and the video panel is wider.
|
||||
@@ -0,0 +1,39 @@
|
||||
# Speaking Lab Subtitle Delete Cues Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task.
|
||||
|
||||
**Goal:** Add admin-side deletion of whole subtitle cue blocks.
|
||||
|
||||
**Architecture:** Backend accepts optional updated subtitle text fields on PATCH. Admin JS parses subtitle text into cue blocks, renders delete buttons during edit mode, rebuilds VTT text from remaining cue blocks, and sends updated content with the existing material edit request.
|
||||
|
||||
**Tech Stack:** FastAPI form fields, SQLite subtitle content, vanilla JavaScript admin page.
|
||||
|
||||
---
|
||||
|
||||
## Task 1: Backend Content Update
|
||||
|
||||
- Modify `backend/main.py`.
|
||||
- Add optional `subtitle_en_content` and `subtitle_zh_content` form fields to PATCH.
|
||||
- Convert provided content fields into subtitle update payloads when no replacement file exists for that language.
|
||||
|
||||
## Task 2: Admin Markup
|
||||
|
||||
- Modify `admin.html`.
|
||||
- Add a container below the subtitle upload inputs for subtitle cue deletion sections.
|
||||
|
||||
## Task 3: Admin Subtitle State
|
||||
|
||||
- Modify `admin.js`.
|
||||
- Add cue parsing and VTT rebuilding helpers.
|
||||
- Track editable subtitle cues for the current editing material.
|
||||
- Render per-language cue lists with `删除` buttons.
|
||||
- Append updated subtitle content to FormData on edit save.
|
||||
|
||||
## Task 4: Styles
|
||||
|
||||
- Modify `styles.css`.
|
||||
- Add compact admin subtitle cue list styles.
|
||||
|
||||
## Task 5: Verify
|
||||
|
||||
Run automated checks and manually verify admin delete/save/study-page reload.
|
||||
Reference in new issue
Block a user