temporarily disable line numbers (No room for new \count)
[librarian.git] / librarian / mobi.py
1 # -*- coding: utf-8 -*-
2 #
3 # This file is part of Librarian, licensed under GNU Affero GPLv3 or later.
4 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
5 #
6
7 from copy import deepcopy
8 import os
9 import subprocess
10 from tempfile import NamedTemporaryFile
11
12 from librarian import OutputFile
13
14
15 def transform(wldoc, verbose=False, sample=None, cover=None,
16               use_kindlegen=False, flags=None, hyphenate=True, ilustr_path=''):
17     """ produces a MOBI file
18
19     wldoc: a WLDocument
20     sample=n: generate sample e-book (with at least n paragraphs)
21     cover: a cover.Cover factory overriding default
22     flags: less-advertising,
23     """
24
25     document = deepcopy(wldoc)
26     del wldoc
27
28     epub = document.as_epub(verbose=verbose, sample=sample,
29                             html_toc=True, cover=cover or True, flags=flags,
30                             hyphenate=hyphenate, ilustr_path=ilustr_path)
31     if verbose:
32         kwargs = {}
33     else:
34         devnull = open("/dev/null", 'w')
35         kwargs = {"stdout": devnull, "stderr": devnull}
36
37     output_file = NamedTemporaryFile(prefix='librarian', suffix='.mobi',
38                                      delete=False)
39     output_file.close()
40
41     if use_kindlegen:
42         output_file_basename = os.path.basename(output_file.name)
43         subprocess.check_call(['kindlegen', '-c2', epub.get_filename(),
44                               '-o', output_file_basename], **kwargs)
45     else:
46         subprocess.check_call(['ebook-convert', epub.get_filename(),
47                                output_file.name, '--no-inline-toc',
48                                '--mobi-file-type=both',
49                                '--mobi-ignore-margins'], **kwargs)
50     return OutputFile.from_filename(output_file.name)