Files
xiaoxia-saas/apps/api/app/services/script_asr_service.py
T
xiaoxia-agent 8998e5f910 feat(#1893): 新增文案库 AI 能力 3 个 API 路由及 ASR 服务封装
- POST /api/v1/scripts/extract-from-douyin: 抖音视频文案提取(yt-dlp+ASR)
- POST /api/v1/scripts/ai-rewrite: AI 文案改写(豆包 LLM)
- POST /api/v1/scripts/ai-generate-titles: AI 标题生成(复用 generate_smart_titles)
- 新增 script_asr_service 封装 ASR 转写(未配置时返回 503)
- 32 个单元测试全部通过
2026-09-15 13:07:12 +08:00

60 lines
1.8 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""文案提取 ASR 服务封装 — Issue #1893.
将已有的 ASR 服务工厂封装为面向文案提取场景的简单接口:
- transcribe_to_text(video_path) -> str:将视频/音频转写为纯文本
- 未配置 ASR 时抛 ASRNotConfiguredError(路由层映射为 503)
- ASR 调用失败时抛 ASRTranscriptionError(路由层映射为 502)
"""
from __future__ import annotations
import logging
from pathlib import Path
from packages.ports.asr_service import ASRServiceError
logger = logging.getLogger(__name__)
class ASRNotConfiguredError(Exception):
"""ASR 服务未配置."""
class ASRTranscriptionError(Exception):
"""ASR 转写失败."""
def transcribe_to_text(media_path: str | Path) -> str:
"""将视频/音频文件转写为纯文本.
Args:
media_path: 媒体文件路径
Returns:
转写出的文本
Raises:
ASRNotConfiguredError: ASR 服务未配置
ASRTranscriptionError: ASR 调用失败
"""
# 延迟导入,避免循环依赖和启动时副作用
from apps.worker.services.asr_service_factory import get_asr_service
asr = get_asr_service()
if asr is None:
raise ASRNotConfiguredError("ASR 服务未配置,请联系管理员配置火山 MediaKit 或阿里云 ASR 密钥")
try:
timeline = asr.transcribe(Path(media_path))
# 拼接所有分段的文本
text = "".join(seg.text for seg in timeline.segments)
return text.strip()
except ASRNotConfiguredError:
raise
except ASRServiceError as exc:
logger.error("ASR 转写失败: %s", exc)
raise ASRTranscriptionError(f"语音识别失败: {exc}") from exc
except Exception as exc:
logger.error("ASR 转写异常: %s", exc)
raise ASRTranscriptionError(f"语音识别失败: {exc}") from exc