1 Star 2 Fork 0

JXX / 智能外文字幕翻译合成视频工具

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
贡献代码
同步代码
取消
提示: 由于 Git 不支持空文件夾,创建文件夹后会生成空的 .keep 文件
Loading...
README
Apache-2.0

基于PaddleOCR的字幕翻译工具

jpg jpg jpg jpg jpg

PaddleOCR 简介

PaddleOCR旨在打造一套丰富、领先、且实用的OCR工具库,助力开发者训练出更好的模型,并应用落地。

分享一些Paddle官方有趣的内容:

官方示例:

jpg jpg

更多内容可以参考官方文档

程序简介

这个程序主要使用了PaddleOCR的图片文本检测和识别功能。该程序借鉴了paddle星河社区大佬的项目
通过调用Opencv对视频的切帧能力read()将输入的视频进行间隔切帧并逐一返回给控制台,PaddleOCR从控制台收到帧图片后将其保存 imwrite()jpg图片并读取图片信息检测识别图片内的字幕,将字幕写入文档供百度翻译API进行翻译。
在调用百度翻译API后将翻译结果写入文档,利用moviepy库进行视频合成,将翻译的字幕按特定帧写入到画面底部并结合源视频画面、声 音合成新视频,达到目标。

快速开始

1. 运行环境搭建

1.1 环境要求

  • CPU的安装 paddlepaddle >= 2.1.2
  • GPU的安装 paddlepaddle-gpu >= 2.5.1
  • 3.8 <= Python <= 3.12
  • CUDA >= 11.2
  • cuDNN >= 8.2.1
  • TensorRT >= 8.2.4.2 (需要就装)

1.2 环境安装

1.2.1 安装paddlepaddle

MacOS 暂只支持使用paddlepaddle。

  • 使用以下命令确认你的Python是 3.8/3.9/3.10/3.11/3.12。
    python --version
  • 需要确认pip的版本是否满足要求,要求pip版本为 20.2.2 或更高版本。
    python -m pip --version
  • 需要确认Pythonpip是 64bit,并且处理器架构是 x86_64(或称作 x64、Intel 64、AMD64)架构。下面的第一行输出的是”64bit”,第二行输出的是”x86_64”、”x64”或”AMD64”即可:
    python -c "import platform;print(platform.architecture()[0]);print(platform.machine())"
  • 默认提供的安装包需要计算机支持MKL,Windows 暂不支持NCCL,分布式等相关功能。
  • 下面使用pip进行安装。
    python -m pip install paddlepaddle==2.6.0 -i https://mirror.baidu.com/pypi/simple
  • 验证安装
    • 安装完成后可以进入Python使用以下语句检查是否安装成功。
      import paddle
      paddle.utils.run_check()
    • 运行出现PaddlePaddle is installed successfully!则代表安装成功。
  • 卸载方法
    • 使用以下语句卸载paddlepaddle。
      python -m pip uninstall paddlepaddle

1.2.2 安装paddlepaddle-gpu

