diff --git a/.env.example b/.env.example index ebc11db..24a46ff 100644 --- a/.env.example +++ b/.env.example @@ -1,4 +1,18 @@ -AI_API_KEY= -AI_BASE_URL=https://coding.simgreek.com/v1 -AI_TEXT_MODEL=qwen-plus -AI_AUDIO_MODEL=qwen-omni-turbo +TEXT_AI_API_KEY= +TEXT_AI_BASE_URL=https://api.deepseek.com +TEXT_AI_MODEL=deepseek-v4-pro +TEXT_AI_PROVIDER=deepseek +TEXT_AI_PROTOCOL=openai +TEXT_AI_BATCH_SIZE=0 +TEXT_AI_TIMEOUT_SECONDS=120 + +ASR_PROVIDER=openai +OPENAI_API_KEY= +OPENAI_BASE_URL=https://api.openai.com +OPENAI_ASR_MODEL=whisper-1 +ASR_TIMEOUT_SECONDS=120 + +LOCAL_WHISPER_ENABLED=true +LOCAL_WHISPER_MODEL=small +LOCAL_WHISPER_DEVICE=cpu +LOCAL_WHISPER_COMPUTE_TYPE=int8 diff --git a/admin.html b/admin.html index 2bd271d..486f43e 100644 --- a/admin.html +++ b/admin.html @@ -54,6 +54,7 @@
+
diff --git a/admin.js b/admin.js index d66c366..ff7d63c 100644 --- a/admin.js +++ b/admin.js @@ -22,6 +22,7 @@ const els = { aiReport: IS_BROWSER ? document.querySelector("#aiSubtitleReport") : null, testAiBtn: IS_BROWSER ? document.querySelector("#testAiBtn") : null, processAiSubtitlesBtn: IS_BROWSER ? document.querySelector("#processAiSubtitlesBtn") : null, + generateLocalWhisperSubtitlesBtn: IS_BROWSER ? document.querySelector("#generateLocalWhisperSubtitlesBtn") : null, subtitleShiftStatus: IS_BROWSER ? document.querySelector("#subtitleShiftStatus") : null, shiftSubtitleEarlierSmallBtn: IS_BROWSER ? document.querySelector("#shiftSubtitleEarlierSmallBtn") : null, shiftSubtitleLaterSmallBtn: IS_BROWSER ? document.querySelector("#shiftSubtitleLaterSmallBtn") : null, @@ -93,6 +94,7 @@ function initializeAdmin() { els.cancelEditBtn.addEventListener("click", resetFormMode); 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)); @@ -167,9 +169,13 @@ async function loadAiStatus() { if (els.processAiSubtitlesBtn) { els.processAiSubtitlesBtn.disabled = buttonState.disabled; } + if (els.generateLocalWhisperSubtitlesBtn) { + els.generateLocalWhisperSubtitlesBtn.disabled = buttonState.disabled; + } } catch (error) { els.aiStatus.textContent = error.message || "AI 状态读取失败。"; if (els.processAiSubtitlesBtn) els.processAiSubtitlesBtn.disabled = true; + if (els.generateLocalWhisperSubtitlesBtn) els.generateLocalWhisperSubtitlesBtn.disabled = true; } } @@ -204,6 +210,40 @@ async function testAiConnection() { } } +async function generateLocalWhisperSubtitles() { + if (!editingVideo) { + showMessage("请先选择一个素材。", true); + return; + } + + const button = els.generateLocalWhisperSubtitlesBtn; + if (!button) return; + button.disabled = true; + 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(",") + "。"; + } + await loadVideos(); + const updated = videos.find((video) => String(video.id) === String(editingVideo.id)); + if (updated) startEditingVideo(updated); + showMessage("本地字幕生成和翻译完成。"); + } catch (error) { + showMessage(error.message || "本地字幕生成失败。", true); + } finally { + button.textContent = "本地生成并翻译字幕"; + await loadAiStatus(); + } +} + async function processAiSubtitles() { if (!editingVideo) { showMessage("请先选择一个素材。", true); diff --git a/backend/ai_config.py b/backend/ai_config.py index bc84907..82f4e64 100644 --- a/backend/ai_config.py +++ b/backend/ai_config.py @@ -4,6 +4,8 @@ from dataclasses import dataclass import os from pathlib import Path +from .local_whisper import LocalWhisperConfig + PROJECT_DIR = Path(__file__).resolve().parent.parent ENV_PATH = PROJECT_DIR / ".env" @@ -15,6 +17,25 @@ class DeepSeekConfig: base_url: str model: str audio_model: str + provider: str + 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]: @@ -22,12 +43,12 @@ def read_env_file(path: Path = ENV_PATH) -> dict[str, str]: return {} values: dict[str, str] = {} - for raw_line in path.read_text(encoding="utf-8").splitlines(): + for raw_line in path.read_text(encoding="utf-8-sig").splitlines(): line = raw_line.strip() if not line or line.startswith("#") or "=" not in line: continue key, value = line.split("=", 1) - values[key.strip()] = value.strip().strip('"').strip("'") + values[key.strip().lstrip("\ufeff")] = value.strip().strip('"').strip("'") return values @@ -36,6 +57,56 @@ def get_config_value(key: str, default: str = "") -> str: return os.getenv(key, env_values.get(key, default)).strip() +def load_text_ai_config() -> DeepSeekConfig: + api_key = ( + get_config_value("TEXT_AI_API_KEY") + or get_config_value("AI_API_KEY") + or get_config_value("DEEPSEEK_API_KEY") + ) + base_url = ( + get_config_value("TEXT_AI_BASE_URL") + or get_config_value("AI_BASE_URL") + or get_config_value("DEEPSEEK_BASE_URL", "https://api.deepseek.com") + ) + model = ( + get_config_value("TEXT_AI_MODEL") + or get_config_value("AI_TEXT_MODEL") + or get_config_value("DEEPSEEK_MODEL", "deepseek-chat") + ) + return DeepSeekConfig( + api_key=api_key, + base_url=base_url.rstrip("/"), + model=model, + audio_model=get_config_value("TEXT_AI_AUDIO_MODEL") or get_config_value("AI_AUDIO_MODEL") or model, + provider=get_config_value("TEXT_AI_PROVIDER") or get_config_value("AI_PROVIDER", "deepseek") or "deepseek", + protocol=(get_config_value("TEXT_AI_PROTOCOL") or get_config_value("AI_API_PROTOCOL", "openai") or "openai").lower(), + translation_batch_size=parse_non_negative_int_config(get_config_value("TEXT_AI_BATCH_SIZE") or get_config_value("AI_TRANSLATION_BATCH_SIZE", "40"), 40), + timeout_seconds=parse_int_config(get_config_value("TEXT_AI_TIMEOUT_SECONDS") or get_config_value("AI_TIMEOUT_SECONDS", "120"), 120), + 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", + ) + + +def load_local_whisper_config() -> LocalWhisperConfig: + return LocalWhisperConfig( + enabled=parse_bool_config(get_config_value("LOCAL_WHISPER_ENABLED", "false")), + model=get_config_value("LOCAL_WHISPER_MODEL", "small") or "small", + device=get_config_value("LOCAL_WHISPER_DEVICE", "cpu") or "cpu", + compute_type=get_config_value("LOCAL_WHISPER_COMPUTE_TYPE", "int8") or "int8", + ) + + def load_deepseek_config() -> DeepSeekConfig: api_key = get_config_value("AI_API_KEY") or get_config_value("DEEPSEEK_API_KEY") base_url = get_config_value("AI_BASE_URL") or get_config_value("DEEPSEEK_BASE_URL", "https://api.deepseek.com") @@ -45,21 +116,44 @@ def load_deepseek_config() -> DeepSeekConfig: base_url=base_url.rstrip("/"), model=model, audio_model=get_config_value("AI_AUDIO_MODEL") or model, + provider=get_config_value("AI_PROVIDER", "deepseek") or "deepseek", + protocol=(get_config_value("AI_API_PROTOCOL", "openai") or "openai").lower(), + translation_batch_size=parse_int_config(get_config_value("AI_TRANSLATION_BATCH_SIZE", "5"), 5), + timeout_seconds=parse_int_config(get_config_value("AI_TIMEOUT_SECONDS", "180"), 180), + enable_audio_alignment=parse_bool_config(get_config_value("AI_ENABLE_AUDIO_ALIGNMENT", "false")), ) def get_ai_status() -> dict[str, object]: - config = load_deepseek_config() - if not config.api_key: - return { - "configured": False, - "provider": "deepseek", - "model": config.model, - "message": "未配置 AI_API_KEY,请在 .env 中填写。旧配置 DEEPSEEK_API_KEY 也兼容。", - } + text_config = load_text_ai_config() + asr_config = load_asr_config() return { - "configured": True, - "provider": "deepseek", - "model": config.model, - "message": "DeepSeek API 已配置。", + "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 中填写。", } + + +def parse_int_config(value: str, default: int) -> int: + try: + parsed = int(str(value).strip()) + except (TypeError, ValueError): + return default + return parsed if parsed > 0 else default + + +def parse_non_negative_int_config(value: str, default: int) -> int: + try: + parsed = int(str(value).strip()) + except (TypeError, ValueError): + return default + return parsed if parsed >= 0 else default + + +def parse_bool_config(value: str) -> bool: + return str(value or "").strip().lower() in {"1", "true", "yes", "on"} diff --git a/backend/deepseek_client.py b/backend/deepseek_client.py index 7aad98b..aa5b4dd 100644 --- a/backend/deepseek_client.py +++ b/backend/deepseek_client.py @@ -2,6 +2,7 @@ from __future__ import annotations import base64 import json +import re import urllib.error import urllib.request from pathlib import Path @@ -20,47 +21,34 @@ class DeepSeekClient: def chat_json(self, system_prompt: str, user_payload: dict[str, object]) -> dict[str, object]: if not self.config.api_key: - raise DeepSeekError("未配置 DEEPSEEK_API_KEY。") + raise DeepSeekError("未配置 AI_API_KEY。") + if self.config.protocol == "anthropic": + return self._anthropic_chat_json(system_prompt, user_payload) + return self._openai_chat_json(system_prompt, user_payload) - body = json.dumps({ + def audio_json(self, system_prompt: str, audio_path: Path, user_text: str) -> dict[str, object]: + if not self.config.api_key: + raise DeepSeekError("未配置 AI_API_KEY。") + if self.config.protocol == "anthropic": + return self._anthropic_audio_json(system_prompt, audio_path, user_text) + return self._openai_audio_json(system_prompt, audio_path, user_text) + + def _openai_chat_json(self, system_prompt: str, user_payload: dict[str, object]) -> dict[str, object]: + body = { "model": self.config.model, "messages": [ {"role": "system", "content": system_prompt}, {"role": "user", "content": json.dumps(user_payload, ensure_ascii=False)}, ], "response_format": {"type": "json_object"}, - }).encode("utf-8") - request = urllib.request.Request( - f"{self.config.base_url}/chat/completions", - data=body, - headers={ - "Authorization": f"Bearer {self.config.api_key}", - "Content-Type": "application/json", - }, - method="POST", - ) - - try: - with urllib.request.urlopen(request, timeout=self.timeout_seconds) as response: - payload = json.loads(response.read().decode("utf-8")) - except urllib.error.HTTPError as error: - detail = error.read().decode("utf-8", errors="replace") - raise DeepSeekError(f"DeepSeek 请求失败:{error.code} {detail}") from error - except Exception as error: - raise DeepSeekError(f"DeepSeek 请求失败:{error}") from error - + } + payload = self._post_json("/chat/completions", body, self._openai_headers(), "AI 请求失败") content = payload.get("choices", [{}])[0].get("message", {}).get("content", "") - try: - return json.loads(content) - except json.JSONDecodeError as error: - raise DeepSeekError("DeepSeek 返回内容不是有效 JSON。") from error - - def audio_json(self, system_prompt: str, audio_path: Path, user_text: str) -> dict[str, object]: - if not self.config.api_key: - raise DeepSeekError("未配置 AI_API_KEY。") + return self._parse_json_text(content, "AI 返回内容不是有效 JSON。") + def _openai_audio_json(self, system_prompt: str, audio_path: Path, user_text: str) -> dict[str, object]: audio_data = base64.b64encode(audio_path.read_bytes()).decode("ascii") - body = json.dumps({ + body = { "model": self.config.audio_model, "messages": [ {"role": "system", "content": system_prompt}, @@ -79,28 +67,128 @@ class DeepSeekClient: }, ], "response_format": {"type": "json_object"}, - }).encode("utf-8") + } + payload = self._post_json("/chat/completions", body, self._openai_headers(), "音频识别请求失败") + content = payload.get("choices", [{}])[0].get("message", {}).get("content", "") + return self._parse_json_text(content, "音频识别返回内容不是有效 JSON。") + + def _anthropic_chat_json(self, system_prompt: str, user_payload: dict[str, object]) -> dict[str, object]: + body = { + "model": self.config.model, + "max_tokens": 4096, + "system": system_prompt, + "messages": [ + { + "role": "user", + "content": [ + { + "type": "text", + "text": ( + "Return only one valid JSON object. Do not use markdown fences or extra text.\n" + f"{json.dumps(user_payload, ensure_ascii=False)}" + ), + } + ], + } + ], + } + payload = self._post_json("/v1/messages", body, self._anthropic_headers(), "Anthropic 请求失败") + return self._parse_json_text(self._extract_anthropic_text(payload), "Anthropic 返回内容不是有效 JSON。") + + def _anthropic_audio_json(self, system_prompt: str, audio_path: Path, user_text: str) -> dict[str, object]: + audio_data = base64.b64encode(audio_path.read_bytes()).decode("ascii") + body = { + "model": self.config.audio_model, + "max_tokens": 1024, + "system": system_prompt, + "messages": [ + { + "role": "user", + "content": [ + {"type": "text", "text": user_text}, + { + "type": "input_audio", + "source": { + "type": "base64", + "media_type": "audio/wav", + "data": audio_data, + }, + }, + ], + } + ], + } + payload = self._post_json("/v1/messages", body, self._anthropic_headers(), "Anthropic 音频识别请求失败") + return self._parse_json_text(self._extract_anthropic_text(payload), "Anthropic 音频识别返回内容不是有效 JSON。") + + def _post_json( + self, + path: str, + body: dict[str, object], + headers: dict[str, str], + error_prefix: str, + ) -> dict[str, object]: request = urllib.request.Request( - f"{self.config.base_url}/chat/completions", - data=body, - headers={ - "Authorization": f"Bearer {self.config.api_key}", - "Content-Type": "application/json", - }, + f"{self.config.base_url}{path}", + data=json.dumps(body).encode("utf-8"), + headers=headers, method="POST", ) - try: with urllib.request.urlopen(request, timeout=self.timeout_seconds) as response: - payload = json.loads(response.read().decode("utf-8")) + 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"Qwen 音频识别请求失败:{error.code} {detail}") from error + raise DeepSeekError(f"{error_prefix}:{error.code} {detail}") from error except Exception as error: - raise DeepSeekError(f"Qwen 音频识别请求失败:{error}") from error + raise DeepSeekError(f"{error_prefix}:{error}") from error - content = payload.get("choices", [{}])[0].get("message", {}).get("content", "") + def _openai_headers(self) -> dict[str, str]: + return { + "Authorization": f"Bearer {self.config.api_key}", + "Content-Type": "application/json", + } + + def _anthropic_headers(self) -> dict[str, str]: + return { + "x-api-key": self.config.api_key, + "anthropic-version": "2023-06-01", + "Content-Type": "application/json", + } + + def _extract_anthropic_text(self, payload: dict[str, object]) -> str: + blocks = payload.get("content", []) + if not isinstance(blocks, list): + return "" + texts = [ + str(block.get("text", "")) + for block in blocks + if isinstance(block, dict) and block.get("type") == "text" + ] + return "\n".join(texts).strip() + + def _parse_json_text(self, content: str, error_message: str) -> dict[str, object]: + json_text = self._extract_json_text(content) try: - return json.loads(content) + return json.loads(json_text) except json.JSONDecodeError as error: - raise DeepSeekError("Qwen 音频识别返回内容不是有效 JSON。") from error + raise DeepSeekError(error_message) from error + + def _extract_json_text(self, content: str) -> str: + text = str(content or "").strip() + if not text: + return text + + fenced = re.search(r"```(?:json)?\s*(\{.*?\})\s*```", text, re.IGNORECASE | re.DOTALL) + if fenced: + return fenced.group(1).strip() + + start = text.find("{") + if start < 0: + return text + decoder = json.JSONDecoder() + try: + _, end = decoder.raw_decode(text[start:]) + except json.JSONDecodeError: + return text + return text[start:start + end].strip() diff --git a/backend/local_whisper.py b/backend/local_whisper.py new file mode 100644 index 0000000..4443799 --- /dev/null +++ b/backend/local_whisper.py @@ -0,0 +1,101 @@ +from __future__ import annotations + +from dataclasses import dataclass +from pathlib import Path +import importlib +import subprocess +import tempfile + +from .subtitle_tools import format_timestamp + + +class LocalWhisperError(RuntimeError): + pass + + +@dataclass(frozen=True) +class LocalWhisperConfig: + enabled: bool + model: str + device: str + compute_type: str + + +def transcribe_video_to_vtt(video_path: Path, config: LocalWhisperConfig) -> str: + if not config.enabled: + raise LocalWhisperError("本地 Whisper 未启用。") + if not video_path.exists(): + raise LocalWhisperError("视频文件不存在,无法生成字幕。") + + with tempfile.TemporaryDirectory() as temp_dir: + audio_path = Path(temp_dir) / "whisper-audio.wav" + extract_audio_for_whisper(video_path, audio_path) + segments = transcribe_audio(audio_path, config) + return build_vtt_from_segments(segments) + + +def extract_audio_for_whisper(video_path: Path, audio_path: Path) -> None: + command = [ + "ffmpeg", + "-y", + "-i", + str(video_path), + "-vn", + "-ac", + "1", + "-ar", + "16000", + str(audio_path), + ] + try: + subprocess.run(command, check=True, capture_output=True) + except FileNotFoundError as error: + raise LocalWhisperError("未找到 ffmpeg,请先安装 ffmpeg。") from error + except subprocess.CalledProcessError as error: + detail = error.stderr.decode("utf-8", errors="replace") + raise LocalWhisperError(f"ffmpeg 提取音频失败:{detail}") from error + + +def transcribe_audio(audio_path: Path, config: LocalWhisperConfig) -> list[dict[str, object]]: + faster_whisper = import_optional("faster_whisper") + if faster_whisper is None: + raise LocalWhisperError("未安装 faster-whisper,请先安装后再生成本地字幕。") + + model = faster_whisper.WhisperModel( + config.model, + device=config.device, + compute_type=config.compute_type, + ) + segments, _info = model.transcribe( + str(audio_path), + language="en", + vad_filter=True, + ) + return [ + { + "start": float(segment.start), + "end": float(segment.end), + "text": str(segment.text).strip(), + } + for segment in segments + if str(segment.text).strip() + ] + + +def import_optional(module_name: str): + try: + return importlib.import_module(module_name) + except ImportError: + return None + + +def build_vtt_from_segments(segments: list[dict[str, object]]) -> str: + blocks: list[str] = [] + for index, segment in enumerate(segments, 1): + text = str(segment.get("text", "")).strip() + if not text: + continue + start = float(segment.get("start", 0) or 0) + end = float(segment.get("end", start) or start) + blocks.append(f"{index}\n{format_timestamp(start)} --> {format_timestamp(end)}\n{text}") + return "WEBVTT\n\n" + "\n\n".join(blocks).strip() + "\n" diff --git a/backend/main.py b/backend/main.py index ddc87e9..c83e5ce 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_deepseek_config +from .ai_config import get_ai_status, load_asr_config, load_local_whisper_config, load_text_ai_config from .db import ( DATABASE_PATH, create_video, @@ -20,7 +20,9 @@ from .db import ( upsert_video_subtitle, ) from .deepseek_client import DeepSeekClient, DeepSeekError -from .subtitle_alignment import align_first_sentence +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 @@ -386,22 +388,31 @@ def api_process_video_subtitles(video_id: int) -> dict[str, object]: raise HTTPException(status_code=400, detail="请先上传英文字幕。") try: - client = DeepSeekClient(load_deepseek_config()) + 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 video_path and cleaned_for_alignment.cues: - alignment = align_first_sentence(video_path, cleaned_for_alignment.cues[0], client) + 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 = "当前视频不是本地上传文件,已跳过自动首句校准。" + 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: @@ -435,6 +446,75 @@ def api_process_video_subtitles(video_id: int) -> dict[str, object]: } + + +def save_processed_subtitles(video_id: int, subtitles: dict[str, object], result: dict[str, object]) -> None: + english_subtitle = subtitles.get("en", {}) + english_file_path = "" + if isinstance(english_subtitle, dict): + english_file_path = str(english_subtitle.get("filePath") or "") + upsert_video_subtitle( + video_id, + language_code="en", + language_name="English", + format="vtt", + file_path=english_file_path, + content=str(result["subtitle_en_content"]), + ) + + chinese_subtitle = subtitles.get("zh", {}) + chinese_file_path = "" + if isinstance(chinese_subtitle, dict): + chinese_file_path = str(chinese_subtitle.get("filePath") or "") + upsert_video_subtitle( + video_id, + language_code="zh", + language_name="中文", + format="vtt", + file_path=chinese_file_path, + content=str(result["subtitle_zh_content"]), + ) + + +@app.post("/api/videos/{video_id}/local-whisper/subtitles") +def api_generate_local_whisper_subtitles(video_id: int) -> 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="视频不存在") + + video_path = upload_url_to_path(str(video.get("videoUrl") or "")) + 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: + raise HTTPException(status_code=400, detail=str(error)) from error + + save_processed_subtitles(video_id, subtitles, result) + return { + "video": get_video(video_id), + "report": result["report"], + } + @app.get("/") def read_index() -> FileResponse: return FileResponse(PROJECT_DIR / "index.html") diff --git a/backend/openai_asr_client.py b/backend/openai_asr_client.py new file mode 100644 index 0000000..a221fb9 --- /dev/null +++ b/backend/openai_asr_client.py @@ -0,0 +1,66 @@ +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 aa6264f..6e2dc52 100644 --- a/backend/subtitle_ai.py +++ b/backend/subtitle_ai.py @@ -1,45 +1,42 @@ from __future__ import annotations -from .subtitle_tools import build_vtt, clean_english_subtitle, shift_cues +from .subtitle_tools import SubtitleCue, build_vtt, clean_english_subtitle, shift_cues TRANSLATION_SYSTEM_PROMPT = """ -你是英语学习产品的字幕翻译助手。输入是按顺序排列的英文字幕。 +你是英语学习产品的字幕处理助手。输入是按顺序排列的英文字幕。 请只返回 JSON,格式为 {"translations":[{"index":1,"zh":"中文翻译"}]}。 要求: 1. 只翻译英文文本,不要改写原文含义。 2. 不要修改时间轴,不要生成任何 start/end/time 字段。 -3. 不要增删字幕条数,每个 index 必须返回一条中文。 -4. 中文自然,适合英语学习;不要解释。 +3. 不要增删字幕条数,每个输入 index 必须返回且只返回一条中文。 +4. translations 可以乱序,但 index 必须和输入完全一致。 +5. 中文自然,适合英语学习;不要解释。 """.strip() -def process_subtitles_with_ai(english_content: str, client, timestamp_offset_seconds: float = 0.0) -> dict[str, object]: +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 - payload = { - "cues": [ - {"index": index, "text": cue.text} - for index, cue in enumerate(english_cues, 1) - ] - } - response = client.chat_json(TRANSLATION_SYSTEM_PROMPT, payload) - translations = response.get("translations") - if not isinstance(translations, list): - raise ValueError("AI 返回结果缺少 translations。") - if len(translations) != len(english_cues): - raise ValueError("AI 返回的翻译条数和英文字幕条数不一致。") + translations = translate_cues(english_cues, client, batch_size) zh_cues = [] - for cue, translation in zip(english_cues, translations): + for index, cue in enumerate(english_cues, 1): + translation = translations[index] zh_text = str(translation.get("zh", "")).strip() if not zh_text: - raise ValueError("AI 返回了空翻译。") + raise ValueError(f"AI 返回了空翻译:index {index}") zh_cues.append({"start": cue.start, "end": cue.end, "text": zh_text}) + translation_batches = count_batches(len(english_cues), batch_size) return { "subtitle_en_content": build_vtt(english_cues), "subtitle_zh_content": build_vtt(zh_cues), @@ -49,8 +46,62 @@ def process_subtitles_with_ai(english_content: str, client, timestamp_offset_sec "duplicate_count": cleaned.duplicate_count, "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 不逐句修改时间轴。", }, } + + +def translate_cues( + cues: list[SubtitleCue], + client, + batch_size: int, +) -> dict[int, dict[str, object]]: + translations: dict[int, dict[str, object]] = {} + indexed_cues = list(enumerate(cues, 1)) + effective_batch_size = int(batch_size or 0) + batches = ( + [indexed_cues] + if effective_batch_size <= 0 or effective_batch_size >= len(indexed_cues) + else [indexed_cues[start:start + effective_batch_size] for start in range(0, len(indexed_cues), effective_batch_size)] + ) + + for batch in batches: + 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 + + missing = sorted(expected_indexes - translations.keys()) + if missing: + raise ValueError(f"AI 返回的翻译条数和英文字幕条数不一致,缺少 index:{missing[:10]}") + + return translations + + +def count_batches(cue_count: int, batch_size: int) -> int: + effective_batch_size = int(batch_size or 0) + if cue_count <= 0: + return 0 + if effective_batch_size <= 0 or effective_batch_size >= cue_count: + return 1 + return (cue_count + effective_batch_size - 1) // effective_batch_size diff --git a/backend/subtitle_alignment.py b/backend/subtitle_alignment.py index acdec32..2172f60 100644 --- a/backend/subtitle_alignment.py +++ b/backend/subtitle_alignment.py @@ -4,6 +4,7 @@ from dataclasses import dataclass from pathlib import Path import subprocess import tempfile +from typing import Callable from .subtitle_tools import SubtitleCue, parse_timestamp @@ -41,16 +42,59 @@ def align_first_sentence(video_path: Path, first_cue: SubtitleCue, client) -> Al except Exception as error: return AlignmentResult(False, 0.0, None, 0.0, f"首句自动校准失败,已跳过:{error}") - first_sentence_start = parse_alignment_second(response.get("first_sentence_start")) - confidence = parse_alignment_second(response.get("confidence")) + 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, "AI 没有返回有效的首句开始时间,已跳过自动校准。") + 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"首句自动校准成功,整体平移 {offset:.2f} 秒。") + 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: diff --git a/tests/ai_client_test.py b/tests/ai_client_test.py new file mode 100644 index 0000000..d92ce0c --- /dev/null +++ b/tests/ai_client_test.py @@ -0,0 +1,95 @@ +import json +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) + +from backend.ai_config import DeepSeekConfig +from backend.deepseek_client import DeepSeekClient + + +class FakeResponse: + def __init__(self, payload): + self.payload = payload + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc, tb): + return False + + def read(self): + return json.dumps(self.payload).encode("utf-8") + + +def make_config() -> DeepSeekConfig: + return DeepSeekConfig( + api_key="test-key", + base_url="https://coding.simgreek.com", + model="qwen-plus", + audio_model="qwen-plus", + provider="qwen", + protocol="anthropic", + translation_batch_size=20, + timeout_seconds=180, + enable_audio_alignment=False, + ) + + +def test_anthropic_chat_json_posts_messages_request(monkeypatch): + captured = {} + + def fake_urlopen(request, timeout): + captured["url"] = request.full_url + captured["headers"] = dict(request.header_items()) + captured["body"] = json.loads(request.data.decode("utf-8")) + return FakeResponse({ + "content": [ + {"type": "text", "text": '{"translations":[{"index":1,"zh":"你好"}]}'} + ] + }) + + monkeypatch.setattr("backend.deepseek_client.urllib.request.urlopen", fake_urlopen) + client = DeepSeekClient(make_config()) + + result = client.chat_json("Return JSON only.", {"cues": [{"index": 1, "text": "Hello"}]}) + + assert captured["url"] == "https://coding.simgreek.com/v1/messages" + assert captured["body"]["model"] == "qwen-plus" + assert captured["body"]["system"] == "Return JSON only." + assert captured["body"]["messages"][0]["role"] == "user" + assert "x-api-key" in {key.lower(): value for key, value in captured["headers"].items()} + assert result["translations"][0]["zh"] == "你好" + + +def test_chat_json_accepts_markdown_wrapped_json(monkeypatch): + def fake_urlopen(request, timeout): + return FakeResponse({ + "content": [ + { + "type": "text", + "text": 'Here is the result:\n```json\n{"translations":[{"index":1,"zh":"你好"}]}\n```', + } + ] + }) + + monkeypatch.setattr("backend.deepseek_client.urllib.request.urlopen", fake_urlopen) + client = DeepSeekClient(make_config()) + + result = client.chat_json("Return JSON only.", {"cues": [{"index": 1, "text": "Hello"}]}) + + assert result["translations"][0]["zh"] == "你好" + + +if __name__ == "__main__": + class MonkeyPatch: + def setattr(self, target, value): + parts = target.split(".") + module = __import__(".".join(parts[:2]), fromlist=[parts[1]]) + current = module + for part in parts[2:-1]: + current = getattr(current, part) + setattr(current, parts[-1], value) + + test_anthropic_chat_json_posts_messages_request(MonkeyPatch()) + test_chat_json_accepts_markdown_wrapped_json(MonkeyPatch()) diff --git a/tests/ai_config_test.py b/tests/ai_config_test.py index 629d5d7..5bde563 100644 --- a/tests/ai_config_test.py +++ b/tests/ai_config_test.py @@ -4,7 +4,13 @@ from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) from backend import ai_config -from backend.ai_config import get_ai_status, load_deepseek_config +from backend.ai_config import ( + get_ai_status, + load_asr_config, + load_deepseek_config, + load_local_whisper_config, + load_text_ai_config, +) def test_ai_status_reports_missing_key(monkeypatch): @@ -33,6 +39,10 @@ def test_load_deepseek_config_accepts_generic_ai_names(monkeypatch): monkeypatch.setenv("AI_BASE_URL", "https://coding.simgreek.com/v1") monkeypatch.setenv("AI_TEXT_MODEL", "qwen-plus") monkeypatch.setenv("AI_AUDIO_MODEL", "qwen-omni-turbo") + monkeypatch.setenv("AI_API_PROTOCOL", "anthropic") + monkeypatch.setenv("AI_TRANSLATION_BATCH_SIZE", "15") + monkeypatch.setenv("AI_TIMEOUT_SECONDS", "180") + monkeypatch.setenv("AI_ENABLE_AUDIO_ALIGNMENT", "true") config = load_deepseek_config() @@ -40,6 +50,81 @@ def test_load_deepseek_config_accepts_generic_ai_names(monkeypatch): assert config.base_url == "https://coding.simgreek.com/v1" assert config.model == "qwen-plus" assert config.audio_model == "qwen-omni-turbo" + assert config.protocol == "anthropic" + assert config.translation_batch_size == 15 + assert config.timeout_seconds == 180 + assert config.enable_audio_alignment is True + + +def test_load_split_text_and_asr_configs(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): + monkeypatch.setenv("TEXT_AI_API_KEY", "text-key") + monkeypatch.setenv("TEXT_AI_BATCH_SIZE", "0") + + config = load_text_ai_config() + + assert config.translation_batch_size == 0 + + +def test_load_local_whisper_config(monkeypatch): + monkeypatch.setenv("LOCAL_WHISPER_ENABLED", "true") + monkeypatch.setenv("LOCAL_WHISPER_MODEL", "small") + monkeypatch.setenv("LOCAL_WHISPER_DEVICE", "cpu") + monkeypatch.setenv("LOCAL_WHISPER_COMPUTE_TYPE", "int8") + + config = load_local_whisper_config() + + assert config.enabled is True + assert config.model == "small" + assert config.device == "cpu" + assert config.compute_type == "int8" + + +def test_ai_status_uses_configured_provider_name(monkeypatch): + monkeypatch.setenv("AI_API_KEY", "generic-key") + monkeypatch.setenv("AI_PROVIDER", "qwen") + monkeypatch.setenv("AI_TEXT_MODEL", "qwen-plus") + + status = get_ai_status() + + assert status["configured"] is True + assert status["provider"] == "qwen" + assert status["model"] == "qwen-plus" + assert "AI API" in status["message"] + + +def test_read_env_file_accepts_utf8_bom(): + import tempfile + + with tempfile.TemporaryDirectory() as temp_dir: + env_path = Path(temp_dir) / ".env" + env_path.write_bytes(b"\xef\xbb\xbfAI_API_KEY=test-key\nAI_API_PROTOCOL=anthropic\n") + + values = ai_config.read_env_file(env_path) + + assert values["AI_API_KEY"] == "test-key" + assert values["AI_API_PROTOCOL"] == "anthropic" class EnvPatch: @@ -72,6 +157,7 @@ class EnvPatch: if __name__ == "__main__": + test_read_env_file_accepts_utf8_bom() patch = EnvPatch() original_read_env_file = ai_config.read_env_file ai_config.read_env_file = lambda path=ai_config.ENV_PATH: {} @@ -81,6 +167,14 @@ if __name__ == "__main__": test_load_deepseek_config_uses_defaults(patch) patch.restore() test_load_deepseek_config_accepts_generic_ai_names(patch) + patch.restore() + test_load_split_text_and_asr_configs(patch) + patch.restore() + test_text_ai_batch_size_allows_zero(patch) + patch.restore() + test_load_local_whisper_config(patch) + patch.restore() + test_ai_status_uses_configured_provider_name(patch) finally: patch.restore() ai_config.read_env_file = original_read_env_file diff --git a/tests/ai_routes_test.py b/tests/ai_routes_test.py index a14c6eb..36f6a6d 100644 --- a/tests/ai_routes_test.py +++ b/tests/ai_routes_test.py @@ -37,7 +37,7 @@ def test_ai_status_route_reports_missing_key(monkeypatch): status = main.api_ai_status() assert status["configured"] is False - assert "DEEPSEEK_API_KEY" in status["message"] + assert "TEXT_AI_API_KEY" in status["message"] def test_ai_test_route_rejects_missing_key(monkeypatch): @@ -47,7 +47,7 @@ def test_ai_test_route_rejects_missing_key(monkeypatch): main.api_ai_test() except HTTPException as error: assert error.status_code == 400 - assert "DEEPSEEK_API_KEY" in error.detail + assert "TEXT_AI_API_KEY" in error.detail else: raise AssertionError("api_ai_test should reject missing DeepSeek API key") diff --git a/tests/local_whisper_test.py b/tests/local_whisper_test.py new file mode 100644 index 0000000..cbaddc2 --- /dev/null +++ b/tests/local_whisper_test.py @@ -0,0 +1,28 @@ +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) + +from backend.local_whisper import build_vtt_from_segments + + +def test_build_vtt_from_whisper_segments(): + segments = [ + {"start": 0.0, "end": 2.5, "text": "Hello world."}, + {"start": 2.5, "end": 5.0, "text": "This is a test."}, + ] + + assert build_vtt_from_segments(segments) == """WEBVTT + +1 +00:00:00.000 --> 00:00:02.500 +Hello world. + +2 +00:00:02.500 --> 00:00:05.000 +This is a test. +""" + + +if __name__ == "__main__": + test_build_vtt_from_whisper_segments() diff --git a/tests/openai_asr_client_test.py b/tests/openai_asr_client_test.py new file mode 100644 index 0000000..3ea9e64 --- /dev/null +++ b/tests/openai_asr_client_test.py @@ -0,0 +1,69 @@ +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 6bc8486..4c9cdb9 100644 --- a/tests/subtitle_ai_test.py +++ b/tests/subtitle_ai_test.py @@ -41,10 +41,51 @@ My first job as an investor was when I was 24 years old, 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 "timestamp_calibrated" in result["report"] assert result["report"]["timestamp_calibrated"] is True assert result["report"]["timestamp_offset_seconds"] == 0.2 +class SingleBatchClient: + def __init__(self): + self.calls = [] + + def chat_json(self, system_prompt, user_payload): + self.calls.append(user_payload) + return { + "translations": [ + {"index": 3, "zh": "第三句"}, + {"index": 1, "zh": "第一句"}, + {"index": 2, "zh": "第二句"}, + ] + } + + +def test_process_subtitles_with_ai_translates_all_cues_by_default_and_matches_index(): + raw = """WEBVTT + +00:00:00.000 --> 00:00:01.000 +One. + +00:00:01.000 --> 00:00:02.000 +Two. + +00:00:02.000 --> 00:00:03.000 +Three. +""" + + client = SingleBatchClient() + result = process_subtitles_with_ai(raw, client) + + assert len(client.calls) == 1 + assert [cue["index"] for cue in client.calls[0]["cues"]] == [1, 2, 3] + assert "第一句" in result["subtitle_zh_content"] + assert "第二句" in result["subtitle_zh_content"] + assert "第三句" in result["subtitle_zh_content"] + assert result["subtitle_zh_content"].index("第一句") < result["subtitle_zh_content"].index("第二句") + assert result["subtitle_zh_content"].index("第二句") < result["subtitle_zh_content"].index("第三句") + assert result["report"]["translation_batches"] == 1 + + 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() diff --git a/tests/subtitle_alignment_test.py b/tests/subtitle_alignment_test.py new file mode 100644 index 0000000..ba4bf4e --- /dev/null +++ b/tests/subtitle_alignment_test.py @@ -0,0 +1,39 @@ +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()