videocr/utils.py (view raw)
1from urllib.request import urlopen
2import shutil
3
4from . import constants
5
6
7# download language data files to ~/tessdata if necessary
8def download_lang_data(lang: str):
9 constants.TESSDATA_DIR.mkdir(parents=True, exist_ok=True)
10
11 for lang_name in lang.split('+'):
12 filepath = constants.TESSDATA_DIR / '{}.traineddata'.format(lang_name)
13 if not filepath.is_file():
14 # download needed file
15 if lang_name[0].isupper():
16 url = constants.TESSDATA_SCRIPT_URL.format(lang_name)
17 else:
18 url = constants.TESSDATA_URL.format(lang_name)
19
20 with urlopen(url) as res, open(filepath, 'w+b') as f:
21 shutil.copyfileobj(res, f)