openlrc

zh-plusMIT活跃维护

用 Whisper 把音频转成文字,再调用 GPT、Claude 等大模型翻译润色,直接输出 LRC 字幕文件,省去手动打轴和翻译的麻烦。

Transcribe and translate voice into LRC file using Whisper and LLMs (GPT, Claude, et,al). 使用whisper和LLM(GPT,Claude等)来转录、翻译你的音频为字幕文件。

1.7.0a2发布于 2026-08-10 09:21 UTC685star54fork同步于 2026-11-07 07:30 UTC

怎么上手

由 README 提炼,执行前请确认
pip install openlrc
硬件要求按 README 说明

README 未给出具体显存要求;转录依赖 faster-whisper,需按 CTranslate2 文档安装 CUDA、cuDNN 和 cuBLAS,Windows 用户可从 Purfview 仓库下载所需 NVIDIA 库并加入 PATH。

需要 CUDA
下载:源码 zip·GitHub Releases(安装包)本站不镜像安装包

项目说明

由 README 自动翻译提炼

用 faster-whisper 转录音频、再用 LLM 翻译润色成 LRC 字幕的 Python 库

用 Whisper 把音频转成文字,再调用 GPT、Claude 等大模型翻译润色,直接输出 LRC 字幕文件,省去手动打轴和翻译的麻烦。

核心能力

  • 用 faster-whisper 做语音转录并输出 LRC/SRT 字幕
  • 按上下文分批翻译,支持术语表提升译文质量
  • 支持 OpenAI、Anthropic、Google、OpenRouter 及本地模型
  • 转录串行、多文件翻译并发执行
  • 可选用 DPDFNet 做噪声抑制与响度归一化预处理

容易踩的坑

需先自行安装 ffmpeg 并把 bin 目录加入 PATH;噪声抑制需装 openlrc[full],首次使用会下载约 10MB 的 DPDFNet 模型到 ~/.cache/dpdfnet/models;翻译需提前设置 OPENAI_API_KEY、ANTHROPIC_API_KEY、GOOGLE_API_KEY 或 OPENROUTER_API_KEY 等环境变量。

内容由模型根据 README 生成,可能不完整或不准确,以官方文档为准。看原文 README

最近发版

5 个版本1.7.0a2
  1. 1.7.0a2v1.7.0a2最新正式版2026-08-10 · 2026-08-10 09:21 UTC

    Improve noise-suppression portability, extend Python compatibility, and strengthen the test and CI workflow.

    New Features:

    • Replace the PyTorch-based DeepFilterNet noise-suppression backend with the ONNX-based DPDFNet implementation in the optional full extra.
    • Raise the minimum Python version to 3.11, add Python 3.13 and 3.14 support, and refresh dependency constraints for the expanded range.

    Other Changes:

    • Migrate the test runner to pytest and make the suite independent of the current working directory.
    • Resolve Pyright errors, make the prompt base class generic, and enforce Pyright and Ruff checks in CI.
    • Pin spaCy away from its broken 3.8.14 release and tighten the Numba constraint for clean installations.
    • Run live LLM integration tests exclusively against the OpenAI-compatible deepseek-v4-flash model using DEEPSEEK_API_KEY locally and in GitHub Actions.
  2. 1.7.0v1.7.0a12026-05-25 · 2026-05-25 03:37 UTC
    查看更新说明

    Add a token-efficient lean translation pipeline, broaden model-provider routing, and refresh the configuration surface for mixed-model workflows.

    New Features:

    • Add LeanTranslator with compact anchored prompts, sliding context, checkpoint resume, retry handling, binary-split recovery, and atomic fallback for missing lines.
    • Add lean mode integration to LRCer through TranslationConfig(translate_mode="lean"), including optional Context Review and separate CR/translation chatbots.
    • Add LiteLLM support as an optional provider gateway via openlrc[litellm] and litellm:<provider/model> routing.
    • Add ModelConfig.extra_body passthrough for provider-specific request parameters across OpenAI-compatible, Anthropic, Gemini, and LiteLLM backends.

    Other Changes:

    • Replace legacy string-based translation config fields with ModelConfig objects for primary, retry, and Context Review chatbots.
    • Decouple model capability limits from the static model registry; max_tokens and context_window are now opt-in runtime caps.
    • Improve custom-provider and provider-prefix inference for OpenAI-compatible, Anthropic, Gemini, LiteLLM, and third-party model names.
    • Restrict lingua language detection to the supported language set and add anchor-based validation for lean translation output.
    • Split media helpers from utils into media_utils to keep heavyweight media dependencies isolated.
    • Centralize live API test configuration, add LeanTranslator and LiteLLM regression coverage, and update CI to exercise the new optional litellm extra.
    • Refresh README examples for lean mode, mixed-model translation, live test configuration, and the current local-LLM/provider support status.
  3. 1.6.3v1.6.32026-05-06 · 2026-05-06 10:18 UTC
    查看更新说明

    Improve translation reliability, reduce heavy import overhead, and tighten release tooling around the uv workflow.

    New Features:

    • Add token-aware, scene-sensitive chunk splitting for long subtitle translation.
    • Add chunked guideline generation for long subtitle files.

    Other Changes:

    • Fully defer heavyweight package-root imports and move torch/deepfilternet behind the optional full extra.
    • Harden ChatBot and GeminiBot lifecycle handling, retry behavior, and error recovery.
    • Reduce translation log noise and add OPENLRC_LOG_LEVEL.
    • Improve line-mismatch retry behavior and raise the default context window to 32K.
    • Replace runtime assert checks with explicit exceptions.
    • Fix empty-translation early return, continuous-script duplicate word handling, and lazy import test stdout parsing.
    • Gate long stress tests behind OPENLRC_TEST_STRESS and expand chunking/translation coverage.
  4. 1.6.2v1.6.22026-03-11 · 2026-03-11 01:54 UTC
    查看更新说明

    Refine the transcription and translation pipeline, expand test coverage, and improve the release workflow around uv.

    New Features:

    • Add TranscriptionConfig and TranslationConfig dataclasses for clearer runtime configuration.
    • Decouple transcription and translation in LRCer.
    • Add OpenRouter fallback model support.

    Other Changes:

    • Add skip_preprocess support.
    • Fix retry_model validation.
    • Improve duplicate handling and video format inference in the decoupled flow.
    • Refresh README examples to the new config API.
    • Add mock and live regression coverage for translator and LRCer behavior.
    • Add Ruff and Pyright checks and update CI environment variables for live API tests.
  5. 1.6.1v1.6.12025-04-30 · 2025-04-30 06:57 UTC
    查看更新说明

    Hot fix for missed mp3 files issue. Replace poetry with uv package manager. Fix #69.

    Other Changes:

    • Hot fix for missed mp3 files issue.
    • Allow un-recorded (not in models.py) model name.

