【问题标题】:Adding subtitles to video with moviepy requiring encoding使用需要编码的moviepy向视频添加字幕
【发布时间】:2021-06-10 13:32:46
【问题描述】:

我有一个名为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'

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

from moviepy.decorators import convert_path_to_string

导入装饰器convert_path_to_string失败。

源代码似乎与我安装的不一致。无论如何要修复它?如果没有,是否有任何 Python 库的替代方案可以用于插入字幕或进行一般视频编辑?

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

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

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

【问题讨论】:

    标签: python moviepy video-editing srt video-subtitles


    【解决方案1】:

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

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

    仅将该文件复制到您的源代码很可能无法正常工作,因为这将取决于两个版本之间发生的更改。但是,如果您喜欢冒险,可以按照moviepy docs 中的手动方法 部分安装包的dev 版本。

    【讨论】:

      猜你喜欢
      • 2023-01-26
      • 2016-08-08
      • 2021-07-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-13
      • 2017-05-03
      • 1970-01-01
      相关资源
      最近更新 更多