【3】Python 视频文字识别提取 - json2txt

【3】Python 视频文字识别提取 - json2txt,第1张

【3】Python 视频文字识别提取 - json2txt

  json2txt.py

## simple_srt.py

from datetime import timedelta
from datetime import datetime


def us_to_string(microseconds):
    return (datetime(1, 1, 1) + timedelta(microseconds=microseconds)).strftime('%H:%M:%S') + ',' + str((microseconds % 10**6) // 10**3).zfill(3)


def tracks_to_srt_list(tracks):
    tracks.sort(key=lambda t: t['start'])

    tracks_in_string = []
    for i, t in enumerate(tracks):
        tracks_in_string.append(
            'n'.join([str(i+1),
                       us_to_string(t['start']) + ' ---> ' +
                       us_to_string(t['end']),
                       t['content']])
        )

    return tracks_in_string


def tracks_to_srt_string(tracks):
    return 'nn'.join(tracks_to_srt_list(tracks))


## draft_content.py


import json


def draft_content_to_tracks(draft_content):
    texts = {t['id']: t['content']
             for t in draft_content['materials']['texts']
             if t['type'] == 'subtitle'}

    """[
        'start': (μs),
        'end': (μs),
        'content': (...)
    }]"""
    tracks = []
    for t in draft_content['tracks']:
        for s in t['segments']:
            if s['material_id'] in texts.keys():
                timerange = s['target_timerange']
                tracks.append({
                    'start': timerange['start'],
                    'end': timerange['start'] + timerange['duration'],
                    'content': texts[s['material_id']]
                })

    return tracks


def read_draft_content_src(directory):
    with open(directory, 'r', encoding='utf-8') as f:
        draft_content = json.loads(f.read())

    print(draft_content)
    return draft_content_to_tracks(draft_content)



# if __name__ == '__main__':
#     print(r'''剪映的草稿文件一般位于 C:Users您的用户名AppDataLocalJianyingProUser DataProjects 。''')
#
#     draft_content_directory = input("请输入 draft_content.json 的地址>>")
#     if not draft_content_directory:
#         draft_content_directory = r'C:UserswangjunAppDataLocalJianyingProUser DataProjectscom.lveditor.draft202108251454draft_content.json'
#
#     tracks = read_draft_content_src(draft_content_directory)
#
#     with open('./subtitles.srt', 'w', encoding='utf-8') as f:
#         f.write(tracks_to_srt_string(tracks))
#
#     input('请查收 subtitles.srt。')

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5652182.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存