用户点评

登录用户的真实使用记录,可按版本和硬件筛选
共 0 条

    还没有人点评。第一个说出真实体验的人最有价值。

    README 原文

    未翻译

    Open-Lyrics

    PyPI PyPI - License Downloads GitHub Workflow Status (with event)

    Open-Lyrics is a Python library that transcribes audio with faster-whisper, then translates/polishes the text into .lrc subtitles with LLMs such as OpenAI and Anthropic.

    Key Features
    • Audio preprocessing to reduce hallucinations (loudness normalization and optional noise suppression).
    • Context-aware translation to improve translation quality. Check prompt for details.
    • Lean translation mode for token-efficient translation with mixed-model support (e.g. cheap MT model + larger CR model).
    • Check here for an overview of the architecture.

    Installation ⚙️

    1. Install CUDA and cuDNN according to https://opennmt.net/CTranslate2/installation.html to enable faster-whisper.

      faster-whisper also needs cuBLAS installed.

      (Windows only) You can download the libraries from Purfview's repository:

      Purfview's whisper-standalone-win provides the required NVIDIA libraries for Windows in a single archive. Decompress the archive and place the libraries in a directory included in the PATH.

    2. Add LLM API keys (recommended for most users: OPENROUTER_API_KEY):

    3. Install ffmpeg and add bin directory to your PATH.

    4. Install from PyPI:

      pip install openlrc
      

      or install directly from GitHub:

      pip install git+https://github.com/zh-plus/openlrc
      
    5. (Optional) If you need noise suppression (noise_suppress=True), install the full extras which includes DPDFNet:

      pip install 'openlrc[full]'
      

      If you want to route translation through LiteLLM, install the LiteLLM extra:

      pip install 'openlrc[litellm]'
      

    Lightweight Imports

    OpenLRC keeps several package-root APIs lightweight to import.

    The following imports are guaranteed not to eagerly load heavyweight runtime dependencies such as dpdfnet, spacy, faster-whisper, tiktoken, or lingua:

    import openlrc
    from openlrc import LRCer
    from openlrc import TranscriptionConfig, TranslationConfig
    from openlrc import ModelConfig, ModelProvider, list_chatbot_models
    

    This is useful when you only need configuration objects, model metadata, or the LRCer type itself without immediately starting transcription or language-processing work.

    Heavy dependencies are loaded only when the corresponding features are first used. For example:

    • faster-whisper is loaded when transcription is first needed.
    • dpdfnet is loaded when noise suppression is used.
    • spacy is loaded when sentence segmentation or related NLP helpers are used.
    • tiktoken is loaded when token counting is used.
    • lingua is loaded when language detection helpers are used.

    [!NOTE] The base pip install openlrc does not include dpdfnet. It is only installed with pip install 'openlrc[full]' and is only needed for noise suppression (noise_suppress=True). On first use, DPDFNet downloads its model (default dpdfnet2_48khz_hr, ~10MB) to ~/.cache/dpdfnet/models.

    Usage 🐍

    Python code

    from openlrc import LRCer, ModelConfig, ModelProvider, TranscriptionConfig, TranslationConfig
    
    if __name__ == '__main__':
        lrcer = LRCer()
    
        # Single file
        lrcer.run('./data/test.mp3',
                  target_lang='zh-cn')  # Generate translated ./data/test.lrc with default translate prompt.
    
        # Multiple files
        lrcer.run(['./data/test1.mp3', './data/test2.mp3'], target_lang='zh-cn')
        # Note we run the transcription sequentially, but run the translation concurrently for each file.
    
        # Path can contain video
        lrcer.run(['./data/test_audio.mp3', './data/test_video.mp4'], target_lang='zh-cn')
        # Generate translated ./data/test_audio.lrc and ./data/test_video.srt
    
        # Use glossary to improve translation
        lrcer = LRCer(translation=TranslationConfig(glossary='./data/aoe4-glossary.yaml'))
    
        # To skip translation process
        lrcer.run('./data/test.mp3', target_lang='en', skip_trans=True)
    
        # Change asr_options or vad_options (see openlrc.defaults for details)
        vad_options = {"threshold": 0.1}
        lrcer = LRCer(transcription=TranscriptionConfig(vad_options=vad_options))
        lrcer.run('./data/test.mp3', target_lang='zh-cn')
    
        # Enhance the audio using noise suppression (requires openlrc[full], consumes more time).
        lrcer.run('./data/test.mp3', target_lang='zh-cn', noise_suppress=True)
    
        # Change the translation model
        lrcer = LRCer(translation=TranslationConfig(
            chatbot=ModelConfig(provider=ModelProvider.ANTHROPIC, name='claude-3-sonnet-20240229')
        ))
        lrcer.run('./data/test.mp3', target_lang='zh-cn')
    
        # Clear temp folder after processing done
        lrcer.run('./data/test.mp3', target_lang='zh-cn', clear_temp=True)
    
        # Use a custom OpenAI-compatible endpoint
        lrcer = LRCer(
            translation=TranslationConfig(
                chatbot=ModelConfig(
                    provider=ModelProvider.OPENAI,
                    name='gpt-4.1-nano',
                    base_url='https://example.com/v1',
                    api_key='token',
                )
            )
        )
    
        # Route through LiteLLM (requires openlrc[litellm])
        lrcer = LRCer(translation=TranslationConfig(
            chatbot=ModelConfig(provider=ModelProvider.LITELLM, name='openai/gpt-4o')
        ))
    
        # Bilingual subtitle
        lrcer.run('./data/test.mp3', target_lang='zh-cn', bilingual_sub=True)
    
        # Lean translation mode (token-efficient, simplified prompts)
        lrcer = LRCer(translation=TranslationConfig(translate_mode='lean'))
        lrcer.run('./data/test.mp3', target_lang='zh-cn')
    
        # Lean mode with mixed-model architecture (separate CR and translation models)
        from openlrc.agents import create_chatbot
        from openlrc.translate import LeanTranslator
    
        mt_bot = create_chatbot(ModelConfig(
            provider=ModelProvider.OPENAI, name='your-mt-model',
            base_url='http://localhost:8000/v1', api_key='token',
        ))
        cr_bot = create_chatbot(ModelConfig(
            provider=ModelProvider.OPENAI, name='your-cr-model',
            base_url='http://localhost:8001/v1', api_key='token',
        ))
        translator = LeanTranslator(chatbot=mt_bot, cr_chatbot=cr_bot, enable_cr=True)
        translations = translator.translate(['Hello', 'World'], 'en', 'zh')
    

    LRCer supports the context manager protocol, which automatically closes the underlying LLM connections when the block exits:

    with LRCer() as lrcer:
        lrcer.run(['./data/file1.mp3', './data/file2.mp3'], target_lang='zh-cn')
    # Connections are closed automatically here.
    

    This is recommended when processing multiple files, as the LLM connection pool is shared across all files within the same LRCer instance.

    Check more details in Documentation.

    Glossary

    Add glossary to improve domain specific translation. For example aoe4-glossary.json:

    {
      "aoe4": "帝国时代4",
      "feudal": "封建时代",
      "2TC": "双TC",
      "English": "英格兰文明",
      "scout": "侦察兵"
    }
    
    lrcer = LRCer(translation=TranslationConfig(glossary='./data/aoe4-glossary.json'))
    lrcer.run('./data/test.mp3', target_lang='zh-cn')
    

    To keep TranslationConfig serialization-friendly, save in-memory glossary data to a JSON file and pass the file path via TranslationConfig(glossary=...).

    Pricing 💰

    pricing data from OpenAI and Anthropic

    Model NamePricing for 1M Tokens (Input/Output) (USD)Cost for 1 Hour Audio (USD)
    gpt-3.5-turbo0.5, 1.50.01
    gpt-4o-mini0.5, 1.50.01
    gpt-4-0125-preview10, 300.5
    gpt-4-turbo-preview10, 300.5
    gpt-4o5, 150.25
    claude-3-haiku-202403070.25, 1.250.015
    claude-3-sonnet-202402293, 150.2
    claude-3-opus-2024022915, 751
    claude-3-5-sonnet-202406203, 150.2
    gemini-1.5-flash0.175, 2.10.01
    gemini-1.0-pro0.5, 1.50.01
    gemini-1.5-pro1.75, 210.1
    deepseek-chat0.18, 2.20.01

    Note the cost is estimated based on the token count of the input and output text. The actual cost may vary due to the language and audio speed.

    Recommended translation model

    For English audio, we recommend deepseek-chat, gpt-4o-mini, or gemini-1.5-flash.

    For non-English audio, we recommend claude-3-5-sonnet-20240620.

    How it works

    To maintain context between translation segments, the process is sequential for each audio file.

    Development Guide

    This project uses uv for package management. Install uv with the standalone installer:

    On macOS and Linux
    curl -LsSf https://astral.sh/uv/install.sh | sh
    
    On Windows
    powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"
    

    Install dependencies

    uv venv
    uv sync
    

    Code quality checks

    Before committing, please make sure the following checks pass locally:

    # Lint
    uv run ruff check openlrc/ tests/
    
    # Format
    uv run ruff format --check openlrc/ tests/
    # To auto-fix formatting:
    # uv run ruff format openlrc/ tests/
    
    # Type check
    uv run pyright openlrc/
    
    # Tests
    uv run --extra full --extra litellm pytest
    

    For live translation testing as a developer (and for CI usage), set:

    export DEEPSEEK_API_KEY="your-api-key"
    export OPENLRC_TEST_LIVE_API=1
    

    Live tests use the OpenAI-compatible deepseek-v4-flash model by default. See tests/conftest.py for configurable environment variables (e.g. OPENLRC_TEST_LLM_BASE_URL to point at another compatible test endpoint).

    Build and publish a release

    Use uv end-to-end for release builds and publishing:

    # Build source and wheel distributions
    uv build
    
    # Validate the generated metadata before uploading
    uvx twine check dist/*
    
    # Publish to PyPI
    # Preferred for local publishing:
    uv publish
    #
    # Or publish with an explicit token:
    # uv publish --token <pypi-token>
    

    If you prefer GitHub Actions publishing, configure PyPI trusted publishing for this repository and push a version tag such as v1.7.0a2.

    Todo

    • [Efficiency] Batched translate/polish for GPT request (enable contextual ability).
    • [Efficiency] Concurrent support for GPT request.
    • [Translation Quality] Make translate prompt more robust according to https://github.com/openai/openai-cookbook.
    • [Feature] Automatically fix json encoder error using GPT.
    • [Efficiency] Asynchronously perform transcription and translation for multiple audio inputs.
    • [Quality] Improve batched translation/polish prompt according to gpt-subtrans.
    • [Feature] Input video support.
    • [Feature] Multiple output format support.
    • [Quality] Speech enhancement for input audio.
    • [Feature] Preprocessor: Voice-music separation.
    • [Feature] Align ground-truth transcription with audio.
    • [Quality] Use multilingual language model to assess translation quality.
    • [Efficiency] Add Azure OpenAI Service support.
    • [Quality] Use claude for translation.
    • [Feature] Add local LLM support.
    • [Feature] Multiple translate engine (Anthropic, Microsoft, DeepL, Google, etc.) support.
    • [Feature] Build a electron + fastapi GUI for cross-platform application.
    • [Feature] Web-based streamlit GUI.
    • Add fine-tuned whisper-large-v2 models for common languages.
    • [Feature] Add custom OpenAI & Anthropic endpoint support.
    • [Feature] Add local translation model support (e.g. SakuraLLM).
    • [Quality] Construct translation quality benchmark test for each patch.
    • [Quality] Split subtitles using LLM (ref).
    • [Quality] Trim extra long subtitle using LLM (ref).
    • [Others] Add transcribed examples.
      • Song
      • Podcast
      • Audiobook

    Credits

    Star History

    Star History Chart

    Citation

    @book{openlrc2024zh,
    	title = {zh-plus/openlrc},
    	url = {https://github.com/zh-plus/openlrc},
    	author = {Hao, Zheng},
    	date = {2024-09-10},
    	year = {2024},
    	month = {9},
    	day = {10},
    }