使用需要编码的 moviepy 向视频添加字幕

Adding subtitles to video with moviepy requiring encoding

我有一个名为 subtitles.srt 的非英文 srt 文件,我遵循了 moviepy 包 (https://moviepy.readthedocs.io/en/latest/_modules/moviepy/video/tools/subtitles.html) 的文档和源代码的说明:

from moviepy.video.tools.subtitles import SubtitlesClip
from moviepy.video.io.VideoFileClip import VideoFileClip
generator = lambda txt: TextClip(txt, font='Georgia-Regular', fontsize=24, color='white')
sub = SubtitlesClip("subtitles.srt", generator, encoding='utf-8')

这给出了错误 TypeError: __init__() got an unexpected keyword argument 'encoding'

在源代码中,class SubtitlesClip 确实有一个关键字参数 encoding。这是否意味着源代码的版本已过时或其他什么?我能做些什么呢?我什至尝试将带有 encoding 关键字参数的 moviepy.video.tools.subtitles 的源代码直接复制到我的代码中,但它导致了更多错误,例如行:

from moviepy.decorators import convert_path_to_string

导入装饰器失败convert_path_to_string

源码好像和我安装的不一致。无论如何要修复它?如果没有,是否有任何好的 Python 库替代品用于一般插入字幕或视频编辑?

编辑:我目前的解决方案是创建 SubtitlesClip 的子 class 并覆盖父 class 的构造函数:

from moviepy.video.tools.subtitles import SubtitlesClip
from moviepy.video.VideoClip import TextClip, VideoClip
from moviepy.video.compositing.CompositeVideoClip import CompositeVideoClip
import re



from moviepy.tools import cvsecs

def file_to_subtitles_with_encoding(filename):
    """ Converts a srt file into subtitles.

    The returned list is of the form ``[((ta,tb),'some text'),...]``
    and can be fed to SubtitlesClip.

    Only works for '.srt' format for the moment.
    """
    times_texts = []
    current_times = None
    current_text = ""
    with open(filename,'r',encoding='utf-8') as f:
        for line in f:
            times = re.findall("([0-9]*:[0-9]*:[0-9]*,[0-9]*)", line)
            if times:
                current_times = [cvsecs(t) for t in times]
            elif line.strip() == '':
                times_texts.append((current_times, current_text.strip('\n')))
                current_times, current_text = None, ""
            elif current_times:
                current_text += line
    return times_texts


class SubtitlesClipUTF8(SubtitlesClip):
    def __init__(self, subtitles, make_textclip=None):
        
        VideoClip.__init__(self, has_constant_size=False)

        if isinstance(subtitles, str):
            subtitles = file_to_subtitles_with_encoding(subtitles)

        #subtitles = [(map(cvsecs, tt),txt) for tt, txt in subtitles]
        self.subtitles = subtitles
        self.textclips = dict()

        if make_textclip is None:
            make_textclip = lambda txt: TextClip(txt, font='Georgia-Bold',
                                        fontsize=24, color='white',
                                        stroke_color='black', stroke_width=0.5)

        self.make_textclip = make_textclip
        self.start=0
        self.duration = max([tb for ((ta,tb), txt) in self.subtitles])
        self.end=self.duration
        
        def add_textclip_if_none(t):
            """ Will generate a textclip if it hasn't been generated asked
            to generate it yet. If there is no subtitle to show at t, return
            false. """
            sub =[((ta,tb),txt) for ((ta,tb),txt) in self.textclips.keys()
                   if (ta<=t<tb)]
            if not sub:
                sub = [((ta,tb),txt) for ((ta,tb),txt) in self.subtitles if
                       (ta<=t<tb)]
                if not sub:
                    return False
            sub = sub[0]
            if sub not in self.textclips.keys():
                self.textclips[sub] = self.make_textclip(sub[1])

            return sub

        def make_frame(t):
            sub = add_textclip_if_none(t)
            return (self.textclips[sub].get_frame(t) if sub
                    else np.array([[[0,0,0]]]))

        def make_mask_frame(t):
            sub = add_textclip_if_none(t)
            return (self.textclips[sub].mask.get_frame(t) if sub
                    else np.array([[0]]))
        
        self.make_frame = make_frame
        hasmask = bool(self.make_textclip('T').mask)
        self.mask = VideoClip(make_mask_frame, ismask=True) if hasmask else None

我实际上只改了两行,但我必须创建一个新的class并重新定义整个东西,所以我怀疑是否真的有必要。还有比这更好的解决方案吗?

文档中的 latest 版本(您正在查看的版本)对应开发版本 2.x,尚未发布到 PyPI。您通过 pip 安装的版本很可能是 1.0.3,这是 PyPI 上的最新版本,并且它不允许 encoding 参数。

从引入该功能的 PR 中,您可以看到它只被标记为在 2.x 版本中发布。

仅将该文件复制到您的源代码中很可能不起作用,因为这将取决于两个版本之间发生的更改。然而,如果你喜欢冒险,你可以安装包的 dev 版本,按照 moviepy 的 docs.