From 0608b846649a82e0017f01899f31719396c34ffa Mon Sep 17 00:00:00 2001 From: TTlaji Date: Thu, 4 Jun 2026 01:26:41 +0800 Subject: [PATCH] feat: refine subtitle flow and study UI --- admin.html | 14 +- admin.js | 186 +++++------ app.js | 41 +-- backend/ai_config.py | 32 -- backend/main.py | 58 +--- backend/openai_asr_client.py | 66 ---- backend/subtitle_ai.py | 68 ++-- backend/subtitle_alignment.py | 124 -------- backend/subtitle_tools.py | 14 - ...6-06-04-speaking-lab-home-premium-cards.md | 75 +++++ ...06-04-speaking-lab-study-toolbar-polish.md | 64 ++++ ...-speaking-lab-home-premium-cards-design.md | 86 +++++ ...peaking-lab-study-toolbar-polish-design.md | 73 +++++ study.html | 42 +-- styles.css | 300 +++++++++++++----- tests/admin-ai-state.test.mjs | 27 +- tests/admin-subtitle-editor.test.mjs | 24 +- tests/ai_client_test.py | 1 - tests/ai_config_test.py | 15 +- tests/ai_routes_test.py | 37 +++ tests/openai_asr_client_test.py | 69 ---- tests/subtitle_ai_test.py | 53 +++- tests/subtitle_alignment_test.py | 39 --- tests/subtitle_tools_test.py | 17 +- 24 files changed, 795 insertions(+), 730 deletions(-) delete mode 100644 backend/openai_asr_client.py delete mode 100644 backend/subtitle_alignment.py create mode 100644 docs/superpowers/plans/2026-06-04-speaking-lab-home-premium-cards.md create mode 100644 docs/superpowers/plans/2026-06-04-speaking-lab-study-toolbar-polish.md create mode 100644 docs/superpowers/specs/2026-06-04-speaking-lab-home-premium-cards-design.md create mode 100644 docs/superpowers/specs/2026-06-04-speaking-lab-study-toolbar-polish-design.md delete mode 100644 tests/openai_asr_client_test.py delete mode 100644 tests/subtitle_alignment_test.py 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 - +
@@ -37,32 +37,22 @@
- - - - - - - -
- -
-

-

-
- -
-
-

还没有选择视频

-

请选择视频。

