Fix for picture in Python 3.
[librarian.git] / librarian / packagers.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 from __future__ import print_function, unicode_literals
7
8 import os
9 from librarian import pdf, epub, mobi, DirDocProvider, ParseError
10 from librarian.parser import WLDocument
11
12 from .util import makedirs
13
14
15 class Packager(object):
16     cover = None
17     flags = None
18
19     @classmethod
20     def transform(cls, *args, **kwargs):
21         return cls.converter.transform(*args, **kwargs)
22
23     @classmethod
24     def prepare_file(cls, main_input, output_dir, verbose=False, overwrite=False):
25         path, fname = os.path.realpath(main_input).rsplit('/', 1)
26         provider = DirDocProvider(path)
27         slug, ext = os.path.splitext(fname)
28
29         if output_dir != '':
30             makedirs(output_dir)
31         outfile = os.path.join(output_dir, slug + '.' + cls.ext)
32         if os.path.exists(outfile) and not overwrite:
33             return
34
35         doc = WLDocument.from_file(main_input, provider=provider)
36         output_file = cls.transform(doc, cover=cls.cover, flags=cls.flags)
37         doc.save_output_file(output_file, output_path=outfile)
38
39     @classmethod
40     def prepare(cls, input_filenames, output_dir='', verbose=False, overwrite=False):
41         try:
42             for main_input in input_filenames:
43                 if verbose:
44                     print(main_input)
45                 cls.prepare_file(main_input, output_dir, verbose, overwrite)
46         except ParseError as e:
47             print('%(file)s:%(name)s:%(message)s' % {
48                 'file': main_input,
49                 'name': e.__class__.__name__,
50                 'message': e.message
51             })
52
53
54 class EpubPackager(Packager):
55     converter = epub
56     ext = 'epub'
57
58
59 class MobiPackager(Packager):
60     converter = mobi
61     ext = 'mobi'
62
63
64 class PdfPackager(Packager):
65     converter = pdf
66     ext = 'pdf'
67
68     @classmethod
69     def transform(cls, *args, **kwargs):
70         return cls.converter.transform(*args, morefloats='new', **kwargs)