feat: add local whisper subtitle generation
This commit is contained in:
1 parent
5228765473
commit
6a6fd347bd
17 files changed
+1041
-96
No files matched your search
+108
-14
@@ -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"}
|
||||
+133
-45
@@ -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()
|
||||
@@ -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"
|
||||
+86
-6
@@ -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")
|
||||
|
||||
@@ -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)
|
||||
+70
-19
@@ -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
|
||||
@@ -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:
|
||||
|
||||
Reference in new issue
Block a user