diff --git a/admin.html b/admin.html
index 486f43e..f90d919 100644
--- a/admin.html
+++ b/admin.html
@@ -54,23 +54,11 @@
-
+
-
-
-
字幕时间校准
-
先编辑一个已有素材,再整体提前或延后字幕。
-
-
-
-
-
-
-
-
diff --git a/admin.js b/admin.js
index ff7d63c..bd3645d 100644
--- a/admin.js
+++ b/admin.js
@@ -23,11 +23,6 @@ const els = {
testAiBtn: IS_BROWSER ? document.querySelector("#testAiBtn") : null,
processAiSubtitlesBtn: IS_BROWSER ? document.querySelector("#processAiSubtitlesBtn") : null,
generateLocalWhisperSubtitlesBtn: IS_BROWSER ? document.querySelector("#generateLocalWhisperSubtitlesBtn") : null,
- subtitleShiftStatus: IS_BROWSER ? document.querySelector("#subtitleShiftStatus") : null,
- shiftSubtitleEarlierSmallBtn: IS_BROWSER ? document.querySelector("#shiftSubtitleEarlierSmallBtn") : null,
- shiftSubtitleLaterSmallBtn: IS_BROWSER ? document.querySelector("#shiftSubtitleLaterSmallBtn") : null,
- shiftSubtitleEarlierBtn: IS_BROWSER ? document.querySelector("#shiftSubtitleEarlierBtn") : null,
- shiftSubtitleLaterBtn: IS_BROWSER ? document.querySelector("#shiftSubtitleLaterBtn") : null,
refreshBtn: IS_BROWSER ? document.querySelector("#refreshVideosBtn") : null,
message: IS_BROWSER ? document.querySelector("#adminMessage") : null,
videoList: IS_BROWSER ? document.querySelector("#adminVideoList") : null,
@@ -95,10 +90,6 @@ function initializeAdmin() {
els.testAiBtn?.addEventListener("click", testAiConnection);
els.processAiSubtitlesBtn?.addEventListener("click", processAiSubtitles);
els.generateLocalWhisperSubtitlesBtn?.addEventListener("click", generateLocalWhisperSubtitles);
- els.shiftSubtitleEarlierSmallBtn?.addEventListener("click", () => shiftEditableSubtitles(-0.2));
- els.shiftSubtitleLaterSmallBtn?.addEventListener("click", () => shiftEditableSubtitles(0.2));
- els.shiftSubtitleEarlierBtn?.addEventListener("click", () => shiftEditableSubtitles(-0.5));
- els.shiftSubtitleLaterBtn?.addEventListener("click", () => shiftEditableSubtitles(0.5));
bindFileInputs();
loadAiStatus();
loadVideos();
@@ -164,13 +155,14 @@ async function loadAiStatus() {
if (!els.aiStatus) return;
try {
const status = await apiRequest("/api/ai/status");
- const buttonState = getAiSubtitleButtonState(status, editingVideo);
- els.aiStatus.textContent = buttonState.hint || status.message || "AI 状态未知。";
+ const aiButtonState = getAiSubtitleButtonState(status, editingVideo);
+ const localWhisperButtonState = getLocalWhisperButtonState(status, editingVideo);
+ els.aiStatus.textContent = aiButtonState.hint || localWhisperButtonState.hint || status.message || "AI 状态未知。";
if (els.processAiSubtitlesBtn) {
- els.processAiSubtitlesBtn.disabled = buttonState.disabled;
+ els.processAiSubtitlesBtn.disabled = aiButtonState.disabled;
}
if (els.generateLocalWhisperSubtitlesBtn) {
- els.generateLocalWhisperSubtitlesBtn.disabled = buttonState.disabled;
+ els.generateLocalWhisperSubtitlesBtn.disabled = localWhisperButtonState.disabled;
}
} catch (error) {
els.aiStatus.textContent = error.message || "AI 状态读取失败。";
@@ -200,6 +192,52 @@ function getAiSubtitleButtonState(status, selectedVideo) {
};
}
+function getLocalWhisperButtonState(status, selectedVideo) {
+ if (!status?.localWhisperEnabled) {
+ return {
+ disabled: true,
+ hint: "请先开启本地 Whisper。",
+ };
+ }
+
+ if (!selectedVideo) {
+ return {
+ disabled: true,
+ hint: "请先在右侧素材列表点“编辑”。",
+ };
+ }
+
+ return {
+ disabled: false,
+ hint: "",
+ };
+}
+
+function shouldConfirmSubtitleOverwrite(video) {
+ const subtitles = video?.subtitles || {};
+ return Boolean(subtitles.en?.content);
+}
+
+function setAiReportText(text) {
+ if (!els.aiReport) return;
+ els.aiReport.hidden = false;
+ els.aiReport.textContent = text;
+}
+
+function startLocalWhisperProgress() {
+ const stages = [
+ "处理进度:提取音频...",
+ "处理进度:生成英文字幕...",
+ ];
+ setAiReportText(stages[0]);
+
+ const timers = [
+ window.setTimeout(() => setAiReportText(stages[1]), 1200),
+ ];
+
+ return () => timers.forEach((timer) => window.clearTimeout(timer));
+}
+
async function testAiConnection() {
try {
const result = await apiRequest("/api/ai/test", { method: "POST" });
@@ -216,30 +254,36 @@ async function generateLocalWhisperSubtitles() {
return;
}
+ if (shouldConfirmSubtitleOverwrite(editingVideo)) {
+ const confirmed = window.confirm("当前素材已有英文字幕,重新生成会覆盖它。继续吗?");
+ if (!confirmed) return;
+ }
+
const button = els.generateLocalWhisperSubtitlesBtn;
if (!button) return;
+ const stopProgress = startLocalWhisperProgress();
button.disabled = true;
- button.textContent = "本地生成中...";
+ button.textContent = "处理中...";
try {
const result = await apiRequest(`/api/videos/${editingVideo.id}/local-whisper/subtitles`, { method: "POST" });
const report = result.report || {};
- if (els.aiReport) {
- els.aiReport.hidden = false;
- els.aiReport.textContent = [
- `英文字幕 ${report.cleaned_count || 0} 条`,
- `中文字幕 ${report.translation_count || 0} 条`,
- report.alignment_note || "本地 Whisper 已完成",
- ].join(",") + "。";
- }
+ setAiReportText([
+ "处理进度:完成",
+ `英文字幕 ${report.english_count || 0} 条`,
+ "本地 Whisper 已完成",
+ ].join(";") + "。");
await loadVideos();
const updated = videos.find((video) => String(video.id) === String(editingVideo.id));
if (updated) startEditingVideo(updated);
- showMessage("本地字幕生成和翻译完成。");
+ showMessage("本地英文字幕生成完成。");
} catch (error) {
- showMessage(error.message || "本地字幕生成失败。", true);
+ const message = error.message || "本地英文字幕生成失败。";
+ setAiReportText(`处理失败:${message}`);
+ showMessage(message, true);
} finally {
- button.textContent = "本地生成并翻译字幕";
+ stopProgress();
+ button.textContent = "本地生成英文字幕";
await loadAiStatus();
}
}
@@ -263,7 +307,6 @@ async function processAiSubtitles() {
els.aiReport.textContent = [
`处理完成:删除重复 ${report.duplicate_count || 0} 条`,
`删除空白 ${report.empty_count || 0} 条`,
- report.timestamp_calibrated ? `首句校准 ${Number(report.timestamp_offset_seconds || 0).toFixed(2)} 秒` : (report.alignment_note || "首句未自动校准"),
`生成中文 ${report.translation_count || 0} 条`,
].join(",") + "。";
}
@@ -272,7 +315,9 @@ async function processAiSubtitles() {
if (updated) startEditingVideo(updated);
showMessage("AI 字幕处理完成。");
} catch (error) {
- showMessage(error.message || "AI 字幕处理失败。", true);
+ const message = error.message || "AI 字幕处理失败。";
+ setAiReportText(`处理失败:${message}`);
+ showMessage(message, true);
} finally {
button.textContent = "AI 修复并翻译字幕";
await loadAiStatus();
@@ -370,7 +415,6 @@ function startEditingVideo(video) {
renderSubtitleEditor();
renderVideos();
loadAiStatus();
- updateSubtitleShiftControls();
}
function resetFormMode() {
@@ -386,7 +430,6 @@ function resetFormMode() {
renderSubtitleEditor();
renderVideos();
loadAiStatus();
- updateSubtitleShiftControls();
}
function pickVideoAfterSave(videoList, response, previousEditingVideo) {
@@ -462,9 +505,9 @@ if (typeof module !== "undefined" && module.exports) {
parseSubtitleBlocks,
buildWebVtt,
getAiSubtitleButtonState,
+ getLocalWhisperButtonState,
+ shouldConfirmSubtitleOverwrite,
pickVideoAfterSave,
- shiftCueTimeRange,
- shiftSubtitleCues,
};
}
@@ -565,86 +608,6 @@ function hasSubtitleText(textRows) {
.trim().length > 0;
}
-function shiftEditableSubtitles(offsetSeconds) {
- const tracks = [editableSubtitles.en, editableSubtitles.zh].filter(Boolean);
- if (!editingVideo || !tracks.length) {
- showMessage("请先编辑一个带字幕的素材。", true);
- return;
- }
-
- tracks.forEach((track) => {
- track.cues = shiftSubtitleCues(track.cues, offsetSeconds);
- track.dirty = true;
- });
- renderSubtitleEditor();
- updateSubtitleShiftControls(offsetSeconds);
-}
-
-function updateSubtitleShiftControls(lastOffset = 0) {
- const hasEditableCues = Boolean(editingVideo && [editableSubtitles.en, editableSubtitles.zh]
- .filter(Boolean)
- .some((track) => track.cues.length));
- [
- els.shiftSubtitleEarlierSmallBtn,
- els.shiftSubtitleLaterSmallBtn,
- els.shiftSubtitleEarlierBtn,
- els.shiftSubtitleLaterBtn,
- ].forEach((button) => {
- if (button) button.disabled = !hasEditableCues;
- });
- if (!els.subtitleShiftStatus) return;
-
- if (!editingVideo) {
- els.subtitleShiftStatus.textContent = "先编辑一个已有素材,再整体提前或延后字幕。";
- return;
- }
- if (!hasEditableCues) {
- els.subtitleShiftStatus.textContent = "当前素材没有可校准的字幕。";
- return;
- }
- if (lastOffset > 0) {
- els.subtitleShiftStatus.textContent = `字幕已整体延后 ${lastOffset.toFixed(1)} 秒,点“保存修改”生效。`;
- return;
- }
- if (lastOffset < 0) {
- els.subtitleShiftStatus.textContent = `字幕已整体提前 ${Math.abs(lastOffset).toFixed(1)} 秒,点“保存修改”生效。`;
- return;
- }
- els.subtitleShiftStatus.textContent = "如果字幕太早,点 +0.2/+0.5 秒;如果字幕太晚,点 -0.2/-0.5 秒。";
-}
-
-function shiftSubtitleCues(cues, offsetSeconds) {
- return cues.map((cue) => ({
- ...cue,
- timeRange: shiftCueTimeRange(cue.timeRange, offsetSeconds),
- }));
-}
-
-function shiftCueTimeRange(timeRange, offsetSeconds) {
- const [startRaw, endRaw] = String(timeRange).split("-->").map((part) => part.trim());
- return `${formatVttTimestamp(parseVttTimestamp(startRaw) + offsetSeconds)} --> ${formatVttTimestamp(parseVttTimestamp(endRaw) + offsetSeconds)}`;
-}
-
-function parseVttTimestamp(value) {
- const clean = String(value).replace(",", ".").split(/\s+/)[0];
- const parts = clean.split(":").map(Number);
- if (parts.length === 3) return parts[0] * 3600 + parts[1] * 60 + parts[2];
- if (parts.length === 2) return parts[0] * 60 + parts[1];
- return Number(clean) || 0;
-}
-
-function formatVttTimestamp(seconds) {
- const totalMilliseconds = Math.max(0, Math.round((Number(seconds) || 0) * 1000));
- const hours = Math.floor(totalMilliseconds / 3600000);
- const minutes = Math.floor((totalMilliseconds % 3600000) / 60000);
- const wholeSeconds = Math.floor((totalMilliseconds % 60000) / 1000);
- const milliseconds = totalMilliseconds % 1000;
- return [
- String(hours).padStart(2, "0"),
- String(minutes).padStart(2, "0"),
- String(wholeSeconds).padStart(2, "0"),
- ].join(":") + `.${String(milliseconds).padStart(3, "0")}`;
-}
function renderSubtitleEditor() {
if (!els.subtitleEditor) return;
@@ -698,7 +661,6 @@ function renderSubtitleEditor() {
els.subtitleEditor.appendChild(section);
});
- updateSubtitleShiftControls();
}
function appendEditedSubtitleContent(formData) {
diff --git a/app.js b/app.js
index 0b6d9bf..1279506 100644
--- a/app.js
+++ b/app.js
@@ -16,9 +16,7 @@ const els = {
videoList: IS_BROWSER ? document.querySelector("#videoList") : null,
videoCount: IS_BROWSER ? document.querySelector("#videoCount") : null,
videoTitle: IS_BROWSER ? document.querySelector("#videoTitle") : null,
- continueBtn: IS_BROWSER ? document.querySelector("#continueBtn") : null,
favoriteBtn: IS_BROWSER ? document.querySelector("#favoriteBtn") : null,
- watchLaterBtn: IS_BROWSER ? document.querySelector("#watchLaterBtn") : null,
previousBtn: IS_BROWSER ? document.querySelector("#previousBtn") : null,
replayBtn: IS_BROWSER ? document.querySelector("#replayBtn") : null,
nextBtn: IS_BROWSER ? document.querySelector("#nextBtn") : null,
@@ -242,9 +240,7 @@ function bindEvents() {
els.previousBtn.addEventListener("click", () => jumpRelative(-1));
els.replayBtn.addEventListener("click", () => jumpToLine(activeLineIndex >= 0 ? activeLineIndex : 0));
els.nextBtn.addEventListener("click", () => jumpRelative(1));
- els.continueBtn.addEventListener("click", continueLearning);
els.favoriteBtn.addEventListener("click", () => toggleSaved("favorites"));
- els.watchLaterBtn.addEventListener("click", () => toggleSaved("watchLater"));
els.recordBtn.addEventListener("click", startRecording);
els.stopRecordBtn.addEventListener("click", stopRecording);
els.playRecordingBtn.addEventListener("click", () => {
@@ -279,7 +275,6 @@ function renderAccount() {
els.userLabel.textContent = `${user.email}${user.role === "admin" ? " · 管理员" : ""}`;
}
renderAdminAccess();
- renderContinueAction();
}
function renderAdminAccess() {
@@ -390,7 +385,6 @@ function selectVideo(id) {
restoreProgressForActiveVideo();
syncSubtitles();
updateNavigationState();
- renderContinueAction();
}
async function loadVideoSource(video) {
@@ -434,9 +428,8 @@ function renderVideoMeta() {
const video = getActiveVideo();
if (!video) return;
const user = getCurrentUser();
- els.videoTitle.textContent = video.title;
+ if (els.videoTitle) els.videoTitle.textContent = video.title;
els.favoriteBtn.textContent = user?.favorites.includes(video.id) ? "已收藏" : "收藏";
- els.watchLaterBtn.textContent = user?.watchLater.includes(video.id) ? "已加入稍后再看" : "稍后再看";
}
function renderSubtitleModeTabs() {
@@ -453,12 +446,12 @@ function renderTranscript() {
els.transcriptList.innerHTML = "";
if (!primary.length) {
- els.subtitleMeta.textContent = modeConfig.message || "当前视频没有可用字幕。";
+ if (els.subtitleMeta) els.subtitleMeta.textContent = modeConfig.message || "当前视频没有可用字幕。";
els.transcriptList.innerHTML = `${modeConfig.message || "请在后台上传 .srt 或 .vtt 字幕。"}
`;
return;
}
- els.subtitleMeta.textContent = modeConfig.message || `${primary.length} 句 · 点击文字稿跳转到对应片段`;
+ if (els.subtitleMeta) els.subtitleMeta.textContent = modeConfig.message || `${primary.length} 句 · 点击文字稿跳转到对应片段`;
const fragment = document.createDocumentFragment();
primary.forEach((cue, index) => {
@@ -560,8 +553,8 @@ function syncSubtitles() {
const primary = getPrimaryCues()[activeLineIndex];
const secondary = getSecondaryCues()[activeLineIndex];
const modeConfig = getActiveSubtitleModeConfig();
- els.primarySubtitle.textContent = primary?.text || "";
- els.secondarySubtitle.textContent = modeConfig.showSecondary && secondary ? secondary.text : "";
+ if (els.primarySubtitle) els.primarySubtitle.textContent = primary?.text || "";
+ if (els.secondarySubtitle) els.secondarySubtitle.textContent = modeConfig.showSecondary && secondary ? secondary.text : "";
}
function updateNavigationState() {
@@ -586,7 +579,6 @@ function saveActiveProgress(partial = {}, immediate = false) {
if (immediate || now - lastProgressSaveAt > 1500) {
lastProgressSaveAt = now;
saveState();
- renderContinueAction();
renderLibrary();
}
}
@@ -605,26 +597,6 @@ function restoreProgressForActiveVideo() {
}
}
-function continueLearning() {
- const progress = getActiveProgress();
- if (!progress) return;
-
- if (progress.currentTime > 1) {
- els.video.currentTime = progress.currentTime;
- }
- if (progress.activeLineIndex >= 0 && getPrimaryCues()[progress.activeLineIndex]) {
- jumpToLine(progress.activeLineIndex);
- return;
- }
- els.video.play().catch(() => {});
-}
-
-function renderContinueAction() {
- const progress = getActiveProgress();
- const hasProgress = Boolean(progress && (progress.currentTime > 1 || progress.activeLineIndex > 0));
- els.continueBtn.hidden = !hasProgress;
-}
-
function toggleLineStatus(index, status, event) {
event.stopPropagation();
const progress = getActiveProgress();
@@ -668,12 +640,11 @@ function renderSavedLists() {
const user = getCurrentUser();
if (!user) {
- els.savedLists.innerHTML = "登录后可使用收藏和稍后再看。";
+ els.savedLists.innerHTML = "登录后可使用收藏。";
return;
}
els.savedLists.innerHTML = `
收藏
${renderSavedNames(user.favorites)}
- 稍后再看
${renderSavedNames(user.watchLater)}
`;
}
diff --git a/backend/ai_config.py b/backend/ai_config.py
index 82f4e64..026ef04 100644
--- a/backend/ai_config.py
+++ b/backend/ai_config.py
@@ -21,21 +21,6 @@ class DeepSeekConfig:
protocol: str
translation_batch_size: int
timeout_seconds: int
- enable_audio_alignment: bool
-
-
-@dataclass(frozen=True)
-class AsrConfig:
- provider: str
- api_key: str
- base_url: str
- model: str
- timeout_seconds: int
- enabled: bool
-
- @property
- def configured(self) -> bool:
- return self.enabled and bool(self.api_key)
def read_env_file(path: Path = ENV_PATH) -> dict[str, str]:
@@ -82,19 +67,6 @@ def load_text_ai_config() -> DeepSeekConfig:
protocol=(get_config_value("TEXT_AI_PROTOCOL") or get_config_value("AI_API_PROTOCOL", "openai") or "openai").lower(),
translation_batch_size=parse_non_negative_int_config(get_config_value("TEXT_AI_BATCH_SIZE") or get_config_value("AI_TRANSLATION_BATCH_SIZE", "40"), 40),
timeout_seconds=parse_int_config(get_config_value("TEXT_AI_TIMEOUT_SECONDS") or get_config_value("AI_TIMEOUT_SECONDS", "120"), 120),
- enable_audio_alignment=False,
- )
-
-
-def load_asr_config() -> AsrConfig:
- provider = (get_config_value("ASR_PROVIDER", "none") or "none").lower()
- return AsrConfig(
- provider=provider,
- api_key=get_config_value("OPENAI_API_KEY"),
- base_url=(get_config_value("OPENAI_BASE_URL", "https://api.openai.com") or "https://api.openai.com").rstrip("/"),
- model=get_config_value("OPENAI_ASR_MODEL", "whisper-1") or "whisper-1",
- timeout_seconds=parse_int_config(get_config_value("ASR_TIMEOUT_SECONDS", "120"), 120),
- enabled=provider == "openai",
)
@@ -120,20 +92,16 @@ def load_deepseek_config() -> DeepSeekConfig:
protocol=(get_config_value("AI_API_PROTOCOL", "openai") or "openai").lower(),
translation_batch_size=parse_int_config(get_config_value("AI_TRANSLATION_BATCH_SIZE", "5"), 5),
timeout_seconds=parse_int_config(get_config_value("AI_TIMEOUT_SECONDS", "180"), 180),
- enable_audio_alignment=parse_bool_config(get_config_value("AI_ENABLE_AUDIO_ALIGNMENT", "false")),
)
def get_ai_status() -> dict[str, object]:
text_config = load_text_ai_config()
- asr_config = load_asr_config()
return {
"configured": bool(text_config.api_key),
"provider": text_config.provider,
"protocol": text_config.protocol,
"model": text_config.model,
- "asrProvider": asr_config.provider,
- "asrConfigured": asr_config.configured,
"localWhisperEnabled": load_local_whisper_config().enabled,
"message": "AI API 已配置。" if text_config.api_key else "未配置 TEXT_AI_API_KEY,请在 .env 中填写。",
}
diff --git a/backend/main.py b/backend/main.py
index c83e5ce..ae9b4c7 100644
--- a/backend/main.py
+++ b/backend/main.py
@@ -6,7 +6,7 @@ from fastapi import FastAPI, File, Form, HTTPException, UploadFile
from fastapi.responses import FileResponse
from fastapi.staticfiles import StaticFiles
-from .ai_config import get_ai_status, load_asr_config, load_local_whisper_config, load_text_ai_config
+from .ai_config import get_ai_status, load_local_whisper_config, load_text_ai_config
from .db import (
DATABASE_PATH,
create_video,
@@ -21,10 +21,7 @@ from .db import (
)
from .deepseek_client import DeepSeekClient, DeepSeekError
from .local_whisper import LocalWhisperError, transcribe_video_to_vtt
-from .openai_asr_client import OpenAIAsrClient
-from .subtitle_alignment import align_first_sentence_with_asr
from .subtitle_ai import process_subtitles_with_ai
-from .subtitle_tools import clean_english_subtitle
PROJECT_DIR = Path(__file__).resolve().parent.parent
@@ -389,32 +386,12 @@ def api_process_video_subtitles(video_id: int) -> dict[str, object]:
try:
text_ai_config = load_text_ai_config()
- asr_config = load_asr_config()
client = DeepSeekClient(text_ai_config, timeout_seconds=text_ai_config.timeout_seconds)
- timestamp_offset_seconds = 0.0
- alignment_note = "未执行首句校准。"
- cleaned_for_alignment = clean_english_subtitle(str(english_subtitle["content"]))
- video_path = upload_url_to_path(str(video.get("videoUrl") or ""))
- if asr_config.configured and video_path and cleaned_for_alignment.cues:
- alignment = align_first_sentence_with_asr(
- video_path,
- cleaned_for_alignment.cues[0],
- OpenAIAsrClient(asr_config),
- )
- timestamp_offset_seconds = alignment.offset_seconds if alignment.applied else 0.0
- alignment_note = alignment.note
- elif not asr_config.configured:
- alignment_note = "未配置 OpenAI ASR,已跳过首句校准,继续执行 DeepSeek 字幕处理。"
- elif not video_path:
- alignment_note = "当前视频不是本地上传文件,已跳过 OpenAI ASR 首句校准。"
-
result = process_subtitles_with_ai(
str(english_subtitle["content"]),
client,
- timestamp_offset_seconds=timestamp_offset_seconds,
batch_size=text_ai_config.translation_batch_size,
)
- result["report"]["alignment_note"] = alignment_note
except (DeepSeekError, ValueError) as error:
raise HTTPException(status_code=400, detail=str(error)) from error
@@ -478,10 +455,6 @@ def save_processed_subtitles(video_id: int, subtitles: dict[str, object], result
@app.post("/api/videos/{video_id}/local-whisper/subtitles")
def api_generate_local_whisper_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="视频不存在")
@@ -490,29 +463,26 @@ def api_generate_local_whisper_subtitles(video_id: int) -> dict[str, object]:
if not video_path:
raise HTTPException(status_code=400, detail="本地 Whisper 只能处理本地上传的视频文件。")
- subtitles = video.get("subtitles", {})
- if not isinstance(subtitles, dict):
- subtitles = {}
-
try:
whisper_config = load_local_whisper_config()
english_vtt = transcribe_video_to_vtt(video_path, whisper_config)
- text_ai_config = load_text_ai_config()
- client = DeepSeekClient(text_ai_config, timeout_seconds=text_ai_config.timeout_seconds)
- result = process_subtitles_with_ai(
- english_vtt,
- client,
- batch_size=text_ai_config.translation_batch_size,
- )
- result["report"]["local_whisper_generated"] = True
- result["report"]["alignment_note"] = "本地 Whisper 已生成英文字幕,DeepSeek 已翻译中文字幕。"
- except (DeepSeekError, LocalWhisperError, ValueError) as error:
+ except LocalWhisperError as error:
raise HTTPException(status_code=400, detail=str(error)) from error
- save_processed_subtitles(video_id, subtitles, result)
+ upsert_video_subtitle(
+ video_id,
+ language_code="en",
+ language_name="English",
+ format="vtt",
+ file_path="",
+ content=english_vtt,
+ )
return {
"video": get_video(video_id),
- "report": result["report"],
+ "report": {
+ "local_whisper_generated": True,
+ "english_count": english_vtt.count("-->"),
+ },
}
@app.get("/")
diff --git a/backend/openai_asr_client.py b/backend/openai_asr_client.py
deleted file mode 100644
index a221fb9..0000000
--- a/backend/openai_asr_client.py
+++ /dev/null
@@ -1,66 +0,0 @@
-from __future__ import annotations
-
-import json
-from pathlib import Path
-import uuid
-import urllib.error
-import urllib.request
-
-from .ai_config import AsrConfig
-from .deepseek_client import DeepSeekError
-
-
-class OpenAIAsrClient:
- def __init__(self, config: AsrConfig):
- self.config = config
-
- def transcribe(self, audio_path: Path) -> dict[str, object]:
- if not self.config.configured:
- raise DeepSeekError("未配置 OPENAI_API_KEY,已跳过 ASR。")
- if not audio_path.exists():
- raise DeepSeekError("音频文件不存在,无法 ASR。")
-
- boundary = f"----speaking-lab-{uuid.uuid4().hex}"
- body = self._build_multipart_body(boundary, audio_path)
- request = urllib.request.Request(
- f"{self.config.base_url}/v1/audio/transcriptions",
- data=body,
- headers={
- "Authorization": f"Bearer {self.config.api_key}",
- "Content-Type": f"multipart/form-data; boundary={boundary}",
- },
- method="POST",
- )
-
- try:
- with urllib.request.urlopen(request, timeout=self.config.timeout_seconds) as response:
- return json.loads(response.read().decode("utf-8"))
- except urllib.error.HTTPError as error:
- detail = error.read().decode("utf-8", errors="replace")
- raise DeepSeekError(f"OpenAI ASR 请求失败:{error.code} {detail}") from error
- except Exception as error:
- raise DeepSeekError(f"OpenAI ASR 请求失败:{error}") from error
-
- def _build_multipart_body(self, boundary: str, audio_path: Path) -> bytes:
- fields = [
- ("model", self.config.model),
- ("response_format", "verbose_json"),
- ("timestamp_granularities[]", "segment"),
- ]
- chunks: list[bytes] = []
- for key, value in fields:
- chunks.extend([
- f"--{boundary}\r\n".encode("utf-8"),
- f'Content-Disposition: form-data; name="{key}"\r\n\r\n'.encode("utf-8"),
- f"{value}\r\n".encode("utf-8"),
- ])
-
- chunks.extend([
- f"--{boundary}\r\n".encode("utf-8"),
- f'Content-Disposition: form-data; name="file"; filename="{audio_path.name}"\r\n'.encode("utf-8"),
- b"Content-Type: audio/wav\r\n\r\n",
- audio_path.read_bytes(),
- b"\r\n",
- f"--{boundary}--\r\n".encode("utf-8"),
- ])
- return b"".join(chunks)
diff --git a/backend/subtitle_ai.py b/backend/subtitle_ai.py
index 6e2dc52..007b357 100644
--- a/backend/subtitle_ai.py
+++ b/backend/subtitle_ai.py
@@ -1,6 +1,6 @@
from __future__ import annotations
-from .subtitle_tools import SubtitleCue, build_vtt, clean_english_subtitle, shift_cues
+from .subtitle_tools import SubtitleCue, build_vtt, clean_english_subtitle
TRANSLATION_SYSTEM_PROMPT = """
@@ -18,13 +18,12 @@ TRANSLATION_SYSTEM_PROMPT = """
def process_subtitles_with_ai(
english_content: str,
client,
- timestamp_offset_seconds: float = 0.0,
batch_size: int = 0,
) -> dict[str, object]:
cleaned = clean_english_subtitle(english_content)
if not cleaned.cues:
raise ValueError("英文字幕为空,无法处理。")
- english_cues = shift_cues(cleaned.cues, timestamp_offset_seconds) if timestamp_offset_seconds else cleaned.cues
+ english_cues = cleaned.cues
translations = translate_cues(english_cues, client, batch_size)
@@ -47,9 +46,6 @@ def process_subtitles_with_ai(
"empty_count": cleaned.empty_count,
"translation_count": len(zh_cues),
"translation_batches": translation_batches,
- "timestamp_calibrated": bool(timestamp_offset_seconds),
- "timestamp_offset_seconds": round(timestamp_offset_seconds, 3),
- "timestamp_note": "首句校准只计算整体偏移,AI 不逐句修改时间轴。",
},
}
@@ -69,35 +65,53 @@ def translate_cues(
)
for batch in batches:
- payload = {
- "cues": [
- {"index": index, "text": cue.text}
- for index, cue in batch
- ]
- }
- response = client.chat_json(TRANSLATION_SYSTEM_PROMPT, payload)
- batch_translations = response.get("translations")
- if not isinstance(batch_translations, list):
- raise ValueError("AI 返回结果缺少 translations。")
-
expected_indexes = {index for index, _cue in batch}
- for item in batch_translations:
- if not isinstance(item, dict):
- continue
- try:
- item_index = int(item.get("index"))
- except (TypeError, ValueError):
- continue
- if item_index in expected_indexes:
- translations[item_index] = item
-
+ collect_translations(batch, expected_indexes, translations, client)
missing = sorted(expected_indexes - translations.keys())
+ if missing:
+ missing_batch = [(index, cue) for index, cue in batch if index in missing]
+ collect_translations(missing_batch, set(missing), translations, client)
+ missing = sorted(expected_indexes - translations.keys())
+ if missing:
+ for index, cue in [(index, cue) for index, cue in batch if index in missing]:
+ collect_translations([(index, cue)], {index}, translations, client)
+ missing = sorted(expected_indexes - translations.keys())
if missing:
raise ValueError(f"AI 返回的翻译条数和英文字幕条数不一致,缺少 index:{missing[:10]}")
return translations
+def collect_translations(
+ batch: list[tuple[int, SubtitleCue]],
+ expected_indexes: set[int],
+ translations: dict[int, dict[str, object]],
+ client,
+) -> None:
+ if not batch:
+ return
+ payload = {
+ "cues": [
+ {"index": index, "text": cue.text}
+ for index, cue in batch
+ ]
+ }
+ response = client.chat_json(TRANSLATION_SYSTEM_PROMPT, payload)
+ batch_translations = response.get("translations")
+ if not isinstance(batch_translations, list):
+ raise ValueError("AI 返回结果缺少 translations。")
+
+ for item in batch_translations:
+ if not isinstance(item, dict):
+ continue
+ try:
+ item_index = int(item.get("index"))
+ except (TypeError, ValueError):
+ continue
+ if item_index in expected_indexes:
+ translations[item_index] = item
+
+
def count_batches(cue_count: int, batch_size: int) -> int:
effective_batch_size = int(batch_size or 0)
if cue_count <= 0:
diff --git a/backend/subtitle_alignment.py b/backend/subtitle_alignment.py
deleted file mode 100644
index 2172f60..0000000
--- a/backend/subtitle_alignment.py
+++ /dev/null
@@ -1,124 +0,0 @@
-from __future__ import annotations
-
-from dataclasses import dataclass
-from pathlib import Path
-import subprocess
-import tempfile
-from typing import Callable
-
-from .subtitle_tools import SubtitleCue, parse_timestamp
-
-
-FIRST_SENTENCE_ALIGNMENT_PROMPT = """
-你是字幕首句时间校准助手。你只需要分析这段音频的前 10 秒。
-请找出给定英文字幕第一句在音频中真正开始说话的时间,单位是秒。
-只返回 JSON:{"first_sentence_start":1.23,"matched_text":"...","confidence":0.95}
-不要返回解释,不要校准后续句子。
-""".strip()
-
-
-@dataclass
-class AlignmentResult:
- applied: bool
- offset_seconds: float
- first_sentence_start: float | None
- confidence: float
- note: str
-
-
-def align_first_sentence(video_path: Path, first_cue: SubtitleCue, client) -> AlignmentResult:
- if not video_path.exists():
- return AlignmentResult(False, 0.0, None, 0.0, "视频文件不存在,已跳过自动首句校准。")
-
- with tempfile.TemporaryDirectory() as temp_dir:
- audio_path = Path(temp_dir) / "first10.wav"
- try:
- extract_first_audio(video_path, audio_path)
- response = client.audio_json(
- FIRST_SENTENCE_ALIGNMENT_PROMPT,
- audio_path,
- f"第一句英文字幕:{first_cue.text}\n请只判断这句开始说话的秒数。",
- )
- except Exception as error:
- return AlignmentResult(False, 0.0, None, 0.0, f"首句自动校准失败,已跳过:{error}")
-
- return alignment_from_start(first_cue, response.get("first_sentence_start"), response.get("confidence"))
-
-
-def align_first_sentence_with_asr(
- video_path: Path,
- first_cue: SubtitleCue,
- asr_client,
- extract_audio: Callable[[Path, Path], None] = None,
-) -> AlignmentResult:
- if not video_path.exists():
- return AlignmentResult(False, 0.0, None, 0.0, "视频文件不存在,已跳过 OpenAI ASR 首句校准。")
-
- audio_extractor = extract_audio or extract_first_audio
- with tempfile.TemporaryDirectory() as temp_dir:
- audio_path = Path(temp_dir) / "first10.wav"
- try:
- audio_extractor(video_path, audio_path)
- response = asr_client.transcribe(audio_path)
- except Exception as error:
- return AlignmentResult(False, 0.0, None, 0.0, f"OpenAI ASR 首句校准失败,已跳过:{error}")
-
- first_start = first_segment_start(response)
- return alignment_from_start(first_cue, first_start, 0.9, source_name="OpenAI ASR")
-
-
-def alignment_from_start(
- first_cue: SubtitleCue,
- start_value,
- confidence_value=None,
- source_name: str = "AI",
-) -> AlignmentResult:
- first_sentence_start = parse_alignment_second(start_value)
- confidence = parse_alignment_second(confidence_value)
- if first_sentence_start is None:
- return AlignmentResult(False, 0.0, None, confidence or 0.0, f"{source_name} 没有返回有效的首句开始时间,已跳过自动校准。")
-
- offset = first_sentence_start - parse_timestamp(first_cue.start)
- if abs(offset) > 5:
- return AlignmentResult(False, 0.0, first_sentence_start, confidence or 0.0, f"检测到偏移 {offset:.2f} 秒,超过 5 秒安全阈值,已跳过自动校准。")
-
- return AlignmentResult(True, offset, first_sentence_start, confidence or 0.0, f"{source_name} 首句校准成功,整体平移 {offset:.2f} 秒。")
-
-
-def first_segment_start(response: dict[str, object]) -> float | None:
- segments = response.get("segments")
- if isinstance(segments, list):
- for segment in segments:
- if isinstance(segment, dict):
- start = parse_alignment_second(segment.get("start"))
- text = str(segment.get("text", "")).strip()
- if start is not None and text:
- return start
- return None
-
-
-def extract_first_audio(video_path: Path, audio_path: Path) -> None:
- command = [
- "ffmpeg",
- "-y",
- "-i",
- str(video_path),
- "-ss",
- "0",
- "-t",
- "10",
- "-vn",
- "-ac",
- "1",
- "-ar",
- "16000",
- str(audio_path),
- ]
- subprocess.run(command, check=True, capture_output=True)
-
-
-def parse_alignment_second(value) -> float | None:
- try:
- return float(value)
- except (TypeError, ValueError):
- return None
diff --git a/backend/subtitle_tools.py b/backend/subtitle_tools.py
index acf0001..0137e4f 100644
--- a/backend/subtitle_tools.py
+++ b/backend/subtitle_tools.py
@@ -125,17 +125,3 @@ def format_timestamp(seconds: float) -> str:
whole_seconds = (total_milliseconds % 60_000) // 1000
milliseconds = total_milliseconds % 1000
return f"{hours:02d}:{minutes:02d}:{whole_seconds:02d}.{milliseconds:03d}"
-
-
-def shift_cues(cues: list[SubtitleCue] | list[dict[str, str]], offset_seconds: float) -> list[SubtitleCue]:
- shifted: list[SubtitleCue] = []
- for cue in cues:
- 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"]
- shifted.append(SubtitleCue(
- format_timestamp(parse_timestamp(start) + offset_seconds),
- format_timestamp(parse_timestamp(end) + offset_seconds),
- text,
- ))
- return shifted
diff --git a/docs/superpowers/plans/2026-06-04-speaking-lab-home-premium-cards.md b/docs/superpowers/plans/2026-06-04-speaking-lab-home-premium-cards.md
new file mode 100644
index 0000000..681ff59
--- /dev/null
+++ b/docs/superpowers/plans/2026-06-04-speaking-lab-home-premium-cards.md
@@ -0,0 +1,75 @@
+# Speaking Lab Home Premium Cards UI Implementation Plan
+
+> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
+
+**Goal:** Restyle the home page with a spacious premium card-based learning library look.
+
+**Architecture:** Keep the existing HTML and JavaScript. Implement the design through `styles.css` by updating page background, home grid layout, dashboard surfaces, metric button states, material card presentation, stat bar styling, and chip styling.
+
+**Tech Stack:** CSS, existing vanilla HTML/JS, existing local FastAPI server for browser verification.
+
+---
+
+## Task 1: Restyle Home Layout And Dashboard
+
+**Files:**
+- Modify: `F:\ooo\speaking-practice-local\styles.css`
+
+- [ ] **Step 1: Update page background and home shell**
+
+Set `.home-page` to `#f8fafc`, and `.home-shell` to a 280px sidebar grid with larger gap and padding.
+
+- [ ] **Step 2: Update dashboard surface**
+
+Make `.home-dashboard-title` and `.home-metric` feel premium: white background, 16px radius, soft gray shadow, smooth transition.
+
+- [ ] **Step 3: Add metric hover and active states**
+
+Hover should lift slightly and deepen the border/shadow. Active should use a subtle blue-tinted or teal-tinted background, not harsh black.
+
+## Task 2: Restyle Material Grid And Cards
+
+**Files:**
+- Modify: `F:\ooo\speaking-practice-local\styles.css`
+
+- [ ] **Step 1: Update card grid**
+
+Use `repeat(auto-fill, minmax(320px, 1fr))` and `gap: 24px`.
+
+- [ ] **Step 2: Update material cards**
+
+Use white cards, 16px radius, overflow hidden, soft shadow, and `translateY(-4px)` hover.
+
+- [ ] **Step 3: Update cover and card body**
+
+Set cover height to 180px. Increase card body padding. Improve title weight/color/line-height.
+
+- [ ] **Step 4: Update stats**
+
+Make `.home-card-stats` a compact bottom bar with a dashed top border and horizontal flex-like grid.
+
+## Task 3: Restyle Chips And Verify
+
+**Files:**
+- Modify: `F:\ooo\speaking-practice-local\styles.css`
+
+- [ ] **Step 1: Update `.chip`**
+
+Make chips capsule-shaped with soft gray default state and strong active state.
+
+- [ ] **Step 2: Run checks**
+
+Run:
+
+```powershell
+node --check home.js
+node --check app.js
+node --check admin.js
+python -m py_compile backend\main.py backend\db.py
+node tests\progress-helpers.test.mjs
+node tests\admin-file-input.test.mjs
+```
+
+- [ ] **Step 3: Browser verify**
+
+Open `http://127.0.0.1:8000/` and confirm layout, cards, hover behavior, chips, and no text overlap.
diff --git a/docs/superpowers/plans/2026-06-04-speaking-lab-study-toolbar-polish.md b/docs/superpowers/plans/2026-06-04-speaking-lab-study-toolbar-polish.md
new file mode 100644
index 0000000..3ccf897
--- /dev/null
+++ b/docs/superpowers/plans/2026-06-04-speaking-lab-study-toolbar-polish.md
@@ -0,0 +1,64 @@
+# Speaking Lab Study Toolbar Polish Implementation Plan
+
+> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
+
+**Goal:** Center the main sentence controls, enlarge the loop toggle, remove continue/watch-later actions from the study toolbar, and polish the study page visual consistency.
+
+**Architecture:** Update `study.html` toolbar zones, remove now-unused visible bindings from `app.js`, and restyle the toolbar in `styles.css`. Keep existing recording, favorite, sentence navigation, and loop behavior.
+
+**Tech Stack:** Vanilla HTML, CSS, JavaScript.
+
+---
+
+## Task 1: Update Toolbar Markup
+
+**Files:**
+- Modify: `F:\ooo\speaking-practice-local\study.html`
+
+- [ ] Replace toolbar content with three zones:
+ - `.recording-controls`: `录音 / 停止 / 回放`
+ - `.sentence-controls`: `上一句 / 重播 / 下一句`
+ - `.study-side-actions`: enlarged loop toggle and `收藏`
+
+## Task 2: Remove Deleted Button Bindings
+
+**Files:**
+- Modify: `F:\ooo\speaking-practice-local\app.js`
+
+- [ ] Remove `continueBtn` and `watchLaterBtn` DOM references.
+- [ ] Remove event listeners for `continueLearning` and `watchLater`.
+- [ ] Remove visible text updates for `watchLaterBtn`.
+- [ ] Guard or remove `renderContinueAction()` calls so no missing element is referenced.
+
+## Task 3: Style Unified Toolbar
+
+**Files:**
+- Modify: `F:\ooo\speaking-practice-local\styles.css`
+
+- [ ] Make `.tool-row` a three-column grid: left, center, right.
+- [ ] Style `.sentence-controls` as the centered primary control group.
+- [ ] Style `.recording-controls` as secondary.
+- [ ] Enlarge `.toggle` inside `.study-side-actions`.
+- [ ] Keep narrow viewport wrapping without horizontal overflow.
+
+## Task 4: Verify
+
+Run:
+
+```powershell
+node --check app.js
+node --check home.js
+node --check admin.js
+python -m py_compile backend\main.py backend\db.py
+node tests\progress-helpers.test.mjs
+node tests\admin-file-input.test.mjs
+```
+
+Browser check:
+
+- Open `http://127.0.0.1:8000/study.html`.
+- Confirm `继续学习` and `稍后再看` are gone.
+- Confirm `上一句 / 重播 / 下一句` are centered.
+- Confirm loop toggle is larger.
+- Confirm favorite remains.
+- Confirm no horizontal overflow.
diff --git a/docs/superpowers/specs/2026-06-04-speaking-lab-home-premium-cards-design.md b/docs/superpowers/specs/2026-06-04-speaking-lab-home-premium-cards-design.md
new file mode 100644
index 0000000..859ba5c
--- /dev/null
+++ b/docs/superpowers/specs/2026-06-04-speaking-lab-home-premium-cards-design.md
@@ -0,0 +1,86 @@
+# Speaking Lab Home Premium Cards UI Design
+
+## Goal
+
+Upgrade the home page visual design into a cleaner, higher-quality learning library interface.
+
+This pass focuses on spacing, cards, dashboard polish, material card quality, and category chips.
+
+## Scope
+
+Included:
+
+- Home page background and layout spacing.
+- Home shell grid with a 280px sidebar and adaptive content area.
+- White dashboard surface with 16px radius and soft shadow.
+- Metric card hover and active transitions.
+- Larger, clearer metric numbers.
+- Responsive material card grid using `repeat(auto-fill, minmax(320px, 1fr))`.
+- Premium white material cards with 16px radius, soft shadow, and hover lift.
+- Fixed 180px cover area.
+- More comfortable card content spacing and title hierarchy.
+- Dashed divider above card stats.
+- Card stats as a compact horizontal bottom bar.
+- Capsule category chips with soft default state and strong active state.
+
+Excluded:
+
+- README changes.
+- Backend changes.
+- Study page changes.
+- Admin page changes.
+- New data fields.
+- Custom thumbnail upload.
+- Real image extraction.
+
+## Visual Rules
+
+Use:
+
+- page background `#f8fafc`
+- cards `#ffffff`
+- soft gray borders
+- soft non-black shadows
+- 16px radii for dashboard and material cards
+- 20px pill radii for chips
+- subtle motion: `translateY(-4px)` on material card hover
+
+Avoid:
+
+- heavy dark shadows
+- large gradients dominating cards
+- reducing readability
+- layout shifts on hover
+
+## Implementation Notes
+
+The existing HTML structure already supports the design.
+
+Implementation should primarily modify `styles.css`.
+
+The existing generated cover tones can remain, but the cover area should have a stable 180px height and feel more refined.
+
+The existing `dl.home-card-stats` should be restyled as a bottom stat bar instead of boxed mini cards.
+
+## Verification
+
+Automated checks:
+
+```powershell
+node --check home.js
+node --check app.js
+node --check admin.js
+python -m py_compile backend\main.py backend\db.py
+node tests\progress-helpers.test.mjs
+node tests\admin-file-input.test.mjs
+```
+
+Browser checks:
+
+1. Open `http://127.0.0.1:8000/`.
+2. Confirm the page background is light gray-blue.
+3. Confirm sidebar width and spacing feel more premium.
+4. Confirm material card grid uses wider cards.
+5. Hover a material card and confirm it lifts smoothly.
+6. Confirm category chips are capsule-shaped.
+7. Confirm no text overlaps on desktop or narrow viewport.
diff --git a/docs/superpowers/specs/2026-06-04-speaking-lab-study-toolbar-polish-design.md b/docs/superpowers/specs/2026-06-04-speaking-lab-study-toolbar-polish-design.md
new file mode 100644
index 0000000..87c86ac
--- /dev/null
+++ b/docs/superpowers/specs/2026-06-04-speaking-lab-study-toolbar-polish-design.md
@@ -0,0 +1,73 @@
+# Speaking Lab Study Toolbar Polish Design
+
+## Goal
+
+Refine the study page toolbar so the core English practice controls feel centered, focused, and visually consistent with the upgraded home page UI.
+
+## Scope
+
+Included:
+
+- Remove `继续学习` from the study page toolbar.
+- Remove `稍后再看` from the study page toolbar.
+- Keep `收藏`.
+- Place `上一句 / 重播 / 下一句` in the visual center as the primary practice controls.
+- Place recording controls as secondary controls on the left.
+- Place a larger loop toggle and favorite action on the right.
+- Style the toolbar and buttons with a premium white-card look matching the home page.
+
+Excluded:
+
+- Removing existing localStorage `watchLater` data.
+- Removing helper functions unrelated to visible toolbar behavior.
+- Backend changes.
+- README changes.
+- Home page changes.
+
+## Layout
+
+The toolbar uses three zones:
+
+- Left: `录音 / 停止 / 回放`
+- Center: `上一句 / 重播 / 下一句`
+- Right: large `循环` toggle and `收藏`
+
+On narrow screens, the zones may wrap but should remain readable and should not overflow horizontally.
+
+## Behavior
+
+Existing behavior remains:
+
+- Previous sentence jumps back one cue.
+- Replay jumps to current sentence.
+- Next sentence jumps forward one cue.
+- Loop checkbox controls sentence loop.
+- Favorite toggles current material in favorites.
+- Recording controls keep existing browser recording behavior.
+
+Removed behavior:
+
+- The study page no longer exposes a `继续学习` button.
+- The study page no longer exposes a `稍后再看` button.
+
+## Verification
+
+Run:
+
+```powershell
+node --check app.js
+node --check home.js
+node --check admin.js
+python -m py_compile backend\main.py backend\db.py
+node tests\progress-helpers.test.mjs
+node tests\admin-file-input.test.mjs
+```
+
+Browser checks:
+
+1. Open `http://127.0.0.1:8000/study.html`.
+2. Confirm `上一句 / 重播 / 下一句` are centered.
+3. Confirm `循环` is larger and easy to see.
+4. Confirm `继续学习` and `稍后再看` do not appear.
+5. Confirm `收藏` still works.
+6. Confirm no horizontal overflow on a narrow viewport.
diff --git a/study.html b/study.html
index e02ad3f..faca5e7 100644
--- a/study.html
+++ b/study.html
@@ -4,7 +4,7 @@
Speaking Lab
-
+