2 # -*- coding: utf-8 -*-
4 # This file is part of Librarian, licensed under GNU Affero GPLv3 or later.
5 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
7 from collections import namedtuple
11 from librarian import DirDocProvider, ParseError
12 from librarian.parser import WLDocument
13 from librarian.cover import DefaultEbookCover
17 """Option for optparse. Use it like `optparse.OptionParser.add_option`."""
18 def __init__(self, *names, **options):
20 self.options = options
22 def add(self, parser):
23 parser.add_option(*self.names, **self.options)
26 return self.options['dest']
28 def value(self, options):
29 return getattr(options, self.name())
32 class Book2Anything(object):
33 """A class for creating book2... scripts.
35 Subclass it for any format you want to convert to.
37 format_name = None # Set format name, like "PDF".
38 ext = None # Set file extension, like "pdf".
39 uses_cover = False # Can it add a cover?
40 cover_optional = True # Only relevant if uses_cover
41 uses_provider = False # Does it need a DocProvider?
42 transform = None # Transform method. Uses WLDocument.as_{ext} by default.
43 parser_options = [] # List of Option objects for additional parser args.
44 transform_options = [] # List of Option objects for additional transform args.
45 transform_flags = [] # List of Option objects for supported transform flags.
50 # Parse commandline arguments
51 usage = """Usage: %%prog [options] SOURCE [SOURCE...]
52 Convert SOURCE files to %s format.""" % cls.format_name
54 parser = optparse.OptionParser(usage=usage)
56 parser.add_option('-v', '--verbose',
57 action='store_true', dest='verbose', default=False,
58 help='print status messages to stdout')
59 parser.add_option('-d', '--make-dir',
60 action='store_true', dest='make_dir', default=False,
61 help='create a directory for author and put the output file in it')
62 parser.add_option('-o', '--output-file',
63 dest='output_file', metavar='FILE',
64 help='specifies the output file')
65 parser.add_option('-O', '--output-dir',
66 dest='output_dir', metavar='DIR',
67 help='specifies the directory for output')
69 if cls.cover_optional:
70 parser.add_option('-c', '--with-cover',
71 action='store_true', dest='with_cover', default=False,
72 help='create default cover')
73 parser.add_option('-C', '--image-cache',
74 dest='image_cache', metavar='URL',
75 help='prefix for image download cache' +
76 (' (implies --with-cover)' if cls.cover_optional else ''))
77 for option in cls.parser_options + cls.transform_options + cls.transform_flags:
80 options, input_filenames = parser.parse_args()
82 if len(input_filenames) < 1:
86 # Prepare additional args for parser.
88 for option in cls.parser_options:
89 parser_args[option.name()] = option.value(options)
90 # Prepare additional args for transform method.
92 for option in cls.transform_options:
93 transform_args[option.name()] = option.value(options)
94 # Add flags to transform_args, if any.
95 transform_flags = [flag.name() for flag in cls.transform_flags
96 if flag.value(options)]
98 transform_args['flags'] = transform_flags
99 # Add cover support, if any.
101 if options.image_cache:
102 def cover_class(*args, **kwargs):
103 return DefaultEbookCover(image_cache=options.image_cache, *args, **kwargs)
104 transform_args['cover'] = cover_class
105 elif not cls.cover_optional or options.with_cover:
106 transform_args['cover'] = DefaultEbookCover
111 for main_input in input_filenames:
115 # Where to find input?
116 if cls.uses_provider:
117 path, fname = os.path.realpath(main_input).rsplit('/', 1)
118 provider = DirDocProvider(path)
122 # Where to write output?
123 if not (options.output_file or options.output_dir):
124 output_file = os.path.splitext(main_input)[0] + '.' + cls.ext
128 # Do the transformation.
129 doc = WLDocument.from_file(main_input, provider=provider, **parser_args)
130 transform = cls.transform
131 if transform is None:
132 transform = getattr(WLDocument, 'as_%s' % cls.ext)
133 output = transform(doc, **transform_args)
135 doc.save_output_file(output,
136 output_file, options.output_dir, options.make_dir, cls.ext)
138 except ParseError, e:
139 print '%(file)s:%(name)s:%(message)s' % {
141 'name': e.__class__.__name__,