MacOS 暂只支持使用paddlepaddle。

  • 使用以下命令确认你的Python是 3.8/3.9/3.10/3.11/3.12。

    python --version
  • 需要确认pip的版本是否满足要求,要求pip版本为 20.2.2 或更高版本。

    python -m pip --version
  • 需要确认Pythonpip是 64bit,并且处理器架构是 x86_64(或称作 x64、Intel 64、AMD64)架构。下面的第一行输出的是”64bit”,第二行输出的是”x86_64”、”x64”或”AMD64”即可:

    python -c "import platform;print(platform.architecture()[0]);print(platform.machine())"
  • 默认提供的安装包需要计算机支持MKL,Windows 暂不支持NCCL,分布式等相关功能。

  • 针对有GPU的设备,需要确保硬件版本一一对应,这里建议使用CUDA 11.6因为比较稳定,对应的是cuDNN 8.4.0,如需要加速推理需要安装TensorRT 8.4.0.6,这里也给出paddle官方的版本对应表格,适用于GPU 运算能力超过 3.5 的硬件设备。

    CUDA版本 cuDNN版本 TensorRT版本
    11.2 8.2.1 8.2.4.2
    11.6 8.4.0 8.4.0.6
    11.7 8.4.1 8.4.2.4
    11.8 8.6.0 8.5.1.7
    12.0 8.9.1 8.6.1.6

    注:目前官方发布的 windows 安装包仅包含 CUDA 11.2/11.6/11.7/11.8/12.0,如需使用其他 cuda 版本,请通过源码自行编译。您可参考 NVIDIA 官方文档了解 CUDA、CUDNN 和 TensorRT 的安装流程和配置方法,请见CUDAcuDNNTensorRT

  • 针对不同版本的CUDA使用pip进行安装:

    # CUDA 11.2
    python -m pip install paddlepaddle-gpu==2.6.0.post112 -f https://www.paddlepaddle.org.cn/whl/windows/mkl/avx/stable.html
    # CUDA 11.6
    python -m pip install paddlepaddle-gpu==2.6.0.post116 -f https://www.paddlepaddle.org.cn/whl/windows/mkl/avx/stable.html
    # CUDA 11.7
    python -m pip install paddlepaddle-gpu==2.6.0.post117 -f https://www.paddlepaddle.org.cn/whl/windows/mkl/avx/stable.html
    # CUDA 11.8
    python -m pip install paddlepaddle-gpu==2.6.0 -i https://mirror.baidu.com/pypi/simple
    # CUDA 12.0
    python -m pip install paddlepaddle-gpu==2.6.0.post120 -f https://www.paddlepaddle.org.cn/whl/windows/mkl/avx/stable.html
  • 验证安装

    • 安装完成后可以进入Python使用以下语句检查是否安装成功。
      import paddle
      paddle.utils.run_check()
    • 运行出现PaddlePaddle is installed successfully!则代表安装成功。
  • 卸载方法

    • 使用以下语句卸载paddlepaddle-gpu。
      python -m pip uninstall paddlepaddle-gpu

2. 三方库安装

  • 使用Python运行以下代码安装三方库
    python -m pip install -r requirements.txt

3. 翻译功能实现

  • 这里为了方便就不使用飞桨的paddlenlp了,同时为了简便容易配置直接调用百度翻译开放平台的API,每人每月最高可以拥有100万字符的免费额度,一般够用了。

  • 登录百度翻译开放平台,确保已经实名认证,免费开通通用文本翻译服务。

  • 开通之后进入管理控制台,在页面底端可以看到自己的申请信息,例如:

    | 申请信息
    APP ID: 2024XXXXXXXX
    密钥: XXXXXXXXXXXX

  • 下面直接附上百度官方提供的API调用Python代码,如果用作测试使用请替换代码中的appidappkey为自己的信息。

    # -*- coding: utf-8 -*-
    # This code shows an example of text translation from English to Simplified-Chinese.
    # This code runs on Python 2.7.x and Python 3.x.
    # You may install `requests` to run this code: pip install requests
    # Please refer to `https://api.fanyi.baidu.com/doc/21` for complete api document
    
    import requests
    import random
    import json
    from hashlib import md5
    
    # Set your own appid/appkey.
    appid = 'INPUT_YOUR_APPID'
    appkey = 'INPUT_YOUR_APPKEY'
    
    # For list of language codes, please refer to `https://api.fanyi.baidu.com/doc/21`
    from_lang = 'en'
    to_lang =  'zh'
    
    endpoint = 'http://api.fanyi.baidu.com'
    path = '/api/trans/vip/translate'
    url = endpoint + path
    
    query = 'Hello World! This is 1st paragraph.\nThis is 2nd paragraph.'
    
    # Generate salt and sign
    def make_md5(s, encoding='utf-8'):
        return md5(s.encode(encoding)).hexdigest()
    
    salt = random.randint(32768, 65536)
    sign = make_md5(appid + query + str(salt) + appkey)
    
    # Build request
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    payload = {'appid': appid, 'q': query, 'from': from_lang, 'to': to_lang, 'salt': salt, 'sign': sign}
    
    # Send request
    r = requests.post(url, params=payload, headers=headers)
    result = r.json()
    
    # Show response
    print(json.dumps(result, indent=4, ensure_ascii=False))
  • 运行结果如下:

    {
      "from": "en",
      "to": "zh",
      "trans_result": [
          {
              "src": "Hello World! This is 1st paragraph.",
              "dst": "你好,世界!这是第一段。"
          },
          {
              "src": "This is 2nd paragraph.",
              "dst": "这是第2段。"
          }
      ]
    }
  • 如果你的运行结果也是这样就可以了。

