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
@@ -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())
|
||||
+95
-1
@@ -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
|
||||
@@ -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")
|
||||
|
||||
|
||||
@@ -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()
|
||||
@@ -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())
|
||||
@@ -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()
|
||||
@@ -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()
|
||||
Reference in new issue
Block a user