Epub fixes.
[librarian.git] / src / librarian / fonts.py
1 import os
2 from shutil import rmtree
3 import subprocess
4 from tempfile import mkdtemp
5
6
7 def strip_font(path, chars, verbose=False):
8     tmpdir = mkdtemp('-librarian-epub')
9     try:
10         cwd = os.getcwd()
11     except OSError:
12         cwd = None
13
14     os.chdir(os.path.join(os.path.dirname(os.path.realpath(__file__)),
15                           'font-optimizer'))
16     optimizer_call = [
17         'perl', 'subset.pl', '--chars',
18         ''.join(chars).encode('utf-8'),
19         path,
20         os.path.join(tmpdir, 'font.ttf')
21     ]
22     env = {"PERL_USE_UNSAFE_INC": "1"}
23     if verbose:
24         print("Running font-optimizer")
25         subprocess.check_call(optimizer_call, env=env)
26     else:
27         dev_null = open(os.devnull, 'w')
28         subprocess.check_call(optimizer_call, stdout=dev_null,
29                               stderr=dev_null, env=env)
30     with open(os.path.join(tmpdir, 'font.ttf'), 'rb') as f:
31         content = f.read()
32
33     rmtree(tmpdir)
34
35     if cwd is not None:
36         os.chdir(cwd)
37
38     return content