4. 程序运行

4.1 框架

  • 程序框架图如下:

    `---subtitle_translation
        |
        `---font
        |   |---HarmonyOS_Sans_SC_Regular.ttf  // 界面字体
        |
        `---infer
        |   |---infer.jpg                      // 推理图片
        |   |---result.txt                     // 推理文本
        |
        `---translate
        |   |---trans.txt                      // 翻译文本
        |
        `---readme_img
        |   |---00006737.jpg
        |   |---test_add_91.jpg
        |
        |---input.mp4                          // 输入视频
        |---output_video.mp4                   // 输出视频
        |---main.py                            // 主程序
        |---LICENSE
        |---README.md
  • 代码框架图如下:

    `---SubtitleTranslation
        |
        `---read_movie          // 读取视频
        |
        `---movie_to_text       // 检测识别文本
        |
        `---translate_text      // 翻译文本
        |
        `---add_text_subtitles  // 添加字幕

4.2 运行

  1. 执行下面的代码运行程序:
    python main.py
  2. 输入自己百度翻译开放平台的appid,appkey以及自己准备好的视频的地址,点击确定等待运行结束即可。

5. 运行可能遇到的问题

  1. 当运行PaddleOCR时可能会提示cannot load cuDNN_cnn_infer64_8.dll. Error code 193,这可能是由于你安装的CUDA、cuDNN的版本过高导致的, 请确认你的CUDA和cuDNN安装的版本是否对应,如果还是报错可以降低cuDNN的版本进行重新安装,因为cuDNN可能运行不稳定。
  2. 当运行moviepy时可能会遇到报错:
    OSError: MoviePy Error: creation of None failed because of the following error:
    [WinError 2] 系统找不到指定的文件. . .
    This error can be due to the fact that ImageMagick is not installed on your computer, or (for Windows users) that you didn't specify the path to the ImageMagick binary in file conf.py, or that the path you specified is incorrect
    这是由于moviepy库缺少ImageMagick模块导致的,可以到ImageMagick官网下载ImageMagick, 在安装时注意要勾选Install development headers and libraries for C and C++选项,安装后设置MAGICK_HOME环境变量,值为ImageMagick的安装路径,并将安装路径加入系统变量path。 安装成功之后,修改moviepy模块下的config_defaults.py文件,修改后的内容如下:
    FFMPEG_BINARY = os.getenv('FFMPEG_BINARY', 'ffmpeg-imageio')
    # IMAGEMAGICK_BINARY = os.getenv('IMAGEMAGICK_BINARY', 'auto-detect')
    # 修改为刚刚ImageMagic的安装路径
    IMAGEMAGICK_BINARY = r"D:\你安装ImageMagick的文件夹\magick.exe"
    如有不清楚的地方可以看原文,这个方法参考了CSDN上一个博主的文章。

建议与意见

如果还有其他的问题或者对程序有好建议可以issue给我,我会积极认真做认真改,争取完善这个程序。

许可证信息

该程序(项目)受Apache-2.0 License许可范围内许可认证。

其他信息

  1. 同步该程序(项目)的github地址:跳转到github
Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

简介

利用PaddleOCR和OpenCV实现对视频中的外文字幕进行翻译和合成新的视频。 展开 收起
Apache-2.0
取消

贡献者

全部

近期动态

加载更多
不能加载更多了
1
https://gitee.com/JXX_CODE/subtitle_traslation.git
git@gitee.com:JXX_CODE/subtitle_traslation.git
JXX_CODE
subtitle_traslation
智能外文字幕翻译合成视频工具
master

搜索帮助