+
+ + +
-
- +
+ + + +
+
+ -
@@ -87,6 +77,6 @@ - + diff --git a/styles.css b/styles.css index 0f83ca7..433b36c 100644 --- a/styles.css +++ b/styles.css @@ -111,7 +111,9 @@ textarea:focus { .tag-filters, .tabs, .video-actions, -.tool-row, +.recording-controls, +.sentence-controls, +.study-side-actions, .lesson-meta, .recording-line { display: flex; @@ -154,11 +156,22 @@ textarea:focus { } .chip { - min-height: 30px; - border-radius: 999px; - padding: 0 10px; + min-height: 34px; + border-color: transparent; + border-radius: 20px; + padding: 0 14px; + color: #27364a; + background: #eef2f7; font-size: 12px; + font-weight: 700; white-space: nowrap; + transition: color 160ms ease, background 160ms ease, border-color 160ms ease, box-shadow 160ms ease; +} + +.chip:hover { + border-color: #cbd5e1; + background: #f8fafc; + box-shadow: 0 6px 16px rgba(15, 39, 66, 0.08); } .chip.active { @@ -307,12 +320,12 @@ textarea:focus { min-height: 0; overflow: hidden; display: grid; - grid-template-rows: minmax(320px, 1fr) auto auto auto auto; + grid-template-rows: minmax(520px, 1fr) auto auto; } .video-frame { position: relative; - min-height: 320px; + min-height: 520px; background: #0b1220; } @@ -340,24 +353,119 @@ video { } .tool-row { - gap: 8px; - padding: 9px 12px; + display: grid; + grid-template-columns: minmax(0, 1fr) auto minmax(0, 1fr); + align-items: center; + gap: 16px; + min-height: 71px; + padding: 14px 16px; border-top: 1px solid var(--line); background: #fff; - overflow-x: auto; + overflow: visible; +} + +.recording-controls { + justify-content: flex-start; + gap: 8px; + min-width: 0; + flex-wrap: wrap; +} + +.sentence-controls { + justify-content: center; + gap: 10px; + min-width: 0; + flex-wrap: wrap; +} + +.study-side-actions { + justify-content: flex-end; + gap: 10px; + min-width: 0; + flex-wrap: wrap; } .tool-row button { - min-width: 40px; + min-width: 54px; + min-height: 38px; + border-radius: 10px; border-color: #d8e2ec; background: #f8fafc; font-weight: 650; white-space: nowrap; + transition: background 160ms ease, border-color 160ms ease, box-shadow 160ms ease, transform 160ms ease; +} + +.tool-row button:disabled { + border-color: #e2e8f0; + color: #98a2b3; + background: #f1f5f9; + box-shadow: none; + transform: none; } .tool-row button:hover { border-color: #b9dcd5; background: var(--brand-soft); + box-shadow: 0 8px 20px rgba(15, 118, 110, 0.1); + transform: translateY(-1px); +} + +.sentence-controls button { + min-width: 76px; + color: #0f2742; + border-color: #c8d7e6; + background: #ffffff; + font-size: 15px; + font-weight: 800; +} + +.sentence-controls #replayBtn { + color: #fff; + border-color: var(--accent); + background: var(--accent); +} + +.sentence-controls #replayBtn:hover { + border-color: #1e3a5f; + background: #1e3a5f; + box-shadow: 0 10px 24px rgba(15, 39, 66, 0.2); +} + +.sentence-controls #replayBtn:disabled { + border-color: #d8e2ec; + color: #98a2b3; + background: #e8eef5; +} + +.study-side-actions .toggle { + min-height: 42px; + padding: 0 14px; + border: 1px solid #c8d7e6; + border-radius: 999px; + color: #0f2742; + background: #f8fafc; + font-size: 14px; + font-weight: 800; + transition: background 160ms ease, border-color 160ms ease, box-shadow 160ms ease, transform 160ms ease; +} + +.study-side-actions .toggle:hover { + border-color: #b9dcd5; + background: var(--brand-soft); + box-shadow: 0 8px 20px rgba(15, 118, 110, 0.1); + transform: translateY(-1px); +} + +.study-side-actions .toggle input { + width: 18px; + height: 18px; +} + +.study-side-actions #favoriteBtn { + min-width: 68px; + color: #0f2742; + background: #fff; } .subtitle-card { @@ -720,36 +828,22 @@ video { } .admin-ai-panel, -.admin-subtitle-shift { - 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, -.admin-subtitle-shift h3, -.admin-subtitle-shift p { +.admin-ai-panel p { margin: 0; } -.admin-ai-panel h3, -.admin-subtitle-shift h3 { +.admin-ai-panel h3 { font-size: 14px; } -.admin-ai-panel p, -.admin-subtitle-shift p { +.admin-ai-panel p { color: var(--muted); font-size: 13px; line-height: 1.45; } -.admin-ai-actions, -.admin-shift-actions { +.admin-ai-actions { display: flex; flex-wrap: wrap; gap: 8px; @@ -938,7 +1032,7 @@ video { .home-page { min-height: 100vh; - background: var(--bg); + background: #f8fafc; } .home-topbar .brand { @@ -951,11 +1045,11 @@ video { .home-shell { display: grid; - grid-template-columns: 260px minmax(0, 1fr); - gap: 18px; + grid-template-columns: 280px minmax(0, 1fr); + gap: 32px; width: 100%; margin: 0; - padding: 20px 24px 40px; + padding: 32px 40px 56px; } .home-dashboard, @@ -966,17 +1060,17 @@ video { .home-dashboard { align-self: start; position: sticky; - top: 82px; + top: 94px; display: grid; - gap: 12px; + gap: 14px; } .home-dashboard-title { - padding: 14px; + padding: 18px; border: 1px solid var(--line); - border-radius: 8px; - background: var(--panel); - box-shadow: var(--shadow); + border-radius: 16px; + background: #fff; + box-shadow: 0 18px 45px rgba(15, 23, 42, 0.06); } .home-dashboard-title span, @@ -999,20 +1093,29 @@ video { .home-metrics { display: grid; - gap: 9px; + gap: 12px; } .home-metric { - min-height: 76px; + min-height: 82px; display: grid; grid-template-columns: 38px minmax(0, 1fr) auto; align-items: center; - gap: 10px; - padding: 12px; + gap: 12px; + padding: 14px; text-align: left; - border-radius: 8px; - background: var(--panel); - box-shadow: var(--shadow); + border-color: #edf1f6; + border-radius: 16px; + background: #fff; + box-shadow: 0 14px 34px rgba(15, 23, 42, 0.05); + transition: transform 180ms ease, border-color 180ms ease, box-shadow 180ms ease, background 180ms ease; +} + +.home-metric:hover { + transform: translateY(-2px); + border-color: #cbd5e1; + background: #ffffff; + box-shadow: 0 20px 44px rgba(15, 23, 42, 0.09); } .home-metric-icon { @@ -1035,7 +1138,8 @@ video { } .home-metric strong { - font-size: 24px; + color: #0f2742; + font-size: 28px; line-height: 1; font-variant-numeric: tabular-nums; } @@ -1071,8 +1175,9 @@ video { } .home-metric.active { - border-color: #b9dcd5; - background: #f0fbf8; + border-color: #a7c7e8; + background: #eef7ff; + box-shadow: 0 18px 42px rgba(37, 99, 235, 0.11); } .home-metric.active small { @@ -1084,7 +1189,7 @@ video { justify-content: space-between; align-items: flex-start; gap: 16px; - margin-bottom: 16px; + margin-bottom: 20px; } .home-heading h2 { @@ -1100,31 +1205,38 @@ video { .home-categories { display: flex; - gap: 8px; + gap: 10px; overflow-x: auto; - padding: 2px 0 12px; + padding: 2px 0 18px; } .home-status { min-height: 22px; color: var(--muted); font-size: 13px; - margin-bottom: 12px; + margin-bottom: 18px; } .home-grid { display: grid; - grid-template-columns: repeat(auto-fill, minmax(250px, 1fr)); - gap: 14px; + grid-template-columns: repeat(auto-fill, minmax(320px, 1fr)); + gap: 24px; } .home-card { min-width: 0; overflow: hidden; - border: 1px solid var(--line); - border-radius: 8px; - background: var(--panel); - box-shadow: var(--shadow); + border: 1px solid #edf1f6; + border-radius: 16px; + background: #fff; + box-shadow: 0 18px 42px rgba(15, 23, 42, 0.06); + transition: transform 180ms ease, box-shadow 180ms ease, border-color 180ms ease; +} + +.home-card:hover { + transform: translateY(-4px); + border-color: #d6dee9; + box-shadow: 0 26px 60px rgba(15, 23, 42, 0.12); } .home-card-link { @@ -1139,12 +1251,12 @@ video { .home-cover { position: relative; - min-height: 138px; + min-height: 180px; display: grid; align-content: space-between; - padding: 14px; + padding: 16px; color: #fff; - background: #0f766e; + background: #e5eaf1; } .home-favorite { @@ -1204,13 +1316,15 @@ video { } .home-card-body { - padding: 12px; + padding: 18px; } .home-card-body h3 { margin: 0; - font-size: 16px; - line-height: 1.35; + color: #1a202c; + font-size: 18px; + font-weight: 850; + line-height: 1.42; } .home-card-meta, @@ -1226,7 +1340,7 @@ video { display: flex; flex-wrap: wrap; gap: 6px; - margin-top: 10px; + margin-top: 12px; } .home-card-tags span { @@ -1240,15 +1354,18 @@ video { .home-card-stats { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); - gap: 6px; - margin: 12px 0 0; + gap: 14px; + margin: 16px 0 0; + padding-top: 14px; + border-top: 1px dashed #d7dee8; } .home-card-stats div { min-width: 0; - padding: 8px; - border-radius: 7px; - background: var(--panel-soft); + display: flex; + align-items: baseline; + justify-content: space-between; + gap: 8px; } .home-card-stats dt, @@ -1259,12 +1376,14 @@ video { .home-card-stats dt { color: var(--muted); font-size: 11px; + white-space: nowrap; } .home-card-stats dd { - margin-top: 3px; + color: #1a202c; font-weight: 800; font-size: 13px; + white-space: nowrap; } .home-progress { @@ -1301,11 +1420,46 @@ video { padding-top: 12px; } + .tool-row { + grid-template-columns: 1fr; + justify-items: stretch; + gap: 10px; + } + + .recording-controls, + .sentence-controls, + .study-side-actions { + justify-content: center; + } + .admin-form { grid-template-columns: 1fr; } } +@media (max-width: 560px) { + .study-shell { + padding-left: 10px; + padding-right: 10px; + } + + .video-panel { + grid-template-rows: minmax(360px, 1fr) auto auto; + } + + .video-frame { + min-height: 360px; + } + + .tool-row { + padding: 12px; + } + + .sentence-controls button { + flex: 1 1 84px; + } +} + @media (max-width: 900px) { .admin-topbar { height: auto; @@ -1336,7 +1490,8 @@ video { @media (max-width: 720px) { .home-shell { grid-template-columns: 1fr; - padding: 14px 12px 28px; + gap: 20px; + padding: 18px 14px 32px; } .home-dashboard { @@ -1358,5 +1513,6 @@ video { .home-grid { grid-template-columns: 1fr; + gap: 18px; } } diff --git a/tests/admin-ai-state.test.mjs b/tests/admin-ai-state.test.mjs index 3ee70fc..97a9b12 100644 --- a/tests/admin-ai-state.test.mjs +++ b/tests/admin-ai-state.test.mjs @@ -1,7 +1,12 @@ import assert from "node:assert/strict"; import adminHelpers from "../admin.js"; -const { getAiSubtitleButtonState, pickVideoAfterSave } = adminHelpers; +const { + getAiSubtitleButtonState, + getLocalWhisperButtonState, + pickVideoAfterSave, + shouldConfirmSubtitleOverwrite, +} = adminHelpers; assert.deepEqual(getAiSubtitleButtonState({ configured: false }, { id: 1 }), { disabled: true, @@ -18,7 +23,27 @@ assert.deepEqual(getAiSubtitleButtonState({ configured: true }, { id: 1 }), { hint: "", }); +assert.deepEqual(getLocalWhisperButtonState({ configured: false, localWhisperEnabled: true }, { id: 1 }), { + disabled: false, + hint: "", +}); + +assert.deepEqual(getLocalWhisperButtonState({ configured: true, localWhisperEnabled: false }, { id: 1 }), { + disabled: true, + hint: "请先开启本地 Whisper。", +}); + +assert.deepEqual(getLocalWhisperButtonState({ configured: true, localWhisperEnabled: true }, null), { + disabled: true, + hint: "请先在右侧素材列表点“编辑”。", +}); + const created = { id: 9, title: "New material" }; const previous = { id: 7, title: "Old material" }; assert.equal(pickVideoAfterSave([previous, created], { video: created }, null), created); assert.equal(pickVideoAfterSave([previous, created], { ok: true }, previous), previous); + +assert.equal(shouldConfirmSubtitleOverwrite(null), false); +assert.equal(shouldConfirmSubtitleOverwrite({ subtitles: {} }), false); +assert.equal(shouldConfirmSubtitleOverwrite({ subtitles: { en: { content: "WEBVTT\n\nhello" } } }), true); +assert.equal(shouldConfirmSubtitleOverwrite({ subtitles: { zh: { content: "WEBVTT\n\nhello" } } }), false); diff --git a/tests/admin-subtitle-editor.test.mjs b/tests/admin-subtitle-editor.test.mjs index 61d23e5..40ee484 100644 --- a/tests/admin-subtitle-editor.test.mjs +++ b/tests/admin-subtitle-editor.test.mjs @@ -1,7 +1,7 @@ import assert from "node:assert/strict"; import adminHelpers from "../admin.js"; -const { buildWebVtt, parseSubtitleBlocks, shiftCueTimeRange, shiftSubtitleCues } = adminHelpers; +const { buildWebVtt, parseSubtitleBlocks } = adminHelpers; const cues = parseSubtitleBlocks(`WEBVTT @@ -41,23 +41,5 @@ Second line continued `); -assert.equal( - shiftCueTimeRange("00:00:00.200 --> 00:00:01.200", -0.5), - "00:00:00.000 --> 00:00:00.700", -); - -assert.equal( - shiftCueTimeRange("00:00:04.000 --> 00:00:08.000", 0.5), - "00:00:04.500 --> 00:00:08.500", -); - -assert.equal( - shiftCueTimeRange("00:00:04.000 --> 00:00:08.000", 0.2), - "00:00:04.200 --> 00:00:08.200", -); - -const shifted = shiftSubtitleCues([ - { timeRange: "00:00:04.000 --> 00:00:08.000", text: "Second line" }, -], 1.25); -assert.equal(shifted[0].timeRange, "00:00:05.250 --> 00:00:09.250"); -assert.equal(shifted[0].text, "Second line"); +assert.equal(adminHelpers.shiftCueTimeRange, undefined); +assert.equal(adminHelpers.shiftSubtitleCues, undefined); diff --git a/tests/ai_client_test.py b/tests/ai_client_test.py index d92ce0c..deb449d 100644 --- a/tests/ai_client_test.py +++ b/tests/ai_client_test.py @@ -32,7 +32,6 @@ def make_config() -> DeepSeekConfig: protocol="anthropic", translation_batch_size=20, timeout_seconds=180, - enable_audio_alignment=False, ) diff --git a/tests/ai_config_test.py b/tests/ai_config_test.py index 5bde563..28c8bbc 100644 --- a/tests/ai_config_test.py +++ b/tests/ai_config_test.py @@ -6,7 +6,6 @@ sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) from backend import ai_config from backend.ai_config import ( get_ai_status, - load_asr_config, load_deepseek_config, load_local_whisper_config, load_text_ai_config, @@ -42,7 +41,6 @@ def test_load_deepseek_config_accepts_generic_ai_names(monkeypatch): monkeypatch.setenv("AI_API_PROTOCOL", "anthropic") monkeypatch.setenv("AI_TRANSLATION_BATCH_SIZE", "15") monkeypatch.setenv("AI_TIMEOUT_SECONDS", "180") - monkeypatch.setenv("AI_ENABLE_AUDIO_ALIGNMENT", "true") config = load_deepseek_config() @@ -53,29 +51,20 @@ def test_load_deepseek_config_accepts_generic_ai_names(monkeypatch): assert config.protocol == "anthropic" assert config.translation_batch_size == 15 assert config.timeout_seconds == 180 - assert config.enable_audio_alignment is True -def test_load_split_text_and_asr_configs(monkeypatch): +def test_load_split_text_config(monkeypatch): monkeypatch.setenv("TEXT_AI_API_KEY", "text-key") monkeypatch.setenv("TEXT_AI_BASE_URL", "https://api.deepseek.com") monkeypatch.setenv("TEXT_AI_MODEL", "deepseek-chat") monkeypatch.setenv("TEXT_AI_PROTOCOL", "openai") - monkeypatch.setenv("ASR_PROVIDER", "openai") - monkeypatch.setenv("OPENAI_API_KEY", "openai-key") - monkeypatch.setenv("OPENAI_ASR_MODEL", "whisper-1") text_config = load_text_ai_config() - asr_config = load_asr_config() assert text_config.api_key == "text-key" assert text_config.base_url == "https://api.deepseek.com" assert text_config.model == "deepseek-chat" assert text_config.protocol == "openai" - assert asr_config.configured is True - assert asr_config.provider == "openai" - assert asr_config.api_key == "openai-key" - assert asr_config.model == "whisper-1" def test_text_ai_batch_size_allows_zero(monkeypatch): @@ -168,7 +157,7 @@ if __name__ == "__main__": patch.restore() test_load_deepseek_config_accepts_generic_ai_names(patch) patch.restore() - test_load_split_text_and_asr_configs(patch) + test_load_split_text_config(patch) patch.restore() test_text_ai_batch_size_allows_zero(patch) patch.restore() diff --git a/tests/ai_routes_test.py b/tests/ai_routes_test.py index 36f6a6d..35a6aca 100644 --- a/tests/ai_routes_test.py +++ b/tests/ai_routes_test.py @@ -11,6 +11,7 @@ from backend import ai_config, main class EnvPatch: def __init__(self): self.originals = {} + self.attributes = [] def delenv(self, key, raising=True): import os @@ -29,6 +30,13 @@ class EnvPatch: os.environ.pop(key, None) else: os.environ[key] = value + while self.attributes: + target, name, original = self.attributes.pop() + setattr(target, name, original) + + def setattr(self, target, name, value): + self.attributes.append((target, name, getattr(target, name))) + setattr(target, name, value) def test_ai_status_route_reports_missing_key(monkeypatch): @@ -52,6 +60,33 @@ def test_ai_test_route_rejects_missing_key(monkeypatch): raise AssertionError("api_ai_test should reject missing DeepSeek API key") +def test_local_whisper_route_generates_only_english_subtitle(monkeypatch): + calls = [] + + monkeypatch.setattr(main, "get_video", lambda video_id: {"id": video_id, "videoUrl": "/uploads/videos/demo.mp4", "subtitles": {}}) + monkeypatch.setattr(main, "upload_url_to_path", lambda value: Path("uploads/videos/demo.mp4")) + monkeypatch.setattr(main, "load_local_whisper_config", lambda: object()) + monkeypatch.setattr(main, "transcribe_video_to_vtt", lambda video_path, config: "WEBVTT\n\n1\n00:00:00.000 --> 00:00:01.000\nHello.\n") + + def fake_process_subtitles_with_ai(*args, **kwargs): + raise AssertionError("local whisper route should not call AI translation") + + def fake_upsert_video_subtitle(video_id, **kwargs): + calls.append({"video_id": video_id, **kwargs}) + + monkeypatch.setattr(main, "process_subtitles_with_ai", fake_process_subtitles_with_ai) + monkeypatch.setattr(main, "upsert_video_subtitle", fake_upsert_video_subtitle) + + result = main.api_generate_local_whisper_subtitles(7) + + assert result["report"]["local_whisper_generated"] is True + assert result["report"]["english_count"] == 1 + assert len(calls) == 1 + assert calls[0]["video_id"] == 7 + assert calls[0]["language_code"] == "en" + assert "subtitle_zh_content" not in calls[0] + + if __name__ == "__main__": patch = EnvPatch() original_read_env_file = ai_config.read_env_file @@ -60,6 +95,8 @@ if __name__ == "__main__": test_ai_status_route_reports_missing_key(patch) patch.restore() test_ai_test_route_rejects_missing_key(patch) + patch.restore() + test_local_whisper_route_generates_only_english_subtitle(patch) finally: patch.restore() ai_config.read_env_file = original_read_env_file diff --git a/tests/openai_asr_client_test.py b/tests/openai_asr_client_test.py deleted file mode 100644 index 3ea9e64..0000000 --- a/tests/openai_asr_client_test.py +++ /dev/null @@ -1,69 +0,0 @@ -import json -import sys -from pathlib import Path - -sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) - -from backend.ai_config import AsrConfig -from backend.openai_asr_client import OpenAIAsrClient - - -class FakeResponse: - def __enter__(self): - return self - - def __exit__(self, exc_type, exc, tb): - return False - - def read(self): - return json.dumps({ - "text": "hello world", - "segments": [ - {"start": 1.25, "end": 2.5, "text": "hello world"} - ], - }).encode("utf-8") - - -def test_openai_asr_client_posts_transcription_request(monkeypatch, tmp_path=None): - audio_path = Path("tests") / "tmp-first10.wav" - audio_path.write_bytes(b"fake wav") - captured = {} - - def fake_urlopen(request, timeout): - captured["url"] = request.full_url - captured["headers"] = dict(request.header_items()) - captured["body_prefix"] = request.data[:120] - return FakeResponse() - - try: - monkeypatch.setattr("backend.openai_asr_client.urllib.request.urlopen", fake_urlopen) - client = OpenAIAsrClient(AsrConfig( - provider="openai", - api_key="openai-key", - base_url="https://api.openai.com", - model="whisper-1", - timeout_seconds=120, - enabled=True, - )) - - result = client.transcribe(audio_path) - - assert captured["url"] == "https://api.openai.com/v1/audio/transcriptions" - assert "authorization" in {key.lower(): value for key, value in captured["headers"].items()} - assert b"whisper-1" in captured["body_prefix"] or b"model" in captured["body_prefix"] - assert result["segments"][0]["start"] == 1.25 - finally: - audio_path.unlink(missing_ok=True) - - -if __name__ == "__main__": - class MonkeyPatch: - def setattr(self, target, value): - parts = target.split(".") - module = __import__(".".join(parts[:2]), fromlist=[parts[1]]) - current = module - for part in parts[2:-1]: - current = getattr(current, part) - setattr(current, parts[-1], value) - - test_openai_asr_client_posts_transcription_request(MonkeyPatch()) diff --git a/tests/subtitle_ai_test.py b/tests/subtitle_ai_test.py index 4c9cdb9..a8293fb 100644 --- a/tests/subtitle_ai_test.py +++ b/tests/subtitle_ai_test.py @@ -33,16 +33,16 @@ My first job as an investor was when I was 24 years old, My first job as an investor was when I was 24 years old, """ - result = process_subtitles_with_ai(raw, FakeClient(), timestamp_offset_seconds=0.2) + result = process_subtitles_with_ai(raw, FakeClient()) assert "My first job as an investor" in result["subtitle_en_content"] assert "我第一次做投资人是在 24 岁。" in result["subtitle_zh_content"] assert result["report"]["duplicate_count"] == 1 assert result["report"]["translation_count"] == 1 - assert "00:00:01.072 --> 00:00:05.159" in result["subtitle_en_content"] - assert "00:00:01.072 --> 00:00:05.159" in result["subtitle_zh_content"] - assert result["report"]["timestamp_calibrated"] is True - assert result["report"]["timestamp_offset_seconds"] == 0.2 + assert "00:00:00.872 --> 00:00:04.959" in result["subtitle_en_content"] + assert "00:00:00.872 --> 00:00:04.959" in result["subtitle_zh_content"] + assert "timestamp_calibrated" not in result["report"] + assert "timestamp_offset_seconds" not in result["report"] class SingleBatchClient: @@ -86,6 +86,49 @@ Three. assert result["report"]["translation_batches"] == 1 +class MissingThenRepairClient: + def __init__(self): + self.calls = [] + + def chat_json(self, system_prompt, user_payload): + self.calls.append(user_payload) + indexes = [cue["index"] for cue in user_payload["cues"]] + if indexes == [1, 2, 3]: + return { + "translations": [ + {"index": 1, "zh": "第一句"}, + {"index": 3, "zh": "第三句"}, + ] + } + if indexes == [2]: + return {"translations": [{"index": 2, "zh": "第二句"}]} + raise AssertionError(f"unexpected retry indexes: {indexes}") + + +def test_process_subtitles_with_ai_repairs_missing_translation_indexes(): + raw = """WEBVTT + +00:00:00.000 --> 00:00:01.000 +One. + +00:00:01.000 --> 00:00:02.000 +Two. + +00:00:02.000 --> 00:00:03.000 +Three. +""" + + client = MissingThenRepairClient() + result = process_subtitles_with_ai(raw, client) + + assert [[cue["index"] for cue in call["cues"]] for call in client.calls] == [[1, 2, 3], [2]] + assert "第一句" in result["subtitle_zh_content"] + assert "第二句" in result["subtitle_zh_content"] + assert "第三句" in result["subtitle_zh_content"] + assert result["report"]["translation_count"] == 3 + + if __name__ == "__main__": test_process_subtitles_with_ai_returns_clean_en_and_zh_vtt() test_process_subtitles_with_ai_translates_all_cues_by_default_and_matches_index() + test_process_subtitles_with_ai_repairs_missing_translation_indexes() diff --git a/tests/subtitle_alignment_test.py b/tests/subtitle_alignment_test.py deleted file mode 100644 index ba4bf4e..0000000 --- a/tests/subtitle_alignment_test.py +++ /dev/null @@ -1,39 +0,0 @@ -import sys -from pathlib import Path - -sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) - -from backend.subtitle_alignment import align_first_sentence_with_asr -from backend.subtitle_tools import SubtitleCue - - -class FakeAsrClient: - def transcribe(self, audio_path): - return { - "text": "hello world", - "segments": [ - {"start": 1.5, "end": 3.0, "text": "hello world"} - ], - } - - -def test_align_first_sentence_with_asr_uses_first_segment_start(tmp_path=None): - video_path = Path("tests") / "tmp-video.mp4" - video_path.write_bytes(b"fake video") - try: - result = align_first_sentence_with_asr( - video_path, - SubtitleCue("00:00:00.500", "00:00:02.000", "Hello world"), - FakeAsrClient(), - extract_audio=lambda source, target: target.write_bytes(b"fake wav"), - ) - finally: - video_path.unlink(missing_ok=True) - - assert result.applied is True - assert result.first_sentence_start == 1.5 - assert result.offset_seconds == 1.0 - - -if __name__ == "__main__": - test_align_first_sentence_with_asr_uses_first_segment_start() diff --git a/tests/subtitle_tools_test.py b/tests/subtitle_tools_test.py index 32d1b31..25ade3d 100644 --- a/tests/subtitle_tools_test.py +++ b/tests/subtitle_tools_test.py @@ -3,7 +3,7 @@ from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) -from backend.subtitle_tools import build_vtt, clean_english_subtitle, shift_cues +from backend.subtitle_tools import build_vtt, clean_english_subtitle def test_clean_english_subtitle_removes_empty_and_duplicate_cues(): @@ -43,21 +43,6 @@ def test_build_vtt_outputs_numbered_blocks(): assert result == "WEBVTT\n\n1\n00:00:00.872 --> 00:00:04.959\nMy first job as an investor\n" -def test_shift_cues_moves_time_without_touching_text(): - shifted = shift_cues([ - { - "start": "00:00:00.200", - "end": "00:00:01.200", - "text": "First line", - } - ], -0.5) - - assert shifted[0].start == "00:00:00.000" - assert shifted[0].end == "00:00:00.700" - assert shifted[0].text == "First line" - - if __name__ == "__main__": test_clean_english_subtitle_removes_empty_and_duplicate_cues() test_build_vtt_outputs_numbered_blocks() - test_shift_cues_moves_time_without_touching_text()