videocr/api.py (view raw)
1from urllib.request import urlopen
2import shutil
3
4from . import constants
5from .video import Video
6
7
8def get_subtitles(
9 video_path: str, lang='eng', time_start='0:00', time_end='',
10 conf_threshold=65, sim_threshold=90, use_fullframe=False) -> str:
11 # download tesseract data file to ~/tessdata if necessary
12 fpath = constants.TESSDATA_DIR / '{}.traineddata'.format(lang)
13 if not fpath.is_file():
14 if lang == 'eng':
15 url = constants.ENG_URL
16 else:
17 url = constants.TESSDATA_URL.format(lang)
18 constants.TESSDATA_DIR.mkdir(parents=True, exist_ok=True)
19 with urlopen(url) as res, open(fpath, 'w+b') as f:
20 shutil.copyfileobj(res, f)
21
22 v = Video(video_path)
23 v.run_ocr(lang, time_start, time_end, conf_threshold, use_fullframe)
24 return v.get_subtitles(sim_threshold)
25
26
27def save_subtitles_to_file(
28 video_path: str, file_path='subtitle.srt', lang='eng',
29 time_start='0:00', time_end='', conf_threshold=65, sim_threshold=90,
30 use_fullframe=False) -> None:
31 with open(file_path, 'w+') as f:
32 f.write(get_subtitles(
33 video_path, lang, time_start, time_end, conf_threshold,
34 sim_threshold, use_fullframe))